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
# -*- coding: utf-8 -*- """API Request cache tests.""" # # (C) Pywikibot team, 2012-2014 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals __version__ = '$Id$' # from pywikibot.site import BaseSite import scripts.maintenance.cache as cache from tests import _cache_dir from tests.aspects import unittest, TestCase class RequestCacheTests(TestCase): """Validate cache entries.""" net = False def _check_cache_entry(self, entry): """Assert validity of the cache entry.""" self.assertIsInstance(entry.site, BaseSite) self.assertIsInstance(entry.site._loginstatus, int) self.assertIsInstance(entry.site._username, list) if entry.site._loginstatus >= 1: self.assertIsNotNone(entry.site._username[0]) self.assertIsInstance(entry._params, dict) self.assertIsNotNone(entry._params) # TODO: more tests on entry._params, and possibly fixes needed # to make it closely replicate the original object. def test_cache(self): """Test the apicache by doing _check_cache_entry over each entry.""" cache.process_entries(_cache_dir, self._check_cache_entry) if __name__ == '__main__': unittest.main()
valhallasw/pywikibot-core
tests/cache_tests.py
Python
mit
1,258
#!/bin/bash cd "$(dirname "${BASH_SOURCE[0]}")" \ && . "../../utils.sh" # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - print_in_purple "\n Dashboard\n\n" execute "defaults write com.apple.dashboard mcx-disabled -bool true" \ "Disable Dashboard" # `killall Dashboard` doesn't actually do anything. To apply the # changes for `Dashboard`, `killall Dock` is enough as `Dock` is # `Dashboard`'s parent process. killall "Dock" &> /dev/null
b-boogaard/dotfiles
src/os/preferences/macos/dashboard.sh
Shell
mit
476
var expect = require('expect.js'); var path = require('path'); var fs = require('../extfs'); describe('extfs', function () { var rootPath = path.join(__dirname, '../'); it('should return all directories', function (done) { fs.getDirs(rootPath, function (err, dirs) { expect(dirs).to.be.an(Array); expect(dirs.length).to.be.greaterThan(0); done(); }); }); it('should return all directories sync', function () { var dirs = fs.getDirsSync(rootPath); expect(dirs).to.be.an(Array); expect(dirs.length > 0).to.be.ok(); }); it('should check if a file is empty', function (done) { var notEmptyFile = path.join(__dirname, '../README.md'); var emptyFile = './AN EMPTY FILE'; fs.isEmpty(notEmptyFile, function (empty) { expect(empty).to.be(false); fs.isEmpty(emptyFile, function (empty) { expect(empty).to.be(true); done(); }); }); }); it('should check if a file is empty sync', function () { var notEmptyFile = path.join(__dirname, '../README.md'); var emptyFile = './AN EMPTY FILE'; var empty = fs.isEmptySync(notEmptyFile); expect(empty).to.be(false); empty = fs.isEmptySync(emptyFile); expect(empty).to.be(true); }); it('should check if a directory is empty', function (done) { var notEmptyDir = __dirname; var emptyDir = './AN EMPTY DIR'; fs.isEmpty(notEmptyDir, function (empty) { expect(empty).to.be(false); fs.isEmpty(emptyDir, function (empty) { expect(empty).to.be(true); done(); }) }); }); it('should check if a directory is empty sync', function () { var notEmptyDir = __dirname; var emptyDir = './AN EMPTY DIR'; expect(fs.isEmptySync(notEmptyDir)).to.be(false); expect(fs.isEmptySync(emptyDir)).to.be(true); }); describe('remove directories', function () { var tmpPath = path.join(rootPath, 'tmp'); var folders = [ 'folder1', 'folder2', 'folder3' ]; var files = [ '1.txt', '2.txt', '3.txt' ]; folders = folders.map(function (folder) { return path.join(tmpPath, folder); }); /** * Create 3 folders with 3 files each */ beforeEach(function () { if (!fs.existsSync(tmpPath)) { fs.mkdirSync(tmpPath, '0755'); } folders.forEach(function (folder) { if (!fs.existsSync(folder)) { fs.mkdirSync(folder, '0755'); } files.forEach(function (file) { fs.writeFile(path.join(folder, file), 'file content'); }); }); }); it('should remove a non empty directory', function (done) { fs.remove(tmpPath, function (err) { expect(err).to.be(null); expect(fs.existsSync(tmpPath)).to.be(false); done(); }); }); it('should remove a non empty directory synchronously', function () { fs.removeSync(tmpPath); expect(fs.existsSync(tmpPath)).to.be(false); }); it('should remove an array of directories', function (done) { fs.remove(folders, function (err) { expect(err).to.be(null); expect(fs.existsSync(folders[0])).to.be(false); expect(fs.existsSync(folders[1])).to.be(false); expect(fs.existsSync(folders[2])).to.be(false); expect(fs.existsSync(tmpPath)).to.be(true); done(); }); }); it('should remove an array of directories synchronously', function () { fs.removeSync(folders); expect(fs.existsSync(folders[0])).to.be(false); expect(fs.existsSync(folders[1])).to.be(false); expect(fs.existsSync(folders[2])).to.be(false); expect(fs.existsSync(tmpPath)).to.be(true); }); }); it('should extends to fs', function () { expect(fs.readdir).to.be.a(Function); }); });
codexar/npm-extfs
tests/extfsTest.js
JavaScript
mit
3,671
require 'set' require 'tsort' module Librarian class ManifestSet class GraphHash < Hash include TSort alias tsort_each_node each_key def tsort_each_child(node, &block) self[node].each(&block) end end class << self def shallow_strip(manifests, names) new(manifests).shallow_strip!(names).send(method_for(manifests)) end def deep_strip(manifests, names) new(manifests).deep_strip!(names).send(method_for(manifests)) end def shallow_keep(manifests, names) new(manifests).shallow_keep!(names).send(method_for(manifests)) end def deep_keep(manifests, names) new(manifests).deep_keep!(names).send(method_for(manifests)) end def sort(manifests) manifests = Hash[manifests.map{|m| [m.name, m]}] if Array === manifests manifest_pairs = GraphHash[manifests.map{|k, m| [k, m.dependencies.map{|d| d.name}]}] manifest_names = manifest_pairs.tsort manifest_names.map{|n| manifests[n]} end private def method_for(manifests) case manifests when Hash :to_hash when Array :to_a end end end def initialize(manifests) self.index = Hash === manifests ? manifests.dup : Hash[manifests.map{|m| [m.name, m]}] end def to_a index.values end def to_hash index.dup end def dup self.class.new(index) end def shallow_strip(names) dup.shallow_strip!(names) end def shallow_strip!(names) assert_strings!(names) names.each do |name| index.delete(name) end self end def deep_strip(names) dup.deep_strip!(names) end def deep_strip!(names) names = Array === names ? names.dup : names.to_a assert_strings!(names) strippables = dependencies_of(names) shallow_strip!(strippables) self end def shallow_keep(names) dup.shallow_keep!(names) end def shallow_keep!(names) assert_strings!(names) names = Set.new(names) unless Set === names index.reject! { |k, v| !names.include?(k) } self end def deep_keep(names) dup.conservative_strip!(names) end def deep_keep!(names) names = Array === names ? names.dup : names.to_a assert_strings!(names) keepables = dependencies_of(names) shallow_keep!(keepables) self end def consistent? index.values.all? do |manifest| in_compliance_with?(manifest.dependencies) end end def in_compliance_with?(dependencies) dependencies.all? do |dependency| manifest = index[dependency.name] manifest && manifest.satisfies?(dependency) end end private attr_accessor :index def assert_strings!(names) non_strings = names.reject{|name| String === name} non_strings.empty? or raise TypeError, "names must all be strings" end # Straightforward breadth-first graph traversal algorithm. def dependencies_of(names) names = Array === names ? names.dup : names.to_a assert_strings!(names) deps = Set.new until names.empty? name = names.shift next if deps.include?(name) deps << name names.concat index[name].dependencies.map(&:name) end deps.to_a end end end
phinze/librarian-puppet
vendor/librarian/lib/librarian/manifest_set.rb
Ruby
mit
3,434
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_CatalogSearch * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ class Mage_CatalogSearch_Model_Session extends Mage_Core_Model_Session_Abstract { public function __construct() { $this->init('catalogsearch'); } }
hansbonini/cloud9-magento
www/app/code/core/Mage/CatalogSearch/Model/Session.php
PHP
mit
1,136
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Rule * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ class Mage_Rule_Block_Rule extends Mage_Core_Block_Abstract { }
hansbonini/cloud9-magento
www/app/code/core/Mage/Rule/Block/Rule.php
PHP
mit
1,025
describe("BASIC CRUD SCENARIOS", function() { require("./basic"); }); describe("VALIDATE CRUD SCENARIOS", function() { require("./validation"); }); describe("REPORT SCENARIOS", function() { require("./report"); });
AndreaZain/dl-module
test/production/finishing-printing/monitoring-event/index.js
JavaScript
mit
228
var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); var testCase = require('../../deps/nodeunit').testCase, debug = require('util').debug, inspect = require('util').inspect, nodeunit = require('../../deps/nodeunit'), gleak = require('../../tools/gleak'), Db = mongodb.Db, Cursor = mongodb.Cursor, Collection = mongodb.Collection, Server = mongodb.Server, ServerManager = require('../../test/tools/server_manager').ServerManager, Step = require("../../deps/step/lib/step"); var MONGODB = 'integration_tests'; var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null)}); var serverManager = null; // Define the tests, we want them to run as a nested test so we only clean up the // db connection once var tests = testCase({ setUp: function(callback) { callback(); }, tearDown: function(callback) { // serverManager.stop(9, function(err, result) { callback(); // }); }, shouldCorrectlyKeepInsertingDocumentsWhenServerDiesAndComesUp : function(test) { var db1 = new Db('mongo-ruby-test-single-server', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); // All inserted docs var docs = []; var errs = []; var insertDocs = []; // Start server serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true}) serverManager.start(true, function() { db1.open(function(err, db) { // Startup the insert of documents var intervalId = setInterval(function() { db.collection('inserts', function(err, collection) { var doc = {timestamp:new Date().getTime()}; insertDocs.push(doc); // Insert document collection.insert(doc, {safe:{fsync:true}}, function(err, result) { // Save errors if(err != null) errs.push(err); if(err == null) { docs.push(result[0]); } }) }); }, 500); // Wait for a second and then kill the server setTimeout(function() { // Kill server instance serverManager.stop(9, function(err, result) { // Server down for 1 second setTimeout(function() { // Restart server serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true}); serverManager.start(true, function() { // Wait for it setTimeout(function() { // Drop db db.dropDatabase(function(err, result) { // Close db db.close(); // Check that we got at least one error // test.ok(errs.length > 0); test.ok(docs.length > 0); test.ok(insertDocs.length > 0); // Finish up test.done(); }); }, 5000) }) }, 1000); }); }, 3000); }) }); }, shouldCorrectlyInsertKillServerFailThenRestartServerAndSucceed : function(test) { var db = new Db('test-single-server-recovery', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {numberOfRetries:3, retryMiliSeconds:500, native_parser: (process.env['TEST_NATIVE'] != null)}); // All inserted docs var docs = []; var errs = []; var insertDocs = []; // Start server serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true}) serverManager.start(true, function() { db.open(function(err, db) { // Add an error handler db.on("error", function(err) { console.log("----------------------------------------------- received error") console.dir(err) errs.push(err); }); db.collection('inserts', function(err, collection) { var doc = {timestamp:new Date().getTime(), a:1}; collection.insert(doc, {safe:true}, function(err, result) { test.equal(null, err); // Kill server instance serverManager.stop(9, function(err, result) { // Attemp insert (should timeout) var doc = {timestamp:new Date().getTime(), b:1}; collection.insert(doc, {safe:true}, function(err, result) { test.ok(err != null); test.equal(null, result); // Restart server serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true}); serverManager.start(true, function() { // Attemp insert again collection.insert(doc, {safe:true}, function(err, result) { // Fetch the documents collection.find({b:1}).toArray(function(err, items) { test.equal(null, err); test.equal(1, items[0].b); test.done(); }); }); }); }); }); }) }); }); }); }, noGlobalsLeaked : function(test) { var leaks = gleak.detectNew(); test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); test.done(); } }) // Assign out tests module.exports = tests;
thebinarypenguin/tasty
server/node_modules/mongodb/test/auxilliary/single_server_kill_reconnect.js
JavaScript
mit
5,743
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager.Models { using System.Linq; /// <summary> /// Deployment operation information. /// </summary> public partial class DeploymentOperation { /// <summary> /// Initializes a new instance of the DeploymentOperation class. /// </summary> public DeploymentOperation() { } /// <summary> /// Initializes a new instance of the DeploymentOperation class. /// </summary> /// <param name="id">Full deployment operation ID.</param> /// <param name="operationId">Deployment operation ID.</param> /// <param name="properties">Deployment properties.</param> public DeploymentOperation(string id = default(string), string operationId = default(string), DeploymentOperationProperties properties = default(DeploymentOperationProperties)) { Id = id; OperationId = operationId; Properties = properties; } /// <summary> /// Gets full deployment operation ID. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "id")] public string Id { get; private set; } /// <summary> /// Gets deployment operation ID. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "operationId")] public string OperationId { get; private set; } /// <summary> /// Gets or sets deployment properties. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "properties")] public DeploymentOperationProperties Properties { get; set; } } }
ScottHolden/azure-sdk-for-net
src/SDKs/Resource/Management.ResourceManager/Generated/Models/DeploymentOperation.cs
C#
mit
1,977
/** * The MIT License * Copyright (c) 2014-2016 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit; public class Bow implements Weapon { @Override public String toString() { return "Bow"; } }
Crossy147/java-design-patterns
factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java
Java
mit
1,281
Dir[File.join(Rails.root, "lib", "core_ext", "*.rb")].each {|l| require l }
edurange/edurange
config/initializers/core_ext.rb
Ruby
mit
75
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Runtime.CompilerServices { using System; using System.Reflection; // This Enum matchs the miImpl flags defined in corhdr.h. It is used to specify // certain method properties. [Flags] [Serializable] public enum MethodImplOptions { Unmanaged = MethodImplAttributes.Unmanaged , ForwardRef = MethodImplAttributes.ForwardRef , PreserveSig = MethodImplAttributes.PreserveSig , InternalCall = MethodImplAttributes.InternalCall, Synchronized = MethodImplAttributes.Synchronized, NoInlining = MethodImplAttributes.NoInlining , } [Serializable] public enum MethodCodeType { IL = System.Reflection.MethodImplAttributes.IL , Native = System.Reflection.MethodImplAttributes.Native , /// <internalonly/> OPTIL = System.Reflection.MethodImplAttributes.OPTIL , Runtime = System.Reflection.MethodImplAttributes.Runtime, } // Custom attribute to specify additional method properties. [Serializable] [AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false )] sealed public class MethodImplAttribute : Attribute { internal MethodImplOptions m_val; public MethodCodeType MethodCodeType; internal MethodImplAttribute( MethodImplAttributes methodImplAttributes ) { MethodImplOptions all = MethodImplOptions.Unmanaged | MethodImplOptions.ForwardRef | MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall | MethodImplOptions.Synchronized | MethodImplOptions.NoInlining; m_val = ((MethodImplOptions)methodImplAttributes) & all; } public MethodImplAttribute( MethodImplOptions methodImplOptions ) { m_val = methodImplOptions; } //// public MethodImplAttribute( short value ) //// { //// m_val = (MethodImplOptions)value; //// } public MethodImplAttribute() { } public MethodImplOptions Value { get { return m_val; } } } }
jelin1/llilum
Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/MethodImplAttribute.cs
C#
mit
2,378
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; using System.Security.AccessControl; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class hosts a node class in the child process. It uses shared memory to communicate /// with the local node provider. /// Wraps a Node. /// </summary> public class LocalNode { #region Static Constructors /// <summary> /// Hook up an unhandled exception handler, in case our error handling paths are leaky /// </summary> static LocalNode() { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); } #endregion #region Static Methods /// <summary> /// Dump any unhandled exceptions to a file so they can be diagnosed /// </summary> private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e) { Exception ex = (Exception)e.ExceptionObject; DumpExceptionToFile(ex); } /// <summary> /// Dump the exception information to a file /// </summary> internal static void DumpExceptionToFile(Exception ex) { // Lock as multiple threads may throw simultaneously lock (dumpFileLocker) { if (dumpFileName == null) { Guid guid = Guid.NewGuid(); string tempPath = Path.GetTempPath(); // For some reason we get Watson buckets because GetTempPath gives us a folder here that doesn't exist. // Either because %TMP% is misdefined, or because they deleted the temp folder during the build. if (!Directory.Exists(tempPath)) { // If this throws, no sense catching it, we can't log it now, and we're here // because we're a child node with no console to log to, so die Directory.CreateDirectory(tempPath); } dumpFileName = Path.Combine(tempPath, "MSBuild_" + guid.ToString()); using (StreamWriter writer = new StreamWriter(dumpFileName, true /*append*/)) { writer.WriteLine("UNHANDLED EXCEPTIONS FROM CHILD NODE:"); writer.WriteLine("==================="); } } using (StreamWriter writer = new StreamWriter(dumpFileName, true /*append*/)) { writer.WriteLine(DateTime.Now.ToLongTimeString()); writer.WriteLine(ex.ToString()); writer.WriteLine("==================="); } } } #endregion #region Constructors /// <summary> /// Creates an instance of this class. /// </summary> internal LocalNode(int nodeNumberIn) { this.nodeNumber = nodeNumberIn; engineCallback = new LocalNodeCallback(communicationThreadExitEvent, this); } #endregion #region Communication Methods /// <summary> /// This method causes the reader and writer threads to start and create the shared memory structures /// </summary> void StartCommunicationThreads() { // The writer thread should be created before the // reader thread because some LocalCallDescriptors // assume the shared memory for the writer thread // has already been created. The method will both // instantiate the shared memory for the writer // thread and also start the writer thread itself. // We will verifyThrow in the method if the // sharedMemory was not created correctly. engineCallback.StartWriterThread(nodeNumber); // Create the shared memory buffer this.sharedMemory = new SharedMemory ( // Generate the name for the shared memory region LocalNodeProviderGlobalNames.NodeInputMemoryName(nodeNumber), SharedMemoryType.ReadOnly, // Reuse an existing shared memory region as it should have already // been created by the parent node side true ); ErrorUtilities.VerifyThrow(this.sharedMemory.IsUsable, "Failed to create shared memory for local node input."); // Start the thread that will be processing the calls from the parent engine ThreadStart threadState = new ThreadStart(this.SharedMemoryReaderThread); readerThread = new Thread(threadState); readerThread.Name = "MSBuild Child<-Parent Reader"; readerThread.Start(); } /// <summary> /// This method causes the reader and writer threads to exit and dispose of the shared memory structures /// </summary> void StopCommunicationThreads() { communicationThreadExitEvent.Set(); // Wait for communication threads to exit Thread writerThread = engineCallback.GetWriterThread(); // The threads may not exist if the child has timed out before the parent has told the node // to start up its communication threads. This can happen if the node is started with /nodemode:x // and no parent is running, or if the parent node has spawned a new process and then crashed // before establishing communication with the child node. if(writerThread != null) { writerThread.Join(); } if (readerThread != null) { readerThread.Join(); } // Make sure the exit event is not set communicationThreadExitEvent.Reset(); } #endregion #region Startup Methods /// <summary> /// Create global events necessary for handshaking with the parent /// </summary> /// <param name="nodeNumber"></param> /// <returns>True if events created successfully and false otherwise</returns> private static bool CreateGlobalEvents(int nodeNumber) { bool createdNew = false; if (NativeMethods.IsUserAdministrator()) { EventWaitHandleSecurity mSec = new EventWaitHandleSecurity(); // Add a rule that grants the access only to admins and systems mSec.SetSecurityDescriptorSddlForm(NativeMethods.ADMINONLYSDDL); // Create an initiation event to allow the parent side to prove to the child that we have the same level of privilege as it does. // this is done by having the parent set this event which means it needs to have administrative permissions to do so. globalInitiateActivationEvent = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeInitiateActivationEventName(nodeNumber), out createdNew, mSec); } else { // Create an initiation event to allow the parent side to prove to the child that we have the same level of privilege as it does. // this is done by having the parent set this event which means it has atleast the same permissions as the child process globalInitiateActivationEvent = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeInitiateActivationEventName(nodeNumber), out createdNew); } // This process must be the creator of the event to prevent squating by a lower privilaged attacker if (!createdNew) { return false; } // Informs the parent process that the child process has been created. globalNodeActive = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeActiveEventName(nodeNumber)); globalNodeActive.Set(); // Indicate to the parent process, this node is currently is ready to start to recieve requests globalNodeInUse = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeInUseEventName(nodeNumber)); // Used by the parent process to inform the child process to shutdown due to the child process // not recieving the initialization command. globalNodeErrorShutdown = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeErrorShutdownEventName(nodeNumber)); // Inform the parent process the node has started its communication threads. globalNodeActivate = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeActivedEventName(nodeNumber)); return true; } /// <summary> /// This function starts local node when process is launched and shuts it down on time out /// Called by msbuild.exe. /// </summary> public static void StartLocalNodeServer(int nodeNumber) { // Create global events necessary for handshaking with the parent if (!CreateGlobalEvents(nodeNumber)) { return; } LocalNode localNode = new LocalNode(nodeNumber); WaitHandle[] waitHandles = new WaitHandle[4]; waitHandles[0] = shutdownEvent; waitHandles[1] = globalNodeErrorShutdown; waitHandles[2] = inUseEvent; waitHandles[3] = globalInitiateActivationEvent; // This is necessary to make build.exe finish promptly. Dont remove. if (!Engine.debugMode) { // Create null streams for the current input/output/error streams Console.SetOut(new StreamWriter(Stream.Null)); Console.SetError(new StreamWriter(Stream.Null)); Console.SetIn(new StreamReader(Stream.Null)); } bool continueRunning = true; while (continueRunning) { int eventType = WaitHandle.WaitAny(waitHandles, inactivityTimeout, false); if (eventType == 0 || eventType == 1 || eventType == WaitHandle.WaitTimeout) { continueRunning = false; localNode.ShutdownNode(eventType != 1 ? Node.NodeShutdownLevel.PoliteShutdown : Node.NodeShutdownLevel.ErrorShutdown, true, true); } else if (eventType == 2) { // reset the event as we do not want it to go into this state again when we are done with this if statement. inUseEvent.Reset(); // The parent knows at this point the child process has been launched globalNodeActivate.Reset(); // Set the global inuse event so other parent processes know this node is now initialized globalNodeInUse.Set(); // Make a copy of the parents handle to protect ourselves in case the parent dies, // this is to prevent a parent from reserving a node another parent is trying to use. globalNodeReserveHandle = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeReserveEventName(nodeNumber)); WaitHandle[] waitHandlesActive = new WaitHandle[3]; waitHandlesActive[0] = shutdownEvent; waitHandlesActive[1] = globalNodeErrorShutdown; waitHandlesActive[2] = notInUseEvent; eventType = WaitHandle.WaitTimeout; while (eventType == WaitHandle.WaitTimeout && continueRunning == true) { eventType = WaitHandle.WaitAny(waitHandlesActive, parentCheckInterval, false); if (eventType == 0 || /* nice shutdown due to shutdownEvent */ eventType == 1 || /* error shutdown due to globalNodeErrorShutdown */ eventType == WaitHandle.WaitTimeout && !localNode.IsParentProcessAlive()) { continueRunning = false; // If the exit is not triggered by running of shutdown method if (eventType != 0) { localNode.ShutdownNode(Node.NodeShutdownLevel.ErrorShutdown, true, true); } } else if (eventType == 2) { // Trigger a collection before the node goes idle to insure that // the memory is released to the system as soon as possible GC.Collect(); // Change the current directory to a safe one so that the directory // last used by the build can be safely deleted. We must have read // access to the safe directory so use SystemDirectory for this purpose. Directory.SetCurrentDirectory(Environment.SystemDirectory); notInUseEvent.Reset(); globalNodeInUse.Reset(); } } ErrorUtilities.VerifyThrow(localNode.node == null, "Expected either node to be null or continueRunning to be false."); // Stop the communication threads and release the shared memory object so that the next parent can create it localNode.StopCommunicationThreads(); // Close the local copy of the reservation handle (this allows another parent to reserve // the node) globalNodeReserveHandle.Close(); globalNodeReserveHandle = null; } else if (eventType == 3) { globalInitiateActivationEvent.Reset(); localNode.StartCommunicationThreads(); globalNodeActivate.Set(); } } // Stop the communication threads and release the shared memory object so that the next parent can create it localNode.StopCommunicationThreads(); globalNodeActive.Close(); globalNodeInUse.Close(); } #endregion #region Methods /// <summary> /// This method is run in its own thread, it is responsible for reading messages sent from the parent process /// through the shared memory region. /// </summary> private void SharedMemoryReaderThread() { // Create an array of event to the node thread responds WaitHandle[] waitHandles = new WaitHandle[2]; waitHandles[0] = communicationThreadExitEvent; waitHandles[1] = sharedMemory.ReadFlag; bool continueExecution = true; try { while (continueExecution) { // Wait for the next work item or an exit command int eventType = WaitHandle.WaitAny(waitHandles); if (eventType == 0) { // Exit node event continueExecution = false; } else { // Read the list of LocalCallDescriptors from sharedMemory, // this will be null if a large object is being read from shared // memory and will continue to be null until the large object has // been completly sent. IList localCallDescriptorList = sharedMemory.Read(); if (localCallDescriptorList != null) { foreach (LocalCallDescriptor callDescriptor in localCallDescriptorList) { // Execute the command method which relates to running on a child node callDescriptor.NodeAction(node, this); if ((callDescriptor.IsReply) && (callDescriptor is LocalReplyCallDescriptor)) { // Process the reply from the parent so it can be looked in a hashtable based // on the call descriptor who requested the reply. engineCallback.PostReplyFromParent((LocalReplyCallDescriptor) callDescriptor); } } } } } } catch (Exception e) { // Will rethrow the exception if necessary ReportFatalCommunicationError(e); } // Dispose of the shared memory buffer if (sharedMemory != null) { sharedMemory.Dispose(); sharedMemory = null; } } /// <summary> /// This method will shutdown the node being hosted by the child process and notify the parent process if requested, /// </summary> /// <param name="shutdownLevel">What kind of shutdown is causing the child node to shutdown</param> /// <param name="exitProcess">should the child process exit as part of the shutdown process</param> /// <param name="noParentNotification">Indicates if the parent process should be notified the child node is being shutdown</param> internal void ShutdownNode(Node.NodeShutdownLevel shutdownLevel, bool exitProcess, bool noParentNotification) { if (node != null) { try { node.ShutdownNode(shutdownLevel); if (!noParentNotification) { // Write the last event out directly LocalCallDescriptorForShutdownComplete callDescriptor = new LocalCallDescriptorForShutdownComplete(shutdownLevel, node.TotalTaskTime); // Post the message indicating that the shutdown is complete engineCallback.PostMessageToParent(callDescriptor, true); } } catch (Exception e) { if (shutdownLevel != Node.NodeShutdownLevel.ErrorShutdown) { ReportNonFatalCommunicationError(e); } } } // If the shutdownLevel is not a build complete message, then this means there was a politeshutdown or an error shutdown, null the node out // as either it is no longer needed due to the node goign idle or there was a error and it is now in a bad state. if (shutdownLevel != Node.NodeShutdownLevel.BuildCompleteSuccess && shutdownLevel != Node.NodeShutdownLevel.BuildCompleteFailure) { node = null; notInUseEvent.Set(); } if (exitProcess) { // Even if we completed a build, if we are goign to exit the process we need to null out the node and set the notInUseEvent, this is // accomplished by calling this method again with the ErrorShutdown handle if ( shutdownLevel == Node.NodeShutdownLevel.BuildCompleteSuccess || shutdownLevel == Node.NodeShutdownLevel.BuildCompleteFailure ) { ShutdownNode(Node.NodeShutdownLevel.ErrorShutdown, false, true); } // Signal all the communication threads to exit shutdownEvent.Set(); } } /// <summary> /// This methods activates the local node /// </summary> internal void Activate ( Hashtable environmentVariables, LoggerDescription[] nodeLoggers, int nodeId, BuildPropertyGroup parentGlobalProperties, ToolsetDefinitionLocations toolsetSearchLocations, int parentId, string parentStartupDirectory ) { ErrorUtilities.VerifyThrow(node == null, "Expected node to be null on activation."); this.parentProcessId = parentId; engineCallback.Reset(); inUseEvent.Set(); // Clear the environment so that we dont have extra variables laying around, this // may be a performance hog but needs to be done IDictionary variableDictionary = Environment.GetEnvironmentVariables(); foreach (string variableName in variableDictionary.Keys) { Environment.SetEnvironmentVariable(variableName, null); } foreach(string key in environmentVariables.Keys) { Environment.SetEnvironmentVariable(key,(string)environmentVariables[key]); } // Host the msbuild engine and system node = new Node(nodeId, nodeLoggers, engineCallback, parentGlobalProperties, toolsetSearchLocations, parentStartupDirectory); // Write the initialization complete event out directly LocalCallDescriptorForInitializationComplete callDescriptor = new LocalCallDescriptorForInitializationComplete(Process.GetCurrentProcess().Id); // Post the message indicating that the initialization is complete engineCallback.PostMessageToParent(callDescriptor, true); } /// <summary> /// This method checks is the parent process has not exited /// </summary> /// <returns>True if the parent process is still alive</returns> private bool IsParentProcessAlive() { bool isParentAlive = true; try { // Check if the parent is still there if (Process.GetProcessById(parentProcessId).HasExited) { isParentAlive = false; } } catch (ArgumentException) { isParentAlive = false; } if (!isParentAlive) { // No logging's going to reach the parent at this point: // indicate on the console what's going on string message = ResourceUtilities.FormatResourceString("ParentProcessUnexpectedlyDied", node.NodeId); Console.WriteLine(message); } return isParentAlive; } /// <summary> /// Any error occuring in the shared memory transport is considered to be fatal /// </summary> /// <param name="originalException"></param> /// <exception cref="Exception">Re-throws exception passed in</exception> internal void ReportFatalCommunicationError(Exception originalException) { try { DumpExceptionToFile(originalException); } finally { if (node != null) { node.ReportFatalCommunicationError(originalException, null); } } } /// <summary> /// This function is used to report exceptions which don't indicate breakdown /// of communication with the parent /// </summary> /// <param name="originalException"></param> internal void ReportNonFatalCommunicationError(Exception originalException) { if (node != null) { try { DumpExceptionToFile(originalException); } finally { node.ReportUnhandledError(originalException); } } else { // Since there is no node object report rethrow the exception ReportFatalCommunicationError(originalException); } } #endregion #region Properties internal static string DumpFileName { get { return dumpFileName; } } #endregion #region Member data private Node node; private SharedMemory sharedMemory; private LocalNodeCallback engineCallback; private int parentProcessId; private int nodeNumber; private Thread readerThread; private static object dumpFileLocker = new Object(); // Public named events // If this event is set the node host process is currently running private static EventWaitHandle globalNodeActive; // If this event is set the node is currently running a build private static EventWaitHandle globalNodeInUse; // If this event exists the node is reserved for use by a particular parent engine // the node keeps a handle to this event during builds to prevent it from being used // by another parent engine if the original dies private static EventWaitHandle globalNodeReserveHandle; // If this event is set the node will immediatelly exit. The event is used by the // parent engine to cause the node to exit if communication is lost. private static EventWaitHandle globalNodeErrorShutdown; // This event is used to cause the child to create the shared memory structures to start communication // with the parent private static EventWaitHandle globalInitiateActivationEvent; // This event is used to indicate to the parent that shared memory buffers have been created and are ready for // use private static EventWaitHandle globalNodeActivate; // Private local events private static ManualResetEvent communicationThreadExitEvent = new ManualResetEvent(false); private static ManualResetEvent shutdownEvent = new ManualResetEvent(false); private static ManualResetEvent notInUseEvent = new ManualResetEvent(false); /// <summary> /// Indicates the node is now in use. This means the node has recieved an activate command with initialization /// data from the parent procss /// </summary> private static ManualResetEvent inUseEvent = new ManualResetEvent(false); /// <summary> /// Randomly generated file name for all exceptions thrown by this node that need to be dumped to a file. /// (There may be more than one exception, if they occur on different threads.) /// </summary> private static string dumpFileName = null; // Timeouts && Constants private const int inactivityTimeout = 60 * 1000; // 60 seconds of inactivity to exit private const int parentCheckInterval = 5 * 1000; // Check if the parent process is there every 5 seconds #endregion } }
nikson/msbuild
src/OrcasEngine/LocalProvider/LocalNode.cs
C#
mit
28,537
//****************************************************************************** // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //****************************************************************************** // WindowsDataXmlXsl.h // Generated from winmd2objc #pragma once #include <UWP/interopBase.h> @class WDXXXsltProcessor; @protocol WDXXIXsltProcessor , WDXXIXsltProcessor2, WDXXIXsltProcessorFactory; #include "WindowsDataXmlDom.h" #import <Foundation/Foundation.h> // Windows.Data.Xml.Xsl.XsltProcessor #ifndef __WDXXXsltProcessor_DEFINED__ #define __WDXXXsltProcessor_DEFINED__ WINRT_EXPORT @interface WDXXXsltProcessor : RTObject + (WDXXXsltProcessor*)makeInstance:(WDXDXmlDocument*)document ACTIVATOR; - (NSString*)transformToString:(RTObject<WDXDIXmlNode>*)inputNode; - (WDXDXmlDocument*)transformToDocument:(RTObject<WDXDIXmlNode>*)inputNode; @end #endif // __WDXXXsltProcessor_DEFINED__
rajsesh-msft/WinObjC
include/Platform/Universal Windows/UWP/WindowsDataXmlXsl.h
C
mit
1,477
/** * @license * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as ts from "typescript"; import * as Lint from "../index"; export declare class Rule extends Lint.Rules.AbstractRule { static metadata: Lint.IRuleMetadata; static FAILURE_STRING_FACTORY(ident: string): string; apply(sourceFile: ts.SourceFile): Lint.RuleFailure[]; }
AxelSparkster/axelsparkster.github.io
node_modules/tslint/lib/rules/noParameterPropertiesRule.d.ts
TypeScript
mit
911
/* FreeRTOS V8.2.3 - Copyright (C) 2015 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS 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 >>>> AND MODIFIED BY <<<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS 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. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ /* * Interrupt service routines that cannot nest have no special requirements and * can be written as per the compiler documentation. However interrupts written * in this manner will utilise the stack of whichever task was interrupts, * rather than the system stack, necessitating that adequate stack space be * allocated to each created task. It is therefore not recommended to write * interrupt service routines in this manner. * * Interrupts service routines that can nest require a simple assembly wrapper. * This file is provided as a example of how this is done. * * The example in this file creates a single task. The task blocks on a * semaphore which is periodically 'given' from a timer interrupt. The assembly * wrapper for the interrupt is implemented in ISRTriggeredTask_isr.S. The * C function called by the assembly wrapper is implemented in this file. * * The task toggle LED mainISR_TRIGGERED_LED each time it is unblocked by the * interrupt. */ /* Standard includes. */ #include <stdio.h> /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" #include "semphr.h" /* Standard demo includes. */ #include "ParTest.h" /*-----------------------------------------------------------*/ /* The LED controlled by the ISR triggered task. */ #define mainISR_TRIGGERED_LED ( 1 ) /* Constants used to configure T5. */ #define mainT5PRESCALAR ( 6 ) #define mainT5_SEMAPHORE_RATE ( 31250 ) /*-----------------------------------------------------------*/ /* * The task that is periodically triggered by an interrupt, as described at the * top of this file. */ static void prvISRTriggeredTask( void* pvParameters ); /* * Configures the T5 timer peripheral to generate the interrupts that unblock * the task implemented by the prvISRTriggeredTask() function. */ static void prvSetupT5( void ); /* The timer 5 interrupt handler. As this interrupt uses the FreeRTOS assembly entry point the IPL setting in the following function prototype has no effect. */ void __attribute__( (interrupt(IPL3AUTO), vector(_TIMER_5_VECTOR))) vT5InterruptWrapper( void ); /*-----------------------------------------------------------*/ /* The semaphore given by the T5 interrupt to unblock the task implemented by the prvISRTriggeredTask() function. */ static SemaphoreHandle_t xBlockSemaphore = NULL; /*-----------------------------------------------------------*/ void vStartISRTriggeredTask( void ) { /* Create the task described at the top of this file. The timer is configured by the task itself. */ xTaskCreate( prvISRTriggeredTask, /* The function that implements the task. */ "ISRt", /* Text name to help debugging - not used by the kernel. */ configMINIMAL_STACK_SIZE, /* The size of the stack to allocate to the task - defined in words, not bytes. */ NULL, /* The parameter to pass into the task. Not used in this case. */ configMAX_PRIORITIES - 1, /* The priority at which the task is created. */ NULL ); /* Used to pass a handle to the created task out of the function. Not used in this case. */ } /*-----------------------------------------------------------*/ void vT5InterruptHandler( void ) { portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE; /* This function is the handler for the peripheral timer interrupt. The interrupt is initially signalled in a separate assembly file which switches to the system stack and then calls this function. It gives a semaphore which signals the prvISRBlockTask */ /* Give the semaphore. If giving the semaphore causes the task to leave the Blocked state, and the priority of the task is higher than the priority of the interrupted task, then xHigherPriorityTaskWoken will be set to pdTRUE inside the xSemaphoreGiveFromISR() function. xHigherPriorityTaskWoken is later passed into portEND_SWITCHING_ISR(), where a context switch is requested if it is pdTRUE. The context switch ensures the interrupt returns directly to the unblocked task. */ xSemaphoreGiveFromISR( xBlockSemaphore, &xHigherPriorityTaskWoken ); /* Clear the interrupt */ IFS0CLR = _IFS0_T5IF_MASK; /* See comment above the call to xSemaphoreGiveFromISR(). */ portEND_SWITCHING_ISR( xHigherPriorityTaskWoken ); } /*-----------------------------------------------------------*/ static void prvISRTriggeredTask( void* pvParameters ) { /* Avoid compiler warnings. */ ( void ) pvParameters; /* Create the semaphore used to signal this task */ xBlockSemaphore = xSemaphoreCreateBinary(); /* Configure the timer to generate the interrupts. */ prvSetupT5(); for( ;; ) { /* Block on the binary semaphore given by the T5 interrupt. */ xSemaphoreTake( xBlockSemaphore, portMAX_DELAY ); /* Toggle the LED. */ vParTestToggleLED( mainISR_TRIGGERED_LED ); } } /*-----------------------------------------------------------*/ static void prvSetupT5( void ) { /* Set up timer 5 to generate an interrupt every 50 ms */ T5CON = 0; TMR5 = 0; T5CONbits.TCKPS = mainT5PRESCALAR; PR5 = mainT5_SEMAPHORE_RATE; /* Setup timer 5 interrupt priority to be the maximum from which interrupt safe FreeRTOS API functions can be called. Interrupt safe FreeRTOS API functions are those that end "FromISR". */ IPC6bits.T5IP = configMAX_SYSCALL_INTERRUPT_PRIORITY; /* Clear the interrupt as a starting condition. */ IFS0bits.T5IF = 0; /* Enable the interrupt. */ IEC0bits.T5IE = 1; /* Start the timer. */ T5CONbits.TON = 1; }
PUCSIE-embedded-course/stm32f4-examples
firmware/freertos/semaphore/lib/FreeRTOSV8.2.3/FreeRTOS/Demo/PIC32MZ_MPLAB/ISRTriggeredTask.c
C
mit
9,510
<?php get_header(); ?> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <article role="main" class="primary-content type-post" id="post-<?php the_ID(); ?>"> <header> <h1><?php the_title(); ?></h1> </header> <?php the_post_thumbnail('full');?> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:' ), 'after' => '</div>' ) ); ?> <footer class="entry-meta"> <p>Posted <strong><?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?></strong> on <time datetime="<?php the_time('l, F jS, Y') ?>" pubdate><?php the_time('l, F jS, Y') ?></time> &middot; <a href="<?php the_permalink(); ?>">Permalink</a></p> </footer> <?php comments_template( '', true ); ?> <ul class="navigation"> <li class="older"> <?php previous_post_link( '%link', '&larr; %title' ); ?> </li> <li class="newer"> <?php next_post_link( '%link', '%title &rarr;' ); ?> </li> </ul> <?php endwhile; // end of the loop. ?> </article> <?php get_footer(); ?>
evanhuntley/ftg
single.php
PHP
mit
1,237
# What is Plone? [Plone](https://plone.org) is a free and open source content management system built on top of the Zope application server. %%LOGO%% ## Features - Images for Plone 5 and Plone 4 - Enable add-ons via environment variables ## Usage ### Start a single Plone instance This will download and start the latest Plone 5 container, based on [Debian](https://www.debian.org/). ```console $ docker run -p 8080:8080 plone ``` This image includes `EXPOSE 8080` (the Plone port), so standard container linking will make it automatically available to the linked containers. Now you can add a Plone Site at http://localhost:8080 - default Zope user and password are `admin/admin`. ### Start Plone within a ZEO cluster Start ZEO server ```console $ docker run --name=zeo plone zeoserver ``` Start 2 Plone clients ```console $ docker run --link=zeo -e ZEO_ADDRESS=zeo:8100 -p 8081:8080 plone $ docker run --link=zeo -e ZEO_ADDRESS=zeo:8100 -p 8082:8080 plone ``` ### Start Plone in debug mode You can also start Plone in debug mode (`fg`) by running ```console $ docker run -p 8080:8080 plone fg ``` ### Add-ons You can enable Plone add-ons via the `PLONE_ADDONS` environment variable ```console $ docker run -p 8080:8080 -e PLONE_ADDONS="eea.facetednavigation Products.PloneFormGen" plone ``` For more information on how to extend this image with your own custom settings, adding more add-ons, building it or mounting volumes, please refer to our [documentation](https://github.com/plone/plone.docker/blob/master/docs/usage.rst). ### Supported Environment Variables The Plone image uses several environment variable that allow to specify a more specific setup. - `PLONE_ADDONS`, `ADDONS` - Customize Plone via Plone add-ons using this environment variable - `PLONE_ZCML`, `ZCML` - Include custom Plone add-ons ZCML files - `PLONE_DEVELOP`, `DEVELOP` - Develop new or existing Plone add-ons - `ZEO_ADDRESS` - This environment variable allows you to run Plone image as a ZEO client. - `ZEO_READ_ONLY` - Run Plone as a read-only ZEO client. Defaults to `off`. - `ZEO_CLIENT_READ_ONLY_FALLBACK` - A flag indicating whether a read-only remote storage should be acceptable as a fallback when no writable storages are available. Defaults to `false`. - `ZEO_SHARED_BLOB_DIR` - Set this to on if the ZEO server and the instance have access to the same directory. Defaults to `off`. - `ZEO_STORAGE` - Set the storage number of the ZEO storage. Defaults to `1`. - `ZEO_CLIENT_CACHE_SIZE` - Set the size of the ZEO client cache. Defaults to `128MB`. - `ZEO_PACK_KEEP_OLD` - Can be set to false to disable the creation of `*.fs.old` files before the pack is run. Defaults to true. - `HEALTH_CHECK_TIMEOUT` - Time in seconds to wait until health check starts. Defaults to `1` second. - `HEALTH_CHECK_INTERVAL` - Interval in seconds to check that the Zope application is still healthy. Defaults to `1` second. ## Documentation Full documentation for end users can be found in the ["docs"](https://github.com/plone/plone.docker/tree/master/docs) folder. It is also available online at http://docs.plone.org/ ## Credits This docker image was originally financed by the [European Environment Agency](http://eea.europa.eu), an agency of the European Union. Thanks to [Antonio De Marinis](https://github.com/demarant), [Sven Strack](https://github.com/svx) and [Alin Voinea](https://github.com/avoinea) for their preliminary work.
pydio/docs
plone/content.md
Markdown
mit
3,440
/** * Copyright (c) 2014,2015 NetEase, Inc. and other Pomelo contributors * MIT Licensed. */ #include <assert.h> #include <string.h> #include <pomelo_trans.h> #include "pc_lib.h" #include "pc_pomelo_i.h" void pc_trans_fire_event(pc_client_t* client, int ev_type, const char* arg1, const char* arg2) { int pending = 0; if (!client) { pc_lib_log(PC_LOG_ERROR, "pc_client_fire_event - client is null"); return ; } if (client->config.enable_polling) { pending = 1; } pc__trans_fire_event(client, ev_type, arg1, arg2, pending); } void pc__trans_fire_event(pc_client_t* client, int ev_type, const char* arg1, const char* arg2, int pending) { QUEUE* q; pc_ev_handler_t* handler; pc_event_t* ev; int i; if (ev_type >= PC_EV_COUNT || ev_type < 0) { pc_lib_log(PC_LOG_ERROR, "pc__transport_fire_event - error event type"); return; } if (ev_type == PC_EV_USER_DEFINED_PUSH && (!arg1 || !arg2)) { pc_lib_log(PC_LOG_ERROR, "pc__transport_fire_event - push msg but without a route or msg"); return; } if (ev_type == PC_EV_CONNECT_ERROR || ev_type == PC_EV_UNEXPECTED_DISCONNECT || ev_type == PC_EV_PROTO_ERROR || ev_type == PC_EV_CONNECT_FAILED) { if (!arg1) { pc_lib_log(PC_LOG_ERROR, "pc__transport_fire_event - event should be with a reason description"); return ; } } if (pending) { assert(client->config.enable_polling); pc_lib_log(PC_LOG_INFO, "pc__trans_fire_event - add pending event: %s", pc_client_ev_str(ev_type)); pc_mutex_lock(&client->event_mutex); ev = NULL; for (i = 0; i < PC_PRE_ALLOC_EVENT_SLOT_COUNT; ++i) { if (PC_PRE_ALLOC_IS_IDLE(client->pending_events[i].type)) { ev = &client->pending_events[i]; PC_PRE_ALLOC_SET_BUSY(ev->type); break; } } if (!ev) { ev = (pc_event_t* )pc_lib_malloc(sizeof(pc_event_t)); memset(ev, 0, sizeof(pc_event_t)); ev->type = PC_DYN_ALLOC; } PC_EV_SET_NET_EVENT(ev->type); QUEUE_INIT(&ev->queue); QUEUE_INSERT_TAIL(&client->pending_ev_queue, &ev->queue); ev->data.ev.ev_type = ev_type; if (arg1) { ev->data.ev.arg1 = pc_lib_strdup(arg1); } else { ev->data.ev.arg1 = NULL; } if (arg2) { ev->data.ev.arg2 = pc_lib_strdup(arg2); } else { ev->data.ev.arg2 = NULL; } pc_mutex_unlock(&client->event_mutex); return ; } pc_lib_log(PC_LOG_INFO, "pc__trans_fire_event - fire event: %s, arg1: %s, arg2: %s", pc_client_ev_str(ev_type), arg1 ? arg1 : "", arg2 ? arg2 : ""); pc_mutex_lock(&client->state_mutex); switch(ev_type) { case PC_EV_CONNECTED: assert(client->state == PC_ST_CONNECTING); client->state = PC_ST_CONNECTED; break; case PC_EV_CONNECT_ERROR: assert(client->state == PC_ST_CONNECTING || client->state == PC_ST_DISCONNECTING); break; case PC_EV_CONNECT_FAILED: assert(client->state == PC_ST_CONNECTING || client->state == PC_ST_DISCONNECTING); client->state = PC_ST_INITED; break; case PC_EV_DISCONNECT: assert(client->state == PC_ST_DISCONNECTING); client->state = PC_ST_INITED; break; case PC_EV_KICKED_BY_SERVER: assert(client->state == PC_ST_CONNECTED || client->state == PC_ST_DISCONNECTING); client->state = PC_ST_INITED; break; case PC_EV_UNEXPECTED_DISCONNECT: case PC_EV_PROTO_ERROR: assert(client->state == PC_ST_CONNECTING || client->state == PC_ST_CONNECTED || client->state == PC_ST_DISCONNECTING); client->state = PC_ST_CONNECTING; break; case PC_EV_USER_DEFINED_PUSH: /* do nothing here */ break; default: /* never run to here */ pc_lib_log(PC_LOG_ERROR, "pc__trans_fire_event - unknown network event: %d", ev_type); } pc_mutex_unlock(&client->state_mutex); /* invoke handler */ pc_mutex_lock(&client->handler_mutex); QUEUE_FOREACH(q, &client->ev_handlers) { handler = QUEUE_DATA(q, pc_ev_handler_t, queue); assert(handler && handler->cb); handler->cb(client, ev_type, handler->ex_data, arg1, arg2); } pc_mutex_unlock(&client->handler_mutex); } void pc_trans_sent(pc_client_t* client, unsigned int seq_num, int rc) { int pending = 0; if (!client) { pc_lib_log(PC_LOG_ERROR, "pc_trans_sent - client is null"); return ; } if (client->config.enable_polling) { pending = 1; } pc__trans_sent(client, seq_num, rc, pending); } void pc__trans_sent(pc_client_t* client, unsigned int seq_num, int rc, int pending) { QUEUE* q; pc_notify_t* notify; pc_notify_t* target; pc_event_t* ev; int i; if (pending) { pc_mutex_lock(&client->event_mutex); pc_lib_log(PC_LOG_INFO, "pc__trans_sent - add pending sent event, seq_num: %u, rc: %s", seq_num, pc_client_rc_str(rc)); ev = NULL; for (i = 0; i < PC_PRE_ALLOC_EVENT_SLOT_COUNT; ++i) { if (PC_PRE_ALLOC_IS_IDLE(client->pending_events[i].type)) { ev = &client->pending_events[i]; PC_PRE_ALLOC_SET_BUSY(ev->type); break; } } if (!ev) { ev = (pc_event_t* )pc_lib_malloc(sizeof(pc_event_t)); memset(ev, 0, sizeof(pc_event_t)); ev->type = PC_DYN_ALLOC; } QUEUE_INIT(&ev->queue); PC_EV_SET_NOTIFY_SENT(ev->type); ev->data.notify.seq_num = seq_num; ev->data.notify.rc = rc; QUEUE_INSERT_TAIL(&client->pending_ev_queue, &ev->queue); pc_mutex_unlock(&client->event_mutex); return ; } /* callback immediately */ pc_mutex_lock(&client->notify_mutex); target = NULL; QUEUE_FOREACH(q, &client->notify_queue) { notify = (pc_notify_t* )QUEUE_DATA(q, pc_common_req_t, queue); if (notify->base.seq_num == seq_num) { pc_lib_log(PC_LOG_INFO, "pc__trans_sent - fire sent event, seq_num: %u, rc: %s", seq_num, pc_client_rc_str(rc)); target = notify; QUEUE_REMOVE(q); QUEUE_INIT(q); break; } } pc_mutex_unlock(&client->notify_mutex); if (target) { target->cb(target, rc); pc_lib_free((char*)target->base.msg); pc_lib_free((char*)target->base.route); target->base.msg = NULL; target->base.route = NULL; if (PC_IS_PRE_ALLOC(target->base.type)) { pc_mutex_lock(&client->notify_mutex); PC_PRE_ALLOC_SET_IDLE(target->base.type); pc_mutex_unlock(&client->notify_mutex); } else { pc_lib_free(target); } } else { pc_lib_log(PC_LOG_ERROR, "pc__trans_sent - no pending notify found" " when transport has sent it, seq num: %u", seq_num); } } void pc_trans_resp(pc_client_t* client, unsigned int req_id, int rc, const char* resp) { int pending = 0; if (!client) { pc_lib_log(PC_LOG_ERROR, "pc_trans_resp - client is null"); return ; } if (client->config.enable_polling) { pending = 1; } pc__trans_resp(client, req_id, rc, resp, pending); } void pc__trans_resp(pc_client_t* client, unsigned int req_id, int rc, const char* resp, int pending) { QUEUE* q; pc_request_t* req; pc_event_t* ev; pc_request_t* target; int i; if (pending) { pc_mutex_lock(&client->event_mutex); pc_lib_log(PC_LOG_INFO, "pc__trans_resp - add pending resp event, req_id: %u, rc: %s", req_id, pc_client_rc_str(rc)); ev = NULL; for (i = 0; i < PC_PRE_ALLOC_EVENT_SLOT_COUNT; ++i) { if (PC_PRE_ALLOC_IS_IDLE(client->pending_events[i].type)) { ev = &client->pending_events[i]; PC_PRE_ALLOC_SET_BUSY(ev->type); break; } } if (!ev) { ev = (pc_event_t* )pc_lib_malloc(sizeof(pc_event_t)); memset(ev, 0, sizeof(pc_event_t)); ev->type = PC_DYN_ALLOC; } PC_EV_SET_RESP(ev->type); QUEUE_INIT(&ev->queue); ev->data.req.req_id = req_id; ev->data.req.rc = rc; ev->data.req.resp = pc_lib_strdup(resp); QUEUE_INSERT_TAIL(&client->pending_ev_queue, &ev->queue); pc_mutex_unlock(&client->event_mutex); return ; } /* invoke callback immediately */ target = NULL; pc_mutex_lock(&client->req_mutex); QUEUE_FOREACH(q, &client->req_queue) { req= (pc_request_t* )QUEUE_DATA(q, pc_common_req_t, queue); if (req->req_id == req_id) { pc_lib_log(PC_LOG_INFO, "pc__trans_resp - fire resp event, req_id: %u, rc: %s", req_id, pc_client_rc_str(rc)); target = req; QUEUE_REMOVE(q); QUEUE_INIT(q); break; } } pc_mutex_unlock(&client->req_mutex); if (target) { target->cb(target, rc, resp); pc_lib_free((char*)target->base.msg); pc_lib_free((char*)target->base.route); target->base.msg = NULL; target->base.route = NULL; if (PC_IS_PRE_ALLOC(target->base.type)) { pc_mutex_lock(&client->req_mutex); PC_PRE_ALLOC_SET_IDLE(target->base.type); pc_mutex_unlock(&client->req_mutex); } else { pc_lib_free(target); } } else { pc_lib_log(PC_LOG_ERROR, "pc__trans_resp - no pending request found when" " get a response, req id: %u", req_id); } }
hitstanley/libpomelo2
src/pc_trans.c
C
mit
10,100
// Copyright (c) 2011-2016 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include <cstddef> #include <cstring> #include <functional> #define CRYPTO_MAKE_COMPARABLE(type) \ namespace Crypto { \ inline bool operator==(const type &_v1, const type &_v2) { \ return std::memcmp(&_v1, &_v2, sizeof(type)) == 0; \ } \ inline bool operator!=(const type &_v1, const type &_v2) { \ return std::memcmp(&_v1, &_v2, sizeof(type)) != 0; \ } \ } #define CRYPTO_MAKE_HASHABLE(type) \ CRYPTO_MAKE_COMPARABLE(type) \ namespace Crypto { \ static_assert(sizeof(size_t) <= sizeof(type), "Size of " #type " must be at least that of size_t"); \ inline size_t hash_value(const type &_v) { \ return reinterpret_cast<const size_t &>(_v); \ } \ } \ namespace std { \ template<> \ struct hash<Crypto::type> { \ size_t operator()(const Crypto::type &_v) const { \ return reinterpret_cast<const size_t &>(_v); \ } \ }; \ }
Boter/SIT
src/crypto/generic-ops.h
C
mit
1,079
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.ResourceManager.Storage.Models { /// <summary> The resource model definition for a Azure Resource Manager resource with an etag. </summary> public partial class AzureEntityResource : Resource { /// <summary> Initializes a new instance of AzureEntityResource. </summary> public AzureEntityResource() { } /// <summary> Initializes a new instance of AzureEntityResource. </summary> /// <param name="id"> Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. </param> /// <param name="name"> The name of the resource. </param> /// <param name="type"> The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. </param> /// <param name="etag"> Resource Etag. </param> internal AzureEntityResource(string id, string name, string type, string etag) : base(id, name, type) { Etag = etag; } /// <summary> Resource Etag. </summary> public string Etag { get; } } }
ayeletshpigelman/azure-sdk-for-net
sdk/storage/Azure.ResourceManager.Storage/src/Generated/Models/AzureEntityResource.cs
C#
mit
1,326
// // CCHDevice.h // ContextHub // // Created by Kevin Lee on 7/24/14. // Copyright (c) 2014 ChaiOne. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #define kDeviceErrorDomain @"com.contexthub.device.error" /** ContextHub Device error codes. */ typedef NS_ENUM(NSInteger, CCHDeviceErrorCode) { /** Device id cannot be nil */ CCHInvalidDeviceIdParameter, /** Alias cannot be nil */ CCHInvalidDeviceAliasParameter, /** Tags cannot be nil */ CCHInvalidDeviceTagsParameter }; /** The CCHDevice class is used work with devices. Structure of device NSDictionary | key | value | | --------- | --------- | | additional_info | NSDictionary of device specific information (not always present) | | alias | alias that is set for the device (not always present) | | device_type | describes the device, often pulled for the user agent | | id | database id for the device | | last_profile | NSDictionary of contextual information from the last time the device was seen by the server | | push_token | push token assigned to the device (not always present) | | tag_string | a comma separated string of the tags associated with the device | | tags | NSArray of tags associated with the device | */ @interface CCHDevice : NSObject /** @return The singleton instance of CCHDevice. */ + (instancetype)sharedInstance; /** @return The vendor device id as UUIDString. */ - (NSString *)deviceId; /** Gets a device from ContextHub using the device Id. @param deviceId The id of the device stored in ContextHub. @param completionHandler Called when the request completes. The block is passed an NSDictionary object that represents the device. If an error occurs, the NSError will be passed to the block. */ - (void)getDeviceWithId:(NSString *)deviceId completionHandler:(void(^)(NSDictionary *device, NSError *error))completionHandler; /** Gets devices from ContextHub using the device alias. @param alias The alias associated with the devices that you are interested in. @param completionHandler Called when the request completes. The block is passed an NSArray of NSDictionary objects that represent the devices. If an error occurs, the NSError will be passed to the block. */ - (void)getDevicesWithAlias:(NSString *)alias completionHandler:(void(^)(NSArray *devices, NSError *error))completionHandler; /** Gets devices from ContextHub using tags. @param tags Tags of the devices that you are interested in. @param completionHandler Called when the request completes. The block is passed an NSArray of NSDictionary objects that represent the devices. If an error occurs, the NSError will be passed to the block. */ - (void)getDevicesWithTags:(NSArray *)tags completionHandler:(void(^)(NSArray *devices, NSError *error))completionHandler; /** Updates the device record on contexthub. @param alias (optional) The alias associated with the device. @param tags (optional) The tags to be applied to the device. @param completionHandler Called when the request completes. The block is passed an NSDictionary object that represents the device. If an error occurs, the NSError will be passed to the block. @note This method updates the data for the current device. The tags and alias that are set here can be used with CCHPush. The tags can also be used with the CCHSubscriptionService. This method gathers meta-data about the device and sends it to ContextHub along with the alias and tags. You can call this method multiple times. */ - (void)setDeviceAlias:(NSString *)alias tags:(NSArray *)tags completionHandler:(void(^)(NSDictionary *device, NSError *error))completionHandler; @end
contexthub/awareness-ios
ContextHub.framework/Versions/Current/Headers/CCHDevice.h
C
mit
3,725
/* Copyright (c) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // GTLDriveReply.h // // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v3) // Description: // Manages files in Drive including uploading, downloading, searching, // detecting changes, and updating sharing permissions. // Documentation: // https://developers.google.com/drive/ // Classes: // GTLDriveReply (0 custom class methods, 9 custom properties) #if GTL_BUILT_AS_FRAMEWORK #import "GTL/GTLObject.h" #else #import "GTLObject.h" #endif @class GTLDriveUser; // ---------------------------------------------------------------------------- // // GTLDriveReply // // A reply to a comment on a file. @interface GTLDriveReply : GTLObject // The action the reply performed to the parent comment. Valid values are: // - resolve // - reopen @property (nonatomic, copy) NSString *action; // The user who created the reply. @property (nonatomic, retain) GTLDriveUser *author; // The plain text content of the reply. This field is used for setting the // content, while htmlContent should be displayed. This is required on creates // if no action is specified. @property (nonatomic, copy) NSString *content; // The time at which the reply was created (RFC 3339 date-time). @property (nonatomic, retain) GTLDateTime *createdTime; // Whether the reply has been deleted. A deleted reply has no content. @property (nonatomic, retain) NSNumber *deleted; // boolValue // The content of the reply with HTML formatting. @property (nonatomic, copy) NSString *htmlContent; // The ID of the reply. // identifier property maps to 'id' in JSON (to avoid Objective C's 'id'). @property (nonatomic, copy) NSString *identifier; // This is always drive#reply. @property (nonatomic, copy) NSString *kind; // The last time the reply was modified (RFC 3339 date-time). @property (nonatomic, retain) GTLDateTime *modifiedTime; @end
venkatamacha/google_password_manager
google_password_manager/Pods/GoogleAPIClient/Source/Services/Drive/Generated/GTLDriveReply.h
C
mit
2,567
'use strict'; describe('Controller: AboutCtrl', function () { // load the controller's module beforeEach(module('e01App')); var AboutCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); AboutCtrl = $controller('AboutCtrl', { $scope: scope // place here mocked dependencies }); })); it('should attach a list of awesomeThings to the scope', function () { expect(AboutCtrl.awesomeThings.length).toBe(3); }); });
malaniz/cursoAngular
cl06ClienteB/test/spec/controllers/about.js
JavaScript
mit
550
<!DOCTYPE html> <html lang="en"> <head> <title>three.js webgl - trackball camera</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <style> body { color: #000; font-family:Monospace; font-size:13px; text-align:center; font-weight: bold; background-color: #fff; margin: 0px; overflow: hidden; } #info { color:#000; position: absolute; top: 0px; width: 100%; padding: 5px; } a { color: red; } </style> </head> <body> <div id="container"></div> <div id="info"> <a href="http://github.com/mrdoob/three.js" target="_blank">three.js</a> - trackball camera example</br> MOVE mouse &amp; press LEFT/A: rotate, MIDDLE/S: zoom, RIGHT/D: pan </div> <script src="../build/three.min.js"></script> <script src="js/Detector.js"></script> <script src="js/Stats.js"></script> <script> if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); var container, stats; var camera, controls, scene, renderer; var cross; init(); animate(); function init() { camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 ); camera.position.z = 500; controls = new THREE.TrackballControls( camera ); controls.rotateSpeed = 1.0; controls.zoomSpeed = 1.2; controls.panSpeed = 0.8; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.keys = [ 65, 83, 68 ]; controls.addEventListener( 'change', render ); // world scene = new THREE.Scene(); scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 ); var geometry = new THREE.CylinderGeometry( 0, 10, 30, 4, 1 ); var material = new THREE.MeshLambertMaterial( { color:0xffffff, shading: THREE.FlatShading } ); for ( var i = 0; i < 500; i ++ ) { var mesh = new THREE.Mesh( geometry, material ); mesh.position.x = ( Math.random() - 0.5 ) * 1000; mesh.position.y = ( Math.random() - 0.5 ) * 1000; mesh.position.z = ( Math.random() - 0.5 ) * 1000; mesh.updateMatrix(); mesh.matrixAutoUpdate = false; scene.add( mesh ); } // lights light = new THREE.DirectionalLight( 0xffffff ); light.position.set( 1, 1, 1 ); scene.add( light ); light = new THREE.DirectionalLight( 0x002288 ); light.position.set( -1, -1, -1 ); scene.add( light ); light = new THREE.AmbientLight( 0x222222 ); scene.add( light ); // renderer renderer = new THREE.WebGLRenderer( { antialias: false } ); renderer.setClearColor( scene.fog.color, 1 ); renderer.setSize( window.innerWidth, window.innerHeight ); container = document.getElementById( 'container' ); container.appendChild( renderer.domElement ); stats = new Stats(); stats.domElement.style.position = 'absolute'; stats.domElement.style.top = '0px'; stats.domElement.style.zIndex = 100; container.appendChild( stats.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); controls.handleResize(); render(); } function animate() { requestAnimationFrame( animate ); controls.update(); } function render() { renderer.render( scene, camera ); stats.update(); } </script> </body> </html>
christopheschwyzer/StopheWebLab
three/source/three/examples/misc_camera_trackball.html
HTML
mit
3,637
var searchData= [ ['digitalpin_2eh',['DigitalPin.h',['../_digital_pin_8h.html',1,'']]] ];
cnorfleet/Feeder
libraries/SdFatCopy/html/search/files_2.js
JavaScript
mit
92
namespace GraphQL.Types { public class UnionGraphType : GraphType { } }
bryanerayner/graphql-dotnet
src/GraphQL/Types/UnionGraphType.cs
C#
mit
87
{% extends "base.html" %} {% block title %}All notes ({{ notes|length }}){% endblock %} {% block page_title %} <span>All notes ({{ notes|length }})</span> {% endblock %} {% block content %} {% if notes %} <table class="notes"> <tr> <th class="note">Note <a href="/?order=name" class="sort_arrow" >&darr;</a><a href="/?order=-name" class="sort_arrow" >&uarr;</a></th> <th>Pad</th> <th class="date">Last modified <a href="/?order=updated_at" class="sort_arrow" >&darr;</a><a href="/?order=-updated_at" class="sort_arrow" >&uarr;</a></th> </tr> {% for note in notes %} <tr> <td><a href="{{ url_for('view_note', note_id=note.id) }}">{{ note.name }}</a></td> <td class="pad"> {% if note.pad %} <a href="{{ url_for('pad_notes', pad_id=note.pad.id) }}">{{ note.pad.name }}</a> {% else %} No pad {% endif %} </td> <td class="hidden-text date">{{ note.updated_at|smart_date }}</td> </tr> {% endfor %} </table> {% else %} <p class="empty">Create your first note.</p> {% endif %} <a href="{{ url_for('create_note') }}" class="button">New note</a> {% endblock %}
williamn/notejam
flask/notejam/templates/notes/list.html
HTML
mit
1,221
package org.knowm.xchange.ripple; import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.ParseException; import org.junit.Test; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.account.AccountInfo; import org.knowm.xchange.dto.account.Balance; import org.knowm.xchange.dto.account.Wallet; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrade; import org.knowm.xchange.ripple.dto.account.ITransferFeeSource; import org.knowm.xchange.ripple.dto.account.RippleAccountBalances; import org.knowm.xchange.ripple.dto.account.RippleAccountSettings; import org.knowm.xchange.ripple.dto.marketdata.RippleOrderBook; import org.knowm.xchange.ripple.dto.trade.IRippleTradeTransaction; import org.knowm.xchange.ripple.dto.trade.RippleAccountOrders; import org.knowm.xchange.ripple.dto.trade.RippleLimitOrder; import org.knowm.xchange.ripple.dto.trade.RippleOrderTransaction; import org.knowm.xchange.ripple.dto.trade.RipplePaymentTransaction; import org.knowm.xchange.ripple.dto.trade.RippleUserTrade; import org.knowm.xchange.ripple.service.params.RippleMarketDataParams; import org.knowm.xchange.ripple.service.params.RippleTradeHistoryParams; import org.knowm.xchange.service.trade.params.TradeHistoryParams; public class RippleAdaptersTest implements ITransferFeeSource { @Test public void adaptAccountInfoTest() throws IOException { // Read in the JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/account/example-account-balances.json"); // Use Jackson to parse it final ObjectMapper mapper = new ObjectMapper(); final RippleAccountBalances rippleAccount = mapper.readValue(is, RippleAccountBalances.class); // Convert to xchange object and check field values final AccountInfo account = RippleAdapters.adaptAccountInfo(rippleAccount, "username"); assertThat(account.getWallets()).hasSize(2); assertThat(account.getUsername()).isEqualTo("username"); assertThat(account.getTradingFee()).isEqualTo(BigDecimal.ZERO); final Wallet counterWallet = account.getWallet("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(counterWallet.getId()).isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(counterWallet.getBalances()).hasSize(2); final Balance btcBalance = counterWallet.getBalance(Currency.BTC); assertThat(btcBalance.getTotal()).isEqualTo("0.038777349225374"); assertThat(btcBalance.getCurrency()).isEqualTo(Currency.BTC); final Balance usdBalance = counterWallet.getBalance(Currency.USD); assertThat(usdBalance.getTotal()).isEqualTo("10"); assertThat(usdBalance.getCurrency()).isEqualTo(Currency.USD); final Wallet mainWallet = account.getWallet("main"); assertThat(mainWallet.getBalances()).hasSize(1); final Balance xrpBalance = mainWallet.getBalance(Currency.XRP); assertThat(xrpBalance.getTotal()).isEqualTo("861.401578"); assertThat(xrpBalance.getCurrency()).isEqualTo(Currency.XRP); } @Test public void adaptOrderBookTest() throws IOException { // Read in the JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/marketdata/example-order-book.json"); final CurrencyPair currencyPair = CurrencyPair.XRP_BTC; // Test data uses Bitstamp issued BTC final RippleMarketDataParams params = new RippleMarketDataParams(); params.setCounterCounterparty("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); // Use Jackson to parse it final ObjectMapper mapper = new ObjectMapper(); final RippleOrderBook rippleOrderBook = mapper.readValue(is, RippleOrderBook.class); // Convert to xchange object and check field values final OrderBook orderBook = RippleAdapters.adaptOrderBook(rippleOrderBook, params, currencyPair); assertThat(orderBook.getBids()).hasSize(10); assertThat(orderBook.getAsks()).hasSize(10); final LimitOrder lastBid = orderBook.getBids().get(9); assertThat(lastBid).isInstanceOf(RippleLimitOrder.class); assertThat(lastBid.getCurrencyPair()).isEqualTo(currencyPair); assertThat(((RippleLimitOrder) lastBid).getCounterCounterparty()) .isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(lastBid.getType()).isEqualTo(OrderType.BID); assertThat(lastBid.getId()).isEqualTo("1303704"); assertThat(lastBid.getOriginalAmount()).isEqualTo("66314.537782"); assertThat(lastBid.getLimitPrice()).isEqualTo("0.00003317721777288062"); final LimitOrder firstAsk = orderBook.getAsks().get(0); assertThat(firstAsk).isInstanceOf(RippleLimitOrder.class); assertThat(firstAsk.getCurrencyPair()).isEqualTo(currencyPair); assertThat(((RippleLimitOrder) firstAsk).getCounterCounterparty()) .isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(firstAsk.getType()).isEqualTo(OrderType.ASK); assertThat(firstAsk.getId()).isEqualTo("1011310"); assertThat(firstAsk.getOriginalAmount()).isEqualTo("35447.914936"); assertThat(firstAsk.getLimitPrice()).isEqualTo("0.00003380846624897726"); } @Test public void adaptOpenOrdersTest() throws JsonParseException, JsonMappingException, IOException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read in the JSON from the example resources final InputStream is = getClass() .getResourceAsStream("/org/knowm/xchange/ripple/dto/trade/example-account-orders.json"); final ObjectMapper mapper = new ObjectMapper(); final RippleAccountOrders response = mapper.readValue(is, RippleAccountOrders.class); // Convert to XChange orders final OpenOrders orders = RippleAdapters.adaptOpenOrders(response, roundingScale); assertThat(orders.getOpenOrders()).hasSize(12); final LimitOrder firstOrder = orders.getOpenOrders().get(0); assertThat(firstOrder).isInstanceOf(RippleLimitOrder.class); assertThat(firstOrder.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC); assertThat(((RippleLimitOrder) firstOrder).getCounterCounterparty()) .isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(firstOrder.getId()).isEqualTo("5"); assertThat(firstOrder.getLimitPrice()).isEqualTo("0.00003226"); assertThat(firstOrder.getTimestamp()).isNull(); assertThat(firstOrder.getOriginalAmount()).isEqualTo("1"); assertThat(firstOrder.getType()).isEqualTo(OrderType.BID); final LimitOrder secondOrder = orders.getOpenOrders().get(1); assertThat(secondOrder).isInstanceOf(RippleLimitOrder.class); assertThat(secondOrder.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC); assertThat(((RippleLimitOrder) secondOrder).getCounterCounterparty()) .isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(secondOrder.getId()).isEqualTo("7"); // Price = 15159.38551342023 / 123.123456 assertThat(secondOrder.getLimitPrice()) .isEqualTo("123.12345677999998635515884154518859509596611713043533"); assertThat(secondOrder.getTimestamp()).isNull(); assertThat(secondOrder.getOriginalAmount()).isEqualTo("123.123456"); assertThat(secondOrder.getType()).isEqualTo(OrderType.ASK); } @Override public BigDecimal getTransferFeeRate(final String address) throws IOException { final InputStream is = getClass() .getResourceAsStream( String.format( "/org/knowm/xchange/ripple/dto/account/example-account-settings-%s.json", address)); final ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(is, RippleAccountSettings.class).getSettings().getTransferFeeRate(); } @Test public void adaptTrade_BuyXRP_SellBTC() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-trade-buyXRP-sellBTC.json"); final ObjectMapper mapper = new ObjectMapper(); final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class); final RippleTradeHistoryParams params = new RippleTradeHistoryParams(); params.addPreferredCounterCurrency(Currency.BTC); final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("0000000000000000000000000000000000000000000000000000000000000000"); assertThat(trade.getOrderId()).isEqualTo("1010"); // Price = 0.000029309526038 * 0.998 assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("0.000029250906985924") .setScale(roundingScale, RoundingMode.HALF_UP) .stripTrailingZeros()); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2000-00-00T00:00:00.000Z")); assertThat(trade.getOriginalAmount()).isEqualTo("1"); assertThat(trade.getType()).isEqualTo(OrderType.BID); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEmpty(); assertThat(ripple.getBaseTransferFee()).isZero(); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.XRP); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); // Transfer fee = 0.000029309526038 * 0.002 assertThat(ripple.getCounterTransferFee()).isEqualTo("0.000000058619052076"); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); } @Test public void adaptTrade_SellBTC_BuyXRP() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-trade-buyXRP-sellBTC.json"); final ObjectMapper mapper = new ObjectMapper(); final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class); final RippleTradeHistoryParams params = new RippleTradeHistoryParams(); params.addPreferredBaseCurrency(Currency.BTC); final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.BTC_XRP); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("0000000000000000000000000000000000000000000000000000000000000000"); assertThat(trade.getOrderId()).isEqualTo("1010"); // Price = 1.0 / (0.000029309526038 * 0.998) assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("34186.97411609205306550363511634115030681332485583111528") .setScale(roundingScale, RoundingMode.HALF_UP)); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2000-00-00T00:00:00.000Z")); // Quantity = 0.000029309526038 * 0.998 assertThat(trade.getOriginalAmount()).isEqualTo("0.000029250906985924"); assertThat(trade.getType()).isEqualTo(OrderType.ASK); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); // Transfer fee = 0.000029309526038 * 0.002 assertThat(ripple.getBaseTransferFee()).isEqualTo("0.000000058619052076"); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEmpty(); assertThat(ripple.getCounterTransferFee()).isZero(); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.XRP); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); } @Test public void adaptTrade_SellXRP_BuyBTC() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-trade-sellXRP-buyBTC.json"); final ObjectMapper mapper = new ObjectMapper(); final IRippleTradeTransaction response = mapper.readValue(is, RippleOrderTransaction.class); final RippleTradeHistoryParams params = new RippleTradeHistoryParams(); params.setCurrencyPair(CurrencyPair.XRP_BTC); final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("1111111111111111111111111111111111111111111111111111111111111111"); assertThat(trade.getOrderId()).isEqualTo("1111"); assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("0.000028572057152") .setScale(roundingScale, RoundingMode.HALF_UP) .stripTrailingZeros()); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2011-11-11T11:11:11.111Z")); assertThat(trade.getOriginalAmount()).isEqualTo("1"); assertThat(trade.getType()).isEqualTo(OrderType.ASK); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEmpty(); assertThat(ripple.getBaseTransferFee()).isZero(); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.XRP); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); assertThat(ripple.getCounterTransferFee()).isZero(); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); // make sure that if the IRippleTradeTransaction is adapted again it returns the same values final UserTrade trade2 = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade2.getCurrencyPair()).isEqualTo(trade.getCurrencyPair()); assertThat(trade2.getFeeAmount()).isEqualTo(trade.getFeeAmount()); assertThat(trade2.getFeeCurrency()).isEqualTo(trade.getFeeCurrency()); assertThat(trade2.getId()).isEqualTo(trade.getId()); assertThat(trade2.getOrderId()).isEqualTo(trade.getOrderId()); assertThat(trade2.getPrice()).isEqualTo(trade.getPrice()); assertThat(trade2.getTimestamp()).isEqualTo(trade.getTimestamp()); assertThat(trade2.getOriginalAmount()).isEqualTo(trade.getOriginalAmount()); assertThat(trade2.getType()).isEqualTo(trade.getType()); } @Test public void adaptTrade_BuyBTC_SellXRP() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-trade-sellXRP-buyBTC.json"); final ObjectMapper mapper = new ObjectMapper(); final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class); final RippleTradeHistoryParams params = new RippleTradeHistoryParams(); params.addPreferredBaseCurrency(Currency.BTC); final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.BTC_XRP); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("1111111111111111111111111111111111111111111111111111111111111111"); assertThat(trade.getOrderId()).isEqualTo("1111"); // Price = 1.0 / 0.000028572057152 assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("34999.23000574012011552062010939099496310569328655387396") .setScale(roundingScale, RoundingMode.HALF_UP) .stripTrailingZeros()); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2011-11-11T11:11:11.111Z")); assertThat(trade.getOriginalAmount()).isEqualTo("0.000028572057152"); assertThat(trade.getType()).isEqualTo(OrderType.BID); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); assertThat(ripple.getBaseTransferFee()).isZero(); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEmpty(); assertThat(ripple.getCounterTransferFee()).isZero(); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.XRP); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); } @Test public void adaptTrade_BuyBTC_SellBTC() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-trade-buyBTC-sellBTC.json"); final ObjectMapper mapper = new ObjectMapper(); final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class); final TradeHistoryParams params = new TradeHistoryParams() {}; final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair().base).isEqualTo(Currency.BTC); assertThat(trade.getCurrencyPair().counter).isEqualTo(Currency.BTC); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("2222222222222222222222222222222222222222222222222222222222222222"); assertThat(trade.getOrderId()).isEqualTo("2222"); // Price = 0.501 * 0.998 / 0.50150835545121407952 assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("0.99698837430165008596385145696065600512973847422746") .setScale(roundingScale, RoundingMode.HALF_UP)); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2022-22-22T22:22:22.222Z")); assertThat(trade.getOriginalAmount()).isEqualTo("0.50150835545121407952"); assertThat(trade.getType()).isEqualTo(OrderType.BID); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); assertThat(ripple.getBaseTransferFee()).isZero(); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); // Transfer fee = 0.501 * 0.002 assertThat(ripple.getCounterTransferFee()).isEqualTo("0.001002"); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); } @Test public void adaptTrade_PaymentPassthrough() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-payment-passthrough.json"); final ObjectMapper mapper = new ObjectMapper(); final RipplePaymentTransaction response = mapper.readValue(is, RipplePaymentTransaction.class); final TradeHistoryParams params = new TradeHistoryParams() {}; final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair().base).isEqualTo(Currency.XRP); assertThat(trade.getCurrencyPair().counter).isEqualTo(Currency.BTC); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("GHRE072948B95345396B2D9A364363GDE521HRT67QQRGGRTHYTRUP0RRB631107"); assertThat(trade.getOrderId()).isEqualTo("9338"); // Price = 0.009941478580724 / (349.559725 - 0.012) assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("0.00002844097635229638527900589254299967193321026478") .setScale(roundingScale, RoundingMode.HALF_UP)); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2015-08-07T03:58:10.000Z")); assertThat(trade.getOriginalAmount()).isEqualTo("349.547725"); assertThat(trade.getType()).isEqualTo(OrderType.ASK); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEqualTo(""); assertThat(ripple.getBaseTransferFee()).isZero(); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.XRP); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); // Transfer fee = 0.501 * 0.002 assertThat(ripple.getCounterTransferFee()).isEqualTo("0"); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); } }
timmolter/XChange
xchange-ripple/src/test/java/org/knowm/xchange/ripple/RippleAdaptersTest.java
Java
mit
24,065
<?php namespace Oro\Bundle\EmailBundle\Tests\Unit\Entity; use Oro\Bundle\EmailBundle\Entity\EmailFolder; use Oro\Bundle\EmailBundle\Tests\Unit\ReflectionUtil; class EmailFolderTest extends \PHPUnit_Framework_TestCase { public function testIdGetter() { $entity = new EmailFolder(); ReflectionUtil::setId($entity, 1); $this->assertEquals(1, $entity->getId()); } public function testNameGetterAndSetter() { $entity = new EmailFolder(); $entity->setName('test'); $this->assertEquals('test', $entity->getName()); } public function testFullNameGetterAndSetter() { $entity = new EmailFolder(); $entity->setFullName('test'); $this->assertEquals('test', $entity->getFullName()); } public function testTypeGetterAndSetter() { $entity = new EmailFolder(); $entity->setType('test'); $this->assertEquals('test', $entity->getType()); } public function testOriginGetterAndSetter() { $origin = $this->getMock('Oro\Bundle\EmailBundle\Entity\EmailOrigin'); $entity = new EmailFolder(); $entity->setOrigin($origin); $this->assertTrue($origin === $entity->getOrigin()); } public function testEmailGetterAndSetter() { $email = $this->getMock('Oro\Bundle\EmailBundle\Entity\Email'); $entity = new EmailFolder(); $entity->addEmail($email); $emails = $entity->getEmails(); $this->assertInstanceOf('Doctrine\Common\Collections\ArrayCollection', $emails); $this->assertCount(1, $emails); $this->assertTrue($email === $emails[0]); } }
minhnguyen-balance/oro_platform
vendor/oro/platform/src/Oro/Bundle/EmailBundle/Tests/Unit/Entity/EmailFolderTest.php
PHP
mit
1,677
module Serverspec module Helper module Configuration def subject build_configurations super end # You can create a set of configurations provided to all specs in your spec_helper: # # RSpec.configure { |c| c.pre_command = "source ~/.zshrc" } # # Any configurations you provide with `let(:option_name)` in a spec will # automatically be merged on top of the configurations. # # @example # # describe 'Gem' do # let(:pre_command) { "source ~/.zshrc" } # # %w(pry awesome_print bundler).each do |p| # describe package(p) do # it { should be_installed.by('gem') } # end # end # end def build_configurations Serverspec::Configuration.defaults.keys.each do |c| value = self.respond_to?(c.to_sym) ? self.send(c) : RSpec.configuration.send(c) Serverspec::Configuration.send(:"#{c}=", value) end end end end end
netmarkjp/serverspec
lib/serverspec/helper/configuration.rb
Ruby
mit
1,048
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Batch.Models { using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for ComputeNodeFillType. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum ComputeNodeFillType { [EnumMember(Value = "Spread")] Spread, [EnumMember(Value = "Pack")] Pack } internal static class ComputeNodeFillTypeEnumExtension { internal static string ToSerializedValue(this ComputeNodeFillType? value) { return value == null ? null : ((ComputeNodeFillType)value).ToSerializedValue(); } internal static string ToSerializedValue(this ComputeNodeFillType value) { switch( value ) { case ComputeNodeFillType.Spread: return "Spread"; case ComputeNodeFillType.Pack: return "Pack"; } return null; } internal static ComputeNodeFillType? ParseComputeNodeFillType(this string value) { switch( value ) { case "Spread": return ComputeNodeFillType.Spread; case "Pack": return ComputeNodeFillType.Pack; } return null; } } }
yaakoviyun/azure-sdk-for-net
src/SDKs/Batch/Management/Management.Batch/Generated/Models/ComputeNodeFillType.cs
C#
mit
1,801
/** * @typedef {object} Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig * @since 3.0.0 * * @property {Phaser.GameObjects.DynamicBitmapText} parent - The Dynamic Bitmap Text object that owns this character being rendered. * @property {Phaser.Types.GameObjects.BitmapText.TintConfig} tint - The tint of the character being rendered. Always zero in Canvas. * @property {number} index - The index of the character being rendered. * @property {number} charCode - The character code of the character being rendered. * @property {number} x - The x position of the character being rendered. * @property {number} y - The y position of the character being rendered. * @property {number} scale - The scale of the character being rendered. * @property {number} rotation - The rotation of the character being rendered. * @property {any} data - Custom data stored with the character being rendered. */ /** * @callback Phaser.Types.GameObjects.BitmapText.DisplayCallback * * @param {Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} display - Settings of the character that is about to be rendered. * * @return {Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} Altered position, scale and rotation values for the character that is about to be rendered. */
mahill/phaser
src/gameobjects/bitmaptext/typedefs/DisplayCallbackConfig.js
JavaScript
mit
1,291
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ScintillaNET { /// <summary> /// Lexer property types. /// </summary> public enum PropertyType { /// <summary> /// A Boolean property. This is the default. /// </summary> Boolean = NativeMethods.SC_TYPE_BOOLEAN, /// <summary> /// An integer property. /// </summary> Integer = NativeMethods.SC_TYPE_INTEGER, /// <summary> /// A string property. /// </summary> String = NativeMethods.SC_TYPE_STRING } }
cqwang/ScintillaNET
src/ScintillaNET/PropertyType.cs
C#
mit
623
from __future__ import print_function import sys def func(): print('{0}.{1}'.format(*sys.version_info[:2])) print(repr(sys.argv[1:])) print('Hello World') return 0
Teino1978-Corp/pre-commit
testing/resources/python3_hooks_repo/python3_hook/main.py
Python
mit
183
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import '@angular/compiler'; import * as fs from 'fs'; import * as path from 'path'; const UTF8 = { encoding: 'utf-8' }; const PACKAGE = 'angular/packages/core/test/bundling/hello_world_r2'; describe('treeshaking with uglify', () => { let content: string; const contentPath = require.resolve(path.join(PACKAGE, 'bundle.debug.min.js')); beforeAll(() => { content = fs.readFileSync(contentPath, UTF8); }); it('should drop unused TypeScript helpers', () => { expect(content).not.toContain('__asyncGenerator'); }); it('should not contain rxjs from commonjs distro', () => { expect(content).not.toContain('commonjsGlobal'); expect(content).not.toContain('createCommonjsModule'); }); });
gkalpak/angular
packages/core/test/bundling/hello_world_r2/treeshaking_spec.ts
TypeScript
mit
923
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ var base64 = require('base64-js') var ieee754 = require('ieee754') var isArray = require('is-array') exports.Buffer = Buffer exports.SlowBuffer = Buffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation var kMaxLength = 0x3fffffff /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Note: * * - Implementation must support adding new properties to `Uint8Array` instances. * Firefox 4-29 lacked support, fixed in Firefox 30+. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will * get the Object implementation, which is slower but will work correctly. */ Buffer.TYPED_ARRAY_SUPPORT = (function () { try { var buf = new ArrayBuffer(0) var arr = new Uint8Array(buf) arr.foo = function () { return 42 } return 42 === arr.foo() && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } })() /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (subject, encoding, noZero) { if (!(this instanceof Buffer)) return new Buffer(subject, encoding, noZero) var type = typeof subject // Find the length var length if (type === 'number') length = subject > 0 ? subject >>> 0 : 0 else if (type === 'string') { if (encoding === 'base64') subject = base64clean(subject) length = Buffer.byteLength(subject, encoding) } else if (type === 'object' && subject !== null) { // assume object is array-like if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data length = +subject.length > 0 ? Math.floor(+subject.length) : 0 } else throw new TypeError('must start with number, buffer, array or string') if (this.length > kMaxLength) throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength.toString(16) + ' bytes') var buf if (Buffer.TYPED_ARRAY_SUPPORT) { // Preferred: Return an augmented `Uint8Array` instance for best performance buf = Buffer._augment(new Uint8Array(length)) } else { // Fallback: Return THIS instance of Buffer (created by `new`) buf = this buf.length = length buf._isBuffer = true } var i if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') { // Speed optimization -- use set if we're copying from a typed array buf._set(subject) } else if (isArrayish(subject)) { // Treat array-ish objects as a byte array if (Buffer.isBuffer(subject)) { for (i = 0; i < length; i++) buf[i] = subject.readUInt8(i) } else { for (i = 0; i < length; i++) buf[i] = ((subject[i] % 256) + 256) % 256 } } else if (type === 'string') { buf.write(subject, 0, encoding) } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) { for (i = 0; i < length; i++) { buf[i] = 0 } } return buf } Buffer.isBuffer = function (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) throw new TypeError('Arguments must be Buffers') var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} if (i !== len) { x = a[i] y = b[i] } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function (list, totalLength) { if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])') if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } var i if (totalLength === undefined) { totalLength = 0 for (i = 0; i < list.length; i++) { totalLength += list[i].length } } var buf = new Buffer(totalLength) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } Buffer.byteLength = function (str, encoding) { var ret str = str + '' switch (encoding || 'utf8') { case 'ascii': case 'binary': case 'raw': ret = str.length break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = str.length * 2 break case 'hex': ret = str.length >>> 1 break case 'utf8': case 'utf-8': ret = utf8ToBytes(str).length break case 'base64': ret = base64ToBytes(str).length break default: ret = str.length } return ret } // pre-set for values that may exist in the future Buffer.prototype.length = undefined Buffer.prototype.parent = undefined // toString(encoding, start=0, end=buffer.length) Buffer.prototype.toString = function (encoding, start, end) { var loweredCase = false start = start >>> 0 end = end === undefined || end === Infinity ? this.length : end >>> 0 if (!encoding) encoding = 'utf8' if (start < 0) start = 0 if (end > this.length) end = this.length if (end <= start) return '' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } Buffer.prototype.equals = function (b) { if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') return Buffer.compare(this, b) } // `get` will be removed in Node 0.13+ Buffer.prototype.get = function (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` will be removed in Node 0.13+ Buffer.prototype.set = function (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var byte = parseInt(string.substr(i * 2, 2), 16) if (isNaN(byte)) throw new Error('Invalid hex string') buf[offset + i] = byte } return i } function utf8Write (buf, string, offset, length) { var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) return charsWritten } function asciiWrite (buf, string, offset, length) { var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) return charsWritten } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) return charsWritten } function utf16leWrite (buf, string, offset, length) { var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length) return charsWritten } Buffer.prototype.write = function (string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length length = undefined } } else { // legacy var swap = encoding encoding = offset offset = length length = swap } offset = Number(offset) || 0 var remaining = this.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } encoding = String(encoding || 'utf8').toLowerCase() var ret switch (encoding) { case 'hex': ret = hexWrite(this, string, offset, length) break case 'utf8': case 'utf-8': ret = utf8Write(this, string, offset, length) break case 'ascii': ret = asciiWrite(this, string, offset, length) break case 'binary': ret = binaryWrite(this, string, offset, length) break case 'base64': ret = base64Write(this, string, offset, length) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = utf16leWrite(this, string, offset, length) break default: throw new TypeError('Unknown encoding: ' + encoding) } return ret } Buffer.prototype.toJSON = function () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { var res = '' var tmp = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return res + decodeUtf8Char(tmp) } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function binarySlice (buf, start, end) { return asciiSlice(buf, start, end) } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len; if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start if (Buffer.TYPED_ARRAY_SUPPORT) { return Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start var newBuf = new Buffer(sliceLen, undefined, true) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } return newBuf } } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUInt8 = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readInt8 = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') if (value > max || value < min) throw new TypeError('value is out of bounds') if (offset + ext > buf.length) throw new TypeError('index out of range') } Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = value return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) } else objectWriteUInt16(this, value, offset, true) return offset + 2 } Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = value } else objectWriteUInt16(this, value, offset, false) return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = value } else objectWriteUInt32(this, value, offset, true) return offset + 4 } Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = value } else objectWriteUInt32(this, value, offset, false) return offset + 4 } Buffer.prototype.writeInt8 = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = value return offset + 1 } Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) } else objectWriteUInt16(this, value, offset, true) return offset + 2 } Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = value } else objectWriteUInt16(this, value, offset, false) return offset + 2 } Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else objectWriteUInt32(this, value, offset, true) return offset + 4 } Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = value } else objectWriteUInt32(this, value, offset, false) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (value > max || value < min) throw new TypeError('value is out of bounds') if (offset + ext > buf.length) throw new TypeError('index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function (target, target_start, start, end) { var source = this if (!start) start = 0 if (!end && end !== 0) end = this.length if (!target_start) target_start = 0 // Copy 0 bytes; we're done if (end === start) return if (target.length === 0 || source.length === 0) return // Fatal error conditions if (end < start) throw new TypeError('sourceEnd < sourceStart') if (target_start < 0 || target_start >= target.length) throw new TypeError('targetStart out of bounds') if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds') if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - target_start < end - start) end = target.length - target_start + start var len = end - start if (len < 100 || !Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < len; i++) { target[i + target_start] = this[i + start] } } else { target._set(this.subarray(start, start + len), target_start) } } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (end < start) throw new TypeError('end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return if (start < 0 || start >= this.length) throw new TypeError('start out of bounds') if (end < 0 || end > this.length) throw new TypeError('end out of bounds') var i if (typeof value === 'number') { for (i = start; i < end; i++) { this[i] = value } } else { var bytes = utf8ToBytes(value.toString()) var len = bytes.length for (i = start; i < end; i++) { this[i] = bytes[i % len] } } return this } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function () { if (typeof Uint8Array !== 'undefined') { if (Buffer.TYPED_ARRAY_SUPPORT) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) { buf[i] = this[i] } return buf.buffer } } else { throw new TypeError('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function (arr) { arr._isBuffer = true // save reference to original Uint8Array get/set methods before overwriting arr._get = arr.get arr._set = arr.set // deprecated, will be removed in node 0.13+ arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.equals = BP.equals arr.compare = BP.compare arr.copy = BP.copy arr.slice = BP.slice arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } var INVALID_BASE64_RE = /[^+\/0-9A-z]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function isArrayish (subject) { return isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number' } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { var b = str.charCodeAt(i) if (b <= 0x7F) { byteArray.push(b) } else { var start = i if (b >= 0xD800 && b <= 0xDFFF) i++ var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') for (var j = 0; j < h.length; j++) { byteArray.push(parseInt(h[j], 16)) } } } return byteArray } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(str) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } },{"base64-js":2,"ieee754":3,"is-array":4}],2:[function(require,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS) return 62 // '+' if (code === SLASH) return 63 // '/' if (code < NUMBER) return -1 //no match if (code < NUMBER + 10) return code - NUMBER + 26 + 26 if (code < UPPER + 26) return code - UPPER if (code < LOWER + 26) return code - LOWER + 26 } function b64ToByteArray (b64) { var i, j, l, tmp, placeHolders, arr if (b64.length % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],3:[function(require,module,exports){ exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isLE ? (nBytes - 1) : 0, d = isLE ? -1 : 1, s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity); } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), i = isLE ? 0 : (nBytes - 1), d = isLE ? 1 : -1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; },{}],4:[function(require,module,exports){ /** * isArray */ var isArray = Array.isArray; /** * toString */ var str = Object.prototype.toString; /** * Whether or not the given `val` * is an array. * * example: * * isArray([]); * // > true * isArray(arguments); * // > false * isArray(''); * // > false * * @param {mixed} val * @return {bool} */ module.exports = isArray || function (val) { return !! val && '[object Array]' == str.call(val); }; },{}],5:[function(require,module,exports){ ndarray = require( 'ndarray' ); },{"ndarray":6}],6:[function(require,module,exports){ (function (Buffer){ var iota = require("iota-array") var hasTypedArrays = ((typeof Float64Array) !== "undefined") var hasBuffer = ((typeof Buffer) !== "undefined") function compare1st(a, b) { return a[0] - b[0] } function order() { var stride = this.stride var terms = new Array(stride.length) var i for(i=0; i<terms.length; ++i) { terms[i] = [Math.abs(stride[i]), i] } terms.sort(compare1st) var result = new Array(terms.length) for(i=0; i<result.length; ++i) { result[i] = terms[i][1] } return result } function compileConstructor(dtype, dimension) { var className = ["View", dimension, "d", dtype].join("") if(dimension < 0) { className = "View_Nil" + dtype } var useGetters = (dtype === "generic") if(dimension === -1) { //Special case for trivial arrays var code = "function "+className+"(a){this.data=a;};\ var proto="+className+".prototype;\ proto.dtype='"+dtype+"';\ proto.index=function(){return -1};\ proto.size=0;\ proto.dimension=-1;\ proto.shape=proto.stride=proto.order=[];\ proto.lo=proto.hi=proto.transpose=proto.step=\ function(){return new "+className+"(this.data);};\ proto.get=proto.set=function(){};\ proto.pick=function(){return null};\ return function construct_"+className+"(a){return new "+className+"(a);}" var procedure = new Function(code) return procedure() } else if(dimension === 0) { //Special case for 0d arrays var code = "function "+className+"(a,d) {\ this.data = a;\ this.offset = d\ };\ var proto="+className+".prototype;\ proto.dtype='"+dtype+"';\ proto.index=function(){return this.offset};\ proto.dimension=0;\ proto.size=1;\ proto.shape=\ proto.stride=\ proto.order=[];\ proto.lo=\ proto.hi=\ proto.transpose=\ proto.step=function "+className+"_copy() {\ return new "+className+"(this.data,this.offset)\ };\ proto.pick=function "+className+"_pick(){\ return TrivialArray(this.data);\ };\ proto.valueOf=proto.get=function "+className+"_get(){\ return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+ "};\ proto.set=function "+className+"_set(v){\ return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\ };\ return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}" var procedure = new Function("TrivialArray", code) return procedure(CACHED_CONSTRUCTORS[dtype][0]) } var code = ["'use strict'"] //Create constructor for view var indices = iota(dimension) var args = indices.map(function(i) { return "i"+i }) var index_str = "this.offset+" + indices.map(function(i) { return "this.stride[" + i + "]*i" + i }).join("+") var shapeArg = indices.map(function(i) { return "b"+i }).join(",") var strideArg = indices.map(function(i) { return "c"+i }).join(",") code.push( "function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a", "this.shape=[" + shapeArg + "]", "this.stride=[" + strideArg + "]", "this.offset=d|0}", "var proto="+className+".prototype", "proto.dtype='"+dtype+"'", "proto.dimension="+dimension) //view.size: code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\ return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"), "}})") //view.order: if(dimension === 1) { code.push("proto.order=[0]") } else { code.push("Object.defineProperty(proto,'order',{get:") if(dimension < 4) { code.push("function "+className+"_order(){") if(dimension === 2) { code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})") } else if(dimension === 3) { code.push( "var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ if(s0>s1){\ if(s1>s2){\ return [2,1,0];\ }else if(s0>s2){\ return [1,2,0];\ }else{\ return [1,0,2];\ }\ }else if(s0>s2){\ return [2,0,1];\ }else if(s2>s1){\ return [0,1,2];\ }else{\ return [0,2,1];\ }}})") } } else { code.push("ORDER})") } } //view.set(i0, ..., v): code.push( "proto.set=function "+className+"_set("+args.join(",")+",v){") if(useGetters) { code.push("return this.data.set("+index_str+",v)}") } else { code.push("return this.data["+index_str+"]=v}") } //view.get(i0, ...): code.push("proto.get=function "+className+"_get("+args.join(",")+"){") if(useGetters) { code.push("return this.data.get("+index_str+")}") } else { code.push("return this.data["+index_str+"]}") } //view.index: code.push( "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") //view.hi(): code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+ indices.map(function(i) { return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("") }).join(",")+","+ indices.map(function(i) { return "this.stride["+i + "]" }).join(",")+",this.offset)}") //view.lo(): var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }) var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" }) code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(",")) for(var i=0; i<dimension; ++i) { code.push( "if(typeof i"+i+"==='number'&&i"+i+">=0){\ d=i"+i+"|0;\ b+=c"+i+"*d;\ a"+i+"-=d}") } code.push("return new "+className+"(this.data,"+ indices.map(function(i) { return "a"+i }).join(",")+","+ indices.map(function(i) { return "c"+i }).join(",")+",b)}") //view.step(): code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }).join(",")+","+ indices.map(function(i) { return "b"+i+"=this.stride["+i+"]" }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") for(var i=0; i<dimension; ++i) { code.push( "if(typeof i"+i+"==='number'){\ d=i"+i+"|0;\ if(d<0){\ c+=b"+i+"*(a"+i+"-1);\ a"+i+"=ceil(-a"+i+"/d)\ }else{\ a"+i+"=ceil(a"+i+"/d)\ }\ b"+i+"*=d\ }") } code.push("return new "+className+"(this.data,"+ indices.map(function(i) { return "a" + i }).join(",")+","+ indices.map(function(i) { return "b" + i }).join(",")+",c)}") //view.transpose(): var tShape = new Array(dimension) var tStride = new Array(dimension) for(var i=0; i<dimension; ++i) { tShape[i] = "a[i"+i+"]" tStride[i] = "b[i"+i+"]" } code.push("proto.transpose=function "+className+"_transpose("+args+"){"+ args.map(function(n,idx) { return n + "=(" + n + "===undefined?" + idx + ":" + n + "|0)"}).join(";"), "var a=this.shape,b=this.stride;return new "+className+"(this.data,"+tShape.join(",")+","+tStride.join(",")+",this.offset)}") //view.pick(): code.push("proto.pick=function "+className+"_pick("+args+"){var a=[],b=[],c=this.offset") for(var i=0; i<dimension; ++i) { code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") } code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") //Add return statement code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ indices.map(function(i) { return "shape["+i+"]" }).join(",")+","+ indices.map(function(i) { return "stride["+i+"]" }).join(",")+",offset)}") //Compile procedure var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) return procedure(CACHED_CONSTRUCTORS[dtype], order) } function arrayDType(data) { if(hasBuffer) { if(Buffer.isBuffer(data)) { return "buffer" } } if(hasTypedArrays) { switch(Object.prototype.toString.call(data)) { case "[object Float64Array]": return "float64" case "[object Float32Array]": return "float32" case "[object Int8Array]": return "int8" case "[object Int16Array]": return "int16" case "[object Int32Array]": return "int32" case "[object Uint8Array]": return "uint8" case "[object Uint16Array]": return "uint16" case "[object Uint32Array]": return "uint32" case "[object Uint8ClampedArray]": return "uint8_clamped" } } if(Array.isArray(data)) { return "array" } return "generic" } var CACHED_CONSTRUCTORS = { "float32":[], "float64":[], "int8":[], "int16":[], "int32":[], "uint8":[], "uint16":[], "uint32":[], "array":[], "uint8_clamped":[], "buffer":[], "generic":[] } ;(function() { for(var id in CACHED_CONSTRUCTORS) { CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) } }); function wrappedNDArrayCtor(data, shape, stride, offset) { if(data === undefined) { var ctor = CACHED_CONSTRUCTORS.array[0] return ctor([]) } else if(typeof data === "number") { data = [data] } if(shape === undefined) { shape = [ data.length ] } var d = shape.length if(stride === undefined) { stride = new Array(d) for(var i=d-1, sz=1; i>=0; --i) { stride[i] = sz sz *= shape[i] } } if(offset === undefined) { offset = 0 for(var i=0; i<d; ++i) { if(stride[i] < 0) { offset -= (shape[i]-1)*stride[i] } } } var dtype = arrayDType(data) var ctor_list = CACHED_CONSTRUCTORS[dtype] while(ctor_list.length <= d+1) { ctor_list.push(compileConstructor(dtype, ctor_list.length-1)) } var ctor = ctor_list[d+1] return ctor(data, shape, stride, offset) } module.exports = wrappedNDArrayCtor }).call(this,require("buffer").Buffer) },{"buffer":1,"iota-array":7}],7:[function(require,module,exports){ "use strict" function iota(n) { var result = new Array(n) for(var i=0; i<n; ++i) { result[i] = i } return result } module.exports = iota },{}]},{},[5]);
NeoVand/networks3d
js/vendor/ndarray.js
JavaScript
mit
45,269
package com.aspose.cells.model; public class SideWall { private Link link = null; public Link getLink() { return link; } public void setLink(Link link) { this.link = link; } }
aspose-cells/Aspose.Cells-for-Cloud
SDKs/Aspose.Cells-Cloud-SDK-for-Java/src/main/java/com/aspose/cells/model/SideWall.java
Java
mit
210
class Admin::BaseController < ApplicationController end
HakubJozak/barbecue
test/dummy/app/controllers/admin/base_controller.rb
Ruby
mit
56
package com.punchthrough.bean.sdk.internal.upload.sketch; public enum SketchUploadState { INACTIVE, RESETTING_REMOTE, SENDING_START_COMMAND, SENDING_BLOCKS, FINISHED }
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/sketch/SketchUploadState.java
Java
mit
173
define('lodash/internal/createWrapper', ['exports', 'lodash/internal/baseSetData', 'lodash/internal/createBindWrapper', 'lodash/internal/createHybridWrapper', 'lodash/internal/createPartialWrapper', 'lodash/internal/getData', 'lodash/internal/mergeData', 'lodash/internal/setData'], function (exports, _lodashInternalBaseSetData, _lodashInternalCreateBindWrapper, _lodashInternalCreateHybridWrapper, _lodashInternalCreatePartialWrapper, _lodashInternalGetData, _lodashInternalMergeData, _lodashInternalSetData) { 'use strict'; /** Used to compose bitmasks for wrapper metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of flags. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); partials = holders = undefined; } length -= holders ? holders.length : 0; if (bitmask & PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : (0, _lodashInternalGetData['default'])(func), newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; if (data) { (0, _lodashInternalMergeData['default'])(newData, data); bitmask = newData[1]; arity = newData[9]; } newData[9] = arity == null ? isBindKey ? 0 : func.length : nativeMax(arity - length, 0) || 0; if (bitmask == BIND_FLAG) { var result = (0, _lodashInternalCreateBindWrapper['default'])(newData[0], newData[2]); } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) { result = _lodashInternalCreatePartialWrapper['default'].apply(undefined, newData); } else { result = _lodashInternalCreateHybridWrapper['default'].apply(undefined, newData); } var setter = data ? _lodashInternalBaseSetData['default'] : _lodashInternalSetData['default']; return setter(result, newData); } exports['default'] = createWrapper; });
hoka-plus/p-01-web
tmp/babel-output_path-hOv4KMmE.tmp/lodash/internal/createWrapper.js
JavaScript
mit
3,598
// // JDFAppDelegate.h // JDFPeekaboo // // Created by CocoaPods on 02/01/2015. // Copyright (c) 2014 Joe Fryer. All rights reserved. // #import <UIKit/UIKit.h> @interface JDFAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
justinyaoqi/JDFPeekaboo
Example/JDFPeekaboo/JDFAppDelegate.h
C
mit
286
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Phaser Source: src/plugins/weapon/WeaponPlugin.js</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/default.css"> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.cerulean.css"> </head> <body> <div class="container-fluid"> <div class="navbar navbar-fixed-top navbar-inverse"> <div style="position: absolute; width: 143px; height: 31px; right: 10px; top: 10px; z-index: 1050"><a href="http://phaser.io"><img src="img/phaser.png" border="0" /></a></div> <div class="navbar-inner"> <a class="brand" href="index.html">Phaser API</a> <ul class="nav"> <li class="dropdown"> <a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="Phaser.html">Phaser</a> </li> <li class="class-depth-0"> <a href="Phaser.KeyCode.html">KeyCode</a> </li> <li class="class-depth-0"> <a href="PIXI.html">PIXI</a> </li> </ul> </li> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"> <a href="Phaser.Animation.html">Animation</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationManager.html">AnimationManager</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationParser.html">AnimationParser</a> </li> <li class="class-depth-1"> <a href="Phaser.ArraySet.html">ArraySet</a> </li> <li class="class-depth-1"> <a href="Phaser.ArrayUtils.html">ArrayUtils</a> </li> <li class="class-depth-1"> <a href="Phaser.AudioSprite.html">AudioSprite</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapData.html">BitmapData</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapText.html">BitmapText</a> </li> <li class="class-depth-1"> <a href="Phaser.Bullet.html">Bullet</a> </li> <li class="class-depth-1"> <a href="Phaser.Button.html">Button</a> </li> <li class="class-depth-1"> <a href="Phaser.Cache.html">Cache</a> </li> <li class="class-depth-1"> <a href="Phaser.Camera.html">Camera</a> </li> <li class="class-depth-1"> <a href="Phaser.Canvas.html">Canvas</a> </li> <li class="class-depth-1"> <a href="Phaser.Circle.html">Circle</a> </li> <li class="class-depth-1"> <a href="Phaser.Color.html">Color</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Angle.html">Angle</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Animation.html">Animation</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.AutoCull.html">AutoCull</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Bounds.html">Bounds</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.BringToTop.html">BringToTop</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Core.html">Core</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Crop.html">Crop</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Delta.html">Delta</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Destroy.html">Destroy</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.FixedToCamera.html">FixedToCamera</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Health.html">Health</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InCamera.html">InCamera</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InputEnabled.html">InputEnabled</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InWorld.html">InWorld</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.LifeSpan.html">LifeSpan</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.LoadTexture.html">LoadTexture</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Overlap.html">Overlap</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.PhysicsBody.html">PhysicsBody</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Reset.html">Reset</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.ScaleMinMax.html">ScaleMinMax</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Smoothed.html">Smoothed</a> </li> <li class="class-depth-1"> <a href="Phaser.Create.html">Create</a> </li> <li class="class-depth-1"> <a href="Phaser.Creature.html">Creature</a> </li> <li class="class-depth-1"> <a href="Phaser.Device.html">Device</a> </li> <li class="class-depth-1"> <a href="Phaser.DeviceButton.html">DeviceButton</a> </li> <li class="class-depth-1"> <a href="Phaser.DOM.html">DOM</a> </li> <li class="class-depth-1"> <a href="Phaser.Easing.html">Easing</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Back.html">Back</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Bounce.html">Bounce</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Circular.html">Circular</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Cubic.html">Cubic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Elastic.html">Elastic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Exponential.html">Exponential</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Linear.html">Linear</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quadratic.html">Quadratic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quartic.html">Quartic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quintic.html">Quintic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Sinusoidal.html">Sinusoidal</a> </li> <li class="class-depth-1"> <a href="Phaser.Ellipse.html">Ellipse</a> </li> <li class="class-depth-1"> <a href="Phaser.Events.html">Events</a> </li> <li class="class-depth-1"> <a href="Phaser.Filter.html">Filter</a> </li> <li class="class-depth-1"> <a href="Phaser.FlexGrid.html">FlexGrid</a> </li> <li class="class-depth-1"> <a href="Phaser.FlexLayer.html">FlexLayer</a> </li> <li class="class-depth-1"> <a href="Phaser.Frame.html">Frame</a> </li> <li class="class-depth-1"> <a href="Phaser.FrameData.html">FrameData</a> </li> <li class="class-depth-1"> <a href="Phaser.Game.html">Game</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectCreator.html">GameObjectCreator</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectFactory.html">GameObjectFactory</a> </li> <li class="class-depth-1"> <a href="Phaser.Gamepad.html">Gamepad</a> </li> <li class="class-depth-1"> <a href="Phaser.Graphics.html">Graphics</a> </li> <li class="class-depth-1"> <a href="Phaser.Group.html">Group</a> </li> <li class="class-depth-1"> <a href="Phaser.Image.html">Image</a> </li> <li class="class-depth-1"> <a href="Phaser.ImageCollection.html">ImageCollection</a> </li> <li class="class-depth-1"> <a href="Phaser.Input.html">Input</a> </li> <li class="class-depth-1"> <a href="Phaser.InputHandler.html">InputHandler</a> </li> <li class="class-depth-1"> <a href="Phaser.Key.html">Key</a> </li> <li class="class-depth-1"> <a href="Phaser.Keyboard.html">Keyboard</a> </li> <li class="class-depth-1"> <a href="Phaser.Line.html">Line</a> </li> <li class="class-depth-1"> <a href="Phaser.LinkedList.html">LinkedList</a> </li> <li class="class-depth-1"> <a href="Phaser.Loader.html">Loader</a> </li> <li class="class-depth-1"> <a href="Phaser.LoaderParser.html">LoaderParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Math.html">Math</a> </li> <li class="class-depth-1"> <a href="Phaser.Matrix.html">Matrix</a> </li> <li class="class-depth-1"> <a href="Phaser.Mouse.html">Mouse</a> </li> <li class="class-depth-1"> <a href="Phaser.MSPointer.html">MSPointer</a> </li> <li class="class-depth-1"> <a href="Phaser.Net.html">Net</a> </li> <li class="class-depth-1"> <a href="Phaser.Particle.html">Particle</a> </li> <li class="class-depth-1"> <a href="Phaser.Particles.html">Particles</a> </li> <li class="class-depth-2"> <a href="Phaser.Particles.Arcade.html">Arcade</a> </li> <li class="class-depth-3"> <a href="Phaser.Particles.Arcade.Emitter.html">Emitter</a> </li> <li class="class-depth-1"> <a href="Phaser.Physics.html">Physics</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Arcade.html">Arcade</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Arcade.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Arcade.TilemapCollision.html">TilemapCollision</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Ninja.html">Ninja</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.AABB.html">AABB</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Circle.html">Circle</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Tile.html">Tile</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.P2.html">P2</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.BodyDebug.html">BodyDebug</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.DistanceConstraint.html">DistanceConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.FixtureList.html">FixtureList</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.GearConstraint.html">GearConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.InversePointProxy.html">InversePointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.LockConstraint.html">LockConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Material.html">Material</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PointProxy.html">PointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PrismaticConstraint.html">PrismaticConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.RevoluteConstraint.html">RevoluteConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.RotationalSpring.html">RotationalSpring</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Spring.html">Spring</a> </li> <li class="class-depth-1"> <a href="Phaser.Plugin.html">Plugin</a> </li> <li class="class-depth-1"> <a href="Phaser.PluginManager.html">PluginManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Point.html">Point</a> </li> <li class="class-depth-1"> <a href="Phaser.Pointer.html">Pointer</a> </li> <li class="class-depth-1"> <a href="Phaser.PointerMode.html">PointerMode</a> </li> <li class="class-depth-1"> <a href="Phaser.Polygon.html">Polygon</a> </li> <li class="class-depth-1"> <a href="Phaser.QuadTree.html">QuadTree</a> </li> <li class="class-depth-1"> <a href="Phaser.RandomDataGenerator.html">RandomDataGenerator</a> </li> <li class="class-depth-1"> <a href="Phaser.Rectangle.html">Rectangle</a> </li> <li class="class-depth-1"> <a href="Phaser.RenderTexture.html">RenderTexture</a> </li> <li class="class-depth-1"> <a href="Phaser.RequestAnimationFrame.html">RequestAnimationFrame</a> </li> <li class="class-depth-1"> <a href="Phaser.RetroFont.html">RetroFont</a> </li> <li class="class-depth-1"> <a href="Phaser.Rope.html">Rope</a> </li> <li class="class-depth-1"> <a href="Phaser.RoundedRectangle.html">RoundedRectangle</a> </li> <li class="class-depth-1"> <a href="Phaser.ScaleManager.html">ScaleManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Signal.html">Signal</a> </li> <li class="class-depth-1"> <a href="Phaser.SignalBinding.html">SignalBinding</a> </li> <li class="class-depth-1"> <a href="Phaser.SinglePad.html">SinglePad</a> </li> <li class="class-depth-1"> <a href="Phaser.Sound.html">Sound</a> </li> <li class="class-depth-1"> <a href="Phaser.SoundManager.html">SoundManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Sprite.html">Sprite</a> </li> <li class="class-depth-1"> <a href="Phaser.SpriteBatch.html">SpriteBatch</a> </li> <li class="class-depth-1"> <a href="Phaser.Stage.html">Stage</a> </li> <li class="class-depth-1"> <a href="Phaser.State.html">State</a> </li> <li class="class-depth-1"> <a href="Phaser.StateManager.html">StateManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Text.html">Text</a> </li> <li class="class-depth-1"> <a href="Phaser.Tile.html">Tile</a> </li> <li class="class-depth-1"> <a href="Phaser.Tilemap.html">Tilemap</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapLayer.html">TilemapLayer</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapParser.html">TilemapParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Tileset.html">Tileset</a> </li> <li class="class-depth-1"> <a href="Phaser.TileSprite.html">TileSprite</a> </li> <li class="class-depth-1"> <a href="Phaser.Time.html">Time</a> </li> <li class="class-depth-1"> <a href="Phaser.Timer.html">Timer</a> </li> <li class="class-depth-1"> <a href="Phaser.TimerEvent.html">TimerEvent</a> </li> <li class="class-depth-1"> <a href="Phaser.Touch.html">Touch</a> </li> <li class="class-depth-1"> <a href="Phaser.Tween.html">Tween</a> </li> <li class="class-depth-1"> <a href="Phaser.TweenData.html">TweenData</a> </li> <li class="class-depth-1"> <a href="Phaser.TweenManager.html">TweenManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Utils.html">Utils</a> </li> <li class="class-depth-2"> <a href="Phaser.Utils.Debug.html">Debug</a> </li> <li class="class-depth-1"> <a href="Phaser.Video.html">Video</a> </li> <li class="class-depth-1"> <a href="Phaser.Weapon.html">Weapon</a> </li> <li class="class-depth-1"> <a href="Phaser.World.html">World</a> </li> <li class="class-depth-1"> <a href="PIXI.AbstractFilter.html">AbstractFilter</a> </li> <li class="class-depth-1"> <a href="PIXI.BaseTexture.html">BaseTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasBuffer.html">CanvasBuffer</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasGraphics.html">CanvasGraphics</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasMaskManager.html">CanvasMaskManager</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasPool.html">CanvasPool</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasRenderer.html">CanvasRenderer</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasTinter.html">CanvasTinter</a> </li> <li class="class-depth-1"> <a href="PIXI.ComplexPrimitiveShader.html">ComplexPrimitiveShader</a> </li> <li class="class-depth-1"> <a href="PIXI.DisplayObjectContainer.html">DisplayObjectContainer</a> </li> <li class="class-depth-1"> <a href="PIXI.EarCut.html">EarCut</a> </li> <li class="class-depth-1"> <a href="PIXI.Event.html">Event</a> </li> <li class="class-depth-1"> <a href="PIXI.EventTarget.html">EventTarget</a> </li> <li class="class-depth-1"> <a href="PIXI.FilterTexture.html">FilterTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.Graphics.html">Graphics</a> </li> <li class="class-depth-1"> <a href="PIXI.GraphicsData.html">GraphicsData</a> </li> <li class="class-depth-1"> <a href="PIXI.PIXI.html">PIXI</a> </li> <li class="class-depth-2"> <a href="PIXI.PIXI.DisplayObject.html">DisplayObject</a> </li> <li class="class-depth-1"> <a href="PIXI.PixiFastShader.html">PixiFastShader</a> </li> <li class="class-depth-1"> <a href="PIXI.PixiShader.html">PixiShader</a> </li> <li class="class-depth-1"> <a href="PIXI.PolyK.html">PolyK</a> </li> <li class="class-depth-1"> <a href="PIXI.PrimitiveShader.html">PrimitiveShader</a> </li> <li class="class-depth-1"> <a href="PIXI.RenderTexture.html">RenderTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.Rope.html">Rope</a> </li> <li class="class-depth-1"> <a href="PIXI.Sprite.html">Sprite</a> </li> <li class="class-depth-1"> <a href="PIXI.SpriteBatch.html">SpriteBatch</a> </li> <li class="class-depth-1"> <a href="PIXI.Strip.html">Strip</a> </li> <li class="class-depth-1"> <a href="PIXI.StripShader.html">StripShader</a> </li> <li class="class-depth-1"> <a href="PIXI.Texture.html">Texture</a> </li> <li class="class-depth-1"> <a href="PIXI.TilingSprite.html">TilingSprite</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLBlendModeManager.html">WebGLBlendModeManager</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLFastSpriteBatch.html">WebGLFastSpriteBatch</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLFilterManager.html">WebGLFilterManager</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLRenderer.html">WebGLRenderer</a> </li> </ul> </li> <li class="dropdown"> <a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="global.html#ANGLE_DOWN">ANGLE_DOWN</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_LEFT">ANGLE_LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_NORTH_EAST">ANGLE_NORTH_EAST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_NORTH_WEST">ANGLE_NORTH_WEST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_RIGHT">ANGLE_RIGHT</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_SOUTH_EAST">ANGLE_SOUTH_EAST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_SOUTH_WEST">ANGLE_SOUTH_WEST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_UP">ANGLE_UP</a> </li> <li class="class-depth-0"> <a href="global.html#AUTO">AUTO</a> </li> <li class="class-depth-0"> <a href="global.html#BITMAPDATA">BITMAPDATA</a> </li> <li class="class-depth-0"> <a href="global.html#BITMAPTEXT">BITMAPTEXT</a> </li> <li class="class-depth-0"> <a href="global.html#blendModes">blendModes</a> </li> <li class="class-depth-0"> <a href="global.html#BOTTOM_CENTER">BOTTOM_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#BOTTOM_LEFT">BOTTOM_LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#BOTTOM_RIGHT">BOTTOM_RIGHT</a> </li> <li class="class-depth-0"> <a href="global.html#BUTTON">BUTTON</a> </li> <li class="class-depth-0"> <a href="global.html#CANVAS">CANVAS</a> </li> <li class="class-depth-0"> <a href="global.html#CANVAS_FILTER">CANVAS_FILTER</a> </li> <li class="class-depth-0"> <a href="global.html#CENTER">CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#CIRCLE">CIRCLE</a> </li> <li class="class-depth-0"> <a href="global.html#CREATURE">CREATURE</a> </li> <li class="class-depth-0"> <a href="global.html#displayList">displayList</a> </li> <li class="class-depth-0"> <a href="global.html#DOWN">DOWN</a> </li> <li class="class-depth-0"> <a href="global.html#ELLIPSE">ELLIPSE</a> </li> <li class="class-depth-0"> <a href="global.html#EMITTER">EMITTER</a> </li> <li class="class-depth-0"> <a href="global.html#GAMES">GAMES</a> </li> <li class="class-depth-0"> <a href="global.html#GRAPHICS">GRAPHICS</a> </li> <li class="class-depth-0"> <a href="global.html#GROUP">GROUP</a> </li> <li class="class-depth-0"> <a href="global.html#HEADLESS">HEADLESS</a> </li> <li class="class-depth-0"> <a href="global.html#HORIZONTAL">HORIZONTAL</a> </li> <li class="class-depth-0"> <a href="global.html#IMAGE">IMAGE</a> </li> <li class="class-depth-0"> <a href="global.html#intersectsRectangle">intersectsRectangle</a> </li> <li class="class-depth-0"> <a href="global.html#LANDSCAPE">LANDSCAPE</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT">LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT_BOTTOM">LEFT_BOTTOM</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT_CENTER">LEFT_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT_TOP">LEFT_TOP</a> </li> <li class="class-depth-0"> <a href="global.html#LINE">LINE</a> </li> <li class="class-depth-0"> <a href="global.html#MATRIX">MATRIX</a> </li> <li class="class-depth-0"> <a href="global.html#NONE">NONE</a> </li> <li class="class-depth-0"> <a href="global.html#PENDING_ATLAS">PENDING_ATLAS</a> </li> <li class="class-depth-0"> <a href="global.html#POINT">POINT</a> </li> <li class="class-depth-0"> <a href="global.html#POINTER">POINTER</a> </li> <li class="class-depth-0"> <a href="global.html#POLYGON">POLYGON</a> </li> <li class="class-depth-0"> <a href="global.html#PORTRAIT">PORTRAIT</a> </li> <li class="class-depth-0"> <a href="global.html#RECTANGLE">RECTANGLE</a> </li> <li class="class-depth-0"> <a href="global.html#RENDERTEXTURE">RENDERTEXTURE</a> </li> <li class="class-depth-0"> <a href="global.html#RETROFONT">RETROFONT</a> </li> <li class="class-depth-0"> <a href="global.html#RIGHT">RIGHT</a> </li> <li class="class-depth-0"> <a href="global.html#RIGHT_BOTTOM">RIGHT_BOTTOM</a> </li> <li class="class-depth-0"> <a href="global.html#RIGHT_CENTER">RIGHT_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#RIGHT_TOP">RIGHT_TOP</a> </li> <li class="class-depth-0"> <a href="global.html#ROPE">ROPE</a> </li> <li class="class-depth-0"> <a href="global.html#ROUNDEDRECTANGLE">ROUNDEDRECTANGLE</a> </li> <li class="class-depth-0"> <a href="global.html#scaleModes">scaleModes</a> </li> <li class="class-depth-0"> <a href="global.html#SPRITE">SPRITE</a> </li> <li class="class-depth-0"> <a href="global.html#SPRITEBATCH">SPRITEBATCH</a> </li> <li class="class-depth-0"> <a href="global.html#TEXT">TEXT</a> </li> <li class="class-depth-0"> <a href="global.html#TILEMAP">TILEMAP</a> </li> <li class="class-depth-0"> <a href="global.html#TILEMAPLAYER">TILEMAPLAYER</a> </li> <li class="class-depth-0"> <a href="global.html#TILESPRITE">TILESPRITE</a> </li> <li class="class-depth-0"> <a href="global.html#TOP_CENTER">TOP_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#TOP_LEFT">TOP_LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#TOP_RIGHT">TOP_RIGHT</a> </li> <li class="class-depth-0"> <a href="global.html#UP">UP</a> </li> <li class="class-depth-0"> <a href="global.html#VERSION">VERSION</a> </li> <li class="class-depth-0"> <a href="global.html#VERTICAL">VERTICAL</a> </li> <li class="class-depth-0"> <a href="global.html#VIDEO">VIDEO</a> </li> <li class="class-depth-0"> <a href="global.html#WEBGL">WEBGL</a> </li> <li class="class-depth-0"> <a href="global.html#WEBGL_FILTER">WEBGL_FILTER</a> </li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Core<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Game.html">Game</a></li> <li class="class-depth-1"><a href="Phaser.Group.html">Group</a></li> <li class="class-depth-1"><a href="Phaser.World.html">World</a></li> <li class="class-depth-1"><a href="Phaser.Loader.html">Loader</a></li> <li class="class-depth-1"><a href="Phaser.Cache.html">Cache</a></li> <li class="class-depth-1"><a href="Phaser.Time.html">Time</a></li> <li class="class-depth-1"><a href="Phaser.Camera.html">Camera</a></li> <li class="class-depth-1"><a href="Phaser.StateManager.html">State Manager</a></li> <li class="class-depth-1"><a href="Phaser.TweenManager.html">Tween Manager</a></li> <li class="class-depth-1"><a href="Phaser.SoundManager.html">Sound Manager</a></li> <li class="class-depth-1"><a href="Phaser.Input.html">Input Manager</a></li> <li class="class-depth-1"><a href="Phaser.ScaleManager.html">Scale Manager</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Game Objects<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.GameObjectFactory.html">Factory (game.add)</a></li> <li class="class-depth-1"><a href="Phaser.GameObjectCreator.html">Creator (game.make)</a></li> <li class="class-depth-1"><a href="Phaser.Sprite.html">Sprite</a></li> <li class="class-depth-1"><a href="Phaser.Image.html">Image</a></li> <li class="class-depth-1"><a href="Phaser.Sound.html">Sound</a></li> <li class="class-depth-1"><a href="Phaser.Video.html">Video</a></li> <li class="class-depth-1"><a href="Phaser.Particles.Arcade.Emitter.html">Particle Emitter</a></li> <li class="class-depth-1"><a href="Phaser.Particle.html">Particle</a></li> <li class="class-depth-1"><a href="Phaser.Text.html">Text</a></li> <li class="class-depth-1"><a href="Phaser.Tween.html">Tween</a></li> <li class="class-depth-1"><a href="Phaser.BitmapText.html">BitmapText</a></li> <li class="class-depth-1"><a href="Phaser.Tilemap.html">Tilemap</a></li> <li class="class-depth-1"><a href="Phaser.BitmapData.html">BitmapData</a></li> <li class="class-depth-1"><a href="Phaser.RetroFont.html">RetroFont</a></li> <li class="class-depth-1"><a href="Phaser.Button.html">Button</a></li> <li class="class-depth-1"><a href="Phaser.Animation.html">Animation</a></li> <li class="class-depth-1"><a href="Phaser.Graphics.html">Graphics</a></li> <li class="class-depth-1"><a href="Phaser.RenderTexture.html">RenderTexture</a></li> <li class="class-depth-1"><a href="Phaser.TileSprite.html">TileSprite</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Geometry<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Circle.html">Circle</a></li> <li class="class-depth-1"><a href="Phaser.Ellipse.html">Ellipse</a></li> <li class="class-depth-1"><a href="Phaser.Line.html">Line</a></li> <li class="class-depth-1"><a href="Phaser.Matrix.html">Matrix</a></li> <li class="class-depth-1"><a href="Phaser.Point.html">Point</a></li> <li class="class-depth-1"><a href="Phaser.Polygon.html">Polygon</a></li> <li class="class-depth-1"><a href="Phaser.Rectangle.html">Rectangle</a></li> <li class="class-depth-1"><a href="Phaser.RoundedRectangle.html">Rounded Rectangle</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Physics<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Physics.Arcade.html">Arcade Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.Arcade.Body.html">Body</a></li> <li class="class-depth-2"><a href="Phaser.Weapon.html">Weapon</a></li> <li class="class-depth-1"><a href="Phaser.Physics.P2.html">P2 Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.Body.html">Body</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.Spring.html">Spring</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a></li> <li class="class-depth-1"><a href="Phaser.Physics.Ninja.html">Ninja Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.Body.html">Body</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Input<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.InputHandler.html">Input Handler</a></li> <li class="class-depth-1"><a href="Phaser.Pointer.html">Pointer</a></li> <li class="class-depth-1"><a href="Phaser.DeviceButton.html">Device Button</a></li> <li class="class-depth-1"><a href="Phaser.Mouse.html">Mouse</a></li> <li class="class-depth-1"><a href="Phaser.Keyboard.html">Keyboard</a></li> <li class="class-depth-1"><a href="Phaser.Key.html">Key</a></li> <li class="class-depth-1"><a href="Phaser.Gamepad.html">Gamepad</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Community<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="http://phaser.io">Phaser Web Site</a></li> <li class="class-depth-1"><a href="https://github.com/photonstorm/phaser">Phaser Github</a></li> <li class="class-depth-1"><a href="http://phaser.io/examples">Phaser Examples</a></li> <li class="class-depth-1"><a href="https://github.com/photonstorm/phaser-plugins">Phaser Plugins</a></li> <li class="class-depth-1"><a href="http://www.html5gamedevs.com/forum/14-phaser/">Forum</a></li> <li class="class-depth-1"><a href="http://stackoverflow.com/questions/tagged/phaser-framework">Stack Overflow</a></li> <li class="class-depth-1"><a href="http://phaser.io/learn">Tutorials</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/newsletter">Newsletter</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/twitter">Twitter</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/slack">Slack</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/donate">Donate</a></li> <li class="class-depth-1"><a href="https://www.codeandweb.com/texturepacker/phaser">Texture Packer</a></li> </ul> </li> </ul> </div> </div> <div class="row-fluid"> <div class="span12"> <div id="main"> <h1 class="page-title">Source: src/plugins/weapon/WeaponPlugin.js</h1> <section> <article> <pre class="sunlight-highlight-javascript linenums">/** * @author Richard Davey &lt;rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Weapon Plugin provides the ability to easily create a bullet pool and manager. * * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. * * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you * can usually do with a Group, such as move it around the display list, iterate it, etc can be done * to the bullets Group too. * * Bullets can have textures and even animations. You can control the speed at which they are fired, * the firing rate, the firing angle, and even set things like gravity for them. * * A small example, assumed to be running from within a Phaser.State create method. * * `var weapon = this.add.weapon(10, 'bullet');` * `weapon.fireFrom.set(300, 300);` * `this.input.onDown.add(weapon.fire, this);` * * @class Phaser.Weapon * @constructor * @param {Phaser.Game} game - A reference to the current Phaser.Game instance. * @param {Phaser.PluginManager} parent - The Phaser Plugin Manager which looks after this plugin. */ Phaser.Weapon = function (game, parent) { Phaser.Plugin.call(this, game, parent); /** * This is the Phaser.Group that contains all of the bullets managed by this plugin. * @type {Phaser.Group} */ this.bullets = null; /** * Should the bullet pool run out of bullets (i.e. they are all in flight) then this * boolean controls if the Group will create a brand new bullet object or not. * @type {boolean} */ this.autoExpandBulletsGroup = false; /** * Will this weapon auto fire? If set to true then a new bullet will be fired * based on the `fireRate` value. * @type {boolean} */ this.autofire = false; /** * The total number of bullets this Weapon has fired so far. * You can limit the number of shots allowed (via `fireLimit`), and reset * this total via `Weapon.resetShots`. * @type {number} */ this.shots = 0; /** * The maximum number of shots that this Weapon is allowed to fire before it stops. * When the limit is his the `Weapon.onFireLimit` Signal is dispatched. * You can reset the shot counter via `Weapon.resetShots`. * @type {number} */ this.fireLimit = 0; /** * The rate at which this Weapon can fire. The value is given in milliseconds. * @type {number} */ this.fireRate = 100; /** * This is a modifier that is added to the `fireRate` each update to add variety * to the firing rate of the Weapon. The value is given in milliseconds. * If you've a `fireRate` of 200 and a `fireRateVariance` of 50 then the actual * firing rate of the Weapon will be between 150 and 250. * @type {number} */ this.fireRateVariance = 0; /** * This is a Rectangle from within which the bullets are fired. By default it's a 1x1 * rectangle, the equivalent of a Point. But you can change the width and height, and if * larger than 1x1 it'll pick a random point within the rectangle to launch the bullet from. * @type {Phaser.Rectangle} */ this.fireFrom = new Phaser.Rectangle(0, 0, 1, 1); /** * The angle at which the bullets are fired. This can be a const such as Phaser.ANGLE_UP * or it can be any number from 0 to 360 inclusive, where 0 degrees is to the right. * @type {integer} */ this.fireAngle = Phaser.ANGLE_UP; /** * When a Bullet is fired it can optionally inherit the velocity of the `trackedSprite` if set. * @type {boolean} */ this.bulletInheritSpriteSpeed = false; /** * The string based name of the animation that the Bullet will be given on launch. * This is set via `Weapon.addBulletAnimation`. * @type {string} */ this.bulletAnimation = ''; /** * If you've added a set of frames via `Weapon.setBulletFrames` then you can optionally * chose for each Bullet fired to pick a random frame from the set. * @type {boolean} */ this.bulletFrameRandom = false; /** * If you've added a set of frames via `Weapon.setBulletFrames` then you can optionally * chose for each Bullet fired to use the next frame in the set. The frame index is then * advanced one frame until it reaches the end of the set, then it starts from the start * again. Cycling frames like this allows you to create varied bullet effects via * sprite sheets. * @type {boolean} */ this.bulletFrameCycle = false; /** * Should the Bullets wrap around the world bounds? This automatically calls * `World.wrap` on the Bullet each frame. See the docs for that method for details. * @type {boolean} */ this.bulletWorldWrap = false; /** * If `bulletWorldWrap` is true then you can provide an optional padding value with this * property. It's added to the calculations determining when the Bullet should wrap around * the world or not. The value is given in pixels. * @type {integer} */ this.bulletWorldWrapPadding = 0; /** * An optional angle offset applied to the Bullets when they are launched. * This is useful if for example your bullet sprites have been drawn facing up, instead of * to the right, and you want to fire them at an angle. In which case you can set the * angle offset to be 90 and they'll be properly rotated when fired. * @type {number} */ this.bulletAngleOffset = 0; /** * This is a variance added to the angle of Bullets when they are fired. * If you fire from an angle of 90 and have a `bulletAngleVariance` of 20 then the actual * angle of the Bullets will be between 70 and 110 degrees. This is a quick way to add a * great 'spread' effect to a Weapon. * @type {number} */ this.bulletAngleVariance = 0; /** * The speed at which the bullets are fired. This value is given in pixels per second, and * is used to set the starting velocity of the bullets. * @type {number} */ this.bulletSpeed = 200; /** * This is a variance added to the speed of Bullets when they are fired. * If bullets have a `bulletSpeed` value of 200, and a `bulletSpeedVariance` of 50 * then the actual speed of the Bullets will be between 150 and 250 pixels per second. * @type {number} */ this.bulletSpeedVariance = 0; /** * If you've set `bulletKillType` to `Phaser.Weapon.KILL_LIFESPAN` this controls the amount * of lifespan the Bullets have set on launch. The value is given in milliseconds. * When a Bullet hits its lifespan limit it will be automatically killed. * @type {number} */ this.bulletLifespan = 0; /** * If you've set `bulletKillType` to `Phaser.Weapon.KILL_DISTANCE` this controls the distance * the Bullet can travel before it is automatically killed. The distance is given in pixels. * @type {number} */ this.bulletKillDistance = 0; /** * This is the amount of gravity added to the Bullets physics body when fired. * Gravity is expressed in pixels / second / second. * @type {Phaser.Point} */ this.bulletGravity = new Phaser.Point(0, 0); /** * Bullets can optionally adjust their rotation in-flight to match their velocity. * This can create the effect of a bullet 'pointing' to the path it is following, for example * an arrow being fired from a bow, and works especially well when added to `bulletGravity`. * @type {boolean} */ this.bulletRotateToVelocity = false; /** * The Texture Key that the Bullets use when rendering. * Changing this has no effect on bullets in-flight, only on newly spawned bullets. * @type {string} */ this.bulletKey = ''; /** * The Texture Frame that the Bullets use when rendering. * Changing this has no effect on bullets in-flight, only on newly spawned bullets. * @type {string|integer} */ this.bulletFrame = ''; /** * Private var that holds the public `bulletClass` property. * @type {object} * @private */ this._bulletClass = Phaser.Bullet; /** * Private var that holds the public `bulletCollideWorldBounds` property. * @type {boolean} * @private */ this._bulletCollideWorldBounds = false; /** * Private var that holds the public `bulletKillType` property. * @type {integer} * @private */ this._bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; /** * Holds internal data about custom bullet body sizes. * * @type {Object} * @private */ this._data = { customBody: false, width: 0, height: 0, offsetX: 0, offsetY: 0 }; /** * This Rectangle defines the bounds that are used when determining if a Bullet should be killed or not. * It's used in combination with `Weapon.bulletKillType` when that is set to either `Phaser.Weapon.KILL_WEAPON_BOUNDS` * or `Phaser.Weapon.KILL_STATIC_BOUNDS`. If you are not using either of these kill types then the bounds are ignored. * If you are tracking a Sprite or Point then the bounds are centered on that object every frame. * * @type {Phaser.Rectangle} */ this.bounds = new Phaser.Rectangle(); /** * The Rectangle used to calculate the bullet bounds from. * * @type {Phaser.Rectangle} * @private */ this.bulletBounds = game.world.bounds; /** * This array stores the frames added via `Weapon.setBulletFrames`. * * @type {Array} * @protected */ this.bulletFrames = []; /** * The index of the frame within `Weapon.bulletFrames` that is currently being used. * This value is only used if `Weapon.bulletFrameCycle` is set to `true`. * @type {number} * @private */ this.bulletFrameIndex = 0; /** * An internal object that stores the animation data added via `Weapon.addBulletAnimation`. * @type {Object} * @private */ this.anims = {}; /** * The onFire Signal is dispatched each time `Weapon.fire` is called, and a Bullet is * _successfully_ launched. The callback is set two arguments: a reference to the bullet sprite itself, * and a reference to the Weapon that fired the bullet. * * @type {Phaser.Signal} */ this.onFire = new Phaser.Signal(); /** * The onKill Signal is dispatched each time a Bullet that is in-flight is killed. This can be the result * of leaving the Weapon bounds, an expiring lifespan, or exceeding a specified distance. * The callback is sent one argument: A reference to the bullet sprite itself. * * @type {Phaser.Signal} */ this.onKill = new Phaser.Signal(); /** * The onFireLimit Signal is dispatched if `Weapon.fireLimit` is > 0, and a bullet launch takes the number * of shots fired to equal the fire limit. * The callback is sent two arguments: A reference to the Weapon that hit the limit, and the value of * `Weapon.fireLimit`. * * @type {Phaser.Signal} */ this.onFireLimit = new Phaser.Signal(); /** * The Sprite currently being tracked by the Weapon, if any. * This is set via the `Weapon.trackSprite` method. * * @type {Phaser.Sprite|Object} */ this.trackedSprite = null; /** * The Pointer currently being tracked by the Weapon, if any. * This is set via the `Weapon.trackPointer` method. * * @type {Phaser.Pointer} */ this.trackedPointer = null; /** * If the Weapon is tracking a Sprite, should it also track the Sprites rotation? * This is useful for a game such as Asteroids, where you want the weapon to fire based * on the sprites rotation. * * @type {boolean} */ this.trackRotation = false; /** * The Track Offset is a Point object that allows you to specify a pixel offset that bullets use * when launching from a tracked Sprite or Pointer. For example if you've got a bullet that is 2x2 pixels * in size, but you're tracking a Sprite that is 32x32, then you can set `trackOffset.x = 16` to have * the bullet launched from the center of the Sprite. * * @type {Phaser.Point} */ this.trackOffset = new Phaser.Point(); /** * Internal firing rate time tracking variable. * * @type {number} * @private */ this._nextFire = 0; }; Phaser.Weapon.prototype = Object.create(Phaser.Plugin.prototype); Phaser.Weapon.prototype.constructor = Phaser.Weapon; /** * A `bulletKillType` constant that stops the bullets from ever being destroyed automatically. * @constant * @type {integer} */ Phaser.Weapon.KILL_NEVER = 0; /** * A `bulletKillType` constant that automatically kills the bullets when their `bulletLifespan` expires. * @constant * @type {integer} */ Phaser.Weapon.KILL_LIFESPAN = 1; /** * A `bulletKillType` constant that automatically kills the bullets after they * exceed the `bulletDistance` from their original firing position. * @constant * @type {integer} */ Phaser.Weapon.KILL_DISTANCE = 2; /** * A `bulletKillType` constant that automatically kills the bullets when they leave the `Weapon.bounds` rectangle. * @constant * @type {integer} */ Phaser.Weapon.KILL_WEAPON_BOUNDS = 3; /** * A `bulletKillType` constant that automatically kills the bullets when they leave the `Camera.bounds` rectangle. * @constant * @type {integer} */ Phaser.Weapon.KILL_CAMERA_BOUNDS = 4; /** * A `bulletKillType` constant that automatically kills the bullets when they leave the `World.bounds` rectangle. * @constant * @type {integer} */ Phaser.Weapon.KILL_WORLD_BOUNDS = 5; /** * A `bulletKillType` constant that automatically kills the bullets when they leave the `Weapon.bounds` rectangle. * @constant * @type {integer} */ Phaser.Weapon.KILL_STATIC_BOUNDS = 6; /** * This method performs two actions: First it will check to see if the `Weapon.bullets` Group exists or not, * and if not it creates it, adding it the `group` given as the 4th argument. * * Then it will seed the bullet pool with the `quantity` number of Bullets, using the texture key and frame * provided (if any). * * If for example you set the quantity to be 10, then this Weapon will only ever be able to have 10 bullets * in-flight simultaneously. If you try to fire an 11th bullet then nothing will happen until one, or more, of * the in-flight bullets have been killed, freeing them up for use by the Weapon again. * * If you do not wish to have a limit set, then pass in -1 as the quantity. In this instance the Weapon will * keep increasing the size of the bullet pool as needed. It will never reduce the size of the pool however, * so be careful it doesn't grow too large. * * You can either set the texture key and frame here, or via the `Weapon.bulletKey` and `Weapon.bulletFrame` * properties. You can also animate bullets, or set them to use random frames. All Bullets belonging to a * single Weapon instance must share the same texture key however. * * @method Phaser.Weapon#createBullets * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. * @param {string} [key] - The Game.cache key of the image that this Sprite will use. * @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. * @return {Phaser.Weapon} This Weapon instance. */ Phaser.Weapon.prototype.createBullets = function (quantity, key, frame, group) { if (quantity === undefined) { quantity = 1; } if (group === undefined) { group = this.game.world; } if (!this.bullets) { this.bullets = this.game.add.physicsGroup(Phaser.Physics.ARCADE, group); this.bullets.classType = this._bulletClass; } if (quantity !== 0) { if (quantity === -1) { this.autoExpandBulletsGroup = true; quantity = 1; } this.bullets.createMultiple(quantity, key, frame); this.bullets.setAll('data.bulletManager', this); this.bulletKey = key; this.bulletFrame = frame; } return this; }; /** * Call a function on each in-flight bullet in this Weapon. * * See {@link Phaser.Group#forEachExists forEachExists} for more details. * * @method Phaser.Weapon#forEach * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. * @param {object} callbackContext - The context in which the function should be called (usually 'this'). * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. * @return {Phaser.Weapon} This Weapon instance. */ Phaser.Weapon.prototype.forEach = function (callback, callbackContext) { this.bullets.forEachExists(callback, callbackContext, arguments); return this; }; /** * Sets `Body.enable` to `false` on each bullet in this Weapon. * This has the effect of stopping them in-flight should they be moving. * It also stops them being able to be checked for collision. * * @method Phaser.Weapon#pauseAll * @return {Phaser.Weapon} This Weapon instance. */ Phaser.Weapon.prototype.pauseAll = function () { this.bullets.setAll('body.enable', false); return this; }; /** * Sets `Body.enable` to `true` on each bullet in this Weapon. * This has the effect of resuming their motion should they be in-flight. * It also enables them for collision checks again. * * @method Phaser.Weapon#resumeAll * @return {Phaser.Weapon} This Weapon instance. */ Phaser.Weapon.prototype.resumeAll = function () { this.bullets.setAll('body.enable', true); return this; }; /** * Calls `Bullet.kill` on every in-flight bullet in this Weapon. * Also re-enables their physics bodies, should they have been disabled via `pauseAll`. * * @method Phaser.Weapon#killAll * @return {Phaser.Weapon} This Weapon instance. */ Phaser.Weapon.prototype.killAll = function () { this.bullets.callAllExists('kill', true); this.bullets.setAll('body.enable', true); return this; }; /** * Resets the `Weapon.shots` counter back to zero. This is used when you've set * `Weapon.fireLimit`, and have hit (or just wish to reset) your limit. * * @method Phaser.Weapon#resetShots * @param {integer} [newLimit] - Optionally set a new `Weapon.fireLimit`. * @return {Phaser.Weapon} This Weapon instance. */ Phaser.Weapon.prototype.resetShots = function (newLimit) { this.shots = 0; if (newLimit !== undefined) { this.fireLimit = newLimit; } return this; }; /** * Destroys this Weapon. It removes itself from the PluginManager, destroys * the bullets Group, and nulls internal references. * * @method Phaser.Weapon#destroy */ Phaser.Weapon.prototype.destroy = function () { this.parent.remove(this, false); this.bullets.destroy(); this.game = null; this.parent = null; this.active = false; this.visible = false; }; /** * Internal update method, called by the PluginManager. * * @method Phaser.Weapon#update * @protected */ Phaser.Weapon.prototype.update = function () { if (this._bulletKillType === Phaser.Weapon.KILL_WEAPON_BOUNDS) { if (this.trackedSprite) { this.trackedSprite.updateTransform(); this.bounds.centerOn(this.trackedSprite.worldPosition.x, this.trackedSprite.worldPosition.y); } else if (this.trackedPointer) { this.bounds.centerOn(this.trackedPointer.worldX, this.trackedPointer.worldY); } } if (this.autofire &amp;&amp; this.game.time.now &lt; this._nextFire) { this.fire(); } }; /** * Sets this Weapon to track the given Sprite, or any Object with a public `world` Point object. * When a Weapon tracks a Sprite it will automatically update its `fireFrom` value to match the Sprites * position within the Game World, adjusting the coordinates based on the offset arguments. * * This allows you to lock a Weapon to a Sprite, so that bullets are always launched from its location. * * Calling `trackSprite` will reset `Weapon.trackedPointer` to null, should it have been set, as you can * only track _either_ a Sprite, or a Pointer, at once, but not both. * * @method Phaser.Weapon#trackSprite * @param {Phaser.Sprite|Object} sprite - The Sprite to track the position of. * @param {integer} [offsetX=0] - The horizontal offset from the Sprites position to be applied to the Weapon. * @param {integer} [offsetY=0] - The vertical offset from the Sprites position to be applied to the Weapon. * @param {boolean} [trackRotation=false] - Should the Weapon also track the Sprites rotation? * @return {Phaser.Weapon} This Weapon instance. */ Phaser.Weapon.prototype.trackSprite = function (sprite, offsetX, offsetY, trackRotation) { if (offsetX === undefined) { offsetX = 0; } if (offsetY === undefined) { offsetY = 0; } if (trackRotation === undefined) { trackRotation = false; } this.trackedPointer = null; this.trackedSprite = sprite; this.trackRotation = trackRotation; this.trackOffset.set(offsetX, offsetY); return this; }; /** * Sets this Weapon to track the given Pointer. * When a Weapon tracks a Pointer it will automatically update its `fireFrom` value to match the Pointers * position within the Game World, adjusting the coordinates based on the offset arguments. * * This allows you to lock a Weapon to a Pointer, so that bullets are always launched from its location. * * Calling `trackPointer` will reset `Weapon.trackedSprite` to null, should it have been set, as you can * only track _either_ a Pointer, or a Sprite, at once, but not both. * * @method Phaser.Weapon#trackPointer * @param {Phaser.Pointer} [pointer] - The Pointer to track the position of. Defaults to `Input.activePointer` if not specified. * @param {integer} [offsetX=0] - The horizontal offset from the Pointers position to be applied to the Weapon. * @param {integer} [offsetY=0] - The vertical offset from the Pointers position to be applied to the Weapon. * @return {Phaser.Weapon} This Weapon instance. */ Phaser.Weapon.prototype.trackPointer = function (pointer, offsetX, offsetY) { if (pointer === undefined) { pointer = this.game.input.activePointer; } if (offsetX === undefined) { offsetX = 0; } if (offsetY === undefined) { offsetY = 0; } this.trackedPointer = pointer; this.trackedSprite = null; this.trackRotation = false; this.trackOffset.set(offsetX, offsetY); return this; }; /** * Attempts to fire a single Bullet. If there are no more bullets available in the pool, and the pool cannot be extended, * then this method returns `false`. It will also return false if not enough time has expired since the last time * the Weapon was fired, as defined in the `Weapon.fireRate` property. * * Otherwise the first available bullet is selected and launched. * * The arguments are all optional, but allow you to control both where the bullet is launched from, and aimed at. * * If you don't provide any of the arguments then it uses those set via properties such as `Weapon.trackedSprite`, * `Weapon.bulletAngle` and so on. * * When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is * calculated based on Weapon properties like `bulletSpeed`. * * @method Phaser.Weapon#fire * @param {Phaser.Sprite|Phaser.Point|Object} [from] - Optionally fires the bullet **from** the `x` and `y` properties of this object. If set this overrides `Weapon.trackedSprite` or `trackedPointer`. Pass `null` to ignore it. * @param {number} [x] - The x coordinate, in world space, to fire the bullet **towards**. If left as `undefined` the bullet direction is based on its angle. * @param {number} [y] - The y coordinate, in world space, to fire the bullet **towards**. If left as `undefined` the bullet direction is based on its angle. * @return {boolean} True if a bullet was successfully fired, otherwise false. */ Phaser.Weapon.prototype.fire = function (from, x, y) { if (this.game.time.now &lt; this._nextFire || (this.fireLimit > 0 &amp;&amp; this.shots === this.fireLimit)) { return false; } var speed = this.bulletSpeed; // Apply +- speed variance if (this.bulletSpeedVariance !== 0) { speed += Phaser.Math.between(-this.bulletSpeedVariance, this.bulletSpeedVariance); } if (from) { if (this.fireFrom.width > 1) { this.fireFrom.centerOn(from.x, from.y); } else { this.fireFrom.x = from.x; this.fireFrom.y = from.y; } } else if (this.trackedSprite) { if (this.fireFrom.width > 1) { this.fireFrom.centerOn(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); } else { this.fireFrom.x = this.trackedSprite.world.x + this.trackOffset.x; this.fireFrom.y = this.trackedSprite.world.y + this.trackOffset.y; } if (this.bulletInheritSpriteSpeed) { speed += this.trackedSprite.body.speed; } } else if (this.trackedPointer) { if (this.fireFrom.width > 1) { this.fireFrom.centerOn(this.trackedPointer.world.x + this.trackOffset.x, this.trackedPointer.world.y + this.trackOffset.y); } else { this.fireFrom.x = this.trackedPointer.world.x + this.trackOffset.x; this.fireFrom.y = this.trackedPointer.world.y + this.trackOffset.y; } } var fromX = (this.fireFrom.width > 1) ? this.fireFrom.randomX : this.fireFrom.x; var fromY = (this.fireFrom.height > 1) ? this.fireFrom.randomY : this.fireFrom.y; var angle = (this.trackRotation) ? this.trackedSprite.angle : this.fireAngle; // The position (in world space) to fire the bullet towards, if set if (x !== undefined &amp;&amp; y !== undefined) { angle = this.game.math.radToDeg(Math.atan2(y - fromY, x - fromX)); } // Apply +- angle variance if (this.bulletAngleVariance !== 0) { angle += Phaser.Math.between(-this.bulletAngleVariance, this.bulletAngleVariance); } var moveX = 0; var moveY = 0; // Avoid sin/cos for right-angled shots if (angle === 0 || angle === 180) { moveX = Math.cos(this.game.math.degToRad(angle)) * speed; } else if (angle === 90 || angle === 270) { moveY = Math.sin(this.game.math.degToRad(angle)) * speed; } else { moveX = Math.cos(this.game.math.degToRad(angle)) * speed; moveY = Math.sin(this.game.math.degToRad(angle)) * speed; } var bullet = null; if (this.autoExpandBulletsGroup) { bullet = this.bullets.getFirstExists(false, true, fromX, fromY, this.bulletKey, this.bulletFrame); bullet.data.bulletManager = this; } else { bullet = this.bullets.getFirstExists(false); } if (bullet) { bullet.reset(fromX, fromY); bullet.data.fromX = fromX; bullet.data.fromY = fromY; bullet.data.killType = this.bulletKillType; bullet.data.killDistance = this.bulletKillDistance; bullet.data.rotateToVelocity = this.bulletRotateToVelocity; if (this.bulletKillType === Phaser.Weapon.KILL_LIFESPAN) { bullet.lifespan = this.bulletLifespan; } bullet.angle = angle + this.bulletAngleOffset; // Frames and Animations if (this.bulletAnimation !== '') { if (bullet.animations.getAnimation(this.bulletAnimation) === null) { var anim = this.anims[this.bulletAnimation]; bullet.animations.add(anim.name, anim.frames, anim.frameRate, anim.loop, anim.useNumericIndex); } bullet.animations.play(this.bulletAnimation); } else { if (this.bulletFrameCycle) { bullet.frame = this.bulletFrames[this.bulletFrameIndex]; this.bulletFrameIndex++; if (this.bulletFrameIndex >= this.bulletFrames.length) { this.bulletFrameIndex = 0; } } else if (this.bulletFrameRandom) { bullet.frame = this.bulletFrames[Math.floor(Math.random() * this.bulletFrames.length)]; } } if (bullet.data.bodyDirty) { if (this._data.customBody) { bullet.body.setSize(this._data.width, this._data.height, this._data.offsetX, this._data.offsetY); } bullet.body.collideWorldBounds = this.bulletCollideWorldBounds; bullet.data.bodyDirty = false; } bullet.body.velocity.set(moveX, moveY); bullet.body.gravity.set(this.bulletGravity.x, this.bulletGravity.y); this._nextFire = this.game.time.now + this.fireRate; this.shots++; this.onFire.dispatch(bullet, this, speed); if (this.fireLimit > 0 &amp;&amp; this.shots === this.fireLimit) { this.onFireLimit.dispatch(this, this.fireLimit); } } }; /** * Fires a bullet **at** the given Pointer. The bullet will be launched from the `Weapon.fireFrom` position, * or from a Tracked Sprite or Pointer, if you have one set. * * @method Phaser.Weapon#fireAtPointer * @param {Phaser.Pointer} [pointer] - The Pointer to fire the bullet towards. * @return {boolean} True if a bullet was successfully fired, otherwise false. */ Phaser.Weapon.prototype.fireAtPointer = function (pointer) { if (pointer === undefined) { pointer = this.game.input.activePointer; } return this.fire(null, pointer.worldX, pointer.worldY); }; /** * Fires a bullet **at** the given Sprite. The bullet will be launched from the `Weapon.fireFrom` position, * or from a Tracked Sprite or Pointer, if you have one set. * * @method Phaser.Weapon#fireAtSprite * @param {Phaser.Sprite} [sprite] - The Sprite to fire the bullet towards. * @return {boolean} True if a bullet was successfully fired, otherwise false. */ Phaser.Weapon.prototype.fireAtSprite = function (sprite) { return this.fire(null, sprite.world.x, sprite.world.y); }; /** * Fires a bullet **at** the given coordinates. The bullet will be launched from the `Weapon.fireFrom` position, * or from a Tracked Sprite or Pointer, if you have one set. * * @method Phaser.Weapon#fireAtXY * @param {number} [x] - The x coordinate, in world space, to fire the bullet towards. * @param {number} [y] - The y coordinate, in world space, to fire the bullet towards. * @return {boolean} True if a bullet was successfully fired, otherwise false. */ Phaser.Weapon.prototype.fireAtXY = function (x, y) { return this.fire(null, x, y); }; /** * You can modify the size of the physics Body the Bullets use to be any dimension you need. * This allows you to make it smaller, or larger, than the parent Sprite. * You can also control the x and y offset of the Body. This is the position of the * Body relative to the top-left of the Sprite _texture_. * * For example: If you have a Sprite with a texture that is 80x100 in size, * and you want the physics body to be 32x32 pixels in the middle of the texture, you would do: * * `setSize(32, 32, 24, 34)` * * Where the first two parameters is the new Body size (32x32 pixels). * 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34 * is the vertical offset. * * @method Phaser.Weapon#setBulletBodyOffset * @param {number} width - The width of the Body. * @param {number} height - The height of the Body. * @param {number} [offsetX] - The X offset of the Body from the top-left of the Sprites texture. * @param {number} [offsetY] - The Y offset of the Body from the top-left of the Sprites texture. * @return {Phaser.Weapon} The Weapon Plugin. */ Phaser.Weapon.prototype.setBulletBodyOffset = function (width, height, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0; } if (offsetY === undefined) { offsetY = 0; } this._data.customBody = true; this._data.width = width; this._data.height = height; this._data.offsetX = offsetX; this._data.offsetY = offsetY; // Update all bullets in the pool this.bullets.callAll('body.setSize', 'body', width, height, offsetX, offsetY); this.bullets.setAll('data.bodyDirty', false); return this; }; /** * Sets the texture frames that the bullets can use when being launched. * * This is intended for use when you've got numeric based frames, such as those loaded via a Sprite Sheet. * * It works by calling `Phaser.ArrayUtils.numberArray` internally, using the min and max values * provided. Then it sets the frame index to be zero. * * You can optionally set the cycle and random booleans, to allow bullets to cycle through the frames * when they're fired, or pick one at random. * * @method Phaser.Weapon#setBulletFrames * @param {integer} min - The minimum value the frame can be. Usually zero. * @param {integer} max - The maximum value the frame can be. * @param {boolean} [cycle=true] - Should the bullet frames cycle as they are fired? * @param {boolean} [random=false] - Should the bullet frames be picked at random as they are fired? * @return {Phaser.Weapon} The Weapon Plugin. */ Phaser.Weapon.prototype.setBulletFrames = function (min, max, cycle, random) { if (cycle === undefined) { cycle = true; } if (random === undefined) { random = false; } this.bulletFrames = Phaser.ArrayUtils.numberArray(min, max); this.bulletFrameIndex = 0; this.bulletFrameCycle = cycle; this.bulletFrameRandom = random; return this; }; /** * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. * The arguments are all the same as for `Animation.add`, and work in the same way. * * `Weapon.bulletAnimation` will be set to this animation after it's created. From that point on, all * bullets fired will play using this animation. You can swap between animations by calling this method * several times, and then just changing the `Weapon.bulletAnimation` property to the name of the animation * you wish to play for the next launched bullet. * * If you wish to stop using animations at all, set `Weapon.bulletAnimation` to '' (an empty string). * * @method Phaser.Weapon#addBulletAnimation * @param {string} name - The unique (within the Weapon instance) name for the animation, i.e. "fire", "blast". * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? * @return {Phaser.Weapon} The Weapon Plugin. */ Phaser.Weapon.prototype.addBulletAnimation = function (name, frames, frameRate, loop, useNumericIndex) { this.anims[name] = { name: name, frames: frames, frameRate: frameRate, loop: loop, useNumericIndex: useNumericIndex }; // Add the animation to any existing bullets in the pool this.bullets.callAll('animations.add', 'animations', name, frames, frameRate, loop, useNumericIndex); this.bulletAnimation = name; return this; }; /** * Uses `Game.Debug` to draw some useful information about this Weapon, including the number of bullets * both in-flight, and available. And optionally the physics debug bodies of the bullets. * * @method Phaser.Weapon#debug * @param {integer} [x=16] - The coordinate, in screen space, at which to draw the Weapon debug data. * @param {integer} [y=32] - The coordinate, in screen space, at which to draw the Weapon debug data. * @param {boolean} [debugBodies=false] - Optionally draw the physics body of every bullet in-flight. */ Phaser.Weapon.prototype.debug = function (x, y, debugBodies) { if (x === undefined) { x = 16; } if (y === undefined) { y = 32; } if (debugBodies === undefined) { debugBodies = false; } this.game.debug.text("Weapon Plugin", x, y); this.game.debug.text("Bullets Alive: " + this.bullets.total + " - Total: " + this.bullets.length, x, y + 24); if (debugBodies) { this.bullets.forEachExists(this.game.debug.body, this.game.debug, 'rgba(255, 0, 255, 0.8)'); } }; /** * The Class of the bullets that are launched by this Weapon. Defaults `Phaser.Bullet`, but can be * overridden before calling `createBullets` and set to your own class type. * * @name Phaser.Weapon#bulletClass * @property {Object} bulletClass */ Object.defineProperty(Phaser.Weapon.prototype, "bulletClass", { get: function () { return this._bulletClass; }, set: function (classType) { this._bulletClass = classType; this.bullets.classType = this._bulletClass; } }); /** * This controls how the bullets will be killed. The default is `Phaser.Weapon.KILL_WORLD_BOUNDS`. * * There are 7 different "kill types" available: * * * `Phaser.Weapon.KILL_NEVER` * The bullets are never destroyed by the Weapon. It's up to you to destroy them via your own code. * * * `Phaser.Weapon.KILL_LIFESPAN` * The bullets are automatically killed when their `bulletLifespan` amount expires. * * * `Phaser.Weapon.KILL_DISTANCE` * The bullets are automatically killed when they exceed `bulletDistance` pixels away from their original launch position. * * * `Phaser.Weapon.KILL_WEAPON_BOUNDS` * The bullets are automatically killed when they no longer intersect with the `Weapon.bounds` rectangle. * * * `Phaser.Weapon.KILL_CAMERA_BOUNDS` * The bullets are automatically killed when they no longer intersect with the `Camera.bounds` rectangle. * * * `Phaser.Weapon.KILL_WORLD_BOUNDS` * The bullets are automatically killed when they no longer intersect with the `World.bounds` rectangle. * * * `Phaser.Weapon.KILL_STATIC_BOUNDS` * The bullets are automatically killed when they no longer intersect with the `Weapon.bounds` rectangle. * The difference between static bounds and weapon bounds, is that a static bounds will never be adjusted to * match the position of a tracked sprite or pointer. * * @name Phaser.Weapon#bulletKillType * @property {integer} bulletKillType */ Object.defineProperty(Phaser.Weapon.prototype, "bulletKillType", { get: function () { return this._bulletKillType; }, set: function (type) { switch (type) { case Phaser.Weapon.KILL_STATIC_BOUNDS: case Phaser.Weapon.KILL_WEAPON_BOUNDS: this.bulletBounds = this.bounds; break; case Phaser.Weapon.KILL_CAMERA_BOUNDS: this.bulletBounds = this.game.camera.view; break; case Phaser.Weapon.KILL_WORLD_BOUNDS: this.bulletBounds = this.game.world.bounds; break; } this._bulletKillType = type; } }); /** * Should bullets collide with the World bounds or not? * * @name Phaser.Weapon#bulletCollideWorldBounds * @property {boolean} bulletCollideWorldBounds */ Object.defineProperty(Phaser.Weapon.prototype, "bulletCollideWorldBounds", { get: function () { return this._bulletCollideWorldBounds; }, set: function (value) { this._bulletCollideWorldBounds = value; this.bullets.setAll('body.collideWorldBounds', value); this.bullets.setAll('data.bodyDirty', false); } }); /** * The x coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.x`, and * can be overridden by the `Weapon.fire` arguments. * * @name Phaser.Weapon#x * @property {number} x */ Object.defineProperty(Phaser.Weapon.prototype, "x", { get: function () { return this.fireFrom.x; }, set: function (value) { this.fireFrom.x = value; } }); /** * The y coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.y`, and * can be overridden by the `Weapon.fire` arguments. * * @name Phaser.Weapon#y * @property {number} y */ Object.defineProperty(Phaser.Weapon.prototype, "y", { get: function () { return this.fireFrom.y; }, set: function (value) { this.fireFrom.y = value; } }); </pre> </article> </section> </div> <div class="clearfix"></div> <footer> <span class="copyright"> Phaser Copyright © 2012-2016 Photon Storm Ltd. </span> <br /> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.3</a> on Mon Jul 11 2016 10:10:44 GMT+0100 (GMT Daylight Time) using the <a href="https://github.com/terryweiss/docstrap">DocStrap template</a>. </span> </footer> </div> <br clear="both"> </div> </div> <script src="scripts/sunlight.js"></script> <script src="scripts/sunlight.javascript.js"></script> <script src="scripts/sunlight-plugin.doclinks.js"></script> <script src="scripts/sunlight-plugin.linenumbers.js"></script> <script src="scripts/sunlight-plugin.menu.js"></script> <script src="scripts/jquery.min.js"></script> <script src="scripts/jquery.scrollTo.js"></script> <script src="scripts/jquery.localScroll.js"></script> <script src="scripts/bootstrap-dropdown.js"></script> <script src="scripts/toc.js"></script> <script> Sunlight.highlightAll({lineNumbers:true, showMenu: true, enableDoclinks :true}); </script> <script> $( function () { $( "#toc" ).toc( { anchorName : function(i, heading, prefix) { return $(heading).attr("id") || ( prefix + i ); }, selectors : "h1,h2,h3,h4", showAndHide : false, scrollTo : 60 } ); $( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); } ); </script> </body> </html>
fmflame/phaser
docs/src_plugins_weapon_WeaponPlugin.js.html
HTML
mit
79,483
// // Use this file to import your target's public headers that you would like to expose to Swift. // #import "example.h"
dolphilia/swift-lua-example
09_lua_in_swift_multithreading/swiftobjctest/swiftobjctest-Bridging-Header.h
C
mit
123
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; namespace System.Collections.Specialized.Tests { public class GetEnumeratorNameObjectCollectionBaseTests { private String _strErr = "Error!"; [Fact] public void Test01() { MyNameObjectCollection noc = new MyNameObjectCollection(); IEnumerator en = null; bool res; // [] Enumerator for empty collection // Get enumerator en = noc.GetEnumerator(); // MoveNext should return false res = en.MoveNext(); if (res) { Assert.False(true, _strErr + "MoveNext returned true"); } // Attempt to get Current should result in exception Assert.Throws<InvalidOperationException>(() => { String curr = (String)en.Current; }); // [] Enumerator for non-empty collection // Add items for (int i = 0; i < 10; i++) { noc.Add("key_" + i.ToString(), new Foo()); } // Get enumerator en = noc.GetEnumerator(); // Attempt to get Current should result in exception Assert.Throws<InvalidOperationException>(() => { String curr = (String)en.Current; }); // Iterate over collection for (int i = 0; i < noc.Count; i++) { // MoveNext should return true res = en.MoveNext(); if (!res) { Assert.False(true, string.Format(_strErr + "#{0}, MoveNext returned false", i)); } // Check current String curr = (String)en.Current; if (noc[curr] == null) { Assert.False(true, string.Format(_strErr + "#{0}, Current={1}, key not found in collection", i, curr)); } // Check current again String current1 = (String)en.Current; if (current1 != curr) { Assert.False(true, string.Format(_strErr + "#{0}, Value of Current changed! Was {1}, now {2}", i, curr, current1)); } } // next MoveNext should bring us outside of the collection, return false res = en.MoveNext(); if (res) { Assert.False(true, _strErr + "MoveNext returned true"); } // Attempt to get Current should result in exception Assert.Throws<InvalidOperationException>(() => { String curr = (String)en.Current; }); // Reset en.Reset(); // Attempt to get Current should result in exception Assert.Throws<InvalidOperationException>(() => { String curr = (String)en.Current; }); // Modify collection and then then try MoveNext, Current, Reset // new collection noc = new MyNameObjectCollection(); noc.Add("key1", new Foo()); noc.Add("key2", new Foo()); noc.Add("key3", new Foo()); en = noc.GetEnumerator(); // MoveNext if (!en.MoveNext()) { Assert.False(true, _strErr + "MoveNext returned false"); } // Current String current = (String)en.Current; // Modify collection noc.RemoveAt(0); if (noc.Count != 2) { Assert.False(true, string.Format(_strErr + "Collection Count wrong. Expected {0}, got {1}", 2, noc.Count)); } // Current should not throw, but no guarantee is made on the return value string curr1 = (String)en.Current; // MoveNext should throw exception Assert.Throws<InvalidOperationException>(() => { en.MoveNext(); }); // Reset should throw exception Assert.Throws<InvalidOperationException>(() => { en.Reset(); }); // Current should not throw, but no guarantee is made on the return value curr1 = (String)en.Current; // MoveNext should still throw exception if collection is ReadOnly noc.IsReadOnly = true; Assert.Throws<InvalidOperationException>(() => { en.MoveNext(); }); // Clear collection and then then try MoveNext, Current, Reset // new collection noc = new MyNameObjectCollection(); noc.Add("key1", new Foo()); noc.Add("key2", new Foo()); noc.Add("key3", new Foo()); en = noc.GetEnumerator(); // MoveNext if (!en.MoveNext()) { Assert.False(true, _strErr + "MoveNext returned false"); } // Current current = (String)en.Current; // Modify collection noc.Clear(); if (noc.Count != 0) { Assert.False(true, string.Format(_strErr + "Collection Count wrong. Expected {0}, got {1}", 2, noc.Count)); } // Current throws. Should it throw here?! Assert.Throws<InvalidOperationException>(() => { String curr = (String)en.Current; }); // MoveNext should throw exception Assert.Throws<InvalidOperationException>(() => { en.MoveNext(); }); // Reset should throw exception Assert.Throws<InvalidOperationException>(() => { en.Reset(); }); } } }
mafiya69/corefx
src/System.Collections.Specialized/tests/NameObjectCollectionBase/GetEnumeratorTests.cs
C#
mit
5,843
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections; using System.Collections.Generic; using Azure.Core; namespace Azure.Graph.Rbac.Models { /// <summary> Active Directory Password Credential information. </summary> public partial class PasswordCredential : IDictionary<string, object> { /// <summary> Initializes a new instance of PasswordCredential. </summary> public PasswordCredential() { AdditionalProperties = new ChangeTrackingDictionary<string, object>(); } /// <summary> Initializes a new instance of PasswordCredential. </summary> /// <param name="startDate"> Start date. </param> /// <param name="endDate"> End date. </param> /// <param name="keyId"> Key ID. </param> /// <param name="value"> Key value. </param> /// <param name="customKeyIdentifier"> Custom Key Identifier. </param> /// <param name="additionalProperties"> . </param> internal PasswordCredential(DateTimeOffset? startDate, DateTimeOffset? endDate, string keyId, string value, byte[] customKeyIdentifier, IDictionary<string, object> additionalProperties) { StartDate = startDate; EndDate = endDate; KeyId = keyId; Value = value; CustomKeyIdentifier = customKeyIdentifier; AdditionalProperties = additionalProperties; } /// <summary> Start date. </summary> public DateTimeOffset? StartDate { get; set; } /// <summary> End date. </summary> public DateTimeOffset? EndDate { get; set; } /// <summary> Key ID. </summary> public string KeyId { get; set; } /// <summary> Key value. </summary> public string Value { get; set; } /// <summary> Custom Key Identifier. </summary> public byte[] CustomKeyIdentifier { get; set; } internal IDictionary<string, object> AdditionalProperties { get; } /// <inheritdoc /> public IEnumerator<KeyValuePair<string, object>> GetEnumerator() => AdditionalProperties.GetEnumerator(); /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() => AdditionalProperties.GetEnumerator(); /// <inheritdoc /> public bool TryGetValue(string key, out object value) => AdditionalProperties.TryGetValue(key, out value); /// <inheritdoc /> public bool ContainsKey(string key) => AdditionalProperties.ContainsKey(key); /// <inheritdoc /> public ICollection<string> Keys => AdditionalProperties.Keys; /// <inheritdoc /> public ICollection<object> Values => AdditionalProperties.Values; /// <inheritdoc cref="ICollection{T}.Count"/> int ICollection<KeyValuePair<string, object>>.Count => AdditionalProperties.Count; /// <inheritdoc /> public void Add(string key, object value) => AdditionalProperties.Add(key, value); /// <inheritdoc /> public bool Remove(string key) => AdditionalProperties.Remove(key); /// <inheritdoc cref="ICollection{T}.IsReadOnly"/> bool ICollection<KeyValuePair<string, object>>.IsReadOnly => AdditionalProperties.IsReadOnly; /// <inheritdoc cref="ICollection{T}.Add"/> void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> value) => AdditionalProperties.Add(value); /// <inheritdoc cref="ICollection{T}.Remove"/> bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> value) => AdditionalProperties.Remove(value); /// <inheritdoc cref="ICollection{T}.Contains"/> bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> value) => AdditionalProperties.Contains(value); /// <inheritdoc cref="ICollection{T}.CopyTo"/> void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] destination, int offset) => AdditionalProperties.CopyTo(destination, offset); /// <inheritdoc cref="ICollection{T}.Clear"/> void ICollection<KeyValuePair<string, object>>.Clear() => AdditionalProperties.Clear(); /// <inheritdoc /> public object this[string key] { get => AdditionalProperties[key]; set => AdditionalProperties[key] = value; } } }
jackmagic313/azure-sdk-for-net
sdk/testcommon/Azure.Graph.Rbac/src/Generated/Models/PasswordCredential.cs
C#
mit
4,464
Clazz.declarePackage ("JU"); Clazz.load (["JU.V3"], "JU.Measure", ["java.lang.Float", "javajs.api.Interface", "JU.Lst", "$.P3", "$.P4", "$.Quat"], function () { c$ = Clazz.declareType (JU, "Measure"); c$.computeAngle = Clazz.defineMethod (c$, "computeAngle", function (pointA, pointB, pointC, vectorBA, vectorBC, asDegrees) { vectorBA.sub2 (pointA, pointB); vectorBC.sub2 (pointC, pointB); var angle = vectorBA.angle (vectorBC); return (asDegrees ? angle / 0.017453292 : angle); }, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3,~B"); c$.computeAngleABC = Clazz.defineMethod (c$, "computeAngleABC", function (pointA, pointB, pointC, asDegrees) { var vectorBA = new JU.V3 (); var vectorBC = new JU.V3 (); return JU.Measure.computeAngle (pointA, pointB, pointC, vectorBA, vectorBC, asDegrees); }, "JU.T3,JU.T3,JU.T3,~B"); c$.computeTorsion = Clazz.defineMethod (c$, "computeTorsion", function (p1, p2, p3, p4, asDegrees) { var ijx = p1.x - p2.x; var ijy = p1.y - p2.y; var ijz = p1.z - p2.z; var kjx = p3.x - p2.x; var kjy = p3.y - p2.y; var kjz = p3.z - p2.z; var klx = p3.x - p4.x; var kly = p3.y - p4.y; var klz = p3.z - p4.z; var ax = ijy * kjz - ijz * kjy; var ay = ijz * kjx - ijx * kjz; var az = ijx * kjy - ijy * kjx; var cx = kjy * klz - kjz * kly; var cy = kjz * klx - kjx * klz; var cz = kjx * kly - kjy * klx; var ai2 = 1 / (ax * ax + ay * ay + az * az); var ci2 = 1 / (cx * cx + cy * cy + cz * cz); var ai = Math.sqrt (ai2); var ci = Math.sqrt (ci2); var denom = ai * ci; var cross = ax * cx + ay * cy + az * cz; var cosang = cross * denom; if (cosang > 1) { cosang = 1; }if (cosang < -1) { cosang = -1; }var torsion = Math.acos (cosang); var dot = ijx * cx + ijy * cy + ijz * cz; var absDot = Math.abs (dot); torsion = (dot / absDot > 0) ? torsion : -torsion; return (asDegrees ? torsion / 0.017453292 : torsion); }, "JU.T3,JU.T3,JU.T3,JU.T3,~B"); c$.computeHelicalAxis = Clazz.defineMethod (c$, "computeHelicalAxis", function (a, b, dq) { var vab = new JU.V3 (); vab.sub2 (b, a); var theta = dq.getTheta (); var n = dq.getNormal (); var v_dot_n = vab.dot (n); if (Math.abs (v_dot_n) < 0.0001) v_dot_n = 0; var va_prime_d = new JU.V3 (); va_prime_d.cross (vab, n); if (va_prime_d.dot (va_prime_d) != 0) va_prime_d.normalize (); var vda = new JU.V3 (); var vcb = JU.V3.newV (n); if (v_dot_n == 0) v_dot_n = 1.4E-45; vcb.scale (v_dot_n); vda.sub2 (vcb, vab); vda.scale (0.5); va_prime_d.scale (theta == 0 ? 0 : (vda.length () / Math.tan (theta / 2 / 180 * 3.141592653589793))); var r = JU.V3.newV (va_prime_d); if (theta != 0) r.add (vda); var pt_a_prime = JU.P3.newP (a); pt_a_prime.sub (r); if (v_dot_n != 1.4E-45) n.scale (v_dot_n); var pt_b_prime = JU.P3.newP (pt_a_prime); pt_b_prime.add (n); theta = JU.Measure.computeTorsion (a, pt_a_prime, pt_b_prime, b, true); if (Float.isNaN (theta) || r.length () < 0.0001) theta = dq.getThetaDirectedV (n); var residuesPerTurn = Math.abs (theta == 0 ? 0 : 360 / theta); var pitch = Math.abs (v_dot_n == 1.4E-45 ? 0 : n.length () * (theta == 0 ? 1 : 360 / theta)); return Clazz.newArray (-1, [pt_a_prime, n, r, JU.P3.new3 (theta, pitch, residuesPerTurn), pt_b_prime]); }, "JU.P3,JU.P3,JU.Quat"); c$.getPlaneThroughPoints = Clazz.defineMethod (c$, "getPlaneThroughPoints", function (pointA, pointB, pointC, vNorm, vAB, plane) { var w = JU.Measure.getNormalThroughPoints (pointA, pointB, pointC, vNorm, vAB); plane.set4 (vNorm.x, vNorm.y, vNorm.z, w); return plane; }, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3,JU.P4"); c$.getPlaneThroughPoint = Clazz.defineMethod (c$, "getPlaneThroughPoint", function (pt, normal, plane) { plane.set4 (normal.x, normal.y, normal.z, -normal.dot (pt)); }, "JU.T3,JU.V3,JU.P4"); c$.distanceToPlane = Clazz.defineMethod (c$, "distanceToPlane", function (plane, pt) { return (plane == null ? NaN : (plane.dot (pt) + plane.w) / Math.sqrt (plane.dot (plane))); }, "JU.P4,JU.T3"); c$.directedDistanceToPlane = Clazz.defineMethod (c$, "directedDistanceToPlane", function (pt, plane, ptref) { var f = plane.dot (pt) + plane.w; var f1 = plane.dot (ptref) + plane.w; return Math.signum (f1) * f / Math.sqrt (plane.dot (plane)); }, "JU.P3,JU.P4,JU.P3"); c$.distanceToPlaneD = Clazz.defineMethod (c$, "distanceToPlaneD", function (plane, d, pt) { return (plane == null ? NaN : (plane.dot (pt) + plane.w) / d); }, "JU.P4,~N,JU.P3"); c$.distanceToPlaneV = Clazz.defineMethod (c$, "distanceToPlaneV", function (norm, w, pt) { return (norm == null ? NaN : (norm.dot (pt) + w) / Math.sqrt (norm.dot (norm))); }, "JU.V3,~N,JU.P3"); c$.calcNormalizedNormal = Clazz.defineMethod (c$, "calcNormalizedNormal", function (pointA, pointB, pointC, vNormNorm, vAB) { vAB.sub2 (pointB, pointA); vNormNorm.sub2 (pointC, pointA); vNormNorm.cross (vAB, vNormNorm); vNormNorm.normalize (); }, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3"); c$.getDirectedNormalThroughPoints = Clazz.defineMethod (c$, "getDirectedNormalThroughPoints", function (pointA, pointB, pointC, ptRef, vNorm, vAB) { var nd = JU.Measure.getNormalThroughPoints (pointA, pointB, pointC, vNorm, vAB); if (ptRef != null) { var pt0 = JU.P3.newP (pointA); pt0.add (vNorm); var d = pt0.distance (ptRef); pt0.sub2 (pointA, vNorm); if (d > pt0.distance (ptRef)) { vNorm.scale (-1); nd = -nd; }}return nd; }, "JU.T3,JU.T3,JU.T3,JU.T3,JU.V3,JU.V3"); c$.getNormalThroughPoints = Clazz.defineMethod (c$, "getNormalThroughPoints", function (pointA, pointB, pointC, vNorm, vTemp) { JU.Measure.calcNormalizedNormal (pointA, pointB, pointC, vNorm, vTemp); vTemp.setT (pointA); return -vTemp.dot (vNorm); }, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3"); c$.getPlaneProjection = Clazz.defineMethod (c$, "getPlaneProjection", function (pt, plane, ptProj, vNorm) { var dist = JU.Measure.distanceToPlane (plane, pt); vNorm.set (plane.x, plane.y, plane.z); vNorm.normalize (); vNorm.scale (-dist); ptProj.add2 (pt, vNorm); }, "JU.P3,JU.P4,JU.P3,JU.V3"); c$.getNormalFromCenter = Clazz.defineMethod (c$, "getNormalFromCenter", function (ptCenter, ptA, ptB, ptC, isOutward, normal, vTemp) { var d = JU.Measure.getNormalThroughPoints (ptA, ptB, ptC, normal, vTemp); var isReversed = (JU.Measure.distanceToPlaneV (normal, d, ptCenter) > 0); if (isReversed == isOutward) normal.scale (-1.0); return !isReversed; }, "JU.P3,JU.P3,JU.P3,JU.P3,~B,JU.V3,JU.V3"); c$.getNormalToLine = Clazz.defineMethod (c$, "getNormalToLine", function (pointA, pointB, vNormNorm) { vNormNorm.sub2 (pointA, pointB); vNormNorm.cross (vNormNorm, JU.Measure.axisY); vNormNorm.normalize (); if (Float.isNaN (vNormNorm.x)) vNormNorm.set (1, 0, 0); }, "JU.P3,JU.P3,JU.V3"); c$.getBisectingPlane = Clazz.defineMethod (c$, "getBisectingPlane", function (pointA, vAB, ptTemp, vTemp, plane) { ptTemp.scaleAdd2 (0.5, vAB, pointA); vTemp.setT (vAB); vTemp.normalize (); JU.Measure.getPlaneThroughPoint (ptTemp, vTemp, plane); }, "JU.P3,JU.V3,JU.T3,JU.V3,JU.P4"); c$.projectOntoAxis = Clazz.defineMethod (c$, "projectOntoAxis", function (point, axisA, axisUnitVector, vectorProjection) { vectorProjection.sub2 (point, axisA); var projectedLength = vectorProjection.dot (axisUnitVector); point.scaleAdd2 (projectedLength, axisUnitVector, axisA); vectorProjection.sub2 (point, axisA); }, "JU.P3,JU.P3,JU.V3,JU.V3"); c$.calcBestAxisThroughPoints = Clazz.defineMethod (c$, "calcBestAxisThroughPoints", function (points, axisA, axisUnitVector, vectorProjection, nTriesMax) { var nPoints = points.length; axisA.setT (points[0]); axisUnitVector.sub2 (points[nPoints - 1], axisA); axisUnitVector.normalize (); JU.Measure.calcAveragePointN (points, nPoints, axisA); var nTries = 0; while (nTries++ < nTriesMax && JU.Measure.findAxis (points, nPoints, axisA, axisUnitVector, vectorProjection) > 0.001) { } var tempA = JU.P3.newP (points[0]); JU.Measure.projectOntoAxis (tempA, axisA, axisUnitVector, vectorProjection); axisA.setT (tempA); }, "~A,JU.P3,JU.V3,JU.V3,~N"); c$.findAxis = Clazz.defineMethod (c$, "findAxis", function (points, nPoints, axisA, axisUnitVector, vectorProjection) { var sumXiYi = new JU.V3 (); var vTemp = new JU.V3 (); var pt = new JU.P3 (); var ptProj = new JU.P3 (); var a = JU.V3.newV (axisUnitVector); var sum_Xi2 = 0; for (var i = nPoints; --i >= 0; ) { pt.setT (points[i]); ptProj.setT (pt); JU.Measure.projectOntoAxis (ptProj, axisA, axisUnitVector, vectorProjection); vTemp.sub2 (pt, ptProj); vTemp.cross (vectorProjection, vTemp); sumXiYi.add (vTemp); sum_Xi2 += vectorProjection.lengthSquared (); } var m = JU.V3.newV (sumXiYi); m.scale (1 / sum_Xi2); vTemp.cross (m, axisUnitVector); axisUnitVector.add (vTemp); axisUnitVector.normalize (); vTemp.sub2 (axisUnitVector, a); return vTemp.length (); }, "~A,~N,JU.P3,JU.V3,JU.V3"); c$.calcAveragePoint = Clazz.defineMethod (c$, "calcAveragePoint", function (pointA, pointB, pointC) { pointC.set ((pointA.x + pointB.x) / 2, (pointA.y + pointB.y) / 2, (pointA.z + pointB.z) / 2); }, "JU.P3,JU.P3,JU.P3"); c$.calcAveragePointN = Clazz.defineMethod (c$, "calcAveragePointN", function (points, nPoints, averagePoint) { averagePoint.setT (points[0]); for (var i = 1; i < nPoints; i++) averagePoint.add (points[i]); averagePoint.scale (1 / nPoints); }, "~A,~N,JU.P3"); c$.transformPoints = Clazz.defineMethod (c$, "transformPoints", function (vPts, m4, center) { var v = new JU.Lst (); for (var i = 0; i < vPts.size (); i++) { var pt = JU.P3.newP (vPts.get (i)); pt.sub (center); m4.rotTrans (pt); pt.add (center); v.addLast (pt); } return v; }, "JU.Lst,JU.M4,JU.P3"); c$.isInTetrahedron = Clazz.defineMethod (c$, "isInTetrahedron", function (pt, ptA, ptB, ptC, ptD, plane, vTemp, vTemp2, fullyEnclosed) { var b = (JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptC, ptD, ptA, vTemp, vTemp2, plane), pt) >= 0); if (b != (JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptA, ptD, ptB, vTemp, vTemp2, plane), pt) >= 0)) return false; if (b != (JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptB, ptD, ptC, vTemp, vTemp2, plane), pt) >= 0)) return false; var d = JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptA, ptB, ptC, vTemp, vTemp2, plane), pt); if (fullyEnclosed) return (b == (d >= 0)); var d1 = JU.Measure.distanceToPlane (plane, ptD); return d1 * d <= 0 || Math.abs (d1) > Math.abs (d); }, "JU.P3,JU.P3,JU.P3,JU.P3,JU.P3,JU.P4,JU.V3,JU.V3,~B"); c$.getIntersectionPP = Clazz.defineMethod (c$, "getIntersectionPP", function (plane1, plane2) { var a1 = plane1.x; var b1 = plane1.y; var c1 = plane1.z; var d1 = plane1.w; var a2 = plane2.x; var b2 = plane2.y; var c2 = plane2.z; var d2 = plane2.w; var norm1 = JU.V3.new3 (a1, b1, c1); var norm2 = JU.V3.new3 (a2, b2, c2); var nxn = new JU.V3 (); nxn.cross (norm1, norm2); var ax = Math.abs (nxn.x); var ay = Math.abs (nxn.y); var az = Math.abs (nxn.z); var x; var y; var z; var diff; var type = (ax > ay ? (ax > az ? 1 : 3) : ay > az ? 2 : 3); switch (type) { case 1: x = 0; diff = (b1 * c2 - b2 * c1); if (Math.abs (diff) < 0.01) return null; y = (c1 * d2 - c2 * d1) / diff; z = (b2 * d1 - d2 * b1) / diff; break; case 2: diff = (a1 * c2 - a2 * c1); if (Math.abs (diff) < 0.01) return null; x = (c1 * d2 - c2 * d1) / diff; y = 0; z = (a2 * d1 - d2 * a1) / diff; break; case 3: default: diff = (a1 * b2 - a2 * b1); if (Math.abs (diff) < 0.01) return null; x = (b1 * d2 - b2 * d1) / diff; y = (a2 * d1 - d2 * a1) / diff; z = 0; } var list = new JU.Lst (); list.addLast (JU.P3.new3 (x, y, z)); nxn.normalize (); list.addLast (nxn); return list; }, "JU.P4,JU.P4"); c$.getIntersection = Clazz.defineMethod (c$, "getIntersection", function (pt1, v, plane, ptRet, tempNorm, vTemp) { JU.Measure.getPlaneProjection (pt1, plane, ptRet, tempNorm); tempNorm.set (plane.x, plane.y, plane.z); tempNorm.normalize (); if (v == null) v = JU.V3.newV (tempNorm); var l_dot_n = v.dot (tempNorm); if (Math.abs (l_dot_n) < 0.01) return null; vTemp.sub2 (ptRet, pt1); ptRet.scaleAdd2 (vTemp.dot (tempNorm) / l_dot_n, v, pt1); return ptRet; }, "JU.P3,JU.V3,JU.P4,JU.P3,JU.V3,JU.V3"); c$.calculateQuaternionRotation = Clazz.defineMethod (c$, "calculateQuaternionRotation", function (centerAndPoints, retStddev) { retStddev[1] = NaN; var q = new JU.Quat (); if (centerAndPoints[0].length == 1 || centerAndPoints[0].length != centerAndPoints[1].length) return q; var n = centerAndPoints[0].length - 1; if (n < 2) return q; var Sxx = 0; var Sxy = 0; var Sxz = 0; var Syx = 0; var Syy = 0; var Syz = 0; var Szx = 0; var Szy = 0; var Szz = 0; var ptA = new JU.P3 (); var ptB = new JU.P3 (); for (var i = n + 1; --i >= 1; ) { var aij = centerAndPoints[0][i]; var bij = centerAndPoints[1][i]; ptA.sub2 (aij, centerAndPoints[0][0]); ptB.sub2 (bij, centerAndPoints[0][1]); Sxx += ptA.x * ptB.x; Sxy += ptA.x * ptB.y; Sxz += ptA.x * ptB.z; Syx += ptA.y * ptB.x; Syy += ptA.y * ptB.y; Syz += ptA.y * ptB.z; Szx += ptA.z * ptB.x; Szy += ptA.z * ptB.y; Szz += ptA.z * ptB.z; } retStddev[0] = JU.Measure.getRmsd (centerAndPoints, q); var N = Clazz.newDoubleArray (4, 4, 0); N[0][0] = Sxx + Syy + Szz; N[0][1] = N[1][0] = Syz - Szy; N[0][2] = N[2][0] = Szx - Sxz; N[0][3] = N[3][0] = Sxy - Syx; N[1][1] = Sxx - Syy - Szz; N[1][2] = N[2][1] = Sxy + Syx; N[1][3] = N[3][1] = Szx + Sxz; N[2][2] = -Sxx + Syy - Szz; N[2][3] = N[3][2] = Syz + Szy; N[3][3] = -Sxx - Syy + Szz; var v = (javajs.api.Interface.getInterface ("JU.Eigen")).setM (N).getEigenvectorsFloatTransposed ()[3]; q = JU.Quat.newP4 (JU.P4.new4 (v[1], v[2], v[3], v[0])); retStddev[1] = JU.Measure.getRmsd (centerAndPoints, q); return q; }, "~A,~A"); c$.getTransformMatrix4 = Clazz.defineMethod (c$, "getTransformMatrix4", function (ptsA, ptsB, m, centerA) { var cptsA = JU.Measure.getCenterAndPoints (ptsA); var cptsB = JU.Measure.getCenterAndPoints (ptsB); var retStddev = Clazz.newFloatArray (2, 0); var q = JU.Measure.calculateQuaternionRotation ( Clazz.newArray (-1, [cptsA, cptsB]), retStddev); var r = q.getMatrix (); if (centerA == null) r.rotate (cptsA[0]); else centerA.setT (cptsA[0]); var t = JU.V3.newVsub (cptsB[0], cptsA[0]); m.setMV (r, t); return retStddev[1]; }, "JU.Lst,JU.Lst,JU.M4,JU.P3"); c$.getCenterAndPoints = Clazz.defineMethod (c$, "getCenterAndPoints", function (vPts) { var n = vPts.size (); var pts = new Array (n + 1); pts[0] = new JU.P3 (); if (n > 0) { for (var i = 0; i < n; i++) { pts[0].add (pts[i + 1] = vPts.get (i)); } pts[0].scale (1 / n); }return pts; }, "JU.Lst"); c$.getRmsd = Clazz.defineMethod (c$, "getRmsd", function (centerAndPoints, q) { var sum2 = 0; var ptsA = centerAndPoints[0]; var ptsB = centerAndPoints[1]; var cA = ptsA[0]; var cB = ptsB[0]; var n = ptsA.length - 1; var ptAnew = new JU.P3 (); for (var i = n + 1; --i >= 1; ) { ptAnew.sub2 (ptsA[i], cA); q.transform2 (ptAnew, ptAnew).add (cB); sum2 += ptAnew.distanceSquared (ptsB[i]); } return Math.sqrt (sum2 / n); }, "~A,JU.Quat"); Clazz.defineStatics (c$, "radiansPerDegree", (0.017453292519943295)); c$.axisY = c$.prototype.axisY = JU.V3.new3 (0, 1, 0); });
sandipde/Interactive-Sketchmap-Visualizer
static/jmol/j2s/JU/Measure.js
JavaScript
mit
15,234
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2011 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreQuake3Shader.h" #include "OgreSceneManager.h" #include "OgreMaterial.h" #include "OgreTechnique.h" #include "OgrePass.h" #include "OgreTextureUnitState.h" #include "OgreMath.h" #include "OgreLogManager.h" #include "OgreTextureManager.h" #include "OgreRoot.h" #include "OgreMaterialManager.h" namespace Ogre { //----------------------------------------------------------------------- Quake3Shader::Quake3Shader(const String& name) { mName = name; numPasses = 0; deformFunc = DEFORM_FUNC_NONE; farbox = false; skyDome = false; flags = 0; fog = false; cullMode = MANUAL_CULL_BACK; } //----------------------------------------------------------------------- Quake3Shader::~Quake3Shader() { } //----------------------------------------------------------------------- MaterialPtr Quake3Shader::createAsMaterial(int lightmapNumber) { String matName; StringUtil::StrStreamType str; String resourceGroup = ResourceGroupManager::getSingleton().getWorldResourceGroupName(); str << mName << "#" << lightmapNumber; matName = str.str(); MaterialPtr mat = MaterialManager::getSingleton().create(matName, resourceGroup); Ogre::Pass* ogrePass = mat->getTechnique(0)->getPass(0); LogManager::getSingleton().logMessage("Using Q3 shader " + mName, LML_CRITICAL); for (int p = 0; p < numPasses; ++p) { TextureUnitState* t; // Create basic texture if (pass[p].textureName == "$lightmap") { StringUtil::StrStreamType str2; str2 << "@lightmap" << lightmapNumber; t = ogrePass->createTextureUnitState(str2.str()); } // Animated texture support else if (pass[p].animNumFrames > 0) { Real sequenceTime = pass[p].animNumFrames / pass[p].animFps; /* Pre-load textures We need to know if each one was loaded OK since extensions may change for each Quake3 can still include alternate extension filenames e.g. jpg instead of tga Pain in the arse - have to check for each frame as letters<n>.tga for example is different per frame! */ for (unsigned int alt = 0; alt < pass[p].animNumFrames; ++alt) { if (!ResourceGroupManager::getSingleton().resourceExists( resourceGroup, pass[p].frames[alt])) { // Try alternate extension pass[p].frames[alt] = getAlternateName(pass[p].frames[alt]); if (!ResourceGroupManager::getSingleton().resourceExists( resourceGroup, pass[p].frames[alt])) { // stuffed - no texture continue; } } } t = ogrePass->createTextureUnitState(""); t->setAnimatedTextureName(pass[p].frames, pass[p].animNumFrames, sequenceTime); } else { // Quake3 can still include alternate extension filenames e.g. jpg instead of tga // Pain in the arse - have to check for failure if (!ResourceGroupManager::getSingleton().resourceExists( resourceGroup, pass[p].textureName)) { // Try alternate extension pass[p].textureName = getAlternateName(pass[p].textureName); if (!ResourceGroupManager::getSingleton().resourceExists( resourceGroup, pass[p].textureName)) { // stuffed - no texture continue; } } t = ogrePass->createTextureUnitState(pass[p].textureName); } // Blending if (p == 0) { // scene blend mat->setSceneBlending(pass[p].blendSrc, pass[p].blendDest); if (mat->isTransparent()) mat->setDepthWriteEnabled(false); t->setColourOperation(LBO_REPLACE); // Alpha mode ogrePass->setAlphaRejectSettings( pass[p].alphaFunc, pass[p].alphaVal); } else { if (pass[p].customBlend) { // Fallback for now t->setColourOperation(LBO_MODULATE); } else { // simple layer blend t->setColourOperation(pass[p].blend); } // Alpha mode, prefer 'most alphary' CompareFunction currFunc = ogrePass->getAlphaRejectFunction(); unsigned char currVal = ogrePass->getAlphaRejectValue(); if (pass[p].alphaFunc > currFunc || (pass[p].alphaFunc == currFunc && pass[p].alphaVal < currVal)) { ogrePass->setAlphaRejectSettings( pass[p].alphaFunc, pass[p].alphaVal); } } // Tex coords if (pass[p].texGen == TEXGEN_BASE) { t->setTextureCoordSet(0); } else if (pass[p].texGen == TEXGEN_LIGHTMAP) { t->setTextureCoordSet(1); } else if (pass[p].texGen == TEXGEN_ENVIRONMENT) { t->setEnvironmentMap(true, TextureUnitState::ENV_PLANAR); } // Tex mod // Scale t->setTextureUScale(pass[p].tcModScale[0]); t->setTextureVScale(pass[p].tcModScale[1]); // Procedural mods // Custom - don't use mod if generating environment // Because I do env a different way it look horrible if (pass[p].texGen != TEXGEN_ENVIRONMENT) { if (pass[p].tcModRotate) { t->setRotateAnimation(pass[p].tcModRotate); } if (pass[p].tcModScroll[0] || pass[p].tcModScroll[1]) { if (pass[p].tcModTurbOn) { // Turbulent scroll if (pass[p].tcModScroll[0]) { t->setTransformAnimation(TextureUnitState::TT_TRANSLATE_U, WFT_SINE, pass[p].tcModTurb[0], pass[p].tcModTurb[3], pass[p].tcModTurb[2], pass[p].tcModTurb[1]); } if (pass[p].tcModScroll[1]) { t->setTransformAnimation(TextureUnitState::TT_TRANSLATE_V, WFT_SINE, pass[p].tcModTurb[0], pass[p].tcModTurb[3], pass[p].tcModTurb[2], pass[p].tcModTurb[1]); } } else { // Constant scroll t->setScrollAnimation(pass[p].tcModScroll[0], pass[p].tcModScroll[1]); } } if (pass[p].tcModStretchWave != SHADER_FUNC_NONE) { WaveformType wft = WFT_SINE; switch(pass[p].tcModStretchWave) { case SHADER_FUNC_SIN: wft = WFT_SINE; break; case SHADER_FUNC_TRIANGLE: wft = WFT_TRIANGLE; break; case SHADER_FUNC_SQUARE: wft = WFT_SQUARE; break; case SHADER_FUNC_SAWTOOTH: wft = WFT_SAWTOOTH; break; case SHADER_FUNC_INVERSESAWTOOTH: wft = WFT_INVERSE_SAWTOOTH; break; default: break; } // Create wave-based stretcher t->setTransformAnimation(TextureUnitState::TT_SCALE_U, wft, pass[p].tcModStretchParams[3], pass[p].tcModStretchParams[0], pass[p].tcModStretchParams[2], pass[p].tcModStretchParams[1]); t->setTransformAnimation(TextureUnitState::TT_SCALE_V, wft, pass[p].tcModStretchParams[3], pass[p].tcModStretchParams[0], pass[p].tcModStretchParams[2], pass[p].tcModStretchParams[1]); } } // Address mode t->setTextureAddressingMode(pass[p].addressMode); //assert(!t->isBlank()); } // Do farbox (create new material) // Set culling mode and lighting to defaults mat->setCullingMode(CULL_NONE); mat->setManualCullingMode(cullMode); mat->setLightingEnabled(false); mat->load(); return mat; } String Quake3Shader::getAlternateName(const String& texName) { // Get alternative JPG to TGA and vice versa size_t pos; String ext, base; pos = texName.find_last_of("."); ext = texName.substr(pos, 4); StringUtil::toLowerCase(ext); base = texName.substr(0,pos); if (ext == ".jpg") { return base + ".tga"; } else { return base + ".jpg"; } } }
ruleless/ogre
PlugIns/BSPSceneManager/src/OgreQuake3Shader.cpp
C++
mit
11,012
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\TestModuleMSC\Model; use Magento\TestModuleMSC\Api\Data\CustomAttributeDataObjectInterfaceFactory; use Magento\TestModuleMSC\Api\Data\ItemInterfaceFactory; class AllSoapAndRest implements \Magento\TestModuleMSC\Api\AllSoapAndRestInterface { /** * @var ItemInterfaceFactory */ protected $itemDataFactory; /** * @var CustomAttributeDataObjectInterfaceFactory */ protected $customAttributeDataObjectDataFactory; /** * @param ItemInterfaceFactory $itemDataFactory * @param CustomAttributeDataObjectInterfaceFactory $customAttributeNestedDataObjectFactory */ public function __construct( ItemInterfaceFactory $itemDataFactory, CustomAttributeDataObjectInterfaceFactory $customAttributeNestedDataObjectFactory ) { $this->itemDataFactory = $itemDataFactory; $this->customAttributeDataObjectDataFactory = $customAttributeNestedDataObjectFactory; } /** * {@inheritdoc} */ public function item($itemId) { return $this->itemDataFactory->create()->setItemId($itemId)->setName('testProduct1'); } /** * {@inheritdoc} */ public function items() { $result1 = $this->itemDataFactory->create()->setItemId(1)->setName('testProduct1'); $result2 = $this->itemDataFactory->create()->setItemId(2)->setName('testProduct2'); return [$result1, $result2]; } /** * {@inheritdoc} */ public function create($name) { return $this->itemDataFactory->create()->setItemId(rand())->setName($name); } /** * {@inheritdoc} */ public function update(\Magento\TestModuleMSC\Api\Data\ItemInterface $entityItem) { return $this->itemDataFactory->create()->setItemId($entityItem->getItemId()) ->setName('Updated' . $entityItem->getName()); } public function testOptionalParam($name = null) { if ($name === null) { return $this->itemDataFactory->create()->setItemId(3)->setName('No Name'); } else { return $this->itemDataFactory->create()->setItemId(3)->setName($name); } } /** * {@inheritdoc} */ public function itemAnyType(\Magento\TestModuleMSC\Api\Data\ItemInterface $entityItem) { return $entityItem; } /** * {@inheritdoc} */ public function getPreconfiguredItem() { $customAttributeDataObject = $this->customAttributeDataObjectDataFactory->create() ->setName('nameValue') ->setCustomAttribute('custom_attribute_int', 1); $item = $this->itemDataFactory->create() ->setItemId(1) ->setName('testProductAnyType') ->setCustomAttribute('custom_attribute_data_object', $customAttributeDataObject) ->setCustomAttribute('custom_attribute_string', 'someStringValue'); return $item; } }
j-froehlich/magento2_wk
vendor/magento/magento2-base/dev/tests/api-functional/_files/Magento/TestModuleMSC/Model/AllSoapAndRest.php
PHP
mit
3,062
# This file is auto-generated by the Perl DateTime Suite time zone # code generator (0.07) This code generator comes with the # DateTime::TimeZone module distribution in the tools/ directory # # Generated from /tmp/rnClxBLdxJ/northamerica. Olson data version 2013a # # Do not edit this file directly. # package DateTime::TimeZone::America::St_Lucia; { $DateTime::TimeZone::America::St_Lucia::VERSION = '1.57'; } use strict; use Class::Singleton 1.03; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::America::St_Lucia::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, # utc_start 59611176240, # utc_end 1890-01-01 04:04:00 (Wed) DateTime::TimeZone::NEG_INFINITY, # local_start 59611161600, # local_end 1890-01-01 00:00:00 (Wed) -14640, 0, 'LMT', ], [ 59611176240, # utc_start 1890-01-01 04:04:00 (Wed) 60305313840, # utc_end 1912-01-01 04:04:00 (Mon) 59611161600, # local_start 1890-01-01 00:00:00 (Wed) 60305299200, # local_end 1912-01-01 00:00:00 (Mon) -14640, 0, 'CMT', ], [ 60305313840, # utc_start 1912-01-01 04:04:00 (Mon) DateTime::TimeZone::INFINITY, # utc_end 60305299440, # local_start 1912-01-01 00:04:00 (Mon) DateTime::TimeZone::INFINITY, # local_end -14400, 0, 'AST', ], ]; sub olson_version { '2013a' } sub has_dst_changes { 0 } sub _max_year { 2023 } sub _new_instance { return shift->_init( @_, spans => $spans ); } 1;
Dokaponteam/ITF_Project
xampp/perl/vendor/lib/DateTime/TimeZone/America/St_Lucia.pm
Perl
mit
1,498
import Ember from 'ember'; export default Ember.Object.extend({ content: {}, contentLength: 0, add: function(obj) { var id = this.generateId(); this.get('content')[id] = obj; this.incrementProperty("contentLength"); return id; }, getObj: function(key) { var res = this.get('content')[key]; if (!res) { throw "no obj for key "+key; } return res; }, generateId: function() { var num = Math.random() * 1000000000000.0; num = parseInt(num); num = ""+num; return num; }, keys: function() { var res = []; for (var key in this.get('content')) { res.push(key); } return Ember.A(res); }, lengthBinding: "contentLength" });
bdvholmes/ember-drag-drop
app/models/obj-hash.js
JavaScript
mit
717
/* * Core routines and tables shareable across OS platforms. * * Copyright (c) 1994-2002 Justin T. Gibbs. * Copyright (c) 2000-2003 Adaptec Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * NO WARRANTY * 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 MERCHANTIBILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. * * $Id: //depot/aic7xxx/aic7xxx/aic79xx.c#250 $ */ #ifdef __linux__ #include "aic79xx_osm.h" #include "aic79xx_inline.h" #include "aicasm/aicasm_insformat.h" #else #include <dev/aic7xxx/aic79xx_osm.h> #include <dev/aic7xxx/aic79xx_inline.h> #include <dev/aic7xxx/aicasm/aicasm_insformat.h> #endif /***************************** Lookup Tables **********************************/ static char *ahd_chip_names[] = { "NONE", "aic7901", "aic7902", "aic7901A" }; static const u_int num_chip_names = ARRAY_SIZE(ahd_chip_names); /* * Hardware error codes. */ struct ahd_hard_error_entry { uint8_t errno; char *errmesg; }; static struct ahd_hard_error_entry ahd_hard_errors[] = { { DSCTMOUT, "Discard Timer has timed out" }, { ILLOPCODE, "Illegal Opcode in sequencer program" }, { SQPARERR, "Sequencer Parity Error" }, { DPARERR, "Data-path Parity Error" }, { MPARERR, "Scratch or SCB Memory Parity Error" }, { CIOPARERR, "CIOBUS Parity Error" }, }; static const u_int num_errors = ARRAY_SIZE(ahd_hard_errors); static struct ahd_phase_table_entry ahd_phase_table[] = { { P_DATAOUT, MSG_NOOP, "in Data-out phase" }, { P_DATAIN, MSG_INITIATOR_DET_ERR, "in Data-in phase" }, { P_DATAOUT_DT, MSG_NOOP, "in DT Data-out phase" }, { P_DATAIN_DT, MSG_INITIATOR_DET_ERR, "in DT Data-in phase" }, { P_COMMAND, MSG_NOOP, "in Command phase" }, { P_MESGOUT, MSG_NOOP, "in Message-out phase" }, { P_STATUS, MSG_INITIATOR_DET_ERR, "in Status phase" }, { P_MESGIN, MSG_PARITY_ERROR, "in Message-in phase" }, { P_BUSFREE, MSG_NOOP, "while idle" }, { 0, MSG_NOOP, "in unknown phase" } }; /* * In most cases we only wish to itterate over real phases, so * exclude the last element from the count. */ static const u_int num_phases = ARRAY_SIZE(ahd_phase_table) - 1; /* Our Sequencer Program */ #include "aic79xx_seq.h" /**************************** Function Declarations ***************************/ static void ahd_handle_transmission_error(struct ahd_softc *ahd); static void ahd_handle_lqiphase_error(struct ahd_softc *ahd, u_int lqistat1); static int ahd_handle_pkt_busfree(struct ahd_softc *ahd, u_int busfreetime); static int ahd_handle_nonpkt_busfree(struct ahd_softc *ahd); static void ahd_handle_proto_violation(struct ahd_softc *ahd); static void ahd_force_renegotiation(struct ahd_softc *ahd, struct ahd_devinfo *devinfo); static struct ahd_tmode_tstate* ahd_alloc_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel); #ifdef AHD_TARGET_MODE static void ahd_free_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel, int force); #endif static void ahd_devlimited_syncrate(struct ahd_softc *ahd, struct ahd_initiator_tinfo *, u_int *period, u_int *ppr_options, role_t role); static void ahd_update_neg_table(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, struct ahd_transinfo *tinfo); static void ahd_update_pending_scbs(struct ahd_softc *ahd); static void ahd_fetch_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo); static void ahd_scb_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, struct scb *scb); static void ahd_setup_initiator_msgout(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, struct scb *scb); static void ahd_build_transfer_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo); static void ahd_construct_sdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, u_int period, u_int offset); static void ahd_construct_wdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, u_int bus_width); static void ahd_construct_ppr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, u_int period, u_int offset, u_int bus_width, u_int ppr_options); static void ahd_clear_msg_state(struct ahd_softc *ahd); static void ahd_handle_message_phase(struct ahd_softc *ahd); typedef enum { AHDMSG_1B, AHDMSG_2B, AHDMSG_EXT } ahd_msgtype; static int ahd_sent_msg(struct ahd_softc *ahd, ahd_msgtype type, u_int msgval, int full); static int ahd_parse_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo); static int ahd_handle_msg_reject(struct ahd_softc *ahd, struct ahd_devinfo *devinfo); static void ahd_handle_ign_wide_residue(struct ahd_softc *ahd, struct ahd_devinfo *devinfo); static void ahd_reinitialize_dataptrs(struct ahd_softc *ahd); static void ahd_handle_devreset(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, u_int lun, cam_status status, char *message, int verbose_level); #ifdef AHD_TARGET_MODE static void ahd_setup_target_msgin(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, struct scb *scb); #endif static u_int ahd_sglist_size(struct ahd_softc *ahd); static u_int ahd_sglist_allocsize(struct ahd_softc *ahd); static bus_dmamap_callback_t ahd_dmamap_cb; static void ahd_initialize_hscbs(struct ahd_softc *ahd); static int ahd_init_scbdata(struct ahd_softc *ahd); static void ahd_fini_scbdata(struct ahd_softc *ahd); static void ahd_setup_iocell_workaround(struct ahd_softc *ahd); static void ahd_iocell_first_selection(struct ahd_softc *ahd); static void ahd_add_col_list(struct ahd_softc *ahd, struct scb *scb, u_int col_idx); static void ahd_rem_col_list(struct ahd_softc *ahd, struct scb *scb); static void ahd_chip_init(struct ahd_softc *ahd); static void ahd_qinfifo_requeue(struct ahd_softc *ahd, struct scb *prev_scb, struct scb *scb); static int ahd_qinfifo_count(struct ahd_softc *ahd); static int ahd_search_scb_list(struct ahd_softc *ahd, int target, char channel, int lun, u_int tag, role_t role, uint32_t status, ahd_search_action action, u_int *list_head, u_int *list_tail, u_int tid); static void ahd_stitch_tid_list(struct ahd_softc *ahd, u_int tid_prev, u_int tid_cur, u_int tid_next); static void ahd_add_scb_to_free_list(struct ahd_softc *ahd, u_int scbid); static u_int ahd_rem_wscb(struct ahd_softc *ahd, u_int scbid, u_int prev, u_int next, u_int tid); static void ahd_reset_current_bus(struct ahd_softc *ahd); static ahd_callback_t ahd_stat_timer; #ifdef AHD_DUMP_SEQ static void ahd_dumpseq(struct ahd_softc *ahd); #endif static void ahd_loadseq(struct ahd_softc *ahd); static int ahd_check_patch(struct ahd_softc *ahd, struct patch **start_patch, u_int start_instr, u_int *skip_addr); static u_int ahd_resolve_seqaddr(struct ahd_softc *ahd, u_int address); static void ahd_download_instr(struct ahd_softc *ahd, u_int instrptr, uint8_t *dconsts); static int ahd_probe_stack_size(struct ahd_softc *ahd); static int ahd_scb_active_in_fifo(struct ahd_softc *ahd, struct scb *scb); static void ahd_run_data_fifo(struct ahd_softc *ahd, struct scb *scb); #ifdef AHD_TARGET_MODE static void ahd_queue_lstate_event(struct ahd_softc *ahd, struct ahd_tmode_lstate *lstate, u_int initiator_id, u_int event_type, u_int event_arg); static void ahd_update_scsiid(struct ahd_softc *ahd, u_int targid_mask); static int ahd_handle_target_cmd(struct ahd_softc *ahd, struct target_cmd *cmd); #endif static int ahd_abort_scbs(struct ahd_softc *ahd, int target, char channel, int lun, u_int tag, role_t role, uint32_t status); static void ahd_alloc_scbs(struct ahd_softc *ahd); static void ahd_busy_tcl(struct ahd_softc *ahd, u_int tcl, u_int scbid); static void ahd_calc_residual(struct ahd_softc *ahd, struct scb *scb); static void ahd_clear_critical_section(struct ahd_softc *ahd); static void ahd_clear_intstat(struct ahd_softc *ahd); static void ahd_enable_coalescing(struct ahd_softc *ahd, int enable); static u_int ahd_find_busy_tcl(struct ahd_softc *ahd, u_int tcl); static void ahd_freeze_devq(struct ahd_softc *ahd, struct scb *scb); static void ahd_handle_scb_status(struct ahd_softc *ahd, struct scb *scb); static struct ahd_phase_table_entry* ahd_lookup_phase_entry(int phase); static void ahd_shutdown(void *arg); static void ahd_update_coalescing_values(struct ahd_softc *ahd, u_int timer, u_int maxcmds, u_int mincmds); static int ahd_verify_vpd_cksum(struct vpd_config *vpd); static int ahd_wait_seeprom(struct ahd_softc *ahd); static int ahd_match_scb(struct ahd_softc *ahd, struct scb *scb, int target, char channel, int lun, u_int tag, role_t role); /******************************** Private Inlines *****************************/ static __inline void ahd_assert_atn(struct ahd_softc *ahd) { ahd_outb(ahd, SCSISIGO, ATNO); } /* * Determine if the current connection has a packetized * agreement. This does not necessarily mean that we * are currently in a packetized transfer. We could * just as easily be sending or receiving a message. */ static __inline int ahd_currently_packetized(struct ahd_softc *ahd) { ahd_mode_state saved_modes; int packetized; saved_modes = ahd_save_modes(ahd); if ((ahd->bugs & AHD_PKTIZED_STATUS_BUG) != 0) { /* * The packetized bit refers to the last * connection, not the current one. Check * for non-zero LQISTATE instead. */ ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG); packetized = ahd_inb(ahd, LQISTATE) != 0; } else { ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); packetized = ahd_inb(ahd, LQISTAT2) & PACKETIZED; } ahd_restore_modes(ahd, saved_modes); return (packetized); } static __inline int ahd_set_active_fifo(struct ahd_softc *ahd) { u_int active_fifo; AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); active_fifo = ahd_inb(ahd, DFFSTAT) & CURRFIFO; switch (active_fifo) { case 0: case 1: ahd_set_modes(ahd, active_fifo, active_fifo); return (1); default: return (0); } } static __inline void ahd_unbusy_tcl(struct ahd_softc *ahd, u_int tcl) { ahd_busy_tcl(ahd, tcl, SCB_LIST_NULL); } /* * Determine whether the sequencer reported a residual * for this SCB/transaction. */ static __inline void ahd_update_residual(struct ahd_softc *ahd, struct scb *scb) { uint32_t sgptr; sgptr = ahd_le32toh(scb->hscb->sgptr); if ((sgptr & SG_STATUS_VALID) != 0) ahd_calc_residual(ahd, scb); } static __inline void ahd_complete_scb(struct ahd_softc *ahd, struct scb *scb) { uint32_t sgptr; sgptr = ahd_le32toh(scb->hscb->sgptr); if ((sgptr & SG_STATUS_VALID) != 0) ahd_handle_scb_status(ahd, scb); else ahd_done(ahd, scb); } /************************* Sequencer Execution Control ************************/ /* * Restart the sequencer program from address zero */ static void ahd_restart(struct ahd_softc *ahd) { ahd_pause(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); /* No more pending messages */ ahd_clear_msg_state(ahd); ahd_outb(ahd, SCSISIGO, 0); /* De-assert BSY */ ahd_outb(ahd, MSG_OUT, MSG_NOOP); /* No message to send */ ahd_outb(ahd, SXFRCTL1, ahd_inb(ahd, SXFRCTL1) & ~BITBUCKET); ahd_outb(ahd, SEQINTCTL, 0); ahd_outb(ahd, LASTPHASE, P_BUSFREE); ahd_outb(ahd, SEQ_FLAGS, 0); ahd_outb(ahd, SAVED_SCSIID, 0xFF); ahd_outb(ahd, SAVED_LUN, 0xFF); /* * Ensure that the sequencer's idea of TQINPOS * matches our own. The sequencer increments TQINPOS * only after it sees a DMA complete and a reset could * occur before the increment leaving the kernel to believe * the command arrived but the sequencer to not. */ ahd_outb(ahd, TQINPOS, ahd->tqinfifonext); /* Always allow reselection */ ahd_outb(ahd, SCSISEQ1, ahd_inb(ahd, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP)); ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN); /* * Clear any pending sequencer interrupt. It is no * longer relevant since we're resetting the Program * Counter. */ ahd_outb(ahd, CLRINT, CLRSEQINT); ahd_outb(ahd, SEQCTL0, FASTMODE|SEQRESET); ahd_unpause(ahd); } static void ahd_clear_fifo(struct ahd_softc *ahd, u_int fifo) { ahd_mode_state saved_modes; #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_FIFOS) != 0) printf("%s: Clearing FIFO %d\n", ahd_name(ahd), fifo); #endif saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, fifo, fifo); ahd_outb(ahd, DFFSXFRCTL, RSTCHN|CLRSHCNT); if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0) ahd_outb(ahd, CCSGCTL, CCSGRESET); ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR); ahd_outb(ahd, SG_STATE, 0); ahd_restore_modes(ahd, saved_modes); } /************************* Input/Output Queues ********************************/ /* * Flush and completed commands that are sitting in the command * complete queues down on the chip but have yet to be dma'ed back up. */ static void ahd_flush_qoutfifo(struct ahd_softc *ahd) { struct scb *scb; ahd_mode_state saved_modes; u_int saved_scbptr; u_int ccscbctl; u_int scbid; u_int next_scbid; saved_modes = ahd_save_modes(ahd); /* * Flush the good status FIFO for completed packetized commands. */ ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); saved_scbptr = ahd_get_scbptr(ahd); while ((ahd_inb(ahd, LQISTAT2) & LQIGSAVAIL) != 0) { u_int fifo_mode; u_int i; scbid = ahd_inw(ahd, GSFIFO); scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { printf("%s: Warning - GSFIFO SCB %d invalid\n", ahd_name(ahd), scbid); continue; } /* * Determine if this transaction is still active in * any FIFO. If it is, we must flush that FIFO to * the host before completing the command. */ fifo_mode = 0; rescan_fifos: for (i = 0; i < 2; i++) { /* Toggle to the other mode. */ fifo_mode ^= 1; ahd_set_modes(ahd, fifo_mode, fifo_mode); if (ahd_scb_active_in_fifo(ahd, scb) == 0) continue; ahd_run_data_fifo(ahd, scb); /* * Running this FIFO may cause a CFG4DATA for * this same transaction to assert in the other * FIFO or a new snapshot SAVEPTRS interrupt * in this FIFO. Even running a FIFO may not * clear the transaction if we are still waiting * for data to drain to the host. We must loop * until the transaction is not active in either * FIFO just to be sure. Reset our loop counter * so we will visit both FIFOs again before * declaring this transaction finished. We * also delay a bit so that status has a chance * to change before we look at this FIFO again. */ ahd_delay(200); goto rescan_fifos; } ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); ahd_set_scbptr(ahd, scbid); if ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_LIST_NULL) == 0 && ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_FULL_RESID) != 0 || (ahd_inb_scbram(ahd, SCB_RESIDUAL_SGPTR) & SG_LIST_NULL) != 0)) { u_int comp_head; /* * The transfer completed with a residual. * Place this SCB on the complete DMA list * so that we update our in-core copy of the * SCB before completing the command. */ ahd_outb(ahd, SCB_SCSI_STATUS, 0); ahd_outb(ahd, SCB_SGPTR, ahd_inb_scbram(ahd, SCB_SGPTR) | SG_STATUS_VALID); ahd_outw(ahd, SCB_TAG, scbid); ahd_outw(ahd, SCB_NEXT_COMPLETE, SCB_LIST_NULL); comp_head = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD); if (SCBID_IS_NULL(comp_head)) { ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, scbid); ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid); } else { u_int tail; tail = ahd_inw(ahd, COMPLETE_DMA_SCB_TAIL); ahd_set_scbptr(ahd, tail); ahd_outw(ahd, SCB_NEXT_COMPLETE, scbid); ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid); ahd_set_scbptr(ahd, scbid); } } else ahd_complete_scb(ahd, scb); } ahd_set_scbptr(ahd, saved_scbptr); /* * Setup for command channel portion of flush. */ ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN); /* * Wait for any inprogress DMA to complete and clear DMA state * if this if for an SCB in the qinfifo. */ while (((ccscbctl = ahd_inb(ahd, CCSCBCTL)) & (CCARREN|CCSCBEN)) != 0) { if ((ccscbctl & (CCSCBDIR|CCARREN)) == (CCSCBDIR|CCARREN)) { if ((ccscbctl & ARRDONE) != 0) break; } else if ((ccscbctl & CCSCBDONE) != 0) break; ahd_delay(200); } /* * We leave the sequencer to cleanup in the case of DMA's to * update the qoutfifo. In all other cases (DMA's to the * chip or a push of an SCB from the COMPLETE_DMA_SCB list), * we disable the DMA engine so that the sequencer will not * attempt to handle the DMA completion. */ if ((ccscbctl & CCSCBDIR) != 0 || (ccscbctl & ARRDONE) != 0) ahd_outb(ahd, CCSCBCTL, ccscbctl & ~(CCARREN|CCSCBEN)); /* * Complete any SCBs that just finished * being DMA'ed into the qoutfifo. */ ahd_run_qoutfifo(ahd); saved_scbptr = ahd_get_scbptr(ahd); /* * Manually update/complete any completed SCBs that are waiting to be * DMA'ed back up to the host. */ scbid = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD); while (!SCBID_IS_NULL(scbid)) { uint8_t *hscb_ptr; u_int i; ahd_set_scbptr(ahd, scbid); next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE); scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { printf("%s: Warning - DMA-up and complete " "SCB %d invalid\n", ahd_name(ahd), scbid); continue; } hscb_ptr = (uint8_t *)scb->hscb; for (i = 0; i < sizeof(struct hardware_scb); i++) *hscb_ptr++ = ahd_inb_scbram(ahd, SCB_BASE + i); ahd_complete_scb(ahd, scb); scbid = next_scbid; } ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, SCB_LIST_NULL); ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, SCB_LIST_NULL); scbid = ahd_inw(ahd, COMPLETE_ON_QFREEZE_HEAD); while (!SCBID_IS_NULL(scbid)) { ahd_set_scbptr(ahd, scbid); next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE); scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { printf("%s: Warning - Complete Qfrz SCB %d invalid\n", ahd_name(ahd), scbid); continue; } ahd_complete_scb(ahd, scb); scbid = next_scbid; } ahd_outw(ahd, COMPLETE_ON_QFREEZE_HEAD, SCB_LIST_NULL); scbid = ahd_inw(ahd, COMPLETE_SCB_HEAD); while (!SCBID_IS_NULL(scbid)) { ahd_set_scbptr(ahd, scbid); next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE); scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { printf("%s: Warning - Complete SCB %d invalid\n", ahd_name(ahd), scbid); continue; } ahd_complete_scb(ahd, scb); scbid = next_scbid; } ahd_outw(ahd, COMPLETE_SCB_HEAD, SCB_LIST_NULL); /* * Restore state. */ ahd_set_scbptr(ahd, saved_scbptr); ahd_restore_modes(ahd, saved_modes); ahd->flags |= AHD_UPDATE_PEND_CMDS; } /* * Determine if an SCB for a packetized transaction * is active in a FIFO. */ static int ahd_scb_active_in_fifo(struct ahd_softc *ahd, struct scb *scb) { /* * The FIFO is only active for our transaction if * the SCBPTR matches the SCB's ID and the firmware * has installed a handler for the FIFO or we have * a pending SAVEPTRS or CFG4DATA interrupt. */ if (ahd_get_scbptr(ahd) != SCB_GET_TAG(scb) || ((ahd_inb(ahd, LONGJMP_ADDR+1) & INVALID_ADDR) != 0 && (ahd_inb(ahd, SEQINTSRC) & (CFG4DATA|SAVEPTRS)) == 0)) return (0); return (1); } /* * Run a data fifo to completion for a transaction we know * has completed across the SCSI bus (good status has been * received). We are already set to the correct FIFO mode * on entry to this routine. * * This function attempts to operate exactly as the firmware * would when running this FIFO. Care must be taken to update * this routine any time the firmware's FIFO algorithm is * changed. */ static void ahd_run_data_fifo(struct ahd_softc *ahd, struct scb *scb) { u_int seqintsrc; seqintsrc = ahd_inb(ahd, SEQINTSRC); if ((seqintsrc & CFG4DATA) != 0) { uint32_t datacnt; uint32_t sgptr; /* * Clear full residual flag. */ sgptr = ahd_inl_scbram(ahd, SCB_SGPTR) & ~SG_FULL_RESID; ahd_outb(ahd, SCB_SGPTR, sgptr); /* * Load datacnt and address. */ datacnt = ahd_inl_scbram(ahd, SCB_DATACNT); if ((datacnt & AHD_DMA_LAST_SEG) != 0) { sgptr |= LAST_SEG; ahd_outb(ahd, SG_STATE, 0); } else ahd_outb(ahd, SG_STATE, LOADING_NEEDED); ahd_outq(ahd, HADDR, ahd_inq_scbram(ahd, SCB_DATAPTR)); ahd_outl(ahd, HCNT, datacnt & AHD_SG_LEN_MASK); ahd_outb(ahd, SG_CACHE_PRE, sgptr); ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN); /* * Initialize Residual Fields. */ ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, datacnt >> 24); ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr & SG_PTR_MASK); /* * Mark the SCB as having a FIFO in use. */ ahd_outb(ahd, SCB_FIFO_USE_COUNT, ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) + 1); /* * Install a "fake" handler for this FIFO. */ ahd_outw(ahd, LONGJMP_ADDR, 0); /* * Notify the hardware that we have satisfied * this sequencer interrupt. */ ahd_outb(ahd, CLRSEQINTSRC, CLRCFG4DATA); } else if ((seqintsrc & SAVEPTRS) != 0) { uint32_t sgptr; uint32_t resid; if ((ahd_inb(ahd, LONGJMP_ADDR+1)&INVALID_ADDR) != 0) { /* * Snapshot Save Pointers. All that * is necessary to clear the snapshot * is a CLRCHN. */ goto clrchn; } /* * Disable S/G fetch so the DMA engine * is available to future users. */ if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0) ahd_outb(ahd, CCSGCTL, 0); ahd_outb(ahd, SG_STATE, 0); /* * Flush the data FIFO. Strickly only * necessary for Rev A parts. */ ahd_outb(ahd, DFCNTRL, ahd_inb(ahd, DFCNTRL) | FIFOFLUSH); /* * Calculate residual. */ sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR); resid = ahd_inl(ahd, SHCNT); resid |= ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT+3) << 24; ahd_outl(ahd, SCB_RESIDUAL_DATACNT, resid); if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG) == 0) { /* * Must back up to the correct S/G element. * Typically this just means resetting our * low byte to the offset in the SG_CACHE, * but if we wrapped, we have to correct * the other bytes of the sgptr too. */ if ((ahd_inb(ahd, SG_CACHE_SHADOW) & 0x80) != 0 && (sgptr & 0x80) == 0) sgptr -= 0x100; sgptr &= ~0xFF; sgptr |= ahd_inb(ahd, SG_CACHE_SHADOW) & SG_ADDR_MASK; ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr); ahd_outb(ahd, SCB_RESIDUAL_DATACNT + 3, 0); } else if ((resid & AHD_SG_LEN_MASK) == 0) { ahd_outb(ahd, SCB_RESIDUAL_SGPTR, sgptr | SG_LIST_NULL); } /* * Save Pointers. */ ahd_outq(ahd, SCB_DATAPTR, ahd_inq(ahd, SHADDR)); ahd_outl(ahd, SCB_DATACNT, resid); ahd_outl(ahd, SCB_SGPTR, sgptr); ahd_outb(ahd, CLRSEQINTSRC, CLRSAVEPTRS); ahd_outb(ahd, SEQIMODE, ahd_inb(ahd, SEQIMODE) | ENSAVEPTRS); /* * If the data is to the SCSI bus, we are * done, otherwise wait for FIFOEMP. */ if ((ahd_inb(ahd, DFCNTRL) & DIRECTION) != 0) goto clrchn; } else if ((ahd_inb(ahd, SG_STATE) & LOADING_NEEDED) != 0) { uint32_t sgptr; uint64_t data_addr; uint32_t data_len; u_int dfcntrl; /* * Disable S/G fetch so the DMA engine * is available to future users. We won't * be using the DMA engine to load segments. */ if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0) { ahd_outb(ahd, CCSGCTL, 0); ahd_outb(ahd, SG_STATE, LOADING_NEEDED); } /* * Wait for the DMA engine to notice that the * host transfer is enabled and that there is * space in the S/G FIFO for new segments before * loading more segments. */ if ((ahd_inb(ahd, DFSTATUS) & PRELOAD_AVAIL) != 0 && (ahd_inb(ahd, DFCNTRL) & HDMAENACK) != 0) { /* * Determine the offset of the next S/G * element to load. */ sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR); sgptr &= SG_PTR_MASK; if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) { struct ahd_dma64_seg *sg; sg = ahd_sg_bus_to_virt(ahd, scb, sgptr); data_addr = sg->addr; data_len = sg->len; sgptr += sizeof(*sg); } else { struct ahd_dma_seg *sg; sg = ahd_sg_bus_to_virt(ahd, scb, sgptr); data_addr = sg->len & AHD_SG_HIGH_ADDR_MASK; data_addr <<= 8; data_addr |= sg->addr; data_len = sg->len; sgptr += sizeof(*sg); } /* * Update residual information. */ ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, data_len >> 24); ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr); /* * Load the S/G. */ if (data_len & AHD_DMA_LAST_SEG) { sgptr |= LAST_SEG; ahd_outb(ahd, SG_STATE, 0); } ahd_outq(ahd, HADDR, data_addr); ahd_outl(ahd, HCNT, data_len & AHD_SG_LEN_MASK); ahd_outb(ahd, SG_CACHE_PRE, sgptr & 0xFF); /* * Advertise the segment to the hardware. */ dfcntrl = ahd_inb(ahd, DFCNTRL)|PRELOADEN|HDMAEN; if ((ahd->features & AHD_NEW_DFCNTRL_OPTS) != 0) { /* * Use SCSIENWRDIS so that SCSIEN * is never modified by this * operation. */ dfcntrl |= SCSIENWRDIS; } ahd_outb(ahd, DFCNTRL, dfcntrl); } } else if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG_DONE) != 0) { /* * Transfer completed to the end of SG list * and has flushed to the host. */ ahd_outb(ahd, SCB_SGPTR, ahd_inb_scbram(ahd, SCB_SGPTR) | SG_LIST_NULL); goto clrchn; } else if ((ahd_inb(ahd, DFSTATUS) & FIFOEMP) != 0) { clrchn: /* * Clear any handler for this FIFO, decrement * the FIFO use count for the SCB, and release * the FIFO. */ ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR); ahd_outb(ahd, SCB_FIFO_USE_COUNT, ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) - 1); ahd_outb(ahd, DFFSXFRCTL, CLRCHN); } } /* * Look for entries in the QoutFIFO that have completed. * The valid_tag completion field indicates the validity * of the entry - the valid value toggles each time through * the queue. We use the sg_status field in the completion * entry to avoid referencing the hscb if the completion * occurred with no errors and no residual. sg_status is * a copy of the first byte (little endian) of the sgptr * hscb field. */ void ahd_run_qoutfifo(struct ahd_softc *ahd) { struct ahd_completion *completion; struct scb *scb; u_int scb_index; if ((ahd->flags & AHD_RUNNING_QOUTFIFO) != 0) panic("ahd_run_qoutfifo recursion"); ahd->flags |= AHD_RUNNING_QOUTFIFO; ahd_sync_qoutfifo(ahd, BUS_DMASYNC_POSTREAD); for (;;) { completion = &ahd->qoutfifo[ahd->qoutfifonext]; if (completion->valid_tag != ahd->qoutfifonext_valid_tag) break; scb_index = ahd_le16toh(completion->tag); scb = ahd_lookup_scb(ahd, scb_index); if (scb == NULL) { printf("%s: WARNING no command for scb %d " "(cmdcmplt)\nQOUTPOS = %d\n", ahd_name(ahd), scb_index, ahd->qoutfifonext); ahd_dump_card_state(ahd); } else if ((completion->sg_status & SG_STATUS_VALID) != 0) { ahd_handle_scb_status(ahd, scb); } else { ahd_done(ahd, scb); } ahd->qoutfifonext = (ahd->qoutfifonext+1) & (AHD_QOUT_SIZE-1); if (ahd->qoutfifonext == 0) ahd->qoutfifonext_valid_tag ^= QOUTFIFO_ENTRY_VALID; } ahd->flags &= ~AHD_RUNNING_QOUTFIFO; } /************************* Interrupt Handling *********************************/ void ahd_handle_hwerrint(struct ahd_softc *ahd) { /* * Some catastrophic hardware error has occurred. * Print it for the user and disable the controller. */ int i; int error; error = ahd_inb(ahd, ERROR); for (i = 0; i < num_errors; i++) { if ((error & ahd_hard_errors[i].errno) != 0) printf("%s: hwerrint, %s\n", ahd_name(ahd), ahd_hard_errors[i].errmesg); } ahd_dump_card_state(ahd); panic("BRKADRINT"); /* Tell everyone that this HBA is no longer available */ ahd_abort_scbs(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS, CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN, CAM_NO_HBA); /* Tell the system that this controller has gone away. */ ahd_free(ahd); } #ifdef AHD_DEBUG static void ahd_dump_sglist(struct scb *scb) { int i; if (scb->sg_count > 0) { if ((scb->ahd_softc->flags & AHD_64BIT_ADDRESSING) != 0) { struct ahd_dma64_seg *sg_list; sg_list = (struct ahd_dma64_seg*)scb->sg_list; for (i = 0; i < scb->sg_count; i++) { uint64_t addr; uint32_t len; addr = ahd_le64toh(sg_list[i].addr); len = ahd_le32toh(sg_list[i].len); printf("sg[%d] - Addr 0x%x%x : Length %d%s\n", i, (uint32_t)((addr >> 32) & 0xFFFFFFFF), (uint32_t)(addr & 0xFFFFFFFF), sg_list[i].len & AHD_SG_LEN_MASK, (sg_list[i].len & AHD_DMA_LAST_SEG) ? " Last" : ""); } } else { struct ahd_dma_seg *sg_list; sg_list = (struct ahd_dma_seg*)scb->sg_list; for (i = 0; i < scb->sg_count; i++) { uint32_t len; len = ahd_le32toh(sg_list[i].len); printf("sg[%d] - Addr 0x%x%x : Length %d%s\n", i, (len & AHD_SG_HIGH_ADDR_MASK) >> 24, ahd_le32toh(sg_list[i].addr), len & AHD_SG_LEN_MASK, len & AHD_DMA_LAST_SEG ? " Last" : ""); } } } } #endif /* AHD_DEBUG */ void ahd_handle_seqint(struct ahd_softc *ahd, u_int intstat) { u_int seqintcode; /* * Save the sequencer interrupt code and clear the SEQINT * bit. We will unpause the sequencer, if appropriate, * after servicing the request. */ seqintcode = ahd_inb(ahd, SEQINTCODE); ahd_outb(ahd, CLRINT, CLRSEQINT); if ((ahd->bugs & AHD_INTCOLLISION_BUG) != 0) { /* * Unpause the sequencer and let it clear * SEQINT by writing NO_SEQINT to it. This * will cause the sequencer to be paused again, * which is the expected state of this routine. */ ahd_unpause(ahd); while (!ahd_is_paused(ahd)) ; ahd_outb(ahd, CLRINT, CLRSEQINT); } ahd_update_modes(ahd); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MISC) != 0) printf("%s: Handle Seqint Called for code %d\n", ahd_name(ahd), seqintcode); #endif switch (seqintcode) { case ENTERING_NONPACK: { struct scb *scb; u_int scbid; AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK), ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK)); scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { /* * Somehow need to know if this * is from a selection or reselection. * From that, we can determine target * ID so we at least have an I_T nexus. */ } else { ahd_outb(ahd, SAVED_SCSIID, scb->hscb->scsiid); ahd_outb(ahd, SAVED_LUN, scb->hscb->lun); ahd_outb(ahd, SEQ_FLAGS, 0x0); } if ((ahd_inb(ahd, LQISTAT2) & LQIPHASE_OUTPKT) != 0 && (ahd_inb(ahd, SCSISIGO) & ATNO) != 0) { /* * Phase change after read stream with * CRC error with P0 asserted on last * packet. */ #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) printf("%s: Assuming LQIPHASE_NLQ with " "P0 assertion\n", ahd_name(ahd)); #endif } #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) printf("%s: Entering NONPACK\n", ahd_name(ahd)); #endif break; } case INVALID_SEQINT: printf("%s: Invalid Sequencer interrupt occurred, " "resetting channel.\n", ahd_name(ahd)); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) ahd_dump_card_state(ahd); #endif ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE); break; case STATUS_OVERRUN: { struct scb *scb; u_int scbid; scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); if (scb != NULL) ahd_print_path(ahd, scb); else printf("%s: ", ahd_name(ahd)); printf("SCB %d Packetized Status Overrun", scbid); ahd_dump_card_state(ahd); ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE); break; } case CFG4ISTAT_INTR: { struct scb *scb; u_int scbid; scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { ahd_dump_card_state(ahd); printf("CFG4ISTAT: Free SCB %d referenced", scbid); panic("For safety"); } ahd_outq(ahd, HADDR, scb->sense_busaddr); ahd_outw(ahd, HCNT, AHD_SENSE_BUFSIZE); ahd_outb(ahd, HCNT + 2, 0); ahd_outb(ahd, SG_CACHE_PRE, SG_LAST_SEG); ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN); break; } case ILLEGAL_PHASE: { u_int bus_phase; bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK; printf("%s: ILLEGAL_PHASE 0x%x\n", ahd_name(ahd), bus_phase); switch (bus_phase) { case P_DATAOUT: case P_DATAIN: case P_DATAOUT_DT: case P_DATAIN_DT: case P_MESGOUT: case P_STATUS: case P_MESGIN: ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE); printf("%s: Issued Bus Reset.\n", ahd_name(ahd)); break; case P_COMMAND: { struct ahd_devinfo devinfo; struct scb *scb; struct ahd_initiator_tinfo *targ_info; struct ahd_tmode_tstate *tstate; struct ahd_transinfo *tinfo; u_int scbid; /* * If a target takes us into the command phase * assume that it has been externally reset and * has thus lost our previous packetized negotiation * agreement. Since we have not sent an identify * message and may not have fully qualified the * connection, we change our command to TUR, assert * ATN and ABORT the task when we go to message in * phase. The OSM will see the REQUEUE_REQUEST * status and retry the command. */ scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { printf("Invalid phase with no valid SCB. " "Resetting bus.\n"); ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE); break; } ahd_compile_devinfo(&devinfo, SCB_GET_OUR_ID(scb), SCB_GET_TARGET(ahd, scb), SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahd, scb), ROLE_INITIATOR); targ_info = ahd_fetch_transinfo(ahd, devinfo.channel, devinfo.our_scsiid, devinfo.target, &tstate); tinfo = &targ_info->curr; ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT, AHD_TRANS_ACTIVE, /*paused*/TRUE); ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0, /*ppr_options*/0, AHD_TRANS_ACTIVE, /*paused*/TRUE); /* Hand-craft TUR command */ ahd_outb(ahd, SCB_CDB_STORE, 0); ahd_outb(ahd, SCB_CDB_STORE+1, 0); ahd_outb(ahd, SCB_CDB_STORE+2, 0); ahd_outb(ahd, SCB_CDB_STORE+3, 0); ahd_outb(ahd, SCB_CDB_STORE+4, 0); ahd_outb(ahd, SCB_CDB_STORE+5, 0); ahd_outb(ahd, SCB_CDB_LEN, 6); scb->hscb->control &= ~(TAG_ENB|SCB_TAG_TYPE); scb->hscb->control |= MK_MESSAGE; ahd_outb(ahd, SCB_CONTROL, scb->hscb->control); ahd_outb(ahd, MSG_OUT, HOST_MSG); ahd_outb(ahd, SAVED_SCSIID, scb->hscb->scsiid); /* * The lun is 0, regardless of the SCB's lun * as we have not sent an identify message. */ ahd_outb(ahd, SAVED_LUN, 0); ahd_outb(ahd, SEQ_FLAGS, 0); ahd_assert_atn(ahd); scb->flags &= ~SCB_PACKETIZED; scb->flags |= SCB_ABORT|SCB_EXTERNAL_RESET; ahd_freeze_devq(ahd, scb); ahd_set_transaction_status(scb, CAM_REQUEUE_REQ); ahd_freeze_scb(scb); /* Notify XPT */ ahd_send_async(ahd, devinfo.channel, devinfo.target, CAM_LUN_WILDCARD, AC_SENT_BDR); /* * Allow the sequencer to continue with * non-pack processing. */ ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); ahd_outb(ahd, CLRLQOINT1, CLRLQOPHACHGINPKT); if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) { ahd_outb(ahd, CLRLQOINT1, 0); } #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) { ahd_print_path(ahd, scb); printf("Unexpected command phase from " "packetized target\n"); } #endif break; } } break; } case CFG4OVERRUN: { struct scb *scb; u_int scb_index; #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) { printf("%s: CFG4OVERRUN mode = %x\n", ahd_name(ahd), ahd_inb(ahd, MODE_PTR)); } #endif scb_index = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scb_index); if (scb == NULL) { /* * Attempt to transfer to an SCB that is * not outstanding. */ ahd_assert_atn(ahd); ahd_outb(ahd, MSG_OUT, HOST_MSG); ahd->msgout_buf[0] = MSG_ABORT_TASK; ahd->msgout_len = 1; ahd->msgout_index = 0; ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT; /* * Clear status received flag to prevent any * attempt to complete this bogus SCB. */ ahd_outb(ahd, SCB_CONTROL, ahd_inb_scbram(ahd, SCB_CONTROL) & ~STATUS_RCVD); } break; } case DUMP_CARD_STATE: { ahd_dump_card_state(ahd); break; } case PDATA_REINIT: { #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) { printf("%s: PDATA_REINIT - DFCNTRL = 0x%x " "SG_CACHE_SHADOW = 0x%x\n", ahd_name(ahd), ahd_inb(ahd, DFCNTRL), ahd_inb(ahd, SG_CACHE_SHADOW)); } #endif ahd_reinitialize_dataptrs(ahd); break; } case HOST_MSG_LOOP: { struct ahd_devinfo devinfo; /* * The sequencer has encountered a message phase * that requires host assistance for completion. * While handling the message phase(s), we will be * notified by the sequencer after each byte is * transfered so we can track bus phase changes. * * If this is the first time we've seen a HOST_MSG_LOOP * interrupt, initialize the state of the host message * loop. */ ahd_fetch_devinfo(ahd, &devinfo); if (ahd->msg_type == MSG_TYPE_NONE) { struct scb *scb; u_int scb_index; u_int bus_phase; bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK; if (bus_phase != P_MESGIN && bus_phase != P_MESGOUT) { printf("ahd_intr: HOST_MSG_LOOP bad " "phase 0x%x\n", bus_phase); /* * Probably transitioned to bus free before * we got here. Just punt the message. */ ahd_dump_card_state(ahd); ahd_clear_intstat(ahd); ahd_restart(ahd); return; } scb_index = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scb_index); if (devinfo.role == ROLE_INITIATOR) { if (bus_phase == P_MESGOUT) ahd_setup_initiator_msgout(ahd, &devinfo, scb); else { ahd->msg_type = MSG_TYPE_INITIATOR_MSGIN; ahd->msgin_index = 0; } } #ifdef AHD_TARGET_MODE else { if (bus_phase == P_MESGOUT) { ahd->msg_type = MSG_TYPE_TARGET_MSGOUT; ahd->msgin_index = 0; } else ahd_setup_target_msgin(ahd, &devinfo, scb); } #endif } ahd_handle_message_phase(ahd); break; } case NO_MATCH: { /* Ensure we don't leave the selection hardware on */ AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO); printf("%s:%c:%d: no active SCB for reconnecting " "target - issuing BUS DEVICE RESET\n", ahd_name(ahd), 'A', ahd_inb(ahd, SELID) >> 4); printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, " "REG0 == 0x%x ACCUM = 0x%x\n", ahd_inb(ahd, SAVED_SCSIID), ahd_inb(ahd, SAVED_LUN), ahd_inw(ahd, REG0), ahd_inb(ahd, ACCUM)); printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, " "SINDEX == 0x%x\n", ahd_inb(ahd, SEQ_FLAGS), ahd_get_scbptr(ahd), ahd_find_busy_tcl(ahd, BUILD_TCL(ahd_inb(ahd, SAVED_SCSIID), ahd_inb(ahd, SAVED_LUN))), ahd_inw(ahd, SINDEX)); printf("SELID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, " "SCB_CONTROL == 0x%x\n", ahd_inb(ahd, SELID), ahd_inb_scbram(ahd, SCB_SCSIID), ahd_inb_scbram(ahd, SCB_LUN), ahd_inb_scbram(ahd, SCB_CONTROL)); printf("SCSIBUS[0] == 0x%x, SCSISIGI == 0x%x\n", ahd_inb(ahd, SCSIBUS), ahd_inb(ahd, SCSISIGI)); printf("SXFRCTL0 == 0x%x\n", ahd_inb(ahd, SXFRCTL0)); printf("SEQCTL0 == 0x%x\n", ahd_inb(ahd, SEQCTL0)); ahd_dump_card_state(ahd); ahd->msgout_buf[0] = MSG_BUS_DEV_RESET; ahd->msgout_len = 1; ahd->msgout_index = 0; ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT; ahd_outb(ahd, MSG_OUT, HOST_MSG); ahd_assert_atn(ahd); break; } case PROTO_VIOLATION: { ahd_handle_proto_violation(ahd); break; } case IGN_WIDE_RES: { struct ahd_devinfo devinfo; ahd_fetch_devinfo(ahd, &devinfo); ahd_handle_ign_wide_residue(ahd, &devinfo); break; } case BAD_PHASE: { u_int lastphase; lastphase = ahd_inb(ahd, LASTPHASE); printf("%s:%c:%d: unknown scsi bus phase %x, " "lastphase = 0x%x. Attempting to continue\n", ahd_name(ahd), 'A', SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)), lastphase, ahd_inb(ahd, SCSISIGI)); break; } case MISSED_BUSFREE: { u_int lastphase; lastphase = ahd_inb(ahd, LASTPHASE); printf("%s:%c:%d: Missed busfree. " "Lastphase = 0x%x, Curphase = 0x%x\n", ahd_name(ahd), 'A', SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)), lastphase, ahd_inb(ahd, SCSISIGI)); ahd_restart(ahd); return; } case DATA_OVERRUN: { /* * When the sequencer detects an overrun, it * places the controller in "BITBUCKET" mode * and allows the target to complete its transfer. * Unfortunately, none of the counters get updated * when the controller is in this mode, so we have * no way of knowing how large the overrun was. */ struct scb *scb; u_int scbindex; #ifdef AHD_DEBUG u_int lastphase; #endif scbindex = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbindex); #ifdef AHD_DEBUG lastphase = ahd_inb(ahd, LASTPHASE); if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) { ahd_print_path(ahd, scb); printf("data overrun detected %s. Tag == 0x%x.\n", ahd_lookup_phase_entry(lastphase)->phasemsg, SCB_GET_TAG(scb)); ahd_print_path(ahd, scb); printf("%s seen Data Phase. Length = %ld. " "NumSGs = %d.\n", ahd_inb(ahd, SEQ_FLAGS) & DPHASE ? "Have" : "Haven't", ahd_get_transfer_length(scb), scb->sg_count); ahd_dump_sglist(scb); } #endif /* * Set this and it will take effect when the * target does a command complete. */ ahd_freeze_devq(ahd, scb); ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR); ahd_freeze_scb(scb); break; } case MKMSG_FAILED: { struct ahd_devinfo devinfo; struct scb *scb; u_int scbid; ahd_fetch_devinfo(ahd, &devinfo); printf("%s:%c:%d:%d: Attempt to issue message failed\n", ahd_name(ahd), devinfo.channel, devinfo.target, devinfo.lun); scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); if (scb != NULL && (scb->flags & SCB_RECOVERY_SCB) != 0) /* * Ensure that we didn't put a second instance of this * SCB into the QINFIFO. */ ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb), SCB_GET_CHANNEL(ahd, scb), SCB_GET_LUN(scb), SCB_GET_TAG(scb), ROLE_INITIATOR, /*status*/0, SEARCH_REMOVE); ahd_outb(ahd, SCB_CONTROL, ahd_inb_scbram(ahd, SCB_CONTROL) & ~MK_MESSAGE); break; } case TASKMGMT_FUNC_COMPLETE: { u_int scbid; struct scb *scb; scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); if (scb != NULL) { u_int lun; u_int tag; cam_status error; ahd_print_path(ahd, scb); printf("Task Management Func 0x%x Complete\n", scb->hscb->task_management); lun = CAM_LUN_WILDCARD; tag = SCB_LIST_NULL; switch (scb->hscb->task_management) { case SIU_TASKMGMT_ABORT_TASK: tag = SCB_GET_TAG(scb); case SIU_TASKMGMT_ABORT_TASK_SET: case SIU_TASKMGMT_CLEAR_TASK_SET: lun = scb->hscb->lun; error = CAM_REQ_ABORTED; ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb), 'A', lun, tag, ROLE_INITIATOR, error); break; case SIU_TASKMGMT_LUN_RESET: lun = scb->hscb->lun; case SIU_TASKMGMT_TARGET_RESET: { struct ahd_devinfo devinfo; ahd_scb_devinfo(ahd, &devinfo, scb); error = CAM_BDR_SENT; ahd_handle_devreset(ahd, &devinfo, lun, CAM_BDR_SENT, lun != CAM_LUN_WILDCARD ? "Lun Reset" : "Target Reset", /*verbose_level*/0); break; } default: panic("Unexpected TaskMgmt Func\n"); break; } } break; } case TASKMGMT_CMD_CMPLT_OKAY: { u_int scbid; struct scb *scb; /* * An ABORT TASK TMF failed to be delivered before * the targeted command completed normally. */ scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); if (scb != NULL) { /* * Remove the second instance of this SCB from * the QINFIFO if it is still there. */ ahd_print_path(ahd, scb); printf("SCB completes before TMF\n"); /* * Handle losing the race. Wait until any * current selection completes. We will then * set the TMF back to zero in this SCB so that * the sequencer doesn't bother to issue another * sequencer interrupt for its completion. */ while ((ahd_inb(ahd, SCSISEQ0) & ENSELO) != 0 && (ahd_inb(ahd, SSTAT0) & SELDO) == 0 && (ahd_inb(ahd, SSTAT1) & SELTO) == 0) ; ahd_outb(ahd, SCB_TASK_MANAGEMENT, 0); ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb), SCB_GET_CHANNEL(ahd, scb), SCB_GET_LUN(scb), SCB_GET_TAG(scb), ROLE_INITIATOR, /*status*/0, SEARCH_REMOVE); } break; } case TRACEPOINT0: case TRACEPOINT1: case TRACEPOINT2: case TRACEPOINT3: printf("%s: Tracepoint %d\n", ahd_name(ahd), seqintcode - TRACEPOINT0); break; case NO_SEQINT: break; case SAW_HWERR: ahd_handle_hwerrint(ahd); break; default: printf("%s: Unexpected SEQINTCODE %d\n", ahd_name(ahd), seqintcode); break; } /* * The sequencer is paused immediately on * a SEQINT, so we should restart it when * we're done. */ ahd_unpause(ahd); } void ahd_handle_scsiint(struct ahd_softc *ahd, u_int intstat) { struct scb *scb; u_int status0; u_int status3; u_int status; u_int lqistat1; u_int lqostat0; u_int scbid; u_int busfreetime; ahd_update_modes(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); status3 = ahd_inb(ahd, SSTAT3) & (NTRAMPERR|OSRAMPERR); status0 = ahd_inb(ahd, SSTAT0) & (IOERR|OVERRUN|SELDI|SELDO); status = ahd_inb(ahd, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR); lqistat1 = ahd_inb(ahd, LQISTAT1); lqostat0 = ahd_inb(ahd, LQOSTAT0); busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME; /* * Ignore external resets after a bus reset. */ if (((status & SCSIRSTI) != 0) && (ahd->flags & AHD_BUS_RESET_ACTIVE)) { ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI); return; } /* * Clear bus reset flag */ ahd->flags &= ~AHD_BUS_RESET_ACTIVE; if ((status0 & (SELDI|SELDO)) != 0) { u_int simode0; ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG); simode0 = ahd_inb(ahd, SIMODE0); status0 &= simode0 & (IOERR|OVERRUN|SELDI|SELDO); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); } scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); if (scb != NULL && (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0) scb = NULL; if ((status0 & IOERR) != 0) { u_int now_lvd; now_lvd = ahd_inb(ahd, SBLKCTL) & ENAB40; printf("%s: Transceiver State Has Changed to %s mode\n", ahd_name(ahd), now_lvd ? "LVD" : "SE"); ahd_outb(ahd, CLRSINT0, CLRIOERR); /* * A change in I/O mode is equivalent to a bus reset. */ ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE); ahd_pause(ahd); ahd_setup_iocell_workaround(ahd); ahd_unpause(ahd); } else if ((status0 & OVERRUN) != 0) { printf("%s: SCSI offset overrun detected. Resetting bus.\n", ahd_name(ahd)); ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE); } else if ((status & SCSIRSTI) != 0) { printf("%s: Someone reset channel A\n", ahd_name(ahd)); ahd_reset_channel(ahd, 'A', /*Initiate Reset*/FALSE); } else if ((status & SCSIPERR) != 0) { /* Make sure the sequencer is in a safe location. */ ahd_clear_critical_section(ahd); ahd_handle_transmission_error(ahd); } else if (lqostat0 != 0) { printf("%s: lqostat0 == 0x%x!\n", ahd_name(ahd), lqostat0); ahd_outb(ahd, CLRLQOINT0, lqostat0); if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) ahd_outb(ahd, CLRLQOINT1, 0); } else if ((status & SELTO) != 0) { u_int scbid; /* Stop the selection */ ahd_outb(ahd, SCSISEQ0, 0); /* Make sure the sequencer is in a safe location. */ ahd_clear_critical_section(ahd); /* No more pending messages */ ahd_clear_msg_state(ahd); /* Clear interrupt state */ ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR); /* * Although the driver does not care about the * 'Selection in Progress' status bit, the busy * LED does. SELINGO is only cleared by a sucessfull * selection, so we must manually clear it to insure * the LED turns off just incase no future successful * selections occur (e.g. no devices on the bus). */ ahd_outb(ahd, CLRSINT0, CLRSELINGO); scbid = ahd_inw(ahd, WAITING_TID_HEAD); scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { printf("%s: ahd_intr - referenced scb not " "valid during SELTO scb(0x%x)\n", ahd_name(ahd), scbid); ahd_dump_card_state(ahd); } else { struct ahd_devinfo devinfo; #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_SELTO) != 0) { ahd_print_path(ahd, scb); printf("Saw Selection Timeout for SCB 0x%x\n", scbid); } #endif ahd_scb_devinfo(ahd, &devinfo, scb); ahd_set_transaction_status(scb, CAM_SEL_TIMEOUT); ahd_freeze_devq(ahd, scb); /* * Cancel any pending transactions on the device * now that it seems to be missing. This will * also revert us to async/narrow transfers until * we can renegotiate with the device. */ ahd_handle_devreset(ahd, &devinfo, CAM_LUN_WILDCARD, CAM_SEL_TIMEOUT, "Selection Timeout", /*verbose_level*/1); } ahd_outb(ahd, CLRINT, CLRSCSIINT); ahd_iocell_first_selection(ahd); ahd_unpause(ahd); } else if ((status0 & (SELDI|SELDO)) != 0) { ahd_iocell_first_selection(ahd); ahd_unpause(ahd); } else if (status3 != 0) { printf("%s: SCSI Cell parity error SSTAT3 == 0x%x\n", ahd_name(ahd), status3); ahd_outb(ahd, CLRSINT3, status3); } else if ((lqistat1 & (LQIPHASE_LQ|LQIPHASE_NLQ)) != 0) { /* Make sure the sequencer is in a safe location. */ ahd_clear_critical_section(ahd); ahd_handle_lqiphase_error(ahd, lqistat1); } else if ((lqistat1 & LQICRCI_NLQ) != 0) { /* * This status can be delayed during some * streaming operations. The SCSIPHASE * handler has already dealt with this case * so just clear the error. */ ahd_outb(ahd, CLRLQIINT1, CLRLQICRCI_NLQ); } else if ((status & BUSFREE) != 0 || (lqistat1 & LQOBUSFREE) != 0) { u_int lqostat1; int restart; int clear_fifo; int packetized; u_int mode; /* * Clear our selection hardware as soon as possible. * We may have an entry in the waiting Q for this target, * that is affected by this busfree and we don't want to * go about selecting the target while we handle the event. */ ahd_outb(ahd, SCSISEQ0, 0); /* Make sure the sequencer is in a safe location. */ ahd_clear_critical_section(ahd); /* * Determine what we were up to at the time of * the busfree. */ mode = AHD_MODE_SCSI; busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME; lqostat1 = ahd_inb(ahd, LQOSTAT1); switch (busfreetime) { case BUSFREE_DFF0: case BUSFREE_DFF1: { u_int scbid; struct scb *scb; mode = busfreetime == BUSFREE_DFF0 ? AHD_MODE_DFF0 : AHD_MODE_DFF1; ahd_set_modes(ahd, mode, mode); scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { printf("%s: Invalid SCB %d in DFF%d " "during unexpected busfree\n", ahd_name(ahd), scbid, mode); packetized = 0; } else packetized = (scb->flags & SCB_PACKETIZED) != 0; clear_fifo = 1; break; } case BUSFREE_LQO: clear_fifo = 0; packetized = 1; break; default: clear_fifo = 0; packetized = (lqostat1 & LQOBUSFREE) != 0; if (!packetized && ahd_inb(ahd, LASTPHASE) == P_BUSFREE && (ahd_inb(ahd, SSTAT0) & SELDI) == 0 && ((ahd_inb(ahd, SSTAT0) & SELDO) == 0 || (ahd_inb(ahd, SCSISEQ0) & ENSELO) == 0)) /* * Assume packetized if we are not * on the bus in a non-packetized * capacity and any pending selection * was a packetized selection. */ packetized = 1; break; } #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MISC) != 0) printf("Saw Busfree. Busfreetime = 0x%x.\n", busfreetime); #endif /* * Busfrees that occur in non-packetized phases are * handled by the nonpkt_busfree handler. */ if (packetized && ahd_inb(ahd, LASTPHASE) == P_BUSFREE) { restart = ahd_handle_pkt_busfree(ahd, busfreetime); } else { packetized = 0; restart = ahd_handle_nonpkt_busfree(ahd); } /* * Clear the busfree interrupt status. The setting of * the interrupt is a pulse, so in a perfect world, we * would not need to muck with the ENBUSFREE logic. This * would ensure that if the bus moves on to another * connection, busfree protection is still in force. If * BUSFREEREV is broken, however, we must manually clear * the ENBUSFREE if the busfree occurred during a non-pack * connection so that we don't get false positives during * future, packetized, connections. */ ahd_outb(ahd, CLRSINT1, CLRBUSFREE); if (packetized == 0 && (ahd->bugs & AHD_BUSFREEREV_BUG) != 0) ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) & ~ENBUSFREE); if (clear_fifo) ahd_clear_fifo(ahd, mode); ahd_clear_msg_state(ahd); ahd_outb(ahd, CLRINT, CLRSCSIINT); if (restart) { ahd_restart(ahd); } else { ahd_unpause(ahd); } } else { printf("%s: Missing case in ahd_handle_scsiint. status = %x\n", ahd_name(ahd), status); ahd_dump_card_state(ahd); ahd_clear_intstat(ahd); ahd_unpause(ahd); } } static void ahd_handle_transmission_error(struct ahd_softc *ahd) { struct scb *scb; u_int scbid; u_int lqistat1; u_int lqistat2; u_int msg_out; u_int curphase; u_int lastphase; u_int perrdiag; u_int cur_col; int silent; scb = NULL; ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); lqistat1 = ahd_inb(ahd, LQISTAT1) & ~(LQIPHASE_LQ|LQIPHASE_NLQ); lqistat2 = ahd_inb(ahd, LQISTAT2); if ((lqistat1 & (LQICRCI_NLQ|LQICRCI_LQ)) == 0 && (ahd->bugs & AHD_NLQICRC_DELAYED_BUG) != 0) { u_int lqistate; ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG); lqistate = ahd_inb(ahd, LQISTATE); if ((lqistate >= 0x1E && lqistate <= 0x24) || (lqistate == 0x29)) { #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) { printf("%s: NLQCRC found via LQISTATE\n", ahd_name(ahd)); } #endif lqistat1 |= LQICRCI_NLQ; } ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); } ahd_outb(ahd, CLRLQIINT1, lqistat1); lastphase = ahd_inb(ahd, LASTPHASE); curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK; perrdiag = ahd_inb(ahd, PERRDIAG); msg_out = MSG_INITIATOR_DET_ERR; ahd_outb(ahd, CLRSINT1, CLRSCSIPERR); /* * Try to find the SCB associated with this error. */ silent = FALSE; if (lqistat1 == 0 || (lqistat1 & LQICRCI_NLQ) != 0) { if ((lqistat1 & (LQICRCI_NLQ|LQIOVERI_NLQ)) != 0) ahd_set_active_fifo(ahd); scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); if (scb != NULL && SCB_IS_SILENT(scb)) silent = TRUE; } cur_col = 0; if (silent == FALSE) { printf("%s: Transmission error detected\n", ahd_name(ahd)); ahd_lqistat1_print(lqistat1, &cur_col, 50); ahd_lastphase_print(lastphase, &cur_col, 50); ahd_scsisigi_print(curphase, &cur_col, 50); ahd_perrdiag_print(perrdiag, &cur_col, 50); printf("\n"); ahd_dump_card_state(ahd); } if ((lqistat1 & (LQIOVERI_LQ|LQIOVERI_NLQ)) != 0) { if (silent == FALSE) { printf("%s: Gross protocol error during incoming " "packet. lqistat1 == 0x%x. Resetting bus.\n", ahd_name(ahd), lqistat1); } ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE); return; } else if ((lqistat1 & LQICRCI_LQ) != 0) { /* * A CRC error has been detected on an incoming LQ. * The bus is currently hung on the last ACK. * Hit LQIRETRY to release the last ack, and * wait for the sequencer to determine that ATNO * is asserted while in message out to take us * to our host message loop. No NONPACKREQ or * LQIPHASE type errors will occur in this * scenario. After this first LQIRETRY, the LQI * manager will be in ISELO where it will * happily sit until another packet phase begins. * Unexpected bus free detection is enabled * through any phases that occur after we release * this last ack until the LQI manager sees a * packet phase. This implies we may have to * ignore a perfectly valid "unexected busfree" * after our "initiator detected error" message is * sent. A busfree is the expected response after * we tell the target that it's L_Q was corrupted. * (SPI4R09 10.7.3.3.3) */ ahd_outb(ahd, LQCTL2, LQIRETRY); printf("LQIRetry for LQICRCI_LQ to release ACK\n"); } else if ((lqistat1 & LQICRCI_NLQ) != 0) { /* * We detected a CRC error in a NON-LQ packet. * The hardware has varying behavior in this situation * depending on whether this packet was part of a * stream or not. * * PKT by PKT mode: * The hardware has already acked the complete packet. * If the target honors our outstanding ATN condition, * we should be (or soon will be) in MSGOUT phase. * This will trigger the LQIPHASE_LQ status bit as the * hardware was expecting another LQ. Unexpected * busfree detection is enabled. Once LQIPHASE_LQ is * true (first entry into host message loop is much * the same), we must clear LQIPHASE_LQ and hit * LQIRETRY so the hardware is ready to handle * a future LQ. NONPACKREQ will not be asserted again * once we hit LQIRETRY until another packet is * processed. The target may either go busfree * or start another packet in response to our message. * * Read Streaming P0 asserted: * If we raise ATN and the target completes the entire * stream (P0 asserted during the last packet), the * hardware will ack all data and return to the ISTART * state. When the target reponds to our ATN condition, * LQIPHASE_LQ will be asserted. We should respond to * this with an LQIRETRY to prepare for any future * packets. NONPACKREQ will not be asserted again * once we hit LQIRETRY until another packet is * processed. The target may either go busfree or * start another packet in response to our message. * Busfree detection is enabled. * * Read Streaming P0 not asserted: * If we raise ATN and the target transitions to * MSGOUT in or after a packet where P0 is not * asserted, the hardware will assert LQIPHASE_NLQ. * We should respond to the LQIPHASE_NLQ with an * LQIRETRY. Should the target stay in a non-pkt * phase after we send our message, the hardware * will assert LQIPHASE_LQ. Recovery is then just as * listed above for the read streaming with P0 asserted. * Busfree detection is enabled. */ if (silent == FALSE) printf("LQICRC_NLQ\n"); if (scb == NULL) { printf("%s: No SCB valid for LQICRC_NLQ. " "Resetting bus\n", ahd_name(ahd)); ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE); return; } } else if ((lqistat1 & LQIBADLQI) != 0) { printf("Need to handle BADLQI!\n"); ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE); return; } else if ((perrdiag & (PARITYERR|PREVPHASE)) == PARITYERR) { if ((curphase & ~P_DATAIN_DT) != 0) { /* Ack the byte. So we can continue. */ if (silent == FALSE) printf("Acking %s to clear perror\n", ahd_lookup_phase_entry(curphase)->phasemsg); ahd_inb(ahd, SCSIDAT); } if (curphase == P_MESGIN) msg_out = MSG_PARITY_ERROR; } /* * We've set the hardware to assert ATN if we * get a parity error on "in" phases, so all we * need to do is stuff the message buffer with * the appropriate message. "In" phases have set * mesg_out to something other than MSG_NOP. */ ahd->send_msg_perror = msg_out; if (scb != NULL && msg_out == MSG_INITIATOR_DET_ERR) scb->flags |= SCB_TRANSMISSION_ERROR; ahd_outb(ahd, MSG_OUT, HOST_MSG); ahd_outb(ahd, CLRINT, CLRSCSIINT); ahd_unpause(ahd); } static void ahd_handle_lqiphase_error(struct ahd_softc *ahd, u_int lqistat1) { /* * Clear the sources of the interrupts. */ ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); ahd_outb(ahd, CLRLQIINT1, lqistat1); /* * If the "illegal" phase changes were in response * to our ATN to flag a CRC error, AND we ended up * on packet boundaries, clear the error, restart the * LQI manager as appropriate, and go on our merry * way toward sending the message. Otherwise, reset * the bus to clear the error. */ ahd_set_active_fifo(ahd); if ((ahd_inb(ahd, SCSISIGO) & ATNO) != 0 && (ahd_inb(ahd, MDFFSTAT) & DLZERO) != 0) { if ((lqistat1 & LQIPHASE_LQ) != 0) { printf("LQIRETRY for LQIPHASE_LQ\n"); ahd_outb(ahd, LQCTL2, LQIRETRY); } else if ((lqistat1 & LQIPHASE_NLQ) != 0) { printf("LQIRETRY for LQIPHASE_NLQ\n"); ahd_outb(ahd, LQCTL2, LQIRETRY); } else panic("ahd_handle_lqiphase_error: No phase errors\n"); ahd_dump_card_state(ahd); ahd_outb(ahd, CLRINT, CLRSCSIINT); ahd_unpause(ahd); } else { printf("Reseting Channel for LQI Phase error\n"); ahd_dump_card_state(ahd); ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE); } } /* * Packetized unexpected or expected busfree. * Entered in mode based on busfreetime. */ static int ahd_handle_pkt_busfree(struct ahd_softc *ahd, u_int busfreetime) { u_int lqostat1; AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK), ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK)); lqostat1 = ahd_inb(ahd, LQOSTAT1); if ((lqostat1 & LQOBUSFREE) != 0) { struct scb *scb; u_int scbid; u_int saved_scbptr; u_int waiting_h; u_int waiting_t; u_int next; /* * The LQO manager detected an unexpected busfree * either: * * 1) During an outgoing LQ. * 2) After an outgoing LQ but before the first * REQ of the command packet. * 3) During an outgoing command packet. * * In all cases, CURRSCB is pointing to the * SCB that encountered the failure. Clean * up the queue, clear SELDO and LQOBUSFREE, * and allow the sequencer to restart the select * out at its lesure. */ ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); scbid = ahd_inw(ahd, CURRSCB); scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) panic("SCB not valid during LQOBUSFREE"); /* * Clear the status. */ ahd_outb(ahd, CLRLQOINT1, CLRLQOBUSFREE); if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) ahd_outb(ahd, CLRLQOINT1, 0); ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO); ahd_flush_device_writes(ahd); ahd_outb(ahd, CLRSINT0, CLRSELDO); /* * Return the LQO manager to its idle loop. It will * not do this automatically if the busfree occurs * after the first REQ of either the LQ or command * packet or between the LQ and command packet. */ ahd_outb(ahd, LQCTL2, ahd_inb(ahd, LQCTL2) | LQOTOIDLE); /* * Update the waiting for selection queue so * we restart on the correct SCB. */ waiting_h = ahd_inw(ahd, WAITING_TID_HEAD); saved_scbptr = ahd_get_scbptr(ahd); if (waiting_h != scbid) { ahd_outw(ahd, WAITING_TID_HEAD, scbid); waiting_t = ahd_inw(ahd, WAITING_TID_TAIL); if (waiting_t == waiting_h) { ahd_outw(ahd, WAITING_TID_TAIL, scbid); next = SCB_LIST_NULL; } else { ahd_set_scbptr(ahd, waiting_h); next = ahd_inw_scbram(ahd, SCB_NEXT2); } ahd_set_scbptr(ahd, scbid); ahd_outw(ahd, SCB_NEXT2, next); } ahd_set_scbptr(ahd, saved_scbptr); if (scb->crc_retry_count < AHD_MAX_LQ_CRC_ERRORS) { if (SCB_IS_SILENT(scb) == FALSE) { ahd_print_path(ahd, scb); printf("Probable outgoing LQ CRC error. " "Retrying command\n"); } scb->crc_retry_count++; } else { ahd_set_transaction_status(scb, CAM_UNCOR_PARITY); ahd_freeze_scb(scb); ahd_freeze_devq(ahd, scb); } /* Return unpausing the sequencer. */ return (0); } else if ((ahd_inb(ahd, PERRDIAG) & PARITYERR) != 0) { /* * Ignore what are really parity errors that * occur on the last REQ of a free running * clock prior to going busfree. Some drives * do not properly active negate just before * going busfree resulting in a parity glitch. */ ahd_outb(ahd, CLRSINT1, CLRSCSIPERR|CLRBUSFREE); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MASKED_ERRORS) != 0) printf("%s: Parity on last REQ detected " "during busfree phase.\n", ahd_name(ahd)); #endif /* Return unpausing the sequencer. */ return (0); } if (ahd->src_mode != AHD_MODE_SCSI) { u_int scbid; struct scb *scb; scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); ahd_print_path(ahd, scb); printf("Unexpected PKT busfree condition\n"); ahd_dump_card_state(ahd); ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb), 'A', SCB_GET_LUN(scb), SCB_GET_TAG(scb), ROLE_INITIATOR, CAM_UNEXP_BUSFREE); /* Return restarting the sequencer. */ return (1); } printf("%s: Unexpected PKT busfree condition\n", ahd_name(ahd)); ahd_dump_card_state(ahd); /* Restart the sequencer. */ return (1); } /* * Non-packetized unexpected or expected busfree. */ static int ahd_handle_nonpkt_busfree(struct ahd_softc *ahd) { struct ahd_devinfo devinfo; struct scb *scb; u_int lastphase; u_int saved_scsiid; u_int saved_lun; u_int target; u_int initiator_role_id; u_int scbid; u_int ppr_busfree; int printerror; /* * Look at what phase we were last in. If its message out, * chances are pretty good that the busfree was in response * to one of our abort requests. */ lastphase = ahd_inb(ahd, LASTPHASE); saved_scsiid = ahd_inb(ahd, SAVED_SCSIID); saved_lun = ahd_inb(ahd, SAVED_LUN); target = SCSIID_TARGET(ahd, saved_scsiid); initiator_role_id = SCSIID_OUR_ID(saved_scsiid); ahd_compile_devinfo(&devinfo, initiator_role_id, target, saved_lun, 'A', ROLE_INITIATOR); printerror = 1; scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); if (scb != NULL && (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0) scb = NULL; ppr_busfree = (ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0; if (lastphase == P_MESGOUT) { u_int tag; tag = SCB_LIST_NULL; if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT_TAG, TRUE) || ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT, TRUE)) { int found; int sent_msg; if (scb == NULL) { ahd_print_devinfo(ahd, &devinfo); printf("Abort for unidentified " "connection completed.\n"); /* restart the sequencer. */ return (1); } sent_msg = ahd->msgout_buf[ahd->msgout_index - 1]; ahd_print_path(ahd, scb); printf("SCB %d - Abort%s Completed.\n", SCB_GET_TAG(scb), sent_msg == MSG_ABORT_TAG ? "" : " Tag"); if (sent_msg == MSG_ABORT_TAG) tag = SCB_GET_TAG(scb); if ((scb->flags & SCB_EXTERNAL_RESET) != 0) { /* * This abort is in response to an * unexpected switch to command phase * for a packetized connection. Since * the identify message was never sent, * "saved lun" is 0. We really want to * abort only the SCB that encountered * this error, which could have a different * lun. The SCB will be retried so the OS * will see the UA after renegotiating to * packetized. */ tag = SCB_GET_TAG(scb); saved_lun = scb->hscb->lun; } found = ahd_abort_scbs(ahd, target, 'A', saved_lun, tag, ROLE_INITIATOR, CAM_REQ_ABORTED); printf("found == 0x%x\n", found); printerror = 0; } else if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_BUS_DEV_RESET, TRUE)) { #ifdef __FreeBSD__ /* * Don't mark the user's request for this BDR * as completing with CAM_BDR_SENT. CAM3 * specifies CAM_REQ_CMP. */ if (scb != NULL && scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV && ahd_match_scb(ahd, scb, target, 'A', CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_INITIATOR)) ahd_set_transaction_status(scb, CAM_REQ_CMP); #endif ahd_handle_devreset(ahd, &devinfo, CAM_LUN_WILDCARD, CAM_BDR_SENT, "Bus Device Reset", /*verbose_level*/0); printerror = 0; } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, FALSE) && ppr_busfree == 0) { struct ahd_initiator_tinfo *tinfo; struct ahd_tmode_tstate *tstate; /* * PPR Rejected. * * If the previous negotiation was packetized, * this could be because the device has been * reset without our knowledge. Force our * current negotiation to async and retry the * negotiation. Otherwise retry the command * with non-ppr negotiation. */ #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf("PPR negotiation rejected busfree.\n"); #endif tinfo = ahd_fetch_transinfo(ahd, devinfo.channel, devinfo.our_scsiid, devinfo.target, &tstate); if ((tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ)!=0) { ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT, AHD_TRANS_CUR, /*paused*/TRUE); ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0, /*ppr_options*/0, AHD_TRANS_CUR, /*paused*/TRUE); /* * The expect PPR busfree handler below * will effect the retry and necessary * abort. */ } else { tinfo->curr.transport_version = 2; tinfo->goal.transport_version = 2; tinfo->goal.ppr_options = 0; /* * Remove any SCBs in the waiting for selection * queue that may also be for this target so * that command ordering is preserved. */ ahd_freeze_devq(ahd, scb); ahd_qinfifo_requeue_tail(ahd, scb); printerror = 0; } } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, FALSE) && ppr_busfree == 0) { /* * Negotiation Rejected. Go-narrow and * retry command. */ #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf("WDTR negotiation rejected busfree.\n"); #endif ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT, AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE); /* * Remove any SCBs in the waiting for selection * queue that may also be for this target so that * command ordering is preserved. */ ahd_freeze_devq(ahd, scb); ahd_qinfifo_requeue_tail(ahd, scb); printerror = 0; } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, FALSE) && ppr_busfree == 0) { /* * Negotiation Rejected. Go-async and * retry command. */ #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf("SDTR negotiation rejected busfree.\n"); #endif ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0, /*ppr_options*/0, AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE); /* * Remove any SCBs in the waiting for selection * queue that may also be for this target so that * command ordering is preserved. */ ahd_freeze_devq(ahd, scb); ahd_qinfifo_requeue_tail(ahd, scb); printerror = 0; } else if ((ahd->msg_flags & MSG_FLAG_EXPECT_IDE_BUSFREE) != 0 && ahd_sent_msg(ahd, AHDMSG_1B, MSG_INITIATOR_DET_ERR, TRUE)) { #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf("Expected IDE Busfree\n"); #endif printerror = 0; } else if ((ahd->msg_flags & MSG_FLAG_EXPECT_QASREJ_BUSFREE) && ahd_sent_msg(ahd, AHDMSG_1B, MSG_MESSAGE_REJECT, TRUE)) { #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf("Expected QAS Reject Busfree\n"); #endif printerror = 0; } } /* * The busfree required flag is honored at the end of * the message phases. We check it last in case we * had to send some other message that caused a busfree. */ if (printerror != 0 && (lastphase == P_MESGIN || lastphase == P_MESGOUT) && ((ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0)) { ahd_freeze_devq(ahd, scb); ahd_set_transaction_status(scb, CAM_REQUEUE_REQ); ahd_freeze_scb(scb); if ((ahd->msg_flags & MSG_FLAG_IU_REQ_CHANGED) != 0) { ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb), SCB_GET_CHANNEL(ahd, scb), SCB_GET_LUN(scb), SCB_LIST_NULL, ROLE_INITIATOR, CAM_REQ_ABORTED); } else { #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf("PPR Negotiation Busfree.\n"); #endif ahd_done(ahd, scb); } printerror = 0; } if (printerror != 0) { int aborted; aborted = 0; if (scb != NULL) { u_int tag; if ((scb->hscb->control & TAG_ENB) != 0) tag = SCB_GET_TAG(scb); else tag = SCB_LIST_NULL; ahd_print_path(ahd, scb); aborted = ahd_abort_scbs(ahd, target, 'A', SCB_GET_LUN(scb), tag, ROLE_INITIATOR, CAM_UNEXP_BUSFREE); } else { /* * We had not fully identified this connection, * so we cannot abort anything. */ printf("%s: ", ahd_name(ahd)); } printf("Unexpected busfree %s, %d SCBs aborted, " "PRGMCNT == 0x%x\n", ahd_lookup_phase_entry(lastphase)->phasemsg, aborted, ahd_inw(ahd, PRGMCNT)); ahd_dump_card_state(ahd); if (lastphase != P_BUSFREE) ahd_force_renegotiation(ahd, &devinfo); } /* Always restart the sequencer. */ return (1); } static void ahd_handle_proto_violation(struct ahd_softc *ahd) { struct ahd_devinfo devinfo; struct scb *scb; u_int scbid; u_int seq_flags; u_int curphase; u_int lastphase; int found; ahd_fetch_devinfo(ahd, &devinfo); scbid = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scbid); seq_flags = ahd_inb(ahd, SEQ_FLAGS); curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK; lastphase = ahd_inb(ahd, LASTPHASE); if ((seq_flags & NOT_IDENTIFIED) != 0) { /* * The reconnecting target either did not send an * identify message, or did, but we didn't find an SCB * to match. */ ahd_print_devinfo(ahd, &devinfo); printf("Target did not send an IDENTIFY message. " "LASTPHASE = 0x%x.\n", lastphase); scb = NULL; } else if (scb == NULL) { /* * We don't seem to have an SCB active for this * transaction. Print an error and reset the bus. */ ahd_print_devinfo(ahd, &devinfo); printf("No SCB found during protocol violation\n"); goto proto_violation_reset; } else { ahd_set_transaction_status(scb, CAM_SEQUENCE_FAIL); if ((seq_flags & NO_CDB_SENT) != 0) { ahd_print_path(ahd, scb); printf("No or incomplete CDB sent to device.\n"); } else if ((ahd_inb_scbram(ahd, SCB_CONTROL) & STATUS_RCVD) == 0) { /* * The target never bothered to provide status to * us prior to completing the command. Since we don't * know the disposition of this command, we must attempt * to abort it. Assert ATN and prepare to send an abort * message. */ ahd_print_path(ahd, scb); printf("Completed command without status.\n"); } else { ahd_print_path(ahd, scb); printf("Unknown protocol violation.\n"); ahd_dump_card_state(ahd); } } if ((lastphase & ~P_DATAIN_DT) == 0 || lastphase == P_COMMAND) { proto_violation_reset: /* * Target either went directly to data * phase or didn't respond to our ATN. * The only safe thing to do is to blow * it away with a bus reset. */ found = ahd_reset_channel(ahd, 'A', TRUE); printf("%s: Issued Channel %c Bus Reset. " "%d SCBs aborted\n", ahd_name(ahd), 'A', found); } else { /* * Leave the selection hardware off in case * this abort attempt will affect yet to * be sent commands. */ ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO); ahd_assert_atn(ahd); ahd_outb(ahd, MSG_OUT, HOST_MSG); if (scb == NULL) { ahd_print_devinfo(ahd, &devinfo); ahd->msgout_buf[0] = MSG_ABORT_TASK; ahd->msgout_len = 1; ahd->msgout_index = 0; ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT; } else { ahd_print_path(ahd, scb); scb->flags |= SCB_ABORT; } printf("Protocol violation %s. Attempting to abort.\n", ahd_lookup_phase_entry(curphase)->phasemsg); } } /* * Force renegotiation to occur the next time we initiate * a command to the current device. */ static void ahd_force_renegotiation(struct ahd_softc *ahd, struct ahd_devinfo *devinfo) { struct ahd_initiator_tinfo *targ_info; struct ahd_tmode_tstate *tstate; #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) { ahd_print_devinfo(ahd, devinfo); printf("Forcing renegotiation\n"); } #endif targ_info = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid, devinfo->target, &tstate); ahd_update_neg_request(ahd, devinfo, tstate, targ_info, AHD_NEG_IF_NON_ASYNC); } #define AHD_MAX_STEPS 2000 static void ahd_clear_critical_section(struct ahd_softc *ahd) { ahd_mode_state saved_modes; int stepping; int steps; int first_instr; u_int simode0; u_int simode1; u_int simode3; u_int lqimode0; u_int lqimode1; u_int lqomode0; u_int lqomode1; if (ahd->num_critical_sections == 0) return; stepping = FALSE; steps = 0; first_instr = 0; simode0 = 0; simode1 = 0; simode3 = 0; lqimode0 = 0; lqimode1 = 0; lqomode0 = 0; lqomode1 = 0; saved_modes = ahd_save_modes(ahd); for (;;) { struct cs *cs; u_int seqaddr; u_int i; ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); seqaddr = ahd_inw(ahd, CURADDR); cs = ahd->critical_sections; for (i = 0; i < ahd->num_critical_sections; i++, cs++) { if (cs->begin < seqaddr && cs->end >= seqaddr) break; } if (i == ahd->num_critical_sections) break; if (steps > AHD_MAX_STEPS) { printf("%s: Infinite loop in critical section\n" "%s: First Instruction 0x%x now 0x%x\n", ahd_name(ahd), ahd_name(ahd), first_instr, seqaddr); ahd_dump_card_state(ahd); panic("critical section loop"); } steps++; #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MISC) != 0) printf("%s: Single stepping at 0x%x\n", ahd_name(ahd), seqaddr); #endif if (stepping == FALSE) { first_instr = seqaddr; ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG); simode0 = ahd_inb(ahd, SIMODE0); simode3 = ahd_inb(ahd, SIMODE3); lqimode0 = ahd_inb(ahd, LQIMODE0); lqimode1 = ahd_inb(ahd, LQIMODE1); lqomode0 = ahd_inb(ahd, LQOMODE0); lqomode1 = ahd_inb(ahd, LQOMODE1); ahd_outb(ahd, SIMODE0, 0); ahd_outb(ahd, SIMODE3, 0); ahd_outb(ahd, LQIMODE0, 0); ahd_outb(ahd, LQIMODE1, 0); ahd_outb(ahd, LQOMODE0, 0); ahd_outb(ahd, LQOMODE1, 0); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); simode1 = ahd_inb(ahd, SIMODE1); /* * We don't clear ENBUSFREE. Unfortunately * we cannot re-enable busfree detection within * the current connection, so we must leave it * on while single stepping. */ ahd_outb(ahd, SIMODE1, simode1 & ENBUSFREE); ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) | STEP); stepping = TRUE; } ahd_outb(ahd, CLRSINT1, CLRBUSFREE); ahd_outb(ahd, CLRINT, CLRSCSIINT); ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode); ahd_outb(ahd, HCNTRL, ahd->unpause); while (!ahd_is_paused(ahd)) ahd_delay(200); ahd_update_modes(ahd); } if (stepping) { ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG); ahd_outb(ahd, SIMODE0, simode0); ahd_outb(ahd, SIMODE3, simode3); ahd_outb(ahd, LQIMODE0, lqimode0); ahd_outb(ahd, LQIMODE1, lqimode1); ahd_outb(ahd, LQOMODE0, lqomode0); ahd_outb(ahd, LQOMODE1, lqomode1); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) & ~STEP); ahd_outb(ahd, SIMODE1, simode1); /* * SCSIINT seems to glitch occassionally when * the interrupt masks are restored. Clear SCSIINT * one more time so that only persistent errors * are seen as a real interrupt. */ ahd_outb(ahd, CLRINT, CLRSCSIINT); } ahd_restore_modes(ahd, saved_modes); } /* * Clear any pending interrupt status. */ static void ahd_clear_intstat(struct ahd_softc *ahd) { AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK), ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK)); /* Clear any interrupt conditions this may have caused */ ahd_outb(ahd, CLRLQIINT0, CLRLQIATNQAS|CLRLQICRCT1|CLRLQICRCT2 |CLRLQIBADLQT|CLRLQIATNLQ|CLRLQIATNCMD); ahd_outb(ahd, CLRLQIINT1, CLRLQIPHASE_LQ|CLRLQIPHASE_NLQ|CLRLIQABORT |CLRLQICRCI_LQ|CLRLQICRCI_NLQ|CLRLQIBADLQI |CLRLQIOVERI_LQ|CLRLQIOVERI_NLQ|CLRNONPACKREQ); ahd_outb(ahd, CLRLQOINT0, CLRLQOTARGSCBPERR|CLRLQOSTOPT2|CLRLQOATNLQ |CLRLQOATNPKT|CLRLQOTCRC); ahd_outb(ahd, CLRLQOINT1, CLRLQOINITSCBPERR|CLRLQOSTOPI2|CLRLQOBADQAS |CLRLQOBUSFREE|CLRLQOPHACHGINPKT); if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) { ahd_outb(ahd, CLRLQOINT0, 0); ahd_outb(ahd, CLRLQOINT1, 0); } ahd_outb(ahd, CLRSINT3, CLRNTRAMPERR|CLROSRAMPERR); ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI |CLRBUSFREE|CLRSCSIPERR|CLRREQINIT); ahd_outb(ahd, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO |CLRIOERR|CLROVERRUN); ahd_outb(ahd, CLRINT, CLRSCSIINT); } /**************************** Debugging Routines ******************************/ #ifdef AHD_DEBUG uint32_t ahd_debug = AHD_DEBUG_OPTS; #endif #if 0 void ahd_print_scb(struct scb *scb) { struct hardware_scb *hscb; int i; hscb = scb->hscb; printf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n", (void *)scb, hscb->control, hscb->scsiid, hscb->lun, hscb->cdb_len); printf("Shared Data: "); for (i = 0; i < sizeof(hscb->shared_data.idata.cdb); i++) printf("%#02x", hscb->shared_data.idata.cdb[i]); printf(" dataptr:%#x%x datacnt:%#x sgptr:%#x tag:%#x\n", (uint32_t)((ahd_le64toh(hscb->dataptr) >> 32) & 0xFFFFFFFF), (uint32_t)(ahd_le64toh(hscb->dataptr) & 0xFFFFFFFF), ahd_le32toh(hscb->datacnt), ahd_le32toh(hscb->sgptr), SCB_GET_TAG(scb)); ahd_dump_sglist(scb); } #endif /* 0 */ /************************* Transfer Negotiation *******************************/ /* * Allocate per target mode instance (ID we respond to as a target) * transfer negotiation data structures. */ static struct ahd_tmode_tstate * ahd_alloc_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel) { struct ahd_tmode_tstate *master_tstate; struct ahd_tmode_tstate *tstate; int i; master_tstate = ahd->enabled_targets[ahd->our_id]; if (ahd->enabled_targets[scsi_id] != NULL && ahd->enabled_targets[scsi_id] != master_tstate) panic("%s: ahd_alloc_tstate - Target already allocated", ahd_name(ahd)); tstate = malloc(sizeof(*tstate), M_DEVBUF, M_NOWAIT); if (tstate == NULL) return (NULL); /* * If we have allocated a master tstate, copy user settings from * the master tstate (taken from SRAM or the EEPROM) for this * channel, but reset our current and goal settings to async/narrow * until an initiator talks to us. */ if (master_tstate != NULL) { memcpy(tstate, master_tstate, sizeof(*tstate)); memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns)); for (i = 0; i < 16; i++) { memset(&tstate->transinfo[i].curr, 0, sizeof(tstate->transinfo[i].curr)); memset(&tstate->transinfo[i].goal, 0, sizeof(tstate->transinfo[i].goal)); } } else memset(tstate, 0, sizeof(*tstate)); ahd->enabled_targets[scsi_id] = tstate; return (tstate); } #ifdef AHD_TARGET_MODE /* * Free per target mode instance (ID we respond to as a target) * transfer negotiation data structures. */ static void ahd_free_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel, int force) { struct ahd_tmode_tstate *tstate; /* * Don't clean up our "master" tstate. * It has our default user settings. */ if (scsi_id == ahd->our_id && force == FALSE) return; tstate = ahd->enabled_targets[scsi_id]; if (tstate != NULL) free(tstate, M_DEVBUF); ahd->enabled_targets[scsi_id] = NULL; } #endif /* * Called when we have an active connection to a target on the bus, * this function finds the nearest period to the input period limited * by the capabilities of the bus connectivity of and sync settings for * the target. */ void ahd_devlimited_syncrate(struct ahd_softc *ahd, struct ahd_initiator_tinfo *tinfo, u_int *period, u_int *ppr_options, role_t role) { struct ahd_transinfo *transinfo; u_int maxsync; if ((ahd_inb(ahd, SBLKCTL) & ENAB40) != 0 && (ahd_inb(ahd, SSTAT2) & EXP_ACTIVE) == 0) { maxsync = AHD_SYNCRATE_PACED; } else { maxsync = AHD_SYNCRATE_ULTRA; /* Can't do DT related options on an SE bus */ *ppr_options &= MSG_EXT_PPR_QAS_REQ; } /* * Never allow a value higher than our current goal * period otherwise we may allow a target initiated * negotiation to go above the limit as set by the * user. In the case of an initiator initiated * sync negotiation, we limit based on the user * setting. This allows the system to still accept * incoming negotiations even if target initiated * negotiation is not performed. */ if (role == ROLE_TARGET) transinfo = &tinfo->user; else transinfo = &tinfo->goal; *ppr_options &= (transinfo->ppr_options|MSG_EXT_PPR_PCOMP_EN); if (transinfo->width == MSG_EXT_WDTR_BUS_8_BIT) { maxsync = max(maxsync, (u_int)AHD_SYNCRATE_ULTRA2); *ppr_options &= ~MSG_EXT_PPR_DT_REQ; } if (transinfo->period == 0) { *period = 0; *ppr_options = 0; } else { *period = max(*period, (u_int)transinfo->period); ahd_find_syncrate(ahd, period, ppr_options, maxsync); } } /* * Look up the valid period to SCSIRATE conversion in our table. * Return the period and offset that should be sent to the target * if this was the beginning of an SDTR. */ void ahd_find_syncrate(struct ahd_softc *ahd, u_int *period, u_int *ppr_options, u_int maxsync) { if (*period < maxsync) *period = maxsync; if ((*ppr_options & MSG_EXT_PPR_DT_REQ) != 0 && *period > AHD_SYNCRATE_MIN_DT) *ppr_options &= ~MSG_EXT_PPR_DT_REQ; if (*period > AHD_SYNCRATE_MIN) *period = 0; /* Honor PPR option conformance rules. */ if (*period > AHD_SYNCRATE_PACED) *ppr_options &= ~MSG_EXT_PPR_RTI; if ((*ppr_options & MSG_EXT_PPR_IU_REQ) == 0) *ppr_options &= (MSG_EXT_PPR_DT_REQ|MSG_EXT_PPR_QAS_REQ); if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0) *ppr_options &= MSG_EXT_PPR_QAS_REQ; /* Skip all PACED only entries if IU is not available */ if ((*ppr_options & MSG_EXT_PPR_IU_REQ) == 0 && *period < AHD_SYNCRATE_DT) *period = AHD_SYNCRATE_DT; /* Skip all DT only entries if DT is not available */ if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0 && *period < AHD_SYNCRATE_ULTRA2) *period = AHD_SYNCRATE_ULTRA2; } /* * Truncate the given synchronous offset to a value the * current adapter type and syncrate are capable of. */ static void ahd_validate_offset(struct ahd_softc *ahd, struct ahd_initiator_tinfo *tinfo, u_int period, u_int *offset, int wide, role_t role) { u_int maxoffset; /* Limit offset to what we can do */ if (period == 0) maxoffset = 0; else if (period <= AHD_SYNCRATE_PACED) { if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0) maxoffset = MAX_OFFSET_PACED_BUG; else maxoffset = MAX_OFFSET_PACED; } else maxoffset = MAX_OFFSET_NON_PACED; *offset = min(*offset, maxoffset); if (tinfo != NULL) { if (role == ROLE_TARGET) *offset = min(*offset, (u_int)tinfo->user.offset); else *offset = min(*offset, (u_int)tinfo->goal.offset); } } /* * Truncate the given transfer width parameter to a value the * current adapter type is capable of. */ static void ahd_validate_width(struct ahd_softc *ahd, struct ahd_initiator_tinfo *tinfo, u_int *bus_width, role_t role) { switch (*bus_width) { default: if (ahd->features & AHD_WIDE) { /* Respond Wide */ *bus_width = MSG_EXT_WDTR_BUS_16_BIT; break; } /* FALLTHROUGH */ case MSG_EXT_WDTR_BUS_8_BIT: *bus_width = MSG_EXT_WDTR_BUS_8_BIT; break; } if (tinfo != NULL) { if (role == ROLE_TARGET) *bus_width = min((u_int)tinfo->user.width, *bus_width); else *bus_width = min((u_int)tinfo->goal.width, *bus_width); } } /* * Update the bitmask of targets for which the controller should * negotiate with at the next convenient oportunity. This currently * means the next time we send the initial identify messages for * a new transaction. */ int ahd_update_neg_request(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, struct ahd_tmode_tstate *tstate, struct ahd_initiator_tinfo *tinfo, ahd_neg_type neg_type) { u_int auto_negotiate_orig; auto_negotiate_orig = tstate->auto_negotiate; if (neg_type == AHD_NEG_ALWAYS) { /* * Force our "current" settings to be * unknown so that unless a bus reset * occurs the need to renegotiate is * recorded persistently. */ if ((ahd->features & AHD_WIDE) != 0) tinfo->curr.width = AHD_WIDTH_UNKNOWN; tinfo->curr.period = AHD_PERIOD_UNKNOWN; tinfo->curr.offset = AHD_OFFSET_UNKNOWN; } if (tinfo->curr.period != tinfo->goal.period || tinfo->curr.width != tinfo->goal.width || tinfo->curr.offset != tinfo->goal.offset || tinfo->curr.ppr_options != tinfo->goal.ppr_options || (neg_type == AHD_NEG_IF_NON_ASYNC && (tinfo->goal.offset != 0 || tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT || tinfo->goal.ppr_options != 0))) tstate->auto_negotiate |= devinfo->target_mask; else tstate->auto_negotiate &= ~devinfo->target_mask; return (auto_negotiate_orig != tstate->auto_negotiate); } /* * Update the user/goal/curr tables of synchronous negotiation * parameters as well as, in the case of a current or active update, * any data structures on the host controller. In the case of an * active update, the specified target is currently talking to us on * the bus, so the transfer parameter update must take effect * immediately. */ void ahd_set_syncrate(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, u_int period, u_int offset, u_int ppr_options, u_int type, int paused) { struct ahd_initiator_tinfo *tinfo; struct ahd_tmode_tstate *tstate; u_int old_period; u_int old_offset; u_int old_ppr; int active; int update_needed; active = (type & AHD_TRANS_ACTIVE) == AHD_TRANS_ACTIVE; update_needed = 0; if (period == 0 || offset == 0) { period = 0; offset = 0; } tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid, devinfo->target, &tstate); if ((type & AHD_TRANS_USER) != 0) { tinfo->user.period = period; tinfo->user.offset = offset; tinfo->user.ppr_options = ppr_options; } if ((type & AHD_TRANS_GOAL) != 0) { tinfo->goal.period = period; tinfo->goal.offset = offset; tinfo->goal.ppr_options = ppr_options; } old_period = tinfo->curr.period; old_offset = tinfo->curr.offset; old_ppr = tinfo->curr.ppr_options; if ((type & AHD_TRANS_CUR) != 0 && (old_period != period || old_offset != offset || old_ppr != ppr_options)) { update_needed++; tinfo->curr.period = period; tinfo->curr.offset = offset; tinfo->curr.ppr_options = ppr_options; ahd_send_async(ahd, devinfo->channel, devinfo->target, CAM_LUN_WILDCARD, AC_TRANSFER_NEG); if (bootverbose) { if (offset != 0) { int options; printf("%s: target %d synchronous with " "period = 0x%x, offset = 0x%x", ahd_name(ahd), devinfo->target, period, offset); options = 0; if ((ppr_options & MSG_EXT_PPR_RD_STRM) != 0) { printf("(RDSTRM"); options++; } if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0) { printf("%s", options ? "|DT" : "(DT"); options++; } if ((ppr_options & MSG_EXT_PPR_IU_REQ) != 0) { printf("%s", options ? "|IU" : "(IU"); options++; } if ((ppr_options & MSG_EXT_PPR_RTI) != 0) { printf("%s", options ? "|RTI" : "(RTI"); options++; } if ((ppr_options & MSG_EXT_PPR_QAS_REQ) != 0) { printf("%s", options ? "|QAS" : "(QAS"); options++; } if (options != 0) printf(")\n"); else printf("\n"); } else { printf("%s: target %d using " "asynchronous transfers%s\n", ahd_name(ahd), devinfo->target, (ppr_options & MSG_EXT_PPR_QAS_REQ) != 0 ? "(QAS)" : ""); } } } /* * Always refresh the neg-table to handle the case of the * sequencer setting the ENATNO bit for a MK_MESSAGE request. * We will always renegotiate in that case if this is a * packetized request. Also manage the busfree expected flag * from this common routine so that we catch changes due to * WDTR or SDTR messages. */ if ((type & AHD_TRANS_CUR) != 0) { if (!paused) ahd_pause(ahd); ahd_update_neg_table(ahd, devinfo, &tinfo->curr); if (!paused) ahd_unpause(ahd); if (ahd->msg_type != MSG_TYPE_NONE) { if ((old_ppr & MSG_EXT_PPR_IU_REQ) != (ppr_options & MSG_EXT_PPR_IU_REQ)) { #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) { ahd_print_devinfo(ahd, devinfo); printf("Expecting IU Change busfree\n"); } #endif ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE | MSG_FLAG_IU_REQ_CHANGED; } if ((old_ppr & MSG_EXT_PPR_IU_REQ) != 0) { #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf("PPR with IU_REQ outstanding\n"); #endif ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE; } } } update_needed += ahd_update_neg_request(ahd, devinfo, tstate, tinfo, AHD_NEG_TO_GOAL); if (update_needed && active) ahd_update_pending_scbs(ahd); } /* * Update the user/goal/curr tables of wide negotiation * parameters as well as, in the case of a current or active update, * any data structures on the host controller. In the case of an * active update, the specified target is currently talking to us on * the bus, so the transfer parameter update must take effect * immediately. */ void ahd_set_width(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, u_int width, u_int type, int paused) { struct ahd_initiator_tinfo *tinfo; struct ahd_tmode_tstate *tstate; u_int oldwidth; int active; int update_needed; active = (type & AHD_TRANS_ACTIVE) == AHD_TRANS_ACTIVE; update_needed = 0; tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid, devinfo->target, &tstate); if ((type & AHD_TRANS_USER) != 0) tinfo->user.width = width; if ((type & AHD_TRANS_GOAL) != 0) tinfo->goal.width = width; oldwidth = tinfo->curr.width; if ((type & AHD_TRANS_CUR) != 0 && oldwidth != width) { update_needed++; tinfo->curr.width = width; ahd_send_async(ahd, devinfo->channel, devinfo->target, CAM_LUN_WILDCARD, AC_TRANSFER_NEG); if (bootverbose) { printf("%s: target %d using %dbit transfers\n", ahd_name(ahd), devinfo->target, 8 * (0x01 << width)); } } if ((type & AHD_TRANS_CUR) != 0) { if (!paused) ahd_pause(ahd); ahd_update_neg_table(ahd, devinfo, &tinfo->curr); if (!paused) ahd_unpause(ahd); } update_needed += ahd_update_neg_request(ahd, devinfo, tstate, tinfo, AHD_NEG_TO_GOAL); if (update_needed && active) ahd_update_pending_scbs(ahd); } /* * Update the current state of tagged queuing for a given target. */ static void ahd_set_tags(struct ahd_softc *ahd, struct scsi_cmnd *cmd, struct ahd_devinfo *devinfo, ahd_queue_alg alg) { struct scsi_device *sdev = cmd->device; ahd_platform_set_tags(ahd, sdev, devinfo, alg); ahd_send_async(ahd, devinfo->channel, devinfo->target, devinfo->lun, AC_TRANSFER_NEG); } static void ahd_update_neg_table(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, struct ahd_transinfo *tinfo) { ahd_mode_state saved_modes; u_int period; u_int ppr_opts; u_int con_opts; u_int offset; u_int saved_negoaddr; uint8_t iocell_opts[sizeof(ahd->iocell_opts)]; saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); saved_negoaddr = ahd_inb(ahd, NEGOADDR); ahd_outb(ahd, NEGOADDR, devinfo->target); period = tinfo->period; offset = tinfo->offset; memcpy(iocell_opts, ahd->iocell_opts, sizeof(ahd->iocell_opts)); ppr_opts = tinfo->ppr_options & (MSG_EXT_PPR_QAS_REQ|MSG_EXT_PPR_DT_REQ |MSG_EXT_PPR_IU_REQ|MSG_EXT_PPR_RTI); con_opts = 0; if (period == 0) period = AHD_SYNCRATE_ASYNC; if (period == AHD_SYNCRATE_160) { if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0) { /* * When the SPI4 spec was finalized, PACE transfers * was not made a configurable option in the PPR * message. Instead it is assumed to be enabled for * any syncrate faster than 80MHz. Nevertheless, * Harpoon2A4 allows this to be configurable. * * Harpoon2A4 also assumes at most 2 data bytes per * negotiated REQ/ACK offset. Paced transfers take * 4, so we must adjust our offset. */ ppr_opts |= PPROPT_PACE; offset *= 2; /* * Harpoon2A assumed that there would be a * fallback rate between 160MHz and 80Mhz, * so 7 is used as the period factor rather * than 8 for 160MHz. */ period = AHD_SYNCRATE_REVA_160; } if ((tinfo->ppr_options & MSG_EXT_PPR_PCOMP_EN) == 0) iocell_opts[AHD_PRECOMP_SLEW_INDEX] &= ~AHD_PRECOMP_MASK; } else { /* * Precomp should be disabled for non-paced transfers. */ iocell_opts[AHD_PRECOMP_SLEW_INDEX] &= ~AHD_PRECOMP_MASK; if ((ahd->features & AHD_NEW_IOCELL_OPTS) != 0 && (ppr_opts & MSG_EXT_PPR_DT_REQ) != 0 && (ppr_opts & MSG_EXT_PPR_IU_REQ) == 0) { /* * Slow down our CRC interval to be * compatible with non-packetized * U160 devices that can't handle a * CRC at full speed. */ con_opts |= ENSLOWCRC; } if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0) { /* * On H2A4, revert to a slower slewrate * on non-paced transfers. */ iocell_opts[AHD_PRECOMP_SLEW_INDEX] &= ~AHD_SLEWRATE_MASK; } } ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_PRECOMP_SLEW); ahd_outb(ahd, ANNEXDAT, iocell_opts[AHD_PRECOMP_SLEW_INDEX]); ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_AMPLITUDE); ahd_outb(ahd, ANNEXDAT, iocell_opts[AHD_AMPLITUDE_INDEX]); ahd_outb(ahd, NEGPERIOD, period); ahd_outb(ahd, NEGPPROPTS, ppr_opts); ahd_outb(ahd, NEGOFFSET, offset); if (tinfo->width == MSG_EXT_WDTR_BUS_16_BIT) con_opts |= WIDEXFER; /* * Slow down our CRC interval to be * compatible with packetized U320 devices * that can't handle a CRC at full speed */ if (ahd->features & AHD_AIC79XXB_SLOWCRC) { con_opts |= ENSLOWCRC; } /* * During packetized transfers, the target will * give us the oportunity to send command packets * without us asserting attention. */ if ((tinfo->ppr_options & MSG_EXT_PPR_IU_REQ) == 0) con_opts |= ENAUTOATNO; ahd_outb(ahd, NEGCONOPTS, con_opts); ahd_outb(ahd, NEGOADDR, saved_negoaddr); ahd_restore_modes(ahd, saved_modes); } /* * When the transfer settings for a connection change, setup for * negotiation in pending SCBs to effect the change as quickly as * possible. We also cancel any negotiations that are scheduled * for inflight SCBs that have not been started yet. */ static void ahd_update_pending_scbs(struct ahd_softc *ahd) { struct scb *pending_scb; int pending_scb_count; int paused; u_int saved_scbptr; ahd_mode_state saved_modes; /* * Traverse the pending SCB list and ensure that all of the * SCBs there have the proper settings. We can only safely * clear the negotiation required flag (setting requires the * execution queue to be modified) and this is only possible * if we are not already attempting to select out for this * SCB. For this reason, all callers only call this routine * if we are changing the negotiation settings for the currently * active transaction on the bus. */ pending_scb_count = 0; LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) { struct ahd_devinfo devinfo; struct ahd_initiator_tinfo *tinfo; struct ahd_tmode_tstate *tstate; ahd_scb_devinfo(ahd, &devinfo, pending_scb); tinfo = ahd_fetch_transinfo(ahd, devinfo.channel, devinfo.our_scsiid, devinfo.target, &tstate); if ((tstate->auto_negotiate & devinfo.target_mask) == 0 && (pending_scb->flags & SCB_AUTO_NEGOTIATE) != 0) { pending_scb->flags &= ~SCB_AUTO_NEGOTIATE; pending_scb->hscb->control &= ~MK_MESSAGE; } ahd_sync_scb(ahd, pending_scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE); pending_scb_count++; } if (pending_scb_count == 0) return; if (ahd_is_paused(ahd)) { paused = 1; } else { paused = 0; ahd_pause(ahd); } /* * Force the sequencer to reinitialize the selection for * the command at the head of the execution queue if it * has already been setup. The negotiation changes may * effect whether we select-out with ATN. It is only * safe to clear ENSELO when the bus is not free and no * selection is in progres or completed. */ saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); if ((ahd_inb(ahd, SCSISIGI) & BSYI) != 0 && (ahd_inb(ahd, SSTAT0) & (SELDO|SELINGO)) == 0) ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO); saved_scbptr = ahd_get_scbptr(ahd); /* Ensure that the hscbs down on the card match the new information */ LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) { u_int scb_tag; u_int control; scb_tag = SCB_GET_TAG(pending_scb); ahd_set_scbptr(ahd, scb_tag); control = ahd_inb_scbram(ahd, SCB_CONTROL); control &= ~MK_MESSAGE; control |= pending_scb->hscb->control & MK_MESSAGE; ahd_outb(ahd, SCB_CONTROL, control); } ahd_set_scbptr(ahd, saved_scbptr); ahd_restore_modes(ahd, saved_modes); if (paused == 0) ahd_unpause(ahd); } /**************************** Pathing Information *****************************/ static void ahd_fetch_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo) { ahd_mode_state saved_modes; u_int saved_scsiid; role_t role; int our_id; saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); if (ahd_inb(ahd, SSTAT0) & TARGET) role = ROLE_TARGET; else role = ROLE_INITIATOR; if (role == ROLE_TARGET && (ahd_inb(ahd, SEQ_FLAGS) & CMDPHASE_PENDING) != 0) { /* We were selected, so pull our id from TARGIDIN */ our_id = ahd_inb(ahd, TARGIDIN) & OID; } else if (role == ROLE_TARGET) our_id = ahd_inb(ahd, TOWNID); else our_id = ahd_inb(ahd, IOWNID); saved_scsiid = ahd_inb(ahd, SAVED_SCSIID); ahd_compile_devinfo(devinfo, our_id, SCSIID_TARGET(ahd, saved_scsiid), ahd_inb(ahd, SAVED_LUN), SCSIID_CHANNEL(ahd, saved_scsiid), role); ahd_restore_modes(ahd, saved_modes); } void ahd_print_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo) { printf("%s:%c:%d:%d: ", ahd_name(ahd), 'A', devinfo->target, devinfo->lun); } static struct ahd_phase_table_entry* ahd_lookup_phase_entry(int phase) { struct ahd_phase_table_entry *entry; struct ahd_phase_table_entry *last_entry; /* * num_phases doesn't include the default entry which * will be returned if the phase doesn't match. */ last_entry = &ahd_phase_table[num_phases]; for (entry = ahd_phase_table; entry < last_entry; entry++) { if (phase == entry->phase) break; } return (entry); } void ahd_compile_devinfo(struct ahd_devinfo *devinfo, u_int our_id, u_int target, u_int lun, char channel, role_t role) { devinfo->our_scsiid = our_id; devinfo->target = target; devinfo->lun = lun; devinfo->target_offset = target; devinfo->channel = channel; devinfo->role = role; if (channel == 'B') devinfo->target_offset += 8; devinfo->target_mask = (0x01 << devinfo->target_offset); } static void ahd_scb_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, struct scb *scb) { role_t role; int our_id; our_id = SCSIID_OUR_ID(scb->hscb->scsiid); role = ROLE_INITIATOR; if ((scb->hscb->control & TARGET_SCB) != 0) role = ROLE_TARGET; ahd_compile_devinfo(devinfo, our_id, SCB_GET_TARGET(ahd, scb), SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahd, scb), role); } /************************ Message Phase Processing ****************************/ /* * When an initiator transaction with the MK_MESSAGE flag either reconnects * or enters the initial message out phase, we are interrupted. Fill our * outgoing message buffer with the appropriate message and beging handing * the message phase(s) manually. */ static void ahd_setup_initiator_msgout(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, struct scb *scb) { /* * To facilitate adding multiple messages together, * each routine should increment the index and len * variables instead of setting them explicitly. */ ahd->msgout_index = 0; ahd->msgout_len = 0; if (ahd_currently_packetized(ahd)) ahd->msg_flags |= MSG_FLAG_PACKETIZED; if (ahd->send_msg_perror && ahd_inb(ahd, MSG_OUT) == HOST_MSG) { ahd->msgout_buf[ahd->msgout_index++] = ahd->send_msg_perror; ahd->msgout_len++; ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT; #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf("Setting up for Parity Error delivery\n"); #endif return; } else if (scb == NULL) { printf("%s: WARNING. No pending message for " "I_T msgin. Issuing NO-OP\n", ahd_name(ahd)); ahd->msgout_buf[ahd->msgout_index++] = MSG_NOOP; ahd->msgout_len++; ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT; return; } if ((scb->flags & SCB_DEVICE_RESET) == 0 && (scb->flags & SCB_PACKETIZED) == 0 && ahd_inb(ahd, MSG_OUT) == MSG_IDENTIFYFLAG) { u_int identify_msg; identify_msg = MSG_IDENTIFYFLAG | SCB_GET_LUN(scb); if ((scb->hscb->control & DISCENB) != 0) identify_msg |= MSG_IDENTIFY_DISCFLAG; ahd->msgout_buf[ahd->msgout_index++] = identify_msg; ahd->msgout_len++; if ((scb->hscb->control & TAG_ENB) != 0) { ahd->msgout_buf[ahd->msgout_index++] = scb->hscb->control & (TAG_ENB|SCB_TAG_TYPE); ahd->msgout_buf[ahd->msgout_index++] = SCB_GET_TAG(scb); ahd->msgout_len += 2; } } if (scb->flags & SCB_DEVICE_RESET) { ahd->msgout_buf[ahd->msgout_index++] = MSG_BUS_DEV_RESET; ahd->msgout_len++; ahd_print_path(ahd, scb); printf("Bus Device Reset Message Sent\n"); /* * Clear our selection hardware in advance of * the busfree. We may have an entry in the waiting * Q for this target, and we don't want to go about * selecting while we handle the busfree and blow it * away. */ ahd_outb(ahd, SCSISEQ0, 0); } else if ((scb->flags & SCB_ABORT) != 0) { if ((scb->hscb->control & TAG_ENB) != 0) { ahd->msgout_buf[ahd->msgout_index++] = MSG_ABORT_TAG; } else { ahd->msgout_buf[ahd->msgout_index++] = MSG_ABORT; } ahd->msgout_len++; ahd_print_path(ahd, scb); printf("Abort%s Message Sent\n", (scb->hscb->control & TAG_ENB) != 0 ? " Tag" : ""); /* * Clear our selection hardware in advance of * the busfree. We may have an entry in the waiting * Q for this target, and we don't want to go about * selecting while we handle the busfree and blow it * away. */ ahd_outb(ahd, SCSISEQ0, 0); } else if ((scb->flags & (SCB_AUTO_NEGOTIATE|SCB_NEGOTIATE)) != 0) { ahd_build_transfer_msg(ahd, devinfo); /* * Clear our selection hardware in advance of potential * PPR IU status change busfree. We may have an entry in * the waiting Q for this target, and we don't want to go * about selecting while we handle the busfree and blow * it away. */ ahd_outb(ahd, SCSISEQ0, 0); } else { printf("ahd_intr: AWAITING_MSG for an SCB that " "does not have a waiting message\n"); printf("SCSIID = %x, target_mask = %x\n", scb->hscb->scsiid, devinfo->target_mask); panic("SCB = %d, SCB Control = %x:%x, MSG_OUT = %x " "SCB flags = %x", SCB_GET_TAG(scb), scb->hscb->control, ahd_inb_scbram(ahd, SCB_CONTROL), ahd_inb(ahd, MSG_OUT), scb->flags); } /* * Clear the MK_MESSAGE flag from the SCB so we aren't * asked to send this message again. */ ahd_outb(ahd, SCB_CONTROL, ahd_inb_scbram(ahd, SCB_CONTROL) & ~MK_MESSAGE); scb->hscb->control &= ~MK_MESSAGE; ahd->msgout_index = 0; ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT; } /* * Build an appropriate transfer negotiation message for the * currently active target. */ static void ahd_build_transfer_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo) { /* * We need to initiate transfer negotiations. * If our current and goal settings are identical, * we want to renegotiate due to a check condition. */ struct ahd_initiator_tinfo *tinfo; struct ahd_tmode_tstate *tstate; int dowide; int dosync; int doppr; u_int period; u_int ppr_options; u_int offset; tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid, devinfo->target, &tstate); /* * Filter our period based on the current connection. * If we can't perform DT transfers on this segment (not in LVD * mode for instance), then our decision to issue a PPR message * may change. */ period = tinfo->goal.period; offset = tinfo->goal.offset; ppr_options = tinfo->goal.ppr_options; /* Target initiated PPR is not allowed in the SCSI spec */ if (devinfo->role == ROLE_TARGET) ppr_options = 0; ahd_devlimited_syncrate(ahd, tinfo, &period, &ppr_options, devinfo->role); dowide = tinfo->curr.width != tinfo->goal.width; dosync = tinfo->curr.offset != offset || tinfo->curr.period != period; /* * Only use PPR if we have options that need it, even if the device * claims to support it. There might be an expander in the way * that doesn't. */ doppr = ppr_options != 0; if (!dowide && !dosync && !doppr) { dowide = tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT; dosync = tinfo->goal.offset != 0; } if (!dowide && !dosync && !doppr) { /* * Force async with a WDTR message if we have a wide bus, * or just issue an SDTR with a 0 offset. */ if ((ahd->features & AHD_WIDE) != 0) dowide = 1; else dosync = 1; if (bootverbose) { ahd_print_devinfo(ahd, devinfo); printf("Ensuring async\n"); } } /* Target initiated PPR is not allowed in the SCSI spec */ if (devinfo->role == ROLE_TARGET) doppr = 0; /* * Both the PPR message and SDTR message require the * goal syncrate to be limited to what the target device * is capable of handling (based on whether an LVD->SE * expander is on the bus), so combine these two cases. * Regardless, guarantee that if we are using WDTR and SDTR * messages that WDTR comes first. */ if (doppr || (dosync && !dowide)) { offset = tinfo->goal.offset; ahd_validate_offset(ahd, tinfo, period, &offset, doppr ? tinfo->goal.width : tinfo->curr.width, devinfo->role); if (doppr) { ahd_construct_ppr(ahd, devinfo, period, offset, tinfo->goal.width, ppr_options); } else { ahd_construct_sdtr(ahd, devinfo, period, offset); } } else { ahd_construct_wdtr(ahd, devinfo, tinfo->goal.width); } } /* * Build a synchronous negotiation message in our message * buffer based on the input parameters. */ static void ahd_construct_sdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, u_int period, u_int offset) { if (offset == 0) period = AHD_ASYNC_XFER_PERIOD; ahd->msgout_index += spi_populate_sync_msg( ahd->msgout_buf + ahd->msgout_index, period, offset); ahd->msgout_len += 5; if (bootverbose) { printf("(%s:%c:%d:%d): Sending SDTR period %x, offset %x\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun, period, offset); } } /* * Build a wide negotiateion message in our message * buffer based on the input parameters. */ static void ahd_construct_wdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, u_int bus_width) { ahd->msgout_index += spi_populate_width_msg( ahd->msgout_buf + ahd->msgout_index, bus_width); ahd->msgout_len += 4; if (bootverbose) { printf("(%s:%c:%d:%d): Sending WDTR %x\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun, bus_width); } } /* * Build a parallel protocol request message in our message * buffer based on the input parameters. */ static void ahd_construct_ppr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, u_int period, u_int offset, u_int bus_width, u_int ppr_options) { /* * Always request precompensation from * the other target if we are running * at paced syncrates. */ if (period <= AHD_SYNCRATE_PACED) ppr_options |= MSG_EXT_PPR_PCOMP_EN; if (offset == 0) period = AHD_ASYNC_XFER_PERIOD; ahd->msgout_index += spi_populate_ppr_msg( ahd->msgout_buf + ahd->msgout_index, period, offset, bus_width, ppr_options); ahd->msgout_len += 8; if (bootverbose) { printf("(%s:%c:%d:%d): Sending PPR bus_width %x, period %x, " "offset %x, ppr_options %x\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun, bus_width, period, offset, ppr_options); } } /* * Clear any active message state. */ static void ahd_clear_msg_state(struct ahd_softc *ahd) { ahd_mode_state saved_modes; saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); ahd->send_msg_perror = 0; ahd->msg_flags = MSG_FLAG_NONE; ahd->msgout_len = 0; ahd->msgin_index = 0; ahd->msg_type = MSG_TYPE_NONE; if ((ahd_inb(ahd, SCSISIGO) & ATNO) != 0) { /* * The target didn't care to respond to our * message request, so clear ATN. */ ahd_outb(ahd, CLRSINT1, CLRATNO); } ahd_outb(ahd, MSG_OUT, MSG_NOOP); ahd_outb(ahd, SEQ_FLAGS2, ahd_inb(ahd, SEQ_FLAGS2) & ~TARGET_MSG_PENDING); ahd_restore_modes(ahd, saved_modes); } /* * Manual message loop handler. */ static void ahd_handle_message_phase(struct ahd_softc *ahd) { struct ahd_devinfo devinfo; u_int bus_phase; int end_session; ahd_fetch_devinfo(ahd, &devinfo); end_session = FALSE; bus_phase = ahd_inb(ahd, LASTPHASE); if ((ahd_inb(ahd, LQISTAT2) & LQIPHASE_OUTPKT) != 0) { printf("LQIRETRY for LQIPHASE_OUTPKT\n"); ahd_outb(ahd, LQCTL2, LQIRETRY); } reswitch: switch (ahd->msg_type) { case MSG_TYPE_INITIATOR_MSGOUT: { int lastbyte; int phasemis; int msgdone; if (ahd->msgout_len == 0 && ahd->send_msg_perror == 0) panic("HOST_MSG_LOOP interrupt with no active message"); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) { ahd_print_devinfo(ahd, &devinfo); printf("INITIATOR_MSG_OUT"); } #endif phasemis = bus_phase != P_MESGOUT; if (phasemis) { #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) { printf(" PHASEMIS %s\n", ahd_lookup_phase_entry(bus_phase) ->phasemsg); } #endif if (bus_phase == P_MESGIN) { /* * Change gears and see if * this messages is of interest to * us or should be passed back to * the sequencer. */ ahd_outb(ahd, CLRSINT1, CLRATNO); ahd->send_msg_perror = 0; ahd->msg_type = MSG_TYPE_INITIATOR_MSGIN; ahd->msgin_index = 0; goto reswitch; } end_session = TRUE; break; } if (ahd->send_msg_perror) { ahd_outb(ahd, CLRSINT1, CLRATNO); ahd_outb(ahd, CLRSINT1, CLRREQINIT); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf(" byte 0x%x\n", ahd->send_msg_perror); #endif /* * If we are notifying the target of a CRC error * during packetized operations, the target is * within its rights to acknowledge our message * with a busfree. */ if ((ahd->msg_flags & MSG_FLAG_PACKETIZED) != 0 && ahd->send_msg_perror == MSG_INITIATOR_DET_ERR) ahd->msg_flags |= MSG_FLAG_EXPECT_IDE_BUSFREE; ahd_outb(ahd, RETURN_2, ahd->send_msg_perror); ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_WRITE); break; } msgdone = ahd->msgout_index == ahd->msgout_len; if (msgdone) { /* * The target has requested a retry. * Re-assert ATN, reset our message index to * 0, and try again. */ ahd->msgout_index = 0; ahd_assert_atn(ahd); } lastbyte = ahd->msgout_index == (ahd->msgout_len - 1); if (lastbyte) { /* Last byte is signified by dropping ATN */ ahd_outb(ahd, CLRSINT1, CLRATNO); } /* * Clear our interrupt status and present * the next byte on the bus. */ ahd_outb(ahd, CLRSINT1, CLRREQINIT); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf(" byte 0x%x\n", ahd->msgout_buf[ahd->msgout_index]); #endif ahd_outb(ahd, RETURN_2, ahd->msgout_buf[ahd->msgout_index++]); ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_WRITE); break; } case MSG_TYPE_INITIATOR_MSGIN: { int phasemis; int message_done; #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) { ahd_print_devinfo(ahd, &devinfo); printf("INITIATOR_MSG_IN"); } #endif phasemis = bus_phase != P_MESGIN; if (phasemis) { #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) { printf(" PHASEMIS %s\n", ahd_lookup_phase_entry(bus_phase) ->phasemsg); } #endif ahd->msgin_index = 0; if (bus_phase == P_MESGOUT && (ahd->send_msg_perror != 0 || (ahd->msgout_len != 0 && ahd->msgout_index == 0))) { ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT; goto reswitch; } end_session = TRUE; break; } /* Pull the byte in without acking it */ ahd->msgin_buf[ahd->msgin_index] = ahd_inb(ahd, SCSIBUS); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf(" byte 0x%x\n", ahd->msgin_buf[ahd->msgin_index]); #endif message_done = ahd_parse_msg(ahd, &devinfo); if (message_done) { /* * Clear our incoming message buffer in case there * is another message following this one. */ ahd->msgin_index = 0; /* * If this message illicited a response, * assert ATN so the target takes us to the * message out phase. */ if (ahd->msgout_len != 0) { #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) { ahd_print_devinfo(ahd, &devinfo); printf("Asserting ATN for response\n"); } #endif ahd_assert_atn(ahd); } } else ahd->msgin_index++; if (message_done == MSGLOOP_TERMINATED) { end_session = TRUE; } else { /* Ack the byte */ ahd_outb(ahd, CLRSINT1, CLRREQINIT); ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_READ); } break; } case MSG_TYPE_TARGET_MSGIN: { int msgdone; int msgout_request; /* * By default, the message loop will continue. */ ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_TARG); if (ahd->msgout_len == 0) panic("Target MSGIN with no active message"); /* * If we interrupted a mesgout session, the initiator * will not know this until our first REQ. So, we * only honor mesgout requests after we've sent our * first byte. */ if ((ahd_inb(ahd, SCSISIGI) & ATNI) != 0 && ahd->msgout_index > 0) msgout_request = TRUE; else msgout_request = FALSE; if (msgout_request) { /* * Change gears and see if * this messages is of interest to * us or should be passed back to * the sequencer. */ ahd->msg_type = MSG_TYPE_TARGET_MSGOUT; ahd_outb(ahd, SCSISIGO, P_MESGOUT | BSYO); ahd->msgin_index = 0; /* Dummy read to REQ for first byte */ ahd_inb(ahd, SCSIDAT); ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) | SPIOEN); break; } msgdone = ahd->msgout_index == ahd->msgout_len; if (msgdone) { ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) & ~SPIOEN); end_session = TRUE; break; } /* * Present the next byte on the bus. */ ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) | SPIOEN); ahd_outb(ahd, SCSIDAT, ahd->msgout_buf[ahd->msgout_index++]); break; } case MSG_TYPE_TARGET_MSGOUT: { int lastbyte; int msgdone; /* * By default, the message loop will continue. */ ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_TARG); /* * The initiator signals that this is * the last byte by dropping ATN. */ lastbyte = (ahd_inb(ahd, SCSISIGI) & ATNI) == 0; /* * Read the latched byte, but turn off SPIOEN first * so that we don't inadvertently cause a REQ for the * next byte. */ ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) & ~SPIOEN); ahd->msgin_buf[ahd->msgin_index] = ahd_inb(ahd, SCSIDAT); msgdone = ahd_parse_msg(ahd, &devinfo); if (msgdone == MSGLOOP_TERMINATED) { /* * The message is *really* done in that it caused * us to go to bus free. The sequencer has already * been reset at this point, so pull the ejection * handle. */ return; } ahd->msgin_index++; /* * XXX Read spec about initiator dropping ATN too soon * and use msgdone to detect it. */ if (msgdone == MSGLOOP_MSGCOMPLETE) { ahd->msgin_index = 0; /* * If this message illicited a response, transition * to the Message in phase and send it. */ if (ahd->msgout_len != 0) { ahd_outb(ahd, SCSISIGO, P_MESGIN | BSYO); ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) | SPIOEN); ahd->msg_type = MSG_TYPE_TARGET_MSGIN; ahd->msgin_index = 0; break; } } if (lastbyte) end_session = TRUE; else { /* Ask for the next byte. */ ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) | SPIOEN); } break; } default: panic("Unknown REQINIT message type"); } if (end_session) { if ((ahd->msg_flags & MSG_FLAG_PACKETIZED) != 0) { printf("%s: Returning to Idle Loop\n", ahd_name(ahd)); ahd_clear_msg_state(ahd); /* * Perform the equivalent of a clear_target_state. */ ahd_outb(ahd, LASTPHASE, P_BUSFREE); ahd_outb(ahd, SEQ_FLAGS, NOT_IDENTIFIED|NO_CDB_SENT); ahd_outb(ahd, SEQCTL0, FASTMODE|SEQRESET); } else { ahd_clear_msg_state(ahd); ahd_outb(ahd, RETURN_1, EXIT_MSG_LOOP); } } } /* * See if we sent a particular extended message to the target. * If "full" is true, return true only if the target saw the full * message. If "full" is false, return true if the target saw at * least the first byte of the message. */ static int ahd_sent_msg(struct ahd_softc *ahd, ahd_msgtype type, u_int msgval, int full) { int found; u_int index; found = FALSE; index = 0; while (index < ahd->msgout_len) { if (ahd->msgout_buf[index] == MSG_EXTENDED) { u_int end_index; end_index = index + 1 + ahd->msgout_buf[index + 1]; if (ahd->msgout_buf[index+2] == msgval && type == AHDMSG_EXT) { if (full) { if (ahd->msgout_index > end_index) found = TRUE; } else if (ahd->msgout_index > index) found = TRUE; } index = end_index; } else if (ahd->msgout_buf[index] >= MSG_SIMPLE_TASK && ahd->msgout_buf[index] <= MSG_IGN_WIDE_RESIDUE) { /* Skip tag type and tag id or residue param*/ index += 2; } else { /* Single byte message */ if (type == AHDMSG_1B && ahd->msgout_index > index && (ahd->msgout_buf[index] == msgval || ((ahd->msgout_buf[index] & MSG_IDENTIFYFLAG) != 0 && msgval == MSG_IDENTIFYFLAG))) found = TRUE; index++; } if (found) break; } return (found); } /* * Wait for a complete incoming message, parse it, and respond accordingly. */ static int ahd_parse_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo) { struct ahd_initiator_tinfo *tinfo; struct ahd_tmode_tstate *tstate; int reject; int done; int response; done = MSGLOOP_IN_PROG; response = FALSE; reject = FALSE; tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid, devinfo->target, &tstate); /* * Parse as much of the message as is available, * rejecting it if we don't support it. When * the entire message is available and has been * handled, return MSGLOOP_MSGCOMPLETE, indicating * that we have parsed an entire message. * * In the case of extended messages, we accept the length * byte outright and perform more checking once we know the * extended message type. */ switch (ahd->msgin_buf[0]) { case MSG_DISCONNECT: case MSG_SAVEDATAPOINTER: case MSG_CMDCOMPLETE: case MSG_RESTOREPOINTERS: case MSG_IGN_WIDE_RESIDUE: /* * End our message loop as these are messages * the sequencer handles on its own. */ done = MSGLOOP_TERMINATED; break; case MSG_MESSAGE_REJECT: response = ahd_handle_msg_reject(ahd, devinfo); /* FALLTHROUGH */ case MSG_NOOP: done = MSGLOOP_MSGCOMPLETE; break; case MSG_EXTENDED: { /* Wait for enough of the message to begin validation */ if (ahd->msgin_index < 2) break; switch (ahd->msgin_buf[2]) { case MSG_EXT_SDTR: { u_int period; u_int ppr_options; u_int offset; u_int saved_offset; if (ahd->msgin_buf[1] != MSG_EXT_SDTR_LEN) { reject = TRUE; break; } /* * Wait until we have both args before validating * and acting on this message. * * Add one to MSG_EXT_SDTR_LEN to account for * the extended message preamble. */ if (ahd->msgin_index < (MSG_EXT_SDTR_LEN + 1)) break; period = ahd->msgin_buf[3]; ppr_options = 0; saved_offset = offset = ahd->msgin_buf[4]; ahd_devlimited_syncrate(ahd, tinfo, &period, &ppr_options, devinfo->role); ahd_validate_offset(ahd, tinfo, period, &offset, tinfo->curr.width, devinfo->role); if (bootverbose) { printf("(%s:%c:%d:%d): Received " "SDTR period %x, offset %x\n\t" "Filtered to period %x, offset %x\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun, ahd->msgin_buf[3], saved_offset, period, offset); } ahd_set_syncrate(ahd, devinfo, period, offset, ppr_options, AHD_TRANS_ACTIVE|AHD_TRANS_GOAL, /*paused*/TRUE); /* * See if we initiated Sync Negotiation * and didn't have to fall down to async * transfers. */ if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, TRUE)) { /* We started it */ if (saved_offset != offset) { /* Went too low - force async */ reject = TRUE; } } else { /* * Send our own SDTR in reply */ if (bootverbose && devinfo->role == ROLE_INITIATOR) { printf("(%s:%c:%d:%d): Target " "Initiated SDTR\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun); } ahd->msgout_index = 0; ahd->msgout_len = 0; ahd_construct_sdtr(ahd, devinfo, period, offset); ahd->msgout_index = 0; response = TRUE; } done = MSGLOOP_MSGCOMPLETE; break; } case MSG_EXT_WDTR: { u_int bus_width; u_int saved_width; u_int sending_reply; sending_reply = FALSE; if (ahd->msgin_buf[1] != MSG_EXT_WDTR_LEN) { reject = TRUE; break; } /* * Wait until we have our arg before validating * and acting on this message. * * Add one to MSG_EXT_WDTR_LEN to account for * the extended message preamble. */ if (ahd->msgin_index < (MSG_EXT_WDTR_LEN + 1)) break; bus_width = ahd->msgin_buf[3]; saved_width = bus_width; ahd_validate_width(ahd, tinfo, &bus_width, devinfo->role); if (bootverbose) { printf("(%s:%c:%d:%d): Received WDTR " "%x filtered to %x\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun, saved_width, bus_width); } if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, TRUE)) { /* * Don't send a WDTR back to the * target, since we asked first. * If the width went higher than our * request, reject it. */ if (saved_width > bus_width) { reject = TRUE; printf("(%s:%c:%d:%d): requested %dBit " "transfers. Rejecting...\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun, 8 * (0x01 << bus_width)); bus_width = 0; } } else { /* * Send our own WDTR in reply */ if (bootverbose && devinfo->role == ROLE_INITIATOR) { printf("(%s:%c:%d:%d): Target " "Initiated WDTR\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun); } ahd->msgout_index = 0; ahd->msgout_len = 0; ahd_construct_wdtr(ahd, devinfo, bus_width); ahd->msgout_index = 0; response = TRUE; sending_reply = TRUE; } /* * After a wide message, we are async, but * some devices don't seem to honor this portion * of the spec. Force a renegotiation of the * sync component of our transfer agreement even * if our goal is async. By updating our width * after forcing the negotiation, we avoid * renegotiating for width. */ ahd_update_neg_request(ahd, devinfo, tstate, tinfo, AHD_NEG_ALWAYS); ahd_set_width(ahd, devinfo, bus_width, AHD_TRANS_ACTIVE|AHD_TRANS_GOAL, /*paused*/TRUE); if (sending_reply == FALSE && reject == FALSE) { /* * We will always have an SDTR to send. */ ahd->msgout_index = 0; ahd->msgout_len = 0; ahd_build_transfer_msg(ahd, devinfo); ahd->msgout_index = 0; response = TRUE; } done = MSGLOOP_MSGCOMPLETE; break; } case MSG_EXT_PPR: { u_int period; u_int offset; u_int bus_width; u_int ppr_options; u_int saved_width; u_int saved_offset; u_int saved_ppr_options; if (ahd->msgin_buf[1] != MSG_EXT_PPR_LEN) { reject = TRUE; break; } /* * Wait until we have all args before validating * and acting on this message. * * Add one to MSG_EXT_PPR_LEN to account for * the extended message preamble. */ if (ahd->msgin_index < (MSG_EXT_PPR_LEN + 1)) break; period = ahd->msgin_buf[3]; offset = ahd->msgin_buf[5]; bus_width = ahd->msgin_buf[6]; saved_width = bus_width; ppr_options = ahd->msgin_buf[7]; /* * According to the spec, a DT only * period factor with no DT option * set implies async. */ if ((ppr_options & MSG_EXT_PPR_DT_REQ) == 0 && period <= 9) offset = 0; saved_ppr_options = ppr_options; saved_offset = offset; /* * Transfer options are only available if we * are negotiating wide. */ if (bus_width == 0) ppr_options &= MSG_EXT_PPR_QAS_REQ; ahd_validate_width(ahd, tinfo, &bus_width, devinfo->role); ahd_devlimited_syncrate(ahd, tinfo, &period, &ppr_options, devinfo->role); ahd_validate_offset(ahd, tinfo, period, &offset, bus_width, devinfo->role); if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, TRUE)) { /* * If we are unable to do any of the * requested options (we went too low), * then we'll have to reject the message. */ if (saved_width > bus_width || saved_offset != offset || saved_ppr_options != ppr_options) { reject = TRUE; period = 0; offset = 0; bus_width = 0; ppr_options = 0; } } else { if (devinfo->role != ROLE_TARGET) printf("(%s:%c:%d:%d): Target " "Initiated PPR\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun); else printf("(%s:%c:%d:%d): Initiator " "Initiated PPR\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun); ahd->msgout_index = 0; ahd->msgout_len = 0; ahd_construct_ppr(ahd, devinfo, period, offset, bus_width, ppr_options); ahd->msgout_index = 0; response = TRUE; } if (bootverbose) { printf("(%s:%c:%d:%d): Received PPR width %x, " "period %x, offset %x,options %x\n" "\tFiltered to width %x, period %x, " "offset %x, options %x\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun, saved_width, ahd->msgin_buf[3], saved_offset, saved_ppr_options, bus_width, period, offset, ppr_options); } ahd_set_width(ahd, devinfo, bus_width, AHD_TRANS_ACTIVE|AHD_TRANS_GOAL, /*paused*/TRUE); ahd_set_syncrate(ahd, devinfo, period, offset, ppr_options, AHD_TRANS_ACTIVE|AHD_TRANS_GOAL, /*paused*/TRUE); done = MSGLOOP_MSGCOMPLETE; break; } default: /* Unknown extended message. Reject it. */ reject = TRUE; break; } break; } #ifdef AHD_TARGET_MODE case MSG_BUS_DEV_RESET: ahd_handle_devreset(ahd, devinfo, CAM_LUN_WILDCARD, CAM_BDR_SENT, "Bus Device Reset Received", /*verbose_level*/0); ahd_restart(ahd); done = MSGLOOP_TERMINATED; break; case MSG_ABORT_TAG: case MSG_ABORT: case MSG_CLEAR_QUEUE: { int tag; /* Target mode messages */ if (devinfo->role != ROLE_TARGET) { reject = TRUE; break; } tag = SCB_LIST_NULL; if (ahd->msgin_buf[0] == MSG_ABORT_TAG) tag = ahd_inb(ahd, INITIATOR_TAG); ahd_abort_scbs(ahd, devinfo->target, devinfo->channel, devinfo->lun, tag, ROLE_TARGET, CAM_REQ_ABORTED); tstate = ahd->enabled_targets[devinfo->our_scsiid]; if (tstate != NULL) { struct ahd_tmode_lstate* lstate; lstate = tstate->enabled_luns[devinfo->lun]; if (lstate != NULL) { ahd_queue_lstate_event(ahd, lstate, devinfo->our_scsiid, ahd->msgin_buf[0], /*arg*/tag); ahd_send_lstate_events(ahd, lstate); } } ahd_restart(ahd); done = MSGLOOP_TERMINATED; break; } #endif case MSG_QAS_REQUEST: #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) printf("%s: QAS request. SCSISIGI == 0x%x\n", ahd_name(ahd), ahd_inb(ahd, SCSISIGI)); #endif ahd->msg_flags |= MSG_FLAG_EXPECT_QASREJ_BUSFREE; /* FALLTHROUGH */ case MSG_TERM_IO_PROC: default: reject = TRUE; break; } if (reject) { /* * Setup to reject the message. */ ahd->msgout_index = 0; ahd->msgout_len = 1; ahd->msgout_buf[0] = MSG_MESSAGE_REJECT; done = MSGLOOP_MSGCOMPLETE; response = TRUE; } if (done != MSGLOOP_IN_PROG && !response) /* Clear the outgoing message buffer */ ahd->msgout_len = 0; return (done); } /* * Process a message reject message. */ static int ahd_handle_msg_reject(struct ahd_softc *ahd, struct ahd_devinfo *devinfo) { /* * What we care about here is if we had an * outstanding SDTR or WDTR message for this * target. If we did, this is a signal that * the target is refusing negotiation. */ struct scb *scb; struct ahd_initiator_tinfo *tinfo; struct ahd_tmode_tstate *tstate; u_int scb_index; u_int last_msg; int response = 0; scb_index = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scb_index); tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid, devinfo->target, &tstate); /* Might be necessary */ last_msg = ahd_inb(ahd, LAST_MSG); if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, /*full*/FALSE)) { if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, /*full*/TRUE) && tinfo->goal.period <= AHD_SYNCRATE_PACED) { /* * Target may not like our SPI-4 PPR Options. * Attempt to negotiate 80MHz which will turn * off these options. */ if (bootverbose) { printf("(%s:%c:%d:%d): PPR Rejected. " "Trying simple U160 PPR\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun); } tinfo->goal.period = AHD_SYNCRATE_DT; tinfo->goal.ppr_options &= MSG_EXT_PPR_IU_REQ | MSG_EXT_PPR_QAS_REQ | MSG_EXT_PPR_DT_REQ; } else { /* * Target does not support the PPR message. * Attempt to negotiate SPI-2 style. */ if (bootverbose) { printf("(%s:%c:%d:%d): PPR Rejected. " "Trying WDTR/SDTR\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun); } tinfo->goal.ppr_options = 0; tinfo->curr.transport_version = 2; tinfo->goal.transport_version = 2; } ahd->msgout_index = 0; ahd->msgout_len = 0; ahd_build_transfer_msg(ahd, devinfo); ahd->msgout_index = 0; response = 1; } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, /*full*/FALSE)) { /* note 8bit xfers */ printf("(%s:%c:%d:%d): refuses WIDE negotiation. Using " "8bit transfers\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun); ahd_set_width(ahd, devinfo, MSG_EXT_WDTR_BUS_8_BIT, AHD_TRANS_ACTIVE|AHD_TRANS_GOAL, /*paused*/TRUE); /* * No need to clear the sync rate. If the target * did not accept the command, our syncrate is * unaffected. If the target started the negotiation, * but rejected our response, we already cleared the * sync rate before sending our WDTR. */ if (tinfo->goal.offset != tinfo->curr.offset) { /* Start the sync negotiation */ ahd->msgout_index = 0; ahd->msgout_len = 0; ahd_build_transfer_msg(ahd, devinfo); ahd->msgout_index = 0; response = 1; } } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, /*full*/FALSE)) { /* note asynch xfers and clear flag */ ahd_set_syncrate(ahd, devinfo, /*period*/0, /*offset*/0, /*ppr_options*/0, AHD_TRANS_ACTIVE|AHD_TRANS_GOAL, /*paused*/TRUE); printf("(%s:%c:%d:%d): refuses synchronous negotiation. " "Using asynchronous transfers\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun); } else if ((scb->hscb->control & MSG_SIMPLE_TASK) != 0) { int tag_type; int mask; tag_type = (scb->hscb->control & MSG_SIMPLE_TASK); if (tag_type == MSG_SIMPLE_TASK) { printf("(%s:%c:%d:%d): refuses tagged commands. " "Performing non-tagged I/O\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun); ahd_set_tags(ahd, scb->io_ctx, devinfo, AHD_QUEUE_NONE); mask = ~0x23; } else { printf("(%s:%c:%d:%d): refuses %s tagged commands. " "Performing simple queue tagged I/O only\n", ahd_name(ahd), devinfo->channel, devinfo->target, devinfo->lun, tag_type == MSG_ORDERED_TASK ? "ordered" : "head of queue"); ahd_set_tags(ahd, scb->io_ctx, devinfo, AHD_QUEUE_BASIC); mask = ~0x03; } /* * Resend the identify for this CCB as the target * may believe that the selection is invalid otherwise. */ ahd_outb(ahd, SCB_CONTROL, ahd_inb_scbram(ahd, SCB_CONTROL) & mask); scb->hscb->control &= mask; ahd_set_transaction_tag(scb, /*enabled*/FALSE, /*type*/MSG_SIMPLE_TASK); ahd_outb(ahd, MSG_OUT, MSG_IDENTIFYFLAG); ahd_assert_atn(ahd); ahd_busy_tcl(ahd, BUILD_TCL(scb->hscb->scsiid, devinfo->lun), SCB_GET_TAG(scb)); /* * Requeue all tagged commands for this target * currently in our posession so they can be * converted to untagged commands. */ ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb), SCB_GET_CHANNEL(ahd, scb), SCB_GET_LUN(scb), /*tag*/SCB_LIST_NULL, ROLE_INITIATOR, CAM_REQUEUE_REQ, SEARCH_COMPLETE); } else if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_IDENTIFYFLAG, TRUE)) { /* * Most likely the device believes that we had * previously negotiated packetized. */ ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE | MSG_FLAG_IU_REQ_CHANGED; ahd_force_renegotiation(ahd, devinfo); ahd->msgout_index = 0; ahd->msgout_len = 0; ahd_build_transfer_msg(ahd, devinfo); ahd->msgout_index = 0; response = 1; } else { /* * Otherwise, we ignore it. */ printf("%s:%c:%d: Message reject for %x -- ignored\n", ahd_name(ahd), devinfo->channel, devinfo->target, last_msg); } return (response); } /* * Process an ingnore wide residue message. */ static void ahd_handle_ign_wide_residue(struct ahd_softc *ahd, struct ahd_devinfo *devinfo) { u_int scb_index; struct scb *scb; scb_index = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scb_index); /* * XXX Actually check data direction in the sequencer? * Perhaps add datadir to some spare bits in the hscb? */ if ((ahd_inb(ahd, SEQ_FLAGS) & DPHASE) == 0 || ahd_get_transfer_dir(scb) != CAM_DIR_IN) { /* * Ignore the message if we haven't * seen an appropriate data phase yet. */ } else { /* * If the residual occurred on the last * transfer and the transfer request was * expected to end on an odd count, do * nothing. Otherwise, subtract a byte * and update the residual count accordingly. */ uint32_t sgptr; sgptr = ahd_inb_scbram(ahd, SCB_RESIDUAL_SGPTR); if ((sgptr & SG_LIST_NULL) != 0 && (ahd_inb_scbram(ahd, SCB_TASK_ATTRIBUTE) & SCB_XFERLEN_ODD) != 0) { /* * If the residual occurred on the last * transfer and the transfer request was * expected to end on an odd count, do * nothing. */ } else { uint32_t data_cnt; uint64_t data_addr; uint32_t sglen; /* Pull in the rest of the sgptr */ sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR); data_cnt = ahd_inl_scbram(ahd, SCB_RESIDUAL_DATACNT); if ((sgptr & SG_LIST_NULL) != 0) { /* * The residual data count is not updated * for the command run to completion case. * Explicitly zero the count. */ data_cnt &= ~AHD_SG_LEN_MASK; } data_addr = ahd_inq(ahd, SHADDR); data_cnt += 1; data_addr -= 1; sgptr &= SG_PTR_MASK; if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) { struct ahd_dma64_seg *sg; sg = ahd_sg_bus_to_virt(ahd, scb, sgptr); /* * The residual sg ptr points to the next S/G * to load so we must go back one. */ sg--; sglen = ahd_le32toh(sg->len) & AHD_SG_LEN_MASK; if (sg != scb->sg_list && sglen < (data_cnt & AHD_SG_LEN_MASK)) { sg--; sglen = ahd_le32toh(sg->len); /* * Preserve High Address and SG_LIST * bits while setting the count to 1. */ data_cnt = 1|(sglen&(~AHD_SG_LEN_MASK)); data_addr = ahd_le64toh(sg->addr) + (sglen & AHD_SG_LEN_MASK) - 1; /* * Increment sg so it points to the * "next" sg. */ sg++; sgptr = ahd_sg_virt_to_bus(ahd, scb, sg); } } else { struct ahd_dma_seg *sg; sg = ahd_sg_bus_to_virt(ahd, scb, sgptr); /* * The residual sg ptr points to the next S/G * to load so we must go back one. */ sg--; sglen = ahd_le32toh(sg->len) & AHD_SG_LEN_MASK; if (sg != scb->sg_list && sglen < (data_cnt & AHD_SG_LEN_MASK)) { sg--; sglen = ahd_le32toh(sg->len); /* * Preserve High Address and SG_LIST * bits while setting the count to 1. */ data_cnt = 1|(sglen&(~AHD_SG_LEN_MASK)); data_addr = ahd_le32toh(sg->addr) + (sglen & AHD_SG_LEN_MASK) - 1; /* * Increment sg so it points to the * "next" sg. */ sg++; sgptr = ahd_sg_virt_to_bus(ahd, scb, sg); } } /* * Toggle the "oddness" of the transfer length * to handle this mid-transfer ignore wide * residue. This ensures that the oddness is * correct for subsequent data transfers. */ ahd_outb(ahd, SCB_TASK_ATTRIBUTE, ahd_inb_scbram(ahd, SCB_TASK_ATTRIBUTE) ^ SCB_XFERLEN_ODD); ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr); ahd_outl(ahd, SCB_RESIDUAL_DATACNT, data_cnt); /* * The FIFO's pointers will be updated if/when the * sequencer re-enters a data phase. */ } } } /* * Reinitialize the data pointers for the active transfer * based on its current residual. */ static void ahd_reinitialize_dataptrs(struct ahd_softc *ahd) { struct scb *scb; ahd_mode_state saved_modes; u_int scb_index; u_int wait; uint32_t sgptr; uint32_t resid; uint64_t dataptr; AHD_ASSERT_MODES(ahd, AHD_MODE_DFF0_MSK|AHD_MODE_DFF1_MSK, AHD_MODE_DFF0_MSK|AHD_MODE_DFF1_MSK); scb_index = ahd_get_scbptr(ahd); scb = ahd_lookup_scb(ahd, scb_index); /* * Release and reacquire the FIFO so we * have a clean slate. */ ahd_outb(ahd, DFFSXFRCTL, CLRCHN); wait = 1000; while (--wait && !(ahd_inb(ahd, MDFFSTAT) & FIFOFREE)) ahd_delay(100); if (wait == 0) { ahd_print_path(ahd, scb); printf("ahd_reinitialize_dataptrs: Forcing FIFO free.\n"); ahd_outb(ahd, DFFSXFRCTL, RSTCHN|CLRSHCNT); } saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); ahd_outb(ahd, DFFSTAT, ahd_inb(ahd, DFFSTAT) | (saved_modes == 0x11 ? CURRFIFO_1 : CURRFIFO_0)); /* * Determine initial values for data_addr and data_cnt * for resuming the data phase. */ sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR); sgptr &= SG_PTR_MASK; resid = (ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT + 2) << 16) | (ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT + 1) << 8) | ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT); if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) { struct ahd_dma64_seg *sg; sg = ahd_sg_bus_to_virt(ahd, scb, sgptr); /* The residual sg_ptr always points to the next sg */ sg--; dataptr = ahd_le64toh(sg->addr) + (ahd_le32toh(sg->len) & AHD_SG_LEN_MASK) - resid; ahd_outl(ahd, HADDR + 4, dataptr >> 32); } else { struct ahd_dma_seg *sg; sg = ahd_sg_bus_to_virt(ahd, scb, sgptr); /* The residual sg_ptr always points to the next sg */ sg--; dataptr = ahd_le32toh(sg->addr) + (ahd_le32toh(sg->len) & AHD_SG_LEN_MASK) - resid; ahd_outb(ahd, HADDR + 4, (ahd_le32toh(sg->len) & ~AHD_SG_LEN_MASK) >> 24); } ahd_outl(ahd, HADDR, dataptr); ahd_outb(ahd, HCNT + 2, resid >> 16); ahd_outb(ahd, HCNT + 1, resid >> 8); ahd_outb(ahd, HCNT, resid); } /* * Handle the effects of issuing a bus device reset message. */ static void ahd_handle_devreset(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, u_int lun, cam_status status, char *message, int verbose_level) { #ifdef AHD_TARGET_MODE struct ahd_tmode_tstate* tstate; #endif int found; found = ahd_abort_scbs(ahd, devinfo->target, devinfo->channel, lun, SCB_LIST_NULL, devinfo->role, status); #ifdef AHD_TARGET_MODE /* * Send an immediate notify ccb to all target mord peripheral * drivers affected by this action. */ tstate = ahd->enabled_targets[devinfo->our_scsiid]; if (tstate != NULL) { u_int cur_lun; u_int max_lun; if (lun != CAM_LUN_WILDCARD) { cur_lun = 0; max_lun = AHD_NUM_LUNS - 1; } else { cur_lun = lun; max_lun = lun; } for (cur_lun <= max_lun; cur_lun++) { struct ahd_tmode_lstate* lstate; lstate = tstate->enabled_luns[cur_lun]; if (lstate == NULL) continue; ahd_queue_lstate_event(ahd, lstate, devinfo->our_scsiid, MSG_BUS_DEV_RESET, /*arg*/0); ahd_send_lstate_events(ahd, lstate); } } #endif /* * Go back to async/narrow transfers and renegotiate. */ ahd_set_width(ahd, devinfo, MSG_EXT_WDTR_BUS_8_BIT, AHD_TRANS_CUR, /*paused*/TRUE); ahd_set_syncrate(ahd, devinfo, /*period*/0, /*offset*/0, /*ppr_options*/0, AHD_TRANS_CUR, /*paused*/TRUE); if (status != CAM_SEL_TIMEOUT) ahd_send_async(ahd, devinfo->channel, devinfo->target, CAM_LUN_WILDCARD, AC_SENT_BDR); if (message != NULL && bootverbose) printf("%s: %s on %c:%d. %d SCBs aborted\n", ahd_name(ahd), message, devinfo->channel, devinfo->target, found); } #ifdef AHD_TARGET_MODE static void ahd_setup_target_msgin(struct ahd_softc *ahd, struct ahd_devinfo *devinfo, struct scb *scb) { /* * To facilitate adding multiple messages together, * each routine should increment the index and len * variables instead of setting them explicitly. */ ahd->msgout_index = 0; ahd->msgout_len = 0; if (scb != NULL && (scb->flags & SCB_AUTO_NEGOTIATE) != 0) ahd_build_transfer_msg(ahd, devinfo); else panic("ahd_intr: AWAITING target message with no message"); ahd->msgout_index = 0; ahd->msg_type = MSG_TYPE_TARGET_MSGIN; } #endif /**************************** Initialization **********************************/ static u_int ahd_sglist_size(struct ahd_softc *ahd) { bus_size_t list_size; list_size = sizeof(struct ahd_dma_seg) * AHD_NSEG; if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) list_size = sizeof(struct ahd_dma64_seg) * AHD_NSEG; return (list_size); } /* * Calculate the optimum S/G List allocation size. S/G elements used * for a given transaction must be physically contiguous. Assume the * OS will allocate full pages to us, so it doesn't make sense to request * less than a page. */ static u_int ahd_sglist_allocsize(struct ahd_softc *ahd) { bus_size_t sg_list_increment; bus_size_t sg_list_size; bus_size_t max_list_size; bus_size_t best_list_size; /* Start out with the minimum required for AHD_NSEG. */ sg_list_increment = ahd_sglist_size(ahd); sg_list_size = sg_list_increment; /* Get us as close as possible to a page in size. */ while ((sg_list_size + sg_list_increment) <= PAGE_SIZE) sg_list_size += sg_list_increment; /* * Try to reduce the amount of wastage by allocating * multiple pages. */ best_list_size = sg_list_size; max_list_size = roundup(sg_list_increment, PAGE_SIZE); if (max_list_size < 4 * PAGE_SIZE) max_list_size = 4 * PAGE_SIZE; if (max_list_size > (AHD_SCB_MAX_ALLOC * sg_list_increment)) max_list_size = (AHD_SCB_MAX_ALLOC * sg_list_increment); while ((sg_list_size + sg_list_increment) <= max_list_size && (sg_list_size % PAGE_SIZE) != 0) { bus_size_t new_mod; bus_size_t best_mod; sg_list_size += sg_list_increment; new_mod = sg_list_size % PAGE_SIZE; best_mod = best_list_size % PAGE_SIZE; if (new_mod > best_mod || new_mod == 0) { best_list_size = sg_list_size; } } return (best_list_size); } /* * Allocate a controller structure for a new device * and perform initial initializion. */ struct ahd_softc * ahd_alloc(void *platform_arg, char *name) { struct ahd_softc *ahd; #ifndef __FreeBSD__ ahd = malloc(sizeof(*ahd), M_DEVBUF, M_NOWAIT); if (!ahd) { printf("aic7xxx: cannot malloc softc!\n"); free(name, M_DEVBUF); return NULL; } #else ahd = device_get_softc((device_t)platform_arg); #endif memset(ahd, 0, sizeof(*ahd)); ahd->seep_config = malloc(sizeof(*ahd->seep_config), M_DEVBUF, M_NOWAIT); if (ahd->seep_config == NULL) { #ifndef __FreeBSD__ free(ahd, M_DEVBUF); #endif free(name, M_DEVBUF); return (NULL); } LIST_INIT(&ahd->pending_scbs); /* We don't know our unit number until the OSM sets it */ ahd->name = name; ahd->unit = -1; ahd->description = NULL; ahd->bus_description = NULL; ahd->channel = 'A'; ahd->chip = AHD_NONE; ahd->features = AHD_FENONE; ahd->bugs = AHD_BUGNONE; ahd->flags = AHD_SPCHK_ENB_A|AHD_RESET_BUS_A|AHD_TERM_ENB_A | AHD_EXTENDED_TRANS_A|AHD_STPWLEVEL_A; ahd_timer_init(&ahd->reset_timer); ahd_timer_init(&ahd->stat_timer); ahd->int_coalescing_timer = AHD_INT_COALESCING_TIMER_DEFAULT; ahd->int_coalescing_maxcmds = AHD_INT_COALESCING_MAXCMDS_DEFAULT; ahd->int_coalescing_mincmds = AHD_INT_COALESCING_MINCMDS_DEFAULT; ahd->int_coalescing_threshold = AHD_INT_COALESCING_THRESHOLD_DEFAULT; ahd->int_coalescing_stop_threshold = AHD_INT_COALESCING_STOP_THRESHOLD_DEFAULT; if (ahd_platform_alloc(ahd, platform_arg) != 0) { ahd_free(ahd); ahd = NULL; } #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MEMORY) != 0) { printf("%s: scb size = 0x%x, hscb size = 0x%x\n", ahd_name(ahd), (u_int)sizeof(struct scb), (u_int)sizeof(struct hardware_scb)); } #endif return (ahd); } int ahd_softc_init(struct ahd_softc *ahd) { ahd->unpause = 0; ahd->pause = PAUSE; return (0); } void ahd_set_unit(struct ahd_softc *ahd, int unit) { ahd->unit = unit; } void ahd_set_name(struct ahd_softc *ahd, char *name) { if (ahd->name != NULL) free(ahd->name, M_DEVBUF); ahd->name = name; } void ahd_free(struct ahd_softc *ahd) { int i; switch (ahd->init_level) { default: case 5: ahd_shutdown(ahd); /* FALLTHROUGH */ case 4: ahd_dmamap_unload(ahd, ahd->shared_data_dmat, ahd->shared_data_map.dmamap); /* FALLTHROUGH */ case 3: ahd_dmamem_free(ahd, ahd->shared_data_dmat, ahd->qoutfifo, ahd->shared_data_map.dmamap); ahd_dmamap_destroy(ahd, ahd->shared_data_dmat, ahd->shared_data_map.dmamap); /* FALLTHROUGH */ case 2: ahd_dma_tag_destroy(ahd, ahd->shared_data_dmat); case 1: #ifndef __linux__ ahd_dma_tag_destroy(ahd, ahd->buffer_dmat); #endif break; case 0: break; } #ifndef __linux__ ahd_dma_tag_destroy(ahd, ahd->parent_dmat); #endif ahd_platform_free(ahd); ahd_fini_scbdata(ahd); for (i = 0; i < AHD_NUM_TARGETS; i++) { struct ahd_tmode_tstate *tstate; tstate = ahd->enabled_targets[i]; if (tstate != NULL) { #ifdef AHD_TARGET_MODE int j; for (j = 0; j < AHD_NUM_LUNS; j++) { struct ahd_tmode_lstate *lstate; lstate = tstate->enabled_luns[j]; if (lstate != NULL) { xpt_free_path(lstate->path); free(lstate, M_DEVBUF); } } #endif free(tstate, M_DEVBUF); } } #ifdef AHD_TARGET_MODE if (ahd->black_hole != NULL) { xpt_free_path(ahd->black_hole->path); free(ahd->black_hole, M_DEVBUF); } #endif if (ahd->name != NULL) free(ahd->name, M_DEVBUF); if (ahd->seep_config != NULL) free(ahd->seep_config, M_DEVBUF); if (ahd->saved_stack != NULL) free(ahd->saved_stack, M_DEVBUF); #ifndef __FreeBSD__ free(ahd, M_DEVBUF); #endif return; } static void ahd_shutdown(void *arg) { struct ahd_softc *ahd; ahd = (struct ahd_softc *)arg; /* * Stop periodic timer callbacks. */ ahd_timer_stop(&ahd->reset_timer); ahd_timer_stop(&ahd->stat_timer); /* This will reset most registers to 0, but not all */ ahd_reset(ahd, /*reinit*/FALSE); } /* * Reset the controller and record some information about it * that is only available just after a reset. If "reinit" is * non-zero, this reset occured after initial configuration * and the caller requests that the chip be fully reinitialized * to a runable state. Chip interrupts are *not* enabled after * a reinitialization. The caller must enable interrupts via * ahd_intr_enable(). */ int ahd_reset(struct ahd_softc *ahd, int reinit) { u_int sxfrctl1; int wait; uint32_t cmd; /* * Preserve the value of the SXFRCTL1 register for all channels. * It contains settings that affect termination and we don't want * to disturb the integrity of the bus. */ ahd_pause(ahd); ahd_update_modes(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); sxfrctl1 = ahd_inb(ahd, SXFRCTL1); cmd = ahd_pci_read_config(ahd->dev_softc, PCIR_COMMAND, /*bytes*/2); if ((ahd->bugs & AHD_PCIX_CHIPRST_BUG) != 0) { uint32_t mod_cmd; /* * A4 Razor #632 * During the assertion of CHIPRST, the chip * does not disable its parity logic prior to * the start of the reset. This may cause a * parity error to be detected and thus a * spurious SERR or PERR assertion. Disble * PERR and SERR responses during the CHIPRST. */ mod_cmd = cmd & ~(PCIM_CMD_PERRESPEN|PCIM_CMD_SERRESPEN); ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND, mod_cmd, /*bytes*/2); } ahd_outb(ahd, HCNTRL, CHIPRST | ahd->pause); /* * Ensure that the reset has finished. We delay 1000us * prior to reading the register to make sure the chip * has sufficiently completed its reset to handle register * accesses. */ wait = 1000; do { ahd_delay(1000); } while (--wait && !(ahd_inb(ahd, HCNTRL) & CHIPRSTACK)); if (wait == 0) { printf("%s: WARNING - Failed chip reset! " "Trying to initialize anyway.\n", ahd_name(ahd)); } ahd_outb(ahd, HCNTRL, ahd->pause); if ((ahd->bugs & AHD_PCIX_CHIPRST_BUG) != 0) { /* * Clear any latched PCI error status and restore * previous SERR and PERR response enables. */ ahd_pci_write_config(ahd->dev_softc, PCIR_STATUS + 1, 0xFF, /*bytes*/1); ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND, cmd, /*bytes*/2); } /* * Mode should be SCSI after a chip reset, but lets * set it just to be safe. We touch the MODE_PTR * register directly so as to bypass the lazy update * code in ahd_set_modes(). */ ahd_known_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); ahd_outb(ahd, MODE_PTR, ahd_build_mode_state(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI)); /* * Restore SXFRCTL1. * * We must always initialize STPWEN to 1 before we * restore the saved values. STPWEN is initialized * to a tri-state condition which can only be cleared * by turning it on. */ ahd_outb(ahd, SXFRCTL1, sxfrctl1|STPWEN); ahd_outb(ahd, SXFRCTL1, sxfrctl1); /* Determine chip configuration */ ahd->features &= ~AHD_WIDE; if ((ahd_inb(ahd, SBLKCTL) & SELWIDE) != 0) ahd->features |= AHD_WIDE; /* * If a recovery action has forced a chip reset, * re-initialize the chip to our liking. */ if (reinit != 0) ahd_chip_init(ahd); return (0); } /* * Determine the number of SCBs available on the controller */ static int ahd_probe_scbs(struct ahd_softc *ahd) { int i; AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK), ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK)); for (i = 0; i < AHD_SCB_MAX; i++) { int j; ahd_set_scbptr(ahd, i); ahd_outw(ahd, SCB_BASE, i); for (j = 2; j < 64; j++) ahd_outb(ahd, SCB_BASE+j, 0); /* Start out life as unallocated (needing an abort) */ ahd_outb(ahd, SCB_CONTROL, MK_MESSAGE); if (ahd_inw_scbram(ahd, SCB_BASE) != i) break; ahd_set_scbptr(ahd, 0); if (ahd_inw_scbram(ahd, SCB_BASE) != 0) break; } return (i); } static void ahd_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error) { dma_addr_t *baddr; baddr = (dma_addr_t *)arg; *baddr = segs->ds_addr; } static void ahd_initialize_hscbs(struct ahd_softc *ahd) { int i; for (i = 0; i < ahd->scb_data.maxhscbs; i++) { ahd_set_scbptr(ahd, i); /* Clear the control byte. */ ahd_outb(ahd, SCB_CONTROL, 0); /* Set the next pointer */ ahd_outw(ahd, SCB_NEXT, SCB_LIST_NULL); } } static int ahd_init_scbdata(struct ahd_softc *ahd) { struct scb_data *scb_data; int i; scb_data = &ahd->scb_data; TAILQ_INIT(&scb_data->free_scbs); for (i = 0; i < AHD_NUM_TARGETS * AHD_NUM_LUNS_NONPKT; i++) LIST_INIT(&scb_data->free_scb_lists[i]); LIST_INIT(&scb_data->any_dev_free_scb_list); SLIST_INIT(&scb_data->hscb_maps); SLIST_INIT(&scb_data->sg_maps); SLIST_INIT(&scb_data->sense_maps); /* Determine the number of hardware SCBs and initialize them */ scb_data->maxhscbs = ahd_probe_scbs(ahd); if (scb_data->maxhscbs == 0) { printf("%s: No SCB space found\n", ahd_name(ahd)); return (ENXIO); } ahd_initialize_hscbs(ahd); /* * Create our DMA tags. These tags define the kinds of device * accessible memory allocations and memory mappings we will * need to perform during normal operation. * * Unless we need to further restrict the allocation, we rely * on the restrictions of the parent dmat, hence the common * use of MAXADDR and MAXSIZE. */ /* DMA tag for our hardware scb structures */ if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1, /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1, /*lowaddr*/BUS_SPACE_MAXADDR_32BIT, /*highaddr*/BUS_SPACE_MAXADDR, /*filter*/NULL, /*filterarg*/NULL, PAGE_SIZE, /*nsegments*/1, /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT, /*flags*/0, &scb_data->hscb_dmat) != 0) { goto error_exit; } scb_data->init_level++; /* DMA tag for our S/G structures. */ if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/8, /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1, /*lowaddr*/BUS_SPACE_MAXADDR_32BIT, /*highaddr*/BUS_SPACE_MAXADDR, /*filter*/NULL, /*filterarg*/NULL, ahd_sglist_allocsize(ahd), /*nsegments*/1, /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT, /*flags*/0, &scb_data->sg_dmat) != 0) { goto error_exit; } #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MEMORY) != 0) printf("%s: ahd_sglist_allocsize = 0x%x\n", ahd_name(ahd), ahd_sglist_allocsize(ahd)); #endif scb_data->init_level++; /* DMA tag for our sense buffers. We allocate in page sized chunks */ if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1, /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1, /*lowaddr*/BUS_SPACE_MAXADDR_32BIT, /*highaddr*/BUS_SPACE_MAXADDR, /*filter*/NULL, /*filterarg*/NULL, PAGE_SIZE, /*nsegments*/1, /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT, /*flags*/0, &scb_data->sense_dmat) != 0) { goto error_exit; } scb_data->init_level++; /* Perform initial CCB allocation */ ahd_alloc_scbs(ahd); if (scb_data->numscbs == 0) { printf("%s: ahd_init_scbdata - " "Unable to allocate initial scbs\n", ahd_name(ahd)); goto error_exit; } /* * Note that we were successfull */ return (0); error_exit: return (ENOMEM); } static struct scb * ahd_find_scb_by_tag(struct ahd_softc *ahd, u_int tag) { struct scb *scb; /* * Look on the pending list. */ LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) { if (SCB_GET_TAG(scb) == tag) return (scb); } /* * Then on all of the collision free lists. */ TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) { struct scb *list_scb; list_scb = scb; do { if (SCB_GET_TAG(list_scb) == tag) return (list_scb); list_scb = LIST_NEXT(list_scb, collision_links); } while (list_scb); } /* * And finally on the generic free list. */ LIST_FOREACH(scb, &ahd->scb_data.any_dev_free_scb_list, links.le) { if (SCB_GET_TAG(scb) == tag) return (scb); } return (NULL); } static void ahd_fini_scbdata(struct ahd_softc *ahd) { struct scb_data *scb_data; scb_data = &ahd->scb_data; if (scb_data == NULL) return; switch (scb_data->init_level) { default: case 7: { struct map_node *sns_map; while ((sns_map = SLIST_FIRST(&scb_data->sense_maps)) != NULL) { SLIST_REMOVE_HEAD(&scb_data->sense_maps, links); ahd_dmamap_unload(ahd, scb_data->sense_dmat, sns_map->dmamap); ahd_dmamem_free(ahd, scb_data->sense_dmat, sns_map->vaddr, sns_map->dmamap); free(sns_map, M_DEVBUF); } ahd_dma_tag_destroy(ahd, scb_data->sense_dmat); /* FALLTHROUGH */ } case 6: { struct map_node *sg_map; while ((sg_map = SLIST_FIRST(&scb_data->sg_maps)) != NULL) { SLIST_REMOVE_HEAD(&scb_data->sg_maps, links); ahd_dmamap_unload(ahd, scb_data->sg_dmat, sg_map->dmamap); ahd_dmamem_free(ahd, scb_data->sg_dmat, sg_map->vaddr, sg_map->dmamap); free(sg_map, M_DEVBUF); } ahd_dma_tag_destroy(ahd, scb_data->sg_dmat); /* FALLTHROUGH */ } case 5: { struct map_node *hscb_map; while ((hscb_map = SLIST_FIRST(&scb_data->hscb_maps)) != NULL) { SLIST_REMOVE_HEAD(&scb_data->hscb_maps, links); ahd_dmamap_unload(ahd, scb_data->hscb_dmat, hscb_map->dmamap); ahd_dmamem_free(ahd, scb_data->hscb_dmat, hscb_map->vaddr, hscb_map->dmamap); free(hscb_map, M_DEVBUF); } ahd_dma_tag_destroy(ahd, scb_data->hscb_dmat); /* FALLTHROUGH */ } case 4: case 3: case 2: case 1: case 0: break; } } /* * DSP filter Bypass must be enabled until the first selection * after a change in bus mode (Razor #491 and #493). */ static void ahd_setup_iocell_workaround(struct ahd_softc *ahd) { ahd_mode_state saved_modes; saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG); ahd_outb(ahd, DSPDATACTL, ahd_inb(ahd, DSPDATACTL) | BYPASSENAB | RCVROFFSTDIS | XMITOFFSTDIS); ahd_outb(ahd, SIMODE0, ahd_inb(ahd, SIMODE0) | (ENSELDO|ENSELDI)); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MISC) != 0) printf("%s: Setting up iocell workaround\n", ahd_name(ahd)); #endif ahd_restore_modes(ahd, saved_modes); ahd->flags &= ~AHD_HAD_FIRST_SEL; } static void ahd_iocell_first_selection(struct ahd_softc *ahd) { ahd_mode_state saved_modes; u_int sblkctl; if ((ahd->flags & AHD_HAD_FIRST_SEL) != 0) return; saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); sblkctl = ahd_inb(ahd, SBLKCTL); ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MISC) != 0) printf("%s: iocell first selection\n", ahd_name(ahd)); #endif if ((sblkctl & ENAB40) != 0) { ahd_outb(ahd, DSPDATACTL, ahd_inb(ahd, DSPDATACTL) & ~BYPASSENAB); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MISC) != 0) printf("%s: BYPASS now disabled\n", ahd_name(ahd)); #endif } ahd_outb(ahd, SIMODE0, ahd_inb(ahd, SIMODE0) & ~(ENSELDO|ENSELDI)); ahd_outb(ahd, CLRINT, CLRSCSIINT); ahd_restore_modes(ahd, saved_modes); ahd->flags |= AHD_HAD_FIRST_SEL; } /*************************** SCB Management ***********************************/ static void ahd_add_col_list(struct ahd_softc *ahd, struct scb *scb, u_int col_idx) { struct scb_list *free_list; struct scb_tailq *free_tailq; struct scb *first_scb; scb->flags |= SCB_ON_COL_LIST; AHD_SET_SCB_COL_IDX(scb, col_idx); free_list = &ahd->scb_data.free_scb_lists[col_idx]; free_tailq = &ahd->scb_data.free_scbs; first_scb = LIST_FIRST(free_list); if (first_scb != NULL) { LIST_INSERT_AFTER(first_scb, scb, collision_links); } else { LIST_INSERT_HEAD(free_list, scb, collision_links); TAILQ_INSERT_TAIL(free_tailq, scb, links.tqe); } } static void ahd_rem_col_list(struct ahd_softc *ahd, struct scb *scb) { struct scb_list *free_list; struct scb_tailq *free_tailq; struct scb *first_scb; u_int col_idx; scb->flags &= ~SCB_ON_COL_LIST; col_idx = AHD_GET_SCB_COL_IDX(ahd, scb); free_list = &ahd->scb_data.free_scb_lists[col_idx]; free_tailq = &ahd->scb_data.free_scbs; first_scb = LIST_FIRST(free_list); if (first_scb == scb) { struct scb *next_scb; /* * Maintain order in the collision free * lists for fairness if this device has * other colliding tags active. */ next_scb = LIST_NEXT(scb, collision_links); if (next_scb != NULL) { TAILQ_INSERT_AFTER(free_tailq, scb, next_scb, links.tqe); } TAILQ_REMOVE(free_tailq, scb, links.tqe); } LIST_REMOVE(scb, collision_links); } /* * Get a free scb. If there are none, see if we can allocate a new SCB. */ struct scb * ahd_get_scb(struct ahd_softc *ahd, u_int col_idx) { struct scb *scb; int tries; tries = 0; look_again: TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) { if (AHD_GET_SCB_COL_IDX(ahd, scb) != col_idx) { ahd_rem_col_list(ahd, scb); goto found; } } if ((scb = LIST_FIRST(&ahd->scb_data.any_dev_free_scb_list)) == NULL) { if (tries++ != 0) return (NULL); ahd_alloc_scbs(ahd); goto look_again; } LIST_REMOVE(scb, links.le); if (col_idx != AHD_NEVER_COL_IDX && (scb->col_scb != NULL) && (scb->col_scb->flags & SCB_ACTIVE) == 0) { LIST_REMOVE(scb->col_scb, links.le); ahd_add_col_list(ahd, scb->col_scb, col_idx); } found: scb->flags |= SCB_ACTIVE; return (scb); } /* * Return an SCB resource to the free list. */ void ahd_free_scb(struct ahd_softc *ahd, struct scb *scb) { /* Clean up for the next user */ scb->flags = SCB_FLAG_NONE; scb->hscb->control = 0; ahd->scb_data.scbindex[SCB_GET_TAG(scb)] = NULL; if (scb->col_scb == NULL) { /* * No collision possible. Just free normally. */ LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list, scb, links.le); } else if ((scb->col_scb->flags & SCB_ON_COL_LIST) != 0) { /* * The SCB we might have collided with is on * a free collision list. Put both SCBs on * the generic list. */ ahd_rem_col_list(ahd, scb->col_scb); LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list, scb, links.le); LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list, scb->col_scb, links.le); } else if ((scb->col_scb->flags & (SCB_PACKETIZED|SCB_ACTIVE)) == SCB_ACTIVE && (scb->col_scb->hscb->control & TAG_ENB) != 0) { /* * The SCB we might collide with on the next allocation * is still active in a non-packetized, tagged, context. * Put us on the SCB collision list. */ ahd_add_col_list(ahd, scb, AHD_GET_SCB_COL_IDX(ahd, scb->col_scb)); } else { /* * The SCB we might collide with on the next allocation * is either active in a packetized context, or free. * Since we can't collide, put this SCB on the generic * free list. */ LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list, scb, links.le); } ahd_platform_scb_free(ahd, scb); } static void ahd_alloc_scbs(struct ahd_softc *ahd) { struct scb_data *scb_data; struct scb *next_scb; struct hardware_scb *hscb; struct map_node *hscb_map; struct map_node *sg_map; struct map_node *sense_map; uint8_t *segs; uint8_t *sense_data; dma_addr_t hscb_busaddr; dma_addr_t sg_busaddr; dma_addr_t sense_busaddr; int newcount; int i; scb_data = &ahd->scb_data; if (scb_data->numscbs >= AHD_SCB_MAX_ALLOC) /* Can't allocate any more */ return; if (scb_data->scbs_left != 0) { int offset; offset = (PAGE_SIZE / sizeof(*hscb)) - scb_data->scbs_left; hscb_map = SLIST_FIRST(&scb_data->hscb_maps); hscb = &((struct hardware_scb *)hscb_map->vaddr)[offset]; hscb_busaddr = hscb_map->physaddr + (offset * sizeof(*hscb)); } else { hscb_map = malloc(sizeof(*hscb_map), M_DEVBUF, M_NOWAIT); if (hscb_map == NULL) return; /* Allocate the next batch of hardware SCBs */ if (ahd_dmamem_alloc(ahd, scb_data->hscb_dmat, (void **)&hscb_map->vaddr, BUS_DMA_NOWAIT, &hscb_map->dmamap) != 0) { free(hscb_map, M_DEVBUF); return; } SLIST_INSERT_HEAD(&scb_data->hscb_maps, hscb_map, links); ahd_dmamap_load(ahd, scb_data->hscb_dmat, hscb_map->dmamap, hscb_map->vaddr, PAGE_SIZE, ahd_dmamap_cb, &hscb_map->physaddr, /*flags*/0); hscb = (struct hardware_scb *)hscb_map->vaddr; hscb_busaddr = hscb_map->physaddr; scb_data->scbs_left = PAGE_SIZE / sizeof(*hscb); } if (scb_data->sgs_left != 0) { int offset; offset = ((ahd_sglist_allocsize(ahd) / ahd_sglist_size(ahd)) - scb_data->sgs_left) * ahd_sglist_size(ahd); sg_map = SLIST_FIRST(&scb_data->sg_maps); segs = sg_map->vaddr + offset; sg_busaddr = sg_map->physaddr + offset; } else { sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT); if (sg_map == NULL) return; /* Allocate the next batch of S/G lists */ if (ahd_dmamem_alloc(ahd, scb_data->sg_dmat, (void **)&sg_map->vaddr, BUS_DMA_NOWAIT, &sg_map->dmamap) != 0) { free(sg_map, M_DEVBUF); return; } SLIST_INSERT_HEAD(&scb_data->sg_maps, sg_map, links); ahd_dmamap_load(ahd, scb_data->sg_dmat, sg_map->dmamap, sg_map->vaddr, ahd_sglist_allocsize(ahd), ahd_dmamap_cb, &sg_map->physaddr, /*flags*/0); segs = sg_map->vaddr; sg_busaddr = sg_map->physaddr; scb_data->sgs_left = ahd_sglist_allocsize(ahd) / ahd_sglist_size(ahd); #ifdef AHD_DEBUG if (ahd_debug & AHD_SHOW_MEMORY) printf("Mapped SG data\n"); #endif } if (scb_data->sense_left != 0) { int offset; offset = PAGE_SIZE - (AHD_SENSE_BUFSIZE * scb_data->sense_left); sense_map = SLIST_FIRST(&scb_data->sense_maps); sense_data = sense_map->vaddr + offset; sense_busaddr = sense_map->physaddr + offset; } else { sense_map = malloc(sizeof(*sense_map), M_DEVBUF, M_NOWAIT); if (sense_map == NULL) return; /* Allocate the next batch of sense buffers */ if (ahd_dmamem_alloc(ahd, scb_data->sense_dmat, (void **)&sense_map->vaddr, BUS_DMA_NOWAIT, &sense_map->dmamap) != 0) { free(sense_map, M_DEVBUF); return; } SLIST_INSERT_HEAD(&scb_data->sense_maps, sense_map, links); ahd_dmamap_load(ahd, scb_data->sense_dmat, sense_map->dmamap, sense_map->vaddr, PAGE_SIZE, ahd_dmamap_cb, &sense_map->physaddr, /*flags*/0); sense_data = sense_map->vaddr; sense_busaddr = sense_map->physaddr; scb_data->sense_left = PAGE_SIZE / AHD_SENSE_BUFSIZE; #ifdef AHD_DEBUG if (ahd_debug & AHD_SHOW_MEMORY) printf("Mapped sense data\n"); #endif } newcount = min(scb_data->sense_left, scb_data->scbs_left); newcount = min(newcount, scb_data->sgs_left); newcount = min(newcount, (AHD_SCB_MAX_ALLOC - scb_data->numscbs)); for (i = 0; i < newcount; i++) { struct scb_platform_data *pdata; u_int col_tag; #ifndef __linux__ int error; #endif next_scb = (struct scb *)malloc(sizeof(*next_scb), M_DEVBUF, M_NOWAIT); if (next_scb == NULL) break; pdata = (struct scb_platform_data *)malloc(sizeof(*pdata), M_DEVBUF, M_NOWAIT); if (pdata == NULL) { free(next_scb, M_DEVBUF); break; } next_scb->platform_data = pdata; next_scb->hscb_map = hscb_map; next_scb->sg_map = sg_map; next_scb->sense_map = sense_map; next_scb->sg_list = segs; next_scb->sense_data = sense_data; next_scb->sense_busaddr = sense_busaddr; memset(hscb, 0, sizeof(*hscb)); next_scb->hscb = hscb; hscb->hscb_busaddr = ahd_htole32(hscb_busaddr); /* * The sequencer always starts with the second entry. * The first entry is embedded in the scb. */ next_scb->sg_list_busaddr = sg_busaddr; if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) next_scb->sg_list_busaddr += sizeof(struct ahd_dma64_seg); else next_scb->sg_list_busaddr += sizeof(struct ahd_dma_seg); next_scb->ahd_softc = ahd; next_scb->flags = SCB_FLAG_NONE; #ifndef __linux__ error = ahd_dmamap_create(ahd, ahd->buffer_dmat, /*flags*/0, &next_scb->dmamap); if (error != 0) { free(next_scb, M_DEVBUF); free(pdata, M_DEVBUF); break; } #endif next_scb->hscb->tag = ahd_htole16(scb_data->numscbs); col_tag = scb_data->numscbs ^ 0x100; next_scb->col_scb = ahd_find_scb_by_tag(ahd, col_tag); if (next_scb->col_scb != NULL) next_scb->col_scb->col_scb = next_scb; ahd_free_scb(ahd, next_scb); hscb++; hscb_busaddr += sizeof(*hscb); segs += ahd_sglist_size(ahd); sg_busaddr += ahd_sglist_size(ahd); sense_data += AHD_SENSE_BUFSIZE; sense_busaddr += AHD_SENSE_BUFSIZE; scb_data->numscbs++; scb_data->sense_left--; scb_data->scbs_left--; scb_data->sgs_left--; } } void ahd_controller_info(struct ahd_softc *ahd, char *buf) { const char *speed; const char *type; int len; len = sprintf(buf, "%s: ", ahd_chip_names[ahd->chip & AHD_CHIPID_MASK]); buf += len; speed = "Ultra320 "; if ((ahd->features & AHD_WIDE) != 0) { type = "Wide "; } else { type = "Single "; } len = sprintf(buf, "%s%sChannel %c, SCSI Id=%d, ", speed, type, ahd->channel, ahd->our_id); buf += len; sprintf(buf, "%s, %d SCBs", ahd->bus_description, ahd->scb_data.maxhscbs); } static const char *channel_strings[] = { "Primary Low", "Primary High", "Secondary Low", "Secondary High" }; static const char *termstat_strings[] = { "Terminated Correctly", "Over Terminated", "Under Terminated", "Not Configured" }; /* * Start the board, ready for normal operation */ int ahd_init(struct ahd_softc *ahd) { uint8_t *next_vaddr; dma_addr_t next_baddr; size_t driver_data_size; int i; int error; u_int warn_user; uint8_t current_sensing; uint8_t fstat; AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); ahd->stack_size = ahd_probe_stack_size(ahd); ahd->saved_stack = malloc(ahd->stack_size * sizeof(uint16_t), M_DEVBUF, M_NOWAIT); if (ahd->saved_stack == NULL) return (ENOMEM); /* * Verify that the compiler hasn't over-agressively * padded important structures. */ if (sizeof(struct hardware_scb) != 64) panic("Hardware SCB size is incorrect"); #ifdef AHD_DEBUG if ((ahd_debug & AHD_DEBUG_SEQUENCER) != 0) ahd->flags |= AHD_SEQUENCER_DEBUG; #endif /* * Default to allowing initiator operations. */ ahd->flags |= AHD_INITIATORROLE; /* * Only allow target mode features if this unit has them enabled. */ if ((AHD_TMODE_ENABLE & (0x1 << ahd->unit)) == 0) ahd->features &= ~AHD_TARGETMODE; #ifndef __linux__ /* DMA tag for mapping buffers into device visible space. */ if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1, /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1, /*lowaddr*/ahd->flags & AHD_39BIT_ADDRESSING ? (dma_addr_t)0x7FFFFFFFFFULL : BUS_SPACE_MAXADDR_32BIT, /*highaddr*/BUS_SPACE_MAXADDR, /*filter*/NULL, /*filterarg*/NULL, /*maxsize*/(AHD_NSEG - 1) * PAGE_SIZE, /*nsegments*/AHD_NSEG, /*maxsegsz*/AHD_MAXTRANSFER_SIZE, /*flags*/BUS_DMA_ALLOCNOW, &ahd->buffer_dmat) != 0) { return (ENOMEM); } #endif ahd->init_level++; /* * DMA tag for our command fifos and other data in system memory * the card's sequencer must be able to access. For initiator * roles, we need to allocate space for the qoutfifo. When providing * for the target mode role, we must additionally provide space for * the incoming target command fifo. */ driver_data_size = AHD_SCB_MAX * sizeof(*ahd->qoutfifo) + sizeof(struct hardware_scb); if ((ahd->features & AHD_TARGETMODE) != 0) driver_data_size += AHD_TMODE_CMDS * sizeof(struct target_cmd); if ((ahd->bugs & AHD_PKT_BITBUCKET_BUG) != 0) driver_data_size += PKT_OVERRUN_BUFSIZE; if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1, /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1, /*lowaddr*/BUS_SPACE_MAXADDR_32BIT, /*highaddr*/BUS_SPACE_MAXADDR, /*filter*/NULL, /*filterarg*/NULL, driver_data_size, /*nsegments*/1, /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT, /*flags*/0, &ahd->shared_data_dmat) != 0) { return (ENOMEM); } ahd->init_level++; /* Allocation of driver data */ if (ahd_dmamem_alloc(ahd, ahd->shared_data_dmat, (void **)&ahd->shared_data_map.vaddr, BUS_DMA_NOWAIT, &ahd->shared_data_map.dmamap) != 0) { return (ENOMEM); } ahd->init_level++; /* And permanently map it in */ ahd_dmamap_load(ahd, ahd->shared_data_dmat, ahd->shared_data_map.dmamap, ahd->shared_data_map.vaddr, driver_data_size, ahd_dmamap_cb, &ahd->shared_data_map.physaddr, /*flags*/0); ahd->qoutfifo = (struct ahd_completion *)ahd->shared_data_map.vaddr; next_vaddr = (uint8_t *)&ahd->qoutfifo[AHD_QOUT_SIZE]; next_baddr = ahd->shared_data_map.physaddr + AHD_QOUT_SIZE*sizeof(struct ahd_completion); if ((ahd->features & AHD_TARGETMODE) != 0) { ahd->targetcmds = (struct target_cmd *)next_vaddr; next_vaddr += AHD_TMODE_CMDS * sizeof(struct target_cmd); next_baddr += AHD_TMODE_CMDS * sizeof(struct target_cmd); } if ((ahd->bugs & AHD_PKT_BITBUCKET_BUG) != 0) { ahd->overrun_buf = next_vaddr; next_vaddr += PKT_OVERRUN_BUFSIZE; next_baddr += PKT_OVERRUN_BUFSIZE; } /* * We need one SCB to serve as the "next SCB". Since the * tag identifier in this SCB will never be used, there is * no point in using a valid HSCB tag from an SCB pulled from * the standard free pool. So, we allocate this "sentinel" * specially from the DMA safe memory chunk used for the QOUTFIFO. */ ahd->next_queued_hscb = (struct hardware_scb *)next_vaddr; ahd->next_queued_hscb_map = &ahd->shared_data_map; ahd->next_queued_hscb->hscb_busaddr = ahd_htole32(next_baddr); ahd->init_level++; /* Allocate SCB data now that buffer_dmat is initialized */ if (ahd_init_scbdata(ahd) != 0) return (ENOMEM); if ((ahd->flags & AHD_INITIATORROLE) == 0) ahd->flags &= ~AHD_RESET_BUS_A; /* * Before committing these settings to the chip, give * the OSM one last chance to modify our configuration. */ ahd_platform_init(ahd); /* Bring up the chip. */ ahd_chip_init(ahd); AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); if ((ahd->flags & AHD_CURRENT_SENSING) == 0) goto init_done; /* * Verify termination based on current draw and * warn user if the bus is over/under terminated. */ error = ahd_write_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, CURSENSE_ENB); if (error != 0) { printf("%s: current sensing timeout 1\n", ahd_name(ahd)); goto init_done; } for (i = 20, fstat = FLX_FSTAT_BUSY; (fstat & FLX_FSTAT_BUSY) != 0 && i; i--) { error = ahd_read_flexport(ahd, FLXADDR_FLEXSTAT, &fstat); if (error != 0) { printf("%s: current sensing timeout 2\n", ahd_name(ahd)); goto init_done; } } if (i == 0) { printf("%s: Timedout during current-sensing test\n", ahd_name(ahd)); goto init_done; } /* Latch Current Sensing status. */ error = ahd_read_flexport(ahd, FLXADDR_CURRENT_STAT, &current_sensing); if (error != 0) { printf("%s: current sensing timeout 3\n", ahd_name(ahd)); goto init_done; } /* Diable current sensing. */ ahd_write_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, 0); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_TERMCTL) != 0) { printf("%s: current_sensing == 0x%x\n", ahd_name(ahd), current_sensing); } #endif warn_user = 0; for (i = 0; i < 4; i++, current_sensing >>= FLX_CSTAT_SHIFT) { u_int term_stat; term_stat = (current_sensing & FLX_CSTAT_MASK); switch (term_stat) { case FLX_CSTAT_OVER: case FLX_CSTAT_UNDER: warn_user++; case FLX_CSTAT_INVALID: case FLX_CSTAT_OKAY: if (warn_user == 0 && bootverbose == 0) break; printf("%s: %s Channel %s\n", ahd_name(ahd), channel_strings[i], termstat_strings[term_stat]); break; } } if (warn_user) { printf("%s: WARNING. Termination is not configured correctly.\n" "%s: WARNING. SCSI bus operations may FAIL.\n", ahd_name(ahd), ahd_name(ahd)); } init_done: ahd_restart(ahd); ahd_timer_reset(&ahd->stat_timer, AHD_STAT_UPDATE_US, ahd_stat_timer, ahd); return (0); } /* * (Re)initialize chip state after a chip reset. */ static void ahd_chip_init(struct ahd_softc *ahd) { uint32_t busaddr; u_int sxfrctl1; u_int scsiseq_template; u_int wait; u_int i; u_int target; ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); /* * Take the LED out of diagnostic mode */ ahd_outb(ahd, SBLKCTL, ahd_inb(ahd, SBLKCTL) & ~(DIAGLEDEN|DIAGLEDON)); /* * Return HS_MAILBOX to its default value. */ ahd->hs_mailbox = 0; ahd_outb(ahd, HS_MAILBOX, 0); /* Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1. */ ahd_outb(ahd, IOWNID, ahd->our_id); ahd_outb(ahd, TOWNID, ahd->our_id); sxfrctl1 = (ahd->flags & AHD_TERM_ENB_A) != 0 ? STPWEN : 0; sxfrctl1 |= (ahd->flags & AHD_SPCHK_ENB_A) != 0 ? ENSPCHK : 0; if ((ahd->bugs & AHD_LONG_SETIMO_BUG) && (ahd->seltime != STIMESEL_MIN)) { /* * The selection timer duration is twice as long * as it should be. Halve it by adding "1" to * the user specified setting. */ sxfrctl1 |= ahd->seltime + STIMESEL_BUG_ADJ; } else { sxfrctl1 |= ahd->seltime; } ahd_outb(ahd, SXFRCTL0, DFON); ahd_outb(ahd, SXFRCTL1, sxfrctl1|ahd->seltime|ENSTIMER|ACTNEGEN); ahd_outb(ahd, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR); /* * Now that termination is set, wait for up * to 500ms for our transceivers to settle. If * the adapter does not have a cable attached, * the transceivers may never settle, so don't * complain if we fail here. */ for (wait = 10000; (ahd_inb(ahd, SBLKCTL) & (ENAB40|ENAB20)) == 0 && wait; wait--) ahd_delay(100); /* Clear any false bus resets due to the transceivers settling */ ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI); ahd_outb(ahd, CLRINT, CLRSCSIINT); /* Initialize mode specific S/G state. */ for (i = 0; i < 2; i++) { ahd_set_modes(ahd, AHD_MODE_DFF0 + i, AHD_MODE_DFF0 + i); ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR); ahd_outb(ahd, SG_STATE, 0); ahd_outb(ahd, CLRSEQINTSRC, 0xFF); ahd_outb(ahd, SEQIMODE, ENSAVEPTRS|ENCFG4DATA|ENCFG4ISTAT |ENCFG4TSTAT|ENCFG4ICMD|ENCFG4TCMD); } ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG); ahd_outb(ahd, DSCOMMAND0, ahd_inb(ahd, DSCOMMAND0)|MPARCKEN|CACHETHEN); ahd_outb(ahd, DFF_THRSH, RD_DFTHRSH_75|WR_DFTHRSH_75); ahd_outb(ahd, SIMODE0, ENIOERR|ENOVERRUN); ahd_outb(ahd, SIMODE3, ENNTRAMPERR|ENOSRAMPERR); if ((ahd->bugs & AHD_BUSFREEREV_BUG) != 0) { ahd_outb(ahd, OPTIONMODE, AUTOACKEN|AUTO_MSGOUT_DE); } else { ahd_outb(ahd, OPTIONMODE, AUTOACKEN|BUSFREEREV|AUTO_MSGOUT_DE); } ahd_outb(ahd, SCSCHKN, CURRFIFODEF|WIDERESEN|SHVALIDSTDIS); if ((ahd->chip & AHD_BUS_MASK) == AHD_PCIX) /* * Do not issue a target abort when a split completion * error occurs. Let our PCIX interrupt handler deal * with it instead. H2A4 Razor #625 */ ahd_outb(ahd, PCIXCTL, ahd_inb(ahd, PCIXCTL) | SPLTSTADIS); if ((ahd->bugs & AHD_LQOOVERRUN_BUG) != 0) ahd_outb(ahd, LQOSCSCTL, LQONOCHKOVER); /* * Tweak IOCELL settings. */ if ((ahd->flags & AHD_HP_BOARD) != 0) { for (i = 0; i < NUMDSPS; i++) { ahd_outb(ahd, DSPSELECT, i); ahd_outb(ahd, WRTBIASCTL, WRTBIASCTL_HP_DEFAULT); } #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MISC) != 0) printf("%s: WRTBIASCTL now 0x%x\n", ahd_name(ahd), WRTBIASCTL_HP_DEFAULT); #endif } ahd_setup_iocell_workaround(ahd); /* * Enable LQI Manager interrupts. */ ahd_outb(ahd, LQIMODE1, ENLQIPHASE_LQ|ENLQIPHASE_NLQ|ENLIQABORT | ENLQICRCI_LQ|ENLQICRCI_NLQ|ENLQIBADLQI | ENLQIOVERI_LQ|ENLQIOVERI_NLQ); ahd_outb(ahd, LQOMODE0, ENLQOATNLQ|ENLQOATNPKT|ENLQOTCRC); /* * We choose to have the sequencer catch LQOPHCHGINPKT errors * manually for the command phase at the start of a packetized * selection case. ENLQOBUSFREE should be made redundant by * the BUSFREE interrupt, but it seems that some LQOBUSFREE * events fail to assert the BUSFREE interrupt so we must * also enable LQOBUSFREE interrupts. */ ahd_outb(ahd, LQOMODE1, ENLQOBUSFREE); /* * Setup sequencer interrupt handlers. */ ahd_outw(ahd, INTVEC1_ADDR, ahd_resolve_seqaddr(ahd, LABEL_seq_isr)); ahd_outw(ahd, INTVEC2_ADDR, ahd_resolve_seqaddr(ahd, LABEL_timer_isr)); /* * Setup SCB Offset registers. */ if ((ahd->bugs & AHD_PKT_LUN_BUG) != 0) { ahd_outb(ahd, LUNPTR, offsetof(struct hardware_scb, pkt_long_lun)); } else { ahd_outb(ahd, LUNPTR, offsetof(struct hardware_scb, lun)); } ahd_outb(ahd, CMDLENPTR, offsetof(struct hardware_scb, cdb_len)); ahd_outb(ahd, ATTRPTR, offsetof(struct hardware_scb, task_attribute)); ahd_outb(ahd, FLAGPTR, offsetof(struct hardware_scb, task_management)); ahd_outb(ahd, CMDPTR, offsetof(struct hardware_scb, shared_data.idata.cdb)); ahd_outb(ahd, QNEXTPTR, offsetof(struct hardware_scb, next_hscb_busaddr)); ahd_outb(ahd, ABRTBITPTR, MK_MESSAGE_BIT_OFFSET); ahd_outb(ahd, ABRTBYTEPTR, offsetof(struct hardware_scb, control)); if ((ahd->bugs & AHD_PKT_LUN_BUG) != 0) { ahd_outb(ahd, LUNLEN, sizeof(ahd->next_queued_hscb->pkt_long_lun) - 1); } else { ahd_outb(ahd, LUNLEN, LUNLEN_SINGLE_LEVEL_LUN); } ahd_outb(ahd, CDBLIMIT, SCB_CDB_LEN_PTR - 1); ahd_outb(ahd, MAXCMD, 0xFF); ahd_outb(ahd, SCBAUTOPTR, AUSCBPTR_EN | offsetof(struct hardware_scb, tag)); /* We haven't been enabled for target mode yet. */ ahd_outb(ahd, MULTARGID, 0); ahd_outb(ahd, MULTARGID + 1, 0); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); /* Initialize the negotiation table. */ if ((ahd->features & AHD_NEW_IOCELL_OPTS) == 0) { /* * Clear the spare bytes in the neg table to avoid * spurious parity errors. */ for (target = 0; target < AHD_NUM_TARGETS; target++) { ahd_outb(ahd, NEGOADDR, target); ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_PER_DEV0); for (i = 0; i < AHD_NUM_PER_DEV_ANNEXCOLS; i++) ahd_outb(ahd, ANNEXDAT, 0); } } for (target = 0; target < AHD_NUM_TARGETS; target++) { struct ahd_devinfo devinfo; struct ahd_initiator_tinfo *tinfo; struct ahd_tmode_tstate *tstate; tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id, target, &tstate); ahd_compile_devinfo(&devinfo, ahd->our_id, target, CAM_LUN_WILDCARD, 'A', ROLE_INITIATOR); ahd_update_neg_table(ahd, &devinfo, &tinfo->curr); } ahd_outb(ahd, CLRSINT3, NTRAMPERR|OSRAMPERR); ahd_outb(ahd, CLRINT, CLRSCSIINT); #ifdef NEEDS_MORE_TESTING /* * Always enable abort on incoming L_Qs if this feature is * supported. We use this to catch invalid SCB references. */ if ((ahd->bugs & AHD_ABORT_LQI_BUG) == 0) ahd_outb(ahd, LQCTL1, ABORTPENDING); else #endif ahd_outb(ahd, LQCTL1, 0); /* All of our queues are empty */ ahd->qoutfifonext = 0; ahd->qoutfifonext_valid_tag = QOUTFIFO_ENTRY_VALID; ahd_outb(ahd, QOUTFIFO_ENTRY_VALID_TAG, QOUTFIFO_ENTRY_VALID); for (i = 0; i < AHD_QOUT_SIZE; i++) ahd->qoutfifo[i].valid_tag = 0; ahd_sync_qoutfifo(ahd, BUS_DMASYNC_PREREAD); ahd->qinfifonext = 0; for (i = 0; i < AHD_QIN_SIZE; i++) ahd->qinfifo[i] = SCB_LIST_NULL; if ((ahd->features & AHD_TARGETMODE) != 0) { /* All target command blocks start out invalid. */ for (i = 0; i < AHD_TMODE_CMDS; i++) ahd->targetcmds[i].cmd_valid = 0; ahd_sync_tqinfifo(ahd, BUS_DMASYNC_PREREAD); ahd->tqinfifonext = 1; ahd_outb(ahd, KERNEL_TQINPOS, ahd->tqinfifonext - 1); ahd_outb(ahd, TQINPOS, ahd->tqinfifonext); } /* Initialize Scratch Ram. */ ahd_outb(ahd, SEQ_FLAGS, 0); ahd_outb(ahd, SEQ_FLAGS2, 0); /* We don't have any waiting selections */ ahd_outw(ahd, WAITING_TID_HEAD, SCB_LIST_NULL); ahd_outw(ahd, WAITING_TID_TAIL, SCB_LIST_NULL); ahd_outw(ahd, MK_MESSAGE_SCB, SCB_LIST_NULL); ahd_outw(ahd, MK_MESSAGE_SCSIID, 0xFF); for (i = 0; i < AHD_NUM_TARGETS; i++) ahd_outw(ahd, WAITING_SCB_TAILS + (2 * i), SCB_LIST_NULL); /* * Nobody is waiting to be DMAed into the QOUTFIFO. */ ahd_outw(ahd, COMPLETE_SCB_HEAD, SCB_LIST_NULL); ahd_outw(ahd, COMPLETE_SCB_DMAINPROG_HEAD, SCB_LIST_NULL); ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, SCB_LIST_NULL); ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, SCB_LIST_NULL); ahd_outw(ahd, COMPLETE_ON_QFREEZE_HEAD, SCB_LIST_NULL); /* * The Freeze Count is 0. */ ahd->qfreeze_cnt = 0; ahd_outw(ahd, QFREEZE_COUNT, 0); ahd_outw(ahd, KERNEL_QFREEZE_COUNT, 0); /* * Tell the sequencer where it can find our arrays in memory. */ busaddr = ahd->shared_data_map.physaddr; ahd_outl(ahd, SHARED_DATA_ADDR, busaddr); ahd_outl(ahd, QOUTFIFO_NEXT_ADDR, busaddr); /* * Setup the allowed SCSI Sequences based on operational mode. * If we are a target, we'll enable select in operations once * we've had a lun enabled. */ scsiseq_template = ENAUTOATNP; if ((ahd->flags & AHD_INITIATORROLE) != 0) scsiseq_template |= ENRSELI; ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq_template); /* There are no busy SCBs yet. */ for (target = 0; target < AHD_NUM_TARGETS; target++) { int lun; for (lun = 0; lun < AHD_NUM_LUNS_NONPKT; lun++) ahd_unbusy_tcl(ahd, BUILD_TCL_RAW(target, 'A', lun)); } /* * Initialize the group code to command length table. * Vendor Unique codes are set to 0 so we only capture * the first byte of the cdb. These can be overridden * when target mode is enabled. */ ahd_outb(ahd, CMDSIZE_TABLE, 5); ahd_outb(ahd, CMDSIZE_TABLE + 1, 9); ahd_outb(ahd, CMDSIZE_TABLE + 2, 9); ahd_outb(ahd, CMDSIZE_TABLE + 3, 0); ahd_outb(ahd, CMDSIZE_TABLE + 4, 15); ahd_outb(ahd, CMDSIZE_TABLE + 5, 11); ahd_outb(ahd, CMDSIZE_TABLE + 6, 0); ahd_outb(ahd, CMDSIZE_TABLE + 7, 0); /* Tell the sequencer of our initial queue positions */ ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN); ahd_outb(ahd, QOFF_CTLSTA, SCB_QSIZE_512); ahd->qinfifonext = 0; ahd_set_hnscb_qoff(ahd, ahd->qinfifonext); ahd_set_hescb_qoff(ahd, 0); ahd_set_snscb_qoff(ahd, 0); ahd_set_sescb_qoff(ahd, 0); ahd_set_sdscb_qoff(ahd, 0); /* * Tell the sequencer which SCB will be the next one it receives. */ busaddr = ahd_le32toh(ahd->next_queued_hscb->hscb_busaddr); ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr); /* * Default to coalescing disabled. */ ahd_outw(ahd, INT_COALESCING_CMDCOUNT, 0); ahd_outw(ahd, CMDS_PENDING, 0); ahd_update_coalescing_values(ahd, ahd->int_coalescing_timer, ahd->int_coalescing_maxcmds, ahd->int_coalescing_mincmds); ahd_enable_coalescing(ahd, FALSE); ahd_loadseq(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); if (ahd->features & AHD_AIC79XXB_SLOWCRC) { u_int negodat3 = ahd_inb(ahd, NEGCONOPTS); negodat3 |= ENSLOWCRC; ahd_outb(ahd, NEGCONOPTS, negodat3); negodat3 = ahd_inb(ahd, NEGCONOPTS); if (!(negodat3 & ENSLOWCRC)) printf("aic79xx: failed to set the SLOWCRC bit\n"); else printf("aic79xx: SLOWCRC bit set\n"); } } /* * Setup default device and controller settings. * This should only be called if our probe has * determined that no configuration data is available. */ int ahd_default_config(struct ahd_softc *ahd) { int targ; ahd->our_id = 7; /* * Allocate a tstate to house information for our * initiator presence on the bus as well as the user * data for any target mode initiator. */ if (ahd_alloc_tstate(ahd, ahd->our_id, 'A') == NULL) { printf("%s: unable to allocate ahd_tmode_tstate. " "Failing attach\n", ahd_name(ahd)); return (ENOMEM); } for (targ = 0; targ < AHD_NUM_TARGETS; targ++) { struct ahd_devinfo devinfo; struct ahd_initiator_tinfo *tinfo; struct ahd_tmode_tstate *tstate; uint16_t target_mask; tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id, targ, &tstate); /* * We support SPC2 and SPI4. */ tinfo->user.protocol_version = 4; tinfo->user.transport_version = 4; target_mask = 0x01 << targ; ahd->user_discenable |= target_mask; tstate->discenable |= target_mask; ahd->user_tagenable |= target_mask; #ifdef AHD_FORCE_160 tinfo->user.period = AHD_SYNCRATE_DT; #else tinfo->user.period = AHD_SYNCRATE_160; #endif tinfo->user.offset = MAX_OFFSET; tinfo->user.ppr_options = MSG_EXT_PPR_RD_STRM | MSG_EXT_PPR_WR_FLOW | MSG_EXT_PPR_HOLD_MCS | MSG_EXT_PPR_IU_REQ | MSG_EXT_PPR_QAS_REQ | MSG_EXT_PPR_DT_REQ; if ((ahd->features & AHD_RTI) != 0) tinfo->user.ppr_options |= MSG_EXT_PPR_RTI; tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT; /* * Start out Async/Narrow/Untagged and with * conservative protocol support. */ tinfo->goal.protocol_version = 2; tinfo->goal.transport_version = 2; tinfo->curr.protocol_version = 2; tinfo->curr.transport_version = 2; ahd_compile_devinfo(&devinfo, ahd->our_id, targ, CAM_LUN_WILDCARD, 'A', ROLE_INITIATOR); tstate->tagenable &= ~target_mask; ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT, AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE); ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0, /*ppr_options*/0, AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE); } return (0); } /* * Parse device configuration information. */ int ahd_parse_cfgdata(struct ahd_softc *ahd, struct seeprom_config *sc) { int targ; int max_targ; max_targ = sc->max_targets & CFMAXTARG; ahd->our_id = sc->brtime_id & CFSCSIID; /* * Allocate a tstate to house information for our * initiator presence on the bus as well as the user * data for any target mode initiator. */ if (ahd_alloc_tstate(ahd, ahd->our_id, 'A') == NULL) { printf("%s: unable to allocate ahd_tmode_tstate. " "Failing attach\n", ahd_name(ahd)); return (ENOMEM); } for (targ = 0; targ < max_targ; targ++) { struct ahd_devinfo devinfo; struct ahd_initiator_tinfo *tinfo; struct ahd_transinfo *user_tinfo; struct ahd_tmode_tstate *tstate; uint16_t target_mask; tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id, targ, &tstate); user_tinfo = &tinfo->user; /* * We support SPC2 and SPI4. */ tinfo->user.protocol_version = 4; tinfo->user.transport_version = 4; target_mask = 0x01 << targ; ahd->user_discenable &= ~target_mask; tstate->discenable &= ~target_mask; ahd->user_tagenable &= ~target_mask; if (sc->device_flags[targ] & CFDISC) { tstate->discenable |= target_mask; ahd->user_discenable |= target_mask; ahd->user_tagenable |= target_mask; } else { /* * Cannot be packetized without disconnection. */ sc->device_flags[targ] &= ~CFPACKETIZED; } user_tinfo->ppr_options = 0; user_tinfo->period = (sc->device_flags[targ] & CFXFER); if (user_tinfo->period < CFXFER_ASYNC) { if (user_tinfo->period <= AHD_PERIOD_10MHz) user_tinfo->ppr_options |= MSG_EXT_PPR_DT_REQ; user_tinfo->offset = MAX_OFFSET; } else { user_tinfo->offset = 0; user_tinfo->period = AHD_ASYNC_XFER_PERIOD; } #ifdef AHD_FORCE_160 if (user_tinfo->period <= AHD_SYNCRATE_160) user_tinfo->period = AHD_SYNCRATE_DT; #endif if ((sc->device_flags[targ] & CFPACKETIZED) != 0) { user_tinfo->ppr_options |= MSG_EXT_PPR_RD_STRM | MSG_EXT_PPR_WR_FLOW | MSG_EXT_PPR_HOLD_MCS | MSG_EXT_PPR_IU_REQ; if ((ahd->features & AHD_RTI) != 0) user_tinfo->ppr_options |= MSG_EXT_PPR_RTI; } if ((sc->device_flags[targ] & CFQAS) != 0) user_tinfo->ppr_options |= MSG_EXT_PPR_QAS_REQ; if ((sc->device_flags[targ] & CFWIDEB) != 0) user_tinfo->width = MSG_EXT_WDTR_BUS_16_BIT; else user_tinfo->width = MSG_EXT_WDTR_BUS_8_BIT; #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MISC) != 0) printf("(%d): %x:%x:%x:%x\n", targ, user_tinfo->width, user_tinfo->period, user_tinfo->offset, user_tinfo->ppr_options); #endif /* * Start out Async/Narrow/Untagged and with * conservative protocol support. */ tstate->tagenable &= ~target_mask; tinfo->goal.protocol_version = 2; tinfo->goal.transport_version = 2; tinfo->curr.protocol_version = 2; tinfo->curr.transport_version = 2; ahd_compile_devinfo(&devinfo, ahd->our_id, targ, CAM_LUN_WILDCARD, 'A', ROLE_INITIATOR); ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT, AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE); ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0, /*ppr_options*/0, AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE); } ahd->flags &= ~AHD_SPCHK_ENB_A; if (sc->bios_control & CFSPARITY) ahd->flags |= AHD_SPCHK_ENB_A; ahd->flags &= ~AHD_RESET_BUS_A; if (sc->bios_control & CFRESETB) ahd->flags |= AHD_RESET_BUS_A; ahd->flags &= ~AHD_EXTENDED_TRANS_A; if (sc->bios_control & CFEXTEND) ahd->flags |= AHD_EXTENDED_TRANS_A; ahd->flags &= ~AHD_BIOS_ENABLED; if ((sc->bios_control & CFBIOSSTATE) == CFBS_ENABLED) ahd->flags |= AHD_BIOS_ENABLED; ahd->flags &= ~AHD_STPWLEVEL_A; if ((sc->adapter_control & CFSTPWLEVEL) != 0) ahd->flags |= AHD_STPWLEVEL_A; return (0); } /* * Parse device configuration information. */ int ahd_parse_vpddata(struct ahd_softc *ahd, struct vpd_config *vpd) { int error; error = ahd_verify_vpd_cksum(vpd); if (error == 0) return (EINVAL); if ((vpd->bios_flags & VPDBOOTHOST) != 0) ahd->flags |= AHD_BOOT_CHANNEL; return (0); } void ahd_intr_enable(struct ahd_softc *ahd, int enable) { u_int hcntrl; hcntrl = ahd_inb(ahd, HCNTRL); hcntrl &= ~INTEN; ahd->pause &= ~INTEN; ahd->unpause &= ~INTEN; if (enable) { hcntrl |= INTEN; ahd->pause |= INTEN; ahd->unpause |= INTEN; } ahd_outb(ahd, HCNTRL, hcntrl); } static void ahd_update_coalescing_values(struct ahd_softc *ahd, u_int timer, u_int maxcmds, u_int mincmds) { if (timer > AHD_TIMER_MAX_US) timer = AHD_TIMER_MAX_US; ahd->int_coalescing_timer = timer; if (maxcmds > AHD_INT_COALESCING_MAXCMDS_MAX) maxcmds = AHD_INT_COALESCING_MAXCMDS_MAX; if (mincmds > AHD_INT_COALESCING_MINCMDS_MAX) mincmds = AHD_INT_COALESCING_MINCMDS_MAX; ahd->int_coalescing_maxcmds = maxcmds; ahd_outw(ahd, INT_COALESCING_TIMER, timer / AHD_TIMER_US_PER_TICK); ahd_outb(ahd, INT_COALESCING_MAXCMDS, -maxcmds); ahd_outb(ahd, INT_COALESCING_MINCMDS, -mincmds); } static void ahd_enable_coalescing(struct ahd_softc *ahd, int enable) { ahd->hs_mailbox &= ~ENINT_COALESCE; if (enable) ahd->hs_mailbox |= ENINT_COALESCE; ahd_outb(ahd, HS_MAILBOX, ahd->hs_mailbox); ahd_flush_device_writes(ahd); ahd_run_qoutfifo(ahd); } /* * Ensure that the card is paused in a location * outside of all critical sections and that all * pending work is completed prior to returning. * This routine should only be called from outside * an interrupt context. */ void ahd_pause_and_flushwork(struct ahd_softc *ahd) { u_int intstat; u_int maxloops; maxloops = 1000; ahd->flags |= AHD_ALL_INTERRUPTS; ahd_pause(ahd); /* * Freeze the outgoing selections. We do this only * until we are safely paused without further selections * pending. */ ahd->qfreeze_cnt--; ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt); ahd_outb(ahd, SEQ_FLAGS2, ahd_inb(ahd, SEQ_FLAGS2) | SELECTOUT_QFROZEN); do { ahd_unpause(ahd); /* * Give the sequencer some time to service * any active selections. */ ahd_delay(500); ahd_intr(ahd); ahd_pause(ahd); intstat = ahd_inb(ahd, INTSTAT); if ((intstat & INT_PEND) == 0) { ahd_clear_critical_section(ahd); intstat = ahd_inb(ahd, INTSTAT); } } while (--maxloops && (intstat != 0xFF || (ahd->features & AHD_REMOVABLE) == 0) && ((intstat & INT_PEND) != 0 || (ahd_inb(ahd, SCSISEQ0) & ENSELO) != 0 || (ahd_inb(ahd, SSTAT0) & (SELDO|SELINGO)) != 0)); if (maxloops == 0) { printf("Infinite interrupt loop, INTSTAT = %x", ahd_inb(ahd, INTSTAT)); } ahd->qfreeze_cnt++; ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt); ahd_flush_qoutfifo(ahd); ahd->flags &= ~AHD_ALL_INTERRUPTS; } #if 0 int ahd_suspend(struct ahd_softc *ahd) { ahd_pause_and_flushwork(ahd); if (LIST_FIRST(&ahd->pending_scbs) != NULL) { ahd_unpause(ahd); return (EBUSY); } ahd_shutdown(ahd); return (0); } #endif /* 0 */ #if 0 int ahd_resume(struct ahd_softc *ahd) { ahd_reset(ahd, /*reinit*/TRUE); ahd_intr_enable(ahd, TRUE); ahd_restart(ahd); return (0); } #endif /* 0 */ /************************** Busy Target Table *********************************/ /* * Set SCBPTR to the SCB that contains the busy * table entry for TCL. Return the offset into * the SCB that contains the entry for TCL. * saved_scbid is dereferenced and set to the * scbid that should be restored once manipualtion * of the TCL entry is complete. */ static __inline u_int ahd_index_busy_tcl(struct ahd_softc *ahd, u_int *saved_scbid, u_int tcl) { /* * Index to the SCB that contains the busy entry. */ AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); *saved_scbid = ahd_get_scbptr(ahd); ahd_set_scbptr(ahd, TCL_LUN(tcl) | ((TCL_TARGET_OFFSET(tcl) & 0xC) << 4)); /* * And now calculate the SCB offset to the entry. * Each entry is 2 bytes wide, hence the * multiplication by 2. */ return (((TCL_TARGET_OFFSET(tcl) & 0x3) << 1) + SCB_DISCONNECTED_LISTS); } /* * Return the untagged transaction id for a given target/channel lun. */ static u_int ahd_find_busy_tcl(struct ahd_softc *ahd, u_int tcl) { u_int scbid; u_int scb_offset; u_int saved_scbptr; scb_offset = ahd_index_busy_tcl(ahd, &saved_scbptr, tcl); scbid = ahd_inw_scbram(ahd, scb_offset); ahd_set_scbptr(ahd, saved_scbptr); return (scbid); } static void ahd_busy_tcl(struct ahd_softc *ahd, u_int tcl, u_int scbid) { u_int scb_offset; u_int saved_scbptr; scb_offset = ahd_index_busy_tcl(ahd, &saved_scbptr, tcl); ahd_outw(ahd, scb_offset, scbid); ahd_set_scbptr(ahd, saved_scbptr); } /************************** SCB and SCB queue management **********************/ static int ahd_match_scb(struct ahd_softc *ahd, struct scb *scb, int target, char channel, int lun, u_int tag, role_t role) { int targ = SCB_GET_TARGET(ahd, scb); char chan = SCB_GET_CHANNEL(ahd, scb); int slun = SCB_GET_LUN(scb); int match; match = ((chan == channel) || (channel == ALL_CHANNELS)); if (match != 0) match = ((targ == target) || (target == CAM_TARGET_WILDCARD)); if (match != 0) match = ((lun == slun) || (lun == CAM_LUN_WILDCARD)); if (match != 0) { #ifdef AHD_TARGET_MODE int group; group = XPT_FC_GROUP(scb->io_ctx->ccb_h.func_code); if (role == ROLE_INITIATOR) { match = (group != XPT_FC_GROUP_TMODE) && ((tag == SCB_GET_TAG(scb)) || (tag == SCB_LIST_NULL)); } else if (role == ROLE_TARGET) { match = (group == XPT_FC_GROUP_TMODE) && ((tag == scb->io_ctx->csio.tag_id) || (tag == SCB_LIST_NULL)); } #else /* !AHD_TARGET_MODE */ match = ((tag == SCB_GET_TAG(scb)) || (tag == SCB_LIST_NULL)); #endif /* AHD_TARGET_MODE */ } return match; } static void ahd_freeze_devq(struct ahd_softc *ahd, struct scb *scb) { int target; char channel; int lun; target = SCB_GET_TARGET(ahd, scb); lun = SCB_GET_LUN(scb); channel = SCB_GET_CHANNEL(ahd, scb); ahd_search_qinfifo(ahd, target, channel, lun, /*tag*/SCB_LIST_NULL, ROLE_UNKNOWN, CAM_REQUEUE_REQ, SEARCH_COMPLETE); ahd_platform_freeze_devq(ahd, scb); } void ahd_qinfifo_requeue_tail(struct ahd_softc *ahd, struct scb *scb) { struct scb *prev_scb; ahd_mode_state saved_modes; saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN); prev_scb = NULL; if (ahd_qinfifo_count(ahd) != 0) { u_int prev_tag; u_int prev_pos; prev_pos = AHD_QIN_WRAP(ahd->qinfifonext - 1); prev_tag = ahd->qinfifo[prev_pos]; prev_scb = ahd_lookup_scb(ahd, prev_tag); } ahd_qinfifo_requeue(ahd, prev_scb, scb); ahd_set_hnscb_qoff(ahd, ahd->qinfifonext); ahd_restore_modes(ahd, saved_modes); } static void ahd_qinfifo_requeue(struct ahd_softc *ahd, struct scb *prev_scb, struct scb *scb) { if (prev_scb == NULL) { uint32_t busaddr; busaddr = ahd_le32toh(scb->hscb->hscb_busaddr); ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr); } else { prev_scb->hscb->next_hscb_busaddr = scb->hscb->hscb_busaddr; ahd_sync_scb(ahd, prev_scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE); } ahd->qinfifo[AHD_QIN_WRAP(ahd->qinfifonext)] = SCB_GET_TAG(scb); ahd->qinfifonext++; scb->hscb->next_hscb_busaddr = ahd->next_queued_hscb->hscb_busaddr; ahd_sync_scb(ahd, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE); } static int ahd_qinfifo_count(struct ahd_softc *ahd) { u_int qinpos; u_int wrap_qinpos; u_int wrap_qinfifonext; AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK); qinpos = ahd_get_snscb_qoff(ahd); wrap_qinpos = AHD_QIN_WRAP(qinpos); wrap_qinfifonext = AHD_QIN_WRAP(ahd->qinfifonext); if (wrap_qinfifonext >= wrap_qinpos) return (wrap_qinfifonext - wrap_qinpos); else return (wrap_qinfifonext + ARRAY_SIZE(ahd->qinfifo) - wrap_qinpos); } void ahd_reset_cmds_pending(struct ahd_softc *ahd) { struct scb *scb; ahd_mode_state saved_modes; u_int pending_cmds; saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN); /* * Don't count any commands as outstanding that the * sequencer has already marked for completion. */ ahd_flush_qoutfifo(ahd); pending_cmds = 0; LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) { pending_cmds++; } ahd_outw(ahd, CMDS_PENDING, pending_cmds - ahd_qinfifo_count(ahd)); ahd_restore_modes(ahd, saved_modes); ahd->flags &= ~AHD_UPDATE_PEND_CMDS; } static void ahd_done_with_status(struct ahd_softc *ahd, struct scb *scb, uint32_t status) { cam_status ostat; cam_status cstat; ostat = ahd_get_transaction_status(scb); if (ostat == CAM_REQ_INPROG) ahd_set_transaction_status(scb, status); cstat = ahd_get_transaction_status(scb); if (cstat != CAM_REQ_CMP) ahd_freeze_scb(scb); ahd_done(ahd, scb); } int ahd_search_qinfifo(struct ahd_softc *ahd, int target, char channel, int lun, u_int tag, role_t role, uint32_t status, ahd_search_action action) { struct scb *scb; struct scb *mk_msg_scb; struct scb *prev_scb; ahd_mode_state saved_modes; u_int qinstart; u_int qinpos; u_int qintail; u_int tid_next; u_int tid_prev; u_int scbid; u_int seq_flags2; u_int savedscbptr; uint32_t busaddr; int found; int targets; /* Must be in CCHAN mode */ saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN); /* * Halt any pending SCB DMA. The sequencer will reinitiate * this dma if the qinfifo is not empty once we unpause. */ if ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN|CCSCBDIR)) == (CCARREN|CCSCBEN|CCSCBDIR)) { ahd_outb(ahd, CCSCBCTL, ahd_inb(ahd, CCSCBCTL) & ~(CCARREN|CCSCBEN)); while ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN)) != 0) ; } /* Determine sequencer's position in the qinfifo. */ qintail = AHD_QIN_WRAP(ahd->qinfifonext); qinstart = ahd_get_snscb_qoff(ahd); qinpos = AHD_QIN_WRAP(qinstart); found = 0; prev_scb = NULL; if (action == SEARCH_PRINT) { printf("qinstart = %d qinfifonext = %d\nQINFIFO:", qinstart, ahd->qinfifonext); } /* * Start with an empty queue. Entries that are not chosen * for removal will be re-added to the queue as we go. */ ahd->qinfifonext = qinstart; busaddr = ahd_le32toh(ahd->next_queued_hscb->hscb_busaddr); ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr); while (qinpos != qintail) { scb = ahd_lookup_scb(ahd, ahd->qinfifo[qinpos]); if (scb == NULL) { printf("qinpos = %d, SCB index = %d\n", qinpos, ahd->qinfifo[qinpos]); panic("Loop 1\n"); } if (ahd_match_scb(ahd, scb, target, channel, lun, tag, role)) { /* * We found an scb that needs to be acted on. */ found++; switch (action) { case SEARCH_COMPLETE: if ((scb->flags & SCB_ACTIVE) == 0) printf("Inactive SCB in qinfifo\n"); ahd_done_with_status(ahd, scb, status); /* FALLTHROUGH */ case SEARCH_REMOVE: break; case SEARCH_PRINT: printf(" 0x%x", ahd->qinfifo[qinpos]); /* FALLTHROUGH */ case SEARCH_COUNT: ahd_qinfifo_requeue(ahd, prev_scb, scb); prev_scb = scb; break; } } else { ahd_qinfifo_requeue(ahd, prev_scb, scb); prev_scb = scb; } qinpos = AHD_QIN_WRAP(qinpos+1); } ahd_set_hnscb_qoff(ahd, ahd->qinfifonext); if (action == SEARCH_PRINT) printf("\nWAITING_TID_QUEUES:\n"); /* * Search waiting for selection lists. We traverse the * list of "their ids" waiting for selection and, if * appropriate, traverse the SCBs of each "their id" * looking for matches. */ ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); seq_flags2 = ahd_inb(ahd, SEQ_FLAGS2); if ((seq_flags2 & PENDING_MK_MESSAGE) != 0) { scbid = ahd_inw(ahd, MK_MESSAGE_SCB); mk_msg_scb = ahd_lookup_scb(ahd, scbid); } else mk_msg_scb = NULL; savedscbptr = ahd_get_scbptr(ahd); tid_next = ahd_inw(ahd, WAITING_TID_HEAD); tid_prev = SCB_LIST_NULL; targets = 0; for (scbid = tid_next; !SCBID_IS_NULL(scbid); scbid = tid_next) { u_int tid_head; u_int tid_tail; targets++; if (targets > AHD_NUM_TARGETS) panic("TID LIST LOOP"); if (scbid >= ahd->scb_data.numscbs) { printf("%s: Waiting TID List inconsistency. " "SCB index == 0x%x, yet numscbs == 0x%x.", ahd_name(ahd), scbid, ahd->scb_data.numscbs); ahd_dump_card_state(ahd); panic("for safety"); } scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { printf("%s: SCB = 0x%x Not Active!\n", ahd_name(ahd), scbid); panic("Waiting TID List traversal\n"); } ahd_set_scbptr(ahd, scbid); tid_next = ahd_inw_scbram(ahd, SCB_NEXT2); if (ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN) == 0) { tid_prev = scbid; continue; } /* * We found a list of scbs that needs to be searched. */ if (action == SEARCH_PRINT) printf(" %d ( ", SCB_GET_TARGET(ahd, scb)); tid_head = scbid; found += ahd_search_scb_list(ahd, target, channel, lun, tag, role, status, action, &tid_head, &tid_tail, SCB_GET_TARGET(ahd, scb)); /* * Check any MK_MESSAGE SCB that is still waiting to * enter this target's waiting for selection queue. */ if (mk_msg_scb != NULL && ahd_match_scb(ahd, mk_msg_scb, target, channel, lun, tag, role)) { /* * We found an scb that needs to be acted on. */ found++; switch (action) { case SEARCH_COMPLETE: if ((mk_msg_scb->flags & SCB_ACTIVE) == 0) printf("Inactive SCB pending MK_MSG\n"); ahd_done_with_status(ahd, mk_msg_scb, status); /* FALLTHROUGH */ case SEARCH_REMOVE: { u_int tail_offset; printf("Removing MK_MSG scb\n"); /* * Reset our tail to the tail of the * main per-target list. */ tail_offset = WAITING_SCB_TAILS + (2 * SCB_GET_TARGET(ahd, mk_msg_scb)); ahd_outw(ahd, tail_offset, tid_tail); seq_flags2 &= ~PENDING_MK_MESSAGE; ahd_outb(ahd, SEQ_FLAGS2, seq_flags2); ahd_outw(ahd, CMDS_PENDING, ahd_inw(ahd, CMDS_PENDING)-1); mk_msg_scb = NULL; break; } case SEARCH_PRINT: printf(" 0x%x", SCB_GET_TAG(scb)); /* FALLTHROUGH */ case SEARCH_COUNT: break; } } if (mk_msg_scb != NULL && SCBID_IS_NULL(tid_head) && ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN)) { /* * When removing the last SCB for a target * queue with a pending MK_MESSAGE scb, we * must queue the MK_MESSAGE scb. */ printf("Queueing mk_msg_scb\n"); tid_head = ahd_inw(ahd, MK_MESSAGE_SCB); seq_flags2 &= ~PENDING_MK_MESSAGE; ahd_outb(ahd, SEQ_FLAGS2, seq_flags2); mk_msg_scb = NULL; } if (tid_head != scbid) ahd_stitch_tid_list(ahd, tid_prev, tid_head, tid_next); if (!SCBID_IS_NULL(tid_head)) tid_prev = tid_head; if (action == SEARCH_PRINT) printf(")\n"); } /* Restore saved state. */ ahd_set_scbptr(ahd, savedscbptr); ahd_restore_modes(ahd, saved_modes); return (found); } static int ahd_search_scb_list(struct ahd_softc *ahd, int target, char channel, int lun, u_int tag, role_t role, uint32_t status, ahd_search_action action, u_int *list_head, u_int *list_tail, u_int tid) { struct scb *scb; u_int scbid; u_int next; u_int prev; int found; AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); found = 0; prev = SCB_LIST_NULL; next = *list_head; *list_tail = SCB_LIST_NULL; for (scbid = next; !SCBID_IS_NULL(scbid); scbid = next) { if (scbid >= ahd->scb_data.numscbs) { printf("%s:SCB List inconsistency. " "SCB == 0x%x, yet numscbs == 0x%x.", ahd_name(ahd), scbid, ahd->scb_data.numscbs); ahd_dump_card_state(ahd); panic("for safety"); } scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { printf("%s: SCB = %d Not Active!\n", ahd_name(ahd), scbid); panic("Waiting List traversal\n"); } ahd_set_scbptr(ahd, scbid); *list_tail = scbid; next = ahd_inw_scbram(ahd, SCB_NEXT); if (ahd_match_scb(ahd, scb, target, channel, lun, SCB_LIST_NULL, role) == 0) { prev = scbid; continue; } found++; switch (action) { case SEARCH_COMPLETE: if ((scb->flags & SCB_ACTIVE) == 0) printf("Inactive SCB in Waiting List\n"); ahd_done_with_status(ahd, scb, status); /* FALLTHROUGH */ case SEARCH_REMOVE: ahd_rem_wscb(ahd, scbid, prev, next, tid); *list_tail = prev; if (SCBID_IS_NULL(prev)) *list_head = next; break; case SEARCH_PRINT: printf("0x%x ", scbid); case SEARCH_COUNT: prev = scbid; break; } if (found > AHD_SCB_MAX) panic("SCB LIST LOOP"); } if (action == SEARCH_COMPLETE || action == SEARCH_REMOVE) ahd_outw(ahd, CMDS_PENDING, ahd_inw(ahd, CMDS_PENDING) - found); return (found); } static void ahd_stitch_tid_list(struct ahd_softc *ahd, u_int tid_prev, u_int tid_cur, u_int tid_next) { AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); if (SCBID_IS_NULL(tid_cur)) { /* Bypass current TID list */ if (SCBID_IS_NULL(tid_prev)) { ahd_outw(ahd, WAITING_TID_HEAD, tid_next); } else { ahd_set_scbptr(ahd, tid_prev); ahd_outw(ahd, SCB_NEXT2, tid_next); } if (SCBID_IS_NULL(tid_next)) ahd_outw(ahd, WAITING_TID_TAIL, tid_prev); } else { /* Stitch through tid_cur */ if (SCBID_IS_NULL(tid_prev)) { ahd_outw(ahd, WAITING_TID_HEAD, tid_cur); } else { ahd_set_scbptr(ahd, tid_prev); ahd_outw(ahd, SCB_NEXT2, tid_cur); } ahd_set_scbptr(ahd, tid_cur); ahd_outw(ahd, SCB_NEXT2, tid_next); if (SCBID_IS_NULL(tid_next)) ahd_outw(ahd, WAITING_TID_TAIL, tid_cur); } } /* * Manipulate the waiting for selection list and return the * scb that follows the one that we remove. */ static u_int ahd_rem_wscb(struct ahd_softc *ahd, u_int scbid, u_int prev, u_int next, u_int tid) { u_int tail_offset; AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); if (!SCBID_IS_NULL(prev)) { ahd_set_scbptr(ahd, prev); ahd_outw(ahd, SCB_NEXT, next); } /* * SCBs that have MK_MESSAGE set in them may * cause the tail pointer to be updated without * setting the next pointer of the previous tail. * Only clear the tail if the removed SCB was * the tail. */ tail_offset = WAITING_SCB_TAILS + (2 * tid); if (SCBID_IS_NULL(next) && ahd_inw(ahd, tail_offset) == scbid) ahd_outw(ahd, tail_offset, prev); ahd_add_scb_to_free_list(ahd, scbid); return (next); } /* * Add the SCB as selected by SCBPTR onto the on chip list of * free hardware SCBs. This list is empty/unused if we are not * performing SCB paging. */ static void ahd_add_scb_to_free_list(struct ahd_softc *ahd, u_int scbid) { /* XXX Need some other mechanism to designate "free". */ /* * Invalidate the tag so that our abort * routines don't think it's active. ahd_outb(ahd, SCB_TAG, SCB_LIST_NULL); */ } /******************************** Error Handling ******************************/ /* * Abort all SCBs that match the given description (target/channel/lun/tag), * setting their status to the passed in status if the status has not already * been modified from CAM_REQ_INPROG. This routine assumes that the sequencer * is paused before it is called. */ static int ahd_abort_scbs(struct ahd_softc *ahd, int target, char channel, int lun, u_int tag, role_t role, uint32_t status) { struct scb *scbp; struct scb *scbp_next; u_int i, j; u_int maxtarget; u_int minlun; u_int maxlun; int found; ahd_mode_state saved_modes; /* restore this when we're done */ saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); found = ahd_search_qinfifo(ahd, target, channel, lun, SCB_LIST_NULL, role, CAM_REQUEUE_REQ, SEARCH_COMPLETE); /* * Clean out the busy target table for any untagged commands. */ i = 0; maxtarget = 16; if (target != CAM_TARGET_WILDCARD) { i = target; if (channel == 'B') i += 8; maxtarget = i + 1; } if (lun == CAM_LUN_WILDCARD) { minlun = 0; maxlun = AHD_NUM_LUNS_NONPKT; } else if (lun >= AHD_NUM_LUNS_NONPKT) { minlun = maxlun = 0; } else { minlun = lun; maxlun = lun + 1; } if (role != ROLE_TARGET) { for (;i < maxtarget; i++) { for (j = minlun;j < maxlun; j++) { u_int scbid; u_int tcl; tcl = BUILD_TCL_RAW(i, 'A', j); scbid = ahd_find_busy_tcl(ahd, tcl); scbp = ahd_lookup_scb(ahd, scbid); if (scbp == NULL || ahd_match_scb(ahd, scbp, target, channel, lun, tag, role) == 0) continue; ahd_unbusy_tcl(ahd, BUILD_TCL_RAW(i, 'A', j)); } } } /* * Don't abort commands that have already completed, * but haven't quite made it up to the host yet. */ ahd_flush_qoutfifo(ahd); /* * Go through the pending CCB list and look for * commands for this target that are still active. * These are other tagged commands that were * disconnected when the reset occurred. */ scbp_next = LIST_FIRST(&ahd->pending_scbs); while (scbp_next != NULL) { scbp = scbp_next; scbp_next = LIST_NEXT(scbp, pending_links); if (ahd_match_scb(ahd, scbp, target, channel, lun, tag, role)) { cam_status ostat; ostat = ahd_get_transaction_status(scbp); if (ostat == CAM_REQ_INPROG) ahd_set_transaction_status(scbp, status); if (ahd_get_transaction_status(scbp) != CAM_REQ_CMP) ahd_freeze_scb(scbp); if ((scbp->flags & SCB_ACTIVE) == 0) printf("Inactive SCB on pending list\n"); ahd_done(ahd, scbp); found++; } } ahd_restore_modes(ahd, saved_modes); ahd_platform_abort_scbs(ahd, target, channel, lun, tag, role, status); ahd->flags |= AHD_UPDATE_PEND_CMDS; return found; } static void ahd_reset_current_bus(struct ahd_softc *ahd) { uint8_t scsiseq; AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) & ~ENSCSIRST); scsiseq = ahd_inb(ahd, SCSISEQ0) & ~(ENSELO|ENARBO|SCSIRSTO); ahd_outb(ahd, SCSISEQ0, scsiseq | SCSIRSTO); ahd_flush_device_writes(ahd); ahd_delay(AHD_BUSRESET_DELAY); /* Turn off the bus reset */ ahd_outb(ahd, SCSISEQ0, scsiseq); ahd_flush_device_writes(ahd); ahd_delay(AHD_BUSRESET_DELAY); if ((ahd->bugs & AHD_SCSIRST_BUG) != 0) { /* * 2A Razor #474 * Certain chip state is not cleared for * SCSI bus resets that we initiate, so * we must reset the chip. */ ahd_reset(ahd, /*reinit*/TRUE); ahd_intr_enable(ahd, /*enable*/TRUE); AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); } ahd_clear_intstat(ahd); } int ahd_reset_channel(struct ahd_softc *ahd, char channel, int initiate_reset) { struct ahd_devinfo devinfo; u_int initiator; u_int target; u_int max_scsiid; int found; u_int fifo; u_int next_fifo; uint8_t scsiseq; /* * Check if the last bus reset is cleared */ if (ahd->flags & AHD_BUS_RESET_ACTIVE) { printf("%s: bus reset still active\n", ahd_name(ahd)); return 0; } ahd->flags |= AHD_BUS_RESET_ACTIVE; ahd->pending_device = NULL; ahd_compile_devinfo(&devinfo, CAM_TARGET_WILDCARD, CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD, channel, ROLE_UNKNOWN); ahd_pause(ahd); /* Make sure the sequencer is in a safe location. */ ahd_clear_critical_section(ahd); /* * Run our command complete fifos to ensure that we perform * completion processing on any commands that 'completed' * before the reset occurred. */ ahd_run_qoutfifo(ahd); #ifdef AHD_TARGET_MODE if ((ahd->flags & AHD_TARGETROLE) != 0) { ahd_run_tqinfifo(ahd, /*paused*/TRUE); } #endif ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); /* * Disable selections so no automatic hardware * functions will modify chip state. */ ahd_outb(ahd, SCSISEQ0, 0); ahd_outb(ahd, SCSISEQ1, 0); /* * Safely shut down our DMA engines. Always start with * the FIFO that is not currently active (if any are * actively connected). */ next_fifo = fifo = ahd_inb(ahd, DFFSTAT) & CURRFIFO; if (next_fifo > CURRFIFO_1) /* If disconneced, arbitrarily start with FIFO1. */ next_fifo = fifo = 0; do { next_fifo ^= CURRFIFO_1; ahd_set_modes(ahd, next_fifo, next_fifo); ahd_outb(ahd, DFCNTRL, ahd_inb(ahd, DFCNTRL) & ~(SCSIEN|HDMAEN)); while ((ahd_inb(ahd, DFCNTRL) & HDMAENACK) != 0) ahd_delay(10); /* * Set CURRFIFO to the now inactive channel. */ ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); ahd_outb(ahd, DFFSTAT, next_fifo); } while (next_fifo != fifo); /* * Reset the bus if we are initiating this reset */ ahd_clear_msg_state(ahd); ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) & ~(ENBUSFREE|ENSCSIRST)); if (initiate_reset) ahd_reset_current_bus(ahd); ahd_clear_intstat(ahd); /* * Clean up all the state information for the * pending transactions on this bus. */ found = ahd_abort_scbs(ahd, CAM_TARGET_WILDCARD, channel, CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN, CAM_SCSI_BUS_RESET); /* * Cleanup anything left in the FIFOs. */ ahd_clear_fifo(ahd, 0); ahd_clear_fifo(ahd, 1); /* * Clear SCSI interrupt status */ ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI); /* * Reenable selections */ ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) | ENSCSIRST); scsiseq = ahd_inb(ahd, SCSISEQ_TEMPLATE); ahd_outb(ahd, SCSISEQ1, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP)); max_scsiid = (ahd->features & AHD_WIDE) ? 15 : 7; #ifdef AHD_TARGET_MODE /* * Send an immediate notify ccb to all target more peripheral * drivers affected by this action. */ for (target = 0; target <= max_scsiid; target++) { struct ahd_tmode_tstate* tstate; u_int lun; tstate = ahd->enabled_targets[target]; if (tstate == NULL) continue; for (lun = 0; lun < AHD_NUM_LUNS; lun++) { struct ahd_tmode_lstate* lstate; lstate = tstate->enabled_luns[lun]; if (lstate == NULL) continue; ahd_queue_lstate_event(ahd, lstate, CAM_TARGET_WILDCARD, EVENT_TYPE_BUS_RESET, /*arg*/0); ahd_send_lstate_events(ahd, lstate); } } #endif /* * Revert to async/narrow transfers until we renegotiate. */ for (target = 0; target <= max_scsiid; target++) { if (ahd->enabled_targets[target] == NULL) continue; for (initiator = 0; initiator <= max_scsiid; initiator++) { struct ahd_devinfo devinfo; ahd_compile_devinfo(&devinfo, target, initiator, CAM_LUN_WILDCARD, 'A', ROLE_UNKNOWN); ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT, AHD_TRANS_CUR, /*paused*/TRUE); ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0, /*ppr_options*/0, AHD_TRANS_CUR, /*paused*/TRUE); } } /* Notify the XPT that a bus reset occurred */ ahd_send_async(ahd, devinfo.channel, CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD, AC_BUS_RESET); ahd_restart(ahd); return (found); } /**************************** Statistics Processing ***************************/ static void ahd_stat_timer(void *arg) { struct ahd_softc *ahd = arg; u_long s; int enint_coal; ahd_lock(ahd, &s); enint_coal = ahd->hs_mailbox & ENINT_COALESCE; if (ahd->cmdcmplt_total > ahd->int_coalescing_threshold) enint_coal |= ENINT_COALESCE; else if (ahd->cmdcmplt_total < ahd->int_coalescing_stop_threshold) enint_coal &= ~ENINT_COALESCE; if (enint_coal != (ahd->hs_mailbox & ENINT_COALESCE)) { ahd_enable_coalescing(ahd, enint_coal); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_INT_COALESCING) != 0) printf("%s: Interrupt coalescing " "now %sabled. Cmds %d\n", ahd_name(ahd), (enint_coal & ENINT_COALESCE) ? "en" : "dis", ahd->cmdcmplt_total); #endif } ahd->cmdcmplt_bucket = (ahd->cmdcmplt_bucket+1) & (AHD_STAT_BUCKETS-1); ahd->cmdcmplt_total -= ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket]; ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket] = 0; ahd_timer_reset(&ahd->stat_timer, AHD_STAT_UPDATE_US, ahd_stat_timer, ahd); ahd_unlock(ahd, &s); } /****************************** Status Processing *****************************/ static void ahd_handle_scsi_status(struct ahd_softc *ahd, struct scb *scb) { struct hardware_scb *hscb; int paused; /* * The sequencer freezes its select-out queue * anytime a SCSI status error occurs. We must * handle the error and increment our qfreeze count * to allow the sequencer to continue. We don't * bother clearing critical sections here since all * operations are on data structures that the sequencer * is not touching once the queue is frozen. */ hscb = scb->hscb; if (ahd_is_paused(ahd)) { paused = 1; } else { paused = 0; ahd_pause(ahd); } /* Freeze the queue until the client sees the error. */ ahd_freeze_devq(ahd, scb); ahd_freeze_scb(scb); ahd->qfreeze_cnt++; ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt); if (paused == 0) ahd_unpause(ahd); /* Don't want to clobber the original sense code */ if ((scb->flags & SCB_SENSE) != 0) { /* * Clear the SCB_SENSE Flag and perform * a normal command completion. */ scb->flags &= ~SCB_SENSE; ahd_set_transaction_status(scb, CAM_AUTOSENSE_FAIL); ahd_done(ahd, scb); return; } ahd_set_transaction_status(scb, CAM_SCSI_STATUS_ERROR); ahd_set_scsi_status(scb, hscb->shared_data.istatus.scsi_status); switch (hscb->shared_data.istatus.scsi_status) { case STATUS_PKT_SENSE: { struct scsi_status_iu_header *siu; ahd_sync_sense(ahd, scb, BUS_DMASYNC_POSTREAD); siu = (struct scsi_status_iu_header *)scb->sense_data; ahd_set_scsi_status(scb, siu->status); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_SENSE) != 0) { ahd_print_path(ahd, scb); printf("SCB 0x%x Received PKT Status of 0x%x\n", SCB_GET_TAG(scb), siu->status); printf("\tflags = 0x%x, sense len = 0x%x, " "pktfail = 0x%x\n", siu->flags, scsi_4btoul(siu->sense_length), scsi_4btoul(siu->pkt_failures_length)); } #endif if ((siu->flags & SIU_RSPVALID) != 0) { ahd_print_path(ahd, scb); if (scsi_4btoul(siu->pkt_failures_length) < 4) { printf("Unable to parse pkt_failures\n"); } else { switch (SIU_PKTFAIL_CODE(siu)) { case SIU_PFC_NONE: printf("No packet failure found\n"); break; case SIU_PFC_CIU_FIELDS_INVALID: printf("Invalid Command IU Field\n"); break; case SIU_PFC_TMF_NOT_SUPPORTED: printf("TMF not supportd\n"); break; case SIU_PFC_TMF_FAILED: printf("TMF failed\n"); break; case SIU_PFC_INVALID_TYPE_CODE: printf("Invalid L_Q Type code\n"); break; case SIU_PFC_ILLEGAL_REQUEST: printf("Illegal request\n"); default: break; } } if (siu->status == SCSI_STATUS_OK) ahd_set_transaction_status(scb, CAM_REQ_CMP_ERR); } if ((siu->flags & SIU_SNSVALID) != 0) { scb->flags |= SCB_PKT_SENSE; #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_SENSE) != 0) printf("Sense data available\n"); #endif } ahd_done(ahd, scb); break; } case SCSI_STATUS_CMD_TERMINATED: case SCSI_STATUS_CHECK_COND: { struct ahd_devinfo devinfo; struct ahd_dma_seg *sg; struct scsi_sense *sc; struct ahd_initiator_tinfo *targ_info; struct ahd_tmode_tstate *tstate; struct ahd_transinfo *tinfo; #ifdef AHD_DEBUG if (ahd_debug & AHD_SHOW_SENSE) { ahd_print_path(ahd, scb); printf("SCB %d: requests Check Status\n", SCB_GET_TAG(scb)); } #endif if (ahd_perform_autosense(scb) == 0) break; ahd_compile_devinfo(&devinfo, SCB_GET_OUR_ID(scb), SCB_GET_TARGET(ahd, scb), SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahd, scb), ROLE_INITIATOR); targ_info = ahd_fetch_transinfo(ahd, devinfo.channel, devinfo.our_scsiid, devinfo.target, &tstate); tinfo = &targ_info->curr; sg = scb->sg_list; sc = (struct scsi_sense *)hscb->shared_data.idata.cdb; /* * Save off the residual if there is one. */ ahd_update_residual(ahd, scb); #ifdef AHD_DEBUG if (ahd_debug & AHD_SHOW_SENSE) { ahd_print_path(ahd, scb); printf("Sending Sense\n"); } #endif scb->sg_count = 0; sg = ahd_sg_setup(ahd, scb, sg, ahd_get_sense_bufaddr(ahd, scb), ahd_get_sense_bufsize(ahd, scb), /*last*/TRUE); sc->opcode = REQUEST_SENSE; sc->byte2 = 0; if (tinfo->protocol_version <= SCSI_REV_2 && SCB_GET_LUN(scb) < 8) sc->byte2 = SCB_GET_LUN(scb) << 5; sc->unused[0] = 0; sc->unused[1] = 0; sc->length = ahd_get_sense_bufsize(ahd, scb); sc->control = 0; /* * We can't allow the target to disconnect. * This will be an untagged transaction and * having the target disconnect will make this * transaction indestinguishable from outstanding * tagged transactions. */ hscb->control = 0; /* * This request sense could be because the * the device lost power or in some other * way has lost our transfer negotiations. * Renegotiate if appropriate. Unit attention * errors will be reported before any data * phases occur. */ if (ahd_get_residual(scb) == ahd_get_transfer_length(scb)) { ahd_update_neg_request(ahd, &devinfo, tstate, targ_info, AHD_NEG_IF_NON_ASYNC); } if (tstate->auto_negotiate & devinfo.target_mask) { hscb->control |= MK_MESSAGE; scb->flags &= ~(SCB_NEGOTIATE|SCB_ABORT|SCB_DEVICE_RESET); scb->flags |= SCB_AUTO_NEGOTIATE; } hscb->cdb_len = sizeof(*sc); ahd_setup_data_scb(ahd, scb); scb->flags |= SCB_SENSE; ahd_queue_scb(ahd, scb); break; } case SCSI_STATUS_OK: printf("%s: Interrupted for staus of 0???\n", ahd_name(ahd)); /* FALLTHROUGH */ default: ahd_done(ahd, scb); break; } } static void ahd_handle_scb_status(struct ahd_softc *ahd, struct scb *scb) { if (scb->hscb->shared_data.istatus.scsi_status != 0) { ahd_handle_scsi_status(ahd, scb); } else { ahd_calc_residual(ahd, scb); ahd_done(ahd, scb); } } /* * Calculate the residual for a just completed SCB. */ static void ahd_calc_residual(struct ahd_softc *ahd, struct scb *scb) { struct hardware_scb *hscb; struct initiator_status *spkt; uint32_t sgptr; uint32_t resid_sgptr; uint32_t resid; /* * 5 cases. * 1) No residual. * SG_STATUS_VALID clear in sgptr. * 2) Transferless command * 3) Never performed any transfers. * sgptr has SG_FULL_RESID set. * 4) No residual but target did not * save data pointers after the * last transfer, so sgptr was * never updated. * 5) We have a partial residual. * Use residual_sgptr to determine * where we are. */ hscb = scb->hscb; sgptr = ahd_le32toh(hscb->sgptr); if ((sgptr & SG_STATUS_VALID) == 0) /* Case 1 */ return; sgptr &= ~SG_STATUS_VALID; if ((sgptr & SG_LIST_NULL) != 0) /* Case 2 */ return; /* * Residual fields are the same in both * target and initiator status packets, * so we can always use the initiator fields * regardless of the role for this SCB. */ spkt = &hscb->shared_data.istatus; resid_sgptr = ahd_le32toh(spkt->residual_sgptr); if ((sgptr & SG_FULL_RESID) != 0) { /* Case 3 */ resid = ahd_get_transfer_length(scb); } else if ((resid_sgptr & SG_LIST_NULL) != 0) { /* Case 4 */ return; } else if ((resid_sgptr & SG_OVERRUN_RESID) != 0) { ahd_print_path(ahd, scb); printf("data overrun detected Tag == 0x%x.\n", SCB_GET_TAG(scb)); ahd_freeze_devq(ahd, scb); ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR); ahd_freeze_scb(scb); return; } else if ((resid_sgptr & ~SG_PTR_MASK) != 0) { panic("Bogus resid sgptr value 0x%x\n", resid_sgptr); /* NOTREACHED */ } else { struct ahd_dma_seg *sg; /* * Remainder of the SG where the transfer * stopped. */ resid = ahd_le32toh(spkt->residual_datacnt) & AHD_SG_LEN_MASK; sg = ahd_sg_bus_to_virt(ahd, scb, resid_sgptr & SG_PTR_MASK); /* The residual sg_ptr always points to the next sg */ sg--; /* * Add up the contents of all residual * SG segments that are after the SG where * the transfer stopped. */ while ((ahd_le32toh(sg->len) & AHD_DMA_LAST_SEG) == 0) { sg++; resid += ahd_le32toh(sg->len) & AHD_SG_LEN_MASK; } } if ((scb->flags & SCB_SENSE) == 0) ahd_set_residual(scb, resid); else ahd_set_sense_residual(scb, resid); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_MISC) != 0) { ahd_print_path(ahd, scb); printf("Handled %sResidual of %d bytes\n", (scb->flags & SCB_SENSE) ? "Sense " : "", resid); } #endif } /******************************* Target Mode **********************************/ #ifdef AHD_TARGET_MODE /* * Add a target mode event to this lun's queue */ static void ahd_queue_lstate_event(struct ahd_softc *ahd, struct ahd_tmode_lstate *lstate, u_int initiator_id, u_int event_type, u_int event_arg) { struct ahd_tmode_event *event; int pending; xpt_freeze_devq(lstate->path, /*count*/1); if (lstate->event_w_idx >= lstate->event_r_idx) pending = lstate->event_w_idx - lstate->event_r_idx; else pending = AHD_TMODE_EVENT_BUFFER_SIZE + 1 - (lstate->event_r_idx - lstate->event_w_idx); if (event_type == EVENT_TYPE_BUS_RESET || event_type == MSG_BUS_DEV_RESET) { /* * Any earlier events are irrelevant, so reset our buffer. * This has the effect of allowing us to deal with reset * floods (an external device holding down the reset line) * without losing the event that is really interesting. */ lstate->event_r_idx = 0; lstate->event_w_idx = 0; xpt_release_devq(lstate->path, pending, /*runqueue*/FALSE); } if (pending == AHD_TMODE_EVENT_BUFFER_SIZE) { xpt_print_path(lstate->path); printf("immediate event %x:%x lost\n", lstate->event_buffer[lstate->event_r_idx].event_type, lstate->event_buffer[lstate->event_r_idx].event_arg); lstate->event_r_idx++; if (lstate->event_r_idx == AHD_TMODE_EVENT_BUFFER_SIZE) lstate->event_r_idx = 0; xpt_release_devq(lstate->path, /*count*/1, /*runqueue*/FALSE); } event = &lstate->event_buffer[lstate->event_w_idx]; event->initiator_id = initiator_id; event->event_type = event_type; event->event_arg = event_arg; lstate->event_w_idx++; if (lstate->event_w_idx == AHD_TMODE_EVENT_BUFFER_SIZE) lstate->event_w_idx = 0; } /* * Send any target mode events queued up waiting * for immediate notify resources. */ void ahd_send_lstate_events(struct ahd_softc *ahd, struct ahd_tmode_lstate *lstate) { struct ccb_hdr *ccbh; struct ccb_immed_notify *inot; while (lstate->event_r_idx != lstate->event_w_idx && (ccbh = SLIST_FIRST(&lstate->immed_notifies)) != NULL) { struct ahd_tmode_event *event; event = &lstate->event_buffer[lstate->event_r_idx]; SLIST_REMOVE_HEAD(&lstate->immed_notifies, sim_links.sle); inot = (struct ccb_immed_notify *)ccbh; switch (event->event_type) { case EVENT_TYPE_BUS_RESET: ccbh->status = CAM_SCSI_BUS_RESET|CAM_DEV_QFRZN; break; default: ccbh->status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN; inot->message_args[0] = event->event_type; inot->message_args[1] = event->event_arg; break; } inot->initiator_id = event->initiator_id; inot->sense_len = 0; xpt_done((union ccb *)inot); lstate->event_r_idx++; if (lstate->event_r_idx == AHD_TMODE_EVENT_BUFFER_SIZE) lstate->event_r_idx = 0; } } #endif /******************** Sequencer Program Patching/Download *********************/ #ifdef AHD_DUMP_SEQ void ahd_dumpseq(struct ahd_softc* ahd) { int i; int max_prog; max_prog = 2048; ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE|LOADRAM); ahd_outw(ahd, PRGMCNT, 0); for (i = 0; i < max_prog; i++) { uint8_t ins_bytes[4]; ahd_insb(ahd, SEQRAM, ins_bytes, 4); printf("0x%08x\n", ins_bytes[0] << 24 | ins_bytes[1] << 16 | ins_bytes[2] << 8 | ins_bytes[3]); } } #endif static void ahd_loadseq(struct ahd_softc *ahd) { struct cs cs_table[num_critical_sections]; u_int begin_set[num_critical_sections]; u_int end_set[num_critical_sections]; struct patch *cur_patch; u_int cs_count; u_int cur_cs; u_int i; int downloaded; u_int skip_addr; u_int sg_prefetch_cnt; u_int sg_prefetch_cnt_limit; u_int sg_prefetch_align; u_int sg_size; u_int cacheline_mask; uint8_t download_consts[DOWNLOAD_CONST_COUNT]; if (bootverbose) printf("%s: Downloading Sequencer Program...", ahd_name(ahd)); #if DOWNLOAD_CONST_COUNT != 8 #error "Download Const Mismatch" #endif /* * Start out with 0 critical sections * that apply to this firmware load. */ cs_count = 0; cur_cs = 0; memset(begin_set, 0, sizeof(begin_set)); memset(end_set, 0, sizeof(end_set)); /* * Setup downloadable constant table. * * The computation for the S/G prefetch variables is * a bit complicated. We would like to always fetch * in terms of cachelined sized increments. However, * if the cacheline is not an even multiple of the * SG element size or is larger than our SG RAM, using * just the cache size might leave us with only a portion * of an SG element at the tail of a prefetch. If the * cacheline is larger than our S/G prefetch buffer less * the size of an SG element, we may round down to a cacheline * that doesn't contain any or all of the S/G of interest * within the bounds of our S/G ram. Provide variables to * the sequencer that will allow it to handle these edge * cases. */ /* Start by aligning to the nearest cacheline. */ sg_prefetch_align = ahd->pci_cachesize; if (sg_prefetch_align == 0) sg_prefetch_align = 8; /* Round down to the nearest power of 2. */ while (powerof2(sg_prefetch_align) == 0) sg_prefetch_align--; cacheline_mask = sg_prefetch_align - 1; /* * If the cacheline boundary is greater than half our prefetch RAM * we risk not being able to fetch even a single complete S/G * segment if we align to that boundary. */ if (sg_prefetch_align > CCSGADDR_MAX/2) sg_prefetch_align = CCSGADDR_MAX/2; /* Start by fetching a single cacheline. */ sg_prefetch_cnt = sg_prefetch_align; /* * Increment the prefetch count by cachelines until * at least one S/G element will fit. */ sg_size = sizeof(struct ahd_dma_seg); if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) sg_size = sizeof(struct ahd_dma64_seg); while (sg_prefetch_cnt < sg_size) sg_prefetch_cnt += sg_prefetch_align; /* * If the cacheline is not an even multiple of * the S/G size, we may only get a partial S/G when * we align. Add a cacheline if this is the case. */ if ((sg_prefetch_align % sg_size) != 0 && (sg_prefetch_cnt < CCSGADDR_MAX)) sg_prefetch_cnt += sg_prefetch_align; /* * Lastly, compute a value that the sequencer can use * to determine if the remainder of the CCSGRAM buffer * has a full S/G element in it. */ sg_prefetch_cnt_limit = -(sg_prefetch_cnt - sg_size + 1); download_consts[SG_PREFETCH_CNT] = sg_prefetch_cnt; download_consts[SG_PREFETCH_CNT_LIMIT] = sg_prefetch_cnt_limit; download_consts[SG_PREFETCH_ALIGN_MASK] = ~(sg_prefetch_align - 1); download_consts[SG_PREFETCH_ADDR_MASK] = (sg_prefetch_align - 1); download_consts[SG_SIZEOF] = sg_size; download_consts[PKT_OVERRUN_BUFOFFSET] = (ahd->overrun_buf - (uint8_t *)ahd->qoutfifo) / 256; download_consts[SCB_TRANSFER_SIZE] = SCB_TRANSFER_SIZE_1BYTE_LUN; download_consts[CACHELINE_MASK] = cacheline_mask; cur_patch = patches; downloaded = 0; skip_addr = 0; ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE|LOADRAM); ahd_outw(ahd, PRGMCNT, 0); for (i = 0; i < sizeof(seqprog)/4; i++) { if (ahd_check_patch(ahd, &cur_patch, i, &skip_addr) == 0) { /* * Don't download this instruction as it * is in a patch that was removed. */ continue; } /* * Move through the CS table until we find a CS * that might apply to this instruction. */ for (; cur_cs < num_critical_sections; cur_cs++) { if (critical_sections[cur_cs].end <= i) { if (begin_set[cs_count] == TRUE && end_set[cs_count] == FALSE) { cs_table[cs_count].end = downloaded; end_set[cs_count] = TRUE; cs_count++; } continue; } if (critical_sections[cur_cs].begin <= i && begin_set[cs_count] == FALSE) { cs_table[cs_count].begin = downloaded; begin_set[cs_count] = TRUE; } break; } ahd_download_instr(ahd, i, download_consts); downloaded++; } ahd->num_critical_sections = cs_count; if (cs_count != 0) { cs_count *= sizeof(struct cs); ahd->critical_sections = malloc(cs_count, M_DEVBUF, M_NOWAIT); if (ahd->critical_sections == NULL) panic("ahd_loadseq: Could not malloc"); memcpy(ahd->critical_sections, cs_table, cs_count); } ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE); if (bootverbose) { printf(" %d instructions downloaded\n", downloaded); printf("%s: Features 0x%x, Bugs 0x%x, Flags 0x%x\n", ahd_name(ahd), ahd->features, ahd->bugs, ahd->flags); } } static int ahd_check_patch(struct ahd_softc *ahd, struct patch **start_patch, u_int start_instr, u_int *skip_addr) { struct patch *cur_patch; struct patch *last_patch; u_int num_patches; num_patches = ARRAY_SIZE(patches); last_patch = &patches[num_patches]; cur_patch = *start_patch; while (cur_patch < last_patch && start_instr == cur_patch->begin) { if (cur_patch->patch_func(ahd) == 0) { /* Start rejecting code */ *skip_addr = start_instr + cur_patch->skip_instr; cur_patch += cur_patch->skip_patch; } else { /* Accepted this patch. Advance to the next * one and wait for our intruction pointer to * hit this point. */ cur_patch++; } } *start_patch = cur_patch; if (start_instr < *skip_addr) /* Still skipping */ return (0); return (1); } static u_int ahd_resolve_seqaddr(struct ahd_softc *ahd, u_int address) { struct patch *cur_patch; int address_offset; u_int skip_addr; u_int i; address_offset = 0; cur_patch = patches; skip_addr = 0; for (i = 0; i < address;) { ahd_check_patch(ahd, &cur_patch, i, &skip_addr); if (skip_addr > i) { int end_addr; end_addr = min(address, skip_addr); address_offset += end_addr - i; i = skip_addr; } else { i++; } } return (address - address_offset); } static void ahd_download_instr(struct ahd_softc *ahd, u_int instrptr, uint8_t *dconsts) { union ins_formats instr; struct ins_format1 *fmt1_ins; struct ins_format3 *fmt3_ins; u_int opcode; /* * The firmware is always compiled into a little endian format. */ instr.integer = ahd_le32toh(*(uint32_t*)&seqprog[instrptr * 4]); fmt1_ins = &instr.format1; fmt3_ins = NULL; /* Pull the opcode */ opcode = instr.format1.opcode; switch (opcode) { case AIC_OP_JMP: case AIC_OP_JC: case AIC_OP_JNC: case AIC_OP_CALL: case AIC_OP_JNE: case AIC_OP_JNZ: case AIC_OP_JE: case AIC_OP_JZ: { fmt3_ins = &instr.format3; fmt3_ins->address = ahd_resolve_seqaddr(ahd, fmt3_ins->address); /* FALLTHROUGH */ } case AIC_OP_OR: case AIC_OP_AND: case AIC_OP_XOR: case AIC_OP_ADD: case AIC_OP_ADC: case AIC_OP_BMOV: if (fmt1_ins->parity != 0) { fmt1_ins->immediate = dconsts[fmt1_ins->immediate]; } fmt1_ins->parity = 0; /* FALLTHROUGH */ case AIC_OP_ROL: { int i, count; /* Calculate odd parity for the instruction */ for (i = 0, count = 0; i < 31; i++) { uint32_t mask; mask = 0x01 << i; if ((instr.integer & mask) != 0) count++; } if ((count & 0x01) == 0) instr.format1.parity = 1; /* The sequencer is a little endian cpu */ instr.integer = ahd_htole32(instr.integer); ahd_outsb(ahd, SEQRAM, instr.bytes, 4); break; } default: panic("Unknown opcode encountered in seq program"); break; } } static int ahd_probe_stack_size(struct ahd_softc *ahd) { int last_probe; last_probe = 0; while (1) { int i; /* * We avoid using 0 as a pattern to avoid * confusion if the stack implementation * "back-fills" with zeros when "poping' * entries. */ for (i = 1; i <= last_probe+1; i++) { ahd_outb(ahd, STACK, i & 0xFF); ahd_outb(ahd, STACK, (i >> 8) & 0xFF); } /* Verify */ for (i = last_probe+1; i > 0; i--) { u_int stack_entry; stack_entry = ahd_inb(ahd, STACK) |(ahd_inb(ahd, STACK) << 8); if (stack_entry != i) goto sized; } last_probe++; } sized: return (last_probe); } int ahd_print_register(ahd_reg_parse_entry_t *table, u_int num_entries, const char *name, u_int address, u_int value, u_int *cur_column, u_int wrap_point) { int printed; u_int printed_mask; if (cur_column != NULL && *cur_column >= wrap_point) { printf("\n"); *cur_column = 0; } printed = printf("%s[0x%x]", name, value); if (table == NULL) { printed += printf(" "); *cur_column += printed; return (printed); } printed_mask = 0; while (printed_mask != 0xFF) { int entry; for (entry = 0; entry < num_entries; entry++) { if (((value & table[entry].mask) != table[entry].value) || ((printed_mask & table[entry].mask) == table[entry].mask)) continue; printed += printf("%s%s", printed_mask == 0 ? ":(" : "|", table[entry].name); printed_mask |= table[entry].mask; break; } if (entry >= num_entries) break; } if (printed_mask != 0) printed += printf(") "); else printed += printf(" "); if (cur_column != NULL) *cur_column += printed; return (printed); } void ahd_dump_card_state(struct ahd_softc *ahd) { struct scb *scb; ahd_mode_state saved_modes; u_int dffstat; int paused; u_int scb_index; u_int saved_scb_index; u_int cur_col; int i; if (ahd_is_paused(ahd)) { paused = 1; } else { paused = 0; ahd_pause(ahd); } saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); printf(">>>>>>>>>>>>>>>>>> Dump Card State Begins <<<<<<<<<<<<<<<<<\n" "%s: Dumping Card State at program address 0x%x Mode 0x%x\n", ahd_name(ahd), ahd_inw(ahd, CURADDR), ahd_build_mode_state(ahd, ahd->saved_src_mode, ahd->saved_dst_mode)); if (paused) printf("Card was paused\n"); if (ahd_check_cmdcmpltqueues(ahd)) printf("Completions are pending\n"); /* * Mode independent registers. */ cur_col = 0; ahd_intstat_print(ahd_inb(ahd, INTSTAT), &cur_col, 50); ahd_seloid_print(ahd_inb(ahd, SELOID), &cur_col, 50); ahd_selid_print(ahd_inb(ahd, SELID), &cur_col, 50); ahd_hs_mailbox_print(ahd_inb(ahd, LOCAL_HS_MAILBOX), &cur_col, 50); ahd_intctl_print(ahd_inb(ahd, INTCTL), &cur_col, 50); ahd_seqintstat_print(ahd_inb(ahd, SEQINTSTAT), &cur_col, 50); ahd_saved_mode_print(ahd_inb(ahd, SAVED_MODE), &cur_col, 50); ahd_dffstat_print(ahd_inb(ahd, DFFSTAT), &cur_col, 50); ahd_scsisigi_print(ahd_inb(ahd, SCSISIGI), &cur_col, 50); ahd_scsiphase_print(ahd_inb(ahd, SCSIPHASE), &cur_col, 50); ahd_scsibus_print(ahd_inb(ahd, SCSIBUS), &cur_col, 50); ahd_lastphase_print(ahd_inb(ahd, LASTPHASE), &cur_col, 50); ahd_scsiseq0_print(ahd_inb(ahd, SCSISEQ0), &cur_col, 50); ahd_scsiseq1_print(ahd_inb(ahd, SCSISEQ1), &cur_col, 50); ahd_seqctl0_print(ahd_inb(ahd, SEQCTL0), &cur_col, 50); ahd_seqintctl_print(ahd_inb(ahd, SEQINTCTL), &cur_col, 50); ahd_seq_flags_print(ahd_inb(ahd, SEQ_FLAGS), &cur_col, 50); ahd_seq_flags2_print(ahd_inb(ahd, SEQ_FLAGS2), &cur_col, 50); ahd_qfreeze_count_print(ahd_inw(ahd, QFREEZE_COUNT), &cur_col, 50); ahd_kernel_qfreeze_count_print(ahd_inw(ahd, KERNEL_QFREEZE_COUNT), &cur_col, 50); ahd_mk_message_scb_print(ahd_inw(ahd, MK_MESSAGE_SCB), &cur_col, 50); ahd_mk_message_scsiid_print(ahd_inb(ahd, MK_MESSAGE_SCSIID), &cur_col, 50); ahd_sstat0_print(ahd_inb(ahd, SSTAT0), &cur_col, 50); ahd_sstat1_print(ahd_inb(ahd, SSTAT1), &cur_col, 50); ahd_sstat2_print(ahd_inb(ahd, SSTAT2), &cur_col, 50); ahd_sstat3_print(ahd_inb(ahd, SSTAT3), &cur_col, 50); ahd_perrdiag_print(ahd_inb(ahd, PERRDIAG), &cur_col, 50); ahd_simode1_print(ahd_inb(ahd, SIMODE1), &cur_col, 50); ahd_lqistat0_print(ahd_inb(ahd, LQISTAT0), &cur_col, 50); ahd_lqistat1_print(ahd_inb(ahd, LQISTAT1), &cur_col, 50); ahd_lqistat2_print(ahd_inb(ahd, LQISTAT2), &cur_col, 50); ahd_lqostat0_print(ahd_inb(ahd, LQOSTAT0), &cur_col, 50); ahd_lqostat1_print(ahd_inb(ahd, LQOSTAT1), &cur_col, 50); ahd_lqostat2_print(ahd_inb(ahd, LQOSTAT2), &cur_col, 50); printf("\n"); printf("\nSCB Count = %d CMDS_PENDING = %d LASTSCB 0x%x " "CURRSCB 0x%x NEXTSCB 0x%x\n", ahd->scb_data.numscbs, ahd_inw(ahd, CMDS_PENDING), ahd_inw(ahd, LASTSCB), ahd_inw(ahd, CURRSCB), ahd_inw(ahd, NEXTSCB)); cur_col = 0; /* QINFIFO */ ahd_search_qinfifo(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS, CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN, /*status*/0, SEARCH_PRINT); saved_scb_index = ahd_get_scbptr(ahd); printf("Pending list:"); i = 0; LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) { if (i++ > AHD_SCB_MAX) break; cur_col = printf("\n%3d FIFO_USE[0x%x] ", SCB_GET_TAG(scb), ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT)); ahd_set_scbptr(ahd, SCB_GET_TAG(scb)); ahd_scb_control_print(ahd_inb_scbram(ahd, SCB_CONTROL), &cur_col, 60); ahd_scb_scsiid_print(ahd_inb_scbram(ahd, SCB_SCSIID), &cur_col, 60); } printf("\nTotal %d\n", i); printf("Kernel Free SCB list: "); i = 0; TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) { struct scb *list_scb; list_scb = scb; do { printf("%d ", SCB_GET_TAG(list_scb)); list_scb = LIST_NEXT(list_scb, collision_links); } while (list_scb && i++ < AHD_SCB_MAX); } LIST_FOREACH(scb, &ahd->scb_data.any_dev_free_scb_list, links.le) { if (i++ > AHD_SCB_MAX) break; printf("%d ", SCB_GET_TAG(scb)); } printf("\n"); printf("Sequencer Complete DMA-inprog list: "); scb_index = ahd_inw(ahd, COMPLETE_SCB_DMAINPROG_HEAD); i = 0; while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) { ahd_set_scbptr(ahd, scb_index); printf("%d ", scb_index); scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE); } printf("\n"); printf("Sequencer Complete list: "); scb_index = ahd_inw(ahd, COMPLETE_SCB_HEAD); i = 0; while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) { ahd_set_scbptr(ahd, scb_index); printf("%d ", scb_index); scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE); } printf("\n"); printf("Sequencer DMA-Up and Complete list: "); scb_index = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD); i = 0; while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) { ahd_set_scbptr(ahd, scb_index); printf("%d ", scb_index); scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE); } printf("\n"); printf("Sequencer On QFreeze and Complete list: "); scb_index = ahd_inw(ahd, COMPLETE_ON_QFREEZE_HEAD); i = 0; while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) { ahd_set_scbptr(ahd, scb_index); printf("%d ", scb_index); scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE); } printf("\n"); ahd_set_scbptr(ahd, saved_scb_index); dffstat = ahd_inb(ahd, DFFSTAT); for (i = 0; i < 2; i++) { #ifdef AHD_DEBUG struct scb *fifo_scb; #endif u_int fifo_scbptr; ahd_set_modes(ahd, AHD_MODE_DFF0 + i, AHD_MODE_DFF0 + i); fifo_scbptr = ahd_get_scbptr(ahd); printf("\n\n%s: FIFO%d %s, LONGJMP == 0x%x, SCB 0x%x\n", ahd_name(ahd), i, (dffstat & (FIFO0FREE << i)) ? "Free" : "Active", ahd_inw(ahd, LONGJMP_ADDR), fifo_scbptr); cur_col = 0; ahd_seqimode_print(ahd_inb(ahd, SEQIMODE), &cur_col, 50); ahd_seqintsrc_print(ahd_inb(ahd, SEQINTSRC), &cur_col, 50); ahd_dfcntrl_print(ahd_inb(ahd, DFCNTRL), &cur_col, 50); ahd_dfstatus_print(ahd_inb(ahd, DFSTATUS), &cur_col, 50); ahd_sg_cache_shadow_print(ahd_inb(ahd, SG_CACHE_SHADOW), &cur_col, 50); ahd_sg_state_print(ahd_inb(ahd, SG_STATE), &cur_col, 50); ahd_dffsxfrctl_print(ahd_inb(ahd, DFFSXFRCTL), &cur_col, 50); ahd_soffcnt_print(ahd_inb(ahd, SOFFCNT), &cur_col, 50); ahd_mdffstat_print(ahd_inb(ahd, MDFFSTAT), &cur_col, 50); if (cur_col > 50) { printf("\n"); cur_col = 0; } cur_col += printf("SHADDR = 0x%x%x, SHCNT = 0x%x ", ahd_inl(ahd, SHADDR+4), ahd_inl(ahd, SHADDR), (ahd_inb(ahd, SHCNT) | (ahd_inb(ahd, SHCNT + 1) << 8) | (ahd_inb(ahd, SHCNT + 2) << 16))); if (cur_col > 50) { printf("\n"); cur_col = 0; } cur_col += printf("HADDR = 0x%x%x, HCNT = 0x%x ", ahd_inl(ahd, HADDR+4), ahd_inl(ahd, HADDR), (ahd_inb(ahd, HCNT) | (ahd_inb(ahd, HCNT + 1) << 8) | (ahd_inb(ahd, HCNT + 2) << 16))); ahd_ccsgctl_print(ahd_inb(ahd, CCSGCTL), &cur_col, 50); #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_SG) != 0) { fifo_scb = ahd_lookup_scb(ahd, fifo_scbptr); if (fifo_scb != NULL) ahd_dump_sglist(fifo_scb); } #endif } printf("\nLQIN: "); for (i = 0; i < 20; i++) printf("0x%x ", ahd_inb(ahd, LQIN + i)); printf("\n"); ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG); printf("%s: LQISTATE = 0x%x, LQOSTATE = 0x%x, OPTIONMODE = 0x%x\n", ahd_name(ahd), ahd_inb(ahd, LQISTATE), ahd_inb(ahd, LQOSTATE), ahd_inb(ahd, OPTIONMODE)); printf("%s: OS_SPACE_CNT = 0x%x MAXCMDCNT = 0x%x\n", ahd_name(ahd), ahd_inb(ahd, OS_SPACE_CNT), ahd_inb(ahd, MAXCMDCNT)); printf("%s: SAVED_SCSIID = 0x%x SAVED_LUN = 0x%x\n", ahd_name(ahd), ahd_inb(ahd, SAVED_SCSIID), ahd_inb(ahd, SAVED_LUN)); ahd_simode0_print(ahd_inb(ahd, SIMODE0), &cur_col, 50); printf("\n"); ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN); cur_col = 0; ahd_ccscbctl_print(ahd_inb(ahd, CCSCBCTL), &cur_col, 50); printf("\n"); ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode); printf("%s: REG0 == 0x%x, SINDEX = 0x%x, DINDEX = 0x%x\n", ahd_name(ahd), ahd_inw(ahd, REG0), ahd_inw(ahd, SINDEX), ahd_inw(ahd, DINDEX)); printf("%s: SCBPTR == 0x%x, SCB_NEXT == 0x%x, SCB_NEXT2 == 0x%x\n", ahd_name(ahd), ahd_get_scbptr(ahd), ahd_inw_scbram(ahd, SCB_NEXT), ahd_inw_scbram(ahd, SCB_NEXT2)); printf("CDB %x %x %x %x %x %x\n", ahd_inb_scbram(ahd, SCB_CDB_STORE), ahd_inb_scbram(ahd, SCB_CDB_STORE+1), ahd_inb_scbram(ahd, SCB_CDB_STORE+2), ahd_inb_scbram(ahd, SCB_CDB_STORE+3), ahd_inb_scbram(ahd, SCB_CDB_STORE+4), ahd_inb_scbram(ahd, SCB_CDB_STORE+5)); printf("STACK:"); for (i = 0; i < ahd->stack_size; i++) { ahd->saved_stack[i] = ahd_inb(ahd, STACK)|(ahd_inb(ahd, STACK) << 8); printf(" 0x%x", ahd->saved_stack[i]); } for (i = ahd->stack_size-1; i >= 0; i--) { ahd_outb(ahd, STACK, ahd->saved_stack[i] & 0xFF); ahd_outb(ahd, STACK, (ahd->saved_stack[i] >> 8) & 0xFF); } printf("\n<<<<<<<<<<<<<<<<< Dump Card State Ends >>>>>>>>>>>>>>>>>>\n"); ahd_restore_modes(ahd, saved_modes); if (paused == 0) ahd_unpause(ahd); } #if 0 void ahd_dump_scbs(struct ahd_softc *ahd) { ahd_mode_state saved_modes; u_int saved_scb_index; int i; saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); saved_scb_index = ahd_get_scbptr(ahd); for (i = 0; i < AHD_SCB_MAX; i++) { ahd_set_scbptr(ahd, i); printf("%3d", i); printf("(CTRL 0x%x ID 0x%x N 0x%x N2 0x%x SG 0x%x, RSG 0x%x)\n", ahd_inb_scbram(ahd, SCB_CONTROL), ahd_inb_scbram(ahd, SCB_SCSIID), ahd_inw_scbram(ahd, SCB_NEXT), ahd_inw_scbram(ahd, SCB_NEXT2), ahd_inl_scbram(ahd, SCB_SGPTR), ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR)); } printf("\n"); ahd_set_scbptr(ahd, saved_scb_index); ahd_restore_modes(ahd, saved_modes); } #endif /* 0 */ /**************************** Flexport Logic **********************************/ /* * Read count 16bit words from 16bit word address start_addr from the * SEEPROM attached to the controller, into buf, using the controller's * SEEPROM reading state machine. Optionally treat the data as a byte * stream in terms of byte order. */ int ahd_read_seeprom(struct ahd_softc *ahd, uint16_t *buf, u_int start_addr, u_int count, int bytestream) { u_int cur_addr; u_int end_addr; int error; /* * If we never make it through the loop even once, * we were passed invalid arguments. */ error = EINVAL; AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); end_addr = start_addr + count; for (cur_addr = start_addr; cur_addr < end_addr; cur_addr++) { ahd_outb(ahd, SEEADR, cur_addr); ahd_outb(ahd, SEECTL, SEEOP_READ | SEESTART); error = ahd_wait_seeprom(ahd); if (error) break; if (bytestream != 0) { uint8_t *bytestream_ptr; bytestream_ptr = (uint8_t *)buf; *bytestream_ptr++ = ahd_inb(ahd, SEEDAT); *bytestream_ptr = ahd_inb(ahd, SEEDAT+1); } else { /* * ahd_inw() already handles machine byte order. */ *buf = ahd_inw(ahd, SEEDAT); } buf++; } return (error); } /* * Write count 16bit words from buf, into SEEPROM attache to the * controller starting at 16bit word address start_addr, using the * controller's SEEPROM writing state machine. */ int ahd_write_seeprom(struct ahd_softc *ahd, uint16_t *buf, u_int start_addr, u_int count) { u_int cur_addr; u_int end_addr; int error; int retval; AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); error = ENOENT; /* Place the chip into write-enable mode */ ahd_outb(ahd, SEEADR, SEEOP_EWEN_ADDR); ahd_outb(ahd, SEECTL, SEEOP_EWEN | SEESTART); error = ahd_wait_seeprom(ahd); if (error) return (error); /* * Write the data. If we don't get throught the loop at * least once, the arguments were invalid. */ retval = EINVAL; end_addr = start_addr + count; for (cur_addr = start_addr; cur_addr < end_addr; cur_addr++) { ahd_outw(ahd, SEEDAT, *buf++); ahd_outb(ahd, SEEADR, cur_addr); ahd_outb(ahd, SEECTL, SEEOP_WRITE | SEESTART); retval = ahd_wait_seeprom(ahd); if (retval) break; } /* * Disable writes. */ ahd_outb(ahd, SEEADR, SEEOP_EWDS_ADDR); ahd_outb(ahd, SEECTL, SEEOP_EWDS | SEESTART); error = ahd_wait_seeprom(ahd); if (error) return (error); return (retval); } /* * Wait ~100us for the serial eeprom to satisfy our request. */ static int ahd_wait_seeprom(struct ahd_softc *ahd) { int cnt; cnt = 5000; while ((ahd_inb(ahd, SEESTAT) & (SEEARBACK|SEEBUSY)) != 0 && --cnt) ahd_delay(5); if (cnt == 0) return (ETIMEDOUT); return (0); } /* * Validate the two checksums in the per_channel * vital product data struct. */ static int ahd_verify_vpd_cksum(struct vpd_config *vpd) { int i; int maxaddr; uint32_t checksum; uint8_t *vpdarray; vpdarray = (uint8_t *)vpd; maxaddr = offsetof(struct vpd_config, vpd_checksum); checksum = 0; for (i = offsetof(struct vpd_config, resource_type); i < maxaddr; i++) checksum = checksum + vpdarray[i]; if (checksum == 0 || (-checksum & 0xFF) != vpd->vpd_checksum) return (0); checksum = 0; maxaddr = offsetof(struct vpd_config, checksum); for (i = offsetof(struct vpd_config, default_target_flags); i < maxaddr; i++) checksum = checksum + vpdarray[i]; if (checksum == 0 || (-checksum & 0xFF) != vpd->checksum) return (0); return (1); } int ahd_verify_cksum(struct seeprom_config *sc) { int i; int maxaddr; uint32_t checksum; uint16_t *scarray; maxaddr = (sizeof(*sc)/2) - 1; checksum = 0; scarray = (uint16_t *)sc; for (i = 0; i < maxaddr; i++) checksum = checksum + scarray[i]; if (checksum == 0 || (checksum & 0xFFFF) != sc->checksum) { return (0); } else { return (1); } } int ahd_acquire_seeprom(struct ahd_softc *ahd) { /* * We should be able to determine the SEEPROM type * from the flexport logic, but unfortunately not * all implementations have this logic and there is * no programatic method for determining if the logic * is present. */ return (1); #if 0 uint8_t seetype; int error; error = ahd_read_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, &seetype); if (error != 0 || ((seetype & FLX_ROMSTAT_SEECFG) == FLX_ROMSTAT_SEE_NONE)) return (0); return (1); #endif } void ahd_release_seeprom(struct ahd_softc *ahd) { /* Currently a no-op */ } /* * Wait at most 2 seconds for flexport arbitration to succeed. */ static int ahd_wait_flexport(struct ahd_softc *ahd) { int cnt; AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); cnt = 1000000 * 2 / 5; while ((ahd_inb(ahd, BRDCTL) & FLXARBACK) == 0 && --cnt) ahd_delay(5); if (cnt == 0) return (ETIMEDOUT); return (0); } int ahd_write_flexport(struct ahd_softc *ahd, u_int addr, u_int value) { int error; AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); if (addr > 7) panic("ahd_write_flexport: address out of range"); ahd_outb(ahd, BRDCTL, BRDEN|(addr << 3)); error = ahd_wait_flexport(ahd); if (error != 0) return (error); ahd_outb(ahd, BRDDAT, value); ahd_flush_device_writes(ahd); ahd_outb(ahd, BRDCTL, BRDSTB|BRDEN|(addr << 3)); ahd_flush_device_writes(ahd); ahd_outb(ahd, BRDCTL, BRDEN|(addr << 3)); ahd_flush_device_writes(ahd); ahd_outb(ahd, BRDCTL, 0); ahd_flush_device_writes(ahd); return (0); } int ahd_read_flexport(struct ahd_softc *ahd, u_int addr, uint8_t *value) { int error; AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK); if (addr > 7) panic("ahd_read_flexport: address out of range"); ahd_outb(ahd, BRDCTL, BRDRW|BRDEN|(addr << 3)); error = ahd_wait_flexport(ahd); if (error != 0) return (error); *value = ahd_inb(ahd, BRDDAT); ahd_outb(ahd, BRDCTL, 0); ahd_flush_device_writes(ahd); return (0); } /************************* Target Mode ****************************************/ #ifdef AHD_TARGET_MODE cam_status ahd_find_tmode_devs(struct ahd_softc *ahd, struct cam_sim *sim, union ccb *ccb, struct ahd_tmode_tstate **tstate, struct ahd_tmode_lstate **lstate, int notfound_failure) { if ((ahd->features & AHD_TARGETMODE) == 0) return (CAM_REQ_INVALID); /* * Handle the 'black hole' device that sucks up * requests to unattached luns on enabled targets. */ if (ccb->ccb_h.target_id == CAM_TARGET_WILDCARD && ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) { *tstate = NULL; *lstate = ahd->black_hole; } else { u_int max_id; max_id = (ahd->features & AHD_WIDE) ? 16 : 8; if (ccb->ccb_h.target_id >= max_id) return (CAM_TID_INVALID); if (ccb->ccb_h.target_lun >= AHD_NUM_LUNS) return (CAM_LUN_INVALID); *tstate = ahd->enabled_targets[ccb->ccb_h.target_id]; *lstate = NULL; if (*tstate != NULL) *lstate = (*tstate)->enabled_luns[ccb->ccb_h.target_lun]; } if (notfound_failure != 0 && *lstate == NULL) return (CAM_PATH_INVALID); return (CAM_REQ_CMP); } void ahd_handle_en_lun(struct ahd_softc *ahd, struct cam_sim *sim, union ccb *ccb) { #if NOT_YET struct ahd_tmode_tstate *tstate; struct ahd_tmode_lstate *lstate; struct ccb_en_lun *cel; cam_status status; u_int target; u_int lun; u_int target_mask; u_long s; char channel; status = ahd_find_tmode_devs(ahd, sim, ccb, &tstate, &lstate, /*notfound_failure*/FALSE); if (status != CAM_REQ_CMP) { ccb->ccb_h.status = status; return; } if ((ahd->features & AHD_MULTIROLE) != 0) { u_int our_id; our_id = ahd->our_id; if (ccb->ccb_h.target_id != our_id) { if ((ahd->features & AHD_MULTI_TID) != 0 && (ahd->flags & AHD_INITIATORROLE) != 0) { /* * Only allow additional targets if * the initiator role is disabled. * The hardware cannot handle a re-select-in * on the initiator id during a re-select-out * on a different target id. */ status = CAM_TID_INVALID; } else if ((ahd->flags & AHD_INITIATORROLE) != 0 || ahd->enabled_luns > 0) { /* * Only allow our target id to change * if the initiator role is not configured * and there are no enabled luns which * are attached to the currently registered * scsi id. */ status = CAM_TID_INVALID; } } } if (status != CAM_REQ_CMP) { ccb->ccb_h.status = status; return; } /* * We now have an id that is valid. * If we aren't in target mode, switch modes. */ if ((ahd->flags & AHD_TARGETROLE) == 0 && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) { u_long s; printf("Configuring Target Mode\n"); ahd_lock(ahd, &s); if (LIST_FIRST(&ahd->pending_scbs) != NULL) { ccb->ccb_h.status = CAM_BUSY; ahd_unlock(ahd, &s); return; } ahd->flags |= AHD_TARGETROLE; if ((ahd->features & AHD_MULTIROLE) == 0) ahd->flags &= ~AHD_INITIATORROLE; ahd_pause(ahd); ahd_loadseq(ahd); ahd_restart(ahd); ahd_unlock(ahd, &s); } cel = &ccb->cel; target = ccb->ccb_h.target_id; lun = ccb->ccb_h.target_lun; channel = SIM_CHANNEL(ahd, sim); target_mask = 0x01 << target; if (channel == 'B') target_mask <<= 8; if (cel->enable != 0) { u_int scsiseq1; /* Are we already enabled?? */ if (lstate != NULL) { xpt_print_path(ccb->ccb_h.path); printf("Lun already enabled\n"); ccb->ccb_h.status = CAM_LUN_ALRDY_ENA; return; } if (cel->grp6_len != 0 || cel->grp7_len != 0) { /* * Don't (yet?) support vendor * specific commands. */ ccb->ccb_h.status = CAM_REQ_INVALID; printf("Non-zero Group Codes\n"); return; } /* * Seems to be okay. * Setup our data structures. */ if (target != CAM_TARGET_WILDCARD && tstate == NULL) { tstate = ahd_alloc_tstate(ahd, target, channel); if (tstate == NULL) { xpt_print_path(ccb->ccb_h.path); printf("Couldn't allocate tstate\n"); ccb->ccb_h.status = CAM_RESRC_UNAVAIL; return; } } lstate = malloc(sizeof(*lstate), M_DEVBUF, M_NOWAIT); if (lstate == NULL) { xpt_print_path(ccb->ccb_h.path); printf("Couldn't allocate lstate\n"); ccb->ccb_h.status = CAM_RESRC_UNAVAIL; return; } memset(lstate, 0, sizeof(*lstate)); status = xpt_create_path(&lstate->path, /*periph*/NULL, xpt_path_path_id(ccb->ccb_h.path), xpt_path_target_id(ccb->ccb_h.path), xpt_path_lun_id(ccb->ccb_h.path)); if (status != CAM_REQ_CMP) { free(lstate, M_DEVBUF); xpt_print_path(ccb->ccb_h.path); printf("Couldn't allocate path\n"); ccb->ccb_h.status = CAM_RESRC_UNAVAIL; return; } SLIST_INIT(&lstate->accept_tios); SLIST_INIT(&lstate->immed_notifies); ahd_lock(ahd, &s); ahd_pause(ahd); if (target != CAM_TARGET_WILDCARD) { tstate->enabled_luns[lun] = lstate; ahd->enabled_luns++; if ((ahd->features & AHD_MULTI_TID) != 0) { u_int targid_mask; targid_mask = ahd_inw(ahd, TARGID); targid_mask |= target_mask; ahd_outw(ahd, TARGID, targid_mask); ahd_update_scsiid(ahd, targid_mask); } else { u_int our_id; char channel; channel = SIM_CHANNEL(ahd, sim); our_id = SIM_SCSI_ID(ahd, sim); /* * This can only happen if selections * are not enabled */ if (target != our_id) { u_int sblkctl; char cur_channel; int swap; sblkctl = ahd_inb(ahd, SBLKCTL); cur_channel = (sblkctl & SELBUSB) ? 'B' : 'A'; if ((ahd->features & AHD_TWIN) == 0) cur_channel = 'A'; swap = cur_channel != channel; ahd->our_id = target; if (swap) ahd_outb(ahd, SBLKCTL, sblkctl ^ SELBUSB); ahd_outb(ahd, SCSIID, target); if (swap) ahd_outb(ahd, SBLKCTL, sblkctl); } } } else ahd->black_hole = lstate; /* Allow select-in operations */ if (ahd->black_hole != NULL && ahd->enabled_luns > 0) { scsiseq1 = ahd_inb(ahd, SCSISEQ_TEMPLATE); scsiseq1 |= ENSELI; ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq1); scsiseq1 = ahd_inb(ahd, SCSISEQ1); scsiseq1 |= ENSELI; ahd_outb(ahd, SCSISEQ1, scsiseq1); } ahd_unpause(ahd); ahd_unlock(ahd, &s); ccb->ccb_h.status = CAM_REQ_CMP; xpt_print_path(ccb->ccb_h.path); printf("Lun now enabled for target mode\n"); } else { struct scb *scb; int i, empty; if (lstate == NULL) { ccb->ccb_h.status = CAM_LUN_INVALID; return; } ahd_lock(ahd, &s); ccb->ccb_h.status = CAM_REQ_CMP; LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) { struct ccb_hdr *ccbh; ccbh = &scb->io_ctx->ccb_h; if (ccbh->func_code == XPT_CONT_TARGET_IO && !xpt_path_comp(ccbh->path, ccb->ccb_h.path)){ printf("CTIO pending\n"); ccb->ccb_h.status = CAM_REQ_INVALID; ahd_unlock(ahd, &s); return; } } if (SLIST_FIRST(&lstate->accept_tios) != NULL) { printf("ATIOs pending\n"); ccb->ccb_h.status = CAM_REQ_INVALID; } if (SLIST_FIRST(&lstate->immed_notifies) != NULL) { printf("INOTs pending\n"); ccb->ccb_h.status = CAM_REQ_INVALID; } if (ccb->ccb_h.status != CAM_REQ_CMP) { ahd_unlock(ahd, &s); return; } xpt_print_path(ccb->ccb_h.path); printf("Target mode disabled\n"); xpt_free_path(lstate->path); free(lstate, M_DEVBUF); ahd_pause(ahd); /* Can we clean up the target too? */ if (target != CAM_TARGET_WILDCARD) { tstate->enabled_luns[lun] = NULL; ahd->enabled_luns--; for (empty = 1, i = 0; i < 8; i++) if (tstate->enabled_luns[i] != NULL) { empty = 0; break; } if (empty) { ahd_free_tstate(ahd, target, channel, /*force*/FALSE); if (ahd->features & AHD_MULTI_TID) { u_int targid_mask; targid_mask = ahd_inw(ahd, TARGID); targid_mask &= ~target_mask; ahd_outw(ahd, TARGID, targid_mask); ahd_update_scsiid(ahd, targid_mask); } } } else { ahd->black_hole = NULL; /* * We can't allow selections without * our black hole device. */ empty = TRUE; } if (ahd->enabled_luns == 0) { /* Disallow select-in */ u_int scsiseq1; scsiseq1 = ahd_inb(ahd, SCSISEQ_TEMPLATE); scsiseq1 &= ~ENSELI; ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq1); scsiseq1 = ahd_inb(ahd, SCSISEQ1); scsiseq1 &= ~ENSELI; ahd_outb(ahd, SCSISEQ1, scsiseq1); if ((ahd->features & AHD_MULTIROLE) == 0) { printf("Configuring Initiator Mode\n"); ahd->flags &= ~AHD_TARGETROLE; ahd->flags |= AHD_INITIATORROLE; ahd_pause(ahd); ahd_loadseq(ahd); ahd_restart(ahd); /* * Unpaused. The extra unpause * that follows is harmless. */ } } ahd_unpause(ahd); ahd_unlock(ahd, &s); } #endif } static void ahd_update_scsiid(struct ahd_softc *ahd, u_int targid_mask) { #if NOT_YET u_int scsiid_mask; u_int scsiid; if ((ahd->features & AHD_MULTI_TID) == 0) panic("ahd_update_scsiid called on non-multitid unit\n"); /* * Since we will rely on the TARGID mask * for selection enables, ensure that OID * in SCSIID is not set to some other ID * that we don't want to allow selections on. */ if ((ahd->features & AHD_ULTRA2) != 0) scsiid = ahd_inb(ahd, SCSIID_ULTRA2); else scsiid = ahd_inb(ahd, SCSIID); scsiid_mask = 0x1 << (scsiid & OID); if ((targid_mask & scsiid_mask) == 0) { u_int our_id; /* ffs counts from 1 */ our_id = ffs(targid_mask); if (our_id == 0) our_id = ahd->our_id; else our_id--; scsiid &= TID; scsiid |= our_id; } if ((ahd->features & AHD_ULTRA2) != 0) ahd_outb(ahd, SCSIID_ULTRA2, scsiid); else ahd_outb(ahd, SCSIID, scsiid); #endif } void ahd_run_tqinfifo(struct ahd_softc *ahd, int paused) { struct target_cmd *cmd; ahd_sync_tqinfifo(ahd, BUS_DMASYNC_POSTREAD); while ((cmd = &ahd->targetcmds[ahd->tqinfifonext])->cmd_valid != 0) { /* * Only advance through the queue if we * have the resources to process the command. */ if (ahd_handle_target_cmd(ahd, cmd) != 0) break; cmd->cmd_valid = 0; ahd_dmamap_sync(ahd, ahd->shared_data_dmat, ahd->shared_data_map.dmamap, ahd_targetcmd_offset(ahd, ahd->tqinfifonext), sizeof(struct target_cmd), BUS_DMASYNC_PREREAD); ahd->tqinfifonext++; /* * Lazily update our position in the target mode incoming * command queue as seen by the sequencer. */ if ((ahd->tqinfifonext & (HOST_TQINPOS - 1)) == 1) { u_int hs_mailbox; hs_mailbox = ahd_inb(ahd, HS_MAILBOX); hs_mailbox &= ~HOST_TQINPOS; hs_mailbox |= ahd->tqinfifonext & HOST_TQINPOS; ahd_outb(ahd, HS_MAILBOX, hs_mailbox); } } } static int ahd_handle_target_cmd(struct ahd_softc *ahd, struct target_cmd *cmd) { struct ahd_tmode_tstate *tstate; struct ahd_tmode_lstate *lstate; struct ccb_accept_tio *atio; uint8_t *byte; int initiator; int target; int lun; initiator = SCSIID_TARGET(ahd, cmd->scsiid); target = SCSIID_OUR_ID(cmd->scsiid); lun = (cmd->identify & MSG_IDENTIFY_LUNMASK); byte = cmd->bytes; tstate = ahd->enabled_targets[target]; lstate = NULL; if (tstate != NULL) lstate = tstate->enabled_luns[lun]; /* * Commands for disabled luns go to the black hole driver. */ if (lstate == NULL) lstate = ahd->black_hole; atio = (struct ccb_accept_tio*)SLIST_FIRST(&lstate->accept_tios); if (atio == NULL) { ahd->flags |= AHD_TQINFIFO_BLOCKED; /* * Wait for more ATIOs from the peripheral driver for this lun. */ return (1); } else ahd->flags &= ~AHD_TQINFIFO_BLOCKED; #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_TQIN) != 0) printf("Incoming command from %d for %d:%d%s\n", initiator, target, lun, lstate == ahd->black_hole ? "(Black Holed)" : ""); #endif SLIST_REMOVE_HEAD(&lstate->accept_tios, sim_links.sle); if (lstate == ahd->black_hole) { /* Fill in the wildcards */ atio->ccb_h.target_id = target; atio->ccb_h.target_lun = lun; } /* * Package it up and send it off to * whomever has this lun enabled. */ atio->sense_len = 0; atio->init_id = initiator; if (byte[0] != 0xFF) { /* Tag was included */ atio->tag_action = *byte++; atio->tag_id = *byte++; atio->ccb_h.flags = CAM_TAG_ACTION_VALID; } else { atio->ccb_h.flags = 0; } byte++; /* Okay. Now determine the cdb size based on the command code */ switch (*byte >> CMD_GROUP_CODE_SHIFT) { case 0: atio->cdb_len = 6; break; case 1: case 2: atio->cdb_len = 10; break; case 4: atio->cdb_len = 16; break; case 5: atio->cdb_len = 12; break; case 3: default: /* Only copy the opcode. */ atio->cdb_len = 1; printf("Reserved or VU command code type encountered\n"); break; } memcpy(atio->cdb_io.cdb_bytes, byte, atio->cdb_len); atio->ccb_h.status |= CAM_CDB_RECVD; if ((cmd->identify & MSG_IDENTIFY_DISCFLAG) == 0) { /* * We weren't allowed to disconnect. * We're hanging on the bus until a * continue target I/O comes in response * to this accept tio. */ #ifdef AHD_DEBUG if ((ahd_debug & AHD_SHOW_TQIN) != 0) printf("Received Immediate Command %d:%d:%d - %p\n", initiator, target, lun, ahd->pending_device); #endif ahd->pending_device = lstate; ahd_freeze_ccb((union ccb *)atio); atio->ccb_h.flags |= CAM_DIS_DISCONNECT; } xpt_done((union ccb*)atio); return (0); } #endif
impedimentToProgress/UCI-BlueChip
snapgear_linux/linux-2.6.21.1/drivers/scsi/aic7xxx/aic79xx_core.c
C
mit
278,803
# Image Patches Differential Optical Flow Rotation/Scale # # This example shows off using your OpenMV Cam to measure # rotation/scale by comparing the current and the previous # image against each other. Note that only rotation/scale is # handled - not X and Y translation in this mode. # # However, this examples goes beyond doing optical flow on the whole # image at once. Instead it breaks up the process by working on groups # of pixels in the image. This gives you a "new" image of results. # # NOTE that surfaces need to have some type of "edge" on them for the # algorithm to work. A featureless surface produces crazy results. # NOTE: Unless you have a very nice test rig this example is hard to see usefulness of... BLOCK_W = 16 # pow2 BLOCK_H = 16 # pow2 # To run this demo effectively please mount your OpenMV Cam on a steady # base and SLOWLY rotate the camera around the lens and move the camera # forward/backwards to see the numbers change. # I.e. Z direction changes only. import sensor, image, time, math # NOTE!!! You have to use a small power of 2 resolution when using # find_displacement(). This is because the algorithm is powered by # something called phase correlation which does the image comparison # using FFTs. A non-power of 2 resolution requires padding to a power # of 2 which reduces the usefulness of the algorithm results. Please # use a resolution like B128X128 or B128X64 (2x faster). # Your OpenMV Cam supports power of 2 resolutions of 64x32, 64x64, # 128x64, and 128x128. If you want a resolution of 32x32 you can create # it by doing "img.pool(2, 2)" on a 64x64 image. sensor.reset() # Reset and initialize the sensor. sensor.set_pixformat(sensor.GRAYSCALE) # Set pixel format to GRAYSCALE (or RGB565) sensor.set_framesize(sensor.B128X128) # Set frame size to 128x128... (or 128x64)... sensor.skip_frames(time = 2000) # Wait for settings take effect. clock = time.clock() # Create a clock object to track the FPS. # Take from the main frame buffer's RAM to allocate a second frame buffer. # There's a lot more RAM in the frame buffer than in the MicroPython heap. # However, after doing this you have a lot less RAM for some algorithms... # So, be aware that it's a lot easier to get out of RAM issues now. extra_fb = sensor.alloc_extra_fb(sensor.width(), sensor.height(), sensor.GRAYSCALE) extra_fb.replace(sensor.snapshot()) while(True): clock.tick() # Track elapsed milliseconds between snapshots(). img = sensor.snapshot() # Take a picture and return the image. for y in range(0, sensor.height(), BLOCK_H): for x in range(0, sensor.width(), BLOCK_W): displacement = extra_fb.find_displacement(img, logpolar=True, \ roi = (x, y, BLOCK_W, BLOCK_H), template_roi = (x, y, BLOCK_W, BLOCK_H)) # Below 0.1 or so (YMMV) and the results are just noise. if(displacement.response() > 0.1): rotation_change = displacement.rotation() zoom_amount = 1.0 + displacement.scale() pixel_x = x + (BLOCK_W//2) + int(math.sin(rotation_change) * zoom_amount * (BLOCK_W//4)) pixel_y = y + (BLOCK_H//2) + int(math.cos(rotation_change) * zoom_amount * (BLOCK_H//4)) img.draw_line((x + BLOCK_W//2, y + BLOCK_H//2, pixel_x, pixel_y), \ color = 255) else: img.draw_line((x + BLOCK_W//2, y + BLOCK_H//2, x + BLOCK_W//2, y + BLOCK_H//2), \ color = 0) extra_fb.replace(img) print(clock.fps())
openmv/openmv
scripts/examples/OpenMV/22-Optical-Flow/image-patches-differential-rotation-scale.py
Python
mit
3,596
import { Observable } from 'rxjs/Observable'; /** * @name Keyboard * @description * @usage * ```typescript * import { Keyboard } from 'ionic-native'; * * * * ``` */ export declare class Keyboard { /** * Hide the keyboard accessory bar with the next, previous and done buttons. * @param hide {boolean} */ static hideKeyboardAccessoryBar(hide: boolean): void; /** * Force keyboard to be shown. */ static show(): void; /** * Close the keyboard if open. */ static close(): void; /** * Prevents the native UIScrollView from moving when an input is focused. * @param disable */ static disableScroll(disable: boolean): void; /** * Creates an observable that notifies you when the keyboard is shown. Unsubscribe to observable to cancel event watch. * @returns {Observable<any>} */ static onKeyboardShow(): Observable<any>; /** * Creates an observable that notifies you when the keyboard is hidden. Unsubscribe to observable to cancel event watch. * @returns {Observable<any>} */ static onKeyboardHide(): Observable<any>; }
Spect-AR/Spect-AR
node_modules/node_modules/ionic-native/dist/esm/plugins/keyboard.d.ts
TypeScript
mit
1,153
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Jasmine Spec Runner</title> <link rel="shortcut icon" type="image/png" href="lib/jasmine-1.3.1/jasmine_favicon.png"> <link rel="stylesheet" type="text/css" href="lib/jasmine-1.3.1/jasmine.css"> <script type="text/javascript" src="lib/jasmine-1.3.1/jasmine.js"></script> <script type="text/javascript" src="lib/jasmine-1.3.1/jasmine-html.js"></script> <!-- include source files here... --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script> <script src="https://cdn.firebase.com/js/client/1.1.0/firebase.js"></script> <script src="https://cdn-staging.firebase.com/v0/firebase-token-generator.js"></script> <script src="../www/js/firefeed.js"></script> <!-- include spec files here... --> <script type="text/javascript" src="spec/helper.js"></script> <script type="text/javascript" src="spec/initialization.js"></script> <script type="text/javascript" src="spec/operations.js"></script> <script type="text/javascript" src="spec/events.js"></script> <script type="text/javascript"> (function() { var jasmineEnv = jasmine.getEnv(); jasmineEnv.updateInterval = 1000; var htmlReporter = new jasmine.HtmlReporter(); jasmineEnv.addReporter(htmlReporter); jasmineEnv.specFilter = function(spec) { return htmlReporter.specFilter(spec); }; var currentWindowOnload = window.onload; window.onload = function() { if (currentWindowOnload) { currentWindowOnload(); } execJasmine(); }; function execJasmine() { jasmineEnv.execute(); } })(); </script> </head> <body> </body> </html>
h3xagram/h3xagram.github.io
test/index.html
HTML
mit
1,895
""" categories: Types,bytes description: Bytes subscr with step != 1 not implemented cause: Unknown workaround: Unknown """ print(b'123'[0:3:2])
cwyark/micropython
tests/cpydiff/types_bytes_subscrstep.py
Python
mit
145
#pragma once // Do³¹czenie nag³ówka SDKDDKVer.h definiuje najwy¿sz¹ dostêpn¹ platformê systemu Windows. // Jeœli chcesz skompilowaæ aplikacjê dla wczeœniejszej platformy systemu Windows, do³¹cz nag³ówek WinSDKVer.h i // ustaw makro _WIN32_WINNT na platformê, któr¹ chcesz wspieraæ, przed do³¹czeniem nag³ówka SDKDDKVer.h. #include <SDKDDKVer.h>
andrzej151/ZMPO
ZMPO3/ZMPO/ZMPO/targetver.h
C
mit
348
require('ember-runtime/core'); require('ember-runtime/system/core_object'); require('ember-runtime/mixins/mutable_enumerable'); require('ember-runtime/mixins/copyable'); require('ember-runtime/mixins/freezable'); /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, isNone = Ember.isNone, fmt = Ember.String.fmt; /** An unordered collection of objects. A Set works a bit like an array except that its items are not ordered. You can create a set to efficiently test for membership for an object. You can also iterate through a set just like an array, even accessing objects by index, however there is no guarantee as to their order. All Sets are observable via the Enumerable Observer API - which works on any enumerable object including both Sets and Arrays. ## Creating a Set You can create a set like you would most objects using `new Ember.Set()`. Most new sets you create will be empty, but you can also initialize the set with some content by passing an array or other enumerable of objects to the constructor. Finally, you can pass in an existing set and the set will be copied. You can also create a copy of a set by calling `Ember.Set#copy()`. ```javascript // creates a new empty set var foundNames = new Ember.Set(); // creates a set with four names in it. var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P // creates a copy of the names set. var namesCopy = new Ember.Set(names); // same as above. var anotherNamesCopy = names.copy(); ``` ## Adding/Removing Objects You generally add or remove objects from a set using `add()` or `remove()`. You can add any type of object including primitives such as numbers, strings, and booleans. Unlike arrays, objects can only exist one time in a set. If you call `add()` on a set with the same object multiple times, the object will only be added once. Likewise, calling `remove()` with the same object multiple times will remove the object the first time and have no effect on future calls until you add the object to the set again. NOTE: You cannot add/remove `null` or `undefined` to a set. Any attempt to do so will be ignored. In addition to add/remove you can also call `push()`/`pop()`. Push behaves just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary object, remove it and return it. This is a good way to use a set as a job queue when you don't care which order the jobs are executed in. ## Testing for an Object To test for an object's presence in a set you simply call `Ember.Set#contains()`. ## Observing changes When using `Ember.Set`, you can observe the `"[]"` property to be alerted whenever the content changes. You can also add an enumerable observer to the set to be notified of specific objects that are added and removed from the set. See `Ember.Enumerable` for more information on enumerables. This is often unhelpful. If you are filtering sets of objects, for instance, it is very inefficient to re-filter all of the items each time the set changes. It would be better if you could just adjust the filtered set based on what was changed on the original set. The same issue applies to merging sets, as well. ## Other Methods `Ember.Set` primary implements other mixin APIs. For a complete reference on the methods you will use with `Ember.Set`, please consult these mixins. The most useful ones will be `Ember.Enumerable` and `Ember.MutableEnumerable` which implement most of the common iterator methods you are used to on Array. Note that you can also use the `Ember.Copyable` and `Ember.Freezable` APIs on `Ember.Set` as well. Once a set is frozen it can no longer be modified. The benefit of this is that when you call `frozenCopy()` on it, Ember will avoid making copies of the set. This allows you to write code that can know with certainty when the underlying set data will or will not be modified. @class Set @namespace Ember @extends Ember.CoreObject @uses Ember.MutableEnumerable @uses Ember.Copyable @uses Ember.Freezable @since Ember 0.9 */ Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable, /** @scope Ember.Set.prototype */ { // .......................................................... // IMPLEMENT ENUMERABLE APIS // /** This property will change as the number of objects in the set changes. @property length @type number @default 0 */ length: 0, /** Clears the set. This is useful if you want to reuse an existing set without having to recreate it. ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.length; // 3 colors.clear(); colors.length; // 0 ``` @method clear @return {Ember.Set} An empty Set */ clear: function() { if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); } var len = get(this, 'length'); if (len === 0) { return this; } var guid; this.enumerableContentWillChange(len, 0); Ember.propertyWillChange(this, 'firstObject'); Ember.propertyWillChange(this, 'lastObject'); for (var i=0; i < len; i++){ guid = guidFor(this[i]); delete this[guid]; delete this[i]; } set(this, 'length', 0); Ember.propertyDidChange(this, 'firstObject'); Ember.propertyDidChange(this, 'lastObject'); this.enumerableContentDidChange(len, 0); return this; }, /** Returns true if the passed object is also an enumerable that contains the same objects as the receiver. ```javascript var colors = ["red", "green", "blue"], same_colors = new Ember.Set(colors); same_colors.isEqual(colors); // true same_colors.isEqual(["purple", "brown"]); // false ``` @method isEqual @param {Ember.Set} obj the other object. @return {Boolean} */ isEqual: function(obj) { // fail fast if (!Ember.Enumerable.detect(obj)) return false; var loc = get(this, 'length'); if (get(obj, 'length') !== loc) return false; while(--loc >= 0) { if (!obj.contains(this[loc])) return false; } return true; }, /** Adds an object to the set. Only non-`null` objects can be added to a set and those can only be added once. If the object is already in the set or the passed value is null this method will have no effect. This is an alias for `Ember.MutableEnumerable.addObject()`. ```javascript var colors = new Ember.Set(); colors.add("blue"); // ["blue"] colors.add("blue"); // ["blue"] colors.add("red"); // ["blue", "red"] colors.add(null); // ["blue", "red"] colors.add(undefined); // ["blue", "red"] ``` @method add @param {Object} obj The object to add. @return {Ember.Set} The set itself. */ add: Ember.aliasMethod('addObject'), /** Removes the object from the set if it is found. If you pass a `null` value or an object that is already not in the set, this method will have no effect. This is an alias for `Ember.MutableEnumerable.removeObject()`. ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.remove("red"); // ["blue", "green"] colors.remove("purple"); // ["blue", "green"] colors.remove(null); // ["blue", "green"] ``` @method remove @param {Object} obj The object to remove @return {Ember.Set} The set itself. */ remove: Ember.aliasMethod('removeObject'), /** Removes the last element from the set and returns it, or `null` if it's empty. ```javascript var colors = new Ember.Set(["green", "blue"]); colors.pop(); // "blue" colors.pop(); // "green" colors.pop(); // null ``` @method pop @return {Object} The removed object from the set or null. */ pop: function() { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); var obj = this.length > 0 ? this[this.length-1] : null; this.remove(obj); return obj; }, /** Inserts the given object on to the end of the set. It returns the set itself. This is an alias for `Ember.MutableEnumerable.addObject()`. ```javascript var colors = new Ember.Set(); colors.push("red"); // ["red"] colors.push("green"); // ["red", "green"] colors.push("blue"); // ["red", "green", "blue"] ``` @method push @return {Ember.Set} The set itself. */ push: Ember.aliasMethod('addObject'), /** Removes the last element from the set and returns it, or `null` if it's empty. This is an alias for `Ember.Set.pop()`. ```javascript var colors = new Ember.Set(["green", "blue"]); colors.shift(); // "blue" colors.shift(); // "green" colors.shift(); // null ``` @method shift @return {Object} The removed object from the set or null. */ shift: Ember.aliasMethod('pop'), /** Inserts the given object on to the end of the set. It returns the set itself. This is an alias of `Ember.Set.push()` ```javascript var colors = new Ember.Set(); colors.unshift("red"); // ["red"] colors.unshift("green"); // ["red", "green"] colors.unshift("blue"); // ["red", "green", "blue"] ``` @method unshift @return {Ember.Set} The set itself. */ unshift: Ember.aliasMethod('push'), /** Adds each object in the passed enumerable to the set. This is an alias of `Ember.MutableEnumerable.addObjects()` ```javascript var colors = new Ember.Set(); colors.addEach(["red", "green", "blue"]); // ["red", "green", "blue"] ``` @method addEach @param {Ember.Enumerable} objects the objects to add. @return {Ember.Set} The set itself. */ addEach: Ember.aliasMethod('addObjects'), /** Removes each object in the passed enumerable to the set. This is an alias of `Ember.MutableEnumerable.removeObjects()` ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.removeEach(["red", "blue"]); // ["green"] ``` @method removeEach @param {Ember.Enumerable} objects the objects to remove. @return {Ember.Set} The set itself. */ removeEach: Ember.aliasMethod('removeObjects'), // .......................................................... // PRIVATE ENUMERABLE SUPPORT // init: function(items) { this._super(); if (items) this.addObjects(items); }, // implement Ember.Enumerable nextObject: function(idx) { return this[idx]; }, // more optimized version firstObject: Ember.computed(function() { return this.length > 0 ? this[0] : undefined; }), // more optimized version lastObject: Ember.computed(function() { return this.length > 0 ? this[this.length-1] : undefined; }), // implements Ember.MutableEnumerable addObject: function(obj) { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); if (isNone(obj)) return this; // nothing to do var guid = guidFor(obj), idx = this[guid], len = get(this, 'length'), added ; if (idx>=0 && idx<len && (this[idx] === obj)) return this; // added added = [obj]; this.enumerableContentWillChange(null, added); Ember.propertyWillChange(this, 'lastObject'); len = get(this, 'length'); this[guid] = len; this[len] = obj; set(this, 'length', len+1); Ember.propertyDidChange(this, 'lastObject'); this.enumerableContentDidChange(null, added); return this; }, // implements Ember.MutableEnumerable removeObject: function(obj) { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); if (isNone(obj)) return this; // nothing to do var guid = guidFor(obj), idx = this[guid], len = get(this, 'length'), isFirst = idx === 0, isLast = idx === len-1, last, removed; if (idx>=0 && idx<len && (this[idx] === obj)) { removed = [obj]; this.enumerableContentWillChange(removed, null); if (isFirst) { Ember.propertyWillChange(this, 'firstObject'); } if (isLast) { Ember.propertyWillChange(this, 'lastObject'); } // swap items - basically move the item to the end so it can be removed if (idx < len-1) { last = this[len-1]; this[idx] = last; this[guidFor(last)] = idx; } delete this[guid]; delete this[len-1]; set(this, 'length', len-1); if (isFirst) { Ember.propertyDidChange(this, 'firstObject'); } if (isLast) { Ember.propertyDidChange(this, 'lastObject'); } this.enumerableContentDidChange(removed, null); } return this; }, // optimized version contains: function(obj) { return this[guidFor(obj)]>=0; }, copy: function() { var C = this.constructor, ret = new C(), loc = get(this, 'length'); set(ret, 'length', loc); while(--loc>=0) { ret[loc] = this[loc]; ret[guidFor(this[loc])] = loc; } return ret; }, toString: function() { var len = this.length, idx, array = []; for(idx = 0; idx < len; idx++) { array[idx] = this[idx]; } return fmt("Ember.Set<%@>", [array.join(',')]); } });
teddyzeenny/ember.js
packages/ember-runtime/lib/system/set.js
JavaScript
mit
13,316
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BoundingBoxWireFrameVisual3D.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // <summary> // A visual element that shows a wireframe for the specified bounding box. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace HelixToolkit.Wpf { using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media.Media3D; /// <summary> /// A visual element that shows a wireframe for the specified bounding box. /// </summary> public class BoundingBoxWireFrameVisual3D : LinesVisual3D { /// <summary> /// Identifies the <see cref="BoundingBox"/> dependency property. /// </summary> public static readonly DependencyProperty BoundingBoxProperty = DependencyProperty.Register( "BoundingBox", typeof(Rect3D), typeof(BoundingBoxWireFrameVisual3D), new UIPropertyMetadata(new Rect3D(), BoxChanged)); /// <summary> /// Gets or sets the bounding box. /// </summary> /// <value> The bounding box. </value> public Rect3D BoundingBox { get { return (Rect3D)this.GetValue(BoundingBoxProperty); } set { this.SetValue(BoundingBoxProperty, value); } } /// <summary> /// Updates the box. /// </summary> protected virtual void OnBoxChanged() { if (this.BoundingBox.IsEmpty) { this.Points = null; return; } var points = new List<Point3D>(); var bb = this.BoundingBox; var p0 = new Point3D(bb.X, bb.Y, bb.Z); var p1 = new Point3D(bb.X, bb.Y + bb.SizeY, bb.Z); var p2 = new Point3D(bb.X + bb.SizeX, bb.Y + bb.SizeY, bb.Z); var p3 = new Point3D(bb.X + bb.SizeX, bb.Y, bb.Z); var p4 = new Point3D(bb.X, bb.Y, bb.Z + bb.SizeZ); var p5 = new Point3D(bb.X, bb.Y + bb.SizeY, bb.Z + bb.SizeZ); var p6 = new Point3D(bb.X + bb.SizeX, bb.Y + bb.SizeY, bb.Z + bb.SizeZ); var p7 = new Point3D(bb.X + bb.SizeX, bb.Y, bb.Z + bb.SizeZ); Action<Point3D, Point3D> addEdge = (p, q) => { points.Add(p); points.Add(q); }; addEdge(p0, p1); addEdge(p1, p2); addEdge(p2, p3); addEdge(p3, p0); addEdge(p4, p5); addEdge(p5, p6); addEdge(p6, p7); addEdge(p7, p4); addEdge(p0, p4); addEdge(p1, p5); addEdge(p2, p6); addEdge(p3, p7); this.Points = points; } /// <summary> /// Called when the box dimensions changed. /// </summary> /// <param name="d"> /// The sender. /// </param> /// <param name="e"> /// The event arguments. /// </param> private static void BoxChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((BoundingBoxWireFrameVisual3D)d).OnBoxChanged(); } } }
DynamoDS/helix-toolkit
Source/HelixToolkit.Wpf/Visual3Ds/ScreenSpaceVisuals/BoundingBoxWireFrameVisual3D.cs
C#
mit
3,576
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using UnityEngine; using System; using System.Collections.Generic; namespace HUX.Utility { public class AABBTree<T> where T : class { #region Private Classes /// <summary> /// Node class for the tree. CAn be either a branch or a leaf. /// </summary> private class AABBNode { #region Public Static Functions /// <summary> /// Creates a node containing both bounds. /// </summary> /// <param name="rightBounds"></param> /// <param name="leftBounds"></param> /// <returns></returns> public static AABBNode CreateNode(Bounds rightBounds, Bounds leftBounds) { AABBNode newNode = new AABBNode(); newNode.Bounds = rightBounds.ExpandToContian(leftBounds); return newNode; } /// <summary> /// Creates a node with the bounds and data. /// </summary> /// <param name="bounds"></param> /// <param name="data"></param> /// <returns></returns> public static AABBNode CreateNode(Bounds bounds, T data) { AABBNode newNode = new AABBNode(); newNode.Bounds = bounds; newNode.UserData = data; // Determine if we want a margin bounds; return newNode; } #endregion //----------------------------------------------------------------------------------------------------------- #region Public Variables /// <summary> /// Children of this node. /// </summary> public AABBNode[] Children = new AABBNode[2]; /// <summary> /// The Axis Aligned Bounding Box for this node. /// </summary> public Bounds Bounds; /// <summary> /// User Data for this node. /// </summary> public T UserData; #endregion //----------------------------------------------------------------------------------------------------------- #region Private Variables /// <summary> /// A weak reference to the parent so the tree will get cleaned up if the root node is no longer referenced. /// </summary> private WeakReference m_ParentRef; #endregion //----------------------------------------------------------------------------------------------------------- #region Accessors /// <summary> /// True if this is a branch node with no children assigned. /// </summary> public bool IsLeaf { get { return Children[0] == null && Children[1] == null; } } /// <summary> /// Accessor for setting/getting the parent. /// </summary> public AABBNode Parent { get { return m_ParentRef != null && m_ParentRef.IsAlive ? m_ParentRef.Target as AABBNode : null; } set { if (value == null) { m_ParentRef = null; } else { m_ParentRef = new WeakReference(value); } } } #endregion //----------------------------------------------------------------------------------------------------------- #region Public Functions /// <summary> /// Sets the children for this node. /// </summary> /// <param name="child1"></param> /// <param name="child2"></param> public void SetChildren(AABBNode child1, AABBNode child2) { child1.Parent = this; child2.Parent = this; Children[0] = child1; Children[1] = child2; } /// <summary> /// Sets the bounds to the size of both children. /// </summary> public void RebuildBounds() { Bounds = Children[0].Bounds.ExpandToContian(Children[1].Bounds); } #endregion } #endregion //----------------------------------------------------------------------------------------------------------- #region Private Variables /// <summary> /// The root node of the tree. /// </summary> private AABBNode m_RootNode; #endregion //----------------------------------------------------------------------------------------------------------- #region Public Functions /// <summary> /// Creates a new node with the provided bounds. /// </summary> /// <param name="bounds"></param> /// <param name="data"></param> public void Insert(Bounds bounds, T data) { AABBNode newNode = AABBNode.CreateNode(bounds, data); if (m_RootNode == null) { m_RootNode = newNode; } else { RecursiveInsert(m_RootNode, newNode); } } /// <summary> /// Removes the node containing data. /// </summary> /// <param name="data"></param> public void Remove(T data) { AABBNode node = FindNode(data); RemoveNode(node); } /// <summary> /// Removes the node with the bounds. If two nodes have the exact same bounds only the first one found will be removed. /// </summary> /// <param name="bounds"></param> public void Remove(Bounds bounds) { AABBNode node = FindNode(bounds); RemoveNode(node); } /// <summary> /// Destroys all nodes in the tree. /// </summary> public void Clear() { // All we need to do is remove the root node reference. The garbage collector will do the rest. m_RootNode = null; } #endregion //----------------------------------------------------------------------------------------------------------- #region Private Functions /// <summary> /// Recursively Insert the new Node until we hit a leaf node. Then branch and insert both nodes. /// </summary> /// <param name="currentNode"></param> /// <param name="newNode"></param> private void RecursiveInsert(AABBNode currentNode, AABBNode newNode) { AABBNode branch = currentNode; if (currentNode.IsLeaf) { branch = AABBNode.CreateNode(currentNode.Bounds, newNode.Bounds); branch.Parent = currentNode.Parent; if (currentNode == m_RootNode) { m_RootNode = branch; } else { branch.Parent.Children[branch.Parent.Children[0] == currentNode ? 0 : 1] = branch; } branch.SetChildren(currentNode, newNode); } else { Bounds withChild1 = branch.Children[0].Bounds.ExpandToContian(newNode.Bounds); Bounds withChild2 = branch.Children[1].Bounds.ExpandToContian(newNode.Bounds); float volume1 = withChild1.Volume(); float volume2 = withChild2.Volume(); RecursiveInsert((volume1 <= volume2) ? branch.Children[0] : branch.Children[1], newNode); } branch.RebuildBounds(); } /// <summary> /// Finds the node that has the assigned user data. /// </summary> /// <param name="userData"></param> /// <returns></returns> private AABBNode FindNode(T userData) { AABBNode foundNode = null; List<AABBNode> nodesToSearch = new List<AABBNode>(); nodesToSearch.Add(m_RootNode); while (nodesToSearch.Count > 0) { AABBNode currentNode = nodesToSearch[0]; nodesToSearch.RemoveAt(0); if (currentNode.UserData == userData) { foundNode = currentNode; break; } else if (!currentNode.IsLeaf) { nodesToSearch.AddRange(currentNode.Children); } } return foundNode; } /// <summary> /// Finds the leaf node that matches bounds. /// </summary> /// <param name="bounds"></param> /// <returns></returns> private AABBNode FindNode(Bounds bounds) { AABBNode foundNode = null; AABBNode currentNode = m_RootNode; while (currentNode != null) { if (currentNode.IsLeaf) { foundNode = currentNode.Bounds == bounds ? currentNode : null; break; } else { //Which child node if any would the bounds be in? if (currentNode.Children[0].Bounds.ContainsBounds(bounds)) { currentNode = currentNode.Children[0]; } else if (currentNode.Children[1].Bounds.ContainsBounds(bounds)) { currentNode = currentNode.Children[1]; } else { currentNode = null; } } } return foundNode; } /// <summary> /// Removes a node from the tree /// </summary> /// <param name="node"></param> private void RemoveNode(AABBNode node) { AABBNode nodeParent = node.Parent; if (node == m_RootNode) { m_RootNode = null; } else { AABBNode otherChild = nodeParent.Children[0] == node ? nodeParent.Children[1] : nodeParent.Children[0]; if (nodeParent.Parent == null) { m_RootNode = otherChild; otherChild.Parent = null; } else { int childIndex = nodeParent.Parent.Children[0] == nodeParent ? 0 : 1; nodeParent.Parent.Children[childIndex] = otherChild; otherChild.Parent = nodeParent.Parent; } UpdateNodeBoundUp(otherChild.Parent); } } /// <summary> /// Updates the bounds nonleaf node object moving up the Parent tree to Root. /// </summary> /// <param name="node"></param> private void UpdateNodeBoundUp(AABBNode node) { if (node != null) { if (!node.IsLeaf) { node.RebuildBounds(); } UpdateNodeBoundUp(node.Parent); } } #endregion } }
AllBecomesGood/Share-UpdateHolograms
ShareAndKeepSynced/Assets/MRDesignLab/HUX/Scripts/Utility/AABBTree.cs
C#
mit
8,882
/*! * Bootstrap-select v1.13.2 (https://developer.snapappointments.com/bootstrap-select) * * Copyright 2012-2018 SnapAppointments, LLC * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ (function (root, factory) { if (root === undefined && window !== undefined) root = window; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define(["jquery"], function (a0) { return (factory(a0)); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("jquery")); } else { factory(root["jQuery"]); } }(this, function (jQuery) { (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Нищо избрано', noneResultsText: 'Няма резултат за {0}', countSelectedText: function (numSelected, numTotal) { return (numSelected == 1) ? "{0} избран елемент" : "{0} избрани елемента"; }, maxOptionsText: function (numAll, numGroup) { return [ (numAll == 1) ? 'Лимита е достигнат ({n} елемент максимум)' : 'Лимита е достигнат ({n} елемента максимум)', (numGroup == 1) ? 'Груповия лимит е достигнат ({n} елемент максимум)' : 'Груповия лимит е достигнат ({n} елемента максимум)' ]; }, selectAllText: 'Избери всички', deselectAllText: 'Размаркирай всички', multipleSeparator: ', ' }; })(jQuery); }));
extend1994/cdnjs
ajax/libs/bootstrap-select/1.13.2/js/i18n/defaults-bg_BG.js
JavaScript
mit
1,838
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Core\Promotion\Checker\Rule; use Sylius\Component\Core\Model\OrderInterface; use Sylius\Component\Core\Model\OrderItemInterface; use Sylius\Component\Core\Model\ProductInterface; use Sylius\Component\Promotion\Checker\Rule\RuleCheckerInterface; use Sylius\Component\Promotion\Exception\UnsupportedTypeException; use Sylius\Component\Promotion\Model\PromotionSubjectInterface; final class HasTaxonRuleChecker implements RuleCheckerInterface { public const TYPE = 'has_taxon'; /** * {@inheritdoc} * * @throws UnsupportedTypeException */ public function isEligible(PromotionSubjectInterface $subject, array $configuration): bool { if (!isset($configuration['taxons'])) { return false; } if (!$subject instanceof OrderInterface) { throw new UnsupportedTypeException($subject, OrderInterface::class); } /** @var OrderItemInterface $item */ foreach ($subject->getItems() as $item) { if ($this->hasProductValidTaxon($item->getProduct(), $configuration)) { return true; } } return false; } /** * @param ProductInterface $product * @param array $configuration * * @return bool */ private function hasProductValidTaxon(ProductInterface $product, array $configuration): bool { foreach ($product->getTaxons() as $taxon) { if (in_array($taxon->getCode(), $configuration['taxons'], true)) { return true; } } return false; } }
videni/Sylius
src/Sylius/Component/Core/Promotion/Checker/Rule/HasTaxonRuleChecker.php
PHP
mit
1,866
require 'faraday' require 'json' module Twitter module REST module Response class ParseJson < Faraday::Response::Middleware WHITESPACE_REGEX = /\A^\s*$\z/ def parse(body) case body when WHITESPACE_REGEX, nil nil else JSON.parse(body, :symbolize_names => true) end end def on_complete(response) response.body = parse(response.body) if respond_to?(:parse) && !unparsable_status_codes.include?(response.status) end def unparsable_status_codes [204, 301, 302, 304] end end end end end Faraday::Response.register_middleware :twitter_parse_json => Twitter::REST::Response::ParseJson
yukisako/omiyage
vendor/bundle/ruby/2.2.0/gems/twitter-5.15.0/lib/twitter/rest/response/parse_json.rb
Ruby
mit
746
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.event.item.inventory; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.event.Cancellable; import org.spongepowered.api.item.inventory.ItemStack; public interface ChangeInventoryEvent extends TargetInventoryEvent, AffectSlotEvent, Cancellable { /** * Fired when a {@link Living} changes it's equipment. */ interface Equipment extends ChangeInventoryEvent {} /** * Fired when a {@link Living} changes it's held {@link ItemStack}. */ interface Held extends ChangeInventoryEvent {} interface Transfer extends ChangeInventoryEvent {} interface Pickup extends ChangeInventoryEvent {} }
kashike/SpongeAPI
src/main/java/org/spongepowered/api/event/item/inventory/ChangeInventoryEvent.java
Java
mit
1,942
<h2>設定</h2> <p>このページでは、管理者が基本的な設定を実行することができます。 実際、このページでは、多くの管理者が必要とする最小設定のみ表示しています。 あなたが他の多くの (そして高度な) 設定を閲覧したい場合、<span class="filename">include/config_default.inc.php</span>ファイルを参照してください。</p> <p>このページは、テーマにより設定パラメータを再編成するため、いくつかのセクションに分けられています。</p> <h3>メイン</h3> <ul> <li><strong>ギャラリータイトル</strong>: RSSフィードおよびメール通知に使用されます。</li> <li><strong>ページバナー</strong>: それぞれのページのトップに表示されます。</li> <li><strong>ギャラリーURI</strong>: RSSフィードに使用されます。</li> <li><strong>ギャラリーをロックする</strong>: メンテナンスのため、ギャラリー全体をロックします。 管理者のみギャラリーにアクセスすることができます。</li> <li><strong>評価</strong>: 写真の評価機能を有効にします。</li> <li><strong>ゲストによる評価</strong>: 未登録のユーザでも写真を評価できます。</li> <li><strong>ユーザ登録を許可する</strong>: すべての人が自由にユーザ登録できます。</li> <li><strong>すべてのユーザにメールアドレスを必須とする</strong>: 管理者による処理を除き、ユーザ登録およびプロファイル更新時にメールアドレスがチェックされます。</li> <li><strong>新しいユーザ登録時、管理者にメールする</strong>: すべてのユーザ登録に関して、管理者がメール受信します。</li> </ul> <h3>履歴</h3> <p>ページにアクセスすることで、<span class="pwgScreen">category.php</span>および<span class="pwgScreen">picture.php</span>が<code>history</code>テーブルに記録されます。</p> <p>アクセスは、「<span class="pwgScreen">管理 > 特別 > 履歴</span>」に表示されます。</p> <ul> <li><strong>ゲストによるページアクセスを記録する</strong>: ゲストによるページアクセスが記録されます。</li> <li><strong>ユーザによるページアクセスを記録する</strong>: ユーザによるページアクセスが記録されます。</li> <li><strong>管理者によるページアクセスを記録する</strong>: 管理者によるページアクセスが記録されます。</li> </ul> <h3>コメント</h3> <ul> <li><strong>すべてのユーザにコメントを許可する</strong>: ユーザ登録されていないゲストでもコメントを投稿することができます。</li> <li><strong>1ページあたりのコメント数</strong>.</li> <li><strong>承認</strong>: サイトで閲覧可能な状態になる前に、管理者がユーザによるコメントを承認します。 ユーザコメントの承認は、「<span class="pwgScreen">管理 > 写真 > コメント</span>」にて実施されます。</li> <li><strong>有効なコメントが投稿された場合、管理者にメールする</strong>: ユーザがコメントを登録して、コメントが承認された場合、管理者にメール送信します。</li> <li><strong>コメントの承認が必要な場合、管理者にメールする</strong>: 管理者による承認が必要なコメントをユーザが投稿した場合、管理者にメール送信します。 ユーザコメントの承認は、「<span class="pwgScreen">管理 > 写真 > コメント</span>」にて実施されます。</li> </ul> <!--TODO --><h3>アップロード</h3> <ul> <!--TODO --> <li><strong>毎回アップロードリンクを表示する</strong>: アップロード可能なアルバムが存在する場合、それぞれのアルバムに追加リンクが表示されます。</li> <!--TODO --> <li><strong>アップロードに関するユーザアクセスレベル</strong>: ユーザによるアップロードの制限を許可します。</li> <li><strong>写真がアップロードされた場合、管理者にメールする</strong>: ユーザにより写真がアップロードされた場合、管理者にメール通知します。</li> </ul> <h3>デフォルト表示</h3> <p>ここであなたは、ログインしていないユーザに対する、デフォルト表示オプションを変更することができます。 ユーザがログインした場合、これらのオプションは、ユーザ独自のオプション (<span class="pwgScreen">プロファイル</span>で変更可) により上書きされます。</p> <p>すべてのユーザは、表示オプションを変更することができますが、あなたは「<span class="pwgScreen">管理 > アイデンティフィケーション > ユーザ</span>」にて、 選択したユーザの表示オプションを変更することもできます。</p> <ul> <li><strong>言語</strong>: Piwigoラベルのみに関係します。アルバム名、写真名およびすべての説明はローカライズされません。</li> <li><strong>1行あたりのイメージ数</strong></li> <li><strong>1ページあたりの行数</strong></li> <li><strong>インターフェーステーマ</strong></li> <li><strong>最近の期間</strong>: 日数。写真が新しい写真として表示される期間です。1日より多い日数を指定してください。</li> <li><strong>すべてのアルバムを拡げる</strong>: デフォルトで、すべてのアルバムをメニューに広げますか? <em>警告</em>: このオプションは、多くのりソースを消費して、あなたのアルバムツリーが多くのアルバムを含む場合、巨大なメニューを作成してしまいます。</li> <li><strong>コメント数を表示する</strong>: サムネイルページで、それぞれの写真のコメント数を表示します。多くのリソースを消費します。</li> <li><strong>ヒット数を表示する</strong>: サムネイルページで、写真のヒット数をサムネイル下に表示します。 特別設定パラメータが次の場合のみ表示されます: <br /> $conf['show_nb_hits'] = true; <br /> 注意: デフォルトでは、falseが設定されています。</li> <li><strong>写真の最大幅</strong>: 写真の最大表示幅です。この設定より写真が大きい場合、表示時にリサイズされます。 この設定に値を入力したい場合、あなたの写真の幅に変更することをお勧めします。</li> <li><strong>写真の最大高</strong>: 前の設定と同じです。</li> </ul>
ale252/theatre
web/piwigo/language/ja_JP/help/configuration.html
HTML
mit
6,959
/*! Tablesaw - v2.0.3 - 2016-05-02 * https://github.com/filamentgroup/tablesaw * Copyright (c) 2016 Filament Group; Licensed MIT */ table.tablesaw { empty-cells: show; max-width: 100%; width: 100%; } .tablesaw { border-collapse: collapse; width: 100%; } /* Structure */ .tablesaw { border: 0; padding: 0; } .tablesaw th, .tablesaw td { box-sizing: border-box; padding: .5em .7em; } .tablesaw thead tr:first-child th { padding-top: .9em; padding-bottom: .7em; } .tablesaw-enhanced .tablesaw-bar .btn { border: 1px solid #ccc; background: none; background-color: #fafafa; box-shadow: 0 1px 0 rgba(255,255,255,1); color: #4a4a4a; clear: both; cursor: pointer; display: block; font: bold 20px/1 sans-serif; margin: 0; padding: .5em .85em .4em .85em; position: relative; text-align: center; text-decoration: none; text-transform: capitalize; text-shadow: 0 1px 0 #fff; width: 100%; /* Theming */ background-image: -webkit-linear-gradient(top, rgba( 255,255,255,.1 ) 0%, rgba( 255,255,255,.1 ) 50%, rgba( 170,170,170,.1 ) 55%, rgba( 120,120,120,.15 ) 100%); background-image: linear-gradient( top, rgba( 255,255,255,.1 ) 0%, rgba( 255,255,255,.1 ) 50%, rgba( 170,170,170,.1 ) 55%, rgba( 120,120,120,.15 ) 100% ); -webkit-appearance: none !important; -moz-appearance: none !important; box-sizing: border-box; -webkit-font-smoothing: antialiased; border-radius: .25em; } .tablesaw-enhanced .tablesaw-bar a.btn { color: #1c95d4; } .tablesaw-enhanced .tablesaw-bar .btn:hover { text-decoration: none; } /* Default radio/checkbox styling horizonal controlgroups. */ .tablesaw-enhanced .tablesaw-bar .btn:active { background-color: #ddd; background-image: -webkit-linear-gradient(top, rgba( 100,100,100,.35 ) 0%, rgba( 255,255,255,0 ) 70%); background-image: linear-gradient( top, rgba( 100,100,100,.35 ) 0%, rgba( 255,255,255,0 ) 70% ); } .tablesaw-enhanced .tablesaw-bar .btn:hover, .tablesaw-enhanced .tablesaw-bar .btn:focus { color: #208de3; background-color: #fff; outline: none; } .tablesaw-bar .btn:focus { box-shadow: 0 0 .35em #4faeef !important; } .tablesaw-bar .btn-select select { background: none; border: none; display: block; position: absolute; font-weight: inherit; left: 0; top: 0; margin: 0; width: 100%; height: 100%; z-index: 2; min-height: 1em; } .tablesaw-bar .btn-select select { opacity: 0; filter: alpha(opacity=0); display: inline-block; color: transparent; } .tablesaw-bar .btn select option { background: #fff; color: #000; font-family: sans-serif; } .tablesaw-enhanced .tablesaw-bar .btn.btn-select { color: #4d4d4d; padding-right: 2.5em; min-width: 7.25em; text-align: left; text-indent: 0; } .tablesaw-bar .btn.btn-small, .tablesaw-bar .btn.btn-micro { display: inline-block; width: auto; height: auto; position: relative; top: 0; } .tablesaw-bar .btn.btn-small { font-size: 1.0625em; line-height: 19px; padding: .3em 1em .3em 1em; } .tablesaw-bar .btn.btn-micro { font-size: .8125em; padding: .4em .7em .25em .7em; } .tablesaw-enhanced .tablesaw-bar .btn-select { text-align: left; } .tablesaw-bar .btn-select:after { background: #e5e5e5; background: rgba(0,0,0,.1); box-shadow: 0 2px 2px rgba(255,255,255,.25); content: " "; display: block; position: absolute; } .tablesaw-bar .btn-select.btn-small, .tablesaw-bar .btn-select.btn-micro { padding-right: 1.5em; } .tablesaw-bar .btn-select:after { background: none; background-repeat: no-repeat; background-position: .25em .45em; content: "\25bc"; font-size: .55em; padding-top: 1.2em; padding-left: 1em; left: auto; right: 0; margin: 0; top: 0; bottom: 0; width: 1.8em; } .tablesaw-bar .btn-select.btn-small:after, .tablesaw-bar .btn-select.btn-micro:after { width: 1.2em; font-size: .5em; padding-top: 1em; padding-right: .5em; line-height: 1.65; background: none; box-shadow: none; border-left-width: 0; } /* Column navigation buttons for swipe and columntoggle tables */ .tablesaw-advance .btn { -webkit-appearance: none; -moz-appearance: none; box-sizing: border-box; text-shadow: 0 1px 0 #fff; border-radius: .25em; } .tablesaw-advance .btn.btn-micro { font-size: .8125em; padding: .3em .7em .25em .7em; } .tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn { display: inline-block; overflow: hidden; width: 1.8em; height: 1.8em; background-position: 50% 50%; margin-left: .5em; position: relative; } .tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.left:before, .tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.right:before, .tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.down:before, .tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.up:before { content: "\0020"; overflow: hidden; width: 0; height: 0; position: absolute; } .tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.down:before { left: .5em; top: .65em; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #808080; } .tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.up:before { left: .5em; top: .65em; border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 5px solid #808080; } .tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.left:before, .tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.right:before { top: .45em; border-top: 5px solid transparent; border-bottom: 5px solid transparent; } .tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.left:before { left: .6em; border-right: 5px solid #808080; } .tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.right:before { left: .7em; border-left: 5px solid #808080; } .tablesaw-advance a.tablesaw-nav-btn.disabled { opacity: .25; filter: alpha(opacity=25); cursor: default; pointer-events: none; } /* Table Toolbar */ .tablesaw-bar { clear: both; font-family: sans-serif; } .tablesaw-toolbar { font-size: .875em; float: left; } .tablesaw-toolbar label { padding: .5em 0; clear: both; display: block; color: #888; margin-right: .5em; text-transform: uppercase; } .tablesaw-bar .btn, .tablesaw-enhanced .tablesaw-bar .btn { margin-top: .5em; margin-bottom: .5em; } .tablesaw-bar .btn-select, .tablesaw-enhanced .tablesaw-bar .btn-select { margin-bottom: 0; } .tablesaw-bar .tablesaw-toolbar .btn { margin-left: .4em; margin-top: 0; text-transform: uppercase; border: none; box-shadow: none; background: transparent; font-family: sans-serif; font-size: 1em; padding-left: .3em; } .tablesaw-bar .tablesaw-toolbar .btn-select { min-width: 0; } .tablesaw-bar .tablesaw-toolbar .btn-select:after { padding-top: .9em; } .tablesaw-bar .tablesaw-toolbar select { color: #888; text-transform: none; background: transparent; } .tablesaw-toolbar ~ table { clear: both; } .tablesaw-toolbar .a11y-sm { clip: rect(0 0 0 0); height: 1px; overflow: hidden; position: absolute; width: 1px; } @media (min-width: 24em) { .tablesaw-toolbar .a11y-sm { clip: none; height: auto; width: auto; position: static; overflow: visible; } } table.tablesaw tbody th { font-weight: bold; } table.tablesaw thead th, table.tablesaw thead td { color: #444; font-size: .9em; } .tablesaw th, .tablesaw td { line-height: 1em; text-align: left; vertical-align: middle; } .tablesaw td, .tablesaw tbody th { vertical-align: middle; font-size: 1.17em; /* 19px */ } .tablesaw td .btn, .tablesaw tbody th .btn { margin: 0; } .tablesaw thead { border: 1px solid #e5e5e4; background: #e2dfdc; background-image: -webkit-linear-gradient(top, #fff, #e2dfdc); background-image: linear-gradient(to bottom, #fff, #e2dfdc); } .tablesaw thead th { font-weight: 100; color: #777; text-transform: uppercase; text-shadow: 0 1px 0 #fff; text-align: left; } .tablesaw thead tr:first-child th { font-weight: normal; font-family: sans-serif; border-right: 1px solid #e4e1de; } /* Table rows have a gray bottom stroke by default */ .tablesaw tbody tr { border-bottom: 1px solid #dfdfdf; } .tablesaw caption { text-align: left; margin-bottom: 0; opacity: .5; filter: alpha(opacity=50); line-height: 2.4; } @media (min-width: 25em) { .tablesaw caption { margin-bottom: .6em; line-height: 1.2; } } /* Stack */ .tablesaw-cell-label-top { text-transform: uppercase; font-size: .9em; font-weight: normal; } .tablesaw-cell-label { font-size: .65em; text-transform: uppercase; color: #888; font-family: sans-serif; } @media (min-width: 40em) { .tablesaw td { line-height: 2em; } } @media only all { .tablesaw-swipe .tablesaw-cell-persist { border-right: 1px solid #e4e1de; } .tablesaw-swipe .tablesaw-cell-persist { box-shadow: 3px 0 4px -1px #e4e1de; } } /* Table rows have a gray bottom stroke by default */ .tablesaw-stack tbody tr { border-bottom: 1px solid #dfdfdf; } .tablesaw-stack td .tablesaw-cell-label, .tablesaw-stack th .tablesaw-cell-label { display: none; } /* Mobile first styles: Begin with the stacked presentation at narrow widths */ @media only all { /* Show the table cells as a block level element */ .tablesaw-stack td, .tablesaw-stack th { text-align: left; display: block; } .tablesaw-stack tr { clear: both; display: table-row; } /* Make the label elements a percentage width */ .tablesaw-stack td .tablesaw-cell-label, .tablesaw-stack th .tablesaw-cell-label { display: block; padding: 0 .6em 0 0; width: 30%; display: inline-block; } /* For grouped headers, have a different style to visually separate the levels by classing the first label in each col group */ .tablesaw-stack th .tablesaw-cell-label-top, .tablesaw-stack td .tablesaw-cell-label-top { display: block; padding: .4em 0; margin: .4em 0; } .tablesaw-cell-label { display: block; } /* Avoid double strokes when stacked */ .tablesaw-stack tbody th.group { margin-top: -1px; } /* Avoid double strokes when stacked */ .tablesaw-stack th.group b.tablesaw-cell-label { display: none !important; } } @media (max-width: 39.9375em) { .tablesaw-stack thead td, .tablesaw-stack thead th { display: none; } .tablesaw-stack tbody td, .tablesaw-stack tbody th { clear: left; float: left; width: 100%; } .tablesaw-cell-label { vertical-align: top; } .tablesaw-cell-content { max-width: 67%; display: inline-block; } .tablesaw-stack td:empty, .tablesaw-stack th:empty { display: none; } } /* Media query to show as a standard table at 560px (35em x 16px) or wider */ @media (min-width: 40em) { .tablesaw-stack tr { display: table-row; } /* Show the table header rows */ .tablesaw-stack td, .tablesaw-stack th, .tablesaw-stack thead td, .tablesaw-stack thead th { display: table-cell; margin: 0; } /* Hide the labels in each cell */ .tablesaw-stack td .tablesaw-cell-label, .tablesaw-stack th .tablesaw-cell-label { display: none !important; } } .tablesaw-fix-persist { table-layout: fixed; } @media only all { /* Unchecked manually: Always hide */ .tablesaw-swipe th.tablesaw-cell-hidden, .tablesaw-swipe td.tablesaw-cell-hidden { display: none; } } .btn.tablesaw-columntoggle-btn span { text-indent: -9999px; display: inline-block; } .tablesaw-columntoggle-btnwrap { position: relative; /* for dialog positioning */ } .tablesaw-columntoggle-btnwrap .dialog-content { padding: .5em; } .tablesaw-columntoggle tbody td { line-height: 1.5; } /* Remove top/bottom margins around the fieldcontain on check list */ .tablesaw-columntoggle-popup { display: none; } .tablesaw-columntoggle-btnwrap.visible .tablesaw-columntoggle-popup { display: block; position: absolute; top: 2em; right: 0; background-color: #fff; padding: .5em .8em; border: 1px solid #ccc; box-shadow: 0 1px 2px #ccc; border-radius: .2em; z-index: 1; } .tablesaw-columntoggle-popup fieldset { margin: 0; } /* Hide all prioritized columns by default */ @media only all { .tablesaw-columntoggle th.tablesaw-priority-6, .tablesaw-columntoggle td.tablesaw-priority-6, .tablesaw-columntoggle th.tablesaw-priority-5, .tablesaw-columntoggle td.tablesaw-priority-5, .tablesaw-columntoggle th.tablesaw-priority-4, .tablesaw-columntoggle td.tablesaw-priority-4, .tablesaw-columntoggle th.tablesaw-priority-3, .tablesaw-columntoggle td.tablesaw-priority-3, .tablesaw-columntoggle th.tablesaw-priority-2, .tablesaw-columntoggle td.tablesaw-priority-2, .tablesaw-columntoggle th.tablesaw-priority-1, .tablesaw-columntoggle td.tablesaw-priority-1 { display: none; } } .tablesaw-columntoggle-btnwrap .dialog-content { top: 0 !important; right: 1em; left: auto !important; width: 12em; max-width: 18em; margin: -.5em auto 0; } .tablesaw-columntoggle-btnwrap .dialog-content:focus { outline-style: none; } /* Preset breakpoints if "" class added to table */ /* Show priority 1 at 320px (20em x 16px) */ @media (min-width: 20em) { .tablesaw-columntoggle th.tablesaw-priority-1, .tablesaw-columntoggle td.tablesaw-priority-1 { display: table-cell; } } /* Show priority 2 at 480px (30em x 16px) */ @media (min-width: 30em) { .tablesaw-columntoggle th.tablesaw-priority-2, .tablesaw-columntoggle td.tablesaw-priority-2 { display: table-cell; } } /* Show priority 3 at 640px (40em x 16px) */ @media (min-width: 40em) { .tablesaw-columntoggle th.tablesaw-priority-3, .tablesaw-columntoggle td.tablesaw-priority-3 { display: table-cell; } .tablesaw-columntoggle tbody td { line-height: 2; } } /* Show priority 4 at 800px (50em x 16px) */ @media (min-width: 50em) { .tablesaw-columntoggle th.tablesaw-priority-4, .tablesaw-columntoggle td.tablesaw-priority-4 { display: table-cell; } } /* Show priority 5 at 960px (60em x 16px) */ @media (min-width: 60em) { .tablesaw-columntoggle th.tablesaw-priority-5, .tablesaw-columntoggle td.tablesaw-priority-5 { display: table-cell; } } /* Show priority 6 at 1,120px (70em x 16px) */ @media (min-width: 70em) { .tablesaw-columntoggle th.tablesaw-priority-6, .tablesaw-columntoggle td.tablesaw-priority-6 { display: table-cell; } } @media only all { /* Unchecked manually: Always hide */ .tablesaw-columntoggle th.tablesaw-cell-hidden, .tablesaw-columntoggle td.tablesaw-cell-hidden { display: none; } /* Checked manually: Always show */ .tablesaw-columntoggle th.tablesaw-cell-visible, .tablesaw-columntoggle td.tablesaw-cell-visible { display: table-cell; } } .tablesaw-columntoggle-popup .btn-group > label { display: block; padding: .2em 0; white-space: nowrap; } .tablesaw-columntoggle-popup .btn-group > label input { margin-right: .8em; } .tablesaw-sortable, .tablesaw-sortable thead, .tablesaw-sortable thead tr, .tablesaw-sortable thead tr th { position: relative; } .tablesaw-sortable thead tr th { padding-right: 1.6em; vertical-align: top; } .tablesaw-sortable th.tablesaw-sortable-head, .tablesaw-sortable tr:first-child th.tablesaw-sortable-head { padding: 0; } .tablesaw-sortable th.tablesaw-sortable-head button { padding-top: .9em; padding-bottom: .7em; padding-left: .6em; padding-right: 1.6em; } .tablesaw-sortable .tablesaw-sortable-head button { min-width: 100%; color: inherit; background: transparent; border: 0; padding: 0; text-align: left; font: inherit; text-transform: inherit; position: relative; } .tablesaw-sortable .tablesaw-sortable-head.tablesaw-sortable-ascending button:after, .tablesaw-sortable .tablesaw-sortable-head.tablesaw-sortable-descending button:after { width: 7px; height: 10px; content: "\0020"; position: absolute; right: .5em; } .tablesaw-sortable .tablesaw-sortable-head.tablesaw-sortable-ascending button:after { content: "\2191"; } .tablesaw-sortable .tablesaw-sortable-head.tablesaw-sortable-descending button:after { content: "\2193"; } .tablesaw-sortable .not-applicable:after { content: "--"; display: block; } .tablesaw-sortable .not-applicable span { display: none; } .tablesaw-advance { float: right; } .tablesaw-advance.minimap { margin-right: .4em; } .tablesaw-advance-dots { float: left; margin: 0; padding: 0; list-style: none; } .tablesaw-advance-dots li { display: table-cell; margin: 0; padding: .4em .2em; } .tablesaw-advance-dots li i { width: .25em; height: .25em; background: #555; border-radius: 100%; display: inline-block; } .tablesaw-advance-dots-hide { opacity: .25; filter: alpha(opacity=25); cursor: default; pointer-events: none; }
jeffthemaximum/jeffline
templates/rubix/demo/public/bower_components/filament-tablesaw/dist/tablesaw.css
CSS
mit
16,889
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.tools.workbench.framework.context; import org.eclipse.persistence.tools.workbench.framework.resources.IconResourceFileNameMap; import org.eclipse.persistence.tools.workbench.framework.resources.ResourceRepository; import org.eclipse.persistence.tools.workbench.framework.resources.ResourceRepositoryWrapper; /** * Wrap another context and expand its resource * repository with a resource repository wrapper. */ public class ExpandedResourceRepositoryApplicationContext extends ApplicationContextWrapper { private ResourceRepository expandedResourceRepository; // ********** constructor/initialization ********** /** * Construct a context with an expanded resource repository * that adds the resources in the specified resource bundle and icon map * to the original resource repository. */ public ExpandedResourceRepositoryApplicationContext(ApplicationContext delegate, Class resourceBundleClass, IconResourceFileNameMap iconResourceFileNameMap) { super(delegate); this.expandedResourceRepository = new ResourceRepositoryWrapper(this.delegateResourceRepository(), resourceBundleClass, iconResourceFileNameMap); } // ********** non-delegated behavior ********** /** * @see ApplicationContextWrapper#getResourceRepository() */ public ResourceRepository getResourceRepository() { return this.expandedResourceRepository; } // ********** additional behavior ********** /** * Return the original, unwrapped resource repository. */ public ResourceRepository delegateResourceRepository() { return this.getDelegate().getResourceRepository(); } }
RallySoftware/eclipselink.runtime
utils/eclipselink.utils.workbench/framework/source/org/eclipse/persistence/tools/workbench/framework/context/ExpandedResourceRepositoryApplicationContext.java
Java
epl-1.0
2,433
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.mappings.transformers; import org.eclipse.persistence.sessions.Session; import org.eclipse.persistence.core.mappings.transformers.CoreFieldTransformer; import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping; /** * PUBLIC: * This interface is used by the Transformation Mapping to build the value for a * specific field. The user must provide implementations of this interface to the * Transformation Mapping. * @author mmacivor * @since 10.1.3 */ public interface FieldTransformer extends CoreFieldTransformer<Session> { /** * Initialize this transformer. Only required if the user needs some special * information from the mapping in order to do the transformation * @param mapping - the mapping this transformer is associated with. */ public void initialize(AbstractTransformationMapping mapping); /** * @param instance - an instance of the domain class which contains the attribute * @param session - the current session * @param fieldName - the name of the field being transformed. Used if the user wants to use this transformer for multiple fields. * @return - The value to be written for the field associated with this transformer */ @Override public Object buildFieldValue(Object instance, String fieldName, Session session); }
RallySoftware/eclipselink.runtime
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/mappings/transformers/FieldTransformer.java
Java
epl-1.0
2,097
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.tests.writing; import org.eclipse.persistence.testing.framework.*; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.sessions.*; import org.eclipse.persistence.sessions.server.ClientSession; import org.eclipse.persistence.testing.framework.WriteObjectTest; /** * Test changing private parts of an object. */ public class ComplexUpdateTest extends WriteObjectTest { /** The object which is actually changed */ public Object workingCopy; public boolean usesUnitOfWork = false; public boolean usesNestedUnitOfWork = false; public boolean shouldCommitParent = false; /** TODO: Set this to true, and fix issues from tests that fail. */ public boolean shouldCompareClone = true; public ComplexUpdateTest() { super(); } public ComplexUpdateTest(Object originalObject) { super(originalObject); } protected void changeObject() { // By default do nothing } public void commitParentUnitOfWork() { useNestedUnitOfWork(); this.shouldCommitParent = true; } public String getName() { return super.getName() + new Boolean(usesUnitOfWork) + new Boolean(usesNestedUnitOfWork); } public void reset() { if (getExecutor().getSession().isUnitOfWork()) { getExecutor().setSession(((UnitOfWork)getSession()).getParent()); // Do the same for nested units of work. if (getExecutor().getSession().isUnitOfWork()) { getExecutor().setSession(((UnitOfWork)getSession()).getParent()); } } super.reset(); } protected void setup() { super.setup(); if (this.usesUnitOfWork) { getExecutor().setSession(getSession().acquireUnitOfWork()); if (this.usesNestedUnitOfWork) { getExecutor().setSession(getSession().acquireUnitOfWork()); } this.workingCopy = ((UnitOfWork)getSession()).registerObject(this.objectToBeWritten); } else { this.workingCopy = this.objectToBeWritten; } } protected void test() { changeObject(); if (this.usesUnitOfWork) { // Ensure that the original has not been changed. if (!((UnitOfWork)getSession()).getParent().compareObjects(this.originalObject, this.objectToBeWritten)) { throw new TestErrorException("The original object was changed through changing the clone."); } ((UnitOfWork)getSession()).commit(); getExecutor().setSession(((UnitOfWork)getSession()).getParent()); if (this.usesNestedUnitOfWork) { if (this.shouldCommitParent) { ((UnitOfWork)getSession()).commit(); } getExecutor().setSession(((UnitOfWork)getSession()).getParent()); } // Ensure that the clone matches the cache. if (this.shouldCompareClone) { ClassDescriptor descriptor = getSession().getClassDescriptor(this.objectToBeWritten); if(descriptor.shouldIsolateObjectsInUnitOfWork()) { getSession().logMessage("ComplexUpdateTest: descriptor.shouldIsolateObjectsInUnitOfWork() == null. In this case object's changes are not merged back into parent's cache"); } else if (descriptor.shouldIsolateProtectedObjectsInUnitOfWork() && getSession().isClientSession()){ if (!getAbstractSession().compareObjects(this.workingCopy, ((ClientSession)getSession()).getParent().getIdentityMapAccessor().getFromIdentityMap(this.workingCopy))) { throw new TestErrorException("The clone does not match the cached object."); } } else { if (!getAbstractSession().compareObjects(this.workingCopy, this.objectToBeWritten)) { throw new TestErrorException("The clone does not match the cached object."); } } } } else { super.test(); } } public void useNestedUnitOfWork() { this.usesNestedUnitOfWork = true; this.usesUnitOfWork = true; } }
RallySoftware/eclipselink.runtime
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/writing/ComplexUpdateTest.java
Java
epl-1.0
5,045
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.tests.jpa.advanced; import org.eclipse.persistence.testing.models.jpa.advanced.Project; /** * Tests the @PostUpdate events from an Entity. * * @author Guy Pelletier */ public class EntityMethodPostUpdateTest extends CallbackEventTest { public void test() throws Exception { m_beforeEvent = 0; // Loading a new object to update, count starts at 0. Project project = updateProject(); m_afterEvent = project.post_update_count; } }
RallySoftware/eclipselink.runtime
jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/tests/jpa/advanced/EntityMethodPostUpdateTest.java
Java
epl-1.0
1,234
<?php /* Plugin Name: Black Studio TinyMCE Widget Plugin URI: https://wordpress.org/plugins/black-studio-tinymce-widget/ Description: Adds a new "Visual Editor" widget type based on the native WordPress TinyMCE editor. Version: 2.2.10 Author: Black Studio Author URI: http://www.blackstudio.it Requires at least: 3.1 Tested up to: 4.5 License: GPLv3 Text Domain: black-studio-tinymce-widget Domain Path: /languages */ // Exit if accessed directly if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Main plugin class * * @package Black_Studio_TinyMCE_Widget * @since 2.0.0 */ if ( ! class_exists( 'Black_Studio_TinyMCE_Plugin' ) ) { final class Black_Studio_TinyMCE_Plugin { /** * Plugin version * * @var string * @since 2.0.0 */ public static $version = '2.2.10'; /** * The single instance of the plugin class * * @var object * @since 2.0.0 */ protected static $_instance = null; /** * Instance of admin class * * @var object * @since 2.0.0 */ protected static $admin = null; /** * Instance of admin pointer class * * @var object * @since 2.1.0 */ protected static $admin_pointer = null; /** * Instance of compatibility class * * @var object * @since 2.0.0 */ protected static $compatibility = null; /** * Instance of the text filters class * * @var object * @since 2.0.0 */ protected static $text_filters = null; /** * Return the main plugin instance * * @return object * @since 2.0.0 */ public static function instance() { if ( is_null( self::$_instance ) ) { self::$_instance = new self(); } return self::$_instance; } /** * Return the instance of the admin class * * @return object * @since 2.0.0 */ public static function admin() { return self::$admin; } /** * Return the instance of the admin pointer class * * @return object * @since 2.1.0 */ public static function admin_pointer() { return self::$admin_pointer; } /** * Return the instance of the compatibility class * * @return object * @since 2.0.0 */ public static function compatibility() { return self::$compatibility; } /** * Return the instance of the text filters class * * @return object * @since 2.0.0 */ public static function text_filters() { return self::$text_filters; } /** * Get plugin version * * @return string * @since 2.0.0 */ public static function get_version() { return self::$version; } /** * Get plugin basename * * @uses plugin_basename() * * @return string * @since 2.0.0 */ public static function get_basename() { return plugin_basename( __FILE__ ); } /** * Class constructor * * @uses add_action() * @uses add_filter() * @uses get_option() * @uses get_bloginfo() * * @global object $wp_embed * @since 2.0.0 */ protected function __construct() { // Include required files include_once( plugin_dir_path( __FILE__ ) . 'includes/class-widget.php' ); // Include and instantiate admin class on admin pages if ( is_admin() ) { include_once( plugin_dir_path( __FILE__ ) . 'includes/class-admin.php' ); self::$admin = Black_Studio_TinyMCE_Admin::instance(); include_once( plugin_dir_path( __FILE__ ) . 'includes/class-admin-pointer.php' ); self::$admin_pointer = Black_Studio_TinyMCE_Admin_Pointer::instance(); } // Include and instantiate text filter class on frontend pages else { include_once( plugin_dir_path( __FILE__ ) . 'includes/class-text-filters.php' ); self::$text_filters = Black_Studio_TinyMCE_Text_Filters::instance(); } // Register action and filter hooks add_action( 'plugins_loaded', array( $this, 'load_compatibility' ), 50 ); add_action( 'widgets_init', array( $this, 'widgets_init' ) ); } /** * Prevent the class from being cloned * * @return void * @since 2.0.0 */ protected function __clone() { _doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; uh?' ), '2.0' ); } /** * Load compatibility class * * @uses apply_filters() * @uses get_bloginfo() * @uses plugin_dir_path() * * @return void * @since 2.0.0 */ public function load_compatibility() { // Compatibility load flag (for both deprecated functions and code for compatibility with other plugins) $load_compatibility = apply_filters( 'black_studio_tinymce_load_compatibility', true ); if ( $load_compatibility ) { include_once( plugin_dir_path( __FILE__ ) . 'includes/class-compatibility.php' ); self::$compatibility = Black_Studio_TinyMCE_Compatibility::instance(); } } /** * Widget initialization * * @uses is_blog_installed() * @uses register_widget() * * @return null|void * @since 2.0.0 */ public function widgets_init() { if ( ! is_blog_installed() ) { return; } register_widget( 'WP_Widget_Black_Studio_TinyMCE' ); } /** * Check if a widget is a Black Studio Tinyme Widget instance * * @param object $widget * @return boolean * @since 2.0.0 */ public function check_widget( $widget ) { return 'object' == gettype( $widget ) && ( 'WP_Widget_Black_Studio_TinyMCE' == get_class( $widget ) || is_subclass_of( $widget , 'WP_Widget_Black_Studio_TinyMCE' ) ); } } // END class Black_Studio_TinyMCE_Plugin } // END class_exists check if ( ! function_exists( 'bstw' ) ) { /** * Return the main instance to prevent the need to use globals * * @return object * @since 2.0.0 */ function bstw() { return Black_Studio_TinyMCE_Plugin::instance(); } /* Create the main instance */ bstw(); } // END function_exists bstw check else { /* Check for multiple plugin instances */ if ( ! function_exists( 'bstw_multiple_notice' ) ) { /** * Show admin notice when multiple instances of the plugin are detected * * @return void * @since 2.1.0 */ function bstw_multiple_notice() { global $pagenow; if ( 'widgets.php' == $pagenow ) { echo '<div class="error">'; /* translators: error message shown when multiple instance of the plugin are detected */ echo '<p>' . esc_html( __( 'ERROR: Multiple instances of the Black Studio TinyMCE Widget plugin were detected. Please activate only one instance at a time.', 'black-studio-tinymce-widget' ) ) . '</p>'; echo '</div>'; } } add_action( 'admin_notices', 'bstw_multiple_notice' ); } // END function_exists bstw_multiple_notice check } // END else function_exists bstw check
bbiehl/The-Bronze-Horse
wp-content/plugins/black-studio-tinymce-widget/black-studio-tinymce-widget.php
PHP
gpl-2.0
6,595
/*! PopUp Free - v4.7.11 * https://wordpress.org/plugins/wordpress-popup/ * Copyright (c) 2015; * Licensed GPLv2+ */ /*global window:false */ /*global document:false */ /*global wp:false */ /*global wpmUi:false */ /*global ace:false */ /** * Admin Javascript functions for PopUp */ jQuery(function init_admin() { // ----- POPUP EDITOR -- // Disables dragging of metaboxes: Users cannot change the metabox order. function disable_metabox_dragging() { var boxes = jQuery( '.meta-box-sortables' ), handles = jQuery( '.postbox .hndle' ); if ( ! boxes.length ) { return; } boxes.sortable({ disabled: true }); handles.css( 'cursor', 'pointer' ); } // Keeps the submitdiv always visible, even when scrolling. function scrolling_submitdiv() { var scroll_top, top_offset, submitdiv = jQuery( '#submitdiv' ), postbody = jQuery( '#post-body' ), body = jQuery( 'body' ), padding = 20; if ( ! submitdiv.length ) { return; } top_offset = submitdiv.position().top; var small_make_sticky = function() { if ( ! body.hasClass( 'sticky-submit' ) ) { body.addClass( 'sticky-submit' ); submitdiv.css({ 'marginTop': 0 } ); submitdiv.find( '.sticky-actions' ).show(); submitdiv.find( '.non-sticky' ).hide(); } }; var small_remove_sticky = function() { if ( body.hasClass( 'sticky-submit' ) ) { body.removeClass( 'sticky-submit' ); submitdiv.find( '.sticky-actions' ).hide(); submitdiv.find( '.non-sticky' ).show(); } }; jQuery( window ).resize(function() { var is_small = jQuery( window ).width() <= 850; if ( is_small ) { if ( ! body.hasClass( 'po-small' ) ) { body.addClass( 'po-small' ); } } else { if ( body.hasClass( 'po-small' ) ) { body.removeClass( 'po-small' ); small_remove_sticky(); } } }).scroll(function(){ if ( postbody.hasClass( 'columns-1' ) || body.hasClass( 'po-small' ) ) { // 1-column view: // The div stays as sticky toolbar when scrolling down. scroll_top = jQuery( window ).scrollTop() - top_offset; if ( scroll_top > 0 ) { small_make_sticky(); } else { small_remove_sticky(); } } else { // 2-column view: // The div scrolls with the page to stay visible. scroll_top = jQuery( window ).scrollTop() - top_offset + padding; if ( scroll_top > 0 ) { submitdiv.css({ 'marginTop': scroll_top } ); } else { submitdiv.css({ 'marginTop': 0 } ); } } }); window.setTimeout( function() { jQuery( window ).trigger( 'scroll' ); }, 100 ); } // Change the text-fields to colorpicker fields. function init_colorpicker() { var inp = jQuery( '.colorpicker' ); if ( ! inp.length || 'function' !== typeof inp.wpColorPicker ) { return; } var maybe_hide_picker = function maybe_hide_picker( ev ) { var el = jQuery( ev.target ), cp = el.closest( '.wp-picker-container' ), me = cp.find( '.colorpicker' ), do_hide = jQuery( '.colorpicker' ); if ( cp.length ) { do_hide = do_hide.not( me ); } do_hide.each( function() { var picker = jQuery( this ), wrap = picker.closest( '.wp-picker-container' ); picker.iris( 'hide' ); // As mentioned: Color picker does not like to hide properly... picker.hide(); wrap.find( '.wp-picker-clear').addClass( 'hidden' ); wrap.find( '.wp-picker-open').removeClass( 'wp-picker-open' ); }); }; inp.wpColorPicker(); // Don't ask why the handler is hooked three times ;-) // The Color picker is a bit bitchy when it comes to hiding it... jQuery( document ).on( 'mousedown', maybe_hide_picker ); jQuery( document ).on( 'click', maybe_hide_picker ); jQuery( document ).on( 'mouseup', maybe_hide_picker ); } // Add event handlers for editor UI controls (i.e. to checkboxes) function init_edit_controls() { var chk_colors = jQuery( '#po-custom-colors' ), chk_size = jQuery( '#po-custom-size' ), opt_display = jQuery( '[name=po_display]' ), chk_can_hide = jQuery( '#po-can-hide' ), chk_close_hides = jQuery( '#po-close-hides' ); if ( ! chk_colors.length ) { return; } var toggle_section = function toggle_section() { var group, me = jQuery( this ), sel = me.data( 'toggle' ), sect = jQuery( sel ), group_or = me.data( 'or' ), group_and = me.data( 'and' ), is_active = false; if ( group_or ) { group = jQuery( group_or ); is_active = ( group.filter( ':checked' ).length > 0); } else if ( group_and ) { group = jQuery( group_and ); is_active = ( group.length === group.filter( ':checked' ).length ); } else { is_active = me.prop( 'checked' ); } if ( is_active ) { sect.removeClass( 'inactive' ); sect.find( 'input,select,textarea,a' ) .prop( 'readonly', false ) .removeClass( 'disabled' ); } else { sect.addClass( 'inactive' ); // Do NOT set .prop('disabled', true)! sect.find( 'input,select,textarea,a' ) .prop( 'readonly', true ) .addClass( 'disabled' ); } sect.addClass( 'inactive-anim' ); }; var toggle_section_group = function toggle_section_group() { var me = jQuery( this ), name = me.attr( 'name' ), group = jQuery( '[name="' + name + '"]' ); group.each(function() { toggle_section.call( this ); }); }; var create_sliders = function create_sliders() { jQuery( '.slider' ).each(function() { var me = jQuery( this ), wrap = me.closest( '.slider-wrap' ), inp_base = me.data( 'input' ), inp_min = wrap.find( inp_base + 'min' ), inp_max = wrap.find( inp_base + 'max' ), min_input = wrap.find( '.slider-min-input' ), min_ignore = wrap.find( '.slider-min-ignore' ), max_input = wrap.find( '.slider-max-input' ), max_ignore = wrap.find( '.slider-max-ignore' ), min = me.data( 'min' ), max = me.data( 'max' ); if ( isNaN( min ) ) { min = 0; } if ( isNaN( max ) ) { max = 9999; } inp_min.prop( 'readonly', true ); inp_max.prop( 'readonly', true ); var update_fields = function update_fields( val1, val2 ) { inp_min.val( val1 ); inp_max.val( val2 ); if ( val1 === min ) { min_input.hide(); min_ignore.show(); } else { min_input.show(); min_ignore.hide(); } if ( val2 === max ) { max_input.hide(); max_ignore.show(); } else { max_input.show(); max_ignore.hide(); } }; me.slider({ range: true, min: min, max: max, values: [ inp_min.val(), inp_max.val() ], slide: function( event, ui ) { update_fields( ui.values[0], ui.values[1] ); } }); update_fields( inp_min.val(), inp_max.val() ); }); }; chk_colors.click( toggle_section ); chk_size.click( toggle_section ); chk_can_hide.click( toggle_section ); chk_close_hides.click( toggle_section ); opt_display.click( toggle_section_group ); toggle_section.call( chk_colors ); toggle_section.call( chk_size ); toggle_section.call( chk_can_hide ); toggle_section.call( chk_close_hides ); opt_display.each(function() { toggle_section.call( jQuery( this ) ); }); create_sliders(); } // Toggle rules on/off function init_rules() { var all_rules = jQuery( '#meta-rules .all-rules' ), active_rules = jQuery( '#meta-rules .active-rules' ); if ( ! all_rules.length ) { return; } var toggle_checkbox = function toggle_checkbox( ev ) { var me = jQuery( ev.target ), chk = me.find( 'input.wpmui-toggle-checkbox' ); if ( me.closest( '.wpmui-toggle' ).length ) { return; } if ( me.hasClass( 'inactive' ) ) { return false; } chk.trigger( 'click' ); }; var toggle_rule = function toggle_rule() { var me = jQuery( this ), rule = me.closest( '.rule' ), sel = me.data( 'form' ), form = active_rules.find( sel ), active = me.prop( 'checked' ); if ( active ) { rule.removeClass( 'off' ).addClass( 'on' ); form.removeClass( 'off' ).addClass( 'on open' ); } else { rule.removeClass( 'on' ).addClass( 'off' ); form.removeClass( 'on' ).addClass( 'off' ); } exclude_rules( me, active ); }; var exclude_rules = function exclude_rules( checkbox, active ) { var ind, excl1, excl2, excl = checkbox.data( 'exclude' ), keys = (excl ? excl.split( ',' ) : []); // Exclude other rules. for ( ind = keys.length - 1; ind >= 0; ind -= 1 ) { excl1 = all_rules.find( '.rule-' + keys[ ind ] ); excl2 = active_rules.find( '#po-rule-' + keys[ ind ] ); if ( excl1.hasClass( 'on' ) ) { // Rule is active; possibly migrated from old PopUp editor // so we cannot disable the rule now... continue; } excl1.prop( 'disabled', active ); if ( active ) { excl1.addClass( 'inactive off' ).removeClass( 'on' ); excl2.addClass( 'off' ).removeClass( 'on' ); } else { excl1.removeClass( 'inactive off' ); } } }; var toggle_form = function toggle_form() { var me = jQuery( this ), form = me.closest( '.rule' ); form.toggleClass( 'open' ); }; all_rules.find( 'input.wpmui-toggle-checkbox' ).click( toggle_rule ); all_rules.find( '.rule' ).click( toggle_checkbox ); active_rules.on( 'click', '.rule-title,.rule-toggle', toggle_form ); // Exclude rules. all_rules.find( '.rule.on input.wpmui-toggle-checkbox' ).each(function() { exclude_rules( jQuery( this ), true ); }); jQuery( '.init-loading' ).removeClass( 'wpmui-loading' ); } // Hook up the "Featured image" button. function init_image() { // Uploading files var box = jQuery( '.content-image' ), btn = box.find( '.add_image' ), dropzone = box.find( '.featured-img' ), reset = box.find( '.reset' ), inp = box.find( '.po-image' ), img_preview = box.find( '.img-preview' ), img_label = box.find( '.lbl-empty' ), img_pos = box.find( '.img-pos' ), file_frame; // User selected an image (via drag-drop or file_frame) var use_image = function use_image( url ) { inp.val( url ); img_preview.attr( 'src', url ).show(); img_label.hide(); img_pos.show(); dropzone.addClass( 'has-image' ); }; // User selected an image (via drag-drop or file_frame) var reset_image = function reset_image( url ) { inp.val( '' ); img_preview.attr( 'src', '' ).hide(); img_label.show(); img_pos.hide(); dropzone.removeClass( 'has-image' ); }; // User clicks on the "Add image" button. var select_clicked = function select_clicked( ev ) { ev.preventDefault(); // If the media frame already exists, reopen it. if ( file_frame ) { file_frame.open(); return; } // Create the media frame. file_frame = wp.media.frames.file_frame = wp.media({ title: btn.attr( 'data-title' ), button: { text: btn.attr( 'data-button' ) }, multiple: false // Set to true to allow multiple files to be selected }); // When an image is selected, run a callback. file_frame.on( 'select', function() { // We set multiple to false so only get one image from the uploader var attachment = file_frame.state().get('selection').first().toJSON(); // Do something with attachment.id and/or attachment.url here use_image( attachment.url ); }); // Finally, open the modal file_frame.open(); }; var select_pos = function select_pos( ev ) { var me = jQuery( this ); img_pos.find( '.option' ).removeClass( 'selected' ); me.addClass( 'selected' ); }; btn.on( 'click', select_clicked ); reset.on( 'click', reset_image ); img_pos.on( 'click', '.option', select_pos ); } // ----- POPUP LIST -- // Adds custom bulk actions to the popup list. function bulk_actions() { var key, ba1 = jQuery( 'select[name="action"] '), ba2 = jQuery( 'select[name="action2"] '); if ( ! ba1.length || 'object' !== typeof window.po_bulk ) { return; } for ( key in window.po_bulk ) { jQuery( '<option>' ) .val( key ) .text( window.po_bulk[key] ) .appendTo( ba1 ) .clone() .appendTo( ba2 ); } } // Makes the post-list sortable (to change popup-order) function sortable_list() { var table = jQuery( 'table.posts' ), tbody = table.find( '#the-list' ); if ( ! tbody.length ) { return; } var ajax_done = function ajax_done( resp, okay ) { table.removeClass( 'wpmui-loading' ); if ( okay ) { for ( var id in resp ) { if ( ! resp.hasOwnProperty( id ) ) { continue; } tbody.find( '#post-' + id + ' .the-pos' ).text( resp[id] ); } } }; var save_order = function save_order( event, ui ) { var i, rows = tbody.find('tr'), order = []; for ( i = 0; i < rows.length; i+= 1 ) { order.push( jQuery( rows[i] ).attr( 'id' ) ); } table.addClass( 'wpmui-loading' ); wpmUi.ajax( null, 'po-ajax' ) .data({ 'do': 'order', 'order': order }) .ondone( ajax_done ) .load_json(); }; tbody.sortable({ placeholder: 'ui-sortable-placeholder', axis: 'y', handle: '.column-po_order', helper: 'clone', opacity: 0.75, update: save_order }); tbody.disableSelection(); } // Shows a preview of the current PopUp. function init_preview() { var doc = jQuery( document ), body = jQuery( '#wpcontent' ); var handle_list_click = function handle_list_click( ev ) { var me = jQuery( this ), po_id = me.data( 'id' ); ev.preventDefault(); if ( undefined === window.inc_popup ) { return false; } body.addClass( 'wpmui-loading' ); window.inc_popup.load( po_id ); return false; }; var handle_editor_click = function handle_editor_click( ev ) { var data, me = jQuery( this ), form = jQuery( '#post' ), ajax = wpmUi.ajax(); ev.preventDefault(); if ( undefined === window.inc_popup ) { return false; } data = ajax.extract_data( form ); body.addClass( 'wpmui-loading' ); window.inc_popup.load( 0, data ); return false; }; var show_popup = function show_popup( ev, popup ) { body.removeClass( 'wpmui-loading' ); popup.init(); }; doc.on( 'click', '.posts .po-preview', handle_list_click ); doc.on( 'click', '#post .preview', handle_editor_click ); doc.on( 'popup-initialized', show_popup ); } // Initialize the CSS editor function init_css_editor() { jQuery('.po_css_editor').each(function(){ var editor = ace.edit(this.id); jQuery(this).data('editor', editor); editor.setTheme('ace/theme/chrome'); editor.getSession().setMode('ace/mode/css'); editor.getSession().setUseWrapMode(true); editor.getSession().setUseWrapMode(false); }); jQuery('.po_css_editor').each(function(){ var self = this, input = jQuery( jQuery(this).data('input') ); jQuery(this).data('editor').getSession().on('change', function () { input.val( jQuery(self).data('editor').getSession().getValue() ); }); }); } if ( ! jQuery( 'body.post-type-inc_popup' ).length ) { return; } // EDITOR if ( jQuery( 'body.post-php' ).length || jQuery( 'body.post-new-php' ).length ) { disable_metabox_dragging(); scrolling_submitdiv(); init_colorpicker(); init_edit_controls(); init_rules(); init_preview(); init_image(); init_css_editor(); wpmUi.upgrade_multiselect(); } // POPUP LIST else if ( jQuery( 'body.edit-php' ).length ) { sortable_list(); bulk_actions(); init_preview(); } });
iAPT/producerroom
wp-content/plugins/wordpress-popup/js/popup-admin.js
JavaScript
gpl-2.0
15,341
/**************************************************************************** * * * GNAT COMPILER COMPONENTS * * * * D E C L * * * * C Implementation File * * * * Copyright (C) 1992-2006, Free Software Foundation, Inc. * * * * GNAT is free software; you can redistribute it and/or modify it under * * terms of the GNU General Public License as published by the Free Soft- * * ware Foundation; either version 2, or (at your option) any later ver- * * sion. GNAT is distributed in the hope that it will be useful, but WITH- * * OUT 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 distributed with GNAT; see file COPYING. If not, write * * to the Free Software Foundation, 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * * * * GNAT was originally developed by the GNAT team at New York University. * * Extensive contributions were provided by Ada Core Technologies Inc. * * * ****************************************************************************/ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "tree.h" #include "flags.h" #include "toplev.h" #include "convert.h" #include "ggc.h" #include "obstack.h" #include "target.h" #include "expr.h" #include "ada.h" #include "types.h" #include "atree.h" #include "elists.h" #include "namet.h" #include "nlists.h" #include "repinfo.h" #include "snames.h" #include "stringt.h" #include "uintp.h" #include "fe.h" #include "sinfo.h" #include "einfo.h" #include "ada-tree.h" #include "gigi.h" /* Convention_Stdcall should be processed in a specific way on Windows targets only. The macro below is a helper to avoid having to check for a Windows specific attribute throughout this unit. */ #if TARGET_DLLIMPORT_DECL_ATTRIBUTES #define Has_Stdcall_Convention(E) (Convention (E) == Convention_Stdcall) #else #define Has_Stdcall_Convention(E) (0) #endif /* These two variables are used to defer recursively expanding incomplete types while we are processing a record or subprogram type. */ static int defer_incomplete_level = 0; static struct incomplete { struct incomplete *next; tree old_type; Entity_Id full_type; } *defer_incomplete_list = 0; /* These two variables are used to defer emission of debug information for nested incomplete record types */ static int defer_debug_level = 0; static tree defer_debug_incomplete_list; static void copy_alias_set (tree, tree); static tree substitution_list (Entity_Id, Entity_Id, tree, bool); static bool allocatable_size_p (tree, bool); static void prepend_attributes (Entity_Id, struct attrib **); static tree elaborate_expression (Node_Id, Entity_Id, tree, bool, bool, bool); static bool is_variable_size (tree); static tree elaborate_expression_1 (Node_Id, Entity_Id, tree, tree, bool, bool); static tree make_packable_type (tree); static tree gnat_to_gnu_field (Entity_Id, tree, int, bool); static bool same_discriminant_p (Entity_Id, Entity_Id); static void components_to_record (tree, Node_Id, tree, int, bool, tree *, bool, bool, bool, bool); static int compare_field_bitpos (const PTR, const PTR); static Uint annotate_value (tree); static void annotate_rep (Entity_Id, tree); static tree compute_field_positions (tree, tree, tree, tree, unsigned int); static tree validate_size (Uint, tree, Entity_Id, enum tree_code, bool, bool); static void set_rm_size (Uint, tree, Entity_Id); static tree make_type_from_size (tree, tree, bool); static unsigned int validate_alignment (Uint, Entity_Id, unsigned int); static void check_ok_for_atomic (tree, Entity_Id, bool); static int compatible_signatures_p (tree ftype1, tree ftype2); /* Given GNAT_ENTITY, an entity in the incoming GNAT tree, return a GCC type corresponding to that entity. GNAT_ENTITY is assumed to refer to an Ada type. */ tree gnat_to_gnu_type (Entity_Id gnat_entity) { tree gnu_decl; /* The back end never attempts to annotate generic types */ if (Is_Generic_Type (gnat_entity) && type_annotate_only) return void_type_node; /* Convert the ada entity type into a GCC TYPE_DECL node. */ gnu_decl = gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0); gcc_assert (TREE_CODE (gnu_decl) == TYPE_DECL); return TREE_TYPE (gnu_decl); } /* Given GNAT_ENTITY, a GNAT defining identifier node, which denotes some Ada entity, this routine returns the equivalent GCC tree for that entity (an ..._DECL node) and associates the ..._DECL node with the input GNAT defining identifier. If GNAT_ENTITY is a variable or a constant declaration, GNU_EXPR gives its initial value (in GCC tree form). This is optional for variables. For renamed entities, GNU_EXPR gives the object being renamed. DEFINITION is nonzero if this call is intended for a definition. This is used for separate compilation where it necessary to know whether an external declaration or a definition should be created if the GCC equivalent was not created previously. The value of 1 is normally used for a nonzero DEFINITION, but a value of 2 is used in special circumstances, defined in the code. */ tree gnat_to_gnu_entity (Entity_Id gnat_entity, tree gnu_expr, int definition) { tree gnu_entity_id; tree gnu_type = NULL_TREE; /* Contains the gnu XXXX_DECL tree node which is equivalent to the input GNAT tree. This node will be associated with the GNAT node by calling the save_gnu_tree routine at the end of the `switch' statement. */ tree gnu_decl = NULL_TREE; /* true if we have already saved gnu_decl as a gnat association. */ bool saved = false; /* Nonzero if we incremented defer_incomplete_level. */ bool this_deferred = false; /* Nonzero if we incremented defer_debug_level. */ bool debug_deferred = false; /* Nonzero if we incremented force_global. */ bool this_global = false; /* Nonzero if we should check to see if elaborated during processing. */ bool maybe_present = false; /* Nonzero if we made GNU_DECL and its type here. */ bool this_made_decl = false; struct attrib *attr_list = NULL; bool debug_info_p = (Needs_Debug_Info (gnat_entity) || debug_info_level == DINFO_LEVEL_VERBOSE); Entity_Kind kind = Ekind (gnat_entity); Entity_Id gnat_temp; unsigned int esize = ((Known_Esize (gnat_entity) && UI_Is_In_Int_Range (Esize (gnat_entity))) ? MIN (UI_To_Int (Esize (gnat_entity)), IN (kind, Float_Kind) ? fp_prec_to_size (LONG_DOUBLE_TYPE_SIZE) : IN (kind, Access_Kind) ? POINTER_SIZE * 2 : LONG_LONG_TYPE_SIZE) : LONG_LONG_TYPE_SIZE); tree gnu_size = 0; bool imported_p = ((Is_Imported (gnat_entity) && No (Address_Clause (gnat_entity))) || From_With_Type (gnat_entity)); unsigned int align = 0; /* Since a use of an Itype is a definition, process it as such if it is not in a with'ed unit. */ if (!definition && Is_Itype (gnat_entity) && !present_gnu_tree (gnat_entity) && In_Extended_Main_Code_Unit (gnat_entity)) { /* Ensure that we are in a subprogram mentioned in the Scope chain of this entity, our current scope is global, or that we encountered a task or entry (where we can't currently accurately check scoping). */ if (!current_function_decl || DECL_ELABORATION_PROC_P (current_function_decl)) { process_type (gnat_entity); return get_gnu_tree (gnat_entity); } for (gnat_temp = Scope (gnat_entity); Present (gnat_temp); gnat_temp = Scope (gnat_temp)) { if (Is_Type (gnat_temp)) gnat_temp = Underlying_Type (gnat_temp); if (Ekind (gnat_temp) == E_Subprogram_Body) gnat_temp = Corresponding_Spec (Parent (Declaration_Node (gnat_temp))); if (IN (Ekind (gnat_temp), Subprogram_Kind) && Present (Protected_Body_Subprogram (gnat_temp))) gnat_temp = Protected_Body_Subprogram (gnat_temp); if (Ekind (gnat_temp) == E_Entry || Ekind (gnat_temp) == E_Entry_Family || Ekind (gnat_temp) == E_Task_Type || (IN (Ekind (gnat_temp), Subprogram_Kind) && present_gnu_tree (gnat_temp) && (current_function_decl == gnat_to_gnu_entity (gnat_temp, NULL_TREE, 0)))) { process_type (gnat_entity); return get_gnu_tree (gnat_entity); } } /* This abort means the entity "gnat_entity" has an incorrect scope, i.e. that its scope does not correspond to the subprogram in which it is declared */ gcc_unreachable (); } /* If this is entity 0, something went badly wrong. */ gcc_assert (Present (gnat_entity)); /* If we've already processed this entity, return what we got last time. If we are defining the node, we should not have already processed it. In that case, we will abort below when we try to save a new GCC tree for this object. We also need to handle the case of getting a dummy type when a Full_View exists. */ if (present_gnu_tree (gnat_entity) && (! definition || (Is_Type (gnat_entity) && imported_p))) { gnu_decl = get_gnu_tree (gnat_entity); if (TREE_CODE (gnu_decl) == TYPE_DECL && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_decl)) && IN (kind, Incomplete_Or_Private_Kind) && Present (Full_View (gnat_entity))) { gnu_decl = gnat_to_gnu_entity (Full_View (gnat_entity), NULL_TREE, 0); save_gnu_tree (gnat_entity, NULL_TREE, false); save_gnu_tree (gnat_entity, gnu_decl, false); } return gnu_decl; } /* If this is a numeric or enumeral type, or an access type, a nonzero Esize must be specified unless it was specified by the programmer. */ gcc_assert (!Unknown_Esize (gnat_entity) || Has_Size_Clause (gnat_entity) || (!IN (kind, Numeric_Kind) && !IN (kind, Enumeration_Kind) && (!IN (kind, Access_Kind) || kind == E_Access_Protected_Subprogram_Type || kind == E_Access_Subtype))); /* Likewise, RM_Size must be specified for all discrete and fixed-point types. */ gcc_assert (!IN (kind, Discrete_Or_Fixed_Point_Kind) || !Unknown_RM_Size (gnat_entity)); /* Get the name of the entity and set up the line number and filename of the original definition for use in any decl we make. */ gnu_entity_id = get_entity_name (gnat_entity); Sloc_to_locus (Sloc (gnat_entity), &input_location); /* If we get here, it means we have not yet done anything with this entity. If we are not defining it here, it must be external, otherwise we should have defined it already. */ gcc_assert (definition || Is_Public (gnat_entity) || type_annotate_only || kind == E_Discriminant || kind == E_Component || kind == E_Label || (kind == E_Constant && Present (Full_View (gnat_entity))) || IN (kind, Type_Kind)); /* For cases when we are not defining (i.e., we are referencing from another compilation unit) Public entities, show we are at global level for the purpose of computing scopes. Don't do this for components or discriminants since the relevant test is whether or not the record is being defined. But do this for Imported functions or procedures in all cases. */ if ((!definition && Is_Public (gnat_entity) && !Is_Statically_Allocated (gnat_entity) && kind != E_Discriminant && kind != E_Component) || (Is_Imported (gnat_entity) && (kind == E_Function || kind == E_Procedure))) force_global++, this_global = true; /* Handle any attributes directly attached to the entity. */ if (Has_Gigi_Rep_Item (gnat_entity)) prepend_attributes (gnat_entity, &attr_list); /* Machine_Attributes on types are expected to be propagated to subtypes. The corresponding Gigi_Rep_Items are only attached to the first subtype though, so we handle the propagation here. */ if (Is_Type (gnat_entity) && Base_Type (gnat_entity) != gnat_entity && !Is_First_Subtype (gnat_entity) && Has_Gigi_Rep_Item (First_Subtype (Base_Type (gnat_entity)))) prepend_attributes (First_Subtype (Base_Type (gnat_entity)), &attr_list); switch (kind) { case E_Constant: /* If this is a use of a deferred constant, get its full declaration. */ if (!definition && Present (Full_View (gnat_entity))) { gnu_decl = gnat_to_gnu_entity (Full_View (gnat_entity), gnu_expr, definition); saved = true; break; } /* If we have an external constant that we are not defining, get the expression that is was defined to represent. We may throw that expression away later if it is not a constant. Do not retrieve the expression if it is an aggregate, because in complex instantiation contexts it may not be expanded */ if (!definition && Present (Expression (Declaration_Node (gnat_entity))) && !No_Initialization (Declaration_Node (gnat_entity)) && (Nkind (Expression (Declaration_Node (gnat_entity))) != N_Aggregate)) gnu_expr = gnat_to_gnu (Expression (Declaration_Node (gnat_entity))); /* Ignore deferred constant definitions; they are processed fully in the front-end. For deferred constant references, get the full definition. On the other hand, constants that are renamings are handled like variable renamings. If No_Initialization is set, this is not a deferred constant but a constant whose value is built manually. */ if (definition && !gnu_expr && !No_Initialization (Declaration_Node (gnat_entity)) && No (Renamed_Object (gnat_entity))) { gnu_decl = error_mark_node; saved = true; break; } else if (!definition && IN (kind, Incomplete_Or_Private_Kind) && Present (Full_View (gnat_entity))) { gnu_decl = gnat_to_gnu_entity (Full_View (gnat_entity), NULL_TREE, 0); saved = true; break; } goto object; case E_Exception: /* We used to special case VMS exceptions here to directly map them to their associated condition code. Since this code had to be masked dynamically to strip off the severity bits, this caused trouble in the GCC/ZCX case because the "type" pointers we store in the tables have to be static. We now don't special case here anymore, and let the regular processing take place, which leaves us with a regular exception data object for VMS exceptions too. The condition code mapping is taken care of by the front end and the bitmasking by the runtime library. */ goto object; case E_Discriminant: case E_Component: { /* The GNAT record where the component was defined. */ Entity_Id gnat_record = Underlying_Type (Scope (gnat_entity)); /* If the variable is an inherited record component (in the case of extended record types), just return the inherited entity, which must be a FIELD_DECL. Likewise for discriminants. For discriminants of untagged records which have explicit stored discriminants, return the entity for the corresponding stored discriminant. Also use Original_Record_Component if the record has a private extension. */ if (Present (Original_Record_Component (gnat_entity)) && Original_Record_Component (gnat_entity) != gnat_entity) { gnu_decl = gnat_to_gnu_entity (Original_Record_Component (gnat_entity), gnu_expr, definition); saved = true; break; } /* If the enclosing record has explicit stored discriminants, then it is an untagged record. If the Corresponding_Discriminant is not empty then this must be a renamed discriminant and its Original_Record_Component must point to the corresponding explicit stored discriminant (i.e., we should have taken the previous branch). */ else if (Present (Corresponding_Discriminant (gnat_entity)) && Is_Tagged_Type (gnat_record)) { /* A tagged record has no explicit stored discriminants. */ gcc_assert (First_Discriminant (gnat_record) == First_Stored_Discriminant (gnat_record)); gnu_decl = gnat_to_gnu_entity (Corresponding_Discriminant (gnat_entity), gnu_expr, definition); saved = true; break; } /* If the enclosing record has explicit stored discriminants, then it is an untagged record. If the Corresponding_Discriminant is not empty then this must be a renamed discriminant and its Original_Record_Component must point to the corresponding explicit stored discriminant (i.e., we should have taken the first branch). */ else if (Present (Corresponding_Discriminant (gnat_entity)) && (First_Discriminant (gnat_record) != First_Stored_Discriminant (gnat_record))) gcc_unreachable (); /* Otherwise, if we are not defining this and we have no GCC type for the containing record, make one for it. Then we should have made our own equivalent. */ else if (!definition && !present_gnu_tree (gnat_record)) { /* ??? If this is in a record whose scope is a protected type and we have an Original_Record_Component, use it. This is a workaround for major problems in protected type handling. */ Entity_Id Scop = Scope (Scope (gnat_entity)); if ((Is_Protected_Type (Scop) || (Is_Private_Type (Scop) && Present (Full_View (Scop)) && Is_Protected_Type (Full_View (Scop)))) && Present (Original_Record_Component (gnat_entity))) { gnu_decl = gnat_to_gnu_entity (Original_Record_Component (gnat_entity), gnu_expr, definition); saved = true; break; } gnat_to_gnu_entity (Scope (gnat_entity), NULL_TREE, 0); gnu_decl = get_gnu_tree (gnat_entity); saved = true; break; } else /* Here we have no GCC type and this is a reference rather than a definition. This should never happen. Most likely the cause is a reference before declaration in the gnat tree for gnat_entity. */ gcc_unreachable (); } case E_Loop_Parameter: case E_Out_Parameter: case E_Variable: /* Simple variables, loop variables, OUT parameters, and exceptions. */ object: { bool used_by_ref = false; bool const_flag = ((kind == E_Constant || kind == E_Variable) && !Is_Statically_Allocated (gnat_entity) && Is_True_Constant (gnat_entity) && (((Nkind (Declaration_Node (gnat_entity)) == N_Object_Declaration) && Present (Expression (Declaration_Node (gnat_entity)))) || Present (Renamed_Object (gnat_entity)))); bool inner_const_flag = const_flag; bool static_p = Is_Statically_Allocated (gnat_entity); bool mutable_p = false; tree gnu_ext_name = NULL_TREE; tree renamed_obj = NULL_TREE; if (Present (Renamed_Object (gnat_entity)) && !definition) { if (kind == E_Exception) gnu_expr = gnat_to_gnu_entity (Renamed_Entity (gnat_entity), NULL_TREE, 0); else gnu_expr = gnat_to_gnu (Renamed_Object (gnat_entity)); } /* Get the type after elaborating the renamed object. */ gnu_type = gnat_to_gnu_type (Etype (gnat_entity)); /* If this is a loop variable, its type should be the base type. This is because the code for processing a loop determines whether a normal loop end test can be done by comparing the bounds of the loop against those of the base type, which is presumed to be the size used for computation. But this is not correct when the size of the subtype is smaller than the type. */ if (kind == E_Loop_Parameter) gnu_type = get_base_type (gnu_type); /* Reject non-renamed objects whose types are unconstrained arrays or any object whose type is a dummy type or VOID_TYPE. */ if ((TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE && No (Renamed_Object (gnat_entity))) || TYPE_IS_DUMMY_P (gnu_type) || TREE_CODE (gnu_type) == VOID_TYPE) { gcc_assert (type_annotate_only); if (this_global) force_global--; return error_mark_node; } /* If an alignment is specified, use it if valid. Note that exceptions are objects but don't have alignments. We must do this before we validate the size, since the alignment can affect the size. */ if (kind != E_Exception && Known_Alignment (gnat_entity)) { gcc_assert (Present (Alignment (gnat_entity))); align = validate_alignment (Alignment (gnat_entity), gnat_entity, TYPE_ALIGN (gnu_type)); gnu_type = maybe_pad_type (gnu_type, NULL_TREE, align, gnat_entity, "PAD", 0, definition, 1); } /* If we are defining the object, see if it has a Size value and validate it if so. If we are not defining the object and a Size clause applies, simply retrieve the value. We don't want to ignore the clause and it is expected to have been validated already. Then get the new type, if any. */ if (definition) gnu_size = validate_size (Esize (gnat_entity), gnu_type, gnat_entity, VAR_DECL, false, Has_Size_Clause (gnat_entity)); else if (Has_Size_Clause (gnat_entity)) gnu_size = UI_To_gnu (Esize (gnat_entity), bitsizetype); if (gnu_size) { gnu_type = make_type_from_size (gnu_type, gnu_size, Has_Biased_Representation (gnat_entity)); if (operand_equal_p (TYPE_SIZE (gnu_type), gnu_size, 0)) gnu_size = NULL_TREE; } /* If this object has self-referential size, it must be a record with a default value. We are supposed to allocate an object of the maximum size in this case unless it is a constant with an initializing expression, in which case we can get the size from that. Note that the resulting size may still be a variable, so this may end up with an indirect allocation. */ if (No (Renamed_Object (gnat_entity)) && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type))) { if (gnu_expr && kind == E_Constant) /* LLVM local begin */ { gnu_type = TREE_TYPE (gnu_expr); gnu_size = SUBSTITUTE_PLACEHOLDER_IN_EXPR (TYPE_SIZE (gnu_type), gnu_expr); } /* LLVM local end */ /* We may have no GNU_EXPR because No_Initialization is set even though there's an Expression. */ else if (kind == E_Constant && (Nkind (Declaration_Node (gnat_entity)) == N_Object_Declaration) && Present (Expression (Declaration_Node (gnat_entity)))) /* LLVM local begin */ { gnu_type = gnat_to_gnu_type (Etype (Expression (Declaration_Node (gnat_entity)))); gnu_size = TYPE_SIZE (gnu_type); } /* LLVM local end */ else { gnu_size = max_size (TYPE_SIZE (gnu_type), true); mutable_p = true; } } /* If the size is zero bytes, make it one byte since some linkers have trouble with zero-sized objects. If the object will have a template, that will make it nonzero so don't bother. Also avoid doing that for an object renaming or an object with an address clause, as we would lose useful information on the view size (e.g. for null array slices) and we are not allocating the object here anyway. */ if (((gnu_size && integer_zerop (gnu_size)) || (TYPE_SIZE (gnu_type) && integer_zerop (TYPE_SIZE (gnu_type)))) && (!Is_Constr_Subt_For_UN_Aliased (Etype (gnat_entity)) || !Is_Array_Type (Etype (gnat_entity))) && !Present (Renamed_Object (gnat_entity)) && !Present (Address_Clause (gnat_entity))) gnu_size = bitsize_unit_node; /* If this is an atomic object with no specified size and alignment, but where the size of the type is a constant, set the alignment to the lowest power of two greater than the size, or to the biggest meaningful alignment, whichever is smaller. */ if (Is_Atomic (gnat_entity) && !gnu_size && align == 0 && TREE_CODE (TYPE_SIZE (gnu_type)) == INTEGER_CST) { if (!host_integerp (TYPE_SIZE (gnu_type), 1) || 0 <= compare_tree_int (TYPE_SIZE (gnu_type), BIGGEST_ALIGNMENT)) align = BIGGEST_ALIGNMENT; else align = ((unsigned int) 1 << (floor_log2 (tree_low_cst (TYPE_SIZE (gnu_type), 1) - 1) + 1)); } /* If the object is set to have atomic components, find the component type and validate it. ??? Note that we ignore Has_Volatile_Components on objects; it's not at all clear what to do in that case. */ if (Has_Atomic_Components (gnat_entity)) { tree gnu_inner = (TREE_CODE (gnu_type) == ARRAY_TYPE ? TREE_TYPE (gnu_type) : gnu_type); while (TREE_CODE (gnu_inner) == ARRAY_TYPE && TYPE_MULTI_ARRAY_P (gnu_inner)) gnu_inner = TREE_TYPE (gnu_inner); check_ok_for_atomic (gnu_inner, gnat_entity, true); } /* Now check if the type of the object allows atomic access. Note that we must test the type, even if this object has size and alignment to allow such access, because we will be going inside the padded record to assign to the object. We could fix this by always copying via an intermediate value, but it's not clear it's worth the effort. */ if (Is_Atomic (gnat_entity)) check_ok_for_atomic (gnu_type, gnat_entity, false); /* If this is an aliased object with an unconstrained nominal subtype, make a type that includes the template. */ if (Is_Constr_Subt_For_UN_Aliased (Etype (gnat_entity)) && Is_Array_Type (Etype (gnat_entity)) && !type_annotate_only) { tree gnu_fat = TREE_TYPE (gnat_to_gnu_type (Base_Type (Etype (gnat_entity)))); gnu_type = build_unc_object_type_from_ptr (gnu_fat, gnu_type, concat_id_with_name (gnu_entity_id, "UNC")); } #ifdef MINIMUM_ATOMIC_ALIGNMENT /* If the size is a constant and no alignment is specified, force the alignment to be the minimum valid atomic alignment. The restriction on constant size avoids problems with variable-size temporaries; if the size is variable, there's no issue with atomic access. Also don't do this for a constant, since it isn't necessary and can interfere with constant replacement. Finally, do not do it for Out parameters since that creates an size inconsistency with In parameters. */ if (align == 0 && MINIMUM_ATOMIC_ALIGNMENT > TYPE_ALIGN (gnu_type) && !FLOAT_TYPE_P (gnu_type) && !const_flag && No (Renamed_Object (gnat_entity)) && !imported_p && No (Address_Clause (gnat_entity)) && kind != E_Out_Parameter && (gnu_size ? TREE_CODE (gnu_size) == INTEGER_CST : TREE_CODE (TYPE_SIZE (gnu_type)) == INTEGER_CST)) align = MINIMUM_ATOMIC_ALIGNMENT; #endif /* Make a new type with the desired size and alignment, if needed. */ gnu_type = maybe_pad_type (gnu_type, gnu_size, align, gnat_entity, "PAD", false, definition, true); /* Make a volatile version of this object's type if we are to make the object volatile. Note that 13.3(19) says that we should treat other types of objects as volatile as well. */ if ((Treat_As_Volatile (gnat_entity) || Is_Exported (gnat_entity) || Is_Imported (gnat_entity) || Present (Address_Clause (gnat_entity))) && !TYPE_VOLATILE (gnu_type)) gnu_type = build_qualified_type (gnu_type, (TYPE_QUALS (gnu_type) | TYPE_QUAL_VOLATILE)); /* Convert the expression to the type of the object except in the case where the object's type is unconstrained or the object's type is a padded record whose field is of self-referential size. In the former case, converting will generate unnecessary evaluations of the CONSTRUCTOR to compute the size and in the latter case, we want to only copy the actual data. */ if (gnu_expr && TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type)) && !(TREE_CODE (gnu_type) == RECORD_TYPE && TYPE_IS_PADDING_P (gnu_type) && (CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS (gnu_type))))))) gnu_expr = convert (gnu_type, gnu_expr); /* See if this is a renaming, and handle appropriately depending on what is renamed and in which context. There are three major cases: 1/ This is a constant renaming and we can just make an object with what is renamed as its initial value, 2/ We can reuse a stabilized version of what is renamed in place of the renaming, 3/ If neither 1 or 2 applies, we make the renaming entity a constant pointer to what is being renamed. */ if (Present (Renamed_Object (gnat_entity))) { /* If the renamed object had padding, strip off the reference to the inner object and reset our type. */ if (TREE_CODE (gnu_expr) == COMPONENT_REF && (TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_expr, 0))) == RECORD_TYPE) && (TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_expr, 0))))) { gnu_expr = TREE_OPERAND (gnu_expr, 0); gnu_type = TREE_TYPE (gnu_expr); } /* Case 1: If this is a constant renaming, treat it as a normal object whose initial value is what is being renamed. We cannot do this if the type is unconstrained or class-wide. */ if (const_flag && !TREE_SIDE_EFFECTS (gnu_expr) && TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE && TYPE_MODE (gnu_type) != BLKmode && Ekind (Etype (gnat_entity)) != E_Class_Wide_Type && !Is_Array_Type (Etype (gnat_entity))) ; /* Otherwise, see if we can proceed with a stabilized version of the renamed entity or if we need to make a pointer. */ else { bool stabilized = false; tree maybe_stable_expr = NULL_TREE; /* Case 2: If the renaming entity need not be materialized and the renamed expression is something we can stabilize, use that for the renaming. At the global level, we can only do this if we know no SAVE_EXPRs need be made, because the expression we return might be used in arbitrary conditional branches so we must force the SAVE_EXPRs evaluation immediately and this requires a function context. */ if (!Materialize_Entity (gnat_entity) && (!global_bindings_p () || (staticp (gnu_expr) && !TREE_SIDE_EFFECTS (gnu_expr)))) { maybe_stable_expr = maybe_stabilize_reference (gnu_expr, true, false, &stabilized); if (stabilized) { gnu_decl = maybe_stable_expr; save_gnu_tree (gnat_entity, gnu_decl, true); saved = true; break; } /* The stabilization failed. Keep maybe_stable_expr untouched here to let the pointer case below know about that failure. */ } /* Case 3: Make this into a constant pointer to the object we are to rename and attach the object to the pointer if it is an lvalue that can be stabilized. From the proper scope, attached objects will be referenced directly instead of indirectly via the pointer to avoid subtle aliasing problems with non addressable entities. They have to be stable because we must not evaluate the variables in the expression every time the renaming is used. They also have to be lvalues because the context in which they are reused sometimes requires so. We call pointers with an attached object "renaming" pointers. In the rare cases where we cannot stabilize the renamed object, we just make a "bare" pointer, and the renamed entity is always accessed indirectly through it. */ { bool expr_has_side_effects = TREE_SIDE_EFFECTS (gnu_expr); inner_const_flag = TREE_READONLY (gnu_expr); const_flag = true; gnu_type = build_reference_type (gnu_type); /* If a previous attempt at unrestricted stabilization failed, there is no point trying again and we can reuse the result without attaching it to the pointer. */ if (maybe_stable_expr) ; /* Otherwise, try to stabilize now, restricting to lvalues only, and attach the expression to the pointer if the stabilization succeeds. Note that this might introduce SAVE_EXPRs and we don't check whether we're at the global level or not. This is fine since we are building a pointer initializer and neither the pointer nor the initializing expression can be accessed before the pointer elaboration has taken place in a correct program. SAVE_EXPRs will be evaluated at the right spots by either create_var_decl->expand_decl_init for the non-global case or build_unit_elab for the global case, and will be attached to the elaboration procedure by the RTL expander in the latter case. We have no need to force an early evaluation here. */ else { maybe_stable_expr = maybe_stabilize_reference (gnu_expr, true, true, &stabilized); if (stabilized) renamed_obj = maybe_stable_expr; /* Attaching is actually performed downstream, as soon as we have a DECL for the pointer we make. */ } gnu_expr = build_unary_op (ADDR_EXPR, gnu_type, maybe_stable_expr); /* If the initial expression has side effects, we might still have an unstabilized version at this point (for instance if it involves a function call). Wrap the result into a SAVE_EXPR now, in case it happens to be referenced several times. */ if (expr_has_side_effects && ! stabilized) gnu_expr = save_expr (gnu_expr); gnu_size = NULL_TREE; used_by_ref = true; } } } /* If this is an aliased object whose nominal subtype is unconstrained, the object is a record that contains both the template and the object. If there is an initializer, it will have already been converted to the right type, but we need to create the template if there is no initializer. */ else if (definition && TREE_CODE (gnu_type) == RECORD_TYPE && (TYPE_CONTAINS_TEMPLATE_P (gnu_type) /* Beware that padding might have been introduced via maybe_pad_type above. */ || (TYPE_IS_PADDING_P (gnu_type) && TREE_CODE (TREE_TYPE (TYPE_FIELDS (gnu_type))) == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (TYPE_FIELDS (gnu_type))))) && !gnu_expr) { tree template_field = TYPE_IS_PADDING_P (gnu_type) ? TYPE_FIELDS (TREE_TYPE (TYPE_FIELDS (gnu_type))) : TYPE_FIELDS (gnu_type); gnu_expr = gnat_build_constructor (gnu_type, tree_cons (template_field, build_template (TREE_TYPE (template_field), TREE_TYPE (TREE_CHAIN (template_field)), NULL_TREE), NULL_TREE)); } /* If this is a pointer and it does not have an initializing expression, initialize it to NULL, unless the object is imported. */ if (definition && (POINTER_TYPE_P (gnu_type) || TYPE_FAT_POINTER_P (gnu_type)) && !Is_Imported (gnat_entity) && !gnu_expr) gnu_expr = integer_zero_node; /* If we are defining the object and it has an Address clause we must get the address expression from the saved GCC tree for the object if the object has a Freeze_Node. Otherwise, we elaborate the address expression here since the front-end has guaranteed in that case that the elaboration has no effects. Note that only the latter mechanism is currently in use. */ if (definition && Present (Address_Clause (gnat_entity))) { tree gnu_address = (present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : gnat_to_gnu (Expression (Address_Clause (gnat_entity)))); save_gnu_tree (gnat_entity, NULL_TREE, false); /* Ignore the size. It's either meaningless or was handled above. */ gnu_size = NULL_TREE; gnu_type = build_reference_type (gnu_type); gnu_address = convert (gnu_type, gnu_address); used_by_ref = true; const_flag = !Is_Public (gnat_entity); /* If we don't have an initializing expression for the underlying variable, the initializing expression for the pointer is the specified address. Otherwise, we have to make a COMPOUND_EXPR to assign both the address and the initial value. */ if (!gnu_expr) gnu_expr = gnu_address; else gnu_expr = build2 (COMPOUND_EXPR, gnu_type, build_binary_op (MODIFY_EXPR, NULL_TREE, build_unary_op (INDIRECT_REF, NULL_TREE, gnu_address), gnu_expr), gnu_address); } /* If it has an address clause and we are not defining it, mark it as an indirect object. Likewise for Stdcall objects that are imported. */ if ((!definition && Present (Address_Clause (gnat_entity))) || (Is_Imported (gnat_entity) && Has_Stdcall_Convention (gnat_entity))) { gnu_type = build_reference_type (gnu_type); gnu_size = NULL_TREE; gnu_expr = NULL_TREE; /* No point in taking the address of an initializing expression that isn't going to be used. */ used_by_ref = true; } /* If we are at top level and this object is of variable size, make the actual type a hidden pointer to the real type and make the initializer be a memory allocation and initialization. Likewise for objects we aren't defining (presumed to be external references from other packages), but there we do not set up an initialization. If the object's size overflows, make an allocator too, so that Storage_Error gets raised. Note that we will never free such memory, so we presume it never will get allocated. */ if (!allocatable_size_p (TYPE_SIZE_UNIT (gnu_type), global_bindings_p () || !definition || static_p) || (gnu_size && ! allocatable_size_p (gnu_size, global_bindings_p () || !definition || static_p))) { gnu_type = build_reference_type (gnu_type); gnu_size = NULL_TREE; used_by_ref = true; const_flag = true; /* In case this was a aliased object whose nominal subtype is unconstrained, the pointer above will be a thin pointer and build_allocator will automatically make the template. If we have a template initializer only (that we made above), pretend there is none and rely on what build_allocator creates again anyway. Otherwise (if we have a full initializer), get the data part and feed that to build_allocator. If we are elaborating a mutable object, tell build_allocator to ignore a possibly simpler size from the initializer, if any, as we must allocate the maximum possible size in this case. */ if (definition) { tree gnu_alloc_type = TREE_TYPE (gnu_type); if (TREE_CODE (gnu_alloc_type) == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (gnu_alloc_type)) { gnu_alloc_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (gnu_alloc_type))); if (TREE_CODE (gnu_expr) == CONSTRUCTOR && 1 == VEC_length (constructor_elt, CONSTRUCTOR_ELTS (gnu_expr))) gnu_expr = 0; else gnu_expr = build_component_ref (gnu_expr, NULL_TREE, TREE_CHAIN (TYPE_FIELDS (TREE_TYPE (gnu_expr))), false); } if (TREE_CODE (TYPE_SIZE_UNIT (gnu_alloc_type)) == INTEGER_CST && TREE_CONSTANT_OVERFLOW (TYPE_SIZE_UNIT (gnu_alloc_type)) && !Is_Imported (gnat_entity)) post_error ("Storage_Error will be raised at run-time?", gnat_entity); gnu_expr = build_allocator (gnu_alloc_type, gnu_expr, gnu_type, 0, 0, gnat_entity, mutable_p); } else { gnu_expr = NULL_TREE; const_flag = false; } } /* If this object would go into the stack and has an alignment larger than the default largest alignment, make a variable to hold the "aligning type" with a modified initial value, if any, then point to it and make that the value of this variable, which is now indirect. */ if (!global_bindings_p () && !static_p && definition && !imported_p && TYPE_ALIGN (gnu_type) > BIGGEST_ALIGNMENT) { tree gnu_new_type = make_aligning_type (gnu_type, TYPE_ALIGN (gnu_type), TYPE_SIZE_UNIT (gnu_type)); tree gnu_new_var; gnu_new_var = create_var_decl (create_concat_name (gnat_entity, "ALIGN"), NULL_TREE, gnu_new_type, NULL_TREE, false, false, false, false, NULL, gnat_entity); if (gnu_expr) add_stmt_with_node (build_binary_op (MODIFY_EXPR, NULL_TREE, build_component_ref (gnu_new_var, NULL_TREE, TYPE_FIELDS (gnu_new_type), false), gnu_expr), gnat_entity); gnu_type = build_reference_type (gnu_type); gnu_expr = build_unary_op (ADDR_EXPR, gnu_type, build_component_ref (gnu_new_var, NULL_TREE, TYPE_FIELDS (gnu_new_type), false)); gnu_size = NULL_TREE; used_by_ref = true; const_flag = true; } if (const_flag) gnu_type = build_qualified_type (gnu_type, (TYPE_QUALS (gnu_type) | TYPE_QUAL_CONST)); /* Convert the expression to the type of the object except in the case where the object's type is unconstrained or the object's type is a padded record whose field is of self-referential size. In the former case, converting will generate unnecessary evaluations of the CONSTRUCTOR to compute the size and in the latter case, we want to only copy the actual data. */ if (gnu_expr && TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type)) && !(TREE_CODE (gnu_type) == RECORD_TYPE && TYPE_IS_PADDING_P (gnu_type) && (CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS (gnu_type))))))) gnu_expr = convert (gnu_type, gnu_expr); /* If this name is external or there was a name specified, use it, unless this is a VMS exception object since this would conflict with the symbol we need to export in addition. Don't use the Interface_Name if there is an address clause (see CD30005). */ if (!Is_VMS_Exception (gnat_entity) && ((Present (Interface_Name (gnat_entity)) && No (Address_Clause (gnat_entity))) || (Is_Public (gnat_entity) && (!Is_Imported (gnat_entity) || Is_Exported (gnat_entity))))) gnu_ext_name = create_concat_name (gnat_entity, 0); /* If this is constant initialized to a static constant and the object has an aggregate type, force it to be statically allocated. */ if (const_flag && gnu_expr && TREE_CONSTANT (gnu_expr) && host_integerp (TYPE_SIZE_UNIT (gnu_type), 1) && (AGGREGATE_TYPE_P (gnu_type) && !(TREE_CODE (gnu_type) == RECORD_TYPE && TYPE_IS_PADDING_P (gnu_type)))) static_p = true; gnu_decl = create_var_decl (gnu_entity_id, gnu_ext_name, gnu_type, gnu_expr, const_flag, Is_Public (gnat_entity), imported_p || !definition, static_p, attr_list, gnat_entity); DECL_BY_REF_P (gnu_decl) = used_by_ref; DECL_POINTS_TO_READONLY_P (gnu_decl) = used_by_ref && inner_const_flag; if (TREE_CODE (gnu_decl) == VAR_DECL && renamed_obj) { SET_DECL_RENAMED_OBJECT (gnu_decl, renamed_obj); DECL_RENAMING_GLOBAL_P (gnu_decl) = global_bindings_p (); } /* If we have an address clause and we've made this indirect, it's not enough to merely mark the type as volatile since volatile references only conflict with other volatile references while this reference must conflict with all other references. So ensure that the dereferenced value has alias set 0. */ if (Present (Address_Clause (gnat_entity)) && used_by_ref) DECL_POINTER_ALIAS_SET (gnu_decl) = 0; if (definition && DECL_SIZE (gnu_decl) && get_block_jmpbuf_decl () && (TREE_CODE (DECL_SIZE (gnu_decl)) != INTEGER_CST || (flag_stack_check && !STACK_CHECK_BUILTIN && 0 < compare_tree_int (DECL_SIZE_UNIT (gnu_decl), STACK_CHECK_MAX_VAR_SIZE)))) add_stmt_with_node (build_call_1_expr (update_setjmp_buf_decl, build_unary_op (ADDR_EXPR, NULL_TREE, get_block_jmpbuf_decl ())), gnat_entity); /* If this is a public constant or we're not optimizing and we're not making a VAR_DECL for it, make one just for export or debugger use. Likewise if the address is taken or if the object or type is aliased. */ if (definition && TREE_CODE (gnu_decl) == CONST_DECL && (Is_Public (gnat_entity) || optimize == 0 || Address_Taken (gnat_entity) || Is_Aliased (gnat_entity) || Is_Aliased (Etype (gnat_entity)))) { tree gnu_corr_var = create_var_decl (gnu_entity_id, gnu_ext_name, gnu_type, gnu_expr, false, Is_Public (gnat_entity), false, static_p, NULL, gnat_entity); SET_DECL_CONST_CORRESPONDING_VAR (gnu_decl, gnu_corr_var); } /* If this is declared in a block that contains a block with an exception handler, we must force this variable in memory to suppress an invalid optimization. */ if (Has_Nested_Block_With_Handler (Scope (gnat_entity)) && Exception_Mechanism != Back_End_Exceptions) TREE_ADDRESSABLE (gnu_decl) = 1; /* Back-annotate the Alignment of the object if not already in the tree. Likewise for Esize if the object is of a constant size. But if the "object" is actually a pointer to an object, the alignment and size are the same as the type, so don't back-annotate the values for the pointer. */ if (!used_by_ref && Unknown_Alignment (gnat_entity)) Set_Alignment (gnat_entity, UI_From_Int (DECL_ALIGN (gnu_decl) / BITS_PER_UNIT)); if (!used_by_ref && Unknown_Esize (gnat_entity) && DECL_SIZE (gnu_decl)) { tree gnu_back_size = DECL_SIZE (gnu_decl); if (TREE_CODE (TREE_TYPE (gnu_decl)) == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (gnu_decl))) gnu_back_size = TYPE_SIZE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (TREE_TYPE (gnu_decl))))); Set_Esize (gnat_entity, annotate_value (gnu_back_size)); } } break; case E_Void: /* Return a TYPE_DECL for "void" that we previously made. */ gnu_decl = void_type_decl_node; break; case E_Enumeration_Type: /* A special case, for the types Character and Wide_Character in Standard, we do not list all the literals. So if the literals are not specified, make this an unsigned type. */ if (No (First_Literal (gnat_entity))) { gnu_type = make_unsigned_type (esize); break; } /* Normal case of non-character type, or non-Standard character type */ { /* Here we have a list of enumeral constants in First_Literal. We make a CONST_DECL for each and build into GNU_LITERAL_LIST the list to be places into TYPE_FIELDS. Each node in the list is a TREE_LIST node whose TREE_VALUE is the literal name and whose TREE_PURPOSE is the value of the literal. Esize contains the number of bits needed to represent the enumeral type, Type_Low_Bound also points to the first literal and Type_High_Bound points to the last literal. */ Entity_Id gnat_literal; tree gnu_literal_list = NULL_TREE; if (Is_Unsigned_Type (gnat_entity)) gnu_type = make_unsigned_type (esize); else gnu_type = make_signed_type (esize); TREE_SET_CODE (gnu_type, ENUMERAL_TYPE); for (gnat_literal = First_Literal (gnat_entity); Present (gnat_literal); gnat_literal = Next_Literal (gnat_literal)) { tree gnu_value = UI_To_gnu (Enumeration_Rep (gnat_literal), gnu_type); tree gnu_literal = create_var_decl (get_entity_name (gnat_literal), NULL_TREE, gnu_type, gnu_value, true, false, false, false, NULL, gnat_literal); save_gnu_tree (gnat_literal, gnu_literal, false); gnu_literal_list = tree_cons (DECL_NAME (gnu_literal), gnu_value, gnu_literal_list); } TYPE_VALUES (gnu_type) = nreverse (gnu_literal_list); /* Note that the bounds are updated at the end of this function because to avoid an infinite recursion when we get the bounds of this type, since those bounds are objects of this type. */ } break; case E_Signed_Integer_Type: case E_Ordinary_Fixed_Point_Type: case E_Decimal_Fixed_Point_Type: /* For integer types, just make a signed type the appropriate number of bits. */ gnu_type = make_signed_type (esize); break; case E_Modular_Integer_Type: /* For modular types, make the unsigned type of the proper number of bits and then set up the modulus, if required. */ { enum machine_mode mode; tree gnu_modulus; tree gnu_high = 0; if (Is_Packed_Array_Type (gnat_entity)) esize = UI_To_Int (RM_Size (gnat_entity)); /* Find the smallest mode at least ESIZE bits wide and make a class using that mode. */ for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); GET_MODE_BITSIZE (mode) < esize; mode = GET_MODE_WIDER_MODE (mode)) ; gnu_type = make_unsigned_type (GET_MODE_BITSIZE (mode)); TYPE_PACKED_ARRAY_TYPE_P (gnu_type) = Is_Packed_Array_Type (gnat_entity); /* Get the modulus in this type. If it overflows, assume it is because it is equal to 2**Esize. Note that there is no overflow checking done on unsigned type, so we detect the overflow by looking for a modulus of zero, which is otherwise invalid. */ gnu_modulus = UI_To_gnu (Modulus (gnat_entity), gnu_type); if (!integer_zerop (gnu_modulus)) { TYPE_MODULAR_P (gnu_type) = 1; SET_TYPE_MODULUS (gnu_type, gnu_modulus); gnu_high = fold (build2 (MINUS_EXPR, gnu_type, gnu_modulus, convert (gnu_type, integer_one_node))); } /* If we have to set TYPE_PRECISION different from its natural value, make a subtype to do do. Likewise if there is a modulus and it is not one greater than TYPE_MAX_VALUE. */ if (TYPE_PRECISION (gnu_type) != esize || (TYPE_MODULAR_P (gnu_type) && !tree_int_cst_equal (TYPE_MAX_VALUE (gnu_type), gnu_high))) { tree gnu_subtype = make_node (INTEGER_TYPE); TYPE_NAME (gnu_type) = create_concat_name (gnat_entity, "UMT"); TREE_TYPE (gnu_subtype) = gnu_type; TYPE_MIN_VALUE (gnu_subtype) = TYPE_MIN_VALUE (gnu_type); TYPE_MAX_VALUE (gnu_subtype) = TYPE_MODULAR_P (gnu_type) ? gnu_high : TYPE_MAX_VALUE (gnu_type); TYPE_PRECISION (gnu_subtype) = esize; TYPE_UNSIGNED (gnu_subtype) = 1; TYPE_EXTRA_SUBTYPE_P (gnu_subtype) = 1; TYPE_PACKED_ARRAY_TYPE_P (gnu_subtype) = Is_Packed_Array_Type (gnat_entity); layout_type (gnu_subtype); gnu_type = gnu_subtype; } } break; case E_Signed_Integer_Subtype: case E_Enumeration_Subtype: case E_Modular_Integer_Subtype: case E_Ordinary_Fixed_Point_Subtype: case E_Decimal_Fixed_Point_Subtype: /* For integral subtypes, we make a new INTEGER_TYPE. Note that we do not want to call build_range_type since we would like each subtype node to be distinct. This will be important when memory aliasing is implemented. The TREE_TYPE field of the INTEGER_TYPE we make points to the parent type; this fact is used by the arithmetic conversion functions. We elaborate the Ancestor_Subtype if it is not in the current unit and one of our bounds is non-static. We do this to ensure consistent naming in the case where several subtypes share the same bounds by always elaborating the first such subtype first, thus using its name. */ if (definition == 0 && Present (Ancestor_Subtype (gnat_entity)) && !In_Extended_Main_Code_Unit (Ancestor_Subtype (gnat_entity)) && (!Compile_Time_Known_Value (Type_Low_Bound (gnat_entity)) || !Compile_Time_Known_Value (Type_High_Bound (gnat_entity)))) gnat_to_gnu_entity (Ancestor_Subtype (gnat_entity), gnu_expr, definition); gnu_type = make_node (INTEGER_TYPE); if (Is_Packed_Array_Type (gnat_entity)) { esize = UI_To_Int (RM_Size (gnat_entity)); TYPE_PACKED_ARRAY_TYPE_P (gnu_type) = 1; } TYPE_PRECISION (gnu_type) = esize; TREE_TYPE (gnu_type) = get_unpadded_type (Etype (gnat_entity)); TYPE_MIN_VALUE (gnu_type) = convert (TREE_TYPE (gnu_type), elaborate_expression (Type_Low_Bound (gnat_entity), gnat_entity, get_identifier ("L"), definition, 1, Needs_Debug_Info (gnat_entity))); TYPE_MAX_VALUE (gnu_type) = convert (TREE_TYPE (gnu_type), elaborate_expression (Type_High_Bound (gnat_entity), gnat_entity, get_identifier ("U"), definition, 1, Needs_Debug_Info (gnat_entity))); /* One of the above calls might have caused us to be elaborated, so don't blow up if so. */ if (present_gnu_tree (gnat_entity)) { maybe_present = true; break; } TYPE_BIASED_REPRESENTATION_P (gnu_type) = Has_Biased_Representation (gnat_entity); /* This should be an unsigned type if the lower bound is constant and non-negative or if the base type is unsigned; a signed type otherwise. */ TYPE_UNSIGNED (gnu_type) = (TYPE_UNSIGNED (TREE_TYPE (gnu_type)) || (TREE_CODE (TYPE_MIN_VALUE (gnu_type)) == INTEGER_CST && TREE_INT_CST_HIGH (TYPE_MIN_VALUE (gnu_type)) >= 0) || TYPE_BIASED_REPRESENTATION_P (gnu_type) || Is_Unsigned_Type (gnat_entity)); layout_type (gnu_type); /* Inherit our alias set from what we're a subtype of. Subtypes are not different types and a pointer can designate any instance within a subtype hierarchy. */ copy_alias_set (gnu_type, TREE_TYPE (gnu_type)); /* If the type we are dealing with is to represent a packed array, we need to have the bits left justified on big-endian targets and right justified on little-endian targets. We also need to ensure that when the value is read (e.g. for comparison of two such values), we only get the good bits, since the unused bits are uninitialized. Both goals are accomplished by wrapping the modular value in an enclosing struct. */ if (Is_Packed_Array_Type (gnat_entity)) { tree gnu_field_type = gnu_type; tree gnu_field; TYPE_RM_SIZE_NUM (gnu_field_type) = UI_To_gnu (RM_Size (gnat_entity), bitsizetype); gnu_type = make_node (RECORD_TYPE); TYPE_NAME (gnu_type) = create_concat_name (gnat_entity, "JM"); TYPE_ALIGN (gnu_type) = TYPE_ALIGN (gnu_field_type); TYPE_PACKED (gnu_type) = 1; /* Create a stripped-down declaration of the original type, mainly for debugging. */ create_type_decl (get_entity_name (gnat_entity), gnu_field_type, NULL, true, debug_info_p, gnat_entity); /* Don't notify the field as "addressable", since we won't be taking it's address and it would prevent create_field_decl from making a bitfield. */ gnu_field = create_field_decl (get_identifier ("OBJECT"), gnu_field_type, gnu_type, 1, 0, 0, 0); finish_record_type (gnu_type, gnu_field, false, false); TYPE_JUSTIFIED_MODULAR_P (gnu_type) = 1; SET_TYPE_ADA_SIZE (gnu_type, bitsize_int (esize)); copy_alias_set (gnu_type, gnu_field_type); } break; case E_Floating_Point_Type: /* If this is a VAX floating-point type, use an integer of the proper size. All the operations will be handled with ASM statements. */ if (Vax_Float (gnat_entity)) { gnu_type = make_signed_type (esize); TYPE_VAX_FLOATING_POINT_P (gnu_type) = 1; SET_TYPE_DIGITS_VALUE (gnu_type, UI_To_gnu (Digits_Value (gnat_entity), sizetype)); break; } /* The type of the Low and High bounds can be our type if this is a type from Standard, so set them at the end of the function. */ gnu_type = make_node (REAL_TYPE); TYPE_PRECISION (gnu_type) = fp_size_to_prec (esize); layout_type (gnu_type); break; case E_Floating_Point_Subtype: if (Vax_Float (gnat_entity)) { gnu_type = gnat_to_gnu_type (Etype (gnat_entity)); break; } { if (definition == 0 && Present (Ancestor_Subtype (gnat_entity)) && !In_Extended_Main_Code_Unit (Ancestor_Subtype (gnat_entity)) && (!Compile_Time_Known_Value (Type_Low_Bound (gnat_entity)) || !Compile_Time_Known_Value (Type_High_Bound (gnat_entity)))) gnat_to_gnu_entity (Ancestor_Subtype (gnat_entity), gnu_expr, definition); gnu_type = make_node (REAL_TYPE); TREE_TYPE (gnu_type) = get_unpadded_type (Etype (gnat_entity)); TYPE_PRECISION (gnu_type) = fp_size_to_prec (esize); TYPE_MIN_VALUE (gnu_type) = convert (TREE_TYPE (gnu_type), elaborate_expression (Type_Low_Bound (gnat_entity), gnat_entity, get_identifier ("L"), definition, 1, Needs_Debug_Info (gnat_entity))); TYPE_MAX_VALUE (gnu_type) = convert (TREE_TYPE (gnu_type), elaborate_expression (Type_High_Bound (gnat_entity), gnat_entity, get_identifier ("U"), definition, 1, Needs_Debug_Info (gnat_entity))); /* One of the above calls might have caused us to be elaborated, so don't blow up if so. */ if (present_gnu_tree (gnat_entity)) { maybe_present = true; break; } layout_type (gnu_type); /* Inherit our alias set from what we're a subtype of, as for integer subtypes. */ copy_alias_set (gnu_type, TREE_TYPE (gnu_type)); } break; /* Array and String Types and Subtypes Unconstrained array types are represented by E_Array_Type and constrained array types are represented by E_Array_Subtype. There are no actual objects of an unconstrained array type; all we have are pointers to that type. The following fields are defined on array types and subtypes: Component_Type Component type of the array. Number_Dimensions Number of dimensions (an int). First_Index Type of first index. */ case E_String_Type: case E_Array_Type: { tree gnu_template_fields = NULL_TREE; tree gnu_template_type = make_node (RECORD_TYPE); tree gnu_ptr_template = build_pointer_type (gnu_template_type); tree gnu_fat_type = make_node (RECORD_TYPE); int ndim = Number_Dimensions (gnat_entity); int firstdim = (Convention (gnat_entity) == Convention_Fortran) ? ndim - 1 : 0; int nextdim = (Convention (gnat_entity) == Convention_Fortran) ? - 1 : 1; tree *gnu_index_types = (tree *) alloca (ndim * sizeof (tree *)); tree *gnu_temp_fields = (tree *) alloca (ndim * sizeof (tree *)); tree gnu_comp_size = 0; tree gnu_max_size = size_one_node; tree gnu_max_size_unit; int index; Entity_Id gnat_ind_subtype; Entity_Id gnat_ind_base_subtype; tree gnu_template_reference; tree tem; TYPE_NAME (gnu_template_type) = create_concat_name (gnat_entity, "XUB"); TYPE_NAME (gnu_fat_type) = create_concat_name (gnat_entity, "XUP"); TYPE_IS_FAT_POINTER_P (gnu_fat_type) = 1; TYPE_READONLY (gnu_template_type) = 1; /* Make a node for the array. If we are not defining the array suppress expanding incomplete types. */ gnu_type = make_node (UNCONSTRAINED_ARRAY_TYPE); if (!definition) defer_incomplete_level++, this_deferred = true; /* Build the fat pointer type. Use a "void *" object instead of a pointer to the array type since we don't have the array type yet (it will reference the fat pointer via the bounds). */ tem = chainon (chainon (NULL_TREE, create_field_decl (get_identifier ("P_ARRAY"), ptr_void_type_node, gnu_fat_type, 0, 0, 0, 0)), create_field_decl (get_identifier ("P_BOUNDS"), gnu_ptr_template, gnu_fat_type, 0, 0, 0, 0)); /* Make sure we can put this into a register. */ TYPE_ALIGN (gnu_fat_type) = MIN (BIGGEST_ALIGNMENT, 2 * POINTER_SIZE); finish_record_type (gnu_fat_type, tem, false, true); /* Build a reference to the template from a PLACEHOLDER_EXPR that is the fat pointer. This will be used to access the individual fields once we build them. */ tem = build3 (COMPONENT_REF, gnu_ptr_template, build0 (PLACEHOLDER_EXPR, gnu_fat_type), TREE_CHAIN (TYPE_FIELDS (gnu_fat_type)), NULL_TREE); gnu_template_reference = build_unary_op (INDIRECT_REF, gnu_template_type, tem); TREE_READONLY (gnu_template_reference) = 1; /* Now create the GCC type for each index and add the fields for that index to the template. */ for (index = firstdim, gnat_ind_subtype = First_Index (gnat_entity), gnat_ind_base_subtype = First_Index (Implementation_Base_Type (gnat_entity)); index < ndim && index >= 0; index += nextdim, gnat_ind_subtype = Next_Index (gnat_ind_subtype), gnat_ind_base_subtype = Next_Index (gnat_ind_base_subtype)) { char field_name[10]; tree gnu_ind_subtype = get_unpadded_type (Base_Type (Etype (gnat_ind_subtype))); tree gnu_base_subtype = get_unpadded_type (Etype (gnat_ind_base_subtype)); tree gnu_base_min = convert (sizetype, TYPE_MIN_VALUE (gnu_base_subtype)); tree gnu_base_max = convert (sizetype, TYPE_MAX_VALUE (gnu_base_subtype)); tree gnu_min_field, gnu_max_field, gnu_min, gnu_max; /* Make the FIELD_DECLs for the minimum and maximum of this type and then make extractions of that field from the template. */ sprintf (field_name, "LB%d", index); gnu_min_field = create_field_decl (get_identifier (field_name), gnu_ind_subtype, gnu_template_type, 0, 0, 0, 0); field_name[0] = 'U'; gnu_max_field = create_field_decl (get_identifier (field_name), gnu_ind_subtype, gnu_template_type, 0, 0, 0, 0); Sloc_to_locus (Sloc (gnat_entity), &DECL_SOURCE_LOCATION (gnu_min_field)); Sloc_to_locus (Sloc (gnat_entity), &DECL_SOURCE_LOCATION (gnu_max_field)); gnu_temp_fields[index] = chainon (gnu_min_field, gnu_max_field); /* We can't use build_component_ref here since the template type isn't complete yet. */ gnu_min = build3 (COMPONENT_REF, gnu_ind_subtype, gnu_template_reference, gnu_min_field, NULL_TREE); gnu_max = build3 (COMPONENT_REF, gnu_ind_subtype, gnu_template_reference, gnu_max_field, NULL_TREE); TREE_READONLY (gnu_min) = TREE_READONLY (gnu_max) = 1; /* Make a range type with the new ranges, but using the Ada subtype. Then we convert to sizetype. */ gnu_index_types[index] = create_index_type (convert (sizetype, gnu_min), convert (sizetype, gnu_max), build_range_type (gnu_ind_subtype, gnu_min, gnu_max)); /* Update the maximum size of the array, in elements. */ gnu_max_size = size_binop (MULT_EXPR, gnu_max_size, size_binop (PLUS_EXPR, size_one_node, size_binop (MINUS_EXPR, gnu_base_max, gnu_base_min))); TYPE_NAME (gnu_index_types[index]) = create_concat_name (gnat_entity, field_name); } for (index = 0; index < ndim; index++) gnu_template_fields = chainon (gnu_template_fields, gnu_temp_fields[index]); /* Install all the fields into the template. */ finish_record_type (gnu_template_type, gnu_template_fields, false, false); TYPE_READONLY (gnu_template_type) = 1; /* Now make the array of arrays and update the pointer to the array in the fat pointer. Note that it is the first field. */ tem = gnat_to_gnu_type (Component_Type (gnat_entity)); /* Get and validate any specified Component_Size, but if Packed, ignore it since the front end will have taken care of it. */ gnu_comp_size = validate_size (Component_Size (gnat_entity), tem, gnat_entity, (Is_Bit_Packed_Array (gnat_entity) ? TYPE_DECL : VAR_DECL), true, Has_Component_Size_Clause (gnat_entity)); if (Has_Atomic_Components (gnat_entity)) check_ok_for_atomic (tem, gnat_entity, true); /* If the component type is a RECORD_TYPE that has a self-referential size, use the maxium size. */ if (!gnu_comp_size && TREE_CODE (tem) == RECORD_TYPE && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (tem))) gnu_comp_size = max_size (TYPE_SIZE (tem), true); if (!Is_Bit_Packed_Array (gnat_entity) && gnu_comp_size) { tem = make_type_from_size (tem, gnu_comp_size, false); tem = maybe_pad_type (tem, gnu_comp_size, 0, gnat_entity, "C_PAD", false, definition, true); } if (Has_Volatile_Components (gnat_entity)) tem = build_qualified_type (tem, TYPE_QUALS (tem) | TYPE_QUAL_VOLATILE); /* If Component_Size is not already specified, annotate it with the size of the component. */ if (Unknown_Component_Size (gnat_entity)) Set_Component_Size (gnat_entity, annotate_value (TYPE_SIZE (tem))); gnu_max_size_unit = size_binop (MAX_EXPR, size_zero_node, size_binop (MULT_EXPR, gnu_max_size, TYPE_SIZE_UNIT (tem))); gnu_max_size = size_binop (MAX_EXPR, bitsize_zero_node, size_binop (MULT_EXPR, convert (bitsizetype, gnu_max_size), TYPE_SIZE (tem))); for (index = ndim - 1; index >= 0; index--) { tem = build_array_type (tem, gnu_index_types[index]); TYPE_MULTI_ARRAY_P (tem) = (index > 0); /* If the type below this an multi-array type, then this does not not have aliased components. ??? Otherwise, for now, we say that any component of aggregate type is addressable because the front end may take 'Reference of it. But we have to make it addressable if it must be passed by reference or it that is the default. */ TYPE_NONALIASED_COMPONENT (tem) = ((TREE_CODE (TREE_TYPE (tem)) == ARRAY_TYPE && TYPE_MULTI_ARRAY_P (TREE_TYPE (tem))) ? 1 : (!Has_Aliased_Components (gnat_entity) && !AGGREGATE_TYPE_P (TREE_TYPE (tem)))); } /* If an alignment is specified, use it if valid. But ignore it for types that represent the unpacked base type for packed arrays. */ if (No (Packed_Array_Type (gnat_entity)) && Known_Alignment (gnat_entity)) { gcc_assert (Present (Alignment (gnat_entity))); TYPE_ALIGN (tem) = validate_alignment (Alignment (gnat_entity), gnat_entity, TYPE_ALIGN (tem)); } TYPE_CONVENTION_FORTRAN_P (tem) = (Convention (gnat_entity) == Convention_Fortran); TREE_TYPE (TYPE_FIELDS (gnu_fat_type)) = build_pointer_type (tem); /* The result type is an UNCONSTRAINED_ARRAY_TYPE that indicates the corresponding fat pointer. */ TREE_TYPE (gnu_type) = TYPE_POINTER_TO (gnu_type) = TYPE_REFERENCE_TO (gnu_type) = gnu_fat_type; TYPE_MODE (gnu_type) = BLKmode; TYPE_ALIGN (gnu_type) = TYPE_ALIGN (tem); SET_TYPE_UNCONSTRAINED_ARRAY (gnu_fat_type, gnu_type); /* If the maximum size doesn't overflow, use it. */ if (TREE_CODE (gnu_max_size) == INTEGER_CST && !TREE_OVERFLOW (gnu_max_size)) TYPE_SIZE (tem) = size_binop (MIN_EXPR, gnu_max_size, TYPE_SIZE (tem)); if (TREE_CODE (gnu_max_size_unit) == INTEGER_CST && !TREE_OVERFLOW (gnu_max_size_unit)) TYPE_SIZE_UNIT (tem) = size_binop (MIN_EXPR, gnu_max_size_unit, TYPE_SIZE_UNIT (tem)); create_type_decl (create_concat_name (gnat_entity, "XUA"), tem, NULL, !Comes_From_Source (gnat_entity), debug_info_p, gnat_entity); /* Create a record type for the object and its template and set the template at a negative offset. */ tem = build_unc_object_type (gnu_template_type, tem, create_concat_name (gnat_entity, "XUT")); DECL_FIELD_OFFSET (TYPE_FIELDS (tem)) = size_binop (MINUS_EXPR, size_zero_node, byte_position (TREE_CHAIN (TYPE_FIELDS (tem)))); DECL_FIELD_OFFSET (TREE_CHAIN (TYPE_FIELDS (tem))) = size_zero_node; DECL_FIELD_BIT_OFFSET (TREE_CHAIN (TYPE_FIELDS (tem))) = bitsize_zero_node; SET_TYPE_UNCONSTRAINED_ARRAY (tem, gnu_type); TYPE_OBJECT_RECORD_TYPE (gnu_type) = tem; /* Give the thin pointer type a name. */ create_type_decl (create_concat_name (gnat_entity, "XUX"), build_pointer_type (tem), NULL, !Comes_From_Source (gnat_entity), debug_info_p, gnat_entity); } break; case E_String_Subtype: case E_Array_Subtype: /* This is the actual data type for array variables. Multidimensional arrays are implemented in the gnu tree as arrays of arrays. Note that for the moment arrays which have sparse enumeration subtypes as index components create sparse arrays, which is obviously space inefficient but so much easier to code for now. Also note that the subtype never refers to the unconstrained array type, which is somewhat at variance with Ada semantics. First check to see if this is simply a renaming of the array type. If so, the result is the array type. */ gnu_type = gnat_to_gnu_type (Etype (gnat_entity)); if (!Is_Constrained (gnat_entity)) break; else { int index; int array_dim = Number_Dimensions (gnat_entity); int first_dim = ((Convention (gnat_entity) == Convention_Fortran) ? array_dim - 1 : 0); int next_dim = (Convention (gnat_entity) == Convention_Fortran) ? -1 : 1; Entity_Id gnat_ind_subtype; Entity_Id gnat_ind_base_subtype; tree gnu_base_type = gnu_type; tree *gnu_index_type = (tree *) alloca (array_dim * sizeof (tree *)); tree gnu_comp_size = NULL_TREE; tree gnu_max_size = size_one_node; tree gnu_max_size_unit; bool need_index_type_struct = false; bool max_overflow = false; /* First create the gnu types for each index. Create types for debugging information to point to the index types if the are not integer types, have variable bounds, or are wider than sizetype. */ for (index = first_dim, gnat_ind_subtype = First_Index (gnat_entity), gnat_ind_base_subtype = First_Index (Implementation_Base_Type (gnat_entity)); index < array_dim && index >= 0; index += next_dim, gnat_ind_subtype = Next_Index (gnat_ind_subtype), gnat_ind_base_subtype = Next_Index (gnat_ind_base_subtype)) { tree gnu_index_subtype = get_unpadded_type (Etype (gnat_ind_subtype)); tree gnu_min = convert (sizetype, TYPE_MIN_VALUE (gnu_index_subtype)); tree gnu_max = convert (sizetype, TYPE_MAX_VALUE (gnu_index_subtype)); tree gnu_base_subtype = get_unpadded_type (Etype (gnat_ind_base_subtype)); tree gnu_base_min = convert (sizetype, TYPE_MIN_VALUE (gnu_base_subtype)); tree gnu_base_max = convert (sizetype, TYPE_MAX_VALUE (gnu_base_subtype)); tree gnu_base_type = get_base_type (gnu_base_subtype); tree gnu_base_base_min = convert (sizetype, TYPE_MIN_VALUE (gnu_base_type)); tree gnu_base_base_max = convert (sizetype, TYPE_MAX_VALUE (gnu_base_type)); tree gnu_high; tree gnu_this_max; /* If the minimum and maximum values both overflow in SIZETYPE, but the difference in the original type does not overflow in SIZETYPE, ignore the overflow indications. */ if ((TYPE_PRECISION (gnu_index_subtype) > TYPE_PRECISION (sizetype) || TYPE_UNSIGNED (gnu_index_subtype) != TYPE_UNSIGNED (sizetype)) && TREE_CODE (gnu_min) == INTEGER_CST && TREE_CODE (gnu_max) == INTEGER_CST && TREE_OVERFLOW (gnu_min) && TREE_OVERFLOW (gnu_max) && (!TREE_OVERFLOW (fold (build2 (MINUS_EXPR, gnu_index_subtype, TYPE_MAX_VALUE (gnu_index_subtype), TYPE_MIN_VALUE (gnu_index_subtype)))))) TREE_OVERFLOW (gnu_min) = TREE_OVERFLOW (gnu_max) = TREE_CONSTANT_OVERFLOW (gnu_min) = TREE_CONSTANT_OVERFLOW (gnu_max) = 0; /* Similarly, if the range is null, use bounds of 1..0 for the sizetype bounds. */ else if ((TYPE_PRECISION (gnu_index_subtype) > TYPE_PRECISION (sizetype) || TYPE_UNSIGNED (gnu_index_subtype) != TYPE_UNSIGNED (sizetype)) && TREE_CODE (gnu_min) == INTEGER_CST && TREE_CODE (gnu_max) == INTEGER_CST && (TREE_OVERFLOW (gnu_min) || TREE_OVERFLOW (gnu_max)) && tree_int_cst_lt (TYPE_MAX_VALUE (gnu_index_subtype), TYPE_MIN_VALUE (gnu_index_subtype))) gnu_min = size_one_node, gnu_max = size_zero_node; /* Now compute the size of this bound. We need to provide GCC with an upper bound to use but have to deal with the "superflat" case. There are three ways to do this. If we can prove that the array can never be superflat, we can just use the high bound of the index subtype. If we can prove that the low bound minus one can't overflow, we can do this as MAX (hb, lb - 1). Otherwise, we have to use the expression hb >= lb ? hb : lb - 1. */ gnu_high = size_binop (MINUS_EXPR, gnu_min, size_one_node); /* See if the base array type is already flat. If it is, we are probably compiling an ACVC test, but it will cause the code below to malfunction if we don't handle it specially. */ if (TREE_CODE (gnu_base_min) == INTEGER_CST && TREE_CODE (gnu_base_max) == INTEGER_CST && !TREE_CONSTANT_OVERFLOW (gnu_base_min) && !TREE_CONSTANT_OVERFLOW (gnu_base_max) && tree_int_cst_lt (gnu_base_max, gnu_base_min)) gnu_high = size_zero_node, gnu_min = size_one_node; /* If gnu_high is now an integer which overflowed, the array cannot be superflat. */ else if (TREE_CODE (gnu_high) == INTEGER_CST && TREE_OVERFLOW (gnu_high)) gnu_high = gnu_max; else if (TYPE_UNSIGNED (gnu_base_subtype) || TREE_CODE (gnu_high) == INTEGER_CST) gnu_high = size_binop (MAX_EXPR, gnu_max, gnu_high); else gnu_high = build_cond_expr (sizetype, build_binary_op (GE_EXPR, integer_type_node, gnu_max, gnu_min), gnu_max, gnu_high); gnu_index_type[index] = create_index_type (gnu_min, gnu_high, gnu_index_subtype); /* Also compute the maximum size of the array. Here we see if any constraint on the index type of the base type can be used in the case of self-referential bound on the index type of the subtype. We look for a non-"infinite" and non-self-referential bound from any type involved and handle each bound separately. */ if ((TREE_CODE (gnu_min) == INTEGER_CST && !TREE_OVERFLOW (gnu_min) && !operand_equal_p (gnu_min, gnu_base_base_min, 0)) || !CONTAINS_PLACEHOLDER_P (gnu_min)) gnu_base_min = gnu_min; if ((TREE_CODE (gnu_max) == INTEGER_CST && !TREE_OVERFLOW (gnu_max) && !operand_equal_p (gnu_max, gnu_base_base_max, 0)) || !CONTAINS_PLACEHOLDER_P (gnu_max)) gnu_base_max = gnu_max; if ((TREE_CODE (gnu_base_min) == INTEGER_CST && TREE_CONSTANT_OVERFLOW (gnu_base_min)) || operand_equal_p (gnu_base_min, gnu_base_base_min, 0) || (TREE_CODE (gnu_base_max) == INTEGER_CST && TREE_CONSTANT_OVERFLOW (gnu_base_max)) || operand_equal_p (gnu_base_max, gnu_base_base_max, 0)) max_overflow = true; gnu_base_min = size_binop (MAX_EXPR, gnu_base_min, gnu_min); gnu_base_max = size_binop (MIN_EXPR, gnu_base_max, gnu_max); gnu_this_max = size_binop (MAX_EXPR, size_binop (PLUS_EXPR, size_one_node, size_binop (MINUS_EXPR, gnu_base_max, gnu_base_min)), size_zero_node); if (TREE_CODE (gnu_this_max) == INTEGER_CST && TREE_CONSTANT_OVERFLOW (gnu_this_max)) max_overflow = true; gnu_max_size = size_binop (MULT_EXPR, gnu_max_size, gnu_this_max); if (!integer_onep (TYPE_MIN_VALUE (gnu_index_subtype)) || (TREE_CODE (TYPE_MAX_VALUE (gnu_index_subtype)) != INTEGER_CST) || TREE_CODE (gnu_index_subtype) != INTEGER_TYPE || (TREE_TYPE (gnu_index_subtype) && (TREE_CODE (TREE_TYPE (gnu_index_subtype)) != INTEGER_TYPE)) || TYPE_BIASED_REPRESENTATION_P (gnu_index_subtype) || (TYPE_PRECISION (gnu_index_subtype) > TYPE_PRECISION (sizetype))) need_index_type_struct = true; } /* Then flatten: create the array of arrays. */ gnu_type = gnat_to_gnu_type (Component_Type (gnat_entity)); /* One of the above calls might have caused us to be elaborated, so don't blow up if so. */ if (present_gnu_tree (gnat_entity)) { maybe_present = true; break; } /* Get and validate any specified Component_Size, but if Packed, ignore it since the front end will have taken care of it. */ gnu_comp_size = validate_size (Component_Size (gnat_entity), gnu_type, gnat_entity, (Is_Bit_Packed_Array (gnat_entity) ? TYPE_DECL : VAR_DECL), true, Has_Component_Size_Clause (gnat_entity)); /* If the component type is a RECORD_TYPE that has a self-referential size, use the maxium size. */ if (!gnu_comp_size && TREE_CODE (gnu_type) == RECORD_TYPE && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type))) gnu_comp_size = max_size (TYPE_SIZE (gnu_type), true); if (!Is_Bit_Packed_Array (gnat_entity) && gnu_comp_size) { gnu_type = make_type_from_size (gnu_type, gnu_comp_size, false); gnu_type = maybe_pad_type (gnu_type, gnu_comp_size, 0, gnat_entity, "C_PAD", false, definition, true); } if (Has_Volatile_Components (Base_Type (gnat_entity))) gnu_type = build_qualified_type (gnu_type, (TYPE_QUALS (gnu_type) | TYPE_QUAL_VOLATILE)); gnu_max_size_unit = size_binop (MULT_EXPR, gnu_max_size, TYPE_SIZE_UNIT (gnu_type)); gnu_max_size = size_binop (MULT_EXPR, convert (bitsizetype, gnu_max_size), TYPE_SIZE (gnu_type)); for (index = array_dim - 1; index >= 0; index --) { gnu_type = build_array_type (gnu_type, gnu_index_type[index]); TYPE_MULTI_ARRAY_P (gnu_type) = (index > 0); /* If the type below this an multi-array type, then this does not not have aliased components. ??? Otherwise, for now, we say that any component of aggregate type is addressable because the front end may take 'Reference of it. But we have to make it addressable if it must be passed by reference or it that is the default. */ TYPE_NONALIASED_COMPONENT (gnu_type) = ((TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type))) ? 1 : (!Has_Aliased_Components (gnat_entity) && !AGGREGATE_TYPE_P (TREE_TYPE (gnu_type)))); } /* If we are at file level and this is a multi-dimensional array, we need to make a variable corresponding to the stride of the inner dimensions. */ if (global_bindings_p () && array_dim > 1) { tree gnu_str_name = get_identifier ("ST"); tree gnu_arr_type; for (gnu_arr_type = TREE_TYPE (gnu_type); TREE_CODE (gnu_arr_type) == ARRAY_TYPE; gnu_arr_type = TREE_TYPE (gnu_arr_type), gnu_str_name = concat_id_with_name (gnu_str_name, "ST")) { tree eltype = TREE_TYPE (gnu_arr_type); TYPE_SIZE (gnu_arr_type) = elaborate_expression_1 (gnat_entity, gnat_entity, TYPE_SIZE (gnu_arr_type), gnu_str_name, definition, 0); /* ??? For now, store the size as a multiple of the alignment of the element type in bytes so that we can see the alignment from the tree. */ TYPE_SIZE_UNIT (gnu_arr_type) = build_binary_op (MULT_EXPR, sizetype, elaborate_expression_1 (gnat_entity, gnat_entity, build_binary_op (EXACT_DIV_EXPR, sizetype, TYPE_SIZE_UNIT (gnu_arr_type), size_int (TYPE_ALIGN (eltype) / BITS_PER_UNIT)), concat_id_with_name (gnu_str_name, "A_U"), definition, 0), size_int (TYPE_ALIGN (eltype) / BITS_PER_UNIT)); } } /* If we need to write out a record type giving the names of the bounds, do it now. */ if (need_index_type_struct && debug_info_p) { tree gnu_bound_rec_type = make_node (RECORD_TYPE); tree gnu_field_list = NULL_TREE; tree gnu_field; TYPE_NAME (gnu_bound_rec_type) = create_concat_name (gnat_entity, "XA"); for (index = array_dim - 1; index >= 0; index--) { tree gnu_type_name = TYPE_NAME (TYPE_INDEX_TYPE (gnu_index_type[index])); if (TREE_CODE (gnu_type_name) == TYPE_DECL) gnu_type_name = DECL_NAME (gnu_type_name); gnu_field = create_field_decl (gnu_type_name, integer_type_node, gnu_bound_rec_type, 0, NULL_TREE, NULL_TREE, 0); TREE_CHAIN (gnu_field) = gnu_field_list; gnu_field_list = gnu_field; } finish_record_type (gnu_bound_rec_type, gnu_field_list, false, false); } TYPE_CONVENTION_FORTRAN_P (gnu_type) = (Convention (gnat_entity) == Convention_Fortran); TYPE_PACKED_ARRAY_TYPE_P (gnu_type) = Is_Packed_Array_Type (gnat_entity); /* If our size depends on a placeholder and the maximum size doesn't overflow, use it. */ if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type)) && !(TREE_CODE (gnu_max_size) == INTEGER_CST && TREE_OVERFLOW (gnu_max_size)) && !(TREE_CODE (gnu_max_size_unit) == INTEGER_CST && TREE_OVERFLOW (gnu_max_size_unit)) && !max_overflow) { TYPE_SIZE (gnu_type) = size_binop (MIN_EXPR, gnu_max_size, TYPE_SIZE (gnu_type)); TYPE_SIZE_UNIT (gnu_type) = size_binop (MIN_EXPR, gnu_max_size_unit, TYPE_SIZE_UNIT (gnu_type)); } /* Set our alias set to that of our base type. This gives all array subtypes the same alias set. */ copy_alias_set (gnu_type, gnu_base_type); } /* If this is a packed type, make this type the same as the packed array type, but do some adjusting in the type first. */ if (Present (Packed_Array_Type (gnat_entity))) { Entity_Id gnat_index; tree gnu_inner_type; /* First finish the type we had been making so that we output debugging information for it */ gnu_type = build_qualified_type (gnu_type, (TYPE_QUALS (gnu_type) | (TYPE_QUAL_VOLATILE * Treat_As_Volatile (gnat_entity)))); gnu_decl = create_type_decl (gnu_entity_id, gnu_type, attr_list, !Comes_From_Source (gnat_entity), debug_info_p, gnat_entity); if (!Comes_From_Source (gnat_entity)) DECL_ARTIFICIAL (gnu_decl) = 1; /* Save it as our equivalent in case the call below elaborates this type again. */ save_gnu_tree (gnat_entity, gnu_decl, false); gnu_decl = gnat_to_gnu_entity (Packed_Array_Type (gnat_entity), NULL_TREE, 0); this_made_decl = true; gnu_inner_type = gnu_type = TREE_TYPE (gnu_decl); save_gnu_tree (gnat_entity, NULL_TREE, false); while (TREE_CODE (gnu_inner_type) == RECORD_TYPE && (TYPE_JUSTIFIED_MODULAR_P (gnu_inner_type) || TYPE_IS_PADDING_P (gnu_inner_type))) gnu_inner_type = TREE_TYPE (TYPE_FIELDS (gnu_inner_type)); /* We need to point the type we just made to our index type so the actual bounds can be put into a template. */ if ((TREE_CODE (gnu_inner_type) == ARRAY_TYPE && !TYPE_ACTUAL_BOUNDS (gnu_inner_type)) || (TREE_CODE (gnu_inner_type) == INTEGER_TYPE && !TYPE_HAS_ACTUAL_BOUNDS_P (gnu_inner_type))) { if (TREE_CODE (gnu_inner_type) == INTEGER_TYPE) { /* The TYPE_ACTUAL_BOUNDS field is also used for the modulus. If it is, we need to make another type. */ if (TYPE_MODULAR_P (gnu_inner_type)) { tree gnu_subtype; gnu_subtype = make_node (INTEGER_TYPE); TREE_TYPE (gnu_subtype) = gnu_inner_type; TYPE_MIN_VALUE (gnu_subtype) = TYPE_MIN_VALUE (gnu_inner_type); TYPE_MAX_VALUE (gnu_subtype) = TYPE_MAX_VALUE (gnu_inner_type); TYPE_PRECISION (gnu_subtype) = TYPE_PRECISION (gnu_inner_type); TYPE_UNSIGNED (gnu_subtype) = TYPE_UNSIGNED (gnu_inner_type); TYPE_EXTRA_SUBTYPE_P (gnu_subtype) = 1; layout_type (gnu_subtype); gnu_inner_type = gnu_subtype; } TYPE_HAS_ACTUAL_BOUNDS_P (gnu_inner_type) = 1; } SET_TYPE_ACTUAL_BOUNDS (gnu_inner_type, NULL_TREE); for (gnat_index = First_Index (gnat_entity); Present (gnat_index); gnat_index = Next_Index (gnat_index)) SET_TYPE_ACTUAL_BOUNDS (gnu_inner_type, tree_cons (NULL_TREE, get_unpadded_type (Etype (gnat_index)), TYPE_ACTUAL_BOUNDS (gnu_inner_type))); if (Convention (gnat_entity) != Convention_Fortran) SET_TYPE_ACTUAL_BOUNDS (gnu_inner_type, nreverse (TYPE_ACTUAL_BOUNDS (gnu_inner_type))); if (TREE_CODE (gnu_type) == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (gnu_type)) TREE_TYPE (TYPE_FIELDS (gnu_type)) = gnu_inner_type; } } /* Abort if packed array with no packed array type field set. */ else gcc_assert (!Is_Packed (gnat_entity)); break; case E_String_Literal_Subtype: /* Create the type for a string literal. */ { Entity_Id gnat_full_type = (IN (Ekind (Etype (gnat_entity)), Private_Kind) && Present (Full_View (Etype (gnat_entity))) ? Full_View (Etype (gnat_entity)) : Etype (gnat_entity)); tree gnu_string_type = get_unpadded_type (gnat_full_type); tree gnu_string_array_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_string_type)))); tree gnu_string_index_type = get_base_type (TREE_TYPE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_string_array_type)))); tree gnu_lower_bound = convert (gnu_string_index_type, gnat_to_gnu (String_Literal_Low_Bound (gnat_entity))); int length = UI_To_Int (String_Literal_Length (gnat_entity)); tree gnu_length = ssize_int (length - 1); tree gnu_upper_bound = build_binary_op (PLUS_EXPR, gnu_string_index_type, gnu_lower_bound, convert (gnu_string_index_type, gnu_length)); tree gnu_range_type = build_range_type (gnu_string_index_type, gnu_lower_bound, gnu_upper_bound); tree gnu_index_type = create_index_type (convert (sizetype, TYPE_MIN_VALUE (gnu_range_type)), convert (sizetype, TYPE_MAX_VALUE (gnu_range_type)), gnu_range_type); gnu_type = build_array_type (gnat_to_gnu_type (Component_Type (gnat_entity)), gnu_index_type); copy_alias_set (gnu_type, gnu_string_type); } break; /* Record Types and Subtypes The following fields are defined on record types: Has_Discriminants True if the record has discriminants First_Discriminant Points to head of list of discriminants First_Entity Points to head of list of fields Is_Tagged_Type True if the record is tagged Implementation of Ada records and discriminated records: A record type definition is transformed into the equivalent of a C struct definition. The fields that are the discriminants which are found in the Full_Type_Declaration node and the elements of the Component_List found in the Record_Type_Definition node. The Component_List can be a recursive structure since each Variant of the Variant_Part of the Component_List has a Component_List. Processing of a record type definition comprises starting the list of field declarations here from the discriminants and the calling the function components_to_record to add the rest of the fields from the component list and return the gnu type node. The function components_to_record will call itself recursively as it traverses the tree. */ case E_Record_Type: if (Has_Complex_Representation (gnat_entity)) { gnu_type = build_complex_type (get_unpadded_type (Etype (Defining_Entity (First (Component_Items (Component_List (Type_Definition (Declaration_Node (gnat_entity))))))))); break; } { Node_Id full_definition = Declaration_Node (gnat_entity); Node_Id record_definition = Type_Definition (full_definition); Entity_Id gnat_field; tree gnu_field; tree gnu_field_list = NULL_TREE; tree gnu_get_parent; int packed = (Is_Packed (gnat_entity) ? 1 : (Component_Alignment (gnat_entity) == Calign_Storage_Unit) ? -1 : 0); bool has_rep = Has_Specified_Layout (gnat_entity); bool all_rep = has_rep; bool is_extension = (Is_Tagged_Type (gnat_entity) && Nkind (record_definition) == N_Derived_Type_Definition); /* See if all fields have a rep clause. Stop when we find one that doesn't. */ for (gnat_field = First_Entity (gnat_entity); Present (gnat_field) && all_rep; gnat_field = Next_Entity (gnat_field)) if ((Ekind (gnat_field) == E_Component || Ekind (gnat_field) == E_Discriminant) && No (Component_Clause (gnat_field))) all_rep = false; /* If this is a record extension, go a level further to find the record definition. Also, verify we have a Parent_Subtype. */ if (is_extension) { if (!type_annotate_only || Present (Record_Extension_Part (record_definition))) record_definition = Record_Extension_Part (record_definition); gcc_assert (type_annotate_only || Present (Parent_Subtype (gnat_entity))); } /* Make a node for the record. If we are not defining the record, suppress expanding incomplete types. We use the same RECORD_TYPE as for a dummy type and reset TYPE_DUMMY_P to show it's no longer a dummy. It is very tempting to delay resetting this bit until we are done with completing the type, e.g. to let possible intermediate elaboration of access types designating the record know it is not complete and arrange for update_pointer_to to fix things up later. It would be wrong, however, because dummy types are expected only to be created for Ada incomplete or private types, which is not what we have here. Doing so would make other parts of gigi think we are dealing with a really incomplete or private type, and have nasty side effects, typically on the generation of the associated debugging information. */ gnu_type = make_dummy_type (gnat_entity); TYPE_DUMMY_P (gnu_type) = 0; if (TREE_CODE (TYPE_NAME (gnu_type)) == TYPE_DECL && debug_info_p) DECL_IGNORED_P (TYPE_NAME (gnu_type)) = 0; TYPE_ALIGN (gnu_type) = 0; TYPE_PACKED (gnu_type) = packed || has_rep; if (!definition) defer_incomplete_level++, this_deferred = true; /* If both a size and rep clause was specified, put the size in the record type now so that it can get the proper mode. */ if (has_rep && Known_Esize (gnat_entity)) TYPE_SIZE (gnu_type) = UI_To_gnu (Esize (gnat_entity), sizetype); /* Always set the alignment here so that it can be used to set the mode, if it is making the alignment stricter. If it is invalid, it will be checked again below. If this is to be Atomic, choose a default alignment of a word unless we know the size and it's smaller. */ if (Known_Alignment (gnat_entity)) TYPE_ALIGN (gnu_type) = validate_alignment (Alignment (gnat_entity), gnat_entity, 0); else if (Is_Atomic (gnat_entity)) TYPE_ALIGN (gnu_type) = (esize >= BITS_PER_WORD ? BITS_PER_WORD : 1 << (floor_log2 (esize - 1) + 1)); /* If we have a Parent_Subtype, make a field for the parent. If this record has rep clauses, force the position to zero. */ if (Present (Parent_Subtype (gnat_entity))) { Entity_Id gnat_parent = Parent_Subtype (gnat_entity); tree gnu_parent; /* A major complexity here is that the parent subtype will reference our discriminants in its Discriminant_Constraint list. But those must reference the parent component of this record which is of the parent subtype we have not built yet! To break the circle we first build a dummy COMPONENT_REF which represents the "get to the parent" operation and initialize each of those discriminants to a COMPONENT_REF of the above dummy parent referencing the corresponding discriminant of the base type of the parent subtype. */ gnu_get_parent = build3 (COMPONENT_REF, void_type_node, build0 (PLACEHOLDER_EXPR, gnu_type), build_decl (FIELD_DECL, NULL_TREE, NULL_TREE), NULL_TREE); if (Has_Discriminants (gnat_entity)) for (gnat_field = First_Stored_Discriminant (gnat_entity); Present (gnat_field); gnat_field = Next_Stored_Discriminant (gnat_field)) if (Present (Corresponding_Discriminant (gnat_field))) save_gnu_tree (gnat_field, build3 (COMPONENT_REF, get_unpadded_type (Etype (gnat_field)), gnu_get_parent, gnat_to_gnu_field_decl (Corresponding_Discriminant (gnat_field)), NULL_TREE), true); /* Then we build the parent subtype. */ gnu_parent = gnat_to_gnu_type (gnat_parent); /* Finally we fix up both kinds of twisted COMPONENT_REF we have initially built. The discriminants must reference the fields of the parent subtype and not those of its base type for the placeholder machinery to properly work. */ if (Has_Discriminants (gnat_entity)) for (gnat_field = First_Stored_Discriminant (gnat_entity); Present (gnat_field); gnat_field = Next_Stored_Discriminant (gnat_field)) if (Present (Corresponding_Discriminant (gnat_field))) { Entity_Id field = Empty; for (field = First_Stored_Discriminant (gnat_parent); Present (field); field = Next_Stored_Discriminant (field)) if (same_discriminant_p (gnat_field, field)) break; gcc_assert (Present (field)); TREE_OPERAND (get_gnu_tree (gnat_field), 1) = gnat_to_gnu_field_decl (field); } /* The "get to the parent" COMPONENT_REF must be given its proper type... */ TREE_TYPE (gnu_get_parent) = gnu_parent; /* ...and reference the _parent field of this record. */ gnu_field_list = create_field_decl (get_identifier (Get_Name_String (Name_uParent)), gnu_parent, gnu_type, 0, has_rep ? TYPE_SIZE (gnu_parent) : 0, has_rep ? bitsize_zero_node : 0, 1); DECL_INTERNAL_P (gnu_field_list) = 1; TREE_OPERAND (gnu_get_parent, 1) = gnu_field_list; } /* Make the fields for the discriminants and put them into the record unless it's an Unchecked_Union. */ if (Has_Discriminants (gnat_entity)) for (gnat_field = First_Stored_Discriminant (gnat_entity); Present (gnat_field); gnat_field = Next_Stored_Discriminant (gnat_field)) { /* If this is a record extension and this discriminant is the renaming of another discriminant, we've already handled the discriminant above. */ if (Present (Parent_Subtype (gnat_entity)) && Present (Corresponding_Discriminant (gnat_field))) continue; gnu_field = gnat_to_gnu_field (gnat_field, gnu_type, packed, definition); /* Make an expression using a PLACEHOLDER_EXPR from the FIELD_DECL node just created and link that with the corresponding GNAT defining identifier. Then add to the list of fields. */ save_gnu_tree (gnat_field, build3 (COMPONENT_REF, TREE_TYPE (gnu_field), build0 (PLACEHOLDER_EXPR, DECL_CONTEXT (gnu_field)), gnu_field, NULL_TREE), true); if (!Is_Unchecked_Union (gnat_entity)) { TREE_CHAIN (gnu_field) = gnu_field_list; gnu_field_list = gnu_field; } } /* Put the discriminants into the record (backwards), so we can know the appropriate discriminant to use for the names of the variants. */ TYPE_FIELDS (gnu_type) = gnu_field_list; /* Add the listed fields into the record and finish up. */ components_to_record (gnu_type, Component_List (record_definition), gnu_field_list, packed, definition, NULL, false, all_rep, this_deferred, Is_Unchecked_Union (gnat_entity)); if (this_deferred) { debug_deferred = true; defer_debug_level++; defer_debug_incomplete_list = tree_cons (NULL_TREE, gnu_type, defer_debug_incomplete_list); } /* We used to remove the associations of the discriminants and _Parent for validity checking, but we may need them if there's Freeze_Node for a subtype used in this record. */ TYPE_VOLATILE (gnu_type) = Treat_As_Volatile (gnat_entity); TYPE_BY_REFERENCE_P (gnu_type) = Is_By_Reference_Type (gnat_entity); /* If it is a tagged record force the type to BLKmode to insure that these objects will always be placed in memory. Do the same thing for limited record types. */ if (Is_Tagged_Type (gnat_entity) || Is_Limited_Record (gnat_entity)) TYPE_MODE (gnu_type) = BLKmode; /* If this is a derived type, we must make the alias set of this type the same as that of the type we are derived from. We assume here that the other type is already frozen. */ if (Etype (gnat_entity) != gnat_entity && !(Is_Private_Type (Etype (gnat_entity)) && Full_View (Etype (gnat_entity)) == gnat_entity)) copy_alias_set (gnu_type, gnat_to_gnu_type (Etype (gnat_entity))); /* Fill in locations of fields. */ annotate_rep (gnat_entity, gnu_type); /* If there are any entities in the chain corresponding to components that we did not elaborate, ensure we elaborate their types if they are Itypes. */ for (gnat_temp = First_Entity (gnat_entity); Present (gnat_temp); gnat_temp = Next_Entity (gnat_temp)) if ((Ekind (gnat_temp) == E_Component || Ekind (gnat_temp) == E_Discriminant) && Is_Itype (Etype (gnat_temp)) && !present_gnu_tree (gnat_temp)) gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, 0); } break; case E_Class_Wide_Subtype: /* If an equivalent type is present, that is what we should use. Otherwise, fall through to handle this like a record subtype since it may have constraints. */ if (Present (Equivalent_Type (gnat_entity))) { gnu_decl = gnat_to_gnu_entity (Equivalent_Type (gnat_entity), NULL_TREE, 0); maybe_present = true; break; } /* ... fall through ... */ case E_Record_Subtype: /* If Cloned_Subtype is Present it means this record subtype has identical layout to that type or subtype and we should use that GCC type for this one. The front end guarantees that the component list is shared. */ if (Present (Cloned_Subtype (gnat_entity))) { gnu_decl = gnat_to_gnu_entity (Cloned_Subtype (gnat_entity), NULL_TREE, 0); maybe_present = true; } /* Otherwise, first ensure the base type is elaborated. Then, if we are changing the type, make a new type with each field having the type of the field in the new subtype but having the position computed by transforming every discriminant reference according to the constraints. We don't see any difference between private and nonprivate type here since derivations from types should have been deferred until the completion of the private type. */ else { Entity_Id gnat_base_type = Implementation_Base_Type (gnat_entity); tree gnu_base_type; tree gnu_orig_type; if (!definition) defer_incomplete_level++, this_deferred = true; /* Get the base type initially for its alignment and sizes. But if it is a padded type, we do all the other work with the unpadded type. */ gnu_type = gnu_orig_type = gnu_base_type = gnat_to_gnu_type (gnat_base_type); if (TREE_CODE (gnu_type) == RECORD_TYPE && TYPE_IS_PADDING_P (gnu_type)) gnu_type = gnu_orig_type = TREE_TYPE (TYPE_FIELDS (gnu_type)); if (present_gnu_tree (gnat_entity)) { maybe_present = true; break; } /* When the type has discriminants, and these discriminants affect the shape of what it built, factor them in. If we are making a subtype of an Unchecked_Union (must be an Itype), just return the type. We can't just use Is_Constrained because private subtypes without discriminants of full types with discriminants with default expressions are Is_Constrained but aren't constrained! */ if (IN (Ekind (gnat_base_type), Record_Kind) && !Is_For_Access_Subtype (gnat_entity) && !Is_Unchecked_Union (gnat_base_type) && Is_Constrained (gnat_entity) && Stored_Constraint (gnat_entity) != No_Elist && Present (Discriminant_Constraint (gnat_entity))) { Entity_Id gnat_field; tree gnu_field_list = 0; tree gnu_pos_list = compute_field_positions (gnu_orig_type, NULL_TREE, size_zero_node, bitsize_zero_node, BIGGEST_ALIGNMENT); tree gnu_subst_list = substitution_list (gnat_entity, gnat_base_type, NULL_TREE, definition); tree gnu_temp; gnu_type = make_node (RECORD_TYPE); TYPE_NAME (gnu_type) = gnu_entity_id; TYPE_STUB_DECL (gnu_type) = create_type_decl (NULL_TREE, gnu_type, NULL, false, false, gnat_entity); TYPE_ALIGN (gnu_type) = TYPE_ALIGN (gnu_base_type); for (gnat_field = First_Entity (gnat_entity); Present (gnat_field); gnat_field = Next_Entity (gnat_field)) if ((Ekind (gnat_field) == E_Component || Ekind (gnat_field) == E_Discriminant) && (Underlying_Type (Scope (Original_Record_Component (gnat_field))) == gnat_base_type) && (No (Corresponding_Discriminant (gnat_field)) || !Is_Tagged_Type (gnat_base_type))) { tree gnu_old_field = gnat_to_gnu_field_decl (Original_Record_Component (gnat_field)); tree gnu_offset = TREE_VALUE (purpose_member (gnu_old_field, gnu_pos_list)); tree gnu_pos = TREE_PURPOSE (gnu_offset); tree gnu_bitpos = TREE_VALUE (TREE_VALUE (gnu_offset)); tree gnu_field_type = gnat_to_gnu_type (Etype (gnat_field)); tree gnu_size = TYPE_SIZE (gnu_field_type); tree gnu_new_pos = 0; unsigned int offset_align = tree_low_cst (TREE_PURPOSE (TREE_VALUE (gnu_offset)), 1); tree gnu_field; /* If there was a component clause, the field types must be the same for the type and subtype, so copy the data from the old field to avoid recomputation here. Also if the field is justified modular and the optimization in gnat_to_gnu_field was applied. */ if (Present (Component_Clause (Original_Record_Component (gnat_field))) || (TREE_CODE (gnu_field_type) == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (gnu_field_type) && TREE_TYPE (TYPE_FIELDS (gnu_field_type)) == TREE_TYPE (gnu_old_field))) { gnu_size = DECL_SIZE (gnu_old_field); gnu_field_type = TREE_TYPE (gnu_old_field); } /* If this was a bitfield, get the size from the old field. Also ensure the type can be placed into a bitfield. */ else if (DECL_BIT_FIELD (gnu_old_field)) { gnu_size = DECL_SIZE (gnu_old_field); if (TYPE_MODE (gnu_field_type) == BLKmode && TREE_CODE (gnu_field_type) == RECORD_TYPE && host_integerp (TYPE_SIZE (gnu_field_type), 1)) gnu_field_type = make_packable_type (gnu_field_type); } if (CONTAINS_PLACEHOLDER_P (gnu_pos)) for (gnu_temp = gnu_subst_list; gnu_temp; gnu_temp = TREE_CHAIN (gnu_temp)) gnu_pos = substitute_in_expr (gnu_pos, TREE_PURPOSE (gnu_temp), TREE_VALUE (gnu_temp)); /* If the size is now a constant, we can set it as the size of the field when we make it. Otherwise, we need to deal with it specially. */ if (TREE_CONSTANT (gnu_pos)) gnu_new_pos = bit_from_pos (gnu_pos, gnu_bitpos); gnu_field = create_field_decl (DECL_NAME (gnu_old_field), gnu_field_type, gnu_type, 0, gnu_size, gnu_new_pos, !DECL_NONADDRESSABLE_P (gnu_old_field)); if (!TREE_CONSTANT (gnu_pos)) { normalize_offset (&gnu_pos, &gnu_bitpos, offset_align); DECL_FIELD_OFFSET (gnu_field) = gnu_pos; DECL_FIELD_BIT_OFFSET (gnu_field) = gnu_bitpos; SET_DECL_OFFSET_ALIGN (gnu_field, offset_align); DECL_SIZE (gnu_field) = gnu_size; DECL_SIZE_UNIT (gnu_field) = convert (sizetype, size_binop (CEIL_DIV_EXPR, gnu_size, bitsize_unit_node)); layout_decl (gnu_field, DECL_OFFSET_ALIGN (gnu_field)); } DECL_INTERNAL_P (gnu_field) = DECL_INTERNAL_P (gnu_old_field); SET_DECL_ORIGINAL_FIELD (gnu_field, (DECL_ORIGINAL_FIELD (gnu_old_field) ? DECL_ORIGINAL_FIELD (gnu_old_field) : gnu_old_field)); DECL_DISCRIMINANT_NUMBER (gnu_field) = DECL_DISCRIMINANT_NUMBER (gnu_old_field); TREE_THIS_VOLATILE (gnu_field) = TREE_THIS_VOLATILE (gnu_old_field); TREE_CHAIN (gnu_field) = gnu_field_list; gnu_field_list = gnu_field; save_gnu_tree (gnat_field, gnu_field, false); } /* Now go through the entities again looking for Itypes that we have not elaborated but should (e.g., Etypes of fields that have Original_Components). */ for (gnat_field = First_Entity (gnat_entity); Present (gnat_field); gnat_field = Next_Entity (gnat_field)) if ((Ekind (gnat_field) == E_Discriminant || Ekind (gnat_field) == E_Component) && !present_gnu_tree (Etype (gnat_field))) gnat_to_gnu_entity (Etype (gnat_field), NULL_TREE, 0); finish_record_type (gnu_type, nreverse (gnu_field_list), true, false); /* Now set the size, alignment and alias set of the new type to match that of the old one, doing any substitutions, as above. */ TYPE_ALIGN (gnu_type) = TYPE_ALIGN (gnu_base_type); TYPE_SIZE (gnu_type) = TYPE_SIZE (gnu_base_type); TYPE_SIZE_UNIT (gnu_type) = TYPE_SIZE_UNIT (gnu_base_type); SET_TYPE_ADA_SIZE (gnu_type, TYPE_ADA_SIZE (gnu_base_type)); copy_alias_set (gnu_type, gnu_base_type); if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type))) for (gnu_temp = gnu_subst_list; gnu_temp; gnu_temp = TREE_CHAIN (gnu_temp)) TYPE_SIZE (gnu_type) = substitute_in_expr (TYPE_SIZE (gnu_type), TREE_PURPOSE (gnu_temp), TREE_VALUE (gnu_temp)); if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE_UNIT (gnu_type))) for (gnu_temp = gnu_subst_list; gnu_temp; gnu_temp = TREE_CHAIN (gnu_temp)) TYPE_SIZE_UNIT (gnu_type) = substitute_in_expr (TYPE_SIZE_UNIT (gnu_type), TREE_PURPOSE (gnu_temp), TREE_VALUE (gnu_temp)); if (CONTAINS_PLACEHOLDER_P (TYPE_ADA_SIZE (gnu_type))) for (gnu_temp = gnu_subst_list; gnu_temp; gnu_temp = TREE_CHAIN (gnu_temp)) SET_TYPE_ADA_SIZE (gnu_type, substitute_in_expr (TYPE_ADA_SIZE (gnu_type), TREE_PURPOSE (gnu_temp), TREE_VALUE (gnu_temp))); /* Recompute the mode of this record type now that we know its actual size. */ compute_record_mode (gnu_type); /* Fill in locations of fields. */ annotate_rep (gnat_entity, gnu_type); } /* If we've made a new type, record it and make an XVS type to show what this is a subtype of. Some debuggers require the XVS type to be output first, so do it in that order. */ if (gnu_type != gnu_orig_type) { if (debug_info_p) { tree gnu_subtype_marker = make_node (RECORD_TYPE); tree gnu_orig_name = TYPE_NAME (gnu_orig_type); if (TREE_CODE (gnu_orig_name) == TYPE_DECL) gnu_orig_name = DECL_NAME (gnu_orig_name); TYPE_NAME (gnu_subtype_marker) = create_concat_name (gnat_entity, "XVS"); finish_record_type (gnu_subtype_marker, create_field_decl (gnu_orig_name, integer_type_node, gnu_subtype_marker, 0, NULL_TREE, NULL_TREE, 0), false, false); } TYPE_VOLATILE (gnu_type) = Treat_As_Volatile (gnat_entity); TYPE_NAME (gnu_type) = gnu_entity_id; TYPE_STUB_DECL (gnu_type) = create_type_decl (TYPE_NAME (gnu_type), gnu_type, NULL, true, debug_info_p, gnat_entity); } /* Otherwise, go down all the components in the new type and make them equivalent to those in the base type. */ else for (gnat_temp = First_Entity (gnat_entity); Present (gnat_temp); gnat_temp = Next_Entity (gnat_temp)) if ((Ekind (gnat_temp) == E_Discriminant && !Is_Unchecked_Union (gnat_base_type)) || Ekind (gnat_temp) == E_Component) save_gnu_tree (gnat_temp, gnat_to_gnu_field_decl (Original_Record_Component (gnat_temp)), false); } break; case E_Access_Subprogram_Type: case E_Anonymous_Access_Subprogram_Type: /* If we are not defining this entity, and we have incomplete entities being processed above us, make a dummy type and fill it in later. */ if (!definition && defer_incomplete_level != 0) { struct incomplete *p = (struct incomplete *) xmalloc (sizeof (struct incomplete)); gnu_type = build_pointer_type (make_dummy_type (Directly_Designated_Type (gnat_entity))); gnu_decl = create_type_decl (gnu_entity_id, gnu_type, attr_list, !Comes_From_Source (gnat_entity), debug_info_p, gnat_entity); save_gnu_tree (gnat_entity, gnu_decl, false); this_made_decl = saved = true; p->old_type = TREE_TYPE (gnu_type); p->full_type = Directly_Designated_Type (gnat_entity); p->next = defer_incomplete_list; defer_incomplete_list = p; break; } /* ... fall through ... */ case E_Allocator_Type: case E_Access_Type: case E_Access_Attribute_Type: case E_Anonymous_Access_Type: case E_General_Access_Type: { Entity_Id gnat_desig_type = Directly_Designated_Type (gnat_entity); Entity_Id gnat_desig_full = ((IN (Ekind (Etype (gnat_desig_type)), Incomplete_Or_Private_Kind)) ? Full_View (gnat_desig_type) : 0); /* We want to know if we'll be seeing the freeze node for any incomplete type we may be pointing to. */ bool in_main_unit = (Present (gnat_desig_full) ? In_Extended_Main_Code_Unit (gnat_desig_full) : In_Extended_Main_Code_Unit (gnat_desig_type)); bool got_fat_p = false; bool made_dummy = false; tree gnu_desig_type = NULL_TREE; enum machine_mode p_mode = mode_for_size (esize, MODE_INT, 0); if (!targetm.valid_pointer_mode (p_mode)) p_mode = ptr_mode; if (No (gnat_desig_full) && (Ekind (gnat_desig_type) == E_Class_Wide_Type || (Ekind (gnat_desig_type) == E_Class_Wide_Subtype && Present (Equivalent_Type (gnat_desig_type))))) { if (Present (Equivalent_Type (gnat_desig_type))) { gnat_desig_full = Equivalent_Type (gnat_desig_type); if (IN (Ekind (gnat_desig_full), Incomplete_Or_Private_Kind)) gnat_desig_full = Full_View (gnat_desig_full); } else if (IN (Ekind (Root_Type (gnat_desig_type)), Incomplete_Or_Private_Kind)) gnat_desig_full = Full_View (Root_Type (gnat_desig_type)); } if (Present (gnat_desig_full) && Is_Concurrent_Type (gnat_desig_full)) gnat_desig_full = Corresponding_Record_Type (gnat_desig_full); /* If either the designated type or its full view is an unconstrained array subtype, replace it with the type it's a subtype of. This avoids problems with multiple copies of unconstrained array types. */ if (Ekind (gnat_desig_type) == E_Array_Subtype && !Is_Constrained (gnat_desig_type)) gnat_desig_type = Etype (gnat_desig_type); if (Present (gnat_desig_full) && Ekind (gnat_desig_full) == E_Array_Subtype && !Is_Constrained (gnat_desig_full)) gnat_desig_full = Etype (gnat_desig_full); /* If the designated type is a subtype of an incomplete record type, use the parent type to avoid order of elaboration issues. This can lose some code efficiency, but there is no alternative. */ if (Present (gnat_desig_full) && Ekind (gnat_desig_full) == E_Record_Subtype && Ekind (Etype (gnat_desig_full)) == E_Record_Type) gnat_desig_full = Etype (gnat_desig_full); /* LLVM local begin gcc 125602 */ /* If we are pointing to an incomplete type whose completion is an unconstrained array, make a fat pointer type. The two types in our fields will be pointers to dummy nodes and will be replaced in update_pointer_to. Similarly, if the type itself is a dummy type or an unconstrained array. Also make a dummy TYPE_OBJECT_RECORD_TYPE in case we have any thin pointers to it. */ /* LLVM local end gcc 125602 */ if ((Present (gnat_desig_full) && Is_Array_Type (gnat_desig_full) && !Is_Constrained (gnat_desig_full)) || (present_gnu_tree (gnat_desig_type) && TYPE_IS_DUMMY_P (TREE_TYPE (get_gnu_tree (gnat_desig_type))) && Is_Array_Type (gnat_desig_type) && !Is_Constrained (gnat_desig_type)) || (present_gnu_tree (gnat_desig_type) && (TREE_CODE (TREE_TYPE (get_gnu_tree (gnat_desig_type))) == UNCONSTRAINED_ARRAY_TYPE) && !(TYPE_POINTER_TO (TREE_TYPE (get_gnu_tree (gnat_desig_type))))) || (No (gnat_desig_full) && !in_main_unit && defer_incomplete_level && !present_gnu_tree (gnat_desig_type) && Is_Array_Type (gnat_desig_type) && !Is_Constrained (gnat_desig_type))) { tree gnu_old = (present_gnu_tree (gnat_desig_type) ? gnat_to_gnu_type (gnat_desig_type) : make_dummy_type (gnat_desig_type)); tree fields; /* Show the dummy we get will be a fat pointer. */ got_fat_p = made_dummy = true; /* If the call above got something that has a pointer, that pointer is our type. This could have happened either because the type was elaborated or because somebody else executed the code below. */ gnu_type = TYPE_POINTER_TO (gnu_old); if (!gnu_type) { /* LLVM local begin gcc 125602 */ tree gnu_template_type = make_node (ENUMERAL_TYPE); tree gnu_ptr_template = build_pointer_type (gnu_template_type); tree gnu_array_type = make_node (ENUMERAL_TYPE); tree gnu_ptr_array = build_pointer_type (gnu_array_type); TYPE_NAME (gnu_template_type) = concat_id_with_name (get_entity_name (gnat_desig_type), "XUB"); TYPE_DUMMY_P (gnu_template_type) = 1; TYPE_NAME (gnu_array_type) = concat_id_with_name (get_entity_name (gnat_desig_type), "XUA"); TYPE_DUMMY_P (gnu_array_type) = 1; /* LLVM local end gcc 125602 */ gnu_type = make_node (RECORD_TYPE); SET_TYPE_UNCONSTRAINED_ARRAY (gnu_type, gnu_old); TYPE_POINTER_TO (gnu_old) = gnu_type; Sloc_to_locus (Sloc (gnat_entity), &input_location); fields = chainon (chainon (NULL_TREE, create_field_decl (get_identifier ("P_ARRAY"), /* LLVM local begin gcc 125602 */ gnu_ptr_array, gnu_type, 0, 0, 0, 0)), /* LLVM local end gcc 125602 */ create_field_decl (get_identifier ("P_BOUNDS"), /* LLVM local gcc 125602 */ gnu_ptr_template, gnu_type, 0, 0, 0, 0)); /* Make sure we can place this into a register. */ TYPE_ALIGN (gnu_type) = MIN (BIGGEST_ALIGNMENT, 2 * POINTER_SIZE); TYPE_IS_FAT_POINTER_P (gnu_type) = 1; finish_record_type (gnu_type, fields, false, true); TYPE_OBJECT_RECORD_TYPE (gnu_old) = make_node (RECORD_TYPE); TYPE_NAME (TYPE_OBJECT_RECORD_TYPE (gnu_old)) = concat_id_with_name (get_entity_name (gnat_desig_type), "XUT"); TYPE_DUMMY_P (TYPE_OBJECT_RECORD_TYPE (gnu_old)) = 1; } } /* If we already know what the full type is, use it. */ else if (Present (gnat_desig_full) && present_gnu_tree (gnat_desig_full)) gnu_desig_type = TREE_TYPE (get_gnu_tree (gnat_desig_full)); /* Get the type of the thing we are to point to and build a pointer to it. If it is a reference to an incomplete or private type with a full view that is a record, make a dummy type node and get the actual type later when we have verified it is safe. */ else if (!in_main_unit && !present_gnu_tree (gnat_desig_type) && Present (gnat_desig_full) && !present_gnu_tree (gnat_desig_full) && Is_Record_Type (gnat_desig_full)) { gnu_desig_type = make_dummy_type (gnat_desig_type); made_dummy = true; } /* Likewise if we are pointing to a record or array and we are to defer elaborating incomplete types. We do this since this access type may be the full view of some private type. Note that the unconstrained array case is handled above. */ else if ((!in_main_unit || imported_p) && defer_incomplete_level != 0 && !present_gnu_tree (gnat_desig_type) && ((Is_Record_Type (gnat_desig_type) || Is_Array_Type (gnat_desig_type)) || (Present (gnat_desig_full) && (Is_Record_Type (gnat_desig_full) || Is_Array_Type (gnat_desig_full))))) { gnu_desig_type = make_dummy_type (gnat_desig_type); made_dummy = true; } else if (gnat_desig_type == gnat_entity) { gnu_type = build_pointer_type_for_mode (make_node (VOID_TYPE), p_mode, No_Strict_Aliasing (gnat_entity)); TREE_TYPE (gnu_type) = TYPE_POINTER_TO (gnu_type) = gnu_type; } else gnu_desig_type = gnat_to_gnu_type (gnat_desig_type); /* It is possible that the above call to gnat_to_gnu_type resolved our type. If so, just return it. */ if (present_gnu_tree (gnat_entity)) { maybe_present = true; break; } /* If we have a GCC type for the designated type, possibly modify it if we are pointing only to constant objects and then make a pointer to it. Don't do this for unconstrained arrays. */ if (!gnu_type && gnu_desig_type) { if (Is_Access_Constant (gnat_entity) && TREE_CODE (gnu_desig_type) != UNCONSTRAINED_ARRAY_TYPE) { gnu_desig_type = build_qualified_type (gnu_desig_type, TYPE_QUALS (gnu_desig_type) | TYPE_QUAL_CONST); /* Some extra processing is required if we are building a pointer to an incomplete type (in the GCC sense). We might have such a type if we just made a dummy, or directly out of the call to gnat_to_gnu_type above if we are processing an access type for a record component designating the record type itself. */ if (TYPE_MODE (gnu_desig_type) == VOIDmode) { /* We must ensure that the pointer to variant we make will be processed by update_pointer_to when the initial type is completed. Pretend we made a dummy and let further processing act as usual. */ made_dummy = true; /* We must ensure that update_pointer_to will not retrieve the dummy variant when building a properly qualified version of the complete type. We take advantage of the fact that get_qualified_type is requiring TYPE_NAMEs to match to influence build_qualified_type and then also update_pointer_to here. */ TYPE_NAME (gnu_desig_type) = create_concat_name (gnat_desig_type, "INCOMPLETE_CST"); } } gnu_type = build_pointer_type_for_mode (gnu_desig_type, p_mode, No_Strict_Aliasing (gnat_entity)); } /* If we are not defining this object and we made a dummy pointer, save our current definition, evaluate the actual type, and replace the tentative type we made with the actual one. If we are to defer actually looking up the actual type, make an entry in the deferred list. */ if (!in_main_unit && made_dummy) { tree gnu_old_type = TYPE_FAT_POINTER_P (gnu_type) ? TYPE_UNCONSTRAINED_ARRAY (gnu_type) : TREE_TYPE (gnu_type); if (esize == POINTER_SIZE && (got_fat_p || TYPE_FAT_POINTER_P (gnu_type))) gnu_type = build_pointer_type (TYPE_OBJECT_RECORD_TYPE (TYPE_UNCONSTRAINED_ARRAY (gnu_type))); gnu_decl = create_type_decl (gnu_entity_id, gnu_type, attr_list, !Comes_From_Source (gnat_entity), debug_info_p, gnat_entity); save_gnu_tree (gnat_entity, gnu_decl, false); this_made_decl = saved = true; if (defer_incomplete_level == 0) /* Note that the call to gnat_to_gnu_type here might have updated gnu_old_type directly, in which case it is not a dummy type any more when we get into update_pointer_to. This may happen for instance when the designated type is a record type, because their elaboration starts with an initial node from make_dummy_type, which may yield the same node as the one we got. Besides, variants of this non-dummy type might have been created along the way. update_pointer_to is expected to properly take care of those situations. */ update_pointer_to (TYPE_MAIN_VARIANT (gnu_old_type), gnat_to_gnu_type (gnat_desig_type)); else { struct incomplete *p = (struct incomplete *) xmalloc (sizeof (struct incomplete)); p->old_type = gnu_old_type; p->full_type = gnat_desig_type; p->next = defer_incomplete_list; defer_incomplete_list = p; } } } break; case E_Access_Protected_Subprogram_Type: case E_Anonymous_Access_Protected_Subprogram_Type: if (type_annotate_only && No (Equivalent_Type (gnat_entity))) gnu_type = build_pointer_type (void_type_node); else /* The runtime representation is the equivalent type. */ gnu_type = gnat_to_gnu_type (Equivalent_Type (gnat_entity)); if (Is_Itype (Directly_Designated_Type (gnat_entity)) && !present_gnu_tree (Directly_Designated_Type (gnat_entity)) && No (Freeze_Node (Directly_Designated_Type (gnat_entity))) && !Is_Record_Type (Scope (Directly_Designated_Type (gnat_entity)))) gnat_to_gnu_entity (Directly_Designated_Type (gnat_entity), NULL_TREE, 0); break; case E_Access_Subtype: /* We treat this as identical to its base type; any constraint is meaningful only to the front end. The designated type must be elaborated as well, if it does not have its own freeze node. Designated (sub)types created for constrained components of records with discriminants are not frozen by the front end and thus not elaborated by gigi, because their use may appear before the base type is frozen, and because it is not clear that they are needed anywhere in Gigi. With the current model, there is no correct place where they could be elaborated. */ gnu_type = gnat_to_gnu_type (Etype (gnat_entity)); if (Is_Itype (Directly_Designated_Type (gnat_entity)) && !present_gnu_tree (Directly_Designated_Type (gnat_entity)) && Is_Frozen (Directly_Designated_Type (gnat_entity)) && No (Freeze_Node (Directly_Designated_Type (gnat_entity)))) { /* If we are not defining this entity, and we have incomplete entities being processed above us, make a dummy type and elaborate it later. */ if (!definition && defer_incomplete_level != 0) { struct incomplete *p = (struct incomplete *) xmalloc (sizeof (struct incomplete)); tree gnu_ptr_type = build_pointer_type (make_dummy_type (Directly_Designated_Type (gnat_entity))); p->old_type = TREE_TYPE (gnu_ptr_type); p->full_type = Directly_Designated_Type (gnat_entity); p->next = defer_incomplete_list; defer_incomplete_list = p; } else if (IN (Ekind (Base_Type (Directly_Designated_Type (gnat_entity))), Incomplete_Or_Private_Kind)) ; else gnat_to_gnu_entity (Directly_Designated_Type (gnat_entity), NULL_TREE, 0); } maybe_present = true; break; /* Subprogram Entities The following access functions are defined for subprograms (functions or procedures): First_Formal The first formal parameter. Is_Imported Indicates that the subprogram has appeared in an INTERFACE or IMPORT pragma. For now we assume that the external language is C. Is_Inlined True if the subprogram is to be inlined. In addition for function subprograms we have: Etype Return type of the function. Each parameter is first checked by calling must_pass_by_ref on its type to determine if it is passed by reference. For parameters which are copied in, if they are Ada IN OUT or OUT parameters, their return value becomes part of a record which becomes the return type of the function (C function - note that this applies only to Ada procedures so there is no Ada return type). Additional code to store back the parameters will be generated on the caller side. This transformation is done here, not in the front-end. The intended result of the transformation can be seen from the equivalent source rewritings that follow: struct temp {int a,b}; procedure P (A,B: IN OUT ...) is temp P (int A,B) { .. .. end P; return {A,B}; } procedure call { temp t; P(X,Y); t = P(X,Y); X = t.a , Y = t.b; } For subprogram types we need to perform mainly the same conversions to GCC form that are needed for procedures and function declarations. The only difference is that at the end, we make a type declaration instead of a function declaration. */ case E_Subprogram_Type: case E_Function: case E_Procedure: { /* The first GCC parameter declaration (a PARM_DECL node). The PARM_DECL nodes are chained through the TREE_CHAIN field, so this actually is the head of this parameter list. */ tree gnu_param_list = NULL_TREE; /* The type returned by a function. If the subprogram is a procedure this type should be void_type_node. */ tree gnu_return_type = void_type_node; /* List of fields in return type of procedure with copy in copy out parameters. */ tree gnu_field_list = NULL_TREE; /* Non-null for subprograms containing parameters passed by copy in copy out (Ada IN OUT or OUT parameters not passed by reference), in which case it is the list of nodes used to specify the values of the in out/out parameters that are returned as a record upon procedure return. The TREE_PURPOSE of an element of this list is a field of the record and the TREE_VALUE is the PARM_DECL corresponding to that field. This list will be saved in the TYPE_CI_CO_LIST field of the FUNCTION_TYPE node we create. */ tree gnu_return_list = NULL_TREE; /* If an import pragma asks to map this subprogram to a GCC builtin, this is the builtin DECL node. */ tree gnu_builtin_decl = NULL_TREE; Entity_Id gnat_param; bool inline_flag = Is_Inlined (gnat_entity); bool public_flag = Is_Public (gnat_entity); bool extern_flag = (Is_Public (gnat_entity) && !definition) || imported_p; bool pure_flag = Is_Pure (gnat_entity); bool volatile_flag = No_Return (gnat_entity); bool returns_by_ref = false; bool returns_unconstrained = false; bool returns_by_target_ptr = false; tree gnu_ext_name = create_concat_name (gnat_entity, 0); bool has_copy_in_out = false; int parmnum; if (kind == E_Subprogram_Type && !definition) /* A parameter may refer to this type, so defer completion of any incomplete types. */ defer_incomplete_level++, this_deferred = true; /* If the subprogram has an alias, it is probably inherited, so we can use the original one. If the original "subprogram" is actually an enumeration literal, it may be the first use of its type, so we must elaborate that type now. */ if (Present (Alias (gnat_entity))) { if (Ekind (Alias (gnat_entity)) == E_Enumeration_Literal) gnat_to_gnu_entity (Etype (Alias (gnat_entity)), NULL_TREE, 0); gnu_decl = gnat_to_gnu_entity (Alias (gnat_entity), gnu_expr, 0); /* Elaborate any Itypes in the parameters of this entity. */ for (gnat_temp = First_Formal (gnat_entity); Present (gnat_temp); gnat_temp = Next_Formal_With_Extras (gnat_temp)) if (Is_Itype (Etype (gnat_temp))) gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, 0); break; } /* If this subprogram is expectedly bound to a GCC builtin, fetch the corresponding DECL node. We still want the parameter associations to take place because the proper generation of calls depends on it (a GNAT parameter without a corresponding GCC tree has a very specific meaning), so we don't just break here. */ if (Convention (gnat_entity) == Convention_Intrinsic) gnu_builtin_decl = builtin_decl_for (gnu_ext_name); /* ??? What if we don't find the builtin node above ? warn ? err ? In the current state we neither warn nor err, and calls will just be handled as for regular subprograms. */ if (kind == E_Function || kind == E_Subprogram_Type) gnu_return_type = gnat_to_gnu_type (Etype (gnat_entity)); /* If this function returns by reference, make the actual return type of this function the pointer and mark the decl. */ if (Returns_By_Ref (gnat_entity)) { returns_by_ref = true; gnu_return_type = build_pointer_type (gnu_return_type); } /* If the Mechanism is By_Reference, ensure the return type uses the machine's by-reference mechanism, which may not the same as above (e.g., it might be by passing a fake parameter). */ else if (kind == E_Function && Mechanism (gnat_entity) == By_Reference) { gnu_return_type = copy_type (gnu_return_type); TREE_ADDRESSABLE (gnu_return_type) = 1; } /* If we are supposed to return an unconstrained array, actually return a fat pointer and make a note of that. Return a pointer to an unconstrained record of variable size. */ else if (TREE_CODE (gnu_return_type) == UNCONSTRAINED_ARRAY_TYPE) { gnu_return_type = TREE_TYPE (gnu_return_type); returns_unconstrained = true; } /* If the type requires a transient scope, the result is allocated on the secondary stack, so the result type of the function is just a pointer. */ else if (Requires_Transient_Scope (Etype (gnat_entity))) { gnu_return_type = build_pointer_type (gnu_return_type); returns_unconstrained = true; } /* If the type is a padded type and the underlying type would not be passed by reference or this function has a foreign convention, return the underlying type. */ else if (TREE_CODE (gnu_return_type) == RECORD_TYPE && TYPE_IS_PADDING_P (gnu_return_type) && (!default_pass_by_ref (TREE_TYPE (TYPE_FIELDS (gnu_return_type))) || Has_Foreign_Convention (gnat_entity))) gnu_return_type = TREE_TYPE (TYPE_FIELDS (gnu_return_type)); /* If the return type is unconstrained, that means it must have a maximum size. We convert the function into a procedure and its caller will pass a pointer to an object of that maximum size as the first parameter when we call the function. */ if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_return_type))) { returns_by_target_ptr = true; gnu_param_list = create_param_decl (get_identifier ("TARGET"), build_reference_type (gnu_return_type), true); gnu_return_type = void_type_node; } /* If the return type has a size that overflows, we cannot have a function that returns that type. This usage doesn't make sense anyway, so give an error here. */ if (TYPE_SIZE_UNIT (gnu_return_type) && TREE_CONSTANT (TYPE_SIZE_UNIT (gnu_return_type)) && TREE_OVERFLOW (TYPE_SIZE_UNIT (gnu_return_type))) { post_error ("cannot return type whose size overflows", gnat_entity); gnu_return_type = copy_node (gnu_return_type); TYPE_SIZE (gnu_return_type) = bitsize_zero_node; TYPE_SIZE_UNIT (gnu_return_type) = size_zero_node; TYPE_MAIN_VARIANT (gnu_return_type) = gnu_return_type; TYPE_NEXT_VARIANT (gnu_return_type) = NULL_TREE; } /* Look at all our parameters and get the type of each. While doing this, build a copy-out structure if we need one. */ for (gnat_param = First_Formal (gnat_entity), parmnum = 0; Present (gnat_param); gnat_param = Next_Formal_With_Extras (gnat_param), parmnum++) { tree gnu_param_name = get_entity_name (gnat_param); tree gnu_param_type = gnat_to_gnu_type (Etype (gnat_param)); tree gnu_param, gnu_field; bool by_ref_p = false; bool by_descr_p = false; bool by_component_ptr_p = false; bool copy_in_copy_out_flag = false; bool req_by_copy = false, req_by_ref = false; /* Builtins are expanded inline and there is no real call sequence involved. so the type expected by the underlying expander is always the type of each argument "as is". */ if (gnu_builtin_decl) req_by_copy = 1; /* Otherwise, see if a Mechanism was supplied that forced this parameter to be passed one way or another. */ else if (Is_Valued_Procedure (gnat_entity) && parmnum == 0) req_by_copy = true; else if (Mechanism (gnat_param) == Default) ; else if (Mechanism (gnat_param) == By_Copy) req_by_copy = true; else if (Mechanism (gnat_param) == By_Reference) req_by_ref = true; else if (Mechanism (gnat_param) <= By_Descriptor) by_descr_p = true; else if (Mechanism (gnat_param) > 0) { if (TREE_CODE (gnu_param_type) == UNCONSTRAINED_ARRAY_TYPE || TREE_CODE (TYPE_SIZE (gnu_param_type)) != INTEGER_CST || 0 < compare_tree_int (TYPE_SIZE (gnu_param_type), Mechanism (gnat_param))) req_by_ref = true; else req_by_copy = true; } else post_error ("unsupported mechanism for&", gnat_param); /* If this is either a foreign function or if the underlying type won't be passed by reference, strip off possible padding type. */ if (TREE_CODE (gnu_param_type) == RECORD_TYPE && TYPE_IS_PADDING_P (gnu_param_type) && (req_by_ref || Has_Foreign_Convention (gnat_entity) || (!must_pass_by_ref (TREE_TYPE (TYPE_FIELDS (gnu_param_type))) && (req_by_copy || !default_pass_by_ref (TREE_TYPE (TYPE_FIELDS (gnu_param_type))))))) gnu_param_type = TREE_TYPE (TYPE_FIELDS (gnu_param_type)); /* If this is an IN parameter it is read-only, so make a variant of the type that is read-only. ??? However, if this is an unconstrained array, that type can be very complex. So skip it for now. Likewise for any other self-referential type. */ if (Ekind (gnat_param) == E_In_Parameter && TREE_CODE (gnu_param_type) != UNCONSTRAINED_ARRAY_TYPE && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_param_type))) gnu_param_type = build_qualified_type (gnu_param_type, (TYPE_QUALS (gnu_param_type) | TYPE_QUAL_CONST)); /* For foreign conventions, pass arrays as a pointer to the underlying type. First check for unconstrained array and get the underlying array. Then get the component type and build a pointer to it. */ if (Has_Foreign_Convention (gnat_entity) && TREE_CODE (gnu_param_type) == UNCONSTRAINED_ARRAY_TYPE) gnu_param_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_param_type)))); if (by_descr_p) gnu_param_type = build_pointer_type (build_vms_descriptor (gnu_param_type, Mechanism (gnat_param), gnat_entity)); else if (Has_Foreign_Convention (gnat_entity) && !req_by_copy && TREE_CODE (gnu_param_type) == ARRAY_TYPE) { /* Strip off any multi-dimensional entries, then strip off the last array to get the component type. */ while (TREE_CODE (TREE_TYPE (gnu_param_type)) == ARRAY_TYPE && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_param_type))) gnu_param_type = TREE_TYPE (gnu_param_type); by_component_ptr_p = true; gnu_param_type = TREE_TYPE (gnu_param_type); if (Ekind (gnat_param) == E_In_Parameter) gnu_param_type = build_qualified_type (gnu_param_type, (TYPE_QUALS (gnu_param_type) | TYPE_QUAL_CONST)); gnu_param_type = build_pointer_type (gnu_param_type); } /* Fat pointers are passed as thin pointers for foreign conventions. */ else if (Has_Foreign_Convention (gnat_entity) && TYPE_FAT_POINTER_P (gnu_param_type)) gnu_param_type = make_type_from_size (gnu_param_type, size_int (POINTER_SIZE), false); /* If we must pass or were requested to pass by reference, do so. If we were requested to pass by copy, do so. Otherwise, for foreign conventions, pass all in out parameters or aggregates by reference. For COBOL and Fortran, pass all integer and FP types that way too. For Convention Ada, use the standard Ada default. */ else if (must_pass_by_ref (gnu_param_type) || req_by_ref || (!req_by_copy && ((Has_Foreign_Convention (gnat_entity) && (Ekind (gnat_param) != E_In_Parameter || AGGREGATE_TYPE_P (gnu_param_type))) || (((Convention (gnat_entity) == Convention_Fortran) || (Convention (gnat_entity) == Convention_COBOL)) && (INTEGRAL_TYPE_P (gnu_param_type) || FLOAT_TYPE_P (gnu_param_type))) /* For convention Ada, see if we pass by reference by default. */ || (!Has_Foreign_Convention (gnat_entity) && default_pass_by_ref (gnu_param_type))))) { gnu_param_type = build_reference_type (gnu_param_type); by_ref_p = true; } else if (Ekind (gnat_param) != E_In_Parameter) copy_in_copy_out_flag = true; if (req_by_copy && (by_ref_p || by_component_ptr_p)) post_error ("?cannot pass & by copy", gnat_param); /* If this is an OUT parameter that isn't passed by reference and isn't a pointer or aggregate, we don't make a PARM_DECL for it. Instead, it will be a VAR_DECL created when we process the procedure. For the special parameter of Valued_Procedure, never pass it in. An exception is made to cover the RM-6.4.1 rule requiring "by copy" out parameters with discriminants or implicit initial values to be handled like in out parameters. These type are normally built as aggregates, and hence passed by reference, except for some packed arrays which end up encoded in special integer types. The exception we need to make is then for packed arrays of records with discriminants or implicit initial values. We have no light/easy way to check for the latter case, so we merely check for packed arrays of records. This may lead to useless copy-in operations, but in very rare cases only, as these would be exceptions in a set of already exceptional situations. */ if (Ekind (gnat_param) == E_Out_Parameter && !by_ref_p && ((Is_Valued_Procedure (gnat_entity) && parmnum == 0) || (!by_descr_p && !POINTER_TYPE_P (gnu_param_type) && !AGGREGATE_TYPE_P (gnu_param_type))) && !(Is_Array_Type (Etype (gnat_param)) && Is_Packed (Etype (gnat_param)) && Is_Composite_Type (Component_Type (Etype (gnat_param))))) gnu_param = NULL_TREE; else { gnu_param = create_param_decl (gnu_param_name, gnu_param_type, by_ref_p || by_component_ptr_p || Ekind (gnat_param) == E_In_Parameter); DECL_BY_REF_P (gnu_param) = by_ref_p; DECL_BY_COMPONENT_PTR_P (gnu_param) = by_component_ptr_p; DECL_BY_DESCRIPTOR_P (gnu_param) = by_descr_p; DECL_POINTS_TO_READONLY_P (gnu_param) = (Ekind (gnat_param) == E_In_Parameter && (by_ref_p || by_component_ptr_p)); Sloc_to_locus (Sloc (gnat_param), &DECL_SOURCE_LOCATION (gnu_param)); save_gnu_tree (gnat_param, gnu_param, false); gnu_param_list = chainon (gnu_param, gnu_param_list); /* If a parameter is a pointer, this function may modify memory through it and thus shouldn't be considered a pure function. Also, the memory may be modified between two calls, so they can't be CSE'ed. The latter case also handles by-ref parameters. */ if (POINTER_TYPE_P (gnu_param_type) || TYPE_FAT_POINTER_P (gnu_param_type)) pure_flag = false; } if (copy_in_copy_out_flag) { if (!has_copy_in_out) { gcc_assert (TREE_CODE (gnu_return_type) == VOID_TYPE); gnu_return_type = make_node (RECORD_TYPE); TYPE_NAME (gnu_return_type) = get_identifier ("RETURN"); has_copy_in_out = true; } gnu_field = create_field_decl (gnu_param_name, gnu_param_type, gnu_return_type, 0, 0, 0, 0); Sloc_to_locus (Sloc (gnat_param), &DECL_SOURCE_LOCATION (gnu_field)); TREE_CHAIN (gnu_field) = gnu_field_list; gnu_field_list = gnu_field; gnu_return_list = tree_cons (gnu_field, gnu_param, gnu_return_list); } } /* Do not compute record for out parameters if subprogram is stubbed since structures are incomplete for the back-end. */ if (gnu_field_list && Convention (gnat_entity) != Convention_Stubbed) { /* If all types are not complete, defer emission of debug information for this record types. Otherwise, we risk emitting debug information for a dummy type contained in the fields for that record. */ finish_record_type (gnu_return_type, nreverse (gnu_field_list), false, defer_incomplete_level); if (defer_incomplete_level) { debug_deferred = true; defer_debug_level++; defer_debug_incomplete_list = tree_cons (NULL_TREE, gnu_return_type, defer_debug_incomplete_list); } } /* If we have a CICO list but it has only one entry, we convert this function into a function that simply returns that one object. */ if (list_length (gnu_return_list) == 1) gnu_return_type = TREE_TYPE (TREE_PURPOSE (gnu_return_list)); if (Has_Stdcall_Convention (gnat_entity)) { struct attrib *attr = (struct attrib *) xmalloc (sizeof (struct attrib)); attr->next = attr_list; attr->type = ATTR_MACHINE_ATTRIBUTE; attr->name = get_identifier ("stdcall"); attr->args = NULL_TREE; attr->error_point = gnat_entity; attr_list = attr; } /* Both lists ware built in reverse. */ gnu_param_list = nreverse (gnu_param_list); gnu_return_list = nreverse (gnu_return_list); gnu_type = create_subprog_type (gnu_return_type, gnu_param_list, gnu_return_list, returns_unconstrained, returns_by_ref, Function_Returns_With_DSP (gnat_entity), returns_by_target_ptr); /* A subprogram (something that doesn't return anything) shouldn't be considered Pure since there would be no reason for such a subprogram. Note that procedures with Out (or In Out) parameters have already been converted into a function with a return type. */ if (TREE_CODE (gnu_return_type) == VOID_TYPE) pure_flag = false; /* The semantics of "pure" in Ada essentially matches that of "const" in the back-end. In particular, both properties are orthogonal to the "nothrow" property. But this is true only if the EH circuitry is explicit in the internal representation of the back-end. If we are to completely hide the EH circuitry from it, we need to declare that calls to pure Ada subprograms that can throw have side effects since they can trigger an "abnormal" transfer of control flow; thus they can be neither "const" nor "pure" in the back-end sense. */ gnu_type = build_qualified_type (gnu_type, TYPE_QUALS (gnu_type) | (Exception_Mechanism == Back_End_Exceptions ? TYPE_QUAL_CONST * pure_flag : 0) | (TYPE_QUAL_VOLATILE * volatile_flag)); Sloc_to_locus (Sloc (gnat_entity), &input_location); /* If we have a builtin decl for that function, check the signatures compatibilities. If the signatures are compatible, use the builtin decl. If they are not, we expect the checker predicate to have posted the appropriate errors, and just continue with what we have so far. */ if (gnu_builtin_decl) { tree gnu_builtin_type = TREE_TYPE (gnu_builtin_decl); if (compatible_signatures_p (gnu_type, gnu_builtin_type)) { gnu_decl = gnu_builtin_decl; gnu_type = gnu_builtin_type; break; } } /* If there was no specified Interface_Name and the external and internal names of the subprogram are the same, only use the internal name to allow disambiguation of nested subprograms. */ if (No (Interface_Name (gnat_entity)) && gnu_ext_name == gnu_entity_id) gnu_ext_name = NULL_TREE; /* If we are defining the subprogram and it has an Address clause we must get the address expression from the saved GCC tree for the subprogram if it has a Freeze_Node. Otherwise, we elaborate the address expression here since the front-end has guaranteed in that case that the elaboration has no effects. If there is an Address clause and we are not defining the object, just make it a constant. */ if (Present (Address_Clause (gnat_entity))) { tree gnu_address = NULL_TREE; if (definition) gnu_address = (present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : gnat_to_gnu (Expression (Address_Clause (gnat_entity)))); save_gnu_tree (gnat_entity, NULL_TREE, false); gnu_type = build_reference_type (gnu_type); if (gnu_address) gnu_address = convert (gnu_type, gnu_address); gnu_decl = create_var_decl (gnu_entity_id, gnu_ext_name, gnu_type, gnu_address, false, Is_Public (gnat_entity), extern_flag, false, NULL, gnat_entity); DECL_BY_REF_P (gnu_decl) = 1; } else if (kind == E_Subprogram_Type) gnu_decl = create_type_decl (gnu_entity_id, gnu_type, attr_list, !Comes_From_Source (gnat_entity), debug_info_p && !defer_incomplete_level, gnat_entity); else { gnu_decl = create_subprog_decl (gnu_entity_id, gnu_ext_name, gnu_type, gnu_param_list, inline_flag, public_flag, extern_flag, attr_list, gnat_entity); DECL_STUBBED_P (gnu_decl) = Convention (gnat_entity) == Convention_Stubbed; } } break; case E_Incomplete_Type: case E_Private_Type: case E_Limited_Private_Type: case E_Record_Type_With_Private: case E_Private_Subtype: case E_Limited_Private_Subtype: case E_Record_Subtype_With_Private: /* If this type does not have a full view in the unit we are compiling, then just get the type from its Etype. */ if (No (Full_View (gnat_entity))) { /* If this is an incomplete type with no full view, it must be either a limited view brought in by a limited_with clause, in which case we use the non-limited view, or a Taft Amendement type, in which case we just return a dummy type. */ if (kind == E_Incomplete_Type) { if (From_With_Type (gnat_entity) && Present (Non_Limited_View (gnat_entity))) gnu_decl = gnat_to_gnu_entity (Non_Limited_View (gnat_entity), NULL_TREE, 0); else gnu_type = make_dummy_type (gnat_entity); } else if (Present (Underlying_Full_View (gnat_entity))) gnu_decl = gnat_to_gnu_entity (Underlying_Full_View (gnat_entity), NULL_TREE, 0); else { gnu_decl = gnat_to_gnu_entity (Etype (gnat_entity), NULL_TREE, 0); maybe_present = true; } break; } /* Otherwise, if we are not defining the type now, get the type from the full view. But always get the type from the full view for define on use types, since otherwise we won't see them! */ else if (!definition || (Is_Itype (Full_View (gnat_entity)) && No (Freeze_Node (gnat_entity))) || (Is_Itype (gnat_entity) && No (Freeze_Node (Full_View (gnat_entity))))) { gnu_decl = gnat_to_gnu_entity (Full_View (gnat_entity), NULL_TREE, 0); maybe_present = true; break; } /* For incomplete types, make a dummy type entry which will be replaced later. */ gnu_type = make_dummy_type (gnat_entity); /* Save this type as the full declaration's type so we can do any needed updates when we see it. */ gnu_decl = create_type_decl (gnu_entity_id, gnu_type, attr_list, !Comes_From_Source (gnat_entity), debug_info_p, gnat_entity); save_gnu_tree (Full_View (gnat_entity), gnu_decl, false); break; /* Simple class_wide types are always viewed as their root_type by Gigi unless an Equivalent_Type is specified. */ case E_Class_Wide_Type: if (Present (Equivalent_Type (gnat_entity))) gnu_type = gnat_to_gnu_type (Equivalent_Type (gnat_entity)); else gnu_type = gnat_to_gnu_type (Root_Type (gnat_entity)); maybe_present = true; break; case E_Task_Type: case E_Task_Subtype: case E_Protected_Type: case E_Protected_Subtype: if (type_annotate_only && No (Corresponding_Record_Type (gnat_entity))) gnu_type = void_type_node; else gnu_type = gnat_to_gnu_type (Corresponding_Record_Type (gnat_entity)); maybe_present = true; break; case E_Label: gnu_decl = create_label_decl (gnu_entity_id); break; case E_Block: case E_Loop: /* Nothing at all to do here, so just return an ERROR_MARK and claim we've already saved it, so we don't try to. */ gnu_decl = error_mark_node; saved = true; break; default: gcc_unreachable (); } /* If we had a case where we evaluated another type and it might have defined this one, handle it here. */ if (maybe_present && present_gnu_tree (gnat_entity)) { gnu_decl = get_gnu_tree (gnat_entity); saved = true; } /* If we are processing a type and there is either no decl for it or we just made one, do some common processing for the type, such as handling alignment and possible padding. */ if ((!gnu_decl || this_made_decl) && IN (kind, Type_Kind)) { if (Is_Tagged_Type (gnat_entity) || Is_Class_Wide_Equivalent_Type (gnat_entity)) TYPE_ALIGN_OK (gnu_type) = 1; if (AGGREGATE_TYPE_P (gnu_type) && Is_By_Reference_Type (gnat_entity)) TYPE_BY_REFERENCE_P (gnu_type) = 1; /* ??? Don't set the size for a String_Literal since it is either confirming or we don't handle it properly (if the low bound is non-constant). */ if (!gnu_size && kind != E_String_Literal_Subtype) gnu_size = validate_size (Esize (gnat_entity), gnu_type, gnat_entity, TYPE_DECL, false, Has_Size_Clause (gnat_entity)); /* If a size was specified, see if we can make a new type of that size by rearranging the type, for example from a fat to a thin pointer. */ if (gnu_size) { gnu_type = make_type_from_size (gnu_type, gnu_size, Has_Biased_Representation (gnat_entity)); if (operand_equal_p (TYPE_SIZE (gnu_type), gnu_size, 0) && operand_equal_p (rm_size (gnu_type), gnu_size, 0)) gnu_size = 0; } /* If the alignment hasn't already been processed and this is not an unconstrained array, see if an alignment is specified. If not, we pick a default alignment for atomic objects. */ if (align != 0 || TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE) ; else if (Known_Alignment (gnat_entity)) align = validate_alignment (Alignment (gnat_entity), gnat_entity, TYPE_ALIGN (gnu_type)); else if (Is_Atomic (gnat_entity) && !gnu_size && host_integerp (TYPE_SIZE (gnu_type), 1) && integer_pow2p (TYPE_SIZE (gnu_type))) align = MIN (BIGGEST_ALIGNMENT, tree_low_cst (TYPE_SIZE (gnu_type), 1)); else if (Is_Atomic (gnat_entity) && gnu_size && host_integerp (gnu_size, 1) && integer_pow2p (gnu_size)) align = MIN (BIGGEST_ALIGNMENT, tree_low_cst (gnu_size, 1)); /* See if we need to pad the type. If we did, and made a record, the name of the new type may be changed. So get it back for us when we make the new TYPE_DECL below. */ gnu_type = maybe_pad_type (gnu_type, gnu_size, align, gnat_entity, "PAD", true, definition, false); if (TREE_CODE (gnu_type) == RECORD_TYPE && TYPE_IS_PADDING_P (gnu_type)) { gnu_entity_id = TYPE_NAME (gnu_type); if (TREE_CODE (gnu_entity_id) == TYPE_DECL) gnu_entity_id = DECL_NAME (gnu_entity_id); } set_rm_size (RM_Size (gnat_entity), gnu_type, gnat_entity); /* If we are at global level, GCC will have applied variable_size to the type, but that won't have done anything. So, if it's not a constant or self-referential, call elaborate_expression_1 to make a variable for the size rather than calculating it each time. Handle both the RM size and the actual size. */ if (global_bindings_p () && TYPE_SIZE (gnu_type) && !TREE_CONSTANT (TYPE_SIZE (gnu_type)) && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type))) { if (TREE_CODE (gnu_type) == RECORD_TYPE && operand_equal_p (TYPE_ADA_SIZE (gnu_type), TYPE_SIZE (gnu_type), 0)) { TYPE_SIZE (gnu_type) = elaborate_expression_1 (gnat_entity, gnat_entity, TYPE_SIZE (gnu_type), get_identifier ("SIZE"), definition, 0); SET_TYPE_ADA_SIZE (gnu_type, TYPE_SIZE (gnu_type)); } else { TYPE_SIZE (gnu_type) = elaborate_expression_1 (gnat_entity, gnat_entity, TYPE_SIZE (gnu_type), get_identifier ("SIZE"), definition, 0); /* ??? For now, store the size as a multiple of the alignment in bytes so that we can see the alignment from the tree. */ TYPE_SIZE_UNIT (gnu_type) = build_binary_op (MULT_EXPR, sizetype, elaborate_expression_1 (gnat_entity, gnat_entity, build_binary_op (EXACT_DIV_EXPR, sizetype, TYPE_SIZE_UNIT (gnu_type), size_int (TYPE_ALIGN (gnu_type) / BITS_PER_UNIT)), get_identifier ("SIZE_A_UNIT"), definition, 0), size_int (TYPE_ALIGN (gnu_type) / BITS_PER_UNIT)); if (TREE_CODE (gnu_type) == RECORD_TYPE) SET_TYPE_ADA_SIZE (gnu_type, elaborate_expression_1 (gnat_entity, gnat_entity, TYPE_ADA_SIZE (gnu_type), get_identifier ("RM_SIZE"), definition, 0)); } } /* If this is a record type or subtype, call elaborate_expression_1 on any field position. Do this for both global and local types. Skip any fields that we haven't made trees for to avoid problems with class wide types. */ if (IN (kind, Record_Kind)) for (gnat_temp = First_Entity (gnat_entity); Present (gnat_temp); gnat_temp = Next_Entity (gnat_temp)) if (Ekind (gnat_temp) == E_Component && present_gnu_tree (gnat_temp)) { tree gnu_field = get_gnu_tree (gnat_temp); /* ??? Unfortunately, GCC needs to be able to prove the alignment of this offset and if it's a variable, it can't. In GCC 3.4, we'll use DECL_OFFSET_ALIGN in some way, but right now, we have to put in an explicit multiply and divide by that value. */ if (!CONTAINS_PLACEHOLDER_P (DECL_FIELD_OFFSET (gnu_field))) DECL_FIELD_OFFSET (gnu_field) = build_binary_op (MULT_EXPR, sizetype, elaborate_expression_1 (gnat_temp, gnat_temp, build_binary_op (EXACT_DIV_EXPR, sizetype, DECL_FIELD_OFFSET (gnu_field), size_int (DECL_OFFSET_ALIGN (gnu_field) / BITS_PER_UNIT)), get_identifier ("OFFSET"), definition, 0), size_int (DECL_OFFSET_ALIGN (gnu_field) / BITS_PER_UNIT)); } gnu_type = build_qualified_type (gnu_type, (TYPE_QUALS (gnu_type) | (TYPE_QUAL_VOLATILE * Treat_As_Volatile (gnat_entity)))); if (Is_Atomic (gnat_entity)) check_ok_for_atomic (gnu_type, gnat_entity, false); if (Known_Alignment (gnat_entity)) TYPE_USER_ALIGN (gnu_type) = 1; if (!gnu_decl) gnu_decl = create_type_decl (gnu_entity_id, gnu_type, attr_list, !Comes_From_Source (gnat_entity), debug_info_p, gnat_entity); else TREE_TYPE (gnu_decl) = gnu_type; } if (IN (kind, Type_Kind) && !TYPE_IS_DUMMY_P (TREE_TYPE (gnu_decl))) { gnu_type = TREE_TYPE (gnu_decl); /* Back-annotate the Alignment of the type if not already in the tree. Likewise for sizes. */ if (Unknown_Alignment (gnat_entity)) Set_Alignment (gnat_entity, UI_From_Int (TYPE_ALIGN (gnu_type) / BITS_PER_UNIT)); if (Unknown_Esize (gnat_entity) && TYPE_SIZE (gnu_type)) { /* If the size is self-referential, we annotate the maximum value of that size. */ tree gnu_size = TYPE_SIZE (gnu_type); if (CONTAINS_PLACEHOLDER_P (gnu_size)) gnu_size = max_size (gnu_size, true); Set_Esize (gnat_entity, annotate_value (gnu_size)); if (type_annotate_only && Is_Tagged_Type (gnat_entity)) { /* In this mode the tag and the parent components are not generated by the front-end, so the sizes must be adjusted explicitly now. */ int size_offset; int new_size; if (Is_Derived_Type (gnat_entity)) { size_offset = UI_To_Int (Esize (Etype (Base_Type (gnat_entity)))); Set_Alignment (gnat_entity, Alignment (Etype (Base_Type (gnat_entity)))); } else size_offset = POINTER_SIZE; new_size = UI_To_Int (Esize (gnat_entity)) + size_offset; Set_Esize (gnat_entity, UI_From_Int (((new_size + (POINTER_SIZE - 1)) / POINTER_SIZE) * POINTER_SIZE)); Set_RM_Size (gnat_entity, Esize (gnat_entity)); } } if (Unknown_RM_Size (gnat_entity) && rm_size (gnu_type)) Set_RM_Size (gnat_entity, annotate_value (rm_size (gnu_type))); } if (!Comes_From_Source (gnat_entity) && DECL_P (gnu_decl)) DECL_ARTIFICIAL (gnu_decl) = 1; if (!debug_info_p && DECL_P (gnu_decl) && TREE_CODE (gnu_decl) != FUNCTION_DECL && No (Renamed_Object (gnat_entity))) DECL_IGNORED_P (gnu_decl) = 1; /* If we haven't already, associate the ..._DECL node that we just made with the input GNAT entity node. */ if (!saved) save_gnu_tree (gnat_entity, gnu_decl, false); /* If this is an enumeral or floating-point type, we were not able to set the bounds since they refer to the type. These bounds are always static. For enumeration types, also write debugging information and declare the enumeration literal table, if needed. */ if ((kind == E_Enumeration_Type && Present (First_Literal (gnat_entity))) || (kind == E_Floating_Point_Type && !Vax_Float (gnat_entity))) { tree gnu_scalar_type = gnu_type; /* If this is a padded type, we need to use the underlying type. */ if (TREE_CODE (gnu_scalar_type) == RECORD_TYPE && TYPE_IS_PADDING_P (gnu_scalar_type)) gnu_scalar_type = TREE_TYPE (TYPE_FIELDS (gnu_scalar_type)); /* If this is a floating point type and we haven't set a floating point type yet, use this in the evaluation of the bounds. */ if (!longest_float_type_node && kind == E_Floating_Point_Type) longest_float_type_node = gnu_type; TYPE_MIN_VALUE (gnu_scalar_type) = gnat_to_gnu (Type_Low_Bound (gnat_entity)); TYPE_MAX_VALUE (gnu_scalar_type) = gnat_to_gnu (Type_High_Bound (gnat_entity)); if (TREE_CODE (gnu_scalar_type) == ENUMERAL_TYPE) { TYPE_STUB_DECL (gnu_scalar_type) = gnu_decl; /* Since this has both a typedef and a tag, avoid outputting the name twice. */ DECL_ARTIFICIAL (gnu_decl) = 1; rest_of_type_compilation (gnu_scalar_type, global_bindings_p ()); } } /* If we deferred processing of incomplete types, re-enable it. If there were no other disables and we have some to process, do so. */ if (this_deferred && --defer_incomplete_level == 0 && defer_incomplete_list) { struct incomplete *incp = defer_incomplete_list; struct incomplete *next; defer_incomplete_list = NULL; for (; incp; incp = next) { next = incp->next; if (incp->old_type) update_pointer_to (TYPE_MAIN_VARIANT (incp->old_type), gnat_to_gnu_type (incp->full_type)); free (incp); } } /* If we are not defining this type, see if it's in the incomplete list. If so, handle that list entry now. */ else if (!definition) { struct incomplete *incp; for (incp = defer_incomplete_list; incp; incp = incp->next) if (incp->old_type && incp->full_type == gnat_entity) { update_pointer_to (TYPE_MAIN_VARIANT (incp->old_type), TREE_TYPE (gnu_decl)); incp->old_type = NULL_TREE; } } /* If there are no incomplete types and we have deferred emission of debug information, check whether we have finished defining all nested records. If so, handle the list now. */ if (debug_deferred) defer_debug_level--; if (defer_debug_incomplete_list && !defer_incomplete_level && !defer_debug_level) { tree c, n; defer_debug_incomplete_list = nreverse (defer_debug_incomplete_list); for (c = defer_debug_incomplete_list; c; c = n) { n = TREE_CHAIN (c); write_record_type_debug_info (TREE_VALUE (c)); } defer_debug_incomplete_list = 0; } if (this_global) force_global--; if (Is_Packed_Array_Type (gnat_entity) && Is_Itype (Associated_Node_For_Itype (gnat_entity)) && No (Freeze_Node (Associated_Node_For_Itype (gnat_entity))) && !present_gnu_tree (Associated_Node_For_Itype (gnat_entity))) gnat_to_gnu_entity (Associated_Node_For_Itype (gnat_entity), NULL_TREE, 0); return gnu_decl; } /* Similar, but if the returned value is a COMPONENT_REF, return the FIELD_DECL. */ tree gnat_to_gnu_field_decl (Entity_Id gnat_entity) { tree gnu_field = gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0); if (TREE_CODE (gnu_field) == COMPONENT_REF) gnu_field = TREE_OPERAND (gnu_field, 1); return gnu_field; } /* Return true if DISCR1 and DISCR2 represent the same discriminant. */ static bool same_discriminant_p (Entity_Id discr1, Entity_Id discr2) { while (Present (Corresponding_Discriminant (discr1))) discr1 = Corresponding_Discriminant (discr1); while (Present (Corresponding_Discriminant (discr2))) discr2 = Corresponding_Discriminant (discr2); return Original_Record_Component (discr1) == Original_Record_Component (discr2); } /* Given GNAT_ENTITY, elaborate all expressions that are required to be elaborated at the point of its definition, but do nothing else. */ void elaborate_entity (Entity_Id gnat_entity) { switch (Ekind (gnat_entity)) { case E_Signed_Integer_Subtype: case E_Modular_Integer_Subtype: case E_Enumeration_Subtype: case E_Ordinary_Fixed_Point_Subtype: case E_Decimal_Fixed_Point_Subtype: case E_Floating_Point_Subtype: { Node_Id gnat_lb = Type_Low_Bound (gnat_entity); Node_Id gnat_hb = Type_High_Bound (gnat_entity); /* ??? Tests for avoiding static constraint error expression is needed until the front stops generating bogus conversions on bounds of real types. */ if (!Raises_Constraint_Error (gnat_lb)) elaborate_expression (gnat_lb, gnat_entity, get_identifier ("L"), 1, 0, Needs_Debug_Info (gnat_entity)); if (!Raises_Constraint_Error (gnat_hb)) elaborate_expression (gnat_hb, gnat_entity, get_identifier ("U"), 1, 0, Needs_Debug_Info (gnat_entity)); break; } case E_Record_Type: { Node_Id full_definition = Declaration_Node (gnat_entity); Node_Id record_definition = Type_Definition (full_definition); /* If this is a record extension, go a level further to find the record definition. */ if (Nkind (record_definition) == N_Derived_Type_Definition) record_definition = Record_Extension_Part (record_definition); } break; case E_Record_Subtype: case E_Private_Subtype: case E_Limited_Private_Subtype: case E_Record_Subtype_With_Private: if (Is_Constrained (gnat_entity) && Has_Discriminants (Base_Type (gnat_entity)) && Present (Discriminant_Constraint (gnat_entity))) { Node_Id gnat_discriminant_expr; Entity_Id gnat_field; for (gnat_field = First_Discriminant (Base_Type (gnat_entity)), gnat_discriminant_expr = First_Elmt (Discriminant_Constraint (gnat_entity)); Present (gnat_field); gnat_field = Next_Discriminant (gnat_field), gnat_discriminant_expr = Next_Elmt (gnat_discriminant_expr)) /* ??? For now, ignore access discriminants. */ if (!Is_Access_Type (Etype (Node (gnat_discriminant_expr)))) elaborate_expression (Node (gnat_discriminant_expr), gnat_entity, get_entity_name (gnat_field), 1, 0, 0); } break; } } /* Mark GNAT_ENTITY as going out of scope at this point. Recursively mark any entities on its entity chain similarly. */ void mark_out_of_scope (Entity_Id gnat_entity) { Entity_Id gnat_sub_entity; unsigned int kind = Ekind (gnat_entity); /* If this has an entity list, process all in the list. */ if (IN (kind, Class_Wide_Kind) || IN (kind, Concurrent_Kind) || IN (kind, Private_Kind) || kind == E_Block || kind == E_Entry || kind == E_Entry_Family || kind == E_Function || kind == E_Generic_Function || kind == E_Generic_Package || kind == E_Generic_Procedure || kind == E_Loop || kind == E_Operator || kind == E_Package || kind == E_Package_Body || kind == E_Procedure || kind == E_Record_Type || kind == E_Record_Subtype || kind == E_Subprogram_Body || kind == E_Subprogram_Type) for (gnat_sub_entity = First_Entity (gnat_entity); Present (gnat_sub_entity); gnat_sub_entity = Next_Entity (gnat_sub_entity)) if (Scope (gnat_sub_entity) == gnat_entity && gnat_sub_entity != gnat_entity) mark_out_of_scope (gnat_sub_entity); /* Now clear this if it has been defined, but only do so if it isn't a subprogram or parameter. We could refine this, but it isn't worth it. If this is statically allocated, it is supposed to hang around out of cope. */ if (present_gnu_tree (gnat_entity) && !Is_Statically_Allocated (gnat_entity) && kind != E_Procedure && kind != E_Function && !IN (kind, Formal_Kind)) { save_gnu_tree (gnat_entity, NULL_TREE, true); save_gnu_tree (gnat_entity, error_mark_node, true); } } /* Set the alias set of GNU_NEW_TYPE to be that of GNU_OLD_TYPE. If this is a multi-dimensional array type, do this recursively. */ static void copy_alias_set (tree gnu_new_type, tree gnu_old_type) { /* Remove any padding from GNU_OLD_TYPE. It doesn't matter in the case of a one-dimensional array, since the padding has the same alias set as the field type, but if it's a multi-dimensional array, we need to see the inner types. */ while (TREE_CODE (gnu_old_type) == RECORD_TYPE && (TYPE_JUSTIFIED_MODULAR_P (gnu_old_type) || TYPE_IS_PADDING_P (gnu_old_type))) gnu_old_type = TREE_TYPE (TYPE_FIELDS (gnu_old_type)); /* We need to be careful here in case GNU_OLD_TYPE is an unconstrained array. In that case, it doesn't have the same shape as GNU_NEW_TYPE, so we need to go down to what does. */ if (TREE_CODE (gnu_old_type) == UNCONSTRAINED_ARRAY_TYPE) gnu_old_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_old_type)))); if (TREE_CODE (gnu_new_type) == ARRAY_TYPE && TREE_CODE (TREE_TYPE (gnu_new_type)) == ARRAY_TYPE && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_new_type))) copy_alias_set (TREE_TYPE (gnu_new_type), TREE_TYPE (gnu_old_type)); TYPE_ALIAS_SET (gnu_new_type) = get_alias_set (gnu_old_type); record_component_aliases (gnu_new_type); } /* Return a TREE_LIST describing the substitutions needed to reflect discriminant substitutions from GNAT_SUBTYPE to GNAT_TYPE and add them to GNU_LIST. If GNAT_TYPE is not specified, use the base type of GNAT_SUBTYPE. The substitutions can be in any order. TREE_PURPOSE gives the tree for the discriminant and TREE_VALUES is the replacement value. They are in the form of operands to substitute_in_expr. DEFINITION is as in gnat_to_gnu_entity. */ static tree substitution_list (Entity_Id gnat_subtype, Entity_Id gnat_type, tree gnu_list, bool definition) { Entity_Id gnat_discrim; Node_Id gnat_value; if (No (gnat_type)) gnat_type = Implementation_Base_Type (gnat_subtype); if (Has_Discriminants (gnat_type)) for (gnat_discrim = First_Stored_Discriminant (gnat_type), gnat_value = First_Elmt (Stored_Constraint (gnat_subtype)); Present (gnat_discrim); gnat_discrim = Next_Stored_Discriminant (gnat_discrim), gnat_value = Next_Elmt (gnat_value)) /* Ignore access discriminants. */ if (!Is_Access_Type (Etype (Node (gnat_value)))) gnu_list = tree_cons (gnat_to_gnu_field_decl (gnat_discrim), elaborate_expression (Node (gnat_value), gnat_subtype, get_entity_name (gnat_discrim), definition, 1, 0), gnu_list); return gnu_list; } /* For the following two functions: for each GNAT entity, the GCC tree node used as a dummy for that entity, if any. */ static GTY((length ("max_gnat_nodes"))) tree * dummy_node_table; /* Initialize the above table. */ void init_dummy_type (void) { Node_Id gnat_node; dummy_node_table = (tree *) ggc_alloc (max_gnat_nodes * sizeof (tree)); for (gnat_node = 0; gnat_node < max_gnat_nodes; gnat_node++) dummy_node_table[gnat_node] = NULL_TREE; dummy_node_table -= First_Node_Id; } /* Make a dummy type corresponding to GNAT_TYPE. */ tree make_dummy_type (Entity_Id gnat_type) { Entity_Id gnat_underlying; tree gnu_type; enum tree_code code; /* Find a full type for GNAT_TYPE, taking into account any class wide types. */ if (Is_Class_Wide_Type (gnat_type) && Present (Equivalent_Type (gnat_type))) gnat_type = Equivalent_Type (gnat_type); else if (Ekind (gnat_type) == E_Class_Wide_Type) gnat_type = Root_Type (gnat_type); for (gnat_underlying = gnat_type; (IN (Ekind (gnat_underlying), Incomplete_Or_Private_Kind) && Present (Full_View (gnat_underlying))); gnat_underlying = Full_View (gnat_underlying)) ; /* If it there already a dummy type, use that one. Else make one. */ if (dummy_node_table[gnat_underlying]) return dummy_node_table[gnat_underlying]; /* If this is a record, make this a RECORD_TYPE or UNION_TYPE; else make it an ENUMERAL_TYPE. */ if (Is_Record_Type (gnat_underlying)) { Node_Id component_list = Component_List (Type_Definition (Declaration_Node (Implementation_Base_Type (gnat_underlying)))); Node_Id component; /* Make this a UNION_TYPE unless it's either not an Unchecked_Union or we have a non-discriminant field outside a variant. In either case, it's a RECORD_TYPE. */ code = UNION_TYPE; if (!Is_Unchecked_Union (gnat_underlying)) code = RECORD_TYPE; else for (component = First_Non_Pragma (Component_Items (component_list)); Present (component); component = Next_Non_Pragma (component)) if (Ekind (Defining_Entity (component)) == E_Component) code = RECORD_TYPE; } else code = ENUMERAL_TYPE; gnu_type = make_node (code); TYPE_NAME (gnu_type) = get_entity_name (gnat_type); TYPE_DUMMY_P (gnu_type) = 1; if (AGGREGATE_TYPE_P (gnu_type)) TYPE_STUB_DECL (gnu_type) = build_decl (TYPE_DECL, NULL_TREE, gnu_type); dummy_node_table[gnat_underlying] = gnu_type; return gnu_type; } /* Return true if the size represented by GNU_SIZE can be handled by an allocation. If STATIC_P is true, consider only what can be done with a static allocation. */ static bool allocatable_size_p (tree gnu_size, bool static_p) { HOST_WIDE_INT our_size; /* If this is not a static allocation, the only case we want to forbid is an overflowing size. That will be converted into a raise a Storage_Error. */ if (!static_p) return !(TREE_CODE (gnu_size) == INTEGER_CST && TREE_CONSTANT_OVERFLOW (gnu_size)); /* Otherwise, we need to deal with both variable sizes and constant sizes that won't fit in a host int. We use int instead of HOST_WIDE_INT since assemblers may not like very large sizes. */ if (!host_integerp (gnu_size, 1)) return false; our_size = tree_low_cst (gnu_size, 1); return (int) our_size == our_size; } /* Prepend to ATTR_LIST the list of attributes for GNAT_ENTITY, if any. */ static void prepend_attributes (Entity_Id gnat_entity, struct attrib ** attr_list) { Node_Id gnat_temp; for (gnat_temp = First_Rep_Item (gnat_entity); Present (gnat_temp); gnat_temp = Next_Rep_Item (gnat_temp)) if (Nkind (gnat_temp) == N_Pragma) { struct attrib *attr; tree gnu_arg0 = NULL_TREE, gnu_arg1 = NULL_TREE; Node_Id gnat_assoc = Pragma_Argument_Associations (gnat_temp); enum attr_type etype; if (Present (gnat_assoc) && Present (First (gnat_assoc)) && Present (Next (First (gnat_assoc))) && (Nkind (Expression (Next (First (gnat_assoc)))) == N_String_Literal)) { gnu_arg0 = get_identifier (TREE_STRING_POINTER (gnat_to_gnu (Expression (Next (First (gnat_assoc)))))); if (Present (Next (Next (First (gnat_assoc)))) && (Nkind (Expression (Next (Next (First (gnat_assoc))))) == N_String_Literal)) gnu_arg1 = get_identifier (TREE_STRING_POINTER (gnat_to_gnu (Expression (Next (Next (First (gnat_assoc))))))); } switch (Get_Pragma_Id (Chars (gnat_temp))) { case Pragma_Machine_Attribute: etype = ATTR_MACHINE_ATTRIBUTE; break; case Pragma_Linker_Alias: etype = ATTR_LINK_ALIAS; break; case Pragma_Linker_Section: etype = ATTR_LINK_SECTION; break; case Pragma_Linker_Constructor: etype = ATTR_LINK_CONSTRUCTOR; break; case Pragma_Linker_Destructor: etype = ATTR_LINK_DESTRUCTOR; break; case Pragma_Weak_External: etype = ATTR_WEAK_EXTERNAL; break; default: continue; } attr = (struct attrib *) xmalloc (sizeof (struct attrib)); attr->next = *attr_list; attr->type = etype; attr->name = gnu_arg0; /* If we have an argument specified together with an attribute name, make it a single TREE_VALUE entry in a list of arguments, as GCC expects it. */ if (gnu_arg1 != NULL_TREE) attr->args = build_tree_list (NULL_TREE, gnu_arg1); else attr->args = NULL_TREE; attr->error_point = Present (Next (First (gnat_assoc))) ? Expression (Next (First (gnat_assoc))) : gnat_temp; *attr_list = attr; } } /* Get the unpadded version of a GNAT type. */ tree get_unpadded_type (Entity_Id gnat_entity) { tree type = gnat_to_gnu_type (gnat_entity); if (TREE_CODE (type) == RECORD_TYPE && TYPE_IS_PADDING_P (type)) type = TREE_TYPE (TYPE_FIELDS (type)); return type; } /* Called when we need to protect a variable object using a save_expr. */ tree maybe_variable (tree gnu_operand) { if (TREE_CONSTANT (gnu_operand) || TREE_READONLY (gnu_operand) || TREE_CODE (gnu_operand) == SAVE_EXPR || TREE_CODE (gnu_operand) == NULL_EXPR) return gnu_operand; if (TREE_CODE (gnu_operand) == UNCONSTRAINED_ARRAY_REF) { tree gnu_result = build1 (UNCONSTRAINED_ARRAY_REF, TREE_TYPE (gnu_operand), variable_size (TREE_OPERAND (gnu_operand, 0))); TREE_READONLY (gnu_result) = TREE_STATIC (gnu_result) = TYPE_READONLY (TREE_TYPE (TREE_TYPE (gnu_operand))); return gnu_result; } else return variable_size (gnu_operand); } /* Given a GNAT tree GNAT_EXPR, for an expression which is a value within a type definition (either a bound or a discriminant value) for GNAT_ENTITY, return the GCC tree to use for that expression. GNU_NAME is the qualification to use if an external name is appropriate and DEFINITION is nonzero if this is a definition of GNAT_ENTITY. If NEED_VALUE is nonzero, we need a result. Otherwise, we are just elaborating this for side-effects. If NEED_DEBUG is nonzero we need the symbol for debugging purposes even if it isn't needed for code generation. */ static tree elaborate_expression (Node_Id gnat_expr, Entity_Id gnat_entity, tree gnu_name, bool definition, bool need_value, bool need_debug) { tree gnu_expr; /* If we already elaborated this expression (e.g., it was involved in the definition of a private type), use the old value. */ if (present_gnu_tree (gnat_expr)) return get_gnu_tree (gnat_expr); /* If we don't need a value and this is static or a discriminant, we don't need to do anything. */ else if (!need_value && (Is_OK_Static_Expression (gnat_expr) || (Nkind (gnat_expr) == N_Identifier && Ekind (Entity (gnat_expr)) == E_Discriminant))) return 0; /* Otherwise, convert this tree to its GCC equivalent. */ gnu_expr = elaborate_expression_1 (gnat_expr, gnat_entity, gnat_to_gnu (gnat_expr), gnu_name, definition, need_debug); /* Save the expression in case we try to elaborate this entity again. Since this is not a DECL, don't check it. Don't save if it's a discriminant. */ if (!CONTAINS_PLACEHOLDER_P (gnu_expr)) save_gnu_tree (gnat_expr, gnu_expr, true); return need_value ? gnu_expr : error_mark_node; } /* Similar, but take a GNU expression. */ static tree elaborate_expression_1 (Node_Id gnat_expr, Entity_Id gnat_entity, tree gnu_expr, tree gnu_name, bool definition, bool need_debug) { tree gnu_decl = NULL_TREE; /* Strip any conversions to see if the expression is a readonly variable. ??? This really should remain readonly, but we have to think about the typing of the tree here. */ tree gnu_inner_expr = remove_conversions (gnu_expr, true); bool expr_global = Is_Public (gnat_entity) || global_bindings_p (); bool expr_variable; /* In most cases, we won't see a naked FIELD_DECL here because a discriminant reference will have been replaced with a COMPONENT_REF when the type is being elaborated. However, there are some cases involving child types where we will. So convert it to a COMPONENT_REF here. We have to hope it will be at the highest level of the expression in these cases. */ if (TREE_CODE (gnu_expr) == FIELD_DECL) gnu_expr = build3 (COMPONENT_REF, TREE_TYPE (gnu_expr), build0 (PLACEHOLDER_EXPR, DECL_CONTEXT (gnu_expr)), gnu_expr, NULL_TREE); /* If GNU_EXPR is neither a placeholder nor a constant, nor a variable that is a constant, make a variable that is initialized to contain the bound when the package containing the definition is elaborated. If this entity is defined at top level and a bound or discriminant value isn't a constant or a reference to a discriminant, replace the bound by the variable; otherwise use a SAVE_EXPR if needed. Note that we rely here on the fact that an expression cannot contain both the discriminant and some other variable. */ expr_variable = (!CONSTANT_CLASS_P (gnu_expr) && !(TREE_CODE (gnu_inner_expr) == VAR_DECL && (TREE_READONLY (gnu_inner_expr) || DECL_READONLY_ONCE_ELAB (gnu_inner_expr))) && !CONTAINS_PLACEHOLDER_P (gnu_expr)); /* If this is a static expression or contains a discriminant, we don't need the variable for debugging (and can't elaborate anyway if a discriminant). */ if (need_debug && (Is_OK_Static_Expression (gnat_expr) || CONTAINS_PLACEHOLDER_P (gnu_expr))) need_debug = false; /* Now create the variable if we need it. */ if (need_debug || (expr_variable && expr_global)) gnu_decl = create_var_decl (create_concat_name (gnat_entity, IDENTIFIER_POINTER (gnu_name)), NULL_TREE, TREE_TYPE (gnu_expr), gnu_expr, !need_debug, Is_Public (gnat_entity), !definition, false, NULL, gnat_entity); /* We only need to use this variable if we are in global context since GCC can do the right thing in the local case. */ if (expr_global && expr_variable) return gnu_decl; else if (!expr_variable) return gnu_expr; else return maybe_variable (gnu_expr); } /* Create a record type that contains a field of TYPE with a starting bit position so that it is aligned to ALIGN bits and is SIZE bytes long. */ tree make_aligning_type (tree type, int align, tree size) { tree record_type = make_node (RECORD_TYPE); tree place = build0 (PLACEHOLDER_EXPR, record_type); tree size_addr_place = convert (sizetype, build_unary_op (ADDR_EXPR, NULL_TREE, place)); tree name = TYPE_NAME (type); tree pos, field; if (TREE_CODE (name) == TYPE_DECL) name = DECL_NAME (name); TYPE_NAME (record_type) = concat_id_with_name (name, "_ALIGN"); /* The bit position is obtained by "and"ing the alignment minus 1 with the two's complement of the address and multiplying by the number of bits per unit. Do all this in sizetype. */ pos = size_binop (MULT_EXPR, convert (bitsizetype, size_binop (BIT_AND_EXPR, size_diffop (size_zero_node, size_addr_place), ssize_int ((align / BITS_PER_UNIT) - 1))), bitsize_unit_node); /* Create the field, with -1 as the 'addressable' indication to avoid the creation of a bitfield. We don't need one, it would have damaging consequences on the alignment computation, and create_field_decl would make one without this special argument, for instance because of the complex position expression. */ field = create_field_decl (get_identifier ("F"), type, record_type, 1, size, pos, -1); finish_record_type (record_type, field, true, false); TYPE_ALIGN (record_type) = BIGGEST_ALIGNMENT; TYPE_SIZE (record_type) = size_binop (PLUS_EXPR, size_binop (MULT_EXPR, convert (bitsizetype, size), bitsize_unit_node), bitsize_int (align)); TYPE_SIZE_UNIT (record_type) = size_binop (PLUS_EXPR, size, size_int (align / BITS_PER_UNIT)); copy_alias_set (record_type, type); return record_type; } /* TYPE is a RECORD_TYPE, UNION_TYPE, or QUAL_UNION_TYPE, with BLKmode that's being used as the field type of a packed record. See if we can rewrite it as a record that has a non-BLKmode type, which we can pack tighter. If so, return the new type. If not, return the original type. */ static tree make_packable_type (tree type) { tree new_type = make_node (TREE_CODE (type)); tree field_list = NULL_TREE; tree old_field; /* Copy the name and flags from the old type to that of the new and set the alignment to try for an integral type. For QUAL_UNION_TYPE, also copy the size. */ TYPE_NAME (new_type) = TYPE_NAME (type); TYPE_JUSTIFIED_MODULAR_P (new_type) = TYPE_JUSTIFIED_MODULAR_P (type); TYPE_CONTAINS_TEMPLATE_P (new_type) = TYPE_CONTAINS_TEMPLATE_P (type); if (TREE_CODE (type) == RECORD_TYPE) TYPE_IS_PADDING_P (new_type) = TYPE_IS_PADDING_P (type); else if (TREE_CODE (type) == QUAL_UNION_TYPE) { TYPE_SIZE (new_type) = TYPE_SIZE (type); TYPE_SIZE_UNIT (new_type) = TYPE_SIZE_UNIT (type); } TYPE_ALIGN (new_type) = ((HOST_WIDE_INT) 1 << (floor_log2 (tree_low_cst (TYPE_SIZE (type), 1) - 1) + 1)); /* Now copy the fields, keeping the position and size. */ for (old_field = TYPE_FIELDS (type); old_field; old_field = TREE_CHAIN (old_field)) { tree new_field_type = TREE_TYPE (old_field); tree new_field; if (TYPE_MODE (new_field_type) == BLKmode && (TREE_CODE (new_field_type) == RECORD_TYPE || TREE_CODE (new_field_type) == UNION_TYPE || TREE_CODE (new_field_type) == QUAL_UNION_TYPE) && host_integerp (TYPE_SIZE (new_field_type), 1)) new_field_type = make_packable_type (new_field_type); new_field = create_field_decl (DECL_NAME (old_field), new_field_type, new_type, TYPE_PACKED (type), DECL_SIZE (old_field), bit_position (old_field), !DECL_NONADDRESSABLE_P (old_field)); DECL_INTERNAL_P (new_field) = DECL_INTERNAL_P (old_field); SET_DECL_ORIGINAL_FIELD (new_field, (DECL_ORIGINAL_FIELD (old_field) ? DECL_ORIGINAL_FIELD (old_field) : old_field)); if (TREE_CODE (new_type) == QUAL_UNION_TYPE) DECL_QUALIFIER (new_field) = DECL_QUALIFIER (old_field); TREE_CHAIN (new_field) = field_list; field_list = new_field; } finish_record_type (new_type, nreverse (field_list), true, true); copy_alias_set (new_type, type); return TYPE_MODE (new_type) == BLKmode ? type : new_type; } /* Ensure that TYPE has SIZE and ALIGN. Make and return a new padded type if needed. We have already verified that SIZE and TYPE are large enough. GNAT_ENTITY and NAME_TRAILER are used to name the resulting record and to issue a warning. IS_USER_TYPE is true if we must be sure we complete the original type. DEFINITION is true if this type is being defined. SAME_RM_SIZE is true if the RM_Size of the resulting type is to be set to its TYPE_SIZE; otherwise, it's set to the RM_Size of the original type. */ tree maybe_pad_type (tree type, tree size, unsigned int align, Entity_Id gnat_entity, const char *name_trailer, bool is_user_type, bool definition, bool same_rm_size) { tree orig_size = TYPE_SIZE (type); tree record; tree field; /* If TYPE is a padded type, see if it agrees with any size and alignment we were given. If so, return the original type. Otherwise, strip off the padding, since we will either be returning the inner type or repadding it. If no size or alignment is specified, use that of the original padded type. */ if (TREE_CODE (type) == RECORD_TYPE && TYPE_IS_PADDING_P (type)) { if ((!size || operand_equal_p (round_up (size, MAX (align, TYPE_ALIGN (type))), round_up (TYPE_SIZE (type), MAX (align, TYPE_ALIGN (type))), 0)) && (align == 0 || align == TYPE_ALIGN (type))) return type; if (!size) size = TYPE_SIZE (type); if (align == 0) align = TYPE_ALIGN (type); type = TREE_TYPE (TYPE_FIELDS (type)); orig_size = TYPE_SIZE (type); } /* If the size is either not being changed or is being made smaller (which is not done here (and is only valid for bitfields anyway), show the size isn't changing. Likewise, clear the alignment if it isn't being changed. Then return if we aren't doing anything. */ if (size && (operand_equal_p (size, orig_size, 0) || (TREE_CODE (orig_size) == INTEGER_CST && tree_int_cst_lt (size, orig_size)))) size = NULL_TREE; if (align == TYPE_ALIGN (type)) align = 0; if (align == 0 && !size) return type; /* We used to modify the record in place in some cases, but that could generate incorrect debugging information. So make a new record type and name. */ record = make_node (RECORD_TYPE); if (Present (gnat_entity)) TYPE_NAME (record) = create_concat_name (gnat_entity, name_trailer); /* If we were making a type, complete the original type and give it a name. */ if (is_user_type) create_type_decl (get_entity_name (gnat_entity), type, NULL, !Comes_From_Source (gnat_entity), !(TYPE_NAME (type) && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL && DECL_IGNORED_P (TYPE_NAME (type))), gnat_entity); /* If we are changing the alignment and the input type is a record with BLKmode and a small constant size, try to make a form that has an integral mode. That might allow this record to have an integral mode, which will be much more efficient. There is no point in doing this if a size is specified unless it is also smaller than the biggest alignment and it is incorrect to do this if the size of the original type is not a multiple of the alignment. */ if (align != 0 && TREE_CODE (type) == RECORD_TYPE && TYPE_MODE (type) == BLKmode && host_integerp (orig_size, 1) && compare_tree_int (orig_size, BIGGEST_ALIGNMENT) <= 0 && (!size || (TREE_CODE (size) == INTEGER_CST && compare_tree_int (size, BIGGEST_ALIGNMENT) <= 0)) && tree_low_cst (orig_size, 1) % align == 0) type = make_packable_type (type); field = create_field_decl (get_identifier ("F"), type, record, 0, NULL_TREE, bitsize_zero_node, 1); DECL_INTERNAL_P (field) = 1; TYPE_SIZE (record) = size ? size : orig_size; TYPE_SIZE_UNIT (record) = (size ? convert (sizetype, size_binop (CEIL_DIV_EXPR, size, bitsize_unit_node)) : TYPE_SIZE_UNIT (type)); TYPE_ALIGN (record) = align; TYPE_IS_PADDING_P (record) = 1; TYPE_VOLATILE (record) = Present (gnat_entity) && Treat_As_Volatile (gnat_entity); finish_record_type (record, field, true, false); /* Keep the RM_Size of the padded record as that of the old record if requested. */ SET_TYPE_ADA_SIZE (record, same_rm_size ? size : rm_size (type)); /* Unless debugging information isn't being written for the input type, write a record that shows what we are a subtype of and also make a variable that indicates our size, if variable. */ if (TYPE_NAME (record) && AGGREGATE_TYPE_P (type) && (TREE_CODE (TYPE_NAME (type)) != TYPE_DECL || !DECL_IGNORED_P (TYPE_NAME (type)))) { tree marker = make_node (RECORD_TYPE); tree name = (TREE_CODE (TYPE_NAME (record)) == TYPE_DECL ? DECL_NAME (TYPE_NAME (record)) : TYPE_NAME (record)); tree orig_name = TYPE_NAME (type); if (TREE_CODE (orig_name) == TYPE_DECL) orig_name = DECL_NAME (orig_name); TYPE_NAME (marker) = concat_id_with_name (name, "XVS"); finish_record_type (marker, create_field_decl (orig_name, integer_type_node, marker, 0, NULL_TREE, NULL_TREE, 0), false, false); if (size && TREE_CODE (size) != INTEGER_CST && definition) create_var_decl (concat_id_with_name (name, "XVZ"), NULL_TREE, bitsizetype, TYPE_SIZE (record), false, false, false, false, NULL, gnat_entity); } type = record; if (CONTAINS_PLACEHOLDER_P (orig_size)) orig_size = max_size (orig_size, true); /* If the size was widened explicitly, maybe give a warning. */ if (size && Present (gnat_entity) && !operand_equal_p (size, orig_size, 0) && !(TREE_CODE (size) == INTEGER_CST && TREE_CODE (orig_size) == INTEGER_CST && tree_int_cst_lt (size, orig_size))) { Node_Id gnat_error_node = Empty; if (Is_Packed_Array_Type (gnat_entity)) gnat_entity = Associated_Node_For_Itype (gnat_entity); if ((Ekind (gnat_entity) == E_Component || Ekind (gnat_entity) == E_Discriminant) && Present (Component_Clause (gnat_entity))) gnat_error_node = Last_Bit (Component_Clause (gnat_entity)); else if (Present (Size_Clause (gnat_entity))) gnat_error_node = Expression (Size_Clause (gnat_entity)); /* Generate message only for entities that come from source, since if we have an entity created by expansion, the message will be generated for some other corresponding source entity. */ if (Comes_From_Source (gnat_entity) && Present (gnat_error_node)) post_error_ne_tree ("{^ }bits of & unused?", gnat_error_node, gnat_entity, size_diffop (size, orig_size)); else if (*name_trailer == 'C' && !Is_Internal (gnat_entity)) post_error_ne_tree ("component of& padded{ by ^ bits}?", gnat_entity, gnat_entity, size_diffop (size, orig_size)); } return type; } /* Given a GNU tree and a GNAT list of choices, generate an expression to test the value passed against the list of choices. */ tree choices_to_gnu (tree operand, Node_Id choices) { Node_Id choice; Node_Id gnat_temp; tree result = integer_zero_node; tree this_test, low = 0, high = 0, single = 0; for (choice = First (choices); Present (choice); choice = Next (choice)) { switch (Nkind (choice)) { case N_Range: low = gnat_to_gnu (Low_Bound (choice)); high = gnat_to_gnu (High_Bound (choice)); /* There's no good type to use here, so we might as well use integer_type_node. */ this_test = build_binary_op (TRUTH_ANDIF_EXPR, integer_type_node, build_binary_op (GE_EXPR, integer_type_node, operand, low), build_binary_op (LE_EXPR, integer_type_node, operand, high)); break; case N_Subtype_Indication: gnat_temp = Range_Expression (Constraint (choice)); low = gnat_to_gnu (Low_Bound (gnat_temp)); high = gnat_to_gnu (High_Bound (gnat_temp)); this_test = build_binary_op (TRUTH_ANDIF_EXPR, integer_type_node, build_binary_op (GE_EXPR, integer_type_node, operand, low), build_binary_op (LE_EXPR, integer_type_node, operand, high)); break; case N_Identifier: case N_Expanded_Name: /* This represents either a subtype range, an enumeration literal, or a constant Ekind says which. If an enumeration literal or constant, fall through to the next case. */ if (Ekind (Entity (choice)) != E_Enumeration_Literal && Ekind (Entity (choice)) != E_Constant) { tree type = gnat_to_gnu_type (Entity (choice)); low = TYPE_MIN_VALUE (type); high = TYPE_MAX_VALUE (type); this_test = build_binary_op (TRUTH_ANDIF_EXPR, integer_type_node, build_binary_op (GE_EXPR, integer_type_node, operand, low), build_binary_op (LE_EXPR, integer_type_node, operand, high)); break; } /* ... fall through ... */ case N_Character_Literal: case N_Integer_Literal: single = gnat_to_gnu (choice); this_test = build_binary_op (EQ_EXPR, integer_type_node, operand, single); break; case N_Others_Choice: this_test = integer_one_node; break; default: gcc_unreachable (); } result = build_binary_op (TRUTH_ORIF_EXPR, integer_type_node, result, this_test); } return result; } /* Return a GCC tree for a field corresponding to GNAT_FIELD to be placed in GNU_RECORD_TYPE. PACKED is 1 if the enclosing record is packed and -1 if the enclosing record has a Component_Alignment of Storage_Unit. DEFINITION is true if this field is for a record being defined. */ static tree gnat_to_gnu_field (Entity_Id gnat_field, tree gnu_record_type, int packed, bool definition) { tree gnu_field_id = get_entity_name (gnat_field); tree gnu_field_type = gnat_to_gnu_type (Etype (gnat_field)); tree gnu_pos = 0; tree gnu_size = 0; tree gnu_field; bool needs_strict_alignment = (Is_Aliased (gnat_field) || Strict_Alignment (Etype (gnat_field)) || Treat_As_Volatile (gnat_field)); /* If this field requires strict alignment or contains an item of variable sized, pretend it isn't packed. */ if (needs_strict_alignment || is_variable_size (gnu_field_type)) packed = 0; /* For packed records, this is one of the few occasions on which we use the official RM size for discrete or fixed-point components, instead of the normal GNAT size stored in Esize. See description in Einfo: "Handling of Type'Size Values" for further details. */ if (packed == 1) gnu_size = validate_size (RM_Size (Etype (gnat_field)), gnu_field_type, gnat_field, FIELD_DECL, false, true); if (Known_Static_Esize (gnat_field)) gnu_size = validate_size (Esize (gnat_field), gnu_field_type, gnat_field, FIELD_DECL, false, true); /* If we have a specified size that's smaller than that of the field type, or a position is specified, and the field type is also a record that's BLKmode and with a small constant size, see if we can get an integral mode form of the type when appropriate. If we can, show a size was specified for the field if there wasn't one already, so we know to make this a bitfield and avoid making things wider. Doing this is first useful if the record is packed because we can then place the field at a non-byte-aligned position and so achieve tighter packing. This is in addition *required* if the field shares a byte with another field and the front-end lets the back-end handle the references, because GCC does not handle BLKmode bitfields properly. We avoid the transformation if it is not required or potentially useful, as it might entail an increase of the field's alignment and have ripple effects on the outer record type. A typical case is a field known to be byte aligned and not to share a byte with another field. Besides, we don't even look the possibility of a transformation in cases known to be in error already, for instance when an invalid size results from a component clause. */ if (TREE_CODE (gnu_field_type) == RECORD_TYPE && TYPE_MODE (gnu_field_type) == BLKmode && host_integerp (TYPE_SIZE (gnu_field_type), 1) && compare_tree_int (TYPE_SIZE (gnu_field_type), BIGGEST_ALIGNMENT) <= 0 && (packed == 1 || (gnu_size && tree_int_cst_lt (gnu_size, TYPE_SIZE (gnu_field_type))) || (Present (Component_Clause (gnat_field)) && gnu_size != 0))) { /* See what the alternate type and size would be. */ tree gnu_packable_type = make_packable_type (gnu_field_type); bool has_byte_aligned_clause = Present (Component_Clause (gnat_field)) && (UI_To_Int (Component_Bit_Offset (gnat_field)) % BITS_PER_UNIT == 0); /* Compute whether we should avoid the substitution. */ int reject = /* There is no point substituting if there is no change. */ (gnu_packable_type == gnu_field_type || /* ... nor when the field is known to be byte aligned and not to share a byte with another field. */ (has_byte_aligned_clause && value_factor_p (gnu_size, BITS_PER_UNIT)) || /* The size of an aliased field must be an exact multiple of the type's alignment, which the substitution might increase. Reject substitutions that would so invalidate a component clause when the specified position is byte aligned, as the change would have no real benefit from the packing standpoint anyway. */ (Is_Aliased (gnat_field) && has_byte_aligned_clause && ! value_factor_p (gnu_size, TYPE_ALIGN (gnu_packable_type))) ); /* Substitute unless told otherwise. */ if (!reject) { gnu_field_type = gnu_packable_type; if (gnu_size == 0) gnu_size = rm_size (gnu_field_type); } } /* If we are packing the record and the field is BLKmode, round the size up to a byte boundary. */ if (packed && TYPE_MODE (gnu_field_type) == BLKmode && gnu_size) gnu_size = round_up (gnu_size, BITS_PER_UNIT); if (Present (Component_Clause (gnat_field))) { gnu_pos = UI_To_gnu (Component_Bit_Offset (gnat_field), bitsizetype); gnu_size = validate_size (Esize (gnat_field), gnu_field_type, gnat_field, FIELD_DECL, false, true); /* Ensure the position does not overlap with the parent subtype, if there is one. */ if (Present (Parent_Subtype (Underlying_Type (Scope (gnat_field))))) { tree gnu_parent = gnat_to_gnu_type (Parent_Subtype (Underlying_Type (Scope (gnat_field)))); if (TREE_CODE (TYPE_SIZE (gnu_parent)) == INTEGER_CST && tree_int_cst_lt (gnu_pos, TYPE_SIZE (gnu_parent))) { post_error_ne_tree ("offset of& must be beyond parent{, minimum allowed is ^}", First_Bit (Component_Clause (gnat_field)), gnat_field, TYPE_SIZE_UNIT (gnu_parent)); } } /* If this field needs strict alignment, ensure the record is sufficiently aligned and that that position and size are consistent with the alignment. */ if (needs_strict_alignment) { tree gnu_rounded_size = round_up (rm_size (gnu_field_type), TYPE_ALIGN (gnu_field_type)); TYPE_ALIGN (gnu_record_type) = MAX (TYPE_ALIGN (gnu_record_type), TYPE_ALIGN (gnu_field_type)); /* If Atomic, the size must match exactly that of the field. */ if ((Is_Atomic (gnat_field) || Is_Atomic (Etype (gnat_field))) && !operand_equal_p (gnu_size, TYPE_SIZE (gnu_field_type), 0)) { post_error_ne_tree ("atomic field& must be natural size of type{ (^)}", Last_Bit (Component_Clause (gnat_field)), gnat_field, TYPE_SIZE (gnu_field_type)); gnu_size = NULL_TREE; } /* If Aliased, the size must match exactly the rounded size. We used to be more accommodating here and accept greater sizes, but fully supporting this case on big-endian platforms would require switching to a more involved layout for the field. */ else if (Is_Aliased (gnat_field) && gnu_size && ! operand_equal_p (gnu_size, gnu_rounded_size, 0)) { post_error_ne_tree ("size of aliased field& must be ^ bits", Last_Bit (Component_Clause (gnat_field)), gnat_field, gnu_rounded_size); gnu_size = NULL_TREE; } if (!integer_zerop (size_binop (TRUNC_MOD_EXPR, gnu_pos, bitsize_int (TYPE_ALIGN (gnu_field_type))))) { if (Is_Aliased (gnat_field)) post_error_ne_num ("position of aliased field& must be multiple of ^ bits", First_Bit (Component_Clause (gnat_field)), gnat_field, TYPE_ALIGN (gnu_field_type)); else if (Treat_As_Volatile (gnat_field)) post_error_ne_num ("position of volatile field& must be multiple of ^ bits", First_Bit (Component_Clause (gnat_field)), gnat_field, TYPE_ALIGN (gnu_field_type)); else if (Strict_Alignment (Etype (gnat_field))) post_error_ne_num ("position of & with aliased or tagged components not multiple of ^ bits", First_Bit (Component_Clause (gnat_field)), gnat_field, TYPE_ALIGN (gnu_field_type)); else gcc_unreachable (); gnu_pos = NULL_TREE; } } if (Is_Atomic (gnat_field)) check_ok_for_atomic (gnu_field_type, gnat_field, false); } /* If the record has rep clauses and this is the tag field, make a rep clause for it as well. */ else if (Has_Specified_Layout (Scope (gnat_field)) && Chars (gnat_field) == Name_uTag) { gnu_pos = bitsize_zero_node; gnu_size = TYPE_SIZE (gnu_field_type); } /* We need to make the size the maximum for the type if it is self-referential and an unconstrained type. In that case, we can't pack the field since we can't make a copy to align it. */ if (TREE_CODE (gnu_field_type) == RECORD_TYPE && !gnu_size && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_field_type)) && !Is_Constrained (Underlying_Type (Etype (gnat_field)))) { gnu_size = max_size (TYPE_SIZE (gnu_field_type), true); packed = 0; } /* If no size is specified (or if there was an error), don't specify a position. */ if (!gnu_size) gnu_pos = NULL_TREE; else { /* If the field's type is justified modular, we would need to remove the wrapper to (better) meet the layout requirements. However we can do so only if the field is not aliased to preserve the unique layout and if the prescribed size is not greater than that of the packed array to preserve the justification. */ if (!needs_strict_alignment && TREE_CODE (gnu_field_type) == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (gnu_field_type) && tree_int_cst_compare (gnu_size, TYPE_ADA_SIZE (gnu_field_type)) <= 0) gnu_field_type = TREE_TYPE (TYPE_FIELDS (gnu_field_type)); gnu_field_type = make_type_from_size (gnu_field_type, gnu_size, Has_Biased_Representation (gnat_field)); gnu_field_type = maybe_pad_type (gnu_field_type, gnu_size, 0, gnat_field, "PAD", false, definition, true); } gcc_assert (TREE_CODE (gnu_field_type) != RECORD_TYPE || !TYPE_CONTAINS_TEMPLATE_P (gnu_field_type)); /* Now create the decl for the field. */ gnu_field = create_field_decl (gnu_field_id, gnu_field_type, gnu_record_type, packed, gnu_size, gnu_pos, Is_Aliased (gnat_field)); Sloc_to_locus (Sloc (gnat_field), &DECL_SOURCE_LOCATION (gnu_field)); TREE_THIS_VOLATILE (gnu_field) = Treat_As_Volatile (gnat_field); if (Ekind (gnat_field) == E_Discriminant) DECL_DISCRIMINANT_NUMBER (gnu_field) = UI_To_gnu (Discriminant_Number (gnat_field), sizetype); return gnu_field; } /* Return true if TYPE is a type with variable size, a padding type with a field of variable size or is a record that has a field such a field. */ static bool is_variable_size (tree type) { tree field; /* We need not be concerned about this at all if we don't have strict alignment. */ if (!STRICT_ALIGNMENT) return false; else if (!TREE_CONSTANT (TYPE_SIZE (type))) return true; else if (TREE_CODE (type) == RECORD_TYPE && TYPE_IS_PADDING_P (type) && !TREE_CONSTANT (DECL_SIZE (TYPE_FIELDS (type)))) return true; else if (TREE_CODE (type) != RECORD_TYPE && TREE_CODE (type) != UNION_TYPE && TREE_CODE (type) != QUAL_UNION_TYPE) return false; for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field)) if (is_variable_size (TREE_TYPE (field))) return true; return false; } /* Return a GCC tree for a record type given a GNAT Component_List and a chain of GCC trees for fields that are in the record and have already been processed. When called from gnat_to_gnu_entity during the processing of a record type definition, the GCC nodes for the discriminants will be on the chain. The other calls to this function are recursive calls from itself for the Component_List of a variant and the chain is empty. PACKED is 1 if this is for a record with "pragma pack" and -1 is this is for a record type with "pragma component_alignment (storage_unit)". DEFINITION is true if we are defining this record. P_GNU_REP_LIST, if nonzero, is a pointer to a list to which each field with a rep clause is to be added. If it is nonzero, that is all that should be done with such fields. CANCEL_ALIGNMENT, if true, means the alignment should be zeroed before laying out the record. This means the alignment only serves to force fields to be bitfields, but not require the record to be that aligned. This is used for variants. ALL_REP, if true, means a rep clause was found for all the fields. This simplifies the logic since we know we're not in the mixed case. DEFER_DEBUG, if true, means that the debugging routines should not be called when finishing constructing the record type. UNCHECKED_UNION, if tree, means that we are building a type for a record with a Pragma Unchecked_Union. The processing of the component list fills in the chain with all of the fields of the record and then the record type is finished. */ static void components_to_record (tree gnu_record_type, Node_Id component_list, tree gnu_field_list, int packed, bool definition, tree *p_gnu_rep_list, bool cancel_alignment, bool all_rep, bool defer_debug, bool unchecked_union) { Node_Id component_decl; Entity_Id gnat_field; Node_Id variant_part; tree gnu_our_rep_list = NULL_TREE; tree gnu_field, gnu_last; bool layout_with_rep = false; bool all_rep_and_size = all_rep && TYPE_SIZE (gnu_record_type); /* For each variable within each component declaration create a GCC field and add it to the list, skipping any pragmas in the list. */ if (Present (Component_Items (component_list))) for (component_decl = First_Non_Pragma (Component_Items (component_list)); Present (component_decl); component_decl = Next_Non_Pragma (component_decl)) { gnat_field = Defining_Entity (component_decl); if (Chars (gnat_field) == Name_uParent) gnu_field = tree_last (TYPE_FIELDS (gnu_record_type)); else { gnu_field = gnat_to_gnu_field (gnat_field, gnu_record_type, packed, definition); /* If this is the _Tag field, put it before any discriminants, instead of after them as is the case for all other fields. Ignore field of void type if only annotating. */ if (Chars (gnat_field) == Name_uTag) gnu_field_list = chainon (gnu_field_list, gnu_field); else { TREE_CHAIN (gnu_field) = gnu_field_list; gnu_field_list = gnu_field; } } save_gnu_tree (gnat_field, gnu_field, false); } /* At the end of the component list there may be a variant part. */ variant_part = Variant_Part (component_list); /* We create a QUAL_UNION_TYPE for the variant part since the variants are mutually exclusive and should go in the same memory. To do this we need to treat each variant as a record whose elements are created from the component list for the variant. So here we create the records from the lists for the variants and put them all into the QUAL_UNION_TYPE. If this is an Unchecked_Union, we make a UNION_TYPE instead or use GNU_RECORD_TYPE if there are no fields so far. */ if (Present (variant_part)) { tree gnu_discriminant = gnat_to_gnu (Name (variant_part)); Node_Id variant; tree gnu_name = TYPE_NAME (gnu_record_type); tree gnu_var_name = concat_id_with_name (get_identifier (Get_Name_String (Chars (Name (variant_part)))), "XVN"); tree gnu_union_type; tree gnu_union_name; tree gnu_union_field; tree gnu_variant_list = NULL_TREE; if (TREE_CODE (gnu_name) == TYPE_DECL) gnu_name = DECL_NAME (gnu_name); gnu_union_name = concat_id_with_name (gnu_name, IDENTIFIER_POINTER (gnu_var_name)); if (!gnu_field_list && TREE_CODE (gnu_record_type) == UNION_TYPE) gnu_union_type = gnu_record_type; else { gnu_union_type = make_node (unchecked_union ? UNION_TYPE : QUAL_UNION_TYPE); TYPE_NAME (gnu_union_type) = gnu_union_name; TYPE_PACKED (gnu_union_type) = TYPE_PACKED (gnu_record_type); } for (variant = First_Non_Pragma (Variants (variant_part)); Present (variant); variant = Next_Non_Pragma (variant)) { tree gnu_variant_type = make_node (RECORD_TYPE); tree gnu_inner_name; tree gnu_qual; Get_Variant_Encoding (variant); gnu_inner_name = get_identifier (Name_Buffer); TYPE_NAME (gnu_variant_type) = concat_id_with_name (gnu_union_name, IDENTIFIER_POINTER (gnu_inner_name)); /* Set the alignment of the inner type in case we need to make inner objects into bitfields, but then clear it out so the record actually gets only the alignment required. */ TYPE_ALIGN (gnu_variant_type) = TYPE_ALIGN (gnu_record_type); TYPE_PACKED (gnu_variant_type) = TYPE_PACKED (gnu_record_type); /* Similarly, if the outer record has a size specified and all fields have record rep clauses, we can propagate the size into the variant part. */ if (all_rep_and_size) { TYPE_SIZE (gnu_variant_type) = TYPE_SIZE (gnu_record_type); TYPE_SIZE_UNIT (gnu_variant_type) = TYPE_SIZE_UNIT (gnu_record_type); } /* Create the record for the variant. Note that we defer emitting debug info for it until after we are sure to actually use it. */ components_to_record (gnu_variant_type, Component_List (variant), NULL_TREE, packed, definition, &gnu_our_rep_list, !all_rep_and_size, all_rep, true, unchecked_union); gnu_qual = choices_to_gnu (gnu_discriminant, Discrete_Choices (variant)); Set_Present_Expr (variant, annotate_value (gnu_qual)); /* If this is an Unchecked_Union and we have exactly one field, use that field here. */ if (unchecked_union && TYPE_FIELDS (gnu_variant_type) && !TREE_CHAIN (TYPE_FIELDS (gnu_variant_type))) gnu_field = TYPE_FIELDS (gnu_variant_type); else { /* Emit debug info for the record. We used to throw away empty records but we no longer do that because we need them to generate complete debug info for the variant; otherwise, the union type definition will be lacking the fields associated with these empty variants. */ write_record_type_debug_info (gnu_variant_type); gnu_field = create_field_decl (gnu_inner_name, gnu_variant_type, gnu_union_type, 0, (all_rep_and_size ? TYPE_SIZE (gnu_record_type) : 0), (all_rep_and_size ? bitsize_zero_node : 0), 0); DECL_INTERNAL_P (gnu_field) = 1; if (!unchecked_union) DECL_QUALIFIER (gnu_field) = gnu_qual; } TREE_CHAIN (gnu_field) = gnu_variant_list; gnu_variant_list = gnu_field; } /* Only make the QUAL_UNION_TYPE if there are any non-empty variants. */ if (gnu_variant_list) { if (all_rep_and_size) { TYPE_SIZE (gnu_union_type) = TYPE_SIZE (gnu_record_type); TYPE_SIZE_UNIT (gnu_union_type) = TYPE_SIZE_UNIT (gnu_record_type); } finish_record_type (gnu_union_type, nreverse (gnu_variant_list), all_rep_and_size, false); /* If GNU_UNION_TYPE is our record type, it means we must have an Unchecked_Union with no fields. Verify that and, if so, just return. */ if (gnu_union_type == gnu_record_type) { gcc_assert (!gnu_field_list && unchecked_union); return; } gnu_union_field = create_field_decl (gnu_var_name, gnu_union_type, gnu_record_type, packed, all_rep ? TYPE_SIZE (gnu_union_type) : 0, all_rep ? bitsize_zero_node : 0, 0); DECL_INTERNAL_P (gnu_union_field) = 1; TREE_CHAIN (gnu_union_field) = gnu_field_list; gnu_field_list = gnu_union_field; } } /* Scan GNU_FIELD_LIST and see if any fields have rep clauses. If they do, pull them out and put them into GNU_OUR_REP_LIST. We have to do this in a separate pass since we want to handle the discriminants but can't play with them until we've used them in debugging data above. ??? Note: if we then reorder them, debugging information will be wrong, but there's nothing that can be done about this at the moment. */ for (gnu_field = gnu_field_list, gnu_last = NULL_TREE; gnu_field; ) { if (DECL_FIELD_OFFSET (gnu_field)) { tree gnu_next = TREE_CHAIN (gnu_field); if (!gnu_last) gnu_field_list = gnu_next; else TREE_CHAIN (gnu_last) = gnu_next; TREE_CHAIN (gnu_field) = gnu_our_rep_list; gnu_our_rep_list = gnu_field; gnu_field = gnu_next; } else { gnu_last = gnu_field; gnu_field = TREE_CHAIN (gnu_field); } } /* If we have any items in our rep'ed field list, it is not the case that all the fields in the record have rep clauses, and P_REP_LIST is nonzero, set it and ignore the items. */ if (gnu_our_rep_list && p_gnu_rep_list && !all_rep) *p_gnu_rep_list = chainon (*p_gnu_rep_list, gnu_our_rep_list); else if (gnu_our_rep_list) { /* Otherwise, sort the fields by bit position and put them into their own record if we have any fields without rep clauses. */ tree gnu_rep_type = (gnu_field_list ? make_node (RECORD_TYPE) : gnu_record_type); int len = list_length (gnu_our_rep_list); tree *gnu_arr = (tree *) alloca (sizeof (tree) * len); int i; for (i = 0, gnu_field = gnu_our_rep_list; gnu_field; gnu_field = TREE_CHAIN (gnu_field), i++) gnu_arr[i] = gnu_field; qsort (gnu_arr, len, sizeof (tree), compare_field_bitpos); /* Put the fields in the list in order of increasing position, which means we start from the end. */ gnu_our_rep_list = NULL_TREE; for (i = len - 1; i >= 0; i--) { TREE_CHAIN (gnu_arr[i]) = gnu_our_rep_list; gnu_our_rep_list = gnu_arr[i]; DECL_CONTEXT (gnu_arr[i]) = gnu_rep_type; } if (gnu_field_list) { finish_record_type (gnu_rep_type, gnu_our_rep_list, true, false); gnu_field = create_field_decl (get_identifier ("REP"), gnu_rep_type, gnu_record_type, 0, 0, 0, 1); DECL_INTERNAL_P (gnu_field) = 1; gnu_field_list = chainon (gnu_field_list, gnu_field); } else { layout_with_rep = true; gnu_field_list = nreverse (gnu_our_rep_list); } } if (cancel_alignment) TYPE_ALIGN (gnu_record_type) = 0; finish_record_type (gnu_record_type, nreverse (gnu_field_list), layout_with_rep, defer_debug); } /* Called via qsort from the above. Returns -1, 1, depending on the bit positions and ordinals of the two fields. Use DECL_UID to ensure a stable sort. */ static int compare_field_bitpos (const PTR rt1, const PTR rt2) { tree *t1 = (tree *) rt1; tree *t2 = (tree *) rt2; if (tree_int_cst_equal (bit_position (*t1), bit_position (*t2))) return DECL_UID (*t1) < DECL_UID (*t2) ? -1 : 1; else if (tree_int_cst_lt (bit_position (*t1), bit_position (*t2))) return -1; else return 1; } /* Given GNU_SIZE, a GCC tree representing a size, return a Uint to be placed into an Esize, Component_Bit_Offset, or Component_Size value in the GNAT tree. */ static Uint annotate_value (tree gnu_size) { int len = TREE_CODE_LENGTH (TREE_CODE (gnu_size)); TCode tcode; Node_Ref_Or_Val ops[3], ret; int i; int size; /* See if we've already saved the value for this node. */ if (EXPR_P (gnu_size) && TREE_COMPLEXITY (gnu_size)) return (Node_Ref_Or_Val) TREE_COMPLEXITY (gnu_size); /* If we do not return inside this switch, TCODE will be set to the code to use for a Create_Node operand and LEN (set above) will be the number of recursive calls for us to make. */ switch (TREE_CODE (gnu_size)) { case INTEGER_CST: if (TREE_OVERFLOW (gnu_size)) return No_Uint; /* This may have come from a conversion from some smaller type, so ensure this is in bitsizetype. */ gnu_size = convert (bitsizetype, gnu_size); /* For negative values, use NEGATE_EXPR of the supplied value. */ if (tree_int_cst_sgn (gnu_size) < 0) { /* The ridiculous code below is to handle the case of the largest negative integer. */ tree negative_size = size_diffop (bitsize_zero_node, gnu_size); bool adjust = false; tree temp; if (TREE_CONSTANT_OVERFLOW (negative_size)) { negative_size = size_binop (MINUS_EXPR, bitsize_zero_node, size_binop (PLUS_EXPR, gnu_size, bitsize_one_node)); adjust = true; } temp = build1 (NEGATE_EXPR, bitsizetype, negative_size); if (adjust) temp = build2 (MINUS_EXPR, bitsizetype, temp, bitsize_one_node); return annotate_value (temp); } if (!host_integerp (gnu_size, 1)) return No_Uint; size = tree_low_cst (gnu_size, 1); /* This peculiar test is to make sure that the size fits in an int on machines where HOST_WIDE_INT is not "int". */ if (tree_low_cst (gnu_size, 1) == size) return UI_From_Int (size); else return No_Uint; case COMPONENT_REF: /* The only case we handle here is a simple discriminant reference. */ if (TREE_CODE (TREE_OPERAND (gnu_size, 0)) == PLACEHOLDER_EXPR && TREE_CODE (TREE_OPERAND (gnu_size, 1)) == FIELD_DECL && DECL_DISCRIMINANT_NUMBER (TREE_OPERAND (gnu_size, 1))) return Create_Node (Discrim_Val, annotate_value (DECL_DISCRIMINANT_NUMBER (TREE_OPERAND (gnu_size, 1))), No_Uint, No_Uint); else return No_Uint; case NOP_EXPR: case CONVERT_EXPR: case NON_LVALUE_EXPR: return annotate_value (TREE_OPERAND (gnu_size, 0)); /* Now just list the operations we handle. */ case COND_EXPR: tcode = Cond_Expr; break; case PLUS_EXPR: tcode = Plus_Expr; break; case MINUS_EXPR: tcode = Minus_Expr; break; case MULT_EXPR: tcode = Mult_Expr; break; case TRUNC_DIV_EXPR: tcode = Trunc_Div_Expr; break; case CEIL_DIV_EXPR: tcode = Ceil_Div_Expr; break; case FLOOR_DIV_EXPR: tcode = Floor_Div_Expr; break; case TRUNC_MOD_EXPR: tcode = Trunc_Mod_Expr; break; case CEIL_MOD_EXPR: tcode = Ceil_Mod_Expr; break; case FLOOR_MOD_EXPR: tcode = Floor_Mod_Expr; break; case EXACT_DIV_EXPR: tcode = Exact_Div_Expr; break; case NEGATE_EXPR: tcode = Negate_Expr; break; case MIN_EXPR: tcode = Min_Expr; break; case MAX_EXPR: tcode = Max_Expr; break; case ABS_EXPR: tcode = Abs_Expr; break; case TRUTH_ANDIF_EXPR: tcode = Truth_Andif_Expr; break; case TRUTH_ORIF_EXPR: tcode = Truth_Orif_Expr; break; case TRUTH_AND_EXPR: tcode = Truth_And_Expr; break; case TRUTH_OR_EXPR: tcode = Truth_Or_Expr; break; case TRUTH_XOR_EXPR: tcode = Truth_Xor_Expr; break; case TRUTH_NOT_EXPR: tcode = Truth_Not_Expr; break; case BIT_AND_EXPR: tcode = Bit_And_Expr; break; case LT_EXPR: tcode = Lt_Expr; break; case LE_EXPR: tcode = Le_Expr; break; case GT_EXPR: tcode = Gt_Expr; break; case GE_EXPR: tcode = Ge_Expr; break; case EQ_EXPR: tcode = Eq_Expr; break; case NE_EXPR: tcode = Ne_Expr; break; default: return No_Uint; } /* Now get each of the operands that's relevant for this code. If any cannot be expressed as a repinfo node, say we can't. */ for (i = 0; i < 3; i++) ops[i] = No_Uint; for (i = 0; i < len; i++) { ops[i] = annotate_value (TREE_OPERAND (gnu_size, i)); if (ops[i] == No_Uint) return No_Uint; } ret = Create_Node (tcode, ops[0], ops[1], ops[2]); TREE_COMPLEXITY (gnu_size) = ret; return ret; } /* Given GNAT_ENTITY, a record type, and GNU_TYPE, its corresponding GCC type, set Component_Bit_Offset and Esize to the position and size used by Gigi. */ static void annotate_rep (Entity_Id gnat_entity, tree gnu_type) { tree gnu_list; tree gnu_entry; Entity_Id gnat_field; /* We operate by first making a list of all fields and their positions (we can get the sizes easily at any time) by a recursive call and then update all the sizes into the tree. */ gnu_list = compute_field_positions (gnu_type, NULL_TREE, size_zero_node, bitsize_zero_node, BIGGEST_ALIGNMENT); for (gnat_field = First_Entity (gnat_entity); Present (gnat_field); gnat_field = Next_Entity (gnat_field)) if ((Ekind (gnat_field) == E_Component || (Ekind (gnat_field) == E_Discriminant && !Is_Unchecked_Union (Scope (gnat_field))))) { tree parent_offset = bitsize_zero_node; gnu_entry = purpose_member (gnat_to_gnu_field_decl (gnat_field), gnu_list); if (gnu_entry) { if (type_annotate_only && Is_Tagged_Type (gnat_entity)) { /* In this mode the tag and parent components have not been generated, so we add the appropriate offset to each component. For a component appearing in the current extension, the offset is the size of the parent. */ if (Is_Derived_Type (gnat_entity) && Original_Record_Component (gnat_field) == gnat_field) parent_offset = UI_To_gnu (Esize (Etype (Base_Type (gnat_entity))), bitsizetype); else parent_offset = bitsize_int (POINTER_SIZE); } Set_Component_Bit_Offset (gnat_field, annotate_value (size_binop (PLUS_EXPR, bit_from_pos (TREE_PURPOSE (TREE_VALUE (gnu_entry)), TREE_VALUE (TREE_VALUE (TREE_VALUE (gnu_entry)))), parent_offset))); Set_Esize (gnat_field, annotate_value (DECL_SIZE (TREE_PURPOSE (gnu_entry)))); } else if (Is_Tagged_Type (gnat_entity) && Is_Derived_Type (gnat_entity)) { /* If there is no gnu_entry, this is an inherited component whose position is the same as in the parent type. */ Set_Component_Bit_Offset (gnat_field, Component_Bit_Offset (Original_Record_Component (gnat_field))); Set_Esize (gnat_field, Esize (Original_Record_Component (gnat_field))); } } } /* Scan all fields in GNU_TYPE and build entries where TREE_PURPOSE is the FIELD_DECL and TREE_VALUE a TREE_LIST with TREE_PURPOSE being the byte position and TREE_VALUE being a TREE_LIST with TREE_PURPOSE the value to be placed into DECL_OFFSET_ALIGN and TREE_VALUE the bit position. GNU_POS is to be added to the position, GNU_BITPOS to the bit position, OFFSET_ALIGN is the present value of DECL_OFFSET_ALIGN and GNU_LIST is a list of the entries so far. */ static tree compute_field_positions (tree gnu_type, tree gnu_list, tree gnu_pos, tree gnu_bitpos, unsigned int offset_align) { tree gnu_field; tree gnu_result = gnu_list; for (gnu_field = TYPE_FIELDS (gnu_type); gnu_field; gnu_field = TREE_CHAIN (gnu_field)) { tree gnu_our_bitpos = size_binop (PLUS_EXPR, gnu_bitpos, DECL_FIELD_BIT_OFFSET (gnu_field)); tree gnu_our_offset = size_binop (PLUS_EXPR, gnu_pos, DECL_FIELD_OFFSET (gnu_field)); unsigned int our_offset_align = MIN (offset_align, DECL_OFFSET_ALIGN (gnu_field)); gnu_result = tree_cons (gnu_field, tree_cons (gnu_our_offset, tree_cons (size_int (our_offset_align), gnu_our_bitpos, NULL_TREE), NULL_TREE), gnu_result); if (DECL_INTERNAL_P (gnu_field)) gnu_result = compute_field_positions (TREE_TYPE (gnu_field), gnu_result, gnu_our_offset, gnu_our_bitpos, our_offset_align); } return gnu_result; } /* UINT_SIZE is a Uint giving the specified size for an object of GNU_TYPE corresponding to GNAT_OBJECT. If size is valid, return a tree corresponding to its value. Otherwise return 0. KIND is VAR_DECL is we are specifying the size for an object, TYPE_DECL for the size of a type, and FIELD_DECL for the size of a field. COMPONENT_P is true if we are being called to process the Component_Size of GNAT_OBJECT. This is used for error message handling and to indicate to use the object size of GNU_TYPE. ZERO_OK is true if a size of zero is permitted; if ZERO_OK is false, it means that a size of zero should be treated as an unspecified size. */ static tree validate_size (Uint uint_size, tree gnu_type, Entity_Id gnat_object, enum tree_code kind, bool component_p, bool zero_ok) { Node_Id gnat_error_node; tree type_size = kind == VAR_DECL ? TYPE_SIZE (gnu_type) : rm_size (gnu_type); tree size; /* Find the node to use for errors. */ if ((Ekind (gnat_object) == E_Component || Ekind (gnat_object) == E_Discriminant) && Present (Component_Clause (gnat_object))) gnat_error_node = Last_Bit (Component_Clause (gnat_object)); else if (Present (Size_Clause (gnat_object))) gnat_error_node = Expression (Size_Clause (gnat_object)); else gnat_error_node = gnat_object; /* Return 0 if no size was specified, either because Esize was not Present or the specified size was zero. */ if (No (uint_size) || uint_size == No_Uint) return NULL_TREE; /* Get the size as a tree. Give an error if a size was specified, but cannot be represented as in sizetype. */ size = UI_To_gnu (uint_size, bitsizetype); if (TREE_OVERFLOW (size)) { post_error_ne (component_p ? "component size of & is too large" : "size of & is too large", gnat_error_node, gnat_object); return NULL_TREE; } /* Ignore a negative size since that corresponds to our back-annotation. Also ignore a zero size unless a size clause exists. */ else if (tree_int_cst_sgn (size) < 0 || (integer_zerop (size) && !zero_ok)) return NULL_TREE; /* The size of objects is always a multiple of a byte. */ if (kind == VAR_DECL && !integer_zerop (size_binop (TRUNC_MOD_EXPR, size, bitsize_unit_node))) { if (component_p) post_error_ne ("component size for& is not a multiple of Storage_Unit", gnat_error_node, gnat_object); else post_error_ne ("size for& is not a multiple of Storage_Unit", gnat_error_node, gnat_object); return NULL_TREE; } /* If this is an integral type or a packed array type, the front-end has verified the size, so we need not do it here (which would entail checking against the bounds). However, if this is an aliased object, it may not be smaller than the type of the object. */ if ((INTEGRAL_TYPE_P (gnu_type) || TYPE_IS_PACKED_ARRAY_TYPE_P (gnu_type)) && !(kind == VAR_DECL && Is_Aliased (gnat_object))) return size; /* If the object is a record that contains a template, add the size of the template to the specified size. */ if (TREE_CODE (gnu_type) == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (gnu_type)) size = size_binop (PLUS_EXPR, DECL_SIZE (TYPE_FIELDS (gnu_type)), size); /* Modify the size of the type to be that of the maximum size if it has a discriminant or the size of a thin pointer if this is a fat pointer. */ if (type_size && CONTAINS_PLACEHOLDER_P (type_size)) type_size = max_size (type_size, true); else if (TYPE_FAT_POINTER_P (gnu_type)) type_size = bitsize_int (POINTER_SIZE); /* If this is an access type, the minimum size is that given by the smallest integral mode that's valid for pointers. */ if (TREE_CODE (gnu_type) == POINTER_TYPE) { enum machine_mode p_mode; for (p_mode = GET_CLASS_NARROWEST_MODE (MODE_INT); !targetm.valid_pointer_mode (p_mode); p_mode = GET_MODE_WIDER_MODE (p_mode)) ; type_size = bitsize_int (GET_MODE_BITSIZE (p_mode)); } /* If the size of the object is a constant, the new size must not be smaller. */ if (TREE_CODE (type_size) != INTEGER_CST || TREE_OVERFLOW (type_size) || tree_int_cst_lt (size, type_size)) { if (component_p) post_error_ne_tree ("component size for& too small{, minimum allowed is ^}", gnat_error_node, gnat_object, type_size); else post_error_ne_tree ("size for& too small{, minimum allowed is ^}", gnat_error_node, gnat_object, type_size); if (kind == VAR_DECL && !component_p && TREE_CODE (rm_size (gnu_type)) == INTEGER_CST && !tree_int_cst_lt (size, rm_size (gnu_type))) post_error_ne_tree_2 ("\\size of ^ is not a multiple of alignment (^ bits)", gnat_error_node, gnat_object, rm_size (gnu_type), TYPE_ALIGN (gnu_type)); else if (INTEGRAL_TYPE_P (gnu_type)) post_error_ne ("\\size would be legal if & were not aliased!", gnat_error_node, gnat_object); return NULL_TREE; } return size; } /* Similarly, but both validate and process a value of RM_Size. This routine is only called for types. */ static void set_rm_size (Uint uint_size, tree gnu_type, Entity_Id gnat_entity) { /* Only give an error if a Value_Size clause was explicitly given. Otherwise, we'd be duplicating an error on the Size clause. */ Node_Id gnat_attr_node = Get_Attribute_Definition_Clause (gnat_entity, Attr_Value_Size); tree old_size = rm_size (gnu_type); tree size; /* Get the size as a tree. Do nothing if none was specified, either because RM_Size was not Present or if the specified size was zero. Give an error if a size was specified, but cannot be represented as in sizetype. */ if (No (uint_size) || uint_size == No_Uint) return; size = UI_To_gnu (uint_size, bitsizetype); if (TREE_OVERFLOW (size)) { if (Present (gnat_attr_node)) post_error_ne ("Value_Size of & is too large", gnat_attr_node, gnat_entity); return; } /* Ignore a negative size since that corresponds to our back-annotation. Also ignore a zero size unless a size clause exists, a Value_Size clause exists, or this is an integer type, in which case the front end will have always set it. */ else if (tree_int_cst_sgn (size) < 0 || (integer_zerop (size) && No (gnat_attr_node) && !Has_Size_Clause (gnat_entity) && !Is_Discrete_Or_Fixed_Point_Type (gnat_entity))) return; /* If the old size is self-referential, get the maximum size. */ if (CONTAINS_PLACEHOLDER_P (old_size)) old_size = max_size (old_size, true); /* If the size of the object is a constant, the new size must not be smaller (the front end checks this for scalar types). */ if (TREE_CODE (old_size) != INTEGER_CST || TREE_OVERFLOW (old_size) || (AGGREGATE_TYPE_P (gnu_type) && tree_int_cst_lt (size, old_size))) { if (Present (gnat_attr_node)) post_error_ne_tree ("Value_Size for& too small{, minimum allowed is ^}", gnat_attr_node, gnat_entity, old_size); return; } /* Otherwise, set the RM_Size. */ if (TREE_CODE (gnu_type) == INTEGER_TYPE && Is_Discrete_Or_Fixed_Point_Type (gnat_entity)) TYPE_RM_SIZE_NUM (gnu_type) = size; else if (TREE_CODE (gnu_type) == ENUMERAL_TYPE) TYPE_RM_SIZE_NUM (gnu_type) = size; else if ((TREE_CODE (gnu_type) == RECORD_TYPE || TREE_CODE (gnu_type) == UNION_TYPE || TREE_CODE (gnu_type) == QUAL_UNION_TYPE) && !TYPE_IS_FAT_POINTER_P (gnu_type)) SET_TYPE_ADA_SIZE (gnu_type, size); } /* Given a type TYPE, return a new type whose size is appropriate for SIZE. If TYPE is the best type, return it. Otherwise, make a new type. We only support new integral and pointer types. BIASED_P is nonzero if we are making a biased type. */ static tree make_type_from_size (tree type, tree size_tree, bool biased_p) { tree new_type; unsigned HOST_WIDE_INT size; bool unsigned_p; /* If size indicates an error, just return TYPE to avoid propagating the error. Likewise if it's too large to represent. */ if (!size_tree || !host_integerp (size_tree, 1)) return type; size = tree_low_cst (size_tree, 1); switch (TREE_CODE (type)) { case INTEGER_TYPE: case ENUMERAL_TYPE: /* Only do something if the type is not already the proper size and is not a packed array type. */ if (TYPE_PACKED_ARRAY_TYPE_P (type) || (TYPE_PRECISION (type) == size && biased_p == (TREE_CODE (type) == INTEGER_CST && TYPE_BIASED_REPRESENTATION_P (type)))) break; biased_p |= (TREE_CODE (type) == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (type)); unsigned_p = TYPE_UNSIGNED (type) || biased_p; size = MIN (size, LONG_LONG_TYPE_SIZE); new_type = unsigned_p ? make_unsigned_type (size) : make_signed_type (size); TREE_TYPE (new_type) = TREE_TYPE (type) ? TREE_TYPE (type) : type; TYPE_MIN_VALUE (new_type) = convert (TREE_TYPE (new_type), TYPE_MIN_VALUE (type)); TYPE_MAX_VALUE (new_type) = convert (TREE_TYPE (new_type), TYPE_MAX_VALUE (type)); TYPE_BIASED_REPRESENTATION_P (new_type) = biased_p; TYPE_RM_SIZE_NUM (new_type) = bitsize_int (size); return new_type; case RECORD_TYPE: /* Do something if this is a fat pointer, in which case we may need to return the thin pointer. */ if (TYPE_IS_FAT_POINTER_P (type) && size < POINTER_SIZE * 2) return build_pointer_type (TYPE_OBJECT_RECORD_TYPE (TYPE_UNCONSTRAINED_ARRAY (type))); break; case POINTER_TYPE: /* Only do something if this is a thin pointer, in which case we may need to return the fat pointer. */ if (TYPE_THIN_POINTER_P (type) && size >= POINTER_SIZE * 2) return build_pointer_type (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type))); break; default: break; } return type; } /* ALIGNMENT is a Uint giving the alignment specified for GNAT_ENTITY, a type or object whose present alignment is ALIGN. If this alignment is valid, return it. Otherwise, give an error and return ALIGN. */ static unsigned int validate_alignment (Uint alignment, Entity_Id gnat_entity, unsigned int align) { Node_Id gnat_error_node = gnat_entity; unsigned int new_align; #ifndef MAX_OFILE_ALIGNMENT #define MAX_OFILE_ALIGNMENT BIGGEST_ALIGNMENT #endif if (Present (Alignment_Clause (gnat_entity))) gnat_error_node = Expression (Alignment_Clause (gnat_entity)); /* Don't worry about checking alignment if alignment was not specified by the source program and we already posted an error for this entity. */ if (Error_Posted (gnat_entity) && !Has_Alignment_Clause (gnat_entity)) return align; /* Within GCC, an alignment is an integer, so we must make sure a value is specified that fits in that range. Also, alignments of more than MAX_OFILE_ALIGNMENT can't be supported. */ if (! UI_Is_In_Int_Range (alignment) || ((new_align = UI_To_Int (alignment)) > MAX_OFILE_ALIGNMENT / BITS_PER_UNIT)) post_error_ne_num ("largest supported alignment for& is ^", gnat_error_node, gnat_entity, MAX_OFILE_ALIGNMENT / BITS_PER_UNIT); else if (!(Present (Alignment_Clause (gnat_entity)) && From_At_Mod (Alignment_Clause (gnat_entity))) && new_align * BITS_PER_UNIT < align) post_error_ne_num ("alignment for& must be at least ^", gnat_error_node, gnat_entity, align / BITS_PER_UNIT); else align = MAX (align, new_align == 0 ? 1 : new_align * BITS_PER_UNIT); return align; } /* Verify that OBJECT, a type or decl, is something we can implement atomically. If not, give an error for GNAT_ENTITY. COMP_P is true if we require atomic components. */ static void check_ok_for_atomic (tree object, Entity_Id gnat_entity, bool comp_p) { Node_Id gnat_error_point = gnat_entity; Node_Id gnat_node; enum machine_mode mode; unsigned int align; tree size; /* There are three case of what OBJECT can be. It can be a type, in which case we take the size, alignment and mode from the type. It can be a declaration that was indirect, in which case the relevant values are that of the type being pointed to, or it can be a normal declaration, in which case the values are of the decl. The code below assumes that OBJECT is either a type or a decl. */ if (TYPE_P (object)) { mode = TYPE_MODE (object); align = TYPE_ALIGN (object); size = TYPE_SIZE (object); } else if (DECL_BY_REF_P (object)) { mode = TYPE_MODE (TREE_TYPE (TREE_TYPE (object))); align = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (object))); size = TYPE_SIZE (TREE_TYPE (TREE_TYPE (object))); } else { mode = DECL_MODE (object); align = DECL_ALIGN (object); size = DECL_SIZE (object); } /* Consider all floating-point types atomic and any types that that are represented by integers no wider than a machine word. */ if (GET_MODE_CLASS (mode) == MODE_FLOAT || ((GET_MODE_CLASS (mode) == MODE_INT || GET_MODE_CLASS (mode) == MODE_PARTIAL_INT) && GET_MODE_BITSIZE (mode) <= BITS_PER_WORD)) return; /* For the moment, also allow anything that has an alignment equal to its size and which is smaller than a word. */ if (size && TREE_CODE (size) == INTEGER_CST && compare_tree_int (size, align) == 0 && align <= BITS_PER_WORD) return; for (gnat_node = First_Rep_Item (gnat_entity); Present (gnat_node); gnat_node = Next_Rep_Item (gnat_node)) { if (!comp_p && Nkind (gnat_node) == N_Pragma && Get_Pragma_Id (Chars (gnat_node)) == Pragma_Atomic) gnat_error_point = First (Pragma_Argument_Associations (gnat_node)); else if (comp_p && Nkind (gnat_node) == N_Pragma && (Get_Pragma_Id (Chars (gnat_node)) == Pragma_Atomic_Components)) gnat_error_point = First (Pragma_Argument_Associations (gnat_node)); } if (comp_p) post_error_ne ("atomic access to component of & cannot be guaranteed", gnat_error_point, gnat_entity); else post_error_ne ("atomic access to & cannot be guaranteed", gnat_error_point, gnat_entity); } /* Check if FTYPE1 and FTYPE2, two potentially different function type nodes, have compatible signatures so that a call using one type may be safely issued if the actual target function type is the other. Return 1 if it is the case, 0 otherwise, and post errors on the incompatibilities. This is used when an Ada subprogram is mapped onto a GCC builtin, to ensure that calls to the subprogram will have arguments suitable for the later underlying builtin expansion. */ static int compatible_signatures_p (tree ftype1, tree ftype2) { /* As of now, we only perform very trivial tests and consider it's the programmer's responsibility to ensure the type correctness in the Ada declaration, as in the regular Import cases. Mismatches typically result in either error messages from the builtin expander, internal compiler errors, or in a real call sequence. This should be refined to issue diagnostics helping error detection and correction. */ /* Almost fake test, ensuring a use of each argument. */ if (ftype1 == ftype2) return 1; return 1; } /* Given a type T, a FIELD_DECL F, and a replacement value R, return a new type with all size expressions that contain F updated by replacing F with R. This is identical to GCC's substitute_in_type except that it knows about TYPE_INDEX_TYPE. If F is NULL_TREE, always make a new RECORD_TYPE, even if nothing has changed. */ tree gnat_substitute_in_type (tree t, tree f, tree r) { tree new = t; tree tem; switch (TREE_CODE (t)) { case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE: if (CONTAINS_PLACEHOLDER_P (TYPE_MIN_VALUE (t)) || CONTAINS_PLACEHOLDER_P (TYPE_MAX_VALUE (t))) { tree low = SUBSTITUTE_IN_EXPR (TYPE_MIN_VALUE (t), f, r); tree high = SUBSTITUTE_IN_EXPR (TYPE_MAX_VALUE (t), f, r); if (low == TYPE_MIN_VALUE (t) && high == TYPE_MAX_VALUE (t)) return t; new = build_range_type (TREE_TYPE (t), low, high); if (TYPE_INDEX_TYPE (t)) SET_TYPE_INDEX_TYPE (new, gnat_substitute_in_type (TYPE_INDEX_TYPE (t), f, r)); return new; } return t; case REAL_TYPE: if (CONTAINS_PLACEHOLDER_P (TYPE_MIN_VALUE (t)) || CONTAINS_PLACEHOLDER_P (TYPE_MAX_VALUE (t))) { tree low = NULL_TREE, high = NULL_TREE; if (TYPE_MIN_VALUE (t)) low = SUBSTITUTE_IN_EXPR (TYPE_MIN_VALUE (t), f, r); if (TYPE_MAX_VALUE (t)) high = SUBSTITUTE_IN_EXPR (TYPE_MAX_VALUE (t), f, r); if (low == TYPE_MIN_VALUE (t) && high == TYPE_MAX_VALUE (t)) return t; t = copy_type (t); TYPE_MIN_VALUE (t) = low; TYPE_MAX_VALUE (t) = high; } return t; case COMPLEX_TYPE: tem = gnat_substitute_in_type (TREE_TYPE (t), f, r); if (tem == TREE_TYPE (t)) return t; return build_complex_type (tem); case OFFSET_TYPE: case METHOD_TYPE: case FUNCTION_TYPE: case LANG_TYPE: /* Don't know how to do these yet. */ gcc_unreachable (); case ARRAY_TYPE: { tree component = gnat_substitute_in_type (TREE_TYPE (t), f, r); tree domain = gnat_substitute_in_type (TYPE_DOMAIN (t), f, r); if (component == TREE_TYPE (t) && domain == TYPE_DOMAIN (t)) return t; new = build_array_type (component, domain); TYPE_SIZE (new) = 0; TYPE_MULTI_ARRAY_P (new) = TYPE_MULTI_ARRAY_P (t); TYPE_CONVENTION_FORTRAN_P (new) = TYPE_CONVENTION_FORTRAN_P (t); layout_type (new); TYPE_ALIGN (new) = TYPE_ALIGN (t); /* If we had bounded the sizes of T by a constant, bound the sizes of NEW by the same constant. */ if (TREE_CODE (TYPE_SIZE (t)) == MIN_EXPR) TYPE_SIZE (new) = size_binop (MIN_EXPR, TREE_OPERAND (TYPE_SIZE (t), 1), TYPE_SIZE (new)); if (TREE_CODE (TYPE_SIZE_UNIT (t)) == MIN_EXPR) TYPE_SIZE_UNIT (new) = size_binop (MIN_EXPR, TREE_OPERAND (TYPE_SIZE_UNIT (t), 1), TYPE_SIZE_UNIT (new)); return new; } case RECORD_TYPE: case UNION_TYPE: case QUAL_UNION_TYPE: { tree field; bool changed_field = (f == NULL_TREE && !TREE_CONSTANT (TYPE_SIZE (t))); bool field_has_rep = false; tree last_field = NULL_TREE; tree new = copy_type (t); /* Start out with no fields, make new fields, and chain them in. If we haven't actually changed the type of any field, discard everything we've done and return the old type. */ TYPE_FIELDS (new) = NULL_TREE; TYPE_SIZE (new) = NULL_TREE; for (field = TYPE_FIELDS (t); field; field = TREE_CHAIN (field)) { tree new_field = copy_node (field); TREE_TYPE (new_field) = gnat_substitute_in_type (TREE_TYPE (new_field), f, r); if (DECL_HAS_REP_P (field) && !DECL_INTERNAL_P (field)) field_has_rep = true; else if (TREE_TYPE (new_field) != TREE_TYPE (field)) changed_field = true; /* If this is an internal field and the type of this field is a UNION_TYPE or RECORD_TYPE with no elements, ignore it. If the type just has one element, treat that as the field. But don't do this if we are processing a QUAL_UNION_TYPE. */ if (TREE_CODE (t) != QUAL_UNION_TYPE && DECL_INTERNAL_P (new_field) && (TREE_CODE (TREE_TYPE (new_field)) == UNION_TYPE || TREE_CODE (TREE_TYPE (new_field)) == RECORD_TYPE)) { if (!TYPE_FIELDS (TREE_TYPE (new_field))) continue; if (!TREE_CHAIN (TYPE_FIELDS (TREE_TYPE (new_field)))) { tree next_new_field = copy_node (TYPE_FIELDS (TREE_TYPE (new_field))); /* Make sure omitting the union doesn't change the layout. */ DECL_ALIGN (next_new_field) = DECL_ALIGN (new_field); new_field = next_new_field; } } DECL_CONTEXT (new_field) = new; SET_DECL_ORIGINAL_FIELD (new_field, (DECL_ORIGINAL_FIELD (field) ? DECL_ORIGINAL_FIELD (field) : field)); /* If the size of the old field was set at a constant, propagate the size in case the type's size was variable. (This occurs in the case of a variant or discriminated record with a default size used as a field of another record.) */ DECL_SIZE (new_field) = TREE_CODE (DECL_SIZE (field)) == INTEGER_CST ? DECL_SIZE (field) : NULL_TREE; DECL_SIZE_UNIT (new_field) = TREE_CODE (DECL_SIZE_UNIT (field)) == INTEGER_CST ? DECL_SIZE_UNIT (field) : NULL_TREE; if (TREE_CODE (t) == QUAL_UNION_TYPE) { tree new_q = SUBSTITUTE_IN_EXPR (DECL_QUALIFIER (field), f, r); if (new_q != DECL_QUALIFIER (new_field)) changed_field = true; /* Do the substitution inside the qualifier and if we find that this field will not be present, omit it. */ DECL_QUALIFIER (new_field) = new_q; if (integer_zerop (DECL_QUALIFIER (new_field))) continue; } if (!last_field) TYPE_FIELDS (new) = new_field; else TREE_CHAIN (last_field) = new_field; last_field = new_field; /* If this is a qualified type and this field will always be present, we are done. */ if (TREE_CODE (t) == QUAL_UNION_TYPE && integer_onep (DECL_QUALIFIER (new_field))) break; } /* If this used to be a qualified union type, but we now know what field will be present, make this a normal union. */ if (changed_field && TREE_CODE (new) == QUAL_UNION_TYPE && (!TYPE_FIELDS (new) || integer_onep (DECL_QUALIFIER (TYPE_FIELDS (new))))) TREE_SET_CODE (new, UNION_TYPE); else if (!changed_field) return t; gcc_assert (!field_has_rep); layout_type (new); /* If the size was originally a constant use it. */ if (TYPE_SIZE (t) && TREE_CODE (TYPE_SIZE (t)) == INTEGER_CST && TREE_CODE (TYPE_SIZE (new)) != INTEGER_CST) { TYPE_SIZE (new) = TYPE_SIZE (t); TYPE_SIZE_UNIT (new) = TYPE_SIZE_UNIT (t); SET_TYPE_ADA_SIZE (new, TYPE_ADA_SIZE (t)); } return new; } default: return t; } } /* Return the "RM size" of GNU_TYPE. This is the actual number of bits needed to represent the object. */ tree rm_size (tree gnu_type) { /* For integer types, this is the precision. For record types, we store the size explicitly. For other types, this is just the size. */ if (INTEGRAL_TYPE_P (gnu_type) && TYPE_RM_SIZE (gnu_type)) return TYPE_RM_SIZE (gnu_type); else if (TREE_CODE (gnu_type) == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (gnu_type)) /* Return the rm_size of the actual data plus the size of the template. */ return size_binop (PLUS_EXPR, rm_size (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (gnu_type)))), DECL_SIZE (TYPE_FIELDS (gnu_type))); else if ((TREE_CODE (gnu_type) == RECORD_TYPE || TREE_CODE (gnu_type) == UNION_TYPE || TREE_CODE (gnu_type) == QUAL_UNION_TYPE) && !TYPE_IS_FAT_POINTER_P (gnu_type) && TYPE_ADA_SIZE (gnu_type)) return TYPE_ADA_SIZE (gnu_type); else return TYPE_SIZE (gnu_type); } /* Return an identifier representing the external name to be used for GNAT_ENTITY. If SUFFIX is specified, the name is followed by "___" and the specified suffix. */ tree create_concat_name (Entity_Id gnat_entity, const char *suffix) { Entity_Kind kind = Ekind (gnat_entity); const char *str = (!suffix ? "" : suffix); String_Template temp = {1, strlen (str)}; Fat_Pointer fp = {str, &temp}; Get_External_Name_With_Suffix (gnat_entity, fp); /* A variable using the Stdcall convention (meaning we are running on a Windows box) live in a DLL. Here we adjust its name to use the jump-table, the _imp__NAME contains the address for the NAME variable. */ if ((kind == E_Variable || kind == E_Constant) && Has_Stdcall_Convention (gnat_entity)) { const char *prefix = "_imp__"; int k, plen = strlen (prefix); for (k = 0; k <= Name_Len; k++) Name_Buffer [Name_Len - k + plen] = Name_Buffer [Name_Len - k]; strncpy (Name_Buffer, prefix, plen); } return get_identifier (Name_Buffer); } /* Return the name to be used for GNAT_ENTITY. If a type, create a fully-qualified name, possibly with type information encoding. Otherwise, return the name. */ tree get_entity_name (Entity_Id gnat_entity) { Get_Encoded_Name (gnat_entity); return get_identifier (Name_Buffer); } /* Given GNU_ID, an IDENTIFIER_NODE containing a name and SUFFIX, a string, return a new IDENTIFIER_NODE that is the concatenation of the name in GNU_ID and SUFFIX. */ tree concat_id_with_name (tree gnu_id, const char *suffix) { int len = IDENTIFIER_LENGTH (gnu_id); strncpy (Name_Buffer, IDENTIFIER_POINTER (gnu_id), IDENTIFIER_LENGTH (gnu_id)); strncpy (Name_Buffer + len, "___", 3); len += 3; strcpy (Name_Buffer + len, suffix); return get_identifier (Name_Buffer); } #include "gt-ada-decl.h"
aosm/llvmgcc42
gcc/ada/decl.c
C
gpl-2.0
252,765
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Introspecting member function</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../index.html" title="Chapter&#160;1.&#160;The Type Traits Introspection Library"> <link rel="up" href="../index.html" title="Chapter&#160;1.&#160;The Type Traits Introspection Library"> <link rel="prev" href="tti_detail_has_member_data.html" title="Introspecting member data"> <link rel="next" href="tti_detail_has_static_member_data.html" title="Introspecting static member data"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="tti_detail_has_member_data.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="tti_detail_has_static_member_data.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h2 class="title" style="clear: both"> <a name="the_type_traits_introspection_library.tti_detail_has_member_function"></a><a class="link" href="tti_detail_has_member_function.html" title="Introspecting member function">Introspecting member function</a> </h2></div></div></div> <p> The TTI macro <code class="computeroutput"><a class="link" href="../BOOST_TTI_HAS_MEMBER_FUNCTION.html" title="Macro BOOST_TTI_HAS_MEMBER_FUNCTION">BOOST_TTI_HAS_MEMBER_FUNCTION</a></code> introspects a member function of a class. </p> <p> BOOST_TTI_HAS_MEMBER_FUNCTION takes a single parameter which is the name of an inner member function whose existence the programmer wants to check. The macro generates a metafunction called 'has_member_function_'name_of_inner_member_function'. </p> <p> The metafunction can be invoked in two different ways. </p> <p> The first way of invoking the metafunction is by passing it the enclosing type to introspect and a signature for the member function as a series of separate template arguments. The signature for the member function consists of the template arguments of a return type, of optional parameter types in the form of a boost::mpl forward sequence of types, and of an optional Boost FunctionTypes tag type. A typical boost::mpl forward sequence of types is a boost::mpl::vector&lt;&gt;. </p> <p> The optional Boost FunctionTypes tag type may be used to specify cv-qualification. This means you can add 'const', 'volatile', or both by specifying an appropriate tag type. An alternate to using the tag type is to specify the enclosing type as 'const', 'volatile', or both. As an example if you specify the tag type as 'boost::function_types::const_qualified' or if you specify the enclosing type as 'const T', the member function which you are introspecting must be a const function. </p> <p> The second way of invoking the metafunction is by passing it a single parameter, which is a pointer to member function. This type has the form of: </p> <pre class="programlisting"><span class="identifier">Return_Type</span> <span class="special">(</span> <span class="identifier">Enclosing_Type</span><span class="special">::*</span> <span class="special">)</span> <span class="special">(</span> <span class="identifier">Parameter_Types</span> <span class="special">)</span> <span class="identifier">cv_qualifier</span><span class="special">(</span><span class="identifier">s</span><span class="special">)</span> </pre> <p> where the Parameter_Types may be empty, or a comma-separated list of parameter types if there are more than one parameter type. The cv-qualifier may be 'const', 'volatile', or 'const volatile'. </p> <p> The metafunction returns a single type called 'type', which is a boost::mpl::bool_. As a convenience the metafunction returns the value of this type directly as a compile time bool constant called 'value'. This 'value' is true or false depending on whether the inner member function, of the specified signature, exists or not. </p> <h4> <a name="the_type_traits_introspection_library.tti_detail_has_member_function.h0"></a> <span class="phrase"><a name="the_type_traits_introspection_library.tti_detail_has_member_function.generating_the_metafunction"></a></span><a class="link" href="tti_detail_has_member_function.html#the_type_traits_introspection_library.tti_detail_has_member_function.generating_the_metafunction">Generating the metafunction</a> </h4> <p> You generate the metafunction by invoking the macro with the name of an inner member function: </p> <pre class="programlisting"><span class="identifier">BOOST_TTI_HAS_MEMBER_FUNCTION</span><span class="special">(</span><span class="identifier">AMemberFunction</span><span class="special">)</span> </pre> <p> generates a metafunction called 'has_member_function_AMemberFunction' in the current scope. </p> <h4> <a name="the_type_traits_introspection_library.tti_detail_has_member_function.h1"></a> <span class="phrase"><a name="the_type_traits_introspection_library.tti_detail_has_member_function.invoking_the_metafunction"></a></span><a class="link" href="tti_detail_has_member_function.html#the_type_traits_introspection_library.tti_detail_has_member_function.invoking_the_metafunction">Invoking the metafunction</a> </h4> <p> You invoke the metafunction by instantiating the template with an enclosing type to introspect and the signature of the member function as a series of template parameters. Alternatively you can invoke the metafunction by passing it a single type which is a pointer to member function. </p> <p> A return value called 'value' is a compile time bool constant. </p> <pre class="programlisting"><span class="identifier">has_member_function_AMemberFunction</span> <span class="special">&lt;</span> <span class="identifier">Enclosing_Type</span><span class="special">,</span> <span class="identifier">MemberFunction_ReturnType</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">mpl</span><span class="special">::</span><span class="identifier">vector</span><span class="special">&lt;</span><span class="identifier">MemberFunction_ParameterTypes</span><span class="special">&gt;,</span> <span class="comment">// optional, can be any mpl forward sequence</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">function_types</span><span class="special">::</span><span class="identifier">SomeTagType</span> <span class="comment">// optional, can be any FunctionTypes tag type</span> <span class="special">&gt;::</span><span class="identifier">value</span> <span class="identifier">OR</span> <span class="identifier">has_member_function_AMemberFunction</span> <span class="special">&lt;</span> <span class="identifier">MemberFunction_ReturnType</span> <span class="special">(</span><span class="identifier">Enclosing_Type</span><span class="special">::*)</span> <span class="special">(</span><span class="identifier">MemberFunction_ParameterTypes</span><span class="special">)</span> <span class="identifier">optional_cv_qualification</span> <span class="special">&gt;::</span><span class="identifier">value</span> </pre> <h4> <a name="the_type_traits_introspection_library.tti_detail_has_member_function.h2"></a> <span class="phrase"><a name="the_type_traits_introspection_library.tti_detail_has_member_function.examples"></a></span><a class="link" href="tti_detail_has_member_function.html#the_type_traits_introspection_library.tti_detail_has_member_function.examples">Examples</a> </h4> <p> First we generate metafunctions for various inner member function names: </p> <pre class="programlisting"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">tti</span><span class="special">/</span><span class="identifier">has_member_function</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> <span class="identifier">BOOST_TTI_HAS_MEMBER_FUNCTION</span><span class="special">(</span><span class="identifier">function1</span><span class="special">)</span> <span class="identifier">BOOST_TTI_HAS_MEMBER_FUNCTION</span><span class="special">(</span><span class="identifier">function2</span><span class="special">)</span> <span class="identifier">BOOST_TTI_HAS_MEMBER_FUNCTION</span><span class="special">(</span><span class="identifier">function3</span><span class="special">)</span> </pre> <p> Next let us create some user-defined types we want to introspect. </p> <pre class="programlisting"><span class="keyword">struct</span> <span class="identifier">AClass</span> <span class="special">{</span> <span class="special">};</span> <span class="keyword">struct</span> <span class="identifier">Top</span> <span class="special">{</span> <span class="keyword">int</span> <span class="identifier">function1</span><span class="special">();</span> <span class="identifier">AClass</span> <span class="identifier">function2</span><span class="special">(</span><span class="keyword">double</span><span class="special">,</span><span class="keyword">short</span> <span class="special">*);</span> <span class="special">};</span> <span class="keyword">struct</span> <span class="identifier">Top2</span> <span class="special">{</span> <span class="keyword">long</span> <span class="identifier">function2</span><span class="special">(</span><span class="identifier">Top</span> <span class="special">&amp;,</span><span class="keyword">int</span><span class="special">,</span><span class="keyword">bool</span><span class="special">,</span><span class="keyword">short</span><span class="special">,</span><span class="keyword">float</span><span class="special">);</span> <span class="identifier">Top</span> <span class="special">*</span> <span class="identifier">function3</span><span class="special">(</span><span class="keyword">long</span><span class="special">,</span><span class="keyword">int</span><span class="special">,</span><span class="identifier">AClass</span> <span class="special">&amp;);</span> <span class="special">};</span> </pre> <p> Finally we invoke our metafunction and return our value. This all happens at compile time, and can be used by programmers doing compile time template metaprogramming. </p> <p> We will show both forms in the following examples. Both forms are completely interchangeable as to the result desired. </p> <pre class="programlisting"><span class="identifier">has_member_function_function1</span><span class="special">&lt;</span><span class="identifier">Top</span><span class="special">,</span><span class="keyword">int</span><span class="special">&gt;::</span><span class="identifier">value</span><span class="special">;</span> <span class="comment">// true</span> <span class="identifier">has_member_function_function1</span><span class="special">&lt;</span><span class="identifier">Top</span><span class="special">,</span><span class="keyword">int</span><span class="special">,</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">mpl</span><span class="special">::</span><span class="identifier">vector</span><span class="special">&lt;&gt;</span> <span class="special">&gt;::</span><span class="identifier">value</span><span class="special">;</span> <span class="comment">// true</span> <span class="identifier">has_member_function_function1</span><span class="special">&lt;</span><span class="identifier">Top2</span><span class="special">,</span><span class="keyword">int</span><span class="special">&gt;::</span><span class="identifier">value</span><span class="special">;</span> <span class="comment">// false</span> <span class="identifier">has_member_function_function2</span><span class="special">&lt;</span><span class="identifier">AClass</span> <span class="special">(</span><span class="identifier">Top</span><span class="special">::*)</span> <span class="special">(</span><span class="keyword">double</span><span class="special">,</span><span class="keyword">short</span> <span class="special">*)&gt;::</span><span class="identifier">value</span><span class="special">;</span> <span class="comment">// true</span> <span class="identifier">has_member_function_function2</span><span class="special">&lt;</span><span class="identifier">AClass</span> <span class="special">(</span><span class="identifier">Top2</span><span class="special">::*)</span> <span class="special">(</span><span class="keyword">double</span><span class="special">,</span><span class="keyword">short</span> <span class="special">*)&gt;::</span><span class="identifier">value</span><span class="special">;</span> <span class="comment">// false</span> <span class="identifier">has_member_function_function2</span><span class="special">&lt;</span><span class="keyword">long</span> <span class="special">(</span><span class="identifier">Top2</span><span class="special">::*)</span> <span class="special">(</span><span class="identifier">Top</span> <span class="special">&amp;,</span><span class="keyword">int</span><span class="special">,</span><span class="keyword">bool</span><span class="special">,</span><span class="keyword">short</span><span class="special">,</span><span class="keyword">float</span><span class="special">)&gt;::</span><span class="identifier">value</span><span class="special">;</span> <span class="comment">// true</span> <span class="identifier">has_member_function_function3</span><span class="special">&lt;</span><span class="keyword">int</span> <span class="special">(</span><span class="identifier">Top2</span><span class="special">::*)</span> <span class="special">()&gt;::</span><span class="identifier">value</span><span class="special">;</span> <span class="comment">// false</span> <span class="identifier">has_member_function_function3</span><span class="special">&lt;</span><span class="identifier">Top2</span><span class="special">,</span><span class="identifier">Top</span> <span class="special">*,</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">mpl</span><span class="special">::</span><span class="identifier">vector</span><span class="special">&lt;</span><span class="keyword">long</span><span class="special">,</span><span class="keyword">int</span><span class="special">,</span><span class="identifier">AClass</span> <span class="special">&amp;&gt;</span> <span class="special">&gt;::</span><span class="identifier">value</span><span class="special">;</span> <span class="comment">// true;</span> </pre> <h4> <a name="the_type_traits_introspection_library.tti_detail_has_member_function.h3"></a> <span class="phrase"><a name="the_type_traits_introspection_library.tti_detail_has_member_function.metafunction_re_use"></a></span><a class="link" href="tti_detail_has_member_function.html#the_type_traits_introspection_library.tti_detail_has_member_function.metafunction_re_use">Metafunction re-use</a> </h4> <p> The macro encodes only the name of the member function for which we are searching and the fact that we are introspecting for a member function within an enclosing type. </p> <p> Because of this, once we create our metafunction for introspecting a member function by name, we can reuse the metafunction for introspecting any enclosing type, having any member function, for that name. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2011-2013 Tropic Software East Inc<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="tti_detail_has_member_data.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="tti_detail_has_static_member_data.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
FFMG/myoddweb.piger
myodd/boost/libs/tti/doc/html/the_type_traits_introspection_library/tti_detail_has_member_function.html
HTML
gpl-2.0
17,725
goog.provide('ol.source.ImageVector'); goog.require('goog.asserts'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.vec.Mat4'); goog.require('ol.dom'); goog.require('ol.extent'); goog.require('ol.render.canvas.ReplayGroup'); goog.require('ol.renderer.vector'); goog.require('ol.source.ImageCanvas'); goog.require('ol.source.Vector'); goog.require('ol.style.Style'); goog.require('ol.vec.Mat4'); /** * @classdesc * An image source whose images are canvas elements into which vector features * read from a vector source (`ol.source.Vector`) are drawn. An * `ol.source.ImageVector` object is to be used as the `source` of an image * layer (`ol.layer.Image`). Image layers are rotated, scaled, and translated, * as opposed to being re-rendered, during animations and interactions. So, like * any other image layer, an image layer configured with an * `ol.source.ImageVector` will exhibit this behaviour. This is in contrast to a * vector layer, where vector features are re-drawn during animations and * interactions. * * @constructor * @extends {ol.source.ImageCanvas} * @param {olx.source.ImageVectorOptions} options Options. * @api */ ol.source.ImageVector = function(options) { /** * @private * @type {ol.source.Vector} */ this.source_ = options.source; /** * @private * @type {!goog.vec.Mat4.Number} */ this.transform_ = goog.vec.Mat4.createNumber(); /** * @private * @type {CanvasRenderingContext2D} */ this.canvasContext_ = ol.dom.createCanvasContext2D(); /** * @private * @type {ol.Size} */ this.canvasSize_ = [0, 0]; /** * @private * @type {ol.render.canvas.ReplayGroup} */ this.replayGroup_ = null; goog.base(this, { attributions: options.attributions, canvasFunction: goog.bind(this.canvasFunctionInternal_, this), logo: options.logo, projection: options.projection, ratio: options.ratio, resolutions: options.resolutions, state: this.source_.getState() }); /** * User provided style. * @type {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction} * @private */ this.style_ = null; /** * Style function for use within the library. * @type {ol.style.StyleFunction|undefined} * @private */ this.styleFunction_ = undefined; this.setStyle(options.style); goog.events.listen(this.source_, goog.events.EventType.CHANGE, this.handleSourceChange_, undefined, this); }; goog.inherits(ol.source.ImageVector, ol.source.ImageCanvas); /** * @param {ol.Extent} extent Extent. * @param {number} resolution Resolution. * @param {number} pixelRatio Pixel ratio. * @param {ol.Size} size Size. * @param {ol.proj.Projection} projection Projection; * @return {HTMLCanvasElement} Canvas element. * @private */ ol.source.ImageVector.prototype.canvasFunctionInternal_ = function(extent, resolution, pixelRatio, size, projection) { var replayGroup = new ol.render.canvas.ReplayGroup( ol.renderer.vector.getTolerance(resolution, pixelRatio), extent, resolution); this.source_.loadFeatures(extent, resolution, projection); var loading = false; this.source_.forEachFeatureInExtentAtResolution(extent, resolution, /** * @param {ol.Feature} feature Feature. */ function(feature) { loading = loading || this.renderFeature_(feature, resolution, pixelRatio, replayGroup); }, this); replayGroup.finish(); if (loading) { return null; } if (this.canvasSize_[0] != size[0] || this.canvasSize_[1] != size[1]) { this.canvasContext_.canvas.width = size[0]; this.canvasContext_.canvas.height = size[1]; this.canvasSize_[0] = size[0]; this.canvasSize_[1] = size[1]; } else { this.canvasContext_.clearRect(0, 0, size[0], size[1]); } var transform = this.getTransform_(ol.extent.getCenter(extent), resolution, pixelRatio, size); replayGroup.replay(this.canvasContext_, pixelRatio, transform, 0, {}); this.replayGroup_ = replayGroup; return this.canvasContext_.canvas; }; /** * @inheritDoc */ ol.source.ImageVector.prototype.forEachFeatureAtCoordinate = function( coordinate, resolution, rotation, skippedFeatureUids, callback) { if (goog.isNull(this.replayGroup_)) { return undefined; } else { /** @type {Object.<string, boolean>} */ var features = {}; return this.replayGroup_.forEachFeatureAtCoordinate( coordinate, resolution, 0, skippedFeatureUids, /** * @param {ol.Feature} feature Feature. * @return {?} Callback result. */ function(feature) { goog.asserts.assert(goog.isDef(feature)); var key = goog.getUid(feature).toString(); if (!(key in features)) { features[key] = true; return callback(feature); } }); } }; /** * Get a reference to the wrapped source. * @return {ol.source.Vector} Source. * @api */ ol.source.ImageVector.prototype.getSource = function() { return this.source_; }; /** * Get the style for features. This returns whatever was passed to the `style` * option at construction or to the `setStyle` method. * @return {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction} * Layer style. * @api stable */ ol.source.ImageVector.prototype.getStyle = function() { return this.style_; }; /** * Get the style function. * @return {ol.style.StyleFunction|undefined} Layer style function. * @api stable */ ol.source.ImageVector.prototype.getStyleFunction = function() { return this.styleFunction_; }; /** * @param {ol.Coordinate} center Center. * @param {number} resolution Resolution. * @param {number} pixelRatio Pixel ratio. * @param {ol.Size} size Size. * @return {!goog.vec.Mat4.Number} Transform. * @private */ ol.source.ImageVector.prototype.getTransform_ = function(center, resolution, pixelRatio, size) { return ol.vec.Mat4.makeTransform2D(this.transform_, size[0] / 2, size[1] / 2, pixelRatio / resolution, -pixelRatio / resolution, 0, -center[0], -center[1]); }; /** * Handle changes in image style state. * @param {goog.events.Event} event Image style change event. * @private */ ol.source.ImageVector.prototype.handleImageChange_ = function(event) { this.changed(); }; /** * @private */ ol.source.ImageVector.prototype.handleSourceChange_ = function() { // setState will trigger a CHANGE event, so we always rely // change events by calling setState. this.setState(this.source_.getState()); }; /** * @param {ol.Feature} feature Feature. * @param {number} resolution Resolution. * @param {number} pixelRatio Pixel ratio. * @param {ol.render.canvas.ReplayGroup} replayGroup Replay group. * @return {boolean} `true` if an image is loading. * @private */ ol.source.ImageVector.prototype.renderFeature_ = function(feature, resolution, pixelRatio, replayGroup) { var styles; if (goog.isDef(feature.getStyleFunction())) { styles = feature.getStyleFunction().call(feature, resolution); } else if (goog.isDef(this.styleFunction_)) { styles = this.styleFunction_(feature, resolution); } if (!goog.isDefAndNotNull(styles)) { return false; } var i, ii, loading = false; for (i = 0, ii = styles.length; i < ii; ++i) { loading = ol.renderer.vector.renderFeature( replayGroup, feature, styles[i], ol.renderer.vector.getSquaredTolerance(resolution, pixelRatio), this.handleImageChange_, this) || loading; } return loading; }; /** * Set the style for features. This can be a single style object, an array * of styles, or a function that takes a feature and resolution and returns * an array of styles. If it is `undefined` the default style is used. If * it is `null` the layer has no style (a `null` style), so only features * that have their own styles will be rendered in the layer. See * {@link ol.style} for information on the default style. * @param {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction|undefined} * style Layer style. * @api stable */ ol.source.ImageVector.prototype.setStyle = function(style) { this.style_ = goog.isDef(style) ? style : ol.style.defaultStyleFunction; this.styleFunction_ = goog.isNull(style) ? undefined : ol.style.createStyleFunction(this.style_); this.changed(); };
henriquespedro/Autarquia-Livre
vendor/openlayers/ol/ol/source/imagevectorsource.js
JavaScript
gpl-2.0
8,407
/* * OCaml Support For IntelliJ Platform. * Copyright (C) 2010 Maxim Manuylov * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. */ package manuylov.maxim.ocaml.lang.parser.psi.element.impl; import com.intellij.lang.ASTNode; import manuylov.maxim.ocaml.lang.parser.psi.OCamlElementVisitor; import manuylov.maxim.ocaml.lang.parser.psi.element.OCamlParenthesesTypeParameters; import org.jetbrains.annotations.NotNull; /** * @author Maxim.Manuylov * Date: 13.05.2010 */ public class OCamlParenthesesTypeParametersImpl extends OCamlParenthesesImpl implements OCamlParenthesesTypeParameters { public OCamlParenthesesTypeParametersImpl(@NotNull final ASTNode node) { super(node); } public void visit(@NotNull final OCamlElementVisitor visitor) { visitor.visitParenthesesTypeParameters(this); } }
emmeryn/intellij-ocaml
OCamlSources/src/manuylov/maxim/ocaml/lang/parser/psi/element/impl/OCamlParenthesesTypeParametersImpl.java
Java
gpl-2.0
1,487
/* * vendor/product IDs (VID/PID) of devices using FTDI USB serial converters. * Please keep numerically sorted within individual areas, thanks! * * Philipp Gühring - pg@futureware.at - added the Device ID of the USB relais * from Rudolf Gugler * */ /**********************************/ /***** devices using FTDI VID *****/ /**********************************/ #define FTDI_VID 0x0403 /* Vendor Id */ /*** "original" FTDI device PIDs ***/ #define FTDI_8U232AM_PID 0x6001 /* Similar device to SIO above */ #define FTDI_8U232AM_ALT_PID 0x6006 /* FTDI's alternate PID for above */ #define FTDI_8U2232C_PID 0x6010 /* Dual channel device */ #define FTDI_4232H_PID 0x6011 /* Quad channel hi-speed device */ #define FTDI_SIO_PID 0x8372 /* Product Id SIO application of 8U100AX */ #define FTDI_232RL_PID 0xFBFA /* Product ID for FT232RL */ /*** third-party PIDs (using FTDI_VID) ***/ /* * Marvell OpenRD Base, Client * http://www.open-rd.org * OpenRD Base, Client use VID 0x0403 */ #define MARVELL_OPENRD_PID 0x9e90 /* www.candapter.com Ewert Energy Systems CANdapter device */ #define FTDI_CANDAPTER_PID 0x9F80 /* Product Id */ #define FTDI_NXTCAM_PID 0xABB8 /* NXTCam for Mindstorms NXT */ /* US Interface Navigator (http://www.usinterface.com/) */ #define FTDI_USINT_CAT_PID 0xb810 /* Navigator CAT and 2nd PTT lines */ #define FTDI_USINT_WKEY_PID 0xb811 /* Navigator WKEY and FSK lines */ #define FTDI_USINT_RS232_PID 0xb812 /* Navigator RS232 and CONFIG lines */ /* OOCDlink by Joern Kaipf <joernk@web.de> * (http://www.joernonline.de/dw/doku.php?id=start&idx=projects:oocdlink) */ #define FTDI_OOCDLINK_PID 0xbaf8 /* Amontec JTAGkey */ /* Luminary Micro Stellaris Boards, VID = FTDI_VID */ /* FTDI 2332C Dual channel device, side A=245 FIFO (JTAG), Side B=RS232 UART */ #define LMI_LM3S_DEVEL_BOARD_PID 0xbcd8 #define LMI_LM3S_EVAL_BOARD_PID 0xbcd9 #define FTDI_TURTELIZER_PID 0xBDC8 /* JTAG/RS-232 adapter by egnite GmbH */ /* OpenDCC (www.opendcc.de) product id */ #define FTDI_OPENDCC_PID 0xBFD8 #define FTDI_OPENDCC_SNIFFER_PID 0xBFD9 #define FTDI_OPENDCC_THROTTLE_PID 0xBFDA #define FTDI_OPENDCC_GATEWAY_PID 0xBFDB /* * RR-CirKits LocoBuffer USB (http://www.rr-cirkits.com) */ #define FTDI_RRCIRKITS_LOCOBUFFER_PID 0xc7d0 /* LocoBuffer USB */ /* DMX4ALL DMX Interfaces */ #define FTDI_DMX4ALL 0xC850 /* * ASK.fr devices */ #define FTDI_ASK_RDR400_PID 0xC991 /* ASK RDR 400 series card reader */ /* www.starting-point-systems.com µChameleon device */ #define FTDI_MICRO_CHAMELEON_PID 0xCAA0 /* Product Id */ /* * Tactrix OpenPort (ECU) devices. * OpenPort 1.3M submitted by Donour Sizemore. * OpenPort 1.3S and 1.3U submitted by Ian Abbott. */ #define FTDI_TACTRIX_OPENPORT_13M_PID 0xCC48 /* OpenPort 1.3 Mitsubishi */ #define FTDI_TACTRIX_OPENPORT_13S_PID 0xCC49 /* OpenPort 1.3 Subaru */ #define FTDI_TACTRIX_OPENPORT_13U_PID 0xCC4A /* OpenPort 1.3 Universal */ /* SCS HF Radio Modems PID's (http://www.scs-ptc.com) */ /* the VID is the standard ftdi vid (FTDI_VID) */ #define FTDI_SCS_DEVICE_0_PID 0xD010 /* SCS PTC-IIusb */ #define FTDI_SCS_DEVICE_1_PID 0xD011 /* SCS Tracker / DSP TNC */ #define FTDI_SCS_DEVICE_2_PID 0xD012 #define FTDI_SCS_DEVICE_3_PID 0xD013 #define FTDI_SCS_DEVICE_4_PID 0xD014 #define FTDI_SCS_DEVICE_5_PID 0xD015 #define FTDI_SCS_DEVICE_6_PID 0xD016 #define FTDI_SCS_DEVICE_7_PID 0xD017 /* iPlus device */ #define FTDI_IPLUS_PID 0xD070 /* Product Id */ #define FTDI_IPLUS2_PID 0xD071 /* Product Id */ /* * Gamma Scout (http://gamma-scout.com/). Submitted by rsc@runtux.com. */ #define FTDI_GAMMA_SCOUT_PID 0xD678 /* Gamma Scout online */ /* Propox devices */ #define FTDI_PROPOX_JTAGCABLEII_PID 0xD738 /* Lenz LI-USB Computer Interface. */ #define FTDI_LENZ_LIUSB_PID 0xD780 /* * Xsens Technologies BV products (http://www.xsens.com). */ #define XSENS_CONVERTER_0_PID 0xD388 #define XSENS_CONVERTER_1_PID 0xD389 #define XSENS_CONVERTER_2_PID 0xD38A #define XSENS_CONVERTER_3_PID 0xD38B #define XSENS_CONVERTER_4_PID 0xD38C #define XSENS_CONVERTER_5_PID 0xD38D #define XSENS_CONVERTER_6_PID 0xD38E #define XSENS_CONVERTER_7_PID 0xD38F /* * NDI (www.ndigital.com) product ids */ #define FTDI_NDI_HUC_PID 0xDA70 /* NDI Host USB Converter */ #define FTDI_NDI_SPECTRA_SCU_PID 0xDA71 /* NDI Spectra SCU */ #define FTDI_NDI_FUTURE_2_PID 0xDA72 /* NDI future device #2 */ #define FTDI_NDI_FUTURE_3_PID 0xDA73 /* NDI future device #3 */ #define FTDI_NDI_AURORA_SCU_PID 0xDA74 /* NDI Aurora SCU */ /* * ChamSys Limited (www.chamsys.co.uk) USB wing/interface product IDs */ #define FTDI_CHAMSYS_24_MASTER_WING_PID 0xDAF8 #define FTDI_CHAMSYS_PC_WING_PID 0xDAF9 #define FTDI_CHAMSYS_USB_DMX_PID 0xDAFA #define FTDI_CHAMSYS_MIDI_TIMECODE_PID 0xDAFB #define FTDI_CHAMSYS_MINI_WING_PID 0xDAFC #define FTDI_CHAMSYS_MAXI_WING_PID 0xDAFD #define FTDI_CHAMSYS_MEDIA_WING_PID 0xDAFE #define FTDI_CHAMSYS_WING_PID 0xDAFF /* * Westrex International devices submitted by Cory Lee */ #define FTDI_WESTREX_MODEL_777_PID 0xDC00 /* Model 777 */ #define FTDI_WESTREX_MODEL_8900F_PID 0xDC01 /* Model 8900F */ /* * ACG Identification Technologies GmbH products (http://www.acg.de/). * Submitted by anton -at- goto10 -dot- org. */ #define FTDI_ACG_HFDUAL_PID 0xDD20 /* HF Dual ISO Reader (RFID) */ /* * Definitions for Artemis astronomical USB based cameras * Check it at http://www.artemisccd.co.uk/ */ #define FTDI_ARTEMIS_PID 0xDF28 /* All Artemis Cameras */ /* * Definitions for ATIK Instruments astronomical USB based cameras * Check it at http://www.atik-instruments.com/ */ #define FTDI_ATIK_ATK16_PID 0xDF30 /* ATIK ATK-16 Grayscale Camera */ #define FTDI_ATIK_ATK16C_PID 0xDF32 /* ATIK ATK-16C Colour Camera */ #define FTDI_ATIK_ATK16HR_PID 0xDF31 /* ATIK ATK-16HR Grayscale Camera */ #define FTDI_ATIK_ATK16HRC_PID 0xDF33 /* ATIK ATK-16HRC Colour Camera */ #define FTDI_ATIK_ATK16IC_PID 0xDF35 /* ATIK ATK-16IC Grayscale Camera */ /* * Yost Engineering, Inc. products (www.yostengineering.com). * PID 0xE050 submitted by Aaron Prose. */ #define FTDI_YEI_SERVOCENTER31_PID 0xE050 /* YEI ServoCenter3.1 USB */ /* * ELV USB devices submitted by Christian Abt of ELV (www.elv.de). * All of these devices use FTDI's vendor ID (0x0403). * Further IDs taken from ELV Windows .inf file. * * The previously included PID for the UO 100 module was incorrect. * In fact, that PID was for ELV's UR 100 USB-RS232 converter (0xFB58). * * Armin Laeuger originally sent the PID for the UM 100 module. */ #define FTDI_ELV_USR_PID 0xE000 /* ELV Universal-Sound-Recorder */ #define FTDI_ELV_MSM1_PID 0xE001 /* ELV Mini-Sound-Modul */ #define FTDI_ELV_KL100_PID 0xE002 /* ELV Kfz-Leistungsmesser KL 100 */ #define FTDI_ELV_WS550_PID 0xE004 /* WS 550 */ #define FTDI_ELV_EC3000_PID 0xE006 /* ENERGY CONTROL 3000 USB */ #define FTDI_ELV_WS888_PID 0xE008 /* WS 888 */ #define FTDI_ELV_TWS550_PID 0xE009 /* Technoline WS 550 */ #define FTDI_ELV_FEM_PID 0xE00A /* Funk Energie Monitor */ #define FTDI_ELV_FHZ1300PC_PID 0xE0E8 /* FHZ 1300 PC */ #define FTDI_ELV_WS500_PID 0xE0E9 /* PC-Wetterstation (WS 500) */ #define FTDI_ELV_HS485_PID 0xE0EA /* USB to RS-485 adapter */ #define FTDI_ELV_UMS100_PID 0xE0EB /* ELV USB Master-Slave Schaltsteckdose UMS 100 */ #define FTDI_ELV_TFD128_PID 0xE0EC /* ELV Temperatur-Feuchte-Datenlogger TFD 128 */ #define FTDI_ELV_FM3RX_PID 0xE0ED /* ELV Messwertuebertragung FM3 RX */ #define FTDI_ELV_WS777_PID 0xE0EE /* Conrad WS 777 */ #define FTDI_ELV_EM1010PC_PID 0xE0EF /* Energy monitor EM 1010 PC */ #define FTDI_ELV_CSI8_PID 0xE0F0 /* Computer-Schalt-Interface (CSI 8) */ #define FTDI_ELV_EM1000DL_PID 0xE0F1 /* PC-Datenlogger fuer Energiemonitor (EM 1000 DL) */ #define FTDI_ELV_PCK100_PID 0xE0F2 /* PC-Kabeltester (PCK 100) */ #define FTDI_ELV_RFP500_PID 0xE0F3 /* HF-Leistungsmesser (RFP 500) */ #define FTDI_ELV_FS20SIG_PID 0xE0F4 /* Signalgeber (FS 20 SIG) */ #define FTDI_ELV_UTP8_PID 0xE0F5 /* ELV UTP 8 */ #define FTDI_ELV_WS300PC_PID 0xE0F6 /* PC-Wetterstation (WS 300 PC) */ #define FTDI_ELV_WS444PC_PID 0xE0F7 /* Conrad WS 444 PC */ #define FTDI_PHI_FISCO_PID 0xE40B /* PHI Fisco USB to Serial cable */ #define FTDI_ELV_UAD8_PID 0xF068 /* USB-AD-Wandler (UAD 8) */ #define FTDI_ELV_UDA7_PID 0xF069 /* USB-DA-Wandler (UDA 7) */ #define FTDI_ELV_USI2_PID 0xF06A /* USB-Schrittmotoren-Interface (USI 2) */ #define FTDI_ELV_T1100_PID 0xF06B /* Thermometer (T 1100) */ #define FTDI_ELV_PCD200_PID 0xF06C /* PC-Datenlogger (PCD 200) */ #define FTDI_ELV_ULA200_PID 0xF06D /* USB-LCD-Ansteuerung (ULA 200) */ #define FTDI_ELV_ALC8500_PID 0xF06E /* ALC 8500 Expert */ #define FTDI_ELV_FHZ1000PC_PID 0xF06F /* FHZ 1000 PC */ #define FTDI_ELV_UR100_PID 0xFB58 /* USB-RS232-Umsetzer (UR 100) */ #define FTDI_ELV_UM100_PID 0xFB5A /* USB-Modul UM 100 */ #define FTDI_ELV_UO100_PID 0xFB5B /* USB-Modul UO 100 */ /* Additional ELV PIDs that default to using the FTDI D2XX drivers on * MS Windows, rather than the FTDI Virtual Com Port drivers. * Maybe these will be easier to use with the libftdi/libusb user-space * drivers, or possibly the Comedi drivers in some cases. */ #define FTDI_ELV_CLI7000_PID 0xFB59 /* Computer-Light-Interface (CLI 7000) */ #define FTDI_ELV_PPS7330_PID 0xFB5C /* Processor-Power-Supply (PPS 7330) */ #define FTDI_ELV_TFM100_PID 0xFB5D /* Temperatur-Feuchte-Messgeraet (TFM 100) */ #define FTDI_ELV_UDF77_PID 0xFB5E /* USB DCF Funkuhr (UDF 77) */ #define FTDI_ELV_UIO88_PID 0xFB5F /* USB-I/O Interface (UIO 88) */ /* * EVER Eco Pro UPS (http://www.ever.com.pl/) */ #define EVER_ECO_PRO_CDS 0xe520 /* RS-232 converter */ /* * Active Robots product ids. */ #define FTDI_ACTIVE_ROBOTS_PID 0xE548 /* USB comms board */ /* Pyramid Computer GmbH */ #define FTDI_PYRAMID_PID 0xE6C8 /* Pyramid Appliance Display */ /* www.elsterelectricity.com Elster Unicom III Optical Probe */ #define FTDI_ELSTER_UNICOM_PID 0xE700 /* Product Id */ /* * Gude Analog- und Digitalsysteme GmbH */ #define FTDI_GUDEADS_E808_PID 0xE808 #define FTDI_GUDEADS_E809_PID 0xE809 #define FTDI_GUDEADS_E80A_PID 0xE80A #define FTDI_GUDEADS_E80B_PID 0xE80B #define FTDI_GUDEADS_E80C_PID 0xE80C #define FTDI_GUDEADS_E80D_PID 0xE80D #define FTDI_GUDEADS_E80E_PID 0xE80E #define FTDI_GUDEADS_E80F_PID 0xE80F #define FTDI_GUDEADS_E888_PID 0xE888 /* Expert ISDN Control USB */ #define FTDI_GUDEADS_E889_PID 0xE889 /* USB RS-232 OptoBridge */ #define FTDI_GUDEADS_E88A_PID 0xE88A #define FTDI_GUDEADS_E88B_PID 0xE88B #define FTDI_GUDEADS_E88C_PID 0xE88C #define FTDI_GUDEADS_E88D_PID 0xE88D #define FTDI_GUDEADS_E88E_PID 0xE88E #define FTDI_GUDEADS_E88F_PID 0xE88F /* * Eclo (http://www.eclo.pt/) product IDs. * PID 0xEA90 submitted by Martin Grill. */ #define FTDI_ECLO_COM_1WIRE_PID 0xEA90 /* COM to 1-Wire USB adaptor */ /* TNC-X USB-to-packet-radio adapter, versions prior to 3.0 (DLP module) */ #define FTDI_TNC_X_PID 0xEBE0 /* * Teratronik product ids. * Submitted by O. Wölfelschneider. */ #define FTDI_TERATRONIK_VCP_PID 0xEC88 /* Teratronik device (preferring VCP driver on windows) */ #define FTDI_TERATRONIK_D2XX_PID 0xEC89 /* Teratronik device (preferring D2XX driver on windows) */ /* Rig Expert Ukraine devices */ #define FTDI_REU_TINY_PID 0xED22 /* RigExpert Tiny */ /* * Hameg HO820 and HO870 interface (using VID 0x0403) */ #define HAMEG_HO820_PID 0xed74 #define HAMEG_HO730_PID 0xed73 #define HAMEG_HO720_PID 0xed72 #define HAMEG_HO870_PID 0xed71 /* * MaxStream devices www.maxstream.net */ #define FTDI_MAXSTREAM_PID 0xEE18 /* Xbee PKG-U Module */ /* * microHAM product IDs (http://www.microham.com). * Submitted by Justin Burket (KL1RL) <zorton@jtan.com> * and Mike Studer (K6EEP) <k6eep@hamsoftware.org>. * Ian Abbott <abbotti@mev.co.uk> added a few more from the driver INF file. */ #define FTDI_MHAM_KW_PID 0xEEE8 /* USB-KW interface */ #define FTDI_MHAM_YS_PID 0xEEE9 /* USB-YS interface */ #define FTDI_MHAM_Y6_PID 0xEEEA /* USB-Y6 interface */ #define FTDI_MHAM_Y8_PID 0xEEEB /* USB-Y8 interface */ #define FTDI_MHAM_IC_PID 0xEEEC /* USB-IC interface */ #define FTDI_MHAM_DB9_PID 0xEEED /* USB-DB9 interface */ #define FTDI_MHAM_RS232_PID 0xEEEE /* USB-RS232 interface */ #define FTDI_MHAM_Y9_PID 0xEEEF /* USB-Y9 interface */ /* Domintell products http://www.domintell.com */ #define FTDI_DOMINTELL_DGQG_PID 0xEF50 /* Master */ #define FTDI_DOMINTELL_DUSB_PID 0xEF51 /* DUSB01 module */ /* * The following are the values for the Perle Systems * UltraPort USB serial converters */ #define FTDI_PERLE_ULTRAPORT_PID 0xF0C0 /* Perle UltraPort Product Id */ /* Sprog II (Andrew Crosland's SprogII DCC interface) */ #define FTDI_SPROG_II 0xF0C8 /* an infrared receiver for user access control with IR tags */ #define FTDI_PIEGROUP_PID 0xF208 /* Product Id */ /* ACT Solutions HomePro ZWave interface (http://www.act-solutions.com/HomePro.htm) */ #define FTDI_ACTZWAVE_PID 0xF2D0 /* * 4N-GALAXY.DE PIDs for CAN-USB, USB-RS232, USB-RS422, USB-RS485, * USB-TTY aktiv, USB-TTY passiv. Some PIDs are used by several devices * and I'm not entirely sure which are used by which. */ #define FTDI_4N_GALAXY_DE_1_PID 0xF3C0 #define FTDI_4N_GALAXY_DE_2_PID 0xF3C1 /* * Linx Technologies product ids */ #define LINX_SDMUSBQSS_PID 0xF448 /* Linx SDM-USB-QS-S */ #define LINX_MASTERDEVEL2_PID 0xF449 /* Linx Master Development 2.0 */ #define LINX_FUTURE_0_PID 0xF44A /* Linx future device */ #define LINX_FUTURE_1_PID 0xF44B /* Linx future device */ #define LINX_FUTURE_2_PID 0xF44C /* Linx future device */ /* * Oceanic product ids */ #define FTDI_OCEANIC_PID 0xF460 /* Oceanic dive instrument */ /* * SUUNTO product ids */ #define FTDI_SUUNTO_SPORTS_PID 0xF680 /* Suunto Sports instrument */ /* USB-UIRT - An infrared receiver and transmitter using the 8U232AM chip */ /* http://home.earthlink.net/~jrhees/USBUIRT/index.htm */ #define FTDI_USB_UIRT_PID 0xF850 /* Product Id */ /* CCS Inc. ICDU/ICDU40 product ID - * the FT232BM is used in an in-circuit-debugger unit for PIC16's/PIC18's */ #define FTDI_CCSICDU20_0_PID 0xF9D0 #define FTDI_CCSICDU40_1_PID 0xF9D1 #define FTDI_CCSMACHX_2_PID 0xF9D2 #define FTDI_CCSLOAD_N_GO_3_PID 0xF9D3 #define FTDI_CCSICDU64_4_PID 0xF9D4 #define FTDI_CCSPRIME8_5_PID 0xF9D5 /* * The following are the values for the Matrix Orbital LCD displays, * which are the FT232BM ( similar to the 8U232AM ) */ #define FTDI_MTXORB_0_PID 0xFA00 /* Matrix Orbital Product Id */ #define FTDI_MTXORB_1_PID 0xFA01 /* Matrix Orbital Product Id */ #define FTDI_MTXORB_2_PID 0xFA02 /* Matrix Orbital Product Id */ #define FTDI_MTXORB_3_PID 0xFA03 /* Matrix Orbital Product Id */ #define FTDI_MTXORB_4_PID 0xFA04 /* Matrix Orbital Product Id */ #define FTDI_MTXORB_5_PID 0xFA05 /* Matrix Orbital Product Id */ #define FTDI_MTXORB_6_PID 0xFA06 /* Matrix Orbital Product Id */ /* * Home Electronics (www.home-electro.com) USB gadgets */ #define FTDI_HE_TIRA1_PID 0xFA78 /* Tira-1 IR transceiver */ /* Inside Accesso contactless reader (http://www.insidefr.com) */ #define INSIDE_ACCESSO 0xFAD0 /* * ThorLabs USB motor drivers */ #define FTDI_THORLABS_PID 0xfaf0 /* ThorLabs USB motor drivers */ /* * Protego product ids */ #define PROTEGO_SPECIAL_1 0xFC70 /* special/unknown device */ #define PROTEGO_R2X0 0xFC71 /* R200-USB TRNG unit (R210, R220, and R230) */ #define PROTEGO_SPECIAL_3 0xFC72 /* special/unknown device */ #define PROTEGO_SPECIAL_4 0xFC73 /* special/unknown device */ /* * DSS-20 Sync Station for Sony Ericsson P800 */ #define FTDI_DSS20_PID 0xFC82 /* www.irtrans.de device */ #define FTDI_IRTRANS_PID 0xFC60 /* Product Id */ /* * RM Michaelides CANview USB (http://www.rmcan.com) (FTDI_VID) * CAN fieldbus interface adapter, added by port GmbH www.port.de) * Ian Abbott changed the macro names for consistency. */ #define FTDI_RM_CANVIEW_PID 0xfd60 /* Product Id */ /* www.thoughttechnology.com/ TT-USB provide with procomp use ftdi_sio */ #define FTDI_TTUSB_PID 0xFF20 /* Product Id */ #define FTDI_USBX_707_PID 0xF857 /* ADSTech IR Blaster USBX-707 (FTDI_VID) */ #define FTDI_RELAIS_PID 0xFA10 /* Relais device from Rudolf Gugler */ /* * PCDJ use ftdi based dj-controllers. The following PID is * for their DAC-2 device http://www.pcdjhardware.com/DAC2.asp * (the VID is the standard ftdi vid (FTDI_VID), PID sent by Wouter Paesen) */ #define FTDI_PCDJ_DAC2_PID 0xFA88 #define FTDI_R2000KU_TRUE_RNG 0xFB80 /* R2000KU TRUE RNG (FTDI_VID) */ /* * DIEBOLD BCS SE923 (FTDI_VID) */ #define DIEBOLD_BCS_SE923_PID 0xfb99 /* www.crystalfontz.com devices * - thanx for providing free devices for evaluation ! * they use the ftdi chipset for the USB interface * and the vendor id is the same */ #define FTDI_XF_632_PID 0xFC08 /* 632: 16x2 Character Display */ #define FTDI_XF_634_PID 0xFC09 /* 634: 20x4 Character Display */ #define FTDI_XF_547_PID 0xFC0A /* 547: Two line Display */ #define FTDI_XF_633_PID 0xFC0B /* 633: 16x2 Character Display with Keys */ #define FTDI_XF_631_PID 0xFC0C /* 631: 20x2 Character Display */ #define FTDI_XF_635_PID 0xFC0D /* 635: 20x4 Character Display */ #define FTDI_XF_640_PID 0xFC0E /* 640: Two line Display */ #define FTDI_XF_642_PID 0xFC0F /* 642: Two line Display */ /* * Video Networks Limited / Homechoice in the UK use an ftdi-based device * for their 1Mb broadband internet service. The following PID is exhibited * by the usb device supplied (the VID is the standard ftdi vid (FTDI_VID) */ #define FTDI_VNHCPCUSB_D_PID 0xfe38 /* Product Id */ /* AlphaMicro Components AMC-232USB01 device (FTDI_VID) */ #define FTDI_AMC232_PID 0xFF00 /* Product Id */ /* * IBS elektronik product ids (FTDI_VID) * Submitted by Thomas Schleusener */ #define FTDI_IBS_US485_PID 0xff38 /* IBS US485 (USB<-->RS422/485 interface) */ #define FTDI_IBS_PICPRO_PID 0xff39 /* IBS PIC-Programmer */ #define FTDI_IBS_PCMCIA_PID 0xff3a /* IBS Card reader for PCMCIA SRAM-cards */ #define FTDI_IBS_PK1_PID 0xff3b /* IBS PK1 - Particel counter */ #define FTDI_IBS_RS232MON_PID 0xff3c /* IBS RS232 - Monitor */ #define FTDI_IBS_APP70_PID 0xff3d /* APP 70 (dust monitoring system) */ #define FTDI_IBS_PEDO_PID 0xff3e /* IBS PEDO-Modem (RF modem 868.35 MHz) */ #define FTDI_IBS_PROD_PID 0xff3f /* future device */ /* www.canusb.com Lawicel CANUSB device (FTDI_VID) */ #define FTDI_CANUSB_PID 0xFFA8 /* Product Id */ /********************************/ /** third-party VID/PID combos **/ /********************************/ /* * Atmel STK541 */ #define ATMEL_VID 0x03eb /* Vendor ID */ #define STK541_PID 0x2109 /* Zigbee Controller */ /* * Blackfin gnICE JTAG * http://docs.blackfin.uclinux.org/doku.php?id=hw:jtag:gnice */ #define ADI_VID 0x0456 #define ADI_GNICE_PID 0xF000 #define ADI_GNICEPLUS_PID 0xF001 /* * RATOC REX-USB60F */ #define RATOC_VENDOR_ID 0x0584 #define RATOC_PRODUCT_ID_USB60F 0xb020 /* * Acton Research Corp. */ #define ACTON_VID 0x0647 /* Vendor ID */ #define ACTON_SPECTRAPRO_PID 0x0100 /* * Contec products (http://www.contec.com) * Submitted by Daniel Sangorrin */ #define CONTEC_VID 0x06CE /* Vendor ID */ #define CONTEC_COM1USBH_PID 0x8311 /* COM-1(USB)H */ /* * Definitions for B&B Electronics products. */ #define BANDB_VID 0x0856 /* B&B Electronics Vendor ID */ #define BANDB_USOTL4_PID 0xAC01 /* USOTL4 Isolated RS-485 Converter */ #define BANDB_USTL4_PID 0xAC02 /* USTL4 RS-485 Converter */ #define BANDB_USO9ML2_PID 0xAC03 /* USO9ML2 Isolated RS-232 Converter */ #define BANDB_USOPTL4_PID 0xAC11 #define BANDB_USPTL4_PID 0xAC12 #define BANDB_USO9ML2DR_2_PID 0xAC16 #define BANDB_USO9ML2DR_PID 0xAC17 #define BANDB_USOPTL4DR2_PID 0xAC18 /* USOPTL4R-2 2-port Isolated RS-232 Converter */ #define BANDB_USOPTL4DR_PID 0xAC19 #define BANDB_485USB9F_2W_PID 0xAC25 #define BANDB_485USB9F_4W_PID 0xAC26 #define BANDB_232USB9M_PID 0xAC27 #define BANDB_485USBTB_2W_PID 0xAC33 #define BANDB_485USBTB_4W_PID 0xAC34 #define BANDB_TTL5USB9M_PID 0xAC49 #define BANDB_TTL3USB9M_PID 0xAC50 #define BANDB_ZZ_PROG1_USB_PID 0xBA02 /* * Intrepid Control Systems (http://www.intrepidcs.com/) ValueCAN and NeoVI */ #define INTREPID_VID 0x093C #define INTREPID_VALUECAN_PID 0x0601 #define INTREPID_NEOVI_PID 0x0701 /* * Definitions for ID TECH (www.idt-net.com) devices */ #define IDTECH_VID 0x0ACD /* ID TECH Vendor ID */ #define IDTECH_IDT1221U_PID 0x0300 /* IDT1221U USB to RS-232 adapter */ /* * Definitions for Omnidirectional Control Technology, Inc. devices */ #define OCT_VID 0x0B39 /* OCT vendor ID */ /* Note: OCT US101 is also rebadged as Dick Smith Electronics (NZ) XH6381 */ /* Also rebadged as Dick Smith Electronics (Aus) XH6451 */ /* Also rebadged as SIIG Inc. model US2308 hardware version 1 */ #define OCT_DK201_PID 0x0103 /* OCT DK201 USB docking station */ #define OCT_US101_PID 0x0421 /* OCT US101 USB to RS-232 */ /* * Definitions for Icom Inc. devices */ #define ICOM_VID 0x0C26 /* Icom vendor ID */ /* Note: ID-1 is a communications tranceiver for HAM-radio operators */ #define ICOM_ID_1_PID 0x0004 /* ID-1 USB to RS-232 */ /* Note: OPC is an Optional cable to connect an Icom Tranceiver */ #define ICOM_OPC_U_UC_PID 0x0018 /* OPC-478UC, OPC-1122U cloning cable */ /* Note: ID-RP* devices are Icom Repeater Devices for HAM-radio */ #define ICOM_ID_RP2C1_PID 0x0009 /* ID-RP2C Asset 1 to RS-232 */ #define ICOM_ID_RP2C2_PID 0x000A /* ID-RP2C Asset 2 to RS-232 */ #define ICOM_ID_RP2D_PID 0x000B /* ID-RP2D configuration port*/ #define ICOM_ID_RP2VT_PID 0x000C /* ID-RP2V Transmit config port */ #define ICOM_ID_RP2VR_PID 0x000D /* ID-RP2V Receive config port */ #define ICOM_ID_RP4KVT_PID 0x0010 /* ID-RP4000V Transmit config port */ #define ICOM_ID_RP4KVR_PID 0x0011 /* ID-RP4000V Receive config port */ #define ICOM_ID_RP2KVT_PID 0x0012 /* ID-RP2000V Transmit config port */ #define ICOM_ID_RP2KVR_PID 0x0013 /* ID-RP2000V Receive config port */ /* * GN Otometrics (http://www.otometrics.com) * Submitted by Ville Sundberg. */ #define GN_OTOMETRICS_VID 0x0c33 /* Vendor ID */ #define AURICAL_USB_PID 0x0010 /* Aurical USB Audiometer */ /* * The following are the values for the Sealevel SeaLINK+ adapters. * (Original list sent by Tuan Hoang. Ian Abbott renamed the macros and * removed some PIDs that don't seem to match any existing products.) */ #define SEALEVEL_VID 0x0c52 /* Sealevel Vendor ID */ #define SEALEVEL_2101_PID 0x2101 /* SeaLINK+232 (2101/2105) */ #define SEALEVEL_2102_PID 0x2102 /* SeaLINK+485 (2102) */ #define SEALEVEL_2103_PID 0x2103 /* SeaLINK+232I (2103) */ #define SEALEVEL_2104_PID 0x2104 /* SeaLINK+485I (2104) */ #define SEALEVEL_2106_PID 0x9020 /* SeaLINK+422 (2106) */ #define SEALEVEL_2201_1_PID 0x2211 /* SeaPORT+2/232 (2201) Port 1 */ #define SEALEVEL_2201_2_PID 0x2221 /* SeaPORT+2/232 (2201) Port 2 */ #define SEALEVEL_2202_1_PID 0x2212 /* SeaPORT+2/485 (2202) Port 1 */ #define SEALEVEL_2202_2_PID 0x2222 /* SeaPORT+2/485 (2202) Port 2 */ #define SEALEVEL_2203_1_PID 0x2213 /* SeaPORT+2 (2203) Port 1 */ #define SEALEVEL_2203_2_PID 0x2223 /* SeaPORT+2 (2203) Port 2 */ #define SEALEVEL_2401_1_PID 0x2411 /* SeaPORT+4/232 (2401) Port 1 */ #define SEALEVEL_2401_2_PID 0x2421 /* SeaPORT+4/232 (2401) Port 2 */ #define SEALEVEL_2401_3_PID 0x2431 /* SeaPORT+4/232 (2401) Port 3 */ #define SEALEVEL_2401_4_PID 0x2441 /* SeaPORT+4/232 (2401) Port 4 */ #define SEALEVEL_2402_1_PID 0x2412 /* SeaPORT+4/485 (2402) Port 1 */ #define SEALEVEL_2402_2_PID 0x2422 /* SeaPORT+4/485 (2402) Port 2 */ #define SEALEVEL_2402_3_PID 0x2432 /* SeaPORT+4/485 (2402) Port 3 */ #define SEALEVEL_2402_4_PID 0x2442 /* SeaPORT+4/485 (2402) Port 4 */ #define SEALEVEL_2403_1_PID 0x2413 /* SeaPORT+4 (2403) Port 1 */ #define SEALEVEL_2403_2_PID 0x2423 /* SeaPORT+4 (2403) Port 2 */ #define SEALEVEL_2403_3_PID 0x2433 /* SeaPORT+4 (2403) Port 3 */ #define SEALEVEL_2403_4_PID 0x2443 /* SeaPORT+4 (2403) Port 4 */ #define SEALEVEL_2801_1_PID 0X2811 /* SeaLINK+8/232 (2801) Port 1 */ #define SEALEVEL_2801_2_PID 0X2821 /* SeaLINK+8/232 (2801) Port 2 */ #define SEALEVEL_2801_3_PID 0X2831 /* SeaLINK+8/232 (2801) Port 3 */ #define SEALEVEL_2801_4_PID 0X2841 /* SeaLINK+8/232 (2801) Port 4 */ #define SEALEVEL_2801_5_PID 0X2851 /* SeaLINK+8/232 (2801) Port 5 */ #define SEALEVEL_2801_6_PID 0X2861 /* SeaLINK+8/232 (2801) Port 6 */ #define SEALEVEL_2801_7_PID 0X2871 /* SeaLINK+8/232 (2801) Port 7 */ #define SEALEVEL_2801_8_PID 0X2881 /* SeaLINK+8/232 (2801) Port 8 */ #define SEALEVEL_2802_1_PID 0X2812 /* SeaLINK+8/485 (2802) Port 1 */ #define SEALEVEL_2802_2_PID 0X2822 /* SeaLINK+8/485 (2802) Port 2 */ #define SEALEVEL_2802_3_PID 0X2832 /* SeaLINK+8/485 (2802) Port 3 */ #define SEALEVEL_2802_4_PID 0X2842 /* SeaLINK+8/485 (2802) Port 4 */ #define SEALEVEL_2802_5_PID 0X2852 /* SeaLINK+8/485 (2802) Port 5 */ #define SEALEVEL_2802_6_PID 0X2862 /* SeaLINK+8/485 (2802) Port 6 */ #define SEALEVEL_2802_7_PID 0X2872 /* SeaLINK+8/485 (2802) Port 7 */ #define SEALEVEL_2802_8_PID 0X2882 /* SeaLINK+8/485 (2802) Port 8 */ #define SEALEVEL_2803_1_PID 0X2813 /* SeaLINK+8 (2803) Port 1 */ #define SEALEVEL_2803_2_PID 0X2823 /* SeaLINK+8 (2803) Port 2 */ #define SEALEVEL_2803_3_PID 0X2833 /* SeaLINK+8 (2803) Port 3 */ #define SEALEVEL_2803_4_PID 0X2843 /* SeaLINK+8 (2803) Port 4 */ #define SEALEVEL_2803_5_PID 0X2853 /* SeaLINK+8 (2803) Port 5 */ #define SEALEVEL_2803_6_PID 0X2863 /* SeaLINK+8 (2803) Port 6 */ #define SEALEVEL_2803_7_PID 0X2873 /* SeaLINK+8 (2803) Port 7 */ #define SEALEVEL_2803_8_PID 0X2883 /* SeaLINK+8 (2803) Port 8 */ /* * JETI SPECTROMETER SPECBOS 1201 * http://www.jeti.com/products/sys/scb/scb1201.php */ #define JETI_VID 0x0c6c #define JETI_SPC1201_PID 0x04b2 /* * FTDI USB UART chips used in construction projects from the * Elektor Electronics magazine (http://elektor-electronics.co.uk) */ #define ELEKTOR_VID 0x0C7D #define ELEKTOR_FT323R_PID 0x0005 /* RFID-Reader, issue 09-2006 */ /* * Posiflex inc retail equipment (http://www.posiflex.com.tw) */ #define POSIFLEX_VID 0x0d3a /* Vendor ID */ #define POSIFLEX_PP7000_PID 0x0300 /* PP-7000II thermal printer */ /* * The following are the values for two KOBIL chipcard terminals. */ #define KOBIL_VID 0x0d46 /* KOBIL Vendor ID */ #define KOBIL_CONV_B1_PID 0x2020 /* KOBIL Konverter for B1 */ #define KOBIL_CONV_KAAN_PID 0x2021 /* KOBIL_Konverter for KAAN */ #define FTDI_NF_RIC_VID 0x0DCD /* Vendor Id */ #define FTDI_NF_RIC_PID 0x0001 /* Product Id */ /* * Falcom Wireless Communications GmbH */ #define FALCOM_VID 0x0F94 /* Vendor Id */ #define FALCOM_TWIST_PID 0x0001 /* Falcom Twist USB GPRS modem */ #define FALCOM_SAMBA_PID 0x0005 /* Falcom Samba USB GPRS modem */ /* Larsen and Brusgaard AltiTrack/USBtrack */ #define LARSENBRUSGAARD_VID 0x0FD8 #define LB_ALTITRACK_PID 0x0001 /* * TTi (Thurlby Thandar Instruments) */ #define TTI_VID 0x103E /* Vendor Id */ #define TTI_QL355P_PID 0x03E8 /* TTi QL355P power supply */ /* Interbiometrics USB I/O Board */ /* Developed for Interbiometrics by Rudolf Gugler */ #define INTERBIOMETRICS_VID 0x1209 #define INTERBIOMETRICS_IOBOARD_PID 0x1002 #define INTERBIOMETRICS_MINI_IOBOARD_PID 0x1006 /* * Testo products (http://www.testo.com/) * Submitted by Colin Leroy */ #define TESTO_VID 0x128D #define TESTO_USB_INTERFACE_PID 0x0001 /* * Mobility Electronics products. */ #define MOBILITY_VID 0x1342 #define MOBILITY_USB_SERIAL_PID 0x0202 /* EasiDock USB 200 serial */ /* * FIC / OpenMoko, Inc. http://wiki.openmoko.org/wiki/Neo1973_Debug_Board_v3 * Submitted by Harald Welte <laforge@openmoko.org> */ #define FIC_VID 0x1457 #define FIC_NEO1973_DEBUG_PID 0x5118 /* Olimex */ #define OLIMEX_VID 0x15BA #define OLIMEX_ARM_USB_OCD_PID 0x0003 /* * Telldus Technologies */ #define TELLDUS_VID 0x1781 /* Vendor ID */ #define TELLDUS_TELLSTICK_PID 0x0C30 /* RF control dongle 433 MHz using FT232RL */ /* * RT Systems programming cables for various ham radios */ #define RTSYSTEMS_VID 0x2100 /* Vendor ID */ #define RTSYSTEMS_SERIAL_VX7_PID 0x9e52 /* Serial converter for VX-7 Radios using FT232RL */ /* * Bayer Ascensia Contour blood glucose meter USB-converter cable. * http://winglucofacts.com/cables/ */ #define BAYER_VID 0x1A79 #define BAYER_CONTOUR_CABLE_PID 0x6001 /* * The following are the values for the Matrix Orbital FTDI Range * Anything in this range will use an FT232RL. */ #define MTXORB_VID 0x1B3D #define MTXORB_FTDI_RANGE_0100_PID 0x0100 #define MTXORB_FTDI_RANGE_0101_PID 0x0101 #define MTXORB_FTDI_RANGE_0102_PID 0x0102 #define MTXORB_FTDI_RANGE_0103_PID 0x0103 #define MTXORB_FTDI_RANGE_0104_PID 0x0104 #define MTXORB_FTDI_RANGE_0105_PID 0x0105 #define MTXORB_FTDI_RANGE_0106_PID 0x0106 #define MTXORB_FTDI_RANGE_0107_PID 0x0107 #define MTXORB_FTDI_RANGE_0108_PID 0x0108 #define MTXORB_FTDI_RANGE_0109_PID 0x0109 #define MTXORB_FTDI_RANGE_010A_PID 0x010A #define MTXORB_FTDI_RANGE_010B_PID 0x010B #define MTXORB_FTDI_RANGE_010C_PID 0x010C #define MTXORB_FTDI_RANGE_010D_PID 0x010D #define MTXORB_FTDI_RANGE_010E_PID 0x010E #define MTXORB_FTDI_RANGE_010F_PID 0x010F #define MTXORB_FTDI_RANGE_0110_PID 0x0110 #define MTXORB_FTDI_RANGE_0111_PID 0x0111 #define MTXORB_FTDI_RANGE_0112_PID 0x0112 #define MTXORB_FTDI_RANGE_0113_PID 0x0113 #define MTXORB_FTDI_RANGE_0114_PID 0x0114 #define MTXORB_FTDI_RANGE_0115_PID 0x0115 #define MTXORB_FTDI_RANGE_0116_PID 0x0116 #define MTXORB_FTDI_RANGE_0117_PID 0x0117 #define MTXORB_FTDI_RANGE_0118_PID 0x0118 #define MTXORB_FTDI_RANGE_0119_PID 0x0119 #define MTXORB_FTDI_RANGE_011A_PID 0x011A #define MTXORB_FTDI_RANGE_011B_PID 0x011B #define MTXORB_FTDI_RANGE_011C_PID 0x011C #define MTXORB_FTDI_RANGE_011D_PID 0x011D #define MTXORB_FTDI_RANGE_011E_PID 0x011E #define MTXORB_FTDI_RANGE_011F_PID 0x011F #define MTXORB_FTDI_RANGE_0120_PID 0x0120 #define MTXORB_FTDI_RANGE_0121_PID 0x0121 #define MTXORB_FTDI_RANGE_0122_PID 0x0122 #define MTXORB_FTDI_RANGE_0123_PID 0x0123 #define MTXORB_FTDI_RANGE_0124_PID 0x0124 #define MTXORB_FTDI_RANGE_0125_PID 0x0125 #define MTXORB_FTDI_RANGE_0126_PID 0x0126 #define MTXORB_FTDI_RANGE_0127_PID 0x0127 #define MTXORB_FTDI_RANGE_0128_PID 0x0128 #define MTXORB_FTDI_RANGE_0129_PID 0x0129 #define MTXORB_FTDI_RANGE_012A_PID 0x012A #define MTXORB_FTDI_RANGE_012B_PID 0x012B #define MTXORB_FTDI_RANGE_012C_PID 0x012C #define MTXORB_FTDI_RANGE_012D_PID 0x012D #define MTXORB_FTDI_RANGE_012E_PID 0x012E #define MTXORB_FTDI_RANGE_012F_PID 0x012F #define MTXORB_FTDI_RANGE_0130_PID 0x0130 #define MTXORB_FTDI_RANGE_0131_PID 0x0131 #define MTXORB_FTDI_RANGE_0132_PID 0x0132 #define MTXORB_FTDI_RANGE_0133_PID 0x0133 #define MTXORB_FTDI_RANGE_0134_PID 0x0134 #define MTXORB_FTDI_RANGE_0135_PID 0x0135 #define MTXORB_FTDI_RANGE_0136_PID 0x0136 #define MTXORB_FTDI_RANGE_0137_PID 0x0137 #define MTXORB_FTDI_RANGE_0138_PID 0x0138 #define MTXORB_FTDI_RANGE_0139_PID 0x0139 #define MTXORB_FTDI_RANGE_013A_PID 0x013A #define MTXORB_FTDI_RANGE_013B_PID 0x013B #define MTXORB_FTDI_RANGE_013C_PID 0x013C #define MTXORB_FTDI_RANGE_013D_PID 0x013D #define MTXORB_FTDI_RANGE_013E_PID 0x013E #define MTXORB_FTDI_RANGE_013F_PID 0x013F #define MTXORB_FTDI_RANGE_0140_PID 0x0140 #define MTXORB_FTDI_RANGE_0141_PID 0x0141 #define MTXORB_FTDI_RANGE_0142_PID 0x0142 #define MTXORB_FTDI_RANGE_0143_PID 0x0143 #define MTXORB_FTDI_RANGE_0144_PID 0x0144 #define MTXORB_FTDI_RANGE_0145_PID 0x0145 #define MTXORB_FTDI_RANGE_0146_PID 0x0146 #define MTXORB_FTDI_RANGE_0147_PID 0x0147 #define MTXORB_FTDI_RANGE_0148_PID 0x0148 #define MTXORB_FTDI_RANGE_0149_PID 0x0149 #define MTXORB_FTDI_RANGE_014A_PID 0x014A #define MTXORB_FTDI_RANGE_014B_PID 0x014B #define MTXORB_FTDI_RANGE_014C_PID 0x014C #define MTXORB_FTDI_RANGE_014D_PID 0x014D #define MTXORB_FTDI_RANGE_014E_PID 0x014E #define MTXORB_FTDI_RANGE_014F_PID 0x014F #define MTXORB_FTDI_RANGE_0150_PID 0x0150 #define MTXORB_FTDI_RANGE_0151_PID 0x0151 #define MTXORB_FTDI_RANGE_0152_PID 0x0152 #define MTXORB_FTDI_RANGE_0153_PID 0x0153 #define MTXORB_FTDI_RANGE_0154_PID 0x0154 #define MTXORB_FTDI_RANGE_0155_PID 0x0155 #define MTXORB_FTDI_RANGE_0156_PID 0x0156 #define MTXORB_FTDI_RANGE_0157_PID 0x0157 #define MTXORB_FTDI_RANGE_0158_PID 0x0158 #define MTXORB_FTDI_RANGE_0159_PID 0x0159 #define MTXORB_FTDI_RANGE_015A_PID 0x015A #define MTXORB_FTDI_RANGE_015B_PID 0x015B #define MTXORB_FTDI_RANGE_015C_PID 0x015C #define MTXORB_FTDI_RANGE_015D_PID 0x015D #define MTXORB_FTDI_RANGE_015E_PID 0x015E #define MTXORB_FTDI_RANGE_015F_PID 0x015F #define MTXORB_FTDI_RANGE_0160_PID 0x0160 #define MTXORB_FTDI_RANGE_0161_PID 0x0161 #define MTXORB_FTDI_RANGE_0162_PID 0x0162 #define MTXORB_FTDI_RANGE_0163_PID 0x0163 #define MTXORB_FTDI_RANGE_0164_PID 0x0164 #define MTXORB_FTDI_RANGE_0165_PID 0x0165 #define MTXORB_FTDI_RANGE_0166_PID 0x0166 #define MTXORB_FTDI_RANGE_0167_PID 0x0167 #define MTXORB_FTDI_RANGE_0168_PID 0x0168 #define MTXORB_FTDI_RANGE_0169_PID 0x0169 #define MTXORB_FTDI_RANGE_016A_PID 0x016A #define MTXORB_FTDI_RANGE_016B_PID 0x016B #define MTXORB_FTDI_RANGE_016C_PID 0x016C #define MTXORB_FTDI_RANGE_016D_PID 0x016D #define MTXORB_FTDI_RANGE_016E_PID 0x016E #define MTXORB_FTDI_RANGE_016F_PID 0x016F #define MTXORB_FTDI_RANGE_0170_PID 0x0170 #define MTXORB_FTDI_RANGE_0171_PID 0x0171 #define MTXORB_FTDI_RANGE_0172_PID 0x0172 #define MTXORB_FTDI_RANGE_0173_PID 0x0173 #define MTXORB_FTDI_RANGE_0174_PID 0x0174 #define MTXORB_FTDI_RANGE_0175_PID 0x0175 #define MTXORB_FTDI_RANGE_0176_PID 0x0176 #define MTXORB_FTDI_RANGE_0177_PID 0x0177 #define MTXORB_FTDI_RANGE_0178_PID 0x0178 #define MTXORB_FTDI_RANGE_0179_PID 0x0179 #define MTXORB_FTDI_RANGE_017A_PID 0x017A #define MTXORB_FTDI_RANGE_017B_PID 0x017B #define MTXORB_FTDI_RANGE_017C_PID 0x017C #define MTXORB_FTDI_RANGE_017D_PID 0x017D #define MTXORB_FTDI_RANGE_017E_PID 0x017E #define MTXORB_FTDI_RANGE_017F_PID 0x017F #define MTXORB_FTDI_RANGE_0180_PID 0x0180 #define MTXORB_FTDI_RANGE_0181_PID 0x0181 #define MTXORB_FTDI_RANGE_0182_PID 0x0182 #define MTXORB_FTDI_RANGE_0183_PID 0x0183 #define MTXORB_FTDI_RANGE_0184_PID 0x0184 #define MTXORB_FTDI_RANGE_0185_PID 0x0185 #define MTXORB_FTDI_RANGE_0186_PID 0x0186 #define MTXORB_FTDI_RANGE_0187_PID 0x0187 #define MTXORB_FTDI_RANGE_0188_PID 0x0188 #define MTXORB_FTDI_RANGE_0189_PID 0x0189 #define MTXORB_FTDI_RANGE_018A_PID 0x018A #define MTXORB_FTDI_RANGE_018B_PID 0x018B #define MTXORB_FTDI_RANGE_018C_PID 0x018C #define MTXORB_FTDI_RANGE_018D_PID 0x018D #define MTXORB_FTDI_RANGE_018E_PID 0x018E #define MTXORB_FTDI_RANGE_018F_PID 0x018F #define MTXORB_FTDI_RANGE_0190_PID 0x0190 #define MTXORB_FTDI_RANGE_0191_PID 0x0191 #define MTXORB_FTDI_RANGE_0192_PID 0x0192 #define MTXORB_FTDI_RANGE_0193_PID 0x0193 #define MTXORB_FTDI_RANGE_0194_PID 0x0194 #define MTXORB_FTDI_RANGE_0195_PID 0x0195 #define MTXORB_FTDI_RANGE_0196_PID 0x0196 #define MTXORB_FTDI_RANGE_0197_PID 0x0197 #define MTXORB_FTDI_RANGE_0198_PID 0x0198 #define MTXORB_FTDI_RANGE_0199_PID 0x0199 #define MTXORB_FTDI_RANGE_019A_PID 0x019A #define MTXORB_FTDI_RANGE_019B_PID 0x019B #define MTXORB_FTDI_RANGE_019C_PID 0x019C #define MTXORB_FTDI_RANGE_019D_PID 0x019D #define MTXORB_FTDI_RANGE_019E_PID 0x019E #define MTXORB_FTDI_RANGE_019F_PID 0x019F #define MTXORB_FTDI_RANGE_01A0_PID 0x01A0 #define MTXORB_FTDI_RANGE_01A1_PID 0x01A1 #define MTXORB_FTDI_RANGE_01A2_PID 0x01A2 #define MTXORB_FTDI_RANGE_01A3_PID 0x01A3 #define MTXORB_FTDI_RANGE_01A4_PID 0x01A4 #define MTXORB_FTDI_RANGE_01A5_PID 0x01A5 #define MTXORB_FTDI_RANGE_01A6_PID 0x01A6 #define MTXORB_FTDI_RANGE_01A7_PID 0x01A7 #define MTXORB_FTDI_RANGE_01A8_PID 0x01A8 #define MTXORB_FTDI_RANGE_01A9_PID 0x01A9 #define MTXORB_FTDI_RANGE_01AA_PID 0x01AA #define MTXORB_FTDI_RANGE_01AB_PID 0x01AB #define MTXORB_FTDI_RANGE_01AC_PID 0x01AC #define MTXORB_FTDI_RANGE_01AD_PID 0x01AD #define MTXORB_FTDI_RANGE_01AE_PID 0x01AE #define MTXORB_FTDI_RANGE_01AF_PID 0x01AF #define MTXORB_FTDI_RANGE_01B0_PID 0x01B0 #define MTXORB_FTDI_RANGE_01B1_PID 0x01B1 #define MTXORB_FTDI_RANGE_01B2_PID 0x01B2 #define MTXORB_FTDI_RANGE_01B3_PID 0x01B3 #define MTXORB_FTDI_RANGE_01B4_PID 0x01B4 #define MTXORB_FTDI_RANGE_01B5_PID 0x01B5 #define MTXORB_FTDI_RANGE_01B6_PID 0x01B6 #define MTXORB_FTDI_RANGE_01B7_PID 0x01B7 #define MTXORB_FTDI_RANGE_01B8_PID 0x01B8 #define MTXORB_FTDI_RANGE_01B9_PID 0x01B9 #define MTXORB_FTDI_RANGE_01BA_PID 0x01BA #define MTXORB_FTDI_RANGE_01BB_PID 0x01BB #define MTXORB_FTDI_RANGE_01BC_PID 0x01BC #define MTXORB_FTDI_RANGE_01BD_PID 0x01BD #define MTXORB_FTDI_RANGE_01BE_PID 0x01BE #define MTXORB_FTDI_RANGE_01BF_PID 0x01BF #define MTXORB_FTDI_RANGE_01C0_PID 0x01C0 #define MTXORB_FTDI_RANGE_01C1_PID 0x01C1 #define MTXORB_FTDI_RANGE_01C2_PID 0x01C2 #define MTXORB_FTDI_RANGE_01C3_PID 0x01C3 #define MTXORB_FTDI_RANGE_01C4_PID 0x01C4 #define MTXORB_FTDI_RANGE_01C5_PID 0x01C5 #define MTXORB_FTDI_RANGE_01C6_PID 0x01C6 #define MTXORB_FTDI_RANGE_01C7_PID 0x01C7 #define MTXORB_FTDI_RANGE_01C8_PID 0x01C8 #define MTXORB_FTDI_RANGE_01C9_PID 0x01C9 #define MTXORB_FTDI_RANGE_01CA_PID 0x01CA #define MTXORB_FTDI_RANGE_01CB_PID 0x01CB #define MTXORB_FTDI_RANGE_01CC_PID 0x01CC #define MTXORB_FTDI_RANGE_01CD_PID 0x01CD #define MTXORB_FTDI_RANGE_01CE_PID 0x01CE #define MTXORB_FTDI_RANGE_01CF_PID 0x01CF #define MTXORB_FTDI_RANGE_01D0_PID 0x01D0 #define MTXORB_FTDI_RANGE_01D1_PID 0x01D1 #define MTXORB_FTDI_RANGE_01D2_PID 0x01D2 #define MTXORB_FTDI_RANGE_01D3_PID 0x01D3 #define MTXORB_FTDI_RANGE_01D4_PID 0x01D4 #define MTXORB_FTDI_RANGE_01D5_PID 0x01D5 #define MTXORB_FTDI_RANGE_01D6_PID 0x01D6 #define MTXORB_FTDI_RANGE_01D7_PID 0x01D7 #define MTXORB_FTDI_RANGE_01D8_PID 0x01D8 #define MTXORB_FTDI_RANGE_01D9_PID 0x01D9 #define MTXORB_FTDI_RANGE_01DA_PID 0x01DA #define MTXORB_FTDI_RANGE_01DB_PID 0x01DB #define MTXORB_FTDI_RANGE_01DC_PID 0x01DC #define MTXORB_FTDI_RANGE_01DD_PID 0x01DD #define MTXORB_FTDI_RANGE_01DE_PID 0x01DE #define MTXORB_FTDI_RANGE_01DF_PID 0x01DF #define MTXORB_FTDI_RANGE_01E0_PID 0x01E0 #define MTXORB_FTDI_RANGE_01E1_PID 0x01E1 #define MTXORB_FTDI_RANGE_01E2_PID 0x01E2 #define MTXORB_FTDI_RANGE_01E3_PID 0x01E3 #define MTXORB_FTDI_RANGE_01E4_PID 0x01E4 #define MTXORB_FTDI_RANGE_01E5_PID 0x01E5 #define MTXORB_FTDI_RANGE_01E6_PID 0x01E6 #define MTXORB_FTDI_RANGE_01E7_PID 0x01E7 #define MTXORB_FTDI_RANGE_01E8_PID 0x01E8 #define MTXORB_FTDI_RANGE_01E9_PID 0x01E9 #define MTXORB_FTDI_RANGE_01EA_PID 0x01EA #define MTXORB_FTDI_RANGE_01EB_PID 0x01EB #define MTXORB_FTDI_RANGE_01EC_PID 0x01EC #define MTXORB_FTDI_RANGE_01ED_PID 0x01ED #define MTXORB_FTDI_RANGE_01EE_PID 0x01EE #define MTXORB_FTDI_RANGE_01EF_PID 0x01EF #define MTXORB_FTDI_RANGE_01F0_PID 0x01F0 #define MTXORB_FTDI_RANGE_01F1_PID 0x01F1 #define MTXORB_FTDI_RANGE_01F2_PID 0x01F2 #define MTXORB_FTDI_RANGE_01F3_PID 0x01F3 #define MTXORB_FTDI_RANGE_01F4_PID 0x01F4 #define MTXORB_FTDI_RANGE_01F5_PID 0x01F5 #define MTXORB_FTDI_RANGE_01F6_PID 0x01F6 #define MTXORB_FTDI_RANGE_01F7_PID 0x01F7 #define MTXORB_FTDI_RANGE_01F8_PID 0x01F8 #define MTXORB_FTDI_RANGE_01F9_PID 0x01F9 #define MTXORB_FTDI_RANGE_01FA_PID 0x01FA #define MTXORB_FTDI_RANGE_01FB_PID 0x01FB #define MTXORB_FTDI_RANGE_01FC_PID 0x01FC #define MTXORB_FTDI_RANGE_01FD_PID 0x01FD #define MTXORB_FTDI_RANGE_01FE_PID 0x01FE #define MTXORB_FTDI_RANGE_01FF_PID 0x01FF /* * The Mobility Lab (TML) * Submitted by Pierre Castella */ #define TML_VID 0x1B91 /* Vendor ID */ #define TML_USB_SERIAL_PID 0x0064 /* USB - Serial Converter */ /* Alti-2 products http://www.alti-2.com */ #define ALTI2_VID 0x1BC9 #define ALTI2_N3_PID 0x6001 /* Neptune 3 */ /* * Ionics PlugComputer */ #define IONICS_VID 0x1c0c #define IONICS_PLUGCOMPUTER_PID 0x0102 /* * Dresden Elektronik Sensor Terminal Board */ #define DE_VID 0x1cf1 /* Vendor ID */ #define STB_PID 0x0001 /* Sensor Terminal Board */ #define WHT_PID 0x0004 /* Wireless Handheld Terminal */ /* * STMicroelectonics */ #define ST_VID 0x0483 #define ST_STMCLT1030_PID 0x3747 /* ST Micro Connect Lite STMCLT1030 */ /* * Papouch products (http://www.papouch.com/) * Submitted by Folkert van Heusden */ #define PAPOUCH_VID 0x5050 /* Vendor ID */ #define PAPOUCH_TMU_PID 0x0400 /* TMU USB Thermometer */ #define PAPOUCH_QUIDO4x4_PID 0x0900 /* Quido 4/4 Module */ #define PAPOUCH_AD4USB_PID 0x8003 /* AD4USB Measurement Module */ /* * Marvell SheevaPlug */ #define MARVELL_VID 0x9e88 #define MARVELL_SHEEVAPLUG_PID 0x9e8f /* * Evolution Robotics products (http://www.evolution.com/). * Submitted by Shawn M. Lavelle. */ #define EVOLUTION_VID 0xDEEE /* Vendor ID */ #define EVOLUTION_ER1_PID 0x0300 /* ER1 Control Module */ #define EVO_8U232AM_PID 0x02FF /* Evolution robotics RCM2 (FT232AM)*/ #define EVO_HYBRID_PID 0x0302 /* Evolution robotics RCM4 PID (FT232BM)*/ #define EVO_RCM4_PID 0x0303 /* Evolution robotics RCM4 PID */ /* * MJS Gadgets HD Radio / XM Radio / Sirius Radio interfaces (using VID 0x0403) */ #define MJSG_GENERIC_PID 0x9378 #define MJSG_SR_RADIO_PID 0x9379 #define MJSG_XM_RADIO_PID 0x937A #define MJSG_HD_RADIO_PID 0x937C /* * D.O.Tec products (http://www.directout.eu) */ #define FTDI_DOTEC_PID 0x9868 /* * Xverve Signalyzer tools (http://www.signalyzer.com/) */ #define XVERVE_SIGNALYZER_ST_PID 0xBCA0 #define XVERVE_SIGNALYZER_SLITE_PID 0xBCA1 #define XVERVE_SIGNALYZER_SH2_PID 0xBCA2 #define XVERVE_SIGNALYZER_SH4_PID 0xBCA4 /* * Segway Robotic Mobility Platform USB interface (using VID 0x0403) * Submitted by John G. Rogers */ #define SEGWAY_RMP200_PID 0xe729
Bdaman80/BDA-Lexikon
drivers/usb/serial/ftdi_sio_ids.h
C
gpl-2.0
41,479
// // Copyright (c) 2004-2006 Jaroslaw Kowalski <jaak@jkowalski.net> // // 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 Jaroslaw Kowalski 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. // using System; using System.IO; using System.Text; using System.Xml; using System.Reflection; using System.Collections; using System.Diagnostics; using NLog.Internal; using NLog.Config; using NLog.Conditions; using System.Collections.Generic; namespace NLog.Targets.Wrappers { /// <summary> /// A target wrapper that filters buffered log entries based on a set of conditions /// that are evaluated on all events. /// </summary> /// <remarks> /// PostFilteringWrapper must be used with some type of buffering target or wrapper, such as /// AsyncTargetWrapper, BufferingWrapper or ASPNetBufferingWrapper. /// </remarks> /// <example> /// <p> /// This example works like this. If there are no Warn,Error or Fatal messages in the buffer /// only Info messages are written to the file, but if there are any warnings or errors, /// the output includes detailed trace (levels &gt;= Debug). You can plug in a different type /// of buffering wrapper (such as ASPNetBufferingWrapper) to achieve different /// functionality. /// </p> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" src="examples/targets/Configuration File/PostFilteringWrapper/NLog.config" /> /// <p> /// The above examples assume just one target and a single rule. See below for /// a programmatic configuration that's equivalent to the above config file: /// </p> /// <code lang="C#" src="examples/targets/Configuration API/PostFilteringWrapper/Simple/Example.cs" /> /// </example> [Target("PostFilteringWrapper", IgnoresLayout = true, IsWrapper = true)] public class PostFilteringTargetWrapper: WrapperTargetBase { private ConditionExpression _defaultFilter; private FilteringRuleCollection _rules = new FilteringRuleCollection(); /// <summary> /// Creates a new instance of <see cref="PostFilteringTargetWrapper"/>. /// </summary> public PostFilteringTargetWrapper() { } /// <summary> /// Default filter to be applied when no specific rule matches. /// </summary> public string DefaultFilter { get { return _defaultFilter.ToString(); } set { _defaultFilter = ConditionParser.ParseExpression(value); } } /// <summary> /// Collection of filtering rules. The rules are processed top-down /// and the first rule that matches determines the filtering condition to /// be applied to log events. /// </summary> [ArrayParameter(typeof(FilteringRule), "when")] public FilteringRuleCollection Rules { get { return _rules; } } /// <summary> /// Evaluates all filtering rules to find the first one that matches. /// The matching rule determines the filtering condition to be applied /// to all items in a buffer. If no condition matches, default filter /// is applied to the array of log events. /// </summary> /// <param name="logEvents">Array of log events to be post-filtered.</param> public override void Write(LogEventInfo[] logEvents) { ConditionExpression resultFilter = null; if (InternalLogger.IsTraceEnabled) { InternalLogger.Trace("Input: {0} events", logEvents.Length); } // evaluate all the rules to get the filtering condition for (int i = 0; i < logEvents.Length; ++i) { for (int j = 0; j < _rules.Count; ++j) { object v = _rules[j].ExistsCondition.Evaluate(logEvents[i]); if (v is bool && (bool)v) { if (InternalLogger.IsTraceEnabled) InternalLogger.Trace("Rule matched: {0}", _rules[j].ExistsCondition); resultFilter = _rules[j].FilterCondition; break; } } if (resultFilter != null) break; } if (resultFilter == null) resultFilter = _defaultFilter; if (InternalLogger.IsTraceEnabled) InternalLogger.Trace("Filter to apply: {0}", resultFilter); // apply the condition to the buffer List<LogEventInfo> resultBuffer = new List<LogEventInfo>(); for (int i = 0; i < logEvents.Length; ++i) { object v = resultFilter.Evaluate(logEvents[i]); if (v is bool && (bool)v) resultBuffer.Add(logEvents[i]); } if (InternalLogger.IsTraceEnabled) InternalLogger.Trace("After filtering: {0} events", resultBuffer.Count); if (resultBuffer.Count > 0) { WrappedTarget.Write(resultBuffer.ToArray()); } } /// <summary> /// Processes a single log event. Not very useful for this post-filtering /// wrapper. /// </summary> /// <param name="logEvent">Log event.</param> public override void Write(LogEventInfo logEvent) { Write(new LogEventInfo[] { logEvent }); } /// <summary> /// Adds all layouts used by this target to the specified collection. /// </summary> /// <param name="layouts">The collection to add layouts to.</param> public override void PopulateLayouts(LayoutCollection layouts) { base.PopulateLayouts(layouts); foreach (FilteringRule fr in Rules) { fr.FilterCondition.PopulateLayouts(layouts); fr.ExistsCondition.PopulateLayouts(layouts); } _defaultFilter.PopulateLayouts(layouts); } } }
WCell/WCell
Libraries/Source/NLog/Targets/Wrappers/PostFilteringWrapper.cs
C#
gpl-2.0
7,654
# # Copyright (C) 2007-2014 OpenWrt.org # # This is free software, licensed under the GNU General Public License v2. # See /LICENSE for more information. # include $(TOPDIR)/rules.mk include $(INCLUDE_DIR)/kernel.mk PKG_NAME:=mac80211 PKG_VERSION:=2014-11-04 PKG_RELEASE:=1 PKG_SOURCE_URL:=http://mirror2.openwrt.org/sources PKG_BACKPORT_VERSION:= PKG_MD5SUM:=d0b64853fb78cfd1d6cb639327811e2a PKG_SOURCE:=compat-wireless-$(PKG_VERSION)$(PKG_BACKPORT_VERSION).tar.bz2 PKG_BUILD_DIR:=$(KERNEL_BUILD_DIR)/compat-wireless-$(PKG_VERSION) PKG_BUILD_PARALLEL:=1 PKG_MAINTAINER:=Felix Fietkau <nbd@openwrt.org> PKG_DRIVERS = \ adm8211 ath5k libertas-usb libertas-sd p54-common p54-pci p54-usb p54-spi \ rt2x00-lib rt2x00-pci rt2x00-usb rt2800-lib rt2400-pci rt2500-pci \ rt2500-usb rt61-pci rt73-usb rt2800-mmio rt2800-pci rt2800-usb rt2800-soc \ rtl8180 rtl8187 zd1211rw mac80211-hwsim carl9170 b43 b43legacy \ ath9k-common ath9k ath9k-htc ath10k ath net-libipw net-ipw2100 net-ipw2200 \ mwl8k mwifiex-pcie net-hermes net-hermes-pci net-hermes-plx net-hermes-pcmcia \ iwl-legacy iwl3945 iwl4965 iwlagn wlcore wl12xx wl18xx lib80211 \ rtlwifi rtlwifi-pci rtlwifi-usb rtl8192c-common rtl8192ce rtl8192se \ rtl8192de rtl8192cu PKG_CONFIG_DEPENDS:= \ CONFIG_PACKAGE_kmod-mac80211 \ $(patsubst %,CONFIG_PACKAGE_kmod-%,$(PKG_DRIVERS)) \ CONFIG_PACKAGE_MAC80211_DEBUGFS \ CONFIG_PACKAGE_MAC80211_MESH \ CONFIG_PACKAGE_ATH_DEBUG \ CONFIG_PACKAGE_ATH_DFS \ CONFIG_PACKAGE_B43_DEBUG \ CONFIG_PACKAGE_B43_PIO \ CONFIG_PACKAGE_B43_PHY_G \ CONFIG_PACKAGE_B43_PHY_N \ CONFIG_PACKAGE_B43_PHY_LP \ CONFIG_PACKAGE_B43_PHY_HT \ CONFIG_PACKAGE_B43_BUSES_BCMA_AND_SSB \ CONFIG_PACKAGE_B43_BUSES_BCMA \ CONFIG_PACKAGE_B43_BUSES_SSB \ CONFIG_PACKAGE_RTLWIFI_DEBUG \ CONFIG_ATH_USER_REGD \ include $(INCLUDE_DIR)/package.mk WMENU:=Wireless Drivers define KernelPackage/mac80211/Default SUBMENU:=$(WMENU) URL:=http://linuxwireless.org/ MAINTAINER:=Felix Fietkau <nbd@openwrt.org> DEPENDS:=@(!TARGET_avr32||BROKEN) endef define KernelPackage/cfg80211 $(call KernelPackage/mac80211/Default) TITLE:=cfg80211 - wireless configuration API DEPENDS+= +iw FILES:= \ $(PKG_BUILD_DIR)/compat/compat.ko \ $(PKG_BUILD_DIR)/net/wireless/cfg80211.ko endef define KernelPackage/cfg80211/description cfg80211 is the Linux wireless LAN (802.11) configuration API. endef define KernelPackage/mac80211 $(call KernelPackage/mac80211/Default) TITLE:=Linux 802.11 Wireless Networking Stack DEPENDS+= +kmod-crypto-core +kmod-crypto-arc4 +kmod-crypto-aes +kmod-cfg80211 +hostapd-common KCONFIG:=\ CONFIG_AVERAGE=y FILES:= $(PKG_BUILD_DIR)/net/mac80211/mac80211.ko MENU:=1 endef define KernelPackage/mac80211/config if PACKAGE_kmod-mac80211 config PACKAGE_MAC80211_DEBUGFS bool "Export mac80211 internals in DebugFS" select KERNEL_DEBUG_FS select KERNEL_RELAY if PACKAGE_kmod-ath9k-common default y help Select this to see extensive information about the internal state of mac80211 in debugfs. config PACKAGE_MAC80211_MESH bool "Enable 802.11s mesh support" default y endif endef define KernelPackage/mac80211/description Generic IEEE 802.11 Networking Stack (mac80211) endef PKG_LINUX_FIRMWARE_NAME:=linux-firmware PKG_LINUX_FIRMWARE_VERSION:=7f388b4885cf64d6b7833612052d20d4197af96f PKG_LINUX_FIRMWARE_SOURCE:=$(PKG_LINUX_FIRMWARE_NAME)-2014-06-04-$(PKG_LINUX_FIRMWARE_VERSION).tar.bz2 PKG_LINUX_FIRMWARE_PROTO:=git PKG_LINUX_FIRMWARE_SOURCE_URL:=https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git PKG_LINUX_FIRMWARE_SUBDIR:=$(PKG_LINUX_FIRMWARE_NAME)-$(PKG_LINUX_FIRMWARE_VERSION) #PKG_LINUX_FIRMWARE_MIRROR_MD5SUM:=e219333f01835c6e556875a9e0deb3f9 define Download/linux-firmware FILE:=$(PKG_LINUX_FIRMWARE_SOURCE) URL:=$(PKG_LINUX_FIRMWARE_SOURCE_URL) MD5SUM:=$(PKG_LINUX_FIRMWARE_MD5SUM) PROTO:=$(PKG_LINUX_FIRMWARE_PROTO) VERSION:=$(PKG_LINUX_FIRMWARE_VERSION) SUBDIR:=$(PKG_LINUX_FIRMWARE_SUBDIR) MIRROR_MD5SUM:=$(PKG_LINUX_FIRMWARE_MIRROR_MD5SUM) endef $(eval $(call Download,linux-firmware)) PKG_ATH10K_LINUX_FIRMWARE_NAME:=ath10k-firmware PKG_ATH10K_LINUX_FIRMWARE_VERSION:=232b419e71dab27b52b96e80ea7649ed67bdac77 PKG_ATH10K_LINUX_FIRMWARE_SOURCE:=$(PKG_ATH10K_LINUX_FIRMWARE_NAME)-$(PKG_ATH10K_LINUX_FIRMWARE_VERSION).tar.bz2 PKG_ATH10K_LINUX_FIRMWARE_PROTO:=git PKG_ATH10K_LINUX_FIRMWARE_SOURCE_URL:=https://github.com/kvalo/ath10k-firmware.git PKG_ATH10K_LINUX_FIRMWARE_SUBDIR:=$(PKG_ATH10K_LINUX_FIRMWARE_NAME)-$(PKG_ATH10K_LINUX_FIRMWARE_VERSION) #PKG_ATH10K_LINUX_FIRMWARE_MIRROR_MD5SUM:=? define Download/ath10k-firmware FILE:=$(PKG_ATH10K_LINUX_FIRMWARE_SOURCE) URL:=$(PKG_ATH10K_LINUX_FIRMWARE_SOURCE_URL) PROTO:=$(PKG_ATH10K_LINUX_FIRMWARE_PROTO) VERSION:=$(PKG_ATH10K_LINUX_FIRMWARE_VERSION) SUBDIR:=$(PKG_ATH10K_LINUX_FIRMWARE_SUBDIR) #MIRROR_MD5SUM:=$(PKG_ATH10K_LINUX_FIRMWARE_MIRROR_MD5SUM) endef $(eval $(call Download,ath10k-firmware)) # Prism54 drivers P54PCIFW:=2.13.12.0.arm P54USBFW:=2.13.24.0.lm87.arm P54SPIFW:=2.13.0.0.a.13.14.arm define Download/p54usb FILE:=$(P54USBFW) URL:=http://daemonizer.de/prism54/prism54-fw/fw-usb MD5SUM:=8e8ab005a4f8f0123bcdc51bc25b47f6 endef $(eval $(call Download,p54usb)) define Download/p54pci FILE:=$(P54PCIFW) URL:=http://daemonizer.de/prism54/prism54-fw/fw-softmac MD5SUM:=ff7536af2092b1c4b21315bd103ef4c4 endef $(eval $(call Download,p54pci)) define Download/p54spi FILE:=$(P54SPIFW) URL:=http://daemonizer.de/prism54/prism54-fw/stlc4560 MD5SUM:=42661f8ecbadd88012807493f596081d endef $(eval $(call Download,p54spi)) define KernelPackage/p54/Default $(call KernelPackage/mac80211/Default) TITLE:=Prism54 Drivers endef define KernelPackage/p54/description Kernel module for Prism54 chipsets (mac80211) endef define KernelPackage/p54-common $(call KernelPackage/p54/Default) DEPENDS+= @PCI_SUPPORT||@USB_SUPPORT||@TARGET_omap24xx +kmod-mac80211 +kmod-lib-crc-ccitt TITLE+= (COMMON) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/p54/p54common.ko endef define KernelPackage/p54-pci $(call KernelPackage/p54/Default) TITLE+= (PCI) DEPENDS+= @PCI_SUPPORT +kmod-p54-common FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/p54/p54pci.ko AUTOLOAD:=$(call AutoProbe,p54pci) endef define KernelPackage/p54-usb $(call KernelPackage/p54/Default) TITLE+= (USB) DEPENDS+= @USB_SUPPORT +kmod-usb-core +kmod-p54-common FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/p54/p54usb.ko AUTOLOAD:=$(call AutoProbe,p54usb) endef define KernelPackage/p54-spi $(call KernelPackage/p54/Default) TITLE+= (SPI) DEPENDS+= @TARGET_omap24xx +kmod-p54-common FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/p54/p54spi.ko AUTOLOAD:=$(call AutoProbe,p54spi) endef define KernelPackage/rt2x00/Default $(call KernelPackage/mac80211/Default) TITLE:=Ralink Drivers for RT2x00 cards endef define KernelPackage/rt2x00-lib $(call KernelPackage/rt2x00/Default) DEPENDS+= @(PCI_SUPPORT||USB_SUPPORT||TARGET_ramips) +kmod-mac80211 +kmod-lib-crc-itu-t TITLE+= (LIB) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2x00lib.ko MENU:=1 endef define KernelPackage/rt2x00-lib/config if PACKAGE_kmod-rt2x00-lib config PACKAGE_RT2X00_LIB_DEBUGFS bool "Enable rt2x00 debugfs support" depends on PACKAGE_MAC80211_DEBUGFS help Enable creation of debugfs files for the rt2x00 drivers. These debugfs files support both reading and writing of the most important register types of the rt2x00 hardware. config PACKAGE_RT2X00_DEBUG bool "Enable rt2x00 debug output" help Enable debugging output for all rt2x00 modules endif endef define KernelPackage/rt2x00-mmio $(call KernelPackage/rt2x00/Default) DEPENDS+= @(PCI_SUPPORT||TARGET_ramips) +kmod-rt2x00-lib +kmod-eeprom-93cx6 HIDDEN:=1 TITLE+= (MMIO) FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2x00mmio.ko endef define KernelPackage/rt2x00-pci $(call KernelPackage/rt2x00/Default) DEPENDS+= @PCI_SUPPORT +kmod-rt2x00-mmio +kmod-rt2x00-lib HIDDEN:=1 TITLE+= (PCI) FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2x00pci.ko AUTOLOAD:=$(call AutoProbe,rt2x00pci) endef define KernelPackage/rt2x00-usb $(call KernelPackage/rt2x00/Default) DEPENDS+= @USB_SUPPORT +kmod-rt2x00-lib +kmod-usb-core HIDDEN:=1 TITLE+= (USB) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2x00usb.ko AUTOLOAD:=$(call AutoProbe,rt2x00usb) endef define KernelPackage/rt2800-lib $(call KernelPackage/rt2x00/Default) DEPENDS+= @(PCI_SUPPORT||USB_SUPPORT||TARGET_ramips) +kmod-rt2x00-lib +kmod-lib-crc-ccitt +@DRIVER_11N_SUPPORT HIDDEN:=1 TITLE+= (rt2800 LIB) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2800lib.ko endef define KernelPackage/rt2400-pci $(call KernelPackage/rt2x00/Default) DEPENDS+= @PCI_SUPPORT +kmod-rt2x00-pci TITLE+= (RT2400 PCI) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2400pci.ko AUTOLOAD:=$(call AutoProbe,rt2400pci) endef define KernelPackage/rt2500-pci $(call KernelPackage/rt2x00/Default) DEPENDS+= @PCI_SUPPORT +kmod-rt2x00-pci TITLE+= (RT2500 PCI) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2500pci.ko AUTOLOAD:=$(call AutoProbe,rt2500pci) endef define KernelPackage/rt2500-usb $(call KernelPackage/rt2x00/Default) DEPENDS+= @USB_SUPPORT +kmod-rt2x00-usb TITLE+= (RT2500 USB) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2500usb.ko AUTOLOAD:=$(call AutoProbe,rt2500usb) endef define KernelPackage/rt61-pci $(call KernelPackage/rt2x00/Default) DEPENDS+= @PCI_SUPPORT +kmod-rt2x00-pci TITLE+= (RT2x61 PCI) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt61pci.ko AUTOLOAD:=$(call AutoProbe,rt61pci) endef define KernelPackage/rt73-usb $(call KernelPackage/rt2x00/Default) DEPENDS+= @USB_SUPPORT +kmod-rt2x00-usb TITLE+= (RT73 USB) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt73usb.ko AUTOLOAD:=$(call AutoProbe,rt73usb) endef define KernelPackage/rt2800-mmio $(call KernelPackage/rt2x00/Default) TITLE += (RT28xx/RT3xxx MMIO) DEPENDS += +kmod-rt2800-lib +kmod-rt2x00-mmio HIDDEN:=1 FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2800mmio.ko endef define KernelPackage/rt2800-soc $(call KernelPackage/rt2x00/Default) DEPENDS += @(TARGET_ramips_rt288x||TARGET_ramips_rt305x||TARGET_ramips_rt3883||TARGET_ramips_mt7620) +kmod-rt2800-mmio +kmod-rt2800-lib TITLE += (RT28xx/RT3xxx SoC) FILES := \ $(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2x00soc.ko \ $(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2800soc.ko AUTOLOAD:=$(call AutoProbe,rt2800soc) endef define KernelPackage/rt2800-pci $(call KernelPackage/rt2x00/Default) DEPENDS+= @PCI_SUPPORT +kmod-rt2x00-pci +kmod-rt2800-lib +kmod-rt2800-mmio TITLE+= (RT2860 PCI) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2800pci.ko AUTOLOAD:=$(call AutoProbe,rt2800pci) endef define KernelPackage/rt2800-usb $(call KernelPackage/rt2x00/Default) DEPENDS+= @USB_SUPPORT +kmod-rt2x00-usb +kmod-rt2800-lib +kmod-lib-crc-ccitt TITLE+= (RT2870 USB) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2800usb.ko AUTOLOAD:=$(call AutoProbe,rt2800usb) endef define KernelPackage/rtl818x/Default $(call KernelPackage/mac80211/Default) TITLE:=Realtek Drivers for RTL818x devices URL:=http://wireless.kernel.org/en/users/Drivers/rtl8187 DEPENDS+= +kmod-eeprom-93cx6 +kmod-mac80211 endef define KernelPackage/rtl8180 $(call KernelPackage/rtl818x/Default) DEPENDS+= @PCI_SUPPORT TITLE+= (RTL8180 PCI) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtl818x/rtl8180/rtl818x_pci.ko AUTOLOAD:=$(call AutoProbe,rtl818x_pci) endef define KernelPackage/rtl8187 $(call KernelPackage/rtl818x/Default) DEPENDS+= @USB_SUPPORT +kmod-usb-core TITLE+= (RTL8187 USB) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtl818x/rtl8187/rtl8187.ko AUTOLOAD:=$(call AutoProbe,rtl8187) endef define KernelPackage/rtlwifi/config config PACKAGE_RTLWIFI_DEBUG bool "Realtek wireless debugging" depends on PACKAGE_kmod-rtlwifi help Say Y, if you want to debug realtek wireless drivers. endef define KernelPackage/rtlwifi $(call KernelPackage/mac80211/Default) TITLE:=Realtek common driver part DEPENDS+= @(PCI_SUPPORT||USB_SUPPORT) +kmod-mac80211 +@DRIVER_11N_SUPPORT FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtlwifi.ko HIDDEN:=1 endef define KernelPackage/rtlwifi-pci $(call KernelPackage/mac80211/Default) TITLE:=Realtek common driver part (PCI support) DEPENDS+= @PCI_SUPPORT +kmod-rtlwifi FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl_pci.ko AUTOLOAD:=$(call AutoProbe,rtl_pci) HIDDEN:=1 endef define KernelPackage/rtlwifi-usb $(call KernelPackage/mac80211/Default) TITLE:=Realtek common driver part (USB support) DEPENDS+= @USB_SUPPORT +kmod-usb-core +kmod-rtlwifi FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl_usb.ko AUTOLOAD:=$(call AutoProbe,rtl_usb) HIDDEN:=1 endef define KernelPackage/rtl8192c-common $(call KernelPackage/mac80211/Default) TITLE:=Realtek RTL8192CE/RTL8192CU common support module DEPENDS+= +kmod-rtlwifi FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl8192c/rtl8192c-common.ko HIDDEN:=1 endef define KernelPackage/rtl8192ce $(call KernelPackage/mac80211/Default) TITLE:=Realtek RTL8192CE/RTL8188CE support DEPENDS+= +kmod-rtlwifi-pci +kmod-rtl8192c-common FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl8192ce/rtl8192ce.ko AUTOLOAD:=$(call AutoProbe,rtl8192ce) endef define KernelPackage/rtl8192ce/install $(INSTALL_DIR) $(1)/lib/firmware/rtlwifi $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rtlwifi/rtl8192cfw.bin $(1)/lib/firmware/rtlwifi $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rtlwifi/rtl8192cfwU.bin $(1)/lib/firmware/rtlwifi $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rtlwifi/rtl8192cfwU_B.bin $(1)/lib/firmware/rtlwifi endef define KernelPackage/rtl8192se $(call KernelPackage/mac80211/Default) TITLE:=Realtek RTL8192SE/RTL8191SE support DEPENDS+= +kmod-rtlwifi-pci FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl8192se/rtl8192se.ko AUTOLOAD:=$(call AutoProbe,rtl8192se) endef define KernelPackage/rtl8192se/install $(INSTALL_DIR) $(1)/lib/firmware/rtlwifi $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rtlwifi/rtl8192sefw.bin $(1)/lib/firmware/rtlwifi endef define KernelPackage/rtl8192de $(call KernelPackage/mac80211/Default) TITLE:=Realtek RTL8192DE/RTL8188DE support DEPENDS+= +kmod-rtlwifi-pci FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl8192de/rtl8192de.ko AUTOLOAD:=$(call AutoProbe,rtl8192de) endef define KernelPackage/rtl8192de/install $(INSTALL_DIR) $(1)/lib/firmware/rtlwifi $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rtlwifi/rtl8192defw.bin $(1)/lib/firmware/rtlwifi endef define KernelPackage/rtl8192cu $(call KernelPackage/mac80211/Default) TITLE:=Realtek RTL8192CU/RTL8188CU support DEPENDS+= +kmod-rtlwifi-usb +kmod-rtl8192c-common FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl8192cu/rtl8192cu.ko AUTOLOAD:=$(call AutoProbe,rtl8192cu) endef define KernelPackage/rtl8192cu/install $(INSTALL_DIR) $(1)/lib/firmware/rtlwifi $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rtlwifi/rtl8192cufw.bin $(1)/lib/firmware/rtlwifi $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rtlwifi/rtl8192cufw_A.bin $(1)/lib/firmware/rtlwifi $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rtlwifi/rtl8192cufw_B.bin $(1)/lib/firmware/rtlwifi $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rtlwifi/rtl8192cufw_TMSC.bin $(1)/lib/firmware/rtlwifi endef ZD1211FW_NAME:=zd1211-firmware ZD1211FW_VERSION:=1.4 define Download/zd1211rw FILE:=$(ZD1211FW_NAME)-$(ZD1211FW_VERSION).tar.bz2 URL:=@SF/zd1211/ MD5SUM:=19f28781d76569af8551c9d11294c870 endef $(eval $(call Download,zd1211rw)) define KernelPackage/zd1211rw $(call KernelPackage/mac80211/Default) TITLE:=Zydas ZD1211 support DEPENDS+= @USB_SUPPORT +kmod-usb-core +kmod-mac80211 FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/zd1211rw/zd1211rw.ko AUTOLOAD:=$(call AutoProbe,zd1211rw) endef define KernelPackage/adm8211 $(call KernelPackage/mac80211/Default) TITLE:=ADMTek 8211 support DEPENDS+=@PCI_SUPPORT +kmod-mac80211 +kmod-eeprom-93cx6 FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/adm8211.ko AUTOLOAD:=$(call AutoProbe,adm8211) endef define KernelPackage/ath/config if PACKAGE_kmod-ath config ATH_USER_REGD bool "Force Atheros drivers to respect the user's regdomain settings" help Atheros' idea of regulatory handling is that the EEPROM of the card defines the regulatory limits and the user is only allowed to restrict the settings even further, even if the country allows frequencies or power levels that are forbidden by the EEPROM settings. Select this option if you want the driver to respect the user's decision about regulatory settings. config PACKAGE_ATH_DEBUG bool "Atheros wireless debugging" help Say Y, if you want to debug atheros wireless drivers. Right now only ath9k makes use of this. config PACKAGE_ATH_DFS bool "Enable DFS support" default y help Dynamic frequency selection (DFS) is required for most of the 5 GHz band channels in Europe, US, and Japan. Select this option if you want to use such channels. endif endef define KernelPackage/ath $(call KernelPackage/mac80211/Default) TITLE:=Atheros common driver part DEPENDS+= @PCI_SUPPORT||USB_SUPPORT||TARGET_ar71xx||TARGET_atheros +kmod-mac80211 FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath.ko MENU:=1 endef define KernelPackage/ath/description This module contains some common parts needed by Atheros Wireless drivers. endef define KernelPackage/ath5k $(call KernelPackage/mac80211/Default) TITLE:=Atheros 5xxx wireless cards support URL:=http://linuxwireless.org/en/users/Drivers/ath5k DEPENDS+= @PCI_SUPPORT||@TARGET_atheros +kmod-ath FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath5k/ath5k.ko AUTOLOAD:=$(call AutoProbe,ath5k) endef define KernelPackage/ath5k/description This module adds support for wireless adapters based on Atheros 5xxx chipset. endef define KernelPackage/ath9k-common $(call KernelPackage/mac80211/Default) TITLE:=Atheros 802.11n wireless devices (common code for ath9k and ath9k_htc) URL:=http://linuxwireless.org/en/users/Drivers/ath9k DEPENDS+= @PCI_SUPPORT||USB_SUPPORT||TARGET_ar71xx +kmod-ath +@DRIVER_11N_SUPPORT FILES:= \ $(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath9k/ath9k_common.ko \ $(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath9k/ath9k_hw.ko endef define KernelPackage/ath9k $(call KernelPackage/mac80211/Default) TITLE:=Atheros 802.11n PCI wireless cards support URL:=http://linuxwireless.org/en/users/Drivers/ath9k DEPENDS+= @PCI_SUPPORT||TARGET_ar71xx +kmod-ath9k-common FILES:= \ $(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath9k/ath9k.ko AUTOLOAD:=$(call AutoProbe,ath9k) endef define KernelPackage/ath9k/description This module adds support for wireless adapters based on Atheros IEEE 802.11n AR5008 and AR9001 family of chipsets. endef define KernelPackage/ath9k/config config ATH9K_SUPPORT_PCOEM bool "Support chips used in PC OEM cards" depends on PACKAGE_kmod-ath9k endef define KernelPackage/ath9k-htc $(call KernelPackage/mac80211/Default) TITLE:=Atheros 802.11n USB device support URL:=http://linuxwireless.org/en/users/Drivers/ath9k DEPENDS+= @USB_SUPPORT +kmod-ath9k-common +kmod-usb-core FILES:= \ $(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath9k/ath9k_htc.ko AUTOLOAD:=$(call AutoProbe,ath9k_htc) endef define KernelPackage/ath9k-htc/description This module adds support for wireless adapters based on Atheros USB AR9271 and AR7010 family of chipsets. endef define KernelPackage/ath10k $(call KernelPackage/mac80211/Default) TITLE:=Atheros 802.11ac wireless cards support URL:=http://wireless.kernel.org/en/users/Drivers/ath10k DEPENDS+= @PCI_SUPPORT +kmod-ath +@DRIVER_11N_SUPPORT FILES:= \ $(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath10k/ath10k_core.ko \ $(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath10k/ath10k_pci.ko AUTOLOAD:=$(call AutoLoad,55,ath10k_core ath10k_pci) endef define KernelPackage/ath10k/description This module adds support for wireless adapters based on Atheros IEEE 802.11ac family of chipsets. For now only PCI is supported. endef define KernelPackage/ath10k/config if PACKAGE_kmod-ath10k config ATH10K_STA_FW bool "Firmware optimized for STA operation" default n help Use the ath10k firmware optimized for wireless client instead of access point operation. endif endef define KernelPackage/carl9170 $(call KernelPackage/mac80211/Default) TITLE:=Driver for Atheros AR9170 USB sticks DEPENDS:=@USB_SUPPORT +kmod-mac80211 +kmod-ath +kmod-usb-core +kmod-input-core +@DRIVER_11N_SUPPORT FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ath/carl9170/carl9170.ko AUTOLOAD:=$(call AutoProbe,carl9170) endef define KernelPackage/lib80211 $(call KernelPackage/mac80211/Default) TITLE:=802.11 Networking stack DEPENDS:=+kmod-cfg80211 FILES:= \ $(PKG_BUILD_DIR)/net/wireless/lib80211.ko \ $(PKG_BUILD_DIR)/net/wireless/lib80211_crypt_wep.ko \ $(PKG_BUILD_DIR)/net/wireless/lib80211_crypt_ccmp.ko \ $(PKG_BUILD_DIR)/net/wireless/lib80211_crypt_tkip.ko AUTOLOAD:=$(call AutoProbe, \ lib80211 \ lib80211_crypt_wep \ lib80211_crypt_ccmp \ lib80211_crypt_tkip \ ) endef define KernelPackage/lib80211/description Kernel modules for 802.11 Networking stack Includes: - lib80211 - lib80211_crypt_wep - lib80211_crypt_tkip - lib80211_crytp_ccmp endef define KernelPackage/libertas-usb $(call KernelPackage/mac80211/Default) DEPENDS+= @USB_SUPPORT +kmod-cfg80211 +kmod-usb-core +kmod-lib80211 +@DRIVER_WEXT_SUPPORT TITLE:=Marvell 88W8015 Wireless Driver FILES:= \ $(PKG_BUILD_DIR)/drivers/net/wireless/libertas/libertas.ko \ $(PKG_BUILD_DIR)/drivers/net/wireless/libertas/usb8xxx.ko AUTOLOAD:=$(call AutoProbe,libertas usb8xxx) endef define KernelPackage/libertas-sd $(call KernelPackage/mac80211/Default) DEPENDS+= +kmod-cfg80211 +kmod-lib80211 +kmod-mmc +@DRIVER_WEXT_SUPPORT @!TARGET_uml TITLE:=Marvell 88W8686 Wireless Driver FILES:= \ $(PKG_BUILD_DIR)/drivers/net/wireless/libertas/libertas.ko \ $(PKG_BUILD_DIR)/drivers/net/wireless/libertas/libertas_sdio.ko AUTOLOAD:=$(call AutoProbe,libertas libertas_sdio) endef define KernelPackage/mac80211-hwsim $(call KernelPackage/mac80211/Default) TITLE:=mac80211 HW simulation device DEPENDS+= +kmod-mac80211 +@DRIVER_11N_SUPPORT FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/mac80211_hwsim.ko AUTOLOAD:=$(call AutoProbe,mac80211_hwsim) endef define KernelPackage/net-libipw $(call KernelPackage/mac80211/Default) TITLE:=libipw for ipw2100 and ipw2200 DEPENDS:=@PCI_SUPPORT +kmod-crypto-core +kmod-crypto-arc4 +kmod-crypto-aes +kmod-crypto-michael-mic +kmod-lib80211 +kmod-cfg80211 +@DRIVER_WEXT_SUPPORT FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ipw2x00/libipw.ko AUTOLOAD:=$(call AutoProbe,libipw) endef define KernelPackage/net-libipw/description Hardware independent IEEE 802.11 networking stack for ipw2100 and ipw2200. endef IPW2100_NAME:=ipw2100-fw IPW2100_VERSION:=1.3 define Download/net-ipw2100 URL:=http://bughost.org/firmware/ FILE:=$(IPW2100_NAME)-$(IPW2100_VERSION).tgz MD5SUM=46aa75bcda1a00efa841f9707bbbd113 endef $(eval $(call Download,net-ipw2100)) define KernelPackage/net-ipw2100 $(call KernelPackage/mac80211/Default) TITLE:=Intel IPW2100 driver DEPENDS:=@PCI_SUPPORT +kmod-net-libipw FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ipw2x00/ipw2100.ko AUTOLOAD:=$(call AutoProbe,ipw2100) endef define KernelPackage/net-ipw2100/description Kernel support for Intel IPW2100 Includes: - ipw2100 endef IPW2200_NAME:=ipw2200-fw IPW2200_VERSION:=3.1 define Download/net-ipw2200 URL:=http://bughost.org/firmware/ FILE:=$(IPW2200_NAME)-$(IPW2200_VERSION).tgz MD5SUM=eaba788643c7cc7483dd67ace70f6e99 endef $(eval $(call Download,net-ipw2200)) define KernelPackage/net-ipw2200 $(call KernelPackage/mac80211/Default) TITLE:=Intel IPW2200 driver DEPENDS:=@PCI_SUPPORT +kmod-net-libipw FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ipw2x00/ipw2200.ko AUTOLOAD:=$(call AutoProbe,ipw2200) endef define KernelPackage/net-ipw2200/description Kernel support for Intel IPW2200 Includes: - ipw2200 endef define KernelPackage/net-hermes $(call KernelPackage/mac80211/Default) TITLE:=Hermes 802.11b chipset support DEPENDS:=@PCI_SUPPORT||PCMCIA_SUPPORT +kmod-cfg80211 +@DRIVER_WEXT_SUPPORT FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/orinoco/orinoco.ko AUTOLOAD:=$(call AutoProbe,orinoco) endef define KernelPackage/net-hermes/description Kernel support for Hermes 802.11b chipsets endef define KernelPackage/net-hermes-pci $(call KernelPackage/mac80211/Default) TITLE:=Intersil Prism 2.5 PCI support DEPENDS:=@PCI_SUPPORT +kmod-net-hermes FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/orinoco/orinoco_pci.ko AUTOLOAD:=$(call AutoProbe,orinoco_pci) endef define KernelPackage/net-hermes-pci/description Kernel modules for Intersil Prism 2.5 PCI support endef define KernelPackage/net-hermes-plx $(call KernelPackage/mac80211/Default) TITLE:=PLX9052 based PCI adaptor DEPENDS:=@PCI_SUPPORT +kmod-net-hermes FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/orinoco/orinoco_plx.ko AUTOLOAD:=$(call AutoProbe,orinoco_plx) endef define KernelPackage/net-hermes-plx/description Kernel modules for Hermes in PLX9052 based PCI adaptors endef define KernelPackage/net-hermes-pcmcia $(call KernelPackage/mac80211/Default) TITLE:=Hermes based PCMCIA adaptors DEPENDS:=@PCMCIA_SUPPORT +kmod-net-hermes @BROKEN FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/orinoco/orinoco_cs.ko AUTOLOAD:=$(call AutoProbe,orinoco_cs) endef define KernelPackage/net-hermes-pcmcia/description Kernel modules for Hermes based PCMCIA adaptors endef define KernelPackage/iwlagn $(call KernelPackage/mac80211/Default) DEPENDS:= +kmod-mac80211 @PCI_SUPPORT +@DRIVER_11N_SUPPORT TITLE:=Intel AGN Wireless support FILES:= \ $(PKG_BUILD_DIR)/drivers/net/wireless/iwlwifi/iwlwifi.ko \ $(PKG_BUILD_DIR)/drivers/net/wireless/iwlwifi/dvm/iwldvm.ko AUTOLOAD:=$(call AutoProbe,iwlwifi iwldvm) MENU:=1 endef define KernelPackage/iwlagn/description iwlagn kernel module for Intel 5000/5150/1000/6000/6050/6005/6030/100 support endef define KernelPackage/iwlagn/config if PACKAGE_kmod-iwlagn config IWL5000_FW bool "Intel 5000 Firmware" default y help Download and install firmware for: Intel Wireless WiFi 5100AGN, 5300AGN, and 5350AGN config IWL5150_FW bool "Intel 5150 Firmware" default y help Download and install firmware for: Intel Wireless WiFi 5150AGN config IWL1000_FW bool "Intel 1000 Firmware" default y help Download and install firmware for: Intel Centrino Wireless-N 1000 config IWL6000_FW bool "Intel 6000 Firmware" default y help Download and install firmware for: Intel Centrino Ultimate-N 6300 and Advanced-N 6200 config IWL6050_FW bool "Intel 6050 Firmware" default y help Download and install firmware for: Intel Centrino Advanced-N + WiMAX 6250 and Wireless-N + WiMAX 6150 config IWL6005_FW bool "Intel 6005 Firmware" default y help Download and install firmware for: Intel Centrino Advanced-N 6205 config IWL6030_FW bool "Intel 6030 Firmware" default y help Download and install firmware for: Intel Centrino Advanced-N 6230, Wireless-N 1030, Wireless-N 130 and Advanced-N 6235 config IWL7260_FW bool "Intel 7260 Firmware" default y help Download and install firmware for: Intel Dual Band Wireless-N 7260 and Intel Dual Band Wireless-AC 7260 config IWL7265_FW bool "Intel 7265 Firmware" default y help Download and install firmware for: Intel Wireless 7265 config IWL100_FW bool "Intel 100 Firmware" default y help Download and install firmware for: Intel Centrino Wireless-N 100 config IWL2000_FW bool "Intel 2000 Firmware" default y help Download and install firmware for: Intel Centrino Wireless-N 2200 config IWL2030_FW bool "Intel 2030 Firmware" default y help Download and install firmware for: Intel Centrino Wireless-N 2230 config IWL105_FW bool "Intel 105 Firmware" default y help Download and install firmware for: Intel Centrino Wireless-N 105 config IWL135_FW bool "Intel 135 Firmware" default y help Download and install firmware for: Intel Centrino Wireless-N 135 config IWL3160_FW bool "Intel 3160 Firmware" default y help Download and install firmware for: Intel Wireless 3160 endif endef define KernelPackage/iwl-legacy $(call KernelPackage/mac80211/Default) DEPENDS:= +kmod-mac80211 @PCI_SUPPORT TITLE:=Intel legacy Wireless support FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/iwlegacy/iwlegacy.ko AUTOLOAD:=$(call AutoProbe,iwlegacy) endef define KernelPackage/iwl-legacy/description iwl-legacy kernel module for legacy Intel wireless support endef define KernelPackage/iwl3945 $(call KernelPackage/mac80211/Default) DEPENDS:= +kmod-mac80211 +kmod-iwl-legacy TITLE:=Intel iwl3945 Wireless support FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/iwlegacy/iwl3945.ko AUTOLOAD:=$(call AutoProbe,iwl3945) endef define KernelPackage/iwl3945/description iwl3945 kernel module for Intel 3945 support endef define KernelPackage/iwl4965 $(call KernelPackage/mac80211/Default) DEPENDS:= +kmod-mac80211 +kmod-iwl-legacy +@DRIVER_11N_SUPPORT TITLE:=Intel iwl4965 Wireless support FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/iwlegacy/iwl4965.ko AUTOLOAD:=$(call AutoProbe,iwl4965) endef define KernelPackage/iwl4965/description iwl4965 kernel module for Intel 4965 support endef define KernelPackage/mwl8k $(call KernelPackage/mac80211/Default) TITLE:=Driver for Marvell TOPDOG 802.11 Wireless cards URL:=http://wireless.kernel.org/en/users/Drivers/mwl8k DEPENDS+= @PCI_SUPPORT +kmod-mac80211 +@DRIVER_11N_SUPPORT FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/mwl8k.ko AUTOLOAD:=$(call AutoProbe,mwl8k) endef define KernelPackage/mwl8k/description Kernel modules for Marvell TOPDOG 802.11 Wireless cards endef define KernelPackage/mwifiex-pcie $(call KernelPackage/mac80211/Default) TITLE:=Driver for Marvell 802.11n/802.11ac PCIe Wireless cards URL:=http://wireless.kernel.org/en/users/Drivers/mwifiex DEPENDS+= @PCI_SUPPORT +kmod-mac80211 +@DRIVER_11N_SUPPORT FILES:= \ $(PKG_BUILD_DIR)/drivers/net/wireless/mwifiex/mwifiex.ko \ $(PKG_BUILD_DIR)/drivers/net/wireless/mwifiex/mwifiex_pcie.ko AUTOLOAD:=$(call AutoProbe,mwifiex_pcie) endef define KernelPackage/mwifiex-pcie/description Kernel modules for Marvell 802.11n/802.11ac PCIe Wireless cards endef define KernelPackage/wlcore $(call KernelPackage/mac80211/Default) TITLE:=TI common driver part DEPENDS+= @TARGET_omap +kmod-mac80211 +@DRIVER_11N_SUPPORT FILES:= \ $(PKG_BUILD_DIR)/drivers/net/wireless/ti/wlcore/wlcore.ko \ $(PKG_BUILD_DIR)/drivers/net/wireless/ti/wlcore/wlcore_sdio.ko AUTOLOAD:=$(call AutoProbe,wlcore wlcore_sdio) endef define KernelPackage/wlcore/description This module contains some common parts needed by TI Wireless drivers. endef define KernelPackage/wl12xx $(call KernelPackage/mac80211/Default) TITLE:=Driver for TI WL12xx URL:=http://wireless.kernel.org/en/users/Drivers/wl12xx DEPENDS+= +kmod-wlcore FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ti/wl12xx/wl12xx.ko AUTOLOAD:=$(call AutoProbe,wl12xx) endef define KernelPackage/wl12xx/description Kernel modules for TI WL12xx endef define KernelPackage/wl18xx $(call KernelPackage/mac80211/Default) TITLE:=Driver for TI WL18xx URL:=http://wireless.kernel.org/en/users/Drivers/wl18xx DEPENDS+= +kmod-wlcore FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ti/wl18xx/wl18xx.ko AUTOLOAD:=$(call AutoProbe,wl18xx) endef define KernelPackage/wl18xx/description Kernel modules for TI WL18xx endef #Broadcom firmware ifneq ($(CONFIG_B43_FW_6_30),) PKG_B43_FWV4_NAME:=broadcom-wl PKG_B43_FWV4_VERSION:=6.30.163.46 PKG_B43_FWV4_OBJECT:=$(PKG_B43_FWV4_NAME)-$(PKG_B43_FWV4_VERSION).wl_apsta.o PKG_B43_FWV4_SOURCE:=$(PKG_B43_FWV4_NAME)-$(PKG_B43_FWV4_VERSION).tar.bz2 PKG_B43_FWV4_SOURCE_URL:=http://www.lwfinger.com/b43-firmware/ PKG_B43_FWV4_MD5SUM:=6fe97e9368d25342a1ab943d3cf3496d else ifneq ($(CONFIG_B43_FW_5_10),) PKG_B43_FWV4_NAME:=broadcom-wl PKG_B43_FWV4_VERSION:=5.10.56.27.3 PKG_B43_FWV4_OBJECT:=$(PKG_B43_FWV4_NAME)-$(PKG_B43_FWV4_VERSION)/driver/wl_apsta/wl_prebuilt.o PKG_B43_FWV4_SOURCE:=$(PKG_B43_FWV4_NAME)-$(PKG_B43_FWV4_VERSION)_mipsel.tar.bz2 PKG_B43_FWV4_SOURCE_URL:=http://mirror2.openwrt.org/sources/ PKG_B43_FWV4_MD5SUM:=3363e3a6b3d9d73c49dea870c7834eac else ifneq ($(CONFIG_B43_FW_4_178),) PKG_B43_FWV4_NAME:=broadcom-wl PKG_B43_FWV4_VERSION:=4.178.10.4 PKG_B43_FWV4_OBJECT:=$(PKG_B43_FWV4_NAME)-$(PKG_B43_FWV4_VERSION)/linux/wl_apsta.o PKG_B43_FWV4_SOURCE:=$(PKG_B43_FWV4_NAME)-$(PKG_B43_FWV4_VERSION).tar.bz2 PKG_B43_FWV4_SOURCE_URL:=http://mirror2.openwrt.org/sources/ PKG_B43_FWV4_MD5SUM:=14477e8cbbb91b11896affac9b219fdb else ifneq ($(CONFIG_B43_FW_5_100_138),) PKG_B43_FWV4_NAME:=broadcom-wl PKG_B43_FWV4_VERSION:=5.100.138 PKG_B43_FWV4_OBJECT:=$(PKG_B43_FWV4_NAME)-$(PKG_B43_FWV4_VERSION)/linux/wl_apsta.o PKG_B43_FWV4_SOURCE:=$(PKG_B43_FWV4_NAME)-$(PKG_B43_FWV4_VERSION).tar.bz2 PKG_B43_FWV4_SOURCE_URL:=http://www.lwfinger.com/b43-firmware/ PKG_B43_FWV4_MD5SUM:=f4e357b09eaf5d8b1f1920cf3493a555 else PKG_B43_FWV4_NAME:=broadcom-wl PKG_B43_FWV4_VERSION:=4.150.10.5 PKG_B43_FWV4_OBJECT:=$(PKG_B43_FWV4_NAME)-$(PKG_B43_FWV4_VERSION)/driver/wl_apsta_mimo.o PKG_B43_FWV4_SOURCE:=$(PKG_B43_FWV4_NAME)-$(PKG_B43_FWV4_VERSION).tar.bz2 PKG_B43_FWV4_SOURCE_URL:=http://mirror2.openwrt.org/sources/ PKG_B43_FWV4_MD5SUM:=0c6ba9687114c6b598e8019e262d9a60 endif endif endif endif ifneq ($(CONFIG_B43_OPENFIRMWARE),) PKG_B43_FWV4_NAME:=broadcom-wl PKG_B43_FWV4_VERSION:=5.2 PKG_B43_FWV4_OBJECT:=openfwwf-$(PKG_B43_FWV4_VERSION) PKG_B43_FWV4_SOURCE:=openfwwf-$(PKG_B43_FWV4_VERSION).tar.gz PKG_B43_FWV4_SOURCE_URL:=http://www.ing.unibs.it/openfwwf/firmware/ PKG_B43_FWV4_MD5SUM:=e045a135453274e439ae183f8498b0fa endif PKG_B43_FWV3_NAME:=wl_apsta PKG_B43_FWV3_VERSION:=3.130.20.0 PKG_B43_FWV3_SOURCE:=$(PKG_B43_FWV3_NAME)-$(PKG_B43_FWV3_VERSION).o PKG_B43_FWV3_SOURCE_URL:=http://downloads.openwrt.org/sources/ PKG_B43_FWV3_MD5SUM:=e08665c5c5b66beb9c3b2dd54aa80cb3 define Download/b43 FILE:=$(PKG_B43_FWV4_SOURCE) URL:=$(PKG_B43_FWV4_SOURCE_URL) MD5SUM:=$(PKG_B43_FWV4_MD5SUM) endef $(eval $(call Download,b43)) define Download/b43legacy FILE:=$(PKG_B43_FWV3_SOURCE) URL:=$(PKG_B43_FWV3_SOURCE_URL) MD5SUM:=$(PKG_B43_FWV3_MD5SUM) endef $(eval $(call Download,b43legacy)) define KernelPackage/b43 $(call KernelPackage/mac80211/Default) TITLE:=Broadcom 43xx wireless support URL:=http://linuxwireless.org/en/users/Drivers/b43 KCONFIG:= \ CONFIG_HW_RANDOM=y # Depend on PCI_SUPPORT to make sure we can select kmod-bcma or kmod-ssb DEPENDS += \ @PCI_SUPPORT +kmod-mac80211 \ $(if $(CONFIG_PACKAGE_B43_USE_SSB),+kmod-ssb) \ $(if $(CONFIG_PACKAGE_B43_USE_BCMA),+kmod-bcma) FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/b43/b43.ko AUTOLOAD:=$(call AutoProbe,b43) MENU:=1 endef define KernelPackage/b43/config config PACKAGE_B43_USE_SSB select PACKAGE_kmod-ssb tristate depends on !TARGET_brcm47xx && !TARGET_brcm63xx default PACKAGE_kmod-b43 if PACKAGE_B43_BUSES_BCMA_AND_SSB default PACKAGE_kmod-b43 if PACKAGE_B43_BUSES_SSB config PACKAGE_B43_USE_BCMA select PACKAGE_kmod-bcma tristate depends on !TARGET_brcm47xx default PACKAGE_kmod-b43 if PACKAGE_B43_BUSES_BCMA_AND_SSB default PACKAGE_kmod-b43 if PACKAGE_B43_BUSES_BCMA if PACKAGE_kmod-b43 choice prompt "b43 firmware version" default B43_FW_5_100_138 help This option allows you to select the version of the b43 firmware. config B43_FW_4_150 bool "Firmware 410.2160 from driver 4.150.10.5 (old stable)" help Old stable firmware for BCM43xx devices. If unsure, select this. config B43_FW_4_178 bool "Firmware 478.104 from driver 4.178.10.4" help Older firmware for BCM43xx devices. If unsure, select the "stable" firmware. config B43_FW_5_10 bool "Firmware 508.1084 from driver 5.10.56.27" help Older firmware for BCM43xx devices. If unsure, select the "stable" firmware. config B43_FW_5_100_138 bool "Firmware 666.2 from driver 5.100.138 (stable)" help The currently default firmware for BCM43xx devices. This firmware currently gets most of the testing and is needed for some N-PHY devices. If unsure, select the this firmware. config B43_FW_6_30 bool "Firmware 784.2 from driver 6.30.163.46 (experimental)" help Newer experimental firmware for BCM43xx devices. This firmware is mostly untested. If unsure, select the "stable" firmware. config B43_OPENFIRMWARE bool "Open FirmWare for WiFi networks" help Opensource firmware for BCM43xx devices. Do _not_ select this, unless you know what you are doing. The Opensource firmware is not suitable for embedded devices, yet. It does not support QoS, which is bad for AccessPoints. It does not support hardware crypto acceleration, which is a showstopper for embedded devices with low CPU resources. If unsure, select the "stable" firmware. endchoice config B43_FW_SQUASH bool "Remove unnecessary firmware files" depends on !B43_OPENFIRMWARE default y help This options allows you to remove unnecessary b43 firmware files from the final rootfs image. This can reduce the rootfs size by up to 200k. If unsure, say Y. config B43_FW_SQUASH_COREREVS string "Core revisions to include" depends on B43_FW_SQUASH default "5,6,7,8,9,10,11,13,15" if TARGET_brcm47xx_legacy default "16,28,29,30" if TARGET_brcm47xx_mips74k default "5,6,7,8,9,10,11,13,15,16,28,29,30" help This is a comma seperated list of core revision numbers. Example (keep files for rev5 only): 5 Example (keep files for rev5 and rev11): 5,11 config B43_FW_SQUASH_PHYTYPES string "PHY types to include" depends on B43_FW_SQUASH default "G,LP" if TARGET_brcm47xx_legacy default "N,HT" if TARGET_brcm47xx_mips74k default "G,LP,N,HT" help This is a comma seperated list of PHY types: A => A-PHY AG => Dual A-PHY G-PHY G => G-PHY LP => LP-PHY N => N-PHY HT => HT-PHY LCN => LCN-PHY LCN40 => LCN40-PHY AC => AC-PHY Example (keep files for G-PHY only): G Example (keep files for G-PHY and N-PHY): G,N choice prompt "Supported buses" default PACKAGE_B43_BUSES_BCMA_AND_SSB help This allows choosing buses that b43 should support. config PACKAGE_B43_BUSES_BCMA_AND_SSB depends on !TARGET_brcm47xx_legacy && !TARGET_brcm47xx_mips74k bool "BCMA and SSB" config PACKAGE_B43_BUSES_BCMA depends on !TARGET_brcm47xx_legacy bool "BCMA only" config PACKAGE_B43_BUSES_SSB depends on !TARGET_brcm47xx_mips74k bool "SSB only" endchoice config PACKAGE_B43_DEBUG bool "Enable debug output and debugfs for b43" default n help Enable additional debug output and runtime sanity checks for b43 and enables the debugfs interface. If unsure, say N. config PACKAGE_B43_PIO bool "Enable support for PIO transfer mode" default n help Enable support for using PIO instead of DMA. Unless you have DMA transfer problems you don't need this. If unsure, say N. config PACKAGE_B43_PHY_G bool "Enable support for G-PHYs" default n if TARGET_brcm47xx_mips74k default y help Enable support for G-PHY. This includes support for the following devices: PCI: BCM4306, BCM4311, BCM4318 SoC: BCM5352E, BCM4712 If unsure, say Y. config PACKAGE_B43_PHY_N bool "Enable support for N-PHYs" default n if TARGET_brcm47xx_legacy default y help Enable support for N-PHY. This includes support for the following devices: PCI: BCM4321, BCM4322, BCM43222, BCM43224, BCM43225 SoC: BCM4716, BCM4717, BCM4718 Currently only 11g speed is available. If unsure, say Y. config PACKAGE_B43_PHY_LP bool "Enable support for LP-PHYs" default n if TARGET_brcm47xx_mips74k default y help Enable support for LP-PHY. This includes support for the following devices: PCI: BCM4312 SoC: BCM5354 If unsure, say Y. config PACKAGE_B43_PHY_HT bool "Enable support for HT-PHYs" default n if TARGET_brcm47xx_legacy default y help Enable support for HT-PHY. This includes support for the following devices: PCI: BCM4331 Currently only 11g speed is available. If unsure, say Y. config PACKAGE_B43_PHY_LCN bool "Enable support for LCN-PHYs" depends on BROKEN default n help Currently broken. If unsure, say N. endif endef define KernelPackage/b43/description Kernel module for Broadcom 43xx wireless support (mac80211 stack) new endef define KernelPackage/b43legacy $(call KernelPackage/mac80211/Default) TITLE:=Broadcom 43xx-legacy wireless support URL:=http://linuxwireless.org/en/users/Drivers/b43 KCONFIG:= \ CONFIG_HW_RANDOM=y DEPENDS+= +kmod-mac80211 +!(TARGET_brcm47xx||TARGET_brcm63xx):kmod-ssb FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/b43legacy/b43legacy.ko AUTOLOAD:=$(call AutoProbe,b43legacy) MENU:=1 endef define KernelPackage/b43legacy/config if PACKAGE_kmod-b43legacy config B43LEGACY_FW_SQUASH bool "Remove unnecessary firmware files" default y help This options allows you to remove unnecessary b43legacy firmware files from the final rootfs image. This can reduce the rootfs size by up to 50k. If unsure, say Y. config B43LEGACY_FW_SQUASH_COREREVS string "Core revisions to include" depends on B43LEGACY_FW_SQUASH default "1,2,3,4" help This is a comma seperated list of core revision numbers. Example (keep files for rev4 only): 4 Example (keep files for rev2 and rev4): 2,4 endif endef define KernelPackage/b43legacy/description Kernel module for Broadcom 43xx-legacy wireless support (mac80211 stack) new endef define KernelPackage/brcmutil $(call KernelPackage/mac80211/Default) TITLE:=Broadcom IEEE802.11n common driver parts URL:=http://linuxwireless.org/en/users/Drivers/brcm80211 DEPENDS+=@PCI_SUPPORT||USB_SUPPORT FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/brcm80211/brcmutil/brcmutil.ko AUTOLOAD:=$(call AutoProbe,brcmutil) MENU:=1 endef define KernelPackage/brcmutil/description This module contains some common parts needed by Broadcom Wireless drivers brcmsmac and brcmfmac. endef define KernelPackage/brcmutil/config if PACKAGE_kmod-brcmutil config PACKAGE_BRCM80211_DEBUG bool "Broadcom wireless driver debugging" help Say Y, if you want to debug brcmsmac and brcmfmac wireless driver. endif endef PKG_BRCMSMAC_FW_NAME:=broadcom-wl PKG_BRCMSMAC_FW_VERSION:=5.100.138 PKG_BRCMSMAC_FW_OBJECT:=$(PKG_BRCMSMAC_FW_NAME)-$(PKG_BRCMSMAC_FW_VERSION)/linux/wl_apsta.o PKG_BRCMSMAC_FW_SOURCE:=$(PKG_BRCMSMAC_FW_NAME)-$(PKG_BRCMSMAC_FW_VERSION).tar.bz2 PKG_BRCMSMAC_FW_SOURCE_URL:=http://www.lwfinger.com/b43-firmware/ PKG_BRCMSMAC_FW_MD5SUM:=f4e357b09eaf5d8b1f1920cf3493a555 define Download/brcmsmac FILE:=$(PKG_BRCMSMAC_FW_SOURCE) URL:=$(PKG_BRCMSMAC_FW_SOURCE_URL) MD5SUM:=$(PKG_BRCMSMAC_FW_MD5SUM) endef $(eval $(call Download,brcmsmac)) define KernelPackage/brcmsmac $(call KernelPackage/mac80211/Default) TITLE:=Broadcom IEEE802.11n PCIe SoftMAC WLAN driver URL:=http://linuxwireless.org/en/users/Drivers/brcm80211 DEPENDS+= +kmod-mac80211 +@DRIVER_11N_SUPPORT +!TARGET_brcm47xx:kmod-bcma +kmod-lib-cordic +kmod-lib-crc8 +kmod-brcmutil FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/brcm80211/brcmsmac/brcmsmac.ko AUTOLOAD:=$(call AutoProbe,brcmsmac) MENU:=1 endef define KernelPackage/brcmsmac/description Kernel module for Broadcom IEEE802.11n PCIe Wireless cards endef define KernelPackage/brcmsmac/config if PACKAGE_kmod-brcmsmac config BRCMSMAC_USE_FW_FROM_WL bool "Use firmware extracted from broadcom proprietary driver" default y help Instead of using the official brcmsmac firmware a firmware version 666.2 extracted from the proprietary Broadcom driver is used. This is needed to get core rev 17 used in bcm4716 to work. If unsure, say Y. endif endef define KernelPackage/brcmfmac $(call KernelPackage/mac80211/Default) TITLE:=Broadcom IEEE802.11n USB FullMAC WLAN driver URL:=http://linuxwireless.org/en/users/Drivers/brcm80211 DEPENDS+= @USB_SUPPORT +kmod-usb-core +kmod-cfg80211 +@DRIVER_11N_SUPPORT +kmod-brcmutil FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/brcm80211/brcmfmac/brcmfmac.ko AUTOLOAD:=$(call AutoProbe,brcmfmac) endef define KernelPackage/brcmfmac/description Kernel module for Broadcom IEEE802.11n USB Wireless cards endef config_package=$(if $(CONFIG_PACKAGE_kmod-$(1)),m) config-y:= \ WLAN \ NL80211_TESTMODE \ CFG80211_WEXT \ CFG80211_INTERNAL_REGDB \ CFG80211_CERTIFICATION_ONUS \ MAC80211_RC_MINSTREL \ MAC80211_RC_MINSTREL_HT \ MAC80211_RC_MINSTREL_VHT \ MAC80211_RC_DEFAULT_MINSTREL \ config-$(call config_package,cfg80211) += CFG80211 config-$(call config_package,mac80211) += MAC80211 config-$(CONFIG_PACKAGE_MAC80211_MESH) += MAC80211_MESH ifdef CONFIG_PACKAGE_MAC80211_DEBUGFS config-y += \ CFG80211_DEBUGFS \ MAC80211_DEBUGFS \ ATH9K_DEBUGFS \ ATH9K_HTC_DEBUGFS \ ATH10K_DEBUGFS \ CARL9170_DEBUGFS \ ATH5K_DEBUG endif config-$(call config_package,lib80211) += LIB80211 LIB80211_CRYPT_WEP LIB80211_CRYPT_CCMP LIB80211_CRYPT_TKIP config-$(call config_package,ath) += ATH_CARDS ATH_COMMON config-$(CONFIG_PACKAGE_ATH_DEBUG) += ATH_DEBUG ATH10K_DEBUG config-$(CONFIG_PACKAGE_ATH_DFS) += ATH9K_DFS_CERTIFIED ATH10K_DFS_CERTIFIED config-$(call config_package,ath9k) += ATH9K config-$(call config_package,ath9k-common) += ATH9K_COMMON config-$(CONFIG_TARGET_ar71xx) += ATH9K_AHB config-$(CONFIG_PCI) += ATH9K_PCI config-$(CONFIG_ATH_USER_REGD) += ATH_USER_REGD config-$(CONFIG_ATH9K_SUPPORT_PCOEM) += ATH9K_PCOEM config-$(call config_package,ath9k-htc) += ATH9K_HTC config-$(call config_package,ath10k) += ATH10K ATH10K_PCI config-$(call config_package,ath5k) += ATH5K ifdef CONFIG_TARGET_atheros config-y += ATH5K_AHB else config-y += ATH5K_PCI endif config-$(call config_package,carl9170) += CARL9170 config-$(call config_package,b43) += B43 config-$(CONFIG_PACKAGE_B43_BUSES_BCMA_AND_SSB) += B43_BUSES_BCMA_AND_SSB config-$(CONFIG_PACKAGE_B43_BUSES_BCMA) += B43_BUSES_BCMA config-$(CONFIG_PACKAGE_B43_BUSES_SSB) += B43_BUSES_SSB config-$(CONFIG_PACKAGE_B43_PHY_G) += B43_PHY_G config-$(CONFIG_PACKAGE_B43_PHY_N) += B43_PHY_N config-$(CONFIG_PACKAGE_B43_PHY_LP) += B43_PHY_LP config-$(CONFIG_PACKAGE_B43_PHY_HT) += B43_PHY_HT config-$(CONFIG_PACKAGE_B43_PIO) += B43_PIO config-$(CONFIG_PACKAGE_B43_DEBUG) += B43_DEBUG config-$(call config_package,b43legacy) += B43LEGACY config-y += B43LEGACY_DMA_MODE config-$(call config_package,brcmutil) += BRCMUTIL config-$(call config_package,brcmsmac) += BRCMSMAC config-$(call config_package,brcmfmac) += BRCMFMAC config-y += BRCMFMAC_USB config-$(CONFIG_PACKAGE_BRCM80211_DEBUG) += BRCMDBG config-$(call config_package,mac80211-hwsim) += MAC80211_HWSIM config-$(call config_package,rt2x00-lib) += RT2X00 RT2X00_LIB config-$(call config_package,rt2x00-pci) += RT2X00_LIB_PCI config-$(call config_package,rt2x00-mmio) += RT2X00_LIB_MMIO config-$(call config_package,rt2x00-usb) += RT2X00_LIB_USB config-$(CONFIG_PACKAGE_RT2X00_LIB_DEBUGFS) += RT2X00_LIB_DEBUGFS config-$(CONFIG_PACKAGE_RT2X00_DEBUG) += RT2X00_DEBUG config-$(call config_package,rt2400-pci) += RT2400PCI config-$(call config_package,rt2500-pci) += RT2500PCI config-$(call config_package,rt2500-usb) += RT2500USB config-$(call config_package,rt61-pci) += RT61PCI config-$(call config_package,rt73-usb) += RT73USB config-$(call config_package,rt2800-lib) += RT2800_LIB config-$(call config_package,rt2800-soc) += RT2800SOC config-$(call config_package,rt2800-pci) += RT2800PCI config-y += RT2800PCI_RT33XX RT2800PCI_RT35XX RT2800PCI_RT53XX RT2800PCI_RT3290 config-$(call config_package,rt2800-usb) += RT2800USB config-y += RT2800USB_RT33XX RT2800USB_RT35XX RT2800USB_RT3573 RT2800USB_RT53XX RT2800USB_RT55XX config-$(call config_package,iwl-legacy) += IWLEGACY config-$(call config_package,iwl3945) += IWL3945 config-$(call config_package,iwl4965) += IWL4965 config-$(call config_package,iwlagn) += IWLWIFI IWLDVM config-$(call config_package,net-libipw) += LIBIPW config-$(call config_package,net-ipw2100) += IPW2100 config-$(call config_package,net-ipw2200) += IPW2200 config-$(call config_package,p54-common) += P54_COMMON config-$(call config_package,p54-pci) += P54_PCI config-$(call config_package,p54-usb) += P54_USB config-$(call config_package,p54-spi) += P54_SPI config-$(call config_package,net-hermes) += HERMES config-$(call config_package,net-hermes-pci) += PCI_HERMES config-$(call config_package,net-hermes-plx) += PLX_HERMES config-$(call config_package,net-hermes-pcmcia) += PCMCIA_HERMES config-y += HERMES_PRISM config-$(call config_package,adm8211) += ADM8211 config-$(call config_package,libertas-sd) += LIBERTAS LIBERTAS_SDIO config-$(call config_package,libertas-usb) += LIBERTAS LIBERTAS_USB config-$(call config_package,mwl8k) += MWL8K config-$(call config_package,mwifiex-pcie) += MWIFIEX MWIFIEX_PCIE config-$(call config_package,rtl8180) += RTL8180 config-$(call config_package,rtl8187) += RTL8187 config-$(call config_package,wlcore) += WLCORE WLCORE_SDIO config-$(call config_package,wl12xx) += WL12XX config-$(call config_package,wl18xx) += WL18XX config-y += WL_TI WILINK_PLATFORM_DATA config-$(call config_package,zd1211rw) += ZD1211RW config-$(call config_package,rtlwifi) += RTL_CARDS RTLWIFI config-$(call config_package,rtlwifi-pci) += RTLWIFI_PCI config-$(call config_package,rtlwifi-usb) += RTLWIFI_USB config-$(call config_package,rtl8192c-common) += RTL8192C_COMMON config-$(call config_package,rtl8192ce) += RTL8192CE config-$(call config_package,rtl8192se) += RTL8192SE config-$(call config_package,rtl8192de) += RTL8192DE config-$(call config_package,rtl8192cu) += RTL8192CU config-$(CONFIG_PACKAGE_RTLWIFI_DEBUG) += RTLWIFI_DEBUG config-$(CONFIG_LEDS_TRIGGERS) += MAC80211_LEDS B43_LEDS B43LEGACY_LEDS MAKE_OPTS:= -C "$(PKG_BUILD_DIR)" \ CROSS_COMPILE="$(KERNEL_CROSS)" \ ARCH="$(LINUX_KARCH)" \ EXTRA_CFLAGS="-I$(PKG_BUILD_DIR)/include" \ KLIB_BUILD="$(LINUX_DIR)" \ MODPROBE=true \ KLIB=$(TARGET_MODULES_DIR) \ KERNEL_SUBLEVEL=$(lastword $(subst ., ,$(KERNEL_PATCHVER))) \ KBUILD_LDFLAGS_MODULE_PREREQ= ifneq ($(findstring c,$(OPENWRT_VERBOSE)),) MAKE_OPTS += V=1 endif define ConfigVars $(subst $(space),,$(foreach opt,$(config-$(1)),CPTCFG_$(opt)=$(1) )) endef define mac80211_config $(call ConfigVars,m)$(call ConfigVars,y) endef $(eval $(call shexport,mac80211_config)) define Build/Prepare rm -rf $(PKG_BUILD_DIR) mkdir -p $(PKG_BUILD_DIR) $(PKG_UNPACK) $(Build/Patch) $(TAR) -C $(PKG_BUILD_DIR) -xzf $(DL_DIR)/$(IPW2100_NAME)-$(IPW2100_VERSION).tgz $(TAR) -C $(PKG_BUILD_DIR) -xzf $(DL_DIR)/$(IPW2200_NAME)-$(IPW2200_VERSION).tgz $(TAR) -C $(PKG_BUILD_DIR) -xjf $(DL_DIR)/$(ZD1211FW_NAME)-$(ZD1211FW_VERSION).tar.bz2 $(TAR) -C $(PKG_BUILD_DIR) -xjf $(DL_DIR)/$(PKG_LINUX_FIRMWARE_SOURCE) $(TAR) -C $(PKG_BUILD_DIR) -xjf $(DL_DIR)/$(PKG_ATH10K_LINUX_FIRMWARE_SOURCE) rm -rf \ $(PKG_BUILD_DIR)/include/linux/ssb \ $(PKG_BUILD_DIR)/include/linux/bcma \ $(PKG_BUILD_DIR)/include/net/bluetooth rm -f \ $(PKG_BUILD_DIR)/include/linux/cordic.h \ $(PKG_BUILD_DIR)/include/linux/crc8.h \ $(PKG_BUILD_DIR)/include/linux/eeprom_93cx6.h \ $(PKG_BUILD_DIR)/include/linux/wl12xx.h \ $(PKG_BUILD_DIR)/include/linux/spi/libertas_spi.h \ $(PKG_BUILD_DIR)/include/net/ieee80211.h echo 'compat-wireless-$(PKG_VERSION)-$(PKG_RELEASE)-$(REVISION)' > $(PKG_BUILD_DIR)/compat_version $(CP) ./files/regdb.txt $(PKG_BUILD_DIR)/net/wireless/db.txt endef ifneq ($(CONFIG_PACKAGE_kmod-cfg80211)$(CONFIG_PACKAGE_kmod-lib80211),) define Build/Compile/kmod rm -rf $(PKG_BUILD_DIR)/modules +$(MAKE) $(PKG_JOBS) $(MAKE_OPTS) modules endef endif define Build/Configure cmp $(PKG_BUILD_DIR)/include/linux/ath9k_platform.h $(LINUX_DIR)/include/linux/ath9k_platform.h cmp $(PKG_BUILD_DIR)/include/linux/ath5k_platform.h $(LINUX_DIR)/include/linux/ath5k_platform.h cmp $(PKG_BUILD_DIR)/include/linux/rt2x00_platform.h $(LINUX_DIR)/include/linux/rt2x00_platform.h endef define Build/Compile $(SH_FUNC) var2file "$(call shvar,mac80211_config)" $(PKG_BUILD_DIR)/.config $(MAKE) $(MAKE_OPTS) allnoconfig $(call Build/Compile/kmod) endef define Build/InstallDev mkdir -p \ $(1)/usr/include/mac80211 \ $(1)/usr/include/mac80211-backport \ $(1)/usr/include/mac80211/ath \ $(1)/usr/include/net/mac80211 $(CP) $(PKG_BUILD_DIR)/net/mac80211/*.h $(PKG_BUILD_DIR)/include/* $(1)/usr/include/mac80211/ $(CP) $(PKG_BUILD_DIR)/backport-include/* $(1)/usr/include/mac80211-backport/ $(CP) $(PKG_BUILD_DIR)/net/mac80211/rate.h $(1)/usr/include/net/mac80211/ $(CP) $(PKG_BUILD_DIR)/drivers/net/wireless/ath/*.h $(1)/usr/include/mac80211/ath/ rm -f $(1)/usr/include/mac80211-backport/linux/module.h endef define KernelPackage/libertas-usb/install $(INSTALL_DIR) $(1)/lib/firmware/libertas $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/libertas/usb8388_v9.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/libertas/usb8682.bin \ $(1)/lib/firmware/libertas/ endef define KernelPackage/libertas-sd/install $(INSTALL_DIR) $(1)/lib/firmware/libertas $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/libertas/sd8385_helper.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/libertas/sd8385.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/libertas/sd8686_v9_helper.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/libertas/sd8686_v9.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/libertas/sd8688_helper.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/libertas/sd8688.bin \ $(1)/lib/firmware/libertas endef define KernelPackage/cfg80211/install $(INSTALL_DIR) $(1)/lib/wifi $(1)/lib/netifd/wireless $(INSTALL_DATA) ./files/lib/wifi/mac80211.sh $(1)/lib/wifi $(INSTALL_BIN) ./files/lib/netifd/wireless/mac80211.sh $(1)/lib/netifd/wireless endef define KernelPackage/p54-pci/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) $(DL_DIR)/$(P54PCIFW) $(1)/lib/firmware/isl3886pci endef define KernelPackage/p54-usb/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) $(DL_DIR)/$(P54USBFW) $(1)/lib/firmware/isl3887usb endef define KernelPackage/p54-spi/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) $(DL_DIR)/$(P54SPIFW) $(1)/lib/firmware/3826.arm endef define KernelPackage/rt61-pci/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rt2561.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rt2561s.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rt2661.bin \ $(1)/lib/firmware/ endef define KernelPackage/rt73-usb/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rt73.bin $(1)/lib/firmware/ endef define KernelPackage/rt2800-pci/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rt2860.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rt3290.bin \ $(1)/lib/firmware endef define KernelPackage/rt2800-usb/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/rt2870.bin $(1)/lib/firmware/ endef define KernelPackage/wl12xx/install $(INSTALL_DIR) $(1)/lib/firmware/ti-connectivity $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/ti-connectivity/wl127x-fw-5-mr.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/ti-connectivity/wl127x-fw-5-plt.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/ti-connectivity/wl127x-fw-5-sr.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/ti-connectivity/wl1271-nvs.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/ti-connectivity/wl128x-fw-5-mr.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/ti-connectivity/wl128x-fw-5-plt.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/ti-connectivity/wl128x-fw-5-sr.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/ti-connectivity/wl128x-nvs.bin \ $(1)/lib/firmware/ti-connectivity endef define KernelPackage/wl18xx/install $(INSTALL_DIR) $(1)/lib/firmware/ti-connectivity $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/ti-connectivity/wl18xx-conf.bin \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/ti-connectivity/wl18xx-fw-3.bin \ $(1)/lib/firmware/ti-connectivity endef define KernelPackage/zd1211rw/install $(INSTALL_DIR) $(1)/lib/firmware/zd1211 $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(ZD1211FW_NAME)/zd1211* $(1)/lib/firmware/zd1211 endef define KernelPackage/carl9170/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/carl9170-1.fw $(1)/lib/firmware endef define KernelPackage/ath9k-htc/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/htc_9271.fw \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/htc_7010.fw \ $(1)/lib/firmware/ endef define KernelPackage/ath10k/install $(INSTALL_DIR) $(1)/lib/firmware/ath10k/QCA988X/hw2.0 $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_ATH10K_LINUX_FIRMWARE_SUBDIR)/ath10k/QCA988X/hw2.0/board.bin \ $(1)/lib/firmware/ath10k/QCA988X/hw2.0/ ifeq ($(CONFIG_ATH10K_STA_FW),y) $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_ATH10K_LINUX_FIRMWARE_SUBDIR)/main/firmware-2.bin_999.999.0.636 \ $(1)/lib/firmware/ath10k/QCA988X/hw2.0/firmware-2.bin else $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_ATH10K_LINUX_FIRMWARE_SUBDIR)/10.2/firmware-3.bin_10.2-00082-4-2 \ $(1)/lib/firmware/ath10k/QCA988X/hw2.0/firmware-3.bin endif endef define KernelPackage/mwl8k/install $(INSTALL_DIR) $(1)/lib/firmware/mwl8k $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/mwl8k/fmimage_8366_ap-3.fw \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/mwl8k/fmimage_8366.fw \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/mwl8k/helper_8366.fw \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/mwl8k/fmimage_8687.fw \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/mwl8k/helper_8687.fw \ $(1)/lib/firmware/mwl8k/ endef define KernelPackage/mwifiex-pcie/install $(INSTALL_DIR) $(1)/lib/firmware/mrvl $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/mrvl/pcie8897_uapsta.bin \ $(1)/lib/firmware/mrvl/ endef define KernelPackage/net-ipw2100/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) $(PKG_BUILD_DIR)/ipw2100-$(IPW2100_VERSION)*.fw $(1)/lib/firmware endef define KernelPackage/net-ipw2200/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(IPW2200_NAME)-$(IPW2200_VERSION)/ipw2200*.fw $(1)/lib/firmware endef define KernelPackage/iwlagn/install $(INSTALL_DIR) $(1)/lib/firmware ifneq ($(CONFIG_IWL5000_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-5000-5.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL5150_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-5150-2.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL1000_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-1000-5.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL6000_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-6000-4.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL6050_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-6050-5.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL6005_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-6000g2a-6.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL6030_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-6000g2b-6.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL7260_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-7260-9.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL7265_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-7265-9.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL100_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-100-5.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL2000_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-2000-6.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL2030_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-2030-6.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL105_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-105-6.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL135_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-135-6.ucode $(1)/lib/firmware endif ifneq ($(CONFIG_IWL3160_FW),) $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-3160-9.ucode $(1)/lib/firmware endif endef define KernelPackage/iwl3945/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-3945-2.ucode $(1)/lib/firmware endef define KernelPackage/iwl4965/install $(INSTALL_DIR) $(1)/lib/firmware $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/iwlwifi-4965-2.ucode $(1)/lib/firmware endef define KernelPackage/b43/install rm -rf $(1)/lib/firmware/ ifeq ($(CONFIG_B43_OPENFIRMWARE),y) tar xzf "$(DL_DIR)/$(PKG_B43_FWV4_SOURCE)" -C "$(PKG_BUILD_DIR)" else tar xjf "$(DL_DIR)/$(PKG_B43_FWV4_SOURCE)" -C "$(PKG_BUILD_DIR)" endif $(INSTALL_DIR) $(1)/lib/firmware/ ifeq ($(CONFIG_B43_OPENFIRMWARE),y) $(MAKE) -C "$(PKG_BUILD_DIR)/$(PKG_B43_FWV4_OBJECT)/" $(INSTALL_DIR) $(1)/lib/firmware/b43-open/ $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_B43_FWV4_OBJECT)/ucode5.fw $(1)/lib/firmware/b43-open/ucode5.fw $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_B43_FWV4_OBJECT)/b0g0bsinitvals5.fw $(1)/lib/firmware/b43-open/b0g0bsinitvals5.fw $(INSTALL_DATA) $(PKG_BUILD_DIR)/$(PKG_B43_FWV4_OBJECT)/b0g0initvals5.fw $(1)/lib/firmware/b43-open/b0g0initvals5.fw else b43-fwcutter -w $(1)/lib/firmware/ $(PKG_BUILD_DIR)/$(PKG_B43_FWV4_OBJECT) endif ifneq ($(CONFIG_B43_FW_SQUASH),) b43-fwsquash.py "$(CONFIG_B43_FW_SQUASH_PHYTYPES)" "$(CONFIG_B43_FW_SQUASH_COREREVS)" "$(1)/lib/firmware/b43" endif endef define KernelPackage/b43legacy/install $(INSTALL_DIR) $(1)/lib/firmware/ b43-fwcutter --unsupported -w $(1)/lib/firmware/ $(DL_DIR)/$(PKG_B43_FWV3_SOURCE) ifneq ($(CONFIG_B43LEGACY_FW_SQUASH),) b43-fwsquash.py "G" "$(CONFIG_B43LEGACY_FW_SQUASH_COREREVS)" "$(1)/lib/firmware/b43legacy" endif endef define KernelPackage/brcmsmac/install $(INSTALL_DIR) $(1)/lib/firmware/brcm ifeq ($(CONFIG_BRCMSMAC_USE_FW_FROM_WL),y) tar xjf "$(DL_DIR)/$(PKG_BRCMSMAC_FW_SOURCE)" -C "$(PKG_BUILD_DIR)" b43-fwcutter --brcmsmac -w $(1)/lib/firmware/ $(PKG_BUILD_DIR)/$(PKG_BRCMSMAC_FW_OBJECT) else $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/brcm/bcm43xx-0.fw \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/brcm/bcm43xx_hdr-0.fw \ $(1)/lib/firmware/brcm/ endif endef define KernelPackage/brcmfmac/install $(INSTALL_DIR) $(1)/lib/firmware/brcm $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/brcm/brcmfmac43236b.bin \ $(1)/lib/firmware/brcm/ $(INSTALL_DATA) \ $(PKG_BUILD_DIR)/$(PKG_LINUX_FIRMWARE_SUBDIR)/brcm/brcmfmac43143.bin \ $(1)/lib/firmware/brcm/ endef $(eval $(call KernelPackage,adm8211)) $(eval $(call KernelPackage,ath5k)) $(eval $(call KernelPackage,lib80211)) $(eval $(call KernelPackage,libertas-usb)) $(eval $(call KernelPackage,libertas-sd)) $(eval $(call KernelPackage,cfg80211)) $(eval $(call KernelPackage,mac80211)) $(eval $(call KernelPackage,p54-common)) $(eval $(call KernelPackage,p54-pci)) $(eval $(call KernelPackage,p54-usb)) $(eval $(call KernelPackage,p54-spi)) $(eval $(call KernelPackage,rt2x00-lib)) $(eval $(call KernelPackage,rt2x00-mmio)) $(eval $(call KernelPackage,rt2x00-pci)) $(eval $(call KernelPackage,rt2x00-usb)) $(eval $(call KernelPackage,rt2800-lib)) $(eval $(call KernelPackage,rt2400-pci)) $(eval $(call KernelPackage,rt2500-pci)) $(eval $(call KernelPackage,rt2500-usb)) $(eval $(call KernelPackage,rt61-pci)) $(eval $(call KernelPackage,rt73-usb)) $(eval $(call KernelPackage,rt2800-mmio)) $(eval $(call KernelPackage,rt2800-soc)) $(eval $(call KernelPackage,rt2800-pci)) $(eval $(call KernelPackage,rt2800-usb)) $(eval $(call KernelPackage,rtl8180)) $(eval $(call KernelPackage,rtl8187)) $(eval $(call KernelPackage,rtlwifi)) $(eval $(call KernelPackage,rtlwifi-pci)) $(eval $(call KernelPackage,rtlwifi-usb)) $(eval $(call KernelPackage,rtl8192c-common)) $(eval $(call KernelPackage,rtl8192ce)) $(eval $(call KernelPackage,rtl8192se)) $(eval $(call KernelPackage,rtl8192de)) $(eval $(call KernelPackage,rtl8192cu)) $(eval $(call KernelPackage,zd1211rw)) $(eval $(call KernelPackage,mac80211-hwsim)) $(eval $(call KernelPackage,ath9k-common)) $(eval $(call KernelPackage,ath9k)) $(eval $(call KernelPackage,ath9k-htc)) $(eval $(call KernelPackage,ath10k)) $(eval $(call KernelPackage,ath)) $(eval $(call KernelPackage,carl9170)) $(eval $(call KernelPackage,b43)) $(eval $(call KernelPackage,b43legacy)) $(eval $(call KernelPackage,brcmutil)) $(eval $(call KernelPackage,brcmsmac)) $(eval $(call KernelPackage,brcmfmac)) $(eval $(call KernelPackage,net-libipw)) $(eval $(call KernelPackage,net-ipw2100)) $(eval $(call KernelPackage,net-ipw2200)) $(eval $(call KernelPackage,iwlagn)) $(eval $(call KernelPackage,iwl-legacy)) $(eval $(call KernelPackage,iwl4965)) $(eval $(call KernelPackage,iwl3945)) $(eval $(call KernelPackage,mwl8k)) $(eval $(call KernelPackage,mwifiex-pcie)) $(eval $(call KernelPackage,net-hermes)) $(eval $(call KernelPackage,net-hermes-pci)) $(eval $(call KernelPackage,net-hermes-plx)) $(eval $(call KernelPackage,net-hermes-pcmcia)) $(eval $(call KernelPackage,wlcore)) $(eval $(call KernelPackage,wl12xx)) $(eval $(call KernelPackage,wl18xx))
houzhenggang/openwrt-hc5661
package/kernel/mac80211/Makefile
Makefile
gpl-2.0
66,895
/* * Block driver for media (i.e., flash cards) * * Copyright 2002 Hewlett-Packard Company * Copyright 2005-2008 Pierre Ossman * * Use consistent with the GNU GPL is permitted, * provided that this copyright notice is * preserved in its entirety in all copies and derived works. * * HEWLETT-PACKARD COMPANY MAKES NO WARRANTIES, EXPRESSED OR IMPLIED, * AS TO THE USEFULNESS OR CORRECTNESS OF THIS CODE OR ITS * FITNESS FOR ANY PARTICULAR PURPOSE. * * Many thanks to Alessandro Rubini and Jonathan Corbet! * * Author: Andrew Christian * 28 May 2002 */ #include <linux/moduleparam.h> #include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/slab.h> #include <linux/errno.h> #include <linux/hdreg.h> #include <linux/kdev_t.h> #include <linux/blkdev.h> #include <linux/mutex.h> #include <linux/scatterlist.h> #include <linux/string_helpers.h> #include <linux/delay.h> #include <linux/capability.h> #include <linux/compat.h> #include <linux/mmc/ioctl.h> #include <linux/mmc/card.h> #include <linux/mmc/host.h> #include <linux/mmc/mmc.h> #include <linux/mmc/sd.h> #include <asm/uaccess.h> #include "queue.h" MODULE_ALIAS("mmc:block"); #ifdef MODULE_PARAM_PREFIX #undef MODULE_PARAM_PREFIX #endif #define MODULE_PARAM_PREFIX "mmcblk." #define INAND_CMD38_ARG_EXT_CSD 113 #define INAND_CMD38_ARG_ERASE 0x00 #define INAND_CMD38_ARG_TRIM 0x01 #define INAND_CMD38_ARG_SECERASE 0x80 #define INAND_CMD38_ARG_SECTRIM1 0x81 #define INAND_CMD38_ARG_SECTRIM2 0x88 #define MMC_BLK_TIMEOUT_MS (30 * 1000) /* 30 sec timeout */ #define MMC_SANITIZE_REQ_TIMEOUT 240000 /* msec */ #define mmc_req_rel_wr(req) (((req->cmd_flags & REQ_FUA) || \ (req->cmd_flags & REQ_META)) && \ (rq_data_dir(req) == WRITE)) #define PACKED_CMD_VER 0x01 #define PACKED_CMD_WR 0x02 #define PACKED_TRIGGER_MAX_ELEMENTS 5000 #define MMC_BLK_UPDATE_STOP_REASON(stats, reason) \ do { \ if (stats->enabled) \ stats->pack_stop_reason[reason]++; \ } while (0) #define PCKD_TRGR_INIT_MEAN_POTEN 17 #define PCKD_TRGR_POTEN_LOWER_BOUND 5 #define PCKD_TRGR_URGENT_PENALTY 2 #define PCKD_TRGR_LOWER_BOUND 5 #define PCKD_TRGR_PRECISION_MULTIPLIER 100 static DEFINE_MUTEX(block_mutex); /* * The defaults come from config options but can be overriden by module * or bootarg options. */ static int perdev_minors = CONFIG_MMC_BLOCK_MINORS; /* * We've only got one major, so number of mmcblk devices is * limited to 256 / number of minors per device. */ static int max_devices; /* 256 minors, so at most 256 separate devices */ static DECLARE_BITMAP(dev_use, 256); static DECLARE_BITMAP(name_use, 256); /* * There is one mmc_blk_data per slot. */ struct mmc_blk_data { spinlock_t lock; struct gendisk *disk; struct mmc_queue queue; struct list_head part; unsigned int flags; #define MMC_BLK_CMD23 (1 << 0) /* Can do SET_BLOCK_COUNT for multiblock */ #define MMC_BLK_REL_WR (1 << 1) /* MMC Reliable write support */ unsigned int usage; unsigned int read_only; unsigned int part_type; unsigned int name_idx; unsigned int reset_done; #define MMC_BLK_READ BIT(0) #define MMC_BLK_WRITE BIT(1) #define MMC_BLK_DISCARD BIT(2) #define MMC_BLK_SECDISCARD BIT(3) /* * Only set in main mmc_blk_data associated * with mmc_card with mmc_set_drvdata, and keeps * track of the current selected device partition. */ unsigned int part_curr; struct device_attribute force_ro; struct device_attribute power_ro_lock; struct device_attribute num_wr_reqs_to_start_packing; struct device_attribute bkops_check_threshold; struct device_attribute no_pack_for_random; int area_type; }; static DEFINE_MUTEX(open_lock); enum { MMC_PACKED_N_IDX = -1, MMC_PACKED_N_ZERO, MMC_PACKED_N_SINGLE, }; module_param(perdev_minors, int, 0444); MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device"); static inline void mmc_blk_clear_packed(struct mmc_queue_req *mqrq) { mqrq->packed_cmd = MMC_PACKED_NONE; mqrq->packed_num = MMC_PACKED_N_ZERO; } static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk) { struct mmc_blk_data *md; mutex_lock(&open_lock); md = disk->private_data; if (md && md->usage == 0) md = NULL; if (md) md->usage++; mutex_unlock(&open_lock); return md; } static inline int mmc_get_devidx(struct gendisk *disk) { int devidx = disk->first_minor / perdev_minors; return devidx; } static void mmc_blk_put(struct mmc_blk_data *md) { mutex_lock(&open_lock); md->usage--; if (md->usage == 0) { int devidx = mmc_get_devidx(md->disk); blk_cleanup_queue(md->queue.queue); __clear_bit(devidx, dev_use); put_disk(md->disk); kfree(md); } mutex_unlock(&open_lock); } static ssize_t power_ro_lock_show(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); struct mmc_card *card = md->queue.card; int locked = 0; if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PERM_WP_EN) locked = 2; else if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_EN) locked = 1; ret = snprintf(buf, PAGE_SIZE, "%d\n", locked); return ret; } static ssize_t power_ro_lock_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret; struct mmc_blk_data *md, *part_md; struct mmc_card *card; unsigned long set; if (kstrtoul(buf, 0, &set)) return -EINVAL; if (set != 1) return count; md = mmc_blk_get(dev_to_disk(dev)); card = md->queue.card; mmc_claim_host(card->host); ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BOOT_WP, card->ext_csd.boot_ro_lock | EXT_CSD_BOOT_WP_B_PWR_WP_EN, card->ext_csd.part_time); if (ret) pr_err("%s: Locking boot partition ro until next power on failed: %d\n", md->disk->disk_name, ret); else card->ext_csd.boot_ro_lock |= EXT_CSD_BOOT_WP_B_PWR_WP_EN; mmc_release_host(card->host); if (!ret) { pr_info("%s: Locking boot partition ro until next power on\n", md->disk->disk_name); set_disk_ro(md->disk, 1); list_for_each_entry(part_md, &md->part, part) if (part_md->area_type == MMC_BLK_DATA_AREA_BOOT) { pr_info("%s: Locking boot partition ro until next power on\n", part_md->disk->disk_name); set_disk_ro(part_md->disk, 1); } } mmc_blk_put(md); return count; } static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); ret = snprintf(buf, PAGE_SIZE, "%d", get_disk_ro(dev_to_disk(dev)) ^ md->read_only); mmc_blk_put(md); return ret; } static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret; char *end; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); unsigned long set = simple_strtoul(buf, &end, 0); if (end == buf) { ret = -EINVAL; goto out; } set_disk_ro(dev_to_disk(dev), set || md->read_only); ret = count; out: mmc_blk_put(md); return ret; } static ssize_t num_wr_reqs_to_start_packing_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); int num_wr_reqs_to_start_packing; int ret; num_wr_reqs_to_start_packing = md->queue.num_wr_reqs_to_start_packing; ret = snprintf(buf, PAGE_SIZE, "%d\n", num_wr_reqs_to_start_packing); mmc_blk_put(md); return ret; } static ssize_t num_wr_reqs_to_start_packing_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int value; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); sscanf(buf, "%d", &value); if (value >= 0) md->queue.num_wr_reqs_to_start_packing = value; mmc_blk_put(md); return count; } static ssize_t bkops_check_threshold_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); struct mmc_card *card = md->queue.card; int ret; if (!card) ret = -EINVAL; else ret = snprintf(buf, PAGE_SIZE, "%d\n", card->bkops_info.size_percentage_to_queue_delayed_work); mmc_blk_put(md); return ret; } static ssize_t bkops_check_threshold_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int value; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); struct mmc_card *card = md->queue.card; unsigned int card_size; int ret = count; if (!card) { ret = -EINVAL; goto exit; } sscanf(buf, "%d", &value); if ((value <= 0) || (value >= 100)) { ret = -EINVAL; goto exit; } card_size = (unsigned int)get_capacity(md->disk); if (card_size <= 0) { ret = -EINVAL; goto exit; } card->bkops_info.size_percentage_to_queue_delayed_work = value; card->bkops_info.min_sectors_to_queue_delayed_work = (card_size * value) / 100; pr_debug("%s: size_percentage = %d, min_sectors = %d", mmc_hostname(card->host), card->bkops_info.size_percentage_to_queue_delayed_work, card->bkops_info.min_sectors_to_queue_delayed_work); exit: mmc_blk_put(md); return count; } static ssize_t no_pack_for_random_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); int ret; ret = snprintf(buf, PAGE_SIZE, "%d\n", md->queue.no_pack_for_random); mmc_blk_put(md); return ret; } static ssize_t no_pack_for_random_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int value; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); struct mmc_card *card = md->queue.card; int ret = count; if (!card) { ret = -EINVAL; goto exit; } sscanf(buf, "%d", &value); if (value < 0) { pr_err("%s: value %d is not valid. old value remains = %d", mmc_hostname(card->host), value, md->queue.no_pack_for_random); ret = -EINVAL; goto exit; } md->queue.no_pack_for_random = (value > 0) ? true : false; pr_debug("%s: no_pack_for_random: new value = %d", mmc_hostname(card->host), md->queue.no_pack_for_random); exit: mmc_blk_put(md); return ret; } static int mmc_blk_open(struct block_device *bdev, fmode_t mode) { struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk); int ret = -ENXIO; mutex_lock(&block_mutex); if (md) { if (md->usage == 2) check_disk_change(bdev); ret = 0; if ((mode & FMODE_WRITE) && md->read_only) { mmc_blk_put(md); ret = -EROFS; } } mutex_unlock(&block_mutex); return ret; } static int mmc_blk_release(struct gendisk *disk, fmode_t mode) { struct mmc_blk_data *md = disk->private_data; mutex_lock(&block_mutex); mmc_blk_put(md); mutex_unlock(&block_mutex); return 0; } static int mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo) { geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16); geo->heads = 4; geo->sectors = 16; return 0; } struct mmc_blk_ioc_data { struct mmc_ioc_cmd ic; unsigned char *buf; u64 buf_bytes; }; static struct mmc_blk_ioc_data *mmc_blk_ioctl_copy_from_user( struct mmc_ioc_cmd __user *user) { struct mmc_blk_ioc_data *idata; int err; idata = kzalloc(sizeof(*idata), GFP_KERNEL); if (!idata) { err = -ENOMEM; goto out; } if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) { err = -EFAULT; goto idata_err; } idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks; if (idata->buf_bytes > MMC_IOC_MAX_BYTES) { err = -EOVERFLOW; goto idata_err; } if (!idata->buf_bytes) return idata; idata->buf = kzalloc(idata->buf_bytes, GFP_KERNEL); if (!idata->buf) { err = -ENOMEM; goto idata_err; } if (copy_from_user(idata->buf, (void __user *)(unsigned long) idata->ic.data_ptr, idata->buf_bytes)) { err = -EFAULT; goto copy_err; } return idata; copy_err: kfree(idata->buf); idata_err: kfree(idata); out: return ERR_PTR(err); } struct scatterlist *mmc_blk_get_sg(struct mmc_card *card, unsigned char *buf, int *sg_len, int size) { struct scatterlist *sg; struct scatterlist *sl; int total_sec_cnt, sec_cnt; int max_seg_size, len; total_sec_cnt = size; max_seg_size = card->host->max_seg_size; len = (size - 1 + max_seg_size) / max_seg_size; sl = kmalloc(sizeof(struct scatterlist) * len, GFP_KERNEL); if (!sl) { return NULL; } sg = (struct scatterlist *)sl; sg_init_table(sg, len); while (total_sec_cnt) { if (total_sec_cnt < max_seg_size) sec_cnt = total_sec_cnt; else sec_cnt = max_seg_size; sg_set_page(sg, virt_to_page(buf), sec_cnt, offset_in_page(buf)); buf = buf + sec_cnt; total_sec_cnt = total_sec_cnt - sec_cnt; if (total_sec_cnt == 0) break; sg = sg_next(sg); } if (sg) sg_mark_end(sg); *sg_len = len; return sl; } static int mmc_blk_ioctl_cmd(struct block_device *bdev, struct mmc_ioc_cmd __user *ic_ptr) { struct mmc_blk_ioc_data *idata; struct mmc_blk_data *md; struct mmc_card *card; struct mmc_command cmd = {0}; struct mmc_data data = {0}; struct mmc_request mrq = {NULL}; struct scatterlist *sg = 0; int err = 0; /* * The caller must have CAP_SYS_RAWIO, and must be calling this on the * whole block device, not on a partition. This prevents overspray * between sibling partitions. */ if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains)) return -EPERM; idata = mmc_blk_ioctl_copy_from_user(ic_ptr); if (IS_ERR(idata)) return PTR_ERR(idata); md = mmc_blk_get(bdev->bd_disk); if (!md) { err = -EINVAL; goto blk_err; } card = md->queue.card; if (IS_ERR(card)) { err = PTR_ERR(card); goto cmd_done; } cmd.opcode = idata->ic.opcode; cmd.arg = idata->ic.arg; cmd.flags = idata->ic.flags; if (idata->buf_bytes) { int len; data.blksz = idata->ic.blksz; data.blocks = idata->ic.blocks; sg = mmc_blk_get_sg(card, idata->buf, &len, idata->buf_bytes); data.sg = sg; data.sg_len = len; if (idata->ic.write_flag) data.flags = MMC_DATA_WRITE; else data.flags = MMC_DATA_READ; /* data.flags must already be set before doing this. */ mmc_set_data_timeout(&data, card); /* Allow overriding the timeout_ns for empirical tuning. */ if (idata->ic.data_timeout_ns) data.timeout_ns = idata->ic.data_timeout_ns; if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) { /* * Pretend this is a data transfer and rely on the * host driver to compute timeout. When all host * drivers support cmd.cmd_timeout for R1B, this * can be changed to: * * mrq.data = NULL; * cmd.cmd_timeout = idata->ic.cmd_timeout_ms; */ data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000; } mrq.data = &data; } mrq.cmd = &cmd; mmc_claim_host(card->host); if (idata->ic.is_acmd) { err = mmc_app_cmd(card->host, card); if (err) goto cmd_rel_host; } mmc_wait_for_req(card->host, &mrq); if (cmd.error) { dev_err(mmc_dev(card->host), "%s: cmd error %d\n", __func__, cmd.error); err = cmd.error; goto cmd_rel_host; } if (data.error) { dev_err(mmc_dev(card->host), "%s: data error %d\n", __func__, data.error); err = data.error; goto cmd_rel_host; } /* * According to the SD specs, some commands require a delay after * issuing the command. */ if (idata->ic.postsleep_min_us) usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us); if (copy_to_user(&(ic_ptr->response), cmd.resp, sizeof(cmd.resp))) { err = -EFAULT; goto cmd_rel_host; } if (!idata->ic.write_flag) { if (copy_to_user((void __user *)(unsigned long) idata->ic.data_ptr, idata->buf, idata->buf_bytes)) { err = -EFAULT; goto cmd_rel_host; } } cmd_rel_host: mmc_release_host(card->host); cmd_done: mmc_blk_put(md); if (sg) kfree(sg); blk_err: kfree(idata->buf); kfree(idata); return err; } static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { int ret = -EINVAL; if (cmd == MMC_IOC_CMD) ret = mmc_blk_ioctl_cmd(bdev, (struct mmc_ioc_cmd __user *)arg); return ret; } #ifdef CONFIG_COMPAT static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg)); } #endif static const struct block_device_operations mmc_bdops = { .open = mmc_blk_open, .release = mmc_blk_release, .getgeo = mmc_blk_getgeo, .owner = THIS_MODULE, .ioctl = mmc_blk_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = mmc_blk_compat_ioctl, #endif }; static inline int mmc_blk_part_switch(struct mmc_card *card, struct mmc_blk_data *md) { int ret; struct mmc_blk_data *main_md = mmc_get_drvdata(card); if (main_md->part_curr == md->part_type) return 0; if (mmc_card_mmc(card)) { u8 part_config = card->ext_csd.part_config; part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK; part_config |= md->part_type; ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_PART_CONFIG, part_config, card->ext_csd.part_time); if (ret) return ret; card->ext_csd.part_config = part_config; } main_md->part_curr = md->part_type; return 0; } static u32 mmc_sd_num_wr_blocks(struct mmc_card *card) { int err; u32 result; __be32 *blocks; struct mmc_request mrq = {NULL}; struct mmc_command cmd = {0}; struct mmc_data data = {0}; struct scatterlist sg; cmd.opcode = MMC_APP_CMD; cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) return (u32)-1; if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD)) return (u32)-1; memset(&cmd, 0, sizeof(struct mmc_command)); cmd.opcode = SD_APP_SEND_NUM_WR_BLKS; cmd.arg = 0; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC; data.blksz = 4; data.blocks = 1; data.flags = MMC_DATA_READ; data.sg = &sg; data.sg_len = 1; mmc_set_data_timeout(&data, card); mrq.cmd = &cmd; mrq.data = &data; blocks = kmalloc(4, GFP_KERNEL); if (!blocks) return (u32)-1; sg_init_one(&sg, blocks, 4); mmc_wait_for_req(card->host, &mrq); result = ntohl(*blocks); kfree(blocks); if (cmd.error || data.error) result = (u32)-1; return result; } static int send_stop(struct mmc_card *card, u32 *status) { struct mmc_command cmd = {0}; int err; cmd.opcode = MMC_STOP_TRANSMISSION; cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 5); if (err == 0) *status = cmd.resp[0]; return err; } static int get_card_status(struct mmc_card *card, u32 *status, int retries) { struct mmc_command cmd = {0}; int err; cmd.opcode = MMC_SEND_STATUS; if (!mmc_host_is_spi(card->host)) cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, retries); if (err == 0) *status = cmd.resp[0]; return err; } #define ERR_NOMEDIUM 3 #define ERR_RETRY 2 #define ERR_ABORT 1 #define ERR_CONTINUE 0 static int mmc_blk_cmd_error(struct request *req, const char *name, int error, bool status_valid, u32 status) { switch (error) { case -EILSEQ: /* response crc error, retry the r/w cmd */ pr_err("%s: %s sending %s command, card status %#x\n", req->rq_disk->disk_name, "response CRC error", name, status); return ERR_RETRY; case -ETIMEDOUT: pr_err("%s: %s sending %s command, card status %#x\n", req->rq_disk->disk_name, "timed out", name, status); /* If the status cmd initially failed, retry the r/w cmd */ if (!status_valid) { pr_err("%s: status not valid, retrying timeout\n", req->rq_disk->disk_name); return ERR_RETRY; } /* * If it was a r/w cmd crc error, or illegal command * (eg, issued in wrong state) then retry - we should * have corrected the state problem above. */ if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND)) { pr_err("%s: command error, retrying timeout\n", req->rq_disk->disk_name); return ERR_RETRY; } /* Otherwise abort the command */ pr_err("%s: not retrying timeout\n", req->rq_disk->disk_name); return ERR_ABORT; default: /* We don't understand the error code the driver gave us */ pr_err("%s: unknown error %d sending read/write command, card status %#x\n", req->rq_disk->disk_name, error, status); return ERR_ABORT; } } /* * Initial r/w and stop cmd error recovery. * We don't know whether the card received the r/w cmd or not, so try to * restore things back to a sane state. Essentially, we do this as follows: * - Obtain card status. If the first attempt to obtain card status fails, * the status word will reflect the failed status cmd, not the failed * r/w cmd. If we fail to obtain card status, it suggests we can no * longer communicate with the card. * - Check the card state. If the card received the cmd but there was a * transient problem with the response, it might still be in a data transfer * mode. Try to send it a stop command. If this fails, we can't recover. * - If the r/w cmd failed due to a response CRC error, it was probably * transient, so retry the cmd. * - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry. * - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or * illegal cmd, retry. * Otherwise we don't understand what happened, so abort. */ static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req, struct mmc_blk_request *brq, int *ecc_err, int *gen_err) { bool prev_cmd_status_valid = true; u32 status, stop_status = 0; int err, retry; if (mmc_card_removed(card)) return ERR_NOMEDIUM; /* * Try to get card status which indicates both the card state * and why there was no response. If the first attempt fails, * we can't be sure the returned status is for the r/w command. */ for (retry = 2; retry >= 0; retry--) { err = get_card_status(card, &status, 0); if (!err) break; prev_cmd_status_valid = false; pr_err("%s: error %d sending status command, %sing\n", req->rq_disk->disk_name, err, retry ? "retry" : "abort"); } /* We couldn't get a response from the card. Give up. */ if (err) { /* Check if the card is removed */ if (mmc_detect_card_removed(card->host)) return ERR_NOMEDIUM; return ERR_ABORT; } /* Flag ECC errors */ if ((status & R1_CARD_ECC_FAILED) || (brq->stop.resp[0] & R1_CARD_ECC_FAILED) || (brq->cmd.resp[0] & R1_CARD_ECC_FAILED)) *ecc_err = 1; /* Flag General errors */ if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) if ((status & R1_ERROR) || (brq->stop.resp[0] & R1_ERROR)) { pr_err("%s: %s: general error sending stop or status command, stop cmd response %#x, card status %#x\n", req->rq_disk->disk_name, __func__, brq->stop.resp[0], status); *gen_err = 1; } /* * Check the current card state. If it is in some data transfer * mode, tell it to stop (and hopefully transition back to TRAN.) */ if (R1_CURRENT_STATE(status) == R1_STATE_DATA || R1_CURRENT_STATE(status) == R1_STATE_RCV) { err = send_stop(card, &stop_status); if (err) pr_err("%s: error %d sending stop command\n", req->rq_disk->disk_name, err); /* * If the stop cmd also timed out, the card is probably * not present, so abort. Other errors are bad news too. */ if (err) return ERR_ABORT; if (stop_status & R1_CARD_ECC_FAILED) *ecc_err = 1; if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) if (stop_status & R1_ERROR) { pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n", req->rq_disk->disk_name, __func__, stop_status); *gen_err = 1; } } /* Check for set block count errors */ if (brq->sbc.error) return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error, prev_cmd_status_valid, status); /* Check for r/w command errors */ if (brq->cmd.error) return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error, prev_cmd_status_valid, status); /* Data errors */ if (!brq->stop.error) return ERR_CONTINUE; /* Now for stop errors. These aren't fatal to the transfer. */ pr_err("%s: error %d sending stop command, original cmd response %#x, card status %#x\n", req->rq_disk->disk_name, brq->stop.error, brq->cmd.resp[0], status); /* * Subsitute in our own stop status as this will give the error * state which happened during the execution of the r/w command. */ if (stop_status) { brq->stop.resp[0] = stop_status; brq->stop.error = 0; } return ERR_CONTINUE; } static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host, int type) { int err; if (md->reset_done & type) return -EEXIST; md->reset_done |= type; err = mmc_hw_reset(host); /* Ensure we switch back to the correct partition */ if (err != -EOPNOTSUPP) { struct mmc_blk_data *main_md = mmc_get_drvdata(host->card); int part_err; main_md->part_curr = main_md->part_type; part_err = mmc_blk_part_switch(host->card, md); if (part_err) { /* * We have failed to get back into the correct * partition, so we need to abort the whole request. */ return -ENODEV; } } return err; } static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type) { md->reset_done &= ~type; } static int mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; unsigned int from, nr, arg; int err = 0, type = MMC_BLK_DISCARD; if (!mmc_can_erase(card)) { err = -EOPNOTSUPP; goto out; } from = blk_rq_pos(req); nr = blk_rq_sectors(req); if (card->ext_csd.bkops_en) card->bkops_info.sectors_changed += blk_rq_sectors(req); if (mmc_can_discard(card)) arg = MMC_DISCARD_ARG; else if (mmc_can_trim(card)) arg = MMC_TRIM_ARG; else arg = MMC_ERASE_ARG; retry: if (card->quirks & MMC_QUIRK_INAND_CMD38) { err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, INAND_CMD38_ARG_EXT_CSD, arg == MMC_TRIM_ARG ? INAND_CMD38_ARG_TRIM : INAND_CMD38_ARG_ERASE, 0); if (err) goto out; } err = mmc_erase(card, from, nr, arg); out: if (err == -EIO && !mmc_blk_reset(md, card->host, type)) goto retry; if (!err) mmc_blk_reset_success(md, type); blk_end_request(req, err, blk_rq_bytes(req)); return err ? 0 : 1; } static int mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq, struct request *req) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; unsigned int from, nr, arg; int err = 0, type = MMC_BLK_SECDISCARD; if (!(mmc_can_secure_erase_trim(card))) { err = -EOPNOTSUPP; goto out; } from = blk_rq_pos(req); nr = blk_rq_sectors(req); if (mmc_can_trim(card) && !mmc_erase_group_aligned(card, from, nr)) arg = MMC_SECURE_TRIM1_ARG; else arg = MMC_SECURE_ERASE_ARG; retry: if (card->quirks & MMC_QUIRK_INAND_CMD38) { err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, INAND_CMD38_ARG_EXT_CSD, arg == MMC_SECURE_TRIM1_ARG ? INAND_CMD38_ARG_SECTRIM1 : INAND_CMD38_ARG_SECERASE, 0); if (err) goto out_retry; } err = mmc_erase(card, from, nr, arg); if (err == -EIO) goto out_retry; if (err) goto out; if (arg == MMC_SECURE_TRIM1_ARG) { if (card->quirks & MMC_QUIRK_INAND_CMD38) { err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, INAND_CMD38_ARG_EXT_CSD, INAND_CMD38_ARG_SECTRIM2, 0); if (err) goto out_retry; } err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG); if (err == -EIO) goto out_retry; if (err) goto out; } out_retry: if (err && !mmc_blk_reset(md, card->host, type)) goto retry; if (!err) mmc_blk_reset_success(md, type); out: blk_end_request(req, err, blk_rq_bytes(req)); return err ? 0 : 1; } static int mmc_blk_issue_sanitize_rq(struct mmc_queue *mq, struct request *req) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; int err = 0; BUG_ON(!card); BUG_ON(!card->host); if (!(mmc_can_sanitize(card) && (card->host->caps2 & MMC_CAP2_SANITIZE))) { pr_warning("%s: %s - SANITIZE is not supported\n", mmc_hostname(card->host), __func__); err = -EOPNOTSUPP; goto out; } pr_debug("%s: %s - SANITIZE IN PROGRESS...\n", mmc_hostname(card->host), __func__); err = mmc_switch_ignore_timeout(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_SANITIZE_START, 1, MMC_SANITIZE_REQ_TIMEOUT); if (err) pr_err("%s: %s - mmc_switch() with " "EXT_CSD_SANITIZE_START failed. err=%d\n", mmc_hostname(card->host), __func__, err); pr_debug("%s: %s - SANITIZE COMPLETED\n", mmc_hostname(card->host), __func__); out: blk_end_request(req, err, blk_rq_bytes(req)); return err ? 0 : 1; } static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; int ret = 0; ret = mmc_flush_cache(card); if (ret) ret = -EIO; blk_end_request_all(req, ret); return ret ? 0 : 1; } /* * Reformat current write as a reliable write, supporting * both legacy and the enhanced reliable write MMC cards. * In each transfer we'll handle only as much as a single * reliable write can handle, thus finish the request in * partial completions. */ static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq, struct mmc_card *card, struct request *req) { if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) { /* Legacy mode imposes restrictions on transfers. */ if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors)) brq->data.blocks = 1; if (brq->data.blocks > card->ext_csd.rel_sectors) brq->data.blocks = card->ext_csd.rel_sectors; else if (brq->data.blocks < card->ext_csd.rel_sectors) brq->data.blocks = 1; } } #define CMD_ERRORS \ (R1_OUT_OF_RANGE | /* Command argument out of range */ \ R1_ADDRESS_ERROR | /* Misaligned address */ \ R1_BLOCK_LEN_ERROR | /* Transferred block length incorrect */\ R1_WP_VIOLATION | /* Tried to write to protected block */ \ R1_CC_ERROR | /* Card controller error */ \ R1_ERROR) /* General/unknown error */ static int mmc_blk_err_check(struct mmc_card *card, struct mmc_async_req *areq) { struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req, mmc_active); struct mmc_blk_request *brq = &mq_mrq->brq; struct request *req = mq_mrq->req; int ecc_err = 0, gen_err = 0; /* * sbc.error indicates a problem with the set block count * command. No data will have been transferred. * * cmd.error indicates a problem with the r/w command. No * data will have been transferred. * * stop.error indicates a problem with the stop command. Data * may have been transferred, or may still be transferring. */ if (brq->sbc.error || brq->cmd.error || brq->stop.error || brq->data.error) { switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err, &gen_err)) { case ERR_RETRY: return MMC_BLK_RETRY; case ERR_ABORT: return MMC_BLK_ABORT; case ERR_NOMEDIUM: return MMC_BLK_NOMEDIUM; case ERR_CONTINUE: break; } } /* * Check for errors relating to the execution of the * initial command - such as address errors. No data * has been transferred. */ if (brq->cmd.resp[0] & CMD_ERRORS) { pr_err("%s: r/w command failed, status = %#x\n", req->rq_disk->disk_name, brq->cmd.resp[0]); return MMC_BLK_ABORT; } /* * Everything else is either success, or a data error of some * kind. If it was a write, we may have transitioned to * program mode, which we have to wait for it to complete. */ if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) { u32 status; unsigned long timeout; /* Check stop command response */ if (brq->stop.resp[0] & R1_ERROR) { pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n", req->rq_disk->disk_name, __func__, brq->stop.resp[0]); gen_err = 1; } timeout = jiffies + msecs_to_jiffies(MMC_BLK_TIMEOUT_MS); do { int err = get_card_status(card, &status, 5); if (err) { pr_err("%s: error %d requesting status\n", req->rq_disk->disk_name, err); return MMC_BLK_CMD_ERR; } if (status & R1_ERROR) { pr_err("%s: %s: general error sending status command, card status %#x\n", req->rq_disk->disk_name, __func__, status); gen_err = 1; } /* Timeout if the device never becomes ready for data * and never leaves the program state. */ if (time_after(jiffies, timeout)) { pr_err("%s: Card stuck in programming state!"\ " %s %s\n", mmc_hostname(card->host), req->rq_disk->disk_name, __func__); return MMC_BLK_CMD_ERR; } /* * Some cards mishandle the status bits, * so make sure to check both the busy * indication and the card state. */ } while (!(status & R1_READY_FOR_DATA) || (R1_CURRENT_STATE(status) == R1_STATE_PRG)); } /* if general error occurs, retry the write operation. */ if (gen_err) { pr_warn("%s: retrying write for general error\n", req->rq_disk->disk_name); return MMC_BLK_RETRY; } if (brq->data.error) { pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n", req->rq_disk->disk_name, brq->data.error, (unsigned)blk_rq_pos(req), (unsigned)blk_rq_sectors(req), brq->cmd.resp[0], brq->stop.resp[0]); if (rq_data_dir(req) == READ) { if (ecc_err) return MMC_BLK_ECC_ERR; return MMC_BLK_DATA_ERR; } else { return MMC_BLK_CMD_ERR; } } if (!brq->data.bytes_xfered) return MMC_BLK_RETRY; if (mq_mrq->packed_cmd != MMC_PACKED_NONE) { if (unlikely(brq->data.blocks << 9 != brq->data.bytes_xfered)) return MMC_BLK_PARTIAL; else return MMC_BLK_SUCCESS; } if (blk_rq_bytes(req) != brq->data.bytes_xfered) return MMC_BLK_PARTIAL; return MMC_BLK_SUCCESS; } /* * mmc_blk_reinsert_req() - re-insert request back to the scheduler * @areq: request to re-insert. * * Request may be packed or single. When fails to reinsert request, it will be * requeued to the the dispatch queue. */ static void mmc_blk_reinsert_req(struct mmc_async_req *areq) { struct request *prq; int ret = 0; struct mmc_queue_req *mq_rq; struct request_queue *q; mq_rq = container_of(areq, struct mmc_queue_req, mmc_active); q = mq_rq->req->q; if (mq_rq->packed_cmd != MMC_PACKED_NONE) { while (!list_empty(&mq_rq->packed_list)) { /* return requests in reverse order */ prq = list_entry_rq(mq_rq->packed_list.prev); list_del_init(&prq->queuelist); spin_lock_irq(q->queue_lock); ret = blk_reinsert_request(q, prq); if (ret) { blk_requeue_request(q, prq); spin_unlock_irq(q->queue_lock); goto reinsert_error; } spin_unlock_irq(q->queue_lock); } } else { spin_lock_irq(q->queue_lock); ret = blk_reinsert_request(q, mq_rq->req); if (ret) blk_requeue_request(q, mq_rq->req); spin_unlock_irq(q->queue_lock); } return; reinsert_error: pr_err("%s: blk_reinsert_request() failed (%d)", mq_rq->req->rq_disk->disk_name, ret); /* * -EIO will be reported for this request and rest of packed_list. * Urgent request will be proceeded anyway, while upper layer * responsibility to re-send failed requests */ while (!list_empty(&mq_rq->packed_list)) { prq = list_entry_rq(mq_rq->packed_list.next); list_del_init(&prq->queuelist); spin_lock_irq(q->queue_lock); blk_requeue_request(q, prq); spin_unlock_irq(q->queue_lock); } } /* * mmc_blk_update_interrupted_req() - update of the stopped request * @card: the MMC card associated with the request. * @areq: interrupted async request. * * Get stopped request state from card and update successfully done part of * the request by setting packed_fail_idx. The packed_fail_idx is index of * first uncompleted request in packed request list, for non-packed request * packed_fail_idx remains unchanged. * * Returns: MMC_BLK_SUCCESS for success, MMC_BLK_ABORT otherwise */ static int mmc_blk_update_interrupted_req(struct mmc_card *card, struct mmc_async_req *areq) { int ret = MMC_BLK_SUCCESS; u8 *ext_csd; int correctly_done; struct mmc_queue_req *mq_rq = container_of(areq, struct mmc_queue_req, mmc_active); struct request *prq; u8 req_index = 0; if (mq_rq->packed_cmd == MMC_PACKED_NONE) return MMC_BLK_SUCCESS; ext_csd = kmalloc(512, GFP_KERNEL); if (!ext_csd) return MMC_BLK_ABORT; /* get correctly programmed sectors number from card */ ret = mmc_send_ext_csd(card, ext_csd); if (ret) { pr_err("%s: error %d reading ext_csd\n", mmc_hostname(card->host), ret); ret = MMC_BLK_ABORT; goto exit; } correctly_done = card->ext_csd.data_sector_size * (ext_csd[EXT_CSD_CORRECTLY_PRG_SECTORS_NUM + 0] << 0 | ext_csd[EXT_CSD_CORRECTLY_PRG_SECTORS_NUM + 1] << 8 | ext_csd[EXT_CSD_CORRECTLY_PRG_SECTORS_NUM + 2] << 16 | ext_csd[EXT_CSD_CORRECTLY_PRG_SECTORS_NUM + 3] << 24); list_for_each_entry(prq, &mq_rq->packed_list, queuelist) { if ((correctly_done - (int)blk_rq_bytes(prq)) < 0) { /* prq is not successfull */ mq_rq->packed_fail_idx = req_index; break; } correctly_done -= blk_rq_bytes(prq); req_index++; } exit: kfree(ext_csd); return ret; } static int mmc_blk_packed_err_check(struct mmc_card *card, struct mmc_async_req *areq) { struct mmc_queue_req *mq_rq = container_of(areq, struct mmc_queue_req, mmc_active); struct request *req = mq_rq->req; int err, check, status; u8 ext_csd[512]; mq_rq->packed_retries--; check = mmc_blk_err_check(card, areq); err = get_card_status(card, &status, 0); if (err) { pr_err("%s: error %d sending status command\n", req->rq_disk->disk_name, err); return MMC_BLK_ABORT; } if (status & R1_EXCEPTION_EVENT) { err = mmc_send_ext_csd(card, ext_csd); if (err) { pr_err("%s: error %d sending ext_csd\n", req->rq_disk->disk_name, err); return MMC_BLK_ABORT; } if ((ext_csd[EXT_CSD_EXP_EVENTS_STATUS] & EXT_CSD_PACKED_FAILURE) && (ext_csd[EXT_CSD_PACKED_CMD_STATUS] & EXT_CSD_PACKED_GENERIC_ERROR)) { if (ext_csd[EXT_CSD_PACKED_CMD_STATUS] & EXT_CSD_PACKED_INDEXED_ERROR) { mq_rq->packed_fail_idx = ext_csd[EXT_CSD_PACKED_FAILURE_INDEX] - 1; return MMC_BLK_PARTIAL; } } } return check; } static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq, struct mmc_card *card, int disable_multi, struct mmc_queue *mq) { u32 readcmd, writecmd; struct mmc_blk_request *brq = &mqrq->brq; struct request *req = mqrq->req; struct mmc_blk_data *md = mq->data; bool do_data_tag; /* * Reliable writes are used to implement Forced Unit Access and * REQ_META accesses, and are supported only on MMCs. * * XXX: this really needs a good explanation of why REQ_META * is treated special. */ bool do_rel_wr = ((req->cmd_flags & REQ_FUA) || (req->cmd_flags & REQ_META)) && (rq_data_dir(req) == WRITE) && (md->flags & MMC_BLK_REL_WR); memset(brq, 0, sizeof(struct mmc_blk_request)); brq->mrq.cmd = &brq->cmd; brq->mrq.data = &brq->data; brq->cmd.arg = blk_rq_pos(req); if (!mmc_card_blockaddr(card)) brq->cmd.arg <<= 9; brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC; brq->data.blksz = 512; brq->stop.opcode = MMC_STOP_TRANSMISSION; brq->stop.arg = 0; brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; brq->data.blocks = blk_rq_sectors(req); brq->data.fault_injected = false; /* * The block layer doesn't support all sector count * restrictions, so we need to be prepared for too big * requests. */ if (brq->data.blocks > card->host->max_blk_count) brq->data.blocks = card->host->max_blk_count; if (brq->data.blocks > 1) { /* * After a read error, we redo the request one sector * at a time in order to accurately determine which * sectors can be read successfully. */ if (disable_multi) brq->data.blocks = 1; /* Some controllers can't do multiblock reads due to hw bugs */ if (card->host->caps2 & MMC_CAP2_NO_MULTI_READ && rq_data_dir(req) == READ) brq->data.blocks = 1; } if (brq->data.blocks > 1 || do_rel_wr) { /* SPI multiblock writes terminate using a special * token, not a STOP_TRANSMISSION request. */ if (!mmc_host_is_spi(card->host) || rq_data_dir(req) == READ) brq->mrq.stop = &brq->stop; readcmd = MMC_READ_MULTIPLE_BLOCK; writecmd = MMC_WRITE_MULTIPLE_BLOCK; } else { brq->mrq.stop = NULL; readcmd = MMC_READ_SINGLE_BLOCK; writecmd = MMC_WRITE_BLOCK; } if (rq_data_dir(req) == READ) { brq->cmd.opcode = readcmd; brq->data.flags |= MMC_DATA_READ; } else { brq->cmd.opcode = writecmd; brq->data.flags |= MMC_DATA_WRITE; } if (do_rel_wr) mmc_apply_rel_rw(brq, card, req); /* * Data tag is used only during writing meta data to speed * up write and any subsequent read of this meta data */ do_data_tag = (card->ext_csd.data_tag_unit_size) && (req->cmd_flags & REQ_META) && (rq_data_dir(req) == WRITE) && ((brq->data.blocks * brq->data.blksz) >= card->ext_csd.data_tag_unit_size); /* * Pre-defined multi-block transfers are preferable to * open ended-ones (and necessary for reliable writes). * However, it is not sufficient to just send CMD23, * and avoid the final CMD12, as on an error condition * CMD12 (stop) needs to be sent anyway. This, coupled * with Auto-CMD23 enhancements provided by some * hosts, means that the complexity of dealing * with this is best left to the host. If CMD23 is * supported by card and host, we'll fill sbc in and let * the host deal with handling it correctly. This means * that for hosts that don't expose MMC_CAP_CMD23, no * change of behavior will be observed. * * N.B: Some MMC cards experience perf degradation. * We'll avoid using CMD23-bounded multiblock writes for * these, while retaining features like reliable writes. */ if ((md->flags & MMC_BLK_CMD23) && mmc_op_multi(brq->cmd.opcode) && (do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23) || do_data_tag)) { brq->sbc.opcode = MMC_SET_BLOCK_COUNT; brq->sbc.arg = brq->data.blocks | (do_rel_wr ? (1 << 31) : 0) | (do_data_tag ? (1 << 29) : 0); brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC; brq->mrq.sbc = &brq->sbc; } mmc_set_data_timeout(&brq->data, card); brq->data.sg = mqrq->sg; brq->data.sg_len = mmc_queue_map_sg(mq, mqrq); /* * Adjust the sg list so it is the same size as the * request. */ if (brq->data.blocks != blk_rq_sectors(req)) { int i, data_size = brq->data.blocks << 9; struct scatterlist *sg; for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) { data_size -= sg->length; if (data_size <= 0) { sg->length += data_size; i++; break; } } brq->data.sg_len = i; } mqrq->mmc_active.mrq = &brq->mrq; mqrq->mmc_active.cmd_flags = req->cmd_flags; mqrq->mmc_active.err_check = mmc_blk_err_check; mqrq->mmc_active.reinsert_req = mmc_blk_reinsert_req; mqrq->mmc_active.update_interrupted_req = mmc_blk_update_interrupted_req; mmc_queue_bounce_pre(mqrq); } /** * mmc_blk_disable_wr_packing() - disables packing mode * @mq: MMC queue. * */ void mmc_blk_disable_wr_packing(struct mmc_queue *mq) { if (mq) { mq->wr_packing_enabled = false; mq->num_of_potential_packed_wr_reqs = 0; } } EXPORT_SYMBOL(mmc_blk_disable_wr_packing); static int get_packed_trigger(int potential, struct mmc_card *card, struct request *req, int curr_trigger) { static int num_mean_elements = 1; static unsigned long mean_potential = PCKD_TRGR_INIT_MEAN_POTEN; unsigned int trigger = curr_trigger; unsigned int pckd_trgr_upper_bound = card->ext_csd.max_packed_writes; /* scale down the upper bound to 75% */ pckd_trgr_upper_bound = (pckd_trgr_upper_bound * 3) / 4; /* * since the most common calls for this function are with small * potential write values and since we don't want these calls to affect * the packed trigger, set a lower bound and ignore calls with * potential lower than that bound */ if (potential <= PCKD_TRGR_POTEN_LOWER_BOUND) return trigger; /* * this is to prevent integer overflow in the following calculation: * once every PACKED_TRIGGER_MAX_ELEMENTS reset the algorithm */ if (num_mean_elements > PACKED_TRIGGER_MAX_ELEMENTS) { num_mean_elements = 1; mean_potential = PCKD_TRGR_INIT_MEAN_POTEN; } /* * get next mean value based on previous mean value and current * potential packed writes. Calculation is as follows: * mean_pot[i+1] = * ((mean_pot[i] * num_mean_elem) + potential)/(num_mean_elem + 1) */ mean_potential *= num_mean_elements; /* * add num_mean_elements so that the division of two integers doesn't * lower mean_potential too much */ if (potential > mean_potential) mean_potential += num_mean_elements; mean_potential += potential; /* this is for gaining more precision when dividing two integers */ mean_potential *= PCKD_TRGR_PRECISION_MULTIPLIER; /* this completes the mean calculation */ mean_potential /= ++num_mean_elements; mean_potential /= PCKD_TRGR_PRECISION_MULTIPLIER; /* * if current potential packed writes is greater than the mean potential * then the heuristic is that the following workload will contain many * write requests, therefore we lower the packed trigger. In the * opposite case we want to increase the trigger in order to get less * packing events. */ if (potential >= mean_potential) trigger = (trigger <= PCKD_TRGR_LOWER_BOUND) ? PCKD_TRGR_LOWER_BOUND : trigger - 1; else trigger = (trigger >= pckd_trgr_upper_bound) ? pckd_trgr_upper_bound : trigger + 1; /* * an urgent read request indicates a packed list being interrupted * by this read, therefore we aim for less packing, hence the trigger * gets increased */ if (req && (req->cmd_flags & REQ_URGENT) && (rq_data_dir(req) == READ)) trigger += PCKD_TRGR_URGENT_PENALTY; return trigger; } static void mmc_blk_write_packing_control(struct mmc_queue *mq, struct request *req) { struct mmc_host *host = mq->card->host; int data_dir; if (!(host->caps2 & MMC_CAP2_PACKED_WR)) return; /* * In case the packing control is not supported by the host, it should * not have an effect on the write packing. Therefore we have to enable * the write packing */ if (!(host->caps2 & MMC_CAP2_PACKED_WR_CONTROL)) { mq->wr_packing_enabled = true; return; } if (!req || (req && (req->cmd_flags & REQ_FLUSH))) { if (mq->num_of_potential_packed_wr_reqs > mq->num_wr_reqs_to_start_packing) mq->wr_packing_enabled = true; mq->num_wr_reqs_to_start_packing = get_packed_trigger(mq->num_of_potential_packed_wr_reqs, mq->card, req, mq->num_wr_reqs_to_start_packing); mq->num_of_potential_packed_wr_reqs = 0; return; } data_dir = rq_data_dir(req); if (data_dir == READ) { mmc_blk_disable_wr_packing(mq); mq->num_wr_reqs_to_start_packing = get_packed_trigger(mq->num_of_potential_packed_wr_reqs, mq->card, req, mq->num_wr_reqs_to_start_packing); mq->num_of_potential_packed_wr_reqs = 0; mq->wr_packing_enabled = false; return; } else if (data_dir == WRITE) { mq->num_of_potential_packed_wr_reqs++; } if (mq->num_of_potential_packed_wr_reqs > mq->num_wr_reqs_to_start_packing) mq->wr_packing_enabled = true; } struct mmc_wr_pack_stats *mmc_blk_get_packed_statistics(struct mmc_card *card) { if (!card) return NULL; return &card->wr_pack_stats; } EXPORT_SYMBOL(mmc_blk_get_packed_statistics); void mmc_blk_init_packed_statistics(struct mmc_card *card) { int max_num_of_packed_reqs = 0; if (!card || !card->wr_pack_stats.packing_events) return; max_num_of_packed_reqs = card->ext_csd.max_packed_writes; spin_lock(&card->wr_pack_stats.lock); memset(card->wr_pack_stats.packing_events, 0, (max_num_of_packed_reqs + 1) * sizeof(*card->wr_pack_stats.packing_events)); memset(&card->wr_pack_stats.pack_stop_reason, 0, sizeof(card->wr_pack_stats.pack_stop_reason)); card->wr_pack_stats.enabled = true; spin_unlock(&card->wr_pack_stats.lock); } EXPORT_SYMBOL(mmc_blk_init_packed_statistics); void print_mmc_packing_stats(struct mmc_card *card) { int i; int max_num_of_packed_reqs = 0; if ((!card) || (!card->wr_pack_stats.packing_events)) return; max_num_of_packed_reqs = card->ext_csd.max_packed_writes; spin_lock(&card->wr_pack_stats.lock); pr_info("%s: write packing statistics:\n", mmc_hostname(card->host)); for (i = 1 ; i <= max_num_of_packed_reqs ; ++i) { if (card->wr_pack_stats.packing_events[i] != 0) pr_info("%s: Packed %d reqs - %d times\n", mmc_hostname(card->host), i, card->wr_pack_stats.packing_events[i]); } pr_info("%s: stopped packing due to the following reasons:\n", mmc_hostname(card->host)); if (card->wr_pack_stats.pack_stop_reason[EXCEEDS_SEGMENTS]) pr_info("%s: %d times: exceedmax num of segments\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[EXCEEDS_SEGMENTS]); if (card->wr_pack_stats.pack_stop_reason[EXCEEDS_SECTORS]) pr_info("%s: %d times: exceeding the max num of sectors\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[EXCEEDS_SECTORS]); if (card->wr_pack_stats.pack_stop_reason[WRONG_DATA_DIR]) pr_info("%s: %d times: wrong data direction\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[WRONG_DATA_DIR]); if (card->wr_pack_stats.pack_stop_reason[FLUSH_OR_DISCARD]) pr_info("%s: %d times: flush or discard\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[FLUSH_OR_DISCARD]); if (card->wr_pack_stats.pack_stop_reason[EMPTY_QUEUE]) pr_info("%s: %d times: empty queue\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[EMPTY_QUEUE]); if (card->wr_pack_stats.pack_stop_reason[REL_WRITE]) pr_info("%s: %d times: rel write\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[REL_WRITE]); if (card->wr_pack_stats.pack_stop_reason[THRESHOLD]) pr_info("%s: %d times: Threshold\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[THRESHOLD]); spin_unlock(&card->wr_pack_stats.lock); } EXPORT_SYMBOL(print_mmc_packing_stats); static u8 mmc_blk_prep_packed_list(struct mmc_queue *mq, struct request *req) { struct request_queue *q = mq->queue; struct mmc_card *card = mq->card; struct request *cur = req, *next = NULL; struct mmc_blk_data *md = mq->data; bool en_rel_wr = card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN; unsigned int req_sectors = 0, phys_segments = 0; unsigned int max_blk_count, max_phys_segs; u8 put_back = 0; u8 max_packed_rw = 0; u8 reqs = 0; struct mmc_wr_pack_stats *stats = &card->wr_pack_stats; mmc_blk_clear_packed(mq->mqrq_cur); if (!(md->flags & MMC_BLK_CMD23) || !card->ext_csd.packed_event_en) goto no_packed; if (!mq->wr_packing_enabled) goto no_packed; if ((rq_data_dir(cur) == WRITE) && (card->host->caps2 & MMC_CAP2_PACKED_WR)) max_packed_rw = card->ext_csd.max_packed_writes; if (max_packed_rw == 0) goto no_packed; if (mmc_req_rel_wr(cur) && (md->flags & MMC_BLK_REL_WR) && !en_rel_wr) goto no_packed; if (mmc_large_sec(card) && !IS_ALIGNED(blk_rq_sectors(cur), 8)) goto no_packed; max_blk_count = min(card->host->max_blk_count, card->host->max_req_size >> 9); if (unlikely(max_blk_count > 0xffff)) max_blk_count = 0xffff; max_phys_segs = queue_max_segments(q); req_sectors += blk_rq_sectors(cur); phys_segments += cur->nr_phys_segments; if (rq_data_dir(cur) == WRITE) { req_sectors++; phys_segments++; } spin_lock(&stats->lock); while (reqs < max_packed_rw - 1) { /* We should stop no-more packing its nopacked_period */ if ((card->host->caps2 & MMC_CAP2_ADAPT_PACKED) && time_is_after_jiffies(mq->nopacked_period)) break; spin_lock_irq(q->queue_lock); next = blk_fetch_request(q); spin_unlock_irq(q->queue_lock); if (!next) { MMC_BLK_UPDATE_STOP_REASON(stats, EMPTY_QUEUE); break; } if (mmc_large_sec(card) && !IS_ALIGNED(blk_rq_sectors(next), 8)) { MMC_BLK_UPDATE_STOP_REASON(stats, LARGE_SEC_ALIGN); put_back = 1; break; } if (next->cmd_flags & REQ_DISCARD || next->cmd_flags & REQ_FLUSH) { MMC_BLK_UPDATE_STOP_REASON(stats, FLUSH_OR_DISCARD); put_back = 1; break; } if (rq_data_dir(cur) != rq_data_dir(next)) { MMC_BLK_UPDATE_STOP_REASON(stats, WRONG_DATA_DIR); put_back = 1; break; } if (mmc_req_rel_wr(next) && (md->flags & MMC_BLK_REL_WR) && !en_rel_wr) { MMC_BLK_UPDATE_STOP_REASON(stats, REL_WRITE); put_back = 1; break; } req_sectors += blk_rq_sectors(next); if (req_sectors > max_blk_count) { if (stats->enabled) stats->pack_stop_reason[EXCEEDS_SECTORS]++; put_back = 1; break; } phys_segments += next->nr_phys_segments; if (phys_segments > max_phys_segs) { MMC_BLK_UPDATE_STOP_REASON(stats, EXCEEDS_SEGMENTS); put_back = 1; break; } if (mq->no_pack_for_random) { if ((blk_rq_pos(cur) + blk_rq_sectors(cur)) != blk_rq_pos(next)) { MMC_BLK_UPDATE_STOP_REASON(stats, RANDOM); put_back = 1; break; } } if (rq_data_dir(next) == WRITE) { mq->num_of_potential_packed_wr_reqs++; if (card->ext_csd.bkops_en) card->bkops_info.sectors_changed += blk_rq_sectors(next); } list_add_tail(&next->queuelist, &mq->mqrq_cur->packed_list); cur = next; reqs++; } if (put_back) { spin_lock_irq(q->queue_lock); blk_requeue_request(q, next); spin_unlock_irq(q->queue_lock); } if (stats->enabled) { if (reqs + 1 <= card->ext_csd.max_packed_writes) stats->packing_events[reqs + 1]++; if (reqs + 1 == max_packed_rw) MMC_BLK_UPDATE_STOP_REASON(stats, THRESHOLD); } spin_unlock(&stats->lock); if (reqs > 0) { list_add(&req->queuelist, &mq->mqrq_cur->packed_list); mq->mqrq_cur->packed_num = ++reqs; mq->mqrq_cur->packed_retries = reqs; return reqs; } no_packed: mmc_blk_clear_packed(mq->mqrq_cur); return 0; } static void mmc_blk_packed_hdr_wrq_prep(struct mmc_queue_req *mqrq, struct mmc_card *card, struct mmc_queue *mq) { struct mmc_blk_request *brq = &mqrq->brq; struct request *req = mqrq->req; struct request *prq; struct mmc_blk_data *md = mq->data; bool do_rel_wr, do_data_tag; u32 *packed_cmd_hdr = mqrq->packed_cmd_hdr; u8 i = 1; mqrq->packed_cmd = MMC_PACKED_WRITE; mqrq->packed_blocks = 0; mqrq->packed_fail_idx = MMC_PACKED_N_IDX; memset(packed_cmd_hdr, 0, sizeof(mqrq->packed_cmd_hdr)); packed_cmd_hdr[0] = (mqrq->packed_num << 16) | (PACKED_CMD_WR << 8) | PACKED_CMD_VER; /* * Argument for each entry of packed group */ list_for_each_entry(prq, &mqrq->packed_list, queuelist) { do_rel_wr = mmc_req_rel_wr(prq) && (md->flags & MMC_BLK_REL_WR); do_data_tag = (card->ext_csd.data_tag_unit_size) && (prq->cmd_flags & REQ_META) && (rq_data_dir(prq) == WRITE) && ((brq->data.blocks * brq->data.blksz) >= card->ext_csd.data_tag_unit_size); /* Argument of CMD23 */ packed_cmd_hdr[(i * 2)] = (do_rel_wr ? MMC_CMD23_ARG_REL_WR : 0) | (do_data_tag ? MMC_CMD23_ARG_TAG_REQ : 0) | blk_rq_sectors(prq); /* Argument of CMD18 or CMD25 */ packed_cmd_hdr[((i * 2)) + 1] = mmc_card_blockaddr(card) ? blk_rq_pos(prq) : blk_rq_pos(prq) << 9; mqrq->packed_blocks += blk_rq_sectors(prq); i++; } memset(brq, 0, sizeof(struct mmc_blk_request)); brq->mrq.cmd = &brq->cmd; brq->mrq.data = &brq->data; brq->mrq.sbc = &brq->sbc; brq->mrq.stop = &brq->stop; brq->sbc.opcode = MMC_SET_BLOCK_COUNT; brq->sbc.arg = MMC_CMD23_ARG_PACKED | (mqrq->packed_blocks + 1); brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC; brq->cmd.opcode = MMC_WRITE_MULTIPLE_BLOCK; brq->cmd.arg = blk_rq_pos(req); if (!mmc_card_blockaddr(card)) brq->cmd.arg <<= 9; brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC; brq->data.blksz = 512; brq->data.blocks = mqrq->packed_blocks + 1; brq->data.flags |= MMC_DATA_WRITE; brq->data.fault_injected = false; brq->stop.opcode = MMC_STOP_TRANSMISSION; brq->stop.arg = 0; brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; mmc_set_data_timeout(&brq->data, card); brq->data.sg = mqrq->sg; brq->data.sg_len = mmc_queue_map_sg(mq, mqrq); mqrq->mmc_active.mrq = &brq->mrq; mqrq->mmc_active.cmd_flags = req->cmd_flags; /* * This is intended for packed commands tests usage - in case these * functions are not in use the respective pointers are NULL */ if (mq->err_check_fn) mqrq->mmc_active.err_check = mq->err_check_fn; else mqrq->mmc_active.err_check = mmc_blk_packed_err_check; if (mq->packed_test_fn) mq->packed_test_fn(mq->queue, mqrq); mqrq->mmc_active.reinsert_req = mmc_blk_reinsert_req; mqrq->mmc_active.update_interrupted_req = mmc_blk_update_interrupted_req; mmc_queue_bounce_pre(mqrq); } static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card, struct mmc_blk_request *brq, struct request *req, int ret) { struct mmc_queue_req *mq_rq; mq_rq = container_of(brq, struct mmc_queue_req, brq); /* * If this is an SD card and we're writing, we can first * mark the known good sectors as ok. * * If the card is not SD, we can still ok written sectors * as reported by the controller (which might be less than * the real number of written sectors, but never more). */ if (mmc_card_sd(card)) { u32 blocks; if (!brq->data.fault_injected) { blocks = mmc_sd_num_wr_blocks(card); if (blocks != (u32)-1) ret = blk_end_request(req, 0, blocks << 9); } else ret = blk_end_request(req, 0, brq->data.bytes_xfered); } else { if (mq_rq->packed_cmd == MMC_PACKED_NONE) ret = blk_end_request(req, 0, brq->data.bytes_xfered); } return ret; } static int mmc_blk_end_packed_req(struct mmc_queue_req *mq_rq) { struct request *prq; int idx = mq_rq->packed_fail_idx, i = 0; int ret = 0; while (!list_empty(&mq_rq->packed_list)) { prq = list_entry_rq(mq_rq->packed_list.next); if (idx == i) { /* retry from error index */ mq_rq->packed_num -= idx; mq_rq->req = prq; ret = 1; if (mq_rq->packed_num == MMC_PACKED_N_SINGLE) { list_del_init(&prq->queuelist); mmc_blk_clear_packed(mq_rq); } return ret; } list_del_init(&prq->queuelist); blk_end_request(prq, 0, blk_rq_bytes(prq)); i++; } mmc_blk_clear_packed(mq_rq); return ret; } static void mmc_blk_abort_packed_req(struct mmc_queue_req *mq_rq) { struct request *prq; while (!list_empty(&mq_rq->packed_list)) { prq = list_entry_rq(mq_rq->packed_list.next); list_del_init(&prq->queuelist); blk_end_request(prq, -EIO, blk_rq_bytes(prq)); } mmc_blk_clear_packed(mq_rq); } static void mmc_blk_revert_packed_req(struct mmc_queue *mq, struct mmc_queue_req *mq_rq) { struct request *prq; struct request_queue *q = mq->queue; while (!list_empty(&mq_rq->packed_list)) { prq = list_entry_rq(mq_rq->packed_list.prev); if (prq->queuelist.prev != &mq_rq->packed_list) { list_del_init(&prq->queuelist); spin_lock_irq(q->queue_lock); blk_requeue_request(mq->queue, prq); spin_unlock_irq(q->queue_lock); } else { list_del_init(&prq->queuelist); } } mmc_blk_clear_packed(mq_rq); } static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; struct mmc_blk_request *brq = &mq->mqrq_cur->brq; int ret = 1, disable_multi = 0, retry = 0, type; enum mmc_blk_status status; struct mmc_queue_req *mq_rq; struct request *req; struct mmc_async_req *areq; const u8 packed_num = 2; u8 reqs = 0; if (!rqc && !mq->mqrq_prev->req) return 0; if (rqc) { if ((card->ext_csd.bkops_en) && (rq_data_dir(rqc) == WRITE)) card->bkops_info.sectors_changed += blk_rq_sectors(rqc); reqs = mmc_blk_prep_packed_list(mq, rqc); } do { if (rqc) { if (reqs >= packed_num) mmc_blk_packed_hdr_wrq_prep(mq->mqrq_cur, card, mq); else mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq); areq = &mq->mqrq_cur->mmc_active; } else areq = NULL; areq = mmc_start_req(card->host, areq, (int *) &status); if (!areq) { if (status == MMC_BLK_NEW_REQUEST) mq->flags |= MMC_QUEUE_NEW_REQUEST; return 0; } mq_rq = container_of(areq, struct mmc_queue_req, mmc_active); brq = &mq_rq->brq; req = mq_rq->req; type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE; mmc_queue_bounce_post(mq_rq); switch (status) { case MMC_BLK_URGENT: if (mq_rq->packed_cmd != MMC_PACKED_NONE) { /* complete successfully transmitted part */ if (mmc_blk_end_packed_req(mq_rq)) /* process for not transmitted part */ mmc_blk_reinsert_req(areq); } else { mmc_blk_reinsert_req(areq); } mq->flags |= MMC_QUEUE_URGENT_REQUEST; ret = 0; break; case MMC_BLK_URGENT_DONE: case MMC_BLK_SUCCESS: case MMC_BLK_PARTIAL: /* * A block was successfully transferred. */ mmc_blk_reset_success(md, type); if (mq_rq->packed_cmd != MMC_PACKED_NONE) { ret = mmc_blk_end_packed_req(mq_rq); break; } else { ret = blk_end_request(req, 0, brq->data.bytes_xfered); } /* * If the blk_end_request function returns non-zero even * though all data has been transferred and no errors * were returned by the host controller, it's a bug. */ if (status == MMC_BLK_SUCCESS && ret) { pr_err("%s BUG rq_tot %d d_xfer %d\n", __func__, blk_rq_bytes(req), brq->data.bytes_xfered); rqc = NULL; goto cmd_abort; } break; case MMC_BLK_CMD_ERR: ret = mmc_blk_cmd_err(md, card, brq, req, ret); if (!mmc_blk_reset(md, card->host, type)) break; goto cmd_abort; case MMC_BLK_RETRY: if (retry++ < 5) break; /* Fall through */ case MMC_BLK_ABORT: if (!mmc_blk_reset(md, card->host, type)) break; goto cmd_abort; case MMC_BLK_DATA_ERR: { int err; err = mmc_blk_reset(md, card->host, type); if (!err) break; if (err == -ENODEV || mq_rq->packed_cmd != MMC_PACKED_NONE) goto cmd_abort; /* Fall through */ } case MMC_BLK_ECC_ERR: if (brq->data.blocks > 1) { /* Redo read one sector at a time */ pr_warning("%s: retrying using single block read\n", req->rq_disk->disk_name); disable_multi = 1; break; } /* * After an error, we redo I/O one sector at a * time, so we only reach here after trying to * read a single sector. */ ret = blk_end_request(req, -EIO, brq->data.blksz); if (!ret) goto start_new_req; break; case MMC_BLK_NOMEDIUM: goto cmd_abort; default: pr_err("%s:%s: Unhandled return value (%d)", req->rq_disk->disk_name, __func__, status); goto cmd_abort; } if (ret) { if (mq_rq->packed_cmd == MMC_PACKED_NONE) { /* * In case of a incomplete request * prepare it again and resend. */ mmc_blk_rw_rq_prep(mq_rq, card, disable_multi, mq); mmc_start_req(card->host, &mq_rq->mmc_active, NULL); } else { if (!mq_rq->packed_retries) goto cmd_abort; mmc_blk_packed_hdr_wrq_prep(mq_rq, card, mq); mmc_start_req(card->host, &mq_rq->mmc_active, NULL); } } } while (ret); return 1; cmd_abort: if (mq_rq->packed_cmd == MMC_PACKED_NONE) { if (mmc_card_removed(card)) req->cmd_flags |= REQ_QUIET; while (ret) ret = blk_end_request(req, -EIO, blk_rq_cur_bytes(req)); } else { mmc_blk_abort_packed_req(mq_rq); } start_new_req: if (rqc) { /* * If current request is packed, it needs to put back. */ if (mq->mqrq_cur->packed_cmd != MMC_PACKED_NONE) mmc_blk_revert_packed_req(mq, mq->mqrq_cur); mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq); mmc_start_req(card->host, &mq->mqrq_cur->mmc_active, NULL); } return 0; } static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req) { int ret; struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; #ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME if (mmc_bus_needs_resume(card->host)) { mmc_resume_bus(card->host); mmc_blk_set_blksize(md, card); } #endif if (req && !mq->mqrq_prev->req) { /* claim host only for the first request */ mmc_claim_host(card->host); if (card->ext_csd.bkops_en) mmc_stop_bkops(card); } ret = mmc_blk_part_switch(card, md); if (ret) { if (req) { blk_end_request_all(req, -EIO); } ret = 0; goto out; } mmc_blk_write_packing_control(mq, req); mq->flags &= ~MMC_QUEUE_NEW_REQUEST; mq->flags &= ~MMC_QUEUE_URGENT_REQUEST; if (req && req->cmd_flags & REQ_SANITIZE) { /* complete ongoing async transfer before issuing sanitize */ if (card->host && card->host->areq) mmc_blk_issue_rw_rq(mq, NULL); ret = mmc_blk_issue_sanitize_rq(mq, req); } else if (req && req->cmd_flags & REQ_DISCARD) { /* complete ongoing async transfer before issuing discard */ if (card->host->areq) mmc_blk_issue_rw_rq(mq, NULL); if (req->cmd_flags & REQ_SECURE) ret = mmc_blk_issue_secdiscard_rq(mq, req); else ret = mmc_blk_issue_discard_rq(mq, req); } else if (req && req->cmd_flags & REQ_FLUSH) { /* complete ongoing async transfer before issuing flush */ if (card->host->areq) mmc_blk_issue_rw_rq(mq, NULL); ret = mmc_blk_issue_flush(mq, req); } else { ret = mmc_blk_issue_rw_rq(mq, req); } out: /* * packet burst is over, when one of the following occurs: * - no more requests and new request notification is not in progress * - urgent notification in progress and current request is not urgent * (all existing requests completed or reinserted to the block layer) */ if ((!req && !(mq->flags & MMC_QUEUE_NEW_REQUEST)) || ((mq->flags & MMC_QUEUE_URGENT_REQUEST) && !(mq->mqrq_cur->req->cmd_flags & REQ_URGENT))) { if (mmc_card_need_bkops(card)) mmc_start_bkops(card, false); /* release host only when there are no more requests */ mmc_release_host(card->host); } return ret; } static inline int mmc_blk_readonly(struct mmc_card *card) { return mmc_card_readonly(card) || !(card->csd.cmdclass & CCC_BLOCK_WRITE); } static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card, struct device *parent, sector_t size, bool default_ro, const char *subname, int area_type) { struct mmc_blk_data *md; int devidx, ret; unsigned int percentage = BKOPS_SIZE_PERCENTAGE_TO_QUEUE_DELAYED_WORK; devidx = find_first_zero_bit(dev_use, max_devices); if (devidx >= max_devices) return ERR_PTR(-ENOSPC); __set_bit(devidx, dev_use); md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL); if (!md) { ret = -ENOMEM; goto out; } /* * !subname implies we are creating main mmc_blk_data that will be * associated with mmc_card with mmc_set_drvdata. Due to device * partitions, devidx will not coincide with a per-physical card * index anymore so we keep track of a name index. */ if (!subname) { md->name_idx = find_first_zero_bit(name_use, max_devices); __set_bit(md->name_idx, name_use); } else md->name_idx = ((struct mmc_blk_data *) dev_to_disk(parent)->private_data)->name_idx; md->area_type = area_type; /* * Set the read-only status based on the supported commands * and the write protect switch. */ md->read_only = mmc_blk_readonly(card); md->disk = alloc_disk(perdev_minors); if (md->disk == NULL) { ret = -ENOMEM; goto err_kfree; } spin_lock_init(&md->lock); INIT_LIST_HEAD(&md->part); md->usage = 1; ret = mmc_init_queue(&md->queue, card, &md->lock, subname); if (ret) goto err_putdisk; md->queue.issue_fn = mmc_blk_issue_rq; md->queue.data = md; md->disk->major = MMC_BLOCK_MAJOR; md->disk->first_minor = devidx * perdev_minors; md->disk->fops = &mmc_bdops; md->disk->private_data = md; md->disk->queue = md->queue.queue; md->disk->driverfs_dev = parent; set_disk_ro(md->disk, md->read_only || default_ro); md->disk->flags = GENHD_FL_EXT_DEVT; /* * As discussed on lkml, GENHD_FL_REMOVABLE should: * * - be set for removable media with permanent block devices * - be unset for removable block devices with permanent media * * Since MMC block devices clearly fall under the second * case, we do not set GENHD_FL_REMOVABLE. Userspace * should use the block device creation/destruction hotplug * messages to tell when the card is present. */ snprintf(md->disk->disk_name, sizeof(md->disk->disk_name), "mmcblk%d%s", md->name_idx, subname ? subname : ""); blk_queue_logical_block_size(md->queue.queue, 512); set_capacity(md->disk, size); card->bkops_info.size_percentage_to_queue_delayed_work = percentage; card->bkops_info.min_sectors_to_queue_delayed_work = ((unsigned int)size * percentage) / 100; if (mmc_host_cmd23(card->host)) { if (mmc_card_mmc(card) || (mmc_card_sd(card) && card->scr.cmds & SD_SCR_CMD23_SUPPORT && mmc_sd_card_uhs(card))) md->flags |= MMC_BLK_CMD23; } if (mmc_card_mmc(card) && md->flags & MMC_BLK_CMD23 && ((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) || card->ext_csd.rel_sectors)) { md->flags |= MMC_BLK_REL_WR; blk_queue_flush(md->queue.queue, REQ_FLUSH | REQ_FUA); } return md; err_putdisk: put_disk(md->disk); err_kfree: kfree(md); out: return ERR_PTR(ret); } static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card) { sector_t size; struct mmc_blk_data *md; if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) { /* * The EXT_CSD sector count is in number or 512 byte * sectors. */ size = card->ext_csd.sectors; } else { /* * The CSD capacity field is in units of read_blkbits. * set_capacity takes units of 512 bytes. */ size = card->csd.capacity << (card->csd.read_blkbits - 9); } md = mmc_blk_alloc_req(card, &card->dev, size, false, NULL, MMC_BLK_DATA_AREA_MAIN); return md; } static int mmc_blk_alloc_part(struct mmc_card *card, struct mmc_blk_data *md, unsigned int part_type, sector_t size, bool default_ro, const char *subname, int area_type) { char cap_str[10]; struct mmc_blk_data *part_md; part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro, subname, area_type); if (IS_ERR(part_md)) return PTR_ERR(part_md); part_md->part_type = part_type; list_add(&part_md->part, &md->part); string_get_size((u64)get_capacity(part_md->disk) << 9, STRING_UNITS_2, cap_str, sizeof(cap_str)); pr_info("%s: %s %s partition %u %s\n", part_md->disk->disk_name, mmc_card_id(card), mmc_card_name(card), part_md->part_type, cap_str); return 0; } /* MMC Physical partitions consist of two boot partitions and * up to four general purpose partitions. * For each partition enabled in EXT_CSD a block device will be allocatedi * to provide access to the partition. */ static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md) { int idx, ret = 0; if (!mmc_card_mmc(card)) return 0; for (idx = 0; idx < card->nr_parts; idx++) { if (card->part[idx].size) { ret = mmc_blk_alloc_part(card, md, card->part[idx].part_cfg, card->part[idx].size >> 9, card->part[idx].force_ro, card->part[idx].name, card->part[idx].area_type); if (ret) return ret; } } return ret; } static void mmc_blk_remove_req(struct mmc_blk_data *md) { struct mmc_card *card; if (md) { card = md->queue.card; device_remove_file(disk_to_dev(md->disk), &md->num_wr_reqs_to_start_packing); if (md->disk->flags & GENHD_FL_UP) { device_remove_file(disk_to_dev(md->disk), &md->force_ro); if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) && card->ext_csd.boot_ro_lockable) device_remove_file(disk_to_dev(md->disk), &md->power_ro_lock); /* Stop new requests from getting into the queue */ del_gendisk(md->disk); } /* Then flush out any already in there */ mmc_cleanup_queue(&md->queue); mmc_blk_put(md); } } static void mmc_blk_remove_parts(struct mmc_card *card, struct mmc_blk_data *md) { struct list_head *pos, *q; struct mmc_blk_data *part_md; __clear_bit(md->name_idx, name_use); list_for_each_safe(pos, q, &md->part) { part_md = list_entry(pos, struct mmc_blk_data, part); list_del(pos); mmc_blk_remove_req(part_md); } } static int mmc_add_disk(struct mmc_blk_data *md) { int ret; struct mmc_card *card = md->queue.card; add_disk(md->disk); md->force_ro.show = force_ro_show; md->force_ro.store = force_ro_store; sysfs_attr_init(&md->force_ro.attr); md->force_ro.attr.name = "force_ro"; md->force_ro.attr.mode = S_IRUGO | S_IWUSR; ret = device_create_file(disk_to_dev(md->disk), &md->force_ro); if (ret) goto force_ro_fail; if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) && card->ext_csd.boot_ro_lockable) { umode_t mode; if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_DIS) mode = S_IRUGO; else mode = S_IRUGO | S_IWUSR; md->power_ro_lock.show = power_ro_lock_show; md->power_ro_lock.store = power_ro_lock_store; sysfs_attr_init(&md->power_ro_lock.attr); md->power_ro_lock.attr.mode = mode; md->power_ro_lock.attr.name = "ro_lock_until_next_power_on"; ret = device_create_file(disk_to_dev(md->disk), &md->power_ro_lock); if (ret) goto power_ro_lock_fail; } md->num_wr_reqs_to_start_packing.show = num_wr_reqs_to_start_packing_show; md->num_wr_reqs_to_start_packing.store = num_wr_reqs_to_start_packing_store; sysfs_attr_init(&md->num_wr_reqs_to_start_packing.attr); md->num_wr_reqs_to_start_packing.attr.name = "num_wr_reqs_to_start_packing"; md->num_wr_reqs_to_start_packing.attr.mode = S_IRUGO | S_IWUSR; ret = device_create_file(disk_to_dev(md->disk), &md->num_wr_reqs_to_start_packing); if (ret) goto num_wr_reqs_to_start_packing_fail; md->bkops_check_threshold.show = bkops_check_threshold_show; md->bkops_check_threshold.store = bkops_check_threshold_store; sysfs_attr_init(&md->bkops_check_threshold.attr); md->bkops_check_threshold.attr.name = "bkops_check_threshold"; md->bkops_check_threshold.attr.mode = S_IRUGO | S_IWUSR; ret = device_create_file(disk_to_dev(md->disk), &md->bkops_check_threshold); if (ret) goto bkops_check_threshold_fails; md->no_pack_for_random.show = no_pack_for_random_show; md->no_pack_for_random.store = no_pack_for_random_store; sysfs_attr_init(&md->no_pack_for_random.attr); md->no_pack_for_random.attr.name = "no_pack_for_random"; md->no_pack_for_random.attr.mode = S_IRUGO | S_IWUSR; ret = device_create_file(disk_to_dev(md->disk), &md->no_pack_for_random); if (ret) goto no_pack_for_random_fails; return ret; no_pack_for_random_fails: device_remove_file(disk_to_dev(md->disk), &md->bkops_check_threshold); bkops_check_threshold_fails: device_remove_file(disk_to_dev(md->disk), &md->num_wr_reqs_to_start_packing); num_wr_reqs_to_start_packing_fail: device_remove_file(disk_to_dev(md->disk), &md->power_ro_lock); power_ro_lock_fail: device_remove_file(disk_to_dev(md->disk), &md->force_ro); force_ro_fail: del_gendisk(md->disk); return ret; } #define CID_MANFID_SANDISK 0x2 #define CID_MANFID_TOSHIBA 0x11 #define CID_MANFID_MICRON 0x13 #define CID_MANFID_SAMSUNG 0x15 static const struct mmc_fixup blk_fixups[] = { MMC_FIXUP("SEM02G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM04G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM08G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM16G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM32G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), /* * Some MMC cards experience performance degradation with CMD23 * instead of CMD12-bounded multiblock transfers. For now we'll * black list what's bad... * - Certain Toshiba cards. * * N.B. This doesn't affect SD cards. */ MMC_FIXUP("MMC08G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_BLK_NO_CMD23), MMC_FIXUP("MMC16G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_BLK_NO_CMD23), MMC_FIXUP("MMC32G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_BLK_NO_CMD23), /* * Some Micron MMC cards needs longer data read timeout than * indicated in CSD. */ MMC_FIXUP(CID_NAME_ANY, CID_MANFID_MICRON, 0x200, add_quirk_mmc, MMC_QUIRK_LONG_READ_TIME), /* Some TLC movinand cards needs Sync operation for performance*/ MMC_FIXUP("S5U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("J5U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("J5U00B", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("J5U00A", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("L7U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("N5U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("K5U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("K5U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("K7U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("M4G1YC", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("M8G1WA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("MAG2WA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), MMC_FIXUP("MBG4WA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_MOVINAND_TLC), /* Some INAND MCP devices advertise incorrect timeout values */ MMC_FIXUP("SEM04G", 0x45, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_INAND_DATA_TIMEOUT), END_FIXUP }; static int mmc_blk_probe(struct mmc_card *card) { struct mmc_blk_data *md, *part_md; char cap_str[10]; /* * Check that the card supports the command class(es) we need. */ if (!(card->csd.cmdclass & CCC_BLOCK_READ)) return -ENODEV; md = mmc_blk_alloc(card); if (IS_ERR(md)) return PTR_ERR(md); string_get_size((u64)get_capacity(md->disk) << 9, STRING_UNITS_2, cap_str, sizeof(cap_str)); pr_info("%s: %s %s %s %s\n", md->disk->disk_name, mmc_card_id(card), mmc_card_name(card), cap_str, md->read_only ? "(ro)" : ""); if (mmc_blk_alloc_parts(card, md)) goto out; mmc_set_drvdata(card, md); mmc_fixup_device(card, blk_fixups); #ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME mmc_set_bus_resume_policy(card->host, 1); #endif if (mmc_add_disk(md)) goto out; list_for_each_entry(part_md, &md->part, part) { if (mmc_add_disk(part_md)) goto out; } return 0; out: mmc_blk_remove_parts(card, md); mmc_blk_remove_req(md); return 0; } static void mmc_blk_remove(struct mmc_card *card) { struct mmc_blk_data *md = mmc_get_drvdata(card); mmc_blk_remove_parts(card, md); mmc_claim_host(card->host); mmc_blk_part_switch(card, md); mmc_release_host(card->host); mmc_blk_remove_req(md); mmc_set_drvdata(card, NULL); #ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME mmc_set_bus_resume_policy(card->host, 0); #endif } #ifdef CONFIG_PM static int mmc_blk_suspend(struct mmc_card *card) { struct mmc_blk_data *part_md; struct mmc_blk_data *md = mmc_get_drvdata(card); int rc = 0; if (md) { rc = mmc_queue_suspend(&md->queue); if (rc) goto out; list_for_each_entry(part_md, &md->part, part) { rc = mmc_queue_suspend(&part_md->queue); if (rc) goto out_resume; } } goto out; out_resume: mmc_queue_resume(&md->queue); list_for_each_entry(part_md, &md->part, part) { mmc_queue_resume(&part_md->queue); } out: return rc; } static int mmc_blk_resume(struct mmc_card *card) { struct mmc_blk_data *part_md; struct mmc_blk_data *md = mmc_get_drvdata(card); if (md) { /* * Resume involves the card going into idle state, * so current partition is always the main one. */ md->part_curr = md->part_type; mmc_queue_resume(&md->queue); list_for_each_entry(part_md, &md->part, part) { mmc_queue_resume(&part_md->queue); } } return 0; } #else #define mmc_blk_suspend NULL #define mmc_blk_resume NULL #endif static struct mmc_driver mmc_driver = { .drv = { .name = "mmcblk", }, .probe = mmc_blk_probe, .remove = mmc_blk_remove, .suspend = mmc_blk_suspend, .resume = mmc_blk_resume, }; static int __init mmc_blk_init(void) { int res; if (perdev_minors != CONFIG_MMC_BLOCK_MINORS) pr_info("mmcblk: using %d minors per device\n", perdev_minors); max_devices = 256 / perdev_minors; res = register_blkdev(MMC_BLOCK_MAJOR, "mmc"); if (res) goto out; res = mmc_register_driver(&mmc_driver); if (res) goto out2; return 0; out2: unregister_blkdev(MMC_BLOCK_MAJOR, "mmc"); out: return res; } static void __exit mmc_blk_exit(void) { mmc_unregister_driver(&mmc_driver); unregister_blkdev(MMC_BLOCK_MAJOR, "mmc"); } module_init(mmc_blk_init); module_exit(mmc_blk_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
mahound/Cyanogenmod_kernel_samsung_loganreltexx
drivers/mmc/card/block.c
C
gpl-2.0
81,469
/* arch/arm/mach-msm/include/mach/vmalloc.h * * Copyright (C) 2007 Google, Inc. * Copyright (c) 2009, Code Aurora Forum. All rights reserved. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #ifndef __ASM_ARCH_MSM_VMALLOC_H #define __ASM_ARCH_MSM_VMALLOC_H #ifdef CONFIG_VMSPLIT_2G #define VMALLOC_END (PAGE_OFFSET + 0x7A000000) #else #if defined (CONFIG_LGE_4G_DDR) /* 2010-06-29 [junyeong.han@lge.com] Support 512MB SDRAM */ /* To support 512MB SDRAM in VMSPLIT_3G */ #define VMALLOC_END (PAGE_OFFSET + 0x3A000000) #else /* original */ #define VMALLOC_END (PAGE_OFFSET + 0x20000000) #endif #endif #endif
Perferom/android_kernel_lge_msm7x27-3.0.x
arch/arm/mach-msm/include/mach/vmalloc.h
C
gpl-2.0
1,030
//# LCExtension.cc: Extend an LCRegion along straight lines to other dimensions //# Copyright (C) 1998,2001 //# Associated Universities, Inc. Washington DC, USA. //# //# This library is free software; you can redistribute it and/or modify it //# under the terms of the GNU Library General Public License as published by //# the Free Software Foundation; either version 2 of the License, or (at your //# option) any later version. //# //# This library is distributed in the hope that it will be useful, but WITHOUT //# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or //# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public //# License for more details. //# //# You should have received a copy of the GNU Library General Public License //# along with this library; if not, write to the Free Software Foundation, //# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA. //# //# Correspondence concerning AIPS++ should be addressed as follows: //# Internet email: aips2-request@nrao.edu. //# Postal address: AIPS++ Project Office //# National Radio Astronomy Observatory //# 520 Edgemont Road //# Charlottesville, VA 22903-2475 USA //# //# $Id$ #include <casacore/lattices/LRegions/LCExtension.h> #include <casacore/lattices/LRegions/LCBox.h> #include <casacore/casa/Arrays/Vector.h> #include <casacore/tables/Tables/TableRecord.h> #include <casacore/casa/Utilities/GenSort.h> #include <casacore/casa/Exceptions/Error.h> namespace casacore { //# NAMESPACE CASACORE - BEGIN LCExtension::LCExtension() {} LCExtension::LCExtension (const LCRegion& region, const IPosition& extendAxes, const LCBox& extendBox) : LCRegionMulti (True, region.cloneRegion()) { // Fill the other members variables and determine the bounding box. fill (extendAxes, extendBox); } LCExtension::LCExtension (Bool takeOver, const LCRegion* region, const IPosition& extendAxes, const LCBox& extendBox) : LCRegionMulti (takeOver, region) { // Fill the other members variables and determine the bounding box. fill (extendAxes, extendBox); } LCExtension::LCExtension (const LCExtension& other) : LCRegionMulti (other), itsExtendAxes (other.itsExtendAxes), itsRegionAxes (other.itsRegionAxes), itsExtendBox (other.itsExtendBox) {} LCExtension::~LCExtension() {} LCExtension& LCExtension::operator= (const LCExtension& other) { if (this != &other) { LCRegionMulti::operator= (other); itsExtendAxes.resize (other.itsExtendAxes.nelements()); itsRegionAxes.resize (other.itsRegionAxes.nelements()); itsExtendAxes = other.itsExtendAxes; itsRegionAxes = other.itsRegionAxes; itsExtendBox = other.itsExtendBox; } return *this; } Bool LCExtension::operator== (const LCRegion& other) const { // Check if parent class matches. // If so, we can safely cast. if (! LCRegionMulti::operator== (other)) { return False; } const LCExtension& that = (const LCExtension&)other; // Check the private data if (! itsExtendAxes.isEqual (that.itsExtendAxes) || ! itsRegionAxes.isEqual (that.itsRegionAxes) || !(itsExtendBox == that.itsExtendBox)) { return False; } return True; } LCRegion* LCExtension::cloneRegion() const { return new LCExtension (*this); } LCRegion* LCExtension::doTranslate (const Vector<Float>& translateVector, const IPosition& newLatticeShape) const { uInt i; // First translate the extendBox. // Take appropriate elements from the vectors. uInt nre = itsExtendAxes.nelements(); Vector<Float> boxTransVec (nre); IPosition boxLatShape (nre); for (i=0; i<nre; i++) { uInt axis = itsExtendAxes(i); boxTransVec(i) = translateVector(axis); boxLatShape(i) = newLatticeShape(axis); } LCBox* boxPtr = (LCBox*)(itsExtendBox.translate (boxTransVec, boxLatShape)); // Now translate the region. uInt nrr = itsRegionAxes.nelements(); Vector<Float> regTransVec (nrr); IPosition regLatShape (nrr); for (i=0; i<nrr; i++) { uInt axis = itsRegionAxes(i); regTransVec(i) = translateVector(axis); regLatShape(i) = newLatticeShape(axis); } LCRegion* regPtr = region().translate (regTransVec, regLatShape); // Create the new LCExtension object. LCExtension* extPtr = new LCExtension (*regPtr, itsExtendAxes, *boxPtr); delete boxPtr; delete regPtr; return extPtr; } String LCExtension::className() { return "LCExtension"; } String LCExtension::type() const { return className(); } TableRecord LCExtension::toRecord (const String& tableName) const { TableRecord rec; defineRecordFields (rec, className()); rec.defineRecord ("region", region().toRecord (tableName)); rec.define ("axes", itsExtendAxes.asVector()); rec.defineRecord ("box", itsExtendBox.toRecord (tableName)); return rec; } LCExtension* LCExtension::fromRecord (const TableRecord& rec, const String& tableName) { // Initialize pointers to 0 to get rid of gcc-2.95 warnings. LCRegion* regPtr = 0; regPtr = LCRegion::fromRecord (rec.asRecord("region"), tableName); LCBox* boxPtr = 0; boxPtr = (LCBox*)(LCRegion::fromRecord (rec.asRecord("box"), tableName)); LCExtension* extPtr = new LCExtension (True, regPtr, Vector<Int>(rec.toArrayInt ("axes")), *boxPtr); delete boxPtr; return extPtr; } void LCExtension::fillRegionAxes() { uInt nre = itsExtendAxes.nelements(); uInt nrr = region().ndim(); uInt nrdim = nre+nrr; // allAxes will get the remaining (thus region) axes at the end. IPosition allAxes = IPosition::makeAxisPath (nrdim, itsExtendAxes); itsRegionAxes.resize (nrr); for (uInt i=nre; i<nrdim; i++) { uInt axis = allAxes(i); itsRegionAxes(i-nre) = axis; } } void LCExtension::fill (const IPosition& extendAxes, const LCBox& extendBox) { // Check if extend axes are specified correctly. // They do not need to be in ascending order, but duplicates are // not allowed. IPosition regionShape = region().shape(); uInt nre = extendAxes.nelements(); if (nre == 0) { throw (AipsError ("LCExtension::LCExtension - " "no extend axes have been specified")); } if (nre != extendBox.blc().nelements()) { throw (AipsError ("LCExtension::LCExtension - " "number of axes in extend box mismatches " "number of extend axes")); } // The axes can be specified in any order. We want them ordered. // So sort them and fill itsExtendAxes and itsExtendBox. itsExtendAxes.resize (nre); IPosition boxLatShape(nre); Vector<Float> boxLatBlc(nre); Vector<Float> boxLatTrc(nre); Vector<uInt> reginx(nre); GenSortIndirect<ssize_t>::sort (reginx, extendAxes.storage(), nre); Int first = -1; for (uInt i=0; i<nre; i++) { uInt axis = reginx(i); itsExtendAxes(i) = extendAxes(axis); boxLatShape(i) = extendBox.latticeShape()(axis); boxLatBlc(i) = extendBox.blc()(axis); boxLatTrc(i) = extendBox.trc()(axis); if (itsExtendAxes(i) <= first) { throw (AipsError ("LCExtension::LCExtension - " "extend axes multiply specified")); } first = itsExtendAxes(i); } itsExtendBox = LCBox (boxLatBlc, boxLatTrc, boxLatShape); // Fill itsRegionAxes, i.e. the mapping of the axis of the contributing // region into the extended region. fillRegionAxes(); // Make up the lattice shape from the region and box latticeshape. // Fill the bounding box from blc/trc in region and box. uInt nrr = itsRegionAxes.nelements(); uInt nrdim = nre+nrr; IPosition latShape(nrdim); IPosition blc (nrdim); IPosition trc (nrdim); const IPosition& regionShp = region().latticeShape(); const IPosition& regionBlc = region().boundingBox().start(); const IPosition& regionTrc = region().boundingBox().end(); for (uInt i=0; i<nrr; i++) { uInt axis = itsRegionAxes(i); latShape(axis) = regionShp(i); blc(axis) = regionBlc(i); trc(axis) = regionTrc(i); } const IPosition& boxShp = itsExtendBox.latticeShape(); const IPosition& boxBlc = itsExtendBox.boundingBox().start(); const IPosition& boxTrc = itsExtendBox.boundingBox().end(); for (uInt i=0; i<nre; i++) { uInt axis = itsExtendAxes(i); latShape(axis) = boxShp(i); blc(axis) = boxBlc(i); trc(axis) = boxTrc(i); } setShapeAndBoundingBox (latShape, Slicer(blc, trc, Slicer::endIsLast)); fillHasMask(); } void LCExtension::multiGetSlice (Array<Bool>& buffer, const Slicer& section) { buffer.resize (section.length()); uInt i; uInt nre = itsExtendAxes.nelements(); uInt nrr = itsRegionAxes.nelements(); // Read the required region section. // This means we have to create a Slicer for those axes only. IPosition blc(nrr); IPosition len(nrr); IPosition inc(nrr); IPosition shape(buffer.ndim(), 1); for (i=0; i<nrr; i++) { uInt axis = itsRegionAxes(i); blc(i) = section.start()(axis); len(i) = section.length()(axis); inc(i) = section.stride()(axis); shape(axis) = len(i); } Array<Bool> tmpbuf(len); LCRegion* reg = (LCRegion*)(regions()[0]); reg->doGetSlice (tmpbuf, Slicer(blc, len, inc)); // Reform tmpbuf, so it has the same dimensionality as buffer. Array<Bool> mask = tmpbuf.reform (shape); // Now we have to extend tmpbuf along all extend axes. const IPosition& length = section.length(); IPosition pos (buffer.ndim(), 0); IPosition end (buffer.shape() - 1); //# Iterate along itsExtendAxes (the new axes) through the new mask. for (;;) { for (i=0; i<nre; i++) { end(itsExtendAxes(i)) = pos(itsExtendAxes(i)); } //# Set each section of the mask to the mask of the region. buffer(pos,end) = mask; //# Go to the next section. for (i=0; i<nre; i++) { if (++pos(itsExtendAxes(i)) < length(itsExtendAxes(i))) { break; } // This dimension is done. Reset it and continue with the next. pos(itsExtendAxes(i)) = 0; } //# End the iteration when all dimensions are done. if (i == nre) { break; } } } IPosition LCExtension::doNiceCursorShape (uInt maxPixels) const { return Lattice<Bool>::doNiceCursorShape (maxPixels); } } //# NAMESPACE CASACORE - END
bmerry/casacore
lattices/LRegions/LCExtension.cc
C++
gpl-2.0
10,331
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Composer\Factory; use Composer\Config; use Composer\Downloader\TransportException; use Composer\Repository\PlatformRepository; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Util\ConfigValidator; use Composer\Util\IniHelper; use Composer\Util\ProcessExecutor; use Composer\Util\RemoteFilesystem; use Composer\Util\StreamContextFactory; use Composer\SelfUpdate\Keys; use Composer\SelfUpdate\Versions; use Composer\IO\NullIO; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class DiagnoseCommand extends BaseCommand { /** @var RemoteFilesystem */ protected $rfs; /** @var ProcessExecutor */ protected $process; /** @var int */ protected $exitCode = 0; protected function configure() { $this ->setName('diagnose') ->setDescription('Diagnoses the system to identify common errors.') ->setHelp( <<<EOT The <info>diagnose</info> command checks common errors to help debugging problems. The process exit code will be 1 in case of warnings and 2 for errors. Read more at https://getcomposer.org/doc/03-cli.md#diagnose EOT ) ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $composer = $this->getComposer(false); $io = $this->getIO(); if ($composer) { $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $io->write('Checking composer.json: ', false); $this->outputResult($this->checkComposerSchema()); } if ($composer) { $config = $composer->getConfig(); } else { $config = Factory::createConfig(); } $config->merge(array('config' => array('secure-http' => false))); $config->prohibitUrlByConfig('http://repo.packagist.org', new NullIO); $this->rfs = Factory::createRemoteFilesystem($io, $config); $this->process = new ProcessExecutor($io); $io->write('Checking platform settings: ', false); $this->outputResult($this->checkPlatform()); $io->write('Checking git settings: ', false); $this->outputResult($this->checkGit()); $io->write('Checking http connectivity to packagist: ', false); $this->outputResult($this->checkHttp('http', $config)); $io->write('Checking https connectivity to packagist: ', false); $this->outputResult($this->checkHttp('https', $config)); $opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org')); if (!empty($opts['http']['proxy'])) { $io->write('Checking HTTP proxy: ', false); $this->outputResult($this->checkHttpProxy()); $io->write('Checking HTTP proxy support for request_fulluri: ', false); $this->outputResult($this->checkHttpProxyFullUriRequestParam()); $io->write('Checking HTTPS proxy support for request_fulluri: ', false); $this->outputResult($this->checkHttpsProxyFullUriRequestParam()); } if ($oauth = $config->get('github-oauth')) { foreach ($oauth as $domain => $token) { $io->write('Checking '.$domain.' oauth access: ', false); $this->outputResult($this->checkGithubOauth($domain, $token)); } } else { $io->write('Checking github.com rate limit: ', false); try { $rate = $this->getGithubRateLimit('github.com'); if (!is_array($rate)) { $this->outputResult($rate); } elseif (10 > $rate['remaining']) { $io->write('<warning>WARNING</warning>'); $io->write(sprintf( '<comment>Github has a rate limit on their API. ' . 'You currently have <options=bold>%u</options=bold> ' . 'out of <options=bold>%u</options=bold> requests left.' . PHP_EOL . 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL . ' https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens</comment>', $rate['remaining'], $rate['limit'] )); } else { $this->outputResult(true); } } catch (\Exception $e) { if ($e instanceof TransportException && $e->getCode() === 401) { $this->outputResult('<comment>The oauth token for github.com seems invalid, run "composer config --global --unset github-oauth.github.com" to remove it</comment>'); } else { $this->outputResult($e); } } } $io->write('Checking disk free space: ', false); $this->outputResult($this->checkDiskSpace($config)); if ('phar:' === substr(__FILE__, 0, 5)) { $io->write('Checking pubkeys: ', false); $this->outputResult($this->checkPubKeys($config)); $io->write('Checking composer version: ', false); $this->outputResult($this->checkVersion($config)); } $io->write(sprintf('Composer version: <comment>%s</comment>', Composer::VERSION)); $platformOverrides = $config->get('platform') ?: array(); $platformRepo = new PlatformRepository(array(), $platformOverrides); $phpPkg = $platformRepo->findPackage('php', '*'); $phpVersion = $phpPkg->getPrettyVersion(); if (false !== strpos($phpPkg->getDescription(), 'overridden')) { $phpVersion .= ' - ' . $phpPkg->getDescription(); } $io->write(sprintf('PHP version: <comment>%s</comment>', $phpVersion)); if (defined('PHP_BINARY')) { $io->write(sprintf('PHP binary path: <comment>%s</comment>', PHP_BINARY)); } return $this->exitCode; } private function checkComposerSchema() { $validator = new ConfigValidator($this->getIO()); list($errors, , $warnings) = $validator->validate(Factory::getComposerFile()); if ($errors || $warnings) { $messages = array( 'error' => $errors, 'warning' => $warnings, ); $output = ''; foreach ($messages as $style => $msgs) { foreach ($msgs as $msg) { $output .= '<' . $style . '>' . $msg . '</' . $style . '>' . PHP_EOL; } } return rtrim($output); } return true; } private function checkGit() { $this->process->execute('git config color.ui', $output); if (strtolower(trim($output)) === 'always') { return '<comment>Your git color.ui setting is set to always, this is known to create issues. Use "git config --global color.ui true" to set it correctly.</comment>'; } return true; } private function checkHttp($proto, Config $config) { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } $disableTls = false; $result = array(); if ($proto === 'https' && $config->get('disable-tls') === true) { $disableTls = true; $result[] = '<warning>Composer is configured to disable SSL/TLS protection. This will leave remote HTTPS requests vulnerable to Man-In-The-Middle attacks.</warning>'; } if ($proto === 'https' && !extension_loaded('openssl') && !$disableTls) { $result[] = '<error>Composer is configured to use SSL/TLS protection but the openssl extension is not available.</error>'; } try { $this->rfs->getContents('packagist.org', $proto . '://repo.packagist.org/packages.json', false); } catch (TransportException $e) { if (false !== strpos($e->getMessage(), 'cafile')) { $result[] = '<error>[' . get_class($e) . '] ' . $e->getMessage() . '</error>'; $result[] = '<error>Unable to locate a valid CA certificate file. You must set a valid \'cafile\' option.</error>'; $result[] = '<error>You can alternatively disable this error, at your own risk, by enabling the \'disable-tls\' option.</error>'; } else { array_unshift($result, '[' . get_class($e) . '] ' . $e->getMessage()); } } if (count($result) > 0) { return $result; } return true; } private function checkHttpProxy() { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } $protocol = extension_loaded('openssl') ? 'https' : 'http'; try { $json = json_decode($this->rfs->getContents('packagist.org', $protocol . '://repo.packagist.org/packages.json', false), true); $hash = reset($json['provider-includes']); $hash = $hash['sha256']; $path = str_replace('%hash%', $hash, key($json['provider-includes'])); $provider = $this->rfs->getContents('packagist.org', $protocol . '://repo.packagist.org/'.$path, false); if (hash('sha256', $provider) !== $hash) { return 'It seems that your proxy is modifying http traffic on the fly'; } } catch (\Exception $e) { return $e; } return true; } /** * Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter, * and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825. * This method will test, if you need to disable this parameter via setting extra environment variable in your system. * * @return bool|string */ private function checkHttpProxyFullUriRequestParam() { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } $url = 'http://repo.packagist.org/packages.json'; try { $this->rfs->getContents('packagist.org', $url, false); } catch (TransportException $e) { try { $this->rfs->getContents('packagist.org', $url, false, array('http' => array('request_fulluri' => false))); } catch (TransportException $e) { return 'Unable to assess the situation, maybe packagist.org is down ('.$e->getMessage().')'; } return 'It seems there is a problem with your proxy server, try setting the "HTTP_PROXY_REQUEST_FULLURI" and "HTTPS_PROXY_REQUEST_FULLURI" environment variables to "false"'; } return true; } /** * Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter, * and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825. * This method will test, if you need to disable this parameter via setting extra environment variable in your system. * * @return bool|string */ private function checkHttpsProxyFullUriRequestParam() { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } if (!extension_loaded('openssl')) { return 'You need the openssl extension installed for this check'; } $url = 'https://api.github.com/repos/Seldaek/jsonlint/zipball/1.0.0'; try { $this->rfs->getContents('github.com', $url, false); } catch (TransportException $e) { try { $this->rfs->getContents('github.com', $url, false, array('http' => array('request_fulluri' => false))); } catch (TransportException $e) { return 'Unable to assess the situation, maybe github is down ('.$e->getMessage().')'; } return 'It seems there is a problem with your proxy server, try setting the "HTTPS_PROXY_REQUEST_FULLURI" environment variable to "false"'; } return true; } private function checkGithubOauth($domain, $token) { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic'); try { $url = $domain === 'github.com' ? 'https://api.'.$domain.'/' : 'https://'.$domain.'/api/v3/'; return $this->rfs->getContents($domain, $url, false, array( 'retry-auth-failure' => false, )) ? true : 'Unexpected error'; } catch (\Exception $e) { if ($e instanceof TransportException && $e->getCode() === 401) { return '<comment>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</comment>'; } return $e; } } /** * @param string $domain * @param string $token * @throws TransportException * @return array|string */ private function getGithubRateLimit($domain, $token = null) { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } if ($token) { $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic'); } $url = $domain === 'github.com' ? 'https://api.'.$domain.'/rate_limit' : 'https://'.$domain.'/api/rate_limit'; $json = $this->rfs->getContents($domain, $url, false, array('retry-auth-failure' => false)); $data = json_decode($json, true); return $data['resources']['core']; } private function checkDiskSpace($config) { $minSpaceFree = 1024 * 1024; if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree) || (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree) ) { return '<error>The disk hosting '.$dir.' is full</error>'; } return true; } private function checkPubKeys($config) { $home = $config->get('home'); $errors = array(); $io = $this->getIO(); if (file_exists($home.'/keys.tags.pub') && file_exists($home.'/keys.dev.pub')) { $io->write(''); } if (file_exists($home.'/keys.tags.pub')) { $io->write('Tags Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.tags.pub')); } else { $errors[] = '<error>Missing pubkey for tags verification</error>'; } if (file_exists($home.'/keys.dev.pub')) { $io->write('Dev Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.dev.pub')); } else { $errors[] = '<error>Missing pubkey for dev verification</error>'; } if ($errors) { $errors[] = '<error>Run composer self-update --update-keys to set them up</error>'; } return $errors ?: true; } private function checkVersion($config) { $result = $this->checkConnectivity(); if ($result !== true) { return $result; } $versionsUtil = new Versions($config, $this->rfs); $latest = $versionsUtil->getLatest(); if (Composer::VERSION !== $latest['version'] && Composer::VERSION !== '@package_version@') { return '<comment>You are not running the latest '.$versionsUtil->getChannel().' version, run `composer self-update` to update ('.Composer::VERSION.' => '.$latest['version'].')</comment>'; } return true; } /** * @param bool|string|\Exception $result */ private function outputResult($result) { $io = $this->getIO(); if (true === $result) { $io->write('<info>OK</info>'); return; } $hadError = false; $hadWarning = false; if ($result instanceof \Exception) { $result = '<error>['.get_class($result).'] '.$result->getMessage().'</error>'; } if (!$result) { // falsey results should be considered as an error, even if there is nothing to output $hadError = true; } else { if (!is_array($result)) { $result = array($result); } foreach ($result as $message) { if (false !== strpos($message, '<error>')) { $hadError = true; } elseif (false !== strpos($message, '<warning>')) { $hadWarning = true; } } } if ($hadError) { $io->write('<error>FAIL</error>'); $this->exitCode = max($this->exitCode, 2); } elseif ($hadWarning) { $io->write('<warning>WARNING</warning>'); $this->exitCode = max($this->exitCode, 1); } if ($result) { foreach ($result as $message) { $io->write($message); } } } private function checkPlatform() { $output = ''; $out = function ($msg, $style) use (&$output) { $output .= '<'.$style.'>'.$msg.'</'.$style.'>'.PHP_EOL; }; // code below taken from getcomposer.org/installer, any changes should be made there and replicated here $errors = array(); $warnings = array(); $displayIniMessage = false; $iniMessage = PHP_EOL.PHP_EOL.IniHelper::getMessage(); $iniMessage .= PHP_EOL.'If you can not modify the ini file, you can also run `php -d option=value` to modify ini values on the fly. You can use -d multiple times.'; if (!function_exists('json_decode')) { $errors['json'] = true; } if (!extension_loaded('Phar')) { $errors['phar'] = true; } if (!extension_loaded('filter')) { $errors['filter'] = true; } if (!extension_loaded('hash')) { $errors['hash'] = true; } if (!extension_loaded('iconv') && !extension_loaded('mbstring')) { $errors['iconv_mbstring'] = true; } if (!filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN)) { $errors['allow_url_fopen'] = true; } if (extension_loaded('ionCube Loader') && ioncube_loader_iversion() < 40009) { $errors['ioncube'] = ioncube_loader_version(); } if (PHP_VERSION_ID < 50302) { $errors['php'] = PHP_VERSION; } if (!isset($errors['php']) && PHP_VERSION_ID < 50304) { $warnings['php'] = PHP_VERSION; } if (!extension_loaded('openssl')) { $errors['openssl'] = true; } if (extension_loaded('openssl') && OPENSSL_VERSION_NUMBER < 0x1000100f) { $warnings['openssl_version'] = true; } if (!defined('HHVM_VERSION') && !extension_loaded('apcu') && filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN)) { $warnings['apc_cli'] = true; } if (!extension_loaded('zlib')) { $warnings['zlib'] = true; } ob_start(); phpinfo(INFO_GENERAL); $phpinfo = ob_get_clean(); if (preg_match('{Configure Command(?: *</td><td class="v">| *=> *)(.*?)(?:</td>|$)}m', $phpinfo, $match)) { $configure = $match[1]; if (false !== strpos($configure, '--enable-sigchild')) { $warnings['sigchild'] = true; } if (false !== strpos($configure, '--with-curlwrappers')) { $warnings['curlwrappers'] = true; } } if (filter_var(ini_get('xdebug.profiler_enabled'), FILTER_VALIDATE_BOOLEAN)) { $warnings['xdebug_profile'] = true; } elseif (extension_loaded('xdebug')) { $warnings['xdebug_loaded'] = true; } if (!empty($errors)) { foreach ($errors as $error => $current) { switch ($error) { case 'json': $text = PHP_EOL."The json extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-json"; break; case 'phar': $text = PHP_EOL."The phar extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-phar"; break; case 'filter': $text = PHP_EOL."The filter extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-filter"; break; case 'hash': $text = PHP_EOL."The hash extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-hash"; break; case 'iconv_mbstring': $text = PHP_EOL."The iconv OR mbstring extension is required and both are missing.".PHP_EOL; $text .= "Install either of them or recompile php without --disable-iconv"; break; case 'unicode': $text = PHP_EOL."The detect_unicode setting must be disabled.".PHP_EOL; $text .= "Add the following to the end of your `php.ini`:".PHP_EOL; $text .= " detect_unicode = Off"; $displayIniMessage = true; break; case 'suhosin': $text = PHP_EOL."The suhosin.executor.include.whitelist setting is incorrect.".PHP_EOL; $text .= "Add the following to the end of your `php.ini` or suhosin.ini (Example path [for Debian]: /etc/php5/cli/conf.d/suhosin.ini):".PHP_EOL; $text .= " suhosin.executor.include.whitelist = phar ".$current; $displayIniMessage = true; break; case 'php': $text = PHP_EOL."Your PHP ({$current}) is too old, you must upgrade to PHP 5.3.2 or higher."; break; case 'allow_url_fopen': $text = PHP_EOL."The allow_url_fopen setting is incorrect.".PHP_EOL; $text .= "Add the following to the end of your `php.ini`:".PHP_EOL; $text .= " allow_url_fopen = On"; $displayIniMessage = true; break; case 'ioncube': $text = PHP_EOL."Your ionCube Loader extension ($current) is incompatible with Phar files.".PHP_EOL; $text .= "Upgrade to ionCube 4.0.9 or higher or remove this line (path may be different) from your `php.ini` to disable it:".PHP_EOL; $text .= " zend_extension = /usr/lib/php5/20090626+lfs/ioncube_loader_lin_5.3.so"; $displayIniMessage = true; break; case 'openssl': $text = PHP_EOL."The openssl extension is missing, which means that secure HTTPS transfers are impossible.".PHP_EOL; $text .= "If possible you should enable it or recompile php with --with-openssl"; break; } $out($text, 'error'); } $output .= PHP_EOL; } if (!empty($warnings)) { foreach ($warnings as $warning => $current) { switch ($warning) { case 'apc_cli': $text = "The apc.enable_cli setting is incorrect.".PHP_EOL; $text .= "Add the following to the end of your `php.ini`:".PHP_EOL; $text .= " apc.enable_cli = Off"; $displayIniMessage = true; break; case 'zlib': $text = 'The zlib extension is not loaded, this can slow down Composer a lot.'.PHP_EOL; $text .= 'If possible, enable it or recompile php with --with-zlib'.PHP_EOL; $displayIniMessage = true; break; case 'sigchild': $text = "PHP was compiled with --enable-sigchild which can cause issues on some platforms.".PHP_EOL; $text .= "Recompile it without this flag if possible, see also:".PHP_EOL; $text .= " https://bugs.php.net/bug.php?id=22999"; break; case 'curlwrappers': $text = "PHP was compiled with --with-curlwrappers which will cause issues with HTTP authentication and GitHub.".PHP_EOL; $text .= " Recompile it without this flag if possible"; break; case 'php': $text = "Your PHP ({$current}) is quite old, upgrading to PHP 5.3.4 or higher is recommended.".PHP_EOL; $text .= " Composer works with 5.3.2+ for most people, but there might be edge case issues."; break; case 'openssl_version': // Attempt to parse version number out, fallback to whole string value. $opensslVersion = strstr(trim(strstr(OPENSSL_VERSION_TEXT, ' ')), ' ', true); $opensslVersion = $opensslVersion ?: OPENSSL_VERSION_TEXT; $text = "The OpenSSL library ({$opensslVersion}) used by PHP does not support TLSv1.2 or TLSv1.1.".PHP_EOL; $text .= "If possible you should upgrade OpenSSL to version 1.0.1 or above."; break; case 'xdebug_loaded': $text = "The xdebug extension is loaded, this can slow down Composer a little.".PHP_EOL; $text .= " Disabling it when using Composer is recommended."; break; case 'xdebug_profile': $text = "The xdebug.profiler_enabled setting is enabled, this can slow down Composer a lot.".PHP_EOL; $text .= "Add the following to the end of your `php.ini` to disable it:".PHP_EOL; $text .= " xdebug.profiler_enabled = 0"; $displayIniMessage = true; break; } $out($text, 'comment'); } } if ($displayIniMessage) { $out($iniMessage, 'comment'); } return !$warnings && !$errors ? true : $output; } /** * Check if allow_url_fopen is ON * * @return bool|string */ private function checkConnectivity() { if (!ini_get('allow_url_fopen')) { $result = '<info>Skipped because allow_url_fopen is missing.</info>'; return $result; } return true; } }
rsathishkumar/drupal8
vendor/composer/composer/src/Composer/Command/DiagnoseCommand.php
PHP
gpl-2.0
28,267
/* * drivers/media/video/msm/ov5642_reg_globaloptics.c * * Refer to drivers/media/video/msm/mt9d112_reg.c * For IC OV5642 of Module GLOBALOPTICS: 5.0Mp 1/4-Inch System-On-A-Chip (SOC) CMOS Digital Image Sensor * * Copyright (C) 2009-2010 ZTE Corporation. * * 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/delay.h> #include <linux/types.h> #include <linux/i2c.h> #include <linux/uaccess.h> #include <linux/miscdevice.h> #include <media/msm_camera.h> #include <mach/gpio.h> #include "mt9d113.h" #define MT9D113_SENSOR_PROBE_INIT #ifdef MT9D113_SENSOR_PROBE_INIT #define MT9D113_PROBE_WORKQUEUE #endif #if defined(MT9D113_PROBE_WORKQUEUE) #include <linux/workqueue.h> static struct platform_device *pdev_wq = NULL; static struct workqueue_struct *mt9d113_wq = NULL; static void mt9d113_workqueue(struct work_struct *work); static DECLARE_WORK(mt9d113_cb_work, mt9d113_workqueue); #endif #define MT9D113_CAMIO_MCLK 24000000 #define MT9D113_I2C_BOARD_NAME "mt9d113" #define MT9D113_I2C_BUS_ID (0) #define MT9D113_SLAVE_WR_ADDR 0x78 #define MT9D113_SLAVE_RD_ADDR 0x79 #define REG_MT9D113_MODEL_ID 0x0000 #define MT9D113_MODEL_ID 0x2580 #define REG_MT9D113_MODEL_ID_SUB 0x31FE #define MT9D113_MODEL_ID_SUB 0x0003 #define REG_MT9D113_STANDBY_CONTROL 0x0018 #if defined(CONFIG_MACH_R750) || defined(CONFIG_MACH_JOE) #define MT9D113_GPIO_SWITCH_CTL 39 #define MT9D113_GPIO_SWITCH_VAL 0 #else #undef MT9D113_GPIO_SWITCH_CTL #undef MT9D113_GPIO_SWITCH_VAL #endif struct mt9d113_work_t { struct work_struct work; }; struct mt9d113_ctrl_t { const struct msm_camera_sensor_info *sensordata; }; static struct mt9d113_work_t *mt9d113_sensorw = NULL; static struct i2c_client *mt9d113_client = NULL; static struct mt9d113_ctrl_t *mt9d113_ctrl = NULL; static uint16_t model_id; DECLARE_MUTEX(mt9d113_sem); static struct wake_lock mt9d113_wake_lock; static int mt9d113_sensor_init(const struct msm_camera_sensor_info *data); static int mt9d113_sensor_config(void __user *argp); static int mt9d113_sensor_release(void); static int mt9d113_sensor_release_internal(void); static int32_t mt9d113_i2c_add_driver(void); static void mt9d113_i2c_del_driver(void); extern int32_t msm_camera_power_backend(enum msm_camera_pwr_mode_t pwr_mode); extern int msm_camera_clk_switch(const struct msm_camera_sensor_info *data, uint32_t gpio_switch, uint32_t switch_val); #ifdef CONFIG_ZTE_PLATFORM #ifdef CONFIG_ZTE_FTM_FLAG_SUPPORT extern int zte_get_ftm_flag(void); #endif #endif static inline void mt9d113_init_suspend(void) { CDBG("%s: entry\n", __func__); wake_lock_init(&mt9d113_wake_lock, WAKE_LOCK_IDLE, "mt9d113"); } static inline void mt9d113_deinit_suspend(void) { CDBG("%s: entry\n", __func__); wake_lock_destroy(&mt9d113_wake_lock); } static inline void mt9d113_prevent_suspend(void) { CDBG("%s: entry\n", __func__); wake_lock(&mt9d113_wake_lock); } static inline void mt9d113_allow_suspend(void) { CDBG("%s: entry\n", __func__); wake_unlock(&mt9d113_wake_lock); } static int mt9d113_hard_standby(const struct msm_camera_sensor_info *dev, uint32_t on) { int rc; CDBG("%s: entry\n", __func__); rc = gpio_request(dev->sensor_pwd, "mt9d113"); if (0 == rc) { rc = gpio_direction_output(dev->sensor_pwd, on); mdelay(10); } gpio_free(dev->sensor_pwd); return rc; } static int mt9d113_hard_reset(const struct msm_camera_sensor_info *dev) { int rc = 0; CDBG("%s: entry\n", __func__); rc = gpio_request(dev->sensor_reset, "mt9d113"); if (0 == rc) { rc = gpio_direction_output(dev->sensor_reset, 1); mdelay(10); rc = gpio_direction_output(dev->sensor_reset, 0); mdelay(10); rc = gpio_direction_output(dev->sensor_reset, 1); mdelay(10); } gpio_free(dev->sensor_reset); return rc; } static int32_t mt9d113_i2c_txdata(unsigned short saddr, unsigned char *txdata, int length) { struct i2c_msg msg[] = { { .addr = saddr, .flags = 0, .len = length, .buf = txdata, }, }; if (i2c_transfer(mt9d113_client->adapter, msg, 1) < 0) { CCRT("%s: failed!\n", __func__); return -EIO; } return 0; } static int32_t mt9d113_i2c_write(unsigned short saddr, unsigned short waddr, unsigned short wdata, enum mt9d113_width_t width) { int32_t rc = -EFAULT; unsigned char buf[4]; memset(buf, 0, sizeof(buf)); switch (width) { case WORD_LEN: { buf[0] = (waddr & 0xFF00) >> 8; buf[1] = (waddr & 0x00FF); buf[2] = (wdata & 0xFF00) >> 8; buf[3] = (wdata & 0x00FF); rc = mt9d113_i2c_txdata(saddr, buf, 4); } break; case BYTE_LEN: { buf[0] = waddr; buf[1] = wdata; rc = mt9d113_i2c_txdata(saddr, buf, 2); } break; default: { rc = -EFAULT; } break; } if (rc < 0) { CCRT("%s: waddr = 0x%x, wdata = 0x%x, failed!\n", __func__, waddr, wdata); } return rc; } static int32_t mt9d113_i2c_write_table(struct mt9d113_i2c_reg_conf const *reg_conf_tbl, int len) { uint32_t i; int32_t rc = 0; #ifdef MT9D113_SENSOR_PROBE_INIT for (i = 0; i < len; i++) { rc = mt9d113_i2c_write(mt9d113_client->addr, reg_conf_tbl[i].waddr, reg_conf_tbl[i].wdata, reg_conf_tbl[i].width); if (rc < 0) { break; } if (reg_conf_tbl[i].mdelay_time != 0) { mdelay(reg_conf_tbl[i].mdelay_time); } if (0x00 == (!(i | 0xFFFFFFE0) && 0x0F)) { mdelay(1); } } #else if(reg_conf_tbl == mt9d113_regs.prevsnap_tbl) { for (i = 0; i < len; i++) { rc = mt9d113_i2c_write(mt9d113_client->addr, reg_conf_tbl[i].waddr, reg_conf_tbl[i].wdata, reg_conf_tbl[i].width); if (rc < 0) { break; } if (reg_conf_tbl[i].mdelay_time != 0) { mdelay(reg_conf_tbl[i].mdelay_time); } if ((i < (len >> 6)) && (0x00 == (!(i | 0xFFFFFFE0) && 0x0F))) { mdelay(1); } } } else { for (i = 0; i < len; i++) { rc = mt9d113_i2c_write(mt9d113_client->addr, reg_conf_tbl[i].waddr, reg_conf_tbl[i].wdata, reg_conf_tbl[i].width); if (rc < 0) { break; } if (reg_conf_tbl[i].mdelay_time != 0) { mdelay(reg_conf_tbl[i].mdelay_time); } } } #endif return rc; } static int mt9d113_i2c_rxdata(unsigned short saddr, unsigned char *rxdata, int length) { struct i2c_msg msgs[] = { { .addr = saddr, .flags = 0, .len = 2, .buf = rxdata, }, { .addr = saddr, .flags = I2C_M_RD, .len = length, .buf = rxdata, }, }; if (i2c_transfer(mt9d113_client->adapter, msgs, 2) < 0) { CCRT("%s: failed!\n", __func__); return -EIO; } return 0; } static int32_t mt9d113_i2c_read(unsigned short saddr, unsigned short raddr, unsigned short *rdata, enum mt9d113_width_t width) { int32_t rc = 0; unsigned char buf[4]; if (!rdata) { CCRT("%s: rdata points to NULL!\n", __func__); return -EIO; } memset(buf, 0, sizeof(buf)); switch (width) { case WORD_LEN: { buf[0] = (raddr & 0xFF00) >> 8; buf[1] = (raddr & 0x00FF); rc = mt9d113_i2c_rxdata(saddr, buf, 2); if (rc < 0) { return rc; } *rdata = buf[0] << 8 | buf[1]; } break; default: { rc = -EFAULT; } break; } if (rc < 0) { CCRT("%s: failed!\n", __func__); } return rc; } static int32_t __attribute__((unused)) mt9d113_af_trigger(void) { CDBG("%s: not supported!\n", __func__); return 0; } static int32_t mt9d113_set_wb(int8_t wb_mode) { int32_t rc = 0; CDBG("%s: entry: wb_mode=%d\n", __func__, wb_mode); switch (wb_mode) { case CAMERA_WB_MODE_AWB: { rc = mt9d113_i2c_write_table(mt9d113_regs.wb_auto_tbl, mt9d113_regs.wb_auto_tbl_sz); } break; case CAMERA_WB_MODE_SUNLIGHT: { rc = mt9d113_i2c_write_table(mt9d113_regs.wb_daylight_tbl, mt9d113_regs.wb_daylight_tbl_sz); } break; case CAMERA_WB_MODE_INCANDESCENT: { rc = mt9d113_i2c_write_table(mt9d113_regs.wb_incandescent_tbl, mt9d113_regs.wb_incandescent_tbl_sz); } break; case CAMERA_WB_MODE_FLUORESCENT: { rc = mt9d113_i2c_write_table(mt9d113_regs.wb_flourescant_tbl, mt9d113_regs.wb_flourescant_tbl_sz); } break; case CAMERA_WB_MODE_CLOUDY: { rc = mt9d113_i2c_write_table(mt9d113_regs.wb_cloudy_tbl, mt9d113_regs.wb_cloudy_tbl_sz); } break; default: { CCRT("%s: parameter error!\n", __func__); rc = -EFAULT; } } mdelay(100); return rc; } static int32_t mt9d113_set_contrast(int8_t contrast) { int32_t rc = 0; CDBG("%s: entry: contrast=%d\n", __func__, contrast); switch (contrast) { case CAMERA_CONTRAST_0: { rc = mt9d113_i2c_write_table(mt9d113_regs.contrast_tbl[0], mt9d113_regs.contrast_tbl_sz[0]); } break; case CAMERA_CONTRAST_1: { rc = mt9d113_i2c_write_table(mt9d113_regs.contrast_tbl[1], mt9d113_regs.contrast_tbl_sz[1]); } break; case CAMERA_CONTRAST_2: { rc = mt9d113_i2c_write_table(mt9d113_regs.contrast_tbl[2], mt9d113_regs.contrast_tbl_sz[2]); } break; case CAMERA_CONTRAST_3: { rc = mt9d113_i2c_write_table(mt9d113_regs.contrast_tbl[3], mt9d113_regs.contrast_tbl_sz[3]); } break; case CAMERA_CONTRAST_4: { rc = mt9d113_i2c_write_table(mt9d113_regs.contrast_tbl[4], mt9d113_regs.contrast_tbl_sz[4]); } break; default: { CCRT("%s: parameter error!\n", __func__); rc = -EFAULT; } } mdelay(100); return rc; } static int32_t mt9d113_set_brightness(int8_t brightness) { int32_t rc = 0; CCRT("%s: entry: brightness=%d\n", __func__, brightness); switch (brightness) { case CAMERA_BRIGHTNESS_0: { rc = mt9d113_i2c_write_table(mt9d113_regs.brightness_tbl[0], mt9d113_regs.brightness_tbl_sz[0]); } break; case CAMERA_BRIGHTNESS_1: { rc = mt9d113_i2c_write_table(mt9d113_regs.brightness_tbl[1], mt9d113_regs.brightness_tbl_sz[1]); } break; case CAMERA_BRIGHTNESS_2: { rc = mt9d113_i2c_write_table(mt9d113_regs.brightness_tbl[2], mt9d113_regs.brightness_tbl_sz[2]); } break; case CAMERA_BRIGHTNESS_3: { rc = mt9d113_i2c_write_table(mt9d113_regs.brightness_tbl[3], mt9d113_regs.brightness_tbl_sz[3]); } break; case CAMERA_BRIGHTNESS_4: { rc = mt9d113_i2c_write_table(mt9d113_regs.brightness_tbl[4], mt9d113_regs.brightness_tbl_sz[4]); } break; case CAMERA_BRIGHTNESS_5: { rc = mt9d113_i2c_write_table(mt9d113_regs.brightness_tbl[5], mt9d113_regs.brightness_tbl_sz[5]); } break; case CAMERA_BRIGHTNESS_6: { rc = mt9d113_i2c_write_table(mt9d113_regs.brightness_tbl[6], mt9d113_regs.brightness_tbl_sz[6]); } break; default: { CCRT("%s: parameter error!\n", __func__); rc = -EFAULT; } } return rc; } static int32_t mt9d113_set_saturation(int8_t saturation) { int32_t rc = 0; CCRT("%s: entry: saturation=%d\n", __func__, saturation); switch (saturation) { case CAMERA_SATURATION_0: { rc = mt9d113_i2c_write_table(mt9d113_regs.saturation_tbl[0], mt9d113_regs.saturation_tbl_sz[0]); } break; case CAMERA_SATURATION_1: { rc = mt9d113_i2c_write_table(mt9d113_regs.saturation_tbl[1], mt9d113_regs.saturation_tbl_sz[1]); } break; case CAMERA_SATURATION_2: { rc = mt9d113_i2c_write_table(mt9d113_regs.saturation_tbl[2], mt9d113_regs.saturation_tbl_sz[2]); } break; case CAMERA_SATURATION_3: { rc = mt9d113_i2c_write_table(mt9d113_regs.saturation_tbl[3], mt9d113_regs.saturation_tbl_sz[3]); } break; case CAMERA_SATURATION_4: { rc = mt9d113_i2c_write_table(mt9d113_regs.saturation_tbl[4], mt9d113_regs.saturation_tbl_sz[4]); } break; default: { CCRT("%s: parameter error!\n", __func__); rc = -EFAULT; } } mdelay(100); return rc; } static int32_t mt9d113_set_sharpness(int8_t sharpness) { int32_t rc = 0; CDBG("%s: entry: sharpness=%d\n", __func__, sharpness); switch (sharpness) { case CAMERA_SHARPNESS_0: { rc = mt9d113_i2c_write_table(mt9d113_regs.sharpness_tbl[0], mt9d113_regs.sharpness_tbl_sz[0]); } break; case CAMERA_SHARPNESS_1: { rc = mt9d113_i2c_write_table(mt9d113_regs.sharpness_tbl[1], mt9d113_regs.sharpness_tbl_sz[1]); } break; case CAMERA_SHARPNESS_2: { rc = mt9d113_i2c_write_table(mt9d113_regs.sharpness_tbl[2], mt9d113_regs.sharpness_tbl_sz[2]); } break; case CAMERA_SHARPNESS_3: { rc = mt9d113_i2c_write_table(mt9d113_regs.sharpness_tbl[3], mt9d113_regs.sharpness_tbl_sz[3]); } break; case CAMERA_SHARPNESS_4: { rc = mt9d113_i2c_write_table(mt9d113_regs.sharpness_tbl[4], mt9d113_regs.sharpness_tbl_sz[4]); } break; default: { CCRT("%s: parameter error!\n", __func__); rc = -EFAULT; } } return rc; } static int32_t mt9d113_set_iso(int8_t iso_val) { int32_t rc = 0; CDBG("%s: entry: iso_val=%d\n", __func__, iso_val); switch (iso_val) { case CAMERA_ISO_SET_AUTO: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20D, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0020, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20E, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0090, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0006, WORD_LEN); if (rc < 0) { return rc; } mdelay(200); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20D, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0020, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20E, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0090, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; case CAMERA_ISO_SET_HJR: { CCRT("%s: not supported!\n", __func__); rc = -EFAULT; } break; case CAMERA_ISO_SET_100: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20D, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0020, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20E, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0028, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; case CAMERA_ISO_SET_200: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20D, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0040, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20E, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0048, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; case CAMERA_ISO_SET_400: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20D, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0050, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20E, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0080, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; case CAMERA_ISO_SET_800: { CCRT("%s: not supported!\n", __func__); rc = -EFAULT; } break; default: { CCRT("%s: parameter error!\n", __func__); rc = -EFAULT; } } mdelay(100); return rc; } static int32_t mt9d113_set_antibanding(int8_t antibanding) { int32_t rc = 0; CDBG("%s: entry: antibanding=%d\n", __func__, antibanding); switch (antibanding) { case CAMERA_ANTIBANDING_SET_OFF: { CCRT("%s: CAMERA_ANTIBANDING_SET_OFF NOT supported!\n", __func__); } break; case CAMERA_ANTIBANDING_SET_60HZ: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA118, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA11E, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA124, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA12A, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA404, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x00A0, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; case CAMERA_ANTIBANDING_SET_50HZ: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA118, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA11E, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA124, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA12A, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA404, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x00E0, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; case CAMERA_ANTIBANDING_SET_AUTO: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA118, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0001, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA11E, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0001, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA124, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0000, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA12A, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0001, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; default: { CCRT("%s: parameter error!\n", __func__); rc = -EFAULT; } } mdelay(100); return rc; } static int32_t __attribute__((unused))mt9d113_set_lensshading(int8_t lensshading) { #if 0 int32_t rc = 0; uint16_t brightness_lev = 0; CDBG("%s: entry: lensshading=%d\n", __func__, lensshading); if (0 == lensshading) { CCRT("%s: lens shading is disabled!\n", __func__); return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098E, 0x3835, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_read(mt9d113_client->addr, 0x0990, &brightness_lev, WORD_LEN); if (rc < 0) { return rc; } if (brightness_lev < 5) { rc = mt9d113_i2c_write_table(mt9d113_regs.lens_for_outdoor_tbl, mt9d113_regs.lens_for_outdoor_tbl_sz); if (rc < 0) { return rc; } } else { rc = mt9d113_i2c_write_table(mt9d113_regs.lens_for_indoor_tbl, mt9d113_regs.lens_for_indoor_tbl_sz); if (rc < 0) { return rc; } } return rc; #else return 0; #endif } static long mt9d113_set_exposure_compensation(int8_t exposure) { long rc = 0; CDBG("%s: entry: exposure=%d\n", __func__, exposure); switch(exposure) { case CAMERA_EXPOSURE_0: { } break; case CAMERA_EXPOSURE_1: { } break; case CAMERA_EXPOSURE_2: { } break; case CAMERA_EXPOSURE_3: { } break; case CAMERA_EXPOSURE_4: { } break; default: { CCRT("%s: parameter error!\n", __func__); return -EFAULT; } } return rc; } static long mt9d113_reg_init(void) { long rc; CDBG("%s: entry\n", __func__); rc = mt9d113_i2c_write_table(mt9d113_regs.prevsnap_tbl, mt9d113_regs.prevsnap_tbl_sz); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, REG_MT9D113_STANDBY_CONTROL, 0x0028, WORD_LEN); if (rc < 0) { return rc; } mdelay(10); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0006, WORD_LEN); if (rc < 0) { return rc; } mdelay(300); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } return 0; } static long mt9d113_set_sensor_mode(int32_t mode) { long rc = 0; CDBG("%s: entry\n", __func__); switch (mode) { case SENSOR_PREVIEW_MODE: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA115, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0000, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0001, WORD_LEN); if (rc < 0) { return rc; } mdelay(80); } break; case SENSOR_SNAPSHOT_MODE: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA115, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN); if (rc < 0) { return rc; } } break; default: { return -EFAULT; } } return 0; } static long mt9d113_set_effect(int32_t mode, int32_t effect) { uint16_t __attribute__((unused)) reg_addr; uint16_t __attribute__((unused)) reg_val; long rc = 0; switch (mode) { case SENSOR_PREVIEW_MODE: { } break; case SENSOR_SNAPSHOT_MODE: { } break; default: { } break; } switch (effect) { case CAMERA_EFFECT_OFF: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2759, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6440, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x275B, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6440, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; case CAMERA_EFFECT_MONO: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2759, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6441, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x275B, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6441, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; case CAMERA_EFFECT_NEGATIVE: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2759, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6443, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x275B, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6443, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; case CAMERA_EFFECT_SOLARIZE: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2759, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6444, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x275B, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6444, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; case CAMERA_EFFECT_SEPIA: { rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2763, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0xB023, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2759, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6442, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x275B, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6442, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) { return rc; } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN); if (rc < 0) { return rc; } } break; default: { return -EFAULT; } } mdelay(100); return rc; } static long mt9d113_power_up(void) { CDBG("%s: not supported!\n", __func__); return 0; } static long mt9d113_power_down(void) { CDBG("%s: not supported!\n", __func__); return 0; } #if 0 static int mt9d113_power_shutdown(uint32_t on) { int rc; CDBG("%s: entry\n", __func__); rc = gpio_request(MT9D113_GPIO_SHUTDOWN_CTL, "mt9d113"); if (0 == rc) { rc = gpio_direction_output(MT9D113_GPIO_SHUTDOWN_CTL, on); mdelay(1); } gpio_free(MT9D113_GPIO_SHUTDOWN_CTL); return rc; } #endif #if !defined(CONFIG_SENSOR_ADAPTER) static int mt9d113_sensor_init_probe(const struct msm_camera_sensor_info *data) { uint32_t switch_on; int rc = 0; CDBG("%s: entry\n", __func__); #if 0 switch_on = 0; rc = mt9d113_power_shutdown(switch_on); if (rc < 0) { CCRT("enter/quit lowest-power mode failed!\n"); goto init_probe_fail; } #endif switch_on = 0; rc = mt9d113_hard_standby(data, switch_on); if (rc < 0) { CCRT("set standby failed!\n"); goto init_probe_fail; } rc = mt9d113_hard_reset(data); if (rc < 0) { CCRT("hard reset failed!\n"); goto init_probe_fail; } model_id = 0x0000; rc = mt9d113_i2c_read(mt9d113_client->addr, REG_MT9D113_MODEL_ID, &model_id, WORD_LEN); if (rc < 0) { goto init_probe_fail; } CDBG("%s: model_id = 0x%x\n", __func__, model_id); #ifdef CONFIG_SENSOR_INFO msm_sensorinfo_set_sensor_id(model_id); #else #endif if (model_id != MT9D113_MODEL_ID) { rc = -EFAULT; goto init_probe_fail; } rc = mt9d113_i2c_write_table(mt9d113_regs.pll_tbl, mt9d113_regs.pll_tbl_sz); if (rc < 0) { return rc; } model_id = 0x0000; rc = mt9d113_i2c_read(mt9d113_client->addr, REG_MT9D113_MODEL_ID_SUB, &model_id, WORD_LEN); if (rc < 0) { goto init_probe_fail; } CDBG("%s: model_id_sub = 0x%x\n", __func__, model_id); #ifdef CONFIG_SENSOR_INFO msm_sensorinfo_set_sensor_id(model_id); #else #endif if (model_id != MT9D113_MODEL_ID_SUB) { rc = -EFAULT; goto init_probe_fail; } rc = mt9d113_reg_init(); if (rc < 0) { goto init_probe_fail; } return rc; init_probe_fail: CCRT("%s: rc = %d, failed!\n", __func__, rc); return rc; } #else static int mt9d113_sensor_i2c_probe_on(void) { int rc; struct i2c_board_info info; struct i2c_adapter *adapter; struct i2c_client *client; rc = mt9d113_i2c_add_driver(); if (rc < 0) { CCRT("%s: add i2c driver failed!\n", __func__); return rc; } memset(&info, 0, sizeof(struct i2c_board_info)); info.addr = MT9D113_SLAVE_WR_ADDR >> 1; strlcpy(info.type, MT9D113_I2C_BOARD_NAME, I2C_NAME_SIZE); adapter = i2c_get_adapter(MT9D113_I2C_BUS_ID); if (!adapter) { CCRT("%s: get i2c adapter failed!\n", __func__); goto i2c_probe_failed; } client = i2c_new_device(adapter, &info); i2c_put_adapter(adapter); if (!client) { CCRT("%s: add i2c device failed!\n", __func__); goto i2c_probe_failed; } mt9d113_client = client; return 0; i2c_probe_failed: mt9d113_i2c_del_driver(); return -ENODEV; } static void mt9d113_sensor_i2c_probe_off(void) { i2c_unregister_device(mt9d113_client); mt9d113_i2c_del_driver(); } static int mt9d113_sensor_dev_probe(const struct msm_camera_sensor_info *pinfo) { int rc; rc = msm_camera_power_backend(MSM_CAMERA_PWRUP_MODE); if (rc < 0) { CCRT("%s: camera_power_backend failed!\n", __func__); return rc; } #if defined(CONFIG_MACH_R750) || defined(CONFIG_MACH_JOE) rc = msm_camera_clk_switch(pinfo, MT9D113_GPIO_SWITCH_CTL, MT9D113_GPIO_SWITCH_VAL); if (rc < 0) { CCRT("%s: camera_clk_switch failed!\n", __func__); return rc;; } #else #endif msm_camio_clk_rate_set(MT9D113_CAMIO_MCLK); mdelay(5); rc = mt9d113_hard_standby(pinfo, 0); if (rc < 0) { CCRT("set standby failed!\n"); return rc; } rc = mt9d113_hard_reset(pinfo); if (rc < 0) { CCRT("hard reset failed!\n"); return rc; } model_id = 0x0000; rc = mt9d113_i2c_read(mt9d113_client->addr, REG_MT9D113_MODEL_ID, &model_id, WORD_LEN); if (rc < 0) { return rc; } CDBG("%s: model_id = 0x%x\n", __func__, model_id); #ifdef CONFIG_SENSOR_INFO msm_sensorinfo_set_sensor_id(model_id); #else #endif if (model_id != MT9D113_MODEL_ID) { return -EFAULT; } rc = mt9d113_i2c_write_table(mt9d113_regs.pll_tbl, mt9d113_regs.pll_tbl_sz); if (rc < 0) { return rc; } model_id = 0x0000; rc = mt9d113_i2c_read(mt9d113_client->addr, REG_MT9D113_MODEL_ID_SUB, &model_id, WORD_LEN); if (rc < 0) { return rc; } CDBG("%s: model_id_sub = 0x%x\n", __func__, model_id); #ifdef CONFIG_SENSOR_INFO msm_sensorinfo_set_sensor_id(model_id); #else #endif if (model_id != MT9D113_MODEL_ID_SUB) { return -EFAULT; } return 0; } #endif static int mt9d113_sensor_probe_init(const struct msm_camera_sensor_info *data) { int rc; CDBG("%s: entry\n", __func__); if (!data || strcmp(data->sensor_name, "mt9d113")) { CCRT("%s: invalid parameters!\n", __func__); rc = -ENODEV; goto probe_init_fail; } mt9d113_ctrl = kzalloc(sizeof(struct mt9d113_ctrl_t), GFP_KERNEL); if (!mt9d113_ctrl) { CCRT("%s: kzalloc failed!\n", __func__); rc = -ENOMEM; goto probe_init_fail; } mt9d113_ctrl->sensordata = data; #if !defined(CONFIG_SENSOR_ADAPTER) rc = msm_camera_power_backend(MSM_CAMERA_PWRUP_MODE); if (rc < 0) { CCRT("%s: camera_power_backend failed!\n", __func__); goto probe_init_fail; } #if defined(CONFIG_MACH_R750) || defined(CONFIG_MACH_JOE) rc = msm_camera_clk_switch(mt9d113_ctrl->sensordata, MT9D113_GPIO_SWITCH_CTL, MT9D113_GPIO_SWITCH_VAL); if (rc < 0) { CCRT("%s: camera_clk_switch failed!\n", __func__); goto probe_init_fail; } #else #endif msm_camio_clk_rate_set(MT9D113_CAMIO_MCLK); mdelay(5); rc = mt9d113_sensor_init_probe(mt9d113_ctrl->sensordata); if (rc < 0) { CCRT("%s: sensor_init_probe failed!\n", __func__); goto probe_init_fail; } #else rc = mt9d113_sensor_dev_probe(mt9d113_ctrl->sensordata); if (rc < 0) { CCRT("%s: mt9d113_sensor_dev_probe failed!\n", __func__); goto probe_init_fail; } rc = mt9d113_reg_init(); if (rc < 0) { CCRT("%s: mt9d113_reg_init failed!\n", __func__); goto probe_init_fail; } #endif return 0; probe_init_fail: msm_camera_power_backend(MSM_CAMERA_PWRDWN_MODE); if(mt9d113_ctrl) { kfree(mt9d113_ctrl); } return rc; } #ifdef MT9D113_SENSOR_PROBE_INIT static int mt9d113_sensor_init(const struct msm_camera_sensor_info *data) { uint32_t switch_on; int rc; CDBG("%s: entry\n", __func__); if ((NULL == data) || strcmp(data->sensor_name, "mt9d113") || strcmp(mt9d113_ctrl->sensordata->sensor_name, "mt9d113")) { CCRT("%s: data is NULL, or sensor_name is not equal to mt9d113!\n", __func__); rc = -ENODEV; goto sensor_init_fail; } rc = msm_camera_power_backend(MSM_CAMERA_NORMAL_MODE); if (rc < 0) { CCRT("%s: camera_power_backend failed!\n", __func__); goto sensor_init_fail; } msm_camio_clk_rate_set(MT9D113_CAMIO_MCLK); mdelay(5); msm_camio_camif_pad_reg_reset(); mdelay(10); switch_on = 0; rc = mt9d113_hard_standby(mt9d113_ctrl->sensordata, switch_on); if (rc < 0) { CCRT("set standby failed!\n"); goto sensor_init_fail; } mdelay(10); return 0; sensor_init_fail: return rc; } #else static int mt9d113_sensor_init(const struct msm_camera_sensor_info *data) { int rc; rc = mt9d113_sensor_probe_init(data); return rc; } #endif static int mt9d113_sensor_config(void __user *argp) { struct sensor_cfg_data cfg_data; long rc = 0; CDBG("%s: entry\n", __func__); if (copy_from_user(&cfg_data, (void *)argp, sizeof(struct sensor_cfg_data))) { CCRT("%s: copy_from_user failed!\n", __func__); return -EFAULT; } CDBG("%s: cfgtype = %d, mode = %d\n", __func__, cfg_data.cfgtype, cfg_data.mode); switch (cfg_data.cfgtype) { case CFG_SET_MODE: { rc = mt9d113_set_sensor_mode(cfg_data.mode); } break; case CFG_SET_EFFECT: { rc = mt9d113_set_effect(cfg_data.mode, cfg_data.cfg.effect); } break; case CFG_PWR_UP: { rc = mt9d113_power_up(); } break; case CFG_PWR_DOWN: { rc = mt9d113_power_down(); } break; case CFG_SET_WB: { rc = mt9d113_set_wb(cfg_data.cfg.wb_mode); } break; case CFG_SET_AF: { rc = 0; } break; case CFG_SET_ISO: { rc = mt9d113_set_iso(cfg_data.cfg.iso_val); } break; case CFG_SET_ANTIBANDING: { rc = mt9d113_set_antibanding(cfg_data.cfg.antibanding); } break; case CFG_SET_BRIGHTNESS: { rc = mt9d113_set_brightness(cfg_data.cfg.brightness); } break; case CFG_SET_SATURATION: { rc = mt9d113_set_saturation(cfg_data.cfg.saturation); } break; case CFG_SET_CONTRAST: { rc = mt9d113_set_contrast(cfg_data.cfg.contrast); } break; case CFG_SET_SHARPNESS: { rc = mt9d113_set_sharpness(cfg_data.cfg.sharpness); } break; case CFG_SET_LENS_SHADING: { rc = 0; } break; case CFG_SET_EXPOSURE_COMPENSATION: { rc = mt9d113_set_exposure_compensation(cfg_data.cfg.exposure); } break; default: { rc = -EFAULT; } break; } mt9d113_prevent_suspend(); return rc; } #ifdef MT9D113_SENSOR_PROBE_INIT static int mt9d113_sensor_release_internal(void) { int rc; uint32_t switch_on; CDBG("%s: entry\n", __func__); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0028, 0x0000, WORD_LEN); if (rc < 0) { return rc; } mdelay(1); switch_on = 1; rc = mt9d113_hard_standby(mt9d113_ctrl->sensordata, switch_on); if (rc < 0) { return rc; } mdelay(200); rc = msm_camera_power_backend(MSM_CAMERA_STANDBY_MODE); if (rc < 0) { return rc; } return 0; } #else static int mt9d113_sensor_release_internal(void) { int rc; rc = msm_camera_power_backend(MSM_CAMERA_PWRDWN_MODE); kfree(mt9d113_ctrl); return rc; } #endif static int mt9d113_sensor_release(void) { int rc; rc = mt9d113_sensor_release_internal(); mt9d113_allow_suspend(); return rc; } static int mt9d113_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { int rc = 0; CDBG("%s: entry\n", __func__); if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { rc = -ENOTSUPP; goto probe_failure; } mt9d113_sensorw = kzalloc(sizeof(struct mt9d113_work_t), GFP_KERNEL); if (!mt9d113_sensorw) { rc = -ENOMEM; goto probe_failure; } i2c_set_clientdata(client, mt9d113_sensorw); mt9d113_client = client; return 0; probe_failure: kfree(mt9d113_sensorw); mt9d113_sensorw = NULL; CCRT("%s: rc = %d, failed!\n", __func__, rc); return rc; } static int __exit mt9d113_i2c_remove(struct i2c_client *client) { struct mt9d113_work_t *sensorw = i2c_get_clientdata(client); CDBG("%s: entry\n", __func__); free_irq(client->irq, sensorw); kfree(sensorw); mt9d113_deinit_suspend(); mt9d113_client = NULL; mt9d113_sensorw = NULL; return 0; } static const struct i2c_device_id mt9d113_id[] = { { "mt9d113", 0}, { }, }; static struct i2c_driver mt9d113_driver = { .id_table = mt9d113_id, .probe = mt9d113_i2c_probe, .remove = __exit_p(mt9d113_i2c_remove), .driver = { .name = MT9D113_I2C_BOARD_NAME, }, }; static int32_t mt9d113_i2c_add_driver(void) { int32_t rc = 0; rc = i2c_add_driver(&mt9d113_driver); if (IS_ERR_VALUE(rc)) { goto init_failure; } return rc; init_failure: CCRT("%s: rc = %d, failed!\n", __func__, rc); return rc; } static void mt9d113_i2c_del_driver(void) { i2c_del_driver(&mt9d113_driver); } void mt9d113_exit(void) { CDBG("%s: entry\n", __func__); mt9d113_i2c_del_driver(); } int mt9d113_sensor_probe(const struct msm_camera_sensor_info *info, struct msm_sensor_ctrl *s) { int rc; CDBG("%s: entry\n", __func__); #if !defined(CONFIG_SENSOR_ADAPTER) rc = mt9d113_i2c_add_driver(); if (rc < 0) { goto probe_failed; } #else #endif #ifdef MT9D113_SENSOR_PROBE_INIT rc = mt9d113_sensor_probe_init(info); if (rc < 0) { CCRT("%s: mt9d113_sensor_probe_init failed!\n", __func__); goto probe_failed; } rc = mt9d113_sensor_release_internal(); if (rc < 0) { CCRT("%s: mt9d113_sensor_release failed!\n", __func__); goto probe_failed; } #endif mt9d113_init_suspend(); s->s_init = mt9d113_sensor_init; s->s_config = mt9d113_sensor_config; s->s_release = mt9d113_sensor_release; return 0; probe_failed: CCRT("%s: rc = %d, failed!\n", __func__, rc); #if !defined(CONFIG_SENSOR_ADAPTER) mt9d113_i2c_del_driver(); #else #endif return rc; } #if defined(MT9D113_PROBE_WORKQUEUE) static void mt9d113_workqueue(struct work_struct *work) { int32_t rc; #ifdef CONFIG_ZTE_PLATFORM #ifdef CONFIG_ZTE_FTM_FLAG_SUPPORT if(zte_get_ftm_flag()) { return; } #endif #endif if (!pdev_wq) { CCRT("%s: pdev_wq is NULL!\n", __func__); return; } #if !defined(CONFIG_SENSOR_ADAPTER) rc = msm_camera_drv_start(pdev_wq, mt9d113_sensor_probe); #else rc = msm_camera_dev_start(pdev_wq, mt9d113_sensor_i2c_probe_on, mt9d113_sensor_i2c_probe_off, mt9d113_sensor_dev_probe); if (rc < 0) { CCRT("%s: msm_camera_dev_start failed!\n", __func__); goto probe_failed; } rc = msm_camera_drv_start(pdev_wq, mt9d113_sensor_probe); if (rc < 0) { goto probe_failed; } return; probe_failed: CCRT("%s: rc = %d, failed!\n", __func__, rc); msm_camera_power_backend(MSM_CAMERA_PWRDWN_MODE); return; #endif } static int32_t mt9d113_probe_workqueue(void) { int32_t rc; mt9d113_wq = create_singlethread_workqueue("mt9d113_wq"); if (!mt9d113_wq) { CCRT("%s: mt9d113_wq is NULL!\n", __func__); return -EFAULT; } rc = queue_work(mt9d113_wq, &mt9d113_cb_work); return 0; } static int __mt9d113_probe(struct platform_device *pdev) { int32_t rc; pdev_wq = pdev; rc = mt9d113_probe_workqueue(); return rc; } #else static int __mt9d113_probe(struct platform_device *pdev) { #ifdef CONFIG_ZTE_PLATFORM #ifdef CONFIG_ZTE_FTM_FLAG_SUPPORT if(zte_get_ftm_flag()) { return 0; } #endif #endif return msm_camera_drv_start(pdev, mt9d113_sensor_probe); } #endif static struct platform_driver msm_camera_driver = { .probe = __mt9d113_probe, .driver = { .name = "msm_camera_mt9d113", .owner = THIS_MODULE, }, }; static int __init mt9d113_init(void) { return platform_driver_register(&msm_camera_driver); } module_init(mt9d113_init);
ZTE-BLADE/ZTE-BLADE-2.6.32
drivers/media/video/msm/mt9d113_qtech_sunny_socket.c
C
gpl-2.0
56,303
/* * This file contains the RTC driver table for Motorola MCF5206eLITE * ColdFire evaluation board. * * Copyright (C) 2000 OKTET Ltd., St.-Petersburg, Russia * Author: Victor V. Vengerov <vvv@oktet.ru> * * 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. */ #include <bsp.h> #include <libchip/rtc.h> #include <ds1307.h> /* Forward function declaration */ bool mcf5206elite_ds1307_probe(int minor); extern rtc_fns ds1307_fns; /* The following table configures the RTC drivers used in this BSP */ rtc_tbl RTC_Table[] = { { "/dev/rtc", /* sDeviceName */ RTC_CUSTOM, /* deviceType */ &ds1307_fns, /* pDeviceFns */ mcf5206elite_ds1307_probe, /* deviceProbe */ NULL, /* pDeviceParams */ 0x00, /* ulCtrlPort1, for DS1307-I2C bus number */ DS1307_I2C_ADDRESS, /* ulDataPort, for DS1307-I2C device addr */ NULL, /* getRegister - not applicable to DS1307 */ NULL /* setRegister - not applicable to DS1307 */ } }; /* Some information used by the RTC driver */ #define NUM_RTCS (sizeof(RTC_Table)/sizeof(rtc_tbl)) size_t RTC_Count = NUM_RTCS; rtems_device_minor_number RTC_Minor; /* mcf5206elite_ds1307_probe -- * RTC presence probe function. Return TRUE, if device is present. * Device presence checked by probe access to RTC device over I2C bus. * * PARAMETERS: * minor - minor RTC device number * * RETURNS: * TRUE, if RTC device is present */ bool mcf5206elite_ds1307_probe(int minor) { int try = 0; i2c_message_status status; rtc_tbl *rtc; i2c_bus_number bus; i2c_address addr; if (minor >= NUM_RTCS) return false; rtc = RTC_Table + minor; bus = rtc->ulCtrlPort1; addr = rtc->ulDataPort; do { status = i2c_wrbyte(bus, addr, 0); if (status == I2C_NO_DEVICE) return false; try++; } while ((try < 15) && (status != I2C_SUCCESSFUL)); if (status == I2C_SUCCESSFUL) return true; else return false; }
yangxi/omap4m3
c/src/lib/libbsp/m68k/mcf5206elite/tod/todcfg.c
C
gpl-2.0
2,267
/* { dg-do compile } */ /* { dg-options "-O2 -fdump-tree-forwprop2" } */ /* LLVM LOCAL test not applicable */ /* { dg-require-fdump "" } */ class YY { public: YY(const YY &v) { e[0] = v.e[0]; e[1] = v.e[1]; e[2] = v.e[2]; } double &y() { return e[1]; } double e[3]; }; class XX { public: YY direction() const { return v; } YY v; }; int foo(XX& r) { if (r.direction().y() < 0.000001) return 0; return 1; } /* { dg-final { scan-tree-dump-times "&this" 0 "forwprop2" } } */ /* { dg-final { scan-tree-dump-times "&r" 0 "forwprop2" } } */ /* { dg-final { cleanup-tree-dump "forwprop2" } } */
unofficial-opensource-apple/llvmgcc42
gcc/testsuite/g++.dg/tree-ssa/pr14814.C
C++
gpl-2.0
608
/********************************************************************** * $Id$ lpc18xx_qei.c 2011-06-02 *//** * @file lpc18xx_pwr.c * @brief Contains all functions support for QEI firmware library on LPC18xx * @version 1.0 * @date 02. June. 2011 * @author NXP MCU SW Application Team * * Copyright(C) 2011, NXP Semiconductor * All rights reserved. * *********************************************************************** * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * products. This software is supplied "AS IS" without any warranties. * NXP Semiconductors assumes no responsibility or liability for the * use of the software, conveys no license or title under any patent, * copyright, or mask work right to the product. NXP Semiconductors * reserves the right to make changes in the software without * notification. NXP Semiconductors also make no representation or * warranty that such application will be suitable for the specified * use without further testing or modification. **********************************************************************/ /* Peripheral group ----------------------------------------------------------- */ /** @addtogroup QEI * @{ */ /* Includes ------------------------------------------------------------------- */ #include "lpc18xx_qei.h" #include "lpc18xx_cgu.h" /* If this source file built with example, the LPC18xx FW library configuration * file in each example directory ("lpc18xx_libcfg.h") must be included, * otherwise the default FW library configuration file must be included instead */ #ifdef __BUILD_WITH_EXAMPLE__ #include "lpc18xx_libcfg.h" #else #include "lpc18xx_libcfg_default.h" #endif /* __BUILD_WITH_EXAMPLE__ */ #ifdef _QEI /* Private Types -------------------------------------------------------------- */ /** @defgroup QEI_Private_Types QEI Private Types * @{ */ /** * @brief QEI configuration union type definition */ typedef union { QEI_CFG_Type bmQEIConfig; uint32_t ulQEIConfig; } QEI_CFGOPT_Type; /** * @} */ LPC_QEI_Type* QEI_GetPointer(uint8_t qeiId); /* Public Functions ----------------------------------------------------------- */ /** @addtogroup QEI_Public_Functions * @{ */ /*********************************************************************//** * @brief Get the point to typedef of QEI component * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @return None **********************************************************************/ LPC_QEI_Type* QEI_GetPointer(uint8_t qeiId) { LPC_QEI_Type* pQei = NULL; if(qeiId == 0) { pQei = LPC_QEI; } return pQei; } /*********************************************************************//** * @brief Resets value for each type of QEI value, such as velocity, * counter, position, etc.. * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] ulResetType QEI Reset Type, should be one of the following: * - QEI_RESET_POS :Reset Position Counter * - QEI_RESET_POSOnIDX :Reset Position Counter on Index signal * - QEI_RESET_VEL :Reset Velocity * - QEI_RESET_IDX :Reset Index Counter * @return None **********************************************************************/ void QEI_Reset(uint8_t qeiId, uint32_t ulResetType) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); pQei->CON = ulResetType; } /*********************************************************************//** * @brief Initializes the QEI peripheral according to the specified * parameters in the QEI_ConfigStruct. * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] QEI_ConfigStruct Pointer to a QEI_CFG_Type structure * that contains the configuration information for the * specified QEI peripheral * @return None **********************************************************************/ void QEI_Init(uint8_t qeiId, QEI_CFG_Type *QEI_ConfigStruct) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); /* Set up clock and power for QEI module */ // Already enabled by BASE_M3_CLK // Reset all remaining value in QEI peripheral pQei->MAXPOS = 0x00; pQei->CMPOS0 = 0x00; pQei->CMPOS1 = 0x00; pQei->CMPOS2 = 0x00; pQei->INXCMP0 = 0x00; pQei->VELCOMP = 0x00; pQei->LOAD = 0x00; pQei->CON = QEI_CON_RESP | QEI_CON_RESV | QEI_CON_RESI; pQei->FILTERPHA = 0x00; pQei->FILTERPHB = 0x00; pQei->FILTERINX = 0x00; // Disable all Interrupt pQei->IEC = QEI_IECLR_BITMASK; // Clear all Interrupt pending pQei->CLR = QEI_INTCLR_BITMASK; // Set QEI configuration value corresponding to its setting up value pQei->CONF = ((QEI_CFGOPT_Type *)QEI_ConfigStruct)->ulQEIConfig; } /*********************************************************************//** * @brief De-Initalize QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @return None **********************************************************************/ void QEI_DeInit(uint8_t qeiId) { /* Turn off clock and power for QEI module */ } /*****************************************************************************//** * @brief Fills each QIE_InitStruct member with its default value: * - DirectionInvert = QEI_DIRINV_NONE * - SignalMode = QEI_SIGNALMODE_QUAD * - CaptureMode = QEI_CAPMODE_4X * - InvertIndex = QEI_INVINX_NONE * @param[in] QIE_InitStruct Pointer to a QEI_CFG_Type structure which will be * initialized. * @return None *******************************************************************************/ void QEI_GetCfgDefault(QEI_CFG_Type *QIE_InitStruct) { QIE_InitStruct->CaptureMode = QEI_CAPMODE_4X; QIE_InitStruct->DirectionInvert = QEI_DIRINV_NONE; QIE_InitStruct->InvertIndex = QEI_INVINX_NONE; QIE_InitStruct->SignalMode = QEI_SIGNALMODE_QUAD; } /*********************************************************************//** * @brief Check whether if specified flag status is set or not * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] ulFlagType Status Flag Type, should be one of the following: * - QEI_STATUS_DIR: Direction Status * @return New Status of this status flag (SET or RESET) **********************************************************************/ FlagStatus QEI_GetStatus(uint8_t qeiId, uint32_t ulFlagType) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); return ((pQei->STAT & ulFlagType) ? SET : RESET); } /*********************************************************************//** * @brief Get current position value in QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @return Current position value of QEI peripheral **********************************************************************/ uint32_t QEI_GetPosition(uint8_t qeiId) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); return (pQei->POS); } /*********************************************************************//** * @brief Set max position value for QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] ulMaxPos Max position value to set * @return None **********************************************************************/ void QEI_SetMaxPosition(uint8_t qeiId, uint32_t ulMaxPos) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); pQei->MAXPOS = ulMaxPos; } /*********************************************************************//** * @brief Set position compare value for QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] bPosCompCh Compare Position channel, should be: * - QEI_COMPPOS_CH_0 :QEI compare position channel 0 * - QEI_COMPPOS_CH_1 :QEI compare position channel 1 * - QEI_COMPPOS_CH_2 :QEI compare position channel 2 * @param[in] ulPosComp Compare Position value to set * @return None **********************************************************************/ void QEI_SetPositionComp(uint8_t qeiId, uint8_t bPosCompCh, uint32_t ulPosComp) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); uint32_t *tmp; tmp = (uint32_t *) (&(pQei->CMPOS0) + bPosCompCh * 4); *tmp = ulPosComp; } /*********************************************************************//** * @brief Get current index counter of QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @return Current value of QEI index counter **********************************************************************/ uint32_t QEI_GetIndex(uint8_t qeiId) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); return (pQei->INXCNT); } /*********************************************************************//** * @brief Set value for index compare in QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] ulIndexComp Compare Index Value to set * @return None **********************************************************************/ void QEI_SetIndexComp(uint8_t qeiId, uint32_t ulIndexComp) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); pQei->INXCMP0 = ulIndexComp; } /*********************************************************************//** * @brief Set timer reload value for QEI peripheral. When the velocity timer is * over-flow, the value that set for Timer Reload register will be loaded * into the velocity timer for next period. The calculated velocity in RPM * therefore will be affect by this value. * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] QEIReloadStruct QEI reload structure * @return None **********************************************************************/ void QEI_SetTimerReload(uint8_t qeiId, QEI_RELOADCFG_Type *QEIReloadStruct) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); uint64_t pclk; if (QEIReloadStruct->ReloadOption == QEI_TIMERRELOAD_TICKVAL) { pQei->LOAD = QEIReloadStruct->ReloadValue - 1; } else { #if 1 pclk = CGU_GetPCLKFrequency(CGU_PERIPHERAL_M3CORE); pclk = (pclk /(1000000/QEIReloadStruct->ReloadValue)) - 1; pQei->LOAD = (uint32_t)pclk; #else ld = M3Frequency; if (ld/1000000 > 0) { ld /= 1000000; ld *= QEIReloadStruct->ReloadValue; ld -= 1; } else { ld *= QEIReloadStruct->ReloadValue; ld /= 1000000; ld -= 1; } pQei->LOAD = ld; #endif } } /*********************************************************************//** * @brief Get current timer counter in QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @return Current timer counter in QEI peripheral **********************************************************************/ uint32_t QEI_GetTimer(uint8_t qeiId) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); return (pQei->TIME); } /*********************************************************************//** * @brief Get current velocity pulse counter in current time period * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @return Current velocity pulse counter value **********************************************************************/ uint32_t QEI_GetVelocity(uint8_t qeiId) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); return (pQei->VEL); } /*********************************************************************//** * @brief Get the most recently measured velocity of the QEI. When * the Velocity timer in QEI is over-flow, the current velocity * value will be loaded into Velocity Capture register. * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @return The most recently measured velocity value **********************************************************************/ uint32_t QEI_GetVelocityCap(uint8_t qeiId) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); return (pQei->CAP); } /*********************************************************************//** * @brief Set Velocity Compare value for QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] ulVelComp Compare Velocity value to set * @return None **********************************************************************/ void QEI_SetVelocityComp(uint8_t qeiId, uint32_t ulVelComp) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); pQei->VELCOMP = ulVelComp; } /*********************************************************************//** * @brief Set value of sampling count for the digital filter in * QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] ulSamplingPulse Value of sampling count to set * @return None **********************************************************************/ void QEI_SetDigiFilter(uint8_t qeiId, st_Qei_FilterCfg FilterVal) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); pQei->FILTERPHA = FilterVal.PHA_FilterVal; pQei->FILTERPHB = FilterVal.PHB_FilterVal; pQei->FILTERINX = FilterVal.INX_FilterVal; } /*********************************************************************//** * @brief Check whether if specified interrupt flag status in QEI * peripheral is set or not * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] ulIntType Interrupt Flag Status type, should be: * - QEI_INTFLAG_INX_Int : index pulse was detected interrupt * - QEI_INTFLAG_TIM_Int : Velocity timer over flow interrupt * - QEI_INTFLAG_VELC_Int : Capture velocity is less than compare interrupt * - QEI_INTFLAG_DIR_Int : Change of direction interrupt * - QEI_INTFLAG_ERR_Int : An encoder phase error interrupt * - QEI_INTFLAG_ENCLK_Int : An encoder clock pulse was detected interrupt * - QEI_INTFLAG_POS0_Int : position 0 compare value is equal to the current position interrupt * - QEI_INTFLAG_POS1_Int : position 1 compare value is equal to the current position interrupt * - QEI_INTFLAG_POS2_Int : position 2 compare value is equal to the current position interrupt * - QEI_INTFLAG_REV_Int : Index compare value is equal to the current index count interrupt * - QEI_INTFLAG_POS0REV_Int : Combined position 0 and revolution count interrupt * - QEI_INTFLAG_POS1REV_Int : Combined position 1 and revolution count interrupt * - QEI_INTFLAG_POS2REV_Int : Combined position 2 and revolution count interrupt * @return New State of specified interrupt flag status (SET or RESET) **********************************************************************/ FlagStatus QEI_GetIntStatus(uint8_t qeiId, uint32_t ulIntType) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); return((pQei->INTSTAT & ulIntType) ? SET : RESET); } /*********************************************************************//** * @brief Enable/Disable specified interrupt in QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] ulIntType Interrupt Flag Status type, should be: * - QEI_INTFLAG_INX_Int : index pulse was detected interrupt * - QEI_INTFLAG_TIM_Int : Velocity timer over flow interrupt * - QEI_INTFLAG_VELC_Int : Capture velocity is less than compare interrupt * - QEI_INTFLAG_DIR_Int : Change of direction interrupt * - QEI_INTFLAG_ERR_Int : An encoder phase error interrupt * - QEI_INTFLAG_ENCLK_Int : An encoder clock pulse was detected interrupt * - QEI_INTFLAG_POS0_Int : position 0 compare value is equal to the current position interrupt * - QEI_INTFLAG_POS1_Int : position 1 compare value is equal to the current position interrupt * - QEI_INTFLAG_POS2_Int : position 2 compare value is equal to the current position interrupt * - QEI_INTFLAG_REV_Int : Index compare value is equal to the current index count interrupt * - QEI_INTFLAG_POS0REV_Int : Combined position 0 and revolution count interrupt * - QEI_INTFLAG_POS1REV_Int : Combined position 1 and revolution count interrupt * - QEI_INTFLAG_POS2REV_Int : Combined position 2 and revolution count interrupt * @param[in] NewState New function state, should be: * - DISABLE * - ENABLE * @return None **********************************************************************/ void QEI_IntCmd(uint8_t qeiId, uint32_t ulIntType, FunctionalState NewState) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); if (NewState == ENABLE) { pQei->IES = ulIntType; } else { pQei->IEC = ulIntType; } } /*********************************************************************//** * @brief Sets (forces) specified interrupt in QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] ulIntType Interrupt Flag Status type, should be: * - QEI_INTFLAG_INX_Int : index pulse was detected interrupt * - QEI_INTFLAG_TIM_Int : Velocity timer over flow interrupt * - QEI_INTFLAG_VELC_Int : Capture velocity is less than compare interrupt * - QEI_INTFLAG_DIR_Int : Change of direction interrupt * - QEI_INTFLAG_ERR_Int : An encoder phase error interrupt * - QEI_INTFLAG_ENCLK_Int : An encoder clock pulse was detected interrupt * - QEI_INTFLAG_POS0_Int : position 0 compare value is equal to the current position interrupt * - QEI_INTFLAG_POS1_Int : position 1 compare value is equal to the current position interrupt * - QEI_INTFLAG_POS2_Int : position 2 compare value is equal to the current position interrupt * - QEI_INTFLAG_REV_Int : Index compare value is equal to the current index count interrupt * - QEI_INTFLAG_POS0REV_Int : Combined position 0 and revolution count interrupt * - QEI_INTFLAG_POS1REV_Int : Combined position 1 and revolution count interrupt * - QEI_INTFLAG_POS2REV_Int : Combined position 2 and revolution count interrupt * @return None **********************************************************************/ void QEI_IntSet(uint8_t qeiId, uint32_t ulIntType) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); pQei->SET = ulIntType; } /*********************************************************************//** * @brief Clear (force) specified interrupt (pending) in QEI peripheral * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] ulIntType Interrupt Flag Status type, should be: * - QEI_INTFLAG_INX_Int : index pulse was detected interrupt * - QEI_INTFLAG_TIM_Int : Velocity timer over flow interrupt * - QEI_INTFLAG_VELC_Int : Capture velocity is less than compare interrupt * - QEI_INTFLAG_DIR_Int : Change of direction interrupt * - QEI_INTFLAG_ERR_Int : An encoder phase error interrupt * - QEI_INTFLAG_ENCLK_Int : An encoder clock pulse was detected interrupt * - QEI_INTFLAG_POS0_Int : position 0 compare value is equal to the current position interrupt * - QEI_INTFLAG_POS1_Int : position 1 compare value is equal to the current position interrupt * - QEI_INTFLAG_POS2_Int : position 2 compare value is equal to the current position interrupt * - QEI_INTFLAG_REV_Int : Index compare value is equal to the current index count interrupt * - QEI_INTFLAG_POS0REV_Int : Combined position 0 and revolution count interrupt * - QEI_INTFLAG_POS1REV_Int : Combined position 1 and revolution count interrupt * - QEI_INTFLAG_POS2REV_Int : Combined position 2 and revolution count interrupt * @return None **********************************************************************/ void QEI_IntClear(uint8_t qeiId, uint32_t ulIntType) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); pQei->CLR = ulIntType; } /*********************************************************************//** * @brief Calculates the actual velocity in RPM passed via velocity * capture value and Pulse Per Round (of the encoder) value * parameter input. * @param[in] qeiId The Id of the expected QEI component, should be: 0 * @param[in] ulVelCapValue Velocity capture input value that can be * got from QEI_GetVelocityCap() function * @param[in] ulPPR Pulse per round of encoder * @return The actual value of velocity in RPM (Round per minute) **********************************************************************/ uint32_t QEI_CalculateRPM(uint8_t qeiId, uint32_t ulVelCapValue, uint32_t ulPPR) { LPC_QEI_Type* pQei = QEI_GetPointer(qeiId); uint64_t rpm, clock, Load, edges; // Get current Clock rate for timer input clock = CGU_GetPCLKFrequency(CGU_PERIPHERAL_M3CORE); // Get Timer load value (velocity capture period) Load = (uint64_t)(pQei->LOAD + 1); // Get Edge edges = (uint64_t)((pQei->CONF & QEI_CONF_CAPMODE) ? 4 : 2); // Calculate RPM rpm = ((clock * ulVelCapValue * 60) / (Load * ulPPR * edges)); return (uint32_t)(rpm); } /** * @} */ #endif /* _QEI */ /** * @} */ /* --------------------------------- End Of File ------------------------------ */
Lindem-Data-Acquisition-AS/TM4C129-discontinued
libraries/FreeRTOSv8.0.1/FreeRTOS-Plus/Demo/FreeRTOS_Plus_UDP_and_CLI_LPC1830_GCC/ThirdParty/CMSISv2p10_LPC18xx_DriverLib/src/lpc18xx_qei.c
C
gpl-2.0
20,918
/* * Driver O/S-independent utility routines * * $Copyright Open Broadcom Corporation$ * $Id: bcmutils.c,v 1.277.2.18 2011-01-26 02:32:08 $ */ #include <typedefs.h> #include <bcmdefs.h> #include <stdarg.h> #ifdef BCMDRIVER #include <osl.h> #include <bcmutils.h> #include <siutils.h> #if defined(BCMNVRAM) #include <bcmnvram.h> #endif #else /* !BCMDRIVER */ #include <stdio.h> #include <string.h> #include <bcmutils.h> #if defined(BCMEXTSUP) #include <bcm_osl.h> #endif #endif /* !BCMDRIVER */ #include <bcmendian.h> #include <bcmdevs.h> #include <proto/ethernet.h> #include <proto/vlan.h> #include <proto/bcmip.h> #include <proto/802.1d.h> #include <proto/802.11.h> void *_bcmutils_dummy_fn = NULL; #ifdef BCMDRIVER /* copy a pkt buffer chain into a buffer */ uint pktcopy(osl_t *osh, void *p, uint offset, int len, uchar *buf) { uint n, ret = 0; if (len < 0) len = 4096; /* "infinite" */ /* skip 'offset' bytes */ for (; p && offset; p = PKTNEXT(osh, p)) { if (offset < (uint)PKTLEN(osh, p)) break; offset -= PKTLEN(osh, p); } if (!p) return 0; /* copy the data */ for (; p && len; p = PKTNEXT(osh, p)) { n = MIN((uint)PKTLEN(osh, p) - offset, (uint)len); bcopy(PKTDATA(osh, p) + offset, buf, n); buf += n; len -= n; ret += n; offset = 0; } return ret; } /* copy a buffer into a pkt buffer chain */ uint pktfrombuf(osl_t *osh, void *p, uint offset, int len, uchar *buf) { uint n, ret = 0; /* skip 'offset' bytes */ for (; p && offset; p = PKTNEXT(osh, p)) { if (offset < (uint)PKTLEN(osh, p)) break; offset -= PKTLEN(osh, p); } if (!p) return 0; /* copy the data */ for (; p && len; p = PKTNEXT(osh, p)) { n = MIN((uint)PKTLEN(osh, p) - offset, (uint)len); bcopy(buf, PKTDATA(osh, p) + offset, n); buf += n; len -= n; ret += n; offset = 0; } return ret; } /* return total length of buffer chain */ uint BCMFASTPATH pkttotlen(osl_t *osh, void *p) { uint total; total = 0; for (; p; p = PKTNEXT(osh, p)) total += PKTLEN(osh, p); return (total); } /* return the last buffer of chained pkt */ void * pktlast(osl_t *osh, void *p) { for (; PKTNEXT(osh, p); p = PKTNEXT(osh, p)) ; return (p); } /* count segments of a chained packet */ uint BCMFASTPATH pktsegcnt(osl_t *osh, void *p) { uint cnt; for (cnt = 0; p; p = PKTNEXT(osh, p)) cnt++; return cnt; } /* * osl multiple-precedence packet queue * hi_prec is always >= the number of the highest non-empty precedence */ void * BCMFASTPATH pktq_penq(struct pktq *pq, int prec, void *p) { struct pktq_prec *q; ASSERT(prec >= 0 && prec < pq->num_prec); ASSERT(PKTLINK(p) == NULL); /* queueing chains not allowed */ ASSERT(!pktq_full(pq)); ASSERT(!pktq_pfull(pq, prec)); q = &pq->q[prec]; if (q->head) PKTSETLINK(q->tail, p); else q->head = p; q->tail = p; q->len++; pq->len++; if (pq->hi_prec < prec) pq->hi_prec = (uint8)prec; return p; } void * BCMFASTPATH pktq_penq_head(struct pktq *pq, int prec, void *p) { struct pktq_prec *q; ASSERT(prec >= 0 && prec < pq->num_prec); ASSERT(PKTLINK(p) == NULL); /* queueing chains not allowed */ ASSERT(!pktq_full(pq)); ASSERT(!pktq_pfull(pq, prec)); q = &pq->q[prec]; if (q->head == NULL) q->tail = p; PKTSETLINK(p, q->head); q->head = p; q->len++; pq->len++; if (pq->hi_prec < prec) pq->hi_prec = (uint8)prec; return p; } void * BCMFASTPATH pktq_pdeq(struct pktq *pq, int prec) { struct pktq_prec *q; void *p; ASSERT(prec >= 0 && prec < pq->num_prec); q = &pq->q[prec]; if ((p = q->head) == NULL) return NULL; if ((q->head = PKTLINK(p)) == NULL) q->tail = NULL; q->len--; pq->len--; PKTSETLINK(p, NULL); return p; } void * BCMFASTPATH pktq_pdeq_tail(struct pktq *pq, int prec) { struct pktq_prec *q; void *p, *prev; ASSERT(prec >= 0 && prec < pq->num_prec); q = &pq->q[prec]; if ((p = q->head) == NULL) return NULL; for (prev = NULL; p != q->tail; p = PKTLINK(p)) prev = p; if (prev) PKTSETLINK(prev, NULL); else q->head = NULL; q->tail = prev; q->len--; pq->len--; return p; } void pktq_pflush(osl_t *osh, struct pktq *pq, int prec, bool dir, ifpkt_cb_t fn, int arg) { struct pktq_prec *q; void *p, *prev = NULL; q = &pq->q[prec]; p = q->head; while (p) { if (fn == NULL || (*fn)(p, arg)) { bool head = (p == q->head); if (head) q->head = PKTLINK(p); else PKTSETLINK(prev, PKTLINK(p)); PKTSETLINK(p, NULL); PKTFREE(osh, p, dir); q->len--; pq->len--; p = (head ? q->head : PKTLINK(prev)); } else { prev = p; p = PKTLINK(p); } } if (q->head == NULL) { ASSERT(q->len == 0); q->tail = NULL; } } bool BCMFASTPATH pktq_pdel(struct pktq *pq, void *pktbuf, int prec) { struct pktq_prec *q; void *p; ASSERT(prec >= 0 && prec < pq->num_prec); if (!pktbuf) return FALSE; q = &pq->q[prec]; if (q->head == pktbuf) { if ((q->head = PKTLINK(pktbuf)) == NULL) q->tail = NULL; } else { for (p = q->head; p && PKTLINK(p) != pktbuf; p = PKTLINK(p)) ; if (p == NULL) return FALSE; PKTSETLINK(p, PKTLINK(pktbuf)); if (q->tail == pktbuf) q->tail = p; } q->len--; pq->len--; PKTSETLINK(pktbuf, NULL); return TRUE; } void pktq_init(struct pktq *pq, int num_prec, int max_len) { int prec; ASSERT(num_prec > 0 && num_prec <= PKTQ_MAX_PREC); /* pq is variable size; only zero out what's requested */ bzero(pq, OFFSETOF(struct pktq, q) + (sizeof(struct pktq_prec) * num_prec)); pq->num_prec = (uint16)num_prec; pq->max = (uint16)max_len; for (prec = 0; prec < num_prec; prec++) pq->q[prec].max = pq->max; } void * BCMFASTPATH pktq_deq(struct pktq *pq, int *prec_out) { struct pktq_prec *q; void *p; int prec; if (pq->len == 0) return NULL; while ((prec = pq->hi_prec) > 0 && pq->q[prec].head == NULL) pq->hi_prec--; q = &pq->q[prec]; if ((p = q->head) == NULL) return NULL; if ((q->head = PKTLINK(p)) == NULL) q->tail = NULL; q->len--; pq->len--; if (prec_out) *prec_out = prec; PKTSETLINK(p, NULL); return p; } void * BCMFASTPATH pktq_deq_tail(struct pktq *pq, int *prec_out) { struct pktq_prec *q; void *p, *prev; int prec; if (pq->len == 0) return NULL; for (prec = 0; prec < pq->hi_prec; prec++) if (pq->q[prec].head) break; q = &pq->q[prec]; if ((p = q->head) == NULL) return NULL; for (prev = NULL; p != q->tail; p = PKTLINK(p)) prev = p; if (prev) PKTSETLINK(prev, NULL); else q->head = NULL; q->tail = prev; q->len--; pq->len--; if (prec_out) *prec_out = prec; PKTSETLINK(p, NULL); return p; } void * pktq_peek(struct pktq *pq, int *prec_out) { int prec; if (pq->len == 0) return NULL; while ((prec = pq->hi_prec) > 0 && pq->q[prec].head == NULL) pq->hi_prec--; if (prec_out) *prec_out = prec; return (pq->q[prec].head); } void * pktq_peek_tail(struct pktq *pq, int *prec_out) { int prec; if (pq->len == 0) return NULL; for (prec = 0; prec < pq->hi_prec; prec++) if (pq->q[prec].head) break; if (prec_out) *prec_out = prec; return (pq->q[prec].tail); } void pktq_flush(osl_t *osh, struct pktq *pq, bool dir, ifpkt_cb_t fn, int arg) { int prec; for (prec = 0; prec < pq->num_prec; prec++) pktq_pflush(osh, pq, prec, dir, fn, arg); if (fn == NULL) ASSERT(pq->len == 0); } /* Return sum of lengths of a specific set of precedences */ int pktq_mlen(struct pktq *pq, uint prec_bmp) { int prec, len; len = 0; for (prec = 0; prec <= pq->hi_prec; prec++) if (prec_bmp & (1 << prec)) len += pq->q[prec].len; return len; } /* Priority dequeue from a specific set of precedences */ void * BCMFASTPATH pktq_mdeq(struct pktq *pq, uint prec_bmp, int *prec_out) { struct pktq_prec *q; void *p; int prec; if (pq->len == 0) return NULL; while ((prec = pq->hi_prec) > 0 && pq->q[prec].head == NULL) pq->hi_prec--; while ((prec_bmp & (1 << prec)) == 0 || pq->q[prec].head == NULL) if (prec-- == 0) return NULL; q = &pq->q[prec]; if ((p = q->head) == NULL) return NULL; if ((q->head = PKTLINK(p)) == NULL) q->tail = NULL; q->len--; if (prec_out) *prec_out = prec; pq->len--; PKTSETLINK(p, NULL); return p; } #endif /* BCMDRIVER */ const unsigned char bcm_ctype[] = { _BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 0-7 */ _BCM_C, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C, _BCM_C, /* 8-15 */ _BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 16-23 */ _BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 24-31 */ _BCM_S|_BCM_SP,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 32-39 */ _BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 40-47 */ _BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D, /* 48-55 */ _BCM_D,_BCM_D,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 56-63 */ _BCM_P, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U, /* 64-71 */ _BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U, /* 72-79 */ _BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U, /* 80-87 */ _BCM_U,_BCM_U,_BCM_U,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 88-95 */ _BCM_P, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L, /* 96-103 */ _BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L, /* 104-111 */ _BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L, /* 112-119 */ _BCM_L,_BCM_L,_BCM_L,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_C, /* 120-127 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 128-143 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144-159 */ _BCM_S|_BCM_SP, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, /* 160-175 */ _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, /* 176-191 */ _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, /* 192-207 */ _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_P, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_L, /* 208-223 */ _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, /* 224-239 */ _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_P, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L /* 240-255 */ }; ulong BCMROMFN(bcm_strtoul)(char *cp, char **endp, uint base) { ulong result, last_result = 0, value; bool minus; minus = FALSE; while (bcm_isspace(*cp)) cp++; if (cp[0] == '+') cp++; else if (cp[0] == '-') { minus = TRUE; cp++; } if (base == 0) { if (cp[0] == '0') { if ((cp[1] == 'x') || (cp[1] == 'X')) { base = 16; cp = &cp[2]; } else { base = 8; cp = &cp[1]; } } else base = 10; } else if (base == 16 && (cp[0] == '0') && ((cp[1] == 'x') || (cp[1] == 'X'))) { cp = &cp[2]; } result = 0; while (bcm_isxdigit(*cp) && (value = bcm_isdigit(*cp) ? *cp-'0' : bcm_toupper(*cp)-'A'+10) < base) { result = result*base + value; /* Detected overflow */ if (result < last_result && !minus) return (ulong)-1; last_result = result; cp++; } if (minus) result = (ulong)(-(long)result); if (endp) *endp = (char *)cp; return (result); } int BCMROMFN(bcm_atoi)(char *s) { return (int)bcm_strtoul(s, NULL, 10); } /* return pointer to location of substring 'needle' in 'haystack' */ char* BCMROMFN(bcmstrstr)(char *haystack, char *needle) { int len, nlen; int i; if ((haystack == NULL) || (needle == NULL)) return (haystack); nlen = strlen(needle); len = strlen(haystack) - nlen + 1; for (i = 0; i < len; i++) if (memcmp(needle, &haystack[i], nlen) == 0) return (&haystack[i]); return (NULL); } char* BCMROMFN(bcmstrcat)(char *dest, const char *src) { char *p; p = dest + strlen(dest); while ((*p++ = *src++) != '\0') ; return (dest); } char* BCMROMFN(bcmstrncat)(char *dest, const char *src, uint size) { char *endp; char *p; p = dest + strlen(dest); endp = p + size; while (p != endp && (*p++ = *src++) != '\0') ; return (dest); } /**************************************************************************** * Function: bcmstrtok * * Purpose: * Tokenizes a string. This function is conceptually similiar to ANSI C strtok(), * but allows strToken() to be used by different strings or callers at the same * time. Each call modifies '*string' by substituting a NULL character for the * first delimiter that is encountered, and updates 'string' to point to the char * after the delimiter. Leading delimiters are skipped. * * Parameters: * string (mod) Ptr to string ptr, updated by token. * delimiters (in) Set of delimiter characters. * tokdelim (out) Character that delimits the returned token. (May * be set to NULL if token delimiter is not required). * * Returns: Pointer to the next token found. NULL when no more tokens are found. ***************************************************************************** */ char * bcmstrtok(char **string, const char *delimiters, char *tokdelim) { unsigned char *str; unsigned long map[8]; int count; char *nextoken; if (tokdelim != NULL) { /* Prime the token delimiter */ *tokdelim = '\0'; } /* Clear control map */ for (count = 0; count < 8; count++) { map[count] = 0; } /* Set bits in delimiter table */ do { map[*delimiters >> 5] |= (1 << (*delimiters & 31)); } while (*delimiters++); str = (unsigned char*)*string; /* Find beginning of token (skip over leading delimiters). Note that * there is no token iff this loop sets str to point to the terminal * null (*str == '\0') */ while (((map[*str >> 5] & (1 << (*str & 31))) && *str) || (*str == ' ')) { str++; } nextoken = (char*)str; /* Find the end of the token. If it is not the end of the string, * put a null there. */ for (; *str; str++) { if (map[*str >> 5] & (1 << (*str & 31))) { if (tokdelim != NULL) { *tokdelim = *str; } *str++ = '\0'; break; } } *string = (char*)str; /* Determine if a token has been found. */ if (nextoken == (char *) str) { return NULL; } else { return nextoken; } } #define xToLower(C) \ ((C >= 'A' && C <= 'Z') ? (char)((int)C - (int)'A' + (int)'a') : C) /**************************************************************************** * Function: bcmstricmp * * Purpose: Compare to strings case insensitively. * * Parameters: s1 (in) First string to compare. * s2 (in) Second string to compare. * * Returns: Return 0 if the two strings are equal, -1 if t1 < t2 and 1 if * t1 > t2, when ignoring case sensitivity. ***************************************************************************** */ int bcmstricmp(const char *s1, const char *s2) { char dc, sc; while (*s2 && *s1) { dc = xToLower(*s1); sc = xToLower(*s2); if (dc < sc) return -1; if (dc > sc) return 1; s1++; s2++; } if (*s1 && !*s2) return 1; if (!*s1 && *s2) return -1; return 0; } /**************************************************************************** * Function: bcmstrnicmp * * Purpose: Compare to strings case insensitively, upto a max of 'cnt' * characters. * * Parameters: s1 (in) First string to compare. * s2 (in) Second string to compare. * cnt (in) Max characters to compare. * * Returns: Return 0 if the two strings are equal, -1 if t1 < t2 and 1 if * t1 > t2, when ignoring case sensitivity. ***************************************************************************** */ int bcmstrnicmp(const char* s1, const char* s2, int cnt) { char dc, sc; while (*s2 && *s1 && cnt) { dc = xToLower(*s1); sc = xToLower(*s2); if (dc < sc) return -1; if (dc > sc) return 1; s1++; s2++; cnt--; } if (!cnt) return 0; if (*s1 && !*s2) return 1; if (!*s1 && *s2) return -1; return 0; } /* parse a xx:xx:xx:xx:xx:xx format ethernet address */ int BCMROMFN(bcm_ether_atoe)(char *p, struct ether_addr *ea) { int i = 0; for (;;) { ea->octet[i++] = (char) bcm_strtoul(p, &p, 16); if (!*p++ || i == 6) break; } return (i == 6); } #if defined(CONFIG_USBRNDIS_RETAIL) || defined(NDIS_MINIPORT_DRIVER) /* registry routine buffer preparation utility functions: * parameter order is like strncpy, but returns count * of bytes copied. Minimum bytes copied is null char(1)/wchar(2) */ ulong wchar2ascii(char *abuf, ushort *wbuf, ushort wbuflen, ulong abuflen) { ulong copyct = 1; ushort i; if (abuflen == 0) return 0; /* wbuflen is in bytes */ wbuflen /= sizeof(ushort); for (i = 0; i < wbuflen; ++i) { if (--abuflen == 0) break; *abuf++ = (char) *wbuf++; ++copyct; } *abuf = '\0'; return copyct; } #endif /* CONFIG_USBRNDIS_RETAIL || NDIS_MINIPORT_DRIVER */ char * bcm_ether_ntoa(const struct ether_addr *ea, char *buf) { static const char template[] = "%02x:%02x:%02x:%02x:%02x:%02x"; snprintf(buf, 18, template, ea->octet[0]&0xff, ea->octet[1]&0xff, ea->octet[2]&0xff, ea->octet[3]&0xff, ea->octet[4]&0xff, ea->octet[5]&0xff); return (buf); } char * bcm_ip_ntoa(struct ipv4_addr *ia, char *buf) { snprintf(buf, 16, "%d.%d.%d.%d", ia->addr[0], ia->addr[1], ia->addr[2], ia->addr[3]); return (buf); } #ifdef BCMDRIVER void bcm_mdelay(uint ms) { uint i; for (i = 0; i < ms; i++) { OSL_DELAY(1000); } } #if defined(DHD_DEBUG) /* pretty hex print a pkt buffer chain */ void prpkt(const char *msg, osl_t *osh, void *p0) { void *p; if (msg && (msg[0] != '\0')) printf("%s:\n", msg); for (p = p0; p; p = PKTNEXT(osh, p)) prhex(NULL, PKTDATA(osh, p), PKTLEN(osh, p)); } #endif /* Takes an Ethernet frame and sets out-of-bound PKTPRIO. * Also updates the inplace vlan tag if requested. * For debugging, it returns an indication of what it did. */ uint BCMFASTPATH pktsetprio(void *pkt, bool update_vtag) { struct ether_header *eh; struct ethervlan_header *evh; uint8 *pktdata; int priority = 0; int rc = 0; pktdata = (uint8 *) PKTDATA(NULL, pkt); ASSERT(ISALIGNED((uintptr)pktdata, sizeof(uint16))); eh = (struct ether_header *) pktdata; if (ntoh16(eh->ether_type) == ETHER_TYPE_8021Q) { uint16 vlan_tag; int vlan_prio, dscp_prio = 0; evh = (struct ethervlan_header *)eh; vlan_tag = ntoh16(evh->vlan_tag); vlan_prio = (int) (vlan_tag >> VLAN_PRI_SHIFT) & VLAN_PRI_MASK; if (ntoh16(evh->ether_type) == ETHER_TYPE_IP) { uint8 *ip_body = pktdata + sizeof(struct ethervlan_header); uint8 tos_tc = IP_TOS46(ip_body); dscp_prio = (int)(tos_tc >> IPV4_TOS_PREC_SHIFT); } /* DSCP priority gets precedence over 802.1P (vlan tag) */ if (dscp_prio != 0) { priority = dscp_prio; rc |= PKTPRIO_VDSCP; } else { priority = vlan_prio; rc |= PKTPRIO_VLAN; } /* * If the DSCP priority is not the same as the VLAN priority, * then overwrite the priority field in the vlan tag, with the * DSCP priority value. This is required for Linux APs because * the VLAN driver on Linux, overwrites the skb->priority field * with the priority value in the vlan tag */ if (update_vtag && (priority != vlan_prio)) { vlan_tag &= ~(VLAN_PRI_MASK << VLAN_PRI_SHIFT); vlan_tag |= (uint16)priority << VLAN_PRI_SHIFT; evh->vlan_tag = hton16(vlan_tag); rc |= PKTPRIO_UPD; } } else if (ntoh16(eh->ether_type) == ETHER_TYPE_IP) { uint8 *ip_body = pktdata + sizeof(struct ether_header); uint8 tos_tc = IP_TOS46(ip_body); priority = (int)(tos_tc >> IPV4_TOS_PREC_SHIFT); rc |= PKTPRIO_DSCP; } ASSERT(priority >= 0 && priority <= MAXPRIO); PKTSETPRIO(pkt, priority); return (rc | priority); } static char bcm_undeferrstr[32]; static const char *bcmerrorstrtable[] = BCMERRSTRINGTABLE; /* Convert the error codes into related error strings */ const char * bcmerrorstr(int bcmerror) { /* check if someone added a bcmerror code but forgot to add errorstring */ ASSERT(ABS(BCME_LAST) == (ARRAYSIZE(bcmerrorstrtable) - 1)); if (bcmerror > 0 || bcmerror < BCME_LAST) { snprintf(bcm_undeferrstr, sizeof(bcm_undeferrstr), "Undefined error %d", bcmerror); return bcm_undeferrstr; } ASSERT(strlen(bcmerrorstrtable[-bcmerror]) < BCME_STRLEN); return bcmerrorstrtable[-bcmerror]; } /* iovar table lookup */ const bcm_iovar_t* bcm_iovar_lookup(const bcm_iovar_t *table, const char *name) { const bcm_iovar_t *vi; const char *lookup_name; /* skip any ':' delimited option prefixes */ lookup_name = strrchr(name, ':'); if (lookup_name != NULL) lookup_name++; else lookup_name = name; ASSERT(table != NULL); for (vi = table; vi->name; vi++) { if (!strcmp(vi->name, lookup_name)) return vi; } /* ran to end of table */ return NULL; /* var name not found */ } int bcm_iovar_lencheck(const bcm_iovar_t *vi, void *arg, int len, bool set) { int bcmerror = 0; /* length check on io buf */ switch (vi->type) { case IOVT_BOOL: case IOVT_INT8: case IOVT_INT16: case IOVT_INT32: case IOVT_UINT8: case IOVT_UINT16: case IOVT_UINT32: /* all integers are int32 sized args at the ioctl interface */ if (len < (int)sizeof(int)) { bcmerror = BCME_BUFTOOSHORT; } break; case IOVT_BUFFER: /* buffer must meet minimum length requirement */ if (len < vi->minlen) { bcmerror = BCME_BUFTOOSHORT; } break; case IOVT_VOID: if (!set) { /* Cannot return nil... */ bcmerror = BCME_UNSUPPORTED; } else if (len) { /* Set is an action w/o parameters */ bcmerror = BCME_BUFTOOLONG; } break; default: /* unknown type for length check in iovar info */ ASSERT(0); bcmerror = BCME_UNSUPPORTED; } return bcmerror; } #endif /* BCMDRIVER */ /******************************************************************************* * crc8 * * Computes a crc8 over the input data using the polynomial: * * x^8 + x^7 +x^6 + x^4 + x^2 + 1 * * The caller provides the initial value (either CRC8_INIT_VALUE * or the previous returned value) to allow for processing of * discontiguous blocks of data. When generating the CRC the * caller is responsible for complementing the final return value * and inserting it into the byte stream. When checking, a final * return value of CRC8_GOOD_VALUE indicates a valid CRC. * * Reference: Dallas Semiconductor Application Note 27 * Williams, Ross N., "A Painless Guide to CRC Error Detection Algorithms", * ver 3, Aug 1993, ross@guest.adelaide.edu.au, Rocksoft Pty Ltd., * ftp://ftp.rocksoft.com/clients/rocksoft/papers/crc_v3.txt * * **************************************************************************** */ static const uint8 crc8_table[256] = { 0x00, 0xF7, 0xB9, 0x4E, 0x25, 0xD2, 0x9C, 0x6B, 0x4A, 0xBD, 0xF3, 0x04, 0x6F, 0x98, 0xD6, 0x21, 0x94, 0x63, 0x2D, 0xDA, 0xB1, 0x46, 0x08, 0xFF, 0xDE, 0x29, 0x67, 0x90, 0xFB, 0x0C, 0x42, 0xB5, 0x7F, 0x88, 0xC6, 0x31, 0x5A, 0xAD, 0xE3, 0x14, 0x35, 0xC2, 0x8C, 0x7B, 0x10, 0xE7, 0xA9, 0x5E, 0xEB, 0x1C, 0x52, 0xA5, 0xCE, 0x39, 0x77, 0x80, 0xA1, 0x56, 0x18, 0xEF, 0x84, 0x73, 0x3D, 0xCA, 0xFE, 0x09, 0x47, 0xB0, 0xDB, 0x2C, 0x62, 0x95, 0xB4, 0x43, 0x0D, 0xFA, 0x91, 0x66, 0x28, 0xDF, 0x6A, 0x9D, 0xD3, 0x24, 0x4F, 0xB8, 0xF6, 0x01, 0x20, 0xD7, 0x99, 0x6E, 0x05, 0xF2, 0xBC, 0x4B, 0x81, 0x76, 0x38, 0xCF, 0xA4, 0x53, 0x1D, 0xEA, 0xCB, 0x3C, 0x72, 0x85, 0xEE, 0x19, 0x57, 0xA0, 0x15, 0xE2, 0xAC, 0x5B, 0x30, 0xC7, 0x89, 0x7E, 0x5F, 0xA8, 0xE6, 0x11, 0x7A, 0x8D, 0xC3, 0x34, 0xAB, 0x5C, 0x12, 0xE5, 0x8E, 0x79, 0x37, 0xC0, 0xE1, 0x16, 0x58, 0xAF, 0xC4, 0x33, 0x7D, 0x8A, 0x3F, 0xC8, 0x86, 0x71, 0x1A, 0xED, 0xA3, 0x54, 0x75, 0x82, 0xCC, 0x3B, 0x50, 0xA7, 0xE9, 0x1E, 0xD4, 0x23, 0x6D, 0x9A, 0xF1, 0x06, 0x48, 0xBF, 0x9E, 0x69, 0x27, 0xD0, 0xBB, 0x4C, 0x02, 0xF5, 0x40, 0xB7, 0xF9, 0x0E, 0x65, 0x92, 0xDC, 0x2B, 0x0A, 0xFD, 0xB3, 0x44, 0x2F, 0xD8, 0x96, 0x61, 0x55, 0xA2, 0xEC, 0x1B, 0x70, 0x87, 0xC9, 0x3E, 0x1F, 0xE8, 0xA6, 0x51, 0x3A, 0xCD, 0x83, 0x74, 0xC1, 0x36, 0x78, 0x8F, 0xE4, 0x13, 0x5D, 0xAA, 0x8B, 0x7C, 0x32, 0xC5, 0xAE, 0x59, 0x17, 0xE0, 0x2A, 0xDD, 0x93, 0x64, 0x0F, 0xF8, 0xB6, 0x41, 0x60, 0x97, 0xD9, 0x2E, 0x45, 0xB2, 0xFC, 0x0B, 0xBE, 0x49, 0x07, 0xF0, 0x9B, 0x6C, 0x22, 0xD5, 0xF4, 0x03, 0x4D, 0xBA, 0xD1, 0x26, 0x68, 0x9F }; #define CRC_INNER_LOOP(n, c, x) \ (c) = ((c) >> 8) ^ crc##n##_table[((c) ^ (x)) & 0xff] uint8 BCMROMFN(hndcrc8)( uint8 *pdata, /* pointer to array of data to process */ uint nbytes, /* number of input data bytes to process */ uint8 crc /* either CRC8_INIT_VALUE or previous return value */ ) { /* hard code the crc loop instead of using CRC_INNER_LOOP macro * to avoid the undefined and unnecessary (uint8 >> 8) operation. */ while (nbytes-- > 0) crc = crc8_table[(crc ^ *pdata++) & 0xff]; return crc; } /******************************************************************************* * crc16 * * Computes a crc16 over the input data using the polynomial: * * x^16 + x^12 +x^5 + 1 * * The caller provides the initial value (either CRC16_INIT_VALUE * or the previous returned value) to allow for processing of * discontiguous blocks of data. When generating the CRC the * caller is responsible for complementing the final return value * and inserting it into the byte stream. When checking, a final * return value of CRC16_GOOD_VALUE indicates a valid CRC. * * Reference: Dallas Semiconductor Application Note 27 * Williams, Ross N., "A Painless Guide to CRC Error Detection Algorithms", * ver 3, Aug 1993, ross@guest.adelaide.edu.au, Rocksoft Pty Ltd., * ftp://ftp.rocksoft.com/clients/rocksoft/papers/crc_v3.txt * * **************************************************************************** */ static const uint16 crc16_table[256] = { 0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF, 0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7, 0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E, 0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876, 0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD, 0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5, 0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C, 0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974, 0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB, 0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3, 0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A, 0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72, 0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9, 0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1, 0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738, 0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70, 0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7, 0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF, 0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036, 0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E, 0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5, 0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD, 0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134, 0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C, 0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3, 0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB, 0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232, 0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A, 0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1, 0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9, 0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330, 0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78 }; uint16 BCMROMFN(hndcrc16)( uint8 *pdata, /* pointer to array of data to process */ uint nbytes, /* number of input data bytes to process */ uint16 crc /* either CRC16_INIT_VALUE or previous return value */ ) { while (nbytes-- > 0) CRC_INNER_LOOP(16, crc, *pdata++); return crc; } static const uint32 crc32_table[256] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; /* * crc input is CRC32_INIT_VALUE for a fresh start, or previous return value if * accumulating over multiple pieces. */ uint32 BCMROMFN(hndcrc32)(uint8 *pdata, uint nbytes, uint32 crc) { uint8 *pend; #ifdef __mips__ uint8 tmp[4]; ulong *tptr = (ulong *)tmp; /* in case the beginning of the buffer isn't aligned */ pend = (uint8 *)((uint)(pdata + 3) & 0xfffffffc); nbytes -= (pend - pdata); while (pdata < pend) CRC_INNER_LOOP(32, crc, *pdata++); /* handle bulk of data as 32-bit words */ pend = pdata + (nbytes & 0xfffffffc); while (pdata < pend) { *tptr = *(ulong *)pdata; pdata += sizeof(ulong *); CRC_INNER_LOOP(32, crc, tmp[0]); CRC_INNER_LOOP(32, crc, tmp[1]); CRC_INNER_LOOP(32, crc, tmp[2]); CRC_INNER_LOOP(32, crc, tmp[3]); } /* 1-3 bytes at end of buffer */ pend = pdata + (nbytes & 0x03); while (pdata < pend) CRC_INNER_LOOP(32, crc, *pdata++); #else pend = pdata + nbytes; while (pdata < pend) CRC_INNER_LOOP(32, crc, *pdata++); #endif /* __mips__ */ return crc; } #ifdef notdef #define CLEN 1499 /* CRC Length */ #define CBUFSIZ (CLEN+4) #define CNBUFS 5 /* # of bufs */ void testcrc32(void) { uint j, k, l; uint8 *buf; uint len[CNBUFS]; uint32 crcr; uint32 crc32tv[CNBUFS] = {0xd2cb1faa, 0xd385c8fa, 0xf5b4f3f3, 0x55789e20, 0x00343110}; ASSERT((buf = MALLOC(CBUFSIZ*CNBUFS)) != NULL); /* step through all possible alignments */ for (l = 0; l <= 4; l++) { for (j = 0; j < CNBUFS; j++) { len[j] = CLEN; for (k = 0; k < len[j]; k++) *(buf + j*CBUFSIZ + (k+l)) = (j+k) & 0xff; } for (j = 0; j < CNBUFS; j++) { crcr = crc32(buf + j*CBUFSIZ + l, len[j], CRC32_INIT_VALUE); ASSERT(crcr == crc32tv[j]); } } MFREE(buf, CBUFSIZ*CNBUFS); return; } #endif /* notdef */ /* * Advance from the current 1-byte tag/1-byte length/variable-length value * triple, to the next, returning a pointer to the next. * If the current or next TLV is invalid (does not fit in given buffer length), * NULL is returned. * *buflen is not modified if the TLV elt parameter is invalid, or is decremented * by the TLV parameter's length if it is valid. */ bcm_tlv_t * BCMROMFN(bcm_next_tlv)(bcm_tlv_t *elt, int *buflen) { int len; /* validate current elt */ if (!bcm_valid_tlv(elt, *buflen)) return NULL; /* advance to next elt */ len = elt->len; elt = (bcm_tlv_t*)(elt->data + len); *buflen -= (2 + len); /* validate next elt */ if (!bcm_valid_tlv(elt, *buflen)) return NULL; return elt; } /* * Traverse a string of 1-byte tag/1-byte length/variable-length value * triples, returning a pointer to the substring whose first element * matches tag */ bcm_tlv_t * BCMROMFN(bcm_parse_tlvs)(void *buf, int buflen, uint key) { bcm_tlv_t *elt; int totlen; elt = (bcm_tlv_t*)buf; totlen = buflen; /* find tagged parameter */ while (totlen >= 2) { int len = elt->len; /* validate remaining totlen */ if ((elt->id == key) && (totlen >= (len + 2))) return (elt); elt = (bcm_tlv_t*)((uint8*)elt + (len + 2)); totlen -= (len + 2); } return NULL; } /* * Traverse a string of 1-byte tag/1-byte length/variable-length value * triples, returning a pointer to the substring whose first element * matches tag. Stop parsing when we see an element whose ID is greater * than the target key. */ bcm_tlv_t * BCMROMFN(bcm_parse_ordered_tlvs)(void *buf, int buflen, uint key) { bcm_tlv_t *elt; int totlen; elt = (bcm_tlv_t*)buf; totlen = buflen; /* find tagged parameter */ while (totlen >= 2) { uint id = elt->id; int len = elt->len; /* Punt if we start seeing IDs > than target key */ if (id > key) return (NULL); /* validate remaining totlen */ if ((id == key) && (totlen >= (len + 2))) return (elt); elt = (bcm_tlv_t*)((uint8*)elt + (len + 2)); totlen -= (len + 2); } return NULL; } #if defined(WLMSG_PRHDRS) || defined(WLMSG_PRPKT) || defined(WLMSG_ASSOC) || \ defined(DHD_DEBUG) int bcm_format_flags(const bcm_bit_desc_t *bd, uint32 flags, char* buf, int len) { int i; char* p = buf; char hexstr[16]; int slen = 0, nlen = 0; uint32 bit; const char* name; if (len < 2 || !buf) return 0; buf[0] = '\0'; for (i = 0; flags != 0; i++) { bit = bd[i].bit; name = bd[i].name; if (bit == 0 && flags != 0) { /* print any unnamed bits */ snprintf(hexstr, 16, "0x%X", flags); name = hexstr; flags = 0; /* exit loop */ } else if ((flags & bit) == 0) continue; flags &= ~bit; nlen = strlen(name); slen += nlen; /* count btwn flag space */ if (flags != 0) slen += 1; /* need NULL char as well */ if (len <= slen) break; /* copy NULL char but don't count it */ strncpy(p, name, nlen + 1); p += nlen; /* copy btwn flag space and NULL char */ if (flags != 0) p += snprintf(p, 2, " "); len -= slen; } /* indicate the str was too short */ if (flags != 0) { if (len < 2) p -= 2 - len; /* overwrite last char */ p += snprintf(p, 2, ">"); } return (int)(p - buf); } #endif #if defined(WLMSG_PRHDRS) || defined(WLMSG_PRPKT) || defined(WLMSG_ASSOC) || \ defined(DHD_DEBUG) || defined(WLMEDIA_PEAKRATE) /* print bytes formatted as hex to a string. return the resulting string length */ int bcm_format_hex(char *str, const void *bytes, int len) { int i; char *p = str; const uint8 *src = (const uint8*)bytes; for (i = 0; i < len; i++) { p += snprintf(p, 3, "%02X", *src); src++; } return (int)(p - str); } #endif /* pretty hex print a contiguous buffer */ void prhex(const char *msg, uchar *buf, uint nbytes) { char line[128], *p; int len = sizeof(line); int nchar; uint i; if (msg && (msg[0] != '\0')) printf("%s:\n", msg); p = line; for (i = 0; i < nbytes; i++) { if (i % 16 == 0) { nchar = snprintf(p, len, " %04d: ", i); /* line prefix */ p += nchar; len -= nchar; } if (len > 0) { nchar = snprintf(p, len, "%02x ", buf[i]); p += nchar; len -= nchar; } if (i % 16 == 15) { printf("%s\n", line); /* flush line */ p = line; len = sizeof(line); } } /* flush last partial line */ if (p != line) printf("%s\n", line); } static const char *crypto_algo_names[] = { "NONE", "WEP1", "TKIP", "WEP128", "AES_CCM", "AES_OCB_MSDU", "AES_OCB_MPDU", "NALG" "UNDEF", "UNDEF", "UNDEF", #ifdef BCMWAPI_WPI "WAPI", #endif /* BCMWAPI_WPI */ "UNDEF" }; const char * bcm_crypto_algo_name(uint algo) { return (algo < ARRAYSIZE(crypto_algo_names)) ? crypto_algo_names[algo] : "ERR"; } char * bcm_chipname(uint chipid, char *buf, uint len) { const char *fmt; fmt = ((chipid > 0xa000) || (chipid < 0x4000)) ? "%d" : "%x"; snprintf(buf, len, fmt, chipid); return buf; } /* Produce a human-readable string for boardrev */ char * bcm_brev_str(uint32 brev, char *buf) { if (brev < 0x100) snprintf(buf, 8, "%d.%d", (brev & 0xf0) >> 4, brev & 0xf); else snprintf(buf, 8, "%c%03x", ((brev & 0xf000) == 0x1000) ? 'P' : 'A', brev & 0xfff); return (buf); } #define BUFSIZE_TODUMP_ATONCE 512 /* Buffer size */ /* dump large strings to console */ void printbig(char *buf) { uint len, max_len; char c; len = strlen(buf); max_len = BUFSIZE_TODUMP_ATONCE; while (len > max_len) { c = buf[max_len]; buf[max_len] = '\0'; printf("%s", buf); buf[max_len] = c; buf += max_len; len -= max_len; } /* print the remaining string */ printf("%s\n", buf); return; } /* routine to dump fields in a fileddesc structure */ uint bcmdumpfields(bcmutl_rdreg_rtn read_rtn, void *arg0, uint arg1, struct fielddesc *fielddesc_array, char *buf, uint32 bufsize) { uint filled_len; int len; struct fielddesc *cur_ptr; filled_len = 0; cur_ptr = fielddesc_array; while (bufsize > 1) { if (cur_ptr->nameandfmt == NULL) break; len = snprintf(buf, bufsize, cur_ptr->nameandfmt, read_rtn(arg0, arg1, cur_ptr->offset)); /* check for snprintf overflow or error */ if (len < 0 || (uint32)len >= bufsize) len = bufsize - 1; buf += len; bufsize -= len; filled_len += len; cur_ptr++; } return filled_len; } uint bcm_mkiovar(char *name, char *data, uint datalen, char *buf, uint buflen) { uint len; len = strlen(name) + 1; if ((len + datalen) > buflen) return 0; strncpy(buf, name, buflen); /* append data onto the end of the name string */ memcpy(&buf[len], data, datalen); len += datalen; return len; } /* Quarter dBm units to mW * Table starts at QDBM_OFFSET, so the first entry is mW for qdBm=153 * Table is offset so the last entry is largest mW value that fits in * a uint16. */ #define QDBM_OFFSET 153 /* Offset for first entry */ #define QDBM_TABLE_LEN 40 /* Table size */ /* Smallest mW value that will round up to the first table entry, QDBM_OFFSET. * Value is ( mW(QDBM_OFFSET - 1) + mW(QDBM_OFFSET) ) / 2 */ #define QDBM_TABLE_LOW_BOUND 6493 /* Low bound */ /* Largest mW value that will round down to the last table entry, * QDBM_OFFSET + QDBM_TABLE_LEN-1. * Value is ( mW(QDBM_OFFSET + QDBM_TABLE_LEN - 1) + mW(QDBM_OFFSET + QDBM_TABLE_LEN) ) / 2. */ #define QDBM_TABLE_HIGH_BOUND 64938 /* High bound */ static const uint16 nqdBm_to_mW_map[QDBM_TABLE_LEN] = { /* qdBm: +0 +1 +2 +3 +4 +5 +6 +7 */ /* 153: */ 6683, 7079, 7499, 7943, 8414, 8913, 9441, 10000, /* 161: */ 10593, 11220, 11885, 12589, 13335, 14125, 14962, 15849, /* 169: */ 16788, 17783, 18836, 19953, 21135, 22387, 23714, 25119, /* 177: */ 26607, 28184, 29854, 31623, 33497, 35481, 37584, 39811, /* 185: */ 42170, 44668, 47315, 50119, 53088, 56234, 59566, 63096 }; uint16 BCMROMFN(bcm_qdbm_to_mw)(uint8 qdbm) { uint factor = 1; int idx = qdbm - QDBM_OFFSET; if (idx >= QDBM_TABLE_LEN) { /* clamp to max uint16 mW value */ return 0xFFFF; } /* scale the qdBm index up to the range of the table 0-40 * where an offset of 40 qdBm equals a factor of 10 mW. */ while (idx < 0) { idx += 40; factor *= 10; } /* return the mW value scaled down to the correct factor of 10, * adding in factor/2 to get proper rounding. */ return ((nqdBm_to_mW_map[idx] + factor/2) / factor); } uint8 BCMROMFN(bcm_mw_to_qdbm)(uint16 mw) { uint8 qdbm; int offset; uint mw_uint = mw; uint boundary; /* handle boundary case */ if (mw_uint <= 1) return 0; offset = QDBM_OFFSET; /* move mw into the range of the table */ while (mw_uint < QDBM_TABLE_LOW_BOUND) { mw_uint *= 10; offset -= 40; } for (qdbm = 0; qdbm < QDBM_TABLE_LEN-1; qdbm++) { boundary = nqdBm_to_mW_map[qdbm] + (nqdBm_to_mW_map[qdbm+1] - nqdBm_to_mW_map[qdbm])/2; if (mw_uint < boundary) break; } qdbm += (uint8)offset; return (qdbm); } uint BCMROMFN(bcm_bitcount)(uint8 *bitmap, uint length) { uint bitcount = 0, i; uint8 tmp; for (i = 0; i < length; i++) { tmp = bitmap[i]; while (tmp) { bitcount++; tmp &= (tmp - 1); } } return bitcount; } #ifdef BCMDRIVER /* Initialization of bcmstrbuf structure */ void bcm_binit(struct bcmstrbuf *b, char *buf, uint size) { b->origsize = b->size = size; b->origbuf = b->buf = buf; } /* Buffer sprintf wrapper to guard against buffer overflow */ int bcm_bprintf(struct bcmstrbuf *b, const char *fmt, ...) { va_list ap; int r; va_start(ap, fmt); r = vsnprintf(b->buf, b->size, fmt, ap); /* Non Ansi C99 compliant returns -1, * Ansi compliant return r >= b->size, * bcmstdlib returns 0, handle all */ if ((r == -1) || (r >= (int)b->size) || (r == 0)) { b->size = 0; } else { b->size -= r; b->buf += r; } va_end(ap); return r; } void bcm_inc_bytes(uchar *num, int num_bytes, uint8 amount) { int i; for (i = 0; i < num_bytes; i++) { num[i] += amount; if (num[i] >= amount) break; amount = 1; } } int bcm_cmp_bytes(uchar *arg1, uchar *arg2, uint8 nbytes) { int i; for (i = nbytes - 1; i >= 0; i--) { if (arg1[i] != arg2[i]) return (arg1[i] - arg2[i]); } return 0; } void bcm_print_bytes(char *name, const uchar *data, int len) { int i; int per_line = 0; printf("%s: %d \n", name ? name : "", len); for (i = 0; i < len; i++) { printf("%02x ", *data++); per_line++; if (per_line == 16) { per_line = 0; printf("\n"); } } printf("\n"); } #if defined(WLTINYDUMP) || defined(WLMSG_INFORM) || defined(WLMSG_ASSOC) || \ defined(WLMSG_PRPKT) || defined(WLMSG_WSEC) #define SSID_FMT_BUF_LEN ((4 * DOT11_MAX_SSID_LEN) + 1) int bcm_format_ssid(char* buf, const uchar ssid[], uint ssid_len) { uint i, c; char *p = buf; char *endp = buf + SSID_FMT_BUF_LEN; if (ssid_len > DOT11_MAX_SSID_LEN) ssid_len = DOT11_MAX_SSID_LEN; for (i = 0; i < ssid_len; i++) { c = (uint)ssid[i]; if (c == '\\') { *p++ = '\\'; *p++ = '\\'; } else if (bcm_isprint((uchar)c)) { *p++ = (char)c; } else { p += snprintf(p, (endp - p), "\\x%02X", c); } } *p = '\0'; ASSERT(p < endp); return (int)(p - buf); } #endif #endif /* BCMDRIVER */ /* * ProcessVars:Takes a buffer of "<var>=<value>\n" lines read from a file and ending in a NUL. * also accepts nvram files which are already in the format of <var1>=<value>\0\<var2>=<value2>\0 * Removes carriage returns, empty lines, comment lines, and converts newlines to NULs. * Shortens buffer as needed and pads with NULs. End of buffer is marked by two NULs. */ unsigned int process_nvram_vars(char *varbuf, unsigned int len) { char *dp; bool findNewline; int column; unsigned int buf_len, n; unsigned int pad = 0; dp = varbuf; findNewline = FALSE; column = 0; for (n = 0; n < len; n++) { if (varbuf[n] == '\r') continue; if (findNewline && varbuf[n] != '\n') continue; findNewline = FALSE; if (varbuf[n] == '#') { findNewline = TRUE; continue; } if (varbuf[n] == '\n') { if (column == 0) continue; *dp++ = 0; column = 0; continue; } *dp++ = varbuf[n]; column++; } buf_len = (unsigned int)(dp - varbuf); if (buf_len % 4) { pad = 4 - buf_len % 4; if (pad && (buf_len + pad <= len)) { buf_len += pad; } } while (dp < varbuf + n) *dp++ = 0; return buf_len; }
hroark13/n861_two_n860
drivers/net/wireless/bcmdhd/bcmutils.c
C
gpl-2.0
45,582
#ifndef __SDCPP_H #define __SDCPP_H #ifdef _WIN32 /* declaration of alloca */ #include <malloc.h> #include <string.h> #ifdef __BORLANDC__ #define strcasecmp stricmp #else #define strcasecmp _stricmp #endif #endif #define BYTES_BIG_ENDIAN 0 /* * From defaults.h */ #ifndef GET_ENVIRONMENT #define GET_ENVIRONMENT(VALUE, NAME) do { (VALUE) = getenv (NAME); } while (0) #endif /* Define results of standard character escape sequences. */ #define TARGET_BELL 007 #define TARGET_BS 010 #define TARGET_TAB 011 #define TARGET_NEWLINE 012 #define TARGET_VT 013 #define TARGET_FF 014 #define TARGET_CR 015 #define TARGET_ESC 033 #define CHAR_TYPE_SIZE 8 #define WCHAR_TYPE_SIZE 32 /* ? maybe ? */ #define SUPPORTS_ONE_ONLY 0 #define TARGET_OBJECT_SUFFIX ".rel" #ifndef WCHAR_UNSIGNED #define WCHAR_UNSIGNED 0 #endif /* * From langhooks.h */ struct diagnostic_context; struct lang_hooks { /* The first callback made to the front end, for simple initialization needed before any calls to handle_option. Return the language mask to filter the switch array with. */ unsigned int (*init_options) (unsigned int argc, const char **argv); /* Handle the switch CODE, which has real type enum opt_code from options.h. If the switch takes an argument, it is passed in ARG which points to permanent storage. The handler is responsible for checking whether ARG is NULL, which indicates that no argument was in fact supplied. For -f and -W switches, VALUE is 1 or 0 for the positive and negative forms respectively. Return 1 if the switch is valid, 0 if invalid, and -1 if it's valid and should not be treated as language-independent too. */ int (*handle_option) (size_t code, const char *arg, int value); /* Return false to use the default complaint about a missing argument, otherwise output a complaint and return true. */ bool (*missing_argument) (const char *opt, size_t code); /* Called when all command line options have been parsed to allow further processing and initialization Should return true to indicate that a compiler back-end is not required, such as with the -E option. If errorcount is nonzero after this call the compiler exits immediately and the finish hook is not called. */ bool (*post_options) (const char **); /* Called after post_options to initialize the front end. Return false to indicate that no further compilation be performed, in which case the finish hook is called immediately. */ bool (*init) (void); /* Called at the end of compilation, as a finalizer. */ void (*finish) (void); }; /* Each front end provides its own. */ extern const struct lang_hooks lang_hooks; /* * From toplev.h */ /* If we haven't already defined a frontend specific diagnostics style, use the generic one. */ #ifndef GCC_DIAG_STYLE #define GCC_DIAG_STYLE __gcc_tdiag__ #endif extern void internal_error (const char *, ...) ATTRIBUTE_PRINTF_1 ATTRIBUTE_NORETURN; /* Pass one of the OPT_W* from options.h as the first parameter. */ extern void warning (int, const char *, ...) ATTRIBUTE_PRINTF_2; extern void error (const char *, ...) ATTRIBUTE_PRINTF_1; extern void fatal_error (const char *, ...) ATTRIBUTE_PRINTF_1 ATTRIBUTE_NORETURN; extern void inform (const char *, ...) ATTRIBUTE_PRINTF_1; extern const char *progname; extern bool exit_after_options; extern void print_version (FILE *, const char *); /* Handle -d switch. */ extern void decode_d_option (const char *); /* Functions used to get and set GCC's notion of in what directory compilation was started. */ extern const char *get_src_pwd (void); extern bool set_src_pwd (const char *); /* * From flags.h */ /* Don't suppress warnings from system headers. -Wsystem-headers. */ extern bool warn_system_headers; /* If -Werror. */ extern bool warnings_are_errors; /* Nonzero for -pedantic switch: warn about anything that standard C forbids. */ /* Temporarily suppress certain warnings. This is set while reading code from a system header file. */ extern int in_system_header; /* Nonzero means `char' should be signed. */ extern int flag_signed_char; /* Nonzero means change certain warnings into errors. Usually these are warnings about failure to conform to some standard. */ extern int flag_pedantic_errors; /* * From options.h */ extern int inhibit_warnings; /* * From c-common.h */ #include "hwint.h" #include "cpplib.h" /* Nonzero means don't output line number information. */ extern char flag_no_line_commands; /* Nonzero causes -E output not to be done, but directives such as #define that have side effects are still obeyed. */ extern char flag_no_output; /* Nonzero means dump macros in some fashion; contains the 'D', 'M' or 'N' of the command line switch. */ extern char flag_dump_macros; /* 0 means we want the preprocessor to not emit line directives for the current working directory. 1 means we want it to do it. -1 means we should decide depending on whether debugging information is being emitted or not. */ extern int flag_working_directory; /* Nonzero means warn about usage of long long when `-pedantic'. */ extern int warn_long_long; extern int sdcpp_common_handle_option (size_t code, const char *arg, int value); extern bool sdcpp_common_missing_argument (const char *opt, size_t code); extern unsigned int sdcpp_common_init_options (unsigned int, const char **); extern bool sdcpp_common_post_options (const char **); extern bool sdcpp_common_init (void); extern void sdcpp_common_finish (void); /* Nonzero means pass #include lines through to the output. */ extern char flag_dump_includes; /* In c-ppoutput.c */ extern void init_pp_output (FILE *); extern void preprocess_file (cpp_reader *); extern void pp_file_change (const struct line_map *); extern void pp_dir_change (cpp_reader *, const char *); /* * From c-pragma.h */ extern struct cpp_reader* parse_in; /* * From input.h */ extern struct line_maps *line_table; typedef source_location location_t; /* deprecated typedef */ /* Top-level source file. */ extern const char *main_input_filename; /* * From tree.h */ /* Define the overall contents of a tree node. just to make diagnostic.c happy */ union tree_node { struct tree_decl { location_t locus; } decl; }; #define DECL_SOURCE_LOCATION(NODE) ((NODE)->decl.locus) /* * From diagnostic.h */ extern int errorcount; /* * From c-tree.h */ /* In order for the format checking to accept the C frontend diagnostic framework extensions, you must include this file before toplev.h, not after. */ #if GCC_VERSION >= 4001 #define ATTRIBUTE_GCC_CDIAG(m, n) __attribute__ ((__format__ (GCC_DIAG_STYLE, m ,n))) ATTRIBUTE_NONNULL(m) #else #define ATTRIBUTE_GCC_CDIAG(m, n) ATTRIBUTE_NONNULL(m) #endif extern bool c_cpp_error (cpp_reader *, int, int, location_t, unsigned int, const char *, va_list *) ATTRIBUTE_GCC_CDIAG(6,0); #endif /* __SDCPP_H */
pfalcon/sdcc
support/cpp/sdcpp.h
C
gpl-2.0
7,065
/* * 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * */ /* * (C) Copyright IBM Corp. 1998-2013 - All Rights Reserved * */ #ifndef __OPENTYPELAYOUTENGINE_H #define __OPENTYPELAYOUTENGINE_H #include "LETypes.h" #include "LEGlyphFilter.h" #include "LEFontInstance.h" #include "LayoutEngine.h" #include "LETableReference.h" #include "GlyphSubstitutionTables.h" #include "GlyphDefinitionTables.h" #include "GlyphPositioningTables.h" U_NAMESPACE_BEGIN /** * OpenTypeLayoutEngine implements complex text layout for OpenType fonts - that is * fonts which have GSUB and GPOS tables associated with them. In order to do this, * the glyph processsing step described for LayoutEngine is further broken into three * steps: * * 1) Character processing - this step analyses the characters and assigns a list of OpenType * feature tags to each one. It may also change, remove or add characters, and change * their order. * * 2) Glyph processing - This step performs character to glyph mapping,and uses the GSUB * table associated with the font to perform glyph substitutions, such as ligature substitution. * * 3) Glyph post processing - in cases where the font doesn't directly contain a GSUB table, * the previous two steps may have generated "fake" glyph indices to use with a "canned" GSUB * table. This step turns those glyph indices into actual font-specific glyph indices, and may * perform any other adjustments requried by the previous steps. * * OpenTypeLayoutEngine will also use the font's GPOS table to apply position adjustments * such as kerning and accent positioning. * * @see LayoutEngine * * @internal */ class U_LAYOUT_API OpenTypeLayoutEngine : public LayoutEngine { public: /** * This is the main constructor. It constructs an instance of OpenTypeLayoutEngine for * a particular font, script and language. It takes the GSUB table as a parameter since * LayoutEngine::layoutEngineFactory has to read the GSUB table to know that it has an * OpenType font. * * @param fontInstance - the font * @param scriptCode - the script * @param langaugeCode - the language * @param gsubTable - the GSUB table * @param success - set to an error code if the operation fails * * @see LayoutEngine::layoutEngineFactory * @see ScriptAndLangaugeTags.h for script and language codes * * @internal */ OpenTypeLayoutEngine(const LEFontInstance *fontInstance, le_int32 scriptCode, le_int32 languageCode, le_int32 typoFlags, const LEReferenceTo<GlyphSubstitutionTableHeader> &gsubTable, LEErrorCode &success); /** * This constructor is used when the font requires a "canned" GSUB table which can't be known * until after this constructor has been invoked. * * @param fontInstance - the font * @param scriptCode - the script * @param langaugeCode - the language * @param success - set to an error code if the operation fails * * @internal */ OpenTypeLayoutEngine(const LEFontInstance *fontInstance, le_int32 scriptCode, le_int32 languageCode, le_int32 typoFlags, LEErrorCode &success); /** * The destructor, virtual for correct polymorphic invocation. * * @internal */ virtual ~OpenTypeLayoutEngine(); /** * A convenience method used to convert the script code into * the four byte script tag required by OpenType. * For Indic languages where multiple script tags exist, * the version 1 (old style) tag is returned. * * @param scriptCode - the script code * * @return the four byte script tag * * @internal */ static LETag getScriptTag(le_int32 scriptCode); /** * A convenience method used to convert the script code into * the four byte script tag required by OpenType. * For Indic languages where multiple script tags exist, * the version 2 tag is returned. * * @param scriptCode - the script code * * @return the four byte script tag * * @internal */ static LETag getV2ScriptTag(le_int32 scriptCode); /** * A convenience method used to convert the langauge code into * the four byte langauge tag required by OpenType. * * @param languageCode - the language code * * @return the four byte language tag * * @internal */ static LETag getLangSysTag(le_int32 languageCode); /** * ICU "poor man's RTTI", returns a UClassID for the actual class. * * @stable ICU 2.8 */ virtual UClassID getDynamicClassID() const; /** * ICU "poor man's RTTI", returns a UClassID for this class. * * @stable ICU 2.8 */ static UClassID getStaticClassID(); /** * The array of language tags, indexed by language code. * * @internal */ static const LETag languageTags[]; private: /** * This method is used by the constructors to convert the script * and language codes to four byte tags and save them. */ void setScriptAndLanguageTags(); /** * The array of script tags, indexed by script code. */ static const LETag scriptTags[]; /** * apply the typoflags. Only called by the c'tors. */ void applyTypoFlags(); protected: /** * A set of "default" features. The default characterProcessing method * will apply all of these features to every glyph. * * @internal */ FeatureMask fFeatureMask; /** * A set of mappings from feature tags to feature masks. These may * be in the order in which the featues should be applied, but they * don't need to be. * * @internal */ const FeatureMap *fFeatureMap; /** * The length of the feature map. * * @internal */ le_int32 fFeatureMapCount; /** * <code>TRUE</code> if the features in the * feature map are in the order in which they * must be applied. * * @internal */ le_bool fFeatureOrder; /** * The address of the GSUB table. * * @internal */ LEReferenceTo<GlyphSubstitutionTableHeader> fGSUBTable; /** * The address of the GDEF table. * * @internal */ LEReferenceTo<GlyphDefinitionTableHeader> fGDEFTable; /** * The address of the GPOS table. * * @internal */ LEReferenceTo<GlyphPositioningTableHeader> fGPOSTable; /** * An optional filter used to inhibit substitutions * preformed by the GSUB table. This is used for some * "canned" GSUB tables to restrict substitutions to * glyphs that are in the font. * * @internal */ LEGlyphFilter *fSubstitutionFilter; /** * The four byte script tag. * * @internal */ LETag fScriptTag; /** * The four byte script tag for V2 fonts. * * @internal */ LETag fScriptTagV2; /** * The four byte language tag * * @internal */ LETag fLangSysTag; /** * This method does the OpenType character processing. It assigns the OpenType feature * tags to the characters, and may generate output characters that differ from the input * charcters due to insertions, deletions, or reorderings. In such cases, it will also * generate an output character index array reflecting these changes. * * Subclasses must override this method. * * Input parameters: * @param chars - the input character context * @param offset - the index of the first character to process * @param count - the number of characters to process * @param max - the number of characters in the input context * @param rightToLeft - TRUE if the characters are in a right to left directional run * * Output parameters: * @param outChars - the output character array, if different from the input * @param charIndices - the output character index array * @param featureTags - the output feature tag array * @param success - set to an error code if the operation fails * * @return the output character count (input character count if no change) * * @internal */ virtual le_int32 characterProcessing(const LEUnicode /*chars*/[], le_int32 offset, le_int32 count, le_int32 max, le_bool /*rightToLeft*/, LEUnicode *&/*outChars*/, LEGlyphStorage &glyphStorage, LEErrorCode &success); /** * This method does character to glyph mapping, and applies the GSUB table. The * default implementation calls mapCharsToGlyphs and then applies the GSUB table, * if there is one. * * Note that in the case of "canned" GSUB tables, the output glyph indices may be * "fake" glyph indices that need to be converted to "real" glyph indices by the * glyphPostProcessing method. * * Input parameters: * @param chars - the input character context * @param offset - the index of the first character to process * @param count - the number of characters to process * @param max - the number of characters in the input context * @param rightToLeft - TRUE if the characters are in a right to left directional run * @param featureTags - the feature tag array * * Output parameters: * @param glyphs - the output glyph index array * @param charIndices - the output character index array * @param success - set to an error code if the operation fails * * @return the number of glyphs in the output glyph index array * * Note: if the character index array was already set by the characterProcessing * method, this method won't change it. * * @internal */ virtual le_int32 glyphProcessing(const LEUnicode chars[], le_int32 offset, le_int32 count, le_int32 max, le_bool rightToLeft, LEGlyphStorage &glyphStorage, LEErrorCode &success); virtual le_int32 glyphSubstitution(le_int32 count, le_int32 max, le_bool rightToLeft, LEGlyphStorage &glyphStorage, LEErrorCode &success); /** * This method does any processing necessary to convert "fake" * glyph indices used by the glyphProcessing method into "real" glyph * indices which can be used to render the text. Note that in some * cases, such as CDAC Indic fonts, several "real" glyphs may be needed * to render one "fake" glyph. * * The default implementation of this method just returns the input glyph * index and character index arrays, assuming that no "fake" glyph indices * were needed to do GSUB processing. * * Input paramters: * @param tempGlyphs - the input "fake" glyph index array * @param tempCharIndices - the input "fake" character index array * @param tempGlyphCount - the number of "fake" glyph indices * * Output parameters: * @param glyphs - the output glyph index array * @param charIndices - the output character index array * @param success - set to an error code if the operation fails * * @return the number of glyph indices in the output glyph index array * * @internal */ virtual le_int32 glyphPostProcessing(LEGlyphStorage &tempGlyphStorage, LEGlyphStorage &glyphStorage, LEErrorCode &success); /** * This method applies the characterProcessing, glyphProcessing and glyphPostProcessing * methods. Most subclasses will not need to override this method. * * Input parameters: * @param chars - the input character context * @param offset - the index of the first character to process * @param count - the number of characters to process * @param max - the number of characters in the input context * @param rightToLeft - TRUE if the text is in a right to left directional run * * Output parameters: * @param glyphs - the glyph index array * @param charIndices - the character index array * @param success - set to an error code if the operation fails * * @return the number of glyphs in the glyph index array * * @see LayoutEngine::computeGlyphs * * @internal */ virtual le_int32 computeGlyphs(const LEUnicode chars[], le_int32 offset, le_int32 count, le_int32 max, le_bool rightToLeft, LEGlyphStorage &glyphStorage, LEErrorCode &success); /** * This method uses the GPOS table, if there is one, to adjust the glyph positions. * * Input parameters: * @param glyphs - the input glyph array * @param glyphCount - the number of glyphs in the glyph array * @param x - the starting X position * @param y - the starting Y position * * Output parameters: * @param positions - the output X and Y positions (two entries per glyph) * @param success - set to an error code if the operation fails * * @internal */ virtual void adjustGlyphPositions(const LEUnicode chars[], le_int32 offset, le_int32 count, le_bool reverse, LEGlyphStorage &glyphStorage, LEErrorCode &success); /** * This method frees the feature tag array so that the * OpenTypeLayoutEngine can be reused for different text. * It is also called from our destructor. * * @internal */ virtual void reset(); }; U_NAMESPACE_END #endif
greghaskins/openjdk-jdk7u-jdk
src/share/native/sun/font/layout/OpenTypeLayoutEngine.h
C
gpl-2.0
14,528
// methods (functions of objects) // see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions // http://www.ecma-international.org/ecma-262/6.0/#sec-method-definitions var Obj = { myMethod(a, b) { }, *myGenerator(a, b) { } }
masatake/ctags
Units/parser-javascript.r/js-methods.d/input.js
JavaScript
gpl-2.0
284
/* Copyright (c) 2012-2013, 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 pr_fmt(fmt) "%s: " fmt, __func__ #include <linux/iopoll.h> #include <linux/delay.h> #include <linux/dma-mapping.h> #include "mdss_fb.h" #include "mdss_mdp.h" #include "mdss_timeout.h" /* wait for at least 2 vsyncs for lowest refresh rate (24hz) */ #define VSYNC_TIMEOUT_US 100000 #define MDP_INTR_MASK_INTF_VSYNC(intf_num) \ (1 << (2 * (intf_num - MDSS_MDP_INTF0) + MDSS_MDP_IRQ_INTF_VSYNC)) /* intf timing settings */ struct intf_timing_params { u32 width; u32 height; u32 xres; u32 yres; u32 h_back_porch; u32 h_front_porch; u32 v_back_porch; u32 v_front_porch; u32 hsync_pulse_width; u32 vsync_pulse_width; u32 border_clr; u32 underflow_clr; u32 hsync_skew; }; struct mdss_mdp_video_ctx { u32 intf_num; char __iomem *base; u32 intf_type; u8 ref_cnt; u8 timegen_en; bool polling_en; u32 poll_cnt; struct completion vsync_comp; int wait_pending; atomic_t vsync_ref; spinlock_t vsync_lock; struct list_head vsync_handlers; }; static inline void mdp_video_write(struct mdss_mdp_video_ctx *ctx, u32 reg, u32 val) { writel_relaxed(val, ctx->base + reg); } static inline u32 mdp_video_read(struct mdss_mdp_video_ctx *ctx, u32 reg) { return readl_relaxed(ctx->base + reg); } static inline u32 mdss_mdp_video_line_count(struct mdss_mdp_ctl *ctl) { struct mdss_mdp_video_ctx *ctx = ctl->priv_data; u32 line_cnt = 0; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); line_cnt = mdp_video_read(ctx, MDSS_MDP_REG_INTF_LINE_COUNT); mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); return line_cnt; } int mdss_mdp_video_addr_setup(struct mdss_data_type *mdata, u32 *offsets, u32 count) { struct mdss_mdp_video_ctx *head; u32 i; head = devm_kzalloc(&mdata->pdev->dev, sizeof(struct mdss_mdp_video_ctx) * count, GFP_KERNEL); if (!head) return -ENOMEM; for (i = 0; i < count; i++) { head[i].base = mdata->mdp_base + offsets[i]; pr_debug("adding Video Intf #%d offset=0x%x virt=%p\n", i, offsets[i], head[i].base); head[i].ref_cnt = 0; head[i].intf_num = i + MDSS_MDP_INTF0; INIT_LIST_HEAD(&head[i].vsync_handlers); } mdata->video_intf = head; mdata->nintf = count; return 0; } static int mdss_mdp_video_timegen_setup(struct mdss_mdp_video_ctx *ctx, struct intf_timing_params *p) { u32 hsync_period, vsync_period; u32 hsync_start_x, hsync_end_x, display_v_start, display_v_end; u32 active_h_start, active_h_end, active_v_start, active_v_end; u32 den_polarity, hsync_polarity, vsync_polarity; u32 display_hctl, active_hctl, hsync_ctl, polarity_ctl; hsync_period = p->hsync_pulse_width + p->h_back_porch + p->width + p->h_front_porch; vsync_period = p->vsync_pulse_width + p->v_back_porch + p->height + p->v_front_porch; display_v_start = ((p->vsync_pulse_width + p->v_back_porch) * hsync_period) + p->hsync_skew; display_v_end = ((vsync_period - p->v_front_porch) * hsync_period) + p->hsync_skew - 1; if (ctx->intf_type == MDSS_INTF_EDP) { display_v_start += p->hsync_pulse_width + p->h_back_porch; display_v_end -= p->h_front_porch; } hsync_start_x = p->h_back_porch + p->hsync_pulse_width; hsync_end_x = hsync_period - p->h_front_porch - 1; if (p->width != p->xres) { active_h_start = hsync_start_x; active_h_end = active_h_start + p->xres - 1; } else { active_h_start = 0; active_h_end = 0; } if (p->height != p->yres) { active_v_start = display_v_start; active_v_end = active_v_start + (p->yres * hsync_period) - 1; } else { active_v_start = 0; active_v_end = 0; } if (active_h_end) { active_hctl = (active_h_end << 16) | active_h_start; active_hctl |= BIT(31); /* ACTIVE_H_ENABLE */ } else { active_hctl = 0; } if (active_v_end) active_v_start |= BIT(31); /* ACTIVE_V_ENABLE */ hsync_ctl = (hsync_period << 16) | p->hsync_pulse_width; display_hctl = (hsync_end_x << 16) | hsync_start_x; den_polarity = 0; if (MDSS_INTF_HDMI == ctx->intf_type) { hsync_polarity = p->yres >= 720 ? 0 : 1; vsync_polarity = p->yres >= 720 ? 0 : 1; } else { hsync_polarity = 0; vsync_polarity = 0; } polarity_ctl = (den_polarity << 2) | /* DEN Polarity */ (vsync_polarity << 1) | /* VSYNC Polarity */ (hsync_polarity << 0); /* HSYNC Polarity */ mdp_video_write(ctx, MDSS_MDP_REG_INTF_HSYNC_CTL, hsync_ctl); mdp_video_write(ctx, MDSS_MDP_REG_INTF_VSYNC_PERIOD_F0, vsync_period * hsync_period); mdp_video_write(ctx, MDSS_MDP_REG_INTF_VSYNC_PULSE_WIDTH_F0, p->vsync_pulse_width * hsync_period); mdp_video_write(ctx, MDSS_MDP_REG_INTF_DISPLAY_HCTL, display_hctl); mdp_video_write(ctx, MDSS_MDP_REG_INTF_DISPLAY_V_START_F0, display_v_start); mdp_video_write(ctx, MDSS_MDP_REG_INTF_DISPLAY_V_END_F0, display_v_end); mdp_video_write(ctx, MDSS_MDP_REG_INTF_ACTIVE_HCTL, active_hctl); mdp_video_write(ctx, MDSS_MDP_REG_INTF_ACTIVE_V_START_F0, active_v_start); mdp_video_write(ctx, MDSS_MDP_REG_INTF_ACTIVE_V_END_F0, active_v_end); mdp_video_write(ctx, MDSS_MDP_REG_INTF_BORDER_COLOR, p->border_clr); mdp_video_write(ctx, MDSS_MDP_REG_INTF_UNDERFLOW_COLOR, p->underflow_clr); mdp_video_write(ctx, MDSS_MDP_REG_INTF_HSYNC_SKEW, p->hsync_skew); mdp_video_write(ctx, MDSS_MDP_REG_INTF_POLARITY_CTL, polarity_ctl); mdp_video_write(ctx, MDSS_MDP_REG_INTF_FRAME_LINE_COUNT_EN, 0x3); return 0; } static inline void video_vsync_irq_enable(struct mdss_mdp_ctl *ctl, bool clear) { struct mdss_mdp_video_ctx *ctx = ctl->priv_data; if (atomic_inc_return(&ctx->vsync_ref) == 1) mdss_mdp_irq_enable(MDSS_MDP_IRQ_INTF_VSYNC, ctl->intf_num); else if (clear) mdss_mdp_irq_clear(ctl->mdata, MDSS_MDP_IRQ_INTF_VSYNC, ctl->intf_num); } static inline void video_vsync_irq_disable(struct mdss_mdp_ctl *ctl) { struct mdss_mdp_video_ctx *ctx = ctl->priv_data; if (atomic_dec_return(&ctx->vsync_ref) == 0) mdss_mdp_irq_disable(MDSS_MDP_IRQ_INTF_VSYNC, ctl->intf_num); } static int mdss_mdp_video_add_vsync_handler(struct mdss_mdp_ctl *ctl, struct mdss_mdp_vsync_handler *handle) { struct mdss_mdp_video_ctx *ctx; unsigned long flags; int ret = 0; bool irq_en = false; if (!handle || !(handle->vsync_handler)) { ret = -EINVAL; goto exit; } ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data; if (!ctx) { pr_err("invalid ctx for ctl=%d\n", ctl->num); ret = -ENODEV; goto exit; } spin_lock_irqsave(&ctx->vsync_lock, flags); if (!handle->enabled) { handle->enabled = true; list_add(&handle->list, &ctx->vsync_handlers); irq_en = true; } spin_unlock_irqrestore(&ctx->vsync_lock, flags); if (irq_en) video_vsync_irq_enable(ctl, false); exit: return ret; } static int mdss_mdp_video_remove_vsync_handler(struct mdss_mdp_ctl *ctl, struct mdss_mdp_vsync_handler *handle) { struct mdss_mdp_video_ctx *ctx; unsigned long flags; bool irq_dis = false; ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data; if (!ctx) { pr_err("invalid ctx for ctl=%d\n", ctl->num); return -ENODEV; } spin_lock_irqsave(&ctx->vsync_lock, flags); if (handle->enabled) { handle->enabled = false; list_del_init(&handle->list); irq_dis = true; } spin_unlock_irqrestore(&ctx->vsync_lock, flags); if (irq_dis) video_vsync_irq_disable(ctl); return 0; } static int mdss_mdp_video_stop(struct mdss_mdp_ctl *ctl) { struct mdss_mdp_video_ctx *ctx; struct mdss_mdp_vsync_handler *tmp, *handle; int rc; pr_debug("stop ctl=%d\n", ctl->num); ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data; if (!ctx) { pr_err("invalid ctx for ctl=%d\n", ctl->num); return -ENODEV; } if (ctx->timegen_en) { rc = mdss_mdp_ctl_intf_event(ctl, MDSS_EVENT_BLANK, NULL); if (rc == -EBUSY) { pr_debug("intf #%d busy don't turn off\n", ctl->intf_num); return rc; } WARN(rc, "intf %d blank error (%d)\n", ctl->intf_num, rc); mdp_video_write(ctx, MDSS_MDP_REG_INTF_TIMING_ENGINE_EN, 0); mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); ctx->timegen_en = false; rc = mdss_mdp_ctl_intf_event(ctl, MDSS_EVENT_PANEL_OFF, NULL); WARN(rc, "intf %d timegen off error (%d)\n", ctl->intf_num, rc); mdss_mdp_irq_disable(MDSS_MDP_IRQ_INTF_UNDER_RUN, ctl->intf_num); } list_for_each_entry_safe(handle, tmp, &ctx->vsync_handlers, list) mdss_mdp_video_remove_vsync_handler(ctl, handle); mdss_mdp_set_intr_callback(MDSS_MDP_IRQ_INTF_VSYNC, ctl->intf_num, NULL, NULL); mdss_mdp_set_intr_callback(MDSS_MDP_IRQ_INTF_UNDER_RUN, ctl->intf_num, NULL, NULL); ctx->ref_cnt--; ctl->priv_data = NULL; return 0; } static void mdss_mdp_video_vsync_intr_done(void *arg) { struct mdss_mdp_ctl *ctl = arg; struct mdss_mdp_video_ctx *ctx = ctl->priv_data; struct mdss_mdp_vsync_handler *tmp; ktime_t vsync_time; if (!ctx) { pr_err("invalid ctx\n"); return; } vsync_time = ktime_get(); ctl->vsync_cnt++; pr_debug("intr ctl=%d vsync cnt=%u vsync_time=%d\n", ctl->num, ctl->vsync_cnt, (int)ktime_to_ms(vsync_time)); ctx->polling_en = false; complete_all(&ctx->vsync_comp); spin_lock(&ctx->vsync_lock); list_for_each_entry(tmp, &ctx->vsync_handlers, list) { tmp->vsync_handler(ctl, vsync_time); } spin_unlock(&ctx->vsync_lock); } static int mdss_mdp_video_pollwait(struct mdss_mdp_ctl *ctl) { struct mdss_mdp_video_ctx *ctx = ctl->priv_data; u32 mask, status; int rc; mask = MDP_INTR_MASK_INTF_VSYNC(ctl->intf_num); mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); rc = readl_poll_timeout(ctl->mdata->mdp_base + MDSS_MDP_REG_INTR_STATUS, status, (status & mask) || try_wait_for_completion(&ctx->vsync_comp), 1000, VSYNC_TIMEOUT_US); mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); if (rc == 0) { pr_debug("vsync poll successful! rc=%d status=0x%x\n", rc, status); ctx->poll_cnt++; if (status) { struct mdss_mdp_vsync_handler *tmp; unsigned long flags; ktime_t vsync_time = ktime_get(); spin_lock_irqsave(&ctx->vsync_lock, flags); list_for_each_entry(tmp, &ctx->vsync_handlers, list) tmp->vsync_handler(ctl, vsync_time); spin_unlock_irqrestore(&ctx->vsync_lock, flags); } } else { pr_warn("vsync poll timed out! rc=%d status=0x%x mask=0x%x\n", rc, status, mask); } return rc; } static int mdss_mdp_video_wait4comp(struct mdss_mdp_ctl *ctl, void *arg) { struct mdss_mdp_video_ctx *ctx; int rc; static int timeout_occurred; u32 prev_vsync_cnt; ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data; if (!ctx) { pr_err("invalid ctx\n"); return -ENODEV; } WARN(!ctx->wait_pending, "waiting without commit! ctl=%d", ctl->num); if (ctx->polling_en) { rc = mdss_mdp_video_pollwait(ctl); } else { prev_vsync_cnt = ctl->vsync_cnt; rc = wait_for_completion_timeout(&ctx->vsync_comp, usecs_to_jiffies(VSYNC_TIMEOUT_US)); if (rc == 0) { pr_err("%s: TIMEOUT (vsync_cnt: prev: %u cur: %u)\n", __func__, prev_vsync_cnt, ctl->vsync_cnt); timeout_occurred = 1; mdss_timeout_dump(ctl->mfd, __func__); pr_warn("vsync wait timeout %d, fallback to poll mode\n", ctl->num); ctx->polling_en++; rc = mdss_mdp_video_pollwait(ctl); } else { if (timeout_occurred) pr_info("%s: recovered from previous timeout\n", __func__); timeout_occurred = 0; rc = 0; } } if (ctx->wait_pending) { ctx->wait_pending = 0; video_vsync_irq_disable(ctl); } return rc; } static void mdss_mdp_video_underrun_intr_done(void *arg) { struct mdss_mdp_ctl *ctl = arg; if (unlikely(!ctl)) return; ctl->underrun_cnt++; pr_debug("display underrun detected for ctl=%d count=%d\n", ctl->num, ctl->underrun_cnt); } static int mdss_mdp_video_display(struct mdss_mdp_ctl *ctl, void *arg) { struct mdss_mdp_video_ctx *ctx; int rc; pr_debug("kickoff ctl=%d\n", ctl->num); ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data; if (!ctx) { pr_err("invalid ctx\n"); return -ENODEV; } if (!ctx->wait_pending) { ctx->wait_pending++; video_vsync_irq_enable(ctl, true); INIT_COMPLETION(ctx->vsync_comp); } else { WARN(1, "commit without wait! ctl=%d", ctl->num); } if (!ctx->timegen_en) { rc = mdss_mdp_ctl_intf_event(ctl, MDSS_EVENT_UNBLANK, NULL); if (rc) { pr_warn("intf #%d unblank error (%d)\n", ctl->intf_num, rc); video_vsync_irq_disable(ctl); ctx->wait_pending = 0; return rc; } pr_debug("enabling timing gen for intf=%d\n", ctl->intf_num); mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); mdss_mdp_irq_enable(MDSS_MDP_IRQ_INTF_UNDER_RUN, ctl->intf_num); mdp_video_write(ctx, MDSS_MDP_REG_INTF_TIMING_ENGINE_EN, 1); wmb(); rc = wait_for_completion_timeout(&ctx->vsync_comp, usecs_to_jiffies(VSYNC_TIMEOUT_US)); WARN(rc == 0, "timeout (%d) enabling timegen on ctl=%d\n", rc, ctl->num); ctx->timegen_en = true; rc = mdss_mdp_ctl_intf_event(ctl, MDSS_EVENT_PANEL_ON, NULL); WARN(rc, "intf %d panel on error (%d)\n", ctl->intf_num, rc); } return 0; } void mdss_mdp_video_lock_panel(struct mdss_mdp_ctl *ctl) { mdss_mdp_ctl_intf_event(ctl, MDSS_EVENT_LOCK_PANEL_MUTEX, NULL); } void mdss_mdp_video_unlock_panel(struct mdss_mdp_ctl *ctl) { mdss_mdp_ctl_intf_event(ctl, MDSS_EVENT_UNLOCK_PANEL_MUTEX, NULL); } int mdss_mdp_video_copy_splash_screen(struct mdss_panel_data *pdata) { void *virt = NULL; unsigned long bl_fb_addr = 0; unsigned long *bl_fb_addr_va; unsigned long pipe_addr, pipe_src_size; u32 height, width, rgb_size, bpp; size_t size; static struct ion_handle *ihdl; struct ion_client *iclient = mdss_get_ionclient(); static ion_phys_addr_t phys; pipe_addr = MDSS_MDP_REG_SSPP_OFFSET(3) + MDSS_MDP_REG_SSPP_SRC0_ADDR; pipe_src_size = MDSS_MDP_REG_SSPP_OFFSET(3) + MDSS_MDP_REG_SSPP_SRC_SIZE; bpp = 3; rgb_size = MDSS_MDP_REG_READ(pipe_src_size); bl_fb_addr = MDSS_MDP_REG_READ(pipe_addr); height = (rgb_size >> 16) & 0xffff; width = rgb_size & 0xffff; size = PAGE_ALIGN(height * width * bpp); pr_debug("%s:%d splash_height=%d splash_width=%d Buffer size=%d\n", __func__, __LINE__, height, width, size); ihdl = ion_alloc(iclient, size, SZ_1M, ION_HEAP(ION_QSECOM_HEAP_ID), 0); if (IS_ERR_OR_NULL(ihdl)) { pr_err("unable to alloc fbmem from ion (%p)\n", ihdl); return -ENOMEM; } pdata->panel_info.splash_ihdl = ihdl; virt = ion_map_kernel(iclient, ihdl); ion_phys(iclient, ihdl, &phys, &size); pr_debug("%s %d Allocating %u bytes at 0x%lx (%pa phys)\n", __func__, __LINE__, size, (unsigned long int)virt, &phys); bl_fb_addr_va = (unsigned long *)ioremap(bl_fb_addr, size); memcpy(virt, bl_fb_addr_va, size); iounmap(bl_fb_addr_va); MDSS_MDP_REG_WRITE(pipe_addr, phys); MDSS_MDP_REG_WRITE(MDSS_MDP_REG_CTL_FLUSH + MDSS_MDP_REG_CTL_OFFSET(0), 0x48); return 0; } int mdss_mdp_video_reconfigure_splash_done(struct mdss_mdp_ctl *ctl) { struct ion_client *iclient = mdss_get_ionclient(); struct mdss_panel_data *pdata; int ret = 0, off; int mdss_mdp_rev = MDSS_MDP_REG_READ(MDSS_MDP_REG_HW_VERSION); int mdss_v2_intf_off = 0; off = 0; pdata = ctl->panel_data; pdata->panel_info.cont_splash_enabled = 0; ret = mdss_mdp_ctl_intf_event(ctl, MDSS_EVENT_CONT_SPLASH_BEGIN, NULL); if (ret) { pr_err("%s: Failed to handle 'CONT_SPLASH_BEGIN' event\n", __func__); return ret; } mdss_mdp_ctl_write(ctl, 0, MDSS_MDP_LM_BORDER_COLOR); off = MDSS_MDP_REG_INTF_OFFSET(ctl->intf_num); if (mdss_mdp_rev >= MDSS_MDP_HW_REV_102) mdss_v2_intf_off = 0xEC00; MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_TIMING_ENGINE_EN - mdss_v2_intf_off, 0); /* wait for 1 VSYNC for the pipe to be unstaged */ msleep(20); ion_free(iclient, pdata->panel_info.splash_ihdl); ret = mdss_mdp_ctl_intf_event(ctl, MDSS_EVENT_CONT_SPLASH_FINISH, NULL); mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); return ret; } void mdss_mdp_video_dump_ctx(struct mdss_mdp_ctl *ctl) { struct mdss_mdp_video_ctx *ctx = ctl->priv_data; MDSS_TIMEOUT_LOG("timegen_en=%u\n", ctx->timegen_en); MDSS_TIMEOUT_LOG("polling_en=%u\n", ctx->polling_en); MDSS_TIMEOUT_LOG("poll_cnt=%u\n", ctx->poll_cnt); MDSS_TIMEOUT_LOG("wait_pending=%d\n", ctx->wait_pending); } int mdss_mdp_video_start(struct mdss_mdp_ctl *ctl) { struct mdss_data_type *mdata; struct mdss_panel_info *pinfo; struct mdss_mdp_video_ctx *ctx; struct mdss_mdp_mixer *mixer; struct intf_timing_params itp = {0}; u32 dst_bpp; int i; mdata = ctl->mdata; pinfo = &ctl->panel_data->panel_info; mixer = mdss_mdp_mixer_get(ctl, MDSS_MDP_MIXER_MUX_LEFT); if (!mixer) { pr_err("mixer not setup correctly\n"); return -ENODEV; } i = ctl->intf_num - MDSS_MDP_INTF0; if (i < mdata->nintf) { ctx = ((struct mdss_mdp_video_ctx *) mdata->video_intf) + i; if (ctx->ref_cnt) { pr_err("Intf %d already in use\n", ctl->intf_num); return -EBUSY; } pr_debug("video Intf #%d base=%p", ctx->intf_num, ctx->base); ctx->ref_cnt++; } else { pr_err("Invalid intf number: %d\n", ctl->intf_num); return -EINVAL; } pr_debug("start ctl=%u\n", ctl->num); ctl->priv_data = ctx; ctx->intf_type = ctl->intf_type; init_completion(&ctx->vsync_comp); spin_lock_init(&ctx->vsync_lock); atomic_set(&ctx->vsync_ref, 0); mdss_mdp_set_intr_callback(MDSS_MDP_IRQ_INTF_VSYNC, ctl->intf_num, mdss_mdp_video_vsync_intr_done, ctl); mdss_mdp_set_intr_callback(MDSS_MDP_IRQ_INTF_UNDER_RUN, ctl->intf_num, mdss_mdp_video_underrun_intr_done, ctl); dst_bpp = pinfo->fbc.enabled ? (pinfo->fbc.target_bpp) : (pinfo->bpp); itp.width = mult_frac((pinfo->xres + pinfo->lcdc.xres_pad), dst_bpp, pinfo->bpp); itp.height = pinfo->yres + pinfo->lcdc.yres_pad; itp.border_clr = pinfo->lcdc.border_clr; itp.underflow_clr = pinfo->lcdc.underflow_clr; itp.hsync_skew = pinfo->lcdc.hsync_skew; itp.xres = mult_frac(pinfo->xres, dst_bpp, pinfo->bpp); itp.yres = pinfo->yres; itp.h_back_porch = mult_frac(pinfo->lcdc.h_back_porch, dst_bpp, pinfo->bpp); itp.h_front_porch = mult_frac(pinfo->lcdc.h_front_porch, dst_bpp, pinfo->bpp); itp.v_back_porch = mult_frac(pinfo->lcdc.v_back_porch, dst_bpp, pinfo->bpp); itp.v_front_porch = mult_frac(pinfo->lcdc.v_front_porch, dst_bpp, pinfo->bpp); itp.hsync_pulse_width = mult_frac(pinfo->lcdc.h_pulse_width, dst_bpp, pinfo->bpp); itp.vsync_pulse_width = pinfo->lcdc.v_pulse_width; if (mdss_mdp_video_timegen_setup(ctx, &itp)) { pr_err("unable to get timing parameters\n"); return -EINVAL; } mdp_video_write(ctx, MDSS_MDP_REG_INTF_PANEL_FORMAT, ctl->dst_format); ctl->stop_fnc = mdss_mdp_video_stop; ctl->display_fnc = mdss_mdp_video_display; ctl->wait_fnc = mdss_mdp_video_wait4comp; ctl->read_line_cnt_fnc = mdss_mdp_video_line_count; ctl->add_vsync_handler = mdss_mdp_video_add_vsync_handler; ctl->remove_vsync_handler = mdss_mdp_video_remove_vsync_handler; ctl->ctx_dump_fnc = mdss_mdp_video_dump_ctx; return 0; }
Spartonos/android_kernel_motorola_falcon_umts
drivers/video/msm/mdss/mdss_mdp_intf_video.c
C
gpl-2.0
19,252
/* * Copyright (C) 2013 University of Dundee & Open Microscopy Environment. * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 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. */ package org.openmicroscopy.shoola.keywords; import java.awt.Component; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.util.NoSuchElementException; import javax.swing.JPanel; import org.robotframework.abbot.finder.BasicFinder; import org.robotframework.abbot.finder.ComponentNotFoundException; import org.robotframework.abbot.finder.Matcher; import org.robotframework.abbot.finder.MultipleComponentsFoundException; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; /** * Robot Framework SwingLibrary keyword library offering methods for checking thumbnails. * @author m.t.b.carroll@dundee.ac.uk * @since 4.4.9 */ public class ThumbnailCheckLibrary { /** Allow Robot Framework to instantiate this library only once. */ public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL"; /** * An iterator over the integer pixel values of a rendered image, * first increasing <em>x</em>, then <em>y</em> when <em>x</em> wraps back to 0. * This is written so as to be scalable over arbitrary image sizes * and to not cause heap allocations during the iteration. * @author m.t.b.carroll@dundee.ac.uk * @since 4.4.9 */ private static class IteratorIntPixel { final Raster raster; final int width; final int height; final int[] pixel = new int[1]; int x = 0; int y = 0; /** * Create a new pixel iterator for the given image. * The image is assumed to be of a type that packs data for each pixel into an <code>int</code>. * @param image the image over whose pixels to iterate */ IteratorIntPixel(RenderedImage image) { this.raster = image.getData(); this.width = image.getWidth(); this.height = image.getHeight(); } /** * @return if any pixels remain to be read with {@link #next()} */ boolean hasNext() { return y < height; } /** * @return the next pixel * @throws NoSuchElementException if no more pixels remain */ int next() { if (!hasNext()) { throw new NoSuchElementException(); } raster.getDataElements(x, y, pixel); if (++x == width) { x = 0; ++y; } return pixel[0]; } } /** * Find the thumbnail <code>Component</code> in the AWT hierarchy. * @param panelType if the thumbnail should be the whole <code>"image node"</code> or just its <code>"thumbnail"</code> canvas * @param imageFilename the name of the image whose thumbnail is to be rasterized * @return the AWT <code>Component</code> for the thumbnail * @throws MultipleComponentsFoundException if multiple thumbnails are for the given image name * @throws ComponentNotFoundException if no thumbnails are for the given image name */ private static Component componentFinder(final String panelType, final String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { return new BasicFinder().find(new Matcher() { private final String soughtName = panelType + " for " + imageFilename; public boolean matches(Component component) { return component instanceof JPanel && this.soughtName.equals(component.getName()); }}); } /** * Convert the thumbnail for the image of the given filename into rasterized pixel data. * Each pixel is represented by an <code>int</code>. * @param panelType if the thumbnail should be the whole <code>"image node"</code> or just its <code>"thumbnail"</code> canvas * @param imageFilename the name of the image whose thumbnail is to be rasterized * @return the image on the thumbnail * @throws MultipleComponentsFoundException if multiple thumbnails are for the given image name * @throws ComponentNotFoundException if no thumbnails are for the given image name */ private static RenderedImage captureImage(final String panelType, final String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { final JPanel thumbnail = (JPanel) componentFinder(panelType, imageFilename); final int width = thumbnail.getWidth(); final int height = thumbnail.getHeight(); final BufferedImage image = new BufferedImage(width, height, StaticFieldLibrary.IMAGE_TYPE); final Graphics2D graphics = image.createGraphics(); if (graphics == null) { throw new RuntimeException("thumbnail is not displayable"); } thumbnail.paint(graphics); graphics.dispose(); return image; } /** * <table> * <td>Get Thumbnail Border Color</td> * <td>name of image whose thumbnail is queried</td> * </table> * @param imageFilename the name of the image * @return the color of the thumbnail's corner pixel * @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name * @throws ComponentNotFoundException if no thumbnails exist for the given name */ public String getThumbnailBorderColor(String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { final RenderedImage image = captureImage("image node", imageFilename); final IteratorIntPixel pixels = new IteratorIntPixel(image); if (!pixels.hasNext()) { throw new RuntimeException("image node has no pixels"); } return Integer.toHexString(pixels.next()); } /** * <table> * <td>Is Thumbnail Monochromatic</td> * <td>name of image whose thumbnail is queried</td> * </table> * @param imageFilename the name of the image * @return if the image's thumbnail canvas is solidly one color * @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name * @throws ComponentNotFoundException if no thumbnails exist for the given name */ public boolean isThumbnailMonochromatic(String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { final RenderedImage image = captureImage("thumbnail", imageFilename); final IteratorIntPixel pixels = new IteratorIntPixel(image); if (!pixels.hasNext()) { throw new RuntimeException("thumbnail image has no pixels"); } final int oneColor = pixels.next(); while (pixels.hasNext()) { if (pixels.next() != oneColor) { return false; } } return true; } /** * <table> * <td>Get Thumbnail Hash</td> * <td>name of image whose thumbnail is queried</td> * </table> * @param imageFilename the name of the image * @return the hash of the thumbnail canvas image * @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name * @throws ComponentNotFoundException if no thumbnails exist for the given name */ public String getThumbnailHash(String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { final RenderedImage image = captureImage("thumbnail", imageFilename); final IteratorIntPixel pixels = new IteratorIntPixel(image); final Hasher hasher = Hashing.goodFastHash(128).newHasher(); while (pixels.hasNext()) { hasher.putInt(pixels.next()); } return hasher.hash().toString(); } /** * <table> * <td>Get Name Of Thumbnail For Image</td> * <td>name of image whose thumbnail is queried</td> * </table> * @param imageFilename the name of the image * @return the return value of the corresponding <code>ThumbnailCanvas.getName()</code> * @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name * @throws ComponentNotFoundException if no thumbnails exist for the given name */ public String getNameOfThumbnailForImage(final String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { return componentFinder("thumbnail", imageFilename).getName(); } }
jballanc/openmicroscopy
components/tests/ui/library/java/src/org/openmicroscopy/shoola/keywords/ThumbnailCheckLibrary.java
Java
gpl-2.0
9,339
<?php /** * Akeeba Engine * The modular PHP5 site backup engine * @copyright Copyright (c)2009-2013 Nicholas K. Dionysopoulos * @license GNU GPL version 3 or, at your option, any later version * @package akeebaengine */ // Protection against direct access defined('AKEEBAENGINE') or die(); /** * Database interface class. * * Based on Joomla! Platform 11.2 */ interface AEAbstractDriverInterface { /** * Test to see if the connector is available. * * @return boolean True on success, false otherwise. */ public static function test(); /** * Test to see if the connector is available. * * @return boolean True on success, false otherwise. * * @since 11.2 */ public static function isSupported(); } /** * Database driver superclass. Used as the base of all Akeeba Engine database drivers. * Strongly based on Joomla Platform's JDatabase class. */ abstract class AEAbstractDriver extends AEAbstractObject implements AEAbstractDriverInterface { /** @var string The name of the database. */ private $_database; /** @var string The name of the database driver. */ public $name; /** @var resource The db conenction resource */ protected $connection = ''; /** @var integer The number of SQL statements executed by the database driver. */ protected $count = 0; /** @var resource The database connection cursor from the last query. */ protected $cursor; /** @var boolean The database driver debugging state. */ protected $debug = false; /** @var int Query's limit */ protected $limit = 0; /** @var array The log of executed SQL statements by the database driver. */ protected $log = array(); /** @var string Quote for named objects */ protected $nameQuote = ''; /** @var string The null or zero representation of a timestamp for the database driver. */ protected $nullDate; /** @var int Query's offset */ protected $offset = 0; /** @var array Passed in upon instantiation and saved. */ protected $options; /** @var mixed The SQL query string */ protected $sql = ''; /** @var string The prefix used in the database, if any */ protected $tablePrefix = ''; /** @var bool Support for UTF-8 */ protected $utf = true; /** @var int The db server's error number */ protected $errorNum = 0; /** @var string The db server's error string */ protected $errorMsg = ''; /** @var array JDatabaseDriver instances container. */ protected static $instances = array(); /** @var string The minimum supported database version. */ protected static $dbMinimum; /** @var string Driver type, e.g. mysql, mssql, pgsql and so on */ protected $driverType = ''; /** * Splits a string of multiple queries into an array of individual queries. * * @param string $query Input SQL string with which to split into individual queries. * * @return array The queries from the input string separated into an array. */ public static function splitSql($query) { $start = 0; $open = false; $char = ''; $end = strlen($query); $queries = array(); for ($i = 0; $i < $end; $i++) { $current = substr($query, $i, 1); if (($current == '"' || $current == '\'')) { $n = 2; while (substr($query, $i - $n + 1, 1) == '\\' && $n < $i) { $n++; } if ($n % 2 == 0) { if ($open) { if ($current == $char) { $open = false; $char = ''; } } else { $open = true; $char = $current; } } } if (($current == ';' && !$open) || $i == $end - 1) { $queries[] = substr($query, $start, ($i - $start + 1)); $start = $i + 1; } } return $queries; } /** * Magic method to provide method alias support for quote() and quoteName(). * * @param string $method The called method. * @param array $args The array of arguments passed to the method. * * @return string The aliased method's return value or null. */ public function __call($method, $args) { if (empty($args)) { return; } switch ($method) { case 'q': return $this->quote($args[0], isset($args[1]) ? $args[1] : true); break; case 'nq': case 'qn': return $this->quoteName($args[0]); break; } } /** * Database object constructor * @param array List of options used to configure the connection */ public function __construct( $options ) { $prefix = array_key_exists('prefix', $options) ? $options['prefix'] : ''; $database = array_key_exists('database', $options) ? $options['database'] : ''; $connection = array_key_exists('connection', $options) ? $options['connection']: null; $this->tablePrefix = $prefix; $this->_database = $database; $this->connection = $connection; $this->errorNum = 0; $this->count = 0; $this->log = array(); $this->options = $options; } /** * Database object destructor * @return bool */ public function __destruct() { return $this->close(); } /** * By default, when the object is shutting down, the connection is closed */ public function _onSerialize() { $this->close(); } public function __wakeup() { $this->open(); } /** * Alter database's character set, obtaining query string from protected member. * * @param string $dbName The database name that will be altered * * @return string The query that alter the database query string * * @throws RuntimeException */ public function alterDbCharacterSet($dbName) { if (is_null($dbName)) { throw new RuntimeException('Database name must not be null.'); } $this->setQuery($this->getAlterDbCharacterSet($dbName)); return $this->execute(); } /** * Opens a database connection. It MUST be overriden by children classes * @return AEAbstractDriver */ public function open() { // Don't try to reconnect if we're already connected if(is_resource($this->connection) && !is_null($this->connection)) return $this; // Determine utf-8 support $this->utf = $this->hasUTF(); // Set charactersets (needed for MySQL 4.1.2+) if ($this->utf){ $this->setUTF(); } // Select the current database $this->select($this->_database); return $this; } /** * Closes the database connection */ abstract public function close(); /** * Determines if the connection to the server is active. * * @return boolean True if connected to the database engine. */ abstract public function connected(); /** * Create a new database using information from $options object, obtaining query string * from protected member. * * @param stdClass $options Object used to pass user and database name to database driver. * This object must have "db_name" and "db_user" set. * @param boolean $utf True if the database supports the UTF-8 character set. * * @return string The query that creates database * * @throws RuntimeException */ public function createDatabase($options, $utf = true) { if (is_null($options)) { throw new RuntimeException('$options object must not be null.'); } elseif (empty($options->db_name)) { throw new RuntimeException('$options object must have db_name set.'); } elseif (empty($options->db_user)) { throw new RuntimeException('$options object must have db_user set.'); } $this->setQuery($this->getCreateDatabaseQuery($options, $utf)); return $this->execute(); } /** * Drops a table from the database. * * @param string $table The name of the database table to drop. * @param boolean $ifExists Optionally specify that the table must exist before it is dropped. * * @return AEAbstractDriver Returns this object to support chaining. */ public abstract function dropTable($table, $ifExists = true); /** * Method to escape a string for usage in an SQL statement. * * @param string $text The string to be escaped. * @param boolean $extra Optional parameter to provide extra escaping. * * @return string The escaped string. */ abstract public function escape($text, $extra = false); /** * Method to fetch a row from the result set cursor as an array. * * @param mixed $cursor The optional result set cursor from which to fetch the row. * * @return mixed Either the next row from the result set or false if there are no more rows. */ abstract protected function fetchArray($cursor = null); /** * Method to fetch a row from the result set cursor as an associative array. * * @param mixed $cursor The optional result set cursor from which to fetch the row. * * @return mixed Either the next row from the result set or false if there are no more rows. */ abstract public function fetchAssoc($cursor = null); /** * Method to fetch a row from the result set cursor as an object. * * @param mixed $cursor The optional result set cursor from which to fetch the row. * @param string $class The class name to use for the returned row object. * * @return mixed Either the next row from the result set or false if there are no more rows. */ abstract protected function fetchObject($cursor = null, $class = 'stdClass'); /** * Method to free up the memory used for the result set. * * @param mixed $cursor The optional result set cursor from which to fetch the row. * * @return void */ abstract public function freeResult($cursor = null); /** * Get the number of affected rows for the previous executed SQL statement. * * @return integer The number of affected rows. */ abstract public function getAffectedRows(); /** * Return the query string to alter the database character set. * * @param string $dbName The database name * * @return string The query that alter the database query string */ protected function getAlterDbCharacterSet($dbName) { $query = 'ALTER DATABASE ' . $this->quoteName($dbName) . ' CHARACTER SET `utf8`'; return $query; } /** * Return the query string to create new Database. * Each database driver, other than MySQL, need to override this member to return correct string. * * @param stdClass $options Object used to pass user and database name to database driver. * This object must have "db_name" and "db_user" set. * @param boolean $utf True if the database supports the UTF-8 character set. * * @return string The query that creates database */ protected function getCreateDatabaseQuery($options, $utf) { if ($utf) { $query = 'CREATE DATABASE ' . $this->quoteName($options->db_name) . ' CHARACTER SET `utf8`'; } else { $query = 'CREATE DATABASE ' . $this->quoteName($options->db_name); } return $query; } /** * Method to get the database collation in use by sampling a text field of a table in the database. * * @return mixed The collation in use by the database or boolean false if not supported. */ abstract public function getCollation(); /** * Method that provides access to the underlying database connection. Useful for when you need to call a * proprietary method such as postgresql's lo_* methods. * * @return resource The underlying database connection resource. */ public function getConnection() { return $this->connection; } /** * Inherits the connection of another database driver. Useful for cloning * the CMS database connection into an Akeeba Engine database driver. * * @param resource $connection */ public function setConnection($connection) { $this->connection = $connection; } /** * Get the total number of SQL statements executed by the database driver. * * @return integer * * @since 11.1 */ public function getCount() { return $this->count; } /** * Gets the name of the database used by this conneciton. * * @return string */ protected function getDatabase() { return $this->_database; } /** * Returns a PHP date() function compliant date format for the database driver. * * @return string The format string. */ public function getDateFormat() { return 'Y-m-d H:i:s'; } /** * Get the database driver SQL statement log. * * @return array SQL statements executed by the database driver. * * @since 11.1 */ public function getLog() { return $this->log; } /** * Get the minimum supported database version. * * @return string The minimum version number for the database driver. * * @since 12.1 */ public function getMinimum() { return static::$dbMinimum; } /** * Get the null or zero representation of a timestamp for the database driver. * * @return string Null or zero representation of a timestamp. */ public function getNullDate() { return $this->nullDate; } /** * Get the number of returned rows for the previous executed SQL statement. * * @param resource $cursor An optional database cursor resource to extract the row count from. * * @return integer The number of returned rows. */ abstract public function getNumRows($cursor = null); /** * Get the database table prefix * * @return string The database prefix */ public final function getPrefix() { return $this->tablePrefix; } /** * Get the current query object or a new AEAbstractQuery object. * * @param boolean $new False to return the current query object, True to return a new AEAbstractQuery object. * * @return AEAbstractQuery The current query object or a new object extending the AEAbstractQuery class. */ abstract public function getQuery($new = false); /** * Retrieves field information about the given tables. * * @param string $table The name of the database table. * @param boolean $typeOnly True (default) to only return field types. * * @return array An array of fields by table. */ abstract public function getTableColumns($table, $typeOnly = true); /** * Shows the table CREATE statement that creates the given tables. * * @param mixed $tables A table name or a list of table names. * * @return array A list of the create SQL for the tables. */ abstract public function getTableCreate($tables); /** * Retrieves field information about the given tables. * * @param mixed $tables A table name or a list of table names. * * @return array An array of keys for the table(s). */ abstract public function getTableKeys($tables); /** * Method to get an array of all tables in the database. * * @return array An array of all the tables in the database. */ abstract public function getTableList(); /** * Determine whether or not the database engine supports UTF-8 character encoding. * * @return boolean True if the database engine supports UTF-8 character encoding. */ public function getUTFSupport() { return $this->utf; } /** * Determine whether or not the database engine supports UTF-8 character encoding. * * @return boolean True if the database engine supports UTF-8 character encoding. */ public function hasUTFSupport() { return $this->utf; } /** * Determines if the database engine supports UTF-8 character encoding. * * @return boolean True if supported. */ public function hasUTF() { return $this->utf; } /** * Get the version of the database connector * * @return string The database connector version. */ abstract public function getVersion(); /** * Method to get the auto-incremented value from the last INSERT statement. * * @return integer The value of the auto-increment field from the last inserted row. */ abstract public function insertid(); /** * Inserts a row into a table based on an object's properties. * * @param string $table The name of the database table to insert into. * @param object &$object A reference to an object whose public properties match the table fields. * @param string $key The name of the primary key. If provided the object property is updated. * * @return boolean True on success. */ public function insertObject($table, &$object, $key = null) { $fields = array(); $values = array(); // Iterate over the object variables to build the query fields and values. foreach (get_object_vars($object) as $k => $v) { // Only process non-null scalars. if (is_array($v) or is_object($v) or $v === null) { continue; } // Ignore any internal fields. if ($k[0] == '_') { continue; } // Prepare and sanitize the fields and values for the database query. $fields[] = $this->quoteName($k); $values[] = $this->quote($v); } // Create the base insert statement. $query = $this->getQuery(true) ->insert($this->quoteName($table)) ->columns($fields) ->values(implode(',', $values)); // Set the query and execute the insert. $this->setQuery($query); if (!$this->execute()) { return false; } // Update the primary key if it exists. $id = $this->insertid(); if ($key && $id && is_string($key)) { $object->$key = $id; } return true; } /** * Method to check whether the installed database version is supported by the database driver * * @return boolean True if the database version is supported * * @since 12.1 */ public function isMinimumVersion() { return version_compare($this->getVersion(), static::$dbMinimum) >= 0; } /** * Method to get the first row of the result set from the database query as an associative array * of ['field_name' => 'row_value']. * * @return mixed The return value or null if the query failed. */ public function loadAssoc() { $ret = null; // Execute the query and get the result set cursor. if (!($cursor = $this->execute())) { return null; } // Get the first row from the result set as an associative array. if ($array = $this->fetchAssoc($cursor)) { $ret = $array; } // Free up system resources and return. $this->freeResult($cursor); return $ret; } /** * Method to get an array of the result set rows from the database query where each row is an associative array * of ['field_name' => 'row_value']. The array of rows can optionally be keyed by a field name, but defaults to * a sequential numeric array. * * NOTE: Chosing to key the result array by a non-unique field name can result in unwanted * behavior and should be avoided. * * @param string $key The name of a field on which to key the result array. * @param string $column An optional column name. Instead of the whole row, only this column value will be in * the result array. * * @return mixed The return value or null if the query failed. */ public function loadAssocList($key = null, $column = null) { $array = array(); // Execute the query and get the result set cursor. if (!($cursor = $this->execute())) { return null; } // Get all of the rows from the result set. while ($row = $this->fetchAssoc($cursor)) { $value = ($column) ? (isset($row[$column]) ? $row[$column] : $row) : $row; if ($key) { $array[$row[$key]] = $value; } else { $array[] = $value; } } // Free up system resources and return. $this->freeResult($cursor); return $array; } /** * Method to get an array of values from the <var>$offset</var> field in each row of the result set from * the database query. * * @param integer $offset The row offset to use to build the result array. * * @return mixed The return value or null if the query failed. */ public function loadColumn($offset = 0) { $array = array(); // Execute the query and get the result set cursor. if (!($cursor = $this->execute())) { return null; } // Get all of the rows from the result set as arrays. while ($row = $this->fetchArray($cursor)) { $array[] = $row[$offset]; } // Free up system resources and return. $this->freeResult($cursor); return $array; } /** * Method to get the next row in the result set from the database query as an object. * * @param string $class The class name to use for the returned row object. * * @return mixed The result of the query as an array, false if there are no more rows. */ public function loadNextObject($class = 'stdClass') { static $cursor = null; // Execute the query and get the result set cursor. if ( is_null($cursor) ) { if (!($cursor = $this->execute())) { return $this->errorNum ? null : false; } } // Get the next row from the result set as an object of type $class. if ($row = $this->fetchObject($cursor, $class)) { return $row; } // Free up system resources and return. $this->freeResult($cursor); $cursor = null; return false; } /** * Method to get the next row in the result set from the database query as an array. * * @return mixed The result of the query as an array, false if there are no more rows. */ public function loadNextRow() { static $cursor = null; // Execute the query and get the result set cursor. if ( is_null($cursor) ) { if (!($cursor = $this->execute())) { return $this->errorNum ? null : false; } } // Get the next row from the result set as an object of type $class. if ($row = $this->fetchArray($cursor)) { return $row; } // Free up system resources and return. $this->freeResult($cursor); $cursor = null; return false; } /** * Method to get the first row of the result set from the database query as an object. * * @param string $class The class name to use for the returned row object. * * @return mixed The return value or null if the query failed. */ public function loadObject($class = 'stdClass') { $ret = null; // Execute the query and get the result set cursor. if (!($cursor = $this->execute())) { return null; } // Get the first row from the result set as an object of type $class. if ($object = $this->fetchObject($cursor, $class)) { $ret = $object; } // Free up system resources and return. $this->freeResult($cursor); return $ret; } /** * Method to get an array of the result set rows from the database query where each row is an object. The array * of objects can optionally be keyed by a field name, but defaults to a sequential numeric array. * * NOTE: Choosing to key the result array by a non-unique field name can result in unwanted * behavior and should be avoided. * * @param string $key The name of a field on which to key the result array. * @param string $class The class name to use for the returned row objects. * * @return mixed The return value or null if the query failed. */ public function loadObjectList($key = '', $class = 'stdClass') { $array = array(); // Execute the query and get the result set cursor. if (!($cursor = $this->execute())) { return null; } // Get all of the rows from the result set as objects of type $class. while ($row = $this->fetchObject($cursor, $class)) { if ($key) { $array[$row->$key] = $row; } else { $array[] = $row; } } // Free up system resources and return. $this->freeResult($cursor); return $array; } /** * Method to get the first field of the first row of the result set from the database query. * * @return mixed The return value or null if the query failed. */ public function loadResult() { $ret = null; // Execute the query and get the result set cursor. if (!($cursor = $this->execute())) { return null; } // Get the first row from the result set as an array. if ($row = $this->fetchArray($cursor)) { $ret = $row[0]; } // Free up system resources and return. $this->freeResult($cursor); return $ret; } /** * Method to get the first row of the result set from the database query as an array. Columns are indexed * numerically so the first column in the result set would be accessible via <var>$row[0]</var>, etc. * * @return mixed The return value or null if the query failed. */ public function loadRow() { $ret = null; // Execute the query and get the result set cursor. if (!($cursor = $this->execute())) { return null; } // Get the first row from the result set as an array. if ($row = $this->fetchArray($cursor)) { $ret = $row; } // Free up system resources and return. $this->freeResult($cursor); return $ret; } /** * Method to get an array of the result set rows from the database query where each row is an array. The array * of objects can optionally be keyed by a field offset, but defaults to a sequential numeric array. * * NOTE: Choosing to key the result array by a non-unique field can result in unwanted * behavior and should be avoided. * * @param string $key The name of a field on which to key the result array. * * @return mixed The return value or null if the query failed. */ public function loadRowList($key = null) { $array = array(); // Execute the query and get the result set cursor. if (!($cursor = $this->execute())) { return null; } // Get all of the rows from the result set as arrays. while ($row = $this->fetchArray($cursor)) { if ($key !== null) { $array[$row[$key]] = $row; } else { $array[] = $row; } } // Free up system resources and return. $this->freeResult($cursor); return $array; } /** * Locks a table in the database. * * @param string $tableName The name of the table to unlock. * * @return AEAbstractDriver Returns this object to support chaining. */ public abstract function lockTable($tableName); /** * Execute the SQL statement. * * @return mixed A database cursor resource on success, boolean false on failure. */ abstract public function query(); /** * An alias for query(), for compatibility with Joomla! 2.5+ which has deprecated * query() in favour of execute() * * @return mixed A database cursor resource on success, boolean false on failure. */ public function execute() { return $this->query(); } /** * Method to quote and optionally escape a string to database requirements for insertion into the database. * * @param string $text The string to quote. * @param boolean $escape True (default) to escape the string, false to leave it unchanged. */ public function quote($text, $escape = true) { return '\'' . ($escape ? $this->escape($text) : $text) . '\''; } /** * Wrap an SQL statement identifier name such as column, table or database names in quotes to prevent injection * risks and reserved word conflicts. * * @param mixed $name The identifier name to wrap in quotes, or an array of identifier names to wrap in quotes. * Each type supports dot-notation name. * @param mixed $as The AS query part associated to $name. It can be string or array, in latter case it has to be * same length of $name; if is null there will not be any AS part for string or array element. */ public function quoteName($name, $as = null) { if (is_string($name)) { $quotedName = $this->quoteNameStr(explode('.', $name)); $quotedAs = ''; if (!is_null($as)) { settype($as, 'array'); $quotedAs .= ' AS ' . $this->quoteNameStr($as); } return $quotedName . $quotedAs; } else { $fin = array(); if (is_null($as)) { foreach ($name as $str) { $fin[] = $this->quoteName($str); } } elseif (is_array($name) && (count($name) == count($as))) { $count = count($name); for ($i = 0; $i < $count; $i++) { $fin[] = $this->quoteName($name[$i], $as[$i]); } } return $fin; } } /** * Quote strings coming from quoteName call. * * @param array $strArr Array of strings coming from quoteName dot-explosion. * * @return string Dot-imploded string of quoted parts. */ protected function quoteNameStr($strArr) { $parts = array(); $q = $this->nameQuote; foreach ($strArr as $part) { if (is_null($part)) { continue; } if (strlen($q) == 1) { $parts[] = $q . $part . $q; } else { $parts[] = $q{0} . $part . $q{1}; } } return implode('.', $parts); } /** * This function replaces a string identifier <var>$prefix</var> with the string held is the * <var>tablePrefix</var> class variable. * * @param string $query The SQL statement to prepare. * @param string $prefix The common table prefix. * * @return string The processed SQL statement. */ public function replacePrefix($query, $prefix = '#__') { $escaped = false; $startPos = 0; $quoteChar = ''; $literal = ''; $query = trim($query); $n = strlen($query); while ($startPos < $n) { $ip = strpos($query, $prefix, $startPos); if ($ip === false) { break; } $j = strpos($query, "'", $startPos); $k = strpos($query, '"', $startPos); if (($k !== false) && (($k < $j) || ($j === false))) { $quoteChar = '"'; $j = $k; } else { $quoteChar = "'"; } if ($j === false) { $j = $n; } $literal .= str_replace($prefix, $this->tablePrefix, substr($query, $startPos, $j - $startPos)); $startPos = $j; $j = $startPos + 1; if ($j >= $n) { break; } // Quote comes first, find end of quote while (true) { $k = strpos($query, $quoteChar, $j); $escaped = false; if ($k === false) { break; } $l = $k - 1; while ($l >= 0 && $query{$l} == '\\') { $l--; $escaped = !$escaped; } if ($escaped) { $j = $k + 1; continue; } break; } if ($k === false) { // Error in the query - no end quote; ignore it break; } $literal .= substr($query, $startPos, $k - $startPos + 1); $startPos = $k + 1; } if ($startPos < $n) { $literal .= substr($query, $startPos, $n - $startPos); } return $literal; } /** * Renames a table in the database. * * @param string $oldTable The name of the table to be renamed * @param string $newTable The new name for the table. * @param string $backup Table prefix * @param string $prefix For the table - used to rename constraints in non-mysql databases * * @return AEAbstractDriver Returns this object to support chaining. */ public abstract function renameTable($oldTable, $newTable, $backup = null, $prefix = null); /** * Select a database for use. * * @param string $database The name of the database to select for use. * * @return boolean True if the database was successfully selected. */ abstract public function select($database); /** * Sets the database debugging state for the driver. * * @param boolean $level True to enable debugging. * * @return boolean The old debugging level. */ public function setDebug($level) { $previous = $this->debug; $this->debug = (bool) $level; return $previous; } /** * Sets the SQL statement string for later execution. * * @param mixed $query The SQL statement to set either as a AEAbstractQuery object or a string. * @param integer $offset The affected row offset to set. * @param integer $limit The maximum affected rows to set. * * @return AEAbstractDriver This object to support method chaining. */ public function setQuery($query, $offset = 0, $limit = 0) { $this->sql = $query; $this->limit = (int) $limit; $this->offset = (int) $offset; return $this; } /** * Set the connection to use UTF-8 character encoding. * * @return boolean True on success. */ abstract public function setUTF(); /** * Method to commit a transaction. * * @return void */ abstract public function transactionCommit(); /** * Method to roll back a transaction. * * @return void */ abstract public function transactionRollback(); /** * Method to initialize a transaction. * * @return void */ abstract public function transactionStart(); /** * Method to truncate a table. * * @param string $table The table to truncate * * @return void */ public function truncateTable($table) { $this->setQuery('TRUNCATE TABLE ' . $this->quoteName($table)); $this->query(); } /** * Updates a row in a table based on an object's properties. * * @param string $table The name of the database table to update. * @param object &$object A reference to an object whose public properties match the table fields. * @param string $key The name of the primary key. * @param boolean $nulls True to update null fields or false to ignore them. * * @return boolean True on success. */ public function updateObject($table, &$object, $key, $nulls = false) { $fields = array(); $where = array(); if (is_string($key)) { $key = array($key); } if (is_object($key)) { $key = (array) $key; } // Create the base update statement. $statement = 'UPDATE ' . $this->quoteName($table) . ' SET %s WHERE %s'; // Iterate over the object variables to build the query fields/value pairs. foreach (get_object_vars($object) as $k => $v) { // Only process scalars that are not internal fields. if (is_array($v) or is_object($v) or $k[0] == '_') { continue; } // Set the primary key to the WHERE clause instead of a field to update. if (in_array($k, $key)) { $where[] = $this->quoteName($k) . '=' . $this->quote($v); continue; } // Prepare and sanitize the fields and values for the database query. if ($v === null) { // If the value is null and we want to update nulls then set it. if ($nulls) { $val = 'NULL'; } // If the value is null and we do not want to update nulls then ignore this field. else { continue; } } // The field is not null so we prep it for update. else { $val = $this->quote($v); } // Add the field to be updated. $fields[] = $this->quoteName($k) . '=' . $val; } // We don't have any fields to update. if (empty($fields)) { return true; } // Set the query and execute the update. $this->setQuery(sprintf($statement, implode(",", $fields), implode(' AND ', $where))); return $this->execute(); } /** * Unlocks tables in the database. * * @return AEAbstractDriver Returns this object to support chaining. */ public abstract function unlockTables(); /** * Get the error message * @return string The error message for the most recent query */ public final function getErrorMsg($escaped = false) { if($escaped) { return addslashes($this->errorMsg); } else { return $this->errorMsg; } } /** * Get the error number * @return int The error number for the most recent query */ public final function getErrorNum() { return $this->errorNum; } /** * Method to escape a string for usage in an SQL statement. * * @param string $text The string to be escaped. * @param boolean $extra Optional parameter to provide extra escaping. * * @return string The escaped string. */ public function getEscaped($text, $extra = false) { return $this->escape($text, $extra); } /** * Retrieves field information about the given tables. * * @param mixed $tables A table name or a list of table names. * @param boolean $typeOnly True to only return field types. * * @return array An array of fields by table. */ public function getTableFields($tables, $typeOnly = true) { $results = array(); settype($tables, 'array'); foreach ($tables as $table) { $results[$table] = $this->getTableColumns($table, $typeOnly); } return $results; } /** * Method to get an array of values from the <var>$offset</var> field in each row of the result set from * the database query. * * @param integer $offset The row offset to use to build the result array. * * @return mixed The return value or null if the query failed. */ public function loadResultArray($offset = 0) { return $this->loadColumn($offset); } /** * Wrap an SQL statement identifier name such as column, table or database names in quotes to prevent injection * risks and reserved word conflicts. * * @param string $name The identifier name to wrap in quotes. * * @return string The quote wrapped name. */ public function nameQuote($name) { return $this->quoteName($name); } /** * Returns the abstracted name of a database object * @param string $tableName * @return srting */ public function getAbstract( $tableName ) { $prefix = $this->getPrefix(); // Don't return abstract names for non-CMS tables if(is_null($prefix)) return $tableName; switch( $prefix ) { case '': // This is more of a hack; it assumes all tables are CMS tables if the prefix is empty. return '#__' . $tableName; break; default: // Normal behaviour for 99% of sites $tableAbstract = $tableName; if(!empty($prefix)) { if( substr($tableName, 0, strlen($prefix)) == $prefix ) { $tableAbstract = '#__' . substr($tableName, strlen($prefix)); } else { $tableAbstract = $tableName; } } return $tableAbstract; break; } } public final function getDriverType() { return $this->driverType; } public static function test() { return self::isSupported(); } }
effortlesssites/template
tmp/com_akeeba-3.9.2-core/backend/akeeba/abstract/driver.php
PHP
gpl-2.0
39,065
/* * Creado por SharpDevelop. * Usuario: jonathan * Fecha: 09/12/2013 * Hora: 11:17 p. m. * * Para cambiar esta plantilla use Herramientas | Opciones | Codificación | Editar Encabezados Estándar */ using System; using System.Drawing; using System.Windows.Forms; namespace Proyecto { /// <summary> /// Description of MenuConsulta. /// </summary> public partial class MenuConsulta : Form { public MenuConsulta() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // } void ButSalirClick(object sender, EventArgs e) { this.Close(); } void ButActualizarClick(object sender, EventArgs e) { } void ButConsultaClienteClick(object sender, EventArgs e) { ConsultaCliente cliente = new ConsultaCliente(); cliente.Show(); } } }
csaldana/Proyecto-final
ZombieSystem1.2.0/Proyecto V 1.1.1/Zombie System V1.2/Zombie System V1.3/Proyecto/MenuConsulta.cs
C#
gpl-2.0
939
/* * linux/sound/oss/dmasound/dmasound_awacs.c * * PowerMac `AWACS' and `Burgundy' DMA Sound Driver * with some limited support for DACA & Tumbler * * See linux/sound/oss/dmasound/dmasound_core.c for copyright and * history prior to 2001/01/26. * * 26/01/2001 ed 0.1 Iain Sandoe * - added version info. * - moved dbdma command buffer allocation to PMacXXXSqSetup() * - fixed up beep dbdma cmd buffers * * 08/02/2001 [0.2] * - make SNDCTL_DSP_GETFMTS return the correct info for the h/w * - move soft format translations to a separate file * - [0.3] make SNDCTL_DSP_GETCAPS return correct info. * - [0.4] more informative machine name strings. * - [0.5] * - record changes. * - made the default_hard/soft entries. * 04/04/2001 [0.6] * - minor correction to bit assignments in awacs_defs.h * - incorporate mixer changes from 2.2.x back-port. * - take out passthru as a rec input (it isn't). * - make Input Gain slider work the 'right way up'. * - try to make the mixer sliders more logical - so now the * input selectors are just two-state (>50% == ON) and the * Input Gain slider handles the rest of the gain issues. * - try to pick slider representations that most closely match * the actual use - e.g. IGain for input gain... * - first stab at over/under-run detection. * - minor cosmetic changes to IRQ identification. * - fix bug where rates > max would be reported as supported. * - first stab at over/under-run detection. * - make use of i2c for mixer settings conditional on perch * rather than cuda (some machines without perch have cuda). * - fix bug where TX stops when dbdma status comes up "DEAD" * so far only reported on PowerComputing clones ... but. * - put in AWACS/Screamer register write timeouts. * - part way to partitioning the init() stuff * - first pass at 'tumbler' stuff (not support - just an attempt * to allow the driver to load on new G4s). * 01/02/2002 [0.7] - BenH * - all sort of minor bits went in since the latest update, I * bumped the version number for that reason * * 07/26/2002 [0.8] - BenH * - More minor bits since last changelog (I should be more careful * with those) * - Support for snapper & better tumbler integration by Toby Sargeant * - Headphone detect for scremer by Julien Blache * - More tumbler fixed by Andreas Schwab * 11/29/2003 [0.8.1] - Renzo Davoli (King Enzo) * - Support for Snapper line in * - snapper input resampling (for rates < 44100) * - software line gain control */ /* GENERAL FIXME/TODO: check that the assumptions about what is written to mac-io is valid for DACA & Tumbler. This driver is in bad need of a rewrite. The dbdma code has to be split, some proper device-tree parsing code has to be written, etc... */ #include <linux/types.h> #include <linux/module.h> #include <linux/config.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/soundcard.h> #include <linux/adb.h> #include <linux/nvram.h> #include <linux/tty.h> #include <linux/vt_kern.h> #include <linux/spinlock.h> #include <linux/kmod.h> #include <linux/interrupt.h> #include <linux/input.h> #include <asm/semaphore.h> #ifdef CONFIG_ADB_CUDA #include <linux/cuda.h> #endif #ifdef CONFIG_ADB_PMU #include <linux/pmu.h> #endif #include <linux/i2c-dev.h> #include <asm/uaccess.h> #include <asm/prom.h> #include <asm/machdep.h> #include <asm/io.h> #include <asm/dbdma.h> #include <asm/pmac_feature.h> #include <asm/irq.h> #include <asm/nvram.h> #include "awacs_defs.h" #include "dmasound.h" #include "tas3001c.h" #include "tas3004.h" #include "tas_common.h" #define DMASOUND_AWACS_REVISION 0 #define DMASOUND_AWACS_EDITION 7 #define AWACS_SNAPPER 110 /* fake revision # for snapper */ #define AWACS_BURGUNDY 100 /* fake revision # for burgundy */ #define AWACS_TUMBLER 90 /* fake revision # for tumbler */ #define AWACS_DACA 80 /* fake revision # for daca (ibook) */ #define AWACS_AWACS 2 /* holding revision for AWACS */ #define AWACS_SCREAMER 3 /* holding revision for Screamer */ /* * Interrupt numbers and addresses, & info obtained from the device tree. */ static int awacs_irq, awacs_tx_irq, awacs_rx_irq; static volatile struct awacs_regs __iomem *awacs; static volatile u32 __iomem *i2s; static volatile struct dbdma_regs __iomem *awacs_txdma, *awacs_rxdma; static int awacs_rate_index; static int awacs_subframe; static struct device_node* awacs_node; static struct device_node* i2s_node; static char awacs_name[64]; static int awacs_revision; static int awacs_sleeping; static DECLARE_MUTEX(dmasound_sem); static int sound_device_id; /* exists after iMac revA */ static int hw_can_byteswap = 1 ; /* most pmac sound h/w can */ /* model info */ /* To be replaced with better interaction with pmac_feature.c */ static int is_pbook_3X00; static int is_pbook_g3; /* expansion info */ static int has_perch; static int has_ziva; /* for earlier powerbooks which need fiddling with mac-io to enable * cd etc. */ static unsigned char __iomem *latch_base; static unsigned char __iomem *macio_base; /* * Space for the DBDMA command blocks. */ static void *awacs_tx_cmd_space; static volatile struct dbdma_cmd *awacs_tx_cmds; static int number_of_tx_cmd_buffers; static void *awacs_rx_cmd_space; static volatile struct dbdma_cmd *awacs_rx_cmds; static int number_of_rx_cmd_buffers; /* * Cached values of AWACS registers (we can't read them). * Except on the burgundy (and screamer). XXX */ int awacs_reg[8]; int awacs_reg1_save; /* tracking values for the mixer contents */ static int spk_vol; static int line_vol; static int passthru_vol; static int ip_gain; /* mic preamp settings */ static int rec_lev = 0x4545 ; /* default CD gain 69 % */ static int mic_lev; static int cd_lev = 0x6363 ; /* 99 % */ static int line_lev; static int hdp_connected; /* * Stuff for outputting a beep. The values range from -327 to +327 * so we can multiply by an amplitude in the range 0..100 to get a * signed short value to put in the output buffer. */ static short beep_wform[256] = { 0, 40, 79, 117, 153, 187, 218, 245, 269, 288, 304, 316, 323, 327, 327, 324, 318, 310, 299, 288, 275, 262, 249, 236, 224, 213, 204, 196, 190, 186, 183, 182, 182, 183, 186, 189, 192, 196, 200, 203, 206, 208, 209, 209, 209, 207, 204, 201, 197, 193, 188, 183, 179, 174, 170, 166, 163, 161, 160, 159, 159, 160, 161, 162, 164, 166, 168, 169, 171, 171, 171, 170, 169, 167, 163, 159, 155, 150, 144, 139, 133, 128, 122, 117, 113, 110, 107, 105, 103, 103, 103, 103, 104, 104, 105, 105, 105, 103, 101, 97, 92, 86, 78, 68, 58, 45, 32, 18, 3, -11, -26, -41, -55, -68, -79, -88, -95, -100, -102, -102, -99, -93, -85, -75, -62, -48, -33, -16, 0, 16, 33, 48, 62, 75, 85, 93, 99, 102, 102, 100, 95, 88, 79, 68, 55, 41, 26, 11, -3, -18, -32, -45, -58, -68, -78, -86, -92, -97, -101, -103, -105, -105, -105, -104, -104, -103, -103, -103, -103, -105, -107, -110, -113, -117, -122, -128, -133, -139, -144, -150, -155, -159, -163, -167, -169, -170, -171, -171, -171, -169, -168, -166, -164, -162, -161, -160, -159, -159, -160, -161, -163, -166, -170, -174, -179, -183, -188, -193, -197, -201, -204, -207, -209, -209, -209, -208, -206, -203, -200, -196, -192, -189, -186, -183, -182, -182, -183, -186, -190, -196, -204, -213, -224, -236, -249, -262, -275, -288, -299, -310, -318, -324, -327, -327, -323, -316, -304, -288, -269, -245, -218, -187, -153, -117, -79, -40, }; /* beep support */ #define BEEP_SRATE 22050 /* 22050 Hz sample rate */ #define BEEP_BUFLEN 512 #define BEEP_VOLUME 15 /* 0 - 100 */ static int beep_vol = BEEP_VOLUME; static int beep_playing; static int awacs_beep_state; static short *beep_buf; static void *beep_dbdma_cmd_space; static volatile struct dbdma_cmd *beep_dbdma_cmd; /* Burgundy functions */ static void awacs_burgundy_wcw(unsigned addr,unsigned newval); static unsigned awacs_burgundy_rcw(unsigned addr); static void awacs_burgundy_write_volume(unsigned address, int volume); static int awacs_burgundy_read_volume(unsigned address); static void awacs_burgundy_write_mvolume(unsigned address, int volume); static int awacs_burgundy_read_mvolume(unsigned address); /* we will allocate a single 'emergency' dbdma cmd block to use if the tx status comes up "DEAD". This happens on some PowerComputing Pmac clones, either owing to a bug in dbdma or some interaction between IDE and sound. However, this measure would deal with DEAD status if if appeared elsewhere. for the sake of memory efficiency we'll allocate this cmd as part of the beep cmd stuff. */ static volatile struct dbdma_cmd *emergency_dbdma_cmd; #ifdef CONFIG_PM /* * Stuff for restoring after a sleep. */ static int awacs_sleep_notify(struct pmu_sleep_notifier *self, int when); struct pmu_sleep_notifier awacs_sleep_notifier = { awacs_sleep_notify, SLEEP_LEVEL_SOUND, }; #endif /* CONFIG_PM */ /* for (soft) sample rate translations */ int expand_bal; /* Balance factor for expanding (not volume!) */ int expand_read_bal; /* Balance factor for expanding reads (not volume!) */ /*** Low level stuff *********************************************************/ static void *PMacAlloc(unsigned int size, int flags); static void PMacFree(void *ptr, unsigned int size); static int PMacIrqInit(void); #ifdef MODULE static void PMacIrqCleanup(void); #endif static void PMacSilence(void); static void PMacInit(void); static int PMacSetFormat(int format); static int PMacSetVolume(int volume); static void PMacPlay(void); static void PMacRecord(void); static irqreturn_t pmac_awacs_tx_intr(int irq, void *devid, struct pt_regs *regs); static irqreturn_t pmac_awacs_rx_intr(int irq, void *devid, struct pt_regs *regs); static irqreturn_t pmac_awacs_intr(int irq, void *devid, struct pt_regs *regs); static void awacs_write(int val); static int awacs_get_volume(int reg, int lshift); static int awacs_volume_setter(int volume, int n, int mute, int lshift); /*** Mid level stuff **********************************************************/ static int PMacMixerIoctl(u_int cmd, u_long arg); static int PMacWriteSqSetup(void); static int PMacReadSqSetup(void); static void PMacAbortRead(void); extern TRANS transAwacsNormal ; extern TRANS transAwacsExpand ; extern TRANS transAwacsNormalRead ; extern TRANS transAwacsExpandRead ; extern int daca_init(void); extern void daca_cleanup(void); extern int daca_set_volume(uint left_vol, uint right_vol); extern void daca_get_volume(uint * left_vol, uint *right_vol); extern int daca_enter_sleep(void); extern int daca_leave_sleep(void); #define TRY_LOCK() \ if ((rc = down_interruptible(&dmasound_sem)) != 0) \ return rc; #define LOCK() down(&dmasound_sem); #define UNLOCK() up(&dmasound_sem); /* We use different versions that the ones provided in dmasound.h * * FIXME: Use different names ;) */ #undef IOCTL_IN #undef IOCTL_OUT #define IOCTL_IN(arg, ret) \ rc = get_user(ret, (int __user *)(arg)); \ if (rc) break; #define IOCTL_OUT(arg, ret) \ ioctl_return2((int __user *)(arg), ret) static inline int ioctl_return2(int __user *addr, int value) { return value < 0 ? value : put_user(value, addr); } /*** AE - TUMBLER / SNAPPER START ************************************************/ int gpio_audio_reset, gpio_audio_reset_pol; int gpio_amp_mute, gpio_amp_mute_pol; int gpio_headphone_mute, gpio_headphone_mute_pol; int gpio_headphone_detect, gpio_headphone_detect_pol; int gpio_headphone_irq; int setup_audio_gpio(const char *name, const char* compatible, int *gpio_addr, int* gpio_pol) { struct device_node *np; u32* pp; np = find_devices("gpio"); if (!np) return -ENODEV; np = np->child; while(np != 0) { if (name) { char *property = get_property(np,"audio-gpio",NULL); if (property != 0 && strcmp(property,name) == 0) break; } else if (compatible && device_is_compatible(np, compatible)) break; np = np->sibling; } if (!np) return -ENODEV; pp = (u32 *)get_property(np, "AAPL,address", NULL); if (!pp) return -ENODEV; *gpio_addr = (*pp) & 0x0000ffff; pp = (u32 *)get_property(np, "audio-gpio-active-state", NULL); if (pp) *gpio_pol = *pp; else *gpio_pol = 1; if (np->n_intrs > 0) return np->intrs[0].line; return 0; } static inline void write_audio_gpio(int gpio_addr, int data) { if (!gpio_addr) return; pmac_call_feature(PMAC_FTR_WRITE_GPIO, NULL, gpio_addr, data ? 0x05 : 0x04); } static inline int read_audio_gpio(int gpio_addr) { if (!gpio_addr) return 0; return ((pmac_call_feature(PMAC_FTR_READ_GPIO, NULL, gpio_addr, 0) & 0x02) !=0); } /* * Headphone interrupt via GPIO (Tumbler, Snapper, DACA) */ static irqreturn_t headphone_intr(int irq, void *devid, struct pt_regs *regs) { unsigned long flags; spin_lock_irqsave(&dmasound.lock, flags); if (read_audio_gpio(gpio_headphone_detect) == gpio_headphone_detect_pol) { printk(KERN_INFO "Audio jack plugged, muting speakers.\n"); write_audio_gpio(gpio_headphone_mute, !gpio_headphone_mute_pol); write_audio_gpio(gpio_amp_mute, gpio_amp_mute_pol); tas_output_device_change(sound_device_id,TAS_OUTPUT_HEADPHONES,0); } else { printk(KERN_INFO "Audio jack unplugged, enabling speakers.\n"); write_audio_gpio(gpio_amp_mute, !gpio_amp_mute_pol); write_audio_gpio(gpio_headphone_mute, gpio_headphone_mute_pol); tas_output_device_change(sound_device_id,TAS_OUTPUT_INTERNAL_SPKR,0); } spin_unlock_irqrestore(&dmasound.lock, flags); return IRQ_HANDLED; } /* Initialize tumbler */ static int tas_dmasound_init(void) { setup_audio_gpio( "audio-hw-reset", NULL, &gpio_audio_reset, &gpio_audio_reset_pol); setup_audio_gpio( "amp-mute", NULL, &gpio_amp_mute, &gpio_amp_mute_pol); setup_audio_gpio("headphone-mute", NULL, &gpio_headphone_mute, &gpio_headphone_mute_pol); gpio_headphone_irq = setup_audio_gpio( "headphone-detect", NULL, &gpio_headphone_detect, &gpio_headphone_detect_pol); /* Fix some broken OF entries in desktop machines */ if (!gpio_headphone_irq) gpio_headphone_irq = setup_audio_gpio( NULL, "keywest-gpio15", &gpio_headphone_detect, &gpio_headphone_detect_pol); write_audio_gpio(gpio_audio_reset, gpio_audio_reset_pol); msleep(100); write_audio_gpio(gpio_audio_reset, !gpio_audio_reset_pol); msleep(100); if (gpio_headphone_irq) { if (request_irq(gpio_headphone_irq,headphone_intr,0,"Headphone detect",NULL) < 0) { printk(KERN_ERR "tumbler: Can't request headphone interrupt\n"); gpio_headphone_irq = 0; } else { u8 val; /* Activate headphone status interrupts */ val = pmac_call_feature(PMAC_FTR_READ_GPIO, NULL, gpio_headphone_detect, 0); pmac_call_feature(PMAC_FTR_WRITE_GPIO, NULL, gpio_headphone_detect, val | 0x80); /* Trigger it */ headphone_intr(0,NULL,NULL); } } if (!gpio_headphone_irq) { /* Some machine enter this case ? */ printk(KERN_WARNING "tumbler: Headphone detect IRQ not found, enabling all outputs !\n"); write_audio_gpio(gpio_amp_mute, !gpio_amp_mute_pol); write_audio_gpio(gpio_headphone_mute, !gpio_headphone_mute_pol); } return 0; } static int tas_dmasound_cleanup(void) { if (gpio_headphone_irq) free_irq(gpio_headphone_irq, NULL); return 0; } /* We don't support 48k yet */ static int tas_freqs[1] = { 44100 } ; static int tas_freqs_ok[1] = { 1 } ; /* don't know what to do really - just have to leave it where * OF left things */ static int tas_set_frame_rate(void) { if (i2s) { out_le32(i2s + (I2S_REG_SERIAL_FORMAT >> 2), 0x41190000); out_le32(i2s + (I2S_REG_DATAWORD_SIZES >> 2), 0x02000200); } dmasound.hard.speed = 44100 ; awacs_rate_index = 0 ; return 44100 ; } static int tas_mixer_ioctl(u_int cmd, u_long arg) { int __user *argp = (int __user *)arg; int data; int rc; rc=tas_device_ioctl(cmd, arg); if (rc != -EINVAL) { return rc; } if ((cmd & ~0xff) == MIXER_WRITE(0) && tas_supported_mixers() & (1<<(cmd & 0xff))) { rc = get_user(data, argp); if (rc<0) return rc; tas_set_mixer_level(cmd & 0xff, data); tas_get_mixer_level(cmd & 0xff, &data); return ioctl_return2(argp, data); } if ((cmd & ~0xff) == MIXER_READ(0) && tas_supported_mixers() & (1<<(cmd & 0xff))) { tas_get_mixer_level(cmd & 0xff, &data); return ioctl_return2(argp, data); } switch(cmd) { case SOUND_MIXER_READ_DEVMASK: data = tas_supported_mixers() | SOUND_MASK_SPEAKER; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_STEREODEVS: data = tas_stereo_mixers(); rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_CAPS: rc = IOCTL_OUT(arg, 0); break; case SOUND_MIXER_READ_RECMASK: // XXX FIXME: find a way to check what is really available */ data = SOUND_MASK_LINE | SOUND_MASK_MIC; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_RECSRC: if (awacs_reg[0] & MASK_MUX_AUDIN) data |= SOUND_MASK_LINE; if (awacs_reg[0] & MASK_MUX_MIC) data |= SOUND_MASK_MIC; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_WRITE_RECSRC: IOCTL_IN(arg, data); data =0; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_WRITE_SPEAKER: /* really bell volume */ IOCTL_IN(arg, data); beep_vol = data & 0xff; /* fall through */ case SOUND_MIXER_READ_SPEAKER: rc = IOCTL_OUT(arg, (beep_vol<<8) | beep_vol); break; case SOUND_MIXER_OUTMASK: case SOUND_MIXER_OUTSRC: default: rc = -EINVAL; } return rc; } static void __init tas_init_frame_rates(unsigned int *prop, unsigned int l) { int i ; if (prop) { for (i=0; i<1; i++) tas_freqs_ok[i] = 0; for (l /= sizeof(int); l > 0; --l) { unsigned int r = *prop++; /* Apple 'Fixed' format */ if (r >= 0x10000) r >>= 16; for (i = 0; i < 1; ++i) { if (r == tas_freqs[i]) { tas_freqs_ok[i] = 1; break; } } } } /* else we assume that all the rates are available */ } /*** AE - TUMBLER / SNAPPER END ************************************************/ /*** Low level stuff *********************************************************/ /* * PCI PowerMac, with AWACS, Screamer, Burgundy, DACA or Tumbler and DBDMA. */ static void *PMacAlloc(unsigned int size, int flags) { return kmalloc(size, flags); } static void PMacFree(void *ptr, unsigned int size) { kfree(ptr); } static int __init PMacIrqInit(void) { if (awacs) if (request_irq(awacs_irq, pmac_awacs_intr, 0, "Built-in Sound misc", NULL)) return 0; if (request_irq(awacs_tx_irq, pmac_awacs_tx_intr, 0, "Built-in Sound out", NULL) || request_irq(awacs_rx_irq, pmac_awacs_rx_intr, 0, "Built-in Sound in", NULL)) return 0; return 1; } #ifdef MODULE static void PMacIrqCleanup(void) { /* turn off input & output dma */ DBDMA_DO_STOP(awacs_txdma); DBDMA_DO_STOP(awacs_rxdma); if (awacs) /* disable interrupts from awacs interface */ out_le32(&awacs->control, in_le32(&awacs->control) & 0xfff); /* Switch off the sound clock */ pmac_call_feature(PMAC_FTR_SOUND_CHIP_ENABLE, awacs_node, 0, 0); /* Make sure proper bits are set on pismo & tipb */ if ((machine_is_compatible("PowerBook3,1") || machine_is_compatible("PowerBook3,2")) && awacs) { awacs_reg[1] |= MASK_PAROUT0 | MASK_PAROUT1; awacs_write(MASK_ADDR1 | awacs_reg[1]); msleep(200); } if (awacs) free_irq(awacs_irq, NULL); free_irq(awacs_tx_irq, NULL); free_irq(awacs_rx_irq, NULL); if (awacs) iounmap(awacs); if (i2s) iounmap(i2s); iounmap(awacs_txdma); iounmap(awacs_rxdma); release_OF_resource(awacs_node, 0); release_OF_resource(awacs_node, 1); release_OF_resource(awacs_node, 2); kfree(awacs_tx_cmd_space); kfree(awacs_rx_cmd_space); kfree(beep_dbdma_cmd_space); kfree(beep_buf); #ifdef CONFIG_PM pmu_unregister_sleep_notifier(&awacs_sleep_notifier); #endif } #endif /* MODULE */ static void PMacSilence(void) { /* turn off output dma */ DBDMA_DO_STOP(awacs_txdma); } /* don't know what to do really - just have to leave it where * OF left things */ static int daca_set_frame_rate(void) { if (i2s) { out_le32(i2s + (I2S_REG_SERIAL_FORMAT >> 2), 0x41190000); out_le32(i2s + (I2S_REG_DATAWORD_SIZES >> 2), 0x02000200); } dmasound.hard.speed = 44100 ; awacs_rate_index = 0 ; return 44100 ; } static int awacs_freqs[8] = { 44100, 29400, 22050, 17640, 14700, 11025, 8820, 7350 }; static int awacs_freqs_ok[8] = { 1, 1, 1, 1, 1, 1, 1, 1 }; static int awacs_set_frame_rate(int desired, int catch_r) { int tolerance, i = 8 ; /* * If we have a sample rate which is within catchRadius percent * of the requested value, we don't have to expand the samples. * Otherwise choose the next higher rate. * N.B.: burgundy awacs only works at 44100 Hz. */ do { tolerance = catch_r * awacs_freqs[--i] / 100; if (awacs_freqs_ok[i] && dmasound.soft.speed <= awacs_freqs[i] + tolerance) break; } while (i > 0); dmasound.hard.speed = awacs_freqs[i]; awacs_rate_index = i; out_le32(&awacs->control, MASK_IEPC | (i << 8) | 0x11 ); awacs_reg[1] = (awacs_reg[1] & ~MASK_SAMPLERATE) | (i << 3); awacs_write(awacs_reg[1] | MASK_ADDR1); return dmasound.hard.speed; } static int burgundy_set_frame_rate(void) { awacs_rate_index = 0 ; awacs_reg[1] = (awacs_reg[1] & ~MASK_SAMPLERATE) ; /* XXX disable error interrupt on burgundy for now */ out_le32(&awacs->control, MASK_IEPC | 0 | 0x11 | MASK_IEE); return 44100 ; } static int set_frame_rate(int desired, int catch_r) { switch (awacs_revision) { case AWACS_BURGUNDY: dmasound.hard.speed = burgundy_set_frame_rate(); break ; case AWACS_TUMBLER: case AWACS_SNAPPER: dmasound.hard.speed = tas_set_frame_rate(); break ; case AWACS_DACA: dmasound.hard.speed = daca_set_frame_rate(); break ; default: dmasound.hard.speed = awacs_set_frame_rate(desired, catch_r); break ; } return dmasound.hard.speed ; } static void awacs_recalibrate(void) { /* Sorry for the horrible delays... I hope to get that improved * by making the whole PM process asynchronous in a future version */ msleep(750); awacs_reg[1] |= MASK_CMUTE | MASK_AMUTE; awacs_write(awacs_reg[1] | MASK_RECALIBRATE | MASK_ADDR1); msleep(1000); awacs_write(awacs_reg[1] | MASK_ADDR1); } static void PMacInit(void) { int tolerance; switch (dmasound.soft.format) { case AFMT_S16_LE: case AFMT_U16_LE: if (hw_can_byteswap) dmasound.hard.format = AFMT_S16_LE; else dmasound.hard.format = AFMT_S16_BE; break; default: dmasound.hard.format = AFMT_S16_BE; break; } dmasound.hard.stereo = 1; dmasound.hard.size = 16; /* set dmasound.hard.speed - on the basis of what we want (soft) * and the tolerance we'll allow. */ set_frame_rate(dmasound.soft.speed, catchRadius) ; tolerance = (catchRadius * dmasound.hard.speed) / 100; if (dmasound.soft.speed >= dmasound.hard.speed - tolerance) { dmasound.trans_write = &transAwacsNormal; dmasound.trans_read = &transAwacsNormalRead; } else { dmasound.trans_write = &transAwacsExpand; dmasound.trans_read = &transAwacsExpandRead; } if (awacs) { if (hw_can_byteswap && (dmasound.hard.format == AFMT_S16_LE)) out_le32(&awacs->byteswap, BS_VAL); else out_le32(&awacs->byteswap, 0); } expand_bal = -dmasound.soft.speed; expand_read_bal = -dmasound.soft.speed; } static int PMacSetFormat(int format) { int size; int req_format = format; switch (format) { case AFMT_QUERY: return dmasound.soft.format; case AFMT_MU_LAW: case AFMT_A_LAW: case AFMT_U8: case AFMT_S8: size = 8; break; case AFMT_S16_LE: if(!hw_can_byteswap) format = AFMT_S16_BE; case AFMT_S16_BE: size = 16; break; case AFMT_U16_LE: if(!hw_can_byteswap) format = AFMT_U16_BE; case AFMT_U16_BE: size = 16; break; default: /* :-) */ printk(KERN_ERR "dmasound: unknown format 0x%x, using AFMT_U8\n", format); size = 8; format = AFMT_U8; } if (req_format == format) { dmasound.soft.format = format; dmasound.soft.size = size; if (dmasound.minDev == SND_DEV_DSP) { dmasound.dsp.format = format; dmasound.dsp.size = size; } } return format; } #define AWACS_VOLUME_TO_MASK(x) (15 - ((((x) - 1) * 15) / 99)) #define AWACS_MASK_TO_VOLUME(y) (100 - ((y) * 99 / 15)) static int awacs_get_volume(int reg, int lshift) { int volume; volume = AWACS_MASK_TO_VOLUME((reg >> lshift) & 0xf); volume |= AWACS_MASK_TO_VOLUME(reg & 0xf) << 8; return volume; } static int awacs_volume_setter(int volume, int n, int mute, int lshift) { int r1, rn; if (mute && volume == 0) { r1 = awacs_reg[1] | mute; } else { r1 = awacs_reg[1] & ~mute; rn = awacs_reg[n] & ~(0xf | (0xf << lshift)); rn |= ((AWACS_VOLUME_TO_MASK(volume & 0xff) & 0xf) << lshift); rn |= AWACS_VOLUME_TO_MASK((volume >> 8) & 0xff) & 0xf; awacs_reg[n] = rn; awacs_write((n << 12) | rn); volume = awacs_get_volume(rn, lshift); } if (r1 != awacs_reg[1]) { awacs_reg[1] = r1; awacs_write(r1 | MASK_ADDR1); } return volume; } static int PMacSetVolume(int volume) { printk(KERN_WARNING "Bogus call to PMacSetVolume !\n"); return 0; } static void awacs_setup_for_beep(int speed) { out_le32(&awacs->control, (in_le32(&awacs->control) & ~0x1f00) | ((speed > 0 ? speed : awacs_rate_index) << 8)); if (hw_can_byteswap && (dmasound.hard.format == AFMT_S16_LE) && speed == -1) out_le32(&awacs->byteswap, BS_VAL); else out_le32(&awacs->byteswap, 0); } /* CHECK: how much of this *really* needs IRQs masked? */ static void __PMacPlay(void) { volatile struct dbdma_cmd *cp; int next_frg, count; count = 300 ; /* > two cycles at the lowest sample rate */ /* what we want to send next */ next_frg = (write_sq.front + write_sq.active) % write_sq.max_count; if (awacs_beep_state) { /* sound takes precedence over beeps */ /* stop the dma channel */ out_le32(&awacs_txdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16); while ( (in_le32(&awacs_txdma->status) & RUN) && count--) udelay(1); if (awacs) awacs_setup_for_beep(-1); out_le32(&awacs_txdma->cmdptr, virt_to_bus(&(awacs_tx_cmds[next_frg]))); beep_playing = 0; awacs_beep_state = 0; } /* this won't allow more than two frags to be in the output queue at once. (or one, if the max frags is 2 - because count can't exceed 2 in that case) */ while (write_sq.active < 2 && write_sq.active < write_sq.count) { count = (write_sq.count == write_sq.active + 1) ? write_sq.rear_size:write_sq.block_size ; if (count < write_sq.block_size) { if (!write_sq.syncing) /* last block not yet filled,*/ break; /* and we're not syncing or POST-ed */ else { /* pretend the block is full to force a new block to be started on the next write */ write_sq.rear_size = write_sq.block_size ; write_sq.syncing &= ~2 ; /* clear POST */ } } cp = &awacs_tx_cmds[next_frg]; st_le16(&cp->req_count, count); st_le16(&cp->xfer_status, 0); st_le16(&cp->command, OUTPUT_MORE + INTR_ALWAYS); /* put a STOP at the end of the queue - but only if we have space for it. This means that, if we under-run and we only have two fragments, we might re-play sound from an existing queued frag. I guess the solution to that is not to set two frags if you are likely to under-run... */ if (write_sq.count < write_sq.max_count) { if (++next_frg >= write_sq.max_count) next_frg = 0 ; /* wrap */ /* if we get here then we've underrun so we will stop*/ st_le16(&awacs_tx_cmds[next_frg].command, DBDMA_STOP); } /* set the dbdma controller going, if it is not already */ if (write_sq.active == 0) out_le32(&awacs_txdma->cmdptr, virt_to_bus(cp)); (void)in_le32(&awacs_txdma->status); out_le32(&awacs_txdma->control, ((RUN|WAKE) << 16) + (RUN|WAKE)); ++write_sq.active; } } static void PMacPlay(void) { LOCK(); if (!awacs_sleeping) { unsigned long flags; spin_lock_irqsave(&dmasound.lock, flags); __PMacPlay(); spin_unlock_irqrestore(&dmasound.lock, flags); } UNLOCK(); } static void PMacRecord(void) { unsigned long flags; if (read_sq.active) return; spin_lock_irqsave(&dmasound.lock, flags); /* This is all we have to do......Just start it up. */ out_le32(&awacs_rxdma->control, ((RUN|WAKE) << 16) + (RUN|WAKE)); read_sq.active = 1; spin_unlock_irqrestore(&dmasound.lock, flags); } /* if the TX status comes up "DEAD" - reported on some Power Computing machines we need to re-start the dbdma - but from a different physical start address and with a different transfer length. It would get very messy to do this with the normal dbdma_cmd blocks - we would have to re-write the buffer start addresses each time. So, we will keep a single dbdma_cmd block which can be fiddled with. When DEAD status is first reported the content of the faulted dbdma block is copied into the emergency buffer and we note that the buffer is in use. we then bump the start physical address by the amount that was successfully output before it died. On any subsequent DEAD result we just do the bump-ups (we know that we are already using the emergency dbdma_cmd). CHECK: this just tries to "do it". It is possible that we should abandon xfers when the number of residual bytes gets below a certain value - I can see that this might cause a loop-forever if too small a transfer causes DEAD status. However this is a TODO for now - we'll see what gets reported. When we get a successful transfer result with the emergency buffer we just pretend that it completed using the original dmdma_cmd and carry on. The 'next_cmd' field will already point back to the original loop of blocks. */ static irqreturn_t pmac_awacs_tx_intr(int irq, void *devid, struct pt_regs *regs) { int i = write_sq.front; int stat; int i_nowrap = write_sq.front; volatile struct dbdma_cmd *cp; /* != 0 when we are dealing with a DEAD xfer */ static int emergency_in_use; spin_lock(&dmasound.lock); while (write_sq.active > 0) { /* we expect to have done something*/ if (emergency_in_use) /* we are dealing with DEAD xfer */ cp = emergency_dbdma_cmd ; else cp = &awacs_tx_cmds[i]; stat = ld_le16(&cp->xfer_status); if (stat & DEAD) { unsigned short req, res ; unsigned int phy ; #ifdef DEBUG_DMASOUND printk("dmasound_pmac: tx-irq: xfer died - patching it up...\n") ; #endif /* to clear DEAD status we must first clear RUN set it to quiescent to be on the safe side */ (void)in_le32(&awacs_txdma->status); out_le32(&awacs_txdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16); write_sq.died++ ; if (!emergency_in_use) { /* new problem */ memcpy((void *)emergency_dbdma_cmd, (void *)cp, sizeof(struct dbdma_cmd)); emergency_in_use = 1; cp = emergency_dbdma_cmd; } /* now bump the values to reflect the amount we haven't yet shifted */ req = ld_le16(&cp->req_count); res = ld_le16(&cp->res_count); phy = ld_le32(&cp->phy_addr); phy += (req - res); st_le16(&cp->req_count, res); st_le16(&cp->res_count, 0); st_le16(&cp->xfer_status, 0); st_le32(&cp->phy_addr, phy); st_le32(&cp->cmd_dep, virt_to_bus(&awacs_tx_cmds[(i+1)%write_sq.max_count])); st_le16(&cp->command, OUTPUT_MORE | BR_ALWAYS | INTR_ALWAYS); /* point at our patched up command block */ out_le32(&awacs_txdma->cmdptr, virt_to_bus(cp)); /* we must re-start the controller */ (void)in_le32(&awacs_txdma->status); /* should complete clearing the DEAD status */ out_le32(&awacs_txdma->control, ((RUN|WAKE) << 16) + (RUN|WAKE)); break; /* this block is still going */ } if ((stat & ACTIVE) == 0) break; /* this frame is still going */ if (emergency_in_use) emergency_in_use = 0 ; /* done that */ --write_sq.count; --write_sq.active; i_nowrap++; if (++i >= write_sq.max_count) i = 0; } /* if we stopped and we were not sync-ing - then we under-ran */ if( write_sq.syncing == 0 ){ stat = in_le32(&awacs_txdma->status) ; /* we hit the dbdma_stop */ if( (stat & ACTIVE) == 0 ) write_sq.xruns++ ; } /* if we used some data up then wake the writer to supply some more*/ if (i_nowrap != write_sq.front) WAKE_UP(write_sq.action_queue); write_sq.front = i; /* but make sure we funnel what we've already got */\ if (!awacs_sleeping) __PMacPlay(); /* make the wake-on-empty conditional on syncing */ if (!write_sq.active && (write_sq.syncing & 1)) WAKE_UP(write_sq.sync_queue); /* any time we're empty */ spin_unlock(&dmasound.lock); return IRQ_HANDLED; } static irqreturn_t pmac_awacs_rx_intr(int irq, void *devid, struct pt_regs *regs) { int stat ; /* For some reason on my PowerBook G3, I get one interrupt * when the interrupt vector is installed (like something is * pending). This happens before the dbdma is initialized by * us, so I just check the command pointer and if it is zero, * just blow it off. */ if (in_le32(&awacs_rxdma->cmdptr) == 0) return IRQ_HANDLED; /* We also want to blow 'em off when shutting down. */ if (read_sq.active == 0) return IRQ_HANDLED; spin_lock(&dmasound.lock); /* Check multiple buffers in case we were held off from * interrupt processing for a long time. Geeze, I really hope * this doesn't happen. */ while ((stat=awacs_rx_cmds[read_sq.rear].xfer_status)) { /* if we got a "DEAD" status then just log it for now. and try to restart dma. TODO: figure out how best to fix it up */ if (stat & DEAD){ #ifdef DEBUG_DMASOUND printk("dmasound_pmac: rx-irq: DIED - attempting resurection\n"); #endif /* to clear DEAD status we must first clear RUN set it to quiescent to be on the safe side */ (void)in_le32(&awacs_txdma->status); out_le32(&awacs_txdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16); awacs_rx_cmds[read_sq.rear].xfer_status = 0; awacs_rx_cmds[read_sq.rear].res_count = 0; read_sq.died++ ; (void)in_le32(&awacs_txdma->status); /* re-start the same block */ out_le32(&awacs_rxdma->cmdptr, virt_to_bus(&awacs_rx_cmds[read_sq.rear])); /* we must re-start the controller */ (void)in_le32(&awacs_rxdma->status); /* should complete clearing the DEAD status */ out_le32(&awacs_rxdma->control, ((RUN|WAKE) << 16) + (RUN|WAKE)); spin_unlock(&dmasound.lock); return IRQ_HANDLED; /* try this block again */ } /* Clear status and move on to next buffer. */ awacs_rx_cmds[read_sq.rear].xfer_status = 0; read_sq.rear++; /* Wrap the buffer ring. */ if (read_sq.rear >= read_sq.max_active) read_sq.rear = 0; /* If we have caught up to the front buffer, bump it. * This will cause weird (but not fatal) results if the * read loop is currently using this buffer. The user is * behind in this case anyway, so weird things are going * to happen. */ if (read_sq.rear == read_sq.front) { read_sq.front++; read_sq.xruns++ ; /* we overan */ if (read_sq.front >= read_sq.max_active) read_sq.front = 0; } } WAKE_UP(read_sq.action_queue); spin_unlock(&dmasound.lock); return IRQ_HANDLED; } static irqreturn_t pmac_awacs_intr(int irq, void *devid, struct pt_regs *regs) { int ctrl; int status; int r1; spin_lock(&dmasound.lock); ctrl = in_le32(&awacs->control); status = in_le32(&awacs->codec_stat); if (ctrl & MASK_PORTCHG) { /* tested on Screamer, should work on others too */ if (awacs_revision == AWACS_SCREAMER) { if (((status & MASK_HDPCONN) >> 3) && (hdp_connected == 0)) { hdp_connected = 1; r1 = awacs_reg[1] | MASK_SPKMUTE; awacs_reg[1] = r1; awacs_write(r1 | MASK_ADDR_MUTE); } else if (((status & MASK_HDPCONN) >> 3 == 0) && (hdp_connected == 1)) { hdp_connected = 0; r1 = awacs_reg[1] & ~MASK_SPKMUTE; awacs_reg[1] = r1; awacs_write(r1 | MASK_ADDR_MUTE); } } } if (ctrl & MASK_CNTLERR) { int err = (in_le32(&awacs->codec_stat) & MASK_ERRCODE) >> 16; /* CHECK: we just swallow burgundy errors at the moment..*/ if (err != 0 && awacs_revision != AWACS_BURGUNDY) printk(KERN_ERR "dmasound_pmac: error %x\n", err); } /* Writing 1s to the CNTLERR and PORTCHG bits clears them... */ out_le32(&awacs->control, ctrl); spin_unlock(&dmasound.lock); return IRQ_HANDLED; } static void awacs_write(int val) { int count = 300 ; if (awacs_revision >= AWACS_DACA || !awacs) return ; while ((in_le32(&awacs->codec_ctrl) & MASK_NEWECMD) && count--) udelay(1) ; /* timeout is > 2 samples at lowest rate */ out_le32(&awacs->codec_ctrl, val | (awacs_subframe << 22)); (void)in_le32(&awacs->byteswap); } /* this is called when the beep timer expires... it will be called even if the beep has been overidden by other sound output. */ static void awacs_nosound(unsigned long xx) { unsigned long flags; int count = 600 ; /* > four samples at lowest rate */ spin_lock_irqsave(&dmasound.lock, flags); if (beep_playing) { st_le16(&beep_dbdma_cmd->command, DBDMA_STOP); out_le32(&awacs_txdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16); while ((in_le32(&awacs_txdma->status) & RUN) && count--) udelay(1); if (awacs) awacs_setup_for_beep(-1); beep_playing = 0; } spin_unlock_irqrestore(&dmasound.lock, flags); } /* * We generate the beep with a single dbdma command that loops a buffer * forever - without generating interrupts. * * So, to stop it you have to stop dma output as per awacs_nosound. */ static int awacs_beep_event(struct input_dev *dev, unsigned int type, unsigned int code, int hz) { unsigned long flags; int beep_speed = 0; int srate; int period, ncycles, nsamples; int i, j, f; short *p; static int beep_hz_cache; static int beep_nsamples_cache; static int beep_volume_cache; if (type != EV_SND) return -1; switch (code) { case SND_BELL: if (hz) hz = 1000; break; case SND_TONE: break; default: return -1; } if (beep_buf == NULL) return -1; /* quick-hack fix for DACA, Burgundy & Tumbler */ if (awacs_revision >= AWACS_DACA){ srate = 44100 ; } else { for (i = 0; i < 8 && awacs_freqs[i] >= BEEP_SRATE; ++i) if (awacs_freqs_ok[i]) beep_speed = i; srate = awacs_freqs[beep_speed]; } if (hz <= srate / BEEP_BUFLEN || hz > srate / 2) { /* cancel beep currently playing */ awacs_nosound(0); return 0; } spin_lock_irqsave(&dmasound.lock, flags); if (beep_playing || write_sq.active || beep_buf == NULL) { spin_unlock_irqrestore(&dmasound.lock, flags); return -1; /* too hard, sorry :-( */ } beep_playing = 1; st_le16(&beep_dbdma_cmd->command, OUTPUT_MORE + BR_ALWAYS); spin_unlock_irqrestore(&dmasound.lock, flags); if (hz == beep_hz_cache && beep_vol == beep_volume_cache) { nsamples = beep_nsamples_cache; } else { period = srate * 256 / hz; /* fixed point */ ncycles = BEEP_BUFLEN * 256 / period; nsamples = (period * ncycles) >> 8; f = ncycles * 65536 / nsamples; j = 0; p = beep_buf; for (i = 0; i < nsamples; ++i, p += 2) { p[0] = p[1] = beep_wform[j >> 8] * beep_vol; j = (j + f) & 0xffff; } beep_hz_cache = hz; beep_volume_cache = beep_vol; beep_nsamples_cache = nsamples; } st_le16(&beep_dbdma_cmd->req_count, nsamples*4); st_le16(&beep_dbdma_cmd->xfer_status, 0); st_le32(&beep_dbdma_cmd->cmd_dep, virt_to_bus(beep_dbdma_cmd)); st_le32(&beep_dbdma_cmd->phy_addr, virt_to_bus(beep_buf)); awacs_beep_state = 1; spin_lock_irqsave(&dmasound.lock, flags); if (beep_playing) { /* i.e. haven't been terminated already */ int count = 300 ; out_le32(&awacs_txdma->control, (RUN|WAKE|FLUSH|PAUSE) << 16); while ((in_le32(&awacs_txdma->status) & RUN) && count--) udelay(1); /* timeout > 2 samples at lowest rate*/ if (awacs) awacs_setup_for_beep(beep_speed); out_le32(&awacs_txdma->cmdptr, virt_to_bus(beep_dbdma_cmd)); (void)in_le32(&awacs_txdma->status); out_le32(&awacs_txdma->control, RUN | (RUN << 16)); } spin_unlock_irqrestore(&dmasound.lock, flags); return 0; } /* used in init and for wake-up */ static void load_awacs(void) { awacs_write(awacs_reg[0] + MASK_ADDR0); awacs_write(awacs_reg[1] + MASK_ADDR1); awacs_write(awacs_reg[2] + MASK_ADDR2); awacs_write(awacs_reg[4] + MASK_ADDR4); if (awacs_revision == AWACS_SCREAMER) { awacs_write(awacs_reg[5] + MASK_ADDR5); msleep(100); awacs_write(awacs_reg[6] + MASK_ADDR6); msleep(2); awacs_write(awacs_reg[1] + MASK_ADDR1); awacs_write(awacs_reg[7] + MASK_ADDR7); } if (awacs) { if (hw_can_byteswap && (dmasound.hard.format == AFMT_S16_LE)) out_le32(&awacs->byteswap, BS_VAL); else out_le32(&awacs->byteswap, 0); } } #ifdef CONFIG_PM /* * Save state when going to sleep, restore it afterwards. */ /* FIXME: sort out disabling/re-enabling of read stuff as well */ static int awacs_sleep_notify(struct pmu_sleep_notifier *self, int when) { unsigned long flags; switch (when) { case PBOOK_SLEEP_NOW: LOCK(); awacs_sleeping = 1; /* Tell the rest of the driver we are now going to sleep */ mb(); if (awacs_revision == AWACS_SCREAMER || awacs_revision == AWACS_AWACS) { awacs_reg1_save = awacs_reg[1]; awacs_reg[1] |= MASK_AMUTE | MASK_CMUTE; awacs_write(MASK_ADDR1 | awacs_reg[1]); } PMacSilence(); /* stop rx - if going - a bit of a daft user... but */ out_le32(&awacs_rxdma->control, (RUN|WAKE|FLUSH << 16)); /* deny interrupts */ if (awacs) disable_irq(awacs_irq); disable_irq(awacs_tx_irq); disable_irq(awacs_rx_irq); /* Chip specific sleep code */ switch (awacs_revision) { case AWACS_TUMBLER: case AWACS_SNAPPER: write_audio_gpio(gpio_headphone_mute, gpio_headphone_mute_pol); write_audio_gpio(gpio_amp_mute, gpio_amp_mute_pol); tas_enter_sleep(); write_audio_gpio(gpio_audio_reset, gpio_audio_reset_pol); break ; case AWACS_DACA: daca_enter_sleep(); break ; case AWACS_BURGUNDY: break ; case AWACS_SCREAMER: case AWACS_AWACS: default: out_le32(&awacs->control, 0x11) ; break ; } /* Disable sound clock */ pmac_call_feature(PMAC_FTR_SOUND_CHIP_ENABLE, awacs_node, 0, 0); /* According to Darwin, we do that after turning off the sound * chip clock. All this will have to be cleaned up once we properly * parse the OF sound-objects */ if ((machine_is_compatible("PowerBook3,1") || machine_is_compatible("PowerBook3,2")) && awacs) { awacs_reg[1] |= MASK_PAROUT0 | MASK_PAROUT1; awacs_write(MASK_ADDR1 | awacs_reg[1]); msleep(200); } break; case PBOOK_WAKE: /* Enable sound clock */ pmac_call_feature(PMAC_FTR_SOUND_CHIP_ENABLE, awacs_node, 0, 1); if ((machine_is_compatible("PowerBook3,1") || machine_is_compatible("PowerBook3,2")) && awacs) { msleep(100); awacs_reg[1] &= ~(MASK_PAROUT0 | MASK_PAROUT1); awacs_write(MASK_ADDR1 | awacs_reg[1]); msleep(300); } else msleep(1000); /* restore settings */ switch (awacs_revision) { case AWACS_TUMBLER: case AWACS_SNAPPER: write_audio_gpio(gpio_headphone_mute, gpio_headphone_mute_pol); write_audio_gpio(gpio_amp_mute, gpio_amp_mute_pol); write_audio_gpio(gpio_audio_reset, gpio_audio_reset_pol); msleep(100); write_audio_gpio(gpio_audio_reset, !gpio_audio_reset_pol); msleep(150); tas_leave_sleep(); /* Stub for now */ headphone_intr(0,NULL,NULL); break; case AWACS_DACA: msleep(10); /* Check this !!! */ daca_leave_sleep(); break ; /* dont know how yet */ case AWACS_BURGUNDY: break ; case AWACS_SCREAMER: case AWACS_AWACS: default: load_awacs() ; break ; } /* Recalibrate chip */ if (awacs_revision == AWACS_SCREAMER && awacs) awacs_recalibrate(); /* Make sure dma is stopped */ PMacSilence(); if (awacs) enable_irq(awacs_irq); enable_irq(awacs_tx_irq); enable_irq(awacs_rx_irq); if (awacs) { /* OK, allow ints back again */ out_le32(&awacs->control, MASK_IEPC | (awacs_rate_index << 8) | 0x11 | (awacs_revision < AWACS_DACA ? MASK_IEE: 0)); } if (macio_base && is_pbook_g3) { /* FIXME: should restore the setup we had...*/ out_8(macio_base + 0x37, 3); } else if (is_pbook_3X00) { in_8(latch_base + 0x190); } /* Remove mute */ if (awacs_revision == AWACS_SCREAMER || awacs_revision == AWACS_AWACS) { awacs_reg[1] = awacs_reg1_save; awacs_write(MASK_ADDR1 | awacs_reg[1]); } awacs_sleeping = 0; /* Resume pending sounds. */ /* we don't try to restart input... */ spin_lock_irqsave(&dmasound.lock, flags); __PMacPlay(); spin_unlock_irqrestore(&dmasound.lock, flags); UNLOCK(); } return PBOOK_SLEEP_OK; } #endif /* CONFIG_PM */ /* All the burgundy functions: */ /* Waits for busy flag to clear */ static inline void awacs_burgundy_busy_wait(void) { int count = 50; /* > 2 samples at 44k1 */ while ((in_le32(&awacs->codec_ctrl) & MASK_NEWECMD) && count--) udelay(1) ; } static inline void awacs_burgundy_extend_wait(void) { int count = 50 ; /* > 2 samples at 44k1 */ while ((!(in_le32(&awacs->codec_stat) & MASK_EXTEND)) && count--) udelay(1) ; count = 50; while ((in_le32(&awacs->codec_stat) & MASK_EXTEND) && count--) udelay(1); } static void awacs_burgundy_wcw(unsigned addr, unsigned val) { out_le32(&awacs->codec_ctrl, addr + 0x200c00 + (val & 0xff)); awacs_burgundy_busy_wait(); out_le32(&awacs->codec_ctrl, addr + 0x200d00 +((val>>8) & 0xff)); awacs_burgundy_busy_wait(); out_le32(&awacs->codec_ctrl, addr + 0x200e00 +((val>>16) & 0xff)); awacs_burgundy_busy_wait(); out_le32(&awacs->codec_ctrl, addr + 0x200f00 +((val>>24) & 0xff)); awacs_burgundy_busy_wait(); } static unsigned awacs_burgundy_rcw(unsigned addr) { unsigned val = 0; unsigned long flags; /* should have timeouts here */ spin_lock_irqsave(&dmasound.lock, flags); out_le32(&awacs->codec_ctrl, addr + 0x100000); awacs_burgundy_busy_wait(); awacs_burgundy_extend_wait(); val += (in_le32(&awacs->codec_stat) >> 4) & 0xff; out_le32(&awacs->codec_ctrl, addr + 0x100100); awacs_burgundy_busy_wait(); awacs_burgundy_extend_wait(); val += ((in_le32(&awacs->codec_stat)>>4) & 0xff) <<8; out_le32(&awacs->codec_ctrl, addr + 0x100200); awacs_burgundy_busy_wait(); awacs_burgundy_extend_wait(); val += ((in_le32(&awacs->codec_stat)>>4) & 0xff) <<16; out_le32(&awacs->codec_ctrl, addr + 0x100300); awacs_burgundy_busy_wait(); awacs_burgundy_extend_wait(); val += ((in_le32(&awacs->codec_stat)>>4) & 0xff) <<24; spin_unlock_irqrestore(&dmasound.lock, flags); return val; } static void awacs_burgundy_wcb(unsigned addr, unsigned val) { out_le32(&awacs->codec_ctrl, addr + 0x300000 + (val & 0xff)); awacs_burgundy_busy_wait(); } static unsigned awacs_burgundy_rcb(unsigned addr) { unsigned val = 0; unsigned long flags; /* should have timeouts here */ spin_lock_irqsave(&dmasound.lock, flags); out_le32(&awacs->codec_ctrl, addr + 0x100000); awacs_burgundy_busy_wait(); awacs_burgundy_extend_wait(); val += (in_le32(&awacs->codec_stat) >> 4) & 0xff; spin_unlock_irqrestore(&dmasound.lock, flags); return val; } static int awacs_burgundy_check(void) { /* Checks to see the chip is alive and kicking */ int error = in_le32(&awacs->codec_ctrl) & MASK_ERRCODE; return error == 0xf0000; } static int awacs_burgundy_init(void) { if (awacs_burgundy_check()) { printk(KERN_WARNING "dmasound_pmac: burgundy not working :-(\n"); return 1; } awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_OUTPUTENABLES, DEF_BURGUNDY_OUTPUTENABLES); awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_MORE_OUTPUTENABLES, DEF_BURGUNDY_MORE_OUTPUTENABLES); awacs_burgundy_wcw(MASK_ADDR_BURGUNDY_OUTPUTSELECTS, DEF_BURGUNDY_OUTPUTSELECTS); awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_INPSEL21, DEF_BURGUNDY_INPSEL21); awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_INPSEL3, DEF_BURGUNDY_INPSEL3); awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_GAINCD, DEF_BURGUNDY_GAINCD); awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_GAINLINE, DEF_BURGUNDY_GAINLINE); awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_GAINMIC, DEF_BURGUNDY_GAINMIC); awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_GAINMODEM, DEF_BURGUNDY_GAINMODEM); awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_ATTENSPEAKER, DEF_BURGUNDY_ATTENSPEAKER); awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_ATTENLINEOUT, DEF_BURGUNDY_ATTENLINEOUT); awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_ATTENHP, DEF_BURGUNDY_ATTENHP); awacs_burgundy_wcw(MASK_ADDR_BURGUNDY_MASTER_VOLUME, DEF_BURGUNDY_MASTER_VOLUME); awacs_burgundy_wcw(MASK_ADDR_BURGUNDY_VOLCD, DEF_BURGUNDY_VOLCD); awacs_burgundy_wcw(MASK_ADDR_BURGUNDY_VOLLINE, DEF_BURGUNDY_VOLLINE); awacs_burgundy_wcw(MASK_ADDR_BURGUNDY_VOLMIC, DEF_BURGUNDY_VOLMIC); return 0; } static void awacs_burgundy_write_volume(unsigned address, int volume) { int hardvolume,lvolume,rvolume; lvolume = (volume & 0xff) ? (volume & 0xff) + 155 : 0; rvolume = ((volume >>8)&0xff) ? ((volume >> 8)&0xff ) + 155 : 0; hardvolume = lvolume + (rvolume << 16); awacs_burgundy_wcw(address, hardvolume); } static int awacs_burgundy_read_volume(unsigned address) { int softvolume,wvolume; wvolume = awacs_burgundy_rcw(address); softvolume = (wvolume & 0xff) - 155; softvolume += (((wvolume >> 16) & 0xff) - 155)<<8; return softvolume > 0 ? softvolume : 0; } static int awacs_burgundy_read_mvolume(unsigned address) { int lvolume,rvolume,wvolume; wvolume = awacs_burgundy_rcw(address); wvolume &= 0xffff; rvolume = (wvolume & 0xff) - 155; lvolume = ((wvolume & 0xff00)>>8) - 155; return lvolume + (rvolume << 8); } static void awacs_burgundy_write_mvolume(unsigned address, int volume) { int lvolume,rvolume,hardvolume; lvolume = (volume &0xff) ? (volume & 0xff) + 155 :0; rvolume = ((volume >>8) & 0xff) ? (volume >> 8) + 155 :0; hardvolume = lvolume + (rvolume << 8); hardvolume += (hardvolume << 16); awacs_burgundy_wcw(address, hardvolume); } /* End burgundy functions */ /* Set up output volumes on machines with the 'perch/whisper' extension card. * this has an SGS i2c chip (7433) which is accessed using the cuda. * * TODO: split this out and make use of the other parts of the SGS chip to * do Bass, Treble etc. */ static void awacs_enable_amp(int spkr_vol) { #ifdef CONFIG_ADB_CUDA struct adb_request req; if (sys_ctrler != SYS_CTRLER_CUDA) return; /* turn on headphones */ cuda_request(&req, NULL, 5, CUDA_PACKET, CUDA_GET_SET_IIC, 0x8a, 4, 0); while (!req.complete) cuda_poll(); cuda_request(&req, NULL, 5, CUDA_PACKET, CUDA_GET_SET_IIC, 0x8a, 6, 0); while (!req.complete) cuda_poll(); /* turn on speaker */ cuda_request(&req, NULL, 5, CUDA_PACKET, CUDA_GET_SET_IIC, 0x8a, 3, (100 - (spkr_vol & 0xff)) * 32 / 100); while (!req.complete) cuda_poll(); cuda_request(&req, NULL, 5, CUDA_PACKET, CUDA_GET_SET_IIC, 0x8a, 5, (100 - ((spkr_vol >> 8) & 0xff)) * 32 / 100); while (!req.complete) cuda_poll(); cuda_request(&req, NULL, 5, CUDA_PACKET, CUDA_GET_SET_IIC, 0x8a, 1, 0x29); while (!req.complete) cuda_poll(); #endif /* CONFIG_ADB_CUDA */ } /*** Mid level stuff *********************************************************/ /* * /dev/mixer abstraction */ static void do_line_lev(int data) { line_lev = data ; awacs_reg[0] &= ~MASK_MUX_AUDIN; if ((data & 0xff) >= 50) awacs_reg[0] |= MASK_MUX_AUDIN; awacs_write(MASK_ADDR0 | awacs_reg[0]); } static void do_ip_gain(int data) { ip_gain = data ; data &= 0xff; awacs_reg[0] &= ~MASK_GAINLINE; if (awacs_revision == AWACS_SCREAMER) { awacs_reg[6] &= ~MASK_MIC_BOOST ; if (data >= 33) { awacs_reg[0] |= MASK_GAINLINE; if( data >= 66) awacs_reg[6] |= MASK_MIC_BOOST ; } awacs_write(MASK_ADDR6 | awacs_reg[6]) ; } else { if (data >= 50) awacs_reg[0] |= MASK_GAINLINE; } awacs_write(MASK_ADDR0 | awacs_reg[0]); } static void do_mic_lev(int data) { mic_lev = data ; data &= 0xff; awacs_reg[0] &= ~MASK_MUX_MIC; if (data >= 50) awacs_reg[0] |= MASK_MUX_MIC; awacs_write(MASK_ADDR0 | awacs_reg[0]); } static void do_cd_lev(int data) { cd_lev = data ; awacs_reg[0] &= ~MASK_MUX_CD; if ((data & 0xff) >= 50) awacs_reg[0] |= MASK_MUX_CD; awacs_write(MASK_ADDR0 | awacs_reg[0]); } static void do_rec_lev(int data) { int left, right ; rec_lev = data ; /* need to fudge this to use the volume setter routine */ left = 100 - (data & 0xff) ; if( left < 0 ) left = 0 ; right = 100 - ((data >> 8) & 0xff) ; if( right < 0 ) right = 0 ; left |= (right << 8 ); left = awacs_volume_setter(left, 0, 0, 4); } static void do_passthru_vol(int data) { passthru_vol = data ; awacs_reg[1] &= ~MASK_LOOPTHRU; if (awacs_revision == AWACS_SCREAMER) { if( data ) { /* switch it on for non-zero */ awacs_reg[1] |= MASK_LOOPTHRU; awacs_write(MASK_ADDR1 | awacs_reg[1]); } data = awacs_volume_setter(data, 5, 0, 6) ; } else { if ((data & 0xff) >= 50) awacs_reg[1] |= MASK_LOOPTHRU; awacs_write(MASK_ADDR1 | awacs_reg[1]); data = (awacs_reg[1] & MASK_LOOPTHRU)? 100: 0; } } static int awacs_mixer_ioctl(u_int cmd, u_long arg) { int data; int rc; switch (cmd) { case SOUND_MIXER_READ_CAPS: /* say we will allow multiple inputs? prob. wrong so I'm switching it to single */ return IOCTL_OUT(arg, 1); case SOUND_MIXER_READ_DEVMASK: data = SOUND_MASK_VOLUME | SOUND_MASK_SPEAKER | SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_CD | SOUND_MASK_IGAIN | SOUND_MASK_RECLEV | SOUND_MASK_ALTPCM | SOUND_MASK_MONITOR; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_RECMASK: data = SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_CD; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_RECSRC: data = 0; if (awacs_reg[0] & MASK_MUX_AUDIN) data |= SOUND_MASK_LINE; if (awacs_reg[0] & MASK_MUX_MIC) data |= SOUND_MASK_MIC; if (awacs_reg[0] & MASK_MUX_CD) data |= SOUND_MASK_CD; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_WRITE_RECSRC: IOCTL_IN(arg, data); data &= (SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_CD); awacs_reg[0] &= ~(MASK_MUX_CD | MASK_MUX_MIC | MASK_MUX_AUDIN); if (data & SOUND_MASK_LINE) awacs_reg[0] |= MASK_MUX_AUDIN; if (data & SOUND_MASK_MIC) awacs_reg[0] |= MASK_MUX_MIC; if (data & SOUND_MASK_CD) awacs_reg[0] |= MASK_MUX_CD; awacs_write(awacs_reg[0] | MASK_ADDR0); rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_STEREODEVS: data = SOUND_MASK_VOLUME | SOUND_MASK_SPEAKER| SOUND_MASK_RECLEV ; if (awacs_revision == AWACS_SCREAMER) data |= SOUND_MASK_MONITOR ; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_WRITE_VOLUME: IOCTL_IN(arg, data); line_vol = data ; awacs_volume_setter(data, 2, 0, 6); /* fall through */ case SOUND_MIXER_READ_VOLUME: rc = IOCTL_OUT(arg, line_vol); break; case SOUND_MIXER_WRITE_SPEAKER: IOCTL_IN(arg, data); spk_vol = data ; if (has_perch) awacs_enable_amp(data); else (void)awacs_volume_setter(data, 4, MASK_CMUTE, 6); /* fall though */ case SOUND_MIXER_READ_SPEAKER: rc = IOCTL_OUT(arg, spk_vol); break; case SOUND_MIXER_WRITE_ALTPCM: /* really bell volume */ IOCTL_IN(arg, data); beep_vol = data & 0xff; /* fall through */ case SOUND_MIXER_READ_ALTPCM: rc = IOCTL_OUT(arg, beep_vol); break; case SOUND_MIXER_WRITE_LINE: IOCTL_IN(arg, data); do_line_lev(data) ; /* fall through */ case SOUND_MIXER_READ_LINE: rc = IOCTL_OUT(arg, line_lev); break; case SOUND_MIXER_WRITE_IGAIN: IOCTL_IN(arg, data); do_ip_gain(data) ; /* fall through */ case SOUND_MIXER_READ_IGAIN: rc = IOCTL_OUT(arg, ip_gain); break; case SOUND_MIXER_WRITE_MIC: IOCTL_IN(arg, data); do_mic_lev(data); /* fall through */ case SOUND_MIXER_READ_MIC: rc = IOCTL_OUT(arg, mic_lev); break; case SOUND_MIXER_WRITE_CD: IOCTL_IN(arg, data); do_cd_lev(data); /* fall through */ case SOUND_MIXER_READ_CD: rc = IOCTL_OUT(arg, cd_lev); break; case SOUND_MIXER_WRITE_RECLEV: IOCTL_IN(arg, data); do_rec_lev(data) ; /* fall through */ case SOUND_MIXER_READ_RECLEV: rc = IOCTL_OUT(arg, rec_lev); break; case MIXER_WRITE(SOUND_MIXER_MONITOR): IOCTL_IN(arg, data); do_passthru_vol(data) ; /* fall through */ case MIXER_READ(SOUND_MIXER_MONITOR): rc = IOCTL_OUT(arg, passthru_vol); break; default: rc = -EINVAL; } return rc; } static void awacs_mixer_init(void) { awacs_volume_setter(line_vol, 2, 0, 6); if (has_perch) awacs_enable_amp(spk_vol); else (void)awacs_volume_setter(spk_vol, 4, MASK_CMUTE, 6); do_line_lev(line_lev) ; do_ip_gain(ip_gain) ; do_mic_lev(mic_lev) ; do_cd_lev(cd_lev) ; do_rec_lev(rec_lev) ; do_passthru_vol(passthru_vol) ; } static int burgundy_mixer_ioctl(u_int cmd, u_long arg) { int data; int rc; /* We are, we are, we are... Burgundy or better */ switch(cmd) { case SOUND_MIXER_READ_DEVMASK: data = SOUND_MASK_VOLUME | SOUND_MASK_CD | SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_SPEAKER | SOUND_MASK_ALTPCM; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_RECMASK: data = SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_CD; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_RECSRC: data = 0; if (awacs_reg[0] & MASK_MUX_AUDIN) data |= SOUND_MASK_LINE; if (awacs_reg[0] & MASK_MUX_MIC) data |= SOUND_MASK_MIC; if (awacs_reg[0] & MASK_MUX_CD) data |= SOUND_MASK_CD; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_WRITE_RECSRC: IOCTL_IN(arg, data); data &= (SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_CD); awacs_reg[0] &= ~(MASK_MUX_CD | MASK_MUX_MIC | MASK_MUX_AUDIN); if (data & SOUND_MASK_LINE) awacs_reg[0] |= MASK_MUX_AUDIN; if (data & SOUND_MASK_MIC) awacs_reg[0] |= MASK_MUX_MIC; if (data & SOUND_MASK_CD) awacs_reg[0] |= MASK_MUX_CD; awacs_write(awacs_reg[0] | MASK_ADDR0); rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_STEREODEVS: data = SOUND_MASK_VOLUME | SOUND_MASK_SPEAKER | SOUND_MASK_RECLEV | SOUND_MASK_CD | SOUND_MASK_LINE; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_CAPS: rc = IOCTL_OUT(arg, 0); break; case SOUND_MIXER_WRITE_VOLUME: IOCTL_IN(arg, data); awacs_burgundy_write_mvolume(MASK_ADDR_BURGUNDY_MASTER_VOLUME, data); /* Fall through */ case SOUND_MIXER_READ_VOLUME: rc = IOCTL_OUT(arg, awacs_burgundy_read_mvolume(MASK_ADDR_BURGUNDY_MASTER_VOLUME)); break; case SOUND_MIXER_WRITE_SPEAKER: IOCTL_IN(arg, data); if (!(data & 0xff)) { /* Mute the left speaker */ awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_MORE_OUTPUTENABLES, awacs_burgundy_rcb(MASK_ADDR_BURGUNDY_MORE_OUTPUTENABLES) & ~0x2); } else { /* Unmute the left speaker */ awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_MORE_OUTPUTENABLES, awacs_burgundy_rcb(MASK_ADDR_BURGUNDY_MORE_OUTPUTENABLES) | 0x2); } if (!(data & 0xff00)) { /* Mute the right speaker */ awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_MORE_OUTPUTENABLES, awacs_burgundy_rcb(MASK_ADDR_BURGUNDY_MORE_OUTPUTENABLES) & ~0x4); } else { /* Unmute the right speaker */ awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_MORE_OUTPUTENABLES, awacs_burgundy_rcb(MASK_ADDR_BURGUNDY_MORE_OUTPUTENABLES) | 0x4); } data = (((data&0xff)*16)/100 > 0xf ? 0xf : (((data&0xff)*16)/100)) + ((((data>>8)*16)/100 > 0xf ? 0xf : ((((data>>8)*16)/100)))<<4); awacs_burgundy_wcb(MASK_ADDR_BURGUNDY_ATTENSPEAKER, ~data); /* Fall through */ case SOUND_MIXER_READ_SPEAKER: data = awacs_burgundy_rcb(MASK_ADDR_BURGUNDY_ATTENSPEAKER); data = (((data & 0xf)*100)/16) + ((((data>>4)*100)/16)<<8); rc = IOCTL_OUT(arg, (~data) & 0x0000ffff); break; case SOUND_MIXER_WRITE_ALTPCM: /* really bell volume */ IOCTL_IN(arg, data); beep_vol = data & 0xff; /* fall through */ case SOUND_MIXER_READ_ALTPCM: rc = IOCTL_OUT(arg, beep_vol); break; case SOUND_MIXER_WRITE_LINE: IOCTL_IN(arg, data); awacs_burgundy_write_volume(MASK_ADDR_BURGUNDY_VOLLINE, data); /* fall through */ case SOUND_MIXER_READ_LINE: data = awacs_burgundy_read_volume(MASK_ADDR_BURGUNDY_VOLLINE); rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_WRITE_MIC: IOCTL_IN(arg, data); /* Mic is mono device */ data = (data << 8) + (data << 24); awacs_burgundy_write_volume(MASK_ADDR_BURGUNDY_VOLMIC, data); /* fall through */ case SOUND_MIXER_READ_MIC: data = awacs_burgundy_read_volume(MASK_ADDR_BURGUNDY_VOLMIC); data <<= 24; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_WRITE_CD: IOCTL_IN(arg, data); awacs_burgundy_write_volume(MASK_ADDR_BURGUNDY_VOLCD, data); /* fall through */ case SOUND_MIXER_READ_CD: data = awacs_burgundy_read_volume(MASK_ADDR_BURGUNDY_VOLCD); rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_WRITE_RECLEV: IOCTL_IN(arg, data); data = awacs_volume_setter(data, 0, 0, 4); rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_RECLEV: data = awacs_get_volume(awacs_reg[0], 4); rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_OUTMASK: case SOUND_MIXER_OUTSRC: default: rc = -EINVAL; } return rc; } static int daca_mixer_ioctl(u_int cmd, u_long arg) { int data; int rc; /* And the DACA's no genius either! */ switch(cmd) { case SOUND_MIXER_READ_DEVMASK: data = SOUND_MASK_VOLUME; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_RECMASK: data = 0; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_RECSRC: data = 0; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_WRITE_RECSRC: IOCTL_IN(arg, data); data =0; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_STEREODEVS: data = SOUND_MASK_VOLUME; rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_READ_CAPS: rc = IOCTL_OUT(arg, 0); break; case SOUND_MIXER_WRITE_VOLUME: IOCTL_IN(arg, data); daca_set_volume(data, data); /* Fall through */ case SOUND_MIXER_READ_VOLUME: daca_get_volume(& data, &data); rc = IOCTL_OUT(arg, data); break; case SOUND_MIXER_OUTMASK: case SOUND_MIXER_OUTSRC: default: rc = -EINVAL; } return rc; } static int PMacMixerIoctl(u_int cmd, u_long arg) { int rc; /* Different IOCTLS for burgundy and, eventually, DACA & Tumbler */ TRY_LOCK(); switch (awacs_revision){ case AWACS_BURGUNDY: rc = burgundy_mixer_ioctl(cmd, arg); break ; case AWACS_DACA: rc = daca_mixer_ioctl(cmd, arg); break; case AWACS_TUMBLER: case AWACS_SNAPPER: rc = tas_mixer_ioctl(cmd, arg); break ; default: /* ;-)) */ rc = awacs_mixer_ioctl(cmd, arg); } UNLOCK(); return rc; } static void PMacMixerInit(void) { switch (awacs_revision) { case AWACS_TUMBLER: printk("AE-Init tumbler mixer\n"); break ; case AWACS_SNAPPER: printk("AE-Init snapper mixer\n"); break ; case AWACS_DACA: case AWACS_BURGUNDY: break ; /* don't know yet */ case AWACS_AWACS: case AWACS_SCREAMER: default: awacs_mixer_init() ; break ; } } /* Write/Read sq setup functions: Check to see if we have enough (or any) dbdma cmd buffers for the user's fragment settings. If not, allocate some. If this fails we will point at the beep buffer - as an emergency provision - to stop dma tromping on some random bit of memory (if someone lets it go anyway). The command buffers are then set up to point to the fragment buffers (allocated elsewhere). We need n+1 commands the last of which holds a NOP + loop to start. */ static int PMacWriteSqSetup(void) { int i, count = 600 ; volatile struct dbdma_cmd *cp; LOCK(); /* stop the controller from doing any output - if it isn't already. it _should_ be before this is called anyway */ out_le32(&awacs_txdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16); while ((in_le32(&awacs_txdma->status) & RUN) && count--) udelay(1); #ifdef DEBUG_DMASOUND if (count <= 0) printk("dmasound_pmac: write sq setup: timeout waiting for dma to stop\n"); #endif if ((write_sq.max_count + 1) > number_of_tx_cmd_buffers) { kfree(awacs_tx_cmd_space); number_of_tx_cmd_buffers = 0; /* we need nbufs + 1 (for the loop) and we should request + 1 again because the DBDMA_ALIGN might pull the start up by up to sizeof(struct dbdma_cmd) - 4. */ awacs_tx_cmd_space = kmalloc ((write_sq.max_count + 1 + 1) * sizeof(struct dbdma_cmd), GFP_KERNEL); if (awacs_tx_cmd_space == NULL) { /* don't leave it dangling - nasty but better than a random address */ out_le32(&awacs_txdma->cmdptr, virt_to_bus(beep_dbdma_cmd)); printk(KERN_ERR "dmasound_pmac: can't allocate dbdma cmd buffers" ", driver disabled\n"); UNLOCK(); return -ENOMEM; } awacs_tx_cmds = (volatile struct dbdma_cmd *) DBDMA_ALIGN(awacs_tx_cmd_space); number_of_tx_cmd_buffers = write_sq.max_count + 1; } cp = awacs_tx_cmds; memset((void *)cp, 0, (write_sq.max_count+1) * sizeof(struct dbdma_cmd)); for (i = 0; i < write_sq.max_count; ++i, ++cp) { st_le32(&cp->phy_addr, virt_to_bus(write_sq.buffers[i])); } st_le16(&cp->command, DBDMA_NOP + BR_ALWAYS); st_le32(&cp->cmd_dep, virt_to_bus(awacs_tx_cmds)); /* point the controller at the command stack - ready to go */ out_le32(&awacs_txdma->cmdptr, virt_to_bus(awacs_tx_cmds)); UNLOCK(); return 0; } static int PMacReadSqSetup(void) { int i, count = 600; volatile struct dbdma_cmd *cp; LOCK(); /* stop the controller from doing any input - if it isn't already. it _should_ be before this is called anyway */ out_le32(&awacs_rxdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16); while ((in_le32(&awacs_rxdma->status) & RUN) && count--) udelay(1); #ifdef DEBUG_DMASOUND if (count <= 0) printk("dmasound_pmac: read sq setup: timeout waiting for dma to stop\n"); #endif if ((read_sq.max_count+1) > number_of_rx_cmd_buffers ) { kfree(awacs_rx_cmd_space); number_of_rx_cmd_buffers = 0; /* we need nbufs + 1 (for the loop) and we should request + 1 again because the DBDMA_ALIGN might pull the start up by up to sizeof(struct dbdma_cmd) - 4 (assuming kmalloc aligns 32 bits). */ awacs_rx_cmd_space = kmalloc ((read_sq.max_count + 1 + 1) * sizeof(struct dbdma_cmd), GFP_KERNEL); if (awacs_rx_cmd_space == NULL) { /* don't leave it dangling - nasty but better than a random address */ out_le32(&awacs_rxdma->cmdptr, virt_to_bus(beep_dbdma_cmd)); printk(KERN_ERR "dmasound_pmac: can't allocate dbdma cmd buffers" ", driver disabled\n"); UNLOCK(); return -ENOMEM; } awacs_rx_cmds = (volatile struct dbdma_cmd *) DBDMA_ALIGN(awacs_rx_cmd_space); number_of_rx_cmd_buffers = read_sq.max_count + 1 ; } cp = awacs_rx_cmds; memset((void *)cp, 0, (read_sq.max_count+1) * sizeof(struct dbdma_cmd)); /* Set dma buffers up in a loop */ for (i = 0; i < read_sq.max_count; i++,cp++) { st_le32(&cp->phy_addr, virt_to_bus(read_sq.buffers[i])); st_le16(&cp->command, INPUT_MORE + INTR_ALWAYS); st_le16(&cp->req_count, read_sq.block_size); st_le16(&cp->xfer_status, 0); } /* The next two lines make the thing loop around. */ st_le16(&cp->command, DBDMA_NOP + BR_ALWAYS); st_le32(&cp->cmd_dep, virt_to_bus(awacs_rx_cmds)); /* point the controller at the command stack - ready to go */ out_le32(&awacs_rxdma->cmdptr, virt_to_bus(awacs_rx_cmds)); UNLOCK(); return 0; } /* TODO: this needs work to guarantee that when it returns DMA has stopped but in a more elegant way than is done here.... */ static void PMacAbortRead(void) { int i; volatile struct dbdma_cmd *cp; LOCK(); /* give it a chance to update the output and provide the IRQ that is expected. */ out_le32(&awacs_rxdma->control, ((FLUSH) << 16) + FLUSH ); cp = awacs_rx_cmds; for (i = 0; i < read_sq.max_count; i++,cp++) st_le16(&cp->command, DBDMA_STOP); /* * We should probably wait for the thing to stop before we * release the memory. */ msleep(100) ; /* give it a (small) chance to act */ /* apply the sledgehammer approach - just stop it now */ out_le32(&awacs_rxdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16); UNLOCK(); } extern char *get_afmt_string(int); static int PMacStateInfo(char *b, size_t sp) { int i, len = 0; len = sprintf(b,"HW rates: "); switch (awacs_revision){ case AWACS_DACA: case AWACS_BURGUNDY: len += sprintf(b,"44100 ") ; break ; case AWACS_TUMBLER: case AWACS_SNAPPER: for (i=0; i<1; i++){ if (tas_freqs_ok[i]) len += sprintf(b+len,"%d ", tas_freqs[i]) ; } break ; case AWACS_AWACS: case AWACS_SCREAMER: default: for (i=0; i<8; i++){ if (awacs_freqs_ok[i]) len += sprintf(b+len,"%d ", awacs_freqs[i]) ; } break ; } len += sprintf(b+len,"s/sec\n") ; if (len < sp) { len += sprintf(b+len,"HW AFMTS: "); i = AFMT_U16_BE ; while (i) { if (i & dmasound.mach.hardware_afmts) len += sprintf(b+len,"%s ", get_afmt_string(i & dmasound.mach.hardware_afmts)); i >>= 1 ; } len += sprintf(b+len,"\n") ; } return len ; } /*** Machine definitions *****************************************************/ static SETTINGS def_hard = { .format = AFMT_S16_BE, .stereo = 1, .size = 16, .speed = 44100 } ; static SETTINGS def_soft = { .format = AFMT_S16_BE, .stereo = 1, .size = 16, .speed = 44100 } ; static MACHINE machPMac = { .name = awacs_name, .name2 = "PowerMac Built-in Sound", .owner = THIS_MODULE, .dma_alloc = PMacAlloc, .dma_free = PMacFree, .irqinit = PMacIrqInit, #ifdef MODULE .irqcleanup = PMacIrqCleanup, #endif /* MODULE */ .init = PMacInit, .silence = PMacSilence, .setFormat = PMacSetFormat, .setVolume = PMacSetVolume, .play = PMacPlay, .record = NULL, /* default to no record */ .mixer_init = PMacMixerInit, .mixer_ioctl = PMacMixerIoctl, .write_sq_setup = PMacWriteSqSetup, .read_sq_setup = PMacReadSqSetup, .state_info = PMacStateInfo, .abort_read = PMacAbortRead, .min_dsp_speed = 7350, .max_dsp_speed = 44100, .version = ((DMASOUND_AWACS_REVISION<<8) + DMASOUND_AWACS_EDITION) }; /*** Config & Setup **********************************************************/ /* Check for pmac models that we care about in terms of special actions. */ void __init set_model(void) { /* portables/lap-tops */ if (machine_is_compatible("AAPL,3400/2400") || machine_is_compatible("AAPL,3500")) { is_pbook_3X00 = 1 ; } if (machine_is_compatible("PowerBook1,1") || /* lombard */ machine_is_compatible("AAPL,PowerBook1998")){ /* wallstreet */ is_pbook_g3 = 1 ; return ; } } /* Get the OF node that tells us about the registers, interrupts etc. to use for sound IO. On most machines the sound IO OF node is the 'davbus' node. On newer pmacs with DACA (& Tumbler) the node to use is i2s-a. On much older machines i.e. before 9500 there is no davbus node and we have to use the 'awacs' property. In the latter case we signal this by setting the codec value - so that the code that looks for chip properties knows how to go about it. */ static struct device_node* __init get_snd_io_node(void) { struct device_node *np = NULL; /* set up awacs_node for early OF which doesn't have a full set of * properties on davbus */ awacs_node = find_devices("awacs"); if (awacs_node) awacs_revision = AWACS_AWACS; /* powermac models after 9500 (other than those which use DACA or * Tumbler) have a node called "davbus". */ np = find_devices("davbus"); /* * if we didn't find a davbus device, try 'i2s-a' since * this seems to be what iBooks (& Tumbler) have. */ if (np == NULL) np = i2s_node = find_devices("i2s-a"); /* if we didn't find this - perhaps we are on an early model * which _only_ has an 'awacs' node */ if (np == NULL && awacs_node) np = awacs_node ; /* if we failed all these return null - this will cause the * driver to give up... */ return np ; } /* Get the OF node that contains the info about the sound chip, inputs s-rates etc. This node does not exist (or contains much reduced info) on earlier machines we have to deduce the info other ways for these. */ static struct device_node* __init get_snd_info_node(struct device_node *io) { struct device_node *info; info = find_devices("sound"); while (info && info->parent != io) info = info->next; return info; } /* Find out what type of codec we have. */ static int __init get_codec_type(struct device_node *info) { /* already set if pre-davbus model and info will be NULL */ int codec = awacs_revision ; if (info) { /* must do awacs first to allow screamer to overide it */ if (device_is_compatible(info, "awacs")) codec = AWACS_AWACS ; if (device_is_compatible(info, "screamer")) codec = AWACS_SCREAMER; if (device_is_compatible(info, "burgundy")) codec = AWACS_BURGUNDY ; if (device_is_compatible(info, "daca")) codec = AWACS_DACA; if (device_is_compatible(info, "tumbler")) codec = AWACS_TUMBLER; if (device_is_compatible(info, "snapper")) codec = AWACS_SNAPPER; } return codec ; } /* find out what type, if any, of expansion card we have */ static void __init get_expansion_type(void) { if (find_devices("perch") != NULL) has_perch = 1; if (find_devices("pb-ziva-pc") != NULL) has_ziva = 1; /* need to work out how we deal with iMac SRS module */ } /* set up frame rates. * I suspect that these routines don't quite go about it the right way: * - where there is more than one rate - I think that the first property * value is the number of rates. * TODO: check some more device trees and modify accordingly * Set dmasound.mach.max_dsp_rate on the basis of these routines. */ static void __init awacs_init_frame_rates(unsigned int *prop, unsigned int l) { int i ; if (prop) { for (i=0; i<8; i++) awacs_freqs_ok[i] = 0 ; for (l /= sizeof(int); l > 0; --l) { unsigned int r = *prop++; /* Apple 'Fixed' format */ if (r >= 0x10000) r >>= 16; for (i = 0; i < 8; ++i) { if (r == awacs_freqs[i]) { awacs_freqs_ok[i] = 1; break; } } } } /* else we assume that all the rates are available */ } static void __init burgundy_init_frame_rates(unsigned int *prop, unsigned int l) { int temp[9] ; int i = 0 ; if (prop) { for (l /= sizeof(int); l > 0; --l) { unsigned int r = *prop++; /* Apple 'Fixed' format */ if (r >= 0x10000) r >>= 16; temp[i] = r ; i++ ; if(i>=9) i=8; } } #ifdef DEBUG_DMASOUND if (i > 1){ int j; printk("dmasound_pmac: burgundy with multiple frame rates\n"); for(j=0; j<i; j++) printk("%d ", temp[j]) ; printk("\n") ; } #endif } static void __init daca_init_frame_rates(unsigned int *prop, unsigned int l) { int temp[9] ; int i = 0 ; if (prop) { for (l /= sizeof(int); l > 0; --l) { unsigned int r = *prop++; /* Apple 'Fixed' format */ if (r >= 0x10000) r >>= 16; temp[i] = r ; i++ ; if(i>=9) i=8; } } #ifdef DEBUG_DMASOUND if (i > 1){ int j; printk("dmasound_pmac: DACA with multiple frame rates\n"); for(j=0; j<i; j++) printk("%d ", temp[j]) ; printk("\n") ; } #endif } static void __init init_frame_rates(unsigned int *prop, unsigned int l) { switch (awacs_revision) { case AWACS_TUMBLER: case AWACS_SNAPPER: tas_init_frame_rates(prop, l); break ; case AWACS_DACA: daca_init_frame_rates(prop, l); break ; case AWACS_BURGUNDY: burgundy_init_frame_rates(prop, l); break ; default: awacs_init_frame_rates(prop, l); break ; } } /* find things/machines that can't do mac-io byteswap */ static void __init set_hw_byteswap(struct device_node *io) { struct device_node *mio ; unsigned int kl = 0 ; /* if seems that Keylargo can't byte-swap */ for (mio = io->parent; mio ; mio = mio->parent) { if (strcmp(mio->name, "mac-io") == 0) { if (device_is_compatible(mio, "Keylargo")) kl = 1; break; } } hw_can_byteswap = !kl; } /* Allocate the resources necessary for beep generation. This cannot be (quite) done statically (yet) because we cannot do virt_to_bus() on static vars when the code is loaded as a module. for the sake of saving the possibility that two allocations will incur the overhead of two pull-ups in DBDMA_ALIGN() we allocate the 'emergency' dmdma command here as well... even tho' it is not part of the beep process. */ int32_t __init setup_beep(void) { /* Initialize beep stuff */ /* want one cmd buffer for beeps, and a second one for emergencies - i.e. dbdma error conditions. ask for three to allow for pull up in DBDMA_ALIGN(). */ beep_dbdma_cmd_space = kmalloc((2 + 1) * sizeof(struct dbdma_cmd), GFP_KERNEL); if(beep_dbdma_cmd_space == NULL) { printk(KERN_ERR "dmasound_pmac: no beep dbdma cmd space\n") ; return -ENOMEM ; } beep_dbdma_cmd = (volatile struct dbdma_cmd *) DBDMA_ALIGN(beep_dbdma_cmd_space); /* set up emergency dbdma cmd */ emergency_dbdma_cmd = beep_dbdma_cmd+1 ; beep_buf = (short *) kmalloc(BEEP_BUFLEN * 4, GFP_KERNEL); if (beep_buf == NULL) { printk(KERN_ERR "dmasound_pmac: no memory for beep buffer\n"); kfree(beep_dbdma_cmd_space) ; return -ENOMEM ; } return 0 ; } static struct input_dev awacs_beep_dev = { .evbit = { BIT(EV_SND) }, .sndbit = { BIT(SND_BELL) | BIT(SND_TONE) }, .event = awacs_beep_event, .name = "dmasound beeper", .phys = "macio/input0", /* what the heck is this?? */ .id = { .bustype = BUS_HOST, }, }; int __init dmasound_awacs_init(void) { struct device_node *io = NULL, *info = NULL; int vol, res; if (_machine != _MACH_Pmac) return -ENODEV; awacs_subframe = 0; awacs_revision = 0; hw_can_byteswap = 1 ; /* most can */ /* look for models we need to handle specially */ set_model() ; /* find the OF node that tells us about the dbdma stuff */ io = get_snd_io_node(); if (io == NULL) { #ifdef DEBUG_DMASOUND printk("dmasound_pmac: couldn't find sound io OF node\n"); #endif return -ENODEV ; } /* find the OF node that tells us about the sound sub-system * this doesn't exist on pre-davbus machines (earlier than 9500) */ if (awacs_revision != AWACS_AWACS) { /* set for pre-davbus */ info = get_snd_info_node(io) ; if (info == NULL){ #ifdef DEBUG_DMASOUND printk("dmasound_pmac: couldn't find 'sound' OF node\n"); #endif return -ENODEV ; } } awacs_revision = get_codec_type(info) ; if (awacs_revision == 0) { #ifdef DEBUG_DMASOUND printk("dmasound_pmac: couldn't find a Codec we can handle\n"); #endif return -ENODEV ; /* we don't know this type of h/w */ } /* set up perch, ziva, SRS or whatever else we have as sound * expansion. */ get_expansion_type(); /* we've now got enough information to make up the audio topology. * we will map the sound part of mac-io now so that we can probe for * other info if necessary (early AWACS we want to read chip ids) */ if (io->n_addrs < 3 || io->n_intrs < 3) { /* OK - maybe we need to use the 'awacs' node (on earlier * machines). */ if (awacs_node) { io = awacs_node ; if (io->n_addrs < 3 || io->n_intrs < 3) { printk("dmasound_pmac: can't use %s" " (%d addrs, %d intrs)\n", io->full_name, io->n_addrs, io->n_intrs); return -ENODEV; } } else { printk("dmasound_pmac: can't use %s (%d addrs, %d intrs)\n", io->full_name, io->n_addrs, io->n_intrs); } } if (!request_OF_resource(io, 0, NULL)) { printk(KERN_ERR "dmasound: can't request IO resource !\n"); return -ENODEV; } if (!request_OF_resource(io, 1, " (tx dma)")) { release_OF_resource(io, 0); printk(KERN_ERR "dmasound: can't request TX DMA resource !\n"); return -ENODEV; } if (!request_OF_resource(io, 2, " (rx dma)")) { release_OF_resource(io, 0); release_OF_resource(io, 1); printk(KERN_ERR "dmasound: can't request RX DMA resource !\n"); return -ENODEV; } /* all OF versions I've seen use this value */ if (i2s_node) i2s = ioremap(io->addrs[0].address, 0x1000); else awacs = ioremap(io->addrs[0].address, 0x1000); awacs_txdma = ioremap(io->addrs[1].address, 0x100); awacs_rxdma = ioremap(io->addrs[2].address, 0x100); /* first of all make sure that the chip is powered up....*/ pmac_call_feature(PMAC_FTR_SOUND_CHIP_ENABLE, io, 0, 1); if (awacs_revision == AWACS_SCREAMER && awacs) awacs_recalibrate(); awacs_irq = io->intrs[0].line; awacs_tx_irq = io->intrs[1].line; awacs_rx_irq = io->intrs[2].line; /* Hack for legacy crap that will be killed someday */ awacs_node = io; /* if we have an awacs or screamer - probe the chip to make * sure we have the right revision. */ if (awacs_revision <= AWACS_SCREAMER){ uint32_t temp, rev, mfg ; /* find out the awacs revision from the chip */ temp = in_le32(&awacs->codec_stat); rev = (temp >> 12) & 0xf; mfg = (temp >> 8) & 0xf; #ifdef DEBUG_DMASOUND printk("dmasound_pmac: Awacs/Screamer Codec Mfct: %d Rev %d\n", mfg, rev); #endif if (rev >= AWACS_SCREAMER) awacs_revision = AWACS_SCREAMER ; else awacs_revision = rev ; } dmasound.mach = machPMac; /* find out other bits & pieces from OF, these may be present only on some models ... so be careful. */ /* in the absence of a frame rates property we will use the defaults */ if (info) { unsigned int *prop, l; sound_device_id = 0; /* device ID appears post g3 b&w */ prop = (unsigned int *)get_property(info, "device-id", NULL); if (prop != 0) sound_device_id = *prop; /* look for a property saying what sample rates are available */ prop = (unsigned int *)get_property(info, "sample-rates", &l); if (prop == 0) prop = (unsigned int *) get_property (info, "output-frame-rates", &l); /* if it's there use it to set up frame rates */ init_frame_rates(prop, l) ; } if (awacs) out_le32(&awacs->control, 0x11); /* set everything quiesent */ set_hw_byteswap(io) ; /* figure out if the h/w can do it */ #ifdef CONFIG_NVRAM /* get default volume from nvram */ vol = ((pmac_xpram_read( 8 ) & 7 ) << 1 ); #else vol = 0; #endif /* set up tracking values */ spk_vol = vol * 100 ; spk_vol /= 7 ; /* get set value to a percentage */ spk_vol |= (spk_vol << 8) ; /* equal left & right */ line_vol = passthru_vol = spk_vol ; /* fill regs that are shared between AWACS & Burgundy */ awacs_reg[2] = vol + (vol << 6); awacs_reg[4] = vol + (vol << 6); awacs_reg[5] = vol + (vol << 6); /* screamer has loopthru vol control */ awacs_reg[6] = 0; /* maybe should be vol << 3 for PCMCIA speaker */ awacs_reg[7] = 0; awacs_reg[0] = MASK_MUX_CD; awacs_reg[1] = MASK_LOOPTHRU; /* FIXME: Only machines with external SRS module need MASK_PAROUT */ if (has_perch || sound_device_id == 0x5 || /*sound_device_id == 0x8 ||*/ sound_device_id == 0xb) awacs_reg[1] |= MASK_PAROUT0 | MASK_PAROUT1; switch (awacs_revision) { case AWACS_TUMBLER: tas_register_driver(&tas3001c_hooks); tas_init(I2C_DRIVERID_TAS3001C, I2C_DRIVERNAME_TAS3001C); tas_dmasound_init(); tas_post_init(); break ; case AWACS_SNAPPER: tas_register_driver(&tas3004_hooks); tas_init(I2C_DRIVERID_TAS3004,I2C_DRIVERNAME_TAS3004); tas_dmasound_init(); tas_post_init(); break; case AWACS_DACA: daca_init(); break; case AWACS_BURGUNDY: awacs_burgundy_init(); break ; case AWACS_SCREAMER: case AWACS_AWACS: default: load_awacs(); break ; } /* enable/set-up external modules - when we know how */ if (has_perch) awacs_enable_amp(100 * 0x101); /* Reset dbdma channels */ out_le32(&awacs_txdma->control, (RUN|PAUSE|FLUSH|WAKE|DEAD) << 16); while (in_le32(&awacs_txdma->status) & RUN) udelay(1); out_le32(&awacs_rxdma->control, (RUN|PAUSE|FLUSH|WAKE|DEAD) << 16); while (in_le32(&awacs_rxdma->status) & RUN) udelay(1); /* Initialize beep stuff */ if ((res=setup_beep())) return res ; #ifdef CONFIG_PM pmu_register_sleep_notifier(&awacs_sleep_notifier); #endif /* CONFIG_PM */ /* Powerbooks have odd ways of enabling inputs such as an expansion-bay CD or sound from an internal modem or a PC-card modem. */ if (is_pbook_3X00) { /* * Enable CD and PC-card sound inputs. * This is done by reading from address * f301a000, + 0x10 to enable the expansion-bay * CD sound input, + 0x80 to enable the PC-card * sound input. The 0x100 enables the SCSI bus * terminator power. */ latch_base = ioremap (0xf301a000, 0x1000); in_8(latch_base + 0x190); } else if (is_pbook_g3) { struct device_node* mio; macio_base = NULL; for (mio = io->parent; mio; mio = mio->parent) { if (strcmp(mio->name, "mac-io") == 0 && mio->n_addrs > 0) { macio_base = ioremap(mio->addrs[0].address, 0x40); break; } } /* * Enable CD sound input. * The relevant bits for writing to this byte are 0x8f. * I haven't found out what the 0x80 bit does. * For the 0xf bits, writing 3 or 7 enables the CD * input, any other value disables it. Values * 1, 3, 5, 7 enable the microphone. Values 0, 2, * 4, 6, 8 - f enable the input from the modem. * -- paulus. */ if (macio_base) out_8(macio_base + 0x37, 3); } if (hw_can_byteswap) dmasound.mach.hardware_afmts = (AFMT_S16_BE | AFMT_S16_LE) ; else dmasound.mach.hardware_afmts = AFMT_S16_BE ; /* shut out chips that do output only. * may need to extend this to machines which have no inputs - even tho' * they use screamer - IIRC one of the powerbooks is like this. */ if (awacs_revision != AWACS_DACA) { dmasound.mach.capabilities = DSP_CAP_DUPLEX ; dmasound.mach.record = PMacRecord ; } dmasound.mach.default_hard = def_hard ; dmasound.mach.default_soft = def_soft ; switch (awacs_revision) { case AWACS_BURGUNDY: sprintf(awacs_name, "PowerMac Burgundy ") ; break ; case AWACS_DACA: sprintf(awacs_name, "PowerMac DACA ") ; break ; case AWACS_TUMBLER: sprintf(awacs_name, "PowerMac Tumbler ") ; break ; case AWACS_SNAPPER: sprintf(awacs_name, "PowerMac Snapper ") ; break ; case AWACS_SCREAMER: sprintf(awacs_name, "PowerMac Screamer ") ; break ; case AWACS_AWACS: default: sprintf(awacs_name, "PowerMac AWACS rev %d ", awacs_revision) ; break ; } /* * XXX: we should handle errors here, but that would mean * rewriting the whole init code. later.. */ input_register_device(&awacs_beep_dev); return dmasound_init(); } static void __exit dmasound_awacs_cleanup(void) { input_unregister_device(&awacs_beep_dev); switch (awacs_revision) { case AWACS_TUMBLER: case AWACS_SNAPPER: tas_dmasound_cleanup(); tas_cleanup(); break ; case AWACS_DACA: daca_cleanup(); break; } dmasound_deinit(); } MODULE_DESCRIPTION("PowerMac built-in audio driver."); MODULE_LICENSE("GPL"); module_init(dmasound_awacs_init); module_exit(dmasound_awacs_cleanup);
waterice/Test-Git
sound/oss/dmasound/dmasound_awacs.c
C
gpl-2.0
86,835
//----------------------------------------------------------------------------- // boost-libs variant/test/test8.cpp header file // See http://www.boost.org for updates, documentation, and revision history. //----------------------------------------------------------------------------- // // Copyright (c) 2003 // Eric Friedman, Itay Maman // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "boost/test/minimal.hpp" #include "boost/variant.hpp" #include <iostream> #include <vector> #include <string> using namespace std; using namespace boost; typedef variant<float, std::string, int, std::vector<std::string> > t_var1; struct int_sum : static_visitor<> { int_sum() : result_(0) { } void operator()(int t) { result_ += t; } result_type operator()(float ) { } result_type operator()(const std::string& ) { } result_type operator()(const std::vector<std::string>& ) { } int result_; }; template <typename T, typename Variant> T& check_pass(Variant& v, T value) { BOOST_CHECK(get<T>(&v)); try { T& r = get<T>(v); BOOST_CHECK(r == value); return r; } catch(boost::bad_get&) { throw; // must never reach } } template <typename T, typename Variant> void check_fail(Variant& v) { BOOST_CHECK(!relaxed_get<T>(&v)); try { T& r = relaxed_get<T>(v); (void)r; // suppress warning about r not being used BOOST_CHECK(false && &r); // should never reach } catch(const boost::bad_get& e) { BOOST_CHECK(!!e.what()); // make sure that what() is const qualified and returnes something } } int test_main(int , char* []) { int_sum acc; t_var1 v1 = 800; // check get on non-const variant { int& r1 = check_pass<int>(v1, 800); const int& cr1 = check_pass<const int>(v1, 800); check_fail<float>(v1); check_fail<const float>(v1); check_fail<short>(v1); check_fail<const short>(v1); apply_visitor(acc, v1); BOOST_CHECK(acc.result_ == 800); r1 = 920; // NOTE: modifies content of v1 apply_visitor(acc, v1); BOOST_CHECK(cr1 == 920); BOOST_CHECK(acc.result_ == 800 + 920); } // check const correctness: { const t_var1& c = v1; check_pass<const int>(c, 920); //check_fail<int>(c); check_fail<const float>(c); //check_fail<float>(c); check_fail<const short>(c); //check_fail<short>(c); } return boost::exit_success; }
rprata/boost
libs/variant/test/test8.cpp
C++
gpl-2.0
2,621
/* * iaf_psc_alpha_presc.cpp * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST 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. * * NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. * */ #include "iaf_psc_alpha_presc.h" #include "exceptions.h" #include "network.h" #include "dict.h" #include "integerdatum.h" #include "doubledatum.h" #include "dictutils.h" #include "numerics.h" #include "universal_data_logger_impl.h" #include <limits> /* ---------------------------------------------------------------- * Recordables map * ---------------------------------------------------------------- */ nest::RecordablesMap<nest::iaf_psc_alpha_presc> nest::iaf_psc_alpha_presc::recordablesMap_; namespace nest { /* * Override the create() method with one call to RecordablesMap::insert_() * for each quantity to be recorded. */ template <> void RecordablesMap<iaf_psc_alpha_presc>::create() { // use standard names whereever you can for consistency! insert_(names::V_m, &iaf_psc_alpha_presc::get_V_m_); } } /* ---------------------------------------------------------------- * Default constructors defining default parameters and state * ---------------------------------------------------------------- */ nest::iaf_psc_alpha_presc::Parameters_::Parameters_() : tau_m_ ( 10.0 ), // ms tau_syn_( 2.0 ), // ms c_m_ (250.0 ), // pF t_ref_ ( 2.0 ), // ms E_L_ (-70.0 ), // mV I_e_ ( 0.0 ), // pA U_th_ (-55.0-E_L_), // mV, rel to E_L_ U_min_ (-std::numeric_limits<double_t>::infinity()), U_reset_(-70.0-E_L_), Interpol_(iaf_psc_alpha_presc::LINEAR) {} nest::iaf_psc_alpha_presc::State_::State_() : y0_(0.0), y1_(0.0), y2_(0.0), y3_(0.0), r_(0), last_spike_step_(-1), last_spike_offset_(0.0) {} /* ---------------------------------------------------------------- * Parameter and state extractions and manipulation functions * ---------------------------------------------------------------- */ void nest::iaf_psc_alpha_presc::Parameters_::get(DictionaryDatum &d) const { def<double>(d, names::E_L, E_L_); def<double>(d, names::I_e, I_e_); def<double>(d, names::V_th, U_th_+E_L_); def<double>(d, names::V_min, U_min_+E_L_); def<double>(d, names::V_reset, U_reset_+E_L_); def<double>(d, names::C_m, c_m_); def<double>(d, names::tau_m, tau_m_); def<double>(d, names::tau_syn, tau_syn_); def<double>(d, names::t_ref, t_ref_); def<long>(d, names::Interpol_Order, Interpol_); } double nest::iaf_psc_alpha_presc::Parameters_::set(const DictionaryDatum& d) { // if E_L_ is changed, we need to adjust all variables defined relative to E_L_ const double ELold = E_L_; updateValue<double>(d, names::E_L, E_L_); const double delta_EL = E_L_ - ELold; updateValue<double>(d, names::tau_m, tau_m_); updateValue<double>(d, names::tau_syn, tau_syn_); updateValue<double>(d, names::C_m, c_m_); updateValue<double>(d, names::t_ref, t_ref_); updateValue<double>(d, names::I_e, I_e_); if (updateValue<double>(d, names::V_th, U_th_)) U_th_ -= E_L_; else U_th_ -= delta_EL; if (updateValue<double>(d, names::V_min, U_min_)) U_min_ -= E_L_; else U_min_ -= delta_EL; if (updateValue<double>(d, names::V_reset, U_reset_)) U_reset_ -= E_L_; else U_reset_ -= delta_EL; long_t tmp; if ( updateValue<long_t>(d, names::Interpol_Order, tmp) ) { if ( NO_INTERPOL <= tmp && tmp < END_INTERP_ORDER ) Interpol_ = static_cast<interpOrder>(tmp); else throw BadProperty("Invalid interpolation order. " "Valid orders are 0, 1, 2, 3."); } if ( U_reset_ >= U_th_ ) throw BadProperty("Reset potential must be smaller than threshold."); if ( U_reset_ < U_min_ ) throw BadProperty("Reset potential must be greater equal minimum potential."); if ( c_m_ <= 0 ) throw BadProperty("Capacitance must be strictly positive."); if ( t_ref_ < 0 ) throw BadProperty("Refractory time must not be negative."); if ( tau_m_ <= 0 || tau_syn_ <= 0 ) throw BadProperty("All time constants must be strictly positive."); if ( tau_m_ == tau_syn_ ) throw BadProperty("Membrane and synapse time constant(s) must differ." "See note in documentation."); return delta_EL; } void nest::iaf_psc_alpha_presc::State_::get(DictionaryDatum &d, const Parameters_& p) const { def<double>(d, names::V_m, y3_ + p.E_L_); // Membrane potential def<double>(d, names::t_spike, Time(Time::step(last_spike_step_)).get_ms()); def<double>(d, names::offset, last_spike_offset_); } void nest::iaf_psc_alpha_presc::State_::set(const DictionaryDatum& d, const Parameters_& p, double delta_EL) { if ( updateValue<double>(d, names::V_m, y3_) ) y3_ -= p.E_L_; else y3_ -= delta_EL; } nest::iaf_psc_alpha_presc::Buffers_::Buffers_(iaf_psc_alpha_presc& n) : logger_(n) {} nest::iaf_psc_alpha_presc::Buffers_::Buffers_(const Buffers_&, iaf_psc_alpha_presc& n) : logger_(n) {} /* ---------------------------------------------------------------- * Default and copy constructor for node * ---------------------------------------------------------------- */ nest::iaf_psc_alpha_presc::iaf_psc_alpha_presc() : Node(), P_(), S_(), B_(*this) { recordablesMap_.create(); } nest::iaf_psc_alpha_presc::iaf_psc_alpha_presc(const iaf_psc_alpha_presc& n) : Node(n), P_(n.P_), S_(n.S_), B_(n.B_, *this) {} /* ---------------------------------------------------------------- * Node initialization functions * ---------------------------------------------------------------- */ void nest::iaf_psc_alpha_presc::init_state_(const Node& proto) { const iaf_psc_alpha_presc& pr = downcast<iaf_psc_alpha_presc>(proto); S_ = pr.S_; } void nest::iaf_psc_alpha_presc::init_buffers_() { B_.spike_y1_.clear(); // includes resize B_.spike_y2_.clear(); // includes resize B_.spike_y3_.clear(); // includes resize B_.currents_.clear(); // includes resize B_.logger_.reset(); } void nest::iaf_psc_alpha_presc::calibrate() { B_.logger_.init(); V_.h_ms_ = Time::get_resolution().get_ms(); V_.PSCInitialValue_ = 1.0 * numerics::e / P_.tau_syn_; V_.gamma_ = 1/P_.c_m_ / ( 1/P_.tau_syn_ - 1/P_.tau_m_ ); V_.gamma_sq_ = 1/P_.c_m_ / ( ( 1/P_.tau_syn_ - 1/P_.tau_m_ ) * ( 1/P_.tau_syn_ - 1/P_.tau_m_ ) ); // pre-compute matrix for full time step V_.expm1_tau_m_ = numerics::expm1(-V_.h_ms_/P_.tau_m_); V_.expm1_tau_syn_ = numerics::expm1(-V_.h_ms_/P_.tau_syn_); V_.P30_ = -P_.tau_m_ / P_.c_m_ * V_.expm1_tau_m_; V_.P31_ = V_.gamma_sq_ * V_.expm1_tau_m_ - V_.gamma_sq_ * V_.expm1_tau_syn_ - V_.h_ms_ * V_.gamma_ * V_.expm1_tau_syn_ - V_.h_ms_ * V_.gamma_; V_.P32_ = V_.gamma_ * V_.expm1_tau_m_ - V_.gamma_ * V_.expm1_tau_syn_; // t_ref_ is the refractory period in ms // refractory_steps_ is the duration of the refractory period in whole // steps, rounded down V_.refractory_steps_ = Time(Time::ms(P_.t_ref_)).get_steps(); assert(V_.refractory_steps_ >= 0); // since t_ref_ >= 0, this can only fail in error } void nest::iaf_psc_alpha_presc::update(Time const & origin, const long_t from, const long_t to) { assert(to >= 0); assert(static_cast<delay>(from) < Scheduler::get_min_delay()); assert(from < to); /* Neurons may have been initialized to superthreshold potentials. We need to check for this here and issue spikes at the beginning of the interval. */ if ( S_.y3_ >= P_.U_th_ ) { set_spiketime(Time::step(origin.get_steps() + from + 1)); S_.last_spike_offset_ = V_.h_ms_ * (1-std::numeric_limits<double_t>::epsilon()); // reset neuron and make it refractory S_.y3_ = P_.U_reset_; S_.r_ = V_.refractory_steps_; // send spike SpikeEvent se; se.set_offset(S_.last_spike_offset_); network()->send(*this, se, from); } for ( long_t lag = from ; lag < to ; ++lag ) { // time at start of update step const long_t T = origin.get_steps() + lag; // save state at beginning of interval for spike-time interpolation V_.y0_before_ = S_.y0_; V_.y1_before_ = S_.y1_; V_.y2_before_ = S_.y2_; V_.y3_before_ = S_.y3_; /* obtain input to y3_ We need to collect this value even while the neuron is refractory, since we need to clear any spikes that have come in from the ring buffer. */ const double_t dy3 = B_.spike_y3_.get_value(lag); if ( S_.r_ == 0 ) { // neuron is not refractory S_.y3_ = V_.P30_ * (P_.I_e_+S_.y0_) + V_.P31_*S_.y1_ + V_.P32_*S_.y2_ + V_.expm1_tau_m_*S_.y3_ + S_.y3_; S_.y3_ += dy3; // add input // enforce lower bound S_.y3_ = ( S_.y3_< P_.U_min_ ? P_.U_min_ : S_.y3_); } else if ( S_.r_ == 1 ) { // neuron returns from refractoriness during interval S_.r_ = 0; // Iterate third component (membrane pot) from end of // refractory period to end of interval. As first-order // approximation, add a proportion of the effect of synaptic // input during the interval to membrane pot. The proportion // is given by the part of the interval after the end of the // refractory period. S_.y3_ = P_.U_reset_ + // try fix 070623, md update_y3_delta_() + dy3 - dy3 * (1 - S_.last_spike_offset_/V_.h_ms_); // enforce lower bound S_.y3_ = ( S_.y3_< P_.U_min_ ? P_.U_min_ : S_.y3_); } else { // neuron is refractory // y3_ remains unchanged at 0.0 --S_.r_; } // update synaptic currents S_.y2_ =V_. expm1_tau_syn_*V_.h_ms_*S_.y1_ + V_.expm1_tau_syn_*S_.y2_ + V_.h_ms_*S_.y1_ + S_.y2_; S_.y1_ = V_.expm1_tau_syn_*S_.y1_ + S_.y1_; // add synaptic inputs from the ring buffer // this must happen BEFORE threshold-crossing interpolation, // since synaptic inputs occured during the interval S_.y1_ += B_.spike_y1_.get_value(lag); S_.y2_ += B_.spike_y2_.get_value(lag); //neuron spikes if ( S_.y3_ >= P_.U_th_ ) { // compute spike time set_spiketime(Time::step(T+1)); // The time for the threshpassing S_.last_spike_offset_ = V_.h_ms_ - thresh_find_(V_.h_ms_); // reset AFTER spike-time interpolation S_.y3_ = P_.U_reset_; S_.r_ = V_.refractory_steps_; // sent event SpikeEvent se; se.set_offset(S_.last_spike_offset_); network()->send(*this, se, lag); } // Set new input current. The current change occurs at the // end of the interval and thus must come AFTER the threshold- // crossing interpolation S_.y0_ = B_.currents_.get_value(lag); // logging B_.logger_.record_data(origin.get_steps()+lag); } // from lag = from ... } //function handles exact spike times void nest::iaf_psc_alpha_presc::handle(SpikeEvent & e) { assert(e.get_delay() > 0 ); const long_t Tdeliver = e.get_rel_delivery_steps(network()->get_slice_origin()); const double_t spike_weight = V_.PSCInitialValue_ * e.get_weight() * e.get_multiplicity(); const double_t dt = e.get_offset(); // Building the new matrix for the offset of the spike // NOTE: We do not use get matrix, but compute only those // components we actually need for spike registration const double_t ps_e_TauSyn = numerics::expm1(-dt/P_.tau_syn_); // needed in any case const double_t ps_e_Tau = numerics::expm1(-dt/P_.tau_m_); const double_t ps_P31 = V_.gamma_sq_ * ps_e_Tau - V_.gamma_sq_ * ps_e_TauSyn - dt * V_.gamma_ * ps_e_TauSyn - dt * V_.gamma_; B_.spike_y1_.add_value(Tdeliver, spike_weight*ps_e_TauSyn + spike_weight); B_.spike_y2_.add_value(Tdeliver, spike_weight*dt*ps_e_TauSyn + spike_weight*dt); B_.spike_y3_.add_value(Tdeliver, spike_weight*ps_P31); } void nest::iaf_psc_alpha_presc::handle(CurrentEvent& e) { assert(e.get_delay() > 0); const double_t c=e.get_current(); const double_t w=e.get_weight(); // add weighted current; HEP 2002-10-04 B_.currents_.add_value(e.get_rel_delivery_steps(network()->get_slice_origin()), w * c); } void nest::iaf_psc_alpha_presc::handle(DataLoggingRequest& e) { B_.logger_.handle(e); } // auxiliary functions --------------------------------------------- inline void nest::iaf_psc_alpha_presc::set_spiketime(Time const & now) { S_.last_spike_step_ = now.get_steps(); } inline nest::Time nest::iaf_psc_alpha_presc::get_spiketime() const { return Time::step(S_.last_spike_step_); } nest::double_t nest::iaf_psc_alpha_presc::update_y3_delta_() const { /* We need to proceed in two steps: 1. Update the synaptic currents as far as h_ms-last_spike_offset, when the refractory period ends. y3_ is clamped to 0 during this time. 2. Update y3_ from t_th to the end of the interval. The synaptic currents need not be updated during this time, since they are anyways updated for the entire interval outside. Instead of calling get_matrix(), we compute only those components we actually need locally. */ // update synaptic currents const double t_th = V_.h_ms_ - S_.last_spike_offset_; double_t ps_e_TauSyn = numerics::expm1(-t_th/P_.tau_syn_); //ps_y2_ = ps_P21_*y1_before_ + ps_P22_* y2_before_; const double ps_y2 = t_th * ps_e_TauSyn * V_.y1_before_ + ps_e_TauSyn * V_.y2_before_ + t_th * V_.y1_before_ + V_.y2_before_ ; //ps_y1_ = y1_before_*ps_P11_; const double ps_y1 = ps_e_TauSyn * V_.y1_before_ + V_.y1_before_ ; // update y3_ over remaineder of interval const double_t dt = S_.last_spike_offset_; ps_e_TauSyn = numerics::expm1(-dt / P_.tau_syn_); const double_t ps_e_Tau = numerics::expm1(-dt/P_.tau_m_); const double_t ps_P30 = - P_.tau_m_ / P_.c_m_ * ps_e_Tau; const double_t ps_P31 = V_.gamma_sq_ * ps_e_Tau - V_.gamma_sq_ * ps_e_TauSyn - dt*V_.gamma_*ps_e_TauSyn - dt*V_.gamma_; const double_t ps_P32 = V_.gamma_*ps_e_Tau - V_.gamma_* ps_e_TauSyn; // y3_ == 0.0 at beginning of sub-step return ps_P30 * (P_.I_e_+V_.y0_before_) + ps_P31 * ps_y1 + ps_P32 * ps_y2; } // finds threshpassing inline nest::double_t nest::iaf_psc_alpha_presc::thresh_find_(double_t const dt) const { switch (P_.Interpol_) { case NO_INTERPOL: return dt; case LINEAR : return thresh_find1_(dt); case QUADRATIC : return thresh_find2_(dt); case CUBIC : return thresh_find3_(dt); default: network()->message(SLIInterpreter::M_ERROR, "iaf_psc_alpha_presc::thresh_find_()", "Invalid interpolation---Internal model error."); throw BadProperty(); } return 0; } // finds threshpassing via linear interpolation nest::double_t nest::iaf_psc_alpha_presc::thresh_find1_(double_t const dt) const { double_t tau = ( P_.U_th_ - V_.y3_before_ ) * dt / ( S_.y3_ - V_.y3_before_ ); return tau; } // finds threshpassing via quadratic interpolation nest::double_t nest::iaf_psc_alpha_presc::thresh_find2_(double_t const dt) const { const double_t h_sq = dt * dt; const double_t derivative = - V_.y3_before_/P_.tau_m_ + (P_.I_e_ + V_.y0_before_ + V_.y2_before_)/P_.c_m_; const double_t a = (-V_.y3_before_/h_sq) + (S_.y3_/h_sq) - (derivative/dt); const double_t b = derivative; const double_t c = V_.y3_before_; const double_t sqr_ = std::sqrt(b*b - 4*a*c + 4*a*P_.U_th_); const double_t tau1 = (-b + sqr_) / (2*a); const double_t tau2 = (- b - sqr_) / (2*a); if (tau1 >= 0) return tau1; else if (tau2 >= 0) return tau2; else return thresh_find1_(dt); } nest::double_t nest::iaf_psc_alpha_presc::thresh_find3_(double_t const dt) const { const double_t h_ms_=dt; const double_t h_sq = h_ms_*h_ms_; const double_t h_cb = h_sq*h_ms_; const double_t deriv_t1 = - V_.y3_before_/P_.tau_m_ + (P_.I_e_ + V_.y0_before_ + V_.y2_before_)/P_.c_m_; const double_t deriv_t2 = - S_.y3_/P_.tau_m_ + (P_.I_e_ + S_.y0_ + S_.y2_)/P_.c_m_; const double_t w3_ = (2 * V_.y3_before_ / h_cb) - (2 * S_.y3_ / h_cb) + ( deriv_t1 / h_sq) + ( deriv_t2 / h_sq) ; const double_t w2_ = - (3 * V_.y3_before_ / h_sq) + (3 * S_.y3_ / h_sq) - ( 2 * deriv_t1 / h_ms_) - ( deriv_t2 / h_ms_) ; const double_t w1_ = deriv_t1; const double_t w0_ = V_.y3_before_; //normal form : x^3 + r*x^2 + s*x + t with coefficients : r, s, t const double_t r = w2_ / w3_; const double_t s = w1_ / w3_; const double_t t = (w0_ - P_.U_th_) / w3_; const double_t r_sq= r*r; //substitution y = x + r/3 : y^3 + p*y + q == 0 const double_t p = - r_sq / 3 + s; const double_t q = 2 * ( r_sq * r ) / 27 - r * s / 3 + t; //discriminante const double_t D = std::pow( (p/3), 3) + std::pow( (q/2), 2); double_t tau1; double_t tau2; double_t tau3; if(D<0){ const double_t roh = std::sqrt( -(p*p*p)/ 27 ); const double_t phi = std::acos( -q/ (2*roh) ); const double_t a = 2 * std::pow(roh, (1.0/3.0)); tau1 = (a * std::cos( phi/3 )) - r/3; tau2 = (a * std::cos( phi/3 + 2* numerics::pi/3 )) - r/3; tau3 = (a * std::cos( phi/3 + 4* numerics::pi/3 )) - r/3; } else{ const double_t sgnq = (q >= 0 ? 1 : -1); const double_t u = -sgnq * std::pow(std::fabs(q)/2.0 + std::sqrt(D), 1.0/3.0); const double_t v = - p/(3*u); tau1= (u+v) - r/3; if (tau1 >= 0) { return tau1; } else { return thresh_find2_(dt); } } //set tau to the smallest root above 0 double tau = (tau1 >= 0) ? tau1 : 2*h_ms_; if ((tau2 >=0) && (tau2 < tau)) tau = tau2; if ((tau3 >=0) && (tau3 < tau)) tau = tau3; return (tau <= h_ms_) ? tau : thresh_find2_(dt); }
INM-6/nest-git-migration
precise/iaf_psc_alpha_presc.cpp
C++
gpl-2.0
18,368
/* Copyright (c) 2006-2009 by Jakob Schroeter <js@camaya.net> This file is part of the gloox library. http://camaya.net/gloox This software is distributed under a license. The full license agreement can be found in the file LICENSE in this distribution. This software may not be copied, modified, sold or distributed other than expressed in the named license agreement. This software is distributed without any warranty. */ #include "vcardupdate.h" #include "tag.h" namespace gloox { VCardUpdate::VCardUpdate() : StanzaExtension( ExtVCardUpdate ), m_notReady( true ), m_noImage( true ), m_valid( true ) { } VCardUpdate::VCardUpdate( const std::string& hash ) : StanzaExtension( ExtVCardUpdate ), m_hash( hash ), m_notReady( false ), m_noImage( false ), m_valid( true ) { if( m_hash.empty() ) { m_noImage = true; m_valid = false; } } VCardUpdate::VCardUpdate( const Tag* tag ) : StanzaExtension( ExtVCardUpdate ), m_notReady( true ), m_noImage( true ), m_valid( false ) { if( tag && tag->name() == "x" && tag->hasAttribute( XMLNS, XMLNS_X_VCARD_UPDATE ) ) { m_valid = true; if( tag->hasChild( "photo" ) ) { m_notReady = false; m_hash = tag->findChild( "photo" )->cdata(); if( !m_hash.empty() ) m_noImage = false; } } } VCardUpdate::~VCardUpdate() { } const std::string& VCardUpdate::filterString() const { static const std::string filter = "/presence/x[@xmlns='" + XMLNS_X_VCARD_UPDATE + "']"; return filter; } Tag* VCardUpdate::tag() const { if( !m_valid ) return 0; Tag* x = new Tag( "x", XMLNS, XMLNS_X_VCARD_UPDATE ); if( !m_notReady ) { Tag* p = new Tag( x, "photo" ); if( !m_noImage ) p->setCData( m_hash ); } return x; } }
segfault/gloox-clone
src/vcardupdate.cpp
C++
gpl-2.0
1,874
<?php /** * TestLink Open Source Project - http://testlink.sourceforge.net/ * $Id: keywordBarChart.php,v 1.16.2.1 2010/12/10 15:52:23 franciscom Exp $ * * @author Kevin Levy * * - PHP autoload feature is used to load classes on demand * * @internal revisions * */ require_once('../../config.inc.php'); require_once('common.php'); require_once('charts.inc.php'); testlinkInitPage($db,true,false,"checkRights"); $cfg = new stdClass(); $cfg->scale = new stdClass(); $chart_cfg = config_get('results'); $chart_cfg = $chart_cfg['charts']['dimensions']['keywordBarChart']; $cfg->chartTitle = lang_get($chart_cfg['chartTitle']); $cfg->XSize = $chart_cfg['XSize']; $cfg->YSize = $chart_cfg['YSize']; $cfg->beginX = $chart_cfg['beginX']; $cfg->beginY = $chart_cfg['beginY']; $cfg->scale->legendXAngle = $chart_cfg['legendXAngle']; $args = init_args(); $info = getDataAndScale($db,$args); createChart($info,$cfg); /* function: getDataAndScale args: dbHandler returns: object */ function getDataAndScale(&$dbHandler,$argsObj) { $resultsCfg = config_get('results'); $obj = new stdClass(); $items = array(); $totals = null; $metricsMgr = new tlTestPlanMetrics($dbHandler); $dummy = $metricsMgr->getStatusTotalsByKeywordForRender($argsObj->tplan_id); $obj->canDraw = false; if( !is_null($dummy) ) { $dataSet = $dummy->info; $obj->canDraw = !is_null($dataSet) && (count($dataSet) > 0); } if($obj->canDraw) { // Process to enable alphabetical order foreach($dataSet as $keyword_id => $elem) { $item_descr[$elem['name']] = $keyword_id; } ksort($item_descr); foreach($item_descr as $name => $keyword_id) { $items[] = htmlspecialchars($name); foreach($dataSet[$keyword_id]['details'] as $status => $value) { $totals[$status][] = $value['qty']; } } } $obj->xAxis = new stdClass(); $obj->xAxis->values = $items; $obj->xAxis->serieName = 'Serie8'; $obj->series_color = null; $obj->scale = new stdClass(); $obj->scale->maxY = 0; $obj->scale->minY = 0; $obj->scale->divisions = 0; if(!is_null($totals)) { // in this array position we will find minimun value after an rsort $minPos = count($dataSet)-1; $obj->scale->maxY = 0; $obj->scale->minY = 0; foreach($totals as $status => $values) { $obj->chart_data[] = $values; $obj->series_label[] = lang_get($resultsCfg['status_label'][$status]); if( isset($resultsCfg['charts']['status_colour'][$status]) ) { $obj->series_color[] = $resultsCfg['charts']['status_colour'][$status]; } } } return $obj; } function init_args() { $argsObj = new stdClass(); // $argsObj->tproject_id = intval($_REQUEST['tproject_id']); $argsObj->tplan_id = intval($_REQUEST['tplan_id']); if( isset($_REQUEST['debug']) ) { $argsObj->debug = 'yes'; } return $argsObj; } function checkRights(&$db,&$user) { return $user->hasRight($db,'testplan_metrics'); } ?>
TabbedOut/testlink-1.9.9
lib/results/keywordBarChart.php
PHP
gpl-2.0
3,079