code
stringlengths
4
1.01M
module Rack # Middleware that authenticates webhooks from Twilio using the request # validator. # # The middleware takes an auth token with which to set up the request # validator and any number of paths. When a path matches the incoming request # path, the request will be checked for authentication. # # Example: # # require 'rack' # use Rack::TwilioWebhookAuthentication, ENV['AUTH_TOKEN'], /\/messages/ # # The above appends this middleware to the stack, using an auth token saved in # the ENV and only against paths that match /\/messages/. If the request # validates then it gets passed on to the action as normal. If the request # doesn't validate then the middleware responds immediately with a 403 status. class TwilioWebhookAuthentication def initialize(app, auth_token, *paths, &auth_token_lookup) @app = app @auth_token = auth_token define_singleton_method(:get_auth_token, auth_token_lookup) if block_given? @path_regex = Regexp.union(paths) end def call(env) return @app.call(env) unless env["PATH_INFO"].match(@path_regex) request = Rack::Request.new(env) original_url = request.url params = request.post? ? request.POST : {} auth_token = @auth_token || get_auth_token(params['AccountSid']) validator = Twilio::Util::RequestValidator.new(auth_token) signature = env['HTTP_X_TWILIO_SIGNATURE'] || "" if validator.validate(original_url, params, signature) @app.call(env) else [ 403, {'Content-Type' => 'text/plain'}, ["Twilio Request Validation Failed."] ] end end end end
Karma can be easily extended through plugins. In fact, all the existing preprocessors, reporters, browser launchers and frameworks are plugins. ## Installation Karma plugins are NPM modules, so the recommended way is to keep all the plugins your project requires in `package.json`: ```javascript { "devDependencies": { "karma": "~0.10", "karma-mocha": "~0.0.1", "karma-growl-reporter": "~0.0.1", "karma-firefox-launcher": "~0.0.1" } } ``` Therefore, a simple way how to install a plugin is ```bash npm install karma-<plugin name> --save-dev ``` ## Loading Plugins By default, Karma loads all NPM modules that are siblinks to it and their name matches `karma-*`. You can also explicitly list plugins you want to load. It can be either a string (module name), which will be required by Karma, or an object (inlined plugin). ```javascript plugins: [ // these plugins will be require() by Karma 'karma-jasmine', 'karma-chrome-launcher' // inelined plugins {'framework:xyz', ['factory', factoryFn]}, require('./plugin-required-from-config') ] ``` There are already many [existing plugins]. Of course, you write [your own plugins] too! [existing plugins]: https://npmjs.org/browse/keyword/karma-plugin [your own plugins]: ../dev/plugins.html
//****************************************************************************** // // Copyright (c) 2016 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. // //****************************************************************************** #pragma once #import <StoreKit/StoreKitExport.h> #import <Foundation/NSObject.h> @class NSError; @class SKPayment; @class NSString; @class NSData; @class NSDate; @class NSArray; typedef NSInteger SKPaymentTransactionState; enum { SKPaymentTransactionStatePurchasing, SKPaymentTransactionStatePurchased, SKPaymentTransactionStateFailed, SKPaymentTransactionStateRestored, SKPaymentTransactionStateDeferred, }; STOREKIT_EXPORT_CLASS @interface SKPaymentTransaction : NSObject <NSObject> @property (readonly, nonatomic) NSError* error STUB_PROPERTY; @property (readonly, nonatomic) SKPayment* payment STUB_PROPERTY; @property (readonly, nonatomic) SKPaymentTransactionState transactionState STUB_PROPERTY; @property (readonly, nonatomic) NSString* transactionIdentifier STUB_PROPERTY; @property (readonly, nonatomic) NSData* transactionReceipt STUB_PROPERTY; @property (readonly, nonatomic) NSDate* transactionDate STUB_PROPERTY; @property (readonly, nonatomic) NSArray* downloads STUB_PROPERTY; @property (readonly, nonatomic) SKPaymentTransaction* originalTransaction STUB_PROPERTY; @end
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.ServiceModel.Discovery { using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime; using SR2 = System.ServiceModel.Discovery.SR; [Fx.Tag.XamlVisible(false)] public class FindResponse { Dictionary<EndpointDiscoveryMetadata, DiscoveryMessageSequence> messageSequenceTable; Collection<EndpointDiscoveryMetadata> endpoints; internal FindResponse() { this.endpoints = new Collection<EndpointDiscoveryMetadata>(); this.messageSequenceTable = new Dictionary<EndpointDiscoveryMetadata, DiscoveryMessageSequence>(); } public Collection<EndpointDiscoveryMetadata> Endpoints { get { return this.endpoints; } } public DiscoveryMessageSequence GetMessageSequence(EndpointDiscoveryMetadata endpointDiscoveryMetadata) { if (endpointDiscoveryMetadata == null) { throw FxTrace.Exception.ArgumentNull("endpointDiscoveryMetadata"); } DiscoveryMessageSequence messageSequence = null; if (!this.messageSequenceTable.TryGetValue(endpointDiscoveryMetadata, out messageSequence)) { throw FxTrace.Exception.Argument("endpointDiscoveryMetadata", SR2.DiscoveryFindResponseMessageSequenceNotFound); } return messageSequence; } internal void AddDiscoveredEndpoint(EndpointDiscoveryMetadata endpointDiscoveryMetadata, DiscoveryMessageSequence messageSequence) { this.messageSequenceTable.Add(endpointDiscoveryMetadata, messageSequence); this.endpoints.Add(endpointDiscoveryMetadata); } } }
var foo = arr.map(v => ({ x: v.bar, y: v.bar * 2 })); var fn = () => ({}).key;
//------------------------------------------------------------------------------ // <copyright file="LinqDataSource.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System.Web.UI.WebControls.Expressions; using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Design; using System.Globalization; using System.Web.DynamicData; using System.Web.Resources; using System.Web.UI; // Represents a data source that applies LINQ expressions against a business object in order to perform the Select // operation. When the Delete, Insert and Update operations are enabled the business object, specified in // ContextTypeName, must be a LINQ TO SQL DataContext. The LINQ expressions are applied in the order of Where, // OrderBy, GroupBy, OrderGroupsBy, Select. [ DefaultEvent("Selecting"), DefaultProperty("ContextTypeName"), Designer("System.Web.UI.Design.WebControls.LinqDataSourceDesigner, " + AssemblyRef.SystemWebExtensionsDesign), ParseChildren(true), PersistChildren(false), ResourceDescription("LinqDataSource_Description"), ResourceDisplayName("LinqDataSource_DisplayName"), ToolboxBitmap(typeof(LinqDataSource), "LinqDataSource.bmp") ] public class LinqDataSource : ContextDataSource, IDynamicDataSource { private const string DefaultViewName = "DefaultView"; private LinqDataSourceView _view; public LinqDataSource() { } internal LinqDataSource(LinqDataSourceView view) : base(view) { } // internal constructor that takes page mock for unit tests. internal LinqDataSource(IPage page) : base(page) { } private LinqDataSourceView View { get { if (_view == null) { _view = (LinqDataSourceView)GetView(DefaultViewName); } return _view; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_AutoGenerateOrderByClause"), ] public bool AutoGenerateOrderByClause { get { return View.AutoGenerateOrderByClause; } set { View.AutoGenerateOrderByClause = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_AutoGenerateWhereClause"), ] public bool AutoGenerateWhereClause { get { return View.AutoGenerateWhereClause; } set { View.AutoGenerateWhereClause = value; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_AutoPage"), ] public bool AutoPage { get { return View.AutoPage; } set { View.AutoPage = value; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_AutoSort"), ] public bool AutoSort { get { return View.AutoSort; } set { View.AutoSort = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_DeleteParameters"), Browsable(false) ] public ParameterCollection DeleteParameters { get { return View.DeleteParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_ContextTypeName") ] public override string ContextTypeName { get { return View.ContextTypeName; } set { View.ContextTypeName = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_EnableDelete"), ] public bool EnableDelete { get { return View.EnableDelete; } set { View.EnableDelete = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_EnableInsert"), ] public bool EnableInsert { get { return View.EnableInsert; } set { View.EnableInsert = value; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_EnableObjectTracking"), ] public bool EnableObjectTracking { get { return View.EnableObjectTracking; } set { View.EnableObjectTracking = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_EnableUpdate"), ] public bool EnableUpdate { get { return View.EnableUpdate; } set { View.EnableUpdate = value; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_GroupBy"), ] public string GroupBy { get { return View.GroupBy; } set { View.GroupBy = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_GroupByParameters"), Browsable(false) ] public ParameterCollection GroupByParameters { get { return View.GroupByParameters; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_InsertParameters"), Browsable(false) ] public ParameterCollection InsertParameters { get { return View.InsertParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_OrderBy"), ] public string OrderBy { get { return View.OrderBy; } set { View.OrderBy = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_OrderByParameters"), Browsable(false) ] public ParameterCollection OrderByParameters { get { return View.OrderByParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_OrderGroupsBy"), ] public string OrderGroupsBy { get { return View.OrderGroupsBy; } set { View.OrderGroupsBy = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_OrderGroupsByParameters"), Browsable(false) ] public ParameterCollection OrderGroupsByParameters { get { return View.OrderGroupsByParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_Select"), ] public string Select { get { return View.SelectNew; } set { View.SelectNew = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_SelectParameters"), Browsable(false) ] public ParameterCollection SelectParameters { get { return View.SelectNewParameters; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_StoreOriginalValuesInViewState"), ] public bool StoreOriginalValuesInViewState { get { return View.StoreOriginalValuesInViewState; } set { View.StoreOriginalValuesInViewState = value; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_TableName"), ] public string TableName { get { return View.TableName; } set { View.TableName = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_UpdateParameters"), Browsable(false) ] public ParameterCollection UpdateParameters { get { return View.UpdateParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_Where"), ] public string Where { get { return View.Where; } set { View.Where = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_WhereParameters"), Browsable(false) ] public ParameterCollection WhereParameters { get { return View.WhereParameters; } } [ Category("Data"), ResourceDescription("LinqDataSource_ContextCreated"), ] public event EventHandler<LinqDataSourceStatusEventArgs> ContextCreated { add { View.ContextCreated += value; } remove { View.ContextCreated -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_ContextCreating"), ] public event EventHandler<LinqDataSourceContextEventArgs> ContextCreating { add { View.ContextCreating += value; } remove { View.ContextCreating -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_ContextDisposing"), ] public event EventHandler<LinqDataSourceDisposeEventArgs> ContextDisposing { add { View.ContextDisposing += value; } remove { View.ContextDisposing -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Deleted"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Deleted { add { View.Deleted += value; } remove { View.Deleted -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Deleting"), ] public event EventHandler<LinqDataSourceDeleteEventArgs> Deleting { add { View.Deleting += value; } remove { View.Deleting -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Inserted"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Inserted { add { View.Inserted += value; } remove { View.Inserted -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Inserting"), ] public event EventHandler<LinqDataSourceInsertEventArgs> Inserting { add { View.Inserting += value; } remove { View.Inserting -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Selected"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Selected { add { View.Selected += value; } remove { View.Selected -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Selecting"), ] public event EventHandler<LinqDataSourceSelectEventArgs> Selecting { add { View.Selecting += value; } remove { View.Selecting -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Updated"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Updated { add { View.Updated += value; } remove { View.Updated -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Updating"), ] public event EventHandler<LinqDataSourceUpdateEventArgs> Updating { add { View.Updating += value; } remove { View.Updating -= value; } } protected virtual LinqDataSourceView CreateView() { return new LinqDataSourceView(this, DefaultViewName, Context); } protected override QueryableDataSourceView CreateQueryableView() { return CreateView(); } public int Delete(IDictionary keys, IDictionary oldValues) { return View.Delete(keys, oldValues); } public int Insert(IDictionary values) { return View.Insert(values); } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected internal override void OnInit(EventArgs e) { base.OnInit(e); if (StoreOriginalValuesInViewState && (EnableUpdate || EnableDelete)) { IPage.RegisterRequiresViewStateEncryption(); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected internal override void OnUnload(EventArgs e) { base.OnUnload(e); // keeping the select contexts alive until Unload so that users can use deferred query evaluation. if (View != null) { View.ReleaseSelectContexts(); } } public int Update(IDictionary keys, IDictionary values, IDictionary oldValues) { return View.Update(keys, values, oldValues); } #region IDynamicDataSource members [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Property used for IDynamicDataSource abstraction that wraps the ContextTypeName.")] Type IDynamicDataSource.ContextType { get { if (String.IsNullOrEmpty(ContextTypeName)) { return null; } return View.ContextType; } set { View.ContextTypeName = value.AssemblyQualifiedName; } } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Property used for IDynamicDataSource abstraction that wraps the TableName.")] string IDynamicDataSource.EntitySetName { get { return TableName; } set { TableName = value; } } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "IDynamicDataSource abstraction for handling exceptions available to user through other events.")] event EventHandler<DynamicValidatorEventArgs> IDynamicDataSource.Exception { add { View.Exception += value; } remove { View.Exception -= value; } } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="SqlDataSourceFilterEventHandler.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; public delegate void SqlDataSourceFilteringEventHandler(object sender, SqlDataSourceFilteringEventArgs e); }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; namespace Microsoft.Azure.Management.Automation { public static partial class ConnectionTypeOperationsExtensions { /// <summary> /// Create a connectiontype. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create or update /// connectiontype operation. /// </param> /// <returns> /// The response model for the create or update connection type /// operation. /// </returns> public static ConnectionTypeCreateOrUpdateResponse CreateOrUpdate(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, ConnectionTypeCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IConnectionTypeOperations)s).CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a connectiontype. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create or update /// connectiontype operation. /// </param> /// <returns> /// The response model for the create or update connection type /// operation. /// </returns> public static Task<ConnectionTypeCreateOrUpdateResponse> CreateOrUpdateAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, ConnectionTypeCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Delete the connectiontype. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionTypeName'> /// Required. The name of connectiontype. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName) { return Task.Factory.StartNew((object s) => { return ((IConnectionTypeOperations)s).DeleteAsync(resourceGroupName, automationAccount, connectionTypeName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the connectiontype. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionTypeName'> /// Required. The name of connectiontype. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName) { return operations.DeleteAsync(resourceGroupName, automationAccount, connectionTypeName, CancellationToken.None); } /// <summary> /// Retrieve the connectiontype identified by connectiontype name. /// (see http://aka.ms/azureautomationsdk/connectiontypeoperations /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionTypeName'> /// Required. The name of connectiontype. /// </param> /// <returns> /// The response model for the get connection type operation. /// </returns> public static ConnectionTypeGetResponse Get(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName) { return Task.Factory.StartNew((object s) => { return ((IConnectionTypeOperations)s).GetAsync(resourceGroupName, automationAccount, connectionTypeName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the connectiontype identified by connectiontype name. /// (see http://aka.ms/azureautomationsdk/connectiontypeoperations /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionTypeName'> /// Required. The name of connectiontype. /// </param> /// <returns> /// The response model for the get connection type operation. /// </returns> public static Task<ConnectionTypeGetResponse> GetAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName) { return operations.GetAsync(resourceGroupName, automationAccount, connectionTypeName, CancellationToken.None); } /// <summary> /// Retrieve a list of connectiontypes. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list connection type operation. /// </returns> public static ConnectionTypeListResponse List(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount) { return Task.Factory.StartNew((object s) => { return ((IConnectionTypeOperations)s).ListAsync(resourceGroupName, automationAccount); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of connectiontypes. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list connection type operation. /// </returns> public static Task<ConnectionTypeListResponse> ListAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount) { return operations.ListAsync(resourceGroupName, automationAccount, CancellationToken.None); } /// <summary> /// Retrieve next list of connectiontypes. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list connection type operation. /// </returns> public static ConnectionTypeListResponse ListNext(this IConnectionTypeOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IConnectionTypeOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve next list of connectiontypes. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list connection type operation. /// </returns> public static Task<ConnectionTypeListResponse> ListNextAsync(this IConnectionTypeOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } } }
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v12.0.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var columnController_1 = require("../columnController/columnController"); var gridPanel_1 = require("../gridPanel/gridPanel"); var column_1 = require("../entities/column"); var context_1 = require("../context/context"); var headerContainer_1 = require("./headerContainer"); var eventService_1 = require("../eventService"); var events_1 = require("../events"); var scrollVisibleService_1 = require("../gridPanel/scrollVisibleService"); var HeaderRenderer = (function () { function HeaderRenderer() { } HeaderRenderer.prototype.init = function () { var _this = this; this.eHeaderViewport = this.gridPanel.getHeaderViewport(); this.eRoot = this.gridPanel.getRoot(); this.eHeaderOverlay = this.gridPanel.getHeaderOverlay(); this.centerContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getHeaderContainer(), this.gridPanel.getHeaderViewport(), this.eRoot, null); this.childContainers = [this.centerContainer]; if (!this.gridOptionsWrapper.isForPrint()) { this.pinnedLeftContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getPinnedLeftHeader(), null, this.eRoot, column_1.Column.PINNED_LEFT); this.pinnedRightContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getPinnedRightHeader(), null, this.eRoot, column_1.Column.PINNED_RIGHT); this.childContainers.push(this.pinnedLeftContainer); this.childContainers.push(this.pinnedRightContainer); } this.childContainers.forEach(function (container) { return _this.context.wireBean(container); }); // when grid columns change, it means the number of rows in the header has changed and it's all new columns this.eventService.addEventListener(events_1.Events.EVENT_GRID_COLUMNS_CHANGED, this.onGridColumnsChanged.bind(this)); // shotgun way to get labels to change, eg from sum(amount) to avg(amount) this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_VALUE_CHANGED, this.refreshHeader.bind(this)); // for resized, the individual cells take care of this, so don't need to refresh everything this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_RESIZED, this.setPinnedColContainerWidth.bind(this)); this.eventService.addEventListener(events_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.setPinnedColContainerWidth.bind(this)); this.eventService.addEventListener(events_1.Events.EVENT_SCROLL_VISIBILITY_CHANGED, this.onScrollVisibilityChanged.bind(this)); if (this.columnController.isReady()) { this.refreshHeader(); } }; HeaderRenderer.prototype.onScrollVisibilityChanged = function () { this.setPinnedColContainerWidth(); }; HeaderRenderer.prototype.forEachHeaderElement = function (callback) { this.childContainers.forEach(function (childContainer) { return childContainer.forEachHeaderElement(callback); }); }; HeaderRenderer.prototype.destroy = function () { this.childContainers.forEach(function (container) { return container.destroy(); }); }; HeaderRenderer.prototype.onGridColumnsChanged = function () { this.setHeight(); }; HeaderRenderer.prototype.refreshHeader = function () { this.setHeight(); this.childContainers.forEach(function (container) { return container.refresh(); }); this.setPinnedColContainerWidth(); }; HeaderRenderer.prototype.setHeight = function () { // if forPrint, overlay is missing if (this.eHeaderOverlay) { var rowHeight = this.gridOptionsWrapper.getHeaderHeight(); // we can probably get rid of this when we no longer need the overlay var dept = this.columnController.getHeaderRowCount(); this.eHeaderOverlay.style.height = rowHeight + 'px'; this.eHeaderOverlay.style.top = ((dept - 1) * rowHeight) + 'px'; } }; HeaderRenderer.prototype.setPinnedColContainerWidth = function () { // pinned col doesn't exist when doing forPrint if (this.gridOptionsWrapper.isForPrint()) { return; } var pinnedLeftWidthWithScroll = this.scrollVisibleService.getPinnedLeftWithScrollWidth(); var pinnedRightWidthWithScroll = this.scrollVisibleService.getPinnedRightWithScrollWidth(); this.eHeaderViewport.style.marginLeft = pinnedLeftWidthWithScroll + 'px'; this.eHeaderViewport.style.marginRight = pinnedRightWidthWithScroll + 'px'; }; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], HeaderRenderer.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], HeaderRenderer.prototype, "columnController", void 0); __decorate([ context_1.Autowired('gridPanel'), __metadata("design:type", gridPanel_1.GridPanel) ], HeaderRenderer.prototype, "gridPanel", void 0); __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], HeaderRenderer.prototype, "context", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], HeaderRenderer.prototype, "eventService", void 0); __decorate([ context_1.Autowired('scrollVisibleService'), __metadata("design:type", scrollVisibleService_1.ScrollVisibleService) ], HeaderRenderer.prototype, "scrollVisibleService", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], HeaderRenderer.prototype, "init", null); __decorate([ context_1.PreDestroy, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], HeaderRenderer.prototype, "destroy", null); HeaderRenderer = __decorate([ context_1.Bean('headerRenderer') ], HeaderRenderer); return HeaderRenderer; }()); exports.HeaderRenderer = HeaderRenderer;
require File.join(File.dirname(File.expand_path(__FILE__)), "spec_helper") describe "pg_hstore extension" do before do Sequel.extension :pg_array, :pg_hstore @db = Sequel.connect('mock://postgres', :quote_identifiers=>false) @m = Sequel::Postgres @c = @m::HStore @db.extension :pg_hstore end it "should parse hstore strings correctly" do @c.parse('').to_hash.must_equal({}) @c.parse('"a"=>"b"').to_hash.must_equal('a'=>'b') @c.parse('"a"=>"b", "c"=>NULL').to_hash.must_equal('a'=>'b', 'c'=>nil) @c.parse('"a"=>"b", "c"=>"NULL"').to_hash.must_equal('a'=>'b', 'c'=>'NULL') @c.parse('"a"=>"b", "c"=>"\\\\ \\"\'=>"').to_hash.must_equal('a'=>'b', 'c'=>'\ "\'=>') end it "should cache parse results" do r = @c::Parser.new('') o = r.parse o.must_equal({}) r.parse.must_be_same_as(o) end it "should literalize HStores to strings correctly" do @db.literal(Sequel.hstore({})).must_equal '\'\'::hstore' @db.literal(Sequel.hstore("a"=>"b")).must_equal '\'"a"=>"b"\'::hstore' @db.literal(Sequel.hstore("c"=>nil)).must_equal '\'"c"=>NULL\'::hstore' @db.literal(Sequel.hstore("c"=>'NULL')).must_equal '\'"c"=>"NULL"\'::hstore' @db.literal(Sequel.hstore('c'=>'\ "\'=>')).must_equal '\'"c"=>"\\\\ \\"\'\'=>"\'::hstore' ['\'"a"=>"b","c"=>"d"\'::hstore', '\'"c"=>"d","a"=>"b"\'::hstore'].must_include(@db.literal(Sequel.hstore("a"=>"b","c"=>"d"))) end it "should have Sequel.hstore method for creating HStore instances" do Sequel.hstore({}).class.must_equal(@c) end it "should have Sequel.hstore return HStores as-is" do a = Sequel.hstore({}) Sequel.hstore(a).object_id.must_equal(a.object_id) end it "should HStore#to_hash method for getting underlying hash" do Sequel.hstore({}).to_hash.must_be_kind_of(Hash) end it "should convert keys and values to strings on creation" do Sequel.hstore(1=>2).to_hash.must_equal("1"=>"2") end it "should convert keys and values to strings on assignment" do v = Sequel.hstore({}) v[1] = 2 v.to_hash.must_equal("1"=>"2") v.store(:'1', 3) v.to_hash.must_equal("1"=>"3") end it "should not convert nil values to strings on creation" do Sequel.hstore(:foo=>nil).to_hash.must_equal("foo"=>nil) end it "should not convert nil values to strings on assignment" do v = Sequel.hstore({}) v[:foo] = nil v.to_hash.must_equal("foo"=>nil) end it "should convert lookups by key to string" do Sequel.hstore('foo'=>'bar')[:foo].must_equal 'bar' Sequel.hstore('1'=>'bar')[1].must_equal 'bar' Sequel.hstore('foo'=>'bar').fetch(:foo).must_equal 'bar' Sequel.hstore('foo'=>'bar').fetch(:foo2, 2).must_equal 2 k = nil Sequel.hstore('foo2'=>'bar').fetch(:foo){|key| k = key }.must_equal 'foo' k.must_equal 'foo' Sequel.hstore('foo'=>'bar').has_key?(:foo).must_equal true Sequel.hstore('foo'=>'bar').has_key?(:bar).must_equal false Sequel.hstore('foo'=>'bar').key?(:foo).must_equal true Sequel.hstore('foo'=>'bar').key?(:bar).must_equal false Sequel.hstore('foo'=>'bar').member?(:foo).must_equal true Sequel.hstore('foo'=>'bar').member?(:bar).must_equal false Sequel.hstore('foo'=>'bar').include?(:foo).must_equal true Sequel.hstore('foo'=>'bar').include?(:bar).must_equal false Sequel.hstore('foo'=>'bar', '1'=>'2').values_at(:foo3, :foo, :foo2, 1).must_equal [nil, 'bar', nil, '2'] if RUBY_VERSION >= '1.9.0' Sequel.hstore('foo'=>'bar').assoc(:foo).must_equal ['foo', 'bar'] Sequel.hstore('foo'=>'bar').assoc(:foo2).must_equal nil end end it "should convert has_value?/value? lookups to string" do Sequel.hstore('foo'=>'bar').has_value?(:bar).must_equal true Sequel.hstore('foo'=>'bar').has_value?(:foo).must_equal false Sequel.hstore('foo'=>'bar').value?(:bar).must_equal true Sequel.hstore('foo'=>'bar').value?(:foo).must_equal false end it "should handle nil values in has_value?/value? lookups" do Sequel.hstore('foo'=>'').has_value?('').must_equal true Sequel.hstore('foo'=>'').has_value?(nil).must_equal false Sequel.hstore('foo'=>nil).has_value?(nil).must_equal true end it "should have underlying hash convert lookups by key to string" do Sequel.hstore('foo'=>'bar').to_hash[:foo].must_equal 'bar' Sequel.hstore('1'=>'bar').to_hash[1].must_equal 'bar' end if RUBY_VERSION >= '1.9.0' it "should convert key lookups to string" do Sequel.hstore('foo'=>'bar').key(:bar).must_equal 'foo' Sequel.hstore('foo'=>'bar').key(:bar2).must_equal nil end it "should handle nil values in key lookups" do Sequel.hstore('foo'=>'').key('').must_equal 'foo' Sequel.hstore('foo'=>'').key(nil).must_equal nil Sequel.hstore('foo'=>nil).key(nil).must_equal 'foo' end it "should convert rassoc lookups to string" do Sequel.hstore('foo'=>'bar').rassoc(:bar).must_equal ['foo', 'bar'] Sequel.hstore('foo'=>'bar').rassoc(:bar2).must_equal nil end it "should handle nil values in rassoc lookups" do Sequel.hstore('foo'=>'').rassoc('').must_equal ['foo', ''] Sequel.hstore('foo'=>'').rassoc(nil).must_equal nil Sequel.hstore('foo'=>nil).rassoc(nil).must_equal ['foo', nil] end end it "should have delete convert key to string" do v = Sequel.hstore('foo'=>'bar') v.delete(:foo).must_equal 'bar' v.to_hash.must_equal({}) end it "should handle #replace with hashes that do not use strings" do v = Sequel.hstore('foo'=>'bar') v.replace(:bar=>1) v.class.must_equal(@c) v.must_equal('bar'=>'1') v.to_hash[:bar].must_equal '1' end it "should handle #merge with hashes that do not use strings" do v = Sequel.hstore('foo'=>'bar').merge(:bar=>1) v.class.must_equal(@c) v.must_equal('foo'=>'bar', 'bar'=>'1') end it "should handle #merge/#update with hashes that do not use strings" do v = Sequel.hstore('foo'=>'bar') v.merge!(:bar=>1) v.class.must_equal(@c) v.must_equal('foo'=>'bar', 'bar'=>'1') v = Sequel.hstore('foo'=>'bar') v.update(:bar=>1) v.class.must_equal(@c) v.must_equal('foo'=>'bar', 'bar'=>'1') end it "should support using hstores as bound variables" do @db.bound_variable_arg(1, nil).must_equal 1 @db.bound_variable_arg({'1'=>'2'}, nil).must_equal '"1"=>"2"' @db.bound_variable_arg(Sequel.hstore('1'=>'2'), nil).must_equal '"1"=>"2"' @db.bound_variable_arg(Sequel.hstore('1'=>nil), nil).must_equal '"1"=>NULL' @db.bound_variable_arg(Sequel.hstore('1'=>"NULL"), nil).must_equal '"1"=>"NULL"' @db.bound_variable_arg(Sequel.hstore('1'=>"'\\ \"=>"), nil).must_equal '"1"=>"\'\\\\ \\"=>"' ['"a"=>"b","c"=>"d"', '"c"=>"d","a"=>"b"'].must_include(@db.bound_variable_arg(Sequel.hstore("a"=>"b","c"=>"d"), nil)) end it "should parse hstore type from the schema correctly" do @db.fetch = [{:name=>'id', :db_type=>'integer'}, {:name=>'i', :db_type=>'hstore'}] @db.schema(:items).map{|e| e[1][:type]}.must_equal [:integer, :hstore] end it "should support typecasting for the hstore type" do h = Sequel.hstore(1=>2) @db.typecast_value(:hstore, h).object_id.must_equal(h.object_id) @db.typecast_value(:hstore, {}).class.must_equal(@c) @db.typecast_value(:hstore, {}).must_equal Sequel.hstore({}) @db.typecast_value(:hstore, {'a'=>'b'}).must_equal Sequel.hstore("a"=>"b") proc{@db.typecast_value(:hstore, [])}.must_raise(Sequel::InvalidValue) end it "should be serializable" do v = Sequel.hstore('foo'=>'bar') dump = Marshal.dump(v) Marshal.load(dump).must_equal v end it "should return correct results for Database#schema_type_class" do @db.schema_type_class(:hstore).must_equal Sequel::Postgres::HStore @db.schema_type_class(:integer).must_equal Integer end end
/* * $Id$ * * Various URI related functions * * Copyright (C) 2001-2003 FhG Fokus * * This file is part of ser, a free SIP server. * * ser is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version * * For a license to use the ser software under conditions * other than those described here, or to purchase support for this * software, please contact iptel.org by e-mail at the following addresses: * info@iptel.org * * ser 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 * * History: * -------- * 2003-02-26: created by janakj */ #ifndef URI_MOD_H #define URI_MOD_H #include "../../lib/srdb2/db.h" #include "../../str.h" #endif /* URI_MOD_H */
/************************************************************************* * The contents of this file are subject to the Adempiere License. You may * obtain a copy of the License at http://www.adempiere.org/license.html * Software is on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either * express or implied. See the License for details. Code: Adempiere ERP+CRM * Copyright (C) 1999-2003 Jorg Janke, ComPiere, Inc. All Rights Reserved. ************************************************************************* * $Id: DBA_Recompile_Run.sql,v 1.1 2006/04/21 17:51:58 jjanke Exp $ *** * Title: Run Recompile and list invalids and disabeled * Description: ************************************************************************/ BEGIN DBA_Recompile(NULL); DBA_Cleanup(); END; / -- Check General Status SELECT Object_Name AS Object_Invalid, Status FROM User_Objects WHERE Status <> 'VALID' --AND Object_Type='VIEW' / -- Trigger Info SELECT Trigger_Name AS Trigger_NotEnabled, Status FROM User_Triggers WHERE Status != 'ENABLED' / -- Constraint Info SELECT Constraint_Name AS Constraint_Problem, Status, Validated FROM User_Constraints WHERE Status != 'ENABLED' OR Validated != 'VALIDATED' / SELECT * FROM USER_ERRORS /
/******************************************************************* * This file is part of the Emulex Linux Device Driver for * * Fibre Channel Host Bus Adapters. * * Copyright (C) 2004-2008 Emulex. All rights reserved. * * EMULEX and SLI are trademarks of Emulex. * * www.emulex.com * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of version 2 of the GNU General * * Public License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful. * * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE * * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD * * TO BE LEGALLY INVALID. See the GNU General Public License for * * more details, a copy of which can be found in the file COPYING * * included with this package. * *******************************************************************/ #define LPFC_DRIVER_VERSION "8.2.7" #define LPFC_DRIVER_NAME "lpfc" #define LPFC_MODULE_DESC "Emulex LightPulse Fibre Channel SCSI driver " \ LPFC_DRIVER_VERSION #define LPFC_COPYRIGHT "Copyright(c) 2004-2008 Emulex. All rights reserved."
/** * Copyright (c) 2009--2014 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package com.redhat.rhn.domain.kickstart; import java.util.Date; import java.io.Serializable; import org.apache.commons.lang.builder.HashCodeBuilder; import com.redhat.rhn.domain.rhnpackage.PackageName; /** * KickstartPackage * @version $Rev$ */ public class KickstartPackage implements Serializable, Comparable<KickstartPackage> { private static final long serialVersionUID = 1L; private Long position; private Date created; private Date modified; private KickstartData ksData; private PackageName packageName; /** * */ public KickstartPackage() { super(); } /** * @param ksDataIn identifies kickstart * @param packageNameIn PackageName to be associated */ public KickstartPackage(KickstartData ksDataIn, PackageName packageNameIn) { super(); this.ksData = ksDataIn; this.packageName = packageNameIn; this.position = 0L; } /** * @param ksDataIn identifies kickstart * @param packageNameIn PackageName to be associated * @param posIn position the package Name is in the kickstart package list */ public KickstartPackage(KickstartData ksDataIn, PackageName packageNameIn, Long posIn) { this(ksDataIn, packageNameIn); this.position = posIn; } /** * @return Returns the position. */ public Long getPosition() { return position; } /** * @param positionIn The position to set. */ public void setPosition(Long positionIn) { this.position = positionIn; } /** * @return Returns the created. */ public Date getCreated() { return created; } /** * @param createdIn The created to set. */ public void setCreated(Date createdIn) { this.created = createdIn; } /** * @return Returns the modified. */ public Date getModified() { return modified; } /** * @param modifiedIn The modified to set. */ public void setModified(Date modifiedIn) { this.modified = modifiedIn; } /** * @return Returns the ksdata. */ public KickstartData getKsData() { return ksData; } /** * @param ksdata The ksdata to set. */ public void setKsData(KickstartData ksdata) { this.ksData = ksdata; } /** * @return Returns the packageName. */ public PackageName getPackageName() { return packageName; } /** * @param pn The packageName to set. */ public void setPackageName(PackageName pn) { this.packageName = pn; } /** * @param that KickstartPackage to be compared * @return -1,0,1 for sort algo */ public int compareTo(KickstartPackage that) { final int equal = 0; if (this.equals(that)) { return equal; } int comparism = this.getKsData().getLabel().compareTo(that.getKsData().getLabel()); if (equal != comparism) { return comparism; } comparism = this.getPosition().compareTo(that.getPosition()); if (equal != comparism) { return comparism; } return this.getPackageName().compareTo(that.getPackageName()); } /** * {@inheritDoc} */ public boolean equals(final Object other) { if (!(other instanceof KickstartPackage)) { return false; } KickstartPackage that = (KickstartPackage) other; return this.hashCode() == other.hashCode(); } /** * {@inheritDoc} */ public int hashCode() { return new HashCodeBuilder() .append(getKsData().getId()) .append(getPosition()) .append(getPackageName()) .toHashCode(); } /** * {@inheritDoc} */ public String toString() { return "{ " + this.getKsData().getId().toString() + ", " + this.getPosition().toString() + ", " + this.getPackageName().getName() + " }"; } /** * Produce a clone of a kickstartPackage object * @param data The new kickstart data * @return the clone */ public KickstartPackage deepCopy(KickstartData data) { KickstartPackage kp = new KickstartPackage(); kp.setKsData(data); kp.setPackageName(this.getPackageName()); kp.setPosition(this.getPosition()); return kp; } }
// SPDX-License-Identifier: GPL-2.0 /* * gadget.c - DesignWare USB3 DRD Controller Gadget Framework Link * * Copyright (C) 2010-2011 Texas Instruments Incorporated - https://www.ti.com * * Authors: Felipe Balbi <balbi@ti.com>, * Sebastian Andrzej Siewior <bigeasy@linutronix.de> */ #include <linux/kernel.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/list.h> #include <linux/dma-mapping.h> #include <linux/usb/ch9.h> #include <linux/usb/gadget.h> #include "debug.h" #include "core.h" #include "gadget.h" #include "io.h" #define DWC3_ALIGN_FRAME(d, n) (((d)->frame_number + ((d)->interval * (n))) \ & ~((d)->interval - 1)) /** * dwc3_gadget_set_test_mode - enables usb2 test modes * @dwc: pointer to our context structure * @mode: the mode to set (J, K SE0 NAK, Force Enable) * * Caller should take care of locking. This function will return 0 on * success or -EINVAL if wrong Test Selector is passed. */ int dwc3_gadget_set_test_mode(struct dwc3 *dwc, int mode) { u32 reg; reg = dwc3_readl(dwc->regs, DWC3_DCTL); reg &= ~DWC3_DCTL_TSTCTRL_MASK; switch (mode) { case USB_TEST_J: case USB_TEST_K: case USB_TEST_SE0_NAK: case USB_TEST_PACKET: case USB_TEST_FORCE_ENABLE: reg |= mode << 1; break; default: return -EINVAL; } dwc3_gadget_dctl_write_safe(dwc, reg); return 0; } /** * dwc3_gadget_get_link_state - gets current state of usb link * @dwc: pointer to our context structure * * Caller should take care of locking. This function will * return the link state on success (>= 0) or -ETIMEDOUT. */ int dwc3_gadget_get_link_state(struct dwc3 *dwc) { u32 reg; reg = dwc3_readl(dwc->regs, DWC3_DSTS); return DWC3_DSTS_USBLNKST(reg); } /** * dwc3_gadget_set_link_state - sets usb link to a particular state * @dwc: pointer to our context structure * @state: the state to put link into * * Caller should take care of locking. This function will * return 0 on success or -ETIMEDOUT. */ int dwc3_gadget_set_link_state(struct dwc3 *dwc, enum dwc3_link_state state) { int retries = 10000; u32 reg; /* * Wait until device controller is ready. Only applies to 1.94a and * later RTL. */ if (!DWC3_VER_IS_PRIOR(DWC3, 194A)) { while (--retries) { reg = dwc3_readl(dwc->regs, DWC3_DSTS); if (reg & DWC3_DSTS_DCNRD) udelay(5); else break; } if (retries <= 0) return -ETIMEDOUT; } reg = dwc3_readl(dwc->regs, DWC3_DCTL); reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK; /* set no action before sending new link state change */ dwc3_writel(dwc->regs, DWC3_DCTL, reg); /* set requested state */ reg |= DWC3_DCTL_ULSTCHNGREQ(state); dwc3_writel(dwc->regs, DWC3_DCTL, reg); /* * The following code is racy when called from dwc3_gadget_wakeup, * and is not needed, at least on newer versions */ if (!DWC3_VER_IS_PRIOR(DWC3, 194A)) return 0; /* wait for a change in DSTS */ retries = 10000; while (--retries) { reg = dwc3_readl(dwc->regs, DWC3_DSTS); if (DWC3_DSTS_USBLNKST(reg) == state) return 0; udelay(5); } return -ETIMEDOUT; } /** * dwc3_ep_inc_trb - increment a trb index. * @index: Pointer to the TRB index to increment. * * The index should never point to the link TRB. After incrementing, * if it is point to the link TRB, wrap around to the beginning. The * link TRB is always at the last TRB entry. */ static void dwc3_ep_inc_trb(u8 *index) { (*index)++; if (*index == (DWC3_TRB_NUM - 1)) *index = 0; } /** * dwc3_ep_inc_enq - increment endpoint's enqueue pointer * @dep: The endpoint whose enqueue pointer we're incrementing */ static void dwc3_ep_inc_enq(struct dwc3_ep *dep) { dwc3_ep_inc_trb(&dep->trb_enqueue); } /** * dwc3_ep_inc_deq - increment endpoint's dequeue pointer * @dep: The endpoint whose enqueue pointer we're incrementing */ static void dwc3_ep_inc_deq(struct dwc3_ep *dep) { dwc3_ep_inc_trb(&dep->trb_dequeue); } static void dwc3_gadget_del_and_unmap_request(struct dwc3_ep *dep, struct dwc3_request *req, int status) { struct dwc3 *dwc = dep->dwc; list_del(&req->list); req->remaining = 0; req->needs_extra_trb = false; if (req->request.status == -EINPROGRESS) req->request.status = status; if (req->trb) usb_gadget_unmap_request_by_dev(dwc->sysdev, &req->request, req->direction); req->trb = NULL; trace_dwc3_gadget_giveback(req); if (dep->number > 1) pm_runtime_put(dwc->dev); } /** * dwc3_gadget_giveback - call struct usb_request's ->complete callback * @dep: The endpoint to whom the request belongs to * @req: The request we're giving back * @status: completion code for the request * * Must be called with controller's lock held and interrupts disabled. This * function will unmap @req and call its ->complete() callback to notify upper * layers that it has completed. */ void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req, int status) { struct dwc3 *dwc = dep->dwc; dwc3_gadget_del_and_unmap_request(dep, req, status); req->status = DWC3_REQUEST_STATUS_COMPLETED; spin_unlock(&dwc->lock); usb_gadget_giveback_request(&dep->endpoint, &req->request); spin_lock(&dwc->lock); } /** * dwc3_send_gadget_generic_command - issue a generic command for the controller * @dwc: pointer to the controller context * @cmd: the command to be issued * @param: command parameter * * Caller should take care of locking. Issue @cmd with a given @param to @dwc * and wait for its completion. */ int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd, u32 param) { u32 timeout = 500; int status = 0; int ret = 0; u32 reg; dwc3_writel(dwc->regs, DWC3_DGCMDPAR, param); dwc3_writel(dwc->regs, DWC3_DGCMD, cmd | DWC3_DGCMD_CMDACT); do { reg = dwc3_readl(dwc->regs, DWC3_DGCMD); if (!(reg & DWC3_DGCMD_CMDACT)) { status = DWC3_DGCMD_STATUS(reg); if (status) ret = -EINVAL; break; } } while (--timeout); if (!timeout) { ret = -ETIMEDOUT; status = -ETIMEDOUT; } trace_dwc3_gadget_generic_cmd(cmd, param, status); return ret; } static int __dwc3_gadget_wakeup(struct dwc3 *dwc); /** * dwc3_send_gadget_ep_cmd - issue an endpoint command * @dep: the endpoint to which the command is going to be issued * @cmd: the command to be issued * @params: parameters to the command * * Caller should handle locking. This function will issue @cmd with given * @params to @dep and wait for its completion. */ int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned int cmd, struct dwc3_gadget_ep_cmd_params *params) { const struct usb_endpoint_descriptor *desc = dep->endpoint.desc; struct dwc3 *dwc = dep->dwc; u32 timeout = 5000; u32 saved_config = 0; u32 reg; int cmd_status = 0; int ret = -EINVAL; /* * When operating in USB 2.0 speeds (HS/FS), if GUSB2PHYCFG.ENBLSLPM or * GUSB2PHYCFG.SUSPHY is set, it must be cleared before issuing an * endpoint command. * * Save and clear both GUSB2PHYCFG.ENBLSLPM and GUSB2PHYCFG.SUSPHY * settings. Restore them after the command is completed. * * DWC_usb3 3.30a and DWC_usb31 1.90a programming guide section 3.2.2 */ if (dwc->gadget->speed <= USB_SPEED_HIGH) { reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0)); if (unlikely(reg & DWC3_GUSB2PHYCFG_SUSPHY)) { saved_config |= DWC3_GUSB2PHYCFG_SUSPHY; reg &= ~DWC3_GUSB2PHYCFG_SUSPHY; } if (reg & DWC3_GUSB2PHYCFG_ENBLSLPM) { saved_config |= DWC3_GUSB2PHYCFG_ENBLSLPM; reg &= ~DWC3_GUSB2PHYCFG_ENBLSLPM; } if (saved_config) dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg); } if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) { int link_state; link_state = dwc3_gadget_get_link_state(dwc); if (link_state == DWC3_LINK_STATE_U1 || link_state == DWC3_LINK_STATE_U2 || link_state == DWC3_LINK_STATE_U3) { ret = __dwc3_gadget_wakeup(dwc); dev_WARN_ONCE(dwc->dev, ret, "wakeup failed --> %d\n", ret); } } dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0); dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1); dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2); /* * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're * not relying on XferNotReady, we can make use of a special "No * Response Update Transfer" command where we should clear both CmdAct * and CmdIOC bits. * * With this, we don't need to wait for command completion and can * straight away issue further commands to the endpoint. * * NOTICE: We're making an assumption that control endpoints will never * make use of Update Transfer command. This is a safe assumption * because we can never have more than one request at a time with * Control Endpoints. If anybody changes that assumption, this chunk * needs to be updated accordingly. */ if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER && !usb_endpoint_xfer_isoc(desc)) cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT); else cmd |= DWC3_DEPCMD_CMDACT; dwc3_writel(dep->regs, DWC3_DEPCMD, cmd); do { reg = dwc3_readl(dep->regs, DWC3_DEPCMD); if (!(reg & DWC3_DEPCMD_CMDACT)) { cmd_status = DWC3_DEPCMD_STATUS(reg); switch (cmd_status) { case 0: ret = 0; break; case DEPEVT_TRANSFER_NO_RESOURCE: dev_WARN(dwc->dev, "No resource for %s\n", dep->name); ret = -EINVAL; break; case DEPEVT_TRANSFER_BUS_EXPIRY: /* * SW issues START TRANSFER command to * isochronous ep with future frame interval. If * future interval time has already passed when * core receives the command, it will respond * with an error status of 'Bus Expiry'. * * Instead of always returning -EINVAL, let's * give a hint to the gadget driver that this is * the case by returning -EAGAIN. */ ret = -EAGAIN; break; default: dev_WARN(dwc->dev, "UNKNOWN cmd status\n"); } break; } } while (--timeout); if (timeout == 0) { ret = -ETIMEDOUT; cmd_status = -ETIMEDOUT; } trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status); if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) { if (ret == 0) dep->flags |= DWC3_EP_TRANSFER_STARTED; if (ret != -ETIMEDOUT) dwc3_gadget_ep_get_transfer_index(dep); } if (saved_config) { reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0)); reg |= saved_config; dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg); } return ret; } static int dwc3_send_clear_stall_ep_cmd(struct dwc3_ep *dep) { struct dwc3 *dwc = dep->dwc; struct dwc3_gadget_ep_cmd_params params; u32 cmd = DWC3_DEPCMD_CLEARSTALL; /* * As of core revision 2.60a the recommended programming model * is to set the ClearPendIN bit when issuing a Clear Stall EP * command for IN endpoints. This is to prevent an issue where * some (non-compliant) hosts may not send ACK TPs for pending * IN transfers due to a mishandled error condition. Synopsys * STAR 9000614252. */ if (dep->direction && !DWC3_VER_IS_PRIOR(DWC3, 260A) && (dwc->gadget->speed >= USB_SPEED_SUPER)) cmd |= DWC3_DEPCMD_CLEARPENDIN; memset(&params, 0, sizeof(params)); return dwc3_send_gadget_ep_cmd(dep, cmd, &params); } static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep, struct dwc3_trb *trb) { u32 offset = (char *) trb - (char *) dep->trb_pool; return dep->trb_pool_dma + offset; } static int dwc3_alloc_trb_pool(struct dwc3_ep *dep) { struct dwc3 *dwc = dep->dwc; if (dep->trb_pool) return 0; dep->trb_pool = dma_alloc_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM, &dep->trb_pool_dma, GFP_KERNEL); if (!dep->trb_pool) { dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n", dep->name); return -ENOMEM; } return 0; } static void dwc3_free_trb_pool(struct dwc3_ep *dep) { struct dwc3 *dwc = dep->dwc; dma_free_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM, dep->trb_pool, dep->trb_pool_dma); dep->trb_pool = NULL; dep->trb_pool_dma = 0; } static int dwc3_gadget_set_xfer_resource(struct dwc3_ep *dep) { struct dwc3_gadget_ep_cmd_params params; memset(&params, 0x00, sizeof(params)); params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1); return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE, &params); } /** * dwc3_gadget_start_config - configure ep resources * @dep: endpoint that is being enabled * * Issue a %DWC3_DEPCMD_DEPSTARTCFG command to @dep. After the command's * completion, it will set Transfer Resource for all available endpoints. * * The assignment of transfer resources cannot perfectly follow the data book * due to the fact that the controller driver does not have all knowledge of the * configuration in advance. It is given this information piecemeal by the * composite gadget framework after every SET_CONFIGURATION and * SET_INTERFACE. Trying to follow the databook programming model in this * scenario can cause errors. For two reasons: * * 1) The databook says to do %DWC3_DEPCMD_DEPSTARTCFG for every * %USB_REQ_SET_CONFIGURATION and %USB_REQ_SET_INTERFACE (8.1.5). This is * incorrect in the scenario of multiple interfaces. * * 2) The databook does not mention doing more %DWC3_DEPCMD_DEPXFERCFG for new * endpoint on alt setting (8.1.6). * * The following simplified method is used instead: * * All hardware endpoints can be assigned a transfer resource and this setting * will stay persistent until either a core reset or hibernation. So whenever we * do a %DWC3_DEPCMD_DEPSTARTCFG(0) we can go ahead and do * %DWC3_DEPCMD_DEPXFERCFG for every hardware endpoint as well. We are * guaranteed that there are as many transfer resources as endpoints. * * This function is called for each endpoint when it is being enabled but is * triggered only when called for EP0-out, which always happens first, and which * should only happen in one of the above conditions. */ static int dwc3_gadget_start_config(struct dwc3_ep *dep) { struct dwc3_gadget_ep_cmd_params params; struct dwc3 *dwc; u32 cmd; int i; int ret; if (dep->number) return 0; memset(&params, 0x00, sizeof(params)); cmd = DWC3_DEPCMD_DEPSTARTCFG; dwc = dep->dwc; ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params); if (ret) return ret; for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) { struct dwc3_ep *dep = dwc->eps[i]; if (!dep) continue; ret = dwc3_gadget_set_xfer_resource(dep); if (ret) return ret; } return 0; } static int dwc3_gadget_set_ep_config(struct dwc3_ep *dep, unsigned int action) { const struct usb_ss_ep_comp_descriptor *comp_desc; const struct usb_endpoint_descriptor *desc; struct dwc3_gadget_ep_cmd_params params; struct dwc3 *dwc = dep->dwc; comp_desc = dep->endpoint.comp_desc; desc = dep->endpoint.desc; memset(&params, 0x00, sizeof(params)); params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc)) | DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc)); /* Burst size is only needed in SuperSpeed mode */ if (dwc->gadget->speed >= USB_SPEED_SUPER) { u32 burst = dep->endpoint.maxburst; params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst - 1); } params.param0 |= action; if (action == DWC3_DEPCFG_ACTION_RESTORE) params.param2 |= dep->saved_state; if (usb_endpoint_xfer_control(desc)) params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN; if (dep->number <= 1 || usb_endpoint_xfer_isoc(desc)) params.param1 |= DWC3_DEPCFG_XFER_NOT_READY_EN; if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) { params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE | DWC3_DEPCFG_XFER_COMPLETE_EN | DWC3_DEPCFG_STREAM_EVENT_EN; dep->stream_capable = true; } if (!usb_endpoint_xfer_control(desc)) params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN; /* * We are doing 1:1 mapping for endpoints, meaning * Physical Endpoints 2 maps to Logical Endpoint 2 and * so on. We consider the direction bit as part of the physical * endpoint number. So USB endpoint 0x81 is 0x03. */ params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number); /* * We must use the lower 16 TX FIFOs even though * HW might have more */ if (dep->direction) params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1); if (desc->bInterval) { u8 bInterval_m1; /* * Valid range for DEPCFG.bInterval_m1 is from 0 to 13. * * NOTE: The programming guide incorrectly stated bInterval_m1 * must be set to 0 when operating in fullspeed. Internally the * controller does not have this limitation. See DWC_usb3x * programming guide section 3.2.2.1. */ bInterval_m1 = min_t(u8, desc->bInterval - 1, 13); if (usb_endpoint_type(desc) == USB_ENDPOINT_XFER_INT && dwc->gadget->speed == USB_SPEED_FULL) dep->interval = desc->bInterval; else dep->interval = 1 << (desc->bInterval - 1); params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(bInterval_m1); } return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETEPCONFIG, &params); } static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool interrupt); /** * dwc3_gadget_calc_tx_fifo_size - calculates the txfifo size value * @dwc: pointer to the DWC3 context * @nfifos: number of fifos to calculate for * * Calculates the size value based on the equation below: * * DWC3 revision 280A and prior: * fifo_size = mult * (max_packet / mdwidth) + 1; * * DWC3 revision 290A and onwards: * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1 * * The max packet size is set to 1024, as the txfifo requirements mainly apply * to super speed USB use cases. However, it is safe to overestimate the fifo * allocations for other scenarios, i.e. high speed USB. */ static int dwc3_gadget_calc_tx_fifo_size(struct dwc3 *dwc, int mult) { int max_packet = 1024; int fifo_size; int mdwidth; mdwidth = dwc3_mdwidth(dwc); /* MDWIDTH is represented in bits, we need it in bytes */ mdwidth >>= 3; if (DWC3_VER_IS_PRIOR(DWC3, 290A)) fifo_size = mult * (max_packet / mdwidth) + 1; else fifo_size = mult * ((max_packet + mdwidth) / mdwidth) + 1; return fifo_size; } /** * dwc3_gadget_clear_tx_fifo_size - Clears txfifo allocation * @dwc: pointer to the DWC3 context * * Iterates through all the endpoint registers and clears the previous txfifo * allocations. */ void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc) { struct dwc3_ep *dep; int fifo_depth; int size; int num; if (!dwc->do_fifo_resize) return; /* Read ep0IN related TXFIFO size */ dep = dwc->eps[1]; size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0)); if (DWC3_IP_IS(DWC3)) fifo_depth = DWC3_GTXFIFOSIZ_TXFDEP(size); else fifo_depth = DWC31_GTXFIFOSIZ_TXFDEP(size); dwc->last_fifo_depth = fifo_depth; /* Clear existing TXFIFO for all IN eps except ep0 */ for (num = 3; num < min_t(int, dwc->num_eps, DWC3_ENDPOINTS_NUM); num += 2) { dep = dwc->eps[num]; /* Don't change TXFRAMNUM on usb31 version */ size = DWC3_IP_IS(DWC3) ? 0 : dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1)) & DWC31_GTXFIFOSIZ_TXFRAMNUM; dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1), size); } dwc->num_ep_resized = 0; } /* * dwc3_gadget_resize_tx_fifos - reallocate fifo spaces for current use-case * @dwc: pointer to our context structure * * This function will a best effort FIFO allocation in order * to improve FIFO usage and throughput, while still allowing * us to enable as many endpoints as possible. * * Keep in mind that this operation will be highly dependent * on the configured size for RAM1 - which contains TxFifo -, * the amount of endpoints enabled on coreConsultant tool, and * the width of the Master Bus. * * In general, FIFO depths are represented with the following equation: * * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1 * * In conjunction with dwc3_gadget_check_config(), this resizing logic will * ensure that all endpoints will have enough internal memory for one max * packet per endpoint. */ static int dwc3_gadget_resize_tx_fifos(struct dwc3_ep *dep) { struct dwc3 *dwc = dep->dwc; int fifo_0_start; int ram1_depth; int fifo_size; int min_depth; int num_in_ep; int remaining; int num_fifos = 1; int fifo; int tmp; if (!dwc->do_fifo_resize) return 0; /* resize IN endpoints except ep0 */ if (!usb_endpoint_dir_in(dep->endpoint.desc) || dep->number <= 1) return 0; ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7); if ((dep->endpoint.maxburst > 1 && usb_endpoint_xfer_bulk(dep->endpoint.desc)) || usb_endpoint_xfer_isoc(dep->endpoint.desc)) num_fifos = 3; if (dep->endpoint.maxburst > 6 && usb_endpoint_xfer_bulk(dep->endpoint.desc) && DWC3_IP_IS(DWC31)) num_fifos = dwc->tx_fifo_resize_max_num; /* FIFO size for a single buffer */ fifo = dwc3_gadget_calc_tx_fifo_size(dwc, 1); /* Calculate the number of remaining EPs w/o any FIFO */ num_in_ep = dwc->max_cfg_eps; num_in_ep -= dwc->num_ep_resized; /* Reserve at least one FIFO for the number of IN EPs */ min_depth = num_in_ep * (fifo + 1); remaining = ram1_depth - min_depth - dwc->last_fifo_depth; remaining = max_t(int, 0, remaining); /* * We've already reserved 1 FIFO per EP, so check what we can fit in * addition to it. If there is not enough remaining space, allocate * all the remaining space to the EP. */ fifo_size = (num_fifos - 1) * fifo; if (remaining < fifo_size) fifo_size = remaining; fifo_size += fifo; /* Last increment according to the TX FIFO size equation */ fifo_size++; /* Check if TXFIFOs start at non-zero addr */ tmp = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0)); fifo_0_start = DWC3_GTXFIFOSIZ_TXFSTADDR(tmp); fifo_size |= (fifo_0_start + (dwc->last_fifo_depth << 16)); if (DWC3_IP_IS(DWC3)) dwc->last_fifo_depth += DWC3_GTXFIFOSIZ_TXFDEP(fifo_size); else dwc->last_fifo_depth += DWC31_GTXFIFOSIZ_TXFDEP(fifo_size); /* Check fifo size allocation doesn't exceed available RAM size. */ if (dwc->last_fifo_depth >= ram1_depth) { dev_err(dwc->dev, "Fifosize(%d) > RAM size(%d) %s depth:%d\n", dwc->last_fifo_depth, ram1_depth, dep->endpoint.name, fifo_size); if (DWC3_IP_IS(DWC3)) fifo_size = DWC3_GTXFIFOSIZ_TXFDEP(fifo_size); else fifo_size = DWC31_GTXFIFOSIZ_TXFDEP(fifo_size); dwc->last_fifo_depth -= fifo_size; return -ENOMEM; } dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1), fifo_size); dwc->num_ep_resized++; return 0; } /** * __dwc3_gadget_ep_enable - initializes a hw endpoint * @dep: endpoint to be initialized * @action: one of INIT, MODIFY or RESTORE * * Caller should take care of locking. Execute all necessary commands to * initialize a HW endpoint so it can be used by a gadget driver. */ static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action) { const struct usb_endpoint_descriptor *desc = dep->endpoint.desc; struct dwc3 *dwc = dep->dwc; u32 reg; int ret; if (!(dep->flags & DWC3_EP_ENABLED)) { ret = dwc3_gadget_resize_tx_fifos(dep); if (ret) return ret; ret = dwc3_gadget_start_config(dep); if (ret) return ret; } ret = dwc3_gadget_set_ep_config(dep, action); if (ret) return ret; if (!(dep->flags & DWC3_EP_ENABLED)) { struct dwc3_trb *trb_st_hw; struct dwc3_trb *trb_link; dep->type = usb_endpoint_type(desc); dep->flags |= DWC3_EP_ENABLED; reg = dwc3_readl(dwc->regs, DWC3_DALEPENA); reg |= DWC3_DALEPENA_EP(dep->number); dwc3_writel(dwc->regs, DWC3_DALEPENA, reg); if (usb_endpoint_xfer_control(desc)) goto out; /* Initialize the TRB ring */ dep->trb_dequeue = 0; dep->trb_enqueue = 0; memset(dep->trb_pool, 0, sizeof(struct dwc3_trb) * DWC3_TRB_NUM); /* Link TRB. The HWO bit is never reset */ trb_st_hw = &dep->trb_pool[0]; trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1]; trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw)); trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw)); trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB; trb_link->ctrl |= DWC3_TRB_CTRL_HWO; } /* * Issue StartTransfer here with no-op TRB so we can always rely on No * Response Update Transfer command. */ if (usb_endpoint_xfer_bulk(desc) || usb_endpoint_xfer_int(desc)) { struct dwc3_gadget_ep_cmd_params params; struct dwc3_trb *trb; dma_addr_t trb_dma; u32 cmd; memset(&params, 0, sizeof(params)); trb = &dep->trb_pool[0]; trb_dma = dwc3_trb_dma_offset(dep, trb); params.param0 = upper_32_bits(trb_dma); params.param1 = lower_32_bits(trb_dma); cmd = DWC3_DEPCMD_STARTTRANSFER; ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params); if (ret < 0) return ret; if (dep->stream_capable) { /* * For streams, at start, there maybe a race where the * host primes the endpoint before the function driver * queues a request to initiate a stream. In that case, * the controller will not see the prime to generate the * ERDY and start stream. To workaround this, issue a * no-op TRB as normal, but end it immediately. As a * result, when the function driver queues the request, * the next START_TRANSFER command will cause the * controller to generate an ERDY to initiate the * stream. */ dwc3_stop_active_transfer(dep, true, true); /* * All stream eps will reinitiate stream on NoStream * rejection until we can determine that the host can * prime after the first transfer. * * However, if the controller is capable of * TXF_FLUSH_BYPASS, then IN direction endpoints will * automatically restart the stream without the driver * initiation. */ if (!dep->direction || !(dwc->hwparams.hwparams9 & DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS)) dep->flags |= DWC3_EP_FORCE_RESTART_STREAM; } } out: trace_dwc3_gadget_ep_enable(dep); return 0; } static void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep) { struct dwc3_request *req; dwc3_stop_active_transfer(dep, true, false); /* - giveback all requests to gadget driver */ while (!list_empty(&dep->started_list)) { req = next_request(&dep->started_list); dwc3_gadget_giveback(dep, req, -ESHUTDOWN); } while (!list_empty(&dep->pending_list)) { req = next_request(&dep->pending_list); dwc3_gadget_giveback(dep, req, -ESHUTDOWN); } while (!list_empty(&dep->cancelled_list)) { req = next_request(&dep->cancelled_list); dwc3_gadget_giveback(dep, req, -ESHUTDOWN); } } /** * __dwc3_gadget_ep_disable - disables a hw endpoint * @dep: the endpoint to disable * * This function undoes what __dwc3_gadget_ep_enable did and also removes * requests which are currently being processed by the hardware and those which * are not yet scheduled. * * Caller should take care of locking. */ static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep) { struct dwc3 *dwc = dep->dwc; u32 reg; trace_dwc3_gadget_ep_disable(dep); /* make sure HW endpoint isn't stalled */ if (dep->flags & DWC3_EP_STALL) __dwc3_gadget_ep_set_halt(dep, 0, false); reg = dwc3_readl(dwc->regs, DWC3_DALEPENA); reg &= ~DWC3_DALEPENA_EP(dep->number); dwc3_writel(dwc->regs, DWC3_DALEPENA, reg); /* Clear out the ep descriptors for non-ep0 */ if (dep->number > 1) { dep->endpoint.comp_desc = NULL; dep->endpoint.desc = NULL; } dwc3_remove_requests(dwc, dep); dep->stream_capable = false; dep->type = 0; dep->flags = 0; return 0; } /* -------------------------------------------------------------------------- */ static int dwc3_gadget_ep0_enable(struct usb_ep *ep, const struct usb_endpoint_descriptor *desc) { return -EINVAL; } static int dwc3_gadget_ep0_disable(struct usb_ep *ep) { return -EINVAL; } /* -------------------------------------------------------------------------- */ static int dwc3_gadget_ep_enable(struct usb_ep *ep, const struct usb_endpoint_descriptor *desc) { struct dwc3_ep *dep; struct dwc3 *dwc; unsigned long flags; int ret; if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) { pr_debug("dwc3: invalid parameters\n"); return -EINVAL; } if (!desc->wMaxPacketSize) { pr_debug("dwc3: missing wMaxPacketSize\n"); return -EINVAL; } dep = to_dwc3_ep(ep); dwc = dep->dwc; if (dev_WARN_ONCE(dwc->dev, dep->flags & DWC3_EP_ENABLED, "%s is already enabled\n", dep->name)) return 0; spin_lock_irqsave(&dwc->lock, flags); ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT); spin_unlock_irqrestore(&dwc->lock, flags); return ret; } static int dwc3_gadget_ep_disable(struct usb_ep *ep) { struct dwc3_ep *dep; struct dwc3 *dwc; unsigned long flags; int ret; if (!ep) { pr_debug("dwc3: invalid parameters\n"); return -EINVAL; } dep = to_dwc3_ep(ep); dwc = dep->dwc; if (dev_WARN_ONCE(dwc->dev, !(dep->flags & DWC3_EP_ENABLED), "%s is already disabled\n", dep->name)) return 0; spin_lock_irqsave(&dwc->lock, flags); ret = __dwc3_gadget_ep_disable(dep); spin_unlock_irqrestore(&dwc->lock, flags); return ret; } static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep, gfp_t gfp_flags) { struct dwc3_request *req; struct dwc3_ep *dep = to_dwc3_ep(ep); req = kzalloc(sizeof(*req), gfp_flags); if (!req) return NULL; req->direction = dep->direction; req->epnum = dep->number; req->dep = dep; req->status = DWC3_REQUEST_STATUS_UNKNOWN; trace_dwc3_alloc_request(req); return &req->request; } static void dwc3_gadget_ep_free_request(struct usb_ep *ep, struct usb_request *request) { struct dwc3_request *req = to_dwc3_request(request); trace_dwc3_free_request(req); kfree(req); } /** * dwc3_ep_prev_trb - returns the previous TRB in the ring * @dep: The endpoint with the TRB ring * @index: The index of the current TRB in the ring * * Returns the TRB prior to the one pointed to by the index. If the * index is 0, we will wrap backwards, skip the link TRB, and return * the one just before that. */ static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index) { u8 tmp = index; if (!tmp) tmp = DWC3_TRB_NUM - 1; return &dep->trb_pool[tmp - 1]; } static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep) { u8 trbs_left; /* * If the enqueue & dequeue are equal then the TRB ring is either full * or empty. It's considered full when there are DWC3_TRB_NUM-1 of TRBs * pending to be processed by the driver. */ if (dep->trb_enqueue == dep->trb_dequeue) { /* * If there is any request remained in the started_list at * this point, that means there is no TRB available. */ if (!list_empty(&dep->started_list)) return 0; return DWC3_TRB_NUM - 1; } trbs_left = dep->trb_dequeue - dep->trb_enqueue; trbs_left &= (DWC3_TRB_NUM - 1); if (dep->trb_dequeue < dep->trb_enqueue) trbs_left--; return trbs_left; } static void __dwc3_prepare_one_trb(struct dwc3_ep *dep, struct dwc3_trb *trb, dma_addr_t dma, unsigned int length, unsigned int chain, unsigned int node, unsigned int stream_id, unsigned int short_not_ok, unsigned int no_interrupt, unsigned int is_last, bool must_interrupt) { struct dwc3 *dwc = dep->dwc; struct usb_gadget *gadget = dwc->gadget; enum usb_device_speed speed = gadget->speed; trb->size = DWC3_TRB_SIZE_LENGTH(length); trb->bpl = lower_32_bits(dma); trb->bph = upper_32_bits(dma); switch (usb_endpoint_type(dep->endpoint.desc)) { case USB_ENDPOINT_XFER_CONTROL: trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP; break; case USB_ENDPOINT_XFER_ISOC: if (!node) { trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST; /* * USB Specification 2.0 Section 5.9.2 states that: "If * there is only a single transaction in the microframe, * only a DATA0 data packet PID is used. If there are * two transactions per microframe, DATA1 is used for * the first transaction data packet and DATA0 is used * for the second transaction data packet. If there are * three transactions per microframe, DATA2 is used for * the first transaction data packet, DATA1 is used for * the second, and DATA0 is used for the third." * * IOW, we should satisfy the following cases: * * 1) length <= maxpacket * - DATA0 * * 2) maxpacket < length <= (2 * maxpacket) * - DATA1, DATA0 * * 3) (2 * maxpacket) < length <= (3 * maxpacket) * - DATA2, DATA1, DATA0 */ if (speed == USB_SPEED_HIGH) { struct usb_ep *ep = &dep->endpoint; unsigned int mult = 2; unsigned int maxp = usb_endpoint_maxp(ep->desc); if (length <= (2 * maxp)) mult--; if (length <= maxp) mult--; trb->size |= DWC3_TRB_SIZE_PCM1(mult); } } else { trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS; } /* always enable Interrupt on Missed ISOC */ trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI; break; case USB_ENDPOINT_XFER_BULK: case USB_ENDPOINT_XFER_INT: trb->ctrl = DWC3_TRBCTL_NORMAL; break; default: /* * This is only possible with faulty memory because we * checked it already :) */ dev_WARN(dwc->dev, "Unknown endpoint type %d\n", usb_endpoint_type(dep->endpoint.desc)); } /* * Enable Continue on Short Packet * when endpoint is not a stream capable */ if (usb_endpoint_dir_out(dep->endpoint.desc)) { if (!dep->stream_capable) trb->ctrl |= DWC3_TRB_CTRL_CSP; if (short_not_ok) trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI; } if ((!no_interrupt && !chain) || must_interrupt) trb->ctrl |= DWC3_TRB_CTRL_IOC; if (chain) trb->ctrl |= DWC3_TRB_CTRL_CHN; else if (dep->stream_capable && is_last) trb->ctrl |= DWC3_TRB_CTRL_LST; if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable) trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(stream_id); trb->ctrl |= DWC3_TRB_CTRL_HWO; dwc3_ep_inc_enq(dep); trace_dwc3_prepare_trb(dep, trb); } /** * dwc3_prepare_one_trb - setup one TRB from one request * @dep: endpoint for which this request is prepared * @req: dwc3_request pointer * @trb_length: buffer size of the TRB * @chain: should this TRB be chained to the next? * @node: only for isochronous endpoints. First TRB needs different type. * @use_bounce_buffer: set to use bounce buffer * @must_interrupt: set to interrupt on TRB completion */ static void dwc3_prepare_one_trb(struct dwc3_ep *dep, struct dwc3_request *req, unsigned int trb_length, unsigned int chain, unsigned int node, bool use_bounce_buffer, bool must_interrupt) { struct dwc3_trb *trb; dma_addr_t dma; unsigned int stream_id = req->request.stream_id; unsigned int short_not_ok = req->request.short_not_ok; unsigned int no_interrupt = req->request.no_interrupt; unsigned int is_last = req->request.is_last; if (use_bounce_buffer) dma = dep->dwc->bounce_addr; else if (req->request.num_sgs > 0) dma = sg_dma_address(req->start_sg); else dma = req->request.dma; trb = &dep->trb_pool[dep->trb_enqueue]; if (!req->trb) { dwc3_gadget_move_started_request(req); req->trb = trb; req->trb_dma = dwc3_trb_dma_offset(dep, trb); } req->num_trbs++; __dwc3_prepare_one_trb(dep, trb, dma, trb_length, chain, node, stream_id, short_not_ok, no_interrupt, is_last, must_interrupt); } static bool dwc3_needs_extra_trb(struct dwc3_ep *dep, struct dwc3_request *req) { unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc); unsigned int rem = req->request.length % maxp; if ((req->request.length && req->request.zero && !rem && !usb_endpoint_xfer_isoc(dep->endpoint.desc)) || (!req->direction && rem)) return true; return false; } /** * dwc3_prepare_last_sg - prepare TRBs for the last SG entry * @dep: The endpoint that the request belongs to * @req: The request to prepare * @entry_length: The last SG entry size * @node: Indicates whether this is not the first entry (for isoc only) * * Return the number of TRBs prepared. */ static int dwc3_prepare_last_sg(struct dwc3_ep *dep, struct dwc3_request *req, unsigned int entry_length, unsigned int node) { unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc); unsigned int rem = req->request.length % maxp; unsigned int num_trbs = 1; if (dwc3_needs_extra_trb(dep, req)) num_trbs++; if (dwc3_calc_trbs_left(dep) < num_trbs) return 0; req->needs_extra_trb = num_trbs > 1; /* Prepare a normal TRB */ if (req->direction || req->request.length) dwc3_prepare_one_trb(dep, req, entry_length, req->needs_extra_trb, node, false, false); /* Prepare extra TRBs for ZLP and MPS OUT transfer alignment */ if ((!req->direction && !req->request.length) || req->needs_extra_trb) dwc3_prepare_one_trb(dep, req, req->direction ? 0 : maxp - rem, false, 1, true, false); return num_trbs; } static int dwc3_prepare_trbs_sg(struct dwc3_ep *dep, struct dwc3_request *req) { struct scatterlist *sg = req->start_sg; struct scatterlist *s; int i; unsigned int length = req->request.length; unsigned int remaining = req->request.num_mapped_sgs - req->num_queued_sgs; unsigned int num_trbs = req->num_trbs; bool needs_extra_trb = dwc3_needs_extra_trb(dep, req); /* * If we resume preparing the request, then get the remaining length of * the request and resume where we left off. */ for_each_sg(req->request.sg, s, req->num_queued_sgs, i) length -= sg_dma_len(s); for_each_sg(sg, s, remaining, i) { unsigned int num_trbs_left = dwc3_calc_trbs_left(dep); unsigned int trb_length; bool must_interrupt = false; bool last_sg = false; trb_length = min_t(unsigned int, length, sg_dma_len(s)); length -= trb_length; /* * IOMMU driver is coalescing the list of sgs which shares a * page boundary into one and giving it to USB driver. With * this the number of sgs mapped is not equal to the number of * sgs passed. So mark the chain bit to false if it isthe last * mapped sg. */ if ((i == remaining - 1) || !length) last_sg = true; if (!num_trbs_left) break; if (last_sg) { if (!dwc3_prepare_last_sg(dep, req, trb_length, i)) break; } else { /* * Look ahead to check if we have enough TRBs for the * next SG entry. If not, set interrupt on this TRB to * resume preparing the next SG entry when more TRBs are * free. */ if (num_trbs_left == 1 || (needs_extra_trb && num_trbs_left <= 2 && sg_dma_len(sg_next(s)) >= length)) must_interrupt = true; dwc3_prepare_one_trb(dep, req, trb_length, 1, i, false, must_interrupt); } /* * There can be a situation where all sgs in sglist are not * queued because of insufficient trb number. To handle this * case, update start_sg to next sg to be queued, so that * we have free trbs we can continue queuing from where we * previously stopped */ if (!last_sg) req->start_sg = sg_next(s); req->num_queued_sgs++; req->num_pending_sgs--; /* * The number of pending SG entries may not correspond to the * number of mapped SG entries. If all the data are queued, then * don't include unused SG entries. */ if (length == 0) { req->num_pending_sgs = 0; break; } if (must_interrupt) break; } return req->num_trbs - num_trbs; } static int dwc3_prepare_trbs_linear(struct dwc3_ep *dep, struct dwc3_request *req) { return dwc3_prepare_last_sg(dep, req, req->request.length, 0); } /* * dwc3_prepare_trbs - setup TRBs from requests * @dep: endpoint for which requests are being prepared * * The function goes through the requests list and sets up TRBs for the * transfers. The function returns once there are no more TRBs available or * it runs out of requests. * * Returns the number of TRBs prepared or negative errno. */ static int dwc3_prepare_trbs(struct dwc3_ep *dep) { struct dwc3_request *req, *n; int ret = 0; BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM); /* * We can get in a situation where there's a request in the started list * but there weren't enough TRBs to fully kick it in the first time * around, so it has been waiting for more TRBs to be freed up. * * In that case, we should check if we have a request with pending_sgs * in the started list and prepare TRBs for that request first, * otherwise we will prepare TRBs completely out of order and that will * break things. */ list_for_each_entry(req, &dep->started_list, list) { if (req->num_pending_sgs > 0) { ret = dwc3_prepare_trbs_sg(dep, req); if (!ret || req->num_pending_sgs) return ret; } if (!dwc3_calc_trbs_left(dep)) return ret; /* * Don't prepare beyond a transfer. In DWC_usb32, its transfer * burst capability may try to read and use TRBs beyond the * active transfer instead of stopping. */ if (dep->stream_capable && req->request.is_last) return ret; } list_for_each_entry_safe(req, n, &dep->pending_list, list) { struct dwc3 *dwc = dep->dwc; ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request, dep->direction); if (ret) return ret; req->sg = req->request.sg; req->start_sg = req->sg; req->num_queued_sgs = 0; req->num_pending_sgs = req->request.num_mapped_sgs; if (req->num_pending_sgs > 0) { ret = dwc3_prepare_trbs_sg(dep, req); if (req->num_pending_sgs) return ret; } else { ret = dwc3_prepare_trbs_linear(dep, req); } if (!ret || !dwc3_calc_trbs_left(dep)) return ret; /* * Don't prepare beyond a transfer. In DWC_usb32, its transfer * burst capability may try to read and use TRBs beyond the * active transfer instead of stopping. */ if (dep->stream_capable && req->request.is_last) return ret; } return ret; } static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep); static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep) { struct dwc3_gadget_ep_cmd_params params; struct dwc3_request *req; int starting; int ret; u32 cmd; /* * Note that it's normal to have no new TRBs prepared (i.e. ret == 0). * This happens when we need to stop and restart a transfer such as in * the case of reinitiating a stream or retrying an isoc transfer. */ ret = dwc3_prepare_trbs(dep); if (ret < 0) return ret; starting = !(dep->flags & DWC3_EP_TRANSFER_STARTED); /* * If there's no new TRB prepared and we don't need to restart a * transfer, there's no need to update the transfer. */ if (!ret && !starting) return ret; req = next_request(&dep->started_list); if (!req) { dep->flags |= DWC3_EP_PENDING_REQUEST; return 0; } memset(&params, 0, sizeof(params)); if (starting) { params.param0 = upper_32_bits(req->trb_dma); params.param1 = lower_32_bits(req->trb_dma); cmd = DWC3_DEPCMD_STARTTRANSFER; if (dep->stream_capable) cmd |= DWC3_DEPCMD_PARAM(req->request.stream_id); if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) cmd |= DWC3_DEPCMD_PARAM(dep->frame_number); } else { cmd = DWC3_DEPCMD_UPDATETRANSFER | DWC3_DEPCMD_PARAM(dep->resource_index); } ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params); if (ret < 0) { struct dwc3_request *tmp; if (ret == -EAGAIN) return ret; dwc3_stop_active_transfer(dep, true, true); list_for_each_entry_safe(req, tmp, &dep->started_list, list) dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_DEQUEUED); /* If ep isn't started, then there's no end transfer pending */ if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING)) dwc3_gadget_ep_cleanup_cancelled_requests(dep); return ret; } if (dep->stream_capable && req->request.is_last) dep->flags |= DWC3_EP_WAIT_TRANSFER_COMPLETE; return 0; } static int __dwc3_gadget_get_frame(struct dwc3 *dwc) { u32 reg; reg = dwc3_readl(dwc->regs, DWC3_DSTS); return DWC3_DSTS_SOFFN(reg); } /** * dwc3_gadget_start_isoc_quirk - workaround invalid frame number * @dep: isoc endpoint * * This function tests for the correct combination of BIT[15:14] from the 16-bit * microframe number reported by the XferNotReady event for the future frame * number to start the isoc transfer. * * In DWC_usb31 version 1.70a-ea06 and prior, for highspeed and fullspeed * isochronous IN, BIT[15:14] of the 16-bit microframe number reported by the * XferNotReady event are invalid. The driver uses this number to schedule the * isochronous transfer and passes it to the START TRANSFER command. Because * this number is invalid, the command may fail. If BIT[15:14] matches the * internal 16-bit microframe, the START TRANSFER command will pass and the * transfer will start at the scheduled time, if it is off by 1, the command * will still pass, but the transfer will start 2 seconds in the future. For all * other conditions, the START TRANSFER command will fail with bus-expiry. * * In order to workaround this issue, we can test for the correct combination of * BIT[15:14] by sending START TRANSFER commands with different values of * BIT[15:14]: 'b00, 'b01, 'b10, and 'b11. Each combination is 2^14 uframe apart * (or 2 seconds). 4 seconds into the future will result in a bus-expiry status. * As the result, within the 4 possible combinations for BIT[15:14], there will * be 2 successful and 2 failure START COMMAND status. One of the 2 successful * command status will result in a 2-second delay start. The smaller BIT[15:14] * value is the correct combination. * * Since there are only 4 outcomes and the results are ordered, we can simply * test 2 START TRANSFER commands with BIT[15:14] combinations 'b00 and 'b01 to * deduce the smaller successful combination. * * Let test0 = test status for combination 'b00 and test1 = test status for 'b01 * of BIT[15:14]. The correct combination is as follow: * * if test0 fails and test1 passes, BIT[15:14] is 'b01 * if test0 fails and test1 fails, BIT[15:14] is 'b10 * if test0 passes and test1 fails, BIT[15:14] is 'b11 * if test0 passes and test1 passes, BIT[15:14] is 'b00 * * Synopsys STAR 9001202023: Wrong microframe number for isochronous IN * endpoints. */ static int dwc3_gadget_start_isoc_quirk(struct dwc3_ep *dep) { int cmd_status = 0; bool test0; bool test1; while (dep->combo_num < 2) { struct dwc3_gadget_ep_cmd_params params; u32 test_frame_number; u32 cmd; /* * Check if we can start isoc transfer on the next interval or * 4 uframes in the future with BIT[15:14] as dep->combo_num */ test_frame_number = dep->frame_number & DWC3_FRNUMBER_MASK; test_frame_number |= dep->combo_num << 14; test_frame_number += max_t(u32, 4, dep->interval); params.param0 = upper_32_bits(dep->dwc->bounce_addr); params.param1 = lower_32_bits(dep->dwc->bounce_addr); cmd = DWC3_DEPCMD_STARTTRANSFER; cmd |= DWC3_DEPCMD_PARAM(test_frame_number); cmd_status = dwc3_send_gadget_ep_cmd(dep, cmd, &params); /* Redo if some other failure beside bus-expiry is received */ if (cmd_status && cmd_status != -EAGAIN) { dep->start_cmd_status = 0; dep->combo_num = 0; return 0; } /* Store the first test status */ if (dep->combo_num == 0) dep->start_cmd_status = cmd_status; dep->combo_num++; /* * End the transfer if the START_TRANSFER command is successful * to wait for the next XferNotReady to test the command again */ if (cmd_status == 0) { dwc3_stop_active_transfer(dep, true, true); return 0; } } /* test0 and test1 are both completed at this point */ test0 = (dep->start_cmd_status == 0); test1 = (cmd_status == 0); if (!test0 && test1) dep->combo_num = 1; else if (!test0 && !test1) dep->combo_num = 2; else if (test0 && !test1) dep->combo_num = 3; else if (test0 && test1) dep->combo_num = 0; dep->frame_number &= DWC3_FRNUMBER_MASK; dep->frame_number |= dep->combo_num << 14; dep->frame_number += max_t(u32, 4, dep->interval); /* Reinitialize test variables */ dep->start_cmd_status = 0; dep->combo_num = 0; return __dwc3_gadget_kick_transfer(dep); } static int __dwc3_gadget_start_isoc(struct dwc3_ep *dep) { const struct usb_endpoint_descriptor *desc = dep->endpoint.desc; struct dwc3 *dwc = dep->dwc; int ret; int i; if (list_empty(&dep->pending_list) && list_empty(&dep->started_list)) { dep->flags |= DWC3_EP_PENDING_REQUEST; return -EAGAIN; } if (!dwc->dis_start_transfer_quirk && (DWC3_VER_IS_PRIOR(DWC31, 170A) || DWC3_VER_TYPE_IS_WITHIN(DWC31, 170A, EA01, EA06))) { if (dwc->gadget->speed <= USB_SPEED_HIGH && dep->direction) return dwc3_gadget_start_isoc_quirk(dep); } if (desc->bInterval <= 14 && dwc->gadget->speed >= USB_SPEED_HIGH) { u32 frame = __dwc3_gadget_get_frame(dwc); bool rollover = frame < (dep->frame_number & DWC3_FRNUMBER_MASK); /* * frame_number is set from XferNotReady and may be already * out of date. DSTS only provides the lower 14 bit of the * current frame number. So add the upper two bits of * frame_number and handle a possible rollover. * This will provide the correct frame_number unless more than * rollover has happened since XferNotReady. */ dep->frame_number = (dep->frame_number & ~DWC3_FRNUMBER_MASK) | frame; if (rollover) dep->frame_number += BIT(14); } for (i = 0; i < DWC3_ISOC_MAX_RETRIES; i++) { dep->frame_number = DWC3_ALIGN_FRAME(dep, i + 1); ret = __dwc3_gadget_kick_transfer(dep); if (ret != -EAGAIN) break; } /* * After a number of unsuccessful start attempts due to bus-expiry * status, issue END_TRANSFER command and retry on the next XferNotReady * event. */ if (ret == -EAGAIN) { struct dwc3_gadget_ep_cmd_params params; u32 cmd; cmd = DWC3_DEPCMD_ENDTRANSFER | DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_PARAM(dep->resource_index); dep->resource_index = 0; memset(&params, 0, sizeof(params)); ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params); if (!ret) dep->flags |= DWC3_EP_END_TRANSFER_PENDING; } return ret; } static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req) { struct dwc3 *dwc = dep->dwc; if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) { dev_err(dwc->dev, "%s: can't queue to disabled endpoint\n", dep->name); return -ESHUTDOWN; } if (WARN(req->dep != dep, "request %pK belongs to '%s'\n", &req->request, req->dep->name)) return -EINVAL; if (WARN(req->status < DWC3_REQUEST_STATUS_COMPLETED, "%s: request %pK already in flight\n", dep->name, &req->request)) return -EINVAL; pm_runtime_get(dwc->dev); req->request.actual = 0; req->request.status = -EINPROGRESS; trace_dwc3_ep_queue(req); list_add_tail(&req->list, &dep->pending_list); req->status = DWC3_REQUEST_STATUS_QUEUED; if (dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE) return 0; /* * Start the transfer only after the END_TRANSFER is completed * and endpoint STALL is cleared. */ if ((dep->flags & DWC3_EP_END_TRANSFER_PENDING) || (dep->flags & DWC3_EP_WEDGE) || (dep->flags & DWC3_EP_STALL)) { dep->flags |= DWC3_EP_DELAY_START; return 0; } /* * NOTICE: Isochronous endpoints should NEVER be prestarted. We must * wait for a XferNotReady event so we will know what's the current * (micro-)frame number. * * Without this trick, we are very, very likely gonna get Bus Expiry * errors which will force us issue EndTransfer command. */ if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) { if (!(dep->flags & DWC3_EP_PENDING_REQUEST) && !(dep->flags & DWC3_EP_TRANSFER_STARTED)) return 0; if ((dep->flags & DWC3_EP_PENDING_REQUEST)) { if (!(dep->flags & DWC3_EP_TRANSFER_STARTED)) return __dwc3_gadget_start_isoc(dep); } } __dwc3_gadget_kick_transfer(dep); return 0; } static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request, gfp_t gfp_flags) { struct dwc3_request *req = to_dwc3_request(request); struct dwc3_ep *dep = to_dwc3_ep(ep); struct dwc3 *dwc = dep->dwc; unsigned long flags; int ret; spin_lock_irqsave(&dwc->lock, flags); ret = __dwc3_gadget_ep_queue(dep, req); spin_unlock_irqrestore(&dwc->lock, flags); return ret; } static void dwc3_gadget_ep_skip_trbs(struct dwc3_ep *dep, struct dwc3_request *req) { int i; /* If req->trb is not set, then the request has not started */ if (!req->trb) return; /* * If request was already started, this means we had to * stop the transfer. With that we also need to ignore * all TRBs used by the request, however TRBs can only * be modified after completion of END_TRANSFER * command. So what we do here is that we wait for * END_TRANSFER completion and only after that, we jump * over TRBs by clearing HWO and incrementing dequeue * pointer. */ for (i = 0; i < req->num_trbs; i++) { struct dwc3_trb *trb; trb = &dep->trb_pool[dep->trb_dequeue]; trb->ctrl &= ~DWC3_TRB_CTRL_HWO; dwc3_ep_inc_deq(dep); } req->num_trbs = 0; } static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep) { struct dwc3_request *req; struct dwc3_request *tmp; struct dwc3 *dwc = dep->dwc; list_for_each_entry_safe(req, tmp, &dep->cancelled_list, list) { dwc3_gadget_ep_skip_trbs(dep, req); switch (req->status) { case DWC3_REQUEST_STATUS_DISCONNECTED: dwc3_gadget_giveback(dep, req, -ESHUTDOWN); break; case DWC3_REQUEST_STATUS_DEQUEUED: dwc3_gadget_giveback(dep, req, -ECONNRESET); break; case DWC3_REQUEST_STATUS_STALLED: dwc3_gadget_giveback(dep, req, -EPIPE); break; default: dev_err(dwc->dev, "request cancelled with wrong reason:%d\n", req->status); dwc3_gadget_giveback(dep, req, -ECONNRESET); break; } } } static int dwc3_gadget_ep_dequeue(struct usb_ep *ep, struct usb_request *request) { struct dwc3_request *req = to_dwc3_request(request); struct dwc3_request *r = NULL; struct dwc3_ep *dep = to_dwc3_ep(ep); struct dwc3 *dwc = dep->dwc; unsigned long flags; int ret = 0; trace_dwc3_ep_dequeue(req); spin_lock_irqsave(&dwc->lock, flags); list_for_each_entry(r, &dep->cancelled_list, list) { if (r == req) goto out; } list_for_each_entry(r, &dep->pending_list, list) { if (r == req) { dwc3_gadget_giveback(dep, req, -ECONNRESET); goto out; } } list_for_each_entry(r, &dep->started_list, list) { if (r == req) { struct dwc3_request *t; /* wait until it is processed */ dwc3_stop_active_transfer(dep, true, true); /* * Remove any started request if the transfer is * cancelled. */ list_for_each_entry_safe(r, t, &dep->started_list, list) dwc3_gadget_move_cancelled_request(r, DWC3_REQUEST_STATUS_DEQUEUED); dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE; goto out; } } dev_err(dwc->dev, "request %pK was not queued to %s\n", request, ep->name); ret = -EINVAL; out: spin_unlock_irqrestore(&dwc->lock, flags); return ret; } int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol) { struct dwc3_gadget_ep_cmd_params params; struct dwc3 *dwc = dep->dwc; struct dwc3_request *req; struct dwc3_request *tmp; int ret; if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) { dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name); return -EINVAL; } memset(&params, 0x00, sizeof(params)); if (value) { struct dwc3_trb *trb; unsigned int transfer_in_flight; unsigned int started; if (dep->number > 1) trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue); else trb = &dwc->ep0_trb[dep->trb_enqueue]; transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO; started = !list_empty(&dep->started_list); if (!protocol && ((dep->direction && transfer_in_flight) || (!dep->direction && started))) { return -EAGAIN; } ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL, &params); if (ret) dev_err(dwc->dev, "failed to set STALL on %s\n", dep->name); else dep->flags |= DWC3_EP_STALL; } else { /* * Don't issue CLEAR_STALL command to control endpoints. The * controller automatically clears the STALL when it receives * the SETUP token. */ if (dep->number <= 1) { dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE); return 0; } dwc3_stop_active_transfer(dep, true, true); list_for_each_entry_safe(req, tmp, &dep->started_list, list) dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_STALLED); if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) { dep->flags |= DWC3_EP_PENDING_CLEAR_STALL; return 0; } dwc3_gadget_ep_cleanup_cancelled_requests(dep); ret = dwc3_send_clear_stall_ep_cmd(dep); if (ret) { dev_err(dwc->dev, "failed to clear STALL on %s\n", dep->name); return ret; } dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE); if ((dep->flags & DWC3_EP_DELAY_START) && !usb_endpoint_xfer_isoc(dep->endpoint.desc)) __dwc3_gadget_kick_transfer(dep); dep->flags &= ~DWC3_EP_DELAY_START; } return ret; } static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value) { struct dwc3_ep *dep = to_dwc3_ep(ep); struct dwc3 *dwc = dep->dwc; unsigned long flags; int ret; spin_lock_irqsave(&dwc->lock, flags); ret = __dwc3_gadget_ep_set_halt(dep, value, false); spin_unlock_irqrestore(&dwc->lock, flags); return ret; } static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep) { struct dwc3_ep *dep = to_dwc3_ep(ep); struct dwc3 *dwc = dep->dwc; unsigned long flags; int ret; spin_lock_irqsave(&dwc->lock, flags); dep->flags |= DWC3_EP_WEDGE; if (dep->number == 0 || dep->number == 1) ret = __dwc3_gadget_ep0_set_halt(ep, 1); else ret = __dwc3_gadget_ep_set_halt(dep, 1, false); spin_unlock_irqrestore(&dwc->lock, flags); return ret; } /* -------------------------------------------------------------------------- */ static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bmAttributes = USB_ENDPOINT_XFER_CONTROL, }; static const struct usb_ep_ops dwc3_gadget_ep0_ops = { .enable = dwc3_gadget_ep0_enable, .disable = dwc3_gadget_ep0_disable, .alloc_request = dwc3_gadget_ep_alloc_request, .free_request = dwc3_gadget_ep_free_request, .queue = dwc3_gadget_ep0_queue, .dequeue = dwc3_gadget_ep_dequeue, .set_halt = dwc3_gadget_ep0_set_halt, .set_wedge = dwc3_gadget_ep_set_wedge, }; static const struct usb_ep_ops dwc3_gadget_ep_ops = { .enable = dwc3_gadget_ep_enable, .disable = dwc3_gadget_ep_disable, .alloc_request = dwc3_gadget_ep_alloc_request, .free_request = dwc3_gadget_ep_free_request, .queue = dwc3_gadget_ep_queue, .dequeue = dwc3_gadget_ep_dequeue, .set_halt = dwc3_gadget_ep_set_halt, .set_wedge = dwc3_gadget_ep_set_wedge, }; /* -------------------------------------------------------------------------- */ static int dwc3_gadget_get_frame(struct usb_gadget *g) { struct dwc3 *dwc = gadget_to_dwc(g); return __dwc3_gadget_get_frame(dwc); } static int __dwc3_gadget_wakeup(struct dwc3 *dwc) { int retries; int ret; u32 reg; u8 link_state; /* * According to the Databook Remote wakeup request should * be issued only when the device is in early suspend state. * * We can check that via USB Link State bits in DSTS register. */ reg = dwc3_readl(dwc->regs, DWC3_DSTS); link_state = DWC3_DSTS_USBLNKST(reg); switch (link_state) { case DWC3_LINK_STATE_RESET: case DWC3_LINK_STATE_RX_DET: /* in HS, means Early Suspend */ case DWC3_LINK_STATE_U3: /* in HS, means SUSPEND */ case DWC3_LINK_STATE_U2: /* in HS, means Sleep (L1) */ case DWC3_LINK_STATE_U1: case DWC3_LINK_STATE_RESUME: break; default: return -EINVAL; } ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV); if (ret < 0) { dev_err(dwc->dev, "failed to put link in Recovery\n"); return ret; } /* Recent versions do this automatically */ if (DWC3_VER_IS_PRIOR(DWC3, 194A)) { /* write zeroes to Link Change Request */ reg = dwc3_readl(dwc->regs, DWC3_DCTL); reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK; dwc3_writel(dwc->regs, DWC3_DCTL, reg); } /* poll until Link State changes to ON */ retries = 20000; while (retries--) { reg = dwc3_readl(dwc->regs, DWC3_DSTS); /* in HS, means ON */ if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0) break; } if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) { dev_err(dwc->dev, "failed to send remote wakeup\n"); return -EINVAL; } return 0; } static int dwc3_gadget_wakeup(struct usb_gadget *g) { struct dwc3 *dwc = gadget_to_dwc(g); unsigned long flags; int ret; spin_lock_irqsave(&dwc->lock, flags); ret = __dwc3_gadget_wakeup(dwc); spin_unlock_irqrestore(&dwc->lock, flags); return ret; } static int dwc3_gadget_set_selfpowered(struct usb_gadget *g, int is_selfpowered) { struct dwc3 *dwc = gadget_to_dwc(g); unsigned long flags; spin_lock_irqsave(&dwc->lock, flags); g->is_selfpowered = !!is_selfpowered; spin_unlock_irqrestore(&dwc->lock, flags); return 0; } static void dwc3_stop_active_transfers(struct dwc3 *dwc) { u32 epnum; for (epnum = 2; epnum < dwc->num_eps; epnum++) { struct dwc3_ep *dep; dep = dwc->eps[epnum]; if (!dep) continue; dwc3_remove_requests(dwc, dep); } } static void __dwc3_gadget_set_ssp_rate(struct dwc3 *dwc) { enum usb_ssp_rate ssp_rate = dwc->gadget_ssp_rate; u32 reg; if (ssp_rate == USB_SSP_GEN_UNKNOWN) ssp_rate = dwc->max_ssp_rate; reg = dwc3_readl(dwc->regs, DWC3_DCFG); reg &= ~DWC3_DCFG_SPEED_MASK; reg &= ~DWC3_DCFG_NUMLANES(~0); if (ssp_rate == USB_SSP_GEN_1x2) reg |= DWC3_DCFG_SUPERSPEED; else if (dwc->max_ssp_rate != USB_SSP_GEN_1x2) reg |= DWC3_DCFG_SUPERSPEED_PLUS; if (ssp_rate != USB_SSP_GEN_2x1 && dwc->max_ssp_rate != USB_SSP_GEN_2x1) reg |= DWC3_DCFG_NUMLANES(1); dwc3_writel(dwc->regs, DWC3_DCFG, reg); } static void __dwc3_gadget_set_speed(struct dwc3 *dwc) { enum usb_device_speed speed; u32 reg; speed = dwc->gadget_max_speed; if (speed == USB_SPEED_UNKNOWN || speed > dwc->maximum_speed) speed = dwc->maximum_speed; if (speed == USB_SPEED_SUPER_PLUS && DWC3_IP_IS(DWC32)) { __dwc3_gadget_set_ssp_rate(dwc); return; } reg = dwc3_readl(dwc->regs, DWC3_DCFG); reg &= ~(DWC3_DCFG_SPEED_MASK); /* * WORKAROUND: DWC3 revision < 2.20a have an issue * which would cause metastability state on Run/Stop * bit if we try to force the IP to USB2-only mode. * * Because of that, we cannot configure the IP to any * speed other than the SuperSpeed * * Refers to: * * STAR#9000525659: Clock Domain Crossing on DCTL in * USB 2.0 Mode */ if (DWC3_VER_IS_PRIOR(DWC3, 220A) && !dwc->dis_metastability_quirk) { reg |= DWC3_DCFG_SUPERSPEED; } else { switch (speed) { case USB_SPEED_FULL: reg |= DWC3_DCFG_FULLSPEED; break; case USB_SPEED_HIGH: reg |= DWC3_DCFG_HIGHSPEED; break; case USB_SPEED_SUPER: reg |= DWC3_DCFG_SUPERSPEED; break; case USB_SPEED_SUPER_PLUS: if (DWC3_IP_IS(DWC3)) reg |= DWC3_DCFG_SUPERSPEED; else reg |= DWC3_DCFG_SUPERSPEED_PLUS; break; default: dev_err(dwc->dev, "invalid speed (%d)\n", speed); if (DWC3_IP_IS(DWC3)) reg |= DWC3_DCFG_SUPERSPEED; else reg |= DWC3_DCFG_SUPERSPEED_PLUS; } } if (DWC3_IP_IS(DWC32) && speed > USB_SPEED_UNKNOWN && speed < USB_SPEED_SUPER_PLUS) reg &= ~DWC3_DCFG_NUMLANES(~0); dwc3_writel(dwc->regs, DWC3_DCFG, reg); } static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on, int suspend) { u32 reg; u32 timeout = 500; if (pm_runtime_suspended(dwc->dev)) return 0; reg = dwc3_readl(dwc->regs, DWC3_DCTL); if (is_on) { if (DWC3_VER_IS_WITHIN(DWC3, ANY, 187A)) { reg &= ~DWC3_DCTL_TRGTULST_MASK; reg |= DWC3_DCTL_TRGTULST_RX_DET; } if (!DWC3_VER_IS_PRIOR(DWC3, 194A)) reg &= ~DWC3_DCTL_KEEP_CONNECT; reg |= DWC3_DCTL_RUN_STOP; if (dwc->has_hibernation) reg |= DWC3_DCTL_KEEP_CONNECT; __dwc3_gadget_set_speed(dwc); dwc->pullups_connected = true; } else { reg &= ~DWC3_DCTL_RUN_STOP; if (dwc->has_hibernation && !suspend) reg &= ~DWC3_DCTL_KEEP_CONNECT; dwc->pullups_connected = false; } dwc3_gadget_dctl_write_safe(dwc, reg); do { reg = dwc3_readl(dwc->regs, DWC3_DSTS); reg &= DWC3_DSTS_DEVCTRLHLT; } while (--timeout && !(!is_on ^ !reg)); if (!timeout) return -ETIMEDOUT; return 0; } static void dwc3_gadget_disable_irq(struct dwc3 *dwc); static void __dwc3_gadget_stop(struct dwc3 *dwc); static int __dwc3_gadget_start(struct dwc3 *dwc); static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on) { struct dwc3 *dwc = gadget_to_dwc(g); unsigned long flags; int ret; is_on = !!is_on; /* * Per databook, when we want to stop the gadget, if a control transfer * is still in process, complete it and get the core into setup phase. */ if (!is_on && dwc->ep0state != EP0_SETUP_PHASE) { reinit_completion(&dwc->ep0_in_setup); ret = wait_for_completion_timeout(&dwc->ep0_in_setup, msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT)); if (ret == 0) dev_warn(dwc->dev, "timed out waiting for SETUP phase\n"); } /* * Avoid issuing a runtime resume if the device is already in the * suspended state during gadget disconnect. DWC3 gadget was already * halted/stopped during runtime suspend. */ if (!is_on) { pm_runtime_barrier(dwc->dev); if (pm_runtime_suspended(dwc->dev)) return 0; } /* * Check the return value for successful resume, or error. For a * successful resume, the DWC3 runtime PM resume routine will handle * the run stop sequence, so avoid duplicate operations here. */ ret = pm_runtime_get_sync(dwc->dev); if (!ret || ret < 0) { pm_runtime_put(dwc->dev); return 0; } /* * Synchronize and disable any further event handling while controller * is being enabled/disabled. */ disable_irq(dwc->irq_gadget); spin_lock_irqsave(&dwc->lock, flags); if (!is_on) { u32 count; dwc->connected = false; /* * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a * Section 4.1.8 Table 4-7, it states that for a device-initiated * disconnect, the SW needs to ensure that it sends "a DEPENDXFER * command for any active transfers" before clearing the RunStop * bit. */ dwc3_stop_active_transfers(dwc); __dwc3_gadget_stop(dwc); /* * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a * Section 1.3.4, it mentions that for the DEVCTRLHLT bit, the * "software needs to acknowledge the events that are generated * (by writing to GEVNTCOUNTn) while it is waiting for this bit * to be set to '1'." */ count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0)); count &= DWC3_GEVNTCOUNT_MASK; if (count > 0) { dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count); dwc->ev_buf->lpos = (dwc->ev_buf->lpos + count) % dwc->ev_buf->length; } } else { __dwc3_gadget_start(dwc); } ret = dwc3_gadget_run_stop(dwc, is_on, false); spin_unlock_irqrestore(&dwc->lock, flags); enable_irq(dwc->irq_gadget); pm_runtime_put(dwc->dev); return ret; } static void dwc3_gadget_enable_irq(struct dwc3 *dwc) { u32 reg; /* Enable all but Start and End of Frame IRQs */ reg = (DWC3_DEVTEN_EVNTOVERFLOWEN | DWC3_DEVTEN_CMDCMPLTEN | DWC3_DEVTEN_ERRTICERREN | DWC3_DEVTEN_WKUPEVTEN | DWC3_DEVTEN_CONNECTDONEEN | DWC3_DEVTEN_USBRSTEN | DWC3_DEVTEN_DISCONNEVTEN); if (DWC3_VER_IS_PRIOR(DWC3, 250A)) reg |= DWC3_DEVTEN_ULSTCNGEN; /* On 2.30a and above this bit enables U3/L2-L1 Suspend Events */ if (!DWC3_VER_IS_PRIOR(DWC3, 230A)) reg |= DWC3_DEVTEN_U3L2L1SUSPEN; dwc3_writel(dwc->regs, DWC3_DEVTEN, reg); } static void dwc3_gadget_disable_irq(struct dwc3 *dwc) { /* mask all interrupts */ dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00); } static irqreturn_t dwc3_interrupt(int irq, void *_dwc); static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc); /** * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG * @dwc: pointer to our context structure * * The following looks like complex but it's actually very simple. In order to * calculate the number of packets we can burst at once on OUT transfers, we're * gonna use RxFIFO size. * * To calculate RxFIFO size we need two numbers: * MDWIDTH = size, in bits, of the internal memory bus * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits) * * Given these two numbers, the formula is simple: * * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16; * * 24 bytes is for 3x SETUP packets * 16 bytes is a clock domain crossing tolerance * * Given RxFIFO Size, NUMP = RxFIFOSize / 1024; */ static void dwc3_gadget_setup_nump(struct dwc3 *dwc) { u32 ram2_depth; u32 mdwidth; u32 nump; u32 reg; ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7); mdwidth = dwc3_mdwidth(dwc); nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024; nump = min_t(u32, nump, 16); /* update NumP */ reg = dwc3_readl(dwc->regs, DWC3_DCFG); reg &= ~DWC3_DCFG_NUMP_MASK; reg |= nump << DWC3_DCFG_NUMP_SHIFT; dwc3_writel(dwc->regs, DWC3_DCFG, reg); } static int __dwc3_gadget_start(struct dwc3 *dwc) { struct dwc3_ep *dep; int ret = 0; u32 reg; /* * Use IMOD if enabled via dwc->imod_interval. Otherwise, if * the core supports IMOD, disable it. */ if (dwc->imod_interval) { dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval); dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB); } else if (dwc3_has_imod(dwc)) { dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0); } /* * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP * field instead of letting dwc3 itself calculate that automatically. * * This way, we maximize the chances that we'll be able to get several * bursts of data without going through any sort of endpoint throttling. */ reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG); if (DWC3_IP_IS(DWC3)) reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL; else reg &= ~DWC31_GRXTHRCFG_PKTCNTSEL; dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg); dwc3_gadget_setup_nump(dwc); /* * Currently the controller handles single stream only. So, Ignore * Packet Pending bit for stream selection and don't search for another * stream if the host sends Data Packet with PP=0 (for OUT direction) or * ACK with NumP=0 and PP=0 (for IN direction). This slightly improves * the stream performance. */ reg = dwc3_readl(dwc->regs, DWC3_DCFG); reg |= DWC3_DCFG_IGNSTRMPP; dwc3_writel(dwc->regs, DWC3_DCFG, reg); /* Start with SuperSpeed Default */ dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512); dep = dwc->eps[0]; ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT); if (ret) { dev_err(dwc->dev, "failed to enable %s\n", dep->name); goto err0; } dep = dwc->eps[1]; ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT); if (ret) { dev_err(dwc->dev, "failed to enable %s\n", dep->name); goto err1; } /* begin to receive SETUP packets */ dwc->ep0state = EP0_SETUP_PHASE; dwc->link_state = DWC3_LINK_STATE_SS_DIS; dwc->delayed_status = false; dwc3_ep0_out_start(dwc); dwc3_gadget_enable_irq(dwc); return 0; err1: __dwc3_gadget_ep_disable(dwc->eps[0]); err0: return ret; } static int dwc3_gadget_start(struct usb_gadget *g, struct usb_gadget_driver *driver) { struct dwc3 *dwc = gadget_to_dwc(g); unsigned long flags; int ret; int irq; irq = dwc->irq_gadget; ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt, IRQF_SHARED, "dwc3", dwc->ev_buf); if (ret) { dev_err(dwc->dev, "failed to request irq #%d --> %d\n", irq, ret); return ret; } spin_lock_irqsave(&dwc->lock, flags); dwc->gadget_driver = driver; spin_unlock_irqrestore(&dwc->lock, flags); return 0; } static void __dwc3_gadget_stop(struct dwc3 *dwc) { dwc3_gadget_disable_irq(dwc); __dwc3_gadget_ep_disable(dwc->eps[0]); __dwc3_gadget_ep_disable(dwc->eps[1]); } static int dwc3_gadget_stop(struct usb_gadget *g) { struct dwc3 *dwc = gadget_to_dwc(g); unsigned long flags; spin_lock_irqsave(&dwc->lock, flags); dwc->gadget_driver = NULL; dwc->max_cfg_eps = 0; spin_unlock_irqrestore(&dwc->lock, flags); free_irq(dwc->irq_gadget, dwc->ev_buf); return 0; } static void dwc3_gadget_config_params(struct usb_gadget *g, struct usb_dcd_config_params *params) { struct dwc3 *dwc = gadget_to_dwc(g); params->besl_baseline = USB_DEFAULT_BESL_UNSPECIFIED; params->besl_deep = USB_DEFAULT_BESL_UNSPECIFIED; /* Recommended BESL */ if (!dwc->dis_enblslpm_quirk) { /* * If the recommended BESL baseline is 0 or if the BESL deep is * less than 2, Microsoft's Windows 10 host usb stack will issue * a usb reset immediately after it receives the extended BOS * descriptor and the enumeration will fail. To maintain * compatibility with the Windows' usb stack, let's set the * recommended BESL baseline to 1 and clamp the BESL deep to be * within 2 to 15. */ params->besl_baseline = 1; if (dwc->is_utmi_l1_suspend) params->besl_deep = clamp_t(u8, dwc->hird_threshold, 2, 15); } /* U1 Device exit Latency */ if (dwc->dis_u1_entry_quirk) params->bU1devExitLat = 0; else params->bU1devExitLat = DWC3_DEFAULT_U1_DEV_EXIT_LAT; /* U2 Device exit Latency */ if (dwc->dis_u2_entry_quirk) params->bU2DevExitLat = 0; else params->bU2DevExitLat = cpu_to_le16(DWC3_DEFAULT_U2_DEV_EXIT_LAT); } static void dwc3_gadget_set_speed(struct usb_gadget *g, enum usb_device_speed speed) { struct dwc3 *dwc = gadget_to_dwc(g); unsigned long flags; spin_lock_irqsave(&dwc->lock, flags); dwc->gadget_max_speed = speed; spin_unlock_irqrestore(&dwc->lock, flags); } static void dwc3_gadget_set_ssp_rate(struct usb_gadget *g, enum usb_ssp_rate rate) { struct dwc3 *dwc = gadget_to_dwc(g); unsigned long flags; spin_lock_irqsave(&dwc->lock, flags); dwc->gadget_max_speed = USB_SPEED_SUPER_PLUS; dwc->gadget_ssp_rate = rate; spin_unlock_irqrestore(&dwc->lock, flags); } static int dwc3_gadget_vbus_draw(struct usb_gadget *g, unsigned int mA) { struct dwc3 *dwc = gadget_to_dwc(g); union power_supply_propval val = {0}; int ret; if (dwc->usb2_phy) return usb_phy_set_power(dwc->usb2_phy, mA); if (!dwc->usb_psy) return -EOPNOTSUPP; val.intval = 1000 * mA; ret = power_supply_set_property(dwc->usb_psy, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, &val); return ret; } /** * dwc3_gadget_check_config - ensure dwc3 can support the USB configuration * @g: pointer to the USB gadget * * Used to record the maximum number of endpoints being used in a USB composite * device. (across all configurations) This is to be used in the calculation * of the TXFIFO sizes when resizing internal memory for individual endpoints. * It will help ensured that the resizing logic reserves enough space for at * least one max packet. */ static int dwc3_gadget_check_config(struct usb_gadget *g) { struct dwc3 *dwc = gadget_to_dwc(g); struct usb_ep *ep; int fifo_size = 0; int ram1_depth; int ep_num = 0; if (!dwc->do_fifo_resize) return 0; list_for_each_entry(ep, &g->ep_list, ep_list) { /* Only interested in the IN endpoints */ if (ep->claimed && (ep->address & USB_DIR_IN)) ep_num++; } if (ep_num <= dwc->max_cfg_eps) return 0; /* Update the max number of eps in the composition */ dwc->max_cfg_eps = ep_num; fifo_size = dwc3_gadget_calc_tx_fifo_size(dwc, dwc->max_cfg_eps); /* Based on the equation, increment by one for every ep */ fifo_size += dwc->max_cfg_eps; /* Check if we can fit a single fifo per endpoint */ ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7); if (fifo_size > ram1_depth) return -ENOMEM; return 0; } static void dwc3_gadget_async_callbacks(struct usb_gadget *g, bool enable) { struct dwc3 *dwc = gadget_to_dwc(g); unsigned long flags; spin_lock_irqsave(&dwc->lock, flags); dwc->async_callbacks = enable; spin_unlock_irqrestore(&dwc->lock, flags); } static const struct usb_gadget_ops dwc3_gadget_ops = { .get_frame = dwc3_gadget_get_frame, .wakeup = dwc3_gadget_wakeup, .set_selfpowered = dwc3_gadget_set_selfpowered, .pullup = dwc3_gadget_pullup, .udc_start = dwc3_gadget_start, .udc_stop = dwc3_gadget_stop, .udc_set_speed = dwc3_gadget_set_speed, .udc_set_ssp_rate = dwc3_gadget_set_ssp_rate, .get_config_params = dwc3_gadget_config_params, .vbus_draw = dwc3_gadget_vbus_draw, .check_config = dwc3_gadget_check_config, .udc_async_callbacks = dwc3_gadget_async_callbacks, }; /* -------------------------------------------------------------------------- */ static int dwc3_gadget_init_control_endpoint(struct dwc3_ep *dep) { struct dwc3 *dwc = dep->dwc; usb_ep_set_maxpacket_limit(&dep->endpoint, 512); dep->endpoint.maxburst = 1; dep->endpoint.ops = &dwc3_gadget_ep0_ops; if (!dep->direction) dwc->gadget->ep0 = &dep->endpoint; dep->endpoint.caps.type_control = true; return 0; } static int dwc3_gadget_init_in_endpoint(struct dwc3_ep *dep) { struct dwc3 *dwc = dep->dwc; u32 mdwidth; int size; mdwidth = dwc3_mdwidth(dwc); /* MDWIDTH is represented in bits, we need it in bytes */ mdwidth /= 8; size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1)); if (DWC3_IP_IS(DWC3)) size = DWC3_GTXFIFOSIZ_TXFDEP(size); else size = DWC31_GTXFIFOSIZ_TXFDEP(size); /* FIFO Depth is in MDWDITH bytes. Multiply */ size *= mdwidth; /* * To meet performance requirement, a minimum TxFIFO size of 3x * MaxPacketSize is recommended for endpoints that support burst and a * minimum TxFIFO size of 2x MaxPacketSize for endpoints that don't * support burst. Use those numbers and we can calculate the max packet * limit as below. */ if (dwc->maximum_speed >= USB_SPEED_SUPER) size /= 3; else size /= 2; usb_ep_set_maxpacket_limit(&dep->endpoint, size); dep->endpoint.max_streams = 16; dep->endpoint.ops = &dwc3_gadget_ep_ops; list_add_tail(&dep->endpoint.ep_list, &dwc->gadget->ep_list); dep->endpoint.caps.type_iso = true; dep->endpoint.caps.type_bulk = true; dep->endpoint.caps.type_int = true; return dwc3_alloc_trb_pool(dep); } static int dwc3_gadget_init_out_endpoint(struct dwc3_ep *dep) { struct dwc3 *dwc = dep->dwc; u32 mdwidth; int size; mdwidth = dwc3_mdwidth(dwc); /* MDWIDTH is represented in bits, convert to bytes */ mdwidth /= 8; /* All OUT endpoints share a single RxFIFO space */ size = dwc3_readl(dwc->regs, DWC3_GRXFIFOSIZ(0)); if (DWC3_IP_IS(DWC3)) size = DWC3_GRXFIFOSIZ_RXFDEP(size); else size = DWC31_GRXFIFOSIZ_RXFDEP(size); /* FIFO depth is in MDWDITH bytes */ size *= mdwidth; /* * To meet performance requirement, a minimum recommended RxFIFO size * is defined as follow: * RxFIFO size >= (3 x MaxPacketSize) + * (3 x 8 bytes setup packets size) + (16 bytes clock crossing margin) * * Then calculate the max packet limit as below. */ size -= (3 * 8) + 16; if (size < 0) size = 0; else size /= 3; usb_ep_set_maxpacket_limit(&dep->endpoint, size); dep->endpoint.max_streams = 16; dep->endpoint.ops = &dwc3_gadget_ep_ops; list_add_tail(&dep->endpoint.ep_list, &dwc->gadget->ep_list); dep->endpoint.caps.type_iso = true; dep->endpoint.caps.type_bulk = true; dep->endpoint.caps.type_int = true; return dwc3_alloc_trb_pool(dep); } static int dwc3_gadget_init_endpoint(struct dwc3 *dwc, u8 epnum) { struct dwc3_ep *dep; bool direction = epnum & 1; int ret; u8 num = epnum >> 1; dep = kzalloc(sizeof(*dep), GFP_KERNEL); if (!dep) return -ENOMEM; dep->dwc = dwc; dep->number = epnum; dep->direction = direction; dep->regs = dwc->regs + DWC3_DEP_BASE(epnum); dwc->eps[epnum] = dep; dep->combo_num = 0; dep->start_cmd_status = 0; snprintf(dep->name, sizeof(dep->name), "ep%u%s", num, direction ? "in" : "out"); dep->endpoint.name = dep->name; if (!(dep->number > 1)) { dep->endpoint.desc = &dwc3_gadget_ep0_desc; dep->endpoint.comp_desc = NULL; } if (num == 0) ret = dwc3_gadget_init_control_endpoint(dep); else if (direction) ret = dwc3_gadget_init_in_endpoint(dep); else ret = dwc3_gadget_init_out_endpoint(dep); if (ret) return ret; dep->endpoint.caps.dir_in = direction; dep->endpoint.caps.dir_out = !direction; INIT_LIST_HEAD(&dep->pending_list); INIT_LIST_HEAD(&dep->started_list); INIT_LIST_HEAD(&dep->cancelled_list); dwc3_debugfs_create_endpoint_dir(dep); return 0; } static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total) { u8 epnum; INIT_LIST_HEAD(&dwc->gadget->ep_list); for (epnum = 0; epnum < total; epnum++) { int ret; ret = dwc3_gadget_init_endpoint(dwc, epnum); if (ret) return ret; } return 0; } static void dwc3_gadget_free_endpoints(struct dwc3 *dwc) { struct dwc3_ep *dep; u8 epnum; for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) { dep = dwc->eps[epnum]; if (!dep) continue; /* * Physical endpoints 0 and 1 are special; they form the * bi-directional USB endpoint 0. * * For those two physical endpoints, we don't allocate a TRB * pool nor do we add them the endpoints list. Due to that, we * shouldn't do these two operations otherwise we would end up * with all sorts of bugs when removing dwc3.ko. */ if (epnum != 0 && epnum != 1) { dwc3_free_trb_pool(dep); list_del(&dep->endpoint.ep_list); } debugfs_remove_recursive(debugfs_lookup(dep->name, debugfs_lookup(dev_name(dep->dwc->dev), usb_debug_root))); kfree(dep); } } /* -------------------------------------------------------------------------- */ static int dwc3_gadget_ep_reclaim_completed_trb(struct dwc3_ep *dep, struct dwc3_request *req, struct dwc3_trb *trb, const struct dwc3_event_depevt *event, int status, int chain) { unsigned int count; dwc3_ep_inc_deq(dep); trace_dwc3_complete_trb(dep, trb); req->num_trbs--; /* * If we're in the middle of series of chained TRBs and we * receive a short transfer along the way, DWC3 will skip * through all TRBs including the last TRB in the chain (the * where CHN bit is zero. DWC3 will also avoid clearing HWO * bit and SW has to do it manually. * * We're going to do that here to avoid problems of HW trying * to use bogus TRBs for transfers. */ if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO)) trb->ctrl &= ~DWC3_TRB_CTRL_HWO; /* * For isochronous transfers, the first TRB in a service interval must * have the Isoc-First type. Track and report its interval frame number. */ if (usb_endpoint_xfer_isoc(dep->endpoint.desc) && (trb->ctrl & DWC3_TRBCTL_ISOCHRONOUS_FIRST)) { unsigned int frame_number; frame_number = DWC3_TRB_CTRL_GET_SID_SOFN(trb->ctrl); frame_number &= ~(dep->interval - 1); req->request.frame_number = frame_number; } /* * We use bounce buffer for requests that needs extra TRB or OUT ZLP. If * this TRB points to the bounce buffer address, it's a MPS alignment * TRB. Don't add it to req->remaining calculation. */ if (trb->bpl == lower_32_bits(dep->dwc->bounce_addr) && trb->bph == upper_32_bits(dep->dwc->bounce_addr)) { trb->ctrl &= ~DWC3_TRB_CTRL_HWO; return 1; } count = trb->size & DWC3_TRB_SIZE_MASK; req->remaining += count; if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN) return 1; if (event->status & DEPEVT_STATUS_SHORT && !chain) return 1; if ((trb->ctrl & DWC3_TRB_CTRL_IOC) || (trb->ctrl & DWC3_TRB_CTRL_LST)) return 1; return 0; } static int dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep *dep, struct dwc3_request *req, const struct dwc3_event_depevt *event, int status) { struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue]; struct scatterlist *sg = req->sg; struct scatterlist *s; unsigned int num_queued = req->num_queued_sgs; unsigned int i; int ret = 0; for_each_sg(sg, s, num_queued, i) { trb = &dep->trb_pool[dep->trb_dequeue]; req->sg = sg_next(s); req->num_queued_sgs--; ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb, event, status, true); if (ret) break; } return ret; } static int dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep *dep, struct dwc3_request *req, const struct dwc3_event_depevt *event, int status) { struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue]; return dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb, event, status, false); } static bool dwc3_gadget_ep_request_completed(struct dwc3_request *req) { return req->num_pending_sgs == 0 && req->num_queued_sgs == 0; } static int dwc3_gadget_ep_cleanup_completed_request(struct dwc3_ep *dep, const struct dwc3_event_depevt *event, struct dwc3_request *req, int status) { int ret; if (req->request.num_mapped_sgs) ret = dwc3_gadget_ep_reclaim_trb_sg(dep, req, event, status); else ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event, status); req->request.actual = req->request.length - req->remaining; if (!dwc3_gadget_ep_request_completed(req)) goto out; if (req->needs_extra_trb) { ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event, status); req->needs_extra_trb = false; } dwc3_gadget_giveback(dep, req, status); out: return ret; } static void dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep *dep, const struct dwc3_event_depevt *event, int status) { struct dwc3_request *req; struct dwc3_request *tmp; list_for_each_entry_safe(req, tmp, &dep->started_list, list) { int ret; ret = dwc3_gadget_ep_cleanup_completed_request(dep, event, req, status); if (ret) break; } } static bool dwc3_gadget_ep_should_continue(struct dwc3_ep *dep) { struct dwc3_request *req; struct dwc3 *dwc = dep->dwc; if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) return false; if (!list_empty(&dep->pending_list)) return true; /* * We only need to check the first entry of the started list. We can * assume the completed requests are removed from the started list. */ req = next_request(&dep->started_list); if (!req) return false; return !dwc3_gadget_ep_request_completed(req); } static void dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep *dep, const struct dwc3_event_depevt *event) { dep->frame_number = event->parameters; } static bool dwc3_gadget_endpoint_trbs_complete(struct dwc3_ep *dep, const struct dwc3_event_depevt *event, int status) { struct dwc3 *dwc = dep->dwc; bool no_started_trb = true; dwc3_gadget_ep_cleanup_completed_requests(dep, event, status); if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) goto out; if (usb_endpoint_xfer_isoc(dep->endpoint.desc) && list_empty(&dep->started_list) && (list_empty(&dep->pending_list) || status == -EXDEV)) dwc3_stop_active_transfer(dep, true, true); else if (dwc3_gadget_ep_should_continue(dep)) if (__dwc3_gadget_kick_transfer(dep) == 0) no_started_trb = false; out: /* * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround. * See dwc3_gadget_linksts_change_interrupt() for 1st half. */ if (DWC3_VER_IS_PRIOR(DWC3, 183A)) { u32 reg; int i; for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) { dep = dwc->eps[i]; if (!(dep->flags & DWC3_EP_ENABLED)) continue; if (!list_empty(&dep->started_list)) return no_started_trb; } reg = dwc3_readl(dwc->regs, DWC3_DCTL); reg |= dwc->u1u2; dwc3_writel(dwc->regs, DWC3_DCTL, reg); dwc->u1u2 = 0; } return no_started_trb; } static void dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep *dep, const struct dwc3_event_depevt *event) { int status = 0; if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) dwc3_gadget_endpoint_frame_from_event(dep, event); if (event->status & DEPEVT_STATUS_BUSERR) status = -ECONNRESET; if (event->status & DEPEVT_STATUS_MISSED_ISOC) status = -EXDEV; dwc3_gadget_endpoint_trbs_complete(dep, event, status); } static void dwc3_gadget_endpoint_transfer_complete(struct dwc3_ep *dep, const struct dwc3_event_depevt *event) { int status = 0; dep->flags &= ~DWC3_EP_TRANSFER_STARTED; if (event->status & DEPEVT_STATUS_BUSERR) status = -ECONNRESET; if (dwc3_gadget_endpoint_trbs_complete(dep, event, status)) dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE; } static void dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep *dep, const struct dwc3_event_depevt *event) { dwc3_gadget_endpoint_frame_from_event(dep, event); /* * The XferNotReady event is generated only once before the endpoint * starts. It will be generated again when END_TRANSFER command is * issued. For some controller versions, the XferNotReady event may be * generated while the END_TRANSFER command is still in process. Ignore * it and wait for the next XferNotReady event after the command is * completed. */ if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) return; (void) __dwc3_gadget_start_isoc(dep); } static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep, const struct dwc3_event_depevt *event) { u8 cmd = DEPEVT_PARAMETER_CMD(event->parameters); if (cmd != DWC3_DEPCMD_ENDTRANSFER) return; dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING; dep->flags &= ~DWC3_EP_TRANSFER_STARTED; dwc3_gadget_ep_cleanup_cancelled_requests(dep); if (dep->flags & DWC3_EP_PENDING_CLEAR_STALL) { struct dwc3 *dwc = dep->dwc; dep->flags &= ~DWC3_EP_PENDING_CLEAR_STALL; if (dwc3_send_clear_stall_ep_cmd(dep)) { struct usb_ep *ep0 = &dwc->eps[0]->endpoint; dev_err(dwc->dev, "failed to clear STALL on %s\n", dep->name); if (dwc->delayed_status) __dwc3_gadget_ep0_set_halt(ep0, 1); return; } dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE); if (dwc->delayed_status) dwc3_ep0_send_delayed_status(dwc); } if ((dep->flags & DWC3_EP_DELAY_START) && !usb_endpoint_xfer_isoc(dep->endpoint.desc)) __dwc3_gadget_kick_transfer(dep); dep->flags &= ~DWC3_EP_DELAY_START; } static void dwc3_gadget_endpoint_stream_event(struct dwc3_ep *dep, const struct dwc3_event_depevt *event) { struct dwc3 *dwc = dep->dwc; if (event->status == DEPEVT_STREAMEVT_FOUND) { dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED; goto out; } /* Note: NoStream rejection event param value is 0 and not 0xFFFF */ switch (event->parameters) { case DEPEVT_STREAM_PRIME: /* * If the host can properly transition the endpoint state from * idle to prime after a NoStream rejection, there's no need to * force restarting the endpoint to reinitiate the stream. To * simplify the check, assume the host follows the USB spec if * it primed the endpoint more than once. */ if (dep->flags & DWC3_EP_FORCE_RESTART_STREAM) { if (dep->flags & DWC3_EP_FIRST_STREAM_PRIMED) dep->flags &= ~DWC3_EP_FORCE_RESTART_STREAM; else dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED; } break; case DEPEVT_STREAM_NOSTREAM: if ((dep->flags & DWC3_EP_IGNORE_NEXT_NOSTREAM) || !(dep->flags & DWC3_EP_FORCE_RESTART_STREAM) || !(dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)) break; /* * If the host rejects a stream due to no active stream, by the * USB and xHCI spec, the endpoint will be put back to idle * state. When the host is ready (buffer added/updated), it will * prime the endpoint to inform the usb device controller. This * triggers the device controller to issue ERDY to restart the * stream. However, some hosts don't follow this and keep the * endpoint in the idle state. No prime will come despite host * streams are updated, and the device controller will not be * triggered to generate ERDY to move the next stream data. To * workaround this and maintain compatibility with various * hosts, force to reinitate the stream until the host is ready * instead of waiting for the host to prime the endpoint. */ if (DWC3_VER_IS_WITHIN(DWC32, 100A, ANY)) { unsigned int cmd = DWC3_DGCMD_SET_ENDPOINT_PRIME; dwc3_send_gadget_generic_command(dwc, cmd, dep->number); } else { dep->flags |= DWC3_EP_DELAY_START; dwc3_stop_active_transfer(dep, true, true); return; } break; } out: dep->flags &= ~DWC3_EP_IGNORE_NEXT_NOSTREAM; } static void dwc3_endpoint_interrupt(struct dwc3 *dwc, const struct dwc3_event_depevt *event) { struct dwc3_ep *dep; u8 epnum = event->endpoint_number; dep = dwc->eps[epnum]; if (!(dep->flags & DWC3_EP_ENABLED)) { if (!(dep->flags & DWC3_EP_TRANSFER_STARTED)) return; /* Handle only EPCMDCMPLT when EP disabled */ if (event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT) return; } if (epnum == 0 || epnum == 1) { dwc3_ep0_interrupt(dwc, event); return; } switch (event->endpoint_event) { case DWC3_DEPEVT_XFERINPROGRESS: dwc3_gadget_endpoint_transfer_in_progress(dep, event); break; case DWC3_DEPEVT_XFERNOTREADY: dwc3_gadget_endpoint_transfer_not_ready(dep, event); break; case DWC3_DEPEVT_EPCMDCMPLT: dwc3_gadget_endpoint_command_complete(dep, event); break; case DWC3_DEPEVT_XFERCOMPLETE: dwc3_gadget_endpoint_transfer_complete(dep, event); break; case DWC3_DEPEVT_STREAMEVT: dwc3_gadget_endpoint_stream_event(dep, event); break; case DWC3_DEPEVT_RXTXFIFOEVT: break; } } static void dwc3_disconnect_gadget(struct dwc3 *dwc) { if (dwc->async_callbacks && dwc->gadget_driver->disconnect) { spin_unlock(&dwc->lock); dwc->gadget_driver->disconnect(dwc->gadget); spin_lock(&dwc->lock); } } static void dwc3_suspend_gadget(struct dwc3 *dwc) { if (dwc->async_callbacks && dwc->gadget_driver->suspend) { spin_unlock(&dwc->lock); dwc->gadget_driver->suspend(dwc->gadget); spin_lock(&dwc->lock); } } static void dwc3_resume_gadget(struct dwc3 *dwc) { if (dwc->async_callbacks && dwc->gadget_driver->resume) { spin_unlock(&dwc->lock); dwc->gadget_driver->resume(dwc->gadget); spin_lock(&dwc->lock); } } static void dwc3_reset_gadget(struct dwc3 *dwc) { if (!dwc->gadget_driver) return; if (dwc->async_callbacks && dwc->gadget->speed != USB_SPEED_UNKNOWN) { spin_unlock(&dwc->lock); usb_gadget_udc_reset(dwc->gadget, dwc->gadget_driver); spin_lock(&dwc->lock); } } static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool interrupt) { struct dwc3_gadget_ep_cmd_params params; u32 cmd; int ret; if (!(dep->flags & DWC3_EP_TRANSFER_STARTED) || (dep->flags & DWC3_EP_END_TRANSFER_PENDING)) return; /* * NOTICE: We are violating what the Databook says about the * EndTransfer command. Ideally we would _always_ wait for the * EndTransfer Command Completion IRQ, but that's causing too * much trouble synchronizing between us and gadget driver. * * We have discussed this with the IP Provider and it was * suggested to giveback all requests here. * * Note also that a similar handling was tested by Synopsys * (thanks a lot Paul) and nothing bad has come out of it. * In short, what we're doing is issuing EndTransfer with * CMDIOC bit set and delay kicking transfer until the * EndTransfer command had completed. * * As of IP version 3.10a of the DWC_usb3 IP, the controller * supports a mode to work around the above limitation. The * software can poll the CMDACT bit in the DEPCMD register * after issuing a EndTransfer command. This mode is enabled * by writing GUCTL2[14]. This polling is already done in the * dwc3_send_gadget_ep_cmd() function so if the mode is * enabled, the EndTransfer command will have completed upon * returning from this function. * * This mode is NOT available on the DWC_usb31 IP. */ cmd = DWC3_DEPCMD_ENDTRANSFER; cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0; cmd |= interrupt ? DWC3_DEPCMD_CMDIOC : 0; cmd |= DWC3_DEPCMD_PARAM(dep->resource_index); memset(&params, 0, sizeof(params)); ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params); WARN_ON_ONCE(ret); dep->resource_index = 0; /* * The END_TRANSFER command will cause the controller to generate a * NoStream Event, and it's not due to the host DP NoStream rejection. * Ignore the next NoStream event. */ if (dep->stream_capable) dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM; if (!interrupt) dep->flags &= ~DWC3_EP_TRANSFER_STARTED; else dep->flags |= DWC3_EP_END_TRANSFER_PENDING; } static void dwc3_clear_stall_all_ep(struct dwc3 *dwc) { u32 epnum; for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) { struct dwc3_ep *dep; int ret; dep = dwc->eps[epnum]; if (!dep) continue; if (!(dep->flags & DWC3_EP_STALL)) continue; dep->flags &= ~DWC3_EP_STALL; ret = dwc3_send_clear_stall_ep_cmd(dep); WARN_ON_ONCE(ret); } } static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc) { int reg; dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RX_DET); reg = dwc3_readl(dwc->regs, DWC3_DCTL); reg &= ~DWC3_DCTL_INITU1ENA; reg &= ~DWC3_DCTL_INITU2ENA; dwc3_gadget_dctl_write_safe(dwc, reg); dwc3_disconnect_gadget(dwc); dwc->gadget->speed = USB_SPEED_UNKNOWN; dwc->setup_packet_pending = false; usb_gadget_set_state(dwc->gadget, USB_STATE_NOTATTACHED); dwc->connected = false; } static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc) { u32 reg; /* * Ideally, dwc3_reset_gadget() would trigger the function * drivers to stop any active transfers through ep disable. * However, for functions which defer ep disable, such as mass * storage, we will need to rely on the call to stop active * transfers here, and avoid allowing of request queuing. */ dwc->connected = false; /* * WORKAROUND: DWC3 revisions <1.88a have an issue which * would cause a missing Disconnect Event if there's a * pending Setup Packet in the FIFO. * * There's no suggested workaround on the official Bug * report, which states that "unless the driver/application * is doing any special handling of a disconnect event, * there is no functional issue". * * Unfortunately, it turns out that we _do_ some special * handling of a disconnect event, namely complete all * pending transfers, notify gadget driver of the * disconnection, and so on. * * Our suggested workaround is to follow the Disconnect * Event steps here, instead, based on a setup_packet_pending * flag. Such flag gets set whenever we have a SETUP_PENDING * status for EP0 TRBs and gets cleared on XferComplete for the * same endpoint. * * Refers to: * * STAR#9000466709: RTL: Device : Disconnect event not * generated if setup packet pending in FIFO */ if (DWC3_VER_IS_PRIOR(DWC3, 188A)) { if (dwc->setup_packet_pending) dwc3_gadget_disconnect_interrupt(dwc); } dwc3_reset_gadget(dwc); /* * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a * Section 4.1.2 Table 4-2, it states that during a USB reset, the SW * needs to ensure that it sends "a DEPENDXFER command for any active * transfers." */ dwc3_stop_active_transfers(dwc); dwc->connected = true; reg = dwc3_readl(dwc->regs, DWC3_DCTL); reg &= ~DWC3_DCTL_TSTCTRL_MASK; dwc3_gadget_dctl_write_safe(dwc, reg); dwc->test_mode = false; dwc3_clear_stall_all_ep(dwc); /* Reset device address to zero */ reg = dwc3_readl(dwc->regs, DWC3_DCFG); reg &= ~(DWC3_DCFG_DEVADDR_MASK); dwc3_writel(dwc->regs, DWC3_DCFG, reg); } static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc) { struct dwc3_ep *dep; int ret; u32 reg; u8 lanes = 1; u8 speed; reg = dwc3_readl(dwc->regs, DWC3_DSTS); speed = reg & DWC3_DSTS_CONNECTSPD; dwc->speed = speed; if (DWC3_IP_IS(DWC32)) lanes = DWC3_DSTS_CONNLANES(reg) + 1; dwc->gadget->ssp_rate = USB_SSP_GEN_UNKNOWN; /* * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed * each time on Connect Done. * * Currently we always use the reset value. If any platform * wants to set this to a different value, we need to add a * setting and update GCTL.RAMCLKSEL here. */ switch (speed) { case DWC3_DSTS_SUPERSPEED_PLUS: dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512); dwc->gadget->ep0->maxpacket = 512; dwc->gadget->speed = USB_SPEED_SUPER_PLUS; if (lanes > 1) dwc->gadget->ssp_rate = USB_SSP_GEN_2x2; else dwc->gadget->ssp_rate = USB_SSP_GEN_2x1; break; case DWC3_DSTS_SUPERSPEED: /* * WORKAROUND: DWC3 revisions <1.90a have an issue which * would cause a missing USB3 Reset event. * * In such situations, we should force a USB3 Reset * event by calling our dwc3_gadget_reset_interrupt() * routine. * * Refers to: * * STAR#9000483510: RTL: SS : USB3 reset event may * not be generated always when the link enters poll */ if (DWC3_VER_IS_PRIOR(DWC3, 190A)) dwc3_gadget_reset_interrupt(dwc); dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512); dwc->gadget->ep0->maxpacket = 512; dwc->gadget->speed = USB_SPEED_SUPER; if (lanes > 1) { dwc->gadget->speed = USB_SPEED_SUPER_PLUS; dwc->gadget->ssp_rate = USB_SSP_GEN_1x2; } break; case DWC3_DSTS_HIGHSPEED: dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64); dwc->gadget->ep0->maxpacket = 64; dwc->gadget->speed = USB_SPEED_HIGH; break; case DWC3_DSTS_FULLSPEED: dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64); dwc->gadget->ep0->maxpacket = 64; dwc->gadget->speed = USB_SPEED_FULL; break; } dwc->eps[1]->endpoint.maxpacket = dwc->gadget->ep0->maxpacket; /* Enable USB2 LPM Capability */ if (!DWC3_VER_IS_WITHIN(DWC3, ANY, 194A) && !dwc->usb2_gadget_lpm_disable && (speed != DWC3_DSTS_SUPERSPEED) && (speed != DWC3_DSTS_SUPERSPEED_PLUS)) { reg = dwc3_readl(dwc->regs, DWC3_DCFG); reg |= DWC3_DCFG_LPM_CAP; dwc3_writel(dwc->regs, DWC3_DCFG, reg); reg = dwc3_readl(dwc->regs, DWC3_DCTL); reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN); reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold | (dwc->is_utmi_l1_suspend << 4)); /* * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and * DCFG.LPMCap is set, core responses with an ACK and the * BESL value in the LPM token is less than or equal to LPM * NYET threshold. */ WARN_ONCE(DWC3_VER_IS_PRIOR(DWC3, 240A) && dwc->has_lpm_erratum, "LPM Erratum not available on dwc3 revisions < 2.40a\n"); if (dwc->has_lpm_erratum && !DWC3_VER_IS_PRIOR(DWC3, 240A)) reg |= DWC3_DCTL_NYET_THRES(dwc->lpm_nyet_threshold); dwc3_gadget_dctl_write_safe(dwc, reg); } else { if (dwc->usb2_gadget_lpm_disable) { reg = dwc3_readl(dwc->regs, DWC3_DCFG); reg &= ~DWC3_DCFG_LPM_CAP; dwc3_writel(dwc->regs, DWC3_DCFG, reg); } reg = dwc3_readl(dwc->regs, DWC3_DCTL); reg &= ~DWC3_DCTL_HIRD_THRES_MASK; dwc3_gadget_dctl_write_safe(dwc, reg); } dep = dwc->eps[0]; ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY); if (ret) { dev_err(dwc->dev, "failed to enable %s\n", dep->name); return; } dep = dwc->eps[1]; ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY); if (ret) { dev_err(dwc->dev, "failed to enable %s\n", dep->name); return; } /* * Configure PHY via GUSB3PIPECTLn if required. * * Update GTXFIFOSIZn * * In both cases reset values should be sufficient. */ } static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc) { /* * TODO take core out of low power mode when that's * implemented. */ if (dwc->async_callbacks && dwc->gadget_driver->resume) { spin_unlock(&dwc->lock); dwc->gadget_driver->resume(dwc->gadget); spin_lock(&dwc->lock); } } static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc, unsigned int evtinfo) { enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK; unsigned int pwropt; /* * WORKAROUND: DWC3 < 2.50a have an issue when configured without * Hibernation mode enabled which would show up when device detects * host-initiated U3 exit. * * In that case, device will generate a Link State Change Interrupt * from U3 to RESUME which is only necessary if Hibernation is * configured in. * * There are no functional changes due to such spurious event and we * just need to ignore it. * * Refers to: * * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation * operational mode */ pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1); if (DWC3_VER_IS_PRIOR(DWC3, 250A) && (pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) { if ((dwc->link_state == DWC3_LINK_STATE_U3) && (next == DWC3_LINK_STATE_RESUME)) { return; } } /* * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending * on the link partner, the USB session might do multiple entry/exit * of low power states before a transfer takes place. * * Due to this problem, we might experience lower throughput. The * suggested workaround is to disable DCTL[12:9] bits if we're * transitioning from U1/U2 to U0 and enable those bits again * after a transfer completes and there are no pending transfers * on any of the enabled endpoints. * * This is the first half of that workaround. * * Refers to: * * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us * core send LGO_Ux entering U0 */ if (DWC3_VER_IS_PRIOR(DWC3, 183A)) { if (next == DWC3_LINK_STATE_U0) { u32 u1u2; u32 reg; switch (dwc->link_state) { case DWC3_LINK_STATE_U1: case DWC3_LINK_STATE_U2: reg = dwc3_readl(dwc->regs, DWC3_DCTL); u1u2 = reg & (DWC3_DCTL_INITU2ENA | DWC3_DCTL_ACCEPTU2ENA | DWC3_DCTL_INITU1ENA | DWC3_DCTL_ACCEPTU1ENA); if (!dwc->u1u2) dwc->u1u2 = reg & u1u2; reg &= ~u1u2; dwc3_gadget_dctl_write_safe(dwc, reg); break; default: /* do nothing */ break; } } } switch (next) { case DWC3_LINK_STATE_U1: if (dwc->speed == USB_SPEED_SUPER) dwc3_suspend_gadget(dwc); break; case DWC3_LINK_STATE_U2: case DWC3_LINK_STATE_U3: dwc3_suspend_gadget(dwc); break; case DWC3_LINK_STATE_RESUME: dwc3_resume_gadget(dwc); break; default: /* do nothing */ break; } dwc->link_state = next; } static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc, unsigned int evtinfo) { enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK; if (dwc->link_state != next && next == DWC3_LINK_STATE_U3) dwc3_suspend_gadget(dwc); dwc->link_state = next; } static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc, unsigned int evtinfo) { unsigned int is_ss = evtinfo & BIT(4); /* * WORKAROUND: DWC3 revison 2.20a with hibernation support * have a known issue which can cause USB CV TD.9.23 to fail * randomly. * * Because of this issue, core could generate bogus hibernation * events which SW needs to ignore. * * Refers to: * * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0 * Device Fallback from SuperSpeed */ if (is_ss ^ (dwc->speed == USB_SPEED_SUPER)) return; /* enter hibernation here */ } static void dwc3_gadget_interrupt(struct dwc3 *dwc, const struct dwc3_event_devt *event) { switch (event->type) { case DWC3_DEVICE_EVENT_DISCONNECT: dwc3_gadget_disconnect_interrupt(dwc); break; case DWC3_DEVICE_EVENT_RESET: dwc3_gadget_reset_interrupt(dwc); break; case DWC3_DEVICE_EVENT_CONNECT_DONE: dwc3_gadget_conndone_interrupt(dwc); break; case DWC3_DEVICE_EVENT_WAKEUP: dwc3_gadget_wakeup_interrupt(dwc); break; case DWC3_DEVICE_EVENT_HIBER_REQ: if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation, "unexpected hibernation event\n")) break; dwc3_gadget_hibernation_interrupt(dwc, event->event_info); break; case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE: dwc3_gadget_linksts_change_interrupt(dwc, event->event_info); break; case DWC3_DEVICE_EVENT_SUSPEND: /* It changed to be suspend event for version 2.30a and above */ if (!DWC3_VER_IS_PRIOR(DWC3, 230A)) { /* * Ignore suspend event until the gadget enters into * USB_STATE_CONFIGURED state. */ if (dwc->gadget->state >= USB_STATE_CONFIGURED) dwc3_gadget_suspend_interrupt(dwc, event->event_info); } break; case DWC3_DEVICE_EVENT_SOF: case DWC3_DEVICE_EVENT_ERRATIC_ERROR: case DWC3_DEVICE_EVENT_CMD_CMPL: case DWC3_DEVICE_EVENT_OVERFLOW: break; default: dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type); } } static void dwc3_process_event_entry(struct dwc3 *dwc, const union dwc3_event *event) { trace_dwc3_event(event->raw, dwc); if (!event->type.is_devspec) dwc3_endpoint_interrupt(dwc, &event->depevt); else if (event->type.type == DWC3_EVENT_TYPE_DEV) dwc3_gadget_interrupt(dwc, &event->devt); else dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw); } static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt) { struct dwc3 *dwc = evt->dwc; irqreturn_t ret = IRQ_NONE; int left; u32 reg; left = evt->count; if (!(evt->flags & DWC3_EVENT_PENDING)) return IRQ_NONE; while (left > 0) { union dwc3_event event; event.raw = *(u32 *) (evt->cache + evt->lpos); dwc3_process_event_entry(dwc, &event); /* * FIXME we wrap around correctly to the next entry as * almost all entries are 4 bytes in size. There is one * entry which has 12 bytes which is a regular entry * followed by 8 bytes data. ATM I don't know how * things are organized if we get next to the a * boundary so I worry about that once we try to handle * that. */ evt->lpos = (evt->lpos + 4) % evt->length; left -= 4; } evt->count = 0; evt->flags &= ~DWC3_EVENT_PENDING; ret = IRQ_HANDLED; /* Unmask interrupt */ reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0)); reg &= ~DWC3_GEVNTSIZ_INTMASK; dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg); if (dwc->imod_interval) { dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB); dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval); } return ret; } static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt) { struct dwc3_event_buffer *evt = _evt; struct dwc3 *dwc = evt->dwc; unsigned long flags; irqreturn_t ret = IRQ_NONE; spin_lock_irqsave(&dwc->lock, flags); ret = dwc3_process_event_buf(evt); spin_unlock_irqrestore(&dwc->lock, flags); return ret; } static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt) { struct dwc3 *dwc = evt->dwc; u32 amount; u32 count; u32 reg; if (pm_runtime_suspended(dwc->dev)) { pm_runtime_get(dwc->dev); disable_irq_nosync(dwc->irq_gadget); dwc->pending_events = true; return IRQ_HANDLED; } /* * With PCIe legacy interrupt, test shows that top-half irq handler can * be called again after HW interrupt deassertion. Check if bottom-half * irq event handler completes before caching new event to prevent * losing events. */ if (evt->flags & DWC3_EVENT_PENDING) return IRQ_HANDLED; count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0)); count &= DWC3_GEVNTCOUNT_MASK; if (!count) return IRQ_NONE; evt->count = count; evt->flags |= DWC3_EVENT_PENDING; /* Mask interrupt */ reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0)); reg |= DWC3_GEVNTSIZ_INTMASK; dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg); amount = min(count, evt->length - evt->lpos); memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount); if (amount < count) memcpy(evt->cache, evt->buf, count - amount); dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count); return IRQ_WAKE_THREAD; } static irqreturn_t dwc3_interrupt(int irq, void *_evt) { struct dwc3_event_buffer *evt = _evt; return dwc3_check_event_buf(evt); } static int dwc3_gadget_get_irq(struct dwc3 *dwc) { struct platform_device *dwc3_pdev = to_platform_device(dwc->dev); int irq; irq = platform_get_irq_byname_optional(dwc3_pdev, "peripheral"); if (irq > 0) goto out; if (irq == -EPROBE_DEFER) goto out; irq = platform_get_irq_byname_optional(dwc3_pdev, "dwc_usb3"); if (irq > 0) goto out; if (irq == -EPROBE_DEFER) goto out; irq = platform_get_irq(dwc3_pdev, 0); if (irq > 0) goto out; if (!irq) irq = -EINVAL; out: return irq; } static void dwc_gadget_release(struct device *dev) { struct usb_gadget *gadget = container_of(dev, struct usb_gadget, dev); kfree(gadget); } /** * dwc3_gadget_init - initializes gadget related registers * @dwc: pointer to our controller context structure * * Returns 0 on success otherwise negative errno. */ int dwc3_gadget_init(struct dwc3 *dwc) { int ret; int irq; struct device *dev; irq = dwc3_gadget_get_irq(dwc); if (irq < 0) { ret = irq; goto err0; } dwc->irq_gadget = irq; dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2, &dwc->ep0_trb_addr, GFP_KERNEL); if (!dwc->ep0_trb) { dev_err(dwc->dev, "failed to allocate ep0 trb\n"); ret = -ENOMEM; goto err0; } dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL); if (!dwc->setup_buf) { ret = -ENOMEM; goto err1; } dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, &dwc->bounce_addr, GFP_KERNEL); if (!dwc->bounce) { ret = -ENOMEM; goto err2; } init_completion(&dwc->ep0_in_setup); dwc->gadget = kzalloc(sizeof(struct usb_gadget), GFP_KERNEL); if (!dwc->gadget) { ret = -ENOMEM; goto err3; } usb_initialize_gadget(dwc->sysdev, dwc->gadget, dwc_gadget_release); dev = &dwc->gadget->dev; dev->platform_data = dwc; dwc->gadget->ops = &dwc3_gadget_ops; dwc->gadget->speed = USB_SPEED_UNKNOWN; dwc->gadget->ssp_rate = USB_SSP_GEN_UNKNOWN; dwc->gadget->sg_supported = true; dwc->gadget->name = "dwc3-gadget"; dwc->gadget->lpm_capable = !dwc->usb2_gadget_lpm_disable; /* * FIXME We might be setting max_speed to <SUPER, however versions * <2.20a of dwc3 have an issue with metastability (documented * elsewhere in this driver) which tells us we can't set max speed to * anything lower than SUPER. * * Because gadget.max_speed is only used by composite.c and function * drivers (i.e. it won't go into dwc3's registers) we are allowing this * to happen so we avoid sending SuperSpeed Capability descriptor * together with our BOS descriptor as that could confuse host into * thinking we can handle super speed. * * Note that, in fact, we won't even support GetBOS requests when speed * is less than super speed because we don't have means, yet, to tell * composite.c that we are USB 2.0 + LPM ECN. */ if (DWC3_VER_IS_PRIOR(DWC3, 220A) && !dwc->dis_metastability_quirk) dev_info(dwc->dev, "changing max_speed on rev %08x\n", dwc->revision); dwc->gadget->max_speed = dwc->maximum_speed; dwc->gadget->max_ssp_rate = dwc->max_ssp_rate; /* * REVISIT: Here we should clear all pending IRQs to be * sure we're starting from a well known location. */ ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps); if (ret) goto err4; ret = usb_add_gadget(dwc->gadget); if (ret) { dev_err(dwc->dev, "failed to add gadget\n"); goto err5; } if (DWC3_IP_IS(DWC32) && dwc->maximum_speed == USB_SPEED_SUPER_PLUS) dwc3_gadget_set_ssp_rate(dwc->gadget, dwc->max_ssp_rate); else dwc3_gadget_set_speed(dwc->gadget, dwc->maximum_speed); return 0; err5: dwc3_gadget_free_endpoints(dwc); err4: usb_put_gadget(dwc->gadget); dwc->gadget = NULL; err3: dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce, dwc->bounce_addr); err2: kfree(dwc->setup_buf); err1: dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2, dwc->ep0_trb, dwc->ep0_trb_addr); err0: return ret; } /* -------------------------------------------------------------------------- */ void dwc3_gadget_exit(struct dwc3 *dwc) { if (!dwc->gadget) return; usb_del_gadget(dwc->gadget); dwc3_gadget_free_endpoints(dwc); usb_put_gadget(dwc->gadget); dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce, dwc->bounce_addr); kfree(dwc->setup_buf); dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2, dwc->ep0_trb, dwc->ep0_trb_addr); } int dwc3_gadget_suspend(struct dwc3 *dwc) { if (!dwc->gadget_driver) return 0; dwc3_gadget_run_stop(dwc, false, false); dwc3_disconnect_gadget(dwc); __dwc3_gadget_stop(dwc); return 0; } int dwc3_gadget_resume(struct dwc3 *dwc) { int ret; if (!dwc->gadget_driver) return 0; ret = __dwc3_gadget_start(dwc); if (ret < 0) goto err0; ret = dwc3_gadget_run_stop(dwc, true, false); if (ret < 0) goto err1; return 0; err1: __dwc3_gadget_stop(dwc); err0: return ret; } void dwc3_gadget_process_pending_events(struct dwc3 *dwc) { if (dwc->pending_events) { dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf); dwc->pending_events = false; enable_irq(dwc->irq_gadget); } }
#pragma once namespace vm { using namespace ps3; } enum CELL_MOUSE_ERROR_CODE { CELL_MOUSE_ERROR_FATAL = 0x80121201, CELL_MOUSE_ERROR_INVALID_PARAMETER = 0x80121202, CELL_MOUSE_ERROR_ALREADY_INITIALIZED = 0x80121203, CELL_MOUSE_ERROR_UNINITIALIZED = 0x80121204, CELL_MOUSE_ERROR_RESOURCE_ALLOCATION_FAILED = 0x80121205, CELL_MOUSE_ERROR_DATA_READ_FAILED = 0x80121206, CELL_MOUSE_ERROR_NO_DEVICE = 0x80121207, CELL_MOUSE_ERROR_SYS_SETTING_FAILED = 0x80121208, }; static const u32 CELL_MAX_MICE = 127; struct CellMouseInfo { be_t<u32> max_connect; be_t<u32> now_connect; be_t<u32> info; be_t<u16> vendor_id[CELL_MAX_MICE]; be_t<u16> product_id[CELL_MAX_MICE]; u8 status[CELL_MAX_MICE]; }; struct CellMouseInfoTablet { be_t<u32> is_supported; be_t<u32> mode; }; struct CellMouseData { u8 update; u8 buttons; s8 x_axis; s8 y_axis; s8 wheel; s8 tilt; }; static const u32 CELL_MOUSE_MAX_DATA_LIST_NUM = 8; struct CellMouseDataList { be_t<u32> list_num; CellMouseData list[CELL_MOUSE_MAX_DATA_LIST_NUM]; }; static const u32 CELL_MOUSE_MAX_CODES = 64;
<?php namespace Drupal\commerce; /** * Represents a country. */ final class Country { /** * Two-letter country code. * * @var string */ protected $countryCode; /** * Constructs a new Country object. * * @param string $country_code * The country code. */ public function __construct($country_code) { $this->countryCode = strtoupper($country_code); } /** * Gets the country code. * * @return string * The country code. */ public function getCountryCode() { return $this->countryCode; } /** * Gets the string representation of the country. * * @return string * The string representation of the country */ public function __toString() { return $this->countryCode; } }
/* * dv1394-private.h - DV input/output over IEEE 1394 on OHCI chips * Copyright (C)2001 Daniel Maas <dmaas@dcine.com> * receive, proc_fs by Dan Dennedy <dan@dennedy.org> * * based on: * video1394.h - driver for OHCI 1394 boards * Copyright (C)1999,2000 Sebastien Rougeaux <sebastien.rougeaux@anu.edu.au> * Peter Schlaile <udbz@rz.uni-karlsruhe.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _DV_1394_PRIVATE_H #define _DV_1394_PRIVATE_H #include "ieee1394.h" #include "ohci1394.h" #include "dma.h" /* data structures private to the dv1394 driver */ /* none of this is exposed to user-space */ /* the 8-byte CIP (Common Isochronous Packet) header that precedes each packet of DV data. See the IEC 61883 standard. */ struct CIP_header { unsigned char b[8]; }; static inline void fill_cip_header(struct CIP_header *cip, unsigned char source_node_id, unsigned long counter, enum pal_or_ntsc format, unsigned long timestamp) { cip->b[0] = source_node_id; cip->b[1] = 0x78; /* packet size in quadlets (480/4) - even for empty packets! */ cip->b[2] = 0x00; cip->b[3] = counter; cip->b[4] = 0x80; /* const */ switch(format) { case DV1394_PAL: cip->b[5] = 0x80; break; case DV1394_NTSC: cip->b[5] = 0x00; break; } cip->b[6] = timestamp >> 8; cip->b[7] = timestamp & 0xFF; } /* DMA commands used to program the OHCI's DMA engine See the Texas Instruments OHCI 1394 chipset documentation. */ struct output_more_immediate { u32 q[8]; }; struct output_more { u32 q[4]; }; struct output_last { u32 q[4]; }; struct input_more { u32 q[4]; }; struct input_last { u32 q[4]; }; /* outputs */ static inline void fill_output_more_immediate(struct output_more_immediate *omi, unsigned char tag, unsigned char channel, unsigned char sync_tag, unsigned int payload_size) { omi->q[0] = cpu_to_le32(0x02000000 | 8); /* OUTPUT_MORE_IMMEDIATE; 8 is the size of the IT header */ omi->q[1] = 0; omi->q[2] = 0; omi->q[3] = 0; /* IT packet header */ omi->q[4] = cpu_to_le32( (0x0 << 16) /* IEEE1394_SPEED_100 */ | (tag << 14) | (channel << 8) | (TCODE_ISO_DATA << 4) | (sync_tag) ); /* reserved field; mimic behavior of my Sony DSR-40 */ omi->q[5] = cpu_to_le32((payload_size << 16) | (0x7F << 8) | 0xA0); omi->q[6] = 0; omi->q[7] = 0; } static inline void fill_output_more(struct output_more *om, unsigned int data_size, unsigned long data_phys_addr) { om->q[0] = cpu_to_le32(data_size); om->q[1] = cpu_to_le32(data_phys_addr); om->q[2] = 0; om->q[3] = 0; } static inline void fill_output_last(struct output_last *ol, int want_timestamp, int want_interrupt, unsigned int data_size, unsigned long data_phys_addr) { u32 temp = 0; temp |= 1 << 28; /* OUTPUT_LAST */ if (want_timestamp) /* controller will update timestamp at DMA time */ temp |= 1 << 27; if (want_interrupt) temp |= 3 << 20; temp |= 3 << 18; /* must take branch */ temp |= data_size; ol->q[0] = cpu_to_le32(temp); ol->q[1] = cpu_to_le32(data_phys_addr); ol->q[2] = 0; ol->q[3] = 0; } /* inputs */ static inline void fill_input_more(struct input_more *im, int want_interrupt, unsigned int data_size, unsigned long data_phys_addr) { u32 temp = 2 << 28; /* INPUT_MORE */ temp |= 8 << 24; /* s = 1, update xferStatus and resCount */ if (want_interrupt) temp |= 0 << 20; /* interrupts, i=0 in packet-per-buffer mode */ temp |= 0x0 << 16; /* disable branch to address for packet-per-buffer mode */ /* disable wait on sync field, not used in DV :-( */ temp |= data_size; im->q[0] = cpu_to_le32(temp); im->q[1] = cpu_to_le32(data_phys_addr); im->q[2] = 0; /* branchAddress and Z not use in packet-per-buffer mode */ im->q[3] = 0; /* xferStatus & resCount, resCount must be initialize to data_size */ } static inline void fill_input_last(struct input_last *il, int want_interrupt, unsigned int data_size, unsigned long data_phys_addr) { u32 temp = 3 << 28; /* INPUT_LAST */ temp |= 8 << 24; /* s = 1, update xferStatus and resCount */ if (want_interrupt) temp |= 3 << 20; /* enable interrupts */ temp |= 0xC << 16; /* enable branch to address */ /* disable wait on sync field, not used in DV :-( */ temp |= data_size; il->q[0] = cpu_to_le32(temp); il->q[1] = cpu_to_le32(data_phys_addr); il->q[2] = cpu_to_le32(1); /* branchAddress (filled in later) and Z = 1 descriptor in next block */ il->q[3] = cpu_to_le32(data_size); /* xferStatus & resCount, resCount must be initialize to data_size */ } /* A "DMA descriptor block" consists of several contiguous DMA commands. struct DMA_descriptor_block encapsulates all of the commands necessary to send one packet of DV data. There are three different types of these blocks: 1) command to send an empty packet (CIP header only, no DV data): OUTPUT_MORE-Immediate <-- contains the iso header in-line OUTPUT_LAST <-- points to the CIP header 2) command to send a full packet when the DV data payload does NOT cross a page boundary: OUTPUT_MORE-Immediate <-- contains the iso header in-line OUTPUT_MORE <-- points to the CIP header OUTPUT_LAST <-- points to entire DV data payload 3) command to send a full packet when the DV payload DOES cross a page boundary: OUTPUT_MORE-Immediate <-- contains the iso header in-line OUTPUT_MORE <-- points to the CIP header OUTPUT_MORE <-- points to first part of DV data payload OUTPUT_LAST <-- points to second part of DV data payload This struct describes all three block types using unions. !!! It is vital that an even number of these descriptor blocks fit on one page of memory, since a block cannot cross a page boundary !!! */ struct DMA_descriptor_block { union { struct { /* iso header, common to all output block types */ struct output_more_immediate omi; union { /* empty packet */ struct { struct output_last ol; /* CIP header */ } empty; /* full packet */ struct { struct output_more om; /* CIP header */ union { /* payload does not cross page boundary */ struct { struct output_last ol; /* data payload */ } nocross; /* payload crosses page boundary */ struct { struct output_more om; /* data payload */ struct output_last ol; /* data payload */ } cross; } u; } full; } u; } out; struct { struct input_last il; } in; } u; /* ensure that PAGE_SIZE % sizeof(struct DMA_descriptor_block) == 0 by padding out to 128 bytes */ u32 __pad__[12]; }; /* struct frame contains all data associated with one frame in the ringbuffer these are allocated when the DMA context is initialized do_dv1394_init(). They are re-used after the card finishes transmitting the frame. */ struct video_card; /* forward declaration */ struct frame { /* points to the struct video_card that owns this frame */ struct video_card *video; /* index of this frame in video_card->frames[] */ unsigned int frame_num; /* FRAME_CLEAR - DMA program not set up, waiting for data FRAME_READY - DMA program written, ready to transmit Changes to these should be locked against the interrupt */ enum { FRAME_CLEAR = 0, FRAME_READY } state; /* whether this frame has been DMA'ed already; used only from the IRQ handler to determine whether the frame can be reset */ int done; /* kernel virtual pointer to the start of this frame's data in the user ringbuffer. Use only for CPU access; to get the DMA bus address you must go through the video->user_dma mapping */ unsigned long data; /* Max # of packets per frame */ #define MAX_PACKETS 500 /* a PAGE_SIZE memory pool for allocating CIP headers !header_pool must be aligned to PAGE_SIZE! */ struct CIP_header *header_pool; dma_addr_t header_pool_dma; /* a physically contiguous memory pool for allocating DMA descriptor blocks; usually around 64KB in size !descriptor_pool must be aligned to PAGE_SIZE! */ struct DMA_descriptor_block *descriptor_pool; dma_addr_t descriptor_pool_dma; unsigned long descriptor_pool_size; /* # of packets allocated for this frame */ unsigned int n_packets; /* below are several pointers (kernel virtual addresses, not DMA bus addresses) to parts of the DMA program. These are set each time the DMA program is written in frame_prepare(). They are used later on, e.g. from the interrupt handler, to check the status of the frame */ /* points to status/timestamp field of first DMA packet */ /* (we'll check it later to monitor timestamp accuracy) */ u32 *frame_begin_timestamp; /* the timestamp we assigned to the first packet in the frame */ u32 assigned_timestamp; /* pointer to the first packet's CIP header (where the timestamp goes) */ struct CIP_header *cip_syt1; /* pointer to the second packet's CIP header (only set if the first packet was empty) */ struct CIP_header *cip_syt2; /* in order to figure out what caused an interrupt, store pointers to the status fields of the two packets that can cause interrupts. We'll check these from the interrupt handler. */ u32 *mid_frame_timestamp; u32 *frame_end_timestamp; /* branch address field of final packet. This is effectively the "tail" in the chain of DMA descriptor blocks. We will fill it with the address of the first DMA descriptor block in the subsequent frame, once it is ready. */ u32 *frame_end_branch; /* the number of descriptors in the first descriptor block of the frame. Needed to start DMA */ int first_n_descriptors; }; struct packet { u16 timestamp; u16 invalid; u16 iso_header; u16 data_length; u32 cip_h1; u32 cip_h2; unsigned char data[480]; unsigned char padding[16]; /* force struct size =512 for page alignment */ }; /* allocate/free a frame */ static struct frame* frame_new(unsigned int frame_num, struct video_card *video); static void frame_delete(struct frame *f); /* reset f so that it can be used again */ static void frame_reset(struct frame *f); /* struct video_card contains all data associated with one instance of the dv1394 driver */ enum modes { MODE_RECEIVE, MODE_TRANSMIT }; struct video_card { /* ohci card to which this instance corresponds */ struct ti_ohci *ohci; /* OHCI card id; the link between the VFS inode and a specific video_card (essentially the device minor number) */ int id; /* entry in dv1394_cards */ struct list_head list; /* handle to /dev/ieee1394/dv/N, NULL if devfs not in use */ devfs_handle_t devfs_handle; /* OHCI card IT DMA context number, -1 if not in use */ int ohci_it_ctx; struct ohci1394_iso_tasklet it_tasklet; /* register offsets for current IT DMA context, 0 if not in use */ u32 ohci_IsoXmitContextControlSet; u32 ohci_IsoXmitContextControlClear; u32 ohci_IsoXmitCommandPtr; /* OHCI card IR DMA context number, -1 if not in use */ struct ohci1394_iso_tasklet ir_tasklet; int ohci_ir_ctx; /* register offsets for current IR DMA context, 0 if not in use */ u32 ohci_IsoRcvContextControlSet; u32 ohci_IsoRcvContextControlClear; u32 ohci_IsoRcvCommandPtr; u32 ohci_IsoRcvContextMatch; /* CONCURRENCY CONTROL */ /* there are THREE levels of locking associated with video_card. */ /* 1) the 'open' flag - this prevents more than one process from opening the device. (the driver currently assumes only one opener). This is a regular int, but use test_and_set_bit() (on bit zero) for atomicity. */ unsigned long open; /* 2) the spinlock - this provides mutual exclusion between the interrupt handler and process-context operations. Generally you must take the spinlock under the following conditions: 1) DMA (and hence the interrupt handler) may be running AND 2) you need to operate on the video_card, especially active_frame It is OK to play with video_card without taking the spinlock if you are certain that DMA is not running. Even if DMA is running, it is OK to *read* active_frame with the lock, then drop it immediately. This is safe because the interrupt handler will never advance active_frame onto a frame that is not READY (and the spinlock must be held while marking a frame READY). spinlock is also used to protect ohci_it_ctx and ohci_ir_ctx, which can be accessed from both process and interrupt context */ spinlock_t spinlock; /* flag to prevent spurious interrupts (which OHCI seems to generate a lot :) from accessing the struct */ int dma_running; /* 3) the sleeping semaphore 'sem' - this is used from process context only, to serialize various operations on the video_card. Even though only one open() is allowed, we still need to prevent multiple threads of execution from entering calls like read, write, ioctl, etc. I honestly can't think of a good reason to use dv1394 from several threads at once, but we need to serialize anyway to prevent oopses =). NOTE: if you need both spinlock and sem, take sem first to avoid deadlock! */ struct semaphore sem; /* people waiting for buffer space, please form a line here... */ wait_queue_head_t waitq; /* support asynchronous I/O signals (SIGIO) */ struct fasync_struct *fasync; /* the large, non-contiguous (rvmalloc()) ringbuffer for DV data, exposed to user-space via mmap() */ unsigned long dv_buf_size; struct dma_region dv_buf; /* next byte in the ringbuffer that a write() call will fill */ size_t write_off; struct frame *frames[DV1394_MAX_FRAMES]; /* n_frames also serves as an indicator that this struct video_card is initialized and ready to run DMA buffers */ int n_frames; /* this is the frame that is currently "owned" by the OHCI DMA controller (set to -1 iff DMA is not running) ! must lock against the interrupt handler when accessing it ! RULES: Only the interrupt handler may change active_frame if DMA is running; if not, process may change it If the next frame is READY, the interrupt handler will advance active_frame when the current frame is finished. If the next frame is CLEAR, the interrupt handler will re-transmit the current frame, and the dropped_frames counter will be incremented. The interrupt handler will NEVER advance active_frame to a frame that is not READY. */ int active_frame; int first_run; /* the same locking rules apply to these three fields also: */ /* altered ONLY from process context. Must check first_clear_frame->state; if it's READY, that means the ringbuffer is full with READY frames; if it's CLEAR, that means one or more ringbuffer frames are CLEAR */ unsigned int first_clear_frame; /* altered both by process and interrupt */ unsigned int n_clear_frames; /* only altered by the interrupt */ unsigned int dropped_frames; /* the CIP accumulator and continuity counter are properties of the DMA stream as a whole (not a single frame), so they are stored here in the video_card */ unsigned long cip_accum; unsigned long cip_n, cip_d; unsigned int syt_offset; unsigned int continuity_counter; enum pal_or_ntsc pal_or_ntsc; /* redundant, but simplifies the code somewhat */ unsigned int frame_size; /* in bytes */ /* the isochronous channel to use, -1 if video card is inactive */ int channel; /* physically contiguous packet ringbuffer for receive */ struct dma_region packet_buf; unsigned long packet_buf_size; unsigned int current_packet; int first_frame; /* received first start frame marker? */ enum modes mode; }; /* if the video_card is not initialized, then the ONLY fields that are valid are: ohci open n_frames */ static inline int video_card_initialized(struct video_card *v) { return v->n_frames > 0; } static int do_dv1394_init(struct video_card *video, struct dv1394_init *init); static int do_dv1394_init_default(struct video_card *video); static void do_dv1394_shutdown(struct video_card *video, int free_user_buf); /* NTSC empty packet rate accurate to within 0.01%, calibrated against a Sony DSR-40 DVCAM deck */ #define CIP_N_NTSC 68000000 #define CIP_D_NTSC 1068000000 #define CIP_N_PAL 1 #define CIP_D_PAL 16 #endif /* _DV_1394_PRIVATE_H */
<table class="form-table"> <tr> <th>Main color</th> <td> <?php $controls->color('theme_color'); ?> (eg. #87aa14) </td> </tr> </table>
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * 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@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: HtmlElement.php 24593 2012-01-05 20:35:02Z matthew $ */ /** * @see Zend_View_Helper_Abstract */ #require_once 'Zend/View/Helper/Abstract.php'; /** * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_View_Helper_HtmlElement extends Zend_View_Helper_Abstract { /** * EOL character */ const EOL = "\n"; /** * The tag closing bracket * * @var string */ protected $_closingBracket = null; /** * Get the tag closing bracket * * @return string */ public function getClosingBracket() { if (!$this->_closingBracket) { if ($this->_isXhtml()) { $this->_closingBracket = ' />'; } else { $this->_closingBracket = '>'; } } return $this->_closingBracket; } /** * Is doctype XHTML? * * @return boolean */ protected function _isXhtml() { $doctype = $this->view->doctype(); return $doctype->isXhtml(); } /** * Is doctype strict? * * @return boolean */ protected function _isStrictDoctype() { $doctype = $this->view->doctype(); return $doctype->isStrict(); } /** * Converts an associative array to a string of tag attributes. * * @access public * * @param array $attribs From this array, each key-value pair is * converted to an attribute name and value. * * @return string The XHTML for the attributes. */ protected function _htmlAttribs($attribs) { $xhtml = ''; foreach ((array) $attribs as $key => $val) { $key = $this->view->escape($key); if (('on' == substr($key, 0, 2)) || ('constraints' == $key)) { // Don't escape event attributes; _do_ substitute double quotes with singles if (!is_scalar($val)) { // non-scalar data should be cast to JSON first #require_once 'Zend/Json.php'; $val = Zend_Json::encode($val); } // Escape single quotes inside event attribute values. // This will create html, where the attribute value has // single quotes around it, and escaped single quotes or // non-escaped double quotes inside of it $val = str_replace('\'', '&#39;', $val); } else { if (is_array($val)) { $val = implode(' ', $val); } $val = $this->view->escape($val); } if ('id' == $key) { $val = $this->_normalizeId($val); } if (strpos($val, '"') !== false) { $xhtml .= " $key='$val'"; } else { $xhtml .= " $key=\"$val\""; } } return $xhtml; } /** * Normalize an ID * * @param string $value * @return string */ protected function _normalizeId($value) { if (strstr($value, '[')) { if ('[]' == substr($value, -2)) { $value = substr($value, 0, strlen($value) - 2); } $value = trim($value, ']'); $value = str_replace('][', '-', $value); $value = str_replace('[', '-', $value); } return $value; } }
/* * Universal Interface for Intel High Definition Audio Codec * * HD audio interface patch for SigmaTel STAC92xx * * Copyright (c) 2005 Embedded Alley Solutions, Inc. * Matt Porter <mporter@embeddedalley.com> * * Based on patch_cmedia.c and patch_realtek.c * Copyright (c) 2004 Takashi Iwai <tiwai@suse.de> * * This driver 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 driver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/init.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/pci.h> #include <linux/dmi.h> #include <sound/core.h> #include <sound/asoundef.h> #include <sound/jack.h> #include <sound/tlv.h> #include "hda_codec.h" #include "hda_local.h" #include "hda_beep.h" enum { STAC_VREF_EVENT = 1, STAC_INSERT_EVENT, STAC_PWR_EVENT, STAC_HP_EVENT, STAC_LO_EVENT, STAC_MIC_EVENT, }; enum { STAC_AUTO, STAC_REF, STAC_9200_OQO, STAC_9200_DELL_D21, STAC_9200_DELL_D22, STAC_9200_DELL_D23, STAC_9200_DELL_M21, STAC_9200_DELL_M22, STAC_9200_DELL_M23, STAC_9200_DELL_M24, STAC_9200_DELL_M25, STAC_9200_DELL_M26, STAC_9200_DELL_M27, STAC_9200_M4, STAC_9200_M4_2, STAC_9200_PANASONIC, STAC_9200_MODELS }; enum { STAC_9205_AUTO, STAC_9205_REF, STAC_9205_DELL_M42, STAC_9205_DELL_M43, STAC_9205_DELL_M44, STAC_9205_EAPD, STAC_9205_MODELS }; enum { STAC_92HD73XX_AUTO, STAC_92HD73XX_NO_JD, /* no jack-detection */ STAC_92HD73XX_REF, STAC_92HD73XX_INTEL, STAC_DELL_M6_AMIC, STAC_DELL_M6_DMIC, STAC_DELL_M6_BOTH, STAC_DELL_EQ, STAC_ALIENWARE_M17X, STAC_92HD73XX_MODELS }; enum { STAC_92HD83XXX_AUTO, STAC_92HD83XXX_REF, STAC_92HD83XXX_PWR_REF, STAC_DELL_S14, STAC_92HD83XXX_HP, STAC_HP_DV7_4000, STAC_92HD83XXX_MODELS }; enum { STAC_92HD71BXX_AUTO, STAC_92HD71BXX_REF, STAC_DELL_M4_1, STAC_DELL_M4_2, STAC_DELL_M4_3, STAC_HP_M4, STAC_HP_DV4, STAC_HP_DV5, STAC_HP_HDX, STAC_HP_DV4_1222NR, STAC_92HD71BXX_MODELS }; enum { STAC_925x_AUTO, STAC_925x_REF, STAC_M1, STAC_M1_2, STAC_M2, STAC_M2_2, STAC_M3, STAC_M5, STAC_M6, STAC_925x_MODELS }; enum { STAC_922X_AUTO, STAC_D945_REF, STAC_D945GTP3, STAC_D945GTP5, STAC_INTEL_MAC_V1, STAC_INTEL_MAC_V2, STAC_INTEL_MAC_V3, STAC_INTEL_MAC_V4, STAC_INTEL_MAC_V5, STAC_INTEL_MAC_AUTO, /* This model is selected if no module parameter * is given, one of the above models will be * chosen according to the subsystem id. */ /* for backward compatibility */ STAC_MACMINI, STAC_MACBOOK, STAC_MACBOOK_PRO_V1, STAC_MACBOOK_PRO_V2, STAC_IMAC_INTEL, STAC_IMAC_INTEL_20, STAC_ECS_202, STAC_922X_DELL_D81, STAC_922X_DELL_D82, STAC_922X_DELL_M81, STAC_922X_DELL_M82, STAC_922X_MODELS }; enum { STAC_927X_AUTO, STAC_D965_REF_NO_JD, /* no jack-detection */ STAC_D965_REF, STAC_D965_3ST, STAC_D965_5ST, STAC_D965_5ST_NO_FP, STAC_DELL_3ST, STAC_DELL_BIOS, STAC_927X_VOLKNOB, STAC_927X_MODELS }; enum { STAC_9872_AUTO, STAC_9872_VAIO, STAC_9872_MODELS }; struct sigmatel_event { hda_nid_t nid; unsigned char type; unsigned char tag; int data; }; struct sigmatel_mic_route { hda_nid_t pin; signed char mux_idx; signed char dmux_idx; }; #define MAX_PINS_NUM 16 #define MAX_ADCS_NUM 4 #define MAX_DMICS_NUM 4 struct sigmatel_spec { struct snd_kcontrol_new *mixers[4]; unsigned int num_mixers; int board_config; unsigned int eapd_switch: 1; unsigned int surr_switch: 1; unsigned int alt_switch: 1; unsigned int hp_detect: 1; unsigned int spdif_mute: 1; unsigned int check_volume_offset:1; unsigned int auto_mic:1; unsigned int linear_tone_beep:1; /* gpio lines */ unsigned int eapd_mask; unsigned int gpio_mask; unsigned int gpio_dir; unsigned int gpio_data; unsigned int gpio_mute; unsigned int gpio_led; unsigned int gpio_led_polarity; /* stream */ unsigned int stream_delay; /* analog loopback */ struct snd_kcontrol_new *aloopback_ctl; unsigned char aloopback_mask; unsigned char aloopback_shift; /* power management */ unsigned int num_pwrs; unsigned int *pwr_mapping; hda_nid_t *pwr_nids; hda_nid_t *dac_list; /* events */ struct snd_array events; /* playback */ struct hda_input_mux *mono_mux; unsigned int cur_mmux; struct hda_multi_out multiout; hda_nid_t dac_nids[5]; hda_nid_t hp_dacs[5]; hda_nid_t speaker_dacs[5]; int volume_offset; /* capture */ hda_nid_t *adc_nids; unsigned int num_adcs; hda_nid_t *mux_nids; unsigned int num_muxes; hda_nid_t *dmic_nids; unsigned int num_dmics; hda_nid_t *dmux_nids; unsigned int num_dmuxes; hda_nid_t *smux_nids; unsigned int num_smuxes; unsigned int num_analog_muxes; unsigned long *capvols; /* amp-volume attr: HDA_COMPOSE_AMP_VAL() */ unsigned long *capsws; /* amp-mute attr: HDA_COMPOSE_AMP_VAL() */ unsigned int num_caps; /* number of capture volume/switch elements */ struct sigmatel_mic_route ext_mic; struct sigmatel_mic_route int_mic; struct sigmatel_mic_route dock_mic; const char * const *spdif_labels; hda_nid_t dig_in_nid; hda_nid_t mono_nid; hda_nid_t anabeep_nid; hda_nid_t digbeep_nid; /* pin widgets */ hda_nid_t *pin_nids; unsigned int num_pins; /* codec specific stuff */ struct hda_verb *init; struct snd_kcontrol_new *mixer; /* capture source */ struct hda_input_mux *dinput_mux; unsigned int cur_dmux[2]; struct hda_input_mux *input_mux; unsigned int cur_mux[3]; struct hda_input_mux *sinput_mux; unsigned int cur_smux[2]; unsigned int cur_amux; hda_nid_t *amp_nids; unsigned int powerdown_adcs; /* i/o switches */ unsigned int io_switch[2]; unsigned int clfe_swap; hda_nid_t line_switch; /* shared line-in for input and output */ hda_nid_t mic_switch; /* shared mic-in for input and output */ hda_nid_t hp_switch; /* NID of HP as line-out */ unsigned int aloopback; struct hda_pcm pcm_rec[2]; /* PCM information */ /* dynamic controls and input_mux */ struct auto_pin_cfg autocfg; struct snd_array kctls; struct hda_input_mux private_dimux; struct hda_input_mux private_imux; struct hda_input_mux private_smux; struct hda_input_mux private_mono_mux; /* auto spec */ unsigned auto_pin_cnt; hda_nid_t auto_pin_nids[MAX_PINS_NUM]; unsigned auto_adc_cnt; hda_nid_t auto_adc_nids[MAX_ADCS_NUM]; hda_nid_t auto_mux_nids[MAX_ADCS_NUM]; hda_nid_t auto_dmux_nids[MAX_ADCS_NUM]; unsigned long auto_capvols[MAX_ADCS_NUM]; unsigned auto_dmic_cnt; hda_nid_t auto_dmic_nids[MAX_DMICS_NUM]; }; static hda_nid_t stac9200_adc_nids[1] = { 0x03, }; static hda_nid_t stac9200_mux_nids[1] = { 0x0c, }; static hda_nid_t stac9200_dac_nids[1] = { 0x02, }; static hda_nid_t stac92hd73xx_pwr_nids[8] = { 0x0a, 0x0b, 0x0c, 0xd, 0x0e, 0x0f, 0x10, 0x11 }; static hda_nid_t stac92hd73xx_slave_dig_outs[2] = { 0x26, 0, }; static hda_nid_t stac92hd73xx_adc_nids[2] = { 0x1a, 0x1b }; #define STAC92HD73XX_NUM_DMICS 2 static hda_nid_t stac92hd73xx_dmic_nids[STAC92HD73XX_NUM_DMICS + 1] = { 0x13, 0x14, 0 }; #define STAC92HD73_DAC_COUNT 5 static hda_nid_t stac92hd73xx_mux_nids[2] = { 0x20, 0x21, }; static hda_nid_t stac92hd73xx_dmux_nids[2] = { 0x20, 0x21, }; static hda_nid_t stac92hd73xx_smux_nids[2] = { 0x22, 0x23, }; #define STAC92HD73XX_NUM_CAPS 2 static unsigned long stac92hd73xx_capvols[] = { HDA_COMPOSE_AMP_VAL(0x20, 3, 0, HDA_OUTPUT), HDA_COMPOSE_AMP_VAL(0x21, 3, 0, HDA_OUTPUT), }; #define stac92hd73xx_capsws stac92hd73xx_capvols #define STAC92HD83_DAC_COUNT 3 static hda_nid_t stac92hd83xxx_pwr_nids[4] = { 0xa, 0xb, 0xd, 0xe, }; static hda_nid_t stac92hd83xxx_slave_dig_outs[2] = { 0x1e, 0, }; static unsigned int stac92hd83xxx_pwr_mapping[4] = { 0x03, 0x0c, 0x20, 0x40, }; static hda_nid_t stac92hd83xxx_dmic_nids[] = { 0x11, 0x20, }; static hda_nid_t stac92hd71bxx_pwr_nids[3] = { 0x0a, 0x0d, 0x0f }; static hda_nid_t stac92hd71bxx_adc_nids[2] = { 0x12, 0x13, }; static hda_nid_t stac92hd71bxx_mux_nids[2] = { 0x1a, 0x1b }; static hda_nid_t stac92hd71bxx_dmux_nids[2] = { 0x1c, 0x1d, }; static hda_nid_t stac92hd71bxx_smux_nids[2] = { 0x24, 0x25, }; #define STAC92HD71BXX_NUM_DMICS 2 static hda_nid_t stac92hd71bxx_dmic_nids[STAC92HD71BXX_NUM_DMICS + 1] = { 0x18, 0x19, 0 }; static hda_nid_t stac92hd71bxx_slave_dig_outs[2] = { 0x22, 0 }; #define STAC92HD71BXX_NUM_CAPS 2 static unsigned long stac92hd71bxx_capvols[] = { HDA_COMPOSE_AMP_VAL(0x1c, 3, 0, HDA_OUTPUT), HDA_COMPOSE_AMP_VAL(0x1d, 3, 0, HDA_OUTPUT), }; #define stac92hd71bxx_capsws stac92hd71bxx_capvols static hda_nid_t stac925x_adc_nids[1] = { 0x03, }; static hda_nid_t stac925x_mux_nids[1] = { 0x0f, }; static hda_nid_t stac925x_dac_nids[1] = { 0x02, }; #define STAC925X_NUM_DMICS 1 static hda_nid_t stac925x_dmic_nids[STAC925X_NUM_DMICS + 1] = { 0x15, 0 }; static hda_nid_t stac925x_dmux_nids[1] = { 0x14, }; static unsigned long stac925x_capvols[] = { HDA_COMPOSE_AMP_VAL(0x09, 3, 0, HDA_OUTPUT), }; static unsigned long stac925x_capsws[] = { HDA_COMPOSE_AMP_VAL(0x14, 3, 0, HDA_OUTPUT), }; static hda_nid_t stac922x_adc_nids[2] = { 0x06, 0x07, }; static hda_nid_t stac922x_mux_nids[2] = { 0x12, 0x13, }; #define STAC922X_NUM_CAPS 2 static unsigned long stac922x_capvols[] = { HDA_COMPOSE_AMP_VAL(0x17, 3, 0, HDA_INPUT), HDA_COMPOSE_AMP_VAL(0x18, 3, 0, HDA_INPUT), }; #define stac922x_capsws stac922x_capvols static hda_nid_t stac927x_slave_dig_outs[2] = { 0x1f, 0, }; static hda_nid_t stac927x_adc_nids[3] = { 0x07, 0x08, 0x09 }; static hda_nid_t stac927x_mux_nids[3] = { 0x15, 0x16, 0x17 }; static hda_nid_t stac927x_smux_nids[1] = { 0x21, }; static hda_nid_t stac927x_dac_nids[6] = { 0x02, 0x03, 0x04, 0x05, 0x06, 0 }; static hda_nid_t stac927x_dmux_nids[1] = { 0x1b, }; #define STAC927X_NUM_DMICS 2 static hda_nid_t stac927x_dmic_nids[STAC927X_NUM_DMICS + 1] = { 0x13, 0x14, 0 }; #define STAC927X_NUM_CAPS 3 static unsigned long stac927x_capvols[] = { HDA_COMPOSE_AMP_VAL(0x18, 3, 0, HDA_INPUT), HDA_COMPOSE_AMP_VAL(0x19, 3, 0, HDA_INPUT), HDA_COMPOSE_AMP_VAL(0x1a, 3, 0, HDA_INPUT), }; static unsigned long stac927x_capsws[] = { HDA_COMPOSE_AMP_VAL(0x1b, 3, 0, HDA_OUTPUT), HDA_COMPOSE_AMP_VAL(0x1c, 3, 0, HDA_OUTPUT), HDA_COMPOSE_AMP_VAL(0x1d, 3, 0, HDA_OUTPUT), }; static const char * const stac927x_spdif_labels[5] = { "Digital Playback", "ADAT", "Analog Mux 1", "Analog Mux 2", "Analog Mux 3" }; static hda_nid_t stac9205_adc_nids[2] = { 0x12, 0x13 }; static hda_nid_t stac9205_mux_nids[2] = { 0x19, 0x1a }; static hda_nid_t stac9205_dmux_nids[1] = { 0x1d, }; static hda_nid_t stac9205_smux_nids[1] = { 0x21, }; #define STAC9205_NUM_DMICS 2 static hda_nid_t stac9205_dmic_nids[STAC9205_NUM_DMICS + 1] = { 0x17, 0x18, 0 }; #define STAC9205_NUM_CAPS 2 static unsigned long stac9205_capvols[] = { HDA_COMPOSE_AMP_VAL(0x1b, 3, 0, HDA_INPUT), HDA_COMPOSE_AMP_VAL(0x1c, 3, 0, HDA_INPUT), }; static unsigned long stac9205_capsws[] = { HDA_COMPOSE_AMP_VAL(0x1d, 3, 0, HDA_OUTPUT), HDA_COMPOSE_AMP_VAL(0x1e, 3, 0, HDA_OUTPUT), }; static hda_nid_t stac9200_pin_nids[8] = { 0x08, 0x09, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, }; static hda_nid_t stac925x_pin_nids[8] = { 0x07, 0x08, 0x0a, 0x0b, 0x0c, 0x0d, 0x10, 0x11, }; static hda_nid_t stac922x_pin_nids[10] = { 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x15, 0x1b, }; static hda_nid_t stac92hd73xx_pin_nids[13] = { 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x22, 0x23 }; #define STAC92HD71BXX_NUM_PINS 13 static hda_nid_t stac92hd71bxx_pin_nids_4port[STAC92HD71BXX_NUM_PINS] = { 0x0a, 0x0b, 0x0c, 0x0d, 0x00, 0x00, 0x14, 0x18, 0x19, 0x1e, 0x1f, 0x20, 0x27 }; static hda_nid_t stac92hd71bxx_pin_nids_6port[STAC92HD71BXX_NUM_PINS] = { 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x14, 0x18, 0x19, 0x1e, 0x1f, 0x20, 0x27 }; static hda_nid_t stac927x_pin_nids[14] = { 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x21, 0x22, 0x23, }; static hda_nid_t stac9205_pin_nids[12] = { 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x14, 0x16, 0x17, 0x18, 0x21, 0x22, }; static int stac92xx_dmux_enum_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; return snd_hda_input_mux_info(spec->dinput_mux, uinfo); } static int stac92xx_dmux_enum_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; unsigned int dmux_idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); ucontrol->value.enumerated.item[0] = spec->cur_dmux[dmux_idx]; return 0; } static int stac92xx_dmux_enum_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; unsigned int dmux_idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); return snd_hda_input_mux_put(codec, spec->dinput_mux, ucontrol, spec->dmux_nids[dmux_idx], &spec->cur_dmux[dmux_idx]); } static int stac92xx_smux_enum_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; return snd_hda_input_mux_info(spec->sinput_mux, uinfo); } static int stac92xx_smux_enum_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; unsigned int smux_idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); ucontrol->value.enumerated.item[0] = spec->cur_smux[smux_idx]; return 0; } static int stac92xx_smux_enum_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; struct hda_input_mux *smux = &spec->private_smux; unsigned int smux_idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); int err, val; hda_nid_t nid; err = snd_hda_input_mux_put(codec, spec->sinput_mux, ucontrol, spec->smux_nids[smux_idx], &spec->cur_smux[smux_idx]); if (err < 0) return err; if (spec->spdif_mute) { if (smux_idx == 0) nid = spec->multiout.dig_out_nid; else nid = codec->slave_dig_outs[smux_idx - 1]; if (spec->cur_smux[smux_idx] == smux->num_items - 1) val = HDA_AMP_MUTE; else val = 0; /* un/mute SPDIF out */ snd_hda_codec_amp_stereo(codec, nid, HDA_OUTPUT, 0, HDA_AMP_MUTE, val); } return 0; } static unsigned int stac92xx_vref_set(struct hda_codec *codec, hda_nid_t nid, unsigned int new_vref) { int error; unsigned int pincfg; pincfg = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_PIN_WIDGET_CONTROL, 0); pincfg &= 0xff; pincfg &= ~(AC_PINCTL_VREFEN | AC_PINCTL_IN_EN | AC_PINCTL_OUT_EN); pincfg |= new_vref; if (new_vref == AC_PINCTL_VREF_HIZ) pincfg |= AC_PINCTL_OUT_EN; else pincfg |= AC_PINCTL_IN_EN; error = snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_PIN_WIDGET_CONTROL, pincfg); if (error < 0) return error; else return 1; } static unsigned int stac92xx_vref_get(struct hda_codec *codec, hda_nid_t nid) { unsigned int vref; vref = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_PIN_WIDGET_CONTROL, 0); vref &= AC_PINCTL_VREFEN; return vref; } static int stac92xx_mux_enum_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; return snd_hda_input_mux_info(spec->input_mux, uinfo); } static int stac92xx_mux_enum_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; unsigned int adc_idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); ucontrol->value.enumerated.item[0] = spec->cur_mux[adc_idx]; return 0; } static int stac92xx_mux_enum_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; unsigned int adc_idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); const struct hda_input_mux *imux = spec->input_mux; unsigned int idx, prev_idx, didx; idx = ucontrol->value.enumerated.item[0]; if (idx >= imux->num_items) idx = imux->num_items - 1; prev_idx = spec->cur_mux[adc_idx]; if (prev_idx == idx) return 0; if (idx < spec->num_analog_muxes) { snd_hda_codec_write_cache(codec, spec->mux_nids[adc_idx], 0, AC_VERB_SET_CONNECT_SEL, imux->items[idx].index); if (prev_idx >= spec->num_analog_muxes && spec->mux_nids[adc_idx] != spec->dmux_nids[adc_idx]) { imux = spec->dinput_mux; /* 0 = analog */ snd_hda_codec_write_cache(codec, spec->dmux_nids[adc_idx], 0, AC_VERB_SET_CONNECT_SEL, imux->items[0].index); } } else { imux = spec->dinput_mux; /* first dimux item is hardcoded to select analog imux, * so lets skip it */ didx = idx - spec->num_analog_muxes + 1; snd_hda_codec_write_cache(codec, spec->dmux_nids[adc_idx], 0, AC_VERB_SET_CONNECT_SEL, imux->items[didx].index); } spec->cur_mux[adc_idx] = idx; return 1; } static int stac92xx_mono_mux_enum_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; return snd_hda_input_mux_info(spec->mono_mux, uinfo); } static int stac92xx_mono_mux_enum_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; ucontrol->value.enumerated.item[0] = spec->cur_mmux; return 0; } static int stac92xx_mono_mux_enum_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; return snd_hda_input_mux_put(codec, spec->mono_mux, ucontrol, spec->mono_nid, &spec->cur_mmux); } #define stac92xx_aloopback_info snd_ctl_boolean_mono_info static int stac92xx_aloopback_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); unsigned int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); struct sigmatel_spec *spec = codec->spec; ucontrol->value.integer.value[0] = !!(spec->aloopback & (spec->aloopback_mask << idx)); return 0; } static int stac92xx_aloopback_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; unsigned int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); unsigned int dac_mode; unsigned int val, idx_val; idx_val = spec->aloopback_mask << idx; if (ucontrol->value.integer.value[0]) val = spec->aloopback | idx_val; else val = spec->aloopback & ~idx_val; if (spec->aloopback == val) return 0; spec->aloopback = val; /* Only return the bits defined by the shift value of the * first two bytes of the mask */ dac_mode = snd_hda_codec_read(codec, codec->afg, 0, kcontrol->private_value & 0xFFFF, 0x0); dac_mode >>= spec->aloopback_shift; if (spec->aloopback & idx_val) { snd_hda_power_up(codec); dac_mode |= idx_val; } else { snd_hda_power_down(codec); dac_mode &= ~idx_val; } snd_hda_codec_write_cache(codec, codec->afg, 0, kcontrol->private_value >> 16, dac_mode); return 1; } static struct hda_verb stac9200_core_init[] = { /* set dac0mux for dac converter */ { 0x07, AC_VERB_SET_CONNECT_SEL, 0x00}, {} }; static struct hda_verb stac9200_eapd_init[] = { /* set dac0mux for dac converter */ {0x07, AC_VERB_SET_CONNECT_SEL, 0x00}, {0x08, AC_VERB_SET_EAPD_BTLENABLE, 0x02}, {} }; static struct hda_verb dell_eq_core_init[] = { /* set master volume to max value without distortion * and direct control */ { 0x1f, AC_VERB_SET_VOLUME_KNOB_CONTROL, 0xec}, {} }; static struct hda_verb stac92hd73xx_core_init[] = { /* set master volume and direct control */ { 0x1f, AC_VERB_SET_VOLUME_KNOB_CONTROL, 0xff}, {} }; static struct hda_verb stac92hd83xxx_core_init[] = { /* power state controls amps */ { 0x01, AC_VERB_SET_EAPD, 1 << 2}, {} }; static struct hda_verb stac92hd71bxx_core_init[] = { /* set master volume and direct control */ { 0x28, AC_VERB_SET_VOLUME_KNOB_CONTROL, 0xff}, {} }; static struct hda_verb stac92hd71bxx_unmute_core_init[] = { /* unmute right and left channels for nodes 0x0f, 0xa, 0x0d */ { 0x0f, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)}, { 0x0a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)}, { 0x0d, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)}, {} }; static struct hda_verb stac925x_core_init[] = { /* set dac0mux for dac converter */ { 0x06, AC_VERB_SET_CONNECT_SEL, 0x00}, /* mute the master volume */ { 0x0e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE }, {} }; static struct hda_verb stac922x_core_init[] = { /* set master volume and direct control */ { 0x16, AC_VERB_SET_VOLUME_KNOB_CONTROL, 0xff}, {} }; static struct hda_verb d965_core_init[] = { /* set master volume and direct control */ { 0x24, AC_VERB_SET_VOLUME_KNOB_CONTROL, 0xff}, /* unmute node 0x1b */ { 0x1b, AC_VERB_SET_AMP_GAIN_MUTE, 0xb000}, /* select node 0x03 as DAC */ { 0x0b, AC_VERB_SET_CONNECT_SEL, 0x01}, {} }; static struct hda_verb dell_3st_core_init[] = { /* don't set delta bit */ {0x24, AC_VERB_SET_VOLUME_KNOB_CONTROL, 0x7f}, /* unmute node 0x1b */ {0x1b, AC_VERB_SET_AMP_GAIN_MUTE, 0xb000}, /* select node 0x03 as DAC */ {0x0b, AC_VERB_SET_CONNECT_SEL, 0x01}, {} }; static struct hda_verb stac927x_core_init[] = { /* set master volume and direct control */ { 0x24, AC_VERB_SET_VOLUME_KNOB_CONTROL, 0xff}, /* enable analog pc beep path */ { 0x01, AC_VERB_SET_DIGI_CONVERT_2, 1 << 5}, {} }; static struct hda_verb stac927x_volknob_core_init[] = { /* don't set delta bit */ {0x24, AC_VERB_SET_VOLUME_KNOB_CONTROL, 0x7f}, /* enable analog pc beep path */ {0x01, AC_VERB_SET_DIGI_CONVERT_2, 1 << 5}, {} }; static struct hda_verb stac9205_core_init[] = { /* set master volume and direct control */ { 0x24, AC_VERB_SET_VOLUME_KNOB_CONTROL, 0xff}, /* enable analog pc beep path */ { 0x01, AC_VERB_SET_DIGI_CONVERT_2, 1 << 5}, {} }; #define STAC_MONO_MUX \ { \ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \ .name = "Mono Mux", \ .count = 1, \ .info = stac92xx_mono_mux_enum_info, \ .get = stac92xx_mono_mux_enum_get, \ .put = stac92xx_mono_mux_enum_put, \ } #define STAC_ANALOG_LOOPBACK(verb_read, verb_write, cnt) \ { \ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \ .name = "Analog Loopback", \ .count = cnt, \ .info = stac92xx_aloopback_info, \ .get = stac92xx_aloopback_get, \ .put = stac92xx_aloopback_put, \ .private_value = verb_read | (verb_write << 16), \ } #define DC_BIAS(xname, idx, nid) \ { \ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \ .name = xname, \ .index = idx, \ .info = stac92xx_dc_bias_info, \ .get = stac92xx_dc_bias_get, \ .put = stac92xx_dc_bias_put, \ .private_value = nid, \ } static struct snd_kcontrol_new stac9200_mixer[] = { HDA_CODEC_VOLUME_MIN_MUTE("Master Playback Volume", 0xb, 0, HDA_OUTPUT), HDA_CODEC_MUTE("Master Playback Switch", 0xb, 0, HDA_OUTPUT), HDA_CODEC_VOLUME("Capture Volume", 0x0a, 0, HDA_OUTPUT), HDA_CODEC_MUTE("Capture Switch", 0x0a, 0, HDA_OUTPUT), { } /* end */ }; static struct snd_kcontrol_new stac92hd73xx_6ch_loopback[] = { STAC_ANALOG_LOOPBACK(0xFA0, 0x7A1, 3), {} }; static struct snd_kcontrol_new stac92hd73xx_8ch_loopback[] = { STAC_ANALOG_LOOPBACK(0xFA0, 0x7A1, 4), {} }; static struct snd_kcontrol_new stac92hd73xx_10ch_loopback[] = { STAC_ANALOG_LOOPBACK(0xFA0, 0x7A1, 5), {} }; static struct snd_kcontrol_new stac92hd71bxx_loopback[] = { STAC_ANALOG_LOOPBACK(0xFA0, 0x7A0, 2) }; static struct snd_kcontrol_new stac925x_mixer[] = { HDA_CODEC_VOLUME_MIN_MUTE("Master Playback Volume", 0xe, 0, HDA_OUTPUT), HDA_CODEC_MUTE("Master Playback Switch", 0x0e, 0, HDA_OUTPUT), { } /* end */ }; static struct snd_kcontrol_new stac9205_loopback[] = { STAC_ANALOG_LOOPBACK(0xFE0, 0x7E0, 1), {} }; static struct snd_kcontrol_new stac927x_loopback[] = { STAC_ANALOG_LOOPBACK(0xFEB, 0x7EB, 1), {} }; static struct snd_kcontrol_new stac_dmux_mixer = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Digital Input Source", /* count set later */ .info = stac92xx_dmux_enum_info, .get = stac92xx_dmux_enum_get, .put = stac92xx_dmux_enum_put, }; static struct snd_kcontrol_new stac_smux_mixer = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "IEC958 Playback Source", /* count set later */ .info = stac92xx_smux_enum_info, .get = stac92xx_smux_enum_get, .put = stac92xx_smux_enum_put, }; static const char * const slave_vols[] = { "Front Playback Volume", "Surround Playback Volume", "Center Playback Volume", "LFE Playback Volume", "Side Playback Volume", "Headphone Playback Volume", "Speaker Playback Volume", NULL }; static const char * const slave_sws[] = { "Front Playback Switch", "Surround Playback Switch", "Center Playback Switch", "LFE Playback Switch", "Side Playback Switch", "Headphone Playback Switch", "Speaker Playback Switch", "IEC958 Playback Switch", NULL }; static void stac92xx_free_kctls(struct hda_codec *codec); static int stac92xx_add_jack(struct hda_codec *codec, hda_nid_t nid, int type); static int stac92xx_build_controls(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; struct auto_pin_cfg *cfg = &spec->autocfg; hda_nid_t nid; int err; int i; if (spec->mixer) { err = snd_hda_add_new_ctls(codec, spec->mixer); if (err < 0) return err; } for (i = 0; i < spec->num_mixers; i++) { err = snd_hda_add_new_ctls(codec, spec->mixers[i]); if (err < 0) return err; } if (!spec->auto_mic && spec->num_dmuxes > 0 && snd_hda_get_bool_hint(codec, "separate_dmux") == 1) { stac_dmux_mixer.count = spec->num_dmuxes; err = snd_hda_ctl_add(codec, 0, snd_ctl_new1(&stac_dmux_mixer, codec)); if (err < 0) return err; } if (spec->num_smuxes > 0) { int wcaps = get_wcaps(codec, spec->multiout.dig_out_nid); struct hda_input_mux *smux = &spec->private_smux; /* check for mute support on SPDIF out */ if (wcaps & AC_WCAP_OUT_AMP) { snd_hda_add_imux_item(smux, "Off", 0, NULL); spec->spdif_mute = 1; } stac_smux_mixer.count = spec->num_smuxes; err = snd_hda_ctl_add(codec, 0, snd_ctl_new1(&stac_smux_mixer, codec)); if (err < 0) return err; } if (spec->multiout.dig_out_nid) { err = snd_hda_create_spdif_out_ctls(codec, spec->multiout.dig_out_nid); if (err < 0) return err; err = snd_hda_create_spdif_share_sw(codec, &spec->multiout); if (err < 0) return err; spec->multiout.share_spdif = 1; } if (spec->dig_in_nid && !(spec->gpio_dir & 0x01)) { err = snd_hda_create_spdif_in_ctls(codec, spec->dig_in_nid); if (err < 0) return err; } /* if we have no master control, let's create it */ if (!snd_hda_find_mixer_ctl(codec, "Master Playback Volume")) { unsigned int vmaster_tlv[4]; snd_hda_set_vmaster_tlv(codec, spec->multiout.dac_nids[0], HDA_OUTPUT, vmaster_tlv); /* correct volume offset */ vmaster_tlv[2] += vmaster_tlv[3] * spec->volume_offset; /* minimum value is actually mute */ vmaster_tlv[3] |= TLV_DB_SCALE_MUTE; err = snd_hda_add_vmaster(codec, "Master Playback Volume", vmaster_tlv, slave_vols); if (err < 0) return err; } if (!snd_hda_find_mixer_ctl(codec, "Master Playback Switch")) { err = snd_hda_add_vmaster(codec, "Master Playback Switch", NULL, slave_sws); if (err < 0) return err; } if (spec->aloopback_ctl && snd_hda_get_bool_hint(codec, "loopback") == 1) { err = snd_hda_add_new_ctls(codec, spec->aloopback_ctl); if (err < 0) return err; } stac92xx_free_kctls(codec); /* no longer needed */ /* create jack input elements */ if (spec->hp_detect) { for (i = 0; i < cfg->hp_outs; i++) { int type = SND_JACK_HEADPHONE; nid = cfg->hp_pins[i]; /* jack detection */ if (cfg->hp_outs == i) type |= SND_JACK_LINEOUT; err = stac92xx_add_jack(codec, nid, type); if (err < 0) return err; } } for (i = 0; i < cfg->line_outs; i++) { err = stac92xx_add_jack(codec, cfg->line_out_pins[i], SND_JACK_LINEOUT); if (err < 0) return err; } for (i = 0; i < cfg->num_inputs; i++) { nid = cfg->inputs[i].pin; err = stac92xx_add_jack(codec, nid, SND_JACK_MICROPHONE); if (err < 0) return err; } return 0; } static unsigned int ref9200_pin_configs[8] = { 0x01c47010, 0x01447010, 0x0221401f, 0x01114010, 0x02a19020, 0x01a19021, 0x90100140, 0x01813122, }; static unsigned int gateway9200_m4_pin_configs[8] = { 0x400000fe, 0x404500f4, 0x400100f0, 0x90110010, 0x400100f1, 0x02a1902e, 0x500000f2, 0x500000f3, }; static unsigned int gateway9200_m4_2_pin_configs[8] = { 0x400000fe, 0x404500f4, 0x400100f0, 0x90110010, 0x400100f1, 0x02a1902e, 0x500000f2, 0x500000f3, }; /* STAC 9200 pin configs for 102801A8 102801DE 102801E8 */ static unsigned int dell9200_d21_pin_configs[8] = { 0x400001f0, 0x400001f1, 0x02214030, 0x01014010, 0x02a19020, 0x01a19021, 0x90100140, 0x01813122, }; /* STAC 9200 pin configs for 102801C0 102801C1 */ static unsigned int dell9200_d22_pin_configs[8] = { 0x400001f0, 0x400001f1, 0x0221401f, 0x01014010, 0x01813020, 0x02a19021, 0x90100140, 0x400001f2, }; /* STAC 9200 pin configs for 102801C4 (Dell Dimension E310) 102801C5 102801C7 102801D9 102801DA 102801E3 */ static unsigned int dell9200_d23_pin_configs[8] = { 0x400001f0, 0x400001f1, 0x0221401f, 0x01014010, 0x01813020, 0x01a19021, 0x90100140, 0x400001f2, }; /* STAC 9200-32 pin configs for 102801B5 (Dell Inspiron 630m) 102801D8 (Dell Inspiron 640m) */ static unsigned int dell9200_m21_pin_configs[8] = { 0x40c003fa, 0x03441340, 0x0321121f, 0x90170310, 0x408003fb, 0x03a11020, 0x401003fc, 0x403003fd, }; /* STAC 9200-32 pin configs for 102801C2 (Dell Latitude D620) 102801C8 102801CC (Dell Latitude D820) 102801D4 102801D6 */ static unsigned int dell9200_m22_pin_configs[8] = { 0x40c003fa, 0x0144131f, 0x0321121f, 0x90170310, 0x90a70321, 0x03a11020, 0x401003fb, 0x40f000fc, }; /* STAC 9200-32 pin configs for 102801CE (Dell XPS M1710) 102801CF (Dell Precision M90) */ static unsigned int dell9200_m23_pin_configs[8] = { 0x40c003fa, 0x01441340, 0x0421421f, 0x90170310, 0x408003fb, 0x04a1102e, 0x90170311, 0x403003fc, }; /* STAC 9200-32 pin configs for 102801C9 102801CA 102801CB (Dell Latitude 120L) 102801D3 */ static unsigned int dell9200_m24_pin_configs[8] = { 0x40c003fa, 0x404003fb, 0x0321121f, 0x90170310, 0x408003fc, 0x03a11020, 0x401003fd, 0x403003fe, }; /* STAC 9200-32 pin configs for 102801BD (Dell Inspiron E1505n) 102801EE 102801EF */ static unsigned int dell9200_m25_pin_configs[8] = { 0x40c003fa, 0x01441340, 0x0421121f, 0x90170310, 0x408003fb, 0x04a11020, 0x401003fc, 0x403003fd, }; /* STAC 9200-32 pin configs for 102801F5 (Dell Inspiron 1501) 102801F6 */ static unsigned int dell9200_m26_pin_configs[8] = { 0x40c003fa, 0x404003fb, 0x0421121f, 0x90170310, 0x408003fc, 0x04a11020, 0x401003fd, 0x403003fe, }; /* STAC 9200-32 102801CD (Dell Inspiron E1705/9400) */ static unsigned int dell9200_m27_pin_configs[8] = { 0x40c003fa, 0x01441340, 0x0421121f, 0x90170310, 0x90170310, 0x04a11020, 0x90170310, 0x40f003fc, }; static unsigned int oqo9200_pin_configs[8] = { 0x40c000f0, 0x404000f1, 0x0221121f, 0x02211210, 0x90170111, 0x90a70120, 0x400000f2, 0x400000f3, }; static unsigned int *stac9200_brd_tbl[STAC_9200_MODELS] = { [STAC_REF] = ref9200_pin_configs, [STAC_9200_OQO] = oqo9200_pin_configs, [STAC_9200_DELL_D21] = dell9200_d21_pin_configs, [STAC_9200_DELL_D22] = dell9200_d22_pin_configs, [STAC_9200_DELL_D23] = dell9200_d23_pin_configs, [STAC_9200_DELL_M21] = dell9200_m21_pin_configs, [STAC_9200_DELL_M22] = dell9200_m22_pin_configs, [STAC_9200_DELL_M23] = dell9200_m23_pin_configs, [STAC_9200_DELL_M24] = dell9200_m24_pin_configs, [STAC_9200_DELL_M25] = dell9200_m25_pin_configs, [STAC_9200_DELL_M26] = dell9200_m26_pin_configs, [STAC_9200_DELL_M27] = dell9200_m27_pin_configs, [STAC_9200_M4] = gateway9200_m4_pin_configs, [STAC_9200_M4_2] = gateway9200_m4_2_pin_configs, [STAC_9200_PANASONIC] = ref9200_pin_configs, }; static const char * const stac9200_models[STAC_9200_MODELS] = { [STAC_AUTO] = "auto", [STAC_REF] = "ref", [STAC_9200_OQO] = "oqo", [STAC_9200_DELL_D21] = "dell-d21", [STAC_9200_DELL_D22] = "dell-d22", [STAC_9200_DELL_D23] = "dell-d23", [STAC_9200_DELL_M21] = "dell-m21", [STAC_9200_DELL_M22] = "dell-m22", [STAC_9200_DELL_M23] = "dell-m23", [STAC_9200_DELL_M24] = "dell-m24", [STAC_9200_DELL_M25] = "dell-m25", [STAC_9200_DELL_M26] = "dell-m26", [STAC_9200_DELL_M27] = "dell-m27", [STAC_9200_M4] = "gateway-m4", [STAC_9200_M4_2] = "gateway-m4-2", [STAC_9200_PANASONIC] = "panasonic", }; static struct snd_pci_quirk stac9200_cfg_tbl[] = { /* SigmaTel reference board */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x2668, "DFI LanParty", STAC_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_DFI, 0x3101, "DFI LanParty", STAC_REF), /* Dell laptops have BIOS problem */ SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01a8, "unknown Dell", STAC_9200_DELL_D21), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01b5, "Dell Inspiron 630m", STAC_9200_DELL_M21), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01bd, "Dell Inspiron E1505n", STAC_9200_DELL_M25), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01c0, "unknown Dell", STAC_9200_DELL_D22), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01c1, "unknown Dell", STAC_9200_DELL_D22), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01c2, "Dell Latitude D620", STAC_9200_DELL_M22), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01c5, "unknown Dell", STAC_9200_DELL_D23), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01c7, "unknown Dell", STAC_9200_DELL_D23), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01c8, "unknown Dell", STAC_9200_DELL_M22), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01c9, "unknown Dell", STAC_9200_DELL_M24), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01ca, "unknown Dell", STAC_9200_DELL_M24), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01cb, "Dell Latitude 120L", STAC_9200_DELL_M24), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01cc, "Dell Latitude D820", STAC_9200_DELL_M22), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01cd, "Dell Inspiron E1705/9400", STAC_9200_DELL_M27), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01ce, "Dell XPS M1710", STAC_9200_DELL_M23), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01cf, "Dell Precision M90", STAC_9200_DELL_M23), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01d3, "unknown Dell", STAC_9200_DELL_M22), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01d4, "unknown Dell", STAC_9200_DELL_M22), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01d6, "unknown Dell", STAC_9200_DELL_M22), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01d8, "Dell Inspiron 640m", STAC_9200_DELL_M21), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01d9, "unknown Dell", STAC_9200_DELL_D23), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01da, "unknown Dell", STAC_9200_DELL_D23), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01de, "unknown Dell", STAC_9200_DELL_D21), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01e3, "unknown Dell", STAC_9200_DELL_D23), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01e8, "unknown Dell", STAC_9200_DELL_D21), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01ee, "unknown Dell", STAC_9200_DELL_M25), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01ef, "unknown Dell", STAC_9200_DELL_M25), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01f5, "Dell Inspiron 1501", STAC_9200_DELL_M26), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01f6, "unknown Dell", STAC_9200_DELL_M26), /* Panasonic */ SND_PCI_QUIRK(0x10f7, 0x8338, "Panasonic CF-74", STAC_9200_PANASONIC), /* Gateway machines needs EAPD to be set on resume */ SND_PCI_QUIRK(0x107b, 0x0205, "Gateway S-7110M", STAC_9200_M4), SND_PCI_QUIRK(0x107b, 0x0317, "Gateway MT3423, MX341*", STAC_9200_M4_2), SND_PCI_QUIRK(0x107b, 0x0318, "Gateway ML3019, MT3707", STAC_9200_M4_2), /* OQO Mobile */ SND_PCI_QUIRK(0x1106, 0x3288, "OQO Model 2", STAC_9200_OQO), {} /* terminator */ }; static unsigned int ref925x_pin_configs[8] = { 0x40c003f0, 0x424503f2, 0x01813022, 0x02a19021, 0x90a70320, 0x02214210, 0x01019020, 0x9033032e, }; static unsigned int stac925xM1_pin_configs[8] = { 0x40c003f4, 0x424503f2, 0x400000f3, 0x02a19020, 0x40a000f0, 0x90100210, 0x400003f1, 0x9033032e, }; static unsigned int stac925xM1_2_pin_configs[8] = { 0x40c003f4, 0x424503f2, 0x400000f3, 0x02a19020, 0x40a000f0, 0x90100210, 0x400003f1, 0x9033032e, }; static unsigned int stac925xM2_pin_configs[8] = { 0x40c003f4, 0x424503f2, 0x400000f3, 0x02a19020, 0x40a000f0, 0x90100210, 0x400003f1, 0x9033032e, }; static unsigned int stac925xM2_2_pin_configs[8] = { 0x40c003f4, 0x424503f2, 0x400000f3, 0x02a19020, 0x40a000f0, 0x90100210, 0x400003f1, 0x9033032e, }; static unsigned int stac925xM3_pin_configs[8] = { 0x40c003f4, 0x424503f2, 0x400000f3, 0x02a19020, 0x40a000f0, 0x90100210, 0x400003f1, 0x503303f3, }; static unsigned int stac925xM5_pin_configs[8] = { 0x40c003f4, 0x424503f2, 0x400000f3, 0x02a19020, 0x40a000f0, 0x90100210, 0x400003f1, 0x9033032e, }; static unsigned int stac925xM6_pin_configs[8] = { 0x40c003f4, 0x424503f2, 0x400000f3, 0x02a19020, 0x40a000f0, 0x90100210, 0x400003f1, 0x90330320, }; static unsigned int *stac925x_brd_tbl[STAC_925x_MODELS] = { [STAC_REF] = ref925x_pin_configs, [STAC_M1] = stac925xM1_pin_configs, [STAC_M1_2] = stac925xM1_2_pin_configs, [STAC_M2] = stac925xM2_pin_configs, [STAC_M2_2] = stac925xM2_2_pin_configs, [STAC_M3] = stac925xM3_pin_configs, [STAC_M5] = stac925xM5_pin_configs, [STAC_M6] = stac925xM6_pin_configs, }; static const char * const stac925x_models[STAC_925x_MODELS] = { [STAC_925x_AUTO] = "auto", [STAC_REF] = "ref", [STAC_M1] = "m1", [STAC_M1_2] = "m1-2", [STAC_M2] = "m2", [STAC_M2_2] = "m2-2", [STAC_M3] = "m3", [STAC_M5] = "m5", [STAC_M6] = "m6", }; static struct snd_pci_quirk stac925x_codec_id_cfg_tbl[] = { SND_PCI_QUIRK(0x107b, 0x0316, "Gateway M255", STAC_M2), SND_PCI_QUIRK(0x107b, 0x0366, "Gateway MP6954", STAC_M5), SND_PCI_QUIRK(0x107b, 0x0461, "Gateway NX560XL", STAC_M1), SND_PCI_QUIRK(0x107b, 0x0681, "Gateway NX860", STAC_M2), SND_PCI_QUIRK(0x107b, 0x0367, "Gateway MX6453", STAC_M1_2), /* Not sure about the brand name for those */ SND_PCI_QUIRK(0x107b, 0x0281, "Gateway mobile", STAC_M1), SND_PCI_QUIRK(0x107b, 0x0507, "Gateway mobile", STAC_M3), SND_PCI_QUIRK(0x107b, 0x0281, "Gateway mobile", STAC_M6), SND_PCI_QUIRK(0x107b, 0x0685, "Gateway mobile", STAC_M2_2), {} /* terminator */ }; static struct snd_pci_quirk stac925x_cfg_tbl[] = { /* SigmaTel reference board */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x2668, "DFI LanParty", STAC_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_DFI, 0x3101, "DFI LanParty", STAC_REF), SND_PCI_QUIRK(0x8384, 0x7632, "Stac9202 Reference Board", STAC_REF), /* Default table for unknown ID */ SND_PCI_QUIRK(0x1002, 0x437b, "Gateway mobile", STAC_M2_2), {} /* terminator */ }; static unsigned int ref92hd73xx_pin_configs[13] = { 0x02214030, 0x02a19040, 0x01a19020, 0x02214030, 0x0181302e, 0x01014010, 0x01014020, 0x01014030, 0x02319040, 0x90a000f0, 0x90a000f0, 0x01452050, 0x01452050, }; static unsigned int dell_m6_pin_configs[13] = { 0x0321101f, 0x4f00000f, 0x4f0000f0, 0x90170110, 0x03a11020, 0x0321101f, 0x4f0000f0, 0x4f0000f0, 0x4f0000f0, 0x90a60160, 0x4f0000f0, 0x4f0000f0, 0x4f0000f0, }; static unsigned int alienware_m17x_pin_configs[13] = { 0x0321101f, 0x0321101f, 0x03a11020, 0x03014020, 0x90170110, 0x4f0000f0, 0x4f0000f0, 0x4f0000f0, 0x4f0000f0, 0x90a60160, 0x4f0000f0, 0x4f0000f0, 0x904601b0, }; static unsigned int intel_dg45id_pin_configs[13] = { 0x02214230, 0x02A19240, 0x01013214, 0x01014210, 0x01A19250, 0x01011212, 0x01016211 }; static unsigned int *stac92hd73xx_brd_tbl[STAC_92HD73XX_MODELS] = { [STAC_92HD73XX_REF] = ref92hd73xx_pin_configs, [STAC_DELL_M6_AMIC] = dell_m6_pin_configs, [STAC_DELL_M6_DMIC] = dell_m6_pin_configs, [STAC_DELL_M6_BOTH] = dell_m6_pin_configs, [STAC_DELL_EQ] = dell_m6_pin_configs, [STAC_ALIENWARE_M17X] = alienware_m17x_pin_configs, [STAC_92HD73XX_INTEL] = intel_dg45id_pin_configs, }; static const char * const stac92hd73xx_models[STAC_92HD73XX_MODELS] = { [STAC_92HD73XX_AUTO] = "auto", [STAC_92HD73XX_NO_JD] = "no-jd", [STAC_92HD73XX_REF] = "ref", [STAC_92HD73XX_INTEL] = "intel", [STAC_DELL_M6_AMIC] = "dell-m6-amic", [STAC_DELL_M6_DMIC] = "dell-m6-dmic", [STAC_DELL_M6_BOTH] = "dell-m6", [STAC_DELL_EQ] = "dell-eq", [STAC_ALIENWARE_M17X] = "alienware", }; static struct snd_pci_quirk stac92hd73xx_cfg_tbl[] = { /* SigmaTel reference board */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x2668, "DFI LanParty", STAC_92HD73XX_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_DFI, 0x3101, "DFI LanParty", STAC_92HD73XX_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x5002, "Intel DG45ID", STAC_92HD73XX_INTEL), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x5003, "Intel DG45FC", STAC_92HD73XX_INTEL), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0254, "Dell Studio 1535", STAC_DELL_M6_DMIC), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0255, "unknown Dell", STAC_DELL_M6_DMIC), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0256, "unknown Dell", STAC_DELL_M6_BOTH), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0257, "unknown Dell", STAC_DELL_M6_BOTH), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x025e, "unknown Dell", STAC_DELL_M6_AMIC), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x025f, "unknown Dell", STAC_DELL_M6_AMIC), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0271, "unknown Dell", STAC_DELL_M6_DMIC), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0272, "unknown Dell", STAC_DELL_M6_DMIC), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x029f, "Dell Studio 1537", STAC_DELL_M6_DMIC), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x02a0, "Dell Studio 17", STAC_DELL_M6_DMIC), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x02be, "Dell Studio 1555", STAC_DELL_M6_DMIC), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x02bd, "Dell Studio 1557", STAC_DELL_M6_DMIC), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x02fe, "Dell Studio XPS 1645", STAC_DELL_M6_BOTH), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0413, "Dell Studio 1558", STAC_DELL_M6_BOTH), {} /* terminator */ }; static struct snd_pci_quirk stac92hd73xx_codec_id_cfg_tbl[] = { SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x02a1, "Alienware M17x", STAC_ALIENWARE_M17X), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x043a, "Alienware M17x", STAC_ALIENWARE_M17X), {} /* terminator */ }; static unsigned int ref92hd83xxx_pin_configs[10] = { 0x02214030, 0x02211010, 0x02a19020, 0x02170130, 0x01014050, 0x01819040, 0x01014020, 0x90a3014e, 0x01451160, 0x98560170, }; static unsigned int dell_s14_pin_configs[10] = { 0x0221403f, 0x0221101f, 0x02a19020, 0x90170110, 0x40f000f0, 0x40f000f0, 0x40f000f0, 0x90a60160, 0x40f000f0, 0x40f000f0, }; static unsigned int hp_dv7_4000_pin_configs[10] = { 0x03a12050, 0x0321201f, 0x40f000f0, 0x90170110, 0x40f000f0, 0x40f000f0, 0x90170110, 0xd5a30140, 0x40f000f0, 0x40f000f0, }; static unsigned int *stac92hd83xxx_brd_tbl[STAC_92HD83XXX_MODELS] = { [STAC_92HD83XXX_REF] = ref92hd83xxx_pin_configs, [STAC_92HD83XXX_PWR_REF] = ref92hd83xxx_pin_configs, [STAC_DELL_S14] = dell_s14_pin_configs, [STAC_HP_DV7_4000] = hp_dv7_4000_pin_configs, }; static const char * const stac92hd83xxx_models[STAC_92HD83XXX_MODELS] = { [STAC_92HD83XXX_AUTO] = "auto", [STAC_92HD83XXX_REF] = "ref", [STAC_92HD83XXX_PWR_REF] = "mic-ref", [STAC_DELL_S14] = "dell-s14", [STAC_92HD83XXX_HP] = "hp", [STAC_HP_DV7_4000] = "hp-dv7-4000", }; static struct snd_pci_quirk stac92hd83xxx_cfg_tbl[] = { /* SigmaTel reference board */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x2668, "DFI LanParty", STAC_92HD83XXX_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_DFI, 0x3101, "DFI LanParty", STAC_92HD83XXX_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x02ba, "unknown Dell", STAC_DELL_S14), SND_PCI_QUIRK_MASK(PCI_VENDOR_ID_HP, 0xff00, 0x3600, "HP", STAC_92HD83XXX_HP), {} /* terminator */ }; static unsigned int ref92hd71bxx_pin_configs[STAC92HD71BXX_NUM_PINS] = { 0x02214030, 0x02a19040, 0x01a19020, 0x01014010, 0x0181302e, 0x01014010, 0x01019020, 0x90a000f0, 0x90a000f0, 0x01452050, 0x01452050, 0x00000000, 0x00000000 }; static unsigned int dell_m4_1_pin_configs[STAC92HD71BXX_NUM_PINS] = { 0x0421101f, 0x04a11221, 0x40f000f0, 0x90170110, 0x23a1902e, 0x23014250, 0x40f000f0, 0x90a000f0, 0x40f000f0, 0x4f0000f0, 0x4f0000f0, 0x00000000, 0x00000000 }; static unsigned int dell_m4_2_pin_configs[STAC92HD71BXX_NUM_PINS] = { 0x0421101f, 0x04a11221, 0x90a70330, 0x90170110, 0x23a1902e, 0x23014250, 0x40f000f0, 0x40f000f0, 0x40f000f0, 0x044413b0, 0x044413b0, 0x00000000, 0x00000000 }; static unsigned int dell_m4_3_pin_configs[STAC92HD71BXX_NUM_PINS] = { 0x0421101f, 0x04a11221, 0x90a70330, 0x90170110, 0x40f000f0, 0x40f000f0, 0x40f000f0, 0x90a000f0, 0x40f000f0, 0x044413b0, 0x044413b0, 0x00000000, 0x00000000 }; static unsigned int *stac92hd71bxx_brd_tbl[STAC_92HD71BXX_MODELS] = { [STAC_92HD71BXX_REF] = ref92hd71bxx_pin_configs, [STAC_DELL_M4_1] = dell_m4_1_pin_configs, [STAC_DELL_M4_2] = dell_m4_2_pin_configs, [STAC_DELL_M4_3] = dell_m4_3_pin_configs, [STAC_HP_M4] = NULL, [STAC_HP_DV4] = NULL, [STAC_HP_DV5] = NULL, [STAC_HP_HDX] = NULL, [STAC_HP_DV4_1222NR] = NULL, }; static const char * const stac92hd71bxx_models[STAC_92HD71BXX_MODELS] = { [STAC_92HD71BXX_AUTO] = "auto", [STAC_92HD71BXX_REF] = "ref", [STAC_DELL_M4_1] = "dell-m4-1", [STAC_DELL_M4_2] = "dell-m4-2", [STAC_DELL_M4_3] = "dell-m4-3", [STAC_HP_M4] = "hp-m4", [STAC_HP_DV4] = "hp-dv4", [STAC_HP_DV5] = "hp-dv5", [STAC_HP_HDX] = "hp-hdx", [STAC_HP_DV4_1222NR] = "hp-dv4-1222nr", }; static struct snd_pci_quirk stac92hd71bxx_cfg_tbl[] = { /* SigmaTel reference board */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x2668, "DFI LanParty", STAC_92HD71BXX_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_DFI, 0x3101, "DFI LanParty", STAC_92HD71BXX_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_HP, 0x30fb, "HP dv4-1222nr", STAC_HP_DV4_1222NR), SND_PCI_QUIRK_MASK(PCI_VENDOR_ID_HP, 0xfff0, 0x1720, "HP", STAC_HP_DV5), SND_PCI_QUIRK_MASK(PCI_VENDOR_ID_HP, 0xfff0, 0x3080, "HP", STAC_HP_DV5), SND_PCI_QUIRK_MASK(PCI_VENDOR_ID_HP, 0xfff0, 0x30f0, "HP dv4-7", STAC_HP_DV4), SND_PCI_QUIRK_MASK(PCI_VENDOR_ID_HP, 0xfff0, 0x3600, "HP dv4-7", STAC_HP_DV5), SND_PCI_QUIRK(PCI_VENDOR_ID_HP, 0x3610, "HP HDX", STAC_HP_HDX), /* HDX18 */ SND_PCI_QUIRK(PCI_VENDOR_ID_HP, 0x361a, "HP mini 1000", STAC_HP_M4), SND_PCI_QUIRK(PCI_VENDOR_ID_HP, 0x361b, "HP HDX", STAC_HP_HDX), /* HDX16 */ SND_PCI_QUIRK_MASK(PCI_VENDOR_ID_HP, 0xfff0, 0x3620, "HP dv6", STAC_HP_DV5), SND_PCI_QUIRK(PCI_VENDOR_ID_HP, 0x3061, "HP dv6", STAC_HP_DV5), /* HP dv6-1110ax */ SND_PCI_QUIRK(PCI_VENDOR_ID_HP, 0x363e, "HP DV6", STAC_HP_DV5), SND_PCI_QUIRK_MASK(PCI_VENDOR_ID_HP, 0xfff0, 0x7010, "HP", STAC_HP_DV5), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0233, "unknown Dell", STAC_DELL_M4_1), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0234, "unknown Dell", STAC_DELL_M4_1), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0250, "unknown Dell", STAC_DELL_M4_1), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x024f, "unknown Dell", STAC_DELL_M4_1), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x024d, "unknown Dell", STAC_DELL_M4_1), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0251, "unknown Dell", STAC_DELL_M4_1), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0277, "unknown Dell", STAC_DELL_M4_1), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0263, "unknown Dell", STAC_DELL_M4_2), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0265, "unknown Dell", STAC_DELL_M4_2), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0262, "unknown Dell", STAC_DELL_M4_2), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0264, "unknown Dell", STAC_DELL_M4_2), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x02aa, "unknown Dell", STAC_DELL_M4_3), {} /* terminator */ }; static unsigned int ref922x_pin_configs[10] = { 0x01014010, 0x01016011, 0x01012012, 0x0221401f, 0x01813122, 0x01011014, 0x01441030, 0x01c41030, 0x40000100, 0x40000100, }; /* STAC 922X pin configs for 102801A7 102801AB 102801A9 102801D1 102801D2 */ static unsigned int dell_922x_d81_pin_configs[10] = { 0x02214030, 0x01a19021, 0x01111012, 0x01114010, 0x02a19020, 0x01117011, 0x400001f0, 0x400001f1, 0x01813122, 0x400001f2, }; /* STAC 922X pin configs for 102801AC 102801D0 */ static unsigned int dell_922x_d82_pin_configs[10] = { 0x02214030, 0x01a19021, 0x01111012, 0x01114010, 0x02a19020, 0x01117011, 0x01451140, 0x400001f0, 0x01813122, 0x400001f1, }; /* STAC 922X pin configs for 102801BF */ static unsigned int dell_922x_m81_pin_configs[10] = { 0x0321101f, 0x01112024, 0x01111222, 0x91174220, 0x03a11050, 0x01116221, 0x90a70330, 0x01452340, 0x40C003f1, 0x405003f0, }; /* STAC 9221 A1 pin configs for 102801D7 (Dell XPS M1210) */ static unsigned int dell_922x_m82_pin_configs[10] = { 0x02211211, 0x408103ff, 0x02a1123e, 0x90100310, 0x408003f1, 0x0221121f, 0x03451340, 0x40c003f2, 0x508003f3, 0x405003f4, }; static unsigned int d945gtp3_pin_configs[10] = { 0x0221401f, 0x01a19022, 0x01813021, 0x01014010, 0x40000100, 0x40000100, 0x40000100, 0x40000100, 0x02a19120, 0x40000100, }; static unsigned int d945gtp5_pin_configs[10] = { 0x0221401f, 0x01011012, 0x01813024, 0x01014010, 0x01a19021, 0x01016011, 0x01452130, 0x40000100, 0x02a19320, 0x40000100, }; static unsigned int intel_mac_v1_pin_configs[10] = { 0x0121e21f, 0x400000ff, 0x9017e110, 0x400000fd, 0x400000fe, 0x0181e020, 0x1145e030, 0x11c5e240, 0x400000fc, 0x400000fb, }; static unsigned int intel_mac_v2_pin_configs[10] = { 0x0121e21f, 0x90a7012e, 0x9017e110, 0x400000fd, 0x400000fe, 0x0181e020, 0x1145e230, 0x500000fa, 0x400000fc, 0x400000fb, }; static unsigned int intel_mac_v3_pin_configs[10] = { 0x0121e21f, 0x90a7012e, 0x9017e110, 0x400000fd, 0x400000fe, 0x0181e020, 0x1145e230, 0x11c5e240, 0x400000fc, 0x400000fb, }; static unsigned int intel_mac_v4_pin_configs[10] = { 0x0321e21f, 0x03a1e02e, 0x9017e110, 0x9017e11f, 0x400000fe, 0x0381e020, 0x1345e230, 0x13c5e240, 0x400000fc, 0x400000fb, }; static unsigned int intel_mac_v5_pin_configs[10] = { 0x0321e21f, 0x03a1e02e, 0x9017e110, 0x9017e11f, 0x400000fe, 0x0381e020, 0x1345e230, 0x13c5e240, 0x400000fc, 0x400000fb, }; static unsigned int ecs202_pin_configs[10] = { 0x0221401f, 0x02a19020, 0x01a19020, 0x01114010, 0x408000f0, 0x01813022, 0x074510a0, 0x40c400f1, 0x9037012e, 0x40e000f2, }; static unsigned int *stac922x_brd_tbl[STAC_922X_MODELS] = { [STAC_D945_REF] = ref922x_pin_configs, [STAC_D945GTP3] = d945gtp3_pin_configs, [STAC_D945GTP5] = d945gtp5_pin_configs, [STAC_INTEL_MAC_V1] = intel_mac_v1_pin_configs, [STAC_INTEL_MAC_V2] = intel_mac_v2_pin_configs, [STAC_INTEL_MAC_V3] = intel_mac_v3_pin_configs, [STAC_INTEL_MAC_V4] = intel_mac_v4_pin_configs, [STAC_INTEL_MAC_V5] = intel_mac_v5_pin_configs, [STAC_INTEL_MAC_AUTO] = intel_mac_v3_pin_configs, /* for backward compatibility */ [STAC_MACMINI] = intel_mac_v3_pin_configs, [STAC_MACBOOK] = intel_mac_v5_pin_configs, [STAC_MACBOOK_PRO_V1] = intel_mac_v3_pin_configs, [STAC_MACBOOK_PRO_V2] = intel_mac_v3_pin_configs, [STAC_IMAC_INTEL] = intel_mac_v2_pin_configs, [STAC_IMAC_INTEL_20] = intel_mac_v3_pin_configs, [STAC_ECS_202] = ecs202_pin_configs, [STAC_922X_DELL_D81] = dell_922x_d81_pin_configs, [STAC_922X_DELL_D82] = dell_922x_d82_pin_configs, [STAC_922X_DELL_M81] = dell_922x_m81_pin_configs, [STAC_922X_DELL_M82] = dell_922x_m82_pin_configs, }; static const char * const stac922x_models[STAC_922X_MODELS] = { [STAC_922X_AUTO] = "auto", [STAC_D945_REF] = "ref", [STAC_D945GTP5] = "5stack", [STAC_D945GTP3] = "3stack", [STAC_INTEL_MAC_V1] = "intel-mac-v1", [STAC_INTEL_MAC_V2] = "intel-mac-v2", [STAC_INTEL_MAC_V3] = "intel-mac-v3", [STAC_INTEL_MAC_V4] = "intel-mac-v4", [STAC_INTEL_MAC_V5] = "intel-mac-v5", [STAC_INTEL_MAC_AUTO] = "intel-mac-auto", /* for backward compatibility */ [STAC_MACMINI] = "macmini", [STAC_MACBOOK] = "macbook", [STAC_MACBOOK_PRO_V1] = "macbook-pro-v1", [STAC_MACBOOK_PRO_V2] = "macbook-pro", [STAC_IMAC_INTEL] = "imac-intel", [STAC_IMAC_INTEL_20] = "imac-intel-20", [STAC_ECS_202] = "ecs202", [STAC_922X_DELL_D81] = "dell-d81", [STAC_922X_DELL_D82] = "dell-d82", [STAC_922X_DELL_M81] = "dell-m81", [STAC_922X_DELL_M82] = "dell-m82", }; static struct snd_pci_quirk stac922x_cfg_tbl[] = { /* SigmaTel reference board */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x2668, "DFI LanParty", STAC_D945_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_DFI, 0x3101, "DFI LanParty", STAC_D945_REF), /* Intel 945G based systems */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0101, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0202, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0606, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0601, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0111, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x1115, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x1116, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x1117, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x1118, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x1119, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x8826, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x5049, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x5055, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x5048, "Intel D945G", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0110, "Intel D945G", STAC_D945GTP3), /* Intel D945G 5-stack systems */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0404, "Intel D945G", STAC_D945GTP5), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0303, "Intel D945G", STAC_D945GTP5), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0013, "Intel D945G", STAC_D945GTP5), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0417, "Intel D945G", STAC_D945GTP5), /* Intel 945P based systems */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0b0b, "Intel D945P", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0112, "Intel D945P", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0d0d, "Intel D945P", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0909, "Intel D945P", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0505, "Intel D945P", STAC_D945GTP3), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0707, "Intel D945P", STAC_D945GTP5), /* other intel */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x0204, "Intel D945", STAC_D945_REF), /* other systems */ /* Apple Intel Mac (Mac Mini, MacBook, MacBook Pro...) */ SND_PCI_QUIRK(0x8384, 0x7680, "Mac", STAC_INTEL_MAC_AUTO), /* Dell systems */ SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01a7, "unknown Dell", STAC_922X_DELL_D81), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01a9, "unknown Dell", STAC_922X_DELL_D81), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01ab, "unknown Dell", STAC_922X_DELL_D81), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01ac, "unknown Dell", STAC_922X_DELL_D82), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01bf, "unknown Dell", STAC_922X_DELL_M81), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01d0, "unknown Dell", STAC_922X_DELL_D82), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01d1, "unknown Dell", STAC_922X_DELL_D81), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01d2, "unknown Dell", STAC_922X_DELL_D81), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01d7, "Dell XPS M1210", STAC_922X_DELL_M82), /* ECS/PC Chips boards */ SND_PCI_QUIRK_MASK(0x1019, 0xf000, 0x2000, "ECS/PC chips", STAC_ECS_202), {} /* terminator */ }; static unsigned int ref927x_pin_configs[14] = { 0x02214020, 0x02a19080, 0x0181304e, 0x01014010, 0x01a19040, 0x01011012, 0x01016011, 0x0101201f, 0x183301f0, 0x18a001f0, 0x18a001f0, 0x01442070, 0x01c42190, 0x40000100, }; static unsigned int d965_3st_pin_configs[14] = { 0x0221401f, 0x02a19120, 0x40000100, 0x01014011, 0x01a19021, 0x01813024, 0x40000100, 0x40000100, 0x40000100, 0x40000100, 0x40000100, 0x40000100, 0x40000100, 0x40000100 }; static unsigned int d965_5st_pin_configs[14] = { 0x02214020, 0x02a19080, 0x0181304e, 0x01014010, 0x01a19040, 0x01011012, 0x01016011, 0x40000100, 0x40000100, 0x40000100, 0x40000100, 0x01442070, 0x40000100, 0x40000100 }; static unsigned int d965_5st_no_fp_pin_configs[14] = { 0x40000100, 0x40000100, 0x0181304e, 0x01014010, 0x01a19040, 0x01011012, 0x01016011, 0x40000100, 0x40000100, 0x40000100, 0x40000100, 0x01442070, 0x40000100, 0x40000100 }; static unsigned int dell_3st_pin_configs[14] = { 0x02211230, 0x02a11220, 0x01a19040, 0x01114210, 0x01111212, 0x01116211, 0x01813050, 0x01112214, 0x403003fa, 0x90a60040, 0x90a60040, 0x404003fb, 0x40c003fc, 0x40000100 }; static unsigned int *stac927x_brd_tbl[STAC_927X_MODELS] = { [STAC_D965_REF_NO_JD] = ref927x_pin_configs, [STAC_D965_REF] = ref927x_pin_configs, [STAC_D965_3ST] = d965_3st_pin_configs, [STAC_D965_5ST] = d965_5st_pin_configs, [STAC_D965_5ST_NO_FP] = d965_5st_no_fp_pin_configs, [STAC_DELL_3ST] = dell_3st_pin_configs, [STAC_DELL_BIOS] = NULL, [STAC_927X_VOLKNOB] = NULL, }; static const char * const stac927x_models[STAC_927X_MODELS] = { [STAC_927X_AUTO] = "auto", [STAC_D965_REF_NO_JD] = "ref-no-jd", [STAC_D965_REF] = "ref", [STAC_D965_3ST] = "3stack", [STAC_D965_5ST] = "5stack", [STAC_D965_5ST_NO_FP] = "5stack-no-fp", [STAC_DELL_3ST] = "dell-3stack", [STAC_DELL_BIOS] = "dell-bios", [STAC_927X_VOLKNOB] = "volknob", }; static struct snd_pci_quirk stac927x_cfg_tbl[] = { /* SigmaTel reference board */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x2668, "DFI LanParty", STAC_D965_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_DFI, 0x3101, "DFI LanParty", STAC_D965_REF), /* Intel 946 based systems */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x3d01, "Intel D946", STAC_D965_3ST), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0xa301, "Intel D946", STAC_D965_3ST), /* 965 based 3 stack systems */ SND_PCI_QUIRK_MASK(PCI_VENDOR_ID_INTEL, 0xff00, 0x2100, "Intel D965", STAC_D965_3ST), SND_PCI_QUIRK_MASK(PCI_VENDOR_ID_INTEL, 0xff00, 0x2000, "Intel D965", STAC_D965_3ST), /* Dell 3 stack systems */ SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01dd, "Dell Dimension E520", STAC_DELL_3ST), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01ed, "Dell ", STAC_DELL_3ST), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01f4, "Dell ", STAC_DELL_3ST), /* Dell 3 stack systems with verb table in BIOS */ SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01f3, "Dell Inspiron 1420", STAC_DELL_BIOS), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01f7, "Dell XPS M1730", STAC_DELL_BIOS), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0227, "Dell Vostro 1400 ", STAC_DELL_BIOS), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x022e, "Dell ", STAC_DELL_BIOS), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x022f, "Dell Inspiron 1525", STAC_DELL_BIOS), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0242, "Dell ", STAC_DELL_BIOS), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0243, "Dell ", STAC_DELL_BIOS), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x02ff, "Dell ", STAC_DELL_BIOS), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0209, "Dell XPS 1330", STAC_DELL_BIOS), /* 965 based 5 stack systems */ SND_PCI_QUIRK_MASK(PCI_VENDOR_ID_INTEL, 0xff00, 0x2300, "Intel D965", STAC_D965_5ST), SND_PCI_QUIRK_MASK(PCI_VENDOR_ID_INTEL, 0xff00, 0x2500, "Intel D965", STAC_D965_5ST), /* volume-knob fixes */ SND_PCI_QUIRK_VENDOR(0x10cf, "FSC", STAC_927X_VOLKNOB), {} /* terminator */ }; static unsigned int ref9205_pin_configs[12] = { 0x40000100, 0x40000100, 0x01016011, 0x01014010, 0x01813122, 0x01a19021, 0x01019020, 0x40000100, 0x90a000f0, 0x90a000f0, 0x01441030, 0x01c41030 }; /* STAC 9205 pin configs for 102801F1 102801F2 102801FC 102801FD 10280204 1028021F 10280228 (Dell Vostro 1500) 10280229 (Dell Vostro 1700) */ static unsigned int dell_9205_m42_pin_configs[12] = { 0x0321101F, 0x03A11020, 0x400003FA, 0x90170310, 0x400003FB, 0x400003FC, 0x400003FD, 0x40F000F9, 0x90A60330, 0x400003FF, 0x0144131F, 0x40C003FE, }; /* STAC 9205 pin configs for 102801F9 102801FA 102801FE 102801FF (Dell Precision M4300) 10280206 10280200 10280201 */ static unsigned int dell_9205_m43_pin_configs[12] = { 0x0321101f, 0x03a11020, 0x90a70330, 0x90170310, 0x400000fe, 0x400000ff, 0x400000fd, 0x40f000f9, 0x400000fa, 0x400000fc, 0x0144131f, 0x40c003f8, }; static unsigned int dell_9205_m44_pin_configs[12] = { 0x0421101f, 0x04a11020, 0x400003fa, 0x90170310, 0x400003fb, 0x400003fc, 0x400003fd, 0x400003f9, 0x90a60330, 0x400003ff, 0x01441340, 0x40c003fe, }; static unsigned int *stac9205_brd_tbl[STAC_9205_MODELS] = { [STAC_9205_REF] = ref9205_pin_configs, [STAC_9205_DELL_M42] = dell_9205_m42_pin_configs, [STAC_9205_DELL_M43] = dell_9205_m43_pin_configs, [STAC_9205_DELL_M44] = dell_9205_m44_pin_configs, [STAC_9205_EAPD] = NULL, }; static const char * const stac9205_models[STAC_9205_MODELS] = { [STAC_9205_AUTO] = "auto", [STAC_9205_REF] = "ref", [STAC_9205_DELL_M42] = "dell-m42", [STAC_9205_DELL_M43] = "dell-m43", [STAC_9205_DELL_M44] = "dell-m44", [STAC_9205_EAPD] = "eapd", }; static struct snd_pci_quirk stac9205_cfg_tbl[] = { /* SigmaTel reference board */ SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0x2668, "DFI LanParty", STAC_9205_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_INTEL, 0xfb30, "SigmaTel", STAC_9205_REF), SND_PCI_QUIRK(PCI_VENDOR_ID_DFI, 0x3101, "DFI LanParty", STAC_9205_REF), /* Dell */ SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01f1, "unknown Dell", STAC_9205_DELL_M42), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01f2, "unknown Dell", STAC_9205_DELL_M42), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01f8, "Dell Precision", STAC_9205_DELL_M43), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01f9, "Dell Precision", STAC_9205_DELL_M43), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01fa, "Dell Precision", STAC_9205_DELL_M43), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01fc, "unknown Dell", STAC_9205_DELL_M42), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01fd, "unknown Dell", STAC_9205_DELL_M42), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01fe, "Dell Precision", STAC_9205_DELL_M43), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x01ff, "Dell Precision M4300", STAC_9205_DELL_M43), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0204, "unknown Dell", STAC_9205_DELL_M42), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0206, "Dell Precision", STAC_9205_DELL_M43), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x021b, "Dell Precision", STAC_9205_DELL_M43), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x021c, "Dell Precision", STAC_9205_DELL_M43), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x021f, "Dell Inspiron", STAC_9205_DELL_M44), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0228, "Dell Vostro 1500", STAC_9205_DELL_M42), SND_PCI_QUIRK(PCI_VENDOR_ID_DELL, 0x0229, "Dell Vostro 1700", STAC_9205_DELL_M42), /* Gateway */ SND_PCI_QUIRK(0x107b, 0x0560, "Gateway T6834c", STAC_9205_EAPD), SND_PCI_QUIRK(0x107b, 0x0565, "Gateway T1616", STAC_9205_EAPD), {} /* terminator */ }; static void stac92xx_set_config_regs(struct hda_codec *codec, unsigned int *pincfgs) { int i; struct sigmatel_spec *spec = codec->spec; if (!pincfgs) return; for (i = 0; i < spec->num_pins; i++) if (spec->pin_nids[i] && pincfgs[i]) snd_hda_codec_set_pincfg(codec, spec->pin_nids[i], pincfgs[i]); } /* * Analog playback callbacks */ static int stac92xx_playback_pcm_open(struct hda_pcm_stream *hinfo, struct hda_codec *codec, struct snd_pcm_substream *substream) { struct sigmatel_spec *spec = codec->spec; if (spec->stream_delay) msleep(spec->stream_delay); return snd_hda_multi_out_analog_open(codec, &spec->multiout, substream, hinfo); } static int stac92xx_playback_pcm_prepare(struct hda_pcm_stream *hinfo, struct hda_codec *codec, unsigned int stream_tag, unsigned int format, struct snd_pcm_substream *substream) { struct sigmatel_spec *spec = codec->spec; return snd_hda_multi_out_analog_prepare(codec, &spec->multiout, stream_tag, format, substream); } static int stac92xx_playback_pcm_cleanup(struct hda_pcm_stream *hinfo, struct hda_codec *codec, struct snd_pcm_substream *substream) { struct sigmatel_spec *spec = codec->spec; return snd_hda_multi_out_analog_cleanup(codec, &spec->multiout); } /* * Digital playback callbacks */ static int stac92xx_dig_playback_pcm_open(struct hda_pcm_stream *hinfo, struct hda_codec *codec, struct snd_pcm_substream *substream) { struct sigmatel_spec *spec = codec->spec; return snd_hda_multi_out_dig_open(codec, &spec->multiout); } static int stac92xx_dig_playback_pcm_close(struct hda_pcm_stream *hinfo, struct hda_codec *codec, struct snd_pcm_substream *substream) { struct sigmatel_spec *spec = codec->spec; return snd_hda_multi_out_dig_close(codec, &spec->multiout); } static int stac92xx_dig_playback_pcm_prepare(struct hda_pcm_stream *hinfo, struct hda_codec *codec, unsigned int stream_tag, unsigned int format, struct snd_pcm_substream *substream) { struct sigmatel_spec *spec = codec->spec; return snd_hda_multi_out_dig_prepare(codec, &spec->multiout, stream_tag, format, substream); } static int stac92xx_dig_playback_pcm_cleanup(struct hda_pcm_stream *hinfo, struct hda_codec *codec, struct snd_pcm_substream *substream) { struct sigmatel_spec *spec = codec->spec; return snd_hda_multi_out_dig_cleanup(codec, &spec->multiout); } /* * Analog capture callbacks */ static int stac92xx_capture_pcm_prepare(struct hda_pcm_stream *hinfo, struct hda_codec *codec, unsigned int stream_tag, unsigned int format, struct snd_pcm_substream *substream) { struct sigmatel_spec *spec = codec->spec; hda_nid_t nid = spec->adc_nids[substream->number]; if (spec->powerdown_adcs) { msleep(40); snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_POWER_STATE, AC_PWRST_D0); } snd_hda_codec_setup_stream(codec, nid, stream_tag, 0, format); return 0; } static int stac92xx_capture_pcm_cleanup(struct hda_pcm_stream *hinfo, struct hda_codec *codec, struct snd_pcm_substream *substream) { struct sigmatel_spec *spec = codec->spec; hda_nid_t nid = spec->adc_nids[substream->number]; snd_hda_codec_cleanup_stream(codec, nid); if (spec->powerdown_adcs) snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_POWER_STATE, AC_PWRST_D3); return 0; } static struct hda_pcm_stream stac92xx_pcm_digital_playback = { .substreams = 1, .channels_min = 2, .channels_max = 2, /* NID is set in stac92xx_build_pcms */ .ops = { .open = stac92xx_dig_playback_pcm_open, .close = stac92xx_dig_playback_pcm_close, .prepare = stac92xx_dig_playback_pcm_prepare, .cleanup = stac92xx_dig_playback_pcm_cleanup }, }; static struct hda_pcm_stream stac92xx_pcm_digital_capture = { .substreams = 1, .channels_min = 2, .channels_max = 2, /* NID is set in stac92xx_build_pcms */ }; static struct hda_pcm_stream stac92xx_pcm_analog_playback = { .substreams = 1, .channels_min = 2, .channels_max = 8, .nid = 0x02, /* NID to query formats and rates */ .ops = { .open = stac92xx_playback_pcm_open, .prepare = stac92xx_playback_pcm_prepare, .cleanup = stac92xx_playback_pcm_cleanup }, }; static struct hda_pcm_stream stac92xx_pcm_analog_alt_playback = { .substreams = 1, .channels_min = 2, .channels_max = 2, .nid = 0x06, /* NID to query formats and rates */ .ops = { .open = stac92xx_playback_pcm_open, .prepare = stac92xx_playback_pcm_prepare, .cleanup = stac92xx_playback_pcm_cleanup }, }; static struct hda_pcm_stream stac92xx_pcm_analog_capture = { .channels_min = 2, .channels_max = 2, /* NID + .substreams is set in stac92xx_build_pcms */ .ops = { .prepare = stac92xx_capture_pcm_prepare, .cleanup = stac92xx_capture_pcm_cleanup }, }; static int stac92xx_build_pcms(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; struct hda_pcm *info = spec->pcm_rec; codec->num_pcms = 1; codec->pcm_info = info; info->name = "STAC92xx Analog"; info->stream[SNDRV_PCM_STREAM_PLAYBACK] = stac92xx_pcm_analog_playback; info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid = spec->multiout.dac_nids[0]; info->stream[SNDRV_PCM_STREAM_CAPTURE] = stac92xx_pcm_analog_capture; info->stream[SNDRV_PCM_STREAM_CAPTURE].nid = spec->adc_nids[0]; info->stream[SNDRV_PCM_STREAM_CAPTURE].substreams = spec->num_adcs; if (spec->alt_switch) { codec->num_pcms++; info++; info->name = "STAC92xx Analog Alt"; info->stream[SNDRV_PCM_STREAM_PLAYBACK] = stac92xx_pcm_analog_alt_playback; } if (spec->multiout.dig_out_nid || spec->dig_in_nid) { codec->num_pcms++; info++; info->name = "STAC92xx Digital"; info->pcm_type = spec->autocfg.dig_out_type[0]; if (spec->multiout.dig_out_nid) { info->stream[SNDRV_PCM_STREAM_PLAYBACK] = stac92xx_pcm_digital_playback; info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid = spec->multiout.dig_out_nid; } if (spec->dig_in_nid) { info->stream[SNDRV_PCM_STREAM_CAPTURE] = stac92xx_pcm_digital_capture; info->stream[SNDRV_PCM_STREAM_CAPTURE].nid = spec->dig_in_nid; } } return 0; } static unsigned int stac92xx_get_default_vref(struct hda_codec *codec, hda_nid_t nid) { unsigned int pincap = snd_hda_query_pin_caps(codec, nid); pincap = (pincap & AC_PINCAP_VREF) >> AC_PINCAP_VREF_SHIFT; if (pincap & AC_PINCAP_VREF_100) return AC_PINCTL_VREF_100; if (pincap & AC_PINCAP_VREF_80) return AC_PINCTL_VREF_80; if (pincap & AC_PINCAP_VREF_50) return AC_PINCTL_VREF_50; if (pincap & AC_PINCAP_VREF_GRD) return AC_PINCTL_VREF_GRD; return 0; } static void stac92xx_auto_set_pinctl(struct hda_codec *codec, hda_nid_t nid, int pin_type) { snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_PIN_WIDGET_CONTROL, pin_type); } #define stac92xx_hp_switch_info snd_ctl_boolean_mono_info static int stac92xx_hp_switch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; ucontrol->value.integer.value[0] = !!spec->hp_switch; return 0; } static void stac_issue_unsol_event(struct hda_codec *codec, hda_nid_t nid); static int stac92xx_hp_switch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; int nid = kcontrol->private_value; spec->hp_switch = ucontrol->value.integer.value[0] ? nid : 0; /* check to be sure that the ports are up to date with * switch changes */ stac_issue_unsol_event(codec, nid); return 1; } static int stac92xx_dc_bias_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { int i; static char *texts[] = { "Mic In", "Line In", "Line Out" }; struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; hda_nid_t nid = kcontrol->private_value; if (nid == spec->mic_switch || nid == spec->line_switch) i = 3; else i = 2; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->value.enumerated.items = i; uinfo->count = 1; if (uinfo->value.enumerated.item >= i) uinfo->value.enumerated.item = i-1; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int stac92xx_dc_bias_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); hda_nid_t nid = kcontrol->private_value; unsigned int vref = stac92xx_vref_get(codec, nid); if (vref == stac92xx_get_default_vref(codec, nid)) ucontrol->value.enumerated.item[0] = 0; else if (vref == AC_PINCTL_VREF_GRD) ucontrol->value.enumerated.item[0] = 1; else if (vref == AC_PINCTL_VREF_HIZ) ucontrol->value.enumerated.item[0] = 2; return 0; } static int stac92xx_dc_bias_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); unsigned int new_vref = 0; int error; hda_nid_t nid = kcontrol->private_value; if (ucontrol->value.enumerated.item[0] == 0) new_vref = stac92xx_get_default_vref(codec, nid); else if (ucontrol->value.enumerated.item[0] == 1) new_vref = AC_PINCTL_VREF_GRD; else if (ucontrol->value.enumerated.item[0] == 2) new_vref = AC_PINCTL_VREF_HIZ; else return 0; if (new_vref != stac92xx_vref_get(codec, nid)) { error = stac92xx_vref_set(codec, nid, new_vref); return error; } return 0; } static int stac92xx_io_switch_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[2]; struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; if (kcontrol->private_value == spec->line_switch) texts[0] = "Line In"; else texts[0] = "Mic In"; texts[1] = "Line Out"; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->value.enumerated.items = 2; uinfo->count = 1; if (uinfo->value.enumerated.item >= 2) uinfo->value.enumerated.item = 1; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int stac92xx_io_switch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; hda_nid_t nid = kcontrol->private_value; int io_idx = (nid == spec->mic_switch) ? 1 : 0; ucontrol->value.enumerated.item[0] = spec->io_switch[io_idx]; return 0; } static int stac92xx_io_switch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; hda_nid_t nid = kcontrol->private_value; int io_idx = (nid == spec->mic_switch) ? 1 : 0; unsigned short val = !!ucontrol->value.enumerated.item[0]; spec->io_switch[io_idx] = val; if (val) stac92xx_auto_set_pinctl(codec, nid, AC_PINCTL_OUT_EN); else { unsigned int pinctl = AC_PINCTL_IN_EN; if (io_idx) /* set VREF for mic */ pinctl |= stac92xx_get_default_vref(codec, nid); stac92xx_auto_set_pinctl(codec, nid, pinctl); } /* check the auto-mute again: we need to mute/unmute the speaker * appropriately according to the pin direction */ if (spec->hp_detect) stac_issue_unsol_event(codec, nid); return 1; } #define stac92xx_clfe_switch_info snd_ctl_boolean_mono_info static int stac92xx_clfe_switch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; ucontrol->value.integer.value[0] = spec->clfe_swap; return 0; } static int stac92xx_clfe_switch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; hda_nid_t nid = kcontrol->private_value & 0xff; unsigned int val = !!ucontrol->value.integer.value[0]; if (spec->clfe_swap == val) return 0; spec->clfe_swap = val; snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_EAPD_BTLENABLE, spec->clfe_swap ? 0x4 : 0x0); return 1; } #define STAC_CODEC_HP_SWITCH(xname) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \ .name = xname, \ .index = 0, \ .info = stac92xx_hp_switch_info, \ .get = stac92xx_hp_switch_get, \ .put = stac92xx_hp_switch_put, \ } #define STAC_CODEC_IO_SWITCH(xname, xpval) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \ .name = xname, \ .index = 0, \ .info = stac92xx_io_switch_info, \ .get = stac92xx_io_switch_get, \ .put = stac92xx_io_switch_put, \ .private_value = xpval, \ } #define STAC_CODEC_CLFE_SWITCH(xname, xpval) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \ .name = xname, \ .index = 0, \ .info = stac92xx_clfe_switch_info, \ .get = stac92xx_clfe_switch_get, \ .put = stac92xx_clfe_switch_put, \ .private_value = xpval, \ } enum { STAC_CTL_WIDGET_VOL, STAC_CTL_WIDGET_MUTE, STAC_CTL_WIDGET_MUTE_BEEP, STAC_CTL_WIDGET_MONO_MUX, STAC_CTL_WIDGET_HP_SWITCH, STAC_CTL_WIDGET_IO_SWITCH, STAC_CTL_WIDGET_CLFE_SWITCH, STAC_CTL_WIDGET_DC_BIAS }; static struct snd_kcontrol_new stac92xx_control_templates[] = { HDA_CODEC_VOLUME(NULL, 0, 0, 0), HDA_CODEC_MUTE(NULL, 0, 0, 0), HDA_CODEC_MUTE_BEEP(NULL, 0, 0, 0), STAC_MONO_MUX, STAC_CODEC_HP_SWITCH(NULL), STAC_CODEC_IO_SWITCH(NULL, 0), STAC_CODEC_CLFE_SWITCH(NULL, 0), DC_BIAS(NULL, 0, 0), }; /* add dynamic controls */ static struct snd_kcontrol_new * stac_control_new(struct sigmatel_spec *spec, struct snd_kcontrol_new *ktemp, const char *name, unsigned int subdev) { struct snd_kcontrol_new *knew; snd_array_init(&spec->kctls, sizeof(*knew), 32); knew = snd_array_new(&spec->kctls); if (!knew) return NULL; *knew = *ktemp; knew->name = kstrdup(name, GFP_KERNEL); if (!knew->name) { /* roolback */ memset(knew, 0, sizeof(*knew)); spec->kctls.alloced--; return NULL; } knew->subdevice = subdev; return knew; } static int stac92xx_add_control_temp(struct sigmatel_spec *spec, struct snd_kcontrol_new *ktemp, int idx, const char *name, unsigned long val) { struct snd_kcontrol_new *knew = stac_control_new(spec, ktemp, name, HDA_SUBDEV_AMP_FLAG); if (!knew) return -ENOMEM; knew->index = idx; knew->private_value = val; return 0; } static inline int stac92xx_add_control_idx(struct sigmatel_spec *spec, int type, int idx, const char *name, unsigned long val) { return stac92xx_add_control_temp(spec, &stac92xx_control_templates[type], idx, name, val); } /* add dynamic controls */ static inline int stac92xx_add_control(struct sigmatel_spec *spec, int type, const char *name, unsigned long val) { return stac92xx_add_control_idx(spec, type, 0, name, val); } static struct snd_kcontrol_new stac_input_src_temp = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Input Source", .info = stac92xx_mux_enum_info, .get = stac92xx_mux_enum_get, .put = stac92xx_mux_enum_put, }; static inline int stac92xx_add_jack_mode_control(struct hda_codec *codec, hda_nid_t nid, int idx) { int def_conf = snd_hda_codec_get_pincfg(codec, nid); int control = 0; struct sigmatel_spec *spec = codec->spec; char name[22]; if (snd_hda_get_input_pin_attr(def_conf) != INPUT_PIN_ATTR_INT) { if (stac92xx_get_default_vref(codec, nid) == AC_PINCTL_VREF_GRD && nid == spec->line_switch) control = STAC_CTL_WIDGET_IO_SWITCH; else if (snd_hda_query_pin_caps(codec, nid) & (AC_PINCAP_VREF_GRD << AC_PINCAP_VREF_SHIFT)) control = STAC_CTL_WIDGET_DC_BIAS; else if (nid == spec->mic_switch) control = STAC_CTL_WIDGET_IO_SWITCH; } if (control) { strcpy(name, hda_get_input_pin_label(codec, nid, 1)); return stac92xx_add_control(codec->spec, control, strcat(name, " Jack Mode"), nid); } return 0; } static int stac92xx_add_input_source(struct sigmatel_spec *spec) { struct snd_kcontrol_new *knew; struct hda_input_mux *imux = &spec->private_imux; if (spec->auto_mic) return 0; /* no need for input source */ if (!spec->num_adcs || imux->num_items <= 1) return 0; /* no need for input source control */ knew = stac_control_new(spec, &stac_input_src_temp, stac_input_src_temp.name, 0); if (!knew) return -ENOMEM; knew->count = spec->num_adcs; return 0; } /* check whether the line-input can be used as line-out */ static hda_nid_t check_line_out_switch(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; struct auto_pin_cfg *cfg = &spec->autocfg; hda_nid_t nid; unsigned int pincap; int i; if (cfg->line_out_type != AUTO_PIN_LINE_OUT) return 0; for (i = 0; i < cfg->num_inputs; i++) { if (cfg->inputs[i].type == AUTO_PIN_LINE_IN) { nid = cfg->inputs[i].pin; pincap = snd_hda_query_pin_caps(codec, nid); if (pincap & AC_PINCAP_OUT) return nid; } } return 0; } static hda_nid_t get_unassigned_dac(struct hda_codec *codec, hda_nid_t nid); /* check whether the mic-input can be used as line-out */ static hda_nid_t check_mic_out_switch(struct hda_codec *codec, hda_nid_t *dac) { struct sigmatel_spec *spec = codec->spec; struct auto_pin_cfg *cfg = &spec->autocfg; unsigned int def_conf, pincap; int i; *dac = 0; if (cfg->line_out_type != AUTO_PIN_LINE_OUT) return 0; for (i = 0; i < cfg->num_inputs; i++) { hda_nid_t nid = cfg->inputs[i].pin; if (cfg->inputs[i].type != AUTO_PIN_MIC) continue; def_conf = snd_hda_codec_get_pincfg(codec, nid); /* some laptops have an internal analog microphone * which can't be used as a output */ if (snd_hda_get_input_pin_attr(def_conf) != INPUT_PIN_ATTR_INT) { pincap = snd_hda_query_pin_caps(codec, nid); if (pincap & AC_PINCAP_OUT) { *dac = get_unassigned_dac(codec, nid); if (*dac) return nid; } } } return 0; } static int is_in_dac_nids(struct sigmatel_spec *spec, hda_nid_t nid) { int i; for (i = 0; i < spec->multiout.num_dacs; i++) { if (spec->multiout.dac_nids[i] == nid) return 1; } return 0; } static int check_all_dac_nids(struct sigmatel_spec *spec, hda_nid_t nid) { int i; if (is_in_dac_nids(spec, nid)) return 1; for (i = 0; i < spec->autocfg.hp_outs; i++) if (spec->hp_dacs[i] == nid) return 1; for (i = 0; i < spec->autocfg.speaker_outs; i++) if (spec->speaker_dacs[i] == nid) return 1; return 0; } static hda_nid_t get_unassigned_dac(struct hda_codec *codec, hda_nid_t nid) { struct sigmatel_spec *spec = codec->spec; int j, conn_len; hda_nid_t conn[HDA_MAX_CONNECTIONS]; unsigned int wcaps, wtype; conn_len = snd_hda_get_connections(codec, nid, conn, HDA_MAX_CONNECTIONS); /* 92HD88: trace back up the link of nids to find the DAC */ while (conn_len == 1 && (get_wcaps_type(get_wcaps(codec, conn[0])) != AC_WID_AUD_OUT)) { nid = conn[0]; conn_len = snd_hda_get_connections(codec, nid, conn, HDA_MAX_CONNECTIONS); } for (j = 0; j < conn_len; j++) { wcaps = get_wcaps(codec, conn[j]); wtype = get_wcaps_type(wcaps); /* we check only analog outputs */ if (wtype != AC_WID_AUD_OUT || (wcaps & AC_WCAP_DIGITAL)) continue; /* if this route has a free DAC, assign it */ if (!check_all_dac_nids(spec, conn[j])) { if (conn_len > 1) { /* select this DAC in the pin's input mux */ snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_CONNECT_SEL, j); } return conn[j]; } } /* if all DACs are already assigned, connect to the primary DAC */ if (conn_len > 1) { for (j = 0; j < conn_len; j++) { if (conn[j] == spec->multiout.dac_nids[0]) { snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_CONNECT_SEL, j); break; } } } return 0; } static int add_spec_dacs(struct sigmatel_spec *spec, hda_nid_t nid); static int add_spec_extra_dacs(struct sigmatel_spec *spec, hda_nid_t nid); /* * Fill in the dac_nids table from the parsed pin configuration * This function only works when every pin in line_out_pins[] * contains atleast one DAC in its connection list. Some 92xx * codecs are not connected directly to a DAC, such as the 9200 * and 9202/925x. For those, dac_nids[] must be hard-coded. */ static int stac92xx_auto_fill_dac_nids(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; struct auto_pin_cfg *cfg = &spec->autocfg; int i; hda_nid_t nid, dac; for (i = 0; i < cfg->line_outs; i++) { nid = cfg->line_out_pins[i]; dac = get_unassigned_dac(codec, nid); if (!dac) { if (spec->multiout.num_dacs > 0) { /* we have already working output pins, * so let's drop the broken ones again */ cfg->line_outs = spec->multiout.num_dacs; break; } /* error out, no available DAC found */ snd_printk(KERN_ERR "%s: No available DAC for pin 0x%x\n", __func__, nid); return -ENODEV; } add_spec_dacs(spec, dac); } for (i = 0; i < cfg->hp_outs; i++) { nid = cfg->hp_pins[i]; dac = get_unassigned_dac(codec, nid); if (dac) { if (!spec->multiout.hp_nid) spec->multiout.hp_nid = dac; else add_spec_extra_dacs(spec, dac); } spec->hp_dacs[i] = dac; } for (i = 0; i < cfg->speaker_outs; i++) { nid = cfg->speaker_pins[i]; dac = get_unassigned_dac(codec, nid); if (dac) add_spec_extra_dacs(spec, dac); spec->speaker_dacs[i] = dac; } /* add line-in as output */ nid = check_line_out_switch(codec); if (nid) { dac = get_unassigned_dac(codec, nid); if (dac) { snd_printdd("STAC: Add line-in 0x%x as output %d\n", nid, cfg->line_outs); cfg->line_out_pins[cfg->line_outs] = nid; cfg->line_outs++; spec->line_switch = nid; add_spec_dacs(spec, dac); } } /* add mic as output */ nid = check_mic_out_switch(codec, &dac); if (nid && dac) { snd_printdd("STAC: Add mic-in 0x%x as output %d\n", nid, cfg->line_outs); cfg->line_out_pins[cfg->line_outs] = nid; cfg->line_outs++; spec->mic_switch = nid; add_spec_dacs(spec, dac); } snd_printd("stac92xx: dac_nids=%d (0x%x/0x%x/0x%x/0x%x/0x%x)\n", spec->multiout.num_dacs, spec->multiout.dac_nids[0], spec->multiout.dac_nids[1], spec->multiout.dac_nids[2], spec->multiout.dac_nids[3], spec->multiout.dac_nids[4]); return 0; } /* create volume control/switch for the given prefx type */ static int create_controls_idx(struct hda_codec *codec, const char *pfx, int idx, hda_nid_t nid, int chs) { struct sigmatel_spec *spec = codec->spec; char name[32]; int err; if (!spec->check_volume_offset) { unsigned int caps, step, nums, db_scale; caps = query_amp_caps(codec, nid, HDA_OUTPUT); step = (caps & AC_AMPCAP_STEP_SIZE) >> AC_AMPCAP_STEP_SIZE_SHIFT; step = (step + 1) * 25; /* in .01dB unit */ nums = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT; db_scale = nums * step; /* if dB scale is over -64dB, and finer enough, * let's reduce it to half */ if (db_scale > 6400 && nums >= 0x1f) spec->volume_offset = nums / 2; spec->check_volume_offset = 1; } sprintf(name, "%s Playback Volume", pfx); err = stac92xx_add_control_idx(spec, STAC_CTL_WIDGET_VOL, idx, name, HDA_COMPOSE_AMP_VAL_OFS(nid, chs, 0, HDA_OUTPUT, spec->volume_offset)); if (err < 0) return err; sprintf(name, "%s Playback Switch", pfx); err = stac92xx_add_control_idx(spec, STAC_CTL_WIDGET_MUTE, idx, name, HDA_COMPOSE_AMP_VAL(nid, chs, 0, HDA_OUTPUT)); if (err < 0) return err; return 0; } #define create_controls(codec, pfx, nid, chs) \ create_controls_idx(codec, pfx, 0, nid, chs) static int add_spec_dacs(struct sigmatel_spec *spec, hda_nid_t nid) { if (spec->multiout.num_dacs > 4) { printk(KERN_WARNING "stac92xx: No space for DAC 0x%x\n", nid); return 1; } else { spec->multiout.dac_nids[spec->multiout.num_dacs] = nid; spec->multiout.num_dacs++; } return 0; } static int add_spec_extra_dacs(struct sigmatel_spec *spec, hda_nid_t nid) { int i; for (i = 0; i < ARRAY_SIZE(spec->multiout.extra_out_nid); i++) { if (!spec->multiout.extra_out_nid[i]) { spec->multiout.extra_out_nid[i] = nid; return 0; } } printk(KERN_WARNING "stac92xx: No space for extra DAC 0x%x\n", nid); return 1; } /* Create output controls * The mixer elements are named depending on the given type (AUTO_PIN_XXX_OUT) */ static int create_multi_out_ctls(struct hda_codec *codec, int num_outs, const hda_nid_t *pins, const hda_nid_t *dac_nids, int type) { struct sigmatel_spec *spec = codec->spec; static const char * const chname[4] = { "Front", "Surround", NULL /*CLFE*/, "Side" }; hda_nid_t nid; int i, err; unsigned int wid_caps; for (i = 0; i < num_outs && i < ARRAY_SIZE(chname); i++) { if (type == AUTO_PIN_HP_OUT && !spec->hp_detect) { wid_caps = get_wcaps(codec, pins[i]); if (wid_caps & AC_WCAP_UNSOL_CAP) spec->hp_detect = 1; } nid = dac_nids[i]; if (!nid) continue; if (type != AUTO_PIN_HP_OUT && i == 2) { /* Center/LFE */ err = create_controls(codec, "Center", nid, 1); if (err < 0) return err; err = create_controls(codec, "LFE", nid, 2); if (err < 0) return err; wid_caps = get_wcaps(codec, nid); if (wid_caps & AC_WCAP_LR_SWAP) { err = stac92xx_add_control(spec, STAC_CTL_WIDGET_CLFE_SWITCH, "Swap Center/LFE Playback Switch", nid); if (err < 0) return err; } } else { const char *name; int idx; switch (type) { case AUTO_PIN_HP_OUT: name = "Headphone"; idx = i; break; case AUTO_PIN_SPEAKER_OUT: name = "Speaker"; idx = i; break; default: name = chname[i]; idx = 0; break; } err = create_controls_idx(codec, name, idx, nid, 3); if (err < 0) return err; } } return 0; } static int stac92xx_add_capvol_ctls(struct hda_codec *codec, unsigned long vol, unsigned long sw, int idx) { int err; err = stac92xx_add_control_idx(codec->spec, STAC_CTL_WIDGET_VOL, idx, "Capture Volume", vol); if (err < 0) return err; err = stac92xx_add_control_idx(codec->spec, STAC_CTL_WIDGET_MUTE, idx, "Capture Switch", sw); if (err < 0) return err; return 0; } /* add playback controls from the parsed DAC table */ static int stac92xx_auto_create_multi_out_ctls(struct hda_codec *codec, const struct auto_pin_cfg *cfg) { struct sigmatel_spec *spec = codec->spec; hda_nid_t nid; int err; int idx; err = create_multi_out_ctls(codec, cfg->line_outs, cfg->line_out_pins, spec->multiout.dac_nids, cfg->line_out_type); if (err < 0) return err; if (cfg->hp_outs > 1 && cfg->line_out_type == AUTO_PIN_LINE_OUT) { err = stac92xx_add_control(spec, STAC_CTL_WIDGET_HP_SWITCH, "Headphone as Line Out Switch", cfg->hp_pins[cfg->hp_outs - 1]); if (err < 0) return err; } for (idx = 0; idx < cfg->num_inputs; idx++) { if (cfg->inputs[idx].type > AUTO_PIN_LINE_IN) break; nid = cfg->inputs[idx].pin; err = stac92xx_add_jack_mode_control(codec, nid, idx); if (err < 0) return err; } return 0; } /* add playback controls for Speaker and HP outputs */ static int stac92xx_auto_create_hp_ctls(struct hda_codec *codec, struct auto_pin_cfg *cfg) { struct sigmatel_spec *spec = codec->spec; int err; err = create_multi_out_ctls(codec, cfg->hp_outs, cfg->hp_pins, spec->hp_dacs, AUTO_PIN_HP_OUT); if (err < 0) return err; err = create_multi_out_ctls(codec, cfg->speaker_outs, cfg->speaker_pins, spec->speaker_dacs, AUTO_PIN_SPEAKER_OUT); if (err < 0) return err; return 0; } /* labels for mono mux outputs */ static const char * const stac92xx_mono_labels[4] = { "DAC0", "DAC1", "Mixer", "DAC2" }; /* create mono mux for mono out on capable codecs */ static int stac92xx_auto_create_mono_output_ctls(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; struct hda_input_mux *mono_mux = &spec->private_mono_mux; int i, num_cons; hda_nid_t con_lst[ARRAY_SIZE(stac92xx_mono_labels)]; num_cons = snd_hda_get_connections(codec, spec->mono_nid, con_lst, HDA_MAX_NUM_INPUTS); if (num_cons <= 0 || num_cons > ARRAY_SIZE(stac92xx_mono_labels)) return -EINVAL; for (i = 0; i < num_cons; i++) snd_hda_add_imux_item(mono_mux, stac92xx_mono_labels[i], i, NULL); return stac92xx_add_control(spec, STAC_CTL_WIDGET_MONO_MUX, "Mono Mux", spec->mono_nid); } /* create PC beep volume controls */ static int stac92xx_auto_create_beep_ctls(struct hda_codec *codec, hda_nid_t nid) { struct sigmatel_spec *spec = codec->spec; u32 caps = query_amp_caps(codec, nid, HDA_OUTPUT); int err, type = STAC_CTL_WIDGET_MUTE_BEEP; if (spec->anabeep_nid == nid) type = STAC_CTL_WIDGET_MUTE; /* check for mute support for the the amp */ if ((caps & AC_AMPCAP_MUTE) >> AC_AMPCAP_MUTE_SHIFT) { err = stac92xx_add_control(spec, type, "Beep Playback Switch", HDA_COMPOSE_AMP_VAL(nid, 1, 0, HDA_OUTPUT)); if (err < 0) return err; } /* check to see if there is volume support for the amp */ if ((caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT) { err = stac92xx_add_control(spec, STAC_CTL_WIDGET_VOL, "Beep Playback Volume", HDA_COMPOSE_AMP_VAL(nid, 1, 0, HDA_OUTPUT)); if (err < 0) return err; } return 0; } #ifdef CONFIG_SND_HDA_INPUT_BEEP #define stac92xx_dig_beep_switch_info snd_ctl_boolean_mono_info static int stac92xx_dig_beep_switch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); ucontrol->value.integer.value[0] = codec->beep->enabled; return 0; } static int stac92xx_dig_beep_switch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); return snd_hda_enable_beep_device(codec, ucontrol->value.integer.value[0]); } static struct snd_kcontrol_new stac92xx_dig_beep_ctrl = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .info = stac92xx_dig_beep_switch_info, .get = stac92xx_dig_beep_switch_get, .put = stac92xx_dig_beep_switch_put, }; static int stac92xx_beep_switch_ctl(struct hda_codec *codec) { return stac92xx_add_control_temp(codec->spec, &stac92xx_dig_beep_ctrl, 0, "Beep Playback Switch", 0); } #endif static int stac92xx_auto_create_mux_input_ctls(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; int i, j, err = 0; for (i = 0; i < spec->num_muxes; i++) { hda_nid_t nid; unsigned int wcaps; unsigned long val; nid = spec->mux_nids[i]; wcaps = get_wcaps(codec, nid); if (!(wcaps & AC_WCAP_OUT_AMP)) continue; /* check whether already the same control was created as * normal Capture Volume. */ val = HDA_COMPOSE_AMP_VAL(nid, 3, 0, HDA_OUTPUT); for (j = 0; j < spec->num_caps; j++) { if (spec->capvols[j] == val) break; } if (j < spec->num_caps) continue; err = stac92xx_add_control_idx(spec, STAC_CTL_WIDGET_VOL, i, "Mux Capture Volume", val); if (err < 0) return err; } return 0; }; static const char * const stac92xx_spdif_labels[3] = { "Digital Playback", "Analog Mux 1", "Analog Mux 2", }; static int stac92xx_auto_create_spdif_mux_ctls(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; struct hda_input_mux *spdif_mux = &spec->private_smux; const char * const *labels = spec->spdif_labels; int i, num_cons; hda_nid_t con_lst[HDA_MAX_NUM_INPUTS]; num_cons = snd_hda_get_connections(codec, spec->smux_nids[0], con_lst, HDA_MAX_NUM_INPUTS); if (num_cons <= 0) return -EINVAL; if (!labels) labels = stac92xx_spdif_labels; for (i = 0; i < num_cons; i++) snd_hda_add_imux_item(spdif_mux, labels[i], i, NULL); return 0; } /* labels for dmic mux inputs */ static const char * const stac92xx_dmic_labels[5] = { "Analog Inputs", "Digital Mic 1", "Digital Mic 2", "Digital Mic 3", "Digital Mic 4" }; static hda_nid_t get_connected_node(struct hda_codec *codec, hda_nid_t mux, int idx) { hda_nid_t conn[HDA_MAX_NUM_INPUTS]; int nums; nums = snd_hda_get_connections(codec, mux, conn, ARRAY_SIZE(conn)); if (idx >= 0 && idx < nums) return conn[idx]; return 0; } static int get_connection_index(struct hda_codec *codec, hda_nid_t mux, hda_nid_t nid) { hda_nid_t conn[HDA_MAX_NUM_INPUTS]; int i, nums; if (!(get_wcaps(codec, mux) & AC_WCAP_CONN_LIST)) return -1; nums = snd_hda_get_connections(codec, mux, conn, ARRAY_SIZE(conn)); for (i = 0; i < nums; i++) if (conn[i] == nid) return i; for (i = 0; i < nums; i++) { unsigned int wid_caps = get_wcaps(codec, conn[i]); unsigned int wid_type = get_wcaps_type(wid_caps); if (wid_type != AC_WID_PIN && wid_type != AC_WID_AUD_MIX) if (get_connection_index(codec, conn[i], nid) >= 0) return i; } return -1; } /* create a volume assigned to the given pin (only if supported) */ /* return 1 if the volume control is created */ static int create_elem_capture_vol(struct hda_codec *codec, hda_nid_t nid, const char *label, int idx, int direction) { unsigned int caps, nums; char name[32]; int err; if (direction == HDA_OUTPUT) caps = AC_WCAP_OUT_AMP; else caps = AC_WCAP_IN_AMP; if (!(get_wcaps(codec, nid) & caps)) return 0; caps = query_amp_caps(codec, nid, direction); nums = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT; if (!nums) return 0; snprintf(name, sizeof(name), "%s Capture Volume", label); err = stac92xx_add_control_idx(codec->spec, STAC_CTL_WIDGET_VOL, idx, name, HDA_COMPOSE_AMP_VAL(nid, 3, 0, direction)); if (err < 0) return err; return 1; } /* create playback/capture controls for input pins on dmic capable codecs */ static int stac92xx_auto_create_dmic_input_ctls(struct hda_codec *codec, const struct auto_pin_cfg *cfg) { struct sigmatel_spec *spec = codec->spec; struct hda_input_mux *imux = &spec->private_imux; struct hda_input_mux *dimux = &spec->private_dimux; int err, i; unsigned int def_conf; snd_hda_add_imux_item(dimux, stac92xx_dmic_labels[0], 0, NULL); for (i = 0; i < spec->num_dmics; i++) { hda_nid_t nid; int index, type_idx; const char *label; nid = spec->dmic_nids[i]; if (get_wcaps_type(get_wcaps(codec, nid)) != AC_WID_PIN) continue; def_conf = snd_hda_codec_get_pincfg(codec, nid); if (get_defcfg_connect(def_conf) == AC_JACK_PORT_NONE) continue; index = get_connection_index(codec, spec->dmux_nids[0], nid); if (index < 0) continue; label = hda_get_input_pin_label(codec, nid, 1); snd_hda_add_imux_item(dimux, label, index, &type_idx); if (snd_hda_get_bool_hint(codec, "separate_dmux") != 1) snd_hda_add_imux_item(imux, label, index, &type_idx); err = create_elem_capture_vol(codec, nid, label, type_idx, HDA_INPUT); if (err < 0) return err; if (!err) { err = create_elem_capture_vol(codec, nid, label, type_idx, HDA_OUTPUT); if (err < 0) return err; if (!err) { nid = get_connected_node(codec, spec->dmux_nids[0], index); if (nid) err = create_elem_capture_vol(codec, nid, label, type_idx, HDA_INPUT); if (err < 0) return err; } } } return 0; } static int check_mic_pin(struct hda_codec *codec, hda_nid_t nid, hda_nid_t *fixed, hda_nid_t *ext, hda_nid_t *dock) { unsigned int cfg; if (!nid) return 0; cfg = snd_hda_codec_get_pincfg(codec, nid); switch (snd_hda_get_input_pin_attr(cfg)) { case INPUT_PIN_ATTR_INT: if (*fixed) return 1; /* already occupied */ *fixed = nid; break; case INPUT_PIN_ATTR_UNUSED: break; case INPUT_PIN_ATTR_DOCK: if (*dock) return 1; /* already occupied */ *dock = nid; break; default: if (*ext) return 1; /* already occupied */ *ext = nid; break; } return 0; } static int set_mic_route(struct hda_codec *codec, struct sigmatel_mic_route *mic, hda_nid_t pin) { struct sigmatel_spec *spec = codec->spec; struct auto_pin_cfg *cfg = &spec->autocfg; int i; mic->pin = pin; if (pin == 0) return 0; for (i = 0; i < cfg->num_inputs; i++) { if (pin == cfg->inputs[i].pin) break; } if (i < cfg->num_inputs && cfg->inputs[i].type == AUTO_PIN_MIC) { /* analog pin */ i = get_connection_index(codec, spec->mux_nids[0], pin); if (i < 0) return -1; mic->mux_idx = i; mic->dmux_idx = -1; if (spec->dmux_nids) mic->dmux_idx = get_connection_index(codec, spec->dmux_nids[0], spec->mux_nids[0]); } else if (spec->dmux_nids) { /* digital pin */ i = get_connection_index(codec, spec->dmux_nids[0], pin); if (i < 0) return -1; mic->dmux_idx = i; mic->mux_idx = -1; if (spec->mux_nids) mic->mux_idx = get_connection_index(codec, spec->mux_nids[0], spec->dmux_nids[0]); } return 0; } /* return non-zero if the device is for automatic mic switch */ static int stac_check_auto_mic(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; struct auto_pin_cfg *cfg = &spec->autocfg; hda_nid_t fixed, ext, dock; int i; for (i = 0; i < cfg->num_inputs; i++) { if (cfg->inputs[i].type >= AUTO_PIN_LINE_IN) return 0; /* must be exclusively mics */ } fixed = ext = dock = 0; for (i = 0; i < cfg->num_inputs; i++) if (check_mic_pin(codec, cfg->inputs[i].pin, &fixed, &ext, &dock)) return 0; for (i = 0; i < spec->num_dmics; i++) if (check_mic_pin(codec, spec->dmic_nids[i], &fixed, &ext, &dock)) return 0; if (!fixed || (!ext && !dock)) return 0; /* no input to switch */ if (!(get_wcaps(codec, ext) & AC_WCAP_UNSOL_CAP)) return 0; /* no unsol support */ if (set_mic_route(codec, &spec->ext_mic, ext) || set_mic_route(codec, &spec->int_mic, fixed) || set_mic_route(codec, &spec->dock_mic, dock)) return 0; /* something is wrong */ return 1; } /* create playback/capture controls for input pins */ static int stac92xx_auto_create_analog_input_ctls(struct hda_codec *codec, const struct auto_pin_cfg *cfg) { struct sigmatel_spec *spec = codec->spec; struct hda_input_mux *imux = &spec->private_imux; int i, j; const char *label; for (i = 0; i < cfg->num_inputs; i++) { hda_nid_t nid = cfg->inputs[i].pin; int index, err, type_idx; index = -1; for (j = 0; j < spec->num_muxes; j++) { index = get_connection_index(codec, spec->mux_nids[j], nid); if (index >= 0) break; } if (index < 0) continue; label = hda_get_autocfg_input_label(codec, cfg, i); snd_hda_add_imux_item(imux, label, index, &type_idx); err = create_elem_capture_vol(codec, nid, label, type_idx, HDA_INPUT); if (err < 0) return err; } spec->num_analog_muxes = imux->num_items; if (imux->num_items) { /* * Set the current input for the muxes. * The STAC9221 has two input muxes with identical source * NID lists. Hopefully this won't get confused. */ for (i = 0; i < spec->num_muxes; i++) { snd_hda_codec_write_cache(codec, spec->mux_nids[i], 0, AC_VERB_SET_CONNECT_SEL, imux->items[0].index); } } return 0; } static void stac92xx_auto_init_multi_out(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; int i; for (i = 0; i < spec->autocfg.line_outs; i++) { hda_nid_t nid = spec->autocfg.line_out_pins[i]; stac92xx_auto_set_pinctl(codec, nid, AC_PINCTL_OUT_EN); } } static void stac92xx_auto_init_hp_out(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; int i; for (i = 0; i < spec->autocfg.hp_outs; i++) { hda_nid_t pin; pin = spec->autocfg.hp_pins[i]; if (pin) /* connect to front */ stac92xx_auto_set_pinctl(codec, pin, AC_PINCTL_OUT_EN | AC_PINCTL_HP_EN); } for (i = 0; i < spec->autocfg.speaker_outs; i++) { hda_nid_t pin; pin = spec->autocfg.speaker_pins[i]; if (pin) /* connect to front */ stac92xx_auto_set_pinctl(codec, pin, AC_PINCTL_OUT_EN); } } static int is_dual_headphones(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; int i, valid_hps; if (spec->autocfg.line_out_type != AUTO_PIN_SPEAKER_OUT || spec->autocfg.hp_outs <= 1) return 0; valid_hps = 0; for (i = 0; i < spec->autocfg.hp_outs; i++) { hda_nid_t nid = spec->autocfg.hp_pins[i]; unsigned int cfg = snd_hda_codec_get_pincfg(codec, nid); if (get_defcfg_location(cfg) & AC_JACK_LOC_SEPARATE) continue; valid_hps++; } return (valid_hps > 1); } static int stac92xx_parse_auto_config(struct hda_codec *codec, hda_nid_t dig_out, hda_nid_t dig_in) { struct sigmatel_spec *spec = codec->spec; int hp_swap = 0; int i, err; if ((err = snd_hda_parse_pin_def_config(codec, &spec->autocfg, spec->dmic_nids)) < 0) return err; if (! spec->autocfg.line_outs) return 0; /* can't find valid pin config */ /* If we have no real line-out pin and multiple hp-outs, HPs should * be set up as multi-channel outputs. */ if (is_dual_headphones(codec)) { /* Copy hp_outs to line_outs, backup line_outs in * speaker_outs so that the following routines can handle * HP pins as primary outputs. */ snd_printdd("stac92xx: Enabling multi-HPs workaround\n"); memcpy(spec->autocfg.speaker_pins, spec->autocfg.line_out_pins, sizeof(spec->autocfg.line_out_pins)); spec->autocfg.speaker_outs = spec->autocfg.line_outs; memcpy(spec->autocfg.line_out_pins, spec->autocfg.hp_pins, sizeof(spec->autocfg.hp_pins)); spec->autocfg.line_outs = spec->autocfg.hp_outs; spec->autocfg.line_out_type = AUTO_PIN_HP_OUT; spec->autocfg.hp_outs = 0; hp_swap = 1; } if (spec->autocfg.mono_out_pin) { int dir = get_wcaps(codec, spec->autocfg.mono_out_pin) & (AC_WCAP_OUT_AMP | AC_WCAP_IN_AMP); u32 caps = query_amp_caps(codec, spec->autocfg.mono_out_pin, dir); hda_nid_t conn_list[1]; /* get the mixer node and then the mono mux if it exists */ if (snd_hda_get_connections(codec, spec->autocfg.mono_out_pin, conn_list, 1) && snd_hda_get_connections(codec, conn_list[0], conn_list, 1) > 0) { int wcaps = get_wcaps(codec, conn_list[0]); int wid_type = get_wcaps_type(wcaps); /* LR swap check, some stac925x have a mux that * changes the DACs output path instead of the * mono-mux path. */ if (wid_type == AC_WID_AUD_SEL && !(wcaps & AC_WCAP_LR_SWAP)) spec->mono_nid = conn_list[0]; } if (dir) { hda_nid_t nid = spec->autocfg.mono_out_pin; /* most mono outs have a least a mute/unmute switch */ dir = (dir & AC_WCAP_OUT_AMP) ? HDA_OUTPUT : HDA_INPUT; err = stac92xx_add_control(spec, STAC_CTL_WIDGET_MUTE, "Mono Playback Switch", HDA_COMPOSE_AMP_VAL(nid, 1, 0, dir)); if (err < 0) return err; /* check for volume support for the amp */ if ((caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT) { err = stac92xx_add_control(spec, STAC_CTL_WIDGET_VOL, "Mono Playback Volume", HDA_COMPOSE_AMP_VAL(nid, 1, 0, dir)); if (err < 0) return err; } } stac92xx_auto_set_pinctl(codec, spec->autocfg.mono_out_pin, AC_PINCTL_OUT_EN); } if (!spec->multiout.num_dacs) { err = stac92xx_auto_fill_dac_nids(codec); if (err < 0) return err; err = stac92xx_auto_create_multi_out_ctls(codec, &spec->autocfg); if (err < 0) return err; } /* setup analog beep controls */ if (spec->anabeep_nid > 0) { err = stac92xx_auto_create_beep_ctls(codec, spec->anabeep_nid); if (err < 0) return err; } /* setup digital beep controls and input device */ #ifdef CONFIG_SND_HDA_INPUT_BEEP if (spec->digbeep_nid > 0) { hda_nid_t nid = spec->digbeep_nid; unsigned int caps; err = stac92xx_auto_create_beep_ctls(codec, nid); if (err < 0) return err; err = snd_hda_attach_beep_device(codec, nid); if (err < 0) return err; if (codec->beep) { /* IDT/STAC codecs have linear beep tone parameter */ codec->beep->linear_tone = spec->linear_tone_beep; /* if no beep switch is available, make its own one */ caps = query_amp_caps(codec, nid, HDA_OUTPUT); if (!(caps & AC_AMPCAP_MUTE)) { err = stac92xx_beep_switch_ctl(codec); if (err < 0) return err; } } } #endif err = stac92xx_auto_create_hp_ctls(codec, &spec->autocfg); if (err < 0) return err; /* All output parsing done, now restore the swapped hp pins */ if (hp_swap) { memcpy(spec->autocfg.hp_pins, spec->autocfg.line_out_pins, sizeof(spec->autocfg.hp_pins)); spec->autocfg.hp_outs = spec->autocfg.line_outs; spec->autocfg.line_out_type = AUTO_PIN_HP_OUT; spec->autocfg.line_outs = 0; } if (stac_check_auto_mic(codec)) { spec->auto_mic = 1; /* only one capture for auto-mic */ spec->num_adcs = 1; spec->num_caps = 1; spec->num_muxes = 1; } for (i = 0; i < spec->num_caps; i++) { err = stac92xx_add_capvol_ctls(codec, spec->capvols[i], spec->capsws[i], i); if (err < 0) return err; } err = stac92xx_auto_create_analog_input_ctls(codec, &spec->autocfg); if (err < 0) return err; if (spec->mono_nid > 0) { err = stac92xx_auto_create_mono_output_ctls(codec); if (err < 0) return err; } if (spec->num_dmics > 0 && !spec->dinput_mux) if ((err = stac92xx_auto_create_dmic_input_ctls(codec, &spec->autocfg)) < 0) return err; if (spec->num_muxes > 0) { err = stac92xx_auto_create_mux_input_ctls(codec); if (err < 0) return err; } if (spec->num_smuxes > 0) { err = stac92xx_auto_create_spdif_mux_ctls(codec); if (err < 0) return err; } err = stac92xx_add_input_source(spec); if (err < 0) return err; spec->multiout.max_channels = spec->multiout.num_dacs * 2; if (spec->multiout.max_channels > 2) spec->surr_switch = 1; if (spec->autocfg.dig_outs) spec->multiout.dig_out_nid = dig_out; if (dig_in && spec->autocfg.dig_in_pin) spec->dig_in_nid = dig_in; if (spec->kctls.list) spec->mixers[spec->num_mixers++] = spec->kctls.list; spec->input_mux = &spec->private_imux; if (!spec->dinput_mux) spec->dinput_mux = &spec->private_dimux; spec->sinput_mux = &spec->private_smux; spec->mono_mux = &spec->private_mono_mux; return 1; } /* add playback controls for HP output */ static int stac9200_auto_create_hp_ctls(struct hda_codec *codec, struct auto_pin_cfg *cfg) { struct sigmatel_spec *spec = codec->spec; hda_nid_t pin = cfg->hp_pins[0]; unsigned int wid_caps; if (! pin) return 0; wid_caps = get_wcaps(codec, pin); if (wid_caps & AC_WCAP_UNSOL_CAP) spec->hp_detect = 1; return 0; } /* add playback controls for LFE output */ static int stac9200_auto_create_lfe_ctls(struct hda_codec *codec, struct auto_pin_cfg *cfg) { struct sigmatel_spec *spec = codec->spec; int err; hda_nid_t lfe_pin = 0x0; int i; /* * search speaker outs and line outs for a mono speaker pin * with an amp. If one is found, add LFE controls * for it. */ for (i = 0; i < spec->autocfg.speaker_outs && lfe_pin == 0x0; i++) { hda_nid_t pin = spec->autocfg.speaker_pins[i]; unsigned int wcaps = get_wcaps(codec, pin); wcaps &= (AC_WCAP_STEREO | AC_WCAP_OUT_AMP); if (wcaps == AC_WCAP_OUT_AMP) /* found a mono speaker with an amp, must be lfe */ lfe_pin = pin; } /* if speaker_outs is 0, then speakers may be in line_outs */ if (lfe_pin == 0 && spec->autocfg.speaker_outs == 0) { for (i = 0; i < spec->autocfg.line_outs && lfe_pin == 0x0; i++) { hda_nid_t pin = spec->autocfg.line_out_pins[i]; unsigned int defcfg; defcfg = snd_hda_codec_get_pincfg(codec, pin); if (get_defcfg_device(defcfg) == AC_JACK_SPEAKER) { unsigned int wcaps = get_wcaps(codec, pin); wcaps &= (AC_WCAP_STEREO | AC_WCAP_OUT_AMP); if (wcaps == AC_WCAP_OUT_AMP) /* found a mono speaker with an amp, must be lfe */ lfe_pin = pin; } } } if (lfe_pin) { err = create_controls(codec, "LFE", lfe_pin, 1); if (err < 0) return err; } return 0; } static int stac9200_parse_auto_config(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; int err; if ((err = snd_hda_parse_pin_def_config(codec, &spec->autocfg, NULL)) < 0) return err; if ((err = stac92xx_auto_create_analog_input_ctls(codec, &spec->autocfg)) < 0) return err; if ((err = stac9200_auto_create_hp_ctls(codec, &spec->autocfg)) < 0) return err; if ((err = stac9200_auto_create_lfe_ctls(codec, &spec->autocfg)) < 0) return err; if (spec->num_muxes > 0) { err = stac92xx_auto_create_mux_input_ctls(codec); if (err < 0) return err; } err = stac92xx_add_input_source(spec); if (err < 0) return err; if (spec->autocfg.dig_outs) spec->multiout.dig_out_nid = 0x05; if (spec->autocfg.dig_in_pin) spec->dig_in_nid = 0x04; if (spec->kctls.list) spec->mixers[spec->num_mixers++] = spec->kctls.list; spec->input_mux = &spec->private_imux; spec->dinput_mux = &spec->private_dimux; return 1; } /* * Early 2006 Intel Macintoshes with STAC9220X5 codecs seem to have a * funky external mute control using GPIO pins. */ static void stac_gpio_set(struct hda_codec *codec, unsigned int mask, unsigned int dir_mask, unsigned int data) { unsigned int gpiostate, gpiomask, gpiodir; gpiostate = snd_hda_codec_read(codec, codec->afg, 0, AC_VERB_GET_GPIO_DATA, 0); gpiostate = (gpiostate & ~dir_mask) | (data & dir_mask); gpiomask = snd_hda_codec_read(codec, codec->afg, 0, AC_VERB_GET_GPIO_MASK, 0); gpiomask |= mask; gpiodir = snd_hda_codec_read(codec, codec->afg, 0, AC_VERB_GET_GPIO_DIRECTION, 0); gpiodir |= dir_mask; /* Configure GPIOx as CMOS */ snd_hda_codec_write(codec, codec->afg, 0, 0x7e7, 0); snd_hda_codec_write(codec, codec->afg, 0, AC_VERB_SET_GPIO_MASK, gpiomask); snd_hda_codec_read(codec, codec->afg, 0, AC_VERB_SET_GPIO_DIRECTION, gpiodir); /* sync */ msleep(1); snd_hda_codec_read(codec, codec->afg, 0, AC_VERB_SET_GPIO_DATA, gpiostate); /* sync */ } static int stac92xx_add_jack(struct hda_codec *codec, hda_nid_t nid, int type) { #ifdef CONFIG_SND_HDA_INPUT_JACK int def_conf = snd_hda_codec_get_pincfg(codec, nid); int connectivity = get_defcfg_connect(def_conf); char name[32]; int err; if (connectivity && connectivity != AC_JACK_PORT_FIXED) return 0; snprintf(name, sizeof(name), "%s at %s %s Jack", snd_hda_get_jack_type(def_conf), snd_hda_get_jack_connectivity(def_conf), snd_hda_get_jack_location(def_conf)); err = snd_hda_input_jack_add(codec, nid, type, name); if (err < 0) return err; #endif /* CONFIG_SND_HDA_INPUT_JACK */ return 0; } static int stac_add_event(struct sigmatel_spec *spec, hda_nid_t nid, unsigned char type, int data) { struct sigmatel_event *event; snd_array_init(&spec->events, sizeof(*event), 32); event = snd_array_new(&spec->events); if (!event) return -ENOMEM; event->nid = nid; event->type = type; event->tag = spec->events.used; event->data = data; return event->tag; } static struct sigmatel_event *stac_get_event(struct hda_codec *codec, hda_nid_t nid) { struct sigmatel_spec *spec = codec->spec; struct sigmatel_event *event = spec->events.list; int i; for (i = 0; i < spec->events.used; i++, event++) { if (event->nid == nid) return event; } return NULL; } static struct sigmatel_event *stac_get_event_from_tag(struct hda_codec *codec, unsigned char tag) { struct sigmatel_spec *spec = codec->spec; struct sigmatel_event *event = spec->events.list; int i; for (i = 0; i < spec->events.used; i++, event++) { if (event->tag == tag) return event; } return NULL; } /* check if given nid is a valid pin and no other events are assigned * to it. If OK, assign the event, set the unsol flag, and returns 1. * Otherwise, returns zero. */ static int enable_pin_detect(struct hda_codec *codec, hda_nid_t nid, unsigned int type) { struct sigmatel_event *event; int tag; if (!(get_wcaps(codec, nid) & AC_WCAP_UNSOL_CAP)) return 0; event = stac_get_event(codec, nid); if (event) { if (event->type != type) return 0; tag = event->tag; } else { tag = stac_add_event(codec->spec, nid, type, 0); if (tag < 0) return 0; } snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | tag); return 1; } static int is_nid_hp_pin(struct auto_pin_cfg *cfg, hda_nid_t nid) { int i; for (i = 0; i < cfg->hp_outs; i++) if (cfg->hp_pins[i] == nid) return 1; /* nid is a HP-Out */ return 0; /* nid is not a HP-Out */ }; static void stac92xx_power_down(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; /* power down inactive DACs */ hda_nid_t *dac; for (dac = spec->dac_list; *dac; dac++) if (!check_all_dac_nids(spec, *dac)) snd_hda_codec_write(codec, *dac, 0, AC_VERB_SET_POWER_STATE, AC_PWRST_D3); } static void stac_toggle_power_map(struct hda_codec *codec, hda_nid_t nid, int enable); static inline int get_int_hint(struct hda_codec *codec, const char *key, int *valp) { const char *p; p = snd_hda_get_hint(codec, key); if (p) { unsigned long val; if (!strict_strtoul(p, 0, &val)) { *valp = val; return 1; } } return 0; } /* override some hints from the hwdep entry */ static void stac_store_hints(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; int val; val = snd_hda_get_bool_hint(codec, "hp_detect"); if (val >= 0) spec->hp_detect = val; if (get_int_hint(codec, "gpio_mask", &spec->gpio_mask)) { spec->eapd_mask = spec->gpio_dir = spec->gpio_data = spec->gpio_mask; } if (get_int_hint(codec, "gpio_dir", &spec->gpio_dir)) spec->gpio_mask &= spec->gpio_mask; if (get_int_hint(codec, "gpio_data", &spec->gpio_data)) spec->gpio_dir &= spec->gpio_mask; if (get_int_hint(codec, "eapd_mask", &spec->eapd_mask)) spec->eapd_mask &= spec->gpio_mask; if (get_int_hint(codec, "gpio_mute", &spec->gpio_mute)) spec->gpio_mute &= spec->gpio_mask; val = snd_hda_get_bool_hint(codec, "eapd_switch"); if (val >= 0) spec->eapd_switch = val; get_int_hint(codec, "gpio_led_polarity", &spec->gpio_led_polarity); if (get_int_hint(codec, "gpio_led", &spec->gpio_led)) { spec->gpio_mask |= spec->gpio_led; spec->gpio_dir |= spec->gpio_led; if (spec->gpio_led_polarity) spec->gpio_data |= spec->gpio_led; } } static int stac92xx_init(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; struct auto_pin_cfg *cfg = &spec->autocfg; unsigned int gpio; int i; snd_hda_sequence_write(codec, spec->init); /* power down adcs initially */ if (spec->powerdown_adcs) for (i = 0; i < spec->num_adcs; i++) snd_hda_codec_write(codec, spec->adc_nids[i], 0, AC_VERB_SET_POWER_STATE, AC_PWRST_D3); /* override some hints */ stac_store_hints(codec); /* set up GPIO */ gpio = spec->gpio_data; /* turn on EAPD statically when spec->eapd_switch isn't set. * otherwise, unsol event will turn it on/off dynamically */ if (!spec->eapd_switch) gpio |= spec->eapd_mask; stac_gpio_set(codec, spec->gpio_mask, spec->gpio_dir, gpio); /* set up pins */ if (spec->hp_detect) { /* Enable unsolicited responses on the HP widget */ for (i = 0; i < cfg->hp_outs; i++) { hda_nid_t nid = cfg->hp_pins[i]; enable_pin_detect(codec, nid, STAC_HP_EVENT); } if (cfg->line_out_type == AUTO_PIN_LINE_OUT && cfg->speaker_outs > 0) { /* enable pin-detect for line-outs as well */ for (i = 0; i < cfg->line_outs; i++) { hda_nid_t nid = cfg->line_out_pins[i]; enable_pin_detect(codec, nid, STAC_LO_EVENT); } } /* force to enable the first line-out; the others are set up * in unsol_event */ stac92xx_auto_set_pinctl(codec, spec->autocfg.line_out_pins[0], AC_PINCTL_OUT_EN); /* fake event to set up pins */ if (cfg->hp_pins[0]) stac_issue_unsol_event(codec, cfg->hp_pins[0]); else if (cfg->line_out_pins[0]) stac_issue_unsol_event(codec, cfg->line_out_pins[0]); } else { stac92xx_auto_init_multi_out(codec); stac92xx_auto_init_hp_out(codec); for (i = 0; i < cfg->hp_outs; i++) stac_toggle_power_map(codec, cfg->hp_pins[i], 1); } if (spec->auto_mic) { /* initialize connection to analog input */ if (spec->dmux_nids) snd_hda_codec_write_cache(codec, spec->dmux_nids[0], 0, AC_VERB_SET_CONNECT_SEL, 0); if (enable_pin_detect(codec, spec->ext_mic.pin, STAC_MIC_EVENT)) stac_issue_unsol_event(codec, spec->ext_mic.pin); if (enable_pin_detect(codec, spec->dock_mic.pin, STAC_MIC_EVENT)) stac_issue_unsol_event(codec, spec->dock_mic.pin); } for (i = 0; i < cfg->num_inputs; i++) { hda_nid_t nid = cfg->inputs[i].pin; int type = cfg->inputs[i].type; unsigned int pinctl, conf; if (type == AUTO_PIN_MIC) { /* for mic pins, force to initialize */ pinctl = stac92xx_get_default_vref(codec, nid); pinctl |= AC_PINCTL_IN_EN; stac92xx_auto_set_pinctl(codec, nid, pinctl); } else { pinctl = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_PIN_WIDGET_CONTROL, 0); /* if PINCTL already set then skip */ /* Also, if both INPUT and OUTPUT are set, * it must be a BIOS bug; need to override, too */ if (!(pinctl & AC_PINCTL_IN_EN) || (pinctl & AC_PINCTL_OUT_EN)) { pinctl &= ~AC_PINCTL_OUT_EN; pinctl |= AC_PINCTL_IN_EN; stac92xx_auto_set_pinctl(codec, nid, pinctl); } } conf = snd_hda_codec_get_pincfg(codec, nid); if (get_defcfg_connect(conf) != AC_JACK_PORT_FIXED) { if (enable_pin_detect(codec, nid, STAC_INSERT_EVENT)) stac_issue_unsol_event(codec, nid); } } for (i = 0; i < spec->num_dmics; i++) stac92xx_auto_set_pinctl(codec, spec->dmic_nids[i], AC_PINCTL_IN_EN); if (cfg->dig_out_pins[0]) stac92xx_auto_set_pinctl(codec, cfg->dig_out_pins[0], AC_PINCTL_OUT_EN); if (cfg->dig_in_pin) stac92xx_auto_set_pinctl(codec, cfg->dig_in_pin, AC_PINCTL_IN_EN); for (i = 0; i < spec->num_pwrs; i++) { hda_nid_t nid = spec->pwr_nids[i]; int pinctl, def_conf; /* power on when no jack detection is available */ if (!spec->hp_detect) { stac_toggle_power_map(codec, nid, 1); continue; } if (is_nid_hp_pin(cfg, nid)) continue; /* already has an unsol event */ pinctl = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_PIN_WIDGET_CONTROL, 0); /* outputs are only ports capable of power management * any attempts on powering down a input port cause the * referenced VREF to act quirky. */ if (pinctl & AC_PINCTL_IN_EN) { stac_toggle_power_map(codec, nid, 1); continue; } def_conf = snd_hda_codec_get_pincfg(codec, nid); def_conf = get_defcfg_connect(def_conf); /* skip any ports that don't have jacks since presence * detection is useless */ if (def_conf != AC_JACK_PORT_COMPLEX) { if (def_conf != AC_JACK_PORT_NONE) stac_toggle_power_map(codec, nid, 1); continue; } if (enable_pin_detect(codec, nid, STAC_PWR_EVENT)) stac_issue_unsol_event(codec, nid); } /* sync mute LED */ if (spec->gpio_led) hda_call_check_power_status(codec, 0x01); if (spec->dac_list) stac92xx_power_down(codec); return 0; } static void stac92xx_free_kctls(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; if (spec->kctls.list) { struct snd_kcontrol_new *kctl = spec->kctls.list; int i; for (i = 0; i < spec->kctls.used; i++) kfree(kctl[i].name); } snd_array_free(&spec->kctls); } static void stac92xx_shutup(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; snd_hda_shutup_pins(codec); if (spec->eapd_mask) stac_gpio_set(codec, spec->gpio_mask, spec->gpio_dir, spec->gpio_data & ~spec->eapd_mask); } static void stac92xx_free(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; if (! spec) return; stac92xx_shutup(codec); snd_hda_input_jack_free(codec); snd_array_free(&spec->events); kfree(spec); snd_hda_detach_beep_device(codec); } static void stac92xx_set_pinctl(struct hda_codec *codec, hda_nid_t nid, unsigned int flag) { unsigned int old_ctl, pin_ctl; pin_ctl = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_PIN_WIDGET_CONTROL, 0x00); if (pin_ctl & AC_PINCTL_IN_EN) { /* * we need to check the current set-up direction of * shared input pins since they can be switched via * "xxx as Output" mixer switch */ struct sigmatel_spec *spec = codec->spec; if (nid == spec->line_switch || nid == spec->mic_switch) return; } old_ctl = pin_ctl; /* if setting pin direction bits, clear the current direction bits first */ if (flag & (AC_PINCTL_IN_EN | AC_PINCTL_OUT_EN)) pin_ctl &= ~(AC_PINCTL_IN_EN | AC_PINCTL_OUT_EN); pin_ctl |= flag; if (old_ctl != pin_ctl) snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_PIN_WIDGET_CONTROL, pin_ctl); } static void stac92xx_reset_pinctl(struct hda_codec *codec, hda_nid_t nid, unsigned int flag) { unsigned int pin_ctl = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_PIN_WIDGET_CONTROL, 0x00); if (pin_ctl & flag) snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_PIN_WIDGET_CONTROL, pin_ctl & ~flag); } static inline int get_pin_presence(struct hda_codec *codec, hda_nid_t nid) { if (!nid) return 0; return snd_hda_jack_detect(codec, nid); } static void stac92xx_line_out_detect(struct hda_codec *codec, int presence) { struct sigmatel_spec *spec = codec->spec; struct auto_pin_cfg *cfg = &spec->autocfg; int i; for (i = 0; i < cfg->line_outs; i++) { if (presence) break; presence = get_pin_presence(codec, cfg->line_out_pins[i]); if (presence) { unsigned int pinctl; pinctl = snd_hda_codec_read(codec, cfg->line_out_pins[i], 0, AC_VERB_GET_PIN_WIDGET_CONTROL, 0); if (pinctl & AC_PINCTL_IN_EN) presence = 0; /* mic- or line-input */ } } if (presence) { /* disable speakers */ for (i = 0; i < cfg->speaker_outs; i++) stac92xx_reset_pinctl(codec, cfg->speaker_pins[i], AC_PINCTL_OUT_EN); if (spec->eapd_mask && spec->eapd_switch) stac_gpio_set(codec, spec->gpio_mask, spec->gpio_dir, spec->gpio_data & ~spec->eapd_mask); } else { /* enable speakers */ for (i = 0; i < cfg->speaker_outs; i++) stac92xx_set_pinctl(codec, cfg->speaker_pins[i], AC_PINCTL_OUT_EN); if (spec->eapd_mask && spec->eapd_switch) stac_gpio_set(codec, spec->gpio_mask, spec->gpio_dir, spec->gpio_data | spec->eapd_mask); } } /* return non-zero if the hp-pin of the given array index isn't * a jack-detection target */ static int no_hp_sensing(struct sigmatel_spec *spec, int i) { struct auto_pin_cfg *cfg = &spec->autocfg; /* ignore sensing of shared line and mic jacks */ if (cfg->hp_pins[i] == spec->line_switch) return 1; if (cfg->hp_pins[i] == spec->mic_switch) return 1; /* ignore if the pin is set as line-out */ if (cfg->hp_pins[i] == spec->hp_switch) return 1; return 0; } static void stac92xx_hp_detect(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; struct auto_pin_cfg *cfg = &spec->autocfg; int i, presence; presence = 0; if (spec->gpio_mute) presence = !(snd_hda_codec_read(codec, codec->afg, 0, AC_VERB_GET_GPIO_DATA, 0) & spec->gpio_mute); for (i = 0; i < cfg->hp_outs; i++) { if (presence) break; if (no_hp_sensing(spec, i)) continue; presence = get_pin_presence(codec, cfg->hp_pins[i]); if (presence) { unsigned int pinctl; pinctl = snd_hda_codec_read(codec, cfg->hp_pins[i], 0, AC_VERB_GET_PIN_WIDGET_CONTROL, 0); if (pinctl & AC_PINCTL_IN_EN) presence = 0; /* mic- or line-input */ } } if (presence) { /* disable lineouts */ if (spec->hp_switch) stac92xx_reset_pinctl(codec, spec->hp_switch, AC_PINCTL_OUT_EN); for (i = 0; i < cfg->line_outs; i++) stac92xx_reset_pinctl(codec, cfg->line_out_pins[i], AC_PINCTL_OUT_EN); } else { /* enable lineouts */ if (spec->hp_switch) stac92xx_set_pinctl(codec, spec->hp_switch, AC_PINCTL_OUT_EN); for (i = 0; i < cfg->line_outs; i++) stac92xx_set_pinctl(codec, cfg->line_out_pins[i], AC_PINCTL_OUT_EN); } stac92xx_line_out_detect(codec, presence); /* toggle hp outs */ for (i = 0; i < cfg->hp_outs; i++) { unsigned int val = AC_PINCTL_OUT_EN | AC_PINCTL_HP_EN; if (no_hp_sensing(spec, i)) continue; if (presence) stac92xx_set_pinctl(codec, cfg->hp_pins[i], val); #if 0 /* FIXME */ /* Resetting the pinctl like below may lead to (a sort of) regressions * on some devices since they use the HP pin actually for line/speaker * outs although the default pin config shows a different pin (that is * wrong and useless). * * So, it's basically a problem of default pin configs, likely a BIOS issue. * But, disabling the code below just works around it, and I'm too tired of * bug reports with such devices... */ else stac92xx_reset_pinctl(codec, cfg->hp_pins[i], val); #endif /* FIXME */ } } static void stac_toggle_power_map(struct hda_codec *codec, hda_nid_t nid, int enable) { struct sigmatel_spec *spec = codec->spec; unsigned int idx, val; for (idx = 0; idx < spec->num_pwrs; idx++) { if (spec->pwr_nids[idx] == nid) break; } if (idx >= spec->num_pwrs) return; /* several codecs have two power down bits */ if (spec->pwr_mapping) idx = spec->pwr_mapping[idx]; else idx = 1 << idx; val = snd_hda_codec_read(codec, codec->afg, 0, 0x0fec, 0x0) & 0xff; if (enable) val &= ~idx; else val |= idx; /* power down unused output ports */ snd_hda_codec_write(codec, codec->afg, 0, 0x7ec, val); } static void stac92xx_pin_sense(struct hda_codec *codec, hda_nid_t nid) { stac_toggle_power_map(codec, nid, get_pin_presence(codec, nid)); } /* get the pin connection (fixed, none, etc) */ static unsigned int stac_get_defcfg_connect(struct hda_codec *codec, int idx) { struct sigmatel_spec *spec = codec->spec; unsigned int cfg; cfg = snd_hda_codec_get_pincfg(codec, spec->pin_nids[idx]); return get_defcfg_connect(cfg); } static int stac92xx_connected_ports(struct hda_codec *codec, hda_nid_t *nids, int num_nids) { struct sigmatel_spec *spec = codec->spec; int idx, num; unsigned int def_conf; for (num = 0; num < num_nids; num++) { for (idx = 0; idx < spec->num_pins; idx++) if (spec->pin_nids[idx] == nids[num]) break; if (idx >= spec->num_pins) break; def_conf = stac_get_defcfg_connect(codec, idx); if (def_conf == AC_JACK_PORT_NONE) break; } return num; } static void stac92xx_mic_detect(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; struct sigmatel_mic_route *mic; if (get_pin_presence(codec, spec->ext_mic.pin)) mic = &spec->ext_mic; else if (get_pin_presence(codec, spec->dock_mic.pin)) mic = &spec->dock_mic; else mic = &spec->int_mic; if (mic->dmux_idx >= 0) snd_hda_codec_write_cache(codec, spec->dmux_nids[0], 0, AC_VERB_SET_CONNECT_SEL, mic->dmux_idx); if (mic->mux_idx >= 0) snd_hda_codec_write_cache(codec, spec->mux_nids[0], 0, AC_VERB_SET_CONNECT_SEL, mic->mux_idx); } static void stac_issue_unsol_event(struct hda_codec *codec, hda_nid_t nid) { struct sigmatel_event *event = stac_get_event(codec, nid); if (!event) return; codec->patch_ops.unsol_event(codec, (unsigned)event->tag << 26); } static void stac92xx_unsol_event(struct hda_codec *codec, unsigned int res) { struct sigmatel_spec *spec = codec->spec; struct sigmatel_event *event; int tag, data; tag = (res >> 26) & 0x7f; event = stac_get_event_from_tag(codec, tag); if (!event) return; switch (event->type) { case STAC_HP_EVENT: case STAC_LO_EVENT: stac92xx_hp_detect(codec); break; case STAC_MIC_EVENT: stac92xx_mic_detect(codec); break; } switch (event->type) { case STAC_HP_EVENT: case STAC_LO_EVENT: case STAC_MIC_EVENT: case STAC_INSERT_EVENT: case STAC_PWR_EVENT: if (spec->num_pwrs > 0) stac92xx_pin_sense(codec, event->nid); snd_hda_input_jack_report(codec, event->nid); switch (codec->subsystem_id) { case 0x103c308f: if (event->nid == 0xb) { int pin = AC_PINCTL_IN_EN; if (get_pin_presence(codec, 0xa) && get_pin_presence(codec, 0xb)) pin |= AC_PINCTL_VREF_80; if (!get_pin_presence(codec, 0xb)) pin |= AC_PINCTL_VREF_80; /* toggle VREF state based on mic + hp pin * status */ stac92xx_auto_set_pinctl(codec, 0x0a, pin); } } break; case STAC_VREF_EVENT: data = snd_hda_codec_read(codec, codec->afg, 0, AC_VERB_GET_GPIO_DATA, 0); /* toggle VREF state based on GPIOx status */ snd_hda_codec_write(codec, codec->afg, 0, 0x7e0, !!(data & (1 << event->data))); break; } } static int hp_blike_system(u32 subsystem_id); static void set_hp_led_gpio(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; unsigned int gpio; if (spec->gpio_led) return; gpio = snd_hda_param_read(codec, codec->afg, AC_PAR_GPIO_CAP); gpio &= AC_GPIO_IO_COUNT; if (gpio > 3) spec->gpio_led = 0x08; /* GPIO 3 */ else spec->gpio_led = 0x01; /* GPIO 0 */ } /* * This method searches for the mute LED GPIO configuration * provided as OEM string in SMBIOS. The format of that string * is HP_Mute_LED_P_G or HP_Mute_LED_P * where P can be 0 or 1 and defines mute LED GPIO control state (low/high) * that corresponds to the NOT muted state of the master volume * and G is the index of the GPIO to use as the mute LED control (0..9) * If _G portion is missing it is assigned based on the codec ID * * So, HP B-series like systems may have HP_Mute_LED_0 (current models) * or HP_Mute_LED_0_3 (future models) OEM SMBIOS strings * * * The dv-series laptops don't seem to have the HP_Mute_LED* strings in * SMBIOS - at least the ones I have seen do not have them - which include * my own system (HP Pavilion dv6-1110ax) and my cousin's * HP Pavilion dv9500t CTO. * Need more information on whether it is true across the entire series. * -- kunal */ static int find_mute_led_gpio(struct hda_codec *codec, int default_polarity) { struct sigmatel_spec *spec = codec->spec; const struct dmi_device *dev = NULL; if ((codec->subsystem_id >> 16) == PCI_VENDOR_ID_HP) { while ((dev = dmi_find_device(DMI_DEV_TYPE_OEM_STRING, NULL, dev))) { if (sscanf(dev->name, "HP_Mute_LED_%d_%d", &spec->gpio_led_polarity, &spec->gpio_led) == 2) { spec->gpio_led = 1 << spec->gpio_led; return 1; } if (sscanf(dev->name, "HP_Mute_LED_%d", &spec->gpio_led_polarity) == 1) { set_hp_led_gpio(codec); return 1; } } /* * Fallback case - if we don't find the DMI strings, * we statically set the GPIO - if not a B-series system. */ if (!hp_blike_system(codec->subsystem_id)) { set_hp_led_gpio(codec); spec->gpio_led_polarity = default_polarity; return 1; } } return 0; } static int hp_blike_system(u32 subsystem_id) { switch (subsystem_id) { case 0x103c1520: case 0x103c1521: case 0x103c1523: case 0x103c1524: case 0x103c1525: case 0x103c1722: case 0x103c1723: case 0x103c1724: case 0x103c1725: case 0x103c1726: case 0x103c1727: case 0x103c1728: case 0x103c1729: case 0x103c172a: case 0x103c172b: case 0x103c307e: case 0x103c307f: case 0x103c3080: case 0x103c3081: case 0x103c7007: case 0x103c7008: return 1; } return 0; } #ifdef CONFIG_PROC_FS static void stac92hd_proc_hook(struct snd_info_buffer *buffer, struct hda_codec *codec, hda_nid_t nid) { if (nid == codec->afg) snd_iprintf(buffer, "Power-Map: 0x%02x\n", snd_hda_codec_read(codec, nid, 0, 0x0fec, 0x0)); } static void analog_loop_proc_hook(struct snd_info_buffer *buffer, struct hda_codec *codec, unsigned int verb) { snd_iprintf(buffer, "Analog Loopback: 0x%02x\n", snd_hda_codec_read(codec, codec->afg, 0, verb, 0)); } /* stac92hd71bxx, stac92hd73xx */ static void stac92hd7x_proc_hook(struct snd_info_buffer *buffer, struct hda_codec *codec, hda_nid_t nid) { stac92hd_proc_hook(buffer, codec, nid); if (nid == codec->afg) analog_loop_proc_hook(buffer, codec, 0xfa0); } static void stac9205_proc_hook(struct snd_info_buffer *buffer, struct hda_codec *codec, hda_nid_t nid) { if (nid == codec->afg) analog_loop_proc_hook(buffer, codec, 0xfe0); } static void stac927x_proc_hook(struct snd_info_buffer *buffer, struct hda_codec *codec, hda_nid_t nid) { if (nid == codec->afg) analog_loop_proc_hook(buffer, codec, 0xfeb); } #else #define stac92hd_proc_hook NULL #define stac92hd7x_proc_hook NULL #define stac9205_proc_hook NULL #define stac927x_proc_hook NULL #endif #ifdef SND_HDA_NEEDS_RESUME static int stac92xx_resume(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; stac92xx_init(codec); snd_hda_codec_resume_amp(codec); snd_hda_codec_resume_cache(codec); /* fake event to set up pins again to override cached values */ if (spec->hp_detect) { if (spec->autocfg.hp_pins[0]) stac_issue_unsol_event(codec, spec->autocfg.hp_pins[0]); else if (spec->autocfg.line_out_pins[0]) stac_issue_unsol_event(codec, spec->autocfg.line_out_pins[0]); } /* sync mute LED */ if (spec->gpio_led) hda_call_check_power_status(codec, 0x01); return 0; } /* * using power check for controlling mute led of HP notebooks * check for mute state only on Speakers (nid = 0x10) * * For this feature CONFIG_SND_HDA_POWER_SAVE is needed, otherwise * the LED is NOT working properly ! * * Changed name to reflect that it now works for any designated * model, not just HP HDX. */ #ifdef CONFIG_SND_HDA_POWER_SAVE static int stac92xx_hp_check_power_status(struct hda_codec *codec, hda_nid_t nid) { struct sigmatel_spec *spec = codec->spec; int i, muted = 1; for (i = 0; i < spec->multiout.num_dacs; i++) { nid = spec->multiout.dac_nids[i]; if (!(snd_hda_codec_amp_read(codec, nid, 0, HDA_OUTPUT, 0) & HDA_AMP_MUTE)) { muted = 0; /* something heard */ break; } } if (muted) spec->gpio_data &= ~spec->gpio_led; /* orange */ else spec->gpio_data |= spec->gpio_led; /* white */ if (!spec->gpio_led_polarity) { /* LED state is inverted on these systems */ spec->gpio_data ^= spec->gpio_led; } stac_gpio_set(codec, spec->gpio_mask, spec->gpio_dir, spec->gpio_data); return 0; } #endif static int stac92xx_suspend(struct hda_codec *codec, pm_message_t state) { stac92xx_shutup(codec); return 0; } #endif static struct hda_codec_ops stac92xx_patch_ops = { .build_controls = stac92xx_build_controls, .build_pcms = stac92xx_build_pcms, .init = stac92xx_init, .free = stac92xx_free, .unsol_event = stac92xx_unsol_event, #ifdef SND_HDA_NEEDS_RESUME .suspend = stac92xx_suspend, .resume = stac92xx_resume, #endif .reboot_notify = stac92xx_shutup, }; static int patch_stac9200(struct hda_codec *codec) { struct sigmatel_spec *spec; int err; spec = kzalloc(sizeof(*spec), GFP_KERNEL); if (spec == NULL) return -ENOMEM; codec->no_trigger_sense = 1; codec->spec = spec; spec->linear_tone_beep = 1; spec->num_pins = ARRAY_SIZE(stac9200_pin_nids); spec->pin_nids = stac9200_pin_nids; spec->board_config = snd_hda_check_board_config(codec, STAC_9200_MODELS, stac9200_models, stac9200_cfg_tbl); if (spec->board_config < 0) snd_printdd(KERN_INFO "hda_codec: %s: BIOS auto-probing.\n", codec->chip_name); else stac92xx_set_config_regs(codec, stac9200_brd_tbl[spec->board_config]); spec->multiout.max_channels = 2; spec->multiout.num_dacs = 1; spec->multiout.dac_nids = stac9200_dac_nids; spec->adc_nids = stac9200_adc_nids; spec->mux_nids = stac9200_mux_nids; spec->num_muxes = 1; spec->num_dmics = 0; spec->num_adcs = 1; spec->num_pwrs = 0; if (spec->board_config == STAC_9200_M4 || spec->board_config == STAC_9200_M4_2 || spec->board_config == STAC_9200_OQO) spec->init = stac9200_eapd_init; else spec->init = stac9200_core_init; spec->mixer = stac9200_mixer; if (spec->board_config == STAC_9200_PANASONIC) { spec->gpio_mask = spec->gpio_dir = 0x09; spec->gpio_data = 0x00; } err = stac9200_parse_auto_config(codec); if (err < 0) { stac92xx_free(codec); return err; } /* CF-74 has no headphone detection, and the driver should *NOT* * do detection and HP/speaker toggle because the hardware does it. */ if (spec->board_config == STAC_9200_PANASONIC) spec->hp_detect = 0; codec->patch_ops = stac92xx_patch_ops; return 0; } static int patch_stac925x(struct hda_codec *codec) { struct sigmatel_spec *spec; int err; spec = kzalloc(sizeof(*spec), GFP_KERNEL); if (spec == NULL) return -ENOMEM; codec->no_trigger_sense = 1; codec->spec = spec; spec->linear_tone_beep = 1; spec->num_pins = ARRAY_SIZE(stac925x_pin_nids); spec->pin_nids = stac925x_pin_nids; /* Check first for codec ID */ spec->board_config = snd_hda_check_board_codec_sid_config(codec, STAC_925x_MODELS, stac925x_models, stac925x_codec_id_cfg_tbl); /* Now checks for PCI ID, if codec ID is not found */ if (spec->board_config < 0) spec->board_config = snd_hda_check_board_config(codec, STAC_925x_MODELS, stac925x_models, stac925x_cfg_tbl); again: if (spec->board_config < 0) snd_printdd(KERN_INFO "hda_codec: %s: BIOS auto-probing.\n", codec->chip_name); else stac92xx_set_config_regs(codec, stac925x_brd_tbl[spec->board_config]); spec->multiout.max_channels = 2; spec->multiout.num_dacs = 1; spec->multiout.dac_nids = stac925x_dac_nids; spec->adc_nids = stac925x_adc_nids; spec->mux_nids = stac925x_mux_nids; spec->num_muxes = 1; spec->num_adcs = 1; spec->num_pwrs = 0; switch (codec->vendor_id) { case 0x83847632: /* STAC9202 */ case 0x83847633: /* STAC9202D */ case 0x83847636: /* STAC9251 */ case 0x83847637: /* STAC9251D */ spec->num_dmics = STAC925X_NUM_DMICS; spec->dmic_nids = stac925x_dmic_nids; spec->num_dmuxes = ARRAY_SIZE(stac925x_dmux_nids); spec->dmux_nids = stac925x_dmux_nids; break; default: spec->num_dmics = 0; break; } spec->init = stac925x_core_init; spec->mixer = stac925x_mixer; spec->num_caps = 1; spec->capvols = stac925x_capvols; spec->capsws = stac925x_capsws; err = stac92xx_parse_auto_config(codec, 0x8, 0x7); if (!err) { if (spec->board_config < 0) { printk(KERN_WARNING "hda_codec: No auto-config is " "available, default to model=ref\n"); spec->board_config = STAC_925x_REF; goto again; } err = -EINVAL; } if (err < 0) { stac92xx_free(codec); return err; } codec->patch_ops = stac92xx_patch_ops; return 0; } static int patch_stac92hd73xx(struct hda_codec *codec) { struct sigmatel_spec *spec; hda_nid_t conn[STAC92HD73_DAC_COUNT + 2]; int err = 0; int num_dacs; spec = kzalloc(sizeof(*spec), GFP_KERNEL); if (spec == NULL) return -ENOMEM; codec->no_trigger_sense = 1; codec->spec = spec; spec->linear_tone_beep = 0; codec->slave_dig_outs = stac92hd73xx_slave_dig_outs; spec->num_pins = ARRAY_SIZE(stac92hd73xx_pin_nids); spec->pin_nids = stac92hd73xx_pin_nids; spec->board_config = snd_hda_check_board_config(codec, STAC_92HD73XX_MODELS, stac92hd73xx_models, stac92hd73xx_cfg_tbl); /* check codec subsystem id if not found */ if (spec->board_config < 0) spec->board_config = snd_hda_check_board_codec_sid_config(codec, STAC_92HD73XX_MODELS, stac92hd73xx_models, stac92hd73xx_codec_id_cfg_tbl); again: if (spec->board_config < 0) snd_printdd(KERN_INFO "hda_codec: %s: BIOS auto-probing.\n", codec->chip_name); else stac92xx_set_config_regs(codec, stac92hd73xx_brd_tbl[spec->board_config]); num_dacs = snd_hda_get_connections(codec, 0x0a, conn, STAC92HD73_DAC_COUNT + 2) - 1; if (num_dacs < 3 || num_dacs > 5) { printk(KERN_WARNING "hda_codec: Could not determine " "number of channels defaulting to DAC count\n"); num_dacs = STAC92HD73_DAC_COUNT; } spec->init = stac92hd73xx_core_init; switch (num_dacs) { case 0x3: /* 6 Channel */ spec->aloopback_ctl = stac92hd73xx_6ch_loopback; break; case 0x4: /* 8 Channel */ spec->aloopback_ctl = stac92hd73xx_8ch_loopback; break; case 0x5: /* 10 Channel */ spec->aloopback_ctl = stac92hd73xx_10ch_loopback; break; } spec->multiout.dac_nids = spec->dac_nids; spec->aloopback_mask = 0x01; spec->aloopback_shift = 8; spec->digbeep_nid = 0x1c; spec->mux_nids = stac92hd73xx_mux_nids; spec->adc_nids = stac92hd73xx_adc_nids; spec->dmic_nids = stac92hd73xx_dmic_nids; spec->dmux_nids = stac92hd73xx_dmux_nids; spec->smux_nids = stac92hd73xx_smux_nids; spec->num_muxes = ARRAY_SIZE(stac92hd73xx_mux_nids); spec->num_adcs = ARRAY_SIZE(stac92hd73xx_adc_nids); spec->num_dmuxes = ARRAY_SIZE(stac92hd73xx_dmux_nids); spec->num_caps = STAC92HD73XX_NUM_CAPS; spec->capvols = stac92hd73xx_capvols; spec->capsws = stac92hd73xx_capsws; switch (spec->board_config) { case STAC_DELL_EQ: spec->init = dell_eq_core_init; /* fallthru */ case STAC_DELL_M6_AMIC: case STAC_DELL_M6_DMIC: case STAC_DELL_M6_BOTH: spec->num_smuxes = 0; spec->eapd_switch = 0; switch (spec->board_config) { case STAC_DELL_M6_AMIC: /* Analog Mics */ snd_hda_codec_set_pincfg(codec, 0x0b, 0x90A70170); spec->num_dmics = 0; break; case STAC_DELL_M6_DMIC: /* Digital Mics */ snd_hda_codec_set_pincfg(codec, 0x13, 0x90A60160); spec->num_dmics = 1; break; case STAC_DELL_M6_BOTH: /* Both */ snd_hda_codec_set_pincfg(codec, 0x0b, 0x90A70170); snd_hda_codec_set_pincfg(codec, 0x13, 0x90A60160); spec->num_dmics = 1; break; } break; case STAC_ALIENWARE_M17X: spec->num_dmics = STAC92HD73XX_NUM_DMICS; spec->num_smuxes = ARRAY_SIZE(stac92hd73xx_smux_nids); spec->eapd_switch = 0; break; default: spec->num_dmics = STAC92HD73XX_NUM_DMICS; spec->num_smuxes = ARRAY_SIZE(stac92hd73xx_smux_nids); spec->eapd_switch = 1; break; } if (spec->board_config != STAC_92HD73XX_REF) { /* GPIO0 High = Enable EAPD */ spec->eapd_mask = spec->gpio_mask = spec->gpio_dir = 0x1; spec->gpio_data = 0x01; } spec->num_pwrs = ARRAY_SIZE(stac92hd73xx_pwr_nids); spec->pwr_nids = stac92hd73xx_pwr_nids; err = stac92xx_parse_auto_config(codec, 0x25, 0x27); if (!err) { if (spec->board_config < 0) { printk(KERN_WARNING "hda_codec: No auto-config is " "available, default to model=ref\n"); spec->board_config = STAC_92HD73XX_REF; goto again; } err = -EINVAL; } if (err < 0) { stac92xx_free(codec); return err; } if (spec->board_config == STAC_92HD73XX_NO_JD) spec->hp_detect = 0; codec->patch_ops = stac92xx_patch_ops; codec->proc_widget_hook = stac92hd7x_proc_hook; return 0; } static int hp_bnb2011_with_dock(struct hda_codec *codec) { if (codec->vendor_id != 0x111d7605 && codec->vendor_id != 0x111d76d1) return 0; switch (codec->subsystem_id) { case 0x103c1618: case 0x103c1619: case 0x103c161a: case 0x103c161b: case 0x103c161c: case 0x103c161d: case 0x103c161e: case 0x103c161f: case 0x103c162a: case 0x103c162b: case 0x103c1630: case 0x103c1631: case 0x103c1633: case 0x103c1634: case 0x103c1635: case 0x103c3587: case 0x103c3588: case 0x103c3589: case 0x103c358a: case 0x103c3667: case 0x103c3668: case 0x103c3669: return 1; } return 0; } static void stac92hd8x_add_pin(struct hda_codec *codec, hda_nid_t nid) { struct sigmatel_spec *spec = codec->spec; unsigned int def_conf = snd_hda_codec_get_pincfg(codec, nid); int i; spec->auto_pin_nids[spec->auto_pin_cnt] = nid; spec->auto_pin_cnt++; if (get_defcfg_device(def_conf) == AC_JACK_MIC_IN && get_defcfg_connect(def_conf) != AC_JACK_PORT_NONE) { for (i = 0; i < ARRAY_SIZE(stac92hd83xxx_dmic_nids); i++) { if (nid == stac92hd83xxx_dmic_nids[i]) { spec->auto_dmic_nids[spec->auto_dmic_cnt] = nid; spec->auto_dmic_cnt++; } } } } static void stac92hd8x_add_adc(struct hda_codec *codec, hda_nid_t nid) { struct sigmatel_spec *spec = codec->spec; spec->auto_adc_nids[spec->auto_adc_cnt] = nid; spec->auto_adc_cnt++; } static void stac92hd8x_add_mux(struct hda_codec *codec, hda_nid_t nid) { int i, j; struct sigmatel_spec *spec = codec->spec; for (i = 0; i < spec->auto_adc_cnt; i++) { if (get_connection_index(codec, spec->auto_adc_nids[i], nid) >= 0) { /* mux and volume for adc_nids[i] */ if (!spec->auto_mux_nids[i]) { spec->auto_mux_nids[i] = nid; /* 92hd codecs capture volume is in mux */ spec->auto_capvols[i] = HDA_COMPOSE_AMP_VAL(nid, 3, 0, HDA_OUTPUT); } for (j = 0; j < spec->auto_dmic_cnt; j++) { if (get_connection_index(codec, nid, spec->auto_dmic_nids[j]) >= 0) { /* dmux for adc_nids[i] */ if (!spec->auto_dmux_nids[i]) spec->auto_dmux_nids[i] = nid; break; } } break; } } } static void stac92hd8x_fill_auto_spec(struct hda_codec *codec) { hda_nid_t nid, end_nid; unsigned int wid_caps, wid_type; struct sigmatel_spec *spec = codec->spec; end_nid = codec->start_nid + codec->num_nodes; for (nid = codec->start_nid; nid < end_nid; nid++) { wid_caps = get_wcaps(codec, nid); wid_type = get_wcaps_type(wid_caps); if (wid_type == AC_WID_PIN) stac92hd8x_add_pin(codec, nid); if (wid_type == AC_WID_AUD_IN && !(wid_caps & AC_WCAP_DIGITAL)) stac92hd8x_add_adc(codec, nid); } for (nid = codec->start_nid; nid < end_nid; nid++) { wid_caps = get_wcaps(codec, nid); wid_type = get_wcaps_type(wid_caps); if (wid_type == AC_WID_AUD_SEL) stac92hd8x_add_mux(codec, nid); } spec->pin_nids = spec->auto_pin_nids; spec->num_pins = spec->auto_pin_cnt; spec->adc_nids = spec->auto_adc_nids; spec->num_adcs = spec->auto_adc_cnt; spec->capvols = spec->auto_capvols; spec->capsws = spec->auto_capvols; spec->num_caps = spec->auto_adc_cnt; spec->mux_nids = spec->auto_mux_nids; spec->num_muxes = spec->auto_adc_cnt; spec->dmux_nids = spec->auto_dmux_nids; spec->num_dmuxes = spec->auto_adc_cnt; spec->dmic_nids = spec->auto_dmic_nids; spec->num_dmics = spec->auto_dmic_cnt; } static int patch_stac92hd83xxx(struct hda_codec *codec) { struct sigmatel_spec *spec; hda_nid_t conn[STAC92HD83_DAC_COUNT + 1]; int err; int num_dacs; spec = kzalloc(sizeof(*spec), GFP_KERNEL); if (spec == NULL) return -ENOMEM; if (hp_bnb2011_with_dock(codec)) { snd_hda_codec_set_pincfg(codec, 0xa, 0x2101201f); snd_hda_codec_set_pincfg(codec, 0xf, 0x2181205e); } /* reset pin power-down; Windows may leave these bits after reboot */ snd_hda_codec_write_cache(codec, codec->afg, 0, 0x7EC, 0); snd_hda_codec_write_cache(codec, codec->afg, 0, 0x7ED, 0); codec->no_trigger_sense = 1; codec->spec = spec; stac92hd8x_fill_auto_spec(codec); spec->linear_tone_beep = 0; codec->slave_dig_outs = stac92hd83xxx_slave_dig_outs; spec->digbeep_nid = 0x21; spec->pwr_nids = stac92hd83xxx_pwr_nids; spec->pwr_mapping = stac92hd83xxx_pwr_mapping; spec->num_pwrs = ARRAY_SIZE(stac92hd83xxx_pwr_nids); spec->multiout.dac_nids = spec->dac_nids; spec->init = stac92hd83xxx_core_init; spec->board_config = snd_hda_check_board_config(codec, STAC_92HD83XXX_MODELS, stac92hd83xxx_models, stac92hd83xxx_cfg_tbl); again: if (spec->board_config < 0) snd_printdd(KERN_INFO "hda_codec: %s: BIOS auto-probing.\n", codec->chip_name); else stac92xx_set_config_regs(codec, stac92hd83xxx_brd_tbl[spec->board_config]); switch (codec->vendor_id) { case 0x111d76d1: case 0x111d76d9: case 0x111d76e5: case 0x111d7666: case 0x111d7667: case 0x111d7668: case 0x111d7669: case 0x111d76e3: case 0x111d7604: case 0x111d76d4: case 0x111d7605: case 0x111d76d5: case 0x111d76e7: if (spec->board_config == STAC_92HD83XXX_PWR_REF) break; spec->num_pwrs = 0; break; } codec->patch_ops = stac92xx_patch_ops; if (find_mute_led_gpio(codec, 0)) snd_printd("mute LED gpio %d polarity %d\n", spec->gpio_led, spec->gpio_led_polarity); #ifdef CONFIG_SND_HDA_POWER_SAVE if (spec->gpio_led) { spec->gpio_mask |= spec->gpio_led; spec->gpio_dir |= spec->gpio_led; spec->gpio_data |= spec->gpio_led; /* register check_power_status callback. */ codec->patch_ops.check_power_status = stac92xx_hp_check_power_status; } #endif err = stac92xx_parse_auto_config(codec, 0x1d, 0); if (!err) { if (spec->board_config < 0) { printk(KERN_WARNING "hda_codec: No auto-config is " "available, default to model=ref\n"); spec->board_config = STAC_92HD83XXX_REF; goto again; } err = -EINVAL; } if (err < 0) { stac92xx_free(codec); return err; } /* docking output support */ num_dacs = snd_hda_get_connections(codec, 0xF, conn, STAC92HD83_DAC_COUNT + 1) - 1; /* skip non-DAC connections */ while (num_dacs >= 0 && (get_wcaps_type(get_wcaps(codec, conn[num_dacs])) != AC_WID_AUD_OUT)) num_dacs--; /* set port E and F to select the last DAC */ if (num_dacs >= 0) { snd_hda_codec_write_cache(codec, 0xE, 0, AC_VERB_SET_CONNECT_SEL, num_dacs); snd_hda_codec_write_cache(codec, 0xF, 0, AC_VERB_SET_CONNECT_SEL, num_dacs); } codec->proc_widget_hook = stac92hd_proc_hook; return 0; } static int stac92hd71bxx_connected_smuxes(struct hda_codec *codec, hda_nid_t dig0pin) { struct sigmatel_spec *spec = codec->spec; int idx; for (idx = 0; idx < spec->num_pins; idx++) if (spec->pin_nids[idx] == dig0pin) break; if ((idx + 2) >= spec->num_pins) return 0; /* dig1pin case */ if (stac_get_defcfg_connect(codec, idx + 1) != AC_JACK_PORT_NONE) return 2; /* dig0pin + dig2pin case */ if (stac_get_defcfg_connect(codec, idx + 2) != AC_JACK_PORT_NONE) return 2; if (stac_get_defcfg_connect(codec, idx) != AC_JACK_PORT_NONE) return 1; else return 0; } /* HP dv7 bass switch - GPIO5 */ #define stac_hp_bass_gpio_info snd_ctl_boolean_mono_info static int stac_hp_bass_gpio_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; ucontrol->value.integer.value[0] = !!(spec->gpio_data & 0x20); return 0; } static int stac_hp_bass_gpio_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct sigmatel_spec *spec = codec->spec; unsigned int gpio_data; gpio_data = (spec->gpio_data & ~0x20) | (ucontrol->value.integer.value[0] ? 0x20 : 0); if (gpio_data == spec->gpio_data) return 0; spec->gpio_data = gpio_data; stac_gpio_set(codec, spec->gpio_mask, spec->gpio_dir, spec->gpio_data); return 1; } static struct snd_kcontrol_new stac_hp_bass_sw_ctrl = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .info = stac_hp_bass_gpio_info, .get = stac_hp_bass_gpio_get, .put = stac_hp_bass_gpio_put, }; static int stac_add_hp_bass_switch(struct hda_codec *codec) { struct sigmatel_spec *spec = codec->spec; if (!stac_control_new(spec, &stac_hp_bass_sw_ctrl, "Bass Speaker Playback Switch", 0)) return -ENOMEM; spec->gpio_mask |= 0x20; spec->gpio_dir |= 0x20; spec->gpio_data |= 0x20; return 0; } static int patch_stac92hd71bxx(struct hda_codec *codec) { struct sigmatel_spec *spec; struct hda_verb *unmute_init = stac92hd71bxx_unmute_core_init; unsigned int pin_cfg; int err = 0; spec = kzalloc(sizeof(*spec), GFP_KERNEL); if (spec == NULL) return -ENOMEM; codec->no_trigger_sense = 1; codec->spec = spec; spec->linear_tone_beep = 0; codec->patch_ops = stac92xx_patch_ops; spec->num_pins = STAC92HD71BXX_NUM_PINS; switch (codec->vendor_id) { case 0x111d76b6: case 0x111d76b7: spec->pin_nids = stac92hd71bxx_pin_nids_4port; break; case 0x111d7603: case 0x111d7608: /* On 92HD75Bx 0x27 isn't a pin nid */ spec->num_pins--; /* fallthrough */ default: spec->pin_nids = stac92hd71bxx_pin_nids_6port; } spec->num_pwrs = ARRAY_SIZE(stac92hd71bxx_pwr_nids); spec->board_config = snd_hda_check_board_config(codec, STAC_92HD71BXX_MODELS, stac92hd71bxx_models, stac92hd71bxx_cfg_tbl); again: if (spec->board_config < 0) snd_printdd(KERN_INFO "hda_codec: %s: BIOS auto-probing.\n", codec->chip_name); else stac92xx_set_config_regs(codec, stac92hd71bxx_brd_tbl[spec->board_config]); if (spec->board_config != STAC_92HD71BXX_REF) { /* GPIO0 = EAPD */ spec->gpio_mask = 0x01; spec->gpio_dir = 0x01; spec->gpio_data = 0x01; } spec->dmic_nids = stac92hd71bxx_dmic_nids; spec->dmux_nids = stac92hd71bxx_dmux_nids; spec->num_caps = STAC92HD71BXX_NUM_CAPS; spec->capvols = stac92hd71bxx_capvols; spec->capsws = stac92hd71bxx_capsws; switch (codec->vendor_id) { case 0x111d76b6: /* 4 Port without Analog Mixer */ case 0x111d76b7: unmute_init++; /* fallthru */ case 0x111d76b4: /* 6 Port without Analog Mixer */ case 0x111d76b5: spec->init = stac92hd71bxx_core_init; codec->slave_dig_outs = stac92hd71bxx_slave_dig_outs; spec->num_dmics = stac92xx_connected_ports(codec, stac92hd71bxx_dmic_nids, STAC92HD71BXX_NUM_DMICS); break; case 0x111d7608: /* 5 Port with Analog Mixer */ switch (spec->board_config) { case STAC_HP_M4: /* Enable VREF power saving on GPIO1 detect */ err = stac_add_event(spec, codec->afg, STAC_VREF_EVENT, 0x02); if (err < 0) return err; snd_hda_codec_write_cache(codec, codec->afg, 0, AC_VERB_SET_GPIO_UNSOLICITED_RSP_MASK, 0x02); snd_hda_codec_write_cache(codec, codec->afg, 0, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | err); spec->gpio_mask |= 0x02; break; } if ((codec->revision_id & 0xf) == 0 || (codec->revision_id & 0xf) == 1) spec->stream_delay = 40; /* 40 milliseconds */ /* no output amps */ spec->num_pwrs = 0; /* disable VSW */ spec->init = stac92hd71bxx_core_init; unmute_init++; snd_hda_codec_set_pincfg(codec, 0x0f, 0x40f000f0); snd_hda_codec_set_pincfg(codec, 0x19, 0x40f000f3); stac92hd71bxx_dmic_nids[STAC92HD71BXX_NUM_DMICS - 1] = 0; spec->num_dmics = stac92xx_connected_ports(codec, stac92hd71bxx_dmic_nids, STAC92HD71BXX_NUM_DMICS - 1); break; case 0x111d7603: /* 6 Port with Analog Mixer */ if ((codec->revision_id & 0xf) == 1) spec->stream_delay = 40; /* 40 milliseconds */ /* no output amps */ spec->num_pwrs = 0; /* fallthru */ default: spec->init = stac92hd71bxx_core_init; codec->slave_dig_outs = stac92hd71bxx_slave_dig_outs; spec->num_dmics = stac92xx_connected_ports(codec, stac92hd71bxx_dmic_nids, STAC92HD71BXX_NUM_DMICS); break; } if (get_wcaps(codec, 0xa) & AC_WCAP_IN_AMP) snd_hda_sequence_write_cache(codec, unmute_init); /* Some HP machines seem to have unstable codec communications * especially with ATI fglrx driver. For recovering from the * CORB/RIRB stall, allow the BUS reset and keep always sync */ if (spec->board_config == STAC_HP_DV5) { codec->bus->sync_write = 1; codec->bus->allow_bus_reset = 1; } spec->aloopback_ctl = stac92hd71bxx_loopback; spec->aloopback_mask = 0x50; spec->aloopback_shift = 0; spec->powerdown_adcs = 1; spec->digbeep_nid = 0x26; spec->mux_nids = stac92hd71bxx_mux_nids; spec->adc_nids = stac92hd71bxx_adc_nids; spec->smux_nids = stac92hd71bxx_smux_nids; spec->pwr_nids = stac92hd71bxx_pwr_nids; spec->num_muxes = ARRAY_SIZE(stac92hd71bxx_mux_nids); spec->num_adcs = ARRAY_SIZE(stac92hd71bxx_adc_nids); spec->num_dmuxes = ARRAY_SIZE(stac92hd71bxx_dmux_nids); spec->num_smuxes = stac92hd71bxx_connected_smuxes(codec, 0x1e); snd_printdd("Found board config: %d\n", spec->board_config); switch (spec->board_config) { case STAC_HP_M4: /* enable internal microphone */ snd_hda_codec_set_pincfg(codec, 0x0e, 0x01813040); stac92xx_auto_set_pinctl(codec, 0x0e, AC_PINCTL_IN_EN | AC_PINCTL_VREF_80); /* fallthru */ case STAC_DELL_M4_2: spec->num_dmics = 0; spec->num_smuxes = 0; spec->num_dmuxes = 0; break; case STAC_DELL_M4_1: case STAC_DELL_M4_3: spec->num_dmics = 1; spec->num_smuxes = 0; spec->num_dmuxes = 1; break; case STAC_HP_DV4_1222NR: spec->num_dmics = 1; /* I don't know if it needs 1 or 2 smuxes - will wait for * bug reports to fix if needed */ spec->num_smuxes = 1; spec->num_dmuxes = 1; /* fallthrough */ case STAC_HP_DV4: spec->gpio_led = 0x01; /* fallthrough */ case STAC_HP_DV5: snd_hda_codec_set_pincfg(codec, 0x0d, 0x90170010); stac92xx_auto_set_pinctl(codec, 0x0d, AC_PINCTL_OUT_EN); /* HP dv6 gives the headphone pin as a line-out. Thus we * need to set hp_detect flag here to force to enable HP * detection. */ spec->hp_detect = 1; break; case STAC_HP_HDX: spec->num_dmics = 1; spec->num_dmuxes = 1; spec->num_smuxes = 1; spec->gpio_led = 0x08; break; } if (hp_blike_system(codec->subsystem_id)) { pin_cfg = snd_hda_codec_get_pincfg(codec, 0x0f); if (get_defcfg_device(pin_cfg) == AC_JACK_LINE_OUT || get_defcfg_device(pin_cfg) == AC_JACK_SPEAKER || get_defcfg_device(pin_cfg) == AC_JACK_HP_OUT) { /* It was changed in the BIOS to just satisfy MS DTM. * Lets turn it back into slaved HP */ pin_cfg = (pin_cfg & (~AC_DEFCFG_DEVICE)) | (AC_JACK_HP_OUT << AC_DEFCFG_DEVICE_SHIFT); pin_cfg = (pin_cfg & (~(AC_DEFCFG_DEF_ASSOC | AC_DEFCFG_SEQUENCE))) | 0x1f; snd_hda_codec_set_pincfg(codec, 0x0f, pin_cfg); } } if (find_mute_led_gpio(codec, 1)) snd_printd("mute LED gpio %d polarity %d\n", spec->gpio_led, spec->gpio_led_polarity); #ifdef CONFIG_SND_HDA_POWER_SAVE if (spec->gpio_led) { spec->gpio_mask |= spec->gpio_led; spec->gpio_dir |= spec->gpio_led; spec->gpio_data |= spec->gpio_led; /* register check_power_status callback. */ codec->patch_ops.check_power_status = stac92xx_hp_check_power_status; } #endif spec->multiout.dac_nids = spec->dac_nids; err = stac92xx_parse_auto_config(codec, 0x21, 0); if (!err) { if (spec->board_config < 0) { printk(KERN_WARNING "hda_codec: No auto-config is " "available, default to model=ref\n"); spec->board_config = STAC_92HD71BXX_REF; goto again; } err = -EINVAL; } if (err < 0) { stac92xx_free(codec); return err; } /* enable bass on HP dv7 */ if (spec->board_config == STAC_HP_DV4 || spec->board_config == STAC_HP_DV5) { unsigned int cap; cap = snd_hda_param_read(codec, 0x1, AC_PAR_GPIO_CAP); cap &= AC_GPIO_IO_COUNT; if (cap >= 6) stac_add_hp_bass_switch(codec); } codec->proc_widget_hook = stac92hd7x_proc_hook; return 0; } static int patch_stac922x(struct hda_codec *codec) { struct sigmatel_spec *spec; int err; spec = kzalloc(sizeof(*spec), GFP_KERNEL); if (spec == NULL) return -ENOMEM; codec->no_trigger_sense = 1; codec->spec = spec; spec->linear_tone_beep = 1; spec->num_pins = ARRAY_SIZE(stac922x_pin_nids); spec->pin_nids = stac922x_pin_nids; spec->board_config = snd_hda_check_board_config(codec, STAC_922X_MODELS, stac922x_models, stac922x_cfg_tbl); if (spec->board_config == STAC_INTEL_MAC_AUTO) { spec->gpio_mask = spec->gpio_dir = 0x03; spec->gpio_data = 0x03; /* Intel Macs have all same PCI SSID, so we need to check * codec SSID to distinguish the exact models */ printk(KERN_INFO "hda_codec: STAC922x, Apple subsys_id=%x\n", codec->subsystem_id); switch (codec->subsystem_id) { case 0x106b0800: spec->board_config = STAC_INTEL_MAC_V1; break; case 0x106b0600: case 0x106b0700: spec->board_config = STAC_INTEL_MAC_V2; break; case 0x106b0e00: case 0x106b0f00: case 0x106b1600: case 0x106b1700: case 0x106b0200: case 0x106b1e00: spec->board_config = STAC_INTEL_MAC_V3; break; case 0x106b1a00: case 0x00000100: spec->board_config = STAC_INTEL_MAC_V4; break; case 0x106b0a00: case 0x106b2200: spec->board_config = STAC_INTEL_MAC_V5; break; default: spec->board_config = STAC_INTEL_MAC_V3; break; } } again: if (spec->board_config < 0) snd_printdd(KERN_INFO "hda_codec: %s: BIOS auto-probing.\n", codec->chip_name); else stac92xx_set_config_regs(codec, stac922x_brd_tbl[spec->board_config]); spec->adc_nids = stac922x_adc_nids; spec->mux_nids = stac922x_mux_nids; spec->num_muxes = ARRAY_SIZE(stac922x_mux_nids); spec->num_adcs = ARRAY_SIZE(stac922x_adc_nids); spec->num_dmics = 0; spec->num_pwrs = 0; spec->init = stac922x_core_init; spec->num_caps = STAC922X_NUM_CAPS; spec->capvols = stac922x_capvols; spec->capsws = stac922x_capsws; spec->multiout.dac_nids = spec->dac_nids; err = stac92xx_parse_auto_config(codec, 0x08, 0x09); if (!err) { if (spec->board_config < 0) { printk(KERN_WARNING "hda_codec: No auto-config is " "available, default to model=ref\n"); spec->board_config = STAC_D945_REF; goto again; } err = -EINVAL; } if (err < 0) { stac92xx_free(codec); return err; } codec->patch_ops = stac92xx_patch_ops; /* Fix Mux capture level; max to 2 */ snd_hda_override_amp_caps(codec, 0x12, HDA_OUTPUT, (0 << AC_AMPCAP_OFFSET_SHIFT) | (2 << AC_AMPCAP_NUM_STEPS_SHIFT) | (0x27 << AC_AMPCAP_STEP_SIZE_SHIFT) | (0 << AC_AMPCAP_MUTE_SHIFT)); return 0; } static int patch_stac927x(struct hda_codec *codec) { struct sigmatel_spec *spec; int err; spec = kzalloc(sizeof(*spec), GFP_KERNEL); if (spec == NULL) return -ENOMEM; codec->no_trigger_sense = 1; codec->spec = spec; spec->linear_tone_beep = 1; codec->slave_dig_outs = stac927x_slave_dig_outs; spec->num_pins = ARRAY_SIZE(stac927x_pin_nids); spec->pin_nids = stac927x_pin_nids; spec->board_config = snd_hda_check_board_config(codec, STAC_927X_MODELS, stac927x_models, stac927x_cfg_tbl); again: if (spec->board_config < 0) snd_printdd(KERN_INFO "hda_codec: %s: BIOS auto-probing.\n", codec->chip_name); else stac92xx_set_config_regs(codec, stac927x_brd_tbl[spec->board_config]); spec->digbeep_nid = 0x23; spec->adc_nids = stac927x_adc_nids; spec->num_adcs = ARRAY_SIZE(stac927x_adc_nids); spec->mux_nids = stac927x_mux_nids; spec->num_muxes = ARRAY_SIZE(stac927x_mux_nids); spec->smux_nids = stac927x_smux_nids; spec->num_smuxes = ARRAY_SIZE(stac927x_smux_nids); spec->spdif_labels = stac927x_spdif_labels; spec->dac_list = stac927x_dac_nids; spec->multiout.dac_nids = spec->dac_nids; if (spec->board_config != STAC_D965_REF) { /* GPIO0 High = Enable EAPD */ spec->eapd_mask = spec->gpio_mask = 0x01; spec->gpio_dir = spec->gpio_data = 0x01; } switch (spec->board_config) { case STAC_D965_3ST: case STAC_D965_5ST: /* GPIO0 High = Enable EAPD */ spec->num_dmics = 0; spec->init = d965_core_init; break; case STAC_DELL_BIOS: switch (codec->subsystem_id) { case 0x10280209: case 0x1028022e: /* correct the device field to SPDIF out */ snd_hda_codec_set_pincfg(codec, 0x21, 0x01442070); break; } /* configure the analog microphone on some laptops */ snd_hda_codec_set_pincfg(codec, 0x0c, 0x90a79130); /* correct the front output jack as a hp out */ snd_hda_codec_set_pincfg(codec, 0x0f, 0x0227011f); /* correct the front input jack as a mic */ snd_hda_codec_set_pincfg(codec, 0x0e, 0x02a79130); /* fallthru */ case STAC_DELL_3ST: if (codec->subsystem_id != 0x1028022f) { /* GPIO2 High = Enable EAPD */ spec->eapd_mask = spec->gpio_mask = 0x04; spec->gpio_dir = spec->gpio_data = 0x04; } spec->dmic_nids = stac927x_dmic_nids; spec->num_dmics = STAC927X_NUM_DMICS; spec->init = dell_3st_core_init; spec->dmux_nids = stac927x_dmux_nids; spec->num_dmuxes = ARRAY_SIZE(stac927x_dmux_nids); break; case STAC_927X_VOLKNOB: spec->num_dmics = 0; spec->init = stac927x_volknob_core_init; break; default: spec->num_dmics = 0; spec->init = stac927x_core_init; break; } spec->num_caps = STAC927X_NUM_CAPS; spec->capvols = stac927x_capvols; spec->capsws = stac927x_capsws; spec->num_pwrs = 0; spec->aloopback_ctl = stac927x_loopback; spec->aloopback_mask = 0x40; spec->aloopback_shift = 0; spec->eapd_switch = 1; err = stac92xx_parse_auto_config(codec, 0x1e, 0x20); if (!err) { if (spec->board_config < 0) { printk(KERN_WARNING "hda_codec: No auto-config is " "available, default to model=ref\n"); spec->board_config = STAC_D965_REF; goto again; } err = -EINVAL; } if (err < 0) { stac92xx_free(codec); return err; } codec->patch_ops = stac92xx_patch_ops; codec->proc_widget_hook = stac927x_proc_hook; /* * !!FIXME!! * The STAC927x seem to require fairly long delays for certain * command sequences. With too short delays (even if the answer * is set to RIRB properly), it results in the silence output * on some hardwares like Dell. * * The below flag enables the longer delay (see get_response * in hda_intel.c). */ codec->bus->needs_damn_long_delay = 1; /* no jack detecion for ref-no-jd model */ if (spec->board_config == STAC_D965_REF_NO_JD) spec->hp_detect = 0; return 0; } static int patch_stac9205(struct hda_codec *codec) { struct sigmatel_spec *spec; int err; spec = kzalloc(sizeof(*spec), GFP_KERNEL); if (spec == NULL) return -ENOMEM; codec->no_trigger_sense = 1; codec->spec = spec; spec->linear_tone_beep = 1; spec->num_pins = ARRAY_SIZE(stac9205_pin_nids); spec->pin_nids = stac9205_pin_nids; spec->board_config = snd_hda_check_board_config(codec, STAC_9205_MODELS, stac9205_models, stac9205_cfg_tbl); again: if (spec->board_config < 0) snd_printdd(KERN_INFO "hda_codec: %s: BIOS auto-probing.\n", codec->chip_name); else stac92xx_set_config_regs(codec, stac9205_brd_tbl[spec->board_config]); spec->digbeep_nid = 0x23; spec->adc_nids = stac9205_adc_nids; spec->num_adcs = ARRAY_SIZE(stac9205_adc_nids); spec->mux_nids = stac9205_mux_nids; spec->num_muxes = ARRAY_SIZE(stac9205_mux_nids); spec->smux_nids = stac9205_smux_nids; spec->num_smuxes = ARRAY_SIZE(stac9205_smux_nids); spec->dmic_nids = stac9205_dmic_nids; spec->num_dmics = STAC9205_NUM_DMICS; spec->dmux_nids = stac9205_dmux_nids; spec->num_dmuxes = ARRAY_SIZE(stac9205_dmux_nids); spec->num_pwrs = 0; spec->init = stac9205_core_init; spec->aloopback_ctl = stac9205_loopback; spec->num_caps = STAC9205_NUM_CAPS; spec->capvols = stac9205_capvols; spec->capsws = stac9205_capsws; spec->aloopback_mask = 0x40; spec->aloopback_shift = 0; /* Turn on/off EAPD per HP plugging */ if (spec->board_config != STAC_9205_EAPD) spec->eapd_switch = 1; spec->multiout.dac_nids = spec->dac_nids; switch (spec->board_config){ case STAC_9205_DELL_M43: /* Enable SPDIF in/out */ snd_hda_codec_set_pincfg(codec, 0x1f, 0x01441030); snd_hda_codec_set_pincfg(codec, 0x20, 0x1c410030); /* Enable unsol response for GPIO4/Dock HP connection */ err = stac_add_event(spec, codec->afg, STAC_VREF_EVENT, 0x01); if (err < 0) return err; snd_hda_codec_write_cache(codec, codec->afg, 0, AC_VERB_SET_GPIO_UNSOLICITED_RSP_MASK, 0x10); snd_hda_codec_write_cache(codec, codec->afg, 0, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | err); spec->gpio_dir = 0x0b; spec->eapd_mask = 0x01; spec->gpio_mask = 0x1b; spec->gpio_mute = 0x10; /* GPIO0 High = EAPD, GPIO1 Low = Headphone Mute, * GPIO3 Low = DRM */ spec->gpio_data = 0x01; break; case STAC_9205_REF: /* SPDIF-In enabled */ break; default: /* GPIO0 High = EAPD */ spec->eapd_mask = spec->gpio_mask = spec->gpio_dir = 0x1; spec->gpio_data = 0x01; break; } err = stac92xx_parse_auto_config(codec, 0x1f, 0x20); if (!err) { if (spec->board_config < 0) { printk(KERN_WARNING "hda_codec: No auto-config is " "available, default to model=ref\n"); spec->board_config = STAC_9205_REF; goto again; } err = -EINVAL; } if (err < 0) { stac92xx_free(codec); return err; } codec->patch_ops = stac92xx_patch_ops; codec->proc_widget_hook = stac9205_proc_hook; return 0; } /* * STAC9872 hack */ static struct hda_verb stac9872_core_init[] = { {0x15, AC_VERB_SET_CONNECT_SEL, 0x1}, /* mic-sel: 0a,0d,14,02 */ {0x15, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE}, /* Mic-in -> 0x9 */ {} }; static hda_nid_t stac9872_pin_nids[] = { 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11, 0x13, 0x14, }; static hda_nid_t stac9872_adc_nids[] = { 0x8 /*,0x6*/ }; static hda_nid_t stac9872_mux_nids[] = { 0x15 }; static unsigned long stac9872_capvols[] = { HDA_COMPOSE_AMP_VAL(0x09, 3, 0, HDA_INPUT), }; #define stac9872_capsws stac9872_capvols static unsigned int stac9872_vaio_pin_configs[9] = { 0x03211020, 0x411111f0, 0x411111f0, 0x03a15030, 0x411111f0, 0x90170110, 0x411111f0, 0x411111f0, 0x90a7013e }; static const char * const stac9872_models[STAC_9872_MODELS] = { [STAC_9872_AUTO] = "auto", [STAC_9872_VAIO] = "vaio", }; static unsigned int *stac9872_brd_tbl[STAC_9872_MODELS] = { [STAC_9872_VAIO] = stac9872_vaio_pin_configs, }; static struct snd_pci_quirk stac9872_cfg_tbl[] = { SND_PCI_QUIRK_MASK(0x104d, 0xfff0, 0x81e0, "Sony VAIO F/S", STAC_9872_VAIO), {} /* terminator */ }; static int patch_stac9872(struct hda_codec *codec) { struct sigmatel_spec *spec; int err; spec = kzalloc(sizeof(*spec), GFP_KERNEL); if (spec == NULL) return -ENOMEM; codec->no_trigger_sense = 1; codec->spec = spec; spec->linear_tone_beep = 1; spec->num_pins = ARRAY_SIZE(stac9872_pin_nids); spec->pin_nids = stac9872_pin_nids; spec->board_config = snd_hda_check_board_config(codec, STAC_9872_MODELS, stac9872_models, stac9872_cfg_tbl); if (spec->board_config < 0) snd_printdd(KERN_INFO "hda_codec: %s: BIOS auto-probing.\n", codec->chip_name); else stac92xx_set_config_regs(codec, stac9872_brd_tbl[spec->board_config]); spec->multiout.dac_nids = spec->dac_nids; spec->num_adcs = ARRAY_SIZE(stac9872_adc_nids); spec->adc_nids = stac9872_adc_nids; spec->num_muxes = ARRAY_SIZE(stac9872_mux_nids); spec->mux_nids = stac9872_mux_nids; spec->init = stac9872_core_init; spec->num_caps = 1; spec->capvols = stac9872_capvols; spec->capsws = stac9872_capsws; err = stac92xx_parse_auto_config(codec, 0x10, 0x12); if (err < 0) { stac92xx_free(codec); return -EINVAL; } spec->input_mux = &spec->private_imux; codec->patch_ops = stac92xx_patch_ops; return 0; } /* * patch entries */ static struct hda_codec_preset snd_hda_preset_sigmatel[] = { { .id = 0x83847690, .name = "STAC9200", .patch = patch_stac9200 }, { .id = 0x83847882, .name = "STAC9220 A1", .patch = patch_stac922x }, { .id = 0x83847680, .name = "STAC9221 A1", .patch = patch_stac922x }, { .id = 0x83847880, .name = "STAC9220 A2", .patch = patch_stac922x }, { .id = 0x83847681, .name = "STAC9220D/9223D A2", .patch = patch_stac922x }, { .id = 0x83847682, .name = "STAC9221 A2", .patch = patch_stac922x }, { .id = 0x83847683, .name = "STAC9221D A2", .patch = patch_stac922x }, { .id = 0x83847618, .name = "STAC9227", .patch = patch_stac927x }, { .id = 0x83847619, .name = "STAC9227", .patch = patch_stac927x }, { .id = 0x83847616, .name = "STAC9228", .patch = patch_stac927x }, { .id = 0x83847617, .name = "STAC9228", .patch = patch_stac927x }, { .id = 0x83847614, .name = "STAC9229", .patch = patch_stac927x }, { .id = 0x83847615, .name = "STAC9229", .patch = patch_stac927x }, { .id = 0x83847620, .name = "STAC9274", .patch = patch_stac927x }, { .id = 0x83847621, .name = "STAC9274D", .patch = patch_stac927x }, { .id = 0x83847622, .name = "STAC9273X", .patch = patch_stac927x }, { .id = 0x83847623, .name = "STAC9273D", .patch = patch_stac927x }, { .id = 0x83847624, .name = "STAC9272X", .patch = patch_stac927x }, { .id = 0x83847625, .name = "STAC9272D", .patch = patch_stac927x }, { .id = 0x83847626, .name = "STAC9271X", .patch = patch_stac927x }, { .id = 0x83847627, .name = "STAC9271D", .patch = patch_stac927x }, { .id = 0x83847628, .name = "STAC9274X5NH", .patch = patch_stac927x }, { .id = 0x83847629, .name = "STAC9274D5NH", .patch = patch_stac927x }, { .id = 0x83847632, .name = "STAC9202", .patch = patch_stac925x }, { .id = 0x83847633, .name = "STAC9202D", .patch = patch_stac925x }, { .id = 0x83847634, .name = "STAC9250", .patch = patch_stac925x }, { .id = 0x83847635, .name = "STAC9250D", .patch = patch_stac925x }, { .id = 0x83847636, .name = "STAC9251", .patch = patch_stac925x }, { .id = 0x83847637, .name = "STAC9250D", .patch = patch_stac925x }, { .id = 0x83847645, .name = "92HD206X", .patch = patch_stac927x }, { .id = 0x83847646, .name = "92HD206D", .patch = patch_stac927x }, /* The following does not take into account .id=0x83847661 when subsys = * 104D0C00 which is STAC9225s. Because of this, some SZ Notebooks are * currently not fully supported. */ { .id = 0x83847661, .name = "CXD9872RD/K", .patch = patch_stac9872 }, { .id = 0x83847662, .name = "STAC9872AK", .patch = patch_stac9872 }, { .id = 0x83847664, .name = "CXD9872AKD", .patch = patch_stac9872 }, { .id = 0x83847698, .name = "STAC9205", .patch = patch_stac9205 }, { .id = 0x838476a0, .name = "STAC9205", .patch = patch_stac9205 }, { .id = 0x838476a1, .name = "STAC9205D", .patch = patch_stac9205 }, { .id = 0x838476a2, .name = "STAC9204", .patch = patch_stac9205 }, { .id = 0x838476a3, .name = "STAC9204D", .patch = patch_stac9205 }, { .id = 0x838476a4, .name = "STAC9255", .patch = patch_stac9205 }, { .id = 0x838476a5, .name = "STAC9255D", .patch = patch_stac9205 }, { .id = 0x838476a6, .name = "STAC9254", .patch = patch_stac9205 }, { .id = 0x838476a7, .name = "STAC9254D", .patch = patch_stac9205 }, { .id = 0x111d7603, .name = "92HD75B3X5", .patch = patch_stac92hd71bxx}, { .id = 0x111d7604, .name = "92HD83C1X5", .patch = patch_stac92hd83xxx}, { .id = 0x111d76d4, .name = "92HD83C1C5", .patch = patch_stac92hd83xxx}, { .id = 0x111d7605, .name = "92HD81B1X5", .patch = patch_stac92hd83xxx}, { .id = 0x111d76d5, .name = "92HD81B1C5", .patch = patch_stac92hd83xxx}, { .id = 0x111d76d1, .name = "92HD87B1/3", .patch = patch_stac92hd83xxx}, { .id = 0x111d76d9, .name = "92HD87B2/4", .patch = patch_stac92hd83xxx}, { .id = 0x111d7666, .name = "92HD88B3", .patch = patch_stac92hd83xxx}, { .id = 0x111d7667, .name = "92HD88B1", .patch = patch_stac92hd83xxx}, { .id = 0x111d7668, .name = "92HD88B2", .patch = patch_stac92hd83xxx}, { .id = 0x111d7669, .name = "92HD88B4", .patch = patch_stac92hd83xxx}, { .id = 0x111d7608, .name = "92HD75B2X5", .patch = patch_stac92hd71bxx}, { .id = 0x111d7674, .name = "92HD73D1X5", .patch = patch_stac92hd73xx }, { .id = 0x111d7675, .name = "92HD73C1X5", .patch = patch_stac92hd73xx }, { .id = 0x111d7676, .name = "92HD73E1X5", .patch = patch_stac92hd73xx }, { .id = 0x111d76b0, .name = "92HD71B8X", .patch = patch_stac92hd71bxx }, { .id = 0x111d76b1, .name = "92HD71B8X", .patch = patch_stac92hd71bxx }, { .id = 0x111d76b2, .name = "92HD71B7X", .patch = patch_stac92hd71bxx }, { .id = 0x111d76b3, .name = "92HD71B7X", .patch = patch_stac92hd71bxx }, { .id = 0x111d76b4, .name = "92HD71B6X", .patch = patch_stac92hd71bxx }, { .id = 0x111d76b5, .name = "92HD71B6X", .patch = patch_stac92hd71bxx }, { .id = 0x111d76b6, .name = "92HD71B5X", .patch = patch_stac92hd71bxx }, { .id = 0x111d76b7, .name = "92HD71B5X", .patch = patch_stac92hd71bxx }, { .id = 0x111d76c0, .name = "92HD89C3", .patch = patch_stac92hd73xx }, { .id = 0x111d76c1, .name = "92HD89C2", .patch = patch_stac92hd73xx }, { .id = 0x111d76c2, .name = "92HD89C1", .patch = patch_stac92hd73xx }, { .id = 0x111d76c3, .name = "92HD89B3", .patch = patch_stac92hd73xx }, { .id = 0x111d76c4, .name = "92HD89B2", .patch = patch_stac92hd73xx }, { .id = 0x111d76c5, .name = "92HD89B1", .patch = patch_stac92hd73xx }, { .id = 0x111d76c6, .name = "92HD89E3", .patch = patch_stac92hd73xx }, { .id = 0x111d76c7, .name = "92HD89E2", .patch = patch_stac92hd73xx }, { .id = 0x111d76c8, .name = "92HD89E1", .patch = patch_stac92hd73xx }, { .id = 0x111d76c9, .name = "92HD89D3", .patch = patch_stac92hd73xx }, { .id = 0x111d76ca, .name = "92HD89D2", .patch = patch_stac92hd73xx }, { .id = 0x111d76cb, .name = "92HD89D1", .patch = patch_stac92hd73xx }, { .id = 0x111d76cc, .name = "92HD89F3", .patch = patch_stac92hd73xx }, { .id = 0x111d76cd, .name = "92HD89F2", .patch = patch_stac92hd73xx }, { .id = 0x111d76ce, .name = "92HD89F1", .patch = patch_stac92hd73xx }, { .id = 0x111d76e0, .name = "92HD91BXX", .patch = patch_stac92hd83xxx}, { .id = 0x111d76e3, .name = "92HD98BXX", .patch = patch_stac92hd83xxx}, { .id = 0x111d76e5, .name = "92HD99BXX", .patch = patch_stac92hd83xxx}, { .id = 0x111d76e7, .name = "92HD90BXX", .patch = patch_stac92hd83xxx}, {} /* terminator */ }; MODULE_ALIAS("snd-hda-codec-id:8384*"); MODULE_ALIAS("snd-hda-codec-id:111d*"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("IDT/Sigmatel HD-audio codec"); static struct hda_codec_preset_list sigmatel_list = { .preset = snd_hda_preset_sigmatel, .owner = THIS_MODULE, }; static int __init patch_sigmatel_init(void) { return snd_hda_add_codec_preset(&sigmatel_list); } static void __exit patch_sigmatel_exit(void) { snd_hda_delete_codec_preset(&sigmatel_list); } module_init(patch_sigmatel_init) module_exit(patch_sigmatel_exit)
<?php /* * $Id: CmsTestBase.php 875 2007-12-19 11:10:15Z heltem $ * * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information please see * <http://propel.phpdb.org>. */ require_once 'PHPUnit/Framework/TestCase.php'; include_once 'cms/CmsDataPopulator.php'; /** * Base class contains some methods shared by subclass test cases. */ abstract class CmsTestBase extends PHPUnit_Framework_TestCase { /** * This is run before each unit test; it populates the database. */ protected function setUp() { parent::setUp(); CmsDataPopulator::depopulate(); CmsDataPopulator::populate(); } /** * This is run after each unit test. It empties the database. */ protected function tearDown() { CmsDataPopulator::depopulate(); parent::tearDown(); } }
<?php /** * @group Database */ class MovePageTest extends MediaWikiTestCase { /** * @dataProvider provideIsValidMove * @covers MovePage::isValidMove * @covers MovePage::isValidFileMove */ public function testIsValidMove( $old, $new, $error ) { $this->setMwGlobals( 'wgContentHandlerUseDB', false ); $mp = new MovePage( Title::newFromText( $old ), Title::newFromText( $new ) ); $status = $mp->isValidMove(); if ( $error === true ) { $this->assertTrue( $status->isGood() ); } else { $this->assertTrue( $status->hasMessage( $error ) ); } } /** * This should be kept in sync with TitleTest::provideTestIsValidMoveOperation */ public static function provideIsValidMove() { return [ // for MovePage::isValidMove [ 'Test', 'Test', 'selfmove' ], [ 'Special:FooBar', 'Test', 'immobile-source-namespace' ], [ 'Test', 'Special:FooBar', 'immobile-target-namespace' ], [ 'MediaWiki:Common.js', 'Help:Some wikitext page', 'bad-target-model' ], [ 'Page', 'File:Test.jpg', 'nonfile-cannot-move-to-file' ], // for MovePage::isValidFileMove [ 'File:Test.jpg', 'Page', 'imagenocrossnamespace' ], ]; } /** * Integration test to catch regressions like T74870. Taken and modified * from SemanticMediaWiki */ public function testTitleMoveCompleteIntegrationTest() { $oldTitle = Title::newFromText( 'Help:Some title' ); WikiPage::factory( $oldTitle )->doEditContent( new WikitextContent( 'foo' ), 'bar' ); $newTitle = Title::newFromText( 'Help:Some other title' ); $this->assertNull( WikiPage::factory( $newTitle )->getRevision() ); $this->assertTrue( $oldTitle->moveTo( $newTitle, false, 'test1', true ) ); $this->assertNotNull( WikiPage::factory( $oldTitle )->getRevision() ); $this->assertNotNull( WikiPage::factory( $newTitle )->getRevision() ); } }
/* * This file is part of Cleanflight. * * Cleanflight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Cleanflight 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 Cleanflight. If not, see <http://www.gnu.org/licenses/>. */ /* * Authors: * Dominic Clifton - Cleanflight implementation * John Ihlein - Initial FF32 code */ #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include "platform.h" #include "common/axis.h" #include "common/maths.h" #include "system.h" #include "gpio.h" #include "bus_spi.h" #include "sensor.h" #include "accgyro.h" #include "accgyro_spi_mpu6000.h" static bool mpuSpi6000InitDone = false; // Registers #define MPU6000_PRODUCT_ID 0x0C #define MPU6000_SMPLRT_DIV 0x19 #define MPU6000_GYRO_CONFIG 0x1B #define MPU6000_ACCEL_CONFIG 0x1C #define MPU6000_FIFO_EN 0x23 #define MPU6000_INT_PIN_CFG 0x37 #define MPU6000_INT_ENABLE 0x38 #define MPU6000_INT_STATUS 0x3A #define MPU6000_ACCEL_XOUT_H 0x3B #define MPU6000_ACCEL_XOUT_L 0x3C #define MPU6000_ACCEL_YOUT_H 0x3D #define MPU6000_ACCEL_YOUT_L 0x3E #define MPU6000_ACCEL_ZOUT_H 0x3F #define MPU6000_ACCEL_ZOUT_L 0x40 #define MPU6000_TEMP_OUT_H 0x41 #define MPU6000_TEMP_OUT_L 0x42 #define MPU6000_GYRO_XOUT_H 0x43 #define MPU6000_GYRO_XOUT_L 0x44 #define MPU6000_GYRO_YOUT_H 0x45 #define MPU6000_GYRO_YOUT_L 0x46 #define MPU6000_GYRO_ZOUT_H 0x47 #define MPU6000_GYRO_ZOUT_L 0x48 #define MPU6000_USER_CTRL 0x6A #define MPU6000_SIGNAL_PATH_RESET 0x68 #define MPU6000_PWR_MGMT_1 0x6B #define MPU6000_PWR_MGMT_2 0x6C #define MPU6000_FIFO_COUNTH 0x72 #define MPU6000_FIFO_COUNTL 0x73 #define MPU6000_FIFO_R_W 0x74 #define MPU6000_WHOAMI 0x75 // Bits #define BIT_SLEEP 0x40 #define BIT_H_RESET 0x80 #define BITS_CLKSEL 0x07 #define MPU_CLK_SEL_PLLGYROX 0x01 #define MPU_CLK_SEL_PLLGYROZ 0x03 #define MPU_EXT_SYNC_GYROX 0x02 #define BITS_FS_250DPS 0x00 #define BITS_FS_500DPS 0x08 #define BITS_FS_1000DPS 0x10 #define BITS_FS_2000DPS 0x18 #define BITS_FS_2G 0x00 #define BITS_FS_4G 0x08 #define BITS_FS_8G 0x10 #define BITS_FS_16G 0x18 #define BITS_FS_MASK 0x18 #define BITS_DLPF_CFG_256HZ 0x00 #define BITS_DLPF_CFG_188HZ 0x01 #define BITS_DLPF_CFG_98HZ 0x02 #define BITS_DLPF_CFG_42HZ 0x03 #define BITS_DLPF_CFG_20HZ 0x04 #define BITS_DLPF_CFG_10HZ 0x05 #define BITS_DLPF_CFG_5HZ 0x06 #define BITS_DLPF_CFG_2100HZ_NOLPF 0x07 #define BITS_DLPF_CFG_MASK 0x07 #define BIT_INT_ANYRD_2CLEAR 0x10 #define BIT_RAW_RDY_EN 0x01 #define BIT_I2C_IF_DIS 0x10 #define BIT_INT_STATUS_DATA 0x01 #define BIT_GYRO 3 #define BIT_ACC 2 #define BIT_TEMP 1 // Product ID Description for MPU6000 // high 4 bits low 4 bits // Product Name Product Revision #define MPU6000ES_REV_C4 0x14 #define MPU6000ES_REV_C5 0x15 #define MPU6000ES_REV_D6 0x16 #define MPU6000ES_REV_D7 0x17 #define MPU6000ES_REV_D8 0x18 #define MPU6000_REV_C4 0x54 #define MPU6000_REV_C5 0x55 #define MPU6000_REV_D6 0x56 #define MPU6000_REV_D7 0x57 #define MPU6000_REV_D8 0x58 #define MPU6000_REV_D9 0x59 #define MPU6000_REV_D10 0x5A #define DISABLE_MPU6000 GPIO_SetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN) #define ENABLE_MPU6000 GPIO_ResetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN) void mpu6000SpiGyroRead(int16_t *gyroData); void mpu6000SpiAccRead(int16_t *gyroData); static void mpu6000WriteRegister(uint8_t reg, uint8_t data) { ENABLE_MPU6000; spiTransferByte(MPU6000_SPI_INSTANCE, reg); spiTransferByte(MPU6000_SPI_INSTANCE, data); DISABLE_MPU6000; } static void mpu6000ReadRegister(uint8_t reg, uint8_t *data, int length) { ENABLE_MPU6000; spiTransferByte(MPU6000_SPI_INSTANCE, reg | 0x80); // read transaction spiTransfer(MPU6000_SPI_INSTANCE, data, NULL, length); DISABLE_MPU6000; } void mpu6000SpiGyroInit(void) { } void mpu6000SpiAccInit(void) { acc_1G = 512 * 8; } bool mpu6000SpiDetect(void) { uint8_t in; uint8_t attemptsRemaining = 5; if (mpuSpi6000InitDone) { return true; } spiSetDivisor(MPU6000_SPI_INSTANCE, SPI_0_5625MHZ_CLOCK_DIVIDER); mpu6000WriteRegister(MPU6000_PWR_MGMT_1, BIT_H_RESET); do { delay(150); mpu6000ReadRegister(MPU6000_WHOAMI, &in, 1); if (in == MPU6000_WHO_AM_I_CONST) { break; } if (!attemptsRemaining) { return false; } } while (attemptsRemaining--); mpu6000ReadRegister(MPU6000_PRODUCT_ID, &in, 1); /* look for a product ID we recognise */ // verify product revision switch (in) { case MPU6000ES_REV_C4: case MPU6000ES_REV_C5: case MPU6000_REV_C4: case MPU6000_REV_C5: case MPU6000ES_REV_D6: case MPU6000ES_REV_D7: case MPU6000ES_REV_D8: case MPU6000_REV_D6: case MPU6000_REV_D7: case MPU6000_REV_D8: case MPU6000_REV_D9: case MPU6000_REV_D10: return true; } return false; } void mpu6000AccAndGyroInit() { if (mpuSpi6000InitDone) { return; } spiSetDivisor(MPU6000_SPI_INSTANCE, SPI_0_5625MHZ_CLOCK_DIVIDER); // Device Reset mpu6000WriteRegister(MPU6000_PWR_MGMT_1, BIT_H_RESET); delay(150); mpu6000WriteRegister(MPU6000_SIGNAL_PATH_RESET, BIT_GYRO | BIT_ACC | BIT_TEMP); delay(150); // Clock Source PPL with Z axis gyro reference mpu6000WriteRegister(MPU6000_PWR_MGMT_1, MPU_CLK_SEL_PLLGYROZ); delayMicroseconds(1); // Disable Primary I2C Interface mpu6000WriteRegister(MPU6000_USER_CTRL, BIT_I2C_IF_DIS); delayMicroseconds(1); mpu6000WriteRegister(MPU6000_PWR_MGMT_2, 0x00); delayMicroseconds(1); // Accel Sample Rate 1kHz // Gyroscope Output Rate = 1kHz when the DLPF is enabled mpu6000WriteRegister(MPU6000_SMPLRT_DIV, 0x00); delayMicroseconds(1); // Accel +/- 8 G Full Scale mpu6000WriteRegister(MPU6000_ACCEL_CONFIG, BITS_FS_8G); delayMicroseconds(1); // Gyro +/- 1000 DPS Full Scale mpu6000WriteRegister(MPU6000_GYRO_CONFIG, BITS_FS_2000DPS); delayMicroseconds(1); mpuSpi6000InitDone = true; } bool mpu6000SpiAccDetect(acc_t *acc) { if (!mpu6000SpiDetect()) { return false; } spiResetErrorCounter(MPU6000_SPI_INSTANCE); mpu6000AccAndGyroInit(); acc->init = mpu6000SpiAccInit; acc->read = mpu6000SpiAccRead; delay(100); return true; } bool mpu6000SpiGyroDetect(gyro_t *gyro, uint16_t lpf) { if (!mpu6000SpiDetect()) { return false; } spiResetErrorCounter(MPU6000_SPI_INSTANCE); mpu6000AccAndGyroInit(); uint8_t mpuLowPassFilter = BITS_DLPF_CFG_42HZ; int16_t data[3]; // default lpf is 42Hz switch (lpf) { case 256: mpuLowPassFilter = BITS_DLPF_CFG_256HZ; break; case 188: mpuLowPassFilter = BITS_DLPF_CFG_188HZ; break; case 98: mpuLowPassFilter = BITS_DLPF_CFG_98HZ; break; default: case 42: mpuLowPassFilter = BITS_DLPF_CFG_42HZ; break; case 20: mpuLowPassFilter = BITS_DLPF_CFG_20HZ; break; case 10: mpuLowPassFilter = BITS_DLPF_CFG_10HZ; break; case 5: mpuLowPassFilter = BITS_DLPF_CFG_5HZ; break; case 0: mpuLowPassFilter = BITS_DLPF_CFG_2100HZ_NOLPF; break; } spiSetDivisor(MPU6000_SPI_INSTANCE, SPI_0_5625MHZ_CLOCK_DIVIDER); // Accel and Gyro DLPF Setting mpu6000WriteRegister(MPU6000_CONFIG, mpuLowPassFilter); delayMicroseconds(1); mpu6000SpiGyroRead(data); if ((((int8_t)data[1]) == -1 && ((int8_t)data[0]) == -1) || spiGetErrorCounter(MPU6000_SPI_INSTANCE) != 0) { spiResetErrorCounter(MPU6000_SPI_INSTANCE); return false; } gyro->init = mpu6000SpiGyroInit; gyro->read = mpu6000SpiGyroRead; // 16.4 dps/lsb scalefactor gyro->scale = 1.0f / 16.4f; //gyro->scale = (4.0f / 16.4f) * (M_PIf / 180.0f) * 0.000001f; delay(100); return true; } void mpu6000SpiGyroRead(int16_t *gyroData) { uint8_t buf[6]; spiSetDivisor(MPU6000_SPI_INSTANCE, SPI_18MHZ_CLOCK_DIVIDER); // 18 MHz SPI clock mpu6000ReadRegister(MPU6000_GYRO_XOUT_H, buf, 6); gyroData[X] = (int16_t)((buf[0] << 8) | buf[1]); gyroData[Y] = (int16_t)((buf[2] << 8) | buf[3]); gyroData[Z] = (int16_t)((buf[4] << 8) | buf[5]); } void mpu6000SpiAccRead(int16_t *gyroData) { uint8_t buf[6]; spiSetDivisor(MPU6000_SPI_INSTANCE, SPI_18MHZ_CLOCK_DIVIDER); // 18 MHz SPI clock mpu6000ReadRegister(MPU6000_ACCEL_XOUT_H, buf, 6); gyroData[X] = (int16_t)((buf[0] << 8) | buf[1]); gyroData[Y] = (int16_t)((buf[2] << 8) | buf[3]); gyroData[Z] = (int16_t)((buf[4] << 8) | buf[5]); }
@import url("./Steel on Blue.css"); @import url("../Styles/noname.css");
----------------------------------- -- Area: Nashmau -- NPC: Wafeeyah -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x000B); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
<?php if (!defined('sugarEntry') || !sugarEntry) { die('Not A Valid Entry Point'); } /** * * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd. * Copyright (C) 2011 - 2018 SalesAgility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". */ $module_name = 'SurveyQuestionResponses'; $listViewDefs[$module_name] = array( 'NAME' => array( 'width' => '32', 'label' => 'LBL_NAME', 'default' => true, 'link' => true ), 'ASSIGNED_USER_NAME' => array( 'width' => '9', 'label' => 'LBL_ASSIGNED_TO_NAME', 'module' => 'Employees', 'id' => 'ASSIGNED_USER_ID', 'default' => true ), );
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.query.timeboundary; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import io.druid.jackson.DefaultObjectMapper; import io.druid.query.Druids; import io.druid.query.Query; import org.junit.Assert; import org.junit.Test; import java.io.IOException; public class TimeBoundaryQueryTest { private static final ObjectMapper jsonMapper = new DefaultObjectMapper(); @Test public void testQuerySerialization() throws IOException { Query query = Druids.newTimeBoundaryQueryBuilder() .dataSource("testing") .build(); String json = jsonMapper.writeValueAsString(query); Query serdeQuery = jsonMapper.readValue(json, Query.class); Assert.assertEquals(query, serdeQuery); } @Test public void testContextSerde() throws Exception { final TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder() .dataSource("foo") .intervals("2013/2014") .context( ImmutableMap.<String, Object>of( "priority", 1, "useCache", true, "populateCache", true, "finalize", true ) ).build(); final ObjectMapper mapper = new DefaultObjectMapper(); final TimeBoundaryQuery serdeQuery = mapper.readValue( mapper.writeValueAsBytes( mapper.readValue( mapper.writeValueAsString( query ), TimeBoundaryQuery.class ) ), TimeBoundaryQuery.class ); Assert.assertEquals(1, serdeQuery.getContextValue("priority")); Assert.assertEquals(true, serdeQuery.getContextValue("useCache")); Assert.assertEquals(true, serdeQuery.getContextValue("populateCache")); Assert.assertEquals(true, serdeQuery.getContextValue("finalize")); } @Test public void testContextSerde2() throws Exception { final TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder() .dataSource("foo") .intervals("2013/2014") .context( ImmutableMap.<String, Object>of( "priority", "1", "useCache", "true", "populateCache", "true", "finalize", "true" ) ).build(); final ObjectMapper mapper = new DefaultObjectMapper(); final TimeBoundaryQuery serdeQuery = mapper.readValue( mapper.writeValueAsBytes( mapper.readValue( mapper.writeValueAsString( query ), TimeBoundaryQuery.class ) ), TimeBoundaryQuery.class ); Assert.assertEquals("1", serdeQuery.getContextValue("priority")); Assert.assertEquals("true", serdeQuery.getContextValue("useCache")); Assert.assertEquals("true", serdeQuery.getContextValue("populateCache")); Assert.assertEquals("true", serdeQuery.getContextValue("finalize")); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.rest; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.logger.java.JavaLogger; import org.apache.ignite.marshaller.Marshaller; import org.apache.ignite.marshaller.jdk.JdkMarshaller; import org.jetbrains.annotations.Nullable; /** * Test client. */ final class TestMemcacheClient { /** Header length. */ private static final short HDR_LEN = 24; /** Serialized flag. */ private static final short SERIALIZED_FLAG = 1; /** Boolean flag. */ private static final short BOOLEAN_FLAG = (1 << 8); /** Integer flag. */ private static final short INT_FLAG = (2 << 8); /** Long flag. */ private static final short LONG_FLAG = (3 << 8); /** Date flag. */ private static final short DATE_FLAG = (4 << 8); /** Byte flag. */ private static final short BYTE_FLAG = (5 << 8); /** Float flag. */ private static final short FLOAT_FLAG = (6 << 8); /** Double flag. */ private static final short DOUBLE_FLAG = (7 << 8); /** Byte array flag. */ private static final short BYTE_ARR_FLAG = (8 << 8); /** Logger. */ private final IgniteLogger log = new JavaLogger(); /** JDK marshaller. */ private final Marshaller jdkMarshaller = new JdkMarshaller(); /** Socket. */ private final Socket sock; /** Opaque counter. */ private final AtomicInteger opaqueCntr = new AtomicInteger(0); /** Response queue. */ private final BlockingQueue<Response> queue = new LinkedBlockingQueue<>(); /** Socket reader. */ private final Thread rdr; /** Quit response. */ private static final Response QUIT_RESP = new Response(0, false, null, null); /** * Creates client. * * @param host Hostname. * @param port Port number. * @throws IgniteCheckedException In case of error. */ TestMemcacheClient(String host, int port) throws IgniteCheckedException { assert host != null; assert port > 0; try { sock = new Socket(host, port); } catch (IOException e) { throw new IgniteCheckedException("Failed to establish connection.", e); } // Start socket reader thread. rdr = new Thread(new Runnable() { @SuppressWarnings("InfiniteLoopStatement") @Override public void run() { try { InputStream in = sock.getInputStream(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); boolean running = true; while (running) { byte opCode = 0; byte extrasLength = 0; int keyLength = 0; boolean success = false; int totalLength = 0; int opaque = 0; short keyFlags = 0; short valFlags = 0; Object obj = null; Object key = null; int i = 0; while (true) { int symbol = in.read(); if (symbol == -1) { running = false; break; } byte b = (byte)symbol; if (i == 1) opCode = b; if (i == 2 || i == 3) { buf.write(b); if (i == 3) { keyLength = U.bytesToShort(buf.toByteArray(), 0); buf.reset(); } } else if (i == 4) extrasLength = b; else if (i == 6 || i == 7) { buf.write(b); if (i == 7) { success = U.bytesToShort(buf.toByteArray(), 0) == 0; buf.reset(); } } else if (i >= 8 && i <= 11) { buf.write(b); if (i == 11) { totalLength = U.bytesToInt(buf.toByteArray(), 0); buf.reset(); } } else if (i >= 12 && i <= 15) { buf.write(b); if (i == 15) { opaque = U.bytesToInt(buf.toByteArray(), 0); buf.reset(); } } else if (i >= HDR_LEN && i < HDR_LEN + extrasLength) { buf.write(b); if (i == HDR_LEN + extrasLength - 1) { byte[] rawFlags = buf.toByteArray(); keyFlags = U.bytesToShort(rawFlags, 0); valFlags = U.bytesToShort(rawFlags, 2); buf.reset(); } } else if (i >= HDR_LEN + extrasLength && i < HDR_LEN + extrasLength + keyLength) { buf.write(b); if (i == HDR_LEN + extrasLength + keyLength - 1) { key = decode(buf.toByteArray(), keyFlags); buf.reset(); } } else if (i >= HDR_LEN + extrasLength + keyLength && i < HDR_LEN + totalLength) { buf.write(b); if (opCode == 0x05 || opCode == 0x06) valFlags = LONG_FLAG; if (i == HDR_LEN + totalLength - 1) { obj = decode(buf.toByteArray(), valFlags); buf.reset(); } } if (i == HDR_LEN + totalLength - 1) { queue.add(new Response(opaque, success, key, obj)); break; } i++; } } } catch (IOException e) { if (!Thread.currentThread().isInterrupted()) U.error(log, e); } catch (Exception e) { U.error(log, e); } finally { U.closeQuiet(sock); queue.add(QUIT_RESP); } } }); rdr.start(); } /** {@inheritDoc} */ public void shutdown() throws IgniteCheckedException { try { if (rdr != null) { rdr.interrupt(); U.closeQuiet(sock); rdr.join(); } } catch (InterruptedException e) { throw new IgniteCheckedException(e); } } /** * Makes request to server and waits for response. * * @param cmd Command. * @param cacheName Cache name. * @param key Key. * @param val Value. * @param extras Extras. * @return Response. * @throws IgniteCheckedException In case of error. */ private Response makeRequest( Command cmd, @Nullable String cacheName, @Nullable Object key, @Nullable Object val, @Nullable Long... extras ) throws IgniteCheckedException { assert cmd != null; int opaque = opaqueCntr.getAndIncrement(); // Send request. try { sock.getOutputStream().write(createPacket(cmd, cacheName, key, val, opaque, extras)); } catch (IOException e) { throw new IgniteCheckedException("Failed to send packet.", e); } // Wait for response. while (true) { try { // Take response from queue. Response res = queue.take(); if (res == QUIT_RESP) return res; // Check opaque value. if (res.getOpaque() == opaque) { if (!res.isSuccess() && res.getObject() != null) throw new IgniteCheckedException((String)res.getObject()); else return res; } else // Return response to queue if opaque is incorrect. queue.add(res); } catch (InterruptedException e) { throw new IgniteCheckedException("Interrupted while waiting for response.", e); } } } /** * Makes request to server and waits for response. * * @param cmd Command. * @param cacheName Cache name. * @param key Key. * @param val Value. * @param extras Extras. * @return Response. * @throws IgniteCheckedException In case of error. */ private List<Response> makeMultiRequest( Command cmd, @Nullable String cacheName, @Nullable Object key, @Nullable Object val, @Nullable Long... extras ) throws IgniteCheckedException { assert cmd != null; int opaque = opaqueCntr.getAndIncrement(); List<Response> resList = new LinkedList<>(); // Send request. try { sock.getOutputStream().write(createPacket(cmd, cacheName, key, val, opaque, extras)); } catch (IOException e) { throw new IgniteCheckedException("Failed to send packet.", e); } // Wait for response. while (true) { try { // Take response from queue. Response res = queue.take(); if (res == QUIT_RESP) return resList; // Check opaque value. if (res.getOpaque() == opaque) { if (!res.isSuccess() && res.getObject() != null) throw new IgniteCheckedException((String)res.getObject()); else { if (res.getObject() == null) return resList; resList.add(res); } } else // Return response to queue if opaque is incorrect. queue.add(res); } catch (InterruptedException e) { throw new IgniteCheckedException("Interrupted while waiting for response.", e); } } } /** * Creates packet. * * @param cmd Command. * @param cacheName Cache name. * @param key Key. * @param val Value. * @param opaque Opaque. * @param extras Extras. * @throws IgniteCheckedException In case of error. * @return Packet. */ private byte[] createPacket( Command cmd, @Nullable String cacheName, @Nullable Object key, @Nullable Object val, int opaque, @Nullable Long[] extras ) throws IgniteCheckedException { assert cmd != null; assert opaque >= 0; byte[] cacheNameBytes = cacheName != null ? cacheName.getBytes() : null; Data keyData = encode(key); Data valData = encode(val); int cacheNameLength = cacheNameBytes != null ? cacheNameBytes.length : 0; int extrasLength = cmd.extrasLength() + cacheNameLength; byte[] packet = new byte[HDR_LEN + extrasLength + keyData.length() + valData.length()]; packet[0] = (byte)0x80; packet[1] = cmd.operationCode(); U.shortToBytes((short) keyData.length(), packet, 2); packet[4] = (byte)(extrasLength); U.intToBytes(extrasLength + keyData.length() + valData.length(), packet, 8); U.intToBytes(opaque, packet, 12); if (extrasLength > 0) { if (extras != null) { int offset = HDR_LEN; for (Long extra : extras) { if (extra != null) U.longToBytes(extra, packet, offset); offset += 8; } } else { U.shortToBytes(keyData.getFlags(), packet, HDR_LEN); U.shortToBytes(valData.getFlags(), packet, HDR_LEN + 2); } } if (cacheNameBytes != null) U.arrayCopy(cacheNameBytes, 0, packet, HDR_LEN + cmd.extrasLength(), cacheNameLength); if (keyData.getBytes() != null) U.arrayCopy(keyData.getBytes(), 0, packet, HDR_LEN + extrasLength, keyData.length()); if (valData.getBytes() != null) U.arrayCopy(valData.getBytes(), 0, packet, HDR_LEN + extrasLength + keyData.length(), valData.length()); return packet; } /** * @param cacheName Cache name. * @param key Key. * @param val Value. * @return If value was actually put. * @throws IgniteCheckedException In case of error. */ public <K, V> boolean cachePut(@Nullable String cacheName, K key, V val) throws IgniteCheckedException { assert key != null; assert val != null; return makeRequest(Command.PUT, cacheName, key, val).isSuccess(); } /** * @param cacheName Cache name. * @param key Key. * @return Value. * @throws IgniteCheckedException In case of error. */ public <K, V> V cacheGet(@Nullable String cacheName, K key) throws IgniteCheckedException { assert key != null; return makeRequest(Command.GET, cacheName, key, null).getObject(); } /** * @param cacheName Cache name. * @param key Key. * @return Whether entry was actually removed. * @throws IgniteCheckedException In case of error. */ public <K> boolean cacheRemove(@Nullable String cacheName, K key) throws IgniteCheckedException { assert key != null; return makeRequest(Command.REMOVE, cacheName, key, null).isSuccess(); } /** * @param cacheName Cache name. * @param key Key. * @param val Value. * @return Whether entry was added. * @throws IgniteCheckedException In case of error. */ public <K, V> boolean cacheAdd(@Nullable String cacheName, K key, V val) throws IgniteCheckedException { assert key != null; assert val != null; return makeRequest(Command.ADD, cacheName, key, val).isSuccess(); } /** * @param cacheName Cache name. * @param key Key. * @param val Value. * @return Whether value was actually replaced. * @throws IgniteCheckedException In case of error. */ public <K, V> boolean cacheReplace(@Nullable String cacheName, K key, V val) throws IgniteCheckedException { assert key != null; assert val != null; return makeRequest(Command.REPLACE, cacheName, key, val).isSuccess(); } /** * @param cacheName Cache name. * @throws IgniteCheckedException In case of error. * @return Metrics map. */ public <K> Map<String, Long> cacheMetrics(@Nullable String cacheName) throws IgniteCheckedException { List<Response> raw = makeMultiRequest(Command.CACHE_METRICS, cacheName, null, null); Map<String, Long> res = new HashMap<>(raw.size()); for (Response resp : raw) res.put((String)resp.key(), Long.parseLong(String.valueOf(resp.<String>getObject()))); return res; } /** * @param key Key. * @param init Initial value (optional). * @param incr Amount to add. * @return New value. * @throws IgniteCheckedException In case of error. */ public <K> long increment(K key, @Nullable Long init, long incr) throws IgniteCheckedException { assert key != null; return makeRequest(Command.INCREMENT, null, key, null, incr, init).<Long>getObject(); } /** * @param key Key. * @param init Initial value (optional). * @param decr Amount to subtract. * @return New value. * @throws IgniteCheckedException In case of error. */ public <K> long decrement(K key, @Nullable Long init, long decr) throws IgniteCheckedException { assert key != null; return makeRequest(Command.DECREMENT, null, key, null, decr, init).<Long>getObject(); } /** * @param cacheName Cache name. * @param key Key. * @param val Value to append. * @return Whether operation succeeded. * @throws IgniteCheckedException In case of error. */ public <K> boolean cacheAppend(@Nullable String cacheName, K key, String val) throws IgniteCheckedException { assert key != null; assert val != null; return makeRequest(Command.APPEND, cacheName, key, val).isSuccess(); } /** * @param cacheName Cache name. * @param key Key. * @param val Value to prepend. * @return Whether operation succeeded. * @throws IgniteCheckedException In case of error. */ public <K> boolean cachePrepend(@Nullable String cacheName, K key, String val) throws IgniteCheckedException { assert key != null; assert val != null; return makeRequest(Command.PREPEND, cacheName, key, val).isSuccess(); } /** * @return Version. * @throws IgniteCheckedException In case of error. */ public String version() throws IgniteCheckedException { return makeRequest(Command.VERSION, null, null, null).getObject(); } /** * @throws IgniteCheckedException In case of error. */ public void noop() throws IgniteCheckedException { Response res = makeRequest(Command.NOOP, null, null, null); assert res != null; assert res.isSuccess(); assert res.getObject() == null; } /** * @throws IgniteCheckedException In case of error. */ public void quit() throws IgniteCheckedException { makeRequest(Command.QUIT, null, null, null); assert sock.isClosed(); } /** * Encodes object. * * @param obj Object. * @return Encoded data. * @throws IgniteCheckedException In case of error. */ public Data encode(@Nullable Object obj) throws IgniteCheckedException { if (obj == null) return new Data(null, (short)0); byte[] bytes; short flags = 0; if (obj instanceof String) bytes = ((String)obj).getBytes(); else if (obj instanceof Boolean) { bytes = new byte[] {(byte)((Boolean)obj ? '1' : '0')}; flags |= BOOLEAN_FLAG; } else if (obj instanceof Integer) { bytes = U.intToBytes((Integer) obj); flags |= INT_FLAG; } else if (obj instanceof Long) { bytes = U.longToBytes((Long) obj); flags |= LONG_FLAG; } else if (obj instanceof Date) { bytes = U.longToBytes(((Date) obj).getTime()); flags |= DATE_FLAG; } else if (obj instanceof Byte) { bytes = new byte[] {(Byte)obj}; flags |= BYTE_FLAG; } else if (obj instanceof Float) { bytes = U.intToBytes(Float.floatToIntBits((Float) obj)); flags |= FLOAT_FLAG; } else if (obj instanceof Double) { bytes = U.longToBytes(Double.doubleToLongBits((Double) obj)); flags |= DOUBLE_FLAG; } else if (obj instanceof byte[]) { bytes = (byte[])obj; flags |= BYTE_ARR_FLAG; } else { bytes = jdkMarshaller.marshal(obj); flags |= SERIALIZED_FLAG; } return new Data(bytes, flags); } /** * @param bytes Byte array to decode. * @param flags Flags. * @return Decoded value. * @throws IgniteCheckedException In case of error. */ public Object decode(byte[] bytes, short flags) throws IgniteCheckedException { assert bytes != null; assert flags >= 0; if ((flags & SERIALIZED_FLAG) != 0) return jdkMarshaller.unmarshal(bytes, getClass().getClassLoader()); int masked = flags & 0xff00; switch (masked) { case BOOLEAN_FLAG: return bytes[0] == '1'; case INT_FLAG: return U.bytesToInt(bytes, 0); case LONG_FLAG: return U.bytesToLong(bytes, 0); case DATE_FLAG: return new Date(U.bytesToLong(bytes, 0)); case BYTE_FLAG: return bytes[0]; case FLOAT_FLAG: return Float.intBitsToFloat(U.bytesToInt(bytes, 0)); case DOUBLE_FLAG: return Double.longBitsToDouble(U.bytesToLong(bytes, 0)); case BYTE_ARR_FLAG: return bytes; default: return new String(bytes); } } /** * Response data. */ private static class Response { /** Opaque. */ private final int opaque; /** Success flag. */ private final boolean success; /** Key. */ private final Object key; /** Response object. */ private final Object obj; /** * @param opaque Opaque. * @param success Success flag. * @param key Key object. * @param obj Response object. */ Response(int opaque, boolean success, @Nullable Object key, @Nullable Object obj) { assert opaque >= 0; this.opaque = opaque; this.success = success; this.key = key; this.obj = obj; } /** * @return Opaque. */ int getOpaque() { return opaque; } /** * @return Success flag. */ boolean isSuccess() { return success; } Object key() { return key; } /** * @return Response object. */ @SuppressWarnings("unchecked") <T> T getObject() { return (T)obj; } } private static class Data { /** Bytes. */ private final byte[] bytes; /** Flags. */ private final short flags; /** * @param bytes Bytes. * @param flags Flags. */ Data(@Nullable byte[] bytes, short flags) { assert flags >= 0; this.bytes = bytes; this.flags = flags; } /** * @return Bytes. */ @Nullable public byte[] getBytes() { return bytes; } /** * @return Flags. */ public short getFlags() { return flags; } /** * @return Length. */ public int length() { return bytes != null ? bytes.length : 0; } } /** * Command. */ private enum Command { /** Get. */ GET((byte)0x00, 4), /** Put. */ PUT((byte)0x01, 8), /** Add. */ ADD((byte)0x02, 8), /** Replace. */ REPLACE((byte)0x03, 8), /** Remove. */ REMOVE((byte)0x04, 4), /** Increment. */ INCREMENT((byte)0x05, 20), /** Decrement. */ DECREMENT((byte)0x06, 20), /** Quit. */ QUIT((byte)0x07, 0), /** Cache metrics. */ CACHE_METRICS((byte)0x10, 4), /** No-op. */ NOOP((byte)0x0A, 0), /** Version. */ VERSION((byte)0x0B, 0), /** Append. */ APPEND((byte)0x0E, 4), /** Append. */ PREPEND((byte)0x0F, 4); /** Operation code. */ private final byte opCode; /** Extras length. */ private final int extrasLength; /** * @param opCode Operation code. * @param extrasLength Extras length. */ Command(byte opCode, int extrasLength) { this.opCode = opCode; this.extrasLength = extrasLength; } /** * @return Operation code. */ public byte operationCode() { return opCode; } /** * @return Extras length. */ public int extrasLength() { return extrasLength; } } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.query; import com.fasterxml.jackson.core.io.JsonStringEncoder; import org.apache.lucene.index.Term; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.spans.SpanTermQuery; import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.lucene.BytesRefs; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.search.internal.SearchContext; import java.io.IOException; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; public class SpanTermQueryBuilderTests extends AbstractTermQueryTestCase<SpanTermQueryBuilder> { @Override protected SpanTermQueryBuilder doCreateTestQueryBuilder() { String fieldName = randomFrom(STRING_FIELD_NAME, STRING_ALIAS_FIELD_NAME, randomAlphaOfLengthBetween(1, 10)); Object value; if (frequently()) { value = randomAlphaOfLengthBetween(1, 10); } else { // generate unicode string in 10% of cases JsonStringEncoder encoder = JsonStringEncoder.getInstance(); value = new String(encoder.quoteAsString(randomUnicodeOfLength(10))); } return createQueryBuilder(fieldName, value); } @Override protected SpanTermQueryBuilder createQueryBuilder(String fieldName, Object value) { return new SpanTermQueryBuilder(fieldName, value); } @Override protected void doAssertLuceneQuery(SpanTermQueryBuilder queryBuilder, Query query, SearchContext context) throws IOException { assertThat(query, instanceOf(SpanTermQuery.class)); SpanTermQuery spanTermQuery = (SpanTermQuery) query; String expectedFieldName = expectedFieldName(queryBuilder.fieldName); assertThat(spanTermQuery.getTerm().field(), equalTo(expectedFieldName)); MappedFieldType mapper = context.getQueryShardContext().fieldMapper(queryBuilder.fieldName()); if (mapper != null) { Term term = ((TermQuery) mapper.termQuery(queryBuilder.value(), null)).getTerm(); assertThat(spanTermQuery.getTerm(), equalTo(term)); } else { assertThat(spanTermQuery.getTerm().bytes(), equalTo(BytesRefs.toBytesRef(queryBuilder.value()))); } } /** * @param amount a number of clauses that will be returned * @return the array of random {@link SpanTermQueryBuilder} with same field name */ public SpanTermQueryBuilder[] createSpanTermQueryBuilders(int amount) { SpanTermQueryBuilder[] clauses = new SpanTermQueryBuilder[amount]; SpanTermQueryBuilder first = createTestQueryBuilder(false, true); clauses[0] = first; for (int i = 1; i < amount; i++) { // we need same field name in all clauses, so we only randomize value SpanTermQueryBuilder spanTermQuery = new SpanTermQueryBuilder(first.fieldName(), getRandomValueForFieldName(first.fieldName())); if (randomBoolean()) { spanTermQuery.queryName(randomAlphaOfLengthBetween(1, 10)); } clauses[i] = spanTermQuery; } return clauses; } public void testFromJson() throws IOException { String json = "{ \"span_term\" : { \"user\" : { \"value\" : \"kimchy\", \"boost\" : 2.0 } }}"; SpanTermQueryBuilder parsed = (SpanTermQueryBuilder) parseQuery(json); checkGeneratedJson(json, parsed); assertEquals(json, "kimchy", parsed.value()); assertEquals(json, 2.0, parsed.boost(), 0.0001); } public void testParseFailsWithMultipleFields() throws IOException { String json = "{\n" + " \"span_term\" : {\n" + " \"message1\" : {\n" + " \"term\" : \"this\"\n" + " },\n" + " \"message2\" : {\n" + " \"term\" : \"this\"\n" + " }\n" + " }\n" + "}"; ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json)); assertEquals("[span_term] query doesn't support multiple fields, found [message1] and [message2]", e.getMessage()); String shortJson = "{\n" + " \"span_term\" : {\n" + " \"message1\" : \"this\",\n" + " \"message2\" : \"this\"\n" + " }\n" + "}"; e = expectThrows(ParsingException.class, () -> parseQuery(shortJson)); assertEquals("[span_term] query doesn't support multiple fields, found [message1] and [message2]", e.getMessage()); } public void testWithMetaDataField() throws IOException { QueryShardContext context = createShardContext(); for (String field : new String[]{"field1", "field2"}) { SpanTermQueryBuilder spanTermQueryBuilder = new SpanTermQueryBuilder(field, "toto"); Query query = spanTermQueryBuilder.toQuery(context); Query expected = new SpanTermQuery(new Term(field, "toto")); assertEquals(expected, query); } } }
module Fog module Parsers module AWS module RDS class SecurityGroupParser < Fog::Parsers::Base def reset @security_group = fresh_security_group end def fresh_security_group {'EC2SecurityGroups' => [], 'IPRanges' => []} end def start_element(name, attrs = []) super case name when 'EC2SecurityGroup', 'IPRange'; then @ingress = {} end end def end_element(name) case name when 'DBSecurityGroupDescription' then @security_group['DBSecurityGroupDescription'] = value when 'DBSecurityGroupName' then @security_group['DBSecurityGroupName'] = value when 'OwnerId' then @security_group['OwnerId'] = value when 'EC2SecurityGroup', 'IPRange' @security_group["#{name}s"] << @ingress unless @ingress.empty? when 'EC2SecurityGroupName', 'EC2SecurityGroupOwnerId', 'CIDRIP', 'Status' @ingress[name] = value end end end end end end end
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:generate go run gen.go gen_trieval.go gen_common.go // Package idna implements IDNA2008 using the compatibility processing // defined by UTS (Unicode Technical Standard) #46, which defines a standard to // deal with the transition from IDNA2003. // // IDNA2008 (Internationalized Domain Names for Applications), is defined in RFC // 5890, RFC 5891, RFC 5892, RFC 5893 and RFC 5894. // UTS #46 is defined in http://www.unicode.org/reports/tr46. // See http://unicode.org/cldr/utility/idna.jsp for a visualization of the // differences between these two standards. package idna // import "golang.org/x/text/internal/export/idna" import ( "fmt" "strings" "unicode/utf8" "golang.org/x/text/secure/bidirule" "golang.org/x/text/unicode/bidi" "golang.org/x/text/unicode/norm" ) // NOTE: Unlike common practice in Go APIs, the functions will return a // sanitized domain name in case of errors. Browsers sometimes use a partially // evaluated string as lookup. // TODO: the current error handling is, in my opinion, the least opinionated. // Other strategies are also viable, though: // Option 1) Return an empty string in case of error, but allow the user to // specify explicitly which errors to ignore. // Option 2) Return the partially evaluated string if it is itself a valid // string, otherwise return the empty string in case of error. // Option 3) Option 1 and 2. // Option 4) Always return an empty string for now and implement Option 1 as // needed, and document that the return string may not be empty in case of // error in the future. // I think Option 1 is best, but it is quite opinionated. // ToASCII is a wrapper for Punycode.ToASCII. func ToASCII(s string) (string, error) { return Punycode.process(s, true) } // ToUnicode is a wrapper for Punycode.ToUnicode. func ToUnicode(s string) (string, error) { return Punycode.process(s, false) } // An Option configures a Profile at creation time. type Option func(*options) // Transitional sets a Profile to use the Transitional mapping as defined in UTS // #46. This will cause, for example, "ß" to be mapped to "ss". Using the // transitional mapping provides a compromise between IDNA2003 and IDNA2008 // compatibility. It is used by most browsers when resolving domain names. This // option is only meaningful if combined with MapForLookup. func Transitional(transitional bool) Option { return func(o *options) { o.transitional = true } } // VerifyDNSLength sets whether a Profile should fail if any of the IDN parts // are longer than allowed by the RFC. func VerifyDNSLength(verify bool) Option { return func(o *options) { o.verifyDNSLength = verify } } // RemoveLeadingDots removes leading label separators. Leading runes that map to // dots, such as U+3002 IDEOGRAPHIC FULL STOP, are removed as well. // // This is the behavior suggested by the UTS #46 and is adopted by some // browsers. func RemoveLeadingDots(remove bool) Option { return func(o *options) { o.removeLeadingDots = remove } } // ValidateLabels sets whether to check the mandatory label validation criteria // as defined in Section 5.4 of RFC 5891. This includes testing for correct use // of hyphens ('-'), normalization, validity of runes, and the context rules. func ValidateLabels(enable bool) Option { return func(o *options) { // Don't override existing mappings, but set one that at least checks // normalization if it is not set. if o.mapping == nil && enable { o.mapping = normalize } o.trie = trie o.validateLabels = enable o.fromPuny = validateFromPunycode } } // StrictDomainName limits the set of permissible ASCII characters to those // allowed in domain names as defined in RFC 1034 (A-Z, a-z, 0-9 and the // hyphen). This is set by default for MapForLookup and ValidateForRegistration. // // This option is useful, for instance, for browsers that allow characters // outside this range, for example a '_' (U+005F LOW LINE). See // http://www.rfc-editor.org/std/std3.txt for more details This option // corresponds to the UseSTD3ASCIIRules option in UTS #46. func StrictDomainName(use bool) Option { return func(o *options) { o.trie = trie o.useSTD3Rules = use o.fromPuny = validateFromPunycode } } // NOTE: the following options pull in tables. The tables should not be linked // in as long as the options are not used. // BidiRule enables the Bidi rule as defined in RFC 5893. Any application // that relies on proper validation of labels should include this rule. func BidiRule() Option { return func(o *options) { o.bidirule = bidirule.ValidString } } // ValidateForRegistration sets validation options to verify that a given IDN is // properly formatted for registration as defined by Section 4 of RFC 5891. func ValidateForRegistration() Option { return func(o *options) { o.mapping = validateRegistration StrictDomainName(true)(o) ValidateLabels(true)(o) VerifyDNSLength(true)(o) BidiRule()(o) } } // MapForLookup sets validation and mapping options such that a given IDN is // transformed for domain name lookup according to the requirements set out in // Section 5 of RFC 5891. The mappings follow the recommendations of RFC 5894, // RFC 5895 and UTS 46. It does not add the Bidi Rule. Use the BidiRule option // to add this check. // // The mappings include normalization and mapping case, width and other // compatibility mappings. func MapForLookup() Option { return func(o *options) { o.mapping = validateAndMap StrictDomainName(true)(o) ValidateLabels(true)(o) } } type options struct { transitional bool useSTD3Rules bool validateLabels bool verifyDNSLength bool removeLeadingDots bool trie *idnaTrie // fromPuny calls validation rules when converting A-labels to U-labels. fromPuny func(p *Profile, s string) error // mapping implements a validation and mapping step as defined in RFC 5895 // or UTS 46, tailored to, for example, domain registration or lookup. mapping func(p *Profile, s string) (mapped string, isBidi bool, err error) // bidirule, if specified, checks whether s conforms to the Bidi Rule // defined in RFC 5893. bidirule func(s string) bool } // A Profile defines the configuration of an IDNA mapper. type Profile struct { options } func apply(o *options, opts []Option) { for _, f := range opts { f(o) } } // New creates a new Profile. // // With no options, the returned Profile is the most permissive and equals the // Punycode Profile. Options can be passed to further restrict the Profile. The // MapForLookup and ValidateForRegistration options set a collection of options, // for lookup and registration purposes respectively, which can be tailored by // adding more fine-grained options, where later options override earlier // options. func New(o ...Option) *Profile { p := &Profile{} apply(&p.options, o) return p } // ToASCII converts a domain or domain label to its ASCII form. For example, // ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and // ToASCII("golang") is "golang". If an error is encountered it will return // an error and a (partially) processed result. func (p *Profile) ToASCII(s string) (string, error) { return p.process(s, true) } // ToUnicode converts a domain or domain label to its Unicode form. For example, // ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and // ToUnicode("golang") is "golang". If an error is encountered it will return // an error and a (partially) processed result. func (p *Profile) ToUnicode(s string) (string, error) { pp := *p pp.transitional = false return pp.process(s, false) } // String reports a string with a description of the profile for debugging // purposes. The string format may change with different versions. func (p *Profile) String() string { s := "" if p.transitional { s = "Transitional" } else { s = "NonTransitional" } if p.useSTD3Rules { s += ":UseSTD3Rules" } if p.validateLabels { s += ":ValidateLabels" } if p.verifyDNSLength { s += ":VerifyDNSLength" } return s } var ( // Punycode is a Profile that does raw punycode processing with a minimum // of validation. Punycode *Profile = punycode // Lookup is the recommended profile for looking up domain names, according // to Section 5 of RFC 5891. The exact configuration of this profile may // change over time. Lookup *Profile = lookup // Display is the recommended profile for displaying domain names. // The configuration of this profile may change over time. Display *Profile = display // Registration is the recommended profile for checking whether a given // IDN is valid for registration, according to Section 4 of RFC 5891. Registration *Profile = registration punycode = &Profile{} lookup = &Profile{options{ transitional: true, useSTD3Rules: true, validateLabels: true, trie: trie, fromPuny: validateFromPunycode, mapping: validateAndMap, bidirule: bidirule.ValidString, }} display = &Profile{options{ useSTD3Rules: true, validateLabels: true, trie: trie, fromPuny: validateFromPunycode, mapping: validateAndMap, bidirule: bidirule.ValidString, }} registration = &Profile{options{ useSTD3Rules: true, validateLabels: true, verifyDNSLength: true, trie: trie, fromPuny: validateFromPunycode, mapping: validateRegistration, bidirule: bidirule.ValidString, }} // TODO: profiles // Register: recommended for approving domain names: don't do any mappings // but rather reject on invalid input. Bundle or block deviation characters. ) type labelError struct{ label, code_ string } func (e labelError) code() string { return e.code_ } func (e labelError) Error() string { return fmt.Sprintf("idna: invalid label %q", e.label) } type runeError rune func (e runeError) code() string { return "P1" } func (e runeError) Error() string { return fmt.Sprintf("idna: disallowed rune %U", e) } // process implements the algorithm described in section 4 of UTS #46, // see http://www.unicode.org/reports/tr46. func (p *Profile) process(s string, toASCII bool) (string, error) { var err error var isBidi bool if p.mapping != nil { s, isBidi, err = p.mapping(p, s) } // Remove leading empty labels. if p.removeLeadingDots { for ; len(s) > 0 && s[0] == '.'; s = s[1:] { } } // TODO: allow for a quick check of the tables data. // It seems like we should only create this error on ToASCII, but the // UTS 46 conformance tests suggests we should always check this. if err == nil && p.verifyDNSLength && s == "" { err = &labelError{s, "A4"} } labels := labelIter{orig: s} for ; !labels.done(); labels.next() { label := labels.label() if label == "" { // Empty labels are not okay. The label iterator skips the last // label if it is empty. if err == nil && p.verifyDNSLength { err = &labelError{s, "A4"} } continue } if strings.HasPrefix(label, acePrefix) { u, err2 := decode(label[len(acePrefix):]) if err2 != nil { if err == nil { err = err2 } // Spec says keep the old label. continue } isBidi = isBidi || bidirule.DirectionString(u) != bidi.LeftToRight labels.set(u) if err == nil && p.validateLabels { err = p.fromPuny(p, u) } if err == nil { // This should be called on NonTransitional, according to the // spec, but that currently does not have any effect. Use the // original profile to preserve options. err = p.validateLabel(u) } } else if err == nil { err = p.validateLabel(label) } } if isBidi && p.bidirule != nil && err == nil { for labels.reset(); !labels.done(); labels.next() { if !p.bidirule(labels.label()) { err = &labelError{s, "B"} break } } } if toASCII { for labels.reset(); !labels.done(); labels.next() { label := labels.label() if !ascii(label) { a, err2 := encode(acePrefix, label) if err == nil { err = err2 } label = a labels.set(a) } n := len(label) if p.verifyDNSLength && err == nil && (n == 0 || n > 63) { err = &labelError{label, "A4"} } } } s = labels.result() if toASCII && p.verifyDNSLength && err == nil { // Compute the length of the domain name minus the root label and its dot. n := len(s) if n > 0 && s[n-1] == '.' { n-- } if len(s) < 1 || n > 253 { err = &labelError{s, "A4"} } } return s, err } func normalize(p *Profile, s string) (mapped string, isBidi bool, err error) { // TODO: consider first doing a quick check to see if any of these checks // need to be done. This will make it slower in the general case, but // faster in the common case. mapped = norm.NFC.String(s) isBidi = bidirule.DirectionString(mapped) == bidi.RightToLeft return mapped, isBidi, nil } func validateRegistration(p *Profile, s string) (idem string, bidi bool, err error) { // TODO: filter need for normalization in loop below. if !norm.NFC.IsNormalString(s) { return s, false, &labelError{s, "V1"} } for i := 0; i < len(s); { v, sz := trie.lookupString(s[i:]) if sz == 0 { return s, bidi, runeError(utf8.RuneError) } bidi = bidi || info(v).isBidi(s[i:]) // Copy bytes not copied so far. switch p.simplify(info(v).category()) { // TODO: handle the NV8 defined in the Unicode idna data set to allow // for strict conformance to IDNA2008. case valid, deviation: case disallowed, mapped, unknown, ignored: r, _ := utf8.DecodeRuneInString(s[i:]) return s, bidi, runeError(r) } i += sz } return s, bidi, nil } func (c info) isBidi(s string) bool { if !c.isMapped() { return c&attributesMask == rtl } // TODO: also store bidi info for mapped data. This is possible, but a bit // cumbersome and not for the common case. p, _ := bidi.LookupString(s) switch p.Class() { case bidi.R, bidi.AL, bidi.AN: return true } return false } func validateAndMap(p *Profile, s string) (vm string, bidi bool, err error) { var ( b []byte k int ) // combinedInfoBits contains the or-ed bits of all runes. We use this // to derive the mayNeedNorm bit later. This may trigger normalization // overeagerly, but it will not do so in the common case. The end result // is another 10% saving on BenchmarkProfile for the common case. var combinedInfoBits info for i := 0; i < len(s); { v, sz := trie.lookupString(s[i:]) if sz == 0 { b = append(b, s[k:i]...) b = append(b, "\ufffd"...) k = len(s) if err == nil { err = runeError(utf8.RuneError) } break } combinedInfoBits |= info(v) bidi = bidi || info(v).isBidi(s[i:]) start := i i += sz // Copy bytes not copied so far. switch p.simplify(info(v).category()) { case valid: continue case disallowed: if err == nil { r, _ := utf8.DecodeRuneInString(s[start:]) err = runeError(r) } continue case mapped, deviation: b = append(b, s[k:start]...) b = info(v).appendMapping(b, s[start:i]) case ignored: b = append(b, s[k:start]...) // drop the rune case unknown: b = append(b, s[k:start]...) b = append(b, "\ufffd"...) } k = i } if k == 0 { // No changes so far. if combinedInfoBits&mayNeedNorm != 0 { s = norm.NFC.String(s) } } else { b = append(b, s[k:]...) if norm.NFC.QuickSpan(b) != len(b) { b = norm.NFC.Bytes(b) } // TODO: the punycode converters require strings as input. s = string(b) } return s, bidi, err } // A labelIter allows iterating over domain name labels. type labelIter struct { orig string slice []string curStart int curEnd int i int } func (l *labelIter) reset() { l.curStart = 0 l.curEnd = 0 l.i = 0 } func (l *labelIter) done() bool { return l.curStart >= len(l.orig) } func (l *labelIter) result() string { if l.slice != nil { return strings.Join(l.slice, ".") } return l.orig } func (l *labelIter) label() string { if l.slice != nil { return l.slice[l.i] } p := strings.IndexByte(l.orig[l.curStart:], '.') l.curEnd = l.curStart + p if p == -1 { l.curEnd = len(l.orig) } return l.orig[l.curStart:l.curEnd] } // next sets the value to the next label. It skips the last label if it is empty. func (l *labelIter) next() { l.i++ if l.slice != nil { if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" { l.curStart = len(l.orig) } } else { l.curStart = l.curEnd + 1 if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' { l.curStart = len(l.orig) } } } func (l *labelIter) set(s string) { if l.slice == nil { l.slice = strings.Split(l.orig, ".") } l.slice[l.i] = s } // acePrefix is the ASCII Compatible Encoding prefix. const acePrefix = "xn--" func (p *Profile) simplify(cat category) category { switch cat { case disallowedSTD3Mapped: if p.useSTD3Rules { cat = disallowed } else { cat = mapped } case disallowedSTD3Valid: if p.useSTD3Rules { cat = disallowed } else { cat = valid } case deviation: if !p.transitional { cat = valid } case validNV8, validXV8: // TODO: handle V2008 cat = valid } return cat } func validateFromPunycode(p *Profile, s string) error { if !norm.NFC.IsNormalString(s) { return &labelError{s, "V1"} } // TODO: detect whether string may have to be normalized in the following // loop. for i := 0; i < len(s); { v, sz := trie.lookupString(s[i:]) if sz == 0 { return runeError(utf8.RuneError) } if c := p.simplify(info(v).category()); c != valid && c != deviation { return &labelError{s, "V6"} } i += sz } return nil } const ( zwnj = "\u200c" zwj = "\u200d" ) type joinState int8 const ( stateStart joinState = iota stateVirama stateBefore stateBeforeVirama stateAfter stateFAIL ) var joinStates = [][numJoinTypes]joinState{ stateStart: { joiningL: stateBefore, joiningD: stateBefore, joinZWNJ: stateFAIL, joinZWJ: stateFAIL, joinVirama: stateVirama, }, stateVirama: { joiningL: stateBefore, joiningD: stateBefore, }, stateBefore: { joiningL: stateBefore, joiningD: stateBefore, joiningT: stateBefore, joinZWNJ: stateAfter, joinZWJ: stateFAIL, joinVirama: stateBeforeVirama, }, stateBeforeVirama: { joiningL: stateBefore, joiningD: stateBefore, joiningT: stateBefore, }, stateAfter: { joiningL: stateFAIL, joiningD: stateBefore, joiningT: stateAfter, joiningR: stateStart, joinZWNJ: stateFAIL, joinZWJ: stateFAIL, joinVirama: stateAfter, // no-op as we can't accept joiners here }, stateFAIL: { 0: stateFAIL, joiningL: stateFAIL, joiningD: stateFAIL, joiningT: stateFAIL, joiningR: stateFAIL, joinZWNJ: stateFAIL, joinZWJ: stateFAIL, joinVirama: stateFAIL, }, } // validateLabel validates the criteria from Section 4.1. Item 1, 4, and 6 are // already implicitly satisfied by the overall implementation. func (p *Profile) validateLabel(s string) (err error) { if s == "" { if p.verifyDNSLength { return &labelError{s, "A4"} } return nil } if !p.validateLabels { return nil } trie := p.trie // p.validateLabels is only set if trie is set. if len(s) > 4 && s[2] == '-' && s[3] == '-' { return &labelError{s, "V2"} } if s[0] == '-' || s[len(s)-1] == '-' { return &labelError{s, "V3"} } // TODO: merge the use of this in the trie. v, sz := trie.lookupString(s) x := info(v) if x.isModifier() { return &labelError{s, "V5"} } // Quickly return in the absence of zero-width (non) joiners. if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 { return nil } st := stateStart for i := 0; ; { jt := x.joinType() if s[i:i+sz] == zwj { jt = joinZWJ } else if s[i:i+sz] == zwnj { jt = joinZWNJ } st = joinStates[st][jt] if x.isViramaModifier() { st = joinStates[st][joinVirama] } if i += sz; i == len(s) { break } v, sz = trie.lookupString(s[i:]) x = info(v) } if st == stateFAIL || st == stateAfter { return &labelError{s, "C"} } return nil } func ascii(s string) bool { for i := 0; i < len(s); i++ { if s[i] >= utf8.RuneSelf { return false } } return true }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.deltaspike.core.api.literal; import javax.enterprise.util.AnnotationLiteral; import org.apache.deltaspike.core.api.lifecycle.Initialized; /** * Annotation literal for {@link Initialized}. */ public class InitializedLiteral extends AnnotationLiteral<Initialized> implements Initialized { public static final Initialized INSTANCE = new InitializedLiteral(); private static final long serialVersionUID = 2392444150652655120L; }
/* chi_squared_test.hpp header file * * Copyright Steven Watanabe 2010 * 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) * * $Id: chi_squared_test.hpp 71018 2011-04-05 21:27:52Z steven_watanabe $ * */ #ifndef BOOST_RANDOM_TEST_CHI_SQUARED_TEST_HPP_INCLUDED #define BOOST_RANDOM_TEST_CHI_SQUARED_TEST_HPP_INCLUDED #include <vector> #include <boost/math/special_functions/pow.hpp> #include <boost/math/distributions/chi_squared.hpp> // This only works for discrete distributions with fixed // upper and lower bounds. template<class IntType> struct chi_squared_collector { static const IntType cutoff = 5; chi_squared_collector() : chi_squared(0), variables(0), prev_actual(0), prev_expected(0), current_actual(0), current_expected(0) {} void operator()(IntType actual, double expected) { current_actual += actual; current_expected += expected; if(current_expected >= cutoff) { if(prev_expected != 0) { update(prev_actual, prev_expected); } prev_actual = current_actual; prev_expected = current_expected; current_actual = 0; current_expected = 0; } } void update(IntType actual, double expected) { chi_squared += boost::math::pow<2>(actual - expected) / expected; ++variables; } double cdf() { if(prev_expected != 0) { update(prev_actual + current_actual, prev_expected + current_expected); prev_actual = 0; prev_expected = 0; current_actual = 0; current_expected = 0; } if(variables <= 1) { return 0; } else { return boost::math::cdf(boost::math::chi_squared(variables - 1), chi_squared); } } double chi_squared; std::size_t variables; IntType prev_actual; double prev_expected; IntType current_actual; double current_expected; }; template<class IntType> double chi_squared_test(const std::vector<IntType>& results, const std::vector<double>& probabilities, IntType iterations) { chi_squared_collector<IntType> calc; for(std::size_t i = 0; i < results.size(); ++i) { calc(results[i], iterations * probabilities[i]); } return calc.cdf(); } #endif
package com.mossle.ext; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.MultipartResolver; public class MultipartHandler { private static Logger logger = LoggerFactory .getLogger(MultipartHandler.class); private MultipartResolver multipartResolver; private MultipartHttpServletRequest multipartHttpServletRequest = null; private MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<String, String>(); private MultiValueMap<String, MultipartFile> multiFileMap; public MultipartHandler(MultipartResolver multipartResolver) { this.multipartResolver = multipartResolver; } public void handle(HttpServletRequest request) { if (request instanceof MultipartHttpServletRequest) { logger.debug("force cast to MultipartHttpServletRequest"); MultipartHttpServletRequest req = (MultipartHttpServletRequest) request; this.multiFileMap = req.getMultiFileMap(); logger.debug("multiFileMap : {}", multiFileMap); this.handleMultiValueMap(req); logger.debug("multiValueMap : {}", multiValueMap); return; } if (multipartResolver.isMultipart(request)) { logger.debug("is multipart : {}", multipartResolver.isMultipart(request)); this.multipartHttpServletRequest = multipartResolver .resolveMultipart(request); logger.debug("multipartHttpServletRequest : {}", multipartHttpServletRequest); this.multiFileMap = multipartHttpServletRequest.getMultiFileMap(); logger.debug("multiFileMap : {}", multiFileMap); this.handleMultiValueMap(multipartHttpServletRequest); logger.debug("multiValueMap : {}", multiValueMap); } else { this.handleMultiValueMap(request); logger.debug("multiValueMap : {}", multiValueMap); } } public void clear() { if (multipartHttpServletRequest == null) { return; } multipartResolver.cleanupMultipart(multipartHttpServletRequest); } public void handleMultiValueMap(HttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); for (String value : entry.getValue()) { multiValueMap.add(key, value); } } } public MultiValueMap<String, String> getMultiValueMap() { return multiValueMap; } public MultiValueMap<String, MultipartFile> getMultiFileMap() { return multiFileMap; } }
// Copyright 2004-present Facebook. All Rights Reserved. #pragma once #include <atomic> #include <functional> #include <map> #include <vector> #include <folly/dynamic.h> #include "Executor.h" #include "ExecutorToken.h" #include "JSModulesUnbundle.h" #include "MessageQueueThread.h" #include "MethodCall.h" #include "NativeModule.h" #include "Value.h" namespace folly { struct dynamic; } namespace facebook { namespace react { struct InstanceCallback; class ModuleRegistry; class ExecutorRegistration { public: ExecutorRegistration( std::unique_ptr<JSExecutor> executor, std::shared_ptr<MessageQueueThread> executorMessageQueueThread) : executor_(std::move(executor)), messageQueueThread_(executorMessageQueueThread) {} std::unique_ptr<JSExecutor> executor_; std::shared_ptr<MessageQueueThread> messageQueueThread_; }; class JsToNativeBridge; // This class manages calls from native code to JS. It also manages // executors and their threads. This part is used by both bridges for // now, but further refactorings should separate the bridges more // fully #11247981. class NativeToJsBridge { public: friend class JsToNativeBridge; /** * This must be called on the main JS thread. */ NativeToJsBridge( JSExecutorFactory* jsExecutorFactory, std::shared_ptr<ModuleRegistry> registry, std::shared_ptr<MessageQueueThread> jsQueue, std::unique_ptr<MessageQueueThread> nativeQueue, std::shared_ptr<InstanceCallback> callback); virtual ~NativeToJsBridge(); /** * Executes a function with the module ID and method ID and any additional * arguments in JS. */ void callFunction( ExecutorToken executorToken, std::string&& module, std::string&& method, folly::dynamic&& args); /** * Invokes a callback with the cbID, and optional additional arguments in JS. */ void invokeCallback(ExecutorToken executorToken, double callbackId, folly::dynamic&& args); /** * Starts the JS application from an "bundle", i.e. a JavaScript file that * contains code for all modules and a runtime that resolves and * executes modules. */ void loadApplicationScript(std::unique_ptr<const JSBigString> script, std::string sourceURL); /** * Similar to loading a "bundle", but instead of passing js source this method accepts * path to a directory containing files prepared for particular JSExecutor. */ void loadOptimizedApplicationScript(std::string bundlePath, std::string sourceURL, int flags); /** * An "unbundle" is a backend that stores and injects JavaScript modules as * individual scripts, rather than bundling all of them into a single scrupt. * * Loading an unbundle means setting the storage backend and executing the * startup script. */ void loadApplicationUnbundle( std::unique_ptr<JSModulesUnbundle> unbundle, std::unique_ptr<const JSBigString> startupCode, std::string sourceURL); void setGlobalVariable(std::string propName, std::unique_ptr<const JSBigString> jsonValue); void* getJavaScriptContext(); bool supportsProfiling(); void startProfiler(const std::string& title); void stopProfiler(const std::string& title, const std::string& filename); void handleMemoryPressureUiHidden(); void handleMemoryPressureModerate(); void handleMemoryPressureCritical(); /** * Returns the ExecutorToken corresponding to the main JSExecutor. */ ExecutorToken getMainExecutorToken() const; /** * Synchronously tears down the bridge and the main executor. */ void destroy(); private: /** * Registers the given JSExecutor which runs on the given MessageQueueThread * with the NativeToJsBridge. Part of this registration is transfering * ownership of this JSExecutor to the NativeToJsBridge for the duration of * the registration. * * Returns a ExecutorToken which can be used to refer to this JSExecutor * in the NativeToJsBridge. */ ExecutorToken registerExecutor( ExecutorToken token, std::unique_ptr<JSExecutor> executor, std::shared_ptr<MessageQueueThread> executorMessageQueueThread); /** * Unregisters a JSExecutor that was previously registered with this NativeToJsBridge * using registerExecutor. */ std::unique_ptr<JSExecutor> unregisterExecutor(JSExecutor& executorToken); void runOnExecutorQueue(ExecutorToken token, std::function<void(JSExecutor*)> task); // This is used to avoid a race condition where a proxyCallback gets queued // after ~NativeToJsBridge(), on the same thread. In that case, the callback // will try to run the task on m_callback which will have been destroyed // within ~NativeToJsBridge(), thus causing a SIGSEGV. std::shared_ptr<bool> m_destroyed; JSExecutor* m_mainExecutor; ExecutorToken m_mainExecutorToken; std::shared_ptr<JsToNativeBridge> m_delegate; std::unordered_map<JSExecutor*, ExecutorToken> m_executorTokenMap; std::unordered_map<ExecutorToken, ExecutorRegistration> m_executorMap; std::mutex m_registrationMutex; #ifdef WITH_FBSYSTRACE std::atomic_uint_least32_t m_systraceCookie = ATOMIC_VAR_INIT(); #endif MessageQueueThread* getMessageQueueThread(const ExecutorToken& executorToken); JSExecutor* getExecutor(const ExecutorToken& executorToken); ExecutorToken getTokenForExecutor(JSExecutor& executor); }; } }
#include <stdlib.h> #include <string.h> #ifndef WIN32 #include "config.h" #endif #ifdef ENABLE_NLS #include <libintl.h> #endif #define _ISOC9X_SOURCE 1 #define _ISOC99_SOURCE 1 #define __USE_ISOC99 1 #define __USE_ISOC9X 1 #include <math.h> #include "ladspa.h" #ifdef WIN32 #define _WINDOWS_DLL_EXPORT_ __declspec(dllexport) int bIsFirstTime = 1; static void __attribute__((constructor)) swh_init(); // forward declaration #else #define _WINDOWS_DLL_EXPORT_ #endif #define WAVETERRAIN_XB 0 #define WAVETERRAIN_YB 1 #define WAVETERRAIN_ZB 2 static LADSPA_Descriptor *waveTerrainDescriptor = NULL; typedef struct { LADSPA_Data *xb; LADSPA_Data *yb; LADSPA_Data *zb; LADSPA_Data run_adding_gain; } WaveTerrain; _WINDOWS_DLL_EXPORT_ const LADSPA_Descriptor *ladspa_descriptor(unsigned long index) { #ifdef WIN32 if (bIsFirstTime) { swh_init(); bIsFirstTime = 0; } #endif switch (index) { case 0: return waveTerrainDescriptor; default: return NULL; } } static void cleanupWaveTerrain(LADSPA_Handle instance) { free(instance); } static void connectPortWaveTerrain( LADSPA_Handle instance, unsigned long port, LADSPA_Data *data) { WaveTerrain *plugin; plugin = (WaveTerrain *)instance; switch (port) { case WAVETERRAIN_XB: plugin->xb = data; break; case WAVETERRAIN_YB: plugin->yb = data; break; case WAVETERRAIN_ZB: plugin->zb = data; break; } } static LADSPA_Handle instantiateWaveTerrain( const LADSPA_Descriptor *descriptor, unsigned long s_rate) { WaveTerrain *plugin_data = (WaveTerrain *)calloc(1, sizeof(WaveTerrain)); plugin_data->run_adding_gain = 1.0f; return (LADSPA_Handle)plugin_data; } #undef buffer_write #undef RUN_ADDING #undef RUN_REPLACING #define buffer_write(b, v) (b = v) #define RUN_ADDING 0 #define RUN_REPLACING 1 static void runWaveTerrain(LADSPA_Handle instance, unsigned long sample_count) { WaveTerrain *plugin_data = (WaveTerrain *)instance; /* x (array of floats of length sample_count) */ const LADSPA_Data * const xb = plugin_data->xb; /* y (array of floats of length sample_count) */ const LADSPA_Data * const yb = plugin_data->yb; /* z (array of floats of length sample_count) */ LADSPA_Data * const zb = plugin_data->zb; #line 18 "wave_terrain_1412.xml" unsigned long pos; float x, y; for (pos = 0; pos < sample_count; pos++) { x = xb[pos]; y = yb[pos]; buffer_write(zb[pos], (x - y) * (x - 1.0f) * (x + 1.0f) * (y - 1.0f) * (y + 1.0f) ); } } #undef buffer_write #undef RUN_ADDING #undef RUN_REPLACING #define buffer_write(b, v) (b += (v) * run_adding_gain) #define RUN_ADDING 1 #define RUN_REPLACING 0 static void setRunAddingGainWaveTerrain(LADSPA_Handle instance, LADSPA_Data gain) { ((WaveTerrain *)instance)->run_adding_gain = gain; } static void runAddingWaveTerrain(LADSPA_Handle instance, unsigned long sample_count) { WaveTerrain *plugin_data = (WaveTerrain *)instance; LADSPA_Data run_adding_gain = plugin_data->run_adding_gain; /* x (array of floats of length sample_count) */ const LADSPA_Data * const xb = plugin_data->xb; /* y (array of floats of length sample_count) */ const LADSPA_Data * const yb = plugin_data->yb; /* z (array of floats of length sample_count) */ LADSPA_Data * const zb = plugin_data->zb; #line 18 "wave_terrain_1412.xml" unsigned long pos; float x, y; for (pos = 0; pos < sample_count; pos++) { x = xb[pos]; y = yb[pos]; buffer_write(zb[pos], (x - y) * (x - 1.0f) * (x + 1.0f) * (y - 1.0f) * (y + 1.0f) ); } } static void __attribute__((constructor)) swh_init() { char **port_names; LADSPA_PortDescriptor *port_descriptors; LADSPA_PortRangeHint *port_range_hints; #ifdef ENABLE_NLS #define D_(s) dgettext(PACKAGE, s) bindtextdomain(PACKAGE, PACKAGE_LOCALE_DIR); #else #define D_(s) (s) #endif waveTerrainDescriptor = (LADSPA_Descriptor *)malloc(sizeof(LADSPA_Descriptor)); if (waveTerrainDescriptor) { waveTerrainDescriptor->UniqueID = 1412; waveTerrainDescriptor->Label = "waveTerrain"; waveTerrainDescriptor->Properties = LADSPA_PROPERTY_HARD_RT_CAPABLE; waveTerrainDescriptor->Name = D_("Wave Terrain Oscillator"); waveTerrainDescriptor->Maker = "Steve Harris <steve@plugin.org.uk>"; waveTerrainDescriptor->Copyright = "GPL"; waveTerrainDescriptor->PortCount = 3; port_descriptors = (LADSPA_PortDescriptor *)calloc(3, sizeof(LADSPA_PortDescriptor)); waveTerrainDescriptor->PortDescriptors = (const LADSPA_PortDescriptor *)port_descriptors; port_range_hints = (LADSPA_PortRangeHint *)calloc(3, sizeof(LADSPA_PortRangeHint)); waveTerrainDescriptor->PortRangeHints = (const LADSPA_PortRangeHint *)port_range_hints; port_names = (char **)calloc(3, sizeof(char*)); waveTerrainDescriptor->PortNames = (const char **)port_names; /* Parameters for x */ port_descriptors[WAVETERRAIN_XB] = LADSPA_PORT_INPUT | LADSPA_PORT_AUDIO; port_names[WAVETERRAIN_XB] = D_("x"); port_range_hints[WAVETERRAIN_XB].HintDescriptor = 0; /* Parameters for y */ port_descriptors[WAVETERRAIN_YB] = LADSPA_PORT_INPUT | LADSPA_PORT_AUDIO; port_names[WAVETERRAIN_YB] = D_("y"); port_range_hints[WAVETERRAIN_YB].HintDescriptor = 0; /* Parameters for z */ port_descriptors[WAVETERRAIN_ZB] = LADSPA_PORT_OUTPUT | LADSPA_PORT_AUDIO; port_names[WAVETERRAIN_ZB] = D_("z"); port_range_hints[WAVETERRAIN_ZB].HintDescriptor = 0; waveTerrainDescriptor->activate = NULL; waveTerrainDescriptor->cleanup = cleanupWaveTerrain; waveTerrainDescriptor->connect_port = connectPortWaveTerrain; waveTerrainDescriptor->deactivate = NULL; waveTerrainDescriptor->instantiate = instantiateWaveTerrain; waveTerrainDescriptor->run = runWaveTerrain; waveTerrainDescriptor->run_adding = runAddingWaveTerrain; waveTerrainDescriptor->set_run_adding_gain = setRunAddingGainWaveTerrain; } } static void __attribute__((destructor)) swh_fini() { if (waveTerrainDescriptor) { free((LADSPA_PortDescriptor *)waveTerrainDescriptor->PortDescriptors); free((char **)waveTerrainDescriptor->PortNames); free((LADSPA_PortRangeHint *)waveTerrainDescriptor->PortRangeHints); free(waveTerrainDescriptor); } waveTerrainDescriptor = NULL; }
<?php /** * Отображение для environment: * * @category YupeView * @package yupe * @author Yupe Team <team@yupe.ru> * @license https://github.com/yupe/yupe/blob/master/LICENSE BSD * @link http://yupe.ru **/ ?> <?php if (!$data['result']) : { ?> <div class="alert alert-danger"> <b><?php echo Yii::t('InstallModule.install', 'Install can\'t be continued. Please check errors!'); ?></b> </div> <?php } endif; ?> <?php $this->widget('install.widgets.GetHelpWidget'); ?> <div class="alert alert-info"> <p><?php echo Yii::t( 'InstallModule.install', 'On this step Yupe checks access right for needed directories.' ); ?></p> <p><?php echo Yii::t( 'InstallModule.install', 'To continue installation you need to repair error was occured.' ); ?></p> </div> <table class="table table-striped"> <tr> <th><?php echo Yii::t('InstallModule.install', 'Value'); ?></th> <th><?php echo Yii::t('InstallModule.install', 'Result'); ?></th> <th><?php echo Yii::t('InstallModule.install', 'Comments'); ?></th> </tr> <?php foreach ($data['requirements'] as $requirement): { ?> <tr> <td style="width:200px;"><?php echo $requirement[0]; ?></td> <td> <?php $this->widget( 'bootstrap.widgets.TbLabel', [ 'context' => $requirement[1] ? 'success' : 'danger', 'label' => $requirement[1] ? 'ОК' : Yii::t('InstallModule.install', 'Error'), ] ); ?> </td> <td><?php echo $requirement[2]; ?></td> </tr> <?php } endforeach; ?> </table> <br/> <?php echo CHtml::link( Yii::t('InstallModule.install', '< Back'), ['/install/default/index'], ['class' => 'btn btn-primary'] ); ?> <?php if ($data['result'] !== false) { echo CHtml::link( Yii::t('InstallModule.install', 'Continue >'), ['/install/default/requirements'], ['class' => 'btn btn-primary'] ); } else { echo CHtml::link( Yii::t('InstallModule.install', 'Refresh'), ['/install/default/environment'], ['class' => 'btn btn-primary'] ); } ?>
<?php /* * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ namespace ProxyManagerTest\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator; use PHPUnit_Framework_TestCase; use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\InterceptedMethod; use Zend\Code\Reflection\MethodReflection; /** * Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\InterceptedMethod} * * @author Marco Pivetta <ocramius@gmail.com> * @license MIT * * @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\InterceptedMethod */ class InterceptedMethodTest extends PHPUnit_Framework_TestCase { public function testBodyStructure() { $prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator'); $suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator'); $prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre')); $suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post')); $method = InterceptedMethod::generateMethod( new MethodReflection('ProxyManagerTestAsset\\BaseClass', 'publicByReferenceParameterMethod'), $prefixInterceptors, $suffixInterceptors ); $this->assertInstanceOf('ProxyManager\\Generator\\MethodGenerator', $method); $this->assertSame('publicByReferenceParameterMethod', $method->getName()); $this->assertCount(2, $method->getParameters()); $this->assertGreaterThan( 0, strpos( $method->getBody(), '$returnValue = parent::publicByReferenceParameterMethod($param, $byRefParam);' ) ); } }
// RUN: mkdir -p %T/move-type-alias // RUN: cp %S/Inputs/type_alias.h %T/move-type-alias/type_alias.h // RUN: echo '#include "type_alias.h"' > %T/move-type-alias/type_alias.cpp // RUN: cd %T/move-type-alias // // ----------------------------------------------------------------------------- // Test moving typedef declarations. // ----------------------------------------------------------------------------- // RUN: clang-move -names="Int1" -new_cc=%T/move-type-alias/new_test.cpp -new_header=%T/move-type-alias/new_test.h -old_cc=%T/move-type-alias/type_alias.cpp -old_header=%T/move-type-alias/type_alias.h %T/move-type-alias/type_alias.cpp -- -std=c++11 // RUN: FileCheck -input-file=%T/move-type-alias/new_test.h -check-prefix=CHECK-NEW-TEST-H-CASE1 %s // RUN: FileCheck -input-file=%T/move-type-alias/type_alias.h -check-prefix=CHECK-OLD-TEST-H-CASE1 %s // CHECK-NEW-TEST-H-CASE1: typedef int Int1; // CHECK-OLD-TEST-H-CASE1-NOT: typedef int Int1; // ----------------------------------------------------------------------------- // Test moving type alias declarations. // ----------------------------------------------------------------------------- // RUN: cp %S/Inputs/type_alias.h %T/move-type-alias/type_alias.h // RUN: echo '#include "type_alias.h"' > %T/move-type-alias/type_alias.cpp // RUN: clang-move -names="Int2" -new_cc=%T/move-type-alias/new_test.cpp -new_header=%T/move-type-alias/new_test.h -old_cc=%T/move-type-alias/type_alias.cpp -old_header=%T/move-type-alias/type_alias.h %T/move-type-alias/type_alias.cpp -- -std=c++11 // RUN: FileCheck -input-file=%T/move-type-alias/new_test.h -check-prefix=CHECK-NEW-TEST-H-CASE2 %s // RUN: FileCheck -input-file=%T/move-type-alias/type_alias.h -check-prefix=CHECK-OLD-TEST-H-CASE2 %s // CHECK-NEW-TEST-H-CASE2: using Int2 = int; // CHECK-OLD-TEST-H-CASE2-NOT: using Int2 = int; // ----------------------------------------------------------------------------- // Test moving template type alias declarations. // ----------------------------------------------------------------------------- // RUN: cp %S/Inputs/type_alias.h %T/move-type-alias/type_alias.h // RUN: echo '#include "type_alias.h"' > %T/move-type-alias/type_alias.cpp // RUN: clang-move -names="B" -new_cc=%T/move-type-alias/new_test.cpp -new_header=%T/move-type-alias/new_test.h -old_cc=%T/move-type-alias/type_alias.cpp -old_header=%T/move-type-alias/type_alias.h %T/move-type-alias/type_alias.cpp -- -std=c++11 // RUN: FileCheck -input-file=%T/move-type-alias/new_test.h -check-prefix=CHECK-OLD-TEST-H-CASE3 %s // CHECK-NEW-TEST-H-CASE3: template<class T> using B = A<T>; // CHECK-OLD-TEST-H-CASE3-NOT: template<class T> using B = A<T>; // ----------------------------------------------------------------------------- // Test not moving class-insided typedef declarations. // ----------------------------------------------------------------------------- // RUN: cp %S/Inputs/type_alias.h %T/move-type-alias/type_alias.h // RUN: echo '#include "type_alias.h"' > %T/move-type-alias/type_alias.cpp // RUN: clang-move -names="C::Int3" -new_cc=%T/move-type-alias/new_test.cpp -new_header=%T/move-type-alias/new_test.h -old_cc=%T/move-type-alias/type_alias.cpp -old_header=%T/move-type-alias/type_alias.h %T/move-type-alias/type_alias.cpp -- -std=c++11 // RUN: FileCheck -input-file=%T/move-type-alias/new_test.h -allow-empty -check-prefix=CHECK-EMPTY %s // CHECK-EMPTY: {{^}}{{$}}
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_WEBUI_PROFILER_UI_H_ #define CHROME_BROWSER_UI_WEBUI_PROFILER_UI_H_ #include "base/memory/weak_ptr.h" #include "components/metrics/profiler/tracking_synchronizer_observer.h" #include "content/public/browser/web_ui_controller.h" // The C++ back-end for the chrome://profiler webui page. class ProfilerUI : public content::WebUIController, public metrics::TrackingSynchronizerObserver { public: explicit ProfilerUI(content::WebUI* web_ui); ~ProfilerUI() override; // Get the tracking data from TrackingSynchronizer. void GetData(); private: // TrackingSynchronizerObserver: void ReceivedProfilerData( const metrics::ProfilerDataAttributes& attributes, const tracked_objects::ProcessDataPhaseSnapshot& process_data_phase, const metrics::ProfilerEvents& past_events) override; // Used to get |weak_ptr_| to self on the UI thread. base::WeakPtrFactory<ProfilerUI> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ProfilerUI); }; #endif // CHROME_BROWSER_UI_WEBUI_PROFILER_UI_H_
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Generator for unique element IDs. * */ goog.provide('goog.ui.IdGenerator'); /** * Creates a new id generator. * @constructor */ goog.ui.IdGenerator = function() { }; goog.addSingletonGetter(goog.ui.IdGenerator); /** * Next unique ID to use * @type {number} * @private */ goog.ui.IdGenerator.prototype.nextId_ = 0; /** * Gets the next unique ID. * @return {string} The next unique identifier. */ goog.ui.IdGenerator.prototype.getNextUniqueId = function() { return ':' + (this.nextId_++).toString(36); }; /** * Default instance for id generation. Done as an instance instead of statics * so it's possible to inject a mock for unit testing purposes. * @type {goog.ui.IdGenerator} * @deprecated Use goog.ui.IdGenerator.getInstance() instead and do not refer * to goog.ui.IdGenerator.instance anymore. */ goog.ui.IdGenerator.instance = goog.ui.IdGenerator.getInstance();
<?php /** * Locale data for 'ar_MA'. * * This file is automatically generated by yiic cldr command. * * Copyright © 1991-2007 Unicode, Inc. All rights reserved. * Distributed under the Terms of Use in http://www.unicode.org/copyright.html. * * @copyright 2008-2013 Yii Software LLC (http://www.yiiframework.com/license/) */ return array ( 'version' => '6177', 'numberSymbols' => array ( 'alias' => '', 'decimal' => ',', 'group' => '.', 'list' => ';', 'percentSign' => '%', 'plusSign' => '+', 'minusSign' => '-', 'exponential' => 'E', 'perMille' => '‰', 'infinity' => '∞', 'nan' => 'NaN', ), 'decimalFormat' => '#0.###;#0.###-', 'scientificFormat' => '#E0', 'percentFormat' => '#,##0%', 'currencyFormat' => '¤ #0.00;¤ #0.00-', 'currencySymbols' => array ( 'AUD' => 'AU$', 'BRL' => 'ر.ب.‏', 'CAD' => 'CA$', 'CNY' => 'ي.ص', 'EUR' => '€', 'GBP' => '£', 'HKD' => 'HK$', 'ILS' => '₪', 'INR' => 'ر.ه.‏', 'JPY' => 'JP¥', 'KRW' => '₩', 'MXN' => 'MX$', 'NZD' => 'NZ$', 'THB' => '฿', 'TWD' => 'NT$', 'USD' => 'US$', 'VND' => '₫', 'XAF' => 'ف.ا.‏', 'XCD' => 'EC$', 'XOF' => 'CFA', 'XPF' => 'CFPF', 'AED' => 'د.إ.‏', 'BHD' => 'د.ب.‏', 'DZD' => 'د.ج.‏', 'EGP' => 'ج.م.‏', 'IQD' => 'د.ع.‏', 'JOD' => 'د.أ.‏', 'KMF' => 'ف.ج.ق.‏', 'KWD' => 'د.ك.‏', 'LBP' => 'ل.ل.‏', 'LYD' => 'د.ل.‏', 'MAD' => 'د.م.‏', 'MRO' => 'أ.م.‏', 'OMR' => 'ر.ع.‏', 'QAR' => 'ر.ق.‏', 'RUB' => 'ر.ر.‏', 'SAR' => 'ر.س.‏', 'SDD' => 'د.س.‏', 'SDP' => 'ج.س.‏', 'SYP' => 'ل.س.‏', 'TND' => 'د.ت.‏', 'XXX' => '***', 'YER' => 'ر.ي.‏', ), 'monthNames' => array ( 'wide' => array ( 1 => 'يناير', 2 => 'فبراير', 3 => 'مارس', 4 => 'أبريل', 5 => 'مايو', 6 => 'يونيو', 7 => 'يوليو', 8 => 'أغسطس', 9 => 'سبتمبر', 10 => 'أكتوبر', 11 => 'نوفمبر', 12 => 'ديسمبر', ), 'abbreviated' => array ( 1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9', 10 => '10', 11 => '11', 12 => '12', ), ), 'monthNamesSA' => array ( 'narrow' => array ( 1 => 'ي', 2 => 'ف', 3 => 'م', 4 => 'أ', 5 => 'و', 6 => 'ن', 7 => 'ل', 8 => 'غ', 9 => 'س', 10 => 'ك', 11 => 'ب', 12 => 'د', ), ), 'weekDayNames' => array ( 'wide' => array ( 0 => 'الأحد', 1 => 'الاثنين', 2 => 'الثلاثاء', 3 => 'الأربعاء', 4 => 'الخميس', 5 => 'الجمعة', 6 => 'السبت', ), 'abbreviated' => array ( 0 => 'الأحد', 1 => 'الاثنين', 2 => 'الثلاثاء', 3 => 'الأربعاء', 4 => 'الخميس', 5 => 'الجمعة', 6 => 'السبت', ), ), 'weekDayNamesSA' => array ( 'narrow' => array ( 0 => 'ح', 1 => 'ن', 2 => 'ث', 3 => 'ر', 4 => 'خ', 5 => 'ج', 6 => 'س', ), 'abbreviated' => array ( 0 => 'الأحد', 1 => 'الاثنين', 2 => 'الثلاثاء', 3 => 'الأربعاء', 4 => 'الخميس', 5 => 'الجمعة', 6 => 'السبت', ), 'wide' => array ( 1 => 'الاثنين', ), ), 'eraNames' => array ( 'abbreviated' => array ( 0 => 'ق.م', 1 => 'م', ), 'wide' => array ( 0 => 'قبل الميلاد', 1 => 'ميلادي', ), 'narrow' => array ( 0 => 'ق.م', 1 => 'م', ), ), 'dateFormats' => array ( 'full' => 'EEEE، d MMMM، y', 'long' => 'd MMMM، y', 'medium' => 'yyyy/MM/dd', 'short' => 'yyyy/M/d', ), 'timeFormats' => array ( 'full' => 'zzzz h:mm:ss a', 'long' => 'z h:mm:ss a', 'medium' => 'h:mm:ss a', 'short' => 'h:mm a', ), 'dateTimeFormat' => '{1} {0}', 'amName' => 'ص', 'pmName' => 'م', 'orientation' => 'rtl', 'languages' => array ( 'aa' => 'الأفارية', 'ab' => 'الأبخازية', 'ace' => 'الأتشينيزية', 'ach' => 'الأكولية', 'ada' => 'الأدانجمية', 'ady' => 'الأديجه', 'ae' => 'الأفستية', 'af' => 'الأفريقية', 'afa' => 'لغة أفرو آسيوية', 'afh' => 'الأفريهيلية', 'ain' => 'الآينوية', 'ak' => 'الأكانية', 'akk' => 'الأكادية', 'ale' => 'الأليوتية', 'alg' => 'اللغات الأمريكية الهندية', 'alt' => 'الألطائية الجنوبية', 'am' => 'الأمهرية', 'an' => 'الأراجونية', 'ang' => 'الإنجليزية القديمة', 'anp' => 'الأنجيكا', 'apa' => 'اللغات الأباتشية', 'ar' => 'العربية', 'arc' => 'الآرامية', 'arn' => 'الأروكانية', 'arp' => 'الأراباهو', 'art' => 'الصناعية - أخرى', 'arw' => 'الأراواكية', 'as' => 'الأسامية', 'ast' => 'الأسترية', 'ath' => 'اللغة الأزباسكانية', 'aus' => 'اللغة الأسترالية', 'av' => 'الأفاريكية', 'awa' => 'الأوادية', 'ay' => 'الأيمارا', 'az' => 'الأذرية', 'ba' => 'الباشكيرية', 'bad' => 'الباندا', 'bai' => 'اللغة الباميليكية', 'bal' => 'البلوشية', 'ban' => 'اللغة البالية', 'bas' => 'الباسا', 'bat' => 'اللغة البلطيقية', 'be' => 'البيلوروسية', 'bej' => 'البيجا', 'bem' => 'البيمبا', 'ber' => 'البربرية', 'bg' => 'البلغارية', 'bh' => 'البيهارية', 'bho' => 'البهوجبرية', 'bi' => 'البيسلامية', 'bik' => 'البيكولية', 'bin' => 'البينية', 'bla' => 'السيكسيكية', 'bm' => 'البامبارا', 'bn' => 'البنغالية', 'bnt' => 'البانتو', 'bo' => 'التبتية', 'br' => 'البريتونية', 'bra' => 'البراجية', 'bs' => 'البوسنية', 'btk' => 'الباتاكية', 'bua' => 'البرياتية', 'bug' => 'البجينيزية', 'byn' => 'البلينية', 'ca' => 'الكتالانية', 'cad' => 'الكادو', 'cai' => 'اللغة الهندية الأمريكية الوسطى', 'car' => 'الكاريبية', 'cau' => 'القوقازية - أخرى', 'cch' => 'الأتسام', 'ce' => 'الشيشانية', 'ceb' => 'السيبيونو', 'cel' => 'السلتية - أخرى', 'ch' => 'التشامورو', 'chb' => 'التشيبشا', 'chg' => 'التشاجاتاي', 'chk' => 'التشكيزية', 'chm' => 'الماري', 'chn' => 'الشينوك جارجون', 'cho' => 'الشوكتو', 'chp' => 'الشيباوايان', 'chr' => 'الشيروكي', 'chy' => 'الشايان', 'cmc' => 'اللغة التشاميكية', 'co' => 'الكورسيكية', 'cop' => 'القبطية', 'cpe' => 'الكرييولى و اللغات المبسطة الأخرى للتفاهم بين الشعوب على أساس الأنجليزية', 'cpf' => 'الكرييولى و اللغات المبسطة الأخرى للتفاهم بين الشعوب على أساس الفرنسية', 'cpp' => 'الكرييولي واللغات المبسطة الأخرى للتفاهم بين الشعوب على أساس البرتغالية', 'cr' => 'الكرى', 'crh' => 'التركية الكريمينية', 'crp' => 'الكرييولى و اللغات المبسطة الأخرى للتفاهم بين الشعوب - أخرى', 'cs' => 'التشيكية', 'csb' => 'الكاشبايان', 'cu' => 'سلافية كنسية', 'cus' => 'اللغة الكشيتيكية', 'cv' => 'التشفاش', 'cy' => 'الولزية', 'da' => 'الدانماركية', 'dak' => 'الداكوتا', 'dar' => 'الدارجوا', 'day' => 'الدياك', 'de' => 'الألمانية', 'de_at' => 'الألمانية النمساوية', 'de_ch' => 'الألمانية العليا السويسرية', 'del' => 'الديلوير', 'den' => 'السلافية', 'dgr' => 'الدوجريب', 'din' => 'الدنكا', 'doi' => 'الدوجري', 'dra' => 'اللغة الدرافيدينية', 'dsb' => 'الصربية السفلى', 'dua' => 'الديولا', 'dum' => 'الهولندية الوسطى', 'dv' => 'المالديفية', 'dyu' => 'الدايلا', 'dz' => 'الزونخاية', 'ee' => 'الإيوي', 'efi' => 'الإفيك', 'egy' => 'المصرية القديمة', 'eka' => 'الإكاجك', 'el' => 'اليونانية', 'elx' => 'الإمايت', 'en' => 'الإنجليزية', 'en_au' => 'الإنجليزية الأسترالية', 'en_ca' => 'الإنجليزية الكندية', 'en_gb' => 'الإنجليزية البريطانية', 'en_us' => 'الإنجليزية الولايات المتحدة', 'enm' => 'الإنجليزية الوسطى', 'eo' => 'الإسبرانتو', 'es' => 'الإسبانية', 'es_419' => 'إسبانية أمريكا اللاتينية', 'es_es' => 'الإسبانية الأيبيرية', 'et' => 'الإستونية', 'eu' => 'لغة الباسك', 'ewo' => 'الإيوندو', 'fa' => 'الفارسية', 'fan' => 'الفانج', 'fat' => 'الفانتي', 'ff' => 'الفلة', 'fi' => 'الفنلندية', 'fil' => 'الفلبينية', 'fiu' => 'لغة فينو أجريانية', 'fj' => 'الفيجية', 'fo' => 'الفارويز', 'fon' => 'الفون', 'fr' => 'الفرنسية', 'fr_ca' => 'الفرنسية الكندية', 'fr_ch' => 'الفرنسية السويسرية', 'frm' => 'الفرنسية الوسطى', 'fro' => 'الفرنسية القديمة', 'frr' => 'الفريزينية الشمالية', 'frs' => 'الفريزينية الشرقية', 'fur' => 'الفريلايان', 'fy' => 'الفريزيان', 'ga' => 'الأيرلندية', 'gaa' => 'الجا', 'gay' => 'الجايو', 'gba' => 'الجبيا', 'gd' => 'الغيلية الأسكتلندية', 'gem' => 'اللغة الجرمانية', 'gez' => 'الجيز', 'gil' => 'لغة أهل جبل طارق', 'gl' => 'الجاليكية', 'gmh' => 'الألمانية العليا الوسطى', 'gn' => 'الجواراني', 'goh' => 'الألمانية العليا القديمة', 'gon' => 'الجندي', 'gor' => 'الجورونتالو', 'got' => 'القوطية', 'grb' => 'الجريبو', 'grc' => 'اليونانية القديمة', 'gsw' => 'الألمانية السويسرية', 'gu' => 'الغوجاراتية', 'gv' => 'المنكية', 'ha' => 'الهوسا', 'hai' => 'الهيدا', 'haw' => 'لغة أهل الهاواي', 'he' => 'العبرية', 'hi' => 'الهندية', 'hil' => 'الهيليجينون', 'him' => 'الهيماتشالي', 'hit' => 'الحثية', 'hmn' => 'الهمونجية', 'ho' => 'الهيري موتو', 'hr' => 'الكرواتية', 'hsb' => 'الصربية العليا', 'ht' => 'الهايتية', 'hu' => 'الهنغارية', 'hup' => 'الهبا', 'hy' => 'الأرمينية', 'hz' => 'الهيريرو', 'ia' => 'اللّغة الوسيطة', 'iba' => 'الإيبان', 'id' => 'الإندونيسية', 'ie' => 'الإنترلينج', 'ig' => 'الإيجبو', 'ii' => 'السيتشيون يي', 'ijo' => 'الإجو', 'ik' => 'الإينبياك', 'ilo' => 'الإيلوكو', 'inc' => 'اللغة الهندية', 'ine' => 'الهندية الأوروبية - أخرى', 'inh' => 'الإنجوشية', 'io' => 'الإيدو', 'ira' => 'اللغة الإيرانية', 'iro' => 'اللغة الإيروكويانية', 'is' => 'الأيسلاندية', 'it' => 'الإيطالية', 'iu' => 'الإينكتيتت', 'ja' => 'اليابانية', 'jbo' => 'اللوجبان', 'jpr' => 'الجيدو - الفارسي', 'jrb' => 'الجيدو - العربي', 'jv' => 'الجاوية', 'ka' => 'الجورجية', 'kaa' => 'الكارا-كالباك', 'kab' => 'القبيلية', 'kac' => 'الكاتشين', 'kaj' => 'الجو', 'kam' => 'الكامبا', 'kar' => 'الكاريين', 'kaw' => 'الكوي', 'kbd' => 'الكاباردايان', 'kfo' => 'الكورو', 'kg' => 'الكونغو', 'kha' => 'الكازية', 'khi' => 'اللغة الخويسانية', 'kho' => 'الخوتانيز', 'ki' => 'الكيكيو', 'kj' => 'الكيونياما', 'kk' => 'الكازاخستانية', 'kl' => 'الكالاليست', 'km' => 'الخميرية', 'kmb' => 'الكيمبندو', 'kn' => 'الكانادا', 'ko' => 'الكورية', 'kok' => 'الكونكانية', 'kos' => 'الكوسراين', 'kpe' => 'الكبيل', 'kr' => 'الكانيوري', 'krc' => 'الكاراتشاي-بالكار', 'krl' => 'الكريلية', 'kro' => 'الكرو', 'ks' => 'الكاشميرية', 'ku' => 'الكردية', 'kum' => 'الكميك', 'kut' => 'الكتيناي', 'kv' => 'الكومي', 'kw' => 'الكورنية', 'ky' => 'القيرغستانية', 'la' => 'اللاتينية', 'lad' => 'الإسباعبرية', 'lah' => 'اللاهندا', 'lam' => 'اللامبا', 'lb' => 'اللوكسمبرجية', 'lez' => 'الليزجهايانية', 'lg' => 'الجاندا', 'li' => 'الليمبرجيشية', 'ln' => 'اللينجالا', 'lo' => 'اللاوية', 'lol' => 'منغولى', 'loz' => 'اللوزي', 'lt' => 'اللتوانية', 'lu' => 'اللبا-كاتانجا', 'lua' => 'اللبا-لؤلؤ', 'lui' => 'اللوسينو', 'lun' => 'اللوندا', 'luo' => 'اللو', 'lus' => 'اللشاي', 'lv' => 'اللاتفية', 'mad' => 'المادريز', 'mag' => 'الماجا', 'mai' => 'المايثيلي', 'mak' => 'الماكاسار', 'man' => 'الماندينغ', 'map' => 'الأوسترونيسيان', 'mas' => 'الماساي', 'mdf' => 'الموكشا', 'mdr' => 'الماندار', 'men' => 'الميند', 'mg' => 'المالاجاشية', 'mga' => 'الأيرلندية الوسطى', 'mh' => 'المارشالية', 'mi' => 'الماورية', 'mic' => 'الميكماكيونية', 'min' => 'المينانجكاباو', 'mis' => 'اللغة المتنوعة', 'mk' => 'المقدونية', 'mkh' => 'لغة المون - خمير', 'ml' => 'الماليالام', 'mn' => 'المنغولية', 'mnc' => 'المانشو', 'mni' => 'المانيبري', 'mno' => 'لغات مانوبو', 'mo' => 'المولدوفية', 'moh' => 'الموهوك', 'mos' => 'الموسي', 'mr' => 'الماراثي', 'ms' => 'لغة الملايو', 'mt' => 'المالطية', 'mul' => 'لغات متعددة', 'mun' => 'لغة المندا', 'mus' => 'الكريك', 'mwl' => 'الميرانديز', 'mwr' => 'المارواري', 'my' => 'البورمية', 'myn' => 'لغة المايا', 'myv' => 'الأرزية', 'na' => 'النورو', 'nah' => 'الناهيوتل', 'nai' => 'اللغة الهندية الأمريكية الشمالية', 'nap' => 'اللغة النابولية', 'nb' => 'البوكمالية النرويجية', 'nd' => 'النديبيل الشمالي', 'nds' => 'الألمانية السفلى', 'ne' => 'النيبالية', 'new' => 'النيواري', 'ng' => 'الندونجا', 'nia' => 'النياس', 'nic' => 'النيجر - كوردوفانايان', 'niu' => 'النيوي', 'nl' => 'الهولندية', 'nl_be' => 'الفلمنك', 'nn' => 'النينورسك النرويجي', 'no' => 'النرويجية', 'nog' => 'النوجاي', 'non' => 'النورس القديم', 'nqo' => 'أنكو', 'nr' => 'النديبيل الجنوبي', 'nso' => 'السوتو الشمالية', 'nub' => 'لغة نوبية', 'nv' => 'النافاجو', 'nwc' => 'النوارية التقليدية', 'ny' => 'النيانجا', 'nym' => 'النيامويزي', 'nyn' => 'النيانكول', 'nyo' => 'النيورو', 'nzi' => 'النزيما', 'oc' => 'الأوكيتانية', 'oj' => 'الأوجيبوا', 'om' => 'الأورومو', 'or' => 'الأورييا', 'os' => 'الأوسيتيك', 'osa' => 'الأوساج', 'ota' => 'التركية العثمانية', 'oto' => 'اللغة الأوتومية', 'pa' => 'البنجابية', 'paa' => 'اللغة الغينية', 'pag' => 'البانجاسينان', 'pal' => 'البهلوية', 'pam' => 'البامبانجا', 'pap' => 'البابيامينتو', 'pau' => 'البالوان', 'peo' => 'الفارسية القديمة', 'phi' => 'اللغة الفليبينية', 'phn' => 'الفينيقية', 'pi' => 'البالية', 'pl' => 'البولندية', 'pon' => 'البوهنبيايان', 'pra' => 'اللغات البراقريطية', 'pro' => 'البروفانسية القديمة', 'ps' => 'بشتو', 'pt' => 'البرتغالية', 'pt_br' => 'البرتغالية البرازيلية', 'pt_pt' => 'البرتغالية الأيبيرية', 'qu' => 'الكويتشوا', 'raj' => 'الراجاسثانية', 'rap' => 'الراباني', 'rar' => 'الراروتونجاني', 'rm' => 'الرهايتو-رومانس', 'rn' => 'الرندي', 'ro' => 'الرومانية', 'roa' => 'اللغة الرومانسية', 'rom' => 'غجري', 'root' => 'الجذر', 'ru' => 'الروسية', 'rup' => 'الأرومانيان', 'rw' => 'الكينيارواندا', 'sa' => 'السنسكريتية', 'sad' => 'السانداوي', 'sah' => 'الساخية', 'sai' => 'اللغة الهندية الأمريكية الجنوبية', 'sal' => 'اللغة الساليشانية', 'sam' => 'الآرامية السومارية', 'sas' => 'الساساك', 'sat' => 'السانتالي', 'sc' => 'السردينية', 'scn' => 'الصقلية', 'sco' => 'الأسكتلندية', 'sd' => 'السيندي', 'se' => 'السامي الشمالي', 'sel' => 'السيلكب', 'sem' => 'لغة سامية', 'sg' => 'السانجو', 'sga' => 'الأيرلندية القديمة', 'sgn' => 'لغات الإشارة', 'shn' => 'الشانية', 'si' => 'السنهالية', 'sid' => 'السيدامو', 'sio' => 'لغة السيويون', 'sit' => 'اللغة الصينية التيبتية', 'sk' => 'السلوفاكية', 'sl' => 'السلوفانية', 'sla' => 'اللغة السلافية', 'sm' => 'الساموائية', 'sma' => 'السامي الجنوبي', 'smi' => 'اللغة السامية', 'smj' => 'اللول سامي', 'smn' => 'الإيناري سامي', 'sms' => 'السكولت سامي', 'sn' => 'الشونا', 'snk' => 'السونينك', 'so' => 'الصومالية', 'sog' => 'السوجدين', 'son' => 'السونجهاي', 'sq' => 'الألبانية', 'sr' => 'الصربية', 'srn' => 'السرانان تونجو', 'srr' => 'السرر', 'ss' => 'السواتي', 'ssa' => 'لغة نيلية الصحراوية', 'st' => 'السوتو الجنوبية', 'su' => 'السودانية', 'suk' => 'السوكوما', 'sus' => 'السوسو', 'sux' => 'السومارية', 'sv' => 'السويدية', 'sw' => 'السواحلية', 'swb' => 'القمرية', 'syc' => 'سريانية تقليدية', 'syr' => 'السريانية', 'ta' => 'التاميلية', 'tai' => 'لغة تاي', 'te' => 'التيلجو', 'tem' => 'التيمن', 'ter' => 'التيرينو', 'tet' => 'التيتم', 'tg' => 'الطاجيكية', 'th' => 'التايلاندية', 'ti' => 'التيجرينيا', 'tig' => 'التيجر', 'tiv' => 'التيف', 'tk' => 'التركمانية', 'tkl' => 'التوكيلاو', 'tl' => 'التاغالوغية', 'tlh' => 'الكلينجون', 'tli' => 'التلينغيتية', 'tmh' => 'التاماشيك', 'tn' => 'التسوانية', 'to' => 'التونغية', 'tog' => 'تونجا - نياسا', 'tpi' => 'التوك بيسين', 'tr' => 'التركية', 'ts' => 'السونجا', 'tsi' => 'التسيمشيان', 'tt' => 'التتارية', 'tum' => 'التامبوكا', 'tup' => 'اللغة التوبية', 'tut' => 'الألطائية - أخرى', 'tvl' => 'التوفالو', 'tw' => 'التوي', 'ty' => 'التاهيتية', 'udm' => 'الأدمرت', 'ug' => 'الأيغورية', 'uga' => 'اليجاريتيك', 'uk' => 'الأوكرانية', 'umb' => 'الأمبندو', 'und' => 'لغة غير معروفة', 'ur' => 'الأردية', 'uz' => 'الأوزباكية', 'vai' => 'الفاي', 've' => 'الفيندا', 'vi' => 'الفيتنامية', 'vot' => 'الفوتيك', 'wa' => 'الولونية', 'wak' => 'اللغة الواكاشانية', 'wal' => 'الوالامو', 'war' => 'الواراي', 'was' => 'الواشو', 'wen' => 'اللغة الصربية', 'wo' => 'الولوف', 'xal' => 'الكالميك', 'xh' => 'الخوسا', 'yao' => 'الياو', 'yap' => 'اليابيز', 'yi' => 'اليديشية', 'yo' => 'اليوروبية', 'ypk' => 'اللغة اليوبيكية', 'yue' => 'الكَنْتُونية', 'za' => 'الزهيونج', 'zap' => 'الزابوتيك', 'zen' => 'الزيناجا', 'zh' => 'الصينية', 'znd' => 'الزاند', 'zu' => 'الزولو', 'zun' => 'الزونية', 'zxx' => 'بدون محتوى لغوي', ), 'scripts' => array ( 'arab' => 'الفارسية العربية', 'armn' => 'الأرمينية', 'bali' => 'البالية', 'batk' => 'الباتاك', 'beng' => 'البنغالية', 'blis' => 'رموز بليس', 'bopo' => 'البوبوموفو', 'brah' => 'الهندوسية', 'brai' => 'البرايل', 'bugi' => 'البجينيز', 'buhd' => 'البهيدية', 'cans' => 'مقاطع كندية أصلية موحدة', 'cari' => 'الكارية', 'cham' => 'التشامية', 'cher' => 'الشيروكي', 'cirt' => 'السيرث', 'copt' => 'القبطية', 'cprt' => 'القبرصية', 'cyrl' => 'السيريلية', 'cyrs' => 'السيريلية السلافية الكنسية القديمة', 'deva' => 'الديفاناجاري', 'dsrt' => 'الديسيريت', 'egyd' => 'الديموطيقية', 'egyh' => 'الهيراطيقية', 'egyp' => 'الهيروغليفية', 'ethi' => 'الأثيوبية', 'geok' => 'الأبجدية الجورجية - أسومتافرلي و نسخري', 'geor' => 'الجورجية', 'glag' => 'الجلاجوليتيك', 'goth' => 'القوطية', 'grek' => 'اليونانية', 'gujr' => 'التاغجراتية', 'guru' => 'الجرمخي', 'hang' => 'الهانغول', 'hani' => 'الهان', 'hano' => 'الهانونو', 'hans' => 'الهان المبسطة', 'hant' => 'الهان التقليدية', 'hebr' => 'العبرية', 'hira' => 'الهيراجانا', 'hmng' => 'الباهوه همونج', 'hrkt' => 'الكتكانا أو الهيراجانا', 'hung' => 'المجرية القديمة', 'inds' => 'اندس - هارابان', 'ital' => 'الإيطالية القديمة', 'java' => 'الجاوية', 'jpan' => 'اليابانية', 'kali' => 'الكياه لى', 'kana' => 'الكتكانا', 'khar' => 'الخاروشتى', 'khmr' => 'الخميرية', 'knda' => 'الكانادا', 'kore' => 'الكورية', 'lana' => 'الانا', 'laoo' => 'اللاو', 'latf' => 'اللاتينية - متغير فراكتر', 'latg' => 'اللاتينية - متغير غيلى', 'latn' => 'اللاتينية', 'lepc' => 'الليبتشا - رونج', 'limb' => 'الليمبو', 'lina' => 'الخطية أ', 'linb' => 'الخطية ب', 'lyci' => 'الليسية', 'lydi' => 'الليدية', 'mand' => 'المانداينية', 'maya' => 'المايا الهيروغليفية', 'mero' => 'الميرويتيك', 'mlym' => 'الماليالام', 'mong' => 'المغولية', 'moon' => 'مون', 'mymr' => 'الميانمار', 'nkoo' => 'أنكو', 'ogam' => 'الأوجهام', 'orkh' => 'الأورخون', 'orya' => 'الأوريا', 'osma' => 'الأوسمانيا', 'perm' => 'البيرميكية القديمة', 'phag' => 'الفاجسبا', 'phnx' => 'الفينيقية', 'plrd' => 'الصوتيات الجماء', 'roro' => 'رنجورنجو', 'runr' => 'الروني', 'sara' => 'الساراتي', 'shaw' => 'الشواني', 'sinh' => 'السينهالا', 'sund' => 'السوندانية', 'sylo' => 'السيلوتي ناغري', 'syrc' => 'السريانية', 'syre' => 'السريانية الأسترنجيلية', 'syrj' => 'السريانية الغربية', 'syrn' => 'السريانية الشرقية', 'tagb' => 'التاجبانوا', 'tale' => 'التاي لي', 'talu' => 'التاى لى الجديد', 'taml' => 'التاميلية', 'telu' => 'التيلجو', 'teng' => 'التينجوار', 'tfng' => 'التيفيناغ', 'tglg' => 'التغالوغية', 'thaa' => 'الثعنة', 'thai' => 'التايلاندية', 'tibt' => 'التبتية', 'ugar' => 'الأجاريتيكية', 'vaii' => 'الفاي', 'visp' => 'الكلام المرئي', 'xpeo' => 'الفارسية القديمة', 'xsux' => 'الكتابة المسمارية الأكدية السومرية', 'yiii' => 'اليي', 'zinh' => 'الموروث', 'zsym' => 'رموز', 'zxxx' => 'غير مكتوب', 'zyyy' => 'عام', 'zzzz' => 'نص مكتوب غير معروف', ), 'territories' => array ( '001' => 'العالم', '002' => 'أفريقيا', '003' => 'أمريكا الشمالية', '005' => 'أمريكا الجنوبية', '009' => 'أوقيانوسيا', '011' => 'غرب أفريقيا', '013' => 'أمريكا الوسطى', '014' => 'شرق أفريقيا', '015' => 'شمال أفريقيا', '017' => 'وسط أفريقيا', '018' => 'أفريقيا الجنوبية', '019' => 'الأمريكتين', '021' => 'شمال أمريكا', '029' => 'الكاريبي', '030' => 'شرق آسيا', '034' => 'جنوب آسيا', '035' => 'جنوب شرق آسيا', '039' => 'جنوب أوروبا', '053' => 'أستراليا ونيوزيلندا', '054' => 'ميلانيزيا', '057' => 'الجزر الميكرونيزية', '061' => 'بولينيزيا', 142 => 'آسيا', 143 => 'وسط آسيا', 145 => 'غرب آسيا', 150 => 'أوروبا', 151 => 'شرق أوروبا', 154 => 'شمال أوروبا', 155 => 'غرب أوروبا', 419 => 'أمريكا اللاتينية', 'ac' => 'جزيرة أسينشيون', 'ad' => 'أندورا', 'ae' => 'الإمارات العربية المتحدة', 'af' => 'أفغانستان', 'ag' => 'أنتيغوا وبربودا', 'ai' => 'أنغويلا', 'al' => 'ألبانيا', 'am' => 'أرمينيا', 'an' => 'جزر الأنتيل الهولندية', 'ao' => 'أنغولا', 'aq' => 'القطب الجنوبي', 'ar' => 'الأرجنتين', 'as' => 'ساموا الأمريكية', 'at' => 'النمسا', 'au' => 'أستراليا', 'aw' => 'آروبا', 'ax' => 'جزر أولان', 'az' => 'أذربيجان', 'ba' => 'البوسنة والهرسك', 'bb' => 'بربادوس', 'bd' => 'بنجلاديش', 'be' => 'بلجيكا', 'bf' => 'بوركينا فاسو', 'bg' => 'بلغاريا', 'bh' => 'البحرين', 'bi' => 'بوروندي', 'bj' => 'بنين', 'bl' => 'سان بارتليمي', 'bm' => 'برمودا', 'bn' => 'بروناي', 'bo' => 'بوليفيا', 'br' => 'البرازيل', 'bs' => 'الباهاما', 'bt' => 'بوتان', 'bv' => 'جزيرة بوفيه', 'bw' => 'بتسوانا', 'by' => 'روسيا البيضاء', 'bz' => 'بليز', 'ca' => 'كندا', 'cc' => 'جزر كوكوس', 'cd' => 'جمهورية الكونغو الديمقراطية', 'cf' => 'جمهورية أفريقيا الوسطى', 'cg' => 'جمهورية الكونغو', 'ch' => 'سويسرا', 'ci' => 'ساحل العاج', 'ck' => 'جزر كوك', 'cl' => 'شيلي', 'cm' => 'الكاميرون', 'cn' => 'الصين', 'co' => 'كولومبيا', 'cp' => 'جزيرة كليبيرتون', 'cr' => 'كوستاريكا', 'cs' => 'صربيا والجبل الأسود', 'cu' => 'كوبا', 'cv' => 'الرأس الأخضر', 'cx' => 'جزيرة الكريسماس', 'cy' => 'قبرص', 'cz' => 'جمهورية التشيك', 'de' => 'ألمانيا', 'dg' => 'دييغو غارسيا', 'dj' => 'جيبوتي', 'dk' => 'الدانمرك', 'dm' => 'دومينيكا', 'do' => 'جمهورية الدومينيك', 'dz' => 'الجزائر', 'ea' => 'سيوتا وميليلا', 'ec' => 'الإكوادور', 'ee' => 'أستونيا', 'eg' => 'مصر', 'eh' => 'الصحراء الغربية', 'er' => 'أريتريا', 'es' => 'إسبانيا', 'et' => 'إثيوبيا', 'eu' => 'الاتحاد الأوروبي', 'fi' => 'فنلندا', 'fj' => 'فيجي', 'fk' => 'جزر فوكلاند - جزر مالفيناس', 'fm' => 'ميكرونيزيا', 'fo' => 'جزر فارو', 'fr' => 'فرنسا', 'fx' => 'ميتروبولويتان فرنسا', 'ga' => 'الجابون', 'gb' => 'المملكة المتحدة', 'gd' => 'غرينادا', 'ge' => 'جورجيا', 'gf' => 'غويانا الفرنسية', 'gg' => 'غيرنزي', 'gh' => 'غانا', 'gi' => 'جبل طارق', 'gl' => 'غرينلاند', 'gm' => 'غامبيا', 'gn' => 'غينيا', 'gp' => 'جوادلوب', 'gq' => 'غينيا الاستوائية', 'gr' => 'اليونان', 'gs' => 'جورجيا الجنوبية وجزر ساندويتش الجنوبية', 'gt' => 'غواتيمالا', 'gu' => 'غوام', 'gw' => 'غينيا بيساو', 'gy' => 'غيانا', 'hk' => 'هونغ كونغ', 'hm' => 'جزيرة هيرد وجزر ماكدونالد', 'hn' => 'هندوراس', 'hr' => 'كرواتيا', 'ht' => 'هايتي', 'hu' => 'هنغاريا', 'ic' => 'جزر الكناري', 'id' => 'اندونيسيا', 'ie' => 'أيرلندا', 'il' => 'إسرائيل', 'im' => 'جزيرة مان', 'in' => 'الهند', 'io' => 'الإقليم البريطاني في المحيط الهندي', 'iq' => 'العراق', 'ir' => 'إيران', 'is' => 'أيسلندا', 'it' => 'إيطاليا', 'je' => 'جيرسي', 'jm' => 'جامايكا', 'jo' => 'الأردن', 'jp' => 'اليابان', 'ke' => 'كينيا', 'kg' => 'قرغيزستان', 'kh' => 'كمبوديا', 'ki' => 'كيريباتي', 'km' => 'جزر القمر', 'kn' => 'سانت كيتس ونيفيس', 'kp' => 'كوريا الشمالية', 'kr' => 'كوريا الجنوبية', 'kw' => 'الكويت', 'ky' => 'جزر الكايمن', 'kz' => 'كازاخستان', 'la' => 'لاوس', 'lb' => 'لبنان', 'lc' => 'سانت لوسيا', 'li' => 'ليختنشتاين', 'lk' => 'سريلانكا', 'lr' => 'ليبيريا', 'ls' => 'ليسوتو', 'lt' => 'ليتوانيا', 'lu' => 'لوكسمبورغ', 'lv' => 'لاتفيا', 'ly' => 'ليبيا', 'ma' => 'المغرب', 'mc' => 'موناكو', 'md' => 'مولدافيا', 'me' => 'الجبل الأسود', 'mf' => 'سانت مارتين', 'mg' => 'مدغشقر', 'mh' => 'جزر المارشال', 'mk' => 'مقدونيا- جمهورية مقدونيا اليوغسلافية السابقة', 'ml' => 'مالي', 'mm' => 'ميانمار -بورما', 'mn' => 'منغوليا', 'mo' => 'ماكاو', 'mp' => 'جزر ماريانا الشمالية', 'mq' => 'مارتينيك', 'mr' => 'موريتانيا', 'ms' => 'مونتسرات', 'mt' => 'مالطا', 'mu' => 'موريشيوس', 'mv' => 'جزر المالديف', 'mw' => 'ملاوي', 'mx' => 'المكسيك', 'my' => 'ماليزيا', 'mz' => 'موزمبيق', 'na' => 'ناميبيا', 'nc' => 'كاليدونيا الجديدة', 'ne' => 'النيجر', 'nf' => 'جزيرة نورفوك', 'ng' => 'نيجيريا', 'ni' => 'نيكاراغوا', 'nl' => 'هولندا', 'no' => 'النرويج', 'np' => 'نيبال', 'nr' => 'ناورو', 'nu' => 'نيوي', 'nz' => 'نيوزيلاندا', 'om' => 'عُمان', 'pa' => 'بنما', 'pe' => 'بيرو', 'pf' => 'بولينيزيا الفرنسية', 'pg' => 'بابوا غينيا الجديدة', 'ph' => 'الفيلبين', 'pk' => 'باكستان', 'pl' => 'بولندا', 'pm' => 'سانت بيير وميكولون', 'pn' => 'جزر بيتكيرن', 'pr' => 'بورتوريكو', 'ps' => 'فلسطين', 'pt' => 'البرتغال', 'pw' => 'بالاو', 'py' => 'باراغواي', 'qa' => 'قطر', 'qo' => 'أوقيانوسيا النائية', 're' => 'روينيون', 'ro' => 'رومانيا', 'rs' => 'صربيا', 'ru' => 'روسيا', 'rw' => 'رواندا', 'sa' => 'المملكة العربية السعودية', 'sb' => 'جزر سليمان', 'sc' => 'سيشل', 'sd' => 'السودان', 'se' => 'السويد', 'sg' => 'سنغافورة', 'sh' => 'سانت هيلنا', 'si' => 'سلوفينيا', 'sj' => 'سفالبارد وجان مايان', 'sk' => 'سلوفاكيا', 'sl' => 'سيراليون', 'sm' => 'سان مارينو', 'sn' => 'السنغال', 'so' => 'الصومال', 'sr' => 'سورينام', 'st' => 'ساو تومي وبرينسيبي', 'sv' => 'السلفادور', 'sy' => 'سوريا', 'sz' => 'سوازيلاند', 'ta' => 'تريستان دي كونها', 'tc' => 'جزر الترك وجايكوس', 'td' => 'تشاد', 'tf' => 'المقاطعات الجنوبية الفرنسية', 'tg' => 'توجو', 'th' => 'تايلند', 'tj' => 'طاجكستان', 'tk' => 'توكيلو', 'tl' => 'تيمور الشرقية', 'tm' => 'تركمانستان', 'tn' => 'تونس', 'to' => 'تونغا', 'tr' => 'تركيا', 'tt' => 'ترينيداد وتوباغو', 'tv' => 'توفالو', 'tw' => 'تايوان', 'tz' => 'تانزانيا', 'ua' => 'أوكرانيا', 'ug' => 'أوغندا', 'um' => 'جزر الولايات المتحدة البعيدة الصغيرة', 'us' => 'الولايات المتحدة الأمريكية', 'uy' => 'أورغواي', 'uz' => 'أوزبكستان', 'va' => 'الفاتيكان', 'vc' => 'سانت فنسنت وغرنادين', 've' => 'فنزويلا', 'vg' => 'جزر فرجين البريطانية', 'vi' => 'جزر فرجين الأمريكية', 'vn' => 'فيتنام', 'vu' => 'فانواتو', 'wf' => 'جزر والس وفوتونا', 'ws' => 'ساموا', 'ye' => 'اليمن', 'yt' => 'مايوت', 'za' => 'جنوب أفريقيا', 'zm' => 'زامبيا', 'zw' => 'زيمبابوي', 'zz' => 'منطقة غير معروفة', ), 'pluralRules' => array ( 0 => 'n==0', 1 => 'n==1', 2 => 'n==2', 3 => '(fmod(n,100)>=3&&fmod(n,100)<=10&&fmod(fmod(n,100),1)==0)', 4 => '(fmod(n,100)>=11&&fmod(n,100)<=99&&fmod(fmod(n,100),1)==0)', 5 => 'true', ), );
// // Main.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2011 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 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. // using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace RecipesAndPrinting { public class Application { // This is the main entry point of the application. static void Main (string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main (args, null, "AppDelegate"); } } }
#!/usr/bin/python2.4 # Copyright 2009, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Test for environment_tools. These are SMALL and MEDIUM tests.""" import os import unittest import TestFramework class EnvToolsTests(unittest.TestCase): """Tests for environment_tools module.""" def setUp(self): """Per-test setup.""" self.env = self.root_env.Clone() def testFilterOut(self): """Test FilterOut().""" env = self.env env.Replace( TEST1=['ant', 'bear', 'cat'], TEST2=[1, 2, 3, 4], ) # Simple filter env.FilterOut(TEST1=['bear']) self.assertEqual(env['TEST1'], ['ant', 'cat']) # Filter multiple env.FilterOut(TEST1=['ant'], TEST2=[1, 3]) self.assertEqual(env['TEST1'], ['cat']) self.assertEqual(env['TEST2'], [2, 4]) # Filter doesn't care if the variable or value doesn't exist env.FilterOut(TEST1=['dog'], TEST3=[2]) self.assertEqual(env['TEST1'], ['cat']) self.assertEqual(env['TEST2'], [2, 4]) def testFilterOutRepeated(self): """Test FilterOut() filters all matches.""" env = self.env env['TEST3'] = ['A', 'B', 'B', 'C'] env.FilterOut(TEST3=['B']) self.assertEqual(env['TEST3'], ['A', 'C']) def testFilterOutNested(self): """Test FilterOut on nested lists.""" env = self.env # FilterOut does not currently flatten lists, nor remove values from # sub-lists. This is related to not evaluating environment variables (see # below). env['TEST4'] = ['A', ['B', 'C'], 'D'] env.FilterOut(TEST4=['B']) self.assertEqual(env['TEST4'], ['A', ['B', 'C'], 'D']) # If you specify the entire sub-list, it will be filtered env.FilterOut(TEST4=[['B', 'C']]) self.assertEqual(env['TEST4'], ['A', 'D']) def testFilterOutNoEval(self): """Test FilterOut does not evaluate variables in the list.""" env = self.env # FilterOut does not evaluate variables in the list. (Doing so would # defeat much of the purpose of variables.) Note that this means it does # not filter variables which evaluate partially or wholly to the filtered # string. On the plus side, this means you CAN filter out variables. env.Replace( TEST5=['$V1', '$V2', '$V3', '$V4'], V1='A', # (V2 intentionally undefined at this point) V3=['A', 'B'], V4='C', ) env.FilterOut(TEST5=['A', '$V4']) self.assertEqual(env['TEST5'], ['$V1', '$V2', '$V3']) def testOverlap(self): """Test Overlap().""" env = self.env env.Replace( OLVAR='baz', OLLIST=['2', '3', '4'], ) # Simple string compares self.assertEqual(env.Overlap('foo', 'foo'), ['foo']) self.assertEqual(env.Overlap('foo', 'food'), []) # String compare with variable substitution self.assertEqual(env.Overlap('foobaz', 'foo$OLVAR'), ['foobaz']) # Simple list overlap # Need to use set() for comparison, since the order of entries in the # output list is indeterminate self.assertEqual(set(env.Overlap(['1', '2', '3'], ['2', '3', '4'])), set(['2', '3'])) # Overlap removes duplicates self.assertEqual(env.Overlap(['1', '2', '2'], ['2', '3', '2']), ['2']) # List and string self.assertEqual(env.Overlap('3', ['1', '2', '3']), ['3']) self.assertEqual(env.Overlap('4', ['1', '2', '3']), []) self.assertEqual(env.Overlap(['1', '$OLVAR', '3'], '$OLVAR'), ['baz']) # Variable substitition will replace and flatten lists self.assertEqual(set(env.Overlap(['1', '2', '3'], '$OLLIST')), set(['2', '3'])) # Substitution flattens lists self.assertEqual(set(env.Overlap([['1', '2'], '3'], ['2', ['3', '4']])), set(['2', '3'])) def testSubstList2(self): """Test SubstList2().""" env = self.env # Empty args should return empty list self.assertEqual(env.SubstList2(), []) # Undefined variable also returns empty list self.assertEqual(env.SubstList2('$NO_SUCH_VAR'), []) # Simple substitution (recursively evaluates variables) env['STR1'] = 'FOO$STR2' env['STR2'] = 'BAR' self.assertEqual(env.SubstList2('$STR1'), ['FOOBAR']) # Simple list substitution env['LIST1'] = ['A', 'B'] self.assertEqual(env.SubstList2('$LIST1'), ['A', 'B']) # Nested lists env['LIST2'] = ['C', '$LIST1'] self.assertEqual(env.SubstList2('$LIST2'), ['C', 'A', 'B']) # Multiple variables in a single entry stay a single entry self.assertEqual(env.SubstList2('$STR1 $STR2'), ['FOOBAR BAR']) # Multiple args to command self.assertEqual(env.SubstList2('$LIST2', '$STR2'), ['C', 'A', 'B', 'BAR']) # Items in list are actually strings, not some subclass self.assert_(type(env.SubstList2('$STR1')[0]) is str) def testRelativePath(self): """Test RelativePath().""" env = self.env # Trivial cases - directory or file relative to itself self.assertEqual(env.RelativePath('a', 'a'), '.') self.assertEqual(env.RelativePath('a/b/c', 'a/b/c'), '.') self.assertEqual(env.RelativePath('a', 'a', source_is_file=True), 'a') self.assertEqual(env.RelativePath('a/b/c', 'a/b/c', source_is_file=True), 'c') # Can pass in directory or file nodes self.assertEqual(env.RelativePath(env.Dir('a'), env.File('b/c'), sep='/'), '../b/c') # Separator argument is respected self.assertEqual(env.RelativePath('.', 'a/b/c', sep='BOOGA'), 'aBOOGAbBOOGAc') # Default separator is os.sep self.assertEqual(env.RelativePath('.', 'a/b'), 'a' + os.sep + 'b') # No common dirs self.assertEqual(env.RelativePath('a/b/c', 'd/e/f', sep='/'), '../../../d/e/f') self.assertEqual( env.RelativePath('a/b/c', 'd/e/f', sep='/', source_is_file=True), '../../d/e/f') # Common dirs self.assertEqual(env.RelativePath('a/b/c/d', 'a/b/e/f', sep='/'), '../../e/f') # Source or destination path is different length self.assertEqual(env.RelativePath('a/b/c/d', 'a/b', sep='/'), '../..') self.assertEqual(env.RelativePath('a/b', 'a/b/c/d', sep='/'), 'c/d') # Current directory on either side self.assertEqual(env.RelativePath('a/b/c', '.', sep='/'), '../../..') self.assertEqual(env.RelativePath('.', 'a/b/c', sep='/'), 'a/b/c') # Variables are evaluated env.Replace( DIR1='foo', DIR2='bar', ) self.assertEqual(env.RelativePath('foo/$DIR2/a', '$DIR1/bar/b', sep='/'), '../b') def testApplyBuildSConscript(self): """Test ApplySConscript() and BuildSConscript() (MEDIUM test).""" env = self.env env['SUB1'] = 'nougat' # ApplySConscript() affects the calling environment env.ApplySConscript('SConscript1') self.assertEqual(env.get('SUB2'), 'orange') # BuildSConscript() does not affect the calling environment env.BuildSConscript('SConscript2') self.assertEqual(env.get('SUB2'), 'orange') # BuildSConscript finds build.scons in preference to SConscript env.BuildSConscript('abs1') # But does look for SConscript if there isn't build.scons env.BuildSConscript('abs2') def TestSConstruct(scons_globals): """Test SConstruct file. Args: scons_globals: Global variables dict from the SConscript file. """ # Get globals from SCons Environment = scons_globals['Environment'] env = Environment(tools=['environment_tools']) # Run unit tests TestFramework.RunUnitTests(EnvToolsTests, root_env=env) sconscript1_contents = """ Import('env') if env.get('SUB1') != 'nougat': raise ValueError('ApplySConscript() failure in sconscript1') env['SUB2'] = 'orange' """ sconscript2_contents = """ Import('env') if env.get('SUB1') != 'nougat': raise ValueError('BuildSConscript() failure in sconscript2') env['SUB2'] = 'pizza' """ sconscript3_contents = """ Import('env') filename = '%s' env.Execute(Touch(filename)) """ def main(): test = TestFramework.TestFramework() test.subdir('environment_tools') base = 'environment_tools/' test.WriteSConscript(base + 'SConstruct', TestSConstruct) test.write(base + 'SConscript1', sconscript1_contents) test.write(base + 'SConscript2', sconscript2_contents) test.subdir(base + 'abs1') test.write(base + 'abs1/build.scons', sconscript3_contents % 'yes1') test.write(base + 'abs1/SConscript', sconscript3_contents % 'no') test.subdir(base + 'abs2') test.write(base + 'abs2/SConscript', sconscript3_contents % 'yes2') # Ignore stderr since unittest prints its output there test.run(chdir=base, stderr=None) test.must_exist(base + 'abs1/yes1') test.must_not_exist(base + 'abs1/no') test.must_exist(base + 'abs2/yes2') test.pass_test() if __name__ == '__main__': main()
// Type definitions for geojson 7946.0 // Project: https://geojson.org/ // Definitions by: Jacob Bruun <https://github.com/cobster> // Arne Schubert <https://github.com/atd-schubert> // Jeff Jacobson <https://github.com/JeffJacobson> // Ilia Choly <https://github.com/icholy> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 // Note: as of the RFC 7946 version of GeoJSON, Coordinate Reference Systems // are no longer supported. (See https://tools.ietf.org/html/rfc7946#appendix-B)} export as namespace GeoJSON; /** * The valid values for the "type" property of GeoJSON geometry objects. * https://tools.ietf.org/html/rfc7946#section-1.4 */ export type GeoJsonGeometryTypes = "Point" | "LineString" | "MultiPoint" | "Polygon" | "MultiLineString" | "MultiPolygon" | "GeometryCollection"; /** * The value values for the "type" property of GeoJSON Objects. * https://tools.ietf.org/html/rfc7946#section-1.4 */ export type GeoJsonTypes = "FeatureCollection" | "Feature" | GeoJsonGeometryTypes; /** * Bounding box * https://tools.ietf.org/html/rfc7946#section-5 */ export type BBox = [number, number, number, number] | [number, number, number, number, number, number]; /** * A Position is an array of coordinates. * https://tools.ietf.org/html/rfc7946#section-3.1.1 * Array should contain between two and three elements. * The previous GeoJSON specification allowed more elements (e.g., which could be used to represent M values), * but the current specification only allows X, Y, and (optionally) Z to be defined. */ export type Position = number[]; // [number, number] | [number, number, number]; /** * The base GeoJSON object. * https://tools.ietf.org/html/rfc7946#section-3 * The GeoJSON specification also allows foreign members * (https://tools.ietf.org/html/rfc7946#section-6.1) * Developers should use "&" type in TypeScript or extend the interface * to add these foreign members. */ export interface GeoJsonObject { // Don't include foreign members directly into this type def. // in order to preserve type safety. // [key: string]: any; /** * Specifies the type of GeoJSON object. */ type: GeoJsonTypes; /** * Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. * https://tools.ietf.org/html/rfc7946#section-5 */ bbox?: BBox; } /** * Union of GeoJSON objects. */ export type GeoJSON = Geometry | Feature | FeatureCollection; /** * A geometry object. * https://tools.ietf.org/html/rfc7946#section-3 */ export interface GeometryObject extends GeoJsonObject { type: GeoJsonGeometryTypes; } /** * Union of geometry objects. * https://tools.ietf.org/html/rfc7946#section-3 */ export type Geometry = Point | MultiPoint | LineString | MultiLineString | Polygon | MultiPolygon | GeometryCollection; /** * Point geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.2 */ export interface Point extends GeometryObject { type: "Point"; coordinates: Position; } /** * MultiPoint geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.3 */ export interface MultiPoint extends GeometryObject { type: "MultiPoint"; coordinates: Position[]; } /** * LineString geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.4 */ export interface LineString extends GeometryObject { type: "LineString"; coordinates: Position[]; } /** * MultiLineString geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.5 */ export interface MultiLineString extends GeometryObject { type: "MultiLineString"; coordinates: Position[][]; } /** * Polygon geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.6 */ export interface Polygon extends GeometryObject { type: "Polygon"; coordinates: Position[][]; } /** * MultiPolygon geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.7 */ export interface MultiPolygon extends GeometryObject { type: "MultiPolygon"; coordinates: Position[][][]; } /** * Geometry Collection * https://tools.ietf.org/html/rfc7946#section-3.1.8 */ export interface GeometryCollection extends GeometryObject { type: "GeometryCollection"; geometries: Geometry[]; } export type GeoJsonProperties = { [name: string]: any; } | null; /** * A feature object which contains a geometry and associated properties. * https://tools.ietf.org/html/rfc7946#section-3.2 */ export interface Feature<G extends GeometryObject | null = Geometry, P = GeoJsonProperties> extends GeoJsonObject { type: "Feature"; /** * The feature's geometry */ geometry: G; /** * A value that uniquely identifies this feature in a * https://tools.ietf.org/html/rfc7946#section-3.2. */ id?: string | number; /** * Properties associated with this feature. */ properties: P; } /** * A collection of feature objects. * https://tools.ietf.org/html/rfc7946#section-3.3 */ export interface FeatureCollection<G extends GeometryObject | null = Geometry, P = GeoJsonProperties> extends GeoJsonObject { type: "FeatureCollection"; features: Array<Feature<G, P>>; }
////////////////////////////////////////////////////////////////////////// // Software License Agreement (BSD License) // // // // Copyright (c) 2009 // // Engin Tola // // web : http://cvlab.epfl.ch/~tola // // email : engin.tola@epfl.ch // // // // All rights reserved. // // // // Redistribution and use in source and binary forms, with or without // // modification, are permitted provided that the following conditions // // are met: // // // // * Redistributions of source code must retain the above copyright // // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // // copyright notice, this list of conditions and the following // // disclaimer in the documentation and/or other materials provided // // with the distribution. // // * Neither the name of the EPFL 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. // // // // See licence.txt file for more details // ////////////////////////////////////////////////////////////////////////// #ifndef KUTILITY_MATH_H #define KUTILITY_MATH_H #include "kutility/general.h" // #include "kutility/linear_algebra.h" #include "kutility/convolution.h" namespace kutility { template<typename T> inline T distance( T a[2], T b[2] ) { T d0 = a[0]-b[0]; T d1 = a[1]-b[1]; return sqrt( d0*d0+d1*d1 ); } template<typename T> inline void shift_array_right( T* arr, int sz, int start ) { for( int i=sz-2; i>=start; i-- ) { arr[i+1] = arr[i]; } } /// creates a 1D gaussian filter with N(mean,sigma). inline void gaussian_1d(float* fltr, int fsz, float sigma, float mean ) { assert(fltr != NULL); int sz = (fsz-1)/2; int counter=-1; float sum = 0.0; float v = 2*sigma*sigma; for( int x=-sz; x<=sz; x++ ) { counter++; fltr[counter] = exp((-(x-mean)*(x-mean))/v); sum += fltr[counter]; } if( sum != 0 ) { for( int x=0; x<fsz; x++ ) fltr[x] /= sum; } } /// creates a 2D gaussian filter with N(mean,sigma). inline float* gaussian_2d(int fsz, float sigma, float mn) { int fltr_size = fsz * fsz; float* fltr = new float[fltr_size]; int sz = (fsz-1)/2; int y,x; int counter=-1; float sum=0; float v = 2*sigma*sigma; for( y=-sz; y<=sz; y++ ) { for( x=-sz; x<=sz; x++ ) { counter++; fltr[counter] = exp((-(x)*(x-mn)-(y-mn)*(y-mn))/v); sum += fltr[counter]; } } if( sum != 0 ) { for( x=0; x<fltr_size; x++ ) fltr[x] /= sum; } return fltr; } template<class T1, class T2> inline double normalized_cross_correlation( T1* a, T2* b, int sz ) { double mean_a = 0; double mean_b = 0; for( int i=0; i<sz; i++ ) { mean_a += a[i]; mean_b += b[i]; } mean_a /= sz; mean_b /= sz; double var_a = 0; double var_b = 0; double var_ab = 0; double a_part = 0; double b_part = 0; for( int i=0; i<sz; i++ ) { a_part = ( a[i] - mean_a ); b_part = ( b[i] - mean_b ); var_a += a_part * a_part; var_b += b_part * b_part; var_ab += a_part * b_part; } var_a /= sz; var_b /= sz; var_ab /= sz; if( var_a != 0 && var_b != 0 ) return var_ab / sqrt(var_a * var_b); else if ( var_a == 0 && var_b == 0 ) return 1; else return -1; } inline float pi() { return atan2( 0.0f, -1.0f ); } /// Applies a 2d gaussian blur of sigma std to the input array. if /// kernel_size is not set or it is set to 0, then it is taken as /// 3*sigma and if it is set to an even number, it is incremented /// to be an odd number. if in_place=true, then T1 must be equal /// to T2 naturally. template<class T1, class T2> inline T1* blur_gaussian_2d( T2* array, int rn, int cn, float sigma, int kernel_size=0, bool in_place=false ) { T1* out = NULL; if( in_place ) out = (T1*)array; else out = type_cast<T1,T2>(array,rn*cn); if( kernel_size == 0 ) kernel_size = (int)(3*sigma); if( kernel_size%2 == 0 ) kernel_size++; // kernel size must be odd if( kernel_size < 3 ) kernel_size= 3; // kernel size cannot be smaller than 3 float* kernel = new float[kernel_size]; gaussian_1d(kernel, kernel_size, sigma, 0); // !! apply the filter separately convolve_sym( out, rn, cn, kernel, kernel_size ); // conv_horizontal( out, rn, cn, kernel, kernel_size); // conv_vertical ( out, rn, cn, kernel, kernel_size); deallocate(kernel); return out; } /// inserts a portion of the source to the destination. template<class Td, class Ts> void insert( Td* dst, int dcn, int dymin, int dymax, int dxmin, int dxmax, Ts* src, int scn, int symin=-1, int symax=-1, int sxmin=-1, int sxmax=-1 ) { int xsz = dxmax - dxmin; int ysz = dymax - dymin; if( symin == -1 && symax == -1 && sxmin == -1 && sxmax == -1 ) { sxmin = 0; symin = 0; sxmax = scn; symax = ysz; } if( ysz != symax - symin ) error("insert: intervals must match"); if( xsz != sxmax - sxmin ) error("insert: intervals must match"); for( int y=0; y<ysz; y++ ) { for( int x=0; x<xsz; x++ ) { dst[ (dymin+y)*dcn+(dxmin+x) ] = (Td)( src[ (symin+y)*scn+(sxmin+x) ] ); } } } /// swaps the values of y and x template<class T> inline void swap(T &y, T &x) { T tmp = x; x = y; y = tmp; } /// inverts a boolean array: 1->0 & 0->1. inline bool* invert( bool* data, int sz, bool in_place=true) { bool* out=NULL; if( in_place ) out = data; else out = new bool[sz]; for(int i=0; i<sz; i++) out[i] = !data[i]; return out; } /// extracts a square patch of patch_width x patch_width from a the /// image around the point ry,rx ; /// returns true if all the pixels are within the image and false /// if some of the pixels are outside the image. template<class T1, class T2> bool extract_patch( T1* dst, T1* src, int h, int w, T2 ry, T2 rx, int patch_width ) { float w_2 = patch_width/2; float x,y; float yy, xx; bool out_of_image = true; int index=0; for( y=0; y<patch_width; y++ ) { for( x=0; x<patch_width; x++ ) { yy = ry + y - w_2; xx = rx + x - w_2; if( is_outside( xx, 0, w, yy, 0, h ) ) { dst[index] = 0; out_of_image = false; } else { dst[ index ] = (T1)bilinear_interpolation( src, w, xx, yy ); } index++; } } return out_of_image; } /// extracts a square patch of patch_width x patch_width from a /// rotated image around the point ry,rx ; rotation_angle is in /// radians. returns true if all the pixels are within the image /// and false if some of the pixels are outside the image. template<class T1, class T2, class T3> bool extract_rotated_patch( T1* dst, T1* src, int h, int w, T2 ry, T2 rx, int patch_width, T3 rotation_angle ) { int w_2 = patch_width/2; float kos = cos( rotation_angle ); float zin = sin( rotation_angle ); int yp, xp; float yu, xu; float y, x; int index = 0; bool out_of_image = true; for( yp=0; yp<patch_width; yp++ ) { for( xp=0; xp<patch_width; xp++ ) { xu = xp-w_2; yu = yp-w_2; x = kos * xu - zin * yu + rx; y = zin * xu + kos * yu + ry; if( is_inside( x, 0, w, y, 0, h ) ) { dst[ index ] = (T1)bilinear_interpolation(src, w, x, y); } else { dst[ index ] = 0; out_of_image = false; } index++; } } return out_of_image; } /// extracts a portion of the matrix [ymin:ymax) & [xmin:xmax) /// and returns the result. /// note: you should deallocate the dst memory yourself /// note: upper boundaries are not included in the output matrix template<class T> T* extract( T* src, int xmin, int xmax, int ymin, int ymax, int matw) { int xsz = xmax - xmin; int ysz = ymax - ymin; T* dst = new T[ysz*xsz]; int yy=0; int xx=0; for( int y=ymin; y<ymax; y++ ) { xx=0; for( int x=xmin; x<xmax; x++ ) { dst[yy*xsz+xx] = src[y*matw+x]; xx++; } yy++; } return dst; } /// extracts a portion of the matrix [ymin:ymax) & [xmin:xmax) /// and returns the result. /// note: you should deallocate the dst memory yourself /// note: upper boundaries are not included in the output matrix template<class T> T* crop( T* src, int h, int w, int center_y, int center_x, int patch_rad) { int pw = 2*patch_rad+1; int psz = pw*pw; T* dst = new T[psz]; initialize( dst, psz, 0); int yy, xx; for( yy = -patch_rad; yy<=patch_rad; yy++ ) { if( yy + center_y < 0 || yy + center_y > h ) continue; for( xx = -patch_rad; xx<=patch_rad; xx++ ) { if( xx+center_x < 0 || xx+center_x > w ) continue; dst[ ( yy+patch_rad ) * pw + xx + patch_rad ] = src[ (yy+center_y)*w+xx+center_x ]; } } return dst; } /// extracts a portion of the matrix [ymin:ymax) & [xmin:xmax) /// and returns the result in the given pointer. /// note: you should allocate the dst memory yourself /// note: upper boundaries are not included in the output matrix template<class T> void extract( T* dst, T* src, int xmin, int xmax, int ymin, int ymax, int mw) { int xsz = xmax - xmin; int yy=0; int xx=0; for( int y=ymin; y<ymax; y++ ) { xx=0; for( int x=xmin; x<xmax; x++ ) { dst[yy*xsz+xx] = src[y*mw+x]; xx++; } yy++; } } /// extracts a portion of the matrix [ymin:ymax) & [xmin:xmax) /// and returns the result in the given pointer. /// note: you should deallocate the dst memory yourself /// note: upper boundaries are not included in the output matrix template<class T> T** extract( T** src, int xmin, int xmax, int ymin, int ymax) { int xsz = xmax - xmin; int ysz = ymax - ymin; T** dst = allocate<T>(ysz,xsz); int yy=0; int xx=0; for( int y=ymin; y<ymax; y++ ) { xx=0; for( int x=xmin; x<xmax; x++ ) { dst[yy][xx] = src[y][x]; xx++; } yy++; } return dst; } /// extracts a portion of the matrix [ymin:ymax) & [xmin:xmax) /// and returns the result in the given pointer. /// note: you should allocate the dst memory yourself /// note: upper boundaries are not included in the output matrix template<class T> void extract( T** dst, T** src, int xmin, int xmax, int ymin, int ymax) { int yy=0; int xx=0; for( int y=ymin; y<ymax; y++ ) { xx=0; for( int x=xmin; x<xmax; x++ ) { dst[yy][xx] = src[y][x]; xx++; } yy++; } } /// rounds a number: if real part is bigger than 0,5 rounds up else down template<class T> inline T round( T x ) { T fx = floor(x); if( x-fx > 0.5 ) return fx+1; else return fx; } /// rounds an array of numbers: if real part is bigger than 0,5 /// rounds up else down. template<class T> inline T* round( T* x, int sz, bool in_place = false ) { T* out; if( in_place ) out = x; else out = allocate<T>(sz); for( int i=0; i<sz; i++ ) { out[i] = round(x[i]); } return out; } // /// filters the image with a filter. // float* filter_2d(float* &im, int r, int c, float* filter, int fr, int fc, bool in_place=false); /// r & c is the size of the image and filter has fr, fc size. it /// supports in place filtering. it uses simple for loops and does /// not employs a fast convolution implementation. beware: it is /// not equal to convolution - it does not invert the filter. template<class T> T* filter_2d(T* &im, int r, int c, T* filter, int fr, int fc, bool in_place) { int y,x; int yy,xx; int ya,xa; int yc, yac; int fr_half = fr/2; int fc_half = fc/2; int sz = r*c; T* out = allocate<T>(sz); initialize(out, sz, 0); T sum; int findex=0; for( y=0; y<r; y++ ) { ya = y - fr_half-1; yc = y*c; for( x=0; x<c; x++ ) { sum = 0; xa = x-fc_half-1; findex=0; for( yy=0; yy<fr; yy++ ) { ya++; if( is_outside(ya, 0, r) ) { findex += fc; continue; } yac = ya*c; for( xx=0; xx<fc; xx++ ) { xa++; if( is_outside(xa,0,c) ) { findex++; continue; } sum += im[yac+xa]*filter[findex++]; } xa -= fc; } ya -= fr; out[yc++] = sum; } } if( in_place ) { delete []im; im = out; } return out; } /// returns an array filled with ones. template<class T> inline T* ones (int r) { T* data = allocate<T>(r); for( int i=0; i<r; i++ ) data[i] = 1; return data; } /// returns an array filled with zeroes. template<class T> inline T* zeros(int r) { T* data = allocate<T>(r); memset( data, 0, sizeof(T)*r ); return data; } /// computes the square of a number and returns it. template<class T> inline T square(T a) { return a*a; } /// computes the square of an array. if in_place is enabled, the /// result is returned in the array arr. template<class T> inline T* square(T* arr, int sz, bool in_place=false) { T* out; if( in_place ) out = arr; else out = allocate<T>(sz); for( int i=0; i<sz; i++ ) out[i] = arr[i]*arr[i]; return out; } /// computes the p power of a number and returns it. template<class T1, class T2> inline T1 power(T1 a, T2 p) { return (T1)pow(a,p); } /// computes the p power of an array. if in_place is enabled, the /// result is returned in the array arr. template<class T1, class T2> inline T1* power(T1* arr, int sz, T2 p, bool in_place=false) { T1* out; if( in_place ) out = arr; else out = allocate<T1>(sz); for( int i=0; i<sz; i++ ) out[i] = power(arr[i],p); return out; } /// returns the theta component of a point in the range -PI to PI. template<class T> inline float angle(T x, T y) { return atan2( (float)y, (float)x ); } /// returns the theta component of a point array in the range -PI to PI. template<class T> inline float* angle(T* x, T* y, int lsz) { float* ang = allocate<float>(lsz); for( int k=0; k<lsz; k++ ) { ang[k] = angle<T>(x[k],y[k]); } return ang; } /// returns the radial component of a point. template<class T> inline T magnitude(T x, T y) { return sqrt(x*x+y*y); } /// computes the radial component of a 2D array and returns the /// result in a REAL array. the x&y coordinates are given in /// separate 1D arrays together with their size. template<class T> inline T* magnitude(T* arrx, T* arry, int lsz) { T* mag = allocate<T>(lsz); for( int k=0; k<lsz; k++ ) { mag[k] = sqrt( arrx[k]*arrx[k] + arry[k]*arry[k] ); } return mag; } /// Converts the given cartesian coordinates of a point to polar /// ones. template<class T> inline void cartesian2polar(T x, T y, float &r, float &th) { r = magnitude(x,y); th = angle(x,y); } /// Converts the given polar coordinates of a point to cartesian /// ones. template<class T1, class T2> inline void polar2cartesian(T1 r, T1 t, T2 &y, T2 &x) { x = (T2)( r * cos( t ) ); y = (T2)( r * sin( t ) ); } /// returns an interval list that starts at "st" and ends at "en" /// having "level_no" levels. The list has entries like : /// [ s1 e1 ; /// s2 e2 ; /// .... /// sn en ] -> s(i+1) = e(i) /// the function uses upto 4 point precisions if not specified template<class T> inline T** interval( T st, T en, int levels, int prec=4) { T** interval_list = allocate<T>(levels, 2); float step = ((float)(en-st))/levels; for( int i=0; i<levels; i++ ) { interval_list[i][0] = i*step+st; interval_list[i][1] = i*step+st+step; } return interval_list; } /// computes the gradient of an image and returns the result in /// pointers to REAL. template <class T> inline void gradient(T* im, int h, int w, T* dy, T* dx) { assert( dx != NULL ); assert( dy != NULL ); for( int y=0; y<h; y++ ) { int yw = y*w; for( int x=0; x<w; x++ ) { int ind = yw+x; // dx if( x>0 && x<w-1 ) dx[ind] = ((T)im[ind+1]-(T)im[ind-1])/2.0; if( x==0 ) dx[ind] = ((T)im[ind+1]-(T)im[ind]); if( x==w-1 ) dx[ind] = ((T)im[ind ]-(T)im[ind-1]); //dy if( y>0 && y<h-1 ) dy[ind] = ((T)im[ind+w]-(T)im[ind-w])/2.0; if( y==0 ) dy[ind] = ((T)im[ind+w]-(T)im[ind]); if( y==h-1 ) dy[ind] = ((T)im[ind] -(T)im[ind-w]); } } } template<class T> inline T is_positive( T number ) { if( number > 0 ) return number; else return (T)(0); } template<class T> inline T* layered_gradient( T* data, int h, int w, int layer_no=8 ) { int data_size = h * w; T* layers = zeros<T>(layer_no * data_size); // smooth the data matrix T* bdata = blur_gaussian_2d<T,T>( data, h, w, 0.5, 5, false); T *dx = new T[data_size]; T *dy = new T[data_size]; gradient(bdata, h, w, dy, dx); deallocate( bdata ); #if defined(WITH_OPENMP) #pragma omp parallel for #endif for( int l=0; l<layer_no; l++ ) { float angle = 2*l*pi()/layer_no; float kos = cos( angle ); float zin = sin( angle ); T* layer_l = layers + l*data_size; for( int index=0; index<data_size; index++ ) { float value = kos * dx[ index ] + zin * dy[ index ]; if( value > 0 ) layer_l[index] = value; else layer_l[index] = 0; } } deallocate(dy); deallocate(dx); return layers; } /// be careful, 'data' is destroyed afterwards template<class T> inline void layered_gradient( T* data, int h, int w, int layer_no, T* layers, T* workspace=0, int lwork=0 ) { (void) workspace; int data_size = h * w; assert(layers!=NULL); memset(layers,0,sizeof(T)*data_size*layer_no); bool empty=false; T* work=NULL; if( lwork < 3*data_size ) { work = new T[3*data_size]; empty=true; } // // smooth the data matrix // T* bdata = blur_gaussian_2d<T,T>( data, h, w, 0.5, 5, false); float kernel[5]; gaussian_1d(kernel, 5, 0.5, 0); memcpy( work, data, sizeof(T)*data_size); convolve_sym( work, h, w, kernel, 5 ); T *dx = work+data_size; T *dy = work+2*data_size; gradient( work, h, w, dy, dx ); #if defined(WITH_OPENMP) #pragma omp parallel for #endif for( int l=0; l<layer_no; l++ ) { float angle = 2*l*pi()/layer_no; float kos = cos( angle ); float zin = sin( angle ); T* layer_l = layers + l*data_size; for( int index=0; index<data_size; index++ ) { float value = kos * dx[ index ] + zin * dy[ index ]; if( value > 0 ) layer_l[index] = value; else layer_l[index] = 0; } } if( empty ) delete []work; } /// computes the bilinearly interpolated value of the point (x,y). template<class T1, class T2> inline float bilinear_interpolation(T1* arr, int w, T2 x, T2 y) { int mnx = (int)floor( x ); int mny = (int)floor( y ); int mxx = (int) ceil( x ); int mxy = (int) ceil( y ); double alfa = mxx - x; double beta = mxy - y; if( alfa < 0.001 ) alfa = 0; if( beta < 0.001 ) beta = 0; int mnyw = mny * w; int mxyw = mxy * w; if( alfa < 0.001 ) return float(beta * arr[mnyw+mxx] + (1-beta) * arr[mxyw+mxx]); if( alfa > 0.999 ) return float(beta * arr[mnyw+mnx] + (1-beta) * arr[mxyw+mnx]); if( beta < 0.001 ) return float(alfa * arr[mxyw+mnx] + (1-alfa) * arr[mxyw+mxx]); if( beta > 0.999 ) return float(alfa * arr[mnyw+mnx] + (1-alfa) * arr[mnyw+mxx]); return float( beta*(alfa * arr[mnyw+mnx] + (1-alfa)*arr[mnyw+mxx] ) +(1-beta)*(alfa * arr[mxyw+mnx] + (1-alfa)*arr[mxyw+mxx] ) ); } /// divides the elements of the array with "norm". function /// supports in-place operations in which case the result is casted /// to the input type; default is non-in-place. template<class T1, class T2> inline T2* normalize(T1* data, int sz, T2 norm, bool in_place=false) { assert( norm != 0.0 ); float inv_norm = 1.0/norm; if( in_place ) { for( int i=0; i<sz; i++ ) { data[i] = (T1)(data[i]*inv_norm); } return NULL; } else { T2* new_data = allocate<T2>(sz); for( int i=0; i<sz; i++ ) { new_data[i] = (T2)(data[i]*inv_norm); } return new_data; } } template<typename T> inline void diff( const T* a, const T* b, const int sz, T* a_m_b) { for( int k=0; k<sz; k++ ) a_m_b[k] = a[k] - b[k]; } /// computes the difference of two arrays and returns the resulting /// array. function supports in place operation, and returns the /// result in the "a" array if in place is enabled. template<class T> inline T* diff( T* a, const T* b, const int sz, bool in_place=false) { T* d=NULL; if( in_place ) d = a; else d = allocate<T>(sz); for( int k=0; k<sz; k++ ) { d[k] = a[k]-b[k]; } return d; } /// computes the absolute difference of two arrays and returns the /// resulting array : d = |a-b|. function supports in place /// operation, and returns the result in the "a" array if in place /// is enabled. template<class T> inline T* absdiff( T* a, T* b, int sz, bool in_place=false) { T* d=NULL; if( in_place ) d = a; else d = allocate<T>(sz); for( int k=0; k<sz; k++ ) { d[k] = (T)fabs(a[k]-b[k]); } return d; } /// computes the absolute difference of two matrices and returns /// the resulting matrix : d = |a-b|. function supports in place /// operation, and returns the result in the "a" matrix if in place /// is enabled. template<class T> inline T** absdiff( T** a, T** b, int ysz, int xsz, bool in_place=false) { T** d=NULL; if( in_place ) d = a; else d = allocate<T>(ysz,xsz); for( int y=0; y<ysz; y++ ) { for( int x=0; x<xsz; x++ ) { d[y][x] = fabs(a[y][x]-b[y][x]); } } return d; } /// computes the l1norm of an array: sum_i( |a(i)| ) template<class T> inline T l1norm( T* a, int sz) { T norm=0; for( int k=0; k<sz; k++ ) norm += abs( a[k] ); } /// computes the l1norm of the difference of two arrays: sum_i( a(i)-b(i) ) template<class T> inline T l1norm( T* a, T* b, int sz) { T norm=0; for( int k=0; k<sz; k++ ) norm += abs(a[k]-b[k]); return norm; } /// computes the l2norm of an array: [ sum_i( [a(i)]^2 ) ]^0.5 template<class T> inline float l2norm( T* a, int sz) { float norm=0; for( int k=0; k<sz; k++ ) norm += a[k]*a[k]; return sqrt(norm); } /// computes the l2norm of the difference of two arrays: [ sum_i( [a(i)-b(i)]^2 ) ]^0.5 template<class T1, class T2> inline float l2norm( T1* a, T2* b, int sz) { float norm=0; for( int i=0; i<sz; i++ ) { norm += square( (float)a[i] - (float)b[i] ); } norm = sqrt( norm ); return norm; } template<class T> inline float l2norm( T y0, T x0, T y1, T x1 ) { float d0 = x0 - x1; float d1 = y0 - y1; return sqrt( d0*d0 + d1*d1 ); } /// computes the l2 norm of the difference of two arrays by /// weighting regions of them. if reg is set to -1 (or not /// specified) each difference is weighted. if reg is not -1, /// arrays are assumed to be composed of sz/reg segments and the /// weighting is applied to these segments. reg must be a integer /// multiple of sz. template<class T1, class T2> inline float weighted_l2_norm(T1* a, T1* b, int sz, T2* w=NULL, int reg=-1) { if( w == NULL ) error("weight array is NULL. use more efficient l2norm instead"); int wsz; if( reg == -1 ) wsz = sz; else wsz = reg; int rsz = sz / reg; if( rsz*reg != reg ) error("reg must be an integer multiple of array size sz"); int k; float norm=0; float sub_norm=0; for( k=0; k<wsz; k++ ) { sub_norm = l2norm( a+k*rsz, b+k*rsz, rsz ); norm += w[k] * sub_norm; } return norm; } template<class T1, class T2> inline float mean_absolute_difference( T1* arr1, T2* arr2, int size) { float mad_score=0; for( int i=0; i<size; i++ ) { mad_score += fabs( (float)arr1[i] - (float)arr2[i] ); } return mad_score/size; } /// adds a constant number to every number in the array; template<class T1, class T2> inline T1* add(T1* arr, int sz, T2 num, bool in_place=false) { T1* out; if( in_place ) out = arr; else out = allocate<T1>(sz); for( int i=0; i<sz; i++ ) { out[i] = arr[i] + (T1)num; } return out; } /// adds a constant number to every number in the matrix; template<class T1, class T2> inline T1** add(T1** arr, int ysz, int xsz, T2 num, bool in_place=false) { T1** out; if( in_place ) out = arr; else out = allocate<T1>(ysz,xsz); for( int y=0; y<ysz; y++ ) for( int x=0; x<xsz; x++ ) { out[y][x] = arr[y][x] + (T1)num; } return out; } /// subtracts a constant number from every element in the array; template<class T1, class T2> inline T1* subt(T1* arr, int sz, T2 num, bool in_place=false) { T1* out = add(arr,sz,-num,in_place); return out; } /// subtracts a constant number from every element in the matrix; template<class T1, class T2> inline T1** subt(T1** arr, int ysz, int xsz, T2 num, bool in_place=false) { T1* out = add(arr,ysz,xsz,-num,in_place); return out; } /// divides the elements of the array with num template<class T1, class T2> inline void divide(T1* arr, int sz, T2 num ) { float inv_num = 1.0 / num; for( int i=0; i<sz; i++ ) { arr[i] = (T1)(arr[i]*inv_num); } } /// thresholds the data. template<class T> inline T* threshold(T* data, int sz, T threshold) { if(sz == 0) return NULL; T* result = allocate<T>(sz); for(int i=0; i<sz; i++) { if( data[i] > threshold ) result[i] = 1; else result[i] = 0; } return result; } /// returns the sign of a point. template<class T> inline int sign(T num) { if( num < 0.0 ) return -1; if( num == 0.0 ) return 0; if( num > 0.0 ) return 1; } /// returns the sign array of an array. template<class T> inline int* sign(T* arr, int sz) { int* out = allocate<int>(sz); for( int k=0; k<sz; k++ ) { out[k] = sign( arr[k] ); } return out; } template<class T> inline int compare( const void* a, const void* b ) { return (int)(*(T*)a - *(T*)b); } /// sorts the data array "data". template<class T> inline T* quick_sort( T* data, int dsz, bool in_place=true) { T* out=NULL; if( in_place ) out = data; else out = clone(data, dsz); std::qsort( out, dsz, sizeof(T), compare<T> ); return out; } template<class T> inline T median(T* data, int dsz) { T* tmp = quick_sort(data, dsz, false); T med=0; if( dsz%2 == 1 ) med = tmp[ dsz/2 ]; else med = (tmp[ dsz/2 ] + tmp[ dsz/2 - 1 ] ) /2; deallocate(tmp); return med; } /// computes the median of the array: destroys the contents of the data array. template<typename T> inline void median( T* data, int sz, T &medval ) { std::qsort(data, sz, sizeof(T), compare<T> ); if( sz%2 == 1 ) medval = data[sz/2]; else medval = (data[sz/2]+data[sz/2-1])/2; } template<typename T> inline void smooth_median( T* data, int h, int w, int msz, T* out ) { int wsz=(2*msz+1)*(2*msz+1); const static int max_buffer_size = 441; assert( wsz < max_buffer_size ); T buffer[max_buffer_size]; for( int y=0; y<h; y++ ) { for( int x=0; x<w; x++ ) { int cnt = 0; for( int r=-msz; r<=msz; r++ ) { int yy = y+r; if( yy >= h ) yy = h-1; if( yy < 0 ) yy = 0; for( int c=-msz; c<=msz; c++ ) { int xx=x+c; if( xx >= w ) xx = w-1; if( xx < 0 ) xx = 0; buffer[cnt++] = data[yy*w+xx]; } } median( buffer, wsz, out[y*w+x] ); } } } /// multiplies two arrays element by element. /// the result is in the first array's type template<class T1, class T2> inline T1* times( T1* arr1, T2* arr2, int w) { T1* out = allocate<T1>(w); for( int i=0; i<w; i++ ) out[i] = (T1)(arr1[i]*arr2[i]); return out; } /// multiplies two matrices element by element. /// the result is in the first matrix's type template<class T1, class T2> inline T1** times( T1** mat1, T2** mat2, int h, int w) { T1** out = allocate<T1*>(h); for( int i=0; i<h; i++ ) out[i] = times( mat1[i], mat2[i], w ); return out; } /// convert a ** data to a * data in row-first order. /// it uses memcpy, therefore, works for built-in types. template<class T> inline T* arrayize(T** data, int xsz, int ysz) { T* out = allocate<T>(xsz*ysz); for( int i=0; i<ysz; i++ ) memcpy(out[i*xsz],data[i],sizeof(T)*xsz); return out; } /// inplace shifting: accepts negative shifts template<class T> T* shift_array(T* arr, int size, int shift) { // if shift = 0 -> you can return now if( shift == 0 ) return arr; T* temp_array = allocate<T>(size); // if negative -> compansate if( shift < 0 ) shift += size; // copy the first portion memcpy(temp_array, arr+shift, sizeof(T)*(size-shift) ); // copy the rest memcpy(temp_array+size-shift, arr, sizeof(T)*shift ); memcpy(arr,temp_array,size); deallocate(temp_array); return arr; } /// shifts the contents of the array in segmented regions /// i.e: shifts the contents by "shift" in a segment /// size = n*segment, n = integer template<class T> T* segmented_shift_array(T* &arr, int size, int segment, int shift) { int segment_step = size / segment; if( shift == 0 ) return arr; for( int s=0; s<size; s += segment_step ) { shift_array(arr+s, segment_step, shift); } return arr; } /// counts the number of times the value val occurs in data[] template<class T> inline int count( T* data, int sz, T val) { int counter = 0; for(int i=0; i<sz; i++) { if( data[i] == val ) counter++; } return counter; } template<class T1, class T2> inline void set(T1* data, int sz, T2 val) { for( int k=0; k<sz; k++ ) data[k]=(T1)val; } template<class T1, class T2> inline void set(T1** data, int rsz, int csz, T2 val) { for( int r=0; r<rsz; r++ ) for( int c=0; c<csz; c++ ) data[r][c]=(T1)val; } /// rotates x1 y1 by theta (in radians) template<class T1, class T2> inline void rotate( T1 y1, T1 x1, T2& y2, T2& x2, float theta, T1 ty, T1 tx ) { float kos = cos( theta ); float zin = sin( theta ); x2 = (T2)( x1*kos - y1*zin ); y2 = (T2)( x1*zin + y1*kos ); return; } /// rotates the image with respect to ry, rx. template<class T> inline T* rotate( T* imge, int h, int w, float theta, float ry=0, float rx=0 ) { float kos = cos(theta); float zin = sin(theta); int x, y; T* rimge = allocate<T>(h*w); initialize(rimge, h*w, 0); float ty, tx; float ny, nx; for( y=0; y<h; y++ ) { for( x=0; x<w; x++ ) { tx = x - rx; ty = y - ry; nx = ( tx * kos - ty * zin + rx ); ny = ( tx * zin + ty * kos + ry ); if( is_inside( nx, 0, w-1, ny, 0, h-1 ) ) rimge[y*w+x] = (T)bilinear_interpolation(imge, w, nx, ny); } } return rimge; } /// stretches the image to minI=0 -- maxI=255 range template<class T> inline T* stretch(T* image, int sz, T val, bool in_place=false) { // find the min intensity in roi T min_inten=INT_MAX; T max_inten=INT_MIN; for( int k=0; k<sz; k++ ) { if( image[k] <= val ) continue; if( image[k] < min_inten ) min_inten = image[k]; if( image[k] > max_inten ) max_inten = image[k]; } float s = 255.0f/(float)(max_inten-min_inten); T* output = NULL; if( in_place ) output = image; else output = zeros<T>(sz); for( int k=0; k<sz; k++ ) { if( image[k] > val ) output[k] = (T)((image[k]-min_inten) * s); else output[k] = image[k]; } return output; } /// returns the number of digits of a number. inline int digit_number(int num) { if( num == 0 ) return 1; int counter = 0; while( num != 0 ) { num /= 10; counter++; } return counter; } /// returns the value of a sigmoid spanning miny-maxy with 'rate' /// and x-symmetry axis sym_axis. /// miny-maxy : the minimum and maximum interval for the y axis. /// rate : the rate at which the sigmoid reaches maxy from miny. /// sym_axis : symmetry axis in the x axis. sig(sx-d)+sig(sx+d) = maxy: /// sum of the y values from the symmetry point makes maxy. inline float sigmoid(float x, float miny, float maxy, float rate, float sym_axis) { float xp = exp(rate*(x-sym_axis)); return (maxy - miny) * xp / ( xp + 1 ) + miny; } /// returns the "and" of two boolean arrays. inline bool* and_array( bool* a, bool* b, int sz) { bool* c = allocate<bool>(sz); for( int i=0; i<sz; i++ ) c[i] = a[i] & b[i]; return c; } /// returns the "or" of two boolean arrays. inline bool* or_array( bool* a, bool* b, int sz) { bool* c = allocate<bool>(sz); for( int i=0; i<sz; i++ ) c[i] = a[i] | b[i]; return c; } /// finds the n local-modes: locals -> return indices, workspace[sz] template<typename T> inline void find_n_local_min(const T* arr, const int sz, int* locals, const int n, T* workspace ) { int min_count=0; for( int i=0; i<sz; i++ ) workspace[i] = -1; for( int i=0; i<n; i++ ) locals[i] = -1; T prev=INT_MAX; T next=INT_MAX; for( int i=0; i<sz; i++ ) { if( i > 0 ) prev = arr[i-1]; else prev = INT_MAX; if( i < sz-1 ) next = arr[i+1]; else next = INT_MAX; if( (arr[i] < prev) && (arr[i] < next) ) { workspace[min_count] = i; min_count++; } } // cout<<"mins\n"; // for( int i=0; i<min_count; i++ ) // { // cout<<workspace[i]<<" "; // if( workspace[i] != -1 ) cout<<arr[(int)workspace[i]]<<endl; // else cout<<-1<<endl; // } // cout<<endl; bool inserted=false; int fn=1; locals[0] = workspace[0]; for( int j=1; j<min_count; j++ ) { inserted=false; if( workspace[j] == -1 ) break; for( int k=0; k<fn; k++ ) { if( arr[ (int)workspace[j] ] <= arr[ locals[k] ] ) { shift_array_right( locals, n, k ); locals[k] = workspace[j]; if( fn < n ) fn++; inserted=true; break; } } if( !inserted && (fn < n) ) { locals[fn] = workspace[j]; fn++; } } for( int i=fn; i<n; i++ ) locals[i]=-1; // cout<<"locals\n"; // for( int i=0; i<n; i++ ) // { // cout<<locals[i]<<" "; // if( locals[i] != -1 ) cout<<arr[locals[i]]<<endl; // else cout<<-1<<endl; // } // cout<<endl; } } #endif
version https://git-lfs.github.com/spec/v1 oid sha256:df5a7287a63d8b28fe1df2552b7f2deaa719327f8aa49fef192f5fb72bbbbaad size 4023
'use strict'; var path = require('path'); var mergeTrees = require('broccoli-merge-trees'); var SassCompiler = require('../broccoli-sass'); function SASSPlugin() { this.name = 'ember-cli-sass'; this.ext = ['scss', 'sass']; } SASSPlugin.prototype.toTree = function(tree, inputPath, outputPath, inputOptions) { var options = inputOptions; var inputTrees = [tree]; if (options.includePaths) { inputTrees = inputTrees.concat(options.includePaths); } var ext = options.extension || 'scss'; var paths = options.outputPaths; var trees = Object.keys(paths).map(function(file) { var input = path.join(inputPath, file + '.' + ext); var output = paths[file]; return new SassCompiler(inputTrees, input, output, options); }); return mergeTrees(trees); }; module.exports = { name: 'ember-cli-sass', setupPreprocessorRegistry: function(type, registry) { registry.add('css', new SASSPlugin()); }, };
<?php /* * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\DBAL\Platforms; use Doctrine\DBAL\Schema\TableDiff, Doctrine\DBAL\Schema\Table; /** * PostgreSqlPlatform. * * @since 2.0 * @author Roman Borschel <roman@code-factory.org> * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library) * @author Benjamin Eberlei <kontakt@beberlei.de> * @todo Rename: PostgreSQLPlatform */ class PostgreSqlPlatform extends AbstractPlatform { /** * @var bool */ private $useBooleanTrueFalseStrings = true; /** * PostgreSQL has different behavior with some drivers * with regard to how booleans have to be handled. * * Enables use of 'true'/'false' or otherwise 1 and 0 instead. * * @param bool $flag */ public function setUseBooleanTrueFalseStrings($flag) { $this->useBooleanTrueFalseStrings = (bool)$flag; } /** * {@inheritDoc} */ public function getSubstringExpression($value, $from, $length = null) { if ($length === null) { return 'SUBSTRING(' . $value . ' FROM ' . $from . ')'; } return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $length . ')'; } /** * {@inheritDoc} */ public function getNowExpression() { return 'LOCALTIMESTAMP(0)'; } /** * {@inheritDoc} */ public function getRegexpExpression() { return 'SIMILAR TO'; } /** * {@inheritDoc} */ public function getLocateExpression($str, $substr, $startPos = false) { if ($startPos !== false) { $str = $this->getSubstringExpression($str, $startPos); return 'CASE WHEN (POSITION('.$substr.' IN '.$str.') = 0) THEN 0 ELSE (POSITION('.$substr.' IN '.$str.') + '.($startPos-1).') END'; } return 'POSITION('.$substr.' IN '.$str.')'; } /** * {@inheritDoc} */ public function getDateDiffExpression($date1, $date2) { return '(DATE(' . $date1 . ')-DATE(' . $date2 . '))'; } /** * {@inheritDoc} */ public function getDateAddDaysExpression($date, $days) { return "(" . $date ." + (" . $days . " || ' day')::interval)"; } /** * {@inheritDoc} */ public function getDateSubDaysExpression($date, $days) { return "(" . $date ." - (" . $days . " || ' day')::interval)"; } /** * {@inheritDoc} */ public function getDateAddMonthExpression($date, $months) { return "(" . $date ." + (" . $months . " || ' month')::interval)"; } /** * {@inheritDoc} */ public function getDateSubMonthExpression($date, $months) { return "(" . $date ." - (" . $months . " || ' month')::interval)"; } /** * {@inheritDoc} */ public function supportsSequences() { return true; } /** * {@inheritDoc} */ public function supportsSchemas() { return true; } /** * {@inheritDoc} */ public function supportsIdentityColumns() { return true; } /** * {@inheritDoc} */ public function supportsCommentOnStatement() { return true; } /** * {@inheritDoc} */ public function prefersSequences() { return true; } /** * {@inheritDoc} */ public function hasNativeGuidType() { return true; } public function getListDatabasesSQL() { return 'SELECT datname FROM pg_database'; } public function getListSequencesSQL($database) { return "SELECT c.relname, n.nspname AS schemaname FROM pg_class c, pg_namespace n WHERE relkind = 'S' AND n.oid = c.relnamespace AND (n.nspname NOT LIKE 'pg_%' AND n.nspname != 'information_schema')"; } public function getListTablesSQL() { return "SELECT tablename AS table_name, schemaname AS schema_name FROM pg_tables WHERE schemaname NOT LIKE 'pg_%' AND schemaname != 'information_schema' AND tablename != 'geometry_columns' AND tablename != 'spatial_ref_sys'"; } /** * {@inheritDoc} */ public function getListViewsSQL($database) { return 'SELECT viewname, definition FROM pg_views'; } public function getListTableForeignKeysSQL($table, $database = null) { return "SELECT r.conname, pg_catalog.pg_get_constraintdef(r.oid, true) as condef FROM pg_catalog.pg_constraint r WHERE r.conrelid = ( SELECT c.oid FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n WHERE " .$this->getTableWhereClause($table) ." AND n.oid = c.relnamespace ) AND r.contype = 'f'"; } public function getCreateViewSQL($name, $sql) { return 'CREATE VIEW ' . $name . ' AS ' . $sql; } public function getDropViewSQL($name) { return 'DROP VIEW '. $name; } public function getListTableConstraintsSQL($table) { return "SELECT relname FROM pg_class WHERE oid IN ( SELECT indexrelid FROM pg_index, pg_class WHERE pg_class.relname = '$table' AND pg_class.oid = pg_index.indrelid AND (indisunique = 't' OR indisprimary = 't') )"; } /** * {@inheritDoc} * * @license New BSD License * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html */ public function getListTableIndexesSQL($table, $currentDatabase = null) { return "SELECT relname, pg_index.indisunique, pg_index.indisprimary, pg_index.indkey, pg_index.indrelid FROM pg_class, pg_index WHERE oid IN ( SELECT indexrelid FROM pg_index si, pg_class sc, pg_namespace sn WHERE " . $this->getTableWhereClause($table, 'sc', 'sn')." AND sc.oid=si.indrelid AND sc.relnamespace = sn.oid ) AND pg_index.indexrelid = oid"; } /** * @param string $table * @param string $classAlias * @param string $namespaceAlias * * @return string */ private function getTableWhereClause($table, $classAlias = 'c', $namespaceAlias = 'n') { $whereClause = $namespaceAlias.".nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast') AND "; if (strpos($table, ".") !== false) { list($schema, $table) = explode(".", $table); $schema = "'" . $schema . "'"; } else { $schema = "ANY(string_to_array((select replace(setting,'\"\$user\"',user) from pg_catalog.pg_settings where name = 'search_path'),','))"; } $whereClause .= "$classAlias.relname = '" . $table . "' AND $namespaceAlias.nspname = $schema"; return $whereClause; } public function getListTableColumnsSQL($table, $database = null) { return "SELECT a.attnum, a.attname AS field, t.typname AS type, format_type(a.atttypid, a.atttypmod) AS complete_type, (SELECT t1.typname FROM pg_catalog.pg_type t1 WHERE t1.oid = t.typbasetype) AS domain_type, (SELECT format_type(t2.typbasetype, t2.typtypmod) FROM pg_catalog.pg_type t2 WHERE t2.typtype = 'd' AND t2.oid = a.atttypid) AS domain_complete_type, a.attnotnull AS isnotnull, (SELECT 't' FROM pg_index WHERE c.oid = pg_index.indrelid AND pg_index.indkey[0] = a.attnum AND pg_index.indisprimary = 't' ) AS pri, (SELECT pg_attrdef.adsrc FROM pg_attrdef WHERE c.oid = pg_attrdef.adrelid AND pg_attrdef.adnum=a.attnum ) AS default, (SELECT pg_description.description FROM pg_description WHERE pg_description.objoid = c.oid AND a.attnum = pg_description.objsubid ) AS comment FROM pg_attribute a, pg_class c, pg_type t, pg_namespace n WHERE ".$this->getTableWhereClause($table, 'c', 'n') ." AND a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid AND n.oid = c.relnamespace ORDER BY a.attnum"; } /** * {@inheritDoc} */ public function getCreateDatabaseSQL($name) { return 'CREATE DATABASE ' . $name; } /** * {@inheritDoc} */ public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey) { $query = ''; if ($foreignKey->hasOption('match')) { $query .= ' MATCH ' . $foreignKey->getOption('match'); } $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey); if ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false) { $query .= ' DEFERRABLE'; } else { $query .= ' NOT DEFERRABLE'; } if (($foreignKey->hasOption('feferred') && $foreignKey->getOption('feferred') !== false) || ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false) ) { $query .= ' INITIALLY DEFERRED'; } else { $query .= ' INITIALLY IMMEDIATE'; } return $query; } /** * {@inheritDoc} */ public function getAlterTableSQL(TableDiff $diff) { $sql = array(); $commentsSQL = array(); $columnSql = array(); foreach ($diff->addedColumns as $column) { if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) { continue; } $query = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray()); $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; if ($comment = $this->getColumnComment($column)) { $commentsSQL[] = $this->getCommentOnColumnSQL($diff->name, $column->getName(), $comment); } } foreach ($diff->removedColumns as $column) { if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) { continue; } $query = 'DROP ' . $column->getQuotedName($this); $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; } foreach ($diff->changedColumns as $columnDiff) { /** @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */ if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) { continue; } $oldColumnName = $columnDiff->oldColumnName; $column = $columnDiff->column; if ($columnDiff->hasChanged('type')) { $type = $column->getType(); // here was a server version check before, but DBAL API does not support this anymore. $query = 'ALTER ' . $oldColumnName . ' TYPE ' . $type->getSqlDeclaration($column->toArray(), $this); $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; } if ($columnDiff->hasChanged('default')) { $query = 'ALTER ' . $oldColumnName . ' SET ' . $this->getDefaultValueDeclarationSQL($column->toArray()); $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; } if ($columnDiff->hasChanged('notnull')) { $query = 'ALTER ' . $oldColumnName . ' ' . ($column->getNotNull() ? 'SET' : 'DROP') . ' NOT NULL'; $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; } if ($columnDiff->hasChanged('autoincrement')) { if ($column->getAutoincrement()) { // add autoincrement $seqName = $diff->name . '_' . $oldColumnName . '_seq'; $sql[] = "CREATE SEQUENCE " . $seqName; $sql[] = "SELECT setval('" . $seqName . "', (SELECT MAX(" . $oldColumnName . ") FROM " . $diff->name . "))"; $query = "ALTER " . $oldColumnName . " SET DEFAULT nextval('" . $seqName . "')"; $sql[] = "ALTER TABLE " . $diff->name . " " . $query; } else { // Drop autoincrement, but do NOT drop the sequence. It might be re-used by other tables or have $query = "ALTER " . $oldColumnName . " " . "DROP DEFAULT"; $sql[] = "ALTER TABLE " . $diff->name . " " . $query; } } if ($columnDiff->hasChanged('comment')) { $commentsSQL[] = $this->getCommentOnColumnSQL( $diff->name, $column->getName(), $this->getColumnComment($column) ); } if ($columnDiff->hasChanged('length')) { $query = 'ALTER ' . $column->getName() . ' TYPE ' . $column->getType()->getSqlDeclaration($column->toArray(), $this); $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; } } foreach ($diff->renamedColumns as $oldColumnName => $column) { if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) { continue; } $sql[] = 'ALTER TABLE ' . $diff->name . ' RENAME COLUMN ' . $oldColumnName . ' TO ' . $column->getQuotedName($this); } $tableSql = array(); if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { if ($diff->newName !== false) { $sql[] = 'ALTER TABLE ' . $diff->name . ' RENAME TO ' . $diff->newName; } $sql = array_merge($sql, $this->_getAlterTableIndexForeignKeySQL($diff), $commentsSQL); } return array_merge($sql, $tableSql, $columnSql); } /** * {@inheritdoc} */ public function getCommentOnColumnSQL($tableName, $columnName, $comment) { $comment = $comment === null ? 'NULL' : "'$comment'"; return "COMMENT ON COLUMN $tableName.$columnName IS $comment"; } /** * {@inheritDoc} */ public function getCreateSequenceSQL(\Doctrine\DBAL\Schema\Sequence $sequence) { return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) . ' INCREMENT BY ' . $sequence->getAllocationSize() . ' MINVALUE ' . $sequence->getInitialValue() . ' START ' . $sequence->getInitialValue(); } /** * {@inheritDoc} */ public function getAlterSequenceSQL(\Doctrine\DBAL\Schema\Sequence $sequence) { return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) . ' INCREMENT BY ' . $sequence->getAllocationSize(); } /** * {@inheritDoc} */ public function getDropSequenceSQL($sequence) { if ($sequence instanceof \Doctrine\DBAL\Schema\Sequence) { $sequence = $sequence->getQuotedName($this); } return 'DROP SEQUENCE ' . $sequence . ' CASCADE'; } /** * {@inheritDoc} */ public function getDropForeignKeySQL($foreignKey, $table) { return $this->getDropConstraintSQL($foreignKey, $table); } /** * {@inheritDoc} */ protected function _getCreateTableSQL($tableName, array $columns, array $options = array()) { $queryFields = $this->getColumnDeclarationListSQL($columns); if (isset($options['primary']) && ! empty($options['primary'])) { $keyColumns = array_unique(array_values($options['primary'])); $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')'; } $query = 'CREATE TABLE ' . $tableName . ' (' . $queryFields . ')'; $sql[] = $query; if (isset($options['indexes']) && ! empty($options['indexes'])) { foreach ($options['indexes'] as $index) { $sql[] = $this->getCreateIndexSQL($index, $tableName); } } if (isset($options['foreignKeys'])) { foreach ((array) $options['foreignKeys'] as $definition) { $sql[] = $this->getCreateForeignKeySQL($definition, $tableName); } } return $sql; } /** * {@inheritDoc} * * Postgres wants boolean values converted to the strings 'true'/'false'. */ public function convertBooleans($item) { if ( ! $this->useBooleanTrueFalseStrings) { return parent::convertBooleans($item); } if (is_array($item)) { foreach ($item as $key => $value) { if (is_bool($value) || is_numeric($item)) { $item[$key] = ($value) ? 'true' : 'false'; } } } else { if (is_bool($item) || is_numeric($item)) { $item = ($item) ? 'true' : 'false'; } } return $item; } public function getSequenceNextValSQL($sequenceName) { return "SELECT NEXTVAL('" . $sequenceName . "')"; } /** * {@inheritDoc} */ public function getSetTransactionIsolationSQL($level) { return 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level); } /** * {@inheritDoc} */ public function getBooleanTypeDeclarationSQL(array $field) { return 'BOOLEAN'; } /** * {@inheritDoc} */ public function getIntegerTypeDeclarationSQL(array $field) { if ( ! empty($field['autoincrement'])) { return 'SERIAL'; } return 'INT'; } /** * {@inheritDoc} */ public function getBigIntTypeDeclarationSQL(array $field) { if ( ! empty($field['autoincrement'])) { return 'BIGSERIAL'; } return 'BIGINT'; } /** * {@inheritDoc} */ public function getSmallIntTypeDeclarationSQL(array $field) { return 'SMALLINT'; } /** * {@inheritDoc} */ public function getGuidTypeDeclarationSQL(array $field) { return 'UUID'; } /** * {@inheritDoc} */ public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) { return 'TIMESTAMP(0) WITHOUT TIME ZONE'; } /** * {@inheritDoc} */ public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration) { return 'TIMESTAMP(0) WITH TIME ZONE'; } /** * {@inheritDoc} */ public function getDateTypeDeclarationSQL(array $fieldDeclaration) { return 'DATE'; } /** * {@inheritDoc} */ public function getTimeTypeDeclarationSQL(array $fieldDeclaration) { return 'TIME(0) WITHOUT TIME ZONE'; } /** * {@inheritDoc} */ public function getGuidExpression() { return 'UUID_GENERATE_V4()'; } /** * {@inheritDoc} */ protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) { return ''; } /** * {@inheritDoc} */ protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed) { return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)') : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)'); } /** * {@inheritDoc} */ public function getClobTypeDeclarationSQL(array $field) { return 'TEXT'; } /** * {@inheritDoc} */ public function getName() { return 'postgresql'; } /** * {@inheritDoc} * * PostgreSQL returns all column names in SQL result sets in lowercase. */ public function getSQLResultCasing($column) { return strtolower($column); } /** * {@inheritDoc} */ public function getDateTimeTzFormatString() { return 'Y-m-d H:i:sO'; } /** * {@inheritDoc} */ public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName) { return 'INSERT INTO ' . $quotedTableName . ' (' . $quotedIdentifierColumnName . ') VALUES (DEFAULT)'; } /** * {@inheritDoc} */ public function getTruncateTableSQL($tableName, $cascade = false) { return 'TRUNCATE '.$tableName.' '.(($cascade)?'CASCADE':''); } /** * {@inheritDoc} */ public function getReadLockSQL() { return 'FOR SHARE'; } /** * {@inheritDoc} */ protected function initializeDoctrineTypeMappings() { $this->doctrineTypeMapping = array( 'smallint' => 'smallint', 'int2' => 'smallint', 'serial' => 'integer', 'serial4' => 'integer', 'int' => 'integer', 'int4' => 'integer', 'integer' => 'integer', 'bigserial' => 'bigint', 'serial8' => 'bigint', 'bigint' => 'bigint', 'int8' => 'bigint', 'bool' => 'boolean', 'boolean' => 'boolean', 'text' => 'text', 'varchar' => 'string', 'interval' => 'string', '_varchar' => 'string', 'char' => 'string', 'bpchar' => 'string', 'inet' => 'string', 'date' => 'date', 'datetime' => 'datetime', 'timestamp' => 'datetime', 'timestamptz' => 'datetimetz', 'time' => 'time', 'timetz' => 'time', 'float' => 'float', 'float4' => 'float', 'float8' => 'float', 'double' => 'float', 'double precision' => 'float', 'real' => 'float', 'decimal' => 'decimal', 'money' => 'decimal', 'numeric' => 'decimal', 'year' => 'date', 'uuid' => 'guid', 'bytea' => 'blob', ); } /** * {@inheritDoc} */ public function getVarcharMaxLength() { return 65535; } /** * {@inheritDoc} */ protected function getReservedKeywordsClass() { return 'Doctrine\DBAL\Platforms\Keywords\PostgreSQLKeywords'; } /** * {@inheritDoc} */ public function getBlobTypeDeclarationSQL(array $field) { return 'BYTEA'; } }
--- index: 6 layout: guide title: Asynchronous code sidebar: guides_nav.html --- PouchDB provides a fully **asynchronous** API. This ensures that when you talk to PouchDB, the UI doesn't stutter, because the DOM is not being blocked by database operations. However, working with asynchronous code can be very complex, especially if you're only accustomed to synchronous APIs. So it's worth going over some of the basics. I promise to call you back... ------ To make things as flexible as possible for PouchDB users, the API is provided in both **callback** format and **promise** format. The **callback** format looks like this: ```js db.get('mittens', function (error, doc) { if (error) { // oh noes! we got an error } else { // okay, doc contains our document } }); ``` The **promise** format looks like this: ```js db.get('mittens').then(function (doc) { // okay, doc contains our document }).catch(function (err) { // oh noes! we got an error }); ``` Basically, if you include a callback as the last argument in a function, then PouchDB assumes you want the callback style. Otherwise it assumes you want the promise style. Let's talk about promises ------- For this guide, we will use the **promise** format for a few reasons: 1. Callbacks easily lead to spaghetti code, or to the [pyramid of doom](https://medium.com/@wavded/managing-node-js-callback-hell-1fe03ba8baf). 2. Promises generally lead to better code organization, although they do have a steep learning curve. If you already understand promises, you can [skip to the next section](updating-deleting.html). Understanding promises --------- If you have the time, you are strongly encouraged to watch [this 50-minute video: "Redemption from Callback Hell"](http://youtu.be/hf1T_AONQJU). The rest of this chapter basically summarizes that video. The best way to think of promises is that they bring keywords like `return` and `try/catch` to asynchronous code. Synchronous code: ```js function returnSomething() { try { doSomething(); doSomethingElse(); return true; } catch (err) { console.log(err); } } ``` Asynchronous code: ```js function returnSomething() { return doSomething().then(function () { return doSomethingElse(); }).then(function () { return true; }).catch(function (err) { console.log(err); }); } ``` Use `catch()` to catch errors -------- The big advantage of working with Promises in asynchronous code is that you can always attach a `catch` function to the end of a big promise chain, and any errors that occur along the way will show up at the end. This avoids endless `if (err) {}` checking in the callback world: ```js doSomething(function (err, result) { if (err) { // handle error } doSomethingElse(function (err, result) { if (err) { // handle error again... } doSomethingYetAgain(function (err, result) { if (err) { // seriously? okay, handle error again... } }); }); }); ``` Instead, in the promise world, you can have a long chain of asynchronous operations with a single `catch` at the end. To use PouchDB as an example: ```js db.put({_id: 'charlie', age: 21}).then(function () { return db.get('charlie'); }).then(function (charlie) { // increment Charlie's age charlie.age++; return db.put(charlie); }).then(function () { return db.get('charlie'); }).then(function (charlie) { // increment Charlie's age again charlie.age++; return db.put(charlie); }).then(function () { return db.get('charlie'); }).then(function (charlie) { console.log(charlie); }).catch(function (err) { console.log(err); }); ``` You should see: ```js {"age":23,"_id":"charlie","_rev":"3-e794618b4e39ed566cc68b56f5426e8e"} ``` You can see **[a live example](http://bl.ocks.org/nolanlawson/612f95cbbb69eaafc2d5)** of this code. In this example, we put/get a document 3 times in a row. At the very end, there is a `catch()` statement to catch any errors along the way. What kind of errors might we run into? Well, let's imagine that we accidentally misspell the id `'charlie'` at some point. In this case, we will gracefully catch the error. Here's another **[live example](http://bl.ocks.org/nolanlawson/0f1c815cb5fe74cff5fc)**. You should see: ```js {"status":404,"name":"not_found","message":"missing"} ``` This is really nice! No matter where the misspelling is, the error can be handled within a single function. That's much nicer than having to do `if (err){}` an endless number of times! An alternate way of catching errors ------- If you've been doing promises for awhile, you might have seen this instead: ```js db.get('charlie').then(function (charlie) { // we got the charlie doc }, function (err) { // we got an error }) ``` This is equivalent to: ```js db.get('charlie').then(function (charlie) { // we got the charlie doc }).catch(function (err) { // we got an error }) ``` The `catch()` method is just syntactic sugar. You can use either format. Promises 101 ------ The `then()` method takes a function. What can you do within this function? Three things: * Return another promise * Throw an error * Return a non-promise object (or `undefined`) Another way to think of it is this: ```js db.get('charlie').then(function (charlie) { // Within this function, you can do // try/catch/return like you normally would, // and it will be handled asynchronously! }).then(function (result) { // If the previous function returned something // (or returned undefined), it will show up here // as "result". }).catch(function (err) { // If the previous function threw an error, // it will show up here as "err". }); ``` Promises in PouchDB ------- Promises are supported natively in [some browsers](http://caniuse.com/#feat=promises). But since they're not universally supported, PouchDB uses [lie](https://github.com/calvinmetcalf/lie) in browsers that don't support them. In Node.js PouchDB uses [bluebird](https://github.com/petkaantonov/bluebird). You are free to integrate any Promise library you like with PouchDB, as long as it is compliant with [the Promises A+ spec](http://promisesaplus.com/). Some libraries that fit the bill: <ul> <li><a href="https://github.com/petkaantonov/bluebird">bluebird</a></li> <li><a href="https://github.com/calvinmetcalf/lie">lie</a></li> <li><a href="https://github.com/kriskowal/q">Q</a></li> <li><a href="https://github.com/tildeio/rsvp.js">RSVP</a></li> <li><a href="https://github.com/then/promise">then/promise</a></li> <li><a href="https://github.com/cujojs/when">when</a></li> </ul> If you use one of these libraries, then you will have access to some advanced Promise features. Read that library's documentation for details. Next ------ Now that you have a grasp on promises, let's learn about updating and deleting documents.
declare class X { a: number; static b: number; c: number; }
<?php namespace W3TC; if ( !defined( 'W3TC' ) ) die(); ?> <form class="w3tc_cdn_stackpath2_form" method="post"> <?php Util_Ui::hidden( '', 'api_config', $details['api_config'] ); ?> <div class="metabox-holder"> <?php Util_Ui::postbox_header( __( 'Select site to use', 'w3-total-cache' ) ); ?> <table class="form-table"> <tr> <td>Site:</td> <td> <?php if ( count( $details['sites'] ) > 15 ) { echo '<div style="width: 100%; height: 300px; overflow-y: scroll">'; } ?> <?php foreach ( $details['sites'] as $i ): ?> <label> <input name="site_id" type="radio" class="w3tc-ignore-change" value="<?php echo esc_attr( $i['id'] ) ?>" /> <?php echo esc_html( $i['label'] ) ?> </label><br /> <?php endforeach ?> <label> <input name="site_id" type="radio" class="w3tc-ignore-change" value="" /> Add new site: <?php echo esc_html( $details['new_hostname'] ) ?> </label> <?php if ( count( $details['sites'] ) > 15 ) { echo '</div>'; } ?> </td> </tr> </table> <p class="submit"> <input type="button" class="w3tc_cdn_stackpath2_configure_site w3tc-button-save button-primary" value="<?php _e( 'Apply', 'w3-total-cache' ); ?>" /> </p> <?php Util_Ui::postbox_footer(); ?> </div> </form>
/*! * jQuery UI Effects Fold 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/fold-effect/ */(function(e){typeof define=="function"&&define.amd?define(["jquery","./effect"],e):e(jQuery)})(function(e){return e.effects.effect.fold=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=s==="hide",a=t.size||15,f=/([0-9]+)%/.exec(a),l=!!t.horizFirst,c=o!==l,h=c?["width","height"]:["height","width"],p=t.duration/2,d,v,m={},g={};e.effects.save(r,i),r.show(),d=e.effects.createWrapper(r).css({overflow:"hidden"}),v=c?[d.width(),d.height()]:[d.height(),d.width()],f&&(a=parseInt(f[1],10)/100*v[u?0:1]),o&&d.css(l?{height:0,width:a}:{height:a,width:0}),m[h[0]]=o?v[0]:a,g[h[1]]=o?v[1]:0,d.animate(m,p,t.easing).animate(g,p,t.easing,function(){u&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()})}});
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title>JQuery JSONView</title> <link rel="stylesheet" href="jquery.jsonview.css" /> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script type="text/javascript" src="jquery.jsonview.js"></script> <script type="text/javascript"> var json = { "hey": "guy", "anumber": 243, "anobject": { "whoa": "nuts", "anarray": [1, 2, "thr<h1>ee"], "more":"stuff" }, "awesome": true, "bogus": false, "meaning": null, "japanese":"明日がある。", "link": "http://jsonview.com", "notLink": "http://jsonview.com is great", "multiline": ['Much like me, you make your way forward,', 'Walking with downturned eyes.', 'Well, I too kept mine lowered.', 'Passer-by, stop here, please.'].join("\n") }; $(function() { $("#json").JSONView(json); $("#json-collapsed").JSONView(json, { collapsed: true, nl2br: true, recursive_collapser: true }); $('#collapse-btn').on('click', function() { $('#json').JSONView('collapse'); }); $('#expand-btn').on('click', function() { $('#json').JSONView('expand'); }); $('#toggle-btn').on('click', function() { $('#json').JSONView('toggle'); }); $('#toggle-level1-btn').on('click', function() { $('#json').JSONView('toggle', 1); }); $('#toggle-level2-btn').on('click', function() { $('#json').JSONView('toggle', 2); }); }); </script> </head> <body> <h2>Data</h2> <button id="collapse-btn">Collapse</button> <button id="expand-btn">Expand</button> <button id="toggle-btn">Toggle</button> <button id="toggle-level1-btn">Toggle level1</button> <button id="toggle-level2-btn">Toggle level2</button> <div id="json"></div> <h2>Data Collapsed</h2> <div id="json-collapsed"></div> </body> </html>
/*-------------------------------------------------------------------------------------------- * * General * *--------------------------------------------------------------------------------------------*/ /* Horizontal List */ .acf-hl { padding: 0; margin: 0; list-style: none; display: block; position: relative; } .acf-hl > li { float: left; display: block; margin: 0; padding: 0; } .acf-hl > li.acf-fr { float: right; } /* Horizontal List: Clearfix */ .acf-hl:before, .acf-hl:after, .acf-bl:before, .acf-bl:after, .acf-cf:before, .acf-cf:after { content: ""; display: block; line-height: 0; } .acf-hl:after, .acf-bl:after, .acf-cf:after { clear: both; } /* Block List */ .acf-bl { padding: 0; margin: 0; list-style: none; display: block; position: relative; } .acf-bl > li { display: block; margin: 0; padding: 0; float: none; } /* Full width */ img.acf-fw { width: 100%; } /* icon */ [class^="acf-sprite-"] { display: block; width: 8px; height: 8px; float: left; background: url(../images/sprite.png); margin: 0; } /* Browser */ .acf-visible { display: block; visibility: visible; } .acf-hidden { display: none; visibility: visible; } /* Float */ .acf-fl { float: left; } .acf-fr { float: right; } .acf-fn { float: none; } /* Align */ .acf-al { text-align: left; } .acf-ar { text-align: right; } .acf-ac { text-align: center; } /* loading */ .acf-loading { display: inline-block; height: 20px; width: 20px; vertical-align: text-top; background: transparent url(../images/spinner.gif) no-repeat 50% 50%; } .acf-loading + .acf-button { margin-left: 3px; } /* required */ .acf-required { color: #f00; } /* show on hover */ .acf-soh .acf-soh-target { -webkit-transition: opacity 0.25s 0s ease-in-out, visibility 0s linear 0.25s; -moz-transition: opacity 0.25s 0s ease-in-out, visibility 0s linear 0.25s; -o-transition: opacity 0.25s 0s ease-in-out, visibility 0s linear 0.25s; transition: opacity 0.25s 0s ease-in-out, visibility 0s linear 0.25s; visibility: hidden; opacity: 0; } .acf-soh:hover .acf-soh-target { -webkit-transition-delay:0s; -moz-transition-delay:0s; -o-transition-delay:0s; transition-delay:0s; visibility: visible; opacity: 1; } /* show if value */ .show-if-value { display: none; } .hide-if-value { display: block; } .has-value .show-if-value { display: block; } .has-value .hide-if-value { display: none; } /* select2 WP animation fix */ .select2-search-choice-close { -webkit-transition: none; -moz-transition: none; -o-transition: none; transition: none; } /*--------------------------------------------------------------------------------------------- * * tooltip * *---------------------------------------------------------------------------------------------*/ .acf-tooltip { display: inline; position: relative; } .acf-tooltip:hover:after{ background: #333; background: rgba(0,0,0,.8); border-radius: 5px; bottom: 26px; color: #fff; content: attr(title); left: 20%; padding: 5px 15px; position: absolute; z-index: 98; width: 220px; } .acf-tooltip:hover:before{ border: solid; border-color: #333 transparent; border-width: 6px 6px 0 6px; bottom: 20px; content: ""; left: 50%; position: absolute; z-index: 99; } /*--------------------------------------------------------------------------------------------- * * callout * *---------------------------------------------------------------------------------------------*/ .acf-callout { margin: 20px 0; padding: 20px; background-color: #FCF8F2; border-left: 3px solid #F0AD4E; } .acf-callout h4 { color: #F0AD4E; margin: 0 !important; } .acf-callout p { margin-bottom: 0; } .acf-callout.danger { border-color: #D9534F; background-color: #FDF7F7; } .acf-callout.danger h4 { color: #D9534F; } .acf-callout.success { background-color: #f4faf6; border-color: #bcf1c5; } .acf-callout.success h4 { color: #3aad60; } /*-------------------------------------------------------------------------------------------- * * acf-icon * *--------------------------------------------------------------------------------------------*/ .acf-icon { display: block; height: 26px; width: 26px; border: #BBB solid 1px; border-radius: 15px; position: relative; overflow: hidden; font-size: 13px; line-height: 25px; text-align: center; background: #fff; } .acf-icon:hover { border-color: #999; } .acf-icon:active, .acf-icon:focus { outline: none; } /* sizes */ .acf-icon.small { width: 18px; height: 18px; line-height: 17px; } .acf-icon.large { width: 28px; height: 28px; line-height: 27px; } /* sprite */ .acf-icon [class^="acf-sprite-"] { position: absolute; top: 50%; left: 50%; margin: -4px 0 0 -4px; } /* styles */ .acf-icon.light { border: 0 none; padding: 1px; background: #F5F5F5; } .acf-icon.light:hover { background: #EBEBEB; } .acf-icon.dark { border: 0 none; padding: 1px; background: #0B0B0B; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25); } /* logo */ .acf-icon.logo { width: 150px; height: 150px; border-radius: 75px; background: #5EE8BF; border: 0 none; position: absolute; right: 0; top: 0; } /*-------------------------------------------------------------------------------------------- * * Sprite * *--------------------------------------------------------------------------------------------*/ /* add */ .acf-sprite-add { background-position: 0 0; width: 8px; height: 8px; } .acf-icon .acf-sprite-add { margin: -4px 0 0 -4px; } .acf-icon.dark .acf-sprite-add { background-position: 0 -50px; } .acf-sprite-add:hover, .acf-icon:hover .acf-sprite-add { background-position: 0 -100px; } /* remove */ .acf-sprite-remove { background-position: -50px 0; width: 9px; height: 2px; } .acf-icon .acf-sprite-remove { margin: -1px 0 0 -4px; } .acf-icon.dark .acf-sprite-remove { background-position: -50px -50px; } .acf-sprite-remove:hover, .acf-icon:hover .acf-sprite-remove { background-position: -50px -100px; } /* delete */ .acf-sprite-delete { background-position: -100px 0; width: 10px; height: 10px; } .acf-icon .acf-sprite-delete { margin: -5px 0 0 -5px; } .acf-icon.dark .acf-sprite-delete { background-position: -100px -50px; } .acf-sprite-delete:hover, .acf-icon:hover .acf-sprite-delete { background-position: -100px -100px; } /* edit */ .acf-sprite-edit { background-position: -150px 0; width: 14px; height: 14px; } .acf-icon .acf-sprite-edit { margin: -7px 0 0 -7px; } .acf-icon.dark .acf-sprite-edit { background-position: -150px -50px; } .acf-sprite-edit:hover, .acf-icon:hover .acf-sprite-edit { background-position: -150px -100px; } /* locate */ .acf-sprite-locate { background-position: -200px 0; width: 12px; height: 13px; } .acf-icon .acf-sprite-locate { margin: -6px 0 0 -7px; } .acf-icon.dark .acf-sprite-locate { background-position: -200px -50px; } .acf-sprite-locate:hover, .acf-icon:hover .acf-sprite-locate { background-position: -200px -100px; } /* left */ .acf-sprite-left { background-position: -250px 0; width: 6px; height: 10px; } .acf-icon .acf-sprite-left { margin: -5px 0 0 -4px; } .acf-icon.dark .acf-sprite-left { background-position: -250px -50px; } .acf-sprite-left:hover, .acf-icon:hover .acf-sprite-left { background-position: -250px -100px; } /* right */ .acf-sprite-right { background-position: -300px 0; width: 6px; height: 10px; } .acf-icon .acf-sprite-right { margin: -5px 0 0 -3px; } .acf-icon.dark .acf-sprite-right { background-position: -300px -50px; } .acf-sprite-right:hover, .acf-icon:hover .acf-sprite-right { background-position: -300px -100px; } /* arrow */ .acf-sprite-arrow { background-position: 0 -150px; margin: 4px 5px 0 7px; width: 16px; height: 16px; } /* gallery */ .acf-sprite-media { background-position: -50px -150px; width: 36px; height: 36px; } /* .acf-sprite-submit:hover, .acf-icon:hover .acf-sprite-submit { background-position: -250px -50px; } */ /* acf */ .acf-sprite-logo { background-position: -100px -150px; width: 100px; height: 46px; } .acf-icon .acf-sprite-logo { margin: -23px 0 0 -50px; } .acf-sprite-url { background-position: -350px 0; height: 14px; width: 14px; } /*-------------------------------------------------------------------------------------------- * * acf-box * *--------------------------------------------------------------------------------------------*/ .acf-box { background: #FFFFFF; border: 1px solid #E5E5E5; position: relative; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04); } .acf-box .title { border-bottom: 1px solid #EEEEEE; margin: 0; padding: 15px; background: #FFFFFF; } .acf-box .title h3 { font-size: 14px; line-height: 1em; margin: 0; padding: 0; } .acf-box .inner { padding: 15px; } .acf-box h2 { color: #333333; font-size: 25px; line-height: 29px; margin: 0.25em 0 0.75em; padding: 0; } .acf-box h3 { margin: 1.5em 0 0; } .acf-box p { margin-top: 0.5em; } .acf-box .footer { background: #F5F5F5; border-top: 1px solid #E1E1E1; overflow: hidden; padding: 15px; position: relative; } .acf-box .footer-blue { border-top: 0 none; background-color: #52ACCC; color: #FFFFFF; } .acf-box .footer-blue a { text-decoration: none; text-shadow: none; } .acf-box .footer .acf-hl > li { margin: 0 10px 0 0; } .acf-box .footer .acf-hl > li.acf-fr { margin: 0 0 0 10px; } /*-------------------------------------------------------------------------------------------- * * Basic ACF field wrap * *--------------------------------------------------------------------------------------------*/ .acf-field { margin: 0 0 20px; max-width: 1400px; } .acf-field .acf-label { vertical-align: top; margin: 0 0 10px; } .acf-field .acf-label label { display: block; font-weight: bold; font-size: 13px; line-height: 1.4em; margin: 0 0 3px; } .acf-field .acf-label p { color: #777777; display: block; font-size: 12px; line-height: 1.4em; font-style: normal; margin: 3px 0 0 !important; padding: 0 !important; } .acf-field .acf-input { vertical-align: top; } /* error */ .acf-error-message { position: relative; display: block; background: #F55E4F; border-radius: 3px; margin: 5px 0 15px; padding: 1px 10px; min-height: 0px; } .acf-error-message p { font-size: 12px !important; line-height: 14px; margin: 10px 0 !important; padding: 0; text-shadow: none; color: #fff; text-shadow: 0 1px 0 #DD4232; } /* field error */ .acf-field .acf-error-message { background: #F55E4F; color: #fff; margin: 0 0 10px; } .acf-field .acf-error-message:after { content: ""; display: block; width: 0; height: 0; border: transparent 5px solid; border-top-color: #F55E4F; display: block; position: absolute; bottom: -10px; left: 10px; } .acf-field .acf-error-message p { margin: 8px 0 !important; } /* add term */ #addtag div.acf-field.error { border: 0 none; padding: 8px 0; } /* widget */ .widget .widget-inside .acf-error-message p { margin: 10px 0; } .widget .widget-inside div.acf-field.error { border: 0 none; background: transparent; margin: 0 0 20px; padding: 0; } /* width */ .acf-field[data-width] { float: left; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .acf-field[data-width] + .acf-field { clear: left; } .acf-field[data-width] + .acf-field[data-width] { clear: none; border-left: 1px solid #eeeeee; } td.acf-field[data-width] { float: none; } /* field width helpers */ .acf-r0 { border-top: none !important; } .acf-c0 { clear: left !important; border-left: none !important; } /*-------------------------------------------------------------------------------------------- * * acf-table * *--------------------------------------------------------------------------------------------*/ .acf-table { background: #fff; border: 0 none; border-spacing: 0; border-radius: 0; table-layout: auto; padding: 0; margin: 0; width: 100%; clear: both; } .acf-table > thead > tr > th, .acf-table > tbody > tr > th { vertical-align: top; } .acf-table > tbody > tr > td { vertical-align: top; padding: 13px 15px; border: 0 none; border-top: 1px solid #F5F5F5; border-left: 1px solid #F5F5F5; } .acf-table > tbody > tr:first-child > td { border-top: 0; } .acf-table > tbody > tr > td:first-child { border-left: 0; } .acf-table td.acf-label { background: #F9F9F9; border-top-color: #F0F0F0; width: 24%; } .acf-table td.acf-input { border-left-color: #E1E1E1; } /* clear table */ .acf-clear-table > tbody > tr > td, .acf-clear-table > thead > tr > th { border: 0 none; padding: 4px; } /* input table */ .acf-input-table { border: 1px solid #F5F5F5; background: #F9F9F9; } /*-------------------------------------------------------------------------------------------- * * acf-button * *--------------------------------------------------------------------------------------------*/ .acf-button { position: relative; display: inline-block; border-radius: 3px; height: 28px; padding: 0 11px 1px; cursor: pointer; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; color: #333; font-weight: normal; font-size: 13px; line-height: 26px; text-align: center; text-decoration: none; background: #F9F9F9; border: #BBBBBB solid 1px; box-shadow: 0 1px 0 rgba(255, 255, 255, 0.25) inset; } .acf-button:hover { border-color: #999; color: #333; } .acf-button:focus, .acf-button:active { outline: none; line-height: 28px; } .acf-button:active { box-shadow: none; } .acf-button[disabled], .acf-button.disabled { background: #F7F7F7 !important; border-color: #DDDDDD !important; box-shadow: none !important; color: #AAAAAA !important; cursor: default !important; } /* sizes */ .acf-button.large { height: 32px; line-height: 31px; font-size: 14px; } /* all colors */ .acf-button.blue, .acf-button.green, .acf-button.orange { color: #fff !important; } /* blue */ .acf-button.blue { background-color: #2EA2CC; border-color: #0074A2; } .acf-button.blue:hover { background-color: #298CBA; } .acf-button.blue[disabled], .acf-button.blue.disabled { background: #298CBA !important; border-color: #1B607F !important; box-shadow: none !important; color: #94CDE7 !important; } /* orange */ .acf-button.orange { background: #e86740; background-image: -webkit-gradient(linear, left top, left bottom, from(#eb7551), to(#e05c37)); /* Safari 4+, Chrome */ background-image: -webkit-linear-gradient(top, #eb7551, #e05c37); /* Chrome 10+, Safari 5.1+, iOS 5+ */ background-image: -moz-linear-gradient(top, #eb7551, #e05c37); /* Firefox 3.6-15 */ background-image: -o-linear-gradient(top, #eb7551, #e05c37); /* Opera 11.10+ */ background-image: linear-gradient(to bottom, #eb7551, #e05c37); /* Firefox 16+ */ border: #c94c2a solid 1px; text-shadow: #c94c2a 0 1px 0; box-shadow: inset #f09674 0 1px 0 0; } /* green */ .acf-button.green { background: #2CB75A; background-image: -webkit-gradient(linear, left top, left bottom, from(#39CB69), to(#27B957)); /* Safari 4+, Chrome */ background-image: -webkit-linear-gradient(top, #39CB69, #27B957); /* Chrome 10+, Safari 5.1+, iOS 5+ */ background-image: -moz-linear-gradient(top, #39CB69, #27B957); /* Firefox 3.6-15 */ background-image: -o-linear-gradient(top, #39CB69, #27B957); /* Opera 11.10+ */ background-image: linear-gradient(to bottom, #39CB69, #27B957); /* Firefox 16+ */ border: #21B351 solid 1px; text-shadow: #21B351 0 1px 0; box-shadow: inset #4DDF7D 0 1px 0 0; } /*-------------------------------------------------------------------------------------------- * * acf-postbox * *--------------------------------------------------------------------------------------------*/ .acf-postbox { position: relative; } .acf-postbox > .inside, .acf-fields { margin: 0 !important; padding: 0 !important; position: relative; } .acf-fields > .acf-field { margin: 0; padding: 15px 12px; border-top: #EEEEEE solid 1px; } .acf-fields > .acf-field:first-child { border-top: 0 none; } /* seamless */ .acf-postbox.seamless { border: 0 none; background: transparent; box-shadow: none; } .acf-postbox.seamless > .hndle, .acf-postbox.seamless > .handlediv { display: none; } .acf-postbox.seamless > .acf-fields > .acf-field { margin: 0; padding: 15px 0; border: 0 none !important; } .acf-postbox.seamless > .acf-fields > .acf-table, .acf-postbox.seamless > .acf-fields > .acf-table > tbody > tr > td { background: none; border: 0 none; } .acf-postbox.seamless.closed .inside { display: block; } /* override WP CSS */ .metabox-prefs label.acf-hidden { display: none; } /*--------------------------------------------------------------------------------------------- * * wp-admin * *---------------------------------------------------------------------------------------------*/ /* Menu */ #adminmenu a[href="edit.php?post_type=acf-field-group&page=acf-upgrade"], #adminmenu a[href="edit.php?post_type=acf-field-group&page=acf-settings-info"] { display: none; } /*--------------------------------------------------------------------------------------------- * * Field Group List * *---------------------------------------------------------------------------------------------*/ #icon-edit.icon32-posts-acf-field-group { background-position: -11px -5px; } #acf-col-wrap { position: relative; clear: both; } #acf-col-main { margin-right: 300px; } #acf-col-main .tablenav, #acf-col-main p.search-box { display: none; } #acf-col-main .wp-list-table .check-column { padding-left: 5px; } #acf-col-main .wp-list-table th#fields { width: 25%; } #acf-col-main .tablenav.bottom { display: block; } #acf-col-main form { position: relative; float: left; width: 100%; } #acf-col-side { float: right; width: 281px; padding-top: 34px !important; } #acf-col-main .wp-list-table { border-radius: 0; } /*--------------------------------------------------------------------------------------------- * * Fake table * *---------------------------------------------------------------------------------------------*/ .acf-thead, .acf-tbody, .acf-tfoot { width: 100%; padding: 0; margin: 0; } .acf-thead > li, .acf-tbody > li, .acf-tfoot > li { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 8px 15px; font-size: 12px; line-height: 13px; } .acf-thead { background: #FFFFFF; border-bottom: #E1E1E1 solid 1px; } .acf-thead > li { font-size: 14px; line-height: 1.4em; font-family: "Open Sans",sans-serif; color: #222222; font-weight: bold; } .acf-tfoot { background: #EAF2FA; border-top: #c7d7e2 solid 1px; } .acf-tfoot > li { color: #7A9BBE; font-size: 12px; line-height: 27px; } .acf-tfoot > li.comic-sans { font-family: Comic Sans MS, sans-serif; font-size: 11px; } /*--------------------------------------------------------------------------------------------- * * Input Table * *---------------------------------------------------------------------------------------------*/ .acf-input-table { border: #DFDFDF solid 1px; } .acf-input-table > thead { } .acf-input-table > thead th { background: #fff; border-left: 1px solid #E1E1E1; border-bottom: 1px solid #E1E1E1; padding: 8px; position: relative; vertical-align: top; text-align: left; color: #333333; font-size: 14px; line-height: 1.4em; font-weight: normal; } .acf-input-table > tbody > tr { z-index: 1; } .acf-input-table > tbody > tr > td { padding: 8px; text-align: left; border-color: #EDEDED; background: #fff; } /* nested tables */ .acf-input-table > tbody > tr > td.acf-table-wrap { padding: 0; } /* order */ .acf-input-table > thead > tr > th.order, .acf-input-table > tbody > tr > td.order{ width: 16px !important; text-align: center !important; vertical-align: middle; } .acf-input-table > tbody > tr > td.order { border-right-color: #E1E1E1; background: #f4f4f4; cursor: move; color: #aaa; text-shadow: #fff 0 1px 0; } .acf-input-table > tbody > tr > td.order:hover { color: #666; } .acf-input-table > tbody > tr > td.order + td { border-left-color: #DFDFDF; } /* row block layout */ .acf-table.row-layout > tbody > tr > td, .acf-table.block-layout > tbody > tr > td { border-top-color: #E1E1E1; } /* remove */ .acf-input-table > thead > tr > th.remove, .acf-input-table > tbody > tr > td.remove{ width: 16px !important; vertical-align: middle; } .acf-input-table > tbody > tr > td.remove { background: #F9F9F9; } /* border limits */ .acf-input-table > thead > tr > th:first-child, .acf-input-table > tbody > tr > td:first-child { border-left-width: 0; } /* remove buttons */ .acf-input-table > tbody > tr > td.remove > .acf-icon { -webkit-transition: opacity 0.25s 0s ease-in-out, visibility 0s linear 0.25s; -moz-transition: opacity 0.25s 0s ease-in-out, visibility 0s linear 0.25s; -o-transition: opacity 0.25s 0s ease-in-out, visibility 0s linear 0.25s; transition: opacity 0.25s 0s ease-in-out, visibility 0s linear 0.25s; visibility: hidden; opacity: 0; } .acf-input-table > tbody > tr:hover > td.remove > .acf-icon { -webkit-transition-delay:0s; -moz-transition-delay:0s; -o-transition-delay:0s; transition-delay:0s; visibility: visible; opacity: 1; } /* media fix */ .media-item .describe .acf-input-table > thead > tr > th { width: auto; } /* remove tr */ .acf-remove-element { -webkit-transition: all 0.25s ease-out; -moz-transition: all 0.25s ease-out; -o-transition: all 0.25s ease-out; transition: all 0.25s ease-out; transform: translate(50px, 0); opacity: 0; } /*-------------------------------------------------------------------------------------------- * * User * *--------------------------------------------------------------------------------------------*/ .form-table .acf-label { padding: 10px; width: 200px; } .form-table th.acf-th { width: auto; } /*-------------------------------------------------------------------------------------------- * * Comment * *--------------------------------------------------------------------------------------------*/ .editcomment td:first-child { white-space: nowrap; width: 131px; } /*-------------------------------------------------------------------------------------------- * * Settings * *--------------------------------------------------------------------------------------------*/ .acf-settings-wrap { } .acf-settings-wrap .acf-box { margin: 20px 0; } /*-------------------------------------------------------------------------------------------- * * Settings: Add-ons * *--------------------------------------------------------------------------------------------*/ .add-ons-list { margin: 20px 0 0 -18px; max-width: 960px; } .add-ons-list .add-on { width: 220px; margin: 0 0 20px 18px; float: left; } .add-ons-list .add-on .inner { min-height: 90px; } .add-ons-list .add-on-acf-pro { width: 940px; } .add-ons-list .add-on .thumbnail { } .add-ons-list .add-on .thumbnail img { display: block; } .add-ons-list .add-on h3 a { color: inherit; text-decoration: none; } .add-ons-list .add-on h3 { margin: 0.5em 0; } /*-------------------------------------------------------------------------------------------- * * acf-popup * *--------------------------------------------------------------------------------------------*/ #acf-popup { position: fixed; z-index: 9999; top: 0; left: 0; right: 0; bottom: 0; } #acf-popup .bg { position: absolute; top: 0; left: 0; right: 0; bottom: 0; z-index: 0; background: rgba(0,0,0,0.25); } #acf-popup .acf-popup-box { position: absolute; z-index: 1; width: 300px; height: 300px; left: 50%; top: 50%; margin: -150px 0 0 -150px; border-color: #aaaaaa; } #acf-popup .title .acf-icon { position: absolute; top: 10px; right: 10px; } #acf-popup .acf-popup-box .inner, #acf-popup .acf-popup-box .loading { position: absolute; top: 44px; left: 0; right: 0; bottom: 0; z-index: 1; } #acf-popup .acf-popup-box .loading { background: rgba(0,0,0,0.1); z-index: 2; border-top: #DDDDDD solid 1px; display: none; } #acf-popup .acf-popup-box .loading .acf-loading { position: absolute; top: 50%; left: 50%; margin: -10px 0 0 -10px; } /*-------------------------------------------------------------------------------------------- * * upgrade notice * *--------------------------------------------------------------------------------------------*/ #acf-upgrade-notice { margin-left: -20px; background: #fff; border-bottom: #E5E5E5 solid 1px; } #acf-upgrade-notice .inner { padding: 20px; } #acf-upgrade-notice .logo { position: relative; float: left; } #acf-upgrade-notice .content { margin-left: 170px; max-width: 710px; } #acf-upgrade-notice h2 { } #acf-upgrade-notice p { font-size: 14px; } /*-------------------------------------------------------------------------------------------- * * Welcome * *--------------------------------------------------------------------------------------------*/ .acf-wrap { } .acf-wrap h1 { margin-top: 0; padding-top: 20px; } .acf-wrap .about-text { margin-top: 0.5em; min-height: 50px; } /*-------------------------------------------------------------------------------------------- * * RTL * *--------------------------------------------------------------------------------------------*/ html[dir="rtl"] .acf-fl { float: right; } html[dir="rtl"] .acf-fr { float: left; } html[dir="rtl"] .acf-hl > li { float: right; } html[dir="rtl"] .acf-hl > li.acf-fr { float: left; } html[dir="rtl"] .acf-icon.logo { left: 0; right: auto; } html[dir="rtl"] .acf-table > tbody > tr > td { border: 0 none; border-top: 1px solid #F5F5F5; border-right: 1px solid #F5F5F5; } html[dir="rtl"] .acf-table td.acf-input { border-left-color: #F5F5F5; border-right-color: #E1E1E1; } /*--------------------------------------------------------------------------------------------- * * Retina * *---------------------------------------------------------------------------------------------*/ @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and ( min--moz-device-pixel-ratio: 2), only screen and ( -o-min-device-pixel-ratio: 2/1), only screen and ( min-device-pixel-ratio: 2), only screen and ( min-resolution: 192dpi), only screen and ( min-resolution: 2dppx) { [class^="acf-sprite-"], [class*=" acf-sprite-"] { background-image: url(../images/sprite@2x.png); background-size: 500px 500px; } .acf-loading { background-image: url(../images/spinner@2x.gif); background-size: 20px 20px; } }
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #ifndef IPV6_END_POINT_H #define IPV6_END_POINT_H #include <stdint.h> #include "ns3/ipv6-address.h" #include "ns3/callback.h" namespace ns3 { class Header; class Packet; /** * \class Ipv6EndPoint * \brief An IPv6 end point, four tuples identification. */ class Ipv6EndPoint { public: /** * \brief Constructor. * \param addr the IPv6 address * \param port the port */ Ipv6EndPoint (Ipv6Address addr, uint16_t port); /** * \brief Destructor. */ ~Ipv6EndPoint (); /** * \brief Get the local address. * \return the local address */ Ipv6Address GetLocalAddress (); /** * \brief Set the local address. * \param addr the address to set */ void SetLocalAddress (Ipv6Address addr); /** * \brief Get the local port. * \return the local port */ uint16_t GetLocalPort (); /** * \brief Set the local port. * \param port the port to set */ void SetLocalPort (uint16_t port); /** * \brief Get the peer address. * \return the peer address */ Ipv6Address GetPeerAddress (); /** * \brief Get the peer port. * \return the peer port */ uint16_t GetPeerPort (); /** * \brief Set the peer informations (address and port). * \param addr peer address * \param port peer port */ void SetPeer (Ipv6Address addr, uint16_t port); /** * \brief Set the reception callback. * \param callback callback function */ void SetRxCallback (Callback<void, Ptr<Packet>, Ipv6Address, uint16_t> callback); /** * \brief Set the ICMP callback. * \param callback callback function */ void SetIcmpCallback (Callback<void, Ipv6Address, uint8_t, uint8_t, uint8_t, uint32_t> callback); /** * \brief Set the default destroy callback. * \param callback callback function */ void SetDestroyCallback (Callback<void> callback); /** * \brief Forward the packet to the upper level. * \param p the packet * \param addr source address * \param port source port */ void ForwardUp (Ptr<Packet> p, Ipv6Address addr, uint16_t port); /** * \brief Function called from an L4Protocol implementation * to notify an endpoint of an icmp message reception. * \param src source IPv6 address * \param ttl time-to-live * \param type ICMPv6 type * \param code ICMPv6 code * \param info ICMPv6 info */ void ForwardIcmp (Ipv6Address src, uint8_t ttl, uint8_t type, uint8_t code, uint32_t info); private: /** * \brief ForwardUp wrapper. * \param p packet * \param saddr source IPv6 address * \param sport source port */ void DoForwardUp (Ptr<Packet> p, Ipv6Address saddr, uint16_t sport); /** * \brief ForwardIcmp wrapper. * \param src source IPv6 address * \param ttl time-to-live * \param type ICMPv6 type * \param code ICMPv6 code * \param info ICMPv6 info */ void DoForwardIcmp (Ipv6Address src, uint8_t ttl, uint8_t type, uint8_t code, uint32_t info); /** * \brief The local address. */ Ipv6Address m_localAddr; /** * \brief The local port. */ uint16_t m_localPort; /** * \brief The peer address. */ Ipv6Address m_peerAddr; /** * \brief The peer port. */ uint16_t m_peerPort; /** * \brief The RX callback. */ Callback<void, Ptr<Packet>, Ipv6Address, uint16_t> m_rxCallback; /** * \brief The ICMPv6 callback. */ Callback<void, Ipv6Address, uint8_t, uint8_t, uint8_t, uint32_t> m_icmpCallback; /** * \brief The destroy callback. */ Callback<void> m_destroyCallback; }; } /* namespace ns3 */ #endif /* IPV6_END_POINT_H */
/* * Copyright (C) 2002-2015 The DOSBox Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Write the data from the opcode */ switch (inst.code.save) { /* Byte */ case S_C_Eb: inst_op1_b=inst.cond ? 1 : 0; case S_Eb: if (inst.rm<0xc0) SaveMb(inst.rm_eaa,inst_op1_b); else reg_8(inst.rm_eai)=inst_op1_b; break; case S_Gb: reg_8(inst.rm_index)=inst_op1_b; break; case S_EbGb: if (inst.rm<0xc0) SaveMb(inst.rm_eaa,inst_op1_b); else reg_8(inst.rm_eai)=inst_op1_b; reg_8(inst.rm_index)=inst_op2_b; break; /* Word */ case S_Ew: if (inst.rm<0xc0) SaveMw(inst.rm_eaa,inst_op1_w); else reg_16(inst.rm_eai)=inst_op1_w; break; case S_Gw: reg_16(inst.rm_index)=inst_op1_w; break; case S_EwGw: if (inst.rm<0xc0) SaveMw(inst.rm_eaa,inst_op1_w); else reg_16(inst.rm_eai)=inst_op1_w; reg_16(inst.rm_index)=inst_op2_w; break; /* Dword */ case S_Ed: if (inst.rm<0xc0) SaveMd(inst.rm_eaa,inst_op1_d); else reg_32(inst.rm_eai)=inst_op1_d; break; case S_EdMw: /* Special one 16 to memory, 32 zero extend to reg */ if (inst.rm<0xc0) SaveMw(inst.rm_eaa,inst_op1_w); else reg_32(inst.rm_eai)=inst_op1_d; break; case S_Gd: reg_32(inst.rm_index)=inst_op1_d; break; case S_EdGd: if (inst.rm<0xc0) SaveMd(inst.rm_eaa,inst_op1_d); else reg_32(inst.rm_eai)=inst_op1_d; reg_32(inst.rm_index)=inst_op2_d; break; case S_REGb: reg_8(inst.code.extra)=inst_op1_b; break; case S_REGw: reg_16(inst.code.extra)=inst_op1_w; break; case S_REGd: reg_32(inst.code.extra)=inst_op1_d; break; case S_SEGm: if (CPU_SetSegGeneral((SegNames)inst.rm_index,inst_op1_w)) RunException(); break; case S_SEGGw: if (CPU_SetSegGeneral((SegNames)inst.code.extra,inst_op2_w)) RunException(); reg_16(inst.rm_index)=inst_op1_w; break; case S_SEGGd: if (CPU_SetSegGeneral((SegNames)inst.code.extra,inst_op2_w)) RunException(); reg_32(inst.rm_index)=inst_op1_d; break; case S_PUSHw: Push_16(inst_op1_w); break; case S_PUSHd: Push_32(inst_op1_d); break; case S_C_AIPw: if (!inst.cond) goto nextopcode; case S_AIPw: SaveIP(); reg_eip+=inst_op1_d; reg_eip&=0xffff; continue; case S_C_AIPd: if (!inst.cond) goto nextopcode; case S_AIPd: SaveIP(); reg_eip+=inst_op1_d; continue; case S_IPIw: reg_esp+=Fetchw(); case S_IP: SaveIP(); reg_eip=inst_op1_d; continue; case 0: break; default: LOG(LOG_CPU,LOG_ERROR)("SAVE:Unhandled code %d entry %X",inst.code.save,inst.entry); }
/* * File: pci-acpi.c * Purpose: Provide PCI support in ACPI * * Copyright (C) 2005 David Shaohua Li <shaohua.li@intel.com> * Copyright (C) 2004 Tom Long Nguyen <tom.l.nguyen@intel.com> * Copyright (C) 2004 Intel Corp. */ #include <linux/delay.h> #include <linux/init.h> #include <linux/pci.h> #include <linux/module.h> #include <linux/pci-aspm.h> #include <acpi/acpi.h> #include <acpi/acnamesp.h> #include <acpi/acresrc.h> #include <acpi/acpi_bus.h> #include <linux/pci-acpi.h> #include "pci.h" struct acpi_osc_data { acpi_handle handle; u32 support_set; u32 control_set; int is_queried; u32 query_result; struct list_head sibiling; }; static LIST_HEAD(acpi_osc_data_list); struct acpi_osc_args { u32 capbuf[3]; u32 query_result; }; static struct acpi_osc_data *acpi_get_osc_data(acpi_handle handle) { struct acpi_osc_data *data; list_for_each_entry(data, &acpi_osc_data_list, sibiling) { if (data->handle == handle) return data; } data = kzalloc(sizeof(*data), GFP_KERNEL); if (!data) return NULL; INIT_LIST_HEAD(&data->sibiling); data->handle = handle; list_add_tail(&data->sibiling, &acpi_osc_data_list); return data; } static u8 OSC_UUID[16] = {0x5B, 0x4D, 0xDB, 0x33, 0xF7, 0x1F, 0x1C, 0x40, 0x96, 0x57, 0x74, 0x41, 0xC0, 0x3D, 0xD7, 0x66}; static acpi_status acpi_run_osc(acpi_handle handle, struct acpi_osc_args *osc_args) { acpi_status status; struct acpi_object_list input; union acpi_object in_params[4]; struct acpi_buffer output = {ACPI_ALLOCATE_BUFFER, NULL}; union acpi_object *out_obj; u32 osc_dw0, flags = osc_args->capbuf[OSC_QUERY_TYPE]; /* Setting up input parameters */ input.count = 4; input.pointer = in_params; in_params[0].type = ACPI_TYPE_BUFFER; in_params[0].buffer.length = 16; in_params[0].buffer.pointer = OSC_UUID; in_params[1].type = ACPI_TYPE_INTEGER; in_params[1].integer.value = 1; in_params[2].type = ACPI_TYPE_INTEGER; in_params[2].integer.value = 3; in_params[3].type = ACPI_TYPE_BUFFER; in_params[3].buffer.length = 12; in_params[3].buffer.pointer = (u8 *)osc_args->capbuf; status = acpi_evaluate_object(handle, "_OSC", &input, &output); if (ACPI_FAILURE(status)) return status; out_obj = output.pointer; if (out_obj->type != ACPI_TYPE_BUFFER) { printk(KERN_DEBUG "Evaluate _OSC returns wrong type\n"); status = AE_TYPE; goto out_kfree; } osc_dw0 = *((u32 *)out_obj->buffer.pointer); if (osc_dw0) { if (osc_dw0 & OSC_REQUEST_ERROR) printk(KERN_DEBUG "_OSC request fails\n"); if (osc_dw0 & OSC_INVALID_UUID_ERROR) printk(KERN_DEBUG "_OSC invalid UUID\n"); if (osc_dw0 & OSC_INVALID_REVISION_ERROR) printk(KERN_DEBUG "_OSC invalid revision\n"); if (osc_dw0 & OSC_CAPABILITIES_MASK_ERROR) { if (flags & OSC_QUERY_ENABLE) goto out_success; printk(KERN_DEBUG "_OSC FW not grant req. control\n"); status = AE_SUPPORT; goto out_kfree; } status = AE_ERROR; goto out_kfree; } out_success: if (flags & OSC_QUERY_ENABLE) osc_args->query_result = *((u32 *)(out_obj->buffer.pointer + 8)); status = AE_OK; out_kfree: kfree(output.pointer); return status; } static acpi_status acpi_query_osc(acpi_handle handle, u32 level, void *context, void **retval) { acpi_status status; struct acpi_osc_data *osc_data; u32 flags = (unsigned long)context, support_set; acpi_handle tmp; struct acpi_osc_args osc_args; status = acpi_get_handle(handle, "_OSC", &tmp); if (ACPI_FAILURE(status)) return status; osc_data = acpi_get_osc_data(handle); if (!osc_data) { printk(KERN_ERR "acpi osc data array is full\n"); return AE_ERROR; } /* do _OSC query for all possible controls */ support_set = osc_data->support_set | (flags & OSC_SUPPORT_MASKS); osc_args.capbuf[OSC_QUERY_TYPE] = OSC_QUERY_ENABLE; osc_args.capbuf[OSC_SUPPORT_TYPE] = support_set; osc_args.capbuf[OSC_CONTROL_TYPE] = OSC_CONTROL_MASKS; status = acpi_run_osc(handle, &osc_args); if (ACPI_SUCCESS(status)) { osc_data->support_set = support_set; osc_data->query_result = osc_args.query_result; osc_data->is_queried = 1; } return status; } /** * __pci_osc_support_set - register OS support to Firmware * @flags: OS support bits * @hid: hardware ID * * Update OS support fields and doing a _OSC Query to obtain an update * from Firmware on supported control bits. **/ acpi_status __pci_osc_support_set(u32 flags, const char *hid) { if (!(flags & OSC_SUPPORT_MASKS)) return AE_TYPE; acpi_get_devices(hid, acpi_query_osc, (void *)(unsigned long)flags, NULL); return AE_OK; } /** * pci_osc_control_set - commit requested control to Firmware * @handle: acpi_handle for the target ACPI object * @flags: driver's requested control bits * * Attempt to take control from Firmware on requested control bits. **/ acpi_status pci_osc_control_set(acpi_handle handle, u32 flags) { acpi_status status; u32 ctrlset, control_set; acpi_handle tmp; struct acpi_osc_data *osc_data; struct acpi_osc_args osc_args; status = acpi_get_handle(handle, "_OSC", &tmp); if (ACPI_FAILURE(status)) return status; osc_data = acpi_get_osc_data(handle); if (!osc_data) { printk(KERN_ERR "acpi osc data array is full\n"); return AE_ERROR; } ctrlset = (flags & OSC_CONTROL_MASKS); if (!ctrlset) return AE_TYPE; if (osc_data->is_queried && ((osc_data->query_result & ctrlset) != ctrlset)) return AE_SUPPORT; control_set = osc_data->control_set | ctrlset; osc_args.capbuf[OSC_QUERY_TYPE] = 0; osc_args.capbuf[OSC_SUPPORT_TYPE] = osc_data->support_set; osc_args.capbuf[OSC_CONTROL_TYPE] = control_set; status = acpi_run_osc(handle, &osc_args); if (ACPI_SUCCESS(status)) osc_data->control_set = control_set; return status; } EXPORT_SYMBOL(pci_osc_control_set); /* * _SxD returns the D-state with the highest power * (lowest D-state number) supported in the S-state "x". * * If the devices does not have a _PRW * (Power Resources for Wake) supporting system wakeup from "x" * then the OS is free to choose a lower power (higher number * D-state) than the return value from _SxD. * * But if _PRW is enabled at S-state "x", the OS * must not choose a power lower than _SxD -- * unless the device has an _SxW method specifying * the lowest power (highest D-state number) the device * may enter while still able to wake the system. * * ie. depending on global OS policy: * * if (_PRW at S-state x) * choose from highest power _SxD to lowest power _SxW * else // no _PRW at S-state x * choose highest power _SxD or any lower power */ static pci_power_t acpi_pci_choose_state(struct pci_dev *pdev) { int acpi_state; acpi_state = acpi_pm_device_sleep_state(&pdev->dev, NULL); if (acpi_state < 0) return PCI_POWER_ERROR; switch (acpi_state) { case ACPI_STATE_D0: return PCI_D0; case ACPI_STATE_D1: return PCI_D1; case ACPI_STATE_D2: return PCI_D2; case ACPI_STATE_D3: return PCI_D3hot; } return PCI_POWER_ERROR; } static bool acpi_pci_power_manageable(struct pci_dev *dev) { acpi_handle handle = DEVICE_ACPI_HANDLE(&dev->dev); return handle ? acpi_bus_power_manageable(handle) : false; } static int acpi_pci_set_power_state(struct pci_dev *dev, pci_power_t state) { acpi_handle handle = DEVICE_ACPI_HANDLE(&dev->dev); acpi_handle tmp; static const u8 state_conv[] = { [PCI_D0] = ACPI_STATE_D0, [PCI_D1] = ACPI_STATE_D1, [PCI_D2] = ACPI_STATE_D2, [PCI_D3hot] = ACPI_STATE_D3, [PCI_D3cold] = ACPI_STATE_D3 }; int error = -EINVAL; /* If the ACPI device has _EJ0, ignore the device */ if (!handle || ACPI_SUCCESS(acpi_get_handle(handle, "_EJ0", &tmp))) return -ENODEV; switch (state) { case PCI_D0: case PCI_D1: case PCI_D2: case PCI_D3hot: case PCI_D3cold: error = acpi_bus_set_power(handle, state_conv[state]); } if (!error) dev_printk(KERN_INFO, &dev->dev, "power state changed by ACPI to D%d\n", state); return error; } static bool acpi_pci_can_wakeup(struct pci_dev *dev) { acpi_handle handle = DEVICE_ACPI_HANDLE(&dev->dev); return handle ? acpi_bus_can_wakeup(handle) : false; } static int acpi_pci_sleep_wake(struct pci_dev *dev, bool enable) { int error = acpi_pm_device_sleep_wake(&dev->dev, enable); if (!error) dev_printk(KERN_INFO, &dev->dev, "wake-up capability %s by ACPI\n", enable ? "enabled" : "disabled"); return error; } static struct pci_platform_pm_ops acpi_pci_platform_pm = { .is_manageable = acpi_pci_power_manageable, .set_state = acpi_pci_set_power_state, .choose_state = acpi_pci_choose_state, .can_wakeup = acpi_pci_can_wakeup, .sleep_wake = acpi_pci_sleep_wake, }; /* ACPI bus type */ static int acpi_pci_find_device(struct device *dev, acpi_handle *handle) { struct pci_dev * pci_dev; acpi_integer addr; pci_dev = to_pci_dev(dev); /* Please ref to ACPI spec for the syntax of _ADR */ addr = (PCI_SLOT(pci_dev->devfn) << 16) | PCI_FUNC(pci_dev->devfn); *handle = acpi_get_child(DEVICE_ACPI_HANDLE(dev->parent), addr); if (!*handle) return -ENODEV; return 0; } static int acpi_pci_find_root_bridge(struct device *dev, acpi_handle *handle) { int num; unsigned int seg, bus; /* * The string should be the same as root bridge's name * Please look at 'pci_scan_bus_parented' */ num = sscanf(dev->bus_id, "pci%04x:%02x", &seg, &bus); if (num != 2) return -ENODEV; *handle = acpi_get_pci_rootbridge_handle(seg, bus); if (!*handle) return -ENODEV; return 0; } static struct acpi_bus_type acpi_pci_bus = { .bus = &pci_bus_type, .find_device = acpi_pci_find_device, .find_bridge = acpi_pci_find_root_bridge, }; static int __init acpi_pci_init(void) { int ret; if (acpi_gbl_FADT.boot_flags & BAF_MSI_NOT_SUPPORTED) { printk(KERN_INFO"ACPI FADT declares the system doesn't support MSI, so disable it\n"); pci_no_msi(); } if (acpi_gbl_FADT.boot_flags & BAF_PCIE_ASPM_CONTROL) { printk(KERN_INFO"ACPI FADT declares the system doesn't support PCIe ASPM, so disable it\n"); pcie_no_aspm(); } ret = register_acpi_bus_type(&acpi_pci_bus); if (ret) return 0; pci_set_platform_pm(&acpi_pci_platform_pm); return 0; } arch_initcall(acpi_pci_init);
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007,2008 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Jahanzeb Farooq <jahanzeb.farooq@sophia.inria.fr> */ #ifndef WIMAX_PHY_H #define WIMAX_PHY_H #include <stdint.h> #include <list> #include "ns3/callback.h" #include "ns3/nstime.h" #include "ns3/event-id.h" #include "bvec.h" #include "send-params.h" #include "ns3/log.h" #include "ns3/object.h" #include "ns3/traced-callback.h" namespace ns3 { class WimaxChannel; class WimaxNetDevice; class NetDevice; class Packet; class WimaxPhy : public Object { public: enum ModulationType // Table 356 and 362 { MODULATION_TYPE_BPSK_12, MODULATION_TYPE_QPSK_12, MODULATION_TYPE_QPSK_34, MODULATION_TYPE_QAM16_12, MODULATION_TYPE_QAM16_34, MODULATION_TYPE_QAM64_23, MODULATION_TYPE_QAM64_34 }; enum PhyState { PHY_STATE_IDLE, PHY_STATE_SCANNING, PHY_STATE_TX, PHY_STATE_RX }; enum PhyType { SimpleWimaxPhy, simpleOfdmWimaxPhy }; static TypeId GetTypeId (void); WimaxPhy (void); virtual ~WimaxPhy (void); /** * Attach the physical layer to a channel. * \param channel the channel to which the physical layer will be attached */ void Attach (Ptr<WimaxChannel> channel); /** * \return the channel to which this physical layer is attached */ Ptr<WimaxChannel> GetChannel (void) const; /** * \brief Set the device in which this physical layer is installed * \param device the device in which this physical layer is installed */ void SetDevice (Ptr<WimaxNetDevice> device); /** * \return the the device in which this physical layer is installed */ Ptr<NetDevice> GetDevice (void) const; /** * \brief set the callback function to call when a burst is received * \param callback the callback function to call when a burst is received */ void SetReceiveCallback (Callback<void, Ptr<const PacketBurst> > callback); /** * \return the receive callback */ Callback<void, Ptr<const PacketBurst> > GetReceiveCallback (void) const; /** * \brief send a packet on the channel * \param params the parameters used to send the packet */ virtual void Send (SendParams *params) = 0; /** * \brief Get the type of the physical layer */ virtual PhyType GetPhyType (void) const = 0; /** * \brief configure the physical layer in duplex mode * \param rxFrequency the reception frequency * \param txFrequency the transmission frequency */ void SetDuplex (uint64_t rxFrequency, uint64_t txFrequency); /** * \brief configure the physical layer in simplex mode * \param frequency the frequency to be used for reception and transmission process */ void SetSimplex (uint64_t frequency); /** * \return the reception frequency */ uint64_t GetRxFrequency (void) const; /** * \return the transmission frequency */ uint64_t GetTxFrequency (void) const; /** * \return the scanning frequency */ uint64_t GetScanningFrequency (void) const; /** * \brief Set the number of carriers in the physical frame * \param nrCarriers the number of carriers in the frame */ void SetNrCarriers (uint8_t nrCarriers); /** * \return the number of carriers in the frame */ uint8_t GetNrCarriers (void) const; /** * \brief Set the frame duration * \param frameDuration the frame duration */ void SetFrameDuration (Time frameDuration); /** * \return the frame duration in seconds */ Time GetFrameDurationSec (void) const; /** * \return the frame duration */ Time GetFrameDuration (void) const; /** * \brief set the frequency on which the device should lock * \param frequency the frequency to configure */ void SetFrequency (uint32_t frequency); /** * \return the frequency on which the device is locked */ uint32_t GetFrequency (void) const; /** * \brief Set the channel bandwidth * \param channelBandwidth The channel bandwidth */ void SetChannelBandwidth (uint32_t channelBandwidth); /** * \return the channel bandwidth */ uint32_t GetChannelBandwidth (void) const; /** * \return the size of the FFT */ uint16_t GetNfft (void) const; /** * \return the sampling factor */ double GetSamplingFactor (void) const; /** * \return the sampling frequency */ double GetSamplingFrequency (void) const; /** * \brief set the physical slot duration in seconds * \param psDuration the physical slot duration */ void SetPsDuration (Time psDuration); /** * \return the physical slot duration */ Time GetPsDuration (void) const; /** * \brief set the OFMD symbol duration in second * \param symbolDuration the symbol duration is second */ void SetSymbolDuration (Time symbolDuration); /** * \return the symbol duration in second */ Time GetSymbolDuration (void) const; /** * \return the guard interval factor (The ratio TG/Td) */ double GetGValue (void) const; /** * \brief set the number of physical slots per symbol * \param psPerSymbol the number of physical slots per symbol */ void SetPsPerSymbol (uint16_t psPerSymbol); /** * \return the number of physical slots per symbol */ uint16_t GetPsPerSymbol (void) const; /** * \brief set the number of physical slot per frame * \param psPerFrame the number of physical slot per frame */ void SetPsPerFrame (uint16_t psPerFrame); /** * \return the number of physical slot per frame */ uint16_t GetPsPerFrame (void) const; /** * \brief set the number of symbols per frame * \param symbolsPerFrame the number of symbols per frame */ void SetSymbolsPerFrame (uint32_t symbolsPerFrame); /** * \return the number of symbols per frame */ uint32_t GetSymbolsPerFrame (void) const; /** * \return true if the device is configured in duplex mode */ bool IsDuplex (void) const; /** * \brief set the state of the device * \param state the state to be set (PHY_STATE_IDLE, PHY_STATE_SCANNING, PHY_STATE_TX, PHY_STATE_RX) */ void SetState (PhyState state); /** * \return the state of the device (PHY_STATE_IDLE, PHY_STATE_SCANNING, PHY_STATE_TX, PHY_STATE_RX) */ PhyState GetState (void) const; /** * \brief scan the frequency frequency for maximum timeout seconds and calls callback if the frequency could be used * \param frequency the frequency to scan * \param timeout the timout before considering the channel as unusable * \param callback the function to call if the channel could be used */ void StartScanning (uint64_t frequency, Time timeout, Callback<void, bool, uint64_t> callback); /** * \brief calls the scanning call back function */ void SetScanningCallback (void) const; EventId GetChnlSrchTimeoutEvent (void) const; /** * \brief calculates the data rate of each modulation and save them for future use */ void SetDataRates (void); /** * \return the data rate of the modulation modulationType * \param modulationType the modulation that you want to get its data rate */ uint32_t GetDataRate (ModulationType modulationType) const; /** * \return the time needed to transmit size bytes using the modulation modulationType * \param size the number of byte to transmit * \param modulationType the modulation that will be used to transmit the bytes */ Time GetTransmissionTime (uint32_t size, ModulationType modulationType) const; /** * \return the number of symbols needed to transmit size bytes using the modulation modulationType * \param size the number of byte to transmit * \param modulationType the modulation that will be used to transmit the bytes */ uint64_t GetNrSymbols (uint32_t size, ModulationType modulationType) const; /** * \return the maximum number of bytes that could be carried by symbols symbols using the modulation modulationType * \param symbols the number of symbols to use * \param modulationType the modulation that will be used */ uint64_t GetNrBytes (uint32_t symbols, ModulationType modulationType) const; /** * \return the transmit/receive transition gap */ uint16_t GetTtg (void) const; /** * \return the receive/transmit transition gap */ uint16_t GetRtg (void) const; uint8_t GetFrameDurationCode (void) const; Time GetFrameDuration (uint8_t frameDurationCode) const; /** * \brief computes the Physical parameters and store them */ void SetPhyParameters (void); virtual void DoDispose (void); /** * \return the mobility model of the device */ virtual Ptr<Object> GetMobility (void); /** * \brief set the mobility model of the device * \param mobility the mobility model to set */ virtual void SetMobility (Ptr<Object> mobility); private: void GetModulationFecParams (ModulationType modulationType, uint8_t &bitsPerSymbol, double &fecCode) const; void EndScanning (void); virtual Time DoGetTransmissionTime (uint32_t size, ModulationType modulationType) const = 0; virtual void DoAttach (Ptr<WimaxChannel> channel) = 0; virtual void DoSetDataRates (void) = 0; virtual uint32_t DoGetDataRate (ModulationType modulationType) const = 0; virtual uint64_t DoGetNrSymbols (uint32_t size, ModulationType modulationType) const = 0; virtual uint64_t DoGetNrBytes (uint32_t symbols, ModulationType modulationType) const = 0; virtual uint16_t DoGetTtg (void) const = 0; virtual uint16_t DoGetRtg (void) const = 0; virtual uint8_t DoGetFrameDurationCode (void) const = 0; virtual Time DoGetFrameDuration (uint8_t frameDurationCode) const = 0; virtual void DoSetPhyParameters (void) = 0; virtual double DoGetSamplingFactor (void) const = 0; virtual uint16_t DoGetNfft (void) const = 0; virtual double DoGetSamplingFrequency (void) const = 0; virtual double DoGetGValue (void) const = 0; Ptr<WimaxNetDevice> m_device; Ptr<WimaxChannel> m_channel; uint64_t m_txFrequency; uint64_t m_rxFrequency; uint64_t m_scanningFrequency; EventId m_dlChnlSrchTimeoutEvent; bool m_duplex; PhyState m_state; Callback<void, Ptr<const PacketBurst> > m_rxCallback; Callback<void, bool, uint64_t> m_scanningCallback; uint8_t m_nrCarriers; Time m_frameDuration; // in seconds uint32_t m_frequency; // in KHz uint32_t m_channelBandwidth; // in Hz Time m_psDuration; // in seconds Time m_symbolDuration; // in seconds uint16_t m_psPerSymbol; uint16_t m_psPerFrame; uint32_t m_symbolsPerFrame; Ptr<Object> m_mobility; }; } // namespace ns3 #endif /* WIMAX_PHY_H */
/* Copyright 2016 Fred Sundvik <fsundvik@gmail.com> Jun Wako <wakojun@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdint.h> #include <stdbool.h> #include <string.h> #include "hal.h" #include "timer.h" #include "wait.h" #include "print.h" #include "debug.h" #include "matrix.h" #include "serial_link/system/serial_link.h" /* * Infinity ErgoDox Pinusage: * Column pins are input with internal pull-down. Row pins are output and strobe with high. * Key is high or 1 when it turns on. * * col: { PTD1, PTD4, PTD5, PTD6, PTD7 } * row: { PTB2, PTB3, PTB18, PTB19, PTC0, PTC9, PTC10, PTC11, PTD0 } */ /* matrix state(1:on, 0:off) */ static matrix_row_t matrix[MATRIX_ROWS]; static matrix_row_t matrix_debouncing[LOCAL_MATRIX_ROWS]; static bool debouncing = false; static uint16_t debouncing_time = 0; void matrix_init(void) { /* Column(sense) */ palSetPadMode(GPIOD, 1, PAL_MODE_INPUT_PULLDOWN); palSetPadMode(GPIOD, 4, PAL_MODE_INPUT_PULLDOWN); palSetPadMode(GPIOD, 5, PAL_MODE_INPUT_PULLDOWN); palSetPadMode(GPIOD, 6, PAL_MODE_INPUT_PULLDOWN); palSetPadMode(GPIOD, 7, PAL_MODE_INPUT_PULLDOWN); /* Row(strobe) */ palSetPadMode(GPIOB, 2, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOB, 3, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOB, 18, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOB, 19, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOC, 0, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOC, 9, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOC, 10, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOC, 11, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOD, 0, PAL_MODE_OUTPUT_PUSHPULL); memset(matrix, 0, MATRIX_ROWS); memset(matrix_debouncing, 0, LOCAL_MATRIX_ROWS); matrix_init_quantum(); } uint8_t matrix_scan(void) { for (int row = 0; row < LOCAL_MATRIX_ROWS; row++) { matrix_row_t data = 0; // strobe row switch (row) { case 0: palSetPad(GPIOB, 2); break; case 1: palSetPad(GPIOB, 3); break; case 2: palSetPad(GPIOB, 18); break; case 3: palSetPad(GPIOB, 19); break; case 4: palSetPad(GPIOC, 0); break; case 5: palSetPad(GPIOC, 9); break; case 6: palSetPad(GPIOC, 10); break; case 7: palSetPad(GPIOC, 11); break; case 8: palSetPad(GPIOD, 0); break; } // need wait to settle pin state // if you wait too short, or have a too high update rate // the keyboard might freeze, or there might not be enough // processing power to update the LCD screen properly. // 20us, or two ticks at 100000Hz seems to be OK wait_us(20); // read col data: { PTD1, PTD4, PTD5, PTD6, PTD7 } data = ((palReadPort(GPIOD) & 0xF0) >> 3) | ((palReadPort(GPIOD) & 0x02) >> 1); // un-strobe row switch (row) { case 0: palClearPad(GPIOB, 2); break; case 1: palClearPad(GPIOB, 3); break; case 2: palClearPad(GPIOB, 18); break; case 3: palClearPad(GPIOB, 19); break; case 4: palClearPad(GPIOC, 0); break; case 5: palClearPad(GPIOC, 9); break; case 6: palClearPad(GPIOC, 10); break; case 7: palClearPad(GPIOC, 11); break; case 8: palClearPad(GPIOD, 0); break; } if (matrix_debouncing[row] != data) { matrix_debouncing[row] = data; debouncing = true; debouncing_time = timer_read(); } } uint8_t offset = 0; #ifdef MASTER_IS_ON_RIGHT if (is_serial_link_master()) { offset = MATRIX_ROWS - LOCAL_MATRIX_ROWS; } #endif if (debouncing && timer_elapsed(debouncing_time) > DEBOUNCE) { for (int row = 0; row < LOCAL_MATRIX_ROWS; row++) { matrix[offset + row] = matrix_debouncing[row]; } debouncing = false; } matrix_scan_quantum(); return 1; } bool matrix_is_on(uint8_t row, uint8_t col) { return (matrix[row] & (1<<col)); } matrix_row_t matrix_get_row(uint8_t row) { return matrix[row]; } void matrix_print(void) { xprintf("\nr/c 01234567\n"); for (uint8_t row = 0; row < MATRIX_ROWS; row++) { xprintf("%X0: ", row); matrix_row_t data = matrix_get_row(row); for (int col = 0; col < MATRIX_COLS; col++) { if (data & (1<<col)) xprintf("1"); else xprintf("0"); } xprintf("\n"); } } void matrix_set_remote(matrix_row_t* rows, uint8_t index) { uint8_t offset = 0; #ifdef MASTER_IS_ON_RIGHT offset = MATRIX_ROWS - LOCAL_MATRIX_ROWS * (index + 2); #else offset = LOCAL_MATRIX_ROWS * (index + 1); #endif for (int row = 0; row < LOCAL_MATRIX_ROWS; row++) { matrix[offset + row] = rows[row]; } }
/* * Registrar protocol messages * * Copyright (C) 2012, Broadcom Corporation * All Rights Reserved. * * This is UNPUBLISHED PROPRIETARY SOURCE CODE of Broadcom Corporation; * the contents of this file may not be disclosed to third parties, copied * or duplicated in any form, in whole or in part, without the prior * written permission of Broadcom Corporation. * * $Id: reg_protomsg.h 292703 2011-10-28 03:05:19Z $ */ #ifndef _WPS_MSG_H #define _WPS_MSG_H #ifdef __cplusplus extern "C" { #endif #include <reg_prototlv.h> #include <wps_sslist.h> /* Message Structures */ /* Message M1 */ typedef struct { CTlvVersion version; CTlvMsgType msgType; CTlvUuid uuid; CTlvMacAddr macAddr; CTlvEnrolleeNonce enrolleeNonce; CTlvPublicKey publicKey; CTlvAuthTypeFlags authTypeFlags; CTlvEncrTypeFlags encrTypeFlags; CTlvConnTypeFlags connTypeFlags; CTlvConfigMethods configMethods; CTlvScState scState; CTlvManufacturer manufacturer; CTlvModelName modelName; CTlvModelNumber modelNumber; CTlvSerialNum serialNumber; CTlvPrimDeviceType primDeviceType; CTlvDeviceName deviceName; CTlvRfBand rfBand; CTlvAssocState assocState; CTlvDevicePwdId devPwdId; CTlvConfigError configError; CTlvOsVersion osVersion; CTlvVendorExt vendorExt; CSubTlvVersion2 version2; /* C: WSC 2.0 */ CSubTlvReqToEnr reqToEnr; /* O: WSC 2.0 */ } WpsM1; /* Message M2 */ typedef struct { CTlvVersion version; CTlvMsgType msgType; CTlvEnrolleeNonce enrolleeNonce; CTlvRegistrarNonce registrarNonce; CTlvUuid uuid; CTlvPublicKey publicKey; CTlvAuthTypeFlags authTypeFlags; CTlvEncrTypeFlags encrTypeFlags; CTlvConnTypeFlags connTypeFlags; CTlvConfigMethods configMethods; CTlvManufacturer manufacturer; CTlvModelName modelName; CTlvModelNumber modelNumber; CTlvSerialNum serialNumber; CTlvPrimDeviceType primDeviceType; CTlvDeviceName deviceName; CTlvRfBand rfBand; CTlvAssocState assocState; CTlvConfigError configError; CTlvDevicePwdId devPwdId; CTlvOsVersion osVersion; CTlvEncrSettings encrSettings; CTlvVendorExt vendorExt; CSubTlvVersion2 version2; /* C: WSC 2.0 */ CTlvAuthenticator authenticator; } WpsM2; /* Message M2D */ typedef struct { CTlvVersion version; CTlvMsgType msgType; CTlvEnrolleeNonce enrolleeNonce; CTlvRegistrarNonce registrarNonce; CTlvUuid uuid; CTlvAuthTypeFlags authTypeFlags; CTlvEncrTypeFlags encrTypeFlags; CTlvConnTypeFlags connTypeFlags; CTlvConfigMethods configMethods; CTlvManufacturer manufacturer; CTlvModelName modelName; CTlvModelNumber modelNumber; CTlvSerialNum serialNumber; CTlvPrimDeviceType primDeviceType; CTlvDeviceName deviceName; CTlvRfBand rfBand; CTlvAssocState assocState; CTlvConfigError configError; CTlvDevicePwdId devPwdId; CTlvOsVersion osVersion; CTlvVendorExt vendorExt; CSubTlvVersion2 version2; /* C: WSC 2.0 */ } WpsM2D; /* Message M3 */ typedef struct { CTlvVersion version; CTlvMsgType msgType; CTlvRegistrarNonce registrarNonce; CTlvHash eHash1; CTlvHash eHash2; CTlvVendorExt vendorExt; CSubTlvVersion2 version2; /* C: WSC 2.0 */ CTlvAuthenticator authenticator; } WpsM3; /* Message M4 */ typedef struct { CTlvVersion version; CTlvMsgType msgType; CTlvEnrolleeNonce enrolleeNonce; CTlvHash rHash1; CTlvHash rHash2; CTlvEncrSettings encrSettings; CTlvVendorExt vendorExt; CSubTlvVersion2 version2; /* C: WSC 2.0 */ CTlvAuthenticator authenticator; } WpsM4; /* Message M5 */ typedef struct { CTlvVersion version; CTlvMsgType msgType; CTlvRegistrarNonce registrarNonce; CTlvEncrSettings encrSettings; CTlvVendorExt vendorExt; CSubTlvVersion2 version2; /* C: WSC 2.0 */ CTlvAuthenticator authenticator; } WpsM5; /* Message M6 */ typedef struct { CTlvVersion version; CTlvMsgType msgType; CTlvEnrolleeNonce enrolleeNonce; CTlvEncrSettings encrSettings; CTlvVendorExt vendorExt; CSubTlvVersion2 version2; /* C: WSC 2.0 */ CTlvAuthenticator authenticator; } WpsM6; /* Message M7 */ typedef struct { CTlvVersion version; CTlvMsgType msgType; CTlvRegistrarNonce registrarNonce; CTlvEncrSettings encrSettings; CTlvX509CertReq x509CertReq; CTlvVendorExt vendorExt; CSubTlvSettingsDelayTime settingsDelayTime; /* O: WSC 2.0 */ CSubTlvVersion2 version2; /* C: WSC 2.0 */ CTlvAuthenticator authenticator; } WpsM7; /* Message M8 */ typedef struct { CTlvVersion version; CTlvMsgType msgType; CTlvEnrolleeNonce enrolleeNonce; CTlvEncrSettings encrSettings; CTlvX509Cert x509Cert; CTlvVendorExt vendorExt; CSubTlvVersion2 version2; /* C: WSC 2.0 */ CTlvAuthenticator authenticator; } WpsM8; /* ACK and DONE Messages */ typedef struct { CTlvVersion version; CTlvMsgType msgType; CTlvEnrolleeNonce enrolleeNonce; CTlvRegistrarNonce registrarNonce; CTlvVendorExt vendorExt; CSubTlvVersion2 version2; /* C: WSC 2.0 */ } WpsACK, WpsDone; /* NACK Message */ typedef struct { CTlvVersion version; CTlvMsgType msgType; CTlvEnrolleeNonce enrolleeNonce; CTlvRegistrarNonce registrarNonce; CTlvConfigError configError; CTlvVendorExt vendorExt; CSubTlvVersion2 version2; /* C: WSC 2.0 */ } WpsNACK; /* Encrypted settings for various messages */ /* * M4, M5, M6 - contain only Nonce and vendor extension * this structure doesn't allocate dyamic memory * doesn't need a free function at the moment. */ typedef struct { CTlvNonce nonce; /* could be RS1, ES1 or RS2 */ CTlvAuthenticator keyWrapAuth; /* reuse Authenticator data struct */ } TlvEsNonce; /* M7 */ /* NOTE : this structure MUST be freed using reg_msg_m7enr_del */ typedef struct { int es_type; CTlvNonce nonce; /* ES2 */ CTlvIdentityProof idProof; CTlvAuthenticator keyWrapAuth; /* reuse Authenticator data struct */ } EsM7Enr; /* NOTE : this structure MUST be freed using reg_msg_m7ap_del */ typedef struct { int es_type; CTlvNonce nonce; /* ES2 */ CTlvSsid ssid; CTlvMacAddr macAddr; CTlvAuthType authType; CTlvEncrType encrType; WPS_SSLIST *nwKeyIndex; WPS_SSLIST *nwKey; CTlvWEPTransmitKey wepIdx; CTlvAuthenticator keyWrapAuth; /* reuse Authenticator data struct */ } EsM7Ap; /* M8 */ /* NOTE : this structure MUST be freed using reg_msg_m8ap_del */ typedef struct { int es_type; CTlvNwIndex nwIndex; CTlvSsid ssid; CTlvAuthType authType; CTlvEncrType encrType; WPS_SSLIST *nwKeyIndex; WPS_SSLIST *nwKey; CTlvMacAddr macAddr; CTlvNewPwd new_pwd; CTlvDevicePwdId pwdId; CTlvWEPTransmitKey wepIdx; CTlvAuthenticator keyWrapAuth; /* reuse Authenticator data struct */ } EsM8Ap; typedef struct { int es_type; WPS_SSLIST *credential; CTlvNewPwd new_pwd; CTlvDevicePwdId pwdId; CTlvAuthenticator keyWrapAuth; /* reuse Authenticator data struct */ } EsM8Sta; #define ES_TYPE_M7ENR 1 #define ES_TYPE_M7AP 2 #define ES_TYPE_M8AP 3 #define ES_TYPE_M8STA 4 void reg_msg_init(void *m, int type); int reg_msg_version_check(uint8 msgId, BufferObj *theBuf, TlvObj_uint8 *version, TlvObj_uint8 *msgType); void reg_msg_nonce_parse(TlvEsNonce *t, uint16 theType, BufferObj *theBuf, BufferObj *authKey); void reg_msg_nonce_write(TlvEsNonce *t, BufferObj *theBuf, BufferObj *authKey); uint32 reg_msg_m7enr_parse(EsM7Enr *t, BufferObj *theBuf, BufferObj *authKey, bool allocate); void reg_msg_m7enr_write(EsM7Enr *t, BufferObj *theBuf, BufferObj *authKey); uint32 reg_msg_m7ap_parse(EsM7Ap *tlv, BufferObj *theBuf, BufferObj *authKey, bool allocate); void reg_msg_m7ap_write(EsM7Ap *tlv, BufferObj *theBuf, BufferObj *authKey); void reg_msg_m8ap_parse(EsM8Ap *t, BufferObj *theBuf, BufferObj *authKey, bool allocate); void reg_msg_m8ap_write(EsM8Ap *t, BufferObj *theBuf, BufferObj *authKey, bool b_wsp_version2); void reg_msg_m8sta_parse(EsM8Sta *t, BufferObj *theBuf, BufferObj *authKey, bool allocate); void reg_msg_m8sta_write(EsM8Sta *t, BufferObj *theBuf); void reg_msg_m8sta_write_cred(EsM8Sta *t, BufferObj *theBuf); void reg_msg_m8sta_write_key(EsM8Sta *t, BufferObj *theBuf, BufferObj *authKey); void *reg_msg_es_new(int es_type); void reg_msg_es_del(void *tlv, bool content_only); #ifdef __cplusplus } #endif #endif /* _WPS_MSG_H */
// eSpeak and other code here are under the GNU GPL. function generateSpeech(text, args) { var self = { text: text, args: args, ret: null }; (function() {
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <TITLE> Overview List </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TH ALIGN="left" NOWRAP><FONT size="+1" CLASS="FrameTitleFont"> <B></B></FONT></TH> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT CLASS="FrameItemFont"><A HREF="allclasses-frame.html" target="packageFrame">All Classes</A></FONT> <P> <FONT size="+1" CLASS="FrameHeadingFont"> Packages</FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="com/rapplogic/xbee/package-frame.html" target="packageFrame">com.rapplogic.xbee</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="com/rapplogic/xbee/api/package-frame.html" target="packageFrame">com.rapplogic.xbee.api</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="com/rapplogic/xbee/api/wpan/package-frame.html" target="packageFrame">com.rapplogic.xbee.api.wpan</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="com/rapplogic/xbee/api/zigbee/package-frame.html" target="packageFrame">com.rapplogic.xbee.api.zigbee</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="com/rapplogic/xbee/util/package-frame.html" target="packageFrame">com.rapplogic.xbee.util</A></FONT> <BR> </TD> </TR> </TABLE> <P> &nbsp; </BODY> </HTML>
#!/bin/bash echo =============================================================================== echo \[tabescape_dflt.sh\]: test for default tab escaping . $srcdir/diag.sh init . $srcdir/diag.sh generate-HOSTNAME ./nettester -ttabescape_dflt -iudp if [ "$?" -ne "0" ]; then echo erorr in udp run exit 1 fi echo test via tcp ./nettester -ttabescape_dflt -itcp if [ "$?" -ne "0" ]; then echo erorr in tcp run exit 1 fi
/* * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client * Copyright (C) 2002-2012 Match Grun and the Claws Mail team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /* * General functions for saving properties to an XML file. */ #ifndef __XMLSAVER_H__ #define __XMLSAVER_H__ #include <stdio.h> #include <glib.h> /* XML property data */ typedef struct _XmlProperty XmlProperty; struct _XmlProperty { gchar *path; gchar *encoding; GHashTable *propertyTable; gint retVal; }; /* Function prototypes */ XmlProperty *xmlprops_create ( void ); void xmlprops_free ( XmlProperty *props ); void xmlprops_set_path ( XmlProperty *props, const gchar *value ); gint xmlprops_load_file ( XmlProperty *props ); gint xmlprops_save_file ( XmlProperty *props ); void xmlprops_set_property ( XmlProperty *props, const gchar *name, const gchar *value ); void xmlprops_set_property_i ( XmlProperty *props, const gchar *name, const gint value ); void xmlprops_set_property_b ( XmlProperty *props, const gchar *name, const gboolean value ); void xmlprops_get_property_s ( XmlProperty *props, const gchar *name, gchar *buffer ); gint xmlprops_get_property_i ( XmlProperty *props, const gchar *name ); gboolean xmlprops_get_property_b( XmlProperty *props, const gchar *name ); #endif /* __XMLSAVER_H__ */
/******/ (function() { // webpackBootstrap /******/ "use strict"; /******/ /******/ /******/ })() ;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ScottClayton.Neural { /// <summary> /// A list of NNVectors with an added size check and the ability to save the list. /// </summary> class DoubleVectorList : List<DoubleVector> { /// <summary> /// Add a vector to the list /// </summary> /// <param name="item">The vector to add</param> /// <exception cref="VectorSizeMismatchException"></exception> public new void Add(DoubleVector item) { // If entering another item into the list, make sure that it has the same size as the rest of the vectors if (this.Count > 0 && this[0].Size != item.Size) { throw new VectorSizeMismatchException(); } base.Add(item); } public void Save(BinaryWriter w) { w.Write(this.Count); foreach (DoubleVector v in this) { v.Save(w); } } public static DoubleVectorList Load(BinaryReader r) { DoubleVectorList nnvl = new DoubleVectorList(); int count = r.ReadInt32(); for (int i = 0; i < count; i++) { nnvl.Add(DoubleVector.Load(r)); } return nnvl; } } }
/* Unix SMB/CIFS implementation. Winbind status program. Copyright (C) Tim Potter 2000-2003 Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003-2004 Copyright (C) Francesco Chemolli <kinkie@kame.usr.dsi.unimi.it> 2000 Copyright (C) Robert O'Callahan 2006 (added cached credential code). Copyright (C) Kai Blin <kai@samba.org> 2008 Copyright (C) Simo Sorce 2010 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "includes.h" #include "lib/param/param.h" #include "popt_common.h" #include "utils/ntlm_auth.h" #include "../libcli/auth/libcli_auth.h" #include "../libcli/auth/spnego.h" #include "auth/ntlmssp/ntlmssp.h" #include "auth/gensec/gensec.h" #include "auth/gensec/gensec_internal.h" #include "auth/credentials/credentials.h" #include "librpc/crypto/gse.h" #include "smb_krb5.h" #include "lib/util/tiniparser.h" #include "../lib/crypto/arcfour.h" #include "libads/kerberos_proto.h" #include "nsswitch/winbind_client.h" #include "librpc/gen_ndr/krb5pac.h" #include "../lib/util/asn1.h" #include "auth/common_auth.h" #include "source3/include/auth.h" #include "source3/auth/proto.h" #include "nsswitch/libwbclient/wbclient.h" #include "lib/param/loadparm.h" #if HAVE_KRB5 #include "auth/kerberos/pac_utils.h" #endif #ifndef PAM_WINBIND_CONFIG_FILE #define PAM_WINBIND_CONFIG_FILE "/etc/security/pam_winbind.conf" #endif #define WINBIND_KRB5_AUTH 0x00000080 #undef DBGC_CLASS #define DBGC_CLASS DBGC_WINBIND #define INITIAL_BUFFER_SIZE 300 #define MAX_BUFFER_SIZE 630000 enum stdio_helper_mode { SQUID_2_4_BASIC, SQUID_2_5_BASIC, SQUID_2_5_NTLMSSP, NTLMSSP_CLIENT_1, GSS_SPNEGO_SERVER, GSS_SPNEGO_CLIENT, NTLM_SERVER_1, NTLM_CHANGE_PASSWORD_1, NUM_HELPER_MODES }; enum ntlm_auth_cli_state { CLIENT_INITIAL = 0, CLIENT_RESPONSE, CLIENT_FINISHED, CLIENT_ERROR }; struct ntlm_auth_state { TALLOC_CTX *mem_ctx; enum stdio_helper_mode helper_mode; enum ntlm_auth_cli_state cli_state; struct ntlmssp_state *ntlmssp_state; uint32_t neg_flags; char *want_feature_list; bool have_session_key; DATA_BLOB session_key; DATA_BLOB initial_message; void *gensec_private_1; }; typedef void (*stdio_helper_function)(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2); static void manage_squid_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, stdio_helper_function fn, void **private2); static void manage_squid_basic_request (enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2); static void manage_squid_ntlmssp_request (enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2); static void manage_client_ntlmssp_request (enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2); static void manage_gss_spnego_request (enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2); static void manage_gss_spnego_client_request (enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2); static void manage_ntlm_server_1_request (enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2); static void manage_ntlm_change_password_1_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2); static const struct { enum stdio_helper_mode mode; const char *name; stdio_helper_function fn; } stdio_helper_protocols[] = { { SQUID_2_4_BASIC, "squid-2.4-basic", manage_squid_basic_request}, { SQUID_2_5_BASIC, "squid-2.5-basic", manage_squid_basic_request}, { SQUID_2_5_NTLMSSP, "squid-2.5-ntlmssp", manage_squid_ntlmssp_request}, { NTLMSSP_CLIENT_1, "ntlmssp-client-1", manage_client_ntlmssp_request}, { GSS_SPNEGO_SERVER, "gss-spnego", manage_gss_spnego_request}, { GSS_SPNEGO_CLIENT, "gss-spnego-client", manage_gss_spnego_client_request}, { NTLM_SERVER_1, "ntlm-server-1", manage_ntlm_server_1_request}, { NTLM_CHANGE_PASSWORD_1, "ntlm-change-password-1", manage_ntlm_change_password_1_request}, { NUM_HELPER_MODES, NULL, NULL} }; const char *opt_username; const char *opt_domain; const char *opt_workstation; const char *opt_password; static DATA_BLOB opt_challenge; static DATA_BLOB opt_lm_response; static DATA_BLOB opt_nt_response; static int request_lm_key; static int request_user_session_key; static int use_cached_creds; static const char *require_membership_of; static const char *require_membership_of_sid; static const char *opt_pam_winbind_conf; const char *opt_target_service; const char *opt_target_hostname; /* This is a bit hairy, but the basic idea is to do a password callback to the calling application. The callback comes from within gensec */ static void manage_gensec_get_pw_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **password) { DATA_BLOB in; if (strlen(buf) < 2) { DEBUG(1, ("query [%s] invalid", buf)); x_fprintf(x_stdout, "BH Query invalid\n"); return; } if (strlen(buf) > 3) { in = base64_decode_data_blob(buf + 3); } else { in = data_blob(NULL, 0); } if (strncmp(buf, "PW ", 3) == 0) { *password = talloc_strndup(NULL, (const char *)in.data, in.length); if (*password == NULL) { DEBUG(1, ("Out of memory\n")); x_fprintf(x_stdout, "BH Out of memory\n"); data_blob_free(&in); return; } x_fprintf(x_stdout, "OK\n"); data_blob_free(&in); return; } DEBUG(1, ("Asked for (and expected) a password\n")); x_fprintf(x_stdout, "BH Expected a password\n"); data_blob_free(&in); } /** * Callback for password credentials. This is not async, and when * GENSEC and the credentials code is made async, it will look rather * different. */ static const char *get_password(struct cli_credentials *credentials) { char *password = NULL; /* Ask for a password */ x_fprintf(x_stdout, "PW\n"); manage_squid_request(NUM_HELPER_MODES /* bogus */, NULL, NULL, manage_gensec_get_pw_request, (void **)&password); talloc_steal(credentials, password); return password; } /** * A limited set of features are defined with text strings as needed * by ntlm_auth * */ static void gensec_want_feature_list(struct gensec_security *state, char* feature_list) { if (in_list("NTLMSSP_FEATURE_SESSION_KEY", feature_list, true)) { DEBUG(10, ("want GENSEC_FEATURE_SESSION_KEY\n")); gensec_want_feature(state, GENSEC_FEATURE_SESSION_KEY); } if (in_list("NTLMSSP_FEATURE_SIGN", feature_list, true)) { DEBUG(10, ("want GENSEC_FEATURE_SIGN\n")); gensec_want_feature(state, GENSEC_FEATURE_SIGN); } if (in_list("NTLMSSP_FEATURE_SEAL", feature_list, true)) { DEBUG(10, ("want GENSEC_FEATURE_SEAL\n")); gensec_want_feature(state, GENSEC_FEATURE_SEAL); } } static char winbind_separator(void) { struct winbindd_response response; static bool got_sep; static char sep; if (got_sep) return sep; ZERO_STRUCT(response); /* Send off request */ if (winbindd_request_response(NULL, WINBINDD_INFO, NULL, &response) != NSS_STATUS_SUCCESS) { d_printf("could not obtain winbind separator!\n"); return *lp_winbind_separator(); } sep = response.data.info.winbind_separator; got_sep = True; if (!sep) { d_printf("winbind separator was NULL!\n"); return *lp_winbind_separator(); } return sep; } const char *get_winbind_domain(void) { struct winbindd_response response; static fstring winbind_domain; if (*winbind_domain) { return winbind_domain; } ZERO_STRUCT(response); /* Send off request */ if (winbindd_request_response(NULL, WINBINDD_DOMAIN_NAME, NULL, &response) != NSS_STATUS_SUCCESS) { DEBUG(1, ("could not obtain winbind domain name!\n")); return lp_workgroup(); } fstrcpy(winbind_domain, response.data.domain_name); return winbind_domain; } const char *get_winbind_netbios_name(void) { struct winbindd_response response; static fstring winbind_netbios_name; if (*winbind_netbios_name) { return winbind_netbios_name; } ZERO_STRUCT(response); /* Send off request */ if (winbindd_request_response(NULL, WINBINDD_NETBIOS_NAME, NULL, &response) != NSS_STATUS_SUCCESS) { DEBUG(1, ("could not obtain winbind netbios name!\n")); return lp_netbios_name(); } fstrcpy(winbind_netbios_name, response.data.netbios_name); return winbind_netbios_name; } DATA_BLOB get_challenge(void) { static DATA_BLOB chal; if (opt_challenge.length) return opt_challenge; chal = data_blob(NULL, 8); generate_random_buffer(chal.data, chal.length); return chal; } /* Copy of parse_domain_user from winbindd_util.c. Parse a string of the form DOMAIN/user into a domain and a user */ static bool parse_ntlm_auth_domain_user(const char *domuser, fstring domain, fstring user) { char *p = strchr(domuser,winbind_separator()); if (!p) { return False; } fstrcpy(user, p+1); fstrcpy(domain, domuser); domain[PTR_DIFF(p, domuser)] = 0; return strupper_m(domain); } static bool get_require_membership_sid(void) { struct winbindd_request request; struct winbindd_response response; if (!require_membership_of) { return True; } if (require_membership_of_sid) { return True; } /* Otherwise, ask winbindd for the name->sid request */ ZERO_STRUCT(request); ZERO_STRUCT(response); if (!parse_ntlm_auth_domain_user(require_membership_of, request.data.name.dom_name, request.data.name.name)) { DEBUG(0, ("Could not parse %s into separate domain/name parts!\n", require_membership_of)); return False; } if (winbindd_request_response(NULL, WINBINDD_LOOKUPNAME, &request, &response) != NSS_STATUS_SUCCESS) { DEBUG(0, ("Winbindd lookupname failed to resolve %s into a SID!\n", require_membership_of)); return False; } require_membership_of_sid = SMB_STRDUP(response.data.sid.sid); if (require_membership_of_sid) return True; return False; } /* * Get some configuration from pam_winbind.conf to see if we * need to contact trusted domain */ int get_pam_winbind_config() { int ctrl = 0; struct tiniparser_dictionary *d = NULL; if (!opt_pam_winbind_conf || !*opt_pam_winbind_conf) { opt_pam_winbind_conf = PAM_WINBIND_CONFIG_FILE; } d = tiniparser_load(opt_pam_winbind_conf); if (!d) { return 0; } if (tiniparser_getboolean(d, "global:krb5_auth", false)) { ctrl |= WINBIND_KRB5_AUTH; } tiniparser_freedict(d); return ctrl; } /* Authenticate a user with a plaintext password */ static bool check_plaintext_auth(const char *user, const char *pass, bool stdout_diagnostics) { struct winbindd_request request; struct winbindd_response response; NSS_STATUS result; if (!get_require_membership_sid()) { return False; } /* Send off request */ ZERO_STRUCT(request); ZERO_STRUCT(response); fstrcpy(request.data.auth.user, user); fstrcpy(request.data.auth.pass, pass); if (require_membership_of_sid) { strlcpy(request.data.auth.require_membership_of_sid, require_membership_of_sid, sizeof(request.data.auth.require_membership_of_sid)); } result = winbindd_request_response(NULL, WINBINDD_PAM_AUTH, &request, &response); /* Display response */ if (stdout_diagnostics) { if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) { d_printf("Reading winbind reply failed! (0x01)\n"); } d_printf("%s: %s (0x%x)\n", response.data.auth.nt_status_string, response.data.auth.error_string, response.data.auth.nt_status); } else { if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) { DEBUG(1, ("Reading winbind reply failed! (0x01)\n")); } DEBUG(3, ("%s: %s (0x%x)\n", response.data.auth.nt_status_string, response.data.auth.error_string, response.data.auth.nt_status)); } return (result == NSS_STATUS_SUCCESS); } /* authenticate a user with an encrypted username/password */ NTSTATUS contact_winbind_auth_crap(const char *username, const char *domain, const char *workstation, const DATA_BLOB *challenge, const DATA_BLOB *lm_response, const DATA_BLOB *nt_response, uint32_t flags, uint32_t extra_logon_parameters, uint8_t lm_key[8], uint8_t user_session_key[16], char **error_string, char **unix_name) { NTSTATUS nt_status; NSS_STATUS result; struct winbindd_request request; struct winbindd_response response; if (!get_require_membership_sid()) { return NT_STATUS_INVALID_PARAMETER; } ZERO_STRUCT(request); ZERO_STRUCT(response); request.flags = flags; request.data.auth_crap.logon_parameters = extra_logon_parameters | MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT | MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT; if (require_membership_of_sid) fstrcpy(request.data.auth_crap.require_membership_of_sid, require_membership_of_sid); fstrcpy(request.data.auth_crap.user, username); fstrcpy(request.data.auth_crap.domain, domain); fstrcpy(request.data.auth_crap.workstation, workstation); memcpy(request.data.auth_crap.chal, challenge->data, MIN(challenge->length, 8)); if (lm_response && lm_response->length) { memcpy(request.data.auth_crap.lm_resp, lm_response->data, MIN(lm_response->length, sizeof(request.data.auth_crap.lm_resp))); request.data.auth_crap.lm_resp_len = lm_response->length; } if (nt_response && nt_response->length) { if (nt_response->length > sizeof(request.data.auth_crap.nt_resp)) { request.flags = request.flags | WBFLAG_BIG_NTLMV2_BLOB; request.extra_len = nt_response->length; request.extra_data.data = SMB_MALLOC_ARRAY(char, request.extra_len); if (request.extra_data.data == NULL) { return NT_STATUS_NO_MEMORY; } memcpy(request.extra_data.data, nt_response->data, nt_response->length); } else { memcpy(request.data.auth_crap.nt_resp, nt_response->data, nt_response->length); } request.data.auth_crap.nt_resp_len = nt_response->length; } result = winbindd_request_response(NULL, WINBINDD_PAM_AUTH_CRAP, &request, &response); SAFE_FREE(request.extra_data.data); /* Display response */ if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) { nt_status = NT_STATUS_UNSUCCESSFUL; if (error_string) *error_string = smb_xstrdup("Reading winbind reply failed!"); winbindd_free_response(&response); return nt_status; } nt_status = (NT_STATUS(response.data.auth.nt_status)); if (!NT_STATUS_IS_OK(nt_status)) { if (error_string) *error_string = smb_xstrdup(response.data.auth.error_string); winbindd_free_response(&response); return nt_status; } if ((flags & WBFLAG_PAM_LMKEY) && lm_key) { memcpy(lm_key, response.data.auth.first_8_lm_hash, sizeof(response.data.auth.first_8_lm_hash)); } if ((flags & WBFLAG_PAM_USER_SESSION_KEY) && user_session_key) { memcpy(user_session_key, response.data.auth.user_session_key, sizeof(response.data.auth.user_session_key)); } if (flags & WBFLAG_PAM_UNIX_NAME) { *unix_name = SMB_STRDUP(response.data.auth.unix_username); if (!*unix_name) { winbindd_free_response(&response); return NT_STATUS_NO_MEMORY; } } winbindd_free_response(&response); return nt_status; } /* contact server to change user password using auth crap */ static NTSTATUS contact_winbind_change_pswd_auth_crap(const char *username, const char *domain, const DATA_BLOB new_nt_pswd, const DATA_BLOB old_nt_hash_enc, const DATA_BLOB new_lm_pswd, const DATA_BLOB old_lm_hash_enc, char **error_string) { NTSTATUS nt_status; NSS_STATUS result; struct winbindd_request request; struct winbindd_response response; if (!get_require_membership_sid()) { if(error_string) *error_string = smb_xstrdup("Can't get membership sid."); return NT_STATUS_INVALID_PARAMETER; } ZERO_STRUCT(request); ZERO_STRUCT(response); if(username != NULL) fstrcpy(request.data.chng_pswd_auth_crap.user, username); if(domain != NULL) fstrcpy(request.data.chng_pswd_auth_crap.domain,domain); if(new_nt_pswd.length) { memcpy(request.data.chng_pswd_auth_crap.new_nt_pswd, new_nt_pswd.data, sizeof(request.data.chng_pswd_auth_crap.new_nt_pswd)); request.data.chng_pswd_auth_crap.new_nt_pswd_len = new_nt_pswd.length; } if(old_nt_hash_enc.length) { memcpy(request.data.chng_pswd_auth_crap.old_nt_hash_enc, old_nt_hash_enc.data, sizeof(request.data.chng_pswd_auth_crap.old_nt_hash_enc)); request.data.chng_pswd_auth_crap.old_nt_hash_enc_len = old_nt_hash_enc.length; } if(new_lm_pswd.length) { memcpy(request.data.chng_pswd_auth_crap.new_lm_pswd, new_lm_pswd.data, sizeof(request.data.chng_pswd_auth_crap.new_lm_pswd)); request.data.chng_pswd_auth_crap.new_lm_pswd_len = new_lm_pswd.length; } if(old_lm_hash_enc.length) { memcpy(request.data.chng_pswd_auth_crap.old_lm_hash_enc, old_lm_hash_enc.data, sizeof(request.data.chng_pswd_auth_crap.old_lm_hash_enc)); request.data.chng_pswd_auth_crap.old_lm_hash_enc_len = old_lm_hash_enc.length; } result = winbindd_request_response(NULL, WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, &request, &response); /* Display response */ if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) { nt_status = NT_STATUS_UNSUCCESSFUL; if (error_string) *error_string = smb_xstrdup("Reading winbind reply failed!"); winbindd_free_response(&response); return nt_status; } nt_status = (NT_STATUS(response.data.auth.nt_status)); if (!NT_STATUS_IS_OK(nt_status)) { if (error_string) *error_string = smb_xstrdup(response.data.auth.error_string); winbindd_free_response(&response); return nt_status; } winbindd_free_response(&response); return nt_status; } static NTSTATUS ntlm_auth_generate_session_info(struct auth4_context *auth_context, TALLOC_CTX *mem_ctx, void *server_returned_info, const char *original_user_name, uint32_t session_info_flags, struct auth_session_info **session_info_out) { char *unix_username = (char *)server_returned_info; struct auth_session_info *session_info = talloc_zero(mem_ctx, struct auth_session_info); if (!session_info) { return NT_STATUS_NO_MEMORY; } session_info->unix_info = talloc_zero(session_info, struct auth_user_info_unix); if (!session_info->unix_info) { TALLOC_FREE(session_info); return NT_STATUS_NO_MEMORY; } session_info->unix_info->unix_name = talloc_steal(session_info->unix_info, unix_username); *session_info_out = session_info; return NT_STATUS_OK; } static NTSTATUS ntlm_auth_generate_session_info_pac(struct auth4_context *auth_ctx, TALLOC_CTX *mem_ctx, struct smb_krb5_context *smb_krb5_context, DATA_BLOB *pac_blob, const char *princ_name, const struct tsocket_address *remote_address, uint32_t session_info_flags, struct auth_session_info **session_info) { TALLOC_CTX *tmp_ctx; struct PAC_LOGON_INFO *logon_info = NULL; char *unixuser; NTSTATUS status; char *domain = NULL; char *realm = NULL; char *user = NULL; char *p; tmp_ctx = talloc_new(mem_ctx); if (!tmp_ctx) { return NT_STATUS_NO_MEMORY; } if (pac_blob) { #ifdef HAVE_KRB5 status = kerberos_pac_logon_info(tmp_ctx, *pac_blob, NULL, NULL, NULL, NULL, 0, &logon_info); #else status = NT_STATUS_ACCESS_DENIED; #endif if (!NT_STATUS_IS_OK(status)) { goto done; } } DEBUG(3, ("Kerberos ticket principal name is [%s]\n", princ_name)); p = strchr_m(princ_name, '@'); if (!p) { DEBUG(3, ("[%s] Doesn't look like a valid principal\n", princ_name)); return NT_STATUS_LOGON_FAILURE; } user = talloc_strndup(mem_ctx, princ_name, p - princ_name); if (!user) { return NT_STATUS_NO_MEMORY; } realm = talloc_strdup(talloc_tos(), p + 1); if (!realm) { return NT_STATUS_NO_MEMORY; } if (!strequal(realm, lp_realm())) { DEBUG(3, ("Ticket for foreign realm %s@%s\n", user, realm)); if (!lp_allow_trusted_domains()) { return NT_STATUS_LOGON_FAILURE; } } if (logon_info && logon_info->info3.base.logon_domain.string) { domain = talloc_strdup(mem_ctx, logon_info->info3.base.logon_domain.string); if (!domain) { return NT_STATUS_NO_MEMORY; } DEBUG(10, ("Domain is [%s] (using PAC)\n", domain)); } else { /* If we have winbind running, we can (and must) shorten the username by using the short netbios name. Otherwise we will have inconsistent user names. With Kerberos, we get the fully qualified realm, with ntlmssp we get the short name. And even w2k3 does use ntlmssp if you for example connect to an ip address. */ wbcErr wbc_status; struct wbcDomainInfo *info = NULL; DEBUG(10, ("Mapping [%s] to short name using winbindd\n", realm)); wbc_status = wbcDomainInfo(realm, &info); if (WBC_ERROR_IS_OK(wbc_status)) { domain = talloc_strdup(mem_ctx, info->short_name); wbcFreeMemory(info); } else { DEBUG(3, ("Could not find short name: %s\n", wbcErrorString(wbc_status))); domain = talloc_strdup(mem_ctx, realm); } if (!domain) { return NT_STATUS_NO_MEMORY; } DEBUG(10, ("Domain is [%s] (using Winbind)\n", domain)); } unixuser = talloc_asprintf(tmp_ctx, "%s%c%s", domain, winbind_separator(), user); if (!unixuser) { status = NT_STATUS_NO_MEMORY; goto done; } status = ntlm_auth_generate_session_info(auth_ctx, mem_ctx, unixuser, NULL, session_info_flags, session_info); done: TALLOC_FREE(tmp_ctx); return status; } /** * Return the challenge as determined by the authentication subsystem * @return an 8 byte random challenge */ static NTSTATUS ntlm_auth_get_challenge(struct auth4_context *auth_ctx, uint8_t chal[8]) { if (auth_ctx->challenge.data.length == 8) { DEBUG(5, ("auth_get_challenge: returning previous challenge by module %s (normal)\n", auth_ctx->challenge.set_by)); memcpy(chal, auth_ctx->challenge.data.data, 8); return NT_STATUS_OK; } if (!auth_ctx->challenge.set_by) { generate_random_buffer(chal, 8); auth_ctx->challenge.data = data_blob_talloc(auth_ctx, chal, 8); NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.data.data); auth_ctx->challenge.set_by = "random"; } DEBUG(10,("auth_get_challenge: challenge set by %s\n", auth_ctx->challenge.set_by)); return NT_STATUS_OK; } /** * NTLM2 authentication modifies the effective challenge, * @param challenge The new challenge value */ static NTSTATUS ntlm_auth_set_challenge(struct auth4_context *auth_ctx, const uint8_t chal[8], const char *set_by) { auth_ctx->challenge.set_by = talloc_strdup(auth_ctx, set_by); NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.set_by); auth_ctx->challenge.data = data_blob_talloc(auth_ctx, chal, 8); NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.data.data); return NT_STATUS_OK; } /** * Check the password on an NTLMSSP login. * * Return the session keys used on the connection. */ static NTSTATUS winbind_pw_check(struct auth4_context *auth4_context, TALLOC_CTX *mem_ctx, const struct auth_usersupplied_info *user_info, void **server_returned_info, DATA_BLOB *session_key, DATA_BLOB *lm_session_key) { static const char zeros[16] = { 0, }; NTSTATUS nt_status; char *error_string = NULL; uint8_t lm_key[8]; uint8_t user_sess_key[16]; char *unix_name = NULL; nt_status = contact_winbind_auth_crap(user_info->client.account_name, user_info->client.domain_name, user_info->workstation_name, &auth4_context->challenge.data, &user_info->password.response.lanman, &user_info->password.response.nt, WBFLAG_PAM_LMKEY | WBFLAG_PAM_USER_SESSION_KEY | WBFLAG_PAM_UNIX_NAME, 0, lm_key, user_sess_key, &error_string, &unix_name); if (NT_STATUS_IS_OK(nt_status)) { if (memcmp(lm_key, zeros, 8) != 0) { *lm_session_key = data_blob_talloc(mem_ctx, NULL, 16); memcpy(lm_session_key->data, lm_key, 8); memset(lm_session_key->data+8, '\0', 8); } if (memcmp(user_sess_key, zeros, 16) != 0) { *session_key = data_blob_talloc(mem_ctx, user_sess_key, 16); } *server_returned_info = talloc_strdup(mem_ctx, unix_name); } else { DEBUG(NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED) ? 0 : 3, ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", user_info->client.domain_name, user_info->client.account_name, user_info->workstation_name, error_string ? error_string : "unknown error (NULL)")); } SAFE_FREE(error_string); SAFE_FREE(unix_name); return nt_status; } static NTSTATUS local_pw_check(struct auth4_context *auth4_context, TALLOC_CTX *mem_ctx, const struct auth_usersupplied_info *user_info, void **server_returned_info, DATA_BLOB *session_key, DATA_BLOB *lm_session_key) { NTSTATUS nt_status; struct samr_Password lm_pw, nt_pw; nt_lm_owf_gen (opt_password, nt_pw.hash, lm_pw.hash); nt_status = ntlm_password_check(mem_ctx, true, true, 0, &auth4_context->challenge.data, &user_info->password.response.lanman, &user_info->password.response.nt, user_info->client.account_name, user_info->client.account_name, user_info->client.domain_name, &lm_pw, &nt_pw, session_key, lm_session_key); if (NT_STATUS_IS_OK(nt_status)) { *server_returned_info = talloc_asprintf(mem_ctx, "%s%c%s", user_info->client.domain_name, *lp_winbind_separator(), user_info->client.account_name); } else { DEBUG(3, ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", user_info->client.domain_name, user_info->client.account_name, user_info->workstation_name, nt_errstr(nt_status))); } return nt_status; } static NTSTATUS ntlm_auth_start_ntlmssp_client(struct ntlmssp_state **client_ntlmssp_state) { NTSTATUS status; if ( (opt_username == NULL) || (opt_domain == NULL) ) { status = NT_STATUS_UNSUCCESSFUL; DEBUG(1, ("Need username and domain for NTLMSSP\n")); return NT_STATUS_INVALID_PARAMETER; } status = ntlmssp_client_start(NULL, lp_netbios_name(), lp_workgroup(), lp_client_ntlmv2_auth(), client_ntlmssp_state); if (!NT_STATUS_IS_OK(status)) { DEBUG(1, ("Could not start NTLMSSP client: %s\n", nt_errstr(status))); TALLOC_FREE(*client_ntlmssp_state); return status; } status = ntlmssp_set_username(*client_ntlmssp_state, opt_username); if (!NT_STATUS_IS_OK(status)) { DEBUG(1, ("Could not set username: %s\n", nt_errstr(status))); TALLOC_FREE(*client_ntlmssp_state); return status; } status = ntlmssp_set_domain(*client_ntlmssp_state, opt_domain); if (!NT_STATUS_IS_OK(status)) { DEBUG(1, ("Could not set domain: %s\n", nt_errstr(status))); TALLOC_FREE(*client_ntlmssp_state); return status; } if (opt_password) { status = ntlmssp_set_password(*client_ntlmssp_state, opt_password); if (!NT_STATUS_IS_OK(status)) { DEBUG(1, ("Could not set password: %s\n", nt_errstr(status))); TALLOC_FREE(*client_ntlmssp_state); return status; } } return NT_STATUS_OK; } static struct auth4_context *make_auth4_context_ntlm_auth(TALLOC_CTX *mem_ctx, bool local_pw) { struct auth4_context *auth4_context = talloc_zero(mem_ctx, struct auth4_context); if (auth4_context == NULL) { DEBUG(10, ("failed to allocate auth4_context failed\n")); return NULL; } auth4_context->generate_session_info = ntlm_auth_generate_session_info; auth4_context->generate_session_info_pac = ntlm_auth_generate_session_info_pac; auth4_context->get_ntlm_challenge = ntlm_auth_get_challenge; auth4_context->set_ntlm_challenge = ntlm_auth_set_challenge; if (local_pw) { auth4_context->check_ntlm_password = local_pw_check; } else { auth4_context->check_ntlm_password = winbind_pw_check; } auth4_context->private_data = NULL; return auth4_context; } static NTSTATUS ntlm_auth_prepare_gensec_server(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx, struct gensec_security **gensec_security_out) { struct gensec_security *gensec_security; NTSTATUS nt_status; TALLOC_CTX *tmp_ctx; const struct gensec_security_ops **backends; struct gensec_settings *gensec_settings; size_t idx = 0; struct cli_credentials *server_credentials; struct auth4_context *auth4_context; tmp_ctx = talloc_new(mem_ctx); NT_STATUS_HAVE_NO_MEMORY(tmp_ctx); auth4_context = make_auth4_context_ntlm_auth(tmp_ctx, opt_password); if (auth4_context == NULL) { TALLOC_FREE(tmp_ctx); return NT_STATUS_NO_MEMORY; } gensec_settings = lpcfg_gensec_settings(tmp_ctx, lp_ctx); if (lp_ctx == NULL) { DEBUG(10, ("lpcfg_gensec_settings failed\n")); TALLOC_FREE(tmp_ctx); return NT_STATUS_NO_MEMORY; } /* * This should be a 'netbios domain -> DNS domain' * mapping, and can currently validly return NULL on * poorly configured systems. * * This is used for the NTLMSSP server * */ if (opt_password) { gensec_settings->server_netbios_name = lp_netbios_name(); gensec_settings->server_netbios_domain = lp_workgroup(); } else { gensec_settings->server_netbios_name = get_winbind_netbios_name(); gensec_settings->server_netbios_domain = get_winbind_domain(); } gensec_settings->server_dns_domain = strlower_talloc(gensec_settings, get_mydnsdomname(talloc_tos())); gensec_settings->server_dns_name = strlower_talloc(gensec_settings, get_mydnsfullname()); backends = talloc_zero_array(gensec_settings, const struct gensec_security_ops *, 4); if (backends == NULL) { TALLOC_FREE(tmp_ctx); return NT_STATUS_NO_MEMORY; } gensec_settings->backends = backends; gensec_init(); /* These need to be in priority order, krb5 before NTLMSSP */ #if defined(HAVE_KRB5) backends[idx++] = &gensec_gse_krb5_security_ops; #endif backends[idx++] = gensec_security_by_oid(NULL, GENSEC_OID_NTLMSSP); backends[idx++] = gensec_security_by_oid(NULL, GENSEC_OID_SPNEGO); /* * This is anonymous for now, because we just use it * to set the kerberos state at the moment */ server_credentials = cli_credentials_init_anon(tmp_ctx); if (!server_credentials) { DEBUG(0, ("auth_generic_prepare: Failed to init server credentials\n")); return NT_STATUS_NO_MEMORY; } cli_credentials_set_conf(server_credentials, lp_ctx); if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC || lp_security() == SEC_ADS || USE_KERBEROS_KEYTAB) { cli_credentials_set_kerberos_state(server_credentials, CRED_AUTO_USE_KERBEROS); } else { cli_credentials_set_kerberos_state(server_credentials, CRED_DONT_USE_KERBEROS); } nt_status = gensec_server_start(tmp_ctx, gensec_settings, auth4_context, &gensec_security); if (!NT_STATUS_IS_OK(nt_status)) { TALLOC_FREE(tmp_ctx); return nt_status; } gensec_set_credentials(gensec_security, server_credentials); gensec_want_feature(gensec_security, GENSEC_FEATURE_SIGN); gensec_want_feature(gensec_security, GENSEC_FEATURE_SEAL); talloc_unlink(tmp_ctx, lp_ctx); talloc_unlink(tmp_ctx, server_credentials); talloc_unlink(tmp_ctx, gensec_settings); talloc_unlink(tmp_ctx, auth4_context); *gensec_security_out = talloc_steal(mem_ctx, gensec_security); TALLOC_FREE(tmp_ctx); return NT_STATUS_OK; } /******************************************************************* Used by firefox to drive NTLM auth to IIS servers. *******************************************************************/ static NTSTATUS do_ccache_ntlm_auth(DATA_BLOB initial_msg, DATA_BLOB challenge_msg, DATA_BLOB *reply) { struct winbindd_request wb_request; struct winbindd_response wb_response; int ctrl = 0; NSS_STATUS result; /* get winbindd to do the ntlmssp step on our behalf */ ZERO_STRUCT(wb_request); ZERO_STRUCT(wb_response); /* * This is tricky here. If we set krb5_auth in pam_winbind.conf * creds for users in trusted domain will be stored the winbindd * child of the trusted domain. If we ask the primary domain for * ntlm_ccache_auth, it will fail. So, we have to ask the trusted * domain's child for ccache_ntlm_auth. that is to say, we have to * set WBFLAG_PAM_CONTACT_TRUSTDOM in request.flags. */ ctrl = get_pam_winbind_config(); if (ctrl & WINBIND_KRB5_AUTH) { wb_request.flags |= WBFLAG_PAM_CONTACT_TRUSTDOM; } fstr_sprintf(wb_request.data.ccache_ntlm_auth.user, "%s%c%s", opt_domain, winbind_separator(), opt_username); wb_request.data.ccache_ntlm_auth.uid = geteuid(); wb_request.data.ccache_ntlm_auth.initial_blob_len = initial_msg.length; wb_request.data.ccache_ntlm_auth.challenge_blob_len = challenge_msg.length; wb_request.extra_len = initial_msg.length + challenge_msg.length; if (wb_request.extra_len > 0) { wb_request.extra_data.data = SMB_MALLOC_ARRAY(char, wb_request.extra_len); if (wb_request.extra_data.data == NULL) { return NT_STATUS_NO_MEMORY; } memcpy(wb_request.extra_data.data, initial_msg.data, initial_msg.length); memcpy(wb_request.extra_data.data + initial_msg.length, challenge_msg.data, challenge_msg.length); } result = winbindd_request_response(NULL, WINBINDD_CCACHE_NTLMAUTH, &wb_request, &wb_response); SAFE_FREE(wb_request.extra_data.data); if (result != NSS_STATUS_SUCCESS) { winbindd_free_response(&wb_response); return NT_STATUS_UNSUCCESSFUL; } if (reply) { *reply = data_blob(wb_response.extra_data.data, wb_response.data.ccache_ntlm_auth.auth_blob_len); if (wb_response.data.ccache_ntlm_auth.auth_blob_len > 0 && reply->data == NULL) { winbindd_free_response(&wb_response); return NT_STATUS_NO_MEMORY; } } winbindd_free_response(&wb_response); return NT_STATUS_MORE_PROCESSING_REQUIRED; } static void manage_client_ntlmssp_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2) { DATA_BLOB request, reply; NTSTATUS nt_status; if (!opt_username || !*opt_username) { x_fprintf(x_stderr, "username must be specified!\n\n"); exit(1); } if (strlen(buf) < 2) { DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf)); x_fprintf(x_stdout, "BH NTLMSSP query invalid\n"); return; } if (strlen(buf) > 3) { if(strncmp(buf, "SF ", 3) == 0) { DEBUG(10, ("Looking for flags to negotiate\n")); talloc_free(state->want_feature_list); state->want_feature_list = talloc_strdup(state->mem_ctx, buf+3); x_fprintf(x_stdout, "OK\n"); return; } request = base64_decode_data_blob(buf + 3); } else { request = data_blob_null; } if (strncmp(buf, "PW ", 3) == 0) { /* We asked for a password and obviously got it :-) */ opt_password = SMB_STRNDUP((const char *)request.data, request.length); if (opt_password == NULL) { DEBUG(1, ("Out of memory\n")); x_fprintf(x_stdout, "BH Out of memory\n"); data_blob_free(&request); return; } x_fprintf(x_stdout, "OK\n"); data_blob_free(&request); return; } if (!state->ntlmssp_state && use_cached_creds) { /* check whether cached credentials are usable. */ DATA_BLOB empty_blob = data_blob_null; nt_status = do_ccache_ntlm_auth(empty_blob, empty_blob, NULL); if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) { /* failed to use cached creds */ use_cached_creds = False; } } if (opt_password == NULL && !use_cached_creds) { /* Request a password from the calling process. After sending it, the calling process should retry asking for the negotiate. */ DEBUG(10, ("Requesting password\n")); x_fprintf(x_stdout, "PW\n"); return; } if (strncmp(buf, "YR", 2) == 0) { TALLOC_FREE(state->ntlmssp_state); state->cli_state = CLIENT_INITIAL; } else if (strncmp(buf, "TT", 2) == 0) { /* No special preprocessing required */ } else if (strncmp(buf, "GF", 2) == 0) { DEBUG(10, ("Requested negotiated NTLMSSP flags\n")); if(state->cli_state == CLIENT_FINISHED) { x_fprintf(x_stdout, "GF 0x%08x\n", state->neg_flags); } else { x_fprintf(x_stdout, "BH\n"); } data_blob_free(&request); return; } else if (strncmp(buf, "GK", 2) == 0 ) { DEBUG(10, ("Requested session key\n")); if(state->cli_state == CLIENT_FINISHED) { char *key64 = base64_encode_data_blob(state->mem_ctx, state->session_key); x_fprintf(x_stdout, "GK %s\n", key64?key64:"<NULL>"); TALLOC_FREE(key64); } else { x_fprintf(x_stdout, "BH\n"); } data_blob_free(&request); return; } else { DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf)); x_fprintf(x_stdout, "BH NTLMSSP query invalid\n"); return; } if (!state->ntlmssp_state) { nt_status = ntlm_auth_start_ntlmssp_client( &state->ntlmssp_state); if (!NT_STATUS_IS_OK(nt_status)) { x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status)); return; } ntlmssp_want_feature_list(state->ntlmssp_state, state->want_feature_list); state->initial_message = data_blob_null; } DEBUG(10, ("got NTLMSSP packet:\n")); dump_data(10, request.data, request.length); if (use_cached_creds && !opt_password && (state->cli_state == CLIENT_RESPONSE)) { nt_status = do_ccache_ntlm_auth(state->initial_message, request, &reply); } else { nt_status = ntlmssp_update(state->ntlmssp_state, request, &reply); } if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) { char *reply_base64 = base64_encode_data_blob(state->mem_ctx, reply); if (state->cli_state == CLIENT_INITIAL) { x_fprintf(x_stdout, "YR %s\n", reply_base64); state->initial_message = reply; state->cli_state = CLIENT_RESPONSE; } else { x_fprintf(x_stdout, "KK %s\n", reply_base64); data_blob_free(&reply); } TALLOC_FREE(reply_base64); DEBUG(10, ("NTLMSSP challenge\n")); } else if (NT_STATUS_IS_OK(nt_status)) { char *reply_base64 = base64_encode_data_blob(talloc_tos(), reply); x_fprintf(x_stdout, "AF %s\n", reply_base64); TALLOC_FREE(reply_base64); if(state->have_session_key) data_blob_free(&state->session_key); state->session_key = data_blob( state->ntlmssp_state->session_key.data, state->ntlmssp_state->session_key.length); state->neg_flags = state->ntlmssp_state->neg_flags; state->have_session_key = true; DEBUG(10, ("NTLMSSP OK!\n")); state->cli_state = CLIENT_FINISHED; TALLOC_FREE(state->ntlmssp_state); } else { x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status)); DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status))); state->cli_state = CLIENT_ERROR; TALLOC_FREE(state->ntlmssp_state); } data_blob_free(&request); } static void manage_squid_basic_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2) { char *user, *pass; user=buf; pass=(char *)memchr(buf,' ',length); if (!pass) { DEBUG(2, ("Password not found. Denying access\n")); x_fprintf(x_stdout, "ERR\n"); return; } *pass='\0'; pass++; if (state->helper_mode == SQUID_2_5_BASIC) { rfc1738_unescape(user); rfc1738_unescape(pass); } if (check_plaintext_auth(user, pass, False)) { x_fprintf(x_stdout, "OK\n"); } else { x_fprintf(x_stdout, "ERR\n"); } } static void manage_gensec_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, char *buf, int length, void **private1) { DATA_BLOB in; DATA_BLOB out = data_blob(NULL, 0); char *out_base64 = NULL; const char *reply_arg = NULL; struct gensec_ntlm_state { struct gensec_security *gensec_state; const char *set_password; }; struct gensec_ntlm_state *state; NTSTATUS nt_status; bool first = false; const char *reply_code; struct cli_credentials *creds; static char *want_feature_list = NULL; static DATA_BLOB session_key; TALLOC_CTX *mem_ctx; if (*private1) { state = (struct gensec_ntlm_state *)*private1; } else { state = talloc_zero(NULL, struct gensec_ntlm_state); if (!state) { x_fprintf(x_stdout, "BH No Memory\n"); exit(1); } *private1 = state; if (opt_password) { state->set_password = opt_password; } } if (strlen(buf) < 2) { DEBUG(1, ("query [%s] invalid", buf)); x_fprintf(x_stdout, "BH Query invalid\n"); return; } if (strlen(buf) > 3) { if(strncmp(buf, "SF ", 3) == 0) { DEBUG(10, ("Setting flags to negotiate\n")); talloc_free(want_feature_list); want_feature_list = talloc_strndup(state, buf+3, strlen(buf)-3); x_fprintf(x_stdout, "OK\n"); return; } in = base64_decode_data_blob(buf + 3); } else { in = data_blob(NULL, 0); } if (strncmp(buf, "YR", 2) == 0) { if (state->gensec_state) { talloc_free(state->gensec_state); state->gensec_state = NULL; } } else if ( (strncmp(buf, "OK", 2) == 0)) { /* Just return BH, like ntlm_auth from Samba 3 does. */ x_fprintf(x_stdout, "BH Command expected\n"); data_blob_free(&in); return; } else if ( (strncmp(buf, "TT ", 3) != 0) && (strncmp(buf, "KK ", 3) != 0) && (strncmp(buf, "AF ", 3) != 0) && (strncmp(buf, "NA ", 3) != 0) && (strncmp(buf, "UG", 2) != 0) && (strncmp(buf, "PW ", 3) != 0) && (strncmp(buf, "GK", 2) != 0) && (strncmp(buf, "GF", 2) != 0)) { DEBUG(1, ("SPNEGO request [%s] invalid prefix\n", buf)); x_fprintf(x_stdout, "BH SPNEGO request invalid prefix\n"); data_blob_free(&in); return; } mem_ctx = talloc_named(NULL, 0, "manage_gensec_request internal mem_ctx"); /* setup gensec */ if (!(state->gensec_state)) { switch (stdio_helper_mode) { case GSS_SPNEGO_CLIENT: case NTLMSSP_CLIENT_1: /* setup the client side */ nt_status = gensec_client_start(NULL, &state->gensec_state, lpcfg_gensec_settings(NULL, lp_ctx)); if (!NT_STATUS_IS_OK(nt_status)) { x_fprintf(x_stdout, "BH GENSEC mech failed to start: %s\n", nt_errstr(nt_status)); talloc_free(mem_ctx); return; } creds = cli_credentials_init(state->gensec_state); cli_credentials_set_conf(creds, lp_ctx); if (opt_username) { cli_credentials_set_username(creds, opt_username, CRED_SPECIFIED); } if (opt_domain) { cli_credentials_set_domain(creds, opt_domain, CRED_SPECIFIED); } if (state->set_password) { cli_credentials_set_password(creds, state->set_password, CRED_SPECIFIED); } else { cli_credentials_set_password_callback(creds, get_password); } if (opt_workstation) { cli_credentials_set_workstation(creds, opt_workstation, CRED_SPECIFIED); } gensec_set_credentials(state->gensec_state, creds); break; case GSS_SPNEGO_SERVER: case SQUID_2_5_NTLMSSP: { nt_status = ntlm_auth_prepare_gensec_server(state, lp_ctx, &state->gensec_state); if (!NT_STATUS_IS_OK(nt_status)) { x_fprintf(x_stdout, "BH GENSEC mech failed to start: %s\n", nt_errstr(nt_status)); talloc_free(mem_ctx); return; } break; } default: talloc_free(mem_ctx); abort(); } gensec_want_feature_list(state->gensec_state, want_feature_list); switch (stdio_helper_mode) { case GSS_SPNEGO_CLIENT: case GSS_SPNEGO_SERVER: nt_status = gensec_start_mech_by_oid(state->gensec_state, GENSEC_OID_SPNEGO); if (!in.length) { first = true; } break; case NTLMSSP_CLIENT_1: if (!in.length) { first = true; } /* fall through */ case SQUID_2_5_NTLMSSP: nt_status = gensec_start_mech_by_oid(state->gensec_state, GENSEC_OID_NTLMSSP); break; default: talloc_free(mem_ctx); abort(); } if (!NT_STATUS_IS_OK(nt_status)) { DEBUG(1, ("GENSEC mech failed to start: %s\n", nt_errstr(nt_status))); x_fprintf(x_stdout, "BH GENSEC mech failed to start\n"); talloc_free(mem_ctx); return; } } /* update */ if (strncmp(buf, "PW ", 3) == 0) { state->set_password = talloc_strndup(state, (const char *)in.data, in.length); cli_credentials_set_password(gensec_get_credentials(state->gensec_state), state->set_password, CRED_SPECIFIED); x_fprintf(x_stdout, "OK\n"); data_blob_free(&in); talloc_free(mem_ctx); return; } if (strncmp(buf, "GK", 2) == 0) { char *base64_key; DEBUG(10, ("Requested session key\n")); nt_status = gensec_session_key(state->gensec_state, mem_ctx, &session_key); if(!NT_STATUS_IS_OK(nt_status)) { DEBUG(1, ("gensec_session_key failed: %s\n", nt_errstr(nt_status))); x_fprintf(x_stdout, "BH No session key\n"); talloc_free(mem_ctx); return; } else { base64_key = base64_encode_data_blob(state, session_key); x_fprintf(x_stdout, "GK %s\n", base64_key); talloc_free(base64_key); } talloc_free(mem_ctx); return; } if (stdio_helper_mode == SQUID_2_5_NTLMSSP && strncmp(buf, "GF", 2) == 0) { uint32_t neg_flags; neg_flags = gensec_ntlmssp_neg_flags(state->gensec_state); DEBUG(10, ("Requested negotiated feature flags\n")); x_fprintf(x_stdout, "GF 0x%08x\n", neg_flags); return; } nt_status = gensec_update(state->gensec_state, mem_ctx, in, &out); /* don't leak 'bad password'/'no such user' info to the network client */ nt_status = nt_status_squash(nt_status); if (out.length) { out_base64 = base64_encode_data_blob(mem_ctx, out); } else { out_base64 = NULL; } if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) { reply_arg = "*"; if (first && state->gensec_state->gensec_role == GENSEC_CLIENT) { reply_code = "YR"; } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) { reply_code = "KK"; } else if (state->gensec_state->gensec_role == GENSEC_SERVER) { reply_code = "TT"; } else { abort(); } } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) { reply_code = "BH NT_STATUS_ACCESS_DENIED"; reply_arg = nt_errstr(nt_status); DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status))); } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) { reply_code = "BH NT_STATUS_UNSUCCESSFUL"; reply_arg = nt_errstr(nt_status); DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status))); } else if (!NT_STATUS_IS_OK(nt_status)) { reply_code = "NA"; reply_arg = nt_errstr(nt_status); DEBUG(1, ("GENSEC login failed: %s\n", nt_errstr(nt_status))); } else if /* OK */ (state->gensec_state->gensec_role == GENSEC_SERVER) { struct auth_session_info *session_info; nt_status = gensec_session_info(state->gensec_state, mem_ctx, &session_info); if (!NT_STATUS_IS_OK(nt_status)) { reply_code = "BH Failed to retrive session info"; reply_arg = nt_errstr(nt_status); DEBUG(1, ("GENSEC failed to retrieve the session info: %s\n", nt_errstr(nt_status))); } else { reply_code = "AF"; reply_arg = talloc_strdup(state->gensec_state, session_info->unix_info->unix_name); if (reply_arg == NULL) { reply_code = "BH out of memory"; reply_arg = nt_errstr(NT_STATUS_NO_MEMORY); } talloc_free(session_info); } } else if (state->gensec_state->gensec_role == GENSEC_CLIENT) { reply_code = "AF"; reply_arg = out_base64; } else { abort(); } switch (stdio_helper_mode) { case GSS_SPNEGO_SERVER: x_fprintf(x_stdout, "%s %s %s\n", reply_code, out_base64 ? out_base64 : "*", reply_arg ? reply_arg : "*"); break; default: if (out_base64) { x_fprintf(x_stdout, "%s %s\n", reply_code, out_base64); } else if (reply_arg) { x_fprintf(x_stdout, "%s %s\n", reply_code, reply_arg); } else { x_fprintf(x_stdout, "%s\n", reply_code); } } talloc_free(mem_ctx); return; } static void manage_gss_spnego_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2) { manage_gensec_request(stdio_helper_mode, lp_ctx, buf, length, &state->gensec_private_1); return; } static void manage_squid_ntlmssp_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2) { manage_gensec_request(stdio_helper_mode, lp_ctx, buf, length, &state->gensec_private_1); return; } static struct ntlmssp_state *client_ntlmssp_state = NULL; static bool manage_client_ntlmssp_init(struct spnego_data spnego) { NTSTATUS status; DATA_BLOB null_blob = data_blob_null; DATA_BLOB to_server; char *to_server_base64; const char *my_mechs[] = {OID_NTLMSSP, NULL}; TALLOC_CTX *ctx = talloc_tos(); DEBUG(10, ("Got spnego negTokenInit with NTLMSSP\n")); if (client_ntlmssp_state != NULL) { DEBUG(1, ("Request for initial SPNEGO request where " "we already have a state\n")); return False; } if (!client_ntlmssp_state) { if (!NT_STATUS_IS_OK(status = ntlm_auth_start_ntlmssp_client(&client_ntlmssp_state))) { x_fprintf(x_stdout, "BH %s\n", nt_errstr(status)); return False; } } if (opt_password == NULL) { /* Request a password from the calling process. After sending it, the calling process should retry with the negTokenInit. */ DEBUG(10, ("Requesting password\n")); x_fprintf(x_stdout, "PW\n"); return True; } spnego.type = SPNEGO_NEG_TOKEN_INIT; spnego.negTokenInit.mechTypes = my_mechs; spnego.negTokenInit.reqFlags = data_blob_null; spnego.negTokenInit.reqFlagsPadding = 0; spnego.negTokenInit.mechListMIC = null_blob; status = ntlmssp_update(client_ntlmssp_state, null_blob, &spnego.negTokenInit.mechToken); if ( !(NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) || NT_STATUS_IS_OK(status)) ) { DEBUG(1, ("Expected OK or MORE_PROCESSING_REQUIRED, got: %s\n", nt_errstr(status))); TALLOC_FREE(client_ntlmssp_state); return False; } spnego_write_data(ctx, &to_server, &spnego); data_blob_free(&spnego.negTokenInit.mechToken); to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server); data_blob_free(&to_server); x_fprintf(x_stdout, "KK %s\n", to_server_base64); TALLOC_FREE(to_server_base64); return True; } static void manage_client_ntlmssp_targ(struct spnego_data spnego) { NTSTATUS status; DATA_BLOB null_blob = data_blob_null; DATA_BLOB request; DATA_BLOB to_server; char *to_server_base64; TALLOC_CTX *ctx = talloc_tos(); DEBUG(10, ("Got spnego negTokenTarg with NTLMSSP\n")); if (client_ntlmssp_state == NULL) { DEBUG(1, ("Got NTLMSSP tArg without a client state\n")); x_fprintf(x_stdout, "BH Got NTLMSSP tArg without a client state\n"); return; } if (spnego.negTokenTarg.negResult == SPNEGO_REJECT) { x_fprintf(x_stdout, "NA\n"); TALLOC_FREE(client_ntlmssp_state); return; } if (spnego.negTokenTarg.negResult == SPNEGO_ACCEPT_COMPLETED) { x_fprintf(x_stdout, "AF\n"); TALLOC_FREE(client_ntlmssp_state); return; } status = ntlmssp_update(client_ntlmssp_state, spnego.negTokenTarg.responseToken, &request); if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) && !NT_STATUS_IS_OK(status)) { DEBUG(1, ("Expected MORE_PROCESSING_REQUIRED or OK from " "ntlmssp_client_update, got: %s\n", nt_errstr(status))); x_fprintf(x_stdout, "BH Expected MORE_PROCESSING_REQUIRED from " "ntlmssp_client_update\n"); data_blob_free(&request); TALLOC_FREE(client_ntlmssp_state); return; } spnego.type = SPNEGO_NEG_TOKEN_TARG; spnego.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE; spnego.negTokenTarg.supportedMech = (const char *)OID_NTLMSSP; spnego.negTokenTarg.responseToken = request; spnego.negTokenTarg.mechListMIC = null_blob; spnego_write_data(ctx, &to_server, &spnego); data_blob_free(&request); to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server); data_blob_free(&to_server); x_fprintf(x_stdout, "KK %s\n", to_server_base64); TALLOC_FREE(to_server_base64); return; } #ifdef HAVE_KRB5 static bool manage_client_krb5_init(struct spnego_data spnego) { char *principal; DATA_BLOB tkt, tkt_wrapped, to_server; DATA_BLOB session_key_krb5 = data_blob_null; struct spnego_data reply; char *reply_base64; int retval; const char *my_mechs[] = {OID_KERBEROS5_OLD, NULL}; ssize_t len; TALLOC_CTX *ctx = talloc_tos(); principal = spnego.negTokenInit.targetPrincipal; /* We may not be allowed to use the server-supplied SPNEGO principal, or it may not have been supplied to us */ if (!lp_client_use_spnego_principal() || strequal(principal, ADS_IGNORE_PRINCIPAL)) { principal = NULL; } if (principal == NULL && opt_target_service && opt_target_hostname && !is_ipaddress(opt_target_hostname)) { DEBUG(3,("manage_client_krb5_init: using target " "hostname not SPNEGO principal\n")); principal = kerberos_get_principal_from_service_hostname(talloc_tos(), opt_target_service, opt_target_hostname, lp_realm()); if (!principal) { return false; } DEBUG(3,("manage_client_krb5_init: guessed " "server principal=%s\n", principal ? principal : "<null>")); } if (principal == NULL) { DEBUG(3,("manage_client_krb5_init: could not guess server principal\n")); return false; } retval = cli_krb5_get_ticket(ctx, principal, 0, &tkt, &session_key_krb5, 0, NULL, NULL, NULL); if (retval) { char *user = NULL; /* Let's try to first get the TGT, for that we need a password. */ if (opt_password == NULL) { DEBUG(10, ("Requesting password\n")); x_fprintf(x_stdout, "PW\n"); return True; } user = talloc_asprintf(talloc_tos(), "%s@%s", opt_username, opt_domain); if (!user) { return false; } if ((retval = kerberos_kinit_password(user, opt_password, 0, NULL))) { DEBUG(10, ("Requesting TGT failed: %s\n", error_message(retval))); return False; } retval = cli_krb5_get_ticket(ctx, principal, 0, &tkt, &session_key_krb5, 0, NULL, NULL, NULL); if (retval) { DEBUG(10, ("Kinit suceeded, but getting a ticket failed: %s\n", error_message(retval))); return False; } } /* wrap that up in a nice GSS-API wrapping */ tkt_wrapped = spnego_gen_krb5_wrap(ctx, tkt, TOK_ID_KRB_AP_REQ); data_blob_free(&session_key_krb5); ZERO_STRUCT(reply); reply.type = SPNEGO_NEG_TOKEN_INIT; reply.negTokenInit.mechTypes = my_mechs; reply.negTokenInit.reqFlags = data_blob_null; reply.negTokenInit.reqFlagsPadding = 0; reply.negTokenInit.mechToken = tkt_wrapped; reply.negTokenInit.mechListMIC = data_blob_null; len = spnego_write_data(ctx, &to_server, &reply); data_blob_free(&tkt); if (len == -1) { DEBUG(1, ("Could not write SPNEGO data blob\n")); return False; } reply_base64 = base64_encode_data_blob(talloc_tos(), to_server); x_fprintf(x_stdout, "KK %s *\n", reply_base64); TALLOC_FREE(reply_base64); data_blob_free(&to_server); DEBUG(10, ("sent GSS-SPNEGO KERBEROS5 negTokenInit\n")); return True; } static void manage_client_krb5_targ(struct spnego_data spnego) { switch (spnego.negTokenTarg.negResult) { case SPNEGO_ACCEPT_INCOMPLETE: DEBUG(1, ("Got a Kerberos negTokenTarg with ACCEPT_INCOMPLETE\n")); x_fprintf(x_stdout, "BH Got a Kerberos negTokenTarg with " "ACCEPT_INCOMPLETE\n"); break; case SPNEGO_ACCEPT_COMPLETED: DEBUG(10, ("Accept completed\n")); x_fprintf(x_stdout, "AF\n"); break; case SPNEGO_REJECT: DEBUG(10, ("Rejected\n")); x_fprintf(x_stdout, "NA\n"); break; default: DEBUG(1, ("Got an invalid negTokenTarg\n")); x_fprintf(x_stdout, "AF\n"); } } #endif static void manage_gss_spnego_client_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2) { DATA_BLOB request; struct spnego_data spnego; ssize_t len; TALLOC_CTX *ctx = talloc_tos(); if (!opt_username || !*opt_username) { x_fprintf(x_stderr, "username must be specified!\n\n"); exit(1); } if (strlen(buf) <= 3) { DEBUG(1, ("SPNEGO query [%s] too short\n", buf)); x_fprintf(x_stdout, "BH SPNEGO query too short\n"); return; } request = base64_decode_data_blob(buf+3); if (strncmp(buf, "PW ", 3) == 0) { /* We asked for a password and obviously got it :-) */ opt_password = SMB_STRNDUP((const char *)request.data, request.length); if (opt_password == NULL) { DEBUG(1, ("Out of memory\n")); x_fprintf(x_stdout, "BH Out of memory\n"); data_blob_free(&request); return; } x_fprintf(x_stdout, "OK\n"); data_blob_free(&request); return; } if ( (strncmp(buf, "TT ", 3) != 0) && (strncmp(buf, "AF ", 3) != 0) && (strncmp(buf, "NA ", 3) != 0) ) { DEBUG(1, ("SPNEGO request [%s] invalid\n", buf)); x_fprintf(x_stdout, "BH SPNEGO request invalid\n"); data_blob_free(&request); return; } /* So we got a server challenge to generate a SPNEGO client-to-server request... */ len = spnego_read_data(ctx, request, &spnego); data_blob_free(&request); if (len == -1) { DEBUG(1, ("Could not read SPNEGO data for [%s]\n", buf)); x_fprintf(x_stdout, "BH Could not read SPNEGO data\n"); return; } if (spnego.type == SPNEGO_NEG_TOKEN_INIT) { /* The server offers a list of mechanisms */ const char *const *mechType = spnego.negTokenInit.mechTypes; while (*mechType != NULL) { #ifdef HAVE_KRB5 if ( (strcmp(*mechType, OID_KERBEROS5_OLD) == 0) || (strcmp(*mechType, OID_KERBEROS5) == 0) ) { if (manage_client_krb5_init(spnego)) goto out; } #endif if (strcmp(*mechType, OID_NTLMSSP) == 0) { if (manage_client_ntlmssp_init(spnego)) goto out; } mechType++; } DEBUG(1, ("Server offered no compatible mechanism\n")); x_fprintf(x_stdout, "BH Server offered no compatible mechanism\n"); return; } if (spnego.type == SPNEGO_NEG_TOKEN_TARG) { if (spnego.negTokenTarg.supportedMech == NULL) { /* On accept/reject Windows does not send the mechanism anymore. Handle that here and shut down the mechanisms. */ switch (spnego.negTokenTarg.negResult) { case SPNEGO_ACCEPT_COMPLETED: x_fprintf(x_stdout, "AF\n"); break; case SPNEGO_REJECT: x_fprintf(x_stdout, "NA\n"); break; default: DEBUG(1, ("Got a negTokenTarg with no mech and an " "unknown negResult: %d\n", spnego.negTokenTarg.negResult)); x_fprintf(x_stdout, "BH Got a negTokenTarg with" " no mech and an unknown " "negResult\n"); } TALLOC_FREE(client_ntlmssp_state); goto out; } if (strcmp(spnego.negTokenTarg.supportedMech, OID_NTLMSSP) == 0) { manage_client_ntlmssp_targ(spnego); goto out; } #if HAVE_KRB5 if (strcmp(spnego.negTokenTarg.supportedMech, OID_KERBEROS5_OLD) == 0) { manage_client_krb5_targ(spnego); goto out; } #endif } DEBUG(1, ("Got an SPNEGO token I could not handle [%s]!\n", buf)); x_fprintf(x_stdout, "BH Got an SPNEGO token I could not handle\n"); return; out: spnego_free_data(&spnego); return; } static void manage_ntlm_server_1_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2) { char *request, *parameter; static DATA_BLOB challenge; static DATA_BLOB lm_response; static DATA_BLOB nt_response; static char *full_username; static char *username; static char *domain; static char *plaintext_password; static bool ntlm_server_1_user_session_key; static bool ntlm_server_1_lm_session_key; if (strequal(buf, ".")) { if (!full_username && !username) { x_fprintf(x_stdout, "Error: No username supplied!\n"); } else if (plaintext_password) { /* handle this request as plaintext */ if (!full_username) { if (asprintf(&full_username, "%s%c%s", domain, winbind_separator(), username) == -1) { x_fprintf(x_stdout, "Error: Out of memory in asprintf!\n.\n"); return; } } if (check_plaintext_auth(full_username, plaintext_password, False)) { x_fprintf(x_stdout, "Authenticated: Yes\n"); } else { x_fprintf(x_stdout, "Authenticated: No\n"); } } else if (!lm_response.data && !nt_response.data) { x_fprintf(x_stdout, "Error: No password supplied!\n"); } else if (!challenge.data) { x_fprintf(x_stdout, "Error: No lanman-challenge supplied!\n"); } else { char *error_string = NULL; uchar lm_key[8]; uchar user_session_key[16]; uint32_t flags = 0; if (full_username && !username) { fstring fstr_user; fstring fstr_domain; if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) { /* username might be 'tainted', don't print into our new-line deleimianted stream */ x_fprintf(x_stdout, "Error: Could not parse into domain and username\n"); } SAFE_FREE(username); SAFE_FREE(domain); username = smb_xstrdup(fstr_user); domain = smb_xstrdup(fstr_domain); } if (!domain) { domain = smb_xstrdup(get_winbind_domain()); } if (ntlm_server_1_lm_session_key) flags |= WBFLAG_PAM_LMKEY; if (ntlm_server_1_user_session_key) flags |= WBFLAG_PAM_USER_SESSION_KEY; if (!NT_STATUS_IS_OK( contact_winbind_auth_crap(username, domain, lp_netbios_name(), &challenge, &lm_response, &nt_response, flags, 0, lm_key, user_session_key, &error_string, NULL))) { x_fprintf(x_stdout, "Authenticated: No\n"); x_fprintf(x_stdout, "Authentication-Error: %s\n.\n", error_string); } else { static char zeros[16]; char *hex_lm_key; char *hex_user_session_key; x_fprintf(x_stdout, "Authenticated: Yes\n"); if (ntlm_server_1_lm_session_key && (memcmp(zeros, lm_key, sizeof(lm_key)) != 0)) { hex_lm_key = hex_encode_talloc(NULL, (const unsigned char *)lm_key, sizeof(lm_key)); x_fprintf(x_stdout, "LANMAN-Session-Key: %s\n", hex_lm_key); TALLOC_FREE(hex_lm_key); } if (ntlm_server_1_user_session_key && (memcmp(zeros, user_session_key, sizeof(user_session_key)) != 0)) { hex_user_session_key = hex_encode_talloc(NULL, (const unsigned char *)user_session_key, sizeof(user_session_key)); x_fprintf(x_stdout, "User-Session-Key: %s\n", hex_user_session_key); TALLOC_FREE(hex_user_session_key); } } SAFE_FREE(error_string); } /* clear out the state */ challenge = data_blob_null; nt_response = data_blob_null; lm_response = data_blob_null; SAFE_FREE(full_username); SAFE_FREE(username); SAFE_FREE(domain); SAFE_FREE(plaintext_password); ntlm_server_1_user_session_key = False; ntlm_server_1_lm_session_key = False; x_fprintf(x_stdout, ".\n"); return; } request = buf; /* Indicates a base64 encoded structure */ parameter = strstr_m(request, ":: "); if (!parameter) { parameter = strstr_m(request, ": "); if (!parameter) { DEBUG(0, ("Parameter not found!\n")); x_fprintf(x_stdout, "Error: Parameter not found!\n.\n"); return; } parameter[0] ='\0'; parameter++; parameter[0] ='\0'; parameter++; } else { parameter[0] ='\0'; parameter++; parameter[0] ='\0'; parameter++; parameter[0] ='\0'; parameter++; base64_decode_inplace(parameter); } if (strequal(request, "LANMAN-Challenge")) { challenge = strhex_to_data_blob(NULL, parameter); if (challenge.length != 8) { x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", parameter, (int)challenge.length); challenge = data_blob_null; } } else if (strequal(request, "NT-Response")) { nt_response = strhex_to_data_blob(NULL, parameter); if (nt_response.length < 24) { x_fprintf(x_stdout, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", parameter, (int)nt_response.length); nt_response = data_blob_null; } } else if (strequal(request, "LANMAN-Response")) { lm_response = strhex_to_data_blob(NULL, parameter); if (lm_response.length != 24) { x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", parameter, (int)lm_response.length); lm_response = data_blob_null; } } else if (strequal(request, "Password")) { plaintext_password = smb_xstrdup(parameter); } else if (strequal(request, "NT-Domain")) { domain = smb_xstrdup(parameter); } else if (strequal(request, "Username")) { username = smb_xstrdup(parameter); } else if (strequal(request, "Full-Username")) { full_username = smb_xstrdup(parameter); } else if (strequal(request, "Request-User-Session-Key")) { ntlm_server_1_user_session_key = strequal(parameter, "Yes"); } else if (strequal(request, "Request-LanMan-Session-Key")) { ntlm_server_1_lm_session_key = strequal(parameter, "Yes"); } else { x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request); } } static void manage_ntlm_change_password_1_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, char *buf, int length, void **private2) { char *request, *parameter; static DATA_BLOB new_nt_pswd; static DATA_BLOB old_nt_hash_enc; static DATA_BLOB new_lm_pswd; static DATA_BLOB old_lm_hash_enc; static char *full_username = NULL; static char *username = NULL; static char *domain = NULL; static char *newpswd = NULL; static char *oldpswd = NULL; if (strequal(buf, ".")) { if(newpswd && oldpswd) { uchar old_nt_hash[16]; uchar old_lm_hash[16]; uchar new_nt_hash[16]; uchar new_lm_hash[16]; new_nt_pswd = data_blob(NULL, 516); old_nt_hash_enc = data_blob(NULL, 16); /* Calculate the MD4 hash (NT compatible) of the * password */ E_md4hash(oldpswd, old_nt_hash); E_md4hash(newpswd, new_nt_hash); /* E_deshash returns false for 'long' passwords (> 14 DOS chars). Therefore, don't send a buffer encrypted with the truncated hash (it could allow an even easier attack on the password) Likewise, obey the admin's restriction */ if (lp_client_lanman_auth() && E_deshash(newpswd, new_lm_hash) && E_deshash(oldpswd, old_lm_hash)) { new_lm_pswd = data_blob(NULL, 516); old_lm_hash_enc = data_blob(NULL, 16); encode_pw_buffer(new_lm_pswd.data, newpswd, STR_UNICODE); arcfour_crypt(new_lm_pswd.data, old_nt_hash, 516); E_old_pw_hash(new_nt_hash, old_lm_hash, old_lm_hash_enc.data); } else { new_lm_pswd.data = NULL; new_lm_pswd.length = 0; old_lm_hash_enc.data = NULL; old_lm_hash_enc.length = 0; } encode_pw_buffer(new_nt_pswd.data, newpswd, STR_UNICODE); arcfour_crypt(new_nt_pswd.data, old_nt_hash, 516); E_old_pw_hash(new_nt_hash, old_nt_hash, old_nt_hash_enc.data); } if (!full_username && !username) { x_fprintf(x_stdout, "Error: No username supplied!\n"); } else if ((!new_nt_pswd.data || !old_nt_hash_enc.data) && (!new_lm_pswd.data || old_lm_hash_enc.data) ) { x_fprintf(x_stdout, "Error: No NT or LM password " "blobs supplied!\n"); } else { char *error_string = NULL; if (full_username && !username) { fstring fstr_user; fstring fstr_domain; if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) { /* username might be 'tainted', don't * print into our new-line * deleimianted stream */ x_fprintf(x_stdout, "Error: Could not " "parse into domain and " "username\n"); SAFE_FREE(username); username = smb_xstrdup(full_username); } else { SAFE_FREE(username); SAFE_FREE(domain); username = smb_xstrdup(fstr_user); domain = smb_xstrdup(fstr_domain); } } if(!NT_STATUS_IS_OK(contact_winbind_change_pswd_auth_crap( username, domain, new_nt_pswd, old_nt_hash_enc, new_lm_pswd, old_lm_hash_enc, &error_string))) { x_fprintf(x_stdout, "Password-Change: No\n"); x_fprintf(x_stdout, "Password-Change-Error: " "%s\n.\n", error_string); } else { x_fprintf(x_stdout, "Password-Change: Yes\n"); } SAFE_FREE(error_string); } /* clear out the state */ new_nt_pswd = data_blob_null; old_nt_hash_enc = data_blob_null; new_lm_pswd = data_blob_null; old_nt_hash_enc = data_blob_null; SAFE_FREE(full_username); SAFE_FREE(username); SAFE_FREE(domain); SAFE_FREE(newpswd); SAFE_FREE(oldpswd); x_fprintf(x_stdout, ".\n"); return; } request = buf; /* Indicates a base64 encoded structure */ parameter = strstr_m(request, ":: "); if (!parameter) { parameter = strstr_m(request, ": "); if (!parameter) { DEBUG(0, ("Parameter not found!\n")); x_fprintf(x_stdout, "Error: Parameter not found!\n.\n"); return; } parameter[0] ='\0'; parameter++; parameter[0] ='\0'; parameter++; } else { parameter[0] ='\0'; parameter++; parameter[0] ='\0'; parameter++; parameter[0] ='\0'; parameter++; base64_decode_inplace(parameter); } if (strequal(request, "new-nt-password-blob")) { new_nt_pswd = strhex_to_data_blob(NULL, parameter); if (new_nt_pswd.length != 516) { x_fprintf(x_stdout, "Error: hex decode of %s failed! " "(got %d bytes, expected 516)\n.\n", parameter, (int)new_nt_pswd.length); new_nt_pswd = data_blob_null; } } else if (strequal(request, "old-nt-hash-blob")) { old_nt_hash_enc = strhex_to_data_blob(NULL, parameter); if (old_nt_hash_enc.length != 16) { x_fprintf(x_stdout, "Error: hex decode of %s failed! " "(got %d bytes, expected 16)\n.\n", parameter, (int)old_nt_hash_enc.length); old_nt_hash_enc = data_blob_null; } } else if (strequal(request, "new-lm-password-blob")) { new_lm_pswd = strhex_to_data_blob(NULL, parameter); if (new_lm_pswd.length != 516) { x_fprintf(x_stdout, "Error: hex decode of %s failed! " "(got %d bytes, expected 516)\n.\n", parameter, (int)new_lm_pswd.length); new_lm_pswd = data_blob_null; } } else if (strequal(request, "old-lm-hash-blob")) { old_lm_hash_enc = strhex_to_data_blob(NULL, parameter); if (old_lm_hash_enc.length != 16) { x_fprintf(x_stdout, "Error: hex decode of %s failed! " "(got %d bytes, expected 16)\n.\n", parameter, (int)old_lm_hash_enc.length); old_lm_hash_enc = data_blob_null; } } else if (strequal(request, "nt-domain")) { domain = smb_xstrdup(parameter); } else if(strequal(request, "username")) { username = smb_xstrdup(parameter); } else if(strequal(request, "full-username")) { username = smb_xstrdup(parameter); } else if(strequal(request, "new-password")) { newpswd = smb_xstrdup(parameter); } else if (strequal(request, "old-password")) { oldpswd = smb_xstrdup(parameter); } else { x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request); } } static void manage_squid_request(enum stdio_helper_mode stdio_helper_mode, struct loadparm_context *lp_ctx, struct ntlm_auth_state *state, stdio_helper_function fn, void **private2) { char *buf; char tmp[INITIAL_BUFFER_SIZE+1]; int length, buf_size = 0; char *c; buf = talloc_strdup(state->mem_ctx, ""); if (!buf) { DEBUG(0, ("Failed to allocate input buffer.\n")); x_fprintf(x_stderr, "ERR\n"); exit(1); } do { /* this is not a typo - x_fgets doesn't work too well under * squid */ if (fgets(tmp, sizeof(tmp)-1, stdin) == NULL) { if (ferror(stdin)) { DEBUG(1, ("fgets() failed! dying..... errno=%d " "(%s)\n", ferror(stdin), strerror(ferror(stdin)))); exit(1); } exit(0); } buf = talloc_strdup_append_buffer(buf, tmp); buf_size += INITIAL_BUFFER_SIZE; if (buf_size > MAX_BUFFER_SIZE) { DEBUG(2, ("Oversized message\n")); x_fprintf(x_stderr, "ERR\n"); talloc_free(buf); return; } c = strchr(buf, '\n'); } while (c == NULL); *c = '\0'; length = c-buf; DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length)); if (buf[0] == '\0') { DEBUG(2, ("Invalid Request\n")); x_fprintf(x_stderr, "ERR\n"); talloc_free(buf); return; } fn(stdio_helper_mode, lp_ctx, state, buf, length, private2); talloc_free(buf); } static void squid_stream(enum stdio_helper_mode stdio_mode, struct loadparm_context *lp_ctx, stdio_helper_function fn) { TALLOC_CTX *mem_ctx; struct ntlm_auth_state *state; /* initialize FDescs */ x_setbuf(x_stdout, NULL); x_setbuf(x_stderr, NULL); mem_ctx = talloc_init("ntlm_auth"); if (!mem_ctx) { DEBUG(0, ("squid_stream: Failed to create talloc context\n")); x_fprintf(x_stderr, "ERR\n"); exit(1); } state = talloc_zero(mem_ctx, struct ntlm_auth_state); if (!state) { DEBUG(0, ("squid_stream: Failed to talloc ntlm_auth_state\n")); x_fprintf(x_stderr, "ERR\n"); exit(1); } state->mem_ctx = mem_ctx; state->helper_mode = stdio_mode; while(1) { TALLOC_CTX *frame = talloc_stackframe(); manage_squid_request(stdio_mode, lp_ctx, state, fn, NULL); TALLOC_FREE(frame); } } /* Authenticate a user with a challenge/response */ static bool check_auth_crap(void) { NTSTATUS nt_status; uint32_t flags = 0; char lm_key[8]; char user_session_key[16]; char *hex_lm_key; char *hex_user_session_key; char *error_string; static uint8_t zeros[16]; x_setbuf(x_stdout, NULL); if (request_lm_key) flags |= WBFLAG_PAM_LMKEY; if (request_user_session_key) flags |= WBFLAG_PAM_USER_SESSION_KEY; flags |= WBFLAG_PAM_NT_STATUS_SQUASH; nt_status = contact_winbind_auth_crap(opt_username, opt_domain, opt_workstation, &opt_challenge, &opt_lm_response, &opt_nt_response, flags, 0, (unsigned char *)lm_key, (unsigned char *)user_session_key, &error_string, NULL); if (!NT_STATUS_IS_OK(nt_status)) { x_fprintf(x_stdout, "%s (0x%x)\n", error_string, NT_STATUS_V(nt_status)); SAFE_FREE(error_string); return False; } if (request_lm_key && (memcmp(zeros, lm_key, sizeof(lm_key)) != 0)) { hex_lm_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)lm_key, sizeof(lm_key)); x_fprintf(x_stdout, "LM_KEY: %s\n", hex_lm_key); TALLOC_FREE(hex_lm_key); } if (request_user_session_key && (memcmp(zeros, user_session_key, sizeof(user_session_key)) != 0)) { hex_user_session_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)user_session_key, sizeof(user_session_key)); x_fprintf(x_stdout, "NT_KEY: %s\n", hex_user_session_key); TALLOC_FREE(hex_user_session_key); } return True; } /* Main program */ enum { OPT_USERNAME = 1000, OPT_DOMAIN, OPT_WORKSTATION, OPT_CHALLENGE, OPT_RESPONSE, OPT_LM, OPT_NT, OPT_PASSWORD, OPT_LM_KEY, OPT_USER_SESSION_KEY, OPT_DIAGNOSTICS, OPT_REQUIRE_MEMBERSHIP, OPT_USE_CACHED_CREDS, OPT_PAM_WINBIND_CONF, OPT_TARGET_SERVICE, OPT_TARGET_HOSTNAME }; int main(int argc, const char **argv) { TALLOC_CTX *frame = talloc_stackframe(); int opt; static const char *helper_protocol; static int diagnostics; static const char *hex_challenge; static const char *hex_lm_response; static const char *hex_nt_response; struct loadparm_context *lp_ctx; poptContext pc; /* NOTE: DO NOT change this interface without considering the implications! This is an external interface, which other programs will use to interact with this helper. */ /* We do not use single-letter command abbreviations, because they harm future interface stability. */ struct poptOption long_options[] = { POPT_AUTOHELP { "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"}, { "username", 0, POPT_ARG_STRING, &opt_username, OPT_USERNAME, "username"}, { "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"}, { "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"}, { "challenge", 0, POPT_ARG_STRING, &hex_challenge, OPT_CHALLENGE, "challenge (HEX encoded)"}, { "lm-response", 0, POPT_ARG_STRING, &hex_lm_response, OPT_LM, "LM Response to the challenge (HEX encoded)"}, { "nt-response", 0, POPT_ARG_STRING, &hex_nt_response, OPT_NT, "NT or NTLMv2 Response to the challenge (HEX encoded)"}, { "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"}, { "request-lm-key", 0, POPT_ARG_NONE, &request_lm_key, OPT_LM_KEY, "Retrieve LM session key"}, { "request-nt-key", 0, POPT_ARG_NONE, &request_user_session_key, OPT_USER_SESSION_KEY, "Retrieve User (NT) session key"}, { "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "Use cached credentials if no password is given"}, { "diagnostics", 0, POPT_ARG_NONE, &diagnostics, OPT_DIAGNOSTICS, "Perform diagnostics on the authentication chain"}, { "require-membership-of", 0, POPT_ARG_STRING, &require_membership_of, OPT_REQUIRE_MEMBERSHIP, "Require that a user be a member of this group (either name or SID) for authentication to succeed" }, { "pam-winbind-conf", 0, POPT_ARG_STRING, &opt_pam_winbind_conf, OPT_PAM_WINBIND_CONF, "Require that request must set WBFLAG_PAM_CONTACT_TRUSTDOM when krb5 auth is required" }, { "target-service", 0, POPT_ARG_STRING, &opt_target_service, OPT_TARGET_SERVICE, "Target service (eg http)" }, { "target-hostname", 0, POPT_ARG_STRING, &opt_target_hostname, OPT_TARGET_HOSTNAME, "Target hostname" }, POPT_COMMON_CONFIGFILE POPT_COMMON_VERSION POPT_COMMON_OPTION POPT_TABLEEND }; /* Samba client initialisation */ smb_init_locale(); setup_logging("ntlm_auth", DEBUG_STDERR); /* Parse options */ pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0); /* Parse command line options */ if (argc == 1) { poptPrintHelp(pc, stderr, 0); return 1; } while((opt = poptGetNextOpt(pc)) != -1) { /* Get generic config options like --configfile */ } poptFreeContext(pc); if (!lp_load_global(get_dyn_CONFIGFILE())) { d_fprintf(stderr, "ntlm_auth: error opening config file %s. Error was %s\n", get_dyn_CONFIGFILE(), strerror(errno)); exit(1); } pc = poptGetContext(NULL, argc, (const char **)argv, long_options, POPT_CONTEXT_KEEP_FIRST); while((opt = poptGetNextOpt(pc)) != -1) { switch (opt) { case OPT_CHALLENGE: opt_challenge = strhex_to_data_blob(NULL, hex_challenge); if (opt_challenge.length != 8) { x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", hex_challenge, (int)opt_challenge.length); exit(1); } break; case OPT_LM: opt_lm_response = strhex_to_data_blob(NULL, hex_lm_response); if (opt_lm_response.length != 24) { x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", hex_lm_response, (int)opt_lm_response.length); exit(1); } break; case OPT_NT: opt_nt_response = strhex_to_data_blob(NULL, hex_nt_response); if (opt_nt_response.length < 24) { x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", hex_nt_response, (int)opt_nt_response.length); exit(1); } break; case OPT_REQUIRE_MEMBERSHIP: if (strncasecmp_m("S-", require_membership_of, 2) == 0) { require_membership_of_sid = require_membership_of; } break; } } if (opt_username) { char *domain = SMB_STRDUP(opt_username); char *p = strchr_m(domain, *lp_winbind_separator()); if (p) { opt_username = p+1; *p = '\0'; if (opt_domain && !strequal(opt_domain, domain)) { x_fprintf(x_stderr, "Domain specified in username (%s) " "doesn't match specified domain (%s)!\n\n", domain, opt_domain); poptPrintHelp(pc, stderr, 0); exit(1); } opt_domain = domain; } else { SAFE_FREE(domain); } } /* Note: if opt_domain is "" then send no domain */ if (opt_domain == NULL) { opt_domain = get_winbind_domain(); } if (opt_workstation == NULL) { opt_workstation = ""; } lp_ctx = loadparm_init_s3(NULL, loadparm_s3_helpers()); if (lp_ctx == NULL) { x_fprintf(x_stderr, "loadparm_init_s3() failed!\n"); exit(1); } if (helper_protocol) { int i; for (i=0; i<NUM_HELPER_MODES; i++) { if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) { squid_stream(stdio_helper_protocols[i].mode, lp_ctx, stdio_helper_protocols[i].fn); exit(0); } } x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol); for (i=0; i<NUM_HELPER_MODES; i++) { x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name); } exit(1); } if (!opt_username || !*opt_username) { x_fprintf(x_stderr, "username must be specified!\n\n"); poptPrintHelp(pc, stderr, 0); exit(1); } if (opt_challenge.length) { if (!check_auth_crap()) { exit(1); } exit(0); } if (!opt_password) { char pwd[256] = {0}; int rc; rc = samba_getpass("Password: ", pwd, sizeof(pwd), false, false); if (rc == 0) { opt_password = SMB_STRDUP(pwd); } } if (diagnostics) { if (!diagnose_ntlm_auth()) { return 1; } } else { fstring user; fstr_sprintf(user, "%s%c%s", opt_domain, winbind_separator(), opt_username); if (!check_plaintext_auth(user, opt_password, True)) { return 1; } } /* Exit code */ poptFreeContext(pc); TALLOC_FREE(frame); return 0; }
----------------------------------- -- Shoulder Tackle -- Hand-to-Hand weapon skill -- Skill Level: 40 -- Stuns target. Chance of stunning varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Aqua Gorget & Thunder Gorget. -- Aligned with the Aqua Belt & Thunder Belt. -- Element: None -- Modifiers: VIT:100% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.3; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.vit_wsc = 1.0; end if damage > 0 then local tp = player:getTP(); local duration = (tp/50); if (target:hasStatusEffect(EFFECT_STUN) == false) then target:addStatusEffect(EFFECT_STUN, 1, 0, duration); end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
// // GoogleMobileAds.h // Google Mobile Ads SDK // // Copyright 2014 Google Inc. All rights reserved. #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0 #error The Google Mobile Ads SDK requires a deployment target of iOS 6.0 or later. #endif //! Project version string for GoogleMobileAds. FOUNDATION_EXPORT const unsigned char GoogleMobileAdsVersionString[]; #import <GoogleMobileAds/GADAdNetworkExtras.h> #import <GoogleMobileAds/GADAdSize.h> #import <GoogleMobileAds/GADBannerView.h> #import <GoogleMobileAds/GADBannerViewDelegate.h> #import <GoogleMobileAds/GADExtras.h> #import <GoogleMobileAds/GADInAppPurchase.h> #import <GoogleMobileAds/GADInAppPurchaseDelegate.h> #import <GoogleMobileAds/GADInterstitial.h> #import <GoogleMobileAds/GADInterstitialDelegate.h> #import <GoogleMobileAds/GADRequest.h> #import <GoogleMobileAds/GADRequestError.h> #import <GoogleMobileAds/DFPBannerView.h> #import <GoogleMobileAds/DFPCustomRenderedAd.h> #import <GoogleMobileAds/DFPCustomRenderedBannerViewDelegate.h> #import <GoogleMobileAds/DFPCustomRenderedInterstitialDelegate.h> #import <GoogleMobileAds/DFPInterstitial.h> #import <GoogleMobileAds/DFPRequest.h> #import <GoogleMobileAds/GADAdSizeDelegate.h> #import <GoogleMobileAds/GADAppEventDelegate.h> #import <GoogleMobileAds/Loading/GADAdLoader.h> #import <GoogleMobileAds/Loading/GADAdLoaderAdTypes.h> #import <GoogleMobileAds/Loading/GADAdLoaderDelegate.h> #import <GoogleMobileAds/Loading/Formats/GADNativeAd.h> #import <GoogleMobileAds/Loading/Formats/GADNativeAdDelegate.h> #import <GoogleMobileAds/Loading/Formats/GADNativeAdImage.h> #import <GoogleMobileAds/Loading/Formats/GADNativeAppInstallAd.h> #import <GoogleMobileAds/Loading/Formats/GADNativeContentAd.h> #import <GoogleMobileAds/Loading/Formats/GADNativeCustomTemplateAd.h> #import <GoogleMobileAds/Loading/Options/GADNativeAdImageAdLoaderOptions.h> #import <GoogleMobileAds/Mediation/GADCustomEventBanner.h> #import <GoogleMobileAds/Mediation/GADCustomEventBannerDelegate.h> #import <GoogleMobileAds/Mediation/GADCustomEventExtras.h> #import <GoogleMobileAds/Mediation/GADCustomEventInterstitial.h> #import <GoogleMobileAds/Mediation/GADCustomEventInterstitialDelegate.h> #import <GoogleMobileAds/Mediation/GADCustomEventRequest.h> #import <GoogleMobileAds/Search/GADSearchBannerView.h> #import <GoogleMobileAds/Search/GADSearchRequest.h>
/* * ServerScheduler.hpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SERVER_SCHEDULER_HPP #define SERVER_SCHEDULER_HPP #include <string> #include <core/ScheduledCommand.hpp> namespace rstudio { namespace server { namespace scheduler { // add a scheduled command to the server // // note that this function does not synchronize access to the list of // scheduled commands so it should ONLY be called during server init void addCommand(boost::shared_ptr<core::ScheduledCommand> pCmd); } // namespace scheduler } // namespace server } // namespace rstudio #endif // SERVER_SCHEDULER_HPP
# pylint: disable=missing-docstring # pylint: disable=redefined-outer-name # pylint: disable=unused-argument from lettuce import step, world from common import * ############### ACTIONS #################### @step('There are no courses$') def no_courses(step): world.clear_courses() create_studio_user() @step('I click the New Course button$') def i_click_new_course(step): world.css_click('.new-course-button') @step('I fill in the new course information$') def i_fill_in_a_new_course_information(step): fill_in_course_info() @step('I create a course with "([^"]*)", "([^"]*)", "([^"]*)", and "([^"]*)"') def i_create_course(step, name, org, number, run): fill_in_course_info(name=name, org=org, num=number, run=run) @step('I create a new course$') def i_create_a_course(step): create_a_course() @step('I click the course link in Studio Home$') def i_click_the_course_link_in_studio_home(step): # pylint: disable=invalid-name course_css = 'a.course-link' world.css_click(course_css) @step('I see an error about the length of the org/course/run tuple') def i_see_error_about_length(step): assert world.css_has_text( '#course_creation_error', 'The combined length of the organization, course number, ' 'and course run fields cannot be more than 65 characters.' ) ############ ASSERTIONS ################### @step('the Courseware page has loaded in Studio$') def courseware_page_has_loaded_in_studio(step): course_title_css = 'span.course-title' assert world.is_css_present(course_title_css) @step('I see the course listed in Studio Home$') def i_see_the_course_in_studio_home(step): course_css = 'h3.class-title' assert world.css_has_text(course_css, world.scenario_dict['COURSE'].display_name) @step('I am on the "([^"]*)" tab$') def i_am_on_tab(step, tab_name): header_css = 'div.inner-wrapper h1' assert world.css_has_text(header_css, tab_name) @step('I see a link for adding a new section$') def i_see_new_section_link(step): link_css = '.outline .button-new' assert world.css_has_text(link_css, 'New Section')
/** * * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd. * Copyright (C) 2011 - 2018 SalesAgility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". */ var aclviewer = function () { var lastDisplay = ''; return { view: function (role_id, role_module) { YAHOO.util.Connect.asyncRequest('POST', 'index.php', { 'success': aclviewer.display, 'failure': aclviewer.failed }, 'module=ACLRoles&action=EditRole&record=' + role_id + '&category_name=' + role_module); ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_REQUEST_PROCESSED')); }, save: function (form_name) { var formObject = document.getElementById(form_name); YAHOO.util.Connect.setForm(formObject); YAHOO.util.Connect.asyncRequest('POST', 'index.php', { 'success': aclviewer.postSave, 'failure': aclviewer.failed }); ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING')); }, postSave: function (o) { SUGAR.util.globalEval(o.responseText); aclviewer.view(result['role_id'], result['module']); }, display: function (o) { aclviewer.lastDisplay = ''; ajaxStatus.flashStatus('Done'); document.getElementById('category_data').innerHTML = o.responseText; }, failed: function () { ajax.flashStatus('Could Not Connect'); }, toggleDisplay: function (id) { if (aclviewer.lastDisplay != '' && typeof(aclviewer.lastDisplay) != 'undefined') { aclviewer.hideDisplay(aclviewer.lastDisplay); } if (aclviewer.lastDisplay != id) { aclviewer.showDisplay(id); aclviewer.lastDisplay = id; } else { aclviewer.lastDisplay = ''; } }, hideDisplay: function (id) { document.getElementById(id).style.display = 'none'; document.getElementById(id + 'link').style.display = ''; }, showDisplay: function (id) { document.getElementById(id).style.display = ''; document.getElementById(id + 'link').style.display = 'none'; } }; }();
// Accord.NET Sample Applications // http://accord.googlecode.com // // Copyright © César Souza, 2009-2012 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace DeepLearning.ViewModel { using System.ComponentModel; using System.Windows.Media.Imaging; using Accord.Math; using Accord.Neuro.Networks; using DeepLearning.Databases; /// <summary> /// View-Model for the Use tab. /// </summary> /// public class UseViewModel : INotifyPropertyChanged { public MainViewModel Main { get; private set; } public double[] UserInput { get; set; } public BitmapImage NetworkOutput { get; set; } public bool IsActive { get; set; } public int Classification { get; set; } public UseViewModel(MainViewModel main) { Main = main; PropertyChanged += new PropertyChangedEventHandler(UseViewModel_PropertyChanged); } private void UseViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "UserInput" && IsActive) Compute(); } public bool CanCompute { get { return UserInput != null && Main.CanGenerate; } } public void Compute() { if (!CanCompute) return; double[] input = UserInput; DeepBeliefNetwork network = Main.Network; IDatabase database = Main.Database; database.Normalize(input); { double[] output = network.GenerateOutput(input); double[] reconstruction = network.Reconstruct(output); NetworkOutput = (database.ToBitmap(reconstruction).ToBitmapImage()); } if (Main.CanClassify) { double[] output = network.Compute(input); int imax; output.Max(out imax); Classification = imax; } } // The PropertyChanged event doesn't needs to be explicitly raised // from this application. The event raising is handled automatically // by the NotifyPropertyWeaver VS extension using IL injection. // #pragma warning disable 0067 /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #pragma warning restore 0067 } }
// check-pass // edition:2018 #![deny(unreachable_code)] async fn foo() { endless().await; } async fn endless() -> ! { loop {} } fn main() { }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!DOCTYPE HTML PUBLIC "-//W3C/DTD HTML 3.2 Final//NL"> <html> <head> <title> org.apache.wicket.util.watch package </title> </head> <body> <p> This package provides modification watchers. </p> </body> </html>
// run-pass // Issue #7988 // Transmuting non-immediate type to immediate type // pretty-expanded FIXME #23616 pub fn main() { unsafe { ::std::mem::transmute::<[isize; 1],isize>([1]) }; }
/* * Copyright 2013 LinkedIn, 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. */ package voldemort.client.rebalance.task; import java.util.concurrent.Semaphore; import org.apache.log4j.Logger; import voldemort.VoldemortException; import voldemort.client.protocol.admin.AdminClient; import voldemort.client.rebalance.RebalanceBatchPlanProgressBar; import voldemort.client.rebalance.RebalanceScheduler; import voldemort.client.rebalance.RebalanceTaskInfo; import voldemort.server.rebalance.AlreadyRebalancingException; import voldemort.store.UnreachableStoreException; import com.google.common.collect.Lists; /** * Immutable class that executes a {@link RebalanceTaskInfo} instance on * the rebalance client side. * * This is run from the stealer nodes perspective */ public class StealerBasedRebalanceTask extends RebalanceTask { private static final Logger logger = Logger.getLogger(StealerBasedRebalanceTask.class); private final int stealerNodeId; private final int donorNodeId; private final RebalanceScheduler scheduler; public StealerBasedRebalanceTask(final int batchId, final int taskId, final RebalanceTaskInfo stealInfo, final Semaphore donorPermit, final AdminClient adminClient, final RebalanceBatchPlanProgressBar progressBar, final RebalanceScheduler scheduler) { super(batchId, taskId, Lists.newArrayList(stealInfo), donorPermit, adminClient, progressBar, logger); this.stealerNodeId = stealInfo.getStealerId(); this.donorNodeId = stealInfo.getDonorId(); this.scheduler = scheduler; taskLog(toString()); } private int startNodeRebalancing() { try { taskLog("Trying to start async rebalance task on stealer node " + stealerNodeId); int asyncOperationId = adminClient.rebalanceOps.rebalanceNode(stealInfos.get(0)); taskLog("Started async rebalance task on stealer node " + stealerNodeId); return asyncOperationId; } catch(AlreadyRebalancingException e) { String errorMessage = "Node " + stealerNodeId + " is currently rebalancing. Should not have tried to start new task on stealer node!"; taskLog(errorMessage); throw new VoldemortException(errorMessage + " Failed to start rebalancing with plan: " + getStealInfos(), e); } } @Override public void run() { int rebalanceAsyncId = INVALID_REBALANCE_ID; String threadName = Thread.currentThread().getName(); try { Thread.currentThread().setName(threadName + "-Task-" + taskId + "-asyncid-" + rebalanceAsyncId); acquirePermit(stealInfos.get(0).getDonorId()); // Start rebalance task and then wait. rebalanceAsyncId = startNodeRebalancing(); taskStart(taskId, rebalanceAsyncId); adminClient.rpcOps.waitForCompletion(stealerNodeId, rebalanceAsyncId); taskDone(taskId, rebalanceAsyncId); } catch(UnreachableStoreException e) { exception = e; logger.error("Stealer node " + stealerNodeId + " is unreachable, please make sure it is up and running : " + e.getMessage(), e); } catch(Exception e) { exception = e; logger.error("Rebalance failed : " + e.getMessage(), e); } finally { Thread.currentThread().setName(threadName); donorPermit.release(); isComplete.set(true); scheduler.doneTask(stealerNodeId, donorNodeId); } } @Override public String toString() { return "Stealer based rebalance task on stealer node " + stealerNodeId + " from donor node " + donorNodeId + " : " + getStealInfos(); } }
({"text":"รายละเอียด","insertImageTitle":"คุณสมบัติอิมเมจ","set":"ตั้งค่า","newWindow":"หน้าต่างใหม่","topWindow":"หน้าต่างบนสุด","target":"เป้าหมาย:","createLinkTitle":"คุณสมบัติลิงก์","parentWindow":"หน้าต่างหลัก","currentWindow":"หน้าต่างปัจจุบัน","url":"URL:"})
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests and Benchmarks for Densenet model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gc import time import tensorflow as tf import tensorflow.contrib.eager as tfe from tensorflow.contrib.eager.python.examples.densenet import densenet from tensorflow.python.client import device_lib class DensenetTest(tf.test.TestCase): def test_bottleneck_true(self): depth = 7 growth_rate = 2 num_blocks = 3 output_classes = 10 num_layers_in_each_block = -1 batch_size = 1 data_format = ('channels_first') if tf.test.is_gpu_available() else ( 'channels_last') model = densenet.DenseNet(depth, growth_rate, num_blocks, output_classes, num_layers_in_each_block, data_format, bottleneck=True, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=False, include_top=True) if data_format == 'channels_last': rand_input = tf.random_uniform((batch_size, 32, 32, 3)) else: rand_input = tf.random_uniform((batch_size, 3, 32, 32)) output_shape = model(rand_input).shape self.assertEqual(output_shape, (batch_size, output_classes)) def test_bottleneck_false(self): depth = 7 growth_rate = 2 num_blocks = 3 output_classes = 10 num_layers_in_each_block = -1 batch_size = 1 data_format = ('channels_first') if tf.test.is_gpu_available() else ( 'channels_last') model = densenet.DenseNet(depth, growth_rate, num_blocks, output_classes, num_layers_in_each_block, data_format, bottleneck=False, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=False, include_top=True) if data_format == 'channels_last': rand_input = tf.random_uniform((batch_size, 32, 32, 3)) else: rand_input = tf.random_uniform((batch_size, 3, 32, 32)) output_shape = model(rand_input).shape self.assertEqual(output_shape, (batch_size, output_classes)) def test_pool_initial_true(self): depth = 7 growth_rate = 2 num_blocks = 4 output_classes = 10 num_layers_in_each_block = [1, 2, 2, 1] batch_size = 1 data_format = ('channels_first') if tf.test.is_gpu_available() else ( 'channels_last') model = densenet.DenseNet(depth, growth_rate, num_blocks, output_classes, num_layers_in_each_block, data_format, bottleneck=True, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=True, include_top=True) if data_format == 'channels_last': rand_input = tf.random_uniform((batch_size, 32, 32, 3)) else: rand_input = tf.random_uniform((batch_size, 3, 32, 32)) output_shape = model(rand_input).shape self.assertEqual(output_shape, (batch_size, output_classes)) def test_regularization(self): if tf.test.is_gpu_available(): rand_input = tf.random_uniform((10, 3, 32, 32)) data_format = 'channels_first' else: rand_input = tf.random_uniform((10, 32, 32, 3)) data_format = 'channels_last' weight_decay = 1e-4 conv = tf.keras.layers.Conv2D( 3, (3, 3), padding='same', use_bias=False, data_format=data_format, kernel_regularizer=tf.keras.regularizers.l2(weight_decay)) optimizer = tf.train.GradientDescentOptimizer(0.1) conv(rand_input) # Initialize the variables in the layer def compute_true_l2(vs, wd): return tf.reduce_sum(tf.square(vs)) * wd true_l2 = compute_true_l2(conv.variables, weight_decay) keras_l2 = tf.add_n(conv.losses) self.assertAllClose(true_l2, keras_l2) with tf.GradientTape() as tape_true, tf.GradientTape() as tape_keras: loss = tf.reduce_sum(conv(rand_input)) loss_with_true_l2 = loss + compute_true_l2(conv.variables, weight_decay) loss_with_keras_l2 = loss + tf.add_n(conv.losses) true_grads = tape_true.gradient(loss_with_true_l2, conv.variables) keras_grads = tape_keras.gradient(loss_with_keras_l2, conv.variables) self.assertAllClose(true_grads, keras_grads) optimizer.apply_gradients(zip(keras_grads, conv.variables)) keras_l2_after_update = tf.add_n(conv.losses) self.assertNotAllClose(keras_l2, keras_l2_after_update) def compute_gradients(model, images, labels): with tf.GradientTape() as tape: logits = model(images, training=True) cross_ent = tf.losses.softmax_cross_entropy( logits=logits, onehot_labels=labels) regularization = tf.add_n(model.losses) loss = cross_ent + regularization tf.contrib.summary.scalar(name='loss', tensor=loss) return tape.gradient(loss, model.variables) def apply_gradients(model, optimizer, gradients): optimizer.apply_gradients(zip(gradients, model.variables)) def device_and_data_format(): return ('/gpu:0', 'channels_first') if tf.test.is_gpu_available() else ('/cpu:0', 'channels_last') def random_batch(batch_size, data_format): shape = (3, 224, 224) if data_format == 'channels_first' else (224, 224, 3) shape = (batch_size,) + shape num_classes = 1000 images = tf.random_uniform(shape) labels = tf.random_uniform( [batch_size], minval=0, maxval=num_classes, dtype=tf.int32) one_hot = tf.one_hot(labels, num_classes) return images, one_hot class MockIterator(object): def __init__(self, tensors): self._tensors = [tf.identity(x) for x in tensors] def next(self): return self._tensors class DensenetBenchmark(tf.test.Benchmark): def __init__(self): self.depth = 121 self.growth_rate = 32 self.num_blocks = 4 self.output_classes = 1000 self.num_layers_in_each_block = [6, 12, 24, 16] def _train_batch_sizes(self): """Choose batch sizes based on GPU capability.""" for device in device_lib.list_local_devices(): if tf.DeviceSpec.from_string(device.name).device_type == 'GPU': if 'K20' in device.physical_device_desc: return (16,) if 'P100' in device.physical_device_desc: return (16, 32, 64) if tf.DeviceSpec.from_string(device.name).device_type == 'TPU': return (32,) return (16, 32) def _report(self, label, start, num_iters, device, batch_size, data_format): avg_time = (time.time() - start) / num_iters dev = tf.DeviceSpec.from_string(device).device_type.lower() name = '%s_%s_batch_%d_%s' % (label, dev, batch_size, data_format) extras = {'examples_per_sec': batch_size / avg_time} self.report_benchmark( iters=num_iters, wall_time=avg_time, name=name, extras=extras) def _force_device_sync(self): # If this function is called in the context of a non-CPU device # (e.g., inside a 'with tf.device("/gpu:0")' block) # then this will force a copy from CPU->NON_CPU_DEVICE->CPU, # which forces a sync. This is a roundabout way, yes. tf.constant(1.).cpu() def _benchmark_eager_apply(self, label, device_and_format, defun=False, execution_mode=None): with tfe.execution_mode(execution_mode): device, data_format = device_and_format model = densenet.DenseNet(self.depth, self.growth_rate, self.num_blocks, self.output_classes, self.num_layers_in_each_block, data_format, bottleneck=True, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=True, include_top=True) if defun: # TODO(apassos) enable tfe.function here model.call = tfe.defun(model.call) batch_size = 64 num_burn = 5 num_iters = 30 with tf.device(device): images, _ = random_batch(batch_size, data_format) for _ in xrange(num_burn): model(images, training=False).cpu() if execution_mode: tfe.async_wait() gc.collect() start = time.time() for _ in xrange(num_iters): model(images, training=False).cpu() if execution_mode: tfe.async_wait() self._report(label, start, num_iters, device, batch_size, data_format) def benchmark_eager_apply_sync(self): self._benchmark_eager_apply('eager_apply', device_and_data_format(), defun=False) def benchmark_eager_apply_async(self): self._benchmark_eager_apply( 'eager_apply_async', device_and_data_format(), defun=False, execution_mode=tfe.ASYNC) def benchmark_eager_apply_with_defun(self): self._benchmark_eager_apply('eager_apply_with_defun', device_and_data_format(), defun=True) def _benchmark_eager_train(self, label, make_iterator, device_and_format, defun=False, execution_mode=None): with tfe.execution_mode(execution_mode): device, data_format = device_and_format for batch_size in self._train_batch_sizes(): (images, labels) = random_batch(batch_size, data_format) model = densenet.DenseNet(self.depth, self.growth_rate, self.num_blocks, self.output_classes, self.num_layers_in_each_block, data_format, bottleneck=True, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=True, include_top=True) optimizer = tf.train.GradientDescentOptimizer(0.1) apply_grads = apply_gradients if defun: model.call = tfe.defun(model.call) apply_grads = tfe.defun(apply_gradients) num_burn = 3 num_iters = 10 with tf.device(device): iterator = make_iterator((images, labels)) for _ in xrange(num_burn): (images, labels) = iterator.next() apply_grads(model, optimizer, compute_gradients(model, images, labels)) if execution_mode: tfe.async_wait() self._force_device_sync() gc.collect() start = time.time() for _ in xrange(num_iters): (images, labels) = iterator.next() apply_grads(model, optimizer, compute_gradients(model, images, labels)) if execution_mode: tfe.async_wait() self._force_device_sync() self._report(label, start, num_iters, device, batch_size, data_format) def benchmark_eager_train_sync(self): self._benchmark_eager_train('eager_train', MockIterator, device_and_data_format(), defun=False) def benchmark_eager_train_async(self): self._benchmark_eager_train( 'eager_train_async', MockIterator, device_and_data_format(), defun=False, execution_mode=tfe.ASYNC) def benchmark_eager_train_with_defun(self): self._benchmark_eager_train( 'eager_train_with_defun', MockIterator, device_and_data_format(), defun=True) def benchmark_eager_train_datasets(self): def make_iterator(tensors): with tf.device('/device:CPU:0'): ds = tf.data.Dataset.from_tensors(tensors).repeat() return tfe.Iterator(ds) self._benchmark_eager_train( 'eager_train_dataset', make_iterator, device_and_data_format(), defun=False) def benchmark_eager_train_datasets_with_defun(self): def make_iterator(tensors): with tf.device('/device:CPU:0'): ds = tf.data.Dataset.from_tensors(tensors).repeat() return tfe.Iterator(ds) self._benchmark_eager_train( 'eager_train_dataset_with_defun', make_iterator, device_and_data_format(), defun=True) if __name__ == '__main__': tf.enable_eager_execution() tf.test.main()
package com.twitter.scalding import scala.tools.nsc.interpreter.ILoop trait ILoopCompat extends ILoop
package org.keycloak.testsuite.springboot; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class SpringAdminPage extends AbstractSpringbootPage { @FindBy(className = "test") private WebElement testDiv; public static final String PAGE_TITLE = "springboot admin page"; public SpringAdminPage() { super(PAGE_TITLE); } public String getTestDivString() { return testDiv.getText(); } }
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_COMPILER_MLIR_TENSORFLOW_UTILS_CONVERT_TYPE_H_ #define TENSORFLOW_COMPILER_MLIR_TENSORFLOW_UTILS_CONVERT_TYPE_H_ #include "mlir/IR/Builders.h" // from @llvm-project #include "mlir/IR/Types.h" // from @llvm-project #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/tensor_shape.pb.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/stream_executor/lib/statusor.h" namespace tensorflow { using stream_executor::port::StatusOr; // Converts the TensorFlow DataType 'dtype' into an MLIR (scalar) type. Status ConvertDataType(DataType dtype, mlir::Builder builder, mlir::Type* type); // Converts a scalar MLIR type to a TensorFlow Datatype. Status ConvertScalarTypeToDataType(mlir::Type type, DataType* dtype); // Converts an MLIR type to TensorFlow DataType. If 'type' is a scalar type, it // is converted directly. If it is a shaped type, the element type is converted. Status ConvertToDataType(mlir::Type type, DataType* dtype); // Converts an TensorFlow shape to the one used in MLIR. void ConvertToMlirShape(const TensorShape& input_shape, llvm::SmallVectorImpl<int64_t>* shape); // Converts an TensorFlow shape proto to the one used in MLIR. Status ConvertToMlirShape(const TensorShapeProto& input_shape, llvm::SmallVectorImpl<int64_t>* shape); // Given a tensor shape and dtype, get the corresponding MLIR tensor type. StatusOr<mlir::Type> ConvertToMlirTensorType(const TensorShapeProto& shape, DataType dtype, mlir::Builder* builder); } // namespace tensorflow #endif // TENSORFLOW_COMPILER_MLIR_TENSORFLOW_UTILS_CONVERT_TYPE_H_
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.packages; import com.google.common.base.Predicate; import com.google.common.base.Verify; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.syntax.Label; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Model for the "environment_group' rule: the piece of Bazel's rule constraint system that binds * thematically related environments together and determines which environments a rule supports * by default. See {@link com.google.devtools.build.lib.analysis.constraints.ConstraintSemantics} * for precise semantic details of how this information is used. * * <p>Note that "environment_group" is implemented as a loading-time function, not a rule. This is * to support proper discovery of defaults: Say rule A has no explicit constraints and depends * on rule B, which is explicitly constrained to environment ":bar". Since A declares nothing * explicitly, it's implicitly constrained to DEFAULTS (whatever that is). Therefore, the * dependency is only allowed if DEFAULTS doesn't include environments beyond ":bar". To figure * that out, we need to be able to look up the environment group for ":bar", which is what this * class provides. * * <p>If we implemented this as a rule, we'd have to provide that lookup via rule dependencies, * e.g. something like: * * <code> * environment( * name = 'bar', * group = [':sample_environments'], * is_default = 1 * ) * </code> * * <p>But this won't work. This would let us find the environment group for ":bar", but the only way * to determine what other environments belong to the group is to have the group somehow reference * them. That would produce circular dependencies in the build graph, which is no good. */ @Immutable public class EnvironmentGroup implements Target { private final Label label; private final Location location; private final Package containingPackage; private final Set<Label> environments; private final Set<Label> defaults; /** * Maps a member environment to the set of environments that directly fulfill it. Note that * we can't populate this map until all Target instances for member environments have been * initialized, which may occur after group instantiation (this makes the class mutable). */ private final Map<Label, NestedSet<Label>> fulfillersMap = new HashMap<>(); /** * Predicate that matches labels from a different package than the initialized package. */ private static final class DifferentPackage implements Predicate<Label> { private final Package containingPackage; private DifferentPackage(Package containingPackage) { this.containingPackage = containingPackage; } @Override public boolean apply(Label environment) { return !environment.getPackageName().equals(containingPackage.getName()); } } /** * Instantiates a new group without verifying the soundness of its contents. See the validation * methods below for appropriate checks. * * @param label the build label identifying this group * @param pkg the package this group belongs to * @param environments the set of environments that belong to this group * @param defaults the environments a rule implicitly supports unless otherwise specified * @param location location in the BUILD file of this group */ EnvironmentGroup(Label label, Package pkg, final List<Label> environments, List<Label> defaults, Location location) { this.label = label; this.location = location; this.containingPackage = pkg; this.environments = ImmutableSet.copyOf(environments); this.defaults = ImmutableSet.copyOf(defaults); } /** * Checks that all environments declared by this group are in the same package as the group (so * we can perform an environment --> environment_group lookup and know the package is available) * and checks that all defaults are legitimate members of the group. * * <p>Does <b>not</b> check that the referenced environments exist (see * {@link #processMemberEnvironments}). * * @return a list of validation errors that occurred */ List<Event> validateMembership() { List<Event> events = new ArrayList<>(); // All environments should belong to the same package as this group. for (Label environment : Iterables.filter(environments, new DifferentPackage(containingPackage))) { events.add(Event.error(location, environment + " is not in the same package as group " + label)); } // The defaults must be a subset of the member environments. for (Label unknownDefault : Sets.difference(defaults, environments)) { events.add(Event.error(location, "default " + unknownDefault + " is not a " + "declared environment for group " + getLabel())); } return events; } /** * Checks that the group's declared environments are legitimate same-package environment * rules and prepares the "fulfills" relationships between these environments to support * {@link #getFulfillers}. * * @param pkgTargets mapping from label name to target instance for this group's package * @return a list of validation errors that occurred */ List<Event> processMemberEnvironments(Map<String, Target> pkgTargets) { List<Event> events = new ArrayList<>(); // Maps an environment to the environments that directly fulfill it. Multimap<Label, Label> directFulfillers = HashMultimap.create(); for (Label envName : environments) { Target env = pkgTargets.get(envName.getName()); if (isValidEnvironment(env, envName, "", events)) { AttributeMap attr = NonconfigurableAttributeMapper.of((Rule) env); for (Label fulfilledEnv : attr.get("fulfills", Type.LABEL_LIST)) { if (isValidEnvironment(pkgTargets.get(fulfilledEnv.getName()), fulfilledEnv, "in \"fulfills\" attribute of " + envName + ": ", events)) { directFulfillers.put(fulfilledEnv, envName); } } } } // Now that we know which environments directly fulfill each other, compute which environments // transitively fulfill each other. We could alternatively compute this on-demand, but since // we don't expect these chains to be very large we opt toward computing them once at package // load time. Verify.verify(fulfillersMap.isEmpty()); for (Label envName : environments) { setTransitiveFulfillers(envName, directFulfillers, fulfillersMap); } return events; } /** * Given an environment and set of environments that directly fulfill it, computes a nested * set of environments that <i>transitively</i> fulfill it, places it into transitiveFulfillers, * and returns that set. */ private static NestedSet<Label> setTransitiveFulfillers(Label env, Multimap<Label, Label> directFulfillers, Map<Label, NestedSet<Label>> transitiveFulfillers) { if (transitiveFulfillers.containsKey(env)) { return transitiveFulfillers.get(env); } else if (!directFulfillers.containsKey(env)) { // Nobody fulfills this environment. NestedSet<Label> emptySet = NestedSetBuilder.emptySet(Order.STABLE_ORDER); transitiveFulfillers.put(env, emptySet); return emptySet; } else { NestedSetBuilder<Label> set = NestedSetBuilder.stableOrder(); for (Label fulfillingEnv : directFulfillers.get(env)) { set.add(fulfillingEnv); set.addTransitive( setTransitiveFulfillers(fulfillingEnv, directFulfillers, transitiveFulfillers)); } NestedSet<Label> builtSet = set.build(); transitiveFulfillers.put(env, builtSet); return builtSet; } } private boolean isValidEnvironment(Target env, Label envName, String prefix, List<Event> events) { if (env == null) { events.add(Event.error(location, prefix + "environment " + envName + " does not exist")); return false; } else if (!env.getTargetKind().equals("environment rule")) { events.add(Event.error(location, prefix + env.getLabel() + " is not a valid environment")); return false; } else if (!environments.contains(env.getLabel())) { events.add(Event.error(location, prefix + env.getLabel() + " is not a member of this group")); return false; } return true; } /** * Returns the environments that belong to this group. */ public Set<Label> getEnvironments() { return environments; } /** * Returns the environments a rule supports by default, i.e. if it has no explicit references to * environments in this group. */ public Set<Label> getDefaults() { return defaults; } /** * Determines whether or not an environment is a default. Returns false if the environment * doesn't belong to this group. */ public boolean isDefault(Label environment) { return defaults.contains(environment); } /** * Returns the set of environments that transitively fulfill the specified environment. * The environment must be a valid member of this group. * * <p>>For example, if the input is <code>":foo"</code> and <code>":bar"</code> fulfills * <code>":foo"</code> and <code>":baz"</code> fulfills <code>":bar"</code>, this returns * <code>[":foo", ":bar", ":baz"]</code>. * * <p>If no environments fulfill the input, returns an empty set. */ public Iterable<Label> getFulfillers(Label environment) { return Verify.verifyNotNull(fulfillersMap.get(environment)); } @Override public Label getLabel() { return label; } @Override public String getName() { return label.getName(); } @Override public Package getPackage() { return containingPackage; } @Override public String getTargetKind() { return targetKind(); } @Override public Rule getAssociatedRule() { return null; } @Override public License getLicense() { return License.NO_LICENSE; } @Override public Location getLocation() { return location; } @Override public String toString() { return targetKind() + " " + getLabel(); } @Override public Set<License.DistributionType> getDistributions() { return Collections.emptySet(); } @Override public RuleVisibility getVisibility() { return ConstantRuleVisibility.PRIVATE; // No rule should be referencing an environment_group. } public static String targetKind() { return "environment group"; } @Override public boolean equals(Object o) { // In a distributed implementation these may not be the same object. if (o == this) { return true; } else if (!(o instanceof EnvironmentGroup)) { return false; } else { return ((EnvironmentGroup) o).getLabel().equals(getLabel()); } } }
#!/bin/bash # Copyright 2014 The Kubernetes Authors All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -o errexit set -o nounset set -o pipefail GINKGO_PARALLEL=${GINKGO_PARALLEL:-n} # set to 'y' to run tests in parallel KUBE_ROOT=$(dirname "${BASH_SOURCE}")/.. source "${KUBE_ROOT}/cluster/common.sh" source "${KUBE_ROOT}/hack/lib/init.sh" # Ginkgo will build the e2e tests, so we need to make sure that the environment # is set up correctly (including Godeps, etc). kube::golang::setup_env # Find the ginkgo binary build as part of the release. ginkgo=$(kube::util::find-binary "ginkgo") e2e_test=$(kube::util::find-binary "e2e.test") # --- Setup some env vars. : ${KUBECTL:="${KUBE_ROOT}/cluster/kubectl.sh"} : ${KUBE_CONFIG_FILE:="config-test.sh"} export KUBECTL KUBE_CONFIG_FILE source "${KUBE_ROOT}/cluster/kube-util.sh" # ---- Do cloud-provider-specific setup if [[ -n "${KUBERNETES_CONFORMANCE_TEST:-}" ]]; then echo "Conformance test: not doing test setup." KUBERNETES_PROVIDER="" detect-master-from-kubeconfig auth_config=( "--kubeconfig=${KUBECONFIG}" ) else echo "Setting up for KUBERNETES_PROVIDER=\"${KUBERNETES_PROVIDER}\"." prepare-e2e detect-master >/dev/null KUBE_MASTER_URL="${KUBE_MASTER_URL:-https://${KUBE_MASTER_IP:-}}" auth_config=( "--kubeconfig=${KUBECONFIG:-$DEFAULT_KUBECONFIG}" ) fi if [[ -n "${NODE_INSTANCE_PREFIX:-}" ]]; then NODE_INSTANCE_GROUP="${NODE_INSTANCE_PREFIX}-group" else NODE_INSTANCE_GROUP="" fi if [[ "${KUBERNETES_PROVIDER}" == "gke" ]]; then detect-node-instance-group fi ginkgo_args=() if [[ -n "${CONFORMANCE_TEST_SKIP_REGEX:-}" ]]; then ginkgo_args+=("--skip=${CONFORMANCE_TEST_SKIP_REGEX}") ginkgo_args+=("--seed=1436380640") fi if [[ -n "${GINKGO_PARALLEL_NODES:-}" ]]; then ginkgo_args+=("--nodes=${GINKGO_PARALLEL_NODES}") elif [[ ${GINKGO_PARALLEL} =~ ^[yY]$ ]]; then ginkgo_args+=("--nodes=30") # By default, set --nodes=30. fi # The --host setting is used only when providing --auth_config # If --kubeconfig is used, the host to use is retrieved from the .kubeconfig # file and the one provided with --host is ignored. # Add path for things like running kubectl binary. export PATH=$(dirname "${e2e_test}"):"${PATH}" "${ginkgo}" "${ginkgo_args[@]:+${ginkgo_args[@]}}" "${e2e_test}" -- \ "${auth_config[@]:+${auth_config[@]}}" \ --host="${KUBE_MASTER_URL}" \ --provider="${KUBERNETES_PROVIDER}" \ --gce-project="${PROJECT:-}" \ --gce-zone="${ZONE:-}" \ --gce-service-account="${GCE_SERVICE_ACCOUNT:-}" \ --gke-cluster="${CLUSTER_NAME:-}" \ --kube-master="${KUBE_MASTER:-}" \ --cluster-tag="${CLUSTER_ID:-}" \ --repo-root="${KUBE_ROOT}" \ --node-instance-group="${NODE_INSTANCE_GROUP:-}" \ --prefix="${KUBE_GCE_INSTANCE_PREFIX:-e2e}" \ ${KUBE_OS_DISTRIBUTION:+"--os-distro=${KUBE_OS_DISTRIBUTION}"} \ ${NUM_NODES:+"--num-nodes=${NUM_NODES}"} \ ${E2E_CLEAN_START:+"--clean-start=true"} \ ${E2E_MIN_STARTUP_PODS:+"--minStartupPods=${E2E_MIN_STARTUP_PODS}"} \ ${E2E_REPORT_DIR:+"--report-dir=${E2E_REPORT_DIR}"} \ ${E2E_REPORT_PREFIX:+"--report-prefix=${E2E_REPORT_PREFIX}"} \ "${@:-}"
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.control; import java.io.Serializable; import org.apache.jmeter.samplers.Sampler; import org.apache.jmeter.testelement.property.BooleanProperty; import org.apache.jmeter.testelement.property.StringProperty; import org.apache.jmeter.threads.JMeterContext; import org.apache.jmeter.threads.JMeterVariables; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * ForeachController that iterates over a list of variables named XXXX_NN stored in {@link JMeterVariables} * where NN is a number starting from 1 to number of occurences. * This list of variable is usually set by PostProcessor (Regexp PostProcessor or {@link org.apache.jmeter.extractor.HtmlExtractor}) * Iteration can take the full list or only a subset (configured through indexes) * */ public class ForeachController extends GenericController implements Serializable { private static final Logger log = LoggingManager.getLoggerForClass(); private static final long serialVersionUID = 240L; private static final String INPUTVAL = "ForeachController.inputVal";// $NON-NLS-1$ private static final String START_INDEX = "ForeachController.startIndex";// $NON-NLS-1$ private static final String END_INDEX = "ForeachController.endIndex";// $NON-NLS-1$ private static final String RETURNVAL = "ForeachController.returnVal";// $NON-NLS-1$ private static final String USE_SEPARATOR = "ForeachController.useSeparator";// $NON-NLS-1$ private static final String INDEX_DEFAULT_VALUE = ""; // start/end index default value for string getters and setters private int loopCount = 0; private static final String DEFAULT_SEPARATOR = "_";// $NON-NLS-1$ public ForeachController() { } /** * @param startIndex Start index of loop */ public void setStartIndex(String startIndex) { setProperty(START_INDEX, startIndex, INDEX_DEFAULT_VALUE); } /** * @return start index of loop */ private int getStartIndex() { // Although the default is not the same as for the string value, it is only used internally return getPropertyAsInt(START_INDEX, 0); } /** * @return start index of loop as String */ public String getStartIndexAsString() { return getPropertyAsString(START_INDEX, INDEX_DEFAULT_VALUE); } /** * @param endIndex End index of loop */ public void setEndIndex(String endIndex) { setProperty(END_INDEX, endIndex, INDEX_DEFAULT_VALUE); } /** * @return end index of loop */ private int getEndIndex() { // Although the default is not the same as for the string value, it is only used internally return getPropertyAsInt(END_INDEX, Integer.MAX_VALUE); } /** * @return end index of loop */ public String getEndIndexAsString() { return getPropertyAsString(END_INDEX, INDEX_DEFAULT_VALUE); } public void setInputVal(String inputValue) { setProperty(new StringProperty(INPUTVAL, inputValue)); } private String getInputVal() { getProperty(INPUTVAL).recoverRunningVersion(null); return getInputValString(); } public String getInputValString() { return getPropertyAsString(INPUTVAL); } public void setReturnVal(String inputValue) { setProperty(new StringProperty(RETURNVAL, inputValue)); } private String getReturnVal() { getProperty(RETURNVAL).recoverRunningVersion(null); return getReturnValString(); } public String getReturnValString() { return getPropertyAsString(RETURNVAL); } private String getSeparator() { return getUseSeparator() ? DEFAULT_SEPARATOR : "";// $NON-NLS-1$ } public void setUseSeparator(boolean b) { setProperty(new BooleanProperty(USE_SEPARATOR, b)); } public boolean getUseSeparator() { return getPropertyAsBoolean(USE_SEPARATOR, true); } /** * {@inheritDoc} */ @Override public boolean isDone() { if (loopCount >= getEndIndex()) { return true; } JMeterContext context = getThreadContext(); StringBuilder builder = new StringBuilder( getInputVal().length()+getSeparator().length()+3); String inputVariable = builder.append(getInputVal()) .append(getSeparator()) .append(Integer.toString(loopCount+1)).toString(); final JMeterVariables variables = context.getVariables(); final Object currentVariable = variables.getObject(inputVariable); if (currentVariable != null) { variables.putObject(getReturnVal(), currentVariable); if (log.isDebugEnabled()) { log.debug("ForEach resultstring isDone=" + variables.get(getReturnVal())); } return false; } return super.isDone(); } /** * Tests that JMeterVariables contain inputVal_<count>, if not we can stop iterating */ private boolean endOfArguments() { JMeterContext context = getThreadContext(); String inputVariable = getInputVal() + getSeparator() + (loopCount + 1); if (context.getVariables().getObject(inputVariable) != null) { log.debug("ForEach resultstring eofArgs= false"); return false; } log.debug("ForEach resultstring eofArgs= true"); return true; } // Prevent entry if nothing to do @Override public Sampler next() { if (emptyList()) { reInitialize(); resetLoopCount(); return null; } return super.next(); } /** * Check if there are any matching entries * * @return whether any entries in the list */ private boolean emptyList() { JMeterContext context = getThreadContext(); StringBuilder builder = new StringBuilder( getInputVal().length()+getSeparator().length()+3); String inputVariable = builder.append(getInputVal()) .append(getSeparator()) .append(Integer.toString(loopCount+1)).toString(); if (context.getVariables().getObject(inputVariable) != null) { return false; } if (log.isDebugEnabled()) { log.debug("No entries found - null first entry: " + inputVariable); } return true; } /** * {@inheritDoc} */ @Override protected Sampler nextIsNull() throws NextIsNullException { reInitialize(); // Conditions to reset the loop count if (endOfArguments() // no more variables to iterate ||loopCount >= getEndIndex() // we reached end index ) { // setDone(true); resetLoopCount(); return null; } return next(); } protected void incrementLoopCount() { loopCount++; } protected void resetLoopCount() { loopCount = getStartIndex(); } /** * {@inheritDoc} */ @Override protected int getIterCount() { return loopCount + 1; } /** * {@inheritDoc} */ @Override protected void reInitialize() { setFirst(true); resetCurrent(); incrementLoopCount(); recoverRunningVersion(); } /** * {@inheritDoc} */ @Override public void triggerEndOfLoop() { super.triggerEndOfLoop(); resetLoopCount(); } /** * Reset loopCount to Start index * @see org.apache.jmeter.control.GenericController#initialize() */ @Override public void initialize() { super.initialize(); loopCount = getStartIndex(); } }
/* Copyright (c) 2007 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. */ package sample.gbase.cmdline; import com.google.gdata.client.Service; import java.net.URL; /** * Displays the media entry (meta-data) of one attachment. * This command is called from {@link CustomerTool}. */ public class GetMediaCommand extends Command { private String attachmentId; @Override public void execute() throws Exception { Service service = createService(); Service.GDataRequest request = service.createEntryRequest(new URL(attachmentId)); // Send the request (HTTP GET) request.execute(); // Save the response outputRawResponse(request); } /** Sets the id/URL of the media attachment to display. */ public void setAttachmentId(String attachmentId) { this.attachmentId = attachmentId; } }
//===--- PlistReporter.cpp - ARC Migrate Tool Plist Reporter ----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "Internals.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/PlistSupport.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/Lexer.h" using namespace clang; using namespace arcmt; using namespace markup; static StringRef getLevelName(DiagnosticsEngine::Level Level) { switch (Level) { case DiagnosticsEngine::Ignored: llvm_unreachable("ignored"); case DiagnosticsEngine::Note: return "note"; case DiagnosticsEngine::Remark: case DiagnosticsEngine::Warning: return "warning"; case DiagnosticsEngine::Fatal: case DiagnosticsEngine::Error: return "error"; } llvm_unreachable("Invalid DiagnosticsEngine level!"); } void arcmt::writeARCDiagsToPlist(const std::string &outPath, ArrayRef<StoredDiagnostic> diags, SourceManager &SM, const LangOptions &LangOpts) { DiagnosticIDs DiagIDs; // Build up a set of FIDs that we use by scanning the locations and // ranges of the diagnostics. FIDMap FM; SmallVector<FileID, 10> Fids; for (ArrayRef<StoredDiagnostic>::iterator I = diags.begin(), E = diags.end(); I != E; ++I) { const StoredDiagnostic &D = *I; AddFID(FM, Fids, SM, D.getLocation()); for (StoredDiagnostic::range_iterator RI = D.range_begin(), RE = D.range_end(); RI != RE; ++RI) { AddFID(FM, Fids, SM, RI->getBegin()); AddFID(FM, Fids, SM, RI->getEnd()); } } std::error_code EC; llvm::raw_fd_ostream o(outPath, EC, llvm::sys::fs::F_Text); if (EC) { llvm::errs() << "error: could not create file: " << outPath << '\n'; return; } EmitPlistHeader(o); // Write the root object: a <dict> containing... // - "files", an <array> mapping from FIDs to file names // - "diagnostics", an <array> containing the diagnostics o << "<dict>\n" " <key>files</key>\n" " <array>\n"; for (FileID FID : Fids) EmitString(o << " ", SM.getFileEntryForID(FID)->getName()) << '\n'; o << " </array>\n" " <key>diagnostics</key>\n" " <array>\n"; for (ArrayRef<StoredDiagnostic>::iterator DI = diags.begin(), DE = diags.end(); DI != DE; ++DI) { const StoredDiagnostic &D = *DI; if (D.getLevel() == DiagnosticsEngine::Ignored) continue; o << " <dict>\n"; // Output the diagnostic. o << " <key>description</key>"; EmitString(o, D.getMessage()) << '\n'; o << " <key>category</key>"; EmitString(o, DiagIDs.getCategoryNameFromID( DiagIDs.getCategoryNumberForDiag(D.getID()))) << '\n'; o << " <key>type</key>"; EmitString(o, getLevelName(D.getLevel())) << '\n'; // Output the location of the bug. o << " <key>location</key>\n"; EmitLocation(o, SM, D.getLocation(), FM, 2); // Output the ranges (if any). if (!D.getRanges().empty()) { o << " <key>ranges</key>\n"; o << " <array>\n"; for (auto &R : D.getRanges()) { CharSourceRange ExpansionRange = SM.getExpansionRange(R); EmitRange(o, SM, Lexer::getAsCharRange(ExpansionRange, SM, LangOpts), FM, 4); } o << " </array>\n"; } // Close up the entry. o << " </dict>\n"; } o << " </array>\n"; // Finish. o << "</dict>\n</plist>\n"; }
#include "ruby.h" #include "rubyspec.h" #ifdef RUBY_VERSION_IS_1_8 #include "rubyio.h" #else #include "ruby/io.h" #endif #include <fcntl.h> #ifdef __cplusplus extern "C" { #endif #ifdef RUBY_VERSION_IS_LT_1_8_7 #define rb_io_t OpenFile #endif static int set_non_blocking(int fd) { int flags; #if defined(O_NONBLOCK) if (-1 == (flags = fcntl(fd, F_GETFL, 0))) flags = 0; return fcntl(fd, F_SETFL, flags | O_NONBLOCK); #else flags = 1; return ioctl(fd, FIOBIO, &flags); #endif } #ifdef HAVE_GET_OPEN_FILE static int io_spec_get_fd(VALUE io) { rb_io_t* fp; GetOpenFile(io, fp); #ifdef RUBY_VERSION_IS_1_9 return fp->fd; #else return fileno(fp->f); #endif } VALUE io_spec_GetOpenFile_fd(VALUE self, VALUE io) { return INT2NUM(io_spec_get_fd(io)); } #endif #ifdef HAVE_RB_IO_WRITE VALUE io_spec_rb_io_write(VALUE self, VALUE io, VALUE str) { return rb_io_write(io, str); } #endif #ifdef HAVE_RB_IO_CHECK_READABLE VALUE io_spec_rb_io_check_readable(VALUE self, VALUE io) { rb_io_t* fp; GetOpenFile(io, fp); rb_io_check_readable(fp); return Qnil; } #endif #ifdef HAVE_RB_IO_CHECK_WRITABLE VALUE io_spec_rb_io_check_writable(VALUE self, VALUE io) { rb_io_t* fp; GetOpenFile(io, fp); rb_io_check_writable(fp); return Qnil; } #endif #ifdef HAVE_RB_IO_CHECK_CLOSED VALUE io_spec_rb_io_check_closed(VALUE self, VALUE io) { rb_io_t* fp; GetOpenFile(io, fp); rb_io_check_closed(fp); return Qnil; } #endif #ifdef RUBY_VERSION_IS_1_9 typedef int wait_bool; #define wait_bool_to_ruby_bool(x) (x ? Qtrue : Qfalse) #else typedef VALUE wait_bool; #define wait_bool_to_ruby_bool(x) (x) #endif #ifdef HAVE_RB_IO_WAIT_READABLE #define RB_IO_WAIT_READABLE_BUF 13 VALUE io_spec_rb_io_wait_readable(VALUE self, VALUE io, VALUE read_p) { int fd = io_spec_get_fd(io); set_non_blocking(fd); char buf[RB_IO_WAIT_READABLE_BUF]; wait_bool ret; if(RTEST(read_p)) { rb_ivar_set(self, rb_intern("@write_data"), Qtrue); if(read(fd, buf, RB_IO_WAIT_READABLE_BUF) != -1) { return Qnil; } } ret = rb_io_wait_readable(fd); if(RTEST(read_p)) { if(read(fd, buf, RB_IO_WAIT_READABLE_BUF) != 13) { return Qnil; } rb_ivar_set(self, rb_intern("@read_data"), rb_str_new(buf, RB_IO_WAIT_READABLE_BUF)); } return wait_bool_to_ruby_bool(ret); } #endif #ifdef HAVE_RB_IO_WAIT_WRITABLE VALUE io_spec_rb_io_wait_writable(VALUE self, VALUE io) { wait_bool ret; ret = rb_io_wait_writable(io_spec_get_fd(io)); return wait_bool_to_ruby_bool(ret); } #endif #ifdef HAVE_RB_IO_CLOSE VALUE io_spec_rb_io_close(VALUE self, VALUE io) { return rb_io_close(io); } #endif void Init_io_spec() { VALUE cls = rb_define_class("CApiIOSpecs", rb_cObject); #ifdef HAVE_GET_OPEN_FILE rb_define_method(cls, "GetOpenFile_fd", io_spec_GetOpenFile_fd, 1); #endif #ifdef HAVE_RB_IO_WRITE rb_define_method(cls, "rb_io_write", io_spec_rb_io_write, 2); #endif #ifdef HAVE_RB_IO_CLOSE rb_define_method(cls, "rb_io_close", io_spec_rb_io_close, 1); #endif #ifdef HAVE_RB_IO_CHECK_READABLE rb_define_method(cls, "rb_io_check_readable", io_spec_rb_io_check_readable, 1); #endif #ifdef HAVE_RB_IO_CHECK_WRITABLE rb_define_method(cls, "rb_io_check_writable", io_spec_rb_io_check_writable, 1); #endif #ifdef HAVE_RB_IO_CHECK_CLOSED rb_define_method(cls, "rb_io_check_closed", io_spec_rb_io_check_closed, 1); #endif #ifdef HAVE_RB_IO_WAIT_READABLE rb_define_method(cls, "rb_io_wait_readable", io_spec_rb_io_wait_readable, 2); #endif #ifdef HAVE_RB_IO_WAIT_WRITABLE rb_define_method(cls, "rb_io_wait_writable", io_spec_rb_io_wait_writable, 1); #endif } #ifdef __cplusplus } #endif
<?php /** * File containing the ezcDocumentOdtElementWhitespaceFilter class. * * @package Document * @version 1.3.1 * @copyright Copyright (C) 2005-2010 eZ Systems AS. All rights reserved. * @license http://ez.no/licenses/new_bsd New BSD License * @access private */ /** * Filter for ODT <text:s/>, <text:tab/> and <text:line-break/> elements. * * @package Document * @version 1.3.1 * @access private */ class ezcDocumentOdtElementWhitespaceFilter extends ezcDocumentOdtElementBaseFilter { /** * Filter a single element. * * @param DOMElement $element * @return void */ public function filterElement( DOMElement $element ) { $spaces = ''; switch ( $element->localName ) { case 's': $count = $element->getAttributeNS( ezcDocumentOdt::NS_ODT_TEXT, 'c' ); $spaces = str_repeat( ' ', ( $count !== '' ? (int) $count : 1 ) ); break; case 'tab': $spaces = "\t"; break; case 'line-break': $spaces = "\n"; break; } $element->setProperty( 'spaces', $spaces ); } /** * Check if filter handles the current element. * * Returns a boolean value, indicating weather this filter can handle * the current element. * * @param DOMElement $element * @return void */ public function handles( DOMElement $element ) { return ( $element->namespaceURI === ezcDocumentOdt::NS_ODT_TEXT && ( $element->localName === 's' || $element->localName === 'tab' || $element->localName === 'line-break' ) ); } } ?>
body { background-color: #FFFFFF; } body, td, .content { font-family: Verdana, Arial, helvetica, sans-serif; font-size: 12px; } .title { font-family: Verdana, Arial, helvetica, sans-serif; font-size: 16px; font-weight: bold; } .subtitle { font-size: 12px; font-weight: bold; } .toc_ul, .toc_li { margin-left: 8 px; line-height: 16px; } .step_ol, .step_li { margin-left: 11 px; line-height: 16px; } img { border: 0; } a:visited { color: #666666; text-decoration: underline; } a:active { color: #666666; text-decoration: underline; } a:hover { color: #666666; text-decoration: underline; } a { color: #666666; text-decoration: underline; } .pageheader { border: #E0E0E0 solid 1px; } .pagefooter { border: #E0E0E0 solid 1px; } .sample { background-color: #FFFFFF; border: #000000 solid 1px; } .samplecontent { font-size: 10px; } .code { background-color: #FFFFFF; border: #000000 solid 1px; } .codecontent { font-size: 10px; } .codecontent a:visited { color: #666666; text-decoration: none; font-weight: bold } .codecontent a:active { color: #666666; text-decoration: none; font-weight: bold } .codecontent a:hover { color: #666666; text-decoration: none; font-weight: bold } .codecontent a { color: #666666; text-decoration: none; font-weight: bold } hr { height: 1px; }
/* (C) 1999-2001 Paul `Rusty' Russell * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/types.h> #include <linux/ipv6.h> #include <linux/in6.h> #include <linux/netfilter.h> #include <linux/module.h> #include <linux/skbuff.h> #include <linux/icmp.h> #include <linux/sysctl.h> #include <net/ipv6.h> #include <net/inet_frag.h> #include <linux/netfilter_ipv6.h> #include <linux/netfilter_bridge.h> #if IS_ENABLED(CONFIG_NF_CONNTRACK) #include <net/netfilter/nf_conntrack.h> #include <net/netfilter/nf_conntrack_helper.h> #include <net/netfilter/nf_conntrack_l4proto.h> #include <net/netfilter/nf_conntrack_l3proto.h> #include <net/netfilter/nf_conntrack_core.h> #include <net/netfilter/ipv6/nf_conntrack_ipv6.h> #endif #include <net/netfilter/nf_conntrack_zones.h> #include <net/netfilter/ipv6/nf_defrag_ipv6.h> static enum ip6_defrag_users nf_ct6_defrag_user(unsigned int hooknum, struct sk_buff *skb) { u16 zone = NF_CT_DEFAULT_ZONE; #if IS_ENABLED(CONFIG_NF_CONNTRACK) if (skb->nfct) zone = nf_ct_zone((struct nf_conn *)skb->nfct); #endif #ifdef CONFIG_BRIDGE_NETFILTER if (skb->nf_bridge && skb->nf_bridge->mask & BRNF_NF_BRIDGE_PREROUTING) return IP6_DEFRAG_CONNTRACK_BRIDGE_IN + zone; #endif if (hooknum == NF_INET_PRE_ROUTING) return IP6_DEFRAG_CONNTRACK_IN + zone; else return IP6_DEFRAG_CONNTRACK_OUT + zone; } static unsigned int ipv6_defrag(unsigned int hooknum, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)) { struct sk_buff *reasm; #if IS_ENABLED(CONFIG_NF_CONNTRACK) /* Previously seen (loopback)? */ if (skb->nfct && !nf_ct_is_template((struct nf_conn *)skb->nfct)) return NF_ACCEPT; #endif reasm = nf_ct_frag6_gather(skb, nf_ct6_defrag_user(hooknum, skb)); /* queued */ if (reasm == NULL) return NF_STOLEN; /* error occurred or not fragmented */ if (reasm == skb) return NF_ACCEPT; nf_ct_frag6_consume_orig(reasm); NF_HOOK_THRESH(NFPROTO_IPV6, hooknum, reasm, (struct net_device *) in, (struct net_device *) out, okfn, NF_IP6_PRI_CONNTRACK_DEFRAG + 1); return NF_STOLEN; } static struct nf_hook_ops ipv6_defrag_ops[] = { { .hook = ipv6_defrag, .owner = THIS_MODULE, .pf = NFPROTO_IPV6, .hooknum = NF_INET_PRE_ROUTING, .priority = NF_IP6_PRI_CONNTRACK_DEFRAG, }, { .hook = ipv6_defrag, .owner = THIS_MODULE, .pf = NFPROTO_IPV6, .hooknum = NF_INET_LOCAL_OUT, .priority = NF_IP6_PRI_CONNTRACK_DEFRAG, }, }; static int __init nf_defrag_init(void) { int ret = 0; ret = nf_ct_frag6_init(); if (ret < 0) { pr_err("nf_defrag_ipv6: can't initialize frag6.\n"); return ret; } ret = nf_register_hooks(ipv6_defrag_ops, ARRAY_SIZE(ipv6_defrag_ops)); if (ret < 0) { pr_err("nf_defrag_ipv6: can't register hooks\n"); goto cleanup_frag6; } return ret; cleanup_frag6: nf_ct_frag6_cleanup(); return ret; } static void __exit nf_defrag_fini(void) { nf_unregister_hooks(ipv6_defrag_ops, ARRAY_SIZE(ipv6_defrag_ops)); nf_ct_frag6_cleanup(); } void nf_defrag_ipv6_enable(void) { } EXPORT_SYMBOL_GPL(nf_defrag_ipv6_enable); module_init(nf_defrag_init); module_exit(nf_defrag_fini); MODULE_LICENSE("GPL");
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('axis-time-base', function (Y, NAME) { /** * Provides functionality for the handling of time axis data for a chart. * * @module charts * @submodule axis-time-base */ var Y_Lang = Y.Lang; /** * TimeImpl contains logic for time data. TimeImpl is used by the following classes: * <ul> * <li>{{#crossLink "TimeAxisBase"}}{{/crossLink}}</li> * <li>{{#crossLink "TimeAxis"}}{{/crossLink}}</li> * </ul> * * @class TimeImpl * @constructor * @submodule axis-time-base */ function TimeImpl() { } TimeImpl.NAME = "timeImpl"; TimeImpl.ATTRS = { /** * Method used for formatting a label. This attribute allows for the default label formatting method to overridden. * The method use would need to implement the arguments below and return a `String` or an `HTMLElement`. The default * implementation of the method returns a `String`. The output of this method will be rendered to the DOM using * `appendChild`. If you override the `labelFunction` method and return an html string, you will also need to override * the Axis' `appendLabelFunction` to accept html as a `String`. * <dl> * <dt>val</dt><dd>Label to be formatted. (`String`)</dd> * <dt>format</dt><dd>STRFTime string used to format the label. (optional)</dd> * </dl> * * @attribute labelFunction * @type Function */ /** * Pattern used by the `labelFunction` to format a label. * * @attribute labelFormat * @type String */ labelFormat: { value: "%b %d, %y" } }; TimeImpl.prototype = { /** * Type of data used in `Data`. * * @property _type * @readOnly * @private */ _type: "time", /** * Getter method for maximum attribute. * * @method _maximumGetter * @return Number * @private */ _maximumGetter: function () { var max = this._getNumber(this._setMaximum); if(!Y_Lang.isNumber(max)) { max = this._getNumber(this.get("dataMaximum")); } return parseFloat(max); }, /** * Setter method for maximum attribute. * * @method _maximumSetter * @param {Object} value * @private */ _maximumSetter: function (value) { this._setMaximum = this._getNumber(value); return value; }, /** * Getter method for minimum attribute. * * @method _minimumGetter * @return Number * @private */ _minimumGetter: function () { var min = this._getNumber(this._setMinimum); if(!Y_Lang.isNumber(min)) { min = this._getNumber(this.get("dataMinimum")); } return parseFloat(min); }, /** * Setter method for minimum attribute. * * @method _minimumSetter * @param {Object} value * @private */ _minimumSetter: function (value) { this._setMinimum = this._getNumber(value); return value; }, /** * Indicates whether or not the maximum attribute has been explicitly set. * * @method _getSetMax * @return Boolean * @private */ _getSetMax: function() { var max = this._getNumber(this._setMaximum); return (Y_Lang.isNumber(max)); }, /** * Indicates whether or not the minimum attribute has been explicitly set. * * @method _getSetMin * @return Boolean * @private */ _getSetMin: function() { var min = this._getNumber(this._setMinimum); return (Y_Lang.isNumber(min)); }, /** * Formats a label based on the axis type and optionally specified format. * * @method formatLabel * @param {Object} value * @param {Object} format Pattern used to format the value. * @return String */ formatLabel: function(val, format) { val = Y.DataType.Date.parse(val); if(format) { return Y.DataType.Date.format(val, {format:format}); } return val; }, /** * Constant used to generate unique id. * * @property GUID * @type String * @private */ GUID: "yuitimeaxis", /** * Type of data used in `Axis`. * * @property _dataType * @readOnly * @private */ _dataType: "time", /** * Gets an array of values based on a key. * * @method _getKeyArray * @param {String} key Value key associated with the data array. * @param {Array} data Array in which the data resides. * @return Array * @private */ _getKeyArray: function(key, data) { var obj, keyArray = [], i = 0, val, len = data.length; for(; i < len; ++i) { obj = data[i][key]; if(Y_Lang.isDate(obj)) { val = obj.valueOf(); } else { val = new Date(obj); if(Y_Lang.isDate(val)) { val = val.valueOf(); } else if(!Y_Lang.isNumber(obj)) { if(Y_Lang.isNumber(parseFloat(obj))) { val = parseFloat(obj); } else { if(typeof obj !== "string") { obj = obj; } val = new Date(obj).valueOf(); } } else { val = obj; } } keyArray[i] = val; } return keyArray; }, /** * Calculates the maximum and minimum values for the `Axis`. * * @method _updateMinAndMax * @private */ _updateMinAndMax: function() { var data = this.get("data"), max = 0, min = 0, len, num, i; if(data && data.length && data.length > 0) { len = data.length; max = min = data[0]; if(len > 1) { for(i = 1; i < len; i++) { num = data[i]; if(isNaN(num)) { continue; } max = Math.max(num, max); min = Math.min(num, min); } } } this._dataMaximum = max; this._dataMinimum = min; }, /** * Returns a coordinate corresponding to a data values. * * @method _getCoordFromValue * @param {Number} min The minimum for the axis. * @param {Number} max The maximum for the axis. * @param {Number} length The distance that the axis spans. * @param {Number} dataValue A value used to ascertain the coordinate. * @param {Number} offset Value in which to offset the coordinates. * @param {Boolean} reverse Indicates whether the coordinates should start from * the end of an axis. Only used in the numeric implementation. * @return Number * @private */ _getCoordFromValue: function(min, max, length, dataValue, offset) { var range, multiplier, valuecoord, isNumber = Y_Lang.isNumber; dataValue = this._getNumber(dataValue); if(isNumber(dataValue)) { range = max - min; multiplier = length/range; valuecoord = (dataValue - min) * multiplier; valuecoord = offset + valuecoord; } else { valuecoord = NaN; } return valuecoord; }, /** * Parses value into a number. * * @method _getNumber * @param val {Object} Value to parse into a number * @return Number * @private */ _getNumber: function(val) { if(Y_Lang.isDate(val)) { val = val.valueOf(); } else if(!Y_Lang.isNumber(val) && val) { val = new Date(val).valueOf(); } return val; } }; Y.TimeImpl = TimeImpl; /** * TimeAxisBase manages time data for an axis. * * @class TimeAxisBase * @extends AxisBase * @uses TimeImpl * @constructor * @param {Object} config (optional) Configuration parameters. * @submodule axis-time-base */ Y.TimeAxisBase = Y.Base.create("timeAxisBase", Y.AxisBase, [Y.TimeImpl]); }, '3.17.2', {"requires": ["axis-base"]});
// mgo - MongoDB driver for Go // // Copyright (c) 2014 - Gustavo Niemeyer <gustavo@niemeyer.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: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY 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. // Pacakage scram implements a SCRAM-{SHA-1,etc} client per RFC5802. // // http://tools.ietf.org/html/rfc5802 // package scram import ( "bytes" "crypto/hmac" "crypto/rand" "encoding/base64" "fmt" "hash" "strconv" "strings" ) // Client implements a SCRAM-* client (SCRAM-SHA-1, SCRAM-SHA-256, etc). // // A Client may be used within a SASL conversation with logic resembling: // // var in []byte // var client = scram.NewClient(sha1.New, user, pass) // for client.Step(in) { // out := client.Out() // // send out to server // in := serverOut // } // if client.Err() != nil { // // auth failed // } // type Client struct { newHash func() hash.Hash user string pass string step int out bytes.Buffer err error clientNonce []byte serverNonce []byte saltedPass []byte authMsg bytes.Buffer } // NewClient returns a new SCRAM-* client with the provided hash algorithm. // // For SCRAM-SHA-1, for example, use: // // client := scram.NewClient(sha1.New, user, pass) // func NewClient(newHash func() hash.Hash, user, pass string) *Client { c := &Client{ newHash: newHash, user: user, pass: pass, } c.out.Grow(256) c.authMsg.Grow(256) return c } // Out returns the data to be sent to the server in the current step. func (c *Client) Out() []byte { if c.out.Len() == 0 { return nil } return c.out.Bytes() } // Err returns the error that ocurred, or nil if there were no errors. func (c *Client) Err() error { return c.err } // SetNonce sets the client nonce to the provided value. // If not set, the nonce is generated automatically out of crypto/rand on the first step. func (c *Client) SetNonce(nonce []byte) { c.clientNonce = nonce } var escaper = strings.NewReplacer("=", "=3D", ",", "=2C") // Step processes the incoming data from the server and makes the // next round of data for the server available via Client.Out. // Step returns false if there are no errors and more data is // still expected. func (c *Client) Step(in []byte) bool { c.out.Reset() if c.step > 2 || c.err != nil { return false } c.step++ switch c.step { case 1: c.err = c.step1(in) case 2: c.err = c.step2(in) case 3: c.err = c.step3(in) } return c.step > 2 || c.err != nil } func (c *Client) step1(in []byte) error { if len(c.clientNonce) == 0 { const nonceLen = 6 buf := make([]byte, nonceLen+b64.EncodedLen(nonceLen)) if _, err := rand.Read(buf[:nonceLen]); err != nil { return fmt.Errorf("cannot read random SCRAM-SHA-1 nonce from operating system: %v", err) } c.clientNonce = buf[nonceLen:] b64.Encode(c.clientNonce, buf[:nonceLen]) } c.authMsg.WriteString("n=") escaper.WriteString(&c.authMsg, c.user) c.authMsg.WriteString(",r=") c.authMsg.Write(c.clientNonce) c.out.WriteString("n,,") c.out.Write(c.authMsg.Bytes()) return nil } var b64 = base64.StdEncoding func (c *Client) step2(in []byte) error { c.authMsg.WriteByte(',') c.authMsg.Write(in) fields := bytes.Split(in, []byte(",")) if len(fields) != 3 { return fmt.Errorf("expected 3 fields in first SCRAM-SHA-1 server message, got %d: %q", len(fields), in) } if !bytes.HasPrefix(fields[0], []byte("r=")) || len(fields[0]) < 2 { return fmt.Errorf("server sent an invalid SCRAM-SHA-1 nonce: %q", fields[0]) } if !bytes.HasPrefix(fields[1], []byte("s=")) || len(fields[1]) < 6 { return fmt.Errorf("server sent an invalid SCRAM-SHA-1 salt: %q", fields[1]) } if !bytes.HasPrefix(fields[2], []byte("i=")) || len(fields[2]) < 6 { return fmt.Errorf("server sent an invalid SCRAM-SHA-1 iteration count: %q", fields[2]) } c.serverNonce = fields[0][2:] if !bytes.HasPrefix(c.serverNonce, c.clientNonce) { return fmt.Errorf("server SCRAM-SHA-1 nonce is not prefixed by client nonce: got %q, want %q+\"...\"", c.serverNonce, c.clientNonce) } salt := make([]byte, b64.DecodedLen(len(fields[1][2:]))) n, err := b64.Decode(salt, fields[1][2:]) if err != nil { return fmt.Errorf("cannot decode SCRAM-SHA-1 salt sent by server: %q", fields[1]) } salt = salt[:n] iterCount, err := strconv.Atoi(string(fields[2][2:])) if err != nil { return fmt.Errorf("server sent an invalid SCRAM-SHA-1 iteration count: %q", fields[2]) } c.saltPassword(salt, iterCount) c.authMsg.WriteString(",c=biws,r=") c.authMsg.Write(c.serverNonce) c.out.WriteString("c=biws,r=") c.out.Write(c.serverNonce) c.out.WriteString(",p=") c.out.Write(c.clientProof()) return nil } func (c *Client) step3(in []byte) error { var isv, ise bool var fields = bytes.Split(in, []byte(",")) if len(fields) == 1 { isv = bytes.HasPrefix(fields[0], []byte("v=")) ise = bytes.HasPrefix(fields[0], []byte("e=")) } if ise { return fmt.Errorf("SCRAM-SHA-1 authentication error: %s", fields[0][2:]) } else if !isv { return fmt.Errorf("unsupported SCRAM-SHA-1 final message from server: %q", in) } if !bytes.Equal(c.serverSignature(), fields[0][2:]) { return fmt.Errorf("cannot authenticate SCRAM-SHA-1 server signature: %q", fields[0][2:]) } return nil } func (c *Client) saltPassword(salt []byte, iterCount int) { mac := hmac.New(c.newHash, []byte(c.pass)) mac.Write(salt) mac.Write([]byte{0, 0, 0, 1}) ui := mac.Sum(nil) hi := make([]byte, len(ui)) copy(hi, ui) for i := 1; i < iterCount; i++ { mac.Reset() mac.Write(ui) mac.Sum(ui[:0]) for j, b := range ui { hi[j] ^= b } } c.saltedPass = hi } func (c *Client) clientProof() []byte { mac := hmac.New(c.newHash, c.saltedPass) mac.Write([]byte("Client Key")) clientKey := mac.Sum(nil) hash := c.newHash() hash.Write(clientKey) storedKey := hash.Sum(nil) mac = hmac.New(c.newHash, storedKey) mac.Write(c.authMsg.Bytes()) clientProof := mac.Sum(nil) for i, b := range clientKey { clientProof[i] ^= b } clientProof64 := make([]byte, b64.EncodedLen(len(clientProof))) b64.Encode(clientProof64, clientProof) return clientProof64 } func (c *Client) serverSignature() []byte { mac := hmac.New(c.newHash, c.saltedPass) mac.Write([]byte("Server Key")) serverKey := mac.Sum(nil) mac = hmac.New(c.newHash, serverKey) mac.Write(c.authMsg.Bytes()) serverSignature := mac.Sum(nil) encoded := make([]byte, b64.EncodedLen(len(serverSignature))) b64.Encode(encoded, serverSignature) return encoded }
def tail(log_file) cursor = File.size(log_file) last_checked = Time.now tail_thread = Thread.new do File.open(log_file, 'r') do |f| loop do f.seek cursor if f.mtime > last_checked last_checked = f.mtime contents = f.read cursor += contents.length print contents end sleep 1 end end end tail_thread end
module Timers VERSION = "4.0.1" end
<!DOCTYPE html> <title>Custom Elements: create an element inside a template </title> <link rel="help" href="https://dom.spec.whatwg.org/#concept-create-element"> <script src="../../resources/testharness.js"></script> <script src="../../resources/testharnessreport.js"></script> <script src="resources/custom-elements-helpers.js"></script> <iframe id="iframe"></iframe> <script> 'use strict'; iframe.srcdoc = `<template id="test"><a-a></a-a></template>`; setup({ explicit_done: true }); iframe.onload = () => { let doc = iframe.contentDocument; let w = doc.defaultView; let tmpl = doc.querySelector('#test'); let element = tmpl.content.querySelector('a-a'); w.customElements.define('a-a', class extends w.HTMLElement {}); test(function () { assert_true(element.matches(':not(:defined)')); assert_true(element instanceof w.HTMLElement); }, 'Custom element state in template content should be "not defined"'); done(); }; </script>
{% if ISSO_SITEURL %} <script data-isso="{{ ISSO_SITEURL }}/" src="{{ ISSO_SITEURL }}/js/embed.min.js"></script> {% endif %}
/* gtkcellareacontext.h * * Copyright (C) 2010 Openismus GmbH * * Authors: * Tristan Van Berkom <tristanvb@openismus.com> * * 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, see <http://www.gnu.org/licenses/>. */ #ifndef __GTK_CELL_AREA_CONTEXT_H__ #define __GTK_CELL_AREA_CONTEXT_H__ #if !defined (__GTK_H_INSIDE__) && !defined (GTK_COMPILATION) #error "Only <gtk/gtk.h> can be included directly." #endif #include <gtk/gtkcellarea.h> G_BEGIN_DECLS #define GTK_TYPE_CELL_AREA_CONTEXT (gtk_cell_area_context_get_type ()) #define GTK_CELL_AREA_CONTEXT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_CELL_AREA_CONTEXT, GtkCellAreaContext)) #define GTK_CELL_AREA_CONTEXT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_CELL_AREA_CONTEXT, GtkCellAreaContextClass)) #define GTK_IS_CELL_AREA_CONTEXT(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_CELL_AREA_CONTEXT)) #define GTK_IS_CELL_AREA_CONTEXT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_CELL_AREA_CONTEXT)) #define GTK_CELL_AREA_CONTEXT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_CELL_AREA_CONTEXT, GtkCellAreaContextClass)) typedef struct _GtkCellAreaContextPrivate GtkCellAreaContextPrivate; typedef struct _GtkCellAreaContextClass GtkCellAreaContextClass; struct _GtkCellAreaContext { /*< private >*/ GObject parent_instance; GtkCellAreaContextPrivate *priv; }; /** * GtkCellAreaContextClass: * @allocate: This tells the context that an allocation width or height * (or both) have been decided for a group of rows. The context should * store any allocations for internally aligned cells at this point so * that they dont need to be recalculated at gtk_cell_area_render() time. * @reset: Clear any previously stored information about requested and * allocated sizes for the context. * @get_preferred_height_for_width: Returns the aligned height for the given * width that context must store while collecting sizes for it’s rows. * @get_preferred_width_for_height: Returns the aligned width for the given * height that context must store while collecting sizes for it’s rows. */ struct _GtkCellAreaContextClass { /*< private >*/ GObjectClass parent_class; /*< public >*/ void (* allocate) (GtkCellAreaContext *context, gint width, gint height); void (* reset) (GtkCellAreaContext *context); void (* get_preferred_height_for_width) (GtkCellAreaContext *context, gint width, gint *minimum_height, gint *natural_height); void (* get_preferred_width_for_height) (GtkCellAreaContext *context, gint height, gint *minimum_width, gint *natural_width); /*< private >*/ /* Padding for future expansion */ void (*_gtk_reserved1) (void); void (*_gtk_reserved2) (void); void (*_gtk_reserved3) (void); void (*_gtk_reserved4) (void); void (*_gtk_reserved5) (void); void (*_gtk_reserved6) (void); }; GDK_AVAILABLE_IN_ALL GType gtk_cell_area_context_get_type (void) G_GNUC_CONST; /* Main apis */ GDK_AVAILABLE_IN_ALL GtkCellArea *gtk_cell_area_context_get_area (GtkCellAreaContext *context); GDK_AVAILABLE_IN_ALL void gtk_cell_area_context_allocate (GtkCellAreaContext *context, gint width, gint height); GDK_AVAILABLE_IN_ALL void gtk_cell_area_context_reset (GtkCellAreaContext *context); /* Apis for GtkCellArea clients to consult cached values * for a series of GtkTreeModel rows */ GDK_AVAILABLE_IN_ALL void gtk_cell_area_context_get_preferred_width (GtkCellAreaContext *context, gint *minimum_width, gint *natural_width); GDK_AVAILABLE_IN_ALL void gtk_cell_area_context_get_preferred_height (GtkCellAreaContext *context, gint *minimum_height, gint *natural_height); GDK_AVAILABLE_IN_ALL void gtk_cell_area_context_get_preferred_height_for_width (GtkCellAreaContext *context, gint width, gint *minimum_height, gint *natural_height); GDK_AVAILABLE_IN_ALL void gtk_cell_area_context_get_preferred_width_for_height (GtkCellAreaContext *context, gint height, gint *minimum_width, gint *natural_width); GDK_AVAILABLE_IN_ALL void gtk_cell_area_context_get_allocation (GtkCellAreaContext *context, gint *width, gint *height); /* Apis for GtkCellArea implementations to update cached values * for multiple GtkTreeModel rows */ GDK_AVAILABLE_IN_ALL void gtk_cell_area_context_push_preferred_width (GtkCellAreaContext *context, gint minimum_width, gint natural_width); GDK_AVAILABLE_IN_ALL void gtk_cell_area_context_push_preferred_height (GtkCellAreaContext *context, gint minimum_height, gint natural_height); G_END_DECLS #endif /* __GTK_CELL_AREA_CONTEXT_H__ */