code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
<!DOCTYPE html>
<html>
<style>
div {
border-color: green;
border-style: solid;
border-width: 3px 10px;
}
</style>
<div>This text should have top and bottom borders of 3px and left and right borders of 10px</div>
</html>
| lordmos/blink | LayoutTests/fast/css/variables/calc-expected.html | HTML | mit | 232 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<link href="lib/mocha.css" rel="stylesheet" />
</head>
<body>
<div id="mocha"></div>
<script src="http://localhost:8889/socket.io/socket.io.js"></script>
<script src="lib/mocha.js"></script>
<script data-main="integration.js" src="lib/require.js"></script>
</body>
</html> | klorenz/tcp-socket | test/integration/ws/integration.html | HTML | mit | 395 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18408
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GroupDocsViewerVisualStudioPlugin.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| aliahmedgroupdocs/GroupDocs.Viewer-for-.NET | Plugins/GroupDocs_Viewer_VSPlugin/GroupDocs.Viewer.VisualStudioPlugin/GroupDocsVisualStudioPlugin/Properties/Settings.Designer.cs | C# | mit | 1,090 |
using System.Drawing;
namespace JR.DevFw.Framework.Graphic
{
/// <summary>
/// 绘图处理
/// </summary>
/// <param name="img"></param>
public delegate void ImageGraphicsHandler(Image img);
} | jrsix/devfw | src/core/J6.DevFw.Core/Framework/Graphic/ImageGraphicsHandler.cs | C# | mit | 217 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ClassLibrary.net46")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ClassLibrary.net46")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("10339478-bb59-4ef8-8b0e-8f38cf30a78a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mmitche/xunit-performance | samples/ClassLibrary.net46/Properties/AssemblyInfo.cs | C# | mit | 1,412 |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Sql
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SyncGroupsOperations operations.
/// </summary>
internal partial class SyncGroupsOperations : IServiceOperations<SqlManagementClient>, ISyncGroupsOperations
{
/// <summary>
/// Initializes a new instance of the SyncGroupsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SyncGroupsOperations(SqlManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SqlManagementClient
/// </summary>
public SqlManagementClient Client { get; private set; }
/// <summary>
/// Gets a collection of sync database ids.
/// </summary>
/// <param name='locationName'>
/// The name of the region where the resource is located.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SyncDatabaseIdProperties>>> ListSyncDatabaseIdsWithHttpMessagesAsync(string locationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (locationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "locationName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("locationName", locationName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListSyncDatabaseIds", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationName}/syncDatabaseIds").ToString();
_url = _url.Replace("{locationName}", System.Uri.EscapeDataString(locationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SyncDatabaseIdProperties>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<SyncDatabaseIdProperties>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Refreshes a hub database schema.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> RefreshHubSchemaWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginRefreshHubSchemaWithHttpMessagesAsync(resourceGroupName, serverName, databaseName, syncGroupName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a collection of hub database schemas.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SyncFullSchemaProperties>>> ListHubSchemasWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (syncGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "syncGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("syncGroupName", syncGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListHubSchemas", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/syncGroups/{syncGroupName}/hubSchemas").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{syncGroupName}", System.Uri.EscapeDataString(syncGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SyncFullSchemaProperties>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<SyncFullSchemaProperties>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a collection of sync group logs.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='startTime'>
/// Get logs generated after this time.
/// </param>
/// <param name='endTime'>
/// Get logs generated before this time.
/// </param>
/// <param name='type'>
/// The types of logs to retrieve. Possible values include: 'All', 'Error',
/// 'Warning', 'Success'
/// </param>
/// <param name='continuationToken'>
/// The continuation token for this operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SyncGroupLogProperties>>> ListLogsWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, string startTime, string endTime, string type, string continuationToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (syncGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "syncGroupName");
}
if (startTime == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "startTime");
}
if (endTime == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endTime");
}
if (type == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "type");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("syncGroupName", syncGroupName);
tracingParameters.Add("startTime", startTime);
tracingParameters.Add("endTime", endTime);
tracingParameters.Add("type", type);
tracingParameters.Add("continuationToken", continuationToken);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListLogs", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/syncGroups/{syncGroupName}/logs").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{syncGroupName}", System.Uri.EscapeDataString(syncGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (startTime != null)
{
_queryParameters.Add(string.Format("startTime={0}", System.Uri.EscapeDataString(startTime)));
}
if (endTime != null)
{
_queryParameters.Add(string.Format("endTime={0}", System.Uri.EscapeDataString(endTime)));
}
if (type != null)
{
_queryParameters.Add(string.Format("type={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(type, Client.SerializationSettings).Trim('"'))));
}
if (continuationToken != null)
{
_queryParameters.Add(string.Format("continuationToken={0}", System.Uri.EscapeDataString(continuationToken)));
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SyncGroupLogProperties>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<SyncGroupLogProperties>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Cancels a sync group synchronization.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> CancelSyncWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (syncGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "syncGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("syncGroupName", syncGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CancelSync", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/syncGroups/{syncGroupName}/cancelSync").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{syncGroupName}", System.Uri.EscapeDataString(syncGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Triggers a sync group synchronization.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> TriggerSyncWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (syncGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "syncGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("syncGroupName", syncGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "TriggerSync", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/syncGroups/{syncGroupName}/triggerSync").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{syncGroupName}", System.Uri.EscapeDataString(syncGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a sync group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SyncGroup>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (syncGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "syncGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("syncGroupName", syncGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/syncGroups/{syncGroupName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{syncGroupName}", System.Uri.EscapeDataString(syncGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SyncGroup>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SyncGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a sync group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='parameters'>
/// The requested sync group resource state.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<SyncGroup>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, SyncGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<SyncGroup> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, databaseName, syncGroupName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes a sync group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, serverName, databaseName, syncGroupName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a sync group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='parameters'>
/// The requested sync group resource state.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<SyncGroup>> UpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, SyncGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<SyncGroup> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, serverName, databaseName, syncGroupName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Lists sync groups under a hub database.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SyncGroup>>> ListByDatabaseWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByDatabase", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/syncGroups").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SyncGroup>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<SyncGroup>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Refreshes a hub database schema.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginRefreshHubSchemaWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (syncGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "syncGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("syncGroupName", syncGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginRefreshHubSchema", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/syncGroups/{syncGroupName}/refreshHubSchema").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{syncGroupName}", System.Uri.EscapeDataString(syncGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a sync group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='parameters'>
/// The requested sync group resource state.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SyncGroup>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, SyncGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (syncGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "syncGroupName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("syncGroupName", syncGroupName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/syncGroups/{syncGroupName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{syncGroupName}", System.Uri.EscapeDataString(syncGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SyncGroup>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SyncGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SyncGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a sync group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (syncGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "syncGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("syncGroupName", syncGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/syncGroups/{syncGroupName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{syncGroupName}", System.Uri.EscapeDataString(syncGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates a sync group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database on which the sync group is hosted.
/// </param>
/// <param name='syncGroupName'>
/// The name of the sync group.
/// </param>
/// <param name='parameters'>
/// The requested sync group resource state.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SyncGroup>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, SyncGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (syncGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "syncGroupName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("syncGroupName", syncGroupName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/syncGroups/{syncGroupName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{syncGroupName}", System.Uri.EscapeDataString(syncGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SyncGroup>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SyncGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a collection of sync database ids.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SyncDatabaseIdProperties>>> ListSyncDatabaseIdsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListSyncDatabaseIdsNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SyncDatabaseIdProperties>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<SyncDatabaseIdProperties>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a collection of hub database schemas.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SyncFullSchemaProperties>>> ListHubSchemasNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListHubSchemasNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SyncFullSchemaProperties>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<SyncFullSchemaProperties>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a collection of sync group logs.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SyncGroupLogProperties>>> ListLogsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListLogsNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SyncGroupLogProperties>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<SyncGroupLogProperties>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists sync groups under a hub database.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SyncGroup>>> ListByDatabaseNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByDatabaseNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SyncGroup>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<SyncGroup>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| shahabhijeet/azure-sdk-for-net | src/SDKs/SqlManagement/Management.Sql/Generated/SyncGroupsOperations.cs | C# | mit | 150,170 |
using System;
using Xunit;
namespace HealthMonitoring.AcceptanceTests.Helpers
{
static class CustomAssertions
{
public static void EqualNotStrict(string first, string second)
{
bool equal = string.Equals(first, second, StringComparison.CurrentCultureIgnoreCase);
Assert.True(equal, $"{first} != {second}");
}
}
}
| wongatech/HealthMonitoring | HealthMonitoring.AcceptanceTests/Helpers/CusomAssertions.cs | C# | mit | 377 |
export default class ModelAccessor {
constructor() {
this.value = 10
}
get highCount() {
return this.value + 100
}
set highCount(v) {
this.value = v - 100
}
get doubleHigh() {
return this.highCount * 2
}
incr() {
this.value++
}
}
| nekronos/fuselibs-public | Source/Fuse.Models/Tests/UX/Accessor.js | JavaScript | mit | 255 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Preface</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.62.4" />
<link rel="home" href="index.html" title="Porting Berkeley DB" />
<link rel="up" href="index.html" title="Porting Berkeley DB" />
<link rel="previous" href="index.html" title="Porting Berkeley DB" />
<link rel="next" href="introduction.html" title="Chapter 1. Introduction to Porting Berkeley DB " />
</head>
<body>
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Preface</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="index.html">Prev</a> </td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="introduction.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="preface" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="preface"></a>Preface</h2>
</div>
</div>
<div></div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="preface.html#conventions">Conventions Used in this Book</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="preface.html#audience">Audience</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="preface.html#moreinfo">For More Information</a>
</span>
</dt>
</dl>
</dd>
</dl>
</div>
<p>
The Berkeley DB family of open source, embeddable databases
provides developers with fast, reliable persistence with zero
administration. Often deployed as "edge" databases, the Berkeley DB
family provides very high performance, reliability, scalability,
and availability for application use cases that do not require SQL.
</p>
<p>
As an open source database, Berkeley DB works on many different
platforms, from Wind River's Tornado system, to VMS, to
Windows NT and Windows 95, and most existing UNIX
platforms. It runs on 32 and 64-bit machines, little or big-endian.
</p>
<p>
<span class="emphasis"><em>Berkeley DB Porting Guide</em></span> provides the information you need to
port Berkeley DB to additional platforms.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="conventions"></a>Conventions Used in this Book</h2>
</div>
</div>
<div></div>
</div>
<p>
The following typographical conventions are used within in this manual:
</p>
<p>
Structure names are represented in <tt class="classname">monospaced font</tt>, as are <tt class="methodname">method
names</tt>. For example: "<tt class="methodname">DB->open()</tt> is a method
on a <tt class="classname">DB</tt> handle."
</p>
<p>
Variable or non-literal text is presented in <span class="emphasis"><em>italics</em></span>. For example: "Go to your
<span class="emphasis"><em>DB_INSTALL</em></span>
directory."
</p>
<p>
Program examples are displayed in a <tt class="classname">monospaced font</tt> on a shaded background.
For example:
</p>
<pre class="programlisting">/* File: gettingstarted_common.h */
typedef struct stock_dbs {
DB *inventory_dbp; /* Database containing inventory information */
DB *vendor_dbp; /* Database containing vendor information */
char *db_home_dir; /* Directory containing the database files */
char *inventory_db_name; /* Name of the inventory database */
char *vendor_db_name; /* Name of the vendor database */
} STOCK_DBS; </pre>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
Finally, notes of interest are represented using a note block such
as this.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="audience"></a>Audience</h3>
</div>
</div>
<div></div>
</div>
<p>
This guide is intended
for programmers porting Berkeley DB to a new platform. It
assumes that these programmers possess:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
Familiarity with standard ANSI C and POSIX C 1003.1 and 1003.2 library and system
calls.
</p>
</li>
<li>
<p>
Working knowledge of the target platform as well as the development tools (for example, compilers, linkers, and debuggers) available on that platform.
</p>
</li>
</ul>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="moreinfo"></a>For More Information</h3>
</div>
</div>
<div></div>
</div>
<p>
Beyond this manual, you may also find the following sources of information useful when building a
DB application:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<a href="http://www.oracle.com/technology/documentation/berkeley-db/db/gsg/C/index.html" target="_top">
Getting Started with Berkeley DB for C
</a>
</p>
</li>
<li>
<p>
<a href="http://www.oracle.com/technology/documentation/berkeley-db/db/gsg_txn/C/index.html" target="_top">
Getting Started with Transaction Processing for C
</a>
</p>
</li>
<li>
<p>
<a href="http://www.oracle.com/technology/documentation/berkeley-db/db/gsg_db_rep/C/index.html" target="_top">
Berkeley DB Getting Started with Replicated Applications for C
</a>
</p>
</li>
<li>
<p>
<a href="http://www.oracle.com/technology/documentation/berkeley-db/db/ref/toc.html" target="_top">
Berkeley DB Programmer's Reference Guide
</a>
</p>
</li>
<li>
<p>
<a href="http://www.oracle.com/technology/documentation/berkeley-db/db/api_c/frame.html" target="_top">
Berkeley DB C API
</a>
</p>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="index.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="index.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="introduction.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Porting Berkeley DB </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 1. Introduction to Porting Berkeley DB </td>
</tr>
</table>
</div>
</body>
</html>
| djsedulous/namecoind | libs/db-4.7.25.NC/docs/porting/preface.html | HTML | mit | 8,808 |
//
// UIBarItem+CASAdditions.h
//
//
// Created by Jonas Budelmann on 5/11/13.
//
//
#import <UIKit/UIKit.h>
#import "CASStyleableItem.h"
@interface UIBarItem (CASAdditions) <CASStyleableItem>
+ (void)bootstrapClassy;
@property (nonatomic, weak, readwrite) id<CASStyleableItem> cas_parent;
@end
| sudeepsidhu/Classy | Classy/Additions/UIBarItem+CASAdditions.h | C | mit | 302 |
<?php
namespace Oro\Bundle\UIBundle\Tests\Unit\Twig;
use Symfony\Component\HttpFoundation\Request;
use Oro\Bundle\UIBundle\Twig\UrlExtension;
class UrlExtensionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var UrlExtension
*/
protected $extension;
protected function setUp()
{
$this->extension = new UrlExtension();
}
public function testGetName()
{
$this->assertEquals(UrlExtension::NAME, $this->extension->getName());
}
public function testGetFunctions()
{
$functions = $this->extension->getFunctions();
$this->assertCount(1, $functions);
/** @var \Twig_SimpleFunction $function */
$function = current($functions);
$this->assertInstanceOf('\Twig_SimpleFunction', $function);
$this->assertEquals('oro_url_add_query', $function->getName());
$this->assertEquals([$this->extension, 'addQuery'], $function->getCallable());
}
/**
* @param string $expected
* @param string $source
* @param array|null $query
* @dataProvider addQueryDataProvider
*/
public function testAddQuery($expected, $source, array $query = null)
{
if (null !== $query) {
$request = new Request($query);
$this->extension->setRequest($request);
}
$this->assertEquals($expected, $this->extension->addQuery($source));
}
/**
* @return array
*/
public function addQueryDataProvider()
{
return [
'no request' => [
'expected' => 'http://test.url/',
'source' => 'http://test.url/',
],
'no query params' => [
'expected' => 'http://test.url/',
'source' => 'http://test.url/',
'query' => [],
],
'no query params without host' => [
'expected' => '/',
'source' => '/',
'query' => [],
],
'same query params' => [
'expected' => 'http://test.url/?foo=1#bar',
'source' => 'http://test.url/?foo=1#bar',
'query' => ['foo' => 1],
],
'same query params without host' => [
'expected' => '/?foo=1#bar',
'source' => '/?foo=1#bar',
'query' => ['foo' => 1],
],
'only new query params' => [
'expected' => 'http://test.url/?foo=1#bar',
'source' => 'http://test.url/#bar',
'query' => ['foo' => 1],
],
'only new query params without host' => [
'expected' => '/?foo=1#bar',
'source' => '/#bar',
'query' => ['foo' => 1],
],
'existing and new query params' => [
'expected' => 'http://test.url/?baz=2&foo=1#bar',
'source' => 'http://test.url/?foo=1#bar',
'query' => ['baz' => 2],
],
'existing and new query params without host' => [
'expected' => '/?baz=2&foo=1#bar',
'source' => '/?foo=1#bar',
'query' => ['baz' => 2],
],
'existing and new query params without host with path' => [
'expected' => '/path/?baz=2&foo=1#bar',
'source' => '/path/?foo=1#bar',
'query' => ['baz' => 2],
],
'existing and new query params without host with short path' => [
'expected' => '/path?baz=2&foo=1#bar',
'source' => '/path?foo=1#bar',
'query' => ['baz' => 2],
],
];
}
}
| northdakota/platform | src/Oro/Bundle/UIBundle/Tests/Unit/Twig/UrlExtensionTest.php | PHP | mit | 3,786 |
//
// REComposeViewController.h
// REComposeViewController
//
// Copyright (c) 2013 Roman Efimov (https://github.com/romaonthego)
//
// 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.
//
#import <UIKit/UIKit.h>
#import "RECommonFunctions.h"
#import "REComposeSheetView.h"
#import "REComposeBackgroundView.h"
@class REComposeViewController;
typedef enum _REComposeResult {
REComposeResultCancelled,
REComposeResultPosted
} REComposeResult;
typedef void (^REComposeViewControllerCompletionHandler)(REComposeViewController *composeViewController, REComposeResult result);
@protocol REComposeViewControllerDelegate;
@interface REComposeViewController : UIViewController <REComposeSheetViewDelegate> {
REComposeSheetView *_sheetView;
REComposeBackgroundView *_backgroundView;
UIView *_backView;
UIView *_containerView;
UIImageView *_paperclipView;
}
@property (copy, readwrite, nonatomic) REComposeViewControllerCompletionHandler completionHandler;
@property (weak, readwrite, nonatomic) id<REComposeViewControllerDelegate> delegate;
@property (assign, readwrite, nonatomic) NSInteger cornerRadius;
@property (assign, readwrite, nonatomic) BOOL hasAttachment;
@property (assign, readonly, nonatomic) BOOL userUpdatedAttachment;
@property (strong, readwrite, nonatomic) NSString *text;
@property (strong, readwrite, nonatomic) NSString *placeholderText;
@property (strong, readonly, nonatomic) UINavigationBar *navigationBar;
@property (strong, readonly, nonatomic) UINavigationItem *navigationItem;
@property (strong, readwrite, nonatomic) UIColor *tintColor;
@property (strong, readwrite, nonatomic) UIImage *attachmentImage;
@property (weak, readonly, nonatomic) UIViewController *rootViewController;
- (void)presentFromRootViewController;
- (void)presentFromViewController:(UIViewController *)controller;
@end
@protocol REComposeViewControllerDelegate <NSObject>
- (void)composeViewController:(REComposeViewController *)composeViewController didFinishWithResult:(REComposeResult)result;
@end
| voyage11/SLComposeViewControllerWithBlackKeyboard | REComposeViewController/REComposeViewController.h | C | mit | 3,051 |
require 'spec_helper'
describe "Callback on Notice" do
describe "email notifications (configured individually for each app)" do
custom_thresholds = [2, 4, 8, 16, 32, 64]
before do
Errbit::Config.per_app_email_at_notices = true
@app = Fabricate(:app_with_watcher, :email_at_notices => custom_thresholds)
@problem = Fabricate(:problem, :app => @app)
end
after do
Errbit::Config.per_app_email_at_notices = false
end
custom_thresholds.each do |threshold|
it "sends an email notification after #{threshold} notice(s)" do
allow_any_instance_of(Problem).to receive(:notices_count).and_return(threshold)
expect(Mailer).to receive(:err_notification).
and_return(double('email', :deliver => true))
Fabricate(:notice, :problem => @problem)
end
end
end
describe "email notifications for a resolved issue" do
before do
Errbit::Config.per_app_email_at_notices = true
@app = Fabricate(:app_with_watcher, :email_at_notices => [1])
@problem = Fabricate(:problem, :app => @app, :notices_count => 100)
end
after do
Errbit::Config.per_app_email_at_notices = false
end
it "should send email notification after 1 notice since an error has been resolved" do
@problem.resolve!
expect(Mailer).to receive(:err_notification).and_return(double('email', :deliver => true))
Fabricate(:notice, :problem => @problem)
end
end
describe "should send a notification if a notification service is configured with defaults" do
let(:app) { Fabricate(:app, :email_at_notices => [1], :notification_service => Fabricate(:campfire_notification_service))}
let(:problem) { Fabricate(:problem, :app => app, :notices_count => 100) }
let(:backtrace) { Fabricate(:backtrace) }
before do
Errbit::Config.per_app_email_at_notices = true
end
after do
Errbit::Config.per_app_email_at_notices = false
end
it "should create a campfire notification" do
expect_any_instance_of(app.notification_service.class).to receive(:create_notification)
Notice.create!(:problem => problem, :message => 'FooError: Too Much Bar', :server_environment => {'environment-name' => 'production'},
:backtrace => backtrace, :notifier => { 'name' => 'Notifier', 'version' => '1', 'url' => 'http://toad.com' })
end
end
describe "should not send a notification if a notification service is not configured" do
let(:app) { Fabricate(:app, :email_at_notices => [1], :notification_service => Fabricate(:notification_service))}
let(:problem) { Fabricate(:problem, :app => app, :notices_count => 100) }
let(:backtrace) { Fabricate(:backtrace) }
before do
Errbit::Config.per_app_email_at_notices = true
end
after do
Errbit::Config.per_app_email_at_notices = false
end
it "should not create a campfire notification" do
expect_any_instance_of(app.notification_service.class).to_not receive(:create_notification)
Notice.create!(:problem => problem, :message => 'FooError: Too Much Bar', :server_environment => {'environment-name' => 'production'},
:backtrace => backtrace, :notifier => { 'name' => 'Notifier', 'version' => '1', 'url' => 'http://toad.com' })
end
end
describe 'hipcat notifications' do
let(:app) { Fabricate(:app, :email_at_notices => [1], :notification_service => Fabricate(:hipchat_notification_service))}
let(:problem) { Fabricate(:problem, :app => app, :notices_count => 100) }
before do
Errbit::Config.per_app_email_at_notices = true
end
after do
Errbit::Config.per_app_email_at_notices = false
end
it 'creates a hipchat notification' do
expect_any_instance_of(app.notification_service.class).to receive(:create_notification)
Fabricate(:notice, :problem => problem)
end
end
describe "should send a notification at desired intervals" do
let(:app) { Fabricate(:app, :email_at_notices => [1], :notification_service => Fabricate(:campfire_notification_service, :notify_at_notices => [1,2]))}
let(:backtrace) { Fabricate(:backtrace) }
before do
Errbit::Config.per_app_email_at_notices = true
end
after do
Errbit::Config.per_app_email_at_notices = false
end
it "should create a campfire notification on first notice" do
problem = Fabricate(:problem, :app => app, :notices_count => 1)
expect_any_instance_of(app.notification_service.class).to receive(:create_notification)
Notice.create!(:problem => problem, :message => 'FooError: Too Much Bar', :server_environment => {'environment-name' => 'production'},
:backtrace => backtrace, :notifier => { 'name' => 'Notifier', 'version' => '1', 'url' => 'http://toad.com' })
end
it "should create a campfire notification on second notice" do
problem = Fabricate(:problem, :app => app, :notices_count => 1)
expect_any_instance_of(app.notification_service.class).to receive(:create_notification)
Notice.create!(:problem => problem, :message => 'FooError: Too Much Bar', :server_environment => {'environment-name' => 'production'},
:backtrace => backtrace, :notifier => { 'name' => 'Notifier', 'version' => '1', 'url' => 'http://toad.com' })
end
it "should not create a campfire notification on third notice" do
problem = Fabricate(:problem, :app => app, :notices_count => 1)
expect_any_instance_of(app.notification_service.class).to receive(:create_notification)
Notice.create!(:problem => problem, :message => 'FooError: Too Much Bar', :server_environment => {'environment-name' => 'production'},
:backtrace => backtrace, :notifier => { 'name' => 'Notifier', 'version' => '1', 'url' => 'http://toad.com' })
end
end
end
| denyago/errbit | spec/observers/notice_observer_spec.rb | Ruby | mit | 5,895 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>BoostBook element using-class</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../reference.html" title="Reference">
<link rel="prev" href="paramtype.html" title="BoostBook element paramtype">
<link rel="next" href="run-test.html" title="BoostBook element run-test">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="paramtype.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="run-test.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boostbook.dtd.using-class"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">
BoostBook element <code class="sgmltag-element">using-class</code></span></h2>
<p>using-class — Injects the method and function names of a class into the local scope</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv">using-class ::=
EMPTY
</div>
<div class="refsection">
<a name="idp209879776"></a><h2>Attributes</h2>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
<col>
<col>
</colgroup>
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Value</th>
<th>Purpose</th>
</tr></thead>
<tbody>
<tr>
<td>last-revision</td>
<td>#IMPLIED</td>
<td>CDATA</td>
<td>Set to $Date: 2009-10-10 15:53:46 +0100 (Sat, 10 Oct 2009) $ to keep "last revised" information in sync with CVS changes</td>
</tr>
<tr>
<td>name</td>
<td>#REQUIRED</td>
<td>CDATA</td>
<td>The name of the element being declared to referenced</td>
</tr>
<tr>
<td>id</td>
<td>#IMPLIED</td>
<td>CDATA</td>
<td>A global identifier for this element</td>
</tr>
<tr>
<td>xml:base</td>
<td>#IMPLIED</td>
<td>CDATA</td>
<td>Implementation detail used by XIncludes</td>
</tr>
</tbody>
</table></div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2005 Douglas Gregor<p>Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
<a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>).
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="paramtype.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="run-test.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mxrrow/zaicoin | src/deps/boost/doc/html/boostbook/dtd/using-class.html | HTML | mit | 4,014 |
namespace AngleSharp.Dom
{
using AngleSharp.Attributes;
using System;
/// <summary>
/// The Range interface represents a fragment of a document that can
/// contain nodes and parts of text nodes in a given document.
/// </summary>
[DomName("Range")]
public interface IRange
{
/// <summary>
/// Gets the node that starts the container.
/// </summary>
[DomName("startContainer")]
INode Head { get; }
/// <summary>
/// Gets the offset of the StartContainer in the document.
/// </summary>
[DomName("startOffset")]
Int32 Start { get; }
/// <summary>
/// Gets the node that ends the container.
/// </summary>
[DomName("endContainer")]
INode Tail { get; }
/// <summary>
/// Gets the offset of the EndContainer in the document.
/// </summary>
[DomName("endOffset")]
Int32 End { get; }
/// <summary>
/// Gets a value that indicates if the representation is collapsed.
/// </summary>
[DomName("collapsed")]
Boolean IsCollapsed { get; }
/// <summary>
/// Gets the common ancestor node of the contained range.
/// </summary>
[DomName("commonAncestorContainer")]
INode CommonAncestor { get; }
/// <summary>
/// Selects the start of the given range by using the given reference
/// node and a relative offset.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
/// <param name="offset">
/// The offset relative to the reference node.
/// </param>
[DomName("setStart")]
void StartWith(INode refNode, Int32 offset);
/// <summary>
/// Selects the end of the given range by using the given reference
/// node and a relative offset.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
/// <param name="offset">
/// The offset relative to the reference node.
/// </param>
[DomName("setEnd")]
void EndWith(INode refNode, Int32 offset);
/// <summary>
/// Selects the start of the given range by using an inclusive
/// reference node.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
[DomName("setStartBefore")]
void StartBefore(INode refNode);
/// <summary>
/// Selects the end of the given range by using an inclusive reference
/// node.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
[DomName("setEndBefore")]
void EndBefore(INode refNode);
/// <summary>
/// Selects the start of the given range by using an exclusive
/// reference node.
/// </summary>
/// <param name="refNode">The reference node to use.</param>
[DomName("setStartAfter")]
void StartAfter(INode refNode);
/// <summary>
/// Selects the end of the given range by using an exclusive reference
/// node.
/// </summary>
/// <param name="refNode">The referenced node.</param>
[DomName("setEndAfter")]
void EndAfter(INode refNode);
/// <summary>
/// Collapses the range to a single level.
/// </summary>
/// <param name="toStart">
/// Determines if only the first level should be selected.
/// </param>
[DomName("collapse")]
void Collapse(Boolean toStart);
/// <summary>
/// Selects the contained node.
/// </summary>
/// <param name="refNode">The node to use.</param>
[DomName("selectNode")]
void Select(INode refNode);
/// <summary>
/// Selects the contained nodes by taking a reference node as origin.
/// </summary>
/// <param name="refNode">The reference node.</param>
[DomName("selectNodeContents")]
void SelectContent(INode refNode);
/// <summary>
/// Clears the contained nodes.
/// </summary>
[DomName("deleteContents")]
void ClearContent();
/// <summary>
/// Clears the node representation and returns a document fragment with
/// the originally contained nodes.
/// </summary>
/// <returns>The document fragment containing the nodes.</returns>
[DomName("extractContents")]
IDocumentFragment ExtractContent();
/// <summary>
/// Creates a document fragement of the contained nodes.
/// </summary>
/// <returns>The created document fragment.</returns>
[DomName("cloneContents")]
IDocumentFragment CopyContent();
/// <summary>
/// Inserts a node into the range.
/// </summary>
/// <param name="node">The node to include.</param>
[DomName("insertNode")]
void Insert(INode node);
/// <summary>
/// Includes the given node with its siblings in the range.
/// </summary>
/// <param name="newParent">The range to surround.</param>
[DomName("surroundContents")]
void Surround(INode newParent);
/// <summary>
/// Creates a copy of this range.
/// </summary>
/// <returns>The copy representing the same range.</returns>
[DomName("cloneRange")]
IRange Clone();
/// <summary>
/// Detaches the range from the DOM tree.
/// </summary>
[DomName("detach")]
void Detach();
/// <summary>
/// Checks if the given node is within this range by using a offset.
/// </summary>
/// <param name="node">The node to check for.</param>
/// <param name="offset">The offset to use.</param>
/// <returns>
/// True if the point is within the range, otherwise false.
/// </returns>
[DomName("isPointInRange")]
Boolean Contains(INode node, Int32 offset);
/// <summary>
/// Compares the boundary points of the range.
/// </summary>
/// <param name="how">
/// Determines how these points should be compared.
/// </param>
/// <param name="sourceRange">
/// The range of the other boundary points.
/// </param>
/// <returns>A relative position.</returns>
[DomName("compareBoundaryPoints")]
RangePosition CompareBoundaryTo(RangeType how, IRange sourceRange);
/// <summary>
/// Compares the node to the given offset and returns the relative
/// position.
/// </summary>
/// <param name="node">The node to use.</param>
/// <param name="offset">The offset to use.</param>
/// <returns>The relative position in the range.</returns>
[DomName("comparePoint")]
RangePosition CompareTo(INode node, Int32 offset);
/// <summary>
/// Checks if the given node is contained in this range.
/// </summary>
/// <param name="node">The node to check for.</param>
/// <returns>
/// True if the node is within the range, otherwise false.
/// </returns>
[DomName("intersectsNode")]
Boolean Intersects(INode node);
}
}
| FlorianRappl/AngleSharp | src/AngleSharp/Interfaces/IRange.cs | C# | mit | 7,415 |
.PHONY: test
test: pep8 clean
@coverage report
@nosetests mining/test
@$(which gulp.js)
.PHONY: tox-test
tox-test: environment
@tox
.PHONY: environment
environment:
@pip install -r requirements_dev.txt
@pip install -r requirements.txt
@pip install numexpr==2.3
@python setup.py develop
@npm install gulp gulp-jshint
@mv mining/mining.sample.ini mining/mining.ini
.PHONY: install
install:
@python setup.py install
.PHONY: pep8
pep8:
@flake8 mining --ignore=F403,F401,F812,E128 --exclude=mining/assets
.PHONY: sdist
sdist: test
@python setup.py sdist upload
.PHONY: clean
clean:
@find ./ -name '*.pyc' -exec rm -f {} \;
@find ./ -name 'Thumbs.db' -exec rm -f {} \;
@find ./ -name '*~' -exec rm -f {} \;
| AndrzejR/mining | Makefile | Makefile | mit | 723 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using Azure.Core;
namespace Azure.ResourceManager.Network.Models
{
/// <summary> Subnet in a virtual network resource. </summary>
public partial class Subnet : SubResource
{
/// <summary> Initializes a new instance of Subnet. </summary>
public Subnet()
{
AddressPrefixes = new ChangeTrackingList<string>();
ServiceEndpoints = new ChangeTrackingList<ServiceEndpointPropertiesFormat>();
ServiceEndpointPolicies = new ChangeTrackingList<ServiceEndpointPolicy>();
PrivateEndpoints = new ChangeTrackingList<PrivateEndpoint>();
IpConfigurations = new ChangeTrackingList<IPConfiguration>();
IpConfigurationProfiles = new ChangeTrackingList<IPConfigurationProfile>();
IpAllocations = new ChangeTrackingList<SubResource>();
ResourceNavigationLinks = new ChangeTrackingList<ResourceNavigationLink>();
ServiceAssociationLinks = new ChangeTrackingList<ServiceAssociationLink>();
Delegations = new ChangeTrackingList<Delegation>();
}
/// <summary> Initializes a new instance of Subnet. </summary>
/// <param name="id"> Resource ID. </param>
/// <param name="name"> The name of the resource that is unique within a resource group. This name can be used to access the resource. </param>
/// <param name="etag"> A unique read-only string that changes whenever the resource is updated. </param>
/// <param name="addressPrefix"> The address prefix for the subnet. </param>
/// <param name="addressPrefixes"> List of address prefixes for the subnet. </param>
/// <param name="networkSecurityGroup"> The reference to the NetworkSecurityGroup resource. </param>
/// <param name="routeTable"> The reference to the RouteTable resource. </param>
/// <param name="natGateway"> Nat gateway associated with this subnet. </param>
/// <param name="serviceEndpoints"> An array of service endpoints. </param>
/// <param name="serviceEndpointPolicies"> An array of service endpoint policies. </param>
/// <param name="privateEndpoints"> An array of references to private endpoints. </param>
/// <param name="ipConfigurations"> An array of references to the network interface IP configurations using subnet. </param>
/// <param name="ipConfigurationProfiles"> Array of IP configuration profiles which reference this subnet. </param>
/// <param name="ipAllocations"> Array of IpAllocation which reference this subnet. </param>
/// <param name="resourceNavigationLinks"> An array of references to the external resources using subnet. </param>
/// <param name="serviceAssociationLinks"> An array of references to services injecting into this subnet. </param>
/// <param name="delegations"> An array of references to the delegations on the subnet. </param>
/// <param name="purpose"> A read-only string identifying the intention of use for this subnet based on delegations and other user-defined properties. </param>
/// <param name="provisioningState"> The provisioning state of the subnet resource. </param>
/// <param name="privateEndpointNetworkPolicies"> Enable or Disable apply network policies on private end point in the subnet. </param>
/// <param name="privateLinkServiceNetworkPolicies"> Enable or Disable apply network policies on private link service in the subnet. </param>
internal Subnet(string id, string name, string etag, string addressPrefix, IList<string> addressPrefixes, NetworkSecurityGroup networkSecurityGroup, RouteTable routeTable, SubResource natGateway, IList<ServiceEndpointPropertiesFormat> serviceEndpoints, IList<ServiceEndpointPolicy> serviceEndpointPolicies, IReadOnlyList<PrivateEndpoint> privateEndpoints, IReadOnlyList<IPConfiguration> ipConfigurations, IReadOnlyList<IPConfigurationProfile> ipConfigurationProfiles, IList<SubResource> ipAllocations, IReadOnlyList<ResourceNavigationLink> resourceNavigationLinks, IReadOnlyList<ServiceAssociationLink> serviceAssociationLinks, IList<Delegation> delegations, string purpose, ProvisioningState? provisioningState, string privateEndpointNetworkPolicies, string privateLinkServiceNetworkPolicies) : base(id)
{
Name = name;
Etag = etag;
AddressPrefix = addressPrefix;
AddressPrefixes = addressPrefixes;
NetworkSecurityGroup = networkSecurityGroup;
RouteTable = routeTable;
NatGateway = natGateway;
ServiceEndpoints = serviceEndpoints;
ServiceEndpointPolicies = serviceEndpointPolicies;
PrivateEndpoints = privateEndpoints;
IpConfigurations = ipConfigurations;
IpConfigurationProfiles = ipConfigurationProfiles;
IpAllocations = ipAllocations;
ResourceNavigationLinks = resourceNavigationLinks;
ServiceAssociationLinks = serviceAssociationLinks;
Delegations = delegations;
Purpose = purpose;
ProvisioningState = provisioningState;
PrivateEndpointNetworkPolicies = privateEndpointNetworkPolicies;
PrivateLinkServiceNetworkPolicies = privateLinkServiceNetworkPolicies;
}
/// <summary> The name of the resource that is unique within a resource group. This name can be used to access the resource. </summary>
public string Name { get; set; }
/// <summary> A unique read-only string that changes whenever the resource is updated. </summary>
public string Etag { get; }
/// <summary> The address prefix for the subnet. </summary>
public string AddressPrefix { get; set; }
/// <summary> List of address prefixes for the subnet. </summary>
public IList<string> AddressPrefixes { get; }
/// <summary> The reference to the NetworkSecurityGroup resource. </summary>
public NetworkSecurityGroup NetworkSecurityGroup { get; set; }
/// <summary> The reference to the RouteTable resource. </summary>
public RouteTable RouteTable { get; set; }
/// <summary> Nat gateway associated with this subnet. </summary>
public SubResource NatGateway { get; set; }
/// <summary> An array of service endpoints. </summary>
public IList<ServiceEndpointPropertiesFormat> ServiceEndpoints { get; }
/// <summary> An array of service endpoint policies. </summary>
public IList<ServiceEndpointPolicy> ServiceEndpointPolicies { get; }
/// <summary> An array of references to private endpoints. </summary>
public IReadOnlyList<PrivateEndpoint> PrivateEndpoints { get; }
/// <summary> An array of references to the network interface IP configurations using subnet. </summary>
public IReadOnlyList<IPConfiguration> IpConfigurations { get; }
/// <summary> Array of IP configuration profiles which reference this subnet. </summary>
public IReadOnlyList<IPConfigurationProfile> IpConfigurationProfiles { get; }
/// <summary> Array of IpAllocation which reference this subnet. </summary>
public IList<SubResource> IpAllocations { get; }
/// <summary> An array of references to the external resources using subnet. </summary>
public IReadOnlyList<ResourceNavigationLink> ResourceNavigationLinks { get; }
/// <summary> An array of references to services injecting into this subnet. </summary>
public IReadOnlyList<ServiceAssociationLink> ServiceAssociationLinks { get; }
/// <summary> An array of references to the delegations on the subnet. </summary>
public IList<Delegation> Delegations { get; }
/// <summary> A read-only string identifying the intention of use for this subnet based on delegations and other user-defined properties. </summary>
public string Purpose { get; }
/// <summary> The provisioning state of the subnet resource. </summary>
public ProvisioningState? ProvisioningState { get; }
/// <summary> Enable or Disable apply network policies on private end point in the subnet. </summary>
public string PrivateEndpointNetworkPolicies { get; set; }
/// <summary> Enable or Disable apply network policies on private link service in the subnet. </summary>
public string PrivateLinkServiceNetworkPolicies { get; set; }
}
}
| ayeletshpigelman/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/Models/Subnet.cs | C# | mit | 8,639 |
//
// MMApiObject.h
// Api对象,包含所有接口和对象数据定义
//
// Created by Wechat on 12-2-28.
// Copyright (c) 2012年 Tencent. All rights reserved.
//
#import <Foundation/Foundation.h>
/*! @brief 错误码
*
*/
enum WXErrCode {
WXSuccess = 0, /**< 成功 */
WXErrCodeCommon = -1, /**< 普通错误类型 */
WXErrCodeUserCancel = -2, /**< 用户点击取消并返回 */
WXErrCodeSentFail = -3, /**< 发送失败 */
WXErrCodeAuthDeny = -4, /**< 授权失败 */
WXErrCodeUnsupport = -5, /**< 微信不支持 */
};
/*! @brief 请求发送场景
*
*/
enum WXScene {
WXSceneSession = 0, /**< 聊天界面 */
WXSceneTimeline = 1, /**< 朋友圈 */
WXSceneFavorite = 2, /**< 收藏 */
};
enum WXAPISupport {
WXAPISupportSession = 0,
};
/*! @brief 跳转profile类型
*
*/
enum WXBizProfileType{
WXBizProfileType_Normal = 0, //**< 普通公众号 */
WXBizProfileType_Device = 1, //**< 硬件公众号 */
};
/*! @brief 跳转mp网页类型
*
*/
enum WXMPWebviewType {
WXMPWebviewType_Ad = 0, /**< 广告网页 **/
};
#pragma mark - BaseReq
/*! @brief 该类为微信终端SDK所有请求类的基类
*
*/
@interface BaseReq : NSObject
/** 请求类型 */
@property (nonatomic, assign) int type;
/** 由用户微信号和AppID组成的唯一标识,发送请求时第三方程序必须填写,用于校验微信用户是否换号登录*/
@property (nonatomic, retain) NSString* openID;
@end
#pragma mark - BaseResp
/*! @brief 该类为微信终端SDK所有响应类的基类
*
*/
@interface BaseResp : NSObject
/** 错误码 */
@property (nonatomic, assign) int errCode;
/** 错误提示字符串 */
@property (nonatomic, retain) NSString *errStr;
/** 响应类型 */
@property (nonatomic, assign) int type;
@end
#pragma mark - WXMediaMessage
@class WXMediaMessage;
/*! @brief 第三方向微信终端发起支付的消息结构体
*
* 第三方向微信终端发起支付的消息结构体,微信终端处理后会向第三方返回处理结果
* @see PayResp
*/
@interface PayReq : BaseReq
/** 商家向财付通申请的商家id */
@property (nonatomic, retain) NSString *partnerId;
/** 预支付订单 */
@property (nonatomic, retain) NSString *prepayId;
/** 随机串,防重发 */
@property (nonatomic, retain) NSString *nonceStr;
/** 时间戳,防重发 */
@property (nonatomic, assign) UInt32 timeStamp;
/** 商家根据财付通文档填写的数据和签名 */
@property (nonatomic, retain) NSString *package;
/** 商家根据微信开放平台文档对数据做的签名 */
@property (nonatomic, retain) NSString *sign;
@end
#pragma mark - PayResp
/*! @brief 微信终端返回给第三方的关于支付结果的结构体
*
* 微信终端返回给第三方的关于支付结果的结构体
*/
@interface PayResp : BaseResp
/** 财付通返回给商家的信息 */
@property (nonatomic, retain) NSString *returnKey;
@end
#pragma mark - SendAuthReq
/*! @brief 第三方程序向微信终端请求认证的消息结构
*
* 第三方程序要向微信申请认证,并请求某些权限,需要调用WXApi的sendReq成员函数,
* 向微信终端发送一个SendAuthReq消息结构。微信终端处理完后会向第三方程序发送一个处理结果。
* @see SendAuthResp
*/
@interface SendAuthReq : BaseReq
/** 第三方程序要向微信申请认证,并请求某些权限,需要调用WXApi的sendReq成员函数,向微信终端发送一个SendAuthReq消息结构。微信终端处理完后会向第三方程序发送一个处理结果。
* @see SendAuthResp
* @note scope字符串长度不能超过1K
*/
@property (nonatomic, retain) NSString* scope;
/** 第三方程序本身用来标识其请求的唯一性,最后跳转回第三方程序时,由微信终端回传。
* @note state字符串长度不能超过1K
*/
@property (nonatomic, retain) NSString* state;
@end
#pragma mark - SendAuthResp
/*! @brief 微信处理完第三方程序的认证和权限申请后向第三方程序回送的处理结果。
*
* 第三方程序要向微信申请认证,并请求某些权限,需要调用WXApi的sendReq成员函数,向微信终端发送一个SendAuthReq消息结构。
* 微信终端处理完后会向第三方程序发送一个SendAuthResp。
* @see onResp
*/
@interface SendAuthResp : BaseResp
@property (nonatomic, retain) NSString* code;
/** 第三方程序发送时用来标识其请求的唯一性的标志,由第三方程序调用sendReq时传入,由微信终端回传
* @note state字符串长度不能超过1K
*/
@property (nonatomic, retain) NSString* state;
@property (nonatomic, retain) NSString* lang;
@property (nonatomic, retain) NSString* country;
@end
#pragma mark - SendMessageToWXReq
/*! @brief 第三方程序发送消息至微信终端程序的消息结构体
*
* 第三方程序向微信发送信息需要传入SendMessageToWXReq结构体,信息类型包括文本消息和多媒体消息,
* 分别对应于text和message成员。调用该方法后,微信处理完信息会向第三方程序发送一个处理结果。
* @see SendMessageToWXResp
*/
@interface SendMessageToWXReq : BaseReq
/** 发送消息的文本内容
* @note 文本长度必须大于0且小于10K
*/
@property (nonatomic, retain) NSString* text;
/** 发送消息的多媒体内容
* @see WXMediaMessage
*/
@property (nonatomic, retain) WXMediaMessage* message;
/** 发送消息的类型,包括文本消息和多媒体消息两种,两者只能选择其一,不能同时发送文本和多媒体消息 */
@property (nonatomic, assign) BOOL bText;
/** 发送的目标场景,可以选择发送到会话(WXSceneSession)或者朋友圈(WXSceneTimeline)。 默认发送到会话。
* @see WXScene
*/
@property (nonatomic, assign) int scene;
@end
#pragma mark - SendMessageToWXResp
/*! @brief 微信终端向第三方程序返回的SendMessageToWXReq处理结果。
*
* 第三方程序向微信终端发送SendMessageToWXReq后,微信发送回来的处理结果,该结果用SendMessageToWXResp表示。
*/
@interface SendMessageToWXResp : BaseResp
@property(nonatomic, retain) NSString* lang;
@property(nonatomic, retain) NSString* country;
@end
#pragma mark - GetMessageFromWXReq
/*! @brief 微信终端向第三方程序请求提供内容的消息结构体。
*
* 微信终端向第三方程序请求提供内容,微信终端会向第三方程序发送GetMessageFromWXReq消息结构体,
* 需要第三方程序调用sendResp返回一个GetMessageFromWXResp消息结构体。
*/
@interface GetMessageFromWXReq : BaseReq
@property (nonatomic, retain) NSString* lang;
@property (nonatomic, retain) NSString* country;
@end
#pragma mark - GetMessageFromWXResp
/*! @brief 微信终端向第三方程序请求提供内容,第三方程序向微信终端返回的消息结构体。
*
* 微信终端向第三方程序请求提供内容,第三方程序调用sendResp向微信终端返回一个GetMessageFromWXResp消息结构体。
*/
@interface GetMessageFromWXResp : BaseResp
/** 向微信终端提供的文本内容
@note 文本长度必须大于0且小于10K
*/
@property (nonatomic, retain) NSString* text;
/** 向微信终端提供的多媒体内容。
* @see WXMediaMessage
*/
@property (nonatomic, retain) WXMediaMessage* message;
/** 向微信终端提供内容的消息类型,包括文本消息和多媒体消息两种,两者只能选择其一,不能同时发送文本和多媒体消息 */
@property (nonatomic, assign) BOOL bText;
@end
#pragma mark - ShowMessageFromWXReq
/*! @brief 微信通知第三方程序,要求第三方程序显示的消息结构体。
*
* 微信需要通知第三方程序显示或处理某些内容时,会向第三方程序发送ShowMessageFromWXReq消息结构体。
* 第三方程序处理完内容后调用sendResp向微信终端发送ShowMessageFromWXResp。
*/
@interface ShowMessageFromWXReq : BaseReq
/** 微信终端向第三方程序发送的要求第三方程序处理的多媒体内容
* @see WXMediaMessage
*/
@property (nonatomic, retain) WXMediaMessage* message;
@property (nonatomic, retain) NSString* lang;
@property (nonatomic, retain) NSString* country;
@end
#pragma mark - ShowMessageFromWXResp
/*! @brief 微信通知第三方程序,要求第三方程序显示或处理某些消息,第三方程序处理完后向微信终端发送的处理结果。
*
* 微信需要通知第三方程序显示或处理某些内容时,会向第三方程序发送ShowMessageFromWXReq消息结构体。
* 第三方程序处理完内容后调用sendResp向微信终端发送ShowMessageFromWXResp。
*/
@interface ShowMessageFromWXResp : BaseResp
@end
#pragma mark - LaunchFromWXReq
/*! @brief 微信终端打开第三方程序携带的消息结构体
*
* 微信向第三方发送的结构体,第三方不需要返回
*/
@interface LaunchFromWXReq : BaseReq
@property (nonatomic, retain) WXMediaMessage* message;
@property (nonatomic, retain) NSString* lang;
@property (nonatomic, retain) NSString* country;
@end
#pragma mark - JumpToBizProfileReq
/* ! @brief 第三方通知微信,打开指定微信号profile页面
*
* 第三方通知微信,打开指定微信号profile页面
*/
@interface JumpToBizProfileReq : BaseReq
/** 跳转到该公众号的profile
* @attention 长度不能超过512字节
*/
@property (nonatomic, retain) NSString* username;
/** 如果用户加了该公众号为好友,extMsg会上传到服务器
* @attention 长度不能超过1024字节
*/
@property (nonatomic, retain) NSString* extMsg;
/**
* 跳转的公众号类型
* @see WXBizProfileType
*/
@property (nonatomic, assign) int profileType;
@end
#pragma mark - JumpToBizWebviewReq
/* ! @brief 第三方通知微信,打开指定usrname的profile网页版
*
*/
@interface JumpToBizWebviewReq : BaseReq
/** 跳转的网页类型,目前只支持广告页
* @see WXMPWebviewType
*/
@property(nonatomic, assign) int webType;
/** 跳转到该公众号的profile网页版
* @attention 长度不能超过512字节
*/
@property(nonatomic, retain) NSString* tousrname;
/** 如果用户加了该公众号为好友,extMsg会上传到服务器
* @attention 长度不能超过1024字节
*/
@property(nonatomic, retain) NSString* extMsg;
@end
#pragma mark - WXCardItem
@interface WXCardItem : NSObject
/** 卡id
* @attention 长度不能超过1024字节
*/
@property (nonatomic,retain) NSString* cardId;
/** ext信息
* @attention 长度不能超过2024字节
*/
@property (nonatomic,retain) NSString* extMsg;
/**
* @attention 卡的状态,req不需要填。resp:0为未添加,1为已添加。
*/
@property (nonatomic,assign) UInt32 cardState;
@end;
#pragma mark - AddCardToWXCardPackageReq
/* ! @brief 请求添加卡券至微信卡包
*
*/
@interface AddCardToWXCardPackageReq : BaseReq
/** 卡列表
* @attention 个数不能超过40个 类型WXCardItem
*/
@property (nonatomic,retain) NSArray* cardAry;
@end
#pragma mark - AddCardToWXCardPackageResp
/** ! @brief 微信返回第三方添加卡券结果
*
*/
@interface AddCardToWXCardPackageResp : BaseResp
/** 卡列表
* @attention 个数不能超过40个 类型WXCardItem
*/
@property (nonatomic,retain) NSArray* cardAry;
@end
#pragma mark - WXMediaMessage
/*! @brief 多媒体消息结构体
*
* 用于微信终端和第三方程序之间传递消息的多媒体消息内容
*/
@interface WXMediaMessage : NSObject
+(WXMediaMessage *) message;
/** 标题
* @note 长度不能超过512字节
*/
@property (nonatomic, retain) NSString *title;
/** 描述内容
* @note 长度不能超过1K
*/
@property (nonatomic, retain) NSString *description;
/** 缩略图数据
* @note 大小不能超过32K
*/
@property (nonatomic, retain) NSData *thumbData;
/**
* @note 长度不能超过64字节
*/
@property (nonatomic, retain) NSString *mediaTagName;
/**
*
*/
@property (nonatomic, retain) NSString *messageExt;
@property (nonatomic, retain) NSString *messageAction;
/**
* 多媒体数据对象,可以为WXImageObject,WXMusicObject,WXVideoObject,WXWebpageObject等。
*/
@property (nonatomic, retain) id mediaObject;
/*! @brief 设置消息缩略图的方法
*
* @param image 缩略图
* @note 大小不能超过32K
*/
- (void) setThumbImage:(UIImage *)image;
@end
#pragma mark - WXImageObject
/*! @brief 多媒体消息中包含的图片数据对象
*
* 微信终端和第三方程序之间传递消息中包含的图片数据对象。
* @note imageData和imageUrl成员不能同时为空
* @see WXMediaMessage
*/
@interface WXImageObject : NSObject
/*! @brief 返回一个WXImageObject对象
*
* @note 返回的WXImageObject对象是自动释放的
*/
+(WXImageObject *) object;
/** 图片真实数据内容
* @note 大小不能超过10M
*/
@property (nonatomic, retain) NSData *imageData;
/** 图片url
* @note 长度不能超过10K
*/
@property (nonatomic, retain) NSString *imageUrl;
@end
#pragma mark - WXMusicObject
/*! @brief 多媒体消息中包含的音乐数据对象
*
* 微信终端和第三方程序之间传递消息中包含的音乐数据对象。
* @note musicUrl和musicLowBandUrl成员不能同时为空。
* @see WXMediaMessage
*/
@interface WXMusicObject : NSObject
/*! @brief 返回一个WXMusicObject对象
*
* @note 返回的WXMusicObject对象是自动释放的
*/
+(WXMusicObject *) object;
/** 音乐网页的url地址
* @note 长度不能超过10K
*/
@property (nonatomic, retain) NSString *musicUrl;
/** 音乐lowband网页的url地址
* @note 长度不能超过10K
*/
@property (nonatomic, retain) NSString *musicLowBandUrl;
/** 音乐数据url地址
* @note 长度不能超过10K
*/
@property (nonatomic, retain) NSString *musicDataUrl;
/**音乐lowband数据url地址
* @note 长度不能超过10K
*/
@property (nonatomic, retain) NSString *musicLowBandDataUrl;
@end
#pragma mark - WXVideoObject
/*! @brief 多媒体消息中包含的视频数据对象
*
* 微信终端和第三方程序之间传递消息中包含的视频数据对象。
* @note videoUrl和videoLowBandUrl不能同时为空。
* @see WXMediaMessage
*/
@interface WXVideoObject : NSObject
/*! @brief 返回一个WXVideoObject对象
*
* @note 返回的WXVideoObject对象是自动释放的
*/
+(WXVideoObject *) object;
/** 视频网页的url地址
* @note 长度不能超过10K
*/
@property (nonatomic, retain) NSString *videoUrl;
/** 视频lowband网页的url地址
* @note 长度不能超过10K
*/
@property (nonatomic, retain) NSString *videoLowBandUrl;
@end
#pragma mark - WXWebpageObject
/*! @brief 多媒体消息中包含的网页数据对象
*
* 微信终端和第三方程序之间传递消息中包含的网页数据对象。
* @see WXMediaMessage
*/
@interface WXWebpageObject : NSObject
/*! @brief 返回一个WXWebpageObject对象
*
* @note 返回的WXWebpageObject对象是自动释放的
*/
+(WXWebpageObject *) object;
/** 网页的url地址
* @note 不能为空且长度不能超过10K
*/
@property (nonatomic, retain) NSString *webpageUrl;
@end
#pragma mark - WXAppExtendObject
/*! @brief 多媒体消息中包含的App扩展数据对象
*
* 第三方程序向微信终端发送包含WXAppExtendObject的多媒体消息,
* 微信需要处理该消息时,会调用该第三方程序来处理多媒体消息内容。
* @note url,extInfo和fileData不能同时为空
* @see WXMediaMessage
*/
@interface WXAppExtendObject : NSObject
/*! @brief 返回一个WXAppExtendObject对象
*
* @note 返回的WXAppExtendObject对象是自动释放的
*/
+(WXAppExtendObject *) object;
/** 若第三方程序不存在,微信终端会打开该url所指的App下载地址
* @note 长度不能超过10K
*/
@property (nonatomic, retain) NSString *url;
/** 第三方程序自定义简单数据,微信终端会回传给第三方程序处理
* @note 长度不能超过2K
*/
@property (nonatomic, retain) NSString *extInfo;
/** App文件数据,该数据发送给微信好友,微信好友需要点击后下载数据,微信终端会回传给第三方程序处理
* @note 大小不能超过10M
*/
@property (nonatomic, retain) NSData *fileData;
@end
#pragma mark - WXEmoticonObject
/*! @brief 多媒体消息中包含的表情数据对象
*
* 微信终端和第三方程序之间传递消息中包含的表情数据对象。
* @see WXMediaMessage
*/
@interface WXEmoticonObject : NSObject
/*! @brief 返回一个WXEmoticonObject对象
*
* @note 返回的WXEmoticonObject对象是自动释放的
*/
+(WXEmoticonObject *) object;
/** 表情真实数据内容
* @note 大小不能超过10M
*/
@property (nonatomic, retain) NSData *emoticonData;
@end
#pragma mark - WXFileObject
/*! @brief 多媒体消息中包含的文件数据对象
*
* @see WXMediaMessage
*/
@interface WXFileObject : NSObject
/*! @brief 返回一个WXFileObject对象
*
* @note 返回的WXFileObject对象是自动释放的
*/
+(WXFileObject *) object;
/** 文件后缀名
* @note 长度不超过64字节
*/
@property (nonatomic, retain) NSString *fileExtension;
/** 文件真实数据内容
* @note 大小不能超过10M
*/
@property (nonatomic, retain) NSData *fileData;
@end
| turingou/cordova-wechat | src/ios/lib/1.5/WXApiObject.h | C | mit | 17,403 |
import { argv } from 'yargs';
import * as CONFIG from '../../config';
/**
* Returns the project configuration (consisting of the base configuration provided by seed.config.ts and the additional
* project specific overrides as defined in project.config.ts)
*/
export function templateLocals() {
const configEnvName = argv['config-env'] || 'dev';
const configEnv = CONFIG.getPluginConfig('environment-config')[configEnvName];
if (!configEnv) {
throw new Error('Invalid configuration name');
}
const config = {
ENV_CONFIG: JSON.stringify(configEnv)
};
return Object.assign(config, CONFIG);
}
| nlopezcenteno/angular2-seed | tools/utils/seed/template_locals.ts | TypeScript | mit | 618 |
import { Template } from 'meteor/templating';
Template.messageAction.helpers({
isButton() {
return this.type === 'button';
},
areButtonsHorizontal() {
return Template.parentData(1).button_alignment === 'horizontal';
},
jsActionButtonClassname(processingType) {
return `js-actionButton-${ processingType || 'sendMessage' }`;
},
});
| 4thParty/Rocket.Chat | app/message-action/client/messageAction.js | JavaScript | mit | 344 |
<?php
namespace Illuminate\Tests\Database;
use Illuminate\Database\Connection;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Grammars\MySqlGrammar;
use Illuminate\Database\Schema\Grammars\PostgresGrammar;
use Illuminate\Database\Schema\Grammars\SQLiteGrammar;
use Illuminate\Database\Schema\Grammars\SqlServerGrammar;
use Mockery as m;
use PHPUnit\Framework\TestCase;
class DatabaseSchemaBlueprintTest extends TestCase
{
protected function tearDown(): void
{
m::close();
}
public function testToSqlRunsCommandsFromBlueprint()
{
$conn = m::mock(Connection::class);
$conn->shouldReceive('statement')->once()->with('foo');
$conn->shouldReceive('statement')->once()->with('bar');
$grammar = m::mock(MySqlGrammar::class);
$blueprint = $this->getMockBuilder(Blueprint::class)->setMethods(['toSql'])->setConstructorArgs(['users'])->getMock();
$blueprint->expects($this->once())->method('toSql')->with($this->equalTo($conn), $this->equalTo($grammar))->willReturn(['foo', 'bar']);
$blueprint->build($conn, $grammar);
}
public function testIndexDefaultNames()
{
$blueprint = new Blueprint('users');
$blueprint->unique(['foo', 'bar']);
$commands = $blueprint->getCommands();
$this->assertSame('users_foo_bar_unique', $commands[0]->index);
$blueprint = new Blueprint('users');
$blueprint->index('foo');
$commands = $blueprint->getCommands();
$this->assertSame('users_foo_index', $commands[0]->index);
$blueprint = new Blueprint('geo');
$blueprint->spatialIndex('coordinates');
$commands = $blueprint->getCommands();
$this->assertSame('geo_coordinates_spatialindex', $commands[0]->index);
}
public function testIndexDefaultNamesWhenPrefixSupplied()
{
$blueprint = new Blueprint('users', null, 'prefix_');
$blueprint->unique(['foo', 'bar']);
$commands = $blueprint->getCommands();
$this->assertSame('prefix_users_foo_bar_unique', $commands[0]->index);
$blueprint = new Blueprint('users', null, 'prefix_');
$blueprint->index('foo');
$commands = $blueprint->getCommands();
$this->assertSame('prefix_users_foo_index', $commands[0]->index);
$blueprint = new Blueprint('geo', null, 'prefix_');
$blueprint->spatialIndex('coordinates');
$commands = $blueprint->getCommands();
$this->assertSame('prefix_geo_coordinates_spatialindex', $commands[0]->index);
}
public function testDropIndexDefaultNames()
{
$blueprint = new Blueprint('users');
$blueprint->dropUnique(['foo', 'bar']);
$commands = $blueprint->getCommands();
$this->assertSame('users_foo_bar_unique', $commands[0]->index);
$blueprint = new Blueprint('users');
$blueprint->dropIndex(['foo']);
$commands = $blueprint->getCommands();
$this->assertSame('users_foo_index', $commands[0]->index);
$blueprint = new Blueprint('geo');
$blueprint->dropSpatialIndex(['coordinates']);
$commands = $blueprint->getCommands();
$this->assertSame('geo_coordinates_spatialindex', $commands[0]->index);
}
public function testDropIndexDefaultNamesWhenPrefixSupplied()
{
$blueprint = new Blueprint('users', null, 'prefix_');
$blueprint->dropUnique(['foo', 'bar']);
$commands = $blueprint->getCommands();
$this->assertSame('prefix_users_foo_bar_unique', $commands[0]->index);
$blueprint = new Blueprint('users', null, 'prefix_');
$blueprint->dropIndex(['foo']);
$commands = $blueprint->getCommands();
$this->assertSame('prefix_users_foo_index', $commands[0]->index);
$blueprint = new Blueprint('geo', null, 'prefix_');
$blueprint->dropSpatialIndex(['coordinates']);
$commands = $blueprint->getCommands();
$this->assertSame('prefix_geo_coordinates_spatialindex', $commands[0]->index);
}
public function testDefaultCurrentDateTime()
{
$base = new Blueprint('users', function ($table) {
$table->dateTime('created')->useCurrent();
});
$connection = m::mock(Connection::class);
$blueprint = clone $base;
$this->assertEquals(['alter table `users` add `created` datetime default CURRENT_TIMESTAMP not null'], $blueprint->toSql($connection, new MySqlGrammar));
$blueprint = clone $base;
$this->assertEquals(['alter table "users" add column "created" timestamp(0) without time zone default CURRENT_TIMESTAMP not null'], $blueprint->toSql($connection, new PostgresGrammar));
$blueprint = clone $base;
$this->assertEquals(['alter table "users" add column "created" datetime default CURRENT_TIMESTAMP not null'], $blueprint->toSql($connection, new SQLiteGrammar));
$blueprint = clone $base;
$this->assertEquals(['alter table "users" add "created" datetime default CURRENT_TIMESTAMP not null'], $blueprint->toSql($connection, new SqlServerGrammar));
}
public function testDefaultCurrentTimestamp()
{
$base = new Blueprint('users', function ($table) {
$table->timestamp('created')->useCurrent();
});
$connection = m::mock(Connection::class);
$blueprint = clone $base;
$this->assertEquals(['alter table `users` add `created` timestamp default CURRENT_TIMESTAMP not null'], $blueprint->toSql($connection, new MySqlGrammar));
$blueprint = clone $base;
$this->assertEquals(['alter table "users" add column "created" timestamp(0) without time zone default CURRENT_TIMESTAMP not null'], $blueprint->toSql($connection, new PostgresGrammar));
$blueprint = clone $base;
$this->assertEquals(['alter table "users" add column "created" datetime default CURRENT_TIMESTAMP not null'], $blueprint->toSql($connection, new SQLiteGrammar));
$blueprint = clone $base;
$this->assertEquals(['alter table "users" add "created" datetime default CURRENT_TIMESTAMP not null'], $blueprint->toSql($connection, new SqlServerGrammar));
}
public function testUnsignedDecimalTable()
{
$base = new Blueprint('users', function ($table) {
$table->unsignedDecimal('money', 10, 2)->useCurrent();
});
$connection = m::mock(Connection::class);
$blueprint = clone $base;
$this->assertEquals(['alter table `users` add `money` decimal(10, 2) unsigned not null'], $blueprint->toSql($connection, new MySqlGrammar));
}
public function testRemoveColumn()
{
$base = new Blueprint('users', function ($table) {
$table->string('foo');
$table->string('remove_this');
$table->removeColumn('remove_this');
});
$connection = m::mock(Connection::class);
$blueprint = clone $base;
$this->assertEquals(['alter table `users` add `foo` varchar(255) not null'], $blueprint->toSql($connection, new MySqlGrammar));
}
public function testMacroable()
{
Blueprint::macro('foo', function () {
return $this->addCommand('foo');
});
MySqlGrammar::macro('compileFoo', function () {
return 'bar';
});
$blueprint = new Blueprint('users', function ($table) {
$table->foo();
});
$connection = m::mock(Connection::class);
$this->assertEquals(['bar'], $blueprint->toSql($connection, new MySqlGrammar));
}
}
| ChristopheB/framework | tests/Database/DatabaseSchemaBlueprintTest.php | PHP | mit | 7,610 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using EnvDTE;
using EnvDTE80;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Export, Shared]
internal partial class AnalyzerConfigDocumentAsSolutionItemHandler : IDisposable
{
private static readonly string LocalRegistryPath = $@"Roslyn\Internal\{nameof(AnalyzerConfigDocumentAsSolutionItemHandler)}\";
private static readonly Option<bool> NeverShowAgain = new Option<bool>(nameof(AnalyzerConfigDocumentAsSolutionItemHandler), nameof(NeverShowAgain),
defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(NeverShowAgain)));
private readonly VisualStudioWorkspace _workspace;
private readonly IThreadingContext _threadingContext;
private DTE? _dte;
private bool _infoBarShownForCurrentSolution;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerConfigDocumentAsSolutionItemHandler(
VisualStudioWorkspace workspace,
IThreadingContext threadingContext)
{
_workspace = workspace;
_threadingContext = threadingContext;
_workspace.WorkspaceChanged += OnWorkspaceChanged;
}
public void Initialize(IServiceProvider serviceProvider)
=> _dte = (DTE)serviceProvider.GetService(typeof(DTE));
void IDisposable.Dispose()
=> _workspace.WorkspaceChanged -= OnWorkspaceChanged;
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
_infoBarShownForCurrentSolution = false;
return;
// Check if a new analyzer config document was added
case WorkspaceChangeKind.AnalyzerConfigDocumentAdded:
break;
default:
return;
}
// Bail out if we have a null DTE instance or we have already shown the info bar for current solution.
if (_dte == null ||
_infoBarShownForCurrentSolution)
{
return;
}
// Check if added analyzer config document is at the root of the current solution.
var analyzerConfigDocumentFilePath = e.NewSolution.GetAnalyzerConfigDocument(e.DocumentId)?.FilePath;
var analyzerConfigDirectory = PathUtilities.GetDirectoryName(analyzerConfigDocumentFilePath);
var solutionDirectory = PathUtilities.GetDirectoryName(e.NewSolution.FilePath);
if (analyzerConfigDocumentFilePath == null ||
analyzerConfigDirectory == null ||
analyzerConfigDirectory != solutionDirectory)
{
return;
}
// Check if user has explicitly disabled the suggestion to add newly added analyzer config document as solution item.
if (_workspace.Options.GetOption(NeverShowAgain))
{
return;
}
// Kick off a task to show info bar to make it a solution item.
Task.Run(async () =>
{
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync();
var solution = (Solution2)_dte.Solution;
if (VisualStudioAddSolutionItemService.TryGetExistingSolutionItemsFolder(solution, analyzerConfigDocumentFilePath, out _, out var hasExistingSolutionItem) &&
hasExistingSolutionItem)
{
return;
}
if (!_infoBarShownForCurrentSolution)
{
_infoBarShownForCurrentSolution = true;
var infoBarService = _workspace.Services.GetRequiredService<IInfoBarService>();
infoBarService.ShowInfoBarInGlobalView(
ServicesVSResources.A_new_editorconfig_file_was_detected_at_the_root_of_your_solution_Would_you_like_to_make_it_a_solution_item,
GetInfoBarUIItems().ToArray());
}
});
return;
// Local functions
IEnumerable<InfoBarUI> GetInfoBarUIItems()
{
// Yes - add editorconfig solution item.
yield return new InfoBarUI(
title: ServicesVSResources.Yes,
kind: InfoBarUI.UIKind.Button,
action: AddEditorconfigSolutionItem,
closeAfterAction: true);
// No - do not add editorconfig solution item.
yield return new InfoBarUI(
title: ServicesVSResources.No,
kind: InfoBarUI.UIKind.Button,
action: () => { },
closeAfterAction: true);
// Don't show the InfoBar again link
yield return new InfoBarUI(title: ServicesVSResources.Never_show_this_again,
kind: InfoBarUI.UIKind.Button,
action: () => _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options.WithChangedOption(NeverShowAgain, true))),
closeAfterAction: true);
}
void AddEditorconfigSolutionItem()
{
var addSolutionItemService = _workspace.Services.GetRequiredService<IAddSolutionItemService>();
addSolutionItemService.AddSolutionItemAsync(analyzerConfigDocumentFilePath, CancellationToken.None).Wait();
}
}
}
}
| jmarolf/roslyn | src/VisualStudio/Core/Def/Implementation/ProjectSystem/AnalyzerConfigDocumentAsSolutionItemHandler.cs | C# | mit | 6,406 |
import fs from 'fs';
import url from 'url';
import path from 'path';
import mime from 'mime-types';
import gulp from 'gulp';
import createServerTask from './tasks/server';
import consoleArguments from './console-arguments';
import { adminBundle } from './admin-bundle.tasks';
import { dashboardBundle } from './dashboard-bundle.tasks';
import { mediaBundle } from './media-bundle.tasks';
import { translatorBundle } from './translator-bundle.tasks';
const BUNDLES = [adminBundle, dashboardBundle, mediaBundle, translatorBundle];
const writeToResponse = (req, res, bundlePaths) => {
const formattedUrl = url.parse(req.url);
for (const bundlePath of bundlePaths) {
const filePath = path.normalize(bundlePath + formattedUrl.pathname);
try {
const stat = fs.statSync(filePath);
if (stat && stat.isFile()) {
const rstream = fs.createReadStream(filePath);
const extension = path.extname(filePath);
const contentType = mime.lookup(extension);
res.writeHead(200, {
'Content-Type': contentType,
'Content-Length': stat.size
});
rstream.pipe(res);
return;
}
} catch (e) {
// Does not exist
}
}
return new Error(`Local file for ${req.url} not found`);
};
const handleRequest = (req, res, next) => {
if (writeToResponse(req, res, BUNDLES.map(item => item.config.distPath))) {
// Nothing we can write to the stream, fallback to the default behavior
return next();
};
};
const startLocalTask = createServerTask({
config: {
ui: false,
ghostMode: false,
open: false,
reloadOnRestart: true,
notify: true,
proxy: { target: consoleArguments.backendProxy },
middleware: BUNDLES.map(bundle => { return { route: bundle.config.publicPath, handle: handleRequest } })
}
});
export const buildOnChange = (done) => {
for (const bundle of BUNDLES) {
const srcPath = bundle.config.srcPath;
const jsAssets = srcPath + 'js/**/!(*.spec).js';
gulp.watch(jsAssets, bundle.tasks.scripts);
if (bundle.tasks.bundle) {
const jsNextAssets = srcPath + 'jsnext/**/!(*.spec).js';
gulp.watch(jsNextAssets, bundle.tasks.bundle);
}
const styleAssets = srcPath + 'scss/**/*.scss';
gulp.watch(styleAssets, bundle.tasks.cssOptimized);
if (bundle.tasks.cssNextOptimized) {
const styleNextAssets = srcPath + 'scssnext/**/*.scss';
gulp.watch(styleNextAssets, bundle.tasks.cssNextOptimized);
}
}
done();
};
export function testOnChange(done) {
for (const bundle of BUNDLES) {
if (bundle.tasks.eslint) {
const srcPath = bundle.config.srcPath;
gulp.watch(`${srcPath}jsnext/**/*.js`, bundle.tasks.eslint);
}
if (bundle.tasks.stylelint) {
const srcPath = bundle.config.srcPath;
gulp.watch(`${srcPath}scssnext/**/*.scss`, bundle.tasks.stylelint);
}
}
done();
}
export default startLocalTask;
| Kunstmaan/KunstmaanBundlesCMS | groundcontrol/start-local.task.js | JavaScript | mit | 3,206 |
'use strict';
describe('Service: Initiatives', function () {
// instantiate service
var Initiatives,
Timeout,
cfg,
$httpBackend,
$rootScope,
tPromise;
// load the service's module
beforeEach(module('sumaAnalysis'));
beforeEach(inject(function (_$rootScope_, _$httpBackend_, _initiatives_, $q, $timeout) {
$rootScope = _$rootScope_;
$httpBackend = _$httpBackend_;
Initiatives = _initiatives_;
tPromise = $q.defer();
Timeout = $timeout;
cfg = {
timeoutPromise: tPromise,
timeout: 180000
};
}));
it('should make an AJAX call', function (done) {
$httpBackend.whenGET('lib/php/initiatives.php')
.respond([{}, {}]);
Initiatives.get(cfg).then(function (result) {
expect(result.length).to.equal(2);
done();
});
$httpBackend.flush();
});
it('should respond with error message on failure', function (done) {
$httpBackend.whenGET('lib/php/initiatives.php')
.respond(500, {message: 'Error'});
Initiatives.get(cfg).then(function (result) {
}, function (result) {
expect(result).to.deep.equal({
message: 'Error',
code: 500
});
done();
});
$httpBackend.flush();
});
it('should return error with promiseTimeout true on aborted http request', function (done) {
// simulate aborted request
$httpBackend.whenGET('lib/php/initiatives.php')
.respond(0, {message: 'Error'});
Initiatives.get(cfg).then(function (result) {
}, function (result) {
expect(result).to.deep.equal({
message: 'Initiatives.get Timeout',
code: 0,
promiseTimeout: true
});
done();
});
$httpBackend.flush();
});
it('should return error without promiseTimeout on http timeout', function (done) {
$httpBackend.whenGET('lib/php/initiatives.php')
.respond([{}, {}]);
Initiatives.get(cfg).then(function (result) {
}, function (result) {
expect(result).to.deep.equal({
message: 'Initiatives.get Timeout',
code: 0
});
done();
});
Timeout.flush();
});
});
| cazzerson/Suma | analysis/test/js/spec/services/initiatives.js | JavaScript | mit | 2,143 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Core\Model;
use Sylius\Component\Promotion\Model\PromotionCouponInterface as BasePromotionCouponInterface;
interface PromotionCouponInterface extends BasePromotionCouponInterface
{
public function getPerCustomerUsageLimit(): ?int;
public function setPerCustomerUsageLimit(?int $perCustomerUsageLimit): void;
}
| venyii/Sylius | src/Sylius/Component/Core/Model/PromotionCouponInterface.php | PHP | mit | 594 |
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
/***
* banned.h - list of Microsoft Security Development Lifecycle banned APIs
*
* Purpose:
* This include file contains a list of banned API which should not be used in new code and
* removed from legacy code over time
* History
* 01-Jan-2006 - mikehow - Initial Version
* 22-Apr-2008 - mikehow - Updated to SDL 4.1, commented out recommendations and added memcpy
* 26-Jan-2009 - mikehow - Updated to SDL 5.0, made the list sane, added compliance levels
* 10-Feb-2009 - mikehow - Updated based on feedback from MS Office
* 12-May-2009 - jpardue - Updated based on feedback from mikehow (added wmemcpy)
*
***/
// IMPORTANT:
// Some of these functions are Windows specific, so you may want to add *nix specific banned function calls
#ifndef _INC_BANNED
# define _INC_BANNED
#endif
#ifdef _MSC_VER
# pragma once
# pragma deprecated (strcpy, strcpyA, strcpyW, wcscpy, _tcscpy, _mbscpy, StrCpy, StrCpyA, StrCpyW, lstrcpy, lstrcpyA, lstrcpyW, _tccpy, _mbccpy, _ftcscpy)
# pragma deprecated (strcat, strcatA, strcatW, wcscat, _tcscat, _mbscat, StrCat, StrCatA, StrCatW, lstrcat, lstrcatA, lstrcatW, StrCatBuff, StrCatBuffA, StrCatBuffW, StrCatChainW, _tccat, _mbccat, _ftcscat)
# pragma deprecated (wvsprintf, wvsprintfA, wvsprintfW, vsprintf, _vstprintf, vswprintf)
# pragma deprecated (strncpy, wcsncpy, _tcsncpy, _mbsncpy, _mbsnbcpy, StrCpyN, StrCpyNA, StrCpyNW, StrNCpy, strcpynA, StrNCpyA, StrNCpyW, lstrcpyn, lstrcpynA, lstrcpynW)
# pragma deprecated (strncat, wcsncat, _tcsncat, _mbsncat, _mbsnbcat, StrCatN, StrCatNA, StrCatNW, StrNCat, StrNCatA, StrNCatW, lstrncat, lstrcatnA, lstrcatnW, lstrcatn)
# pragma deprecated (IsBadWritePtr, IsBadHugeWritePtr, IsBadReadPtr, IsBadHugeReadPtr, IsBadCodePtr, IsBadStringPtr)
# pragma deprecated (gets, _getts, _gettws)
# pragma deprecated (RtlCopyMemory, CopyMemory)
# pragma deprecated (wnsprintf, wnsprintfA, wnsprintfW, sprintfW, sprintfA, wsprintf, wsprintfW, wsprintfA, sprintf, swprintf, _stprintf, _snwprintf, _snprintf, _sntprintf)
# pragma deprecated (_vsnprintf, vsnprintf, _vsnwprintf, _vsntprintf, wvnsprintf, wvnsprintfA, wvnsprintfW)
# pragma deprecated (strtok, _tcstok, wcstok, _mbstok)
# pragma deprecated (makepath, _tmakepath, _makepath, _wmakepath)
# pragma deprecated (_splitpath, _tsplitpath, _wsplitpath)
# pragma deprecated (scanf, wscanf, _tscanf, sscanf, swscanf, _stscanf, snscanf, snwscanf, _sntscanf)
# pragma deprecated (_itoa, _itow, _i64toa, _i64tow, _ui64toa, _ui64tot, _ui64tow, _ultoa, _ultot, _ultow)
#if (_SDL_BANNED_LEVEL3)
# pragma deprecated (CharToOem, CharToOemA, CharToOemW, OemToChar, OemToCharA, OemToCharW, CharToOemBuffA, CharToOemBuffW)
# pragma deprecated (alloca, _alloca)
# pragma deprecated (strlen, wcslen, _mbslen, _mbstrlen, StrLen, lstrlen)
# pragma deprecated (ChangeWindowMessageFilter)
#endif
#ifndef PATHCCH_NO_DEPRECATE
// Path APIs which assume MAX_PATH instead of requiring the caller to specify
// the buffer size have been deprecated. Include <PathCch.h> and use the PathCch
// equivalents instead.
# pragma deprecated (PathAddBackslash, PathAddBackslashA, PathAddBackslashW)
# pragma deprecated (PathAddExtension, PathAddExtensionA, PathAddExtensionW)
# pragma deprecated (PathAppend, PathAppendA, PathAppendW)
# pragma deprecated (PathCanonicalize, PathCanonicalizeA, PathCanonicalizeW)
# pragma deprecated (PathCombine, PathCombineA, PathCombineW)
# pragma deprecated (PathRenameExtension, PathRenameExtensionA, PathRenameExtensionW)
#endif // PATHCCH_NO_DEPRECATE
#else // _MSC_VER
#endif /* _INC_BANNED */
| arunetm/ChakraCore_0114 | lib/common/Banned.h | C | mit | 3,962 |
<?php
define('IN_ECS', true);
/* 鎶ュ憡鎵€鏈夐敊璇 */
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
/* 娓呴櫎鎵€鏈夊拰鏂囦欢鎿嶄綔鐩稿叧鐨勭姸鎬佷俊鎭 */
clearstatcache();
/* 瀹氫箟绔欑偣鏍 */
define('ROOT_PATH', str_replace('demo/includes/init.php', '', str_replace('\\', '/', __FILE__)));
require(ROOT_PATH . 'includes/lib_common.php');
@include(ROOT_PATH . 'includes/lib_base.php');
require(ROOT_PATH . 'admin/includes/lib_main.php');
require(ROOT_PATH . 'includes/lib_time.php');
clear_all_files();
/* 鍔犺浇鏁版嵁搴撻厤缃?枃浠 */
if (file_exists(ROOT_PATH . 'data/config.php'))
{
include(ROOT_PATH . 'data/config.php');
}
elseif (file_exists(ROOT_PATH . 'includes/config.php'))
{
if (!rename(ROOT_PATH . 'includes/config.php', ROOT_PATH . 'data/config.php'))
{
die('Can\'t move config.php, please move it from includes/ to data/ manually!');
}
include(ROOT_PATH . 'data/config.php');
}
else
{
die('Can\'t find config.php!');
}
require(ROOT_PATH . 'includes/cls_ecshop.php');
require(ROOT_PATH . 'includes/cls_mysql.php');
/* 鍒涘缓 ECSHOP 瀵硅薄 */
$ecs = new ECS($db_name, $prefix);
/* 鐗堟湰瀛楃?闆嗗彉閲
$ec_version_charset = 'gbk';
*/
$mysql_charset = $ecshop_charset = '';
/* 鑷?姩鑾峰彇鏁版嵁琛ㄧ殑瀛楃?闆 */
$tmp_link = @mysql_connect($db_host, $db_user, $db_pass);
if (!$tmp_link)
{
die("Can't pConnect MySQL Server($db_host)!");
}
else
{
mysql_select_db($db_name);
$query = mysql_query(" SHOW CREATE TABLE " . $ecs->table('users'), $tmp_link) or die(mysql_error());
$tablestruct = mysql_fetch_row($query);
preg_match("/CHARSET=(\w+)/", $tablestruct[1], $m);
if (strpos($m[1], 'utf') === 0)
{
$mysql_charset = str_replace('utf', 'utf-', $m[1]);
}
else
{
$mysql_charset = $m[1];
}
}
if (defined('EC_CHARSET'))
{
$ecshop_charset = EC_CHARSET;
}
/*
if (empty($tmp_charset))
{
$check_charset = false;
$tmp_charset = 'gbk';
}
else
{
$check_charset = true;
}
if (!defined('EC_CHARSET'))
{
define('EC_CHARSET', $tmp_charset);
}
if ($ec_version_charset != EC_CHARSET)
{
die('Database Charset not match!');
}
*/
/* 鍒濆?鍖栨暟鎹?簱绫 */
$db = new cls_mysql($db_host, $db_user, $db_pass, $db_name, $ecshop_charset);
/* 鍒涘缓閿欒?澶勭悊瀵硅薄 */
require(ROOT_PATH . 'includes/cls_error.php');
$err = new ecs_error('message.dwt');
require(ROOT_PATH . 'includes/cls_sql_executor.php');
/* 鍒濆?鍖栨ā鏉垮紩鎿 */
require(ROOT_PATH . 'demo/includes/cls_template.php');
$smarty = new template(ROOT_PATH . 'demo/templates/');
require(ROOT_PATH . 'demo/includes/lib_updater.php');
@set_time_limit(360);
?>
| kitboy/docker-shop | html/ecshop3/ecshop/demo/includes/init.php | PHP | mit | 2,764 |
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/* Tabulator v4.0.2 (c) Oliver Folkerd */
var HtmlTableImport = function HtmlTableImport(table) {
this.table = table; //hold Tabulator object
this.fieldIndex = [];
this.hasIndex = false;
};
HtmlTableImport.prototype.parseTable = function () {
var self = this,
element = self.table.element,
options = self.table.options,
columns = options.columns,
headers = element.getElementsByTagName("th"),
rows = element.getElementsByTagName("tbody")[0].getElementsByTagName("tr"),
data = [],
newTable;
self.hasIndex = false;
self.table.options.htmlImporting.call(this.table);
//check for tablator inline options
self._extractOptions(element, options);
if (headers.length) {
self._extractHeaders(headers, rows);
} else {
self._generateBlankHeaders(headers, rows);
}
//iterate through table rows and build data set
for (var index = 0; index < rows.length; index++) {
var row = rows[index],
cells = row.getElementsByTagName("td"),
item = {};
//create index if the dont exist in table
if (!self.hasIndex) {
item[options.index] = index;
}
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
if (typeof this.fieldIndex[i] !== "undefined") {
item[this.fieldIndex[i]] = cell.innerHTML;
}
}
//add row data to item
data.push(item);
}
//create new element
var newElement = document.createElement("div");
//transfer attributes to new element
var attributes = element.attributes;
// loop through attributes and apply them on div
for (var i in attributes) {
if (_typeof(attributes[i]) == "object") {
newElement.setAttribute(attributes[i].name, attributes[i].value);
}
}
// replace table with div element
element.parentNode.replaceChild(newElement, element);
options.data = data;
self.table.options.htmlImported.call(this.table);
// // newElement.tabulator(options);
this.table.element = newElement;
};
//extract tabluator attribute options
HtmlTableImport.prototype._extractOptions = function (element, options) {
var attributes = element.attributes;
for (var index in attributes) {
var attrib = attributes[index];
var name;
if ((typeof attrib === "undefined" ? "undefined" : _typeof(attrib)) == "object" && attrib.name && attrib.name.indexOf("tabulator-") === 0) {
name = attrib.name.replace("tabulator-", "");
for (var key in options) {
if (key.toLowerCase() == name) {
options[key] = this._attribValue(attrib.value);
}
}
}
}
};
//get value of attribute
HtmlTableImport.prototype._attribValue = function (value) {
if (value === "true") {
return true;
}
if (value === "false") {
return false;
}
return value;
};
//find column if it has already been defined
HtmlTableImport.prototype._findCol = function (title) {
var match = this.table.options.columns.find(function (column) {
return column.title === title;
});
return match || false;
};
//extract column from headers
HtmlTableImport.prototype._extractHeaders = function (headers, rows) {
for (var index = 0; index < headers.length; index++) {
var header = headers[index],
exists = false,
col = this._findCol(header.textContent),
width,
attributes;
if (col) {
exists = true;
} else {
col = { title: header.textContent.trim() };
}
if (!col.field) {
col.field = header.textContent.trim().toLowerCase().replace(" ", "_");
}
width = header.getAttribute("width");
if (width && !col.width) {
col.width = width;
}
//check for tablator inline options
attributes = header.attributes;
// //check for tablator inline options
this._extractOptions(header, col);
for (var i in attributes) {
var attrib = attributes[i],
name;
if ((typeof attrib === "undefined" ? "undefined" : _typeof(attrib)) == "object" && attrib.name && attrib.name.indexOf("tabulator-") === 0) {
name = attrib.name.replace("tabulator-", "");
col[name] = this._attribValue(attrib.value);
}
}
this.fieldIndex[index] = col.field;
if (col.field == this.table.options.index) {
this.hasIndex = true;
}
if (!exists) {
this.table.options.columns.push(col);
}
}
};
//generate blank headers
HtmlTableImport.prototype._generateBlankHeaders = function (headers, rows) {
for (var index = 0; index < headers.length; index++) {
var header = headers[index],
col = { title: "", field: "col" + index };
this.fieldIndex[index] = col.field;
var width = header.getAttribute("width");
if (width) {
col.width = width;
}
this.table.options.columns.push(col);
}
};
Tabulator.prototype.registerModule("htmlTableImport", HtmlTableImport); | joeyparrish/cdnjs | ajax/libs/tabulator/4.0.2/js/modules/html_table_import.js | JavaScript | mit | 4,916 |
<?php
/*
* This file is part of Rocketeer
*
* (c) Maxime Fabre <ehtnam6@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Rocketeer\Binaries\PackageManagers;
use Rocketeer\Abstracts\AbstractPackageManager;
class Bundler extends AbstractPackageManager
{
/**
* The name of the manifest file to look for.
*
* @type string
*/
protected $manifest = 'Gemfile';
/**
* Get an array of default paths to look for.
*
* @return string[]
*/
protected function getKnownPaths()
{
return [
'bundle',
];
}
}
| sbwdlihao/rocketeer | src/Rocketeer/Binaries/PackageManagers/Bundler.php | PHP | mit | 695 |
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
function DumpArray(a)
{
var undef_start = -1;
for (var i = 0; i < a.length; i++)
{
if (a[i] == undefined)
{
if (undef_start == -1)
{
undef_start = i;
}
}
else
{
if (undef_start != -1)
{
WScript.Echo(undef_start + "-" + (i-1) + " = undefined");
undef_start = -1;
}
WScript.Echo(i + " = " + a[i]);
}
}
}
DumpArray([]);
DumpArray([ 0 ]);
DumpArray([ 0, 1, 2, 3, 4, 5, 6 ,7 ,8, 9]);
DumpArray([,,,0,,,1,,,2,,,3,,,4,,,5,,,6,,,7,,,8,,,9,,,]);
var s0 = "";
for (var i = 0; i < 100; i++)
{
s0 += ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,";
}
DumpArray(eval("[" + s0 + "1]"));
var s1 = "";
for (var i = 0; i < 30; i++)
{
s1 += s0;
}
DumpArray(eval("[" + s1 + "1]"));
var s2 = "";
for (var i = 0; i < 10; i++)
{
s2 += s1;
}
DumpArray(eval("[" + s2 + "1]"));
| arunetm/ChakraCore_0114 | test/Array/array_init.js | JavaScript | mit | 1,438 |
/*
* Copyright 2009 The Closure Library Authors. All Rights Reserved.
*
* Use of this source code is governed by the Apache License, Version 2.0.
* See the COPYING file for details.
*/
/*
* Styling for flat buttons created by goog.ui.FlatButtonRenderer.
*
* @author brianp@google.com (Brian Peterson)
*/
.goog-flat-button {
position: relative;
/*width: 20ex;*/
margin: 2px;
border: 1px solid #000;
padding: 2px 6px;
font: normal 13px "Trebuchet MS", Tahoma, Arial, sans-serif;
color: #fff;
background-color: #8c2425;
cursor: pointer;
outline: none;
}
/* State: disabled. */
.goog-flat-button-disabled {
border-color: #888;
color: #888;
background-color: #ccc;
cursor: default;
}
/* State: hover. */
.goog-flat-button-hover {
border-color: #8c2425;
color: #8c2425;
background-color: #eaa4a5;
}
/* State: active, selected, checked. */
.goog-flat-button-active,
.goog-flat-button-selected,
.goog-flat-button-checked {
border-color: #5b4169;
color: #5b4169;
background-color: #d1a8ea;
}
/* State: focused. */
.goog-flat-button-focused {
border-color: #5b4169;
}
/* Pill (collapsed border) styles. */
.goog-flat-button-collapse-right {
margin-right: 0;
}
.goog-flat-button-collapse-left {
margin-left: 0;
border-left: none;
}
| dmincu/IOC | new_php/closure-library/closure/goog/css/flatbutton.css | CSS | mit | 1,350 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_datagram_socket::send</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../basic_datagram_socket.html" title="basic_datagram_socket">
<link rel="prev" href="reuse_address.html" title="basic_datagram_socket::reuse_address">
<link rel="next" href="send/overload1.html" title="basic_datagram_socket::send (1 of 3 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="reuse_address.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_datagram_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="send/overload1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.basic_datagram_socket.send"></a><a class="link" href="send.html" title="basic_datagram_socket::send">basic_datagram_socket::send</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="idp34205456"></a>
Send some data on a connected socket.
</p>
<pre class="programlisting"><span class="keyword">template</span><span class="special"><</span>
<span class="keyword">typename</span> <a class="link" href="../ConstBufferSequence.html" title="Constant buffer sequence requirements">ConstBufferSequence</a><span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="send/overload1.html" title="basic_datagram_socket::send (1 of 3 overloads)">send</a><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">ConstBufferSequence</span> <span class="special">&</span> <span class="identifier">buffers</span><span class="special">);</span>
<span class="emphasis"><em>» <a class="link" href="send/overload1.html" title="basic_datagram_socket::send (1 of 3 overloads)">more...</a></em></span>
<span class="keyword">template</span><span class="special"><</span>
<span class="keyword">typename</span> <a class="link" href="../ConstBufferSequence.html" title="Constant buffer sequence requirements">ConstBufferSequence</a><span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="send/overload2.html" title="basic_datagram_socket::send (2 of 3 overloads)">send</a><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">ConstBufferSequence</span> <span class="special">&</span> <span class="identifier">buffers</span><span class="special">,</span>
<span class="identifier">socket_base</span><span class="special">::</span><span class="identifier">message_flags</span> <span class="identifier">flags</span><span class="special">);</span>
<span class="emphasis"><em>» <a class="link" href="send/overload2.html" title="basic_datagram_socket::send (2 of 3 overloads)">more...</a></em></span>
<span class="keyword">template</span><span class="special"><</span>
<span class="keyword">typename</span> <a class="link" href="../ConstBufferSequence.html" title="Constant buffer sequence requirements">ConstBufferSequence</a><span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="send/overload3.html" title="basic_datagram_socket::send (3 of 3 overloads)">send</a><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">ConstBufferSequence</span> <span class="special">&</span> <span class="identifier">buffers</span><span class="special">,</span>
<span class="identifier">socket_base</span><span class="special">::</span><span class="identifier">message_flags</span> <span class="identifier">flags</span><span class="special">,</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&</span> <span class="identifier">ec</span><span class="special">);</span>
<span class="emphasis"><em>» <a class="link" href="send/overload3.html" title="basic_datagram_socket::send (3 of 3 overloads)">more...</a></em></span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2012 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="reuse_address.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_datagram_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="send/overload1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mxrrow/zaicoin | src/deps/boost/doc/html/boost_asio/reference/basic_datagram_socket/send.html | HTML | mit | 6,402 |
/*
Syntax error: Undefined variable: "$teal".
on line 124 of C:/projects/admin/documentation/sass/bootstrap/_progress-bars.scss, in `gradient-vertical'
from line 124 of C:/projects/admin/documentation/sass/bootstrap/_progress-bars.scss
from line 57 of C:/projects/admin/documentation/sass/bootstrap/bootstrap.scss
Backtrace:
C:/projects/admin/documentation/sass/bootstrap/_progress-bars.scss:124:in `gradient-vertical'
C:/projects/admin/documentation/sass/bootstrap/_progress-bars.scss:124
C:/projects/admin/documentation/sass/bootstrap/bootstrap.scss:57
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/script/variable.rb:49:in `_perform'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/script/node.rb:40:in `perform'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:259:in `block in visit_mixin'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:259:in `map'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:259:in `visit_mixin'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:37:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:100:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:53:in `map'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:53:in `visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:109:in `block in visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:121:in `with_environment'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:108:in `visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:37:in `block in visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:320:in `visit_rule'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:37:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:100:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:227:in `block in visit_import'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:227:in `map'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:227:in `visit_import'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:37:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:100:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:53:in `map'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:53:in `visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:109:in `block in visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:121:in `with_environment'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:108:in `visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:37:in `block in visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:128:in `visit_root'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/base.rb:37:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:100:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/visitors/perform.rb:7:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/tree/root_node.rb:20:in `render'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/engine.rb:315:in `_render'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.7/lib/sass/engine.rb:262:in `render'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/compiler.rb:140:in `block (2 levels) in compile'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/compiler.rb:126:in `timed'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/compiler.rb:139:in `block in compile'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/logger.rb:45:in `red'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/compiler.rb:138:in `compile'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/compiler.rb:118:in `compile_if_required'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/compiler.rb:103:in `block (2 levels) in run'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/compiler.rb:101:in `each'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/compiler.rb:101:in `block in run'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/compiler.rb:126:in `timed'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/compiler.rb:100:in `run'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/commands/watch_project.rb:147:in `recompile'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/path.rb:73:in `call'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/path.rb:73:in `run_callback'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/path.rb:55:in `callback_action'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/path.rb:31:in `create'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/state/directory.rb:26:in `block in created'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/state/directory.rb:25:in `each'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/state/directory.rb:25:in `created'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/state/directory.rb:17:in `refresh'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/backends/polling.rb:17:in `block (2 levels) in run'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/backends/polling.rb:17:in `each'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/backends/polling.rb:17:in `block in run'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/backends/polling.rb:15:in `loop'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/backends/polling.rb:15:in `run'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm/monitor.rb:26:in `run'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/fssm-0.2.10/lib/fssm.rb:70:in `monitor'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/commands/watch_project.rb:87:in `perform'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/commands/base.rb:18:in `execute'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/commands/project_base.rb:19:in `execute'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/exec/sub_command_ui.rb:43:in `perform!'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/exec/sub_command_ui.rb:15:in `run!'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/bin/compass:30:in `block in <top (required)>'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/bin/compass:44:in `call'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/bin/compass:44:in `<top (required)>'
C:/Ruby193/bin/compass:23:in `load'
C:/Ruby193/bin/compass:23:in `<main>'
*/
body:before {
white-space: pre;
font-family: monospace;
content: "Syntax error: Undefined variable: \"$teal\".\A on line 124 of C:/projects/admin/documentation/sass/bootstrap/_progress-bars.scss, in `gradient-vertical'\A from line 124 of C:/projects/admin/documentation/sass/bootstrap/_progress-bars.scss\A from line 57 of C:/projects/admin/documentation/sass/bootstrap/bootstrap.scss"; }
| iraasta/iraasta.github.io | lightbluetemplate/documentation/css/bootstrap/bootstrap.css | CSS | mit | 7,900 |
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 21.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 364.8 140.7" style="enable-background:new 0 0 364.8 140.7;" xml:space="preserve"
height="{{ include.height }}" width="{{ include.width}}">
<style type="text/css">
.white{fill:#FFFFFF;}
</style>
<g id="XMLID_14_">
<g id="XMLID_15_">
<g id="XMLID_49_">
<path id="XMLID_456_" class="white" d="M0.1,130.6c1.6-4.3,8.5-10.9,11.3-10.9c0.9,0,1.3,0.6,1.5,1.7c0.4,0.6,2.1,4.5,9.3,4.5
c7.7,0,15-5.1,17.9-13.2c8.1-22.4-37.4-23.3-23.4-61.6C25.7,26.3,62.4,0,87.9,0c14.7,0,20.2,9.6,14.9,24.2
c-7.6,20.9-39,40.6-50.5,40.6c-6.6,0-8-7-6.6-10.9c1.2-3.2,2.2-1.3,5.4-1.3c10.1,0,32.8-15.8,37.3-28.2
c2.3-6.4,0.9-10.3-6.6-10.3c-13.9,0-43,16.5-50.5,37c-10.6,29.1,35.2,29.7,23.8,61.1C49.6,127.4,32.8,140,17,140
C1,140-0.3,131.7,0.1,130.6z"/>
</g>
</g>
<path id="XMLID_16_" class="white" d="M362,113.1c-1.2,0-2.9,1.2-4.4,4c-3.2,5.8-8.5,14.3-13.5,14.3c-3.2,0-1.4-4.9-1-6.1L353,98
c2.2-6.1,2.9-13.3-5.4-13.3c-6.1,0-12.6,5.7-18.7,13.1l2.2-5.9c1.2-3.2-0.5-5.8-4.6-5.8c-1.7,0-3.6,0.9-4,2.2
c-0.3,0.9-0.1,1.7-1,4.2l-8.3,22.9c-0.4,0.5-0.8,1.1-1.1,1.8c-3.2,5.8-8.5,14.3-13.5,14.3c-3,0-3.1-3.2-2-6.1l7.9-21.8
c1.2-3.2-0.5-5.8-4.6-5.8c-1.7,0-3.6,0.9-4,2.2c-0.3,0.9-0.1,1.7-1,4.2l-7.4,20.3c-2.7,3.7-6.1,6.9-9.4,6.9c-4.3,0-5.6-4-3.1-10.8
c6.9-19,21.1-27.6,30.5-27.6c1.2,0,2.4,0.3,3.5,0.3c1.2,0,1.9-0.8,2.7-3c1.2-3.4-0.3-5.5-3.7-5.5c-15.1,0-34.4,13.5-42.4,35.5
c-0.4,1-0.7,2-0.9,3c-2.9,4.3-6.5,8.2-9.8,8.2c-3.2,0-1.4-4.9-1-6.1l9.9-27.3c2.2-6.1,3-13.3-5.1-13.3c-5.6,0-11.9,5.4-17.5,12.4
c1.9-5.9,2.2-12.4-5.3-12.4c-5.6,0-11.9,5.5-17.8,12.7l2-5.5c1.2-3.2-0.5-5.8-4.6-5.8c-1.7,0-3.6,0.9-4,2.2c-0.3,0.9-0.1,1.7-1,4.2
l-8.3,22.9c-0.4,0.5-0.8,1.1-1.1,1.8c-3.2,5.8-8.5,14.3-13.5,14.3c-2.6,0-3.5-1.8-2-6.1l15.2-41.8c6.6,0,13.9,0,23.9-0.3
c3.3-0.1,9-12.8,4.1-8.8c-8.6,0.4-17.3,0.5-24.9,0.5l8.4-23.1c1.2-3.2-0.5-5.8-4.6-5.8c-1.7,0-4.2,0.5-4.5,1.5
c-0.3,0.9,0.8,1.2-0.6,5L194.5,75c-6.7-0.1-11-0.4-11-0.4c-3.6,0-4.6,8.8-0.6,8.8c0,0,3,0.3,8.5,0.3l-12.9,35.5
c-3.3,5.6-8,12.5-12.5,12.5c-3.2,0-1.4-4.9-1-6.1l9.9-27.3c2.2-6.1,2.9-13.3-5.4-13.3c-6.1,0-12.6,5.7-18.7,13.1l2.2-5.9
c1.2-3.2-0.5-5.8-4.6-5.8c-1.7,0-3.6,0.9-4,2.2c-0.3,0.9-0.1,1.7-1,4.2l-8.3,22.9c-0.4,0.5-0.8,1.1-1.1,1.8
c-3.2,5.8-8.5,14.3-13.5,14.3c-3.2,0-1.4-4.9-1-6.1l12.2-33.5c1.2-3.2-0.5-5.8-4.6-5.8c-1.7,0-4.2,0.5-4.5,1.5
c-0.3,0.9,0.8,1.2-0.6,5l-7.7,21.3c-4.9,9.2-11.7,17.8-16.7,17.8c-3.6,0-4.3-3.8-1.7-11c4-11.1,7.5-16.9,13.3-26.7
c1.2-2,6.7-7.3,0.7-7.3c-6.6,0-6.7,2.6-8.4,4.9c0,0-10.2,15.7-15.3,29.7c-0.1,0.2-0.1,0.4-0.2,0.7c-3.1,4.8-7,9.5-10.7,9.5
c-2.6,0-3.5-1.8-2-6.1l15.2-41.8c6.6,0,13.9,0,23.9-0.3c3.3-0.1,9-12.8,4.1-8.8c-8.6,0.4-17.3,0.5-24.9,0.5l8.4-23.1
c1.2-3.2-0.5-5.8-4.6-5.8c-1.7,0-4.2,0.5-4.5,1.5c-0.3,0.9,0.8,1.2-0.6,5l-8.1,22.3c-6.7-0.1-11-0.4-11-0.4c-3.6,0-4.6,8.8-0.6,8.8
c0,0,3,0.3,8.5,0.3l-15.3,42c-3.8,10.4-0.6,14.7,6.1,14.7c5.2,0,10.1-2.9,14.4-6.8c0.6,4.4,3.3,6.9,8.2,6.9c5.5,0,10.9-4,15.9-9.5
c-1.1,5.3,1.2,9.4,6.8,9.4c4.7,0,9.2-2.3,13.1-5.7c-1.7,4.8,1.4,5.7,3.9,5.7c3.6,0,4.6-3.2,5.5-5.7l7-19.3
c4.7-10.4,16.5-21.8,20.1-21.8c2.4,0,1.4,3.4-0.1,7.5l-9.8,26.8c-2.5,6.7-0.7,12.4,5.9,12.4c5,0,9.8-2.6,13.9-6.4
c0.3,4.4,3.2,6.4,7.7,6.4c4.7,0,9.2-2.3,13.1-5.7c-1.7,4.8,1.4,5.7,3.9,5.7c3.6,0,4.6-3.2,5.5-5.7l7-19.3
c4.5-10.4,15.7-21.8,19.1-21.8c2.1,0,1.1,3.4-0.4,7.5l-12.2,33.4c-1.8,4.9,1.4,5.8,3.8,5.8c3.6,0,4.6-3.2,5.5-5.7l7-19.3
c4.5-10.4,15.7-21.8,19.1-21.8c2.1,0,1.1,3.4-0.4,7.5l-9.8,26.8c-2.5,6.7-0.7,12.4,5.9,12.4c5.3,0,10.2-2.9,14.5-6.9
c0.9,4.3,3.9,6.9,9.2,6.9c4.7,0,9.1-2.4,12.6-5.4c0.7,3.2,3.2,5.4,7.6,5.4c4.7,0,9.2-2.3,13.1-5.7c-1.7,4.8,1.4,5.7,3.9,5.7
c3.6,0,4.6-3.2,5.5-5.7l7-19.3c4.7-10.4,16.5-21.8,20.1-21.8c2.4,0,1.4,3.4-0.1,7.5l-9.8,26.8c-2.5,6.7-0.7,12.4,5.9,12.4
c10.7,0,20-11.9,25.2-20.6c0.3-0.5,0.4-0.8,0.5-0.9C365.3,116,364,113.1,362,113.1z"/>
</g>
</svg>
| khalidabuhakmeh/stuntman | docs/_includes/svg/stuntman-text-white.html | HTML | mit | 4,063 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Debug\Tests\FatalErrorHandler;
use Symfony\Component\ClassLoader\ClassLoader as SymfonyClassLoader;
use Symfony\Component\ClassLoader\UniversalClassLoader as SymfonyUniversalClassLoader;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
class ClassNotFoundFatalErrorHandlerTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider provideClassNotFoundData
*/
public function testHandleClassNotFound($error, $translatedMessage)
{
$handler = new ClassNotFoundFatalErrorHandler();
$exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line']));
$this->assertInstanceof('Symfony\Component\Debug\Exception\ClassNotFoundException', $exception);
$this->assertSame($translatedMessage, $exception->getMessage());
$this->assertSame($error['type'], $exception->getSeverity());
$this->assertSame($error['file'], $exception->getFile());
$this->assertSame($error['line'], $exception->getLine());
}
/**
* @dataProvider provideLegacyClassNotFoundData
* @group legacy
*/
public function testLegacyHandleClassNotFound($error, $translatedMessage, $autoloader)
{
// Unregister all autoloaders to ensure the custom provided
// autoloader is the only one to be used during the test run.
$autoloaders = spl_autoload_functions();
array_map('spl_autoload_unregister', $autoloaders);
spl_autoload_register($autoloader);
$handler = new ClassNotFoundFatalErrorHandler();
$exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line']));
spl_autoload_unregister($autoloader);
array_map('spl_autoload_register', $autoloaders);
$this->assertInstanceof('Symfony\Component\Debug\Exception\ClassNotFoundException', $exception);
$this->assertSame($translatedMessage, $exception->getMessage());
$this->assertSame($error['type'], $exception->getSeverity());
$this->assertSame($error['file'], $exception->getFile());
$this->assertSame($error['line'], $exception->getLine());
}
public function provideClassNotFoundData()
{
return array(
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'WhizBangFactory\' not found',
),
"Attempted to load class \"WhizBangFactory\" from the global namespace.\nDid you forget a \"use\" statement?",
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\WhizBangFactory\' not found',
),
"Attempted to load class \"WhizBangFactory\" from namespace \"Foo\\Bar\".\nDid you forget a \"use\" statement for another namespace?",
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'UndefinedFunctionException\' not found',
),
"Attempted to load class \"UndefinedFunctionException\" from the global namespace.\nDid you forget a \"use\" statement for \"Symfony\Component\Debug\Exception\UndefinedFunctionException\"?",
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'PEARClass\' not found',
),
"Attempted to load class \"PEARClass\" from the global namespace.\nDid you forget a \"use\" statement for \"Symfony_Component_Debug_Tests_Fixtures_PEARClass\"?",
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found',
),
"Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\Bar\".\nDid you forget a \"use\" statement for \"Symfony\Component\Debug\Exception\UndefinedFunctionException\"?",
),
);
}
public function provideLegacyClassNotFoundData()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$prefixes = array('Symfony\Component\Debug\Exception\\' => realpath(__DIR__.'/../../Exception'));
$symfonyAutoloader = new SymfonyClassLoader();
$symfonyAutoloader->addPrefixes($prefixes);
if (class_exists('Symfony\Component\ClassLoader\UniversalClassLoader')) {
$symfonyUniversalClassLoader = new SymfonyUniversalClassLoader();
$symfonyUniversalClassLoader->registerPrefixes($prefixes);
} else {
$symfonyUniversalClassLoader = $symfonyAutoloader;
}
return array(
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found',
),
"Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\Bar\".\nDid you forget a \"use\" statement for \"Symfony\Component\Debug\Exception\UndefinedFunctionException\"?",
array($symfonyAutoloader, 'loadClass'),
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found',
),
"Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\Bar\".\nDid you forget a \"use\" statement for \"Symfony\Component\Debug\Exception\UndefinedFunctionException\"?",
array($symfonyUniversalClassLoader, 'loadClass'),
),
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found',
),
"Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\\Bar\".\nDid you forget a \"use\" statement for another namespace?",
function ($className) { /* do nothing here */ },
),
);
}
public function testCannotRedeclareClass()
{
if (!file_exists(__DIR__.'/../FIXTURES/REQUIREDTWICE.PHP')) {
$this->markTestSkipped('Can only be run on case insensitive filesystems');
}
require_once __DIR__.'/../FIXTURES/REQUIREDTWICE.PHP';
$error = array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\RequiredTwice\' not found',
);
$handler = new ClassNotFoundFatalErrorHandler();
$exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line']));
$this->assertInstanceof('Symfony\Component\Debug\Exception\ClassNotFoundException', $exception);
}
}
| vith/symfony | src/Symfony/Component/Debug/Tests/FatalErrorHandler/ClassNotFoundFatalErrorHandlerTest.php | PHP | mit | 7,910 |
/***************************************************************************/
/* */
/* ftrfork.h */
/* */
/* Embedded resource forks accessor (specification). */
/* */
/* Copyright 2004-2015 by */
/* Masatake YAMATO and Redhat K.K. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
/***************************************************************************/
/* Development of the code in this file is support of */
/* Information-technology Promotion Agency, Japan. */
/***************************************************************************/
#ifndef __FTRFORK_H__
#define __FTRFORK_H__
#include <ft2build.h>
#include FT_INTERNAL_OBJECTS_H
FT_BEGIN_HEADER
/* Number of guessing rules supported in `FT_Raccess_Guess'. */
/* Don't forget to increment the number if you add a new guessing rule. */
#define FT_RACCESS_N_RULES 9
/* A structure to describe a reference in a resource by its resource ID */
/* and internal offset. The `POST' resource expects to be concatenated */
/* by the order of resource IDs instead of its appearance in the file. */
typedef struct FT_RFork_Ref_
{
FT_UShort res_id;
FT_Long offset;
} FT_RFork_Ref;
#ifdef FT_CONFIG_OPTION_GUESSING_EMBEDDED_RFORK
typedef FT_Error
(*ft_raccess_guess_func)( FT_Library library,
FT_Stream stream,
char *base_file_name,
char **result_file_name,
FT_Long *result_offset );
typedef enum FT_RFork_Rule_ {
FT_RFork_Rule_invalid = -2,
FT_RFork_Rule_uknown, /* -1 */
FT_RFork_Rule_apple_double,
FT_RFork_Rule_apple_single,
FT_RFork_Rule_darwin_ufs_export,
FT_RFork_Rule_darwin_newvfs,
FT_RFork_Rule_darwin_hfsplus,
FT_RFork_Rule_vfat,
FT_RFork_Rule_linux_cap,
FT_RFork_Rule_linux_double,
FT_RFork_Rule_linux_netatalk
} FT_RFork_Rule;
/* For fast translation between rule index and rule type,
* the macros FT_RFORK_xxx should be kept consistent with
* the raccess_guess_funcs table
*/
typedef struct ft_raccess_guess_rec_ {
ft_raccess_guess_func func;
FT_RFork_Rule type;
} ft_raccess_guess_rec;
#ifndef FT_CONFIG_OPTION_PIC
/* this array is a storage in non-PIC mode, so ; is needed in END */
#define CONST_FT_RFORK_RULE_ARRAY_BEGIN( name, type ) \
static const type name[] = {
#define CONST_FT_RFORK_RULE_ARRAY_ENTRY( func_suffix, type_suffix ) \
{ raccess_guess_ ## func_suffix, \
FT_RFork_Rule_ ## type_suffix },
#define CONST_FT_RFORK_RULE_ARRAY_END };
#else /* FT_CONFIG_OPTION_PIC */
/* this array is a function in PIC mode, so no ; is needed in END */
#define CONST_FT_RFORK_RULE_ARRAY_BEGIN( name, type ) \
void \
FT_Init_Table_ ## name( type* storage ) \
{ \
type* local = storage; \
\
\
int i = 0;
#define CONST_FT_RFORK_RULE_ARRAY_ENTRY( func_suffix, type_suffix ) \
local[i].func = raccess_guess_ ## func_suffix; \
local[i].type = FT_RFork_Rule_ ## type_suffix; \
i++;
#define CONST_FT_RFORK_RULE_ARRAY_END }
#endif /* FT_CONFIG_OPTION_PIC */
#endif /* FT_CONFIG_OPTION_GUESSING_EMBEDDED_RFORK */
/*************************************************************************/
/* */
/* <Function> */
/* FT_Raccess_Guess */
/* */
/* <Description> */
/* Guess a file name and offset where the actual resource fork is */
/* stored. The macro FT_RACCESS_N_RULES holds the number of */
/* guessing rules; the guessed result for the Nth rule is */
/* represented as a triplet: a new file name (new_names[N]), a file */
/* offset (offsets[N]), and an error code (errors[N]). */
/* */
/* <Input> */
/* library :: */
/* A FreeType library instance. */
/* */
/* stream :: */
/* A file stream containing the resource fork. */
/* */
/* base_name :: */
/* The (base) file name of the resource fork used for some */
/* guessing rules. */
/* */
/* <Output> */
/* new_names :: */
/* An array of guessed file names in which the resource forks may */
/* exist. If `new_names[N]' is NULL, the guessed file name is */
/* equal to `base_name'. */
/* */
/* offsets :: */
/* An array of guessed file offsets. `offsets[N]' holds the file */
/* offset of the possible start of the resource fork in file */
/* `new_names[N]'. */
/* */
/* errors :: */
/* An array of FreeType error codes. `errors[N]' is the error */
/* code of Nth guessing rule function. If `errors[N]' is not */
/* FT_Err_Ok, `new_names[N]' and `offsets[N]' are meaningless. */
/* */
FT_BASE( void )
FT_Raccess_Guess( FT_Library library,
FT_Stream stream,
char* base_name,
char** new_names,
FT_Long* offsets,
FT_Error* errors );
/*************************************************************************/
/* */
/* <Function> */
/* FT_Raccess_Get_HeaderInfo */
/* */
/* <Description> */
/* Get the information from the header of resource fork. The */
/* information includes the file offset where the resource map */
/* starts, and the file offset where the resource data starts. */
/* `FT_Raccess_Get_DataOffsets' requires these two data. */
/* */
/* <Input> */
/* library :: */
/* A FreeType library instance. */
/* */
/* stream :: */
/* A file stream containing the resource fork. */
/* */
/* rfork_offset :: */
/* The file offset where the resource fork starts. */
/* */
/* <Output> */
/* map_offset :: */
/* The file offset where the resource map starts. */
/* */
/* rdata_pos :: */
/* The file offset where the resource data starts. */
/* */
/* <Return> */
/* FreeType error code. FT_Err_Ok means success. */
/* */
FT_BASE( FT_Error )
FT_Raccess_Get_HeaderInfo( FT_Library library,
FT_Stream stream,
FT_Long rfork_offset,
FT_Long *map_offset,
FT_Long *rdata_pos );
/*************************************************************************/
/* */
/* <Function> */
/* FT_Raccess_Get_DataOffsets */
/* */
/* <Description> */
/* Get the data offsets for a tag in a resource fork. Offsets are */
/* stored in an array because, in some cases, resources in a resource */
/* fork have the same tag. */
/* */
/* <Input> */
/* library :: */
/* A FreeType library instance. */
/* */
/* stream :: */
/* A file stream containing the resource fork. */
/* */
/* map_offset :: */
/* The file offset where the resource map starts. */
/* */
/* rdata_pos :: */
/* The file offset where the resource data starts. */
/* */
/* tag :: */
/* The resource tag. */
/* */
/* sort_by_res_id :: */
/* A Boolean to sort the fragmented resource by their ids. */
/* The fragmented resources for `POST' resource should be sorted */
/* to restore Type1 font properly. For `snft' resources, sorting */
/* may induce a different order of the faces in comparison to that */
/* by QuickDraw API. */
/* */
/* <Output> */
/* offsets :: */
/* The stream offsets for the resource data specified by `tag'. */
/* This array is allocated by the function, so you have to call */
/* @ft_mem_free after use. */
/* */
/* count :: */
/* The length of offsets array. */
/* */
/* <Return> */
/* FreeType error code. FT_Err_Ok means success. */
/* */
/* <Note> */
/* Normally you should use `FT_Raccess_Get_HeaderInfo' to get the */
/* value for `map_offset' and `rdata_pos'. */
/* */
FT_BASE( FT_Error )
FT_Raccess_Get_DataOffsets( FT_Library library,
FT_Stream stream,
FT_Long map_offset,
FT_Long rdata_pos,
FT_Long tag,
FT_Bool sort_by_res_id,
FT_Long **offsets,
FT_Long *count );
FT_END_HEADER
#endif /* __FTRFORK_H__ */
/* END */
| yapingxin/saturn-gui-lib-workshop | Workshop/BestPractice/FreeTypePractice/FT_gl_M1/freetype/include/freetype/internal/ftrfork.h | C | mit | 15,151 |
/*
* Copyright (c) 2011-2014 Apple Inc. All rights reserved.
*
* @APPLE_APACHE_LICENSE_HEADER_START@
*
* 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.
*
* @APPLE_APACHE_LICENSE_HEADER_END@
*/
#ifndef __OS_OBJECT__
#define __OS_OBJECT__
#ifdef __APPLE__
#include <Availability.h>
#endif
#include <os/base.h>
/*!
* @header
*
* @preprocinfo
* By default, libSystem objects such as GCD and XPC objects are declared as
* Objective-C types when building with an Objective-C compiler. This allows
* them to participate in ARC, in RR management by the Blocks runtime and in
* leaks checking by the static analyzer, and enables them to be added to Cocoa
* collections.
*
* NOTE: this requires explicit cancellation of dispatch sources and xpc
* connections whose handler blocks capture the source/connection object,
* resp. ensuring that such captures do not form retain cycles (e.g. by
* declaring the source as __weak).
*
* To opt-out of this default behavior, add -DOS_OBJECT_USE_OBJC=0 to your
* compiler flags.
*
* This mode requires a platform with the modern Objective-C runtime, the
* Objective-C GC compiler option to be disabled, and at least a Mac OS X 10.8
* or iOS 6.0 deployment target.
*/
#ifndef OS_OBJECT_HAVE_OBJC_SUPPORT
#if defined(__OBJC__) && defined(__OBJC2__) && !defined(__OBJC_GC__) && ( \
__MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_8 || \
__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_6_0)
#define OS_OBJECT_HAVE_OBJC_SUPPORT 1
#else
#define OS_OBJECT_HAVE_OBJC_SUPPORT 0
#endif
#endif
#if OS_OBJECT_HAVE_OBJC_SUPPORT
#ifndef OS_OBJECT_USE_OBJC
#define OS_OBJECT_USE_OBJC 1
#endif
#elif defined(OS_OBJECT_USE_OBJC) && OS_OBJECT_USE_OBJC
/* Unsupported platform for OS_OBJECT_USE_OBJC=1 */
#undef OS_OBJECT_USE_OBJC
#define OS_OBJECT_USE_OBJC 0
#else
#define OS_OBJECT_USE_OBJC 0
#endif
#if OS_OBJECT_USE_OBJC
#import <objc/NSObject.h>
#if defined(__has_attribute)
#if __has_attribute(objc_independent_class)
#define OS_OBJC_INDEPENDENT_CLASS __attribute__((objc_independent_class))
#endif
#endif // __has_attribute(objc_independent_class)
#ifndef OS_OBJC_INDEPENDENT_CLASS
#define OS_OBJC_INDEPENDENT_CLASS
#endif
#define OS_OBJECT_CLASS(name) OS_##name
#define OS_OBJECT_DECL_IMPL(name, ...) \
@protocol OS_OBJECT_CLASS(name) __VA_ARGS__ \
@end \
typedef NSObject<OS_OBJECT_CLASS(name)> \
* OS_OBJC_INDEPENDENT_CLASS name##_t
#define OS_OBJECT_DECL(name, ...) \
OS_OBJECT_DECL_IMPL(name, <NSObject>)
#define OS_OBJECT_DECL_SUBCLASS(name, super) \
OS_OBJECT_DECL_IMPL(name, <OS_OBJECT_CLASS(super)>)
#if defined(__has_attribute)
#if __has_attribute(ns_returns_retained)
#define OS_OBJECT_RETURNS_RETAINED __attribute__((__ns_returns_retained__))
#else
#define OS_OBJECT_RETURNS_RETAINED
#endif
#if __has_attribute(ns_consumed)
#define OS_OBJECT_CONSUMED __attribute__((__ns_consumed__))
#else
#define OS_OBJECT_CONSUMED
#endif
#else
#define OS_OBJECT_RETURNS_RETAINED
#define OS_OBJECT_CONSUMED
#endif
#if defined(__has_feature)
#if __has_feature(objc_arc)
#define OS_OBJECT_BRIDGE __bridge
#define OS_WARN_RESULT_NEEDS_RELEASE
#else
#define OS_OBJECT_BRIDGE
#define OS_WARN_RESULT_NEEDS_RELEASE OS_WARN_RESULT
#endif
#else
#define OS_OBJECT_BRIDGE
#define OS_WARN_RESULT_NEEDS_RELEASE OS_WARN_RESULT
#endif
#ifndef OS_OBJECT_USE_OBJC_RETAIN_RELEASE
#if defined(__clang_analyzer__)
#define OS_OBJECT_USE_OBJC_RETAIN_RELEASE 1
#elif defined(__has_feature)
#if __has_feature(objc_arc)
#define OS_OBJECT_USE_OBJC_RETAIN_RELEASE 1
#else
#define OS_OBJECT_USE_OBJC_RETAIN_RELEASE 0
#endif
#else
#define OS_OBJECT_USE_OBJC_RETAIN_RELEASE 0
#endif
#endif
#else
/*! @parseOnly */
#define OS_OBJECT_RETURNS_RETAINED
/*! @parseOnly */
#define OS_OBJECT_CONSUMED
/*! @parseOnly */
#define OS_OBJECT_BRIDGE
/*! @parseOnly */
#define OS_WARN_RESULT_NEEDS_RELEASE OS_WARN_RESULT
#define OS_OBJECT_USE_OBJC_RETAIN_RELEASE 0
#endif
#define OS_OBJECT_GLOBAL_OBJECT(type, object) ((OS_OBJECT_BRIDGE type)&(object))
__BEGIN_DECLS
/*!
* @function os_retain
*
* @abstract
* Increment the reference count of an os_object.
*
* @discussion
* On a platform with the modern Objective-C runtime this is exactly equivalent
* to sending the object the -[retain] message.
*
* @param object
* The object to retain.
*
* @result
* The retained object.
*/
__OSX_AVAILABLE_STARTING(__MAC_10_12,__IPHONE_10_0)
OS_EXPORT
void*
os_retain(void *object);
#if OS_OBJECT_USE_OBJC
#undef os_retain
#define os_retain(object) [object retain]
#endif
/*!
* @function os_release
*
* @abstract
* Decrement the reference count of a os_object.
*
* @discussion
* On a platform with the modern Objective-C runtime this is exactly equivalent
* to sending the object the -[release] message.
*
* @param object
* The object to release.
*/
__OSX_AVAILABLE_STARTING(__MAC_10_12,__IPHONE_10_0)
OS_EXPORT
void
os_release(void *object);
#if OS_OBJECT_USE_OBJC
#undef os_release
#define os_release(object) [object release]
#endif
#define fastpath(x) ((typeof(x))__builtin_expect((long)(x), ~0l))
#define slowpath(x) ((typeof(x))__builtin_expect((long)(x), 0l))
__END_DECLS
#endif
| e-t-h-a-n/esdarwin | macos-10124/esdarwin-destroot-b1/System/Library/Frameworks/Kernel.framework/Versions/A/PrivateHeaders/os/object.h | C | mit | 5,646 |
require 'chunky_png'
require 'fileutils'
#COLOR_TRUE = ChunkyPNG::Color::rgba(224, 255, 255, 96) # for kunijiban
COLOR_TRUE = ChunkyPNG::Color::rgba(255, 255, 255, 0) # for ort
COLOR_FALSE = ChunkyPNG::Color::rgba(0, 0, 0, 128)
def _new_image
return ChunkyPNG::Image.new(256, 256, COLOR_FALSE)
end
def write(image, zxy)
path = "#{zxy.join('/')}.png"
FileUtils.mkdir_p(File.dirname(path)) unless File.directory?(File.dirname(path))
image.save(path)
print "wrote #{path}\n"
return _new_image
end
_new_image.save('404.png')
current = [nil, nil, nil]
last = [nil, nil, nil]
(z, x, y, u, v) = [nil, nil, nil, nil, nil]
image = _new_image
while gets
(z, x, y, u, v) = $_.strip.split(',').map{|v| v.to_i}
current = [z, x, y]
if current == last or last[0].nil?
image[u, v] = COLOR_TRUE
else
image = write(image, last)
image[u, v] = COLOR_TRUE
end
last = current
end
write(image, last)
| hfu/octpng-bin | reduce.rb | Ruby | cc0-1.0 | 916 |
###########################################################
#
# Copyright (c) 2014, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = ['ScrollbarWdg', 'TestScrollbarWdg']
from tactic.ui.common import BaseRefreshWdg
from pyasm.web import DivWdg
class TestScrollbarWdg(BaseRefreshWdg):
def get_display(my):
top = my.top
top.add_style("width: 600px")
top.add_style("height: 400px")
return top
class ScrollbarWdg(BaseRefreshWdg):
def get_display(my):
top = my.top
top.add_class("spt_scrollbar_top")
content = my.kwargs.get("content")
content_class = my.kwargs.get("content_class")
if not content_class:
content_class = "spt_content"
width = 8
top.add_style("width: %s" % width)
top.add_style("position: absolute")
top.add_style("top: 0px")
top.add_style("right: 0px")
top.add_color("background", "background")
top.add_style("margin: 3px 5px")
top.add_style("opacity: 0.0")
top.add_behavior( {
'type': 'load',
'cbjs_action': my.get_onload_js()
} )
top.add_behavior( {
'type': 'load',
'content_class': content_class,
'cbjs_action': '''
var parent = bvr.src_el.getParent("." + bvr.content_class);
var size = parent.getSize();
bvr.src_el.setStyle("height", size.y);
var scrollbar = parent.getElement(".spt_scrollbar_top");
parent.addEvent("mouseenter", function() {
new Fx.Tween(scrollbar, {duration: 250}).start("opacity", 1.0);
} );
parent.addEvent("mouseleave", function() {
new Fx.Tween(scrollbar, {duration: 250}).start("opacity", 0.0);
} );
parent.addEvent("keypress", function(evt) {
new Fx.Tween(scrollbar, {duration: 250}).start("opacity", 0.0);
console.log(evt);
} );
parent.addEvent("mousewheel", function(evt) {
evt.stopPropagation();
spt.scrollbar.content = parent;
if (evt.wheel == 1) {
spt.scrollbar.scroll(15)
}
else {
spt.scrollbar.scroll(-15)
}
} );
'''
} )
bar = DivWdg()
bar.add_class("spt_scrollbar")
bar.add_class("hand")
top.add(bar)
bar.add_style("width: %s" % width)
bar.add_style("height: 30px")
bar.add_style("border: solid 1px black")
bar.add_color("background", "background3")
#bar.add_border()
bar.add_style("border-radius: 5")
bar.add_style("position: absolute")
bar.add_style("top: 0px")
top.add_behavior( {
'type': 'smart_drag',
'bvr_match_class': 'spt_scrollbar',
'ignore_default_motion' : True,
"cbjs_setup": 'spt.scrollbar.drag_setup( evt, bvr, mouse_411 );',
"cbjs_motion": 'spt.scrollbar.drag_motion( evt, bvr, mouse_411 );'
} )
return top
def get_onload_js(my):
return r'''
spt.scrollbar = {};
spt.scrollbar.mouse_start_y = null;
spt.scrollbar.el_start_y = null;
spt.scrollbar.top = null;
spt.scrollbar.content = null;
spt.scrollbar.drag_setup = function(evt, bvr, mouse_411) {
spt.scrollbar.mouse_start_y = mouse_411.curr_y;
var src_el = spt.behavior.get_bvr_src( bvr );
var pos_y = parseInt(src_el.getStyle("top").replace("px", ""));
spt.scrollbar.el_start_y = pos_y;
spt.scrollbar.content = $("spt_SCROLL");
spt.scrollbar.top = src_el.getParent(".spt_scrollbar_top")
}
spt.scrollbar.drag_motion = function(evt, bvr, mouse_411) {
var src_el = spt.behavior.get_bvr_src( bvr );
var dy = mouse_411.curr_y - spt.scrollbar.mouse_start_y;
var pos_y = spt.scrollbar.el_start_y + dy;
if (pos_y < 0) {
return;
}
var content = spt.scrollbar.content;
var content_size = spt.scrollbar.content.getSize();
var top_size = spt.scrollbar.top.getSize();
var bar_size = src_el.getSize();
if (pos_y > top_size.y - bar_size.y - 5) {
return;
}
bvr.src_el.setStyle("top", pos_y);
//var content = bvr.src_el.getParent(".spt_content");
content.setStyle("margin-top", -dy);
}
spt.scrollbar.scroll = function(dy) {
spt.scrollbar.content = $("spt_SCROLL");
var content = spt.scrollbar.content;
var pos_y = parseInt(content.getStyle("margin-top").replace("px", ""));
content.setStyle("margin-top", pos_y + dy);
}
'''
| CeltonMcGrath/TACTIC | src/tactic/ui/widget/scrollbar_wdg.py | Python | epl-1.0 | 4,809 |
/*******************************************************************************
* Copyright (c) 2012-2015 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.actions;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.che.api.analytics.client.logger.AnalyticsEventLogger;
import org.eclipse.che.ide.Resources;
import org.eclipse.che.ide.api.action.ActionEvent;
import org.eclipse.che.ide.api.action.ProjectAction;
import org.eclipse.che.ide.api.editor.EditorAgent;
import org.eclipse.che.ide.api.editor.EditorInput;
import org.eclipse.che.ide.api.editor.EditorPartPresenter;
import org.eclipse.che.ide.api.editor.EditorWithAutoSave;
import org.eclipse.che.ide.util.loging.Log;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** @author Evgen Vidolob */
@Singleton
public class SaveAllAction extends ProjectAction {
private final EditorAgent editorAgent;
private final AnalyticsEventLogger eventLogger;
@Inject
public SaveAllAction(EditorAgent editorAgent, Resources resources, AnalyticsEventLogger eventLogger) {
super("Save All", "Save all changes for project", resources.save());
this.editorAgent = editorAgent;
this.eventLogger = eventLogger;
}
/** {@inheritDoc} */
@Override
public void actionPerformed(ActionEvent e) {
eventLogger.log(this);
Collection<EditorPartPresenter> values = editorAgent.getOpenedEditors().values();
List<EditorPartPresenter> editors = new ArrayList<>(values);
save(editors);
}
private void save(final List<EditorPartPresenter> editors) {
if (editors.isEmpty()) {
return;
}
final EditorPartPresenter editorPartPresenter = editors.get(0);
if (editorPartPresenter.isDirty()) {
editorPartPresenter.doSave(new AsyncCallback<EditorInput>() {
@Override
public void onFailure(Throwable caught) {
Log.error(SaveAllAction.class, caught);
//try to save other files
editors.remove(editorPartPresenter);
save(editors);
}
@Override
public void onSuccess(EditorInput result) {
editors.remove(editorPartPresenter);
save(editors);
}
});
} else {
editors.remove(editorPartPresenter);
save(editors);
}
}
/** {@inheritDoc} */
@Override
public void updateProjectAction(ActionEvent e) {
// e.getPresentation().setVisible(true);
boolean hasDirtyEditor = false;
for (EditorPartPresenter editor : editorAgent.getOpenedEditors().values()) {
if(editor instanceof EditorWithAutoSave) {
if (((EditorWithAutoSave)editor).isAutoSaveEnabled()) {
continue;
}
}
if (editor.isDirty()) {
hasDirtyEditor = true;
break;
}
}
e.getPresentation().setEnabledAndVisible(hasDirtyEditor);
}
}
| Ori-Libhaber/che-core | ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/actions/SaveAllAction.java | Java | epl-1.0 | 3,624 |
$_L(["$wt.widgets.Layout"],"$wt.layout.FillLayout",["$wt.graphics.Point","$wt.layout.FillData"],function(){
c$=$_C(function(){
this.type=256;
this.marginWidth=0;
this.marginHeight=0;
this.spacing=0;
$_Z(this,arguments);
},$wt.layout,"FillLayout",$wt.widgets.Layout);
$_K(c$,
function(){
$_R(this,$wt.layout.FillLayout,[]);
});
$_K(c$,
function(type){
$_R(this,$wt.layout.FillLayout,[]);
this.type=type;
},"~N");
$_V(c$,"computeSize",
function(composite,wHint,hHint,flushCache){
var children=composite.getChildren();
var count=children.length;
var maxWidth=0;
var maxHeight=0;
for(var i=0;i<count;i++){
var child=children[i];
var w=wHint;
var h=hHint;
if(count>0){
if(this.type==256&&wHint!=-1){
w=Math.max(0,Math.floor((wHint-(count-1)*this.spacing)/count));
}if(this.type==512&&hHint!=-1){
h=Math.max(0,Math.floor((hHint-(count-1)*this.spacing)/count));
}}var size=this.computeChildSize(child,w,h,flushCache);
maxWidth=Math.max(maxWidth,size.x);
maxHeight=Math.max(maxHeight,size.y);
}
var width=0;
var height=0;
if(this.type==256){
width=count*maxWidth;
if(count!=0)width+=(count-1)*this.spacing;
height=maxHeight;
}else{
width=maxWidth;
height=count*maxHeight;
if(count!=0)height+=(count-1)*this.spacing;
}width+=this.marginWidth*2;
height+=this.marginHeight*2;
if(wHint!=-1)width=wHint;
if(hHint!=-1)height=hHint;
return new $wt.graphics.Point(width,height);
},"$wt.widgets.Composite,~N,~N,~B");
$_M(c$,"computeChildSize",
function(control,wHint,hHint,flushCache){
var data=control.getLayoutData();
if(data==null){
data=new $wt.layout.FillData();
control.setLayoutData(data);
}var size=null;
if(wHint==-1&&hHint==-1){
size=data.computeSize(control,wHint,hHint,flushCache);
}else{
var trimX;
var trimY;
if($_O(control,$wt.widgets.Scrollable)){
var rect=(control).computeTrim(0,0,0,0);
trimX=rect.width;
trimY=rect.height;
}else{
trimX=trimY=control.getBorderWidth()*2;
}var w=wHint==-1?wHint:Math.max(0,wHint-trimX);
var h=hHint==-1?hHint:Math.max(0,hHint-trimY);
size=data.computeSize(control,w,h,flushCache);
}return size;
},"$wt.widgets.Control,~N,~N,~B");
$_V(c$,"flushCache",
function(control){
var data=control.getLayoutData();
if(data!=null)(data).flushCache();
return true;
},"$wt.widgets.Control");
$_M(c$,"getName",
function(){
var string=this.getClass().getName();
var index=string.lastIndexOf('.');
if(index==-1)return string;
return string.substring(index+1,string.length);
});
$_V(c$,"layout",
function(composite,flushCache){
var rect=composite.getClientArea();
var children=composite.getChildren();
var count=children.length;
if(count==0)return;
var width=rect.width-this.marginWidth*2;
var height=rect.height-this.marginHeight*2;
if(this.type==256){
width-=(count-1)*this.spacing;
var x=rect.x+this.marginWidth;
var extra=width%count;
var y=rect.y+this.marginHeight;
var cellWidth=Math.floor(width/count);
for(var i=0;i<count;i++){
var child=children[i];
var childWidth=cellWidth;
if(i==0){
childWidth+=Math.floor(extra/2);
}else{
if(i==count-1)childWidth+=Math.floor((extra+1)/2);
}child.setBounds(x,y,childWidth,height);
x+=childWidth+this.spacing;
}
}else{
height-=(count-1)*this.spacing;
var x=rect.x+this.marginWidth;
var cellHeight=Math.floor(height/count);
var y=rect.y+this.marginHeight;
var extra=height%count;
for(var i=0;i<count;i++){
var child=children[i];
var childHeight=cellHeight;
if(i==0){
childHeight+=Math.floor(extra/2);
}else{
if(i==count-1)childHeight+=Math.floor((extra+1)/2);
}child.setBounds(x,y,width,childHeight);
y+=childHeight+this.spacing;
}
}},"$wt.widgets.Composite,~B");
$_V(c$,"toString",
function(){
var string=this.getName()+"{";
string+="type="+((this.type==512)?"SWT.VERTICAL":"SWT.HORIZONTAL")+" ";
if(this.marginWidth!=0)string+="marginWidth="+this.marginWidth+" ";
if(this.marginHeight!=0)string+="marginHeight="+this.marginHeight+" ";
if(this.spacing!=0)string+="spacing="+this.spacing+" ";
string=string.trim();
string+="}";
return string;
});
});
| 01org/mayloon-portingtool | sources/net.sf.j2s.lib/j2slib/org/eclipse/swt/layout/FillLayout.js | JavaScript | epl-1.0 | 4,054 |
/*
* Created on May 13, 2003
*========================================================================
* Modifications history
*========================================================================
* $Log: PredicateWordRule.java,v $
* Revision 1.2 2003/05/30 20:53:09 agfitzp
* 0.0.2 : Outlining is now done as the user types. Some other bug fixes.
*
*========================================================================
*/
package net.sourceforge.jseditor.editors;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IPredicateRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.rules.WordRule;
import org.eclipse.jface.text.rules.IWordDetector;
/**
* @author fitzpata
*/
public class PredicateWordRule extends WordRule implements IPredicateRule {
/* (non-Javadoc)
* @see org.eclipse.jface.text.rules.IPredicateRule#getSuccessToken()
*/
protected IToken successToken = Token.UNDEFINED;
public void addWords(String[] tokens, IToken token)
{
for (int i = 0; i < tokens.length; i++) {
addWord(tokens[i], token);
}
}
public IToken getSuccessToken() {
return successToken;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.rules.IPredicateRule#evaluate(org.eclipse.jface.text.rules.ICharacterScanner, boolean)
*/
public IToken evaluate(ICharacterScanner scanner, boolean resume) {
successToken = this.evaluate(scanner, resume);//true);
return successToken;
}
/**
* Creates a rule which, with the help of an word detector, will return the token
* associated with the detected word. If no token has been associated, the scanner
* will be rolled back and an undefined token will be returned in order to allow
* any subsequent rules to analyze the characters.
*
* @param detector the word detector to be used by this rule, may not be <code>null</code>
*
* @see #addWord
*/
public PredicateWordRule(IWordDetector detector) {
super(detector);
}
/**
* Creates a rule which, with the help of an word detector, will return the token
* associated with the detected word. If no token has been associated, the
* specified default token will be returned.
*
* @param detector the word detector to be used by this rule, may not be <code>null</code>
* @param defaultToken the default token to be returned on success
* if nothing else is specified, may not be <code>null</code>
*
* @see #addWord
*/
public PredicateWordRule(IWordDetector detector, IToken defaultToken) {
super(detector, defaultToken);
}
public PredicateWordRule(IWordDetector detector, String tokenString, IToken tokenType) {
super(detector);
this.addWord(tokenString, tokenType);
}
public PredicateWordRule(IWordDetector detector, String[] tokens, IToken tokenType) {
super(detector);
this.addWords(tokens, tokenType);
}
public PredicateWordRule(IWordDetector detector, IToken defaultToken, String[] tokens, IToken tokenType) {
super(detector, defaultToken);
this.addWords(tokens, tokenType);
}
}
| royleexhFake/mayloon-portingtool | net.sourceforge.jseditor/src-jseditor/net/sourceforge/jseditor/editors/PredicateWordRule.java | Java | epl-1.0 | 3,101 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>About EclipseLink 2.6</title>
</head>
<body lang="EN-US">
<h1>EclipseLink 2.6</h1>
<h2>Eclipse Kepler simultaneous release</h2>
<p>Target Date - June 2013</p>
<h2>About</h2>
<p>The <a href="http://www.eclipse.org/eclipselink">EclipseLink</a> project's
goal is to provide a complete persistence framework that is both comprehensive
and universal. It will run in any Java environment and read and write objects
to virtually any type of data source, including relational databases, and XML.
EclipseLink will focus on providing leading edge support, including advanced
feature extensions, for the dominant persistence standards for each target data
source; Java Persistence API (JPA) for relational databases, Java API for XML
Binding (JAXB) for XML, Service Data Objects (SDO), and Database Web services
(DBWS). </p>
<p>For tips on getting started with EclipseLink, please see the following resources:
</p>
<ul>
<li> <a href="http://www.eclipse.org/eclipselink/releases/2.6.php">EclipseLink 2.6 Release Notes</a></li>
<li> <a href="http://www.eclipse.org/eclipselink/documentation">Documentation</a></li>
<li> <a href="http://wiki.eclipse.org/EclipseLink/Examples">Examples and How To</a></li>
</ul>
<h2>License </h2>
<p>The Eclipse Foundation makes available all content in this plug-in ("Content").
Unless otherwise indicated below, the Content is provided to you under the terms
and conditions of the Eclipse Public License Version 1.0 ("EPL") and
Eclipse Distribution License Version 1.0 (EDL). A copy of the EPL is available at
<a href="http://www.eclipse.org/legal/epl-v10.html"> http://www.eclipse.org/legal/epl-v10.html</a>
and a copy of the EDL is available at <a href="http://www.eclipse.org/org/documents/edl-v10.php">
http://www.eclipse.org/org/documents/edl-v10.php</a>. For purposes of the EPL, "Program"
will mean the Content.</p>
<p>If you did not receive this Content directly from the Eclipse Foundation, the
Content is being redistributed by another party ("Redistributor")
and different terms and conditions may apply to your use of any object code
in the Content. Check the Redistributor’s license that was provided with
the Content. If no such license exists, contact the Redistributor. Unless otherwise
indicated below, the terms and conditions of the EPL and EDL still apply to any source
code in the Content and such source code may be obtained at <a href="http://www.eclipse.org">http://www.eclipse.org</a>.</p>
<h2>Third Party Content</h2>
<p>The Content includes items that have been sourced from third parties as set
out below. If you did not receive this Content directly from the Eclipse Foundation,
the following is provided for informational purposes only, and you should look
to the Redistributor’s license for terms and conditions of use.</p>
<ul>
<li>Foundation Dependencies
<ul>
<li><a href="#ASM">ASM</a></li>
<li><a href="#JSON">Java API for JSON Processing - Reference Implementation</a></li>
</ul>
</li>
<li>EclipseLink JPA
<ul>
<li><a href="#ANTLR">ANTLR</a></li>
<li><a href="#JPA21">Java Persistence API (JPA) 2.1</a></li>
<li><a href="#JSON">Java API for JSON Processing - Reference Implementation</a></li>
</ul>
</li>
<li>EclipseLink MOXy
<ul>
<li><a href="#JAXB">Java Architecture for XML Binding (JAXB)</a></li>
<li><a href="#MAIL">Java Mail</a></li>
<li><a href="#JSON">Java API for JSON Processing - Reference Implementation</a></li>
</ul>
</li>
<li>EclipseLink SDO
<ul>
<li><a href="#SDO">Service Data Objects (SDO)</a></li>
</ul>
</li>
<li>EclipseLink DBWS
<ul>
<li><a href="#Servlet">Java Servlet 2.4 (or higher)</a></li>
</ul>
</li>
<li>Utilities
<ul>
<li><a href="#JCA">Java Connector</a></li>
<li><a href="#XERCES">Xerces</a></li>
<li><a href="#WSDL4J">WSDL4J 1.6.2 </a></li>
</ul>
</li>
</ul>
<hr />
<h3><a name="ASM" id="ASM"></a>ASM v5.0.1</h3>
<blockquote>
<p>The EclipseLink Project includes ASM for the purpose of
byte code weaving. The AMS library is re-packaged within the source of the
project (org.persistence.eclipse.internal.libraries.asm.*) to avoid version
collisions with other usage of ASM.
</p>
<p>The source code is available within the project's git repository.
The binaries are distributed within the eclipselink.jar and in the org.eclipse.persistence.asm_*.jar
bundle. </p>
<p> <a href="http://asm.objectweb.org/license.html">http://asm.objectweb.org/license.html</a></p>
<p>Copyright (c) 2000-2005 INRIA, France Telecom, All rights reserved.</p>
<p>Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:</p>
<ol>
<li> Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.</li>
<li> 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.</li>
<li> Neither the name of the copyright holders nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.</li>
</ol>
<p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSEARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BELIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, ORCONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OFSUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER INCONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OFTHE POSSIBILITY OF SUCH DAMAGE.</p>
</blockquote>
<h3><a name="ANTLR" id="ANTLR"></a>ANTLR v3.5.2</h3>
<blockquote>
<p>The <a href="http://www.antlr.org/">ANTLR library</a> (<a href="http://www.antlr.org/license.html">license</a>)
is included within EclipseLink Project to enable parsing of the Java Persistence
Query language (JP QL). The ANTLR library is re-packaged within the project
in the org.eclipse.persistence.internal.libraries.antlr.* packages. </p>
<p>The source is available with the project's git repository. The binaries
are distributed within the eclipselink.jar and in the org.eclipse.persistence.antlr_3.5.2.v*.jar
bundle.</p>
</blockquote>
<h3><a name="JSON" id="JSON"></a>JSON Processing v1.0.4</h3>
<blockquote>
<p>The <a href="https://jsonp.java.net">JSON Processing</a> (<a href="https://jsonp.java.net/license.html">license</a>)
is included within EclipseLink Project to enable parsing of JSON files.</p>
<p>The source is available with the project's git repository.</p>
</blockquote>
<h3><a name="JAXB" id="JAXB"></a>Java Architecture for XML Binding (JAXB) v2.2</h3>
<blockquote>
<p>The <a href="http://jaxb.java.net">JAXB libraries</a> distributed
under <a href="http://glassfish.dev.java.net/public/CDDLv1.0.html">CDDL v1.0</a>
are included within the EclipseLink Project to enable the MOXy component's
implementation of JAXB.</p>
<p>JAXB Libraries: </p>
<ul>
<li>javax.xml.bind_2.2.12.v201410011542.jar</li>
<li>jaxb-core_2.2.11.v201407311112.jar</li>
<li>jaxb-xjc_2.2.11.v201407311112.jar</li>
</ul>
</blockquote>
<h3><a name="JPA21" id="JPA2"></a>Java Persistence (JPA) 2.1 </h3>
<blockquote>
<p>EclipseLink is the Java Persistence (JPA) 2.1 Reference Implementation
(<a href="http://jcp.org/en/jsr/detail?id=338">JSR 338</a>). The JPA 2.1
specification API is included in EclipseLink under the <a href="http://www.eclipse.org/legal/epl-v10.html">EPL</a> and <a href="http://www.eclipse.org/org/documents/edl-v10.php">EDL</a> licenses.</p>
</blockquote>
<h3><a name="MAIL" id="MAIL"></a>Java Mail v1.4.0</h3>
<blockquote>
<p>The Java Mail library (mail.jar) can be downloaded from <a href="http://java.sun.com/products/javamail/javamail-1_4.html">java.sun.com</a>
under <a href="http://glassfish.dev.java.net/public/CDDLv1.0.html">CDDL
v1.0</a> and is included within the EclipseLink Project distribution
to support Web Services attachment handling in the MOXy component. It is only
required when using Java SE 5 (Java Mail is included in Java SE 6).</p>
</blockquote>
<h3><a name="SDO" id="SDO"></a>Service Data Objects (SDO) v2.1.1</h3>
<blockquote>
<p>The <a href="http://jcp.org/aboutJava/communityprocess/pr/jsr235/index.html">Service
Data Objects (SDO) API</a> is distributed under a <a href="http://glassfish.dev.java.net/public/CDDLv1.0.html"> CDDLv1.0 </a> and <a href="http://jcp.org/aboutJava/communityprocess/pr/jsr235/index.html">custom
license</a>. It provides the standard API implemented by the EclipseLink Project's SDO component.</p>
</blockquote>
<h3><a name="JCA" id="JCA"></a>Java Connector v1.5</h3>
<blockquote>
<p>The JCA 1.5 API is distributed under <a href="http://glassfish.dev.java.net/public/CDDLv1.0.html">
CDDLv1.0 </a>. </p>
<p>This jar is being shipped and required by the Workbench only. When using
EclipseLink in a container where JCA integration is required that container
will provide the necessary API libraries.</p>
</blockquote>
<h3><a name="XERCES" id="XERCES"></a>Xerces v2.9.0</h3>
<blockquote>
<p>Xerces 2.9.0 is available from <a href="http://xerces.apache.org/xerces-j/">
the Xerces home page</a>. It is distributed under <a href="http://ant.apache.org/license.html">
Apache 2.0</a>.</p>
<p>This jar is shipped for the Workbench's use only in the reading and writing
of XML configuration files.</p>
</blockquote>
<h3><a name="SERVLET" id="SERVLET"></a>Java Servlet 2.4</h3>
<blockquote>
<p>The <a href="http://jcp.org/aboutJava/communityprocess/final/jsr154/index.html">Java Servlet 2.4 specification</a>
is distributed under the <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache 2.0 license</a>. The source code is part of the <a href="http://svn.apache.org/repos/asf/tomcat/trunk/java/javax/servlet/">Apache Tomcat project</a>
<p>This jar is only required at design time for the DBWS Builder utility.</p>
</blockquote>
<h3><a name="WSDL4J" id="WSDL4J"></a>WSDL4j v1.6.2</h3>
<blockquote>
<p>WSDL4J 1.6.2 is available for download from the <a href="http://sourceforge.net/projects/wsdl4j">wsdl4j
project</a>. It distributed under <a href="http://opensource.org/licenses/cpl1.0.php">
CPLv1.0 </a>. </p>
<p>This jar is only required at design time for the DBWS Builder utility.</p>
</blockquote>
<p></p>
</body>
</html>
| RallySoftware/eclipselink.runtime | buildsystem/org.eclipse.persistence.parent/resource/about.html | HTML | epl-1.0 | 11,359 |
/*******************************************************************************
* Copyright (c) 2012-2015 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.core.util;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/** @author andrew00x */
public class ProcessUtilTest {
@Test
public void testKill() throws Exception {
final Process p = Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c", "sleep 10; echo wake\\ up"});
final List<String> stdout = new ArrayList<>();
final List<String> stderr = new ArrayList<>();
final IOException[] processError = new IOException[1];
final CountDownLatch latch = new CountDownLatch(1);
final long start = System.currentTimeMillis();
new Thread() {
public void run() {
try {
ProcessUtil.process(p,
new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
stdout.add(line);
}
@Override
public void close() throws IOException {
}
},
new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
stderr.add(line);
}
@Override
public void close() throws IOException {
}
}
);
} catch (IOException e) {
processError[0] = e; // throw when kill process
} finally {
latch.countDown();
}
}
}.start();
Thread.sleep(1000); // give time to start process
Assert.assertTrue(ProcessUtil.isAlive(p), "Process is not started.");
ProcessUtil.kill(p); // kill process
latch.await(15, TimeUnit.SECONDS); // should not stop here if process killed
final long end = System.currentTimeMillis();
// System process sleeps 10 seconds. It is safety to check we done in less then 3 sec.
Assert.assertTrue((end - start) < 3000, "Fail kill process");
System.out.println(processError[0]);
//processError[0].printStackTrace();
System.out.println(stdout);
System.out.println(stderr);
}
}
| aljiru/che-core | platform-api/che-core-api-core/src/test/java/org/eclipse/che/api/core/util/ProcessUtilTest.java | Java | epl-1.0 | 3,462 |
/**
* Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.python.pydev.refactoring.wizards.rename.visitors;
import java.util.Stack;
import org.python.pydev.parser.jython.SimpleNode;
import org.python.pydev.parser.jython.Visitor;
import org.python.pydev.parser.jython.ast.Call;
import org.python.pydev.parser.jython.ast.Name;
import org.python.pydev.parser.jython.ast.NameTok;
/**
* This visitor is used to find a call given its ast
*
* @author Fabio
*/
public class FindCallVisitor extends Visitor {
private Name name;
private NameTok nameTok;
private Call call;
private Stack<Call> lastCall = new Stack<Call>();
public FindCallVisitor(Name name) {
this.name = name;
}
public FindCallVisitor(NameTok nameTok) {
this.nameTok = nameTok;
}
public Call getCall() {
return call;
}
@Override
public Object visitCall(Call node) throws Exception {
if (this.call != null) {
return null;
}
if (node.func == name) {
//check the name (direct)
this.call = node;
} else if (nameTok != null) {
//check the name tok (inside of attribute)
lastCall.push(node);
Object r = super.visitCall(node);
lastCall.pop();
if (this.call != null) {
return null;
}
return r;
}
if (this.call != null) {
return null;
}
return super.visitCall(node);
}
@Override
public Object visitNameTok(NameTok node) throws Exception {
if (node == nameTok) {
if (lastCall.size() > 0) {
call = lastCall.peek();
}
return null;
}
return super.visitNameTok(node);
}
public static Call findCall(NameTok nametok, SimpleNode root) {
FindCallVisitor visitor = new FindCallVisitor(nametok);
try {
visitor.traverse(root);
} catch (Exception e) {
throw new RuntimeException(e);
}
return visitor.call;
}
public static Call findCall(Name name, SimpleNode root) {
FindCallVisitor visitor = new FindCallVisitor(name);
try {
visitor.traverse(root);
} catch (Exception e) {
throw new RuntimeException(e);
}
return visitor.call;
}
}
| rgom/Pydev | plugins/com.python.pydev.refactoring/src/com/python/pydev/refactoring/wizards/rename/visitors/FindCallVisitor.java | Java | epl-1.0 | 2,648 |
package com.intel.ide.eclipse.mpt.classpath;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import com.intel.ide.eclipse.mpt.launching.J2SCyclicProjectUtils;
public class ContactedClasses extends Resource implements IExternalResource, IClasspathContainer {
private String binRelativePath;
private List classList;
private List externalList;
public void load() {
File file = getAbsoluteFile();
classList = new ArrayList();
externalList = new ArrayList();
if (file.exists()) {
Properties props = PathUtil.loadJZ(file);
String[] reses = PathUtil.getResources(props);
binRelativePath = props.getProperty(PathUtil.J2S_OUTPUT_PATH);
for (int i = 0; i < reses.length; i++) {
if (reses[i] != null) {
String res = reses[i].trim();
if (res.endsWith(".z.js")) {
ContactedClasses jz = new ContactedClasses();
jz.setFolder(this.getAbsoluteFolder());
jz.setRelativePath(res);
jz.setParent(this);
externalList.add(jz);
} else if (res.endsWith(".js")) {
ContactedUnitClass unit = new ContactedUnitClass();
unit.setFolder(this.getAbsoluteFolder());
unit.setRelativePath(res);
unit.parseClassName();
unit.setParent(this);
classList.add(unit);
} else if (res.endsWith(".css")) {
CSSResource css = new CSSResource();
css.setFolder(this.getAbsoluteFolder());
css.setRelativePath(res);
css.setParent(this);
externalList.add(css);
}
}
}
}
}
public void store(Properties props) {
Resource[] reses = getChildren();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < reses.length; i++) {
String str = reses[i].toResourceString();
buf.append(str);
if (i != reses.length - 1) {
buf.append(",");
}
}
props.setProperty(PathUtil.J2S_RESOURCES_LIST, buf.toString());
props.setProperty(PathUtil.J2S_OUTPUT_PATH, binRelativePath);
}
public Resource[] getChildren() {
if (externalList == null || classList == null) {
this.load();
}
int size = externalList.size();
Resource[] res = new Resource[classList.size() + size];
for (int i = 0; i < size; i++) {
res[i] = (Resource) externalList.get(i);
}
for (int i = 0; i < classList.size(); i++) {
res[i + size] = (Resource) classList.get(i);
}
return res;
}
public ContactedUnitClass[] getClasses() {
return (ContactedUnitClass[]) classList.toArray(new ContactedClasses[0]);
}
public IExternalResource[] getExternals() {
return (IExternalResource[]) externalList.toArray(new IExternalResource[0]);
}
public String getBinRelativePath() {
return binRelativePath;
}
public void setBinRelativePath(String binRelativePath) {
this.binRelativePath = binRelativePath;
}
public String toHTMLString() {
if (getRelativePath() != null && getRelativePath().endsWith(".j2x")) {
return "";
}
Resource p = this.getParent();
if (p != null) {
if (p instanceof ContactedClasses) {
Resource pp = p.getParent();
if (pp != null && pp instanceof ContactedClasses) {
return "";
}
}
}
StringBuffer buf = new StringBuffer();
if (externalList == null) {
this.load();
}
for (Iterator iter = externalList.iterator(); iter.hasNext();) {
Resource res = (Resource) iter.next();
if (!J2SCyclicProjectUtils.visit(res)) {
continue;
}
buf.append(res.toHTMLString());
}
buf.append("<script type=\"text/javascript\" src=\"");
String binFolder = getBinRelativePath();
if (binFolder != null) {
String binPath = binFolder.trim();
if (binPath.length() != 0) {
buf.append(binPath);
if (!binPath.endsWith("/")) {
buf.append("/");
}
}
}
if (p != null) {
if (p instanceof ContactedClasses) {
ContactedClasses cc = (ContactedClasses) p;
String path = cc.getRelativePath();
int idx = path.lastIndexOf('/');
if (idx != -1) {
buf.append(path.substring(0, idx + 1));
}
} else if (p instanceof CompositeResources) {
CompositeResources cc = (CompositeResources) p;
String binRelative = cc.getBinRelativePath();
if (binRelative != null) {
if (binRelative.length() != 0 && getRelativePath().endsWith(".z.js")) {
return "";
}
buf.append(binRelative);
}
}
}
buf.append(getRelativePath());
buf.append("\"></script>\r\n");
return buf.toString();
}
public String toJ2XString() {
if (getName().endsWith(".j2x")) {
try {
return getAbsoluteFile().getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
public int getType() {
return CONTAINER;
}
}
| royleexhFake/mayloon-portingtool | com.intel.ide.eclipse.mpt/src/com/intel/ide/eclipse/mpt/classpath/ContactedClasses.java | Java | epl-1.0 | 4,878 |
/****************************************************************************
**
** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved.
**
** This file is part of the qmake spec of the Qt Toolkit.
**
** This file may be used under the terms of the GNU General Public
** License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Alternatively you may (at
** your option) use any later version of the GNU General Public
** License if such license has been publicly approved by Trolltech ASA
** (or its successors, if any) and the KDE Free Qt Foundation. In
** addition, as a special exception, Trolltech gives you certain
** additional rights. These rights are described in the Trolltech GPL
** Exception version 1.2, which can be found at
** http://www.trolltech.com/products/qt/gplexception/ and in the file
** GPL_EXCEPTION.txt in this package.
**
** Please review the following information to ensure GNU General
** Public Licensing requirements will be met:
** http://trolltech.com/products/qt/licenses/licensing/opensource/. If
** you are unsure which license is appropriate for your use, please
** review the following information:
** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
** or contact the sales department at sales@trolltech.com.
**
** In addition, as a special exception, Trolltech, as the sole
** copyright holder for Qt Designer, grants users of the Qt/Eclipse
** Integration plug-in the right for the Qt/Eclipse Integration to
** link to functionality provided by Qt Designer and its related
** libraries.
**
** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly
** granted herein.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#include "../linux-g++/qplatformdefs.h"
| muromec/qtopia-ezx | qtopiacore/qt/mkspecs/linux-icc/qplatformdefs.h | C | gpl-2.0 | 2,177 |
/*
*
* arch/arm/mach-u300/core.c
*
*
* Copyright (C) 2007-2010 ST-Ericsson SA
* License terms: GNU General Public License (GPL) version 2
* Core platform support, IRQ handling and device definitions.
* Author: Linus Walleij <linus.walleij@stericsson.com>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/bitops.h>
#include <linux/device.h>
#include <linux/mm.h>
#include <linux/termios.h>
#include <linux/dmaengine.h>
#include <linux/amba/bus.h>
#include <linux/amba/mmci.h>
#include <linux/amba/serial.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/fsmc.h>
#include <linux/pinctrl/machine.h>
#include <linux/pinctrl/consumer.h>
#include <linux/pinctrl/pinconf-generic.h>
#include <linux/dma-mapping.h>
#include <asm/types.h>
#include <asm/setup.h>
#include <asm/memory.h>
#include <asm/hardware/vic.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/coh901318.h>
#include <mach/hardware.h>
#include <mach/syscon.h>
#include <mach/dma_channels.h>
#include <mach/gpio-u300.h>
#include "clock.h"
#include "spi.h"
#include "i2c.h"
#include "u300-gpio.h"
/*
* Static I/O mappings that are needed for booting the U300 platforms. The
* only things we need are the areas where we find the timer, syscon and
* intcon, since the remaining device drivers will map their own memory
* physical to virtual as the need arise.
*/
static struct map_desc u300_io_desc[] __initdata = {
{
.virtual = U300_SLOW_PER_VIRT_BASE,
.pfn = __phys_to_pfn(U300_SLOW_PER_PHYS_BASE),
.length = SZ_64K,
.type = MT_DEVICE,
},
{
.virtual = U300_AHB_PER_VIRT_BASE,
.pfn = __phys_to_pfn(U300_AHB_PER_PHYS_BASE),
.length = SZ_32K,
.type = MT_DEVICE,
},
{
.virtual = U300_FAST_PER_VIRT_BASE,
.pfn = __phys_to_pfn(U300_FAST_PER_PHYS_BASE),
.length = SZ_32K,
.type = MT_DEVICE,
},
};
void __init u300_map_io(void)
{
iotable_init(u300_io_desc, ARRAY_SIZE(u300_io_desc));
/* We enable a real big DMA buffer if need be. */
init_consistent_dma_size(SZ_4M);
}
/*
* Declaration of devices found on the U300 board and
* their respective memory locations.
*/
static struct amba_pl011_data uart0_plat_data = {
#ifdef CONFIG_COH901318
.dma_filter = coh901318_filter_id,
.dma_rx_param = (void *) U300_DMA_UART0_RX,
.dma_tx_param = (void *) U300_DMA_UART0_TX,
#endif
};
/* Slow device at 0x3000 offset */
static AMBA_APB_DEVICE(uart0, "uart0", 0, U300_UART0_BASE,
{ IRQ_U300_UART0 }, &uart0_plat_data);
/* The U335 have an additional UART1 on the APP CPU */
#ifdef CONFIG_MACH_U300_BS335
static struct amba_pl011_data uart1_plat_data = {
#ifdef CONFIG_COH901318
.dma_filter = coh901318_filter_id,
.dma_rx_param = (void *) U300_DMA_UART1_RX,
.dma_tx_param = (void *) U300_DMA_UART1_TX,
#endif
};
/* Fast device at 0x7000 offset */
static AMBA_APB_DEVICE(uart1, "uart1", 0, U300_UART1_BASE,
{ IRQ_U300_UART1 }, &uart1_plat_data);
#endif
/* AHB device at 0x4000 offset */
static AMBA_APB_DEVICE(pl172, "pl172", 0, U300_EMIF_CFG_BASE, { }, NULL);
/* Fast device at 0x6000 offset */
static AMBA_APB_DEVICE(pl022, "pl022", 0, U300_SPI_BASE,
{ IRQ_U300_SPI }, NULL);
/* Fast device at 0x1000 offset */
#define U300_MMCSD_IRQS { IRQ_U300_MMCSD_MCIINTR0, IRQ_U300_MMCSD_MCIINTR1 }
static struct mmci_platform_data mmcsd_platform_data = {
/*
* Do not set ocr_mask or voltage translation function,
* we have a regulator we can control instead.
*/
.f_max = 24000000,
.gpio_wp = -1,
.gpio_cd = U300_GPIO_PIN_MMC_CD,
.cd_invert = true,
.capabilities = MMC_CAP_MMC_HIGHSPEED |
MMC_CAP_SD_HIGHSPEED | MMC_CAP_4_BIT_DATA | MMC_CAP_8_BIT_DATA,
#ifdef CONFIG_COH901318
.dma_filter = coh901318_filter_id,
.dma_rx_param = (void *) U300_DMA_MMCSD_RX_TX,
/* Don't specify a TX channel, this RX channel is bidirectional */
#endif
};
static AMBA_APB_DEVICE(mmcsd, "mmci", 0, U300_MMCSD_BASE,
U300_MMCSD_IRQS, &mmcsd_platform_data);
/*
* The order of device declaration may be important, since some devices
* have dependencies on other devices being initialized first.
*/
static struct amba_device *amba_devs[] __initdata = {
&uart0_device,
#ifdef CONFIG_MACH_U300_BS335
&uart1_device,
#endif
&pl022_device,
&pl172_device,
&mmcsd_device,
};
/* Here follows a list of all hw resources that the platform devices
* allocate. Note, clock dependencies are not included
*/
static struct resource gpio_resources[] = {
{
.start = U300_GPIO_BASE,
.end = (U300_GPIO_BASE + SZ_4K - 1),
.flags = IORESOURCE_MEM,
},
{
.name = "gpio0",
.start = IRQ_U300_GPIO_PORT0,
.end = IRQ_U300_GPIO_PORT0,
.flags = IORESOURCE_IRQ,
},
{
.name = "gpio1",
.start = IRQ_U300_GPIO_PORT1,
.end = IRQ_U300_GPIO_PORT1,
.flags = IORESOURCE_IRQ,
},
{
.name = "gpio2",
.start = IRQ_U300_GPIO_PORT2,
.end = IRQ_U300_GPIO_PORT2,
.flags = IORESOURCE_IRQ,
},
#if defined(CONFIG_MACH_U300_BS365) || defined(CONFIG_MACH_U300_BS335)
{
.name = "gpio3",
.start = IRQ_U300_GPIO_PORT3,
.end = IRQ_U300_GPIO_PORT3,
.flags = IORESOURCE_IRQ,
},
{
.name = "gpio4",
.start = IRQ_U300_GPIO_PORT4,
.end = IRQ_U300_GPIO_PORT4,
.flags = IORESOURCE_IRQ,
},
#endif
#ifdef CONFIG_MACH_U300_BS335
{
.name = "gpio5",
.start = IRQ_U300_GPIO_PORT5,
.end = IRQ_U300_GPIO_PORT5,
.flags = IORESOURCE_IRQ,
},
{
.name = "gpio6",
.start = IRQ_U300_GPIO_PORT6,
.end = IRQ_U300_GPIO_PORT6,
.flags = IORESOURCE_IRQ,
},
#endif /* CONFIG_MACH_U300_BS335 */
};
static struct resource keypad_resources[] = {
{
.start = U300_KEYPAD_BASE,
.end = U300_KEYPAD_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "coh901461-press",
.start = IRQ_U300_KEYPAD_KEYBF,
.end = IRQ_U300_KEYPAD_KEYBF,
.flags = IORESOURCE_IRQ,
},
{
.name = "coh901461-release",
.start = IRQ_U300_KEYPAD_KEYBR,
.end = IRQ_U300_KEYPAD_KEYBR,
.flags = IORESOURCE_IRQ,
},
};
static struct resource rtc_resources[] = {
{
.start = U300_RTC_BASE,
.end = U300_RTC_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_U300_RTC,
.end = IRQ_U300_RTC,
.flags = IORESOURCE_IRQ,
},
};
/*
* Fsmc does have IRQs: #43 and #44 (NFIF and NFIF2)
* but these are not yet used by the driver.
*/
static struct resource fsmc_resources[] = {
{
.name = "nand_data",
.start = U300_NAND_CS0_PHYS_BASE,
.end = U300_NAND_CS0_PHYS_BASE + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "fsmc_regs",
.start = U300_NAND_IF_PHYS_BASE,
.end = U300_NAND_IF_PHYS_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
static struct resource i2c0_resources[] = {
{
.start = U300_I2C0_BASE,
.end = U300_I2C0_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_U300_I2C0,
.end = IRQ_U300_I2C0,
.flags = IORESOURCE_IRQ,
},
};
static struct resource i2c1_resources[] = {
{
.start = U300_I2C1_BASE,
.end = U300_I2C1_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_U300_I2C1,
.end = IRQ_U300_I2C1,
.flags = IORESOURCE_IRQ,
},
};
static struct resource wdog_resources[] = {
{
.start = U300_WDOG_BASE,
.end = U300_WDOG_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_U300_WDOG,
.end = IRQ_U300_WDOG,
.flags = IORESOURCE_IRQ,
}
};
static struct resource dma_resource[] = {
{
.start = U300_DMAC_BASE,
.end = U300_DMAC_BASE + PAGE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_U300_DMA,
.end = IRQ_U300_DMA,
.flags = IORESOURCE_IRQ,
}
};
#ifdef CONFIG_MACH_U300_BS335
/* points out all dma slave channels.
* Syntax is [A1, B1, A2, B2, .... ,-1,-1]
* Select all channels from A to B, end of list is marked with -1,-1
*/
static int dma_slave_channels[] = {
U300_DMA_MSL_TX_0, U300_DMA_SPI_RX,
U300_DMA_UART1_TX, U300_DMA_UART1_RX, -1, -1};
/* points out all dma memcpy channels. */
static int dma_memcpy_channels[] = {
U300_DMA_GENERAL_PURPOSE_0, U300_DMA_GENERAL_PURPOSE_8, -1, -1};
#else /* CONFIG_MACH_U300_BS335 */
static int dma_slave_channels[] = {U300_DMA_MSL_TX_0, U300_DMA_SPI_RX, -1, -1};
static int dma_memcpy_channels[] = {
U300_DMA_GENERAL_PURPOSE_0, U300_DMA_GENERAL_PURPOSE_10, -1, -1};
#endif
/** register dma for memory access
*
* active 1 means dma intends to access memory
* 0 means dma wont access memory
*/
static void coh901318_access_memory_state(struct device *dev, bool active)
{
}
#define flags_memcpy_config (COH901318_CX_CFG_CH_DISABLE | \
COH901318_CX_CFG_RM_MEMORY_TO_MEMORY | \
COH901318_CX_CFG_LCR_DISABLE | \
COH901318_CX_CFG_TC_IRQ_ENABLE | \
COH901318_CX_CFG_BE_IRQ_ENABLE)
#define flags_memcpy_lli_chained (COH901318_CX_CTRL_TC_ENABLE | \
COH901318_CX_CTRL_BURST_COUNT_32_BYTES | \
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS | \
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE | \
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS | \
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE | \
COH901318_CX_CTRL_MASTER_MODE_M1RW | \
COH901318_CX_CTRL_TCP_DISABLE | \
COH901318_CX_CTRL_TC_IRQ_DISABLE | \
COH901318_CX_CTRL_HSP_DISABLE | \
COH901318_CX_CTRL_HSS_DISABLE | \
COH901318_CX_CTRL_DDMA_LEGACY | \
COH901318_CX_CTRL_PRDD_SOURCE)
#define flags_memcpy_lli (COH901318_CX_CTRL_TC_ENABLE | \
COH901318_CX_CTRL_BURST_COUNT_32_BYTES | \
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS | \
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE | \
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS | \
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE | \
COH901318_CX_CTRL_MASTER_MODE_M1RW | \
COH901318_CX_CTRL_TCP_DISABLE | \
COH901318_CX_CTRL_TC_IRQ_DISABLE | \
COH901318_CX_CTRL_HSP_DISABLE | \
COH901318_CX_CTRL_HSS_DISABLE | \
COH901318_CX_CTRL_DDMA_LEGACY | \
COH901318_CX_CTRL_PRDD_SOURCE)
#define flags_memcpy_lli_last (COH901318_CX_CTRL_TC_ENABLE | \
COH901318_CX_CTRL_BURST_COUNT_32_BYTES | \
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS | \
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE | \
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS | \
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE | \
COH901318_CX_CTRL_MASTER_MODE_M1RW | \
COH901318_CX_CTRL_TCP_DISABLE | \
COH901318_CX_CTRL_TC_IRQ_ENABLE | \
COH901318_CX_CTRL_HSP_DISABLE | \
COH901318_CX_CTRL_HSS_DISABLE | \
COH901318_CX_CTRL_DDMA_LEGACY | \
COH901318_CX_CTRL_PRDD_SOURCE)
const struct coh_dma_channel chan_config[U300_DMA_CHANNELS] = {
{
.number = U300_DMA_MSL_TX_0,
.name = "MSL TX 0",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 0 * 0x40 + 0x20,
},
{
.number = U300_DMA_MSL_TX_1,
.name = "MSL TX 1",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 1 * 0x40 + 0x20,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
},
{
.number = U300_DMA_MSL_TX_2,
.name = "MSL TX 2",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 2 * 0x40 + 0x20,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.desc_nbr_max = 10,
},
{
.number = U300_DMA_MSL_TX_3,
.name = "MSL TX 3",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 3 * 0x40 + 0x20,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
},
{
.number = U300_DMA_MSL_TX_4,
.name = "MSL TX 4",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 4 * 0x40 + 0x20,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1R_M2W |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
},
{
.number = U300_DMA_MSL_TX_5,
.name = "MSL TX 5",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 5 * 0x40 + 0x20,
},
{
.number = U300_DMA_MSL_TX_6,
.name = "MSL TX 6",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 6 * 0x40 + 0x20,
},
{
.number = U300_DMA_MSL_RX_0,
.name = "MSL RX 0",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 0 * 0x40 + 0x220,
},
{
.number = U300_DMA_MSL_RX_1,
.name = "MSL RX 1",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 1 * 0x40 + 0x220,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli = 0,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
},
{
.number = U300_DMA_MSL_RX_2,
.name = "MSL RX 2",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 2 * 0x40 + 0x220,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
},
{
.number = U300_DMA_MSL_RX_3,
.name = "MSL RX 3",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 3 * 0x40 + 0x220,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
},
{
.number = U300_DMA_MSL_RX_4,
.name = "MSL RX 4",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 4 * 0x40 + 0x220,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
},
{
.number = U300_DMA_MSL_RX_5,
.name = "MSL RX 5",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 5 * 0x40 + 0x220,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_32_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M2R_M1W |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_DEMAND_DMA1 |
COH901318_CX_CTRL_PRDD_DEST,
},
{
.number = U300_DMA_MSL_RX_6,
.name = "MSL RX 6",
.priority_high = 0,
.dev_addr = U300_MSL_BASE + 6 * 0x40 + 0x220,
},
/*
* Don't set up device address, burst count or size of src
* or dst bus for this peripheral - handled by PrimeCell
* DMA extension.
*/
{
.number = U300_DMA_MMCSD_RX_TX,
.name = "MMCSD RX TX",
.priority_high = 0,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
},
{
.number = U300_DMA_MSPRO_TX,
.name = "MSPRO TX",
.priority_high = 0,
},
{
.number = U300_DMA_MSPRO_RX,
.name = "MSPRO RX",
.priority_high = 0,
},
/*
* Don't set up device address, burst count or size of src
* or dst bus for this peripheral - handled by PrimeCell
* DMA extension.
*/
{
.number = U300_DMA_UART0_TX,
.name = "UART0 TX",
.priority_high = 0,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
},
{
.number = U300_DMA_UART0_RX,
.name = "UART0 RX",
.priority_high = 0,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
},
{
.number = U300_DMA_APEX_TX,
.name = "APEX TX",
.priority_high = 0,
},
{
.number = U300_DMA_APEX_RX,
.name = "APEX RX",
.priority_high = 0,
},
{
.number = U300_DMA_PCM_I2S0_TX,
.name = "PCM I2S0 TX",
.priority_high = 1,
.dev_addr = U300_PCM_I2S0_BASE + 0x14,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
},
{
.number = U300_DMA_PCM_I2S0_RX,
.name = "PCM I2S0 RX",
.priority_high = 1,
.dev_addr = U300_PCM_I2S0_BASE + 0x10,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_DEST,
},
{
.number = U300_DMA_PCM_I2S1_TX,
.name = "PCM I2S1 TX",
.priority_high = 1,
.dev_addr = U300_PCM_I2S1_BASE + 0x14,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_ENABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_DISABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_SOURCE,
},
{
.number = U300_DMA_PCM_I2S1_RX,
.name = "PCM I2S1 RX",
.priority_high = 1,
.dev_addr = U300_PCM_I2S1_BASE + 0x10,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_DEST,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_BURST_COUNT_16_BYTES |
COH901318_CX_CTRL_SRC_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_SRC_ADDR_INC_DISABLE |
COH901318_CX_CTRL_DST_BUS_SIZE_32_BITS |
COH901318_CX_CTRL_DST_ADDR_INC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_ENABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY |
COH901318_CX_CTRL_PRDD_DEST,
},
{
.number = U300_DMA_XGAM_CDI,
.name = "XGAM CDI",
.priority_high = 0,
},
{
.number = U300_DMA_XGAM_PDI,
.name = "XGAM PDI",
.priority_high = 0,
},
/*
* Don't set up device address, burst count or size of src
* or dst bus for this peripheral - handled by PrimeCell
* DMA extension.
*/
{
.number = U300_DMA_SPI_TX,
.name = "SPI TX",
.priority_high = 0,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
},
{
.number = U300_DMA_SPI_RX,
.name = "SPI RX",
.priority_high = 0,
.param.config = COH901318_CX_CFG_CH_DISABLE |
COH901318_CX_CFG_LCR_DISABLE |
COH901318_CX_CFG_TC_IRQ_ENABLE |
COH901318_CX_CFG_BE_IRQ_ENABLE,
.param.ctrl_lli_chained = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_DISABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
.param.ctrl_lli = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
.param.ctrl_lli_last = 0 |
COH901318_CX_CTRL_TC_ENABLE |
COH901318_CX_CTRL_MASTER_MODE_M1RW |
COH901318_CX_CTRL_TCP_DISABLE |
COH901318_CX_CTRL_TC_IRQ_ENABLE |
COH901318_CX_CTRL_HSP_ENABLE |
COH901318_CX_CTRL_HSS_DISABLE |
COH901318_CX_CTRL_DDMA_LEGACY,
},
{
.number = U300_DMA_GENERAL_PURPOSE_0,
.name = "GENERAL 00",
.priority_high = 0,
.param.config = flags_memcpy_config,
.param.ctrl_lli_chained = flags_memcpy_lli_chained,
.param.ctrl_lli = flags_memcpy_lli,
.param.ctrl_lli_last = flags_memcpy_lli_last,
},
{
.number = U300_DMA_GENERAL_PURPOSE_1,
.name = "GENERAL 01",
.priority_high = 0,
.param.config = flags_memcpy_config,
.param.ctrl_lli_chained = flags_memcpy_lli_chained,
.param.ctrl_lli = flags_memcpy_lli,
.param.ctrl_lli_last = flags_memcpy_lli_last,
},
{
.number = U300_DMA_GENERAL_PURPOSE_2,
.name = "GENERAL 02",
.priority_high = 0,
.param.config = flags_memcpy_config,
.param.ctrl_lli_chained = flags_memcpy_lli_chained,
.param.ctrl_lli = flags_memcpy_lli,
.param.ctrl_lli_last = flags_memcpy_lli_last,
},
{
.number = U300_DMA_GENERAL_PURPOSE_3,
.name = "GENERAL 03",
.priority_high = 0,
.param.config = flags_memcpy_config,
.param.ctrl_lli_chained = flags_memcpy_lli_chained,
.param.ctrl_lli = flags_memcpy_lli,
.param.ctrl_lli_last = flags_memcpy_lli_last,
},
{
.number = U300_DMA_GENERAL_PURPOSE_4,
.name = "GENERAL 04",
.priority_high = 0,
.param.config = flags_memcpy_config,
.param.ctrl_lli_chained = flags_memcpy_lli_chained,
.param.ctrl_lli = flags_memcpy_lli,
.param.ctrl_lli_last = flags_memcpy_lli_last,
},
{
.number = U300_DMA_GENERAL_PURPOSE_5,
.name = "GENERAL 05",
.priority_high = 0,
.param.config = flags_memcpy_config,
.param.ctrl_lli_chained = flags_memcpy_lli_chained,
.param.ctrl_lli = flags_memcpy_lli,
.param.ctrl_lli_last = flags_memcpy_lli_last,
},
{
.number = U300_DMA_GENERAL_PURPOSE_6,
.name = "GENERAL 06",
.priority_high = 0,
.param.config = flags_memcpy_config,
.param.ctrl_lli_chained = flags_memcpy_lli_chained,
.param.ctrl_lli = flags_memcpy_lli,
.param.ctrl_lli_last = flags_memcpy_lli_last,
},
{
.number = U300_DMA_GENERAL_PURPOSE_7,
.name = "GENERAL 07",
.priority_high = 0,
.param.config = flags_memcpy_config,
.param.ctrl_lli_chained = flags_memcpy_lli_chained,
.param.ctrl_lli = flags_memcpy_lli,
.param.ctrl_lli_last = flags_memcpy_lli_last,
},
{
.number = U300_DMA_GENERAL_PURPOSE_8,
.name = "GENERAL 08",
.priority_high = 0,
.param.config = flags_memcpy_config,
.param.ctrl_lli_chained = flags_memcpy_lli_chained,
.param.ctrl_lli = flags_memcpy_lli,
.param.ctrl_lli_last = flags_memcpy_lli_last,
},
#ifdef CONFIG_MACH_U300_BS335
{
.number = U300_DMA_UART1_TX,
.name = "UART1 TX",
.priority_high = 0,
},
{
.number = U300_DMA_UART1_RX,
.name = "UART1 RX",
.priority_high = 0,
}
#else
{
.number = U300_DMA_GENERAL_PURPOSE_9,
.name = "GENERAL 09",
.priority_high = 0,
.param.config = flags_memcpy_config,
.param.ctrl_lli_chained = flags_memcpy_lli_chained,
.param.ctrl_lli = flags_memcpy_lli,
.param.ctrl_lli_last = flags_memcpy_lli_last,
},
{
.number = U300_DMA_GENERAL_PURPOSE_10,
.name = "GENERAL 10",
.priority_high = 0,
.param.config = flags_memcpy_config,
.param.ctrl_lli_chained = flags_memcpy_lli_chained,
.param.ctrl_lli = flags_memcpy_lli,
.param.ctrl_lli_last = flags_memcpy_lli_last,
}
#endif
};
static struct coh901318_platform coh901318_platform = {
.chans_slave = dma_slave_channels,
.chans_memcpy = dma_memcpy_channels,
.access_memory_state = coh901318_access_memory_state,
.chan_conf = chan_config,
.max_channels = U300_DMA_CHANNELS,
};
static struct resource pinctrl_resources[] = {
{
.start = U300_SYSCON_BASE,
.end = U300_SYSCON_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device wdog_device = {
.name = "coh901327_wdog",
.id = -1,
.num_resources = ARRAY_SIZE(wdog_resources),
.resource = wdog_resources,
};
static struct platform_device i2c0_device = {
.name = "stu300",
.id = 0,
.num_resources = ARRAY_SIZE(i2c0_resources),
.resource = i2c0_resources,
};
static struct platform_device i2c1_device = {
.name = "stu300",
.id = 1,
.num_resources = ARRAY_SIZE(i2c1_resources),
.resource = i2c1_resources,
};
static struct platform_device pinctrl_device = {
.name = "pinctrl-u300",
.id = -1,
.num_resources = ARRAY_SIZE(pinctrl_resources),
.resource = pinctrl_resources,
};
/*
* The different variants have a few different versions of the
* GPIO block, with different number of ports.
*/
static struct u300_gpio_platform u300_gpio_plat = {
#if defined(CONFIG_MACH_U300_BS2X) || defined(CONFIG_MACH_U300_BS330)
.variant = U300_GPIO_COH901335,
.ports = 3,
#endif
#ifdef CONFIG_MACH_U300_BS335
.variant = U300_GPIO_COH901571_3_BS335,
.ports = 7,
#endif
#ifdef CONFIG_MACH_U300_BS365
.variant = U300_GPIO_COH901571_3_BS365,
.ports = 5,
#endif
.gpio_base = 0,
.gpio_irq_base = IRQ_U300_GPIO_BASE,
.pinctrl_device = &pinctrl_device,
};
static struct platform_device gpio_device = {
.name = "u300-gpio",
.id = -1,
.num_resources = ARRAY_SIZE(gpio_resources),
.resource = gpio_resources,
.dev = {
.platform_data = &u300_gpio_plat,
},
};
static struct platform_device keypad_device = {
.name = "keypad",
.id = -1,
.num_resources = ARRAY_SIZE(keypad_resources),
.resource = keypad_resources,
};
static struct platform_device rtc_device = {
.name = "rtc-coh901331",
.id = -1,
.num_resources = ARRAY_SIZE(rtc_resources),
.resource = rtc_resources,
};
static struct mtd_partition u300_partitions[] = {
{
.name = "bootrecords",
.offset = 0,
.size = SZ_128K,
},
{
.name = "free",
.offset = SZ_128K,
.size = 8064 * SZ_1K,
},
{
.name = "platform",
.offset = 8192 * SZ_1K,
.size = 253952 * SZ_1K,
},
};
static struct fsmc_nand_platform_data nand_platform_data = {
.partitions = u300_partitions,
.nr_partitions = ARRAY_SIZE(u300_partitions),
.options = NAND_SKIP_BBTSCAN,
.width = FSMC_NAND_BW8,
};
static struct platform_device nand_device = {
.name = "fsmc-nand",
.id = -1,
.resource = fsmc_resources,
.num_resources = ARRAY_SIZE(fsmc_resources),
.dev = {
.platform_data = &nand_platform_data,
},
};
static struct platform_device dma_device = {
.name = "coh901318",
.id = -1,
.resource = dma_resource,
.num_resources = ARRAY_SIZE(dma_resource),
.dev = {
.platform_data = &coh901318_platform,
.coherent_dma_mask = ~0,
},
};
static unsigned long pin_pullup_conf[] = {
PIN_CONF_PACKED(PIN_CONFIG_BIAS_PULL_UP, 1),
};
static unsigned long pin_highz_conf[] = {
PIN_CONF_PACKED(PIN_CONFIG_BIAS_HIGH_IMPEDANCE, 0),
};
/* Pin control settings */
static struct pinctrl_map __initdata u300_pinmux_map[] = {
/* anonymous maps for chip power and EMIFs */
PIN_MAP_MUX_GROUP_HOG_DEFAULT("pinctrl-u300", NULL, "power"),
PIN_MAP_MUX_GROUP_HOG_DEFAULT("pinctrl-u300", NULL, "emif0"),
PIN_MAP_MUX_GROUP_HOG_DEFAULT("pinctrl-u300", NULL, "emif1"),
/* per-device maps for MMC/SD, SPI and UART */
PIN_MAP_MUX_GROUP_DEFAULT("mmci", "pinctrl-u300", NULL, "mmc0"),
PIN_MAP_MUX_GROUP_DEFAULT("pl022", "pinctrl-u300", NULL, "spi0"),
PIN_MAP_MUX_GROUP_DEFAULT("uart0", "pinctrl-u300", NULL, "uart0"),
/* This pin is used for clock return rather than GPIO */
PIN_MAP_CONFIGS_PIN_DEFAULT("mmci", "pinctrl-u300", "PIO APP GPIO 11",
pin_pullup_conf),
/* This pin is used for card detect */
PIN_MAP_CONFIGS_PIN_DEFAULT("mmci", "pinctrl-u300", "PIO MS INS",
pin_highz_conf),
};
struct u300_mux_hog {
struct device *dev;
struct pinctrl *p;
};
static struct u300_mux_hog u300_mux_hogs[] = {
{
.dev = &uart0_device.dev,
},
{
.dev = &pl022_device.dev,
},
{
.dev = &mmcsd_device.dev,
},
};
static int __init u300_pinctrl_fetch(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(u300_mux_hogs); i++) {
struct pinctrl *p;
p = pinctrl_get_select_default(u300_mux_hogs[i].dev);
if (IS_ERR(p)) {
pr_err("u300: could not get pinmux hog for dev %s\n",
dev_name(u300_mux_hogs[i].dev));
continue;
}
u300_mux_hogs[i].p = p;
}
return 0;
}
subsys_initcall(u300_pinctrl_fetch);
/*
* Notice that AMBA devices are initialized before platform devices.
*
*/
static struct platform_device *platform_devs[] __initdata = {
&dma_device,
&i2c0_device,
&i2c1_device,
&keypad_device,
&rtc_device,
&gpio_device,
&nand_device,
&wdog_device,
};
/*
* Interrupts: the U300 platforms have two pl190 ARM PrimeCells connected
* together so some interrupts are connected to the first one and some
* to the second one.
*/
void __init u300_init_irq(void)
{
u32 mask[2] = {0, 0};
struct clk *clk;
int i;
/* initialize clocking early, we want to clock the INTCON */
u300_clock_init();
/* Clock the interrupt controller */
clk = clk_get_sys("intcon", NULL);
BUG_ON(IS_ERR(clk));
clk_enable(clk);
for (i = 0; i < U300_VIC_IRQS_END; i++)
set_bit(i, (unsigned long *) &mask[0]);
vic_init((void __iomem *) U300_INTCON0_VBASE, 0, mask[0], mask[0]);
vic_init((void __iomem *) U300_INTCON1_VBASE, 32, mask[1], mask[1]);
}
/*
* U300 platforms peripheral handling
*/
struct db_chip {
u16 chipid;
const char *name;
};
/*
* This is a list of the Digital Baseband chips used in the U300 platform.
*/
static struct db_chip db_chips[] __initdata = {
{
.chipid = 0xb800,
.name = "DB3000",
},
{
.chipid = 0xc000,
.name = "DB3100",
},
{
.chipid = 0xc800,
.name = "DB3150",
},
{
.chipid = 0xd800,
.name = "DB3200",
},
{
.chipid = 0xe000,
.name = "DB3250",
},
{
.chipid = 0xe800,
.name = "DB3210",
},
{
.chipid = 0xf000,
.name = "DB3350 P1x",
},
{
.chipid = 0xf100,
.name = "DB3350 P2x",
},
{
.chipid = 0x0000, /* List terminator */
.name = NULL,
}
};
static void __init u300_init_check_chip(void)
{
u16 val;
struct db_chip *chip;
const char *chipname;
const char unknown[] = "UNKNOWN";
/* Read out and print chip ID */
val = readw(U300_SYSCON_VBASE + U300_SYSCON_CIDR);
/* This is in funky bigendian order... */
val = (val & 0xFFU) << 8 | (val >> 8);
chip = db_chips;
chipname = unknown;
for ( ; chip->chipid; chip++) {
if (chip->chipid == (val & 0xFF00U)) {
chipname = chip->name;
break;
}
}
printk(KERN_INFO "Initializing U300 system on %s baseband chip " \
"(chip ID 0x%04x)\n", chipname, val);
#ifdef CONFIG_MACH_U300_BS330
if ((val & 0xFF00U) != 0xd800) {
printk(KERN_ERR "Platform configured for BS330 " \
"with DB3200 but %s detected, expect problems!",
chipname);
}
#endif
#ifdef CONFIG_MACH_U300_BS335
if ((val & 0xFF00U) != 0xf000 && (val & 0xFF00U) != 0xf100) {
printk(KERN_ERR "Platform configured for BS335 " \
" with DB3350 but %s detected, expect problems!",
chipname);
}
#endif
#ifdef CONFIG_MACH_U300_BS365
if ((val & 0xFF00U) != 0xe800) {
printk(KERN_ERR "Platform configured for BS365 " \
"with DB3210 but %s detected, expect problems!",
chipname);
}
#endif
}
/*
* Some devices and their resources require reserved physical memory from
* the end of the available RAM. This function traverses the list of devices
* and assigns actual addresses to these.
*/
static void __init u300_assign_physmem(void)
{
unsigned long curr_start = __pa(high_memory);
int i, j;
for (i = 0; i < ARRAY_SIZE(platform_devs); i++) {
for (j = 0; j < platform_devs[i]->num_resources; j++) {
struct resource *const res =
&platform_devs[i]->resource[j];
if (IORESOURCE_MEM == res->flags &&
0 == res->start) {
res->start = curr_start;
res->end += curr_start;
curr_start += resource_size(res);
printk(KERN_INFO "core.c: Mapping RAM " \
"%#x-%#x to device %s:%s\n",
res->start, res->end,
platform_devs[i]->name, res->name);
}
}
}
}
void __init u300_init_devices(void)
{
int i;
u16 val;
/* Check what platform we run and print some status information */
u300_init_check_chip();
/* Set system to run at PLL208, max performance, a known state. */
val = readw(U300_SYSCON_VBASE + U300_SYSCON_CCR);
val &= ~U300_SYSCON_CCR_CLKING_PERFORMANCE_MASK;
writew(val, U300_SYSCON_VBASE + U300_SYSCON_CCR);
/* Wait for the PLL208 to lock if not locked in yet */
while (!(readw(U300_SYSCON_VBASE + U300_SYSCON_CSR) &
U300_SYSCON_CSR_PLL208_LOCK_IND));
/* Initialize SPI device with some board specifics */
u300_spi_init(&pl022_device);
/* Register the AMBA devices in the AMBA bus abstraction layer */
for (i = 0; i < ARRAY_SIZE(amba_devs); i++) {
struct amba_device *d = amba_devs[i];
amba_device_register(d, &iomem_resource);
}
u300_assign_physmem();
/* Initialize pinmuxing */
pinctrl_register_mappings(u300_pinmux_map,
ARRAY_SIZE(u300_pinmux_map));
/* Register subdevices on the I2C buses */
u300_i2c_register_board_devices();
/* Register the platform devices */
platform_add_devices(platform_devs, ARRAY_SIZE(platform_devs));
/* Register subdevices on the SPI bus */
u300_spi_register_board_devices();
/* Enable SEMI self refresh */
val = readw(U300_SYSCON_VBASE + U300_SYSCON_SMCR) |
U300_SYSCON_SMCR_SEMI_SREFREQ_ENABLE;
writew(val, U300_SYSCON_VBASE + U300_SYSCON_SMCR);
}
/* Forward declare this function from the watchdog */
void coh901327_watchdog_reset(void);
void u300_restart(char mode, const char *cmd)
{
switch (mode) {
case 's':
case 'h':
#ifdef CONFIG_COH901327_WATCHDOG
coh901327_watchdog_reset();
#endif
break;
default:
/* Do nothing */
break;
}
/* Wait for system do die/reset. */
while (1);
}
| arnet95/linux | arch/arm/mach-u300/core.c | C | gpl-2.0 | 55,389 |
/*
* pcic.c: MicroSPARC-IIep PCI controller support
*
* Copyright (C) 1998 V. Roganov and G. Raiko
*
* Code is derived from Ultra/PCI PSYCHO controller support, see that
* for author info.
*
* Support for diverse IIep based platforms by Pete Zaitcev.
* CP-1200 by Eric Brower.
*/
#include <linux/config.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <asm/ebus.h>
#include <asm/sbus.h> /* for sanity check... */
#include <asm/swift.h> /* for cache flushing. */
#include <asm/io.h>
#include <linux/ctype.h>
#include <linux/pci.h>
#include <linux/time.h>
#include <linux/timex.h>
#include <linux/interrupt.h>
#include <asm/irq.h>
#include <asm/oplib.h>
#include <asm/pcic.h>
#include <asm/timer.h>
#include <asm/uaccess.h>
unsigned int pcic_pin_to_irq(unsigned int pin, char *name);
/*
* I studied different documents and many live PROMs both from 2.30
* family and 3.xx versions. I came to the amazing conclusion: there is
* absolutely no way to route interrupts in IIep systems relying on
* information which PROM presents. We must hardcode interrupt routing
* schematics. And this actually sucks. -- zaitcev 1999/05/12
*
* To find irq for a device we determine which routing map
* is in effect or, in other words, on which machine we are running.
* We use PROM name for this although other techniques may be used
* in special cases (Gleb reports a PROMless IIep based system).
* Once we know the map we take device configuration address and
* find PCIC pin number where INT line goes. Then we may either program
* preferred irq into the PCIC or supply the preexisting irq to the device.
*/
struct pcic_ca2irq {
unsigned char busno; /* PCI bus number */
unsigned char devfn; /* Configuration address */
unsigned char pin; /* PCIC external interrupt pin */
unsigned char irq; /* Preferred IRQ (mappable in PCIC) */
unsigned int force; /* Enforce preferred IRQ */
};
struct pcic_sn2list {
char *sysname;
struct pcic_ca2irq *intmap;
int mapdim;
};
/*
* JavaEngine-1 apparently has different versions.
*
* According to communications with Sun folks, for P2 build 501-4628-03:
* pin 0 - parallel, audio;
* pin 1 - Ethernet;
* pin 2 - su;
* pin 3 - PS/2 kbd and mouse.
*
* OEM manual (805-1486):
* pin 0: Ethernet
* pin 1: All EBus
* pin 2: IGA (unused)
* pin 3: Not connected
* OEM manual says that 501-4628 & 501-4811 are the same thing,
* only the latter has NAND flash in place.
*
* So far unofficial Sun wins over the OEM manual. Poor OEMs...
*/
static struct pcic_ca2irq pcic_i_je1a[] = { /* 501-4811-03 */
{ 0, 0x00, 2, 12, 0 }, /* EBus: hogs all */
{ 0, 0x01, 1, 6, 1 }, /* Happy Meal */
{ 0, 0x80, 0, 7, 0 }, /* IGA (unused) */
};
/* XXX JS-E entry is incomplete - PCI Slot 2 address (pin 7)? */
static struct pcic_ca2irq pcic_i_jse[] = {
{ 0, 0x00, 0, 13, 0 }, /* Ebus - serial and keyboard */
{ 0, 0x01, 1, 6, 0 }, /* hme */
{ 0, 0x08, 2, 9, 0 }, /* VGA - we hope not used :) */
{ 0, 0x10, 6, 8, 0 }, /* PCI INTA# in Slot 1 */
{ 0, 0x18, 7, 12, 0 }, /* PCI INTA# in Slot 2, shared w. RTC */
{ 0, 0x38, 4, 9, 0 }, /* All ISA devices. Read 8259. */
{ 0, 0x80, 5, 11, 0 }, /* EIDE */
/* {0,0x88, 0,0,0} - unknown device... PMU? Probably no interrupt. */
{ 0, 0xA0, 4, 9, 0 }, /* USB */
/*
* Some pins belong to non-PCI devices, we hardcode them in drivers.
* sun4m timers - irq 10, 14
* PC style RTC - pin 7, irq 4 ?
* Smart card, Parallel - pin 4 shared with USB, ISA
* audio - pin 3, irq 5 ?
*/
};
/* SPARCengine-6 was the original release name of CP1200.
* The documentation differs between the two versions
*/
static struct pcic_ca2irq pcic_i_se6[] = {
{ 0, 0x08, 0, 2, 0 }, /* SCSI */
{ 0, 0x01, 1, 6, 0 }, /* HME */
{ 0, 0x00, 3, 13, 0 }, /* EBus */
};
/*
* Krups (courtesy of Varol Kaptan)
* No documentation available, but it was easy to guess
* because it was very similar to Espresso.
*
* pin 0 - kbd, mouse, serial;
* pin 1 - Ethernet;
* pin 2 - igs (we do not use it);
* pin 3 - audio;
* pin 4,5,6 - unused;
* pin 7 - RTC (from P2 onwards as David B. says).
*/
static struct pcic_ca2irq pcic_i_jk[] = {
{ 0, 0x00, 0, 13, 0 }, /* Ebus - serial and keyboard */
{ 0, 0x01, 1, 6, 0 }, /* hme */
};
/*
* Several entries in this list may point to the same routing map
* as several PROMs may be installed on the same physical board.
*/
#define SN2L_INIT(name, map) \
{ name, map, ARRAY_SIZE(map) }
static struct pcic_sn2list pcic_known_sysnames[] = {
SN2L_INIT("SUNW,JavaEngine1", pcic_i_je1a), /* JE1, PROM 2.32 */
SN2L_INIT("SUNW,JS-E", pcic_i_jse), /* PROLL JavaStation-E */
SN2L_INIT("SUNW,SPARCengine-6", pcic_i_se6), /* SPARCengine-6/CP-1200 */
SN2L_INIT("SUNW,JS-NC", pcic_i_jk), /* PROLL JavaStation-NC */
SN2L_INIT("SUNW,JSIIep", pcic_i_jk), /* OBP JavaStation-NC */
{ NULL, NULL, 0 }
};
/*
* Only one PCIC per IIep,
* and since we have no SMP IIep, only one per system.
*/
static int pcic0_up;
static struct linux_pcic pcic0;
void __iomem *pcic_regs;
volatile int pcic_speculative;
volatile int pcic_trapped;
static void pci_do_gettimeofday(struct timeval *tv);
static int pci_do_settimeofday(struct timespec *tv);
#define CONFIG_CMD(bus, device_fn, where) (0x80000000 | (((unsigned int)bus) << 16) | (((unsigned int)device_fn) << 8) | (where & ~3))
static int pcic_read_config_dword(unsigned int busno, unsigned int devfn,
int where, u32 *value)
{
struct linux_pcic *pcic;
unsigned long flags;
pcic = &pcic0;
local_irq_save(flags);
#if 0 /* does not fail here */
pcic_speculative = 1;
pcic_trapped = 0;
#endif
writel(CONFIG_CMD(busno, devfn, where), pcic->pcic_config_space_addr);
#if 0 /* does not fail here */
nop();
if (pcic_trapped) {
local_irq_restore(flags);
*value = ~0;
return 0;
}
#endif
pcic_speculative = 2;
pcic_trapped = 0;
*value = readl(pcic->pcic_config_space_data + (where&4));
nop();
if (pcic_trapped) {
pcic_speculative = 0;
local_irq_restore(flags);
*value = ~0;
return 0;
}
pcic_speculative = 0;
local_irq_restore(flags);
return 0;
}
static int pcic_read_config(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 *val)
{
unsigned int v;
if (bus->number != 0) return -EINVAL;
switch (size) {
case 1:
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
*val = 0xff & (v >> (8*(where & 3)));
return 0;
case 2:
if (where&1) return -EINVAL;
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
*val = 0xffff & (v >> (8*(where & 3)));
return 0;
case 4:
if (where&3) return -EINVAL;
pcic_read_config_dword(bus->number, devfn, where&~3, val);
return 0;
}
return -EINVAL;
}
static int pcic_write_config_dword(unsigned int busno, unsigned int devfn,
int where, u32 value)
{
struct linux_pcic *pcic;
unsigned long flags;
pcic = &pcic0;
local_irq_save(flags);
writel(CONFIG_CMD(busno, devfn, where), pcic->pcic_config_space_addr);
writel(value, pcic->pcic_config_space_data + (where&4));
local_irq_restore(flags);
return 0;
}
static int pcic_write_config(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 val)
{
unsigned int v;
if (bus->number != 0) return -EINVAL;
switch (size) {
case 1:
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
v = (v & ~(0xff << (8*(where&3)))) |
((0xff&val) << (8*(where&3)));
return pcic_write_config_dword(bus->number, devfn, where&~3, v);
case 2:
if (where&1) return -EINVAL;
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
v = (v & ~(0xffff << (8*(where&3)))) |
((0xffff&val) << (8*(where&3)));
return pcic_write_config_dword(bus->number, devfn, where&~3, v);
case 4:
if (where&3) return -EINVAL;
return pcic_write_config_dword(bus->number, devfn, where, val);
}
return -EINVAL;
}
static struct pci_ops pcic_ops = {
.read = pcic_read_config,
.write = pcic_write_config,
};
/*
* On sparc64 pcibios_init() calls pci_controller_probe().
* We want PCIC probed little ahead so that interrupt controller
* would be operational.
*/
int __init pcic_probe(void)
{
struct linux_pcic *pcic;
struct linux_prom_registers regs[PROMREG_MAX];
struct linux_pbm_info* pbm;
char namebuf[64];
int node;
int err;
if (pcic0_up) {
prom_printf("PCIC: called twice!\n");
prom_halt();
}
pcic = &pcic0;
node = prom_getchild (prom_root_node);
node = prom_searchsiblings (node, "pci");
if (node == 0)
return -ENODEV;
/*
* Map in PCIC register set, config space, and IO base
*/
err = prom_getproperty(node, "reg", (char*)regs, sizeof(regs));
if (err == 0 || err == -1) {
prom_printf("PCIC: Error, cannot get PCIC registers "
"from PROM.\n");
prom_halt();
}
pcic0_up = 1;
pcic->pcic_res_regs.name = "pcic_registers";
pcic->pcic_regs = ioremap(regs[0].phys_addr, regs[0].reg_size);
if (!pcic->pcic_regs) {
prom_printf("PCIC: Error, cannot map PCIC registers.\n");
prom_halt();
}
pcic->pcic_res_io.name = "pcic_io";
if ((pcic->pcic_io = (unsigned long)
ioremap(regs[1].phys_addr, 0x10000)) == 0) {
prom_printf("PCIC: Error, cannot map PCIC IO Base.\n");
prom_halt();
}
pcic->pcic_res_cfg_addr.name = "pcic_cfg_addr";
if ((pcic->pcic_config_space_addr =
ioremap(regs[2].phys_addr, regs[2].reg_size * 2)) == 0) {
prom_printf("PCIC: Error, cannot map"
"PCI Configuration Space Address.\n");
prom_halt();
}
/*
* Docs say three least significant bits in address and data
* must be the same. Thus, we need adjust size of data.
*/
pcic->pcic_res_cfg_data.name = "pcic_cfg_data";
if ((pcic->pcic_config_space_data =
ioremap(regs[3].phys_addr, regs[3].reg_size * 2)) == 0) {
prom_printf("PCIC: Error, cannot map"
"PCI Configuration Space Data.\n");
prom_halt();
}
pbm = &pcic->pbm;
pbm->prom_node = node;
prom_getstring(node, "name", namebuf, 63); namebuf[63] = 0;
strcpy(pbm->prom_name, namebuf);
{
extern volatile int t_nmi[1];
extern int pcic_nmi_trap_patch[1];
t_nmi[0] = pcic_nmi_trap_patch[0];
t_nmi[1] = pcic_nmi_trap_patch[1];
t_nmi[2] = pcic_nmi_trap_patch[2];
t_nmi[3] = pcic_nmi_trap_patch[3];
swift_flush_dcache();
pcic_regs = pcic->pcic_regs;
}
prom_getstring(prom_root_node, "name", namebuf, 63); namebuf[63] = 0;
{
struct pcic_sn2list *p;
for (p = pcic_known_sysnames; p->sysname != NULL; p++) {
if (strcmp(namebuf, p->sysname) == 0)
break;
}
pcic->pcic_imap = p->intmap;
pcic->pcic_imdim = p->mapdim;
}
if (pcic->pcic_imap == NULL) {
/*
* We do not panic here for the sake of embedded systems.
*/
printk("PCIC: System %s is unknown, cannot route interrupts\n",
namebuf);
}
return 0;
}
static void __init pcic_pbm_scan_bus(struct linux_pcic *pcic)
{
struct linux_pbm_info *pbm = &pcic->pbm;
pbm->pci_bus = pci_scan_bus(pbm->pci_first_busno, &pcic_ops, pbm);
#if 0 /* deadwood transplanted from sparc64 */
pci_fill_in_pbm_cookies(pbm->pci_bus, pbm, pbm->prom_node);
pci_record_assignments(pbm, pbm->pci_bus);
pci_assign_unassigned(pbm, pbm->pci_bus);
pci_fixup_irq(pbm, pbm->pci_bus);
#endif
}
/*
* Main entry point from the PCI subsystem.
*/
static int __init pcic_init(void)
{
struct linux_pcic *pcic;
/*
* PCIC should be initialized at start of the timer.
* So, here we report the presence of PCIC and do some magic passes.
*/
if(!pcic0_up)
return 0;
pcic = &pcic0;
/*
* Switch off IOTLB translation.
*/
writeb(PCI_DVMA_CONTROL_IOTLB_DISABLE,
pcic->pcic_regs+PCI_DVMA_CONTROL);
/*
* Increase mapped size for PCI memory space (DMA access).
* Should be done in that order (size first, address second).
* Why we couldn't set up 4GB and forget about it? XXX
*/
writel(0xF0000000UL, pcic->pcic_regs+PCI_SIZE_0);
writel(0+PCI_BASE_ADDRESS_SPACE_MEMORY,
pcic->pcic_regs+PCI_BASE_ADDRESS_0);
pcic_pbm_scan_bus(pcic);
ebus_init();
return 0;
}
int pcic_present(void)
{
return pcic0_up;
}
static int __init pdev_to_pnode(struct linux_pbm_info *pbm,
struct pci_dev *pdev)
{
struct linux_prom_pci_registers regs[PROMREG_MAX];
int err;
int node = prom_getchild(pbm->prom_node);
while(node) {
err = prom_getproperty(node, "reg",
(char *)®s[0], sizeof(regs));
if(err != 0 && err != -1) {
unsigned long devfn = (regs[0].which_io >> 8) & 0xff;
if(devfn == pdev->devfn)
return node;
}
node = prom_getsibling(node);
}
return 0;
}
static inline struct pcidev_cookie *pci_devcookie_alloc(void)
{
return kmalloc(sizeof(struct pcidev_cookie), GFP_ATOMIC);
}
static void pcic_map_pci_device(struct linux_pcic *pcic,
struct pci_dev *dev, int node)
{
char namebuf[64];
unsigned long address;
unsigned long flags;
int j;
if (node == 0 || node == -1) {
strcpy(namebuf, "???");
} else {
prom_getstring(node, "name", namebuf, 63); namebuf[63] = 0;
}
for (j = 0; j < 6; j++) {
address = dev->resource[j].start;
if (address == 0) break; /* are sequential */
flags = dev->resource[j].flags;
if ((flags & IORESOURCE_IO) != 0) {
if (address < 0x10000) {
/*
* A device responds to I/O cycles on PCI.
* We generate these cycles with memory
* access into the fixed map (phys 0x30000000).
*
* Since a device driver does not want to
* do ioremap() before accessing PC-style I/O,
* we supply virtual, ready to access address.
*
* Ebus devices do not come here even if
* CheerIO makes a similar conversion.
* See ebus.c for details.
*
* Note that request_region()
* works for these devices.
*
* XXX Neat trick, but it's a *bad* idea
* to shit into regions like that.
* What if we want to allocate one more
* PCI base address...
*/
dev->resource[j].start =
pcic->pcic_io + address;
dev->resource[j].end = 1; /* XXX */
dev->resource[j].flags =
(flags & ~IORESOURCE_IO) | IORESOURCE_MEM;
} else {
/*
* OOPS... PCI Spec allows this. Sun does
* not have any devices getting above 64K
* so it must be user with a weird I/O
* board in a PCI slot. We must remap it
* under 64K but it is not done yet. XXX
*/
printk("PCIC: Skipping I/O space at 0x%lx,"
"this will Oops if a driver attaches;"
"device '%s' at %02x:%02x)\n", address,
namebuf, dev->bus->number, dev->devfn);
}
}
}
}
static void
pcic_fill_irq(struct linux_pcic *pcic, struct pci_dev *dev, int node)
{
struct pcic_ca2irq *p;
int i, ivec;
char namebuf[64];
if (node == 0 || node == -1) {
strcpy(namebuf, "???");
} else {
prom_getstring(node, "name", namebuf, sizeof(namebuf));
}
if ((p = pcic->pcic_imap) == 0) {
dev->irq = 0;
return;
}
for (i = 0; i < pcic->pcic_imdim; i++) {
if (p->busno == dev->bus->number && p->devfn == dev->devfn)
break;
p++;
}
if (i >= pcic->pcic_imdim) {
printk("PCIC: device %s devfn %02x:%02x not found in %d\n",
namebuf, dev->bus->number, dev->devfn, pcic->pcic_imdim);
dev->irq = 0;
return;
}
i = p->pin;
if (i >= 0 && i < 4) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_LO);
dev->irq = ivec >> (i << 2) & 0xF;
} else if (i >= 4 && i < 8) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_HI);
dev->irq = ivec >> ((i-4) << 2) & 0xF;
} else { /* Corrupted map */
printk("PCIC: BAD PIN %d\n", i); for (;;) {}
}
/* P3 */ /* printk("PCIC: device %s pin %d ivec 0x%x irq %x\n", namebuf, i, ivec, dev->irq); */
/*
* dev->irq=0 means PROM did not bother to program the upper
* half of PCIC. This happens on JS-E with PROM 3.11, for instance.
*/
if (dev->irq == 0 || p->force) {
if (p->irq == 0 || p->irq >= 15) { /* Corrupted map */
printk("PCIC: BAD IRQ %d\n", p->irq); for (;;) {}
}
printk("PCIC: setting irq %d at pin %d for device %02x:%02x\n",
p->irq, p->pin, dev->bus->number, dev->devfn);
dev->irq = p->irq;
i = p->pin;
if (i >= 4) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_HI);
ivec &= ~(0xF << ((i - 4) << 2));
ivec |= p->irq << ((i - 4) << 2);
writew(ivec, pcic->pcic_regs+PCI_INT_SELECT_HI);
} else {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_LO);
ivec &= ~(0xF << (i << 2));
ivec |= p->irq << (i << 2);
writew(ivec, pcic->pcic_regs+PCI_INT_SELECT_LO);
}
}
return;
}
/*
* Normally called from {do_}pci_scan_bus...
*/
void __init pcibios_fixup_bus(struct pci_bus *bus)
{
struct pci_dev *dev;
int i, has_io, has_mem;
unsigned int cmd;
struct linux_pcic *pcic;
/* struct linux_pbm_info* pbm = &pcic->pbm; */
int node;
struct pcidev_cookie *pcp;
if (!pcic0_up) {
printk("pcibios_fixup_bus: no PCIC\n");
return;
}
pcic = &pcic0;
/*
* Next crud is an equivalent of pbm = pcic_bus_to_pbm(bus);
*/
if (bus->number != 0) {
printk("pcibios_fixup_bus: nonzero bus 0x%x\n", bus->number);
return;
}
list_for_each_entry(dev, &bus->devices, bus_list) {
/*
* Comment from i386 branch:
* There are buggy BIOSes that forget to enable I/O and memory
* access to PCI devices. We try to fix this, but we need to
* be sure that the BIOS didn't forget to assign an address
* to the device. [mj]
* OBP is a case of such BIOS :-)
*/
has_io = has_mem = 0;
for(i=0; i<6; i++) {
unsigned long f = dev->resource[i].flags;
if (f & IORESOURCE_IO) {
has_io = 1;
} else if (f & IORESOURCE_MEM)
has_mem = 1;
}
pcic_read_config(dev->bus, dev->devfn, PCI_COMMAND, 2, &cmd);
if (has_io && !(cmd & PCI_COMMAND_IO)) {
printk("PCIC: Enabling I/O for device %02x:%02x\n",
dev->bus->number, dev->devfn);
cmd |= PCI_COMMAND_IO;
pcic_write_config(dev->bus, dev->devfn,
PCI_COMMAND, 2, cmd);
}
if (has_mem && !(cmd & PCI_COMMAND_MEMORY)) {
printk("PCIC: Enabling memory for device %02x:%02x\n",
dev->bus->number, dev->devfn);
cmd |= PCI_COMMAND_MEMORY;
pcic_write_config(dev->bus, dev->devfn,
PCI_COMMAND, 2, cmd);
}
node = pdev_to_pnode(&pcic->pbm, dev);
if(node == 0)
node = -1;
/* cookies */
pcp = pci_devcookie_alloc();
pcp->pbm = &pcic->pbm;
pcp->prom_node = node;
dev->sysdata = pcp;
/* fixing I/O to look like memory */
if ((dev->class>>16) != PCI_BASE_CLASS_BRIDGE)
pcic_map_pci_device(pcic, dev, node);
pcic_fill_irq(pcic, dev, node);
}
}
/*
* pcic_pin_to_irq() is exported to ebus.c.
*/
unsigned int
pcic_pin_to_irq(unsigned int pin, char *name)
{
struct linux_pcic *pcic = &pcic0;
unsigned int irq;
unsigned int ivec;
if (pin < 4) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_LO);
irq = ivec >> (pin << 2) & 0xF;
} else if (pin < 8) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_HI);
irq = ivec >> ((pin-4) << 2) & 0xF;
} else { /* Corrupted map */
printk("PCIC: BAD PIN %d FOR %s\n", pin, name);
for (;;) {} /* XXX Cannot panic properly in case of PROLL */
}
/* P3 */ /* printk("PCIC: dev %s pin %d ivec 0x%x irq %x\n", name, pin, ivec, irq); */
return irq;
}
/* Makes compiler happy */
static volatile int pcic_timer_dummy;
static void pcic_clear_clock_irq(void)
{
pcic_timer_dummy = readl(pcic0.pcic_regs+PCI_SYS_LIMIT);
}
static irqreturn_t pcic_timer_handler (int irq, void *h, struct pt_regs *regs)
{
write_seqlock(&xtime_lock); /* Dummy, to show that we remember */
pcic_clear_clock_irq();
do_timer(regs);
#ifndef CONFIG_SMP
update_process_times(user_mode(regs));
#endif
write_sequnlock(&xtime_lock);
return IRQ_HANDLED;
}
#define USECS_PER_JIFFY 10000 /* We have 100HZ "standard" timer for sparc */
#define TICK_TIMER_LIMIT ((100*1000000/4)/100)
void __init pci_time_init(void)
{
struct linux_pcic *pcic = &pcic0;
unsigned long v;
int timer_irq, irq;
/* A hack until do_gettimeofday prototype is moved to arch specific headers
and btfixupped. Patch do_gettimeofday with ba pci_do_gettimeofday; nop */
((unsigned int *)do_gettimeofday)[0] =
0x10800000 | ((((unsigned long)pci_do_gettimeofday -
(unsigned long)do_gettimeofday) >> 2) & 0x003fffff);
((unsigned int *)do_gettimeofday)[1] = 0x01000000;
BTFIXUPSET_CALL(bus_do_settimeofday, pci_do_settimeofday, BTFIXUPCALL_NORM);
btfixup();
writel (TICK_TIMER_LIMIT, pcic->pcic_regs+PCI_SYS_LIMIT);
/* PROM should set appropriate irq */
v = readb(pcic->pcic_regs+PCI_COUNTER_IRQ);
timer_irq = PCI_COUNTER_IRQ_SYS(v);
writel (PCI_COUNTER_IRQ_SET(timer_irq, 0),
pcic->pcic_regs+PCI_COUNTER_IRQ);
irq = request_irq(timer_irq, pcic_timer_handler,
(SA_INTERRUPT | SA_STATIC_ALLOC), "timer", NULL);
if (irq) {
prom_printf("time_init: unable to attach IRQ%d\n", timer_irq);
prom_halt();
}
local_irq_enable();
}
static __inline__ unsigned long do_gettimeoffset(void)
{
/*
* We devide all to 100
* to have microsecond resolution and to avoid overflow
*/
unsigned long count =
readl(pcic0.pcic_regs+PCI_SYS_COUNTER) & ~PCI_SYS_COUNTER_OVERFLOW;
count = ((count/100)*USECS_PER_JIFFY) / (TICK_TIMER_LIMIT/100);
return count;
}
extern unsigned long wall_jiffies;
static void pci_do_gettimeofday(struct timeval *tv)
{
unsigned long flags;
unsigned long seq;
unsigned long usec, sec;
unsigned long max_ntp_tick = tick_usec - tickadj;
do {
unsigned long lost;
seq = read_seqbegin_irqsave(&xtime_lock, flags);
usec = do_gettimeoffset();
lost = jiffies - wall_jiffies;
/*
* If time_adjust is negative then NTP is slowing the clock
* so make sure not to go into next possible interval.
* Better to lose some accuracy than have time go backwards..
*/
if (unlikely(time_adjust < 0)) {
usec = min(usec, max_ntp_tick);
if (lost)
usec += lost * max_ntp_tick;
}
else if (unlikely(lost))
usec += lost * tick_usec;
sec = xtime.tv_sec;
usec += (xtime.tv_nsec / 1000);
} while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
while (usec >= 1000000) {
usec -= 1000000;
sec++;
}
tv->tv_sec = sec;
tv->tv_usec = usec;
}
static int pci_do_settimeofday(struct timespec *tv)
{
if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
return -EINVAL;
/*
* This is revolting. We need to set "xtime" correctly. However, the
* value in this location is the value at the most recent update of
* wall time. Discover what correction gettimeofday() would have
* made, and then undo it!
*/
tv->tv_nsec -= 1000 * (do_gettimeoffset() +
(jiffies - wall_jiffies) * (USEC_PER_SEC / HZ));
while (tv->tv_nsec < 0) {
tv->tv_nsec += NSEC_PER_SEC;
tv->tv_sec--;
}
wall_to_monotonic.tv_sec += xtime.tv_sec - tv->tv_sec;
wall_to_monotonic.tv_nsec += xtime.tv_nsec - tv->tv_nsec;
if (wall_to_monotonic.tv_nsec > NSEC_PER_SEC) {
wall_to_monotonic.tv_nsec -= NSEC_PER_SEC;
wall_to_monotonic.tv_sec++;
}
if (wall_to_monotonic.tv_nsec < 0) {
wall_to_monotonic.tv_nsec += NSEC_PER_SEC;
wall_to_monotonic.tv_sec--;
}
xtime.tv_sec = tv->tv_sec;
xtime.tv_nsec = tv->tv_nsec;
ntp_clear();
return 0;
}
#if 0
static void watchdog_reset() {
writeb(0, pcic->pcic_regs+PCI_SYS_STATUS);
}
#endif
/*
* Other archs parse arguments here.
*/
char * __init pcibios_setup(char *str)
{
return str;
}
void pcibios_align_resource(void *data, struct resource *res,
unsigned long size, unsigned long align)
{
}
int pcibios_enable_device(struct pci_dev *pdev, int mask)
{
return 0;
}
/*
* NMI
*/
void pcic_nmi(unsigned int pend, struct pt_regs *regs)
{
pend = flip_dword(pend);
if (!pcic_speculative || (pend & PCI_SYS_INT_PENDING_PIO) == 0) {
/*
* XXX On CP-1200 PCI #SERR may happen, we do not know
* what to do about it yet.
*/
printk("Aiee, NMI pend 0x%x pc 0x%x spec %d, hanging\n",
pend, (int)regs->pc, pcic_speculative);
for (;;) { }
}
pcic_speculative = 0;
pcic_trapped = 1;
regs->pc = regs->npc;
regs->npc += 4;
}
static inline unsigned long get_irqmask(int irq_nr)
{
return 1 << irq_nr;
}
static inline char *pcic_irq_itoa(unsigned int irq)
{
static char buff[16];
sprintf(buff, "%d", irq);
return buff;
}
static void pcic_disable_irq(unsigned int irq_nr)
{
unsigned long mask, flags;
mask = get_irqmask(irq_nr);
local_irq_save(flags);
writel(mask, pcic0.pcic_regs+PCI_SYS_INT_TARGET_MASK_SET);
local_irq_restore(flags);
}
static void pcic_enable_irq(unsigned int irq_nr)
{
unsigned long mask, flags;
mask = get_irqmask(irq_nr);
local_irq_save(flags);
writel(mask, pcic0.pcic_regs+PCI_SYS_INT_TARGET_MASK_CLEAR);
local_irq_restore(flags);
}
static void pcic_clear_profile_irq(int cpu)
{
printk("PCIC: unimplemented code: FILE=%s LINE=%d", __FILE__, __LINE__);
}
static void pcic_load_profile_irq(int cpu, unsigned int limit)
{
printk("PCIC: unimplemented code: FILE=%s LINE=%d", __FILE__, __LINE__);
}
/* We assume the caller has disabled local interrupts when these are called,
* or else very bizarre behavior will result.
*/
static void pcic_disable_pil_irq(unsigned int pil)
{
writel(get_irqmask(pil), pcic0.pcic_regs+PCI_SYS_INT_TARGET_MASK_SET);
}
static void pcic_enable_pil_irq(unsigned int pil)
{
writel(get_irqmask(pil), pcic0.pcic_regs+PCI_SYS_INT_TARGET_MASK_CLEAR);
}
void __init sun4m_pci_init_IRQ(void)
{
BTFIXUPSET_CALL(enable_irq, pcic_enable_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(disable_irq, pcic_disable_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(enable_pil_irq, pcic_enable_pil_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(disable_pil_irq, pcic_disable_pil_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(clear_clock_irq, pcic_clear_clock_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(clear_profile_irq, pcic_clear_profile_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(load_profile_irq, pcic_load_profile_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(__irq_itoa, pcic_irq_itoa, BTFIXUPCALL_NORM);
}
int pcibios_assign_resource(struct pci_dev *pdev, int resource)
{
return -ENXIO;
}
/*
* This probably belongs here rather than ioport.c because
* we do not want this crud linked into SBus kernels.
* Also, think for a moment about likes of floppy.c that
* include architecture specific parts. They may want to redefine ins/outs.
*
* We do not use horroble macroses here because we want to
* advance pointer by sizeof(size).
*/
void outsb(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 1;
outb(*(const char *)src, addr);
src += 1;
/* addr += 1; */
}
}
void outsw(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 2;
outw(*(const short *)src, addr);
src += 2;
/* addr += 2; */
}
}
void outsl(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 4;
outl(*(const long *)src, addr);
src += 4;
/* addr += 4; */
}
}
void insb(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 1;
*(unsigned char *)dst = inb(addr);
dst += 1;
/* addr += 1; */
}
}
void insw(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 2;
*(unsigned short *)dst = inw(addr);
dst += 2;
/* addr += 2; */
}
}
void insl(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 4;
/*
* XXX I am sure we are in for an unaligned trap here.
*/
*(unsigned long *)dst = inl(addr);
dst += 4;
/* addr += 4; */
}
}
subsys_initcall(pcic_init);
| zrafa/linuxkernel | linux-2.6.17.new/arch/sparc/kernel/pcic.c | C | gpl-2.0 | 27,310 |
var path = require("path");
module.exports = {
entry: "./public/App.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "public")
}
}; | generalelectrix/wiggles | view/webpack.config.js | JavaScript | gpl-2.0 | 179 |
§ßU<?php exit; ?>a:1:{s:7:"content";a:0:{}} | nilmadhab/webtutplus | wp-content/cache/object/000000/e36/eb4/e36eb471ab990b405292d7034395335a.php | PHP | gpl-2.0 | 44 |
/* Dia -- an diagram creation/manipulation program
* Copyright (C) 1998 Alexander Larsson
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <assert.h>
#include <math.h>
#include <string.h>
#include "intl.h"
#include "object.h"
#include "orth_conn.h"
#include "diarenderer.h"
#include "attributes.h"
#include "arrows.h"
#include "properties.h"
#include "stereotype.h"
#include "uml.h"
#include "pixmaps/realizes.xpm"
typedef struct _Realizes Realizes;
struct _Realizes {
OrthConn orth;
Point text_pos;
Alignment text_align;
real text_width;
Color text_color;
Color line_color;
char *name;
char *stereotype; /* excluding << and >> */
char *st_stereotype; /* including << and >> */
};
#define REALIZES_WIDTH 0.1
#define REALIZES_TRIANGLESIZE 0.8
#define REALIZES_DASHLEN 0.4
#define REALIZES_FONTHEIGHT 0.8
static DiaFont *realize_font = NULL;
static real realizes_distance_from(Realizes *realize, Point *point);
static void realizes_select(Realizes *realize, Point *clicked_point,
DiaRenderer *interactive_renderer);
static ObjectChange* realizes_move_handle(Realizes *realize, Handle *handle,
Point *to, ConnectionPoint *cp,
HandleMoveReason reason, ModifierKeys modifiers);
static ObjectChange* realizes_move(Realizes *realize, Point *to);
static void realizes_draw(Realizes *realize, DiaRenderer *renderer);
static DiaObject *realizes_create(Point *startpoint,
void *user_data,
Handle **handle1,
Handle **handle2);
static void realizes_destroy(Realizes *realize);
static DiaMenu *realizes_get_object_menu(Realizes *realize,
Point *clickedpoint);
static PropDescription *realizes_describe_props(Realizes *realizes);
static void realizes_get_props(Realizes * realizes, GPtrArray *props);
static void realizes_set_props(Realizes * realizes, GPtrArray *props);
static DiaObject *realizes_load(ObjectNode obj_node, int version,
const char *filename);
static void realizes_update_data(Realizes *realize);
static ObjectTypeOps realizes_type_ops =
{
(CreateFunc) realizes_create,
(LoadFunc) realizes_load,/*using_properties*/ /* load */
(SaveFunc) object_save_using_properties, /* save */
(GetDefaultsFunc) NULL,
(ApplyDefaultsFunc) NULL
};
DiaObjectType realizes_type =
{
"UML - Realizes", /* name */
/* Version 0 had no autorouting and so shouldn't have it set by default. */
1, /* version */
(char **) realizes_xpm, /* pixmap */
&realizes_type_ops, /* ops */
NULL, /* pixmap_file */
0 /* default_user_data */
};
static ObjectOps realizes_ops = {
(DestroyFunc) realizes_destroy,
(DrawFunc) realizes_draw,
(DistanceFunc) realizes_distance_from,
(SelectFunc) realizes_select,
(CopyFunc) object_copy_using_properties,
(MoveFunc) realizes_move,
(MoveHandleFunc) realizes_move_handle,
(GetPropertiesFunc) object_create_props_dialog,
(ApplyPropertiesDialogFunc) object_apply_props_from_dialog,
(ObjectMenuFunc) realizes_get_object_menu,
(DescribePropsFunc) realizes_describe_props,
(GetPropsFunc) realizes_get_props,
(SetPropsFunc) realizes_set_props,
(TextEditFunc) 0,
(ApplyPropertiesListFunc) object_apply_props,
};
static PropDescription realizes_props[] = {
ORTHCONN_COMMON_PROPERTIES,
PROP_STD_LINE_COLOUR_OPTIONAL,
/* can't use PROP_STD_TEXT_COLOUR_OPTIONAL cause it has PROP_FLAG_DONT_SAVE. It is designed to fill the Text object - not some subset */
PROP_STD_TEXT_COLOUR_OPTIONS(PROP_FLAG_VISIBLE|PROP_FLAG_STANDARD|PROP_FLAG_OPTIONAL),
{ "name", PROP_TYPE_STRING, PROP_FLAG_VISIBLE,
N_("Name:"), NULL, NULL },
{ "stereotype", PROP_TYPE_STRING, PROP_FLAG_VISIBLE,
N_("Stereotype:"), NULL, NULL },
PROP_DESC_END
};
static PropDescription *
realizes_describe_props(Realizes *realizes)
{
if (realizes_props[0].quark == 0) {
prop_desc_list_calculate_quarks(realizes_props);
}
return realizes_props;
}
static PropOffset realizes_offsets[] = {
ORTHCONN_COMMON_PROPERTIES_OFFSETS,
{ "line_colour", PROP_TYPE_COLOUR, offsetof(Realizes, line_color) },
{ "text_colour", PROP_TYPE_COLOUR, offsetof(Realizes, text_color) },
{ "name", PROP_TYPE_STRING, offsetof(Realizes, name) },
{ "stereotype", PROP_TYPE_STRING, offsetof(Realizes, stereotype) },
{ NULL, 0, 0 }
};
static void
realizes_get_props(Realizes * realizes, GPtrArray *props)
{
object_get_props_from_offsets(&realizes->orth.object,
realizes_offsets,props);
}
static void
realizes_set_props(Realizes *realizes, GPtrArray *props)
{
object_set_props_from_offsets(&realizes->orth.object,
realizes_offsets, props);
g_free(realizes->st_stereotype);
realizes->st_stereotype = NULL;
realizes_update_data(realizes);
}
static real
realizes_distance_from(Realizes *realize, Point *point)
{
OrthConn *orth = &realize->orth;
return orthconn_distance_from(orth, point, REALIZES_WIDTH);
}
static void
realizes_select(Realizes *realize, Point *clicked_point,
DiaRenderer *interactive_renderer)
{
orthconn_update_data(&realize->orth);
}
static ObjectChange*
realizes_move_handle(Realizes *realize, Handle *handle,
Point *to, ConnectionPoint *cp,
HandleMoveReason reason, ModifierKeys modifiers)
{
ObjectChange *change;
assert(realize!=NULL);
assert(handle!=NULL);
assert(to!=NULL);
change = orthconn_move_handle(&realize->orth, handle, to, cp, reason, modifiers);
realizes_update_data(realize);
return change;
}
static ObjectChange*
realizes_move(Realizes *realize, Point *to)
{
orthconn_move(&realize->orth, to);
realizes_update_data(realize);
return NULL;
}
static void
realizes_draw(Realizes *realize, DiaRenderer *renderer)
{
DiaRendererClass *renderer_ops = DIA_RENDERER_GET_CLASS (renderer);
OrthConn *orth = &realize->orth;
Point *points;
int n;
Point pos;
Arrow arrow;
points = &orth->points[0];
n = orth->numpoints;
renderer_ops->set_linewidth(renderer, REALIZES_WIDTH);
renderer_ops->set_linestyle(renderer, LINESTYLE_DASHED);
renderer_ops->set_dashlength(renderer, REALIZES_DASHLEN);
renderer_ops->set_linejoin(renderer, LINEJOIN_MITER);
renderer_ops->set_linecaps(renderer, LINECAPS_BUTT);
arrow.type = ARROW_HOLLOW_TRIANGLE;
arrow.width = REALIZES_TRIANGLESIZE;
arrow.length = REALIZES_TRIANGLESIZE;
renderer_ops->draw_polyline_with_arrows(renderer, points, n,
REALIZES_WIDTH,
&realize->line_color,
&arrow, NULL);
renderer_ops->set_font(renderer, realize_font, REALIZES_FONTHEIGHT);
pos = realize->text_pos;
if (realize->st_stereotype != NULL && realize->st_stereotype[0] != '\0') {
renderer_ops->draw_string(renderer,
realize->st_stereotype,
&pos, realize->text_align,
&realize->text_color);
pos.y += REALIZES_FONTHEIGHT;
}
if (realize->name != NULL && realize->name[0] != '\0') {
renderer_ops->draw_string(renderer,
realize->name,
&pos, realize->text_align,
&realize->text_color);
}
}
static void
realizes_update_data(Realizes *realize)
{
OrthConn *orth = &realize->orth;
DiaObject *obj = &orth->object;
int num_segm, i;
Point *points;
Rectangle rect;
PolyBBExtras *extra;
orthconn_update_data(orth);
realize->text_width = 0.0;
realize->stereotype = remove_stereotype_from_string(realize->stereotype);
if (!realize->st_stereotype) {
realize->st_stereotype = string_to_stereotype(realize->stereotype);
}
if (realize->name)
realize->text_width = dia_font_string_width(realize->name, realize_font,
REALIZES_FONTHEIGHT);
if (realize->stereotype)
realize->text_width = MAX(realize->text_width,
dia_font_string_width(realize->stereotype,
realize_font,
REALIZES_FONTHEIGHT));
extra = &orth->extra_spacing;
extra->start_trans = REALIZES_WIDTH/2.0 + REALIZES_TRIANGLESIZE;
extra->start_long =
extra->middle_trans =
extra->end_trans =
extra->end_long = REALIZES_WIDTH/2.0;
orthconn_update_boundingbox(orth);
/* Calc text pos: */
num_segm = realize->orth.numpoints - 1;
points = realize->orth.points;
i = num_segm / 2;
if ((num_segm % 2) == 0) { /* If no middle segment, use horizontal */
if (realize->orth.orientation[i]==VERTICAL)
i--;
}
switch (realize->orth.orientation[i]) {
case HORIZONTAL:
realize->text_align = ALIGN_CENTER;
realize->text_pos.x = 0.5*(points[i].x+points[i+1].x);
realize->text_pos.y = points[i].y;
if (realize->name)
realize->text_pos.y -=
dia_font_descent(realize->name,realize_font, REALIZES_FONTHEIGHT);
break;
case VERTICAL:
realize->text_align = ALIGN_LEFT;
realize->text_pos.x = points[i].x + 0.1;
realize->text_pos.y = 0.5*(points[i].y+points[i+1].y);
if (realize->name)
realize->text_pos.y -=
dia_font_descent(realize->name, realize_font, REALIZES_FONTHEIGHT);
break;
}
/* Add the text recangle to the bounding box: */
rect.left = realize->text_pos.x;
if (realize->text_align == ALIGN_CENTER)
rect.left -= realize->text_width/2.0;
rect.right = rect.left + realize->text_width;
rect.top = realize->text_pos.y;
if (realize->name)
rect.top -= dia_font_ascent(realize->name,realize_font, REALIZES_FONTHEIGHT);
rect.bottom = rect.top + 2*REALIZES_FONTHEIGHT;
rectangle_union(&obj->bounding_box, &rect);
}
static ObjectChange *
realizes_add_segment_callback(DiaObject *obj, Point *clicked, gpointer data)
{
ObjectChange *change;
change = orthconn_add_segment((OrthConn *)obj, clicked);
realizes_update_data((Realizes *)obj);
return change;
}
static ObjectChange *
realizes_delete_segment_callback(DiaObject *obj, Point *clicked, gpointer data)
{
ObjectChange *change;
change = orthconn_delete_segment((OrthConn *)obj, clicked);
realizes_update_data((Realizes *)obj);
return change;
}
static DiaMenuItem object_menu_items[] = {
{ N_("Add segment"), realizes_add_segment_callback, NULL, 1 },
{ N_("Delete segment"), realizes_delete_segment_callback, NULL, 1 },
ORTHCONN_COMMON_MENUS,
};
static DiaMenu object_menu = {
"Realizes",
sizeof(object_menu_items)/sizeof(DiaMenuItem),
object_menu_items,
NULL
};
static DiaMenu *
realizes_get_object_menu(Realizes *realize, Point *clickedpoint)
{
OrthConn *orth;
orth = &realize->orth;
/* Set entries sensitive/selected etc here */
object_menu_items[0].active = orthconn_can_add_segment(orth, clickedpoint);
object_menu_items[1].active = orthconn_can_delete_segment(orth, clickedpoint);
orthconn_update_object_menu(orth, clickedpoint, &object_menu_items[2]);
return &object_menu;
}
static DiaObject *
realizes_create(Point *startpoint,
void *user_data,
Handle **handle1,
Handle **handle2)
{
Realizes *realize;
OrthConn *orth;
DiaObject *obj;
PolyBBExtras *extra;
if (realize_font == NULL) {
realize_font =
dia_font_new_from_style (DIA_FONT_MONOSPACE, REALIZES_FONTHEIGHT);
}
realize = g_malloc0(sizeof(Realizes));
orth = &realize->orth;
obj = &orth->object;
extra = &orth->extra_spacing;
obj->type = &realizes_type;
obj->ops = &realizes_ops;
orthconn_init(orth, startpoint);
realize->text_color = color_black;
realize->line_color = attributes_get_foreground();
realize->name = NULL;
realize->stereotype = NULL;
realize->st_stereotype = NULL;
realize->text_width = 0;
extra->start_trans = REALIZES_WIDTH/2.0 + REALIZES_TRIANGLESIZE;
extra->start_long =
extra->middle_trans =
extra->end_trans =
extra->end_long = REALIZES_WIDTH/2.0;
realizes_update_data(realize);
*handle1 = orth->handles[0];
*handle2 = orth->handles[orth->numpoints-2];
return &realize->orth.object;
}
static void
realizes_destroy(Realizes *realize)
{
g_free(realize->name);
g_free(realize->stereotype);
g_free(realize->st_stereotype);
orthconn_destroy(&realize->orth);
}
static DiaObject *
realizes_load(ObjectNode obj_node, int version, const char *filename)
{
DiaObject *obj = object_load_using_properties(&realizes_type,
obj_node,version,filename);
if (version == 0) {
AttributeNode attr;
/* In old objects with no autorouting, set it to false. */
attr = object_find_attribute(obj_node, "autorouting");
if (attr == NULL)
((OrthConn*)obj)->autorouting = FALSE;
}
return obj;
}
| montsuqi/monpe | objects/UML/realizes.c | C | gpl-2.0 | 13,321 |
/*
* IEEE 802.15.4 dgram socket interface
*
* Copyright 2007, 2008 Siemens AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Written by:
* Sergey Lapin <slapin@ossfans.org>
* Dmitry Eremin-Solenikov <dbaryshkov@gmail.com>
*/
#include <linux/capability.h>
#include <linux/net.h>
#include <linux/module.h>
#include <linux/if_arp.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/af_ieee802154.h>
#include <net/ieee802154.h>
#include <net/ieee802154_netdev.h>
#include <asm/ioctls.h>
#include "af802154.h"
static HLIST_HEAD(dgram_head);
static DEFINE_RWLOCK(dgram_lock);
struct dgram_sock {
struct sock sk;
struct ieee802154_addr src_addr;
struct ieee802154_addr dst_addr;
unsigned int bound:1;
unsigned int connected:1;
unsigned int want_ack:1;
unsigned int secen:1;
unsigned int secen_override:1;
unsigned int seclevel:3;
unsigned int seclevel_override:1;
};
static inline struct dgram_sock *dgram_sk(const struct sock *sk)
{
return container_of(sk, struct dgram_sock, sk);
}
static void dgram_hash(struct sock *sk)
{
write_lock_bh(&dgram_lock);
sk_add_node(sk, &dgram_head);
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
write_unlock_bh(&dgram_lock);
}
static void dgram_unhash(struct sock *sk)
{
write_lock_bh(&dgram_lock);
if (sk_del_node_init(sk))
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&dgram_lock);
}
static int dgram_init(struct sock *sk)
{
struct dgram_sock *ro = dgram_sk(sk);
ro->want_ack = 1;
return 0;
}
static void dgram_close(struct sock *sk, long timeout)
{
sk_common_release(sk);
}
static int dgram_bind(struct sock *sk, struct sockaddr *uaddr, int len)
{
struct sockaddr_ieee802154 *addr = (struct sockaddr_ieee802154 *)uaddr;
struct ieee802154_addr haddr;
struct dgram_sock *ro = dgram_sk(sk);
int err = -EINVAL;
struct net_device *dev;
lock_sock(sk);
ro->bound = 0;
if (len < sizeof(*addr))
goto out;
if (addr->family != AF_IEEE802154)
goto out;
ieee802154_addr_from_sa(&haddr, &addr->addr);
dev = ieee802154_get_dev(sock_net(sk), &haddr);
if (!dev) {
err = -ENODEV;
goto out;
}
if (dev->type != ARPHRD_IEEE802154) {
err = -ENODEV;
goto out_put;
}
ro->src_addr = haddr;
ro->bound = 1;
err = 0;
out_put:
dev_put(dev);
out:
release_sock(sk);
return err;
}
static int dgram_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ:
{
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ:
{
struct sk_buff *skb;
unsigned long amount;
amount = 0;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb != NULL) {
/* We will only return the amount
* of this packet since that is all
* that will be read.
*/
amount = skb->len - ieee802154_hdr_length(skb);
}
spin_unlock_bh(&sk->sk_receive_queue.lock);
return put_user(amount, (int __user *)arg);
}
}
return -ENOIOCTLCMD;
}
/* FIXME: autobind */
static int dgram_connect(struct sock *sk, struct sockaddr *uaddr,
int len)
{
struct sockaddr_ieee802154 *addr = (struct sockaddr_ieee802154 *)uaddr;
struct dgram_sock *ro = dgram_sk(sk);
int err = 0;
if (len < sizeof(*addr))
return -EINVAL;
if (addr->family != AF_IEEE802154)
return -EINVAL;
lock_sock(sk);
if (!ro->bound) {
err = -ENETUNREACH;
goto out;
}
ieee802154_addr_from_sa(&ro->dst_addr, &addr->addr);
ro->connected = 1;
out:
release_sock(sk);
return err;
}
static int dgram_disconnect(struct sock *sk, int flags)
{
struct dgram_sock *ro = dgram_sk(sk);
lock_sock(sk);
ro->connected = 0;
release_sock(sk);
return 0;
}
static int dgram_sendmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t size)
{
struct net_device *dev;
unsigned int mtu;
struct sk_buff *skb;
struct ieee802154_mac_cb *cb;
struct dgram_sock *ro = dgram_sk(sk);
struct ieee802154_addr dst_addr;
int hlen, tlen;
int err;
if (msg->msg_flags & MSG_OOB) {
pr_debug("msg->msg_flags = 0x%x\n", msg->msg_flags);
return -EOPNOTSUPP;
}
if (!ro->connected && !msg->msg_name)
return -EDESTADDRREQ;
else if (ro->connected && msg->msg_name)
return -EISCONN;
if (!ro->bound)
dev = dev_getfirstbyhwtype(sock_net(sk), ARPHRD_IEEE802154);
else
dev = ieee802154_get_dev(sock_net(sk), &ro->src_addr);
if (!dev) {
pr_debug("no dev\n");
err = -ENXIO;
goto out;
}
mtu = dev->mtu;
pr_debug("name = %s, mtu = %u\n", dev->name, mtu);
if (size > mtu) {
pr_debug("size = %Zu, mtu = %u\n", size, mtu);
err = -EMSGSIZE;
goto out_dev;
}
hlen = LL_RESERVED_SPACE(dev);
tlen = dev->needed_tailroom;
skb = sock_alloc_send_skb(sk, hlen + tlen + size,
msg->msg_flags & MSG_DONTWAIT,
&err);
if (!skb)
goto out_dev;
skb_reserve(skb, hlen);
skb_reset_network_header(skb);
cb = mac_cb_init(skb);
cb->type = IEEE802154_FC_TYPE_DATA;
cb->ackreq = ro->want_ack;
if (msg->msg_name) {
DECLARE_SOCKADDR(struct sockaddr_ieee802154*,
daddr, msg->msg_name);
ieee802154_addr_from_sa(&dst_addr, &daddr->addr);
} else {
dst_addr = ro->dst_addr;
}
cb->secen = ro->secen;
cb->secen_override = ro->secen_override;
cb->seclevel = ro->seclevel;
cb->seclevel_override = ro->seclevel_override;
err = dev_hard_header(skb, dev, ETH_P_IEEE802154, &dst_addr,
ro->bound ? &ro->src_addr : NULL, size);
if (err < 0)
goto out_skb;
err = memcpy_from_msg(skb_put(skb, size), msg, size);
if (err < 0)
goto out_skb;
skb->dev = dev;
skb->sk = sk;
skb->protocol = htons(ETH_P_IEEE802154);
dev_put(dev);
err = dev_queue_xmit(skb);
if (err > 0)
err = net_xmit_errno(err);
return err ?: size;
out_skb:
kfree_skb(skb);
out_dev:
dev_put(dev);
out:
return err;
}
static int dgram_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int noblock,
int flags, int *addr_len)
{
size_t copied = 0;
int err = -EOPNOTSUPP;
struct sk_buff *skb;
DECLARE_SOCKADDR(struct sockaddr_ieee802154 *, saddr, msg->msg_name);
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
/* FIXME: skip headers if necessary ?! */
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_ts_and_drops(msg, sk, skb);
if (saddr) {
saddr->family = AF_IEEE802154;
ieee802154_addr_to_sa(&saddr->addr, &mac_cb(skb)->source);
*addr_len = sizeof(*saddr);
}
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
if (err)
return err;
return copied;
}
static int dgram_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
skb = skb_share_check(skb, GFP_ATOMIC);
if (!skb)
return NET_RX_DROP;
if (sock_queue_rcv_skb(sk, skb) < 0) {
kfree_skb(skb);
return NET_RX_DROP;
}
return NET_RX_SUCCESS;
}
static inline bool
ieee802154_match_sock(__le64 hw_addr, __le16 pan_id, __le16 short_addr,
struct dgram_sock *ro)
{
if (!ro->bound)
return true;
if (ro->src_addr.mode == IEEE802154_ADDR_LONG &&
hw_addr == ro->src_addr.extended_addr)
return true;
if (ro->src_addr.mode == IEEE802154_ADDR_SHORT &&
pan_id == ro->src_addr.pan_id &&
short_addr == ro->src_addr.short_addr)
return true;
return false;
}
int ieee802154_dgram_deliver(struct net_device *dev, struct sk_buff *skb)
{
struct sock *sk, *prev = NULL;
int ret = NET_RX_SUCCESS;
__le16 pan_id, short_addr;
__le64 hw_addr;
/* Data frame processing */
BUG_ON(dev->type != ARPHRD_IEEE802154);
pan_id = ieee802154_mlme_ops(dev)->get_pan_id(dev);
short_addr = ieee802154_mlme_ops(dev)->get_short_addr(dev);
hw_addr = ieee802154_devaddr_from_raw(dev->dev_addr);
read_lock(&dgram_lock);
sk_for_each(sk, &dgram_head) {
if (ieee802154_match_sock(hw_addr, pan_id, short_addr,
dgram_sk(sk))) {
if (prev) {
struct sk_buff *clone;
clone = skb_clone(skb, GFP_ATOMIC);
if (clone)
dgram_rcv_skb(prev, clone);
}
prev = sk;
}
}
if (prev) {
dgram_rcv_skb(prev, skb);
} else {
kfree_skb(skb);
ret = NET_RX_DROP;
}
read_unlock(&dgram_lock);
return ret;
}
static int dgram_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
struct dgram_sock *ro = dgram_sk(sk);
int val, len;
if (level != SOL_IEEE802154)
return -EOPNOTSUPP;
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, sizeof(int));
switch (optname) {
case WPAN_WANTACK:
val = ro->want_ack;
break;
case WPAN_SECURITY:
if (!ro->secen_override)
val = WPAN_SECURITY_DEFAULT;
else if (ro->secen)
val = WPAN_SECURITY_ON;
else
val = WPAN_SECURITY_OFF;
break;
case WPAN_SECURITY_LEVEL:
if (!ro->seclevel_override)
val = WPAN_SECURITY_LEVEL_DEFAULT;
else
val = ro->seclevel;
break;
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
static int dgram_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct dgram_sock *ro = dgram_sk(sk);
struct net *net = sock_net(sk);
int val;
int err = 0;
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case WPAN_WANTACK:
ro->want_ack = !!val;
break;
case WPAN_SECURITY:
if (!ns_capable(net->user_ns, CAP_NET_ADMIN) &&
!ns_capable(net->user_ns, CAP_NET_RAW)) {
err = -EPERM;
break;
}
switch (val) {
case WPAN_SECURITY_DEFAULT:
ro->secen_override = 0;
break;
case WPAN_SECURITY_ON:
ro->secen_override = 1;
ro->secen = 1;
break;
case WPAN_SECURITY_OFF:
ro->secen_override = 1;
ro->secen = 0;
break;
default:
err = -EINVAL;
break;
}
break;
case WPAN_SECURITY_LEVEL:
if (!ns_capable(net->user_ns, CAP_NET_ADMIN) &&
!ns_capable(net->user_ns, CAP_NET_RAW)) {
err = -EPERM;
break;
}
if (val < WPAN_SECURITY_LEVEL_DEFAULT ||
val > IEEE802154_SCF_SECLEVEL_ENC_MIC128) {
err = -EINVAL;
} else if (val == WPAN_SECURITY_LEVEL_DEFAULT) {
ro->seclevel_override = 0;
} else {
ro->seclevel_override = 1;
ro->seclevel = val;
}
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
struct proto ieee802154_dgram_prot = {
.name = "IEEE-802.15.4-MAC",
.owner = THIS_MODULE,
.obj_size = sizeof(struct dgram_sock),
.init = dgram_init,
.close = dgram_close,
.bind = dgram_bind,
.sendmsg = dgram_sendmsg,
.recvmsg = dgram_recvmsg,
.hash = dgram_hash,
.unhash = dgram_unhash,
.connect = dgram_connect,
.disconnect = dgram_disconnect,
.ioctl = dgram_ioctl,
.getsockopt = dgram_getsockopt,
.setsockopt = dgram_setsockopt,
};
| kendling/android_kernel_google_dragon | net/ieee802154/dgram.c | C | gpl-2.0 | 11,497 |
/* Copyright (C) 1996, 1997, 1998 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <hurd.h>
#include <hurd/signal.h>
#include <hurd/threadvar.h>
#include <stdlib.h>
#include <mach/mips/mips_instruction.h>
int
__sigreturn (struct sigcontext *scp)
{
struct hurd_sigstate *ss;
struct hurd_userlink *link = (void *) &scp[1];
mach_port_t *reply_port;
if (scp == NULL || (scp->sc_mask & _SIG_CANT_MASK))
{
errno = EINVAL;
return -1;
}
ss = _hurd_self_sigstate ();
__spin_lock (&ss->lock);
/* Remove the link on the `active resources' chain added by
_hurd_setup_sighandler. Its purpose was to make sure
that we got called; now we have, it is done. */
_hurd_userlink_unlink (link);
/* Restore the set of blocked signals, and the intr_port slot. */
ss->blocked = scp->sc_mask;
ss->intr_port = scp->sc_intr_port;
/* Check for pending signals that were blocked by the old set. */
if (ss->pending & ~ss->blocked)
{
/* There are pending signals that just became unblocked. Wake up the
signal thread to deliver them. But first, squirrel away SCP where
the signal thread will notice it if it runs another handler, and
arrange to have us called over again in the new reality. */
ss->context = scp;
__spin_unlock (&ss->lock);
__msg_sig_post (_hurd_msgport, 0, 0, __mach_task_self ());
/* If a pending signal was handled, sig_post never returned. */
__spin_lock (&ss->lock);
ss->context = NULL;
}
if (scp->sc_onstack)
{
ss->sigaltstack.ss_flags &= ~SS_ONSTACK; /* XXX threadvars */
/* XXX cannot unlock until off sigstack */
abort ();
}
else
__spin_unlock (&ss->lock);
/* Destroy the MiG reply port used by the signal handler, and restore the
reply port in use by the thread when interrupted. */
reply_port =
(mach_port_t *) __hurd_threadvar_location (_HURD_THREADVAR_MIG_REPLY);
if (*reply_port)
{
mach_port_t port = *reply_port;
/* Assigning MACH_PORT_DEAD here tells libc's mig_get_reply_port not to
get another reply port, but avoids mig_dealloc_reply_port trying to
deallocate it after the receive fails (which it will, because the
reply port will be bogus, whether we do this or not). */
*reply_port = MACH_PORT_DEAD;
__mach_port_destroy (__mach_task_self (), port);
}
*reply_port = scp->sc_reply_port;
if (scp->sc_coproc_used & SC_COPROC_USE_FPU)
{
/* Restore FPU state. */
#define restore_fpr(n) \
asm volatile ("l.d $f" #n ",%0" : : "m" (scp->sc_fpr[n]))
/* Restore floating-point registers. */
#ifdef __mips64
restore_fpr (0);
restore_fpr (1);
restore_fpr (2);
restore_fpr (3);
restore_fpr (4);
restore_fpr (5);
restore_fpr (6);
restore_fpr (7);
restore_fpr (8);
restore_fpr (9);
restore_fpr (10);
restore_fpr (11);
restore_fpr (12);
restore_fpr (13);
restore_fpr (14);
restore_fpr (15);
restore_fpr (16);
restore_fpr (17);
restore_fpr (18);
restore_fpr (19);
restore_fpr (20);
restore_fpr (21);
restore_fpr (22);
restore_fpr (23);
restore_fpr (24);
restore_fpr (25);
restore_fpr (26);
restore_fpr (27);
restore_fpr (28);
restore_fpr (29);
restore_fpr (30);
restore_fpr (31);
#else
restore_fpr (0);
restore_fpr (2);
restore_fpr (4);
restore_fpr (6);
restore_fpr (8);
restore_fpr (10);
restore_fpr (12);
restore_fpr (14);
restore_fpr (16);
restore_fpr (18);
restore_fpr (20);
restore_fpr (22);
restore_fpr (24);
restore_fpr (26);
restore_fpr (28);
restore_fpr (30);
#endif
/* Restore the floating-point control/status register ($f31). */
asm volatile ("ctc1 %0,$f31" : : "r" (scp->sc_fpcsr));
}
/* Load all the registers from the sigcontext. */
#ifdef __mips64
#define restore_gpr(n) \
asm volatile ("ld $" #n ",%0" : : "m" (scpreg->sc_gpr[n - 1]))
#else
#define restore_gpr(n) \
asm volatile ("lw $" #n ",%0" : : "m" (scpreg->sc_gpr[n - 1]))
#endif
{
register const struct sigcontext *const scpreg asm ("$1") = scp;
register int *at asm ("$1");
/* First restore the multiplication result registers. The compiler
will use some temporary registers, so we do this before restoring
the general registers. */
asm volatile ("mtlo %0" : : "r" (scpreg->sc_mdlo));
asm volatile ("mthi %0" : : "r" (scpreg->sc_mdhi));
/* In the word after the saved PC, store the saved $1 value. */
(&scpreg->sc_pc)[1] = scpreg->sc_gpr[0];
asm volatile (".set noreorder; .set noat;");
/* Restore the normal registers. */
restore_gpr (2);
restore_gpr (3);
restore_gpr (4);
restore_gpr (5);
restore_gpr (6);
restore_gpr (7);
restore_gpr (8);
restore_gpr (9);
restore_gpr (10);
restore_gpr (11);
restore_gpr (12);
restore_gpr (13);
restore_gpr (14);
restore_gpr (15);
restore_gpr (16);
restore_gpr (17);
restore_gpr (18);
restore_gpr (19);
restore_gpr (20);
restore_gpr (21);
restore_gpr (22);
restore_gpr (23);
restore_gpr (24);
restore_gpr (25);
/* Registers 26-27 are kernel-only. */
restore_gpr (28);
restore_gpr (29); /* Stack pointer. */
restore_gpr (30); /* Frame pointer. */
restore_gpr (31); /* Return address. */
at = &scpreg->sc_pc;
/* This is an emulated instruction that will find at the address in $1
two words: the PC value to restore, and the $1 value to restore. */
asm volatile (".word %0" : : "i" (op_sigreturn));
asm volatile (".set reorder; .set at;");
/* NOTREACHED */
return at; /* To prevent optimization. */
}
/* NOTREACHED */
return -1;
}
weak_alias (__sigreturn, sigreturn)
| nslu2/glibc | sysdeps/mach/hurd/mips/sigreturn.c | C | gpl-2.0 | 6,737 |
<?php
/**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div class="wf-container wf-clearfix">
*
* @package presscore
* @since presscore 0.1
*/
// File Security Check
if ( ! defined( 'ABSPATH' ) ) { exit; }
?><!DOCTYPE html>
<!--[if IE 6]>
<html id="ie6" class="ancient-ie old-ie no-js" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 7]>
<html id="ie7" class="ancient-ie old-ie no-js" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html id="ie8" class="old-ie no-js" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 9]>
<html id="ie9" class="old-ie9 no-js" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!-->
<html class="no-js" <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<?php if ( presscore_responsive() ) : ?>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<?php endif; // is responsive?>
<?php if ( dt_retina_on() ) { dt_core_detect_retina_script(); } ?>
<title><?php echo presscore_blog_title(); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style type="text/css" id="static-stylesheet"></style>
<?php
if ( ! is_preview() ) {
presscore_favicon();
echo of_get_option('general-tracking_code', '');
presscore_icons_for_handhelded_devices();
}
wp_head();
?>
</head>
<body <?php body_class(); ?>>
<?php do_action( 'presscore_body_top' ); ?>
<div id="page"<?php if ( 'boxed' == of_get_option('general-layout', 'wide') ) echo ' class="boxed"'; ?>>
<?php if ( of_get_option('top_bar-show', 1) ) : ?>
<?php get_template_part( 'templates/header/top-bar', of_get_option('top_bar-content_alignment', 'side') ); ?>
<?php endif; // show top bar ?>
<?php if ( apply_filters( 'presscore_show_header', true ) ) : ?>
<?php get_template_part( 'templates/header/header', of_get_option( 'header-layout', 'left' ) ); ?>
<?php endif; // show header ?>
<?php do_action( 'presscore_before_main_container' ); ?>
<div id="main" <?php presscore_main_container_classes(); ?>><!-- class="sidebar-none", class="sidebar-left", class="sidebar-right" -->
<?php if ( presscore_is_content_visible() ): ?>
<div class="main-gradient"></div>
<div class="wf-wrap">
<div class="wf-container-main">
<?php do_action( 'presscore_before_content' ); ?>
<?php endif; ?>
| wiljenum/wordpress-jo | wp-content/themes/dt-the7/header.php | PHP | gpl-2.0 | 2,604 |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 1997-2008 Morgan Stanley All rights reserved.
// See .../src/LICENSE for terms of distribution
//
//
///////////////////////////////////////////////////////////////////////////////
#include <MSGUI/MSRadioBox.H>
MSRadioBox::MSRadioBox(MSWidget *owner_,const char *title_) :
MSActionBox(owner_,title_)
{ _activeButton=0; }
MSRadioBox::MSRadioBox(MSWidget *owner_,const MSStringVector& title_) :
MSActionBox(owner_,title_)
{ _activeButton=0; }
MSRadioBox::~MSRadioBox(void) {}
const MSSymbol& MSRadioBox::symbol(void)
{
static MSSymbol sym ("MSRadioBox");
return sym;
}
const MSSymbol& MSRadioBox::widgetType(void) const
{ return symbol(); }
void MSRadioBox::arm(MSRadioButton *radioButton_)
{
disarm();
_activeButton=radioButton_;
if (activeButton()!=0) activeButton()->state(MSTrue);
}
void MSRadioBox::disarm(void)
{
if (activeButton()!=0) activeButton()->state(MSFalse);
_activeButton=0;
}
void MSRadioBox::firstMapNotify(void)
{
MSNodeItem *hp=childListHead();
MSNodeItem *np=hp;
MSLayoutEntry *entry;
MSRadioButton *radioButton;
unsigned count=0;
while ((np=np->next())!=hp)
{
entry=(MSLayoutEntry *)np->data();
radioButton=(MSRadioButton *)entry->widget();
if (radioButton->state()==MSTrue)
{
if (count==0) _activeButton=radioButton;
count++;
}
if (count>1) radioButton->state(MSFalse);
}
if (count==0&&(np=np->next())!=hp)
{
entry=(MSLayoutEntry *)np->data();
radioButton=(MSRadioButton *)entry->widget();
radioButton->state(MSTrue);
_activeButton=radioButton;
}
MSActionBox::firstMapNotify();
}
void MSRadioBox::activeButton(MSRadioButton *radioButton_, MSBoolean callback_)
{
radioButton_->arm(callback_);
}
| rdm/aplus-fsf | src/MSGUI/MSRadioBox.C | C++ | gpl-2.0 | 1,875 |
<?php
/**
* @package Joomla.Platform
* @subpackage Twitter
*
* @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die();
/**
* Twitter API Search class for the Joomla Platform.
*
* @since 12.3
*/
class JTwittersearch extends JTwitterObject
{
/**
* Method to get tweets that match a specified query.
*
* @param string $query Search query. Should be URL encoded. Queries will be limited by complexity.
* @param string $callback If supplied, the response will use the JSONP format with a callback of the given name
* @param string $geocode Returns tweets by users located within a given radius of the given latitude/longitude. The parameter value is
* specified by "latitude,longitude,radius", where radius units must be specified as either "mi" (miles) or "km" (kilometers).
* @param string $lang Restricts tweets to the given language, given by an ISO 639-1 code.
* @param string $locale Specify the language of the query you are sending (only ja is currently effective). This is intended for
* language-specific clients and the default should work in the majority of cases.
* @param string $result_type Specifies what type of search results you would prefer to receive. The current default is "mixed."
* @param integer $count The number of tweets to return per page, up to a maximum of 100. Defaults to 15.
* @param string $until Returns tweets generated before the given date. Date should be formatted as YYYY-MM-DD.
* @param integer $since_id Returns results with an ID greater than (that is, more recent than) the specified ID.
* @param integer $max_id Returns results with an ID less than (that is, older than) or equal to the specified ID.
* @param boolean $entities When set to either true, t or 1, each tweet will include a node called "entities,". This node offers a
* variety of metadata about the tweet in a discrete structure, including: urls, media and hashtags.
*
* @return array The decoded JSON response
*
* @since 12.3
*/
public function search($query, $callback = null, $geocode = null, $lang = null, $locale = null, $result_type = null, $count = 15,
$until = null, $since_id = 0, $max_id = 0, $entities = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('search', 'tweets');
// Set the API path
$path = '/search/tweets.json';
// Set query parameter.
$data['q'] = rawurlencode($query);
// Check if callback is specified.
if ($callback)
{
$data['callback'] = $callback;
}
// Check if geocode is specified.
if ($geocode)
{
$data['geocode'] = $geocode;
}
// Check if lang is specified.
if ($lang)
{
$data['lang'] = $lang;
}
// Check if locale is specified.
if ($locale)
{
$data['locale'] = $locale;
}
// Check if result_type is specified.
if ($result_type)
{
$data['result_type'] = $result_type;
}
// Check if count is specified.
if ($count != 15)
{
$data['count'] = $count;
}
// Check if until is specified.
if ($until)
{
$data['until'] = $until;
}
// Check if since_id is specified.
if ($since_id > 0)
{
$data['since_id'] = $since_id;
}
// Check if max_id is specified.
if ($max_id > 0)
{
$data['max_id'] = $max_id;
}
// Check if entities is specified.
if (!is_null($entities))
{
$data['include_entities'] = $entities;
}
// Send the request.
return $this->sendRequest($path, 'GET', $data);
}
/**
* Method to get the authenticated user's saved search queries.
*
* @return array The decoded JSON response
*
* @since 12.3
*/
public function getSavedSearches()
{
// Check the rate limit for remaining hits
$this->checkRateLimit('saved_searches', 'list');
// Set the API path
$path = '/saved_searches/list.json';
// Send the request.
return $this->sendRequest($path);
}
/**
* Method to get the information for the saved search represented by the given id.
*
* @param integer $id The ID of the saved search.
*
* @return array The decoded JSON response
*
* @since 12.3
*/
public function getSavedSearchesById($id)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('saved_searches', 'show/:id');
// Set the API path
$path = '/saved_searches/show/' . $id . '.json';
// Send the request.
return $this->sendRequest($path);
}
/**
* Method to create a new saved search for the authenticated user.
*
* @param string $query The query of the search the user would like to save.
*
* @return array The decoded JSON response
*
* @since 12.3
*/
public function createSavedSearch($query)
{
// Set the API path
$path = '/saved_searches/create.json';
// Set POST request data
$data['query'] = rawurlencode($query);
// Send the request.
return $this->sendRequest($path, 'POST', $data);
}
/**
* Method to delete a saved search for the authenticating user.
*
* @param integer $id The ID of the saved search.
*
* @return array The decoded JSON response
*
* @since 12.3
*/
public function deleteSavedSearch($id)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('saved_searches', 'destroy/:id');
// Set the API path
$path = '/saved_searches/destroy/' . $id . '.json';
// Send the request.
return $this->sendRequest($path, 'POST');
}
}
| waveywhite/joomla-cms | libraries/joomla/twitter/search.php | PHP | gpl-2.0 | 5,627 |
$(document).ready(function(){
// removing some column headers when there is at least one product
if ( $('#lines tbody tr.product').length > 0 )
{
$('#lines').addClass('with-product');
$('body').addClass('with-product');
}
if ( $('#lines tbody tr.ticket').length > 0 )
{
$('#lines').addClass('with-ticket');
$('body').addClass('with-ticket');
}
window.print();
// update the parent window's content
if ( window.opener != undefined && typeof window.opener.li === 'object' )
window.opener.li.initContent();
// print again
if ( $('#options #print-again').length > 0 )
window.location = $('#options #print-again a').prop('href');
// close
if ( $('#options #close').length > 0 && $('#options #print-again').length == 0 )
window.close();
});
| Fabrice-li/e-venement | web/js/print-tickets.js | JavaScript | gpl-2.0 | 803 |
#ifndef _LINUX_PTRACE_H
#define _LINUX_PTRACE_H
/* ptrace.h */
/* structs and defines to help the user use the ptrace system call. */
/* has the defines to get at the registers. */
#define PTRACE_TRACEME 0
#define PTRACE_PEEKTEXT 1
#define PTRACE_PEEKDATA 2
#define PTRACE_PEEKUSR 3
#define PTRACE_POKETEXT 4
#define PTRACE_POKEDATA 5
#define PTRACE_POKEUSR 6
#define PTRACE_CONT 7
#define PTRACE_KILL 8
#define PTRACE_SINGLESTEP 9
#define PTRACE_ATTACH 0x10
#define PTRACE_DETACH 0x11
#define PTRACE_SYSCALL 24
/* 0x4200-0x4300 are reserved for architecture-independent additions. */
#define PTRACE_SETOPTIONS 0x4200
#define PTRACE_GETEVENTMSG 0x4201
#define PTRACE_GETSIGINFO 0x4202
#define PTRACE_SETSIGINFO 0x4203
/* options set using PTRACE_SETOPTIONS */
#define PTRACE_O_TRACESYSGOOD 0x00000001
#define PTRACE_O_TRACEFORK 0x00000002
#define PTRACE_O_TRACEVFORK 0x00000004
#define PTRACE_O_TRACECLONE 0x00000008
#define PTRACE_O_TRACEEXEC 0x00000010
#define PTRACE_O_TRACEVFORKDONE 0x00000020
#define PTRACE_O_TRACEEXIT 0x00000040
#define PTRACE_O_MASK 0x0000007f
/* Wait extended result codes for the above trace options. */
#define PTRACE_EVENT_FORK 1
#define PTRACE_EVENT_VFORK 2
#define PTRACE_EVENT_CLONE 3
#define PTRACE_EVENT_EXEC 4
#define PTRACE_EVENT_VFORK_DONE 5
#define PTRACE_EVENT_EXIT 6
#include <asm/ptrace.h>
#ifdef __KERNEL__
/*
* Ptrace flags
*/
#define PT_PTRACED 0x00000001
#define PT_DTRACE 0x00000002 /* delayed trace (used on m68k, i386) */
#define PT_TRACESYSGOOD 0x00000004
#define PT_PTRACE_CAP 0x00000008 /* ptracer can follow suid-exec */
#define PT_TRACE_FORK 0x00000010
#define PT_TRACE_VFORK 0x00000020
#define PT_TRACE_CLONE 0x00000040
#define PT_TRACE_EXEC 0x00000080
#define PT_TRACE_VFORK_DONE 0x00000100
#define PT_TRACE_EXIT 0x00000200
#define PT_ATTACHED 0x00000400 /* parent != real_parent */
#define PT_TRACE_MASK 0x000003f4
/* single stepping state bits (used on ARM and PA-RISC) */
#define PT_SINGLESTEP_BIT 31
#define PT_SINGLESTEP (1<<PT_SINGLESTEP_BIT)
#define PT_BLOCKSTEP_BIT 30
#define PT_BLOCKSTEP (1<<PT_BLOCKSTEP_BIT)
#include <linux/compiler.h> /* For unlikely. */
#include <linux/sched.h> /* For struct task_struct. */
extern int ptrace_readdata(struct task_struct *tsk, unsigned long src, char __user *dst, int len);
extern int ptrace_writedata(struct task_struct *tsk, char __user *src, unsigned long dst, int len);
extern int ptrace_attach(struct task_struct *tsk);
extern int ptrace_detach(struct task_struct *, unsigned int);
extern void ptrace_disable(struct task_struct *);
extern int ptrace_check_attach(struct task_struct *task, int kill);
extern int ptrace_request(struct task_struct *child, long request, long addr, long data);
extern void ptrace_notify(int exit_code);
extern void __ptrace_link(struct task_struct *child,
struct task_struct *new_parent);
extern void __ptrace_unlink(struct task_struct *child);
static inline void ptrace_link(struct task_struct *child,
struct task_struct *new_parent)
{
if (unlikely(child->ptrace))
__ptrace_link(child, new_parent);
}
static inline void ptrace_unlink(struct task_struct *child)
{
if (unlikely(child->ptrace))
__ptrace_unlink(child);
}
#ifndef force_successful_syscall_return
/*
* System call handlers that, upon successful completion, need to return a
* negative value should call force_successful_syscall_return() right before
* returning. On architectures where the syscall convention provides for a
* separate error flag (e.g., alpha, ia64, ppc{,64}, sparc{,64}, possibly
* others), this macro can be used to ensure that the error flag will not get
* set. On architectures which do not support a separate error flag, the macro
* is a no-op and the spurious error condition needs to be filtered out by some
* other means (e.g., in user-level, by passing an extra argument to the
* syscall handler, or something along those lines).
*/
#define force_successful_syscall_return() do { } while (0)
#endif
#endif
#endif
| binhqnguyen/lena | nsc/linux-2.6/include/linux/ptrace.h | C | gpl-2.0 | 4,045 |
<?php
/**
* Class SlideshowPluginSlideInserter
*
* TODO This class will probably need to be renamed to SlideshowPluginSlideHandler to explain more functionality
* TODO than just inserting slides.
*
* @since 2.0.0
* @author Stefan Boonstra
*/
class SlideshowPluginSlideInserter
{
/** @var bool $localizedScript Flag to see if localizeScript function has been called */
private static $localizedScript;
/**
* Returns the html for showing the image insert button.
* Localizes script unless $localizeScript is set to false.
*
* @since 2.0.0
* @param boolean $localizeScript
* @return String $button
*/
static function getImageSlideInsertButton($localizeScript = true)
{
if ($localizeScript)
{
self::localizeScript();
}
// Put popup html in footer
add_action('admin_footer', array(__CLASS__, 'includePopup'));
// Return button html
ob_start();
include(SlideshowPluginMain::getPluginPath() . '/views/' . __CLASS__ . '/insert-image-button.php');
return ob_get_clean();
}
/**
* Returns the html for showing the text insert button.
* Localizes script unless $localizeScript is set to false.
*
* @since 2.0.0
* @param boolean $localizeScript
* @return String $button
*/
static function getTextSlideInsertButton($localizeScript = true)
{
if ($localizeScript)
{
self::localizeScript();
}
// Return button html
ob_start();
include(SlideshowPluginMain::getPluginPath() . '/views/' . __CLASS__ . '/insert-text-button.php');
return ob_get_clean();
}
/**
* Returns the html for showing the video insert button.
* Localizes script unless $localizeScript is set to false.
*
* @since 2.1.0
* @param boolean $localizeScript
* @return String $button
*/
static function getVideoSlideInsertButton($localizeScript = true)
{
if ($localizeScript)
{
self::localizeScript();
}
// Return button html
ob_start();
include(SlideshowPluginMain::getPluginPath() . '/views/' . __CLASS__ . '/insert-video-button.php');
return ob_get_clean();
}
/**
* This function is registered in the SlideshowPluginAjax class
* and prints the results from the search query.
*
* @since 2.0.0
*/
static function printSearchResults()
{
global $wpdb;
// Numberposts and offset
$numberPosts = 10;
$offset = 0;
if (isset($_POST['offset']) &&
is_numeric($_POST['offset']))
{
$offset = $_POST['offset'];
}
$attachmentIDs = array();
if (isset($_POST['attachmentIDs']))
{
$attachmentIDs = array_filter($_POST['attachmentIDs'], 'ctype_digit');
}
// Get attachments with a title alike the search string, needs to be filtered
add_filter('posts_where', array(__CLASS__, 'printSearchResultsWhereFilter'));
$query = new WP_Query(array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'offset' => $offset,
'posts_per_page' => $numberPosts + 1,
'orderby' => 'date',
'order' => 'DESC'
));
$attachments = $query->get_posts();
remove_filter('posts_where', array(__CLASS__, 'printSearchResultsWhereFilter'));
// Look for images by their file's name when not enough matching results were found
if (count($attachments) < $numberPosts)
{
$searchString = esc_sql($_POST['search']);
// Add results found with the previous query to the $attachmentIDs array to exclude them as well
foreach ($attachments as $attachment)
{
$attachmentIDs[] = $attachment->ID;
}
// Search by file name
$fileNameQuery = new WP_Query(array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => $numberPosts - count($attachments),
'post__not_in' => $attachmentIDs,
'meta_query' => array(
array(
'key' => '_wp_attached_file',
'value' => $searchString,
'compare' => 'LIKE'
)
)
));
// Put found results in attachments array
$fileNameQueryAttachments = $fileNameQuery->get_posts();
if (is_array($fileNameQueryAttachments) &&
count($fileNameQueryAttachments) > 0)
{
foreach ($fileNameQueryAttachments as $fileNameQueryAttachment)
{
$attachments[] = $fileNameQueryAttachment;
}
}
}
// Check if there are enough attachments to print a 'Load more images' button
$loadMoreResults = false;
if (count($attachments) > $numberPosts)
{
array_pop($attachments);
$loadMoreResults = true;
}
// Print results to the screen
if (count($attachments) > 0)
{
if ($offset > 0)
{
echo '<tr valign="top">
<td colspan="3" style="text-align: center;">
<b>' . count($attachments) . ' ' . __('More results loaded', 'slideshow-plugin') . '<b>
</td>
</tr>';
}
foreach ($attachments as $attachment)
{
$image = wp_get_attachment_image_src($attachment->ID);
if (!is_array($image) ||
!$image)
{
if (!empty($attachment->guid))
{
$imageSrc = $attachment->guid;
}
else
{
continue;
}
}
else
{
$imageSrc = $image[0];
}
if (!$imageSrc ||
empty($imageSrc))
{
$imageSrc = SlideshowPluginMain::getPluginUrl() . '/images/SlideshowPluginPostType/no-img.png';
}
echo '<tr valign="top" data-attachment-Id="' . $attachment->ID . '" class="result-table-row">
<td class="image">
<img width="60" height="60" src="' . $imageSrc . '" class="attachment" alt="' . $attachment->post_title . '" title="' . $attachment->post_title . '">
</td>
<td class="column-title">
<strong class="title">' . $attachment->post_title . '</strong>
<p class="description">' . $attachment->post_content . '</p>
</td>
<td class="insert-button">
<input
type="button"
class="insert-attachment button-secondary"
value="' . __('Insert', 'slideshow-plugin') . '"
/>
</td>
</tr>';
}
if ($loadMoreResults)
{
echo '<tr>
<td colspan="3" style="text-align: center;">
<button class="button-secondary load-more-results" data-offset="' . ($offset + $numberPosts) . '">
' . __('Load more results', 'slideshow-plugin') . '
</button>
</td>
</tr>';
}
}
else
{
echo '<tr>
<td colspan="3" style="text-align: center;">
<a href="' . admin_url() . 'media-new.php" target="_blank">
' . __('No images were found, click here to upload some.', 'slideshow-plugin') . '
</a>
</td>
</tr>';
}
die;
}
/**
* Applies a where clause on the get_posts call from self::printSearchResults()
*
* @since 2.0.0
* @param string $where
* @return string $where
*/
static function printSearchResultsWhereFilter($where)
{
global $wpdb;
$searchString = $_POST['search'];
$searchString = esc_sql($searchString);
if (isset($_POST['search']))
{
$where .= $wpdb->prepare(
" AND (post_title LIKE '%%%s%%' OR ID LIKE '%%%s%%') ",
$searchString,
$searchString
);
}
return $where;
}
/**
* Include popup, needs to be called in the footer
*
* @since 2.0.0
*/
static function includePopup()
{
include(SlideshowPluginMain::getPluginPath() . '/views/' . __CLASS__ . '/search-popup.php');
}
/**
* Enqueues styles and scripts necessary for the media upload button.
*
* @since 2.2.12
*/
static function localizeScript()
{
// Return if function doesn't exist
if (!function_exists('get_current_screen') ||
self::$localizedScript)
{
return;
}
// Return when not on a slideshow edit page, or files have already been included.
$currentScreen = get_current_screen();
if ($currentScreen->post_type != SlideshowPluginPostType::$postType)
{
return;
}
wp_localize_script(
'slideshow-jquery-image-gallery-backend-script',
'slideshow_jquery_image_gallery_backend_script_editSlideshow',
array(
'data' => array(),
'localization' => array(
'confirm' => __('Are you sure you want to delete this slide?', 'slideshow-plugin'),
'uploaderTitle' => __('Insert image slide', 'slideshow-plugin')
)
)
);
// Set enqueued to true
self::$localizedScript = true;
}
} | tzitziras/aluminet.gr | wp-content/plugins/slideshow-jquery-image-gallery/classes/SlideshowPluginSlideInserter.php | PHP | gpl-2.0 | 8,493 |
/*
* Copyright (C) 2014 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
*/
#import <Foundation/Foundation.h>
#ifndef RunLoopThread_h
#define RunLoopThread_h
@interface RunLoopThread : NSObject
typedef void* (*ThreadMainType)(void*);
+ (ThreadMainType)threadMain;
- (void)didFinishRunLoopInitialization;
- (void)start;
- (void)join;
@end
#endif // RunLoopThread_h
| Debian/openjfx | modules/web/src/main/native/Tools/jsc-cli/jsc-cli/RunLoopThread.h | C | gpl-2.0 | 1,651 |
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**
** Copyright (C), 2003, Victorian Partnership for Advanced Computing (VPAC) Ltd, 110 Victoria Street, Melbourne, 3053, Australia.
**
** Authors:
** Stevan M. Quenette, Senior Software Engineer, VPAC. (steve@vpac.org)
** Patrick D. Sunter, Software Engineer, VPAC. (pds@vpac.org)
** Luke J. Hodkinson, Computational Engineer, VPAC. (lhodkins@vpac.org)
** Siew-Ching Tan, Software Engineer, VPAC. (siew@vpac.org)
** Alan H. Lo, Computational Engineer, VPAC. (alan@vpac.org)
** Raquibul Hassan, Computational Engineer, VPAC. (raq@vpac.org)
**
** 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
**
** $Id: IndexMap.c 2192 2004-10-15 02:45:38Z PatrickSunter $
**
**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#include <mpi.h>
#include "Base/Foundation/Foundation.h"
#include "Base/IO/IO.h"
#include "units.h"
#include "types.h"
#include "IndexMap.h"
#include "PtrMap.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
/* Textual name of this class */
const Type IndexMap_Type = "IndexMap";
/*----------------------------------------------------------------------------------------------------------------------------------
** Constructors
*/
IndexMap* IndexMap_New_Param(
unsigned delta )
{
return _IndexMap_New(
sizeof(IndexMap),
IndexMap_Type,
_IndexMap_Delete,
_IndexMap_Print,
_IndexMap_Copy,
delta );
}
void IndexMap_Init(
IndexMap* self,
unsigned delta )
{
/* General info */
self->type = IndexMap_Type;
self->_sizeOfSelf = sizeof(IndexMap);
self->_deleteSelf = False;
/* Virtual info */
self->_delete = _IndexMap_Delete;
self->_print = _IndexMap_Print;
self->_copy = NULL;
_Stg_Class_Init( (Stg_Class*)self );
/* IndexMap info */
_IndexMap_Init( self, delta );
}
IndexMap* _IndexMap_New(
SizeT _sizeOfSelf,
Type type,
Stg_Class_DeleteFunction* _delete,
Stg_Class_PrintFunction* _print,
Stg_Class_CopyFunction* _copy,
unsigned delta )
{
IndexMap* self;
/* Allocate memory */
assert( _sizeOfSelf >= sizeof(IndexMap) );
self = (IndexMap*)_Stg_Class_New(
_sizeOfSelf,
type,
_delete,
_print,
_copy );
/* General info */
/* Virtual info */
/* IndexMap info */
_IndexMap_Init( self, delta );
return self;
}
void _IndexMap_Init(
IndexMap* self,
unsigned delta )
{
/* General and Virtual info should already be set */
/* IndexMap info */
assert( self );
self->delta = delta;
self->maxTuples = self->delta;
self->tupleTbl = Memory_Alloc_Array( IndexMapTuple, self->maxTuples, "IndexMap->tupleTbl" );
assert( self->tupleTbl ); /* TODO change this to a firewall, or something */
self->tupleCnt = 0;
}
/*----------------------------------------------------------------------------------------------------------------------------------
** Virtual functions
*/
void _IndexMap_Delete( void* indexMap ) {
IndexMap* self = (IndexMap*)indexMap;
/* Stg_Class_Delete the class itself */
assert( self );
if( self->tupleTbl ) {
Memory_Free( self->tupleTbl );
}
/* Stg_Class_Delete parent */
_Stg_Class_Delete( self );
}
void _IndexMap_Print( void* indexMap, Stream* stream ) {
IndexMap* self = (IndexMap*)indexMap;
unsigned tuple_I;
/* Set the Journal for printing informations */
Stream* myStream;
myStream = Journal_Register( InfoStream_Type, "IndexMapStream" );
/* Print parent */
assert( self );
_Stg_Class_Print( self, stream );
/* General info */
Journal_Printf( myStream, "IndexMap (ptr): (%p)\n", self );
/* Virtual info */
/* IndexMap info */
for( tuple_I = 0; tuple_I < self->tupleCnt; tuple_I++ ) {
Journal_Printf( myStream, "\ttuple[%d]: %d -> %d\n", tuple_I, self->tupleTbl[tuple_I].key, self->tupleTbl[tuple_I].idx );
}
}
void* _IndexMap_Copy( void* indexMap, void* dest, Bool deep, Name nameExt, struct PtrMap* ptrMap ) {
IndexMap* self = (IndexMap*)indexMap;
IndexMap* newIndexMap;
PtrMap* map = ptrMap;
Bool ownMap = False;
if( !map ) {
map = PtrMap_New( 10 );
ownMap = True;
}
newIndexMap = _Stg_Class_Copy( self, dest, deep, nameExt, map );
newIndexMap->dictionary = self->dictionary;
newIndexMap->delta = self->delta;
newIndexMap->maxTuples = self->maxTuples;
newIndexMap->tupleCnt = self->tupleCnt;
if( deep ) {
if( (newIndexMap->tupleTbl = PtrMap_Find( map, self->tupleTbl )) == NULL && self->tupleTbl ) {
newIndexMap->tupleTbl = Memory_Alloc_Array( IndexMapTuple, self->maxTuples, "IndexMap->tupleTbl" );
memcpy( newIndexMap->tupleTbl, self->tupleTbl, sizeof(IndexMapTuple) * self->maxTuples );
PtrMap_Append( map, self->tupleTbl, newIndexMap->tupleTbl );
}
}
else {
newIndexMap->tupleTbl = self->tupleTbl;
}
if( ownMap ) {
Stg_Class_Delete( map );
}
return (void*)newIndexMap;
}
/*--------------------------------------------------------------------------------------------------------------------------
** Public Functions
*/
void IndexMap_Append( void* indexMap, Index key, Index idx ) {
IndexMap* self = (IndexMap*)indexMap;
unsigned newTupleCnt;
assert( self && key != -1 && idx != -1 );
if( IndexMap_Find( self, key ) != -1 ) {
return;
}
newTupleCnt = self->tupleCnt + 1;
if( newTupleCnt >= self->maxTuples ) {
unsigned factor;
IndexMapTuple* newTuples;
factor = ceil( (float)(newTupleCnt - self->maxTuples) / (float)self->delta );
self->maxTuples += factor * self->delta;
newTuples = Memory_Alloc_Array( IndexMapTuple, self->maxTuples, "IndexMap->tupleTbl" );
assert( newTuples ); /* TODO change this */
if( self->tupleTbl ) {
memcpy( newTuples, self->tupleTbl, sizeof(IndexMapTuple) * self->tupleCnt );
Memory_Free( self->tupleTbl );
}
self->tupleTbl = newTuples;
}
self->tupleTbl[self->tupleCnt].key = key;
self->tupleTbl[self->tupleCnt].idx = idx;
self->tupleCnt = newTupleCnt;
}
Index IndexMap_Find( void* indexMap, Index key ) {
IndexMap* self = (IndexMap*)indexMap;
unsigned tuple_I;
assert( self );
if( key != -1 ) {
for( tuple_I = 0; tuple_I < self->tupleCnt; tuple_I++ ) {
if( self->tupleTbl[tuple_I].key == key )
return self->tupleTbl[tuple_I].idx;
}
}
return -1;
}
void IndexMap_Remap( void* indexMap, void* mapThrough ) {
IndexMap* self = (IndexMap*)indexMap;
Index tuple_I;
for( tuple_I = 0; tuple_I < self->tupleCnt; tuple_I++ ) {
self->tupleTbl[tuple_I].idx = IndexMap_Find( mapThrough, self->tupleTbl[tuple_I].idx );
}
}
/*----------------------------------------------------------------------------------------------------------------------------------
** Private Functions
*/
| bmi-forum/bmi-pyre | StGermain/Base/Container/src/IndexMap.c | C | gpl-2.0 | 7,534 |
/* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/device.h>
#include <linux/printk.h>
#include <linux/ratelimit.h>
#include <linux/debugfs.h>
#include <linux/list.h>
#include <linux/mfd/wcd9xxx/core.h>
#include <linux/mfd/wcd9xxx/core-resource.h>
#include <linux/mfd/wcd9xxx/wcd9xxx_registers.h>
#include <linux/mfd/wcd9xxx/wcd9320_registers.h>
#include <linux/mfd/wcd9xxx/pdata.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/tlv.h>
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/pm_runtime.h>
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <linux/input.h>
#include "wcd9320.h"
#include "wcd9306.h"
#include "wcd9xxx-mbhc.h"
#include "wcdcal-hwdep.h"
#include "wcd9xxx-resmgr.h"
#include "wcd9xxx-common.h"
#define WCD9XXX_JACK_MASK (SND_JACK_HEADSET | SND_JACK_OC_HPHL | \
SND_JACK_OC_HPHR | SND_JACK_LINEOUT | \
SND_JACK_UNSUPPORTED | SND_JACK_MICROPHONE2)
#define WCD9XXX_JACK_BUTTON_MASK (SND_JACK_BTN_0 | SND_JACK_BTN_1 | \
SND_JACK_BTN_2 | SND_JACK_BTN_3 | \
SND_JACK_BTN_4 | SND_JACK_BTN_5 | \
SND_JACK_BTN_6 | SND_JACK_BTN_7)
#define NUM_DCE_PLUG_DETECT 3
#define NUM_DCE_PLUG_INS_DETECT 5
#define NUM_ATTEMPTS_INSERT_DETECT 25
#define NUM_ATTEMPTS_TO_REPORT 5
#define NUM_TO_REPORT_INVALID 10
#define FAKE_INS_LOW 10
#define FAKE_INS_HIGH 80
#define FAKE_INS_HIGH_NO_SWCH 150
#define FAKE_REMOVAL_MIN_PERIOD_MS 50
#define FAKE_INS_DELTA_SCALED_MV 300
#define BUTTON_MIN 0x8000
#define STATUS_REL_DETECTION 0x0C
#define HS_DETECT_PLUG_TIME_MS (5 * 1000)
#define ANC_HPH_DETECT_PLUG_TIME_MS (5 * 1000)
#define HS_DETECT_PLUG_INERVAL_MS 100
#define SWCH_REL_DEBOUNCE_TIME_MS 50
#define SWCH_IRQ_DEBOUNCE_TIME_US 5000
#define BTN_RELEASE_DEBOUNCE_TIME_MS 25
#define GND_MIC_SWAP_THRESHOLD 2
#define OCP_ATTEMPT 1
#define FW_READ_ATTEMPTS 15
#define FW_READ_TIMEOUT 4000000
#define BUTTON_POLLING_SUPPORTED true
#define MCLK_RATE_12288KHZ 12288000
#define MCLK_RATE_9600KHZ 9600000
#define DEFAULT_DCE_STA_WAIT 55
#define DEFAULT_DCE_WAIT 60000
#define DEFAULT_STA_WAIT 5000
#define VDDIO_MICBIAS_MV 1800
#define WCD9XXX_MICBIAS_PULLDOWN_SETTLE_US 5000
#define WCD9XXX_HPHL_STATUS_READY_WAIT_US 1000
#define WCD9XXX_MUX_SWITCH_READY_WAIT_MS 50
#define WCD9XXX_MEAS_DELTA_MAX_MV 120
#define WCD9XXX_MEAS_INVALD_RANGE_LOW_MV 20
#define WCD9XXX_MEAS_INVALD_RANGE_HIGH_MV 80
/* Threshold in milliohm used for mono/stereo
* plug classification
*/
#define WCD9XXX_MONO_HS_DIFF_THR 20000000
#define WCD9XXX_MONO_HS_MIN_THR 2000
/*
* Invalid voltage range for the detection
* of plug type with current source
*/
#define WCD9XXX_CS_MEAS_INVALD_RANGE_LOW_MV 160
#define WCD9XXX_CS_MEAS_INVALD_RANGE_HIGH_MV 265
/*
* Threshold used to detect euro headset
* with current source
*/
#define WCD9XXX_CS_GM_SWAP_THRES_MIN_MV 10
#define WCD9XXX_CS_GM_SWAP_THRES_MAX_MV 40
#define WCD9XXX_MBHC_NSC_CS 9
#define WCD9XXX_GM_SWAP_THRES_MIN_MV 150
#define WCD9XXX_GM_SWAP_THRES_MAX_MV 650
#define WCD9XXX_THRESHOLD_MIC_THRESHOLD 200
#define WCD9XXX_USLEEP_RANGE_MARGIN_US 100
/* RX_HPH_CNP_WG_TIME increases by 0.24ms */
#define WCD9XXX_WG_TIME_FACTOR_US 240
#ifdef VENDOR_EDIT
// Modified begin by MingLiu@MultiMedia.AudioDrv for headset detect on 2014-10-17
#define WCD9XXX_V_CS_HS_MAX 500
#else /* VENDOR_EDIT */
#define WCD9XXX_V_CS_HS_MAX 1000
// Modified end by MingLiu@MultiMedia.AudioDrv for headset detect on 2014-10-17
#endif /* VENDOR_EDIT */
#ifdef VENDOR_EDIT
/*wangdongdong@MultiMedia.AudioDrv,2015/06/04,add for headset detect*/
/*kang change from 20 to 15 for supporting lenove U.S./CTIA headset*/
#define WCD9XXX_V_CS_NO_MIC 15
#else
#define WCD9XXX_V_CS_NO_MIC 5
#endif
#define WCD9XXX_MB_MEAS_DELTA_MAX_MV 80
#define WCD9XXX_CS_MEAS_DELTA_MAX_MV 12
#define WCD9XXX_ZDET_ZONE_1 80000
#define WCD9XXX_ZDET_ZONE_2 800000
#define WCD9XXX_IS_IN_ZDET_ZONE_1(x) (x < WCD9XXX_ZDET_ZONE_1 ? 1 : 0)
#define WCD9XXX_IS_IN_ZDET_ZONE_2(x) ((x > WCD9XXX_ZDET_ZONE_1 && \
x < WCD9XXX_ZDET_ZONE_2) ? 1 : 0)
#define WCD9XXX_IS_IN_ZDET_ZONE_3(x) (x > WCD9XXX_ZDET_ZONE_2 ? 1 : 0)
#define WCD9XXX_BOX_CAR_AVRG_MIN 1
#define WCD9XXX_BOX_CAR_AVRG_MAX 10
static int impedance_detect_en;
module_param(impedance_detect_en, int,
S_IRUGO | S_IWUSR | S_IWGRP);
MODULE_PARM_DESC(impedance_detect_en, "enable/disable impedance detect");
static unsigned int z_det_box_car_avg = 1;
module_param(z_det_box_car_avg, int,
S_IRUGO | S_IWUSR | S_IWGRP);
MODULE_PARM_DESC(z_det_box_car_avg,
"Number of samples for impedance detection");
static bool detect_use_vddio_switch;
struct wcd9xxx_mbhc_detect {
u16 dce;
u16 sta;
u16 hphl_status;
bool swap_gnd;
bool vddio;
bool hwvalue;
bool mic_bias;
/* internal purpose from here */
bool _above_no_mic;
bool _below_v_hs_max;
s16 _vdces;
enum wcd9xxx_mbhc_plug_type _type;
};
enum meas_type {
STA = 0,
DCE,
};
enum {
MBHC_USE_HPHL_TRIGGER = 1,
MBHC_USE_MB_TRIGGER = 2
};
/*
* Flags to track of PA and DAC state.
* PA and DAC should be tracked separately as AUXPGA loopback requires
* only PA to be turned on without DAC being on.
*/
enum pa_dac_ack_flags {
WCD9XXX_HPHL_PA_OFF_ACK = 0,
WCD9XXX_HPHR_PA_OFF_ACK,
WCD9XXX_HPHL_DAC_OFF_ACK,
WCD9XXX_HPHR_DAC_OFF_ACK
};
enum wcd9xxx_current_v_idx {
WCD9XXX_CURRENT_V_INS_H,
WCD9XXX_CURRENT_V_INS_HU,
WCD9XXX_CURRENT_V_B1_H,
WCD9XXX_CURRENT_V_B1_HU,
WCD9XXX_CURRENT_V_BR_H,
};
static int wcd9xxx_detect_impedance(struct wcd9xxx_mbhc *mbhc, uint32_t *zl,
uint32_t *zr);
static s16 wcd9xxx_get_current_v(struct wcd9xxx_mbhc *mbhc,
const enum wcd9xxx_current_v_idx idx);
static void wcd9xxx_get_z(struct wcd9xxx_mbhc *mbhc, s16 *dce_z, s16 *sta_z,
struct mbhc_micbias_regs *micb_regs,
bool norel);
static void wcd9xxx_mbhc_calc_thres(struct wcd9xxx_mbhc *mbhc);
static u16 wcd9xxx_codec_v_sta_dce(struct wcd9xxx_mbhc *mbhc,
enum meas_type dce, s16 vin_mv,
bool cs_enable);
static bool wcd9xxx_mbhc_polling(struct wcd9xxx_mbhc *mbhc)
{
return snd_soc_read(mbhc->codec, WCD9XXX_A_CDC_MBHC_EN_CTL) & 0x1;
}
static void wcd9xxx_turn_onoff_override(struct wcd9xxx_mbhc *mbhc, bool on)
{
struct snd_soc_codec *codec = mbhc->codec;
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL,
0x04, on ? 0x04 : 0x00);
}
/* called under codec_resource_lock acquisition */
static void wcd9xxx_pause_hs_polling(struct wcd9xxx_mbhc *mbhc)
{
struct snd_soc_codec *codec = mbhc->codec;
pr_debug("%s: enter\n", __func__);
if (!mbhc->polling_active) {
pr_debug("polling not active, nothing to pause\n");
return;
}
/* Soft reset MBHC block */
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x8, 0x8);
pr_debug("%s: leave\n", __func__);
}
/* called under codec_resource_lock acquisition */
static void wcd9xxx_start_hs_polling(struct wcd9xxx_mbhc *mbhc)
{
struct snd_soc_codec *codec = mbhc->codec;
int mbhc_state = mbhc->mbhc_state;
pr_debug("%s: enter\n", __func__);
if (!mbhc->polling_active) {
pr_debug("Polling is not active, do not start polling\n");
return;
}
/*
* setup internal micbias if codec uses internal micbias for
* headset detection
*/
if (mbhc->mbhc_cfg->use_int_rbias) {
if (mbhc->mbhc_cb && mbhc->mbhc_cb->setup_int_rbias)
mbhc->mbhc_cb->setup_int_rbias(codec, true);
else
pr_err("%s: internal bias requested but codec did not provide callback\n",
__func__);
}
snd_soc_write(codec, WCD9XXX_A_MBHC_SCALING_MUX_1, 0x04);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->enable_mux_bias_block)
mbhc->mbhc_cb->enable_mux_bias_block(codec);
else
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1,
0x80, 0x80);
if (!mbhc->no_mic_headset_override &&
mbhc_state == MBHC_STATE_POTENTIAL) {
pr_debug("%s recovering MBHC state machine\n", __func__);
mbhc->mbhc_state = MBHC_STATE_POTENTIAL_RECOVERY;
/* set to max button press threshold */
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B2_CTL, 0x7F);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B1_CTL, 0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B4_CTL, 0x7F);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B3_CTL, 0xFF);
/* set to max */
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B6_CTL, 0x7F);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B5_CTL, 0xFF);
}
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x1);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x8, 0x0);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x1);
pr_debug("%s: leave\n", __func__);
}
static int __wcd9xxx_resmgr_get_k_val(struct wcd9xxx_mbhc *mbhc,
unsigned int cfilt_mv)
{
return wcd9xxx_resmgr_get_k_val(mbhc->resmgr, cfilt_mv);
}
/*
* called under codec_resource_lock acquisition
* return old status
*/
static bool __wcd9xxx_switch_micbias(struct wcd9xxx_mbhc *mbhc,
int vddio_switch, bool restartpolling,
bool checkpolling)
{
bool ret;
int cfilt_k_val;
bool override;
struct snd_soc_codec *codec;
struct mbhc_internal_cal_data *d = &mbhc->mbhc_data;
codec = mbhc->codec;
if (mbhc->micbias_enable) {
pr_debug("%s: micbias is already on\n", __func__);
ret = mbhc->mbhc_micbias_switched;
return ret;
}
ret = mbhc->mbhc_micbias_switched;
if (vddio_switch && !mbhc->mbhc_micbias_switched &&
(!checkpolling || mbhc->polling_active)) {
if (restartpolling)
wcd9xxx_pause_hs_polling(mbhc);
override = snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_B1_CTL) &
0x04;
if (!override)
wcd9xxx_turn_onoff_override(mbhc, true);
/* Adjust threshold if Mic Bias voltage changes */
if (d->micb_mv != VDDIO_MICBIAS_MV) {
cfilt_k_val = __wcd9xxx_resmgr_get_k_val(mbhc,
VDDIO_MICBIAS_MV);
usleep_range(10000, 10100);
snd_soc_update_bits(codec,
mbhc->mbhc_bias_regs.cfilt_val,
0xFC, (cfilt_k_val << 2));
usleep_range(10000, 10100);
/* Threshods for insertion/removal */
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B1_CTL,
d->v_ins_hu[MBHC_V_IDX_VDDIO] & 0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B2_CTL,
(d->v_ins_hu[MBHC_V_IDX_VDDIO] >> 8) &
0xFF);
if (mbhc->mbhc_state != MBHC_STATE_POTENTIAL_RECOVERY) {
/* Threshods for button press */
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B3_CTL,
d->v_b1_hu[MBHC_V_IDX_VDDIO] & 0xFF);
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B4_CTL,
(d->v_b1_hu[MBHC_V_IDX_VDDIO] >> 8) &
0xFF);
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B5_CTL,
d->v_b1_h[MBHC_V_IDX_VDDIO] & 0xFF);
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B6_CTL,
(d->v_b1_h[MBHC_V_IDX_VDDIO] >> 8) &
0xFF);
/* Threshods for button release */
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B9_CTL,
d->v_brh[MBHC_V_IDX_VDDIO] & 0xFF);
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B10_CTL,
(d->v_brh[MBHC_V_IDX_VDDIO] >> 8) &
0xFF);
}
pr_debug("%s: Programmed MBHC thresholds to VDDIO\n",
__func__);
}
/* Enable MIC BIAS Switch to VDDIO */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.mbhc_reg,
0x80, 0x80);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.mbhc_reg,
0x10, 0x00);
if (!override)
wcd9xxx_turn_onoff_override(mbhc, false);
if (restartpolling)
wcd9xxx_start_hs_polling(mbhc);
mbhc->mbhc_micbias_switched = true;
pr_debug("%s: VDDIO switch enabled\n", __func__);
} else if (!vddio_switch && mbhc->mbhc_micbias_switched) {
if ((!checkpolling || mbhc->polling_active) &&
restartpolling)
wcd9xxx_pause_hs_polling(mbhc);
/* Reprogram thresholds */
if (d->micb_mv != VDDIO_MICBIAS_MV) {
cfilt_k_val =
__wcd9xxx_resmgr_get_k_val(mbhc,
d->micb_mv);
snd_soc_update_bits(codec,
mbhc->mbhc_bias_regs.cfilt_val,
0xFC, (cfilt_k_val << 2));
usleep_range(10000, 10100);
/* Revert threshods for insertion/removal */
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B1_CTL,
d->v_ins_hu[MBHC_V_IDX_CFILT] & 0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B2_CTL,
(d->v_ins_hu[MBHC_V_IDX_CFILT] >> 8) &
0xFF);
if (mbhc->mbhc_state != MBHC_STATE_POTENTIAL_RECOVERY) {
/* Revert threshods for button press */
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B3_CTL,
d->v_b1_hu[MBHC_V_IDX_CFILT] & 0xFF);
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B4_CTL,
(d->v_b1_hu[MBHC_V_IDX_CFILT] >> 8) &
0xFF);
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B5_CTL,
d->v_b1_h[MBHC_V_IDX_CFILT] & 0xFF);
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B6_CTL,
(d->v_b1_h[MBHC_V_IDX_CFILT] >> 8) &
0xFF);
/* Revert threshods for button release */
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B9_CTL,
d->v_brh[MBHC_V_IDX_CFILT] & 0xFF);
snd_soc_write(codec,
WCD9XXX_A_CDC_MBHC_VOLT_B10_CTL,
(d->v_brh[MBHC_V_IDX_CFILT] >> 8) &
0xFF);
}
pr_debug("%s: Programmed MBHC thresholds to MICBIAS\n",
__func__);
}
/* Disable MIC BIAS Switch to VDDIO */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.mbhc_reg, 0x80,
0x00);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.mbhc_reg, 0x10,
0x00);
if ((!checkpolling || mbhc->polling_active) && restartpolling)
wcd9xxx_start_hs_polling(mbhc);
mbhc->mbhc_micbias_switched = false;
pr_debug("%s: VDDIO switch disabled\n", __func__);
}
return ret;
}
static void wcd9xxx_switch_micbias(struct wcd9xxx_mbhc *mbhc, int vddio_switch)
{
__wcd9xxx_switch_micbias(mbhc, vddio_switch, true, true);
}
static s16 wcd9xxx_get_current_v(struct wcd9xxx_mbhc *mbhc,
const enum wcd9xxx_current_v_idx idx)
{
enum mbhc_v_index vidx;
s16 ret = -EINVAL;
if ((mbhc->mbhc_data.micb_mv != VDDIO_MICBIAS_MV) &&
mbhc->mbhc_micbias_switched)
vidx = MBHC_V_IDX_VDDIO;
else
vidx = MBHC_V_IDX_CFILT;
switch (idx) {
case WCD9XXX_CURRENT_V_INS_H:
ret = (s16)mbhc->mbhc_data.v_ins_h[vidx];
break;
case WCD9XXX_CURRENT_V_INS_HU:
ret = (s16)mbhc->mbhc_data.v_ins_hu[vidx];
break;
case WCD9XXX_CURRENT_V_B1_H:
ret = (s16)mbhc->mbhc_data.v_b1_h[vidx];
break;
case WCD9XXX_CURRENT_V_B1_HU:
ret = (s16)mbhc->mbhc_data.v_b1_hu[vidx];
break;
case WCD9XXX_CURRENT_V_BR_H:
ret = (s16)mbhc->mbhc_data.v_brh[vidx];
break;
}
return ret;
}
void *wcd9xxx_mbhc_cal_btn_det_mp(
const struct wcd9xxx_mbhc_btn_detect_cfg *btn_det,
const enum wcd9xxx_mbhc_btn_det_mem mem)
{
void *ret = (void *)&btn_det->_v_btn_low;
switch (mem) {
case MBHC_BTN_DET_GAIN:
ret += sizeof(btn_det->_n_cic);
case MBHC_BTN_DET_N_CIC:
ret += sizeof(btn_det->_n_ready);
case MBHC_BTN_DET_N_READY:
ret += sizeof(btn_det->_v_btn_high[0]) * btn_det->num_btn;
case MBHC_BTN_DET_V_BTN_HIGH:
ret += sizeof(btn_det->_v_btn_low[0]) * btn_det->num_btn;
case MBHC_BTN_DET_V_BTN_LOW:
/* do nothing */
break;
default:
ret = NULL;
}
return ret;
}
EXPORT_SYMBOL(wcd9xxx_mbhc_cal_btn_det_mp);
static void wcd9xxx_calibrate_hs_polling(struct wcd9xxx_mbhc *mbhc)
{
struct snd_soc_codec *codec = mbhc->codec;
const s16 v_ins_hu = wcd9xxx_get_current_v(mbhc,
WCD9XXX_CURRENT_V_INS_HU);
const s16 v_b1_hu = wcd9xxx_get_current_v(mbhc,
WCD9XXX_CURRENT_V_B1_HU);
const s16 v_b1_h = wcd9xxx_get_current_v(mbhc, WCD9XXX_CURRENT_V_B1_H);
const s16 v_brh = wcd9xxx_get_current_v(mbhc, WCD9XXX_CURRENT_V_BR_H);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B1_CTL, v_ins_hu & 0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B2_CTL,
(v_ins_hu >> 8) & 0xFF);
if (mbhc->mbhc_state != MBHC_STATE_POTENTIAL_RECOVERY) {
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B3_CTL, v_b1_hu &
0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B4_CTL,
(v_b1_hu >> 8) & 0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B5_CTL, v_b1_h &
0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B6_CTL,
(v_b1_h >> 8) & 0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B9_CTL, v_brh &
0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B10_CTL,
(v_brh >> 8) & 0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B11_CTL,
mbhc->mbhc_data.v_brl & 0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B12_CTL,
(mbhc->mbhc_data.v_brl >> 8) & 0xFF);
}
}
static void wcd9xxx_codec_switch_cfilt_mode(struct wcd9xxx_mbhc *mbhc,
bool fast)
{
struct snd_soc_codec *codec = mbhc->codec;
struct wcd9xxx_cfilt_mode cfilt_mode;
if (mbhc->mbhc_cb && mbhc->mbhc_cb->switch_cfilt_mode) {
cfilt_mode = mbhc->mbhc_cb->switch_cfilt_mode(mbhc, fast);
} else {
if (fast)
cfilt_mode.reg_mode_val = WCD9XXX_CFILT_FAST_MODE;
else
cfilt_mode.reg_mode_val = WCD9XXX_CFILT_SLOW_MODE;
cfilt_mode.reg_mask = 0x40;
cfilt_mode.cur_mode_val =
snd_soc_read(codec, mbhc->mbhc_bias_regs.cfilt_ctl) & 0x40;
}
if (cfilt_mode.cur_mode_val
!= cfilt_mode.reg_mode_val) {
if (mbhc->polling_active && wcd9xxx_mbhc_polling(mbhc))
wcd9xxx_pause_hs_polling(mbhc);
snd_soc_update_bits(codec,
mbhc->mbhc_bias_regs.cfilt_ctl,
cfilt_mode.reg_mask,
cfilt_mode.reg_mode_val);
if (mbhc->polling_active && wcd9xxx_mbhc_polling(mbhc))
wcd9xxx_start_hs_polling(mbhc);
pr_debug("%s: CFILT mode change (%x to %x)\n", __func__,
cfilt_mode.cur_mode_val,
cfilt_mode.reg_mode_val);
} else {
pr_debug("%s: CFILT Value is already %x\n",
__func__, cfilt_mode.cur_mode_val);
}
}
static void wcd9xxx_jack_report(struct wcd9xxx_mbhc *mbhc,
struct snd_soc_jack *jack, int status, int mask)
{
if (jack == &mbhc->headset_jack) {
wcd9xxx_resmgr_cond_update_cond(mbhc->resmgr,
WCD9XXX_COND_HPH_MIC,
status & SND_JACK_MICROPHONE);
wcd9xxx_resmgr_cond_update_cond(mbhc->resmgr,
WCD9XXX_COND_HPH,
status & SND_JACK_HEADPHONE);
}
snd_soc_jack_report_no_dapm(jack, status, mask);
}
static void __hphocp_off_report(struct wcd9xxx_mbhc *mbhc, u32 jack_status,
int irq)
{
struct snd_soc_codec *codec;
pr_debug("%s: clear ocp status %x\n", __func__, jack_status);
codec = mbhc->codec;
if (mbhc->hph_status & jack_status) {
mbhc->hph_status &= ~jack_status;
wcd9xxx_jack_report(mbhc, &mbhc->headset_jack,
mbhc->hph_status, WCD9XXX_JACK_MASK);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_OCP_CTL, 0x10,
0x00);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_OCP_CTL, 0x10,
0x10);
/*
* reset retry counter as PA is turned off signifying
* start of new OCP detection session
*/
if (mbhc->intr_ids->hph_left_ocp)
mbhc->hphlocp_cnt = 0;
else
mbhc->hphrocp_cnt = 0;
wcd9xxx_enable_irq(mbhc->resmgr->core_res, irq);
}
}
static void hphrocp_off_report(struct wcd9xxx_mbhc *mbhc, u32 jack_status)
{
__hphocp_off_report(mbhc, SND_JACK_OC_HPHR,
mbhc->intr_ids->hph_right_ocp);
}
static void hphlocp_off_report(struct wcd9xxx_mbhc *mbhc, u32 jack_status)
{
__hphocp_off_report(mbhc, SND_JACK_OC_HPHL,
mbhc->intr_ids->hph_left_ocp);
}
static void wcd9xxx_get_mbhc_micbias_regs(struct wcd9xxx_mbhc *mbhc,
enum wcd9xxx_mbhc_micbias_type mb_type)
{
unsigned int cfilt;
struct wcd9xxx_micbias_setting *micbias_pdata =
mbhc->resmgr->micbias_pdata;
struct mbhc_micbias_regs *micbias_regs;
enum wcd9xxx_micbias_num mb_num;
if (mb_type == MBHC_ANC_MIC_MB) {
micbias_regs = &mbhc->mbhc_anc_bias_regs;
mb_num = mbhc->mbhc_cfg->anc_micbias;
} else {
micbias_regs = &mbhc->mbhc_bias_regs;
mb_num = mbhc->mbhc_cfg->micbias;
}
switch (mb_num) {
case MBHC_MICBIAS1:
cfilt = micbias_pdata->bias1_cfilt_sel;
micbias_regs->mbhc_reg = WCD9XXX_A_MICB_1_MBHC;
micbias_regs->int_rbias = WCD9XXX_A_MICB_1_INT_RBIAS;
micbias_regs->ctl_reg = WCD9XXX_A_MICB_1_CTL;
break;
case MBHC_MICBIAS2:
cfilt = micbias_pdata->bias2_cfilt_sel;
micbias_regs->mbhc_reg = WCD9XXX_A_MICB_2_MBHC;
micbias_regs->int_rbias = WCD9XXX_A_MICB_2_INT_RBIAS;
micbias_regs->ctl_reg = WCD9XXX_A_MICB_2_CTL;
break;
case MBHC_MICBIAS3:
cfilt = micbias_pdata->bias3_cfilt_sel;
micbias_regs->mbhc_reg = WCD9XXX_A_MICB_3_MBHC;
micbias_regs->int_rbias = WCD9XXX_A_MICB_3_INT_RBIAS;
micbias_regs->ctl_reg = WCD9XXX_A_MICB_3_CTL;
break;
case MBHC_MICBIAS4:
cfilt = micbias_pdata->bias4_cfilt_sel;
micbias_regs->mbhc_reg = mbhc->resmgr->reg_addr->micb_4_mbhc;
micbias_regs->int_rbias =
mbhc->resmgr->reg_addr->micb_4_int_rbias;
micbias_regs->ctl_reg = mbhc->resmgr->reg_addr->micb_4_ctl;
break;
default:
/* Should never reach here */
pr_err("%s: Invalid MIC BIAS for MBHC\n", __func__);
return;
}
micbias_regs->cfilt_sel = cfilt;
switch (cfilt) {
case WCD9XXX_CFILT1_SEL:
micbias_regs->cfilt_val = WCD9XXX_A_MICB_CFILT_1_VAL;
micbias_regs->cfilt_ctl = WCD9XXX_A_MICB_CFILT_1_CTL;
break;
case WCD9XXX_CFILT2_SEL:
micbias_regs->cfilt_val = WCD9XXX_A_MICB_CFILT_2_VAL;
micbias_regs->cfilt_ctl = WCD9XXX_A_MICB_CFILT_2_CTL;
break;
case WCD9XXX_CFILT3_SEL:
micbias_regs->cfilt_val = WCD9XXX_A_MICB_CFILT_3_VAL;
micbias_regs->cfilt_ctl = WCD9XXX_A_MICB_CFILT_3_CTL;
break;
}
if (mb_type == MBHC_PRIMARY_MIC_MB) {
switch (cfilt) {
case WCD9XXX_CFILT1_SEL:
mbhc->mbhc_data.micb_mv = micbias_pdata->cfilt1_mv;
break;
case WCD9XXX_CFILT2_SEL:
mbhc->mbhc_data.micb_mv = micbias_pdata->cfilt2_mv;
break;
case WCD9XXX_CFILT3_SEL:
mbhc->mbhc_data.micb_mv = micbias_pdata->cfilt3_mv;
break;
}
}
}
static void wcd9xxx_clr_and_turnon_hph_padac(struct wcd9xxx_mbhc *mbhc)
{
bool pa_turned_on = false;
struct snd_soc_codec *codec = mbhc->codec;
u8 wg_time;
wg_time = snd_soc_read(codec, WCD9XXX_A_RX_HPH_CNP_WG_TIME);
wg_time += 1;
if (test_and_clear_bit(WCD9XXX_HPHR_DAC_OFF_ACK,
&mbhc->hph_pa_dac_state)) {
pr_debug("%s: HPHR clear flag and enable DAC\n", __func__);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_R_DAC_CTL,
0xC0, 0xC0);
}
if (test_and_clear_bit(WCD9XXX_HPHL_DAC_OFF_ACK,
&mbhc->hph_pa_dac_state)) {
pr_debug("%s: HPHL clear flag and enable DAC\n", __func__);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_L_DAC_CTL,
0x80, 0x80);
}
if (test_and_clear_bit(WCD9XXX_HPHR_PA_OFF_ACK,
&mbhc->hph_pa_dac_state)) {
pr_debug("%s: HPHR clear flag and enable PA\n", __func__);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_CNP_EN, 0x10,
1 << 4);
pa_turned_on = true;
}
if (test_and_clear_bit(WCD9XXX_HPHL_PA_OFF_ACK,
&mbhc->hph_pa_dac_state)) {
pr_debug("%s: HPHL clear flag and enable PA\n", __func__);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_CNP_EN, 0x20, 1
<< 5);
pa_turned_on = true;
}
if (pa_turned_on) {
pr_debug("%s: PA was turned on by MBHC and not by DAPM\n",
__func__);
usleep_range(wg_time * 1000, wg_time * 1000 + 50);
}
}
static int wcd9xxx_cancel_btn_work(struct wcd9xxx_mbhc *mbhc)
{
int r;
r = cancel_delayed_work_sync(&mbhc->mbhc_btn_dwork);
if (r)
/* if scheduled mbhc.mbhc_btn_dwork is canceled from here,
* we have to unlock from here instead btn_work */
wcd9xxx_unlock_sleep(mbhc->resmgr->core_res);
return r;
}
static bool wcd9xxx_is_hph_dac_on(struct snd_soc_codec *codec, int left)
{
u8 hph_reg_val = 0;
if (left)
hph_reg_val = snd_soc_read(codec, WCD9XXX_A_RX_HPH_L_DAC_CTL);
else
hph_reg_val = snd_soc_read(codec, WCD9XXX_A_RX_HPH_R_DAC_CTL);
return (hph_reg_val & 0xC0) ? true : false;
}
static bool wcd9xxx_is_hph_pa_on(struct snd_soc_codec *codec)
{
u8 hph_reg_val = 0;
hph_reg_val = snd_soc_read(codec, WCD9XXX_A_RX_HPH_CNP_EN);
return (hph_reg_val & 0x30) ? true : false;
}
/* called under codec_resource_lock acquisition */
static void wcd9xxx_set_and_turnoff_hph_padac(struct wcd9xxx_mbhc *mbhc)
{
u8 wg_time;
struct snd_soc_codec *codec = mbhc->codec;
wg_time = snd_soc_read(codec, WCD9XXX_A_RX_HPH_CNP_WG_TIME);
wg_time += 1;
/* If headphone PA is on, check if userspace receives
* removal event to sync-up PA's state */
if (wcd9xxx_is_hph_pa_on(codec)) {
pr_debug("%s PA is on, setting PA_OFF_ACK\n", __func__);
set_bit(WCD9XXX_HPHL_PA_OFF_ACK, &mbhc->hph_pa_dac_state);
set_bit(WCD9XXX_HPHR_PA_OFF_ACK, &mbhc->hph_pa_dac_state);
} else {
pr_debug("%s PA is off\n", __func__);
}
if (wcd9xxx_is_hph_dac_on(codec, 1))
set_bit(WCD9XXX_HPHL_DAC_OFF_ACK, &mbhc->hph_pa_dac_state);
if (wcd9xxx_is_hph_dac_on(codec, 0))
set_bit(WCD9XXX_HPHR_DAC_OFF_ACK, &mbhc->hph_pa_dac_state);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_CNP_EN, 0x30, 0x00);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_L_DAC_CTL, 0x80, 0x00);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_R_DAC_CTL, 0xC0, 0x00);
usleep_range(wg_time * 1000, wg_time * 1000 + 50);
}
static void wcd9xxx_insert_detect_setup(struct wcd9xxx_mbhc *mbhc, bool ins)
{
if (!mbhc->mbhc_cfg->insert_detect)
return;
pr_debug("%s: Setting up %s detection\n", __func__,
ins ? "insert" : "removal");
/* Disable detection to avoid glitch */
snd_soc_update_bits(mbhc->codec, WCD9XXX_A_MBHC_INSERT_DETECT, 1, 0);
if (mbhc->mbhc_cfg->gpio_level_insert)
snd_soc_write(mbhc->codec, WCD9XXX_A_MBHC_INSERT_DETECT,
(0x68 | (ins ? (1 << 1) : 0)));
else
snd_soc_write(mbhc->codec, WCD9XXX_A_MBHC_INSERT_DETECT,
(0x6C | (ins ? (1 << 1) : 0)));
/* Re-enable detection */
snd_soc_update_bits(mbhc->codec, WCD9XXX_A_MBHC_INSERT_DETECT, 1, 1);
}
/* called under codec_resource_lock acquisition */
static void wcd9xxx_report_plug(struct wcd9xxx_mbhc *mbhc, int insertion,
enum snd_jack_types jack_type)
{
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
pr_debug("%s: enter insertion %d hph_status %x\n",
__func__, insertion, mbhc->hph_status);
if (!insertion) {
/* Report removal */
mbhc->hph_status &= ~jack_type;
/*
* cancel possibly scheduled btn work and
* report release if we reported button press
*/
if (wcd9xxx_cancel_btn_work(mbhc))
pr_debug("%s: button press is canceled\n", __func__);
else if (mbhc->buttons_pressed) {
pr_debug("%s: release of button press%d\n",
__func__, jack_type);
wcd9xxx_jack_report(mbhc, &mbhc->button_jack, 0,
mbhc->buttons_pressed);
mbhc->buttons_pressed &=
~WCD9XXX_JACK_BUTTON_MASK;
}
if (mbhc->micbias_enable && mbhc->micbias_enable_cb) {
pr_debug("%s: Disabling micbias\n", __func__);
mbhc->micbias_enable = false;
mbhc->micbias_enable_cb(mbhc->codec, false,
mbhc->mbhc_cfg->micbias);
}
mbhc->zl = mbhc->zr = 0;
mbhc->hph_type = MBHC_HPH_NONE;
pr_debug("%s: Reporting removal %d(%x)\n", __func__,
jack_type, mbhc->hph_status);
#ifdef VENDOR_EDIT
/*wangdongdong@MultiMedia.AudioDrv, 2015-03-24, Modify for headset uevent*/
switch_set_state(&mbhc->wcd9xxx_sdev,0);
#endif
wcd9xxx_jack_report(mbhc, &mbhc->headset_jack, mbhc->hph_status,
WCD9XXX_JACK_MASK);
wcd9xxx_set_and_turnoff_hph_padac(mbhc);
hphrocp_off_report(mbhc, SND_JACK_OC_HPHR);
hphlocp_off_report(mbhc, SND_JACK_OC_HPHL);
mbhc->current_plug = PLUG_TYPE_NONE;
mbhc->polling_active = false;
if (mbhc->mbhc_cb && mbhc->mbhc_cb->hph_auto_pulldown_ctrl)
mbhc->mbhc_cb->hph_auto_pulldown_ctrl(mbhc->codec,
false);
} else {
/*
* Report removal of current jack type.
* Headphone to headset shouldn't report headphone
* removal.
*/
if (mbhc->mbhc_cfg->detect_extn_cable &&
!(mbhc->current_plug == PLUG_TYPE_HEADPHONE &&
jack_type == SND_JACK_HEADSET) &&
(mbhc->hph_status && mbhc->hph_status != jack_type)) {
if (mbhc->micbias_enable && mbhc->micbias_enable_cb &&
mbhc->hph_status == SND_JACK_HEADSET) {
pr_debug("%s: Disabling micbias\n", __func__);
mbhc->micbias_enable = false;
mbhc->micbias_enable_cb(mbhc->codec, false,
mbhc->mbhc_cfg->micbias);
}
pr_debug("%s: Reporting removal (%x)\n",
__func__, mbhc->hph_status);
mbhc->zl = mbhc->zr = 0;
wcd9xxx_jack_report(mbhc, &mbhc->headset_jack,
0, WCD9XXX_JACK_MASK);
mbhc->hph_status &= ~(SND_JACK_HEADSET |
SND_JACK_LINEOUT |
SND_JACK_ANC_HEADPHONE |
SND_JACK_UNSUPPORTED);
if (mbhc->mbhc_cb &&
mbhc->mbhc_cb->hph_auto_pulldown_ctrl)
mbhc->mbhc_cb->hph_auto_pulldown_ctrl(
mbhc->codec,
false);
}
/* Report insertion */
mbhc->hph_status |= jack_type;
if (jack_type == SND_JACK_HEADPHONE) {
mbhc->current_plug = PLUG_TYPE_HEADPHONE;
} else if (jack_type == SND_JACK_UNSUPPORTED) {
mbhc->current_plug = PLUG_TYPE_GND_MIC_SWAP;
} else if (jack_type == SND_JACK_HEADSET) {
mbhc->polling_active = BUTTON_POLLING_SUPPORTED;
mbhc->current_plug = PLUG_TYPE_HEADSET;
mbhc->update_z = true;
} else if (jack_type == SND_JACK_LINEOUT) {
mbhc->current_plug = PLUG_TYPE_HIGH_HPH;
} else if (jack_type == SND_JACK_ANC_HEADPHONE) {
mbhc->polling_active = BUTTON_POLLING_SUPPORTED;
mbhc->current_plug = PLUG_TYPE_ANC_HEADPHONE;
}
if (mbhc->micbias_enable && mbhc->micbias_enable_cb) {
pr_debug("%s: Enabling micbias\n", __func__);
mbhc->micbias_enable_cb(mbhc->codec, true,
mbhc->mbhc_cfg->micbias);
}
if (mbhc->impedance_detect && impedance_detect_en)
wcd9xxx_detect_impedance(mbhc, &mbhc->zl, &mbhc->zr);
pr_debug("%s: Reporting insertion %d(%x)\n", __func__,
jack_type, mbhc->hph_status);
#ifdef VENDOR_EDIT
/*wangdongdong@MultiMedia.AudioDrv, 2015-03-24, Modify for headset uevent*/
switch(mbhc->current_plug){
case PLUG_TYPE_HEADPHONE:
case PLUG_TYPE_HIGH_HPH:
mbhc->mbhc_cfg->headset_type = 0;
switch_set_state(&mbhc->wcd9xxx_sdev,2);
break;
case PLUG_TYPE_GND_MIC_SWAP:
mbhc->mbhc_cfg->headset_type = 0;
switch_set_state(&mbhc->wcd9xxx_sdev,1);
break;
case PLUG_TYPE_HEADSET:
mbhc->mbhc_cfg->headset_type = 1;
switch_set_state(&mbhc->wcd9xxx_sdev,1);
break;
default:
mbhc->mbhc_cfg->headset_type = 0;
switch_set_state(&mbhc->wcd9xxx_sdev,0);
break;
}
printk("%s: Reporting insertion %d(%x)\n", __func__,
jack_type, mbhc->hph_status);
#endif
wcd9xxx_jack_report(mbhc, &mbhc->headset_jack,
mbhc->hph_status, WCD9XXX_JACK_MASK);
/*
* if PA is already on, switch micbias
* source to VDDIO
*/
if (((mbhc->current_plug == PLUG_TYPE_HEADSET) ||
(mbhc->current_plug == PLUG_TYPE_ANC_HEADPHONE)) &&
((mbhc->event_state & (1 << MBHC_EVENT_PA_HPHL |
1 << MBHC_EVENT_PA_HPHR |
1 << MBHC_EVENT_PRE_TX_1_3_ON))))
__wcd9xxx_switch_micbias(mbhc, 1, false,
false);
wcd9xxx_clr_and_turnon_hph_padac(mbhc);
}
/* Setup insert detect */
wcd9xxx_insert_detect_setup(mbhc, !insertion);
pr_debug("%s: leave hph_status %x\n", __func__, mbhc->hph_status);
}
/* should be called under interrupt context that hold suspend */
static void wcd9xxx_schedule_hs_detect_plug(struct wcd9xxx_mbhc *mbhc,
struct work_struct *work)
{
pr_debug("%s: scheduling wcd9xxx_correct_swch_plug\n", __func__);
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
mbhc->hs_detect_work_stop = false;
wcd9xxx_lock_sleep(mbhc->resmgr->core_res);
schedule_work(work);
}
/* called under codec_resource_lock acquisition */
static void wcd9xxx_cancel_hs_detect_plug(struct wcd9xxx_mbhc *mbhc,
struct work_struct *work)
{
pr_debug("%s: Canceling correct_plug_swch\n", __func__);
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
mbhc->hs_detect_work_stop = true;
wmb();
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
if (cancel_work_sync(work)) {
pr_debug("%s: correct_plug_swch is canceled\n",
__func__);
wcd9xxx_unlock_sleep(mbhc->resmgr->core_res);
}
WCD9XXX_BCL_LOCK(mbhc->resmgr);
}
static s16 scale_v_micb_vddio(struct wcd9xxx_mbhc *mbhc, int v, bool tovddio)
{
int r;
int vddio_k, mb_k;
vddio_k = __wcd9xxx_resmgr_get_k_val(mbhc, VDDIO_MICBIAS_MV);
mb_k = __wcd9xxx_resmgr_get_k_val(mbhc, mbhc->mbhc_data.micb_mv);
if (tovddio)
r = v * (vddio_k + 4) / (mb_k + 4);
else
r = v * (mb_k + 4) / (vddio_k + 4);
return r;
}
static s16 wcd9xxx_get_current_v_hs_max(struct wcd9xxx_mbhc *mbhc)
{
s16 v_hs_max;
struct wcd9xxx_mbhc_plug_type_cfg *plug_type;
plug_type = WCD9XXX_MBHC_CAL_PLUG_TYPE_PTR(mbhc->mbhc_cfg->calibration);
if ((mbhc->mbhc_data.micb_mv != VDDIO_MICBIAS_MV) &&
mbhc->mbhc_micbias_switched)
v_hs_max = scale_v_micb_vddio(mbhc, plug_type->v_hs_max, true);
else
v_hs_max = plug_type->v_hs_max;
return v_hs_max;
}
static short wcd9xxx_read_sta_result(struct snd_soc_codec *codec)
{
u8 bias_msb, bias_lsb;
short bias_value;
bias_msb = snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_B3_STATUS);
bias_lsb = snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_B2_STATUS);
bias_value = (bias_msb << 8) | bias_lsb;
return bias_value;
}
static short wcd9xxx_read_dce_result(struct snd_soc_codec *codec)
{
u8 bias_msb, bias_lsb;
short bias_value;
bias_msb = snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_B5_STATUS);
bias_lsb = snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_B4_STATUS);
bias_value = (bias_msb << 8) | bias_lsb;
return bias_value;
}
static void wcd9xxx_turn_onoff_rel_detection(struct snd_soc_codec *codec,
bool on)
{
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x02, on << 1);
}
static short __wcd9xxx_codec_sta_dce(struct wcd9xxx_mbhc *mbhc, int dce,
bool override_bypass, bool noreldetection)
{
short bias_value;
struct snd_soc_codec *codec = mbhc->codec;
wcd9xxx_disable_irq(mbhc->resmgr->core_res,
mbhc->intr_ids->dce_est_complete);
if (noreldetection)
wcd9xxx_turn_onoff_rel_detection(codec, false);
if (mbhc->mbhc_cfg->do_recalibration)
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x2,
0x0);
/* Turn on the override */
if (!override_bypass)
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x4, 0x4);
if (dce) {
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x8,
0x8);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x4);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x8,
0x0);
if (mbhc->mbhc_cfg->do_recalibration)
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL,
0x2, 0x2);
usleep_range(mbhc->mbhc_data.t_sta_dce,
mbhc->mbhc_data.t_sta_dce + 50);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x4);
usleep_range(mbhc->mbhc_data.t_dce, mbhc->mbhc_data.t_dce + 50);
bias_value = wcd9xxx_read_dce_result(codec);
} else {
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x8,
0x8);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x2);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x8,
0x0);
if (mbhc->mbhc_cfg->do_recalibration)
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL,
0x2, 0x2);
usleep_range(mbhc->mbhc_data.t_sta_dce,
mbhc->mbhc_data.t_sta_dce + 50);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x2);
usleep_range(mbhc->mbhc_data.t_sta,
mbhc->mbhc_data.t_sta + 50);
bias_value = wcd9xxx_read_sta_result(codec);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x8,
0x8);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x0);
}
/* Turn off the override after measuring mic voltage */
if (!override_bypass)
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x04,
0x00);
if (noreldetection)
wcd9xxx_turn_onoff_rel_detection(codec, true);
wcd9xxx_enable_irq(mbhc->resmgr->core_res,
mbhc->intr_ids->dce_est_complete);
return bias_value;
}
static short wcd9xxx_codec_sta_dce(struct wcd9xxx_mbhc *mbhc, int dce,
bool norel)
{
bool override_bypass;
/* Bypass override if it is already enabled */
override_bypass = (snd_soc_read(mbhc->codec,
WCD9XXX_A_CDC_MBHC_B1_CTL) &
0x04) ? true : false;
return __wcd9xxx_codec_sta_dce(mbhc, dce, override_bypass, norel);
}
static s32 __wcd9xxx_codec_sta_dce_v(struct wcd9xxx_mbhc *mbhc, s8 dce,
u16 bias_value, s16 z, u32 micb_mv)
{
s16 value, mb;
s32 mv = 0;
value = bias_value;
if (dce) {
mb = (mbhc->mbhc_data.dce_mb);
if (mb - z)
mv = (value - z) * (s32)micb_mv / (mb - z);
} else {
mb = (mbhc->mbhc_data.sta_mb);
if (mb - z)
mv = (value - z) * (s32)micb_mv / (mb - z);
}
return mv;
}
static s32 wcd9xxx_codec_sta_dce_v(struct wcd9xxx_mbhc *mbhc, s8 dce,
u16 bias_value)
{
s16 z;
z = dce ? (s16)mbhc->mbhc_data.dce_z : (s16)mbhc->mbhc_data.sta_z;
return __wcd9xxx_codec_sta_dce_v(mbhc, dce, bias_value, z,
mbhc->mbhc_data.micb_mv);
}
/* To enable/disable bandgap and RC oscillator */
static void wcd9xxx_mbhc_ctrl_clk_bandgap(struct wcd9xxx_mbhc *mbhc,
bool enable)
{
if (enable) {
WCD9XXX_BG_CLK_LOCK(mbhc->resmgr);
wcd9xxx_resmgr_get_bandgap(mbhc->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->codec_rco_ctrl) {
WCD9XXX_BG_CLK_UNLOCK(mbhc->resmgr);
mbhc->mbhc_cb->codec_rco_ctrl(mbhc->codec, true);
} else {
wcd9xxx_resmgr_get_clk_block(mbhc->resmgr,
WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(mbhc->resmgr);
}
} else {
if (mbhc->mbhc_cb && mbhc->mbhc_cb->codec_rco_ctrl) {
mbhc->mbhc_cb->codec_rco_ctrl(mbhc->codec, false);
WCD9XXX_BG_CLK_LOCK(mbhc->resmgr);
} else {
WCD9XXX_BG_CLK_LOCK(mbhc->resmgr);
wcd9xxx_resmgr_put_clk_block(mbhc->resmgr,
WCD9XXX_CLK_RCO);
}
wcd9xxx_resmgr_put_bandgap(mbhc->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(mbhc->resmgr);
}
}
/* called only from interrupt which is under codec_resource_lock acquisition */
static short wcd9xxx_mbhc_setup_hs_polling(struct wcd9xxx_mbhc *mbhc,
struct mbhc_micbias_regs *mbhc_micb_regs,
bool is_cs_enable)
{
struct snd_soc_codec *codec = mbhc->codec;
short bias_value;
u8 cfilt_mode;
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
pr_debug("%s: enter\n", __func__);
if (!mbhc->mbhc_cfg->calibration) {
pr_err("%s: Error, no calibration exists\n", __func__);
return -ENODEV;
}
/* Enable external voltage source to micbias if present */
if (mbhc->mbhc_cb && mbhc->mbhc_cb->enable_mb_source)
mbhc->mbhc_cb->enable_mb_source(codec, true, true);
/*
* setup internal micbias if codec uses internal micbias for
* headset detection
*/
if (mbhc->mbhc_cfg->use_int_rbias) {
if (mbhc->mbhc_cb && mbhc->mbhc_cb->setup_int_rbias)
mbhc->mbhc_cb->setup_int_rbias(codec, true);
else
pr_err("%s: internal bias requested but codec did not provide callback\n",
__func__);
}
snd_soc_update_bits(codec, WCD9XXX_A_CLK_BUFF_EN1, 0x05, 0x01);
/* Make sure CFILT is in fast mode, save current mode */
cfilt_mode = snd_soc_read(codec, mbhc_micb_regs->cfilt_ctl);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->cfilt_fast_mode)
mbhc->mbhc_cb->cfilt_fast_mode(codec, mbhc);
else
snd_soc_update_bits(codec, mbhc_micb_regs->cfilt_ctl,
0x70, 0x00);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x2, 0x2);
snd_soc_write(codec, WCD9XXX_A_MBHC_SCALING_MUX_1,
mbhc->scaling_mux_in);
pr_debug("%s: scaling_mux_input: %d\n", __func__,
mbhc->scaling_mux_in);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->enable_mux_bias_block)
mbhc->mbhc_cb->enable_mux_bias_block(codec);
else
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1,
0x80, 0x80);
snd_soc_update_bits(codec, WCD9XXX_A_TX_7_MBHC_EN, 0x80, 0x80);
snd_soc_update_bits(codec, WCD9XXX_A_TX_7_MBHC_EN, 0x1F, 0x1C);
snd_soc_update_bits(codec, WCD9XXX_A_TX_7_MBHC_TEST_CTL, 0x40, 0x40);
snd_soc_update_bits(codec, WCD9XXX_A_TX_7_MBHC_EN, 0x80, 0x00);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x8, 0x8);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x8, 0x00);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x2, 0x2);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x8, 0x8);
if (!mbhc->mbhc_cfg->do_recalibration) {
if (!is_cs_enable)
wcd9xxx_calibrate_hs_polling(mbhc);
}
/* don't flip override */
bias_value = __wcd9xxx_codec_sta_dce(mbhc, 1, true, true);
snd_soc_write(codec, mbhc_micb_regs->cfilt_ctl, cfilt_mode);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x13, 0x00);
return bias_value;
}
static void wcd9xxx_recalibrate(struct wcd9xxx_mbhc *mbhc,
struct mbhc_micbias_regs *mbhc_micb_regs,
bool is_cs_enable)
{
struct snd_soc_codec *codec = mbhc->codec;
s16 reg;
int change;
struct wcd9xxx_mbhc_btn_detect_cfg *btn_det;
s16 sta_z = 0, dce_z = 0;
btn_det = WCD9XXX_MBHC_CAL_BTN_DET_PTR(mbhc->mbhc_cfg->calibration);
if (mbhc->mbhc_cfg->do_recalibration) {
/* recalibrate dce_z and sta_z */
reg = snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_B1_CTL);
change = snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL,
0x78, btn_det->mbhc_nsc << 3);
wcd9xxx_get_z(mbhc, &dce_z, &sta_z, mbhc_micb_regs, true);
if (change)
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, reg);
if (dce_z && sta_z) {
pr_debug("%s: sta_z 0x%x -> 0x%x, dce_z 0x%x -> 0x%x\n",
__func__,
mbhc->mbhc_data.sta_z, sta_z & 0xffff,
mbhc->mbhc_data.dce_z, dce_z & 0xffff);
mbhc->mbhc_data.dce_z = dce_z;
mbhc->mbhc_data.sta_z = sta_z;
wcd9xxx_mbhc_calc_thres(mbhc);
wcd9xxx_calibrate_hs_polling(mbhc);
} else {
pr_warn("%s: failed get new dce_z/sta_z 0x%x/0x%x\n",
__func__, dce_z, sta_z);
}
if (is_cs_enable) {
/* recalibrate dce_nsc_cs_z */
reg = snd_soc_read(mbhc->codec,
WCD9XXX_A_CDC_MBHC_B1_CTL);
snd_soc_update_bits(mbhc->codec,
WCD9XXX_A_CDC_MBHC_B1_CTL,
0x78, WCD9XXX_MBHC_NSC_CS << 3);
wcd9xxx_get_z(mbhc, &dce_z, NULL, mbhc_micb_regs,
true);
snd_soc_write(mbhc->codec, WCD9XXX_A_CDC_MBHC_B1_CTL,
reg);
if (dce_z) {
mbhc->mbhc_data.dce_nsc_cs_z = dce_z;
/* update v_cs_ins_h with new dce_nsc_cs_z */
mbhc->mbhc_data.v_cs_ins_h =
wcd9xxx_codec_v_sta_dce(
mbhc, DCE,
WCD9XXX_V_CS_HS_MAX,
is_cs_enable);
pr_debug("%s: dce_nsc_cs_z 0x%x -> 0x%x, v_cs_ins_h 0x%x\n",
__func__,
mbhc->mbhc_data.dce_nsc_cs_z,
dce_z & 0xffff,
mbhc->mbhc_data.v_cs_ins_h);
} else {
pr_debug("%s: failed get new dce_nsc_cs_z\n",
__func__);
}
}
}
}
static void wcd9xxx_shutdown_hs_removal_detect(struct wcd9xxx_mbhc *mbhc)
{
struct snd_soc_codec *codec = mbhc->codec;
const struct wcd9xxx_mbhc_general_cfg *generic =
WCD9XXX_MBHC_CAL_GENERAL_PTR(mbhc->mbhc_cfg->calibration);
/* Need MBHC clock */
if (mbhc->mbhc_cb && mbhc->mbhc_cb->codec_rco_ctrl)
mbhc->mbhc_cb->codec_rco_ctrl(mbhc->codec, true);
else {
WCD9XXX_BG_CLK_LOCK(mbhc->resmgr);
wcd9xxx_resmgr_get_clk_block(mbhc->resmgr, WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(mbhc->resmgr);
}
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x2, 0x2);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x6, 0x0);
__wcd9xxx_switch_micbias(mbhc, 0, false, false);
usleep_range(generic->t_shutdown_plug_rem,
generic->t_shutdown_plug_rem + 50);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0xA, 0x8);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->codec_rco_ctrl)
mbhc->mbhc_cb->codec_rco_ctrl(mbhc->codec, false);
else {
WCD9XXX_BG_CLK_LOCK(mbhc->resmgr);
/* Put requested CLK back */
wcd9xxx_resmgr_put_clk_block(mbhc->resmgr, WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(mbhc->resmgr);
}
snd_soc_write(codec, WCD9XXX_A_MBHC_SCALING_MUX_1, 0x00);
}
static void wcd9xxx_cleanup_hs_polling(struct wcd9xxx_mbhc *mbhc)
{
pr_debug("%s: enter\n", __func__);
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
wcd9xxx_shutdown_hs_removal_detect(mbhc);
/* Disable external voltage source to micbias if present */
if (mbhc->mbhc_cb && mbhc->mbhc_cb->enable_mb_source)
mbhc->mbhc_cb->enable_mb_source(mbhc->codec, false, true);
mbhc->polling_active = false;
mbhc->mbhc_state = MBHC_STATE_NONE;
pr_debug("%s: leave\n", __func__);
}
/* called under codec_resource_lock acquisition */
static void wcd9xxx_codec_hphr_gnd_switch(struct snd_soc_codec *codec, bool on)
{
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x01, on);
if (on)
usleep_range(5000, 5100);
}
static void wcd9xxx_onoff_vddio_switch(struct wcd9xxx_mbhc *mbhc, bool on)
{
pr_debug("%s: vddio %d\n", __func__, on);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->pull_mb_to_vddio) {
mbhc->mbhc_cb->pull_mb_to_vddio(mbhc->codec, on);
goto exit;
}
if (on) {
snd_soc_update_bits(mbhc->codec, mbhc->mbhc_bias_regs.mbhc_reg,
1 << 7, 1 << 7);
snd_soc_update_bits(mbhc->codec, WCD9XXX_A_MAD_ANA_CTRL,
1 << 4, 0);
} else {
snd_soc_update_bits(mbhc->codec, WCD9XXX_A_MAD_ANA_CTRL,
1 << 4, 1 << 4);
snd_soc_update_bits(mbhc->codec, mbhc->mbhc_bias_regs.mbhc_reg,
1 << 7, 0);
}
exit:
/*
* Wait for the micbias to settle down to vddio
* when the micbias to vddio switch is enabled.
*/
if (on)
usleep_range(10000, 10100);
}
static int wcd9xxx_hphl_status(struct wcd9xxx_mbhc *mbhc)
{
u16 hph, status;
struct snd_soc_codec *codec = mbhc->codec;
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
hph = snd_soc_read(codec, WCD9XXX_A_MBHC_HPH);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x12, 0x02);
usleep_range(WCD9XXX_HPHL_STATUS_READY_WAIT_US,
WCD9XXX_HPHL_STATUS_READY_WAIT_US +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
status = snd_soc_read(codec, WCD9XXX_A_RX_HPH_L_STATUS);
snd_soc_write(codec, WCD9XXX_A_MBHC_HPH, hph);
return status;
}
static enum wcd9xxx_mbhc_plug_type
wcd9xxx_cs_find_plug_type(struct wcd9xxx_mbhc *mbhc,
struct wcd9xxx_mbhc_detect *dt, const int size,
bool highhph,
unsigned long event_state)
{
int i;
int vdce, mb_mv;
int ch, sz, delta_thr;
int minv = 0, maxv = INT_MIN;
struct wcd9xxx_mbhc_detect *d = dt;
struct wcd9xxx_mbhc_detect *dprev = d, *dmicbias = NULL, *dgnd = NULL;
enum wcd9xxx_mbhc_plug_type type = PLUG_TYPE_INVALID;
const struct wcd9xxx_mbhc_plug_type_cfg *plug_type =
WCD9XXX_MBHC_CAL_PLUG_TYPE_PTR(mbhc->mbhc_cfg->calibration);
s16 hs_max, no_mic, dce_z;
int highhph_cnt = 0;
pr_debug("%s: enter\n", __func__);
pr_debug("%s: event_state 0x%lx\n", __func__, event_state);
sz = size - 1;
for (i = 0, d = dt, ch = 0; i < sz; i++, d++) {
if (d->mic_bias) {
dce_z = mbhc->mbhc_data.dce_z;
mb_mv = mbhc->mbhc_data.micb_mv;
hs_max = plug_type->v_hs_max;
no_mic = plug_type->v_no_mic;
} else {
dce_z = mbhc->mbhc_data.dce_nsc_cs_z;
mb_mv = VDDIO_MICBIAS_MV;
hs_max = WCD9XXX_V_CS_HS_MAX;
no_mic = WCD9XXX_V_CS_NO_MIC;
}
vdce = __wcd9xxx_codec_sta_dce_v(mbhc, true, d->dce,
dce_z, (u32)mb_mv);
d->_vdces = vdce;
if (d->_vdces < no_mic)
d->_type = PLUG_TYPE_HEADPHONE;
else if (d->_vdces >= hs_max) {
d->_type = PLUG_TYPE_HIGH_HPH;
highhph_cnt++;
} else
d->_type = PLUG_TYPE_HEADSET;
pr_debug("%s: DCE #%d, %04x, V %04d(%04d), HPHL %d TYPE %d\n",
__func__, i, d->dce, vdce, d->_vdces,
d->hphl_status & 0x01,
d->_type);
ch += d->hphl_status & 0x01;
if (!d->swap_gnd && !d->mic_bias) {
if (maxv < d->_vdces)
maxv = d->_vdces;
if (!minv || minv > d->_vdces)
minv = d->_vdces;
}
if ((!d->mic_bias &&
(d->_vdces >= WCD9XXX_CS_MEAS_INVALD_RANGE_LOW_MV &&
d->_vdces <= WCD9XXX_CS_MEAS_INVALD_RANGE_HIGH_MV)) ||
(d->mic_bias &&
(d->_vdces >= WCD9XXX_MEAS_INVALD_RANGE_LOW_MV &&
d->_vdces <= WCD9XXX_MEAS_INVALD_RANGE_HIGH_MV))) {
pr_debug("%s: within invalid range\n", __func__);
type = PLUG_TYPE_INVALID;
goto exit;
}
}
delta_thr = ((highhph_cnt == sz) || highhph) ?
WCD9XXX_MB_MEAS_DELTA_MAX_MV :
WCD9XXX_CS_MEAS_DELTA_MAX_MV;
for (i = 0, d = dt; i < sz; i++, d++) {
if ((i > 0) && !d->mic_bias && !d->swap_gnd &&
(d->_type != dprev->_type)) {
pr_debug("%s: Invalid, inconsistent types\n", __func__);
type = PLUG_TYPE_INVALID;
goto exit;
}
if (!d->swap_gnd && !d->mic_bias &&
(abs(minv - d->_vdces) > delta_thr ||
abs(maxv - d->_vdces) > delta_thr)) {
pr_debug("%s: Invalid, delta %dmv, %dmv and %dmv\n",
__func__, d->_vdces, minv, maxv);
type = PLUG_TYPE_INVALID;
goto exit;
} else if (d->swap_gnd) {
dgnd = d;
}
if (!d->mic_bias && !d->swap_gnd)
dprev = d;
else if (d->mic_bias)
dmicbias = d;
}
if (dgnd && dt->_type != PLUG_TYPE_HEADSET &&
dt->_type != dgnd->_type) {
pr_debug("%s: Invalid, inconsistent types\n", __func__);
type = PLUG_TYPE_INVALID;
goto exit;
}
type = dt->_type;
if (dmicbias) {
if (dmicbias->_type == PLUG_TYPE_HEADSET &&
(dt->_type == PLUG_TYPE_HIGH_HPH ||
dt->_type == PLUG_TYPE_HEADSET)) {
type = PLUG_TYPE_HEADSET;
if (dt->_type == PLUG_TYPE_HIGH_HPH) {
pr_debug("%s: Headset with threshold on MIC detected\n",
__func__);
if (mbhc->mbhc_cfg->micbias_enable_flags &
(1 << MBHC_MICBIAS_ENABLE_THRESHOLD_HEADSET))
mbhc->micbias_enable = true;
}
}
}
if (type == PLUG_TYPE_HEADSET && dgnd && !dgnd->mic_bias) {
/* if plug type is Headphone report as GND_MIC_SWAP */
if (dgnd->_type == PLUG_TYPE_HEADPHONE) {
pr_debug("%s: GND_MIC_SWAP\n", __func__);
type = PLUG_TYPE_GND_MIC_SWAP;
/*
* if type is GND_MIC_SWAP we should not check
* HPHL status hence goto exit
*/
goto exit;
} else if (dgnd->_type != PLUG_TYPE_HEADSET && !dmicbias) {
pr_debug("%s: Invalid, inconsistent types\n", __func__);
type = PLUG_TYPE_INVALID;
}
}
if (event_state & (1 << MBHC_EVENT_PA_HPHL)) {
pr_debug("%s: HPHL PA was ON\n", __func__);
} else if (ch != sz && ch > 0) {
pr_debug("%s: Invalid, inconsistent HPHL..\n", __func__);
type = PLUG_TYPE_INVALID;
goto exit;
}
if (!(event_state & (1UL << MBHC_EVENT_PA_HPHL))) {
if (((type == PLUG_TYPE_HEADSET ||
type == PLUG_TYPE_HEADPHONE) && ch != sz)) {
pr_debug("%s: Invalid, not fully inserted, TYPE %d\n",
__func__, type);
type = PLUG_TYPE_INVALID;
}
}
if (type == PLUG_TYPE_HEADSET &&
(mbhc->mbhc_cfg->micbias_enable_flags &
(1 << MBHC_MICBIAS_ENABLE_REGULAR_HEADSET)))
mbhc->micbias_enable = true;
exit:
pr_debug("%s: Plug type %d detected\n", __func__, type);
return type;
}
/*
* wcd9xxx_find_plug_type : Find out and return the best plug type with given
* list of wcd9xxx_mbhc_detect structure.
* param mbhc wcd9xxx_mbhc structure
* param dt collected measurements
* param size array size of dt
* param event_state mbhc->event_state when dt is collected
*/
static enum wcd9xxx_mbhc_plug_type
wcd9xxx_find_plug_type(struct wcd9xxx_mbhc *mbhc,
struct wcd9xxx_mbhc_detect *dt, const int size,
unsigned long event_state)
{
int i;
int ch;
enum wcd9xxx_mbhc_plug_type type;
int vdce;
struct wcd9xxx_mbhc_detect *d, *dprev, *dgnd = NULL, *dvddio = NULL;
int maxv = 0, minv = 0;
const struct wcd9xxx_mbhc_plug_type_cfg *plug_type =
WCD9XXX_MBHC_CAL_PLUG_TYPE_PTR(mbhc->mbhc_cfg->calibration);
const s16 hs_max = plug_type->v_hs_max;
const s16 no_mic = plug_type->v_no_mic;
pr_debug("%s: event_state 0x%lx\n", __func__, event_state);
for (i = 0, d = dt, ch = 0; i < size; i++, d++) {
vdce = wcd9xxx_codec_sta_dce_v(mbhc, true, d->dce);
if (d->vddio)
d->_vdces = scale_v_micb_vddio(mbhc, vdce, false);
else
d->_vdces = vdce;
if (d->_vdces >= no_mic && d->_vdces < hs_max)
d->_type = PLUG_TYPE_HEADSET;
else if (d->_vdces < no_mic)
d->_type = PLUG_TYPE_HEADPHONE;
else
d->_type = PLUG_TYPE_HIGH_HPH;
ch += d->hphl_status & 0x01;
if (!d->swap_gnd && !d->hwvalue && !d->vddio) {
if (maxv < d->_vdces)
maxv = d->_vdces;
if (!minv || minv > d->_vdces)
minv = d->_vdces;
}
pr_debug("%s: DCE #%d, %04x, V %04d(%04d), GND %d, VDDIO %d, HPHL %d TYPE %d\n",
__func__, i, d->dce, vdce, d->_vdces,
d->swap_gnd, d->vddio, d->hphl_status & 0x01,
d->_type);
/*
* If GND and MIC prongs are aligned to HPHR and GND of
* headphone, codec measures the voltage based on
* impedance between HPHR and GND which results in ~80mv.
* Avoid this.
*/
if (d->_vdces >= WCD9XXX_MEAS_INVALD_RANGE_LOW_MV &&
d->_vdces <= WCD9XXX_MEAS_INVALD_RANGE_HIGH_MV) {
pr_debug("%s: within invalid range\n", __func__);
type = PLUG_TYPE_INVALID;
goto exit;
}
}
if (event_state & (1 << MBHC_EVENT_PA_HPHL)) {
pr_debug("%s: HPHL PA was ON\n", __func__);
} else if (ch != size && ch > 0) {
pr_debug("%s: Invalid, inconsistent HPHL\n", __func__);
type = PLUG_TYPE_INVALID;
goto exit;
}
for (i = 0, dprev = NULL, d = dt; i < size; i++, d++) {
if (d->vddio) {
dvddio = d;
continue;
}
if ((i > 0) && (dprev != NULL) && (d->_type != dprev->_type)) {
pr_debug("%s: Invalid, inconsistent types\n", __func__);
type = PLUG_TYPE_INVALID;
goto exit;
}
if (!d->swap_gnd && !d->hwvalue &&
(abs(minv - d->_vdces) > WCD9XXX_MEAS_DELTA_MAX_MV ||
abs(maxv - d->_vdces) > WCD9XXX_MEAS_DELTA_MAX_MV)) {
pr_debug("%s: Invalid, delta %dmv, %dmv and %dmv\n",
__func__, d->_vdces, minv, maxv);
type = PLUG_TYPE_INVALID;
goto exit;
} else if (d->swap_gnd) {
dgnd = d;
}
dprev = d;
}
WARN_ON(i != size);
type = dt->_type;
if (type == PLUG_TYPE_HEADSET && dgnd) {
if ((dgnd->_vdces + WCD9XXX_GM_SWAP_THRES_MIN_MV <
minv) &&
(dgnd->_vdces + WCD9XXX_GM_SWAP_THRES_MAX_MV >
maxv))
type = PLUG_TYPE_GND_MIC_SWAP;
}
/* if HPHL PA was on, we cannot use hphl status */
if (!(event_state & (1UL << MBHC_EVENT_PA_HPHL))) {
if (((type == PLUG_TYPE_HEADSET ||
type == PLUG_TYPE_HEADPHONE) && ch != size) ||
(type == PLUG_TYPE_GND_MIC_SWAP && ch)) {
pr_debug("%s: Invalid, not fully inserted, TYPE %d\n",
__func__, type);
type = PLUG_TYPE_INVALID;
}
}
if (type == PLUG_TYPE_HEADSET) {
if (dvddio && ((dvddio->_vdces > hs_max) ||
(dvddio->_vdces > minv + WCD9XXX_THRESHOLD_MIC_THRESHOLD))) {
pr_debug("%s: Headset with threshold on MIC detected\n",
__func__);
if (mbhc->mbhc_cfg->micbias_enable_flags &
(1 << MBHC_MICBIAS_ENABLE_THRESHOLD_HEADSET))
mbhc->micbias_enable = true;
} else {
pr_debug("%s: Headset with regular MIC detected\n",
__func__);
if (mbhc->mbhc_cfg->micbias_enable_flags &
(1 << MBHC_MICBIAS_ENABLE_REGULAR_HEADSET))
mbhc->micbias_enable = true;
}
}
exit:
pr_debug("%s: Plug type %d detected, micbias_enable %d\n", __func__,
type, mbhc->micbias_enable);
return type;
}
/*
* Pull down MBHC micbias for provided duration in microsecond.
*/
static int wcd9xxx_pull_down_micbias(struct wcd9xxx_mbhc *mbhc, int us)
{
bool micbiasconn = false;
struct snd_soc_codec *codec = mbhc->codec;
const u16 ctlreg = mbhc->mbhc_bias_regs.ctl_reg;
/*
* Disable MBHC to micbias connection to pull down
* micbias and pull down micbias for a moment.
*/
if ((snd_soc_read(mbhc->codec, ctlreg) & 0x01)) {
WARN_ONCE(1, "MBHC micbias is already pulled down unexpectedly\n");
return -EFAULT;
}
if ((snd_soc_read(mbhc->codec, WCD9XXX_A_MAD_ANA_CTRL) & 1 << 4)) {
snd_soc_update_bits(mbhc->codec, WCD9XXX_A_MAD_ANA_CTRL,
1 << 4, 0);
micbiasconn = true;
}
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 0x01, 0x01);
/*
* Pull down for 1ms to discharge bias. Give small margin (10us) to be
* able to get consistent result across DCEs.
*/
usleep_range(1000, 1000 + 10);
if (micbiasconn)
snd_soc_update_bits(mbhc->codec, WCD9XXX_A_MAD_ANA_CTRL,
1 << 4, 1 << 4);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 0x01, 0x00);
usleep_range(us, us + WCD9XXX_USLEEP_RANGE_MARGIN_US);
return 0;
}
/* Called under codec resource lock acquisition */
void wcd9xxx_turn_onoff_current_source(struct wcd9xxx_mbhc *mbhc,
struct mbhc_micbias_regs *mbhc_micb_regs,
bool on, bool highhph)
{
struct snd_soc_codec *codec;
struct wcd9xxx_mbhc_btn_detect_cfg *btn_det;
const struct wcd9xxx_mbhc_plug_detect_cfg *plug_det =
WCD9XXX_MBHC_CAL_PLUG_DET_PTR(mbhc->mbhc_cfg->calibration);
btn_det = WCD9XXX_MBHC_CAL_BTN_DET_PTR(mbhc->mbhc_cfg->calibration);
codec = mbhc->codec;
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
if ((on && mbhc->is_cs_enabled) ||
(!on && !mbhc->is_cs_enabled)) {
pr_debug("%s: Current source is already %s\n",
__func__, on ? "ON" : "OFF");
return;
}
if (on) {
pr_debug("%s: enabling current source\n", __func__);
/* Nsc to 9 */
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL,
0x78, 0x48);
/* pull down diode bit to 0 */
snd_soc_update_bits(codec, mbhc_micb_regs->mbhc_reg,
0x01, 0x00);
/*
* Keep the low power insertion/removal
* detection (reg 0x3DD) disabled
*/
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_INT_CTL,
0x01, 0x00);
/*
* Enable the Mic Bias current source
* Write bits[6:5] of register MICB_2_MBHC to 0x3 (V_20_UA)
* Write bit[7] of register MICB_2_MBHC to 1
* (INS_DET_ISRC_EN__ENABLE)
* MICB_2_MBHC__SCHT_TRIG_EN to 1
*/
snd_soc_update_bits(codec, mbhc_micb_regs->mbhc_reg,
0xF0, 0xF0);
/* Disconnect MBHC Override from MicBias and LDOH */
snd_soc_update_bits(codec, WCD9XXX_A_MAD_ANA_CTRL, 0x10, 0x00);
mbhc->is_cs_enabled = true;
} else {
pr_debug("%s: disabling current source\n", __func__);
/* Connect MBHC Override from MicBias and LDOH */
snd_soc_update_bits(codec, WCD9XXX_A_MAD_ANA_CTRL, 0x10, 0x10);
/* INS_DET_ISRC_CTL to acdb value */
snd_soc_update_bits(codec, mbhc_micb_regs->mbhc_reg,
0x60, plug_det->mic_current << 5);
if (!highhph) {
/* INS_DET_ISRC_EN__ENABLE to 0 */
snd_soc_update_bits(codec,
mbhc_micb_regs->mbhc_reg,
0x80, 0x00);
/* MICB_2_MBHC__SCHT_TRIG_EN to 0 */
snd_soc_update_bits(codec,
mbhc_micb_regs->mbhc_reg,
0x10, 0x00);
}
/* Nsc to acdb value */
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x78,
btn_det->mbhc_nsc << 3);
mbhc->is_cs_enabled = false;
}
}
static enum wcd9xxx_mbhc_plug_type
wcd9xxx_codec_cs_get_plug_type(struct wcd9xxx_mbhc *mbhc, bool highhph)
{
struct snd_soc_codec *codec = mbhc->codec;
struct wcd9xxx_mbhc_detect rt[NUM_DCE_PLUG_INS_DETECT];
enum wcd9xxx_mbhc_plug_type type = PLUG_TYPE_INVALID;
int i;
pr_debug("%s: enter\n", __func__);
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
BUG_ON(NUM_DCE_PLUG_INS_DETECT < 4);
wcd9xxx_mbhc_ctrl_clk_bandgap(mbhc, true);
rt[0].swap_gnd = false;
rt[0].vddio = false;
rt[0].hwvalue = true;
rt[0].hphl_status = wcd9xxx_hphl_status(mbhc);
rt[0].dce = wcd9xxx_mbhc_setup_hs_polling(mbhc, &mbhc->mbhc_bias_regs,
true);
rt[0].mic_bias = false;
for (i = 1; i < NUM_DCE_PLUG_INS_DETECT - 1; i++) {
rt[i].swap_gnd = (i == NUM_DCE_PLUG_INS_DETECT - 3);
rt[i].mic_bias = ((i == NUM_DCE_PLUG_INS_DETECT - 4) &&
highhph);
rt[i].hphl_status = wcd9xxx_hphl_status(mbhc);
if (rt[i].swap_gnd)
wcd9xxx_codec_hphr_gnd_switch(codec, true);
if (rt[i].mic_bias)
wcd9xxx_turn_onoff_current_source(mbhc,
&mbhc->mbhc_bias_regs,
false, false);
rt[i].dce = __wcd9xxx_codec_sta_dce(mbhc, 1, !highhph, true);
if (rt[i].mic_bias)
wcd9xxx_turn_onoff_current_source(mbhc,
&mbhc->mbhc_bias_regs,
true, false);
if (rt[i].swap_gnd)
wcd9xxx_codec_hphr_gnd_switch(codec, false);
}
/* recalibrate DCE/STA GND voltages */
wcd9xxx_recalibrate(mbhc, &mbhc->mbhc_bias_regs, true);
type = wcd9xxx_cs_find_plug_type(mbhc, rt, ARRAY_SIZE(rt), highhph,
mbhc->event_state);
wcd9xxx_mbhc_ctrl_clk_bandgap(mbhc, false);
pr_debug("%s: plug_type:%d\n", __func__, type);
return type;
}
static enum wcd9xxx_mbhc_plug_type
wcd9xxx_codec_get_plug_type(struct wcd9xxx_mbhc *mbhc, bool highhph)
{
int i;
bool vddioon;
struct wcd9xxx_mbhc_plug_type_cfg *plug_type_ptr;
struct wcd9xxx_mbhc_detect rt[NUM_DCE_PLUG_INS_DETECT];
enum wcd9xxx_mbhc_plug_type type = PLUG_TYPE_INVALID;
struct snd_soc_codec *codec = mbhc->codec;
pr_debug("%s: enter\n", __func__);
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
/* make sure override is on */
WARN_ON(!(snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_B1_CTL) & 0x04));
/* GND and MIC swap detection requires at least 2 rounds of DCE */
BUG_ON(NUM_DCE_PLUG_INS_DETECT < 2);
detect_use_vddio_switch = mbhc->mbhc_cfg->use_vddio_meas;
/*
* There are chances vddio switch is on and cfilt voltage is adjusted
* to vddio voltage even after plug type removal reported.
*/
vddioon = __wcd9xxx_switch_micbias(mbhc, 0, false, false);
pr_debug("%s: vddio switch was %s\n", __func__, vddioon ? "on" : "off");
plug_type_ptr =
WCD9XXX_MBHC_CAL_PLUG_TYPE_PTR(mbhc->mbhc_cfg->calibration);
/*
* cfilter in fast mode requires 1ms to charge up and down micbias
* fully.
*/
(void) wcd9xxx_pull_down_micbias(mbhc,
WCD9XXX_MICBIAS_PULLDOWN_SETTLE_US);
wcd9xxx_mbhc_ctrl_clk_bandgap(mbhc, true);
rt[0].hphl_status = wcd9xxx_hphl_status(mbhc);
rt[0].dce = wcd9xxx_mbhc_setup_hs_polling(mbhc, &mbhc->mbhc_bias_regs,
false);
rt[0].swap_gnd = false;
rt[0].vddio = false;
rt[0].hwvalue = true;
for (i = 1; i < NUM_DCE_PLUG_INS_DETECT; i++) {
rt[i].swap_gnd = (i == NUM_DCE_PLUG_INS_DETECT - 2);
if (detect_use_vddio_switch)
rt[i].vddio = (i == 1);
else
rt[i].vddio = false;
rt[i].hphl_status = wcd9xxx_hphl_status(mbhc);
rt[i].hwvalue = false;
if (rt[i].swap_gnd)
wcd9xxx_codec_hphr_gnd_switch(codec, true);
if (rt[i].vddio)
wcd9xxx_onoff_vddio_switch(mbhc, true);
/*
* Pull down micbias to detect headset with mic which has
* threshold and to have more consistent voltage measurements.
*
* cfilter in fast mode requires 1ms to charge up and down
* micbias fully.
*/
(void) wcd9xxx_pull_down_micbias(mbhc,
WCD9XXX_MICBIAS_PULLDOWN_SETTLE_US);
rt[i].dce = __wcd9xxx_codec_sta_dce(mbhc, 1, true, true);
if (rt[i].vddio)
wcd9xxx_onoff_vddio_switch(mbhc, false);
if (rt[i].swap_gnd)
wcd9xxx_codec_hphr_gnd_switch(codec, false);
}
/* recalibrate DCE/STA GND voltages */
wcd9xxx_recalibrate(mbhc, &mbhc->mbhc_bias_regs, false);
if (vddioon)
__wcd9xxx_switch_micbias(mbhc, 1, false, false);
type = wcd9xxx_find_plug_type(mbhc, rt, ARRAY_SIZE(rt),
mbhc->event_state);
wcd9xxx_mbhc_ctrl_clk_bandgap(mbhc, false);
pr_debug("%s: leave\n", __func__);
return type;
}
static bool wcd9xxx_swch_level_remove(struct wcd9xxx_mbhc *mbhc)
{
if (mbhc->mbhc_cfg->gpio)
return (gpio_get_value_cansleep(mbhc->mbhc_cfg->gpio) !=
mbhc->mbhc_cfg->gpio_level_insert);
else if (mbhc->mbhc_cfg->insert_detect) {
if (mbhc->mbhc_cb && mbhc->mbhc_cb->insert_rem_status)
return mbhc->mbhc_cb->insert_rem_status(mbhc->codec);
else
return snd_soc_read(mbhc->codec,
WCD9XXX_A_MBHC_INSERT_DET_STATUS) &
(1 << 2);
} else
WARN(1, "Invalid jack detection configuration\n");
return true;
}
static bool is_clk_active(struct snd_soc_codec *codec)
{
return !!(snd_soc_read(codec, WCD9XXX_A_CDC_CLK_MCLK_CTL) & 0x05);
}
static int wcd9xxx_enable_hs_detect(struct wcd9xxx_mbhc *mbhc,
int insertion, int trigger, bool padac_off)
{
struct snd_soc_codec *codec = mbhc->codec;
int central_bias_enabled = 0;
const struct wcd9xxx_mbhc_general_cfg *generic =
WCD9XXX_MBHC_CAL_GENERAL_PTR(mbhc->mbhc_cfg->calibration);
const struct wcd9xxx_mbhc_plug_detect_cfg *plug_det =
WCD9XXX_MBHC_CAL_PLUG_DET_PTR(mbhc->mbhc_cfg->calibration);
pr_debug("%s: enter insertion(%d) trigger(0x%x)\n",
__func__, insertion, trigger);
if (!mbhc->mbhc_cfg->calibration) {
pr_err("Error, no wcd9xxx calibration\n");
return -EINVAL;
}
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_INT_CTL, 0x1, 0);
/*
* Make sure mic bias and Mic line schmitt trigger
* are turned OFF
*/
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 0x01, 0x01);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.mbhc_reg, 0x90, 0x00);
if (insertion) {
wcd9xxx_switch_micbias(mbhc, 0);
/* DAPM can manipulate PA/DAC bits concurrently */
if (padac_off == true)
wcd9xxx_set_and_turnoff_hph_padac(mbhc);
if (trigger & MBHC_USE_HPHL_TRIGGER) {
/* Enable HPH Schmitt Trigger */
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x11,
0x11);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x0C,
plug_det->hph_current << 2);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x02,
0x02);
}
if (trigger & MBHC_USE_MB_TRIGGER) {
/* enable the mic line schmitt trigger */
snd_soc_update_bits(codec,
mbhc->mbhc_bias_regs.mbhc_reg,
0x60, plug_det->mic_current << 5);
snd_soc_update_bits(codec,
mbhc->mbhc_bias_regs.mbhc_reg,
0x80, 0x80);
usleep_range(plug_det->t_mic_pid, plug_det->t_mic_pid +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
snd_soc_update_bits(codec,
mbhc->mbhc_bias_regs.ctl_reg, 0x01,
0x00);
snd_soc_update_bits(codec,
mbhc->mbhc_bias_regs.mbhc_reg,
0x10, 0x10);
}
/* setup for insetion detection */
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_INT_CTL, 0x2, 0);
} else {
pr_debug("setup for removal detection\n");
/* Make sure the HPH schmitt trigger is OFF */
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x12, 0x00);
/* enable the mic line schmitt trigger */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg,
0x01, 0x00);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.mbhc_reg, 0x60,
plug_det->mic_current << 5);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.mbhc_reg,
0x80, 0x80);
usleep_range(plug_det->t_mic_pid, plug_det->t_mic_pid +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.mbhc_reg,
0x10, 0x10);
/* Setup for low power removal detection */
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_INT_CTL, 0x2,
0x2);
}
if (snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_B1_CTL) & 0x4) {
/* called by interrupt */
if (!is_clk_active(codec)) {
wcd9xxx_resmgr_enable_config_mode(mbhc->resmgr, 1);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL,
0x06, 0);
usleep_range(generic->t_shutdown_plug_rem,
generic->t_shutdown_plug_rem +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
wcd9xxx_resmgr_enable_config_mode(mbhc->resmgr, 0);
} else
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL,
0x06, 0);
}
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.int_rbias, 0x80, 0);
/* If central bandgap disabled */
if (!(snd_soc_read(codec, WCD9XXX_A_PIN_CTL_OE1) & 1)) {
snd_soc_update_bits(codec, WCD9XXX_A_PIN_CTL_OE1, 0x3, 0x3);
usleep_range(generic->t_bg_fast_settle,
generic->t_bg_fast_settle +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
central_bias_enabled = 1;
}
/* If LDO_H disabled */
if (snd_soc_read(codec, WCD9XXX_A_PIN_CTL_OE0) & 0x80) {
snd_soc_update_bits(codec, WCD9XXX_A_PIN_CTL_OE0, 0x10, 0);
snd_soc_update_bits(codec, WCD9XXX_A_PIN_CTL_OE0, 0x80, 0x80);
usleep_range(generic->t_ldoh, generic->t_ldoh +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
snd_soc_update_bits(codec, WCD9XXX_A_PIN_CTL_OE0, 0x80, 0);
if (central_bias_enabled)
snd_soc_update_bits(codec, WCD9XXX_A_PIN_CTL_OE1, 0x1,
0);
}
if (mbhc->resmgr->reg_addr && mbhc->resmgr->reg_addr->micb_4_mbhc)
snd_soc_update_bits(codec, mbhc->resmgr->reg_addr->micb_4_mbhc,
0x3, mbhc->mbhc_cfg->micbias);
wcd9xxx_enable_irq(mbhc->resmgr->core_res, mbhc->intr_ids->insertion);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_INT_CTL, 0x1, 0x1);
pr_debug("%s: leave\n", __func__);
return 0;
}
/*
* Function to determine whether anc microphone is preset or not.
* Return true if anc microphone is detected or false if not detected.
*/
static bool wcd9xxx_detect_anc_plug_type(struct wcd9xxx_mbhc *mbhc)
{
struct wcd9xxx_mbhc_detect rt[NUM_DCE_PLUG_INS_DETECT - 1];
bool anc_mic_found = true;
int i, mb_mv;
const struct wcd9xxx_mbhc_plug_type_cfg *plug_type =
WCD9XXX_MBHC_CAL_PLUG_TYPE_PTR(mbhc->mbhc_cfg->calibration);
s16 hs_max, dce_z;
s16 no_mic;
bool override_en;
bool timedout;
unsigned long timeout, retry = 0;
enum wcd9xxx_mbhc_plug_type type;
bool cs_enable;
if (mbhc->mbhc_cfg->anc_micbias != MBHC_MICBIAS3 &&
mbhc->mbhc_cfg->anc_micbias != MBHC_MICBIAS2)
return false;
pr_debug("%s: enter\n", __func__);
override_en = (snd_soc_read(mbhc->codec, WCD9XXX_A_CDC_MBHC_B1_CTL) &
0x04) ? true : false;
cs_enable = ((mbhc->mbhc_cfg->cs_enable_flags &
(1 << MBHC_CS_ENABLE_DET_ANC)) != 0) &&
(!(snd_soc_read(mbhc->codec,
mbhc->mbhc_anc_bias_regs.ctl_reg) & 0x80)) &&
(mbhc->mbhc_cfg->micbias != mbhc->mbhc_cfg->anc_micbias);
if (cs_enable) {
wcd9xxx_turn_onoff_current_source(mbhc,
&mbhc->mbhc_anc_bias_regs,
true, false);
} else {
if (mbhc->mbhc_cfg->anc_micbias == MBHC_MICBIAS3) {
if (mbhc->micbias_enable_cb)
mbhc->micbias_enable_cb(mbhc->codec, true,
mbhc->mbhc_cfg->anc_micbias);
else
return false;
} else {
/* Enable override */
if (!override_en)
wcd9xxx_turn_onoff_override(mbhc, true);
}
}
if (!cs_enable) {
hs_max = plug_type->v_hs_max;
no_mic = plug_type->v_no_mic;
dce_z = mbhc->mbhc_data.dce_z;
mb_mv = mbhc->mbhc_data.micb_mv;
} else {
hs_max = WCD9XXX_V_CS_HS_MAX;
no_mic = WCD9XXX_V_CS_NO_MIC;
mb_mv = VDDIO_MICBIAS_MV;
dce_z = mbhc->mbhc_data.dce_nsc_cs_z;
}
wcd9xxx_mbhc_ctrl_clk_bandgap(mbhc, true);
timeout = jiffies + msecs_to_jiffies(ANC_HPH_DETECT_PLUG_TIME_MS);
anc_mic_found = true;
while (!(timedout = time_after(jiffies, timeout))) {
retry++;
if (wcd9xxx_swch_level_remove(mbhc)) {
pr_debug("%s: Switch level is low\n", __func__);
anc_mic_found = false;
break;
}
pr_debug("%s: Retry attempt %lu", __func__, retry - 1);
rt[0].hphl_status = wcd9xxx_hphl_status(mbhc);
rt[0].dce = wcd9xxx_mbhc_setup_hs_polling(mbhc,
&mbhc->mbhc_anc_bias_regs,
cs_enable);
rt[0]._vdces = __wcd9xxx_codec_sta_dce_v(mbhc, true, rt[0].dce,
dce_z, (u32)mb_mv);
if (rt[0]._vdces >= no_mic && rt[0]._vdces < hs_max)
rt[0]._type = PLUG_TYPE_HEADSET;
else if (rt[0]._vdces < no_mic)
rt[0]._type = PLUG_TYPE_HEADPHONE;
else
rt[0]._type = PLUG_TYPE_HIGH_HPH;
pr_debug("%s: DCE #%d, V %04d, HPHL %d TYPE %d\n",
__func__, 0, rt[0]._vdces,
rt[0].hphl_status & 0x01,
rt[0]._type);
for (i = 1; i < NUM_DCE_PLUG_INS_DETECT - 1; i++) {
rt[i].dce = __wcd9xxx_codec_sta_dce(mbhc, 1,
true, true);
rt[i]._vdces = __wcd9xxx_codec_sta_dce_v(mbhc, true,
rt[i].dce, dce_z,
(u32) mb_mv);
if (rt[i]._vdces >= no_mic && rt[i]._vdces < hs_max)
rt[i]._type = PLUG_TYPE_HEADSET;
else if (rt[i]._vdces < no_mic)
rt[i]._type = PLUG_TYPE_HEADPHONE;
else
rt[i]._type = PLUG_TYPE_HIGH_HPH;
rt[i].hphl_status = wcd9xxx_hphl_status(mbhc);
pr_debug("%s: DCE #%d, V %04d, HPHL %d TYPE %d\n",
__func__, i, rt[i]._vdces,
rt[i].hphl_status & 0x01,
rt[i]._type);
}
/*
* Check for the "type" of all the 4 measurements
* If all 4 measurements have the Type as PLUG_TYPE_HEADSET
* then it is proper mic and declare that the plug has two mics
*/
for (i = 0; i < NUM_DCE_PLUG_INS_DETECT - 1; i++) {
if (i > 0 && (rt[i - 1]._type != rt[i]._type)) {
type = PLUG_TYPE_INVALID;
break;
} else {
type = rt[0]._type;
}
}
pr_debug("%s: Plug type found in ANC detection :%d",
__func__, type);
if (type != PLUG_TYPE_HEADSET)
anc_mic_found = false;
if (anc_mic_found || (type == PLUG_TYPE_HEADPHONE &&
mbhc->mbhc_cfg->hw_jack_type == FIVE_POLE_JACK) ||
(type == PLUG_TYPE_HIGH_HPH &&
mbhc->mbhc_cfg->hw_jack_type == SIX_POLE_JACK))
break;
}
wcd9xxx_mbhc_ctrl_clk_bandgap(mbhc, false);
if (cs_enable) {
wcd9xxx_turn_onoff_current_source(mbhc,
&mbhc->mbhc_anc_bias_regs,
false, false);
} else {
if (mbhc->mbhc_cfg->anc_micbias == MBHC_MICBIAS3) {
if (mbhc->micbias_enable_cb)
mbhc->micbias_enable_cb(mbhc->codec, false,
mbhc->mbhc_cfg->anc_micbias);
} else {
/* Disable override */
if (!override_en)
wcd9xxx_turn_onoff_override(mbhc, false);
}
}
pr_debug("%s: leave\n", __func__);
return anc_mic_found;
}
/* called under codec_resource_lock acquisition */
static void wcd9xxx_find_plug_and_report(struct wcd9xxx_mbhc *mbhc,
enum wcd9xxx_mbhc_plug_type plug_type)
{
bool anc_mic_found = false;
pr_debug("%s: enter current_plug(%d) new_plug(%d)\n",
__func__, mbhc->current_plug, plug_type);
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
if (plug_type == PLUG_TYPE_HEADPHONE &&
mbhc->current_plug == PLUG_TYPE_NONE) {
/*
* Nothing was reported previously
* report a headphone or unsupported
*/
wcd9xxx_report_plug(mbhc, 1, SND_JACK_HEADPHONE);
wcd9xxx_cleanup_hs_polling(mbhc);
} else if (plug_type == PLUG_TYPE_GND_MIC_SWAP) {
if (!mbhc->mbhc_cfg->detect_extn_cable) {
if (mbhc->current_plug == PLUG_TYPE_HEADSET)
wcd9xxx_report_plug(mbhc, 0,
SND_JACK_HEADSET);
else if (mbhc->current_plug == PLUG_TYPE_HEADPHONE)
wcd9xxx_report_plug(mbhc, 0,
SND_JACK_HEADPHONE);
}
wcd9xxx_report_plug(mbhc, 1, SND_JACK_UNSUPPORTED);
wcd9xxx_cleanup_hs_polling(mbhc);
} else if (plug_type == PLUG_TYPE_HEADSET) {
if (mbhc->mbhc_cfg->enable_anc_mic_detect) {
/*
* Do not report Headset, because at this point
* it could be a ANC headphone having two mics.
* So, proceed further to detect if there is a
* second mic.
*/
mbhc->scaling_mux_in = 0x08;
anc_mic_found = wcd9xxx_detect_anc_plug_type(mbhc);
}
if (anc_mic_found) {
/* Report ANC headphone */
wcd9xxx_report_plug(mbhc, 1, SND_JACK_ANC_HEADPHONE);
} else {
/*
* If Headphone was reported previously, this will
* only report the mic line
*/
wcd9xxx_report_plug(mbhc, 1, SND_JACK_HEADSET);
}
/* Button detection required RC oscillator */
wcd9xxx_mbhc_ctrl_clk_bandgap(mbhc, true);
/*
* sleep so that audio path completely tears down
* before report plug insertion to the user space
*/
msleep(100);
wcd9xxx_start_hs_polling(mbhc);
} else if (plug_type == PLUG_TYPE_HIGH_HPH) {
if (mbhc->mbhc_cfg->detect_extn_cable) {
/* High impedance device found. Report as LINEOUT*/
if (mbhc->current_plug == PLUG_TYPE_NONE)
wcd9xxx_report_plug(mbhc, 1, SND_JACK_LINEOUT);
wcd9xxx_cleanup_hs_polling(mbhc);
pr_debug("%s: setup mic trigger for further detection\n",
__func__);
mbhc->lpi_enabled = true;
/*
* Do not enable HPHL trigger. If playback is active,
* it might lead to continuous false HPHL triggers
*/
wcd9xxx_enable_hs_detect(mbhc, 1, MBHC_USE_MB_TRIGGER,
false);
} else {
if (mbhc->current_plug == PLUG_TYPE_NONE)
wcd9xxx_report_plug(mbhc, 1,
SND_JACK_HEADPHONE);
wcd9xxx_cleanup_hs_polling(mbhc);
pr_debug("setup mic trigger for further detection\n");
mbhc->lpi_enabled = true;
wcd9xxx_enable_hs_detect(mbhc, 1, MBHC_USE_MB_TRIGGER |
MBHC_USE_HPHL_TRIGGER,
false);
}
} else {
WARN(1, "Unexpected current plug_type %d, plug_type %d\n",
mbhc->current_plug, plug_type);
}
pr_debug("%s: leave\n", __func__);
}
/* called under codec_resource_lock acquisition */
static void wcd9xxx_mbhc_decide_swch_plug(struct wcd9xxx_mbhc *mbhc)
{
enum wcd9xxx_mbhc_plug_type plug_type;
bool current_source_enable;
pr_debug("%s: enter\n", __func__);
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
current_source_enable = (((mbhc->mbhc_cfg->cs_enable_flags &
(1 << MBHC_CS_ENABLE_INSERTION)) != 0) &&
(!(snd_soc_read(mbhc->codec,
mbhc->mbhc_bias_regs.ctl_reg) & 0x80)));
mbhc->scaling_mux_in = 0x04;
if (current_source_enable) {
wcd9xxx_turn_onoff_current_source(mbhc, &mbhc->mbhc_bias_regs,
true, false);
plug_type = wcd9xxx_codec_cs_get_plug_type(mbhc, false);
/*
* For other plug types, the current source disable
* will be done from wcd9xxx_correct_swch_plug
*/
if (plug_type == PLUG_TYPE_HEADSET)
wcd9xxx_turn_onoff_current_source(mbhc,
&mbhc->mbhc_bias_regs,
false, false);
} else {
wcd9xxx_turn_onoff_override(mbhc, true);
plug_type = wcd9xxx_codec_get_plug_type(mbhc, true);
wcd9xxx_turn_onoff_override(mbhc, false);
}
if (wcd9xxx_swch_level_remove(mbhc)) {
if (current_source_enable && mbhc->is_cs_enabled) {
wcd9xxx_turn_onoff_current_source(mbhc,
&mbhc->mbhc_bias_regs,
false, false);
}
pr_debug("%s: Switch level is low when determining plug\n",
__func__);
return;
}
if (plug_type == PLUG_TYPE_INVALID ||
plug_type == PLUG_TYPE_GND_MIC_SWAP) {
wcd9xxx_cleanup_hs_polling(mbhc);
wcd9xxx_schedule_hs_detect_plug(mbhc,
&mbhc->correct_plug_swch);
} else if (plug_type == PLUG_TYPE_HEADPHONE) {
wcd9xxx_report_plug(mbhc, 1, SND_JACK_HEADPHONE);
wcd9xxx_cleanup_hs_polling(mbhc);
wcd9xxx_schedule_hs_detect_plug(mbhc,
&mbhc->correct_plug_swch);
} else if (plug_type == PLUG_TYPE_HIGH_HPH) {
wcd9xxx_cleanup_hs_polling(mbhc);
wcd9xxx_schedule_hs_detect_plug(mbhc,
&mbhc->correct_plug_swch);
} else {
pr_debug("%s: Valid plug found, determine plug type %d\n",
__func__, plug_type);
wcd9xxx_find_plug_and_report(mbhc, plug_type);
}
pr_debug("%s: leave\n", __func__);
}
/* called under codec_resource_lock acquisition */
static void wcd9xxx_mbhc_detect_plug_type(struct wcd9xxx_mbhc *mbhc)
{
pr_debug("%s: enter\n", __func__);
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
if (wcd9xxx_swch_level_remove(mbhc))
pr_debug("%s: Switch level low when determining plug\n",
__func__);
else
wcd9xxx_mbhc_decide_swch_plug(mbhc);
pr_debug("%s: leave\n", __func__);
}
/* called only from interrupt which is under codec_resource_lock acquisition */
static void wcd9xxx_hs_insert_irq_swch(struct wcd9xxx_mbhc *mbhc,
bool is_removal)
{
if (!is_removal) {
pr_debug("%s: MIC trigger insertion interrupt\n", __func__);
rmb();
if (mbhc->lpi_enabled)
msleep(100);
rmb();
if (!mbhc->lpi_enabled) {
pr_debug("%s: lpi is disabled\n", __func__);
} else if (!wcd9xxx_swch_level_remove(mbhc)) {
pr_debug("%s: Valid insertion, detect plug type\n",
__func__);
wcd9xxx_mbhc_decide_swch_plug(mbhc);
} else {
pr_debug("%s: Invalid insertion stop plug detection\n",
__func__);
}
} else if (mbhc->mbhc_cfg->detect_extn_cable) {
pr_debug("%s: Removal\n", __func__);
if (!wcd9xxx_swch_level_remove(mbhc)) {
/*
* Switch indicates, something is still inserted.
* This could be extension cable i.e. headset is
* removed from extension cable.
*/
/* cancel detect plug */
wcd9xxx_cancel_hs_detect_plug(mbhc,
&mbhc->correct_plug_swch);
wcd9xxx_mbhc_decide_swch_plug(mbhc);
}
} else {
pr_err("%s: Switch IRQ used, invalid MBHC Removal\n", __func__);
}
}
static bool is_valid_mic_voltage(struct wcd9xxx_mbhc *mbhc, s32 mic_mv,
bool cs_enable)
{
const struct wcd9xxx_mbhc_plug_type_cfg *plug_type =
WCD9XXX_MBHC_CAL_PLUG_TYPE_PTR(mbhc->mbhc_cfg->calibration);
const s16 v_hs_max = wcd9xxx_get_current_v_hs_max(mbhc);
if (cs_enable)
return ((mic_mv > WCD9XXX_V_CS_NO_MIC) &&
(mic_mv < WCD9XXX_V_CS_HS_MAX)) ? true : false;
else
return (!(mic_mv > WCD9XXX_MEAS_INVALD_RANGE_LOW_MV &&
mic_mv < WCD9XXX_MEAS_INVALD_RANGE_HIGH_MV) &&
(mic_mv > plug_type->v_no_mic) &&
(mic_mv < v_hs_max)) ? true : false;
}
/*
* called under codec_resource_lock acquisition
* returns true if mic voltage range is back to normal insertion
* returns false either if timedout or removed
*/
static bool wcd9xxx_hs_remove_settle(struct wcd9xxx_mbhc *mbhc)
{
int i;
bool timedout, settled = false;
s32 mic_mv[NUM_DCE_PLUG_DETECT];
short mb_v[NUM_DCE_PLUG_DETECT];
unsigned long retry = 0, timeout;
bool cs_enable;
cs_enable = (((mbhc->mbhc_cfg->cs_enable_flags &
(1 << MBHC_CS_ENABLE_REMOVAL)) != 0) &&
(!(snd_soc_read(mbhc->codec,
mbhc->mbhc_bias_regs.ctl_reg) & 0x80)));
if (cs_enable)
wcd9xxx_turn_onoff_current_source(mbhc, &mbhc->mbhc_bias_regs,
true, false);
timeout = jiffies + msecs_to_jiffies(HS_DETECT_PLUG_TIME_MS);
while (!(timedout = time_after(jiffies, timeout))) {
retry++;
if (wcd9xxx_swch_level_remove(mbhc)) {
pr_debug("%s: Switch indicates removal\n", __func__);
break;
}
if (retry > 1)
msleep(250);
else
msleep(50);
if (wcd9xxx_swch_level_remove(mbhc)) {
pr_debug("%s: Switch indicates removal\n", __func__);
break;
}
if (cs_enable) {
for (i = 0; i < NUM_DCE_PLUG_DETECT; i++) {
mb_v[i] = __wcd9xxx_codec_sta_dce(mbhc, 1,
true, true);
mic_mv[i] = __wcd9xxx_codec_sta_dce_v(mbhc,
true,
mb_v[i],
mbhc->mbhc_data.dce_nsc_cs_z,
(u32)VDDIO_MICBIAS_MV);
pr_debug("%s : DCE run %lu, mic_mv = %d(%x)\n",
__func__, retry, mic_mv[i], mb_v[i]);
}
} else {
for (i = 0; i < NUM_DCE_PLUG_DETECT; i++) {
mb_v[i] = wcd9xxx_codec_sta_dce(mbhc, 1,
true);
mic_mv[i] = wcd9xxx_codec_sta_dce_v(mbhc, 1,
mb_v[i]);
pr_debug("%s : DCE run %lu, mic_mv = %d(%x)\n",
__func__, retry, mic_mv[i],
mb_v[i]);
}
}
if (wcd9xxx_swch_level_remove(mbhc)) {
pr_debug("%s: Switcn indicates removal\n", __func__);
break;
}
if (mbhc->current_plug == PLUG_TYPE_NONE) {
pr_debug("%s : headset/headphone is removed\n",
__func__);
break;
}
for (i = 0; i < NUM_DCE_PLUG_DETECT; i++)
if (!is_valid_mic_voltage(mbhc, mic_mv[i], cs_enable))
break;
if (i == NUM_DCE_PLUG_DETECT) {
pr_debug("%s: MIC voltage settled\n", __func__);
settled = true;
msleep(200);
break;
}
}
if (cs_enable)
wcd9xxx_turn_onoff_current_source(mbhc, &mbhc->mbhc_bias_regs,
false, false);
if (timedout)
pr_debug("%s: Microphone did not settle in %d seconds\n",
__func__, HS_DETECT_PLUG_TIME_MS);
return settled;
}
/* called only from interrupt which is under codec_resource_lock acquisition */
static void wcd9xxx_hs_remove_irq_swch(struct wcd9xxx_mbhc *mbhc)
{
pr_debug("%s: enter\n", __func__);
if (wcd9xxx_hs_remove_settle(mbhc))
wcd9xxx_start_hs_polling(mbhc);
pr_debug("%s: leave\n", __func__);
}
/* called only from interrupt which is under codec_resource_lock acquisition */
static void wcd9xxx_hs_remove_irq_noswch(struct wcd9xxx_mbhc *mbhc)
{
s16 dce, dcez;
unsigned long timeout;
bool removed = true;
struct snd_soc_codec *codec = mbhc->codec;
const struct wcd9xxx_mbhc_general_cfg *generic =
WCD9XXX_MBHC_CAL_GENERAL_PTR(mbhc->mbhc_cfg->calibration);
bool cs_enable;
s16 cur_v_ins_h;
u32 mb_mv;
pr_debug("%s: enter\n", __func__);
if (mbhc->current_plug != PLUG_TYPE_HEADSET &&
mbhc->current_plug != PLUG_TYPE_ANC_HEADPHONE) {
pr_debug("%s(): Headset is not inserted, ignore removal\n",
__func__);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL,
0x08, 0x08);
return;
}
usleep_range(generic->t_shutdown_plug_rem,
generic->t_shutdown_plug_rem +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
/* If micbias is enabled, don't enable current source */
cs_enable = (((mbhc->mbhc_cfg->cs_enable_flags &
(1 << MBHC_CS_ENABLE_REMOVAL)) != 0) &&
(!(snd_soc_read(codec,
mbhc->mbhc_bias_regs.ctl_reg) & 0x80)));
if (cs_enable)
wcd9xxx_turn_onoff_current_source(mbhc, &mbhc->mbhc_bias_regs,
true, false);
timeout = jiffies + msecs_to_jiffies(FAKE_REMOVAL_MIN_PERIOD_MS);
do {
if (cs_enable) {
dce = __wcd9xxx_codec_sta_dce(mbhc, 1, true, true);
dcez = mbhc->mbhc_data.dce_nsc_cs_z;
mb_mv = VDDIO_MICBIAS_MV;
} else {
dce = wcd9xxx_codec_sta_dce(mbhc, 1, true);
dcez = mbhc->mbhc_data.dce_z;
mb_mv = mbhc->mbhc_data.micb_mv;
}
pr_debug("%s: DCE 0x%x,%d\n", __func__, dce,
__wcd9xxx_codec_sta_dce_v(mbhc, true, dce,
dcez, mb_mv));
cur_v_ins_h = cs_enable ? (s16) mbhc->mbhc_data.v_cs_ins_h :
(wcd9xxx_get_current_v(mbhc,
WCD9XXX_CURRENT_V_INS_H));
if (dce < cur_v_ins_h) {
removed = false;
break;
}
} while (!time_after(jiffies, timeout));
pr_debug("%s: headset %sactually removed\n", __func__,
removed ? "" : "not ");
if (cs_enable)
wcd9xxx_turn_onoff_current_source(mbhc, &mbhc->mbhc_bias_regs,
false, false);
if (removed) {
if (mbhc->mbhc_cfg->detect_extn_cable) {
if (!wcd9xxx_swch_level_remove(mbhc)) {
/*
* extension cable is still plugged in
* report it as LINEOUT device
*/
if (mbhc->hph_status == SND_JACK_HEADSET)
wcd9xxx_mbhc_ctrl_clk_bandgap(mbhc,
false);
wcd9xxx_report_plug(mbhc, 1, SND_JACK_LINEOUT);
wcd9xxx_cleanup_hs_polling(mbhc);
wcd9xxx_enable_hs_detect(mbhc, 1,
MBHC_USE_MB_TRIGGER,
false);
}
} else {
/* Cancel possibly running hs_detect_work */
wcd9xxx_cancel_hs_detect_plug(mbhc,
&mbhc->correct_plug_noswch);
/*
* If this removal is not false, first check the micbias
* switch status and switch it to LDOH if it is already
* switched to VDDIO.
*/
wcd9xxx_switch_micbias(mbhc, 0);
wcd9xxx_report_plug(mbhc, 0, SND_JACK_HEADSET);
wcd9xxx_mbhc_ctrl_clk_bandgap(mbhc, false);
wcd9xxx_cleanup_hs_polling(mbhc);
wcd9xxx_enable_hs_detect(mbhc, 1, MBHC_USE_MB_TRIGGER |
MBHC_USE_HPHL_TRIGGER,
true);
}
} else {
wcd9xxx_start_hs_polling(mbhc);
}
pr_debug("%s: leave\n", __func__);
}
/* called only from interrupt which is under codec_resource_lock acquisition */
static void wcd9xxx_hs_insert_irq_extn(struct wcd9xxx_mbhc *mbhc,
bool is_mb_trigger)
{
/* Cancel possibly running hs_detect_work */
wcd9xxx_cancel_hs_detect_plug(mbhc, &mbhc->correct_plug_swch);
if (is_mb_trigger) {
pr_debug("%s: Waiting for Headphone left trigger\n", __func__);
wcd9xxx_enable_hs_detect(mbhc, 1, MBHC_USE_HPHL_TRIGGER, false);
} else {
pr_debug("%s: HPHL trigger received, detecting plug type\n",
__func__);
wcd9xxx_mbhc_detect_plug_type(mbhc);
}
}
static irqreturn_t wcd9xxx_hs_remove_irq(int irq, void *data)
{
struct wcd9xxx_mbhc *mbhc = data;
pr_debug("%s: enter, removal interrupt\n", __func__);
WCD9XXX_BCL_LOCK(mbhc->resmgr);
/*
* While we don't know whether MIC is there or not, let the resmgr know
* so micbias can be disabled temporarily
*/
if (mbhc->current_plug == PLUG_TYPE_HEADSET) {
wcd9xxx_resmgr_cond_update_cond(mbhc->resmgr,
WCD9XXX_COND_HPH_MIC, false);
wcd9xxx_resmgr_cond_update_cond(mbhc->resmgr,
WCD9XXX_COND_HPH, false);
} else if (mbhc->current_plug == PLUG_TYPE_HEADPHONE) {
wcd9xxx_resmgr_cond_update_cond(mbhc->resmgr,
WCD9XXX_COND_HPH, false);
}
if (mbhc->mbhc_cfg->detect_extn_cable &&
!wcd9xxx_swch_level_remove(mbhc))
wcd9xxx_hs_remove_irq_noswch(mbhc);
else
wcd9xxx_hs_remove_irq_swch(mbhc);
if (mbhc->current_plug == PLUG_TYPE_HEADSET) {
wcd9xxx_resmgr_cond_update_cond(mbhc->resmgr,
WCD9XXX_COND_HPH, true);
wcd9xxx_resmgr_cond_update_cond(mbhc->resmgr,
WCD9XXX_COND_HPH_MIC, true);
} else if (mbhc->current_plug == PLUG_TYPE_HEADPHONE) {
wcd9xxx_resmgr_cond_update_cond(mbhc->resmgr,
WCD9XXX_COND_HPH, true);
}
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
return IRQ_HANDLED;
}
static irqreturn_t wcd9xxx_hs_insert_irq(int irq, void *data)
{
bool is_mb_trigger, is_removal;
struct wcd9xxx_mbhc *mbhc = data;
struct snd_soc_codec *codec = mbhc->codec;
pr_debug("%s: enter\n", __func__);
WCD9XXX_BCL_LOCK(mbhc->resmgr);
wcd9xxx_disable_irq(mbhc->resmgr->core_res, mbhc->intr_ids->insertion);
is_mb_trigger = !!(snd_soc_read(codec, mbhc->mbhc_bias_regs.mbhc_reg) &
0x10);
is_removal = !!(snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_INT_CTL) & 0x02);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_INT_CTL, 0x03, 0x00);
/* Turn off both HPH and MIC line schmitt triggers */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.mbhc_reg, 0x90, 0x00);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x13, 0x00);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 0x01, 0x00);
if (mbhc->mbhc_cfg->detect_extn_cable &&
mbhc->current_plug == PLUG_TYPE_HIGH_HPH)
wcd9xxx_hs_insert_irq_extn(mbhc, is_mb_trigger);
else
wcd9xxx_hs_insert_irq_swch(mbhc, is_removal);
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
return IRQ_HANDLED;
}
static void wcd9xxx_btn_lpress_fn(struct work_struct *work)
{
struct delayed_work *dwork;
short bias_value;
int dce_mv, sta_mv;
struct wcd9xxx_mbhc *mbhc;
pr_debug("%s:\n", __func__);
dwork = to_delayed_work(work);
mbhc = container_of(dwork, struct wcd9xxx_mbhc, mbhc_btn_dwork);
bias_value = wcd9xxx_read_sta_result(mbhc->codec);
sta_mv = wcd9xxx_codec_sta_dce_v(mbhc, 0, bias_value);
bias_value = wcd9xxx_read_dce_result(mbhc->codec);
dce_mv = wcd9xxx_codec_sta_dce_v(mbhc, 1, bias_value);
pr_debug("%s: STA: %d, DCE: %d\n", __func__, sta_mv, dce_mv);
pr_debug("%s: Reporting long button press event\n", __func__);
wcd9xxx_jack_report(mbhc, &mbhc->button_jack, mbhc->buttons_pressed,
mbhc->buttons_pressed);
pr_debug("%s: leave\n", __func__);
wcd9xxx_unlock_sleep(mbhc->resmgr->core_res);
}
static void wcd9xxx_mbhc_insert_work(struct work_struct *work)
{
struct delayed_work *dwork;
struct wcd9xxx_mbhc *mbhc;
struct snd_soc_codec *codec;
struct wcd9xxx_core_resource *core_res;
dwork = to_delayed_work(work);
mbhc = container_of(dwork, struct wcd9xxx_mbhc, mbhc_insert_dwork);
codec = mbhc->codec;
core_res = mbhc->resmgr->core_res;
pr_debug("%s:\n", __func__);
/* Turn off both HPH and MIC line schmitt triggers */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.mbhc_reg, 0x90, 0x00);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x13, 0x00);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 0x01, 0x00);
wcd9xxx_disable_irq_sync(core_res, mbhc->intr_ids->insertion);
wcd9xxx_mbhc_detect_plug_type(mbhc);
wcd9xxx_unlock_sleep(core_res);
}
static bool wcd9xxx_mbhc_fw_validate(const void *data, size_t size)
{
u32 cfg_offset;
struct wcd9xxx_mbhc_imped_detect_cfg *imped_cfg;
struct wcd9xxx_mbhc_btn_detect_cfg *btn_cfg;
struct firmware_cal fw;
fw.data = (void *)data;
fw.size = size;
if (fw.size < WCD9XXX_MBHC_CAL_MIN_SIZE)
return false;
/*
* Previous check guarantees that there is enough fw data up
* to num_btn
*/
btn_cfg = WCD9XXX_MBHC_CAL_BTN_DET_PTR(fw.data);
cfg_offset = (u32) ((void *) btn_cfg - (void *) fw.data);
if (fw.size < (cfg_offset + WCD9XXX_MBHC_CAL_BTN_SZ(btn_cfg)))
return false;
/*
* Previous check guarantees that there is enough fw data up
* to start of impedance detection configuration
*/
imped_cfg = WCD9XXX_MBHC_CAL_IMPED_DET_PTR(fw.data);
cfg_offset = (u32) ((void *) imped_cfg - (void *) fw.data);
if (fw.size < (cfg_offset + WCD9XXX_MBHC_CAL_IMPED_MIN_SZ))
return false;
if (fw.size < (cfg_offset + WCD9XXX_MBHC_CAL_IMPED_SZ(imped_cfg)))
return false;
return true;
}
static u16 wcd9xxx_codec_v_sta_dce(struct wcd9xxx_mbhc *mbhc,
enum meas_type dce, s16 vin_mv,
bool cs_enable)
{
s16 diff, zero;
u32 mb_mv, in;
u16 value;
s16 dce_z;
mb_mv = mbhc->mbhc_data.micb_mv;
dce_z = mbhc->mbhc_data.dce_z;
if (mb_mv == 0) {
pr_err("%s: Mic Bias voltage is set to zero\n", __func__);
return -EINVAL;
}
if (cs_enable) {
mb_mv = VDDIO_MICBIAS_MV;
dce_z = mbhc->mbhc_data.dce_nsc_cs_z;
}
if (dce) {
diff = (mbhc->mbhc_data.dce_mb) - (dce_z);
zero = (dce_z);
} else {
diff = (mbhc->mbhc_data.sta_mb) - (mbhc->mbhc_data.sta_z);
zero = (mbhc->mbhc_data.sta_z);
}
in = (u32) diff * vin_mv;
value = (u16) (in / mb_mv) + zero;
return value;
}
static void wcd9xxx_mbhc_calc_thres(struct wcd9xxx_mbhc *mbhc)
{
struct snd_soc_codec *codec;
s16 adj_v_hs_max;
s16 btn_mv = 0, btn_mv_sta[MBHC_V_IDX_NUM], btn_mv_dce[MBHC_V_IDX_NUM];
struct wcd9xxx_mbhc_btn_detect_cfg *btn_det;
struct wcd9xxx_mbhc_plug_type_cfg *plug_type;
u16 *btn_high;
int i;
pr_debug("%s: enter\n", __func__);
codec = mbhc->codec;
btn_det = WCD9XXX_MBHC_CAL_BTN_DET_PTR(mbhc->mbhc_cfg->calibration);
plug_type = WCD9XXX_MBHC_CAL_PLUG_TYPE_PTR(mbhc->mbhc_cfg->calibration);
mbhc->mbhc_data.v_ins_hu[MBHC_V_IDX_CFILT] =
wcd9xxx_codec_v_sta_dce(mbhc, STA, plug_type->v_hs_max, false);
mbhc->mbhc_data.v_ins_h[MBHC_V_IDX_CFILT] =
wcd9xxx_codec_v_sta_dce(mbhc, DCE, plug_type->v_hs_max, false);
mbhc->mbhc_data.v_inval_ins_low = FAKE_INS_LOW;
mbhc->mbhc_data.v_inval_ins_high = FAKE_INS_HIGH;
if (mbhc->mbhc_data.micb_mv != VDDIO_MICBIAS_MV) {
adj_v_hs_max = scale_v_micb_vddio(mbhc, plug_type->v_hs_max,
true);
mbhc->mbhc_data.v_ins_hu[MBHC_V_IDX_VDDIO] =
wcd9xxx_codec_v_sta_dce(mbhc, STA, adj_v_hs_max, false);
mbhc->mbhc_data.v_ins_h[MBHC_V_IDX_VDDIO] =
wcd9xxx_codec_v_sta_dce(mbhc, DCE, adj_v_hs_max, false);
mbhc->mbhc_data.v_inval_ins_low =
scale_v_micb_vddio(mbhc, mbhc->mbhc_data.v_inval_ins_low,
false);
mbhc->mbhc_data.v_inval_ins_high =
scale_v_micb_vddio(mbhc, mbhc->mbhc_data.v_inval_ins_high,
false);
}
mbhc->mbhc_data.v_cs_ins_h = wcd9xxx_codec_v_sta_dce(mbhc, DCE,
WCD9XXX_V_CS_HS_MAX,
true);
pr_debug("%s: v_ins_h for current source: 0x%x\n", __func__,
mbhc->mbhc_data.v_cs_ins_h);
btn_high = wcd9xxx_mbhc_cal_btn_det_mp(btn_det,
MBHC_BTN_DET_V_BTN_HIGH);
for (i = 0; i < btn_det->num_btn; i++)
btn_mv = btn_high[i] > btn_mv ? btn_high[i] : btn_mv;
btn_mv_sta[MBHC_V_IDX_CFILT] = btn_mv + btn_det->v_btn_press_delta_sta;
btn_mv_dce[MBHC_V_IDX_CFILT] = btn_mv + btn_det->v_btn_press_delta_cic;
btn_mv_sta[MBHC_V_IDX_VDDIO] =
scale_v_micb_vddio(mbhc, btn_mv_sta[MBHC_V_IDX_CFILT], true);
btn_mv_dce[MBHC_V_IDX_VDDIO] =
scale_v_micb_vddio(mbhc, btn_mv_dce[MBHC_V_IDX_CFILT], true);
mbhc->mbhc_data.v_b1_hu[MBHC_V_IDX_CFILT] =
wcd9xxx_codec_v_sta_dce(mbhc, STA, btn_mv_sta[MBHC_V_IDX_CFILT],
false);
mbhc->mbhc_data.v_b1_h[MBHC_V_IDX_CFILT] =
wcd9xxx_codec_v_sta_dce(mbhc, DCE, btn_mv_dce[MBHC_V_IDX_CFILT],
false);
mbhc->mbhc_data.v_b1_hu[MBHC_V_IDX_VDDIO] =
wcd9xxx_codec_v_sta_dce(mbhc, STA, btn_mv_sta[MBHC_V_IDX_VDDIO],
false);
mbhc->mbhc_data.v_b1_h[MBHC_V_IDX_VDDIO] =
wcd9xxx_codec_v_sta_dce(mbhc, DCE, btn_mv_dce[MBHC_V_IDX_VDDIO],
false);
mbhc->mbhc_data.v_brh[MBHC_V_IDX_CFILT] =
mbhc->mbhc_data.v_b1_h[MBHC_V_IDX_CFILT];
mbhc->mbhc_data.v_brh[MBHC_V_IDX_VDDIO] =
mbhc->mbhc_data.v_b1_h[MBHC_V_IDX_VDDIO];
mbhc->mbhc_data.v_brl = BUTTON_MIN;
mbhc->mbhc_data.v_no_mic =
wcd9xxx_codec_v_sta_dce(mbhc, STA, plug_type->v_no_mic, false);
pr_debug("%s: leave\n", __func__);
}
static void wcd9xxx_onoff_ext_mclk(struct wcd9xxx_mbhc *mbhc, bool on)
{
/*
* XXX: {codec}_mclk_enable holds WCD9XXX_BCL_LOCK,
* therefore wcd9xxx_onoff_ext_mclk caller SHOULDN'T hold
* WCD9XXX_BCL_LOCK when it calls wcd9xxx_onoff_ext_mclk()
*/
if (mbhc && mbhc->mbhc_cfg && mbhc->mbhc_cfg->mclk_cb_fn)
mbhc->mbhc_cfg->mclk_cb_fn(mbhc->codec, on, false);
}
/*
* Mic Bias Enable Decision
* Return true if high_hph_cnt is a power of 2 (!= 2)
* otherwise return false
*/
static bool wcd9xxx_mbhc_enable_mb_decision(int high_hph_cnt)
{
return (high_hph_cnt > 2) && !(high_hph_cnt & (high_hph_cnt - 1));
}
static inline void wcd9xxx_handle_gnd_mic_swap(struct wcd9xxx_mbhc *mbhc,
int pt_gnd_mic_swap_cnt,
enum wcd9xxx_mbhc_plug_type plug_type)
{
if (mbhc->mbhc_cfg->swap_gnd_mic &&
(pt_gnd_mic_swap_cnt == GND_MIC_SWAP_THRESHOLD)) {
/*
* if switch is toggled, check again,
* otherwise report unsupported plug
*/
mbhc->mbhc_cfg->swap_gnd_mic(mbhc->codec);
} else if (pt_gnd_mic_swap_cnt >= GND_MIC_SWAP_THRESHOLD) {
/* Report UNSUPPORTED plug
* and continue polling
*/
WCD9XXX_BCL_LOCK(mbhc->resmgr);
if (!mbhc->mbhc_cfg->detect_extn_cable) {
if (mbhc->current_plug == PLUG_TYPE_HEADPHONE)
wcd9xxx_report_plug(mbhc, 0,
SND_JACK_HEADPHONE);
else if (mbhc->current_plug == PLUG_TYPE_HEADSET)
wcd9xxx_report_plug(mbhc, 0,
SND_JACK_HEADSET);
}
if (mbhc->current_plug != plug_type)
wcd9xxx_report_plug(mbhc, 1,
SND_JACK_UNSUPPORTED);
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
}
}
static void wcd9xxx_correct_swch_plug(struct work_struct *work)
{
struct wcd9xxx_mbhc *mbhc;
struct snd_soc_codec *codec;
enum wcd9xxx_mbhc_plug_type plug_type = PLUG_TYPE_INVALID;
unsigned long timeout;
int retry = 0, pt_gnd_mic_swap_cnt = 0, invalid_cnt = 0;
int highhph_cnt = 0;
bool correction = false;
bool current_source_enable;
bool wrk_complete = true, highhph = false;
pr_debug("%s: enter\n", __func__);
mbhc = container_of(work, struct wcd9xxx_mbhc, correct_plug_swch);
codec = mbhc->codec;
current_source_enable = (((mbhc->mbhc_cfg->cs_enable_flags &
(1 << MBHC_CS_ENABLE_POLLING)) != 0) &&
(!(snd_soc_read(codec,
mbhc->mbhc_bias_regs.ctl_reg) & 0x80)));
wcd9xxx_onoff_ext_mclk(mbhc, true);
/*
* Keep override on during entire plug type correction work.
*
* This is okay under the assumption that any switch irqs which use
* MBHC block cancel and sync this work so override is off again
* prior to switch interrupt handler's MBHC block usage.
* Also while this correction work is running, we can guarantee
* DAPM doesn't use any MBHC block as this work only runs with
* headphone detection.
*/
if (current_source_enable) {
WCD9XXX_BCL_LOCK(mbhc->resmgr);
wcd9xxx_turn_onoff_current_source(mbhc, &mbhc->mbhc_bias_regs,
true, false);
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
} else {
wcd9xxx_turn_onoff_override(mbhc, true);
}
timeout = jiffies + msecs_to_jiffies(HS_DETECT_PLUG_TIME_MS);
while (!time_after(jiffies, timeout)) {
++retry;
rmb();
if (mbhc->hs_detect_work_stop) {
wrk_complete = false;
pr_debug("%s: stop requested\n", __func__);
break;
}
msleep(HS_DETECT_PLUG_INERVAL_MS);
if (wcd9xxx_swch_level_remove(mbhc)) {
wrk_complete = false;
pr_debug("%s: Switch level is low\n", __func__);
break;
}
/* can race with removal interrupt */
WCD9XXX_BCL_LOCK(mbhc->resmgr);
if (current_source_enable)
#ifndef VENDOR_EDIT
/*wangdongdong@MultiMedia.AudioDrv,2015/05/27,modify for chinese headset detection*/
plug_type = wcd9xxx_codec_cs_get_plug_type(mbhc,
highhph);
#else
plug_type = wcd9xxx_codec_cs_get_plug_type(mbhc,true);
#endif
else
plug_type = wcd9xxx_codec_get_plug_type(mbhc, true);
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
pr_debug("%s: attempt(%d) current_plug(%d) new_plug(%d)\n",
__func__, retry, mbhc->current_plug, plug_type);
highhph_cnt = (plug_type == PLUG_TYPE_HIGH_HPH) ?
(highhph_cnt + 1) :
0;
highhph = wcd9xxx_mbhc_enable_mb_decision(highhph_cnt);
if (plug_type == PLUG_TYPE_INVALID) {
invalid_cnt++;
pr_debug("Invalid plug in attempt # %d count %d\n", retry,invalid_cnt);
if (!mbhc->mbhc_cfg->detect_extn_cable &&
retry == NUM_ATTEMPTS_TO_REPORT &&
mbhc->current_plug == PLUG_TYPE_NONE) {
WCD9XXX_BCL_LOCK(mbhc->resmgr);
wcd9xxx_report_plug(mbhc, 1,
SND_JACK_HEADPHONE);
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
} else if (invalid_cnt == NUM_TO_REPORT_INVALID) {
pr_debug("invalit_cnt = 10 report unsupported\n");
WCD9XXX_BCL_LOCK(mbhc->resmgr);
wcd9xxx_report_plug(mbhc, 1,
SND_JACK_UNSUPPORTED);
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
}
} else if (plug_type == PLUG_TYPE_HEADPHONE) {
pr_debug("Good headphone detected, continue polling\n");
WCD9XXX_BCL_LOCK(mbhc->resmgr);
if (mbhc->mbhc_cfg->detect_extn_cable) {
if (mbhc->current_plug != plug_type)
wcd9xxx_report_plug(mbhc, 1,
SND_JACK_HEADPHONE);
} else if (mbhc->current_plug == PLUG_TYPE_NONE) {
wcd9xxx_report_plug(mbhc, 1,
SND_JACK_HEADPHONE);
}
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
} else if (plug_type == PLUG_TYPE_HIGH_HPH) {
pr_debug("%s: High HPH detected, continue polling\n",
__func__);
WCD9XXX_BCL_LOCK(mbhc->resmgr);
if (mbhc->mbhc_cfg->detect_extn_cable) {
if (mbhc->current_plug != plug_type)
wcd9xxx_report_plug(mbhc, 1,
SND_JACK_LINEOUT);
} else if (mbhc->current_plug == PLUG_TYPE_NONE) {
wcd9xxx_report_plug(mbhc, 1,
SND_JACK_HEADPHONE);
}
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
} else {
if (plug_type == PLUG_TYPE_GND_MIC_SWAP) {
pt_gnd_mic_swap_cnt++;
if (pt_gnd_mic_swap_cnt >=
GND_MIC_SWAP_THRESHOLD)
wcd9xxx_handle_gnd_mic_swap(mbhc,
pt_gnd_mic_swap_cnt,
plug_type);
pr_debug("%s: unsupported HS detected, continue polling\n",
__func__);
continue;
} else {
pt_gnd_mic_swap_cnt = 0;
WCD9XXX_BCL_LOCK(mbhc->resmgr);
/* Turn off override/current source */
if (current_source_enable)
wcd9xxx_turn_onoff_current_source(mbhc,
&mbhc->mbhc_bias_regs,
false, false);
else
wcd9xxx_turn_onoff_override(mbhc,
false);
/*
* The valid plug also includes
* PLUG_TYPE_GND_MIC_SWAP
*/
wcd9xxx_find_plug_and_report(mbhc, plug_type);
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
pr_debug("Attempt %d found correct plug %d\n",
retry,
plug_type);
correction = true;
}
break;
}
}
highhph = false;
if (wrk_complete && plug_type == PLUG_TYPE_HIGH_HPH) {
pr_debug("%s: polling is done, still HPH, so enabling MIC trigger\n",
__func__);
WCD9XXX_BCL_LOCK(mbhc->resmgr);
wcd9xxx_find_plug_and_report(mbhc, plug_type);
highhph = true;
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
}
if (plug_type == PLUG_TYPE_HEADPHONE) {
if (mbhc->mbhc_cb && mbhc->mbhc_cb->hph_auto_pulldown_ctrl)
mbhc->mbhc_cb->hph_auto_pulldown_ctrl(codec, true);
}
if (!correction && current_source_enable) {
WCD9XXX_BCL_LOCK(mbhc->resmgr);
wcd9xxx_turn_onoff_current_source(mbhc, &mbhc->mbhc_bias_regs,
false, highhph);
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
} else if (!correction) {
wcd9xxx_turn_onoff_override(mbhc, false);
}
wcd9xxx_onoff_ext_mclk(mbhc, false);
if (mbhc->mbhc_cfg->detect_extn_cable) {
WCD9XXX_BCL_LOCK(mbhc->resmgr);
if ((mbhc->current_plug == PLUG_TYPE_HEADPHONE &&
wrk_complete) ||
mbhc->current_plug == PLUG_TYPE_GND_MIC_SWAP ||
mbhc->current_plug == PLUG_TYPE_INVALID ||
(plug_type == PLUG_TYPE_INVALID && wrk_complete)) {
/* Enable removal detection */
wcd9xxx_cleanup_hs_polling(mbhc);
wcd9xxx_enable_hs_detect(mbhc, 0, 0, false);
}
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
}
pr_debug("%s: leave current_plug(%d)\n", __func__, mbhc->current_plug);
/* unlock sleep */
wcd9xxx_unlock_sleep(mbhc->resmgr->core_res);
}
static void wcd9xxx_swch_irq_handler(struct wcd9xxx_mbhc *mbhc)
{
bool insert;
bool is_removed = false;
struct snd_soc_codec *codec = mbhc->codec;
pr_debug("%s: enter\n", __func__);
mbhc->in_swch_irq_handler = true;
/* Wait here for debounce time */
usleep_range(SWCH_IRQ_DEBOUNCE_TIME_US, SWCH_IRQ_DEBOUNCE_TIME_US +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
WCD9XXX_BCL_LOCK(mbhc->resmgr);
/* cancel pending button press */
if (wcd9xxx_cancel_btn_work(mbhc))
pr_debug("%s: button press is canceled\n", __func__);
insert = !wcd9xxx_swch_level_remove(mbhc);
pr_debug("%s: Current plug type %d, insert %d\n", __func__,
mbhc->current_plug, insert);
if ((mbhc->current_plug == PLUG_TYPE_NONE) && insert) {
mbhc->lpi_enabled = false;
wmb();
/* cancel detect plug */
wcd9xxx_cancel_hs_detect_plug(mbhc,
&mbhc->correct_plug_swch);
if ((mbhc->current_plug != PLUG_TYPE_NONE) &&
(mbhc->current_plug != PLUG_TYPE_HIGH_HPH) &&
!(snd_soc_read(codec, WCD9XXX_A_MBHC_INSERT_DETECT) &
(1 << 1))) {
pr_debug("%s: current plug: %d\n", __func__,
mbhc->current_plug);
goto exit;
}
/* Disable Mic Bias pull down and HPH Switch to GND */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 0x01,
0x00);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x01, 0x00);
wcd9xxx_mbhc_detect_plug_type(mbhc);
} else if ((mbhc->current_plug != PLUG_TYPE_NONE) && !insert) {
mbhc->lpi_enabled = false;
wmb();
/* cancel detect plug */
wcd9xxx_cancel_hs_detect_plug(mbhc,
&mbhc->correct_plug_swch);
if (mbhc->current_plug == PLUG_TYPE_HEADPHONE) {
wcd9xxx_report_plug(mbhc, 0, SND_JACK_HEADPHONE);
is_removed = true;
} else if (mbhc->current_plug == PLUG_TYPE_GND_MIC_SWAP) {
wcd9xxx_report_plug(mbhc, 0, SND_JACK_UNSUPPORTED);
is_removed = true;
} else if (mbhc->current_plug == PLUG_TYPE_HEADSET) {
wcd9xxx_pause_hs_polling(mbhc);
wcd9xxx_mbhc_ctrl_clk_bandgap(mbhc, false);
wcd9xxx_cleanup_hs_polling(mbhc);
wcd9xxx_report_plug(mbhc, 0, SND_JACK_HEADSET);
is_removed = true;
} else if (mbhc->current_plug == PLUG_TYPE_HIGH_HPH) {
wcd9xxx_report_plug(mbhc, 0, SND_JACK_LINEOUT);
is_removed = true;
} else if (mbhc->current_plug == PLUG_TYPE_ANC_HEADPHONE) {
wcd9xxx_pause_hs_polling(mbhc);
wcd9xxx_mbhc_ctrl_clk_bandgap(mbhc, false);
wcd9xxx_cleanup_hs_polling(mbhc);
wcd9xxx_report_plug(mbhc, 0, SND_JACK_ANC_HEADPHONE);
is_removed = true;
}
if (is_removed) {
snd_soc_write(codec, WCD9XXX_A_MBHC_SCALING_MUX_1,
0x00);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL,
0x02, 0x00);
/* Enable Mic Bias pull down and HPH Switch to GND */
snd_soc_update_bits(codec,
mbhc->mbhc_bias_regs.ctl_reg, 0x01,
0x01);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x01,
0x01);
/* Make sure mic trigger is turned off */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg,
0x01, 0x01);
snd_soc_update_bits(codec,
mbhc->mbhc_bias_regs.mbhc_reg,
0x90, 0x00);
/* Reset MBHC State Machine */
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL,
0x08, 0x08);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL,
0x08, 0x00);
/* Turn off override */
wcd9xxx_turn_onoff_override(mbhc, false);
}
}
exit:
mbhc->in_swch_irq_handler = false;
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
pr_debug("%s: leave\n", __func__);
}
static irqreturn_t wcd9xxx_mech_plug_detect_irq(int irq, void *data)
{
int r = IRQ_HANDLED;
struct wcd9xxx_mbhc *mbhc = data;
pr_debug("%s: enter\n", __func__);
if (unlikely(wcd9xxx_lock_sleep(mbhc->resmgr->core_res) == false)) {
pr_warn("%s: failed to hold suspend\n", __func__);
r = IRQ_NONE;
} else {
/* Call handler */
wcd9xxx_swch_irq_handler(mbhc);
wcd9xxx_unlock_sleep(mbhc->resmgr->core_res);
}
pr_debug("%s: leave %d\n", __func__, r);
return r;
}
static int wcd9xxx_is_false_press(struct wcd9xxx_mbhc *mbhc)
{
s16 mb_v;
int i = 0;
int r = 0;
const s16 v_ins_hu =
wcd9xxx_get_current_v(mbhc, WCD9XXX_CURRENT_V_INS_HU);
const s16 v_ins_h =
wcd9xxx_get_current_v(mbhc, WCD9XXX_CURRENT_V_INS_H);
const s16 v_b1_hu =
wcd9xxx_get_current_v(mbhc, WCD9XXX_CURRENT_V_B1_HU);
const s16 v_b1_h =
wcd9xxx_get_current_v(mbhc, WCD9XXX_CURRENT_V_B1_H);
const unsigned long timeout =
jiffies + msecs_to_jiffies(BTN_RELEASE_DEBOUNCE_TIME_MS);
while (time_before(jiffies, timeout)) {
/*
* This function needs to run measurements just few times during
* release debounce time. Make 1ms interval to avoid
* unnecessary excessive measurements.
*/
usleep_range(1000, 1000 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
if (i == 0) {
mb_v = wcd9xxx_codec_sta_dce(mbhc, 0, true);
pr_debug("%s: STA[0]: %d,%d\n", __func__, mb_v,
wcd9xxx_codec_sta_dce_v(mbhc, 0, mb_v));
if (mb_v < v_b1_hu || mb_v > v_ins_hu) {
r = 1;
break;
}
} else {
mb_v = wcd9xxx_codec_sta_dce(mbhc, 1, true);
pr_debug("%s: DCE[%d]: %d,%d\n", __func__, i, mb_v,
wcd9xxx_codec_sta_dce_v(mbhc, 1, mb_v));
if (mb_v < v_b1_h || mb_v > v_ins_h) {
r = 1;
break;
}
}
i++;
}
return r;
}
/* called under codec_resource_lock acquisition */
static int wcd9xxx_determine_button(const struct wcd9xxx_mbhc *mbhc,
const s32 micmv)
{
s16 *v_btn_low, *v_btn_high;
struct wcd9xxx_mbhc_btn_detect_cfg *btn_det;
int i, btn = -1;
btn_det = WCD9XXX_MBHC_CAL_BTN_DET_PTR(mbhc->mbhc_cfg->calibration);
v_btn_low = wcd9xxx_mbhc_cal_btn_det_mp(btn_det,
MBHC_BTN_DET_V_BTN_LOW);
v_btn_high = wcd9xxx_mbhc_cal_btn_det_mp(btn_det,
MBHC_BTN_DET_V_BTN_HIGH);
for (i = 0; i < btn_det->num_btn; i++) {
if ((v_btn_low[i] <= micmv) && (v_btn_high[i] >= micmv)) {
btn = i;
break;
}
}
if (btn == -1)
pr_debug("%s: couldn't find button number for mic mv %d\n",
__func__, micmv);
return btn;
}
static int wcd9xxx_get_button_mask(const int btn)
{
int mask = 0;
switch (btn) {
case 0:
mask = SND_JACK_BTN_0;
break;
case 1:
mask = SND_JACK_BTN_1;
break;
case 2:
mask = SND_JACK_BTN_2;
break;
case 3:
mask = SND_JACK_BTN_3;
break;
case 4:
mask = SND_JACK_BTN_4;
break;
case 5:
mask = SND_JACK_BTN_5;
break;
case 6:
mask = SND_JACK_BTN_6;
break;
case 7:
mask = SND_JACK_BTN_7;
break;
}
return mask;
}
static void wcd9xxx_get_z(struct wcd9xxx_mbhc *mbhc, s16 *dce_z, s16 *sta_z,
struct mbhc_micbias_regs *micb_regs,
bool norel_detection)
{
s16 reg0, reg1;
int change;
struct snd_soc_codec *codec = mbhc->codec;
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
/* Pull down micbias to ground and disconnect vddio switch */
reg0 = snd_soc_read(codec, micb_regs->ctl_reg);
snd_soc_update_bits(codec, micb_regs->ctl_reg, 0x81, 0x1);
reg1 = snd_soc_read(codec, micb_regs->mbhc_reg);
snd_soc_update_bits(codec, micb_regs->mbhc_reg, 1 << 7, 0);
/* Disconnect override from micbias */
change = snd_soc_update_bits(codec, WCD9XXX_A_MAD_ANA_CTRL, 1 << 4,
1 << 0);
usleep_range(1000, 1000 + 1000);
if (sta_z) {
*sta_z = wcd9xxx_codec_sta_dce(mbhc, 0, norel_detection);
pr_debug("%s: sta_z 0x%x\n", __func__, *sta_z & 0xFFFF);
}
if (dce_z) {
*dce_z = wcd9xxx_codec_sta_dce(mbhc, 1, norel_detection);
pr_debug("%s: dce_z 0x%x\n", __func__, *dce_z & 0xFFFF);
}
/* Connect override from micbias */
if (change)
snd_soc_update_bits(codec, WCD9XXX_A_MAD_ANA_CTRL, 1 << 4,
1 << 4);
/* Disable pull down micbias to ground */
snd_soc_write(codec, micb_regs->mbhc_reg, reg1);
snd_soc_write(codec, micb_regs->ctl_reg, reg0);
}
/*
* This function recalibrates dce_z and sta_z parameters.
* No release detection will be false when this function is
* used.
*/
void wcd9xxx_update_z(struct wcd9xxx_mbhc *mbhc)
{
const u16 sta_z = mbhc->mbhc_data.sta_z;
const u16 dce_z = mbhc->mbhc_data.dce_z;
wcd9xxx_get_z(mbhc, &mbhc->mbhc_data.dce_z, &mbhc->mbhc_data.sta_z,
&mbhc->mbhc_bias_regs, false);
pr_debug("%s: sta_z 0x%x,dce_z 0x%x -> sta_z 0x%x,dce_z 0x%x\n",
__func__, sta_z & 0xFFFF, dce_z & 0xFFFF,
mbhc->mbhc_data.sta_z & 0xFFFF,
mbhc->mbhc_data.dce_z & 0xFFFF);
wcd9xxx_mbhc_calc_thres(mbhc);
wcd9xxx_calibrate_hs_polling(mbhc);
}
/*
* wcd9xxx_update_rel_threshold : update mbhc release upper bound threshold
* to ceilmv + buffer
*/
static int wcd9xxx_update_rel_threshold(struct wcd9xxx_mbhc *mbhc, int ceilmv,
bool vddio)
{
u16 v_brh, v_b1_hu;
int mv;
struct wcd9xxx_mbhc_btn_detect_cfg *btn_det;
void *calibration = mbhc->mbhc_cfg->calibration;
struct snd_soc_codec *codec = mbhc->codec;
btn_det = WCD9XXX_MBHC_CAL_BTN_DET_PTR(calibration);
mv = ceilmv + btn_det->v_btn_press_delta_cic;
if (vddio)
mv = scale_v_micb_vddio(mbhc, mv, true);
pr_debug("%s: reprogram vb1hu/vbrh to %dmv\n", __func__, mv);
if (mbhc->mbhc_state != MBHC_STATE_POTENTIAL_RECOVERY) {
/*
* update LSB first so mbhc hardware block
* doesn't see too low value.
*/
v_b1_hu = wcd9xxx_codec_v_sta_dce(mbhc, STA, mv, false);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B3_CTL, v_b1_hu &
0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B4_CTL,
(v_b1_hu >> 8) & 0xFF);
v_brh = wcd9xxx_codec_v_sta_dce(mbhc, DCE, mv, false);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B9_CTL, v_brh &
0xFF);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_VOLT_B10_CTL,
(v_brh >> 8) & 0xFF);
}
return 0;
}
irqreturn_t wcd9xxx_dce_handler(int irq, void *data)
{
int i, mask;
bool vddio;
u8 mbhc_status;
s16 dce_z, sta_z;
s32 stamv, stamv_s;
s16 *v_btn_high;
struct wcd9xxx_mbhc_btn_detect_cfg *btn_det;
int btn = -1, meas = 0;
struct wcd9xxx_mbhc *mbhc = data;
const struct wcd9xxx_mbhc_btn_detect_cfg *d =
WCD9XXX_MBHC_CAL_BTN_DET_PTR(mbhc->mbhc_cfg->calibration);
short btnmeas[d->n_btn_meas + 1];
short dce[d->n_btn_meas + 1], sta;
s32 mv[d->n_btn_meas + 1], mv_s[d->n_btn_meas + 1];
struct snd_soc_codec *codec = mbhc->codec;
struct wcd9xxx_core_resource *core_res = mbhc->resmgr->core_res;
int n_btn_meas = d->n_btn_meas;
void *calibration = mbhc->mbhc_cfg->calibration;
pr_debug("%s: enter\n", __func__);
WCD9XXX_BCL_LOCK(mbhc->resmgr);
mutex_lock(&mbhc->mbhc_lock);
mbhc_status = snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_B1_STATUS) & 0x3E;
if (mbhc->mbhc_state == MBHC_STATE_POTENTIAL_RECOVERY) {
pr_debug("%s: mbhc is being recovered, skip button press\n",
__func__);
goto done;
}
mbhc->mbhc_state = MBHC_STATE_POTENTIAL;
if (!mbhc->polling_active) {
pr_warn("%s: mbhc polling is not active, skip button press\n",
__func__);
goto done;
}
/* If switch nterrupt already kicked in, ignore button press */
if (mbhc->in_swch_irq_handler) {
pr_debug("%s: Swtich level changed, ignore button press\n",
__func__);
btn = -1;
goto done;
}
/*
* setup internal micbias if codec uses internal micbias for
* headset detection
*/
if (mbhc->mbhc_cfg->use_int_rbias) {
if (mbhc->mbhc_cb && mbhc->mbhc_cb->setup_int_rbias)
mbhc->mbhc_cb->setup_int_rbias(codec, true);
else
pr_err("%s: internal bias requested but codec did not provide callback\n",
__func__);
}
/* Measure scaled HW DCE */
vddio = (mbhc->mbhc_data.micb_mv != VDDIO_MICBIAS_MV &&
mbhc->mbhc_micbias_switched);
dce_z = mbhc->mbhc_data.dce_z;
sta_z = mbhc->mbhc_data.sta_z;
/* Measure scaled HW STA */
dce[0] = wcd9xxx_read_dce_result(codec);
sta = wcd9xxx_read_sta_result(codec);
if (mbhc_status != STATUS_REL_DETECTION) {
if (mbhc->mbhc_last_resume &&
!time_after(jiffies, mbhc->mbhc_last_resume + HZ)) {
pr_debug("%s: Button is released after resume\n",
__func__);
n_btn_meas = 0;
} else {
pr_debug("%s: Button is released without resume",
__func__);
if (mbhc->update_z) {
wcd9xxx_update_z(mbhc);
dce_z = mbhc->mbhc_data.dce_z;
sta_z = mbhc->mbhc_data.sta_z;
mbhc->update_z = true;
}
stamv = __wcd9xxx_codec_sta_dce_v(mbhc, 0, sta, sta_z,
mbhc->mbhc_data.micb_mv);
if (vddio)
stamv_s = scale_v_micb_vddio(mbhc, stamv,
false);
else
stamv_s = stamv;
mv[0] = __wcd9xxx_codec_sta_dce_v(mbhc, 1, dce[0],
dce_z, mbhc->mbhc_data.micb_mv);
mv_s[0] = vddio ? scale_v_micb_vddio(mbhc, mv[0],
false) : mv[0];
btn = wcd9xxx_determine_button(mbhc, mv_s[0]);
if (btn != wcd9xxx_determine_button(mbhc, stamv_s))
btn = -1;
goto done;
}
}
for (meas = 1; ((d->n_btn_meas) && (meas < (d->n_btn_meas + 1)));
meas++)
dce[meas] = wcd9xxx_codec_sta_dce(mbhc, 1, false);
if (mbhc->update_z) {
wcd9xxx_update_z(mbhc);
dce_z = mbhc->mbhc_data.dce_z;
sta_z = mbhc->mbhc_data.sta_z;
mbhc->update_z = true;
}
stamv = __wcd9xxx_codec_sta_dce_v(mbhc, 0, sta, sta_z,
mbhc->mbhc_data.micb_mv);
if (vddio)
stamv_s = scale_v_micb_vddio(mbhc, stamv, false);
else
stamv_s = stamv;
pr_debug("%s: Meas HW - STA 0x%x,%d,%d\n", __func__,
sta & 0xFFFF, stamv, stamv_s);
/* determine pressed button */
mv[0] = __wcd9xxx_codec_sta_dce_v(mbhc, 1, dce[0], dce_z,
mbhc->mbhc_data.micb_mv);
mv_s[0] = vddio ? scale_v_micb_vddio(mbhc, mv[0], false) : mv[0];
btnmeas[0] = wcd9xxx_determine_button(mbhc, mv_s[0]);
pr_debug("%s: Meas HW - DCE 0x%x,%d,%d button %d\n", __func__,
dce[0] & 0xFFFF, mv[0], mv_s[0], btnmeas[0]);
if (n_btn_meas == 0)
btn = btnmeas[0];
for (meas = 1; (n_btn_meas && d->n_btn_meas &&
(meas < (d->n_btn_meas + 1))); meas++) {
mv[meas] = __wcd9xxx_codec_sta_dce_v(mbhc, 1, dce[meas], dce_z,
mbhc->mbhc_data.micb_mv);
mv_s[meas] = vddio ? scale_v_micb_vddio(mbhc, mv[meas], false) :
mv[meas];
btnmeas[meas] = wcd9xxx_determine_button(mbhc, mv_s[meas]);
pr_debug("%s: Meas %d - DCE 0x%x,%d,%d button %d\n",
__func__, meas, dce[meas] & 0xFFFF, mv[meas],
mv_s[meas], btnmeas[meas]);
/*
* if large enough measurements are collected,
* start to check if last all n_btn_con measurements were
* in same button low/high range
*/
if (meas + 1 >= d->n_btn_con) {
for (i = 0; i < d->n_btn_con; i++)
if ((btnmeas[meas] < 0) ||
(btnmeas[meas] != btnmeas[meas - i]))
break;
if (i == d->n_btn_con) {
/* button pressed */
btn = btnmeas[meas];
break;
} else if ((n_btn_meas - meas) < (d->n_btn_con - 1)) {
/*
* if left measurements are less than n_btn_con,
* it's impossible to find button number
*/
break;
}
}
}
if (btn >= 0) {
if (mbhc->in_swch_irq_handler) {
pr_debug(
"%s: Switch irq triggered, ignore button press\n",
__func__);
goto done;
}
btn_det = WCD9XXX_MBHC_CAL_BTN_DET_PTR(calibration);
v_btn_high = wcd9xxx_mbhc_cal_btn_det_mp(btn_det,
MBHC_BTN_DET_V_BTN_HIGH);
WARN_ON(btn >= btn_det->num_btn);
/* reprogram release threshold to catch voltage ramp up early */
wcd9xxx_update_rel_threshold(mbhc, v_btn_high[btn], vddio);
mask = wcd9xxx_get_button_mask(btn);
mbhc->buttons_pressed |= mask;
wcd9xxx_lock_sleep(core_res);
if (schedule_delayed_work(&mbhc->mbhc_btn_dwork,
msecs_to_jiffies(400)) == 0) {
WARN(1, "Button pressed twice without release event\n");
wcd9xxx_unlock_sleep(core_res);
}
} else {
pr_debug("%s: bogus button press, too short press?\n",
__func__);
}
done:
pr_debug("%s: leave\n", __func__);
mutex_unlock(&mbhc->mbhc_lock);
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
return IRQ_HANDLED;
}
static irqreturn_t wcd9xxx_release_handler(int irq, void *data)
{
int ret;
bool waitdebounce = true;
struct wcd9xxx_mbhc *mbhc = data;
pr_debug("%s: enter\n", __func__);
WCD9XXX_BCL_LOCK(mbhc->resmgr);
mbhc->mbhc_state = MBHC_STATE_RELEASE;
if (mbhc->buttons_pressed & WCD9XXX_JACK_BUTTON_MASK) {
ret = wcd9xxx_cancel_btn_work(mbhc);
if (ret == 0) {
pr_debug("%s: Reporting long button release event\n",
__func__);
wcd9xxx_jack_report(mbhc, &mbhc->button_jack, 0,
mbhc->buttons_pressed);
} else {
if (wcd9xxx_is_false_press(mbhc)) {
pr_debug("%s: Fake button press interrupt\n",
__func__);
} else {
if (mbhc->in_swch_irq_handler) {
pr_debug("%s: Switch irq kicked in, ignore\n",
__func__);
} else {
pr_debug("%s: Reporting btn press\n",
__func__);
wcd9xxx_jack_report(mbhc,
&mbhc->button_jack,
mbhc->buttons_pressed,
mbhc->buttons_pressed);
pr_debug("%s: Reporting btn release\n",
__func__);
wcd9xxx_jack_report(mbhc,
&mbhc->button_jack,
0, mbhc->buttons_pressed);
waitdebounce = false;
}
}
}
mbhc->buttons_pressed &= ~WCD9XXX_JACK_BUTTON_MASK;
}
wcd9xxx_calibrate_hs_polling(mbhc);
if (waitdebounce)
msleep(SWCH_REL_DEBOUNCE_TIME_MS);
wcd9xxx_start_hs_polling(mbhc);
pr_debug("%s: leave\n", __func__);
WCD9XXX_BCL_UNLOCK(mbhc->resmgr);
return IRQ_HANDLED;
}
static irqreturn_t wcd9xxx_hphl_ocp_irq(int irq, void *data)
{
struct wcd9xxx_mbhc *mbhc = data;
struct snd_soc_codec *codec;
pr_info("%s: received HPHL OCP irq\n", __func__);
if (mbhc) {
codec = mbhc->codec;
if ((mbhc->hphlocp_cnt < OCP_ATTEMPT) &&
(!mbhc->hphrocp_cnt)) {
pr_info("%s: retry\n", __func__);
mbhc->hphlocp_cnt++;
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_OCP_CTL,
0x10, 0x00);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_OCP_CTL,
0x10, 0x10);
} else {
wcd9xxx_disable_irq(mbhc->resmgr->core_res,
mbhc->intr_ids->hph_left_ocp);
mbhc->hph_status |= SND_JACK_OC_HPHL;
wcd9xxx_jack_report(mbhc, &mbhc->headset_jack,
mbhc->hph_status,
WCD9XXX_JACK_MASK);
}
} else {
pr_err("%s: Bad wcd9xxx private data\n", __func__);
}
return IRQ_HANDLED;
}
static irqreturn_t wcd9xxx_hphr_ocp_irq(int irq, void *data)
{
struct wcd9xxx_mbhc *mbhc = data;
struct snd_soc_codec *codec;
pr_info("%s: received HPHR OCP irq\n", __func__);
codec = mbhc->codec;
if ((mbhc->hphrocp_cnt < OCP_ATTEMPT) &&
(!mbhc->hphlocp_cnt)) {
pr_info("%s: retry\n", __func__);
mbhc->hphrocp_cnt++;
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_OCP_CTL, 0x10,
0x00);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_OCP_CTL, 0x10,
0x10);
} else {
wcd9xxx_disable_irq(mbhc->resmgr->core_res,
mbhc->intr_ids->hph_right_ocp);
mbhc->hph_status |= SND_JACK_OC_HPHR;
wcd9xxx_jack_report(mbhc, &mbhc->headset_jack,
mbhc->hph_status, WCD9XXX_JACK_MASK);
}
return IRQ_HANDLED;
}
static int wcd9xxx_acdb_mclk_index(const int rate)
{
if (rate == MCLK_RATE_12288KHZ)
return 0;
else if (rate == MCLK_RATE_9600KHZ)
return 1;
else {
BUG_ON(1);
return -EINVAL;
}
}
static void wcd9xxx_update_mbhc_clk_rate(struct wcd9xxx_mbhc *mbhc, u32 rate)
{
u32 dce_wait, sta_wait;
u8 ncic, nmeas, navg;
void *calibration;
u8 *n_cic, *n_ready;
struct wcd9xxx_mbhc_btn_detect_cfg *btn_det;
u8 npoll = 4, nbounce_wait = 30;
struct snd_soc_codec *codec = mbhc->codec;
int idx = wcd9xxx_acdb_mclk_index(rate);
int idxmclk = wcd9xxx_acdb_mclk_index(mbhc->mbhc_cfg->mclk_rate);
pr_debug("%s: Updating clock rate dependents, rate = %u\n", __func__,
rate);
calibration = mbhc->mbhc_cfg->calibration;
/*
* First compute the DCE / STA wait times depending on tunable
* parameters. The value is computed in microseconds
*/
btn_det = WCD9XXX_MBHC_CAL_BTN_DET_PTR(calibration);
n_ready = wcd9xxx_mbhc_cal_btn_det_mp(btn_det, MBHC_BTN_DET_N_READY);
n_cic = wcd9xxx_mbhc_cal_btn_det_mp(btn_det, MBHC_BTN_DET_N_CIC);
nmeas = WCD9XXX_MBHC_CAL_BTN_DET_PTR(calibration)->n_meas;
navg = WCD9XXX_MBHC_CAL_GENERAL_PTR(calibration)->mbhc_navg;
/* ncic stays with the same what we had during calibration */
ncic = n_cic[idxmclk];
dce_wait = (1000 * 512 * ncic * (nmeas + 1)) / (rate / 1000);
sta_wait = (1000 * 128 * (navg + 1)) / (rate / 1000);
mbhc->mbhc_data.t_dce = dce_wait;
/* give extra margin to sta for safety */
mbhc->mbhc_data.t_sta = sta_wait + 250;
mbhc->mbhc_data.t_sta_dce = ((1000 * 256) / (rate / 1000) *
n_ready[idx]) + 10;
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_TIMER_B1_CTL, n_ready[idx]);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_TIMER_B6_CTL, ncic);
if (rate == MCLK_RATE_12288KHZ) {
npoll = 4;
nbounce_wait = 30;
} else if (rate == MCLK_RATE_9600KHZ) {
npoll = 3;
nbounce_wait = 23;
}
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_TIMER_B2_CTL, npoll);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_TIMER_B3_CTL, nbounce_wait);
pr_debug("%s: leave\n", __func__);
}
static void wcd9xxx_mbhc_cal(struct wcd9xxx_mbhc *mbhc)
{
u8 cfilt_mode;
u16 reg0, reg1, reg2;
struct snd_soc_codec *codec = mbhc->codec;
pr_debug("%s: enter\n", __func__);
wcd9xxx_disable_irq(mbhc->resmgr->core_res,
mbhc->intr_ids->dce_est_complete);
wcd9xxx_turn_onoff_rel_detection(codec, false);
/* t_dce and t_sta are updated by wcd9xxx_update_mbhc_clk_rate() */
WARN_ON(!mbhc->mbhc_data.t_dce);
WARN_ON(!mbhc->mbhc_data.t_sta);
/*
* LDOH and CFILT are already configured during pdata handling.
* Only need to make sure CFILT and bandgap are in Fast mode.
* Need to restore defaults once calculation is done.
*
* In case when Micbias is powered by external source, request
* turn on the external voltage source for Calibration.
*/
if (mbhc->mbhc_cb && mbhc->mbhc_cb->enable_mb_source)
mbhc->mbhc_cb->enable_mb_source(codec, true, false);
cfilt_mode = snd_soc_read(codec, mbhc->mbhc_bias_regs.cfilt_ctl);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->cfilt_fast_mode)
mbhc->mbhc_cb->cfilt_fast_mode(codec, mbhc);
else
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.cfilt_ctl,
0x40, 0x00);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->micbias_pulldown_ctrl)
mbhc->mbhc_cb->micbias_pulldown_ctrl(mbhc, false);
/*
* Micbias, CFILT, LDOH, MBHC MUX mode settings
* to perform ADC calibration
*/
if (mbhc->mbhc_cb && mbhc->mbhc_cb->select_cfilt)
mbhc->mbhc_cb->select_cfilt(codec, mbhc);
else
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 0x60,
mbhc->mbhc_cfg->micbias << 5);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 0x01, 0x00);
snd_soc_update_bits(codec, WCD9XXX_A_LDO_H_MODE_1, 0x60, 0x60);
snd_soc_write(codec, WCD9XXX_A_TX_7_MBHC_TEST_CTL, 0x78);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->codec_specific_cal)
mbhc->mbhc_cb->codec_specific_cal(codec, mbhc);
else
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL,
0x04, 0x04);
/* Pull down micbias to ground */
reg0 = snd_soc_read(codec, mbhc->mbhc_bias_regs.ctl_reg);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 1, 1);
/* Disconnect override from micbias */
reg1 = snd_soc_read(codec, WCD9XXX_A_MAD_ANA_CTRL);
snd_soc_update_bits(codec, WCD9XXX_A_MAD_ANA_CTRL, 1 << 4, 1 << 0);
/* Connect the MUX to micbias */
snd_soc_write(codec, WCD9XXX_A_MBHC_SCALING_MUX_1, 0x02);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->enable_mux_bias_block)
mbhc->mbhc_cb->enable_mux_bias_block(codec);
else
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1,
0x80, 0x80);
/*
* Hardware that has external cap can delay mic bias ramping down up
* to 50ms.
*/
msleep(WCD9XXX_MUX_SWITCH_READY_WAIT_MS);
/* DCE measurement for 0 voltage */
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x0A);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x02);
mbhc->mbhc_data.dce_z = __wcd9xxx_codec_sta_dce(mbhc, 1, true, false);
/* compute dce_z for current source */
reg2 = snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_B1_CTL);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x78,
WCD9XXX_MBHC_NSC_CS << 3);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x0A);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x02);
mbhc->mbhc_data.dce_nsc_cs_z = __wcd9xxx_codec_sta_dce(mbhc, 1, true,
false);
pr_debug("%s: dce_z with nsc cs: 0x%x\n", __func__,
mbhc->mbhc_data.dce_nsc_cs_z);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, reg2);
/* STA measurement for 0 voltage */
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x0A);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x02);
mbhc->mbhc_data.sta_z = __wcd9xxx_codec_sta_dce(mbhc, 0, true, false);
/* Restore registers */
snd_soc_write(codec, mbhc->mbhc_bias_regs.ctl_reg, reg0);
snd_soc_write(codec, WCD9XXX_A_MAD_ANA_CTRL, reg1);
/* DCE measurment for MB voltage */
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x0A);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x02);
snd_soc_write(codec, WCD9XXX_A_MBHC_SCALING_MUX_1, 0x02);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->enable_mux_bias_block)
mbhc->mbhc_cb->enable_mux_bias_block(codec);
else
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1,
0x80, 0x80);
/*
* Hardware that has external cap can delay mic bias ramping down up
* to 50ms.
*/
msleep(WCD9XXX_MUX_SWITCH_READY_WAIT_MS);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x04);
usleep_range(mbhc->mbhc_data.t_dce, mbhc->mbhc_data.t_dce +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
mbhc->mbhc_data.dce_mb = wcd9xxx_read_dce_result(codec);
/* STA Measurement for MB Voltage */
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x0A);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x02);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_CLK_CTL, 0x02);
snd_soc_write(codec, WCD9XXX_A_MBHC_SCALING_MUX_1, 0x02);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->enable_mux_bias_block)
mbhc->mbhc_cb->enable_mux_bias_block(codec);
else
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1,
0x80, 0x80);
/*
* Hardware that has external cap can delay mic bias ramping down up
* to 50ms.
*/
msleep(WCD9XXX_MUX_SWITCH_READY_WAIT_MS);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x02);
usleep_range(mbhc->mbhc_data.t_sta, mbhc->mbhc_data.t_sta +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
mbhc->mbhc_data.sta_mb = wcd9xxx_read_sta_result(codec);
/* Restore default settings. */
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x04, 0x00);
snd_soc_write(codec, mbhc->mbhc_bias_regs.cfilt_ctl, cfilt_mode);
snd_soc_write(codec, WCD9XXX_A_MBHC_SCALING_MUX_1, 0x04);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->enable_mux_bias_block)
mbhc->mbhc_cb->enable_mux_bias_block(codec);
else
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1,
0x80, 0x80);
usleep_range(100, 110);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->enable_mb_source)
mbhc->mbhc_cb->enable_mb_source(codec, false, false);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->micbias_pulldown_ctrl)
mbhc->mbhc_cb->micbias_pulldown_ctrl(mbhc, true);
wcd9xxx_enable_irq(mbhc->resmgr->core_res,
mbhc->intr_ids->dce_est_complete);
wcd9xxx_turn_onoff_rel_detection(codec, true);
pr_debug("%s: leave\n", __func__);
}
static void wcd9xxx_mbhc_setup(struct wcd9xxx_mbhc *mbhc)
{
int n;
u8 *gain;
struct wcd9xxx_mbhc_general_cfg *generic;
struct wcd9xxx_mbhc_btn_detect_cfg *btn_det;
struct snd_soc_codec *codec = mbhc->codec;
const int idx = wcd9xxx_acdb_mclk_index(mbhc->mbhc_cfg->mclk_rate);
pr_debug("%s: enter\n", __func__);
generic = WCD9XXX_MBHC_CAL_GENERAL_PTR(mbhc->mbhc_cfg->calibration);
btn_det = WCD9XXX_MBHC_CAL_BTN_DET_PTR(mbhc->mbhc_cfg->calibration);
for (n = 0; n < 8; n++) {
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_FIR_B1_CFG,
0x07, n);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_FIR_B2_CFG,
btn_det->c[n]);
}
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B2_CTL, 0x07,
btn_det->nc);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_TIMER_B4_CTL, 0x70,
generic->mbhc_nsa << 4);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_TIMER_B4_CTL, 0x0F,
btn_det->n_meas);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_TIMER_B5_CTL,
generic->mbhc_navg);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x80, 0x80);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x78,
btn_det->mbhc_nsc << 3);
if (mbhc->mbhc_cb && mbhc->mbhc_cb->get_cdc_type &&
mbhc->mbhc_cb->get_cdc_type() !=
WCD9XXX_CDC_TYPE_HELICON) {
if (mbhc->resmgr->reg_addr->micb_4_mbhc)
snd_soc_update_bits(codec,
mbhc->resmgr->reg_addr->micb_4_mbhc,
0x03, MBHC_MICBIAS2);
}
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL, 0x02, 0x02);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_2, 0xF0, 0xF0);
gain = wcd9xxx_mbhc_cal_btn_det_mp(btn_det, MBHC_BTN_DET_GAIN);
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B2_CTL, 0x78,
gain[idx] << 3);
snd_soc_update_bits(codec, WCD9XXX_A_MICB_2_MBHC, 0x04, 0x04);
pr_debug("%s: leave\n", __func__);
}
static int wcd9xxx_setup_jack_detect_irq(struct wcd9xxx_mbhc *mbhc)
{
int ret = 0;
void *core_res = mbhc->resmgr->core_res;
if (mbhc->mbhc_cfg->gpio) {
ret = request_threaded_irq(mbhc->mbhc_cfg->gpio_irq, NULL,
wcd9xxx_mech_plug_detect_irq,
(IRQF_TRIGGER_RISING |
IRQF_TRIGGER_FALLING |
IRQF_DISABLED),
"headset detect", mbhc);
if (ret) {
pr_err("%s: Failed to request gpio irq %d\n", __func__,
mbhc->mbhc_cfg->gpio_irq);
} else {
ret = enable_irq_wake(mbhc->mbhc_cfg->gpio_irq);
if (ret)
pr_err("%s: Failed to enable wake up irq %d\n",
__func__, mbhc->mbhc_cfg->gpio_irq);
}
} else if (mbhc->mbhc_cfg->insert_detect) {
/* Enable HPHL_10K_SW */
snd_soc_update_bits(mbhc->codec, WCD9XXX_A_RX_HPH_OCP_CTL,
1 << 1, 1 << 1);
ret = wcd9xxx_request_irq(core_res,
mbhc->intr_ids->hs_jack_switch,
wcd9xxx_mech_plug_detect_irq,
"Jack Detect",
mbhc);
if (ret)
pr_err("%s: Failed to request insert detect irq %d\n",
__func__, mbhc->intr_ids->hs_jack_switch);
}
return ret;
}
static int wcd9xxx_init_and_calibrate(struct wcd9xxx_mbhc *mbhc)
{
int ret = 0;
struct snd_soc_codec *codec = mbhc->codec;
pr_debug("%s: enter\n", __func__);
/* Enable MCLK during calibration */
wcd9xxx_onoff_ext_mclk(mbhc, true);
wcd9xxx_mbhc_setup(mbhc);
wcd9xxx_mbhc_cal(mbhc);
wcd9xxx_mbhc_calc_thres(mbhc);
wcd9xxx_onoff_ext_mclk(mbhc, false);
wcd9xxx_calibrate_hs_polling(mbhc);
/* Enable Mic Bias pull down and HPH Switch to GND */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 0x01, 0x01);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_HPH, 0x01, 0x01);
INIT_WORK(&mbhc->correct_plug_swch, wcd9xxx_correct_swch_plug);
if (!IS_ERR_VALUE(ret)) {
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_OCP_CTL, 0x10,
0x10);
wcd9xxx_enable_irq(mbhc->resmgr->core_res,
mbhc->intr_ids->hph_left_ocp);
wcd9xxx_enable_irq(mbhc->resmgr->core_res,
mbhc->intr_ids->hph_right_ocp);
/* Initialize mechanical mbhc */
ret = wcd9xxx_setup_jack_detect_irq(mbhc);
if (!ret && mbhc->mbhc_cfg->gpio) {
/* Requested with IRQF_DISABLED */
enable_irq(mbhc->mbhc_cfg->gpio_irq);
/* Bootup time detection */
wcd9xxx_swch_irq_handler(mbhc);
} else if (!ret && mbhc->mbhc_cfg->insert_detect) {
pr_debug("%s: Setting up codec own insert detection\n",
__func__);
/* Setup for insertion detection */
wcd9xxx_insert_detect_setup(mbhc, true);
}
}
pr_debug("%s: leave\n", __func__);
return ret;
}
static void wcd9xxx_mbhc_fw_read(struct work_struct *work)
{
struct delayed_work *dwork;
struct wcd9xxx_mbhc *mbhc;
struct snd_soc_codec *codec;
const struct firmware *fw;
struct firmware_cal *fw_data = NULL;
int ret = -1, retry = 0;
bool use_default_cal = false;
dwork = to_delayed_work(work);
mbhc = container_of(dwork, struct wcd9xxx_mbhc, mbhc_firmware_dwork);
codec = mbhc->codec;
while (retry < FW_READ_ATTEMPTS) {
retry++;
pr_info("%s:Attempt %d to request MBHC firmware\n",
__func__, retry);
if (mbhc->mbhc_cb->get_hwdep_fw_cal)
fw_data = mbhc->mbhc_cb->get_hwdep_fw_cal(codec,
WCD9XXX_MBHC_CAL);
if (!fw_data)
ret = request_firmware(&fw, "wcd9320/wcd9320_mbhc.bin",
codec->dev);
/*
* if request_firmware and hwdep cal both fail then
* retry for few times before bailing out
*/
if ((ret != 0) && !fw_data) {
usleep_range(FW_READ_TIMEOUT, FW_READ_TIMEOUT +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
} else {
pr_info("%s: MBHC Firmware read succesful\n",
__func__);
break;
}
}
if (!fw_data)
pr_info("%s: using request_firmware\n", __func__);
else
pr_info("%s: using hwdep cal\n", __func__);
if (ret != 0 && !fw_data) {
pr_err("%s: Cannot load MBHC firmware use default cal\n",
__func__);
use_default_cal = true;
}
if (!use_default_cal) {
const void *data;
size_t size;
if (fw_data) {
data = fw_data->data;
size = fw_data->size;
} else {
data = fw->data;
size = fw->size;
}
if (wcd9xxx_mbhc_fw_validate(data, size) == false) {
pr_err("%s: Invalid MBHC cal data size use default cal\n",
__func__);
if (!fw_data)
release_firmware(fw);
} else {
if (fw_data) {
mbhc->mbhc_cfg->calibration =
(void *)fw_data->data;
mbhc->mbhc_cal = fw_data;
} else {
mbhc->mbhc_cfg->calibration =
(void *)fw->data;
mbhc->mbhc_fw = fw;
}
}
}
(void) wcd9xxx_init_and_calibrate(mbhc);
}
#ifdef CONFIG_DEBUG_FS
ssize_t codec_mbhc_debug_read(struct file *file, char __user *buf,
size_t count, loff_t *pos)
{
const int size = 768;
char buffer[size];
int n = 0;
struct wcd9xxx_mbhc *mbhc = file->private_data;
const struct mbhc_internal_cal_data *p = &mbhc->mbhc_data;
const s16 v_ins_hu =
wcd9xxx_get_current_v(mbhc, WCD9XXX_CURRENT_V_INS_HU);
const s16 v_ins_h =
wcd9xxx_get_current_v(mbhc, WCD9XXX_CURRENT_V_INS_H);
const s16 v_b1_hu =
wcd9xxx_get_current_v(mbhc, WCD9XXX_CURRENT_V_B1_HU);
const s16 v_b1_h =
wcd9xxx_get_current_v(mbhc, WCD9XXX_CURRENT_V_B1_H);
const s16 v_br_h =
wcd9xxx_get_current_v(mbhc, WCD9XXX_CURRENT_V_BR_H);
n = scnprintf(buffer, size - n, "dce_z = %x(%dmv)\n",
p->dce_z, wcd9xxx_codec_sta_dce_v(mbhc, 1, p->dce_z));
n += scnprintf(buffer + n, size - n, "dce_mb = %x(%dmv)\n",
p->dce_mb, wcd9xxx_codec_sta_dce_v(mbhc, 1, p->dce_mb));
n += scnprintf(buffer + n, size - n, "dce_nsc_cs_z = %x(%dmv)\n",
p->dce_nsc_cs_z,
__wcd9xxx_codec_sta_dce_v(mbhc, 1, p->dce_nsc_cs_z,
p->dce_nsc_cs_z,
VDDIO_MICBIAS_MV));
n += scnprintf(buffer + n, size - n, "sta_z = %x(%dmv)\n",
p->sta_z, wcd9xxx_codec_sta_dce_v(mbhc, 0, p->sta_z));
n += scnprintf(buffer + n, size - n, "sta_mb = %x(%dmv)\n",
p->sta_mb, wcd9xxx_codec_sta_dce_v(mbhc, 0, p->sta_mb));
n += scnprintf(buffer + n, size - n, "t_dce = %d\n", p->t_dce);
n += scnprintf(buffer + n, size - n, "t_sta = %d\n", p->t_sta);
n += scnprintf(buffer + n, size - n, "micb_mv = %dmv\n", p->micb_mv);
n += scnprintf(buffer + n, size - n, "v_ins_hu = %x(%dmv)\n",
v_ins_hu, wcd9xxx_codec_sta_dce_v(mbhc, 0, v_ins_hu));
n += scnprintf(buffer + n, size - n, "v_ins_h = %x(%dmv)\n",
v_ins_h, wcd9xxx_codec_sta_dce_v(mbhc, 1, v_ins_h));
n += scnprintf(buffer + n, size - n, "v_b1_hu = %x(%dmv)\n",
v_b1_hu, wcd9xxx_codec_sta_dce_v(mbhc, 0, v_b1_hu));
n += scnprintf(buffer + n, size - n, "v_b1_h = %x(%dmv)\n",
v_b1_h, wcd9xxx_codec_sta_dce_v(mbhc, 1, v_b1_h));
n += scnprintf(buffer + n, size - n, "v_brh = %x(%dmv)\n",
v_br_h, wcd9xxx_codec_sta_dce_v(mbhc, 1, v_br_h));
n += scnprintf(buffer + n, size - n, "v_brl = %x(%dmv)\n", p->v_brl,
wcd9xxx_codec_sta_dce_v(mbhc, 0, p->v_brl));
n += scnprintf(buffer + n, size - n, "v_no_mic = %x(%dmv)\n",
p->v_no_mic,
wcd9xxx_codec_sta_dce_v(mbhc, 0, p->v_no_mic));
n += scnprintf(buffer + n, size - n, "v_inval_ins_low = %d\n",
p->v_inval_ins_low);
n += scnprintf(buffer + n, size - n, "v_inval_ins_high = %d\n",
p->v_inval_ins_high);
n += scnprintf(buffer + n, size - n, "Insert detect insert = %d\n",
!wcd9xxx_swch_level_remove(mbhc));
buffer[n] = 0;
return simple_read_from_buffer(buf, count, pos, buffer, n);
}
static int codec_debug_open(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static ssize_t codec_debug_write(struct file *filp,
const char __user *ubuf, size_t cnt,
loff_t *ppos)
{
char lbuf[32];
char *buf;
int rc;
struct wcd9xxx_mbhc *mbhc = filp->private_data;
if (cnt > sizeof(lbuf) - 1)
return -EINVAL;
rc = copy_from_user(lbuf, ubuf, cnt);
if (rc)
return -EFAULT;
lbuf[cnt] = '\0';
buf = (char *)lbuf;
mbhc->no_mic_headset_override = (*strsep(&buf, " ") == '0') ?
false : true;
return rc;
}
static const struct file_operations mbhc_trrs_debug_ops = {
.open = codec_debug_open,
.write = codec_debug_write,
};
static const struct file_operations mbhc_debug_ops = {
.open = codec_debug_open,
.read = codec_mbhc_debug_read,
};
static void wcd9xxx_init_debugfs(struct wcd9xxx_mbhc *mbhc)
{
mbhc->debugfs_poke =
debugfs_create_file("TRRS", S_IFREG | S_IRUGO, NULL, mbhc,
&mbhc_trrs_debug_ops);
mbhc->debugfs_mbhc =
debugfs_create_file("wcd9xxx_mbhc", S_IFREG | S_IRUGO,
NULL, mbhc, &mbhc_debug_ops);
}
static void wcd9xxx_cleanup_debugfs(struct wcd9xxx_mbhc *mbhc)
{
debugfs_remove(mbhc->debugfs_poke);
debugfs_remove(mbhc->debugfs_mbhc);
}
#else
static void wcd9xxx_init_debugfs(struct wcd9xxx_mbhc *mbhc)
{
}
static void wcd9xxx_cleanup_debugfs(struct wcd9xxx_mbhc *mbhc)
{
}
#endif
int wcd9xxx_mbhc_start(struct wcd9xxx_mbhc *mbhc,
struct wcd9xxx_mbhc_config *mbhc_cfg)
{
int rc = 0;
struct snd_soc_codec *codec = mbhc->codec;
pr_debug("%s: enter\n", __func__);
if (!codec) {
pr_err("%s: no codec\n", __func__);
return -EINVAL;
}
if (mbhc_cfg->mclk_rate != MCLK_RATE_12288KHZ &&
mbhc_cfg->mclk_rate != MCLK_RATE_9600KHZ) {
pr_err("Error: unsupported clock rate %d\n",
mbhc_cfg->mclk_rate);
return -EINVAL;
}
/* Save mbhc config */
mbhc->mbhc_cfg = mbhc_cfg;
/* Get HW specific mbhc registers' address */
wcd9xxx_get_mbhc_micbias_regs(mbhc, MBHC_PRIMARY_MIC_MB);
/* Get HW specific mbhc registers' address for anc */
wcd9xxx_get_mbhc_micbias_regs(mbhc, MBHC_ANC_MIC_MB);
/* Put CFILT in fast mode by default */
if (mbhc->mbhc_cb && mbhc->mbhc_cb->cfilt_fast_mode)
mbhc->mbhc_cb->cfilt_fast_mode(codec, mbhc);
else
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.cfilt_ctl,
0x40, WCD9XXX_CFILT_FAST_MODE);
/*
* setup internal micbias if codec uses internal micbias for
* headset detection
*/
if (mbhc->mbhc_cfg->use_int_rbias) {
if (mbhc->mbhc_cb && mbhc->mbhc_cb->setup_int_rbias) {
mbhc->mbhc_cb->setup_int_rbias(codec, true);
} else {
pr_info("%s: internal bias requested but codec did not provide callback\n",
__func__);
}
}
/*
* If codec has specific clock gating for MBHC,
* remove the clock gate
*/
if (mbhc->mbhc_cb &&
mbhc->mbhc_cb->enable_clock_gate)
mbhc->mbhc_cb->enable_clock_gate(mbhc->codec, true);
if (!mbhc->mbhc_cfg->read_fw_bin ||
(mbhc->mbhc_cfg->read_fw_bin && mbhc->mbhc_fw) ||
(mbhc->mbhc_cfg->read_fw_bin && mbhc->mbhc_cal)) {
rc = wcd9xxx_init_and_calibrate(mbhc);
} else {
if (!mbhc->mbhc_fw || !mbhc->mbhc_cal)
schedule_delayed_work(&mbhc->mbhc_firmware_dwork,
usecs_to_jiffies(FW_READ_TIMEOUT));
else
pr_debug("%s: Skipping to read mbhc fw, 0x%p %p\n",
__func__, mbhc->mbhc_fw, mbhc->mbhc_cal);
}
pr_debug("%s: leave %d\n", __func__, rc);
return rc;
}
EXPORT_SYMBOL(wcd9xxx_mbhc_start);
void wcd9xxx_mbhc_stop(struct wcd9xxx_mbhc *mbhc)
{
if (mbhc->mbhc_fw || mbhc->mbhc_cal) {
cancel_delayed_work_sync(&mbhc->mbhc_firmware_dwork);
if (!mbhc->mbhc_cal)
release_firmware(mbhc->mbhc_fw);
mbhc->mbhc_fw = NULL;
mbhc->mbhc_cal = NULL;
}
}
EXPORT_SYMBOL(wcd9xxx_mbhc_stop);
static enum wcd9xxx_micbias_num
wcd9xxx_event_to_micbias(const enum wcd9xxx_notify_event event)
{
enum wcd9xxx_micbias_num ret;
switch (event) {
case WCD9XXX_EVENT_PRE_MICBIAS_1_ON:
case WCD9XXX_EVENT_PRE_MICBIAS_1_OFF:
case WCD9XXX_EVENT_POST_MICBIAS_1_ON:
case WCD9XXX_EVENT_POST_MICBIAS_1_OFF:
ret = MBHC_MICBIAS1;
break;
case WCD9XXX_EVENT_PRE_MICBIAS_2_ON:
case WCD9XXX_EVENT_PRE_MICBIAS_2_OFF:
case WCD9XXX_EVENT_POST_MICBIAS_2_ON:
case WCD9XXX_EVENT_POST_MICBIAS_2_OFF:
ret = MBHC_MICBIAS2;
break;
case WCD9XXX_EVENT_PRE_MICBIAS_3_ON:
case WCD9XXX_EVENT_PRE_MICBIAS_3_OFF:
case WCD9XXX_EVENT_POST_MICBIAS_3_ON:
case WCD9XXX_EVENT_POST_MICBIAS_3_OFF:
ret = MBHC_MICBIAS3;
break;
case WCD9XXX_EVENT_PRE_MICBIAS_4_ON:
case WCD9XXX_EVENT_PRE_MICBIAS_4_OFF:
case WCD9XXX_EVENT_POST_MICBIAS_4_ON:
case WCD9XXX_EVENT_POST_MICBIAS_4_OFF:
ret = MBHC_MICBIAS4;
break;
default:
WARN_ONCE(1, "Cannot convert event %d to micbias\n", event);
ret = MBHC_MICBIAS_INVALID;
break;
}
return ret;
}
static int wcd9xxx_event_to_cfilt(const enum wcd9xxx_notify_event event)
{
int ret;
switch (event) {
case WCD9XXX_EVENT_PRE_CFILT_1_OFF:
case WCD9XXX_EVENT_POST_CFILT_1_OFF:
case WCD9XXX_EVENT_PRE_CFILT_1_ON:
case WCD9XXX_EVENT_POST_CFILT_1_ON:
ret = WCD9XXX_CFILT1_SEL;
break;
case WCD9XXX_EVENT_PRE_CFILT_2_OFF:
case WCD9XXX_EVENT_POST_CFILT_2_OFF:
case WCD9XXX_EVENT_PRE_CFILT_2_ON:
case WCD9XXX_EVENT_POST_CFILT_2_ON:
ret = WCD9XXX_CFILT2_SEL;
break;
case WCD9XXX_EVENT_PRE_CFILT_3_OFF:
case WCD9XXX_EVENT_POST_CFILT_3_OFF:
case WCD9XXX_EVENT_PRE_CFILT_3_ON:
case WCD9XXX_EVENT_POST_CFILT_3_ON:
ret = WCD9XXX_CFILT3_SEL;
break;
default:
ret = -1;
}
return ret;
}
static int wcd9xxx_get_mbhc_cfilt_sel(struct wcd9xxx_mbhc *mbhc)
{
int cfilt;
const struct wcd9xxx_micbias_setting *mb_pdata =
mbhc->resmgr->micbias_pdata;
switch (mbhc->mbhc_cfg->micbias) {
case MBHC_MICBIAS1:
cfilt = mb_pdata->bias1_cfilt_sel;
break;
case MBHC_MICBIAS2:
cfilt = mb_pdata->bias2_cfilt_sel;
break;
case MBHC_MICBIAS3:
cfilt = mb_pdata->bias3_cfilt_sel;
break;
case MBHC_MICBIAS4:
cfilt = mb_pdata->bias4_cfilt_sel;
break;
default:
cfilt = MBHC_MICBIAS_INVALID;
break;
}
return cfilt;
}
static void wcd9xxx_enable_mbhc_txfe(struct wcd9xxx_mbhc *mbhc, bool on)
{
if (mbhc->mbhc_cb && mbhc->mbhc_cb->enable_mbhc_txfe)
mbhc->mbhc_cb->enable_mbhc_txfe(mbhc->codec, on);
else
snd_soc_update_bits(mbhc->codec, WCD9XXX_A_TX_7_MBHC_TEST_CTL,
0x40, on ? 0x40 : 0x00);
}
static int wcd9xxx_event_notify(struct notifier_block *self, unsigned long val,
void *data)
{
int ret = 0;
struct wcd9xxx_mbhc *mbhc = ((struct wcd9xxx_resmgr *)data)->mbhc;
struct snd_soc_codec *codec;
enum wcd9xxx_notify_event event = (enum wcd9xxx_notify_event)val;
pr_debug("%s: enter event %s(%d)\n", __func__,
wcd9xxx_get_event_string(event), event);
if (!mbhc || !mbhc->mbhc_cfg) {
pr_debug("mbhc not initialized\n");
return 0;
}
codec = mbhc->codec;
mutex_lock(&mbhc->mbhc_lock);
switch (event) {
/* MICBIAS usage change */
case WCD9XXX_EVENT_PRE_MICBIAS_1_ON:
case WCD9XXX_EVENT_PRE_MICBIAS_2_ON:
case WCD9XXX_EVENT_PRE_MICBIAS_3_ON:
case WCD9XXX_EVENT_PRE_MICBIAS_4_ON:
if (mbhc->mbhc_cfg && mbhc->mbhc_cfg->micbias ==
wcd9xxx_event_to_micbias(event)) {
wcd9xxx_switch_micbias(mbhc, 0);
/*
* Enable MBHC TxFE whenever micbias is
* turned ON and polling is active
*/
if (mbhc->polling_active)
wcd9xxx_enable_mbhc_txfe(mbhc, true);
}
break;
case WCD9XXX_EVENT_POST_MICBIAS_1_ON:
case WCD9XXX_EVENT_POST_MICBIAS_2_ON:
case WCD9XXX_EVENT_POST_MICBIAS_3_ON:
case WCD9XXX_EVENT_POST_MICBIAS_4_ON:
if (mbhc->mbhc_cfg && mbhc->mbhc_cfg->micbias ==
wcd9xxx_event_to_micbias(event) &&
wcd9xxx_mbhc_polling(mbhc)) {
/* if polling is on, restart it */
wcd9xxx_pause_hs_polling(mbhc);
wcd9xxx_start_hs_polling(mbhc);
}
break;
case WCD9XXX_EVENT_POST_MICBIAS_1_OFF:
case WCD9XXX_EVENT_POST_MICBIAS_2_OFF:
case WCD9XXX_EVENT_POST_MICBIAS_3_OFF:
case WCD9XXX_EVENT_POST_MICBIAS_4_OFF:
if (mbhc->mbhc_cfg && mbhc->mbhc_cfg->micbias ==
wcd9xxx_event_to_micbias(event)) {
if (mbhc->event_state &
(1 << MBHC_EVENT_PA_HPHL | 1 << MBHC_EVENT_PA_HPHR))
wcd9xxx_switch_micbias(mbhc, 1);
/*
* Disable MBHC TxFE, in case it was enabled earlier
* when micbias was enabled and polling is not active.
*/
if (!mbhc->polling_active)
wcd9xxx_enable_mbhc_txfe(mbhc, false);
}
if (mbhc->micbias_enable && mbhc->polling_active &&
!(snd_soc_read(mbhc->codec, mbhc->mbhc_bias_regs.ctl_reg)
& 0x80)) {
pr_debug("%s:Micbias turned off by recording, set up again",
__func__);
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg,
0x80, 0x80);
}
break;
/* PA usage change */
case WCD9XXX_EVENT_PRE_HPHL_PA_ON:
set_bit(MBHC_EVENT_PA_HPHL, &mbhc->event_state);
if (!(snd_soc_read(codec, mbhc->mbhc_bias_regs.ctl_reg) & 0x80))
/* if micbias is not enabled, switch to vddio */
wcd9xxx_switch_micbias(mbhc, 1);
break;
case WCD9XXX_EVENT_PRE_HPHR_PA_ON:
set_bit(MBHC_EVENT_PA_HPHR, &mbhc->event_state);
break;
case WCD9XXX_EVENT_POST_HPHL_PA_OFF:
clear_bit(MBHC_EVENT_PA_HPHL, &mbhc->event_state);
/* if HPH PAs are off, report OCP and switch back to CFILT */
clear_bit(WCD9XXX_HPHL_PA_OFF_ACK, &mbhc->hph_pa_dac_state);
clear_bit(WCD9XXX_HPHL_DAC_OFF_ACK, &mbhc->hph_pa_dac_state);
if (mbhc->hph_status & SND_JACK_OC_HPHL)
hphlocp_off_report(mbhc, SND_JACK_OC_HPHL);
if (!(mbhc->event_state &
(1 << MBHC_EVENT_PA_HPHL | 1 << MBHC_EVENT_PA_HPHR |
1 << MBHC_EVENT_PRE_TX_1_3_ON)))
wcd9xxx_switch_micbias(mbhc, 0);
break;
case WCD9XXX_EVENT_POST_HPHR_PA_OFF:
clear_bit(MBHC_EVENT_PA_HPHR, &mbhc->event_state);
/* if HPH PAs are off, report OCP and switch back to CFILT */
clear_bit(WCD9XXX_HPHR_PA_OFF_ACK, &mbhc->hph_pa_dac_state);
clear_bit(WCD9XXX_HPHR_DAC_OFF_ACK, &mbhc->hph_pa_dac_state);
if (mbhc->hph_status & SND_JACK_OC_HPHR)
hphrocp_off_report(mbhc, SND_JACK_OC_HPHL);
if (!(mbhc->event_state &
(1 << MBHC_EVENT_PA_HPHL | 1 << MBHC_EVENT_PA_HPHR |
1 << MBHC_EVENT_PRE_TX_1_3_ON)))
wcd9xxx_switch_micbias(mbhc, 0);
break;
/* Clock usage change */
case WCD9XXX_EVENT_PRE_MCLK_ON:
break;
case WCD9XXX_EVENT_POST_MCLK_ON:
/* Change to lower TxAAF frequency */
snd_soc_update_bits(codec, WCD9XXX_A_TX_COM_BIAS, 1 << 4,
1 << 4);
/* Re-calibrate clock rate dependent values */
wcd9xxx_update_mbhc_clk_rate(mbhc, mbhc->mbhc_cfg->mclk_rate);
/* If clock source changes, stop and restart polling */
if (wcd9xxx_mbhc_polling(mbhc)) {
wcd9xxx_calibrate_hs_polling(mbhc);
wcd9xxx_start_hs_polling(mbhc);
}
break;
case WCD9XXX_EVENT_PRE_MCLK_OFF:
/* If clock source changes, stop and restart polling */
if (wcd9xxx_mbhc_polling(mbhc))
wcd9xxx_pause_hs_polling(mbhc);
break;
case WCD9XXX_EVENT_POST_MCLK_OFF:
break;
case WCD9XXX_EVENT_PRE_RCO_ON:
break;
case WCD9XXX_EVENT_POST_RCO_ON:
/* Change to higher TxAAF frequency */
snd_soc_update_bits(codec, WCD9XXX_A_TX_COM_BIAS, 1 << 4,
0 << 4);
/* Re-calibrate clock rate dependent values */
wcd9xxx_update_mbhc_clk_rate(mbhc, mbhc->rco_clk_rate);
/* If clock source changes, stop and restart polling */
if (wcd9xxx_mbhc_polling(mbhc)) {
wcd9xxx_calibrate_hs_polling(mbhc);
wcd9xxx_start_hs_polling(mbhc);
}
break;
case WCD9XXX_EVENT_PRE_RCO_OFF:
/* If clock source changes, stop and restart polling */
if (wcd9xxx_mbhc_polling(mbhc))
wcd9xxx_pause_hs_polling(mbhc);
break;
case WCD9XXX_EVENT_POST_RCO_OFF:
break;
/* CFILT usage change */
case WCD9XXX_EVENT_PRE_CFILT_1_ON:
case WCD9XXX_EVENT_PRE_CFILT_2_ON:
case WCD9XXX_EVENT_PRE_CFILT_3_ON:
if (wcd9xxx_get_mbhc_cfilt_sel(mbhc) ==
wcd9xxx_event_to_cfilt(event))
/*
* Switch CFILT to slow mode if MBHC CFILT is being
* used.
*/
wcd9xxx_codec_switch_cfilt_mode(mbhc, false);
break;
case WCD9XXX_EVENT_POST_CFILT_1_OFF:
case WCD9XXX_EVENT_POST_CFILT_2_OFF:
case WCD9XXX_EVENT_POST_CFILT_3_OFF:
if (wcd9xxx_get_mbhc_cfilt_sel(mbhc) ==
wcd9xxx_event_to_cfilt(event))
/*
* Switch CFILT to fast mode if MBHC CFILT is not
* used anymore.
*/
wcd9xxx_codec_switch_cfilt_mode(mbhc, true);
break;
/* System resume */
case WCD9XXX_EVENT_POST_RESUME:
mbhc->mbhc_last_resume = jiffies;
break;
/* BG mode chage */
case WCD9XXX_EVENT_PRE_BG_OFF:
case WCD9XXX_EVENT_POST_BG_OFF:
case WCD9XXX_EVENT_PRE_BG_AUDIO_ON:
case WCD9XXX_EVENT_POST_BG_AUDIO_ON:
case WCD9XXX_EVENT_PRE_BG_MBHC_ON:
case WCD9XXX_EVENT_POST_BG_MBHC_ON:
/* Not used for now */
break;
case WCD9XXX_EVENT_PRE_TX_1_3_ON:
/*
* if polling is ON, mbhc micbias not enabled
* switch micbias source to VDDIO
*/
set_bit(MBHC_EVENT_PRE_TX_1_3_ON, &mbhc->event_state);
if (!(snd_soc_read(codec, mbhc->mbhc_bias_regs.ctl_reg)
& 0x80) &&
mbhc->polling_active && !mbhc->mbhc_micbias_switched)
wcd9xxx_switch_micbias(mbhc, 1);
break;
case WCD9XXX_EVENT_POST_TX_1_3_OFF:
/*
* Switch back to micbias if HPH PA or TX3 path
* is disabled
*/
clear_bit(MBHC_EVENT_PRE_TX_1_3_ON, &mbhc->event_state);
if (mbhc->polling_active && mbhc->mbhc_micbias_switched &&
!(mbhc->event_state & (1 << MBHC_EVENT_PA_HPHL |
1 << MBHC_EVENT_PA_HPHR)))
wcd9xxx_switch_micbias(mbhc, 0);
break;
default:
WARN(1, "Unknown event %d\n", event);
ret = -EINVAL;
}
mutex_unlock(&mbhc->mbhc_lock);
pr_debug("%s: leave\n", __func__);
return ret;
}
static s16 wcd9xxx_read_impedance_regs(struct wcd9xxx_mbhc *mbhc)
{
struct snd_soc_codec *codec = mbhc->codec;
short bias_value;
int i;
s32 z_t = 0;
s32 z_loop = z_det_box_car_avg;
/* Box Car avrg of less than a particular loop count will not be
* accomodated. Similarly if the count is more than a particular number
* it will not be counted. Set z_loop counter to a limit, if its more
* or less than the value in WCD9XXX_BOX_CAR_AVRG_MAX or
* WCD9XXX_BOX_CAR_AVRG_MIN
*/
if (z_loop < WCD9XXX_BOX_CAR_AVRG_MIN) {
dev_dbg(codec->dev,
"%s: Box Car avrg counter < %d. Limiting it to %d\n",
__func__, WCD9XXX_BOX_CAR_AVRG_MIN,
WCD9XXX_BOX_CAR_AVRG_MIN);
z_loop = WCD9XXX_BOX_CAR_AVRG_MIN;
} else if (z_loop > WCD9XXX_BOX_CAR_AVRG_MAX) {
dev_dbg(codec->dev,
"%s: Box Car avrg counter > %d. Limiting it to %d\n",
__func__, WCD9XXX_BOX_CAR_AVRG_MAX,
WCD9XXX_BOX_CAR_AVRG_MAX);
z_loop = WCD9XXX_BOX_CAR_AVRG_MAX;
}
/* Take box car average if needed */
for (i = 0; i < z_loop; i++) {
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x2);
/* Wait for atleast 1800uS to let register write to settle */
usleep_range(1800, 1800 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
z_t += wcd9xxx_read_sta_result(codec);
}
/* Take average of the Z values read */
bias_value = (s16) (z_t / z_loop);
return bias_value;
}
static int wcd9xxx_remeasure_z_values(struct wcd9xxx_mbhc *mbhc,
s16 l[3], s16 r[3],
uint32_t *zl, uint32_t *zr,
u32 *zl_stereo, u32 *zl_mono)
{
s16 l_t[3] = {0}, r_t[3] = {0};
s16 l2_stereo, l2_mono;
bool left, right;
struct snd_soc_codec *codec = mbhc->codec;
if (!mbhc->mbhc_cb || !mbhc->mbhc_cb->setup_zdet ||
!mbhc->mbhc_cb->compute_impedance) {
dev_err(codec->dev, "%s: Invalid parameters\n", __func__);
return -EINVAL;
}
left = !!(l);
right = !!(r);
dev_dbg(codec->dev, "%s: Remeasuring impedance values\n", __func__);
dev_dbg(codec->dev, "%s: l: %p, r: %p, left=%d, right=%d\n", __func__,
l, r, left, right);
/* Remeasure V2 values */
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_2, 0xFF, 0xF0);
if (right)
r_t[2] = wcd9xxx_read_impedance_regs(mbhc);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1, 0xFF, 0xC0);
if (left)
l_t[2] = wcd9xxx_read_impedance_regs(mbhc);
/* Ramp down HPHR */
mbhc->mbhc_cb->setup_zdet(mbhc, MBHC_ZDET_HPHR_RAMP_DISABLE);
if (right) {
/* Take R0'/R1' */
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_2,
0xFF, 0xF8);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1,
0xFF, 0xA0);
r_t[1] = wcd9xxx_read_impedance_regs(mbhc);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_2,
0xFF, 0xF0);
r_t[0] = wcd9xxx_read_impedance_regs(mbhc);
}
/* Put back gain to 1x */
if (!left && right)
mbhc->mbhc_cb->setup_zdet(mbhc, MBHC_ZDET_GAIN_0);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1, 0xFF, 0xC0);
/* Take L2'' measurement */
l2_stereo = wcd9xxx_read_impedance_regs(mbhc);
/* Turn off HPHR PA and take L2''' */
mbhc->mbhc_cb->setup_zdet(mbhc, MBHC_ZDET_HPHR_PA_DISABLE);
l2_mono = wcd9xxx_read_impedance_regs(mbhc);
/* Ramp HPHL from -15mV to 0V */
mbhc->mbhc_cb->setup_zdet(mbhc, MBHC_ZDET_HPHL_RAMP_DISABLE);
/* Take L0' and L1' with iCal */
l_t[0] = wcd9xxx_read_impedance_regs(mbhc);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_2, 0xFF, 0xF8);
l_t[1] = wcd9xxx_read_impedance_regs(mbhc);
if (left) {
l[0] = l_t[0];
l[1] = l_t[1];
l[2] = l_t[2];
}
if (right) {
r[0] = r_t[0];
r[1] = r_t[1];
r[2] = r_t[2];
}
/* compute the new impedance values */
mbhc->mbhc_cb->compute_impedance(mbhc, l, r, zl, zr);
if (!left && right)
mbhc->mbhc_cb->setup_zdet(mbhc, MBHC_ZDET_GAIN_UPDATE_1X);
/* compute the new ZL'' value */
l_t[2] = l2_stereo;
mbhc->mbhc_cb->compute_impedance(mbhc, l_t, NULL, zl_stereo, NULL);
/* compute the new ZL''' value */
l_t[2] = l2_mono;
mbhc->mbhc_cb->compute_impedance(mbhc, l_t, NULL, zl_mono, NULL);
pr_debug("%s: L0': 0x%x, L1': 0x%x L2_stereo: 0x%x, L2_mono: 0x%x\n",
__func__, l_t[0] & 0xffff, l_t[1] & 0xffff,
l2_stereo & 0xffff, l2_mono & 0xffff);
pr_debug("%s: ZL_stereo = %u, ZL_mono = %u\n",
__func__, *zl_stereo, *zl_mono);
return 0;
}
static enum mbhc_zdet_zones wcd9xxx_assign_zdet_zone(uint32_t zl, uint32_t zr,
int32_t *gain)
{
enum mbhc_zdet_zones zdet_zone;
if (WCD9XXX_IS_IN_ZDET_ZONE_1(zl) &&
WCD9XXX_IS_IN_ZDET_ZONE_1(zr)) {
zdet_zone = ZL_ZONE1__ZR_ZONE1;
*gain = 0;
} else if (WCD9XXX_IS_IN_ZDET_ZONE_2(zl) &&
WCD9XXX_IS_IN_ZDET_ZONE_2(zr)) {
zdet_zone = ZL_ZONE2__ZR_ZONE2;
*gain = MBHC_ZDET_GAIN_1;
} else if (WCD9XXX_IS_IN_ZDET_ZONE_3(zl) &&
WCD9XXX_IS_IN_ZDET_ZONE_3(zr)) {
zdet_zone = ZL_ZONE3__ZR_ZONE3;
*gain = MBHC_ZDET_GAIN_2;
} else if (WCD9XXX_IS_IN_ZDET_ZONE_2(zl) &&
WCD9XXX_IS_IN_ZDET_ZONE_1(zr)) {
zdet_zone = ZL_ZONE2__ZR_ZONE1;
*gain = MBHC_ZDET_GAIN_1;
} else if (WCD9XXX_IS_IN_ZDET_ZONE_3(zl) &&
WCD9XXX_IS_IN_ZDET_ZONE_1(zr)) {
zdet_zone = ZL_ZONE3__ZR_ZONE1;
*gain = MBHC_ZDET_GAIN_2;
} else if (WCD9XXX_IS_IN_ZDET_ZONE_1(zl) &&
WCD9XXX_IS_IN_ZDET_ZONE_2(zr)) {
zdet_zone = ZL_ZONE1__ZR_ZONE2;
*gain = MBHC_ZDET_GAIN_1;
} else if (WCD9XXX_IS_IN_ZDET_ZONE_1(zl) &&
WCD9XXX_IS_IN_ZDET_ZONE_3(zr)) {
zdet_zone = ZL_ZONE1__ZR_ZONE3;
*gain = MBHC_ZDET_GAIN_2;
} else {
zdet_zone = ZL_ZR_NOT_IN_ZONE1;
*gain = MBHC_ZDET_GAIN_1;
}
return zdet_zone;
}
static int wcd9xxx_detect_impedance(struct wcd9xxx_mbhc *mbhc, uint32_t *zl,
uint32_t *zr)
{
int i;
int ret = 0;
u8 micb_mbhc_val;
s16 l[3], r[3];
s16 *z[] = {
&l[0], &r[0], &r[1], &l[1], &l[2], &r[2],
};
u32 zl_stereo, zl_mono;
u32 zl_diff_1, zl_diff_2;
bool override_en;
struct snd_soc_codec *codec = mbhc->codec;
const int mux_wait_us = 25;
const struct wcd9xxx_reg_mask_val reg_set_mux[] = {
/* Phase 1 */
/* Set MBHC_MUX for HPHL without ical */
{WCD9XXX_A_MBHC_SCALING_MUX_2, 0xFF, 0xF0},
/* Set MBHC_MUX for HPHR without ical */
{WCD9XXX_A_MBHC_SCALING_MUX_1, 0xFF, 0xA0},
/* Set MBHC_MUX for HPHR with ical */
{WCD9XXX_A_MBHC_SCALING_MUX_2, 0xFF, 0xF8},
/* Set MBHC_MUX for HPHL with ical */
{WCD9XXX_A_MBHC_SCALING_MUX_1, 0xFF, 0xC0},
/* Phase 2 */
{WCD9XXX_A_MBHC_SCALING_MUX_2, 0xFF, 0xF0},
/* Set MBHC_MUX for HPHR without ical and wait for 25us */
{WCD9XXX_A_MBHC_SCALING_MUX_1, 0xFF, 0xA0},
};
pr_debug("%s: enter\n", __func__);
WCD9XXX_BCL_ASSERT_LOCKED(mbhc->resmgr);
if (!mbhc->mbhc_cb || !mbhc->mbhc_cb->setup_zdet ||
!mbhc->mbhc_cb->compute_impedance || !zl || !zr) {
return -EINVAL;
}
/*
* Impedance detection is an intrusive function as it mutes RX paths,
* enable PAs and etc. Therefore codec drvier including ALSA
* shouldn't read and write hardware registers during detection.
*/
mutex_lock(&codec->mutex);
wcd9xxx_onoff_ext_mclk(mbhc, true);
/*
* For impedance detection, make sure to disable micbias from
* override signal so that override does not cause micbias
* to be enabled. This setting will be undone after completing
* impedance measurement.
*/
micb_mbhc_val = snd_soc_read(codec, WCD9XXX_A_MAD_ANA_CTRL);
snd_soc_update_bits(codec, WCD9XXX_A_MAD_ANA_CTRL,
0x10, 0x00);
override_en = (snd_soc_read(codec, WCD9XXX_A_CDC_MBHC_B1_CTL) & 0x04) ?
true : false;
if (!override_en)
wcd9xxx_turn_onoff_override(mbhc, true);
pr_debug("%s: Setting impedance detection\n", __func__);
/* Codec specific setup for L0, R0, L1 and R1 measurements */
mbhc->mbhc_cb->setup_zdet(mbhc, MBHC_ZDET_PRE_MEASURE);
pr_debug("%s: Performing impedance detection\n", __func__);
for (i = 0; i < ARRAY_SIZE(reg_set_mux) - 2; i++) {
snd_soc_update_bits(codec, reg_set_mux[i].reg,
reg_set_mux[i].mask,
reg_set_mux[i].val);
if (mbhc->mbhc_cb->get_cdc_type &&
mbhc->mbhc_cb->get_cdc_type() ==
WCD9XXX_CDC_TYPE_TOMTOM) {
*(z[i]) = wcd9xxx_read_impedance_regs(mbhc);
} else {
if (mbhc->mbhc_cb->enable_mux_bias_block)
mbhc->mbhc_cb->enable_mux_bias_block(codec);
else
snd_soc_update_bits(codec,
WCD9XXX_A_MBHC_SCALING_MUX_1,
0x80, 0x80);
/* 25us is required after mux change to settle down */
usleep_range(mux_wait_us,
mux_wait_us + WCD9XXX_USLEEP_RANGE_MARGIN_US);
*(z[i]) = __wcd9xxx_codec_sta_dce(mbhc, 0,
true, false);
}
}
/* Codec specific setup for L2 and R2 measurements */
mbhc->mbhc_cb->setup_zdet(mbhc, MBHC_ZDET_POST_MEASURE);
for (; i < ARRAY_SIZE(reg_set_mux); i++) {
snd_soc_update_bits(codec, reg_set_mux[i].reg,
reg_set_mux[i].mask,
reg_set_mux[i].val);
if (mbhc->mbhc_cb->get_cdc_type &&
mbhc->mbhc_cb->get_cdc_type() ==
WCD9XXX_CDC_TYPE_TOMTOM) {
*(z[i]) = wcd9xxx_read_impedance_regs(mbhc);
} else {
if (mbhc->mbhc_cb->enable_mux_bias_block)
mbhc->mbhc_cb->enable_mux_bias_block(codec);
else
snd_soc_update_bits(codec,
WCD9XXX_A_MBHC_SCALING_MUX_1,
0x80, 0x80);
/* 25us is required after mux change to settle down */
usleep_range(mux_wait_us,
mux_wait_us + WCD9XXX_USLEEP_RANGE_MARGIN_US);
*(z[i]) = __wcd9xxx_codec_sta_dce(mbhc, 0,
true, false);
}
}
mbhc->mbhc_cb->compute_impedance(mbhc, l, r, zl, zr);
/*
* For some codecs, an additional step of zdet is needed
* to overcome effects of noise and for better accuracy of
* z values
*/
if (mbhc->mbhc_cb->get_cdc_type &&
mbhc->mbhc_cb->get_cdc_type() == WCD9XXX_CDC_TYPE_TOMTOM) {
uint32_t zl_t = 0, zr_t = 0;
s16 *l_p, *r_p;
enum mbhc_zdet_zones zdet_zone;
int32_t gain;
zdet_zone = wcd9xxx_assign_zdet_zone(*zl, *zr, &gain);
switch (zdet_zone) {
case ZL_ZONE1__ZR_ZONE1:
l_p = NULL;
r_p = NULL;
break;
case ZL_ZONE2__ZR_ZONE2:
case ZL_ZONE3__ZR_ZONE3:
case ZL_ZR_NOT_IN_ZONE1:
l_p = l;
r_p = r;
break;
case ZL_ZONE2__ZR_ZONE1:
case ZL_ZONE3__ZR_ZONE1:
/* If ZR falls in Zone 1, further computations with
* gain update are not required
*/
l_p = l;
r_p = NULL;
break;
case ZL_ZONE1__ZR_ZONE2:
case ZL_ZONE1__ZR_ZONE3:
/* If ZL falls in Zone 1, further computations with
* gain update are not required
*/
l_p = NULL;
r_p = r;
break;
}
pr_debug("%s:zdet_zone = %d, gain = %d\n", __func__,
zdet_zone, gain);
if (gain)
mbhc->mbhc_cb->setup_zdet(mbhc, gain);
wcd9xxx_remeasure_z_values(mbhc, l_p, r_p, &zl_t, &zr_t,
&zl_stereo, &zl_mono);
*zl = (zl_t) ? zl_t : *zl;
*zr = (zr_t) ? zr_t : *zr;
/* Check for Mono/Stereo Type
* Conditions to classify Mono/Stereo
* i. Difference of zl_stereo and zl_mono > (1/2) of zl_mono
* ii. Absolute difference of zl and zr above a threshold
*/
zl_diff_1 = (zl_mono > zl_stereo) ? (zl_mono - zl_stereo) :
(zl_stereo - zl_mono);
zl_diff_2 = (*zl > *zr) ? (*zl - *zr) : (*zr - *zl);
mbhc->hph_type = MBHC_HPH_NONE;
if (mbhc->current_plug != PLUG_TYPE_HIGH_HPH) {
if ((zl_diff_1 > (zl_mono >> 1)) ||
(zl_diff_2 > WCD9XXX_MONO_HS_DIFF_THR) ||
((*zl < WCD9XXX_MONO_HS_MIN_THR) &&
(*zr > WCD9XXX_MONO_HS_MIN_THR)) ||
((*zr < WCD9XXX_MONO_HS_MIN_THR) &&
(*zl > WCD9XXX_MONO_HS_MIN_THR))) {
pr_debug("%s: MONO plug type detected\n",
__func__);
mbhc->hph_type = MBHC_HPH_MONO;
*zl = zl_mono;
} else {
pr_debug("%s: STEREO plug type detected\n",
__func__);
mbhc->hph_type = MBHC_HPH_STEREO;
}
}
}
mbhc->mbhc_cb->setup_zdet(mbhc, MBHC_ZDET_PA_DISABLE);
/* Calculate z values based on the Q-fuse registers, if used */
if (mbhc->mbhc_cb->zdet_error_approx)
mbhc->mbhc_cb->zdet_error_approx(mbhc, zl, zr);
mutex_unlock(&codec->mutex);
wcd9xxx_onoff_ext_mclk(mbhc, false);
if (!override_en)
wcd9xxx_turn_onoff_override(mbhc, false);
/* Undo the micbias disable for override */
snd_soc_write(codec, WCD9XXX_A_MAD_ANA_CTRL, micb_mbhc_val);
pr_debug("%s: L0: 0x%x(%d), L1: 0x%x(%d), L2: 0x%x(%d)\n",
__func__,
l[0] & 0xffff, l[0], l[1] & 0xffff, l[1], l[2] & 0xffff, l[2]);
pr_debug("%s: R0: 0x%x(%d), R1: 0x%x(%d), R2: 0x%x(%d)\n",
__func__,
r[0] & 0xffff, r[0], r[1] & 0xffff, r[1], r[2] & 0xffff, r[2]);
pr_debug("%s: RL %u milliohm, RR %u milliohm\n", __func__, *zl, *zr);
pr_debug("%s: Impedance detection completed\n", __func__);
return ret;
}
int wcd9xxx_mbhc_get_impedance(struct wcd9xxx_mbhc *mbhc, uint32_t *zl,
uint32_t *zr)
{
*zl = mbhc->zl;
*zr = mbhc->zr;
if (*zl && *zr)
return 0;
else
return -EINVAL;
}
/*
* wcd9xxx_mbhc_init : initialize MBHC internal structures.
*
* NOTE: mbhc->mbhc_cfg is not YET configure so shouldn't be used
*/
int wcd9xxx_mbhc_init(struct wcd9xxx_mbhc *mbhc, struct wcd9xxx_resmgr *resmgr,
struct snd_soc_codec *codec,
int (*micbias_enable_cb) (struct snd_soc_codec*, bool,
enum wcd9xxx_micbias_num),
const struct wcd9xxx_mbhc_cb *mbhc_cb,
const struct wcd9xxx_mbhc_intr *mbhc_cdc_intr_ids,
int rco_clk_rate,
bool impedance_det_en)
{
int ret;
void *core_res;
pr_debug("%s: enter\n", __func__);
memset(&mbhc->mbhc_bias_regs, 0, sizeof(struct mbhc_micbias_regs));
memset(&mbhc->mbhc_data, 0, sizeof(struct mbhc_internal_cal_data));
mbhc->mbhc_data.t_sta_dce = DEFAULT_DCE_STA_WAIT;
mbhc->mbhc_data.t_dce = DEFAULT_DCE_WAIT;
mbhc->mbhc_data.t_sta = DEFAULT_STA_WAIT;
mbhc->mbhc_micbias_switched = false;
mbhc->polling_active = false;
mbhc->mbhc_state = MBHC_STATE_NONE;
mbhc->in_swch_irq_handler = false;
mbhc->current_plug = PLUG_TYPE_NONE;
mbhc->lpi_enabled = false;
mbhc->no_mic_headset_override = false;
mbhc->mbhc_last_resume = 0;
mbhc->codec = codec;
mbhc->resmgr = resmgr;
mbhc->resmgr->mbhc = mbhc;
mbhc->micbias_enable_cb = micbias_enable_cb;
mbhc->rco_clk_rate = rco_clk_rate;
mbhc->mbhc_cb = mbhc_cb;
mbhc->intr_ids = mbhc_cdc_intr_ids;
mbhc->impedance_detect = impedance_det_en;
mbhc->hph_type = MBHC_HPH_NONE;
if (mbhc->intr_ids == NULL) {
pr_err("%s: Interrupt mapping not provided\n", __func__);
return -EINVAL;
}
if (mbhc->headset_jack.jack == NULL) {
ret = snd_soc_jack_new(codec, "Headset Jack", WCD9XXX_JACK_MASK,
&mbhc->headset_jack);
if (ret) {
pr_err("%s: Failed to create new jack\n", __func__);
return ret;
}
ret = snd_soc_jack_new(codec, "Button Jack",
WCD9XXX_JACK_BUTTON_MASK,
&mbhc->button_jack);
if (ret) {
pr_err("Failed to create new jack\n");
return ret;
}
ret = snd_jack_set_key(mbhc->button_jack.jack,
SND_JACK_BTN_0,
KEY_MEDIA);
if (ret) {
pr_err("%s: Failed to set code for btn-0\n",
__func__);
return ret;
}
#ifdef VENDOR_EDIT
//Ming.Liu@MultiMedia.AudioDrv, 2015-03-02, Add for 1+ headphone line control
ret = snd_jack_set_key(mbhc->button_jack.jack,
SND_JACK_BTN_3, KEY_VOLUMEUP);
if (ret) {
pr_err("%s: Failed to set code for btn-3\n",
__func__);
return ret;
}
ret = snd_jack_set_key(mbhc->button_jack.jack,
SND_JACK_BTN_7, KEY_VOLUMEDOWN);
if (ret) {
pr_err("%s: Failed to set code for btn-7\n",
__func__);
return ret;
}
#endif /* VENDOR_EDIT */
INIT_DELAYED_WORK(&mbhc->mbhc_firmware_dwork,
wcd9xxx_mbhc_fw_read);
INIT_DELAYED_WORK(&mbhc->mbhc_btn_dwork, wcd9xxx_btn_lpress_fn);
INIT_DELAYED_WORK(&mbhc->mbhc_insert_dwork,
wcd9xxx_mbhc_insert_work);
}
mutex_init(&mbhc->mbhc_lock);
/* Register event notifier */
mbhc->nblock.notifier_call = wcd9xxx_event_notify;
ret = wcd9xxx_resmgr_register_notifier(mbhc->resmgr, &mbhc->nblock);
if (ret) {
pr_err("%s: Failed to register notifier %d\n", __func__, ret);
mutex_destroy(&mbhc->mbhc_lock);
return ret;
}
wcd9xxx_init_debugfs(mbhc);
/* Disable Impedance detection by default for certain codec types */
if (mbhc->mbhc_cb && mbhc->mbhc_cb->get_cdc_type &&
(mbhc->mbhc_cb->get_cdc_type() == WCD9XXX_CDC_TYPE_HELICON))
impedance_detect_en = 0;
else
impedance_detect_en = impedance_det_en ? 1 : 0;
core_res = mbhc->resmgr->core_res;
ret = wcd9xxx_request_irq(core_res, mbhc->intr_ids->insertion,
wcd9xxx_hs_insert_irq,
"Headset insert detect", mbhc);
if (ret) {
pr_err("%s: Failed to request irq %d, ret = %d\n", __func__,
mbhc->intr_ids->insertion, ret);
goto err_insert_irq;
}
wcd9xxx_disable_irq(core_res, mbhc->intr_ids->insertion);
ret = wcd9xxx_request_irq(core_res, mbhc->intr_ids->poll_plug_rem,
wcd9xxx_hs_remove_irq,
"Headset remove detect", mbhc);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
mbhc->intr_ids->poll_plug_rem);
goto err_remove_irq;
}
ret = wcd9xxx_request_irq(core_res, mbhc->intr_ids->dce_est_complete,
wcd9xxx_dce_handler, "DC Estimation detect",
mbhc);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
mbhc->intr_ids->dce_est_complete);
goto err_potential_irq;
}
ret = wcd9xxx_request_irq(core_res, mbhc->intr_ids->button_release,
wcd9xxx_release_handler,
"Button Release detect", mbhc);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
mbhc->intr_ids->button_release);
goto err_release_irq;
}
ret = wcd9xxx_request_irq(core_res, mbhc->intr_ids->hph_left_ocp,
wcd9xxx_hphl_ocp_irq, "HPH_L OCP detect",
mbhc);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
mbhc->intr_ids->hph_left_ocp);
goto err_hphl_ocp_irq;
}
wcd9xxx_disable_irq(core_res, mbhc->intr_ids->hph_left_ocp);
ret = wcd9xxx_request_irq(core_res, mbhc->intr_ids->hph_right_ocp,
wcd9xxx_hphr_ocp_irq, "HPH_R OCP detect",
mbhc);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
mbhc->intr_ids->hph_right_ocp);
goto err_hphr_ocp_irq;
}
wcd9xxx_disable_irq(core_res, mbhc->intr_ids->hph_right_ocp);
wcd9xxx_regmgr_cond_register(resmgr, 1 << WCD9XXX_COND_HPH_MIC |
1 << WCD9XXX_COND_HPH);
pr_debug("%s: leave ret %d\n", __func__, ret);
return ret;
err_hphr_ocp_irq:
wcd9xxx_free_irq(core_res, mbhc->intr_ids->hph_left_ocp, mbhc);
err_hphl_ocp_irq:
wcd9xxx_free_irq(core_res, mbhc->intr_ids->button_release, mbhc);
err_release_irq:
wcd9xxx_free_irq(core_res, mbhc->intr_ids->dce_est_complete, mbhc);
err_potential_irq:
wcd9xxx_free_irq(core_res, mbhc->intr_ids->poll_plug_rem, mbhc);
err_remove_irq:
wcd9xxx_free_irq(core_res, mbhc->intr_ids->insertion, mbhc);
err_insert_irq:
wcd9xxx_resmgr_unregister_notifier(mbhc->resmgr, &mbhc->nblock);
mutex_destroy(&mbhc->mbhc_lock);
pr_debug("%s: leave ret %d\n", __func__, ret);
return ret;
}
EXPORT_SYMBOL(wcd9xxx_mbhc_init);
void wcd9xxx_mbhc_deinit(struct wcd9xxx_mbhc *mbhc)
{
struct wcd9xxx_core_resource *core_res =
mbhc->resmgr->core_res;
wcd9xxx_regmgr_cond_deregister(mbhc->resmgr, 1 << WCD9XXX_COND_HPH_MIC |
1 << WCD9XXX_COND_HPH);
wcd9xxx_free_irq(core_res, mbhc->intr_ids->button_release, mbhc);
wcd9xxx_free_irq(core_res, mbhc->intr_ids->dce_est_complete, mbhc);
wcd9xxx_free_irq(core_res, mbhc->intr_ids->poll_plug_rem, mbhc);
wcd9xxx_free_irq(core_res, mbhc->intr_ids->insertion, mbhc);
wcd9xxx_free_irq(core_res, mbhc->intr_ids->hs_jack_switch, mbhc);
wcd9xxx_free_irq(core_res, mbhc->intr_ids->hph_left_ocp, mbhc);
wcd9xxx_free_irq(core_res, mbhc->intr_ids->hph_right_ocp, mbhc);
mutex_destroy(&mbhc->mbhc_lock);
wcd9xxx_resmgr_unregister_notifier(mbhc->resmgr, &mbhc->nblock);
wcd9xxx_cleanup_debugfs(mbhc);
}
EXPORT_SYMBOL(wcd9xxx_mbhc_deinit);
MODULE_DESCRIPTION("wcd9xxx MBHC module");
MODULE_LICENSE("GPL v2");
| OnePlusOSS/android_kernel_oneplus_msm8994 | sound/soc/codecs/wcd9xxx-mbhc.c | C | gpl-2.0 | 172,567 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>XED2: XED2 User Guide - Tue Nov 22 12:27:53 2011 </title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.6 -->
<div class="tabs">
<ul>
<li><a href="main.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="classes.html"><span>Data Structures</span></a></li>
<li id="current"><a href="files.html"><span>Files</span></a></li>
<li>
<form action="search.php" method="get">
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td><label> <u>S</u>earch for </label></td>
<td><input type="text" name="query" value="" size="20" accesskey="s"/></td>
</tr>
</table>
</form>
</li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>Globals</span></a></li>
</ul></div>
<h1>xed-operand-values-interface.h</h1><a href="xed-operand-values-interface_8h.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/*BEGIN_LEGAL </span>
<a name="l00002"></a>00002 <span class="comment">Intel Open Source License </span>
<a name="l00003"></a>00003 <span class="comment"></span>
<a name="l00004"></a>00004 <span class="comment">Copyright (c) 2002-2011 Intel Corporation. All rights reserved.</span>
<a name="l00005"></a>00005 <span class="comment"> </span>
<a name="l00006"></a>00006 <span class="comment">Redistribution and use in source and binary forms, with or without</span>
<a name="l00007"></a>00007 <span class="comment">modification, are permitted provided that the following conditions are</span>
<a name="l00008"></a>00008 <span class="comment">met:</span>
<a name="l00009"></a>00009 <span class="comment"></span>
<a name="l00010"></a>00010 <span class="comment">Redistributions of source code must retain the above copyright notice,</span>
<a name="l00011"></a>00011 <span class="comment">this list of conditions and the following disclaimer. Redistributions</span>
<a name="l00012"></a>00012 <span class="comment">in binary form must reproduce the above copyright notice, this list of</span>
<a name="l00013"></a>00013 <span class="comment">conditions and the following disclaimer in the documentation and/or</span>
<a name="l00014"></a>00014 <span class="comment">other materials provided with the distribution. Neither the name of</span>
<a name="l00015"></a>00015 <span class="comment">the Intel Corporation nor the names of its contributors may be used to</span>
<a name="l00016"></a>00016 <span class="comment">endorse or promote products derived from this software without</span>
<a name="l00017"></a>00017 <span class="comment">specific prior written permission.</span>
<a name="l00018"></a>00018 <span class="comment"> </span>
<a name="l00019"></a>00019 <span class="comment">THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS</span>
<a name="l00020"></a>00020 <span class="comment">``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT</span>
<a name="l00021"></a>00021 <span class="comment">LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR</span>
<a name="l00022"></a>00022 <span class="comment">A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR</span>
<a name="l00023"></a>00023 <span class="comment">ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,</span>
<a name="l00024"></a>00024 <span class="comment">SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT</span>
<a name="l00025"></a>00025 <span class="comment">LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,</span>
<a name="l00026"></a>00026 <span class="comment">DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY</span>
<a name="l00027"></a>00027 <span class="comment">THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT</span>
<a name="l00028"></a>00028 <span class="comment">(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE</span>
<a name="l00029"></a>00029 <span class="comment">OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</span>
<a name="l00030"></a>00030 <span class="comment">END_LEGAL */</span>
<a name="l00033"></a>00033
<a name="l00034"></a>00034 <span class="preprocessor">#if !defined(_XED_OPERAND_VALUES_INTERFACE_H_)</span>
<a name="l00035"></a><a class="code" href="xed-operand-values-interface_8h.html#bcb0aa77774d3ee50ead1daafdcf1780">00035</a> <span class="preprocessor"></span><span class="preprocessor"># define _XED_OPERAND_VALUES_INTERFACE_H_</span>
<a name="l00036"></a>00036 <span class="preprocessor"></span>
<a name="l00037"></a>00037 <span class="preprocessor">#include "<a class="code" href="xed-common-hdrs_8h.html">xed-common-hdrs.h</a>"</span>
<a name="l00038"></a>00038 <span class="preprocessor">#include "<a class="code" href="xed-common-defs_8h.html">xed-common-defs.h</a>"</span>
<a name="l00039"></a>00039 <span class="preprocessor">#include "<a class="code" href="xed-portability_8h.html">xed-portability.h</a>"</span>
<a name="l00040"></a>00040 <span class="preprocessor">#include "<a class="code" href="xed-util_8h.html">xed-util.h</a>"</span>
<a name="l00041"></a>00041 <span class="preprocessor">#include "<a class="code" href="xed-types_8h.html">xed-types.h</a>"</span>
<a name="l00042"></a>00042 <span class="preprocessor">#include "<a class="code" href="xed-state_8h.html">xed-state.h</a>"</span> <span class="comment">// a generated file</span>
<a name="l00043"></a>00043 <span class="preprocessor">#include "<a class="code" href="xed-operand-enum_8h.html">xed-operand-enum.h</a>"</span> <span class="comment">// a generated file</span>
<a name="l00044"></a>00044 <span class="preprocessor">#include "<a class="code" href="xed-operand-storage_8h.html">xed-operand-storage.h</a>"</span>
<a name="l00045"></a>00045 <span class="preprocessor">#include "<a class="code" href="xed-reg-enum_8h.html">xed-reg-enum.h</a>"</span> <span class="comment">// generated</span>
<a name="l00046"></a>00046 <span class="preprocessor">#include "<a class="code" href="xed-iclass-enum_8h.html">xed-iclass-enum.h</a>"</span> <span class="comment">// generated</span>
<a name="l00048"></a>00048 <span class="comment"></span>
<a name="l00049"></a>00049
<a name="l00050"></a>00050
<a name="l00051"></a>00051 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span> <a class="code" href="group__OPERANDS.html#gbfc7434cb2fcd765f6ec31ab87bdb629">xed_operand_values_init</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00052"></a>00052
<a name="l00055"></a>00055 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span> <a class="code" href="group__OPERANDS.html#g759593cb89c8d0141460a1d59861ed65">xed_operand_values_init_set_mode</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00056"></a>00056 <span class="keyword">const</span> <a class="code" href="group__INIT.html#g5098627178cf29b62bcc2cea6a6c5d76">xed_state_t</a>* dstate);
<a name="l00057"></a>00057
<a name="l00060"></a>00060 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00061"></a>00061 <a class="code" href="group__OPERANDS.html#gdab21af647586f92eae1279747169d84">xed_operand_values_set_mode</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00062"></a>00062 <span class="keyword">const</span> <a class="code" href="group__INIT.html#g5098627178cf29b62bcc2cea6a6c5d76">xed_state_t</a>* dstate);
<a name="l00063"></a>00063
<a name="l00067"></a>00067 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00068"></a>00068 <a class="code" href="group__OPERANDS.html#gb5b52505e8e1d5772ad132c080c2ad23">xed_operand_values_init_keep_mode</a>( <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* dst,
<a name="l00069"></a>00069 <span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* src );
<a name="l00071"></a>00071
<a name="l00072"></a>00072 <span class="comment">// Returns the raw operand fields. Do not use this. </span>
<a name="l00073"></a>00073 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint32_t
<a name="l00074"></a>00074 <a class="code" href="xed-operand-values-interface_8h.html#44056dc6609804dc13f3acdd2d6a474a">xed_operand_values_get_operand_decider</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00075"></a>00075 <a class="code" href="xed-operand-enum_8h.html#b30d7e8aa0f4b2a0b18bb1655c3d2a33">xed_operand_enum_t</a> operand_decider_index) ;
<a name="l00076"></a>00076
<a name="l00077"></a>00077
<a name="l00080"></a>00080
<a name="l00081"></a>00081
<a name="l00082"></a>00082
<a name="l00083"></a>00083 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00084"></a>00084 <a class="code" href="group__OPERANDS.html#g810550cbd8a2d052c942bf112deac5cb">xed_operand_values_dump</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* ov,
<a name="l00085"></a>00085 <span class="keywordtype">char</span>* buf,
<a name="l00086"></a>00086 <span class="keywordtype">int</span> buflen);
<a name="l00089"></a>00089 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00090"></a>00090 <a class="code" href="group__OPERANDS.html#g5e067ec222258e17049a3d569843e6d8">xed_operand_values_print_short</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* ov,
<a name="l00091"></a>00091 <span class="keywordtype">char</span>* buf,
<a name="l00092"></a>00092 <span class="keywordtype">int</span> buflen);
<a name="l00094"></a>00094
<a name="l00096"></a>00096
<a name="l00097"></a>00097
<a name="l00098"></a>00098
<a name="l00099"></a>00099
<a name="l00100"></a>00100
<a name="l00101"></a>00101 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00102"></a>00102 <a class="code" href="group__OPERANDS.html#g76e9aaaa4c72d081a279da5f01445921">xed_operand_values_has_real_rep</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00106"></a>00106 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00107"></a>00107 <a class="code" href="group__OPERANDS.html#g73930a78a91461cef4d0ccee719a65da">xed_operand_values_has_rep_prefix</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00111"></a>00111 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00112"></a>00112 <a class="code" href="group__OPERANDS.html#g813f96dd2d96a1732899ce335615f8a1">xed_operand_values_has_repne_prefix</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00113"></a>00113
<a name="l00116"></a>00116 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span> <a class="code" href="group__OPERANDS.html#g5c1e320978d436111a743c51f6499411">xed_operand_values_set_repne</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00119"></a>00119 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span> <a class="code" href="group__OPERANDS.html#g171bac032bca35d981c652a62c16a466">xed_operand_values_set_rep</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00122"></a>00122 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span> <a class="code" href="group__OPERANDS.html#g5c413ba7141d7256686f9711bd6d14f0">xed_operand_values_clear_rep</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00123"></a>00123
<a name="l00125"></a>00125
<a name="l00130"></a>00130 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00131"></a>00131 <a class="code" href="group__OPERANDS.html#g5115b45462d5de8e6652e6c0363e9fbc">xed_operand_values_get_atomic</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00132"></a>00132
<a name="l00135"></a>00135 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00136"></a>00136 <a class="code" href="group__OPERANDS.html#g5fce25863add186854f447ec4d21affd">xed_operand_values_has_lock_prefix</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00137"></a>00137
<a name="l00144"></a>00144 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00145"></a>00145 <a class="code" href="group__OPERANDS.html#g37f6ff3bda0096951da47443ed448818">xed_operand_values_using_default_segment</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00146"></a>00146 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> i);
<a name="l00147"></a>00147
<a name="l00148"></a>00148
<a name="l00149"></a>00149
<a name="l00156"></a>00156 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint32_t
<a name="l00157"></a>00157 <a class="code" href="group__OPERANDS.html#g3c1fa3ab644e1ae33a4776fe21267ffe">xed_operand_values_get_effective_operand_width</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00160"></a>00160 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint32_t
<a name="l00161"></a>00161 <a class="code" href="group__OPERANDS.html#gb001312f34d24097c5fc204701bd3bca">xed_operand_values_get_effective_address_width</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00164"></a>00164 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint32_t
<a name="l00165"></a>00165 <a class="code" href="group__OPERANDS.html#g0e74bf39da51adafe58322c941b3d990">xed_operand_values_get_stack_address_width</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00166"></a>00166
<a name="l00167"></a>00167
<a name="l00170"></a>00170 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00171"></a>00171 <a class="code" href="group__OPERANDS.html#ge4effb0f9186f955f644db2bcf325007">xed_operand_values_has_memory_displacement</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00174"></a>00174 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00175"></a>00175 <a class="code" href="group__OPERANDS.html#gc3314da43b2323f02123fcb1f60e95a6">xed_operand_values_has_branch_displacement</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00178"></a>00178 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00179"></a>00179 <a class="code" href="group__OPERANDS.html#g5c74f0cb6e4300babb37d8b2f78a6921">xed_operand_values_has_displacement</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00180"></a>00180
<a name="l00181"></a>00181
<a name="l00184"></a>00184 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00185"></a>00185 <a class="code" href="group__OPERANDS.html#ga65d14a7fdadf391e48c3f0d62537dc5">xed_operand_values_get_displacement_for_memop</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00186"></a>00186
<a name="l00189"></a>00189 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00190"></a>00190 <a class="code" href="group__OPERANDS.html#g5a58d4b769c4ade3f258dbde0267763e">xed_operand_values_has_immediate</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00191"></a>00191
<a name="l00192"></a>00192
<a name="l00197"></a>00197 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00198"></a>00198 <a class="code" href="group__OPERANDS.html#gb117a5d3f5b58c0831477e667af67870">xed_operand_values_has_disp</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00199"></a>00199
<a name="l00202"></a>00202 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00203"></a>00203 <a class="code" href="group__OPERANDS.html#gfe3dcb0cde9f61d4f7b1fa4df4dc97e7">xed_operand_values_has_address_size_prefix</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00204"></a>00204
<a name="l00208"></a>00208 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00209"></a>00209 <a class="code" href="group__OPERANDS.html#g8d5552b8fa82872649d73be2877f128a">xed_operand_values_has_operand_size_prefix</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00210"></a>00210
<a name="l00213"></a>00213 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00214"></a>00214 <a class="code" href="group__OPERANDS.html#g41f053e7b9caec8ec7f9d05bc9712a80">xed_operand_values_has_66_prefix</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00215"></a>00215
<a name="l00218"></a>00218 <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00219"></a>00219 <a class="code" href="group__OPERANDS.html#g0d3d07ebb87921f68bdc7b93d6692d5d">xed_operand_values_has_rexw_prefix</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00220"></a>00220
<a name="l00221"></a>00221 <span class="preprocessor">#if 0</span>
<a name="l00222"></a>00222 <span class="preprocessor"></span><a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00223"></a>00223 xed_operand_values_has_refining_66_prefix(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00224"></a>00224 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00225"></a>00225 xed_operand_values_has_refining_f2_prefix(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00226"></a>00226 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00227"></a>00227 xed_operand_values_has_refining_f3_prefix(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00228"></a>00228 <span class="preprocessor">#endif</span>
<a name="l00229"></a>00229 <span class="preprocessor"></span>
<a name="l00231"></a>00231 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00232"></a>00232 <a class="code" href="group__OPERANDS.html#g1b578769dfb5d10a9f4a9d540f5dc29a">xed_operand_values_has_segment_prefix</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00233"></a>00233
<a name="l00236"></a>00236 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-reg-enum_8h.html#013dd4ba3d251f96c635b7df4eec4edb">xed_reg_enum_t</a>
<a name="l00237"></a>00237 <a class="code" href="group__OPERANDS.html#g33a25167e006d46f18b14c5fa0e14a6d">xed_operand_values_segment_prefix</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00238"></a>00238
<a name="l00240"></a>00240 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00241"></a>00241 <a class="code" href="group__OPERANDS.html#g56d31b4515a3f2defbb7fe5dd769b8ba">xed_operand_values_is_prefetch</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00242"></a>00242
<a name="l00244"></a>00244 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00245"></a>00245 <a class="code" href="group__OPERANDS.html#gbe519ac2a9db769e786db8bf7fee4543">xed_operand_values_get_long_mode</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00247"></a>00247 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00248"></a>00248 <a class="code" href="group__OPERANDS.html#ga0623e51063e63d4c6dc8102c14053a6">xed_operand_values_get_real_mode</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00249"></a>00249
<a name="l00251"></a>00251
<a name="l00252"></a>00252
<a name="l00253"></a>00253 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00254"></a>00254 <a class="code" href="group__OPERANDS.html#ge901dc22bd4ea4cdb672db819ca46ebb">xed_operand_values_accesses_memory</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00255"></a>00255
<a name="l00257"></a>00257 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span>
<a name="l00258"></a>00258 <a class="code" href="group__OPERANDS.html#g3c1e85334b6bddc2e720bf609a77e862">xed_operand_values_number_of_memory_operands</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00259"></a>00259
<a name="l00261"></a>00261 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span>
<a name="l00262"></a>00262 <a class="code" href="group__OPERANDS.html#g2ff46f90542411d5472df63429b637d5">xed_operand_values_get_memory_operand_length</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00263"></a>00263 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> memop_idx);
<a name="l00264"></a>00264
<a name="l00266"></a>00266 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-reg-enum_8h.html#013dd4ba3d251f96c635b7df4eec4edb">xed_reg_enum_t</a>
<a name="l00267"></a>00267 <a class="code" href="group__OPERANDS.html#g78ee856fa24ad2621d2662b300b82e7d">xed_operand_values_get_base_reg</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00268"></a>00268 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> memop_idx);
<a name="l00269"></a>00269
<a name="l00271"></a>00271 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-reg-enum_8h.html#013dd4ba3d251f96c635b7df4eec4edb">xed_reg_enum_t</a>
<a name="l00272"></a>00272 <a class="code" href="group__OPERANDS.html#g428cfd3f35c376e4d063eef51d248d91">xed_operand_values_get_index_reg</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00273"></a>00273 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> memop_idx);
<a name="l00274"></a>00274
<a name="l00276"></a>00276 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-reg-enum_8h.html#013dd4ba3d251f96c635b7df4eec4edb">xed_reg_enum_t</a>
<a name="l00277"></a>00277 <a class="code" href="group__OPERANDS.html#g62c07e4ad7ed8c33481a1e2a74cd47cf">xed_operand_values_get_seg_reg</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00278"></a>00278 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> memop_idx);
<a name="l00279"></a>00279
<a name="l00281"></a>00281 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span>
<a name="l00282"></a>00282 <a class="code" href="group__OPERANDS.html#g52cdf6ffe9e8d81a2ed8e5e46ab38e02">xed_operand_values_get_scale</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00283"></a>00283
<a name="l00287"></a>00287 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00288"></a>00288 <a class="code" href="group__OPERANDS.html#g863322bba29aecfc5ef711c713291f06">xed_operand_values_memop_without_modrm</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00291"></a>00291 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00292"></a>00292 <a class="code" href="group__OPERANDS.html#gdfb77508a402e867ead381dbee738e75">xed_operand_values_has_modrm_byte</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00293"></a>00293
<a name="l00296"></a>00296 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00297"></a>00297 <a class="code" href="group__OPERANDS.html#g44e45eb6e253d0b2a290fd6c8d32e798">xed_operand_values_has_sib_byte</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00299"></a>00299
<a name="l00301"></a>00301 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00302"></a>00302 <a class="code" href="group__OPERANDS.html#g6603b41a24cd2e4c5b09839f3837294a">xed_operand_values_branch_not_taken_hint</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00304"></a>00304 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00305"></a>00305 <a class="code" href="group__OPERANDS.html#g37dba36349443f7f004ac14b93e4a510">xed_operand_values_branch_taken_hint</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00306"></a>00306
<a name="l00308"></a>00308 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#7b03cfdd50b61cf63f302db50d31b336">xed_bool_t</a>
<a name="l00309"></a>00309 <a class="code" href="group__OPERANDS.html#gd6e2d77eebb1e2696bc84e731aba98fd">xed_operand_values_is_nop</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00310"></a>00310
<a name="l00311"></a>00311
<a name="l00313"></a>00313
<a name="l00314"></a>00314
<a name="l00315"></a>00315 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_int64_t
<a name="l00316"></a>00316 <a class="code" href="group__OPERANDS.html#g9ab11cdeac2907a2df862727b0825a35">xed_operand_values_get_immediate_int64</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00317"></a>00317
<a name="l00319"></a>00319 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint64_t
<a name="l00320"></a>00320 <a class="code" href="group__OPERANDS.html#g4260d17809cce0f84e7d187c7d9550cb">xed_operand_values_get_immediate_uint64</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00321"></a>00321
<a name="l00324"></a>00324 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-types_8h.html#4f6211e57e8a06c6ddde22f8c344ad7d">xed_uint_t</a>
<a name="l00325"></a>00325 <a class="code" href="group__OPERANDS.html#g702be63bdef457e212338c320c093cce">xed_operand_values_get_immediate_is_signed</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00326"></a>00326
<a name="l00327"></a>00327
<a name="l00330"></a>00330 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint8_t
<a name="l00331"></a>00331 <a class="code" href="group__OPERANDS.html#gf58927003dc5a2fe16fb8ef483e1ada2">xed_operand_values_get_immediate_byte</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00332"></a>00332 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> i);
<a name="l00333"></a>00333
<a name="l00335"></a>00335 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint8_t
<a name="l00336"></a>00336 <a class="code" href="group__OPERANDS.html#gb0c43c73d38470cc19f5946d6f93b30a">xed_operand_values_get_second_immediate</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00338"></a>00338
<a name="l00340"></a>00340
<a name="l00341"></a>00341
<a name="l00342"></a>00342
<a name="l00343"></a>00343 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint32_t
<a name="l00344"></a>00344 <a class="code" href="group__OPERANDS.html#gcc18341d287a489e1a9d4d943543de5e">xed_operand_values_get_memory_displacement_length</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00347"></a>00347 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint32_t
<a name="l00348"></a>00348 <a class="code" href="group__OPERANDS.html#gdc184927948fc0bcf5121e2c71bd823c">xed_operand_values_get_memory_displacement_length_bits</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00349"></a>00349
<a name="l00351"></a>00351 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_int64_t
<a name="l00352"></a>00352 <a class="code" href="group__OPERANDS.html#g4c79e69e77ec0312565dc11e0cc9d6b4">xed_operand_values_get_memory_displacement_int64</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00353"></a>00353
<a name="l00355"></a>00355 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint8_t
<a name="l00356"></a>00356 <a class="code" href="group__OPERANDS.html#g04050cd0def1cd2834ba5ca692477661">xed_operand_values_get_memory_displacement_byte</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00357"></a>00357 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> i);
<a name="l00359"></a>00359
<a name="l00361"></a>00361
<a name="l00362"></a>00362
<a name="l00363"></a>00363
<a name="l00364"></a>00364 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint32_t
<a name="l00365"></a>00365 <a class="code" href="group__OPERANDS.html#g1f94fc6e89b454d1c7089541eeca7ea7">xed_operand_values_get_branch_displacement_length</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00368"></a>00368 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint32_t
<a name="l00369"></a>00369 <a class="code" href="group__OPERANDS.html#gcf0b37eb66bdaeb879d37dd071ef1f7d">xed_operand_values_get_branch_displacement_length_bits</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00370"></a>00370
<a name="l00372"></a>00372 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_int32_t
<a name="l00373"></a>00373 <a class="code" href="group__OPERANDS.html#g599f875ce673812543d41ea7ec96445a">xed_operand_values_get_branch_displacement_int32</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00374"></a>00374
<a name="l00376"></a>00376 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> xed_uint8_t
<a name="l00377"></a>00377 <a class="code" href="group__OPERANDS.html#gb00e5a34189b380521900ac1bcb47538">xed_operand_values_get_branch_displacement_byte</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00378"></a>00378 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> i);
<a name="l00380"></a>00380
<a name="l00381"></a>00381
<a name="l00383"></a>00383 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <a class="code" href="xed-iclass-enum_8h.html#aac14887efb58dc90badb71262573543">xed_iclass_enum_t</a>
<a name="l00384"></a>00384 <a class="code" href="group__OPERANDS.html#g012d712b9ffb39e8d099d0cf45446c20">xed_operand_values_get_iclass</a>(<span class="keyword">const</span> <a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00385"></a>00385
<a name="l00387"></a>00387 <span class="comment">// ENCODE API</span>
<a name="l00390"></a>00390 <span class="comment"></span>
<a name="l00391"></a>00391
<a name="l00392"></a>00392 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00393"></a>00393 <a class="code" href="group__OPERANDS.html#gbb474ac1cb30aec2c87b2afd42258417">xed_operand_values_zero_immediate</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00395"></a>00395 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00396"></a>00396 <a class="code" href="group__OPERANDS.html#g9cfdffc3e2b160370ce7a78d94357dde">xed_operand_values_zero_branch_displacement</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00398"></a>00398 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00399"></a>00399 <a class="code" href="group__OPERANDS.html#g77a226802710742a4c9087d508953b9e">xed_operand_values_zero_memory_displacement</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00400"></a>00400
<a name="l00402"></a>00402 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span> <a class="code" href="group__OPERANDS.html#g87e1bb6ce1ed8a0a5565e905b5c9827f">xed_operand_values_set_lock</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00404"></a>00404 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00405"></a>00405 <a class="code" href="group__OPERANDS.html#ga4193567c061789a0aeaa6831e766b47">xed_operand_values_zero_segment_override</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00406"></a>00406
<a name="l00407"></a>00407
<a name="l00409"></a>00409 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00410"></a>00410 <a class="code" href="group__OPERANDS.html#g93f59a3f23474ba988703696303619d3">xed_operand_values_set_iclass</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00411"></a>00411 <a class="code" href="xed-iclass-enum_8h.html#aac14887efb58dc90badb71262573543">xed_iclass_enum_t</a> iclass);
<a name="l00412"></a>00412
<a name="l00415"></a>00415 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00416"></a>00416 <a class="code" href="group__OPERANDS.html#g03ae1d5b83a768e2a16dc55e4d94e0e7">xed_operand_values_set_effective_operand_width</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00417"></a>00417 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> width);
<a name="l00418"></a>00418
<a name="l00421"></a>00421 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00422"></a>00422 <a class="code" href="group__OPERANDS.html#g1fd96289e35a77c70246d982f983f2a9">xed_operand_values_set_effective_address_width</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00423"></a>00423 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> width);
<a name="l00424"></a>00424
<a name="l00426"></a>00426 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00427"></a>00427 <a class="code" href="group__OPERANDS.html#g189486f94c14789a4b5ccde415f84c3b">xed_operand_values_set_memory_operand_length</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00428"></a>00428 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> memop_length);
<a name="l00429"></a>00429
<a name="l00430"></a>00430
<a name="l00433"></a>00433 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00434"></a>00434 <a class="code" href="group__OPERANDS.html#gef7b8a5fa4f0956840ec9e723029ae0b">xed_operand_values_set_memory_displacement</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00435"></a>00435 xed_int64_t x, <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> len);
<a name="l00438"></a>00438 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00439"></a>00439 <a class="code" href="group__OPERANDS.html#g543a6bfbc81277745fe418183452b453">xed_operand_values_set_memory_displacement_bits</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00440"></a>00440 xed_int64_t x,
<a name="l00441"></a>00441 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> len_bits);
<a name="l00442"></a>00442
<a name="l00445"></a>00445 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span> <a class="code" href="group__OPERANDS.html#g83f3123783718cb5dc9b428617074b67">xed_operand_values_set_relbr</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p);
<a name="l00446"></a>00446
<a name="l00449"></a>00449 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00450"></a>00450 <a class="code" href="group__OPERANDS.html#g4127c0b36229df2146bf62de56dedb9b">xed_operand_values_set_branch_displacement</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00451"></a>00451 xed_int32_t x,
<a name="l00452"></a>00452 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> len);
<a name="l00455"></a>00455 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00456"></a>00456 <a class="code" href="group__OPERANDS.html#g26acda80a6c5c2a8d546f2d262f72c07">xed_operand_values_set_branch_displacement_bits</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00457"></a>00457 xed_int32_t x,
<a name="l00458"></a>00458 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> len_bits);
<a name="l00459"></a>00459
<a name="l00462"></a>00462 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00463"></a>00463 <a class="code" href="group__OPERANDS.html#gd8dc35d7e382b0df65c26debb162e6ce">xed_operand_values_set_immediate_signed</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00464"></a>00464 xed_int32_t x,
<a name="l00465"></a>00465 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> bytes);
<a name="l00468"></a>00468 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00469"></a>00469 <a class="code" href="group__OPERANDS.html#g39b917b3b3f81ef08c75da5897963dd3">xed_operand_values_set_immediate_signed_bits</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00470"></a>00470 xed_int32_t x,
<a name="l00471"></a>00471 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> bits);
<a name="l00472"></a>00472
<a name="l00473"></a>00473
<a name="l00476"></a>00476 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00477"></a>00477 <a class="code" href="group__OPERANDS.html#gaa1d4d21690399569dfab09a40622f67">xed_operand_values_set_immediate_unsigned</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00478"></a>00478 xed_uint64_t x,
<a name="l00479"></a>00479 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> bytes);
<a name="l00482"></a>00482 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00483"></a>00483 <a class="code" href="group__OPERANDS.html#gd1eaa90ea07598a5d55f4134d54c1f66">xed_operand_values_set_immediate_unsigned_bits</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00484"></a>00484 xed_uint64_t x,
<a name="l00485"></a>00485 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> bits);
<a name="l00486"></a>00486
<a name="l00487"></a>00487
<a name="l00488"></a>00488
<a name="l00490"></a>00490 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span> <a class="code" href="group__OPERANDS.html#gecdbcd1b618477b01efa7668e6f9f519">xed_operand_values_set_base_reg</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00491"></a>00491 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> memop_idx,
<a name="l00492"></a>00492 <a class="code" href="xed-reg-enum_8h.html#013dd4ba3d251f96c635b7df4eec4edb">xed_reg_enum_t</a> new_base);
<a name="l00493"></a>00493
<a name="l00495"></a>00495 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span> <a class="code" href="group__OPERANDS.html#g041c1c11517f29928fad75b481048050">xed_operand_values_set_seg_reg</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00496"></a>00496 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> memop_idx,
<a name="l00497"></a>00497 <a class="code" href="xed-reg-enum_8h.html#013dd4ba3d251f96c635b7df4eec4edb">xed_reg_enum_t</a> new_seg);
<a name="l00498"></a>00498
<a name="l00500"></a>00500 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span> <a class="code" href="group__OPERANDS.html#g797fc0cb3cfe01b01366b20bce1d4466">xed_operand_values_set_index_reg</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00501"></a>00501 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> memop_idx,
<a name="l00502"></a>00502 <a class="code" href="xed-reg-enum_8h.html#013dd4ba3d251f96c635b7df4eec4edb">xed_reg_enum_t</a> new_index);
<a name="l00503"></a>00503
<a name="l00505"></a>00505 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span> <a class="code" href="group__OPERANDS.html#g382b2b2f5c046bb4b3403e81ddca770e">xed_operand_values_set_scale</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00506"></a>00506 <a class="code" href="xed-types_8h.html#4f6211e57e8a06c6ddde22f8c344ad7d">xed_uint_t</a> memop_idx,
<a name="l00507"></a>00507 <a class="code" href="xed-types_8h.html#4f6211e57e8a06c6ddde22f8c344ad7d">xed_uint_t</a> new_scale);
<a name="l00508"></a>00508
<a name="l00509"></a>00509
<a name="l00513"></a>00513 <a class="code" href="xed-common-hdrs_8h.html#fd601b8ebafc7c3142edf0e30a8788cd">XED_DLL_EXPORT</a> <span class="keywordtype">void</span>
<a name="l00514"></a>00514 <a class="code" href="group__OPERANDS.html#g0fa87da871f9dc76c60eb2a65c1671b3">xed_operand_values_set_operand_reg</a>(<a class="code" href="xed-operand-storage_8h.html#dd3db22cd2c259d5fca4660bfa16fbd4">xed_operand_values_t</a>* p,
<a name="l00515"></a>00515 <a class="code" href="xed-operand-enum_8h.html#b30d7e8aa0f4b2a0b18bb1655c3d2a33">xed_operand_enum_t</a> operand_name,
<a name="l00516"></a>00516 <a class="code" href="xed-reg-enum_8h.html#013dd4ba3d251f96c635b7df4eec4edb">xed_reg_enum_t</a> reg_name);
<a name="l00517"></a>00517
<a name="l00519"></a>00519 <span class="preprocessor">#endif</span>
<a name="l00520"></a>00520 <span class="preprocessor"></span>
<a name="l00521"></a>00521 <span class="comment">//Local Variables:</span>
<a name="l00522"></a>00522 <span class="comment">//pref: "../../xed-operand-values-interface.c"</span>
<a name="l00523"></a>00523 <span class="comment">//End:</span>
</pre></div><hr size="1"><address style="align: right;"><small>Generated on Tue Nov 22 12:27:53 2011 for XED2 by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.4.6 </small></address>
</body>
</html>
| jzeng4/top | xed2/xed2-intel64/doc/html/xed-operand-values-interface_8h-source.html | HTML | gpl-2.0 | 57,269 |
<?php
/**
* @file
* Contains \Drupal\migrate_drupal\Tests\d6\MigrateFieldWidgetSettingsTest.
*/
namespace Drupal\migrate_drupal\Tests\d6;
use Drupal\migrate\MigrateExecutable;
use Drupal\migrate_drupal\Tests\MigrateDrupalTestBase;
/**
* Migrate field widget settings.
*
* @group migrate_drupal
*/
class MigrateFieldWidgetSettingsTest extends MigrateDrupalTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array(
'field',
'telephone',
'link',
'file',
'image',
'datetime',
'node',
);
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
entity_create('node_type', array('type' => 'test_page'))->save();
entity_create('node_type', array('type' => 'story'))->save();
// Add some id mappings for the dependant migrations.
$id_mappings = array(
'd6_field_instance' => array(
array(array('fieldname', 'page'), array('node', 'fieldname', 'page')),
),
'd6_field' => array(
array(array('field_test'), array('node', 'field_test')),
array(array('field_test_two'), array('node', 'field_test_two')),
array(array('field_test_three'), array('node', 'field_test_three')),
array(array('field_test_email'), array('node', 'field_test_email')),
array(array('field_test_link'), array('node', 'field_test_link')),
array(array('field_test_filefield'), array('node', 'field_test_filefield')),
array(array('field_test_imagefield'), array('node', 'field_test_imagefield')),
array(array('field_test_phone'), array('node', 'field_test_phone')),
array(array('field_test_date'), array('node', 'field_test_date')),
array(array('field_test_datestamp'), array('node', 'field_test_datestamp')),
array(array('field_test_datetime'), array('node', 'field_test_datetime')),
),
);
$this->prepareMigrations($id_mappings);
$migration = entity_load('migration', 'd6_field_instance_widget_settings');
$dumps = array(
$this->getDumpDirectory() . '/ContentNodeFieldInstance.php',
$this->getDumpDirectory() . '/ContentNodeField.php',
$this->getDumpDirectory() . '/ContentFieldTest.php',
$this->getDumpDirectory() . '/ContentFieldTestTwo.php',
$this->getDumpDirectory() . '/ContentFieldMultivalue.php',
);
$this->prepare($migration, $dumps);
$executable = new MigrateExecutable($migration, $this);
$executable->import();
}
/**
* Test that migrated view modes can be loaded using D8 API's.
*/
public function testWidgetSettings() {
// Test the config can be loaded.
$form_display = entity_load('entity_form_display', 'node.story.default');
$this->assertEqual(is_null($form_display), FALSE, "Form display node.story.default loaded with config.");
// Text field.
$component = $form_display->getComponent('field_test');
$expected = array('weight' => 1, 'type' => 'text_textfield');
$expected['settings'] = array('size' => 60, 'placeholder' => '');
$expected['third_party_settings'] = array();
$this->assertEqual($component, $expected, 'Text field settings are correct.');
// Integer field.
$component = $form_display->getComponent('field_test_two');
$expected['type'] = 'number';
$expected['weight'] = 1;
$expected['settings'] = array('placeholder' => '');
$this->assertEqual($component, $expected);
// Float field.
$component = $form_display->getComponent('field_test_three');
$expected['weight'] = 2;
$this->assertEqual($component, $expected);
// Email field.
$component = $form_display->getComponent('field_test_email');
$expected['type'] = 'email_default';
$expected['weight'] = 6;
$this->assertEqual($component, $expected);
// Link field.
$component = $form_display->getComponent('field_test_link');
$this->assertEqual($component['type'], 'link_default');
$this->assertEqual($component['weight'], 7);
$this->assertFalse(array_filter($component['settings']));
// File field.
$component = $form_display->getComponent('field_test_filefield');
$expected['type'] = 'file_generic';
$expected['weight'] = 8;
$expected['settings'] = array('progress_indicator' => 'bar');
$this->assertEqual($component, $expected);
// Image field.
$component = $form_display->getComponent('field_test_imagefield');
$expected['type'] = 'image_image';
$expected['weight'] = 9;
$expected['settings'] = array('progress_indicator' => 'bar', 'preview_image_style' => 'thumbnail');
$this->assertEqual($component, $expected);
// Phone field.
$component = $form_display->getComponent('field_test_phone');
$expected['type'] = 'telephone_default';
$expected['weight'] = 13;
$expected['settings'] = array('placeholder' => '');
$this->assertEqual($component, $expected);
// Date fields.
$component = $form_display->getComponent('field_test_date');
$expected['type'] = 'datetime_default';
$expected['weight'] = 10;
$expected['settings'] = array();
$this->assertEqual($component, $expected);
$component = $form_display->getComponent('field_test_datestamp');
$expected['weight'] = 11;
$this->assertEqual($component, $expected);
$component = $form_display->getComponent('field_test_datetime');
$expected['weight'] = 12;
$this->assertEqual($component, $expected);
}
}
| webflo/d8-core | modules/migrate_drupal/src/Tests/d6/MigrateFieldWidgetSettingsTest.php | PHP | gpl-2.0 | 5,460 |
/*
* Copyright (C) 2014 The Android Open Source Project
* Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio;
/**
* A read/write HeapLongBuffer.
*/
class HeapLongBuffer
extends LongBuffer {
// For speed these fields are actually declared in X-Buffer;
// these declarations are here as documentation
/*
protected final long[] hb;
protected final int offset;
*/
HeapLongBuffer(int cap, int lim) { // package-private
this(cap, lim, false);
}
HeapLongBuffer(int cap, int lim, boolean isReadOnly) { // package-private
super(-1, 0, lim, cap, new long[cap], 0);
this.isReadOnly = isReadOnly;
}
HeapLongBuffer(long[] buf, int off, int len) { // package-private
this(buf, off, len, false);
}
HeapLongBuffer(long[] buf, int off, int len, boolean isReadOnly) { // package-private
super(-1, off, off + len, buf.length, buf, 0);
this.isReadOnly = isReadOnly;
}
protected HeapLongBuffer(long[] buf,
int mark, int pos, int lim, int cap,
int off) {
this(buf, mark, pos, lim, cap, off, false);
}
protected HeapLongBuffer(long[] buf,
int mark, int pos, int lim, int cap,
int off, boolean isReadOnly) {
super(mark, pos, lim, cap, buf, off);
this.isReadOnly = isReadOnly;
}
public LongBuffer slice() {
return new HeapLongBuffer(hb,
-1,
0,
this.remaining(),
this.remaining(),
this.position() + offset,
isReadOnly);
}
public LongBuffer duplicate() {
return new HeapLongBuffer(hb,
this.markValue(),
this.position(),
this.limit(),
this.capacity(),
offset,
isReadOnly);
}
public LongBuffer asReadOnlyBuffer() {
return new HeapLongBuffer(hb,
this.markValue(),
this.position(),
this.limit(),
this.capacity(),
offset, true);
}
protected int ix(int i) {
return i + offset;
}
public long get() {
return hb[ix(nextGetIndex())];
}
public long get(int i) {
return hb[ix(checkIndex(i))];
}
public LongBuffer get(long[] dst, int offset, int length) {
checkBounds(offset, length, dst.length);
if (length > remaining())
throw new BufferUnderflowException();
System.arraycopy(hb, ix(position()), dst, offset, length);
position(position() + length);
return this;
}
public boolean isDirect() {
return false;
}
public boolean isReadOnly() {
return isReadOnly;
}
public LongBuffer put(long x) {
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
hb[ix(nextPutIndex())] = x;
return this;
}
public LongBuffer put(int i, long x) {
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
hb[ix(checkIndex(i))] = x;
return this;
}
public LongBuffer put(long[] src, int offset, int length) {
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
checkBounds(offset, length, src.length);
if (length > remaining())
throw new BufferOverflowException();
System.arraycopy(src, offset, hb, ix(position()), length);
position(position() + length);
return this;
}
public LongBuffer put(LongBuffer src) {
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
if (src instanceof HeapLongBuffer) {
if (src == this)
throw new IllegalArgumentException();
HeapLongBuffer sb = (HeapLongBuffer) src;
int n = sb.remaining();
if (n > remaining())
throw new BufferOverflowException();
System.arraycopy(sb.hb, sb.ix(sb.position()),
hb, ix(position()), n);
sb.position(sb.position() + n);
position(position() + n);
} else if (src.isDirect()) {
int n = src.remaining();
if (n > remaining())
throw new BufferOverflowException();
src.get(hb, ix(position()), n);
position(position() + n);
} else {
super.put(src);
}
return this;
}
public LongBuffer compact() {
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
System.arraycopy(hb, ix(position()), hb, ix(0), remaining());
position(remaining());
limit(capacity());
discardMark();
return this;
}
public ByteOrder order() {
return ByteOrder.nativeOrder();
}
}
| AdmireTheDistance/android_libcore | ojluni/src/main/java/java/nio/HeapLongBuffer.java | Java | gpl-2.0 | 6,185 |
<?
include('catalog.php');
$out = array();
foreach ($catalog as $row){
$hex = '';
foreach ($row['unicode'] as $cp) $hex .= sprintf('%x', $cp);
$html = "<span class=\"emoji emoji$hex\"></span>";
$out[] = array(
'name' => $row['char_name']['title'],
'unified' => $row['unicode'],
'docomo' => $row['docomo']['unicode'],
'kddi' => $row['au']['unicode'],
'softbank' => $row['softbank']['unicode'],
'google' => $row['google']['unicode'],
'html' => $html,
);
}
function format_codepoints($us){
if (!count($us)) return '-';
$out = array();
foreach ($us as $u){
$out[] = 'U+'.sprintf('%04X', $u);
}
return implode(' ', $out);
}
?>
<html>
<head>
<title>Emoji Catalog</title>
<link rel="stylesheet" type="text/css" media="all" href="emoji.css" />
<style type="text/css">
body {
font-size: 12px;
font-family: Arial, Helvetica, sans-serif;
}
table {
-webkit-border-radius: 0.41em;
-moz-border-radius: 0.41em;
border: 1px solid #999;
font-size: 12px;
}
table td {
padding-left: 0.41em;
padding-right: 0.41em;
}
table th {
font-weight: bold;
text-align: left;
background: #BBB;
color: #333;
font-size: 14px;
padding: 0.41em;
}
table tbody tr:nth-child(even) {
background: #dedede;
}
table tbody td {
padding: 0.41em;
}
</style>
</head>
<body>
<h1>Emoji Catalog</h1>
<table cellspacing="0" cellpadding="0">
<tr>
<th colspan="2">Name</th>
<th>Unified</th>
<th>DoCoMo</th>
<th>KDDI</th>
<th>Softbank</th>
<th>Google</th>
</tr>
<tbody>
<?
foreach ($out as $row){
echo "\t<tr>\n";
echo "\t\t<td>$row[html]</td>\n";
echo "\t\t<td>".HtmlSpecialChars(StrToLower($row['name']))."</td>\n";
echo "\t\t<td>".format_codepoints($row['unified'])."</td>\n";
echo "\t\t<td>".format_codepoints($row['docomo'])."</td>\n";
echo "\t\t<td>".format_codepoints($row['kddi'])."</td>\n";
echo "\t\t<td>".format_codepoints($row['softbank'])."</td>\n";
echo "\t\t<td>".format_codepoints($row['google'])."</td>\n";
echo "\t</tr>\n";
}
?>
</tbody>
</table>
</body>
<html>
| kirvin/journeyof1000li | wp-content/plugins/twitter-tracker/emoji/data/build_table.php | PHP | gpl-2.0 | 2,108 |
<?php
/**
* @file
* Contains the UCXF_Field class.
*/
/**
* Base class for a Extra Fields Pane field
*/
class UCXF_Field {
// -----------------------------------------------------------------------------
// CONSTANTS
// -----------------------------------------------------------------------------
// Fieldtypes
const UCXF_WIDGET_TYPE_SELECT = 1;
const UCXF_WIDGET_TYPE_CONSTANT = 2;
const UCXF_WIDGET_TYPE_PHP = 3;
const UCXF_WIDGET_TYPE_CHECKBOX = 4;
const UCXF_WIDGET_TYPE_TEXTFIELD = 5;
const UCXF_WIDGET_TYPE_PHP_SELECT = 6;
// -----------------------------------------------------------------------------
// PROPERTIES
// -----------------------------------------------------------------------------
/**
* An array of pane types the field is in.
* @var array
* @access private
*/
private $pane_types;
/**
* An array of page names on which the field may be displayed
* @var array
* @access private
*/
private $display_settings;
// -----------------------------------------------------------------------------
// CONSTRUCT
// -----------------------------------------------------------------------------
/**
* UCXF_Field object constructor
* @access public
* @return void
*/
public function __construct() {
// Set default values
$this->weight = 0;
$this->value_type = self::UCXF_WIDGET_TYPE_TEXTFIELD;
$this->required = FALSE;
$this->enabled = TRUE;
$this->pane_types = array();
$this->display_settings = array();
}
// -----------------------------------------------------------------------------
// STATIC METHODS
// -----------------------------------------------------------------------------
/**
* Returns an example for the value section
* @param int $field_type
* One of the field types defined by Extra Fields Pane
* @access public
* @static
* @return string
*/
public static function get_example($field_type) {
switch ($field_type) {
case self::UCXF_WIDGET_TYPE_SELECT:
return '<code>
|' . t('Please select') . '<br />
option1|' . t('Option 1') . '<br />
option2|' . t('Option 2')
. '</code>';
case self::UCXF_WIDGET_TYPE_CONSTANT:
return '<code>' . t('A constant value') . '</code>';
case self::UCXF_WIDGET_TYPE_PHP:
return '<code><?php return "' . t('A string') . '"; ?></code>';
case self::UCXF_WIDGET_TYPE_PHP_SELECT:
return "<code>
<?php<br />
return array(<br />
'' => '" . t('Please select') . "',<br />
'option1' => '" . t('Option 1') . "',<br />
'option2' => '" . t('Option 2') . "',<br />
);<br />
?>"
. "</code>";
}
}
// -----------------------------------------------------------------------------
// SETTERS
// -----------------------------------------------------------------------------
/**
* Setter
* @param string $p_sMember
* @param mixed $p_mValue
* @access public
* @return boolean
*/
public function __set($p_sMember, $p_mValue) {
switch ($p_sMember) {
case 'display_settings':
if (is_string($p_mValue)) {
$p_mValue = unserialize($p_mValue);
}
if (is_array($p_mValue)) {
foreach ($p_mValue as $option_id => $display_setting) {
$this->display_settings[$option_id] = ($display_setting) ? TRUE : FALSE;
}
return TRUE;
}
break;
case 'pane_type':
if (is_string($p_mValue)) {
$pane_types = explode('|', $p_mValue);
return $this->__set('pane_type', $pane_types);
}
elseif (is_array($p_mValue)) {
$this->pane_types = array();
foreach ($p_mValue as $pane_type) {
$pane_type = (string) $pane_type;
if (!empty($pane_type)) {
$this->pane_types[$pane_type] = $pane_type;
}
}
return TRUE;
}
default:
$this->{$p_sMember} = $p_mValue;
return TRUE;
}
return FALSE;
}
/**
* Load an existing item from an array.
* @access public
* @param array $p_aParams
*/
function from_array($p_aParams) {
foreach ($p_aParams as $sKey => $mValue) {
$this->__set($sKey, $mValue);
}
}
// -----------------------------------------------------------------------------
// GETTERS
// -----------------------------------------------------------------------------
/**
* Getter
* @param string $p_sMember
* @access public
* @return mixed
*/
public function __get($p_sMember) {
switch ($p_sMember) {
case 'id':
return $this->__get('field_id');
case 'pane_type':
return implode('|', $this->pane_types);
case 'pane_types':
return $this->pane_types;
default:
if (isset($this->{$p_sMember})) {
return $this->{$p_sMember};
}
break;
}
return NULL;
}
/**
* Return as an array of values.
* @access public
* @return array
*/
public function to_array() {
$aOutput = array();
// Return fields as specified in the schema.
$schema = drupal_get_schema('uc_extra_fields');
if (!empty($schema['fields']) && is_array($schema['fields'])) {
foreach ($schema['fields'] as $field => $info) {
$aOutput[$field] = $this->__get($field);
}
}
return $aOutput;
}
/**
* Output a value with filtering
* @param string $p_sMember
* @access public
* @return string
*/
public function output($p_sMember) {
switch ($p_sMember) {
case 'description':
return uc_extra_fields_pane_tt("field:$this->db_name:description", filter_xss_admin($this->{$p_sMember}));
case 'label':
return uc_extra_fields_pane_tt("field:$this->db_name:label", check_plain($this->{$p_sMember}));
case 'pane_type':
return check_plain($this->__get('pane_type'));
default:
if (isset($this->{$p_sMember})) {
return check_plain($this->{$p_sMember});
}
}
return '';
}
/**
* Output a value based on the field type
* @param string $p_sValue
* The given value
* @access public
* @return void
*/
public function output_value($p_sValue) {
switch ($this->value_type) {
case self::UCXF_WIDGET_TYPE_CHECKBOX:
return ($p_sValue) ? t('Yes') : t('No');
case self::UCXF_WIDGET_TYPE_SELECT:
case self::UCXF_WIDGET_TYPE_PHP_SELECT:
$values = $this->generate_value();
return (isset($values[$p_sValue])) ? check_plain($values[$p_sValue]) : check_plain($p_sValue);
default:
return ($p_sValue != '') ? check_plain($p_sValue) : t('n/a');
}
}
/**
* Returns the "readable" value type, as a string.
*
* @return string
*/
public function get_value_type() {
switch ($this->value_type) {
case UCXF_Field::UCXF_WIDGET_TYPE_TEXTFIELD:
return t('Textfield');
case UCXF_Field::UCXF_WIDGET_TYPE_SELECT:
return t('Select list');
case UCXF_Field::UCXF_WIDGET_TYPE_CHECKBOX:
return t('Checkbox');
case UCXF_Field::UCXF_WIDGET_TYPE_CONSTANT:
return t('Constant');
case UCXF_Field::UCXF_WIDGET_TYPE_PHP:
return t('PHP string');
case UCXF_Field::UCXF_WIDGET_TYPE_PHP_SELECT:
return t('PHP select list');
}
}
// -----------------------------------------------------------------------------
// LOGIC
// -----------------------------------------------------------------------------
/**
* Returns if the field's value may be displayed on te given page.
*
* Returns TRUE if the display setting for the given page does not exist.
*
* @param string $p_sPage
* @access public
* @return boolean
*/
public function may_display($p_sPage) {
if (isset($this->display_settings[$p_sPage])) {
return ($this->display_settings[$p_sPage]) ? TRUE : FALSE;
}
return TRUE;
}
/**
* Returns if field is in given pane
*
* @param string $p_sPane
* @access public
* @return boolean
*/
public function in_pane($p_sPane) {
return (isset($this->pane_types[$p_sPane]));
}
// -----------------------------------------------------------------------------
// DATABASE REQUESTS
// -----------------------------------------------------------------------------
// Deprecated
/**
* load()
* Loads field from database
* @param int $p_iField_id
* @access public
* @return UCXF_Field
*/
public function load($p_iField_id) {
return uc_extra_fields_pane_field_load($p_iField_id);
}
/**
* save()
* Saves field in database
* @access public
* @return void
*/
public function save() {
// Prepare values
$values = $this->to_array();
$update = array();
$sHook = 'insert';
if (!empty($this->field_id)) {
$update[] = 'field_id';
$sHook = 'update';
}
drupal_write_record('uc_extra_fields', $values, $update);
$this->field_id = $values['field_id'];
// Let other modules react on this
module_invoke_all('ucxf_field', $this, $sHook);
}
/**
* Delete the field from the database.
* @access public
* @return boolean
*/
public function delete() {
return UCXF_FieldList::deleteField($this);
}
// -----------------------------------------------------------------------------
// FORMS
// -----------------------------------------------------------------------------
/**
* Get the edit form for the field.
* @access public
* @return array
*/
public function edit_form() {
$form = array('#tree' => TRUE);
// Add instance of this to the form
$form['field'] = array(
'#type' => 'value',
'#value' => $this,
);
if (!empty($this->field_id)) {
$form['ucxf']['field_id'] = array(
'#type' => 'hidden',
'#value' => $this->field_id,
);
drupal_set_title(t('Modify field: @name', array('@name' => $this->db_name)), PASS_THROUGH);
}
$form['ucxf']['label'] = array(
'#title' => t('Label'),
'#type' => 'textfield',
'#size' => 25,
'#description' => t('Label shown to customers in checkout pages.'),
'#required' => TRUE,
'#default_value' => $this->label,
'#weight' => 0,
);
$default_db_name = $this->db_name;
if (strpos($default_db_name, 'ucxf_') !== 0) {
$default_db_name = 'ucxf_';
}
$form['ucxf']['db_name'] = array(
'#title' => t('Field name'),
'#type' => 'textfield',
'#size' => 25,
'#description' => t('Database field name. It must contain only lower chars a-z, digits 0-9 and _. Max allowed length is !number characters. This is inclusive the prefix %prefix.', array('!number' => 32, '%prefix' => 'ucxf_')),
'#required' => TRUE,
'#default_value' => $this->db_name,
'#weight' => 1,
'#maxlength' => 32,
);
if (isset($this->field_id)) {
// if field already exists, don't allow to alter the name
$form['ucxf']['db_name']['#disabled'] = 'disabled';
$form['ucxf']['db_name']['#value'] = $this->db_name;
}
$form['ucxf']['description'] = array(
'#title' => t('Description'),
'#type' => 'textarea',
'#rows' => 3,
'#description' => t('Insert a description to tell customers how to fill this field. ONLY applies for select/textbox options'),
'#default_value' => $this->description,
'#weight' => 3,
);
$form['ucxf']['weight'] = array(
'#type' => 'weight',
'#title' => t('Weight'),
'#delta' => 30,
'#default_value' => $this->weight,
'#description' => t('The listing position to display the order data on checkout/order panes.'),
'#weight' => 5,
);
$form['ucxf']['pane_type'] = array(
'#title' => t('Select which pane you would like the form value to be hooked into.'),
'#type' => 'select',
'#options' => array('extra_information' => t('Extra Information pane')),
'#default_value' => $this->pane_type,
'#weight' => 7,
);
$value_type_options = array(
self::UCXF_WIDGET_TYPE_TEXTFIELD => array(
'#title' => t('Textfield'),
'#description' => t('Let the user input the data in a textbox. If you want a default value, put it in "value" field below.'),
),
self::UCXF_WIDGET_TYPE_SELECT => array(
'#title' => t('Select list'),
'#description' => t('Let the user select from a list of options (enter one <strong>safe_key|Some readable option</strong> per line).'),
),
self::UCXF_WIDGET_TYPE_CHECKBOX => array(
'#title' => t('Checkbox'),
'#description' => t('Let the user select from a checkbox.'),
),
self::UCXF_WIDGET_TYPE_CONSTANT => array(
'#title' => t('Constant'),
'#description' => t('Show a admin defined constant value, insert the value in the "value" section.'),
),
);
if (user_access('use php fields')) {
$value_type_options += array(
self::UCXF_WIDGET_TYPE_PHP => array(
'#title' => t('PHP string'),
'#description' => t('Set the value to the php code that returns a <code>STRING</code> (PHP-mode, experts only).'),
),
self::UCXF_WIDGET_TYPE_PHP_SELECT => array(
'#title' => t('PHP select list'),
'#description' => t('Let the user select from a list of options from php code returning a <code>ARRAY</code> of key => value pairs. ie- <code>return array(\'element1\' => \'somevalue1\',\'element2\' => \'somevalue2\')</code> (PHP-mode, experts only).'),
),
);
}
$form['ucxf']['value_type'] = array(
'#type' => 'radios',
'#title' => t('Field type'),
'#options' => $value_type_options,
'#default_value' => $this->value_type,
'#weight' => 9,
'#required' => TRUE,
'#after_build' => array('uc_extra_fields_pane_field_value_type_after_build'),
);
$form['ucxf']['value'] = array(
'#type' => 'textarea',
'#title' => t('Value'),
'#description' => t('If the PHP-mode is chosen, enter PHP code between %php. Note that executing incorrect PHP-code can break your Drupal site.', array('%php' => '<?php ?>')),
'#default_value' => $this->value,
'#weight' => 10,
);
$form['ucxf']['required'] = array(
'#title' => t('Field required'),
'#type' => 'checkbox',
'#description' => t('Check this item if the field is mandatory.'),
'#default_value' => $this->required,
'#weight' => 12,
);
$form['ucxf']['enabled'] = array(
'#title' => t('Enabled'),
'#type' => 'checkbox',
'#default_value' => $this->enabled,
'#weight' => 14,
);
$display_options = module_invoke_all('ucxf_display_options', $this);
$form['ucxf']['display_settings'] = array(
'#title' => t('Display options'),
'#type' => 'fieldset',
'#weight' => 16,
'#description' => t('Choose on which pages you want to display the field.'),
);
foreach ($display_options as $option_id => $option) {
$form['ucxf']['display_settings'][$option_id] = array(
'#title' => $option_id,
'#type' => 'checkbox',
'#default_value' => $this->may_display($option_id),
);
foreach ($option as $attribute_name => $attribute_value) {
switch ($attribute_name) {
case 'title':
$form['ucxf']['display_settings'][$option_id]['#title'] = $attribute_value;
break;
case 'description':
$form['ucxf']['display_settings'][$option_id]['#description'] = $attribute_value;
break;
case 'weight':
$form['ucxf']['display_settings'][$option_id]['#weight'] = $attribute_value;
break;
}
}
}
$form['ucxf']['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#weight' => 50,
);
if ($this->returnpath) {
// Add 'cancel'-link
$form['ucxf']['submit']['#suffix'] = l(t('Cancel'), $this->returnpath);
}
return $form;
}
/**
* Validate the edit form for the item.
* @param array $form
* @param array $form_state
* @access public
* @return void
*/
public function edit_form_validate($form, &$form_state) {
$field = $form_state['values']['ucxf'];
// No label.
if (!$field['label']) {
form_set_error('ucxf][label', t('Custom order field: you need to provide a label.'));
}
// No field name.
if (!$field['db_name']) {
form_set_error('ucxf][db_name', t('Custom order field: you need to provide a field name.'));
}
if (isset($field['weight']) && !$field['weight'] && $field['weight'] !== 0 && $field['weight'] !== '0') {
form_set_error('ucxf][weight', t('Custom order field: you need to provide a weight value for this extra field.'));
}
if (isset($form['ucxf']['pane_type']) && empty($field['pane_type'])) {
form_set_error('ucxf][pane_type', t('Custom order field: you need to provide a pane-type for this extra field.'));
}
if (!$field['value_type']) {
form_set_error('ucxf][value_type', t('Custom order field: you need to provide a way of processing the value for this field as either textbox, select, constant, or php.'));
}
if (($field['value_type'] == self::UCXF_WIDGET_TYPE_CONSTANT || $field['value_type'] == self::UCXF_WIDGET_TYPE_PHP) && !$field['value'] ) {
form_set_error('ucxf][value', t('Custom order field: you need to provide a value for this way of calculating the field value.'));
}
// Field name validation.
if (empty($field['field_id'])) {
$field_name = $field['db_name'];
// Add the 'ucxf_' prefix.
if (strpos($field_name, 'ucxf_') !== 0) {
$field_name = 'ucxf_' . $field_name;
form_set_value($form['ucxf']['db_name'], $field_name, $form_state);
}
// Invalid field name.
if (!preg_match('!^ucxf_[a-z0-9_]+$!', $field_name)) {
form_set_error('ucxf][db_name', t('Custom order field: the field name %field_name is invalid. The name must include only lowercase unaccentuated letters, numbers, and underscores.', array('%field_name' => $field_name)));
}
// considering prefix ucxf_ no more than 32 characters (32 max for a db field)
if (strlen($field_name) > 32) {
form_set_error('ucxf][db_name', t('Custom order field: the field name %field_name is too long. The name is limited to !number characters, including the \'ucxf_\' prefix.', array('!number' => 32, '%field_name' => $field_name)));
}
// Check if field name already exists in table.
$count = db_select('uc_extra_fields')
->condition('db_name', $field_name)
->countQuery()
->execute()
->fetchField();
if ((int) $count > 0) {
form_set_error('ucxf][db_name', t('Custom order field: the field name %field_name already exists.', array('%field_name' => $field_name)));
}
}
// Check if php tags are present in case of a php field
if ($field['value_type'] == self::UCXF_WIDGET_TYPE_PHP || $field['value_type'] == self::UCXF_WIDGET_TYPE_PHP_SELECT) {
$php_open_tag_position = stripos($field['value'], '<?php');
$php_close_tag_position = strripos($field['value'], '?>');
if ($php_open_tag_position === FALSE || $php_close_tag_position === FALSE || $php_open_tag_position > $php_close_tag_position) {
form_set_error('ucxf][value', t('The PHP code is not entered between %php.', array('%php' => '<?php ?>')));
return;
}
}
// Display a warning when select or PHP-select fields are marked as required, but have no option with an empty key
if (($field['value_type'] == self::UCXF_WIDGET_TYPE_SELECT || $field['value_type'] == self::UCXF_WIDGET_TYPE_PHP_SELECT) && $field['required'] == TRUE) {
$this->value_type = $field['value_type'];
$this->value = $field['value'];
$options = $this->generate_value(FALSE);
$has_empty_key = FALSE;
foreach ($options as $key => $value) {
if ($key === '' || $key === ' ') {
$has_empty_key = TRUE;
break;
}
}
if (!$has_empty_key) {
switch ($field['value_type']) {
case self::UCXF_WIDGET_TYPE_SELECT:
$message_suffix = t('In this example the key of the first item is just a single space.');
break;
case self::UCXF_WIDGET_TYPE_PHP_SELECT:
$message_suffix = t('In this example the key of the first item is an empty string.');
break;
}
drupal_set_message(t('The select field %field is marked as required, but there is no "empty" option in the list. Enter an empty option in the value section as in this example: !example', array('%field' => $field['db_name'], '!example' => '<br />' . self::get_example($field['value_type']) . '<br />')) . $message_suffix, 'warning');
}
}
}
/**
* Submit the edit form for the item.
* @param array $form
* @param array $form_state
* @access public
* @return void
*/
public function edit_form_submit($form, &$form_state) {
$this->from_array($form_state['values']['ucxf']);
$this->display_settings = $form_state['values']['ucxf']['display_settings'];
$this->save();
drupal_set_message(t('Field saved'));
if ($this->returnpath) {
$form_state['redirect'] = $this->returnpath;
}
}
// -----------------------------------------------------------------------------
// ACTION
// -----------------------------------------------------------------------------
/**
* generate()
* Generates a field array used in forms generated by uc_extra_fields_pane
* @access public
* @return void
*/
public function generate() {
$return_field = array();
switch ($this->value_type) {
case self::UCXF_WIDGET_TYPE_TEXTFIELD:
$return_field = array(
'#type' => 'textfield',
'#title' => $this->output('label'),
'#description' => $this->output('description'),
'#size' => 32,
'#maxlength' => 255,
'#required' => $this->required,
);
// Add default value only when there is one
$default_value = $this->generate_value();
if ($default_value != '') {
$return_field['#default_value'] = $default_value;
}
break;
case self::UCXF_WIDGET_TYPE_CHECKBOX:
$return_field = array(
'#type' => 'checkbox',
'#title' => $this->output('label'),
'#description' => $this->output('description'),
'#required' => $this->required,
);
break;
case self::UCXF_WIDGET_TYPE_SELECT:
$return_field = array(
'#type' => 'select',
'#title' => $this->output('label'),
'#description' => $this->output('description'),
'#required' => $this->required,
'#options' => $this->generate_value(),
//'#default_value' => NULL,
);
break;
case self::UCXF_WIDGET_TYPE_PHP:
case self::UCXF_WIDGET_TYPE_CONSTANT:
$return_field = array(
'#type' => 'hidden',
'#value' => $this->generate_value(),
);
break;
case self::UCXF_WIDGET_TYPE_PHP_SELECT:
$return_field = array(
'#type' => 'select',
'#title' => $this->output('label'),
'#description' => $this->output('description'),
'#required' => $this->required,
'#options' => $this->generate_value(),
//'#default_value' => NULL,
);
break;
}
return $return_field;
}
/**
* Generates the value for use in fields.
* This value will be used as a default value for textfields
* and as an array of options for selection fields.
* @param boolean $translate
* If values may be translated.
* @access public
* @return mixed
*/
public function generate_value($translate = TRUE) {
switch ($this->value_type) {
case self::UCXF_WIDGET_TYPE_TEXTFIELD:
// This will return a string
$value = (string) $this->value;
if ($translate) {
$value = uc_extra_fields_pane_tt("field:$this->db_name:value", $value);
}
return $value;
case self::UCXF_WIDGET_TYPE_CONSTANT:
// This will return a string, sanitized.
$value = (string) $this->value;
if ($translate) {
$value = check_plain(uc_extra_fields_pane_tt("field:$this->db_name:value", $value));
}
return $value;
case self::UCXF_WIDGET_TYPE_SELECT:
// This will return an array of options
// like array('key' => 'label', 'key2' => 'label2')
$options = array();
$input_token = strtok($this->value, "\n");
while ($input_token !== FALSE) {
if (strpos($input_token, "|")) {
$arr = explode("|", $input_token);
$key = trim($arr[0]);
$label = trim($arr[1]);
}
else {
$key = trim($input_token);
$label = trim($input_token);
}
$options[$key] = $label;
$input_token = strtok("\n");
}
if ($translate) {
// Translate the labels of the options
foreach ($options as $key => $label) {
$options[$key] = uc_extra_fields_pane_tt("field:$this->db_name:value:$key", $label);
}
}
return $options;
case self::UCXF_WIDGET_TYPE_PHP:
// This will return a string.
$value = (string) eval('?>' . $this->value);
if ($translate) {
$value = uc_extra_fields_pane_tt("field:$this->db_name:value", $value);
}
return $value;
case self::UCXF_WIDGET_TYPE_PHP_SELECT:
// This will return an array of options created with eval
// like array('name' => 'value', 'name2' => 'value2')
// unfortunately php_eval() is not equipped for the task,
// so we need to use the standard php-eval.
$options = eval('?>' . $this->value);
if ($translate) {
// Translate the labels of the options
foreach ($options as $key => $label) {
$options[$key] = uc_extra_fields_pane_tt("field:$this->db_name:value:$key", $label);
}
}
return $options;
}
}
}
| alexey-kuznetsov/teploexpert | sites/all/modules/uc_extra_fields_pane/class/UCXF_Field.class.php | PHP | gpl-2.0 | 26,576 |
/* Copyright (C) 1999 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Philip Blundell <philb@gnu.org>, 1999.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <bits/armsigctx.h>
#define SIGCONTEXT int _a2, int _a3, int _a4, union k_sigcontext
#define SIGCONTEXT_EXTRA_ARGS _a2, _a3, _a4,
#define GET_PC(ctx) ((void *)((ctx.v20.magic == SIGCONTEXT_2_0_MAGIC) ? \
ctx.v20.reg.ARM_pc : ctx.v21.arm_pc))
#define GET_FRAME(ctx) \
ADVANCE_STACK_FRAME((void *)((ctx.v20.magic == SIGCONTEXT_2_0_MAGIC) ? \
ctx.v20.reg.ARM_fp : ctx.v21.arm_fp))
#define GET_STACK(ctx) ((void *)((ctx.v20.magic == SIGCONTEXT_2_0_MAGIC) ? \
ctx.v20.reg.ARM_sp : ctx.v21.arm_sp))
#define ADVANCE_STACK_FRAME(frm) \
((struct layout *)frm - 1)
#define CALL_SIGHANDLER(handler, signo, ctx) \
(handler)((signo), SIGCONTEXT_EXTRA_ARGS (ctx))
| ysleu/RTL8685 | uClinux-dist/uClibc-0.9.15/libpthread/linuxthreads/sysdeps/arm/sigcontextinfo.h | C | gpl-2.0 | 1,586 |
/*
* (C) Copyright 2010
* Texas Instruments, <www.ti.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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#ifndef _SYS_PROTO_H_
#define _SYS_PROTO_H_
#include <asm/arch/omap4.h>
#include <asm/io.h>
struct omap_sysinfo {
char *board_string;
};
void gpmc_init(void);
void watchdog_init(void);
u32 get_device_type(void);
void invalidate_dcache(u32);
void set_muxconf_regs(void);
extern const struct omap_sysinfo sysinfo;
#endif
| lemenkov/u-boot-oxnas | arch/arm/include/asm/arch-omap4/sys_proto.h | C | gpl-2.0 | 1,106 |
/*
* Renesas USB DMA Controller Driver
*
* Copyright (C) 2015 Renesas Electronics Corporation
*
* based on rcar-dmac.c
* Copyright (C) 2014 Renesas Electronics Inc.
* Author: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
*
* This 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.
*/
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_dma.h>
#include <linux/of_platform.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include "../dmaengine.h"
#include "../virt-dma.h"
/*
* struct usb_dmac_sg - Descriptor for a hardware transfer
* @mem_addr: memory address
* @size: transfer size in bytes
*/
struct usb_dmac_sg {
dma_addr_t mem_addr;
u32 size;
};
/*
* struct usb_dmac_desc - USB DMA Transfer Descriptor
* @vd: base virtual channel DMA transaction descriptor
* @direction: direction of the DMA transfer
* @sg_allocated_len: length of allocated sg
* @sg_len: length of sg
* @sg_index: index of sg
* @residue: residue after the DMAC completed a transfer
* @node: node for desc_got and desc_freed
* @done_cookie: cookie after the DMAC completed a transfer
* @sg: information for the transfer
*/
struct usb_dmac_desc {
struct virt_dma_desc vd;
enum dma_transfer_direction direction;
unsigned int sg_allocated_len;
unsigned int sg_len;
unsigned int sg_index;
u32 residue;
struct list_head node;
dma_cookie_t done_cookie;
struct usb_dmac_sg sg[0];
};
#define to_usb_dmac_desc(vd) container_of(vd, struct usb_dmac_desc, vd)
/*
* struct usb_dmac_chan - USB DMA Controller Channel
* @vc: base virtual DMA channel object
* @iomem: channel I/O memory base
* @index: index of this channel in the controller
* @irq: irq number of this channel
* @desc: the current descriptor
* @descs_allocated: number of descriptors allocated
* @desc_got: got descriptors
* @desc_freed: freed descriptors after the DMAC completed a transfer
*/
struct usb_dmac_chan {
struct virt_dma_chan vc;
void __iomem *iomem;
unsigned int index;
int irq;
struct usb_dmac_desc *desc;
int descs_allocated;
struct list_head desc_got;
struct list_head desc_freed;
};
#define to_usb_dmac_chan(c) container_of(c, struct usb_dmac_chan, vc.chan)
/*
* struct usb_dmac - USB DMA Controller
* @engine: base DMA engine object
* @dev: the hardware device
* @iomem: remapped I/O memory base
* @n_channels: number of available channels
* @channels: array of DMAC channels
*/
struct usb_dmac {
struct dma_device engine;
struct device *dev;
void __iomem *iomem;
unsigned int n_channels;
struct usb_dmac_chan *channels;
};
#define to_usb_dmac(d) container_of(d, struct usb_dmac, engine)
/* -----------------------------------------------------------------------------
* Registers
*/
#define USB_DMAC_CHAN_OFFSET(i) (0x20 + 0x20 * (i))
#define USB_DMASWR 0x0008
#define USB_DMASWR_SWR (1 << 0)
#define USB_DMAOR 0x0060
#define USB_DMAOR_AE (1 << 1)
#define USB_DMAOR_DME (1 << 0)
#define USB_DMASAR 0x0000
#define USB_DMADAR 0x0004
#define USB_DMATCR 0x0008
#define USB_DMATCR_MASK 0x00ffffff
#define USB_DMACHCR 0x0014
#define USB_DMACHCR_FTE (1 << 24)
#define USB_DMACHCR_NULLE (1 << 16)
#define USB_DMACHCR_NULL (1 << 12)
#define USB_DMACHCR_TS_8B ((0 << 7) | (0 << 6))
#define USB_DMACHCR_TS_16B ((0 << 7) | (1 << 6))
#define USB_DMACHCR_TS_32B ((1 << 7) | (0 << 6))
#define USB_DMACHCR_IE (1 << 5)
#define USB_DMACHCR_SP (1 << 2)
#define USB_DMACHCR_TE (1 << 1)
#define USB_DMACHCR_DE (1 << 0)
#define USB_DMATEND 0x0018
/* Hardcode the xfer_shift to 5 (32bytes) */
#define USB_DMAC_XFER_SHIFT 5
#define USB_DMAC_XFER_SIZE (1 << USB_DMAC_XFER_SHIFT)
#define USB_DMAC_CHCR_TS USB_DMACHCR_TS_32B
#define USB_DMAC_SLAVE_BUSWIDTH DMA_SLAVE_BUSWIDTH_32_BYTES
/* for descriptors */
#define USB_DMAC_INITIAL_NR_DESC 16
#define USB_DMAC_INITIAL_NR_SG 8
/* -----------------------------------------------------------------------------
* Device access
*/
static void usb_dmac_write(struct usb_dmac *dmac, u32 reg, u32 data)
{
writel(data, dmac->iomem + reg);
}
static u32 usb_dmac_read(struct usb_dmac *dmac, u32 reg)
{
return readl(dmac->iomem + reg);
}
static u32 usb_dmac_chan_read(struct usb_dmac_chan *chan, u32 reg)
{
return readl(chan->iomem + reg);
}
static void usb_dmac_chan_write(struct usb_dmac_chan *chan, u32 reg, u32 data)
{
writel(data, chan->iomem + reg);
}
/* -----------------------------------------------------------------------------
* Initialization and configuration
*/
static bool usb_dmac_chan_is_busy(struct usb_dmac_chan *chan)
{
u32 chcr = usb_dmac_chan_read(chan, USB_DMACHCR);
return (chcr & (USB_DMACHCR_DE | USB_DMACHCR_TE)) == USB_DMACHCR_DE;
}
static u32 usb_dmac_calc_tend(u32 size)
{
/*
* Please refer to the Figure "Example of Final Transaction Valid
* Data Transfer Enable (EDTEN) Setting" in the data sheet.
*/
return 0xffffffff << (32 - (size % USB_DMAC_XFER_SIZE ? :
USB_DMAC_XFER_SIZE));
}
/* This function is already held by vc.lock */
static void usb_dmac_chan_start_sg(struct usb_dmac_chan *chan,
unsigned int index)
{
struct usb_dmac_desc *desc = chan->desc;
struct usb_dmac_sg *sg = desc->sg + index;
dma_addr_t src_addr = 0, dst_addr = 0;
WARN_ON_ONCE(usb_dmac_chan_is_busy(chan));
if (desc->direction == DMA_DEV_TO_MEM)
dst_addr = sg->mem_addr;
else
src_addr = sg->mem_addr;
dev_dbg(chan->vc.chan.device->dev,
"chan%u: queue sg %p: %u@%pad -> %pad\n",
chan->index, sg, sg->size, &src_addr, &dst_addr);
usb_dmac_chan_write(chan, USB_DMASAR, src_addr & 0xffffffff);
usb_dmac_chan_write(chan, USB_DMADAR, dst_addr & 0xffffffff);
usb_dmac_chan_write(chan, USB_DMATCR,
DIV_ROUND_UP(sg->size, USB_DMAC_XFER_SIZE));
usb_dmac_chan_write(chan, USB_DMATEND, usb_dmac_calc_tend(sg->size));
usb_dmac_chan_write(chan, USB_DMACHCR, USB_DMAC_CHCR_TS |
USB_DMACHCR_NULLE | USB_DMACHCR_IE | USB_DMACHCR_DE);
}
/* This function is already held by vc.lock */
static void usb_dmac_chan_start_desc(struct usb_dmac_chan *chan)
{
struct virt_dma_desc *vd;
vd = vchan_next_desc(&chan->vc);
if (!vd) {
chan->desc = NULL;
return;
}
/*
* Remove this request from vc->desc_issued. Otherwise, this driver
* will get the previous value from vchan_next_desc() after a transfer
* was completed.
*/
list_del(&vd->node);
chan->desc = to_usb_dmac_desc(vd);
chan->desc->sg_index = 0;
usb_dmac_chan_start_sg(chan, 0);
}
static int usb_dmac_init(struct usb_dmac *dmac)
{
u16 dmaor;
/* Clear all channels and enable the DMAC globally. */
usb_dmac_write(dmac, USB_DMAOR, USB_DMAOR_DME);
dmaor = usb_dmac_read(dmac, USB_DMAOR);
if ((dmaor & (USB_DMAOR_AE | USB_DMAOR_DME)) != USB_DMAOR_DME) {
dev_warn(dmac->dev, "DMAOR initialization failed.\n");
return -EIO;
}
return 0;
}
/* -----------------------------------------------------------------------------
* Descriptors allocation and free
*/
static int usb_dmac_desc_alloc(struct usb_dmac_chan *chan, unsigned int sg_len,
gfp_t gfp)
{
struct usb_dmac_desc *desc;
unsigned long flags;
desc = kzalloc(sizeof(*desc) + sg_len * sizeof(desc->sg[0]), gfp);
if (!desc)
return -ENOMEM;
desc->sg_allocated_len = sg_len;
INIT_LIST_HEAD(&desc->node);
spin_lock_irqsave(&chan->vc.lock, flags);
list_add_tail(&desc->node, &chan->desc_freed);
spin_unlock_irqrestore(&chan->vc.lock, flags);
return 0;
}
static void usb_dmac_desc_free(struct usb_dmac_chan *chan)
{
struct usb_dmac_desc *desc, *_desc;
LIST_HEAD(list);
list_splice_init(&chan->desc_freed, &list);
list_splice_init(&chan->desc_got, &list);
list_for_each_entry_safe(desc, _desc, &list, node) {
list_del(&desc->node);
kfree(desc);
}
chan->descs_allocated = 0;
}
static struct usb_dmac_desc *usb_dmac_desc_get(struct usb_dmac_chan *chan,
unsigned int sg_len, gfp_t gfp)
{
struct usb_dmac_desc *desc = NULL;
unsigned long flags;
/* Get a freed descritpor */
spin_lock_irqsave(&chan->vc.lock, flags);
list_for_each_entry(desc, &chan->desc_freed, node) {
if (sg_len <= desc->sg_allocated_len) {
list_move_tail(&desc->node, &chan->desc_got);
spin_unlock_irqrestore(&chan->vc.lock, flags);
return desc;
}
}
spin_unlock_irqrestore(&chan->vc.lock, flags);
/* Allocate a new descriptor */
if (!usb_dmac_desc_alloc(chan, sg_len, gfp)) {
/* If allocated the desc, it was added to tail of the list */
spin_lock_irqsave(&chan->vc.lock, flags);
desc = list_last_entry(&chan->desc_freed, struct usb_dmac_desc,
node);
list_move_tail(&desc->node, &chan->desc_got);
spin_unlock_irqrestore(&chan->vc.lock, flags);
return desc;
}
return NULL;
}
static void usb_dmac_desc_put(struct usb_dmac_chan *chan,
struct usb_dmac_desc *desc)
{
unsigned long flags;
spin_lock_irqsave(&chan->vc.lock, flags);
list_move_tail(&desc->node, &chan->desc_freed);
spin_unlock_irqrestore(&chan->vc.lock, flags);
}
/* -----------------------------------------------------------------------------
* Stop and reset
*/
static void usb_dmac_soft_reset(struct usb_dmac_chan *uchan)
{
struct dma_chan *chan = &uchan->vc.chan;
struct usb_dmac *dmac = to_usb_dmac(chan->device);
int i;
/* Don't issue soft reset if any one of channels is busy */
for (i = 0; i < dmac->n_channels; ++i) {
if (usb_dmac_chan_is_busy(uchan))
return;
}
usb_dmac_write(dmac, USB_DMAOR, 0);
usb_dmac_write(dmac, USB_DMASWR, USB_DMASWR_SWR);
udelay(100);
usb_dmac_write(dmac, USB_DMASWR, 0);
usb_dmac_write(dmac, USB_DMAOR, 1);
}
static void usb_dmac_chan_halt(struct usb_dmac_chan *chan)
{
u32 chcr = usb_dmac_chan_read(chan, USB_DMACHCR);
chcr &= ~(USB_DMACHCR_IE | USB_DMACHCR_TE | USB_DMACHCR_DE);
usb_dmac_chan_write(chan, USB_DMACHCR, chcr);
usb_dmac_soft_reset(chan);
}
static void usb_dmac_stop(struct usb_dmac *dmac)
{
usb_dmac_write(dmac, USB_DMAOR, 0);
}
/* -----------------------------------------------------------------------------
* DMA engine operations
*/
static int usb_dmac_alloc_chan_resources(struct dma_chan *chan)
{
struct usb_dmac_chan *uchan = to_usb_dmac_chan(chan);
int ret;
while (uchan->descs_allocated < USB_DMAC_INITIAL_NR_DESC) {
ret = usb_dmac_desc_alloc(uchan, USB_DMAC_INITIAL_NR_SG,
GFP_KERNEL);
if (ret < 0) {
usb_dmac_desc_free(uchan);
return ret;
}
uchan->descs_allocated++;
}
return pm_runtime_get_sync(chan->device->dev);
}
static void usb_dmac_free_chan_resources(struct dma_chan *chan)
{
struct usb_dmac_chan *uchan = to_usb_dmac_chan(chan);
unsigned long flags;
/* Protect against ISR */
spin_lock_irqsave(&uchan->vc.lock, flags);
usb_dmac_chan_halt(uchan);
spin_unlock_irqrestore(&uchan->vc.lock, flags);
usb_dmac_desc_free(uchan);
vchan_free_chan_resources(&uchan->vc);
pm_runtime_put(chan->device->dev);
}
static struct dma_async_tx_descriptor *
usb_dmac_prep_slave_sg(struct dma_chan *chan, struct scatterlist *sgl,
unsigned int sg_len, enum dma_transfer_direction dir,
unsigned long dma_flags, void *context)
{
struct usb_dmac_chan *uchan = to_usb_dmac_chan(chan);
struct usb_dmac_desc *desc;
struct scatterlist *sg;
int i;
if (!sg_len) {
dev_warn(chan->device->dev,
"%s: bad parameter: len=%d\n", __func__, sg_len);
return NULL;
}
desc = usb_dmac_desc_get(uchan, sg_len, GFP_NOWAIT);
if (!desc)
return NULL;
desc->direction = dir;
desc->sg_len = sg_len;
for_each_sg(sgl, sg, sg_len, i) {
desc->sg[i].mem_addr = sg_dma_address(sg);
desc->sg[i].size = sg_dma_len(sg);
}
return vchan_tx_prep(&uchan->vc, &desc->vd, dma_flags);
}
static int usb_dmac_chan_terminate_all(struct dma_chan *chan)
{
struct usb_dmac_chan *uchan = to_usb_dmac_chan(chan);
struct usb_dmac_desc *desc;
unsigned long flags;
LIST_HEAD(head);
LIST_HEAD(list);
spin_lock_irqsave(&uchan->vc.lock, flags);
usb_dmac_chan_halt(uchan);
vchan_get_all_descriptors(&uchan->vc, &head);
if (uchan->desc)
uchan->desc = NULL;
list_splice_init(&uchan->desc_got, &list);
list_for_each_entry(desc, &list, node)
list_move_tail(&desc->node, &uchan->desc_freed);
spin_unlock_irqrestore(&uchan->vc.lock, flags);
vchan_dma_desc_free_list(&uchan->vc, &head);
return 0;
}
static unsigned int usb_dmac_get_current_residue(struct usb_dmac_chan *chan,
struct usb_dmac_desc *desc,
int sg_index)
{
struct usb_dmac_sg *sg = desc->sg + sg_index;
u32 mem_addr = sg->mem_addr & 0xffffffff;
unsigned int residue = sg->size;
/*
* We cannot use USB_DMATCR to calculate residue because USB_DMATCR
* has unsuited value to calculate.
*/
if (desc->direction == DMA_DEV_TO_MEM)
residue -= usb_dmac_chan_read(chan, USB_DMADAR) - mem_addr;
else
residue -= usb_dmac_chan_read(chan, USB_DMASAR) - mem_addr;
return residue;
}
static u32 usb_dmac_chan_get_residue_if_complete(struct usb_dmac_chan *chan,
dma_cookie_t cookie)
{
struct usb_dmac_desc *desc;
u32 residue = 0;
list_for_each_entry_reverse(desc, &chan->desc_freed, node) {
if (desc->done_cookie == cookie) {
residue = desc->residue;
break;
}
}
return residue;
}
static u32 usb_dmac_chan_get_residue(struct usb_dmac_chan *chan,
dma_cookie_t cookie)
{
u32 residue = 0;
struct virt_dma_desc *vd;
struct usb_dmac_desc *desc = chan->desc;
int i;
if (!desc) {
vd = vchan_find_desc(&chan->vc, cookie);
if (!vd)
return 0;
desc = to_usb_dmac_desc(vd);
}
/* Compute the size of all usb_dmac_sg still to be transferred */
for (i = desc->sg_index + 1; i < desc->sg_len; i++)
residue += desc->sg[i].size;
/* Add the residue for the current sg */
residue += usb_dmac_get_current_residue(chan, desc, desc->sg_index);
return residue;
}
static enum dma_status usb_dmac_tx_status(struct dma_chan *chan,
dma_cookie_t cookie,
struct dma_tx_state *txstate)
{
struct usb_dmac_chan *uchan = to_usb_dmac_chan(chan);
enum dma_status status;
unsigned int residue = 0;
unsigned long flags;
status = dma_cookie_status(chan, cookie, txstate);
/* a client driver will get residue after DMA_COMPLETE */
if (!txstate)
return status;
spin_lock_irqsave(&uchan->vc.lock, flags);
if (status == DMA_COMPLETE)
residue = usb_dmac_chan_get_residue_if_complete(uchan, cookie);
else
residue = usb_dmac_chan_get_residue(uchan, cookie);
spin_unlock_irqrestore(&uchan->vc.lock, flags);
dma_set_residue(txstate, residue);
return status;
}
static void usb_dmac_issue_pending(struct dma_chan *chan)
{
struct usb_dmac_chan *uchan = to_usb_dmac_chan(chan);
unsigned long flags;
spin_lock_irqsave(&uchan->vc.lock, flags);
if (vchan_issue_pending(&uchan->vc) && !uchan->desc)
usb_dmac_chan_start_desc(uchan);
spin_unlock_irqrestore(&uchan->vc.lock, flags);
}
static void usb_dmac_virt_desc_free(struct virt_dma_desc *vd)
{
struct usb_dmac_desc *desc = to_usb_dmac_desc(vd);
struct usb_dmac_chan *chan = to_usb_dmac_chan(vd->tx.chan);
usb_dmac_desc_put(chan, desc);
}
/* -----------------------------------------------------------------------------
* IRQ handling
*/
static void usb_dmac_isr_transfer_end(struct usb_dmac_chan *chan)
{
struct usb_dmac_desc *desc = chan->desc;
BUG_ON(!desc);
if (++desc->sg_index < desc->sg_len) {
usb_dmac_chan_start_sg(chan, desc->sg_index);
} else {
desc->residue = usb_dmac_get_current_residue(chan, desc,
desc->sg_index - 1);
desc->done_cookie = desc->vd.tx.cookie;
vchan_cookie_complete(&desc->vd);
/* Restart the next transfer if this driver has a next desc */
usb_dmac_chan_start_desc(chan);
}
}
static irqreturn_t usb_dmac_isr_channel(int irq, void *dev)
{
struct usb_dmac_chan *chan = dev;
irqreturn_t ret = IRQ_NONE;
u32 mask = 0;
u32 chcr;
bool xfer_end = false;
spin_lock(&chan->vc.lock);
chcr = usb_dmac_chan_read(chan, USB_DMACHCR);
if (chcr & (USB_DMACHCR_TE | USB_DMACHCR_SP)) {
mask |= USB_DMACHCR_DE | USB_DMACHCR_TE | USB_DMACHCR_SP;
if (chcr & USB_DMACHCR_DE)
xfer_end = true;
ret |= IRQ_HANDLED;
}
if (chcr & USB_DMACHCR_NULL) {
/* An interruption of TE will happen after we set FTE */
mask |= USB_DMACHCR_NULL;
chcr |= USB_DMACHCR_FTE;
ret |= IRQ_HANDLED;
}
if (mask)
usb_dmac_chan_write(chan, USB_DMACHCR, chcr & ~mask);
if (xfer_end)
usb_dmac_isr_transfer_end(chan);
spin_unlock(&chan->vc.lock);
return ret;
}
/* -----------------------------------------------------------------------------
* OF xlate and channel filter
*/
static bool usb_dmac_chan_filter(struct dma_chan *chan, void *arg)
{
struct usb_dmac_chan *uchan = to_usb_dmac_chan(chan);
struct of_phandle_args *dma_spec = arg;
if (dma_spec->np != chan->device->dev->of_node)
return false;
/* USB-DMAC should be used with fixed usb controller's FIFO */
if (uchan->index != dma_spec->args[0])
return false;
return true;
}
static struct dma_chan *usb_dmac_of_xlate(struct of_phandle_args *dma_spec,
struct of_dma *ofdma)
{
struct usb_dmac_chan *uchan;
struct dma_chan *chan;
dma_cap_mask_t mask;
if (dma_spec->args_count != 1)
return NULL;
/* Only slave DMA channels can be allocated via DT */
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
chan = dma_request_channel(mask, usb_dmac_chan_filter, dma_spec);
if (!chan)
return NULL;
uchan = to_usb_dmac_chan(chan);
return chan;
}
/* -----------------------------------------------------------------------------
* Power management
*/
#ifdef CONFIG_PM
static int usb_dmac_runtime_suspend(struct device *dev)
{
struct usb_dmac *dmac = dev_get_drvdata(dev);
int i;
for (i = 0; i < dmac->n_channels; ++i) {
if (!dmac->channels[i].iomem)
break;
usb_dmac_chan_halt(&dmac->channels[i]);
}
return 0;
}
static int usb_dmac_runtime_resume(struct device *dev)
{
struct usb_dmac *dmac = dev_get_drvdata(dev);
return usb_dmac_init(dmac);
}
#endif /* CONFIG_PM */
static const struct dev_pm_ops usb_dmac_pm = {
SET_RUNTIME_PM_OPS(usb_dmac_runtime_suspend, usb_dmac_runtime_resume,
NULL)
};
/* -----------------------------------------------------------------------------
* Probe and remove
*/
static int usb_dmac_chan_probe(struct usb_dmac *dmac,
struct usb_dmac_chan *uchan,
unsigned int index)
{
struct platform_device *pdev = to_platform_device(dmac->dev);
char pdev_irqname[5];
char *irqname;
int ret;
uchan->index = index;
uchan->iomem = dmac->iomem + USB_DMAC_CHAN_OFFSET(index);
/* Request the channel interrupt. */
sprintf(pdev_irqname, "ch%u", index);
uchan->irq = platform_get_irq_byname(pdev, pdev_irqname);
if (uchan->irq < 0) {
dev_err(dmac->dev, "no IRQ specified for channel %u\n", index);
return -ENODEV;
}
irqname = devm_kasprintf(dmac->dev, GFP_KERNEL, "%s:%u",
dev_name(dmac->dev), index);
if (!irqname)
return -ENOMEM;
ret = devm_request_irq(dmac->dev, uchan->irq, usb_dmac_isr_channel,
IRQF_SHARED, irqname, uchan);
if (ret) {
dev_err(dmac->dev, "failed to request IRQ %u (%d)\n",
uchan->irq, ret);
return ret;
}
uchan->vc.desc_free = usb_dmac_virt_desc_free;
vchan_init(&uchan->vc, &dmac->engine);
INIT_LIST_HEAD(&uchan->desc_freed);
INIT_LIST_HEAD(&uchan->desc_got);
return 0;
}
static int usb_dmac_parse_of(struct device *dev, struct usb_dmac *dmac)
{
struct device_node *np = dev->of_node;
int ret;
ret = of_property_read_u32(np, "dma-channels", &dmac->n_channels);
if (ret < 0) {
dev_err(dev, "unable to read dma-channels property\n");
return ret;
}
if (dmac->n_channels <= 0 || dmac->n_channels >= 100) {
dev_err(dev, "invalid number of channels %u\n",
dmac->n_channels);
return -EINVAL;
}
return 0;
}
static int usb_dmac_probe(struct platform_device *pdev)
{
const enum dma_slave_buswidth widths = USB_DMAC_SLAVE_BUSWIDTH;
struct dma_device *engine;
struct usb_dmac *dmac;
struct resource *mem;
unsigned int i;
int ret;
dmac = devm_kzalloc(&pdev->dev, sizeof(*dmac), GFP_KERNEL);
if (!dmac)
return -ENOMEM;
dmac->dev = &pdev->dev;
platform_set_drvdata(pdev, dmac);
ret = usb_dmac_parse_of(&pdev->dev, dmac);
if (ret < 0)
return ret;
dmac->channels = devm_kcalloc(&pdev->dev, dmac->n_channels,
sizeof(*dmac->channels), GFP_KERNEL);
if (!dmac->channels)
return -ENOMEM;
/* Request resources. */
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
dmac->iomem = devm_ioremap_resource(&pdev->dev, mem);
if (IS_ERR(dmac->iomem))
return PTR_ERR(dmac->iomem);
/* Enable runtime PM and initialize the device. */
pm_runtime_enable(&pdev->dev);
ret = pm_runtime_get_sync(&pdev->dev);
if (ret < 0) {
dev_err(&pdev->dev, "runtime PM get sync failed (%d)\n", ret);
goto error_pm;
}
ret = usb_dmac_init(dmac);
if (ret) {
dev_err(&pdev->dev, "failed to reset device\n");
goto error;
}
/* Initialize the channels. */
INIT_LIST_HEAD(&dmac->engine.channels);
for (i = 0; i < dmac->n_channels; ++i) {
ret = usb_dmac_chan_probe(dmac, &dmac->channels[i], i);
if (ret < 0)
goto error;
}
/* Register the DMAC as a DMA provider for DT. */
ret = of_dma_controller_register(pdev->dev.of_node, usb_dmac_of_xlate,
NULL);
if (ret < 0)
goto error;
/*
* Register the DMA engine device.
*
* Default transfer size of 32 bytes requires 32-byte alignment.
*/
engine = &dmac->engine;
dma_cap_set(DMA_SLAVE, engine->cap_mask);
engine->dev = &pdev->dev;
engine->src_addr_widths = widths;
engine->dst_addr_widths = widths;
engine->directions = BIT(DMA_MEM_TO_DEV) | BIT(DMA_DEV_TO_MEM);
engine->residue_granularity = DMA_RESIDUE_GRANULARITY_BURST;
engine->device_alloc_chan_resources = usb_dmac_alloc_chan_resources;
engine->device_free_chan_resources = usb_dmac_free_chan_resources;
engine->device_prep_slave_sg = usb_dmac_prep_slave_sg;
engine->device_terminate_all = usb_dmac_chan_terminate_all;
engine->device_tx_status = usb_dmac_tx_status;
engine->device_issue_pending = usb_dmac_issue_pending;
ret = dma_async_device_register(engine);
if (ret < 0)
goto error;
pm_runtime_put(&pdev->dev);
return 0;
error:
of_dma_controller_free(pdev->dev.of_node);
pm_runtime_put(&pdev->dev);
error_pm:
pm_runtime_disable(&pdev->dev);
return ret;
}
static void usb_dmac_chan_remove(struct usb_dmac *dmac,
struct usb_dmac_chan *uchan)
{
usb_dmac_chan_halt(uchan);
devm_free_irq(dmac->dev, uchan->irq, uchan);
}
static int usb_dmac_remove(struct platform_device *pdev)
{
struct usb_dmac *dmac = platform_get_drvdata(pdev);
int i;
for (i = 0; i < dmac->n_channels; ++i)
usb_dmac_chan_remove(dmac, &dmac->channels[i]);
of_dma_controller_free(pdev->dev.of_node);
dma_async_device_unregister(&dmac->engine);
pm_runtime_disable(&pdev->dev);
return 0;
}
static void usb_dmac_shutdown(struct platform_device *pdev)
{
struct usb_dmac *dmac = platform_get_drvdata(pdev);
usb_dmac_stop(dmac);
}
static const struct of_device_id usb_dmac_of_ids[] = {
{ .compatible = "renesas,usb-dmac", },
{ /* Sentinel */ }
};
MODULE_DEVICE_TABLE(of, usb_dmac_of_ids);
static struct platform_driver usb_dmac_driver = {
.driver = {
.pm = &usb_dmac_pm,
.name = "usb-dmac",
.of_match_table = usb_dmac_of_ids,
},
.probe = usb_dmac_probe,
.remove = usb_dmac_remove,
.shutdown = usb_dmac_shutdown,
};
module_platform_driver(usb_dmac_driver);
MODULE_DESCRIPTION("Renesas USB DMA Controller Driver");
MODULE_AUTHOR("Yoshihiro Shimoda <yoshihiro.shimoda.uh@renesas.com>");
MODULE_LICENSE("GPL v2");
| kmihelich/linux-espressobin | drivers/dma/sh/usb-dmac.c | C | gpl-2.0 | 23,668 |
<?php
/**
* Solr Authority aspect of the Search Multi-class (Results)
*
* PHP version 5
*
* Copyright (C) Villanova University 2011.
*
* 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
*
* @category VuFind
* @package Search_SolrAuth
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
namespace VuFind\Search\SolrAuth;
/**
* Solr Authority Search Parameters
*
* @category VuFind
* @package Search_SolrAuth
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
class Results extends \VuFind\Search\Solr\Results
{
/**
* Constructor
*
* @param \VuFind\Search\Base\Params $params Object representing user search
* parameters.
*/
public function __construct(\VuFind\Search\Base\Params $params)
{
parent::__construct($params);
$this->backendId = 'SolrAuth';
}
}
| ebsco/vufind | module/VuFind/src/VuFind/Search/SolrAuth/Results.php | PHP | gpl-2.0 | 1,686 |
#!/usr/bin/env python
from runtest import TestBase
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'abc', """
# DURATION TID FUNCTION
62.202 us [28141] | __cxa_atexit();
[28141] | main() {
[28141] | a() {
[28141] | b() {
[28141] | c() {
0.753 us [28141] | getpid();
1.430 us [28141] | } /* c */
1.915 us [28141] | } /* b */
2.405 us [28141] | } /* a */
3.005 us [28141] | } /* main */
""")
| namhyung/uftrace | tests/t001_basic.py | Python | gpl-2.0 | 530 |
/*
* 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 opennlp.tools.doccat;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
/**
* Context generator for document categorizer
*/
class DocumentCategorizerContextGenerator {
private FeatureGenerator[] mFeatureGenerators;
DocumentCategorizerContextGenerator(FeatureGenerator... featureGenerators) {
mFeatureGenerators = featureGenerators;
}
public String[] getContext(String[] text, Map<String, Object> extraInformation) {
Collection<String> context = new LinkedList<>();
for (FeatureGenerator mFeatureGenerator : mFeatureGenerators) {
Collection<String> extractedFeatures =
mFeatureGenerator.extractFeatures(text, extraInformation);
context.addAll(extractedFeatures);
}
return context.toArray(new String[context.size()]);
}
}
| manjeetk09/GoogleScrapper | opennlp/tools/doccat/DocumentCategorizerContextGenerator.java | Java | gpl-2.0 | 1,622 |
using System;
using System.Collections;
namespace FSpot {
public class DirectoryAdaptor : GroupAdaptor {
System.Collections.DictionaryEntry [] dirs;
// FIXME store the Photo.Id list here not just the count
private class Group : IComparer {
public int Count = 1;
public int Compare (object obj1, object obj2)
{
// FIXME use a real exception
if (obj1 is DictionaryEntry && obj2 is DictionaryEntry)
return Compare ((DictionaryEntry)obj1, (DictionaryEntry)obj2);
else
throw new Exception ("I can't compare that");
}
private static int Compare (DictionaryEntry de1, DictionaryEntry de2)
{
return string.Compare ((string)de1.Key, (string)de2.Key);
}
}
public override event GlassSetHandler GlassSet;
public override void SetGlass (int group)
{
if (group < 0 || group > dirs.Length)
return;
Console.WriteLine ("Selected Path {0}", dirs [group].Key);
int item = LookupItem (group);
if (GlassSet != null)
GlassSet (this, item);
}
public override int Count ()
{
return dirs.Length;
}
public override string GlassLabel (int item)
{
return (string)dirs [item].Key;
}
public override string TickLabel (int item)
{
return null;
}
public override int Value (int item)
{
return ((DirectoryAdaptor.Group)dirs [item].Value).Count;
}
public override event ChangedHandler Changed;
protected override void Reload ()
{
System.Collections.Hashtable ht = new System.Collections.Hashtable ();
Photo [] photos = query.Store.Query ((Tag [])null, null, null, null);
foreach (Photo p in photos) {
if (ht.Contains (p.DirectoryPath)) {
DirectoryAdaptor.Group group = (DirectoryAdaptor.Group) ht [p.DirectoryPath];
group.Count += 1;
} else
ht [p.DirectoryPath] = new DirectoryAdaptor.Group ();
}
Console.WriteLine ("Count = {0}", ht.Count);
dirs = new System.Collections.DictionaryEntry [ht.Count];
ht.CopyTo (dirs, 0);
Array.Sort (dirs, new DirectoryAdaptor.Group ());
Array.Sort (query.Photos, new Photo.CompareDirectory ());
if (!order_ascending) {
Array.Reverse (dirs);
Array.Reverse (query.Photos);
}
if (Changed != null)
Changed (this);
}
public override int IndexFromPhoto(FSpot.IBrowsableItem item)
{
Photo photo = (Photo)item;
string directory_path = photo.DirectoryPath;
for (int i = 0; i < dirs.Length; i++) {
if ((string)dirs [i].Key == directory_path) {
return i;
}
}
// FIXME not truly implemented
return 0;
}
public override FSpot.IBrowsableItem PhotoFromIndex (int item)
{
return query.Items [LookupItem (item)];
}
private int LookupItem (int group)
{
int i = 0;
while (i < query.Count) {
if (((Photo)(query [i])).DirectoryPath == (string)dirs [group].Key) {
return i;
}
i++;
}
return 0;
}
public DirectoryAdaptor (PhotoQuery query)
: base (query)
{ }
}
}
| Hibary/facedetect-f-spot | src/DirectoryAdaptor.cs | C# | gpl-2.0 | 2,996 |
<?php
class AIOWPSecurity_General_Init_Tasks
{
function __construct(){
global $aio_wp_security;
if ($aio_wp_security->configs->get_value('aiowps_enable_rename_login_page') == '1') {
add_action( 'widgets_init', array(&$this, 'remove_standard_wp_meta_widget' ));
add_filter( 'retrieve_password_message', array(&$this, 'decode_reset_pw_msg'), 10, 4); //Fix for non decoded html entities in password reset link
}
add_action('admin_notices', array(&$this,'reapply_htaccess_rules_notice'));
if(isset($_REQUEST['aiowps_reapply_htaccess'])){
if(strip_tags($_REQUEST['aiowps_reapply_htaccess']) == 1){
include_once ('wp-security-installer.php');
if(AIOWPSecurity_Installer::reactivation_tasks()){
echo '<div class="updated"><p>The AIOWPS .htaccess rules were successfully re-inserted.</p></div>';
}else{
echo '<div class="error"><p>AIOWPS encountered an error when trying to write to your .htaccess file. Please check the logs.</p></div>';
}
}elseif(strip_tags($_REQUEST['aiowps_reapply_htaccess']) == 2){
//Don't re-write the rules and just delete the temp config item
delete_option('aiowps_temp_configs');
}
}
if($aio_wp_security->configs->get_value('aiowps_prevent_site_display_inside_frame') == '1'){
send_frame_options_header(); //send X-Frame-Options: SAMEORIGIN in HTTP header
}
if($aio_wp_security->configs->get_value('aiowps_remove_wp_generator_meta_info') == '1'){
add_filter('the_generator', array(&$this,'remove_wp_generator_meta_info'));
}
//For the cookie based brute force prevention feature
if($aio_wp_security->configs->get_value('aiowps_enable_brute_force_attack_prevention') == 1){
$bfcf_secret_word = $aio_wp_security->configs->get_value('aiowps_brute_force_secret_word');
if(isset($_GET[$bfcf_secret_word])){
//If URL contains secret word in query param then set cookie and then redirect to the login page
AIOWPSecurity_Utility::set_cookie_value($bfcf_secret_word, "1");
AIOWPSecurity_Utility::redirect_to_url(AIOWPSEC_WP_URL."/wp-admin");
}
}
//For user unlock request feature
if(isset($_POST['aiowps_unlock_request']) || isset($_POST['aiowps_wp_submit_unlock_request'])){
nocache_headers();
remove_action('wp_head','head_addons',7);
include_once(AIO_WP_SECURITY_PATH.'/other-includes/wp-security-unlock-request.php');
exit();
}
if(isset($_GET['aiowps_auth_key'])){
//If URL contains unlock key in query param then process the request
$unlock_key = strip_tags($_GET['aiowps_auth_key']);
AIOWPSecurity_User_Login::process_unlock_request($unlock_key);
}
//For honeypot feature
if(isset($_POST['aio_special_field'])){
$special_field_value = strip_tags($_POST['aio_special_field']);
if(!empty($special_field_value)){
//This means a robot has submitted the login form!
//Redirect back to its localhost
AIOWPSecurity_Utility::redirect_to_url('http://127.0.0.1');
}
}
//For 404 IP lockout feature
if($aio_wp_security->configs->get_value('aiowps_enable_404_IP_lockout') == '1'){
if (!is_user_logged_in() || !current_user_can('administrator')) {
$this->do_404_lockout_tasks();
}
}
//For login captcha feature
if($aio_wp_security->configs->get_value('aiowps_enable_login_captcha') == '1'){
if (!is_user_logged_in()) {
add_action('login_form', array(&$this, 'insert_captcha_question_form'));
}
}
//For custom login form captcha feature, ie, when wp_login_form() function is used to generate login form
if($aio_wp_security->configs->get_value('aiowps_enable_custom_login_captcha') == '1'){
if (!is_user_logged_in()) {
add_filter( 'login_form_middle', array(&$this, 'insert_captcha_custom_login'), 10, 2); //For cases where the WP wp_login_form() function is used
}
}
//For honeypot feature
if($aio_wp_security->configs->get_value('aiowps_enable_login_honeypot') == '1'){
if (!is_user_logged_in()) {
add_action('login_form', array(&$this, 'insert_honeypot_hidden_field'));
}
}
//For lost password captcha feature
if($aio_wp_security->configs->get_value('aiowps_enable_lost_password_captcha') == '1'){
if (!is_user_logged_in()) {
add_action('lostpassword_form', array(&$this, 'insert_captcha_question_form'));
add_action('lostpassword_post', array(&$this, 'process_lost_password_form_post'));
}
}
//For registration page captcha feature
if (AIOWPSecurity_Utility::is_multisite_install()){
$blog_id = get_current_blog_id();
switch_to_blog($blog_id);
if($aio_wp_security->configs->get_value('aiowps_enable_registration_page_captcha') == '1'){
if (!is_user_logged_in()) {
add_action('signup_extra_fields', array(&$this, 'insert_captcha_question_form_multi'));
//add_action('preprocess_signup_form', array(&$this, 'process_signup_form_multi'));
add_filter( 'wpmu_validate_user_signup', array(&$this, 'process_signup_form_multi') );
}
}
restore_current_blog();
}else{
if($aio_wp_security->configs->get_value('aiowps_enable_registration_page_captcha') == '1'){
if (!is_user_logged_in()) {
add_action('register_form', array(&$this, 'insert_captcha_question_form'));
}
}
}
//For comment captcha feature
if (AIOWPSecurity_Utility::is_multisite_install()){
$blog_id = get_current_blog_id();
switch_to_blog($blog_id);
if($aio_wp_security->configs->get_value('aiowps_enable_comment_captcha') == '1'){
add_action( 'comment_form_after_fields', array(&$this, 'insert_captcha_question_form'), 1 );
add_action( 'comment_form_logged_in_after', array(&$this, 'insert_captcha_question_form'), 1 );
add_filter( 'preprocess_comment', array(&$this, 'process_comment_post') );
}
restore_current_blog();
}else{
if($aio_wp_security->configs->get_value('aiowps_enable_comment_captcha') == '1'){
add_action( 'comment_form_after_fields', array(&$this, 'insert_captcha_question_form'), 1 );
add_action( 'comment_form_logged_in_after', array(&$this, 'insert_captcha_question_form'), 1 );
add_filter( 'preprocess_comment', array(&$this, 'process_comment_post') );
}
}
//For buddypress registration captcha feature
if($aio_wp_security->configs->get_value('aiowps_enable_bp_register_captcha') == '1'){
add_action('bp_account_details_fields', array(&$this, 'insert_captcha_question_form'));
add_action('bp_signup_validate', array(&$this, 'buddy_press_signup_validate_captcha'));
}
//For feature which displays logged in users
$this->update_logged_in_user_transient();
//For block fake googlebots feature
if($aio_wp_security->configs->get_value('aiowps_block_fake_googlebots') == '1'){
include_once(AIO_WP_SECURITY_PATH.'/classes/wp-security-bot-protection.php');
AIOWPSecurity_Fake_Bot_Protection::block_fake_googlebots();
}
//For 404 event logging
if($aio_wp_security->configs->get_value('aiowps_enable_404_logging') == '1'){
add_action('wp_head', array(&$this, 'check_404_event'));
}
//Add more tasks that need to be executed at init time
}
function remove_standard_wp_meta_widget()
{
unregister_widget('WP_Widget_Meta');
}
function remove_wp_generator_meta_info()
{
return '';
}
function do_404_lockout_tasks(){
global $aio_wp_security;
$redirect_url = $aio_wp_security->configs->get_value('aiowps_404_lock_redirect_url'); //This is the redirect URL for blocked users
$visitor_ip = AIOWPSecurity_Utility_IP::get_user_ip_address();
$is_locked = AIOWPSecurity_Utility::check_locked_ip($visitor_ip);
if($is_locked){
//redirect blocked user to configured URL
AIOWPSecurity_Utility::redirect_to_url($redirect_url);
}else{
//allow through
}
}
function update_logged_in_user_transient(){
if(is_user_logged_in()){
$current_user_ip = AIOWPSecurity_Utility_IP::get_user_ip_address();
// get the logged in users list from transients entry
$logged_in_users = (AIOWPSecurity_Utility::is_multisite_install() ? get_site_transient('users_online') : get_transient('users_online'));
$current_user = wp_get_current_user();
$current_user = $current_user->ID;
$current_time = current_time('timestamp');
$current_user_info = array("user_id" => $current_user, "last_activity" => $current_time, "ip_address" => $current_user_ip); //We will store last activity time and ip address in transient entry
if($logged_in_users === false || $logged_in_users == NULL){
$logged_in_users = array();
$logged_in_users[] = $current_user_info;
AIOWPSecurity_Utility::is_multisite_install() ? set_site_transient('users_online', $logged_in_users, 30 * 60) : set_transient('users_online', $logged_in_users, 30 * 60);
}
else
{
$key = 0;
$do_nothing = false;
$update_existing = false;
$item_index = 0;
foreach ($logged_in_users as $value)
{
if($value['user_id'] == $current_user && strcmp($value['ip_address'], $current_user_ip) == 0)
{
if ($value['last_activity'] < ($current_time - (15 * 60)))
{
$update_existing = true;
$item_index = $key;
break;
}else{
$do_nothing = true;
break;
}
}
$key++;
}
if($update_existing)
{
//Update transient if the last activity was less than 15 min ago for this user
$logged_in_users[$item_index] = $current_user_info;
AIOWPSecurity_Utility::is_multisite_install() ? set_site_transient('users_online', $logged_in_users, 30 * 60) : set_transient('users_online', $logged_in_users, 30 * 60);
}else if($do_nothing){
//Do nothing
}else{
$logged_in_users[] = $current_user_info;
AIOWPSecurity_Utility::is_multisite_install() ? set_site_transient('users_online', $logged_in_users, 30 * 60) : set_transient('users_online', $logged_in_users, 30 * 60);
}
}
}
}
function insert_captcha_custom_login($cust_html_code, $args)
{
global $aio_wp_security;
$cap_form = '<p class="aiowps-captcha"><label>'.__('Please enter an answer in digits:','aiowpsecurity').'</label>';
$cap_form .= '<div class="aiowps-captcha-equation"><strong>';
$maths_question_output = $aio_wp_security->captcha_obj->generate_maths_question();
$cap_form .= $maths_question_output . '</strong></div></p>';
$cust_html_code .= $cap_form;
return $cust_html_code;
}
function insert_captcha_question_form_multi($error)
{
global $aio_wp_security;
$aio_wp_security->captcha_obj->display_captcha_form();
}
function process_signup_form_multi($result)
{
global $aio_wp_security;
//Check if captcha enabled
if (array_key_exists('aiowps-captcha-answer', $_POST)) //If the register form with captcha was submitted then do some processing
{
isset($_POST['aiowps-captcha-answer'])?$captcha_answer = strip_tags(trim($_POST['aiowps-captcha-answer'])): $captcha_answer = '';
$captcha_secret_string = $aio_wp_security->configs->get_value('aiowps_captcha_secret_key');
$submitted_encoded_string = base64_encode($_POST['aiowps-captcha-temp-string'].$captcha_secret_string.$captcha_answer);
if($submitted_encoded_string !== $_POST['aiowps-captcha-string-info'])
{
//This means a wrong answer was entered
$result['errors']->add('generic', __('<strong>ERROR</strong>: Your answer was incorrect - please try again.', 'aiowpsecurity'));
}
}
return $result;
}
function insert_captcha_question_form(){
global $aio_wp_security;
$aio_wp_security->captcha_obj->display_captcha_form();
}
function insert_honeypot_hidden_field(){
$honey_input = '<p style="display: none;"><label>'.__('Enter something special:','aiowpsecurity').'</label>';
$honey_input .= '<input name="aio_special_field" type="text" id="aio_special_field" class="aio_special_field" /></p>';
echo $honey_input;
}
function process_comment_post( $comment )
{
global $aio_wp_security;
if (is_user_logged_in()) {
return $comment;
}
//Don't process captcha for comment replies inside admin menu
if (isset( $_REQUEST['action'] ) && $_REQUEST['action'] == 'replyto-comment' &&
(check_ajax_referer('replyto-comment', '_ajax_nonce', false) || check_ajax_referer('replyto-comment', '_ajax_nonce-replyto-comment', false))) {
return $comment;
}
//Don't do captcha for pingback/trackback
if ($comment['comment_type'] != '' && $comment['comment_type'] != 'comment') {
return $comment;
}
if (isset($_REQUEST['aiowps-captcha-answer']))
{
// If answer is empty
if ($_REQUEST['aiowps-captcha-answer'] == ''){
wp_die( __('Please enter an answer in the CAPTCHA field.', 'aiowpsecurity' ) );
}
$captcha_answer = trim($_REQUEST['aiowps-captcha-answer']);
$captcha_secret_string = $aio_wp_security->configs->get_value('aiowps_captcha_secret_key');
$submitted_encoded_string = base64_encode($_POST['aiowps-captcha-temp-string'].$captcha_secret_string.$captcha_answer);
if ($_REQUEST['aiowps-captcha-string-info'] === $submitted_encoded_string){
//Correct answer given
return($comment);
}else{
//Wrong answer
wp_die( __('Error: You entered an incorrect CAPTCHA answer. Please go back and try again.', 'aiowpsecurity'));
}
}
}
function process_lost_password_form_post()
{
global $aio_wp_security;
//Check if captcha enabled
if ($aio_wp_security->configs->get_value('aiowps_enable_lost_password_captcha') == '1')
{
if (array_key_exists('aiowps-captcha-answer', $_POST)) //If the lost pass form with captcha was submitted then do some processing
{
isset($_POST['aiowps-captcha-answer'])?($captcha_answer = strip_tags(trim($_POST['aiowps-captcha-answer']))):($captcha_answer = '');
$captcha_secret_string = $aio_wp_security->configs->get_value('aiowps_captcha_secret_key');
$submitted_encoded_string = base64_encode($_POST['aiowps-captcha-temp-string'].$captcha_secret_string.$captcha_answer);
if($submitted_encoded_string !== $_POST['aiowps-captcha-string-info'])
{
add_filter('allow_password_reset', array(&$this, 'add_lostpassword_captcha_error_msg'));
}
}
}
}
function add_lostpassword_captcha_error_msg()
{
//Insert an error just before the password reset process kicks in
return new WP_Error('aiowps_captcha_error',__('<strong>ERROR</strong>: Your answer was incorrect - please try again.', 'aiowpsecurity'));
}
function check_404_event()
{
if(is_404()){
//This means a 404 event has occurred - let's log it!
AIOWPSecurity_Utility::event_logger('404');
}
}
function buddy_press_signup_validate_captcha($errors)
{
global $bp, $aio_wp_security;
//Check if captcha enabled
if (array_key_exists('aiowps-captcha-answer', $_POST)) //If the register form with captcha was submitted then do some processing
{
isset($_POST['aiowps-captcha-answer'])?$captcha_answer = strip_tags(trim($_POST['aiowps-captcha-answer'])): $captcha_answer = '';
$captcha_secret_string = $aio_wp_security->configs->get_value('aiowps_captcha_secret_key');
$submitted_encoded_string = base64_encode($_POST['aiowps-captcha-temp-string'].$captcha_secret_string.$captcha_answer);
if($submitted_encoded_string !== $_POST['aiowps-captcha-string-info'])
{
//This means a wrong answer was entered
$bp->signup->errors['aiowps-captcha-answer'] = __('Your CAPTCHA answer was incorrect - please try again.', 'aiowpsecurity');
}
}
return;
}
//Displays a notice message if the plugin was reactivated after being initially deactivated.
//Notice message gives users option of re-applying the aiowps rules which were deleted from the .htaccess when deactivation occurred
function reapply_htaccess_rules_notice()
{
if (get_option('aiowps_temp_configs') !== FALSE){
echo '<div class="updated"><p>Would you like All In One WP Security & Firewall to re-insert the security rules in your .htaccess file which were cleared when you deactivated the plugin? <a href="admin.php?page='.AIOWPSEC_MENU_SLUG_PREFIX.'&aiowps_reapply_htaccess=1" class="button-primary">Yes</a> <a href="admin.php?page='.AIOWPSEC_MENU_SLUG_PREFIX.'&aiowps_reapply_htaccess=2" class="button-primary">No</a></p></div>';
}
}
//This is a fix for cases when the password reset URL in the email was not decoding all html entities properly
function decode_reset_pw_msg($message, $key, $user_login, $user_data)
{
global $aio_wp_security;
$message = html_entity_decode($message);
return $message;
}
} | toyo213/go-ride-news | wp-content/plugins/all-in-one-wp-security-and-firewall/classes/wp-security-general-init-tasks.php | PHP | gpl-2.0 | 19,886 |
--木遁封印式
function c1802450.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE)
e1:SetTarget(c1802450.target1)
e1:SetOperation(c1802450.operation)
c:RegisterEffect(e1)
--remove
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(1802450,1))
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetHintTiming(0,TIMING_END_PHASE)
e2:SetCost(c1802450.cost2)
e2:SetTarget(c1802450.target2)
e2:SetOperation(c1802450.operation)
c:RegisterEffect(e2)
end
function c1802450.cfilter(c)
return c:IsFaceup() and c:IsAttribute(ATTRIBUTE_EARTH)
end
function c1802450.target1(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and chkc:IsAbleToRemove() end
if chk==0 then return true end
if Duel.CheckReleaseGroup(tp,c1802450.cfilter,1,nil)
and Duel.IsExistingTarget(Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,1,nil) and Duel.SelectYesNo(tp,aux.Stringid(1802450,0)) then
e:SetProperty(EFFECT_FLAG_CARD_TARGET)
local cg=Duel.SelectReleaseGroup(tp,c1802450.cfilter,1,1,nil)
Duel.Release(cg,REASON_COST)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,1,2,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),0,0)
e:GetHandler():RegisterFlagEffect(1802450,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
else e:SetProperty(0) end
end
function c1802450.cost2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,c1802450.cfilter,1,nil) end
local cg=Duel.SelectReleaseGroup(tp,c1802450.cfilter,1,1,nil)
Duel.Release(cg,REASON_COST)
end
function c1802450.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and chkc:IsAbleToRemove() end
if chk==0 then return e:GetHandler():GetFlagEffect(1802450)==0
and Duel.IsExistingTarget(Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,1,2,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),0,0)
e:GetHandler():RegisterFlagEffect(1802450,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
end
function c1802450.operation(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
if not g then return end
g=g:Filter(Card.IsRelateToEffect,nil,e)
Duel.Remove(g,POS_FACEUP,REASON_EFFECT)
end
| SalvationDevelopment/Salvation-Scripts-TCG | c1802450.lua | Lua | gpl-2.0 | 2,685 |
/*
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.crypto;
import java.io.*;
/**
* A CipherOutputStream is composed of an OutputStream and a Cipher so
* that write() methods first process the data before writing them out
* to the underlying OutputStream. The cipher must be fully
* initialized before being used by a CipherOutputStream.
*
* <p> For example, if the cipher is initialized for encryption, the
* CipherOutputStream will attempt to encrypt data before writing out the
* encrypted data.
*
* <p> This class adheres strictly to the semantics, especially the
* failure semantics, of its ancestor classes
* java.io.OutputStream and java.io.FilterOutputStream. This class
* has exactly those methods specified in its ancestor classes, and
* overrides them all. Moreover, this class catches all exceptions
* that are not thrown by its ancestor classes. In particular, this
* class catches BadPaddingException and other exceptions thrown by
* failed integrity checks during decryption. These exceptions are not
* re-thrown, so the client will not be informed that integrity checks
* failed. Because of this behavior, this class may not be suitable
* for use with decryption in an authenticated mode of operation (e.g. GCM)
* if the application requires explicit notification when authentication
* fails. Such an application can use the Cipher API directly as an
* alternative to using this class.
*
* <p> It is crucial for a programmer using this class not to use
* methods that are not defined or overriden in this class (such as a
* new method or constructor that is later added to one of the super
* classes), because the design and implementation of those methods
* are unlikely to have considered security impact with regard to
* CipherOutputStream.
*
* @author Li Gong
* @see java.io.OutputStream
* @see java.io.FilterOutputStream
* @see javax.crypto.Cipher
* @see javax.crypto.CipherInputStream
*
* @since 1.4
*/
public class CipherOutputStream extends FilterOutputStream {
// the cipher engine to use to process stream data
private Cipher cipher;
// the underlying output stream
private OutputStream output;
/* the buffer holding one byte of incoming data */
private byte[] ibuffer = new byte[1];
// the buffer holding data ready to be written out
private byte[] obuffer;
// stream status
private boolean closed = false;
/**
*
* Constructs a CipherOutputStream from an OutputStream and a
* Cipher.
* <br>Note: if the specified output stream or cipher is
* null, a NullPointerException may be thrown later when
* they are used.
*
* @param os the OutputStream object
* @param c an initialized Cipher object
*/
public CipherOutputStream(OutputStream os, Cipher c) {
super(os);
output = os;
cipher = c;
};
/**
* Constructs a CipherOutputStream from an OutputStream without
* specifying a Cipher. This has the effect of constructing a
* CipherOutputStream using a NullCipher.
* <br>Note: if the specified output stream is null, a
* NullPointerException may be thrown later when it is used.
*
* @param os the OutputStream object
*/
protected CipherOutputStream(OutputStream os) {
super(os);
output = os;
cipher = new NullCipher();
}
/**
* Writes the specified byte to this output stream.
*
* @param b the <code>byte</code>.
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void write(int b) throws IOException {
ibuffer[0] = (byte) b;
obuffer = cipher.update(ibuffer, 0, 1);
if (obuffer != null) {
output.write(obuffer);
obuffer = null;
}
};
/**
* Writes <code>b.length</code> bytes from the specified byte array
* to this output stream.
* <p>
* The <code>write</code> method of
* <code>CipherOutputStream</code> calls the <code>write</code>
* method of three arguments with the three arguments
* <code>b</code>, <code>0</code>, and <code>b.length</code>.
*
* @param b the data.
* @exception NullPointerException if <code>b</code> is null.
* @exception IOException if an I/O error occurs.
* @see javax.crypto.CipherOutputStream#write(byte[], int, int)
* @since JCE1.2
*/
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this output stream.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void write(byte b[], int off, int len) throws IOException {
obuffer = cipher.update(b, off, len);
if (obuffer != null) {
output.write(obuffer);
obuffer = null;
}
}
/**
* Flushes this output stream by forcing any buffered output bytes
* that have already been processed by the encapsulated cipher object
* to be written out.
*
* <p>Any bytes buffered by the encapsulated cipher
* and waiting to be processed by it will not be written out. For example,
* if the encapsulated cipher is a block cipher, and the total number of
* bytes written using one of the <code>write</code> methods is less than
* the cipher's block size, no bytes will be written out.
*
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void flush() throws IOException {
if (obuffer != null) {
output.write(obuffer);
obuffer = null;
}
output.flush();
}
/**
* Closes this output stream and releases any system resources
* associated with this stream.
* <p>
* This method invokes the <code>doFinal</code> method of the encapsulated
* cipher object, which causes any bytes buffered by the encapsulated
* cipher to be processed. The result is written out by calling the
* <code>flush</code> method of this output stream.
* <p>
* This method resets the encapsulated cipher object to its initial state
* and calls the <code>close</code> method of the underlying output
* stream.
*
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
try {
obuffer = cipher.doFinal();
} catch (IllegalBlockSizeException | BadPaddingException e) {
obuffer = null;
}
try {
flush();
} catch (IOException ignored) {}
out.close();
}
}
| JetBrains/jdk8u_jdk | src/share/classes/javax/crypto/CipherOutputStream.java | Java | gpl-2.0 | 8,241 |
/* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/i2c.h>
#include <linux/i2c/sx150x.h>
#include <linux/i2c/isl9519.h>
#include <linux/gpio.h>
#include <linux/msm_ssbi.h>
#include <linux/regulator/gpio-regulator.h>
#include <linux/mfd/pm8xxx/pm8921.h>
#include <linux/mfd/pm8xxx/pm8xxx-adc.h>
#include <linux/regulator/consumer.h>
#include <linux/spi/spi.h>
#include <linux/slimbus/slimbus.h>
#include <linux/bootmem.h>
#include <linux/msm_kgsl.h>
#ifdef CONFIG_ANDROID_PMEM
#include <linux/android_pmem.h>
#endif
#include <linux/cyttsp.h>
#include <linux/dma-mapping.h>
#include <linux/platform_data/qcom_crypto_device.h>
#include <linux/platform_data/qcom_wcnss_device.h>
#include <linux/leds.h>
#include <linux/leds-pm8xxx.h>
#include <linux/i2c/atmel_mxt_ts.h>
#include <linux/msm_tsens.h>
#include <linux/ks8851.h>
#include <linux/i2c/isa1200.h>
#include <linux/gpio_keys.h>
#include <linux/memory.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/setup.h>
#include <asm/hardware/gic.h>
#include <asm/mach/mmc.h>
#include <mach/board.h>
#include <mach/msm_iomap.h>
#include <mach/msm_spi.h>
#ifdef CONFIG_USB_MSM_OTG_72K
#include <mach/msm_hsusb.h>
#else
#include <linux/usb/msm_hsusb.h>
#endif
#include <linux/usb/android.h>
#include <mach/usbdiag.h>
#include <mach/socinfo.h>
#include <mach/rpm.h>
#include <mach/gpio.h>
#include <mach/gpiomux.h>
#include <mach/msm_bus_board.h>
#include <mach/msm_memtypes.h>
#include <mach/dma.h>
#include <mach/msm_xo.h>
#include <mach/restart.h>
#ifdef CONFIG_WCD9310_CODEC
#include <linux/slimbus/slimbus.h>
#include <linux/mfd/wcd9310/core.h>
#include <linux/mfd/wcd9310/pdata.h>
#endif
#include <linux/ion.h>
#include <mach/ion.h>
#include <mach/mdm2.h>
#include <mach/msm_rtb.h>
#include "timer.h"
#include "devices.h"
#include "devices-msm8x60.h"
#include "spm.h"
#include "pm.h"
#include <mach/cpuidle.h>
#include "rpm_resources.h"
#include <mach/mpm.h>
#include "acpuclock.h"
#include "rpm_log.h"
#include "smd_private.h"
#include "pm-boot.h"
#include "msm_watchdog.h"
#include "board-8930.h"
static struct platform_device msm_fm_platform_init = {
.name = "iris_fm",
.id = -1,
};
#define KS8851_RST_GPIO 89
#define KS8851_IRQ_GPIO 90
#define HAP_SHIFT_LVL_OE_GPIO 47
#if defined(CONFIG_GPIO_SX150X) || defined(CONFIG_GPIO_SX150X_MODULE)
struct sx150x_platform_data msm8930_sx150x_data[] = {
[SX150X_CAM] = {
.gpio_base = GPIO_CAM_EXPANDER_BASE,
.oscio_is_gpo = false,
.io_pullup_ena = 0x0,
.io_pulldn_ena = 0xc0,
.io_open_drain_ena = 0x0,
.irq_summary = -1,
},
};
#endif
#define MSM_PMEM_ADSP_SIZE 0x7800000
#define MSM_PMEM_AUDIO_SIZE 0x2B4000
#ifdef CONFIG_FB_MSM_HDMI_AS_PRIMARY
#define MSM_PMEM_SIZE 0x4000000 /* 64 Mbytes */
#else
#define MSM_PMEM_SIZE 0x2800000 /* 40 Mbytes */
#endif
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
#define MSM_PMEM_KERNEL_EBI1_SIZE 0x280000
#define MSM_ION_SF_SIZE MSM_PMEM_SIZE
#define MSM_ION_MM_FW_SIZE 0x200000 /* (2MB) */
#define MSM_ION_MM_SIZE MSM_PMEM_ADSP_SIZE
#define MSM_ION_QSECOM_SIZE 0x300000 /* (3MB) */
#define MSM_ION_MFC_SIZE SZ_8K
#define MSM_ION_AUDIO_SIZE MSM_PMEM_AUDIO_SIZE
#define MSM_ION_HEAP_NUM 8
#else
#define MSM_PMEM_KERNEL_EBI1_SIZE 0x110C000
#define MSM_ION_HEAP_NUM 1
#endif
#ifdef CONFIG_KERNEL_PMEM_EBI_REGION
static unsigned pmem_kernel_ebi1_size = MSM_PMEM_KERNEL_EBI1_SIZE;
static int __init pmem_kernel_ebi1_size_setup(char *p)
{
pmem_kernel_ebi1_size = memparse(p, NULL);
return 0;
}
early_param("pmem_kernel_ebi1_size", pmem_kernel_ebi1_size_setup);
#endif
#ifdef CONFIG_ANDROID_PMEM
static unsigned pmem_size = MSM_PMEM_SIZE;
static int __init pmem_size_setup(char *p)
{
pmem_size = memparse(p, NULL);
return 0;
}
early_param("pmem_size", pmem_size_setup);
static unsigned pmem_adsp_size = MSM_PMEM_ADSP_SIZE;
static int __init pmem_adsp_size_setup(char *p)
{
pmem_adsp_size = memparse(p, NULL);
return 0;
}
early_param("pmem_adsp_size", pmem_adsp_size_setup);
static unsigned pmem_audio_size = MSM_PMEM_AUDIO_SIZE;
static int __init pmem_audio_size_setup(char *p)
{
pmem_audio_size = memparse(p, NULL);
return 0;
}
early_param("pmem_audio_size", pmem_audio_size_setup);
#endif
#ifdef CONFIG_ANDROID_PMEM
#ifndef CONFIG_MSM_MULTIMEDIA_USE_ION
static struct android_pmem_platform_data android_pmem_pdata = {
.name = "pmem",
.allocator_type = PMEM_ALLOCATORTYPE_ALLORNOTHING,
.cached = 1,
.memory_type = MEMTYPE_EBI1,
};
static struct platform_device android_pmem_device = {
.name = "android_pmem",
.id = 0,
.dev = {.platform_data = &android_pmem_pdata},
};
static struct android_pmem_platform_data android_pmem_adsp_pdata = {
.name = "pmem_adsp",
.allocator_type = PMEM_ALLOCATORTYPE_BITMAP,
.cached = 0,
.memory_type = MEMTYPE_EBI1,
};
static struct platform_device android_pmem_adsp_device = {
.name = "android_pmem",
.id = 2,
.dev = { .platform_data = &android_pmem_adsp_pdata },
};
#endif
static struct android_pmem_platform_data android_pmem_audio_pdata = {
.name = "pmem_audio",
.allocator_type = PMEM_ALLOCATORTYPE_BITMAP,
.cached = 0,
.memory_type = MEMTYPE_EBI1,
};
static struct platform_device android_pmem_audio_device = {
.name = "android_pmem",
.id = 4,
.dev = { .platform_data = &android_pmem_audio_pdata },
};
#endif
#define DSP_RAM_BASE_8960 0x8da00000
#define DSP_RAM_SIZE_8960 0x1800000
static int dspcrashd_pdata_8960 = 0xDEADDEAD;
static struct resource resources_dspcrashd_8960[] = {
{
.name = "msm_dspcrashd",
.start = DSP_RAM_BASE_8960,
.end = DSP_RAM_BASE_8960 + DSP_RAM_SIZE_8960,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device msm_device_dspcrashd_8960 = {
.name = "msm_dspcrashd",
.num_resources = ARRAY_SIZE(resources_dspcrashd_8960),
.resource = resources_dspcrashd_8960,
.dev = { .platform_data = &dspcrashd_pdata_8960 },
};
static struct memtype_reserve msm8930_reserve_table[] __initdata = {
[MEMTYPE_SMI] = {
},
[MEMTYPE_EBI0] = {
.flags = MEMTYPE_FLAGS_1M_ALIGN,
},
[MEMTYPE_EBI1] = {
.flags = MEMTYPE_FLAGS_1M_ALIGN,
},
};
#if defined(CONFIG_MSM_RTB)
static struct msm_rtb_platform_data msm_rtb_pdata = {
.size = SZ_1M,
};
static int __init msm_rtb_set_buffer_size(char *p)
{
int s;
s = memparse(p, NULL);
msm_rtb_pdata.size = ALIGN(s, SZ_4K);
return 0;
}
early_param("msm_rtb_size", msm_rtb_set_buffer_size);
static struct platform_device msm_rtb_device = {
.name = "msm_rtb",
.id = -1,
.dev = {
.platform_data = &msm_rtb_pdata,
},
};
#endif
static void __init reserve_rtb_memory(void)
{
#if defined(CONFIG_MSM_RTB)
msm8930_reserve_table[MEMTYPE_EBI1].size += msm_rtb_pdata.size;
#endif
}
static void __init size_pmem_devices(void)
{
#ifdef CONFIG_ANDROID_PMEM
#ifndef CONFIG_MSM_MULTIMEDIA_USE_ION
android_pmem_adsp_pdata.size = pmem_adsp_size;
android_pmem_pdata.size = pmem_size;
#endif
android_pmem_audio_pdata.size = MSM_PMEM_AUDIO_SIZE;
#endif
}
static void __init reserve_memory_for(struct android_pmem_platform_data *p)
{
msm8930_reserve_table[p->memory_type].size += p->size;
}
static void __init reserve_pmem_memory(void)
{
#ifdef CONFIG_ANDROID_PMEM
#ifndef CONFIG_MSM_MULTIMEDIA_USE_ION
reserve_memory_for(&android_pmem_adsp_pdata);
reserve_memory_for(&android_pmem_pdata);
#endif
reserve_memory_for(&android_pmem_audio_pdata);
msm8930_reserve_table[MEMTYPE_EBI1].size += pmem_kernel_ebi1_size;
#endif
}
static int msm8930_paddr_to_memtype(unsigned int paddr)
{
return MEMTYPE_EBI1;
}
#ifdef CONFIG_ION_MSM
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
static struct ion_cp_heap_pdata cp_mm_ion_pdata = {
.permission_type = IPT_TYPE_MM_CARVEOUT,
.align = PAGE_SIZE,
};
static struct ion_cp_heap_pdata cp_mfc_ion_pdata = {
.permission_type = IPT_TYPE_MFC_SHAREDMEM,
.align = PAGE_SIZE,
};
static struct ion_co_heap_pdata co_ion_pdata = {
.adjacent_mem_id = INVALID_HEAP_ID,
.align = PAGE_SIZE,
};
static struct ion_co_heap_pdata fw_co_ion_pdata = {
.adjacent_mem_id = ION_CP_MM_HEAP_ID,
.align = SZ_128K,
};
#endif
/**
* These heaps are listed in the order they will be allocated. Due to
* video hardware restrictions and content protection the FW heap has to
* be allocated adjacent (below) the MM heap and the MFC heap has to be
* allocated after the MM heap to ensure MFC heap is not more than 256MB
* away from the base address of the FW heap.
* However, the order of FW heap and MM heap doesn't matter since these
* two heaps are taken care of by separate code to ensure they are adjacent
* to each other.
* Don't swap the order unless you know what you are doing!
*/
static struct ion_platform_data ion_pdata = {
.nr = MSM_ION_HEAP_NUM,
.heaps = {
{
.id = ION_SYSTEM_HEAP_ID,
.type = ION_HEAP_TYPE_SYSTEM,
.name = ION_VMALLOC_HEAP_NAME,
},
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
{
.id = ION_CP_MM_HEAP_ID,
.type = ION_HEAP_TYPE_CP,
.name = ION_MM_HEAP_NAME,
.size = MSM_ION_MM_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &cp_mm_ion_pdata,
},
{
.id = ION_MM_FIRMWARE_HEAP_ID,
.type = ION_HEAP_TYPE_CARVEOUT,
.name = ION_MM_FIRMWARE_HEAP_NAME,
.size = MSM_ION_MM_FW_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &fw_co_ion_pdata,
},
{
.id = ION_CP_MFC_HEAP_ID,
.type = ION_HEAP_TYPE_CP,
.name = ION_MFC_HEAP_NAME,
.size = MSM_ION_MFC_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &cp_mfc_ion_pdata,
},
{
.id = ION_SF_HEAP_ID,
.type = ION_HEAP_TYPE_CARVEOUT,
.name = ION_SF_HEAP_NAME,
.size = MSM_ION_SF_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &co_ion_pdata,
},
{
.id = ION_IOMMU_HEAP_ID,
.type = ION_HEAP_TYPE_IOMMU,
.name = ION_IOMMU_HEAP_NAME,
},
{
.id = ION_QSECOM_HEAP_ID,
.type = ION_HEAP_TYPE_CARVEOUT,
.name = ION_QSECOM_HEAP_NAME,
.size = MSM_ION_QSECOM_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &co_ion_pdata,
},
{
.id = ION_AUDIO_HEAP_ID,
.type = ION_HEAP_TYPE_CARVEOUT,
.name = ION_AUDIO_HEAP_NAME,
.size = MSM_ION_AUDIO_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &co_ion_pdata,
},
#endif
}
};
static struct platform_device ion_dev = {
.name = "ion-msm",
.id = 1,
.dev = { .platform_data = &ion_pdata },
};
#endif
static void reserve_ion_memory(void)
{
#if defined(CONFIG_ION_MSM) && defined(CONFIG_MSM_MULTIMEDIA_USE_ION)
msm8930_reserve_table[MEMTYPE_EBI1].size += MSM_ION_SF_SIZE;
msm8930_reserve_table[MEMTYPE_EBI1].size += MSM_ION_MM_SIZE;
msm8930_reserve_table[MEMTYPE_EBI1].size += MSM_ION_MM_FW_SIZE;
msm8930_reserve_table[MEMTYPE_EBI1].size += MSM_ION_MFC_SIZE;
msm8930_reserve_table[MEMTYPE_EBI1].size += MSM_ION_QSECOM_SIZE;
msm8930_reserve_table[MEMTYPE_EBI1].size += MSM_ION_AUDIO_SIZE;
#endif
}
static void __init reserve_mdp_memory(void)
{
msm8930_mdp_writeback(msm8930_reserve_table);
}
static void __init msm8930_calculate_reserve_sizes(void)
{
size_pmem_devices();
reserve_pmem_memory();
reserve_ion_memory();
reserve_mdp_memory();
reserve_rtb_memory();
}
static struct reserve_info msm8930_reserve_info __initdata = {
.memtype_reserve_table = msm8930_reserve_table,
.calculate_reserve_sizes = msm8930_calculate_reserve_sizes,
.paddr_to_memtype = msm8930_paddr_to_memtype,
};
static int msm8930_memory_bank_size(void)
{
return 1<<29;
}
static void __init locate_unstable_memory(void)
{
struct membank *mb = &meminfo.bank[meminfo.nr_banks - 1];
unsigned long bank_size;
unsigned long low, high;
bank_size = msm8930_memory_bank_size();
low = meminfo.bank[0].start;
high = mb->start + mb->size;
/* Check if 32 bit overflow occured */
if (high < mb->start)
high = ~0UL;
low &= ~(bank_size - 1);
if (high - low <= bank_size)
return;
msm8930_reserve_info.bank_size = bank_size;
#ifdef CONFIG_ENABLE_DMM
msm8930_reserve_info.low_unstable_address = mb->start -
MIN_MEMORY_BLOCK_SIZE + mb->size;
msm8930_reserve_info.max_unstable_size = MIN_MEMORY_BLOCK_SIZE;
pr_info("low unstable address %lx max size %lx bank size %lx\n",
msm8930_reserve_info.low_unstable_address,
msm8930_reserve_info.max_unstable_size,
msm8930_reserve_info.bank_size);
#else
msm8930_reserve_info.low_unstable_address = 0;
msm8930_reserve_info.max_unstable_size = 0;
#endif
}
static void __init place_movable_zone(void)
{
#ifdef CONFIG_ENABLE_DMM
movable_reserved_start = msm8930_reserve_info.low_unstable_address;
movable_reserved_size = msm8930_reserve_info.max_unstable_size;
pr_info("movable zone start %lx size %lx\n",
movable_reserved_start, movable_reserved_size);
#endif
}
static void __init msm8930_early_memory(void)
{
reserve_info = &msm8930_reserve_info;
locate_unstable_memory();
place_movable_zone();
}
static void __init msm8930_reserve(void)
{
msm_reserve();
}
static int msm8930_change_memory_power(u64 start, u64 size,
int change_type)
{
return soc_change_memory_power(start, size, change_type);
}
static void __init msm8930_allocate_memory_regions(void)
{
msm8930_allocate_fb_region();
}
#ifdef CONFIG_WCD9310_CODEC
#define TABLA_INTERRUPT_BASE (NR_MSM_IRQS + NR_GPIO_IRQS + NR_PM8921_IRQS)
/* Micbias setting is based on 8660 CDP/MTP/FLUID requirement
* 4 micbiases are used to power various analog and digital
* microphones operating at 1800 mV. Technically, all micbiases
* can source from single cfilter since all microphones operate
* at the same voltage level. The arrangement below is to make
* sure all cfilters are exercised. LDO_H regulator ouput level
* does not need to be as high as 2.85V. It is choosen for
* microphone sensitivity purpose.
*/
static struct tabla_pdata tabla_platform_data = {
.slimbus_slave_device = {
.name = "tabla-slave",
.e_addr = {0, 0, 0x10, 0, 0x17, 2},
},
.irq = MSM_GPIO_TO_INT(62),
.irq_base = TABLA_INTERRUPT_BASE,
.num_irqs = NR_TABLA_IRQS,
/*TODO: Replace this with right PM8038 gpio */
#ifndef MSM8930_PHASE_2
.reset_gpio = PM8921_GPIO_PM_TO_SYS(34),
#endif
.micbias = {
.ldoh_v = TABLA_LDOH_2P85_V,
.cfilt1_mv = 1800,
.cfilt2_mv = 1800,
.cfilt3_mv = 1800,
.bias1_cfilt_sel = TABLA_CFILT1_SEL,
.bias2_cfilt_sel = TABLA_CFILT2_SEL,
.bias3_cfilt_sel = TABLA_CFILT3_SEL,
.bias4_cfilt_sel = TABLA_CFILT3_SEL,
}
};
static struct slim_device msm_slim_tabla = {
.name = "tabla-slim",
.e_addr = {0, 1, 0x10, 0, 0x17, 2},
.dev = {
.platform_data = &tabla_platform_data,
},
};
static struct tabla_pdata tabla20_platform_data = {
.slimbus_slave_device = {
.name = "tabla-slave",
.e_addr = {0, 0, 0x60, 0, 0x17, 2},
},
.irq = MSM_GPIO_TO_INT(62),
.irq_base = TABLA_INTERRUPT_BASE,
.num_irqs = NR_TABLA_IRQS,
/*TODO: Replace this with right PM8038 gpio */
#ifndef MSM8930_PHASE_2
.reset_gpio = PM8921_GPIO_PM_TO_SYS(34),
#endif
.micbias = {
.ldoh_v = TABLA_LDOH_2P85_V,
.cfilt1_mv = 1800,
.cfilt2_mv = 1800,
.cfilt3_mv = 1800,
.bias1_cfilt_sel = TABLA_CFILT1_SEL,
.bias2_cfilt_sel = TABLA_CFILT2_SEL,
.bias3_cfilt_sel = TABLA_CFILT3_SEL,
.bias4_cfilt_sel = TABLA_CFILT3_SEL,
}
};
static struct slim_device msm_slim_tabla20 = {
.name = "tabla2x-slim",
.e_addr = {0, 1, 0x60, 0, 0x17, 2},
.dev = {
.platform_data = &tabla20_platform_data,
},
};
#endif
static struct slim_boardinfo msm_slim_devices[] = {
#ifdef CONFIG_WCD9310_CODEC
{
.bus_num = 1,
.slim_slave = &msm_slim_tabla,
},
{
.bus_num = 1,
.slim_slave = &msm_slim_tabla20,
},
#endif
/* add more slimbus slaves as needed */
};
#define MSM_WCNSS_PHYS 0x03000000
#define MSM_WCNSS_SIZE 0x280000
static struct resource resources_wcnss_wlan[] = {
{
.start = RIVA_APPS_WLAN_RX_DATA_AVAIL_IRQ,
.end = RIVA_APPS_WLAN_RX_DATA_AVAIL_IRQ,
.name = "wcnss_wlanrx_irq",
.flags = IORESOURCE_IRQ,
},
{
.start = RIVA_APPS_WLAN_DATA_XFER_DONE_IRQ,
.end = RIVA_APPS_WLAN_DATA_XFER_DONE_IRQ,
.name = "wcnss_wlantx_irq",
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_WCNSS_PHYS,
.end = MSM_WCNSS_PHYS + MSM_WCNSS_SIZE - 1,
.name = "wcnss_mmio",
.flags = IORESOURCE_MEM,
},
{
.start = 84,
.end = 88,
.name = "wcnss_gpios_5wire",
.flags = IORESOURCE_IO,
},
};
static struct qcom_wcnss_opts qcom_wcnss_pdata = {
.has_48mhz_xo = 1,
};
static struct platform_device msm_device_wcnss_wlan = {
.name = "wcnss_wlan",
.id = 0,
.num_resources = ARRAY_SIZE(resources_wcnss_wlan),
.resource = resources_wcnss_wlan,
.dev = {.platform_data = &qcom_wcnss_pdata},
};
#if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \
defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE) || \
defined(CONFIG_CRYPTO_DEV_QCEDEV) || \
defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE)
#define QCE_SIZE 0x10000
#define QCE_0_BASE 0x18500000
#define QCE_HW_KEY_SUPPORT 0
#define QCE_SHA_HMAC_SUPPORT 1
#define QCE_SHARE_CE_RESOURCE 1
#define QCE_CE_SHARED 0
static struct resource qcrypto_resources[] = {
[0] = {
.start = QCE_0_BASE,
.end = QCE_0_BASE + QCE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.name = "crypto_channels",
.start = DMOV_CE_IN_CHAN,
.end = DMOV_CE_OUT_CHAN,
.flags = IORESOURCE_DMA,
},
[2] = {
.name = "crypto_crci_in",
.start = DMOV_CE_IN_CRCI,
.end = DMOV_CE_IN_CRCI,
.flags = IORESOURCE_DMA,
},
[3] = {
.name = "crypto_crci_out",
.start = DMOV_CE_OUT_CRCI,
.end = DMOV_CE_OUT_CRCI,
.flags = IORESOURCE_DMA,
},
};
static struct resource qcedev_resources[] = {
[0] = {
.start = QCE_0_BASE,
.end = QCE_0_BASE + QCE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.name = "crypto_channels",
.start = DMOV_CE_IN_CHAN,
.end = DMOV_CE_OUT_CHAN,
.flags = IORESOURCE_DMA,
},
[2] = {
.name = "crypto_crci_in",
.start = DMOV_CE_IN_CRCI,
.end = DMOV_CE_IN_CRCI,
.flags = IORESOURCE_DMA,
},
[3] = {
.name = "crypto_crci_out",
.start = DMOV_CE_OUT_CRCI,
.end = DMOV_CE_OUT_CRCI,
.flags = IORESOURCE_DMA,
},
};
#endif
#if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \
defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE)
static struct msm_ce_hw_support qcrypto_ce_hw_suppport = {
.ce_shared = QCE_CE_SHARED,
.shared_ce_resource = QCE_SHARE_CE_RESOURCE,
.hw_key_support = QCE_HW_KEY_SUPPORT,
.sha_hmac = QCE_SHA_HMAC_SUPPORT,
};
static struct platform_device qcrypto_device = {
.name = "qcrypto",
.id = 0,
.num_resources = ARRAY_SIZE(qcrypto_resources),
.resource = qcrypto_resources,
.dev = {
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &qcrypto_ce_hw_suppport,
},
};
#endif
#if defined(CONFIG_CRYPTO_DEV_QCEDEV) || \
defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE)
static struct msm_ce_hw_support qcedev_ce_hw_suppport = {
.ce_shared = QCE_CE_SHARED,
.shared_ce_resource = QCE_SHARE_CE_RESOURCE,
.hw_key_support = QCE_HW_KEY_SUPPORT,
.sha_hmac = QCE_SHA_HMAC_SUPPORT,
};
static struct platform_device qcedev_device = {
.name = "qce",
.id = 0,
.num_resources = ARRAY_SIZE(qcedev_resources),
.resource = qcedev_resources,
.dev = {
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &qcedev_ce_hw_suppport,
},
};
#endif
#define MDM2AP_ERRFATAL 70
#define AP2MDM_ERRFATAL 95
#define MDM2AP_STATUS 69
#define AP2MDM_STATUS 94
#define AP2MDM_PMIC_RESET_N 80
#define AP2MDM_KPDPWR_N 81
static struct resource mdm_resources[] = {
{
.start = MDM2AP_ERRFATAL,
.end = MDM2AP_ERRFATAL,
.name = "MDM2AP_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_ERRFATAL,
.end = AP2MDM_ERRFATAL,
.name = "AP2MDM_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = MDM2AP_STATUS,
.end = MDM2AP_STATUS,
.name = "MDM2AP_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_STATUS,
.end = AP2MDM_STATUS,
.name = "AP2MDM_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_PMIC_RESET_N,
.end = AP2MDM_PMIC_RESET_N,
.name = "AP2MDM_PMIC_RESET_N",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_KPDPWR_N,
.end = AP2MDM_KPDPWR_N,
.name = "AP2MDM_KPDPWR_N",
.flags = IORESOURCE_IO,
},
};
static struct mdm_platform_data mdm_platform_data = {
.mdm_version = "2.5",
};
static struct platform_device mdm_device = {
.name = "mdm2_modem",
.id = -1,
.num_resources = ARRAY_SIZE(mdm_resources),
.resource = mdm_resources,
.dev = {
.platform_data = &mdm_platform_data,
},
};
static struct platform_device *mdm_devices[] __initdata = {
&mdm_device,
};
#define MSM_SHARED_RAM_PHYS 0x80000000
static void __init msm8930_map_io(void)
{
msm_shared_ram_phys = MSM_SHARED_RAM_PHYS;
msm_map_msm8930_io();
if (socinfo_init() < 0)
pr_err("socinfo_init() failed!\n");
}
static void __init msm8930_init_irq(void)
{
msm_mpm_irq_extn_init();
gic_init(0, GIC_PPI_START, MSM_QGIC_DIST_BASE,
(void *)MSM_QGIC_CPU_BASE);
/* Edge trigger PPIs except AVS_SVICINT and AVS_SVICINTSWDONE */
writel_relaxed(0xFFFFD7FF, MSM_QGIC_DIST_BASE + GIC_DIST_CONFIG + 4);
writel_relaxed(0x0000FFFF, MSM_QGIC_DIST_BASE + GIC_DIST_ENABLE_SET);
mb();
}
static void __init msm8930_init_buses(void)
{
#ifdef CONFIG_MSM_BUS_SCALING
msm_bus_rpm_set_mt_mask();
msm_bus_8960_apps_fabric_pdata.rpm_enabled = 1;
msm_bus_8960_sys_fabric_pdata.rpm_enabled = 1;
msm_bus_8960_mm_fabric_pdata.rpm_enabled = 1;
msm_bus_apps_fabric.dev.platform_data =
&msm_bus_8960_apps_fabric_pdata;
msm_bus_sys_fabric.dev.platform_data = &msm_bus_8960_sys_fabric_pdata;
msm_bus_mm_fabric.dev.platform_data = &msm_bus_8960_mm_fabric_pdata;
msm_bus_sys_fpb.dev.platform_data = &msm_bus_8960_sys_fpb_pdata;
msm_bus_cpss_fpb.dev.platform_data = &msm_bus_8960_cpss_fpb_pdata;
#endif
}
static struct msm_spi_platform_data msm8960_qup_spi_gsbi1_pdata = {
.max_clock_speed = 15060000,
};
#ifdef CONFIG_USB_MSM_OTG_72K
static struct msm_otg_platform_data msm_otg_pdata;
#else
static struct msm_otg_platform_data msm_otg_pdata = {
.mode = USB_OTG,
.otg_control = OTG_PMIC_CONTROL,
.phy_type = SNPS_28NM_INTEGRATED_PHY,
.pmic_id_irq = PM8038_USB_ID_IN_IRQ(PM8038_IRQ_BASE),
.power_budget = 750,
};
#endif
#ifdef CONFIG_USB_EHCI_MSM_HSIC
#define HSIC_HUB_RESET_GPIO 91
static struct msm_hsic_host_platform_data msm_hsic_pdata = {
.strobe = 150,
.data = 151,
};
#else
static struct msm_hsic_host_platform_data msm_hsic_pdata;
#endif
#define PID_MAGIC_ID 0x71432909
#define SERIAL_NUM_MAGIC_ID 0x61945374
#define SERIAL_NUMBER_LENGTH 127
#define DLOAD_USB_BASE_ADD 0x2A03F0C8
struct magic_num_struct {
uint32_t pid;
uint32_t serial_num;
};
struct dload_struct {
uint32_t reserved1;
uint32_t reserved2;
uint32_t reserved3;
uint16_t reserved4;
uint16_t pid;
char serial_number[SERIAL_NUMBER_LENGTH];
uint16_t reserved5;
struct magic_num_struct magic_struct;
};
static int usb_diag_update_pid_and_serial_num(uint32_t pid, const char *snum)
{
struct dload_struct __iomem *dload = 0;
dload = ioremap(DLOAD_USB_BASE_ADD, sizeof(*dload));
if (!dload) {
pr_err("%s: cannot remap I/O memory region: %08x\n",
__func__, DLOAD_USB_BASE_ADD);
return -ENXIO;
}
pr_debug("%s: dload:%p pid:%x serial_num:%s\n",
__func__, dload, pid, snum);
/* update pid */
dload->magic_struct.pid = PID_MAGIC_ID;
dload->pid = pid;
/* update serial number */
dload->magic_struct.serial_num = 0;
if (!snum) {
memset(dload->serial_number, 0, SERIAL_NUMBER_LENGTH);
goto out;
}
dload->magic_struct.serial_num = SERIAL_NUM_MAGIC_ID;
strlcpy(dload->serial_number, snum, SERIAL_NUMBER_LENGTH);
out:
iounmap(dload);
return 0;
}
static struct android_usb_platform_data android_usb_pdata = {
.update_pid_and_serial_num = usb_diag_update_pid_and_serial_num,
};
static struct platform_device android_usb_device = {
.name = "android_usb",
.id = -1,
.dev = {
.platform_data = &android_usb_pdata,
},
};
static uint8_t spm_wfi_cmd_sequence[] __initdata = {
0x03, 0x0f,
};
static uint8_t spm_power_collapse_without_rpm[] __initdata = {
0x00, 0x24, 0x54, 0x10,
0x09, 0x03, 0x01,
0x10, 0x54, 0x30, 0x0C,
0x24, 0x30, 0x0f,
};
static uint8_t spm_power_collapse_with_rpm[] __initdata = {
0x00, 0x24, 0x54, 0x10,
0x09, 0x07, 0x01, 0x0B,
0x10, 0x54, 0x30, 0x0C,
0x24, 0x30, 0x0f,
};
static struct msm_spm_seq_entry msm_spm_seq_list[] __initdata = {
[0] = {
.mode = MSM_SPM_MODE_CLOCK_GATING,
.notify_rpm = false,
.cmd = spm_wfi_cmd_sequence,
},
[1] = {
.mode = MSM_SPM_MODE_POWER_COLLAPSE,
.notify_rpm = false,
.cmd = spm_power_collapse_without_rpm,
},
[2] = {
.mode = MSM_SPM_MODE_POWER_COLLAPSE,
.notify_rpm = true,
.cmd = spm_power_collapse_with_rpm,
},
};
static struct msm_spm_platform_data msm_spm_data[] __initdata = {
[0] = {
.reg_base_addr = MSM_SAW0_BASE,
.reg_init_values[MSM_SPM_REG_SAW2_CFG] = 0x1F,
#if defined(CONFIG_MSM_AVS_HW)
.reg_init_values[MSM_SPM_REG_SAW2_AVS_CTL] = 0x00,
.reg_init_values[MSM_SPM_REG_SAW2_AVS_HYSTERESIS] = 0x00,
#endif
.reg_init_values[MSM_SPM_REG_SAW2_SPM_CTL] = 0x01,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DLY] = 0x02020204,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_0] = 0x0060009C,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_1] = 0x0000001C,
.vctl_timeout_us = 50,
.num_modes = ARRAY_SIZE(msm_spm_seq_list),
.modes = msm_spm_seq_list,
},
[1] = {
.reg_base_addr = MSM_SAW1_BASE,
.reg_init_values[MSM_SPM_REG_SAW2_CFG] = 0x1F,
#if defined(CONFIG_MSM_AVS_HW)
.reg_init_values[MSM_SPM_REG_SAW2_AVS_CTL] = 0x00,
.reg_init_values[MSM_SPM_REG_SAW2_AVS_HYSTERESIS] = 0x00,
#endif
.reg_init_values[MSM_SPM_REG_SAW2_SPM_CTL] = 0x01,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DLY] = 0x02020204,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_0] = 0x0060009C,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_1] = 0x0000001C,
.vctl_timeout_us = 50,
.num_modes = ARRAY_SIZE(msm_spm_seq_list),
.modes = msm_spm_seq_list,
},
};
static uint8_t l2_spm_wfi_cmd_sequence[] __initdata = {
0x00, 0x20, 0x03, 0x20,
0x00, 0x0f,
};
static uint8_t l2_spm_gdhs_cmd_sequence[] __initdata = {
0x00, 0x20, 0x34, 0x64,
0x48, 0x07, 0x48, 0x20,
0x50, 0x64, 0x04, 0x34,
0x50, 0x0f,
};
static uint8_t l2_spm_power_off_cmd_sequence[] __initdata = {
0x00, 0x10, 0x34, 0x64,
0x48, 0x07, 0x48, 0x10,
0x50, 0x64, 0x04, 0x34,
0x50, 0x0F,
};
static struct msm_spm_seq_entry msm_spm_l2_seq_list[] __initdata = {
[0] = {
.mode = MSM_SPM_L2_MODE_RETENTION,
.notify_rpm = false,
.cmd = l2_spm_wfi_cmd_sequence,
},
[1] = {
.mode = MSM_SPM_L2_MODE_GDHS,
.notify_rpm = true,
.cmd = l2_spm_gdhs_cmd_sequence,
},
[2] = {
.mode = MSM_SPM_L2_MODE_POWER_COLLAPSE,
.notify_rpm = true,
.cmd = l2_spm_power_off_cmd_sequence,
},
};
static struct msm_spm_platform_data msm_spm_l2_data[] __initdata = {
[0] = {
.reg_base_addr = MSM_SAW_L2_BASE,
.reg_init_values[MSM_SPM_REG_SAW2_SPM_CTL] = 0x00,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DLY] = 0x02020204,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_0] = 0x00A000AE,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_1] = 0x00A00020,
.modes = msm_spm_l2_seq_list,
.num_modes = ARRAY_SIZE(msm_spm_l2_seq_list),
},
};
#/* TODO: Remove this once PM8038 physically becomes
* available.
*/
#ifndef MSM8930_PHASE_2
#define PM_HAP_EN_GPIO PM8921_GPIO_PM_TO_SYS(33)
#define PM_HAP_LEN_GPIO PM8921_GPIO_PM_TO_SYS(20)
#else
#define ISA1200_HAP_EN_GPIO 77
#define ISA1200_HAP_LEN_GPIO 78
#define ISA1200_HAP_CLK PM8038_GPIO_PM_TO_SYS(7)
#endif
#ifndef MSM8930_PHASE_2
static struct msm_xo_voter *xo_handle_d1;
#endif
static int isa1200_power(int on)
{
#ifndef MSM8930_PHASE_2
int rc = 0;
gpio_set_value(HAP_SHIFT_LVL_OE_GPIO, !!on);
rc = on ? msm_xo_mode_vote(xo_handle_d1, MSM_XO_MODE_ON) :
msm_xo_mode_vote(xo_handle_d1, MSM_XO_MODE_OFF);
if (rc < 0) {
pr_err("%s: failed to %svote for TCXO D1 buffer%d\n",
__func__, on ? "" : "de-", rc);
goto err_xo_vote;
}
return 0;
err_xo_vote:
gpio_set_value(HAP_SHIFT_LVL_OE_GPIO, !on);
return rc;
#else
gpio_set_value_cansleep(ISA1200_HAP_CLK, !!on);
return 0;
#endif
}
static int isa1200_dev_setup(bool enable)
{
int rc = 0;
#ifndef MSM8930_PHASE_2
struct pm_gpio hap_gpio_config = {
.direction = PM_GPIO_DIR_OUT,
.pull = PM_GPIO_PULL_NO,
.out_strength = PM_GPIO_STRENGTH_HIGH,
.function = PM_GPIO_FUNC_NORMAL,
.inv_int_pol = 0,
.vin_sel = 2,
.output_buffer = PM_GPIO_OUT_BUF_CMOS,
.output_value = 0,
};
if (enable == true) {
rc = pm8xxx_gpio_config(PM_HAP_EN_GPIO, &hap_gpio_config);
if (rc) {
pr_err("%s: pm8921 gpio %d config failed(%d)\n",
__func__, PM_HAP_EN_GPIO, rc);
return rc;
}
rc = pm8xxx_gpio_config(PM_HAP_LEN_GPIO, &hap_gpio_config);
if (rc) {
pr_err("%s: pm8921 gpio %d config failed(%d)\n",
__func__, PM_HAP_LEN_GPIO, rc);
return rc;
}
rc = gpio_request(HAP_SHIFT_LVL_OE_GPIO, "hap_shft_lvl_oe");
if (rc) {
pr_err("%s: unable to request gpio %d (%d)\n",
__func__, HAP_SHIFT_LVL_OE_GPIO, rc);
return rc;
}
rc = gpio_direction_output(HAP_SHIFT_LVL_OE_GPIO, 0);
if (rc) {
pr_err("%s: Unable to set direction\n", __func__);
goto free_gpio;
}
xo_handle_d1 = msm_xo_get(MSM_XO_TCXO_D1, "isa1200");
if (IS_ERR(xo_handle_d1)) {
rc = PTR_ERR(xo_handle_d1);
pr_err("%s: failed to get the handle for D1(%d)\n",
__func__, rc);
goto gpio_set_dir;
}
} else {
gpio_free(HAP_SHIFT_LVL_OE_GPIO);
msm_xo_put(xo_handle_d1);
}
return 0;
gpio_set_dir:
gpio_set_value(HAP_SHIFT_LVL_OE_GPIO, 0);
free_gpio:
gpio_free(HAP_SHIFT_LVL_OE_GPIO);
return rc;
#else
struct pm_gpio hap_clk_gpio_config = {
.direction = PM_GPIO_DIR_OUT,
.pull = PM_GPIO_PULL_NO,
.out_strength = PM_GPIO_STRENGTH_HIGH,
.function = PM_GPIO_FUNC_1,
.inv_int_pol = 0,
.vin_sel = PM_GPIO_VIN_S4,
.output_buffer = PM_GPIO_OUT_BUF_CMOS,
.output_value = 0,
};
rc = pm8xxx_gpio_config(ISA1200_HAP_CLK, &hap_clk_gpio_config);
if (rc) {
pr_err("%s: pm8038 gpio %d config failed(%d)\n",
__func__, ISA1200_HAP_CLK, rc);
return rc;
}
rc = gpio_request(ISA1200_HAP_CLK, "haptics_clk");
if (rc) {
pr_err("%s: gpio_request for %d gpio failed rc(%d)\n",
__func__, ISA1200_HAP_CLK, rc);
goto fail_gpio_req;
}
rc = gpio_direction_output(ISA1200_HAP_CLK, 0);
if (rc) {
pr_err("%s: gpio_direction_output failed for %d gpio rc(%d)\n",
__func__, ISA1200_HAP_CLK, rc);
goto fail_gpio_dir;
}
return 0;
fail_gpio_dir:
gpio_free(ISA1200_HAP_CLK);
fail_gpio_req:
return rc;
#endif
}
static struct isa1200_regulator isa1200_reg_data[] = {
#ifndef MSM8930_PHASE_2
{
.name = "vcc_i2c",
.min_uV = ISA_I2C_VTG_MIN_UV,
.max_uV = ISA_I2C_VTG_MAX_UV,
.load_uA = ISA_I2C_CURR_UA,
},
#else
{
.name = "vddp",
.min_uV = ISA_I2C_VTG_MIN_UV,
.max_uV = ISA_I2C_VTG_MAX_UV,
.load_uA = ISA_I2C_CURR_UA,
},
#endif
};
static struct isa1200_platform_data isa1200_1_pdata = {
.name = "vibrator",
.dev_setup = isa1200_dev_setup,
.power_on = isa1200_power,
#ifndef MSM8930_PHASE_2
.hap_en_gpio = PM_HAP_EN_GPIO,
.hap_len_gpio = PM_HAP_LEN_GPIO,
#else
.hap_en_gpio = ISA1200_HAP_EN_GPIO,
.hap_len_gpio = ISA1200_HAP_LEN_GPIO,
#endif
.max_timeout = 15000,
.mode_ctrl = PWM_GEN_MODE,
.pwm_fd = {
.pwm_div = 256,
},
.is_erm = false,
.smart_en = true,
.ext_clk_en = true,
.chip_en = 1,
.regulator_info = isa1200_reg_data,
.num_regulators = ARRAY_SIZE(isa1200_reg_data),
};
static struct i2c_board_info msm_isa1200_board_info[] __initdata = {
{
I2C_BOARD_INFO("isa1200_1", 0x90>>1),
.platform_data = &isa1200_1_pdata,
},
};
#define CYTTSP_TS_GPIO_IRQ 11
#define CYTTSP_TS_SLEEP_GPIO 50
#define CYTTSP_TS_RESOUT_N_GPIO 52
/*virtual key support */
static ssize_t tma340_vkeys_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return snprintf(buf, 200,
__stringify(EV_KEY) ":" __stringify(KEY_BACK) ":73:1120:97:97"
":" __stringify(EV_KEY) ":" __stringify(KEY_MENU) ":230:1120:97:97"
":" __stringify(EV_KEY) ":" __stringify(KEY_HOME) ":389:1120:97:97"
":" __stringify(EV_KEY) ":" __stringify(KEY_SEARCH) ":544:1120:97:97"
"\n");
}
static struct kobj_attribute tma340_vkeys_attr = {
.attr = {
.mode = S_IRUGO,
},
.show = &tma340_vkeys_show,
};
static struct attribute *tma340_properties_attrs[] = {
&tma340_vkeys_attr.attr,
NULL
};
static struct attribute_group tma340_properties_attr_group = {
.attrs = tma340_properties_attrs,
};
static int cyttsp_platform_init(struct i2c_client *client)
{
int rc = 0;
static struct kobject *tma340_properties_kobj;
tma340_vkeys_attr.attr.name = "virtualkeys.cyttsp-i2c";
tma340_properties_kobj = kobject_create_and_add("board_properties",
NULL);
if (tma340_properties_kobj)
rc = sysfs_create_group(tma340_properties_kobj,
&tma340_properties_attr_group);
if (!tma340_properties_kobj || rc)
pr_err("%s: failed to create board_properties\n",
__func__);
return 0;
}
static struct cyttsp_regulator regulator_data[] = {
{
.name = "vdd",
.min_uV = CY_TMA300_VTG_MIN_UV,
.max_uV = CY_TMA300_VTG_MAX_UV,
.hpm_load_uA = CY_TMA300_CURR_24HZ_UA,
.lpm_load_uA = CY_TMA300_SLEEP_CURR_UA,
},
/* TODO: Remove after runtime PM is enabled in I2C driver */
{
.name = "vcc_i2c",
.min_uV = CY_I2C_VTG_MIN_UV,
.max_uV = CY_I2C_VTG_MAX_UV,
.hpm_load_uA = CY_I2C_CURR_UA,
.lpm_load_uA = CY_I2C_SLEEP_CURR_UA,
},
};
static struct cyttsp_platform_data cyttsp_pdata = {
.panel_maxx = 634,
.panel_maxy = 1166,
.disp_maxx = 616,
.disp_maxy = 1023,
.disp_minx = 0,
.disp_miny = 16,
.flags = 0x01,
.gen = CY_GEN3, /* or */
.use_st = CY_USE_ST,
.use_mt = CY_USE_MT,
.use_hndshk = CY_SEND_HNDSHK,
.use_trk_id = CY_USE_TRACKING_ID,
.use_sleep = CY_USE_DEEP_SLEEP_SEL | CY_USE_LOW_POWER_SEL,
.use_gestures = CY_USE_GESTURES,
.fw_fname = "cyttsp_8960_cdp.hex",
/* activate up to 4 groups
* and set active distance
*/
.gest_set = CY_GEST_GRP1 | CY_GEST_GRP2 |
CY_GEST_GRP3 | CY_GEST_GRP4 |
CY_ACT_DIST,
/* change act_intrvl to customize the Active power state
* scanning/processing refresh interval for Operating mode
*/
.act_intrvl = CY_ACT_INTRVL_DFLT,
/* change tch_tmout to customize the touch timeout for the
* Active power state for Operating mode
*/
.tch_tmout = CY_TCH_TMOUT_DFLT,
/* change lp_intrvl to customize the Low Power power state
* scanning/processing refresh interval for Operating mode
*/
.lp_intrvl = CY_LP_INTRVL_DFLT,
.sleep_gpio = CYTTSP_TS_SLEEP_GPIO,
.resout_gpio = CYTTSP_TS_RESOUT_N_GPIO,
.irq_gpio = CYTTSP_TS_GPIO_IRQ,
.regulator_info = regulator_data,
.num_regulators = ARRAY_SIZE(regulator_data),
.init = cyttsp_platform_init,
.correct_fw_ver = 9,
};
static struct i2c_board_info cyttsp_info[] __initdata = {
{
I2C_BOARD_INFO(CY_I2C_NAME, 0x24),
.platform_data = &cyttsp_pdata,
#ifndef CY_USE_TIMER
.irq = MSM_GPIO_TO_INT(CYTTSP_TS_GPIO_IRQ),
#endif /* CY_USE_TIMER */
},
};
#define MXT_TS_GPIO_IRQ 11
#define MXT_TS_RESET_GPIO 52
static const u8 mxt_config_data_8930[] = {
/* T6 Object */
0, 0, 0, 0, 0, 0,
/* T38 Object */
15, 1, 0, 15, 12, 11, 0, 0,
/* T7 Object */
48, 255, 25,
/* T8 Object */
27, 0, 5, 1, 0, 0, 8, 8, 0, 0,
/* T9 Object */
131, 0, 0, 19, 11, 0, 16, 35, 1, 3,
10, 15, 1, 11, 4, 5, 40, 10, 54, 2,
43, 4, 0, 0, 0, 0, 143, 40, 143, 80,
18, 15, 50, 50, 2,
/* T15 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,
/* T18 Object */
0, 0,
/* T19 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
/* T23 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
/* T25 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
/* T40 Object */
0, 0, 0, 0, 0,
/* T42 Object */
0, 0, 0, 0, 0, 0, 0, 0,
/* T46 Object */
0, 3, 16, 48, 0, 0, 1, 0, 0,
/* T47 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* T48 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
};
static ssize_t mxt224e_vkeys_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return snprintf(buf, 200,
__stringify(EV_KEY) ":" __stringify(KEY_BACK) ":65:938:90:90"
":" __stringify(EV_KEY) ":" __stringify(KEY_MENU) ":208:938:90:90"
":" __stringify(EV_KEY) ":" __stringify(KEY_HOME) ":348:938:90:90"
":" __stringify(EV_KEY) ":" __stringify(KEY_SEARCH) ":490:938:90:90"
"\n");
}
static struct kobj_attribute mxt224e_vkeys_attr = {
.attr = {
.mode = S_IRUGO,
},
.show = &mxt224e_vkeys_show,
};
static struct attribute *mxt224e_properties_attrs[] = {
&mxt224e_vkeys_attr.attr,
NULL
};
static struct attribute_group mxt224e_properties_attr_group = {
.attrs = mxt224e_properties_attrs,
};
static void mxt_init_vkeys_8930(void)
{
int rc = 0;
static struct kobject *mxt224e_properties_kobj;
mxt224e_vkeys_attr.attr.name = "virtualkeys.atmel_mxt_ts";
mxt224e_properties_kobj = kobject_create_and_add("board_properties",
NULL);
if (mxt224e_properties_kobj)
rc = sysfs_create_group(mxt224e_properties_kobj,
&mxt224e_properties_attr_group);
if (!mxt224e_properties_kobj || rc)
pr_err("%s: failed to create board_properties\n",
__func__);
return;
}
static struct mxt_config_info mxt_config_array[] = {
{
.config = mxt_config_data_8930,
.config_length = ARRAY_SIZE(mxt_config_data_8930),
.family_id = 0x81,
.variant_id = 0x01,
.version = 0x10,
.build = 0xAA,
},
};
static struct mxt_platform_data mxt_platform_data_8930 = {
.config_array = mxt_config_array,
.config_array_size = ARRAY_SIZE(mxt_config_array),
.panel_minx = 0,
.panel_maxx = 566,
.panel_miny = 0,
.panel_maxy = 1067,
.disp_minx = 0,
.disp_maxx = 540,
.disp_miny = 0,
.disp_maxy = 960,
.irqflags = IRQF_TRIGGER_FALLING,
#ifdef MSM8930_PHASE_2
.digital_pwr_regulator = true,
#endif
.i2c_pull_up = true,
.reset_gpio = MXT_TS_RESET_GPIO,
.irq_gpio = MXT_TS_GPIO_IRQ,
};
static struct i2c_board_info mxt_device_info_8930[] __initdata = {
{
I2C_BOARD_INFO("atmel_mxt_ts", 0x4a),
.platform_data = &mxt_platform_data_8930,
.irq = MSM_GPIO_TO_INT(MXT_TS_GPIO_IRQ),
},
};
#ifdef MSM8930_PHASE_2
#define GPIO_VOLUME_UP PM8038_GPIO_PM_TO_SYS(3)
#define GPIO_VOLUME_DOWN PM8038_GPIO_PM_TO_SYS(8)
#define GPIO_CAMERA_SNAPSHOT PM8038_GPIO_PM_TO_SYS(10)
#define GPIO_CAMERA_FOCUS PM8038_GPIO_PM_TO_SYS(11)
static struct gpio_keys_button keys_8930[] = {
{
.code = KEY_VOLUMEUP,
.type = EV_KEY,
.desc = "volume_up",
.gpio = GPIO_VOLUME_UP,
.wakeup = 1,
.active_low = 1,
},
{
.code = KEY_VOLUMEDOWN,
.type = EV_KEY,
.desc = "volume_down",
.gpio = GPIO_VOLUME_DOWN,
.wakeup = 1,
.active_low = 1,
},
{
.code = KEY_CAMERA_FOCUS,
.type = EV_KEY,
.desc = "camera_focus",
.gpio = GPIO_CAMERA_FOCUS,
.wakeup = 1,
.active_low = 1,
},
{
.code = KEY_CAMERA_SNAPSHOT,
.type = EV_KEY,
.desc = "camera_snapshot",
.gpio = GPIO_CAMERA_SNAPSHOT,
.wakeup = 1,
.active_low = 1,
},
};
/* Add GPIO keys for 8930 */
static struct gpio_keys_platform_data gpio_keys_8930_pdata = {
.buttons = keys_8930,
.nbuttons = 4,
};
static struct platform_device gpio_keys_8930 = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = &gpio_keys_8930_pdata,
},
};
#endif /* MSM8930_PHASE_2 */
static struct msm_i2c_platform_data msm8960_i2c_qup_gsbi4_pdata = {
.clk_freq = 100000,
.src_clk_rate = 24000000,
};
static struct msm_i2c_platform_data msm8960_i2c_qup_gsbi3_pdata = {
.clk_freq = 100000,
.src_clk_rate = 24000000,
};
static struct msm_i2c_platform_data msm8960_i2c_qup_gsbi10_pdata = {
.clk_freq = 100000,
.src_clk_rate = 24000000,
};
static struct msm_i2c_platform_data msm8960_i2c_qup_gsbi12_pdata = {
.clk_freq = 100000,
.src_clk_rate = 24000000,
};
static struct msm_rpm_platform_data msm_rpm_data = {
.reg_base_addrs = {
[MSM_RPM_PAGE_STATUS] = MSM_RPM_BASE,
[MSM_RPM_PAGE_CTRL] = MSM_RPM_BASE + 0x400,
[MSM_RPM_PAGE_REQ] = MSM_RPM_BASE + 0x600,
[MSM_RPM_PAGE_ACK] = MSM_RPM_BASE + 0xa00,
},
.irq_ack = RPM_APCC_CPU0_GP_HIGH_IRQ,
.irq_err = RPM_APCC_CPU0_GP_LOW_IRQ,
.irq_vmpm = RPM_APCC_CPU0_GP_MEDIUM_IRQ,
.msm_apps_ipc_rpm_reg = MSM_APCS_GCC_BASE + 0x008,
.msm_apps_ipc_rpm_val = 4,
};
static struct ks8851_pdata spi_eth_pdata = {
.irq_gpio = KS8851_IRQ_GPIO,
.rst_gpio = KS8851_RST_GPIO,
};
static struct spi_board_info spi_board_info[] __initdata = {
{
.modalias = "ks8851",
.irq = MSM_GPIO_TO_INT(KS8851_IRQ_GPIO),
.max_speed_hz = 19200000,
.bus_num = 0,
.chip_select = 0,
.mode = SPI_MODE_0,
.platform_data = &spi_eth_pdata
},
{
.modalias = "dsi_novatek_3d_panel_spi",
.max_speed_hz = 10800000,
.bus_num = 0,
.chip_select = 1,
.mode = SPI_MODE_0,
},
};
static struct platform_device msm_device_saw_core0 = {
.name = "saw-regulator",
.id = 0,
.dev = {
.platform_data = &msm8930_saw_regulator_core0_pdata,
},
};
static struct platform_device msm_device_saw_core1 = {
.name = "saw-regulator",
.id = 1,
.dev = {
.platform_data = &msm8930_saw_regulator_core1_pdata,
},
};
static struct tsens_platform_data msm_tsens_pdata = {
.slope = {910, 910, 910, 910, 910},
.tsens_factor = 1000,
.hw_type = MSM_8960,
.tsens_num_sensor = 5,
};
#ifdef CONFIG_MSM_FAKE_BATTERY
static struct platform_device fish_battery_device = {
.name = "fish_battery",
};
#endif
#ifndef MSM8930_PHASE_2
/* 8930 Phase 1 */
static struct platform_device msm8930_device_ext_5v_vreg __devinitdata = {
.name = GPIO_REGULATOR_DEV_NAME,
.id = PM8921_MPP_PM_TO_SYS(7),
.dev = {
.platform_data = &msm_gpio_regulator_pdata[GPIO_VREG_ID_EXT_5V],
},
};
static struct platform_device msm8930_device_ext_l2_vreg __devinitdata = {
.name = GPIO_REGULATOR_DEV_NAME,
.id = 91,
.dev = {
.platform_data = &msm_gpio_regulator_pdata[GPIO_VREG_ID_EXT_L2],
},
};
#else
/* 8930 Phase 2 */
static struct platform_device msm8930_device_ext_5v_vreg __devinitdata = {
.name = GPIO_REGULATOR_DEV_NAME,
.id = 63,
.dev = {
.platform_data =
&msm8930_gpio_regulator_pdata[MSM8930_GPIO_VREG_ID_EXT_5V],
},
};
static struct platform_device msm8930_device_ext_otg_sw_vreg __devinitdata = {
.name = GPIO_REGULATOR_DEV_NAME,
.id = 97,
.dev = {
.platform_data =
&msm8930_gpio_regulator_pdata[MSM8930_GPIO_VREG_ID_EXT_OTG_SW],
},
};
#endif
static struct platform_device msm8930_device_rpm_regulator __devinitdata = {
.name = "rpm-regulator",
.id = -1,
.dev = {
/*
* TODO: When physical 8930/PM8038 hardware becomes
* available, replace msm_rpm_regulator_pdata
* with 8930 rpm regulator object.
*/
#if !defined(MSM8930_PHASE_2)
.platform_data = &msm_rpm_regulator_pdata,
#endif
},
};
static struct msm_rpm_log_platform_data msm_rpm_log_pdata = {
.phys_addr_base = 0x0010C000,
.reg_offsets = {
[MSM_RPM_LOG_PAGE_INDICES] = 0x00000080,
[MSM_RPM_LOG_PAGE_BUFFER] = 0x000000A0,
},
.phys_size = SZ_8K,
.log_len = 4096, /* log's buffer length in bytes */
.log_len_mask = (4096 >> 2) - 1, /* length mask in units of u32 */
};
static struct platform_device msm_rpm_log_device = {
.name = "msm_rpm_log",
.id = -1,
.dev = {
.platform_data = &msm_rpm_log_pdata,
},
};
static struct platform_device *common_devices[] __initdata = {
&msm8960_device_dmov,
&msm_device_smd,
&msm8960_device_uart_gsbi5,
&msm_device_uart_dm6,
&msm_device_saw_core0,
&msm_device_saw_core1,
&msm8930_device_ext_5v_vreg,
#ifndef MSM8930_PHASE_2
&msm8930_device_ext_l2_vreg,
#endif
&msm8960_device_ssbi_pmic,
#ifdef MSM8930_PHASE_2
&msm8930_device_ext_otg_sw_vreg,
#endif
&msm_8960_q6_lpass,
&msm_8960_q6_mss_fw,
&msm_8960_q6_mss_sw,
&msm_8960_riva,
&msm_pil_tzapps,
&msm_pil_vidc,
&msm8960_device_qup_spi_gsbi1,
&msm8960_device_qup_i2c_gsbi3,
&msm8960_device_qup_i2c_gsbi4,
&msm8960_device_qup_i2c_gsbi10,
&msm8960_device_qup_i2c_gsbi12,
&msm_slim_ctrl,
&msm_device_wcnss_wlan,
#if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \
defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE)
&qcrypto_device,
#endif
#if defined(CONFIG_CRYPTO_DEV_QCEDEV) || \
defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE)
&qcedev_device,
#endif
#ifdef CONFIG_MSM_ROTATOR
&msm_rotator_device,
#endif
&msm_device_sps,
#ifdef CONFIG_MSM_FAKE_BATTERY
&fish_battery_device,
#endif
#ifdef CONFIG_ANDROID_PMEM
#ifndef CONFIG_MSM_MULTIMEDIA_USE_ION
&android_pmem_device,
&android_pmem_adsp_device,
#endif
&android_pmem_audio_device,
#endif
&msm_device_vidc,
&msm_device_bam_dmux,
&msm_fm_platform_init,
#ifdef CONFIG_HW_RANDOM_MSM
&msm_device_rng,
#endif
&msm_rpm_device,
#ifdef CONFIG_ION_MSM
&ion_dev,
#endif
&msm_rpm_log_device,
&msm_rpm_stat_device,
&msm_device_tz_log,
#ifdef CONFIG_MSM_QDSS
&msm_etb_device,
&msm_tpiu_device,
&msm_funnel_device,
&msm_etm_device,
#endif
&msm_device_dspcrashd_8960,
&msm8960_device_watchdog,
#ifdef MSM8930_PHASE_2
&gpio_keys_8930,
#endif
#ifdef CONFIG_MSM_RTB
&msm_rtb_device,
#endif
&msm8960_device_cache_erp,
};
static struct platform_device *cdp_devices[] __initdata = {
&msm8960_device_otg,
&msm8960_device_gadget_peripheral,
&msm_device_hsusb_host,
&android_usb_device,
&msm_pcm,
&msm_pcm_routing,
&msm_cpudai0,
&msm_cpudai1,
&msm_cpudai_hdmi_rx,
&msm_cpudai_bt_rx,
&msm_cpudai_bt_tx,
&msm_cpudai_fm_rx,
&msm_cpudai_fm_tx,
&msm_cpudai_auxpcm_rx,
&msm_cpudai_auxpcm_tx,
&msm_cpu_fe,
&msm_stub_codec,
&msm_kgsl_3d0,
#ifdef CONFIG_MSM_KGSL_2D
&msm_kgsl_2d0,
&msm_kgsl_2d1,
#endif
#ifdef CONFIG_MSM_GEMINI
&msm8960_gemini_device,
#endif
&msm_voice,
&msm_voip,
&msm_lpa_pcm,
&msm_cpudai_afe_01_rx,
&msm_cpudai_afe_01_tx,
&msm_cpudai_afe_02_rx,
&msm_cpudai_afe_02_tx,
&msm_pcm_afe,
&msm_compr_dsp,
&msm_cpudai_incall_music_rx,
&msm_cpudai_incall_record_rx,
&msm_cpudai_incall_record_tx,
&msm_pcm_hostless,
&msm_bus_apps_fabric,
&msm_bus_sys_fabric,
&msm_bus_mm_fabric,
&msm_bus_sys_fpb,
&msm_bus_cpss_fpb,
};
static void __init msm8930_i2c_init(void)
{
msm8960_device_qup_i2c_gsbi4.dev.platform_data =
&msm8960_i2c_qup_gsbi4_pdata;
msm8960_device_qup_i2c_gsbi3.dev.platform_data =
&msm8960_i2c_qup_gsbi3_pdata;
msm8960_device_qup_i2c_gsbi10.dev.platform_data =
&msm8960_i2c_qup_gsbi10_pdata;
msm8960_device_qup_i2c_gsbi12.dev.platform_data =
&msm8960_i2c_qup_gsbi12_pdata;
}
static void __init msm8930_gfx_init(void)
{
uint32_t soc_platform_version = socinfo_get_version();
if (SOCINFO_VERSION_MAJOR(soc_platform_version) == 1) {
struct kgsl_device_platform_data *kgsl_3d0_pdata =
msm_kgsl_3d0.dev.platform_data;
kgsl_3d0_pdata->pwrlevel[0].gpu_freq = 320000000;
kgsl_3d0_pdata->pwrlevel[1].gpu_freq = 266667000;
}
}
static struct msm_cpuidle_state msm_cstates[] __initdata = {
{0, 0, "C0", "WFI",
MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT},
{0, 1, "C1", "STANDALONE_POWER_COLLAPSE",
MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE},
{0, 2, "C2", "POWER_COLLAPSE",
MSM_PM_SLEEP_MODE_POWER_COLLAPSE},
{1, 0, "C0", "WFI",
MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT},
{1, 1, "C1", "STANDALONE_POWER_COLLAPSE",
MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE},
};
static struct msm_pm_platform_data msm_pm_data[MSM_PM_SLEEP_MODE_NR * 2] = {
[MSM_PM_MODE(0, MSM_PM_SLEEP_MODE_POWER_COLLAPSE)] = {
.idle_supported = 1,
.suspend_supported = 1,
.idle_enabled = 0,
.suspend_enabled = 0,
},
[MSM_PM_MODE(0, MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE)] = {
.idle_supported = 1,
.suspend_supported = 1,
.idle_enabled = 0,
.suspend_enabled = 0,
},
[MSM_PM_MODE(0, MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT)] = {
.idle_supported = 1,
.suspend_supported = 1,
.idle_enabled = 1,
.suspend_enabled = 1,
},
[MSM_PM_MODE(1, MSM_PM_SLEEP_MODE_POWER_COLLAPSE)] = {
.idle_supported = 0,
.suspend_supported = 1,
.idle_enabled = 0,
.suspend_enabled = 0,
},
[MSM_PM_MODE(1, MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE)] = {
.idle_supported = 1,
.suspend_supported = 1,
.idle_enabled = 0,
.suspend_enabled = 0,
},
[MSM_PM_MODE(1, MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT)] = {
.idle_supported = 1,
.suspend_supported = 0,
.idle_enabled = 1,
.suspend_enabled = 0,
},
};
static struct msm_rpmrs_level msm_rpmrs_levels[] __initdata = {
{
MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT,
MSM_RPMRS_LIMITS(ON, ACTIVE, MAX, ACTIVE),
true,
100, 8000, 100000, 1,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE,
MSM_RPMRS_LIMITS(ON, ACTIVE, MAX, ACTIVE),
true,
2000, 6000, 60100000, 3000,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(ON, GDHS, MAX, ACTIVE),
false,
4200, 5000, 60350000, 3500,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(ON, HSFS_OPEN, MAX, ACTIVE),
false,
6300, 4500, 65350000, 4800,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(ON, HSFS_OPEN, ACTIVE, RET_HIGH),
false,
7000, 3500, 66600000, 5150,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(OFF, GDHS, MAX, ACTIVE),
false,
11700, 2500, 67850000, 5500,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(OFF, HSFS_OPEN, MAX, ACTIVE),
false,
13800, 2000, 71850000, 6800,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(OFF, HSFS_OPEN, ACTIVE, RET_HIGH),
false,
29700, 500, 75850000, 8800,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(OFF, HSFS_OPEN, RET_HIGH, RET_LOW),
false,
29700, 0, 76350000, 9800,
},
};
static struct msm_pm_boot_platform_data msm_pm_boot_pdata __initdata = {
.mode = MSM_PM_BOOT_CONFIG_TZ,
};
#ifdef CONFIG_I2C
#define I2C_SURF 1
#define I2C_FFA (1 << 1)
#define I2C_RUMI (1 << 2)
#define I2C_SIM (1 << 3)
#define I2C_FLUID (1 << 4)
#define I2C_LIQUID (1 << 5)
struct i2c_registry {
u8 machs;
int bus;
struct i2c_board_info *info;
int len;
};
static void __init msm8930_init_hsic(void)
{
#ifdef CONFIG_USB_EHCI_MSM_HSIC
uint32_t version = socinfo_get_version();
pr_info("%s: version:%d mtp:%d\n", __func__,
SOCINFO_VERSION_MAJOR(version),
machine_is_msm8930_mtp());
if ((SOCINFO_VERSION_MAJOR(version) == 1) ||
machine_is_msm8930_mtp() ||
machine_is_msm8930_fluid())
return;
platform_device_register(&msm_device_hsic_host);
#endif
}
#ifdef CONFIG_ISL9519_CHARGER
static struct isl_platform_data isl_data __initdata = {
.valid_n_gpio = 0, /* Not required when notify-by-pmic */
.chg_detection_config = NULL, /* Not required when notify-by-pmic */
.max_system_voltage = 4200,
.min_system_voltage = 3200,
.chgcurrent = 1000, /* 1900, */
.term_current = 400, /* Need fine tuning */
.input_current = 2048,
};
static struct i2c_board_info isl_charger_i2c_info[] __initdata = {
{
I2C_BOARD_INFO("isl9519q", 0x9),
.irq = 0, /* Not required when notify-by-pmic */
.platform_data = &isl_data,
},
};
#endif /* CONFIG_ISL9519_CHARGER */
static struct i2c_registry msm8960_i2c_devices[] __initdata = {
#ifdef CONFIG_ISL9519_CHARGER
{
I2C_LIQUID,
MSM_8930_GSBI10_QUP_I2C_BUS_ID,
isl_charger_i2c_info,
ARRAY_SIZE(isl_charger_i2c_info),
},
#endif /* CONFIG_ISL9519_CHARGER */
{
I2C_SURF | I2C_FFA | I2C_FLUID,
MSM_8930_GSBI3_QUP_I2C_BUS_ID,
cyttsp_info,
ARRAY_SIZE(cyttsp_info),
},
#ifndef MSM8930_PHASE_2
{
I2C_LIQUID,
MSM_8930_GSBI10_QUP_I2C_BUS_ID,
msm_isa1200_board_info,
ARRAY_SIZE(msm_isa1200_board_info),
},
#else
{
I2C_FFA | I2C_FLUID,
MSM_8930_GSBI10_QUP_I2C_BUS_ID,
msm_isa1200_board_info,
ARRAY_SIZE(msm_isa1200_board_info),
},
#endif
{
I2C_SURF,
MSM_8930_GSBI3_QUP_I2C_BUS_ID,
mxt_device_info_8930,
ARRAY_SIZE(mxt_device_info_8930),
},
};
#endif /* CONFIG_I2C */
static void __init register_i2c_devices(void)
{
#ifdef CONFIG_I2C
u8 mach_mask = 0;
int i;
#ifdef CONFIG_MSM_CAMERA
struct i2c_registry msm8930_camera_i2c_devices = {
I2C_SURF | I2C_FFA | I2C_FLUID | I2C_LIQUID | I2C_RUMI,
MSM_8930_GSBI4_QUP_I2C_BUS_ID,
msm8930_camera_board_info.board_info,
msm8930_camera_board_info.num_i2c_board_info,
};
#endif
/* Build the matching 'supported_machs' bitmask */
if (machine_is_msm8930_cdp() || machine_is_msm8627_cdp())
mach_mask = I2C_SURF;
else if (machine_is_msm8930_fluid())
mach_mask = I2C_FLUID;
else if (machine_is_msm8930_mtp() || machine_is_msm8627_mtp())
mach_mask = I2C_FFA;
else
pr_err("unmatched machine ID in register_i2c_devices\n");
/* Run the array and install devices as appropriate */
for (i = 0; i < ARRAY_SIZE(msm8960_i2c_devices); ++i) {
if (msm8960_i2c_devices[i].machs & mach_mask)
i2c_register_board_info(msm8960_i2c_devices[i].bus,
msm8960_i2c_devices[i].info,
msm8960_i2c_devices[i].len);
}
#ifdef CONFIG_MSM_CAMERA
if (msm8930_camera_i2c_devices.machs & mach_mask)
i2c_register_board_info(msm8930_camera_i2c_devices.bus,
msm8930_camera_i2c_devices.info,
msm8930_camera_i2c_devices.len);
#endif
#endif
}
static void __init msm8930_cdp_init(void)
{
if (meminfo_init(SYS_MEMORY, SZ_256M) < 0)
pr_err("meminfo_init() failed!\n");
msm_tsens_early_init(&msm_tsens_pdata);
BUG_ON(msm_rpm_init(&msm_rpm_data));
BUG_ON(msm_rpmrs_levels_init(msm_rpmrs_levels,
ARRAY_SIZE(msm_rpmrs_levels)));
regulator_suppress_info_printing();
if (msm_xo_init())
pr_err("Failed to initialize XO votes\n");
platform_device_register(&msm8930_device_rpm_regulator);
msm_clock_init(&msm8960_clock_init_data);
msm8960_device_otg.dev.platform_data = &msm_otg_pdata;
msm_device_hsic_host.dev.platform_data = &msm_hsic_pdata;
msm8930_init_gpiomux();
msm8960_device_qup_spi_gsbi1.dev.platform_data =
&msm8960_qup_spi_gsbi1_pdata;
spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info));
/*
* TODO: When physical 8930/PM8038 hardware becomes
* available, remove this block or add the config
* option.
*/
#ifndef MSM8930_PHASE_2
msm8960_init_pmic();
#else
msm8930_init_pmic();
#endif
msm8930_i2c_init();
msm8930_gfx_init();
msm_spm_init(msm_spm_data, ARRAY_SIZE(msm_spm_data));
msm_spm_l2_init(msm_spm_l2_data);
msm8930_init_buses();
platform_add_devices(msm_footswitch_devices,
msm_num_footswitch_devices);
platform_add_devices(common_devices, ARRAY_SIZE(common_devices));
/*
* TODO: When physical 8930/PM8038 hardware becomes
* available, remove this block or add the config
* option.
*/
#ifndef MSM8930_PHASE_2
msm8960_pm8921_gpio_mpp_init();
#else
msm8930_pm8038_gpio_mpp_init();
#endif
platform_add_devices(cdp_devices, ARRAY_SIZE(cdp_devices));
msm8930_init_hsic();
msm8930_init_cam();
msm8930_init_mmc();
acpuclk_init(&acpuclk_8930_soc_data);
if (machine_is_msm8930_cdp() || machine_is_msm8627_cdp())
mxt_init_vkeys_8930();
register_i2c_devices();
msm8930_init_fb();
slim_register_board_info(msm_slim_devices,
ARRAY_SIZE(msm_slim_devices));
msm_pm_set_platform_data(msm_pm_data, ARRAY_SIZE(msm_pm_data));
msm_pm_set_rpm_wakeup_irq(RPM_APCC_CPU0_WAKE_UP_IRQ);
msm_cpuidle_set_states(msm_cstates, ARRAY_SIZE(msm_cstates),
msm_pm_data);
change_memory_power = &msm8930_change_memory_power;
BUG_ON(msm_pm_boot_init(&msm_pm_boot_pdata));
if (PLATFORM_IS_CHARM25())
platform_add_devices(mdm_devices, ARRAY_SIZE(mdm_devices));
}
MACHINE_START(MSM8930_CDP, "QCT MSM8930 CDP")
.map_io = msm8930_map_io,
.reserve = msm8930_reserve,
.init_irq = msm8930_init_irq,
.handle_irq = gic_handle_irq,
.timer = &msm_timer,
.init_machine = msm8930_cdp_init,
.init_early = msm8930_allocate_memory_regions,
.init_very_early = msm8930_early_memory,
MACHINE_END
MACHINE_START(MSM8930_MTP, "QCT MSM8930 MTP")
.map_io = msm8930_map_io,
.reserve = msm8930_reserve,
.init_irq = msm8930_init_irq,
.handle_irq = gic_handle_irq,
.timer = &msm_timer,
.init_machine = msm8930_cdp_init,
.init_early = msm8930_allocate_memory_regions,
.init_very_early = msm8930_early_memory,
MACHINE_END
MACHINE_START(MSM8930_FLUID, "QCT MSM8930 FLUID")
.map_io = msm8930_map_io,
.reserve = msm8930_reserve,
.init_irq = msm8930_init_irq,
.handle_irq = gic_handle_irq,
.timer = &msm_timer,
.init_machine = msm8930_cdp_init,
.init_early = msm8930_allocate_memory_regions,
.init_very_early = msm8930_early_memory,
MACHINE_END
MACHINE_START(MSM8627_CDP, "QCT MSM8627 CDP")
.map_io = msm8930_map_io,
.reserve = msm8930_reserve,
.init_irq = msm8930_init_irq,
.handle_irq = gic_handle_irq,
.timer = &msm_timer,
.init_machine = msm8930_cdp_init,
.init_early = msm8930_allocate_memory_regions,
.init_very_early = msm8930_early_memory,
MACHINE_END
MACHINE_START(MSM8627_MTP, "QCT MSM8627 MTP")
.map_io = msm8930_map_io,
.reserve = msm8930_reserve,
.init_irq = msm8930_init_irq,
.handle_irq = gic_handle_irq,
.timer = &msm_timer,
.init_machine = msm8930_cdp_init,
.init_early = msm8930_allocate_memory_regions,
.init_very_early = msm8930_early_memory,
MACHINE_END
| animania260/android_ani-kernel_galaxy_reverb | arch/arm/mach-msm/board-8930.c | C | gpl-2.0 | 57,343 |
/* GStreamer
* Copyright (C) 2011 Andoni Morales Alastruey <ylatuya@gmail.com>
*
* gsturidownloader.h:
*
* 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.
*
* Youshould have received a copy of the GNU Library 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.
*/
#ifndef __GSTURI_DOWNLOADER_H__
#define __GSTURI_DOWNLOADER_H__
#include <glib-object.h>
#include <gst/gst.h>
#include "gstfragment.h"
G_BEGIN_DECLS
#define GST_TYPE_URI_DOWNLOADER (gst_uri_downloader_get_type())
#define GST_URI_DOWNLOADER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_URI_DOWNLOADER,GstUriDownloader))
#define GST_URI_DOWNLOADER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_URI_DOWNLOADER,GstUriDownloaderClass))
#define GST_IS_URI_DOWNLOADER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_URI_DOWNLOADER))
#define GST_IS_URI_DOWNLOADER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_URI_DOWNLOADER))
typedef struct _GstUriDownloader GstUriDownloader;
typedef struct _GstUriDownloaderPrivate GstUriDownloaderPrivate;
typedef struct _GstUriDownloaderClass GstUriDownloaderClass;
struct _GstUriDownloader
{
GstObject parent;
GstUriDownloaderPrivate *priv;
};
struct _GstUriDownloaderClass
{
GstObjectClass parent_class;
/*< private >*/
gpointer _gst_reserved[GST_PADDING];
};
GType gst_uri_downloader_get_type (void);
GstUriDownloader * gst_uri_downloader_new (void);
GstFragment * gst_uri_downloader_fetch_uri (GstUriDownloader * downloader, const gchar * uri, const gchar * referer, gboolean compress, gboolean refresh, gboolean allow_cache, GError ** err);
GstFragment * gst_uri_downloader_fetch_uri_with_range (GstUriDownloader * downloader, const gchar * uri, const gchar * referer, gboolean compress, gboolean refresh, gboolean allow_cache, gint64 range_start, gint64 range_end, GError ** err);
void gst_uri_downloader_reset (GstUriDownloader *downloader);
void gst_uri_downloader_cancel (GstUriDownloader *downloader);
void gst_uri_downloader_free (GstUriDownloader *downloader);
G_END_DECLS
#endif /* __GSTURIDOWNLOADER_H__ */
| cee1/gst-plugins-bad | gst-libs/gst/uridownloader/gsturidownloader.h | C | gpl-2.0 | 2,647 |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example96-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.min.js"></script>
</head>
<body ng-app="">
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</body>
</html> | yufieko/rescomm-mis | public/plugins/angular/docs/examples/example-example96/index-production.html | HTML | gpl-2.0 | 488 |
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
import 'bootstrap';
import $ from 'jquery';
import {AjaxResponse} from 'TYPO3/CMS/Core/Ajax/AjaxResponse';
import {AbstractInteractableModule} from '../AbstractInteractableModule';
import Modal = require('TYPO3/CMS/Backend/Modal');
import Notification = require('TYPO3/CMS/Backend/Notification');
import AjaxRequest = require('TYPO3/CMS/Core/Ajax/AjaxRequest');
import InfoBox = require('../../Renderable/InfoBox');
import ProgressBar = require('../../Renderable/ProgressBar');
import Severity = require('../../Renderable/Severity');
import Router = require('../../Router');
/**
* Module: TYPO3/CMS/Install/EnvironmentCheck
*/
class EnvironmentCheck extends AbstractInteractableModule {
private selectorGridderBadge: string = '.t3js-environmentCheck-badge';
private selectorExecuteTrigger: string = '.t3js-environmentCheck-execute';
private selectorOutputContainer: string = '.t3js-environmentCheck-output';
public initialize(currentModal: JQuery): void {
this.currentModal = currentModal;
// Get status on initialize to have the badge and content ready
this.runTests();
currentModal.on('click', this.selectorExecuteTrigger, (e: JQueryEventObject): void => {
e.preventDefault();
this.runTests();
});
}
private runTests(): void {
this.setModalButtonsState(false);
const modalContent = this.getModalBody();
const $errorBadge = $(this.selectorGridderBadge);
$errorBadge.text('').hide();
const message = ProgressBar.render(Severity.loading, 'Loading...', '');
modalContent.find(this.selectorOutputContainer).empty().append(message);
(new AjaxRequest(Router.getUrl('environmentCheckGetStatus')))
.get({cache: 'no-cache'})
.then(
async (response: AjaxResponse): Promise<any> => {
const data = await response.resolve();
modalContent.empty().append(data.html);
Modal.setButtons(data.buttons);
let warningCount = 0;
let errorCount = 0;
if (data.success === true && typeof (data.status) === 'object') {
$.each(data.status, (i: number, element: any): void => {
if (Array.isArray(element) && element.length > 0) {
element.forEach((aStatus: any): void => {
if (aStatus.severity === 1) {
warningCount++;
}
if (aStatus.severity === 2) {
errorCount++;
}
const aMessage = InfoBox.render(aStatus.severity, aStatus.title, aStatus.message);
modalContent.find(this.selectorOutputContainer).append(aMessage);
});
}
});
if (errorCount > 0) {
$errorBadge.removeClass('label-warning').addClass('label-danger').text(errorCount).show();
} else if (warningCount > 0) {
$errorBadge.removeClass('label-error').addClass('label-warning').text(warningCount).show();
}
} else {
Notification.error('Something went wrong', 'The request was not processed successfully. Please check the browser\'s console and TYPO3\'s log.');
}
},
(error: AjaxResponse): void => {
Router.handleAjaxError(error, modalContent);
}
);
}
}
export = new EnvironmentCheck();
| maddy2101/TYPO3.CMS | Build/Sources/TypeScript/install/Resources/Public/TypeScript/Module/Environment/EnvironmentCheck.ts | TypeScript | gpl-2.0 | 3,768 |
<?php
/*
HLstatsX Community Edition - Real-time player and clan rankings and statistics
Copyleft (L) 2008-20XX Nicholas Hastings (nshastings@gmail.com)
http://www.hlxcommunity.com
HLstatsX Community Edition is a continuation of
ELstatsNEO - Real-time player and clan rankings and statistics
Copyleft (L) 2008-20XX Malte Bayer (steam@neo-soft.org)
http://ovrsized.neo-soft.org/
ELstatsNEO is an very improved & enhanced - so called Ultra-Humongus Edition of HLstatsX
HLstatsX - Real-time player and clan rankings and statistics for Half-Life 2
http://www.hlstatsx.com/
Copyright (C) 2005-2007 Tobias Oetzel (Tobi@hlstatsx.com)
HLstatsX is an enhanced version of HLstats made by Simon Garner
HLstats - Real-time player and clan rankings and statistics for Half-Life
http://sourceforge.net/projects/hlstats/
Copyright (C) 2001 Simon Garner
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.
For support and installation notes visit http://www.hlxcommunity.com
*/
if ( !defined('IN_HLSTATS') )
{
die('Do not access this file directly.');
}
flush();
$tblTeams = new Table
(
array
(
new TableColumn
(
'name',
'Team',
'width=35'
),
new TableColumn
(
'teamcount',
'Joined',
'width=10&align=right&append=+times'
),
new TableColumn
(
'percent',
'%',
'width=10&sort=no&align=right&append=' . urlencode('%')
),
new TableColumn
(
'percent',
'Ratio',
'width=40&sort=no&type=bargraph'
)
),
'name',
'teamcount',
'name',
true,
9999,
'teams_page',
'teams_sort',
'teams_sortorder',
'tabteams',
'desc',
true
);
$db->query
("
SELECT
COUNT(*)
FROM
hlstats_Events_ChangeTeam
WHERE
hlstats_Events_ChangeTeam.playerId = $player
");
list($numteamjoins) = $db->fetch_row();
if($numteamjoins == 0) {
$numteamjoins = 1;
}
$result = $db->query
("
SELECT
IFNULL(hlstats_Teams.name, hlstats_Events_ChangeTeam.team) AS name,
COUNT(hlstats_Events_ChangeTeam.id) AS teamcount,
ROUND((COUNT(hlstats_Events_ChangeTeam.id) / $numteamjoins) * 100, 2) AS percent
FROM
hlstats_Events_ChangeTeam
LEFT JOIN
hlstats_Teams
ON
hlstats_Events_ChangeTeam.team = hlstats_Teams.code
WHERE
hlstats_Teams.game = '$game'
AND hlstats_Events_ChangeTeam.playerId = $player
AND
(
hidden <> '1'
OR hidden IS NULL
)
GROUP BY
hlstats_Events_ChangeTeam.team
ORDER BY
$tblTeams->sort $tblTeams->sortorder,
$tblTeams->sort2 $tblTeams->sortorder
");
$numitems = $db->num_rows($result);
if ($numitems > 0)
{
printSectionTitle('Team Selection *');
$tblTeams->draw($result, $numitems, 95);
?>
<br /><br />
<?php
}
flush();
$result = $db->query
("
SELECT
hlstats_Roles.code,
hlstats_Roles.name
FROM
hlstats_Roles
WHERE
hlstats_Roles.game = '$game'
");
while ($rowdata = $db->fetch_row($result))
{
$code = preg_replace("/[ \r\n\t]+/", "", $rowdata[0]);
$fname[strToLower($code)] = htmlspecialchars($rowdata[1]);
}
$tblRoles = new Table
(
array
(
new TableColumn
(
'code',
'Role',
'width=25&type=roleimg&align=left&link=' . urlencode("mode=rolesinfo&role=%k&game=$game"),
$fname
),
new TableColumn
(
'rolecount',
'Joined',
'width=10&align=right&append=+times'
),
new TableColumn
(
'percent',
'%',
'width=10&sort=no&align=right&append=' . urlencode('%')
),
new TableColumn
(
'percent',
'Ratio',
'width=20&sort=no&type=bargraph'
),
new TableColumn
(
'killsTotal',
'Kills',
'width=10&align=right'
),
new TableColumn
(
'deathsTotal',
'Deaths',
'width=10&align=right'
),
new TableColumn
(
'kpd',
'K:D',
'width=10&align=right'
)
),
'code',
'rolecount',
'name',
true,
9999,
'roles_page',
'roles_sort',
'roles_sortorder',
'roles',
'desc',
true
);
$db->query
("
DROP TABLE IF EXISTS
hlstats_Frags_as
");
$db->query
("
CREATE TEMPORARY TABLE
hlstats_Frags_as
(
playerId INT(10),
kills INT(10),
deaths INT(10),
role varchar(128) NOT NULL default ''
)
");
$db->query
("
INSERT INTO
hlstats_Frags_as
(
playerId,
kills,
role
)
SELECT
hlstats_Events_Frags.victimId,
hlstats_Events_Frags.killerId,
hlstats_Events_Frags.killerRole
FROM
hlstats_Events_Frags
WHERE
hlstats_Events_Frags.killerId = $player
");
$db->query
("
INSERT INTO
hlstats_Frags_as
(
playerId,
deaths,
role
)
SELECT
hlstats_Events_Frags.killerId,
hlstats_Events_Frags.victimId,
hlstats_Events_Frags.victimRole
FROM
hlstats_Events_Frags
WHERE
hlstats_Events_Frags.victimId = $player
");
$db->query
("
DROP TABLE IF EXISTS
hlstats_Frags_as_res
");
$db->query
("
CREATE TEMPORARY TABLE
hlstats_Frags_as_res
(
killsTotal INT(10),
deathsTotal INT(10),
role varchar(128) NOT NULL default ''
)
");
$db->query
("
INSERT INTO
hlstats_Frags_as_res
(
killsTotal,
deathsTotal,
role
)
SELECT
COUNT(hlstats_Frags_as.kills) AS kills,
COUNT(hlstats_Frags_as.deaths) AS deaths,
hlstats_Frags_as.role
FROM
hlstats_Frags_as
GROUP BY
hlstats_Frags_as.role
");
$db->query
("
SELECT
COUNT(*)
FROM
hlstats_Events_ChangeRole
WHERE
hlstats_Events_ChangeRole.playerId = $player
");
list($numrolejoins) = $db->fetch_row();
$result = $db->query
("
SELECT
IFNULL(hlstats_Roles.name, hlstats_Events_ChangeRole.role) AS name,
IFNULL(hlstats_Roles.code, hlstats_Events_ChangeRole.role) AS code,
COUNT(hlstats_Events_ChangeRole.id) AS rolecount,
ROUND(COUNT(hlstats_Events_ChangeRole.id) / IF($numrolejoins = 0, 1, $numrolejoins) * 100, 2) AS percent,
hlstats_Frags_as_res.killsTotal,
hlstats_Frags_as_res.deathsTotal,
ROUND(hlstats_Frags_as_res.killsTotal / IF(hlstats_Frags_as_res.deathsTotal = 0, 1, hlstats_Frags_as_res.deathsTotal), 2) AS kpd
FROM
hlstats_Events_ChangeRole
LEFT JOIN
hlstats_Roles
ON
hlstats_Events_ChangeRole.role = hlstats_Roles.code
LEFT JOIN
hlstats_Frags_as_res
ON
hlstats_Frags_as_res.role = hlstats_Events_ChangeRole.role
WHERE
hlstats_Events_ChangeRole.playerId = $player
AND
(
hidden <> '1'
OR hidden IS NULL
)
AND hlstats_Roles.game = '$game'
GROUP BY
hlstats_Events_ChangeRole.role
ORDER BY
$tblRoles->sort $tblRoles->sortorder,
$tblRoles->sort2 $tblRoles->sortorder
");
$numitems = $db->num_rows($result);
if ($numitems > 0)
{
printSectionTitle('Role Selection *');
$tblRoles->draw($result, $numitems, 95);
?>
<br /><br />
<?php
}
?>
| rcguy/insurgency-hlstatsx | web/pages/playerinfo_teams.php | PHP | gpl-2.0 | 7,693 |
/*
* Copyright (C) 2002-2011 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.
*/
static void FPU_FINIT(void) {
FPU_SetCW(0x37F);
fpu.sw = 0;
TOP=FPU_GET_TOP();
fpu.tags[0] = TAG_Empty;
fpu.tags[1] = TAG_Empty;
fpu.tags[2] = TAG_Empty;
fpu.tags[3] = TAG_Empty;
fpu.tags[4] = TAG_Empty;
fpu.tags[5] = TAG_Empty;
fpu.tags[6] = TAG_Empty;
fpu.tags[7] = TAG_Empty;
fpu.tags[8] = TAG_Valid; // is only used by us
}
static void FPU_FCLEX(void){
fpu.sw &= 0x7f00; //should clear exceptions
}
static void FPU_FNOP(void){
return;
}
static void FPU_PUSH(double in){
TOP = (TOP - 1) &7;
//actually check if empty
fpu.tags[TOP] = TAG_Valid;
fpu.regs[TOP].d = in;
// LOG(LOG_FPU,LOG_ERROR)("Pushed at %d %g to the stack",newtop,in);
return;
}
static void FPU_PREP_PUSH(void){
TOP = (TOP - 1) &7;
fpu.tags[TOP] = TAG_Valid;
}
static void FPU_FPOP(void){
fpu.tags[TOP]=TAG_Empty;
//maybe set zero in it as well
TOP = ((TOP+1)&7);
// LOG(LOG_FPU,LOG_ERROR)("popped from %d %g off the stack",top,fpu.regs[top].d);
return;
}
static double FROUND(double in){
switch(fpu.round){
case ROUND_Nearest:
if (in-floor(in)>0.5) return (floor(in)+1);
else if (in-floor(in)<0.5) return (floor(in));
else return (((static_cast<Bit64s>(floor(in)))&1)!=0)?(floor(in)+1):(floor(in));
break;
case ROUND_Down:
return (floor(in));
break;
case ROUND_Up:
return (ceil(in));
break;
case ROUND_Chop:
return in; //the cast afterwards will do it right maybe cast here
break;
default:
return in;
break;
}
}
#define BIAS80 16383
#define BIAS64 1023
static Real64 FPU_FLD80(PhysPt addr) {
struct {
Bit16s begin;
FPU_Reg eind;
} test;
test.eind.l.lower = mem_readd(addr);
test.eind.l.upper = mem_readd(addr+4);
test.begin = mem_readw(addr+8);
Bit64s exp64 = (((test.begin&0x7fff) - BIAS80));
Bit64s blah = ((exp64 >0)?exp64:-exp64)&0x3ff;
Bit64s exp64final = ((exp64 >0)?blah:-blah) +BIAS64;
Bit64s mant64 = (test.eind.ll >> 11) & LONGTYPE(0xfffffffffffff);
Bit64s sign = (test.begin&0x8000)?1:0;
FPU_Reg result;
result.ll = (sign <<63)|(exp64final << 52)| mant64;
if(test.eind.l.lower == 0 && test.eind.l.upper == 0x80000000 && (test.begin&0x7fff) == 0x7fff) {
//Detect INF and -INF (score 3.11 when drawing a slur.)
result.d = sign?-HUGE_VAL:HUGE_VAL;
}
return result.d;
//mant64= test.mant80/2***64 * 2 **53
}
static void FPU_ST80(PhysPt addr,Bitu reg) {
struct {
Bit16s begin;
FPU_Reg eind;
} test;
Bit64s sign80 = (fpu.regs[reg].ll&LONGTYPE(0x8000000000000000))?1:0;
Bit64s exp80 = fpu.regs[reg].ll&LONGTYPE(0x7ff0000000000000);
Bit64s exp80final = (exp80>>52);
Bit64s mant80 = fpu.regs[reg].ll&LONGTYPE(0x000fffffffffffff);
Bit64s mant80final = (mant80 << 11);
if(fpu.regs[reg].d != 0){ //Zero is a special case
// Elvira wants the 8 and tcalc doesn't
mant80final |= LONGTYPE(0x8000000000000000);
//Ca-cyber doesn't like this when result is zero.
exp80final += (BIAS80 - BIAS64);
}
test.begin = (static_cast<Bit16s>(sign80)<<15)| static_cast<Bit16s>(exp80final);
test.eind.ll = mant80final;
mem_writed(addr,test.eind.l.lower);
mem_writed(addr+4,test.eind.l.upper);
mem_writew(addr+8,test.begin);
}
static void FPU_FLD_F32(PhysPt addr,Bitu store_to) {
union {
float f;
Bit32u l;
} blah;
blah.l = mem_readd(addr);
fpu.regs[store_to].d = static_cast<Real64>(blah.f);
}
static void FPU_FLD_F64(PhysPt addr,Bitu store_to) {
fpu.regs[store_to].l.lower = mem_readd(addr);
fpu.regs[store_to].l.upper = mem_readd(addr+4);
}
static void FPU_FLD_F80(PhysPt addr) {
fpu.regs[TOP].d = FPU_FLD80(addr);
}
static void FPU_FLD_I16(PhysPt addr,Bitu store_to) {
Bit16s blah = mem_readw(addr);
fpu.regs[store_to].d = static_cast<Real64>(blah);
}
static void FPU_FLD_I32(PhysPt addr,Bitu store_to) {
Bit32s blah = mem_readd(addr);
fpu.regs[store_to].d = static_cast<Real64>(blah);
}
static void FPU_FLD_I64(PhysPt addr,Bitu store_to) {
FPU_Reg blah;
blah.l.lower = mem_readd(addr);
blah.l.upper = mem_readd(addr+4);
fpu.regs[store_to].d = static_cast<Real64>(blah.ll);
}
static void FPU_FBLD(PhysPt addr,Bitu store_to) {
Bit64u val = 0;
Bitu in = 0;
Bit64u base = 1;
for(Bitu i = 0;i < 9;i++){
in = mem_readb(addr + i);
val += ( (in&0xf) * base); //in&0xf shouldn't be higher then 9
base *= 10;
val += ((( in>>4)&0xf) * base);
base *= 10;
}
//last number, only now convert to float in order to get
//the best signification
Real64 temp = static_cast<Real64>(val);
in = mem_readb(addr + 9);
temp += ( (in&0xf) * base );
if(in&0x80) temp *= -1.0;
fpu.regs[store_to].d = temp;
}
static INLINE void FPU_FLD_F32_EA(PhysPt addr) {
FPU_FLD_F32(addr,8);
}
static INLINE void FPU_FLD_F64_EA(PhysPt addr) {
FPU_FLD_F64(addr,8);
}
static INLINE void FPU_FLD_I32_EA(PhysPt addr) {
FPU_FLD_I32(addr,8);
}
static INLINE void FPU_FLD_I16_EA(PhysPt addr) {
FPU_FLD_I16(addr,8);
}
static void FPU_FST_F32(PhysPt addr) {
union {
float f;
Bit32u l;
} blah;
//should depend on rounding method
blah.f = static_cast<float>(fpu.regs[TOP].d);
mem_writed(addr,blah.l);
}
static void FPU_FST_F64(PhysPt addr) {
mem_writed(addr,fpu.regs[TOP].l.lower);
mem_writed(addr+4,fpu.regs[TOP].l.upper);
}
static void FPU_FST_F80(PhysPt addr) {
FPU_ST80(addr,TOP);
}
static void FPU_FST_I16(PhysPt addr) {
mem_writew(addr,static_cast<Bit16s>(FROUND(fpu.regs[TOP].d)));
}
static void FPU_FST_I32(PhysPt addr) {
mem_writed(addr,static_cast<Bit32s>(FROUND(fpu.regs[TOP].d)));
}
static void FPU_FST_I64(PhysPt addr) {
FPU_Reg blah;
blah.ll = static_cast<Bit64s>(FROUND(fpu.regs[TOP].d));
mem_writed(addr,blah.l.lower);
mem_writed(addr+4,blah.l.upper);
}
static void FPU_FBST(PhysPt addr) {
FPU_Reg val = fpu.regs[TOP];
bool sign = false;
if(fpu.regs[TOP].ll & LONGTYPE(0x8000000000000000)) { //sign
sign=true;
val.d=-val.d;
}
//numbers from back to front
Real64 temp=val.d;
Bitu p;
for(Bitu i=0;i<9;i++){
val.d=temp;
temp = static_cast<Real64>(static_cast<Bit64s>(floor(val.d/10.0)));
p = static_cast<Bitu>(val.d - 10.0*temp);
val.d=temp;
temp = static_cast<Real64>(static_cast<Bit64s>(floor(val.d/10.0)));
p |= (static_cast<Bitu>(val.d - 10.0*temp)<<4);
mem_writeb(addr+i,p);
}
val.d=temp;
temp = static_cast<Real64>(static_cast<Bit64s>(floor(val.d/10.0)));
p = static_cast<Bitu>(val.d - 10.0*temp);
if(sign)
p|=0x80;
mem_writeb(addr+9,p);
}
static void FPU_FADD(Bitu op1, Bitu op2){
fpu.regs[op1].d+=fpu.regs[op2].d;
//flags and such :)
return;
}
static void FPU_FSIN(void){
fpu.regs[TOP].d = sin(fpu.regs[TOP].d);
FPU_SET_C2(0);
//flags and such :)
return;
}
static void FPU_FSINCOS(void){
Real64 temp = fpu.regs[TOP].d;
fpu.regs[TOP].d = sin(temp);
FPU_PUSH(cos(temp));
FPU_SET_C2(0);
//flags and such :)
return;
}
static void FPU_FCOS(void){
fpu.regs[TOP].d = cos(fpu.regs[TOP].d);
FPU_SET_C2(0);
//flags and such :)
return;
}
static void FPU_FSQRT(void){
fpu.regs[TOP].d = sqrt(fpu.regs[TOP].d);
//flags and such :)
return;
}
static void FPU_FPATAN(void){
fpu.regs[STV(1)].d = atan2(fpu.regs[STV(1)].d,fpu.regs[TOP].d);
FPU_FPOP();
//flags and such :)
return;
}
static void FPU_FPTAN(void){
fpu.regs[TOP].d = tan(fpu.regs[TOP].d);
FPU_PUSH(1.0);
FPU_SET_C2(0);
//flags and such :)
return;
}
static void FPU_FDIV(Bitu st, Bitu other){
fpu.regs[st].d= fpu.regs[st].d/fpu.regs[other].d;
//flags and such :)
return;
}
static void FPU_FDIVR(Bitu st, Bitu other){
fpu.regs[st].d= fpu.regs[other].d/fpu.regs[st].d;
// flags and such :)
return;
}
static void FPU_FMUL(Bitu st, Bitu other){
fpu.regs[st].d*=fpu.regs[other].d;
//flags and such :)
return;
}
static void FPU_FSUB(Bitu st, Bitu other){
fpu.regs[st].d = fpu.regs[st].d - fpu.regs[other].d;
//flags and such :)
return;
}
static void FPU_FSUBR(Bitu st, Bitu other){
fpu.regs[st].d= fpu.regs[other].d - fpu.regs[st].d;
//flags and such :)
return;
}
static void FPU_FXCH(Bitu st, Bitu other){
FPU_Tag tag = fpu.tags[other];
FPU_Reg reg = fpu.regs[other];
fpu.tags[other] = fpu.tags[st];
fpu.regs[other] = fpu.regs[st];
fpu.tags[st] = tag;
fpu.regs[st] = reg;
}
static void FPU_FST(Bitu st, Bitu other){
fpu.tags[other] = fpu.tags[st];
fpu.regs[other] = fpu.regs[st];
}
static void FPU_FCOM(Bitu st, Bitu other){
if(((fpu.tags[st] != TAG_Valid) && (fpu.tags[st] != TAG_Zero)) ||
((fpu.tags[other] != TAG_Valid) && (fpu.tags[other] != TAG_Zero))){
FPU_SET_C3(1);FPU_SET_C2(1);FPU_SET_C0(1);return;
}
if(fpu.regs[st].d == fpu.regs[other].d){
FPU_SET_C3(1);FPU_SET_C2(0);FPU_SET_C0(0);return;
}
if(fpu.regs[st].d < fpu.regs[other].d){
FPU_SET_C3(0);FPU_SET_C2(0);FPU_SET_C0(1);return;
}
// st > other
FPU_SET_C3(0);FPU_SET_C2(0);FPU_SET_C0(0);return;
}
static void FPU_FUCOM(Bitu st, Bitu other){
//does atm the same as fcom
FPU_FCOM(st,other);
}
static void FPU_FRNDINT(void){
Bit64s temp= static_cast<Bit64s>(FROUND(fpu.regs[TOP].d));
fpu.regs[TOP].d=static_cast<double>(temp);
}
static void FPU_FPREM(void){
Real64 valtop = fpu.regs[TOP].d;
Real64 valdiv = fpu.regs[STV(1)].d;
Bit64s ressaved = static_cast<Bit64s>( (valtop/valdiv) );
// Some backups
// Real64 res=valtop - ressaved*valdiv;
// res= fmod(valtop,valdiv);
fpu.regs[TOP].d = valtop - ressaved*valdiv;
FPU_SET_C0(static_cast<Bitu>(ressaved&4));
FPU_SET_C3(static_cast<Bitu>(ressaved&2));
FPU_SET_C1(static_cast<Bitu>(ressaved&1));
FPU_SET_C2(0);
}
static void FPU_FPREM1(void){
Real64 valtop = fpu.regs[TOP].d;
Real64 valdiv = fpu.regs[STV(1)].d;
double quot = valtop/valdiv;
double quotf = floor(quot);
Bit64s ressaved;
if (quot-quotf>0.5) ressaved = static_cast<Bit64s>(quotf+1);
else if (quot-quotf<0.5) ressaved = static_cast<Bit64s>(quotf);
else ressaved = static_cast<Bit64s>((((static_cast<Bit64s>(quotf))&1)!=0)?(quotf+1):(quotf));
fpu.regs[TOP].d = valtop - ressaved*valdiv;
FPU_SET_C0(static_cast<Bitu>(ressaved&4));
FPU_SET_C3(static_cast<Bitu>(ressaved&2));
FPU_SET_C1(static_cast<Bitu>(ressaved&1));
FPU_SET_C2(0);
}
static void FPU_FXAM(void){
if(fpu.regs[TOP].ll & LONGTYPE(0x8000000000000000)) //sign
{
FPU_SET_C1(1);
}
else
{
FPU_SET_C1(0);
}
if(fpu.tags[TOP] == TAG_Empty)
{
FPU_SET_C3(1);FPU_SET_C2(0);FPU_SET_C0(1);
return;
}
if(fpu.regs[TOP].d == 0.0) //zero or normalized number.
{
FPU_SET_C3(1);FPU_SET_C2(0);FPU_SET_C0(0);
}
else
{
FPU_SET_C3(0);FPU_SET_C2(1);FPU_SET_C0(0);
}
}
static void FPU_F2XM1(void){
fpu.regs[TOP].d = pow(2.0,fpu.regs[TOP].d) - 1;
return;
}
static void FPU_FYL2X(void){
fpu.regs[STV(1)].d*=log(fpu.regs[TOP].d)/log(static_cast<Real64>(2.0));
FPU_FPOP();
return;
}
static void FPU_FYL2XP1(void){
fpu.regs[STV(1)].d*=log(fpu.regs[TOP].d+1.0)/log(static_cast<Real64>(2.0));
FPU_FPOP();
return;
}
static void FPU_FSCALE(void){
fpu.regs[TOP].d *= pow(2.0,static_cast<Real64>(static_cast<Bit64s>(fpu.regs[STV(1)].d)));
return; //2^x where x is chopped.
}
static void FPU_FSTENV(PhysPt addr){
FPU_SET_TOP(TOP);
if(!cpu.code.big) {
mem_writew(addr+0,static_cast<Bit16u>(fpu.cw));
mem_writew(addr+2,static_cast<Bit16u>(fpu.sw));
mem_writew(addr+4,static_cast<Bit16u>(FPU_GetTag()));
} else {
mem_writed(addr+0,static_cast<Bit32u>(fpu.cw));
mem_writed(addr+4,static_cast<Bit32u>(fpu.sw));
mem_writed(addr+8,static_cast<Bit32u>(FPU_GetTag()));
}
}
static void FPU_FLDENV(PhysPt addr){
Bit16u tag;
Bit32u tagbig;
Bitu cw;
if(!cpu.code.big) {
cw = mem_readw(addr+0);
fpu.sw = mem_readw(addr+2);
tag = mem_readw(addr+4);
} else {
cw = mem_readd(addr+0);
fpu.sw = (Bit16u)mem_readd(addr+4);
tagbig = mem_readd(addr+8);
tag = static_cast<Bit16u>(tagbig);
}
FPU_SetTag(tag);
FPU_SetCW(cw);
TOP = FPU_GET_TOP();
}
static void FPU_FSAVE(PhysPt addr){
FPU_FSTENV(addr);
Bitu start = (cpu.code.big?28:14);
for(Bitu i = 0;i < 8;i++){
FPU_ST80(addr+start,STV(i));
start += 10;
}
FPU_FINIT();
}
static void FPU_FRSTOR(PhysPt addr){
FPU_FLDENV(addr);
Bitu start = (cpu.code.big?28:14);
for(Bitu i = 0;i < 8;i++){
fpu.regs[STV(i)].d = FPU_FLD80(addr+start);
start += 10;
}
}
static void FPU_FXTRACT(void) {
// function stores real bias in st and
// pushes the significant number onto the stack
// if double ever uses a different base please correct this function
FPU_Reg test = fpu.regs[TOP];
Bit64s exp80 = test.ll&LONGTYPE(0x7ff0000000000000);
Bit64s exp80final = (exp80>>52) - BIAS64;
Real64 mant = test.d / (pow(2.0,static_cast<Real64>(exp80final)));
fpu.regs[TOP].d = static_cast<Real64>(exp80final);
FPU_PUSH(mant);
}
static void FPU_FCHS(void){
fpu.regs[TOP].d = -1.0*(fpu.regs[TOP].d);
}
static void FPU_FABS(void){
fpu.regs[TOP].d = fabs(fpu.regs[TOP].d);
}
static void FPU_FTST(void){
fpu.regs[8].d = 0.0;
FPU_FCOM(TOP,8);
}
static void FPU_FLD1(void){
FPU_PREP_PUSH();
fpu.regs[TOP].d = 1.0;
}
static void FPU_FLDL2T(void){
FPU_PREP_PUSH();
fpu.regs[TOP].d = L2T;
}
static void FPU_FLDL2E(void){
FPU_PREP_PUSH();
fpu.regs[TOP].d = L2E;
}
static void FPU_FLDPI(void){
FPU_PREP_PUSH();
fpu.regs[TOP].d = PI;
}
static void FPU_FLDLG2(void){
FPU_PREP_PUSH();
fpu.regs[TOP].d = LG2;
}
static void FPU_FLDLN2(void){
FPU_PREP_PUSH();
fpu.regs[TOP].d = LN2;
}
static void FPU_FLDZ(void){
FPU_PREP_PUSH();
fpu.regs[TOP].d = 0.0;
fpu.tags[TOP] = TAG_Zero;
}
static INLINE void FPU_FADD_EA(Bitu op1){
FPU_FADD(op1,8);
}
static INLINE void FPU_FMUL_EA(Bitu op1){
FPU_FMUL(op1,8);
}
static INLINE void FPU_FSUB_EA(Bitu op1){
FPU_FSUB(op1,8);
}
static INLINE void FPU_FSUBR_EA(Bitu op1){
FPU_FSUBR(op1,8);
}
static INLINE void FPU_FDIV_EA(Bitu op1){
FPU_FDIV(op1,8);
}
static INLINE void FPU_FDIVR_EA(Bitu op1){
FPU_FDIVR(op1,8);
}
static INLINE void FPU_FCOM_EA(Bitu op1){
FPU_FCOM(op1,8);
}
| tramboi/veilbox | src/fpu/fpu_instructions.h | C | gpl-2.0 | 14,473 |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2002 Ben Escoto <ben@emerose.org>
# Copyright 2007 Kenneth Loafman <kenneth@loafman.com>
#
# This file is part of duplicity.
#
# Duplicity 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.
#
# Duplicity 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 duplicity; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import helper
import sys, os, unittest
from duplicity import tempdir
helper.setup()
class TempDirTest(unittest.TestCase):
def test_all(self):
td = tempdir.default()
self.assert_(td.mktemp() != td.mktemp())
dir = td.mktemp()
os.mkdir(dir)
os.rmdir(dir)
fd, fname = td.mkstemp()
os.close(fd)
os.unlink(fname)
td.forget(fname)
fo, fname = td.mkstemp_file()
fo.close() # don't forget, leave to cleanup()
td.cleanup()
if __name__ == "__main__":
unittest.main()
| AZed/duplicity | testing/tests/tempdirtest.py | Python | gpl-2.0 | 1,458 |
/*
*
* Marvell Orion Alsa SOC Sound driver
*
* Author: Yuval Elmaliah
* Author: Ethan Ku
* Copyright (C) 2008 Marvell Ltd.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/asoundef.h>
#include <asm/mach-types.h>
//#include <asm/arch/hardware.h>
#include "../sound/soc/codecs/rt5623.h"
#include <linux/mbus.h>
#include <asm/setup.h>
#include <asm/mach/arch.h>
#include <../arch/arm/mach-dove/common.h>
//#include <asm/plat-orion/i2s-orion.h>
#include "mv88fx-pcm.h"
#include "mv88fx-i2s.h"
#include "ctrlEnv/mvCtrlEnvSpec.h"
#include "audio/mvAudioRegs.h"
extern int mvmpp_gpio_get_value(unsigned int);
extern int mvmpp_gpio_set_value(unsigned int,int);
static struct mv88fx_snd_machine_data mv88fx_machine_data;
static struct rt5623_setup_data rt5623_setup;
static int mv88fx_machine_startup(struct snd_pcm_substream *substream)
{
// struct snd_soc_pcm_runtime *rtd = substream->private_data;
// struct snd_soc_codec_dai *codec_dai = rtd->dai->codec_dai;
// struct snd_soc_cpu_dai *cpu_dai = rtd->dai->cpu_dai;
// int ret;
#if 0
int phoneInDetected;
// printk("%s\n",__func__);
/* check the jack status at stream startup */
phoneInDetected = mvmpp_gpio_get_value(MPP_PhLine_IN);
if (phoneInDetected < 0) {
snd_printk("Failed to detect phone-in.\n");
} else {
if (! phoneInDetected) {
rt5623_setup.mic2_input = 0;
} else {
rt5623_setup.mic2_input = 1;
}
}
#endif
return 0;
}
static void mv88fx_machine_shutdown(struct snd_pcm_substream *substream)
{
// printk("%s\n",__func__);
}
static int mv88fx_machine_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->dai->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->dai->cpu_dai;
unsigned int clk = 0;
int ret = 0;
unsigned int format;
// printk("%s\n",__func__);
/* set codec DAI configuration */
switch (params_rate(params)) {
case 44100:
clk = 11289600;
break;
case 48000:
clk = 12288000;
break;
case 96000:
clk = 24576000;
break;
}
format = SND_SOC_DAIFMT_CBS_CFS | SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF;
ret = codec_dai->ops->set_fmt(codec_dai, format);
if (ret < 0)
return ret;
/* set cpu DAI configuration */
ret = cpu_dai->ops->set_fmt(cpu_dai, format);
if (ret < 0)
return ret;
/* cpu clock is the mv88fx master clock sent to codec */
ret = cpu_dai->ops->set_sysclk(cpu_dai, 0, 0, SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
/* codec system clock is supplied by mv88fx*/
ret = codec_dai->ops->set_sysclk(codec_dai, 0, clk, SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
return 0;
}
static int mv88fx_machine_trigger(struct snd_pcm_substream *substream,int cmd)
{
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
if(substream->stream==SNDRV_PCM_STREAM_PLAYBACK)
{
// mvmpp_gpio_set_value(MPP_Amp_PwrDn,1);
}
break;
case SNDRV_PCM_TRIGGER_STOP:
if(substream->stream==SNDRV_PCM_STREAM_PLAYBACK)
{
// mvmpp_gpio_set_value(MPP_Amp_PwrDn,0);
}
break;
}
return 0;
}
static int mv88fx_rt5623_init(struct snd_soc_codec *codec)
{
mv88fx_snd_debug("");
// mvmpp_gpio_set_value(MPP_Amp_PwrDn,0);
return 0;
}
/* machine stream operations */
static struct snd_soc_ops mv88fx_rt5623_machine_ops =
{
.startup = mv88fx_machine_startup,
.shutdown = mv88fx_machine_shutdown,
.hw_params = mv88fx_machine_hw_params,
.trigger = mv88fx_machine_trigger,
};
static struct snd_soc_dai_link mv88fx_dai = {
.name = "RT5623",
.stream_name = "RT5623",
.cpu_dai = &mv88fx_i2s_dai1,
.codec_dai = &rt5623_dai,
.ops = &mv88fx_rt5623_machine_ops,
.init = mv88fx_rt5623_init,
};
static int mv88fx_probe(struct platform_device *pdev)
{
return 0;
}
static int mv88fx_remove(struct platform_device *pdev)
{
return 0;
}
static struct snd_soc_card dove = {
.name = "Dove",
.platform = &mv88fx_soc_platform,
.probe = mv88fx_probe,
.remove = mv88fx_remove,
/* CPU <--> Codec DAI links */
.dai_link = &mv88fx_dai,
.num_links = 1,
};
static struct rt5623_setup_data rt5623_setup = {
.i2c_address = 0x1a,
.mic2_input = 1,
};
static struct snd_soc_device mv88fx_snd_devdata = {
.card = &dove,
.codec_dev = &soc_codec_dev_rt5623,
.codec_data = &rt5623_setup,
};
static int mv88fx_initalize_machine_data(struct platform_device *pdev)
{
struct resource *r = NULL;
int err = 0;
mv88fx_snd_debug("");
mv88fx_machine_data.port = pdev->id;
mv88fx_machine_data.pdata =
(struct orion_i2s_platform_data *)pdev->dev.platform_data;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r) {
err = -ENXIO;
goto error;
}
r = request_mem_region(r->start, SZ_16K, DRIVER_NAME);
if (!r) {
err = -EBUSY;
goto error;
}
mv88fx_machine_data.res = r;
mv88fx_machine_data.base = ioremap(r->start, SZ_16K);
if (!mv88fx_machine_data.base) {
mv88fx_snd_error("ioremap failed");
err = -ENOMEM;
goto error;
}
mv88fx_machine_data.base -= MV_AUDIO_REGS_OFFSET(mv88fx_machine_data.port);
mv88fx_machine_data.irq = platform_get_irq(pdev, 0);
if (mv88fx_machine_data.irq == NO_IRQ) {
err = -ENXIO;
goto error;
}
#if defined(CONFIG_HAVE_CLK)
mv88fx_machine_data.clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(mv88fx_machine_data.clk))
dev_notice(&pdev->dev, "cannot get clkdev\n");
else
clk_enable(mv88fx_machine_data.clk);
#endif
return 0;
error:
if (mv88fx_machine_data.base) {
iounmap(mv88fx_machine_data.base);
mv88fx_machine_data.base = NULL;
}
release_mem_region(mv88fx_machine_data.res->start, SZ_16K);
return err;
}
static int mv88fx_snd_probe(struct platform_device *pdev)
{
int ret = 0;
mv88fx_snd_debug("");
if (mv88fx_initalize_machine_data(pdev) != 0)
goto error;
mv88fx_machine_data.snd_dev = platform_device_alloc("soc-audio", pdev->id);
if (!mv88fx_machine_data.snd_dev) {
ret = -ENOMEM;
goto error;
}
platform_set_drvdata(mv88fx_machine_data.snd_dev, &mv88fx_snd_devdata);
mv88fx_snd_devdata.dev = &mv88fx_machine_data.snd_dev->dev;
mv88fx_machine_data.snd_dev->dev.platform_data = &mv88fx_machine_data;
ret = platform_device_add(mv88fx_machine_data.snd_dev);
if(ret)
{
platform_device_put(mv88fx_machine_data.snd_dev);
}
return ret;
error:
mv88fx_snd_error("");
#if defined(CONFIG_HAVE_CLK)
if (!IS_ERR(mv88fx_machine_data.clk)) {
clk_disable(mv88fx_machine_data.clk);
clk_put(mv88fx_machine_data.clk);
}
#endif
if (mv88fx_machine_data.snd_dev)
platform_device_unregister(mv88fx_machine_data.snd_dev);
return ret;
}
static int mv88fx_snd_remove(struct platform_device *dev)
{
mv88fx_snd_debug("");
#if defined(CONFIG_HAVE_CLK)
if (!IS_ERR(mv88fx_machine_data.clk)) {
clk_disable(mv88fx_machine_data.clk);
clk_put(mv88fx_machine_data.clk);
}
#endif
mv88fx_machine_data.snd_dev->dev.platform_data = NULL;
platform_device_unregister(mv88fx_machine_data.snd_dev);
release_mem_region(mv88fx_machine_data.res->start, SZ_16K);
return 0;
}
static struct platform_driver mv88fx_snd_driver = {
.probe = mv88fx_snd_probe,
.remove = mv88fx_snd_remove,
.suspend = NULL,
.resume = NULL,
.driver = {
.name = DRIVER_NAME,
},
};
static int __init mv88fx_snd_init(void)
{
if (!machine_is_dove_rd_avng())
return -ENODEV;
mv88fx_snd_debug("");
return platform_driver_register(&mv88fx_snd_driver);
}
static void __exit mv88fx_snd_exit(void)
{
mv88fx_snd_debug("");
platform_driver_unregister(&mv88fx_snd_driver);
}
module_init(mv88fx_snd_init);
module_exit(mv88fx_snd_exit);
/* Module information */
MODULE_AUTHOR("Yuval Elmaliah <eyuval@marvell.com>");
MODULE_AUTHOR("Ethan Ku <eku@marvell.com>");
MODULE_DESCRIPTION("ALSA SoC Dove");
MODULE_LICENSE("GPL");
| Globalscale/D3-Linux | arch/arm/plat-orion/mv_hal_drivers/mv_drivers_lsp/mv_audio_soc/mv88fx-rt5623.c | C | gpl-2.0 | 8,127 |
// Copyright 2013 Dolphin Emulator Project
// Licensed under GPLv2
// Refer to the license.txt file included.
#pragma once
#include <wx/bitmap.h>
#include <wx/defs.h>
#include <wx/event.h>
#include <wx/gdicmn.h>
#include <wx/panel.h>
#include <wx/string.h>
#include <wx/translation.h>
#include <wx/windowid.h>
#include "Common/CommonTypes.h"
#include "Common/Event.h"
#include "DolphinWX/Globals.h"
class CFrame;
class CRegisterWindow;
class CWatchWindow;
class CBreakPointWindow;
class CMemoryWindow;
class CJitWindow;
class CCodeView;
class DSPDebuggerLLE;
class GFXDebuggerPanel;
struct SCoreStartupParameter;
class wxToolBar;
class wxListBox;
class wxMenu;
class wxMenuBar;
class CCodeWindow : public wxPanel
{
public:
CCodeWindow(const SCoreStartupParameter& _LocalCoreStartupParameter,
CFrame * parent,
wxWindowID id = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxTAB_TRAVERSAL | wxBORDER_NONE,
const wxString& name = _("Code"));
void Load();
void Save();
// Parent interaction
CFrame *Parent;
wxMenuBar * GetMenuBar();
wxToolBar * GetToolBar();
wxBitmap m_Bitmaps[Toolbar_Debug_Bitmap_Max];
bool UseInterpreter();
bool BootToPause();
bool AutomaticStart();
bool JITNoBlockCache();
bool JITNoBlockLinking();
bool JumpToAddress(u32 address);
void Update() override;
void NotifyMapLoaded();
void CreateMenu(const SCoreStartupParameter& _LocalCoreStartupParameter, wxMenuBar *pMenuBar);
void CreateMenuOptions(wxMenu *pMenu);
void CreateMenuSymbols(wxMenuBar *pMenuBar);
void RecreateToolbar(wxToolBar*);
void PopulateToolbar(wxToolBar* toolBar);
void UpdateButtonStates();
void OpenPages();
void UpdateManager();
// Menu bar
// -------------------
void OnCPUMode(wxCommandEvent& event); // CPU Mode menu
void OnJITOff(wxCommandEvent& event);
void ToggleCodeWindow(bool bShow);
void ToggleRegisterWindow(bool bShow);
void ToggleWatchWindow(bool bShow);
void ToggleBreakPointWindow(bool bShow);
void ToggleMemoryWindow(bool bShow);
void ToggleJitWindow(bool bShow);
void ToggleSoundWindow(bool bShow);
void ToggleVideoWindow(bool bShow);
void OnChangeFont(wxCommandEvent& event);
void OnCodeStep(wxCommandEvent& event);
void OnAddrBoxChange(wxCommandEvent& event);
void OnSymbolsMenu(wxCommandEvent& event);
void OnJitMenu(wxCommandEvent& event);
void OnProfilerMenu(wxCommandEvent& event);
// Sub dialogs
CRegisterWindow* m_RegisterWindow;
CWatchWindow* m_WatchWindow;
CBreakPointWindow* m_BreakpointWindow;
CMemoryWindow* m_MemoryWindow;
CJitWindow* m_JitWindow;
DSPDebuggerLLE* m_SoundWindow;
GFXDebuggerPanel* m_VideoWindow;
// Settings
bool bAutomaticStart; bool bBootToPause;
bool bShowOnStart[IDM_VIDEO_WINDOW - IDM_LOG_WINDOW + 1];
int iNbAffiliation[IDM_CODE_WINDOW - IDM_LOG_WINDOW + 1];
private:
void OnSymbolListChange(wxCommandEvent& event);
void OnSymbolListContextMenu(wxContextMenuEvent& event);
void OnCallstackListChange(wxCommandEvent& event);
void OnCallersListChange(wxCommandEvent& event);
void OnCallsListChange(wxCommandEvent& event);
void OnCodeViewChange(wxCommandEvent &event);
void OnHostMessage(wxCommandEvent& event);
// Debugger functions
void SingleStep();
void StepOver();
void StepOut();
void ToggleBreakpoint();
void UpdateLists();
void UpdateCallstack();
void InitBitmaps();
CCodeView* codeview;
wxListBox* callstack;
wxListBox* symbols;
wxListBox* callers;
wxListBox* calls;
Common::Event sync_event;
};
| dragonbane0/dolphin | Source/Core/DolphinWX/Debugger/CodeWindow.h | C | gpl-2.0 | 3,573 |
/* bnx2x_cmn.c: QLogic Everest network driver.
*
* Copyright (c) 2007-2013 Broadcom Corporation
* Copyright (c) 2014 QLogic Corporation
* All rights reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* Maintained by: Ariel Elior <ariel.elior@qlogic.com>
* Written by: Eliezer Tamir
* Based on code from Michael Chan's bnx2 driver
* UDP CSUM errata workaround by Arik Gendelman
* Slowpath and fastpath rework by Vladislav Zolotarov
* Statistics and Link management by Yitchak Gertner
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/etherdevice.h>
#include <linux/if_vlan.h>
#include <linux/interrupt.h>
#include <linux/ip.h>
#include <linux/crash_dump.h>
#include <net/tcp.h>
#include <net/ipv6.h>
#include <net/ip6_checksum.h>
#include <net/busy_poll.h>
#include <linux/prefetch.h>
#include "bnx2x_cmn.h"
#include "bnx2x_init.h"
#include "bnx2x_sp.h"
static void bnx2x_free_fp_mem_cnic(struct bnx2x *bp);
static int bnx2x_alloc_fp_mem_cnic(struct bnx2x *bp);
static int bnx2x_alloc_fp_mem(struct bnx2x *bp);
static int bnx2x_poll(struct napi_struct *napi, int budget);
static void bnx2x_add_all_napi_cnic(struct bnx2x *bp)
{
int i;
/* Add NAPI objects */
for_each_rx_queue_cnic(bp, i) {
netif_napi_add(bp->dev, &bnx2x_fp(bp, i, napi),
bnx2x_poll, NAPI_POLL_WEIGHT);
}
}
static void bnx2x_add_all_napi(struct bnx2x *bp)
{
int i;
/* Add NAPI objects */
for_each_eth_queue(bp, i) {
netif_napi_add(bp->dev, &bnx2x_fp(bp, i, napi),
bnx2x_poll, NAPI_POLL_WEIGHT);
}
}
static int bnx2x_calc_num_queues(struct bnx2x *bp)
{
int nq = bnx2x_num_queues ? : netif_get_num_default_rss_queues();
/* Reduce memory usage in kdump environment by using only one queue */
if (is_kdump_kernel())
nq = 1;
nq = clamp(nq, 1, BNX2X_MAX_QUEUES(bp));
return nq;
}
/**
* bnx2x_move_fp - move content of the fastpath structure.
*
* @bp: driver handle
* @from: source FP index
* @to: destination FP index
*
* Makes sure the contents of the bp->fp[to].napi is kept
* intact. This is done by first copying the napi struct from
* the target to the source, and then mem copying the entire
* source onto the target. Update txdata pointers and related
* content.
*/
static inline void bnx2x_move_fp(struct bnx2x *bp, int from, int to)
{
struct bnx2x_fastpath *from_fp = &bp->fp[from];
struct bnx2x_fastpath *to_fp = &bp->fp[to];
struct bnx2x_sp_objs *from_sp_objs = &bp->sp_objs[from];
struct bnx2x_sp_objs *to_sp_objs = &bp->sp_objs[to];
struct bnx2x_fp_stats *from_fp_stats = &bp->fp_stats[from];
struct bnx2x_fp_stats *to_fp_stats = &bp->fp_stats[to];
int old_max_eth_txqs, new_max_eth_txqs;
int old_txdata_index = 0, new_txdata_index = 0;
struct bnx2x_agg_info *old_tpa_info = to_fp->tpa_info;
/* Copy the NAPI object as it has been already initialized */
from_fp->napi = to_fp->napi;
/* Move bnx2x_fastpath contents */
memcpy(to_fp, from_fp, sizeof(*to_fp));
to_fp->index = to;
/* Retain the tpa_info of the original `to' version as we don't want
* 2 FPs to contain the same tpa_info pointer.
*/
to_fp->tpa_info = old_tpa_info;
/* move sp_objs contents as well, as their indices match fp ones */
memcpy(to_sp_objs, from_sp_objs, sizeof(*to_sp_objs));
/* move fp_stats contents as well, as their indices match fp ones */
memcpy(to_fp_stats, from_fp_stats, sizeof(*to_fp_stats));
/* Update txdata pointers in fp and move txdata content accordingly:
* Each fp consumes 'max_cos' txdata structures, so the index should be
* decremented by max_cos x delta.
*/
old_max_eth_txqs = BNX2X_NUM_ETH_QUEUES(bp) * (bp)->max_cos;
new_max_eth_txqs = (BNX2X_NUM_ETH_QUEUES(bp) - from + to) *
(bp)->max_cos;
if (from == FCOE_IDX(bp)) {
old_txdata_index = old_max_eth_txqs + FCOE_TXQ_IDX_OFFSET;
new_txdata_index = new_max_eth_txqs + FCOE_TXQ_IDX_OFFSET;
}
memcpy(&bp->bnx2x_txq[new_txdata_index],
&bp->bnx2x_txq[old_txdata_index],
sizeof(struct bnx2x_fp_txdata));
to_fp->txdata_ptr[0] = &bp->bnx2x_txq[new_txdata_index];
}
/**
* bnx2x_fill_fw_str - Fill buffer with FW version string.
*
* @bp: driver handle
* @buf: character buffer to fill with the fw name
* @buf_len: length of the above buffer
*
*/
void bnx2x_fill_fw_str(struct bnx2x *bp, char *buf, size_t buf_len)
{
if (IS_PF(bp)) {
u8 phy_fw_ver[PHY_FW_VER_LEN];
phy_fw_ver[0] = '\0';
bnx2x_get_ext_phy_fw_version(&bp->link_params,
phy_fw_ver, PHY_FW_VER_LEN);
strlcpy(buf, bp->fw_ver, buf_len);
snprintf(buf + strlen(bp->fw_ver), 32 - strlen(bp->fw_ver),
"bc %d.%d.%d%s%s",
(bp->common.bc_ver & 0xff0000) >> 16,
(bp->common.bc_ver & 0xff00) >> 8,
(bp->common.bc_ver & 0xff),
((phy_fw_ver[0] != '\0') ? " phy " : ""), phy_fw_ver);
} else {
bnx2x_vf_fill_fw_str(bp, buf, buf_len);
}
}
/**
* bnx2x_shrink_eth_fp - guarantees fastpath structures stay intact
*
* @bp: driver handle
* @delta: number of eth queues which were not allocated
*/
static void bnx2x_shrink_eth_fp(struct bnx2x *bp, int delta)
{
int i, cos, old_eth_num = BNX2X_NUM_ETH_QUEUES(bp);
/* Queue pointer cannot be re-set on an fp-basis, as moving pointer
* backward along the array could cause memory to be overridden
*/
for (cos = 1; cos < bp->max_cos; cos++) {
for (i = 0; i < old_eth_num - delta; i++) {
struct bnx2x_fastpath *fp = &bp->fp[i];
int new_idx = cos * (old_eth_num - delta) + i;
memcpy(&bp->bnx2x_txq[new_idx], fp->txdata_ptr[cos],
sizeof(struct bnx2x_fp_txdata));
fp->txdata_ptr[cos] = &bp->bnx2x_txq[new_idx];
}
}
}
int bnx2x_load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
/* free skb in the packet ring at pos idx
* return idx of last bd freed
*/
static u16 bnx2x_free_tx_pkt(struct bnx2x *bp, struct bnx2x_fp_txdata *txdata,
u16 idx, unsigned int *pkts_compl,
unsigned int *bytes_compl)
{
struct sw_tx_bd *tx_buf = &txdata->tx_buf_ring[idx];
struct eth_tx_start_bd *tx_start_bd;
struct eth_tx_bd *tx_data_bd;
struct sk_buff *skb = tx_buf->skb;
u16 bd_idx = TX_BD(tx_buf->first_bd), new_cons;
int nbd;
u16 split_bd_len = 0;
/* prefetch skb end pointer to speedup dev_kfree_skb() */
prefetch(&skb->end);
DP(NETIF_MSG_TX_DONE, "fp[%d]: pkt_idx %d buff @(%p)->skb %p\n",
txdata->txq_index, idx, tx_buf, skb);
tx_start_bd = &txdata->tx_desc_ring[bd_idx].start_bd;
nbd = le16_to_cpu(tx_start_bd->nbd) - 1;
#ifdef BNX2X_STOP_ON_ERROR
if ((nbd - 1) > (MAX_SKB_FRAGS + 2)) {
BNX2X_ERR("BAD nbd!\n");
bnx2x_panic();
}
#endif
new_cons = nbd + tx_buf->first_bd;
/* Get the next bd */
bd_idx = TX_BD(NEXT_TX_IDX(bd_idx));
/* Skip a parse bd... */
--nbd;
bd_idx = TX_BD(NEXT_TX_IDX(bd_idx));
if (tx_buf->flags & BNX2X_HAS_SECOND_PBD) {
/* Skip second parse bd... */
--nbd;
bd_idx = TX_BD(NEXT_TX_IDX(bd_idx));
}
/* TSO headers+data bds share a common mapping. See bnx2x_tx_split() */
if (tx_buf->flags & BNX2X_TSO_SPLIT_BD) {
tx_data_bd = &txdata->tx_desc_ring[bd_idx].reg_bd;
split_bd_len = BD_UNMAP_LEN(tx_data_bd);
--nbd;
bd_idx = TX_BD(NEXT_TX_IDX(bd_idx));
}
/* unmap first bd */
dma_unmap_single(&bp->pdev->dev, BD_UNMAP_ADDR(tx_start_bd),
BD_UNMAP_LEN(tx_start_bd) + split_bd_len,
DMA_TO_DEVICE);
/* now free frags */
while (nbd > 0) {
tx_data_bd = &txdata->tx_desc_ring[bd_idx].reg_bd;
dma_unmap_page(&bp->pdev->dev, BD_UNMAP_ADDR(tx_data_bd),
BD_UNMAP_LEN(tx_data_bd), DMA_TO_DEVICE);
if (--nbd)
bd_idx = TX_BD(NEXT_TX_IDX(bd_idx));
}
/* release skb */
WARN_ON(!skb);
if (likely(skb)) {
(*pkts_compl)++;
(*bytes_compl) += skb->len;
dev_kfree_skb_any(skb);
}
tx_buf->first_bd = 0;
tx_buf->skb = NULL;
return new_cons;
}
int bnx2x_tx_int(struct bnx2x *bp, struct bnx2x_fp_txdata *txdata)
{
struct netdev_queue *txq;
u16 hw_cons, sw_cons, bd_cons = txdata->tx_bd_cons;
unsigned int pkts_compl = 0, bytes_compl = 0;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return -1;
#endif
txq = netdev_get_tx_queue(bp->dev, txdata->txq_index);
hw_cons = le16_to_cpu(*txdata->tx_cons_sb);
sw_cons = txdata->tx_pkt_cons;
while (sw_cons != hw_cons) {
u16 pkt_cons;
pkt_cons = TX_BD(sw_cons);
DP(NETIF_MSG_TX_DONE,
"queue[%d]: hw_cons %u sw_cons %u pkt_cons %u\n",
txdata->txq_index, hw_cons, sw_cons, pkt_cons);
bd_cons = bnx2x_free_tx_pkt(bp, txdata, pkt_cons,
&pkts_compl, &bytes_compl);
sw_cons++;
}
netdev_tx_completed_queue(txq, pkts_compl, bytes_compl);
txdata->tx_pkt_cons = sw_cons;
txdata->tx_bd_cons = bd_cons;
/* Need to make the tx_bd_cons update visible to start_xmit()
* before checking for netif_tx_queue_stopped(). Without the
* memory barrier, there is a small possibility that
* start_xmit() will miss it and cause the queue to be stopped
* forever.
* On the other hand we need an rmb() here to ensure the proper
* ordering of bit testing in the following
* netif_tx_queue_stopped(txq) call.
*/
smp_mb();
if (unlikely(netif_tx_queue_stopped(txq))) {
/* Taking tx_lock() is needed to prevent re-enabling the queue
* while it's empty. This could have happen if rx_action() gets
* suspended in bnx2x_tx_int() after the condition before
* netif_tx_wake_queue(), while tx_action (bnx2x_start_xmit()):
*
* stops the queue->sees fresh tx_bd_cons->releases the queue->
* sends some packets consuming the whole queue again->
* stops the queue
*/
__netif_tx_lock(txq, smp_processor_id());
if ((netif_tx_queue_stopped(txq)) &&
(bp->state == BNX2X_STATE_OPEN) &&
(bnx2x_tx_avail(bp, txdata) >= MAX_DESC_PER_TX_PKT))
netif_tx_wake_queue(txq);
__netif_tx_unlock(txq);
}
return 0;
}
static inline void bnx2x_update_last_max_sge(struct bnx2x_fastpath *fp,
u16 idx)
{
u16 last_max = fp->last_max_sge;
if (SUB_S16(idx, last_max) > 0)
fp->last_max_sge = idx;
}
static inline void bnx2x_update_sge_prod(struct bnx2x_fastpath *fp,
u16 sge_len,
struct eth_end_agg_rx_cqe *cqe)
{
struct bnx2x *bp = fp->bp;
u16 last_max, last_elem, first_elem;
u16 delta = 0;
u16 i;
if (!sge_len)
return;
/* First mark all used pages */
for (i = 0; i < sge_len; i++)
BIT_VEC64_CLEAR_BIT(fp->sge_mask,
RX_SGE(le16_to_cpu(cqe->sgl_or_raw_data.sgl[i])));
DP(NETIF_MSG_RX_STATUS, "fp_cqe->sgl[%d] = %d\n",
sge_len - 1, le16_to_cpu(cqe->sgl_or_raw_data.sgl[sge_len - 1]));
/* Here we assume that the last SGE index is the biggest */
prefetch((void *)(fp->sge_mask));
bnx2x_update_last_max_sge(fp,
le16_to_cpu(cqe->sgl_or_raw_data.sgl[sge_len - 1]));
last_max = RX_SGE(fp->last_max_sge);
last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
/* If ring is not full */
if (last_elem + 1 != first_elem)
last_elem++;
/* Now update the prod */
for (i = first_elem; i != last_elem; i = NEXT_SGE_MASK_ELEM(i)) {
if (likely(fp->sge_mask[i]))
break;
fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
delta += BIT_VEC64_ELEM_SZ;
}
if (delta > 0) {
fp->rx_sge_prod += delta;
/* clear page-end entries */
bnx2x_clear_sge_mask_next_elems(fp);
}
DP(NETIF_MSG_RX_STATUS,
"fp->last_max_sge = %d fp->rx_sge_prod = %d\n",
fp->last_max_sge, fp->rx_sge_prod);
}
/* Get Toeplitz hash value in the skb using the value from the
* CQE (calculated by HW).
*/
static u32 bnx2x_get_rxhash(const struct bnx2x *bp,
const struct eth_fast_path_rx_cqe *cqe,
enum pkt_hash_types *rxhash_type)
{
/* Get Toeplitz hash from CQE */
if ((bp->dev->features & NETIF_F_RXHASH) &&
(cqe->status_flags & ETH_FAST_PATH_RX_CQE_RSS_HASH_FLG)) {
enum eth_rss_hash_type htype;
htype = cqe->status_flags & ETH_FAST_PATH_RX_CQE_RSS_HASH_TYPE;
*rxhash_type = ((htype == TCP_IPV4_HASH_TYPE) ||
(htype == TCP_IPV6_HASH_TYPE)) ?
PKT_HASH_TYPE_L4 : PKT_HASH_TYPE_L3;
return le32_to_cpu(cqe->rss_hash_result);
}
*rxhash_type = PKT_HASH_TYPE_NONE;
return 0;
}
static void bnx2x_tpa_start(struct bnx2x_fastpath *fp, u16 queue,
u16 cons, u16 prod,
struct eth_fast_path_rx_cqe *cqe)
{
struct bnx2x *bp = fp->bp;
struct sw_rx_bd *cons_rx_buf = &fp->rx_buf_ring[cons];
struct sw_rx_bd *prod_rx_buf = &fp->rx_buf_ring[prod];
struct eth_rx_bd *prod_bd = &fp->rx_desc_ring[prod];
dma_addr_t mapping;
struct bnx2x_agg_info *tpa_info = &fp->tpa_info[queue];
struct sw_rx_bd *first_buf = &tpa_info->first_buf;
/* print error if current state != stop */
if (tpa_info->tpa_state != BNX2X_TPA_STOP)
BNX2X_ERR("start of bin not in stop [%d]\n", queue);
/* Try to map an empty data buffer from the aggregation info */
mapping = dma_map_single(&bp->pdev->dev,
first_buf->data + NET_SKB_PAD,
fp->rx_buf_size, DMA_FROM_DEVICE);
/*
* ...if it fails - move the skb from the consumer to the producer
* and set the current aggregation state as ERROR to drop it
* when TPA_STOP arrives.
*/
if (unlikely(dma_mapping_error(&bp->pdev->dev, mapping))) {
/* Move the BD from the consumer to the producer */
bnx2x_reuse_rx_data(fp, cons, prod);
tpa_info->tpa_state = BNX2X_TPA_ERROR;
return;
}
/* move empty data from pool to prod */
prod_rx_buf->data = first_buf->data;
dma_unmap_addr_set(prod_rx_buf, mapping, mapping);
/* point prod_bd to new data */
prod_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
prod_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
/* move partial skb from cons to pool (don't unmap yet) */
*first_buf = *cons_rx_buf;
/* mark bin state as START */
tpa_info->parsing_flags =
le16_to_cpu(cqe->pars_flags.flags);
tpa_info->vlan_tag = le16_to_cpu(cqe->vlan_tag);
tpa_info->tpa_state = BNX2X_TPA_START;
tpa_info->len_on_bd = le16_to_cpu(cqe->len_on_bd);
tpa_info->placement_offset = cqe->placement_offset;
tpa_info->rxhash = bnx2x_get_rxhash(bp, cqe, &tpa_info->rxhash_type);
if (fp->mode == TPA_MODE_GRO) {
u16 gro_size = le16_to_cpu(cqe->pkt_len_or_gro_seg_len);
tpa_info->full_page = SGE_PAGES / gro_size * gro_size;
tpa_info->gro_size = gro_size;
}
#ifdef BNX2X_STOP_ON_ERROR
fp->tpa_queue_used |= (1 << queue);
DP(NETIF_MSG_RX_STATUS, "fp->tpa_queue_used = 0x%llx\n",
fp->tpa_queue_used);
#endif
}
/* Timestamp option length allowed for TPA aggregation:
*
* nop nop kind length echo val
*/
#define TPA_TSTAMP_OPT_LEN 12
/**
* bnx2x_set_gro_params - compute GRO values
*
* @skb: packet skb
* @parsing_flags: parsing flags from the START CQE
* @len_on_bd: total length of the first packet for the
* aggregation.
* @pkt_len: length of all segments
*
* Approximate value of the MSS for this aggregation calculated using
* the first packet of it.
* Compute number of aggregated segments, and gso_type.
*/
static void bnx2x_set_gro_params(struct sk_buff *skb, u16 parsing_flags,
u16 len_on_bd, unsigned int pkt_len,
u16 num_of_coalesced_segs)
{
/* TPA aggregation won't have either IP options or TCP options
* other than timestamp or IPv6 extension headers.
*/
u16 hdrs_len = ETH_HLEN + sizeof(struct tcphdr);
if (GET_FLAG(parsing_flags, PARSING_FLAGS_OVER_ETHERNET_PROTOCOL) ==
PRS_FLAG_OVERETH_IPV6) {
hdrs_len += sizeof(struct ipv6hdr);
skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
} else {
hdrs_len += sizeof(struct iphdr);
skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
}
/* Check if there was a TCP timestamp, if there is it's will
* always be 12 bytes length: nop nop kind length echo val.
*
* Otherwise FW would close the aggregation.
*/
if (parsing_flags & PARSING_FLAGS_TIME_STAMP_EXIST_FLAG)
hdrs_len += TPA_TSTAMP_OPT_LEN;
skb_shinfo(skb)->gso_size = len_on_bd - hdrs_len;
/* tcp_gro_complete() will copy NAPI_GRO_CB(skb)->count
* to skb_shinfo(skb)->gso_segs
*/
NAPI_GRO_CB(skb)->count = num_of_coalesced_segs;
}
static int bnx2x_alloc_rx_sge(struct bnx2x *bp, struct bnx2x_fastpath *fp,
u16 index, gfp_t gfp_mask)
{
struct sw_rx_page *sw_buf = &fp->rx_page_ring[index];
struct eth_rx_sge *sge = &fp->rx_sge_ring[index];
struct bnx2x_alloc_pool *pool = &fp->page_pool;
dma_addr_t mapping;
if (!pool->page) {
pool->page = alloc_pages(gfp_mask, PAGES_PER_SGE_SHIFT);
if (unlikely(!pool->page))
return -ENOMEM;
pool->offset = 0;
}
mapping = dma_map_page(&bp->pdev->dev, pool->page,
pool->offset, SGE_PAGE_SIZE, DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(&bp->pdev->dev, mapping))) {
BNX2X_ERR("Can't map sge\n");
return -ENOMEM;
}
sw_buf->page = pool->page;
sw_buf->offset = pool->offset;
dma_unmap_addr_set(sw_buf, mapping, mapping);
sge->addr_hi = cpu_to_le32(U64_HI(mapping));
sge->addr_lo = cpu_to_le32(U64_LO(mapping));
pool->offset += SGE_PAGE_SIZE;
if (PAGE_SIZE - pool->offset >= SGE_PAGE_SIZE)
get_page(pool->page);
else
pool->page = NULL;
return 0;
}
static int bnx2x_fill_frag_skb(struct bnx2x *bp, struct bnx2x_fastpath *fp,
struct bnx2x_agg_info *tpa_info,
u16 pages,
struct sk_buff *skb,
struct eth_end_agg_rx_cqe *cqe,
u16 cqe_idx)
{
struct sw_rx_page *rx_pg, old_rx_pg;
u32 i, frag_len, frag_size;
int err, j, frag_id = 0;
u16 len_on_bd = tpa_info->len_on_bd;
u16 full_page = 0, gro_size = 0;
frag_size = le16_to_cpu(cqe->pkt_len) - len_on_bd;
if (fp->mode == TPA_MODE_GRO) {
gro_size = tpa_info->gro_size;
full_page = tpa_info->full_page;
}
/* This is needed in order to enable forwarding support */
if (frag_size)
bnx2x_set_gro_params(skb, tpa_info->parsing_flags, len_on_bd,
le16_to_cpu(cqe->pkt_len),
le16_to_cpu(cqe->num_of_coalesced_segs));
#ifdef BNX2X_STOP_ON_ERROR
if (pages > min_t(u32, 8, MAX_SKB_FRAGS) * SGE_PAGES) {
BNX2X_ERR("SGL length is too long: %d. CQE index is %d\n",
pages, cqe_idx);
BNX2X_ERR("cqe->pkt_len = %d\n", cqe->pkt_len);
bnx2x_panic();
return -EINVAL;
}
#endif
/* Run through the SGL and compose the fragmented skb */
for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
u16 sge_idx = RX_SGE(le16_to_cpu(cqe->sgl_or_raw_data.sgl[j]));
/* FW gives the indices of the SGE as if the ring is an array
(meaning that "next" element will consume 2 indices) */
if (fp->mode == TPA_MODE_GRO)
frag_len = min_t(u32, frag_size, (u32)full_page);
else /* LRO */
frag_len = min_t(u32, frag_size, (u32)SGE_PAGES);
rx_pg = &fp->rx_page_ring[sge_idx];
old_rx_pg = *rx_pg;
/* If we fail to allocate a substitute page, we simply stop
where we are and drop the whole packet */
err = bnx2x_alloc_rx_sge(bp, fp, sge_idx, GFP_ATOMIC);
if (unlikely(err)) {
bnx2x_fp_qstats(bp, fp)->rx_skb_alloc_failed++;
return err;
}
dma_unmap_page(&bp->pdev->dev,
dma_unmap_addr(&old_rx_pg, mapping),
SGE_PAGE_SIZE, DMA_FROM_DEVICE);
/* Add one frag and update the appropriate fields in the skb */
if (fp->mode == TPA_MODE_LRO)
skb_fill_page_desc(skb, j, old_rx_pg.page,
old_rx_pg.offset, frag_len);
else { /* GRO */
int rem;
int offset = 0;
for (rem = frag_len; rem > 0; rem -= gro_size) {
int len = rem > gro_size ? gro_size : rem;
skb_fill_page_desc(skb, frag_id++,
old_rx_pg.page,
old_rx_pg.offset + offset,
len);
if (offset)
get_page(old_rx_pg.page);
offset += len;
}
}
skb->data_len += frag_len;
skb->truesize += SGE_PAGES;
skb->len += frag_len;
frag_size -= frag_len;
}
return 0;
}
static void bnx2x_frag_free(const struct bnx2x_fastpath *fp, void *data)
{
if (fp->rx_frag_size)
skb_free_frag(data);
else
kfree(data);
}
static void *bnx2x_frag_alloc(const struct bnx2x_fastpath *fp, gfp_t gfp_mask)
{
if (fp->rx_frag_size) {
/* GFP_KERNEL allocations are used only during initialization */
if (unlikely(gfpflags_allow_blocking(gfp_mask)))
return (void *)__get_free_page(gfp_mask);
return netdev_alloc_frag(fp->rx_frag_size);
}
return kmalloc(fp->rx_buf_size + NET_SKB_PAD, gfp_mask);
}
#ifdef CONFIG_INET
static void bnx2x_gro_ip_csum(struct bnx2x *bp, struct sk_buff *skb)
{
const struct iphdr *iph = ip_hdr(skb);
struct tcphdr *th;
skb_set_transport_header(skb, sizeof(struct iphdr));
th = tcp_hdr(skb);
th->check = ~tcp_v4_check(skb->len - skb_transport_offset(skb),
iph->saddr, iph->daddr, 0);
}
static void bnx2x_gro_ipv6_csum(struct bnx2x *bp, struct sk_buff *skb)
{
struct ipv6hdr *iph = ipv6_hdr(skb);
struct tcphdr *th;
skb_set_transport_header(skb, sizeof(struct ipv6hdr));
th = tcp_hdr(skb);
th->check = ~tcp_v6_check(skb->len - skb_transport_offset(skb),
&iph->saddr, &iph->daddr, 0);
}
static void bnx2x_gro_csum(struct bnx2x *bp, struct sk_buff *skb,
void (*gro_func)(struct bnx2x*, struct sk_buff*))
{
skb_reset_network_header(skb);
gro_func(bp, skb);
tcp_gro_complete(skb);
}
#endif
static void bnx2x_gro_receive(struct bnx2x *bp, struct bnx2x_fastpath *fp,
struct sk_buff *skb)
{
#ifdef CONFIG_INET
if (skb_shinfo(skb)->gso_size) {
switch (be16_to_cpu(skb->protocol)) {
case ETH_P_IP:
bnx2x_gro_csum(bp, skb, bnx2x_gro_ip_csum);
break;
case ETH_P_IPV6:
bnx2x_gro_csum(bp, skb, bnx2x_gro_ipv6_csum);
break;
default:
WARN_ONCE(1, "Error: FW GRO supports only IPv4/IPv6, not 0x%04x\n",
be16_to_cpu(skb->protocol));
}
}
#endif
skb_record_rx_queue(skb, fp->rx_queue);
napi_gro_receive(&fp->napi, skb);
}
static void bnx2x_tpa_stop(struct bnx2x *bp, struct bnx2x_fastpath *fp,
struct bnx2x_agg_info *tpa_info,
u16 pages,
struct eth_end_agg_rx_cqe *cqe,
u16 cqe_idx)
{
struct sw_rx_bd *rx_buf = &tpa_info->first_buf;
u8 pad = tpa_info->placement_offset;
u16 len = tpa_info->len_on_bd;
struct sk_buff *skb = NULL;
u8 *new_data, *data = rx_buf->data;
u8 old_tpa_state = tpa_info->tpa_state;
tpa_info->tpa_state = BNX2X_TPA_STOP;
/* If we there was an error during the handling of the TPA_START -
* drop this aggregation.
*/
if (old_tpa_state == BNX2X_TPA_ERROR)
goto drop;
/* Try to allocate the new data */
new_data = bnx2x_frag_alloc(fp, GFP_ATOMIC);
/* Unmap skb in the pool anyway, as we are going to change
pool entry status to BNX2X_TPA_STOP even if new skb allocation
fails. */
dma_unmap_single(&bp->pdev->dev, dma_unmap_addr(rx_buf, mapping),
fp->rx_buf_size, DMA_FROM_DEVICE);
if (likely(new_data))
skb = build_skb(data, fp->rx_frag_size);
if (likely(skb)) {
#ifdef BNX2X_STOP_ON_ERROR
if (pad + len > fp->rx_buf_size) {
BNX2X_ERR("skb_put is about to fail... pad %d len %d rx_buf_size %d\n",
pad, len, fp->rx_buf_size);
bnx2x_panic();
return;
}
#endif
skb_reserve(skb, pad + NET_SKB_PAD);
skb_put(skb, len);
skb_set_hash(skb, tpa_info->rxhash, tpa_info->rxhash_type);
skb->protocol = eth_type_trans(skb, bp->dev);
skb->ip_summed = CHECKSUM_UNNECESSARY;
if (!bnx2x_fill_frag_skb(bp, fp, tpa_info, pages,
skb, cqe, cqe_idx)) {
if (tpa_info->parsing_flags & PARSING_FLAGS_VLAN)
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), tpa_info->vlan_tag);
bnx2x_gro_receive(bp, fp, skb);
} else {
DP(NETIF_MSG_RX_STATUS,
"Failed to allocate new pages - dropping packet!\n");
dev_kfree_skb_any(skb);
}
/* put new data in bin */
rx_buf->data = new_data;
return;
}
if (new_data)
bnx2x_frag_free(fp, new_data);
drop:
/* drop the packet and keep the buffer in the bin */
DP(NETIF_MSG_RX_STATUS,
"Failed to allocate or map a new skb - dropping packet!\n");
bnx2x_fp_stats(bp, fp)->eth_q_stats.rx_skb_alloc_failed++;
}
static int bnx2x_alloc_rx_data(struct bnx2x *bp, struct bnx2x_fastpath *fp,
u16 index, gfp_t gfp_mask)
{
u8 *data;
struct sw_rx_bd *rx_buf = &fp->rx_buf_ring[index];
struct eth_rx_bd *rx_bd = &fp->rx_desc_ring[index];
dma_addr_t mapping;
data = bnx2x_frag_alloc(fp, gfp_mask);
if (unlikely(data == NULL))
return -ENOMEM;
mapping = dma_map_single(&bp->pdev->dev, data + NET_SKB_PAD,
fp->rx_buf_size,
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(&bp->pdev->dev, mapping))) {
bnx2x_frag_free(fp, data);
BNX2X_ERR("Can't map rx data\n");
return -ENOMEM;
}
rx_buf->data = data;
dma_unmap_addr_set(rx_buf, mapping, mapping);
rx_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
rx_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
return 0;
}
static
void bnx2x_csum_validate(struct sk_buff *skb, union eth_rx_cqe *cqe,
struct bnx2x_fastpath *fp,
struct bnx2x_eth_q_stats *qstats)
{
/* Do nothing if no L4 csum validation was done.
* We do not check whether IP csum was validated. For IPv4 we assume
* that if the card got as far as validating the L4 csum, it also
* validated the IP csum. IPv6 has no IP csum.
*/
if (cqe->fast_path_cqe.status_flags &
ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)
return;
/* If L4 validation was done, check if an error was found. */
if (cqe->fast_path_cqe.type_error_flags &
(ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG |
ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG))
qstats->hw_csum_err++;
else
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
static int bnx2x_rx_int(struct bnx2x_fastpath *fp, int budget)
{
struct bnx2x *bp = fp->bp;
u16 bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
u16 sw_comp_cons, sw_comp_prod;
int rx_pkt = 0;
union eth_rx_cqe *cqe;
struct eth_fast_path_rx_cqe *cqe_fp;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return 0;
#endif
if (budget <= 0)
return rx_pkt;
bd_cons = fp->rx_bd_cons;
bd_prod = fp->rx_bd_prod;
bd_prod_fw = bd_prod;
sw_comp_cons = fp->rx_comp_cons;
sw_comp_prod = fp->rx_comp_prod;
comp_ring_cons = RCQ_BD(sw_comp_cons);
cqe = &fp->rx_comp_ring[comp_ring_cons];
cqe_fp = &cqe->fast_path_cqe;
DP(NETIF_MSG_RX_STATUS,
"queue[%d]: sw_comp_cons %u\n", fp->index, sw_comp_cons);
while (BNX2X_IS_CQE_COMPLETED(cqe_fp)) {
struct sw_rx_bd *rx_buf = NULL;
struct sk_buff *skb;
u8 cqe_fp_flags;
enum eth_rx_cqe_type cqe_fp_type;
u16 len, pad, queue;
u8 *data;
u32 rxhash;
enum pkt_hash_types rxhash_type;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return 0;
#endif
bd_prod = RX_BD(bd_prod);
bd_cons = RX_BD(bd_cons);
/* A rmb() is required to ensure that the CQE is not read
* before it is written by the adapter DMA. PCI ordering
* rules will make sure the other fields are written before
* the marker at the end of struct eth_fast_path_rx_cqe
* but without rmb() a weakly ordered processor can process
* stale data. Without the barrier TPA state-machine might
* enter inconsistent state and kernel stack might be
* provided with incorrect packet description - these lead
* to various kernel crashed.
*/
rmb();
cqe_fp_flags = cqe_fp->type_error_flags;
cqe_fp_type = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
DP(NETIF_MSG_RX_STATUS,
"CQE type %x err %x status %x queue %x vlan %x len %u\n",
CQE_TYPE(cqe_fp_flags),
cqe_fp_flags, cqe_fp->status_flags,
le32_to_cpu(cqe_fp->rss_hash_result),
le16_to_cpu(cqe_fp->vlan_tag),
le16_to_cpu(cqe_fp->pkt_len_or_gro_seg_len));
/* is this a slowpath msg? */
if (unlikely(CQE_TYPE_SLOW(cqe_fp_type))) {
bnx2x_sp_event(fp, cqe);
goto next_cqe;
}
rx_buf = &fp->rx_buf_ring[bd_cons];
data = rx_buf->data;
if (!CQE_TYPE_FAST(cqe_fp_type)) {
struct bnx2x_agg_info *tpa_info;
u16 frag_size, pages;
#ifdef BNX2X_STOP_ON_ERROR
/* sanity check */
if (fp->mode == TPA_MODE_DISABLED &&
(CQE_TYPE_START(cqe_fp_type) ||
CQE_TYPE_STOP(cqe_fp_type)))
BNX2X_ERR("START/STOP packet while TPA disabled, type %x\n",
CQE_TYPE(cqe_fp_type));
#endif
if (CQE_TYPE_START(cqe_fp_type)) {
u16 queue = cqe_fp->queue_index;
DP(NETIF_MSG_RX_STATUS,
"calling tpa_start on queue %d\n",
queue);
bnx2x_tpa_start(fp, queue,
bd_cons, bd_prod,
cqe_fp);
goto next_rx;
}
queue = cqe->end_agg_cqe.queue_index;
tpa_info = &fp->tpa_info[queue];
DP(NETIF_MSG_RX_STATUS,
"calling tpa_stop on queue %d\n",
queue);
frag_size = le16_to_cpu(cqe->end_agg_cqe.pkt_len) -
tpa_info->len_on_bd;
if (fp->mode == TPA_MODE_GRO)
pages = (frag_size + tpa_info->full_page - 1) /
tpa_info->full_page;
else
pages = SGE_PAGE_ALIGN(frag_size) >>
SGE_PAGE_SHIFT;
bnx2x_tpa_stop(bp, fp, tpa_info, pages,
&cqe->end_agg_cqe, comp_ring_cons);
#ifdef BNX2X_STOP_ON_ERROR
if (bp->panic)
return 0;
#endif
bnx2x_update_sge_prod(fp, pages, &cqe->end_agg_cqe);
goto next_cqe;
}
/* non TPA */
len = le16_to_cpu(cqe_fp->pkt_len_or_gro_seg_len);
pad = cqe_fp->placement_offset;
dma_sync_single_for_cpu(&bp->pdev->dev,
dma_unmap_addr(rx_buf, mapping),
pad + RX_COPY_THRESH,
DMA_FROM_DEVICE);
pad += NET_SKB_PAD;
prefetch(data + pad); /* speedup eth_type_trans() */
/* is this an error packet? */
if (unlikely(cqe_fp_flags & ETH_RX_ERROR_FALGS)) {
DP(NETIF_MSG_RX_ERR | NETIF_MSG_RX_STATUS,
"ERROR flags %x rx packet %u\n",
cqe_fp_flags, sw_comp_cons);
bnx2x_fp_qstats(bp, fp)->rx_err_discard_pkt++;
goto reuse_rx;
}
/* Since we don't have a jumbo ring
* copy small packets if mtu > 1500
*/
if ((bp->dev->mtu > ETH_MAX_PACKET_SIZE) &&
(len <= RX_COPY_THRESH)) {
skb = napi_alloc_skb(&fp->napi, len);
if (skb == NULL) {
DP(NETIF_MSG_RX_ERR | NETIF_MSG_RX_STATUS,
"ERROR packet dropped because of alloc failure\n");
bnx2x_fp_qstats(bp, fp)->rx_skb_alloc_failed++;
goto reuse_rx;
}
memcpy(skb->data, data + pad, len);
bnx2x_reuse_rx_data(fp, bd_cons, bd_prod);
} else {
if (likely(bnx2x_alloc_rx_data(bp, fp, bd_prod,
GFP_ATOMIC) == 0)) {
dma_unmap_single(&bp->pdev->dev,
dma_unmap_addr(rx_buf, mapping),
fp->rx_buf_size,
DMA_FROM_DEVICE);
skb = build_skb(data, fp->rx_frag_size);
if (unlikely(!skb)) {
bnx2x_frag_free(fp, data);
bnx2x_fp_qstats(bp, fp)->
rx_skb_alloc_failed++;
goto next_rx;
}
skb_reserve(skb, pad);
} else {
DP(NETIF_MSG_RX_ERR | NETIF_MSG_RX_STATUS,
"ERROR packet dropped because of alloc failure\n");
bnx2x_fp_qstats(bp, fp)->rx_skb_alloc_failed++;
reuse_rx:
bnx2x_reuse_rx_data(fp, bd_cons, bd_prod);
goto next_rx;
}
}
skb_put(skb, len);
skb->protocol = eth_type_trans(skb, bp->dev);
/* Set Toeplitz hash for a none-LRO skb */
rxhash = bnx2x_get_rxhash(bp, cqe_fp, &rxhash_type);
skb_set_hash(skb, rxhash, rxhash_type);
skb_checksum_none_assert(skb);
if (bp->dev->features & NETIF_F_RXCSUM)
bnx2x_csum_validate(skb, cqe, fp,
bnx2x_fp_qstats(bp, fp));
skb_record_rx_queue(skb, fp->rx_queue);
/* Check if this packet was timestamped */
if (unlikely(cqe->fast_path_cqe.type_error_flags &
(1 << ETH_FAST_PATH_RX_CQE_PTP_PKT_SHIFT)))
bnx2x_set_rx_ts(bp, skb);
if (le16_to_cpu(cqe_fp->pars_flags.flags) &
PARSING_FLAGS_VLAN)
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q),
le16_to_cpu(cqe_fp->vlan_tag));
napi_gro_receive(&fp->napi, skb);
next_rx:
rx_buf->data = NULL;
bd_cons = NEXT_RX_IDX(bd_cons);
bd_prod = NEXT_RX_IDX(bd_prod);
bd_prod_fw = NEXT_RX_IDX(bd_prod_fw);
rx_pkt++;
next_cqe:
sw_comp_prod = NEXT_RCQ_IDX(sw_comp_prod);
sw_comp_cons = NEXT_RCQ_IDX(sw_comp_cons);
/* mark CQE as free */
BNX2X_SEED_CQE(cqe_fp);
if (rx_pkt == budget)
break;
comp_ring_cons = RCQ_BD(sw_comp_cons);
cqe = &fp->rx_comp_ring[comp_ring_cons];
cqe_fp = &cqe->fast_path_cqe;
} /* while */
fp->rx_bd_cons = bd_cons;
fp->rx_bd_prod = bd_prod_fw;
fp->rx_comp_cons = sw_comp_cons;
fp->rx_comp_prod = sw_comp_prod;
/* Update producers */
bnx2x_update_rx_prod(bp, fp, bd_prod_fw, sw_comp_prod,
fp->rx_sge_prod);
return rx_pkt;
}
static irqreturn_t bnx2x_msix_fp_int(int irq, void *fp_cookie)
{
struct bnx2x_fastpath *fp = fp_cookie;
struct bnx2x *bp = fp->bp;
u8 cos;
DP(NETIF_MSG_INTR,
"got an MSI-X interrupt on IDX:SB [fp %d fw_sd %d igusb %d]\n",
fp->index, fp->fw_sb_id, fp->igu_sb_id);
bnx2x_ack_sb(bp, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return IRQ_HANDLED;
#endif
/* Handle Rx and Tx according to MSI-X vector */
for_each_cos_in_tx_queue(fp, cos)
prefetch(fp->txdata_ptr[cos]->tx_cons_sb);
prefetch(&fp->sb_running_index[SM_RX_ID]);
napi_schedule_irqoff(&bnx2x_fp(bp, fp->index, napi));
return IRQ_HANDLED;
}
/* HW Lock for shared dual port PHYs */
void bnx2x_acquire_phy_lock(struct bnx2x *bp)
{
mutex_lock(&bp->port.phy_mutex);
bnx2x_acquire_hw_lock(bp, HW_LOCK_RESOURCE_MDIO);
}
void bnx2x_release_phy_lock(struct bnx2x *bp)
{
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_MDIO);
mutex_unlock(&bp->port.phy_mutex);
}
/* calculates MF speed according to current linespeed and MF configuration */
u16 bnx2x_get_mf_speed(struct bnx2x *bp)
{
u16 line_speed = bp->link_vars.line_speed;
if (IS_MF(bp)) {
u16 maxCfg = bnx2x_extract_max_cfg(bp,
bp->mf_config[BP_VN(bp)]);
/* Calculate the current MAX line speed limit for the MF
* devices
*/
if (IS_MF_PERCENT_BW(bp))
line_speed = (line_speed * maxCfg) / 100;
else { /* SD mode */
u16 vn_max_rate = maxCfg * 100;
if (vn_max_rate < line_speed)
line_speed = vn_max_rate;
}
}
return line_speed;
}
/**
* bnx2x_fill_report_data - fill link report data to report
*
* @bp: driver handle
* @data: link state to update
*
* It uses a none-atomic bit operations because is called under the mutex.
*/
static void bnx2x_fill_report_data(struct bnx2x *bp,
struct bnx2x_link_report_data *data)
{
memset(data, 0, sizeof(*data));
if (IS_PF(bp)) {
/* Fill the report data: effective line speed */
data->line_speed = bnx2x_get_mf_speed(bp);
/* Link is down */
if (!bp->link_vars.link_up || (bp->flags & MF_FUNC_DIS))
__set_bit(BNX2X_LINK_REPORT_LINK_DOWN,
&data->link_report_flags);
if (!BNX2X_NUM_ETH_QUEUES(bp))
__set_bit(BNX2X_LINK_REPORT_LINK_DOWN,
&data->link_report_flags);
/* Full DUPLEX */
if (bp->link_vars.duplex == DUPLEX_FULL)
__set_bit(BNX2X_LINK_REPORT_FD,
&data->link_report_flags);
/* Rx Flow Control is ON */
if (bp->link_vars.flow_ctrl & BNX2X_FLOW_CTRL_RX)
__set_bit(BNX2X_LINK_REPORT_RX_FC_ON,
&data->link_report_flags);
/* Tx Flow Control is ON */
if (bp->link_vars.flow_ctrl & BNX2X_FLOW_CTRL_TX)
__set_bit(BNX2X_LINK_REPORT_TX_FC_ON,
&data->link_report_flags);
} else { /* VF */
*data = bp->vf_link_vars;
}
}
/**
* bnx2x_link_report - report link status to OS.
*
* @bp: driver handle
*
* Calls the __bnx2x_link_report() under the same locking scheme
* as a link/PHY state managing code to ensure a consistent link
* reporting.
*/
void bnx2x_link_report(struct bnx2x *bp)
{
bnx2x_acquire_phy_lock(bp);
__bnx2x_link_report(bp);
bnx2x_release_phy_lock(bp);
}
/**
* __bnx2x_link_report - report link status to OS.
*
* @bp: driver handle
*
* None atomic implementation.
* Should be called under the phy_lock.
*/
void __bnx2x_link_report(struct bnx2x *bp)
{
struct bnx2x_link_report_data cur_data;
/* reread mf_cfg */
if (IS_PF(bp) && !CHIP_IS_E1(bp))
bnx2x_read_mf_cfg(bp);
/* Read the current link report info */
bnx2x_fill_report_data(bp, &cur_data);
/* Don't report link down or exactly the same link status twice */
if (!memcmp(&cur_data, &bp->last_reported_link, sizeof(cur_data)) ||
(test_bit(BNX2X_LINK_REPORT_LINK_DOWN,
&bp->last_reported_link.link_report_flags) &&
test_bit(BNX2X_LINK_REPORT_LINK_DOWN,
&cur_data.link_report_flags)))
return;
bp->link_cnt++;
/* We are going to report a new link parameters now -
* remember the current data for the next time.
*/
memcpy(&bp->last_reported_link, &cur_data, sizeof(cur_data));
/* propagate status to VFs */
if (IS_PF(bp))
bnx2x_iov_link_update(bp);
if (test_bit(BNX2X_LINK_REPORT_LINK_DOWN,
&cur_data.link_report_flags)) {
netif_carrier_off(bp->dev);
netdev_err(bp->dev, "NIC Link is Down\n");
return;
} else {
const char *duplex;
const char *flow;
netif_carrier_on(bp->dev);
if (test_and_clear_bit(BNX2X_LINK_REPORT_FD,
&cur_data.link_report_flags))
duplex = "full";
else
duplex = "half";
/* Handle the FC at the end so that only these flags would be
* possibly set. This way we may easily check if there is no FC
* enabled.
*/
if (cur_data.link_report_flags) {
if (test_bit(BNX2X_LINK_REPORT_RX_FC_ON,
&cur_data.link_report_flags)) {
if (test_bit(BNX2X_LINK_REPORT_TX_FC_ON,
&cur_data.link_report_flags))
flow = "ON - receive & transmit";
else
flow = "ON - receive";
} else {
flow = "ON - transmit";
}
} else {
flow = "none";
}
netdev_info(bp->dev, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
cur_data.line_speed, duplex, flow);
}
}
static void bnx2x_set_next_page_sgl(struct bnx2x_fastpath *fp)
{
int i;
for (i = 1; i <= NUM_RX_SGE_PAGES; i++) {
struct eth_rx_sge *sge;
sge = &fp->rx_sge_ring[RX_SGE_CNT * i - 2];
sge->addr_hi =
cpu_to_le32(U64_HI(fp->rx_sge_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_SGE_PAGES)));
sge->addr_lo =
cpu_to_le32(U64_LO(fp->rx_sge_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_SGE_PAGES)));
}
}
static void bnx2x_free_tpa_pool(struct bnx2x *bp,
struct bnx2x_fastpath *fp, int last)
{
int i;
for (i = 0; i < last; i++) {
struct bnx2x_agg_info *tpa_info = &fp->tpa_info[i];
struct sw_rx_bd *first_buf = &tpa_info->first_buf;
u8 *data = first_buf->data;
if (data == NULL) {
DP(NETIF_MSG_IFDOWN, "tpa bin %d empty on free\n", i);
continue;
}
if (tpa_info->tpa_state == BNX2X_TPA_START)
dma_unmap_single(&bp->pdev->dev,
dma_unmap_addr(first_buf, mapping),
fp->rx_buf_size, DMA_FROM_DEVICE);
bnx2x_frag_free(fp, data);
first_buf->data = NULL;
}
}
void bnx2x_init_rx_rings_cnic(struct bnx2x *bp)
{
int j;
for_each_rx_queue_cnic(bp, j) {
struct bnx2x_fastpath *fp = &bp->fp[j];
fp->rx_bd_cons = 0;
/* Activate BD ring */
/* Warning!
* this will generate an interrupt (to the TSTORM)
* must only be done after chip is initialized
*/
bnx2x_update_rx_prod(bp, fp, fp->rx_bd_prod, fp->rx_comp_prod,
fp->rx_sge_prod);
}
}
void bnx2x_init_rx_rings(struct bnx2x *bp)
{
int func = BP_FUNC(bp);
u16 ring_prod;
int i, j;
/* Allocate TPA resources */
for_each_eth_queue(bp, j) {
struct bnx2x_fastpath *fp = &bp->fp[j];
DP(NETIF_MSG_IFUP,
"mtu %d rx_buf_size %d\n", bp->dev->mtu, fp->rx_buf_size);
if (fp->mode != TPA_MODE_DISABLED) {
/* Fill the per-aggregation pool */
for (i = 0; i < MAX_AGG_QS(bp); i++) {
struct bnx2x_agg_info *tpa_info =
&fp->tpa_info[i];
struct sw_rx_bd *first_buf =
&tpa_info->first_buf;
first_buf->data =
bnx2x_frag_alloc(fp, GFP_KERNEL);
if (!first_buf->data) {
BNX2X_ERR("Failed to allocate TPA skb pool for queue[%d] - disabling TPA on this queue!\n",
j);
bnx2x_free_tpa_pool(bp, fp, i);
fp->mode = TPA_MODE_DISABLED;
break;
}
dma_unmap_addr_set(first_buf, mapping, 0);
tpa_info->tpa_state = BNX2X_TPA_STOP;
}
/* "next page" elements initialization */
bnx2x_set_next_page_sgl(fp);
/* set SGEs bit mask */
bnx2x_init_sge_ring_bit_mask(fp);
/* Allocate SGEs and initialize the ring elements */
for (i = 0, ring_prod = 0;
i < MAX_RX_SGE_CNT*NUM_RX_SGE_PAGES; i++) {
if (bnx2x_alloc_rx_sge(bp, fp, ring_prod,
GFP_KERNEL) < 0) {
BNX2X_ERR("was only able to allocate %d rx sges\n",
i);
BNX2X_ERR("disabling TPA for queue[%d]\n",
j);
/* Cleanup already allocated elements */
bnx2x_free_rx_sge_range(bp, fp,
ring_prod);
bnx2x_free_tpa_pool(bp, fp,
MAX_AGG_QS(bp));
fp->mode = TPA_MODE_DISABLED;
ring_prod = 0;
break;
}
ring_prod = NEXT_SGE_IDX(ring_prod);
}
fp->rx_sge_prod = ring_prod;
}
}
for_each_eth_queue(bp, j) {
struct bnx2x_fastpath *fp = &bp->fp[j];
fp->rx_bd_cons = 0;
/* Activate BD ring */
/* Warning!
* this will generate an interrupt (to the TSTORM)
* must only be done after chip is initialized
*/
bnx2x_update_rx_prod(bp, fp, fp->rx_bd_prod, fp->rx_comp_prod,
fp->rx_sge_prod);
if (j != 0)
continue;
if (CHIP_IS_E1(bp)) {
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(func),
U64_LO(fp->rx_comp_mapping));
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(func) + 4,
U64_HI(fp->rx_comp_mapping));
}
}
}
static void bnx2x_free_tx_skbs_queue(struct bnx2x_fastpath *fp)
{
u8 cos;
struct bnx2x *bp = fp->bp;
for_each_cos_in_tx_queue(fp, cos) {
struct bnx2x_fp_txdata *txdata = fp->txdata_ptr[cos];
unsigned pkts_compl = 0, bytes_compl = 0;
u16 sw_prod = txdata->tx_pkt_prod;
u16 sw_cons = txdata->tx_pkt_cons;
while (sw_cons != sw_prod) {
bnx2x_free_tx_pkt(bp, txdata, TX_BD(sw_cons),
&pkts_compl, &bytes_compl);
sw_cons++;
}
netdev_tx_reset_queue(
netdev_get_tx_queue(bp->dev,
txdata->txq_index));
}
}
static void bnx2x_free_tx_skbs_cnic(struct bnx2x *bp)
{
int i;
for_each_tx_queue_cnic(bp, i) {
bnx2x_free_tx_skbs_queue(&bp->fp[i]);
}
}
static void bnx2x_free_tx_skbs(struct bnx2x *bp)
{
int i;
for_each_eth_queue(bp, i) {
bnx2x_free_tx_skbs_queue(&bp->fp[i]);
}
}
static void bnx2x_free_rx_bds(struct bnx2x_fastpath *fp)
{
struct bnx2x *bp = fp->bp;
int i;
/* ring wasn't allocated */
if (fp->rx_buf_ring == NULL)
return;
for (i = 0; i < NUM_RX_BD; i++) {
struct sw_rx_bd *rx_buf = &fp->rx_buf_ring[i];
u8 *data = rx_buf->data;
if (data == NULL)
continue;
dma_unmap_single(&bp->pdev->dev,
dma_unmap_addr(rx_buf, mapping),
fp->rx_buf_size, DMA_FROM_DEVICE);
rx_buf->data = NULL;
bnx2x_frag_free(fp, data);
}
}
static void bnx2x_free_rx_skbs_cnic(struct bnx2x *bp)
{
int j;
for_each_rx_queue_cnic(bp, j) {
bnx2x_free_rx_bds(&bp->fp[j]);
}
}
static void bnx2x_free_rx_skbs(struct bnx2x *bp)
{
int j;
for_each_eth_queue(bp, j) {
struct bnx2x_fastpath *fp = &bp->fp[j];
bnx2x_free_rx_bds(fp);
if (fp->mode != TPA_MODE_DISABLED)
bnx2x_free_tpa_pool(bp, fp, MAX_AGG_QS(bp));
}
}
static void bnx2x_free_skbs_cnic(struct bnx2x *bp)
{
bnx2x_free_tx_skbs_cnic(bp);
bnx2x_free_rx_skbs_cnic(bp);
}
void bnx2x_free_skbs(struct bnx2x *bp)
{
bnx2x_free_tx_skbs(bp);
bnx2x_free_rx_skbs(bp);
}
void bnx2x_update_max_mf_config(struct bnx2x *bp, u32 value)
{
/* load old values */
u32 mf_cfg = bp->mf_config[BP_VN(bp)];
if (value != bnx2x_extract_max_cfg(bp, mf_cfg)) {
/* leave all but MAX value */
mf_cfg &= ~FUNC_MF_CFG_MAX_BW_MASK;
/* set new MAX value */
mf_cfg |= (value << FUNC_MF_CFG_MAX_BW_SHIFT)
& FUNC_MF_CFG_MAX_BW_MASK;
bnx2x_fw_command(bp, DRV_MSG_CODE_SET_MF_BW, mf_cfg);
}
}
/**
* bnx2x_free_msix_irqs - free previously requested MSI-X IRQ vectors
*
* @bp: driver handle
* @nvecs: number of vectors to be released
*/
static void bnx2x_free_msix_irqs(struct bnx2x *bp, int nvecs)
{
int i, offset = 0;
if (nvecs == offset)
return;
/* VFs don't have a default SB */
if (IS_PF(bp)) {
free_irq(bp->msix_table[offset].vector, bp->dev);
DP(NETIF_MSG_IFDOWN, "released sp irq (%d)\n",
bp->msix_table[offset].vector);
offset++;
}
if (CNIC_SUPPORT(bp)) {
if (nvecs == offset)
return;
offset++;
}
for_each_eth_queue(bp, i) {
if (nvecs == offset)
return;
DP(NETIF_MSG_IFDOWN, "about to release fp #%d->%d irq\n",
i, bp->msix_table[offset].vector);
free_irq(bp->msix_table[offset++].vector, &bp->fp[i]);
}
}
void bnx2x_free_irq(struct bnx2x *bp)
{
if (bp->flags & USING_MSIX_FLAG &&
!(bp->flags & USING_SINGLE_MSIX_FLAG)) {
int nvecs = BNX2X_NUM_ETH_QUEUES(bp) + CNIC_SUPPORT(bp);
/* vfs don't have a default status block */
if (IS_PF(bp))
nvecs++;
bnx2x_free_msix_irqs(bp, nvecs);
} else {
free_irq(bp->dev->irq, bp->dev);
}
}
int bnx2x_enable_msix(struct bnx2x *bp)
{
int msix_vec = 0, i, rc;
/* VFs don't have a default status block */
if (IS_PF(bp)) {
bp->msix_table[msix_vec].entry = msix_vec;
BNX2X_DEV_INFO("msix_table[0].entry = %d (slowpath)\n",
bp->msix_table[0].entry);
msix_vec++;
}
/* Cnic requires an msix vector for itself */
if (CNIC_SUPPORT(bp)) {
bp->msix_table[msix_vec].entry = msix_vec;
BNX2X_DEV_INFO("msix_table[%d].entry = %d (CNIC)\n",
msix_vec, bp->msix_table[msix_vec].entry);
msix_vec++;
}
/* We need separate vectors for ETH queues only (not FCoE) */
for_each_eth_queue(bp, i) {
bp->msix_table[msix_vec].entry = msix_vec;
BNX2X_DEV_INFO("msix_table[%d].entry = %d (fastpath #%u)\n",
msix_vec, msix_vec, i);
msix_vec++;
}
DP(BNX2X_MSG_SP, "about to request enable msix with %d vectors\n",
msix_vec);
rc = pci_enable_msix_range(bp->pdev, &bp->msix_table[0],
BNX2X_MIN_MSIX_VEC_CNT(bp), msix_vec);
/*
* reconfigure number of tx/rx queues according to available
* MSI-X vectors
*/
if (rc == -ENOSPC) {
/* Get by with single vector */
rc = pci_enable_msix_range(bp->pdev, &bp->msix_table[0], 1, 1);
if (rc < 0) {
BNX2X_DEV_INFO("Single MSI-X is not attainable rc %d\n",
rc);
goto no_msix;
}
BNX2X_DEV_INFO("Using single MSI-X vector\n");
bp->flags |= USING_SINGLE_MSIX_FLAG;
BNX2X_DEV_INFO("set number of queues to 1\n");
bp->num_ethernet_queues = 1;
bp->num_queues = bp->num_ethernet_queues + bp->num_cnic_queues;
} else if (rc < 0) {
BNX2X_DEV_INFO("MSI-X is not attainable rc %d\n", rc);
goto no_msix;
} else if (rc < msix_vec) {
/* how less vectors we will have? */
int diff = msix_vec - rc;
BNX2X_DEV_INFO("Trying to use less MSI-X vectors: %d\n", rc);
/*
* decrease number of queues by number of unallocated entries
*/
bp->num_ethernet_queues -= diff;
bp->num_queues = bp->num_ethernet_queues + bp->num_cnic_queues;
BNX2X_DEV_INFO("New queue configuration set: %d\n",
bp->num_queues);
}
bp->flags |= USING_MSIX_FLAG;
return 0;
no_msix:
/* fall to INTx if not enough memory */
if (rc == -ENOMEM)
bp->flags |= DISABLE_MSI_FLAG;
return rc;
}
static int bnx2x_req_msix_irqs(struct bnx2x *bp)
{
int i, rc, offset = 0;
/* no default status block for vf */
if (IS_PF(bp)) {
rc = request_irq(bp->msix_table[offset++].vector,
bnx2x_msix_sp_int, 0,
bp->dev->name, bp->dev);
if (rc) {
BNX2X_ERR("request sp irq failed\n");
return -EBUSY;
}
}
if (CNIC_SUPPORT(bp))
offset++;
for_each_eth_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
snprintf(fp->name, sizeof(fp->name), "%s-fp-%d",
bp->dev->name, i);
rc = request_irq(bp->msix_table[offset].vector,
bnx2x_msix_fp_int, 0, fp->name, fp);
if (rc) {
BNX2X_ERR("request fp #%d irq (%d) failed rc %d\n", i,
bp->msix_table[offset].vector, rc);
bnx2x_free_msix_irqs(bp, offset);
return -EBUSY;
}
offset++;
}
i = BNX2X_NUM_ETH_QUEUES(bp);
if (IS_PF(bp)) {
offset = 1 + CNIC_SUPPORT(bp);
netdev_info(bp->dev,
"using MSI-X IRQs: sp %d fp[%d] %d ... fp[%d] %d\n",
bp->msix_table[0].vector,
0, bp->msix_table[offset].vector,
i - 1, bp->msix_table[offset + i - 1].vector);
} else {
offset = CNIC_SUPPORT(bp);
netdev_info(bp->dev,
"using MSI-X IRQs: fp[%d] %d ... fp[%d] %d\n",
0, bp->msix_table[offset].vector,
i - 1, bp->msix_table[offset + i - 1].vector);
}
return 0;
}
int bnx2x_enable_msi(struct bnx2x *bp)
{
int rc;
rc = pci_enable_msi(bp->pdev);
if (rc) {
BNX2X_DEV_INFO("MSI is not attainable\n");
return -1;
}
bp->flags |= USING_MSI_FLAG;
return 0;
}
static int bnx2x_req_irq(struct bnx2x *bp)
{
unsigned long flags;
unsigned int irq;
if (bp->flags & (USING_MSI_FLAG | USING_MSIX_FLAG))
flags = 0;
else
flags = IRQF_SHARED;
if (bp->flags & USING_MSIX_FLAG)
irq = bp->msix_table[0].vector;
else
irq = bp->pdev->irq;
return request_irq(irq, bnx2x_interrupt, flags, bp->dev->name, bp->dev);
}
static int bnx2x_setup_irqs(struct bnx2x *bp)
{
int rc = 0;
if (bp->flags & USING_MSIX_FLAG &&
!(bp->flags & USING_SINGLE_MSIX_FLAG)) {
rc = bnx2x_req_msix_irqs(bp);
if (rc)
return rc;
} else {
rc = bnx2x_req_irq(bp);
if (rc) {
BNX2X_ERR("IRQ request failed rc %d, aborting\n", rc);
return rc;
}
if (bp->flags & USING_MSI_FLAG) {
bp->dev->irq = bp->pdev->irq;
netdev_info(bp->dev, "using MSI IRQ %d\n",
bp->dev->irq);
}
if (bp->flags & USING_MSIX_FLAG) {
bp->dev->irq = bp->msix_table[0].vector;
netdev_info(bp->dev, "using MSIX IRQ %d\n",
bp->dev->irq);
}
}
return 0;
}
static void bnx2x_napi_enable_cnic(struct bnx2x *bp)
{
int i;
for_each_rx_queue_cnic(bp, i) {
napi_enable(&bnx2x_fp(bp, i, napi));
}
}
static void bnx2x_napi_enable(struct bnx2x *bp)
{
int i;
for_each_eth_queue(bp, i) {
napi_enable(&bnx2x_fp(bp, i, napi));
}
}
static void bnx2x_napi_disable_cnic(struct bnx2x *bp)
{
int i;
for_each_rx_queue_cnic(bp, i) {
napi_disable(&bnx2x_fp(bp, i, napi));
}
}
static void bnx2x_napi_disable(struct bnx2x *bp)
{
int i;
for_each_eth_queue(bp, i) {
napi_disable(&bnx2x_fp(bp, i, napi));
}
}
void bnx2x_netif_start(struct bnx2x *bp)
{
if (netif_running(bp->dev)) {
bnx2x_napi_enable(bp);
if (CNIC_LOADED(bp))
bnx2x_napi_enable_cnic(bp);
bnx2x_int_enable(bp);
if (bp->state == BNX2X_STATE_OPEN)
netif_tx_wake_all_queues(bp->dev);
}
}
void bnx2x_netif_stop(struct bnx2x *bp, int disable_hw)
{
bnx2x_int_disable_sync(bp, disable_hw);
bnx2x_napi_disable(bp);
if (CNIC_LOADED(bp))
bnx2x_napi_disable_cnic(bp);
}
u16 bnx2x_select_queue(struct net_device *dev, struct sk_buff *skb,
void *accel_priv, select_queue_fallback_t fallback)
{
struct bnx2x *bp = netdev_priv(dev);
if (CNIC_LOADED(bp) && !NO_FCOE(bp)) {
struct ethhdr *hdr = (struct ethhdr *)skb->data;
u16 ether_type = ntohs(hdr->h_proto);
/* Skip VLAN tag if present */
if (ether_type == ETH_P_8021Q) {
struct vlan_ethhdr *vhdr =
(struct vlan_ethhdr *)skb->data;
ether_type = ntohs(vhdr->h_vlan_encapsulated_proto);
}
/* If ethertype is FCoE or FIP - use FCoE ring */
if ((ether_type == ETH_P_FCOE) || (ether_type == ETH_P_FIP))
return bnx2x_fcoe_tx(bp, txq_index);
}
/* select a non-FCoE queue */
return fallback(dev, skb) % (BNX2X_NUM_ETH_QUEUES(bp) * bp->max_cos);
}
void bnx2x_set_num_queues(struct bnx2x *bp)
{
/* RSS queues */
bp->num_ethernet_queues = bnx2x_calc_num_queues(bp);
/* override in STORAGE SD modes */
if (IS_MF_STORAGE_ONLY(bp))
bp->num_ethernet_queues = 1;
/* Add special queues */
bp->num_cnic_queues = CNIC_SUPPORT(bp); /* For FCOE */
bp->num_queues = bp->num_ethernet_queues + bp->num_cnic_queues;
BNX2X_DEV_INFO("set number of queues to %d\n", bp->num_queues);
}
/**
* bnx2x_set_real_num_queues - configure netdev->real_num_[tx,rx]_queues
*
* @bp: Driver handle
*
* We currently support for at most 16 Tx queues for each CoS thus we will
* allocate a multiple of 16 for ETH L2 rings according to the value of the
* bp->max_cos.
*
* If there is an FCoE L2 queue the appropriate Tx queue will have the next
* index after all ETH L2 indices.
*
* If the actual number of Tx queues (for each CoS) is less than 16 then there
* will be the holes at the end of each group of 16 ETh L2 indices (0..15,
* 16..31,...) with indices that are not coupled with any real Tx queue.
*
* The proper configuration of skb->queue_mapping is handled by
* bnx2x_select_queue() and __skb_tx_hash().
*
* bnx2x_setup_tc() takes care of the proper TC mappings so that __skb_tx_hash()
* will return a proper Tx index if TC is enabled (netdev->num_tc > 0).
*/
static int bnx2x_set_real_num_queues(struct bnx2x *bp, int include_cnic)
{
int rc, tx, rx;
tx = BNX2X_NUM_ETH_QUEUES(bp) * bp->max_cos;
rx = BNX2X_NUM_ETH_QUEUES(bp);
/* account for fcoe queue */
if (include_cnic && !NO_FCOE(bp)) {
rx++;
tx++;
}
rc = netif_set_real_num_tx_queues(bp->dev, tx);
if (rc) {
BNX2X_ERR("Failed to set real number of Tx queues: %d\n", rc);
return rc;
}
rc = netif_set_real_num_rx_queues(bp->dev, rx);
if (rc) {
BNX2X_ERR("Failed to set real number of Rx queues: %d\n", rc);
return rc;
}
DP(NETIF_MSG_IFUP, "Setting real num queues to (tx, rx) (%d, %d)\n",
tx, rx);
return rc;
}
static void bnx2x_set_rx_buf_size(struct bnx2x *bp)
{
int i;
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
u32 mtu;
/* Always use a mini-jumbo MTU for the FCoE L2 ring */
if (IS_FCOE_IDX(i))
/*
* Although there are no IP frames expected to arrive to
* this ring we still want to add an
* IP_HEADER_ALIGNMENT_PADDING to prevent a buffer
* overrun attack.
*/
mtu = BNX2X_FCOE_MINI_JUMBO_MTU;
else
mtu = bp->dev->mtu;
fp->rx_buf_size = BNX2X_FW_RX_ALIGN_START +
IP_HEADER_ALIGNMENT_PADDING +
ETH_OVERHEAD +
mtu +
BNX2X_FW_RX_ALIGN_END;
fp->rx_buf_size = SKB_DATA_ALIGN(fp->rx_buf_size);
/* Note : rx_buf_size doesn't take into account NET_SKB_PAD */
if (fp->rx_buf_size + NET_SKB_PAD <= PAGE_SIZE)
fp->rx_frag_size = fp->rx_buf_size + NET_SKB_PAD;
else
fp->rx_frag_size = 0;
}
}
static int bnx2x_init_rss(struct bnx2x *bp)
{
int i;
u8 num_eth_queues = BNX2X_NUM_ETH_QUEUES(bp);
/* Prepare the initial contents for the indirection table if RSS is
* enabled
*/
for (i = 0; i < sizeof(bp->rss_conf_obj.ind_table); i++)
bp->rss_conf_obj.ind_table[i] =
bp->fp->cl_id +
ethtool_rxfh_indir_default(i, num_eth_queues);
/*
* For 57710 and 57711 SEARCHER configuration (rss_keys) is
* per-port, so if explicit configuration is needed , do it only
* for a PMF.
*
* For 57712 and newer on the other hand it's a per-function
* configuration.
*/
return bnx2x_config_rss_eth(bp, bp->port.pmf || !CHIP_IS_E1x(bp));
}
int bnx2x_rss(struct bnx2x *bp, struct bnx2x_rss_config_obj *rss_obj,
bool config_hash, bool enable)
{
struct bnx2x_config_rss_params params = {NULL};
/* Although RSS is meaningless when there is a single HW queue we
* still need it enabled in order to have HW Rx hash generated.
*
* if (!is_eth_multi(bp))
* bp->multi_mode = ETH_RSS_MODE_DISABLED;
*/
params.rss_obj = rss_obj;
__set_bit(RAMROD_COMP_WAIT, ¶ms.ramrod_flags);
if (enable) {
__set_bit(BNX2X_RSS_MODE_REGULAR, ¶ms.rss_flags);
/* RSS configuration */
__set_bit(BNX2X_RSS_IPV4, ¶ms.rss_flags);
__set_bit(BNX2X_RSS_IPV4_TCP, ¶ms.rss_flags);
__set_bit(BNX2X_RSS_IPV6, ¶ms.rss_flags);
__set_bit(BNX2X_RSS_IPV6_TCP, ¶ms.rss_flags);
if (rss_obj->udp_rss_v4)
__set_bit(BNX2X_RSS_IPV4_UDP, ¶ms.rss_flags);
if (rss_obj->udp_rss_v6)
__set_bit(BNX2X_RSS_IPV6_UDP, ¶ms.rss_flags);
if (!CHIP_IS_E1x(bp)) {
/* valid only for TUNN_MODE_VXLAN tunnel mode */
__set_bit(BNX2X_RSS_IPV4_VXLAN, ¶ms.rss_flags);
__set_bit(BNX2X_RSS_IPV6_VXLAN, ¶ms.rss_flags);
/* valid only for TUNN_MODE_GRE tunnel mode */
__set_bit(BNX2X_RSS_TUNN_INNER_HDRS, ¶ms.rss_flags);
}
} else {
__set_bit(BNX2X_RSS_MODE_DISABLED, ¶ms.rss_flags);
}
/* Hash bits */
params.rss_result_mask = MULTI_MASK;
memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
if (config_hash) {
/* RSS keys */
netdev_rss_key_fill(params.rss_key, T_ETH_RSS_KEY * 4);
__set_bit(BNX2X_RSS_SET_SRCH, ¶ms.rss_flags);
}
if (IS_PF(bp))
return bnx2x_config_rss(bp, ¶ms);
else
return bnx2x_vfpf_config_rss(bp, ¶ms);
}
static int bnx2x_init_hw(struct bnx2x *bp, u32 load_code)
{
struct bnx2x_func_state_params func_params = {NULL};
/* Prepare parameters for function state transitions */
__set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
func_params.f_obj = &bp->func_obj;
func_params.cmd = BNX2X_F_CMD_HW_INIT;
func_params.params.hw_init.load_phase = load_code;
return bnx2x_func_state_change(bp, &func_params);
}
/*
* Cleans the object that have internal lists without sending
* ramrods. Should be run when interrupts are disabled.
*/
void bnx2x_squeeze_objects(struct bnx2x *bp)
{
int rc;
unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
struct bnx2x_mcast_ramrod_params rparam = {NULL};
struct bnx2x_vlan_mac_obj *mac_obj = &bp->sp_objs->mac_obj;
/***************** Cleanup MACs' object first *************************/
/* Wait for completion of requested */
__set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
/* Perform a dry cleanup */
__set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
/* Clean ETH primary MAC */
__set_bit(BNX2X_ETH_MAC, &vlan_mac_flags);
rc = mac_obj->delete_all(bp, &bp->sp_objs->mac_obj, &vlan_mac_flags,
&ramrod_flags);
if (rc != 0)
BNX2X_ERR("Failed to clean ETH MACs: %d\n", rc);
/* Cleanup UC list */
vlan_mac_flags = 0;
__set_bit(BNX2X_UC_LIST_MAC, &vlan_mac_flags);
rc = mac_obj->delete_all(bp, mac_obj, &vlan_mac_flags,
&ramrod_flags);
if (rc != 0)
BNX2X_ERR("Failed to clean UC list MACs: %d\n", rc);
/***************** Now clean mcast object *****************************/
rparam.mcast_obj = &bp->mcast_obj;
__set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
/* Add a DEL command... - Since we're doing a driver cleanup only,
* we take a lock surrounding both the initial send and the CONTs,
* as we don't want a true completion to disrupt us in the middle.
*/
netif_addr_lock_bh(bp->dev);
rc = bnx2x_config_mcast(bp, &rparam, BNX2X_MCAST_CMD_DEL);
if (rc < 0)
BNX2X_ERR("Failed to add a new DEL command to a multi-cast object: %d\n",
rc);
/* ...and wait until all pending commands are cleared */
rc = bnx2x_config_mcast(bp, &rparam, BNX2X_MCAST_CMD_CONT);
while (rc != 0) {
if (rc < 0) {
BNX2X_ERR("Failed to clean multi-cast object: %d\n",
rc);
netif_addr_unlock_bh(bp->dev);
return;
}
rc = bnx2x_config_mcast(bp, &rparam, BNX2X_MCAST_CMD_CONT);
}
netif_addr_unlock_bh(bp->dev);
}
#ifndef BNX2X_STOP_ON_ERROR
#define LOAD_ERROR_EXIT(bp, label) \
do { \
(bp)->state = BNX2X_STATE_ERROR; \
goto label; \
} while (0)
#define LOAD_ERROR_EXIT_CNIC(bp, label) \
do { \
bp->cnic_loaded = false; \
goto label; \
} while (0)
#else /*BNX2X_STOP_ON_ERROR*/
#define LOAD_ERROR_EXIT(bp, label) \
do { \
(bp)->state = BNX2X_STATE_ERROR; \
(bp)->panic = 1; \
return -EBUSY; \
} while (0)
#define LOAD_ERROR_EXIT_CNIC(bp, label) \
do { \
bp->cnic_loaded = false; \
(bp)->panic = 1; \
return -EBUSY; \
} while (0)
#endif /*BNX2X_STOP_ON_ERROR*/
static void bnx2x_free_fw_stats_mem(struct bnx2x *bp)
{
BNX2X_PCI_FREE(bp->fw_stats, bp->fw_stats_mapping,
bp->fw_stats_data_sz + bp->fw_stats_req_sz);
return;
}
static int bnx2x_alloc_fw_stats_mem(struct bnx2x *bp)
{
int num_groups, vf_headroom = 0;
int is_fcoe_stats = NO_FCOE(bp) ? 0 : 1;
/* number of queues for statistics is number of eth queues + FCoE */
u8 num_queue_stats = BNX2X_NUM_ETH_QUEUES(bp) + is_fcoe_stats;
/* Total number of FW statistics requests =
* 1 for port stats + 1 for PF stats + potential 2 for FCoE (fcoe proper
* and fcoe l2 queue) stats + num of queues (which includes another 1
* for fcoe l2 queue if applicable)
*/
bp->fw_stats_num = 2 + is_fcoe_stats + num_queue_stats;
/* vf stats appear in the request list, but their data is allocated by
* the VFs themselves. We don't include them in the bp->fw_stats_num as
* it is used to determine where to place the vf stats queries in the
* request struct
*/
if (IS_SRIOV(bp))
vf_headroom = bnx2x_vf_headroom(bp);
/* Request is built from stats_query_header and an array of
* stats_query_cmd_group each of which contains
* STATS_QUERY_CMD_COUNT rules. The real number or requests is
* configured in the stats_query_header.
*/
num_groups =
(((bp->fw_stats_num + vf_headroom) / STATS_QUERY_CMD_COUNT) +
(((bp->fw_stats_num + vf_headroom) % STATS_QUERY_CMD_COUNT) ?
1 : 0));
DP(BNX2X_MSG_SP, "stats fw_stats_num %d, vf headroom %d, num_groups %d\n",
bp->fw_stats_num, vf_headroom, num_groups);
bp->fw_stats_req_sz = sizeof(struct stats_query_header) +
num_groups * sizeof(struct stats_query_cmd_group);
/* Data for statistics requests + stats_counter
* stats_counter holds per-STORM counters that are incremented
* when STORM has finished with the current request.
* memory for FCoE offloaded statistics are counted anyway,
* even if they will not be sent.
* VF stats are not accounted for here as the data of VF stats is stored
* in memory allocated by the VF, not here.
*/
bp->fw_stats_data_sz = sizeof(struct per_port_stats) +
sizeof(struct per_pf_stats) +
sizeof(struct fcoe_statistics_params) +
sizeof(struct per_queue_stats) * num_queue_stats +
sizeof(struct stats_counter);
bp->fw_stats = BNX2X_PCI_ALLOC(&bp->fw_stats_mapping,
bp->fw_stats_data_sz + bp->fw_stats_req_sz);
if (!bp->fw_stats)
goto alloc_mem_err;
/* Set shortcuts */
bp->fw_stats_req = (struct bnx2x_fw_stats_req *)bp->fw_stats;
bp->fw_stats_req_mapping = bp->fw_stats_mapping;
bp->fw_stats_data = (struct bnx2x_fw_stats_data *)
((u8 *)bp->fw_stats + bp->fw_stats_req_sz);
bp->fw_stats_data_mapping = bp->fw_stats_mapping +
bp->fw_stats_req_sz;
DP(BNX2X_MSG_SP, "statistics request base address set to %x %x\n",
U64_HI(bp->fw_stats_req_mapping),
U64_LO(bp->fw_stats_req_mapping));
DP(BNX2X_MSG_SP, "statistics data base address set to %x %x\n",
U64_HI(bp->fw_stats_data_mapping),
U64_LO(bp->fw_stats_data_mapping));
return 0;
alloc_mem_err:
bnx2x_free_fw_stats_mem(bp);
BNX2X_ERR("Can't allocate FW stats memory\n");
return -ENOMEM;
}
/* send load request to mcp and analyze response */
static int bnx2x_nic_load_request(struct bnx2x *bp, u32 *load_code)
{
u32 param;
/* init fw_seq */
bp->fw_seq =
(SHMEM_RD(bp, func_mb[BP_FW_MB_IDX(bp)].drv_mb_header) &
DRV_MSG_SEQ_NUMBER_MASK);
BNX2X_DEV_INFO("fw_seq 0x%08x\n", bp->fw_seq);
/* Get current FW pulse sequence */
bp->fw_drv_pulse_wr_seq =
(SHMEM_RD(bp, func_mb[BP_FW_MB_IDX(bp)].drv_pulse_mb) &
DRV_PULSE_SEQ_MASK);
BNX2X_DEV_INFO("drv_pulse 0x%x\n", bp->fw_drv_pulse_wr_seq);
param = DRV_MSG_CODE_LOAD_REQ_WITH_LFA;
if (IS_MF_SD(bp) && bnx2x_port_after_undi(bp))
param |= DRV_MSG_CODE_LOAD_REQ_FORCE_LFA;
/* load request */
(*load_code) = bnx2x_fw_command(bp, DRV_MSG_CODE_LOAD_REQ, param);
/* if mcp fails to respond we must abort */
if (!(*load_code)) {
BNX2X_ERR("MCP response failure, aborting\n");
return -EBUSY;
}
/* If mcp refused (e.g. other port is in diagnostic mode) we
* must abort
*/
if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
BNX2X_ERR("MCP refused load request, aborting\n");
return -EBUSY;
}
return 0;
}
/* check whether another PF has already loaded FW to chip. In
* virtualized environments a pf from another VM may have already
* initialized the device including loading FW
*/
int bnx2x_compare_fw_ver(struct bnx2x *bp, u32 load_code, bool print_err)
{
/* is another pf loaded on this engine? */
if (load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP &&
load_code != FW_MSG_CODE_DRV_LOAD_COMMON) {
/* build my FW version dword */
u32 my_fw = (BCM_5710_FW_MAJOR_VERSION) +
(BCM_5710_FW_MINOR_VERSION << 8) +
(BCM_5710_FW_REVISION_VERSION << 16) +
(BCM_5710_FW_ENGINEERING_VERSION << 24);
/* read loaded FW from chip */
u32 loaded_fw = REG_RD(bp, XSEM_REG_PRAM);
DP(BNX2X_MSG_SP, "loaded fw %x, my fw %x\n",
loaded_fw, my_fw);
/* abort nic load if version mismatch */
if (my_fw != loaded_fw) {
if (print_err)
BNX2X_ERR("bnx2x with FW %x was already loaded which mismatches my %x FW. Aborting\n",
loaded_fw, my_fw);
else
BNX2X_DEV_INFO("bnx2x with FW %x was already loaded which mismatches my %x FW, possibly due to MF UNDI\n",
loaded_fw, my_fw);
return -EBUSY;
}
}
return 0;
}
/* returns the "mcp load_code" according to global load_count array */
static int bnx2x_nic_load_no_mcp(struct bnx2x *bp, int port)
{
int path = BP_PATH(bp);
DP(NETIF_MSG_IFUP, "NO MCP - load counts[%d] %d, %d, %d\n",
path, bnx2x_load_count[path][0], bnx2x_load_count[path][1],
bnx2x_load_count[path][2]);
bnx2x_load_count[path][0]++;
bnx2x_load_count[path][1 + port]++;
DP(NETIF_MSG_IFUP, "NO MCP - new load counts[%d] %d, %d, %d\n",
path, bnx2x_load_count[path][0], bnx2x_load_count[path][1],
bnx2x_load_count[path][2]);
if (bnx2x_load_count[path][0] == 1)
return FW_MSG_CODE_DRV_LOAD_COMMON;
else if (bnx2x_load_count[path][1 + port] == 1)
return FW_MSG_CODE_DRV_LOAD_PORT;
else
return FW_MSG_CODE_DRV_LOAD_FUNCTION;
}
/* mark PMF if applicable */
static void bnx2x_nic_load_pmf(struct bnx2x *bp, u32 load_code)
{
if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
(load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
(load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
bp->port.pmf = 1;
/* We need the barrier to ensure the ordering between the
* writing to bp->port.pmf here and reading it from the
* bnx2x_periodic_task().
*/
smp_mb();
} else {
bp->port.pmf = 0;
}
DP(NETIF_MSG_LINK, "pmf %d\n", bp->port.pmf);
}
static void bnx2x_nic_load_afex_dcc(struct bnx2x *bp, int load_code)
{
if (((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
(load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP)) &&
(bp->common.shmem2_base)) {
if (SHMEM2_HAS(bp, dcc_support))
SHMEM2_WR(bp, dcc_support,
(SHMEM_DCC_SUPPORT_DISABLE_ENABLE_PF_TLV |
SHMEM_DCC_SUPPORT_BANDWIDTH_ALLOCATION_TLV));
if (SHMEM2_HAS(bp, afex_driver_support))
SHMEM2_WR(bp, afex_driver_support,
SHMEM_AFEX_SUPPORTED_VERSION_ONE);
}
/* Set AFEX default VLAN tag to an invalid value */
bp->afex_def_vlan_tag = -1;
}
/**
* bnx2x_bz_fp - zero content of the fastpath structure.
*
* @bp: driver handle
* @index: fastpath index to be zeroed
*
* Makes sure the contents of the bp->fp[index].napi is kept
* intact.
*/
static void bnx2x_bz_fp(struct bnx2x *bp, int index)
{
struct bnx2x_fastpath *fp = &bp->fp[index];
int cos;
struct napi_struct orig_napi = fp->napi;
struct bnx2x_agg_info *orig_tpa_info = fp->tpa_info;
/* bzero bnx2x_fastpath contents */
if (fp->tpa_info)
memset(fp->tpa_info, 0, ETH_MAX_AGGREGATION_QUEUES_E1H_E2 *
sizeof(struct bnx2x_agg_info));
memset(fp, 0, sizeof(*fp));
/* Restore the NAPI object as it has been already initialized */
fp->napi = orig_napi;
fp->tpa_info = orig_tpa_info;
fp->bp = bp;
fp->index = index;
if (IS_ETH_FP(fp))
fp->max_cos = bp->max_cos;
else
/* Special queues support only one CoS */
fp->max_cos = 1;
/* Init txdata pointers */
if (IS_FCOE_FP(fp))
fp->txdata_ptr[0] = &bp->bnx2x_txq[FCOE_TXQ_IDX(bp)];
if (IS_ETH_FP(fp))
for_each_cos_in_tx_queue(fp, cos)
fp->txdata_ptr[cos] = &bp->bnx2x_txq[cos *
BNX2X_NUM_ETH_QUEUES(bp) + index];
/* set the tpa flag for each queue. The tpa flag determines the queue
* minimal size so it must be set prior to queue memory allocation
*/
if (bp->dev->features & NETIF_F_LRO)
fp->mode = TPA_MODE_LRO;
else if (bp->dev->features & NETIF_F_GRO &&
bnx2x_mtu_allows_gro(bp->dev->mtu))
fp->mode = TPA_MODE_GRO;
else
fp->mode = TPA_MODE_DISABLED;
/* We don't want TPA if it's disabled in bp
* or if this is an FCoE L2 ring.
*/
if (bp->disable_tpa || IS_FCOE_FP(fp))
fp->mode = TPA_MODE_DISABLED;
}
void bnx2x_set_os_driver_state(struct bnx2x *bp, u32 state)
{
u32 cur;
if (!IS_MF_BD(bp) || !SHMEM2_HAS(bp, os_driver_state) || IS_VF(bp))
return;
cur = SHMEM2_RD(bp, os_driver_state[BP_FW_MB_IDX(bp)]);
DP(NETIF_MSG_IFUP, "Driver state %08x-->%08x\n",
cur, state);
SHMEM2_WR(bp, os_driver_state[BP_FW_MB_IDX(bp)], state);
}
int bnx2x_load_cnic(struct bnx2x *bp)
{
int i, rc, port = BP_PORT(bp);
DP(NETIF_MSG_IFUP, "Starting CNIC-related load\n");
mutex_init(&bp->cnic_mutex);
if (IS_PF(bp)) {
rc = bnx2x_alloc_mem_cnic(bp);
if (rc) {
BNX2X_ERR("Unable to allocate bp memory for cnic\n");
LOAD_ERROR_EXIT_CNIC(bp, load_error_cnic0);
}
}
rc = bnx2x_alloc_fp_mem_cnic(bp);
if (rc) {
BNX2X_ERR("Unable to allocate memory for cnic fps\n");
LOAD_ERROR_EXIT_CNIC(bp, load_error_cnic0);
}
/* Update the number of queues with the cnic queues */
rc = bnx2x_set_real_num_queues(bp, 1);
if (rc) {
BNX2X_ERR("Unable to set real_num_queues including cnic\n");
LOAD_ERROR_EXIT_CNIC(bp, load_error_cnic0);
}
/* Add all CNIC NAPI objects */
bnx2x_add_all_napi_cnic(bp);
DP(NETIF_MSG_IFUP, "cnic napi added\n");
bnx2x_napi_enable_cnic(bp);
rc = bnx2x_init_hw_func_cnic(bp);
if (rc)
LOAD_ERROR_EXIT_CNIC(bp, load_error_cnic1);
bnx2x_nic_init_cnic(bp);
if (IS_PF(bp)) {
/* Enable Timer scan */
REG_WR(bp, TM_REG_EN_LINEAR0_TIMER + port*4, 1);
/* setup cnic queues */
for_each_cnic_queue(bp, i) {
rc = bnx2x_setup_queue(bp, &bp->fp[i], 0);
if (rc) {
BNX2X_ERR("Queue setup failed\n");
LOAD_ERROR_EXIT(bp, load_error_cnic2);
}
}
}
/* Initialize Rx filter. */
bnx2x_set_rx_mode_inner(bp);
/* re-read iscsi info */
bnx2x_get_iscsi_info(bp);
bnx2x_setup_cnic_irq_info(bp);
bnx2x_setup_cnic_info(bp);
bp->cnic_loaded = true;
if (bp->state == BNX2X_STATE_OPEN)
bnx2x_cnic_notify(bp, CNIC_CTL_START_CMD);
DP(NETIF_MSG_IFUP, "Ending successfully CNIC-related load\n");
return 0;
#ifndef BNX2X_STOP_ON_ERROR
load_error_cnic2:
/* Disable Timer scan */
REG_WR(bp, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
load_error_cnic1:
bnx2x_napi_disable_cnic(bp);
/* Update the number of queues without the cnic queues */
if (bnx2x_set_real_num_queues(bp, 0))
BNX2X_ERR("Unable to set real_num_queues not including cnic\n");
load_error_cnic0:
BNX2X_ERR("CNIC-related load failed\n");
bnx2x_free_fp_mem_cnic(bp);
bnx2x_free_mem_cnic(bp);
return rc;
#endif /* ! BNX2X_STOP_ON_ERROR */
}
/* must be called with rtnl_lock */
int bnx2x_nic_load(struct bnx2x *bp, int load_mode)
{
int port = BP_PORT(bp);
int i, rc = 0, load_code = 0;
DP(NETIF_MSG_IFUP, "Starting NIC load\n");
DP(NETIF_MSG_IFUP,
"CNIC is %s\n", CNIC_ENABLED(bp) ? "enabled" : "disabled");
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic)) {
BNX2X_ERR("Can't load NIC when there is panic\n");
return -EPERM;
}
#endif
bp->state = BNX2X_STATE_OPENING_WAIT4_LOAD;
/* zero the structure w/o any lock, before SP handler is initialized */
memset(&bp->last_reported_link, 0, sizeof(bp->last_reported_link));
__set_bit(BNX2X_LINK_REPORT_LINK_DOWN,
&bp->last_reported_link.link_report_flags);
if (IS_PF(bp))
/* must be called before memory allocation and HW init */
bnx2x_ilt_set_info(bp);
/*
* Zero fastpath structures preserving invariants like napi, which are
* allocated only once, fp index, max_cos, bp pointer.
* Also set fp->mode and txdata_ptr.
*/
DP(NETIF_MSG_IFUP, "num queues: %d", bp->num_queues);
for_each_queue(bp, i)
bnx2x_bz_fp(bp, i);
memset(bp->bnx2x_txq, 0, (BNX2X_MAX_RSS_COUNT(bp) * BNX2X_MULTI_TX_COS +
bp->num_cnic_queues) *
sizeof(struct bnx2x_fp_txdata));
bp->fcoe_init = false;
/* Set the receive queues buffer size */
bnx2x_set_rx_buf_size(bp);
if (IS_PF(bp)) {
rc = bnx2x_alloc_mem(bp);
if (rc) {
BNX2X_ERR("Unable to allocate bp memory\n");
return rc;
}
}
/* need to be done after alloc mem, since it's self adjusting to amount
* of memory available for RSS queues
*/
rc = bnx2x_alloc_fp_mem(bp);
if (rc) {
BNX2X_ERR("Unable to allocate memory for fps\n");
LOAD_ERROR_EXIT(bp, load_error0);
}
/* Allocated memory for FW statistics */
if (bnx2x_alloc_fw_stats_mem(bp))
LOAD_ERROR_EXIT(bp, load_error0);
/* request pf to initialize status blocks */
if (IS_VF(bp)) {
rc = bnx2x_vfpf_init(bp);
if (rc)
LOAD_ERROR_EXIT(bp, load_error0);
}
/* As long as bnx2x_alloc_mem() may possibly update
* bp->num_queues, bnx2x_set_real_num_queues() should always
* come after it. At this stage cnic queues are not counted.
*/
rc = bnx2x_set_real_num_queues(bp, 0);
if (rc) {
BNX2X_ERR("Unable to set real_num_queues\n");
LOAD_ERROR_EXIT(bp, load_error0);
}
/* configure multi cos mappings in kernel.
* this configuration may be overridden by a multi class queue
* discipline or by a dcbx negotiation result.
*/
bnx2x_setup_tc(bp->dev, bp->max_cos);
/* Add all NAPI objects */
bnx2x_add_all_napi(bp);
DP(NETIF_MSG_IFUP, "napi added\n");
bnx2x_napi_enable(bp);
if (IS_PF(bp)) {
/* set pf load just before approaching the MCP */
bnx2x_set_pf_load(bp);
/* if mcp exists send load request and analyze response */
if (!BP_NOMCP(bp)) {
/* attempt to load pf */
rc = bnx2x_nic_load_request(bp, &load_code);
if (rc)
LOAD_ERROR_EXIT(bp, load_error1);
/* what did mcp say? */
rc = bnx2x_compare_fw_ver(bp, load_code, true);
if (rc) {
bnx2x_fw_command(bp, DRV_MSG_CODE_LOAD_DONE, 0);
LOAD_ERROR_EXIT(bp, load_error2);
}
} else {
load_code = bnx2x_nic_load_no_mcp(bp, port);
}
/* mark pmf if applicable */
bnx2x_nic_load_pmf(bp, load_code);
/* Init Function state controlling object */
bnx2x__init_func_obj(bp);
/* Initialize HW */
rc = bnx2x_init_hw(bp, load_code);
if (rc) {
BNX2X_ERR("HW init failed, aborting\n");
bnx2x_fw_command(bp, DRV_MSG_CODE_LOAD_DONE, 0);
LOAD_ERROR_EXIT(bp, load_error2);
}
}
bnx2x_pre_irq_nic_init(bp);
/* Connect to IRQs */
rc = bnx2x_setup_irqs(bp);
if (rc) {
BNX2X_ERR("setup irqs failed\n");
if (IS_PF(bp))
bnx2x_fw_command(bp, DRV_MSG_CODE_LOAD_DONE, 0);
LOAD_ERROR_EXIT(bp, load_error2);
}
/* Init per-function objects */
if (IS_PF(bp)) {
/* Setup NIC internals and enable interrupts */
bnx2x_post_irq_nic_init(bp, load_code);
bnx2x_init_bp_objs(bp);
bnx2x_iov_nic_init(bp);
/* Set AFEX default VLAN tag to an invalid value */
bp->afex_def_vlan_tag = -1;
bnx2x_nic_load_afex_dcc(bp, load_code);
bp->state = BNX2X_STATE_OPENING_WAIT4_PORT;
rc = bnx2x_func_start(bp);
if (rc) {
BNX2X_ERR("Function start failed!\n");
bnx2x_fw_command(bp, DRV_MSG_CODE_LOAD_DONE, 0);
LOAD_ERROR_EXIT(bp, load_error3);
}
/* Send LOAD_DONE command to MCP */
if (!BP_NOMCP(bp)) {
load_code = bnx2x_fw_command(bp,
DRV_MSG_CODE_LOAD_DONE, 0);
if (!load_code) {
BNX2X_ERR("MCP response failure, aborting\n");
rc = -EBUSY;
LOAD_ERROR_EXIT(bp, load_error3);
}
}
/* initialize FW coalescing state machines in RAM */
bnx2x_update_coalesce(bp);
}
/* setup the leading queue */
rc = bnx2x_setup_leading(bp);
if (rc) {
BNX2X_ERR("Setup leading failed!\n");
LOAD_ERROR_EXIT(bp, load_error3);
}
/* set up the rest of the queues */
for_each_nondefault_eth_queue(bp, i) {
if (IS_PF(bp))
rc = bnx2x_setup_queue(bp, &bp->fp[i], false);
else /* VF */
rc = bnx2x_vfpf_setup_q(bp, &bp->fp[i], false);
if (rc) {
BNX2X_ERR("Queue %d setup failed\n", i);
LOAD_ERROR_EXIT(bp, load_error3);
}
}
/* setup rss */
rc = bnx2x_init_rss(bp);
if (rc) {
BNX2X_ERR("PF RSS init failed\n");
LOAD_ERROR_EXIT(bp, load_error3);
}
/* Now when Clients are configured we are ready to work */
bp->state = BNX2X_STATE_OPEN;
/* Configure a ucast MAC */
if (IS_PF(bp))
rc = bnx2x_set_eth_mac(bp, true);
else /* vf */
rc = bnx2x_vfpf_config_mac(bp, bp->dev->dev_addr, bp->fp->index,
true);
if (rc) {
BNX2X_ERR("Setting Ethernet MAC failed\n");
LOAD_ERROR_EXIT(bp, load_error3);
}
if (IS_PF(bp) && bp->pending_max) {
bnx2x_update_max_mf_config(bp, bp->pending_max);
bp->pending_max = 0;
}
if (bp->port.pmf) {
rc = bnx2x_initial_phy_init(bp, load_mode);
if (rc)
LOAD_ERROR_EXIT(bp, load_error3);
}
bp->link_params.feature_config_flags &= ~FEATURE_CONFIG_BOOT_FROM_SAN;
/* Start fast path */
/* Re-configure vlan filters */
rc = bnx2x_vlan_reconfigure_vid(bp);
if (rc)
LOAD_ERROR_EXIT(bp, load_error3);
/* Initialize Rx filter. */
bnx2x_set_rx_mode_inner(bp);
if (bp->flags & PTP_SUPPORTED) {
bnx2x_init_ptp(bp);
bnx2x_configure_ptp_filters(bp);
}
/* Start Tx */
switch (load_mode) {
case LOAD_NORMAL:
/* Tx queue should be only re-enabled */
netif_tx_wake_all_queues(bp->dev);
break;
case LOAD_OPEN:
netif_tx_start_all_queues(bp->dev);
smp_mb__after_atomic();
break;
case LOAD_DIAG:
case LOAD_LOOPBACK_EXT:
bp->state = BNX2X_STATE_DIAG;
break;
default:
break;
}
if (bp->port.pmf)
bnx2x_update_drv_flags(bp, 1 << DRV_FLAGS_PORT_MASK, 0);
else
bnx2x__link_status_update(bp);
/* start the timer */
mod_timer(&bp->timer, jiffies + bp->current_interval);
if (CNIC_ENABLED(bp))
bnx2x_load_cnic(bp);
if (IS_PF(bp))
bnx2x_schedule_sp_rtnl(bp, BNX2X_SP_RTNL_GET_DRV_VERSION, 0);
if (IS_PF(bp) && SHMEM2_HAS(bp, drv_capabilities_flag)) {
/* mark driver is loaded in shmem2 */
u32 val;
val = SHMEM2_RD(bp, drv_capabilities_flag[BP_FW_MB_IDX(bp)]);
val &= ~DRV_FLAGS_MTU_MASK;
val |= (bp->dev->mtu << DRV_FLAGS_MTU_SHIFT);
SHMEM2_WR(bp, drv_capabilities_flag[BP_FW_MB_IDX(bp)],
val | DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
DRV_FLAGS_CAPABILITIES_LOADED_L2);
}
/* Wait for all pending SP commands to complete */
if (IS_PF(bp) && !bnx2x_wait_sp_comp(bp, ~0x0UL)) {
BNX2X_ERR("Timeout waiting for SP elements to complete\n");
bnx2x_nic_unload(bp, UNLOAD_CLOSE, false);
return -EBUSY;
}
/* Update driver data for On-Chip MFW dump. */
if (IS_PF(bp))
bnx2x_update_mfw_dump(bp);
/* If PMF - send ADMIN DCBX msg to MFW to initiate DCBX FSM */
if (bp->port.pmf && (bp->state != BNX2X_STATE_DIAG))
bnx2x_dcbx_init(bp, false);
if (!IS_MF_SD_STORAGE_PERSONALITY_ONLY(bp))
bnx2x_set_os_driver_state(bp, OS_DRIVER_STATE_ACTIVE);
DP(NETIF_MSG_IFUP, "Ending successfully NIC load\n");
return 0;
#ifndef BNX2X_STOP_ON_ERROR
load_error3:
if (IS_PF(bp)) {
bnx2x_int_disable_sync(bp, 1);
/* Clean queueable objects */
bnx2x_squeeze_objects(bp);
}
/* Free SKBs, SGEs, TPA pool and driver internals */
bnx2x_free_skbs(bp);
for_each_rx_queue(bp, i)
bnx2x_free_rx_sge_range(bp, bp->fp + i, NUM_RX_SGE);
/* Release IRQs */
bnx2x_free_irq(bp);
load_error2:
if (IS_PF(bp) && !BP_NOMCP(bp)) {
bnx2x_fw_command(bp, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
bnx2x_fw_command(bp, DRV_MSG_CODE_UNLOAD_DONE, 0);
}
bp->port.pmf = 0;
load_error1:
bnx2x_napi_disable(bp);
bnx2x_del_all_napi(bp);
/* clear pf_load status, as it was already set */
if (IS_PF(bp))
bnx2x_clear_pf_load(bp);
load_error0:
bnx2x_free_fw_stats_mem(bp);
bnx2x_free_fp_mem(bp);
bnx2x_free_mem(bp);
return rc;
#endif /* ! BNX2X_STOP_ON_ERROR */
}
int bnx2x_drain_tx_queues(struct bnx2x *bp)
{
u8 rc = 0, cos, i;
/* Wait until tx fastpath tasks complete */
for_each_tx_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
for_each_cos_in_tx_queue(fp, cos)
rc = bnx2x_clean_tx_queue(bp, fp->txdata_ptr[cos]);
if (rc)
return rc;
}
return 0;
}
/* must be called with rtnl_lock */
int bnx2x_nic_unload(struct bnx2x *bp, int unload_mode, bool keep_link)
{
int i;
bool global = false;
DP(NETIF_MSG_IFUP, "Starting NIC unload\n");
if (!IS_MF_SD_STORAGE_PERSONALITY_ONLY(bp))
bnx2x_set_os_driver_state(bp, OS_DRIVER_STATE_DISABLED);
/* mark driver is unloaded in shmem2 */
if (IS_PF(bp) && SHMEM2_HAS(bp, drv_capabilities_flag)) {
u32 val;
val = SHMEM2_RD(bp, drv_capabilities_flag[BP_FW_MB_IDX(bp)]);
SHMEM2_WR(bp, drv_capabilities_flag[BP_FW_MB_IDX(bp)],
val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
}
if (IS_PF(bp) && bp->recovery_state != BNX2X_RECOVERY_DONE &&
(bp->state == BNX2X_STATE_CLOSED ||
bp->state == BNX2X_STATE_ERROR)) {
/* We can get here if the driver has been unloaded
* during parity error recovery and is either waiting for a
* leader to complete or for other functions to unload and
* then ifdown has been issued. In this case we want to
* unload and let other functions to complete a recovery
* process.
*/
bp->recovery_state = BNX2X_RECOVERY_DONE;
bp->is_leader = 0;
bnx2x_release_leader_lock(bp);
smp_mb();
DP(NETIF_MSG_IFDOWN, "Releasing a leadership...\n");
BNX2X_ERR("Can't unload in closed or error state\n");
return -EINVAL;
}
/* Nothing to do during unload if previous bnx2x_nic_load()
* have not completed successfully - all resources are released.
*
* we can get here only after unsuccessful ndo_* callback, during which
* dev->IFF_UP flag is still on.
*/
if (bp->state == BNX2X_STATE_CLOSED || bp->state == BNX2X_STATE_ERROR)
return 0;
/* It's important to set the bp->state to the value different from
* BNX2X_STATE_OPEN and only then stop the Tx. Otherwise bnx2x_tx_int()
* may restart the Tx from the NAPI context (see bnx2x_tx_int()).
*/
bp->state = BNX2X_STATE_CLOSING_WAIT4_HALT;
smp_mb();
/* indicate to VFs that the PF is going down */
bnx2x_iov_channel_down(bp);
if (CNIC_LOADED(bp))
bnx2x_cnic_notify(bp, CNIC_CTL_STOP_CMD);
/* Stop Tx */
bnx2x_tx_disable(bp);
netdev_reset_tc(bp->dev);
bp->rx_mode = BNX2X_RX_MODE_NONE;
del_timer_sync(&bp->timer);
if (IS_PF(bp)) {
/* Set ALWAYS_ALIVE bit in shmem */
bp->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
bnx2x_drv_pulse(bp);
bnx2x_stats_handle(bp, STATS_EVENT_STOP);
bnx2x_save_statistics(bp);
}
/* wait till consumers catch up with producers in all queues.
* If we're recovering, FW can't write to host so no reason
* to wait for the queues to complete all Tx.
*/
if (unload_mode != UNLOAD_RECOVERY)
bnx2x_drain_tx_queues(bp);
/* if VF indicate to PF this function is going down (PF will delete sp
* elements and clear initializations
*/
if (IS_VF(bp))
bnx2x_vfpf_close_vf(bp);
else if (unload_mode != UNLOAD_RECOVERY)
/* if this is a normal/close unload need to clean up chip*/
bnx2x_chip_cleanup(bp, unload_mode, keep_link);
else {
/* Send the UNLOAD_REQUEST to the MCP */
bnx2x_send_unload_req(bp, unload_mode);
/* Prevent transactions to host from the functions on the
* engine that doesn't reset global blocks in case of global
* attention once global blocks are reset and gates are opened
* (the engine which leader will perform the recovery
* last).
*/
if (!CHIP_IS_E1x(bp))
bnx2x_pf_disable(bp);
/* Disable HW interrupts, NAPI */
bnx2x_netif_stop(bp, 1);
/* Delete all NAPI objects */
bnx2x_del_all_napi(bp);
if (CNIC_LOADED(bp))
bnx2x_del_all_napi_cnic(bp);
/* Release IRQs */
bnx2x_free_irq(bp);
/* Report UNLOAD_DONE to MCP */
bnx2x_send_unload_done(bp, false);
}
/*
* At this stage no more interrupts will arrive so we may safely clean
* the queueable objects here in case they failed to get cleaned so far.
*/
if (IS_PF(bp))
bnx2x_squeeze_objects(bp);
/* There should be no more pending SP commands at this stage */
bp->sp_state = 0;
bp->port.pmf = 0;
/* clear pending work in rtnl task */
bp->sp_rtnl_state = 0;
smp_mb();
/* Free SKBs, SGEs, TPA pool and driver internals */
bnx2x_free_skbs(bp);
if (CNIC_LOADED(bp))
bnx2x_free_skbs_cnic(bp);
for_each_rx_queue(bp, i)
bnx2x_free_rx_sge_range(bp, bp->fp + i, NUM_RX_SGE);
bnx2x_free_fp_mem(bp);
if (CNIC_LOADED(bp))
bnx2x_free_fp_mem_cnic(bp);
if (IS_PF(bp)) {
if (CNIC_LOADED(bp))
bnx2x_free_mem_cnic(bp);
}
bnx2x_free_mem(bp);
bp->state = BNX2X_STATE_CLOSED;
bp->cnic_loaded = false;
/* Clear driver version indication in shmem */
if (IS_PF(bp))
bnx2x_update_mng_version(bp);
/* Check if there are pending parity attentions. If there are - set
* RECOVERY_IN_PROGRESS.
*/
if (IS_PF(bp) && bnx2x_chk_parity_attn(bp, &global, false)) {
bnx2x_set_reset_in_progress(bp);
/* Set RESET_IS_GLOBAL if needed */
if (global)
bnx2x_set_reset_global(bp);
}
/* The last driver must disable a "close the gate" if there is no
* parity attention or "process kill" pending.
*/
if (IS_PF(bp) &&
!bnx2x_clear_pf_load(bp) &&
bnx2x_reset_is_done(bp, BP_PATH(bp)))
bnx2x_disable_close_the_gate(bp);
DP(NETIF_MSG_IFUP, "Ending NIC unload\n");
return 0;
}
int bnx2x_set_power_state(struct bnx2x *bp, pci_power_t state)
{
u16 pmcsr;
/* If there is no power capability, silently succeed */
if (!bp->pdev->pm_cap) {
BNX2X_DEV_INFO("No power capability. Breaking.\n");
return 0;
}
pci_read_config_word(bp->pdev, bp->pdev->pm_cap + PCI_PM_CTRL, &pmcsr);
switch (state) {
case PCI_D0:
pci_write_config_word(bp->pdev, bp->pdev->pm_cap + PCI_PM_CTRL,
((pmcsr & ~PCI_PM_CTRL_STATE_MASK) |
PCI_PM_CTRL_PME_STATUS));
if (pmcsr & PCI_PM_CTRL_STATE_MASK)
/* delay required during transition out of D3hot */
msleep(20);
break;
case PCI_D3hot:
/* If there are other clients above don't
shut down the power */
if (atomic_read(&bp->pdev->enable_cnt) != 1)
return 0;
/* Don't shut down the power for emulation and FPGA */
if (CHIP_REV_IS_SLOW(bp))
return 0;
pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
pmcsr |= 3;
if (bp->wol)
pmcsr |= PCI_PM_CTRL_PME_ENABLE;
pci_write_config_word(bp->pdev, bp->pdev->pm_cap + PCI_PM_CTRL,
pmcsr);
/* No more memory access after this point until
* device is brought back to D0.
*/
break;
default:
dev_err(&bp->pdev->dev, "Can't support state = %d\n", state);
return -EINVAL;
}
return 0;
}
/*
* net_device service functions
*/
static int bnx2x_poll(struct napi_struct *napi, int budget)
{
struct bnx2x_fastpath *fp = container_of(napi, struct bnx2x_fastpath,
napi);
struct bnx2x *bp = fp->bp;
int rx_work_done;
u8 cos;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic)) {
napi_complete(napi);
return 0;
}
#endif
for_each_cos_in_tx_queue(fp, cos)
if (bnx2x_tx_queue_has_work(fp->txdata_ptr[cos]))
bnx2x_tx_int(bp, fp->txdata_ptr[cos]);
rx_work_done = (bnx2x_has_rx_work(fp)) ? bnx2x_rx_int(fp, budget) : 0;
if (rx_work_done < budget) {
/* No need to update SB for FCoE L2 ring as long as
* it's connected to the default SB and the SB
* has been updated when NAPI was scheduled.
*/
if (IS_FCOE_FP(fp)) {
napi_complete_done(napi, rx_work_done);
} else {
bnx2x_update_fpsb_idx(fp);
/* bnx2x_has_rx_work() reads the status block,
* thus we need to ensure that status block indices
* have been actually read (bnx2x_update_fpsb_idx)
* prior to this check (bnx2x_has_rx_work) so that
* we won't write the "newer" value of the status block
* to IGU (if there was a DMA right after
* bnx2x_has_rx_work and if there is no rmb, the memory
* reading (bnx2x_update_fpsb_idx) may be postponed
* to right before bnx2x_ack_sb). In this case there
* will never be another interrupt until there is
* another update of the status block, while there
* is still unhandled work.
*/
rmb();
if (!(bnx2x_has_rx_work(fp) || bnx2x_has_tx_work(fp))) {
if (napi_complete_done(napi, rx_work_done)) {
/* Re-enable interrupts */
DP(NETIF_MSG_RX_STATUS,
"Update index to %d\n", fp->fp_hc_idx);
bnx2x_ack_sb(bp, fp->igu_sb_id, USTORM_ID,
le16_to_cpu(fp->fp_hc_idx),
IGU_INT_ENABLE, 1);
}
} else {
rx_work_done = budget;
}
}
}
return rx_work_done;
}
/* we split the first BD into headers and data BDs
* to ease the pain of our fellow microcode engineers
* we use one mapping for both BDs
*/
static u16 bnx2x_tx_split(struct bnx2x *bp,
struct bnx2x_fp_txdata *txdata,
struct sw_tx_bd *tx_buf,
struct eth_tx_start_bd **tx_bd, u16 hlen,
u16 bd_prod)
{
struct eth_tx_start_bd *h_tx_bd = *tx_bd;
struct eth_tx_bd *d_tx_bd;
dma_addr_t mapping;
int old_len = le16_to_cpu(h_tx_bd->nbytes);
/* first fix first BD */
h_tx_bd->nbytes = cpu_to_le16(hlen);
DP(NETIF_MSG_TX_QUEUED, "TSO split header size is %d (%x:%x)\n",
h_tx_bd->nbytes, h_tx_bd->addr_hi, h_tx_bd->addr_lo);
/* now get a new data BD
* (after the pbd) and fill it */
bd_prod = TX_BD(NEXT_TX_IDX(bd_prod));
d_tx_bd = &txdata->tx_desc_ring[bd_prod].reg_bd;
mapping = HILO_U64(le32_to_cpu(h_tx_bd->addr_hi),
le32_to_cpu(h_tx_bd->addr_lo)) + hlen;
d_tx_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
d_tx_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
d_tx_bd->nbytes = cpu_to_le16(old_len - hlen);
/* this marks the BD as one that has no individual mapping */
tx_buf->flags |= BNX2X_TSO_SPLIT_BD;
DP(NETIF_MSG_TX_QUEUED,
"TSO split data size is %d (%x:%x)\n",
d_tx_bd->nbytes, d_tx_bd->addr_hi, d_tx_bd->addr_lo);
/* update tx_bd */
*tx_bd = (struct eth_tx_start_bd *)d_tx_bd;
return bd_prod;
}
#define bswab32(b32) ((__force __le32) swab32((__force __u32) (b32)))
#define bswab16(b16) ((__force __le16) swab16((__force __u16) (b16)))
static __le16 bnx2x_csum_fix(unsigned char *t_header, u16 csum, s8 fix)
{
__sum16 tsum = (__force __sum16) csum;
if (fix > 0)
tsum = ~csum_fold(csum_sub((__force __wsum) csum,
csum_partial(t_header - fix, fix, 0)));
else if (fix < 0)
tsum = ~csum_fold(csum_add((__force __wsum) csum,
csum_partial(t_header, -fix, 0)));
return bswab16(tsum);
}
static u32 bnx2x_xmit_type(struct bnx2x *bp, struct sk_buff *skb)
{
u32 rc;
__u8 prot = 0;
__be16 protocol;
if (skb->ip_summed != CHECKSUM_PARTIAL)
return XMIT_PLAIN;
protocol = vlan_get_protocol(skb);
if (protocol == htons(ETH_P_IPV6)) {
rc = XMIT_CSUM_V6;
prot = ipv6_hdr(skb)->nexthdr;
} else {
rc = XMIT_CSUM_V4;
prot = ip_hdr(skb)->protocol;
}
if (!CHIP_IS_E1x(bp) && skb->encapsulation) {
if (inner_ip_hdr(skb)->version == 6) {
rc |= XMIT_CSUM_ENC_V6;
if (inner_ipv6_hdr(skb)->nexthdr == IPPROTO_TCP)
rc |= XMIT_CSUM_TCP;
} else {
rc |= XMIT_CSUM_ENC_V4;
if (inner_ip_hdr(skb)->protocol == IPPROTO_TCP)
rc |= XMIT_CSUM_TCP;
}
}
if (prot == IPPROTO_TCP)
rc |= XMIT_CSUM_TCP;
if (skb_is_gso(skb)) {
if (skb_is_gso_v6(skb)) {
rc |= (XMIT_GSO_V6 | XMIT_CSUM_TCP);
if (rc & XMIT_CSUM_ENC)
rc |= XMIT_GSO_ENC_V6;
} else {
rc |= (XMIT_GSO_V4 | XMIT_CSUM_TCP);
if (rc & XMIT_CSUM_ENC)
rc |= XMIT_GSO_ENC_V4;
}
}
return rc;
}
/* VXLAN: 4 = 1 (for linear data BD) + 3 (2 for PBD and last BD) */
#define BNX2X_NUM_VXLAN_TSO_WIN_SUB_BDS 4
/* Regular: 3 = 1 (for linear data BD) + 2 (for PBD and last BD) */
#define BNX2X_NUM_TSO_WIN_SUB_BDS 3
#if (MAX_SKB_FRAGS >= MAX_FETCH_BD - BDS_PER_TX_PKT)
/* check if packet requires linearization (packet is too fragmented)
no need to check fragmentation if page size > 8K (there will be no
violation to FW restrictions) */
static int bnx2x_pkt_req_lin(struct bnx2x *bp, struct sk_buff *skb,
u32 xmit_type)
{
int first_bd_sz = 0, num_tso_win_sub = BNX2X_NUM_TSO_WIN_SUB_BDS;
int to_copy = 0, hlen = 0;
if (xmit_type & XMIT_GSO_ENC)
num_tso_win_sub = BNX2X_NUM_VXLAN_TSO_WIN_SUB_BDS;
if (skb_shinfo(skb)->nr_frags >= (MAX_FETCH_BD - num_tso_win_sub)) {
if (xmit_type & XMIT_GSO) {
unsigned short lso_mss = skb_shinfo(skb)->gso_size;
int wnd_size = MAX_FETCH_BD - num_tso_win_sub;
/* Number of windows to check */
int num_wnds = skb_shinfo(skb)->nr_frags - wnd_size;
int wnd_idx = 0;
int frag_idx = 0;
u32 wnd_sum = 0;
/* Headers length */
if (xmit_type & XMIT_GSO_ENC)
hlen = (int)(skb_inner_transport_header(skb) -
skb->data) +
inner_tcp_hdrlen(skb);
else
hlen = (int)(skb_transport_header(skb) -
skb->data) + tcp_hdrlen(skb);
/* Amount of data (w/o headers) on linear part of SKB*/
first_bd_sz = skb_headlen(skb) - hlen;
wnd_sum = first_bd_sz;
/* Calculate the first sum - it's special */
for (frag_idx = 0; frag_idx < wnd_size - 1; frag_idx++)
wnd_sum +=
skb_frag_size(&skb_shinfo(skb)->frags[frag_idx]);
/* If there was data on linear skb data - check it */
if (first_bd_sz > 0) {
if (unlikely(wnd_sum < lso_mss)) {
to_copy = 1;
goto exit_lbl;
}
wnd_sum -= first_bd_sz;
}
/* Others are easier: run through the frag list and
check all windows */
for (wnd_idx = 0; wnd_idx <= num_wnds; wnd_idx++) {
wnd_sum +=
skb_frag_size(&skb_shinfo(skb)->frags[wnd_idx + wnd_size - 1]);
if (unlikely(wnd_sum < lso_mss)) {
to_copy = 1;
break;
}
wnd_sum -=
skb_frag_size(&skb_shinfo(skb)->frags[wnd_idx]);
}
} else {
/* in non-LSO too fragmented packet should always
be linearized */
to_copy = 1;
}
}
exit_lbl:
if (unlikely(to_copy))
DP(NETIF_MSG_TX_QUEUED,
"Linearization IS REQUIRED for %s packet. num_frags %d hlen %d first_bd_sz %d\n",
(xmit_type & XMIT_GSO) ? "LSO" : "non-LSO",
skb_shinfo(skb)->nr_frags, hlen, first_bd_sz);
return to_copy;
}
#endif
/**
* bnx2x_set_pbd_gso - update PBD in GSO case.
*
* @skb: packet skb
* @pbd: parse BD
* @xmit_type: xmit flags
*/
static void bnx2x_set_pbd_gso(struct sk_buff *skb,
struct eth_tx_parse_bd_e1x *pbd,
u32 xmit_type)
{
pbd->lso_mss = cpu_to_le16(skb_shinfo(skb)->gso_size);
pbd->tcp_send_seq = bswab32(tcp_hdr(skb)->seq);
pbd->tcp_flags = pbd_tcp_flags(tcp_hdr(skb));
if (xmit_type & XMIT_GSO_V4) {
pbd->ip_id = bswab16(ip_hdr(skb)->id);
pbd->tcp_pseudo_csum =
bswab16(~csum_tcpudp_magic(ip_hdr(skb)->saddr,
ip_hdr(skb)->daddr,
0, IPPROTO_TCP, 0));
} else {
pbd->tcp_pseudo_csum =
bswab16(~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
0, IPPROTO_TCP, 0));
}
pbd->global_data |=
cpu_to_le16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
}
/**
* bnx2x_set_pbd_csum_enc - update PBD with checksum and return header length
*
* @bp: driver handle
* @skb: packet skb
* @parsing_data: data to be updated
* @xmit_type: xmit flags
*
* 57712/578xx related, when skb has encapsulation
*/
static u8 bnx2x_set_pbd_csum_enc(struct bnx2x *bp, struct sk_buff *skb,
u32 *parsing_data, u32 xmit_type)
{
*parsing_data |=
((((u8 *)skb_inner_transport_header(skb) - skb->data) >> 1) <<
ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W;
if (xmit_type & XMIT_CSUM_TCP) {
*parsing_data |= ((inner_tcp_hdrlen(skb) / 4) <<
ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW;
return skb_inner_transport_header(skb) +
inner_tcp_hdrlen(skb) - skb->data;
}
/* We support checksum offload for TCP and UDP only.
* No need to pass the UDP header length - it's a constant.
*/
return skb_inner_transport_header(skb) +
sizeof(struct udphdr) - skb->data;
}
/**
* bnx2x_set_pbd_csum_e2 - update PBD with checksum and return header length
*
* @bp: driver handle
* @skb: packet skb
* @parsing_data: data to be updated
* @xmit_type: xmit flags
*
* 57712/578xx related
*/
static u8 bnx2x_set_pbd_csum_e2(struct bnx2x *bp, struct sk_buff *skb,
u32 *parsing_data, u32 xmit_type)
{
*parsing_data |=
((((u8 *)skb_transport_header(skb) - skb->data) >> 1) <<
ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W;
if (xmit_type & XMIT_CSUM_TCP) {
*parsing_data |= ((tcp_hdrlen(skb) / 4) <<
ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW;
return skb_transport_header(skb) + tcp_hdrlen(skb) - skb->data;
}
/* We support checksum offload for TCP and UDP only.
* No need to pass the UDP header length - it's a constant.
*/
return skb_transport_header(skb) + sizeof(struct udphdr) - skb->data;
}
/* set FW indication according to inner or outer protocols if tunneled */
static void bnx2x_set_sbd_csum(struct bnx2x *bp, struct sk_buff *skb,
struct eth_tx_start_bd *tx_start_bd,
u32 xmit_type)
{
tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
if (xmit_type & (XMIT_CSUM_ENC_V6 | XMIT_CSUM_V6))
tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IPV6;
if (!(xmit_type & XMIT_CSUM_TCP))
tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IS_UDP;
}
/**
* bnx2x_set_pbd_csum - update PBD with checksum and return header length
*
* @bp: driver handle
* @skb: packet skb
* @pbd: parse BD to be updated
* @xmit_type: xmit flags
*/
static u8 bnx2x_set_pbd_csum(struct bnx2x *bp, struct sk_buff *skb,
struct eth_tx_parse_bd_e1x *pbd,
u32 xmit_type)
{
u8 hlen = (skb_network_header(skb) - skb->data) >> 1;
/* for now NS flag is not used in Linux */
pbd->global_data =
cpu_to_le16(hlen |
((skb->protocol == cpu_to_be16(ETH_P_8021Q)) <<
ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
pbd->ip_hlen_w = (skb_transport_header(skb) -
skb_network_header(skb)) >> 1;
hlen += pbd->ip_hlen_w;
/* We support checksum offload for TCP and UDP only */
if (xmit_type & XMIT_CSUM_TCP)
hlen += tcp_hdrlen(skb) / 2;
else
hlen += sizeof(struct udphdr) / 2;
pbd->total_hlen_w = cpu_to_le16(hlen);
hlen = hlen*2;
if (xmit_type & XMIT_CSUM_TCP) {
pbd->tcp_pseudo_csum = bswab16(tcp_hdr(skb)->check);
} else {
s8 fix = SKB_CS_OFF(skb); /* signed! */
DP(NETIF_MSG_TX_QUEUED,
"hlen %d fix %d csum before fix %x\n",
le16_to_cpu(pbd->total_hlen_w), fix, SKB_CS(skb));
/* HW bug: fixup the CSUM */
pbd->tcp_pseudo_csum =
bnx2x_csum_fix(skb_transport_header(skb),
SKB_CS(skb), fix);
DP(NETIF_MSG_TX_QUEUED, "csum after fix %x\n",
pbd->tcp_pseudo_csum);
}
return hlen;
}
static void bnx2x_update_pbds_gso_enc(struct sk_buff *skb,
struct eth_tx_parse_bd_e2 *pbd_e2,
struct eth_tx_parse_2nd_bd *pbd2,
u16 *global_data,
u32 xmit_type)
{
u16 hlen_w = 0;
u8 outerip_off, outerip_len = 0;
/* from outer IP to transport */
hlen_w = (skb_inner_transport_header(skb) -
skb_network_header(skb)) >> 1;
/* transport len */
hlen_w += inner_tcp_hdrlen(skb) >> 1;
pbd2->fw_ip_hdr_to_payload_w = hlen_w;
/* outer IP header info */
if (xmit_type & XMIT_CSUM_V4) {
struct iphdr *iph = ip_hdr(skb);
u32 csum = (__force u32)(~iph->check) -
(__force u32)iph->tot_len -
(__force u32)iph->frag_off;
outerip_len = iph->ihl << 1;
pbd2->fw_ip_csum_wo_len_flags_frag =
bswab16(csum_fold((__force __wsum)csum));
} else {
pbd2->fw_ip_hdr_to_payload_w =
hlen_w - ((sizeof(struct ipv6hdr)) >> 1);
pbd_e2->data.tunnel_data.flags |=
ETH_TUNNEL_DATA_IPV6_OUTER;
}
pbd2->tcp_send_seq = bswab32(inner_tcp_hdr(skb)->seq);
pbd2->tcp_flags = pbd_tcp_flags(inner_tcp_hdr(skb));
/* inner IP header info */
if (xmit_type & XMIT_CSUM_ENC_V4) {
pbd2->hw_ip_id = bswab16(inner_ip_hdr(skb)->id);
pbd_e2->data.tunnel_data.pseudo_csum =
bswab16(~csum_tcpudp_magic(
inner_ip_hdr(skb)->saddr,
inner_ip_hdr(skb)->daddr,
0, IPPROTO_TCP, 0));
} else {
pbd_e2->data.tunnel_data.pseudo_csum =
bswab16(~csum_ipv6_magic(
&inner_ipv6_hdr(skb)->saddr,
&inner_ipv6_hdr(skb)->daddr,
0, IPPROTO_TCP, 0));
}
outerip_off = (skb_network_header(skb) - skb->data) >> 1;
*global_data |=
outerip_off |
(outerip_len <<
ETH_TX_PARSE_2ND_BD_IP_HDR_LEN_OUTER_W_SHIFT) |
((skb->protocol == cpu_to_be16(ETH_P_8021Q)) <<
ETH_TX_PARSE_2ND_BD_LLC_SNAP_EN_SHIFT);
if (ip_hdr(skb)->protocol == IPPROTO_UDP) {
SET_FLAG(*global_data, ETH_TX_PARSE_2ND_BD_TUNNEL_UDP_EXIST, 1);
pbd2->tunnel_udp_hdr_start_w = skb_transport_offset(skb) >> 1;
}
}
static inline void bnx2x_set_ipv6_ext_e2(struct sk_buff *skb, u32 *parsing_data,
u32 xmit_type)
{
struct ipv6hdr *ipv6;
if (!(xmit_type & (XMIT_GSO_ENC_V6 | XMIT_GSO_V6)))
return;
if (xmit_type & XMIT_GSO_ENC_V6)
ipv6 = inner_ipv6_hdr(skb);
else /* XMIT_GSO_V6 */
ipv6 = ipv6_hdr(skb);
if (ipv6->nexthdr == NEXTHDR_IPV6)
*parsing_data |= ETH_TX_PARSE_BD_E2_IPV6_WITH_EXT_HDR;
}
/* called with netif_tx_lock
* bnx2x_tx_int() runs without netif_tx_lock unless it needs to call
* netif_wake_queue()
*/
netdev_tx_t bnx2x_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
struct netdev_queue *txq;
struct bnx2x_fp_txdata *txdata;
struct sw_tx_bd *tx_buf;
struct eth_tx_start_bd *tx_start_bd, *first_bd;
struct eth_tx_bd *tx_data_bd, *total_pkt_bd = NULL;
struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
struct eth_tx_parse_2nd_bd *pbd2 = NULL;
u32 pbd_e2_parsing_data = 0;
u16 pkt_prod, bd_prod;
int nbd, txq_index;
dma_addr_t mapping;
u32 xmit_type = bnx2x_xmit_type(bp, skb);
int i;
u8 hlen = 0;
__le16 pkt_size = 0;
struct ethhdr *eth;
u8 mac_type = UNICAST_ADDRESS;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return NETDEV_TX_BUSY;
#endif
txq_index = skb_get_queue_mapping(skb);
txq = netdev_get_tx_queue(dev, txq_index);
BUG_ON(txq_index >= MAX_ETH_TXQ_IDX(bp) + (CNIC_LOADED(bp) ? 1 : 0));
txdata = &bp->bnx2x_txq[txq_index];
/* enable this debug print to view the transmission queue being used
DP(NETIF_MSG_TX_QUEUED, "indices: txq %d, fp %d, txdata %d\n",
txq_index, fp_index, txdata_index); */
/* enable this debug print to view the transmission details
DP(NETIF_MSG_TX_QUEUED,
"transmitting packet cid %d fp index %d txdata_index %d tx_data ptr %p fp pointer %p\n",
txdata->cid, fp_index, txdata_index, txdata, fp); */
if (unlikely(bnx2x_tx_avail(bp, txdata) <
skb_shinfo(skb)->nr_frags +
BDS_PER_TX_PKT +
NEXT_CNT_PER_TX_PKT(MAX_BDS_PER_TX_PKT))) {
/* Handle special storage cases separately */
if (txdata->tx_ring_size == 0) {
struct bnx2x_eth_q_stats *q_stats =
bnx2x_fp_qstats(bp, txdata->parent_fp);
q_stats->driver_filtered_tx_pkt++;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
bnx2x_fp_qstats(bp, txdata->parent_fp)->driver_xoff++;
netif_tx_stop_queue(txq);
BNX2X_ERR("BUG! Tx ring full when queue awake!\n");
return NETDEV_TX_BUSY;
}
DP(NETIF_MSG_TX_QUEUED,
"queue[%d]: SKB: summed %x protocol %x protocol(%x,%x) gso type %x xmit_type %x len %d\n",
txq_index, skb->ip_summed, skb->protocol, ipv6_hdr(skb)->nexthdr,
ip_hdr(skb)->protocol, skb_shinfo(skb)->gso_type, xmit_type,
skb->len);
eth = (struct ethhdr *)skb->data;
/* set flag according to packet type (UNICAST_ADDRESS is default)*/
if (unlikely(is_multicast_ether_addr(eth->h_dest))) {
if (is_broadcast_ether_addr(eth->h_dest))
mac_type = BROADCAST_ADDRESS;
else
mac_type = MULTICAST_ADDRESS;
}
#if (MAX_SKB_FRAGS >= MAX_FETCH_BD - BDS_PER_TX_PKT)
/* First, check if we need to linearize the skb (due to FW
restrictions). No need to check fragmentation if page size > 8K
(there will be no violation to FW restrictions) */
if (bnx2x_pkt_req_lin(bp, skb, xmit_type)) {
/* Statistics of linearization */
bp->lin_cnt++;
if (skb_linearize(skb) != 0) {
DP(NETIF_MSG_TX_QUEUED,
"SKB linearization failed - silently dropping this SKB\n");
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
}
#endif
/* Map skb linear data for DMA */
mapping = dma_map_single(&bp->pdev->dev, skb->data,
skb_headlen(skb), DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(&bp->pdev->dev, mapping))) {
DP(NETIF_MSG_TX_QUEUED,
"SKB mapping failed - silently dropping this SKB\n");
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/*
Please read carefully. First we use one BD which we mark as start,
then we have a parsing info BD (used for TSO or xsum),
and only then we have the rest of the TSO BDs.
(don't forget to mark the last one as last,
and to unmap only AFTER you write to the BD ...)
And above all, all pdb sizes are in words - NOT DWORDS!
*/
/* get current pkt produced now - advance it just before sending packet
* since mapping of pages may fail and cause packet to be dropped
*/
pkt_prod = txdata->tx_pkt_prod;
bd_prod = TX_BD(txdata->tx_bd_prod);
/* get a tx_buf and first BD
* tx_start_bd may be changed during SPLIT,
* but first_bd will always stay first
*/
tx_buf = &txdata->tx_buf_ring[TX_BD(pkt_prod)];
tx_start_bd = &txdata->tx_desc_ring[bd_prod].start_bd;
first_bd = tx_start_bd;
tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP)) {
if (!(bp->flags & TX_TIMESTAMPING_EN)) {
BNX2X_ERR("Tx timestamping was not enabled, this packet will not be timestamped\n");
} else if (bp->ptp_tx_skb) {
BNX2X_ERR("The device supports only a single outstanding packet to timestamp, this packet will not be timestamped\n");
} else {
skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
/* schedule check for Tx timestamp */
bp->ptp_tx_skb = skb_get(skb);
bp->ptp_tx_start = jiffies;
schedule_work(&bp->ptp_task);
}
}
/* header nbd: indirectly zero other flags! */
tx_start_bd->general_data = 1 << ETH_TX_START_BD_HDR_NBDS_SHIFT;
/* remember the first BD of the packet */
tx_buf->first_bd = txdata->tx_bd_prod;
tx_buf->skb = skb;
tx_buf->flags = 0;
DP(NETIF_MSG_TX_QUEUED,
"sending pkt %u @%p next_idx %u bd %u @%p\n",
pkt_prod, tx_buf, txdata->tx_pkt_prod, bd_prod, tx_start_bd);
if (skb_vlan_tag_present(skb)) {
tx_start_bd->vlan_or_ethertype =
cpu_to_le16(skb_vlan_tag_get(skb));
tx_start_bd->bd_flags.as_bitfield |=
(X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
} else {
/* when transmitting in a vf, start bd must hold the ethertype
* for fw to enforce it
*/
#ifndef BNX2X_STOP_ON_ERROR
if (IS_VF(bp))
#endif
tx_start_bd->vlan_or_ethertype =
cpu_to_le16(ntohs(eth->h_proto));
#ifndef BNX2X_STOP_ON_ERROR
else
/* used by FW for packet accounting */
tx_start_bd->vlan_or_ethertype = cpu_to_le16(pkt_prod);
#endif
}
nbd = 2; /* start_bd + pbd + frags (updated when pages are mapped) */
/* turn on parsing and get a BD */
bd_prod = TX_BD(NEXT_TX_IDX(bd_prod));
if (xmit_type & XMIT_CSUM)
bnx2x_set_sbd_csum(bp, skb, tx_start_bd, xmit_type);
if (!CHIP_IS_E1x(bp)) {
pbd_e2 = &txdata->tx_desc_ring[bd_prod].parse_bd_e2;
memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
if (xmit_type & XMIT_CSUM_ENC) {
u16 global_data = 0;
/* Set PBD in enc checksum offload case */
hlen = bnx2x_set_pbd_csum_enc(bp, skb,
&pbd_e2_parsing_data,
xmit_type);
/* turn on 2nd parsing and get a BD */
bd_prod = TX_BD(NEXT_TX_IDX(bd_prod));
pbd2 = &txdata->tx_desc_ring[bd_prod].parse_2nd_bd;
memset(pbd2, 0, sizeof(*pbd2));
pbd_e2->data.tunnel_data.ip_hdr_start_inner_w =
(skb_inner_network_header(skb) -
skb->data) >> 1;
if (xmit_type & XMIT_GSO_ENC)
bnx2x_update_pbds_gso_enc(skb, pbd_e2, pbd2,
&global_data,
xmit_type);
pbd2->global_data = cpu_to_le16(global_data);
/* add addition parse BD indication to start BD */
SET_FLAG(tx_start_bd->general_data,
ETH_TX_START_BD_PARSE_NBDS, 1);
/* set encapsulation flag in start BD */
SET_FLAG(tx_start_bd->general_data,
ETH_TX_START_BD_TUNNEL_EXIST, 1);
tx_buf->flags |= BNX2X_HAS_SECOND_PBD;
nbd++;
} else if (xmit_type & XMIT_CSUM) {
/* Set PBD in checksum offload case w/o encapsulation */
hlen = bnx2x_set_pbd_csum_e2(bp, skb,
&pbd_e2_parsing_data,
xmit_type);
}
bnx2x_set_ipv6_ext_e2(skb, &pbd_e2_parsing_data, xmit_type);
/* Add the macs to the parsing BD if this is a vf or if
* Tx Switching is enabled.
*/
if (IS_VF(bp)) {
/* override GRE parameters in BD */
bnx2x_set_fw_mac_addr(&pbd_e2->data.mac_addr.src_hi,
&pbd_e2->data.mac_addr.src_mid,
&pbd_e2->data.mac_addr.src_lo,
eth->h_source);
bnx2x_set_fw_mac_addr(&pbd_e2->data.mac_addr.dst_hi,
&pbd_e2->data.mac_addr.dst_mid,
&pbd_e2->data.mac_addr.dst_lo,
eth->h_dest);
} else {
if (bp->flags & TX_SWITCHING)
bnx2x_set_fw_mac_addr(
&pbd_e2->data.mac_addr.dst_hi,
&pbd_e2->data.mac_addr.dst_mid,
&pbd_e2->data.mac_addr.dst_lo,
eth->h_dest);
#ifdef BNX2X_STOP_ON_ERROR
/* Enforce security is always set in Stop on Error -
* source mac should be present in the parsing BD
*/
bnx2x_set_fw_mac_addr(&pbd_e2->data.mac_addr.src_hi,
&pbd_e2->data.mac_addr.src_mid,
&pbd_e2->data.mac_addr.src_lo,
eth->h_source);
#endif
}
SET_FLAG(pbd_e2_parsing_data,
ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE, mac_type);
} else {
u16 global_data = 0;
pbd_e1x = &txdata->tx_desc_ring[bd_prod].parse_bd_e1x;
memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
/* Set PBD in checksum offload case */
if (xmit_type & XMIT_CSUM)
hlen = bnx2x_set_pbd_csum(bp, skb, pbd_e1x, xmit_type);
SET_FLAG(global_data,
ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
pbd_e1x->global_data |= cpu_to_le16(global_data);
}
/* Setup the data pointer of the first BD of the packet */
tx_start_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
tx_start_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
tx_start_bd->nbytes = cpu_to_le16(skb_headlen(skb));
pkt_size = tx_start_bd->nbytes;
DP(NETIF_MSG_TX_QUEUED,
"first bd @%p addr (%x:%x) nbytes %d flags %x vlan %x\n",
tx_start_bd, tx_start_bd->addr_hi, tx_start_bd->addr_lo,
le16_to_cpu(tx_start_bd->nbytes),
tx_start_bd->bd_flags.as_bitfield,
le16_to_cpu(tx_start_bd->vlan_or_ethertype));
if (xmit_type & XMIT_GSO) {
DP(NETIF_MSG_TX_QUEUED,
"TSO packet len %d hlen %d total len %d tso size %d\n",
skb->len, hlen, skb_headlen(skb),
skb_shinfo(skb)->gso_size);
tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
if (unlikely(skb_headlen(skb) > hlen)) {
nbd++;
bd_prod = bnx2x_tx_split(bp, txdata, tx_buf,
&tx_start_bd, hlen,
bd_prod);
}
if (!CHIP_IS_E1x(bp))
pbd_e2_parsing_data |=
(skb_shinfo(skb)->gso_size <<
ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
ETH_TX_PARSE_BD_E2_LSO_MSS;
else
bnx2x_set_pbd_gso(skb, pbd_e1x, xmit_type);
}
/* Set the PBD's parsing_data field if not zero
* (for the chips newer than 57711).
*/
if (pbd_e2_parsing_data)
pbd_e2->parsing_data = cpu_to_le32(pbd_e2_parsing_data);
tx_data_bd = (struct eth_tx_bd *)tx_start_bd;
/* Handle fragmented skb */
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
mapping = skb_frag_dma_map(&bp->pdev->dev, frag, 0,
skb_frag_size(frag), DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(&bp->pdev->dev, mapping))) {
unsigned int pkts_compl = 0, bytes_compl = 0;
DP(NETIF_MSG_TX_QUEUED,
"Unable to map page - dropping packet...\n");
/* we need unmap all buffers already mapped
* for this SKB;
* first_bd->nbd need to be properly updated
* before call to bnx2x_free_tx_pkt
*/
first_bd->nbd = cpu_to_le16(nbd);
bnx2x_free_tx_pkt(bp, txdata,
TX_BD(txdata->tx_pkt_prod),
&pkts_compl, &bytes_compl);
return NETDEV_TX_OK;
}
bd_prod = TX_BD(NEXT_TX_IDX(bd_prod));
tx_data_bd = &txdata->tx_desc_ring[bd_prod].reg_bd;
if (total_pkt_bd == NULL)
total_pkt_bd = &txdata->tx_desc_ring[bd_prod].reg_bd;
tx_data_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
tx_data_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
tx_data_bd->nbytes = cpu_to_le16(skb_frag_size(frag));
le16_add_cpu(&pkt_size, skb_frag_size(frag));
nbd++;
DP(NETIF_MSG_TX_QUEUED,
"frag %d bd @%p addr (%x:%x) nbytes %d\n",
i, tx_data_bd, tx_data_bd->addr_hi, tx_data_bd->addr_lo,
le16_to_cpu(tx_data_bd->nbytes));
}
DP(NETIF_MSG_TX_QUEUED, "last bd @%p\n", tx_data_bd);
/* update with actual num BDs */
first_bd->nbd = cpu_to_le16(nbd);
bd_prod = TX_BD(NEXT_TX_IDX(bd_prod));
/* now send a tx doorbell, counting the next BD
* if the packet contains or ends with it
*/
if (TX_BD_POFF(bd_prod) < nbd)
nbd++;
/* total_pkt_bytes should be set on the first data BD if
* it's not an LSO packet and there is more than one
* data BD. In this case pkt_size is limited by an MTU value.
* However we prefer to set it for an LSO packet (while we don't
* have to) in order to save some CPU cycles in a none-LSO
* case, when we much more care about them.
*/
if (total_pkt_bd != NULL)
total_pkt_bd->total_pkt_bytes = pkt_size;
if (pbd_e1x)
DP(NETIF_MSG_TX_QUEUED,
"PBD (E1X) @%p ip_data %x ip_hlen %u ip_id %u lso_mss %u tcp_flags %x xsum %x seq %u hlen %u\n",
pbd_e1x, pbd_e1x->global_data, pbd_e1x->ip_hlen_w,
pbd_e1x->ip_id, pbd_e1x->lso_mss, pbd_e1x->tcp_flags,
pbd_e1x->tcp_pseudo_csum, pbd_e1x->tcp_send_seq,
le16_to_cpu(pbd_e1x->total_hlen_w));
if (pbd_e2)
DP(NETIF_MSG_TX_QUEUED,
"PBD (E2) @%p dst %x %x %x src %x %x %x parsing_data %x\n",
pbd_e2,
pbd_e2->data.mac_addr.dst_hi,
pbd_e2->data.mac_addr.dst_mid,
pbd_e2->data.mac_addr.dst_lo,
pbd_e2->data.mac_addr.src_hi,
pbd_e2->data.mac_addr.src_mid,
pbd_e2->data.mac_addr.src_lo,
pbd_e2->parsing_data);
DP(NETIF_MSG_TX_QUEUED, "doorbell: nbd %d bd %u\n", nbd, bd_prod);
netdev_tx_sent_queue(txq, skb->len);
skb_tx_timestamp(skb);
txdata->tx_pkt_prod++;
/*
* Make sure that the BD data is updated before updating the producer
* since FW might read the BD right after the producer is updated.
* This is only applicable for weak-ordered memory model archs such
* as IA-64. The following barrier is also mandatory since FW will
* assumes packets must have BDs.
*/
wmb();
txdata->tx_db.data.prod += nbd;
barrier();
DOORBELL(bp, txdata->cid, txdata->tx_db.raw);
mmiowb();
txdata->tx_bd_prod += nbd;
if (unlikely(bnx2x_tx_avail(bp, txdata) < MAX_DESC_PER_TX_PKT)) {
netif_tx_stop_queue(txq);
/* paired memory barrier is in bnx2x_tx_int(), we have to keep
* ordering of set_bit() in netif_tx_stop_queue() and read of
* fp->bd_tx_cons */
smp_mb();
bnx2x_fp_qstats(bp, txdata->parent_fp)->driver_xoff++;
if (bnx2x_tx_avail(bp, txdata) >= MAX_DESC_PER_TX_PKT)
netif_tx_wake_queue(txq);
}
txdata->tx_pkt++;
return NETDEV_TX_OK;
}
void bnx2x_get_c2s_mapping(struct bnx2x *bp, u8 *c2s_map, u8 *c2s_default)
{
int mfw_vn = BP_FW_MB_IDX(bp);
u32 tmp;
/* If the shmem shouldn't affect configuration, reflect */
if (!IS_MF_BD(bp)) {
int i;
for (i = 0; i < BNX2X_MAX_PRIORITY; i++)
c2s_map[i] = i;
*c2s_default = 0;
return;
}
tmp = SHMEM2_RD(bp, c2s_pcp_map_lower[mfw_vn]);
tmp = (__force u32)be32_to_cpu((__force __be32)tmp);
c2s_map[0] = tmp & 0xff;
c2s_map[1] = (tmp >> 8) & 0xff;
c2s_map[2] = (tmp >> 16) & 0xff;
c2s_map[3] = (tmp >> 24) & 0xff;
tmp = SHMEM2_RD(bp, c2s_pcp_map_upper[mfw_vn]);
tmp = (__force u32)be32_to_cpu((__force __be32)tmp);
c2s_map[4] = tmp & 0xff;
c2s_map[5] = (tmp >> 8) & 0xff;
c2s_map[6] = (tmp >> 16) & 0xff;
c2s_map[7] = (tmp >> 24) & 0xff;
tmp = SHMEM2_RD(bp, c2s_pcp_map_default[mfw_vn]);
tmp = (__force u32)be32_to_cpu((__force __be32)tmp);
*c2s_default = (tmp >> (8 * mfw_vn)) & 0xff;
}
/**
* bnx2x_setup_tc - routine to configure net_device for multi tc
*
* @netdev: net device to configure
* @tc: number of traffic classes to enable
*
* callback connected to the ndo_setup_tc function pointer
*/
int bnx2x_setup_tc(struct net_device *dev, u8 num_tc)
{
struct bnx2x *bp = netdev_priv(dev);
u8 c2s_map[BNX2X_MAX_PRIORITY], c2s_def;
int cos, prio, count, offset;
/* setup tc must be called under rtnl lock */
ASSERT_RTNL();
/* no traffic classes requested. Aborting */
if (!num_tc) {
netdev_reset_tc(dev);
return 0;
}
/* requested to support too many traffic classes */
if (num_tc > bp->max_cos) {
BNX2X_ERR("support for too many traffic classes requested: %d. Max supported is %d\n",
num_tc, bp->max_cos);
return -EINVAL;
}
/* declare amount of supported traffic classes */
if (netdev_set_num_tc(dev, num_tc)) {
BNX2X_ERR("failed to declare %d traffic classes\n", num_tc);
return -EINVAL;
}
bnx2x_get_c2s_mapping(bp, c2s_map, &c2s_def);
/* configure priority to traffic class mapping */
for (prio = 0; prio < BNX2X_MAX_PRIORITY; prio++) {
int outer_prio = c2s_map[prio];
netdev_set_prio_tc_map(dev, prio, bp->prio_to_cos[outer_prio]);
DP(BNX2X_MSG_SP | NETIF_MSG_IFUP,
"mapping priority %d to tc %d\n",
outer_prio, bp->prio_to_cos[outer_prio]);
}
/* Use this configuration to differentiate tc0 from other COSes
This can be used for ets or pfc, and save the effort of setting
up a multio class queue disc or negotiating DCBX with a switch
netdev_set_prio_tc_map(dev, 0, 0);
DP(BNX2X_MSG_SP, "mapping priority %d to tc %d\n", 0, 0);
for (prio = 1; prio < 16; prio++) {
netdev_set_prio_tc_map(dev, prio, 1);
DP(BNX2X_MSG_SP, "mapping priority %d to tc %d\n", prio, 1);
} */
/* configure traffic class to transmission queue mapping */
for (cos = 0; cos < bp->max_cos; cos++) {
count = BNX2X_NUM_ETH_QUEUES(bp);
offset = cos * BNX2X_NUM_NON_CNIC_QUEUES(bp);
netdev_set_tc_queue(dev, cos, count, offset);
DP(BNX2X_MSG_SP | NETIF_MSG_IFUP,
"mapping tc %d to offset %d count %d\n",
cos, offset, count);
}
return 0;
}
int __bnx2x_setup_tc(struct net_device *dev, u32 handle, __be16 proto,
struct tc_to_netdev *tc)
{
if (tc->type != TC_SETUP_MQPRIO)
return -EINVAL;
tc->mqprio->hw = TC_MQPRIO_HW_OFFLOAD_TCS;
return bnx2x_setup_tc(dev, tc->mqprio->num_tc);
}
/* called with rtnl_lock */
int bnx2x_change_mac_addr(struct net_device *dev, void *p)
{
struct sockaddr *addr = p;
struct bnx2x *bp = netdev_priv(dev);
int rc = 0;
if (!is_valid_ether_addr(addr->sa_data)) {
BNX2X_ERR("Requested MAC address is not valid\n");
return -EINVAL;
}
if (IS_MF_STORAGE_ONLY(bp)) {
BNX2X_ERR("Can't change address on STORAGE ONLY function\n");
return -EINVAL;
}
if (netif_running(dev)) {
rc = bnx2x_set_eth_mac(bp, false);
if (rc)
return rc;
}
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
if (netif_running(dev))
rc = bnx2x_set_eth_mac(bp, true);
if (IS_PF(bp) && SHMEM2_HAS(bp, curr_cfg))
SHMEM2_WR(bp, curr_cfg, CURR_CFG_MET_OS);
return rc;
}
static void bnx2x_free_fp_mem_at(struct bnx2x *bp, int fp_index)
{
union host_hc_status_block *sb = &bnx2x_fp(bp, fp_index, status_blk);
struct bnx2x_fastpath *fp = &bp->fp[fp_index];
u8 cos;
/* Common */
if (IS_FCOE_IDX(fp_index)) {
memset(sb, 0, sizeof(union host_hc_status_block));
fp->status_blk_mapping = 0;
} else {
/* status blocks */
if (!CHIP_IS_E1x(bp))
BNX2X_PCI_FREE(sb->e2_sb,
bnx2x_fp(bp, fp_index,
status_blk_mapping),
sizeof(struct host_hc_status_block_e2));
else
BNX2X_PCI_FREE(sb->e1x_sb,
bnx2x_fp(bp, fp_index,
status_blk_mapping),
sizeof(struct host_hc_status_block_e1x));
}
/* Rx */
if (!skip_rx_queue(bp, fp_index)) {
bnx2x_free_rx_bds(fp);
/* fastpath rx rings: rx_buf rx_desc rx_comp */
BNX2X_FREE(bnx2x_fp(bp, fp_index, rx_buf_ring));
BNX2X_PCI_FREE(bnx2x_fp(bp, fp_index, rx_desc_ring),
bnx2x_fp(bp, fp_index, rx_desc_mapping),
sizeof(struct eth_rx_bd) * NUM_RX_BD);
BNX2X_PCI_FREE(bnx2x_fp(bp, fp_index, rx_comp_ring),
bnx2x_fp(bp, fp_index, rx_comp_mapping),
sizeof(struct eth_fast_path_rx_cqe) *
NUM_RCQ_BD);
/* SGE ring */
BNX2X_FREE(bnx2x_fp(bp, fp_index, rx_page_ring));
BNX2X_PCI_FREE(bnx2x_fp(bp, fp_index, rx_sge_ring),
bnx2x_fp(bp, fp_index, rx_sge_mapping),
BCM_PAGE_SIZE * NUM_RX_SGE_PAGES);
}
/* Tx */
if (!skip_tx_queue(bp, fp_index)) {
/* fastpath tx rings: tx_buf tx_desc */
for_each_cos_in_tx_queue(fp, cos) {
struct bnx2x_fp_txdata *txdata = fp->txdata_ptr[cos];
DP(NETIF_MSG_IFDOWN,
"freeing tx memory of fp %d cos %d cid %d\n",
fp_index, cos, txdata->cid);
BNX2X_FREE(txdata->tx_buf_ring);
BNX2X_PCI_FREE(txdata->tx_desc_ring,
txdata->tx_desc_mapping,
sizeof(union eth_tx_bd_types) * NUM_TX_BD);
}
}
/* end of fastpath */
}
static void bnx2x_free_fp_mem_cnic(struct bnx2x *bp)
{
int i;
for_each_cnic_queue(bp, i)
bnx2x_free_fp_mem_at(bp, i);
}
void bnx2x_free_fp_mem(struct bnx2x *bp)
{
int i;
for_each_eth_queue(bp, i)
bnx2x_free_fp_mem_at(bp, i);
}
static void set_sb_shortcuts(struct bnx2x *bp, int index)
{
union host_hc_status_block status_blk = bnx2x_fp(bp, index, status_blk);
if (!CHIP_IS_E1x(bp)) {
bnx2x_fp(bp, index, sb_index_values) =
(__le16 *)status_blk.e2_sb->sb.index_values;
bnx2x_fp(bp, index, sb_running_index) =
(__le16 *)status_blk.e2_sb->sb.running_index;
} else {
bnx2x_fp(bp, index, sb_index_values) =
(__le16 *)status_blk.e1x_sb->sb.index_values;
bnx2x_fp(bp, index, sb_running_index) =
(__le16 *)status_blk.e1x_sb->sb.running_index;
}
}
/* Returns the number of actually allocated BDs */
static int bnx2x_alloc_rx_bds(struct bnx2x_fastpath *fp,
int rx_ring_size)
{
struct bnx2x *bp = fp->bp;
u16 ring_prod, cqe_ring_prod;
int i, failure_cnt = 0;
fp->rx_comp_cons = 0;
cqe_ring_prod = ring_prod = 0;
/* This routine is called only during fo init so
* fp->eth_q_stats.rx_skb_alloc_failed = 0
*/
for (i = 0; i < rx_ring_size; i++) {
if (bnx2x_alloc_rx_data(bp, fp, ring_prod, GFP_KERNEL) < 0) {
failure_cnt++;
continue;
}
ring_prod = NEXT_RX_IDX(ring_prod);
cqe_ring_prod = NEXT_RCQ_IDX(cqe_ring_prod);
WARN_ON(ring_prod <= (i - failure_cnt));
}
if (failure_cnt)
BNX2X_ERR("was only able to allocate %d rx skbs on queue[%d]\n",
i - failure_cnt, fp->index);
fp->rx_bd_prod = ring_prod;
/* Limit the CQE producer by the CQE ring size */
fp->rx_comp_prod = min_t(u16, NUM_RCQ_RINGS*RCQ_DESC_CNT,
cqe_ring_prod);
bnx2x_fp_stats(bp, fp)->eth_q_stats.rx_skb_alloc_failed += failure_cnt;
return i - failure_cnt;
}
static void bnx2x_set_next_page_rx_cq(struct bnx2x_fastpath *fp)
{
int i;
for (i = 1; i <= NUM_RCQ_RINGS; i++) {
struct eth_rx_cqe_next_page *nextpg;
nextpg = (struct eth_rx_cqe_next_page *)
&fp->rx_comp_ring[RCQ_DESC_CNT * i - 1];
nextpg->addr_hi =
cpu_to_le32(U64_HI(fp->rx_comp_mapping +
BCM_PAGE_SIZE*(i % NUM_RCQ_RINGS)));
nextpg->addr_lo =
cpu_to_le32(U64_LO(fp->rx_comp_mapping +
BCM_PAGE_SIZE*(i % NUM_RCQ_RINGS)));
}
}
static int bnx2x_alloc_fp_mem_at(struct bnx2x *bp, int index)
{
union host_hc_status_block *sb;
struct bnx2x_fastpath *fp = &bp->fp[index];
int ring_size = 0;
u8 cos;
int rx_ring_size = 0;
if (!bp->rx_ring_size && IS_MF_STORAGE_ONLY(bp)) {
rx_ring_size = MIN_RX_SIZE_NONTPA;
bp->rx_ring_size = rx_ring_size;
} else if (!bp->rx_ring_size) {
rx_ring_size = MAX_RX_AVAIL/BNX2X_NUM_RX_QUEUES(bp);
if (CHIP_IS_E3(bp)) {
u32 cfg = SHMEM_RD(bp,
dev_info.port_hw_config[BP_PORT(bp)].
default_cfg);
/* Decrease ring size for 1G functions */
if ((cfg & PORT_HW_CFG_NET_SERDES_IF_MASK) ==
PORT_HW_CFG_NET_SERDES_IF_SGMII)
rx_ring_size /= 10;
}
/* allocate at least number of buffers required by FW */
rx_ring_size = max_t(int, bp->disable_tpa ? MIN_RX_SIZE_NONTPA :
MIN_RX_SIZE_TPA, rx_ring_size);
bp->rx_ring_size = rx_ring_size;
} else /* if rx_ring_size specified - use it */
rx_ring_size = bp->rx_ring_size;
DP(BNX2X_MSG_SP, "calculated rx_ring_size %d\n", rx_ring_size);
/* Common */
sb = &bnx2x_fp(bp, index, status_blk);
if (!IS_FCOE_IDX(index)) {
/* status blocks */
if (!CHIP_IS_E1x(bp)) {
sb->e2_sb = BNX2X_PCI_ALLOC(&bnx2x_fp(bp, index, status_blk_mapping),
sizeof(struct host_hc_status_block_e2));
if (!sb->e2_sb)
goto alloc_mem_err;
} else {
sb->e1x_sb = BNX2X_PCI_ALLOC(&bnx2x_fp(bp, index, status_blk_mapping),
sizeof(struct host_hc_status_block_e1x));
if (!sb->e1x_sb)
goto alloc_mem_err;
}
}
/* FCoE Queue uses Default SB and doesn't ACK the SB, thus no need to
* set shortcuts for it.
*/
if (!IS_FCOE_IDX(index))
set_sb_shortcuts(bp, index);
/* Tx */
if (!skip_tx_queue(bp, index)) {
/* fastpath tx rings: tx_buf tx_desc */
for_each_cos_in_tx_queue(fp, cos) {
struct bnx2x_fp_txdata *txdata = fp->txdata_ptr[cos];
DP(NETIF_MSG_IFUP,
"allocating tx memory of fp %d cos %d\n",
index, cos);
txdata->tx_buf_ring = kcalloc(NUM_TX_BD,
sizeof(struct sw_tx_bd),
GFP_KERNEL);
if (!txdata->tx_buf_ring)
goto alloc_mem_err;
txdata->tx_desc_ring = BNX2X_PCI_ALLOC(&txdata->tx_desc_mapping,
sizeof(union eth_tx_bd_types) * NUM_TX_BD);
if (!txdata->tx_desc_ring)
goto alloc_mem_err;
}
}
/* Rx */
if (!skip_rx_queue(bp, index)) {
/* fastpath rx rings: rx_buf rx_desc rx_comp */
bnx2x_fp(bp, index, rx_buf_ring) =
kcalloc(NUM_RX_BD, sizeof(struct sw_rx_bd), GFP_KERNEL);
if (!bnx2x_fp(bp, index, rx_buf_ring))
goto alloc_mem_err;
bnx2x_fp(bp, index, rx_desc_ring) =
BNX2X_PCI_ALLOC(&bnx2x_fp(bp, index, rx_desc_mapping),
sizeof(struct eth_rx_bd) * NUM_RX_BD);
if (!bnx2x_fp(bp, index, rx_desc_ring))
goto alloc_mem_err;
/* Seed all CQEs by 1s */
bnx2x_fp(bp, index, rx_comp_ring) =
BNX2X_PCI_FALLOC(&bnx2x_fp(bp, index, rx_comp_mapping),
sizeof(struct eth_fast_path_rx_cqe) * NUM_RCQ_BD);
if (!bnx2x_fp(bp, index, rx_comp_ring))
goto alloc_mem_err;
/* SGE ring */
bnx2x_fp(bp, index, rx_page_ring) =
kcalloc(NUM_RX_SGE, sizeof(struct sw_rx_page),
GFP_KERNEL);
if (!bnx2x_fp(bp, index, rx_page_ring))
goto alloc_mem_err;
bnx2x_fp(bp, index, rx_sge_ring) =
BNX2X_PCI_ALLOC(&bnx2x_fp(bp, index, rx_sge_mapping),
BCM_PAGE_SIZE * NUM_RX_SGE_PAGES);
if (!bnx2x_fp(bp, index, rx_sge_ring))
goto alloc_mem_err;
/* RX BD ring */
bnx2x_set_next_page_rx_bd(fp);
/* CQ ring */
bnx2x_set_next_page_rx_cq(fp);
/* BDs */
ring_size = bnx2x_alloc_rx_bds(fp, rx_ring_size);
if (ring_size < rx_ring_size)
goto alloc_mem_err;
}
return 0;
/* handles low memory cases */
alloc_mem_err:
BNX2X_ERR("Unable to allocate full memory for queue %d (size %d)\n",
index, ring_size);
/* FW will drop all packets if queue is not big enough,
* In these cases we disable the queue
* Min size is different for OOO, TPA and non-TPA queues
*/
if (ring_size < (fp->mode == TPA_MODE_DISABLED ?
MIN_RX_SIZE_NONTPA : MIN_RX_SIZE_TPA)) {
/* release memory allocated for this queue */
bnx2x_free_fp_mem_at(bp, index);
return -ENOMEM;
}
return 0;
}
static int bnx2x_alloc_fp_mem_cnic(struct bnx2x *bp)
{
if (!NO_FCOE(bp))
/* FCoE */
if (bnx2x_alloc_fp_mem_at(bp, FCOE_IDX(bp)))
/* we will fail load process instead of mark
* NO_FCOE_FLAG
*/
return -ENOMEM;
return 0;
}
static int bnx2x_alloc_fp_mem(struct bnx2x *bp)
{
int i;
/* 1. Allocate FP for leading - fatal if error
* 2. Allocate RSS - fix number of queues if error
*/
/* leading */
if (bnx2x_alloc_fp_mem_at(bp, 0))
return -ENOMEM;
/* RSS */
for_each_nondefault_eth_queue(bp, i)
if (bnx2x_alloc_fp_mem_at(bp, i))
break;
/* handle memory failures */
if (i != BNX2X_NUM_ETH_QUEUES(bp)) {
int delta = BNX2X_NUM_ETH_QUEUES(bp) - i;
WARN_ON(delta < 0);
bnx2x_shrink_eth_fp(bp, delta);
if (CNIC_SUPPORT(bp))
/* move non eth FPs next to last eth FP
* must be done in that order
* FCOE_IDX < FWD_IDX < OOO_IDX
*/
/* move FCoE fp even NO_FCOE_FLAG is on */
bnx2x_move_fp(bp, FCOE_IDX(bp), FCOE_IDX(bp) - delta);
bp->num_ethernet_queues -= delta;
bp->num_queues = bp->num_ethernet_queues +
bp->num_cnic_queues;
BNX2X_ERR("Adjusted num of queues from %d to %d\n",
bp->num_queues + delta, bp->num_queues);
}
return 0;
}
void bnx2x_free_mem_bp(struct bnx2x *bp)
{
int i;
for (i = 0; i < bp->fp_array_size; i++)
kfree(bp->fp[i].tpa_info);
kfree(bp->fp);
kfree(bp->sp_objs);
kfree(bp->fp_stats);
kfree(bp->bnx2x_txq);
kfree(bp->msix_table);
kfree(bp->ilt);
}
int bnx2x_alloc_mem_bp(struct bnx2x *bp)
{
struct bnx2x_fastpath *fp;
struct msix_entry *tbl;
struct bnx2x_ilt *ilt;
int msix_table_size = 0;
int fp_array_size, txq_array_size;
int i;
/*
* The biggest MSI-X table we might need is as a maximum number of fast
* path IGU SBs plus default SB (for PF only).
*/
msix_table_size = bp->igu_sb_cnt;
if (IS_PF(bp))
msix_table_size++;
BNX2X_DEV_INFO("msix_table_size %d\n", msix_table_size);
/* fp array: RSS plus CNIC related L2 queues */
fp_array_size = BNX2X_MAX_RSS_COUNT(bp) + CNIC_SUPPORT(bp);
bp->fp_array_size = fp_array_size;
BNX2X_DEV_INFO("fp_array_size %d\n", bp->fp_array_size);
fp = kcalloc(bp->fp_array_size, sizeof(*fp), GFP_KERNEL);
if (!fp)
goto alloc_err;
for (i = 0; i < bp->fp_array_size; i++) {
fp[i].tpa_info =
kcalloc(ETH_MAX_AGGREGATION_QUEUES_E1H_E2,
sizeof(struct bnx2x_agg_info), GFP_KERNEL);
if (!(fp[i].tpa_info))
goto alloc_err;
}
bp->fp = fp;
/* allocate sp objs */
bp->sp_objs = kcalloc(bp->fp_array_size, sizeof(struct bnx2x_sp_objs),
GFP_KERNEL);
if (!bp->sp_objs)
goto alloc_err;
/* allocate fp_stats */
bp->fp_stats = kcalloc(bp->fp_array_size, sizeof(struct bnx2x_fp_stats),
GFP_KERNEL);
if (!bp->fp_stats)
goto alloc_err;
/* Allocate memory for the transmission queues array */
txq_array_size =
BNX2X_MAX_RSS_COUNT(bp) * BNX2X_MULTI_TX_COS + CNIC_SUPPORT(bp);
BNX2X_DEV_INFO("txq_array_size %d", txq_array_size);
bp->bnx2x_txq = kcalloc(txq_array_size, sizeof(struct bnx2x_fp_txdata),
GFP_KERNEL);
if (!bp->bnx2x_txq)
goto alloc_err;
/* msix table */
tbl = kcalloc(msix_table_size, sizeof(*tbl), GFP_KERNEL);
if (!tbl)
goto alloc_err;
bp->msix_table = tbl;
/* ilt */
ilt = kzalloc(sizeof(*ilt), GFP_KERNEL);
if (!ilt)
goto alloc_err;
bp->ilt = ilt;
return 0;
alloc_err:
bnx2x_free_mem_bp(bp);
return -ENOMEM;
}
int bnx2x_reload_if_running(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
if (unlikely(!netif_running(dev)))
return 0;
bnx2x_nic_unload(bp, UNLOAD_NORMAL, true);
return bnx2x_nic_load(bp, LOAD_NORMAL);
}
int bnx2x_get_cur_phy_idx(struct bnx2x *bp)
{
u32 sel_phy_idx = 0;
if (bp->link_params.num_phys <= 1)
return INT_PHY;
if (bp->link_vars.link_up) {
sel_phy_idx = EXT_PHY1;
/* In case link is SERDES, check if the EXT_PHY2 is the one */
if ((bp->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
(bp->link_params.phy[EXT_PHY2].supported & SUPPORTED_FIBRE))
sel_phy_idx = EXT_PHY2;
} else {
switch (bnx2x_phy_selection(&bp->link_params)) {
case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
sel_phy_idx = EXT_PHY1;
break;
case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
sel_phy_idx = EXT_PHY2;
break;
}
}
return sel_phy_idx;
}
int bnx2x_get_link_cfg_idx(struct bnx2x *bp)
{
u32 sel_phy_idx = bnx2x_get_cur_phy_idx(bp);
/*
* The selected activated PHY is always after swapping (in case PHY
* swapping is enabled). So when swapping is enabled, we need to reverse
* the configuration
*/
if (bp->link_params.multi_phy_config &
PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
if (sel_phy_idx == EXT_PHY1)
sel_phy_idx = EXT_PHY2;
else if (sel_phy_idx == EXT_PHY2)
sel_phy_idx = EXT_PHY1;
}
return LINK_CONFIG_IDX(sel_phy_idx);
}
#ifdef NETDEV_FCOE_WWNN
int bnx2x_fcoe_get_wwn(struct net_device *dev, u64 *wwn, int type)
{
struct bnx2x *bp = netdev_priv(dev);
struct cnic_eth_dev *cp = &bp->cnic_eth_dev;
switch (type) {
case NETDEV_FCOE_WWNN:
*wwn = HILO_U64(cp->fcoe_wwn_node_name_hi,
cp->fcoe_wwn_node_name_lo);
break;
case NETDEV_FCOE_WWPN:
*wwn = HILO_U64(cp->fcoe_wwn_port_name_hi,
cp->fcoe_wwn_port_name_lo);
break;
default:
BNX2X_ERR("Wrong WWN type requested - %d\n", type);
return -EINVAL;
}
return 0;
}
#endif
/* called with rtnl_lock */
int bnx2x_change_mtu(struct net_device *dev, int new_mtu)
{
struct bnx2x *bp = netdev_priv(dev);
if (pci_num_vf(bp->pdev)) {
DP(BNX2X_MSG_IOV, "VFs are enabled, can not change MTU\n");
return -EPERM;
}
if (bp->recovery_state != BNX2X_RECOVERY_DONE) {
BNX2X_ERR("Can't perform change MTU during parity recovery\n");
return -EAGAIN;
}
/* This does not race with packet allocation
* because the actual alloc size is
* only updated as part of load
*/
dev->mtu = new_mtu;
if (IS_PF(bp) && SHMEM2_HAS(bp, curr_cfg))
SHMEM2_WR(bp, curr_cfg, CURR_CFG_MET_OS);
return bnx2x_reload_if_running(dev);
}
netdev_features_t bnx2x_fix_features(struct net_device *dev,
netdev_features_t features)
{
struct bnx2x *bp = netdev_priv(dev);
if (pci_num_vf(bp->pdev)) {
netdev_features_t changed = dev->features ^ features;
/* Revert the requested changes in features if they
* would require internal reload of PF in bnx2x_set_features().
*/
if (!(features & NETIF_F_RXCSUM) && !bp->disable_tpa) {
features &= ~NETIF_F_RXCSUM;
features |= dev->features & NETIF_F_RXCSUM;
}
if (changed & NETIF_F_LOOPBACK) {
features &= ~NETIF_F_LOOPBACK;
features |= dev->features & NETIF_F_LOOPBACK;
}
}
/* TPA requires Rx CSUM offloading */
if (!(features & NETIF_F_RXCSUM)) {
features &= ~NETIF_F_LRO;
features &= ~NETIF_F_GRO;
}
return features;
}
int bnx2x_set_features(struct net_device *dev, netdev_features_t features)
{
struct bnx2x *bp = netdev_priv(dev);
netdev_features_t changes = features ^ dev->features;
bool bnx2x_reload = false;
int rc;
/* VFs or non SRIOV PFs should be able to change loopback feature */
if (!pci_num_vf(bp->pdev)) {
if (features & NETIF_F_LOOPBACK) {
if (bp->link_params.loopback_mode != LOOPBACK_BMAC) {
bp->link_params.loopback_mode = LOOPBACK_BMAC;
bnx2x_reload = true;
}
} else {
if (bp->link_params.loopback_mode != LOOPBACK_NONE) {
bp->link_params.loopback_mode = LOOPBACK_NONE;
bnx2x_reload = true;
}
}
}
/* if GRO is changed while LRO is enabled, don't force a reload */
if ((changes & NETIF_F_GRO) && (features & NETIF_F_LRO))
changes &= ~NETIF_F_GRO;
/* if GRO is changed while HW TPA is off, don't force a reload */
if ((changes & NETIF_F_GRO) && bp->disable_tpa)
changes &= ~NETIF_F_GRO;
if (changes)
bnx2x_reload = true;
if (bnx2x_reload) {
if (bp->recovery_state == BNX2X_RECOVERY_DONE) {
dev->features = features;
rc = bnx2x_reload_if_running(dev);
return rc ? rc : 1;
}
/* else: bnx2x_nic_load() will be called at end of recovery */
}
return 0;
}
void bnx2x_tx_timeout(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
#ifdef BNX2X_STOP_ON_ERROR
if (!bp->panic)
bnx2x_panic();
#endif
/* This allows the netif to be shutdown gracefully before resetting */
bnx2x_schedule_sp_rtnl(bp, BNX2X_SP_RTNL_TX_TIMEOUT, 0);
}
int bnx2x_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct bnx2x *bp;
if (!dev) {
dev_err(&pdev->dev, "BAD net device from bnx2x_init_one\n");
return -ENODEV;
}
bp = netdev_priv(dev);
rtnl_lock();
pci_save_state(pdev);
if (!netif_running(dev)) {
rtnl_unlock();
return 0;
}
netif_device_detach(dev);
bnx2x_nic_unload(bp, UNLOAD_CLOSE, false);
bnx2x_set_power_state(bp, pci_choose_state(pdev, state));
rtnl_unlock();
return 0;
}
int bnx2x_resume(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct bnx2x *bp;
int rc;
if (!dev) {
dev_err(&pdev->dev, "BAD net device from bnx2x_init_one\n");
return -ENODEV;
}
bp = netdev_priv(dev);
if (bp->recovery_state != BNX2X_RECOVERY_DONE) {
BNX2X_ERR("Handling parity error recovery. Try again later\n");
return -EAGAIN;
}
rtnl_lock();
pci_restore_state(pdev);
if (!netif_running(dev)) {
rtnl_unlock();
return 0;
}
bnx2x_set_power_state(bp, PCI_D0);
netif_device_attach(dev);
rc = bnx2x_nic_load(bp, LOAD_OPEN);
rtnl_unlock();
return rc;
}
void bnx2x_set_ctx_validation(struct bnx2x *bp, struct eth_context *cxt,
u32 cid)
{
if (!cxt) {
BNX2X_ERR("bad context pointer %p\n", cxt);
return;
}
/* ustorm cxt validation */
cxt->ustorm_ag_context.cdu_usage =
CDU_RSRVD_VALUE_TYPE_A(HW_CID(bp, cid),
CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
/* xcontext validation */
cxt->xstorm_ag_context.cdu_reserved =
CDU_RSRVD_VALUE_TYPE_A(HW_CID(bp, cid),
CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
}
static void storm_memset_hc_timeout(struct bnx2x *bp, u8 port,
u8 fw_sb_id, u8 sb_index,
u8 ticks)
{
u32 addr = BAR_CSTRORM_INTMEM +
CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index);
REG_WR8(bp, addr, ticks);
DP(NETIF_MSG_IFUP,
"port %x fw_sb_id %d sb_index %d ticks %d\n",
port, fw_sb_id, sb_index, ticks);
}
static void storm_memset_hc_disable(struct bnx2x *bp, u8 port,
u16 fw_sb_id, u8 sb_index,
u8 disable)
{
u32 enable_flag = disable ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
u32 addr = BAR_CSTRORM_INTMEM +
CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index);
u8 flags = REG_RD8(bp, addr);
/* clear and set */
flags &= ~HC_INDEX_DATA_HC_ENABLED;
flags |= enable_flag;
REG_WR8(bp, addr, flags);
DP(NETIF_MSG_IFUP,
"port %x fw_sb_id %d sb_index %d disable %d\n",
port, fw_sb_id, sb_index, disable);
}
void bnx2x_update_coalesce_sb_index(struct bnx2x *bp, u8 fw_sb_id,
u8 sb_index, u8 disable, u16 usec)
{
int port = BP_PORT(bp);
u8 ticks = usec / BNX2X_BTR;
storm_memset_hc_timeout(bp, port, fw_sb_id, sb_index, ticks);
disable = disable ? 1 : (usec ? 0 : 1);
storm_memset_hc_disable(bp, port, fw_sb_id, sb_index, disable);
}
void bnx2x_schedule_sp_rtnl(struct bnx2x *bp, enum sp_rtnl_flag flag,
u32 verbose)
{
smp_mb__before_atomic();
set_bit(flag, &bp->sp_rtnl_state);
smp_mb__after_atomic();
DP((BNX2X_MSG_SP | verbose), "Scheduling sp_rtnl task [Flag: %d]\n",
flag);
schedule_delayed_work(&bp->sp_rtnl_task, 0);
}
| devmapal/linux | drivers/net/ethernet/broadcom/bnx2x/bnx2x_cmn.c | C | gpl-2.0 | 138,415 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.5 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2014 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
require_once '../civicrm.config.php';
require_once 'CRM/Core/Config.php';
$config = CRM_Core_Config::singleton();
session_start();
require_once 'CRM/Utils/REST.php';
$rest = new CRM_Utils_REST();
if (isset($_GET['json']) && $_GET['json']) {
header('Content-Type: text/javascript');
}
else {
header('Content-Type: text/xml');
}
echo $rest->bootAndRun();
| jnapoleone/twig | sites/all/modules/civicrm/extern/rest.php | PHP | gpl-2.0 | 2,028 |
// Auto-generated with: android/scripts/gen-entries.py --mode=wrapper audio/wrappers/alsa.entries
// DO NOT EDIT THIS FILE
#include <dlfcn.h>
#include <alsa/asoundlib.h>
///
/// W R A P P E R P O I N T E R S
///
static snd_pcm_sframes_t (*__dll_snd_pcm_avail_update)(snd_pcm_t * pcm) = 0;
static int (*__dll_snd_pcm_close)(snd_pcm_t * pcm) = 0;
static int (*__dll_snd_pcm_drop)(snd_pcm_t * pcm) = 0;
static int (*__dll_snd_pcm_hw_params)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params) = 0;
static int (*__dll_snd_pcm_hw_params_any)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params) = 0;
static int (*__dll_snd_pcm_hw_params_get_buffer_size)(const snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val) = 0;
static int (*__dll_snd_pcm_hw_params_get_format)(const snd_pcm_hw_params_t * params, snd_pcm_format_t * val) = 0;
static int (*__dll_snd_pcm_hw_params_set_access)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_access_t _access) = 0;
static int (*__dll_snd_pcm_hw_params_set_buffer_size_near)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val) = 0;
static int (*__dll_snd_pcm_hw_params_set_buffer_time_near)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val, int * dir) = 0;
static int (*__dll_snd_pcm_hw_params_set_channels_near)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val) = 0;
static int (*__dll_snd_pcm_hw_params_set_format)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_format_t val) = 0;
static int (*__dll_snd_pcm_hw_params_set_period_size_near)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val, int * dir) = 0;
static int (*__dll_snd_pcm_hw_params_set_period_time_near)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val, int * dir) = 0;
static int (*__dll_snd_pcm_hw_params_set_rate_near)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val, int * dir) = 0;
static size_t (*__dll_snd_pcm_hw_params_sizeof)() = 0;
static int (*__dll_snd_pcm_open)(snd_pcm_t ** pcm, const char * name, snd_pcm_stream_t stream, int mode) = 0;
static int (*__dll_snd_pcm_poll_descriptors)(snd_pcm_t * pcm, struct pollfd * pfds, unsigned int space) = 0;
static int (*__dll_snd_pcm_poll_descriptors_count)(snd_pcm_t * pcm) = 0;
static int (*__dll_snd_pcm_poll_descriptors_revents)(snd_pcm_t * pcm, struct pollfd * pfds, unsigned int nfds, unsigned short * revents) = 0;
static int (*__dll_snd_pcm_prepare)(snd_pcm_t * pcm) = 0;
static snd_pcm_sframes_t (*__dll_snd_pcm_readi)(snd_pcm_t * pcm, void * buffer, snd_pcm_uframes_t size) = 0;
static int (*__dll_snd_pcm_resume)(snd_pcm_t * pcm) = 0;
static snd_pcm_state_t (*__dll_snd_pcm_state)(snd_pcm_t * pcm) = 0;
static int (*__dll_snd_pcm_sw_params)(snd_pcm_t * pcm, snd_pcm_sw_params_t * params) = 0;
static int (*__dll_snd_pcm_sw_params_current)(snd_pcm_t * pcm, snd_pcm_sw_params_t * params) = 0;
static int (*__dll_snd_pcm_sw_params_set_start_threshold)(snd_pcm_t * pcm, snd_pcm_sw_params_t * params, snd_pcm_uframes_t val) = 0;
static size_t (*__dll_snd_pcm_sw_params_sizeof)() = 0;
static snd_pcm_sframes_t (*__dll_snd_pcm_writei)(snd_pcm_t * pcm, const void * buffer, snd_pcm_uframes_t size) = 0;
static const char * (*__dll_snd_strerror)(int errnum) = 0;
///
/// W R A P P E R F U N C T I O N S
///
snd_pcm_sframes_t snd_pcm_avail_update(snd_pcm_t * pcm) {
return __dll_snd_pcm_avail_update(pcm);
}
int snd_pcm_close(snd_pcm_t * pcm) {
return __dll_snd_pcm_close(pcm);
}
int snd_pcm_drop(snd_pcm_t * pcm) {
return __dll_snd_pcm_drop(pcm);
}
int snd_pcm_hw_params(snd_pcm_t * pcm, snd_pcm_hw_params_t * params) {
return __dll_snd_pcm_hw_params(pcm, params);
}
int snd_pcm_hw_params_any(snd_pcm_t * pcm, snd_pcm_hw_params_t * params) {
return __dll_snd_pcm_hw_params_any(pcm, params);
}
int snd_pcm_hw_params_get_buffer_size(const snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val) {
return __dll_snd_pcm_hw_params_get_buffer_size(params, val);
}
int snd_pcm_hw_params_get_format(const snd_pcm_hw_params_t * params, snd_pcm_format_t * val) {
return __dll_snd_pcm_hw_params_get_format(params, val);
}
int snd_pcm_hw_params_set_access(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_access_t _access) {
return __dll_snd_pcm_hw_params_set_access(pcm, params, _access);
}
int snd_pcm_hw_params_set_buffer_size_near(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val) {
return __dll_snd_pcm_hw_params_set_buffer_size_near(pcm, params, val);
}
int snd_pcm_hw_params_set_buffer_time_near(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val, int * dir) {
return __dll_snd_pcm_hw_params_set_buffer_time_near(pcm, params, val, dir);
}
int snd_pcm_hw_params_set_channels_near(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val) {
return __dll_snd_pcm_hw_params_set_channels_near(pcm, params, val);
}
int snd_pcm_hw_params_set_format(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_format_t val) {
return __dll_snd_pcm_hw_params_set_format(pcm, params, val);
}
int snd_pcm_hw_params_set_period_size_near(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val, int * dir) {
return __dll_snd_pcm_hw_params_set_period_size_near(pcm, params, val, dir);
}
int snd_pcm_hw_params_set_period_time_near(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val, int * dir) {
return __dll_snd_pcm_hw_params_set_period_time_near(pcm, params, val, dir);
}
int snd_pcm_hw_params_set_rate_near(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val, int * dir) {
return __dll_snd_pcm_hw_params_set_rate_near(pcm, params, val, dir);
}
size_t snd_pcm_hw_params_sizeof() {
return __dll_snd_pcm_hw_params_sizeof();
}
int snd_pcm_open(snd_pcm_t ** pcm, const char * name, snd_pcm_stream_t stream, int mode) {
return __dll_snd_pcm_open(pcm, name, stream, mode);
}
int snd_pcm_poll_descriptors(snd_pcm_t * pcm, struct pollfd * pfds, unsigned int space) {
return __dll_snd_pcm_poll_descriptors(pcm, pfds, space);
}
int snd_pcm_poll_descriptors_count(snd_pcm_t * pcm) {
return __dll_snd_pcm_poll_descriptors_count(pcm);
}
int snd_pcm_poll_descriptors_revents(snd_pcm_t * pcm, struct pollfd * pfds, unsigned int nfds, unsigned short * revents) {
return __dll_snd_pcm_poll_descriptors_revents(pcm, pfds, nfds, revents);
}
int snd_pcm_prepare(snd_pcm_t * pcm) {
return __dll_snd_pcm_prepare(pcm);
}
snd_pcm_sframes_t snd_pcm_readi(snd_pcm_t * pcm, void * buffer, snd_pcm_uframes_t size) {
return __dll_snd_pcm_readi(pcm, buffer, size);
}
int snd_pcm_resume(snd_pcm_t * pcm) {
return __dll_snd_pcm_resume(pcm);
}
snd_pcm_state_t snd_pcm_state(snd_pcm_t * pcm) {
return __dll_snd_pcm_state(pcm);
}
int snd_pcm_sw_params(snd_pcm_t * pcm, snd_pcm_sw_params_t * params) {
return __dll_snd_pcm_sw_params(pcm, params);
}
int snd_pcm_sw_params_current(snd_pcm_t * pcm, snd_pcm_sw_params_t * params) {
return __dll_snd_pcm_sw_params_current(pcm, params);
}
int snd_pcm_sw_params_set_start_threshold(snd_pcm_t * pcm, snd_pcm_sw_params_t * params, snd_pcm_uframes_t val) {
return __dll_snd_pcm_sw_params_set_start_threshold(pcm, params, val);
}
size_t snd_pcm_sw_params_sizeof() {
return __dll_snd_pcm_sw_params_sizeof();
}
snd_pcm_sframes_t snd_pcm_writei(snd_pcm_t * pcm, const void * buffer, snd_pcm_uframes_t size) {
return __dll_snd_pcm_writei(pcm, buffer, size);
}
const char * snd_strerror(int errnum) {
return __dll_snd_strerror(errnum);
}
///
/// I N I T I A L I Z A T I O N F U N C T I O N
///
int alsa_dynlink_init(void* lib) {
__dll_snd_pcm_avail_update = (snd_pcm_sframes_t(*)(snd_pcm_t * pcm))dlsym(lib, "snd_pcm_avail_update");
if (!__dll_snd_pcm_avail_update) return -1;
__dll_snd_pcm_close = (int(*)(snd_pcm_t * pcm))dlsym(lib, "snd_pcm_close");
if (!__dll_snd_pcm_close) return -1;
__dll_snd_pcm_drop = (int(*)(snd_pcm_t * pcm))dlsym(lib, "snd_pcm_drop");
if (!__dll_snd_pcm_drop) return -1;
__dll_snd_pcm_hw_params = (int(*)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params))dlsym(lib, "snd_pcm_hw_params");
if (!__dll_snd_pcm_hw_params) return -1;
__dll_snd_pcm_hw_params_any = (int(*)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params))dlsym(lib, "snd_pcm_hw_params_any");
if (!__dll_snd_pcm_hw_params_any) return -1;
__dll_snd_pcm_hw_params_get_buffer_size = (int(*)(const snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val))dlsym(lib, "snd_pcm_hw_params_get_buffer_size");
if (!__dll_snd_pcm_hw_params_get_buffer_size) return -1;
__dll_snd_pcm_hw_params_get_format = (int(*)(const snd_pcm_hw_params_t * params, snd_pcm_format_t * val))dlsym(lib, "snd_pcm_hw_params_get_format");
if (!__dll_snd_pcm_hw_params_get_format) return -1;
__dll_snd_pcm_hw_params_set_access = (int(*)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_access_t _access))dlsym(lib, "snd_pcm_hw_params_set_access");
if (!__dll_snd_pcm_hw_params_set_access) return -1;
__dll_snd_pcm_hw_params_set_buffer_size_near = (int(*)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val))dlsym(lib, "snd_pcm_hw_params_set_buffer_size_near");
if (!__dll_snd_pcm_hw_params_set_buffer_size_near) return -1;
__dll_snd_pcm_hw_params_set_buffer_time_near = (int(*)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val, int * dir))dlsym(lib, "snd_pcm_hw_params_set_buffer_time_near");
if (!__dll_snd_pcm_hw_params_set_buffer_time_near) return -1;
__dll_snd_pcm_hw_params_set_channels_near = (int(*)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val))dlsym(lib, "snd_pcm_hw_params_set_channels_near");
if (!__dll_snd_pcm_hw_params_set_channels_near) return -1;
__dll_snd_pcm_hw_params_set_format = (int(*)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_format_t val))dlsym(lib, "snd_pcm_hw_params_set_format");
if (!__dll_snd_pcm_hw_params_set_format) return -1;
__dll_snd_pcm_hw_params_set_period_size_near = (int(*)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val, int * dir))dlsym(lib, "snd_pcm_hw_params_set_period_size_near");
if (!__dll_snd_pcm_hw_params_set_period_size_near) return -1;
__dll_snd_pcm_hw_params_set_period_time_near = (int(*)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val, int * dir))dlsym(lib, "snd_pcm_hw_params_set_period_time_near");
if (!__dll_snd_pcm_hw_params_set_period_time_near) return -1;
__dll_snd_pcm_hw_params_set_rate_near = (int(*)(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, unsigned int * val, int * dir))dlsym(lib, "snd_pcm_hw_params_set_rate_near");
if (!__dll_snd_pcm_hw_params_set_rate_near) return -1;
__dll_snd_pcm_hw_params_sizeof = (size_t(*)())dlsym(lib, "snd_pcm_hw_params_sizeof");
if (!__dll_snd_pcm_hw_params_sizeof) return -1;
__dll_snd_pcm_open = (int(*)(snd_pcm_t ** pcm, const char * name, snd_pcm_stream_t stream, int mode))dlsym(lib, "snd_pcm_open");
if (!__dll_snd_pcm_open) return -1;
__dll_snd_pcm_poll_descriptors = (int(*)(snd_pcm_t * pcm, struct pollfd * pfds, unsigned int space))dlsym(lib, "snd_pcm_poll_descriptors");
if (!__dll_snd_pcm_poll_descriptors) return -1;
__dll_snd_pcm_poll_descriptors_count = (int(*)(snd_pcm_t * pcm))dlsym(lib, "snd_pcm_poll_descriptors_count");
if (!__dll_snd_pcm_poll_descriptors_count) return -1;
__dll_snd_pcm_poll_descriptors_revents = (int(*)(snd_pcm_t * pcm, struct pollfd * pfds, unsigned int nfds, unsigned short * revents))dlsym(lib, "snd_pcm_poll_descriptors_revents");
if (!__dll_snd_pcm_poll_descriptors_revents) return -1;
__dll_snd_pcm_prepare = (int(*)(snd_pcm_t * pcm))dlsym(lib, "snd_pcm_prepare");
if (!__dll_snd_pcm_prepare) return -1;
__dll_snd_pcm_readi = (snd_pcm_sframes_t(*)(snd_pcm_t * pcm, void * buffer, snd_pcm_uframes_t size))dlsym(lib, "snd_pcm_readi");
if (!__dll_snd_pcm_readi) return -1;
__dll_snd_pcm_resume = (int(*)(snd_pcm_t * pcm))dlsym(lib, "snd_pcm_resume");
if (!__dll_snd_pcm_resume) return -1;
__dll_snd_pcm_state = (snd_pcm_state_t(*)(snd_pcm_t * pcm))dlsym(lib, "snd_pcm_state");
if (!__dll_snd_pcm_state) return -1;
__dll_snd_pcm_sw_params = (int(*)(snd_pcm_t * pcm, snd_pcm_sw_params_t * params))dlsym(lib, "snd_pcm_sw_params");
if (!__dll_snd_pcm_sw_params) return -1;
__dll_snd_pcm_sw_params_current = (int(*)(snd_pcm_t * pcm, snd_pcm_sw_params_t * params))dlsym(lib, "snd_pcm_sw_params_current");
if (!__dll_snd_pcm_sw_params_current) return -1;
__dll_snd_pcm_sw_params_set_start_threshold = (int(*)(snd_pcm_t * pcm, snd_pcm_sw_params_t * params, snd_pcm_uframes_t val))dlsym(lib, "snd_pcm_sw_params_set_start_threshold");
if (!__dll_snd_pcm_sw_params_set_start_threshold) return -1;
__dll_snd_pcm_sw_params_sizeof = (size_t(*)())dlsym(lib, "snd_pcm_sw_params_sizeof");
if (!__dll_snd_pcm_sw_params_sizeof) return -1;
__dll_snd_pcm_writei = (snd_pcm_sframes_t(*)(snd_pcm_t * pcm, const void * buffer, snd_pcm_uframes_t size))dlsym(lib, "snd_pcm_writei");
if (!__dll_snd_pcm_writei) return -1;
__dll_snd_strerror = (const char *(*)(int errnum))dlsym(lib, "snd_strerror");
if (!__dll_snd_strerror) return -1;
return 0;
}
| zeldin/platform_external_qemu | audio/wrappers/alsa.c | C | gpl-2.0 | 13,101 |
/*
* f_ecm.c -- USB CDC Ethernet (ECM) link function driver
*
* Copyright (C) 2003-2005,2008 David Brownell
* Copyright (C) 2008 Nokia Corporation
*
* 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.
*/
/* #define VERBOSE_DEBUG */
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/etherdevice.h>
#include "u_ether.h"
/*
* This function is a "CDC Ethernet Networking Control Model" (CDC ECM)
* Ethernet link. The data transfer model is simple (packets sent and
* received over bulk endpoints using normal short packet termination),
* and the control model exposes various data and optional notifications.
*
* ECM is well standardized and (except for Microsoft) supported by most
* operating systems with USB host support. It's the preferred interop
* solution for Ethernet over USB, at least for firmware based solutions.
* (Hardware solutions tend to be more minimalist.) A newer and simpler
* "Ethernet Emulation Model" (CDC EEM) hasn't yet caught on.
*
* Note that ECM requires the use of "alternate settings" for its data
* interface. This means that the set_alt() method has real work to do,
* and also means that a get_alt() method is required.
*/
enum ecm_notify_state {
ECM_NOTIFY_NONE, /* don't notify */
ECM_NOTIFY_CONNECT, /* issue CONNECT next */
ECM_NOTIFY_SPEED, /* issue SPEED_CHANGE next */
};
struct f_ecm {
struct gether port;
u8 ctrl_id, data_id;
char ethaddr[14];
struct usb_ep *notify;
struct usb_request *notify_req;
u8 notify_state;
bool is_open;
/* FIXME is_open needs some irq-ish locking
* ... possibly the same as port.ioport
*/
};
static inline struct f_ecm *func_to_ecm(struct usb_function *f)
{
return container_of(f, struct f_ecm, port.func);
}
/* peak (theoretical) bulk transfer rate in bits-per-second */
static inline unsigned ecm_bitrate(struct usb_gadget *g)
{
if (gadget_is_superspeed(g) && g->speed == USB_SPEED_SUPER)
return 13 * 1024 * 8 * 1000 * 8;
else if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
return 13 * 512 * 8 * 1000 * 8;
else
return 19 * 64 * 1 * 1000 * 8;
}
/*-------------------------------------------------------------------------*/
/*
* Include the status endpoint if we can, even though it's optional.
*
* Use wMaxPacketSize big enough to fit CDC_NOTIFY_SPEED_CHANGE in one
* packet, to simplify cancellation; and a big transfer interval, to
* waste less bandwidth.
*
* Some drivers (like Linux 2.4 cdc-ether!) "need" it to exist even
* if they ignore the connect/disconnect notifications that real aether
* can provide. More advanced cdc configurations might want to support
* encapsulated commands (vendor-specific, using control-OUT).
*/
#define LOG2_STATUS_INTERVAL_MSEC 5 /* 1 << 5 == 32 msec */
#define ECM_STATUS_BYTECOUNT 16 /* 8 byte header + data */
/* interface descriptor: */
static struct usb_interface_assoc_descriptor
ecm_iad_descriptor = {
.bLength = sizeof ecm_iad_descriptor,
.bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
/* .bFirstInterface = DYNAMIC, */
.bInterfaceCount = 2, /* control + data */
.bFunctionClass = USB_CLASS_COMM,
.bFunctionSubClass = USB_CDC_SUBCLASS_ETHERNET,
.bFunctionProtocol = USB_CDC_PROTO_NONE,
/* .iFunction = DYNAMIC */
};
static struct usb_interface_descriptor ecm_control_intf = {
.bLength = sizeof ecm_control_intf,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
/* status endpoint is optional; this could be patched later */
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_COMM,
.bInterfaceSubClass = USB_CDC_SUBCLASS_ETHERNET,
.bInterfaceProtocol = USB_CDC_PROTO_NONE,
/* .iInterface = DYNAMIC */
};
static struct usb_cdc_header_desc ecm_header_desc = {
.bLength = sizeof ecm_header_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_HEADER_TYPE,
.bcdCDC = cpu_to_le16(0x0110),
};
static struct usb_cdc_union_desc ecm_union_desc = {
.bLength = sizeof(ecm_union_desc),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_UNION_TYPE,
/* .bMasterInterface0 = DYNAMIC */
/* .bSlaveInterface0 = DYNAMIC */
};
static struct usb_cdc_ether_desc ecm_desc = {
.bLength = sizeof ecm_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_ETHERNET_TYPE,
/* this descriptor actually adds value, surprise! */
/* .iMACAddress = DYNAMIC */
.bmEthernetStatistics = cpu_to_le32(0), /* no statistics */
.wMaxSegmentSize = cpu_to_le16(ETH_FRAME_LEN),
.wNumberMCFilters = cpu_to_le16(0),
.bNumberPowerFilters = 0,
};
/* the default data interface has no endpoints ... */
static struct usb_interface_descriptor ecm_data_nop_intf = {
.bLength = sizeof ecm_data_nop_intf,
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = 1,
.bAlternateSetting = 0,
.bNumEndpoints = 0,
.bInterfaceClass = USB_CLASS_CDC_DATA,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
/* .iInterface = DYNAMIC */
};
/* ... but the "real" data interface has two bulk endpoints */
static struct usb_interface_descriptor ecm_data_intf = {
.bLength = sizeof ecm_data_intf,
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = 1,
.bAlternateSetting = 1,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC_DATA,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
/* .iInterface = DYNAMIC */
};
/* full speed support: */
static struct usb_endpoint_descriptor fs_ecm_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(ECM_STATUS_BYTECOUNT),
.bInterval = 1 << LOG2_STATUS_INTERVAL_MSEC,
};
static struct usb_endpoint_descriptor fs_ecm_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor fs_ecm_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_descriptor_header *ecm_fs_function[] = {
/* CDC ECM control descriptors */
(struct usb_descriptor_header *) &ecm_iad_descriptor,
(struct usb_descriptor_header *) &ecm_control_intf,
(struct usb_descriptor_header *) &ecm_header_desc,
(struct usb_descriptor_header *) &ecm_union_desc,
(struct usb_descriptor_header *) &ecm_desc,
/* NOTE: status endpoint might need to be removed */
(struct usb_descriptor_header *) &fs_ecm_notify_desc,
/* data interface, altsettings 0 and 1 */
(struct usb_descriptor_header *) &ecm_data_nop_intf,
(struct usb_descriptor_header *) &ecm_data_intf,
(struct usb_descriptor_header *) &fs_ecm_in_desc,
(struct usb_descriptor_header *) &fs_ecm_out_desc,
NULL,
};
/* high speed support: */
static struct usb_endpoint_descriptor hs_ecm_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(ECM_STATUS_BYTECOUNT),
.bInterval = LOG2_STATUS_INTERVAL_MSEC + 4,
};
static struct usb_endpoint_descriptor hs_ecm_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_endpoint_descriptor hs_ecm_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_descriptor_header *ecm_hs_function[] = {
/* CDC ECM control descriptors */
(struct usb_descriptor_header *) &ecm_iad_descriptor,
(struct usb_descriptor_header *) &ecm_control_intf,
(struct usb_descriptor_header *) &ecm_header_desc,
(struct usb_descriptor_header *) &ecm_union_desc,
(struct usb_descriptor_header *) &ecm_desc,
/* NOTE: status endpoint might need to be removed */
(struct usb_descriptor_header *) &hs_ecm_notify_desc,
/* data interface, altsettings 0 and 1 */
(struct usb_descriptor_header *) &ecm_data_nop_intf,
(struct usb_descriptor_header *) &ecm_data_intf,
(struct usb_descriptor_header *) &hs_ecm_in_desc,
(struct usb_descriptor_header *) &hs_ecm_out_desc,
NULL,
};
/* super speed support: */
static struct usb_endpoint_descriptor ss_ecm_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(ECM_STATUS_BYTECOUNT),
.bInterval = LOG2_STATUS_INTERVAL_MSEC + 4,
};
static struct usb_ss_ep_comp_descriptor ss_ecm_intr_comp_desc = {
.bLength = sizeof ss_ecm_intr_comp_desc,
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
/* the following 3 values can be tweaked if necessary */
/* .bMaxBurst = 0, */
/* .bmAttributes = 0, */
.wBytesPerInterval = cpu_to_le16(ECM_STATUS_BYTECOUNT),
};
static struct usb_endpoint_descriptor ss_ecm_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
static struct usb_endpoint_descriptor ss_ecm_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
static struct usb_ss_ep_comp_descriptor ss_ecm_bulk_comp_desc = {
.bLength = sizeof ss_ecm_bulk_comp_desc,
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
/* the following 2 values can be tweaked if necessary */
/* .bMaxBurst = 0, */
/* .bmAttributes = 0, */
};
static struct usb_descriptor_header *ecm_ss_function[] = {
/* CDC ECM control descriptors */
(struct usb_descriptor_header *) &ecm_control_intf,
(struct usb_descriptor_header *) &ecm_header_desc,
(struct usb_descriptor_header *) &ecm_union_desc,
(struct usb_descriptor_header *) &ecm_desc,
/* NOTE: status endpoint might need to be removed */
(struct usb_descriptor_header *) &ss_ecm_notify_desc,
(struct usb_descriptor_header *) &ss_ecm_intr_comp_desc,
/* data interface, altsettings 0 and 1 */
(struct usb_descriptor_header *) &ecm_data_nop_intf,
(struct usb_descriptor_header *) &ecm_data_intf,
(struct usb_descriptor_header *) &ss_ecm_in_desc,
(struct usb_descriptor_header *) &ss_ecm_bulk_comp_desc,
(struct usb_descriptor_header *) &ss_ecm_out_desc,
(struct usb_descriptor_header *) &ss_ecm_bulk_comp_desc,
NULL,
};
/* string descriptors: */
static struct usb_string ecm_string_defs[] = {
[0].s = "CDC Ethernet Control Model (ECM)",
[1].s = NULL /* DYNAMIC */,
[2].s = "CDC Ethernet Data",
[3].s = "CDC ECM",
{ } /* end of list */
};
static struct usb_gadget_strings ecm_string_table = {
.language = 0x0409, /* en-us */
.strings = ecm_string_defs,
};
static struct usb_gadget_strings *ecm_strings[] = {
&ecm_string_table,
NULL,
};
/*-------------------------------------------------------------------------*/
static void ecm_do_notify(struct f_ecm *ecm)
{
struct usb_request *req = ecm->notify_req;
struct usb_cdc_notification *event;
struct usb_composite_dev *cdev = ecm->port.func.config->cdev;
__le32 *data;
int status;
/* notification already in flight? */
if (!req)
return;
event = req->buf;
switch (ecm->notify_state) {
case ECM_NOTIFY_NONE:
return;
case ECM_NOTIFY_CONNECT:
event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
if (ecm->is_open)
event->wValue = cpu_to_le16(1);
else
event->wValue = cpu_to_le16(0);
event->wLength = 0;
req->length = sizeof *event;
DBG(cdev, "notify connect %s\n",
ecm->is_open ? "true" : "false");
ecm->notify_state = ECM_NOTIFY_SPEED;
break;
case ECM_NOTIFY_SPEED:
event->bNotificationType = USB_CDC_NOTIFY_SPEED_CHANGE;
event->wValue = cpu_to_le16(0);
event->wLength = cpu_to_le16(8);
req->length = ECM_STATUS_BYTECOUNT;
/* SPEED_CHANGE data is up/down speeds in bits/sec */
data = req->buf + sizeof *event;
data[0] = cpu_to_le32(ecm_bitrate(cdev->gadget));
data[1] = data[0];
DBG(cdev, "notify speed %d\n", ecm_bitrate(cdev->gadget));
ecm->notify_state = ECM_NOTIFY_NONE;
break;
}
event->bmRequestType = 0xA1;
event->wIndex = cpu_to_le16(ecm->ctrl_id);
ecm->notify_req = NULL;
status = usb_ep_queue(ecm->notify, req, GFP_ATOMIC);
if (status < 0) {
ecm->notify_req = req;
DBG(cdev, "notify --> %d\n", status);
}
}
static void ecm_notify(struct f_ecm *ecm)
{
/* NOTE on most versions of Linux, host side cdc-ethernet
* won't listen for notifications until its netdevice opens.
* The first notification then sits in the FIFO for a long
* time, and the second one is queued.
*/
ecm->notify_state = ECM_NOTIFY_CONNECT;
ecm_do_notify(ecm);
}
static void ecm_notify_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_ecm *ecm = req->context;
struct usb_composite_dev *cdev = ecm->port.func.config->cdev;
struct usb_cdc_notification *event = req->buf;
switch (req->status) {
case 0:
/* no fault */
break;
case -ECONNRESET:
case -ESHUTDOWN:
ecm->notify_state = ECM_NOTIFY_NONE;
break;
default:
DBG(cdev, "event %02x --> %d\n",
event->bNotificationType, req->status);
break;
}
ecm->notify_req = req;
ecm_do_notify(ecm);
}
static int ecm_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
{
struct f_ecm *ecm = func_to_ecm(f);
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
int value = -EOPNOTSUPP;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
/* composite driver infrastructure handles everything except
* CDC class messages; interface activation uses set_alt().
*/
switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_SET_ETHERNET_PACKET_FILTER:
/* see 6.2.30: no data, wIndex = interface,
* wValue = packet filter bitmap
*/
if (w_length != 0 || w_index != ecm->ctrl_id)
goto invalid;
DBG(cdev, "packet filter %02x\n", w_value);
/* REVISIT locking of cdc_filter. This assumes the UDC
* driver won't have a concurrent packet TX irq running on
* another CPU; or that if it does, this write is atomic...
*/
ecm->port.cdc_filter = w_value;
value = 0;
break;
/* and optionally:
* case USB_CDC_SEND_ENCAPSULATED_COMMAND:
* case USB_CDC_GET_ENCAPSULATED_RESPONSE:
* case USB_CDC_SET_ETHERNET_MULTICAST_FILTERS:
* case USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER:
* case USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER:
* case USB_CDC_GET_ETHERNET_STATISTIC:
*/
default:
invalid:
DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
}
/* respond with data transfer or status phase? */
if (value >= 0) {
DBG(cdev, "ecm req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
req->zero = 0;
req->length = value;
value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
if (value < 0)
ERROR(cdev, "ecm req %02x.%02x response err %d\n",
ctrl->bRequestType, ctrl->bRequest,
value);
}
/* device either stalls (value < 0) or reports success */
return value;
}
static int ecm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_ecm *ecm = func_to_ecm(f);
struct usb_composite_dev *cdev = f->config->cdev;
/* Control interface has only altsetting 0 */
if (intf == ecm->ctrl_id) {
if (alt != 0)
goto fail;
if (ecm->notify->driver_data) {
VDBG(cdev, "reset ecm control %d\n", intf);
usb_ep_disable(ecm->notify);
}
if (!(ecm->notify->desc)) {
VDBG(cdev, "init ecm ctrl %d\n", intf);
if (config_ep_by_speed(cdev->gadget, f, ecm->notify))
goto fail;
}
usb_ep_enable(ecm->notify);
ecm->notify->driver_data = ecm;
/* Data interface has two altsettings, 0 and 1 */
} else if (intf == ecm->data_id) {
if (alt > 1)
goto fail;
if (ecm->port.in_ep->driver_data) {
DBG(cdev, "reset ecm\n");
gether_disconnect(&ecm->port);
}
if (!ecm->port.in_ep->desc ||
!ecm->port.out_ep->desc) {
DBG(cdev, "init ecm\n");
if (config_ep_by_speed(cdev->gadget, f,
ecm->port.in_ep) ||
config_ep_by_speed(cdev->gadget, f,
ecm->port.out_ep)) {
ecm->port.in_ep->desc = NULL;
ecm->port.out_ep->desc = NULL;
goto fail;
}
}
/* CDC Ethernet only sends data in non-default altsettings.
* Changing altsettings resets filters, statistics, etc.
*/
if (alt == 1) {
struct net_device *net;
/* Enable zlps by default for ECM conformance;
* override for musb_hdrc (avoids txdma ovhead).
*/
ecm->port.is_zlp_ok = !(gadget_is_musbhdrc(cdev->gadget)
);
ecm->port.cdc_filter = DEFAULT_FILTER;
DBG(cdev, "activate ecm\n");
net = gether_connect(&ecm->port);
if (IS_ERR(net))
return PTR_ERR(net);
}
/* NOTE this can be a minor disagreement with the ECM spec,
* which says speed notifications will "always" follow
* connection notifications. But we allow one connect to
* follow another (if the first is in flight), and instead
* just guarantee that a speed notification is always sent.
*/
ecm_notify(ecm);
} else
goto fail;
return 0;
fail:
return -EINVAL;
}
/* Because the data interface supports multiple altsettings,
* this ECM function *MUST* implement a get_alt() method.
*/
static int ecm_get_alt(struct usb_function *f, unsigned intf)
{
struct f_ecm *ecm = func_to_ecm(f);
if (intf == ecm->ctrl_id)
return 0;
return ecm->port.in_ep->driver_data ? 1 : 0;
}
static void ecm_disable(struct usb_function *f)
{
struct f_ecm *ecm = func_to_ecm(f);
struct usb_composite_dev *cdev = f->config->cdev;
DBG(cdev, "ecm deactivated\n");
if (ecm->port.in_ep->driver_data)
gether_disconnect(&ecm->port);
if (ecm->notify->driver_data) {
usb_ep_disable(ecm->notify);
ecm->notify->driver_data = NULL;
ecm->notify->desc = NULL;
}
}
/*-------------------------------------------------------------------------*/
/*
* Callbacks let us notify the host about connect/disconnect when the
* net device is opened or closed.
*
* For testing, note that link states on this side include both opened
* and closed variants of:
*
* - disconnected/unconfigured
* - configured but inactive (data alt 0)
* - configured and active (data alt 1)
*
* Each needs to be tested with unplug, rmmod, SET_CONFIGURATION, and
* SET_INTERFACE (altsetting). Remember also that "configured" doesn't
* imply the host is actually polling the notification endpoint, and
* likewise that "active" doesn't imply it's actually using the data
* endpoints for traffic.
*/
static void ecm_open(struct gether *geth)
{
struct f_ecm *ecm = func_to_ecm(&geth->func);
DBG(ecm->port.func.config->cdev, "%s\n", __func__);
ecm->is_open = true;
ecm_notify(ecm);
}
static void ecm_close(struct gether *geth)
{
struct f_ecm *ecm = func_to_ecm(&geth->func);
DBG(ecm->port.func.config->cdev, "%s\n", __func__);
ecm->is_open = false;
ecm_notify(ecm);
}
/*-------------------------------------------------------------------------*/
/* ethernet function driver setup/binding */
static int
ecm_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct f_ecm *ecm = func_to_ecm(f);
int status;
struct usb_ep *ep;
/* allocate instance-specific interface IDs */
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
ecm->ctrl_id = status;
ecm_iad_descriptor.bFirstInterface = status;
ecm_control_intf.bInterfaceNumber = status;
ecm_union_desc.bMasterInterface0 = status;
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
ecm->data_id = status;
ecm_data_nop_intf.bInterfaceNumber = status;
ecm_data_intf.bInterfaceNumber = status;
ecm_union_desc.bSlaveInterface0 = status;
status = -ENODEV;
/* allocate instance-specific endpoints */
ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_in_desc);
if (!ep)
goto fail;
ecm->port.in_ep = ep;
ep->driver_data = cdev; /* claim */
ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_out_desc);
if (!ep)
goto fail;
ecm->port.out_ep = ep;
ep->driver_data = cdev; /* claim */
/* NOTE: a status/notification endpoint is *OPTIONAL* but we
* don't treat it that way. It's simpler, and some newer CDC
* profiles (wireless handsets) no longer treat it as optional.
*/
ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_notify_desc);
if (!ep)
goto fail;
ecm->notify = ep;
ep->driver_data = cdev; /* claim */
status = -ENOMEM;
/* allocate notification request and buffer */
ecm->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
if (!ecm->notify_req)
goto fail;
ecm->notify_req->buf = kmalloc(ECM_STATUS_BYTECOUNT, GFP_KERNEL);
if (!ecm->notify_req->buf)
goto fail;
ecm->notify_req->context = ecm;
ecm->notify_req->complete = ecm_notify_complete;
/* support all relevant hardware speeds... we expect that when
* hardware is dual speed, all bulk-capable endpoints work at
* both speeds
*/
hs_ecm_in_desc.bEndpointAddress = fs_ecm_in_desc.bEndpointAddress;
hs_ecm_out_desc.bEndpointAddress = fs_ecm_out_desc.bEndpointAddress;
hs_ecm_notify_desc.bEndpointAddress =
fs_ecm_notify_desc.bEndpointAddress;
ss_ecm_in_desc.bEndpointAddress = fs_ecm_in_desc.bEndpointAddress;
ss_ecm_out_desc.bEndpointAddress = fs_ecm_out_desc.bEndpointAddress;
ss_ecm_notify_desc.bEndpointAddress =
fs_ecm_notify_desc.bEndpointAddress;
status = usb_assign_descriptors(f, ecm_fs_function, ecm_hs_function,
ecm_ss_function);
if (status)
goto fail;
/* NOTE: all that is done without knowing or caring about
* the network link ... which is unavailable to this code
* until we're activated via set_alt().
*/
ecm->port.open = ecm_open;
ecm->port.close = ecm_close;
DBG(cdev, "CDC Ethernet: %s speed IN/%s OUT/%s NOTIFY/%s\n",
gadget_is_superspeed(c->cdev->gadget) ? "super" :
gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
ecm->port.in_ep->name, ecm->port.out_ep->name,
ecm->notify->name);
return 0;
fail:
if (ecm->notify_req) {
kfree(ecm->notify_req->buf);
usb_ep_free_request(ecm->notify, ecm->notify_req);
}
/* we might as well release our claims on endpoints */
if (ecm->notify)
ecm->notify->driver_data = NULL;
if (ecm->port.out_ep->desc)
ecm->port.out_ep->driver_data = NULL;
if (ecm->port.in_ep->desc)
ecm->port.in_ep->driver_data = NULL;
ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
return status;
}
static void
ecm_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct f_ecm *ecm = func_to_ecm(f);
DBG(c->cdev, "ecm unbind\n");
usb_free_all_descriptors(f);
kfree(ecm->notify_req->buf);
usb_ep_free_request(ecm->notify, ecm->notify_req);
ecm_string_defs[1].s = NULL;
kfree(ecm);
}
/**
* ecm_bind_config - add CDC Ethernet network link to a configuration
* @c: the configuration to support the network link
* @ethaddr: a buffer in which the ethernet address of the host side
* side of the link was recorded
* Context: single threaded during gadget setup
*
* Returns zero on success, else negative errno.
*
* Caller must have called @gether_setup(). Caller is also responsible
* for calling @gether_cleanup() before module unload.
*/
int
ecm_bind_config(struct usb_configuration *c, u8 ethaddr[ETH_ALEN])
{
struct f_ecm *ecm;
int status;
if (!can_support_ecm(c->cdev->gadget) || !ethaddr)
return -EINVAL;
/* maybe allocate device-global string IDs */
if (ecm_string_defs[0].id == 0) {
/* control interface label */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
ecm_string_defs[0].id = status;
ecm_control_intf.iInterface = status;
/* data interface label */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
ecm_string_defs[2].id = status;
ecm_data_intf.iInterface = status;
/* MAC address */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
ecm_string_defs[1].id = status;
ecm_desc.iMACAddress = status;
/* IAD label */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
ecm_string_defs[3].id = status;
ecm_iad_descriptor.iFunction = status;
}
/* allocate and initialize one new instance */
ecm = kzalloc(sizeof *ecm, GFP_KERNEL);
if (!ecm)
return -ENOMEM;
/* export host's Ethernet address in CDC format */
snprintf(ecm->ethaddr, sizeof ecm->ethaddr,
"%02X%02X%02X%02X%02X%02X",
ethaddr[0], ethaddr[1], ethaddr[2],
ethaddr[3], ethaddr[4], ethaddr[5]);
ecm_string_defs[1].s = ecm->ethaddr;
ecm->port.cdc_filter = DEFAULT_FILTER;
ecm->port.func.name = "cdc_ethernet";
ecm->port.func.strings = ecm_strings;
/* descriptors are per-instance copies */
ecm->port.func.bind = ecm_bind;
ecm->port.func.unbind = ecm_unbind;
ecm->port.func.set_alt = ecm_set_alt;
ecm->port.func.get_alt = ecm_get_alt;
ecm->port.func.setup = ecm_setup;
ecm->port.func.disable = ecm_disable;
status = usb_add_function(c, &ecm->port.func);
if (status) {
ecm_string_defs[1].s = NULL;
kfree(ecm);
}
return status;
}
| ElectryDev/octokitty | drivers/usb/gadget/f_ecm.c | C | gpl-2.0 | 25,682 |
#ifndef __USB3503_H__
#define __USB3503_H__
#define USB3503_I2C_NAME "usb3503"
enum usb3503_mode {
USB3503_MODE_UNKNOWN,
USB3503_MODE_HUB,
USB3503_MODE_STANDBY,
};
enum usb3503_ref_clk {
USB3503_REFCLK_24M,
USB3503_REFCLK_26M,
};
struct usb3503_platform_data {
enum usb3503_mode initial_mode;
enum usb3503_ref_clk ref_clk;
int gpio_intn;
int gpio_connect;
int gpio_reset;
};
#endif
| jepler/odroid-linux | include/linux/platform_data/usb3503.h | C | gpl-2.0 | 397 |
#include "async.h"
class my_resizer_t : public vec_resizer_t {
public:
my_resizer_t () : vec_resizer_t () {}
size_t resize (u_int nalloc, u_int nwanted, int objid);
};
size_t
my_resizer_t::resize (u_int nalloc, u_int nwanted, int objid)
{
int exponent = fls (max (nalloc, nwanted));
int step;
if (exponent < 3) step = 1;
else if (exponent < 8) step = 3;
else if (exponent < 10) step = 2;
else step = 1;
exponent = ((exponent - 1) / step + 1) * step;
size_t ret = 1 << exponent;
// If you want to know the pattern...
warn << "resize: " << nalloc << "," << nwanted << "," << objid
<< " -> " << ret << "\n";
return ret;
}
template<>
struct vec_obj_id_t<int>
{
vec_obj_id_t (){}
int operator() (void) const { return 1; }
};
static void
vec_test (vec<int> &v, int n)
{
for (int i = 0; i < n; i++) {
v.push_back (i);
}
for (int i = n - 1; i >= 0; i--) {
assert (v.pop_back () == i);
}
}
static void
vec_test (void)
{
vec<int> v1, v2;
int n = 100;
vec_test (v1, n);
set_vec_resizer (New my_resizer_t ());
vec_test (v2, n);
}
int
main (int argc, char *argv[])
{
vec_test ();
return 0;
}
| okws/sfslite | tests/test_vec.C | C++ | gpl-2.0 | 1,161 |
/*
Implement Github like autocomplete mentions
http://ichord.github.com/At.js
Copyright (c) 2013 chord.luo@gmail.com
Licensed under the MIT license.
*/
/*
本插件操作 textarea 或者 input 内的插入符
只实现了获得插入符在文本框中的位置,我设置
插入符的位置.
*/
/**
* --------------------
* Vanilla Forums NOTE:
* --------------------
*
* This file has been highly modified to work with iframes, as well
* as custom username handling with quotation marks and spaces for Vanilla.
* Do not just replace with a more current version. At the time of
* development there was no support for iframes, or spaces in names.
* This may have changed, so if you do decide to upgrade this library,
* you're going to have to update the code that uses this library as well.
* It's all wrapped up in a function called `atCompleteInit`.
*/
(function() {
(function(factory) {
if (typeof define === 'function' && define.amd) {
return define(['jquery'], factory);
} else {
return factory(window.jQuery);
}
})(function($) {
"use strict";
////var EditableCaret, InputCaret, Mirror, Utils, methods, pluginName;
var EditableCaret, InputCaret, Mirror, Utils, methods, pluginName, cWin;
pluginName = 'caret';
EditableCaret = (function() {
function EditableCaret($inputor) {
this.$inputor = $inputor;
this.domInputor = this.$inputor[0];
}
EditableCaret.prototype.setPos = function(pos) {
return this.domInputor;
};
EditableCaret.prototype.getIEPosition = function() {
return $.noop();
};
EditableCaret.prototype.getPosition = function() {
return $.noop();
};
EditableCaret.prototype.getOldIEPos = function() {
var preCaretTextRange, textRange;
textRange = document.selection.createRange();
preCaretTextRange = document.body.createTextRange();
preCaretTextRange.moveToElementText(this.domInputor);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
return preCaretTextRange.text.length;
};
EditableCaret.prototype.getPos = function() {
var clonedRange, pos, range;
if (range = this.range()) {
clonedRange = range.cloneRange();
clonedRange.selectNodeContents(this.domInputor);
clonedRange.setEnd(range.endContainer, range.endOffset);
pos = clonedRange.toString().length;
clonedRange.detach();
return pos;
} else if (document.selection) {
return this.getOldIEPos();
}
};
EditableCaret.prototype.getOldIEOffset = function() {
var range, rect;
range = document.selection.createRange().duplicate();
range.moveStart("character", -1);
rect = range.getBoundingClientRect();
return {
height: rect.bottom - rect.top,
left: rect.left,
top: rect.top
};
};
EditableCaret.prototype.getOffset = function(pos) {
var clonedRange, offset, range, rect;
offset = null;
////if (window.getSelection && (range = this.range())) {
if (cWin.getSelection && (range = this.range())) {
if (range.endOffset - 1 < 0) {
return null;
}
clonedRange = range.cloneRange();
clonedRange.setStart(range.endContainer, range.endOffset - 1);
clonedRange.setEnd(range.endContainer, range.endOffset);
rect = clonedRange.getBoundingClientRect();
offset = {
height: rect.height,
left: rect.left + rect.width,
top: rect.top
};
clonedRange.detach();
offset;
} else if (document.selection) {
this.getOldIEOffset();
}
return Utils.adjustOffset(offset, this.$inputor);
};
EditableCaret.prototype.range = function() {
var sel;
////if (!window.getSelection) {
if (!cWin.getSelection) {
return;
}
////sel = window.getSelection();
sel = cWin.getSelection();
if (sel.rangeCount > 0) {
return sel.getRangeAt(0);
} else {
return null;
}
};
return EditableCaret;
})();
InputCaret = (function() {
function InputCaret($inputor) {
this.$inputor = $inputor;
this.domInputor = this.$inputor[0];
}
InputCaret.prototype.getIEPos = function() {
var endRange, inputor, len, normalizedValue, pos, range, textInputRange;
inputor = this.domInputor;
range = document.selection.createRange();
pos = 0;
if (range && range.parentElement() === inputor) {
normalizedValue = inputor.value.replace(/\r\n/g, "\n");
len = normalizedValue.length;
textInputRange = inputor.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
endRange = inputor.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
pos = len;
} else {
pos = -textInputRange.moveStart("character", -len);
}
}
return pos;
};
InputCaret.prototype.getPos = function() {
if (document.selection) {
return this.getIEPos();
} else {
return this.domInputor.selectionStart;
}
};
InputCaret.prototype.setPos = function(pos) {
var inputor, range;
inputor = this.domInputor;
if (document.selection) {
range = inputor.createTextRange();
range.move("character", pos);
range.select();
} else if (inputor.setSelectionRange) {
inputor.setSelectionRange(pos, pos);
}
return inputor;
};
InputCaret.prototype.getIEOffset = function(pos) {
var h, range, textRange, x, y;
textRange = this.domInputor.createTextRange();
if (pos) {
textRange.move('character', pos);
} else {
range = document.selection.createRange();
textRange.moveToBookmark(range.getBookmark());
}
x = textRange.boundingLeft;
y = textRange.boundingTop;
h = textRange.boundingHeight;
return {
left: x,
top: y,
height: h
};
};
InputCaret.prototype.getOffset = function(pos) {
var $inputor, offset, position;
$inputor = this.$inputor;
if (document.selection) {
return Utils.adjustOffset(this.getIEOffset(pos), $inputor);
} else {
offset = $inputor.offset();
position = this.getPosition(pos);
return offset = {
left: offset.left + position.left,
top: offset.top + position.top,
height: position.height
};
}
};
InputCaret.prototype.getPosition = function(pos) {
var $inputor, at_rect, format, html, mirror, start_range;
$inputor = this.$inputor;
format = function(value) {
return value.replace(/</g, '<').replace(/>/g, '>').replace(/`/g, '`').replace(/"/g, '"').replace(/\r\n|\r|\n/g, "<br />");
};
if (pos === void 0) {
pos = this.getPos();
}
start_range = $inputor.val().slice(0, pos);
html = "<span>" + format(start_range) + "</span>";
html += "<span id='caret'>|</span>";
mirror = new Mirror($inputor);
return at_rect = mirror.create(html).rect();
};
InputCaret.prototype.getIEPosition = function(pos) {
var h, inputorOffset, offset, x, y;
offset = this.getIEOffset(pos);
inputorOffset = this.$inputor.offset();
x = offset.left - inputorOffset.left;
y = offset.top - inputorOffset.top;
h = offset.height;
return {
left: x,
top: y,
height: h
};
};
return InputCaret;
})();
Mirror = (function() {
Mirror.prototype.css_attr = ["overflowY", "height", "width", "paddingTop", "paddingLeft", "paddingRight", "paddingBottom", "marginTop", "marginLeft", "marginRight", "marginBottom", "fontFamily", "borderStyle", "borderWidth", "wordWrap", "fontSize", "lineHeight", "overflowX", "text-align"];
function Mirror($inputor) {
this.$inputor = $inputor;
}
Mirror.prototype.mirrorCss = function() {
var css,
_this = this;
css = {
position: 'absolute',
left: -9999,
top: 0,
zIndex: -20000,
'white-space': 'pre-wrap'
};
$.each(this.css_attr, function(i, p) {
return css[p] = _this.$inputor.css(p);
});
return css;
};
Mirror.prototype.create = function(html) {
this.$mirror = $('<div></div>');
this.$mirror.css(this.mirrorCss());
this.$mirror.html(html);
this.$inputor.after(this.$mirror);
return this;
};
Mirror.prototype.rect = function() {
var $flag, pos, rect;
$flag = this.$mirror.find("#caret");
pos = $flag.position();
rect = {
left: pos.left,
top: pos.top,
height: $flag.height()
};
this.$mirror.remove();
return rect;
};
return Mirror;
})();
Utils = {
adjustOffset: function(offset, $inputor) {
if (!offset) {
return;
}
offset.top += $(window).scrollTop() + $inputor.scrollTop();
offset.left += +$(window).scrollLeft() + $inputor.scrollLeft();
return offset;
},
contentEditable: function($inputor) {
return !!($inputor[0].contentEditable && $inputor[0].contentEditable === 'true');
}
};
methods = {
pos: function(pos) {
if (pos) {
return this.setPos(pos);
} else {
return this.getPos();
}
},
position: function(pos) {
if (document.selection) {
return this.getIEPosition(pos);
} else {
return this.getPosition(pos);
}
},
offset: function(pos) {
return this.getOffset(pos);
}
};
////$.fn.caret = function(method) {
$.fn.caret = function(method, aWin) {
var caret;
////
cWin = aWin;
caret = Utils.contentEditable(this) ? new EditableCaret(this) : new InputCaret(this);
if (methods[method]) {
////return methods[method].apply(caret, Array.prototype.slice.call(arguments, 1));
///////return methods[method].apply(caret, Array.prototype.slice.call(arguments, method == 'pos' ? 2 : 1));
return methods[method].apply(caret, Array.prototype.slice.call(arguments, 2));
} else {
return $.error("Method " + method + " does not exist on jQuery.caret");
}
};
$.fn.caret.EditableCaret = EditableCaret;
$.fn.caret.InputCaret = InputCaret;
$.fn.caret.Utils = Utils;
return $.fn.caret.apis = methods;
});
}).call(this);
/*
Implement Github like autocomplete mentions
http://ichord.github.com/At.js
Copyright (c) 2013 chord.luo@gmail.com
Licensed under the MIT license.
*/
(function() {
var __slice = [].slice;
(function(factory) {
if (typeof define === 'function' && define.amd) {
return define(['jquery'], factory);
} else {
return factory(window.jQuery);
}
})(function($) {
var $CONTAINER, Api, App, Atwho, Controller, DEFAULT_CALLBACKS, KEY_CODE, Model, View;
App = (function() {
function App(inputor) {
this.current_flag = null;
this.controllers = {};
this.$inputor = $(inputor);
this.listen();
}
App.prototype.controller = function(at) {
return this.controllers[at || this.current_flag];
};
App.prototype.set_context_for = function(at) {
this.current_flag = at;
return this;
};
App.prototype.reg = function(flag, setting) {
var controller, _base;
controller = (_base = this.controllers)[flag] || (_base[flag] = new Controller(this, flag));
if (setting.alias) {
this.controllers[setting.alias] = controller;
}
controller.init(setting);
return this;
};
App.prototype.listen = function() {
var _this = this;
return this.$inputor.on('keyup.atwho', function(e) {
return _this.on_keyup(e);
}).on('keydown.atwho', function(e) {
return _this.on_keydown(e);
}).on('scroll.atwho', function(e) {
var _ref;
return (_ref = _this.controller()) != null ? _ref.view.hide() : void 0;
}).on('blur.atwho', function(e) {
var c;
if (c = _this.controller()) {
return c.view.hide(c.get_opt("display_timeout"));
}
});
};
App.prototype.dispatch = function() {
var _this = this;
return $.map(this.controllers, function(c) {
if (c.look_up()) {
return _this.set_context_for(c.at);
}
});
};
App.prototype.on_keyup = function(e) {
var _ref;
switch (e.keyCode) {
case KEY_CODE.ESC:
case KEY_CODE.TAB:
case KEY_CODE.ENTER:
e.preventDefault();
if ((_ref = this.controller()) != null) {
_ref.view.hide();
}
break;
case KEY_CODE.DOWN:
case KEY_CODE.UP:
$.noop();
break;
default:
this.dispatch();
}
};
App.prototype.on_keydown = function(e) {
var view, _ref;
view = (_ref = this.controller()) != null ? _ref.view : void 0;
if (!(view && view.visible())) {
return;
}
switch (e.keyCode) {
case KEY_CODE.ESC:
e.preventDefault();
view.hide();
break;
case KEY_CODE.UP:
e.preventDefault();
view.prev();
break;
case KEY_CODE.DOWN:
e.preventDefault();
view.next();
break;
case KEY_CODE.TAB:
case KEY_CODE.ENTER:
if (!view.visible()) {
return;
}
view.choose(e);
break;
default:
$.noop();
}
};
return App;
})();
Controller = (function() {
var uuid, _uuid;
_uuid = 0;
uuid = function() {
return _uuid += 1;
};
function Controller(app, at) {
this.app = app;
this.at = at;
this.$inputor = this.app.$inputor;
this.id = this.$inputor[0].id || uuid();
this.setting = null;
this.query = null;
this.pos = 0;
this.cur_rect = null;
this.range = null;
$CONTAINER.append(this.$el = $("<div id='atwho-ground-" + this.id + "'></div>"));
this.model = new Model(this);
this.view = new View(this);
}
Controller.prototype.init = function(setting) {
this.setting = $.extend({}, this.setting || $.fn.atwho["default"], setting);
this.view.init();
return this.model.reload(this.setting.data);
};
Controller.prototype.call_default = function() {
var args, func_name;
func_name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
try {
return DEFAULT_CALLBACKS[func_name].apply(this, args);
} catch (error) {
return $.error("" + error + " Or maybe At.js doesn't have function " + func_name);
}
};
Controller.prototype.trigger = function(name, data) {
var alias, event_name;
data.push(this);
alias = this.get_opt('alias');
event_name = alias ? "" + name + "-" + alias + ".atwho" : "" + name + ".atwho";
return this.$inputor.trigger(event_name, data);
};
Controller.prototype.callbacks = function(func_name) {
return this.get_opt("callbacks")[func_name] || DEFAULT_CALLBACKS[func_name];
};
Controller.prototype.get_opt = function(at, default_value) {
try {
return this.setting[at];
} catch (e) {
return null;
}
};
Controller.prototype.content = function() {
var result = {
content: null,
offset: 0
};
if (this.$inputor.is('textarea, input')) {
result.content = this.$inputor.val();
} else {
var textNode = $(document.createElement('div'));
var html = this.$inputor.html();
var breaks = /<br(\s+)?(\/)?>/g;
result.offset = html.match(breaks) ? html.match(breaks).length : 0;
textNode.html(html.replace(breaks, "\n"));
result.content = textNode.text();
}
return result;
};
Controller.prototype.catch_query = function() {
var caret_pos, contents, end, query, start, subtext;
contents = this.content();
////caret_pos = this.$inputor.caret('pos');
caret_pos = this.$inputor.caret('pos', this.setting.cWindow) + contents.offset;
subtext = contents.content.slice(0, caret_pos);
query = this.callbacks("matcher").call(this, this.at, subtext, this.get_opt('start_with_space'));
if (typeof query === "string" && query.length <= this.get_opt('max_len', 20)) {
start = caret_pos - query.length;
end = start + query.length;
this.pos = start;
query = {
'text': query.toLowerCase(),
'head_pos': start,
'end_pos': end
};
this.trigger("matched", [this.at, query.text]);
} else {
this.view.hide();
}
return this.query = query;
};
Controller.prototype.rect = function() {
var c, scale_bottom;
/////if (!(c = this.$inputor.caret('offset', this.pos - 1))) {
if (!(c = this.$inputor.caret('offset', this.setting.cWindow, this.pos - 1))) {
return;
}
if (this.$inputor.attr('contentEditable') === 'true') {
c = (this.cur_rect || (this.cur_rect = c)) || c;
}
scale_bottom = document.selection ? 0 : 2;
return {
left: c.left,
top: c.top,
bottom: c.top + c.height + scale_bottom
};
};
Controller.prototype.reset_rect = function() {
if (this.$inputor.attr('contentEditable') === 'true') {
return this.cur_rect = null;
}
};
Controller.prototype.mark_range = function() {
return this.range = this.get_range() || this.get_ie_range();
};
Controller.prototype.clear_range = function() {
return this.range = null;
};
Controller.prototype.get_range = function() {
////return this.range || (window.getSelection ? window.getSelection().getRangeAt(0) : void 0);
var thisWin = this.setting.cWindow;
//////return this.range || (thisWin.getSelection ? thisWin.getSelection().getRangeAt(0) : void 0);
return thisWin.getSelection ? thisWin.getSelection().getRangeAt(0) : (this.range || void 0);
};
Controller.prototype.get_ie_range = function() {
return this.range || (document.selection ? document.selection.createRange() : void 0);
};
Controller.prototype.insert_content_for = function($li) {
var data, data_value, tpl;
data_value = $li.data('value');
tpl = this.get_opt('insert_tpl');
if (this.$inputor.is('textarea, input') || !tpl) {
return data_value;
}
data = $.extend({}, $li.data('item-data'), {
'atwho-data-value': data_value,
'atwho-at': this.at
});
return this.callbacks("tpl_eval").call(this, tpl, data);
};
Controller.prototype.insert = function(content, $li) {
////var $inputor, $insert_node, class_name, content_node, insert_node, pos, range, sel, source, start_str, text;
//////////var $inputor, $insert_node, class_name, content_node, insert_node, pos, range, sel, source, start_str, text, thisWin;
var $inputor, $insert_node, class_name, content_editable, content_node, insert_node, pos, range, sel, source, start_str, text;
$inputor = this.$inputor;
if ($inputor.attr('contentEditable') === 'true') {
//////////
content_editable = '' + /firefox/i.test(navigator.userAgent);
//class_name = "atwho-view-flag atwho-view-flag-" + (this.get_opt('alias') || this.at);
class_name = "vanilla-mention-" + (this.get_opt('alias') || this.at);
//////////content_node = "" + content + "<span contenteditable='false'> <span>";
//////////insert_node = "<span contenteditable='false' class='" + class_name + "'>" + content_node + "</span>";
//content_node = ("" + content + "<span contenteditable='") + content_editable + "'> <span>";
content_node = "" + content + " ";
//content_node = "" + content;
//insert_node = "<span contenteditable='" + content_editable + ("' class='" + class_name + "'>" + content_node + "</span>");
insert_node = '<span class="' + class_name + '">' + content_node + '</span>';
$insert_node = $(insert_node).data('atwho-data-item', $li.data('item-data'));
if (document.selection) {
$insert_node = $("<span contenteditable='true'></span>").html($insert_node);
}
}
if ($inputor.is('textarea, input')) {
content = '' + content;
source = $inputor.val();
start_str = source.slice(0, Math.max(this.query.head_pos - this.at.length, 0));
text = "" + start_str + content + " " + (source.slice(this.query['end_pos'] || 0));
$inputor.val(text);
////$inputor.caret('pos', start_str.length + content.length + 1);
$inputor.caret('pos', this.setting.cWindow, start_str.length + content.length + 1);
} else if (range = this.get_range()) {
////
thisWin = this.setting.cWindow;
pos = range.startOffset - (this.query.end_pos - this.query.head_pos) - this.at.length;
range.setStart(range.endContainer, Math.max(pos, 0));
range.setEnd(range.endContainer, range.endOffset);
range.deleteContents();
range.insertNode(document.createTextNode(content + " "));
//range.insertNode($insert_node[0]);
range.collapse(false);
////sel = window.getSelection();
sel = thisWin.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (range = this.get_ie_range()) {
range.moveStart('character', this.query.end_pos - this.query.head_pos - this.at.length);
///////
range.pasteHTML($insert_node[0]);
range.collapse(false);
range.select();
}
$inputor.focus();
return $inputor.change();
};
Controller.prototype.render_view = function(data) {
var search_key;
search_key = this.get_opt("search_key");
data = this.callbacks("sorter").call(this, this.query.text, data.slice(0, 1001), search_key);
return this.view.render(data.slice(0, this.get_opt('limit')));
};
Controller.prototype.look_up = function() {
var query, _callback;
if (!(query = this.catch_query())) {
return;
}
_callback = function(data) {
if (data && data.length > 0) {
return this.render_view(data);
} else {
return this.view.hide();
}
};
this.model.query(query.text, $.proxy(_callback, this));
return query;
};
return Controller;
})();
Model = (function() {
var _storage;
_storage = {};
function Model(context) {
this.context = context;
this.at = this.context.at;
}
Model.prototype.saved = function() {
return this.fetch() > 0;
};
Model.prototype.query = function(query, callback) {
var data, search_key, _ref;
data = this.fetch();
search_key = this.context.get_opt("search_key");
callback(data = this.context.callbacks('filter').call(this.context, query, data, search_key));
if (!(data && data.length > 0)) {
return (_ref = this.context.callbacks('remote_filter')) != null ? _ref.call(this.context, query, callback) : void 0;
}
};
Model.prototype.fetch = function() {
return _storage[this.at] || [];
};
Model.prototype.save = function(data) {
return _storage[this.at] = this.context.callbacks("before_save").call(this.context, data || []);
};
Model.prototype.load = function(data) {
if (!(this.saved() || !data)) {
return this._load(data);
}
};
Model.prototype.reload = function(data) {
return this._load(data);
};
Model.prototype._load = function(data) {
var _this = this;
if (typeof data === "string") {
return $.ajax(data, {
dataType: "json"
}).done(function(data) {
return _this.save(data);
});
} else {
return this.save(data);
}
};
return Model;
})();
View = (function() {
function View(context) {
this.context = context;
this.$el = $("<div class='atwho-view'><ul class='atwho-view-ul'></ul></div>");
this.timeout_id = null;
this.context.$el.append(this.$el);
this.bind_event();
}
View.prototype.init = function() {
var id;
id = this.context.get_opt("alias") || this.context.at.charCodeAt(0);
return this.$el.attr({
'id': "at-view-" + id
});
};
View.prototype.bind_event = function() {
var $menu,
_this = this;
$menu = this.$el.find('ul');
$menu.on('mouseenter.atwho-view', 'li', function(e) {
$menu.find('.cur').removeClass('cur');
return $(e.currentTarget).addClass('cur');
}).on('click', function(e) {
_this.choose(e);
return e.preventDefault();
});
return this.$el.on('mouseenter.atwho-view', 'ul', function(e) {
return _this.context.mark_range();
}).on('mouseleave.atwho-view', 'ul', function(e) {
return _this.context.clear_range();
});
};
View.prototype.visible = function() {
return this.$el.is(":visible");
};
View.prototype.choose = function(event) {
var $li, content;
if (($li = this.$el.find(".cur")).length) {
event.preventDefault();
content = this.context.insert_content_for($li);
this.context.insert(this.context.callbacks("before_insert").call(this.context, content, $li), $li);
this.context.trigger("inserted", [$li]);
return this.hide();
}
};
View.prototype.reposition = function(rect) {
////var offset;
////if (rect.bottom + this.$el.height() - $(window).scrollTop() > $(window).height()) {
var offset;
////
// Make sure the non-iframe version still references window.
var thisWin = (this.context.setting.cWindow)
? null
: window;
if (rect.bottom + this.$el.height() - $(thisWin).scrollTop() > $(thisWin).height()) {
rect.bottom = rect.top - this.$el.height();
}
offset = {
left: rect.left,
top: rect.bottom
};
this.$el.offset(offset);
return this.context.trigger("reposition", [offset]);
};
View.prototype.next = function() {
var cur, next;
cur = this.$el.find('.cur').removeClass('cur');
next = cur.next();
if (!next.length) {
next = this.$el.find('li:first');
}
return next.addClass('cur');
};
View.prototype.prev = function() {
var cur, prev;
cur = this.$el.find('.cur').removeClass('cur');
prev = cur.prev();
if (!prev.length) {
prev = this.$el.find('li:last');
}
return prev.addClass('cur');
};
View.prototype.show = function() {
var rect;
if (!this.visible()) {
this.$el.show();
}
if (rect = this.context.rect()) {
return this.reposition(rect);
}
};
View.prototype.hide = function(time) {
var callback,
_this = this;
if (isNaN(time && this.visible())) {
this.context.reset_rect();
return this.$el.hide();
} else {
callback = function() {
return _this.hide();
};
clearTimeout(this.timeout_id);
return this.timeout_id = setTimeout(callback, time);
}
};
View.prototype.render = function(list) {
var $li, $ul, item, li, tpl, _i, _len;
if (!$.isArray(list || list.length <= 0)) {
this.hide();
return;
}
this.$el.find('ul').empty();
$ul = this.$el.find('ul');
tpl = this.context.get_opt('tpl');
for (_i = 0, _len = list.length; _i < _len; _i++) {
item = list[_i];
item = $.extend({}, item, {
'atwho-at': this.context.at
});
li = this.context.callbacks("tpl_eval").call(this.context, tpl, item);
$li = $(this.context.callbacks("highlighter").call(this.context, li, this.context.query.text));
$li.data("item-data", item);
$ul.append($li);
}
this.show();
return $ul.find("li:first").addClass("cur");
};
return View;
})();
KEY_CODE = {
DOWN: 40,
UP: 38,
ESC: 27,
TAB: 9,
ENTER: 13
};
DEFAULT_CALLBACKS = {
before_save: function(data) {
var item, _i, _len, _results;
if (!$.isArray(data)) {
return data;
}
_results = [];
for (_i = 0, _len = data.length; _i < _len; _i++) {
item = data[_i];
if ($.isPlainObject(item)) {
_results.push(item);
} else {
_results.push({
name: item
});
}
}
return _results;
},
matcher: function(flag, subtext, should_start_with_space) {
var match, regexp;
flag = flag.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
if (should_start_with_space) {
flag = '(?:^|\\s)' + flag;
}
regexp = new RegExp(flag + '([A-Za-z0-9_\+\-]*)$|' + flag + '([^\\x00-\\xff]*)$', 'gi');
match = regexp.exec(subtext);
if (match) {
return match[2] || match[1];
} else {
return null;
}
},
filter: function(query, data, search_key) {
var item, _i, _len, _results;
_results = [];
for (_i = 0, _len = data.length; _i < _len; _i++) {
item = data[_i];
if (~item[search_key].toLowerCase().indexOf(query)) {
_results.push(item);
}
}
return _results;
},
remote_filter: null,
sorter: function(query, items, search_key) {
var item, _i, _len, _results;
if (!query) {
return items;
}
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
item.atwho_order = item[search_key].toLowerCase().indexOf(query);
if (item.atwho_order > -1) {
_results.push(item);
}
}
return _results.sort(function(a, b) {
return a.atwho_order - b.atwho_order;
});
},
tpl_eval: function(tpl, map) {
try {
return tpl.replace(/\$\{([^\}]*)\}/g, function(tag, key, pos) {
return map[key];
});
} catch (error) {
return "";
}
},
highlighter: function(li, query) {
var regexp;
if (!query) {
return li;
}
regexp = new RegExp(">\\s*(\\w*)(" + query.replace("+", "\\+") + ")(\\w*)\\s*<", 'ig');
return li.replace(regexp, function(str, $1, $2, $3) {
return '> ' + $1 + '<strong>' + $2 + '</strong>' + $3 + ' <';
});
},
before_insert: function(value, $li) {
return value;
}
};
Api = {
load: function(at, data) {
var c;
if (c = this.controller(at)) {
return c.model.load(data);
}
},
getInsertedItemsWithIDs: function(at) {
var c, ids, items;
if (!(c = this.controller(at))) {
return [null, null];
}
if (at) {
at = "-" + (c.get_opt('alias') || c.at);
}
ids = [];
items = $.map(this.$inputor.find("span.atwho-view-flag" + (at || "")), function(item) {
var data;
data = $(item).data('atwho-data-item');
if (ids.indexOf(data.id) > -1) {
return;
}
if (data.id) {
ids.push = data.id;
}
return data;
});
return [ids, items];
},
getInsertedItems: function(at) {
return Api.getInsertedItemsWithIDs.apply(this, [at])[1];
},
getInsertedIDs: function(at) {
return Api.getInsertedItemsWithIDs.apply(this, [at])[0];
},
run: function() {
return this.dispatch();
}
};
Atwho = {
init: function(options) {
var $this, app;
app = ($this = $(this)).data("atwho");
if (!app) {
$this.data('atwho', (app = new App(this)));
}
app.reg(options.at, options);
return this;
}
};
$CONTAINER = $("<div id='atwho-container'></div>");
$.fn.atwho = function(method) {
var result, _args;
_args = arguments;
$('body').append($CONTAINER);
result = null;
this.filter('textarea, input, [contenteditable=true]').each(function() {
//console.log('at inloop');
//console.log(this);
var app;
if (typeof method === 'object' || !method) {
return Atwho.init.apply(this, _args);
} else if (Api[method]) {
if (app = $(this).data('atwho')) {
return result = Api[method].apply(app, Array.prototype.slice.call(_args, 1));
}
} else {
return $.error("Method " + method + " does not exist on jQuery.caret");
}
});
return result || this;
};
return $.fn.atwho["default"] = {
at: void 0,
alias: void 0,
data: null,
tpl: "<li data-value='${atwho-at}${name}'>${name}</li>",
insert_tpl: "<span>${atwho-data-value}</span>",
callbacks: DEFAULT_CALLBACKS,
search_key: "name",
start_with_space: true,
limit: 5,
max_len: 20,
display_timeout: 300,
////
cWindow: window
};
});
}).call(this);
| rwmcoder/Vanilla | js/library/jquery.atwho.js | JavaScript | gpl-2.0 | 35,430 |
/***************************************************************************
NWNXFuncs.cpp - Implementation of the CNWNXFuncs class.
Copyright (C) 2007 Doug Swarin (zac@intertex.net)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***************************************************************************/
#include "NWNXDefenses.h"
int Local_GetIsDeathAttackImmune(CNWSCreatureStats *target, uint8_t immtype, CNWSCreature *attacker)
{
return -1;
}
/* vim: set sw=4: */
| jd28/nwnx2-linux | plugins/defenses/local/l_GetIsDeathAttackImmune.c | C | gpl-2.0 | 1,163 |
/****************************************************************
Siano Mobile Silicon, Inc.
MDTV receiver kernel modules.
Copyright (C) 2006-2010, Erez Cohen
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/>.
****************************************************************/
/*!
\file spibusdrv.c
\brief spi bus driver module
This file contains implementation of the spi bus driver.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <asm/cacheflush.h>
#include "smscoreapi.h"
#include "smsdbg_prn.h"
#include "smsspicommon.h"
#include "smsspiphy.h"
#ifdef MTK_SPI
#include <linux/delay.h>
#include <mach/eint.h>
#include <cust_eint.h>
#include <mach/irqs.h>
#include <linux/io.h> //debug
struct SMSDev_data {
dev_t devt;
spinlock_t spi_lock;
struct spi_device *spi;
struct list_head device_entry;
struct mutex buf_lock;
unsigned char users;
u8 *tx_buf;
u8 *rx_buf;
};
extern struct SMSDev_data* SMSDev;
#endif //MTK_SPI
#ifdef CONFIG_SMP
static struct workqueue_struct *spi_thread_wq=NULL;
static struct work_struct spi_thread_work;
#endif
#define SMS_INTR_PIN 16 /* 0 for nova sip, 26 for vega */
#define TX_BUFFER_SIZE 0x200
//#define RX_BUFFER_SIZE (0x1000 + SPI_PACKET_SIZE + 0x100)
#define NUM_RX_BUFFERS 72
struct _spi_device_st {
struct _spi_dev dev;
void *phy_dev;
struct completion write_operation;
struct list_head tx_queue;
int allocatedPackets;
int padding_allowed;
char *rxbuf;
struct smscore_device_t *coredev;
struct list_head txqueue;
char *txbuf;
dma_addr_t txbuf_phy_addr;
};
struct _smsspi_txmsg {
struct list_head node; /*! internal management */
void *buffer;
size_t size;
int alignment;
int add_preamble;
struct completion completion;
void (*prewrite) (void *);
void (*postwrite) (void *);
};
struct _Msg {
struct SmsMsgHdr_ST hdr;
u32 data[3];
};
struct _spi_device_st *spi_dev;
#ifdef CONFIG_SMP
static void spi_worker_thread(struct work_struct *work);
#else
static void spi_worker_thread(void *arg);
static DECLARE_WORK(spi_work_queue, (void *)spi_worker_thread);
#endif
static u8 smsspi_preamble[] = { 0xa5, 0x5a, 0xe7, 0x7e };
static u8 smsspi_startup[] = { 0, 0, 0xde, 0xc1, 0xa5, 0x51, 0xf1, 0xed };
static u32 default_type = SMS_NOVA_B0;
static u32 intr_pin = SMS_INTR_PIN;
//static u32 intCount = 0; not used
module_param(default_type, int, 0644);
MODULE_PARM_DESC(default_type, "default board type.");
module_param(intr_pin, int, 0644);
MODULE_PARM_DESC(intr_pin, "interrupt pin number.");
/******************************************/
#ifdef CONFIG_SMP
static void spi_worker_thread(struct work_struct *work)
#else
static void spi_worker_thread(void *arg)
#endif
{
struct _spi_device_st *spi_device = spi_dev;
struct _smsspi_txmsg *msg = NULL;
struct _spi_msg txmsg;
//sms_info("worker start");
do {
/* do we have a msg to write ? */
if (!msg && !list_empty(&spi_device->txqueue)) //ÅжÏÁ´±íÊÇ·ñΪ¿Õ
msg = (struct _smsspi_txmsg *)
list_entry(spi_device->txqueue.
next, struct _smsspi_txmsg, node);
if (msg) {
if (msg->add_preamble)
{
txmsg.len =
min(msg->size + sizeof(smsspi_preamble),
(size_t) TX_BUFFER_SIZE);
txmsg.buf = spi_device->txbuf;
txmsg.buf_phy_addr = spi_device->txbuf_phy_addr;
memcpy(txmsg.buf, smsspi_preamble,
sizeof(smsspi_preamble));
memcpy(&txmsg.buf[sizeof(smsspi_preamble)],
msg->buffer,
txmsg.len - sizeof(smsspi_preamble));
msg->add_preamble = 0;
msg->buffer +=
txmsg.len - sizeof(smsspi_preamble);
msg->size -=
txmsg.len - sizeof(smsspi_preamble);
/* zero out the rest of aligned buffer */
memset(&txmsg.buf[txmsg.len], 0,
TX_BUFFER_SIZE - txmsg.len);
smsspi_common_transfer_msg(&spi_device->dev,
&txmsg, 1);
} else {
txmsg.len =
min(msg->size, (size_t) TX_BUFFER_SIZE);
txmsg.buf = spi_device->txbuf;
txmsg.buf_phy_addr = spi_device->txbuf_phy_addr;
memcpy(txmsg.buf, msg->buffer, txmsg.len);
msg->buffer += txmsg.len;
msg->size -= txmsg.len;
/* zero out the rest of aligned buffer */
memset(&txmsg.buf[txmsg.len], 0,
TX_BUFFER_SIZE - txmsg.len);
smsspi_common_transfer_msg(&spi_device->dev,
&txmsg, 0);
}
} else {
smsspi_common_transfer_msg(&spi_device->dev, NULL, 1);
}
/* if there was write, have we finished ? */
if (msg && !msg->size) {
/* call postwrite call back */
if (msg->postwrite)
msg->postwrite(spi_device);
list_del(&msg->node);
complete(&msg->completion);
msg = NULL;
}
/* if there was read, did we read anything ? */
} while (!list_empty(&spi_device->txqueue) || msg);
//sms_info("worker end");
}
static void msg_found(void *context, void *buf, int offset, int len)
{
struct _spi_device_st *spi_device = (struct _spi_device_st *) context;
struct smscore_buffer_t *cb =
(struct smscore_buffer_t
*)(container_of(buf, struct smscore_buffer_t, p));
PDEBUG("entering\n");
cb->offset = offset;
cb->size = len;
/* PERROR ("buffer %p is sent back to core databuf=%p,
offset=%d.\n", cb, cb->p, cb->offset); */
smscore_onresponse(spi_device->coredev, cb);
PDEBUG("exiting\n");
}
//static void smsspi_int_handler(void *context)
static void smsspi_int_handler(void )
{
//struct _spi_device_st *spi_device = (struct _spi_device_st *) context;
// PDEBUG("interrupt\n");
// sms_info("**Interrupt %d", intCount++);
#ifdef CONFIG_SMP
queue_work(spi_thread_wq, &spi_thread_work);
#else
PREPARE_WORK(&spi_work_queue, (void *)spi_worker_thread);
schedule_work(&spi_work_queue);
#endif
#ifdef MTK_SPI
mt65xx_eint_unmask(CUST_EINT_CMMB_NUM);
#endif
}
static int smsspi_queue_message_and_wait(struct _spi_device_st *spi_device,
struct _smsspi_txmsg *msg)
{
init_completion(&msg->completion);
list_add_tail(&msg->node, &spi_device->txqueue);
#ifdef CONFIG_SMP
queue_work(spi_thread_wq, &spi_thread_work);
#else
schedule_work(&spi_work_queue);
#endif
wait_for_completion(&msg->completion);
return 0;
}
#if 0
struct _smsspi_txmsg *msg=NULL;
struct _Msg *Msg=NULL;
#endif
static int smsspi_preload(void *context)
{
#if 1
struct _smsspi_txmsg msg;
struct _spi_device_st *spi_device = (struct _spi_device_st *) context;
/* struct _Msg Msg = {
{
MSG_SMS_SPI_INT_LINE_SET_REQ, 0, HIF_TASK,
sizeof(struct _Msg), 0}, {
0, intr_pin, 0}
};*/
struct _Msg Msg = {
{
MSG_SMS_SPI_INT_LINE_SET_REQ, 151, HIF_TASK,
sizeof(struct _Msg), 0}, {
0, 4, 400}
};
int rc;
prepareForFWDnl(spi_device->phy_dev);
sms_info("Sending SPI init sequence");
msg.buffer = smsspi_startup;
msg.size = sizeof(smsspi_startup);
msg.alignment = 4;
msg.add_preamble = 0;
msg.prewrite = NULL; /* smsspiphy_reduce_clock; */
msg.postwrite = NULL; /* smsspiphy_restore_clock; */
rc = smsspi_queue_message_and_wait(context, &msg);
if (rc < 0) {
sms_err("smsspi_queue_message_and_wait error, rc = %d\n", rc);
return rc;
}
sms_debug("sending MSG_SMS_SPI_INT_LINE_SET_REQ");
msg.buffer = &Msg;
msg.size = sizeof(Msg);
msg.alignment = SPI_PACKET_SIZE;
msg.add_preamble = 1;
rc = smsspi_queue_message_and_wait(context, &msg);
if (rc < 0) {
sms_err("set interrupt line failed, rc = %d\n", rc);
return rc;
}
#else
void* buf_1=(void*) SMSDev->tx_buf;
void* buf_2 =(void*)SMSDev->rx_buf ;
struct _spi_device_st *spi_device = (struct _spi_device_st *) context;
int rc;
//buf_1 = kmalloc(sizeof(struct _smsspi_txmsg) + SMS_DMA_ALIGNMENT, GFP_KERNEL | GFP_DMA);
//buf_2 = kmalloc(sizeof(struct _Msg) + SMS_DMA_ALIGNMENT, GFP_KERNEL | GFP_DMA);
if((buf_1) &&(buf_2))
{
msg = (struct _smsspi_txmsg *)SMS_ALIGN_ADDRESS(buf_1);
Msg = (struct _Msg *)SMS_ALIGN_ADDRESS(buf_2);
Msg->hdr.msgType = MSG_SMS_SPI_INT_LINE_SET_REQ;
Msg->hdr.msgSrcId = 151;
Msg->hdr.msgDstId = HIF_TASK;
Msg->hdr.msgLength = sizeof(struct _Msg);
Msg->hdr.msgFlags = 0;
Msg->data[0] = 0;
Msg->data[1] = 4;
Msg->data[2] = 400;
prepareForFWDnl(spi_device->phy_dev);
sms_info("Sending SPI init sequence");
msg->buffer = smsspi_startup;
msg->size = sizeof(smsspi_startup);
msg->alignment = 4;
msg->add_preamble = 0;
msg->prewrite = NULL; /* smsspiphy_reduce_clock; */
msg->postwrite = NULL; /* smsspiphy_restore_clock; */
sms_log("**msg=%4x",msg);
rc = smsspi_queue_message_and_wait(context, msg);
if (rc < 0) {
sms_err("smsspi_queue_message_and_wait error, rc = %d\n", rc);
return rc;
}
sms_debug("sending MSG_SMS_SPI_INT_LINE_SET_REQ");
sms_info("Sending SPI Set Interrupt command sequence");
msg->buffer = Msg;
msg->size = sizeof(struct _Msg);
msg->alignment = SPI_PACKET_SIZE;
msg->add_preamble = 1;
sms_log("**msg=%4x",msg);
rc = smsspi_queue_message_and_wait(context, msg);
if (rc < 0) {
sms_err("set interrupt line failed, rc = %d\n", rc);
return rc;
}
}
//kfree(buf_1);
//kfree(buf_2);
#endif
return rc;
}
static int smsspi_postload(void *context)
{
struct _spi_device_st *spi_device = (struct _spi_device_st *) context;
int mode = smscore_registry_getmode(spi_device->coredev->devpath);
if ( (mode != DEVICE_MODE_ISDBT) &&
(mode != DEVICE_MODE_ISDBT_BDA) ) {
fwDnlComplete(spi_device->phy_dev, 0);
}
return 0;
}
static int smsspi_write(void *context, void *txbuf, size_t len)
{
struct _smsspi_txmsg msg;
msg.buffer = txbuf;
msg.size = len;
msg.prewrite = NULL;
msg.postwrite = NULL;
//int msgLen, i; not used
if (len > 0x1000) {
/* The FW is the only long message. Do not add preamble,
and do not padd it */
msg.alignment = 4;
msg.add_preamble = 0;
msg.prewrite = smschipreset;
} else {
msg.alignment = SPI_PACKET_SIZE;
msg.add_preamble = 1;
}
// sms_info("Writing message to SPI.\n");
/*
u8 * t_txbuf =(u8*)txbuf;
sms_info("msg hdr: 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x.\n",
((u8 *) t_txbuf)[0], ((u8 *) t_txbuf)[1], ((u8 *) t_txbuf)[2],
((u8 *) t_txbuf)[3], ((u8 *) t_txbuf)[4], ((u8 *) t_txbuf)[5],
((u8 *) t_txbuf)[6], ((u8 *) t_txbuf)[7]);
msgLen = (t_txbuf[5]<<8) + t_txbuf[4];
if((t_txbuf[0]==0x6C) && (t_txbuf[1]==0x03))
{
sms_info("jackz, Set CW REQ, len: %d, payload:", msgLen);
for(i=0; i<(msgLen-8); i++)
{
sms_info("0x%x ", t_txbuf[8+i]);
}
}
if((t_txbuf[0]==0x6E) && (t_txbuf[1]==0x03))
{
sms_info("jackz, Set SaltKey REQ, len: %d, payload:", msgLen);
for(i=0; i<(msgLen-8); i++)
{
sms_info("0x%x ", t_txbuf[8+i]);
}
}
*/
sms_info("Send msg type: %d", (((u8 *) txbuf)[1]<<8) + ((u8 *) txbuf)[0]);
return smsspi_queue_message_and_wait(context, &msg);
}
struct _rx_buffer_st *allocate_rx_buf(void *context, int size)
{
struct smscore_buffer_t *buf;
struct _spi_device_st *spi_device = (struct _spi_device_st *) context;
if (size > RX_BUFFER_SIZE) {
PERROR("Requested size is bigger than max buffer size.\n");
return NULL;
}
buf = smscore_getbuffer(spi_device->coredev);
PDEBUG("Recieved Rx buf %p physical 0x%x (contained in %p)\n", buf->p,
buf->phys, buf);
flush_cache_all();
/* note: this is not mistake! the rx_buffer_st is identical to part of
smscore_buffer_t and we return the address of the start of the
identical part */
return (struct _rx_buffer_st *) &buf->p;
}
static void free_rx_buf(void *context, struct _rx_buffer_st *buf)
{
struct _spi_device_st *spi_device = (struct _spi_device_st *) context;
struct smscore_buffer_t *cb =
(struct smscore_buffer_t
*)(container_of(((void *)buf), struct smscore_buffer_t, p));
PDEBUG("buffer %p is released.\n", cb);
smscore_putbuffer(spi_device->coredev, cb);
}
/*! Release device STUB
\param[in] dev: device control block
\return void
*/
static void smsspi_release(struct device *dev)
{
PDEBUG("nothing to do\n");
/* Nothing to release */
}
static struct platform_device smsspi_device = {
.name = "smsspi",
.id = 1,
.dev = {
.release = smsspi_release,
},
};
int smsspi_register(void)
{
struct smsdevice_params_t params;
int ret;
struct _spi_device_st *spi_device;
struct _spi_dev_cb_st common_cb;
PDEBUG("entering \n");
#ifdef CONFIG_SMP
sms_info("create a signelthread workqueue");
spi_thread_wq = create_singlethread_workqueue("siano work wq");
INIT_WORK(&spi_thread_work, spi_worker_thread);
#endif
spi_device =
kmalloc(sizeof(struct _spi_device_st), GFP_KERNEL);
spi_dev = spi_device;
INIT_LIST_HEAD(&spi_device->txqueue);
ret = platform_device_register(&smsspi_device);
if (ret < 0) {
PERROR("platform_device_register failed\n");
return ret;
}
//
#if 0 //buf issue 1214
spi_device->txbuf =
dma_alloc_coherent(NULL, TX_BUFFER_SIZE,
&spi_device->txbuf_phy_addr,
GFP_KERNEL | GFP_DMA);
#else
spi_device->txbuf =kmalloc(TX_BUFFER_SIZE, GFP_KERNEL);
spi_device->txbuf_phy_addr = (u32)spi_device->txbuf; //? check txbuf_phy_addr is use or not
printk("**** spi_dev->txbuf = 0x %4x",(unsigned int)spi_dev->txbuf);
#endif
if (!spi_device->txbuf) {
printk(KERN_INFO "%s dma_alloc_coherent(...) failed\n",
__func__);
ret = -ENOMEM;
goto txbuf_error;
}
spi_device->phy_dev =
smsspiphy_init(NULL, smsspi_int_handler, (void*)spi_device);
if (spi_device->phy_dev == 0) {
printk(KERN_INFO "%s smsspiphy_init(...) failed\n", __func__);
//goto phy_error;
}
common_cb.allocate_rx_buf = allocate_rx_buf;
common_cb.free_rx_buf = free_rx_buf;
common_cb.msg_found_cb = msg_found;
common_cb.transfer_data_cb = smsspibus_xfer;
ret =
smsspicommon_init(&spi_device->dev, spi_device, spi_device->phy_dev,
&common_cb);
if (ret) {
printk(KERN_INFO "%s smsspiphy_init(...) failed\n", __func__);
goto common_error;
}
/* register in smscore */
memset(¶ms, 0, sizeof(params));
params.context = spi_device;
params.device = &smsspi_device.dev;
params.buffer_size = RX_BUFFER_SIZE;
params.num_buffers = NUM_RX_BUFFERS;
params.flags = SMS_DEVICE_NOT_READY;
params.sendrequest_handler = smsspi_write;
strcpy(params.devpath, "spi");
params.device_type = default_type;
if (0) {
/* device family */
/* params.setmode_handler = smsspi_setmode; */
} else {
params.flags =
SMS_DEVICE_FAMILY2 | SMS_DEVICE_NOT_READY;
params.preload_handler = smsspi_preload;
params.postload_handler = smsspi_postload;
}
ret = smscore_register_device(¶ms, &spi_device->coredev);
if (ret < 0) {
printk(KERN_INFO "%s smscore_register_device(...) failed\n",
__func__);
goto reg_device_error;
}
ret = smscore_start_device(spi_device->coredev);
if (ret < 0) {
printk(KERN_INFO "%s smscore_start_device(...) failed\n",
__func__);
goto start_device_error;
}
PDEBUG("exiting\n");
return 0;
start_device_error:
smscore_unregister_device(spi_device->coredev);
reg_device_error:
common_error:
smsspiphy_deinit(spi_device->phy_dev);
#if 0 // not used
phy_error:
#if 0 //buf issue 1214
/*dma_free_coherent(NULL, TX_BUFFER_SIZE, spi_device->txbuf,
spi_device->txbuf_phy_addr);*/
#else
kfree(spi_device->txbuf);
#endif
#endif
txbuf_error:
platform_device_unregister(&smsspi_device);
PDEBUG("exiting error %d\n", ret);
return ret;
}
void smsspi_unregister(void)
{
struct _spi_device_st *spi_device = spi_dev;
PDEBUG("entering\n");
/* stop interrupts */
smsspiphy_deinit(spi_device->phy_dev);
smscore_unregister_device(spi_device->coredev);
#if 0 //buf issue 1214
dma_free_coherent(NULL, TX_BUFFER_SIZE, spi_device->txbuf,
spi_device->txbuf_phy_addr);
#else
kfree(spi_device->txbuf);
#endif
#ifdef CONFIG_SMP
destroy_workqueue(spi_thread_wq);
#endif
platform_device_unregister(&smsspi_device);
PDEBUG("exiting\n");
}
| laufersteppenwolf/android_kernel_lge_d680 | mediatek/platform/mt6577/kernel/drivers/cmmbdrv/siano/smsspidrv.c | C | gpl-2.0 | 17,003 |
/* This file is part of the KDE libraries
* Copyright (C) 1999 Waldo Bastian <bastian@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License version 2 as published by the Free Software Foundation;
*
* 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; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
**/
#ifndef KSYCOCADICT_H
#define KSYCOCADICT_H
#include <kdecore_export.h>
#include "ksycocaentry.h"
#include <QList>
class QString;
class QDataStream;
/**
* @internal
* Hash table implementation for the sycoca database file
*
* Only exported for the unit test
*/
class KDECORE_EXPORT KSycocaDict //krazy:exclude=dpointer (not const because it gets deleted by clear())
{
public:
/**
* Create an empty dict, for building the database
*/
KSycocaDict();
/**
* Create a dict from an existing database
*/
KSycocaDict(QDataStream *str, int offset);
~KSycocaDict();
/**
* Adds a 'payload' to the dictionary with key 'key'.
*
* 'payload' should have a valid offset by the time
* the dictionary gets saved.
**/
void add(const QString &key, const KSycocaEntry::Ptr& payload);
/**
* Removes the 'payload' from the dictionary with key 'key'.
*
* Not very fast, use with care O(N)
**/
void remove(const QString &key);
/**
* Looks up an entry identified by 'key'.
*
* If 0 is returned, no matching entry exists.
* Otherwise, the offset of the entry is returned.
*
* NOTE: It is not guaranteed that this entry is
* indeed the one you were looking for.
* After loading the entry you should check that it
* indeed matches the search key. If it doesn't
* then no matching entry exists.
*/
int find_string(const QString &key ) const;
/**
* Looks up all entries identified by 'key'.
* This is useful when the dict is used as a multi-hash.
*
* If an empty list is returned, no matching entry exists.
* Otherwise, the offset of the matching entries are returned.
*
* NOTE: It is not guaranteed that each entry is
* indeed among the ones you were looking for.
* After loading each entry you should check that it
* indeed matches the search key.
*/
QList<int> findMultiString(const QString &key ) const;
/**
* The number of entries in the dictionary.
*
* Only valid when building the database.
*/
uint count() const;
/**
* Reset the dictionary.
*
* Only valid when building the database.
*/
void clear();
/**
* Save the dictionary to the stream
* A reasonable fast hash algorithm will be created.
*
* Typically this will find 90% of the entries directly.
* Average hash table size: nrOfItems * 20 bytes.
* Average duplicate list size: nrOfItms * avgKeyLength / 5.
*
* Unknown keys have an average 20% chance to give a false hit.
* (That's why your program should check the result)
*
* Example:
* Assume 1000 items with an average key length of 60 bytes.
*
* Approx. 900 items will hash directly to the right entry.
* Approx. 100 items require a lookup in the duplicate list.
*
* The hash table size will be approx. 20Kb.
* The duplicate list size will be approx. 12Kb.
**/
void save(QDataStream &str);
private:
Q_DISABLE_COPY(KSycocaDict)
class Private;
Private* d;
};
#endif
| ssj-gz/emscripten-kdelibs | kdecore/sycoca/ksycocadict_p.h | C | gpl-2.0 | 3,921 |
/*----------------------------------------------------------------------------------*/
//This code is part of a larger project whose main purpose is to entretain either //
//by working on it and helping it be better or by playing it in it's actual state //
// //
//Copyright (C) 2011 Three Legged Studio //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2, or (at your option) //
// any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software Foundation, //
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. //
// //
// You can contact us at projectpgz.blogspot.com //
/*----------------------------------------------------------------------------------*/
#include "iPushable.h"
iPushable::iPushable(){
init(stepPushDist, useConstraints);
}
iPushable::iPushable(int stepPushDist, bool useConstraints){
init(stepPushDist, useConstraints);
}
void iPushable::init(int stepPushDist, bool useConstraints){
this->stepPushDist = stepPushDist;
this->useConstraints = useConstraints;
locked = false;
}
iPushable::~iPushable(){
}
std::pair<int, int> iPushable::onPush(Entity *ent, Direction dir){
// mover en base al stepPushDist si no estamos locked
if(!locked){
// Mover en las direcciones aceptadas por los constraints
if(useConstraints)
if(pushConstraints.find(dir) != pushConstraints.end()){
return move(ent, dir);
}
else
return make_pair(0, 0);
// Mover sin restricciones
return move(ent, dir);
}
return make_pair(0, 0);
}
void iPushable::lockPush(){
locked = true;
}
void iPushable::unlockPush(){
locked = false;
}
bool iPushable::isLockedPush(){
return locked;
}
void iPushable::setConstraints(set<Direction> pushConstrains){
this->pushConstraints = pushConstrains;
useConstraints = true;
}
std::pair<int, int> iPushable::move(Entity *ent, Direction dir){
int xtemp, ytemp;
int xorig, yorig;
xorig = ent->x;
yorig = ent->y;
switch (dir) {
case UP:
xtemp = ent->x;
ytemp = ent->y-stepPushDist;
break;
case DOWN:
xtemp = ent->x;
ytemp = ent->y+stepPushDist;
break;
case LEFT:
xtemp = ent->x-stepPushDist;
ytemp = ent->y;
break;
case RIGHT:
xtemp = ent->x+stepPushDist;
ytemp = ent->y;
break;
}
if (xtemp == ent->x && ytemp == ent->y)
return make_pair(0, 0);
/*if (ent->world->place_free(ent->x, ytemp, ent)){
ent->y = ytemp;
}
else{
ent->world->moveToContact(ent->x,ytemp, ent);
}
if (ent->world->place_free(xtemp, ent->y, ent)){
ent->x = xtemp;
}
else{
ent->world->moveToContact(xtemp,ent->y, ent);
}*/
if (!ent->world->place_free(xtemp, ytemp, ent))
ent->world->moveToContact(xtemp, ytemp, ent);
else
ent->x = xtemp, ent->y = ytemp;
return make_pair(abs(ent->x - xorig), abs(ent-> y - yorig));
} | rafadelahoz/projectpgz-dev | interprete/source/src/iPushable.cpp | C++ | gpl-2.0 | 3,637 |
/*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package javax.xml.bind.annotation;
public enum XmlAccessType {
FIELD, NONE, PROPERTY, PUBLIC_MEMBER;
}
| mdaniel/svn-caucho-com-resin | modules/jaxb/src/javax/xml/bind/annotation/XmlAccessType.java | Java | gpl-2.0 | 1,117 |
# Copyright (C) 2007 Rising Sun Pictures and Matthew Landauer
#
# 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
class WatchDirectoryKey < ActiveRecord::Migration
def self.up
add_column :servers, :directory_info_id, :integer
remove_column :servers, :watch_directory
end
def self.down
add_column :servers, :watch_directory, :string, :default => "", :null => false
remove_column :servers, :directory_info_id
end
end
| Jonv/earth | db/migrate/014_watch_directory_key.rb | Ruby | gpl-2.0 | 1,094 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.