code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
#ifndef _SIMFIELDDICTIONARY_H_
#define _SIMFIELDDICTIONARY_H_
// Forward Refs
class ConsoleBaseType;
class SimObject;
#include "core/stringTable.h"
#include "core/stream/stream.h"
#ifndef _TORQUE_STRING_H_
#include "core/util/str.h"
#endif
/// Dictionary to keep track of dynamic fields on SimObject.
class SimFieldDictionary
{
friend class SimFieldDictionaryIterator;
public:
struct Entry
{
Entry() : type( NULL ) {};
StringTableEntry slotName;
char *value;
Entry *next;
ConsoleBaseType *type;
};
enum
{
HashTableSize = 19
};
Entry *mHashTable[HashTableSize];
private:
static Entry *smFreeList;
void freeEntry(Entry *entry);
Entry* addEntry( U32 bucket, StringTableEntry slotName, ConsoleBaseType* type, char* value = 0 );
static U32 getHashValue( StringTableEntry slotName );
static U32 getHashValue( const String& fieldName );
U32 mNumFields;
/// In order to efficiently detect when a dynamic field has been
/// added or deleted, we increment this every time we add or
/// remove a field.
U32 mVersion;
public:
const U32 getVersion() const { return mVersion; }
SimFieldDictionary();
~SimFieldDictionary();
void setFieldType(StringTableEntry slotName, const char *typeString);
void setFieldType(StringTableEntry slotName, const U32 typeId);
void setFieldType(StringTableEntry slotName, ConsoleBaseType *type);
void setFieldValue(StringTableEntry slotName, const char *value);
const char *getFieldValue(StringTableEntry slotName);
U32 getFieldType(StringTableEntry slotName) const;
Entry *findDynamicField(const String &fieldName) const;
Entry *findDynamicField( StringTableEntry fieldName) const;
void writeFields(SimObject *obj, Stream &strem, U32 tabStop);
void printFields(SimObject *obj);
void assignFrom(SimFieldDictionary *dict);
U32 getNumFields() const { return mNumFields; }
Entry *operator[](U32 index);
};
class SimFieldDictionaryIterator
{
SimFieldDictionary * mDictionary;
S32 mHashIndex;
SimFieldDictionary::Entry * mEntry;
public:
SimFieldDictionaryIterator(SimFieldDictionary*);
SimFieldDictionary::Entry* operator++();
SimFieldDictionary::Entry* operator*();
};
#endif // _SIMFIELDDICTIONARY_H_
| elfprince13/Torque3D | Engine/source/console/simFieldDictionary.h | C | mit | 3,635 |
// <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.Network
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// HubVirtualNetworkConnectionsOperations operations.
/// </summary>
public partial interface IHubVirtualNetworkConnectionsOperations
{
/// <summary>
/// Creates a hub virtual network connection if it doesn't exist else
/// updates the existing one.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name of the HubVirtualNetworkConnection.
/// </param>
/// <param name='virtualHubName'>
/// The name of the VirtualHub.
/// </param>
/// <param name='connectionName'>
/// The name of the HubVirtualNetworkConnection.
/// </param>
/// <param name='hubVirtualNetworkConnectionParameters'>
/// Parameters supplied to create or update a hub virtual network
/// connection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<HubVirtualNetworkConnection>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualHubName, string connectionName, HubVirtualNetworkConnection hubVirtualNetworkConnectionParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a HubVirtualNetworkConnection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name of the VirtualHub.
/// </param>
/// <param name='virtualHubName'>
/// The name of the VirtualHub.
/// </param>
/// <param name='connectionName'>
/// The name of the HubVirtualNetworkConnection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualHubName, string connectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieves the details of a HubVirtualNetworkConnection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name of the VirtualHub.
/// </param>
/// <param name='virtualHubName'>
/// The name of the VirtualHub.
/// </param>
/// <param name='connectionName'>
/// The name of the vpn connection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<HubVirtualNetworkConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualHubName, string connectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieves the details of all HubVirtualNetworkConnections.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name of the VirtualHub.
/// </param>
/// <param name='virtualHubName'>
/// The name of the VirtualHub.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<HubVirtualNetworkConnection>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a hub virtual network connection if it doesn't exist else
/// updates the existing one.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name of the HubVirtualNetworkConnection.
/// </param>
/// <param name='virtualHubName'>
/// The name of the VirtualHub.
/// </param>
/// <param name='connectionName'>
/// The name of the HubVirtualNetworkConnection.
/// </param>
/// <param name='hubVirtualNetworkConnectionParameters'>
/// Parameters supplied to create or update a hub virtual network
/// connection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<HubVirtualNetworkConnection>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualHubName, string connectionName, HubVirtualNetworkConnection hubVirtualNetworkConnectionParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a HubVirtualNetworkConnection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name of the VirtualHub.
/// </param>
/// <param name='virtualHubName'>
/// The name of the VirtualHub.
/// </param>
/// <param name='connectionName'>
/// The name of the HubVirtualNetworkConnection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualHubName, string connectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieves the details of all HubVirtualNetworkConnections.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<HubVirtualNetworkConnection>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| ayeletshpigelman/azure-sdk-for-net | sdk/network/Microsoft.Azure.Management.Network/src/Generated/IHubVirtualNetworkConnectionsOperations.cs | C# | mit | 10,612 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "py/runtime.h"
#include "py/mphal.h"
#include "extmod/modnetwork.h"
#include "eth.h"
#if defined(MICROPY_HW_ETH_MDC)
#include "lwip/netif.h"
typedef struct _network_lan_obj_t {
mp_obj_base_t base;
eth_t *eth;
} network_lan_obj_t;
STATIC const network_lan_obj_t network_lan_eth0 = { { &network_lan_type }, ð_instance };
STATIC void network_lan_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
network_lan_obj_t *self = MP_OBJ_TO_PTR(self_in);
struct netif *netif = eth_netif(self->eth);
int status = eth_link_status(self->eth);
mp_printf(print, "<ETH %u %u.%u.%u.%u>",
status,
netif->ip_addr.addr & 0xff,
netif->ip_addr.addr >> 8 & 0xff,
netif->ip_addr.addr >> 16 & 0xff,
netif->ip_addr.addr >> 24
);
}
STATIC mp_obj_t network_lan_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 0, 0, false);
const network_lan_obj_t *self = &network_lan_eth0;
eth_init(self->eth, MP_HAL_MAC_ETH0);
return MP_OBJ_FROM_PTR(self);
}
STATIC mp_obj_t network_lan_active(size_t n_args, const mp_obj_t *args) {
network_lan_obj_t *self = MP_OBJ_TO_PTR(args[0]);
if (n_args == 1) {
return mp_obj_new_bool(eth_link_status(self->eth));
} else {
int ret;
if (mp_obj_is_true(args[1])) {
ret = eth_start(self->eth);
} else {
ret = eth_stop(self->eth);
}
if (ret < 0) {
mp_raise_OSError(-ret);
}
return mp_const_none;
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_lan_active_obj, 1, 2, network_lan_active);
STATIC mp_obj_t network_lan_isconnected(mp_obj_t self_in) {
network_lan_obj_t *self = MP_OBJ_TO_PTR(self_in);
return mp_obj_new_bool(eth_link_status(self->eth) == 3);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(network_lan_isconnected_obj, network_lan_isconnected);
STATIC mp_obj_t network_lan_ifconfig(size_t n_args, const mp_obj_t *args) {
network_lan_obj_t *self = MP_OBJ_TO_PTR(args[0]);
return mod_network_nic_ifconfig(eth_netif(self->eth), n_args - 1, args + 1);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_lan_ifconfig_obj, 1, 2, network_lan_ifconfig);
STATIC mp_obj_t network_lan_status(size_t n_args, const mp_obj_t *args) {
network_lan_obj_t *self = MP_OBJ_TO_PTR(args[0]);
(void)self;
if (n_args == 1) {
// No arguments: return link status
return MP_OBJ_NEW_SMALL_INT(eth_link_status(self->eth));
}
mp_raise_ValueError(MP_ERROR_TEXT("unknown status param"));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_lan_status_obj, 1, 2, network_lan_status);
STATIC mp_obj_t network_lan_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
network_lan_obj_t *self = MP_OBJ_TO_PTR(args[0]);
if (kwargs->used == 0) {
// Get config value
if (n_args != 2) {
mp_raise_TypeError(MP_ERROR_TEXT("must query one param"));
}
switch (mp_obj_str_get_qstr(args[1])) {
case MP_QSTR_mac: {
return mp_obj_new_bytes(ð_netif(self->eth)->hwaddr[0], 6);
}
default:
mp_raise_ValueError(MP_ERROR_TEXT("unknown config param"));
}
} else {
// Set config value(s)
if (n_args != 1) {
mp_raise_TypeError(MP_ERROR_TEXT("can't specify pos and kw args"));
}
for (size_t i = 0; i < kwargs->alloc; ++i) {
if (MP_MAP_SLOT_IS_FILLED(kwargs, i)) {
mp_map_elem_t *e = &kwargs->table[i];
switch (mp_obj_str_get_qstr(e->key)) {
case MP_QSTR_trace: {
eth_set_trace(self->eth, mp_obj_get_int(e->value));
break;
}
case MP_QSTR_low_power: {
eth_low_power_mode(self->eth, mp_obj_get_int(e->value));
break;
}
default:
mp_raise_ValueError(MP_ERROR_TEXT("unknown config param"));
}
}
}
return mp_const_none;
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(network_lan_config_obj, 1, network_lan_config);
STATIC const mp_rom_map_elem_t network_lan_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&network_lan_active_obj) },
{ MP_ROM_QSTR(MP_QSTR_isconnected), MP_ROM_PTR(&network_lan_isconnected_obj) },
{ MP_ROM_QSTR(MP_QSTR_ifconfig), MP_ROM_PTR(&network_lan_ifconfig_obj) },
{ MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&network_lan_status_obj) },
{ MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&network_lan_config_obj) },
};
STATIC MP_DEFINE_CONST_DICT(network_lan_locals_dict, network_lan_locals_dict_table);
const mp_obj_type_t network_lan_type = {
{ &mp_type_type },
.name = MP_QSTR_LAN,
.print = network_lan_print,
.make_new = network_lan_make_new,
.locals_dict = (mp_obj_dict_t *)&network_lan_locals_dict,
};
#endif // defined(MICROPY_HW_ETH_MDC)
| bvernoux/micropython | ports/stm32/network_lan.c | C | mit | 6,344 |
/**
* \file
*
* Copyright (c) 2012 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* 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.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef _SAM3XA_SPI0_INSTANCE_
#define _SAM3XA_SPI0_INSTANCE_
/* ========== Register definition for SPI0 peripheral ========== */
#if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
#define REG_SPI0_CR (0x40008000U) /**< \brief (SPI0) Control Register */
#define REG_SPI0_MR (0x40008004U) /**< \brief (SPI0) Mode Register */
#define REG_SPI0_RDR (0x40008008U) /**< \brief (SPI0) Receive Data Register */
#define REG_SPI0_TDR (0x4000800CU) /**< \brief (SPI0) Transmit Data Register */
#define REG_SPI0_SR (0x40008010U) /**< \brief (SPI0) Status Register */
#define REG_SPI0_IER (0x40008014U) /**< \brief (SPI0) Interrupt Enable Register */
#define REG_SPI0_IDR (0x40008018U) /**< \brief (SPI0) Interrupt Disable Register */
#define REG_SPI0_IMR (0x4000801CU) /**< \brief (SPI0) Interrupt Mask Register */
#define REG_SPI0_CSR (0x40008030U) /**< \brief (SPI0) Chip Select Register */
#define REG_SPI0_WPMR (0x400080E4U) /**< \brief (SPI0) Write Protection Control Register */
#define REG_SPI0_WPSR (0x400080E8U) /**< \brief (SPI0) Write Protection Status Register */
#else
#define REG_SPI0_CR (*(WoReg*)0x40008000U) /**< \brief (SPI0) Control Register */
#define REG_SPI0_MR (*(RwReg*)0x40008004U) /**< \brief (SPI0) Mode Register */
#define REG_SPI0_RDR (*(RoReg*)0x40008008U) /**< \brief (SPI0) Receive Data Register */
#define REG_SPI0_TDR (*(WoReg*)0x4000800CU) /**< \brief (SPI0) Transmit Data Register */
#define REG_SPI0_SR (*(RoReg*)0x40008010U) /**< \brief (SPI0) Status Register */
#define REG_SPI0_IER (*(WoReg*)0x40008014U) /**< \brief (SPI0) Interrupt Enable Register */
#define REG_SPI0_IDR (*(WoReg*)0x40008018U) /**< \brief (SPI0) Interrupt Disable Register */
#define REG_SPI0_IMR (*(RoReg*)0x4000801CU) /**< \brief (SPI0) Interrupt Mask Register */
#define REG_SPI0_CSR (*(RwReg*)0x40008030U) /**< \brief (SPI0) Chip Select Register */
#define REG_SPI0_WPMR (*(RwReg*)0x400080E4U) /**< \brief (SPI0) Write Protection Control Register */
#define REG_SPI0_WPSR (*(RoReg*)0x400080E8U) /**< \brief (SPI0) Write Protection Status Register */
#endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#endif /* _SAM3XA_SPI0_INSTANCE_ */
| grub4android/lk | platform/sam3/cmsis/sam3x/include/instance/instance_spi0.h | C | mit | 4,026 |
import * as React from 'react';
import { render } from 'react-dom';
import BootstrapTable, {
ColumnFormatter,
CellAlignment,
HeaderFormatter,
ColumnDescription,
RowSelectionType,
ROW_SELECT_SINGLE,
ExpandRowProps,
ColumnSortCaret,
HeaderSortingClasses,
} from 'react-bootstrap-table-next';
interface Product {
id: number;
name: string;
price?: number;
quality?: number;
inStockStatus?: number;
sales?: number;
}
const products: Product[] = [
{
id: 1,
name: 'Item name 1',
price: 100,
},
{
id: 2,
name: 'Item name 2',
price: 100,
},
];
const priceHeaderFormatter: HeaderFormatter<Product> = (column, colIndex, components) => {
return (
<div>
{column.text}
{components.sortElement}
{components.filterElement}
</div>
);
};
const priceFormatter: ColumnFormatter<Product, { indexSquare: number }> = (cell, row, rowIndex) => {
return (
<span>
{rowIndex} - {cell}
</span>
);
};
const SortCaret: ColumnSortCaret = (order, column) => {
switch (order) {
case 'asc':
return '▲';
case 'desc':
return '▼';
default:
return null;
}
};
const headerSortingClasses: HeaderSortingClasses = (column, sortOrder, isLastSorting, colIndex) =>
sortOrder === 'asc' || sortOrder === 'desc' ? 'sort-active' : '';
const productColumns: Array<ColumnDescription<Product>> = [
{ dataField: 'id', align: 'center', sort: true, text: 'Product ID' },
{ dataField: 'name', align: 'center', sort: true, text: 'Product Name' },
{
isDummyField: true,
dataField: '',
sort: true,
sortCaret: SortCaret,
text: 'Product Name',
headerSortingClasses,
},
{
dataField: 'price',
sort: true,
formatter: priceFormatter,
text: 'Product Price',
headerFormatter: priceHeaderFormatter,
},
/**
* test optional dataField for dummyFields
*/
{
isDummyField: true,
dataField: '',
sort: true,
formatter: priceFormatter,
text: 'Product Price',
headerFormatter: priceHeaderFormatter,
},
];
/**
* Basic table test with custom header and cell formatters
*/
render(
<BootstrapTable data={products} bootstrap4 striped={true} hover={true} keyField="id" columns={productColumns} />,
document.getElementById('app'),
);
/**
* Inline untyped columns test
*/
render(
<BootstrapTable
data={products}
bootstrap4
striped={true}
hover={true}
keyField="id"
columns={[
{ dataField: 'id', align: 'center', sort: true, text: 'Product ID' },
{ dataField: 'name', align: 'center', sort: true, text: 'Product Name' },
{
isDummyField: true,
dataField: '',
sort: true,
formatter: () => <span>Dummy Field</span>,
text: 'Dummy Columns',
},
{
dataField: 'price',
sort: true,
formatter: priceFormatter,
text: 'Product Price',
headerFormatter: priceHeaderFormatter,
},
/**
* test optional dataField for dummyFields
*/
{
isDummyField: true,
dataField: '',
sort: true,
formatter: priceFormatter,
text: 'Product Price',
headerFormatter: priceHeaderFormatter,
},
]}
/>,
document.getElementById('app'),
);
/**
* Basic table with custom data indicator and caption
*/
render(
<BootstrapTable
data={products}
bootstrap4
striped={true}
hover={true}
keyField="id"
noDataIndication={() => <div>No data available</div>}
caption={<span>Amazing table</span>}
columns={productColumns}
/>,
document.getElementById('app'),
);
/**
* Basic table with function returning string noDataIndication
*/
render(
<BootstrapTable
data={products}
bootstrap4
keyField="id"
noDataIndication={() => 'No data available'}
columns={productColumns}
/>,
document.getElementById('app'),
);
/**
* Basic table with string noDataIndication
*/
render(
<BootstrapTable
data={products}
bootstrap4
keyField="id"
noDataIndication="No data available"
columns={productColumns}
/>,
document.getElementById('app'),
);
/**
* Basic table with JSX element noDataIndication
*/
render(
<BootstrapTable
data={products}
bootstrap4
keyField="id"
noDataIndication={<div>No data available</div>}
columns={productColumns}
/>,
document.getElementById('app'),
);
/**
* Basic table with custom data indicator and caption
*/
render(
<BootstrapTable
data={products}
bootstrap4
keyField="id"
columns={productColumns}
selectRow={{
mode: ROW_SELECT_SINGLE,
}}
/>,
document.getElementById('app'),
);
/**
* Event handling table test
*/
render(
<BootstrapTable
data={products}
rowEvents={{
onClick: (e, row, rowIndex) => {
typeof row.inStockStatus === 'number';
},
onDoubleClick: (e, row, rowIndex) => {},
onMouseEnter: (e, row, rowIndex) => {},
onMouseLeave: (e, row, rowIndex) => {},
}}
keyField="id"
columns={productColumns}
/>,
document.getElementById('app'),
);
interface UserWithStringId {
id: string;
name: string;
description: string;
}
const usersWithStringIds: UserWithStringId[] = [
{ id: '1', name: 'Jeremy', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.' },
{ id: '2', name: 'Richard', description: 'Pellentesque gravida eros nulla, vitae dignissim urna laoreet nec.' },
{ id: '3', name: 'James', description: 'Phasellus fermentum interdum venenatis.' },
{ id: '4', name: 'Stig', description: 'Nulla feugiat pharetra eleifend.' },
];
// test expandRow when string is key type
render(
<BootstrapTable<UserWithStringId, string>
data={usersWithStringIds}
keyField="id"
columns={[
{ text: 'ID', dataField: 'id' },
{ text: 'Name', dataField: 'name' },
]}
expandRow={{
renderer: (row: UserWithStringId) => <p>{row.description}</p>,
nonExpandable: ['2', '4'],
expanded: ['1', '3'],
}}
/>,
document.getElementById('app'),
);
interface UserWithNumberId {
id: number;
name: string;
description: string;
}
const usersWithNumberIds: UserWithNumberId[] = [
{ id: 1, name: 'Jeremy', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.' },
{ id: 2, name: 'Richard', description: 'Pellentesque gravida eros nulla, vitae dignissim urna laoreet nec.' },
{ id: 3, name: 'James', description: 'Phasellus fermentum interdum venenatis.' },
{ id: 4, name: 'Stig', description: 'Nulla feugiat pharetra eleifend.' },
];
// test expandRow when key is of default type
render(
<BootstrapTable<UserWithNumberId>
data={usersWithNumberIds}
keyField="id"
columns={[
{ text: 'ID', dataField: 'id' },
{ text: 'Name', dataField: 'name' },
]}
expandRow={{
renderer: (row: UserWithNumberId) => <p>{row.description}</p>,
nonExpandable: [2, 4],
expanded: [1, 3],
}}
/>,
document.getElementById('app'),
);
// test expandRow when key is of explicitly declared number type
render(
<BootstrapTable<UserWithNumberId, number>
data={usersWithNumberIds}
keyField="id"
columns={[
{ text: 'ID', dataField: 'id' },
{ text: 'Name', dataField: 'name' },
]}
expandRow={{
renderer: (row: UserWithNumberId) => <p>{row.description}</p>,
nonExpandable: [2, 4],
expanded: [1, 3],
}}
/>,
document.getElementById('app'),
);
const expandRow: ExpandRowProps<Product> = {
renderer: (row: Product) => {
return <div></div>;
},
expanded: [1, 2],
onExpand: (row, isExpand, rowIndex, e) => <div></div>,
onExpandAll: (isExpandAll, results) => <div></div>,
showExpandColumn: true,
expandColumnPosition: 'right',
expandByColumnOnly: true,
expandHeaderColumnRenderer: ({ isAnyExpands }) => <br />,
expandColumnRenderer: ({ expanded }) => <br />,
};
| mcliment/DefinitelyTyped | types/react-bootstrap-table-next/react-bootstrap-table-next-tests.tsx | TypeScript | mit | 8,858 |
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/db_iter.h"
#include "db/filename.h"
#include "db/dbformat.h"
#include "leveldb/env.h"
#include "leveldb/iterator.h"
#include "leveldb/perf_count.h"
#include "port/port.h"
#include "util/logging.h"
#include "util/mutexlock.h"
namespace leveldb {
#if 0
static void DumpInternalIter(Iterator* iter) {
for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
ParsedInternalKey k;
if (!ParseInternalKey(iter->key(), &k)) {
fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str());
} else {
fprintf(stderr, "@ '%s'\n", k.DebugString().c_str());
}
}
}
#endif
namespace {
// Memtables and sstables that make the DB representation contain
// (userkey,seq,type) => uservalue entries. DBIter
// combines multiple entries for the same userkey found in the DB
// representation into a single entry while accounting for sequence
// numbers, deletion markers, overwrites, etc.
class DBIter: public Iterator {
public:
// Which direction is the iterator currently moving?
// (1) When moving forward, the internal iterator is positioned at
// the exact entry that yields this->key(), this->value()
// (2) When moving backwards, the internal iterator is positioned
// just before all entries whose user key == this->key().
enum Direction {
kForward,
kReverse
};
DBIter(const std::string* dbname, Env* env,
const Comparator* cmp, Iterator* iter, SequenceNumber s)
: dbname_(dbname),
env_(env),
user_comparator_(cmp),
iter_(iter),
sequence_(s),
direction_(kForward),
valid_(false) {
}
virtual ~DBIter() {
gPerfCounters->Inc(ePerfIterDelete);
delete iter_;
}
virtual bool Valid() const { return valid_; }
virtual Slice key() const {
assert(valid_);
return (direction_ == kForward) ? ExtractUserKey(iter_->key()) : saved_key_;
}
virtual Slice value() const {
assert(valid_);
return (direction_ == kForward) ? iter_->value() : saved_value_;
}
virtual Status status() const {
if (status_.ok()) {
return iter_->status();
} else {
return status_;
}
}
virtual void Next();
virtual void Prev();
virtual void Seek(const Slice& target);
virtual void SeekToFirst();
virtual void SeekToLast();
private:
void FindNextUserEntry(bool skipping, std::string* skip);
void FindPrevUserEntry();
bool ParseKey(ParsedInternalKey* key);
inline void SaveKey(const Slice& k, std::string* dst) {
dst->assign(k.data(), k.size());
}
inline void ClearSavedValue() {
if (saved_value_.capacity() > 1048576) {
std::string empty;
swap(empty, saved_value_);
} else {
saved_value_.clear();
}
}
const std::string* const dbname_;
Env* const env_;
const Comparator* const user_comparator_;
Iterator* const iter_;
SequenceNumber const sequence_;
Status status_;
std::string saved_key_; // == current key when direction_==kReverse
std::string saved_value_; // == current raw value when direction_==kReverse
Direction direction_;
bool valid_;
// No copying allowed
DBIter(const DBIter&);
void operator=(const DBIter&);
};
inline bool DBIter::ParseKey(ParsedInternalKey* ikey) {
if (!ParseInternalKey(iter_->key(), ikey)) {
status_ = Status::Corruption("corrupted internal key in DBIter");
return false;
} else {
return true;
}
}
void DBIter::Next() {
assert(valid_);
gPerfCounters->Inc(ePerfIterNext);
if (direction_ == kReverse) { // Switch directions?
direction_ = kForward;
// iter_ is pointing just before the entries for this->key(),
// so advance into the range of entries for this->key() and then
// use the normal skipping code below.
if (!iter_->Valid()) {
iter_->SeekToFirst();
} else {
iter_->Next();
}
if (!iter_->Valid()) {
valid_ = false;
saved_key_.clear();
return;
}
}
// Temporarily use saved_key_ as storage for key to skip.
std::string* skip = &saved_key_;
SaveKey(ExtractUserKey(iter_->key()), skip);
FindNextUserEntry(true, skip);
}
void DBIter::FindNextUserEntry(bool skipping, std::string* skip) {
// Loop until we hit an acceptable entry to yield
assert(iter_->Valid());
assert(direction_ == kForward);
do {
ParsedInternalKey ikey;
if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
switch (ikey.type) {
case kTypeDeletion:
// Arrange to skip all upcoming entries for this key since
// they are hidden by this deletion.
SaveKey(ikey.user_key, skip);
skipping = true;
break;
case kTypeValue:
if (skipping &&
user_comparator_->Compare(ikey.user_key, *skip) <= 0) {
// Entry hidden
} else {
valid_ = true;
saved_key_.clear();
return;
}
break;
}
}
iter_->Next();
} while (iter_->Valid());
saved_key_.clear();
valid_ = false;
}
void DBIter::Prev() {
assert(valid_);
gPerfCounters->Inc(ePerfIterPrev);
if (direction_ == kForward) { // Switch directions?
// iter_ is pointing at the current entry. Scan backwards until
// the key changes so we can use the normal reverse scanning code.
assert(iter_->Valid()); // Otherwise valid_ would have been false
SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
while (true) {
iter_->Prev();
if (!iter_->Valid()) {
valid_ = false;
saved_key_.clear();
ClearSavedValue();
return;
}
if (user_comparator_->Compare(ExtractUserKey(iter_->key()),
saved_key_) < 0) {
break;
}
}
direction_ = kReverse;
}
FindPrevUserEntry();
}
void DBIter::FindPrevUserEntry() {
assert(direction_ == kReverse);
ValueType value_type = kTypeDeletion;
if (iter_->Valid()) {
do {
ParsedInternalKey ikey;
if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
if ((value_type != kTypeDeletion) &&
user_comparator_->Compare(ikey.user_key, saved_key_) < 0) {
// We encountered a non-deleted value in entries for previous keys,
break;
}
value_type = ikey.type;
if (value_type == kTypeDeletion) {
saved_key_.clear();
ClearSavedValue();
} else {
Slice raw_value = iter_->value();
if (saved_value_.capacity() > raw_value.size() + 1048576) {
std::string empty;
swap(empty, saved_value_);
}
SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
saved_value_.assign(raw_value.data(), raw_value.size());
}
}
iter_->Prev();
} while (iter_->Valid());
}
if (value_type == kTypeDeletion) {
// End
valid_ = false;
saved_key_.clear();
ClearSavedValue();
direction_ = kForward;
} else {
valid_ = true;
}
}
void DBIter::Seek(const Slice& target) {
gPerfCounters->Inc(ePerfIterSeek);
direction_ = kForward;
ClearSavedValue();
saved_key_.clear();
AppendInternalKey(
&saved_key_, ParsedInternalKey(target, sequence_, kValueTypeForSeek));
iter_->Seek(saved_key_);
if (iter_->Valid()) {
FindNextUserEntry(false, &saved_key_ /* temporary storage */);
} else {
valid_ = false;
}
}
void DBIter::SeekToFirst() {
gPerfCounters->Inc(ePerfIterSeekFirst);
direction_ = kForward;
ClearSavedValue();
iter_->SeekToFirst();
if (iter_->Valid()) {
FindNextUserEntry(false, &saved_key_ /* temporary storage */);
} else {
valid_ = false;
}
}
void DBIter::SeekToLast() {
gPerfCounters->Inc(ePerfIterSeekLast);
direction_ = kReverse;
ClearSavedValue();
iter_->SeekToLast();
FindPrevUserEntry();
}
} // anonymous namespace
Iterator* NewDBIterator(
const std::string* dbname,
Env* env,
const Comparator* user_key_comparator,
Iterator* internal_iter,
const SequenceNumber& sequence) {
return new DBIter(dbname, env, user_key_comparator, internal_iter, sequence);
}
} // namespace leveldb
| CryptoDJ/BitcoinTX | src/leveldb/db/db_iter.cc | C++ | mit | 8,358 |
<!doctype html>
<html>
<title>npm-run-script</title>
<meta http-equiv="content-type" value="text/html;utf-8">
<link rel="stylesheet" type="text/css" href="../../static/style.css">
<link rel="canonical" href="https://www.npmjs.org/doc/cli/npm-run-script.html">
<script async=true src="../../static/toc.js"></script>
<body>
<div id="wrapper">
<h1><a href="../cli/npm-run-script.html">npm-run-script</a></h1> <p>Run arbitrary package scripts</p>
<h2 id="SYNOPSIS">SYNOPSIS</h2>
<pre><code>npm run-script [<pkg>] <command></code></pre>
<h2 id="DESCRIPTION">DESCRIPTION</h2>
<p>This runs an arbitrary command from a package's <code>"scripts"</code> object.
If no package name is provided, it will search for a <code>package.json</code>
in the current folder and use its <code>"scripts"</code> object.</p>
<p>It is used by the test, start, restart, and stop commands, but can be
called directly, as well.</p>
<h2 id="SEE-ALSO">SEE ALSO</h2>
<ul><li><a href="../misc/npm-scripts.html">npm-scripts(7)</a></li><li><a href="../cli/npm-test.html">npm-test(1)</a></li><li><a href="../cli/npm-start.html">npm-start(1)</a></li><li><a href="../cli/npm-restart.html">npm-restart(1)</a></li><li><a href="../cli/npm-stop.html">npm-stop(1)</a></li></ul>
</div>
<table border=0 cellspacing=0 cellpadding=0 id=npmlogo>
<tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18> </td></tr>
<tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td colspan=6 style="width:60px;height:10px;background:#fff"> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td></tr>
<tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2> </td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff" rowspan=2> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff"> </td></tr>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
<p id="footer">npm-run-script — [email protected]</p>
| cloxp/cloxp-install | win/node_modules/npm/html/doc/cli/npm-run-script.html | HTML | mit | 3,459 |
<?php namespace Illuminate\Filesystem;
use FilesystemIterator;
use Symfony\Component\Finder\Finder;
class Filesystem {
/**
* Determine if a file exists.
*
* @param string $path
* @return bool
*/
public function exists($path)
{
return file_exists($path);
}
/**
* Get the contents of a file.
*
* @param string $path
* @return string
*
* @throws FileNotFoundException
*/
public function get($path)
{
if ($this->isFile($path)) return file_get_contents($path);
throw new FileNotFoundException("File does not exist at path {$path}");
}
/**
* Get the returned value of a file.
*
* @param string $path
* @return mixed
*
* @throws FileNotFoundException
*/
public function getRequire($path)
{
if ($this->isFile($path)) return require $path;
throw new FileNotFoundException("File does not exist at path {$path}");
}
/**
* Require the given file once.
*
* @param string $file
* @return mixed
*/
public function requireOnce($file)
{
require_once $file;
}
/**
* Write the contents of a file.
*
* @param string $path
* @param string $contents
* @return int
*/
public function put($path, $contents)
{
return file_put_contents($path, $contents);
}
/**
* Prepend to a file.
*
* @param string $path
* @param string $data
* @return int
*/
public function prepend($path, $data)
{
if ($this->exists($path))
{
return $this->put($path, $data.$this->get($path));
}
else
{
return $this->put($path, $data);
}
}
/**
* Append to a file.
*
* @param string $path
* @param string $data
* @return int
*/
public function append($path, $data)
{
return file_put_contents($path, $data, FILE_APPEND);
}
/**
* Delete the file at a given path.
*
* @param string|array $paths
* @return bool
*/
public function delete($paths)
{
$paths = is_array($paths) ? $paths : func_get_args();
$success = true;
foreach ($paths as $path) { if ( ! @unlink($path)) $success = false; }
return $success;
}
/**
* Move a file to a new location.
*
* @param string $path
* @param string $target
* @return bool
*/
public function move($path, $target)
{
return rename($path, $target);
}
/**
* Copy a file to a new location.
*
* @param string $path
* @param string $target
* @return bool
*/
public function copy($path, $target)
{
return copy($path, $target);
}
/**
* Extract the file extension from a file path.
*
* @param string $path
* @return string
*/
public function extension($path)
{
return pathinfo($path, PATHINFO_EXTENSION);
}
/**
* Get the file type of a given file.
*
* @param string $path
* @return string
*/
public function type($path)
{
return filetype($path);
}
/**
* Get the file size of a given file.
*
* @param string $path
* @return int
*/
public function size($path)
{
return filesize($path);
}
/**
* Get the file's last modification time.
*
* @param string $path
* @return int
*/
public function lastModified($path)
{
return filemtime($path);
}
/**
* Determine if the given path is a directory.
*
* @param string $directory
* @return bool
*/
public function isDirectory($directory)
{
return is_dir($directory);
}
/**
* Determine if the given path is writable.
*
* @param string $path
* @return bool
*/
public function isWritable($path)
{
return is_writable($path);
}
/**
* Determine if the given path is a file.
*
* @param string $file
* @return bool
*/
public function isFile($file)
{
return is_file($file);
}
/**
* Find path names matching a given pattern.
*
* @param string $pattern
* @param int $flags
* @return array
*/
public function glob($pattern, $flags = 0)
{
return glob($pattern, $flags);
}
/**
* Get an array of all files in a directory.
*
* @param string $directory
* @return array
*/
public function files($directory)
{
$glob = glob($directory.'/*');
if ($glob === false) return array();
// To get the appropriate files, we'll simply glob the directory and filter
// out any "files" that are not truly files so we do not end up with any
// directories in our list, but only true files within the directory.
return array_filter($glob, function($file)
{
return filetype($file) == 'file';
});
}
/**
* Get all of the files from the given directory (recursive).
*
* @param string $directory
* @return array
*/
public function allFiles($directory)
{
return iterator_to_array(Finder::create()->files()->in($directory), false);
}
/**
* Get all of the directories within a given directory.
*
* @param string $directory
* @return array
*/
public function directories($directory)
{
$directories = array();
foreach (Finder::create()->in($directory)->directories()->depth(0) as $dir)
{
$directories[] = $dir->getPathname();
}
return $directories;
}
/**
* Create a directory.
*
* @param string $path
* @param int $mode
* @param bool $recursive
* @param bool $force
* @return bool
*/
public function makeDirectory($path, $mode = 0755, $recursive = false, $force = false)
{
if ($force)
{
return @mkdir($path, $mode, $recursive);
}
else
{
return mkdir($path, $mode, $recursive);
}
}
/**
* Copy a directory from one location to another.
*
* @param string $directory
* @param string $destination
* @param int $options
* @return bool
*/
public function copyDirectory($directory, $destination, $options = null)
{
if ( ! $this->isDirectory($directory)) return false;
$options = $options ?: FilesystemIterator::SKIP_DOTS;
// If the destination directory does not actually exist, we will go ahead and
// create it recursively, which just gets the destination prepared to copy
// the files over. Once we make the directory we'll proceed the copying.
if ( ! $this->isDirectory($destination))
{
$this->makeDirectory($destination, 0777, true);
}
$items = new FilesystemIterator($directory, $options);
foreach ($items as $item)
{
// As we spin through items, we will check to see if the current file is actually
// a directory or a file. When it is actually a directory we will need to call
// back into this function recursively to keep copying these nested folders.
$target = $destination.'/'.$item->getBasename();
if ($item->isDir())
{
$path = $item->getPathname();
if ( ! $this->copyDirectory($path, $target, $options)) return false;
}
// If the current items is just a regular file, we will just copy this to the new
// location and keep looping. If for some reason the copy fails we'll bail out
// and return false, so the developer is aware that the copy process failed.
else
{
if ( ! $this->copy($item->getPathname(), $target)) return false;
}
}
return true;
}
/**
* Recursively delete a directory.
*
* The directory itself may be optionally preserved.
*
* @param string $directory
* @param bool $preserve
* @return bool
*/
public function deleteDirectory($directory, $preserve = false)
{
if ( ! $this->isDirectory($directory)) return false;
$items = new FilesystemIterator($directory);
foreach ($items as $item)
{
// If the item is a directory, we can just recurse into the function and
// delete that sub-directory otherwise we'll just delete the file and
// keep iterating through each file until the directory is cleaned.
if ($item->isDir())
{
$this->deleteDirectory($item->getPathname());
}
// If the item is just a file, we can go ahead and delete it since we're
// just looping through and waxing all of the files in this directory
// and calling directories recursively, so we delete the real path.
else
{
$this->delete($item->getPathname());
}
}
if ( ! $preserve) @rmdir($directory);
return true;
}
/**
* Empty the specified directory of all files and folders.
*
* @param string $directory
* @return bool
*/
public function cleanDirectory($directory)
{
return $this->deleteDirectory($directory, true);
}
}
| Kurone-chan/CourseBoard | vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php | PHP | mit | 8,244 |
// write-unit8.js
var constant = exports.uint8 = new Array(256);
for (var i = 0x00; i <= 0xFF; i++) {
constant[i] = write0(i);
}
function write0(type) {
return function(encoder) {
var offset = encoder.reserve(1);
encoder.buffer[offset] = type;
};
}
| february29/Learning | web/vue/AccountBook-Express/node_modules/msgpack-lite/lib/write-uint8.js | JavaScript | mit | 266 |
define( [
, './threex.effectcomposer'
, '../../vendor/three.js/examples/js/postprocessing/EffectComposer'
, '../../vendor/three.js/examples/js/postprocessing/BloomPass'
, '../../vendor/three.js/examples/js/postprocessing/DotScreenPass'
, '../../vendor/three.js/examples/js/postprocessing/FilmPass'
, '../../vendor/three.js/examples/js/postprocessing/MaskPass'
, '../../vendor/three.js/examples/js/postprocessing/RenderPass'
, '../../vendor/three.js/examples/js/postprocessing/SavePass'
, '../../vendor/three.js/examples/js/postprocessing/ShaderPass'
, '../../vendor/three.js/examples/js/postprocessing/TexturePass'
, '../../vendor/three.js/examples/js/shaders/BleachBypassShader'
, '../../vendor/three.js/examples/js/shaders/BlendShader'
, '../../vendor/three.js/examples/js/shaders/CopyShader'
, '../../vendor/three.js/examples/js/shaders/ColorifyShader'
, '../../vendor/three.js/examples/js/shaders/ConvolutionShader'
, '../../vendor/three.js/examples/js/shaders/FilmShader'
, '../../vendor/three.js/examples/js/shaders/FXAAShader'
, '../../vendor/three.js/examples/js/shaders/HorizontalBlurShader'
, '../../vendor/three.js/examples/js/shaders/SepiaShader'
, '../../vendor/three.js/examples/js/shaders/VerticalBlurShader'
, '../../vendor/three.js/examples/js/shaders/VignetteShader'
], function(){
}); | jeromeetienne/threex-v0 | threex-2.0.0/src/threex.effectcomposer/package.require.js | JavaScript | mit | 1,326 |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.MetaData.Normalized
{
using System;
public abstract class MetaDataMethodAbstract : MetaDataObject,
IMetaDataHasDeclSecurity,
IMetaDataMethodDefOrRef,
IMetaDataMemberForwarded,
IMetaDataCustomAttributeType,
IMetaDataTypeOrMethodDef
{
//
// Constructor Methods
//
protected MetaDataMethodAbstract( int token ) : base( token )
{
}
//--//
//
// Helper Methods
//
public abstract bool IsOpenMethod
{
get;
}
//
// Debug Methods
//
public abstract string FullName
{
get;
}
public abstract String ToString( IMetaDataDumper context );
}
}
| smaillet-ms/llilum | Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataMethodAbstract.cs | C# | mit | 875 |
## sysctl provider
This is a custom type and provider supplied by `augeasproviders`.
### manage simple entry
sysctl { "net.ipv4.ip_forward":
ensure => present,
value => "1",
}
### manage entry with comment
sysctl { "net.ipv4.ip_forward":
ensure => present,
value => "1",
comment => "test",
}
### delete entry
sysctl { "kernel.sysrq":
ensure => absent,
}
### remove comment from entry
sysctl { "kernel.sysrq":
ensure => present,
comment => "",
}
### manage entry in another sysctl.conf location
sysctl { "net.ipv4.ip_forward":
ensure => present,
value => "1",
target => "/etc/sysctl.d/forwarding.conf",
}
### do not update value with the `sysctl` command
sysctl { "net.ipv4.ip_forward":
ensure => present,
value => "1",
apply => false,
}
| integratedfordevelopers/integrated-puphpet | puppet/modules/augeasproviders_core/docs/examples/sysctl.md | Markdown | mit | 890 |
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
get: function () {
if (!(this instanceof Buffer)) {
return undefined
}
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
get: function () {
if (!(this instanceof Buffer)) {
return undefined
}
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('Invalid typed array length')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (isArrayBuffer(value) || (value && isArrayBuffer(value.buffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
return fromObject(value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj) {
if (ArrayBuffer.isView(obj) || 'length' in obj) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.')
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (ArrayBuffer.isView(buf)) {
buf = Buffer.from(buf)
}
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (ArrayBuffer.isView(string) || isArrayBuffer(string)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.toLocaleString = Buffer.prototype.toString
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
var strLen = string.length
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end)
} else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if ((encoding === 'utf8' && code < 128) ||
encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code
}
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: new Buffer(val, encoding)
var len = bytes.length
if (len === 0) {
throw new TypeError('The value "' + val +
'" is invalid for argument "value"')
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
function isArrayBuffer (obj) {
return obj instanceof ArrayBuffer ||
(obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
typeof obj.byteLength === 'number')
}
function numberIsNaN (obj) {
return obj !== obj // eslint-disable-line no-self-compare
}
| esteladiaz/esteladiaz.github.io | node_modules/styled-components/node_modules/buffer/index.js | JavaScript | mit | 47,193 |
/*
* Authors:
* Copyright (c) 2016 Intel Corporation.
*
* 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.
*/
#ifndef UPM_H_
#define UPM_H_
#ifdef __cplusplus
extern "C" {
#endif
#if __STDC_VERSION__ >= 199901L
#define C99
#endif
#include <upm_types.h>
#include <upm_math.h>
#define upm_perror(...) perror(args, __VA_ARGS__)
#ifdef __cplusplus
}
#endif
#endif /* UPM_H_ */
| sasmita/upm | include/upm.h | C | mit | 1,407 |
<!DOCTYPE html>
<title>Canvas test: 2d.composite.uncovered.fill.destination-in</title>
<script src="../tests.js"></script>
<link rel="stylesheet" href="../tests.css">
<body class="framed show_output">
<h1>
<a href="2d.composite.uncovered.fill.destination-in.html" target="_parent">2d.​composite.​uncovered.​fill.​destination-in</a>
</h1>
<p><a href="#" id="show_output" onclick="document.body.className += ' show_output'; return false">[show output]</a>
<p class="output">Actual output:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<p class="output expectedtext">Expected output:<p><img src="2d.composite.uncovered.fill.destination-in.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
_addTest(function(canvas, ctx) {
ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
ctx.fillRect(0, 0, 100, 50);
ctx.globalCompositeOperation = 'destination-in';
ctx.fillStyle = 'rgba(0, 0, 255, 0.75)';
ctx.translate(0, 25);
ctx.fillRect(0, 50, 100, 50);
_assertPixelApprox(canvas, 50,25, 0,0,0,0, "50,25", "0,0,0,0", 5);
});
</script>
| kangax/webgl-2d | test/philip.html5.org/tests/framed.2d.composite.uncovered.fill.destination-in.html | HTML | mit | 1,136 |
module Paperclip
module Shoulda
module Matchers
# Ensures that the given instance or class has an attachment with the
# given name.
#
# Example:
# describe User do
# it { should have_attached_file(:avatar) }
# end
def have_attached_file name
HaveAttachedFileMatcher.new(name)
end
class HaveAttachedFileMatcher
def initialize attachment_name
@attachment_name = attachment_name
end
def matches? subject
@subject = subject
@subject = @subject.class unless Class === @subject
responds? && has_column?
end
def failure_message
"Should have an attachment named #{@attachment_name}"
end
def negative_failure_message
"Should not have an attachment named #{@attachment_name}"
end
def description
"have an attachment named #{@attachment_name}"
end
protected
def responds?
methods = @subject.instance_methods.map(&:to_s)
methods.include?("#{@attachment_name}") &&
methods.include?("#{@attachment_name}=") &&
methods.include?("#{@attachment_name}?")
end
def has_column?
@subject.column_names.include?("#{@attachment_name}_file_name")
end
end
end
end
end
| Rifu/caa-rails | vendor/gems/ruby/2.0.0/gems/paperclip-3.5.1/lib/paperclip/matchers/have_attached_file_matcher.rb | Ruby | mit | 1,387 |
.content_box form {
font-size: 1.3em;
}
.content_box form li {
display: block;
list-style: none outside none;
margin: 2em 0;
}
.content_box form .field label {
display: block;
float: left;
margin-right: 10px;
margin-top: 2px;
text-align: right;
width: 150px;
}
.content_box form button.submit {
margin-left: 160px;
padding: 3px 1em;
font-size: 1.1em;
}
form .error {
color: red;
margin-left: 160px;
}
form .help {
font-size: 80%;
margin-left: 160px;
}
div.content_box.prefs fieldset {
margin: 30px 0;
border: 1px #ccc solid;
padding: 0 15px;
}
div.content_box.prefs fieldset legend {
text-transform: uppercase;
letter-spacing: 4px;
padding: 0 10px;
}
div.content_box.prefs h2 {
font-weight: bold;
display: block;
margin-bottom: 20px;
}
div.content_box.prefs div.buttonset {
display: block;
margin: 10px 0;
}
div.content_box.prefs div.buttonset label {
font-weight: normal;
}
div.content_box.prefs form li {
margin: 20px 0;
border-top: 1px solid #eaeaea;
padding: 15px 0 0 0;
}
div.content_box.prefs form li:first-child {
padding-top: 0;
border-top: none;
}
div.content_box.prefs form button.submit {
margin: 0;
padding: 10px 20px;
}
| Happy0/lila | public/stylesheets/user-form.css | CSS | mit | 1,208 |
//
// impl/ssl/src.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_SSL_IMPL_SRC_HPP
#define ASIO_SSL_IMPL_SRC_HPP
#define ASIO_SOURCE
#include "asio/detail/config.hpp"
#if defined(ASIO_HEADER_ONLY)
# error Do not compile Asio library source with ASIO_HEADER_ONLY defined
#endif
#include "asio/ssl/impl/context.ipp"
#include "asio/ssl/impl/error.ipp"
#include "asio/ssl/detail/impl/engine.ipp"
#include "asio/ssl/detail/impl/openssl_init.ipp"
#include "asio/ssl/impl/rfc2818_verification.ipp"
#endif // ASIO_SSL_IMPL_SRC_HPP
| smasherprog/websocket_lite | include/asio/ssl/impl/src.hpp | C++ | mit | 760 |
# -*- coding: utf-8 -*-
# Basic exporter for svg icons
from os import listdir
from os.path import isfile, join, dirname, realpath
import subprocess
import sys
import rsvg
import cairo
last_svg_path = None
last_svg_data = None
SCRIPT_FOLDER = dirname(realpath(__file__)) + '/'
theme_dir_base = SCRIPT_FOLDER + '../../scene/resources/default_theme/'
theme_dir_source = theme_dir_base + 'source/'
icons_dir_base = SCRIPT_FOLDER + '../editor/icons/'
icons_dir_2x = icons_dir_base + '2x/'
icons_dir_source = icons_dir_base + 'source/'
def svg_to_png(svg_path, png_path, dpi):
global last_svg_path, last_svg_data
zoom = int(dpi / 90)
if last_svg_path != svg_path:
last_svg_data = open(svg_path, 'r').read()
last_svg_path = svg_path
svg = rsvg.Handle(data=last_svg_data)
img = cairo.ImageSurface(
cairo.FORMAT_ARGB32,
svg.props.width * zoom,
svg.props.height * zoom
)
ctx = cairo.Context(img)
ctx.set_antialias(cairo.ANTIALIAS_DEFAULT)
ctx.scale(zoom, zoom)
svg.render_cairo(ctx)
img.write_to_png('%s.png' % png_path)
svg.close()
def export_icons():
svgs_path = icons_dir_source
file_names = [f for f in listdir(svgs_path) if isfile(join(svgs_path, f))]
for file_name in file_names:
# name without extensions
name_only = file_name.replace('.svg', '')
out_icon_names = [name_only] # export to a png with the same file name
theme_out_icon_names = []
# special cases
if special_icons.has_key(name_only):
special_icon = special_icons[name_only]
if type(special_icon) is dict:
if special_icon.get('avoid_self'):
out_icon_names = []
if special_icon.has_key('output_names'):
out_icon_names += special_icon['output_names']
if special_icon.has_key('theme_output_names'):
theme_out_icon_names += special_icon['theme_output_names']
source_path = '%s%s.svg' % (svgs_path, name_only)
for out_icon_name in out_icon_names:
svg_to_png(source_path, icons_dir_base + out_icon_name, 90)
svg_to_png(source_path, icons_dir_2x + out_icon_name, 180)
for theme_out_icon_name in theme_out_icon_names:
svg_to_png(source_path, theme_dir_base + theme_out_icon_name, 90)
def export_theme():
svgs_path = theme_dir_source
file_names = [f for f in listdir(svgs_path) if isfile(join(svgs_path, f))]
for file_name in file_names:
# name without extensions
name_only = file_name.replace('.svg', '')
out_icon_names = [name_only] # export to a png with the same file name
# special cases
if theme_icons.has_key(name_only):
special_icon = theme_icons[name_only]
if type(special_icon) is dict:
if special_icon.has_key('output_names'):
out_icon_names += special_icon['output_names']
source_path = '%s%s.svg' % (svgs_path, name_only)
for out_icon_name in out_icon_names:
svg_to_png(source_path, theme_dir_base + out_icon_name, 90)
# special cases for icons that will be exported to multiple target pngs or that require transforms.
special_icons = {
'icon_add_track': dict(
output_names=['icon_add'],
theme_output_names=['icon_add', 'icon_zoom_more']
),
'icon_new': dict( output_names=['icon_file'] ),
'icon_animation_tree_player': dict( output_names=['icon_animation_tree'] ),
'icon_tool_rotate': dict(
output_names=['icon_reload'],
theme_output_names= ['icon_reload']
),
'icon_multi_edit': dict( output_names=['icon_multi_node_edit'] ),
'icon_folder': dict(
output_names=['icon_load', 'icon_open'],
theme_output_names= ['icon_folder']
),
'icon_file_list': dict( output_names=['icon_enum'] ),
'icon_collision_2d': dict( output_names=['icon_collision_polygon_2d', 'icon_polygon_2d'] ),
'icon_class_list': dict( output_names=['icon_filesystem'] ),
'icon_color_ramp': dict( output_names=['icon_graph_color_ramp'] ),
'icon_translation': dict( output_names=['icon_p_hash_translation'] ),
'icon_shader': dict( output_names=['icon_shader_material', 'icon_material_shader'] ),
'icon_canvas_item_shader_graph': dict( output_names=['icon_material_shader_graph'] ),
'icon_color_pick': dict( theme_output_names= ['icon_color_pick'], avoid_self=True ),
'icon_play': dict( theme_output_names= ['icon_play'] ),
'icon_stop': dict( theme_output_names= ['icon_stop'] ),
'icon_zoom_less': dict( theme_output_names= ['icon_zoom_less'], avoid_self=True ),
'icon_zoom_reset': dict( theme_output_names= ['icon_zoom_reset'], avoid_self=True )
}
theme_icons = {
'icon_close': dict(output_names=['close', 'close_hl']),
'tab_menu': dict(output_names=['tab_menu_hl'])
}
export_icons()
export_theme()
| est31/godot | tools/scripts/svgs_2_pngs.py | Python | mit | 4,974 |
# coding: utf-8
require 'nokogiri'
module ActiveMerchant #:nodoc:
module Billing #:nodoc:
# = Redsys Merchant Gateway
#
# Gateway support for the Spanish "Redsys" payment gateway system. This is
# used by many banks in Spain and is particularly well supported by
# Catalunya Caixa's ecommerce department.
#
# Redsys requires an order_id be provided with each transaction and it must
# follow a specific format. The rules are as follows:
#
# * First 4 digits must be numerical
# * Remaining 8 digits may be alphanumeric
# * Max length: 12
#
# If an invalid order_id is provided, we do our best to clean it up.
#
# Much of the code for this library is based on the active_merchant_sermepa
# integration gateway which uses essentially the same API but with the
# banks own payment screen.
#
# Written by Samuel Lown for Cabify. For implementation questions, or
# test access details please get in touch: [email protected].
#
# *** SHA256 Authentication Update ***
#
# Redsys is dropping support for the SHA1 authentication method. This
# adapter has been updated to work with the new SHA256 authentication
# method, however in your initialization options hash you will need to
# specify the key/value :signature_algorithm => "sha256" to use the
# SHA256 method. Otherwise it will default to using the SHA1.
#
#
class RedsysGateway < Gateway
self.live_url = "https://sis.sermepa.es/sis/operaciones"
self.test_url = "https://sis-t.redsys.es:25443/sis/operaciones"
self.supported_countries = ['ES']
self.default_currency = 'EUR'
self.money_format = :cents
# Not all card types may be activated by the bank!
self.supported_cardtypes = [:visa, :master, :american_express, :jcb, :diners_club]
self.homepage_url = "http://www.redsys.es/"
self.display_name = "Redsys"
CURRENCY_CODES = {
"AED" => '784',
"ARS" => '32',
"AUD" => '36',
"BRL" => '986',
"BOB" => '68',
"CAD" => '124',
"CHF" => '756',
"CLP" => '152',
"COP" => '170',
"CZK" => '203',
"EUR" => '978',
"GBP" => '826',
"GTQ" => '320',
"HUF" => '348',
"JPY" => '392',
"MYR" => '458',
"MXN" => '484',
"NOK" => '578',
"NZD" => '554',
"PEN" => '604',
"PLN" => '616',
"RUB" => '643',
"SEK" => '752',
"SGD" => '702',
"THB" => '764',
"USD" => '840',
"UYU" => '858'
}
# The set of supported transactions for this gateway.
# More operations are supported by the gateway itself, but
# are not supported in this library.
SUPPORTED_TRANSACTIONS = {
:purchase => 'A',
:authorize => '1',
:capture => '2',
:refund => '3',
:cancel => '9'
}
# These are the text meanings sent back by the acquirer when
# a card has been rejected. Syntax or general request errors
# are not covered here.
RESPONSE_TEXTS = {
0 => "Transaction Approved",
400 => "Cancellation Accepted",
481 => "Cancellation Accepted",
500 => "Reconciliation Accepted",
900 => "Refund / Confirmation approved",
101 => "Card expired",
102 => "Card blocked temporarily or under susciption of fraud",
104 => "Transaction not permitted",
107 => "Contact the card issuer",
109 => "Invalid identification by merchant or POS terminal",
110 => "Invalid amount",
114 => "Card cannot be used to the requested transaction",
116 => "Insufficient credit",
118 => "Non-registered card",
125 => "Card not effective",
129 => "CVV2/CVC2 Error",
167 => "Contact the card issuer: suspected fraud",
180 => "Card out of service",
181 => "Card with credit or debit restrictions",
182 => "Card with credit or debit restrictions",
184 => "Authentication error",
190 => "Refusal with no specific reason",
191 => "Expiry date incorrect",
201 => "Card expired",
202 => "Card blocked temporarily or under suspicion of fraud",
204 => "Transaction not permitted",
207 => "Contact the card issuer",
208 => "Lost or stolen card",
209 => "Lost or stolen card",
280 => "CVV2/CVC2 Error",
290 => "Declined with no specific reason",
480 => "Original transaction not located, or time-out exceeded",
501 => "Original transaction not located, or time-out exceeded",
502 => "Original transaction not located, or time-out exceeded",
503 => "Original transaction not located, or time-out exceeded",
904 => "Merchant not registered at FUC",
909 => "System error",
912 => "Issuer not available",
913 => "Duplicate transmission",
916 => "Amount too low",
928 => "Time-out exceeded",
940 => "Transaction cancelled previously",
941 => "Authorization operation already cancelled",
942 => "Original authorization declined",
943 => "Different details from origin transaction",
944 => "Session error",
945 => "Duplicate transmission",
946 => "Cancellation of transaction while in progress",
947 => "Duplicate tranmission while in progress",
949 => "POS Inoperative",
950 => "Refund not possible",
9064 => "Card number incorrect",
9078 => "No payment method available",
9093 => "Non-existent card",
9218 => "Recursive transaction in bad gateway",
9253 => "Check-digit incorrect",
9256 => "Preauth not allowed for merchant",
9257 => "Preauth not allowed for card",
9261 => "Operating limit exceeded",
9912 => "Issuer not available",
9913 => "Confirmation error",
9914 => "KO Confirmation"
}
# Creates a new instance
#
# Redsys requires a login and secret_key, and optionally also accepts a
# non-default terminal.
#
# ==== Options
#
# * <tt>:login</tt> -- The Redsys Merchant ID (REQUIRED)
# * <tt>:secret_key</tt> -- The Redsys Secret Key. (REQUIRED)
# * <tt>:terminal</tt> -- The Redsys Terminal. Defaults to 1. (OPTIONAL)
# * <tt>:test</tt> -- +true+ or +false+. Defaults to +false+. (OPTIONAL)
# * <tt>:signature_algorithm</tt> -- +"sha256"+ Defaults to +"sha1"+. (OPTIONAL)
def initialize(options = {})
requires!(options, :login, :secret_key)
options[:terminal] ||= 1
options[:signature_algorithm] ||= "sha1"
super
end
def purchase(money, payment, options = {})
requires!(options, :order_id)
data = {}
add_action(data, :purchase)
add_amount(data, money, options)
add_order(data, options[:order_id])
add_payment(data, payment)
data[:description] = options[:description]
data[:store_in_vault] = options[:store]
commit data
end
def authorize(money, payment, options = {})
requires!(options, :order_id)
data = {}
add_action(data, :authorize)
add_amount(data, money, options)
add_order(data, options[:order_id])
add_payment(data, payment)
data[:description] = options[:description]
data[:store_in_vault] = options[:store]
commit data
end
def capture(money, authorization, options = {})
data = {}
add_action(data, :capture)
add_amount(data, money, options)
order_id, _, _ = split_authorization(authorization)
add_order(data, order_id)
data[:description] = options[:description]
commit data
end
def void(authorization, options = {})
data = {}
add_action(data, :cancel)
order_id, amount, currency = split_authorization(authorization)
add_amount(data, amount, :currency => currency)
add_order(data, order_id)
data[:description] = options[:description]
commit data
end
def refund(money, authorization, options = {})
data = {}
add_action(data, :refund)
add_amount(data, money, options)
order_id, _, _ = split_authorization(authorization)
add_order(data, order_id)
data[:description] = options[:description]
commit data
end
def verify(creditcard, options = {})
MultiResponse.run(:use_first_response) do |r|
r.process { authorize(100, creditcard, options) }
r.process(:ignore_result) { void(r.authorization, options) }
end
end
def supports_scrubbing
true
end
def scrub(transcript)
transcript.
gsub(%r((Authorization: Basic )\w+), '\1[FILTERED]').
gsub(%r((%3CDS_MERCHANT_PAN%3E)\d+(%3C%2FDS_MERCHANT_PAN%3E))i, '\1[FILTERED]\2').
gsub(%r((%3CDS_MERCHANT_CVV2%3E)\d+(%3C%2FDS_MERCHANT_CVV2%3E))i, '\1[FILTERED]\2').
gsub(%r((<DS_MERCHANT_PAN>)\d+(</DS_MERCHANT_PAN>))i, '\1[FILTERED]\2').
gsub(%r((<DS_MERCHANT_CVV2>)\d+(</DS_MERCHANT_CVV2>))i, '\1[FILTERED]\2').
gsub(%r((DS_MERCHANT_CVV2)%2F%3E%0A%3C%2F)i, '\1[BLANK]').
gsub(%r((DS_MERCHANT_CVV2)%2F%3E%3C)i, '\1[BLANK]').
gsub(%r((DS_MERCHANT_CVV2%3E)(%3C%2FDS_MERCHANT_CVV2))i, '\1[BLANK]\2').
gsub(%r((<DS_MERCHANT_CVV2>)(</DS_MERCHANT_CVV2>))i, '\1[BLANK]\2').
gsub(%r((DS_MERCHANT_CVV2%3E)\++(%3C%2FDS_MERCHANT_CVV2))i, '\1[BLANK]\2').
gsub(%r((<DS_MERCHANT_CVV2>)\s+(</DS_MERCHANT_CVV2>))i, '\1[BLANK]\2')
end
private
def add_action(data, action)
data[:action] = transaction_code(action)
end
def add_amount(data, money, options)
data[:amount] = amount(money).to_s
data[:currency] = currency_code(options[:currency] || currency(money))
end
def add_order(data, order_id)
data[:order_id] = clean_order_id(order_id)
end
def url
test? ? test_url : live_url
end
def add_payment(data, card)
if card.is_a?(String)
data[:credit_card_token] = card
else
name = [card.first_name, card.last_name].join(' ').slice(0, 60)
year = sprintf("%.4i", card.year)
month = sprintf("%.2i", card.month)
data[:card] = {
:name => name,
:pan => card.number,
:date => "#{year[2..3]}#{month}",
:cvv => card.verification_value
}
end
end
def commit(data)
parse(ssl_post(url, "entrada=#{CGI.escape(xml_request_from(data))}", headers))
end
def headers
{
'Content-Type' => 'application/x-www-form-urlencoded'
}
end
def xml_request_from(data)
if sha256_authentication?
build_sha256_xml_request(data)
else
build_sha1_xml_request(data)
end
end
def build_signature(data)
str = data[:amount] +
data[:order_id].to_s +
@options[:login].to_s +
data[:currency]
if card = data[:card]
str << card[:pan]
str << card[:cvv] if card[:cvv]
end
str << data[:action]
if data[:store_in_vault]
str << 'REQUIRED'
elsif data[:credit_card_token]
str << data[:credit_card_token]
end
str << @options[:secret_key]
Digest::SHA1.hexdigest(str)
end
def build_sha256_xml_request(data)
xml = Builder::XmlMarkup.new
xml.instruct!
xml.REQUEST do
build_merchant_data(xml, data)
xml.DS_SIGNATUREVERSION 'HMAC_SHA256_V1'
xml.DS_SIGNATURE sign_request(merchant_data_xml(data), data[:order_id])
end
xml.target!
end
def build_sha1_xml_request(data)
xml = Builder::XmlMarkup.new :indent => 2
build_merchant_data(xml, data)
xml.target!
end
def merchant_data_xml(data)
xml = Builder::XmlMarkup.new
build_merchant_data(xml, data)
xml.target!
end
def build_merchant_data(xml, data)
xml.DATOSENTRADA do
# Basic elements
xml.DS_Version 0.1
xml.DS_MERCHANT_CURRENCY data[:currency]
xml.DS_MERCHANT_AMOUNT data[:amount]
xml.DS_MERCHANT_ORDER data[:order_id]
xml.DS_MERCHANT_TRANSACTIONTYPE data[:action]
xml.DS_MERCHANT_PRODUCTDESCRIPTION data[:description]
xml.DS_MERCHANT_TERMINAL @options[:terminal]
xml.DS_MERCHANT_MERCHANTCODE @options[:login]
xml.DS_MERCHANT_MERCHANTSIGNATURE build_signature(data) unless sha256_authentication?
# Only when card is present
if data[:card]
xml.DS_MERCHANT_TITULAR data[:card][:name]
xml.DS_MERCHANT_PAN data[:card][:pan]
xml.DS_MERCHANT_EXPIRYDATE data[:card][:date]
xml.DS_MERCHANT_CVV2 data[:card][:cvv]
xml.DS_MERCHANT_IDENTIFIER 'REQUIRED' if data[:store_in_vault]
elsif data[:credit_card_token]
xml.DS_MERCHANT_IDENTIFIER data[:credit_card_token]
end
end
end
def parse(data)
params = {}
success = false
message = ""
options = @options.merge(:test => test?)
xml = Nokogiri::XML(data)
code = xml.xpath("//RETORNOXML/CODIGO").text
if code == "0"
op = xml.xpath("//RETORNOXML/OPERACION")
op.children.each do |element|
params[element.name.downcase.to_sym] = element.text
end
if validate_signature(params)
message = response_text(params[:ds_response])
options[:authorization] = build_authorization(params)
success = is_success_response?(params[:ds_response])
else
message = "Response failed validation check"
end
else
# Some kind of programmer error with the request!
message = "#{code} ERROR"
end
Response.new(success, message, params, options)
end
def validate_signature(data)
if sha256_authentication?
sig = Base64.strict_encode64(mac256(get_key(data[:ds_order].to_s), xml_signed_fields(data)))
sig.upcase == data[:ds_signature].to_s.upcase
else
str = data[:ds_amount] +
data[:ds_order].to_s +
data[:ds_merchantcode] +
data[:ds_currency] +
data[:ds_response] +
data[:ds_cardnumber].to_s +
data[:ds_transactiontype].to_s +
data[:ds_securepayment].to_s +
@options[:secret_key]
sig = Digest::SHA1.hexdigest(str)
data[:ds_signature].to_s.downcase == sig
end
end
def build_authorization(params)
[params[:ds_order], params[:ds_amount], params[:ds_currency]].join("|")
end
def split_authorization(authorization)
order_id, amount, currency = authorization.split("|")
[order_id, amount.to_i, currency]
end
def currency_code(currency)
return currency if currency =~ /^\d+$/
raise ArgumentError, "Unknown currency #{currency}" unless CURRENCY_CODES[currency]
CURRENCY_CODES[currency]
end
def transaction_code(type)
SUPPORTED_TRANSACTIONS[type]
end
def response_text(code)
code = code.to_i
code = 0 if code < 100
RESPONSE_TEXTS[code] || "Unkown code, please check in manual"
end
def is_success_response?(code)
(code.to_i < 100) || [400, 481, 500, 900].include?(code.to_i)
end
def clean_order_id(order_id)
cleansed = order_id.gsub(/[^\da-zA-Z]/, '')
if cleansed =~ /^\d{4}/
cleansed[0..11]
else
"%04d%s" % [rand(0..9999), cleansed[0...8]]
end
end
def sha256_authentication?
@options[:signature_algorithm] == "sha256"
end
def sign_request(xml_request_string, order_id)
key = encrypt(@options[:secret_key], order_id)
Base64.strict_encode64(mac256(key, xml_request_string))
end
def encrypt(key, order_id)
block_length = 8
cipher = OpenSSL::Cipher::Cipher.new('DES3')
cipher.encrypt
cipher.key = Base64.strict_decode64(key)
# The OpenSSL default of an all-zeroes ("\\0") IV is used.
cipher.padding = 0
order_id += "\0" until order_id.bytesize % block_length == 0 # Pad with zeros
output = cipher.update(order_id) + cipher.final
output
end
def mac256(key, data)
OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), key, data)
end
def xml_signed_fields(data)
data[:ds_amount] + data[:ds_order] + data[:ds_merchantcode] + data[:ds_currency] +
data[:ds_response] + data[:ds_transactiontype] + data[:ds_securepayment]
end
def get_key(order_id)
encrypt(@options[:secret_key], order_id)
end
end
end
end
| vivekschetu/active_merchant | lib/active_merchant/billing/gateways/redsys.rb | Ruby | mit | 17,450 |
// Generated by CoffeeScript 1.12.7
(function() {
var Adapter, Stylus, flatten, nodefn, sourcemaps,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Adapter = require('../../adapter_base');
sourcemaps = require('../../sourcemaps');
nodefn = require('when/node/function');
flatten = require('lodash.flatten');
Stylus = (function(superClass) {
extend(Stylus, superClass);
function Stylus() {
return Stylus.__super__.constructor.apply(this, arguments);
}
Stylus.prototype.name = 'stylus';
Stylus.prototype.extensions = ['styl'];
Stylus.prototype.output = 'css';
Stylus.prototype._render = function(str, options) {
var base, defines, i, imports, includes, j, k, l, len, len1, len2, m, obj, plugins, rawDefines, sets, v;
sets = {};
defines = {};
rawDefines = {};
includes = [];
imports = [];
plugins = [];
if (options.sourcemap === true) {
options.sourcemap = {
comment: false
};
}
for (k in options) {
v = options[k];
switch (k) {
case 'define':
Object.assign(defines, v);
break;
case 'rawDefine':
Object.assign(rawDefines, v);
break;
case 'include':
includes.push(v);
break;
case 'import':
imports.push(v);
break;
case 'use':
plugins.push(v);
break;
case 'url':
if (typeof v === 'string') {
obj = {};
obj[v] = this.engine.url();
Object.assign(defines, obj);
} else {
obj = {};
obj[v.name] = this.engine.url({
limit: v.limit != null ? v.limit : 30000,
paths: v.paths || []
});
Object.assign(defines, obj);
}
break;
default:
sets[k] = v;
}
}
includes = flatten(includes);
imports = flatten(imports);
plugins = flatten(plugins);
base = this.engine(str);
for (k in sets) {
v = sets[k];
base.set(k, v);
}
for (k in defines) {
v = defines[k];
base.define(k, v);
}
for (k in rawDefines) {
v = rawDefines[k];
base.define(k, v, true);
}
for (j = 0, len = includes.length; j < len; j++) {
i = includes[j];
base.include(i);
}
for (l = 0, len1 = imports.length; l < len1; l++) {
i = imports[l];
base["import"](i);
}
for (m = 0, len2 = plugins.length; m < len2; m++) {
i = plugins[m];
base.use(i);
}
return nodefn.call(base.render.bind(base)).then(function(res) {
return obj = {
result: res
};
}).then(function(obj) {
if (base.sourcemap) {
return sourcemaps.inline_sources(base.sourcemap).then(function(map) {
obj.sourcemap = map;
return obj;
});
} else {
return obj;
}
});
};
return Stylus;
})(Adapter);
module.exports = Stylus;
}).call(this);
| KhanovaSkola/khanovaskola-v3 | node_modules/gulp-less/node_modules/accord/lib/adapters/stylus/0.x.js | JavaScript | mit | 3,483 |
from adashi import *
from ccrm import *
from eden import *
from filesync import *
from ftp import *
from mcb import *
from wrike import *
| sahana/Turkey | modules/s3/sync_adapter/__init__.py | Python | mit | 138 |
/*
* Copyright (c) 2015 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef M2MREPORTHANDLER_H
#define M2MREPORTHANDLER_H
// Support for std args
#include <stdint.h>
#include "mbed-client/m2mconfig.h"
#include "mbed-client/m2mbase.h"
#include "mbed-client/m2mtimerobserver.h"
#include "mbed-client/m2mresourceinstance.h"
#include "mbed-client/m2mvector.h"
//FORWARD DECLARATION
class M2MReportObserver;
class M2MTimer;
class M2MResourceInstance;
/**
* @brief M2MReportHandler.
* This class is handles all the observation related operations.
*/
class M2MReportHandler: public M2MTimerObserver
{
private:
// Prevents the use of assignment operator by accident.
M2MReportHandler& operator=( const M2MReportHandler& /*other*/ );
public:
M2MReportHandler(M2MReportObserver &observer);
public:
/**
* Enum defining which write attributes are set.
*/
enum {
Cancel = 1,
Pmin = 2,
Pmax = 4,
Lt = 8,
Gt = 16,
St = 32
};
/**
* Destructor
*/
virtual ~M2MReportHandler();
/**
* @brief Sets that object is under observation.
* @param Value for the observation.
* @param handler, Handler object for sending
* observation callbacks.
*/
virtual void set_under_observation(bool observed);
/**
* @brief Sets the value of the given resource.
* @param value, Value of the observed resource.
*/
virtual void set_value(float value);
/**
* @brief Sets notification trigger.
* @param obj_instance_id, Object instance id that has changed
*/
void set_notification_trigger(uint16_t obj_instance_id = 0);
/**
* @brief Parses the received query for notification
* attribute.
* @param query Query to be parsed for attributes.
* @param type Type of the Base Object.
* @param resource_type Type of the Resource.
* @return true if required attributes are present else false.
*/
virtual bool parse_notification_attribute(char *&query,
M2MBase::BaseType type,
M2MResourceInstance::ResourceType resource_type = M2MResourceInstance::OPAQUE);
/**
* @brief Set back to default values.
*/
void set_default_values();
/**
* @brief Return write attribute flags.
*/
uint8_t attribute_flags();
protected : // from M2MTimerObserver
virtual void timer_expired(M2MTimerObserver::Type type =
M2MTimerObserver::Notdefined);
private:
bool set_notification_attribute(char* option,
M2MBase::BaseType type,
M2MResourceInstance::ResourceType resource_type);
/**
* @brief Schedule a report, if the pmin is exceeded
* then report immediately else store the state to be
* reported once the time fires.
*/
void schedule_report();
/**
* @brief Reports a sample that satisfies the reporting criteria.
*/
void report();
/**
* @brief Manage timers for pmin and pmax.
*/
void handle_timers();
/**
* @brief Check whether notification params can be accepted.
*/
bool check_attribute_validity();
/**
* @brief Stop pmin & pmax timers.
*/
void stop_timers();
/**
* @brief Check if current value match threshold values.
* @return True if notify can be send otherwise false.
*/
bool check_threshold_values();
/**
* @brief Check whether current value matches with GT & LT.
* @return True if current value match with GT or LT values.
*/
bool check_gt_lt_params();
private:
M2MReportObserver &_observer;
int _pmax;
int _pmin;
float _gt;
float _lt;
float _st;
bool _pmin_exceeded;
bool _pmax_exceeded;
M2MTimer *_pmin_timer;
M2MTimer *_pmax_timer;
float _high_step;
float _low_step;
float _current_value;
float _last_value;
uint8_t _attribute_state;
bool _notify;
m2m::Vector<uint16_t> _changed_instance_ids;
friend class Test_M2MReportHandler;
};
#endif // M2MREPORTHANDLER_H
| Neuromancer2701/mbedROS2_STF7 | mbed-os/features/FEATURE_CLIENT/mbed-client/source/include/m2mreporthandler.h | C | mit | 5,091 |
/*
* Fingerprintjs2 0.7.3 - Modern & flexible browser fingerprint library v2
* https://github.com/Valve/fingerprintjs2
* Copyright (c) 2015 Valentin Vasilyev ([email protected])
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL VALENTIN VASILYEV 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.
*/
(function (name, context, definition) {
"use strict";
if (typeof module !== "undefined" && module.exports) { module.exports = definition(); }
else if (typeof define === "function" && define.amd) { define(definition); }
else { context[name] = definition(); }
})("Fingerprint2", this, function() {
"use strict";
// This will only be polyfilled for IE8 and older
// Taken from Mozilla MDC
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
if (this == null) {
throw new TypeError("'this' is null or undefined");
}
var O = Object(this);
var len = O.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
var Fingerprint2 = function(options) {
var defaultOptions = {
swfContainerId: "fingerprintjs2",
swfPath: "flash/compiled/FontList.swf",
sortPluginsFor: [/palemoon/i]
};
this.options = this.extend(options, defaultOptions);
this.nativeForEach = Array.prototype.forEach;
this.nativeMap = Array.prototype.map;
};
Fingerprint2.prototype = {
extend: function(source, target) {
if (source == null) { return target; }
for (var k in source) {
if(source[k] != null && target[k] !== source[k]) {
target[k] = source[k];
}
}
return target;
},
log: function(msg){
if(window.console){
console.log(msg);
}
},
get: function(done){
var keys = [];
keys = this.userAgentKey(keys);
keys = this.languageKey(keys);
keys = this.colorDepthKey(keys);
keys = this.screenResolutionKey(keys);
keys = this.timezoneOffsetKey(keys);
keys = this.sessionStorageKey(keys);
keys = this.localStorageKey(keys);
keys = this.indexedDbKey(keys);
keys = this.addBehaviorKey(keys);
keys = this.openDatabaseKey(keys);
keys = this.cpuClassKey(keys);
keys = this.platformKey(keys);
keys = this.doNotTrackKey(keys);
keys = this.pluginsKey(keys);
keys = this.canvasKey(keys);
keys = this.webglKey(keys);
keys = this.adBlockKey(keys);
keys = this.hasLiedLanguagesKey(keys);
keys = this.hasLiedResolutionKey(keys);
keys = this.hasLiedOsKey(keys);
keys = this.hasLiedBrowserKey(keys);
keys = this.touchSupportKey(keys);
var that = this;
this.fontsKey(keys, function(newKeys){
var murmur = that.x64hash128(newKeys.join("~~~"), 31);
return done(murmur);
});
},
userAgentKey: function(keys) {
if(!this.options.excludeUserAgent) {
keys.push(this.getUserAgent());
}
return keys;
},
// for tests
getUserAgent: function(){
return navigator.userAgent;
},
languageKey: function(keys) {
if(!this.options.excludeLanguage) {
keys.push(navigator.language);
}
return keys;
},
colorDepthKey: function(keys) {
if(!this.options.excludeColorDepth) {
keys.push(screen.colorDepth);
}
return keys;
},
screenResolutionKey: function(keys) {
if(!this.options.excludeScreenResolution) {
return this.getScreenResolution(keys);
}
return keys;
},
getScreenResolution: function(keys) {
var resolution;
var available;
if(this.options.detectScreenOrientation) {
resolution = (screen.height > screen.width) ? [screen.height, screen.width] : [screen.width, screen.height];
} else {
resolution = [screen.height, screen.width];
}
if(typeof resolution !== "undefined") { // headless browsers
keys.push(resolution);
}
if(screen.availWidth && screen.availHeight) {
if(this.options.detectScreenOrientation) {
available = (screen.availHeight > screen.availWidth) ? [screen.availHeight, screen.availWidth] : [screen.availWidth, screen.availHeight];
} else {
available = [screen.availHeight, screen.availWidth];
}
}
if(typeof available !== "undefined") { // headless browsers
keys.push(available);
}
return keys;
},
timezoneOffsetKey: function(keys) {
if(!this.options.excludeTimezoneOffset) {
keys.push(new Date().getTimezoneOffset());
}
return keys;
},
sessionStorageKey: function(keys) {
if(!this.options.excludeSessionStorage && this.hasSessionStorage()) {
keys.push("sessionStorageKey");
}
return keys;
},
localStorageKey: function(keys) {
if(!this.options.excludeSessionStorage && this.hasLocalStorage()) {
keys.push("localStorageKey");
}
return keys;
},
indexedDbKey: function(keys) {
if(!this.options.excludeIndexedDB && this.hasIndexedDB()) {
keys.push("indexedDbKey");
}
return keys;
},
addBehaviorKey: function(keys) {
//body might not be defined at this point or removed programmatically
if(document.body && !this.options.excludeAddBehavior && document.body.addBehavior) {
keys.push("addBehaviorKey");
}
return keys;
},
openDatabaseKey: function(keys) {
if(!this.options.excludeOpenDatabase && window.openDatabase) {
keys.push("openDatabase");
}
return keys;
},
cpuClassKey: function(keys) {
if(!this.options.excludeCpuClass) {
keys.push(this.getNavigatorCpuClass());
}
return keys;
},
platformKey: function(keys) {
if(!this.options.excludePlatform) {
keys.push(this.getNavigatorPlatform());
}
return keys;
},
doNotTrackKey: function(keys) {
if(!this.options.excludeDoNotTrack) {
keys.push(this.getDoNotTrack());
}
return keys;
},
canvasKey: function(keys) {
if(!this.options.excludeCanvas && this.isCanvasSupported()) {
keys.push(this.getCanvasFp());
}
return keys;
},
webglKey: function(keys) {
if(this.options.excludeWebGL) {
if(typeof NODEBUG === "undefined"){
this.log("Skipping WebGL fingerprinting per excludeWebGL configuration option");
}
return keys;
}
if(!this.isWebGlSupported()) {
if(typeof NODEBUG === "undefined"){
this.log("Skipping WebGL fingerprinting because it is not supported in this browser");
}
return keys;
}
keys.push(this.getWebglFp());
return keys;
},
adBlockKey: function(keys){
if(!this.options.excludeAdBlock) {
keys.push(this.getAdBlock());
}
return keys;
},
hasLiedLanguagesKey: function(keys){
if(!this.options.excludeHasLiedLanguages){
keys.push(this.getHasLiedLanguages());
}
return keys;
},
hasLiedResolutionKey: function(keys){
if(!this.options.excludeHasLiedResolution){
keys.push(this.getHasLiedResolution());
}
return keys;
},
hasLiedOsKey: function(keys){
if(!this.options.excludeHasLiedOs){
keys.push(this.getHasLiedOs());
}
return keys;
},
hasLiedBrowserKey: function(keys){
if(!this.options.excludeHasLiedBrowser){
keys.push(this.getHasLiedBrowser());
}
return keys;
},
fontsKey: function(keys, done) {
if (this.options.excludeJsFonts) {
return this.flashFontsKey(keys, done);
}
return this.jsFontsKey(keys, done);
},
// flash fonts (will increase fingerprinting time 20X to ~ 130-150ms)
flashFontsKey: function(keys, done) {
if(this.options.excludeFlashFonts) {
if(typeof NODEBUG === "undefined"){
this.log("Skipping flash fonts detection per excludeFlashFonts configuration option");
}
return done(keys);
}
// we do flash if swfobject is loaded
if(!this.hasSwfObjectLoaded()){
if(typeof NODEBUG === "undefined"){
this.log("Swfobject is not detected, Flash fonts enumeration is skipped");
}
return done(keys);
}
if(!this.hasMinFlashInstalled()){
if(typeof NODEBUG === "undefined"){
this.log("Flash is not installed, skipping Flash fonts enumeration");
}
return done(keys);
}
if(typeof this.options.swfPath === "undefined"){
if(typeof NODEBUG === "undefined"){
this.log("To use Flash fonts detection, you must pass a valid swfPath option, skipping Flash fonts enumeration");
}
return done(keys);
}
this.loadSwfAndDetectFonts(function(fonts){
keys.push(fonts.join(";"));
done(keys);
});
},
// kudos to http://www.lalit.org/lab/javascript-css-font-detect/
jsFontsKey: function(keys, done) {
// doing js fonts detection in a pseudo-async fashion
return setTimeout(function(){
// a font will be compared against all the three default fonts.
// and if it doesn't match all 3 then that font is not available.
var baseFonts = ["monospace", "sans-serif", "serif"];
//we use m or w because these two characters take up the maximum width.
// And we use a LLi so that the same matching fonts can get separated
var testString = "mmmmmmmmmmlli";
//we test using 72px font size, we may use any size. I guess larger the better.
var testSize = "72px";
var h = document.getElementsByTagName("body")[0];
// create a SPAN in the document to get the width of the text we use to test
var s = document.createElement("span");
s.style.fontSize = testSize;
s.innerHTML = testString;
var defaultWidth = {};
var defaultHeight = {};
for (var index in baseFonts) {
//get the default width for the three base fonts
s.style.fontFamily = baseFonts[index];
h.appendChild(s);
defaultWidth[baseFonts[index]] = s.offsetWidth; //width for the default font
defaultHeight[baseFonts[index]] = s.offsetHeight; //height for the defualt font
h.removeChild(s);
}
var detect = function (font) {
var detected = false;
for (var index in baseFonts) {
s.style.fontFamily = font + "," + baseFonts[index]; // name of the font along with the base font for fallback.
h.appendChild(s);
var matched = (s.offsetWidth !== defaultWidth[baseFonts[index]] || s.offsetHeight !== defaultHeight[baseFonts[index]]);
h.removeChild(s);
detected = detected || matched;
}
return detected;
};
var fontList = [
"Abadi MT Condensed Light", "Academy Engraved LET", "ADOBE CASLON PRO", "Adobe Garamond", "ADOBE GARAMOND PRO", "Agency FB", "Aharoni", "Albertus Extra Bold", "Albertus Medium", "Algerian", "Amazone BT", "American Typewriter",
"American Typewriter Condensed", "AmerType Md BT", "Andale Mono", "Andalus", "Angsana New", "AngsanaUPC", "Antique Olive", "Aparajita", "Apple Chancery", "Apple Color Emoji", "Apple SD Gothic Neo", "Arabic Typesetting", "ARCHER", "Arial", "Arial Black", "Arial Hebrew",
"Arial MT", "Arial Narrow", "Arial Rounded MT Bold", "Arial Unicode MS", "ARNO PRO", "Arrus BT", "Aurora Cn BT", "AvantGarde Bk BT", "AvantGarde Md BT", "AVENIR", "Ayuthaya", "Bandy", "Bangla Sangam MN", "Bank Gothic", "BankGothic Md BT", "Baskerville",
"Baskerville Old Face", "Batang", "BatangChe", "Bauer Bodoni", "Bauhaus 93", "Bazooka", "Bell MT", "Bembo", "Benguiat Bk BT", "Berlin Sans FB", "Berlin Sans FB Demi", "Bernard MT Condensed", "BernhardFashion BT", "BernhardMod BT", "Big Caslon", "BinnerD",
"Bitstream Vera Sans Mono", "Blackadder ITC", "BlairMdITC TT", "Bodoni 72", "Bodoni 72 Oldstyle", "Bodoni 72 Smallcaps", "Bodoni MT", "Bodoni MT Black", "Bodoni MT Condensed", "Bodoni MT Poster Compressed", "Book Antiqua", "Bookman Old Style",
"Bookshelf Symbol 7", "Boulder", "Bradley Hand", "Bradley Hand ITC", "Bremen Bd BT", "Britannic Bold", "Broadway", "Browallia New", "BrowalliaUPC", "Brush Script MT", "Calibri", "Californian FB", "Calisto MT", "Calligrapher", "Cambria", "Cambria Math", "Candara",
"CaslonOpnface BT", "Castellar", "Centaur", "Century", "Century Gothic", "Century Schoolbook", "Cezanne", "CG Omega", "CG Times", "Chalkboard", "Chalkboard SE", "Chalkduster", "Charlesworth", "Charter Bd BT", "Charter BT", "Chaucer",
"ChelthmITC Bk BT", "Chiller", "Clarendon", "Clarendon Condensed", "CloisterBlack BT", "Cochin", "Colonna MT", "Comic Sans", "Comic Sans MS", "Consolas", "Constantia", "Cooper Black", "Copperplate", "Copperplate Gothic", "Copperplate Gothic Bold",
"Copperplate Gothic Light", "CopperplGoth Bd BT", "Corbel", "Cordia New", "CordiaUPC", "Cornerstone", "Coronet", "Courier", "Courier New", "Cuckoo", "Curlz MT", "DaunPenh", "Dauphin", "David", "DB LCD Temp", "DELICIOUS", "Denmark", "Devanagari Sangam MN",
"DFKai-SB", "Didot", "DilleniaUPC", "DIN", "DokChampa", "Dotum", "DotumChe", "Ebrima", "Edwardian Script ITC", "Elephant", "English 111 Vivace BT", "Engravers MT", "EngraversGothic BT", "Eras Bold ITC", "Eras Demi ITC", "Eras Light ITC", "Eras Medium ITC",
"Estrangelo Edessa", "EucrosiaUPC", "Euphemia", "Euphemia UCAS", "EUROSTILE", "Exotc350 Bd BT", "FangSong", "Felix Titling", "Fixedsys", "FONTIN", "Footlight MT Light", "Forte", "Franklin Gothic", "Franklin Gothic Book", "Franklin Gothic Demi",
"Franklin Gothic Demi Cond", "Franklin Gothic Heavy", "Franklin Gothic Medium", "Franklin Gothic Medium Cond", "FrankRuehl", "Fransiscan", "Freefrm721 Blk BT", "FreesiaUPC", "Freestyle Script", "French Script MT", "FrnkGothITC Bk BT", "Fruitger", "FRUTIGER",
"Futura", "Futura Bk BT", "Futura Lt BT", "Futura Md BT", "Futura ZBlk BT", "FuturaBlack BT", "Gabriola", "Galliard BT", "Garamond", "Gautami", "Geeza Pro", "Geneva", "Geometr231 BT", "Geometr231 Hv BT", "Geometr231 Lt BT", "Georgia", "GeoSlab 703 Lt BT",
"GeoSlab 703 XBd BT", "Gigi", "Gill Sans", "Gill Sans MT", "Gill Sans MT Condensed", "Gill Sans MT Ext Condensed Bold", "Gill Sans Ultra Bold", "Gill Sans Ultra Bold Condensed", "Gisha", "Gloucester MT Extra Condensed", "GOTHAM", "GOTHAM BOLD",
"Goudy Old Style", "Goudy Stout", "GoudyHandtooled BT", "GoudyOLSt BT", "Gujarati Sangam MN", "Gulim", "GulimChe", "Gungsuh", "GungsuhChe", "Gurmukhi MN", "Haettenschweiler", "Harlow Solid Italic", "Harrington", "Heather", "Heiti SC", "Heiti TC", "HELV", "Helvetica",
"Helvetica Neue", "Herald", "High Tower Text", "Hiragino Kaku Gothic ProN", "Hiragino Mincho ProN", "Hoefler Text", "Humanst 521 Cn BT", "Humanst521 BT", "Humanst521 Lt BT", "Impact", "Imprint MT Shadow", "Incised901 Bd BT", "Incised901 BT",
"Incised901 Lt BT", "INCONSOLATA", "Informal Roman", "Informal011 BT", "INTERSTATE", "IrisUPC", "Iskoola Pota", "JasmineUPC", "Jazz LET", "Jenson", "Jester", "Jokerman", "Juice ITC", "Kabel Bk BT", "Kabel Ult BT", "Kailasa", "KaiTi", "Kalinga", "Kannada Sangam MN",
"Kartika", "Kaufmann Bd BT", "Kaufmann BT", "Khmer UI", "KodchiangUPC", "Kokila", "Korinna BT", "Kristen ITC", "Krungthep", "Kunstler Script", "Lao UI", "Latha", "Leelawadee", "Letter Gothic", "Levenim MT", "LilyUPC", "Lithograph", "Lithograph Light", "Long Island",
"Lucida Bright", "Lucida Calligraphy", "Lucida Console", "Lucida Fax", "LUCIDA GRANDE", "Lucida Handwriting", "Lucida Sans", "Lucida Sans Typewriter", "Lucida Sans Unicode", "Lydian BT", "Magneto", "Maiandra GD", "Malayalam Sangam MN", "Malgun Gothic",
"Mangal", "Marigold", "Marion", "Marker Felt", "Market", "Marlett", "Matisse ITC", "Matura MT Script Capitals", "Meiryo", "Meiryo UI", "Microsoft Himalaya", "Microsoft JhengHei", "Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Sans Serif", "Microsoft Tai Le",
"Microsoft Uighur", "Microsoft YaHei", "Microsoft Yi Baiti", "MingLiU", "MingLiU_HKSCS", "MingLiU_HKSCS-ExtB", "MingLiU-ExtB", "Minion", "Minion Pro", "Miriam", "Miriam Fixed", "Mistral", "Modern", "Modern No. 20", "Mona Lisa Solid ITC TT", "Monaco", "Mongolian Baiti",
"MONO", "Monotype Corsiva", "MoolBoran", "Mrs Eaves", "MS Gothic", "MS LineDraw", "MS Mincho", "MS Outlook", "MS PGothic", "MS PMincho", "MS Reference Sans Serif", "MS Reference Specialty", "MS Sans Serif", "MS Serif", "MS UI Gothic", "MT Extra", "MUSEO", "MV Boli", "MYRIAD",
"MYRIAD PRO", "Nadeem", "Narkisim", "NEVIS", "News Gothic", "News GothicMT", "NewsGoth BT", "Niagara Engraved", "Niagara Solid", "Noteworthy", "NSimSun", "Nyala", "OCR A Extended", "Old Century", "Old English Text MT", "Onyx", "Onyx BT", "OPTIMA", "Oriya Sangam MN",
"OSAKA", "OzHandicraft BT", "Palace Script MT", "Palatino", "Palatino Linotype", "Papyrus", "Parchment", "Party LET", "Pegasus", "Perpetua", "Perpetua Titling MT", "PetitaBold", "Pickwick", "Plantagenet Cherokee", "Playbill", "PMingLiU", "PMingLiU-ExtB",
"Poor Richard", "Poster", "PosterBodoni BT", "PRINCETOWN LET", "Pristina", "PTBarnum BT", "Pythagoras", "Raavi", "Rage Italic", "Ravie", "Ribbon131 Bd BT", "Rockwell", "Rockwell Condensed", "Rockwell Extra Bold", "Rod", "Roman", "Sakkal Majalla",
"Santa Fe LET", "Savoye LET", "Sceptre", "Script", "Script MT Bold", "SCRIPTINA", "Segoe Print", "Segoe Script", "Segoe UI", "Segoe UI Light", "Segoe UI Semibold", "Segoe UI Symbol", "Serifa", "Serifa BT", "Serifa Th BT", "ShelleyVolante BT", "Sherwood",
"Shonar Bangla", "Showcard Gothic", "Shruti", "Signboard", "SILKSCREEN", "SimHei", "Simplified Arabic", "Simplified Arabic Fixed", "SimSun", "SimSun-ExtB", "Sinhala Sangam MN", "Sketch Rockwell", "Skia", "Small Fonts", "Snap ITC", "Snell Roundhand", "Socket",
"Souvenir Lt BT", "Staccato222 BT", "Steamer", "Stencil", "Storybook", "Styllo", "Subway", "Swis721 BlkEx BT", "Swiss911 XCm BT", "Sylfaen", "Synchro LET", "System", "Tahoma", "Tamil Sangam MN", "Technical", "Teletype", "Telugu Sangam MN", "Tempus Sans ITC",
"Terminal", "Thonburi", "Times", "Times New Roman", "Times New Roman PS", "Traditional Arabic", "Trajan", "TRAJAN PRO", "Trebuchet MS", "Tristan", "Tubular", "Tunga", "Tw Cen MT", "Tw Cen MT Condensed", "Tw Cen MT Condensed Extra Bold",
"TypoUpright BT", "Unicorn", "Univers", "Univers CE 55 Medium", "Univers Condensed", "Utsaah", "Vagabond", "Vani", "Verdana", "Vijaya", "Viner Hand ITC", "VisualUI", "Vivaldi", "Vladimir Script", "Vrinda", "Westminster", "WHITNEY", "Wide Latin", "Wingdings",
"Wingdings 2", "Wingdings 3", "ZapfEllipt BT", "ZapfHumnst BT", "ZapfHumnst Dm BT", "Zapfino", "Zurich BlkEx BT", "Zurich Ex BT", "ZWAdobeF"];
var available = [];
for (var i = 0, l = fontList.length; i < l; i++) {
if(detect(fontList[i])) {
available.push(fontList[i]);
}
}
keys.push(available.join(";"));
done(keys);
}, 1);
},
pluginsKey: function(keys) {
if(!this.options.excludePlugins){
if(this.isIE()){
keys.push(this.getIEPluginsString());
} else {
keys.push(this.getRegularPluginsString());
}
}
return keys;
},
getRegularPluginsString: function () {
var plugins = [];
for(var i = 0, l = navigator.plugins.length; i < l; i++) {
plugins.push(navigator.plugins[i]);
}
// sorting plugins only for those user agents, that we know randomize the plugins
// every time we try to enumerate them
if(this.pluginsShouldBeSorted()) {
plugins = plugins.sort(function(a, b) {
if(a.name > b.name){ return 1; }
if(a.name < b.name){ return -1; }
return 0;
});
}
return this.map(plugins, function (p) {
var mimeTypes = this.map(p, function(mt){
return [mt.type, mt.suffixes].join("~");
}).join(",");
return [p.name, p.description, mimeTypes].join("::");
}, this).join(";");
},
getIEPluginsString: function () {
if(window.ActiveXObject){
var names = [
"AcroPDF.PDF", // Adobe PDF reader 7+
"Adodb.Stream",
"AgControl.AgControl", // Silverlight
"DevalVRXCtrl.DevalVRXCtrl.1",
"MacromediaFlashPaper.MacromediaFlashPaper",
"Msxml2.DOMDocument",
"Msxml2.XMLHTTP",
"PDF.PdfCtrl", // Adobe PDF reader 6 and earlier, brrr
"QuickTime.QuickTime", // QuickTime
"QuickTimeCheckObject.QuickTimeCheck.1",
"RealPlayer",
"RealPlayer.RealPlayer(tm) ActiveX Control (32-bit)",
"RealVideo.RealVideo(tm) ActiveX Control (32-bit)",
"Scripting.Dictionary",
"SWCtl.SWCtl", // ShockWave player
"Shell.UIHelper",
"ShockwaveFlash.ShockwaveFlash", //flash plugin
"Skype.Detection",
"TDCCtl.TDCCtl",
"WMPlayer.OCX", // Windows media player
"rmocx.RealPlayer G2 Control",
"rmocx.RealPlayer G2 Control.1"
];
// starting to detect plugins in IE
return this.map(names, function(name){
try{
new ActiveXObject(name); // eslint-disable-no-new
return name;
} catch(e){
return null;
}
}).join(";");
} else {
return "";
}
},
pluginsShouldBeSorted: function () {
var should = false;
for(var i = 0, l = this.options.sortPluginsFor.length; i < l; i++) {
var re = this.options.sortPluginsFor[i];
if(navigator.userAgent.match(re)) {
should = true;
break;
}
}
return should;
},
touchSupportKey: function (keys) {
if(!this.options.excludeTouchSupport){
keys.push(this.getTouchSupport());
}
return keys;
},
hasSessionStorage: function () {
try {
return !!window.sessionStorage;
} catch(e) {
return true; // SecurityError when referencing it means it exists
}
},
// https://bugzilla.mozilla.org/show_bug.cgi?id=781447
hasLocalStorage: function () {
try {
return !!window.localStorage;
} catch(e) {
return true; // SecurityError when referencing it means it exists
}
},
hasIndexedDB: function (){
return !!window.indexedDB;
},
getNavigatorCpuClass: function () {
if(navigator.cpuClass){
return "navigatorCpuClass: " + navigator.cpuClass;
} else {
return "navigatorCpuClass: unknown";
}
},
getNavigatorPlatform: function () {
if(navigator.platform) {
return "navigatorPlatform: " + navigator.platform;
} else {
return "navigatorPlatform: unknown";
}
},
getDoNotTrack: function () {
if(navigator.doNotTrack) {
return "doNotTrack: " + navigator.doNotTrack;
} else {
return "doNotTrack: unknown";
}
},
// This is a crude and primitive touch screen detection.
// It's not possible to currently reliably detect the availability of a touch screen
// with a JS, without actually subscribing to a touch event.
// http://www.stucox.com/blog/you-cant-detect-a-touchscreen/
// https://github.com/Modernizr/Modernizr/issues/548
// method returns an array of 3 values:
// maxTouchPoints, the success or failure of creating a TouchEvent,
// and the availability of the 'ontouchstart' property
getTouchSupport: function () {
var maxTouchPoints = 0;
var touchEvent = false;
if(typeof navigator.maxTouchPoints !== "undefined") {
maxTouchPoints = navigator.maxTouchPoints;
} else if (typeof navigator.msMaxTouchPoints !== "undefined") {
maxTouchPoints = navigator.msMaxTouchPoints;
}
try {
document.createEvent("TouchEvent");
touchEvent = true;
} catch(_) { /* squelch */ }
var touchStart = "ontouchstart" in window;
return [maxTouchPoints, touchEvent, touchStart];
},
// https://www.browserleaks.com/canvas#how-does-it-work
getCanvasFp: function() {
var result = [];
// Very simple now, need to make it more complex (geo shapes etc)
var canvas = document.createElement("canvas");
canvas.width = 2000;
canvas.height = 200;
canvas.style.display = "inline";
var ctx = canvas.getContext("2d");
// detect browser support of canvas winding
// http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/canvas/winding.js
ctx.rect(0, 0, 10, 10);
ctx.rect(2, 2, 6, 6);
result.push("canvas winding:" + ((ctx.isPointInPath(5, 5, "evenodd") === false) ? "yes" : "no"));
ctx.textBaseline = "alphabetic";
ctx.fillStyle = "#f60";
ctx.fillRect(125, 1, 62, 20);
ctx.fillStyle = "#069";
ctx.font = "11pt no-real-font-123";
ctx.fillText("Cwm fjordbank glyphs vext quiz, \ud83d\ude03", 2, 15);
ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
ctx.font = "18pt Arial";
ctx.fillText("Cwm fjordbank glyphs vext quiz, \ud83d\ude03", 4, 45);
// canvas blending
// http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
// http://jsfiddle.net/NDYV8/16/
ctx.globalCompositeOperation = "multiply";
ctx.fillStyle = "rgb(255,0,255)";
ctx.beginPath();
ctx.arc(50, 50, 50, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.fillStyle = "rgb(0,255,255)";
ctx.beginPath();
ctx.arc(100, 50, 50, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.fillStyle = "rgb(255,255,0)";
ctx.beginPath();
ctx.arc(75, 100, 50, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.fillStyle = "rgb(255,0,255)";
// canvas winding
// http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/
// http://jsfiddle.net/NDYV8/19/
ctx.arc(75, 75, 75, 0, Math.PI * 2, true);
ctx.arc(75, 75, 25, 0, Math.PI * 2, true);
ctx.fill("evenodd");
result.push("canvas fp:" + canvas.toDataURL());
return result.join("~");
},
getWebglFp: function() {
var gl;
var fa2s = function(fa) {
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
return "[" + fa[0] + ", " + fa[1] + "]";
};
var maxAnisotropy = function(gl) {
var anisotropy, ext = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic");
return ext ? (anisotropy = gl.getParameter(ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT), 0 === anisotropy && (anisotropy = 2), anisotropy) : null;
};
gl = this.getWebglCanvas();
if(!gl) { return null; }
// WebGL fingerprinting is a combination of techniques, found in MaxMind antifraud script & Augur fingerprinting.
// First it draws a gradient object with shaders and convers the image to the Base64 string.
// Then it enumerates all WebGL extensions & capabilities and appends them to the Base64 string, resulting in a huge WebGL string, potentially very unique on each device
// Since iOS supports webgl starting from version 8.1 and 8.1 runs on several graphics chips, the results may be different across ios devices, but we need to verify it.
var result = [];
var vShaderTemplate = "attribute vec2 attrVertex;varying vec2 varyinTexCoordinate;uniform vec2 uniformOffset;void main(){varyinTexCoordinate=attrVertex+uniformOffset;gl_Position=vec4(attrVertex,0,1);}";
var fShaderTemplate = "precision mediump float;varying vec2 varyinTexCoordinate;void main() {gl_FragColor=vec4(varyinTexCoordinate,0,1);}";
var vertexPosBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPosBuffer);
var vertices = new Float32Array([-.2, -.9, 0, .4, -.26, 0, 0, .732134444, 0]);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
vertexPosBuffer.itemSize = 3;
vertexPosBuffer.numItems = 3;
var program = gl.createProgram(), vshader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vshader, vShaderTemplate);
gl.compileShader(vshader);
var fshader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fshader, fShaderTemplate);
gl.compileShader(fshader);
gl.attachShader(program, vshader);
gl.attachShader(program, fshader);
gl.linkProgram(program);
gl.useProgram(program);
program.vertexPosAttrib = gl.getAttribLocation(program, "attrVertex");
program.offsetUniform = gl.getUniformLocation(program, "uniformOffset");
gl.enableVertexAttribArray(program.vertexPosArray);
gl.vertexAttribPointer(program.vertexPosAttrib, vertexPosBuffer.itemSize, gl.FLOAT, !1, 0, 0);
gl.uniform2f(program.offsetUniform, 1, 1);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, vertexPosBuffer.numItems);
if (gl.canvas != null) { result.push(gl.canvas.toDataURL()); }
result.push("extensions:" + gl.getSupportedExtensions().join(";"));
result.push("webgl aliased line width range:" + fa2s(gl.getParameter(gl.ALIASED_LINE_WIDTH_RANGE)));
result.push("webgl aliased point size range:" + fa2s(gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE)));
result.push("webgl alpha bits:" + gl.getParameter(gl.ALPHA_BITS));
result.push("webgl antialiasing:" + (gl.getContextAttributes().antialias ? "yes" : "no"));
result.push("webgl blue bits:" + gl.getParameter(gl.BLUE_BITS));
result.push("webgl depth bits:" + gl.getParameter(gl.DEPTH_BITS));
result.push("webgl green bits:" + gl.getParameter(gl.GREEN_BITS));
result.push("webgl max anisotropy:" + maxAnisotropy(gl));
result.push("webgl max combined texture image units:" + gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS));
result.push("webgl max cube map texture size:" + gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE));
result.push("webgl max fragment uniform vectors:" + gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS));
result.push("webgl max render buffer size:" + gl.getParameter(gl.MAX_RENDERBUFFER_SIZE));
result.push("webgl max texture image units:" + gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS));
result.push("webgl max texture size:" + gl.getParameter(gl.MAX_TEXTURE_SIZE));
result.push("webgl max varying vectors:" + gl.getParameter(gl.MAX_VARYING_VECTORS));
result.push("webgl max vertex attribs:" + gl.getParameter(gl.MAX_VERTEX_ATTRIBS));
result.push("webgl max vertex texture image units:" + gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS));
result.push("webgl max vertex uniform vectors:" + gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS));
result.push("webgl max viewport dims:" + fa2s(gl.getParameter(gl.MAX_VIEWPORT_DIMS)));
result.push("webgl red bits:" + gl.getParameter(gl.RED_BITS));
result.push("webgl renderer:" + gl.getParameter(gl.RENDERER));
result.push("webgl shading language version:" + gl.getParameter(gl.SHADING_LANGUAGE_VERSION));
result.push("webgl stencil bits:" + gl.getParameter(gl.STENCIL_BITS));
result.push("webgl vendor:" + gl.getParameter(gl.VENDOR));
result.push("webgl version:" + gl.getParameter(gl.VERSION));
if (!gl.getShaderPrecisionFormat) {
if (typeof NODEBUG === "undefined") {
this.log("WebGL fingerprinting is incomplete, because your browser does not support getShaderPrecisionFormat");
}
return result.join("~");
}
result.push("webgl vertex shader high float precision:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision);
result.push("webgl vertex shader high float precision rangeMin:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT ).rangeMin);
result.push("webgl vertex shader high float precision rangeMax:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT ).rangeMax);
result.push("webgl vertex shader medium float precision:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision);
result.push("webgl vertex shader medium float precision rangeMin:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).rangeMin);
result.push("webgl vertex shader medium float precision rangeMax:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).rangeMax);
result.push("webgl vertex shader low float precision:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT ).precision);
result.push("webgl vertex shader low float precision rangeMin:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT ).rangeMin);
result.push("webgl vertex shader low float precision rangeMax:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT ).rangeMax);
result.push("webgl fragment shader high float precision:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision);
result.push("webgl fragment shader high float precision rangeMin:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).rangeMin);
result.push("webgl fragment shader high float precision rangeMax:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).rangeMax);
result.push("webgl fragment shader medium float precision:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision);
result.push("webgl fragment shader medium float precision rangeMin:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).rangeMin);
result.push("webgl fragment shader medium float precision rangeMax:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).rangeMax);
result.push("webgl fragment shader low float precision:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT ).precision);
result.push("webgl fragment shader low float precision rangeMin:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT ).rangeMin);
result.push("webgl fragment shader low float precision rangeMax:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT ).rangeMax);
result.push("webgl vertex shader high int precision:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_INT ).precision);
result.push("webgl vertex shader high int precision rangeMin:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_INT ).rangeMin);
result.push("webgl vertex shader high int precision rangeMax:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_INT ).rangeMax);
result.push("webgl vertex shader medium int precision:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_INT ).precision);
result.push("webgl vertex shader medium int precision rangeMin:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_INT ).rangeMin);
result.push("webgl vertex shader medium int precision rangeMax:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_INT ).rangeMax);
result.push("webgl vertex shader low int precision:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_INT ).precision);
result.push("webgl vertex shader low int precision rangeMin:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_INT ).rangeMin);
result.push("webgl vertex shader low int precision rangeMax:" + gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_INT ).rangeMax);
result.push("webgl fragment shader high int precision:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT ).precision);
result.push("webgl fragment shader high int precision rangeMin:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT ).rangeMin);
result.push("webgl fragment shader high int precision rangeMax:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT ).rangeMax);
result.push("webgl fragment shader medium int precision:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT ).precision);
result.push("webgl fragment shader medium int precision rangeMin:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT ).rangeMin);
result.push("webgl fragment shader medium int precision rangeMax:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT ).rangeMax);
result.push("webgl fragment shader low int precision:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT ).precision);
result.push("webgl fragment shader low int precision rangeMin:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT ).rangeMin);
result.push("webgl fragment shader low int precision rangeMax:" + gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT ).rangeMax);
return result.join("~");
},
getAdBlock: function(){
var ads = document.createElement("div");
ads.setAttribute("id", "ads");
document.body.appendChild(ads);
return document.getElementById("ads") ? false : true;
},
getHasLiedLanguages: function(){
//We check if navigator.language is equal to the first language of navigator.languages
if(typeof navigator.languages !== "undefined"){
try {
var firstLanguages = navigator.languages[0].substr(0, 2);
if(firstLanguages !== navigator.language.substr(0, 2)){
return true;
}
} catch(err){
return true;
}
}
return false;
},
getHasLiedResolution: function(){
if(screen.width < screen.availWidth){
return true;
}
if(screen.height < screen.availHeight){
return true;
}
return false;
},
getHasLiedOs: function(){
var userAgent = navigator.userAgent.toLowerCase();
var oscpu = navigator.oscpu;
var platform = navigator.platform.toLowerCase();
var os;
//We extract the OS from the user agent (respect the order of the if else if statement)
if(userAgent.indexOf("windows phone") >= 0){
os = "Windows Phone";
} else if(userAgent.indexOf("win") >= 0){
os = "Windows";
} else if(userAgent.indexOf("android") >= 0){
os = "Android";
} else if(userAgent.indexOf("linux") >= 0){
os = "Linux";
} else if(userAgent.indexOf("iPhone") >= 0 || userAgent.indexOf("iPad") >= 0 ){
os = "iOS";
} else if(userAgent.indexOf("mac") >= 0){
os = "Mac";
} else{
os = "Other";
}
// We detect if the person uses a mobile device
var mobileDevice;
if (("ontouchstart" in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0)) {
mobileDevice = true;
} else{
mobileDevice = false;
}
if(mobileDevice && os !== "Windows Phone" && os !== "Android" && os !== "iOS" && os !== "Other"){
return true;
}
// We compare oscpu with the OS extracted from the UA
if(typeof oscpu !== "undefined"){
oscpu = oscpu.toLowerCase();
if(oscpu.indexOf("win") >= 0 && os !== "Windows" && os !== "Windows Phone"){
return true;
} else if(oscpu.indexOf("linux") >= 0 && os !== "Linux" && os !== "Android"){
return true;
} else if(oscpu.indexOf("mac") >= 0 && os !== "Mac" && os !== "iOS"){
return true;
} else if(oscpu.indexOf("win") === 0 && oscpu.indexOf("linux") === 0 && oscpu.indexOf("mac") >= 0 && os !== "other"){
return true;
}
}
//We compare platform with the OS extracted from the UA
if(platform.indexOf("win") >= 0 && os !== "Windows" && os !== "Windows Phone"){
return true;
} else if((platform.indexOf("linux") >= 0 || platform.indexOf("android") >= 0 || platform.indexOf("pike") >= 0) && os !== "Linux" && os !== "Android"){
return true;
} else if((platform.indexOf("mac") >= 0 || platform.indexOf("ipad") >= 0 || platform.indexOf("ipod") >= 0 || platform.indexOf("iphone") >= 0) && os !== "Mac" && os !== "iOS"){
return true;
} else if(platform.indexOf("win") === 0 && platform.indexOf("linux") === 0 && platform.indexOf("mac") >= 0 && os !== "other"){
return true;
}
if(typeof navigator.plugins === "undefined" && os !== "Windows" && os !== "Windows Phone"){
//We are are in the case where the person uses ie, therefore we can infer that it's windows
return true;
}
return false;
},
getHasLiedBrowser: function () {
var userAgent = navigator.userAgent.toLowerCase();
var productSub = navigator.productSub;
//we extract the browser from the user agent (respect the order of the tests)
var browser;
if(userAgent.indexOf("firefox") >= 0){
browser = "Firefox";
} else if(userAgent.indexOf("opera") >= 0 || userAgent.indexOf("opr") >= 0){
browser = "Opera";
} else if(userAgent.indexOf("chrome") >= 0){
browser = "Chrome";
} else if(userAgent.indexOf("safari") >= 0){
browser = "Safari";
} else if(userAgent.indexOf("trident") >= 0){
browser = "Internet Explorer";
} else{
browser = "Other";
}
if((browser === "Chrome" || browser === "Safari" || browser === "Opera") && productSub !== "20030107"){
return true;
}
var tempRes = eval.toString().length;
if(tempRes === 37 && browser !== "Safari" && browser !== "Firefox" && browser !== "Other"){
return true;
} else if(tempRes === 39 && browser !== "Internet Explorer" && browser !== "Other"){
return true;
} else if(tempRes === 33 && browser !== "Chrome" && browser !== "Opera" && browser !== "Other"){
return true;
}
//We create an error to see how it is handled
var errFirefox;
try {
throw "a";
} catch(err){
try{
err.toSource();
errFirefox = true;
} catch(errOfErr){
errFirefox = false;
}
}
if(errFirefox && browser !== "Firefox" && browser !== "Other"){
return true;
}
return false;
},
isCanvasSupported: function () {
var elem = document.createElement("canvas");
return !!(elem.getContext && elem.getContext("2d"));
},
isWebGlSupported: function() {
// code taken from Modernizr
if (!this.isCanvasSupported()) {
return false;
}
var canvas = document.createElement("canvas"),
glContext;
try {
glContext = canvas.getContext && (canvas.getContext("webgl") || canvas.getContext("experimental-webgl"));
} catch(e) {
glContext = false;
}
return !!window.WebGLRenderingContext && !!glContext;
},
isIE: function () {
if(navigator.appName === "Microsoft Internet Explorer") {
return true;
} else if(navigator.appName === "Netscape" && /Trident/.test(navigator.userAgent)) { // IE 11
return true;
}
return false;
},
hasSwfObjectLoaded: function(){
return typeof window.swfobject !== "undefined";
},
hasMinFlashInstalled: function () {
return swfobject.hasFlashPlayerVersion("9.0.0");
},
addFlashDivNode: function() {
var node = document.createElement("div");
node.setAttribute("id", this.options.swfContainerId);
document.body.appendChild(node);
},
loadSwfAndDetectFonts: function(done) {
var hiddenCallback = "___fp_swf_loaded";
window[hiddenCallback] = function(fonts) {
done(fonts);
};
var id = this.options.swfContainerId;
this.addFlashDivNode();
var flashvars = { onReady: hiddenCallback};
var flashparams = { allowScriptAccess: "always", menu: "false" };
swfobject.embedSWF(this.options.swfPath, id, "1", "1", "9.0.0", false, flashvars, flashparams, {});
},
getWebglCanvas: function() {
var canvas = document.createElement("canvas");
var gl = null;
try {
gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
} catch(e) { /* squelch */ }
if (!gl) { gl = null; }
return gl;
},
each: function (obj, iterator, context) {
if (obj === null) {
return;
}
if (this.nativeForEach && obj.forEach === this.nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === {}) { return; }
}
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (iterator.call(context, obj[key], key, obj) === {}) { return; }
}
}
}
},
map: function(obj, iterator, context) {
var results = [];
// Not using strict equality so that this acts as a
// shortcut to checking for `null` and `undefined`.
if (obj == null) { return results; }
if (this.nativeMap && obj.map === this.nativeMap) { return obj.map(iterator, context); }
this.each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
return results;
},
/// MurmurHash3 related functions
//
// Given two 64bit ints (as an array of two 32bit ints) returns the two
// added together as a 64bit int (as an array of two 32bit ints).
//
x64Add: function(m, n) {
m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];
n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];
var o = [0, 0, 0, 0];
o[3] += m[3] + n[3];
o[2] += o[3] >>> 16;
o[3] &= 0xffff;
o[2] += m[2] + n[2];
o[1] += o[2] >>> 16;
o[2] &= 0xffff;
o[1] += m[1] + n[1];
o[0] += o[1] >>> 16;
o[1] &= 0xffff;
o[0] += m[0] + n[0];
o[0] &= 0xffff;
return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];
},
//
// Given two 64bit ints (as an array of two 32bit ints) returns the two
// multiplied together as a 64bit int (as an array of two 32bit ints).
//
x64Multiply: function(m, n) {
m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];
n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];
var o = [0, 0, 0, 0];
o[3] += m[3] * n[3];
o[2] += o[3] >>> 16;
o[3] &= 0xffff;
o[2] += m[2] * n[3];
o[1] += o[2] >>> 16;
o[2] &= 0xffff;
o[2] += m[3] * n[2];
o[1] += o[2] >>> 16;
o[2] &= 0xffff;
o[1] += m[1] * n[3];
o[0] += o[1] >>> 16;
o[1] &= 0xffff;
o[1] += m[2] * n[2];
o[0] += o[1] >>> 16;
o[1] &= 0xffff;
o[1] += m[3] * n[1];
o[0] += o[1] >>> 16;
o[1] &= 0xffff;
o[0] += (m[0] * n[3]) + (m[1] * n[2]) + (m[2] * n[1]) + (m[3] * n[0]);
o[0] &= 0xffff;
return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];
},
//
// Given a 64bit int (as an array of two 32bit ints) and an int
// representing a number of bit positions, returns the 64bit int (as an
// array of two 32bit ints) rotated left by that number of positions.
//
x64Rotl: function(m, n) {
n %= 64;
if (n === 32) {
return [m[1], m[0]];
}
else if (n < 32) {
return [(m[0] << n) | (m[1] >>> (32 - n)), (m[1] << n) | (m[0] >>> (32 - n))];
}
else {
n -= 32;
return [(m[1] << n) | (m[0] >>> (32 - n)), (m[0] << n) | (m[1] >>> (32 - n))];
}
},
//
// Given a 64bit int (as an array of two 32bit ints) and an int
// representing a number of bit positions, returns the 64bit int (as an
// array of two 32bit ints) shifted left by that number of positions.
//
x64LeftShift: function(m, n) {
n %= 64;
if (n === 0) {
return m;
}
else if (n < 32) {
return [(m[0] << n) | (m[1] >>> (32 - n)), m[1] << n];
}
else {
return [m[1] << (n - 32), 0];
}
},
//
// Given two 64bit ints (as an array of two 32bit ints) returns the two
// xored together as a 64bit int (as an array of two 32bit ints).
//
x64Xor: function(m, n) {
return [m[0] ^ n[0], m[1] ^ n[1]];
},
//
// Given a block, returns murmurHash3's final x64 mix of that block.
// (`[0, h[0] >>> 1]` is a 33 bit unsigned right shift. This is the
// only place where we need to right shift 64bit ints.)
//
x64Fmix: function(h) {
h = this.x64Xor(h, [0, h[0] >>> 1]);
h = this.x64Multiply(h, [0xff51afd7, 0xed558ccd]);
h = this.x64Xor(h, [0, h[0] >>> 1]);
h = this.x64Multiply(h, [0xc4ceb9fe, 0x1a85ec53]);
h = this.x64Xor(h, [0, h[0] >>> 1]);
return h;
},
//
// Given a string and an optional seed as an int, returns a 128 bit
// hash using the x64 flavor of MurmurHash3, as an unsigned hex.
//
x64hash128: function (key, seed) {
key = key || "";
seed = seed || 0;
var remainder = key.length % 16;
var bytes = key.length - remainder;
var h1 = [0, seed];
var h2 = [0, seed];
var k1 = [0, 0];
var k2 = [0, 0];
var c1 = [0x87c37b91, 0x114253d5];
var c2 = [0x4cf5ad43, 0x2745937f];
for (var i = 0; i < bytes; i = i + 16) {
k1 = [((key.charCodeAt(i + 4) & 0xff)) | ((key.charCodeAt(i + 5) & 0xff) << 8) | ((key.charCodeAt(i + 6) & 0xff) << 16) | ((key.charCodeAt(i + 7) & 0xff) << 24), ((key.charCodeAt(i) & 0xff)) | ((key.charCodeAt(i + 1) & 0xff) << 8) | ((key.charCodeAt(i + 2) & 0xff) << 16) | ((key.charCodeAt(i + 3) & 0xff) << 24)];
k2 = [((key.charCodeAt(i + 12) & 0xff)) | ((key.charCodeAt(i + 13) & 0xff) << 8) | ((key.charCodeAt(i + 14) & 0xff) << 16) | ((key.charCodeAt(i + 15) & 0xff) << 24), ((key.charCodeAt(i + 8) & 0xff)) | ((key.charCodeAt(i + 9) & 0xff) << 8) | ((key.charCodeAt(i + 10) & 0xff) << 16) | ((key.charCodeAt(i + 11) & 0xff) << 24)];
k1 = this.x64Multiply(k1, c1);
k1 = this.x64Rotl(k1, 31);
k1 = this.x64Multiply(k1, c2);
h1 = this.x64Xor(h1, k1);
h1 = this.x64Rotl(h1, 27);
h1 = this.x64Add(h1, h2);
h1 = this.x64Add(this.x64Multiply(h1, [0, 5]), [0, 0x52dce729]);
k2 = this.x64Multiply(k2, c2);
k2 = this.x64Rotl(k2, 33);
k2 = this.x64Multiply(k2, c1);
h2 = this.x64Xor(h2, k2);
h2 = this.x64Rotl(h2, 31);
h2 = this.x64Add(h2, h1);
h2 = this.x64Add(this.x64Multiply(h2, [0, 5]), [0, 0x38495ab5]);
}
k1 = [0, 0];
k2 = [0, 0];
switch(remainder) {
case 15:
k2 = this.x64Xor(k2, this.x64LeftShift([0, key.charCodeAt(i + 14)], 48));
case 14:
k2 = this.x64Xor(k2, this.x64LeftShift([0, key.charCodeAt(i + 13)], 40));
case 13:
k2 = this.x64Xor(k2, this.x64LeftShift([0, key.charCodeAt(i + 12)], 32));
case 12:
k2 = this.x64Xor(k2, this.x64LeftShift([0, key.charCodeAt(i + 11)], 24));
case 11:
k2 = this.x64Xor(k2, this.x64LeftShift([0, key.charCodeAt(i + 10)], 16));
case 10:
k2 = this.x64Xor(k2, this.x64LeftShift([0, key.charCodeAt(i + 9)], 8));
case 9:
k2 = this.x64Xor(k2, [0, key.charCodeAt(i + 8)]);
k2 = this.x64Multiply(k2, c2);
k2 = this.x64Rotl(k2, 33);
k2 = this.x64Multiply(k2, c1);
h2 = this.x64Xor(h2, k2);
case 8:
k1 = this.x64Xor(k1, this.x64LeftShift([0, key.charCodeAt(i + 7)], 56));
case 7:
k1 = this.x64Xor(k1, this.x64LeftShift([0, key.charCodeAt(i + 6)], 48));
case 6:
k1 = this.x64Xor(k1, this.x64LeftShift([0, key.charCodeAt(i + 5)], 40));
case 5:
k1 = this.x64Xor(k1, this.x64LeftShift([0, key.charCodeAt(i + 4)], 32));
case 4:
k1 = this.x64Xor(k1, this.x64LeftShift([0, key.charCodeAt(i + 3)], 24));
case 3:
k1 = this.x64Xor(k1, this.x64LeftShift([0, key.charCodeAt(i + 2)], 16));
case 2:
k1 = this.x64Xor(k1, this.x64LeftShift([0, key.charCodeAt(i + 1)], 8));
case 1:
k1 = this.x64Xor(k1, [0, key.charCodeAt(i)]);
k1 = this.x64Multiply(k1, c1);
k1 = this.x64Rotl(k1, 31);
k1 = this.x64Multiply(k1, c2);
h1 = this.x64Xor(h1, k1);
}
h1 = this.x64Xor(h1, [0, key.length]);
h2 = this.x64Xor(h2, [0, key.length]);
h1 = this.x64Add(h1, h2);
h2 = this.x64Add(h2, h1);
h1 = this.x64Fmix(h1);
h2 = this.x64Fmix(h2);
h1 = this.x64Add(h1, h2);
h2 = this.x64Add(h2, h1);
return ("00000000" + (h1[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (h1[1] >>> 0).toString(16)).slice(-8) + ("00000000" + (h2[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (h2[1] >>> 0).toString(16)).slice(-8);
}
};
Fingerprint2.VERSION = "0.7.3";
return Fingerprint2;
});
| ahocevar/cdnjs | ajax/libs/fingerprintjs2/0.7.3/fingerprint2.js | JavaScript | mit | 54,829 |
/*
* The MIT License
*
* Copyright (c) 2013 Red Hat, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.cli;
import org.kohsuke.args4j.Argument;
import jenkins.model.Jenkins;
import hudson.Extension;
import hudson.model.Failure;
import hudson.model.View;
/**
* @author ogondza
* @since 1.538
*/
@Extension
public class CreateViewCommand extends CLICommand {
@Argument(usage="Name of the view to use instead of the one in XML")
public String viewName = null;
@Override
public String getShortDescription() {
return Messages.CreateViewCommand_ShortDescription();
}
@Override
protected int run() throws Exception {
final Jenkins jenkins = Jenkins.get();
jenkins.checkPermission(View.CREATE);
View newView;
try {
newView = View.createViewFromXML(viewName, stdin);
} catch (Failure ex) {
throw new IllegalArgumentException("Invalid view name: " + ex.getMessage());
}
final String newName = newView.getViewName();
if (jenkins.getView(newName) != null) {
throw new IllegalStateException("View '" + newName + "' already exists");
}
jenkins.addView(newView);
return 0;
}
}
| oleg-nenashev/jenkins | core/src/main/java/hudson/cli/CreateViewCommand.java | Java | mit | 2,294 |
<!DOCTYPE html>
<html class="minimal">
<title>Canvas test: 2d.imageData.put.alpha</title>
<script src="../tests.js"></script>
<link rel="stylesheet" href="../tests.css">
<link rel="prev" href="minimal.2d.imageData.put.cross.html" title="2d.imageData.put.cross">
<link rel="next" href="minimal.2d.imageData.put.modified.html" title="2d.imageData.put.modified">
<body>
<p id="passtext">Pass</p>
<p id="failtext">Fail</p>
<!-- TODO: handle "script did not run" case -->
<p class="output">These images should be identical:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<p class="output expectedtext">Expected output:<p><img src="2d.imageData.put.alpha.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
_addTest(function(canvas, ctx) {
ctx.fillStyle = 'rgba(0, 255, 0, 0.25)';
ctx.fillRect(0, 0, 100, 50)
var imgdata = ctx.getImageData(0, 0, 100, 50);
ctx.fillStyle = '#f00';
ctx.fillRect(0, 0, 100, 50)
ctx.putImageData(imgdata, 0, 0);
_assertPixelApprox(canvas, 50,25, 0,255,0,64, "50,25", "0,255,0,64", 2);
});
</script>
| corbanbrook/webgl-2d | test/philip.html5.org/tests/minimal.2d.imageData.put.alpha.html | HTML | mit | 1,119 |
<a href="{{ homepage() }}" class="text-logo">{{ theme_project_nav_name or shorttitle }}</a>
| hahaps/dive-into-openstack | source/_themes/guzzle_sphinx_theme/logo-text.html | HTML | mit | 92 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Tests;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class ConcurrentStackTests : IEnumerable_Generic_Tests<int>
{
protected override IEnumerable<ModifyEnumerable> ModifyEnumerables => new List<ModifyEnumerable>();
protected override IEnumerable<int> GenericIEnumerableFactory(int count) => new ConcurrentStack<int>(Enumerable.Range(0, count));
protected override int CreateT(int seed) => new Random(seed).Next();
protected override EnumerableOrder Order => EnumerableOrder.Unspecified;
protected override bool ResetImplemented => false;
protected override bool IEnumerable_Generic_Enumerator_Current_EnumerationNotStarted_ThrowsInvalidOperationException => false;
[Fact]
public static void Test0_Empty()
{
ConcurrentStack<int> s = new ConcurrentStack<int>();
int item;
Assert.False(s.TryPop(out item), "Test0_Empty: TryPop returned true when the stack is empty");
Assert.False(s.TryPeek(out item), "Test0_Empty: TryPeek returned true when the stack is empty");
Assert.True(s.TryPopRange(new int[1]) == 0, "Test0_Empty: TryPopRange returned non zero when the stack is empty");
int count = 15;
for (int i = 0; i < count; i++)
s.Push(i);
Assert.Equal(count, s.Count);
Assert.False(s.IsEmpty);
}
[Fact]
public static void Test1_PushAndPop()
{
Test1_PushAndPop(0, 0);
Test1_PushAndPop(9, 9);
}
[Fact]
[OuterLoop]
public static void Test1_PushAndPop01()
{
Test1_PushAndPop(3, 0);
Test1_PushAndPop(1024, 512);
}
[Fact]
public static void Test2_ConcPushAndPop()
{
Test2_ConcPushAndPop(3, 1024, 0);
}
[Fact]
public static void Test2_ConcPushAndPop01()
{
Test2_ConcPushAndPop(8, 1024, 512);
}
[Fact]
public static void Test3_Clear()
{
Test3_Clear(0);
Test3_Clear(16);
Test3_Clear(1024);
}
[Fact]
public static void Test4_Enumerator()
{
Test4_Enumerator(0);
Test4_Enumerator(16);
}
[Fact]
[OuterLoop]
public static void Test4_Enumerator01()
{
Test4_Enumerator(1024);
}
[Fact]
public static void Test5_CtorAndCopyToAndToArray()
{
Test5_CtorAndCopyToAndToArray(0);
Test5_CtorAndCopyToAndToArray(16);
}
[Fact]
[OuterLoop]
public static void Test5_CtorAndCopyToAndToArray01()
{
Test5_CtorAndCopyToAndToArray(1024);
}
[Fact]
public static void Test6_PushRange()
{
Test6_PushRange(8, 10);
Test6_PushRange(16, 100);
}
[Fact]
public static void Test7_PopRange()
{
Test7_PopRange(8, 10);
Test7_PopRange(16, 100);
}
[Fact]
[OuterLoop]
public static void Test_PushPopRange()
{
Test6_PushRange(128, 100);
Test7_PopRange(128, 100);
}
// Pushes and pops a certain number of times, and validates the resulting count.
// These operations happen sequentially in a somewhat-interleaved fashion. We use
// a BCL stack on the side to validate contents are correctly maintained.
private static void Test1_PushAndPop(int pushes, int pops)
{
// It utilized a random generator to do x number of pushes and
// y number of pops where x = random, y = random. Removed it
// because it used System.Runtime.Extensions.
ConcurrentStack<int> s = new ConcurrentStack<int>();
Stack<int> s2 = new Stack<int>();
int donePushes = 0, donePops = 0;
while (donePushes < pushes || donePops < pops)
{
for (int i = 0; i < 10; i++)
{
if (donePushes == pushes)
break;
int val = i;
s.Push(val);
s2.Push(val);
donePushes++;
Assert.Equal(s.Count, s2.Count);
}
for (int i = 0; i < 6; i++)
{
if (donePops == pops)
break;
if ((donePushes - donePops) <= 0)
break;
int e0, e1, e2;
bool b0 = s.TryPeek(out e0);
bool b1 = s.TryPop(out e1);
e2 = s2.Pop();
donePops++;
Assert.True(b0);
Assert.True(b1);
Assert.Equal(e0, e1);
Assert.Equal(e1, e2);
Assert.Equal(s.Count, s2.Count);
}
}
Assert.Equal(pushes - pops, s.Count);
}
// Pushes and pops a certain number of times, and validates the resulting count.
// These operations happen concurrently.
private static void Test2_ConcPushAndPop(int threads, int pushes, int pops)
{
// It utilized a random generator to do x number of pushes and
// y number of pops where x = random, y = random. Removed it
// because it used System.Runtime.Extensions.
ConcurrentStack<int> s = new ConcurrentStack<int>();
ManualResetEvent mre = new ManualResetEvent(false);
Task[] tt = new Task[threads];
// Create all threads.
for (int k = 0; k < tt.Length; k++)
{
tt[k] = Task.Run(delegate()
{
mre.WaitOne();
int donePushes = 0, donePops = 0;
while (donePushes < pushes || donePops < pops)
{
for (int i = 0; i < 8; i++)
{
if (donePushes == pushes)
break;
s.Push(i);
donePushes++;
}
for (int i = 0; i < 4; i++)
{
if (donePops == pops)
break;
if ((donePushes - donePops) <= 0)
break;
int e;
if (s.TryPop(out e))
donePops++;
}
}
});
}
// Kick 'em off and wait for them to finish.
mre.Set();
Task.WaitAll(tt);
// Validate the count.
Assert.Equal(threads * (pushes - pops), s.Count);
}
// Just validates clearing the stack's contents.
private static void Test3_Clear(int count)
{
ConcurrentStack<int> s = new ConcurrentStack<int>();
for (int i = 0; i < count; i++)
s.Push(i);
s.Clear();
Assert.True(s.IsEmpty);
Assert.Equal(0, s.Count);
}
// Just validates enumerating the stack.
private static void Test4_Enumerator(int count)
{
ConcurrentStack<int> s = new ConcurrentStack<int>();
for (int i = 0; i < count; i++)
s.Push(i);
// Test enumerator.
int j = count - 1;
foreach (int x in s)
{
// Clear the stack to ensure concurrent modifications are dealt w/.
if (x == count - 1)
{
int e;
while (s.TryPop(out e)) ;
}
Assert.Equal(j, x);
j--;
}
Assert.True(j <= 0, " > did not enumerate all elements in the stack");
}
// Instantiates the stack w/ the enumerator ctor and validates the resulting copyto & toarray.
private static void Test5_CtorAndCopyToAndToArray(int count)
{
int[] arr = new int[count];
for (int i = 0; i < count; i++) arr[i] = i;
ConcurrentStack<int> s = new ConcurrentStack<int>(arr);
// try toarray.
int[] sa1 = s.ToArray();
Assert.Equal(arr.Length, sa1.Length);
for (int i = 0; i < sa1.Length; i++)
{
Assert.Equal(arr[count - i - 1], sa1[i]);
}
int[] sa2 = new int[count];
s.CopyTo(sa2, 0);
Assert.Equal(arr.Length, sa2.Length);
for (int i = 0; i < sa2.Length; i++)
{
Assert.Equal(arr[count - i - 1], sa2[i]);
}
object[] sa3 = new object[count]; // test array variance.
((System.Collections.ICollection)s).CopyTo(sa3, 0);
Assert.Equal(arr.Length, sa3.Length);
for (int i = 0; i < sa3.Length; i++)
{
Assert.Equal(arr[count - i - 1], (int)sa3[i]);
}
}
//Tests COncurrentSTack.PushRange
private static void Test6_PushRange(int NumOfThreads, int localArraySize)
{
ConcurrentStack<int> stack = new ConcurrentStack<int>();
Task[] threads = new Task[NumOfThreads];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = Task.Factory.StartNew((obj) =>
{
int index = (int)obj;
int[] array = new int[localArraySize];
for (int j = 0; j < localArraySize; j++)
{
array[j] = index + j;
}
stack.PushRange(array);
}, i * localArraySize, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
Task.WaitAll(threads);
//validation
for (int i = 0; i < threads.Length; i++)
{
int lastItem = -1;
for (int j = 0; j < localArraySize; j++)
{
int currentItem = 0;
Assert.True(stack.TryPop(out currentItem),
String.Format("* Test6_PushRange({0},{1})L TryPop returned false.", NumOfThreads, localArraySize));
Assert.True((lastItem <= -1) || lastItem - currentItem == 1,
String.Format("* Test6_PushRange({0},{1}): Failed {2} - {3} shouldn't be consecutive", NumOfThreads, localArraySize, lastItem, currentItem));
lastItem = currentItem;
}
}
}
//Tests ConcurrentStack.PopRange by pushing consecutive numbers and run n threads each thread tries to pop m itmes
// the popped m items should be consecutive
private static void Test7_PopRange(int NumOfThreads, int elementsPerThread)
{
int lastValue = NumOfThreads * elementsPerThread;
List<int> allValues = new List<int>();
for (int i = 1; i <= lastValue; i++)
allValues.Add(i);
ConcurrentStack<int> stack = new ConcurrentStack<int>(allValues);
Task[] threads = new Task[NumOfThreads];
int[] array = new int[threads.Length * elementsPerThread];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = Task.Factory.StartNew((obj) =>
{
int index = (int)obj;
int res = stack.TryPopRange(array, index, elementsPerThread);
Assert.Equal(elementsPerThread, res);
}, i * elementsPerThread, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
Task.WaitAll(threads);
// validation
for (int i = 0; i < NumOfThreads; i++)
{
for (int j = 1; j < elementsPerThread; j++)
{
int currentIndex = i * elementsPerThread + j;
Assert.Equal(array[currentIndex - 1], array[currentIndex] + 1);
}
}
}
[Fact]
public static void Test8_Exceptions()
{
ConcurrentStack<int> stack = null;
Assert.Throws<ArgumentNullException>(
() => stack = new ConcurrentStack<int>((IEnumerable<int>)null));
// "Test8_Exceptions: The constructor didn't throw ANE when null collection passed");
stack = new ConcurrentStack<int>();
//CopyTo
Assert.Throws<ArgumentNullException>(
() => stack.CopyTo(null, 0));
// "Test8_Exceptions: CopyTo didn't throw ANE when null array passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => stack.CopyTo(new int[1], -1));
// "Test8_Exceptions: CopyTo didn't throw AORE when negative array index passed");
//PushRange
Assert.Throws<ArgumentNullException>(
() => stack.PushRange(null));
// "Test8_Exceptions: PushRange didn't throw ANE when null array passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => stack.PushRange(new int[1], 0, -1));
// "Test8_Exceptions: PushRange didn't throw AORE when negative count passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => stack.PushRange(new int[1], -1, 1));
// "Test8_Exceptions: PushRange didn't throw AORE when negative index passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => stack.PushRange(new int[1], 2, 1));
// "Test8_Exceptions: PushRange didn't throw AORE when start index > array length");
Assert.Throws<ArgumentException>(
() => stack.PushRange(new int[1], 0, 10));
// "Test8_Exceptions: PushRange didn't throw AE when count + index > array length");
//PopRange
Assert.Throws<ArgumentNullException>(
() => stack.TryPopRange(null));
// "Test8_Exceptions: TryPopRange didn't throw ANE when null array passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => stack.TryPopRange(new int[1], 0, -1));
// "Test8_Exceptions: TryPopRange didn't throw AORE when negative count passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => stack.TryPopRange(new int[1], -1, 1));
// "Test8_Exceptions: TryPopRange didn't throw AORE when negative index passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => stack.TryPopRange(new int[1], 2, 1));
// "Test8_Exceptions: TryPopRange didn't throw AORE when start index > array length");
Assert.Throws<ArgumentException>(
() => stack.TryPopRange(new int[1], 0, 10));
// "Test8_Exceptions: TryPopRange didn't throw AE when count + index > array length");
}
[Fact]
public static void Test9_Interfaces_Negative()
{
ConcurrentStack<int> stack = new ConcurrentStack<int>();
ICollection collection = stack;
Assert.Throws<ArgumentNullException>(
() => collection.CopyTo(null, 0));
// "TestICollection: ICollection.CopyTo didn't throw ANE when null collection passed for collection type: ConcurrentStack");
Assert.Throws<NotSupportedException>(
() => { object obj = collection.SyncRoot; });
// "TestICollection: ICollection.SyncRoot didn't throw NotSupportedException! for collection type: ConcurrentStack");
}
[Fact]
public static void Test10_DebuggerAttributes()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new ConcurrentStack<int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ConcurrentStack<int>());
}
[Fact]
public static void Test9_Interfaces()
{
ConcurrentStack<int> stack = new ConcurrentStack<int>();
IProducerConsumerCollection<int> ipcc = stack;
Assert.Equal(0, ipcc.Count);
int item;
Assert.False(ipcc.TryTake(out item));
Assert.True(ipcc.TryAdd(1));
ICollection collection = stack;
Assert.False(collection.IsSynchronized);
stack.Push(1);
int count = stack.Count;
IEnumerable enumerable = stack;
foreach (object o in enumerable)
count--;
Assert.Equal(0, count);
}
}
}
| shmao/corefx | src/System.Collections.Concurrent/tests/ConcurrentStackTests.cs | C# | mit | 17,568 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.8.6">
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="functions_a.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Chargement...</div>
<div id="SRResults"></div>
<script type="text/javascript"><!--
createResults();
--></script>
<div class="SRStatus" id="Searching">Recherche...</div>
<div class="SRStatus" id="NoMatches">Aucune correspondance</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
| gurujam/Picross | html/search/functions_a.html | HTML | mit | 1,031 |
<?php
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
class Jetpack_JSON_API_User_Connect_Endpoint extends Jetpack_JSON_API_Endpoint {
protected $needed_capabilities = 'create_users';
private $user_id;
private $user_token;
function result() {
Connection_Utils::update_user_token( $this->user_id, sprintf( '%s.%d', $this->user_token, $this->user_id ), false );
return array( 'success' => Jetpack::is_user_connected( $this->user_id ) );
}
function validate_input( $user_id ) {
$input = $this->input();
if ( ! isset( $user_id ) ) {
return new WP_Error( 'input_error', __( 'user_id is required', 'jetpack' ) );
}
$this->user_id = $user_id;
if ( Jetpack::is_user_connected( $this->user_id ) ) {
return new WP_Error( 'user_already_connected', __( 'The user is already connected', 'jetpack' ) );
}
if ( ! isset( $input['user_token'] ) ) {
return new WP_Error( 'input_error', __( 'user_token is required', 'jetpack' ) );
}
$this->user_token = sanitize_text_field( $input[ 'user_token'] );
return parent::validate_input( $user_id );
}
}
| pjhooker/monferratopaesaggi | trunk/wp-content/plugins/jetpack/json-endpoints/jetpack/class.jetpack-json-api-user-connect-endpoint.php | PHP | mit | 1,087 |
using System.Collections.Generic;
using System.Linq;
namespace JiebaNet.Segmenter
{
public class Constants
{
public static readonly double MinProb = -3.14e100;
public static readonly List<string> NounPos = new List<string>() { "n", "ng", "nr", "nrfg", "nrt", "ns", "nt", "nz" };
public static readonly List<string> VerbPos = new List<string>() { "v", "vd", "vg", "vi", "vn", "vq" };
public static readonly List<string> NounAndVerbPos = NounPos.Union(VerbPos).ToList();
public static readonly List<string> IdiomPos = new List<string>() { "i" };
}
}
| anderscui/jieba.NET | src/Segmenter/Constants.cs | C# | mit | 605 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.prefixClass = prefixClass;
var _classScopingMode = require("./classScopingMode");
var hasTransformable = /\b(?=[A-Z])/g;
var noConflictCache = {};
var legacyCache = {};
function prefixSingle(scopedStyle) {
var noConflict = _classScopingMode.classScopingMode.noConflict;
var cache = noConflict ? noConflictCache : legacyCache;
if (cache[scopedStyle]) {
return cache[scopedStyle];
}
var prefixed = scopedStyle.replace(hasTransformable, "vkui");
var resolved = noConflict || scopedStyle === prefixed ? prefixed : prefixed + " " + scopedStyle;
cache[scopedStyle] = resolved;
return resolved;
}
function prefixClass(scopedStyle) {
if (typeof scopedStyle === "string") {
return prefixSingle(scopedStyle);
}
var resolved = "";
for (var i = 0; i < scopedStyle.length; i++) {
var separator = resolved ? " " : "";
resolved += separator + prefixSingle(scopedStyle[i]);
}
return resolved;
}
//# sourceMappingURL=prefixClass.js.map | cdnjs/cdnjs | ajax/libs/vkui/4.27.2/cjs/lib/prefixClass.js | JavaScript | mit | 1,059 |
import{generateUtilityClass,generateUtilityClasses}from"@material-ui/unstyled";function getFabUtilityClass(e){return generateUtilityClass("MuiFab",e)}var fabClasses=generateUtilityClasses("MuiFab",["root","label","primary","secondary","extended","circular","focusVisible","disabled","colorInherit","sizeSmall","sizeMedium","sizeLarge"]);export default fabClasses;export{getFabUtilityClass}; | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-beta.0/legacy/Fab/fabClasses.min.js | JavaScript | mit | 390 |
/**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.dwdunwetter.internal.data;
import java.util.Comparator;
import org.apache.commons.lang.ObjectUtils;
/**
* Comperator to sort a Warning first by Severity, second by the onSet date.
*
* @author Martin Koehler - Initial contribution
*/
public class SeverityComparator implements Comparator<DwdWarningData> {
@Override
public int compare(DwdWarningData o1, DwdWarningData o2) {
Comparator.comparingInt(d -> ((DwdWarningData) d).getSeverity().getOrder());
Comparator.comparing(DwdWarningData::getOnset);
int result = Integer.compare(o1.getSeverity().getOrder(), o2.getSeverity().getOrder());
if (result == 0) {
result = ObjectUtils.compare(o1.getOnset(), o2.getOnset());
}
return result;
}
}
| theoweiss/openhab2 | bundles/org.openhab.binding.dwdunwetter/src/main/java/org/openhab/binding/dwdunwetter/internal/data/SeverityComparator.java | Java | epl-1.0 | 1,179 |
/**
* Copyright (c) 2014-2017 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.core.thing.binding;
import java.util.Collection;
import java.util.Locale;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.type.ThingType;
/**
* The {@link ThingTypeProvider} is responsible for providing thing types.
*
* @author Dennis Nobel
*
*/
public interface ThingTypeProvider {
/**
* Provides a collection of thing types
*
* @param locale
* locale (can be null)
*
* @return the thing types provided by the {@link ThingTypeProvider}
*/
Collection<ThingType> getThingTypes(Locale locale);
/**
* Provides a thing type for the given UID or null if no type for the
* given UID exists.
*
* @param locale
* locale (can be null)
* @return thing type for the given UID or null if no type for the given
* UID exists
*/
ThingType getThingType(ThingTypeUID thingTypeUID, Locale locale);
}
| philomatic/smarthome | bundles/core/org.eclipse.smarthome.core.thing/src/main/java/org/eclipse/smarthome/core/thing/binding/ThingTypeProvider.java | Java | epl-1.0 | 1,308 |
/*
Copyright (c) 2014 Google Inc.
Copyright (c) 2014, 2015 MariaDB 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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */
#ifndef MY_CRYPT_INCLUDED
#define MY_CRYPT_INCLUDED
#include <my_config.h> /* HAVE_EncryptAes128{Ctr,Gcm} */
#include <mysql/service_my_crypt.h>
#endif /* MY_CRYPT_INCLUDED */
| MariaDB/server | include/my_crypt.h | C | gpl-2.0 | 904 |
void __attribute__((naked,noinline)) init_file_modules_task(){
asm volatile(
"STMFD SP!, {R4,LR}\n"
"BL _Unmount_FileSystem\n" // +
"BL sub_FF81CA18\n"
"SUBS R4, R0, #0\n"
"MOV R0, #0x5000\n"
"MOV R1, #0\n"
"ADD R0, R0, #6\n"
"BEQ loc_FF824454\n"
"BL sub_FFB5F594\n"
"loc_FF824454:\n"
"BL sub_FF81CA44_my\n" //---------------->
"MOV R0, #0x5000\n"
"CMP R4, #0\n"
"MOV R1, R4\n"
"ADD R0, R0, #6\n"
"LDMNEFD SP!, {R4,PC}\n"
"LDMFD SP!, {R4,LR}\n"
"B sub_FFB5F594\n"
);
}
void __attribute__((naked,noinline)) sub_FF81CA44_my(){
asm volatile(
"STR LR, [SP,#-4]!\n"
"BL Mount_FileSystem_my\n" //-------------->
"LDR R3, =0x1E0C\n"
"LDR R2, [R3]\n"
"CMP R2, #0\n"
"BNE loc_FF81CA80\n"
"BL sub_FF848778\n"
"AND R0, R0, #0xFF\n"
"BL sub_FFA7D4B4\n"
"BL sub_FF848778\n"
"AND R0, R0, #0xFF\n"
"BL sub_FFA93A4C\n"
"BL sub_FF848788\n"
"AND R0, R0, #0xFF\n"
"BL sub_FFA7D5A4\n"
"loc_FF81CA80:\n"
"LDR R2, =0x1E08\n"
"MOV R3, #1\n"
"STR R3, [R2]\n"
"LDR PC, [SP],#4\n"
);
}
void __attribute__((naked,noinline)) Mount_FileSystem_my(){
asm volatile(
"STMFD SP!, {R4-R6,LR}\n"
"MOV R4, #0\n"
"MOV R5, R4\n"
"LDR R6, =0x85C60\n"
"MOV R0, R5\n"
"BL sub_FFAAD9DC\n"
"LDR R0, [R6,#0x38]\n"
"BL sub_FFAAD070\n"
"CMP R0, R4\n"
"MOV R1, R5\n"
"MOV R0, R5\n"
"BNE loc_FFAAE048\n"
"LDR R3, =0xA320\n"
"LDR R2, =0xA318\n"
"STR R1, [R3]\n"
"LDR R3, =0xA31C\n"
"STR R1, [R2]\n"
"STR R1, [R3]\n"
"loc_FFAAE048:\n"
"BL sub_FFAADA2C\n"
"MOV R0, R5\n"
"BL sub_FFAADD5C_my\n" //----------------->
"MOV R4, R0\n"
"MOV R0, R5\n"
"BL sub_FFAADDE4\n"
"LDR R1, [R6,#0x3C]\n"
"AND R2, R4, R0\n"
"MOV R0, R6\n"
"BL sub_FFAADFB0\n"
"STR R0, [R6,#0x40]\n"
"LDMFD SP!, {R4-R6,PC}\n"
);
}
void __attribute__((naked,noinline)) sub_FFAADD5C_my(){
asm volatile(
"STMFD SP!, {R4-R7,LR}\n"
"LDR R7, =0xA31C\n"
"LDR R3, [R7]\n"
"MOV R4, R0\n"
"CMP R3, #0\n"
"ADD R3, R4, R4,LSL#1\n"
"RSB R3, R4, R3,LSL#3\n"
"LDR R6, =0x85C98\n"
"MOV R5, R3,LSL#2\n"
"MOV R1, R4\n"
"BNE loc_FFAADDD0\n"
"LDR R0, [R6,R5]\n"
"BL sub_FFAADAE4_my\n" //---------------->
"SUBS R3, R0, #0\n"
"MOV R1, R4\n"
"BEQ loc_FFAADDA8\n"
"LDR R0, [R6,R5]\n"
"BL sub_FFAADC38\n"
"MOV R3, R0\n"
"loc_FFAADDA8:\n"
"CMP R3, #0\n"
"MOV R0, R4\n"
"BEQ loc_FFAADDBC\n"
"BL sub_FFAAD148\n"
"MOV R3, R0\n"
"loc_FFAADDBC:\n"
"CMP R3, #0\n"
"MOV R0, R3\n"
"MOVNE R3, #1\n"
"STRNE R3, [R7]\n"
"LDMFD SP!, {R4-R7,PC}\n"
"loc_FFAADDD0:\n"
"MOV R0, #1\n"
"LDMFD SP!, {R4-R7,PC}\n"
);
}
void __attribute__((naked,noinline)) sub_FFAADAE4_my(){
asm volatile(
"STMFD SP!, {R4-R8,LR}\n"
"MOV R5, R1\n"
"MOV R8, R5,LSL#1\n"
"ADD R3, R8, R5\n"
"LDR R2, =0x85C9C\n"
"SUB SP, SP, #8\n"
"RSB R3, R5, R3,LSL#3\n"
"LDR R1, [R2,R3,LSL#2]\n"
"MOV R6, #0\n"
"STR R6, [SP]\n"
"MOV R7, R0\n"
"STR R6, [SP,#4]\n"
"CMP R1, #6\n"
"LDRLS PC, [PC,R1,LSL#2]\n"
"B loc_FFAADBE4\n"
".long loc_FFAADB88\n"
".long loc_FFAADB3C\n"
".long loc_FFAADB3C\n"
".long loc_FFAADB3C\n"
".long loc_FFAADB3C\n"
".long loc_FFAADBD4\n"
".long loc_FFAADB3C\n"
"loc_FFAADB3C:\n"
"MOV R0, #3\n"
"MOV R1, #0x200\n"
"MOV R2, #0\n"
"BL sub_FF81E370\n"
"SUBS R6, R0, #0\n"
"BEQ loc_FFAADC1C\n"
"ADD R12, R8, R5\n"
"RSB R12, R5, R12,LSL#3\n"
"LDR R4, =0x85CAC\n"
"MOV R0, R7\n"
"MOV R1, #0\n"
"MOV R2, #1\n"
"MOV R3, R6\n"
"MOV LR, PC\n"
"LDR PC, [R4,R12,LSL#2]\n"
"CMP R0, #1\n"
"BNE loc_FFAADB90\n"
"MOV R0, #3\n"
"BL sub_FF81E440\n"
"loc_FFAADB88:\n"
"MOV R0, #0\n"
"B loc_FFAADC1C\n"
"loc_FFAADB90:\n"
"MOV R0, R7\n"
"BL sub_FFAC15D0\n"
"MOV R1, R0\n"
"ADD R2, SP, #4\n"
"MOV R3, SP\n"
"MOV R0, R6\n"
"STMFD SP!, {R4-R11,LR}\n" // +
"BL mbr_read\n" //----------->
"LDMFD SP!, {R4-R11,LR}\n" // +
// "BL sub_FFAAD274\n" // original function
"MOV R4, R0\n"
"MOV R0, #3\n"
"BL sub_FF81E440\n"
"CMP R4, #0\n"
"BNE loc_FFAADBF4\n"
"MOV R0, R7\n"
"STR R4, [SP,#4]\n"
"BL sub_FFAC15D0\n"
"STR R0, [SP]\n"
"B loc_FFAADBF4\n"
"loc_FFAADBD4:\n"
"MOV R3, #0\n"
"MOV R2, #0x40\n"
"STMEA SP, {R2,R3}\n"
"B loc_FFAADBF4\n"
"loc_FFAADBE4:\n"
"MOV R1, #0x358\n"
"LDR R0, =0xFFAAD8CC\n"
"ADD R1, R1, #2\n"
"BL sub_FFB4D9F0\n"
"loc_FFAADBF4:\n"
"LDR R2, =0x85C60\n"
"ADD R3, R8, R5\n"
"LDMFD SP, {R0,R12}\n"
"RSB R3, R5, R3,LSL#3\n"
"MOV R3, R3,LSL#2\n"
"ADD R1, R2, #0x48\n"
"ADD R2, R2, #0x44\n"
"STR R0, [R1,R3]\n"
"STR R12, [R2,R3]\n"
"MOV R0, #1\n"
"loc_FFAADC1C:\n"
"ADD SP, SP, #8\n"
"LDMFD SP!, {R4-R8,PC}\n"
);
}
| pixeldoc2000/chdk | platform/tx1/sub/101b/mount.c | C | gpl-2.0 | 7,858 |
/*
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all copies.
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* @defgroup shiva_fdb SHIVA_FDB
* @{
*/
#ifndef _SHIVA_FDB_H_
#define _SHIVA_FDB_H_
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "fal/fal_fdb.h"
sw_error_t
shiva_fdb_init(a_uint32_t dev_id);
#ifdef IN_FDB
#define SHIVA_FDB_INIT(rv, dev_id) \
{ \
rv = shiva_fdb_init(dev_id); \
SW_RTN_ON_ERROR(rv); \
}
#else
#define SHIVA_FDB_INIT(rv, dev_id)
#endif
#ifdef HSL_STANDALONG
HSL_LOCAL sw_error_t
shiva_fdb_add(a_uint32_t dev_id, const fal_fdb_entry_t * entry);
HSL_LOCAL sw_error_t
shiva_fdb_del_all(a_uint32_t dev_id, a_uint32_t flag);
HSL_LOCAL sw_error_t
shiva_fdb_del_by_port(a_uint32_t dev_id, a_uint32_t port_id, a_uint32_t flag);
HSL_LOCAL sw_error_t
shiva_fdb_del_by_mac(a_uint32_t dev_id,
const fal_fdb_entry_t *entry);
HSL_LOCAL sw_error_t
shiva_fdb_first(a_uint32_t dev_id, fal_fdb_entry_t * entry);
HSL_LOCAL sw_error_t
shiva_fdb_find(a_uint32_t dev_id, fal_fdb_entry_t * entry);
HSL_LOCAL sw_error_t
shiva_fdb_port_learn_set(a_uint32_t dev_id, fal_port_t port_id,
a_bool_t enable);
HSL_LOCAL sw_error_t
shiva_fdb_port_learn_get(a_uint32_t dev_id, fal_port_t port_id,
a_bool_t *enable);
HSL_LOCAL sw_error_t
shiva_fdb_age_ctrl_set(a_uint32_t dev_id, a_bool_t enable);
HSL_LOCAL sw_error_t
shiva_fdb_age_ctrl_get(a_uint32_t dev_id, a_bool_t *enable);
HSL_LOCAL sw_error_t
shiva_fdb_age_time_set(a_uint32_t dev_id, a_uint32_t * time);
HSL_LOCAL sw_error_t
shiva_fdb_age_time_get(a_uint32_t dev_id, a_uint32_t * time);
HSL_LOCAL sw_error_t
shiva_fdb_iterate(a_uint32_t dev_id, a_uint32_t * iterator, fal_fdb_entry_t * entry);
#endif
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* _SHIVA_FDB_H_ */
/**
* @}
*/
| itgb/opCloudRouter | qca/src/qca-ssdk/include/hsl/shiva/shiva_fdb.h | C | gpl-2.0 | 2,709 |
// license:BSD-3-Clause
// copyright-holders:David Haywood, Nicola Salmoria
class usgames_state : public driver_device
{
public:
usgames_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag),
m_maincpu(*this, "maincpu"),
m_gfxdecode(*this, "gfxdecode"),
m_videoram(*this, "videoram"),
m_charram(*this, "charram") { }
required_device<cpu_device> m_maincpu;
required_device<gfxdecode_device> m_gfxdecode;
required_shared_ptr<UINT8> m_videoram;
required_shared_ptr<UINT8> m_charram;
tilemap_t *m_tilemap;
DECLARE_WRITE8_MEMBER(rombank_w);
DECLARE_WRITE8_MEMBER(lamps1_w);
DECLARE_WRITE8_MEMBER(lamps2_w);
DECLARE_WRITE8_MEMBER(videoram_w);
DECLARE_WRITE8_MEMBER(charram_w);
TILE_GET_INFO_MEMBER(get_tile_info);
virtual void machine_start() override;
virtual void video_start() override;
DECLARE_PALETTE_INIT(usgames);
UINT32 screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
};
| RJRetro/mame | src/mame/includes/usgames.h | C | gpl-2.0 | 999 |
#ifndef __reg_map_h
#define __reg_map_h
/*
*/
#define regi_artpec_mod 0xb7044000
#define regi_ata 0xb0032000
#define regi_ata_mod 0xb7006000
#define regi_barber 0xb701a000
#define regi_bif_core 0xb0014000
#define regi_bif_dma 0xb0016000
#define regi_bif_slave 0xb0018000
#define regi_bif_slave_ext 0xac000000
#define regi_bus_master 0xb703c000
#define regi_config 0xb003c000
#define regi_dma0 0xb0000000
#define regi_dma1 0xb0002000
#define regi_dma2 0xb0004000
#define regi_dma3 0xb0006000
#define regi_dma4 0xb0008000
#define regi_dma5 0xb000a000
#define regi_dma6 0xb000c000
#define regi_dma7 0xb000e000
#define regi_dma8 0xb0010000
#define regi_dma9 0xb0012000
#define regi_eth0 0xb0034000
#define regi_eth1 0xb0036000
#define regi_eth_mod 0xb7004000
#define regi_eth_mod1 0xb701c000
#define regi_eth_strmod 0xb7008000
#define regi_eth_strmod1 0xb7032000
#define regi_ext_dma 0xb703a000
#define regi_ext_mem 0xb7046000
#define regi_gen_io 0xb7016000
#define regi_gio 0xb001a000
#define regi_hook 0xb7000000
#define regi_iop 0xb0020000
#define regi_irq 0xb001c000
#define regi_irq_nmi 0xb701e000
#define regi_marb 0xb003e000
#define regi_marb_bp0 0xb003e240
#define regi_marb_bp1 0xb003e280
#define regi_marb_bp2 0xb003e2c0
#define regi_marb_bp3 0xb003e300
#define regi_nand_mod 0xb7014000
#define regi_p21 0xb002e000
#define regi_p21_mod 0xb7042000
#define regi_pci_mod 0xb7010000
#define regi_pin_test 0xb7018000
#define regi_pinmux 0xb0038000
#define regi_sdram_chk 0xb703e000
#define regi_sdram_mod 0xb7012000
#define regi_ser0 0xb0026000
#define regi_ser1 0xb0028000
#define regi_ser2 0xb002a000
#define regi_ser3 0xb002c000
#define regi_ser_mod0 0xb7020000
#define regi_ser_mod1 0xb7022000
#define regi_ser_mod2 0xb7024000
#define regi_ser_mod3 0xb7026000
#define regi_smif_stat 0xb700e000
#define regi_sser0 0xb0022000
#define regi_sser1 0xb0024000
#define regi_sser_mod0 0xb700a000
#define regi_sser_mod1 0xb700c000
#define regi_strcop 0xb0030000
#define regi_strmux 0xb003a000
#define regi_strmux_tst 0xb7040000
#define regi_tap 0xb7002000
#define regi_timer 0xb001e000
#define regi_timer_mod 0xb7034000
#define regi_trace 0xb0040000
#define regi_usb0 0xb7028000
#define regi_usb1 0xb702a000
#define regi_usb2 0xb702c000
#define regi_usb3 0xb702e000
#define regi_usb_dev 0xb7030000
#define regi_utmi_mod0 0xb7036000
#define regi_utmi_mod1 0xb7038000
#endif /* */
| holyangel/LGE_G3 | arch/cris/include/arch-v32/mach-fs/mach/hwregs/asm/reg_map_asm.h | C | gpl-2.0 | 5,464 |
# Copyright 2010-2014 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
from __future__ import division
import locale
import logging
import time
from portage import os, _unicode_decode
from portage.exception import PortageException
from portage.localization import _
from portage.output import EOutput
from portage.util import grabfile, writemsg_level
def have_english_locale():
lang, enc = locale.getdefaultlocale()
if lang is not None:
lang = lang.lower()
lang = lang.split('_', 1)[0]
return lang is None or lang in ('c', 'en')
def whenago(seconds):
sec = int(seconds)
mins = 0
days = 0
hrs = 0
years = 0
out = []
if sec > 60:
mins = sec // 60
sec = sec % 60
if mins > 60:
hrs = mins // 60
mins = mins % 60
if hrs > 24:
days = hrs // 24
hrs = hrs % 24
if days > 365:
years = days // 365
days = days % 365
if years:
out.append("%dy " % years)
if days:
out.append("%dd " % days)
if hrs:
out.append("%dh " % hrs)
if mins:
out.append("%dm " % mins)
if sec:
out.append("%ds " % sec)
return "".join(out).strip()
def old_tree_timestamp_warn(portdir, settings):
unixtime = time.time()
default_warnsync = 30
timestamp_file = os.path.join(portdir, "metadata/timestamp.x")
try:
lastsync = grabfile(timestamp_file)
except PortageException:
return False
if not lastsync:
return False
lastsync = lastsync[0].split()
if not lastsync:
return False
try:
lastsync = int(lastsync[0])
except ValueError:
return False
var_name = 'PORTAGE_SYNC_STALE'
try:
warnsync = float(settings.get(var_name, default_warnsync))
except ValueError:
writemsg_level("!!! %s contains non-numeric value: %s\n" % \
(var_name, settings[var_name]),
level=logging.ERROR, noiselevel=-1)
return False
if warnsync <= 0:
return False
if (unixtime - 86400 * warnsync) > lastsync:
out = EOutput()
if have_english_locale():
out.ewarn("Last emerge --sync was %s ago." % \
whenago(unixtime - lastsync))
else:
out.ewarn(_("Last emerge --sync was %s.") % \
_unicode_decode(time.strftime(
'%c', time.localtime(lastsync))))
return True
return False
| ptisserand/portage | pym/portage/sync/old_tree_timestamp.py | Python | gpl-2.0 | 2,161 |
/*
* Copyright (C) 2008-2009 Michal Simek <[email protected]>
* Copyright (C) 2008-2009 PetaLogix
* Copyright (C) 2006 Atmark Techno, Inc.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#ifndef _ASM_MICROBLAZE_TLB_H
#define _ASM_MICROBLAZE_TLB_H
#define tlb_flush(tlb) flush_tlb_mm((tlb)->mm)
#include <linux/pagemap.h>
#include <asm-generic/tlb.h>
#ifdef CONFIG_MMU
#define tlb_start_vma(tlb, vma) do { } while (0)
#define tlb_end_vma(tlb, vma) do { } while (0)
#define __tlb_remove_tlb_entry(tlb, pte, address) do { } while (0)
#endif
#endif /* */
| holyangel/LGE_G3 | arch/microblaze/include/asm/tlb.h | C | gpl-2.0 | 713 |
/*
* omap iommu: tlb and pagetable primitives
*
* Copyright (C) 2008-2010 Nokia Corporation
*
* Written by Hiroshi DOYU <[email protected]>,
* Paul Mundt and Toshihiro Kobayashi
*
* 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/err.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/iommu.h>
#include <linux/mutex.h>
#include <linux/spinlock.h>
#include <asm/cacheflush.h>
#include <plat/iommu.h>
#include <plat/iopgtable.h>
#define for_each_iotlb_cr(obj, n, __i, cr) \
for (__i = 0; \
(__i < (n)) && (cr = __iotlb_read_cr((obj), __i), true); \
__i++)
/* */
#define OMAP_IOMMU_PGSIZES (SZ_4K | SZ_64K | SZ_1M | SZ_16M)
/*
*/
struct omap_iommu_domain {
u32 *pgtable;
struct omap_iommu *iommu_dev;
spinlock_t lock;
};
/* */
static const struct iommu_functions *arch_iommu;
static struct platform_driver omap_iommu_driver;
static struct kmem_cache *iopte_cachep;
/*
*/
int omap_install_iommu_arch(const struct iommu_functions *ops)
{
if (arch_iommu)
return -EBUSY;
arch_iommu = ops;
return 0;
}
EXPORT_SYMBOL_GPL(omap_install_iommu_arch);
/*
*/
void omap_uninstall_iommu_arch(const struct iommu_functions *ops)
{
if (arch_iommu != ops)
pr_err("%s: not your arch\n", __func__);
arch_iommu = NULL;
}
EXPORT_SYMBOL_GPL(omap_uninstall_iommu_arch);
/*
*/
void omap_iommu_save_ctx(struct device *dev)
{
struct omap_iommu *obj = dev_to_omap_iommu(dev);
arch_iommu->save_ctx(obj);
}
EXPORT_SYMBOL_GPL(omap_iommu_save_ctx);
/*
*/
void omap_iommu_restore_ctx(struct device *dev)
{
struct omap_iommu *obj = dev_to_omap_iommu(dev);
arch_iommu->restore_ctx(obj);
}
EXPORT_SYMBOL_GPL(omap_iommu_restore_ctx);
/*
*/
u32 omap_iommu_arch_version(void)
{
return arch_iommu->version;
}
EXPORT_SYMBOL_GPL(omap_iommu_arch_version);
static int iommu_enable(struct omap_iommu *obj)
{
int err;
if (!obj)
return -EINVAL;
if (!arch_iommu)
return -ENODEV;
clk_enable(obj->clk);
err = arch_iommu->enable(obj);
clk_disable(obj->clk);
return err;
}
static void iommu_disable(struct omap_iommu *obj)
{
if (!obj)
return;
clk_enable(obj->clk);
arch_iommu->disable(obj);
clk_disable(obj->clk);
}
/*
*/
void omap_iotlb_cr_to_e(struct cr_regs *cr, struct iotlb_entry *e)
{
BUG_ON(!cr || !e);
arch_iommu->cr_to_e(cr, e);
}
EXPORT_SYMBOL_GPL(omap_iotlb_cr_to_e);
static inline int iotlb_cr_valid(struct cr_regs *cr)
{
if (!cr)
return -EINVAL;
return arch_iommu->cr_valid(cr);
}
static inline struct cr_regs *iotlb_alloc_cr(struct omap_iommu *obj,
struct iotlb_entry *e)
{
if (!e)
return NULL;
return arch_iommu->alloc_cr(obj, e);
}
static u32 iotlb_cr_to_virt(struct cr_regs *cr)
{
return arch_iommu->cr_to_virt(cr);
}
static u32 get_iopte_attr(struct iotlb_entry *e)
{
return arch_iommu->get_pte_attr(e);
}
static u32 iommu_report_fault(struct omap_iommu *obj, u32 *da)
{
return arch_iommu->fault_isr(obj, da);
}
static void iotlb_lock_get(struct omap_iommu *obj, struct iotlb_lock *l)
{
u32 val;
val = iommu_read_reg(obj, MMU_LOCK);
l->base = MMU_LOCK_BASE(val);
l->vict = MMU_LOCK_VICT(val);
}
static void iotlb_lock_set(struct omap_iommu *obj, struct iotlb_lock *l)
{
u32 val;
val = (l->base << MMU_LOCK_BASE_SHIFT);
val |= (l->vict << MMU_LOCK_VICT_SHIFT);
iommu_write_reg(obj, val, MMU_LOCK);
}
static void iotlb_read_cr(struct omap_iommu *obj, struct cr_regs *cr)
{
arch_iommu->tlb_read_cr(obj, cr);
}
static void iotlb_load_cr(struct omap_iommu *obj, struct cr_regs *cr)
{
arch_iommu->tlb_load_cr(obj, cr);
iommu_write_reg(obj, 1, MMU_FLUSH_ENTRY);
iommu_write_reg(obj, 1, MMU_LD_TLB);
}
/*
*/
static inline ssize_t iotlb_dump_cr(struct omap_iommu *obj, struct cr_regs *cr,
char *buf)
{
BUG_ON(!cr || !buf);
return arch_iommu->dump_cr(obj, cr, buf);
}
/* */
static struct cr_regs __iotlb_read_cr(struct omap_iommu *obj, int n)
{
struct cr_regs cr;
struct iotlb_lock l;
iotlb_lock_get(obj, &l);
l.vict = n;
iotlb_lock_set(obj, &l);
iotlb_read_cr(obj, &cr);
return cr;
}
/*
*/
#ifdef PREFETCH_IOTLB
static int load_iotlb_entry(struct omap_iommu *obj, struct iotlb_entry *e)
{
int err = 0;
struct iotlb_lock l;
struct cr_regs *cr;
if (!obj || !obj->nr_tlb_entries || !e)
return -EINVAL;
clk_enable(obj->clk);
iotlb_lock_get(obj, &l);
if (l.base == obj->nr_tlb_entries) {
dev_warn(obj->dev, "%s: preserve entries full\n", __func__);
err = -EBUSY;
goto out;
}
if (!e->prsvd) {
int i;
struct cr_regs tmp;
for_each_iotlb_cr(obj, obj->nr_tlb_entries, i, tmp)
if (!iotlb_cr_valid(&tmp))
break;
if (i == obj->nr_tlb_entries) {
dev_dbg(obj->dev, "%s: full: no entry\n", __func__);
err = -EBUSY;
goto out;
}
iotlb_lock_get(obj, &l);
} else {
l.vict = l.base;
iotlb_lock_set(obj, &l);
}
cr = iotlb_alloc_cr(obj, e);
if (IS_ERR(cr)) {
clk_disable(obj->clk);
return PTR_ERR(cr);
}
iotlb_load_cr(obj, cr);
kfree(cr);
if (e->prsvd)
l.base++;
/* */
if (++l.vict == obj->nr_tlb_entries)
l.vict = l.base;
iotlb_lock_set(obj, &l);
out:
clk_disable(obj->clk);
return err;
}
#else /* */
static int load_iotlb_entry(struct omap_iommu *obj, struct iotlb_entry *e)
{
return 0;
}
#endif /* */
static int prefetch_iotlb_entry(struct omap_iommu *obj, struct iotlb_entry *e)
{
return load_iotlb_entry(obj, e);
}
/*
*/
static void flush_iotlb_page(struct omap_iommu *obj, u32 da)
{
int i;
struct cr_regs cr;
clk_enable(obj->clk);
for_each_iotlb_cr(obj, obj->nr_tlb_entries, i, cr) {
u32 start;
size_t bytes;
if (!iotlb_cr_valid(&cr))
continue;
start = iotlb_cr_to_virt(&cr);
bytes = iopgsz_to_bytes(cr.cam & 3);
if ((start <= da) && (da < start + bytes)) {
dev_dbg(obj->dev, "%s: %08x<=%08x(%x)\n",
__func__, start, da, bytes);
iotlb_load_cr(obj, &cr);
iommu_write_reg(obj, 1, MMU_FLUSH_ENTRY);
}
}
clk_disable(obj->clk);
if (i == obj->nr_tlb_entries)
dev_dbg(obj->dev, "%s: no page for %08x\n", __func__, da);
}
/*
*/
static void flush_iotlb_all(struct omap_iommu *obj)
{
struct iotlb_lock l;
clk_enable(obj->clk);
l.base = 0;
l.vict = 0;
iotlb_lock_set(obj, &l);
iommu_write_reg(obj, 1, MMU_GFLUSH);
clk_disable(obj->clk);
}
#if defined(CONFIG_OMAP_IOMMU_DEBUG) || defined(CONFIG_OMAP_IOMMU_DEBUG_MODULE)
ssize_t omap_iommu_dump_ctx(struct omap_iommu *obj, char *buf, ssize_t bytes)
{
if (!obj || !buf)
return -EINVAL;
clk_enable(obj->clk);
bytes = arch_iommu->dump_ctx(obj, buf, bytes);
clk_disable(obj->clk);
return bytes;
}
EXPORT_SYMBOL_GPL(omap_iommu_dump_ctx);
static int
__dump_tlb_entries(struct omap_iommu *obj, struct cr_regs *crs, int num)
{
int i;
struct iotlb_lock saved;
struct cr_regs tmp;
struct cr_regs *p = crs;
clk_enable(obj->clk);
iotlb_lock_get(obj, &saved);
for_each_iotlb_cr(obj, num, i, tmp) {
if (!iotlb_cr_valid(&tmp))
continue;
*p++ = tmp;
}
iotlb_lock_set(obj, &saved);
clk_disable(obj->clk);
return p - crs;
}
/*
*/
size_t omap_dump_tlb_entries(struct omap_iommu *obj, char *buf, ssize_t bytes)
{
int i, num;
struct cr_regs *cr;
char *p = buf;
num = bytes / sizeof(*cr);
num = min(obj->nr_tlb_entries, num);
cr = kcalloc(num, sizeof(*cr), GFP_KERNEL);
if (!cr)
return 0;
num = __dump_tlb_entries(obj, cr, num);
for (i = 0; i < num; i++)
p += iotlb_dump_cr(obj, cr + i, p);
kfree(cr);
return p - buf;
}
EXPORT_SYMBOL_GPL(omap_dump_tlb_entries);
int omap_foreach_iommu_device(void *data, int (*fn)(struct device *, void *))
{
return driver_for_each_device(&omap_iommu_driver.driver,
NULL, data, fn);
}
EXPORT_SYMBOL_GPL(omap_foreach_iommu_device);
#endif /* */
/*
*/
static void flush_iopgd_range(u32 *first, u32 *last)
{
/* */
do {
asm("mcr p15, 0, %0, c7, c10, 1 @ flush_pgd"
: : "r" (first));
first += L1_CACHE_BYTES / sizeof(*first);
} while (first <= last);
}
static void flush_iopte_range(u32 *first, u32 *last)
{
/* */
do {
asm("mcr p15, 0, %0, c7, c10, 1 @ flush_pte"
: : "r" (first));
first += L1_CACHE_BYTES / sizeof(*first);
} while (first <= last);
}
static void iopte_free(u32 *iopte)
{
/* */
kmem_cache_free(iopte_cachep, iopte);
}
static u32 *iopte_alloc(struct omap_iommu *obj, u32 *iopgd, u32 da)
{
u32 *iopte;
/* */
if (*iopgd)
goto pte_ready;
/*
*/
spin_unlock(&obj->page_table_lock);
iopte = kmem_cache_zalloc(iopte_cachep, GFP_KERNEL);
spin_lock(&obj->page_table_lock);
if (!*iopgd) {
if (!iopte)
return ERR_PTR(-ENOMEM);
*iopgd = virt_to_phys(iopte) | IOPGD_TABLE;
flush_iopgd_range(iopgd, iopgd);
dev_vdbg(obj->dev, "%s: a new pte:%p\n", __func__, iopte);
} else {
/* */
iopte_free(iopte);
}
pte_ready:
iopte = iopte_offset(iopgd, da);
dev_vdbg(obj->dev,
"%s: da:%08x pgd:%p *pgd:%08x pte:%p *pte:%08x\n",
__func__, da, iopgd, *iopgd, iopte, *iopte);
return iopte;
}
static int iopgd_alloc_section(struct omap_iommu *obj, u32 da, u32 pa, u32 prot)
{
u32 *iopgd = iopgd_offset(obj, da);
if ((da | pa) & ~IOSECTION_MASK) {
dev_err(obj->dev, "%s: %08x:%08x should aligned on %08lx\n",
__func__, da, pa, IOSECTION_SIZE);
return -EINVAL;
}
*iopgd = (pa & IOSECTION_MASK) | prot | IOPGD_SECTION;
flush_iopgd_range(iopgd, iopgd);
return 0;
}
static int iopgd_alloc_super(struct omap_iommu *obj, u32 da, u32 pa, u32 prot)
{
u32 *iopgd = iopgd_offset(obj, da);
int i;
if ((da | pa) & ~IOSUPER_MASK) {
dev_err(obj->dev, "%s: %08x:%08x should aligned on %08lx\n",
__func__, da, pa, IOSUPER_SIZE);
return -EINVAL;
}
for (i = 0; i < 16; i++)
*(iopgd + i) = (pa & IOSUPER_MASK) | prot | IOPGD_SUPER;
flush_iopgd_range(iopgd, iopgd + 15);
return 0;
}
static int iopte_alloc_page(struct omap_iommu *obj, u32 da, u32 pa, u32 prot)
{
u32 *iopgd = iopgd_offset(obj, da);
u32 *iopte = iopte_alloc(obj, iopgd, da);
if (IS_ERR(iopte))
return PTR_ERR(iopte);
*iopte = (pa & IOPAGE_MASK) | prot | IOPTE_SMALL;
flush_iopte_range(iopte, iopte);
dev_vdbg(obj->dev, "%s: da:%08x pa:%08x pte:%p *pte:%08x\n",
__func__, da, pa, iopte, *iopte);
return 0;
}
static int iopte_alloc_large(struct omap_iommu *obj, u32 da, u32 pa, u32 prot)
{
u32 *iopgd = iopgd_offset(obj, da);
u32 *iopte = iopte_alloc(obj, iopgd, da);
int i;
if ((da | pa) & ~IOLARGE_MASK) {
dev_err(obj->dev, "%s: %08x:%08x should aligned on %08lx\n",
__func__, da, pa, IOLARGE_SIZE);
return -EINVAL;
}
if (IS_ERR(iopte))
return PTR_ERR(iopte);
for (i = 0; i < 16; i++)
*(iopte + i) = (pa & IOLARGE_MASK) | prot | IOPTE_LARGE;
flush_iopte_range(iopte, iopte + 15);
return 0;
}
static int
iopgtable_store_entry_core(struct omap_iommu *obj, struct iotlb_entry *e)
{
int (*fn)(struct omap_iommu *, u32, u32, u32);
u32 prot;
int err;
if (!obj || !e)
return -EINVAL;
switch (e->pgsz) {
case MMU_CAM_PGSZ_16M:
fn = iopgd_alloc_super;
break;
case MMU_CAM_PGSZ_1M:
fn = iopgd_alloc_section;
break;
case MMU_CAM_PGSZ_64K:
fn = iopte_alloc_large;
break;
case MMU_CAM_PGSZ_4K:
fn = iopte_alloc_page;
break;
default:
fn = NULL;
BUG();
break;
}
prot = get_iopte_attr(e);
spin_lock(&obj->page_table_lock);
err = fn(obj, e->da, e->pa, prot);
spin_unlock(&obj->page_table_lock);
return err;
}
/*
*/
int omap_iopgtable_store_entry(struct omap_iommu *obj, struct iotlb_entry *e)
{
int err;
flush_iotlb_page(obj, e->da);
err = iopgtable_store_entry_core(obj, e);
if (!err)
prefetch_iotlb_entry(obj, e);
return err;
}
EXPORT_SYMBOL_GPL(omap_iopgtable_store_entry);
/*
*/
static void
iopgtable_lookup_entry(struct omap_iommu *obj, u32 da, u32 **ppgd, u32 **ppte)
{
u32 *iopgd, *iopte = NULL;
iopgd = iopgd_offset(obj, da);
if (!*iopgd)
goto out;
if (iopgd_is_table(*iopgd))
iopte = iopte_offset(iopgd, da);
out:
*ppgd = iopgd;
*ppte = iopte;
}
static size_t iopgtable_clear_entry_core(struct omap_iommu *obj, u32 da)
{
size_t bytes;
u32 *iopgd = iopgd_offset(obj, da);
int nent = 1;
if (!*iopgd)
return 0;
if (iopgd_is_table(*iopgd)) {
int i;
u32 *iopte = iopte_offset(iopgd, da);
bytes = IOPTE_SIZE;
if (*iopte & IOPTE_LARGE) {
nent *= 16;
/* */
iopte = iopte_offset(iopgd, (da & IOLARGE_MASK));
}
bytes *= nent;
memset(iopte, 0, nent * sizeof(*iopte));
flush_iopte_range(iopte, iopte + (nent - 1) * sizeof(*iopte));
/*
*/
iopte = iopte_offset(iopgd, 0);
for (i = 0; i < PTRS_PER_IOPTE; i++)
if (iopte[i])
goto out;
iopte_free(iopte);
nent = 1; /* */
} else {
bytes = IOPGD_SIZE;
if ((*iopgd & IOPGD_SUPER) == IOPGD_SUPER) {
nent *= 16;
/* */
iopgd = iopgd_offset(obj, (da & IOSUPER_MASK));
}
bytes *= nent;
}
memset(iopgd, 0, nent * sizeof(*iopgd));
flush_iopgd_range(iopgd, iopgd + (nent - 1) * sizeof(*iopgd));
out:
return bytes;
}
/*
*/
static size_t iopgtable_clear_entry(struct omap_iommu *obj, u32 da)
{
size_t bytes;
spin_lock(&obj->page_table_lock);
bytes = iopgtable_clear_entry_core(obj, da);
flush_iotlb_page(obj, da);
spin_unlock(&obj->page_table_lock);
return bytes;
}
static void iopgtable_clear_entry_all(struct omap_iommu *obj)
{
int i;
spin_lock(&obj->page_table_lock);
for (i = 0; i < PTRS_PER_IOPGD; i++) {
u32 da;
u32 *iopgd;
da = i << IOPGD_SHIFT;
iopgd = iopgd_offset(obj, da);
if (!*iopgd)
continue;
if (iopgd_is_table(*iopgd))
iopte_free(iopte_offset(iopgd, 0));
*iopgd = 0;
flush_iopgd_range(iopgd, iopgd);
}
flush_iotlb_all(obj);
spin_unlock(&obj->page_table_lock);
}
/*
*/
static irqreturn_t iommu_fault_handler(int irq, void *data)
{
u32 da, errs;
u32 *iopgd, *iopte;
struct omap_iommu *obj = data;
struct iommu_domain *domain = obj->domain;
if (!obj->refcount)
return IRQ_NONE;
clk_enable(obj->clk);
errs = iommu_report_fault(obj, &da);
clk_disable(obj->clk);
if (errs == 0)
return IRQ_HANDLED;
/* */
if (!report_iommu_fault(domain, obj->dev, da, 0))
return IRQ_HANDLED;
iommu_disable(obj);
iopgd = iopgd_offset(obj, da);
if (!iopgd_is_table(*iopgd)) {
dev_err(obj->dev, "%s: errs:0x%08x da:0x%08x pgd:0x%p "
"*pgd:px%08x\n", obj->name, errs, da, iopgd, *iopgd);
return IRQ_NONE;
}
iopte = iopte_offset(iopgd, da);
dev_err(obj->dev, "%s: errs:0x%08x da:0x%08x pgd:0x%p *pgd:0x%08x "
"pte:0x%p *pte:0x%08x\n", obj->name, errs, da, iopgd, *iopgd,
iopte, *iopte);
return IRQ_NONE;
}
static int device_match_by_alias(struct device *dev, void *data)
{
struct omap_iommu *obj = to_iommu(dev);
const char *name = data;
pr_debug("%s: %s %s\n", __func__, obj->name, name);
return strcmp(obj->name, name) == 0;
}
/*
*/
static struct omap_iommu *omap_iommu_attach(const char *name, u32 *iopgd)
{
int err = -ENOMEM;
struct device *dev;
struct omap_iommu *obj;
dev = driver_find_device(&omap_iommu_driver.driver, NULL,
(void *)name,
device_match_by_alias);
if (!dev)
return NULL;
obj = to_iommu(dev);
spin_lock(&obj->iommu_lock);
/* */
if (++obj->refcount > 1) {
dev_err(dev, "%s: already attached!\n", obj->name);
err = -EBUSY;
goto err_enable;
}
obj->iopgd = iopgd;
err = iommu_enable(obj);
if (err)
goto err_enable;
flush_iotlb_all(obj);
if (!try_module_get(obj->owner))
goto err_module;
spin_unlock(&obj->iommu_lock);
dev_dbg(obj->dev, "%s: %s\n", __func__, obj->name);
return obj;
err_module:
if (obj->refcount == 1)
iommu_disable(obj);
err_enable:
obj->refcount--;
spin_unlock(&obj->iommu_lock);
return ERR_PTR(err);
}
/*
*/
static void omap_iommu_detach(struct omap_iommu *obj)
{
if (!obj || IS_ERR(obj))
return;
spin_lock(&obj->iommu_lock);
if (--obj->refcount == 0)
iommu_disable(obj);
module_put(obj->owner);
obj->iopgd = NULL;
spin_unlock(&obj->iommu_lock);
dev_dbg(obj->dev, "%s: %s\n", __func__, obj->name);
}
/*
*/
static int __devinit omap_iommu_probe(struct platform_device *pdev)
{
int err = -ENODEV;
int irq;
struct omap_iommu *obj;
struct resource *res;
struct iommu_platform_data *pdata = pdev->dev.platform_data;
if (pdev->num_resources != 2)
return -EINVAL;
obj = kzalloc(sizeof(*obj) + MMU_REG_SIZE, GFP_KERNEL);
if (!obj)
return -ENOMEM;
obj->clk = clk_get(&pdev->dev, pdata->clk_name);
if (IS_ERR(obj->clk))
goto err_clk;
obj->nr_tlb_entries = pdata->nr_tlb_entries;
obj->name = pdata->name;
obj->dev = &pdev->dev;
obj->ctx = (void *)obj + sizeof(*obj);
obj->da_start = pdata->da_start;
obj->da_end = pdata->da_end;
spin_lock_init(&obj->iommu_lock);
mutex_init(&obj->mmap_lock);
spin_lock_init(&obj->page_table_lock);
INIT_LIST_HEAD(&obj->mmap);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
err = -ENODEV;
goto err_mem;
}
res = request_mem_region(res->start, resource_size(res),
dev_name(&pdev->dev));
if (!res) {
err = -EIO;
goto err_mem;
}
obj->regbase = ioremap(res->start, resource_size(res));
if (!obj->regbase) {
err = -ENOMEM;
goto err_ioremap;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
err = -ENODEV;
goto err_irq;
}
err = request_irq(irq, iommu_fault_handler, IRQF_SHARED,
dev_name(&pdev->dev), obj);
if (err < 0)
goto err_irq;
platform_set_drvdata(pdev, obj);
dev_info(&pdev->dev, "%s registered\n", obj->name);
return 0;
err_irq:
iounmap(obj->regbase);
err_ioremap:
release_mem_region(res->start, resource_size(res));
err_mem:
clk_put(obj->clk);
err_clk:
kfree(obj);
return err;
}
static int __devexit omap_iommu_remove(struct platform_device *pdev)
{
int irq;
struct resource *res;
struct omap_iommu *obj = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
iopgtable_clear_entry_all(obj);
irq = platform_get_irq(pdev, 0);
free_irq(irq, obj);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
iounmap(obj->regbase);
clk_put(obj->clk);
dev_info(&pdev->dev, "%s removed\n", obj->name);
kfree(obj);
return 0;
}
static struct platform_driver omap_iommu_driver = {
.probe = omap_iommu_probe,
.remove = __devexit_p(omap_iommu_remove),
.driver = {
.name = "omap-iommu",
},
};
static void iopte_cachep_ctor(void *iopte)
{
clean_dcache_area(iopte, IOPTE_TABLE_SIZE);
}
static int omap_iommu_map(struct iommu_domain *domain, unsigned long da,
phys_addr_t pa, size_t bytes, int prot)
{
struct omap_iommu_domain *omap_domain = domain->priv;
struct omap_iommu *oiommu = omap_domain->iommu_dev;
struct device *dev = oiommu->dev;
struct iotlb_entry e;
int omap_pgsz;
u32 ret, flags;
/* */
omap_pgsz = bytes_to_iopgsz(bytes);
if (omap_pgsz < 0) {
dev_err(dev, "invalid size to map: %d\n", bytes);
return -EINVAL;
}
dev_dbg(dev, "mapping da 0x%lx to pa 0x%x size 0x%x\n", da, pa, bytes);
flags = omap_pgsz | prot;
iotlb_init_entry(&e, da, pa, flags);
ret = omap_iopgtable_store_entry(oiommu, &e);
if (ret)
dev_err(dev, "omap_iopgtable_store_entry failed: %d\n", ret);
return ret;
}
static size_t omap_iommu_unmap(struct iommu_domain *domain, unsigned long da,
size_t size)
{
struct omap_iommu_domain *omap_domain = domain->priv;
struct omap_iommu *oiommu = omap_domain->iommu_dev;
struct device *dev = oiommu->dev;
dev_dbg(dev, "unmapping da 0x%lx size %u\n", da, size);
return iopgtable_clear_entry(oiommu, da);
}
static int
omap_iommu_attach_dev(struct iommu_domain *domain, struct device *dev)
{
struct omap_iommu_domain *omap_domain = domain->priv;
struct omap_iommu *oiommu;
struct omap_iommu_arch_data *arch_data = dev->archdata.iommu;
int ret = 0;
spin_lock(&omap_domain->lock);
/* */
if (omap_domain->iommu_dev) {
dev_err(dev, "iommu domain is already attached\n");
ret = -EBUSY;
goto out;
}
/* */
oiommu = omap_iommu_attach(arch_data->name, omap_domain->pgtable);
if (IS_ERR(oiommu)) {
ret = PTR_ERR(oiommu);
dev_err(dev, "can't get omap iommu: %d\n", ret);
goto out;
}
omap_domain->iommu_dev = arch_data->iommu_dev = oiommu;
oiommu->domain = domain;
out:
spin_unlock(&omap_domain->lock);
return ret;
}
static void omap_iommu_detach_dev(struct iommu_domain *domain,
struct device *dev)
{
struct omap_iommu_domain *omap_domain = domain->priv;
struct omap_iommu_arch_data *arch_data = dev->archdata.iommu;
struct omap_iommu *oiommu = dev_to_omap_iommu(dev);
spin_lock(&omap_domain->lock);
/* */
if (omap_domain->iommu_dev != oiommu) {
dev_err(dev, "invalid iommu device\n");
goto out;
}
iopgtable_clear_entry_all(oiommu);
omap_iommu_detach(oiommu);
omap_domain->iommu_dev = arch_data->iommu_dev = NULL;
out:
spin_unlock(&omap_domain->lock);
}
static int omap_iommu_domain_init(struct iommu_domain *domain)
{
struct omap_iommu_domain *omap_domain;
omap_domain = kzalloc(sizeof(*omap_domain), GFP_KERNEL);
if (!omap_domain) {
pr_err("kzalloc failed\n");
goto out;
}
omap_domain->pgtable = kzalloc(IOPGD_TABLE_SIZE, GFP_KERNEL);
if (!omap_domain->pgtable) {
pr_err("kzalloc failed\n");
goto fail_nomem;
}
/*
*/
BUG_ON(!IS_ALIGNED((long)omap_domain->pgtable, IOPGD_TABLE_SIZE));
clean_dcache_area(omap_domain->pgtable, IOPGD_TABLE_SIZE);
spin_lock_init(&omap_domain->lock);
domain->priv = omap_domain;
return 0;
fail_nomem:
kfree(omap_domain);
out:
return -ENOMEM;
}
/* */
static void omap_iommu_domain_destroy(struct iommu_domain *domain)
{
struct omap_iommu_domain *omap_domain = domain->priv;
domain->priv = NULL;
kfree(omap_domain->pgtable);
kfree(omap_domain);
}
static phys_addr_t omap_iommu_iova_to_phys(struct iommu_domain *domain,
unsigned long da)
{
struct omap_iommu_domain *omap_domain = domain->priv;
struct omap_iommu *oiommu = omap_domain->iommu_dev;
struct device *dev = oiommu->dev;
u32 *pgd, *pte;
phys_addr_t ret = 0;
iopgtable_lookup_entry(oiommu, da, &pgd, &pte);
if (pte) {
if (iopte_is_small(*pte))
ret = omap_iommu_translate(*pte, da, IOPTE_MASK);
else if (iopte_is_large(*pte))
ret = omap_iommu_translate(*pte, da, IOLARGE_MASK);
else
dev_err(dev, "bogus pte 0x%x, da 0x%lx", *pte, da);
} else {
if (iopgd_is_section(*pgd))
ret = omap_iommu_translate(*pgd, da, IOSECTION_MASK);
else if (iopgd_is_super(*pgd))
ret = omap_iommu_translate(*pgd, da, IOSUPER_MASK);
else
dev_err(dev, "bogus pgd 0x%x, da 0x%lx", *pgd, da);
}
return ret;
}
static int omap_iommu_domain_has_cap(struct iommu_domain *domain,
unsigned long cap)
{
return 0;
}
static struct iommu_ops omap_iommu_ops = {
.domain_init = omap_iommu_domain_init,
.domain_destroy = omap_iommu_domain_destroy,
.attach_dev = omap_iommu_attach_dev,
.detach_dev = omap_iommu_detach_dev,
.map = omap_iommu_map,
.unmap = omap_iommu_unmap,
.iova_to_phys = omap_iommu_iova_to_phys,
.domain_has_cap = omap_iommu_domain_has_cap,
.pgsize_bitmap = OMAP_IOMMU_PGSIZES,
};
static int __init omap_iommu_init(void)
{
struct kmem_cache *p;
const unsigned long flags = SLAB_HWCACHE_ALIGN;
size_t align = 1 << 10; /* */
p = kmem_cache_create("iopte_cache", IOPTE_TABLE_SIZE, align, flags,
iopte_cachep_ctor);
if (!p)
return -ENOMEM;
iopte_cachep = p;
bus_set_iommu(&platform_bus_type, &omap_iommu_ops);
return platform_driver_register(&omap_iommu_driver);
}
/* */
subsys_initcall(omap_iommu_init);
static void __exit omap_iommu_exit(void)
{
kmem_cache_destroy(iopte_cachep);
platform_driver_unregister(&omap_iommu_driver);
}
module_exit(omap_iommu_exit);
MODULE_DESCRIPTION("omap iommu: tlb and pagetable primitives");
MODULE_ALIAS("platform:omap-iommu");
MODULE_AUTHOR("Hiroshi DOYU, Paul Mundt and Toshihiro Kobayashi");
MODULE_LICENSE("GPL v2");
| holyangel/LGE_G3 | drivers/iommu/omap-iommu.c | C | gpl-2.0 | 27,231 |
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stddef.h>
#include <unistd.h>
#include <stdint.h>
#include <errno.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include "kdbus-api.h"
#include "kdbus-test.h"
#include "kdbus-util.h"
#include "kdbus-enum.h"
#define KDBUS_MSG_MAX_ITEMS 128
#define KDBUS_USER_MAX_CONN 256
/* maximum number of inflight fds in a target queue per user */
#define KDBUS_CONN_MAX_FDS_PER_USER 16
/* maximum number of memfd items per message */
#define KDBUS_MSG_MAX_MEMFD_ITEMS 16
static int make_msg_payload_dbus(uint64_t src_id, uint64_t dst_id,
uint64_t msg_size,
struct kdbus_msg **msg_dbus)
{
struct kdbus_msg *msg;
msg = malloc(msg_size);
ASSERT_RETURN_VAL(msg, -ENOMEM);
memset(msg, 0, msg_size);
msg->size = msg_size;
msg->src_id = src_id;
msg->dst_id = dst_id;
msg->payload_type = KDBUS_PAYLOAD_DBUS;
*msg_dbus = msg;
return 0;
}
static void make_item_memfds(struct kdbus_item *item,
int *memfds, size_t memfd_size)
{
size_t i;
for (i = 0; i < memfd_size; i++) {
item->type = KDBUS_ITEM_PAYLOAD_MEMFD;
item->size = KDBUS_ITEM_HEADER_SIZE +
sizeof(struct kdbus_memfd);
item->memfd.fd = memfds[i];
item->memfd.size = sizeof(uint64_t); /* const size */
item = KDBUS_ITEM_NEXT(item);
}
}
static void make_item_fds(struct kdbus_item *item,
int *fd_array, size_t fd_size)
{
size_t i;
item->type = KDBUS_ITEM_FDS;
item->size = KDBUS_ITEM_HEADER_SIZE + (sizeof(int) * fd_size);
for (i = 0; i < fd_size; i++)
item->fds[i] = fd_array[i];
}
static int memfd_write(const char *name, void *buf, size_t bufsize)
{
ssize_t ret;
int memfd;
memfd = sys_memfd_create(name, 0);
ASSERT_RETURN_VAL(memfd >= 0, memfd);
ret = write(memfd, buf, bufsize);
ASSERT_RETURN_VAL(ret == (ssize_t)bufsize, -EAGAIN);
ret = sys_memfd_seal_set(memfd);
ASSERT_RETURN_VAL(ret == 0, -errno);
return memfd;
}
static int send_memfds(struct kdbus_conn *conn, uint64_t dst_id,
int *memfds_array, size_t memfd_count)
{
struct kdbus_cmd_send cmd = {};
struct kdbus_item *item;
struct kdbus_msg *msg;
uint64_t size;
int ret;
size = sizeof(struct kdbus_msg);
size += memfd_count * KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd));
if (dst_id == KDBUS_DST_ID_BROADCAST)
size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_bloom_filter)) + 64;
ret = make_msg_payload_dbus(conn->id, dst_id, size, &msg);
ASSERT_RETURN_VAL(ret == 0, ret);
item = msg->items;
if (dst_id == KDBUS_DST_ID_BROADCAST) {
item->type = KDBUS_ITEM_BLOOM_FILTER;
item->size = KDBUS_ITEM_SIZE(sizeof(struct kdbus_bloom_filter)) + 64;
item = KDBUS_ITEM_NEXT(item);
msg->flags |= KDBUS_MSG_SIGNAL;
}
make_item_memfds(item, memfds_array, memfd_count);
cmd.size = sizeof(cmd);
cmd.msg_address = (uintptr_t)msg;
ret = kdbus_cmd_send(conn->fd, &cmd);
if (ret < 0) {
kdbus_printf("error sending message: %d (%m)\n", ret);
return ret;
}
free(msg);
return 0;
}
static int send_fds(struct kdbus_conn *conn, uint64_t dst_id,
int *fd_array, size_t fd_count)
{
struct kdbus_cmd_send cmd = {};
struct kdbus_item *item;
struct kdbus_msg *msg;
uint64_t size;
int ret;
size = sizeof(struct kdbus_msg);
size += KDBUS_ITEM_SIZE(sizeof(int) * fd_count);
if (dst_id == KDBUS_DST_ID_BROADCAST)
size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_bloom_filter)) + 64;
ret = make_msg_payload_dbus(conn->id, dst_id, size, &msg);
ASSERT_RETURN_VAL(ret == 0, ret);
item = msg->items;
if (dst_id == KDBUS_DST_ID_BROADCAST) {
item->type = KDBUS_ITEM_BLOOM_FILTER;
item->size = KDBUS_ITEM_SIZE(sizeof(struct kdbus_bloom_filter)) + 64;
item = KDBUS_ITEM_NEXT(item);
msg->flags |= KDBUS_MSG_SIGNAL;
}
make_item_fds(item, fd_array, fd_count);
cmd.size = sizeof(cmd);
cmd.msg_address = (uintptr_t)msg;
ret = kdbus_cmd_send(conn->fd, &cmd);
if (ret < 0) {
kdbus_printf("error sending message: %d (%m)\n", ret);
return ret;
}
free(msg);
return ret;
}
static int send_fds_memfds(struct kdbus_conn *conn, uint64_t dst_id,
int *fds_array, size_t fd_count,
int *memfds_array, size_t memfd_count)
{
struct kdbus_cmd_send cmd = {};
struct kdbus_item *item;
struct kdbus_msg *msg;
uint64_t size;
int ret;
size = sizeof(struct kdbus_msg);
size += memfd_count * KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd));
size += KDBUS_ITEM_SIZE(sizeof(int) * fd_count);
ret = make_msg_payload_dbus(conn->id, dst_id, size, &msg);
ASSERT_RETURN_VAL(ret == 0, ret);
item = msg->items;
make_item_fds(item, fds_array, fd_count);
item = KDBUS_ITEM_NEXT(item);
make_item_memfds(item, memfds_array, memfd_count);
cmd.size = sizeof(cmd);
cmd.msg_address = (uintptr_t)msg;
ret = kdbus_cmd_send(conn->fd, &cmd);
if (ret < 0) {
kdbus_printf("error sending message: %d (%m)\n", ret);
return ret;
}
free(msg);
return ret;
}
/* Return the number of received fds */
static unsigned int kdbus_item_get_nfds(struct kdbus_msg *msg)
{
unsigned int fds = 0;
const struct kdbus_item *item;
KDBUS_ITEM_FOREACH(item, msg, items) {
switch (item->type) {
case KDBUS_ITEM_FDS: {
fds += (item->size - KDBUS_ITEM_HEADER_SIZE) /
sizeof(int);
break;
}
case KDBUS_ITEM_PAYLOAD_MEMFD:
fds++;
break;
default:
break;
}
}
return fds;
}
static struct kdbus_msg *
get_kdbus_msg_with_fd(struct kdbus_conn *conn_src,
uint64_t dst_id, uint64_t cookie, int fd)
{
int ret;
uint64_t size;
struct kdbus_item *item;
struct kdbus_msg *msg;
size = sizeof(struct kdbus_msg);
if (fd >= 0)
size += KDBUS_ITEM_SIZE(sizeof(int));
ret = make_msg_payload_dbus(conn_src->id, dst_id, size, &msg);
ASSERT_RETURN_VAL(ret == 0, NULL);
msg->cookie = cookie;
if (fd >= 0) {
item = msg->items;
make_item_fds(item, (int *)&fd, 1);
}
return msg;
}
static int kdbus_test_no_fds(struct kdbus_test_env *env,
int *fds, int *memfd)
{
pid_t pid;
int ret, status;
uint64_t cookie;
int connfd1, connfd2;
struct kdbus_msg *msg, *msg_sync_reply;
struct kdbus_cmd_hello hello;
struct kdbus_conn *conn_src, *conn_dst, *conn_dummy;
struct kdbus_cmd_send cmd = {};
struct kdbus_cmd_free cmd_free = {};
conn_src = kdbus_hello(env->buspath, 0, NULL, 0);
ASSERT_RETURN(conn_src);
connfd1 = open(env->buspath, O_RDWR|O_CLOEXEC);
ASSERT_RETURN(connfd1 >= 0);
connfd2 = open(env->buspath, O_RDWR|O_CLOEXEC);
ASSERT_RETURN(connfd2 >= 0);
/*
* Create connections without KDBUS_HELLO_ACCEPT_FD
* to test if send fd operations are blocked
*/
conn_dst = malloc(sizeof(*conn_dst));
ASSERT_RETURN(conn_dst);
conn_dummy = malloc(sizeof(*conn_dummy));
ASSERT_RETURN(conn_dummy);
memset(&hello, 0, sizeof(hello));
hello.size = sizeof(struct kdbus_cmd_hello);
hello.pool_size = POOL_SIZE;
hello.attach_flags_send = _KDBUS_ATTACH_ALL;
ret = kdbus_cmd_hello(connfd1, &hello);
ASSERT_RETURN(ret == 0);
cmd_free.size = sizeof(cmd_free);
cmd_free.offset = hello.offset;
ret = kdbus_cmd_free(connfd1, &cmd_free);
ASSERT_RETURN(ret >= 0);
conn_dst->fd = connfd1;
conn_dst->id = hello.id;
memset(&hello, 0, sizeof(hello));
hello.size = sizeof(struct kdbus_cmd_hello);
hello.pool_size = POOL_SIZE;
hello.attach_flags_send = _KDBUS_ATTACH_ALL;
ret = kdbus_cmd_hello(connfd2, &hello);
ASSERT_RETURN(ret == 0);
cmd_free.size = sizeof(cmd_free);
cmd_free.offset = hello.offset;
ret = kdbus_cmd_free(connfd2, &cmd_free);
ASSERT_RETURN(ret >= 0);
conn_dummy->fd = connfd2;
conn_dummy->id = hello.id;
conn_dst->buf = mmap(NULL, POOL_SIZE, PROT_READ,
MAP_SHARED, connfd1, 0);
ASSERT_RETURN(conn_dst->buf != MAP_FAILED);
conn_dummy->buf = mmap(NULL, POOL_SIZE, PROT_READ,
MAP_SHARED, connfd2, 0);
ASSERT_RETURN(conn_dummy->buf != MAP_FAILED);
/*
* Send fds to connection that do not accept fd passing
*/
ret = send_fds(conn_src, conn_dst->id, fds, 1);
ASSERT_RETURN(ret == -ECOMM);
/*
* memfd are kdbus payload
*/
ret = send_memfds(conn_src, conn_dst->id, memfd, 1);
ASSERT_RETURN(ret == 0);
ret = kdbus_msg_recv_poll(conn_dst, 100, NULL, NULL);
ASSERT_RETURN(ret == 0);
cookie = time(NULL);
pid = fork();
ASSERT_RETURN_VAL(pid >= 0, pid);
if (pid == 0) {
struct timespec now;
/*
* A sync send/reply to a connection that do not
* accept fds should fail if it contains an fd
*/
msg_sync_reply = get_kdbus_msg_with_fd(conn_dst,
conn_dummy->id,
cookie, fds[0]);
ASSERT_EXIT(msg_sync_reply);
ret = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
ASSERT_EXIT(ret == 0);
msg_sync_reply->timeout_ns = now.tv_sec * 1000000000ULL +
now.tv_nsec + 100000000ULL;
msg_sync_reply->flags = KDBUS_MSG_EXPECT_REPLY;
memset(&cmd, 0, sizeof(cmd));
cmd.size = sizeof(cmd);
cmd.msg_address = (uintptr_t)msg_sync_reply;
cmd.flags = KDBUS_SEND_SYNC_REPLY;
ret = kdbus_cmd_send(conn_dst->fd, &cmd);
ASSERT_EXIT(ret == -ECOMM);
/*
* Now send a normal message, but the sync reply
* will fail since it contains an fd that the
* original sender do not want.
*
* The original sender will fail with -ETIMEDOUT
*/
cookie++;
ret = kdbus_msg_send_sync(conn_dst, NULL, cookie,
KDBUS_MSG_EXPECT_REPLY,
5000000000ULL, 0, conn_src->id, -1);
ASSERT_EXIT(ret == -EREMOTEIO);
cookie++;
ret = kdbus_msg_recv_poll(conn_dst, 100, &msg, NULL);
ASSERT_EXIT(ret == 0);
ASSERT_EXIT(msg->cookie == cookie);
free(msg_sync_reply);
kdbus_msg_free(msg);
_exit(EXIT_SUCCESS);
}
ret = kdbus_msg_recv_poll(conn_dummy, 100, NULL, NULL);
ASSERT_RETURN(ret == -ETIMEDOUT);
cookie++;
ret = kdbus_msg_recv_poll(conn_src, 100, &msg, NULL);
ASSERT_RETURN(ret == 0 && msg->cookie == cookie);
kdbus_msg_free(msg);
/*
* Try to reply with a kdbus connection handle, this should
* fail with -EOPNOTSUPP
*/
msg_sync_reply = get_kdbus_msg_with_fd(conn_src,
conn_dst->id,
cookie, conn_dst->fd);
ASSERT_RETURN(msg_sync_reply);
msg_sync_reply->cookie_reply = cookie;
memset(&cmd, 0, sizeof(cmd));
cmd.size = sizeof(cmd);
cmd.msg_address = (uintptr_t)msg_sync_reply;
ret = kdbus_cmd_send(conn_src->fd, &cmd);
ASSERT_RETURN(ret == -EOPNOTSUPP);
free(msg_sync_reply);
/*
* Try to reply with a normal fd, this should fail even
* if the response is a sync reply
*
* From the sender view we fail with -ECOMM
*/
msg_sync_reply = get_kdbus_msg_with_fd(conn_src,
conn_dst->id,
cookie, fds[0]);
ASSERT_RETURN(msg_sync_reply);
msg_sync_reply->cookie_reply = cookie;
memset(&cmd, 0, sizeof(cmd));
cmd.size = sizeof(cmd);
cmd.msg_address = (uintptr_t)msg_sync_reply;
ret = kdbus_cmd_send(conn_src->fd, &cmd);
ASSERT_RETURN(ret == -ECOMM);
free(msg_sync_reply);
/*
* Resend another normal message and check if the queue
* is clear
*/
cookie++;
ret = kdbus_msg_send(conn_src, NULL, cookie, 0, 0, 0,
conn_dst->id);
ASSERT_RETURN(ret == 0);
ret = waitpid(pid, &status, 0);
ASSERT_RETURN_VAL(ret >= 0, ret);
kdbus_conn_free(conn_dummy);
kdbus_conn_free(conn_dst);
kdbus_conn_free(conn_src);
return (status == EXIT_SUCCESS) ? TEST_OK : TEST_ERR;
}
static int kdbus_send_multiple_fds(struct kdbus_conn *conn_src,
struct kdbus_conn *conn_dst)
{
int ret, i;
unsigned int nfds;
int fds[KDBUS_CONN_MAX_FDS_PER_USER + 1];
int memfds[KDBUS_MSG_MAX_ITEMS + 1];
struct kdbus_msg *msg;
uint64_t dummy_value;
dummy_value = time(NULL);
for (i = 0; i < KDBUS_CONN_MAX_FDS_PER_USER + 1; i++) {
fds[i] = open("/dev/null", O_RDWR|O_CLOEXEC);
ASSERT_RETURN_VAL(fds[i] >= 0, -errno);
}
/* Send KDBUS_CONN_MAX_FDS_PER_USER with one more fd */
ret = send_fds(conn_src, conn_dst->id, fds,
KDBUS_CONN_MAX_FDS_PER_USER + 1);
ASSERT_RETURN(ret == -EMFILE);
/* Retry with the correct KDBUS_CONN_MAX_FDS_PER_USER */
ret = send_fds(conn_src, conn_dst->id, fds,
KDBUS_CONN_MAX_FDS_PER_USER);
ASSERT_RETURN(ret == 0);
ret = kdbus_msg_recv(conn_dst, &msg, NULL);
ASSERT_RETURN(ret == 0);
/* Check we got the right number of fds */
nfds = kdbus_item_get_nfds(msg);
ASSERT_RETURN(nfds == KDBUS_CONN_MAX_FDS_PER_USER);
kdbus_msg_free(msg);
for (i = 0; i < KDBUS_MSG_MAX_ITEMS + 1; i++, dummy_value++) {
memfds[i] = memfd_write("memfd-name",
&dummy_value,
sizeof(dummy_value));
ASSERT_RETURN_VAL(memfds[i] >= 0, memfds[i]);
}
/* Send KDBUS_MSG_MAX_ITEMS with one more memfd */
ret = send_memfds(conn_src, conn_dst->id,
memfds, KDBUS_MSG_MAX_ITEMS + 1);
ASSERT_RETURN(ret == -E2BIG);
ret = send_memfds(conn_src, conn_dst->id,
memfds, KDBUS_MSG_MAX_MEMFD_ITEMS + 1);
ASSERT_RETURN(ret == -E2BIG);
/* Retry with the correct KDBUS_MSG_MAX_ITEMS */
ret = send_memfds(conn_src, conn_dst->id,
memfds, KDBUS_MSG_MAX_MEMFD_ITEMS);
ASSERT_RETURN(ret == 0);
ret = kdbus_msg_recv(conn_dst, &msg, NULL);
ASSERT_RETURN(ret == 0);
/* Check we got the right number of fds */
nfds = kdbus_item_get_nfds(msg);
ASSERT_RETURN(nfds == KDBUS_MSG_MAX_MEMFD_ITEMS);
kdbus_msg_free(msg);
/*
* Combine multiple KDBUS_CONN_MAX_FDS_PER_USER+1 fds and
* 10 memfds
*/
ret = send_fds_memfds(conn_src, conn_dst->id,
fds, KDBUS_CONN_MAX_FDS_PER_USER + 1,
memfds, 10);
ASSERT_RETURN(ret == -EMFILE);
ret = kdbus_msg_recv(conn_dst, NULL, NULL);
ASSERT_RETURN(ret == -EAGAIN);
/*
* Combine multiple KDBUS_CONN_MAX_FDS_PER_USER fds and
* (128 - 1) + 1 memfds, all fds take one item, while each
* memfd takes one item
*/
ret = send_fds_memfds(conn_src, conn_dst->id,
fds, KDBUS_CONN_MAX_FDS_PER_USER,
memfds, (KDBUS_MSG_MAX_ITEMS - 1) + 1);
ASSERT_RETURN(ret == -E2BIG);
ret = send_fds_memfds(conn_src, conn_dst->id,
fds, KDBUS_CONN_MAX_FDS_PER_USER,
memfds, KDBUS_MSG_MAX_MEMFD_ITEMS + 1);
ASSERT_RETURN(ret == -E2BIG);
ret = kdbus_msg_recv(conn_dst, NULL, NULL);
ASSERT_RETURN(ret == -EAGAIN);
/*
* Send KDBUS_CONN_MAX_FDS_PER_USER fds +
* KDBUS_MSG_MAX_MEMFD_ITEMS memfds
*/
ret = send_fds_memfds(conn_src, conn_dst->id,
fds, KDBUS_CONN_MAX_FDS_PER_USER,
memfds, KDBUS_MSG_MAX_MEMFD_ITEMS);
ASSERT_RETURN(ret == 0);
ret = kdbus_msg_recv(conn_dst, &msg, NULL);
ASSERT_RETURN(ret == 0);
/* Check we got the right number of fds */
nfds = kdbus_item_get_nfds(msg);
ASSERT_RETURN(nfds == KDBUS_CONN_MAX_FDS_PER_USER +
KDBUS_MSG_MAX_MEMFD_ITEMS);
kdbus_msg_free(msg);
/*
* Re-send fds + memfds, close them, but do not receive them
* and try to queue more
*/
ret = send_fds_memfds(conn_src, conn_dst->id,
fds, KDBUS_CONN_MAX_FDS_PER_USER,
memfds, KDBUS_MSG_MAX_MEMFD_ITEMS);
ASSERT_RETURN(ret == 0);
/* close old references and get a new ones */
for (i = 0; i < KDBUS_CONN_MAX_FDS_PER_USER + 1; i++) {
close(fds[i]);
fds[i] = open("/dev/null", O_RDWR|O_CLOEXEC);
ASSERT_RETURN_VAL(fds[i] >= 0, -errno);
}
/* should fail since we have already fds in the queue */
ret = send_fds(conn_src, conn_dst->id, fds,
KDBUS_CONN_MAX_FDS_PER_USER);
ASSERT_RETURN(ret == -EMFILE);
/* This should succeed */
ret = send_memfds(conn_src, conn_dst->id,
memfds, KDBUS_MSG_MAX_MEMFD_ITEMS);
ASSERT_RETURN(ret == 0);
ret = kdbus_msg_recv(conn_dst, &msg, NULL);
ASSERT_RETURN(ret == 0);
nfds = kdbus_item_get_nfds(msg);
ASSERT_RETURN(nfds == KDBUS_CONN_MAX_FDS_PER_USER +
KDBUS_MSG_MAX_MEMFD_ITEMS);
kdbus_msg_free(msg);
ret = kdbus_msg_recv(conn_dst, &msg, NULL);
ASSERT_RETURN(ret == 0);
nfds = kdbus_item_get_nfds(msg);
ASSERT_RETURN(nfds == KDBUS_MSG_MAX_MEMFD_ITEMS);
kdbus_msg_free(msg);
ret = kdbus_msg_recv(conn_dst, NULL, NULL);
ASSERT_RETURN(ret == -EAGAIN);
for (i = 0; i < KDBUS_CONN_MAX_FDS_PER_USER + 1; i++)
close(fds[i]);
for (i = 0; i < KDBUS_MSG_MAX_ITEMS + 1; i++)
close(memfds[i]);
return 0;
}
int kdbus_test_fd_passing(struct kdbus_test_env *env)
{
struct kdbus_conn *conn_src, *conn_dst;
const char *str = "stackenblocken";
const struct kdbus_item *item;
struct kdbus_msg *msg;
unsigned int i;
uint64_t now;
int fds_conn[2];
int sock_pair[2];
int fds[2];
int memfd;
int ret;
now = (uint64_t) time(NULL);
/* create two connections */
conn_src = kdbus_hello(env->buspath, 0, NULL, 0);
conn_dst = kdbus_hello(env->buspath, 0, NULL, 0);
ASSERT_RETURN(conn_src && conn_dst);
fds_conn[0] = conn_src->fd;
fds_conn[1] = conn_dst->fd;
ret = socketpair(AF_UNIX, SOCK_STREAM, 0, sock_pair);
ASSERT_RETURN(ret == 0);
/* Setup memfd */
memfd = memfd_write("memfd-name", &now, sizeof(now));
ASSERT_RETURN(memfd >= 0);
/* Setup pipes */
ret = pipe(fds);
ASSERT_RETURN(ret == 0);
i = write(fds[1], str, strlen(str));
ASSERT_RETURN(i == strlen(str));
/*
* Try to ass the handle of a connection as message payload.
* This must fail.
*/
ret = send_fds(conn_src, conn_dst->id, fds_conn, 2);
ASSERT_RETURN(ret == -ENOTSUP);
ret = send_fds(conn_dst, conn_src->id, fds_conn, 2);
ASSERT_RETURN(ret == -ENOTSUP);
ret = send_fds(conn_src, conn_dst->id, sock_pair, 2);
ASSERT_RETURN(ret == -ENOTSUP);
/*
* Send fds and memfds to connection that do not accept fds
*/
ret = kdbus_test_no_fds(env, fds, (int *)&memfd);
ASSERT_RETURN(ret == 0);
/* Try to broadcast file descriptors. This must fail. */
ret = send_fds(conn_src, KDBUS_DST_ID_BROADCAST, fds, 1);
ASSERT_RETURN(ret == -ENOTUNIQ);
/* Try to broadcast memfd. This must succeed. */
ret = send_memfds(conn_src, KDBUS_DST_ID_BROADCAST, (int *)&memfd, 1);
ASSERT_RETURN(ret == 0);
/* Open code this loop */
loop_send_fds:
/*
* Send the read end of the pipe and close it.
*/
ret = send_fds(conn_src, conn_dst->id, fds, 1);
ASSERT_RETURN(ret == 0);
close(fds[0]);
ret = kdbus_msg_recv(conn_dst, &msg, NULL);
ASSERT_RETURN(ret == 0);
KDBUS_ITEM_FOREACH(item, msg, items) {
if (item->type == KDBUS_ITEM_FDS) {
char tmp[14];
int nfds = (item->size - KDBUS_ITEM_HEADER_SIZE) /
sizeof(int);
ASSERT_RETURN(nfds == 1);
i = read(item->fds[0], tmp, sizeof(tmp));
if (i != 0) {
ASSERT_RETURN(i == sizeof(tmp));
ASSERT_RETURN(memcmp(tmp, str, sizeof(tmp)) == 0);
/* Write EOF */
close(fds[1]);
/*
* Resend the read end of the pipe,
* the receiver still holds a reference
* to it...
*/
goto loop_send_fds;
}
/* Got EOF */
/*
* Close the last reference to the read end
* of the pipe, other references are
* automatically closed just after send.
*/
close(item->fds[0]);
}
}
/*
* Try to resend the read end of the pipe. Must fail with
* -EBADF since both the sender and receiver closed their
* references to it. We assume the above since sender and
* receiver are on the same process.
*/
ret = send_fds(conn_src, conn_dst->id, fds, 1);
ASSERT_RETURN(ret == -EBADF);
/* Then we clear out received any data... */
kdbus_msg_free(msg);
ret = kdbus_send_multiple_fds(conn_src, conn_dst);
ASSERT_RETURN(ret == 0);
close(sock_pair[0]);
close(sock_pair[1]);
close(memfd);
kdbus_conn_free(conn_src);
kdbus_conn_free(conn_dst);
return TEST_OK;
}
| loxdegio/linux-patched | tools/testing/selftests/kdbus/test-fd.c | C | gpl-2.0 | 19,254 |
// Multimap iterator invalidation tests
// Copyright (C) 2003-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <debug/map>
#include <iterator>
#include <testsuite_hooks.h>
#include <utility>
using __gnu_debug::multimap;
using std::advance;
bool test = true;
// Erase
void test02()
{
multimap<int, int> v;
for (int i = 0; i < 20; ++i)
v.insert(std::make_pair(i, 20-i));
// Single element erase (middle)
multimap<int, int>::iterator before = v.begin();
multimap<int, int>::iterator at = before;
advance(at, 3);
multimap<int, int>::iterator after = at;
++after;
v.erase(at);
VERIFY(before._M_dereferenceable());
VERIFY(at._M_singular());
VERIFY(after._M_dereferenceable());
// Multiple element erase
before = v.begin();
at = before;
advance(at, 3);
after = at;
advance(after, 4);
v.erase(at, after);
VERIFY(before._M_dereferenceable());
VERIFY(at._M_singular());
// clear()
before = v.begin();
multimap<int, int>::iterator finish = v.end();
VERIFY(before._M_dereferenceable());
v.clear();
VERIFY(before._M_singular());
VERIFY(!finish._M_singular() && !finish._M_dereferenceable());
}
int main()
{
test02();
return 0;
}
| mickael-guene/gcc | libstdc++-v3/testsuite/23_containers/multimap/debug/invalidation/2.cc | C++ | gpl-2.0 | 1,890 |
/* { dg-do compile } */
/* { dg-options "-O2" } */
#define vector __attribute__((vector_size(4*sizeof(float))))
/* These are both dups. */
vector float f(vector float a, vector float b)
{
return __builtin_shuffle (a, a, (vector int){0, 1, 0, 1});
}
vector float f1(vector float a, vector float b)
{
return __builtin_shuffle (a, a, (vector int){2, 3, 2, 3});
}
/* { dg-final { scan-assembler-times {[ \t]*dup[ \t]+v[0-9]+\.2d} 2 } } */
| Gurgel100/gcc | gcc/testsuite/gcc.target/aarch64/vdup_n_3.c | C | gpl-2.0 | 442 |
/*
* Copyright (c) 1997, 2010, 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 com.sun.xml.internal.ws.util.pipe;
import com.sun.istack.internal.NotNull;
import com.sun.xml.internal.ws.api.pipe.ClientPipeAssemblerContext;
import com.sun.xml.internal.ws.api.pipe.Pipe;
import com.sun.xml.internal.ws.api.pipe.PipelineAssembler;
import com.sun.xml.internal.ws.api.pipe.ServerPipeAssemblerContext;
/**
* Default Pipeline assembler for JAX-WS client and server side runtimes. It
* assembles various pipes into a pipeline that a message needs to be passed
* through.
*
* @author Kohsuke Kawaguchi
* @author Jitendra Kotamraju
*/
public class StandalonePipeAssembler implements PipelineAssembler {
@NotNull
public Pipe createClient(ClientPipeAssemblerContext context) {
Pipe head = context.createTransportPipe();
head = context.createSecurityPipe(head);
if (dump) {
// for debugging inject a dump pipe. this is left in the production code,
// as it would be very handy for a trouble-shooting at the production site.
head = context.createDumpPipe("client", System.out, head);
}
head = context.createWsaPipe(head);
head = context.createClientMUPipe(head);
return context.createHandlerPipe(head);
}
/**
* On Server-side, HandlerChains cannot be changed after it is deployed.
* During assembling the Pipelines, we can decide if we really need a
* SOAPHandlerPipe and LogicalHandlerPipe for a particular Endpoint.
*/
public Pipe createServer(ServerPipeAssemblerContext context) {
Pipe head = context.getTerminalPipe();
head = context.createHandlerPipe(head);
head = context.createMonitoringPipe(head);
head = context.createServerMUPipe(head);
head = context.createWsaPipe(head);
head = context.createSecurityPipe(head);
return head;
}
/**
* Are we going to dump the message to System.out?
*/
private static final boolean dump;
static {
boolean b = false;
try {
b = Boolean.getBoolean(StandalonePipeAssembler.class.getName()+".dump");
} catch (Throwable t) {
// treat it as false
}
dump = b;
}
}
| axDev-JDK/jaxws | src/share/jaxws_classes/com/sun/xml/internal/ws/util/pipe/StandalonePipeAssembler.java | Java | gpl-2.0 | 3,423 |
<?php
class CommonDreamsBridge extends FeedExpander {
const MAINTAINER = 'nyutag';
const NAME = 'CommonDreams Bridge';
const URI = 'https://www.commondreams.org/';
const DESCRIPTION = 'Returns the newest articles.';
public function collectData(){
$this->collectExpandableDatas('http://www.commondreams.org/rss.xml', 10);
}
protected function parseItem($newsItem){
$item = parent::parseItem($newsItem);
$item['content'] = $this->extractContent($item['uri']);
return $item;
}
private function extractContent($url){
$html3 = getSimpleHTMLDOMCached($url);
$text = $html3->find('div[class=field--type-text-with-summary]', 0)->innertext;
$html3->clear();
unset ($html3);
return $text;
}
}
| stupiddingo/boisewaldorf | web/UXsQTutSQY7w7u6s/bridges/CommonDreamsBridge.php | PHP | gpl-2.0 | 715 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct not_enough_input</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost Algorithm Library">
<link rel="up" href="../../header/boost/algorithm/hex_hpp.html" title="Header <boost/algorithm/hex.hpp>">
<link rel="prev" href="non_hex_input.html" title="Struct non_hex_input">
<link rel="next" href="hex_idp20291248.html" title="Function template hex">
</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="non_hex_input.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/algorithm/hex_hpp.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="hex_idp20291248.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.algorithm.not_enough_input"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct not_enough_input</span></h2>
<p>boost::algorithm::not_enough_input — Thrown when the input sequence unexpectedly ends. </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"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../header/boost/algorithm/hex_hpp.html" title="Header <boost/algorithm/hex.hpp>">boost/algorithm/hex.hpp</a>>
</span>
<span class="keyword">struct</span> <a class="link" href="not_enough_input.html" title="Struct not_enough_input">not_enough_input</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">algorithm</span><span class="special">::</span><span class="identifier">hex_decode_error</span> <span class="special">{</span>
<span class="special">}</span><span class="special">;</span></pre></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 © 2010-2012 Marshall Clow<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="non_hex_input.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/algorithm/hex_hpp.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="hex_idp20291248.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| rprata/boost | libs/algorithm/doc/html/boost/algorithm/not_enough_input.html | HTML | gpl-2.0 | 3,985 |
/*
* Linux INET6 implementation
* FIB front-end.
*
* Authors:
* Pedro Roque <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
/* Changes:
*
* YOSHIFUJI Hideaki @USAGI
* reworked default router selection.
* - respect outgoing interface
* - select from (probably) reachable routers (i.e.
* routers in REACHABLE, STALE, DELAY or PROBE states).
* - always select the same router if it is (probably)
* reachable. otherwise, round-robin the list.
* Ville Nuorvala
* Fixed routing subtrees.
*/
#define pr_fmt(fmt) "IPv6: " fmt
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/export.h>
#include <linux/types.h>
#include <linux/times.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/route.h>
#include <linux/netdevice.h>
#include <linux/in6.h>
#include <linux/mroute6.h>
#include <linux/init.h>
#include <linux/if_arp.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/nsproxy.h>
#include <linux/slab.h>
#include <net/net_namespace.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/ip6_fib.h>
#include <net/ip6_route.h>
#include <net/ndisc.h>
#include <net/addrconf.h>
#include <net/tcp.h>
#include <linux/rtnetlink.h>
#include <net/dst.h>
#include <net/xfrm.h>
#include <net/netevent.h>
#include <net/netlink.h>
#include <net/nexthop.h>
#include <asm/uaccess.h>
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
#endif
enum rt6_nud_state {
RT6_NUD_FAIL_HARD = -2,
RT6_NUD_FAIL_SOFT = -1,
RT6_NUD_SUCCEED = 1
};
static struct rt6_info *ip6_rt_copy(struct rt6_info *ort,
const struct in6_addr *dest);
static struct dst_entry *ip6_dst_check(struct dst_entry *dst, u32 cookie);
static unsigned int ip6_default_advmss(const struct dst_entry *dst);
static unsigned int ip6_mtu(const struct dst_entry *dst);
static struct dst_entry *ip6_negative_advice(struct dst_entry *);
static void ip6_dst_destroy(struct dst_entry *);
static void ip6_dst_ifdown(struct dst_entry *,
struct net_device *dev, int how);
static int ip6_dst_gc(struct dst_ops *ops);
static int ip6_pkt_discard(struct sk_buff *skb);
static int ip6_pkt_discard_out(struct sk_buff *skb);
static int ip6_pkt_prohibit(struct sk_buff *skb);
static int ip6_pkt_prohibit_out(struct sk_buff *skb);
static void ip6_link_failure(struct sk_buff *skb);
static void ip6_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu);
static void rt6_do_redirect(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb);
#ifdef CONFIG_IPV6_ROUTE_INFO
static struct rt6_info *rt6_add_route_info(struct net_device *dev,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr, unsigned int pref);
static struct rt6_info *rt6_get_route_info(struct net_device *dev,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr);
#endif
static u32 *ipv6_cow_metrics(struct dst_entry *dst, unsigned long old)
{
struct rt6_info *rt = (struct rt6_info *) dst;
struct inet_peer *peer;
u32 *p = NULL;
if (!(rt->dst.flags & DST_HOST))
return NULL;
peer = rt6_get_peer_create(rt);
if (peer) {
u32 *old_p = __DST_METRICS_PTR(old);
unsigned long prev, new;
p = peer->metrics;
if (inet_metrics_new(peer))
memcpy(p, old_p, sizeof(u32) * RTAX_MAX);
new = (unsigned long) p;
prev = cmpxchg(&dst->_metrics, old, new);
if (prev != old) {
p = __DST_METRICS_PTR(prev);
if (prev & DST_METRICS_READ_ONLY)
p = NULL;
}
}
return p;
}
static inline const void *choose_neigh_daddr(struct rt6_info *rt,
struct sk_buff *skb,
const void *daddr)
{
struct in6_addr *p = &rt->rt6i_gateway;
if (!ipv6_addr_any(p))
return (const void *) p;
else if (skb)
return &ipv6_hdr(skb)->daddr;
return daddr;
}
static struct neighbour *ip6_neigh_lookup(const struct dst_entry *dst,
struct sk_buff *skb,
const void *daddr)
{
struct rt6_info *rt = (struct rt6_info *) dst;
struct neighbour *n;
daddr = choose_neigh_daddr(rt, skb, daddr);
n = __ipv6_neigh_lookup(dst->dev, daddr);
if (n)
return n;
return neigh_create(&nd_tbl, daddr, dst->dev);
}
static struct dst_ops ip6_dst_ops_template = {
.family = AF_INET6,
.protocol = cpu_to_be16(ETH_P_IPV6),
.gc = ip6_dst_gc,
.gc_thresh = 1024,
.check = ip6_dst_check,
.default_advmss = ip6_default_advmss,
.mtu = ip6_mtu,
.cow_metrics = ipv6_cow_metrics,
.destroy = ip6_dst_destroy,
.ifdown = ip6_dst_ifdown,
.negative_advice = ip6_negative_advice,
.link_failure = ip6_link_failure,
.update_pmtu = ip6_rt_update_pmtu,
.redirect = rt6_do_redirect,
.local_out = __ip6_local_out,
.neigh_lookup = ip6_neigh_lookup,
};
static unsigned int ip6_blackhole_mtu(const struct dst_entry *dst)
{
unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
return mtu ? : dst->dev->mtu;
}
static void ip6_rt_blackhole_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu)
{
}
static void ip6_rt_blackhole_redirect(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb)
{
}
static u32 *ip6_rt_blackhole_cow_metrics(struct dst_entry *dst,
unsigned long old)
{
return NULL;
}
static struct dst_ops ip6_dst_blackhole_ops = {
.family = AF_INET6,
.protocol = cpu_to_be16(ETH_P_IPV6),
.destroy = ip6_dst_destroy,
.check = ip6_dst_check,
.mtu = ip6_blackhole_mtu,
.default_advmss = ip6_default_advmss,
.update_pmtu = ip6_rt_blackhole_update_pmtu,
.redirect = ip6_rt_blackhole_redirect,
.cow_metrics = ip6_rt_blackhole_cow_metrics,
.neigh_lookup = ip6_neigh_lookup,
};
static const u32 ip6_template_metrics[RTAX_MAX] = {
[RTAX_HOPLIMIT - 1] = 0,
};
static const struct rt6_info ip6_null_entry_template = {
.dst = {
.__refcnt = ATOMIC_INIT(1),
.__use = 1,
.obsolete = DST_OBSOLETE_FORCE_CHK,
.error = -ENETUNREACH,
.input = ip6_pkt_discard,
.output = ip6_pkt_discard_out,
},
.rt6i_flags = (RTF_REJECT | RTF_NONEXTHOP),
.rt6i_protocol = RTPROT_KERNEL,
.rt6i_metric = ~(u32) 0,
.rt6i_ref = ATOMIC_INIT(1),
};
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
static const struct rt6_info ip6_prohibit_entry_template = {
.dst = {
.__refcnt = ATOMIC_INIT(1),
.__use = 1,
.obsolete = DST_OBSOLETE_FORCE_CHK,
.error = -EACCES,
.input = ip6_pkt_prohibit,
.output = ip6_pkt_prohibit_out,
},
.rt6i_flags = (RTF_REJECT | RTF_NONEXTHOP),
.rt6i_protocol = RTPROT_KERNEL,
.rt6i_metric = ~(u32) 0,
.rt6i_ref = ATOMIC_INIT(1),
};
static const struct rt6_info ip6_blk_hole_entry_template = {
.dst = {
.__refcnt = ATOMIC_INIT(1),
.__use = 1,
.obsolete = DST_OBSOLETE_FORCE_CHK,
.error = -EINVAL,
.input = dst_discard,
.output = dst_discard,
},
.rt6i_flags = (RTF_REJECT | RTF_NONEXTHOP),
.rt6i_protocol = RTPROT_KERNEL,
.rt6i_metric = ~(u32) 0,
.rt6i_ref = ATOMIC_INIT(1),
};
#endif
/* allocate dst with ip6_dst_ops */
static inline struct rt6_info *ip6_dst_alloc(struct net *net,
struct net_device *dev,
int flags,
struct fib6_table *table)
{
struct rt6_info *rt = dst_alloc(&net->ipv6.ip6_dst_ops, dev,
0, DST_OBSOLETE_FORCE_CHK, flags);
if (rt) {
struct dst_entry *dst = &rt->dst;
memset(dst + 1, 0, sizeof(*rt) - sizeof(*dst));
rt6_init_peer(rt, table ? &table->tb6_peers : net->ipv6.peers);
rt->rt6i_genid = rt_genid(net);
INIT_LIST_HEAD(&rt->rt6i_siblings);
rt->rt6i_nsiblings = 0;
}
return rt;
}
static void ip6_dst_destroy(struct dst_entry *dst)
{
struct rt6_info *rt = (struct rt6_info *)dst;
struct inet6_dev *idev = rt->rt6i_idev;
struct dst_entry *from = dst->from;
if (!(rt->dst.flags & DST_HOST))
dst_destroy_metrics_generic(dst);
if (idev) {
rt->rt6i_idev = NULL;
in6_dev_put(idev);
}
dst->from = NULL;
dst_release(from);
if (rt6_has_peer(rt)) {
struct inet_peer *peer = rt6_peer_ptr(rt);
inet_putpeer(peer);
}
}
void rt6_bind_peer(struct rt6_info *rt, int create)
{
struct inet_peer_base *base;
struct inet_peer *peer;
base = inetpeer_base_ptr(rt->_rt6i_peer);
if (!base)
return;
peer = inet_getpeer_v6(base, &rt->rt6i_dst.addr, create);
if (peer) {
if (!rt6_set_peer(rt, peer))
inet_putpeer(peer);
}
}
static void ip6_dst_ifdown(struct dst_entry *dst, struct net_device *dev,
int how)
{
struct rt6_info *rt = (struct rt6_info *)dst;
struct inet6_dev *idev = rt->rt6i_idev;
struct net_device *loopback_dev =
dev_net(dev)->loopback_dev;
if (dev != loopback_dev) {
if (idev && idev->dev == dev) {
struct inet6_dev *loopback_idev =
in6_dev_get(loopback_dev);
if (loopback_idev) {
rt->rt6i_idev = loopback_idev;
in6_dev_put(idev);
}
}
}
}
static bool rt6_check_expired(const struct rt6_info *rt)
{
if (rt->rt6i_flags & RTF_EXPIRES) {
if (time_after(jiffies, rt->dst.expires))
return true;
} else if (rt->dst.from) {
return rt6_check_expired((struct rt6_info *) rt->dst.from);
}
return false;
}
static bool rt6_need_strict(const struct in6_addr *daddr)
{
return ipv6_addr_type(daddr) &
(IPV6_ADDR_MULTICAST | IPV6_ADDR_LINKLOCAL | IPV6_ADDR_LOOPBACK);
}
/* Multipath route selection:
* Hash based function using packet header and flowlabel.
* Adapted from fib_info_hashfn()
*/
static int rt6_info_hash_nhsfn(unsigned int candidate_count,
const struct flowi6 *fl6)
{
unsigned int val = fl6->flowi6_proto;
val ^= ipv6_addr_hash(&fl6->daddr);
val ^= ipv6_addr_hash(&fl6->saddr);
/* Work only if this not encapsulated */
switch (fl6->flowi6_proto) {
case IPPROTO_UDP:
case IPPROTO_TCP:
case IPPROTO_SCTP:
val ^= (__force u16)fl6->fl6_sport;
val ^= (__force u16)fl6->fl6_dport;
break;
case IPPROTO_ICMPV6:
val ^= (__force u16)fl6->fl6_icmp_type;
val ^= (__force u16)fl6->fl6_icmp_code;
break;
}
/* RFC6438 recommands to use flowlabel */
val ^= (__force u32)fl6->flowlabel;
/* Perhaps, we need to tune, this function? */
val = val ^ (val >> 7) ^ (val >> 12);
return val % candidate_count;
}
static struct rt6_info *rt6_multipath_select(struct rt6_info *match,
struct flowi6 *fl6)
{
struct rt6_info *sibling, *next_sibling;
int route_choosen;
route_choosen = rt6_info_hash_nhsfn(match->rt6i_nsiblings + 1, fl6);
/* Don't change the route, if route_choosen == 0
* (siblings does not include ourself)
*/
if (route_choosen)
list_for_each_entry_safe(sibling, next_sibling,
&match->rt6i_siblings, rt6i_siblings) {
route_choosen--;
if (route_choosen == 0) {
match = sibling;
break;
}
}
return match;
}
/*
* Route lookup. Any table->tb6_lock is implied.
*/
static inline struct rt6_info *rt6_device_match(struct net *net,
struct rt6_info *rt,
const struct in6_addr *saddr,
int oif,
int flags)
{
struct rt6_info *local = NULL;
struct rt6_info *sprt;
if (!oif && ipv6_addr_any(saddr))
goto out;
for (sprt = rt; sprt; sprt = sprt->dst.rt6_next) {
struct net_device *dev = sprt->dst.dev;
if (oif) {
if (dev->ifindex == oif)
return sprt;
if (dev->flags & IFF_LOOPBACK) {
if (!sprt->rt6i_idev ||
sprt->rt6i_idev->dev->ifindex != oif) {
if (flags & RT6_LOOKUP_F_IFACE && oif)
continue;
if (local && (!oif ||
local->rt6i_idev->dev->ifindex == oif))
continue;
}
local = sprt;
}
} else {
if (ipv6_chk_addr(net, saddr, dev,
flags & RT6_LOOKUP_F_IFACE))
return sprt;
}
}
if (oif) {
if (local)
return local;
if (flags & RT6_LOOKUP_F_IFACE)
return net->ipv6.ip6_null_entry;
}
out:
return rt;
}
#ifdef CONFIG_IPV6_ROUTER_PREF
struct __rt6_probe_work {
struct work_struct work;
struct in6_addr target;
struct net_device *dev;
};
static void rt6_probe_deferred(struct work_struct *w)
{
struct in6_addr mcaddr;
struct __rt6_probe_work *work =
container_of(w, struct __rt6_probe_work, work);
addrconf_addr_solict_mult(&work->target, &mcaddr);
ndisc_send_ns(work->dev, NULL, &work->target, &mcaddr, NULL);
dev_put(work->dev);
kfree(w);
}
static void rt6_probe(struct rt6_info *rt)
{
struct neighbour *neigh;
/*
* Okay, this does not seem to be appropriate
* for now, however, we need to check if it
* is really so; aka Router Reachability Probing.
*
* Router Reachability Probe MUST be rate-limited
* to no more than one per minute.
*/
if (!rt || !(rt->rt6i_flags & RTF_GATEWAY))
return;
rcu_read_lock_bh();
neigh = __ipv6_neigh_lookup_noref(rt->dst.dev, &rt->rt6i_gateway);
if (neigh) {
write_lock(&neigh->lock);
if (neigh->nud_state & NUD_VALID)
goto out;
}
if (!neigh ||
time_after(jiffies, neigh->updated + rt->rt6i_idev->cnf.rtr_probe_interval)) {
struct __rt6_probe_work *work;
work = kmalloc(sizeof(*work), GFP_ATOMIC);
if (neigh && work)
neigh->updated = jiffies;
if (neigh)
write_unlock(&neigh->lock);
if (work) {
INIT_WORK(&work->work, rt6_probe_deferred);
work->target = rt->rt6i_gateway;
dev_hold(rt->dst.dev);
work->dev = rt->dst.dev;
schedule_work(&work->work);
}
} else {
out:
write_unlock(&neigh->lock);
}
rcu_read_unlock_bh();
}
#else
static inline void rt6_probe(struct rt6_info *rt)
{
}
#endif
/*
* Default Router Selection (RFC 2461 6.3.6)
*/
static inline int rt6_check_dev(struct rt6_info *rt, int oif)
{
struct net_device *dev = rt->dst.dev;
if (!oif || dev->ifindex == oif)
return 2;
if ((dev->flags & IFF_LOOPBACK) &&
rt->rt6i_idev && rt->rt6i_idev->dev->ifindex == oif)
return 1;
return 0;
}
static inline enum rt6_nud_state rt6_check_neigh(struct rt6_info *rt)
{
struct neighbour *neigh;
enum rt6_nud_state ret = RT6_NUD_FAIL_HARD;
if (rt->rt6i_flags & RTF_NONEXTHOP ||
!(rt->rt6i_flags & RTF_GATEWAY))
return RT6_NUD_SUCCEED;
rcu_read_lock_bh();
neigh = __ipv6_neigh_lookup_noref(rt->dst.dev, &rt->rt6i_gateway);
if (neigh) {
read_lock(&neigh->lock);
if (neigh->nud_state & NUD_VALID)
ret = RT6_NUD_SUCCEED;
#ifdef CONFIG_IPV6_ROUTER_PREF
else if (!(neigh->nud_state & NUD_FAILED))
ret = RT6_NUD_SUCCEED;
#endif
read_unlock(&neigh->lock);
} else {
ret = IS_ENABLED(CONFIG_IPV6_ROUTER_PREF) ?
RT6_NUD_SUCCEED : RT6_NUD_FAIL_SOFT;
}
rcu_read_unlock_bh();
return ret;
}
static int rt6_score_route(struct rt6_info *rt, int oif,
int strict)
{
int m;
m = rt6_check_dev(rt, oif);
if (!m && (strict & RT6_LOOKUP_F_IFACE))
return RT6_NUD_FAIL_HARD;
#ifdef CONFIG_IPV6_ROUTER_PREF
m |= IPV6_DECODE_PREF(IPV6_EXTRACT_PREF(rt->rt6i_flags)) << 2;
#endif
if (strict & RT6_LOOKUP_F_REACHABLE) {
int n = rt6_check_neigh(rt);
if (n < 0)
return n;
}
return m;
}
static struct rt6_info *find_match(struct rt6_info *rt, int oif, int strict,
int *mpri, struct rt6_info *match,
bool *do_rr)
{
int m;
bool match_do_rr = false;
if (rt6_check_expired(rt))
goto out;
m = rt6_score_route(rt, oif, strict);
if (m == RT6_NUD_FAIL_SOFT && !IS_ENABLED(CONFIG_IPV6_ROUTER_PREF)) {
match_do_rr = true;
m = 0; /* lowest valid score */
} else if (m < 0) {
goto out;
}
if (strict & RT6_LOOKUP_F_REACHABLE)
rt6_probe(rt);
if (m > *mpri) {
*do_rr = match_do_rr;
*mpri = m;
match = rt;
}
out:
return match;
}
static struct rt6_info *find_rr_leaf(struct fib6_node *fn,
struct rt6_info *rr_head,
u32 metric, int oif, int strict,
bool *do_rr)
{
struct rt6_info *rt, *match;
int mpri = -1;
match = NULL;
for (rt = rr_head; rt && rt->rt6i_metric == metric;
rt = rt->dst.rt6_next)
match = find_match(rt, oif, strict, &mpri, match, do_rr);
for (rt = fn->leaf; rt && rt != rr_head && rt->rt6i_metric == metric;
rt = rt->dst.rt6_next)
match = find_match(rt, oif, strict, &mpri, match, do_rr);
return match;
}
static struct rt6_info *rt6_select(struct fib6_node *fn, int oif, int strict)
{
struct rt6_info *match, *rt0;
struct net *net;
bool do_rr = false;
rt0 = fn->rr_ptr;
if (!rt0)
fn->rr_ptr = rt0 = fn->leaf;
match = find_rr_leaf(fn, rt0, rt0->rt6i_metric, oif, strict,
&do_rr);
if (do_rr) {
struct rt6_info *next = rt0->dst.rt6_next;
/* no entries matched; do round-robin */
if (!next || next->rt6i_metric != rt0->rt6i_metric)
next = fn->leaf;
if (next != rt0)
fn->rr_ptr = next;
}
net = dev_net(rt0->dst.dev);
return match ? match : net->ipv6.ip6_null_entry;
}
#ifdef CONFIG_IPV6_ROUTE_INFO
int rt6_route_rcv(struct net_device *dev, u8 *opt, int len,
const struct in6_addr *gwaddr)
{
struct route_info *rinfo = (struct route_info *) opt;
struct in6_addr prefix_buf, *prefix;
unsigned int pref;
unsigned long lifetime;
struct rt6_info *rt;
if (len < sizeof(struct route_info)) {
return -EINVAL;
}
/* Sanity check for prefix_len and length */
if (rinfo->length > 3) {
return -EINVAL;
} else if (rinfo->prefix_len > 128) {
return -EINVAL;
} else if (rinfo->prefix_len > 64) {
if (rinfo->length < 2) {
return -EINVAL;
}
} else if (rinfo->prefix_len > 0) {
if (rinfo->length < 1) {
return -EINVAL;
}
}
pref = rinfo->route_pref;
if (pref == ICMPV6_ROUTER_PREF_INVALID)
return -EINVAL;
lifetime = addrconf_timeout_fixup(ntohl(rinfo->lifetime), HZ);
if (rinfo->length == 3)
prefix = (struct in6_addr *)rinfo->prefix;
else {
/* this function is safe */
ipv6_addr_prefix(&prefix_buf,
(struct in6_addr *)rinfo->prefix,
rinfo->prefix_len);
prefix = &prefix_buf;
}
if (rinfo->prefix_len == 0)
rt = rt6_get_dflt_router(gwaddr, dev);
else
rt = rt6_get_route_info(dev, prefix, rinfo->prefix_len, gwaddr);
if (rt && !lifetime) {
ip6_del_rt(rt);
rt = NULL;
}
if (!rt && lifetime)
rt = rt6_add_route_info(dev, prefix, rinfo->prefix_len, gwaddr, pref);
else if (rt)
rt->rt6i_flags = RTF_ROUTEINFO |
(rt->rt6i_flags & ~RTF_PREF_MASK) | RTF_PREF(pref);
if (rt) {
if (!addrconf_finite_timeout(lifetime))
rt6_clean_expires(rt);
else
rt6_set_expires(rt, jiffies + HZ * lifetime);
ip6_rt_put(rt);
}
return 0;
}
#endif
#define BACKTRACK(__net, saddr) \
do { \
if (rt == __net->ipv6.ip6_null_entry) { \
struct fib6_node *pn; \
while (1) { \
if (fn->fn_flags & RTN_TL_ROOT) \
goto out; \
pn = fn->parent; \
if (FIB6_SUBTREE(pn) && FIB6_SUBTREE(pn) != fn) \
fn = fib6_lookup(FIB6_SUBTREE(pn), NULL, saddr); \
else \
fn = pn; \
if (fn->fn_flags & RTN_RTINFO) \
goto restart; \
} \
} \
} while (0)
static struct rt6_info *ip6_pol_route_lookup(struct net *net,
struct fib6_table *table,
struct flowi6 *fl6, int flags)
{
struct fib6_node *fn;
struct rt6_info *rt;
read_lock_bh(&table->tb6_lock);
fn = fib6_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
restart:
rt = fn->leaf;
rt = rt6_device_match(net, rt, &fl6->saddr, fl6->flowi6_oif, flags);
if (rt->rt6i_nsiblings && fl6->flowi6_oif == 0)
rt = rt6_multipath_select(rt, fl6);
BACKTRACK(net, &fl6->saddr);
out:
dst_use(&rt->dst, jiffies);
read_unlock_bh(&table->tb6_lock);
return rt;
}
struct dst_entry * ip6_route_lookup(struct net *net, struct flowi6 *fl6,
int flags)
{
return fib6_rule_lookup(net, fl6, flags, ip6_pol_route_lookup);
}
EXPORT_SYMBOL_GPL(ip6_route_lookup);
struct rt6_info *rt6_lookup(struct net *net, const struct in6_addr *daddr,
const struct in6_addr *saddr, int oif, int strict)
{
struct flowi6 fl6 = {
.flowi6_oif = oif,
.daddr = *daddr,
};
struct dst_entry *dst;
int flags = strict ? RT6_LOOKUP_F_IFACE : 0;
if (saddr) {
memcpy(&fl6.saddr, saddr, sizeof(*saddr));
flags |= RT6_LOOKUP_F_HAS_SADDR;
}
dst = fib6_rule_lookup(net, &fl6, flags, ip6_pol_route_lookup);
if (dst->error == 0)
return (struct rt6_info *) dst;
dst_release(dst);
return NULL;
}
EXPORT_SYMBOL(rt6_lookup);
/* ip6_ins_rt is called with FREE table->tb6_lock.
It takes new route entry, the addition fails by any reason the
route is freed. In any case, if caller does not hold it, it may
be destroyed.
*/
static int __ip6_ins_rt(struct rt6_info *rt, struct nl_info *info)
{
int err;
struct fib6_table *table;
table = rt->rt6i_table;
write_lock_bh(&table->tb6_lock);
err = fib6_add(&table->tb6_root, rt, info);
write_unlock_bh(&table->tb6_lock);
return err;
}
int ip6_ins_rt(struct rt6_info *rt)
{
struct nl_info info = {
.nl_net = dev_net(rt->dst.dev),
};
return __ip6_ins_rt(rt, &info);
}
static struct rt6_info *rt6_alloc_cow(struct rt6_info *ort,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
struct rt6_info *rt;
/*
* Clone the route.
*/
rt = ip6_rt_copy(ort, daddr);
if (rt) {
if (!(rt->rt6i_flags & RTF_GATEWAY)) {
if (ort->rt6i_dst.plen != 128 &&
ipv6_addr_equal(&ort->rt6i_dst.addr, daddr))
rt->rt6i_flags |= RTF_ANYCAST;
}
rt->rt6i_flags |= RTF_CACHE;
#ifdef CONFIG_IPV6_SUBTREES
if (rt->rt6i_src.plen && saddr) {
rt->rt6i_src.addr = *saddr;
rt->rt6i_src.plen = 128;
}
#endif
}
return rt;
}
static struct rt6_info *rt6_alloc_clone(struct rt6_info *ort,
const struct in6_addr *daddr)
{
struct rt6_info *rt = ip6_rt_copy(ort, daddr);
if (rt)
rt->rt6i_flags |= RTF_CACHE;
return rt;
}
static struct rt6_info *ip6_pol_route(struct net *net, struct fib6_table *table, int oif,
struct flowi6 *fl6, int flags)
{
struct fib6_node *fn;
struct rt6_info *rt, *nrt;
int strict = 0;
int attempts = 3;
int err;
int reachable = net->ipv6.devconf_all->forwarding ? 0 : RT6_LOOKUP_F_REACHABLE;
strict |= flags & RT6_LOOKUP_F_IFACE;
relookup:
read_lock_bh(&table->tb6_lock);
restart_2:
fn = fib6_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
restart:
rt = rt6_select(fn, oif, strict | reachable);
if (rt->rt6i_nsiblings && oif == 0)
rt = rt6_multipath_select(rt, fl6);
BACKTRACK(net, &fl6->saddr);
if (rt == net->ipv6.ip6_null_entry ||
rt->rt6i_flags & RTF_CACHE)
goto out;
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
if (!(rt->rt6i_flags & (RTF_NONEXTHOP | RTF_GATEWAY)))
nrt = rt6_alloc_cow(rt, &fl6->daddr, &fl6->saddr);
else if (!(rt->dst.flags & DST_HOST))
nrt = rt6_alloc_clone(rt, &fl6->daddr);
else
goto out2;
ip6_rt_put(rt);
rt = nrt ? : net->ipv6.ip6_null_entry;
dst_hold(&rt->dst);
if (nrt) {
err = ip6_ins_rt(nrt);
if (!err)
goto out2;
}
if (--attempts <= 0)
goto out2;
/*
* Race condition! In the gap, when table->tb6_lock was
* released someone could insert this route. Relookup.
*/
ip6_rt_put(rt);
goto relookup;
out:
if (reachable) {
reachable = 0;
goto restart_2;
}
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
out2:
rt->dst.lastuse = jiffies;
rt->dst.__use++;
return rt;
}
static struct rt6_info *ip6_pol_route_input(struct net *net, struct fib6_table *table,
struct flowi6 *fl6, int flags)
{
return ip6_pol_route(net, table, fl6->flowi6_iif, fl6, flags);
}
static struct dst_entry *ip6_route_input_lookup(struct net *net,
struct net_device *dev,
struct flowi6 *fl6, int flags)
{
if (rt6_need_strict(&fl6->daddr) && dev->type != ARPHRD_PIMREG)
flags |= RT6_LOOKUP_F_IFACE;
return fib6_rule_lookup(net, fl6, flags, ip6_pol_route_input);
}
void ip6_route_input(struct sk_buff *skb)
{
const struct ipv6hdr *iph = ipv6_hdr(skb);
struct net *net = dev_net(skb->dev);
int flags = RT6_LOOKUP_F_HAS_SADDR;
struct flowi6 fl6 = {
.flowi6_iif = skb->dev->ifindex,
.daddr = iph->daddr,
.saddr = iph->saddr,
.flowlabel = ip6_flowinfo(iph),
.flowi6_mark = skb->mark,
.flowi6_proto = iph->nexthdr,
};
skb_dst_set(skb, ip6_route_input_lookup(net, skb->dev, &fl6, flags));
}
static struct rt6_info *ip6_pol_route_output(struct net *net, struct fib6_table *table,
struct flowi6 *fl6, int flags)
{
return ip6_pol_route(net, table, fl6->flowi6_oif, fl6, flags);
}
struct dst_entry * ip6_route_output(struct net *net, const struct sock *sk,
struct flowi6 *fl6)
{
int flags = 0;
fl6->flowi6_iif = LOOPBACK_IFINDEX;
if ((sk && sk->sk_bound_dev_if) || rt6_need_strict(&fl6->daddr))
flags |= RT6_LOOKUP_F_IFACE;
if (!ipv6_addr_any(&fl6->saddr))
flags |= RT6_LOOKUP_F_HAS_SADDR;
else if (sk)
flags |= rt6_srcprefs2flags(inet6_sk(sk)->srcprefs);
return fib6_rule_lookup(net, fl6, flags, ip6_pol_route_output);
}
EXPORT_SYMBOL(ip6_route_output);
struct dst_entry *ip6_blackhole_route(struct net *net, struct dst_entry *dst_orig)
{
struct rt6_info *rt, *ort = (struct rt6_info *) dst_orig;
struct dst_entry *new = NULL;
rt = dst_alloc(&ip6_dst_blackhole_ops, ort->dst.dev, 1, DST_OBSOLETE_NONE, 0);
if (rt) {
new = &rt->dst;
memset(new + 1, 0, sizeof(*rt) - sizeof(*new));
rt6_init_peer(rt, net->ipv6.peers);
new->__use = 1;
new->input = dst_discard;
new->output = dst_discard;
if (dst_metrics_read_only(&ort->dst))
new->_metrics = ort->dst._metrics;
else
dst_copy_metrics(new, &ort->dst);
rt->rt6i_idev = ort->rt6i_idev;
if (rt->rt6i_idev)
in6_dev_hold(rt->rt6i_idev);
rt->rt6i_gateway = ort->rt6i_gateway;
rt->rt6i_flags = ort->rt6i_flags;
rt->rt6i_metric = 0;
memcpy(&rt->rt6i_dst, &ort->rt6i_dst, sizeof(struct rt6key));
#ifdef CONFIG_IPV6_SUBTREES
memcpy(&rt->rt6i_src, &ort->rt6i_src, sizeof(struct rt6key));
#endif
dst_free(new);
}
dst_release(dst_orig);
return new ? new : ERR_PTR(-ENOMEM);
}
/*
* Destination cache support functions
*/
static struct dst_entry *ip6_dst_check(struct dst_entry *dst, u32 cookie)
{
struct rt6_info *rt;
rt = (struct rt6_info *) dst;
/* All IPV6 dsts are created with ->obsolete set to the value
* DST_OBSOLETE_FORCE_CHK which forces validation calls down
* into this function always.
*/
if (rt->rt6i_genid != rt_genid(dev_net(rt->dst.dev)))
return NULL;
if (!rt->rt6i_node || (rt->rt6i_node->fn_sernum != cookie))
return NULL;
if (rt6_check_expired(rt))
return NULL;
return dst;
}
static struct dst_entry *ip6_negative_advice(struct dst_entry *dst)
{
struct rt6_info *rt = (struct rt6_info *) dst;
if (rt) {
if (rt->rt6i_flags & RTF_CACHE) {
if (rt6_check_expired(rt)) {
ip6_del_rt(rt);
dst = NULL;
}
} else {
dst_release(dst);
dst = NULL;
}
}
return dst;
}
static void ip6_link_failure(struct sk_buff *skb)
{
struct rt6_info *rt;
icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_ADDR_UNREACH, 0);
rt = (struct rt6_info *) skb_dst(skb);
if (rt) {
if (rt->rt6i_flags & RTF_CACHE) {
dst_hold(&rt->dst);
if (ip6_del_rt(rt))
dst_free(&rt->dst);
} else if (rt->rt6i_node && (rt->rt6i_flags & RTF_DEFAULT)) {
rt->rt6i_node->fn_sernum = -1;
}
}
}
static void ip6_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu)
{
struct rt6_info *rt6 = (struct rt6_info*)dst;
dst_confirm(dst);
if (mtu < dst_mtu(dst) && rt6->rt6i_dst.plen == 128) {
struct net *net = dev_net(dst->dev);
rt6->rt6i_flags |= RTF_MODIFIED;
if (mtu < IPV6_MIN_MTU) {
u32 features = dst_metric(dst, RTAX_FEATURES);
mtu = IPV6_MIN_MTU;
features |= RTAX_FEATURE_ALLFRAG;
dst_metric_set(dst, RTAX_FEATURES, features);
}
dst_metric_set(dst, RTAX_MTU, mtu);
rt6_update_expires(rt6, net->ipv6.sysctl.ip6_rt_mtu_expires);
}
}
void ip6_update_pmtu(struct sk_buff *skb, struct net *net, __be32 mtu,
int oif, u32 mark)
{
const struct ipv6hdr *iph = (struct ipv6hdr *) skb->data;
struct dst_entry *dst;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_oif = oif;
fl6.flowi6_mark = mark ? mark : IP6_REPLY_MARK(net, skb->mark);
fl6.flowi6_flags = 0;
fl6.daddr = iph->daddr;
fl6.saddr = iph->saddr;
fl6.flowlabel = ip6_flowinfo(iph);
dst = ip6_route_output(net, NULL, &fl6);
if (!dst->error)
ip6_rt_update_pmtu(dst, NULL, skb, ntohl(mtu));
dst_release(dst);
}
EXPORT_SYMBOL_GPL(ip6_update_pmtu);
void ip6_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, __be32 mtu)
{
ip6_update_pmtu(skb, sock_net(sk), mtu,
sk->sk_bound_dev_if, sk->sk_mark);
}
EXPORT_SYMBOL_GPL(ip6_sk_update_pmtu);
void ip6_redirect(struct sk_buff *skb, struct net *net, int oif, u32 mark)
{
const struct ipv6hdr *iph = (struct ipv6hdr *) skb->data;
struct dst_entry *dst;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_oif = oif;
fl6.flowi6_mark = mark;
fl6.flowi6_flags = 0;
fl6.daddr = iph->daddr;
fl6.saddr = iph->saddr;
fl6.flowlabel = ip6_flowinfo(iph);
dst = ip6_route_output(net, NULL, &fl6);
if (!dst->error)
rt6_do_redirect(dst, NULL, skb);
dst_release(dst);
}
EXPORT_SYMBOL_GPL(ip6_redirect);
void ip6_sk_redirect(struct sk_buff *skb, struct sock *sk)
{
ip6_redirect(skb, sock_net(sk), sk->sk_bound_dev_if, sk->sk_mark);
}
EXPORT_SYMBOL_GPL(ip6_sk_redirect);
static unsigned int ip6_default_advmss(const struct dst_entry *dst)
{
struct net_device *dev = dst->dev;
unsigned int mtu = dst_mtu(dst);
struct net *net = dev_net(dev);
mtu -= sizeof(struct ipv6hdr) + sizeof(struct tcphdr);
if (mtu < net->ipv6.sysctl.ip6_rt_min_advmss)
mtu = net->ipv6.sysctl.ip6_rt_min_advmss;
/*
* Maximal non-jumbo IPv6 payload is IPV6_MAXPLEN and
* corresponding MSS is IPV6_MAXPLEN - tcp_header_size.
* IPV6_MAXPLEN is also valid and means: "any MSS,
* rely only on pmtu discovery"
*/
if (mtu > IPV6_MAXPLEN - sizeof(struct tcphdr))
mtu = IPV6_MAXPLEN;
return mtu;
}
static unsigned int ip6_mtu(const struct dst_entry *dst)
{
struct inet6_dev *idev;
unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
if (mtu)
return mtu;
mtu = IPV6_MIN_MTU;
rcu_read_lock();
idev = __in6_dev_get(dst->dev);
if (idev)
mtu = idev->cnf.mtu6;
rcu_read_unlock();
return mtu;
}
static struct dst_entry *icmp6_dst_gc_list;
static DEFINE_SPINLOCK(icmp6_dst_lock);
struct dst_entry *icmp6_dst_alloc(struct net_device *dev,
struct flowi6 *fl6)
{
struct dst_entry *dst;
struct rt6_info *rt;
struct inet6_dev *idev = in6_dev_get(dev);
struct net *net = dev_net(dev);
if (unlikely(!idev))
return ERR_PTR(-ENODEV);
rt = ip6_dst_alloc(net, dev, 0, NULL);
if (unlikely(!rt)) {
in6_dev_put(idev);
dst = ERR_PTR(-ENOMEM);
goto out;
}
rt->dst.flags |= DST_HOST;
rt->dst.output = ip6_output;
atomic_set(&rt->dst.__refcnt, 1);
rt->rt6i_gateway = fl6->daddr;
rt->rt6i_dst.addr = fl6->daddr;
rt->rt6i_dst.plen = 128;
rt->rt6i_idev = idev;
dst_metric_set(&rt->dst, RTAX_HOPLIMIT, 0);
spin_lock_bh(&icmp6_dst_lock);
rt->dst.next = icmp6_dst_gc_list;
icmp6_dst_gc_list = &rt->dst;
spin_unlock_bh(&icmp6_dst_lock);
fib6_force_start_gc(net);
dst = xfrm_lookup(net, &rt->dst, flowi6_to_flowi(fl6), NULL, 0);
out:
return dst;
}
int icmp6_dst_gc(void)
{
struct dst_entry *dst, **pprev;
int more = 0;
spin_lock_bh(&icmp6_dst_lock);
pprev = &icmp6_dst_gc_list;
while ((dst = *pprev) != NULL) {
if (!atomic_read(&dst->__refcnt)) {
*pprev = dst->next;
dst_free(dst);
} else {
pprev = &dst->next;
++more;
}
}
spin_unlock_bh(&icmp6_dst_lock);
return more;
}
static void icmp6_clean_all(int (*func)(struct rt6_info *rt, void *arg),
void *arg)
{
struct dst_entry *dst, **pprev;
spin_lock_bh(&icmp6_dst_lock);
pprev = &icmp6_dst_gc_list;
while ((dst = *pprev) != NULL) {
struct rt6_info *rt = (struct rt6_info *) dst;
if (func(rt, arg)) {
*pprev = dst->next;
dst_free(dst);
} else {
pprev = &dst->next;
}
}
spin_unlock_bh(&icmp6_dst_lock);
}
static int ip6_dst_gc(struct dst_ops *ops)
{
unsigned long now = jiffies;
struct net *net = container_of(ops, struct net, ipv6.ip6_dst_ops);
int rt_min_interval = net->ipv6.sysctl.ip6_rt_gc_min_interval;
int rt_max_size = net->ipv6.sysctl.ip6_rt_max_size;
int rt_elasticity = net->ipv6.sysctl.ip6_rt_gc_elasticity;
int rt_gc_timeout = net->ipv6.sysctl.ip6_rt_gc_timeout;
unsigned long rt_last_gc = net->ipv6.ip6_rt_last_gc;
int entries;
entries = dst_entries_get_fast(ops);
if (time_after(rt_last_gc + rt_min_interval, now) &&
entries <= rt_max_size)
goto out;
net->ipv6.ip6_rt_gc_expire++;
fib6_run_gc(net->ipv6.ip6_rt_gc_expire, net);
net->ipv6.ip6_rt_last_gc = now;
entries = dst_entries_get_slow(ops);
if (entries < ops->gc_thresh)
net->ipv6.ip6_rt_gc_expire = rt_gc_timeout>>1;
out:
net->ipv6.ip6_rt_gc_expire -= net->ipv6.ip6_rt_gc_expire>>rt_elasticity;
return entries > rt_max_size;
}
int ip6_dst_hoplimit(struct dst_entry *dst)
{
int hoplimit = dst_metric_raw(dst, RTAX_HOPLIMIT);
if (hoplimit == 0) {
struct net_device *dev = dst->dev;
struct inet6_dev *idev;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev)
hoplimit = idev->cnf.hop_limit;
else
hoplimit = dev_net(dev)->ipv6.devconf_all->hop_limit;
rcu_read_unlock();
}
return hoplimit;
}
EXPORT_SYMBOL(ip6_dst_hoplimit);
/*
*
*/
int ip6_route_add(struct fib6_config *cfg)
{
int err;
struct net *net = cfg->fc_nlinfo.nl_net;
struct rt6_info *rt = NULL;
struct net_device *dev = NULL;
struct inet6_dev *idev = NULL;
struct fib6_table *table;
int addr_type;
if (cfg->fc_dst_len > 128 || cfg->fc_src_len > 128)
return -EINVAL;
#ifndef CONFIG_IPV6_SUBTREES
if (cfg->fc_src_len)
return -EINVAL;
#endif
if (cfg->fc_ifindex) {
err = -ENODEV;
dev = dev_get_by_index(net, cfg->fc_ifindex);
if (!dev)
goto out;
idev = in6_dev_get(dev);
if (!idev)
goto out;
}
if (cfg->fc_metric == 0)
cfg->fc_metric = IP6_RT_PRIO_USER;
err = -ENOBUFS;
if (cfg->fc_nlinfo.nlh &&
!(cfg->fc_nlinfo.nlh->nlmsg_flags & NLM_F_CREATE)) {
table = fib6_get_table(net, cfg->fc_table);
if (!table) {
pr_warn("NLM_F_CREATE should be specified when creating new route\n");
table = fib6_new_table(net, cfg->fc_table);
}
} else {
table = fib6_new_table(net, cfg->fc_table);
}
if (!table)
goto out;
rt = ip6_dst_alloc(net, NULL, (cfg->fc_flags & RTF_ADDRCONF) ? 0 : DST_NOCOUNT, table);
if (!rt) {
err = -ENOMEM;
goto out;
}
if (cfg->fc_flags & RTF_EXPIRES)
rt6_set_expires(rt, jiffies +
clock_t_to_jiffies(cfg->fc_expires));
else
rt6_clean_expires(rt);
if (cfg->fc_protocol == RTPROT_UNSPEC)
cfg->fc_protocol = RTPROT_BOOT;
rt->rt6i_protocol = cfg->fc_protocol;
addr_type = ipv6_addr_type(&cfg->fc_dst);
if (addr_type & IPV6_ADDR_MULTICAST)
rt->dst.input = ip6_mc_input;
else if (cfg->fc_flags & RTF_LOCAL)
rt->dst.input = ip6_input;
else
rt->dst.input = ip6_forward;
rt->dst.output = ip6_output;
ipv6_addr_prefix(&rt->rt6i_dst.addr, &cfg->fc_dst, cfg->fc_dst_len);
rt->rt6i_dst.plen = cfg->fc_dst_len;
if (rt->rt6i_dst.plen == 128)
rt->dst.flags |= DST_HOST;
if (!(rt->dst.flags & DST_HOST) && cfg->fc_mx) {
u32 *metrics = kzalloc(sizeof(u32) * RTAX_MAX, GFP_KERNEL);
if (!metrics) {
err = -ENOMEM;
goto out;
}
dst_init_metrics(&rt->dst, metrics, 0);
}
#ifdef CONFIG_IPV6_SUBTREES
ipv6_addr_prefix(&rt->rt6i_src.addr, &cfg->fc_src, cfg->fc_src_len);
rt->rt6i_src.plen = cfg->fc_src_len;
#endif
rt->rt6i_metric = cfg->fc_metric;
/* We cannot add true routes via loopback here,
they would result in kernel looping; promote them to reject routes
*/
if ((cfg->fc_flags & RTF_REJECT) ||
(dev && (dev->flags & IFF_LOOPBACK) &&
!(addr_type & IPV6_ADDR_LOOPBACK) &&
!(cfg->fc_flags & RTF_LOCAL))) {
/* hold loopback dev/idev if we haven't done so. */
if (dev != net->loopback_dev) {
if (dev) {
dev_put(dev);
in6_dev_put(idev);
}
dev = net->loopback_dev;
dev_hold(dev);
idev = in6_dev_get(dev);
if (!idev) {
err = -ENODEV;
goto out;
}
}
rt->rt6i_flags = RTF_REJECT|RTF_NONEXTHOP;
switch (cfg->fc_type) {
case RTN_BLACKHOLE:
rt->dst.error = -EINVAL;
rt->dst.output = dst_discard;
rt->dst.input = dst_discard;
break;
case RTN_PROHIBIT:
rt->dst.error = -EACCES;
rt->dst.output = ip6_pkt_prohibit_out;
rt->dst.input = ip6_pkt_prohibit;
break;
case RTN_THROW:
default:
rt->dst.error = (cfg->fc_type == RTN_THROW) ? -EAGAIN
: -ENETUNREACH;
rt->dst.output = ip6_pkt_discard_out;
rt->dst.input = ip6_pkt_discard;
break;
}
goto install_route;
}
if (cfg->fc_flags & RTF_GATEWAY) {
const struct in6_addr *gw_addr;
int gwa_type;
gw_addr = &cfg->fc_gateway;
rt->rt6i_gateway = *gw_addr;
gwa_type = ipv6_addr_type(gw_addr);
if (gwa_type != (IPV6_ADDR_LINKLOCAL|IPV6_ADDR_UNICAST)) {
struct rt6_info *grt;
/* IPv6 strictly inhibits using not link-local
addresses as nexthop address.
Otherwise, router will not able to send redirects.
It is very good, but in some (rare!) circumstances
(SIT, PtP, NBMA NOARP links) it is handy to allow
some exceptions. --ANK
*/
err = -EINVAL;
if (!(gwa_type & IPV6_ADDR_UNICAST))
goto out;
grt = rt6_lookup(net, gw_addr, NULL, cfg->fc_ifindex, 1);
err = -EHOSTUNREACH;
if (!grt)
goto out;
if (dev) {
if (dev != grt->dst.dev) {
ip6_rt_put(grt);
goto out;
}
} else {
dev = grt->dst.dev;
idev = grt->rt6i_idev;
dev_hold(dev);
in6_dev_hold(grt->rt6i_idev);
}
if (!(grt->rt6i_flags & RTF_GATEWAY))
err = 0;
ip6_rt_put(grt);
if (err)
goto out;
}
err = -EINVAL;
if (!dev || (dev->flags & IFF_LOOPBACK))
goto out;
}
err = -ENODEV;
if (!dev)
goto out;
if (!ipv6_addr_any(&cfg->fc_prefsrc)) {
if (!ipv6_chk_addr(net, &cfg->fc_prefsrc, dev, 0)) {
err = -EINVAL;
goto out;
}
rt->rt6i_prefsrc.addr = cfg->fc_prefsrc;
rt->rt6i_prefsrc.plen = 128;
} else
rt->rt6i_prefsrc.plen = 0;
rt->rt6i_flags = cfg->fc_flags;
install_route:
if (cfg->fc_mx) {
struct nlattr *nla;
int remaining;
nla_for_each_attr(nla, cfg->fc_mx, cfg->fc_mx_len, remaining) {
int type = nla_type(nla);
if (type) {
if (type > RTAX_MAX) {
err = -EINVAL;
goto out;
}
dst_metric_set(&rt->dst, type, nla_get_u32(nla));
}
}
}
rt->dst.dev = dev;
rt->rt6i_idev = idev;
rt->rt6i_table = table;
cfg->fc_nlinfo.nl_net = dev_net(dev);
return __ip6_ins_rt(rt, &cfg->fc_nlinfo);
out:
if (dev)
dev_put(dev);
if (idev)
in6_dev_put(idev);
if (rt)
dst_free(&rt->dst);
return err;
}
static int __ip6_del_rt(struct rt6_info *rt, struct nl_info *info)
{
int err;
struct fib6_table *table;
struct net *net = dev_net(rt->dst.dev);
if (rt == net->ipv6.ip6_null_entry) {
err = -ENOENT;
goto out;
}
table = rt->rt6i_table;
write_lock_bh(&table->tb6_lock);
err = fib6_del(rt, info);
write_unlock_bh(&table->tb6_lock);
out:
ip6_rt_put(rt);
return err;
}
int ip6_del_rt(struct rt6_info *rt)
{
struct nl_info info = {
.nl_net = dev_net(rt->dst.dev),
};
return __ip6_del_rt(rt, &info);
}
static int ip6_route_del(struct fib6_config *cfg)
{
struct fib6_table *table;
struct fib6_node *fn;
struct rt6_info *rt;
int err = -ESRCH;
table = fib6_get_table(cfg->fc_nlinfo.nl_net, cfg->fc_table);
if (!table)
return err;
read_lock_bh(&table->tb6_lock);
fn = fib6_locate(&table->tb6_root,
&cfg->fc_dst, cfg->fc_dst_len,
&cfg->fc_src, cfg->fc_src_len);
if (fn) {
for (rt = fn->leaf; rt; rt = rt->dst.rt6_next) {
if (cfg->fc_ifindex &&
(!rt->dst.dev ||
rt->dst.dev->ifindex != cfg->fc_ifindex))
continue;
if (cfg->fc_flags & RTF_GATEWAY &&
!ipv6_addr_equal(&cfg->fc_gateway, &rt->rt6i_gateway))
continue;
if (cfg->fc_metric && cfg->fc_metric != rt->rt6i_metric)
continue;
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
return __ip6_del_rt(rt, &cfg->fc_nlinfo);
}
}
read_unlock_bh(&table->tb6_lock);
return err;
}
static void rt6_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
struct netevent_redirect netevent;
struct rt6_info *rt, *nrt = NULL;
struct ndisc_options ndopts;
struct inet6_dev *in6_dev;
struct neighbour *neigh;
struct rd_msg *msg;
int optlen, on_link;
u8 *lladdr;
optlen = skb->tail - skb->transport_header;
optlen -= sizeof(*msg);
if (optlen < 0) {
net_dbg_ratelimited("rt6_do_redirect: packet too short\n");
return;
}
msg = (struct rd_msg *)icmp6_hdr(skb);
if (ipv6_addr_is_multicast(&msg->dest)) {
net_dbg_ratelimited("rt6_do_redirect: destination address is multicast\n");
return;
}
on_link = 0;
if (ipv6_addr_equal(&msg->dest, &msg->target)) {
on_link = 1;
} else if (ipv6_addr_type(&msg->target) !=
(IPV6_ADDR_UNICAST|IPV6_ADDR_LINKLOCAL)) {
net_dbg_ratelimited("rt6_do_redirect: target address is not link-local unicast\n");
return;
}
in6_dev = __in6_dev_get(skb->dev);
if (!in6_dev)
return;
if (in6_dev->cnf.forwarding || !in6_dev->cnf.accept_redirects)
return;
/* RFC2461 8.1:
* The IP source address of the Redirect MUST be the same as the current
* first-hop router for the specified ICMP Destination Address.
*/
if (!ndisc_parse_options(msg->opt, optlen, &ndopts)) {
net_dbg_ratelimited("rt6_redirect: invalid ND options\n");
return;
}
lladdr = NULL;
if (ndopts.nd_opts_tgt_lladdr) {
lladdr = ndisc_opt_addr_data(ndopts.nd_opts_tgt_lladdr,
skb->dev);
if (!lladdr) {
net_dbg_ratelimited("rt6_redirect: invalid link-layer address length\n");
return;
}
}
rt = (struct rt6_info *) dst;
if (rt == net->ipv6.ip6_null_entry) {
net_dbg_ratelimited("rt6_redirect: source isn't a valid nexthop for redirect target\n");
return;
}
/* Redirect received -> path was valid.
* Look, redirects are sent only in response to data packets,
* so that this nexthop apparently is reachable. --ANK
*/
dst_confirm(&rt->dst);
neigh = __neigh_lookup(&nd_tbl, &msg->target, skb->dev, 1);
if (!neigh)
return;
/*
* We have finally decided to accept it.
*/
neigh_update(neigh, lladdr, NUD_STALE,
NEIGH_UPDATE_F_WEAK_OVERRIDE|
NEIGH_UPDATE_F_OVERRIDE|
(on_link ? 0 : (NEIGH_UPDATE_F_OVERRIDE_ISROUTER|
NEIGH_UPDATE_F_ISROUTER))
);
nrt = ip6_rt_copy(rt, &msg->dest);
if (!nrt)
goto out;
nrt->rt6i_flags = RTF_GATEWAY|RTF_UP|RTF_DYNAMIC|RTF_CACHE;
if (on_link)
nrt->rt6i_flags &= ~RTF_GATEWAY;
nrt->rt6i_gateway = *(struct in6_addr *)neigh->primary_key;
if (ip6_ins_rt(nrt))
goto out;
netevent.old = &rt->dst;
netevent.new = &nrt->dst;
netevent.daddr = &msg->dest;
netevent.neigh = neigh;
call_netevent_notifiers(NETEVENT_REDIRECT, &netevent);
if (rt->rt6i_flags & RTF_CACHE) {
rt = (struct rt6_info *) dst_clone(&rt->dst);
ip6_del_rt(rt);
}
out:
neigh_release(neigh);
}
/*
* Misc support functions
*/
static struct rt6_info *ip6_rt_copy(struct rt6_info *ort,
const struct in6_addr *dest)
{
struct net *net = dev_net(ort->dst.dev);
struct rt6_info *rt = ip6_dst_alloc(net, ort->dst.dev, 0,
ort->rt6i_table);
if (rt) {
rt->dst.input = ort->dst.input;
rt->dst.output = ort->dst.output;
rt->dst.flags |= DST_HOST;
rt->rt6i_dst.addr = *dest;
rt->rt6i_dst.plen = 128;
dst_copy_metrics(&rt->dst, &ort->dst);
rt->dst.error = ort->dst.error;
rt->rt6i_idev = ort->rt6i_idev;
if (rt->rt6i_idev)
in6_dev_hold(rt->rt6i_idev);
rt->dst.lastuse = jiffies;
if (ort->rt6i_flags & RTF_GATEWAY)
rt->rt6i_gateway = ort->rt6i_gateway;
else
rt->rt6i_gateway = *dest;
rt->rt6i_flags = ort->rt6i_flags;
rt6_set_from(rt, ort);
rt->rt6i_metric = 0;
#ifdef CONFIG_IPV6_SUBTREES
memcpy(&rt->rt6i_src, &ort->rt6i_src, sizeof(struct rt6key));
#endif
memcpy(&rt->rt6i_prefsrc, &ort->rt6i_prefsrc, sizeof(struct rt6key));
rt->rt6i_table = ort->rt6i_table;
}
return rt;
}
#ifdef CONFIG_IPV6_ROUTE_INFO
static struct rt6_info *rt6_get_route_info(struct net_device *dev,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr)
{
struct fib6_node *fn;
struct rt6_info *rt = NULL;
struct fib6_table *table;
table = fib6_get_table(dev_net(dev),
addrconf_rt_table(dev, RT6_TABLE_INFO));
if (!table)
return NULL;
read_lock_bh(&table->tb6_lock);
fn = fib6_locate(&table->tb6_root, prefix ,prefixlen, NULL, 0);
if (!fn)
goto out;
for (rt = fn->leaf; rt; rt = rt->dst.rt6_next) {
if (rt->dst.dev->ifindex != dev->ifindex)
continue;
if ((rt->rt6i_flags & (RTF_ROUTEINFO|RTF_GATEWAY)) != (RTF_ROUTEINFO|RTF_GATEWAY))
continue;
if (!ipv6_addr_equal(&rt->rt6i_gateway, gwaddr))
continue;
dst_hold(&rt->dst);
break;
}
out:
read_unlock_bh(&table->tb6_lock);
return rt;
}
static struct rt6_info *rt6_add_route_info(struct net_device *dev,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr, unsigned int pref)
{
struct fib6_config cfg = {
.fc_table = addrconf_rt_table(dev, RT6_TABLE_INFO),
.fc_metric = IP6_RT_PRIO_USER,
.fc_ifindex = dev->ifindex,
.fc_dst_len = prefixlen,
.fc_flags = RTF_GATEWAY | RTF_ADDRCONF | RTF_ROUTEINFO |
RTF_UP | RTF_PREF(pref),
.fc_nlinfo.portid = 0,
.fc_nlinfo.nlh = NULL,
.fc_nlinfo.nl_net = dev_net(dev),
};
cfg.fc_dst = *prefix;
cfg.fc_gateway = *gwaddr;
/* We should treat it as a default route if prefix length is 0. */
if (!prefixlen)
cfg.fc_flags |= RTF_DEFAULT;
ip6_route_add(&cfg);
return rt6_get_route_info(dev, prefix, prefixlen, gwaddr);
}
#endif
struct rt6_info *rt6_get_dflt_router(const struct in6_addr *addr, struct net_device *dev)
{
struct rt6_info *rt;
struct fib6_table *table;
table = fib6_get_table(dev_net(dev),
addrconf_rt_table(dev, RT6_TABLE_MAIN));
if (!table)
return NULL;
read_lock_bh(&table->tb6_lock);
for (rt = table->tb6_root.leaf; rt; rt=rt->dst.rt6_next) {
if (dev == rt->dst.dev &&
((rt->rt6i_flags & (RTF_ADDRCONF | RTF_DEFAULT)) == (RTF_ADDRCONF | RTF_DEFAULT)) &&
ipv6_addr_equal(&rt->rt6i_gateway, addr))
break;
}
if (rt)
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
return rt;
}
struct rt6_info *rt6_add_dflt_router(const struct in6_addr *gwaddr,
struct net_device *dev,
unsigned int pref)
{
struct fib6_config cfg = {
.fc_table = addrconf_rt_table(dev, RT6_TABLE_DFLT),
.fc_metric = IP6_RT_PRIO_USER,
.fc_ifindex = dev->ifindex,
.fc_flags = RTF_GATEWAY | RTF_ADDRCONF | RTF_DEFAULT |
RTF_UP | RTF_EXPIRES | RTF_PREF(pref),
.fc_nlinfo.portid = 0,
.fc_nlinfo.nlh = NULL,
.fc_nlinfo.nl_net = dev_net(dev),
};
cfg.fc_gateway = *gwaddr;
ip6_route_add(&cfg);
return rt6_get_dflt_router(gwaddr, dev);
}
int rt6_addrconf_purge(struct rt6_info *rt, void *arg) {
if (rt->rt6i_flags & (RTF_DEFAULT | RTF_ADDRCONF) &&
(!rt->rt6i_idev || rt->rt6i_idev->cnf.accept_ra != 2))
return -1;
return 0;
}
void rt6_purge_dflt_routers(struct net *net)
{
fib6_clean_all(net, rt6_addrconf_purge, 0, NULL);
}
static void rtmsg_to_fib6_config(struct net *net,
struct in6_rtmsg *rtmsg,
struct fib6_config *cfg)
{
memset(cfg, 0, sizeof(*cfg));
cfg->fc_table = RT6_TABLE_MAIN;
cfg->fc_ifindex = rtmsg->rtmsg_ifindex;
cfg->fc_metric = rtmsg->rtmsg_metric;
cfg->fc_expires = rtmsg->rtmsg_info;
cfg->fc_dst_len = rtmsg->rtmsg_dst_len;
cfg->fc_src_len = rtmsg->rtmsg_src_len;
cfg->fc_flags = rtmsg->rtmsg_flags;
cfg->fc_nlinfo.nl_net = net;
cfg->fc_dst = rtmsg->rtmsg_dst;
cfg->fc_src = rtmsg->rtmsg_src;
cfg->fc_gateway = rtmsg->rtmsg_gateway;
}
int ipv6_route_ioctl(struct net *net, unsigned int cmd, void __user *arg)
{
struct fib6_config cfg;
struct in6_rtmsg rtmsg;
int err;
switch(cmd) {
case SIOCADDRT: /* Add a route */
case SIOCDELRT: /* Delete a route */
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
err = copy_from_user(&rtmsg, arg,
sizeof(struct in6_rtmsg));
if (err)
return -EFAULT;
rtmsg_to_fib6_config(net, &rtmsg, &cfg);
rtnl_lock();
switch (cmd) {
case SIOCADDRT:
err = ip6_route_add(&cfg);
break;
case SIOCDELRT:
err = ip6_route_del(&cfg);
break;
default:
err = -EINVAL;
}
rtnl_unlock();
return err;
}
return -EINVAL;
}
/*
* Drop the packet on the floor
*/
static int ip6_pkt_drop(struct sk_buff *skb, u8 code, int ipstats_mib_noroutes)
{
int type;
struct dst_entry *dst = skb_dst(skb);
switch (ipstats_mib_noroutes) {
case IPSTATS_MIB_INNOROUTES:
type = ipv6_addr_type(&ipv6_hdr(skb)->daddr);
if (type == IPV6_ADDR_ANY) {
IP6_INC_STATS(dev_net(dst->dev), ip6_dst_idev(dst),
IPSTATS_MIB_INADDRERRORS);
break;
}
/* FALLTHROUGH */
case IPSTATS_MIB_OUTNOROUTES:
IP6_INC_STATS(dev_net(dst->dev), ip6_dst_idev(dst),
ipstats_mib_noroutes);
break;
}
icmpv6_send(skb, ICMPV6_DEST_UNREACH, code, 0);
kfree_skb(skb);
return 0;
}
static int ip6_pkt_discard(struct sk_buff *skb)
{
return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_INNOROUTES);
}
static int ip6_pkt_discard_out(struct sk_buff *skb)
{
skb->dev = skb_dst(skb)->dev;
return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_OUTNOROUTES);
}
static int ip6_pkt_prohibit(struct sk_buff *skb)
{
return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_INNOROUTES);
}
static int ip6_pkt_prohibit_out(struct sk_buff *skb)
{
skb->dev = skb_dst(skb)->dev;
return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_OUTNOROUTES);
}
/*
* Allocate a dst for local (unicast / anycast) address.
*/
struct rt6_info *addrconf_dst_alloc(struct inet6_dev *idev,
const struct in6_addr *addr,
bool anycast)
{
struct net *net = dev_net(idev->dev);
struct rt6_info *rt = ip6_dst_alloc(net, net->loopback_dev,
DST_NOCOUNT, NULL);
if (!rt)
return ERR_PTR(-ENOMEM);
in6_dev_hold(idev);
rt->dst.flags |= DST_HOST;
rt->dst.input = ip6_input;
rt->dst.output = ip6_output;
rt->rt6i_idev = idev;
rt->rt6i_flags = RTF_UP | RTF_NONEXTHOP;
if (anycast)
rt->rt6i_flags |= RTF_ANYCAST;
else
rt->rt6i_flags |= RTF_LOCAL;
rt->rt6i_gateway = *addr;
rt->rt6i_dst.addr = *addr;
rt->rt6i_dst.plen = 128;
rt->rt6i_table = fib6_get_table(net, RT6_TABLE_LOCAL);
atomic_set(&rt->dst.__refcnt, 1);
return rt;
}
int ip6_route_get_saddr(struct net *net,
struct rt6_info *rt,
const struct in6_addr *daddr,
unsigned int prefs,
struct in6_addr *saddr)
{
struct inet6_dev *idev = ip6_dst_idev((struct dst_entry*)rt);
int err = 0;
if (rt->rt6i_prefsrc.plen)
*saddr = rt->rt6i_prefsrc.addr;
else
err = ipv6_dev_get_saddr(net, idev ? idev->dev : NULL,
daddr, prefs, saddr);
return err;
}
/* remove deleted ip from prefsrc entries */
struct arg_dev_net_ip {
struct net_device *dev;
struct net *net;
struct in6_addr *addr;
};
static int fib6_remove_prefsrc(struct rt6_info *rt, void *arg)
{
struct net_device *dev = ((struct arg_dev_net_ip *)arg)->dev;
struct net *net = ((struct arg_dev_net_ip *)arg)->net;
struct in6_addr *addr = ((struct arg_dev_net_ip *)arg)->addr;
if (((void *)rt->dst.dev == dev || !dev) &&
rt != net->ipv6.ip6_null_entry &&
ipv6_addr_equal(addr, &rt->rt6i_prefsrc.addr)) {
/* remove prefsrc entry */
rt->rt6i_prefsrc.plen = 0;
}
return 0;
}
void rt6_remove_prefsrc(struct inet6_ifaddr *ifp)
{
struct net *net = dev_net(ifp->idev->dev);
struct arg_dev_net_ip adni = {
.dev = ifp->idev->dev,
.net = net,
.addr = &ifp->addr,
};
fib6_clean_all(net, fib6_remove_prefsrc, 0, &adni);
}
struct arg_dev_net {
struct net_device *dev;
struct net *net;
};
static int fib6_ifdown(struct rt6_info *rt, void *arg)
{
const struct arg_dev_net *adn = arg;
const struct net_device *dev = adn->dev;
if ((rt->dst.dev == dev || !dev) &&
rt != adn->net->ipv6.ip6_null_entry)
return -1;
return 0;
}
void rt6_ifdown(struct net *net, struct net_device *dev)
{
struct arg_dev_net adn = {
.dev = dev,
.net = net,
};
fib6_clean_all(net, fib6_ifdown, 0, &adn);
icmp6_clean_all(fib6_ifdown, &adn);
}
struct rt6_mtu_change_arg {
struct net_device *dev;
unsigned int mtu;
};
static int rt6_mtu_change_route(struct rt6_info *rt, void *p_arg)
{
struct rt6_mtu_change_arg *arg = (struct rt6_mtu_change_arg *) p_arg;
struct inet6_dev *idev;
/* In IPv6 pmtu discovery is not optional,
so that RTAX_MTU lock cannot disable it.
We still use this lock to block changes
caused by addrconf/ndisc.
*/
idev = __in6_dev_get(arg->dev);
if (!idev)
return 0;
/* For administrative MTU increase, there is no way to discover
IPv6 PMTU increase, so PMTU increase should be updated here.
Since RFC 1981 doesn't include administrative MTU increase
update PMTU increase is a MUST. (i.e. jumbo frame)
*/
/*
If new MTU is less than route PMTU, this new MTU will be the
lowest MTU in the path, update the route PMTU to reflect PMTU
decreases; if new MTU is greater than route PMTU, and the
old MTU is the lowest MTU in the path, update the route PMTU
to reflect the increase. In this case if the other nodes' MTU
also have the lowest MTU, TOO BIG MESSAGE will be lead to
PMTU discouvery.
*/
if (rt->dst.dev == arg->dev &&
!dst_metric_locked(&rt->dst, RTAX_MTU) &&
(dst_mtu(&rt->dst) >= arg->mtu ||
(dst_mtu(&rt->dst) < arg->mtu &&
dst_mtu(&rt->dst) == idev->cnf.mtu6))) {
dst_metric_set(&rt->dst, RTAX_MTU, arg->mtu);
}
return 0;
}
void rt6_mtu_change(struct net_device *dev, unsigned int mtu)
{
struct rt6_mtu_change_arg arg = {
.dev = dev,
.mtu = mtu,
};
fib6_clean_all(dev_net(dev), rt6_mtu_change_route, 0, &arg);
}
static const struct nla_policy rtm_ipv6_policy[RTA_MAX+1] = {
[RTA_GATEWAY] = { .len = sizeof(struct in6_addr) },
[RTA_OIF] = { .type = NLA_U32 },
[RTA_IIF] = { .type = NLA_U32 },
[RTA_PRIORITY] = { .type = NLA_U32 },
[RTA_METRICS] = { .type = NLA_NESTED },
[RTA_MULTIPATH] = { .len = sizeof(struct rtnexthop) },
};
static int rtm_to_fib6_config(struct sk_buff *skb, struct nlmsghdr *nlh,
struct fib6_config *cfg)
{
struct rtmsg *rtm;
struct nlattr *tb[RTA_MAX+1];
int err;
err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv6_policy);
if (err < 0)
goto errout;
err = -EINVAL;
rtm = nlmsg_data(nlh);
memset(cfg, 0, sizeof(*cfg));
cfg->fc_table = rtm->rtm_table;
cfg->fc_dst_len = rtm->rtm_dst_len;
cfg->fc_src_len = rtm->rtm_src_len;
cfg->fc_flags = RTF_UP;
cfg->fc_protocol = rtm->rtm_protocol;
cfg->fc_type = rtm->rtm_type;
if (rtm->rtm_type == RTN_UNREACHABLE ||
rtm->rtm_type == RTN_BLACKHOLE ||
rtm->rtm_type == RTN_PROHIBIT ||
rtm->rtm_type == RTN_THROW)
cfg->fc_flags |= RTF_REJECT;
if (rtm->rtm_type == RTN_LOCAL)
cfg->fc_flags |= RTF_LOCAL;
cfg->fc_nlinfo.portid = NETLINK_CB(skb).portid;
cfg->fc_nlinfo.nlh = nlh;
cfg->fc_nlinfo.nl_net = sock_net(skb->sk);
if (tb[RTA_GATEWAY]) {
nla_memcpy(&cfg->fc_gateway, tb[RTA_GATEWAY], 16);
cfg->fc_flags |= RTF_GATEWAY;
}
if (tb[RTA_DST]) {
int plen = (rtm->rtm_dst_len + 7) >> 3;
if (nla_len(tb[RTA_DST]) < plen)
goto errout;
nla_memcpy(&cfg->fc_dst, tb[RTA_DST], plen);
}
if (tb[RTA_SRC]) {
int plen = (rtm->rtm_src_len + 7) >> 3;
if (nla_len(tb[RTA_SRC]) < plen)
goto errout;
nla_memcpy(&cfg->fc_src, tb[RTA_SRC], plen);
}
if (tb[RTA_PREFSRC])
nla_memcpy(&cfg->fc_prefsrc, tb[RTA_PREFSRC], 16);
if (tb[RTA_OIF])
cfg->fc_ifindex = nla_get_u32(tb[RTA_OIF]);
if (tb[RTA_PRIORITY])
cfg->fc_metric = nla_get_u32(tb[RTA_PRIORITY]);
if (tb[RTA_METRICS]) {
cfg->fc_mx = nla_data(tb[RTA_METRICS]);
cfg->fc_mx_len = nla_len(tb[RTA_METRICS]);
}
if (tb[RTA_TABLE])
cfg->fc_table = nla_get_u32(tb[RTA_TABLE]);
if (tb[RTA_MULTIPATH]) {
cfg->fc_mp = nla_data(tb[RTA_MULTIPATH]);
cfg->fc_mp_len = nla_len(tb[RTA_MULTIPATH]);
}
err = 0;
errout:
return err;
}
static int ip6_route_multipath(struct fib6_config *cfg, int add)
{
struct fib6_config r_cfg;
struct rtnexthop *rtnh;
int remaining;
int attrlen;
int err = 0, last_err = 0;
beginning:
rtnh = (struct rtnexthop *)cfg->fc_mp;
remaining = cfg->fc_mp_len;
/* Parse a Multipath Entry */
while (rtnh_ok(rtnh, remaining)) {
memcpy(&r_cfg, cfg, sizeof(*cfg));
if (rtnh->rtnh_ifindex)
r_cfg.fc_ifindex = rtnh->rtnh_ifindex;
attrlen = rtnh_attrlen(rtnh);
if (attrlen > 0) {
struct nlattr *nla, *attrs = rtnh_attrs(rtnh);
nla = nla_find(attrs, attrlen, RTA_GATEWAY);
if (nla) {
nla_memcpy(&r_cfg.fc_gateway, nla, 16);
r_cfg.fc_flags |= RTF_GATEWAY;
}
}
err = add ? ip6_route_add(&r_cfg) : ip6_route_del(&r_cfg);
if (err) {
last_err = err;
/* If we are trying to remove a route, do not stop the
* loop when ip6_route_del() fails (because next hop is
* already gone), we should try to remove all next hops.
*/
if (add) {
/* If add fails, we should try to delete all
* next hops that have been already added.
*/
add = 0;
goto beginning;
}
}
/* Because each route is added like a single route we remove
* this flag after the first nexthop (if there is a collision,
* we have already fail to add the first nexthop:
* fib6_add_rt2node() has reject it).
*/
cfg->fc_nlinfo.nlh->nlmsg_flags &= ~NLM_F_EXCL;
rtnh = rtnh_next(rtnh, &remaining);
}
return last_err;
}
static int inet6_rtm_delroute(struct sk_buff *skb, struct nlmsghdr* nlh)
{
struct fib6_config cfg;
int err;
err = rtm_to_fib6_config(skb, nlh, &cfg);
if (err < 0)
return err;
if (cfg.fc_mp)
return ip6_route_multipath(&cfg, 0);
else
return ip6_route_del(&cfg);
}
static int inet6_rtm_newroute(struct sk_buff *skb, struct nlmsghdr* nlh)
{
struct fib6_config cfg;
int err;
err = rtm_to_fib6_config(skb, nlh, &cfg);
if (err < 0)
return err;
if (cfg.fc_mp)
return ip6_route_multipath(&cfg, 1);
else
return ip6_route_add(&cfg);
}
static inline size_t rt6_nlmsg_size(void)
{
return NLMSG_ALIGN(sizeof(struct rtmsg))
+ nla_total_size(16) /* RTA_SRC */
+ nla_total_size(16) /* RTA_DST */
+ nla_total_size(16) /* RTA_GATEWAY */
+ nla_total_size(16) /* RTA_PREFSRC */
+ nla_total_size(4) /* RTA_TABLE */
+ nla_total_size(4) /* RTA_IIF */
+ nla_total_size(4) /* RTA_OIF */
+ nla_total_size(4) /* RTA_PRIORITY */
+ RTAX_MAX * nla_total_size(4) /* RTA_METRICS */
+ nla_total_size(sizeof(struct rta_cacheinfo));
}
static int rt6_fill_node(struct net *net,
struct sk_buff *skb, struct rt6_info *rt,
struct in6_addr *dst, struct in6_addr *src,
int iif, int type, u32 portid, u32 seq,
int prefix, int nowait, unsigned int flags)
{
struct rtmsg *rtm;
struct nlmsghdr *nlh;
long expires;
u32 table;
if (prefix) { /* user wants prefix routes only */
if (!(rt->rt6i_flags & RTF_PREFIX_RT)) {
/* success since this is not a prefix route */
return 1;
}
}
nlh = nlmsg_put(skb, portid, seq, type, sizeof(*rtm), flags);
if (!nlh)
return -EMSGSIZE;
rtm = nlmsg_data(nlh);
rtm->rtm_family = AF_INET6;
rtm->rtm_dst_len = rt->rt6i_dst.plen;
rtm->rtm_src_len = rt->rt6i_src.plen;
rtm->rtm_tos = 0;
if (rt->rt6i_table)
table = rt->rt6i_table->tb6_id;
else
table = RT6_TABLE_UNSPEC;
rtm->rtm_table = table;
if (nla_put_u32(skb, RTA_TABLE, table))
goto nla_put_failure;
if (rt->rt6i_flags & RTF_REJECT) {
switch (rt->dst.error) {
case -EINVAL:
rtm->rtm_type = RTN_BLACKHOLE;
break;
case -EACCES:
rtm->rtm_type = RTN_PROHIBIT;
break;
case -EAGAIN:
rtm->rtm_type = RTN_THROW;
break;
default:
rtm->rtm_type = RTN_UNREACHABLE;
break;
}
}
else if (rt->rt6i_flags & RTF_LOCAL)
rtm->rtm_type = RTN_LOCAL;
else if (rt->dst.dev && (rt->dst.dev->flags & IFF_LOOPBACK))
rtm->rtm_type = RTN_LOCAL;
else
rtm->rtm_type = RTN_UNICAST;
rtm->rtm_flags = 0;
rtm->rtm_scope = RT_SCOPE_UNIVERSE;
rtm->rtm_protocol = rt->rt6i_protocol;
if (rt->rt6i_flags & RTF_DYNAMIC)
rtm->rtm_protocol = RTPROT_REDIRECT;
else if (rt->rt6i_flags & RTF_ADDRCONF) {
if (rt->rt6i_flags & (RTF_DEFAULT | RTF_ROUTEINFO))
rtm->rtm_protocol = RTPROT_RA;
else
rtm->rtm_protocol = RTPROT_KERNEL;
}
if (rt->rt6i_flags & RTF_CACHE)
rtm->rtm_flags |= RTM_F_CLONED;
if (dst) {
if (nla_put(skb, RTA_DST, 16, dst))
goto nla_put_failure;
rtm->rtm_dst_len = 128;
} else if (rtm->rtm_dst_len)
if (nla_put(skb, RTA_DST, 16, &rt->rt6i_dst.addr))
goto nla_put_failure;
#ifdef CONFIG_IPV6_SUBTREES
if (src) {
if (nla_put(skb, RTA_SRC, 16, src))
goto nla_put_failure;
rtm->rtm_src_len = 128;
} else if (rtm->rtm_src_len &&
nla_put(skb, RTA_SRC, 16, &rt->rt6i_src.addr))
goto nla_put_failure;
#endif
if (iif) {
#ifdef CONFIG_IPV6_MROUTE
if (ipv6_addr_is_multicast(&rt->rt6i_dst.addr)) {
int err = ip6mr_get_route(net, skb, rtm, nowait);
if (err <= 0) {
if (!nowait) {
if (err == 0)
return 0;
goto nla_put_failure;
} else {
if (err == -EMSGSIZE)
goto nla_put_failure;
}
}
} else
#endif
if (nla_put_u32(skb, RTA_IIF, iif))
goto nla_put_failure;
} else if (dst) {
struct in6_addr saddr_buf;
if (ip6_route_get_saddr(net, rt, dst, 0, &saddr_buf) == 0 &&
nla_put(skb, RTA_PREFSRC, 16, &saddr_buf))
goto nla_put_failure;
}
if (rt->rt6i_prefsrc.plen) {
struct in6_addr saddr_buf;
saddr_buf = rt->rt6i_prefsrc.addr;
if (nla_put(skb, RTA_PREFSRC, 16, &saddr_buf))
goto nla_put_failure;
}
if (rtnetlink_put_metrics(skb, dst_metrics_ptr(&rt->dst)) < 0)
goto nla_put_failure;
if (rt->rt6i_flags & RTF_GATEWAY) {
if (nla_put(skb, RTA_GATEWAY, 16, &rt->rt6i_gateway) < 0)
goto nla_put_failure;
}
if (rt->dst.dev &&
nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex))
goto nla_put_failure;
if (nla_put_u32(skb, RTA_PRIORITY, rt->rt6i_metric))
goto nla_put_failure;
expires = (rt->rt6i_flags & RTF_EXPIRES) ? rt->dst.expires - jiffies : 0;
if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, rt->dst.error) < 0)
goto nla_put_failure;
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
int rt6_dump_route(struct rt6_info *rt, void *p_arg)
{
struct rt6_rtnl_dump_arg *arg = (struct rt6_rtnl_dump_arg *) p_arg;
int prefix;
if (nlmsg_len(arg->cb->nlh) >= sizeof(struct rtmsg)) {
struct rtmsg *rtm = nlmsg_data(arg->cb->nlh);
prefix = (rtm->rtm_flags & RTM_F_PREFIX) != 0;
} else
prefix = 0;
return rt6_fill_node(arg->net,
arg->skb, rt, NULL, NULL, 0, RTM_NEWROUTE,
NETLINK_CB(arg->cb->skb).portid, arg->cb->nlh->nlmsg_seq,
prefix, 0, NLM_F_MULTI);
}
static int inet6_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr* nlh)
{
struct net *net = sock_net(in_skb->sk);
struct nlattr *tb[RTA_MAX+1];
struct rt6_info *rt;
struct sk_buff *skb;
struct rtmsg *rtm;
struct flowi6 fl6;
int err, iif = 0, oif = 0;
err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv6_policy);
if (err < 0)
goto errout;
err = -EINVAL;
memset(&fl6, 0, sizeof(fl6));
if (tb[RTA_SRC]) {
if (nla_len(tb[RTA_SRC]) < sizeof(struct in6_addr))
goto errout;
fl6.saddr = *(struct in6_addr *)nla_data(tb[RTA_SRC]);
}
if (tb[RTA_DST]) {
if (nla_len(tb[RTA_DST]) < sizeof(struct in6_addr))
goto errout;
fl6.daddr = *(struct in6_addr *)nla_data(tb[RTA_DST]);
}
if (tb[RTA_IIF])
iif = nla_get_u32(tb[RTA_IIF]);
if (tb[RTA_OIF])
oif = nla_get_u32(tb[RTA_OIF]);
if (iif) {
struct net_device *dev;
int flags = 0;
dev = __dev_get_by_index(net, iif);
if (!dev) {
err = -ENODEV;
goto errout;
}
fl6.flowi6_iif = iif;
if (!ipv6_addr_any(&fl6.saddr))
flags |= RT6_LOOKUP_F_HAS_SADDR;
rt = (struct rt6_info *)ip6_route_input_lookup(net, dev, &fl6,
flags);
} else {
fl6.flowi6_oif = oif;
rt = (struct rt6_info *)ip6_route_output(net, NULL, &fl6);
}
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb) {
ip6_rt_put(rt);
err = -ENOBUFS;
goto errout;
}
/* Reserve room for dummy headers, this skb can pass
through good chunk of routing engine.
*/
skb_reset_mac_header(skb);
skb_reserve(skb, MAX_HEADER + sizeof(struct ipv6hdr));
skb_dst_set(skb, &rt->dst);
err = rt6_fill_node(net, skb, rt, &fl6.daddr, &fl6.saddr, iif,
RTM_NEWROUTE, NETLINK_CB(in_skb).portid,
nlh->nlmsg_seq, 0, 0, 0);
if (err < 0) {
kfree_skb(skb);
goto errout;
}
err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
errout:
return err;
}
void inet6_rt_notify(int event, struct rt6_info *rt, struct nl_info *info)
{
struct sk_buff *skb;
struct net *net = info->nl_net;
u32 seq;
int err;
err = -ENOBUFS;
seq = info->nlh ? info->nlh->nlmsg_seq : 0;
skb = nlmsg_new(rt6_nlmsg_size(), gfp_any());
if (!skb)
goto errout;
err = rt6_fill_node(net, skb, rt, NULL, NULL, 0,
event, info->portid, seq, 0, 0, 0);
if (err < 0) {
/* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, info->portid, RTNLGRP_IPV6_ROUTE,
info->nlh, gfp_any());
return;
errout:
if (err < 0)
rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
}
static int ip6_route_dev_notify(struct notifier_block *this,
unsigned long event, void *data)
{
struct net_device *dev = (struct net_device *)data;
struct net *net = dev_net(dev);
if (event == NETDEV_REGISTER && (dev->flags & IFF_LOOPBACK)) {
net->ipv6.ip6_null_entry->dst.dev = dev;
net->ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(dev);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
net->ipv6.ip6_prohibit_entry->dst.dev = dev;
net->ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(dev);
net->ipv6.ip6_blk_hole_entry->dst.dev = dev;
net->ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(dev);
#endif
}
return NOTIFY_OK;
}
/*
* /proc
*/
#ifdef CONFIG_PROC_FS
struct rt6_proc_arg
{
char *buffer;
int offset;
int length;
int skip;
int len;
};
static int rt6_info_route(struct rt6_info *rt, void *p_arg)
{
struct seq_file *m = p_arg;
seq_printf(m, "%pi6 %02x ", &rt->rt6i_dst.addr, rt->rt6i_dst.plen);
#ifdef CONFIG_IPV6_SUBTREES
seq_printf(m, "%pi6 %02x ", &rt->rt6i_src.addr, rt->rt6i_src.plen);
#else
seq_puts(m, "00000000000000000000000000000000 00 ");
#endif
if (rt->rt6i_flags & RTF_GATEWAY) {
seq_printf(m, "%pi6", &rt->rt6i_gateway);
} else {
seq_puts(m, "00000000000000000000000000000000");
}
seq_printf(m, " %08x %08x %08x %08x %8s\n",
rt->rt6i_metric, atomic_read(&rt->dst.__refcnt),
rt->dst.__use, rt->rt6i_flags,
rt->dst.dev ? rt->dst.dev->name : "");
return 0;
}
static int ipv6_route_show(struct seq_file *m, void *v)
{
struct net *net = (struct net *)m->private;
fib6_clean_all_ro(net, rt6_info_route, 0, m);
return 0;
}
static int ipv6_route_open(struct inode *inode, struct file *file)
{
return single_open_net(inode, file, ipv6_route_show);
}
static const struct file_operations ipv6_route_proc_fops = {
.owner = THIS_MODULE,
.open = ipv6_route_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release_net,
};
static int rt6_stats_seq_show(struct seq_file *seq, void *v)
{
struct net *net = (struct net *)seq->private;
seq_printf(seq, "%04x %04x %04x %04x %04x %04x %04x\n",
net->ipv6.rt6_stats->fib_nodes,
net->ipv6.rt6_stats->fib_route_nodes,
net->ipv6.rt6_stats->fib_rt_alloc,
net->ipv6.rt6_stats->fib_rt_entries,
net->ipv6.rt6_stats->fib_rt_cache,
dst_entries_get_slow(&net->ipv6.ip6_dst_ops),
net->ipv6.rt6_stats->fib_discarded_routes);
return 0;
}
static int rt6_stats_seq_open(struct inode *inode, struct file *file)
{
return single_open_net(inode, file, rt6_stats_seq_show);
}
static const struct file_operations rt6_stats_seq_fops = {
.owner = THIS_MODULE,
.open = rt6_stats_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release_net,
};
#endif /* CONFIG_PROC_FS */
#ifdef CONFIG_SYSCTL
static
int ipv6_sysctl_rtcache_flush(ctl_table *ctl, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct net *net;
int delay;
if (!write)
return -EINVAL;
net = (struct net *)ctl->extra1;
delay = net->ipv6.sysctl.flush_delay;
proc_dointvec(ctl, write, buffer, lenp, ppos);
fib6_run_gc(delay <= 0 ? ~0UL : (unsigned long)delay, net);
return 0;
}
ctl_table ipv6_route_table_template[] = {
{
.procname = "flush",
.data = &init_net.ipv6.sysctl.flush_delay,
.maxlen = sizeof(int),
.mode = 0200,
.proc_handler = ipv6_sysctl_rtcache_flush
},
{
.procname = "gc_thresh",
.data = &ip6_dst_ops_template.gc_thresh,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "max_size",
.data = &init_net.ipv6.sysctl.ip6_rt_max_size,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "gc_min_interval",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "gc_timeout",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "gc_interval",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "gc_elasticity",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_elasticity,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "mtu_expires",
.data = &init_net.ipv6.sysctl.ip6_rt_mtu_expires,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "min_adv_mss",
.data = &init_net.ipv6.sysctl.ip6_rt_min_advmss,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "gc_min_interval_ms",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_ms_jiffies,
},
{ }
};
struct ctl_table * __net_init ipv6_route_sysctl_init(struct net *net)
{
struct ctl_table *table;
table = kmemdup(ipv6_route_table_template,
sizeof(ipv6_route_table_template),
GFP_KERNEL);
if (table) {
table[0].data = &net->ipv6.sysctl.flush_delay;
table[0].extra1 = net;
table[1].data = &net->ipv6.ip6_dst_ops.gc_thresh;
table[2].data = &net->ipv6.sysctl.ip6_rt_max_size;
table[3].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
table[4].data = &net->ipv6.sysctl.ip6_rt_gc_timeout;
table[5].data = &net->ipv6.sysctl.ip6_rt_gc_interval;
table[6].data = &net->ipv6.sysctl.ip6_rt_gc_elasticity;
table[7].data = &net->ipv6.sysctl.ip6_rt_mtu_expires;
table[8].data = &net->ipv6.sysctl.ip6_rt_min_advmss;
table[9].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
/* Don't export sysctls to unprivileged users */
if (net->user_ns != &init_user_ns)
table[0].procname = NULL;
}
return table;
}
#endif
static int __net_init ip6_route_net_init(struct net *net)
{
int ret = -ENOMEM;
memcpy(&net->ipv6.ip6_dst_ops, &ip6_dst_ops_template,
sizeof(net->ipv6.ip6_dst_ops));
if (dst_entries_init(&net->ipv6.ip6_dst_ops) < 0)
goto out_ip6_dst_ops;
net->ipv6.ip6_null_entry = kmemdup(&ip6_null_entry_template,
sizeof(*net->ipv6.ip6_null_entry),
GFP_KERNEL);
if (!net->ipv6.ip6_null_entry)
goto out_ip6_dst_entries;
net->ipv6.ip6_null_entry->dst.path =
(struct dst_entry *)net->ipv6.ip6_null_entry;
net->ipv6.ip6_null_entry->dst.ops = &net->ipv6.ip6_dst_ops;
dst_init_metrics(&net->ipv6.ip6_null_entry->dst,
ip6_template_metrics, true);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
net->ipv6.ip6_prohibit_entry = kmemdup(&ip6_prohibit_entry_template,
sizeof(*net->ipv6.ip6_prohibit_entry),
GFP_KERNEL);
if (!net->ipv6.ip6_prohibit_entry)
goto out_ip6_null_entry;
net->ipv6.ip6_prohibit_entry->dst.path =
(struct dst_entry *)net->ipv6.ip6_prohibit_entry;
net->ipv6.ip6_prohibit_entry->dst.ops = &net->ipv6.ip6_dst_ops;
dst_init_metrics(&net->ipv6.ip6_prohibit_entry->dst,
ip6_template_metrics, true);
net->ipv6.ip6_blk_hole_entry = kmemdup(&ip6_blk_hole_entry_template,
sizeof(*net->ipv6.ip6_blk_hole_entry),
GFP_KERNEL);
if (!net->ipv6.ip6_blk_hole_entry)
goto out_ip6_prohibit_entry;
net->ipv6.ip6_blk_hole_entry->dst.path =
(struct dst_entry *)net->ipv6.ip6_blk_hole_entry;
net->ipv6.ip6_blk_hole_entry->dst.ops = &net->ipv6.ip6_dst_ops;
dst_init_metrics(&net->ipv6.ip6_blk_hole_entry->dst,
ip6_template_metrics, true);
#endif
net->ipv6.sysctl.flush_delay = 0;
net->ipv6.sysctl.ip6_rt_max_size = 4096;
net->ipv6.sysctl.ip6_rt_gc_min_interval = HZ / 2;
net->ipv6.sysctl.ip6_rt_gc_timeout = 60*HZ;
net->ipv6.sysctl.ip6_rt_gc_interval = 30*HZ;
net->ipv6.sysctl.ip6_rt_gc_elasticity = 9;
net->ipv6.sysctl.ip6_rt_mtu_expires = 10*60*HZ;
net->ipv6.sysctl.ip6_rt_min_advmss = IPV6_MIN_MTU - 20 - 40;
net->ipv6.ip6_rt_gc_expire = 30*HZ;
ret = 0;
out:
return ret;
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
out_ip6_prohibit_entry:
kfree(net->ipv6.ip6_prohibit_entry);
out_ip6_null_entry:
kfree(net->ipv6.ip6_null_entry);
#endif
out_ip6_dst_entries:
dst_entries_destroy(&net->ipv6.ip6_dst_ops);
out_ip6_dst_ops:
goto out;
}
static void __net_exit ip6_route_net_exit(struct net *net)
{
kfree(net->ipv6.ip6_null_entry);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
kfree(net->ipv6.ip6_prohibit_entry);
kfree(net->ipv6.ip6_blk_hole_entry);
#endif
dst_entries_destroy(&net->ipv6.ip6_dst_ops);
}
static int __net_init ip6_route_net_init_late(struct net *net)
{
#ifdef CONFIG_PROC_FS
proc_create("ipv6_route", 0, net->proc_net, &ipv6_route_proc_fops);
proc_create("rt6_stats", S_IRUGO, net->proc_net, &rt6_stats_seq_fops);
#endif
return 0;
}
static void __net_exit ip6_route_net_exit_late(struct net *net)
{
#ifdef CONFIG_PROC_FS
remove_proc_entry("ipv6_route", net->proc_net);
remove_proc_entry("rt6_stats", net->proc_net);
#endif
}
static struct pernet_operations ip6_route_net_ops = {
.init = ip6_route_net_init,
.exit = ip6_route_net_exit,
};
static int __net_init ipv6_inetpeer_init(struct net *net)
{
struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL);
if (!bp)
return -ENOMEM;
inet_peer_base_init(bp);
net->ipv6.peers = bp;
return 0;
}
static void __net_exit ipv6_inetpeer_exit(struct net *net)
{
struct inet_peer_base *bp = net->ipv6.peers;
net->ipv6.peers = NULL;
inetpeer_invalidate_tree(bp);
kfree(bp);
}
static struct pernet_operations ipv6_inetpeer_ops = {
.init = ipv6_inetpeer_init,
.exit = ipv6_inetpeer_exit,
};
static struct pernet_operations ip6_route_net_late_ops = {
.init = ip6_route_net_init_late,
.exit = ip6_route_net_exit_late,
};
static struct notifier_block ip6_route_dev_notifier = {
.notifier_call = ip6_route_dev_notify,
.priority = 0,
};
int __init ip6_route_init(void)
{
int ret;
ret = -ENOMEM;
ip6_dst_ops_template.kmem_cachep =
kmem_cache_create("ip6_dst_cache", sizeof(struct rt6_info), 0,
SLAB_HWCACHE_ALIGN, NULL);
if (!ip6_dst_ops_template.kmem_cachep)
goto out;
ret = dst_entries_init(&ip6_dst_blackhole_ops);
if (ret)
goto out_kmem_cache;
ret = register_pernet_subsys(&ipv6_inetpeer_ops);
if (ret)
goto out_dst_entries;
ret = register_pernet_subsys(&ip6_route_net_ops);
if (ret)
goto out_register_inetpeer;
ip6_dst_blackhole_ops.kmem_cachep = ip6_dst_ops_template.kmem_cachep;
/* Registering of the loopback is done before this portion of code,
* the loopback reference in rt6_info will not be taken, do it
* manually for init_net */
init_net.ipv6.ip6_null_entry->dst.dev = init_net.loopback_dev;
init_net.ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
init_net.ipv6.ip6_prohibit_entry->dst.dev = init_net.loopback_dev;
init_net.ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
init_net.ipv6.ip6_blk_hole_entry->dst.dev = init_net.loopback_dev;
init_net.ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
#endif
ret = fib6_init();
if (ret)
goto out_register_subsys;
ret = xfrm6_init();
if (ret)
goto out_fib6_init;
ret = fib6_rules_init();
if (ret)
goto xfrm6_init;
ret = register_pernet_subsys(&ip6_route_net_late_ops);
if (ret)
goto fib6_rules_init;
ret = -ENOBUFS;
if (__rtnl_register(PF_INET6, RTM_NEWROUTE, inet6_rtm_newroute, NULL, NULL) ||
__rtnl_register(PF_INET6, RTM_DELROUTE, inet6_rtm_delroute, NULL, NULL) ||
__rtnl_register(PF_INET6, RTM_GETROUTE, inet6_rtm_getroute, NULL, NULL))
goto out_register_late_subsys;
ret = register_netdevice_notifier(&ip6_route_dev_notifier);
if (ret)
goto out_register_late_subsys;
out:
return ret;
out_register_late_subsys:
unregister_pernet_subsys(&ip6_route_net_late_ops);
fib6_rules_init:
fib6_rules_cleanup();
xfrm6_init:
xfrm6_fini();
out_fib6_init:
fib6_gc_cleanup();
out_register_subsys:
unregister_pernet_subsys(&ip6_route_net_ops);
out_register_inetpeer:
unregister_pernet_subsys(&ipv6_inetpeer_ops);
out_dst_entries:
dst_entries_destroy(&ip6_dst_blackhole_ops);
out_kmem_cache:
kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
goto out;
}
void ip6_route_cleanup(void)
{
unregister_netdevice_notifier(&ip6_route_dev_notifier);
unregister_pernet_subsys(&ip6_route_net_late_ops);
fib6_rules_cleanup();
xfrm6_fini();
fib6_gc_cleanup();
unregister_pernet_subsys(&ipv6_inetpeer_ops);
unregister_pernet_subsys(&ip6_route_net_ops);
dst_entries_destroy(&ip6_dst_blackhole_ops);
kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
}
| Rashed97/caf-kernel-msm-3.10 | net/ipv6/route.c | C | gpl-2.0 | 77,538 |
// 2001-01-17 Benjamin Kosnik <[email protected]>
// Copyright (C) 2001-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 22.2.3.1.1 nunpunct members
#include <locale>
#include <testsuite_hooks.h>
void test01()
{
using namespace std;
// basic construction
locale loc_c = locale::classic();
// cache the numpunct facets
const numpunct<char>& nump_c = use_facet<numpunct<char> >(loc_c);
// sanity check the data is correct.
char dp1 = nump_c.decimal_point();
char th1 = nump_c.thousands_sep();
string g1 = nump_c.grouping();
string t1 = nump_c.truename();
string f1 = nump_c.falsename();
VERIFY ( dp1 == '.' );
VERIFY ( th1 == ',' );
VERIFY ( g1 == "" );
VERIFY ( t1 == "true" );
VERIFY ( f1 == "false" );
}
int main()
{
test01();
return 0;
}
| mickael-guene/gcc | libstdc++-v3/testsuite/22_locale/numpunct/members/char/1.cc | C++ | gpl-2.0 | 1,479 |
/*
* Copyright (c) 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.
*
* 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.
*/
/*
* @test
*
* @summary converted from VM Testbase nsk/jdi/ReferenceType/locationsOfLine_i/locationsofline_i001.
* VM Testbase keywords: [jpda, jdi]
* VM Testbase readme:
* DESCRIPTION:
* The test for the implementation of an object of the type
* ReferenceType.
* The test checks up that a result of the method
* com.sun.jdi.ReferenceType.locationsOfLine_i()
* complies with its spec:
* public List locationsOfLine(int lineNumber)
* throws AbsentInformationException
* Returns a List containing all Location objects that
* map to the given line number.
* This method is equivalent to
* locationsOfLine(vm.getDefaultStratum(), null, lineNumber) -
* see locationsOfLine(java.lang.String,java.lang.String,int)
* for more information.
* Parameters: lineNumber - the line number
* Returns: a List of all Location objects that map to the given line.
* Throws: AbsentInformationException -
* if there is no line number information for this class.
* ClassNotPreparedException -
* if this class not yet been prepared.
* The test checks up that for each line in the List returned by the method
* ReferenceType.allLineLocations(), the method locationsOfLine(lineNumber)
* returns non-empty List object in which each object is a Location object.
* Not throwing AbsentInformationException is checked up as well.
* The test works as follows:
* The debugger program - nsk.jdi.ReferenceType.locationsOfLine_i.locationsofline_i001;
* the debuggee program - nsk.jdi.ReferenceType.locationsOfLine_i.locationsofline_i001a.
* Using nsk.jdi.share classes,
* the debugger gets the debuggee running on another JavaVM,
* creates the object debuggee.VM,
* establishes a pipe with the debuggee program, and then
* send to the programm commands, to which the debuggee replies
* via the pipe. Upon getting reply,
* the debugger calls corresponding debuggee.VM methods to get
* needed data and compares the data got to the data expected.
* In case of error the test produces the return value 97 and
* a corresponding error message(s).
* Otherwise, the test is passed and produces
* the return value 95 and no message.
* COMMENTS:
* The option
* JAVAC_OPTS=-g
* is put into the locationsofline002.cfg file.
*
* @library /vmTestbase
* /test/lib
* @run driver jdk.test.lib.FileInstaller . .
* @build nsk.jdi.ReferenceType.locationsOfLine_i.locationsofline_i001
* nsk.jdi.ReferenceType.locationsOfLine_i.locationsofline_i001a
*
* @comment make sure locationsofline_i001a is compiled with full debug info
* @clean nsk.jdi.ReferenceType.locationsOfLine_i.locationsofline_i001a
* @compile -g:lines,source,vars ../locationsofline_i001a.java
*
* @run main/othervm PropertyResolvingWrapper
* nsk.jdi.ReferenceType.locationsOfLine_i.locationsofline_i001
* -verbose
* -arch=${os.family}-${os.simpleArch}
* -waittime=5
* -debugee.vmkind=java
* -transport.address=dynamic
* "-debugee.vmkeys=${test.vm.opts} ${test.java.opts}"
*/
| md-5/jdk10 | test/hotspot/jtreg/vmTestbase/nsk/jdi/ReferenceType/locationsOfLine_i/locationsofline_i001/TestDescription.java | Java | gpl-2.0 | 4,279 |
/* Copyright 2017 Mathias Andersson <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include QMK_KEYBOARD_H
//Layers
enum {
BASE = 0,
FUNCTION,
ALTERNATE,
LAST,
};
const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
/* Keymap BASE: (Base Layer) Default Layer
*
* ,-----------------------------------------------------------. .-------------------.
* | ~ | 1 | 2| 3| 4| 5| 6| 7| 8| 9| 0| -| =|Backsp | |NumL| / | * | - |
* |-----------------------------------------------------------| |-------------------|
* |Tab | Q| W| E| R| T| Y| U| I| O| P| [| ]| \ | | 7 | 8 | 9 | |
* |-----------------------------------------------------------| |--------------| + |
* |CAPS | A| S| D| F| G| H| J| K| L| ;| '|Return | | 4 | 5 | 6 | |
* |-----------------------------------------------------------| |-------------------|
* |Shift | Z| X| C| V| B| N| M| ,| .| /|Shift | | 1 | 2 | 3 | Ent|
* |-----------------------------------------------------------| |--------------| |
* |Ctrl|Gui |Alt | Space | Alt | Win |FN |Ctr | | 0 | . | |
* `-----------------------------------------------------------' '-------------------'
*/
[BASE] = LAYOUT_all(
KC_GRV, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_MINS, KC_EQL, KC_BSPC, XXXXXXX, KC_NLCK, KC_PSLS, KC_PAST, KC_PMNS,
KC_TAB, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_LBRC, KC_RBRC, KC_BSLS, KC_P7, KC_P8, KC_P9, XXXXXXX,
KC_CAPS, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_QUOT, XXXXXXX, KC_ENT, KC_P4, KC_P5, KC_P6, KC_PPLS,
KC_LSFT, XXXXXXX, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_RSFT, XXXXXXX, KC_P1, KC_P2, KC_P3, XXXXXXX,
KC_LCTL, KC_LGUI, KC_LALT, KC_SPC, KC_RALT, KC_RWIN, MO(FUNCTION), KC_RCTL, KC_P0, XXXXXXX, KC_PDOT, KC_PENT
),
/* Keymap FUNCTION: (Function Layer)
*
* ,-----------------------------------------------------------. .-------------------.
* | | | | | | | | | | | | | | RESET | | | | | |
* |-----------------------------------------------------------| |-------------------|
* | | | | | | | | | | | | | | | | | | | |
* |-----------------------------------------------------------| |-------------------|
* | | | | | | | | | | | | | | | | | | |
* |-----------------------------------------------------------| |-------------------|
* | |Tog|Mod|Hu+|Hu-|Sa+|Sa-|Va+|Va-|Stp| | | | | | | |
* |-----------------------------------------------------------| |--------------| |
* | | | | | | | | | | | | |
* `-----------------------------------------------------------' '-------------------'
*/
[FUNCTION] = LAYOUT_all(
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, RESET, XXXXXXX, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, XXXXXXX,
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, XXXXXXX, _______, _______, _______, _______, _______,
_______, XXXXXXX, RGB_TOG, RGB_MOD, RGB_HUI, RGB_HUD, RGB_SAI, RGB_SAD, RGB_VAI, RGB_VAD, BL_STEP, _______, _______, XXXXXXX, _______, _______, _______, XXXXXXX,
_______, _______, _______, _______, _______, _______, MO(FUNCTION), _______, _______, XXXXXXX, _______, _______
),
[ALTERNATE] = LAYOUT_all(
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, RESET, XXXXXXX, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, XXXXXXX,
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, XXXXXXX, _______, _______, _______, _______, _______,
_______, XXXXXXX, RGB_TOG, RGB_MOD, RGB_HUI, RGB_HUD, RGB_SAI, RGB_SAD, RGB_VAI, RGB_VAD, BL_STEP, _______, _______, XXXXXXX, _______, _______, _______, XXXXXXX,
_______, _______, _______, _______, _______, _______, MO(FUNCTION), _______, _______, XXXXXXX, _______, _______
),
[LAST] = LAYOUT_all(
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, RESET, XXXXXXX, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, XXXXXXX,
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, XXXXXXX, _______, _______, _______, _______, _______,
_______, XXXXXXX, RGB_TOG, RGB_MOD, RGB_HUI, RGB_HUD, RGB_SAI, RGB_SAD, RGB_VAI, RGB_VAD, BL_STEP, _______, _______, XXXXXXX, _______, _______, _______, XXXXXXX,
_______, _______, _______, _______, _______, _______, MO(FUNCTION), _______, _______, XXXXXXX, _______, _______
),
};
#ifdef OLED_DRIVER_ENABLE
void oled_task_user(void) {
oled_write_P(PSTR("M0lly\n"),false);
// Host Keyboard Layer Status
oled_write_P(PSTR("Layer: "), false);
switch (get_highest_layer(layer_state)) {
case BASE:
oled_write_P(PSTR("Base\n"), false);
break;
case FUNCTION:
oled_write_P(PSTR("Function\n"), false);
break;
case ALTERNATE:
oled_write_P(PSTR("Alternate\n"), false);
break;
case LAST:
oled_write_P(PSTR("Last\n"), false);
break;
default:
// Or use the write_ln shortcut over adding '\n' to the end of your string
oled_write_ln_P(PSTR("Undefined"), false);
}
// Host Keyboard LED Status
led_t led_state = host_keyboard_led_state();
oled_write_P(led_state.num_lock ? PSTR("NUM ") : PSTR(" "), false);
oled_write_P(led_state.caps_lock ? PSTR("CAP ") : PSTR(" "), false);
oled_write_P(led_state.scroll_lock ? PSTR("SCR ") : PSTR(" "), false);
}
#endif
| kmtoki/qmk_firmware | keyboards/tkc/m0lly/keymaps/via/keymap.c | C | gpl-2.0 | 7,600 |
<?php
// {$setting_id}[$id] - Contains the setting id, this is what it will be stored in the db as.
// $class - optional class value
// $id - setting id
// $options[$id] value from the db
//var_dump($options[$id]);
$c = 0;
foreach ( $option_values as $k => $v ) {
$alt = '';
if($k === 0){
$alt = " <input class='regular-text' name='{$setting_id}[$id][tweet_text]' type='text' value='" . esc_attr( $options[ $id ]['tweet_text'] ) . "' placeholder='".__('Optional Tweet Text','seedprod')."' />";
}
if($k === 1){
$alt = " <input id='{$id}_facebook_img' placeholder='".__('Image for Facebook Like. Optimal Size: 200px x 200px','seedprod')."' class='regular-text' name='{$setting_id}[$id][facebook_img]' type='text' value='" . esc_attr( $options[ $id ]['facebook_img'] ) . "' />";
$alt .= "<input id='{$id}_facebook_img_upload_image_button' class='button-secondary upload-button' type='button' value='" . __( 'Media Image Library', 'seedprod' ) . "' />";
wp_enqueue_script( 'seed_csp3-upload-js', SEED_CSP3_PLUGIN_URL . 'framework/field-types/js/upload.js', array(
'jquery',
'thickbox',
'media-upload'
) );
}
if($k === 4){
$alt = " <input id='{$id}_pinterest_img' placeholder='".__('Image for Pinterest','seedprod')."' class='regular-text' name='{$setting_id}[$id][pinterest_img]' type='text' value='" . esc_attr( $options[ $id ]['pinterest_img'] ) . "' />";
$alt .= "<input id='{$id}_pinterest_img_upload_image_button' class='button-secondary upload-button' type='button' value='" . __( 'Media Image Library', 'seedprod' ) . "' />";
wp_enqueue_script( 'seed_csp3-upload-js', SEED_CSP3_PLUGIN_URL . 'framework/field-types/js/upload.js', array(
'jquery',
'thickbox',
'media-upload'
) );
}
if(is_int($k)){
echo "<input type='checkbox' name='{$setting_id}[$id][buttons][]' value='$k' " . ( in_array( $k, ( empty( $options[ $id ]['buttons'] ) ? array( ) : $options[ $id ]['buttons'] ) ) ? 'checked' : '' ) . " /> $v $alt<br/>";
$c++;
}
}
| MujeresdelasAmericas/Sitio | wp-content/plugins/seedprod-coming-soon-pro/framework/field-types/customsharebuttons.php | PHP | gpl-2.0 | 2,048 |
// license:BSD-3-Clause
// copyright-holders:Nicola Salmoria, Manuel Abadia
/***************************************************************************
video.c
Functions to emulate the video hardware of the machine.
***************************************************************************/
#include "emu.h"
#include "includes/chqflag.h"
/***************************************************************************
Callbacks for the K051960
***************************************************************************/
K051960_CB_MEMBER(chqflag_state::sprite_callback)
{
enum { sprite_colorbase = 0 };
*priority = (*color & 0x10) ? 0 : GFX_PMASK_1;
*color = sprite_colorbase + (*color & 0x0f);
}
/***************************************************************************
Callbacks for the K051316
***************************************************************************/
K051316_CB_MEMBER(chqflag_state::zoom_callback_1)
{
enum { zoom_colorbase_1 = 256 / 16 };
*code |= ((*color & 0x03) << 8);
*color = zoom_colorbase_1 + ((*color & 0x3c) >> 2);
}
K051316_CB_MEMBER(chqflag_state::zoom_callback_2)
{
enum { zoom_colorbase_2 = 512 / 256 };
*flags = TILE_FLIPYX((*color & 0xc0) >> 6);
*code |= ((*color & 0x0f) << 8);
*color = zoom_colorbase_2 + ((*color & 0x10) >> 4);
}
/***************************************************************************
Display Refresh
***************************************************************************/
UINT32 chqflag_state::screen_update_chqflag(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
screen.priority().fill(0, cliprect);
m_k051316_2->zoom_draw(screen, bitmap, cliprect, TILEMAP_DRAW_LAYER1, 0);
m_k051316_2->zoom_draw(screen, bitmap, cliprect, TILEMAP_DRAW_LAYER0, 1);
m_k051960->k051960_sprites_draw(bitmap, cliprect, screen.priority(), -1, -1);
m_k051316_1->zoom_draw(screen, bitmap, cliprect, 0, 0);
return 0;
}
| h0tw1r3/mame | src/mame/video/chqflag.cpp | C++ | gpl-2.0 | 1,946 |
/*
* Conversion between 32-bit and 64-bit native system calls.
*
* Copyright (C) 2000 Silicon Graphics, Inc.
* Written by Ulf Carlsson ([email protected])
* sys32_execve from ia64/ia32 code, Feb 2000, Kanoj Sarcar ([email protected])
*/
#include <linux/config.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/file.h>
#include <linux/smp_lock.h>
#include <linux/highuid.h>
#include <linux/dirent.h>
#include <linux/resource.h>
#include <linux/highmem.h>
#include <linux/time.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <linux/filter.h>
#include <linux/shm.h>
#include <linux/sem.h>
#include <linux/msg.h>
#include <linux/icmpv6.h>
#include <linux/sysctl.h>
#include <linux/utime.h>
#include <linux/utsname.h>
#include <linux/personality.h>
#include <linux/timex.h>
#include <linux/dnotify.h>
#include <linux/linkage.h>
#include <linux/module.h>
#include <net/sock.h>
#include <net/scm.h>
#include <asm/uaccess.h>
#include <asm/mman.h>
#include <asm/ipc.h>
extern asmlinkage long sys_socket(int family, int type, int protocol);
extern asmlinkage long sys_bind(int fd, struct sockaddr *umyaddr, int addrlen);
extern asmlinkage long sys_connect(int fd, struct sockaddr *uservaddr,
int addrlen);
extern asmlinkage long sys_listen(int fd, int backlog);
extern asmlinkage long sys_accept(int fd, struct sockaddr *upeer_sockaddr,
int *upeer_addrlen);
extern asmlinkage long sys_getsockname(int fd, struct sockaddr *usockaddr,
int *usockaddr_len);
extern asmlinkage long sys_getpeername(int fd, struct sockaddr *usockaddr,
int *usockaddr_len);
extern asmlinkage long sys_socketpair(int family, int type, int protocol,
int *usockvec);
extern asmlinkage long sys_send(int fd, void * buff, size_t len,
unsigned flags);
extern asmlinkage long sys_sendto(int fd, void * buff, size_t len,
unsigned flags, struct sockaddr *addr, int addr_len);
extern asmlinkage long sys_recv(int fd, void * ubuf, size_t size,
unsigned flags);
extern asmlinkage long sys_recvfrom(int fd, void * ubuf, size_t size,
unsigned flags, struct sockaddr *addr, int *addr_len);
extern asmlinkage long sys_shutdown(int fd, int how);
extern asmlinkage long sys_setsockopt(int fd, int level, int optname,
char *optval, int optlen);
extern asmlinkage long sys_getsockopt(int fd, int level, int optname,
char *optval, int *optlen);
extern asmlinkage long sys_sendmsg(int fd, struct msghdr *msg, unsigned flags);
extern asmlinkage long sys_recvmsg(int fd, struct msghdr *msg,
unsigned int flags);
/* Use this to get at 32-bit user passed pointers. */
/* A() macro should be used for places where you e.g.
have some internal variable u32 and just want to get
rid of a compiler warning. AA() has to be used in
places where you want to convert a function argument
to 32bit pointer or when you e.g. access pt_regs
structure and want to consider 32bit registers only.
*/
#define A(__x) ((unsigned long)(__x))
#define AA(__x) ((unsigned long)((int)__x))
#ifdef __MIPSEB__
#define merge_64(r1,r2) ((((r1) & 0xffffffffUL) << 32) + ((r2) & 0xffffffffUL))
#endif
#ifdef __MIPSEL__
#define merge_64(r1,r2) ((((r2) & 0xffffffffUL) << 32) + ((r1) & 0xffffffffUL))
#endif
/*
* Revalidate the inode. This is required for proper NFS attribute caching.
*/
static __inline__ int
do_revalidate(struct dentry *dentry)
{
struct inode * inode = dentry->d_inode;
if (inode->i_op && inode->i_op->revalidate)
return inode->i_op->revalidate(dentry);
return 0;
}
static int cp_new_stat32(struct inode * inode, struct stat32 * statbuf)
{
struct stat32 tmp;
unsigned int blocks, indirect;
memset(&tmp, 0, sizeof(tmp));
tmp.st_dev = kdev_t_to_nr(inode->i_dev);
tmp.st_ino = inode->i_ino;
tmp.st_mode = inode->i_mode;
tmp.st_nlink = inode->i_nlink;
SET_STAT_UID(tmp, inode->i_uid);
SET_STAT_GID(tmp, inode->i_gid);
tmp.st_rdev = kdev_t_to_nr(inode->i_rdev);
tmp.st_size = inode->i_size;
tmp.st_atime = inode->i_atime;
tmp.st_mtime = inode->i_mtime;
tmp.st_ctime = inode->i_ctime;
/*
* st_blocks and st_blksize are approximated with a simple algorithm if
* they aren't supported directly by the filesystem. The minix and msdos
* filesystems don't keep track of blocks, so they would either have to
* be counted explicitly (by delving into the file itself), or by using
* this simple algorithm to get a reasonable (although not 100%
* accurate) value.
*/
/*
* Use minix fs values for the number of direct and indirect blocks.
* The count is now exact for the minix fs except that it counts zero
* blocks. Everything is in units of BLOCK_SIZE until the assignment
* to tmp.st_blksize.
*/
#define D_B 7
#define I_B (BLOCK_SIZE / sizeof(unsigned short))
if (!inode->i_blksize) {
blocks = (tmp.st_size + BLOCK_SIZE - 1) / BLOCK_SIZE;
if (blocks > D_B) {
indirect = (blocks - D_B + I_B - 1) / I_B;
blocks += indirect;
if (indirect > 1) {
indirect = (indirect - 1 + I_B - 1) / I_B;
blocks += indirect;
if (indirect > 1)
blocks++;
}
}
tmp.st_blocks = (BLOCK_SIZE / 512) * blocks;
tmp.st_blksize = BLOCK_SIZE;
} else {
tmp.st_blocks = inode->i_blocks;
tmp.st_blksize = inode->i_blksize;
}
return copy_to_user(statbuf,&tmp,sizeof(tmp)) ? -EFAULT : 0;
}
asmlinkage int sys32_newstat(char * filename, struct stat32 *statbuf)
{
struct nameidata nd;
int error;
error = user_path_walk(filename, &nd);
if (!error) {
error = do_revalidate(nd.dentry);
if (!error)
error = cp_new_stat32(nd.dentry->d_inode, statbuf);
path_release(&nd);
}
return error;
}
asmlinkage int sys32_newlstat(char * filename, struct stat32 *statbuf)
{
struct nameidata nd;
int error;
error = user_path_walk_link(filename, &nd);
if (!error) {
error = do_revalidate(nd.dentry);
if (!error)
error = cp_new_stat32(nd.dentry->d_inode, statbuf);
path_release(&nd);
}
return error;
}
asmlinkage long sys32_newfstat(unsigned int fd, struct stat32 * statbuf)
{
struct file * f;
int err = -EBADF;
f = fget(fd);
if (f) {
struct dentry * dentry = f->f_dentry;
err = do_revalidate(dentry);
if (!err)
err = cp_new_stat32(dentry->d_inode, statbuf);
fput(f);
}
return err;
}
asmlinkage unsigned long
sys32_mmap2(unsigned long addr, size_t len, unsigned long prot,
unsigned long flags, unsigned long fd, unsigned long pgoff)
{
struct file * file = NULL;
unsigned long error;
error = -EINVAL;
if (!(flags & MAP_ANONYMOUS)) {
error = -EBADF;
file = fget(fd);
if (!file)
goto out;
}
flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
down_write(¤t->mm->mmap_sem);
error = do_mmap_pgoff(file, addr, len, prot, flags, pgoff);
up_write(¤t->mm->mmap_sem);
if (file)
fput(file);
out:
return error;
}
asmlinkage long sys_truncate(const char * path, unsigned long length);
asmlinkage int sys_truncate64(const char *path, unsigned int high,
unsigned int low)
{
if ((int)high < 0)
return -EINVAL;
return sys_truncate(path, ((long) high << 32) | low);
}
asmlinkage long sys_ftruncate(unsigned int fd, unsigned long length);
asmlinkage int sys_ftruncate64(unsigned int fd, unsigned int high,
unsigned int low)
{
if ((int)high < 0)
return -EINVAL;
return sys_ftruncate(fd, ((long) high << 32) | low);
}
extern asmlinkage int sys_utime(char * filename, struct utimbuf * times);
struct utimbuf32 {
__kernel_time_t32 actime, modtime;
};
asmlinkage int sys32_utime(char * filename, struct utimbuf32 *times)
{
struct utimbuf t;
mm_segment_t old_fs;
int ret;
char *filenam;
if (!times)
return sys_utime(filename, NULL);
if (get_user (t.actime, ×->actime) ||
__get_user (t.modtime, ×->modtime))
return -EFAULT;
filenam = getname (filename);
ret = PTR_ERR(filenam);
if (!IS_ERR(filenam)) {
old_fs = get_fs();
set_fs (KERNEL_DS);
ret = sys_utime(filenam, &t);
set_fs (old_fs);
putname (filenam);
}
return ret;
}
#if 0
/*
* count32() counts the number of arguments/envelopes
*/
static int count32(u32 * argv, int max)
{
int i = 0;
if (argv != NULL) {
for (;;) {
u32 p; int error;
error = get_user(p,argv);
if (error)
return error;
if (!p)
break;
argv++;
if (++i > max)
return -E2BIG;
}
}
return i;
}
/*
* 'copy_strings32()' copies argument/envelope strings from user
* memory to free pages in kernel mem. These are in a format ready
* to be put directly into the top of new user memory.
*/
int copy_strings32(int argc, u32 * argv, struct linux_binprm *bprm)
{
while (argc-- > 0) {
u32 str;
int len;
unsigned long pos;
if (get_user(str, argv+argc) || !str ||
!(len = strnlen_user((char *)A(str), bprm->p)))
return -EFAULT;
if (bprm->p < len)
return -E2BIG;
bprm->p -= len;
/* XXX: add architecture specific overflow check here. */
pos = bprm->p;
while (len > 0) {
char *kaddr;
int i, new, err;
struct page *page;
int offset, bytes_to_copy;
offset = pos % PAGE_SIZE;
i = pos/PAGE_SIZE;
page = bprm->page[i];
new = 0;
if (!page) {
page = alloc_page(GFP_HIGHUSER);
bprm->page[i] = page;
if (!page)
return -ENOMEM;
new = 1;
}
kaddr = kmap(page);
if (new && offset)
memset(kaddr, 0, offset);
bytes_to_copy = PAGE_SIZE - offset;
if (bytes_to_copy > len) {
bytes_to_copy = len;
if (new)
memset(kaddr+offset+len, 0,
PAGE_SIZE-offset-len);
}
err = copy_from_user(kaddr + offset, (char *)A(str),
bytes_to_copy);
kunmap(page);
if (err)
return -EFAULT;
pos += bytes_to_copy;
str += bytes_to_copy;
len -= bytes_to_copy;
}
}
return 0;
}
/*
* sys_execve32() executes a new program.
*/
int do_execve32(char * filename, u32 * argv, u32 * envp, struct pt_regs * regs)
{
struct linux_binprm bprm;
struct dentry * dentry;
int retval;
int i;
bprm.p = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *);
memset(bprm.page, 0, MAX_ARG_PAGES*sizeof(bprm.page[0]));
dentry = open_namei(filename, 0, 0);
retval = PTR_ERR(dentry);
if (IS_ERR(dentry))
return retval;
bprm.dentry = dentry;
bprm.filename = filename;
bprm.sh_bang = 0;
bprm.loader = 0;
bprm.exec = 0;
if ((bprm.argc = count32(argv, bprm.p / sizeof(u32))) < 0) {
dput(dentry);
return bprm.argc;
}
if ((bprm.envc = count32(envp, bprm.p / sizeof(u32))) < 0) {
dput(dentry);
return bprm.envc;
}
retval = prepare_binprm(&bprm);
if (retval < 0)
goto out;
retval = copy_strings_kernel(1, &bprm.filename, &bprm);
if (retval < 0)
goto out;
bprm.exec = bprm.p;
retval = copy_strings32(bprm.envc, envp, &bprm);
if (retval < 0)
goto out;
retval = copy_strings32(bprm.argc, argv, &bprm);
if (retval < 0)
goto out;
retval = search_binary_handler(&bprm,regs);
if (retval >= 0)
/* execve success */
return retval;
out:
/* Something went wrong, return the inode and free the argument pages*/
if (bprm.dentry)
dput(bprm.dentry);
/* Assumes that free_page() can take a NULL argument. */
/* I hope this is ok for all architectures */
for (i = 0 ; i < MAX_ARG_PAGES ; i++)
if (bprm.page[i])
__free_page(bprm.page[i]);
return retval;
}
/*
* sys_execve() executes a new program.
*/
asmlinkage int sys32_execve(abi64_no_regargs, struct pt_regs regs)
{
int error;
char * filename;
filename = getname((char *) (long)regs.regs[4]);
printk("Executing: %s\n", filename);
error = PTR_ERR(filename);
if (IS_ERR(filename))
goto out;
error = do_execve32(filename, (u32 *) (long)regs.regs[5],
(u32 *) (long)regs.regs[6], ®s);
putname(filename);
out:
return error;
}
#else
static int nargs(unsigned int arg, char **ap)
{
unsigned int addr;
int n, err;
if (!arg)
return 0;
n = 0;
do {
err = get_user(addr, (unsigned int *)A(arg));
if (err)
return err;
if (ap)
*ap++ = (char *) A(addr);
arg += sizeof(unsigned int);
n++;
if (n >= (MAX_ARG_PAGES * PAGE_SIZE) / sizeof(char *))
return -E2BIG;
} while (addr);
return n - 1;
}
asmlinkage int
sys32_execve(abi64_no_regargs, struct pt_regs regs)
{
extern asmlinkage int sys_execve(abi64_no_regargs, struct pt_regs regs);
extern asmlinkage long sys_munmap(unsigned long addr, size_t len);
unsigned int argv = (unsigned int)regs.regs[5];
unsigned int envp = (unsigned int)regs.regs[6];
char **av, **ae;
int na, ne, r, len;
char * filename;
na = nargs(argv, NULL);
if (na < 0)
return na;
ne = nargs(envp, NULL);
if (ne < 0)
return ne;
len = (na + ne + 2) * sizeof(*av);
/*
* kmalloc won't work because the `sys_exec' code will attempt
* to do a `get_user' on the arg list and `get_user' will fail
* on a kernel address (simplifies `get_user'). Instead we
* do an mmap to get a user address. Note that since a successful
* `execve' frees all current memory we only have to do an
* `munmap' if the `execve' fails.
*/
down_write(¤t->mm->mmap_sem);
av = (char **) do_mmap_pgoff(0, 0, len, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0);
up_write(¤t->mm->mmap_sem);
if (IS_ERR(av))
return (long) av;
ae = av + na + 1;
r = __put_user(0, (av + na));
r |= __put_user(0, (ae + ne));
if (r)
goto out;
r = nargs(argv, av);
if (r < 0)
goto out;
r = nargs(envp, ae);
if (r < 0)
goto out;
filename = getname((char *) (long)regs.regs[4]);
r = PTR_ERR(filename);
if (IS_ERR(filename))
goto out;
r = do_execve(filename, av, ae, ®s);
putname(filename);
if (r)
out:
sys_munmap((unsigned long)av, len);
return r ;
}
#endif
struct dirent32 {
unsigned int d_ino;
unsigned int d_off;
unsigned short d_reclen;
char d_name[NAME_MAX + 1];
};
static void
xlate_dirent(void *dirent64, void *dirent32, long n)
{
long off;
struct dirent *dirp;
struct dirent32 *dirp32;
off = 0;
while (off < n) {
dirp = (struct dirent *)(dirent64 + off);
dirp32 = (struct dirent32 *)(dirent32 + off);
off += dirp->d_reclen;
dirp32->d_ino = dirp->d_ino;
dirp32->d_off = (unsigned int)dirp->d_off;
dirp32->d_reclen = dirp->d_reclen;
strncpy(dirp32->d_name, dirp->d_name, dirp->d_reclen - ((3 * 4) + 2));
}
return;
}
asmlinkage long sys_getdents(unsigned int fd, void * dirent, unsigned int count);
asmlinkage long
sys32_getdents(unsigned int fd, void * dirent32, unsigned int count)
{
long n;
void *dirent64;
dirent64 = (void *)((unsigned long)(dirent32 + (sizeof(long) - 1)) & ~(sizeof(long) - 1));
if ((n = sys_getdents(fd, dirent64, count - (dirent64 - dirent32))) < 0)
return(n);
xlate_dirent(dirent64, dirent32, n);
return(n);
}
asmlinkage int old_readdir(unsigned int fd, void * dirent, unsigned int count);
asmlinkage int
sys32_readdir(unsigned int fd, void * dirent32, unsigned int count)
{
int n;
struct dirent dirent64;
if ((n = old_readdir(fd, &dirent64, count)) < 0)
return(n);
xlate_dirent(&dirent64, dirent32, dirent64.d_reclen);
return(n);
}
struct timeval32
{
int tv_sec, tv_usec;
};
struct itimerval32
{
struct timeval32 it_interval;
struct timeval32 it_value;
};
struct rusage32 {
struct timeval32 ru_utime;
struct timeval32 ru_stime;
int ru_maxrss;
int ru_ixrss;
int ru_idrss;
int ru_isrss;
int ru_minflt;
int ru_majflt;
int ru_nswap;
int ru_inblock;
int ru_oublock;
int ru_msgsnd;
int ru_msgrcv;
int ru_nsignals;
int ru_nvcsw;
int ru_nivcsw;
};
static int
put_rusage (struct rusage32 *ru, struct rusage *r)
{
int err;
if (verify_area(VERIFY_WRITE, ru, sizeof *ru))
return -EFAULT;
err = __put_user (r->ru_utime.tv_sec, &ru->ru_utime.tv_sec);
err |= __put_user (r->ru_utime.tv_usec, &ru->ru_utime.tv_usec);
err |= __put_user (r->ru_stime.tv_sec, &ru->ru_stime.tv_sec);
err |= __put_user (r->ru_stime.tv_usec, &ru->ru_stime.tv_usec);
err |= __put_user (r->ru_maxrss, &ru->ru_maxrss);
err |= __put_user (r->ru_ixrss, &ru->ru_ixrss);
err |= __put_user (r->ru_idrss, &ru->ru_idrss);
err |= __put_user (r->ru_isrss, &ru->ru_isrss);
err |= __put_user (r->ru_minflt, &ru->ru_minflt);
err |= __put_user (r->ru_majflt, &ru->ru_majflt);
err |= __put_user (r->ru_nswap, &ru->ru_nswap);
err |= __put_user (r->ru_inblock, &ru->ru_inblock);
err |= __put_user (r->ru_oublock, &ru->ru_oublock);
err |= __put_user (r->ru_msgsnd, &ru->ru_msgsnd);
err |= __put_user (r->ru_msgrcv, &ru->ru_msgrcv);
err |= __put_user (r->ru_nsignals, &ru->ru_nsignals);
err |= __put_user (r->ru_nvcsw, &ru->ru_nvcsw);
err |= __put_user (r->ru_nivcsw, &ru->ru_nivcsw);
return err;
}
asmlinkage int
sys32_wait4(__kernel_pid_t32 pid, unsigned int * stat_addr, int options,
struct rusage32 * ru)
{
if (!ru)
return sys_wait4(pid, stat_addr, options, NULL);
else {
struct rusage r;
int ret;
unsigned int status;
mm_segment_t old_fs = get_fs();
set_fs(KERNEL_DS);
ret = sys_wait4(pid, stat_addr ? &status : NULL, options, &r);
set_fs(old_fs);
if (put_rusage (ru, &r)) return -EFAULT;
if (stat_addr && put_user (status, stat_addr))
return -EFAULT;
return ret;
}
}
asmlinkage int
sys32_waitpid(__kernel_pid_t32 pid, unsigned int *stat_addr, int options)
{
return sys32_wait4(pid, stat_addr, options, NULL);
}
struct sysinfo32 {
s32 uptime;
u32 loads[3];
u32 totalram;
u32 freeram;
u32 sharedram;
u32 bufferram;
u32 totalswap;
u32 freeswap;
u16 procs;
u32 totalhigh;
u32 freehigh;
u32 mem_unit;
char _f[8];
};
extern asmlinkage int sys_sysinfo(struct sysinfo *info);
asmlinkage int sys32_sysinfo(struct sysinfo32 *info)
{
struct sysinfo s;
int ret, err;
mm_segment_t old_fs = get_fs ();
set_fs (KERNEL_DS);
ret = sys_sysinfo(&s);
set_fs (old_fs);
err = put_user (s.uptime, &info->uptime);
err |= __put_user (s.loads[0], &info->loads[0]);
err |= __put_user (s.loads[1], &info->loads[1]);
err |= __put_user (s.loads[2], &info->loads[2]);
err |= __put_user (s.totalram, &info->totalram);
err |= __put_user (s.freeram, &info->freeram);
err |= __put_user (s.sharedram, &info->sharedram);
err |= __put_user (s.bufferram, &info->bufferram);
err |= __put_user (s.totalswap, &info->totalswap);
err |= __put_user (s.freeswap, &info->freeswap);
err |= __put_user (s.procs, &info->procs);
err |= __put_user (s.totalhigh, &info->totalhigh);
err |= __put_user (s.freehigh, &info->freehigh);
err |= __put_user (s.mem_unit, &info->mem_unit);
if (err)
return -EFAULT;
return ret;
}
#define RLIM_INFINITY32 0x7fffffff
#define RESOURCE32(x) ((x > RLIM_INFINITY32) ? RLIM_INFINITY32 : x)
struct rlimit32 {
int rlim_cur;
int rlim_max;
};
extern asmlinkage int sys_old_getrlimit(unsigned int resource, struct rlimit *rlim);
asmlinkage int
sys32_getrlimit(unsigned int resource, struct rlimit32 *rlim)
{
struct rlimit r;
int ret;
mm_segment_t old_fs = get_fs ();
set_fs (KERNEL_DS);
ret = sys_old_getrlimit(resource, &r);
set_fs (old_fs);
if (!ret) {
ret = put_user (RESOURCE32(r.rlim_cur), &rlim->rlim_cur);
ret |= __put_user (RESOURCE32(r.rlim_max), &rlim->rlim_max);
}
return ret;
}
extern asmlinkage int sys_setrlimit(unsigned int resource, struct rlimit *rlim);
asmlinkage int
sys32_setrlimit(unsigned int resource, struct rlimit32 *rlim)
{
struct rlimit r;
int ret;
mm_segment_t old_fs = get_fs ();
if (resource >= RLIM_NLIMITS) return -EINVAL;
if (get_user (r.rlim_cur, &rlim->rlim_cur) ||
__get_user (r.rlim_max, &rlim->rlim_max))
return -EFAULT;
if (r.rlim_cur == RLIM_INFINITY32)
r.rlim_cur = RLIM_INFINITY;
if (r.rlim_max == RLIM_INFINITY32)
r.rlim_max = RLIM_INFINITY;
set_fs (KERNEL_DS);
ret = sys_setrlimit(resource, &r);
set_fs (old_fs);
return ret;
}
struct statfs32 {
int f_type;
int f_bsize;
int f_frsize;
int f_blocks;
int f_bfree;
int f_files;
int f_ffree;
int f_bavail;
__kernel_fsid_t32 f_fsid;
int f_namelen;
int f_spare[6];
};
static inline int
put_statfs (struct statfs32 *ubuf, struct statfs *kbuf)
{
int err;
err = put_user (kbuf->f_type, &ubuf->f_type);
err |= __put_user (kbuf->f_bsize, &ubuf->f_bsize);
err |= __put_user (kbuf->f_blocks, &ubuf->f_blocks);
err |= __put_user (kbuf->f_bfree, &ubuf->f_bfree);
err |= __put_user (kbuf->f_bavail, &ubuf->f_bavail);
err |= __put_user (kbuf->f_files, &ubuf->f_files);
err |= __put_user (kbuf->f_ffree, &ubuf->f_ffree);
err |= __put_user (kbuf->f_namelen, &ubuf->f_namelen);
err |= __put_user (kbuf->f_fsid.val[0], &ubuf->f_fsid.val[0]);
err |= __put_user (kbuf->f_fsid.val[1], &ubuf->f_fsid.val[1]);
return err;
}
extern asmlinkage int sys_statfs(const char * path, struct statfs * buf);
asmlinkage int
sys32_statfs(const char * path, struct statfs32 *buf)
{
int ret;
struct statfs s;
mm_segment_t old_fs = get_fs();
char *pth;
pth = getname (path);
ret = PTR_ERR(pth);
if (!IS_ERR(pth)) {
set_fs (KERNEL_DS);
ret = sys_statfs((const char *)path, &s);
set_fs (old_fs);
if (!ret && put_statfs(buf, &s))
return -EFAULT;
}
return ret;
}
extern asmlinkage int sys_fstatfs(unsigned int fd, struct statfs * buf);
asmlinkage int
sys32_fstatfs(unsigned int fd, struct statfs32 *buf)
{
int ret;
struct statfs s;
mm_segment_t old_fs = get_fs();
set_fs (KERNEL_DS);
ret = sys_fstatfs(fd, &s);
set_fs (old_fs);
if (put_statfs(buf, &s))
return -EFAULT;
return ret;
}
#ifdef __MIPSEB__
asmlinkage long sys32_truncate64(const char * path, unsigned long __dummy,
int length_hi, int length_lo)
#endif
#ifdef __MIPSEL__
asmlinkage long sys32_truncate64(const char * path, unsigned long __dummy,
int length_lo, int length_hi)
#endif
{
loff_t length;
length = ((unsigned long) length_hi << 32) | (unsigned int) length_lo;
return sys_truncate(path, length);
}
#ifdef __MIPSEB__
asmlinkage long sys32_ftruncate64(unsigned int fd, unsigned long __dummy,
int length_hi, int length_lo)
#endif
#ifdef __MIPSEL__
asmlinkage long sys32_ftruncate64(unsigned int fd, unsigned long __dummy,
int length_lo, int length_hi)
#endif
{
loff_t length;
length = ((unsigned long) length_hi << 32) | (unsigned int) length_lo;
return sys_ftruncate(fd, length);
}
extern asmlinkage int
sys_getrusage(int who, struct rusage *ru);
asmlinkage int
sys32_getrusage(int who, struct rusage32 *ru)
{
struct rusage r;
int ret;
mm_segment_t old_fs = get_fs();
set_fs (KERNEL_DS);
ret = sys_getrusage(who, &r);
set_fs (old_fs);
if (put_rusage (ru, &r))
return -EFAULT;
return ret;
}
static inline long
get_tv32(struct timeval *o, struct timeval32 *i)
{
return (!access_ok(VERIFY_READ, i, sizeof(*i)) ||
(__get_user(o->tv_sec, &i->tv_sec) |
__get_user(o->tv_usec, &i->tv_usec)));
}
static inline long
get_it32(struct itimerval *o, struct itimerval32 *i)
{
return (!access_ok(VERIFY_READ, i, sizeof(*i)) ||
(__get_user(o->it_interval.tv_sec, &i->it_interval.tv_sec) |
__get_user(o->it_interval.tv_usec, &i->it_interval.tv_usec) |
__get_user(o->it_value.tv_sec, &i->it_value.tv_sec) |
__get_user(o->it_value.tv_usec, &i->it_value.tv_usec)));
}
static inline long
put_tv32(struct timeval32 *o, struct timeval *i)
{
return (!access_ok(VERIFY_WRITE, o, sizeof(*o)) ||
(__put_user(i->tv_sec, &o->tv_sec) |
__put_user(i->tv_usec, &o->tv_usec)));
}
static inline long
put_it32(struct itimerval32 *o, struct itimerval *i)
{
return (!access_ok(VERIFY_WRITE, o, sizeof(*o)) ||
(__put_user(i->it_interval.tv_sec, &o->it_interval.tv_sec) |
__put_user(i->it_interval.tv_usec, &o->it_interval.tv_usec) |
__put_user(i->it_value.tv_sec, &o->it_value.tv_sec) |
__put_user(i->it_value.tv_usec, &o->it_value.tv_usec)));
}
extern int do_getitimer(int which, struct itimerval *value);
asmlinkage int
sys32_getitimer(int which, struct itimerval32 *it)
{
struct itimerval kit;
int error;
error = do_getitimer(which, &kit);
if (!error && put_it32(it, &kit))
error = -EFAULT;
return error;
}
extern int do_setitimer(int which, struct itimerval *, struct itimerval *);
asmlinkage int
sys32_setitimer(int which, struct itimerval32 *in, struct itimerval32 *out)
{
struct itimerval kin, kout;
int error;
if (in) {
if (get_it32(&kin, in))
return -EFAULT;
} else
memset(&kin, 0, sizeof(kin));
error = do_setitimer(which, &kin, out ? &kout : NULL);
if (error || !out)
return error;
if (put_it32(out, &kout))
return -EFAULT;
return 0;
}
/* Translations due to time_t size differences. Which affects all
sorts of things, like timeval and itimerval. */
extern struct timezone sys_tz;
extern int do_sys_settimeofday(struct timeval *tv, struct timezone *tz);
asmlinkage int
sys32_gettimeofday(struct timeval32 *tv, struct timezone *tz)
{
if (tv) {
struct timeval ktv;
do_gettimeofday(&ktv);
if (put_tv32(tv, &ktv))
return -EFAULT;
}
if (tz) {
if (copy_to_user(tz, &sys_tz, sizeof(sys_tz)))
return -EFAULT;
}
return 0;
}
asmlinkage int
sys32_settimeofday(struct timeval32 *tv, struct timezone *tz)
{
struct timeval ktv;
struct timezone ktz;
if (tv) {
if (get_tv32(&ktv, tv))
return -EFAULT;
}
if (tz) {
if (copy_from_user(&ktz, tz, sizeof(ktz)))
return -EFAULT;
}
return do_sys_settimeofday(tv ? &ktv : NULL, tz ? &ktz : NULL);
}
extern asmlinkage long sys_llseek(unsigned int fd, unsigned long offset_high,
unsigned long offset_low, loff_t * result,
unsigned int origin);
asmlinkage int sys32_llseek(unsigned int fd, unsigned int offset_high,
unsigned int offset_low, loff_t * result,
unsigned int origin)
{
return sys_llseek(fd, offset_high, offset_low, result, origin);
}
struct iovec32 { unsigned int iov_base; int iov_len; };
typedef ssize_t (*IO_fn_t)(struct file *, char *, size_t, loff_t *);
static long
do_readv_writev32(int type, struct file *file, const struct iovec32 *vector,
u32 count)
{
unsigned long tot_len;
struct iovec iovstack[UIO_FASTIOV];
struct iovec *iov=iovstack, *ivp;
struct inode *inode;
long retval, i;
IO_fn_t fn;
/* First get the "struct iovec" from user memory and
* verify all the pointers
*/
if (!count)
return 0;
if(verify_area(VERIFY_READ, vector, sizeof(struct iovec32)*count))
return -EFAULT;
if (count > UIO_MAXIOV)
return -EINVAL;
if (count > UIO_FASTIOV) {
iov = kmalloc(count*sizeof(struct iovec), GFP_KERNEL);
if (!iov)
return -ENOMEM;
}
tot_len = 0;
i = count;
ivp = iov;
while (i > 0) {
u32 len;
u32 buf;
__get_user(len, &vector->iov_len);
__get_user(buf, &vector->iov_base);
tot_len += len;
ivp->iov_base = (void *)A(buf);
ivp->iov_len = (__kernel_size_t) len;
vector++;
ivp++;
i--;
}
/* VERIFY_WRITE actually means a read, as we write to user space */
retval = rw_verify_area((type == VERIFY_WRITE ? READ : WRITE),
file, &file->f_pos, tot_len);
if (retval) {
if (iov != iovstack)
kfree(iov);
return retval;
}
/* Then do the actual IO. Note that sockets need to be handled
* specially as they have atomicity guarantees and can handle
* iovec's natively
*/
if (inode->i_sock) {
int err;
err = sock_readv_writev(type, inode, file, iov, count, tot_len);
if (iov != iovstack)
kfree(iov);
return err;
}
if (!file->f_op) {
if (iov != iovstack)
kfree(iov);
return -EINVAL;
}
/* VERIFY_WRITE actually means a read, as we write to user space */
fn = file->f_op->read;
if (type == VERIFY_READ)
fn = (IO_fn_t) file->f_op->write;
ivp = iov;
while (count > 0) {
void * base;
int len, nr;
base = ivp->iov_base;
len = ivp->iov_len;
ivp++;
count--;
nr = fn(file, base, len, &file->f_pos);
if (nr < 0) {
if (retval)
break;
retval = nr;
break;
}
retval += nr;
if (nr != len)
break;
}
if (iov != iovstack)
kfree(iov);
return retval;
}
asmlinkage long
sys32_readv(int fd, struct iovec32 *vector, u32 count)
{
struct file *file;
ssize_t ret;
ret = -EBADF;
file = fget(fd);
if (!file)
goto bad_file;
if (file->f_op && (file->f_mode & FMODE_READ) &&
(file->f_op->readv || file->f_op->read))
ret = do_readv_writev32(VERIFY_WRITE, file, vector, count);
fput(file);
bad_file:
return ret;
}
asmlinkage long
sys32_writev(int fd, struct iovec32 *vector, u32 count)
{
struct file *file;
ssize_t ret;
ret = -EBADF;
file = fget(fd);
if(!file)
goto bad_file;
if (file->f_op && (file->f_mode & FMODE_WRITE) &&
(file->f_op->writev || file->f_op->write))
ret = do_readv_writev32(VERIFY_READ, file, vector, count);
fput(file);
bad_file:
return ret;
}
/* From the Single Unix Spec: pread & pwrite act like lseek to pos + op +
lseek back to original location. They fail just like lseek does on
non-seekable files. */
asmlinkage ssize_t sys32_pread(unsigned int fd, char * buf,
size_t count, u32 unused, u64 a4, u64 a5)
{
ssize_t ret;
struct file * file;
ssize_t (*read)(struct file *, char *, size_t, loff_t *);
loff_t pos;
ret = -EBADF;
file = fget(fd);
if (!file)
goto bad_file;
if (!(file->f_mode & FMODE_READ))
goto out;
pos = merge_64(a4, a5);
ret = locks_verify_area(FLOCK_VERIFY_READ, file->f_dentry->d_inode,
file, pos, count);
if (ret)
goto out;
ret = -EINVAL;
if (!file->f_op || !(read = file->f_op->read))
goto out;
if (pos < 0)
goto out;
ret = read(file, buf, count, &pos);
if (ret > 0)
dnotify_parent(file->f_dentry, DN_ACCESS);
out:
fput(file);
bad_file:
return ret;
}
asmlinkage ssize_t sys32_pwrite(unsigned int fd, const char * buf,
size_t count, u32 unused, u64 a4, u64 a5)
{
ssize_t ret;
struct file * file;
ssize_t (*write)(struct file *, const char *, size_t, loff_t *);
loff_t pos;
ret = -EBADF;
file = fget(fd);
if (!file)
goto bad_file;
if (!(file->f_mode & FMODE_WRITE))
goto out;
pos = merge_64(a4, a5);
ret = locks_verify_area(FLOCK_VERIFY_WRITE, file->f_dentry->d_inode,
file, pos, count);
if (ret)
goto out;
ret = -EINVAL;
if (!file->f_op || !(write = file->f_op->write))
goto out;
if (pos < 0)
goto out;
ret = write(file, buf, count, &pos);
if (ret > 0)
dnotify_parent(file->f_dentry, DN_MODIFY);
out:
fput(file);
bad_file:
return ret;
}
/*
* Ooo, nasty. We need here to frob 32-bit unsigned longs to
* 64-bit unsigned longs.
*/
static inline int
get_fd_set32(unsigned long n, unsigned long *fdset, u32 *ufdset)
{
if (ufdset) {
unsigned long odd;
if (verify_area(VERIFY_WRITE, ufdset, n*sizeof(u32)))
return -EFAULT;
odd = n & 1UL;
n &= ~1UL;
while (n) {
unsigned long h, l;
__get_user(l, ufdset);
__get_user(h, ufdset+1);
ufdset += 2;
*fdset++ = h << 32 | l;
n -= 2;
}
if (odd)
__get_user(*fdset, ufdset);
} else {
/* Tricky, must clear full unsigned long in the
* kernel fdset at the end, this makes sure that
* actually happens.
*/
memset(fdset, 0, ((n + 1) & ~1)*sizeof(u32));
}
return 0;
}
static inline void
set_fd_set32(unsigned long n, u32 *ufdset, unsigned long *fdset)
{
unsigned long odd;
if (!ufdset)
return;
odd = n & 1UL;
n &= ~1UL;
while (n) {
unsigned long h, l;
l = *fdset++;
h = l >> 32;
__put_user(l, ufdset);
__put_user(h, ufdset+1);
ufdset += 2;
n -= 2;
}
if (odd)
__put_user(*fdset, ufdset);
}
/*
* We can actually return ERESTARTSYS instead of EINTR, but I'd
* like to be certain this leads to no problems. So I return
* EINTR just for safety.
*
* Update: ERESTARTSYS breaks at least the xview clock binary, so
* I'm trying ERESTARTNOHAND which restart only when you want to.
*/
#define MAX_SELECT_SECONDS \
((unsigned long) (MAX_SCHEDULE_TIMEOUT / HZ)-1)
asmlinkage int sys32_select(int n, u32 *inp, u32 *outp, u32 *exp, struct timeval32 *tvp)
{
fd_set_bits fds;
char *bits;
unsigned long nn;
long timeout;
int ret, size;
timeout = MAX_SCHEDULE_TIMEOUT;
if (tvp) {
time_t sec, usec;
if ((ret = verify_area(VERIFY_READ, tvp, sizeof(*tvp)))
|| (ret = __get_user(sec, &tvp->tv_sec))
|| (ret = __get_user(usec, &tvp->tv_usec)))
goto out_nofds;
ret = -EINVAL;
if(sec < 0 || usec < 0)
goto out_nofds;
if ((unsigned long) sec < MAX_SELECT_SECONDS) {
timeout = (usec + 1000000/HZ - 1) / (1000000/HZ);
timeout += sec * (unsigned long) HZ;
}
}
ret = -EINVAL;
if (n < 0)
goto out_nofds;
if (n > current->files->max_fdset)
n = current->files->max_fdset;
/*
* We need 6 bitmaps (in/out/ex for both incoming and outgoing),
* since we used fdset we need to allocate memory in units of
* long-words.
*/
ret = -ENOMEM;
size = FDS_BYTES(n);
bits = kmalloc(6 * size, GFP_KERNEL);
if (!bits)
goto out_nofds;
fds.in = (unsigned long *) bits;
fds.out = (unsigned long *) (bits + size);
fds.ex = (unsigned long *) (bits + 2*size);
fds.res_in = (unsigned long *) (bits + 3*size);
fds.res_out = (unsigned long *) (bits + 4*size);
fds.res_ex = (unsigned long *) (bits + 5*size);
nn = (n + 8*sizeof(u32) - 1) / (8*sizeof(u32));
if ((ret = get_fd_set32(nn, fds.in, inp)) ||
(ret = get_fd_set32(nn, fds.out, outp)) ||
(ret = get_fd_set32(nn, fds.ex, exp)))
goto out;
zero_fd_set(n, fds.res_in);
zero_fd_set(n, fds.res_out);
zero_fd_set(n, fds.res_ex);
ret = do_select(n, &fds, &timeout);
if (tvp && !(current->personality & STICKY_TIMEOUTS)) {
time_t sec = 0, usec = 0;
if (timeout) {
sec = timeout / HZ;
usec = timeout % HZ;
usec *= (1000000/HZ);
}
put_user(sec, &tvp->tv_sec);
put_user(usec, &tvp->tv_usec);
}
if (ret < 0)
goto out;
if (!ret) {
ret = -ERESTARTNOHAND;
if (signal_pending(current))
goto out;
ret = 0;
}
set_fd_set32(nn, inp, fds.res_in);
set_fd_set32(nn, outp, fds.res_out);
set_fd_set32(nn, exp, fds.res_ex);
out:
kfree(bits);
out_nofds:
return ret;
}
struct timespec32 {
int tv_sec;
int tv_nsec;
};
extern asmlinkage int sys_sched_rr_get_interval(pid_t pid,
struct timespec *interval);
asmlinkage int
sys32_sched_rr_get_interval(__kernel_pid_t32 pid, struct timespec32 *interval)
{
struct timespec t;
int ret;
mm_segment_t old_fs = get_fs ();
set_fs (KERNEL_DS);
ret = sys_sched_rr_get_interval(pid, &t);
set_fs (old_fs);
if (put_user (t.tv_sec, &interval->tv_sec) ||
__put_user (t.tv_nsec, &interval->tv_nsec))
return -EFAULT;
return ret;
}
extern asmlinkage int sys_nanosleep(struct timespec *rqtp,
struct timespec *rmtp);
asmlinkage int
sys32_nanosleep(struct timespec32 *rqtp, struct timespec32 *rmtp)
{
struct timespec t;
int ret;
mm_segment_t old_fs = get_fs ();
if (get_user (t.tv_sec, &rqtp->tv_sec) ||
__get_user (t.tv_nsec, &rqtp->tv_nsec))
return -EFAULT;
set_fs (KERNEL_DS);
ret = sys_nanosleep(&t, rmtp ? &t : NULL);
set_fs (old_fs);
if (rmtp && ret == -EINTR) {
if (__put_user (t.tv_sec, &rmtp->tv_sec) ||
__put_user (t.tv_nsec, &rmtp->tv_nsec))
return -EFAULT;
}
return ret;
}
struct tms32 {
int tms_utime;
int tms_stime;
int tms_cutime;
int tms_cstime;
};
extern asmlinkage long sys_times(struct tms * tbuf);
asmlinkage long sys32_times(struct tms32 *tbuf)
{
struct tms t;
long ret;
mm_segment_t old_fs = get_fs();
int err;
set_fs(KERNEL_DS);
ret = sys_times(tbuf ? &t : NULL);
set_fs(old_fs);
if (tbuf) {
err = put_user (t.tms_utime, &tbuf->tms_utime);
err |= __put_user (t.tms_stime, &tbuf->tms_stime);
err |= __put_user (t.tms_cutime, &tbuf->tms_cutime);
err |= __put_user (t.tms_cstime, &tbuf->tms_cstime);
if (err)
ret = -EFAULT;
}
return ret;
}
static int do_set_attach_filter(int fd, int level, int optname,
char *optval, int optlen)
{
struct sock_fprog32 {
__u16 len;
__u32 filter;
} *fprog32 = (struct sock_fprog32 *)optval;
struct sock_fprog kfprog;
struct sock_filter *kfilter;
unsigned int fsize;
mm_segment_t old_fs;
__u32 uptr;
int ret;
if (get_user(kfprog.len, &fprog32->len) ||
__get_user(uptr, &fprog32->filter))
return -EFAULT;
kfprog.filter = (struct sock_filter *)A(uptr);
fsize = kfprog.len * sizeof(struct sock_filter);
kfilter = (struct sock_filter *)kmalloc(fsize, GFP_KERNEL);
if (kfilter == NULL)
return -ENOMEM;
if (copy_from_user(kfilter, kfprog.filter, fsize)) {
kfree(kfilter);
return -EFAULT;
}
kfprog.filter = kfilter;
old_fs = get_fs();
set_fs(KERNEL_DS);
ret = sys_setsockopt(fd, level, optname,
(char *)&kfprog, sizeof(kfprog));
set_fs(old_fs);
kfree(kfilter);
return ret;
}
static int do_set_icmpv6_filter(int fd, int level, int optname,
char *optval, int optlen)
{
struct icmp6_filter kfilter;
mm_segment_t old_fs;
int ret, i;
if (copy_from_user(&kfilter, optval, sizeof(kfilter)))
return -EFAULT;
for (i = 0; i < 8; i += 2) {
u32 tmp = kfilter.data[i];
kfilter.data[i] = kfilter.data[i + 1];
kfilter.data[i + 1] = tmp;
}
old_fs = get_fs();
set_fs(KERNEL_DS);
ret = sys_setsockopt(fd, level, optname,
(char *) &kfilter, sizeof(kfilter));
set_fs(old_fs);
return ret;
}
asmlinkage int sys32_setsockopt(int fd, int level, int optname,
char *optval, int optlen)
{
if (level == SOL_SOCKET && optname == SO_ATTACH_FILTER)
return do_set_attach_filter(fd, level, optname,
optval, optlen);
if (level == SOL_ICMPV6 && optname == ICMPV6_FILTER)
return do_set_icmpv6_filter(fd, level, optname,
optval, optlen);
return sys_setsockopt(fd, level, optname, optval, optlen);
}
static inline int get_flock(struct flock *kfl, struct flock32 *ufl)
{
int err;
if (!access_ok(VERIFY_READ, ufl, sizeof(*ufl)))
return -EFAULT;
err = __get_user(kfl->l_type, &ufl->l_type);
err |= __get_user(kfl->l_whence, &ufl->l_whence);
err |= __get_user(kfl->l_start, &ufl->l_start);
err |= __get_user(kfl->l_len, &ufl->l_len);
err |= __get_user(kfl->l_pid, &ufl->l_pid);
return err;
}
static inline int put_flock(struct flock *kfl, struct flock32 *ufl)
{
int err;
if (!access_ok(VERIFY_WRITE, ufl, sizeof(*ufl)))
return -EFAULT;
err = __put_user(kfl->l_type, &ufl->l_type);
err |= __put_user(kfl->l_whence, &ufl->l_whence);
err |= __put_user(kfl->l_start, &ufl->l_start);
err |= __put_user(kfl->l_len, &ufl->l_len);
err |= __put_user(0, &ufl->l_sysid);
err |= __put_user(kfl->l_pid, &ufl->l_pid);
return err;
}
extern asmlinkage long
sys_fcntl(unsigned int fd, unsigned int cmd, unsigned long arg);
asmlinkage long
sys32_fcntl(unsigned int fd, unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case F_GETLK:
case F_SETLK:
case F_SETLKW:
{
struct flock f;
mm_segment_t old_fs;
long ret;
if (get_flock(&f, (struct flock32 *)arg))
return -EFAULT;
old_fs = get_fs(); set_fs (KERNEL_DS);
ret = sys_fcntl(fd, cmd, (unsigned long)&f);
set_fs (old_fs);
if (put_flock(&f, (struct flock32 *)arg))
return -EFAULT;
return ret;
}
default:
return sys_fcntl(fd, cmd, (unsigned long)arg);
}
}
asmlinkage long
sys32_fcntl64(unsigned int fd, unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case F_GETLK64:
return sys_fcntl(fd, F_GETLK, arg);
case F_SETLK64:
return sys_fcntl(fd, F_SETLK, arg);
case F_SETLKW64:
return sys_fcntl(fd, F_SETLKW, arg);
}
return sys32_fcntl(fd, cmd, arg);
}
struct msgbuf32 { s32 mtype; char mtext[1]; };
struct ipc_perm32
{
key_t key;
__kernel_uid_t32 uid;
__kernel_gid_t32 gid;
__kernel_uid_t32 cuid;
__kernel_gid_t32 cgid;
__kernel_mode_t32 mode;
unsigned short seq;
};
struct ipc64_perm32 {
key_t key;
__kernel_uid_t32 uid;
__kernel_gid_t32 gid;
__kernel_uid_t32 cuid;
__kernel_gid_t32 cgid;
__kernel_mode_t32 mode;
unsigned short seq;
unsigned short __pad1;
unsigned int __unused1;
unsigned int __unused2;
};
struct semid_ds32 {
struct ipc_perm32 sem_perm; /* permissions .. see ipc.h */
__kernel_time_t32 sem_otime; /* last semop time */
__kernel_time_t32 sem_ctime; /* last change time */
u32 sem_base; /* ptr to first semaphore in array */
u32 sem_pending; /* pending operations to be processed */
u32 sem_pending_last; /* last pending operation */
u32 undo; /* undo requests on this array */
unsigned short sem_nsems; /* no. of semaphores in array */
};
struct semid64_ds32 {
struct ipc64_perm32 sem_perm;
__kernel_time_t32 sem_otime;
__kernel_time_t32 sem_ctime;
unsigned int sem_nsems;
unsigned int __unused1;
unsigned int __unused2;
};
struct msqid_ds32
{
struct ipc_perm32 msg_perm;
u32 msg_first;
u32 msg_last;
__kernel_time_t32 msg_stime;
__kernel_time_t32 msg_rtime;
__kernel_time_t32 msg_ctime;
u32 wwait;
u32 rwait;
unsigned short msg_cbytes;
unsigned short msg_qnum;
unsigned short msg_qbytes;
__kernel_ipc_pid_t32 msg_lspid;
__kernel_ipc_pid_t32 msg_lrpid;
};
struct msqid64_ds32 {
struct ipc64_perm32 msg_perm;
__kernel_time_t32 msg_stime;
unsigned int __unused1;
__kernel_time_t32 msg_rtime;
unsigned int __unused2;
__kernel_time_t32 msg_ctime;
unsigned int __unused3;
unsigned int msg_cbytes;
unsigned int msg_qnum;
unsigned int msg_qbytes;
__kernel_pid_t32 msg_lspid;
__kernel_pid_t32 msg_lrpid;
unsigned int __unused4;
unsigned int __unused5;
};
struct shmid_ds32 {
struct ipc_perm32 shm_perm;
int shm_segsz;
__kernel_time_t32 shm_atime;
__kernel_time_t32 shm_dtime;
__kernel_time_t32 shm_ctime;
__kernel_ipc_pid_t32 shm_cpid;
__kernel_ipc_pid_t32 shm_lpid;
unsigned short shm_nattch;
};
struct shmid64_ds32 {
struct ipc64_perm32 shm_perm;
__kernel_size_t32 shm_segsz;
__kernel_time_t32 shm_atime;
__kernel_time_t32 shm_dtime;
__kernel_time_t32 shm_ctime;
__kernel_pid_t32 shm_cpid;
__kernel_pid_t32 shm_lpid;
unsigned int shm_nattch;
unsigned int __unused1;
unsigned int __unused2;
};
struct ipc_kludge32 {
u32 msgp;
s32 msgtyp;
};
static int
do_sys32_semctl(int first, int second, int third, void *uptr)
{
union semun fourth;
u32 pad;
int err, err2;
struct semid64_ds s;
mm_segment_t old_fs;
if (!uptr)
return -EINVAL;
err = -EFAULT;
if (get_user (pad, (u32 *)uptr))
return err;
if ((third & ~IPC_64) == SETVAL)
fourth.val = (int)pad;
else
fourth.__pad = (void *)A(pad);
switch (third & ~IPC_64) {
case IPC_INFO:
case IPC_RMID:
case IPC_SET:
case SEM_INFO:
case GETVAL:
case GETPID:
case GETNCNT:
case GETZCNT:
case GETALL:
case SETVAL:
case SETALL:
err = sys_semctl (first, second, third, fourth);
break;
case IPC_STAT:
case SEM_STAT:
fourth.__pad = &s;
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sys_semctl(first, second, third | IPC_64, fourth);
set_fs(old_fs);
if (third & IPC_64) {
struct semid64_ds32 *usp64 = (struct semid64_ds32 *) A(pad);
if (!access_ok(VERIFY_WRITE, usp64, sizeof(*usp64))) {
err = -EFAULT;
break;
}
err2 = __put_user(s.sem_perm.key, &usp64->sem_perm.key);
err2 |= __put_user(s.sem_perm.uid, &usp64->sem_perm.uid);
err2 |= __put_user(s.sem_perm.gid, &usp64->sem_perm.gid);
err2 |= __put_user(s.sem_perm.cuid, &usp64->sem_perm.cuid);
err2 |= __put_user(s.sem_perm.cgid, &usp64->sem_perm.cgid);
err2 |= __put_user(s.sem_perm.mode, &usp64->sem_perm.mode);
err2 |= __put_user(s.sem_perm.seq, &usp64->sem_perm.seq);
err2 |= __put_user(s.sem_otime, &usp64->sem_otime);
err2 |= __put_user(s.sem_ctime, &usp64->sem_ctime);
err2 |= __put_user(s.sem_nsems, &usp64->sem_nsems);
} else {
struct semid_ds32 *usp32 = (struct semid_ds32 *) A(pad);
if (!access_ok(VERIFY_WRITE, usp32, sizeof(*usp32))) {
err = -EFAULT;
break;
}
err2 = __put_user(s.sem_perm.key, &usp32->sem_perm.key);
err2 |= __put_user(s.sem_perm.uid, &usp32->sem_perm.uid);
err2 |= __put_user(s.sem_perm.gid, &usp32->sem_perm.gid);
err2 |= __put_user(s.sem_perm.cuid, &usp32->sem_perm.cuid);
err2 |= __put_user(s.sem_perm.cgid, &usp32->sem_perm.cgid);
err2 |= __put_user(s.sem_perm.mode, &usp32->sem_perm.mode);
err2 |= __put_user(s.sem_perm.seq, &usp32->sem_perm.seq);
err2 |= __put_user(s.sem_otime, &usp32->sem_otime);
err2 |= __put_user(s.sem_ctime, &usp32->sem_ctime);
err2 |= __put_user(s.sem_nsems, &usp32->sem_nsems);
}
if (err2)
err = -EFAULT;
break;
default:
err = - EINVAL;
break;
}
return err;
}
static int
do_sys32_msgsnd (int first, int second, int third, void *uptr)
{
struct msgbuf32 *up = (struct msgbuf32 *)uptr;
struct msgbuf *p;
mm_segment_t old_fs;
int err;
if (second < 0)
return -EINVAL;
p = kmalloc (second + sizeof (struct msgbuf)
+ 4, GFP_USER);
if (!p)
return -ENOMEM;
err = get_user (p->mtype, &up->mtype);
if (err)
goto out;
err |= __copy_from_user (p->mtext, &up->mtext, second);
if (err)
goto out;
old_fs = get_fs ();
set_fs (KERNEL_DS);
err = sys_msgsnd (first, p, second, third);
set_fs (old_fs);
out:
kfree (p);
return err;
}
static int
do_sys32_msgrcv (int first, int second, int msgtyp, int third,
int version, void *uptr)
{
struct msgbuf32 *up;
struct msgbuf *p;
mm_segment_t old_fs;
int err;
if (!version) {
struct ipc_kludge32 *uipck = (struct ipc_kludge32 *)uptr;
struct ipc_kludge32 ipck;
err = -EINVAL;
if (!uptr)
goto out;
err = -EFAULT;
if (copy_from_user (&ipck, uipck, sizeof (struct ipc_kludge32)))
goto out;
uptr = (void *)AA(ipck.msgp);
msgtyp = ipck.msgtyp;
}
if (second < 0)
return -EINVAL;
err = -ENOMEM;
p = kmalloc (second + sizeof (struct msgbuf) + 4, GFP_USER);
if (!p)
goto out;
old_fs = get_fs ();
set_fs (KERNEL_DS);
err = sys_msgrcv (first, p, second + 4, msgtyp, third);
set_fs (old_fs);
if (err < 0)
goto free_then_out;
up = (struct msgbuf32 *)uptr;
if (put_user (p->mtype, &up->mtype) ||
__copy_to_user (&up->mtext, p->mtext, err))
err = -EFAULT;
free_then_out:
kfree (p);
out:
return err;
}
static int
do_sys32_msgctl (int first, int second, void *uptr)
{
int err = -EINVAL, err2;
struct msqid64_ds m;
struct msqid_ds32 *up32 = (struct msqid_ds32 *)uptr;
struct msqid64_ds32 *up64 = (struct msqid64_ds32 *)uptr;
mm_segment_t old_fs;
switch (second & ~IPC_64) {
case IPC_INFO:
case IPC_RMID:
case MSG_INFO:
err = sys_msgctl (first, second, (struct msqid_ds *)uptr);
break;
case IPC_SET:
if (second & IPC_64) {
if (!access_ok(VERIFY_READ, up64, sizeof(*up64))) {
err = -EFAULT;
break;
}
err = __get_user(m.msg_perm.uid, &up64->msg_perm.uid);
err |= __get_user(m.msg_perm.gid, &up64->msg_perm.gid);
err |= __get_user(m.msg_perm.mode, &up64->msg_perm.mode);
err |= __get_user(m.msg_qbytes, &up64->msg_qbytes);
} else {
if (!access_ok(VERIFY_READ, up32, sizeof(*up32))) {
err = -EFAULT;
break;
}
err = __get_user(m.msg_perm.uid, &up32->msg_perm.uid);
err |= __get_user(m.msg_perm.gid, &up32->msg_perm.gid);
err |= __get_user(m.msg_perm.mode, &up32->msg_perm.mode);
err |= __get_user(m.msg_qbytes, &up32->msg_qbytes);
}
if (err)
break;
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sys_msgctl(first, second | IPC_64, (struct msqid_ds *)&m);
set_fs(old_fs);
break;
case IPC_STAT:
case MSG_STAT:
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sys_msgctl(first, second | IPC_64, (struct msqid_ds *)&m);
set_fs(old_fs);
if (second & IPC_64) {
if (!access_ok(VERIFY_WRITE, up64, sizeof(*up64))) {
err = -EFAULT;
break;
}
err2 = __put_user(m.msg_perm.key, &up64->msg_perm.key);
err2 |= __put_user(m.msg_perm.uid, &up64->msg_perm.uid);
err2 |= __put_user(m.msg_perm.gid, &up64->msg_perm.gid);
err2 |= __put_user(m.msg_perm.cuid, &up64->msg_perm.cuid);
err2 |= __put_user(m.msg_perm.cgid, &up64->msg_perm.cgid);
err2 |= __put_user(m.msg_perm.mode, &up64->msg_perm.mode);
err2 |= __put_user(m.msg_perm.seq, &up64->msg_perm.seq);
err2 |= __put_user(m.msg_stime, &up64->msg_stime);
err2 |= __put_user(m.msg_rtime, &up64->msg_rtime);
err2 |= __put_user(m.msg_ctime, &up64->msg_ctime);
err2 |= __put_user(m.msg_cbytes, &up64->msg_cbytes);
err2 |= __put_user(m.msg_qnum, &up64->msg_qnum);
err2 |= __put_user(m.msg_qbytes, &up64->msg_qbytes);
err2 |= __put_user(m.msg_lspid, &up64->msg_lspid);
err2 |= __put_user(m.msg_lrpid, &up64->msg_lrpid);
if (err2)
err = -EFAULT;
} else {
if (!access_ok(VERIFY_WRITE, up32, sizeof(*up32))) {
err = -EFAULT;
break;
}
err2 = __put_user(m.msg_perm.key, &up32->msg_perm.key);
err2 |= __put_user(m.msg_perm.uid, &up32->msg_perm.uid);
err2 |= __put_user(m.msg_perm.gid, &up32->msg_perm.gid);
err2 |= __put_user(m.msg_perm.cuid, &up32->msg_perm.cuid);
err2 |= __put_user(m.msg_perm.cgid, &up32->msg_perm.cgid);
err2 |= __put_user(m.msg_perm.mode, &up32->msg_perm.mode);
err2 |= __put_user(m.msg_perm.seq, &up32->msg_perm.seq);
err2 |= __put_user(m.msg_stime, &up32->msg_stime);
err2 |= __put_user(m.msg_rtime, &up32->msg_rtime);
err2 |= __put_user(m.msg_ctime, &up32->msg_ctime);
err2 |= __put_user(m.msg_cbytes, &up32->msg_cbytes);
err2 |= __put_user(m.msg_qnum, &up32->msg_qnum);
err2 |= __put_user(m.msg_qbytes, &up32->msg_qbytes);
err2 |= __put_user(m.msg_lspid, &up32->msg_lspid);
err2 |= __put_user(m.msg_lrpid, &up32->msg_lrpid);
if (err2)
err = -EFAULT;
}
break;
}
return err;
}
static int
do_sys32_shmat (int first, int second, int third, int version, void *uptr)
{
unsigned long raddr;
u32 *uaddr = (u32 *)A((u32)third);
int err = -EINVAL;
if (version == 1)
return err;
err = sys_shmat (first, uptr, second, &raddr);
if (err)
return err;
err = put_user (raddr, uaddr);
return err;
}
struct shm_info32 {
int used_ids;
u32 shm_tot, shm_rss, shm_swp;
u32 swap_attempts, swap_successes;
};
static int
do_sys32_shmctl (int first, int second, void *uptr)
{
struct shmid64_ds32 *up64 = (struct shmid64_ds32 *)uptr;
struct shmid_ds32 *up32 = (struct shmid_ds32 *)uptr;
struct shm_info32 *uip = (struct shm_info32 *)uptr;
int err = -EFAULT, err2;
struct shmid64_ds s64;
mm_segment_t old_fs;
struct shm_info si;
struct shmid_ds s;
switch (second & ~IPC_64) {
case IPC_INFO:
second = IPC_INFO; /* So that we don't have to translate it */
case IPC_RMID:
case SHM_LOCK:
case SHM_UNLOCK:
err = sys_shmctl(first, second, (struct shmid_ds *)uptr);
break;
case IPC_SET:
if (second & IPC_64) {
err = get_user(s.shm_perm.uid, &up64->shm_perm.uid);
err |= get_user(s.shm_perm.gid, &up64->shm_perm.gid);
err |= get_user(s.shm_perm.mode, &up64->shm_perm.mode);
} else {
err = get_user(s.shm_perm.uid, &up32->shm_perm.uid);
err |= get_user(s.shm_perm.gid, &up32->shm_perm.gid);
err |= get_user(s.shm_perm.mode, &up32->shm_perm.mode);
}
if (err)
break;
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sys_shmctl(first, second & ~IPC_64, &s);
set_fs(old_fs);
break;
case IPC_STAT:
case SHM_STAT:
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sys_shmctl(first, second | IPC_64, (void *) &s64);
set_fs(old_fs);
if (err < 0)
break;
if (second & IPC_64) {
if (!access_ok(VERIFY_WRITE, up64, sizeof(*up64))) {
err = -EFAULT;
break;
}
err2 = __put_user(s64.shm_perm.key, &up64->shm_perm.key);
err2 |= __put_user(s64.shm_perm.uid, &up64->shm_perm.uid);
err2 |= __put_user(s64.shm_perm.gid, &up64->shm_perm.gid);
err2 |= __put_user(s64.shm_perm.cuid, &up64->shm_perm.cuid);
err2 |= __put_user(s64.shm_perm.cgid, &up64->shm_perm.cgid);
err2 |= __put_user(s64.shm_perm.mode, &up64->shm_perm.mode);
err2 |= __put_user(s64.shm_perm.seq, &up64->shm_perm.seq);
err2 |= __put_user(s64.shm_atime, &up64->shm_atime);
err2 |= __put_user(s64.shm_dtime, &up64->shm_dtime);
err2 |= __put_user(s64.shm_ctime, &up64->shm_ctime);
err2 |= __put_user(s64.shm_segsz, &up64->shm_segsz);
err2 |= __put_user(s64.shm_nattch, &up64->shm_nattch);
err2 |= __put_user(s64.shm_cpid, &up64->shm_cpid);
err2 |= __put_user(s64.shm_lpid, &up64->shm_lpid);
} else {
if (!access_ok(VERIFY_WRITE, up32, sizeof(*up32))) {
err = -EFAULT;
break;
}
err2 = __put_user(s64.shm_perm.key, &up32->shm_perm.key);
err2 |= __put_user(s64.shm_perm.uid, &up32->shm_perm.uid);
err2 |= __put_user(s64.shm_perm.gid, &up32->shm_perm.gid);
err2 |= __put_user(s64.shm_perm.cuid, &up32->shm_perm.cuid);
err2 |= __put_user(s64.shm_perm.cgid, &up32->shm_perm.cgid);
err2 |= __put_user(s64.shm_perm.mode, &up32->shm_perm.mode);
err2 |= __put_user(s64.shm_perm.seq, &up32->shm_perm.seq);
err2 |= __put_user(s64.shm_atime, &up32->shm_atime);
err2 |= __put_user(s64.shm_dtime, &up32->shm_dtime);
err2 |= __put_user(s64.shm_ctime, &up32->shm_ctime);
err2 |= __put_user(s64.shm_segsz, &up32->shm_segsz);
err2 |= __put_user(s64.shm_nattch, &up32->shm_nattch);
err2 |= __put_user(s64.shm_cpid, &up32->shm_cpid);
err2 |= __put_user(s64.shm_lpid, &up32->shm_lpid);
}
if (err2)
err = -EFAULT;
break;
case SHM_INFO:
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sys_shmctl(first, second, (void *)&si);
set_fs(old_fs);
if (err < 0)
break;
err2 = put_user(si.used_ids, &uip->used_ids);
err2 |= __put_user(si.shm_tot, &uip->shm_tot);
err2 |= __put_user(si.shm_rss, &uip->shm_rss);
err2 |= __put_user(si.shm_swp, &uip->shm_swp);
err2 |= __put_user(si.swap_attempts, &uip->swap_attempts);
err2 |= __put_user (si.swap_successes, &uip->swap_successes);
if (err2)
err = -EFAULT;
break;
default:
err = -EINVAL;
break;
}
return err;
}
static inline void *alloc_user_space(long len)
{
struct pt_regs *regs = (struct pt_regs *)
((unsigned long) current + THREAD_SIZE - 32) - 1;
return (void *) (regs->regs[29] - len);
}
static int sys32_semtimedop(int semid, struct sembuf *tsems, int nsems,
const struct timespec32 *timeout32)
{
struct timespec32 t32;
struct timespec *t64 = alloc_user_space(sizeof(*t64));
if (copy_from_user(&t32, timeout32, sizeof(t32)))
return -EFAULT;
if (put_user(t32.tv_sec, &t64->tv_sec) ||
put_user(t32.tv_nsec, &t64->tv_nsec))
return -EFAULT;
return sys_semtimedop(semid, tsems, nsems, t64);
}
asmlinkage long
sys32_ipc (u32 call, int first, int second, int third, u32 ptr, u32 fifth)
{
int version, err;
version = call >> 16; /* hack for backward compatibility */
call &= 0xffff;
switch (call) {
case SEMOP:
/* struct sembuf is the same on 32 and 64bit :)) */
err = sys_semtimedop (first, (struct sembuf *)AA(ptr),
second, NULL);
break;
case SEMTIMEDOP:
err = sys32_semtimedop(first, (struct sembuf *)AA(ptr), second,
(const struct timespec32 *) AA(fifth));
break;
case SEMGET:
err = sys_semget (first, second, third);
break;
case SEMCTL:
err = do_sys32_semctl (first, second, third,
(void *)AA(ptr));
break;
case MSGSND:
err = do_sys32_msgsnd (first, second, third,
(void *)AA(ptr));
break;
case MSGRCV:
err = do_sys32_msgrcv (first, second, fifth, third,
version, (void *)AA(ptr));
break;
case MSGGET:
err = sys_msgget ((key_t) first, second);
break;
case MSGCTL:
err = do_sys32_msgctl (first, second, (void *)AA(ptr));
break;
case SHMAT:
err = do_sys32_shmat (first, second, third,
version, (void *)AA(ptr));
break;
case SHMDT:
err = sys_shmdt ((char *)A(ptr));
break;
case SHMGET:
err = sys_shmget (first, second, third);
break;
case SHMCTL:
err = do_sys32_shmctl (first, second, (void *)AA(ptr));
break;
default:
err = -EINVAL;
break;
}
return err;
}
struct sysctl_args32
{
__kernel_caddr_t32 name;
int nlen;
__kernel_caddr_t32 oldval;
__kernel_caddr_t32 oldlenp;
__kernel_caddr_t32 newval;
__kernel_size_t32 newlen;
unsigned int __unused[4];
};
#ifdef CONFIG_SYSCTL
asmlinkage long sys32_sysctl(struct sysctl_args32 *args)
{
struct sysctl_args32 tmp;
int error;
size_t oldlen, *oldlenp = NULL;
unsigned long addr = (((long)&args->__unused[0]) + 7) & ~7;
if (copy_from_user(&tmp, args, sizeof(tmp)))
return -EFAULT;
if (tmp.oldval && tmp.oldlenp) {
/* Duh, this is ugly and might not work if sysctl_args
is in read-only memory, but do_sysctl does indirectly
a lot of uaccess in both directions and we'd have to
basically copy the whole sysctl.c here, and
glibc's __sysctl uses rw memory for the structure
anyway. */
if (get_user(oldlen, (u32 *)A(tmp.oldlenp)) ||
put_user(oldlen, (size_t *)addr))
return -EFAULT;
oldlenp = (size_t *)addr;
}
lock_kernel();
error = do_sysctl((int *)A(tmp.name), tmp.nlen, (void *)A(tmp.oldval),
oldlenp, (void *)A(tmp.newval), tmp.newlen);
unlock_kernel();
if (oldlenp) {
if (!error) {
if (get_user(oldlen, (size_t *)addr) ||
put_user(oldlen, (u32 *)A(tmp.oldlenp)))
error = -EFAULT;
}
copy_to_user(args->__unused, tmp.__unused, sizeof(tmp.__unused));
}
return error;
}
#else /* CONFIG_SYSCTL */
asmlinkage long sys32_sysctl(struct sysctl_args32 *args)
{
return -ENOSYS;
}
#endif /* CONFIG_SYSCTL */
asmlinkage long sys32_newuname(struct new_utsname * name)
{
int ret = 0;
down_read(&uts_sem);
if (copy_to_user(name,&system_utsname,sizeof *name))
ret = -EFAULT;
up_read(&uts_sem);
if (current->personality == PER_LINUX32 && !ret)
if (copy_to_user(name->machine, "mips\0\0\0", 8))
ret = -EFAULT;
return ret;
}
extern asmlinkage long sys_personality(unsigned long);
asmlinkage int sys32_personality(unsigned long personality)
{
int ret;
if (current->personality == PER_LINUX32 && personality == PER_LINUX)
personality = PER_LINUX32;
ret = sys_personality(personality);
if (ret == PER_LINUX32)
ret = PER_LINUX;
return ret;
}
/* ustat compatibility */
struct ustat32 {
__kernel_daddr_t32 f_tfree;
__kernel_ino_t32 f_tinode;
char f_fname[6];
char f_fpack[6];
};
extern asmlinkage long sys_ustat(dev_t dev, struct ustat * ubuf);
asmlinkage int sys32_ustat(dev_t dev, struct ustat32 * ubuf32)
{
int err;
struct ustat tmp;
struct ustat32 tmp32;
mm_segment_t old_fs = get_fs();
set_fs(KERNEL_DS);
err = sys_ustat(dev, &tmp);
set_fs (old_fs);
if (err)
goto out;
memset(&tmp32,0,sizeof(struct ustat32));
tmp32.f_tfree = tmp.f_tfree;
tmp32.f_tinode = tmp.f_tinode;
err = copy_to_user(ubuf32,&tmp32,sizeof(struct ustat32)) ? -EFAULT : 0;
out:
return err;
}
/* Handle adjtimex compatability. */
struct timex32 {
u32 modes;
s32 offset, freq, maxerror, esterror;
s32 status, constant, precision, tolerance;
struct timeval32 time;
s32 tick;
s32 ppsfreq, jitter, shift, stabil;
s32 jitcnt, calcnt, errcnt, stbcnt;
s32 :32; s32 :32; s32 :32; s32 :32;
s32 :32; s32 :32; s32 :32; s32 :32;
s32 :32; s32 :32; s32 :32; s32 :32;
};
extern int do_adjtimex(struct timex *);
asmlinkage int sys32_adjtimex(struct timex32 *utp)
{
struct timex txc;
int ret;
memset(&txc, 0, sizeof(struct timex));
if(get_user(txc.modes, &utp->modes) ||
__get_user(txc.offset, &utp->offset) ||
__get_user(txc.freq, &utp->freq) ||
__get_user(txc.maxerror, &utp->maxerror) ||
__get_user(txc.esterror, &utp->esterror) ||
__get_user(txc.status, &utp->status) ||
__get_user(txc.constant, &utp->constant) ||
__get_user(txc.precision, &utp->precision) ||
__get_user(txc.tolerance, &utp->tolerance) ||
__get_user(txc.time.tv_sec, &utp->time.tv_sec) ||
__get_user(txc.time.tv_usec, &utp->time.tv_usec) ||
__get_user(txc.tick, &utp->tick) ||
__get_user(txc.ppsfreq, &utp->ppsfreq) ||
__get_user(txc.jitter, &utp->jitter) ||
__get_user(txc.shift, &utp->shift) ||
__get_user(txc.stabil, &utp->stabil) ||
__get_user(txc.jitcnt, &utp->jitcnt) ||
__get_user(txc.calcnt, &utp->calcnt) ||
__get_user(txc.errcnt, &utp->errcnt) ||
__get_user(txc.stbcnt, &utp->stbcnt))
return -EFAULT;
ret = do_adjtimex(&txc);
if(put_user(txc.modes, &utp->modes) ||
__put_user(txc.offset, &utp->offset) ||
__put_user(txc.freq, &utp->freq) ||
__put_user(txc.maxerror, &utp->maxerror) ||
__put_user(txc.esterror, &utp->esterror) ||
__put_user(txc.status, &utp->status) ||
__put_user(txc.constant, &utp->constant) ||
__put_user(txc.precision, &utp->precision) ||
__put_user(txc.tolerance, &utp->tolerance) ||
__put_user(txc.time.tv_sec, &utp->time.tv_sec) ||
__put_user(txc.time.tv_usec, &utp->time.tv_usec) ||
__put_user(txc.tick, &utp->tick) ||
__put_user(txc.ppsfreq, &utp->ppsfreq) ||
__put_user(txc.jitter, &utp->jitter) ||
__put_user(txc.shift, &utp->shift) ||
__put_user(txc.stabil, &utp->stabil) ||
__put_user(txc.jitcnt, &utp->jitcnt) ||
__put_user(txc.calcnt, &utp->calcnt) ||
__put_user(txc.errcnt, &utp->errcnt) ||
__put_user(txc.stbcnt, &utp->stbcnt))
ret = -EFAULT;
return ret;
}
/*
* Declare the 32-bit version of the msghdr
*/
struct msghdr32 {
unsigned int msg_name; /* Socket name */
int msg_namelen; /* Length of name */
unsigned int msg_iov; /* Data blocks */
unsigned int msg_iovlen; /* Number of blocks */
unsigned int msg_control; /* Per protocol magic (eg BSD file descriptor passing) */
unsigned int msg_controllen; /* Length of cmsg list */
unsigned msg_flags;
};
struct cmsghdr32 {
__kernel_size_t32 cmsg_len;
int cmsg_level;
int cmsg_type;
};
/* Bleech... */
#define __CMSG32_NXTHDR(ctl, len, cmsg, cmsglen) __cmsg32_nxthdr((ctl),(len),(cmsg),(cmsglen))
#define CMSG32_NXTHDR(mhdr, cmsg, cmsglen) cmsg32_nxthdr((mhdr), (cmsg), (cmsglen))
#define CMSG32_ALIGN(len) ( ((len)+sizeof(int)-1) & ~(sizeof(int)-1) )
#define CMSG32_DATA(cmsg) ((void *)((char *)(cmsg) + CMSG32_ALIGN(sizeof(struct cmsghdr32))))
#define CMSG32_SPACE(len) (CMSG32_ALIGN(sizeof(struct cmsghdr32)) + CMSG32_ALIGN(len))
#define CMSG32_LEN(len) (CMSG32_ALIGN(sizeof(struct cmsghdr32)) + (len))
#define __CMSG32_FIRSTHDR(ctl,len) ((len) >= sizeof(struct cmsghdr32) ? \
(struct cmsghdr32 *)(ctl) : \
(struct cmsghdr32 *)NULL)
#define CMSG32_FIRSTHDR(msg) __CMSG32_FIRSTHDR((msg)->msg_control, (msg)->msg_controllen)
#define CMSG32_OK(ucmlen, ucmsg, mhdr) \
((ucmlen) >= sizeof(struct cmsghdr32) && \
(ucmlen) <= (unsigned long) \
((mhdr)->msg_controllen - \
((char *)(ucmsg) - (char *)(mhdr)->msg_control)))
__inline__ struct cmsghdr32 *__cmsg32_nxthdr(void *__ctl, __kernel_size_t __size,
struct cmsghdr32 *__cmsg, int __cmsg_len)
{
struct cmsghdr32 * __ptr;
__ptr = (struct cmsghdr32 *)(((unsigned char *) __cmsg) +
CMSG32_ALIGN(__cmsg_len));
if ((unsigned long)((char*)(__ptr+1) - (char *) __ctl) > __size)
return NULL;
return __ptr;
}
__inline__ struct cmsghdr32 *cmsg32_nxthdr (struct msghdr *__msg,
struct cmsghdr32 *__cmsg,
int __cmsg_len)
{
return __cmsg32_nxthdr(__msg->msg_control, __msg->msg_controllen,
__cmsg, __cmsg_len);
}
static inline int iov_from_user32_to_kern(struct iovec *kiov,
struct iovec32 *uiov32,
int niov)
{
int tot_len = 0;
while(niov > 0) {
u32 len, buf;
if(get_user(len, &uiov32->iov_len) ||
get_user(buf, &uiov32->iov_base)) {
tot_len = -EFAULT;
break;
}
tot_len += len;
kiov->iov_base = (void *)AA(buf);
kiov->iov_len = (__kernel_size_t) len;
uiov32++;
kiov++;
niov--;
}
return tot_len;
}
static inline int msghdr_from_user32_to_kern(struct msghdr *kmsg,
struct msghdr32 *umsg)
{
u32 tmp1, tmp2, tmp3;
int err;
err = get_user(tmp1, &umsg->msg_name);
err |= __get_user(tmp2, &umsg->msg_iov);
err |= __get_user(tmp3, &umsg->msg_control);
if (err)
return -EFAULT;
kmsg->msg_name = (void *)AA(tmp1);
kmsg->msg_iov = (struct iovec *)AA(tmp2);
kmsg->msg_control = (void *)AA(tmp3);
err = get_user(kmsg->msg_namelen, &umsg->msg_namelen);
err |= get_user(kmsg->msg_iovlen, &umsg->msg_iovlen);
err |= get_user(kmsg->msg_controllen, &umsg->msg_controllen);
err |= get_user(kmsg->msg_flags, &umsg->msg_flags);
return err;
}
/* I've named the args so it is easy to tell whose space the pointers are in. */
static int verify_iovec32(struct msghdr *kern_msg, struct iovec *kern_iov,
char *kern_address, int mode)
{
int tot_len;
if(kern_msg->msg_namelen) {
if(mode==VERIFY_READ) {
int err = move_addr_to_kernel(kern_msg->msg_name,
kern_msg->msg_namelen,
kern_address);
if(err < 0)
return err;
}
kern_msg->msg_name = kern_address;
} else
kern_msg->msg_name = NULL;
if(kern_msg->msg_iovlen > UIO_FASTIOV) {
kern_iov = kmalloc(kern_msg->msg_iovlen * sizeof(struct iovec),
GFP_KERNEL);
if(!kern_iov)
return -ENOMEM;
}
tot_len = iov_from_user32_to_kern(kern_iov,
(struct iovec32 *)kern_msg->msg_iov,
kern_msg->msg_iovlen);
if(tot_len >= 0)
kern_msg->msg_iov = kern_iov;
else if(kern_msg->msg_iovlen > UIO_FASTIOV)
kfree(kern_iov);
return tot_len;
}
static __inline__ void
sockfd_put(struct socket *sock)
{
fput(sock->file);
}
/* XXX This really belongs in some header file... -DaveM */
#define MAX_SOCK_ADDR 128 /* 108 for Unix domain -
16 for IP, 16 for IPX,
24 for IPv6,
about 80 for AX.25 */
extern struct socket *sockfd_lookup(int fd, int *err);
/* There is a lot of hair here because the alignment rules (and
* thus placement) of cmsg headers and length are different for
* 32-bit apps. -DaveM
*/
static int cmsghdr_from_user32_to_kern(struct msghdr *kmsg,
unsigned char *stackbuf, int stackbuf_size)
{
struct cmsghdr32 *ucmsg;
struct cmsghdr *kcmsg, *kcmsg_base;
__kernel_size_t32 ucmlen;
__kernel_size_t kcmlen, tmp;
kcmlen = 0;
kcmsg_base = kcmsg = (struct cmsghdr *)stackbuf;
ucmsg = CMSG32_FIRSTHDR(kmsg);
while(ucmsg != NULL) {
if(get_user(ucmlen, &ucmsg->cmsg_len))
return -EFAULT;
/* Catch bogons. */
if (!CMSG32_OK(ucmlen, ucmsg, kmsg))
return -EINVAL;
tmp = ((ucmlen - CMSG32_ALIGN(sizeof(*ucmsg))) +
CMSG_ALIGN(sizeof(struct cmsghdr)));
kcmlen += tmp;
ucmsg = CMSG32_NXTHDR(kmsg, ucmsg, ucmlen);
}
if(kcmlen == 0)
return -EINVAL;
/* The kcmlen holds the 64-bit version of the control length.
* It may not be modified as we do not stick it into the kmsg
* until we have successfully copied over all of the data
* from the user.
*/
if(kcmlen > stackbuf_size)
kcmsg_base = kcmsg = kmalloc(kcmlen, GFP_KERNEL);
if(kcmsg == NULL)
return -ENOBUFS;
/* Now copy them over neatly. */
memset(kcmsg, 0, kcmlen);
ucmsg = CMSG32_FIRSTHDR(kmsg);
while(ucmsg != NULL) {
__get_user(ucmlen, &ucmsg->cmsg_len);
tmp = ((ucmlen - CMSG32_ALIGN(sizeof(*ucmsg))) +
CMSG_ALIGN(sizeof(struct cmsghdr)));
kcmsg->cmsg_len = tmp;
__get_user(kcmsg->cmsg_level, &ucmsg->cmsg_level);
__get_user(kcmsg->cmsg_type, &ucmsg->cmsg_type);
/* Copy over the data. */
if(copy_from_user(CMSG_DATA(kcmsg),
CMSG32_DATA(ucmsg),
(ucmlen - CMSG32_ALIGN(sizeof(*ucmsg)))))
goto out_free_efault;
/* Advance. */
kcmsg = (struct cmsghdr *)((char *)kcmsg + CMSG_ALIGN(tmp));
ucmsg = CMSG32_NXTHDR(kmsg, ucmsg, ucmlen);
}
/* Ok, looks like we made it. Hook it up and return success. */
kmsg->msg_control = kcmsg_base;
kmsg->msg_controllen = kcmlen;
return 0;
out_free_efault:
if(kcmsg_base != (struct cmsghdr *)stackbuf)
kfree(kcmsg_base);
return -EFAULT;
}
static void put_cmsg32(struct msghdr *kmsg, int level, int type,
int len, void *data)
{
struct cmsghdr32 *cm = (struct cmsghdr32 *) kmsg->msg_control;
struct cmsghdr32 cmhdr;
int cmlen = CMSG32_LEN(len);
if(cm == NULL || kmsg->msg_controllen < sizeof(*cm)) {
kmsg->msg_flags |= MSG_CTRUNC;
return;
}
if(kmsg->msg_controllen < cmlen) {
kmsg->msg_flags |= MSG_CTRUNC;
cmlen = kmsg->msg_controllen;
}
cmhdr.cmsg_level = level;
cmhdr.cmsg_type = type;
cmhdr.cmsg_len = cmlen;
if(copy_to_user(cm, &cmhdr, sizeof cmhdr))
return;
if(copy_to_user(CMSG32_DATA(cm), data, cmlen - sizeof(struct cmsghdr32)))
return;
cmlen = CMSG32_SPACE(len);
kmsg->msg_control += cmlen;
kmsg->msg_controllen -= cmlen;
}
static void scm_detach_fds32(struct msghdr *kmsg, struct scm_cookie *scm)
{
struct cmsghdr32 *cm = (struct cmsghdr32 *) kmsg->msg_control;
int fdmax = (kmsg->msg_controllen - sizeof(struct cmsghdr32)) / sizeof(int);
int fdnum = scm->fp->count;
struct file **fp = scm->fp->fp;
int *cmfptr;
int err = 0, i;
if (fdnum < fdmax)
fdmax = fdnum;
for (i = 0, cmfptr = (int *) CMSG32_DATA(cm); i < fdmax; i++, cmfptr++) {
int new_fd;
err = get_unused_fd();
if (err < 0)
break;
new_fd = err;
err = put_user(new_fd, cmfptr);
if (err) {
put_unused_fd(new_fd);
break;
}
/* Bump the usage count and install the file. */
get_file(fp[i]);
fd_install(new_fd, fp[i]);
}
if (i > 0) {
int cmlen = CMSG32_LEN(i * sizeof(int));
if (!err)
err = put_user(SOL_SOCKET, &cm->cmsg_level);
if (!err)
err = put_user(SCM_RIGHTS, &cm->cmsg_type);
if (!err)
err = put_user(cmlen, &cm->cmsg_len);
if (!err) {
cmlen = CMSG32_SPACE(i * sizeof(int));
kmsg->msg_control += cmlen;
kmsg->msg_controllen -= cmlen;
}
}
if (i < fdnum)
kmsg->msg_flags |= MSG_CTRUNC;
/*
* All of the files that fit in the message have had their
* usage counts incremented, so we just free the list.
*/
__scm_destroy(scm);
}
/* In these cases we (currently) can just copy to data over verbatim
* because all CMSGs created by the kernel have well defined types which
* have the same layout in both the 32-bit and 64-bit API. One must add
* some special cased conversions here if we start sending control messages
* with incompatible types.
*
* SCM_RIGHTS and SCM_CREDENTIALS are done by hand in recvmsg32 right after
* we do our work. The remaining cases are:
*
* SOL_IP IP_PKTINFO struct in_pktinfo 32-bit clean
* IP_TTL int 32-bit clean
* IP_TOS __u8 32-bit clean
* IP_RECVOPTS variable length 32-bit clean
* IP_RETOPTS variable length 32-bit clean
* (these last two are clean because the types are defined
* by the IPv4 protocol)
* IP_RECVERR struct sock_extended_err +
* struct sockaddr_in 32-bit clean
* SOL_IPV6 IPV6_RECVERR struct sock_extended_err +
* struct sockaddr_in6 32-bit clean
* IPV6_PKTINFO struct in6_pktinfo 32-bit clean
* IPV6_HOPLIMIT int 32-bit clean
* IPV6_FLOWINFO u32 32-bit clean
* IPV6_HOPOPTS ipv6 hop exthdr 32-bit clean
* IPV6_DSTOPTS ipv6 dst exthdr(s) 32-bit clean
* IPV6_RTHDR ipv6 routing exthdr 32-bit clean
* IPV6_AUTHHDR ipv6 auth exthdr 32-bit clean
*/
static void cmsg32_recvmsg_fixup(struct msghdr *kmsg,
unsigned long orig_cmsg_uptr, __kernel_size_t orig_cmsg_len)
{
unsigned char *workbuf, *wp;
unsigned long bufsz, space_avail;
struct cmsghdr *ucmsg;
bufsz = ((unsigned long)kmsg->msg_control) - orig_cmsg_uptr;
space_avail = kmsg->msg_controllen + bufsz;
wp = workbuf = kmalloc(bufsz, GFP_KERNEL);
if(workbuf == NULL)
goto fail;
/* To make this more sane we assume the kernel sends back properly
* formatted control messages. Because of how the kernel will truncate
* the cmsg_len for MSG_TRUNC cases, we need not check that case either.
*/
ucmsg = (struct cmsghdr *) orig_cmsg_uptr;
while(((unsigned long)ucmsg) <=
(((unsigned long)kmsg->msg_control) - sizeof(struct cmsghdr))) {
struct cmsghdr32 *kcmsg32 = (struct cmsghdr32 *) wp;
int clen64, clen32;
/* UCMSG is the 64-bit format CMSG entry in user-space.
* KCMSG32 is within the kernel space temporary buffer
* we use to convert into a 32-bit style CMSG.
*/
__get_user(kcmsg32->cmsg_len, &ucmsg->cmsg_len);
__get_user(kcmsg32->cmsg_level, &ucmsg->cmsg_level);
__get_user(kcmsg32->cmsg_type, &ucmsg->cmsg_type);
clen64 = kcmsg32->cmsg_len;
if ((clen64 < CMSG_ALIGN(sizeof(*ucmsg))) ||
(clen64 > (orig_cmsg_len + wp - workbuf)))
break;
copy_from_user(CMSG32_DATA(kcmsg32), CMSG_DATA(ucmsg),
clen64 - CMSG_ALIGN(sizeof(*ucmsg)));
clen32 = ((clen64 - CMSG_ALIGN(sizeof(*ucmsg))) +
CMSG32_ALIGN(sizeof(struct cmsghdr32)));
kcmsg32->cmsg_len = clen32;
ucmsg = (struct cmsghdr *) (((char *)ucmsg) + CMSG_ALIGN(clen64));
wp = (((char *)kcmsg32) + CMSG32_ALIGN(clen32));
}
/* Copy back fixed up data, and adjust pointers. */
bufsz = (wp - workbuf);
copy_to_user((void *)orig_cmsg_uptr, workbuf, bufsz);
kmsg->msg_control = (struct cmsghdr *)
(((char *)orig_cmsg_uptr) + bufsz);
kmsg->msg_controllen = space_avail - bufsz;
kfree(workbuf);
return;
fail:
/* If we leave the 64-bit format CMSG chunks in there,
* the application could get confused and crash. So to
* ensure greater recovery, we report no CMSGs.
*/
kmsg->msg_controllen += bufsz;
kmsg->msg_control = (void *) orig_cmsg_uptr;
}
asmlinkage int sys32_sendmsg(int fd, struct msghdr32 *user_msg, unsigned user_flags)
{
struct socket *sock;
char address[MAX_SOCK_ADDR];
struct iovec iov[UIO_FASTIOV];
unsigned char ctl[sizeof(struct cmsghdr) + 20];
unsigned char *ctl_buf = ctl;
struct msghdr kern_msg;
int err, total_len;
if(msghdr_from_user32_to_kern(&kern_msg, user_msg))
return -EFAULT;
if(kern_msg.msg_iovlen > UIO_MAXIOV)
return -EINVAL;
err = verify_iovec32(&kern_msg, iov, address, VERIFY_READ);
if (err < 0)
goto out;
total_len = err;
if(kern_msg.msg_controllen) {
err = cmsghdr_from_user32_to_kern(&kern_msg, ctl, sizeof(ctl));
if(err)
goto out_freeiov;
ctl_buf = kern_msg.msg_control;
}
kern_msg.msg_flags = user_flags;
sock = sockfd_lookup(fd, &err);
if (sock != NULL) {
if (sock->file->f_flags & O_NONBLOCK)
kern_msg.msg_flags |= MSG_DONTWAIT;
err = sock_sendmsg(sock, &kern_msg, total_len);
sockfd_put(sock);
}
/* N.B. Use kfree here, as kern_msg.msg_controllen might change? */
if(ctl_buf != ctl)
kfree(ctl_buf);
out_freeiov:
if(kern_msg.msg_iov != iov)
kfree(kern_msg.msg_iov);
out:
return err;
}
asmlinkage int sys32_recvmsg(int fd, struct msghdr32 *user_msg, unsigned int user_flags)
{
struct iovec iovstack[UIO_FASTIOV];
struct msghdr kern_msg;
char addr[MAX_SOCK_ADDR];
struct socket *sock;
struct iovec *iov = iovstack;
struct sockaddr *uaddr;
int *uaddr_len;
unsigned long cmsg_ptr;
__kernel_size_t cmsg_len;
int err, total_len, len = 0;
if(msghdr_from_user32_to_kern(&kern_msg, user_msg))
return -EFAULT;
if(kern_msg.msg_iovlen > UIO_MAXIOV)
return -EINVAL;
uaddr = kern_msg.msg_name;
uaddr_len = &user_msg->msg_namelen;
err = verify_iovec32(&kern_msg, iov, addr, VERIFY_WRITE);
if (err < 0)
goto out;
total_len = err;
cmsg_ptr = (unsigned long) kern_msg.msg_control;
cmsg_len = kern_msg.msg_controllen;
kern_msg.msg_flags = 0;
sock = sockfd_lookup(fd, &err);
if (sock != NULL) {
struct scm_cookie scm;
if (sock->file->f_flags & O_NONBLOCK)
user_flags |= MSG_DONTWAIT;
memset(&scm, 0, sizeof(scm));
err = sock->ops->recvmsg(sock, &kern_msg, total_len,
user_flags, &scm);
if(err >= 0) {
len = err;
if(!kern_msg.msg_control) {
if(sock->passcred || scm.fp)
kern_msg.msg_flags |= MSG_CTRUNC;
if(scm.fp)
__scm_destroy(&scm);
} else {
/* If recvmsg processing itself placed some
* control messages into user space, it's is
* using 64-bit CMSG processing, so we need
* to fix it up before we tack on more stuff.
*/
if((unsigned long) kern_msg.msg_control != cmsg_ptr)
cmsg32_recvmsg_fixup(&kern_msg,
cmsg_ptr, cmsg_len);
/* Wheee... */
if(sock->passcred)
put_cmsg32(&kern_msg,
SOL_SOCKET, SCM_CREDENTIALS,
sizeof(scm.creds), &scm.creds);
if(scm.fp != NULL)
scm_detach_fds32(&kern_msg, &scm);
}
}
sockfd_put(sock);
}
if(uaddr != NULL && kern_msg.msg_namelen && err >= 0)
err = move_addr_to_user(addr, kern_msg.msg_namelen, uaddr, uaddr_len);
if(cmsg_ptr != 0 && err >= 0) {
unsigned long ucmsg_ptr = ((unsigned long)kern_msg.msg_control);
__kernel_size_t32 uclen = (__kernel_size_t32) (ucmsg_ptr - cmsg_ptr);
err |= __put_user(uclen, &user_msg->msg_controllen);
}
if(err >= 0)
err = __put_user(kern_msg.msg_flags, &user_msg->msg_flags);
if(kern_msg.msg_iov != iov)
kfree(kern_msg.msg_iov);
out:
if(err < 0)
return err;
return len;
}
extern asmlinkage ssize_t sys_sendfile(int out_fd, int in_fd, off_t *offset, size_t count);
asmlinkage int sys32_sendfile(int out_fd, int in_fd, __kernel_off_t32 *offset, s32 count)
{
mm_segment_t old_fs = get_fs();
int ret;
off_t of;
if (offset && get_user(of, offset))
return -EFAULT;
set_fs(KERNEL_DS);
ret = sys_sendfile(out_fd, in_fd, offset ? &of : NULL, count);
set_fs(old_fs);
if (offset && put_user(of, offset))
return -EFAULT;
return ret;
}
asmlinkage ssize_t sys_readahead(int fd, loff_t offset, size_t count);
asmlinkage ssize_t sys32_readahead(int fd, u32 pad0, u64 a2, u64 a3,
size_t count)
{
return sys_readahead(fd, merge_64(a2, a3), count);
}
/* Argument list sizes for sys_socketcall */
#define AL(x) ((x) * sizeof(unsigned int))
static unsigned char socketcall_nargs[18]={AL(0),AL(3),AL(3),AL(3),AL(2),AL(3),
AL(3),AL(3),AL(4),AL(4),AL(4),AL(6),
AL(6),AL(2),AL(5),AL(5),AL(3),AL(3)};
#undef AL
/*
* System call vectors.
*
* Argument checking cleaned up. Saved 20% in size.
* This function doesn't need to set the kernel lock because
* it is set by the callees.
*/
asmlinkage long sys32_socketcall(int call, unsigned int *args32)
{
unsigned int a[6];
unsigned int a0,a1;
int err;
if(call<1||call>SYS_RECVMSG)
return -EINVAL;
/* copy_from_user should be SMP safe. */
if (copy_from_user(a, args32, socketcall_nargs[call]))
return -EFAULT;
a0=a[0];
a1=a[1];
switch (call) {
case SYS_SOCKET:
err = sys_socket(a0,a1,a[2]);
break;
case SYS_BIND:
err = sys_bind(a0,(struct sockaddr *)A(a1), a[2]);
break;
case SYS_CONNECT:
err = sys_connect(a0, (struct sockaddr *)A(a1), a[2]);
break;
case SYS_LISTEN:
err = sys_listen(a0,a1);
break;
case SYS_ACCEPT:
err = sys_accept(a0,(struct sockaddr *)A(a1), (int *)A(a[2]));
break;
case SYS_GETSOCKNAME:
err = sys_getsockname(a0,(struct sockaddr *)A(a1), (int *)A(a[2]));
break;
case SYS_GETPEERNAME:
err = sys_getpeername(a0, (struct sockaddr *)A(a1), (int *)A(a[2]));
break;
case SYS_SOCKETPAIR:
err = sys_socketpair(a0,a1, a[2], (int *)A(a[3]));
break;
case SYS_SEND:
err = sys_send(a0, (void *)A(a1), a[2], a[3]);
break;
case SYS_SENDTO:
err = sys_sendto(a0,(void *)A(a1), a[2], a[3],
(struct sockaddr *)A(a[4]), a[5]);
break;
case SYS_RECV:
err = sys_recv(a0, (void *)A(a1), a[2], a[3]);
break;
case SYS_RECVFROM:
err = sys_recvfrom(a0, (void *)A(a1), a[2], a[3],
(struct sockaddr *)A(a[4]), (int *)A(a[5]));
break;
case SYS_SHUTDOWN:
err = sys_shutdown(a0,a1);
break;
case SYS_SETSOCKOPT:
err = sys_setsockopt(a0, a1, a[2], (char *)A(a[3]), a[4]);
break;
case SYS_GETSOCKOPT:
err = sys_getsockopt(a0, a1, a[2], (char *)A(a[3]), (int *)A(a[4]));
break;
case SYS_SENDMSG:
err = sys_sendmsg(a0, (struct msghdr *) A(a1), a[2]);
break;
case SYS_RECVMSG:
err = sys_recvmsg(a0, (struct msghdr *) A(a1), a[2]);
break;
default:
err = -EINVAL;
break;
}
return err;
}
#ifdef CONFIG_MODULES
extern asmlinkage unsigned long sys_create_module(const char *name_user, size_t size);
asmlinkage unsigned long sys32_create_module(const char *name_user, __kernel_size_t32 size)
{
return sys_create_module(name_user, (size_t)size);
}
extern asmlinkage int sys_init_module(const char *name_user, struct module *mod_user);
/* Hey, when you're trying to init module, take time and prepare us a nice 64bit
* module structure, even if from 32bit modutils... Why to pollute kernel... :))
*/
asmlinkage int sys32_init_module(const char *name_user, struct module *mod_user)
{
return sys_init_module(name_user, mod_user);
}
extern asmlinkage int sys_delete_module(const char *name_user);
asmlinkage int sys32_delete_module(const char *name_user)
{
return sys_delete_module(name_user);
}
struct module_info32 {
u32 addr;
u32 size;
u32 flags;
s32 usecount;
};
/* Query various bits about modules. */
static inline long
get_mod_name(const char *user_name, char **buf)
{
unsigned long page;
long retval;
if ((unsigned long)user_name >= TASK_SIZE
&& !segment_eq(get_fs (), KERNEL_DS))
return -EFAULT;
page = __get_free_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
retval = strncpy_from_user((char *)page, user_name, PAGE_SIZE);
if (retval > 0) {
if (retval < PAGE_SIZE) {
*buf = (char *)page;
return retval;
}
retval = -ENAMETOOLONG;
} else if (!retval)
retval = -EINVAL;
free_page(page);
return retval;
}
static inline void
put_mod_name(char *buf)
{
free_page((unsigned long)buf);
}
static __inline__ struct module *find_module(const char *name)
{
struct module *mod;
for (mod = module_list; mod ; mod = mod->next) {
if (mod->flags & MOD_DELETED)
continue;
if (!strcmp(mod->name, name))
break;
}
return mod;
}
static int
qm_modules(char *buf, size_t bufsize, __kernel_size_t32 *ret)
{
struct module *mod;
size_t nmod, space, len;
nmod = space = 0;
for (mod = module_list; mod->next != NULL; mod = mod->next, ++nmod) {
len = strlen(mod->name)+1;
if (len > bufsize)
goto calc_space_needed;
if (copy_to_user(buf, mod->name, len))
return -EFAULT;
buf += len;
bufsize -= len;
space += len;
}
if (put_user(nmod, ret))
return -EFAULT;
else
return 0;
calc_space_needed:
space += len;
while ((mod = mod->next)->next != NULL)
space += strlen(mod->name)+1;
if (put_user(space, ret))
return -EFAULT;
else
return -ENOSPC;
}
static int
qm_deps(struct module *mod, char *buf, size_t bufsize, __kernel_size_t32 *ret)
{
size_t i, space, len;
if (mod->next == NULL)
return -EINVAL;
if (!MOD_CAN_QUERY(mod))
return put_user(0, ret);
space = 0;
for (i = 0; i < mod->ndeps; ++i) {
const char *dep_name = mod->deps[i].dep->name;
len = strlen(dep_name)+1;
if (len > bufsize)
goto calc_space_needed;
if (copy_to_user(buf, dep_name, len))
return -EFAULT;
buf += len;
bufsize -= len;
space += len;
}
return put_user(i, ret);
calc_space_needed:
space += len;
while (++i < mod->ndeps)
space += strlen(mod->deps[i].dep->name)+1;
if (put_user(space, ret))
return -EFAULT;
else
return -ENOSPC;
}
static int
qm_refs(struct module *mod, char *buf, size_t bufsize, __kernel_size_t32 *ret)
{
size_t nrefs, space, len;
struct module_ref *ref;
if (mod->next == NULL)
return -EINVAL;
if (!MOD_CAN_QUERY(mod))
if (put_user(0, ret))
return -EFAULT;
else
return 0;
space = 0;
for (nrefs = 0, ref = mod->refs; ref ; ++nrefs, ref = ref->next_ref) {
const char *ref_name = ref->ref->name;
len = strlen(ref_name)+1;
if (len > bufsize)
goto calc_space_needed;
if (copy_to_user(buf, ref_name, len))
return -EFAULT;
buf += len;
bufsize -= len;
space += len;
}
if (put_user(nrefs, ret))
return -EFAULT;
else
return 0;
calc_space_needed:
space += len;
while ((ref = ref->next_ref) != NULL)
space += strlen(ref->ref->name)+1;
if (put_user(space, ret))
return -EFAULT;
else
return -ENOSPC;
}
static inline int
qm_symbols(struct module *mod, char *buf, size_t bufsize, __kernel_size_t32 *ret)
{
size_t i, space, len;
struct module_symbol *s;
char *strings;
unsigned *vals;
if (!MOD_CAN_QUERY(mod))
if (put_user(0, ret))
return -EFAULT;
else
return 0;
space = mod->nsyms * 2*sizeof(u32);
i = len = 0;
s = mod->syms;
if (space > bufsize)
goto calc_space_needed;
if (!access_ok(VERIFY_WRITE, buf, space))
return -EFAULT;
bufsize -= space;
vals = (unsigned *)buf;
strings = buf+space;
for (; i < mod->nsyms ; ++i, ++s, vals += 2) {
len = strlen(s->name)+1;
if (len > bufsize)
goto calc_space_needed;
if (copy_to_user(strings, s->name, len)
|| __put_user(s->value, vals+0)
|| __put_user(space, vals+1))
return -EFAULT;
strings += len;
bufsize -= len;
space += len;
}
if (put_user(i, ret))
return -EFAULT;
else
return 0;
calc_space_needed:
for (; i < mod->nsyms; ++i, ++s)
space += strlen(s->name)+1;
if (put_user(space, ret))
return -EFAULT;
else
return -ENOSPC;
}
static inline int
qm_info(struct module *mod, char *buf, size_t bufsize, __kernel_size_t32 *ret)
{
int error = 0;
if (mod->next == NULL)
return -EINVAL;
if (sizeof(struct module_info32) <= bufsize) {
struct module_info32 info;
info.addr = (unsigned long)mod;
info.size = mod->size;
info.flags = mod->flags;
info.usecount =
((mod_member_present(mod, can_unload)
&& mod->can_unload)
? -1 : atomic_read(&mod->uc.usecount));
if (copy_to_user(buf, &info, sizeof(struct module_info32)))
return -EFAULT;
} else
error = -ENOSPC;
if (put_user(sizeof(struct module_info32), ret))
return -EFAULT;
return error;
}
asmlinkage int sys32_query_module(char *name_user, int which, char *buf, __kernel_size_t32 bufsize, u32 ret)
{
struct module *mod;
int err;
lock_kernel();
if (name_user == 0) {
/* This finds "kernel_module" which is not exported. */
for(mod = module_list; mod->next != NULL; mod = mod->next)
;
} else {
long namelen;
char *name;
if ((namelen = get_mod_name(name_user, &name)) < 0) {
err = namelen;
goto out;
}
err = -ENOENT;
if (namelen == 0) {
/* This finds "kernel_module" which is not exported. */
for(mod = module_list; mod->next != NULL; mod = mod->next)
;
} else if ((mod = find_module(name)) == NULL) {
put_mod_name(name);
goto out;
}
put_mod_name(name);
}
switch (which)
{
case 0:
err = 0;
break;
case QM_MODULES:
err = qm_modules(buf, bufsize, (__kernel_size_t32 *)AA(ret));
break;
case QM_DEPS:
err = qm_deps(mod, buf, bufsize, (__kernel_size_t32 *)AA(ret));
break;
case QM_REFS:
err = qm_refs(mod, buf, bufsize, (__kernel_size_t32 *)AA(ret));
break;
case QM_SYMBOLS:
err = qm_symbols(mod, buf, bufsize, (__kernel_size_t32 *)AA(ret));
break;
case QM_INFO:
err = qm_info(mod, buf, bufsize, (__kernel_size_t32 *)AA(ret));
break;
default:
err = -EINVAL;
break;
}
out:
unlock_kernel();
return err;
}
struct kernel_sym32 {
u32 value;
char name[60];
};
extern asmlinkage int sys_get_kernel_syms(struct kernel_sym *table);
asmlinkage int sys32_get_kernel_syms(struct kernel_sym32 *table)
{
int len, i;
struct kernel_sym *tbl;
mm_segment_t old_fs;
len = sys_get_kernel_syms(NULL);
if (!table) return len;
tbl = kmalloc (len * sizeof (struct kernel_sym), GFP_KERNEL);
if (!tbl) return -ENOMEM;
old_fs = get_fs();
set_fs (KERNEL_DS);
sys_get_kernel_syms(tbl);
set_fs (old_fs);
for (i = 0; i < len; i++, table++) {
if (put_user (tbl[i].value, &table->value) ||
copy_to_user (table->name, tbl[i].name, 60))
break;
}
kfree (tbl);
return i;
}
#else /* CONFIG_MODULES */
asmlinkage unsigned long
sys32_create_module(const char *name_user, size_t size)
{
return -ENOSYS;
}
asmlinkage int
sys32_init_module(const char *name_user, struct module *mod_user)
{
return -ENOSYS;
}
asmlinkage int
sys32_delete_module(const char *name_user)
{
return -ENOSYS;
}
asmlinkage int
sys32_query_module(const char *name_user, int which, char *buf, size_t bufsize,
size_t *ret)
{
/* Let the program know about the new interface. Not that
it'll do them much good. */
if (which == 0)
return 0;
return -ENOSYS;
}
asmlinkage int
sys32_get_kernel_syms(struct kernel_sym *table)
{
return -ENOSYS;
}
#endif /* CONFIG_MODULES */
| jmesmon/linux-2.4.37.y | arch/mips64/kernel/linux32.c | C | gpl-2.0 | 87,759 |
/*
* U300 GPIO module.
*
* Copyright (C) 2007-2011 ST-Ericsson AB
* License terms: GNU General Public License (GPL) version 2
* This can driver either of the two basic GPIO cores
* available in the U300 platforms:
* COH 901 335 - Used in DB3150 (U300 1.0) and DB3200 (U330 1.0)
* COH 901 571/3 - Used in DB3210 (U365 2.0) and DB3350 (U335 1.0)
* Author: Linus Walleij <[email protected]>
* Author: Jonas Aaberg <[email protected]>
*/
#include <linux/module.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/pinctrl/consumer.h>
#include <linux/pinctrl/pinconf-generic.h>
#include <mach/gpio-u300.h>
#include "pinctrl-coh901.h"
/*
*/
#define U300_335_PORT_STRIDE (0x1C)
/* */
#define U300_335_PXPDIR (0x00)
#define U300_335_PXPDOR (0x00)
/* */
#define U300_335_PXPCR (0x04)
/* */
#define U300_GPIO_PXPCR_ALL_PINS_MODE_MASK (0x0000FFFFUL)
#define U300_GPIO_PXPCR_PIN_MODE_MASK (0x00000003UL)
#define U300_GPIO_PXPCR_PIN_MODE_SHIFT (0x00000002UL)
#define U300_GPIO_PXPCR_PIN_MODE_INPUT (0x00000000UL)
#define U300_GPIO_PXPCR_PIN_MODE_OUTPUT_PUSH_PULL (0x00000001UL)
#define U300_GPIO_PXPCR_PIN_MODE_OUTPUT_OPEN_DRAIN (0x00000002UL)
#define U300_GPIO_PXPCR_PIN_MODE_OUTPUT_OPEN_SOURCE (0x00000003UL)
/* */
#define U300_335_PXIEV (0x08)
/* */
#define U300_335_PXIEN (0x0C)
/* */
#define U300_335_PXIFR (0x10)
/* */
#define U300_335_PXICR (0x14)
/* */
#define U300_GPIO_PXICR_ALL_IRQ_CONFIG_MASK (0x000000FFUL)
#define U300_GPIO_PXICR_IRQ_CONFIG_MASK (0x00000001UL)
#define U300_GPIO_PXICR_IRQ_CONFIG_FALLING_EDGE (0x00000000UL)
#define U300_GPIO_PXICR_IRQ_CONFIG_RISING_EDGE (0x00000001UL)
/* */
#define U300_335_PXPER (0x18)
/* */
#define U300_GPIO_PXPER_ALL_PULL_UP_DISABLE_MASK (0x000000FFUL)
#define U300_GPIO_PXPER_PULL_UP_DISABLE (0x00000001UL)
/* */
#define U300_335_CR (0x54)
#define U300_335_CR_BLOCK_CLOCK_ENABLE (0x00000001UL)
/*
*/
#define U300_571_PORT_STRIDE (0x30)
/*
*/
#define U300_571_CR (0x00)
#define U300_571_CR_SYNC_SEL_ENABLE (0x00000002UL)
#define U300_571_CR_BLOCK_CLKRQ_ENABLE (0x00000001UL)
/*
*/
#define U300_571_PXPDIR (0x04)
#define U300_571_PXPDOR (0x08)
#define U300_571_PXPCR (0x0C)
#define U300_571_PXPER (0x10)
#define U300_571_PXIEV (0x14)
#define U300_571_PXIEN (0x18)
#define U300_571_PXIFR (0x1C)
#define U300_571_PXICR (0x20)
/* */
#define U300_GPIO_PINS_PER_PORT 8
#define U300_GPIO_MAX (U300_GPIO_PINS_PER_PORT * 7)
struct u300_gpio {
struct gpio_chip chip;
struct list_head port_list;
struct clk *clk;
struct resource *memres;
void __iomem *base;
struct device *dev;
int irq_base;
u32 stride;
/* */
u32 pcr;
u32 dor;
u32 dir;
u32 per;
u32 icr;
u32 ien;
u32 iev;
};
struct u300_gpio_port {
struct list_head node;
struct u300_gpio *gpio;
char name[8];
int irq;
int number;
u8 toggle_edge_mode;
};
/*
*/
#define U300_PIN_REG(pin, reg) \
(gpio->base + (pin >> 3) * gpio->stride + gpio->reg)
/*
*/
#define U300_PIN_BIT(pin) \
(1 << (pin & 0x07))
struct u300_gpio_confdata {
u16 bias_mode;
bool output;
int outval;
};
/* */
#define BS335_GPIO_NUM_PORTS 7
/* */
#define BS365_GPIO_NUM_PORTS 5
#define U300_FLOATING_INPUT { \
.bias_mode = PIN_CONFIG_BIAS_HIGH_IMPEDANCE, \
.output = false, \
}
#define U300_PULL_UP_INPUT { \
.bias_mode = PIN_CONFIG_BIAS_PULL_UP, \
.output = false, \
}
#define U300_OUTPUT_LOW { \
.output = true, \
.outval = 0, \
}
#define U300_OUTPUT_HIGH { \
.output = true, \
.outval = 1, \
}
/* */
static const struct __initdata u300_gpio_confdata
bs335_gpio_config[BS335_GPIO_NUM_PORTS][U300_GPIO_PINS_PER_PORT] = {
/* */
{
U300_FLOATING_INPUT,
U300_OUTPUT_HIGH,
U300_FLOATING_INPUT,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
},
/* */
{
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
U300_PULL_UP_INPUT,
U300_FLOATING_INPUT,
U300_OUTPUT_HIGH,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
},
/* */
{
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_OUTPUT_LOW,
U300_PULL_UP_INPUT,
U300_OUTPUT_LOW,
U300_PULL_UP_INPUT,
},
/* */
{
U300_PULL_UP_INPUT,
U300_OUTPUT_LOW,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
},
/* */
{
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
},
/* */
{
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
},
/* */
{
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
}
};
static const struct __initdata u300_gpio_confdata
bs365_gpio_config[BS365_GPIO_NUM_PORTS][U300_GPIO_PINS_PER_PORT] = {
/* */
{
U300_FLOATING_INPUT,
U300_OUTPUT_LOW,
U300_FLOATING_INPUT,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
U300_PULL_UP_INPUT,
U300_FLOATING_INPUT,
},
/* */
{
U300_OUTPUT_LOW,
U300_FLOATING_INPUT,
U300_OUTPUT_LOW,
U300_FLOATING_INPUT,
U300_FLOATING_INPUT,
U300_OUTPUT_HIGH,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
},
/* */
{
U300_FLOATING_INPUT,
U300_PULL_UP_INPUT,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
},
/* */
{
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
},
/* */
{
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
U300_PULL_UP_INPUT,
/* */
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
U300_OUTPUT_LOW,
}
};
/*
*/
static inline struct u300_gpio *to_u300_gpio(struct gpio_chip *chip)
{
return container_of(chip, struct u300_gpio, chip);
}
static int u300_gpio_request(struct gpio_chip *chip, unsigned offset)
{
/*
*/
int gpio = chip->base + offset;
return pinctrl_request_gpio(gpio);
}
static void u300_gpio_free(struct gpio_chip *chip, unsigned offset)
{
int gpio = chip->base + offset;
pinctrl_free_gpio(gpio);
}
static int u300_gpio_get(struct gpio_chip *chip, unsigned offset)
{
struct u300_gpio *gpio = to_u300_gpio(chip);
return readl(U300_PIN_REG(offset, dir)) & U300_PIN_BIT(offset);
}
static void u300_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
struct u300_gpio *gpio = to_u300_gpio(chip);
unsigned long flags;
u32 val;
local_irq_save(flags);
val = readl(U300_PIN_REG(offset, dor));
if (value)
writel(val | U300_PIN_BIT(offset), U300_PIN_REG(offset, dor));
else
writel(val & ~U300_PIN_BIT(offset), U300_PIN_REG(offset, dor));
local_irq_restore(flags);
}
static int u300_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
struct u300_gpio *gpio = to_u300_gpio(chip);
unsigned long flags;
u32 val;
local_irq_save(flags);
val = readl(U300_PIN_REG(offset, pcr));
/* */
val &= ~(U300_GPIO_PXPCR_PIN_MODE_MASK << ((offset & 0x07) << 1));
writel(val, U300_PIN_REG(offset, pcr));
local_irq_restore(flags);
return 0;
}
static int u300_gpio_direction_output(struct gpio_chip *chip, unsigned offset,
int value)
{
struct u300_gpio *gpio = to_u300_gpio(chip);
unsigned long flags;
u32 oldmode;
u32 val;
local_irq_save(flags);
val = readl(U300_PIN_REG(offset, pcr));
/*
*/
oldmode = val & (U300_GPIO_PXPCR_PIN_MODE_MASK <<
((offset & 0x07) << 1));
/* */
if (oldmode == 0) {
val &= ~(U300_GPIO_PXPCR_PIN_MODE_MASK <<
((offset & 0x07) << 1));
val |= (U300_GPIO_PXPCR_PIN_MODE_OUTPUT_PUSH_PULL
<< ((offset & 0x07) << 1));
writel(val, U300_PIN_REG(offset, pcr));
}
u300_gpio_set(chip, offset, value);
local_irq_restore(flags);
return 0;
}
static int u300_gpio_to_irq(struct gpio_chip *chip, unsigned offset)
{
struct u300_gpio *gpio = to_u300_gpio(chip);
int retirq = gpio->irq_base + offset;
dev_dbg(gpio->dev, "request IRQ for GPIO %d, return %d\n", offset,
retirq);
return retirq;
}
/* */
int u300_gpio_config_get(struct gpio_chip *chip,
unsigned offset,
unsigned long *config)
{
struct u300_gpio *gpio = to_u300_gpio(chip);
enum pin_config_param param = (enum pin_config_param) *config;
bool biasmode;
u32 drmode;
/* */
biasmode = !!(readl(U300_PIN_REG(offset, per)) & U300_PIN_BIT(offset));
/* */
drmode = readl(U300_PIN_REG(offset, pcr));
drmode &= (U300_GPIO_PXPCR_PIN_MODE_MASK << ((offset & 0x07) << 1));
drmode >>= ((offset & 0x07) << 1);
switch(param) {
case PIN_CONFIG_BIAS_HIGH_IMPEDANCE:
*config = 0;
if (biasmode)
return 0;
else
return -EINVAL;
break;
case PIN_CONFIG_BIAS_PULL_UP:
*config = 0;
if (!biasmode)
return 0;
else
return -EINVAL;
break;
case PIN_CONFIG_DRIVE_PUSH_PULL:
*config = 0;
if (drmode == U300_GPIO_PXPCR_PIN_MODE_OUTPUT_PUSH_PULL)
return 0;
else
return -EINVAL;
break;
case PIN_CONFIG_DRIVE_OPEN_DRAIN:
*config = 0;
if (drmode == U300_GPIO_PXPCR_PIN_MODE_OUTPUT_OPEN_DRAIN)
return 0;
else
return -EINVAL;
break;
case PIN_CONFIG_DRIVE_OPEN_SOURCE:
*config = 0;
if (drmode == U300_GPIO_PXPCR_PIN_MODE_OUTPUT_OPEN_SOURCE)
return 0;
else
return -EINVAL;
break;
default:
break;
}
return -ENOTSUPP;
}
int u300_gpio_config_set(struct gpio_chip *chip, unsigned offset,
enum pin_config_param param)
{
struct u300_gpio *gpio = to_u300_gpio(chip);
unsigned long flags;
u32 val;
local_irq_save(flags);
switch (param) {
case PIN_CONFIG_BIAS_DISABLE:
case PIN_CONFIG_BIAS_HIGH_IMPEDANCE:
val = readl(U300_PIN_REG(offset, per));
writel(val | U300_PIN_BIT(offset), U300_PIN_REG(offset, per));
break;
case PIN_CONFIG_BIAS_PULL_UP:
val = readl(U300_PIN_REG(offset, per));
writel(val & ~U300_PIN_BIT(offset), U300_PIN_REG(offset, per));
break;
case PIN_CONFIG_DRIVE_PUSH_PULL:
val = readl(U300_PIN_REG(offset, pcr));
val &= ~(U300_GPIO_PXPCR_PIN_MODE_MASK
<< ((offset & 0x07) << 1));
val |= (U300_GPIO_PXPCR_PIN_MODE_OUTPUT_PUSH_PULL
<< ((offset & 0x07) << 1));
writel(val, U300_PIN_REG(offset, pcr));
break;
case PIN_CONFIG_DRIVE_OPEN_DRAIN:
val = readl(U300_PIN_REG(offset, pcr));
val &= ~(U300_GPIO_PXPCR_PIN_MODE_MASK
<< ((offset & 0x07) << 1));
val |= (U300_GPIO_PXPCR_PIN_MODE_OUTPUT_OPEN_DRAIN
<< ((offset & 0x07) << 1));
writel(val, U300_PIN_REG(offset, pcr));
break;
case PIN_CONFIG_DRIVE_OPEN_SOURCE:
val = readl(U300_PIN_REG(offset, pcr));
val &= ~(U300_GPIO_PXPCR_PIN_MODE_MASK
<< ((offset & 0x07) << 1));
val |= (U300_GPIO_PXPCR_PIN_MODE_OUTPUT_OPEN_SOURCE
<< ((offset & 0x07) << 1));
writel(val, U300_PIN_REG(offset, pcr));
break;
default:
local_irq_restore(flags);
dev_err(gpio->dev, "illegal configuration requested\n");
return -EINVAL;
}
local_irq_restore(flags);
return 0;
}
static struct gpio_chip u300_gpio_chip = {
.label = "u300-gpio-chip",
.owner = THIS_MODULE,
.request = u300_gpio_request,
.free = u300_gpio_free,
.get = u300_gpio_get,
.set = u300_gpio_set,
.direction_input = u300_gpio_direction_input,
.direction_output = u300_gpio_direction_output,
.to_irq = u300_gpio_to_irq,
};
static void u300_toggle_trigger(struct u300_gpio *gpio, unsigned offset)
{
u32 val;
val = readl(U300_PIN_REG(offset, icr));
/* */
if (u300_gpio_get(&gpio->chip, offset)) {
/* */
writel(val & ~U300_PIN_BIT(offset), U300_PIN_REG(offset, icr));
dev_dbg(gpio->dev, "next IRQ on falling edge on pin %d\n",
offset);
} else {
/* */
writel(val | U300_PIN_BIT(offset), U300_PIN_REG(offset, icr));
dev_dbg(gpio->dev, "next IRQ on rising edge on pin %d\n",
offset);
}
}
static int u300_gpio_irq_type(struct irq_data *d, unsigned trigger)
{
struct u300_gpio_port *port = irq_data_get_irq_chip_data(d);
struct u300_gpio *gpio = port->gpio;
int offset = d->irq - gpio->irq_base;
u32 val;
if ((trigger & IRQF_TRIGGER_RISING) &&
(trigger & IRQF_TRIGGER_FALLING)) {
/*
*/
dev_dbg(gpio->dev,
"trigger on both rising and falling edge on pin %d\n",
offset);
port->toggle_edge_mode |= U300_PIN_BIT(offset);
u300_toggle_trigger(gpio, offset);
} else if (trigger & IRQF_TRIGGER_RISING) {
dev_dbg(gpio->dev, "trigger on rising edge on pin %d\n",
offset);
val = readl(U300_PIN_REG(offset, icr));
writel(val | U300_PIN_BIT(offset), U300_PIN_REG(offset, icr));
port->toggle_edge_mode &= ~U300_PIN_BIT(offset);
} else if (trigger & IRQF_TRIGGER_FALLING) {
dev_dbg(gpio->dev, "trigger on falling edge on pin %d\n",
offset);
val = readl(U300_PIN_REG(offset, icr));
writel(val & ~U300_PIN_BIT(offset), U300_PIN_REG(offset, icr));
port->toggle_edge_mode &= ~U300_PIN_BIT(offset);
}
return 0;
}
static void u300_gpio_irq_enable(struct irq_data *d)
{
struct u300_gpio_port *port = irq_data_get_irq_chip_data(d);
struct u300_gpio *gpio = port->gpio;
int offset = d->irq - gpio->irq_base;
u32 val;
unsigned long flags;
local_irq_save(flags);
val = readl(U300_PIN_REG(offset, ien));
writel(val | U300_PIN_BIT(offset), U300_PIN_REG(offset, ien));
local_irq_restore(flags);
}
static void u300_gpio_irq_disable(struct irq_data *d)
{
struct u300_gpio_port *port = irq_data_get_irq_chip_data(d);
struct u300_gpio *gpio = port->gpio;
int offset = d->irq - gpio->irq_base;
u32 val;
unsigned long flags;
local_irq_save(flags);
val = readl(U300_PIN_REG(offset, ien));
writel(val & ~U300_PIN_BIT(offset), U300_PIN_REG(offset, ien));
local_irq_restore(flags);
}
static struct irq_chip u300_gpio_irqchip = {
.name = "u300-gpio-irqchip",
.irq_enable = u300_gpio_irq_enable,
.irq_disable = u300_gpio_irq_disable,
.irq_set_type = u300_gpio_irq_type,
};
static void u300_gpio_irq_handler(unsigned irq, struct irq_desc *desc)
{
struct u300_gpio_port *port = irq_get_handler_data(irq);
struct u300_gpio *gpio = port->gpio;
int pinoffset = port->number << 3; /* */
unsigned long val;
desc->irq_data.chip->irq_ack(&desc->irq_data);
/* */
val = readl(U300_PIN_REG(pinoffset, iev));
/* */
val &= 0xFFU; /* */
/* */
writel(val, U300_PIN_REG(pinoffset, iev));
/* */
if (val != 0) {
int irqoffset;
for_each_set_bit(irqoffset, &val, U300_GPIO_PINS_PER_PORT) {
int pin_irq = gpio->irq_base + (port->number << 3)
+ irqoffset;
int offset = pinoffset + irqoffset;
dev_dbg(gpio->dev, "GPIO IRQ %d on pin %d\n",
pin_irq, offset);
generic_handle_irq(pin_irq);
/*
*/
if (port->toggle_edge_mode & U300_PIN_BIT(offset))
u300_toggle_trigger(gpio, offset);
}
}
desc->irq_data.chip->irq_unmask(&desc->irq_data);
}
static void __init u300_gpio_init_pin(struct u300_gpio *gpio,
int offset,
const struct u300_gpio_confdata *conf)
{
/* */
if (conf->output) {
u300_gpio_direction_output(&gpio->chip, offset, conf->outval);
/* */
u300_gpio_config_set(&gpio->chip, offset,
PIN_CONFIG_BIAS_HIGH_IMPEDANCE);
/* */
u300_gpio_config_set(&gpio->chip, offset,
PIN_CONFIG_DRIVE_PUSH_PULL);
dev_dbg(gpio->dev, "set up pin %d as output, value: %d\n",
offset, conf->outval);
} else {
u300_gpio_direction_input(&gpio->chip, offset);
/* */
u300_gpio_set(&gpio->chip, offset, 0);
/* */
u300_gpio_config_set(&gpio->chip, offset, conf->bias_mode);
dev_dbg(gpio->dev, "set up pin %d as input, bias: %04x\n",
offset, conf->bias_mode);
}
}
static void __init u300_gpio_init_coh901571(struct u300_gpio *gpio,
struct u300_gpio_platform *plat)
{
int i, j;
/* */
for (i = 0; i < plat->ports; i++) {
for (j = 0; j < 8; j++) {
const struct u300_gpio_confdata *conf;
int offset = (i*8) + j;
if (plat->variant == U300_GPIO_COH901571_3_BS335)
conf = &bs335_gpio_config[i][j];
else if (plat->variant == U300_GPIO_COH901571_3_BS365)
conf = &bs365_gpio_config[i][j];
else
break;
u300_gpio_init_pin(gpio, offset, conf);
}
}
}
static inline void u300_gpio_free_ports(struct u300_gpio *gpio)
{
struct u300_gpio_port *port;
struct list_head *p, *n;
list_for_each_safe(p, n, &gpio->port_list) {
port = list_entry(p, struct u300_gpio_port, node);
list_del(&port->node);
kfree(port);
}
}
static int __init u300_gpio_probe(struct platform_device *pdev)
{
struct u300_gpio_platform *plat = dev_get_platdata(&pdev->dev);
struct u300_gpio *gpio;
int err = 0;
int portno;
u32 val;
u32 ifr;
int i;
gpio = kzalloc(sizeof(struct u300_gpio), GFP_KERNEL);
if (gpio == NULL) {
dev_err(&pdev->dev, "failed to allocate memory\n");
return -ENOMEM;
}
gpio->chip = u300_gpio_chip;
gpio->chip.ngpio = plat->ports * U300_GPIO_PINS_PER_PORT;
gpio->irq_base = plat->gpio_irq_base;
gpio->chip.dev = &pdev->dev;
gpio->chip.base = plat->gpio_base;
gpio->dev = &pdev->dev;
/* */
gpio->clk = clk_get(gpio->dev, NULL);
if (IS_ERR(gpio->clk)) {
err = PTR_ERR(gpio->clk);
dev_err(gpio->dev, "could not get GPIO clock\n");
goto err_no_clk;
}
err = clk_enable(gpio->clk);
if (err) {
dev_err(gpio->dev, "could not enable GPIO clock\n");
goto err_no_clk_enable;
}
gpio->memres = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!gpio->memres) {
dev_err(gpio->dev, "could not get GPIO memory resource\n");
err = -ENODEV;
goto err_no_resource;
}
if (!request_mem_region(gpio->memres->start,
resource_size(gpio->memres),
"GPIO Controller")) {
err = -ENODEV;
goto err_no_ioregion;
}
gpio->base = ioremap(gpio->memres->start, resource_size(gpio->memres));
if (!gpio->base) {
err = -ENOMEM;
goto err_no_ioremap;
}
if (plat->variant == U300_GPIO_COH901335) {
dev_info(gpio->dev,
"initializing GPIO Controller COH 901 335\n");
gpio->stride = U300_335_PORT_STRIDE;
gpio->pcr = U300_335_PXPCR;
gpio->dor = U300_335_PXPDOR;
gpio->dir = U300_335_PXPDIR;
gpio->per = U300_335_PXPER;
gpio->icr = U300_335_PXICR;
gpio->ien = U300_335_PXIEN;
gpio->iev = U300_335_PXIEV;
ifr = U300_335_PXIFR;
/* */
writel(U300_335_CR_BLOCK_CLOCK_ENABLE,
gpio->base + U300_335_CR);
} else if (plat->variant == U300_GPIO_COH901571_3_BS335 ||
plat->variant == U300_GPIO_COH901571_3_BS365) {
dev_info(gpio->dev,
"initializing GPIO Controller COH 901 571/3\n");
gpio->stride = U300_571_PORT_STRIDE;
gpio->pcr = U300_571_PXPCR;
gpio->dor = U300_571_PXPDOR;
gpio->dir = U300_571_PXPDIR;
gpio->per = U300_571_PXPER;
gpio->icr = U300_571_PXICR;
gpio->ien = U300_571_PXIEN;
gpio->iev = U300_571_PXIEV;
ifr = U300_571_PXIFR;
val = readl(gpio->base + U300_571_CR);
dev_info(gpio->dev, "COH901571/3 block version: %d, " \
"number of cores: %d totalling %d pins\n",
((val & 0x000001FC) >> 2),
((val & 0x0000FE00) >> 9),
((val & 0x0000FE00) >> 9) * 8);
writel(U300_571_CR_BLOCK_CLKRQ_ENABLE,
gpio->base + U300_571_CR);
u300_gpio_init_coh901571(gpio, plat);
} else {
dev_err(gpio->dev, "unknown block variant\n");
err = -ENODEV;
goto err_unknown_variant;
}
/* */
INIT_LIST_HEAD(&gpio->port_list);
for (portno = 0 ; portno < plat->ports; portno++) {
struct u300_gpio_port *port =
kmalloc(sizeof(struct u300_gpio_port), GFP_KERNEL);
if (!port) {
dev_err(gpio->dev, "out of memory\n");
err = -ENOMEM;
goto err_no_port;
}
snprintf(port->name, 8, "gpio%d", portno);
port->number = portno;
port->gpio = gpio;
port->irq = platform_get_irq_byname(pdev,
port->name);
dev_dbg(gpio->dev, "register IRQ %d for %s\n", port->irq,
port->name);
irq_set_chained_handler(port->irq, u300_gpio_irq_handler);
irq_set_handler_data(port->irq, port);
/* */
for (i = 0; i < U300_GPIO_PINS_PER_PORT; i++) {
int irqno = gpio->irq_base + (portno << 3) + i;
dev_dbg(gpio->dev, "handler for IRQ %d on %s\n",
irqno, port->name);
irq_set_chip_and_handler(irqno, &u300_gpio_irqchip,
handle_simple_irq);
set_irq_flags(irqno, IRQF_VALID);
irq_set_chip_data(irqno, port);
}
/* */
writel(0x0, gpio->base + portno * gpio->stride + ifr);
list_add_tail(&port->node, &gpio->port_list);
}
dev_dbg(gpio->dev, "initialized %d GPIO ports\n", portno);
err = gpiochip_add(&gpio->chip);
if (err) {
dev_err(gpio->dev, "unable to add gpiochip: %d\n", err);
goto err_no_chip;
}
/* */
plat->pinctrl_device->dev.platform_data = &gpio->chip;
err = platform_device_register(plat->pinctrl_device);
if (err)
goto err_no_pinctrl;
platform_set_drvdata(pdev, gpio);
return 0;
err_no_pinctrl:
err = gpiochip_remove(&gpio->chip);
err_no_chip:
err_no_port:
u300_gpio_free_ports(gpio);
err_unknown_variant:
iounmap(gpio->base);
err_no_ioremap:
release_mem_region(gpio->memres->start, resource_size(gpio->memres));
err_no_ioregion:
err_no_resource:
clk_disable(gpio->clk);
err_no_clk_enable:
clk_put(gpio->clk);
err_no_clk:
kfree(gpio);
dev_info(&pdev->dev, "module ERROR:%d\n", err);
return err;
}
static int __exit u300_gpio_remove(struct platform_device *pdev)
{
struct u300_gpio_platform *plat = dev_get_platdata(&pdev->dev);
struct u300_gpio *gpio = platform_get_drvdata(pdev);
int err;
/* */
if (plat->variant == U300_GPIO_COH901335)
writel(0x00000000U, gpio->base + U300_335_CR);
if (plat->variant == U300_GPIO_COH901571_3_BS335 ||
plat->variant == U300_GPIO_COH901571_3_BS365)
writel(0x00000000U, gpio->base + U300_571_CR);
err = gpiochip_remove(&gpio->chip);
if (err < 0) {
dev_err(gpio->dev, "unable to remove gpiochip: %d\n", err);
return err;
}
u300_gpio_free_ports(gpio);
iounmap(gpio->base);
release_mem_region(gpio->memres->start,
resource_size(gpio->memres));
clk_disable(gpio->clk);
clk_put(gpio->clk);
platform_set_drvdata(pdev, NULL);
kfree(gpio);
return 0;
}
static struct platform_driver u300_gpio_driver = {
.driver = {
.name = "u300-gpio",
},
.remove = __exit_p(u300_gpio_remove),
};
static int __init u300_gpio_init(void)
{
return platform_driver_probe(&u300_gpio_driver, u300_gpio_probe);
}
static void __exit u300_gpio_exit(void)
{
platform_driver_unregister(&u300_gpio_driver);
}
arch_initcall(u300_gpio_init);
module_exit(u300_gpio_exit);
MODULE_AUTHOR("Linus Walleij <[email protected]>");
MODULE_DESCRIPTION("ST-Ericsson AB COH 901 335/COH 901 571/3 GPIO driver");
MODULE_LICENSE("GPL");
| holyangel/LGE_G3 | drivers/pinctrl/pinctrl-coh901.c | C | gpl-2.0 | 26,082 |
/* Test of select() substitute, reading or writing from a given file descriptor.
Copyright (C) 2008-2018 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/* Written by Bruno Haible <[email protected]>, 2008. */
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
int
main (int argc, char *argv[])
{
if (argc == 4)
{
char mode = argv[1][0];
if (mode == 'r' || mode == 'w')
{
int fd = atoi (argv[2]);
if (fd >= 0)
{
const char *result_file_name = argv[3];
FILE *result_file = fopen (result_file_name, "wb");
if (result_file != NULL)
{
fd_set fds;
struct timeval timeout;
int ret;
FD_ZERO (&fds);
FD_SET (fd, &fds);
timeout.tv_sec = 0;
timeout.tv_usec = 10000;
ret = (mode == 'r'
? select (fd + 1, &fds, NULL, NULL, &timeout)
: select (fd + 1, NULL, &fds, NULL, &timeout));
if (ret < 0)
{
perror ("select failed");
exit (1);
}
if ((ret == 0) != ! FD_ISSET (fd, &fds))
{
fprintf (stderr, "incorrect return value\n");
exit (1);
}
fprintf (result_file, "%d\n", ret);
exit (0);
}
}
}
}
fprintf (stderr, "Usage: test-select-fd mode fd result-file-name\n");
exit (1);
}
| Prelude-SIEM/prelude-manager | libmissing/tests/test-select-fd.c | C | gpl-2.0 | 2,326 |
// license:BSD-3-Clause
// copyright-holders:smf
#include "loopback.h"
const device_type RS232_LOOPBACK = &device_creator<rs232_loopback_device>;
rs232_loopback_device::rs232_loopback_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
: device_t(mconfig, RS232_LOOPBACK, "RS232 Loopback", tag, owner, clock, "rs232_loopback", __FILE__),
device_rs232_port_interface(mconfig, *this)
{
}
void rs232_loopback_device::device_start()
{
}
WRITE_LINE_MEMBER( rs232_loopback_device::input_txd )
{
if (started())
{
output_rxd(state);
}
}
WRITE_LINE_MEMBER( rs232_loopback_device::input_rts )
{
if (started())
{
output_ri(state);
output_cts(state);
}
}
WRITE_LINE_MEMBER( rs232_loopback_device::input_dtr )
{
if (started())
{
output_dsr(state);
output_dcd(state);
}
}
| h0tw1r3/mame | src/devices/bus/rs232/loopback.cpp | C++ | gpl-2.0 | 820 |
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
#include "typedefs.h"
#include "platform.h"
#include "blkdev.h"
#include "cust_nand.h"
#include "nand.h"
#include "nand_core.h"
#include "bmt.h"
#include "part.h"
#include "partition_define.h"
#include "dram_buffer.h"
#ifndef PART_SIZE_BMTPOOL
#define BMT_POOL_SIZE (80)
#else
#define BMT_POOL_SIZE (PART_SIZE_BMTPOOL)
#endif
#define PMT_POOL_SIZE (2)
/******************************************************************************
*
* Macro definition
*
*******************************************************************************/
#define NFI_SET_REG32(reg, value) (DRV_WriteReg32(reg, DRV_Reg32(reg) | (value)))
#define NFI_SET_REG16(reg, value) (DRV_WriteReg16(reg, DRV_Reg16(reg) | (value)))
#define NFI_CLN_REG32(reg, value) (DRV_WriteReg32(reg, DRV_Reg32(reg) & (~(value))))
#define NFI_CLN_REG16(reg, value) (DRV_WriteReg16(reg, DRV_Reg16(reg) & (~(value))))
#define FIFO_PIO_READY(x) (0x1 & x)
#define WAIT_NFI_PIO_READY(timeout) \
do {\
while( (!FIFO_PIO_READY(DRV_Reg(NFI_PIO_DIRDY_REG16))) && (--timeout) );\
if(timeout == 0)\
{\
MSG(ERR, "Error: FIFO_PIO_READY timeout at line=%d, file =%s\n", __LINE__, __FILE__);\
}\
} while(0);
#define TIMEOUT_1 0x1fff
#define TIMEOUT_2 0x8ff
#define TIMEOUT_3 0xffff
#define TIMEOUT_4 5000 //PIO
#define STATUS_READY (0x40)
#define STATUS_FAIL (0x01)
#define STATUS_WR_ALLOW (0x80)
#define NFI_ISSUE_COMMAND(cmd, col_addr, row_addr, col_num, row_num) \
do { \
DRV_WriteReg(NFI_CMD_REG16,cmd);\
while (DRV_Reg32(NFI_STA_REG32) & STA_CMD_STATE);\
DRV_WriteReg32(NFI_COLADDR_REG32, col_addr);\
DRV_WriteReg32(NFI_ROWADDR_REG32, row_addr);\
DRV_WriteReg(NFI_ADDRNOB_REG16, col_num | (row_num<<ADDR_ROW_NOB_SHIFT));\
while (DRV_Reg32(NFI_STA_REG32) & STA_ADDR_STATE);\
}while(0);
u32 PAGE_SIZE;
u32 BLOCK_SIZE;
#define STORAGE_BUFFER_SIZE 0x10000
extern u8 storage_buffer[STORAGE_BUFFER_SIZE];
//u8 __DRAM__ nand_nfi_buf[NAND_NFI_BUFFER_SIZE];
#define nand_nfi_buf g_dram_buf->nand_nfi_buf
/**************************************************************************
* MACRO LIKE FUNCTION
**************************************************************************/
static inline u32 PAGE_NUM(u32 logical_size)
{
return ((unsigned long)(logical_size) / PAGE_SIZE);
}
inline u32 LOGICAL_ADDR(u32 page_addr)
{
return ((unsigned long)(page_addr) * PAGE_SIZE);
}
inline u32 BLOCK_ALIGN(u32 logical_addr)
{
return (((u32) (logical_addr / BLOCK_SIZE)) * BLOCK_SIZE);
}
//---------------------------------------------------------------------------
//-------------------------------------------------------------------------
typedef U32(*STORGE_READ) (u8 * buf, u32 start, u32 img_size);
typedef struct
{
u32 page_size;
u32 pktsz;
} device_info_t;
//-------------------------------------------------------------------------
device_info_t gdevice_info;
boot_dev_t g_dev_vfunc;
static blkdev_t g_nand_bdev;
unsigned char g_nand_spare[128];
unsigned int nand_maf_id;
unsigned int nand_dev_id;
uint8 ext_id1, ext_id2, ext_id3;
static u32 g_u4ChipVer;
static u32 g_i4ErrNum;
static BOOL g_bInitDone;
BOOL g_bHwEcc = TRUE;
u32 PAGE_SIZE;
u32 BLOCK_SIZE;
u8 Bad_Block_Table[8192] = { 0 };
struct nand_chip g_nand_chip;
struct nand_ecclayout *nand_oob = NULL;
static struct nand_ecclayout nand_oob_16 = {
.eccbytes = 8,
.eccpos = {8, 9, 10, 11, 12, 13, 14, 15},
.oobfree = {{1, 6}, {0, 0}}
};
struct nand_ecclayout nand_oob_64 = {
.eccbytes = 32,
.eccpos = {32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63},
.oobfree = {{1, 7}, {9, 7}, {17, 7}, {25, 6}, {0, 0}}
};
struct nand_ecclayout nand_oob_128 = {
.eccbytes = 64,
.eccpos = {
64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 86,
88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 126, 127},
.oobfree = {{1, 7}, {9, 7}, {17, 7}, {25, 7}, {33, 7}, {41, 7}, {49, 7}, {57, 6}}
};
struct NAND_CMD
{
u32 u4ColAddr;
u32 u4RowAddr;
u32 u4OOBRowAddr;
u8 au1OOB[64];
u8 *pDataBuf;
};
static struct NAND_CMD g_kCMD;
static flashdev_info devinfo;
static char *nfi_buf;
bool get_device_info(u8*id, flashdev_info *devinfo);
struct nand_manufacturers nand_manuf_ids[] = {
{NAND_MANFR_TOSHIBA, "Toshiba"},
{NAND_MANFR_SAMSUNG, "Samsung"},
{NAND_MANFR_FUJITSU, "Fujitsu"},
{NAND_MANFR_NATIONAL, "National"},
{NAND_MANFR_RENESAS, "Renesas"},
{NAND_MANFR_STMICRO, "ST Micro"},
{NAND_MANFR_HYNIX, "Hynix"},
{NAND_MANFR_MICRON, "Micron"},
{NAND_MANFR_AMD, "AMD"},
{0x0, "Unknown"}
};
static inline unsigned int uffs(unsigned int x)
{
unsigned int r = 1;
if (!x)
return 0;
if (!(x & 0xffff))
{
x >>= 16;
r += 16;
}
if (!(x & 0xff))
{
x >>= 8;
r += 8;
}
if (!(x & 0xf))
{
x >>= 4;
r += 4;
}
if (!(x & 3))
{
x >>= 2;
r += 2;
}
if (!(x & 1))
{
x >>= 1;
r += 1;
}
return r;
}
#define NAND_SECTOR_SIZE 512
/**************************************************************************
* reset descriptor
**************************************************************************/
void mtk_nand_reset_descriptor(void)
{
g_nand_chip.page_shift = 0;
g_nand_chip.page_size = 0;
g_nand_chip.ChipID = 0; /* Type of DiskOnChip */
g_nand_chip.chips_name = 0;
g_nand_chip.chipsize = 0;
g_nand_chip.erasesize = 0;
g_nand_chip.mfr = 0; /* Flash IDs - only one type of flash per device */
g_nand_chip.id = 0;
g_nand_chip.name = 0;
g_nand_chip.numchips = 0;
g_nand_chip.oobblock = 0; /* Size of OOB blocks (e.g. 512) */
g_nand_chip.oobsize = 0; /* Amount of OOB data per block (e.g. 16) */
g_nand_chip.eccsize = 0;
g_nand_chip.bus16 = 0;
g_nand_chip.nand_ecc_mode = 0;
}
bool get_device_info(u8*id, flashdev_info *devinfo)
{
u32 i,m,n,mismatch;
int target=-1,target_id_len=-1;
for (i = 0; i<CHIP_CNT; i++){
mismatch=0;
for(m=0;m<gen_FlashTable[i].id_length;m++){
if(id[m]!=gen_FlashTable[i].id[m]){
mismatch=1;
break;
}
}
if(mismatch == 0 && gen_FlashTable[i].id_length > target_id_len){
target=i;
target_id_len=gen_FlashTable[i].id_length;
}
}
if(target != -1){
MSG(INIT, "Recognize NAND: ID [");
for(n=0;n<gen_FlashTable[target].id_length;n++){
devinfo->id[n] = gen_FlashTable[target].id[n];
MSG(INIT, "%x ",devinfo->id[n]);
}
MSG(INIT, "], Device Name [%s], Page Size [%d]B Spare Size [%d]B Total Size [%d]MB\n",gen_FlashTable[target].devciename,gen_FlashTable[target].pagesize,gen_FlashTable[target].sparesize,gen_FlashTable[target].totalsize);
devinfo->id_length=gen_FlashTable[i].id_length;
devinfo->blocksize = gen_FlashTable[target].blocksize;
devinfo->addr_cycle = gen_FlashTable[target].addr_cycle;
devinfo->iowidth = gen_FlashTable[target].iowidth;
devinfo->timmingsetting = gen_FlashTable[target].timmingsetting;
devinfo->advancedmode = gen_FlashTable[target].advancedmode;
devinfo->pagesize = gen_FlashTable[target].pagesize;
devinfo->sparesize = gen_FlashTable[target].sparesize;
devinfo->totalsize = gen_FlashTable[target].totalsize;
memcpy(devinfo->devciename, gen_FlashTable[target].devciename, sizeof(devinfo->devciename));
return true;
}else{
MSG(INIT, "Not Found NAND: ID [");
for(n=0;n<NAND_MAX_ID;n++){
MSG(INIT, "%x ",id[n]);
}
MSG(INIT, "]\n");
return false;
}
}
//---------------------------------------------------------------------------
static bool mtk_nand_check_RW_count(u16 u2WriteSize)
{
u32 timeout = 0xFFFF;
u16 u2SecNum = u2WriteSize >> 9;
while (ADDRCNTR_CNTR(DRV_Reg16(NFI_ADDRCNTR_REG16)) < u2SecNum)
{
timeout--;
if (0 == timeout)
{
return FALSE;
}
}
return TRUE;
}
//---------------------------------------------------------------------------
static bool mtk_nand_status_ready(u32 u4Status)
{
u32 timeout = 0xFFFF;
while ((DRV_Reg32(NFI_STA_REG32) & u4Status) != 0)
{
timeout--;
if (0 == timeout)
{
return FALSE;
}
}
return TRUE;
}
//---------------------------------------------------------------------------
static void mtk_nand_set_mode(u16 u2OpMode)
{
u16 u2Mode = DRV_Reg16(NFI_CNFG_REG16);
u2Mode &= ~CNFG_OP_MODE_MASK;
u2Mode |= u2OpMode;
DRV_WriteReg16(NFI_CNFG_REG16, u2Mode);
}
//---------------------------------------------------------------------------
static bool mtk_nand_set_command(u16 command)
{
/* Write command to device */
DRV_WriteReg16(NFI_CMD_REG16, command);
return mtk_nand_status_ready(STA_CMD_STATE);
}
//---------------------------------------------------------------------------
static bool mtk_nand_set_address(u32 u4ColAddr, u32 u4RowAddr, u16 u2ColNOB, u16 u2RowNOB)
{
/* fill cycle addr */
DRV_WriteReg32(NFI_COLADDR_REG32, u4ColAddr);
DRV_WriteReg32(NFI_ROWADDR_REG32, u4RowAddr);
DRV_WriteReg16(NFI_ADDRNOB_REG16, u2ColNOB | (u2RowNOB << ADDR_ROW_NOB_SHIFT));
return mtk_nand_status_ready(STA_ADDR_STATE);
}
//---------------------------------------------------------------------------
static void ECC_Decode_Start(void)
{
/* wait for device returning idle */
while (!(DRV_Reg16(ECC_DECIDLE_REG16) & DEC_IDLE)) ;
DRV_WriteReg16(ECC_DECCON_REG16, DEC_EN);
}
//---------------------------------------------------------------------------
static void ECC_Decode_End(void)
{
/* wait for device returning idle */
while (!(DRV_Reg16(ECC_DECIDLE_REG16) & DEC_IDLE)) ;
DRV_WriteReg16(ECC_DECCON_REG16, DEC_DE);
}
//---------------------------------------------------------------------------
static void ECC_Encode_Start(void)
{
/* wait for device returning idle */
while (!(DRV_Reg32(ECC_ENCIDLE_REG32) & ENC_IDLE)) ;
DRV_WriteReg16(ECC_ENCCON_REG16, ENC_EN);
}
//---------------------------------------------------------------------------
static void ECC_Encode_End(void)
{
/* wait for device returning idle */
while (!(DRV_Reg32(ECC_ENCIDLE_REG32) & ENC_IDLE)) ;
DRV_WriteReg16(ECC_ENCCON_REG16, ENC_DE);
}
//---------------------------------------------------------------------------
static void ECC_Config(u32 ecc_bit)
{
u32 u4ENCODESize;
u32 u4DECODESize;
u32 ecc_bit_cfg = ECC_CNFG_ECC4;
switch (ecc_bit)
{
case 4:
ecc_bit_cfg = ECC_CNFG_ECC4;
break;
case 8:
ecc_bit_cfg = ECC_CNFG_ECC8;
break;
case 10:
ecc_bit_cfg = ECC_CNFG_ECC10;
break;
case 12:
ecc_bit_cfg = ECC_CNFG_ECC12;
break;
default:
break;
}
DRV_WriteReg16(ECC_DECCON_REG16, DEC_DE);
do
{;
}
while (!DRV_Reg16(ECC_DECIDLE_REG16));
DRV_WriteReg16(ECC_ENCCON_REG16, ENC_DE);
do
{;
}
while (!DRV_Reg32(ECC_ENCIDLE_REG32));
/* setup FDM register base */
DRV_WriteReg32(ECC_FDMADDR_REG32, NFI_FDM0L_REG32);
u4ENCODESize = (NAND_SECTOR_SIZE + 8) << 3;
u4DECODESize = ((NAND_SECTOR_SIZE + 8) << 3) + ecc_bit * 13;
/* configure ECC decoder && encoder */
DRV_WriteReg32(ECC_DECCNFG_REG32, ecc_bit_cfg | DEC_CNFG_NFI | DEC_CNFG_EMPTY_EN | (u4DECODESize << DEC_CNFG_CODE_SHIFT));
DRV_WriteReg32(ECC_ENCCNFG_REG32, ecc_bit_cfg | ENC_CNFG_NFI | (u4ENCODESize << ENC_CNFG_MSG_SHIFT));
#ifndef MANUAL_CORRECT
NFI_SET_REG32(ECC_DECCNFG_REG32, DEC_CNFG_CORRECT);
#else
NFI_SET_REG32(ECC_DECCNFG_REG32, DEC_CNFG_EL);
#endif
}
/******************************************************************************
* mtk_nand_check_bch_error
*
* DESCRIPTION:
* Check BCH error or not !
*
* PARAMETERS:
* struct mtd_info *mtd
* u8* pDataBuf
* u32 u4SecIndex
* u32 u4PageAddr
*
* RETURNS:
* None
*
* NOTES:
* None
*
******************************************************************************/
static bool mtk_nand_check_bch_error(u8 * pDataBuf, u32 u4SecIndex, u32 u4PageAddr)
{
bool bRet = TRUE;
u16 u2SectorDoneMask = 1 << u4SecIndex;
u32 u4ErrorNumDebug0, u4ErrorNumDebug1, i, u4ErrNum;
u32 timeout = 0xFFFF;
#ifdef MANUAL_CORRECT
u32 au4ErrBitLoc[6];
u32 u4ErrByteLoc, u4BitOffset;
u32 u4ErrBitLoc1th, u4ErrBitLoc2nd;
#endif
while (0 == (u2SectorDoneMask & DRV_Reg16(ECC_DECDONE_REG16)))
{
timeout--;
if (0 == timeout)
{
return FALSE;
}
}
#ifndef MANUAL_CORRECT
u4ErrorNumDebug0 = DRV_Reg32(ECC_DECENUM0_REG32);
u4ErrorNumDebug1 = DRV_Reg32(ECC_DECENUM1_REG32);
if (0 != (u4ErrorNumDebug0 & 0xFFFFF) || 0 != (u4ErrorNumDebug1 & 0xFFFFF))
{
for (i = 0; i <= u4SecIndex; ++i)
{
if (i < 4)
{
u4ErrNum = DRV_Reg32(ECC_DECENUM0_REG32) >> (i * 5);
} else
{
u4ErrNum = DRV_Reg32(ECC_DECENUM1_REG32) >> ((i - 4) * 5);
}
u4ErrNum &= 0x1F;
if (0x1F == u4ErrNum)
{
MSG(ERR, "In Preloader UnCorrectable at PageAddr=%d, Sector=%d\n", u4PageAddr, i);
bRet = false;
} else
{
if (u4ErrNum)
{
MSG(ERR, " In Preloader Correct %d at PageAddr=%d, Sector=%d\n", u4ErrNum, u4PageAddr, i);
}
}
}
}
#else
/* We will manually correct the error bits in the last sector, not all the sectors of the page!*/
//memset(au4ErrBitLoc, 0x0, sizeof(au4ErrBitLoc));
u4ErrorNumDebug = DRV_Reg32(ECC_DECENUM_REG32);
u4ErrNum = DRV_Reg32(ECC_DECENUM_REG32) >> (u4SecIndex << 2);
u4ErrNum &= 0xF;
if (u4ErrNum)
{
if (0xF == u4ErrNum)
{
//mtd->ecc_stats.failed++;
bRet = FALSE;
} else
{
for (i = 0; i < ((u4ErrNum + 1) >> 1); ++i)
{
au4ErrBitLoc[i] = DRV_Reg32(ECC_DECEL0_REG32 + i);
u4ErrBitLoc1th = au4ErrBitLoc[i] & 0x1FFF;
if (u4ErrBitLoc1th < 0x1000)
{
u4ErrByteLoc = u4ErrBitLoc1th / 8;
u4BitOffset = u4ErrBitLoc1th % 8;
pDataBuf[u4ErrByteLoc] = pDataBuf[u4ErrByteLoc] ^ (1 << u4BitOffset);
//mtd->ecc_stats.corrected++;
} else
{
//mtd->ecc_stats.failed++;
MSG(INIT, "UnCorrectable ErrLoc=%d\n", au4ErrBitLoc[i]);
}
u4ErrBitLoc2nd = (au4ErrBitLoc[i] >> 16) & 0x1FFF;
if (0 != u4ErrBitLoc2nd)
{
if (u4ErrBitLoc2nd < 0x1000)
{
u4ErrByteLoc = u4ErrBitLoc2nd / 8;
u4BitOffset = u4ErrBitLoc2nd % 8;
pDataBuf[u4ErrByteLoc] = pDataBuf[u4ErrByteLoc] ^ (1 << u4BitOffset);
//mtd->ecc_stats.corrected++;
} else
{
//mtd->ecc_stats.failed++;
MSG(INIT, "UnCorrectable High ErrLoc=%d\n", au4ErrBitLoc[i]);
}
}
}
}
if (0 == (DRV_Reg16(ECC_DECFER_REG16) & (1 << u4SecIndex)))
{
bRet = FALSE;
}
}
#endif
return bRet;
}
//---------------------------------------------------------------------------
static bool mtk_nand_RFIFOValidSize(u16 u2Size)
{
u32 timeout = 0xFFFF;
while (FIFO_RD_REMAIN(DRV_Reg16(NFI_FIFOSTA_REG16)) < u2Size)
{
timeout--;
if (0 == timeout)
{
return FALSE;
}
}
if (u2Size == 0)
{
while (FIFO_RD_REMAIN(DRV_Reg16(NFI_FIFOSTA_REG16)))
{
timeout--;
if (0 == timeout)
{
return FALSE;
}
}
}
return TRUE;
}
//---------------------------------------------------------------------------
static bool mtk_nand_WFIFOValidSize(u16 u2Size)
{
u32 timeout = 0xFFFF;
while (FIFO_WR_REMAIN(DRV_Reg16(NFI_FIFOSTA_REG16)) > u2Size)
{
timeout--;
if (0 == timeout)
{
return FALSE;
}
}
if (u2Size == 0)
{
while (FIFO_WR_REMAIN(DRV_Reg16(NFI_FIFOSTA_REG16)))
{
timeout--;
if (0 == timeout)
{
return FALSE;
}
}
}
return TRUE;
}
//---------------------------------------------------------------------------
bool mtk_nand_reset(void)
{
int timeout = 0xFFFF;
if (DRV_Reg16(NFI_MASTERSTA_REG16)) // master is busy
{
DRV_WriteReg16(NFI_CON_REG16, CON_FIFO_FLUSH | CON_NFI_RST);
while (DRV_Reg16(NFI_MASTERSTA_REG16))
{
timeout--;
if (!timeout)
{
MSG(INIT, "MASTERSTA timeout\n");
}
}
}
/* issue reset operation */
DRV_WriteReg16(NFI_CON_REG16, CON_FIFO_FLUSH | CON_NFI_RST);
return mtk_nand_status_ready(STA_NFI_FSM_MASK | STA_NAND_BUSY) && mtk_nand_RFIFOValidSize(0) && mtk_nand_WFIFOValidSize(0);
}
static bool mtk_nand_read_status(void)
{
int status, i;
mtk_nand_reset();
unsigned int timeout;
mtk_nand_reset();
/* Disable HW ECC */
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_HW_ECC_EN);
/* Disable 16-bit I/O */
NFI_CLN_REG16(NFI_PAGEFMT_REG16, PAGEFMT_DBYTE_EN);
NFI_SET_REG16(NFI_CNFG_REG16, CNFG_OP_SRD | CNFG_READ_EN | CNFG_BYTE_RW);
DRV_WriteReg16(NFI_CON_REG16, CON_NFI_SRD | (1 << CON_NOB_SHIFT));
DRV_WriteReg16(NFI_CON_REG16, 0x3);
mtk_nand_set_mode(CNFG_OP_SRD);
DRV_WriteReg16(NFI_CNFG_REG16, 0x2042);
mtk_nand_set_command(NAND_CMD_STATUS);
DRV_WriteReg16(NFI_CON_REG16, 0x90);
timeout = TIMEOUT_4;
WAIT_NFI_PIO_READY(timeout);
if (timeout)
{
status = (DRV_Reg16(NFI_DATAR_REG32));
}
//~ clear NOB
DRV_WriteReg16(NFI_CON_REG16, 0);
if (g_nand_chip.bus16 == NAND_BUS_WIDTH_16)
{
NFI_SET_REG16(NFI_PAGEFMT_REG16, PAGEFMT_DBYTE_EN);
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_BYTE_RW);
}
// check READY/BUSY status first
if (!(STATUS_READY & status))
{
MSG(ERR, "status is not ready\n");
}
// flash is ready now, check status code
if (STATUS_FAIL & status)
{
if (!(STATUS_WR_ALLOW & status))
{
MSG(INIT, "status locked\n");
return FALSE;
} else
{
MSG(INIT, "status unknown\n");
return FALSE;
}
} else
{
return TRUE;
}
}
//---------------------------------------------------------------------------
static void mtk_nand_configure_lock(void)
{
u32 u4WriteColNOB = 2;
u32 u4WriteRowNOB = 3;
u32 u4EraseColNOB = 0;
u32 u4EraseRowNOB = 3;
DRV_WriteReg16(NFI_LOCKANOB_REG16,
(u4WriteColNOB << PROG_CADD_NOB_SHIFT) | (u4WriteRowNOB << PROG_RADD_NOB_SHIFT) | (u4EraseColNOB << ERASE_CADD_NOB_SHIFT) | (u4EraseRowNOB << ERASE_RADD_NOB_SHIFT));
// Workaround method for ECO1 mt6577
if (CHIPVER_ECO_1 == g_u4ChipVer)
{
int i;
for (i = 0; i < 16; ++i)
{
DRV_WriteReg32(NFI_LOCK00ADD_REG32 + (i << 1), 0xFFFFFFFF);
DRV_WriteReg32(NFI_LOCK00FMT_REG32 + (i << 1), 0xFFFFFFFF);
}
//DRV_WriteReg16(NFI_LOCKANOB_REG16, 0x0);
DRV_WriteReg32(NFI_LOCKCON_REG32, 0xFFFFFFFF);
DRV_WriteReg16(NFI_LOCK_REG16, NFI_LOCK_ON);
}
}
//---------------------------------------------------------------------------
static void mtk_nand_configure_fdm(u16 u2FDMSize)
{
NFI_CLN_REG16(NFI_PAGEFMT_REG16, PAGEFMT_FDM_MASK | PAGEFMT_FDM_ECC_MASK);
NFI_SET_REG16(NFI_PAGEFMT_REG16, u2FDMSize << PAGEFMT_FDM_SHIFT);
NFI_SET_REG16(NFI_PAGEFMT_REG16, u2FDMSize << PAGEFMT_FDM_ECC_SHIFT);
}
//---------------------------------------------------------------------------
static void mtk_nand_set_autoformat(bool bEnable)
{
if (bEnable)
{
NFI_SET_REG16(NFI_CNFG_REG16, CNFG_AUTO_FMT_EN);
} else
{
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_AUTO_FMT_EN);
}
}
//---------------------------------------------------------------------------
static void mtk_nand_command_bp(unsigned command)
{
u32 timeout;
switch (command)
{
case NAND_CMD_READID:
/* Issue NAND chip reset command */
NFI_ISSUE_COMMAND(NAND_CMD_RESET, 0, 0, 0, 0);
timeout = TIMEOUT_4;
while (timeout)
timeout--;
mtk_nand_reset();
/* Disable HW ECC */
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_HW_ECC_EN);
/* Disable 16-bit I/O */
NFI_CLN_REG16(NFI_PAGEFMT_REG16, PAGEFMT_DBYTE_EN);
NFI_SET_REG16(NFI_CNFG_REG16, CNFG_READ_EN | CNFG_BYTE_RW);
mtk_nand_reset();
mtk_nand_set_mode(CNFG_OP_SRD);
mtk_nand_set_command(NAND_CMD_READID);
mtk_nand_set_address(0, 0, 1, 0);
DRV_WriteReg16(NFI_CON_REG16, CON_NFI_SRD);
while (DRV_Reg32(NFI_STA_REG32) & STA_DATAR_STATE) ;
break;
default:
break;
}
}
//-----------------------------------------------------------------------------
static u8 mtk_nand_read_byte(void)
{
/* Check the PIO bit is ready or not */
u32 timeout = TIMEOUT_4;
WAIT_NFI_PIO_READY(timeout);
return DRV_Reg8(NFI_DATAR_REG32);
}
bool getflashid(u8 * nand_id, int longest_id_number)
{
u8 maf_id = 0;
u8 dev_id = 0;
int i = 0;
u8 *id = nand_id;
//PDN_Power_CONA_DOWN (PDN_PERI_NFI, FALSE);
DRV_WriteReg32(NFI_ACCCON_REG32, NFI_DEFAULT_ACCESS_TIMING);
DRV_WriteReg16(NFI_CNFG_REG16, 0);
DRV_WriteReg16(NFI_PAGEFMT_REG16, 0);
mtk_nand_command_bp(NAND_CMD_READID);
maf_id = mtk_nand_read_byte();
dev_id = mtk_nand_read_byte();
if (maf_id == 0 || dev_id == 0)
{
return FALSE;
}
//*id= (dev_id<<8)|maf_id;
// *id= (maf_id<<8)|dev_id;
id[0] = maf_id;
id[1] = dev_id;
for (i = 2; i < longest_id_number; i++)
id[i] = mtk_nand_read_byte();
return TRUE;
}
int mtk_nand_init(void)
{
int i, j, busw;
u8 id[NAND_MAX_ID];
u16 spare_bit = 0;
u16 spare_per_sector = 16;
u32 ecc_bit = 4;
nfi_buf = (unsigned char *)NAND_NFI_BUFFER;
memset(&devinfo, 0, sizeof(devinfo));
/* Dynamic Control */
g_bInitDone = FALSE;
g_u4ChipVer = DRV_Reg32(CONFIG_BASE); /*HW_VER */
g_kCMD.u4OOBRowAddr = (u32) - 1;
DRV_WriteReg16(NFI_CSEL_REG16, NFI_DEFAULT_CS);
/* Set default NFI access timing control */
DRV_WriteReg32(NFI_ACCCON_REG32, NFI_DEFAULT_ACCESS_TIMING);
DRV_WriteReg16(NFI_CNFG_REG16, 0);
DRV_WriteReg16(NFI_PAGEFMT_REG16, 0);
/* Reset NFI HW internal state machine and flush NFI in/out FIFO */
mtk_nand_reset();
/* Read the first 4 byte to identify the NAND device */
g_nand_chip.page_shift = NAND_LARGE_PAGE;
g_nand_chip.page_size = 1 << g_nand_chip.page_shift;
g_nand_chip.oobblock = NAND_PAGE_SIZE;
g_nand_chip.oobsize = NAND_BLOCK_BLKS;
g_nand_chip.nand_ecc_mode = NAND_ECC_HW;
mtk_nand_command_bp(NAND_CMD_READID);
for(i=0;i<NAND_MAX_ID;i++){
id[i]=mtk_nand_read_byte ();
}
nand_maf_id = id[0];
nand_dev_id = id[1];
memset(&devinfo, 0, sizeof(devinfo));
if (!get_device_info(id, &devinfo))
{
MSG(INIT, "NAND unsupport\n");
ASSERT(0);
}
g_nand_chip.name = devinfo.devciename;
g_nand_chip.chipsize = devinfo.totalsize << 20;
g_nand_chip.page_size = devinfo.pagesize;
g_nand_chip.page_shift = uffs(g_nand_chip.page_size) - 1;
g_nand_chip.oobblock = g_nand_chip.page_size;
g_nand_chip.erasesize = devinfo.blocksize << 10;
g_nand_chip.bus16 = devinfo.iowidth;
DRV_WriteReg32(NFI_ACCCON_REG32, devinfo.timmingsetting);
if (!devinfo.sparesize)
g_nand_chip.oobsize = (8 << ((ext_id2 >> 2) & 0x01)) * (g_nand_chip.oobblock / 512);
else
g_nand_chip.oobsize = devinfo.sparesize;
spare_per_sector = g_nand_chip.oobsize / (g_nand_chip.page_size / NAND_SECTOR_SIZE);
if (spare_per_sector >= 28)
{
spare_bit = PAGEFMT_SPARE_28;
ecc_bit = 12;
spare_per_sector = 28;
} else if (spare_per_sector >= 27)
{
spare_bit = PAGEFMT_SPARE_27;
ecc_bit = 8;
spare_per_sector = 27;
} else if (spare_per_sector >= 26)
{
spare_bit = PAGEFMT_SPARE_26;
ecc_bit = 8;
spare_per_sector = 26;
} else if (spare_per_sector >= 16)
{
spare_bit = PAGEFMT_SPARE_16;
ecc_bit = 4;
spare_per_sector = 16;
} else
{
MSG(INIT, "[NAND]: NFI not support oobsize: %x\n", spare_per_sector);
ASSERT(0);
}
g_nand_chip.oobsize = spare_per_sector * (g_nand_chip.page_size / NAND_SECTOR_SIZE);
MSG(INIT, "[NAND]: oobsize: %x\n", g_nand_chip.oobsize);
g_nand_chip.chipsize -= g_nand_chip.erasesize * (BMT_POOL_SIZE);
if (g_nand_chip.bus16 == NAND_BUS_WIDTH_16)
{
#ifdef DBG_PRELOADER
MSG(INIT, "USE 16 IO\n");
#endif
NFI_SET_REG16(NFI_PAGEFMT_REG16, PAGEFMT_DBYTE_EN);
}
if (g_nand_chip.oobblock == 4096)
{
NFI_SET_REG16(NFI_PAGEFMT_REG16, (spare_bit << PAGEFMT_SPARE_SHIFT) | PAGEFMT_4K);
nand_oob = &nand_oob_128;
} else if (g_nand_chip.oobblock == 2048)
{
NFI_SET_REG16(NFI_PAGEFMT_REG16, (spare_bit << PAGEFMT_SPARE_SHIFT) | PAGEFMT_2K);
nand_oob = &nand_oob_64;
} else if (g_nand_chip.oobblock == 512)
{
NFI_SET_REG16(NFI_PAGEFMT_REG16, (spare_bit << PAGEFMT_SPARE_SHIFT) | PAGEFMT_512);
nand_oob = &nand_oob_16;
}
if (g_nand_chip.nand_ecc_mode == NAND_ECC_HW)
{
// MSG (INIT, "Use HW ECC\n");
NFI_SET_REG32(NFI_CNFG_REG16, CNFG_HW_ECC_EN);
ECC_Config(ecc_bit);
mtk_nand_configure_fdm(8);
mtk_nand_configure_lock();
}
/* Initilize interrupt. Clear interrupt, read clear. */
DRV_Reg16(NFI_INTR_REG16);
/* Interrupt arise when read data or program data to/from AHB is done. */
DRV_WriteReg16(NFI_INTR_EN_REG16, 0);
if (!(init_bmt(&g_nand_chip, BMT_POOL_SIZE)))
{
MSG(INIT, "Error: init bmt failed, quit!\n");
ASSERT(0);
return 0;
}
g_nand_chip.chipsize -= g_nand_chip.erasesize * (PMT_POOL_SIZE);
return 0;
}
//-----------------------------------------------------------------------------
static void mtk_nand_stop_read(void)
{
NFI_CLN_REG16(NFI_CON_REG16, CON_NFI_BRD);
if (g_bHwEcc)
{
ECC_Decode_End();
}
}
//-----------------------------------------------------------------------------
static void mtk_nand_stop_write(void)
{
NFI_CLN_REG16(NFI_CON_REG16, CON_NFI_BWR);
if (g_bHwEcc)
{
ECC_Encode_End();
}
}
//-----------------------------------------------------------------------------
static bool mtk_nand_check_dececc_done(u32 u4SecNum)
{
u32 timeout, dec_mask;
timeout = 0xffff;
dec_mask = (1 << u4SecNum) - 1;
while ((dec_mask != DRV_Reg(ECC_DECDONE_REG16)) && timeout > 0)
timeout--;
if (timeout == 0)
{
MSG(ERR, "ECC_DECDONE: timeout\n");
return false;
}
return true;
}
//-----------------------------------------------------------------------------
static bool mtk_nand_read_page_data(u32 * buf)
{
u32 timeout = 0xFFFF;
u32 u4Size = g_nand_chip.oobblock;
u32 i;
u32 *pBuf32;
#if (USE_AHB_MODE)
pBuf32 = (u32 *) buf;
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_BYTE_RW);
DRV_Reg16(NFI_INTR_REG16);
DRV_WriteReg16(NFI_INTR_EN_REG16, INTR_AHB_DONE_EN);
NFI_SET_REG16(NFI_CON_REG16, CON_NFI_BRD);
while (!(DRV_Reg16(NFI_INTR_REG16) & INTR_AHB_DONE))
{
timeout--;
if (0 == timeout)
{
return FALSE;
}
}
timeout = 0xFFFF;
while ((u4Size >> 9) > ((DRV_Reg16(NFI_BYTELEN_REG16) & 0xf000) >> 12))
{
timeout--;
if (0 == timeout)
{
return FALSE;
}
}
#else
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_BYTE_RW);
NFI_SET_REG16(NFI_CON_REG16, CON_NFI_BRD);
pBuf32 = (u32 *) buf;
for (i = 0; (i < (u4Size >> 2)) && (timeout > 0);)
{
if (DRV_Reg16(NFI_PIO_DIRDY_REG16) & 1)
{
*pBuf32++ = DRV_Reg32(NFI_DATAR_REG32);
i++;
} else
{
timeout--;
}
if (0 == timeout)
{
return FALSE;
}
}
#endif
return TRUE;
}
//-----------------------------------------------------------------------------
static bool mtk_nand_write_page_data(u32 * buf)
{
u32 timeout = 0xFFFF;
u32 u4Size = g_nand_chip.oobblock;
#if (USE_AHB_MODE)
u32 *pBuf32;
pBuf32 = (u32 *) buf;
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_BYTE_RW);
DRV_Reg16(NFI_INTR_REG16);
DRV_WriteReg16(NFI_INTR_EN_REG16, INTR_AHB_DONE_EN);
NFI_SET_REG16(NFI_CON_REG16, CON_NFI_BWR);
while (!(DRV_Reg16(NFI_INTR_REG16) & INTR_AHB_DONE))
{
timeout--;
if (0 == timeout)
{
return FALSE;
}
}
#else
u32 i;
u32 *pBuf32;
pBuf32 = (u32 *) buf;
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_BYTE_RW);
NFI_SET_REG16(NFI_CON_REG16, CON_NFI_BWR);
for (i = 0; (i < (u4Size >> 2)) && (timeout > 0);)
{
if (DRV_Reg16(NFI_PIO_DIRDY_REG16) & 1)
{
DRV_WriteReg32(NFI_DATAW_REG32, *pBuf32++);
i++;
} else
{
timeout--;
}
if (0 == timeout)
{
return FALSE;
}
}
#endif
return TRUE;
}
//-----------------------------------------------------------------------------
static void mtk_nand_read_fdm_data(u32 u4SecNum, u8 * spare_buf)
{
u32 i;
u32 *pBuf32 = (u32 *) spare_buf;
for (i = 0; i < u4SecNum; ++i)
{
*pBuf32++ = DRV_Reg32(NFI_FDM0L_REG32 + (i << 3));
*pBuf32++ = DRV_Reg32(NFI_FDM0M_REG32 + (i << 3));
}
}
//-----------------------------------------------------------------------------
static void mtk_nand_write_fdm_data(u32 u4SecNum, u8 * oob)
{
u32 i;
u32 *pBuf32 = (u32 *) oob;
for (i = 0; i < u4SecNum; ++i)
{
DRV_WriteReg32(NFI_FDM0L_REG32 + (i << 3), *pBuf32++);
DRV_WriteReg32(NFI_FDM0M_REG32 + (i << 3), *pBuf32++);
}
}
//---------------------------------------------------------------------------
static bool mtk_nand_ready_for_read(u32 page_addr, u32 sec_num, u8 * buf)
{
u32 u4RowAddr = page_addr;
u32 colnob = 2;
u32 rownob = devinfo.addr_cycle - colnob;
bool bRet = FALSE;
if (!mtk_nand_reset())
{
goto cleanup;
}
/* Enable HW ECC */
NFI_SET_REG16(NFI_CNFG_REG16, CNFG_HW_ECC_EN);
mtk_nand_set_mode(CNFG_OP_READ);
NFI_SET_REG16(NFI_CNFG_REG16, CNFG_READ_EN);
DRV_WriteReg16(NFI_CON_REG16, sec_num << CON_NFI_SEC_SHIFT);
#if USE_AHB_MODE
NFI_SET_REG16(NFI_CNFG_REG16, CNFG_AHB);
#else
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_AHB);
#endif
DRV_WriteReg32(NFI_STRADDR_REG32, buf);
if (g_bHwEcc)
{
NFI_SET_REG16(NFI_CNFG_REG16, CNFG_HW_ECC_EN);
} else
{
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_HW_ECC_EN);
}
mtk_nand_set_autoformat(TRUE);
if (g_bHwEcc)
{
ECC_Decode_Start();
}
if (!mtk_nand_set_command(NAND_CMD_READ0))
{
goto cleanup;
}
if (!mtk_nand_set_address(0, u4RowAddr, colnob, rownob))
{
goto cleanup;
}
if (!mtk_nand_set_command(NAND_CMD_READSTART))
{
goto cleanup;
}
if (!mtk_nand_status_ready(STA_NAND_BUSY))
{
goto cleanup;
}
bRet = TRUE;
cleanup:
return bRet;
}
//-----------------------------------------------------------------------------
static bool mtk_nand_ready_for_write(u32 page_addr, u32 sec_num, u8 * buf)
{
bool bRet = FALSE;
u32 u4RowAddr = page_addr;
u32 colnob = 2;
u32 rownob = devinfo.addr_cycle - colnob;
if (!mtk_nand_reset())
{
return FALSE;
}
mtk_nand_set_mode(CNFG_OP_PRGM);
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_READ_EN);
DRV_WriteReg16(NFI_CON_REG16, sec_num << CON_NFI_SEC_SHIFT);
#if USE_AHB_MODE
NFI_SET_REG16(NFI_CNFG_REG16, CNFG_AHB);
DRV_WriteReg32(NFI_STRADDR_REG32, buf);
#else
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_AHB);
#endif
if (g_bHwEcc)
{
NFI_SET_REG16(NFI_CNFG_REG16, CNFG_HW_ECC_EN);
} else
{
NFI_CLN_REG16(NFI_CNFG_REG16, CNFG_HW_ECC_EN);
}
mtk_nand_set_autoformat(TRUE);
if (g_bHwEcc)
{
ECC_Encode_Start();
}
if (!mtk_nand_set_command(NAND_CMD_SEQIN))
{
goto cleanup;
}
if (!mtk_nand_set_address(0, u4RowAddr, colnob, rownob))
{
goto cleanup;
}
if (!mtk_nand_status_ready(STA_NAND_BUSY))
{
goto cleanup;
}
bRet = TRUE;
cleanup:
return bRet;
}
//#############################################################################
//# NAND Driver : Page Read
//#
//# NAND Page Format (Large Page 2KB)
//# |------ Page:2048 Bytes ----->>||---- Spare:64 Bytes -->>|
//#
//# Parameter Description:
//# page_addr : specify the starting page in NAND flash
//#
//#############################################################################
int mtk_nand_read_page_hwecc(unsigned int logical_addr, char *buf)
{
int i, start, len, offset = 0;
int block = logical_addr / g_nand_chip.erasesize;
int page_in_block = PAGE_NUM(logical_addr) % NAND_BLOCK_BLKS;
int mapped_block;
u8 *oob = buf + g_nand_chip.page_size;
mapped_block = get_mapping_block_index(block);
if (!mtk_nand_read_page_hw(page_in_block + mapped_block * NAND_BLOCK_BLKS, buf, g_nand_spare)) // g_nand_spare
return FALSE;
for (i = 0; i < MTD_MAX_OOBFREE_ENTRIES && nand_oob->oobfree[i].length; i++)
{
/* Set the reserved bytes to 0xff */
start = nand_oob->oobfree[i].offset;
len = nand_oob->oobfree[i].length;
memcpy(oob + offset, g_nand_spare + start, len);
offset += len;
}
return true;
}
int mtk_nand_read_page_hw(u32 page, u8 * dat, u8 * oob)
{
bool bRet = TRUE;
u8 *pPageBuf;
u32 u4SecNum = g_nand_chip.oobblock >> NAND_PAGE_SHIFT;
pPageBuf = (u8 *) dat;
if (mtk_nand_ready_for_read(page, u4SecNum, pPageBuf))
{
if (!mtk_nand_read_page_data((u32 *) pPageBuf))
{
bRet = FALSE;
}
if (!mtk_nand_status_ready(STA_NAND_BUSY))
{
bRet = FALSE;
}
if (g_bHwEcc)
{
if (!mtk_nand_check_dececc_done(u4SecNum))
{
bRet = FALSE;
}
}
mtk_nand_read_fdm_data(u4SecNum, oob);
if (g_bHwEcc)
{
if (!mtk_nand_check_bch_error(pPageBuf, u4SecNum - 1, page))
{
MSG(ERASE, "check bch error !\n");
bRet = FALSE;
}
}
mtk_nand_stop_read();
}
return bRet;
}
//#############################################################################
//# NAND Driver : Page Write
//#
//# NAND Page Format (Large Page 2KB)
//# |------ Page:2048 Bytes ----->>||---- Spare:64 Bytes -->>|
//#
//# Parameter Description:
//# page_addr : specify the starting page in NAND flash
//#
//#############################################################################
int mtk_nand_write_page_hwecc(unsigned int logical_addr, char *buf)
{
u16 block = logical_addr / g_nand_chip.erasesize;
u16 mapped_block = get_mapping_block_index(block);
u16 page_in_block = PAGE_NUM(logical_addr) % NAND_BLOCK_BLKS;
u8 *oob = buf + g_nand_chip.oobblock;
int i;
int start, len, offset;
for (i = 0; i < sizeof(g_nand_spare); i++)
*(g_nand_spare + i) = 0xFF;
offset = 0;
for (i = 0; i < MTD_MAX_OOBFREE_ENTRIES && nand_oob->oobfree[i].length; i++)
{
/* Set the reserved bytes to 0xff */
start = nand_oob->oobfree[i].offset;
len = nand_oob->oobfree[i].length;
memcpy((g_nand_spare + start), (oob + offset), len);
offset += len;
}
// write bad index into oob
if (mapped_block != block)
{
set_bad_index_to_oob(g_nand_spare, block);
} else
{
set_bad_index_to_oob(g_nand_spare, FAKE_INDEX);
}
if (!mtk_nand_write_page_hw(page_in_block + mapped_block * NAND_BLOCK_BLKS, buf, g_nand_spare))
{
MSG(INIT, "write fail happened @ block 0x%x, page 0x%x\n", mapped_block, page_in_block);
return update_bmt((page_in_block + mapped_block * NAND_BLOCK_BLKS) * g_nand_chip.oobblock, UPDATE_WRITE_FAIL, buf, g_nand_spare);
}
return TRUE;
}
int mtk_nand_write_page_hw(u32 page, u8 * dat, u8 * oob)
{
bool bRet = TRUE;
u32 pagesz = g_nand_chip.oobblock;
u32 timeout, u4SecNum = pagesz >> NAND_PAGE_SHIFT;
int i, j, start, len;
bool empty = TRUE;
u8 oob_checksum = 0;
for (i = 0; i < MTD_MAX_OOBFREE_ENTRIES && nand_oob->oobfree[i].length; i++)
{
/* Set the reserved bytes to 0xff */
start = nand_oob->oobfree[i].offset;
len = nand_oob->oobfree[i].length;
for (j = 0; j < len; j++)
{
oob_checksum ^= oob[start + j];
if (oob[start + j] != 0xFF)
empty = FALSE;
}
}
if (!empty)
{
oob[nand_oob->oobfree[i - 1].offset + nand_oob->oobfree[i - 1].length] = oob_checksum;
}
while (DRV_Reg32(NFI_STA_REG32) & STA_NAND_BUSY) ;
if (mtk_nand_ready_for_write(page, u4SecNum, dat))
{
mtk_nand_write_fdm_data(u4SecNum, oob);
if (!mtk_nand_write_page_data((u32 *) dat))
{
bRet = FALSE;
}
if (!mtk_nand_check_RW_count(g_nand_chip.oobblock))
{
bRet = FALSE;
}
mtk_nand_stop_write();
mtk_nand_set_command(NAND_CMD_PAGEPROG);
mtk_nand_status_ready(STA_NAND_BUSY);
return mtk_nand_read_status();
} else
{
return FALSE;
}
return bRet;
}
unsigned int nand_block_bad(unsigned int logical_addr)
{
int block = logical_addr / g_nand_chip.erasesize;
int mapped_block = get_mapping_block_index(block);
if (nand_block_bad_hw(mapped_block * g_nand_chip.erasesize))
{
if (update_bmt(mapped_block * g_nand_chip.erasesize, UPDATE_UNMAPPED_BLOCK, NULL, NULL))
{
return logical_addr; // return logical address
}
return logical_addr + g_nand_chip.erasesize;
}
return logical_addr;
}
bool nand_block_bad_hw(u32 logical_addr)
{
bool bRet = FALSE;
u32 page = logical_addr / g_nand_chip.oobblock;
int i, page_num = (g_nand_chip.erasesize / g_nand_chip.oobblock);
unsigned char *pspare;
char *tmp = (char *)nfi_buf;
memset(tmp, 0x0, g_nand_chip.oobblock + g_nand_chip.oobsize);
u32 u4SecNum = g_nand_chip.oobblock >> NAND_PAGE_SHIFT;
page &= ~(page_num - 1);
if (mtk_nand_ready_for_read(page, u4SecNum, tmp))
{
if (!mtk_nand_read_page_data((u32 *) tmp))
{
bRet = FALSE;
}
if (!mtk_nand_status_ready(STA_NAND_BUSY))
{
bRet = FALSE;
}
if (!mtk_nand_check_dececc_done(u4SecNum))
{
bRet = FALSE;
}
mtk_nand_read_fdm_data(u4SecNum, g_nand_spare);
if (!mtk_nand_check_bch_error(tmp, u4SecNum - 1, page))
{
MSG(ERASE, "check bch error !\n");
bRet = FALSE;
}
mtk_nand_stop_read();
}
pspare = g_nand_spare;
if (pspare[0] != 0xFF || pspare[8] != 0xFF || pspare[16] != 0xFF || pspare[24] != 0xFF)
{
bRet = TRUE;
// break;
}
return bRet;
}
bool mark_block_bad(u32 logical_addr)
{
int block = logical_addr / g_nand_chip.erasesize;
int mapped_block = get_mapping_block_index(block);
return mark_block_bad_hw(mapped_block * g_nand_chip.erasesize);
}
bool mark_block_bad_hw(u32 offset)
{
bool bRet = FALSE;
u32 index;
u32 page_addr = offset / g_nand_chip.oobblock;
u32 u4SecNum = g_nand_chip.oobblock >> NAND_PAGE_SHIFT;
unsigned char *pspare;
int i, page_num = (g_nand_chip.erasesize / g_nand_chip.oobblock);
unsigned char buf[2048];
for (index = 0; index < 64; index++)
*(g_nand_spare + index) = 0xFF;
pspare = g_nand_spare;
for (index = 8, i = 0; i < 4; i++)
pspare[i * index] = 0x0;
page_addr &= ~(page_num - 1);
MSG(BAD, "Mark bad block at 0x%x\n", page_addr);
while (DRV_Reg32(NFI_STA_REG32) & STA_NAND_BUSY) ;
if (mtk_nand_ready_for_write(page_addr, u4SecNum, buf))
{
mtk_nand_write_fdm_data(u4SecNum, g_nand_spare);
if (!mtk_nand_write_page_data((u32 *) & buf))
{
bRet = FALSE;
}
if (!mtk_nand_check_RW_count(g_nand_chip.oobblock))
{
bRet = FALSE;
}
mtk_nand_stop_write();
mtk_nand_set_command(NAND_CMD_PAGEPROG);
mtk_nand_status_ready(STA_NAND_BUSY);
} else
{
return FALSE;
}
for (index = 0; index < 64; index++)
*(g_nand_spare + index) = 0xFF;
}
//#############################################################################
//# NAND Driver : Page Write
//#
//# NAND Page Format (Large Page 2KB)
//# |------ Page:2048 Bytes ----->>||---- Spare:64 Bytes -->>|
//#
//# Parameter Description:
//# page_addr : specify the starting page in NAND flash
//#
//#############################################################################
bool mtk_nand_erase_hw(u32 offset)
{
bool bRet = TRUE;
u32 timeout, u4SecNum = g_nand_chip.oobblock >> NAND_PAGE_SHIFT;
u32 rownob = devinfo.addr_cycle - 2;
u32 page_addr = offset / g_nand_chip.oobblock;
if (nand_block_bad_hw(offset))
{
return FALSE;
}
mtk_nand_reset();
mtk_nand_set_mode(CNFG_OP_ERASE);
mtk_nand_set_command(NAND_CMD_ERASE1);
mtk_nand_set_address(0, page_addr, 0, rownob);
mtk_nand_set_command(NAND_CMD_ERASE2);
if (!mtk_nand_status_ready(STA_NAND_BUSY))
{
return FALSE;
}
if (!mtk_nand_read_status())
{
return FALSE;
}
return bRet;
}
int mtk_nand_erase(u32 logical_addr)
{
int block = logical_addr / g_nand_chip.erasesize;
int mapped_block = get_mapping_block_index(block);
if (!mtk_nand_erase_hw(mapped_block * g_nand_chip.erasesize))
{
MSG(INIT, "erase block 0x%x failed\n", mapped_block);
return update_bmt(mapped_block * g_nand_chip.erasesize, UPDATE_ERASE_FAIL, NULL, NULL);
}
return TRUE;
}
bool mtk_nand_wait_for_finish(void)
{
while (DRV_Reg32(NFI_STA_REG32) & STA_NAND_BUSY) ;
return TRUE;
}
/**************************************************************************
* MACRO LIKE FUNCTION
**************************************************************************/
static int nand_bread(blkdev_t * bdev, u32 blknr, u32 blks, u8 * buf)
{
u32 i;
u32 offset = blknr * bdev->blksz;
for (i = 0; i < blks; i++)
{
offset = nand_read_data(buf, offset);
offset += bdev->blksz;
buf += bdev->blksz;
}
return 0;
}
static int nand_bwrite(blkdev_t * bdev, u32 blknr, u32 blks, u8 * buf)
{
u32 i;
u32 offset = blknr * bdev->blksz;
for (i = 0; i < blks; i++)
{
offset = nand_write_data(buf, offset);
offset += bdev->blksz;
buf += bdev->blksz;
}
return 0;
}
// ==========================================================
// NAND Common Interface - Init
// ==========================================================
u32 nand_init_device(void)
{
if (!blkdev_get(BOOTDEV_NAND))
{
mtk_nand_reset_descriptor();
mtk_nand_init();
PAGE_SIZE = (u32) g_nand_chip.page_size;
BLOCK_SIZE = (u32) g_nand_chip.erasesize;
memset(&g_nand_bdev, 0, sizeof(blkdev_t));
g_nand_bdev.blksz = g_nand_chip.page_size;
g_nand_bdev.erasesz = g_nand_chip.erasesize;
g_nand_bdev.blks = g_nand_chip.chipsize;
g_nand_bdev.bread = nand_bread;
g_nand_bdev.bwrite = nand_bwrite;
g_nand_bdev.blkbuf = (u8 *) storage_buffer;
g_nand_bdev.type = BOOTDEV_NAND;
blkdev_register(&g_nand_bdev);
}
return 0;
}
void Invert_Bits(u8 * buff_ptr, u32 bit_pos)
{
u32 byte_pos = 0;
u8 byte_val = 0;
u8 temp_val = 0;
u32 invert_bit = 0;
byte_pos = bit_pos >> 3;
invert_bit = bit_pos & ((1 << 3) - 1);
byte_val = buff_ptr[byte_pos];
temp_val = byte_val & (1 << invert_bit);
if (temp_val > 0)
byte_val &= ~temp_val;
else
byte_val |= (1 << invert_bit);
buff_ptr[byte_pos] = byte_val;
}
void compare_page(u8 * testbuff, u8 * sourcebuff, u32 length, char *s)
{
u32 errnum = 0;
u32 ii = 0;
u32 index;
printf("%s", s);
for (index = 0; index < length; index++)
{
if (testbuff[index] != sourcebuff[index])
{
u8 t = sourcebuff[index] ^ testbuff[index];
for (ii = 0; ii < 8; ii++)
{
if ((t >> ii) & 0x1 == 1)
{
errnum++;
}
}
printf(" ([%d]=%x) != ([%d]=%x )", index, sourcebuff[index], index, testbuff[index]);
}
}
if (errnum > 0)
{
printf(": page have %d mismatch bits\n", errnum);
} else
{
printf(" :the two buffers are same!\n");
}
}
u8 empty_page(u8 * sourcebuff, u32 length)
{
u32 index = 0;
for (index = 0; index < length; index++)
{
if (sourcebuff[index] != 0xFF)
{
return 0;
}
}
return 1;
}
u32 __nand_ecc_test(u32 offset, u32 max_ecc_capable)
{
int ecc_level = max_ecc_capable;
int sec_num = g_nand_chip.page_size >> 9;
u32 sec_size = g_nand_chip.page_size / sec_num;
u32 NAND_MAX_PAGE_LENGTH = g_nand_chip.page_size + 8 * sec_num;
u32 chk_bit_len = 64 * 4;
u32 page_per_blk = g_nand_chip.erasesize / g_nand_chip.page_size;
u32 sec_index, curr_error_bit, err_bits_per_sec, page_idx, errbits, err;
u8 *testbuff = malloc(NAND_MAX_PAGE_LENGTH);
u8 *sourcebuff = malloc(NAND_MAX_PAGE_LENGTH);
u8 empty;
for (err_bits_per_sec = 1; err_bits_per_sec <= ecc_level; err_bits_per_sec++)
{
printf("~~~start test ecc correct in ");
#if USE_AHB_MODE
printf(" AHB mode");
#else
printf(" MCU mode");
#endif
printf(", every sector have %d bit error~~~\n", err_bits_per_sec);
for (curr_error_bit = 0; curr_error_bit < chk_bit_len && offset < g_nand_chip.chipsize; offset += g_nand_chip.page_size)
{
memset(testbuff, 0x0a, NAND_MAX_PAGE_LENGTH);
memset(sourcebuff, 0x0b, NAND_MAX_PAGE_LENGTH);
g_bHwEcc = TRUE;
nand_read_data(sourcebuff, offset);
empty = empty_page(sourcebuff, g_nand_chip.page_size);
if (empty)
{
printf("page %d is empty\n", offset / g_nand_chip.page_size);
memset(sourcebuff, 0x0c, NAND_MAX_PAGE_LENGTH);
nand_write_data(sourcebuff, offset);
nand_read_data(sourcebuff, offset);
}
if (0 != (DRV_Reg32(ECC_DECENUM0_REG32) & 0xFFFFF) ||0 != (DRV_Reg32(ECC_DECENUM1_REG32) & 0xFFFFF) )
{
printf("skip the page %d, because it is empty ( %d )or already have error bits (%x)!\n", offset / g_nand_chip.page_size, empty, err);
} else
{
printf("~~~start test ecc correct in Page 0x%x ~~~\n", offset / g_nand_chip.page_size);
memcpy(testbuff, sourcebuff, NAND_MAX_PAGE_LENGTH);
for (sec_index = 0; sec_index < sec_num; sec_index++)
{
//printf("insert err bit @ page %d:sector %d : bit ",page_idx+offset/g_nand_chip.page_size,sec_index);
for (errbits = 0; errbits < err_bits_per_sec; errbits++)
{
Invert_Bits(((u8 *) testbuff) + sec_index * sec_size, curr_error_bit);
//printf("%d, ",curr_error_bit);
curr_error_bit++;
}
//printf("\n");
}
g_bHwEcc = FALSE;
nand_write_data(testbuff, offset);
compare_page(testbuff, sourcebuff, NAND_MAX_PAGE_LENGTH, "source and test buff check ");
g_bHwEcc = TRUE;
nand_read_data(testbuff, offset);
compare_page(testbuff, sourcebuff, NAND_MAX_PAGE_LENGTH, "read back check ");
}
}
}
free(testbuff);
free(sourcebuff);
}
u32 nand_ecc_test(void)
{
part_t *part = part_get(PART_UBOOT);
u32 offset = (part->startblk) * g_nand_chip.page_size;
__nand_ecc_test(offset, 4);
part_t *part2 = part_get(PART_BOOTIMG);
offset = (part2->startblk) * g_nand_chip.page_size;
__nand_ecc_test(offset, 4);
return 0;
}
u32 nand_get_device_id(u8 * id, u32 len)
{
u8 buf[16];
if (TRUE != getflashid(buf, len))
return -1;
len = len > 16 ? 16 : len;
memcpy(id, buf, len);
return 0;
}
/* LEGACY - TO BE REMOVED { */
// ==========================================================
// NAND Common Interface - Correct R/W Address
// ==========================================================
u32 nand_find_safe_block(u32 offset)
{
u32 original_offset = offset;
u32 new_offset = 0;
unsigned int blk_index = 0;
static BOOL Bad_Block_Table_init = FALSE;
if (Bad_Block_Table_init == FALSE)
{
Bad_Block_Table_init = TRUE;
memset(Bad_Block_Table, 0, sizeof(Bad_Block_Table));
print("Bad_Block_Table init, sizeof(Bad_Block_Table)= %d \n", sizeof(Bad_Block_Table));
}
blk_index = BLOCK_ALIGN(offset) / BLOCK_SIZE;
if (Bad_Block_Table[blk_index] == 1)
{
return offset;
}
// new_offset is block alignment
new_offset = nand_block_bad(BLOCK_ALIGN(offset));
// find next block until the block is good
while (new_offset != BLOCK_ALIGN(offset))
{
offset = new_offset;
new_offset = nand_block_bad(BLOCK_ALIGN(offset));
}
if (original_offset != offset)
{
Bad_Block_Table[(original_offset / BLOCK_SIZE)] = 2;
print("offset (0x%x) is bad block. next safe block is (0x%x)\n", original_offset, offset);
}
Bad_Block_Table[(BLOCK_ALIGN(offset) / BLOCK_SIZE)] = 1;
return offset;
}
/* LEGACY - TO BE REMOVED } */
// ==========================================================
// NAND Common Interface - Read Function
// ==========================================================
u32 nand_read_data(u8 * buf, u32 offset)
{
// make sure the block is safe to flash
offset = nand_find_safe_block(offset);
if (mtk_nand_read_page_hwecc(offset, buf) == FALSE)
{
print("nand_read_data fail\n");
return -1;
}
return offset;
}
// ==========================================================
// NAND Common Interface - Write Function
// ==========================================================
u32 nand_write_data(u8 * buf, u32 offset)
{
// make sure the block is safe to flash
offset = nand_find_safe_block(offset);
if (mtk_nand_write_page_hwecc(offset, buf) == FALSE)
{
print("nand_write_data fail\n");
ASSERT(0);
}
return offset;
}
// ==========================================================
// NAND Common Interface - Erase Function
// ==========================================================
bool nand_erase_data(u32 offset, u32 offset_limit, u32 size)
{
u32 img_size = size;
u32 tpgsz;
u32 tblksz;
u32 cur_offset;
u32 i = 0;
// do block alignment check
if (offset % BLOCK_SIZE != 0)
{
print("offset must be block alignment (0x%x)\n", BLOCK_SIZE);
ASSERT(0);
}
// calculate block number of this image
if ((img_size % BLOCK_SIZE) == 0)
{
tblksz = img_size / BLOCK_SIZE;
} else
{
tblksz = (img_size / BLOCK_SIZE) + 1;
}
print("[ERASE] image size = 0x%x\n", img_size);
print("[ERASE] the number of nand block of this image = %d\n", tblksz);
// erase nand block
cur_offset = offset;
while (tblksz != 0)
{
if (mtk_nand_erase(cur_offset) == FALSE)
{
print("[ERASE] erase fail\n");
mark_block_bad(cur_offset);
//ASSERT (0);
}
cur_offset += BLOCK_SIZE;
tblksz--;
if (tblksz != 0 && cur_offset >= offset_limit)
{
print("[ERASE] cur offset (0x%x) exceeds erase limit address (0x%x)\n", cur_offset, offset_limit);
return TRUE;
}
}
return TRUE;
}
| rimistri/mediatek | mt6732/mediatek/platform/mt6752/preloader/src/drivers/nand.c | C | gpl-2.0 | 56,074 |
#pragma once
/*
* Copyright (C) 2012-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
/*
* DESCRIPTION:
*
* CPVRTimerInfoTag is part of the PVRManager to support sheduled recordings.
*
* The timer information tag holds data about current programmed timers for
* the PVRManager. It is possible to create timers directly based upon
* a EPG entry by giving the EPG information tag or as instant timer
* on currently tuned channel, or give a blank tag to modify later.
*
* With exception of the blank one, the tag can easily and unmodified added
* by the PVRManager function "bool AddTimer(const CFileItem &item)" to
* the backend server.
*
* The filename inside the tag is for reference only and gives the index
* number of the tag reported by the PVR backend and can not be played!
*/
#include "XBDateTime.h"
#include "addons/include/xbmc_pvr_types.h"
#include "utils/ISerializable.h"
#include <memory>
class CFileItem;
namespace EPG
{
class CEpgInfoTag;
typedef std::shared_ptr<EPG::CEpgInfoTag> CEpgInfoTagPtr;
}
namespace PVR
{
class CGUIDialogPVRTimerSettings;
class CPVRTimers;
class CPVRChannelGroupInternal;
class CPVRChannel;
typedef std::shared_ptr<PVR::CPVRChannel> CPVRChannelPtr;
class CPVRTimerInfoTag;
typedef std::shared_ptr<PVR::CPVRTimerInfoTag> CPVRTimerInfoTagPtr;
class CPVRTimerInfoTag : public ISerializable
{
friend class CPVRTimers;
public:
CPVRTimerInfoTag(bool bRadio = false);
CPVRTimerInfoTag(const PVR_TIMER &timer, const CPVRChannelPtr &channel, unsigned int iClientId);
private:
CPVRTimerInfoTag(const CPVRTimerInfoTag &tag); // intentionally not implemented.
CPVRTimerInfoTag &operator=(const CPVRTimerInfoTag &orig); // intentionally not implemented.
public:
virtual ~CPVRTimerInfoTag(void);
bool operator ==(const CPVRTimerInfoTag& right) const;
bool operator !=(const CPVRTimerInfoTag& right) const;
virtual void Serialize(CVariant &value) const;
int Compare(const CPVRTimerInfoTag &timer) const;
void UpdateSummary(void);
void DisplayError(PVR_ERROR err) const;
std::string GetStatus() const;
bool SetDuration(int iDuration);
static CPVRTimerInfoTagPtr CreateFromEpg(const EPG::CEpgInfoTagPtr &tag);
EPG::CEpgInfoTagPtr GetEpgInfoTag(void) const;
/*!
* @return True if this timer has a corresponding epg info tag, false otherwise
*/
bool HasEpgInfoTag() const;
int ChannelNumber(void) const;
std::string ChannelName(void) const;
std::string ChannelIcon(void) const;
CPVRChannelPtr ChannelTag(void) const;
bool UpdateEntry(const CPVRTimerInfoTagPtr &tag);
void UpdateEpgEvent(bool bClear = false);
bool IsActive(void) const
{
return m_state == PVR_TIMER_STATE_SCHEDULED
|| m_state == PVR_TIMER_STATE_RECORDING
|| m_state == PVR_TIMER_STATE_CONFLICT_OK
|| m_state == PVR_TIMER_STATE_CONFLICT_NOK
|| m_state == PVR_TIMER_STATE_ERROR;
}
bool IsRecording(void) const { return m_state == PVR_TIMER_STATE_RECORDING; }
CDateTime StartAsUTC(void) const;
CDateTime StartAsLocalTime(void) const;
void SetStartFromUTC(CDateTime &start) { m_StartTime = start; }
void SetStartFromLocalTime(CDateTime &start) { m_StartTime = start.GetAsUTCDateTime(); }
CDateTime EndAsUTC(void) const;
CDateTime EndAsLocalTime(void) const;
void SetEndFromUTC(CDateTime &end) { m_StopTime = end; }
void SetEndFromLocalTime(CDateTime &end) { m_StopTime = end.GetAsUTCDateTime(); }
CDateTime FirstDayAsUTC(void) const;
CDateTime FirstDayAsLocalTime(void) const;
void SetFirstDayFromUTC(CDateTime &firstDay) { m_FirstDay = firstDay; }
void SetFirstDayFromLocalTime(CDateTime &firstDay) { m_FirstDay = firstDay.GetAsUTCDateTime(); }
unsigned int MarginStart(void) const { return m_iMarginStart; }
void SetMarginStart(unsigned int iMinutes) { m_iMarginStart = iMinutes; }
unsigned int MarginEnd(void) const { return m_iMarginEnd; }
void SetMarginEnd(unsigned int iMinutes) { m_iMarginEnd = iMinutes; }
bool SupportsFolders() const;
/*!
* @brief Show a notification for this timer in the UI
*/
void QueueNotification(void) const;
/*!
* @brief Get the text for the notification.
* @param strText The notification.
*/
void GetNotificationText(std::string &strText) const;
/*!
* @brief Get the text for the notification when a timer has been deleted
*/
std::string GetDeletedNotificationText() const;
const std::string& Title(void) const;
const std::string& Summary(void) const;
const std::string& Path(void) const;
/* Client control functions */
bool AddToClient() const;
bool DeleteFromClient(bool bForce = false) const;
bool RenameOnClient(const std::string &strNewName);
bool UpdateOnClient();
void SetEpgInfoTag(EPG::CEpgInfoTagPtr &tag);
void ClearEpgTag(void);
void UpdateChannel(void);
std::string m_strTitle; /*!< @brief name of this timer */
std::string m_strDirectory; /*!< @brief directory where the recording must be stored */
std::string m_strSummary; /*!< @brief summary string with the time to show inside a GUI list */
PVR_TIMER_STATE m_state; /*!< @brief the state of this timer */
int m_iClientId; /*!< @brief ID of the backend */
int m_iClientIndex; /*!< @brief index number of the tag, given by the backend, -1 for new */
int m_iClientChannelUid; /*!< @brief channel uid */
int m_iPriority; /*!< @brief priority of the timer */
int m_iLifetime; /*!< @brief lifetime of the timer in days */
bool m_bIsRepeating; /*!< @brief repeating timer if true, use the m_FirstDay and repeat flags */
int m_iWeekdays; /*!< @brief bit based store of weekdays to repeat */
std::string m_strFileNameAndPath; /*!< @brief filename is only for reference */
int m_iChannelNumber; /*!< @brief integer value of the channel number */
bool m_bIsRadio; /*!< @brief is radio channel if set */
unsigned int m_iTimerId; /*!< @brief id that won't change as long as XBMC is running */
CPVRChannelPtr m_channel;
unsigned int m_iMarginStart; /*!< @brief (optional) if set, the backend starts the recording iMarginStart minutes before startTime. */
unsigned int m_iMarginEnd; /*!< @brief (optional) if set, the backend ends the recording iMarginEnd minutes after endTime. */
std::vector<std::string> m_genre; /*!< @brief genre of the timer */
int m_iGenreType; /*!< @brief genre type of the timer */
int m_iGenreSubType; /*!< @brief genre subtype of the timer */
private:
CCriticalSection m_critSection;
EPG::CEpgInfoTagPtr m_epgTag;
CDateTime m_StartTime; /*!< start time */
CDateTime m_StopTime; /*!< stop time */
CDateTime m_FirstDay; /*!< if it is a repeating timer the first date it starts */
};
}
| dua123/xbmc | xbmc/pvr/timers/PVRTimerInfoTag.h | C | gpl-2.0 | 8,036 |
<?php
defined('_JEXEC') or die();
/**
*
* @package VirtueMart
* @subpackage Plugins - Elements
* @author Valérie Isaksen
* @version $Id: categories.php 8229 2014-08-23 16:56:12Z alatak $
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - September 20 2016 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
if (!class_exists('VmConfig')) {
require(VMPATH_ROOT . DS . 'administrator' . DS . 'components' . DS . 'com_virtuemart' . DS . 'helpers' . DS . 'config.php');
}
if (!class_exists('ShopFunctions')) {
require(VMPATH_ADMIN . DS . 'helpers' . DS . 'shopfunctions.php');
}
if (!class_exists('TableCategories')) {
require(VMPATH_ADMIN . DS . 'tables' . DS . 'categories.php');
}
jimport('joomla.form.formfield');
class JFormFieldcategories extends JFormFieldList {
var $type = 'categories';
var $class = '';
protected function getInput() {
//VmConfig::loadJLang('com_virtuemart');
$categorylist = ShopFunctions::categoryListTree(array($this->value));
$html = '<select multiple="true" class="inputbox ' . $this->class . '" name="' . $this->name . '" >';
$html .= '<option value="0">' . vmText::_('COM_VIRTUEMART_NONE') . '</option>';
$html .= $categorylist;
$html .= "</select>";
return $html;
}
}
| sajithaliyanage/CMS | tmp/install_581db1f1811d8/admin/plugins/vmpayment/amazon/fields/categories.php | PHP | gpl-2.0 | 1,600 |
#include QMK_KEYBOARD_H
#include "oneshot.h"
#include "swapper.h"
#define HOME G(KC_LEFT)
#define END G(KC_RGHT)
#define FWD G(KC_RBRC)
#define BACK G(KC_LBRC)
#define TABL G(S(KC_LBRC))
#define TABR G(S(KC_RBRC))
#define SPCL A(G(KC_LEFT))
#define SPCR A(G(KC_RGHT))
#define LA_SYM MO(SYM)
#define LA_NAV MO(NAV)
enum layers {
DEF,
SYM,
NAV,
NUM,
};
enum keycodes {
// Custom oneshot mod implementation with no timers.
OS_SHFT = SAFE_RANGE,
OS_CTRL,
OS_ALT,
OS_CMD,
SW_WIN, // Switch to next window (cmd-tab)
SW_LANG, // Switch to next input language (ctl-spc)
};
const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
[DEF] = LAYOUT_callum(
KC_Q, KC_W, KC_F, KC_P, KC_G, KC_J, KC_L, KC_U, KC_Y, KC_QUOT,
KC_A, KC_R, KC_S, KC_T, KC_D, KC_H, KC_N, KC_E, KC_I, KC_O,
KC_Z, KC_X, KC_C, KC_V, KC_B, KC_K, KC_M, KC_COMM, KC_DOT, KC_SLSH,
LA_NAV, KC_LSFT, KC_SPC, LA_SYM
),
[SYM] = LAYOUT_callum(
KC_ESC, KC_LBRC, KC_LCBR, KC_LPRN, KC_TILD, KC_CIRC, KC_RPRN, KC_RCBR, KC_RBRC, KC_GRV,
KC_MINS, KC_ASTR, KC_EQL, KC_UNDS, KC_DLR, KC_HASH, OS_CMD, OS_ALT, OS_CTRL, OS_SHFT,
KC_PLUS, KC_PIPE, KC_AT, KC_BSLS, KC_PERC, XXXXXXX, KC_AMPR, KC_SCLN, KC_COLN, KC_EXLM,
_______, _______, _______, _______
),
[NAV] = LAYOUT_callum(
KC_TAB, SW_WIN, TABL, TABR, KC_VOLU, RESET, HOME, KC_UP, END, KC_DEL,
OS_SHFT, OS_CTRL, OS_ALT, OS_CMD, KC_VOLD, KC_CAPS, KC_LEFT, KC_DOWN, KC_RGHT, KC_BSPC,
SPCL, SPCR, BACK, FWD, KC_MPLY, XXXXXXX, KC_PGDN, KC_PGUP, SW_LANG, KC_ENT,
_______, _______, _______, _______
),
[NUM] = LAYOUT_callum(
KC_7, KC_5, KC_3, KC_1, KC_9, KC_8, KC_0, KC_2, KC_4, KC_6,
OS_SHFT, OS_CTRL, OS_ALT, OS_CMD, KC_F11, KC_F10, OS_CMD, OS_ALT, OS_CTRL, OS_SHFT,
KC_F7, KC_F5, KC_F3, KC_F1, KC_F9, KC_F8, KC_F12, KC_F2, KC_F4, KC_F6,
_______, _______, _______, _______
),
};
bool is_oneshot_cancel_key(uint16_t keycode) {
switch (keycode) {
case LA_SYM:
case LA_NAV:
return true;
default:
return false;
}
}
bool is_oneshot_ignored_key(uint16_t keycode) {
switch (keycode) {
case LA_SYM:
case LA_NAV:
case KC_LSFT:
case OS_SHFT:
case OS_CTRL:
case OS_ALT:
case OS_CMD:
return true;
default:
return false;
}
}
bool sw_win_active = false;
bool sw_lang_active = false;
oneshot_state os_shft_state = os_up_unqueued;
oneshot_state os_ctrl_state = os_up_unqueued;
oneshot_state os_alt_state = os_up_unqueued;
oneshot_state os_cmd_state = os_up_unqueued;
bool process_record_user(uint16_t keycode, keyrecord_t *record) {
update_swapper(
&sw_win_active, KC_LGUI, KC_TAB, SW_WIN,
keycode, record
);
update_swapper(
&sw_lang_active, KC_LCTL, KC_SPC, SW_LANG,
keycode, record
);
update_oneshot(
&os_shft_state, KC_LSFT, OS_SHFT,
keycode, record
);
update_oneshot(
&os_ctrl_state, KC_LCTL, OS_CTRL,
keycode, record
);
update_oneshot(
&os_alt_state, KC_LALT, OS_ALT,
keycode, record
);
update_oneshot(
&os_cmd_state, KC_LCMD, OS_CMD,
keycode, record
);
return true;
}
layer_state_t layer_state_set_user(layer_state_t state) {
return update_tri_layer_state(state, SYM, NAV, NUM);
}
| kmtoki/qmk_firmware | users/callum/callum.c | C | gpl-2.0 | 3,717 |
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
/*
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/sort.h>
#include <linux/fs.h>
#include <linux/bio.h>
#include <linux/gfs2_ondisk.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/quota.h>
#include <linux/dqblk_xfs.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "glock.h"
#include "glops.h"
#include "log.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "super.h"
#include "trans.h"
#include "inode.h"
#include "util.h"
#define QUOTA_USER 1
#define QUOTA_GROUP 0
struct gfs2_quota_change_host {
u64 qc_change;
u32 qc_flags; /* */
u32 qc_id;
};
static LIST_HEAD(qd_lru_list);
static atomic_t qd_lru_count = ATOMIC_INIT(0);
static DEFINE_SPINLOCK(qd_lru_lock);
int gfs2_shrink_qd_memory(struct shrinker *shrink, struct shrink_control *sc)
{
struct gfs2_quota_data *qd;
struct gfs2_sbd *sdp;
int nr_to_scan = sc->nr_to_scan;
if (nr_to_scan == 0)
goto out;
if (!(sc->gfp_mask & __GFP_FS))
return -1;
spin_lock(&qd_lru_lock);
while (nr_to_scan && !list_empty(&qd_lru_list)) {
qd = list_entry(qd_lru_list.next,
struct gfs2_quota_data, qd_reclaim);
sdp = qd->qd_gl->gl_sbd;
/* */
list_del(&qd->qd_list);
gfs2_assert_warn(sdp, !qd->qd_change);
gfs2_assert_warn(sdp, !qd->qd_slot_count);
gfs2_assert_warn(sdp, !qd->qd_bh_count);
gfs2_glock_put(qd->qd_gl);
atomic_dec(&sdp->sd_quota_count);
/* */
list_del_init(&qd->qd_reclaim);
atomic_dec(&qd_lru_count);
spin_unlock(&qd_lru_lock);
kmem_cache_free(gfs2_quotad_cachep, qd);
spin_lock(&qd_lru_lock);
nr_to_scan--;
}
spin_unlock(&qd_lru_lock);
out:
return (atomic_read(&qd_lru_count) * sysctl_vfs_cache_pressure) / 100;
}
static u64 qd2offset(struct gfs2_quota_data *qd)
{
u64 offset;
offset = 2 * (u64)qd->qd_id + !test_bit(QDF_USER, &qd->qd_flags);
offset *= sizeof(struct gfs2_quota);
return offset;
}
static int qd_alloc(struct gfs2_sbd *sdp, int user, u32 id,
struct gfs2_quota_data **qdp)
{
struct gfs2_quota_data *qd;
int error;
qd = kmem_cache_zalloc(gfs2_quotad_cachep, GFP_NOFS);
if (!qd)
return -ENOMEM;
atomic_set(&qd->qd_count, 1);
qd->qd_id = id;
if (user)
set_bit(QDF_USER, &qd->qd_flags);
qd->qd_slot = -1;
INIT_LIST_HEAD(&qd->qd_reclaim);
error = gfs2_glock_get(sdp, 2 * (u64)id + !user,
&gfs2_quota_glops, CREATE, &qd->qd_gl);
if (error)
goto fail;
*qdp = qd;
return 0;
fail:
kmem_cache_free(gfs2_quotad_cachep, qd);
return error;
}
static int qd_get(struct gfs2_sbd *sdp, int user, u32 id,
struct gfs2_quota_data **qdp)
{
struct gfs2_quota_data *qd = NULL, *new_qd = NULL;
int error, found;
*qdp = NULL;
for (;;) {
found = 0;
spin_lock(&qd_lru_lock);
list_for_each_entry(qd, &sdp->sd_quota_list, qd_list) {
if (qd->qd_id == id &&
!test_bit(QDF_USER, &qd->qd_flags) == !user) {
if (!atomic_read(&qd->qd_count) &&
!list_empty(&qd->qd_reclaim)) {
/* */
list_del_init(&qd->qd_reclaim);
atomic_dec(&qd_lru_count);
}
atomic_inc(&qd->qd_count);
found = 1;
break;
}
}
if (!found)
qd = NULL;
if (!qd && new_qd) {
qd = new_qd;
list_add(&qd->qd_list, &sdp->sd_quota_list);
atomic_inc(&sdp->sd_quota_count);
new_qd = NULL;
}
spin_unlock(&qd_lru_lock);
if (qd) {
if (new_qd) {
gfs2_glock_put(new_qd->qd_gl);
kmem_cache_free(gfs2_quotad_cachep, new_qd);
}
*qdp = qd;
return 0;
}
error = qd_alloc(sdp, user, id, &new_qd);
if (error)
return error;
}
}
static void qd_hold(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_gl->gl_sbd;
gfs2_assert(sdp, atomic_read(&qd->qd_count));
atomic_inc(&qd->qd_count);
}
static void qd_put(struct gfs2_quota_data *qd)
{
if (atomic_dec_and_lock(&qd->qd_count, &qd_lru_lock)) {
/* */
list_add_tail(&qd->qd_reclaim, &qd_lru_list);
atomic_inc(&qd_lru_count);
spin_unlock(&qd_lru_lock);
}
}
static int slot_get(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_gl->gl_sbd;
unsigned int c, o = 0, b;
unsigned char byte = 0;
spin_lock(&qd_lru_lock);
if (qd->qd_slot_count++) {
spin_unlock(&qd_lru_lock);
return 0;
}
for (c = 0; c < sdp->sd_quota_chunks; c++)
for (o = 0; o < PAGE_SIZE; o++) {
byte = sdp->sd_quota_bitmap[c][o];
if (byte != 0xFF)
goto found;
}
goto fail;
found:
for (b = 0; b < 8; b++)
if (!(byte & (1 << b)))
break;
qd->qd_slot = c * (8 * PAGE_SIZE) + o * 8 + b;
if (qd->qd_slot >= sdp->sd_quota_slots)
goto fail;
sdp->sd_quota_bitmap[c][o] |= 1 << b;
spin_unlock(&qd_lru_lock);
return 0;
fail:
qd->qd_slot_count--;
spin_unlock(&qd_lru_lock);
return -ENOSPC;
}
static void slot_hold(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_gl->gl_sbd;
spin_lock(&qd_lru_lock);
gfs2_assert(sdp, qd->qd_slot_count);
qd->qd_slot_count++;
spin_unlock(&qd_lru_lock);
}
static void slot_put(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_gl->gl_sbd;
spin_lock(&qd_lru_lock);
gfs2_assert(sdp, qd->qd_slot_count);
if (!--qd->qd_slot_count) {
gfs2_icbit_munge(sdp, sdp->sd_quota_bitmap, qd->qd_slot, 0);
qd->qd_slot = -1;
}
spin_unlock(&qd_lru_lock);
}
static int bh_get(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_gl->gl_sbd;
struct gfs2_inode *ip = GFS2_I(sdp->sd_qc_inode);
unsigned int block, offset;
struct buffer_head *bh;
int error;
struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 };
mutex_lock(&sdp->sd_quota_mutex);
if (qd->qd_bh_count++) {
mutex_unlock(&sdp->sd_quota_mutex);
return 0;
}
block = qd->qd_slot / sdp->sd_qc_per_block;
offset = qd->qd_slot % sdp->sd_qc_per_block;
bh_map.b_size = 1 << ip->i_inode.i_blkbits;
error = gfs2_block_map(&ip->i_inode, block, &bh_map, 0);
if (error)
goto fail;
error = gfs2_meta_read(ip->i_gl, bh_map.b_blocknr, DIO_WAIT, &bh);
if (error)
goto fail;
error = -EIO;
if (gfs2_metatype_check(sdp, bh, GFS2_METATYPE_QC))
goto fail_brelse;
qd->qd_bh = bh;
qd->qd_bh_qc = (struct gfs2_quota_change *)
(bh->b_data + sizeof(struct gfs2_meta_header) +
offset * sizeof(struct gfs2_quota_change));
mutex_unlock(&sdp->sd_quota_mutex);
return 0;
fail_brelse:
brelse(bh);
fail:
qd->qd_bh_count--;
mutex_unlock(&sdp->sd_quota_mutex);
return error;
}
static void bh_put(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_gl->gl_sbd;
mutex_lock(&sdp->sd_quota_mutex);
gfs2_assert(sdp, qd->qd_bh_count);
if (!--qd->qd_bh_count) {
brelse(qd->qd_bh);
qd->qd_bh = NULL;
qd->qd_bh_qc = NULL;
}
mutex_unlock(&sdp->sd_quota_mutex);
}
static int qd_fish(struct gfs2_sbd *sdp, struct gfs2_quota_data **qdp)
{
struct gfs2_quota_data *qd = NULL;
int error;
int found = 0;
*qdp = NULL;
if (sdp->sd_vfs->s_flags & MS_RDONLY)
return 0;
spin_lock(&qd_lru_lock);
list_for_each_entry(qd, &sdp->sd_quota_list, qd_list) {
if (test_bit(QDF_LOCKED, &qd->qd_flags) ||
!test_bit(QDF_CHANGE, &qd->qd_flags) ||
qd->qd_sync_gen >= sdp->sd_quota_sync_gen)
continue;
list_move_tail(&qd->qd_list, &sdp->sd_quota_list);
set_bit(QDF_LOCKED, &qd->qd_flags);
gfs2_assert_warn(sdp, atomic_read(&qd->qd_count));
atomic_inc(&qd->qd_count);
qd->qd_change_sync = qd->qd_change;
gfs2_assert_warn(sdp, qd->qd_slot_count);
qd->qd_slot_count++;
found = 1;
break;
}
if (!found)
qd = NULL;
spin_unlock(&qd_lru_lock);
if (qd) {
gfs2_assert_warn(sdp, qd->qd_change_sync);
error = bh_get(qd);
if (error) {
clear_bit(QDF_LOCKED, &qd->qd_flags);
slot_put(qd);
qd_put(qd);
return error;
}
}
*qdp = qd;
return 0;
}
static int qd_trylock(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_gl->gl_sbd;
if (sdp->sd_vfs->s_flags & MS_RDONLY)
return 0;
spin_lock(&qd_lru_lock);
if (test_bit(QDF_LOCKED, &qd->qd_flags) ||
!test_bit(QDF_CHANGE, &qd->qd_flags)) {
spin_unlock(&qd_lru_lock);
return 0;
}
list_move_tail(&qd->qd_list, &sdp->sd_quota_list);
set_bit(QDF_LOCKED, &qd->qd_flags);
gfs2_assert_warn(sdp, atomic_read(&qd->qd_count));
atomic_inc(&qd->qd_count);
qd->qd_change_sync = qd->qd_change;
gfs2_assert_warn(sdp, qd->qd_slot_count);
qd->qd_slot_count++;
spin_unlock(&qd_lru_lock);
gfs2_assert_warn(sdp, qd->qd_change_sync);
if (bh_get(qd)) {
clear_bit(QDF_LOCKED, &qd->qd_flags);
slot_put(qd);
qd_put(qd);
return 0;
}
return 1;
}
static void qd_unlock(struct gfs2_quota_data *qd)
{
gfs2_assert_warn(qd->qd_gl->gl_sbd,
test_bit(QDF_LOCKED, &qd->qd_flags));
clear_bit(QDF_LOCKED, &qd->qd_flags);
bh_put(qd);
slot_put(qd);
qd_put(qd);
}
static int qdsb_get(struct gfs2_sbd *sdp, int user, u32 id,
struct gfs2_quota_data **qdp)
{
int error;
error = qd_get(sdp, user, id, qdp);
if (error)
return error;
error = slot_get(*qdp);
if (error)
goto fail;
error = bh_get(*qdp);
if (error)
goto fail_slot;
return 0;
fail_slot:
slot_put(*qdp);
fail:
qd_put(*qdp);
return error;
}
static void qdsb_put(struct gfs2_quota_data *qd)
{
bh_put(qd);
slot_put(qd);
qd_put(qd);
}
int gfs2_quota_hold(struct gfs2_inode *ip, u32 uid, u32 gid)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_qadata *qa = ip->i_qadata;
struct gfs2_quota_data **qd = qa->qa_qd;
int error;
if (gfs2_assert_warn(sdp, !qa->qa_qd_num) ||
gfs2_assert_warn(sdp, !test_bit(GIF_QD_LOCKED, &ip->i_flags)))
return -EIO;
if (sdp->sd_args.ar_quota == GFS2_QUOTA_OFF)
return 0;
error = qdsb_get(sdp, QUOTA_USER, ip->i_inode.i_uid, qd);
if (error)
goto out;
qa->qa_qd_num++;
qd++;
error = qdsb_get(sdp, QUOTA_GROUP, ip->i_inode.i_gid, qd);
if (error)
goto out;
qa->qa_qd_num++;
qd++;
if (uid != NO_QUOTA_CHANGE && uid != ip->i_inode.i_uid) {
error = qdsb_get(sdp, QUOTA_USER, uid, qd);
if (error)
goto out;
qa->qa_qd_num++;
qd++;
}
if (gid != NO_QUOTA_CHANGE && gid != ip->i_inode.i_gid) {
error = qdsb_get(sdp, QUOTA_GROUP, gid, qd);
if (error)
goto out;
qa->qa_qd_num++;
qd++;
}
out:
if (error)
gfs2_quota_unhold(ip);
return error;
}
void gfs2_quota_unhold(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_qadata *qa = ip->i_qadata;
unsigned int x;
gfs2_assert_warn(sdp, !test_bit(GIF_QD_LOCKED, &ip->i_flags));
for (x = 0; x < qa->qa_qd_num; x++) {
qdsb_put(qa->qa_qd[x]);
qa->qa_qd[x] = NULL;
}
qa->qa_qd_num = 0;
}
static int sort_qd(const void *a, const void *b)
{
const struct gfs2_quota_data *qd_a = *(const struct gfs2_quota_data **)a;
const struct gfs2_quota_data *qd_b = *(const struct gfs2_quota_data **)b;
if (!test_bit(QDF_USER, &qd_a->qd_flags) !=
!test_bit(QDF_USER, &qd_b->qd_flags)) {
if (test_bit(QDF_USER, &qd_a->qd_flags))
return -1;
else
return 1;
}
if (qd_a->qd_id < qd_b->qd_id)
return -1;
if (qd_a->qd_id > qd_b->qd_id)
return 1;
return 0;
}
static void do_qc(struct gfs2_quota_data *qd, s64 change)
{
struct gfs2_sbd *sdp = qd->qd_gl->gl_sbd;
struct gfs2_inode *ip = GFS2_I(sdp->sd_qc_inode);
struct gfs2_quota_change *qc = qd->qd_bh_qc;
s64 x;
mutex_lock(&sdp->sd_quota_mutex);
gfs2_trans_add_bh(ip->i_gl, qd->qd_bh, 1);
if (!test_bit(QDF_CHANGE, &qd->qd_flags)) {
qc->qc_change = 0;
qc->qc_flags = 0;
if (test_bit(QDF_USER, &qd->qd_flags))
qc->qc_flags = cpu_to_be32(GFS2_QCF_USER);
qc->qc_id = cpu_to_be32(qd->qd_id);
}
x = be64_to_cpu(qc->qc_change) + change;
qc->qc_change = cpu_to_be64(x);
spin_lock(&qd_lru_lock);
qd->qd_change = x;
spin_unlock(&qd_lru_lock);
if (!x) {
gfs2_assert_warn(sdp, test_bit(QDF_CHANGE, &qd->qd_flags));
clear_bit(QDF_CHANGE, &qd->qd_flags);
qc->qc_flags = 0;
qc->qc_id = 0;
slot_put(qd);
qd_put(qd);
} else if (!test_and_set_bit(QDF_CHANGE, &qd->qd_flags)) {
qd_hold(qd);
slot_hold(qd);
}
mutex_unlock(&sdp->sd_quota_mutex);
}
/*
*/
static int gfs2_adjust_quota(struct gfs2_inode *ip, loff_t loc,
s64 change, struct gfs2_quota_data *qd,
struct fs_disk_quota *fdq)
{
struct inode *inode = &ip->i_inode;
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct address_space *mapping = inode->i_mapping;
unsigned long index = loc >> PAGE_CACHE_SHIFT;
unsigned offset = loc & (PAGE_CACHE_SIZE - 1);
unsigned blocksize, iblock, pos;
struct buffer_head *bh;
struct page *page;
void *kaddr, *ptr;
struct gfs2_quota q, *qp;
int err, nbytes;
u64 size;
if (gfs2_is_stuffed(ip)) {
err = gfs2_unstuff_dinode(ip, NULL);
if (err)
return err;
}
memset(&q, 0, sizeof(struct gfs2_quota));
err = gfs2_internal_read(ip, NULL, (char *)&q, &loc, sizeof(q));
if (err < 0)
return err;
err = -EIO;
qp = &q;
qp->qu_value = be64_to_cpu(qp->qu_value);
qp->qu_value += change;
qp->qu_value = cpu_to_be64(qp->qu_value);
qd->qd_qb.qb_value = qp->qu_value;
if (fdq) {
if (fdq->d_fieldmask & FS_DQ_BSOFT) {
qp->qu_warn = cpu_to_be64(fdq->d_blk_softlimit >> sdp->sd_fsb2bb_shift);
qd->qd_qb.qb_warn = qp->qu_warn;
}
if (fdq->d_fieldmask & FS_DQ_BHARD) {
qp->qu_limit = cpu_to_be64(fdq->d_blk_hardlimit >> sdp->sd_fsb2bb_shift);
qd->qd_qb.qb_limit = qp->qu_limit;
}
if (fdq->d_fieldmask & FS_DQ_BCOUNT) {
qp->qu_value = cpu_to_be64(fdq->d_bcount >> sdp->sd_fsb2bb_shift);
qd->qd_qb.qb_value = qp->qu_value;
}
}
/* */
ptr = qp;
nbytes = sizeof(struct gfs2_quota);
get_a_page:
page = find_or_create_page(mapping, index, GFP_NOFS);
if (!page)
return -ENOMEM;
blocksize = inode->i_sb->s_blocksize;
iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
if (!page_has_buffers(page))
create_empty_buffers(page, blocksize, 0);
bh = page_buffers(page);
pos = blocksize;
while (offset >= pos) {
bh = bh->b_this_page;
iblock++;
pos += blocksize;
}
if (!buffer_mapped(bh)) {
gfs2_block_map(inode, iblock, bh, 1);
if (!buffer_mapped(bh))
goto unlock_out;
/* */
if (buffer_new(bh))
zero_user(page, pos - blocksize, bh->b_size);
}
if (PageUptodate(page))
set_buffer_uptodate(bh);
if (!buffer_uptodate(bh)) {
ll_rw_block(READ | REQ_META, 1, &bh);
wait_on_buffer(bh);
if (!buffer_uptodate(bh))
goto unlock_out;
}
gfs2_trans_add_bh(ip->i_gl, bh, 0);
kaddr = kmap_atomic(page);
if (offset + sizeof(struct gfs2_quota) > PAGE_CACHE_SIZE)
nbytes = PAGE_CACHE_SIZE - offset;
memcpy(kaddr + offset, ptr, nbytes);
flush_dcache_page(page);
kunmap_atomic(kaddr);
unlock_page(page);
page_cache_release(page);
/*
*/
if ((offset + sizeof(struct gfs2_quota)) > PAGE_CACHE_SIZE) {
ptr = ptr + nbytes;
nbytes = sizeof(struct gfs2_quota) - nbytes;
offset = 0;
index++;
goto get_a_page;
}
size = loc + sizeof(struct gfs2_quota);
if (size > inode->i_size)
i_size_write(inode, size);
inode->i_mtime = inode->i_atime = CURRENT_TIME;
mark_inode_dirty(inode);
return err;
unlock_out:
unlock_page(page);
page_cache_release(page);
return err;
}
static int do_sync(unsigned int num_qd, struct gfs2_quota_data **qda)
{
struct gfs2_sbd *sdp = (*qda)->qd_gl->gl_sbd;
struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode);
unsigned int data_blocks, ind_blocks;
struct gfs2_holder *ghs, i_gh;
unsigned int qx, x;
struct gfs2_quota_data *qd;
loff_t offset;
unsigned int nalloc = 0, blocks;
int error;
gfs2_write_calc_reserv(ip, sizeof(struct gfs2_quota),
&data_blocks, &ind_blocks);
ghs = kcalloc(num_qd, sizeof(struct gfs2_holder), GFP_NOFS);
if (!ghs)
return -ENOMEM;
sort(qda, num_qd, sizeof(struct gfs2_quota_data *), sort_qd, NULL);
mutex_lock_nested(&ip->i_inode.i_mutex, I_MUTEX_QUOTA);
for (qx = 0; qx < num_qd; qx++) {
error = gfs2_glock_nq_init(qda[qx]->qd_gl, LM_ST_EXCLUSIVE,
GL_NOCACHE, &ghs[qx]);
if (error)
goto out;
}
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &i_gh);
if (error)
goto out;
for (x = 0; x < num_qd; x++) {
offset = qd2offset(qda[x]);
if (gfs2_write_alloc_required(ip, offset,
sizeof(struct gfs2_quota)))
nalloc++;
}
/*
*/
/*
*/
blocks = num_qd * data_blocks + RES_DINODE + num_qd + 3;
error = gfs2_inplace_reserve(ip, 1 +
(nalloc * (data_blocks + ind_blocks)));
if (error)
goto out_alloc;
if (nalloc)
blocks += gfs2_rg_blocks(ip) + nalloc * ind_blocks + RES_STATFS;
error = gfs2_trans_begin(sdp, blocks, 0);
if (error)
goto out_ipres;
for (x = 0; x < num_qd; x++) {
qd = qda[x];
offset = qd2offset(qd);
error = gfs2_adjust_quota(ip, offset, qd->qd_change_sync, qd, NULL);
if (error)
goto out_end_trans;
do_qc(qd, -qd->qd_change_sync);
set_bit(QDF_REFRESH, &qd->qd_flags);
}
error = 0;
out_end_trans:
gfs2_trans_end(sdp);
out_ipres:
gfs2_inplace_release(ip);
out_alloc:
gfs2_glock_dq_uninit(&i_gh);
out:
while (qx--)
gfs2_glock_dq_uninit(&ghs[qx]);
mutex_unlock(&ip->i_inode.i_mutex);
kfree(ghs);
gfs2_log_flush(ip->i_gl->gl_sbd, ip->i_gl);
return error;
}
static int update_qd(struct gfs2_sbd *sdp, struct gfs2_quota_data *qd)
{
struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode);
struct gfs2_quota q;
struct gfs2_quota_lvb *qlvb;
loff_t pos;
int error;
memset(&q, 0, sizeof(struct gfs2_quota));
pos = qd2offset(qd);
error = gfs2_internal_read(ip, NULL, (char *)&q, &pos, sizeof(q));
if (error < 0)
return error;
qlvb = (struct gfs2_quota_lvb *)qd->qd_gl->gl_lvb;
qlvb->qb_magic = cpu_to_be32(GFS2_MAGIC);
qlvb->__pad = 0;
qlvb->qb_limit = q.qu_limit;
qlvb->qb_warn = q.qu_warn;
qlvb->qb_value = q.qu_value;
qd->qd_qb = *qlvb;
return 0;
}
static int do_glock(struct gfs2_quota_data *qd, int force_refresh,
struct gfs2_holder *q_gh)
{
struct gfs2_sbd *sdp = qd->qd_gl->gl_sbd;
struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode);
struct gfs2_holder i_gh;
int error;
restart:
error = gfs2_glock_nq_init(qd->qd_gl, LM_ST_SHARED, 0, q_gh);
if (error)
return error;
qd->qd_qb = *(struct gfs2_quota_lvb *)qd->qd_gl->gl_lvb;
if (force_refresh || qd->qd_qb.qb_magic != cpu_to_be32(GFS2_MAGIC)) {
gfs2_glock_dq_uninit(q_gh);
error = gfs2_glock_nq_init(qd->qd_gl, LM_ST_EXCLUSIVE,
GL_NOCACHE, q_gh);
if (error)
return error;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, 0, &i_gh);
if (error)
goto fail;
error = update_qd(sdp, qd);
if (error)
goto fail_gunlock;
gfs2_glock_dq_uninit(&i_gh);
gfs2_glock_dq_uninit(q_gh);
force_refresh = 0;
goto restart;
}
return 0;
fail_gunlock:
gfs2_glock_dq_uninit(&i_gh);
fail:
gfs2_glock_dq_uninit(q_gh);
return error;
}
int gfs2_quota_lock(struct gfs2_inode *ip, u32 uid, u32 gid)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_qadata *qa = ip->i_qadata;
struct gfs2_quota_data *qd;
unsigned int x;
int error = 0;
error = gfs2_quota_hold(ip, uid, gid);
if (error)
return error;
if (capable(CAP_SYS_RESOURCE) ||
sdp->sd_args.ar_quota != GFS2_QUOTA_ON)
return 0;
sort(qa->qa_qd, qa->qa_qd_num, sizeof(struct gfs2_quota_data *),
sort_qd, NULL);
for (x = 0; x < qa->qa_qd_num; x++) {
int force = NO_FORCE;
qd = qa->qa_qd[x];
if (test_and_clear_bit(QDF_REFRESH, &qd->qd_flags))
force = FORCE;
error = do_glock(qd, force, &qa->qa_qd_ghs[x]);
if (error)
break;
}
if (!error)
set_bit(GIF_QD_LOCKED, &ip->i_flags);
else {
while (x--)
gfs2_glock_dq_uninit(&qa->qa_qd_ghs[x]);
gfs2_quota_unhold(ip);
}
return error;
}
static int need_sync(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_gl->gl_sbd;
struct gfs2_tune *gt = &sdp->sd_tune;
s64 value;
unsigned int num, den;
int do_sync = 1;
if (!qd->qd_qb.qb_limit)
return 0;
spin_lock(&qd_lru_lock);
value = qd->qd_change;
spin_unlock(&qd_lru_lock);
spin_lock(>->gt_spin);
num = gt->gt_quota_scale_num;
den = gt->gt_quota_scale_den;
spin_unlock(>->gt_spin);
if (value < 0)
do_sync = 0;
else if ((s64)be64_to_cpu(qd->qd_qb.qb_value) >=
(s64)be64_to_cpu(qd->qd_qb.qb_limit))
do_sync = 0;
else {
value *= gfs2_jindex_size(sdp) * num;
value = div_s64(value, den);
value += (s64)be64_to_cpu(qd->qd_qb.qb_value);
if (value < (s64)be64_to_cpu(qd->qd_qb.qb_limit))
do_sync = 0;
}
return do_sync;
}
void gfs2_quota_unlock(struct gfs2_inode *ip)
{
struct gfs2_qadata *qa = ip->i_qadata;
struct gfs2_quota_data *qda[4];
unsigned int count = 0;
unsigned int x;
if (!test_and_clear_bit(GIF_QD_LOCKED, &ip->i_flags))
goto out;
for (x = 0; x < qa->qa_qd_num; x++) {
struct gfs2_quota_data *qd;
int sync;
qd = qa->qa_qd[x];
sync = need_sync(qd);
gfs2_glock_dq_uninit(&qa->qa_qd_ghs[x]);
if (sync && qd_trylock(qd))
qda[count++] = qd;
}
if (count) {
do_sync(count, qda);
for (x = 0; x < count; x++)
qd_unlock(qda[x]);
}
out:
gfs2_quota_unhold(ip);
}
#define MAX_LINE 256
static int print_message(struct gfs2_quota_data *qd, char *type)
{
struct gfs2_sbd *sdp = qd->qd_gl->gl_sbd;
printk(KERN_INFO "GFS2: fsid=%s: quota %s for %s %u\n",
sdp->sd_fsname, type,
(test_bit(QDF_USER, &qd->qd_flags)) ? "user" : "group",
qd->qd_id);
return 0;
}
int gfs2_quota_check(struct gfs2_inode *ip, u32 uid, u32 gid)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_qadata *qa = ip->i_qadata;
struct gfs2_quota_data *qd;
s64 value;
unsigned int x;
int error = 0;
if (!test_bit(GIF_QD_LOCKED, &ip->i_flags))
return 0;
if (sdp->sd_args.ar_quota != GFS2_QUOTA_ON)
return 0;
for (x = 0; x < qa->qa_qd_num; x++) {
qd = qa->qa_qd[x];
if (!((qd->qd_id == uid && test_bit(QDF_USER, &qd->qd_flags)) ||
(qd->qd_id == gid && !test_bit(QDF_USER, &qd->qd_flags))))
continue;
value = (s64)be64_to_cpu(qd->qd_qb.qb_value);
spin_lock(&qd_lru_lock);
value += qd->qd_change;
spin_unlock(&qd_lru_lock);
if (be64_to_cpu(qd->qd_qb.qb_limit) && (s64)be64_to_cpu(qd->qd_qb.qb_limit) < value) {
print_message(qd, "exceeded");
quota_send_warning(test_bit(QDF_USER, &qd->qd_flags) ?
USRQUOTA : GRPQUOTA, qd->qd_id,
sdp->sd_vfs->s_dev, QUOTA_NL_BHARDWARN);
error = -EDQUOT;
break;
} else if (be64_to_cpu(qd->qd_qb.qb_warn) &&
(s64)be64_to_cpu(qd->qd_qb.qb_warn) < value &&
time_after_eq(jiffies, qd->qd_last_warn +
gfs2_tune_get(sdp,
gt_quota_warn_period) * HZ)) {
quota_send_warning(test_bit(QDF_USER, &qd->qd_flags) ?
USRQUOTA : GRPQUOTA, qd->qd_id,
sdp->sd_vfs->s_dev, QUOTA_NL_BSOFTWARN);
error = print_message(qd, "warning");
qd->qd_last_warn = jiffies;
}
}
return error;
}
void gfs2_quota_change(struct gfs2_inode *ip, s64 change,
u32 uid, u32 gid)
{
struct gfs2_qadata *qa = ip->i_qadata;
struct gfs2_quota_data *qd;
unsigned int x;
if (gfs2_assert_warn(GFS2_SB(&ip->i_inode), change))
return;
if (ip->i_diskflags & GFS2_DIF_SYSTEM)
return;
for (x = 0; x < qa->qa_qd_num; x++) {
qd = qa->qa_qd[x];
if ((qd->qd_id == uid && test_bit(QDF_USER, &qd->qd_flags)) ||
(qd->qd_id == gid && !test_bit(QDF_USER, &qd->qd_flags))) {
do_qc(qd, change);
}
}
}
int gfs2_quota_sync(struct super_block *sb, int type, int wait)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_quota_data **qda;
unsigned int max_qd = gfs2_tune_get(sdp, gt_quota_simul_sync);
unsigned int num_qd;
unsigned int x;
int error = 0;
sdp->sd_quota_sync_gen++;
qda = kcalloc(max_qd, sizeof(struct gfs2_quota_data *), GFP_KERNEL);
if (!qda)
return -ENOMEM;
do {
num_qd = 0;
for (;;) {
error = qd_fish(sdp, qda + num_qd);
if (error || !qda[num_qd])
break;
if (++num_qd == max_qd)
break;
}
if (num_qd) {
if (!error)
error = do_sync(num_qd, qda);
if (!error)
for (x = 0; x < num_qd; x++)
qda[x]->qd_sync_gen =
sdp->sd_quota_sync_gen;
for (x = 0; x < num_qd; x++)
qd_unlock(qda[x]);
}
} while (!error && num_qd == max_qd);
kfree(qda);
return error;
}
static int gfs2_quota_sync_timeo(struct super_block *sb, int type)
{
return gfs2_quota_sync(sb, type, 0);
}
int gfs2_quota_refresh(struct gfs2_sbd *sdp, int user, u32 id)
{
struct gfs2_quota_data *qd;
struct gfs2_holder q_gh;
int error;
error = qd_get(sdp, user, id, &qd);
if (error)
return error;
error = do_glock(qd, FORCE, &q_gh);
if (!error)
gfs2_glock_dq_uninit(&q_gh);
qd_put(qd);
return error;
}
static void gfs2_quota_change_in(struct gfs2_quota_change_host *qc, const void *buf)
{
const struct gfs2_quota_change *str = buf;
qc->qc_change = be64_to_cpu(str->qc_change);
qc->qc_flags = be32_to_cpu(str->qc_flags);
qc->qc_id = be32_to_cpu(str->qc_id);
}
int gfs2_quota_init(struct gfs2_sbd *sdp)
{
struct gfs2_inode *ip = GFS2_I(sdp->sd_qc_inode);
u64 size = i_size_read(sdp->sd_qc_inode);
unsigned int blocks = size >> sdp->sd_sb.sb_bsize_shift;
unsigned int x, slot = 0;
unsigned int found = 0;
u64 dblock;
u32 extlen = 0;
int error;
if (gfs2_check_internal_file_size(sdp->sd_qc_inode, 1, 64 << 20))
return -EIO;
sdp->sd_quota_slots = blocks * sdp->sd_qc_per_block;
sdp->sd_quota_chunks = DIV_ROUND_UP(sdp->sd_quota_slots, 8 * PAGE_SIZE);
error = -ENOMEM;
sdp->sd_quota_bitmap = kcalloc(sdp->sd_quota_chunks,
sizeof(unsigned char *), GFP_NOFS);
if (!sdp->sd_quota_bitmap)
return error;
for (x = 0; x < sdp->sd_quota_chunks; x++) {
sdp->sd_quota_bitmap[x] = kzalloc(PAGE_SIZE, GFP_NOFS);
if (!sdp->sd_quota_bitmap[x])
goto fail;
}
for (x = 0; x < blocks; x++) {
struct buffer_head *bh;
unsigned int y;
if (!extlen) {
int new = 0;
error = gfs2_extent_map(&ip->i_inode, x, &new, &dblock, &extlen);
if (error)
goto fail;
}
error = -EIO;
bh = gfs2_meta_ra(ip->i_gl, dblock, extlen);
if (!bh)
goto fail;
if (gfs2_metatype_check(sdp, bh, GFS2_METATYPE_QC)) {
brelse(bh);
goto fail;
}
for (y = 0; y < sdp->sd_qc_per_block && slot < sdp->sd_quota_slots;
y++, slot++) {
struct gfs2_quota_change_host qc;
struct gfs2_quota_data *qd;
gfs2_quota_change_in(&qc, bh->b_data +
sizeof(struct gfs2_meta_header) +
y * sizeof(struct gfs2_quota_change));
if (!qc.qc_change)
continue;
error = qd_alloc(sdp, (qc.qc_flags & GFS2_QCF_USER),
qc.qc_id, &qd);
if (error) {
brelse(bh);
goto fail;
}
set_bit(QDF_CHANGE, &qd->qd_flags);
qd->qd_change = qc.qc_change;
qd->qd_slot = slot;
qd->qd_slot_count = 1;
spin_lock(&qd_lru_lock);
gfs2_icbit_munge(sdp, sdp->sd_quota_bitmap, slot, 1);
list_add(&qd->qd_list, &sdp->sd_quota_list);
atomic_inc(&sdp->sd_quota_count);
spin_unlock(&qd_lru_lock);
found++;
}
brelse(bh);
dblock++;
extlen--;
}
if (found)
fs_info(sdp, "found %u quota changes\n", found);
return 0;
fail:
gfs2_quota_cleanup(sdp);
return error;
}
void gfs2_quota_cleanup(struct gfs2_sbd *sdp)
{
struct list_head *head = &sdp->sd_quota_list;
struct gfs2_quota_data *qd;
unsigned int x;
spin_lock(&qd_lru_lock);
while (!list_empty(head)) {
qd = list_entry(head->prev, struct gfs2_quota_data, qd_list);
if (atomic_read(&qd->qd_count) > 1 ||
(atomic_read(&qd->qd_count) &&
!test_bit(QDF_CHANGE, &qd->qd_flags))) {
list_move(&qd->qd_list, head);
spin_unlock(&qd_lru_lock);
schedule();
spin_lock(&qd_lru_lock);
continue;
}
list_del(&qd->qd_list);
/* */
if (!list_empty(&qd->qd_reclaim)) {
list_del_init(&qd->qd_reclaim);
atomic_dec(&qd_lru_count);
}
atomic_dec(&sdp->sd_quota_count);
spin_unlock(&qd_lru_lock);
if (!atomic_read(&qd->qd_count)) {
gfs2_assert_warn(sdp, !qd->qd_change);
gfs2_assert_warn(sdp, !qd->qd_slot_count);
} else
gfs2_assert_warn(sdp, qd->qd_slot_count == 1);
gfs2_assert_warn(sdp, !qd->qd_bh_count);
gfs2_glock_put(qd->qd_gl);
kmem_cache_free(gfs2_quotad_cachep, qd);
spin_lock(&qd_lru_lock);
}
spin_unlock(&qd_lru_lock);
gfs2_assert_warn(sdp, !atomic_read(&sdp->sd_quota_count));
if (sdp->sd_quota_bitmap) {
for (x = 0; x < sdp->sd_quota_chunks; x++)
kfree(sdp->sd_quota_bitmap[x]);
kfree(sdp->sd_quota_bitmap);
}
}
static void quotad_error(struct gfs2_sbd *sdp, const char *msg, int error)
{
if (error == 0 || error == -EROFS)
return;
if (!test_bit(SDF_SHUTDOWN, &sdp->sd_flags))
fs_err(sdp, "gfs2_quotad: %s error %d\n", msg, error);
}
static void quotad_check_timeo(struct gfs2_sbd *sdp, const char *msg,
int (*fxn)(struct super_block *sb, int type),
unsigned long t, unsigned long *timeo,
unsigned int *new_timeo)
{
if (t >= *timeo) {
int error = fxn(sdp->sd_vfs, 0);
quotad_error(sdp, msg, error);
*timeo = gfs2_tune_get_i(&sdp->sd_tune, new_timeo) * HZ;
} else {
*timeo -= t;
}
}
static void quotad_check_trunc_list(struct gfs2_sbd *sdp)
{
struct gfs2_inode *ip;
while(1) {
ip = NULL;
spin_lock(&sdp->sd_trunc_lock);
if (!list_empty(&sdp->sd_trunc_list)) {
ip = list_entry(sdp->sd_trunc_list.next,
struct gfs2_inode, i_trunc_list);
list_del_init(&ip->i_trunc_list);
}
spin_unlock(&sdp->sd_trunc_lock);
if (ip == NULL)
return;
gfs2_glock_finish_truncate(ip);
}
}
void gfs2_wake_up_statfs(struct gfs2_sbd *sdp) {
if (!sdp->sd_statfs_force_sync) {
sdp->sd_statfs_force_sync = 1;
wake_up(&sdp->sd_quota_wait);
}
}
/*
*/
int gfs2_quotad(void *data)
{
struct gfs2_sbd *sdp = data;
struct gfs2_tune *tune = &sdp->sd_tune;
unsigned long statfs_timeo = 0;
unsigned long quotad_timeo = 0;
unsigned long t = 0;
DEFINE_WAIT(wait);
int empty;
while (!kthread_should_stop()) {
/* */
if (sdp->sd_statfs_force_sync) {
int error = gfs2_statfs_sync(sdp->sd_vfs, 0);
quotad_error(sdp, "statfs", error);
statfs_timeo = gfs2_tune_get(sdp, gt_statfs_quantum) * HZ;
}
else
quotad_check_timeo(sdp, "statfs", gfs2_statfs_sync, t,
&statfs_timeo,
&tune->gt_statfs_quantum);
/* */
quotad_check_timeo(sdp, "sync", gfs2_quota_sync_timeo, t,
"ad_timeo, &tune->gt_quota_quantum);
/* */
quotad_check_trunc_list(sdp);
try_to_freeze();
t = min(quotad_timeo, statfs_timeo);
prepare_to_wait(&sdp->sd_quota_wait, &wait, TASK_INTERRUPTIBLE);
spin_lock(&sdp->sd_trunc_lock);
empty = list_empty(&sdp->sd_trunc_list);
spin_unlock(&sdp->sd_trunc_lock);
if (empty && !sdp->sd_statfs_force_sync)
t -= schedule_timeout(t);
else
t = 0;
finish_wait(&sdp->sd_quota_wait, &wait);
}
return 0;
}
static int gfs2_quota_get_xstate(struct super_block *sb,
struct fs_quota_stat *fqs)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
memset(fqs, 0, sizeof(struct fs_quota_stat));
fqs->qs_version = FS_QSTAT_VERSION;
switch (sdp->sd_args.ar_quota) {
case GFS2_QUOTA_ON:
fqs->qs_flags |= (FS_QUOTA_UDQ_ENFD | FS_QUOTA_GDQ_ENFD);
/* */
case GFS2_QUOTA_ACCOUNT:
fqs->qs_flags |= (FS_QUOTA_UDQ_ACCT | FS_QUOTA_GDQ_ACCT);
break;
case GFS2_QUOTA_OFF:
break;
}
if (sdp->sd_quota_inode) {
fqs->qs_uquota.qfs_ino = GFS2_I(sdp->sd_quota_inode)->i_no_addr;
fqs->qs_uquota.qfs_nblks = sdp->sd_quota_inode->i_blocks;
}
fqs->qs_uquota.qfs_nextents = 1; /* */
fqs->qs_gquota = fqs->qs_uquota; /* */
fqs->qs_incoredqs = atomic_read(&qd_lru_count);
return 0;
}
static int gfs2_get_dqblk(struct super_block *sb, int type, qid_t id,
struct fs_disk_quota *fdq)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_quota_lvb *qlvb;
struct gfs2_quota_data *qd;
struct gfs2_holder q_gh;
int error;
memset(fdq, 0, sizeof(struct fs_disk_quota));
if (sdp->sd_args.ar_quota == GFS2_QUOTA_OFF)
return -ESRCH; /* */
if (type == USRQUOTA)
type = QUOTA_USER;
else if (type == GRPQUOTA)
type = QUOTA_GROUP;
else
return -EINVAL;
error = qd_get(sdp, type, id, &qd);
if (error)
return error;
error = do_glock(qd, FORCE, &q_gh);
if (error)
goto out;
qlvb = (struct gfs2_quota_lvb *)qd->qd_gl->gl_lvb;
fdq->d_version = FS_DQUOT_VERSION;
fdq->d_flags = (type == QUOTA_USER) ? FS_USER_QUOTA : FS_GROUP_QUOTA;
fdq->d_id = id;
fdq->d_blk_hardlimit = be64_to_cpu(qlvb->qb_limit) << sdp->sd_fsb2bb_shift;
fdq->d_blk_softlimit = be64_to_cpu(qlvb->qb_warn) << sdp->sd_fsb2bb_shift;
fdq->d_bcount = be64_to_cpu(qlvb->qb_value) << sdp->sd_fsb2bb_shift;
gfs2_glock_dq_uninit(&q_gh);
out:
qd_put(qd);
return error;
}
/* */
#define GFS2_FIELDMASK (FS_DQ_BSOFT|FS_DQ_BHARD|FS_DQ_BCOUNT)
static int gfs2_set_dqblk(struct super_block *sb, int type, qid_t id,
struct fs_disk_quota *fdq)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode);
struct gfs2_quota_data *qd;
struct gfs2_holder q_gh, i_gh;
unsigned int data_blocks, ind_blocks;
unsigned int blocks = 0;
int alloc_required;
loff_t offset;
int error;
if (sdp->sd_args.ar_quota == GFS2_QUOTA_OFF)
return -ESRCH; /* */
switch(type) {
case USRQUOTA:
type = QUOTA_USER;
if (fdq->d_flags != FS_USER_QUOTA)
return -EINVAL;
break;
case GRPQUOTA:
type = QUOTA_GROUP;
if (fdq->d_flags != FS_GROUP_QUOTA)
return -EINVAL;
break;
default:
return -EINVAL;
}
if (fdq->d_fieldmask & ~GFS2_FIELDMASK)
return -EINVAL;
if (fdq->d_id != id)
return -EINVAL;
error = qd_get(sdp, type, id, &qd);
if (error)
return error;
mutex_lock(&ip->i_inode.i_mutex);
error = gfs2_glock_nq_init(qd->qd_gl, LM_ST_EXCLUSIVE, 0, &q_gh);
if (error)
goto out_put;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &i_gh);
if (error)
goto out_q;
/* */
error = update_qd(sdp, qd);
if (error)
goto out_i;
/* */
if ((fdq->d_fieldmask & FS_DQ_BSOFT) &&
((fdq->d_blk_softlimit >> sdp->sd_fsb2bb_shift) == be64_to_cpu(qd->qd_qb.qb_warn)))
fdq->d_fieldmask ^= FS_DQ_BSOFT;
if ((fdq->d_fieldmask & FS_DQ_BHARD) &&
((fdq->d_blk_hardlimit >> sdp->sd_fsb2bb_shift) == be64_to_cpu(qd->qd_qb.qb_limit)))
fdq->d_fieldmask ^= FS_DQ_BHARD;
if ((fdq->d_fieldmask & FS_DQ_BCOUNT) &&
((fdq->d_bcount >> sdp->sd_fsb2bb_shift) == be64_to_cpu(qd->qd_qb.qb_value)))
fdq->d_fieldmask ^= FS_DQ_BCOUNT;
if (fdq->d_fieldmask == 0)
goto out_i;
offset = qd2offset(qd);
alloc_required = gfs2_write_alloc_required(ip, offset, sizeof(struct gfs2_quota));
if (gfs2_is_stuffed(ip))
alloc_required = 1;
if (alloc_required) {
gfs2_write_calc_reserv(ip, sizeof(struct gfs2_quota),
&data_blocks, &ind_blocks);
blocks = 1 + data_blocks + ind_blocks;
error = gfs2_inplace_reserve(ip, blocks);
if (error)
goto out_i;
blocks += gfs2_rg_blocks(ip);
}
/*
*/
error = gfs2_trans_begin(sdp, blocks + RES_DINODE + 2, 0);
if (error)
goto out_release;
/* */
error = gfs2_adjust_quota(ip, offset, 0, qd, fdq);
gfs2_trans_end(sdp);
out_release:
if (alloc_required)
gfs2_inplace_release(ip);
out_i:
gfs2_glock_dq_uninit(&i_gh);
out_q:
gfs2_glock_dq_uninit(&q_gh);
out_put:
mutex_unlock(&ip->i_inode.i_mutex);
qd_put(qd);
return error;
}
const struct quotactl_ops gfs2_quotactl_ops = {
.quota_sync = gfs2_quota_sync,
.get_xstate = gfs2_quota_get_xstate,
.get_dqblk = gfs2_get_dqblk,
.set_dqblk = gfs2_set_dqblk,
};
| holyangel/LGE_G3 | fs/gfs2/quota.c | C | gpl-2.0 | 38,914 |
#ifndef _LINUX_SOUND_H
#define _LINUX_SOUND_H
/*
*/
#include <linux/fs.h>
#define SND_DEV_CTL 0 /* */
#define SND_DEV_SEQ 1 /*
*/
#define SND_DEV_MIDIN 2 /* */
#define SND_DEV_DSP 3 /* */
#define SND_DEV_AUDIO 4 /* */
#define SND_DEV_DSP16 5 /* */
/* */ /* */
#define SND_DEV_UNUSED 6
#define SND_DEV_AWFM 7 /* */
#define SND_DEV_SEQ2 8 /* */
/* */ /* */
/* */
#define SND_DEV_SYNTH 9 /* */
#define SND_DEV_DMFM 10 /* */
#define SND_DEV_UNKNOWN11 11
#define SND_DEV_ADSP 12 /* */
#define SND_DEV_AMIDI 13 /* */
#define SND_DEV_ADMMIDI 14 /* */
#ifdef __KERNEL__
/*
*/
struct device;
extern int register_sound_special(const struct file_operations *fops, int unit);
extern int register_sound_special_device(const struct file_operations *fops, int unit, struct device *dev);
extern int register_sound_mixer(const struct file_operations *fops, int dev);
extern int register_sound_midi(const struct file_operations *fops, int dev);
extern int register_sound_dsp(const struct file_operations *fops, int dev);
extern void unregister_sound_special(int unit);
extern void unregister_sound_mixer(int unit);
extern void unregister_sound_midi(int unit);
extern void unregister_sound_dsp(int unit);
#endif /* */
#endif /* */
| holyangel/LGE_G3 | include/linux/sound.h | C | gpl-2.0 | 1,878 |
/*
* Copyright (c) 2006 Chelsio, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 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.
*/
#ifndef __IWCH_H__
#define __IWCH_H__
#include <linux/mutex.h>
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/idr.h>
#include <linux/workqueue.h>
#include <rdma/ib_verbs.h>
#include "cxio_hal.h"
#include "cxgb3_offload.h"
struct iwch_pd;
struct iwch_cq;
struct iwch_qp;
struct iwch_mr;
struct iwch_rnic_attributes {
u32 max_qps;
u32 max_wrs; /* */
u32 max_sge_per_wr;
u32 max_sge_per_rdma_write_wr; /* */
u32 max_cqs;
u32 max_cqes_per_cq;
u32 max_mem_regs;
u32 max_phys_buf_entries; /* */
u32 max_pds;
/*
*/
u32 mem_pgsizes_bitmask;
u64 max_mr_size;
u8 can_resize_wq;
/*
*/
u32 max_rdma_reads_per_qp;
/*
*/
u32 max_rdma_read_resources;
/*
*/
u32 max_rdma_read_qp_depth;
/*
*/
u32 max_rdma_read_depth;
u8 rq_overflow_handled;
u32 can_modify_ird;
u32 can_modify_ord;
u32 max_mem_windows;
u32 stag0_value;
u8 zbva_support;
u8 local_invalidate_fence;
u32 cq_overflow_detection;
};
struct iwch_dev {
struct ib_device ibdev;
struct cxio_rdev rdev;
u32 device_cap_flags;
struct iwch_rnic_attributes attr;
struct idr cqidr;
struct idr qpidr;
struct idr mmidr;
spinlock_t lock;
struct list_head entry;
struct delayed_work db_drop_task;
};
static inline struct iwch_dev *to_iwch_dev(struct ib_device *ibdev)
{
return container_of(ibdev, struct iwch_dev, ibdev);
}
static inline struct iwch_dev *rdev_to_iwch_dev(struct cxio_rdev *rdev)
{
return container_of(rdev, struct iwch_dev, rdev);
}
static inline int t3b_device(const struct iwch_dev *rhp)
{
return rhp->rdev.t3cdev_p->type == T3B;
}
static inline int t3a_device(const struct iwch_dev *rhp)
{
return rhp->rdev.t3cdev_p->type == T3A;
}
static inline struct iwch_cq *get_chp(struct iwch_dev *rhp, u32 cqid)
{
return idr_find(&rhp->cqidr, cqid);
}
static inline struct iwch_qp *get_qhp(struct iwch_dev *rhp, u32 qpid)
{
return idr_find(&rhp->qpidr, qpid);
}
static inline struct iwch_mr *get_mhp(struct iwch_dev *rhp, u32 mmid)
{
return idr_find(&rhp->mmidr, mmid);
}
static inline int insert_handle(struct iwch_dev *rhp, struct idr *idr,
void *handle, u32 id)
{
int ret;
int newid;
do {
if (!idr_pre_get(idr, GFP_KERNEL)) {
return -ENOMEM;
}
spin_lock_irq(&rhp->lock);
ret = idr_get_new_above(idr, handle, id, &newid);
BUG_ON(newid != id);
spin_unlock_irq(&rhp->lock);
} while (ret == -EAGAIN);
return ret;
}
static inline void remove_handle(struct iwch_dev *rhp, struct idr *idr, u32 id)
{
spin_lock_irq(&rhp->lock);
idr_remove(idr, id);
spin_unlock_irq(&rhp->lock);
}
extern struct cxgb3_client t3c_client;
extern cxgb3_cpl_handler_func t3c_handlers[NUM_CPL_CMDS];
extern void iwch_ev_dispatch(struct cxio_rdev *rdev_p, struct sk_buff *skb);
#endif
| sleekmason/LG-V510-Kitkat | drivers/infiniband/hw/cxgb3/iwch.h | C | gpl-2.0 | 4,720 |
// 2000-12-19 bkoz
// Copyright (C) 2000-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 27.4.2.5 ios_base storage functions
#include <sstream>
#include <iostream>
#include <testsuite_hooks.h>
// http://gcc.gnu.org/ml/gcc-bugs/2000-12/msg00413.html
void test01()
{
using namespace std;
ios::xalloc();
ios::xalloc();
ios::xalloc();
long x4 = ios::xalloc();
ostringstream out("the element of crime, lars von trier");
out.pword(++x4); // should not crash
}
int main(void)
{
__gnu_test::set_memory_limits();
test01();
return 0;
}
| krichter722/gcc | libstdc++-v3/testsuite/27_io/ios_base/storage/1.cc | C++ | gpl-2.0 | 1,250 |
/*
* Gadget Driver for Android
*
* Copyright (C) 2008 Google, Inc.
*.Copyright (c) 2014, The Linux Foundation. All rights reserved.
* Author: Mike Lockwood <[email protected]>
* Benoit Goby <[email protected]>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/utsname.h>
#include <linux/platform_device.h>
#include <linux/pm_qos.h>
#include <linux/of.h>
#include <linux/usb/ch9.h>
#include <linux/usb/composite.h>
#include <linux/usb/gadget.h>
#include <linux/usb/android.h>
#include <linux/qcom/diag_dload.h>
#include "gadget_chips.h"
#include "f_fs.c"
#ifdef CONFIG_SND_PCM
#include "f_audio_source.c"
#endif
#include "f_mass_storage.c"
#define USB_ETH_RNDIS y
#include "f_diag.c"
#include "f_qdss.c"
#include "f_rmnet_smd.c"
#include "f_rmnet.c"
#include "f_gps.c"
#include "u_smd.c"
#include "u_bam.c"
#include "u_rmnet_ctrl_smd.c"
#include "u_rmnet_ctrl_qti.c"
#include "u_ctrl_hsic.c"
#include "u_data_hsic.c"
#include "u_ctrl_hsuart.c"
#include "u_data_hsuart.c"
#include "f_ccid.c"
#include "f_mtp.c"
#include "f_accessory.c"
#include "f_rndis.c"
#include "rndis.c"
#include "f_qc_ecm.c"
#include "f_mbim.c"
#include "f_qc_rndis.c"
#include "u_bam_data.c"
#include "f_ecm.c"
#include "u_ether.c"
#include "u_qc_ether.c"
#ifdef CONFIG_TARGET_CORE
#endif
#ifdef CONFIG_SND_PCM
#include "u_uac1.c"
#include "f_uac1.c"
#endif
#include "f_ncm.c"
#include "f_charger.c"
MODULE_AUTHOR("Mike Lockwood");
MODULE_DESCRIPTION("Android Composite USB Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION("1.0");
static const char longname[] = "Gadget Android";
/* Default vendor and product IDs, overridden by userspace */
#define VENDOR_ID 0x18D1
#define PRODUCT_ID 0x0001
#define ANDROID_DEVICE_NODE_NAME_LENGTH 11
struct android_usb_function {
char *name;
void *config;
struct device *dev;
char *dev_name;
struct device_attribute **attributes;
struct android_dev *android_dev;
/* Optional: initialization during gadget bind */
int (*init)(struct android_usb_function *, struct usb_composite_dev *);
/* Optional: cleanup during gadget unbind */
void (*cleanup)(struct android_usb_function *);
/* Optional: called when the function is added the list of
* enabled functions */
void (*enable)(struct android_usb_function *);
/* Optional: called when it is removed */
void (*disable)(struct android_usb_function *);
int (*bind_config)(struct android_usb_function *,
struct usb_configuration *);
/* Optional: called when the configuration is removed */
void (*unbind_config)(struct android_usb_function *,
struct usb_configuration *);
/* Optional: handle ctrl requests before the device is configured */
int (*ctrlrequest)(struct android_usb_function *,
struct usb_composite_dev *,
const struct usb_ctrlrequest *);
};
struct android_usb_function_holder {
struct android_usb_function *f;
/* for android_conf.enabled_functions */
struct list_head enabled_list;
};
/**
* struct android_dev - represents android USB gadget device
* @name: device name.
* @functions: an array of all the supported USB function
* drivers that this gadget support but not necessarily
* added to one of the gadget configurations.
* @cdev: The internal composite device. Android gadget device
* is a composite device, such that it can support configurations
* with more than one function driver.
* @dev: The kernel device that represents this android device.
* @enabled: True if the android gadget is enabled, means all
* the configurations were set and all function drivers were
* bind and ready for USB enumeration.
* @disable_depth: Number of times the device was disabled, after
* symmetrical number of enables the device willl be enabled.
* Used for controlling ADB userspace disable/enable requests.
* @mutex: Internal mutex for protecting device member fields.
* @pdata: Platform data fetched from the kernel device platfrom data.
* @connected: True if got connect notification from the gadget UDC.
* False if got disconnect notification from the gadget UDC.
* @sw_connected: Equal to 'connected' only after the connect
* notification was handled by the android gadget work function.
* @suspended: True if got suspend notification from the gadget UDC.
* False if got resume notification from the gadget UDC.
* @sw_suspended: Equal to 'suspended' only after the susped
* notification was handled by the android gadget work function.
* @pm_qos: An attribute string that can be set by user space in order to
* determine pm_qos policy. Set to 'high' for always demand pm_qos
* when USB bus is connected and resumed. Set to 'low' for disable
* any setting of pm_qos by this driver. Default = 'high'.
* @work: workqueue used for handling notifications from the gadget UDC.
* @configs: List of configurations currently configured into the device.
* The android gadget supports more than one configuration. The host
* may choose one configuration from the suggested.
* @configs_num: Number of configurations currently configured and existing
* in the configs list.
* @list_item: This driver supports more than one android gadget device (for
* example in order to support multiple USB cores), therefore this is
* a item in a linked list of android devices.
*/
struct android_dev {
const char *name;
struct android_usb_function **functions;
struct usb_composite_dev *cdev;
struct device *dev;
void (*setup_complete)(struct usb_ep *ep,
struct usb_request *req);
bool enabled;
int disable_depth;
struct mutex mutex;
struct android_usb_platform_data *pdata;
bool connected;
bool sw_connected;
bool suspended;
bool sw_suspended;
char pm_qos[5];
struct pm_qos_request pm_qos_req_dma;
unsigned up_pm_qos_sample_sec;
unsigned up_pm_qos_threshold;
unsigned down_pm_qos_sample_sec;
unsigned down_pm_qos_threshold;
unsigned idle_pc_rpm_no_int_secs;
struct delayed_work pm_qos_work;
enum android_pm_qos_state curr_pm_qos_state;
struct work_struct work;
char ffs_aliases[256];
/* A list of struct android_configuration */
struct list_head configs;
int configs_num;
/* A list node inside the android_dev_list */
struct list_head list_item;
};
struct android_configuration {
struct usb_configuration usb_config;
/* A list of the functions supported by this config */
struct list_head enabled_functions;
/* A list node inside the struct android_dev.configs list */
struct list_head list_item;
};
struct dload_struct __iomem *diag_dload;
static struct class *android_class;
static struct list_head android_dev_list;
static int android_dev_count;
static int android_bind_config(struct usb_configuration *c);
static void android_unbind_config(struct usb_configuration *c);
static struct android_dev *cdev_to_android_dev(struct usb_composite_dev *cdev);
static struct android_configuration *alloc_android_config
(struct android_dev *dev);
static void free_android_config(struct android_dev *dev,
struct android_configuration *conf);
static int usb_diag_update_pid_and_serial_num(uint32_t pid, const char *snum);
/* string IDs are assigned dynamically */
#define STRING_MANUFACTURER_IDX 0
#define STRING_PRODUCT_IDX 1
#define STRING_SERIAL_IDX 2
static char manufacturer_string[256];
static char product_string[256];
static char serial_string[256];
/* String Table */
static struct usb_string strings_dev[] = {
[STRING_MANUFACTURER_IDX].s = manufacturer_string,
[STRING_PRODUCT_IDX].s = product_string,
[STRING_SERIAL_IDX].s = serial_string,
{ } /* end of list */
};
static struct usb_gadget_strings stringtab_dev = {
.language = 0x0409, /* en-us */
.strings = strings_dev,
};
static struct usb_gadget_strings *dev_strings[] = {
&stringtab_dev,
NULL,
};
static struct usb_device_descriptor device_desc = {
.bLength = sizeof(device_desc),
.bDescriptorType = USB_DT_DEVICE,
.bcdUSB = __constant_cpu_to_le16(0x0200),
.bDeviceClass = USB_CLASS_PER_INTERFACE,
.idVendor = __constant_cpu_to_le16(VENDOR_ID),
.idProduct = __constant_cpu_to_le16(PRODUCT_ID),
.bcdDevice = __constant_cpu_to_le16(0xffff),
.bNumConfigurations = 1,
};
static struct usb_otg_descriptor otg_descriptor = {
.bLength = sizeof otg_descriptor,
.bDescriptorType = USB_DT_OTG,
.bmAttributes = USB_OTG_SRP | USB_OTG_HNP,
.bcdOTG = __constant_cpu_to_le16(0x0200),
};
static const struct usb_descriptor_header *otg_desc[] = {
(struct usb_descriptor_header *) &otg_descriptor,
NULL,
};
static const char *pm_qos_to_string(enum android_pm_qos_state state)
{
switch (state) {
case NO_USB_VOTE: return "NO_USB_VOTE";
case WFI: return "WFI";
case IDLE_PC: return "IDLE_PC";
case IDLE_PC_RPM: return "IDLE_PC_RPM";
default: return "INVALID_STATE";
}
}
static void android_pm_qos_update_latency(struct android_dev *dev, u32 latency)
{
static int last_vote = -1;
if (latency == last_vote || !latency)
return;
pr_debug("%s: latency updated to: %d\n", __func__, latency);
pm_qos_update_request(&dev->pm_qos_req_dma, latency);
last_vote = latency;
}
#define DOWN_PM_QOS_SAMPLE_SEC 5
#define DOWN_PM_QOS_THRESHOLD 100
#define UP_PM_QOS_SAMPLE_SEC 3
#define UP_PM_QOS_THRESHOLD 70
#define IDLE_PC_RPM_NO_INT_SECS 10
static void android_pm_qos_work(struct work_struct *data)
{
struct android_dev *dev = container_of(data, struct android_dev,
pm_qos_work.work);
struct usb_gadget *gadget = dev->cdev->gadget;
unsigned next_latency, curr_sample_int_count;
unsigned next_sample_delay_sec;
enum android_pm_qos_state next_state = dev->curr_pm_qos_state;
static unsigned no_int_sample_count;
curr_sample_int_count = gadget->xfer_isr_count;
gadget->xfer_isr_count = 0;
switch (dev->curr_pm_qos_state) {
case WFI:
if (curr_sample_int_count <= dev->down_pm_qos_threshold) {
next_state = IDLE_PC;
next_sample_delay_sec = dev->up_pm_qos_sample_sec;
no_int_sample_count = 0;
} else {
next_sample_delay_sec = dev->down_pm_qos_sample_sec;
}
break;
case IDLE_PC:
if (!curr_sample_int_count)
no_int_sample_count++;
else
no_int_sample_count = 0;
if (curr_sample_int_count >= dev->up_pm_qos_threshold) {
next_state = WFI;
next_sample_delay_sec = dev->down_pm_qos_sample_sec;
} else if (no_int_sample_count >=
dev->idle_pc_rpm_no_int_secs/dev->up_pm_qos_sample_sec) {
next_state = IDLE_PC_RPM;
next_sample_delay_sec = dev->up_pm_qos_sample_sec;
} else {
next_sample_delay_sec = dev->up_pm_qos_sample_sec;
}
break;
case IDLE_PC_RPM:
if (curr_sample_int_count) {
next_state = WFI;
next_sample_delay_sec = dev->down_pm_qos_sample_sec;
no_int_sample_count = 0;
} else {
next_sample_delay_sec = 2 * dev->up_pm_qos_sample_sec;
}
break;
default:
pr_debug("invalid pm_qos_state (%u)\n", dev->curr_pm_qos_state);
return;
}
if (next_state != dev->curr_pm_qos_state) {
dev->curr_pm_qos_state = next_state;
next_latency = dev->pdata->pm_qos_latency[next_state];
android_pm_qos_update_latency(dev, next_latency);
pr_debug("%s: pm_qos_state:%s, interrupts in last sample:%d\n",
__func__, pm_qos_to_string(next_state),
curr_sample_int_count);
}
queue_delayed_work(system_nrt_wq, &dev->pm_qos_work,
msecs_to_jiffies(1000*next_sample_delay_sec));
}
enum android_device_state {
USB_DISCONNECTED,
USB_CONNECTED,
USB_CONFIGURED,
USB_SUSPENDED,
USB_RESUMED
};
static void android_work(struct work_struct *data)
{
struct android_dev *dev = container_of(data, struct android_dev, work);
struct usb_composite_dev *cdev = dev->cdev;
struct android_usb_platform_data *pdata = dev->pdata;
char *disconnected[2] = { "USB_STATE=DISCONNECTED", NULL };
char *connected[2] = { "USB_STATE=CONNECTED", NULL };
char *configured[2] = { "USB_STATE=CONFIGURED", NULL };
char *suspended[2] = { "USB_STATE=SUSPENDED", NULL };
char *resumed[2] = { "USB_STATE=RESUMED", NULL };
char **uevent_envp = NULL;
static enum android_device_state last_uevent, next_state;
unsigned long flags;
int pm_qos_vote = -1;
spin_lock_irqsave(&cdev->lock, flags);
if (dev->suspended != dev->sw_suspended && cdev->config) {
if (strncmp(dev->pm_qos, "low", 3))
pm_qos_vote = dev->suspended ? 0 : 1;
next_state = dev->suspended ? USB_SUSPENDED : USB_RESUMED;
uevent_envp = dev->suspended ? suspended : resumed;
} else if (cdev->config) {
uevent_envp = configured;
next_state = USB_CONFIGURED;
} else if (dev->connected != dev->sw_connected) {
uevent_envp = dev->connected ? connected : disconnected;
next_state = dev->connected ? USB_CONNECTED : USB_DISCONNECTED;
if (dev->connected && strncmp(dev->pm_qos, "low", 3))
pm_qos_vote = 1;
else if (!dev->connected || !strncmp(dev->pm_qos, "low", 3))
pm_qos_vote = 0;
}
dev->sw_connected = dev->connected;
dev->sw_suspended = dev->suspended;
spin_unlock_irqrestore(&cdev->lock, flags);
if (pdata->pm_qos_latency[0] && pm_qos_vote == 1) {
cancel_delayed_work_sync(&dev->pm_qos_work);
android_pm_qos_update_latency(dev, pdata->pm_qos_latency[WFI]);
dev->curr_pm_qos_state = WFI;
queue_delayed_work(system_nrt_wq, &dev->pm_qos_work,
msecs_to_jiffies(1000*dev->down_pm_qos_sample_sec));
} else if (pdata->pm_qos_latency[0] && pm_qos_vote == 0) {
cancel_delayed_work_sync(&dev->pm_qos_work);
android_pm_qos_update_latency(dev, PM_QOS_DEFAULT_VALUE);
dev->curr_pm_qos_state = NO_USB_VOTE;
}
if (uevent_envp) {
/*
* Some userspace modules, e.g. MTP, work correctly only if
* CONFIGURED uevent is preceded by DISCONNECT uevent.
* Check if we missed sending out a DISCONNECT uevent. This can
* happen if host PC resets and configures device really quick.
*/
if (((uevent_envp == connected) &&
(last_uevent != USB_DISCONNECTED)) ||
((uevent_envp == configured) &&
(last_uevent == USB_CONFIGURED))) {
pr_info("%s: sent missed DISCONNECT event\n", __func__);
kobject_uevent_env(&dev->dev->kobj, KOBJ_CHANGE,
disconnected);
msleep(20);
}
/*
* Before sending out CONFIGURED uevent give function drivers
* a chance to wakeup userspace threads and notify disconnect
*/
if (uevent_envp == configured)
msleep(50);
/* Do not notify on suspend / resume */
if (next_state != USB_SUSPENDED && next_state != USB_RESUMED) {
kobject_uevent_env(&dev->dev->kobj, KOBJ_CHANGE,
uevent_envp);
last_uevent = next_state;
}
pr_info("%s: sent uevent %s\n", __func__, uevent_envp[0]);
} else {
pr_info("%s: did not send uevent (%d %d %p)\n", __func__,
dev->connected, dev->sw_connected, cdev->config);
}
}
static int android_enable(struct android_dev *dev)
{
struct usb_composite_dev *cdev = dev->cdev;
struct android_configuration *conf;
int err = 0;
if (WARN_ON(!dev->disable_depth))
return err;
if (--dev->disable_depth == 0) {
list_for_each_entry(conf, &dev->configs, list_item) {
err = usb_add_config(cdev, &conf->usb_config,
android_bind_config);
if (err < 0) {
pr_err("%s: usb_add_config failed : err: %d\n",
__func__, err);
return err;
}
}
usb_gadget_connect(cdev->gadget);
}
return err;
}
static void android_disable(struct android_dev *dev)
{
struct usb_composite_dev *cdev = dev->cdev;
struct android_configuration *conf;
if (dev->disable_depth++ == 0) {
usb_gadget_disconnect(cdev->gadget);
/* Cancel pending control requests */
usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
list_for_each_entry(conf, &dev->configs, list_item)
usb_remove_config(cdev, &conf->usb_config);
}
}
/*-------------------------------------------------------------------------*/
/* Supported functions initialization */
struct functionfs_config {
bool opened;
bool enabled;
struct ffs_data *data;
struct android_dev *dev;
};
static int ffs_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
f->config = kzalloc(sizeof(struct functionfs_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return functionfs_init();
}
static void ffs_function_cleanup(struct android_usb_function *f)
{
functionfs_cleanup();
kfree(f->config);
}
static void ffs_function_enable(struct android_usb_function *f)
{
struct android_dev *dev = f->android_dev;
struct functionfs_config *config = f->config;
config->enabled = true;
/* Disable the gadget until the function is ready */
if (!config->opened)
android_disable(dev);
}
static void ffs_function_disable(struct android_usb_function *f)
{
struct android_dev *dev = f->android_dev;
struct functionfs_config *config = f->config;
config->enabled = false;
/* Balance the disable that was called in closed_callback */
if (!config->opened)
android_enable(dev);
}
static int ffs_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct functionfs_config *config = f->config;
return functionfs_bind_config(c->cdev, c, config->data);
}
static ssize_t
ffs_aliases_show(struct device *pdev, struct device_attribute *attr, char *buf)
{
struct android_dev *dev;
int ret;
dev = list_first_entry(&android_dev_list, struct android_dev,
list_item);
mutex_lock(&dev->mutex);
ret = sprintf(buf, "%s\n", dev->ffs_aliases);
mutex_unlock(&dev->mutex);
return ret;
}
static ssize_t
ffs_aliases_store(struct device *pdev, struct device_attribute *attr,
const char *buf, size_t size)
{
struct android_dev *dev;
char buff[256];
dev = list_first_entry(&android_dev_list, struct android_dev,
list_item);
mutex_lock(&dev->mutex);
if (dev->enabled) {
mutex_unlock(&dev->mutex);
return -EBUSY;
}
strlcpy(buff, buf, sizeof(buff));
strlcpy(dev->ffs_aliases, strim(buff), sizeof(dev->ffs_aliases));
mutex_unlock(&dev->mutex);
return size;
}
static DEVICE_ATTR(aliases, S_IRUGO | S_IWUSR, ffs_aliases_show,
ffs_aliases_store);
static struct device_attribute *ffs_function_attributes[] = {
&dev_attr_aliases,
NULL
};
static struct android_usb_function ffs_function = {
.name = "ffs",
.init = ffs_function_init,
.enable = ffs_function_enable,
.disable = ffs_function_disable,
.cleanup = ffs_function_cleanup,
.bind_config = ffs_function_bind_config,
.attributes = ffs_function_attributes,
};
static int functionfs_ready_callback(struct ffs_data *ffs)
{
struct android_dev *dev = ffs_function.android_dev;
struct functionfs_config *config = ffs_function.config;
int ret = 0;
/* dev is null in case ADB is not in the composition */
if (dev) {
mutex_lock(&dev->mutex);
ret = functionfs_bind(ffs, dev->cdev);
if (ret) {
mutex_unlock(&dev->mutex);
return ret;
}
} else {
/* android ffs_func requires daemon to start only after enable*/
pr_debug("start adbd only in ADB composition\n");
return -ENODEV;
}
config->data = ffs;
config->opened = true;
/* Save dev in case the adb function will get disabled */
config->dev = dev;
if (config->enabled)
android_enable(dev);
mutex_unlock(&dev->mutex);
return 0;
}
static void functionfs_closed_callback(struct ffs_data *ffs)
{
struct android_dev *dev = ffs_function.android_dev;
struct functionfs_config *config = ffs_function.config;
/*
* In case new composition is without ADB or ADB got disabled by the
* time ffs_daemon was stopped then use saved one
*/
if (!dev)
dev = config->dev;
/* fatal-error: It should never happen */
if (!dev)
pr_err("adb_closed_callback: config->dev is NULL");
if (dev)
mutex_lock(&dev->mutex);
if (config->enabled && dev)
android_disable(dev);
config->dev = NULL;
config->opened = false;
config->data = NULL;
functionfs_unbind(ffs);
if (dev)
mutex_unlock(&dev->mutex);
}
static void *functionfs_acquire_dev_callback(const char *dev_name)
{
return 0;
}
static void functionfs_release_dev_callback(struct ffs_data *ffs_data)
{
}
/* ACM */
static char acm_transports[32]; /*enabled ACM ports - "tty[,sdio]"*/
#define MAX_ACM_INSTANCES 4
struct acm_function_config {
int instances;
int instances_on;
struct usb_function *f_acm[MAX_ACM_INSTANCES];
struct usb_function_instance *f_acm_inst[MAX_ACM_INSTANCES];
};
static int
acm_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
struct acm_function_config *config;
config = kzalloc(sizeof(struct acm_function_config), GFP_KERNEL);
if (!config)
return -ENOMEM;
f->config = config;
return 0;
}
static void acm_function_cleanup(struct android_usb_function *f)
{
int i;
struct acm_function_config *config = f->config;
acm_port_cleanup();
for (i = 0; i < config->instances_on; i++) {
usb_put_function(config->f_acm[i]);
usb_put_function_instance(config->f_acm_inst[i]);
}
kfree(f->config);
f->config = NULL;
}
static int
acm_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
char *name;
char buf[32], *b;
int err = -1, i;
static int acm_initialized, ports;
struct acm_function_config *config = f->config;
if (acm_initialized)
goto bind_config;
acm_initialized = 1;
strlcpy(buf, acm_transports, sizeof(buf));
b = strim(buf);
while (b) {
name = strsep(&b, ",");
if (name) {
err = acm_init_port(ports, name);
if (err) {
pr_err("acm: Cannot open port '%s'", name);
goto out;
}
ports++;
if (ports >= MAX_ACM_INSTANCES) {
pr_err("acm: max ports reached '%s'", name);
goto out;
}
}
}
err = acm_port_setup(c);
if (err) {
pr_err("acm: Cannot setup transports");
goto out;
}
for (i = 0; i < ports; i++) {
config->f_acm_inst[i] = usb_get_function_instance("acm");
if (IS_ERR(config->f_acm_inst[i])) {
err = PTR_ERR(config->f_acm_inst[i]);
goto err_usb_get_function_instance;
}
config->f_acm[i] = usb_get_function(config->f_acm_inst[i]);
if (IS_ERR(config->f_acm[i])) {
err = PTR_ERR(config->f_acm[i]);
goto err_usb_get_function;
}
}
config->instances_on = ports;
bind_config:
for (i = 0; i < ports; i++) {
err = usb_add_function(c, config->f_acm[i]);
if (err) {
pr_err("Could not bind acm%u config\n", i);
goto err_usb_add_function;
}
}
return 0;
err_usb_add_function:
while (i-- > 0)
usb_remove_function(c, config->f_acm[i]);
config->instances_on = 0;
return err;
err_usb_get_function_instance:
while (i-- > 0) {
usb_put_function(config->f_acm[i]);
err_usb_get_function:
usb_put_function_instance(config->f_acm_inst[i]);
}
out:
config->instances_on = 0;
return err;
}
static void acm_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct acm_function_config *config = f->config;
config->instances_on = 0;
}
static ssize_t acm_transports_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strlcpy(acm_transports, buff, sizeof(acm_transports));
return size;
}
static DEVICE_ATTR(acm_transports, S_IWUSR, NULL, acm_transports_store);
static struct device_attribute *acm_function_attributes[] = {
&dev_attr_acm_transports,
NULL
};
static struct android_usb_function acm_function = {
.name = "acm",
.init = acm_function_init,
.cleanup = acm_function_cleanup,
.bind_config = acm_function_bind_config,
.unbind_config = acm_function_unbind_config,
.attributes = acm_function_attributes,
};
/* RMNET_SMD */
static int rmnet_smd_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return rmnet_smd_bind_config(c);
}
static struct android_usb_function rmnet_smd_function = {
.name = "rmnet_smd",
.bind_config = rmnet_smd_function_bind_config,
};
/*rmnet transport string format(per port):"ctrl0,data0,ctrl1,data1..." */
#define MAX_XPORT_STR_LEN 50
static char rmnet_transports[MAX_XPORT_STR_LEN];
/*rmnet transport name string - "rmnet_hsic[,rmnet_hsusb]" */
static char rmnet_xport_names[MAX_XPORT_STR_LEN];
/*qdss transport string format(per port):"bam [, hsic]" */
static char qdss_transports[MAX_XPORT_STR_LEN];
/*qdss transport name string - "qdss_bam [, qdss_hsic]" */
static char qdss_xport_names[MAX_XPORT_STR_LEN];
/*qdss debug interface setting 0: disable 1:enable */
static bool qdss_debug_intf;
static void rmnet_function_cleanup(struct android_usb_function *f)
{
frmnet_cleanup();
}
static int rmnet_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int i;
int err = 0;
char *ctrl_name;
char *data_name;
char *tname = NULL;
char buf[MAX_XPORT_STR_LEN], *b;
char xport_name_buf[MAX_XPORT_STR_LEN], *tb;
static int rmnet_initialized, ports;
if (!rmnet_initialized) {
rmnet_initialized = 1;
strlcpy(buf, rmnet_transports, sizeof(buf));
b = strim(buf);
strlcpy(xport_name_buf, rmnet_xport_names,
sizeof(xport_name_buf));
tb = strim(xport_name_buf);
while (b) {
ctrl_name = strsep(&b, ",");
data_name = strsep(&b, ",");
if (ctrl_name && data_name) {
if (tb)
tname = strsep(&tb, ",");
err = frmnet_init_port(ctrl_name, data_name,
tname);
if (err) {
pr_err("rmnet: Cannot open ctrl port:"
"'%s' data port:'%s'\n",
ctrl_name, data_name);
goto out;
}
ports++;
}
}
err = rmnet_gport_setup();
if (err) {
pr_err("rmnet: Cannot setup transports");
goto out;
}
}
for (i = 0; i < ports; i++) {
err = frmnet_bind_config(c, i);
if (err) {
pr_err("Could not bind rmnet%u config\n", i);
break;
}
}
out:
return err;
}
static void rmnet_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
frmnet_unbind_config();
}
static ssize_t rmnet_transports_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", rmnet_transports);
}
static ssize_t rmnet_transports_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strlcpy(rmnet_transports, buff, sizeof(rmnet_transports));
return size;
}
static ssize_t rmnet_xport_names_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", rmnet_xport_names);
}
static ssize_t rmnet_xport_names_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strlcpy(rmnet_xport_names, buff, sizeof(rmnet_xport_names));
return size;
}
static struct device_attribute dev_attr_rmnet_transports =
__ATTR(transports, S_IRUGO | S_IWUSR,
rmnet_transports_show,
rmnet_transports_store);
static struct device_attribute dev_attr_rmnet_xport_names =
__ATTR(transport_names, S_IRUGO | S_IWUSR,
rmnet_xport_names_show,
rmnet_xport_names_store);
static struct device_attribute *rmnet_function_attributes[] = {
&dev_attr_rmnet_transports,
&dev_attr_rmnet_xport_names,
NULL };
static struct android_usb_function rmnet_function = {
.name = "rmnet",
.cleanup = rmnet_function_cleanup,
.bind_config = rmnet_function_bind_config,
.unbind_config = rmnet_function_unbind_config,
.attributes = rmnet_function_attributes,
};
static void gps_function_cleanup(struct android_usb_function *f)
{
gps_cleanup();
}
static int gps_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int err;
static int gps_initialized;
if (!gps_initialized) {
gps_initialized = 1;
err = gps_init_port();
if (err) {
pr_err("gps: Cannot init gps port");
return err;
}
}
err = gps_gport_setup();
if (err) {
pr_err("gps: Cannot setup transports");
return err;
}
err = gps_bind_config(c);
if (err) {
pr_err("Could not bind gps config\n");
return err;
}
return 0;
}
static struct android_usb_function gps_function = {
.name = "gps",
.cleanup = gps_function_cleanup,
.bind_config = gps_function_bind_config,
};
/* ncm */
struct ncm_function_config {
u8 ethaddr[ETH_ALEN];
struct eth_dev *dev;
};
static int
ncm_function_init(struct android_usb_function *f, struct usb_composite_dev *c)
{
f->config = kzalloc(sizeof(struct ncm_function_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return 0;
}
static void ncm_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
f->config = NULL;
}
static int
ncm_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct ncm_function_config *ncm = f->config;
int ret;
struct eth_dev *dev;
if (!ncm) {
pr_err("%s: ncm config is null\n", __func__);
return -EINVAL;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
ncm->ethaddr[0], ncm->ethaddr[1], ncm->ethaddr[2],
ncm->ethaddr[3], ncm->ethaddr[4], ncm->ethaddr[5]);
dev = gether_setup_name(c->cdev->gadget, ncm->ethaddr, "ncm");
if (IS_ERR(dev)) {
ret = PTR_ERR(dev);
pr_err("%s: gether setup failed err:%d\n", __func__, ret);
return ret;
}
ncm->dev = dev;
ret = ncm_bind_config(c, ncm->ethaddr, dev);
if (ret) {
pr_err("%s: ncm bind config failed err:%d", __func__, ret);
gether_cleanup(dev);
return ret;
}
return ret;
}
static void ncm_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct ncm_function_config *ncm = f->config;
gether_cleanup(ncm->dev);
}
static ssize_t ncm_ethaddr_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct ncm_function_config *ncm = f->config;
return snprintf(buf, PAGE_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x\n",
ncm->ethaddr[0], ncm->ethaddr[1], ncm->ethaddr[2],
ncm->ethaddr[3], ncm->ethaddr[4], ncm->ethaddr[5]);
}
static ssize_t ncm_ethaddr_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct ncm_function_config *ncm = f->config;
if (sscanf(buf, "%02x:%02x:%02x:%02x:%02x:%02x\n",
(int *)&ncm->ethaddr[0], (int *)&ncm->ethaddr[1],
(int *)&ncm->ethaddr[2], (int *)&ncm->ethaddr[3],
(int *)&ncm->ethaddr[4], (int *)&ncm->ethaddr[5]) == 6)
return size;
return -EINVAL;
}
static DEVICE_ATTR(ncm_ethaddr, S_IRUGO | S_IWUSR, ncm_ethaddr_show,
ncm_ethaddr_store);
static struct device_attribute *ncm_function_attributes[] = {
&dev_attr_ncm_ethaddr,
NULL
};
static struct android_usb_function ncm_function = {
.name = "ncm",
.init = ncm_function_init,
.cleanup = ncm_function_cleanup,
.bind_config = ncm_function_bind_config,
.unbind_config = ncm_function_unbind_config,
.attributes = ncm_function_attributes,
};
/* ecm transport string */
static char ecm_transports[MAX_XPORT_STR_LEN];
struct ecm_function_config {
u8 ethaddr[ETH_ALEN];
struct eth_dev *dev;
};
static int ecm_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
f->config = kzalloc(sizeof(struct ecm_function_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return 0;
}
static void ecm_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
f->config = NULL;
}
static int ecm_qc_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int ret;
char *trans;
struct ecm_function_config *ecm = f->config;
if (!ecm) {
pr_err("%s: ecm_pdata\n", __func__);
return -EINVAL;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
ecm->ethaddr[0], ecm->ethaddr[1], ecm->ethaddr[2],
ecm->ethaddr[3], ecm->ethaddr[4], ecm->ethaddr[5]);
pr_debug("%s: ecm_transport is %s", __func__, ecm_transports);
trans = strim(ecm_transports);
if (strcmp("BAM2BAM_IPA", trans)) {
ret = gether_qc_setup_name(c->cdev->gadget,
ecm->ethaddr, "ecm");
if (ret) {
pr_err("%s: gether_setup failed\n", __func__);
return ret;
}
}
return ecm_qc_bind_config(c, ecm->ethaddr, trans);
}
static void ecm_qc_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
char *trans = strim(ecm_transports);
if (strcmp("BAM2BAM_IPA", trans))
gether_qc_cleanup_name("ecm0");
}
static ssize_t ecm_ethaddr_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct ecm_function_config *ecm = f->config;
return snprintf(buf, PAGE_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x\n",
ecm->ethaddr[0], ecm->ethaddr[1], ecm->ethaddr[2],
ecm->ethaddr[3], ecm->ethaddr[4], ecm->ethaddr[5]);
}
static ssize_t ecm_ethaddr_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct ecm_function_config *ecm = f->config;
if (sscanf(buf, "%02x:%02x:%02x:%02x:%02x:%02x\n",
(int *)&ecm->ethaddr[0], (int *)&ecm->ethaddr[1],
(int *)&ecm->ethaddr[2], (int *)&ecm->ethaddr[3],
(int *)&ecm->ethaddr[4], (int *)&ecm->ethaddr[5]) == 6)
return size;
return -EINVAL;
}
static DEVICE_ATTR(ecm_ethaddr, S_IRUGO | S_IWUSR, ecm_ethaddr_show,
ecm_ethaddr_store);
static ssize_t ecm_transports_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", ecm_transports);
}
static ssize_t ecm_transports_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
strlcpy(ecm_transports, buf, sizeof(ecm_transports));
return size;
}
static DEVICE_ATTR(ecm_transports, S_IRUGO | S_IWUSR, ecm_transports_show,
ecm_transports_store);
static struct device_attribute *ecm_function_attributes[] = {
&dev_attr_ecm_transports,
&dev_attr_ecm_ethaddr,
NULL
};
static struct android_usb_function ecm_qc_function = {
.name = "ecm_qc",
.init = ecm_function_init,
.cleanup = ecm_function_cleanup,
.bind_config = ecm_qc_function_bind_config,
.unbind_config = ecm_qc_function_unbind_config,
.attributes = ecm_function_attributes,
};
/* MBIM - used with BAM */
#define MAX_MBIM_INSTANCES 1
static int mbim_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return mbim_init(MAX_MBIM_INSTANCES);
}
static void mbim_function_cleanup(struct android_usb_function *f)
{
fmbim_cleanup();
}
/* mbim transport string */
static char mbim_transports[MAX_XPORT_STR_LEN];
static int mbim_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
char *trans;
pr_debug("%s: mbim transport is %s", __func__, mbim_transports);
trans = strim(mbim_transports);
return mbim_bind_config(c, 0, trans);
}
static int mbim_function_ctrlrequest(struct android_usb_function *f,
struct usb_composite_dev *cdev,
const struct usb_ctrlrequest *c)
{
return mbim_ctrlrequest(cdev, c);
}
static ssize_t mbim_transports_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", mbim_transports);
}
static ssize_t mbim_transports_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
strlcpy(mbim_transports, buf, sizeof(mbim_transports));
return size;
}
static DEVICE_ATTR(mbim_transports, S_IRUGO | S_IWUSR, mbim_transports_show,
mbim_transports_store);
static ssize_t wMTU_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", ext_mbb_desc.wMTU);
}
static ssize_t wMTU_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
int value;
if (sscanf(buf, "%d", &value) == 1) {
if (value < 0 || value > USHRT_MAX)
pr_err("illegal MTU %d, enter unsigned 16 bits\n",
value);
else
ext_mbb_desc.wMTU = cpu_to_le16(value);
return size;
}
return -EINVAL;
}
static DEVICE_ATTR(wMTU, S_IRUGO | S_IWUSR, wMTU_show,
wMTU_store);
static struct device_attribute *mbim_function_attributes[] = {
&dev_attr_mbim_transports,
&dev_attr_wMTU,
NULL
};
static struct android_usb_function mbim_function = {
.name = "usb_mbim",
.cleanup = mbim_function_cleanup,
.bind_config = mbim_function_bind_config,
.init = mbim_function_init,
.ctrlrequest = mbim_function_ctrlrequest,
.attributes = mbim_function_attributes,
};
#ifdef CONFIG_SND_PCM
/* PERIPHERAL AUDIO */
static int audio_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return audio_bind_config(c);
}
static struct android_usb_function audio_function = {
.name = "audio",
.bind_config = audio_function_bind_config,
};
#endif
/* DIAG */
static char diag_clients[32]; /*enabled DIAG clients- "diag[,diag_mdm]" */
static ssize_t clients_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strlcpy(diag_clients, buff, sizeof(diag_clients));
return size;
}
static DEVICE_ATTR(clients, S_IWUSR, NULL, clients_store);
static struct device_attribute *diag_function_attributes[] =
{ &dev_attr_clients, NULL };
static int diag_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return diag_setup();
}
static void diag_function_cleanup(struct android_usb_function *f)
{
diag_cleanup();
}
static int diag_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
char *name;
char buf[32], *b;
int once = 0, err = -1;
int (*notify)(uint32_t, const char *);
struct android_dev *dev = cdev_to_android_dev(c->cdev);
strlcpy(buf, diag_clients, sizeof(buf));
b = strim(buf);
while (b) {
notify = NULL;
name = strsep(&b, ",");
/* Allow only first diag channel to update pid and serial no */
if (!once++) {
if (dev->pdata && dev->pdata->update_pid_and_serial_num)
notify = dev->pdata->update_pid_and_serial_num;
else
notify = usb_diag_update_pid_and_serial_num;
}
if (name) {
err = diag_function_add(c, name, notify);
if (err)
pr_err("diag: Cannot open channel '%s'", name);
}
}
return err;
}
static struct android_usb_function diag_function = {
.name = "diag",
.init = diag_function_init,
.cleanup = diag_function_cleanup,
.bind_config = diag_function_bind_config,
.attributes = diag_function_attributes,
};
/* DEBUG */
static int qdss_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return qdss_setup();
}
static void qdss_function_cleanup(struct android_usb_function *f)
{
qdss_cleanup();
}
static int qdss_init_transports(int *portnum)
{
char *ts_port;
char *tname = NULL;
char buf[MAX_XPORT_STR_LEN], *type;
char xport_name_buf[MAX_XPORT_STR_LEN], *tn;
int err = 0;
strlcpy(buf, qdss_transports, sizeof(buf));
type = strim(buf);
strlcpy(xport_name_buf, qdss_xport_names,
sizeof(xport_name_buf));
tn = strim(xport_name_buf);
pr_debug("%s: qdss_debug_intf = %d\n",
__func__, qdss_debug_intf);
while (type) {
ts_port = strsep(&type, ",");
if (ts_port) {
if (tn)
tname = strsep(&tn, ",");
err = qdss_init_port(
ts_port,
tname,
qdss_debug_intf);
if (err) {
pr_err("%s: Cannot open transport port:'%s'\n",
__func__, ts_port);
return err;
}
(*portnum)++;
}
}
return err;
}
static int qdss_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int i;
int err = 0;
static int qdss_initialized = 0, portsnum;
if (!qdss_initialized) {
qdss_initialized = 1;
err = qdss_init_transports(&portsnum);
if (err) {
pr_err("qdss: Cannot init transports");
goto out;
}
err = qdss_gport_setup();
if (err) {
pr_err("qdss: Cannot setup transports");
goto out;
}
}
pr_debug("%s: port number is %d\n", __func__, portsnum);
for (i = 0; i < portsnum; i++) {
err = qdss_bind_config(c, i);
if (err) {
pr_err("Could not bind qdss%u config\n", i);
break;
}
}
out:
return err;
}
static ssize_t qdss_transports_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", qdss_transports);
}
static ssize_t qdss_transports_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strlcpy(qdss_transports, buff, sizeof(qdss_transports));
return size;
}
static ssize_t qdss_xport_names_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", qdss_xport_names);
}
static ssize_t qdss_xport_names_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strlcpy(qdss_xport_names, buff, sizeof(qdss_xport_names));
return size;
}
static ssize_t qdss_debug_intf_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strtobool(buff, &qdss_debug_intf);
return size;
}
static ssize_t qdss_debug_intf_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", qdss_debug_intf);
}
static struct device_attribute dev_attr_qdss_transports =
__ATTR(transports, S_IRUGO | S_IWUSR,
qdss_transports_show,
qdss_transports_store);
static struct device_attribute dev_attr_qdss_xport_names =
__ATTR(transport_names, S_IRUGO | S_IWUSR,
qdss_xport_names_show,
qdss_xport_names_store);
/* 1(enable)/0(disable) the qdss debug interface */
static struct device_attribute dev_attr_qdss_debug_intf =
__ATTR(debug_intf, S_IRUGO | S_IWUSR,
qdss_debug_intf_show,
qdss_debug_intf_store);
static struct device_attribute *qdss_function_attributes[] = {
&dev_attr_qdss_transports,
&dev_attr_qdss_xport_names,
&dev_attr_qdss_debug_intf,
NULL };
static struct android_usb_function qdss_function = {
.name = "qdss",
.init = qdss_function_init,
.cleanup = qdss_function_cleanup,
.bind_config = qdss_function_bind_config,
.attributes = qdss_function_attributes,
};
/* SERIAL */
#define MAX_SERIAL_INSTANCES 4
struct serial_function_config {
int instances_on;
struct usb_function *f_serial[MAX_SERIAL_INSTANCES];
struct usb_function_instance *f_serial_inst[MAX_SERIAL_INSTANCES];
};
static char serial_transports[32]; /*enabled FSERIAL ports - "tty[,sdio]"*/
static ssize_t serial_transports_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strlcpy(serial_transports, buff, sizeof(serial_transports));
return size;
}
/*enabled FSERIAL transport names - "serial_hsic[,serial_hsusb]"*/
static char serial_xport_names[32];
static ssize_t serial_xport_names_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strlcpy(serial_xport_names, buff, sizeof(serial_xport_names));
return size;
}
static ssize_t serial_xport_names_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", serial_xport_names);
}
static DEVICE_ATTR(transports, S_IWUSR, NULL, serial_transports_store);
static struct device_attribute dev_attr_serial_xport_names =
__ATTR(transport_names, S_IRUGO | S_IWUSR,
serial_xport_names_show,
serial_xport_names_store);
static struct device_attribute *serial_function_attributes[] = {
&dev_attr_transports,
&dev_attr_serial_xport_names,
NULL };
static int serial_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
struct serial_function_config *config;
config = kzalloc(sizeof(struct serial_function_config), GFP_KERNEL);
if (!config)
return -ENOMEM;
f->config = config;
return 0;
}
static void serial_function_cleanup(struct android_usb_function *f)
{
int i;
struct serial_function_config *config = f->config;
gport_cleanup();
for (i = 0; i < config->instances_on; i++) {
usb_put_function(config->f_serial[i]);
usb_put_function_instance(config->f_serial_inst[i]);
}
kfree(f->config);
f->config = NULL;
}
static int serial_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
char *name, *xport_name = NULL;
char buf[32], *b, xport_name_buf[32], *tb;
int err = -1, i;
static int serial_initialized = 0, ports = 0;
struct serial_function_config *config = f->config;
if (serial_initialized)
goto bind_config;
serial_initialized = 1;
strlcpy(buf, serial_transports, sizeof(buf));
b = strim(buf);
strlcpy(xport_name_buf, serial_xport_names, sizeof(xport_name_buf));
tb = strim(xport_name_buf);
while (b) {
name = strsep(&b, ",");
if (name) {
if (tb)
xport_name = strsep(&tb, ",");
err = gserial_init_port(ports, name, xport_name);
if (err) {
pr_err("serial: Cannot open port '%s'", name);
goto out;
}
ports++;
if (ports >= MAX_SERIAL_INSTANCES) {
pr_err("serial: max ports reached '%s'", name);
goto out;
}
}
}
err = gport_setup(c);
if (err) {
pr_err("serial: Cannot setup transports");
goto out;
}
for (i = 0; i < ports; i++) {
config->f_serial_inst[i] = usb_get_function_instance("gser");
if (IS_ERR(config->f_serial_inst[i])) {
err = PTR_ERR(config->f_serial_inst[i]);
goto err_gser_usb_get_function_instance;
}
config->f_serial[i] = usb_get_function(config->f_serial_inst[i]);
if (IS_ERR(config->f_serial[i])) {
err = PTR_ERR(config->f_serial[i]);
goto err_gser_usb_get_function;
}
}
config->instances_on = ports;
bind_config:
for (i = 0; i < ports; i++) {
err = usb_add_function(c, config->f_serial[i]);
if (err) {
pr_err("Could not bind gser%u config\n", i);
goto err_gser_usb_add_function;
}
}
return 0;
err_gser_usb_add_function:
while (i-- > 0)
usb_remove_function(c, config->f_serial[i]);
return err;
err_gser_usb_get_function_instance:
while (i-- > 0) {
usb_put_function(config->f_serial[i]);
err_gser_usb_get_function:
usb_put_function_instance(config->f_serial_inst[i]);
}
out:
return err;
}
static struct android_usb_function serial_function = {
.name = "serial",
.init = serial_function_init,
.cleanup = serial_function_cleanup,
.bind_config = serial_function_bind_config,
.attributes = serial_function_attributes,
};
/* CCID */
static int ccid_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return ccid_setup();
}
static void ccid_function_cleanup(struct android_usb_function *f)
{
ccid_cleanup();
}
static int ccid_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return ccid_bind_config(c);
}
static struct android_usb_function ccid_function = {
.name = "ccid",
.init = ccid_function_init,
.cleanup = ccid_function_cleanup,
.bind_config = ccid_function_bind_config,
};
/* Charger */
static int charger_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return charger_bind_config(c);
}
static struct android_usb_function charger_function = {
.name = "charging",
.bind_config = charger_function_bind_config,
};
static int
mtp_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return mtp_setup();
}
static void mtp_function_cleanup(struct android_usb_function *f)
{
mtp_cleanup();
}
static int
mtp_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return mtp_bind_config(c, false);
}
static int
ptp_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
/* nothing to do - initialization is handled by mtp_function_init */
return 0;
}
static void ptp_function_cleanup(struct android_usb_function *f)
{
/* nothing to do - cleanup is handled by mtp_function_cleanup */
}
static int
ptp_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return mtp_bind_config(c, true);
}
static int mtp_function_ctrlrequest(struct android_usb_function *f,
struct usb_composite_dev *cdev,
const struct usb_ctrlrequest *c)
{
return mtp_ctrlrequest(cdev, c);
}
static struct android_usb_function mtp_function = {
.name = "mtp",
.init = mtp_function_init,
.cleanup = mtp_function_cleanup,
.bind_config = mtp_function_bind_config,
.ctrlrequest = mtp_function_ctrlrequest,
};
/* PTP function is same as MTP with slightly different interface descriptor */
static struct android_usb_function ptp_function = {
.name = "ptp",
.init = ptp_function_init,
.cleanup = ptp_function_cleanup,
.bind_config = ptp_function_bind_config,
};
/* rndis transport string */
static char rndis_transports[MAX_XPORT_STR_LEN];
struct rndis_function_config {
u8 ethaddr[ETH_ALEN];
u32 vendorID;
u8 max_pkt_per_xfer;
u8 pkt_alignment_factor;
char manufacturer[256];
/* "Wireless" RNDIS; auto-detected by Windows */
bool wceis;
struct eth_dev *dev;
};
static int
rndis_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
f->config = kzalloc(sizeof(struct rndis_function_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return 0;
}
static void rndis_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
f->config = NULL;
}
static int rndis_qc_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
f->config = kzalloc(sizeof(struct rndis_function_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return rndis_qc_init();
}
static void rndis_qc_function_cleanup(struct android_usb_function *f)
{
rndis_qc_cleanup();
kfree(f->config);
}
static int
rndis_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int ret;
struct eth_dev *dev;
struct rndis_function_config *rndis = f->config;
if (!rndis) {
pr_err("%s: rndis_pdata\n", __func__);
return -1;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
rndis->ethaddr[0], rndis->ethaddr[1], rndis->ethaddr[2],
rndis->ethaddr[3], rndis->ethaddr[4], rndis->ethaddr[5]);
if (rndis->ethaddr[0])
dev = gether_setup_name(c->cdev->gadget, NULL, "rndis");
else
dev = gether_setup_name(c->cdev->gadget, rndis->ethaddr,
"rndis");
if (IS_ERR(dev)) {
ret = PTR_ERR(dev);
pr_err("%s: gether_setup failed\n", __func__);
return ret;
}
rndis->dev = dev;
if (rndis->wceis) {
/* "Wireless" RNDIS; auto-detected by Windows */
rndis_iad_descriptor.bFunctionClass =
USB_CLASS_WIRELESS_CONTROLLER;
rndis_iad_descriptor.bFunctionSubClass = 0x01;
rndis_iad_descriptor.bFunctionProtocol = 0x03;
rndis_control_intf.bInterfaceClass =
USB_CLASS_WIRELESS_CONTROLLER;
rndis_control_intf.bInterfaceSubClass = 0x01;
rndis_control_intf.bInterfaceProtocol = 0x03;
}
return rndis_bind_config_vendor(c, rndis->ethaddr, rndis->vendorID,
rndis->manufacturer, rndis->dev);
}
static int rndis_qc_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int ret;
char *trans;
struct rndis_function_config *rndis = f->config;
if (!rndis) {
pr_err("%s: rndis_pdata\n", __func__);
return -EINVAL;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
rndis->ethaddr[0], rndis->ethaddr[1], rndis->ethaddr[2],
rndis->ethaddr[3], rndis->ethaddr[4], rndis->ethaddr[5]);
pr_debug("%s: rndis_transport is %s", __func__, rndis_transports);
trans = strim(rndis_transports);
if (strcmp("BAM2BAM_IPA", trans)) {
ret = gether_qc_setup_name(c->cdev->gadget,
rndis->ethaddr, "rndis");
if (ret) {
pr_err("%s: gether_setup failed\n", __func__);
return ret;
}
}
if (rndis->wceis) {
/* "Wireless" RNDIS; auto-detected by Windows */
rndis_qc_iad_descriptor.bFunctionClass =
USB_CLASS_WIRELESS_CONTROLLER;
rndis_qc_iad_descriptor.bFunctionSubClass = 0x01;
rndis_qc_iad_descriptor.bFunctionProtocol = 0x03;
rndis_qc_control_intf.bInterfaceClass =
USB_CLASS_WIRELESS_CONTROLLER;
rndis_qc_control_intf.bInterfaceSubClass = 0x01;
rndis_qc_control_intf.bInterfaceProtocol = 0x03;
}
return rndis_qc_bind_config_vendor(c, rndis->ethaddr, rndis->vendorID,
rndis->manufacturer, rndis->max_pkt_per_xfer,
rndis->pkt_alignment_factor, trans);
}
static void rndis_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct rndis_function_config *rndis = f->config;
gether_cleanup(rndis->dev);
}
static void rndis_qc_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
char *trans = strim(rndis_transports);
if (strcmp("BAM2BAM_IPA", trans))
gether_qc_cleanup_name("rndis0");
}
static ssize_t rndis_manufacturer_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%s\n", config->manufacturer);
}
static ssize_t rndis_manufacturer_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
if (size >= sizeof(config->manufacturer))
return -EINVAL;
if (sscanf(buf, "%255s", config->manufacturer) == 1)
return size;
return -1;
}
static DEVICE_ATTR(manufacturer, S_IRUGO | S_IWUSR, rndis_manufacturer_show,
rndis_manufacturer_store);
static ssize_t rndis_wceis_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%d\n", config->wceis);
}
static ssize_t rndis_wceis_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
int value;
if (sscanf(buf, "%d", &value) == 1) {
config->wceis = value;
return size;
}
return -EINVAL;
}
static DEVICE_ATTR(wceis, S_IRUGO | S_IWUSR, rndis_wceis_show,
rndis_wceis_store);
static ssize_t rndis_ethaddr_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *rndis = f->config;
return snprintf(buf, PAGE_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x\n",
rndis->ethaddr[0], rndis->ethaddr[1], rndis->ethaddr[2],
rndis->ethaddr[3], rndis->ethaddr[4], rndis->ethaddr[5]);
}
static ssize_t rndis_ethaddr_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *rndis = f->config;
if (sscanf(buf, "%02x:%02x:%02x:%02x:%02x:%02x\n",
(int *)&rndis->ethaddr[0], (int *)&rndis->ethaddr[1],
(int *)&rndis->ethaddr[2], (int *)&rndis->ethaddr[3],
(int *)&rndis->ethaddr[4], (int *)&rndis->ethaddr[5]) == 6)
return size;
return -EINVAL;
}
static DEVICE_ATTR(ethaddr, S_IRUGO | S_IWUSR, rndis_ethaddr_show,
rndis_ethaddr_store);
static ssize_t rndis_vendorID_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%04x\n", config->vendorID);
}
static ssize_t rndis_vendorID_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
int value;
if (sscanf(buf, "%04x", &value) == 1) {
config->vendorID = value;
return size;
}
return -EINVAL;
}
static DEVICE_ATTR(vendorID, S_IRUGO | S_IWUSR, rndis_vendorID_show,
rndis_vendorID_store);
static ssize_t rndis_max_pkt_per_xfer_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%d\n", config->max_pkt_per_xfer);
}
static ssize_t rndis_max_pkt_per_xfer_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
int value;
if (sscanf(buf, "%d", &value) == 1) {
config->max_pkt_per_xfer = value;
return size;
}
return -EINVAL;
}
static DEVICE_ATTR(max_pkt_per_xfer, S_IRUGO | S_IWUSR,
rndis_max_pkt_per_xfer_show,
rndis_max_pkt_per_xfer_store);
static ssize_t rndis_transports_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", rndis_transports);
}
static ssize_t rndis_transports_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
strlcpy(rndis_transports, buf, sizeof(rndis_transports));
return size;
}
static DEVICE_ATTR(rndis_transports, S_IRUGO | S_IWUSR, rndis_transports_show,
rndis_transports_store);
static ssize_t rndis_rx_trigger_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
int value;
if (sscanf(buf, "%d", &value) == 1) {
rndis_rx_trigger();
return size;
}
return -EINVAL;
}
static DEVICE_ATTR(rx_trigger, S_IWUSR, NULL,
rndis_rx_trigger_store);
static ssize_t rndis_pkt_alignment_factor_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%d\n", config->pkt_alignment_factor);
}
static ssize_t rndis_pkt_alignment_factor_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
int value;
if (sscanf(buf, "%d", &value) == 1) {
config->pkt_alignment_factor = value;
return size;
}
return -EINVAL;
}
static DEVICE_ATTR(pkt_alignment_factor, S_IRUGO | S_IWUSR,
rndis_pkt_alignment_factor_show,
rndis_pkt_alignment_factor_store);
static struct device_attribute *rndis_function_attributes[] = {
&dev_attr_manufacturer,
&dev_attr_wceis,
&dev_attr_ethaddr,
&dev_attr_vendorID,
&dev_attr_max_pkt_per_xfer,
&dev_attr_rndis_transports,
&dev_attr_rx_trigger,
&dev_attr_pkt_alignment_factor,
NULL
};
static struct android_usb_function rndis_function = {
.name = "rndis",
.init = rndis_function_init,
.cleanup = rndis_function_cleanup,
.bind_config = rndis_function_bind_config,
.unbind_config = rndis_function_unbind_config,
.attributes = rndis_function_attributes,
};
static struct android_usb_function rndis_qc_function = {
.name = "rndis_qc",
.init = rndis_qc_function_init,
.cleanup = rndis_qc_function_cleanup,
.bind_config = rndis_qc_function_bind_config,
.unbind_config = rndis_qc_function_unbind_config,
.attributes = rndis_function_attributes,
};
static int ecm_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int ret;
struct eth_dev *dev;
struct ecm_function_config *ecm = f->config;
if (!ecm) {
pr_err("%s: ecm_pdata\n", __func__);
return -EINVAL;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
ecm->ethaddr[0], ecm->ethaddr[1], ecm->ethaddr[2],
ecm->ethaddr[3], ecm->ethaddr[4], ecm->ethaddr[5]);
dev = gether_setup_name(c->cdev->gadget, ecm->ethaddr, "ecm");
if (dev) {
ret = PTR_ERR(dev);
pr_err("%s: gether_setup failed\n", __func__);
return ret;
}
ecm->dev = dev;
ret = ecm_bind_config(c, ecm->ethaddr, dev);
if (ret) {
pr_err("%s: ecm_bind_config failed\n", __func__);
gether_cleanup(dev);
}
return ret;
}
static void ecm_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct ecm_function_config *ecm = f->config;
gether_cleanup(ecm->dev);
}
static struct android_usb_function ecm_function = {
.name = "ecm",
.init = ecm_function_init,
.cleanup = ecm_function_cleanup,
.bind_config = ecm_function_bind_config,
.unbind_config = ecm_function_unbind_config,
.attributes = ecm_function_attributes,
};
#define MAX_LUN_STR_LEN 25
static char lun_info[MAX_LUN_STR_LEN] = {'\0'};
struct mass_storage_function_config {
struct fsg_config fsg;
struct fsg_common *common;
};
#define MAX_LUN_NAME 8
static int mass_storage_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
struct android_dev *dev = cdev_to_android_dev(cdev);
struct mass_storage_function_config *config;
struct fsg_common *common;
int err;
int i, n;
char name[FSG_MAX_LUNS][MAX_LUN_NAME];
u8 uicc_nluns = dev->pdata ? dev->pdata->uicc_nluns : 0;
config = kzalloc(sizeof(struct mass_storage_function_config),
GFP_KERNEL);
if (!config) {
pr_err("Memory allocation failed.\n");
return -ENOMEM;
}
config->fsg.nluns = 1;
snprintf(name[0], MAX_LUN_NAME, "lun");
config->fsg.luns[0].removable = 1;
if (dev->pdata && dev->pdata->cdrom) {
config->fsg.luns[config->fsg.nluns].cdrom = 1;
config->fsg.luns[config->fsg.nluns].ro = 1;
config->fsg.luns[config->fsg.nluns].removable = 0;
snprintf(name[config->fsg.nluns], MAX_LUN_NAME, "rom");
config->fsg.nluns++;
}
if (uicc_nluns > FSG_MAX_LUNS - config->fsg.nluns) {
uicc_nluns = FSG_MAX_LUNS - config->fsg.nluns;
pr_debug("limiting uicc luns to %d\n", uicc_nluns);
}
for (i = 0; i < uicc_nluns; i++) {
n = config->fsg.nluns;
snprintf(name[n], MAX_LUN_NAME, "uicc%d", i);
config->fsg.luns[n].removable = 1;
config->fsg.nluns++;
}
common = fsg_common_init(NULL, cdev, &config->fsg);
if (IS_ERR(common)) {
kfree(config);
return PTR_ERR(common);
}
for (i = 0; i < config->fsg.nluns; i++) {
err = sysfs_create_link(&f->dev->kobj,
&common->luns[i].dev.kobj,
name[i]);
if (err)
goto error;
}
config->common = common;
f->config = config;
return 0;
error:
for (; i > 0; i--)
sysfs_remove_link(&f->dev->kobj, name[i-1]);
fsg_common_release(&common->ref);
kfree(config);
return err;
}
static int mass_storage_lun_init(struct android_usb_function *f,
char *lun_info)
{
struct mass_storage_function_config *config = f->config;
bool inc_lun = true;
int i = config->fsg.nluns, index, length;
static int number_of_luns;
length = strlen(lun_info);
if (!length) {
pr_err("LUN_INFO is null.\n");
return -EINVAL;
}
index = i + number_of_luns;
if (index >= FSG_MAX_LUNS) {
pr_err("Number of LUNs exceed the limit.\n");
return -EINVAL;
}
if (!strcmp(lun_info, "disk")) {
config->fsg.luns[index].removable = 1;
} else if (!strcmp(lun_info, "rom")) {
config->fsg.luns[index].cdrom = 1;
config->fsg.luns[index].removable = 0;
config->fsg.luns[index].ro = 1;
} else {
pr_err("Invalid LUN info.\n");
inc_lun = false;
return -EINVAL;
}
if (inc_lun)
number_of_luns++;
pr_debug("number_of_luns:%d\n", number_of_luns);
return number_of_luns;
}
static void mass_storage_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
f->config = NULL;
}
static void mass_storage_function_enable(struct android_usb_function *f)
{
struct usb_composite_dev *cdev = f->android_dev->cdev;
struct mass_storage_function_config *config = f->config;
struct fsg_common *common = config->common;
char *lun_type;
int i, err, prev_nluns;
char buf[MAX_LUN_STR_LEN], *b;
int number_of_luns = 0;
char buf1[5];
char *lun_name = buf1;
static int msc_initialized;
if (msc_initialized)
return;
prev_nluns = config->fsg.nluns;
if (lun_info[0] != '\0') {
strlcpy(buf, lun_info, sizeof(buf));
b = strim(buf);
while (b) {
lun_type = strsep(&b, ",");
if (lun_type)
number_of_luns =
mass_storage_lun_init(f, lun_type);
if (number_of_luns <= 0)
return;
}
} else {
pr_debug("No extra msc lun required.\n");
return;
}
err = fsg_add_lun(common, cdev, &config->fsg, number_of_luns);
if (err) {
pr_err("Failed adding LUN.\n");
return;
}
pr_debug("fsg.nluns:%d\n", config->fsg.nluns);
for (i = prev_nluns; i < config->fsg.nluns; i++) {
snprintf(lun_name, sizeof(buf), "lun%d", (i-prev_nluns));
pr_debug("sysfs: LUN name:%s\n", lun_name);
err = sysfs_create_link(&f->dev->kobj,
&common->luns[i].dev.kobj, lun_name);
if (err)
pr_err("sysfs file creation failed: lun%d err:%d\n",
(i-prev_nluns), err);
}
msc_initialized = 1;
}
static int mass_storage_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct mass_storage_function_config *config = f->config;
int ret;
ret = fsg_bind_config(c->cdev, c, config->common);
if (ret)
pr_err("fsg_bind_config failed. ret:%x\n", ret);
return ret;
}
static ssize_t mass_storage_inquiry_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct mass_storage_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%s\n", config->common->inquiry_string);
}
static ssize_t mass_storage_inquiry_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct mass_storage_function_config *config = f->config;
if (size >= sizeof(config->common->inquiry_string))
return -EINVAL;
if (sscanf(buf, "%28s", config->common->inquiry_string) != 1)
return -EINVAL;
return size;
}
static DEVICE_ATTR(inquiry_string, S_IRUGO | S_IWUSR,
mass_storage_inquiry_show,
mass_storage_inquiry_store);
static ssize_t mass_storage_lun_info_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", lun_info);
}
static ssize_t mass_storage_lun_info_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
strlcpy(lun_info, buf, sizeof(lun_info));
return size;
}
static DEVICE_ATTR(luns, S_IRUGO | S_IWUSR,
mass_storage_lun_info_show,
mass_storage_lun_info_store);
static struct device_attribute *mass_storage_function_attributes[] = {
&dev_attr_inquiry_string,
&dev_attr_luns,
NULL
};
static struct android_usb_function mass_storage_function = {
.name = "mass_storage",
.init = mass_storage_function_init,
.cleanup = mass_storage_function_cleanup,
.bind_config = mass_storage_function_bind_config,
.attributes = mass_storage_function_attributes,
.enable = mass_storage_function_enable,
};
static int accessory_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return acc_setup();
}
static void accessory_function_cleanup(struct android_usb_function *f)
{
acc_cleanup();
}
static int accessory_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return acc_bind_config(c);
}
static int accessory_function_ctrlrequest(struct android_usb_function *f,
struct usb_composite_dev *cdev,
const struct usb_ctrlrequest *c)
{
return acc_ctrlrequest(cdev, c);
}
static struct android_usb_function accessory_function = {
.name = "accessory",
.init = accessory_function_init,
.cleanup = accessory_function_cleanup,
.bind_config = accessory_function_bind_config,
.ctrlrequest = accessory_function_ctrlrequest,
};
#ifdef CONFIG_SND_PCM
static int audio_source_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
struct audio_source_config *config;
config = kzalloc(sizeof(struct audio_source_config), GFP_KERNEL);
if (!config)
return -ENOMEM;
config->card = -1;
config->device = -1;
f->config = config;
return 0;
}
static void audio_source_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
}
static int audio_source_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct audio_source_config *config = f->config;
return audio_source_bind_config(c, config);
}
static void audio_source_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct audio_source_config *config = f->config;
config->card = -1;
config->device = -1;
}
static ssize_t audio_source_pcm_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct audio_source_config *config = f->config;
/* print PCM card and device numbers */
return sprintf(buf, "%d %d\n", config->card, config->device);
}
static DEVICE_ATTR(pcm, S_IRUGO, audio_source_pcm_show, NULL);
static struct device_attribute *audio_source_function_attributes[] = {
&dev_attr_pcm,
NULL
};
static struct android_usb_function audio_source_function = {
.name = "audio_source",
.init = audio_source_function_init,
.cleanup = audio_source_function_cleanup,
.bind_config = audio_source_function_bind_config,
.unbind_config = audio_source_function_unbind_config,
.attributes = audio_source_function_attributes,
};
#endif
static int android_uasp_connect_cb(bool connect)
{
/*
* TODO
* We may have to disable gadget till UASP configfs nodes
* are configured which includes mapping LUN with the
* backing file. It is a fundamental difference between
* f_mass_storage and f_tcp. That means UASP can not be
* in default composition.
*
* For now, assume that UASP configfs nodes are configured
* before enabling android gadget. Or cable should be
* reconnected after mapping the LUN.
*
* Also consider making UASP to respond to Host requests when
* Lun is not mapped.
*/
pr_debug("UASP %s\n", connect ? "connect" : "disconnect");
return 0;
}
static int uasp_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return f_tcm_init(&android_uasp_connect_cb);
}
static void uasp_function_cleanup(struct android_usb_function *f)
{
f_tcm_exit();
}
static int uasp_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return tcm_bind_config(c);
}
static struct android_usb_function uasp_function = {
.name = "uasp",
.init = uasp_function_init,
.cleanup = uasp_function_cleanup,
.bind_config = uasp_function_bind_config,
};
static struct android_usb_function *supported_functions[] = {
&ffs_function,
&mbim_function,
&ecm_qc_function,
#ifdef CONFIG_SND_PCM
&audio_function,
#endif
&rmnet_smd_function,
&rmnet_function,
&gps_function,
&diag_function,
&qdss_function,
&serial_function,
&ccid_function,
&acm_function,
&mtp_function,
&ptp_function,
&rndis_function,
&rndis_qc_function,
&ecm_function,
&ncm_function,
&mass_storage_function,
&accessory_function,
#ifdef CONFIG_SND_PCM
&audio_source_function,
#endif
&uasp_function,
&charger_function,
NULL
};
static void android_cleanup_functions(struct android_usb_function **functions)
{
struct android_usb_function *f;
struct device_attribute **attrs;
struct device_attribute *attr;
while (*functions) {
f = *functions++;
if (f->dev) {
device_destroy(android_class, f->dev->devt);
kfree(f->dev_name);
} else
continue;
if (f->cleanup)
f->cleanup(f);
attrs = f->attributes;
if (attrs) {
while ((attr = *attrs++))
device_remove_file(f->dev, attr);
}
}
}
static int android_init_functions(struct android_usb_function **functions,
struct usb_composite_dev *cdev)
{
struct android_dev *dev = cdev_to_android_dev(cdev);
struct android_usb_function *f;
struct device_attribute **attrs;
struct device_attribute *attr;
int err = 0;
int index = 1; /* index 0 is for android0 device */
for (; (f = *functions++); index++) {
f->dev_name = kasprintf(GFP_KERNEL, "f_%s", f->name);
f->android_dev = NULL;
if (!f->dev_name) {
err = -ENOMEM;
goto err_out;
}
f->dev = device_create(android_class, dev->dev,
MKDEV(0, index), f, f->dev_name);
if (IS_ERR(f->dev)) {
pr_err("%s: Failed to create dev %s", __func__,
f->dev_name);
err = PTR_ERR(f->dev);
f->dev = NULL;
goto err_create;
}
if (f->init) {
err = f->init(f, cdev);
if (err) {
pr_err("%s: Failed to init %s", __func__,
f->name);
goto err_init;
}
}
attrs = f->attributes;
if (attrs) {
while ((attr = *attrs++) && !err)
err = device_create_file(f->dev, attr);
}
if (err) {
pr_err("%s: Failed to create function %s attributes",
__func__, f->name);
goto err_attrs;
}
}
return 0;
err_attrs:
for (attr = *(attrs -= 2); attrs != f->attributes; attr = *(attrs--))
device_remove_file(f->dev, attr);
if (f->cleanup)
f->cleanup(f);
err_init:
device_destroy(android_class, f->dev->devt);
err_create:
f->dev = NULL;
kfree(f->dev_name);
err_out:
android_cleanup_functions(dev->functions);
return err;
}
static int
android_bind_enabled_functions(struct android_dev *dev,
struct usb_configuration *c)
{
struct android_usb_function_holder *f_holder;
struct android_configuration *conf =
container_of(c, struct android_configuration, usb_config);
int ret;
list_for_each_entry(f_holder, &conf->enabled_functions, enabled_list) {
ret = f_holder->f->bind_config(f_holder->f, c);
if (ret) {
pr_err("%s: %s failed\n", __func__, f_holder->f->name);
while (!list_empty(&c->functions)) {
struct usb_function *f;
f = list_first_entry(&c->functions,
struct usb_function, list);
list_del(&f->list);
if (f->unbind)
f->unbind(c, f);
}
if (c->unbind)
c->unbind(c);
return ret;
}
}
return 0;
}
static void
android_unbind_enabled_functions(struct android_dev *dev,
struct usb_configuration *c)
{
struct android_usb_function_holder *f_holder;
struct android_configuration *conf =
container_of(c, struct android_configuration, usb_config);
list_for_each_entry(f_holder, &conf->enabled_functions, enabled_list) {
if (f_holder->f->unbind_config)
f_holder->f->unbind_config(f_holder->f, c);
}
}
static inline void check_streaming_func(struct usb_gadget *gadget,
struct android_usb_platform_data *pdata,
char *name)
{
int i;
for (i = 0; i < pdata->streaming_func_count; i++) {
if (!strcmp(name, pdata->streaming_func[i])) {
pr_debug("set streaming_enabled to true\n");
gadget->streaming_enabled = true;
break;
}
}
}
static int android_enable_function(struct android_dev *dev,
struct android_configuration *conf,
char *name)
{
struct android_usb_function **functions = dev->functions;
struct android_usb_function *f;
struct android_usb_function_holder *f_holder;
struct android_usb_platform_data *pdata = dev->pdata;
struct usb_gadget *gadget = dev->cdev->gadget;
while ((f = *functions++)) {
if (!strcmp(name, f->name)) {
if (f->android_dev && f->android_dev != dev)
pr_err("%s is enabled in other device\n",
f->name);
else {
f_holder = kzalloc(sizeof(*f_holder),
GFP_KERNEL);
if (!f_holder) {
pr_err("Failed to alloc f_holder\n");
return -ENOMEM;
}
f->android_dev = dev;
f_holder->f = f;
list_add_tail(&f_holder->enabled_list,
&conf->enabled_functions);
pr_debug("func:%s is enabled.\n", f->name);
/*
* compare enable function with streaming func
* list and based on the same request streaming.
*/
check_streaming_func(gadget, pdata, f->name);
return 0;
}
}
}
return -EINVAL;
}
/*-------------------------------------------------------------------------*/
/* /sys/class/android_usb/android%d/ interface */
static ssize_t remote_wakeup_show(struct device *pdev,
struct device_attribute *attr, char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct android_configuration *conf;
/*
* Show the wakeup attribute of the first configuration,
* since all configurations have the same wakeup attribute
*/
if (dev->configs_num == 0)
return 0;
conf = list_entry(dev->configs.next,
struct android_configuration,
list_item);
return snprintf(buf, PAGE_SIZE, "%d\n",
!!(conf->usb_config.bmAttributes &
USB_CONFIG_ATT_WAKEUP));
}
static ssize_t remote_wakeup_store(struct device *pdev,
struct device_attribute *attr, const char *buff, size_t size)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct android_configuration *conf;
int enable = 0;
sscanf(buff, "%d", &enable);
pr_debug("android_usb: %s remote wakeup\n",
enable ? "enabling" : "disabling");
list_for_each_entry(conf, &dev->configs, list_item)
if (enable)
conf->usb_config.bmAttributes |=
USB_CONFIG_ATT_WAKEUP;
else
conf->usb_config.bmAttributes &=
~USB_CONFIG_ATT_WAKEUP;
return size;
}
static ssize_t
functions_show(struct device *pdev, struct device_attribute *attr, char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct android_configuration *conf;
struct android_usb_function_holder *f_holder;
char *buff = buf;
mutex_lock(&dev->mutex);
list_for_each_entry(conf, &dev->configs, list_item) {
if (buff != buf)
*(buff-1) = ':';
list_for_each_entry(f_holder, &conf->enabled_functions,
enabled_list)
buff += snprintf(buff, PAGE_SIZE, "%s,",
f_holder->f->name);
}
mutex_unlock(&dev->mutex);
if (buff != buf)
*(buff-1) = '\n';
return buff - buf;
}
static ssize_t
functions_store(struct device *pdev, struct device_attribute *attr,
const char *buff, size_t size)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct list_head *curr_conf = &dev->configs;
struct android_configuration *conf;
char *conf_str;
struct android_usb_function_holder *f_holder;
char *name;
char buf[256], *b;
char aliases[256], *a;
int err;
int is_ffs;
int ffs_enabled = 0;
mutex_lock(&dev->mutex);
if (dev->enabled) {
mutex_unlock(&dev->mutex);
return -EBUSY;
}
/* Clear previous enabled list */
list_for_each_entry(conf, &dev->configs, list_item) {
while (conf->enabled_functions.next !=
&conf->enabled_functions) {
f_holder = list_entry(conf->enabled_functions.next,
typeof(*f_holder),
enabled_list);
f_holder->f->android_dev = NULL;
list_del(&f_holder->enabled_list);
kfree(f_holder);
}
INIT_LIST_HEAD(&conf->enabled_functions);
}
strlcpy(buf, buff, sizeof(buf));
b = strim(buf);
while (b) {
conf_str = strsep(&b, ":");
if (!conf_str)
continue;
/* If the next not equal to the head, take it */
if (curr_conf->next != &dev->configs)
conf = list_entry(curr_conf->next,
struct android_configuration,
list_item);
else
conf = alloc_android_config(dev);
curr_conf = curr_conf->next;
while (conf_str) {
name = strsep(&conf_str, ",");
is_ffs = 0;
strlcpy(aliases, dev->ffs_aliases, sizeof(aliases));
a = aliases;
while (a) {
char *alias = strsep(&a, ",");
if (alias && !strcmp(name, alias)) {
is_ffs = 1;
break;
}
}
if (is_ffs) {
if (ffs_enabled)
continue;
err = android_enable_function(dev, conf, "ffs");
if (err)
pr_err("android_usb: Cannot enable ffs (%d)",
err);
else
ffs_enabled = 1;
continue;
}
err = android_enable_function(dev, conf, name);
if (err)
pr_err("android_usb: Cannot enable '%s' (%d)",
name, err);
}
}
/* Free uneeded configurations if exists */
while (curr_conf->next != &dev->configs) {
conf = list_entry(curr_conf->next,
struct android_configuration, list_item);
free_android_config(dev, conf);
}
mutex_unlock(&dev->mutex);
return size;
}
static ssize_t enable_show(struct device *pdev, struct device_attribute *attr,
char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
return snprintf(buf, PAGE_SIZE, "%d\n", dev->enabled);
}
static ssize_t enable_store(struct device *pdev, struct device_attribute *attr,
const char *buff, size_t size)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct usb_composite_dev *cdev = dev->cdev;
struct android_usb_function_holder *f_holder;
struct android_configuration *conf;
int enabled = 0;
bool audio_enabled = false;
static DEFINE_RATELIMIT_STATE(rl, 10*HZ, 1);
int err = 0;
if (!cdev)
return -ENODEV;
mutex_lock(&dev->mutex);
sscanf(buff, "%d", &enabled);
if (enabled && !dev->enabled) {
/*
* Update values in composite driver's copy of
* device descriptor.
*/
cdev->desc.idVendor = device_desc.idVendor;
cdev->desc.idProduct = device_desc.idProduct;
cdev->desc.bcdDevice = device_desc.bcdDevice;
cdev->desc.bDeviceClass = device_desc.bDeviceClass;
cdev->desc.bDeviceSubClass = device_desc.bDeviceSubClass;
cdev->desc.bDeviceProtocol = device_desc.bDeviceProtocol;
/* Audio dock accessory is unable to enumerate device if
* pull-up is enabled immediately. The enumeration is
* reliable with 100 msec delay.
*/
list_for_each_entry(conf, &dev->configs, list_item)
list_for_each_entry(f_holder, &conf->enabled_functions,
enabled_list) {
if (f_holder->f->enable)
f_holder->f->enable(f_holder->f);
if (!strncmp(f_holder->f->name,
"audio_source", 12))
audio_enabled = true;
}
if (audio_enabled)
msleep(100);
err = android_enable(dev);
if (err < 0) {
pr_err("%s: android_enable failed\n", __func__);
dev->connected = 0;
dev->enabled = false;
mutex_unlock(&dev->mutex);
return size;
}
dev->enabled = true;
} else if (!enabled && dev->enabled) {
android_disable(dev);
list_for_each_entry(conf, &dev->configs, list_item)
list_for_each_entry(f_holder, &conf->enabled_functions,
enabled_list) {
if (f_holder->f->disable)
f_holder->f->disable(f_holder->f);
}
dev->enabled = false;
} else if (__ratelimit(&rl)) {
pr_err("android_usb: already %s\n",
dev->enabled ? "enabled" : "disabled");
}
mutex_unlock(&dev->mutex);
return size;
}
static ssize_t pm_qos_show(struct device *pdev,
struct device_attribute *attr, char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
return snprintf(buf, PAGE_SIZE, "%s\n", dev->pm_qos);
}
static ssize_t pm_qos_store(struct device *pdev,
struct device_attribute *attr,
const char *buff, size_t size)
{
struct android_dev *dev = dev_get_drvdata(pdev);
strlcpy(dev->pm_qos, buff, sizeof(dev->pm_qos));
return size;
}
static ssize_t pm_qos_state_show(struct device *pdev,
struct device_attribute *attr, char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
return snprintf(buf, PAGE_SIZE, "%s\n",
pm_qos_to_string(dev->curr_pm_qos_state));
}
static ssize_t state_show(struct device *pdev, struct device_attribute *attr,
char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct usb_composite_dev *cdev = dev->cdev;
char *state = "DISCONNECTED";
unsigned long flags;
if (!cdev)
goto out;
spin_lock_irqsave(&cdev->lock, flags);
if (cdev->config)
state = "CONFIGURED";
else if (dev->connected)
state = "CONNECTED";
spin_unlock_irqrestore(&cdev->lock, flags);
out:
return snprintf(buf, PAGE_SIZE, "%s\n", state);
}
#define ANDROID_DEV_ATTR(field, format_string) \
static ssize_t \
field ## _show(struct device *pdev, struct device_attribute *attr, \
char *buf) \
{ \
struct android_dev *dev = dev_get_drvdata(pdev); \
\
return snprintf(buf, PAGE_SIZE, \
format_string, dev->field); \
} \
static ssize_t \
field ## _store(struct device *pdev, struct device_attribute *attr, \
const char *buf, size_t size) \
{ \
unsigned value; \
struct android_dev *dev = dev_get_drvdata(pdev); \
\
if (sscanf(buf, format_string, &value) == 1) { \
dev->field = value; \
return size; \
} \
return -EINVAL; \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, field ## _show, field ## _store);
#define DESCRIPTOR_ATTR(field, format_string) \
static ssize_t \
field ## _show(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
return snprintf(buf, PAGE_SIZE, \
format_string, device_desc.field); \
} \
static ssize_t \
field ## _store(struct device *dev, struct device_attribute *attr, \
const char *buf, size_t size) \
{ \
int value; \
if (sscanf(buf, format_string, &value) == 1) { \
device_desc.field = value; \
return size; \
} \
return -1; \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, field ## _show, field ## _store);
#define DESCRIPTOR_STRING_ATTR(field, buffer) \
static ssize_t \
field ## _show(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
return snprintf(buf, PAGE_SIZE, "%s", buffer); \
} \
static ssize_t \
field ## _store(struct device *dev, struct device_attribute *attr, \
const char *buf, size_t size) \
{ \
if (size >= sizeof(buffer)) \
return -EINVAL; \
strlcpy(buffer, buf, sizeof(buffer)); \
strim(buffer); \
return size; \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, field ## _show, field ## _store);
DESCRIPTOR_ATTR(idVendor, "%04x\n")
DESCRIPTOR_ATTR(idProduct, "%04x\n")
DESCRIPTOR_ATTR(bcdDevice, "%04x\n")
DESCRIPTOR_ATTR(bDeviceClass, "%d\n")
DESCRIPTOR_ATTR(bDeviceSubClass, "%d\n")
DESCRIPTOR_ATTR(bDeviceProtocol, "%d\n")
DESCRIPTOR_STRING_ATTR(iManufacturer, manufacturer_string)
DESCRIPTOR_STRING_ATTR(iProduct, product_string)
DESCRIPTOR_STRING_ATTR(iSerial, serial_string)
static DEVICE_ATTR(functions, S_IRUGO | S_IWUSR, functions_show,
functions_store);
static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR, enable_show, enable_store);
static DEVICE_ATTR(pm_qos, S_IRUGO | S_IWUSR, pm_qos_show, pm_qos_store);
static DEVICE_ATTR(pm_qos_state, S_IRUGO, pm_qos_state_show, NULL);
ANDROID_DEV_ATTR(up_pm_qos_sample_sec, "%u\n");
ANDROID_DEV_ATTR(down_pm_qos_sample_sec, "%u\n");
ANDROID_DEV_ATTR(up_pm_qos_threshold, "%u\n");
ANDROID_DEV_ATTR(down_pm_qos_threshold, "%u\n");
ANDROID_DEV_ATTR(idle_pc_rpm_no_int_secs, "%u\n");
static DEVICE_ATTR(state, S_IRUGO, state_show, NULL);
static DEVICE_ATTR(remote_wakeup, S_IRUGO | S_IWUSR,
remote_wakeup_show, remote_wakeup_store);
static struct device_attribute *android_usb_attributes[] = {
&dev_attr_idVendor,
&dev_attr_idProduct,
&dev_attr_bcdDevice,
&dev_attr_bDeviceClass,
&dev_attr_bDeviceSubClass,
&dev_attr_bDeviceProtocol,
&dev_attr_iManufacturer,
&dev_attr_iProduct,
&dev_attr_iSerial,
&dev_attr_functions,
&dev_attr_enable,
&dev_attr_pm_qos,
&dev_attr_up_pm_qos_sample_sec,
&dev_attr_down_pm_qos_sample_sec,
&dev_attr_up_pm_qos_threshold,
&dev_attr_down_pm_qos_threshold,
&dev_attr_idle_pc_rpm_no_int_secs,
&dev_attr_pm_qos_state,
&dev_attr_state,
&dev_attr_remote_wakeup,
NULL
};
/*-------------------------------------------------------------------------*/
/* Composite driver */
static int android_bind_config(struct usb_configuration *c)
{
struct android_dev *dev = cdev_to_android_dev(c->cdev);
int ret = 0;
ret = android_bind_enabled_functions(dev, c);
if (ret)
return ret;
return 0;
}
static void android_unbind_config(struct usb_configuration *c)
{
struct android_dev *dev = cdev_to_android_dev(c->cdev);
if (c->cdev->gadget->streaming_enabled) {
c->cdev->gadget->streaming_enabled = false;
pr_debug("setting streaming_enabled to false.\n");
}
android_unbind_enabled_functions(dev, c);
}
static int android_bind(struct usb_composite_dev *cdev)
{
struct android_dev *dev;
struct usb_gadget *gadget = cdev->gadget;
struct android_configuration *conf;
int id, ret;
/* Bind to the last android_dev that was probed */
dev = list_entry(android_dev_list.prev, struct android_dev, list_item);
dev->cdev = cdev;
/* Save the default handler */
dev->setup_complete = cdev->req->complete;
/*
* Start disconnected. Userspace will connect the gadget once
* it is done configuring the functions.
*/
usb_gadget_disconnect(gadget);
/* Init the supported functions only once, on the first android_dev */
if (android_dev_count == 1) {
ret = android_init_functions(dev->functions, cdev);
if (ret)
return ret;
}
/* Allocate string descriptor numbers ... note that string
* contents can be overridden by the composite_dev glue.
*/
id = usb_string_id(cdev);
if (id < 0)
return id;
strings_dev[STRING_MANUFACTURER_IDX].id = id;
device_desc.iManufacturer = id;
id = usb_string_id(cdev);
if (id < 0)
return id;
strings_dev[STRING_PRODUCT_IDX].id = id;
device_desc.iProduct = id;
/* Default strings - should be updated by userspace */
strlcpy(manufacturer_string, "Android",
sizeof(manufacturer_string) - 1);
strlcpy(product_string, "Android", sizeof(product_string) - 1);
strlcpy(serial_string, "0123456789ABCDEF", sizeof(serial_string) - 1);
id = usb_string_id(cdev);
if (id < 0)
return id;
strings_dev[STRING_SERIAL_IDX].id = id;
device_desc.iSerialNumber = id;
if (gadget_is_otg(cdev->gadget))
list_for_each_entry(conf, &dev->configs, list_item)
conf->usb_config.descriptors = otg_desc;
return 0;
}
static int android_usb_unbind(struct usb_composite_dev *cdev)
{
struct android_dev *dev = cdev_to_android_dev(cdev);
manufacturer_string[0] = '\0';
product_string[0] = '\0';
serial_string[0] = '0';
cancel_work_sync(&dev->work);
cancel_delayed_work_sync(&dev->pm_qos_work);
android_cleanup_functions(dev->functions);
return 0;
}
/* HACK: android needs to override setup for accessory to work */
static int (*composite_setup_func)(struct usb_gadget *gadget, const struct usb_ctrlrequest *c);
static void (*composite_suspend_func)(struct usb_gadget *gadget);
static void (*composite_resume_func)(struct usb_gadget *gadget);
static int
android_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *c)
{
struct usb_composite_dev *cdev = get_gadget_data(gadget);
struct android_dev *dev = cdev_to_android_dev(cdev);
struct usb_request *req = cdev->req;
struct android_usb_function *f;
struct android_usb_function_holder *f_holder;
struct android_configuration *conf;
int value = -EOPNOTSUPP;
unsigned long flags;
bool do_work = false;
req->zero = 0;
req->length = 0;
req->complete = dev->setup_complete;
gadget->ep0->driver_data = cdev;
list_for_each_entry(conf, &dev->configs, list_item)
list_for_each_entry(f_holder,
&conf->enabled_functions,
enabled_list) {
f = f_holder->f;
if (f->ctrlrequest) {
value = f->ctrlrequest(f, cdev, c);
if (value >= 0)
break;
}
}
/* Special case the accessory function.
* It needs to handle control requests before it is enabled.
*/
if (value < 0)
value = acc_ctrlrequest(cdev, c);
if (value < 0)
value = composite_setup_func(gadget, c);
spin_lock_irqsave(&cdev->lock, flags);
if (!dev->connected) {
dev->connected = 1;
do_work = true;
} else if (c->bRequest == USB_REQ_SET_CONFIGURATION &&
cdev->config) {
do_work = true;
}
spin_unlock_irqrestore(&cdev->lock, flags);
if (do_work)
schedule_work(&dev->work);
return value;
}
static void android_disconnect(struct usb_composite_dev *cdev)
{
struct android_dev *dev = cdev_to_android_dev(cdev);
/* accessory HID support can be active while the
accessory function is not actually enabled,
so we need to inform it when we are disconnected.
*/
acc_disconnect();
dev->connected = 0;
schedule_work(&dev->work);
}
static struct usb_composite_driver android_usb_driver = {
.name = "android_usb",
.dev = &device_desc,
.strings = dev_strings,
.bind = android_bind,
.unbind = android_usb_unbind,
.disconnect = android_disconnect,
.max_speed = USB_SPEED_SUPER
};
static void android_suspend(struct usb_gadget *gadget)
{
struct usb_composite_dev *cdev = get_gadget_data(gadget);
struct android_dev *dev = cdev_to_android_dev(cdev);
unsigned long flags;
spin_lock_irqsave(&cdev->lock, flags);
if (!dev->suspended) {
dev->suspended = 1;
schedule_work(&dev->work);
}
spin_unlock_irqrestore(&cdev->lock, flags);
composite_suspend_func(gadget);
}
static void android_resume(struct usb_gadget *gadget)
{
struct usb_composite_dev *cdev = get_gadget_data(gadget);
struct android_dev *dev = cdev_to_android_dev(cdev);
unsigned long flags;
spin_lock_irqsave(&cdev->lock, flags);
if (dev->suspended) {
dev->suspended = 0;
schedule_work(&dev->work);
}
spin_unlock_irqrestore(&cdev->lock, flags);
composite_resume_func(gadget);
}
static int android_create_device(struct android_dev *dev, u8 usb_core_id)
{
struct device_attribute **attrs = android_usb_attributes;
struct device_attribute *attr;
char device_node_name[ANDROID_DEVICE_NODE_NAME_LENGTH];
int err;
/*
* The primary usb core should always have usb_core_id=0, since
* Android user space is currently interested in android0 events.
*/
snprintf(device_node_name, ANDROID_DEVICE_NODE_NAME_LENGTH,
"android%d", usb_core_id);
dev->dev = device_create(android_class, NULL,
MKDEV(0, 0), NULL, device_node_name);
if (IS_ERR(dev->dev))
return PTR_ERR(dev->dev);
dev_set_drvdata(dev->dev, dev);
while ((attr = *attrs++)) {
err = device_create_file(dev->dev, attr);
if (err) {
device_destroy(android_class, dev->dev->devt);
return err;
}
}
return 0;
}
static void android_destroy_device(struct android_dev *dev)
{
struct device_attribute **attrs = android_usb_attributes;
struct device_attribute *attr;
while ((attr = *attrs++))
device_remove_file(dev->dev, attr);
device_destroy(android_class, dev->dev->devt);
}
static struct android_dev *cdev_to_android_dev(struct usb_composite_dev *cdev)
{
struct android_dev *dev = NULL;
/* Find the android dev from the list */
list_for_each_entry(dev, &android_dev_list, list_item) {
if (dev->cdev == cdev)
break;
}
return dev;
}
static struct android_configuration *alloc_android_config
(struct android_dev *dev)
{
struct android_configuration *conf;
conf = kzalloc(sizeof(*conf), GFP_KERNEL);
if (!conf) {
pr_err("%s(): Failed to alloc memory for android conf\n",
__func__);
return ERR_PTR(-ENOMEM);
}
dev->configs_num++;
conf->usb_config.label = dev->name;
conf->usb_config.unbind = android_unbind_config;
conf->usb_config.bConfigurationValue = dev->configs_num;
INIT_LIST_HEAD(&conf->enabled_functions);
list_add_tail(&conf->list_item, &dev->configs);
return conf;
}
static void free_android_config(struct android_dev *dev,
struct android_configuration *conf)
{
list_del(&conf->list_item);
dev->configs_num--;
kfree(conf);
}
static int usb_diag_update_pid_and_serial_num(u32 pid, const char *snum)
{
struct dload_struct local_diag_dload = { 0 };
int *src, *dst, i;
if (!diag_dload) {
pr_debug("%s: unable to update PID and serial_no\n", __func__);
return -ENODEV;
}
pr_debug("%s: dload:%p pid:%x serial_num:%s\n",
__func__, diag_dload, pid, snum);
/* update pid */
local_diag_dload.magic_struct.pid = PID_MAGIC_ID;
local_diag_dload.pid = pid;
/* update serial number */
if (!snum) {
local_diag_dload.magic_struct.serial_num = 0;
memset(&local_diag_dload.serial_number, 0,
SERIAL_NUMBER_LENGTH);
} else {
local_diag_dload.magic_struct.serial_num = SERIAL_NUM_MAGIC_ID;
strlcpy((char *)&local_diag_dload.serial_number, snum,
SERIAL_NUMBER_LENGTH);
}
/* Copy to shared struct (accesses need to be 32 bit aligned) */
src = (int *)&local_diag_dload;
dst = (int *)diag_dload;
for (i = 0; i < sizeof(*diag_dload) / 4; i++)
*dst++ = *src++;
return 0;
}
static int android_probe(struct platform_device *pdev)
{
struct android_usb_platform_data *pdata;
struct android_dev *android_dev;
struct resource *res;
int ret = 0, i, len = 0, prop_len = 0;
if (pdev->dev.of_node) {
dev_dbg(&pdev->dev, "device tree enabled\n");
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata) {
pr_err("unable to allocate platform data\n");
return -ENOMEM;
}
of_get_property(pdev->dev.of_node, "qcom,pm-qos-latency",
&prop_len);
if (prop_len == sizeof(pdata->pm_qos_latency)) {
of_property_read_u32_array(pdev->dev.of_node,
"qcom,pm-qos-latency", pdata->pm_qos_latency,
prop_len/sizeof(*pdata->pm_qos_latency));
} else {
pr_info("pm_qos latency not specified %d\n", prop_len);
}
len = of_property_count_strings(pdev->dev.of_node,
"qcom,streaming-func");
if (len > MAX_STREAMING_FUNCS) {
pr_err("Invalid number of functions used.\n");
return -EINVAL;
}
for (i = 0; i < len; i++) {
const char *name = NULL;
of_property_read_string_index(pdev->dev.of_node,
"qcom,streaming-func", i, &name);
if (!name)
continue;
if (sizeof(name) > FUNC_NAME_LEN) {
pr_err("Function name is bigger than allowed.\n");
continue;
}
strlcpy(pdata->streaming_func[i], name,
sizeof(pdata->streaming_func[i]));
pr_debug("name of streaming function:%s\n",
pdata->streaming_func[i]);
}
pdata->streaming_func_count = len;
pdata->cdrom = of_property_read_bool(pdev->dev.of_node,
"qcom,android-usb-cdrom");
ret = of_property_read_u8(pdev->dev.of_node,
"qcom,android-usb-uicc-nluns",
&pdata->uicc_nluns);
} else {
pdata = pdev->dev.platform_data;
}
if (!android_class) {
android_class = class_create(THIS_MODULE, "android_usb");
if (IS_ERR(android_class))
return PTR_ERR(android_class);
}
android_dev = kzalloc(sizeof(*android_dev), GFP_KERNEL);
if (!android_dev) {
pr_err("%s(): Failed to alloc memory for android_dev\n",
__func__);
ret = -ENOMEM;
goto err_alloc;
}
android_dev->name = pdev->name;
android_dev->disable_depth = 1;
android_dev->functions = supported_functions;
android_dev->configs_num = 0;
INIT_LIST_HEAD(&android_dev->configs);
INIT_WORK(&android_dev->work, android_work);
INIT_DELAYED_WORK(&android_dev->pm_qos_work, android_pm_qos_work);
mutex_init(&android_dev->mutex);
android_dev->pdata = pdata;
list_add_tail(&android_dev->list_item, &android_dev_list);
android_dev_count++;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res) {
diag_dload = devm_ioremap(&pdev->dev, res->start,
resource_size(res));
if (!diag_dload) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto err_dev;
}
} else {
dev_dbg(&pdev->dev, "failed to get mem resource\n");
}
if (pdata)
ret = android_create_device(android_dev, pdata->usb_core_id);
else
ret = android_create_device(android_dev, 0);
if (ret) {
pr_err("%s(): android_create_device failed\n", __func__);
goto err_dev;
}
ret = usb_composite_probe(&android_usb_driver);
if (ret) {
/* Perhaps UDC hasn't probed yet, try again later */
if (ret == -ENODEV)
ret = -EPROBE_DEFER;
else
pr_err("%s(): Failed to register android composite driver\n",
__func__);
goto err_probe;
}
/* pm qos request to prevent apps idle power collapse */
android_dev->curr_pm_qos_state = NO_USB_VOTE;
if (pdata && pdata->pm_qos_latency[0]) {
pm_qos_add_request(&android_dev->pm_qos_req_dma,
PM_QOS_CPU_DMA_LATENCY, PM_QOS_DEFAULT_VALUE);
android_dev->down_pm_qos_sample_sec = DOWN_PM_QOS_SAMPLE_SEC;
android_dev->down_pm_qos_threshold = DOWN_PM_QOS_THRESHOLD;
android_dev->up_pm_qos_sample_sec = UP_PM_QOS_SAMPLE_SEC;
android_dev->up_pm_qos_threshold = UP_PM_QOS_THRESHOLD;
android_dev->idle_pc_rpm_no_int_secs = IDLE_PC_RPM_NO_INT_SECS;
}
strlcpy(android_dev->pm_qos, "high", sizeof(android_dev->pm_qos));
return ret;
err_probe:
android_destroy_device(android_dev);
err_dev:
list_del(&android_dev->list_item);
android_dev_count--;
kfree(android_dev);
err_alloc:
if (list_empty(&android_dev_list)) {
class_destroy(android_class);
android_class = NULL;
}
return ret;
}
static int android_remove(struct platform_device *pdev)
{
struct android_dev *dev = NULL;
struct android_usb_platform_data *pdata = pdev->dev.platform_data;
int usb_core_id = 0;
if (pdata)
usb_core_id = pdata->usb_core_id;
/* Find the android dev from the list */
list_for_each_entry(dev, &android_dev_list, list_item) {
if (!dev->pdata)
break; /*To backward compatibility*/
if (dev->pdata->usb_core_id == usb_core_id)
break;
}
if (dev) {
android_destroy_device(dev);
if (pdata && pdata->pm_qos_latency[0])
pm_qos_remove_request(&dev->pm_qos_req_dma);
list_del(&dev->list_item);
android_dev_count--;
kfree(dev);
}
if (list_empty(&android_dev_list)) {
class_destroy(android_class);
android_class = NULL;
usb_composite_unregister(&android_usb_driver);
}
return 0;
}
static const struct platform_device_id android_id_table[] = {
{
.name = "android_usb",
},
{
.name = "android_usb_hsic",
},
};
static struct of_device_id usb_android_dt_match[] = {
{ .compatible = "qcom,android-usb",
},
{}
};
static struct platform_driver android_platform_driver = {
.driver = {
.name = "android_usb",
.of_match_table = usb_android_dt_match,
},
.probe = android_probe,
.remove = android_remove,
.id_table = android_id_table,
};
static int __init init(void)
{
int ret;
INIT_LIST_HEAD(&android_dev_list);
android_dev_count = 0;
ret = platform_driver_register(&android_platform_driver);
if (ret) {
pr_err("%s(): Failed to register android"
"platform driver\n", __func__);
}
/* HACK: exchange composite's setup with ours */
composite_setup_func = android_usb_driver.gadget_driver.setup;
android_usb_driver.gadget_driver.setup = android_setup;
composite_suspend_func = android_usb_driver.gadget_driver.suspend;
android_usb_driver.gadget_driver.suspend = android_suspend;
composite_resume_func = android_usb_driver.gadget_driver.resume;
android_usb_driver.gadget_driver.resume = android_resume;
return ret;
}
late_initcall(init);
static void __exit cleanup(void)
{
platform_driver_unregister(&android_platform_driver);
}
module_exit(cleanup);
| sandymanu/manufooty_yu | drivers/usb/gadget/android.c | C | gpl-2.0 | 101,908 |
package com.github.mikephil.charting.jobs;
import android.view.View;
import com.github.mikephil.charting.utils.Transformer;
import com.github.mikephil.charting.utils.ViewPortHandler;
/**
* Runnable that is used for viewport modifications since they cannot be
* executed at any time. This can be used to delay the execution of viewport
* modifications until the onSizeChanged(...) method of the chartview is called.
*
* @author Philipp Jahoda
*/
public class MoveViewJob implements Runnable {
protected ViewPortHandler mViewPortHandler;
protected float xIndex = 0f;
protected float yValue = 0f;
protected Transformer mTrans;
protected View view;
public MoveViewJob(ViewPortHandler viewPortHandler, float xIndex, float yValue,
Transformer trans, View v) {
this.mViewPortHandler = viewPortHandler;
this.xIndex = xIndex;
this.yValue = yValue;
this.mTrans = trans;
this.view = v;
}
@Override
public void run() {
float[] pts = new float[] {
xIndex, yValue
};
mTrans.pointValuesToPixel(pts);
mViewPortHandler.centerViewPort(pts, view);
}
}
| silen85/shujutongji | mpchartlib/src/main/java/com/github/mikephil/charting/jobs/MoveViewJob.java | Java | gpl-2.0 | 1,190 |
/*
*
* (c) 2007 Pengutronix, Sascha Hauer <[email protected]>
*
* See file CREDITS for list of people who contributed to this
* project.
*
* 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 __ASM_ARCH_MX31_IMX_REGS_H
#define __ASM_ARCH_MX31_IMX_REGS_H
#if !(defined(__KERNEL_STRICT_NAMES) || defined(__ASSEMBLY__))
#include <asm/types.h>
/* Clock control module registers */
struct clock_control_regs {
u32 ccmr;
u32 pdr0;
u32 pdr1;
u32 rcsr;
u32 mpctl;
u32 upctl;
u32 spctl;
u32 cosr;
u32 cgr0;
u32 cgr1;
u32 cgr2;
u32 wimr0;
u32 ldc;
u32 dcvr0;
u32 dcvr1;
u32 dcvr2;
u32 dcvr3;
u32 ltr0;
u32 ltr1;
u32 ltr2;
u32 ltr3;
u32 ltbr0;
u32 ltbr1;
u32 pmcr0;
u32 pmcr1;
u32 pdr2;
};
struct cspi_regs {
u32 rxdata;
u32 txdata;
u32 ctrl;
u32 intr;
u32 dma;
u32 stat;
u32 period;
u32 test;
};
/* Watchdog Timer (WDOG) registers */
#define WDOG_ENABLE (1 << 2)
#define WDOG_WT_SHIFT 8
#define WDOG_WDZST (1 << 0)
struct wdog_regs {
u16 wcr; /* Control */
u16 wsr; /* Service */
u16 wrsr; /* Reset Status */
};
/* IIM Control Registers */
struct iim_regs {
u32 iim_stat;
u32 iim_statm;
u32 iim_err;
u32 iim_emask;
u32 iim_fctl;
u32 iim_ua;
u32 iim_la;
u32 iim_sdat;
u32 iim_prev;
u32 iim_srev;
u32 iim_prog_p;
u32 iim_scs0;
u32 iim_scs1;
u32 iim_scs2;
u32 iim_scs3;
};
struct iomuxc_regs {
u32 unused1;
u32 unused2;
u32 gpr;
};
struct mx3_cpu_type {
u8 srev;
u32 v;
};
#define IOMUX_PADNUM_MASK 0x1ff
#define IOMUX_PIN(gpionum, padnum) ((padnum) & IOMUX_PADNUM_MASK)
/*
* various IOMUX pad functions
*/
enum iomux_pad_config {
PAD_CTL_NOLOOPBACK = 0x0 << 9,
PAD_CTL_LOOPBACK = 0x1 << 9,
PAD_CTL_PKE_NONE = 0x0 << 8,
PAD_CTL_PKE_ENABLE = 0x1 << 8,
PAD_CTL_PUE_KEEPER = 0x0 << 7,
PAD_CTL_PUE_PUD = 0x1 << 7,
PAD_CTL_100K_PD = 0x0 << 5,
PAD_CTL_100K_PU = 0x1 << 5,
PAD_CTL_47K_PU = 0x2 << 5,
PAD_CTL_22K_PU = 0x3 << 5,
PAD_CTL_HYS_CMOS = 0x0 << 4,
PAD_CTL_HYS_SCHMITZ = 0x1 << 4,
PAD_CTL_ODE_CMOS = 0x0 << 3,
PAD_CTL_ODE_OpenDrain = 0x1 << 3,
PAD_CTL_DRV_NORMAL = 0x0 << 1,
PAD_CTL_DRV_HIGH = 0x1 << 1,
PAD_CTL_DRV_MAX = 0x2 << 1,
PAD_CTL_SRE_SLOW = 0x0 << 0,
PAD_CTL_SRE_FAST = 0x1 << 0
};
/*
* This enumeration is constructed based on the Section
* "sw_pad_ctl & sw_mux_ctl details" of the MX31 IC Spec. Each enumerated
* value is constructed based on the rules described above.
*/
enum iomux_pins {
MX31_PIN_TTM_PAD = IOMUX_PIN(0xff, 0),
MX31_PIN_CSPI3_SPI_RDY = IOMUX_PIN(0xff, 1),
MX31_PIN_CSPI3_SCLK = IOMUX_PIN(0xff, 2),
MX31_PIN_CSPI3_MISO = IOMUX_PIN(0xff, 3),
MX31_PIN_CSPI3_MOSI = IOMUX_PIN(0xff, 4),
MX31_PIN_CLKSS = IOMUX_PIN(0xff, 5),
MX31_PIN_CE_CONTROL = IOMUX_PIN(0xff, 6),
MX31_PIN_ATA_RESET_B = IOMUX_PIN(95, 7),
MX31_PIN_ATA_DMACK = IOMUX_PIN(94, 8),
MX31_PIN_ATA_DIOW = IOMUX_PIN(93, 9),
MX31_PIN_ATA_DIOR = IOMUX_PIN(92, 10),
MX31_PIN_ATA_CS1 = IOMUX_PIN(91, 11),
MX31_PIN_ATA_CS0 = IOMUX_PIN(90, 12),
MX31_PIN_SD1_DATA3 = IOMUX_PIN(63, 13),
MX31_PIN_SD1_DATA2 = IOMUX_PIN(62, 14),
MX31_PIN_SD1_DATA1 = IOMUX_PIN(61, 15),
MX31_PIN_SD1_DATA0 = IOMUX_PIN(60, 16),
MX31_PIN_SD1_CLK = IOMUX_PIN(59, 17),
MX31_PIN_SD1_CMD = IOMUX_PIN(58, 18),
MX31_PIN_D3_SPL = IOMUX_PIN(0xff, 19),
MX31_PIN_D3_CLS = IOMUX_PIN(0xff, 20),
MX31_PIN_D3_REV = IOMUX_PIN(0xff, 21),
MX31_PIN_CONTRAST = IOMUX_PIN(0xff, 22),
MX31_PIN_VSYNC3 = IOMUX_PIN(0xff, 23),
MX31_PIN_READ = IOMUX_PIN(0xff, 24),
MX31_PIN_WRITE = IOMUX_PIN(0xff, 25),
MX31_PIN_PAR_RS = IOMUX_PIN(0xff, 26),
MX31_PIN_SER_RS = IOMUX_PIN(89, 27),
MX31_PIN_LCS1 = IOMUX_PIN(88, 28),
MX31_PIN_LCS0 = IOMUX_PIN(87, 29),
MX31_PIN_SD_D_CLK = IOMUX_PIN(86, 30),
MX31_PIN_SD_D_IO = IOMUX_PIN(85, 31),
MX31_PIN_SD_D_I = IOMUX_PIN(84, 32),
MX31_PIN_DRDY0 = IOMUX_PIN(0xff, 33),
MX31_PIN_FPSHIFT = IOMUX_PIN(0xff, 34),
MX31_PIN_HSYNC = IOMUX_PIN(0xff, 35),
MX31_PIN_VSYNC0 = IOMUX_PIN(0xff, 36),
MX31_PIN_LD17 = IOMUX_PIN(0xff, 37),
MX31_PIN_LD16 = IOMUX_PIN(0xff, 38),
MX31_PIN_LD15 = IOMUX_PIN(0xff, 39),
MX31_PIN_LD14 = IOMUX_PIN(0xff, 40),
MX31_PIN_LD13 = IOMUX_PIN(0xff, 41),
MX31_PIN_LD12 = IOMUX_PIN(0xff, 42),
MX31_PIN_LD11 = IOMUX_PIN(0xff, 43),
MX31_PIN_LD10 = IOMUX_PIN(0xff, 44),
MX31_PIN_LD9 = IOMUX_PIN(0xff, 45),
MX31_PIN_LD8 = IOMUX_PIN(0xff, 46),
MX31_PIN_LD7 = IOMUX_PIN(0xff, 47),
MX31_PIN_LD6 = IOMUX_PIN(0xff, 48),
MX31_PIN_LD5 = IOMUX_PIN(0xff, 49),
MX31_PIN_LD4 = IOMUX_PIN(0xff, 50),
MX31_PIN_LD3 = IOMUX_PIN(0xff, 51),
MX31_PIN_LD2 = IOMUX_PIN(0xff, 52),
MX31_PIN_LD1 = IOMUX_PIN(0xff, 53),
MX31_PIN_LD0 = IOMUX_PIN(0xff, 54),
MX31_PIN_USBH2_DATA1 = IOMUX_PIN(0xff, 55),
MX31_PIN_USBH2_DATA0 = IOMUX_PIN(0xff, 56),
MX31_PIN_USBH2_NXT = IOMUX_PIN(0xff, 57),
MX31_PIN_USBH2_STP = IOMUX_PIN(0xff, 58),
MX31_PIN_USBH2_DIR = IOMUX_PIN(0xff, 59),
MX31_PIN_USBH2_CLK = IOMUX_PIN(0xff, 60),
MX31_PIN_USBOTG_DATA7 = IOMUX_PIN(0xff, 61),
MX31_PIN_USBOTG_DATA6 = IOMUX_PIN(0xff, 62),
MX31_PIN_USBOTG_DATA5 = IOMUX_PIN(0xff, 63),
MX31_PIN_USBOTG_DATA4 = IOMUX_PIN(0xff, 64),
MX31_PIN_USBOTG_DATA3 = IOMUX_PIN(0xff, 65),
MX31_PIN_USBOTG_DATA2 = IOMUX_PIN(0xff, 66),
MX31_PIN_USBOTG_DATA1 = IOMUX_PIN(0xff, 67),
MX31_PIN_USBOTG_DATA0 = IOMUX_PIN(0xff, 68),
MX31_PIN_USBOTG_NXT = IOMUX_PIN(0xff, 69),
MX31_PIN_USBOTG_STP = IOMUX_PIN(0xff, 70),
MX31_PIN_USBOTG_DIR = IOMUX_PIN(0xff, 71),
MX31_PIN_USBOTG_CLK = IOMUX_PIN(0xff, 72),
MX31_PIN_USB_BYP = IOMUX_PIN(31, 73),
MX31_PIN_USB_OC = IOMUX_PIN(30, 74),
MX31_PIN_USB_PWR = IOMUX_PIN(29, 75),
MX31_PIN_SJC_MOD = IOMUX_PIN(0xff, 76),
MX31_PIN_DE_B = IOMUX_PIN(0xff, 77),
MX31_PIN_TRSTB = IOMUX_PIN(0xff, 78),
MX31_PIN_TDO = IOMUX_PIN(0xff, 79),
MX31_PIN_TDI = IOMUX_PIN(0xff, 80),
MX31_PIN_TMS = IOMUX_PIN(0xff, 81),
MX31_PIN_TCK = IOMUX_PIN(0xff, 82),
MX31_PIN_RTCK = IOMUX_PIN(0xff, 83),
MX31_PIN_KEY_COL7 = IOMUX_PIN(57, 84),
MX31_PIN_KEY_COL6 = IOMUX_PIN(56, 85),
MX31_PIN_KEY_COL5 = IOMUX_PIN(55, 86),
MX31_PIN_KEY_COL4 = IOMUX_PIN(54, 87),
MX31_PIN_KEY_COL3 = IOMUX_PIN(0xff, 88),
MX31_PIN_KEY_COL2 = IOMUX_PIN(0xff, 89),
MX31_PIN_KEY_COL1 = IOMUX_PIN(0xff, 90),
MX31_PIN_KEY_COL0 = IOMUX_PIN(0xff, 91),
MX31_PIN_KEY_ROW7 = IOMUX_PIN(53, 92),
MX31_PIN_KEY_ROW6 = IOMUX_PIN(52, 93),
MX31_PIN_KEY_ROW5 = IOMUX_PIN(51, 94),
MX31_PIN_KEY_ROW4 = IOMUX_PIN(50, 95),
MX31_PIN_KEY_ROW3 = IOMUX_PIN(0xff, 96),
MX31_PIN_KEY_ROW2 = IOMUX_PIN(0xff, 97),
MX31_PIN_KEY_ROW1 = IOMUX_PIN(0xff, 98),
MX31_PIN_KEY_ROW0 = IOMUX_PIN(0xff, 99),
MX31_PIN_BATT_LINE = IOMUX_PIN(49, 100),
MX31_PIN_CTS2 = IOMUX_PIN(0xff, 101),
MX31_PIN_RTS2 = IOMUX_PIN(0xff, 102),
MX31_PIN_TXD2 = IOMUX_PIN(28, 103),
MX31_PIN_RXD2 = IOMUX_PIN(27, 104),
MX31_PIN_DTR_DCE2 = IOMUX_PIN(48, 105),
MX31_PIN_DCD_DTE1 = IOMUX_PIN(47, 106),
MX31_PIN_RI_DTE1 = IOMUX_PIN(46, 107),
MX31_PIN_DSR_DTE1 = IOMUX_PIN(45, 108),
MX31_PIN_DTR_DTE1 = IOMUX_PIN(44, 109),
MX31_PIN_DCD_DCE1 = IOMUX_PIN(43, 110),
MX31_PIN_RI_DCE1 = IOMUX_PIN(42, 111),
MX31_PIN_DSR_DCE1 = IOMUX_PIN(41, 112),
MX31_PIN_DTR_DCE1 = IOMUX_PIN(40, 113),
MX31_PIN_CTS1 = IOMUX_PIN(39, 114),
MX31_PIN_RTS1 = IOMUX_PIN(38, 115),
MX31_PIN_TXD1 = IOMUX_PIN(37, 116),
MX31_PIN_RXD1 = IOMUX_PIN(36, 117),
MX31_PIN_CSPI2_SPI_RDY = IOMUX_PIN(0xff, 118),
MX31_PIN_CSPI2_SCLK = IOMUX_PIN(0xff, 119),
MX31_PIN_CSPI2_SS2 = IOMUX_PIN(0xff, 120),
MX31_PIN_CSPI2_SS1 = IOMUX_PIN(0xff, 121),
MX31_PIN_CSPI2_SS0 = IOMUX_PIN(0xff, 122),
MX31_PIN_CSPI2_MISO = IOMUX_PIN(0xff, 123),
MX31_PIN_CSPI2_MOSI = IOMUX_PIN(0xff, 124),
MX31_PIN_CSPI1_SPI_RDY = IOMUX_PIN(0xff, 125),
MX31_PIN_CSPI1_SCLK = IOMUX_PIN(0xff, 126),
MX31_PIN_CSPI1_SS2 = IOMUX_PIN(0xff, 127),
MX31_PIN_CSPI1_SS1 = IOMUX_PIN(0xff, 128),
MX31_PIN_CSPI1_SS0 = IOMUX_PIN(0xff, 129),
MX31_PIN_CSPI1_MISO = IOMUX_PIN(0xff, 130),
MX31_PIN_CSPI1_MOSI = IOMUX_PIN(0xff, 131),
MX31_PIN_SFS6 = IOMUX_PIN(26, 132),
MX31_PIN_SCK6 = IOMUX_PIN(25, 133),
MX31_PIN_SRXD6 = IOMUX_PIN(24, 134),
MX31_PIN_STXD6 = IOMUX_PIN(23, 135),
MX31_PIN_SFS5 = IOMUX_PIN(0xff, 136),
MX31_PIN_SCK5 = IOMUX_PIN(0xff, 137),
MX31_PIN_SRXD5 = IOMUX_PIN(22, 138),
MX31_PIN_STXD5 = IOMUX_PIN(21, 139),
MX31_PIN_SFS4 = IOMUX_PIN(0xff, 140),
MX31_PIN_SCK4 = IOMUX_PIN(0xff, 141),
MX31_PIN_SRXD4 = IOMUX_PIN(20, 142),
MX31_PIN_STXD4 = IOMUX_PIN(19, 143),
MX31_PIN_SFS3 = IOMUX_PIN(0xff, 144),
MX31_PIN_SCK3 = IOMUX_PIN(0xff, 145),
MX31_PIN_SRXD3 = IOMUX_PIN(18, 146),
MX31_PIN_STXD3 = IOMUX_PIN(17, 147),
MX31_PIN_I2C_DAT = IOMUX_PIN(0xff, 148),
MX31_PIN_I2C_CLK = IOMUX_PIN(0xff, 149),
MX31_PIN_CSI_PIXCLK = IOMUX_PIN(83, 150),
MX31_PIN_CSI_HSYNC = IOMUX_PIN(82, 151),
MX31_PIN_CSI_VSYNC = IOMUX_PIN(81, 152),
MX31_PIN_CSI_MCLK = IOMUX_PIN(80, 153),
MX31_PIN_CSI_D15 = IOMUX_PIN(79, 154),
MX31_PIN_CSI_D14 = IOMUX_PIN(78, 155),
MX31_PIN_CSI_D13 = IOMUX_PIN(77, 156),
MX31_PIN_CSI_D12 = IOMUX_PIN(76, 157),
MX31_PIN_CSI_D11 = IOMUX_PIN(75, 158),
MX31_PIN_CSI_D10 = IOMUX_PIN(74, 159),
MX31_PIN_CSI_D9 = IOMUX_PIN(73, 160),
MX31_PIN_CSI_D8 = IOMUX_PIN(72, 161),
MX31_PIN_CSI_D7 = IOMUX_PIN(71, 162),
MX31_PIN_CSI_D6 = IOMUX_PIN(70, 163),
MX31_PIN_CSI_D5 = IOMUX_PIN(69, 164),
MX31_PIN_CSI_D4 = IOMUX_PIN(68, 165),
MX31_PIN_M_GRANT = IOMUX_PIN(0xff, 166),
MX31_PIN_M_REQUEST = IOMUX_PIN(0xff, 167),
MX31_PIN_PC_POE = IOMUX_PIN(0xff, 168),
MX31_PIN_PC_RW_B = IOMUX_PIN(0xff, 169),
MX31_PIN_IOIS16 = IOMUX_PIN(0xff, 170),
MX31_PIN_PC_RST = IOMUX_PIN(0xff, 171),
MX31_PIN_PC_BVD2 = IOMUX_PIN(0xff, 172),
MX31_PIN_PC_BVD1 = IOMUX_PIN(0xff, 173),
MX31_PIN_PC_VS2 = IOMUX_PIN(0xff, 174),
MX31_PIN_PC_VS1 = IOMUX_PIN(0xff, 175),
MX31_PIN_PC_PWRON = IOMUX_PIN(0xff, 176),
MX31_PIN_PC_READY = IOMUX_PIN(0xff, 177),
MX31_PIN_PC_WAIT_B = IOMUX_PIN(0xff, 178),
MX31_PIN_PC_CD2_B = IOMUX_PIN(0xff, 179),
MX31_PIN_PC_CD1_B = IOMUX_PIN(0xff, 180),
MX31_PIN_D0 = IOMUX_PIN(0xff, 181),
MX31_PIN_D1 = IOMUX_PIN(0xff, 182),
MX31_PIN_D2 = IOMUX_PIN(0xff, 183),
MX31_PIN_D3 = IOMUX_PIN(0xff, 184),
MX31_PIN_D4 = IOMUX_PIN(0xff, 185),
MX31_PIN_D5 = IOMUX_PIN(0xff, 186),
MX31_PIN_D6 = IOMUX_PIN(0xff, 187),
MX31_PIN_D7 = IOMUX_PIN(0xff, 188),
MX31_PIN_D8 = IOMUX_PIN(0xff, 189),
MX31_PIN_D9 = IOMUX_PIN(0xff, 190),
MX31_PIN_D10 = IOMUX_PIN(0xff, 191),
MX31_PIN_D11 = IOMUX_PIN(0xff, 192),
MX31_PIN_D12 = IOMUX_PIN(0xff, 193),
MX31_PIN_D13 = IOMUX_PIN(0xff, 194),
MX31_PIN_D14 = IOMUX_PIN(0xff, 195),
MX31_PIN_D15 = IOMUX_PIN(0xff, 196),
MX31_PIN_NFRB = IOMUX_PIN(16, 197),
MX31_PIN_NFCE_B = IOMUX_PIN(15, 198),
MX31_PIN_NFWP_B = IOMUX_PIN(14, 199),
MX31_PIN_NFCLE = IOMUX_PIN(13, 200),
MX31_PIN_NFALE = IOMUX_PIN(12, 201),
MX31_PIN_NFRE_B = IOMUX_PIN(11, 202),
MX31_PIN_NFWE_B = IOMUX_PIN(10, 203),
MX31_PIN_SDQS3 = IOMUX_PIN(0xff, 204),
MX31_PIN_SDQS2 = IOMUX_PIN(0xff, 205),
MX31_PIN_SDQS1 = IOMUX_PIN(0xff, 206),
MX31_PIN_SDQS0 = IOMUX_PIN(0xff, 207),
MX31_PIN_SDCLK_B = IOMUX_PIN(0xff, 208),
MX31_PIN_SDCLK = IOMUX_PIN(0xff, 209),
MX31_PIN_SDCKE1 = IOMUX_PIN(0xff, 210),
MX31_PIN_SDCKE0 = IOMUX_PIN(0xff, 211),
MX31_PIN_SDWE = IOMUX_PIN(0xff, 212),
MX31_PIN_CAS = IOMUX_PIN(0xff, 213),
MX31_PIN_RAS = IOMUX_PIN(0xff, 214),
MX31_PIN_RW = IOMUX_PIN(0xff, 215),
MX31_PIN_BCLK = IOMUX_PIN(0xff, 216),
MX31_PIN_LBA = IOMUX_PIN(0xff, 217),
MX31_PIN_ECB = IOMUX_PIN(0xff, 218),
MX31_PIN_CS5 = IOMUX_PIN(0xff, 219),
MX31_PIN_CS4 = IOMUX_PIN(0xff, 220),
MX31_PIN_CS3 = IOMUX_PIN(0xff, 221),
MX31_PIN_CS2 = IOMUX_PIN(0xff, 222),
MX31_PIN_CS1 = IOMUX_PIN(0xff, 223),
MX31_PIN_CS0 = IOMUX_PIN(0xff, 224),
MX31_PIN_OE = IOMUX_PIN(0xff, 225),
MX31_PIN_EB1 = IOMUX_PIN(0xff, 226),
MX31_PIN_EB0 = IOMUX_PIN(0xff, 227),
MX31_PIN_DQM3 = IOMUX_PIN(0xff, 228),
MX31_PIN_DQM2 = IOMUX_PIN(0xff, 229),
MX31_PIN_DQM1 = IOMUX_PIN(0xff, 230),
MX31_PIN_DQM0 = IOMUX_PIN(0xff, 231),
MX31_PIN_SD31 = IOMUX_PIN(0xff, 232),
MX31_PIN_SD30 = IOMUX_PIN(0xff, 233),
MX31_PIN_SD29 = IOMUX_PIN(0xff, 234),
MX31_PIN_SD28 = IOMUX_PIN(0xff, 235),
MX31_PIN_SD27 = IOMUX_PIN(0xff, 236),
MX31_PIN_SD26 = IOMUX_PIN(0xff, 237),
MX31_PIN_SD25 = IOMUX_PIN(0xff, 238),
MX31_PIN_SD24 = IOMUX_PIN(0xff, 239),
MX31_PIN_SD23 = IOMUX_PIN(0xff, 240),
MX31_PIN_SD22 = IOMUX_PIN(0xff, 241),
MX31_PIN_SD21 = IOMUX_PIN(0xff, 242),
MX31_PIN_SD20 = IOMUX_PIN(0xff, 243),
MX31_PIN_SD19 = IOMUX_PIN(0xff, 244),
MX31_PIN_SD18 = IOMUX_PIN(0xff, 245),
MX31_PIN_SD17 = IOMUX_PIN(0xff, 246),
MX31_PIN_SD16 = IOMUX_PIN(0xff, 247),
MX31_PIN_SD15 = IOMUX_PIN(0xff, 248),
MX31_PIN_SD14 = IOMUX_PIN(0xff, 249),
MX31_PIN_SD13 = IOMUX_PIN(0xff, 250),
MX31_PIN_SD12 = IOMUX_PIN(0xff, 251),
MX31_PIN_SD11 = IOMUX_PIN(0xff, 252),
MX31_PIN_SD10 = IOMUX_PIN(0xff, 253),
MX31_PIN_SD9 = IOMUX_PIN(0xff, 254),
MX31_PIN_SD8 = IOMUX_PIN(0xff, 255),
MX31_PIN_SD7 = IOMUX_PIN(0xff, 256),
MX31_PIN_SD6 = IOMUX_PIN(0xff, 257),
MX31_PIN_SD5 = IOMUX_PIN(0xff, 258),
MX31_PIN_SD4 = IOMUX_PIN(0xff, 259),
MX31_PIN_SD3 = IOMUX_PIN(0xff, 260),
MX31_PIN_SD2 = IOMUX_PIN(0xff, 261),
MX31_PIN_SD1 = IOMUX_PIN(0xff, 262),
MX31_PIN_SD0 = IOMUX_PIN(0xff, 263),
MX31_PIN_SDBA0 = IOMUX_PIN(0xff, 264),
MX31_PIN_SDBA1 = IOMUX_PIN(0xff, 265),
MX31_PIN_A25 = IOMUX_PIN(0xff, 266),
MX31_PIN_A24 = IOMUX_PIN(0xff, 267),
MX31_PIN_A23 = IOMUX_PIN(0xff, 268),
MX31_PIN_A22 = IOMUX_PIN(0xff, 269),
MX31_PIN_A21 = IOMUX_PIN(0xff, 270),
MX31_PIN_A20 = IOMUX_PIN(0xff, 271),
MX31_PIN_A19 = IOMUX_PIN(0xff, 272),
MX31_PIN_A18 = IOMUX_PIN(0xff, 273),
MX31_PIN_A17 = IOMUX_PIN(0xff, 274),
MX31_PIN_A16 = IOMUX_PIN(0xff, 275),
MX31_PIN_A14 = IOMUX_PIN(0xff, 276),
MX31_PIN_A15 = IOMUX_PIN(0xff, 277),
MX31_PIN_A13 = IOMUX_PIN(0xff, 278),
MX31_PIN_A12 = IOMUX_PIN(0xff, 279),
MX31_PIN_A11 = IOMUX_PIN(0xff, 280),
MX31_PIN_MA10 = IOMUX_PIN(0xff, 281),
MX31_PIN_A10 = IOMUX_PIN(0xff, 282),
MX31_PIN_A9 = IOMUX_PIN(0xff, 283),
MX31_PIN_A8 = IOMUX_PIN(0xff, 284),
MX31_PIN_A7 = IOMUX_PIN(0xff, 285),
MX31_PIN_A6 = IOMUX_PIN(0xff, 286),
MX31_PIN_A5 = IOMUX_PIN(0xff, 287),
MX31_PIN_A4 = IOMUX_PIN(0xff, 288),
MX31_PIN_A3 = IOMUX_PIN(0xff, 289),
MX31_PIN_A2 = IOMUX_PIN(0xff, 290),
MX31_PIN_A1 = IOMUX_PIN(0xff, 291),
MX31_PIN_A0 = IOMUX_PIN(0xff, 292),
MX31_PIN_VPG1 = IOMUX_PIN(0xff, 293),
MX31_PIN_VPG0 = IOMUX_PIN(0xff, 294),
MX31_PIN_DVFS1 = IOMUX_PIN(0xff, 295),
MX31_PIN_DVFS0 = IOMUX_PIN(0xff, 296),
MX31_PIN_VSTBY = IOMUX_PIN(0xff, 297),
MX31_PIN_POWER_FAIL = IOMUX_PIN(0xff, 298),
MX31_PIN_CKIL = IOMUX_PIN(0xff, 299),
MX31_PIN_BOOT_MODE4 = IOMUX_PIN(0xff, 300),
MX31_PIN_BOOT_MODE3 = IOMUX_PIN(0xff, 301),
MX31_PIN_BOOT_MODE2 = IOMUX_PIN(0xff, 302),
MX31_PIN_BOOT_MODE1 = IOMUX_PIN(0xff, 303),
MX31_PIN_BOOT_MODE0 = IOMUX_PIN(0xff, 304),
MX31_PIN_CLKO = IOMUX_PIN(0xff, 305),
MX31_PIN_POR_B = IOMUX_PIN(0xff, 306),
MX31_PIN_RESET_IN_B = IOMUX_PIN(0xff, 307),
MX31_PIN_CKIH = IOMUX_PIN(0xff, 308),
MX31_PIN_SIMPD0 = IOMUX_PIN(35, 309),
MX31_PIN_SRX0 = IOMUX_PIN(34, 310),
MX31_PIN_STX0 = IOMUX_PIN(33, 311),
MX31_PIN_SVEN0 = IOMUX_PIN(32, 312),
MX31_PIN_SRST0 = IOMUX_PIN(67, 313),
MX31_PIN_SCLK0 = IOMUX_PIN(66, 314),
MX31_PIN_GPIO3_1 = IOMUX_PIN(65, 315),
MX31_PIN_GPIO3_0 = IOMUX_PIN(64, 316),
MX31_PIN_GPIO1_6 = IOMUX_PIN(6, 317),
MX31_PIN_GPIO1_5 = IOMUX_PIN(5, 318),
MX31_PIN_GPIO1_4 = IOMUX_PIN(4, 319),
MX31_PIN_GPIO1_3 = IOMUX_PIN(3, 320),
MX31_PIN_GPIO1_2 = IOMUX_PIN(2, 321),
MX31_PIN_GPIO1_1 = IOMUX_PIN(1, 322),
MX31_PIN_GPIO1_0 = IOMUX_PIN(0, 323),
MX31_PIN_PWMO = IOMUX_PIN(9, 324),
MX31_PIN_WATCHDOG_RST = IOMUX_PIN(0xff, 325),
MX31_PIN_COMPARE = IOMUX_PIN(8, 326),
MX31_PIN_CAPTURE = IOMUX_PIN(7, 327),
};
/*
* various IOMUX general purpose functions
*/
enum iomux_gp_func {
MUX_PGP_FIRI = 1 << 0,
MUX_DDR_MODE = 1 << 1,
MUX_PGP_CSPI_BB = 1 << 2,
MUX_PGP_ATA_1 = 1 << 3,
MUX_PGP_ATA_2 = 1 << 4,
MUX_PGP_ATA_3 = 1 << 5,
MUX_PGP_ATA_4 = 1 << 6,
MUX_PGP_ATA_5 = 1 << 7,
MUX_PGP_ATA_6 = 1 << 8,
MUX_PGP_ATA_7 = 1 << 9,
MUX_PGP_ATA_8 = 1 << 10,
MUX_PGP_UH2 = 1 << 11,
MUX_SDCTL_CSD0_SEL = 1 << 12,
MUX_SDCTL_CSD1_SEL = 1 << 13,
MUX_CSPI1_UART3 = 1 << 14,
MUX_EXTDMAREQ2_MBX_SEL = 1 << 15,
MUX_TAMPER_DETECT_EN = 1 << 16,
MUX_PGP_USB_4WIRE = 1 << 17,
MUX_PGP_USB_COMMON = 1 << 18,
MUX_SDHC_MEMSTICK1 = 1 << 19,
MUX_SDHC_MEMSTICK2 = 1 << 20,
MUX_PGP_SPLL_BYP = 1 << 21,
MUX_PGP_UPLL_BYP = 1 << 22,
MUX_PGP_MSHC1_CLK_SEL = 1 << 23,
MUX_PGP_MSHC2_CLK_SEL = 1 << 24,
MUX_CSPI3_UART5_SEL = 1 << 25,
MUX_PGP_ATA_9 = 1 << 26,
MUX_PGP_USB_SUSPEND = 1 << 27,
MUX_PGP_USB_OTG_LOOPBACK = 1 << 28,
MUX_PGP_USB_HS1_LOOPBACK = 1 << 29,
MUX_PGP_USB_HS2_LOOPBACK = 1 << 30,
MUX_CLKO_DDR_MODE = 1 << 31,
};
/* Bit definitions for RCSR register in CCM */
#define CCM_RCSR_NF16B (1 << 31)
#define CCM_RCSR_NFMS (1 << 30)
/* WEIM CS control registers */
struct mx31_weim_cscr {
u32 upper;
u32 lower;
u32 additional;
u32 reserved;
};
struct mx31_weim {
struct mx31_weim_cscr cscr[6];
};
/* ESD control registers */
struct esdc_regs {
u32 ctl0;
u32 cfg0;
u32 ctl1;
u32 cfg1;
u32 misc;
u32 dly[5];
u32 dlyl;
};
#endif
#define __REG(x) (*((volatile u32 *)(x)))
#define __REG16(x) (*((volatile u16 *)(x)))
#define __REG8(x) (*((volatile u8 *)(x)))
#define CCM_BASE 0x53f80000
#define CCM_CCMR (CCM_BASE + 0x00)
#define CCM_PDR0 (CCM_BASE + 0x04)
#define CCM_PDR1 (CCM_BASE + 0x08)
#define CCM_RCSR (CCM_BASE + 0x0c)
#define CCM_MPCTL (CCM_BASE + 0x10)
#define CCM_UPCTL (CCM_BASE + 0x14)
#define CCM_SPCTL (CCM_BASE + 0x18)
#define CCM_COSR (CCM_BASE + 0x1C)
#define CCM_CGR0 (CCM_BASE + 0x20)
#define CCM_CGR1 (CCM_BASE + 0x24)
#define CCM_CGR2 (CCM_BASE + 0x28)
#define CCMR_MDS (1 << 7)
#define CCMR_SBYCS (1 << 4)
#define CCMR_MPE (1 << 3)
#define CCMR_PRCS_MASK (3 << 1)
#define CCMR_FPM (1 << 1)
#define CCMR_CKIH (2 << 1)
#define MX31_IIM_BASE_ADDR 0x5001C000
#define PDR0_CSI_PODF(x) (((x) & 0x1ff) << 23)
#define PDR0_PER_PODF(x) (((x) & 0x1f) << 16)
#define PDR0_HSP_PODF(x) (((x) & 0x7) << 11)
#define PDR0_NFC_PODF(x) (((x) & 0x7) << 8)
#define PDR0_IPG_PODF(x) (((x) & 0x3) << 6)
#define PDR0_MAX_PODF(x) (((x) & 0x7) << 3)
#define PDR0_MCU_PODF(x) ((x) & 0x7)
#define PLL_PD(x) (((x) & 0xf) << 26)
#define PLL_MFD(x) (((x) & 0x3ff) << 16)
#define PLL_MFI(x) (((x) & 0xf) << 10)
#define PLL_MFN(x) (((x) & 0x3ff) << 0)
#define GET_PDR0_CSI_PODF(x) (((x) >> 23) & 0x1ff)
#define GET_PDR0_PER_PODF(x) (((x) >> 16) & 0x1f)
#define GET_PDR0_HSP_PODF(x) (((x) >> 11) & 0x7)
#define GET_PDR0_NFC_PODF(x) (((x) >> 8) & 0x7)
#define GET_PDR0_IPG_PODF(x) (((x) >> 6) & 0x3)
#define GET_PDR0_MAX_PODF(x) (((x) >> 3) & 0x7)
#define GET_PDR0_MCU_PODF(x) ((x) & 0x7)
#define GET_PLL_PD(x) (((x) >> 26) & 0xf)
#define GET_PLL_MFD(x) (((x) >> 16) & 0x3ff)
#define GET_PLL_MFI(x) (((x) >> 10) & 0xf)
#define GET_PLL_MFN(x) (((x) >> 0) & 0x3ff)
#define WEIM_ESDCTL0 0xB8001000
#define WEIM_ESDCFG0 0xB8001004
#define WEIM_ESDCTL1 0xB8001008
#define WEIM_ESDCFG1 0xB800100C
#define WEIM_ESDMISC 0xB8001010
#define UART1_BASE 0x43F90000
#define UART2_BASE 0x43F94000
#define UART3_BASE 0x5000C000
#define UART4_BASE 0x43FB0000
#define UART5_BASE 0x43FB4000
#define ESDCTL_SDE (1 << 31)
#define ESDCTL_CMD_RW (0 << 28)
#define ESDCTL_CMD_PRECHARGE (1 << 28)
#define ESDCTL_CMD_AUTOREFRESH (2 << 28)
#define ESDCTL_CMD_LOADMODEREG (3 << 28)
#define ESDCTL_CMD_MANUALREFRESH (4 << 28)
#define ESDCTL_ROW_13 (2 << 24)
#define ESDCTL_ROW(x) ((x) << 24)
#define ESDCTL_COL_9 (1 << 20)
#define ESDCTL_COL(x) ((x) << 20)
#define ESDCTL_DSIZ(x) ((x) << 16)
#define ESDCTL_SREFR(x) ((x) << 13)
#define ESDCTL_PWDT(x) ((x) << 10)
#define ESDCTL_FP(x) ((x) << 8)
#define ESDCTL_BL(x) ((x) << 7)
#define ESDCTL_PRCT(x) ((x) << 0)
#define ESDCTL_BASE_ADDR 0xB8001000
/* 13 fields of the upper CS control register */
#define CSCR_U(sp, wp, bcd, bcs, psz, pme, sync, dol, \
cnc, wsc, ew, wws, edc) \
((sp) << 31 | (wp) << 30 | (bcd) << 28 | (psz) << 22 | (pme) << 21 |\
(sync) << 20 | (dol) << 16 | (cnc) << 14 | (wsc) << 8 | (ew) << 7 |\
(wws) << 4 | (edc) << 0)
/* 12 fields of the lower CS control register */
#define CSCR_L(oea, oen, ebwa, ebwn, \
csa, ebc, dsz, csn, psr, cre, wrap, csen) \
((oea) << 28 | (oen) << 24 | (ebwa) << 20 | (ebwn) << 16 |\
(csa) << 12 | (ebc) << 11 | (dsz) << 8 | (csn) << 4 |\
(psr) << 3 | (cre) << 2 | (wrap) << 1 | (csen) << 0)
/* 14 fields of the additional CS control register */
#define CSCR_A(ebra, ebrn, rwa, rwn, mum, lah, lbn, lba, dww, dct, \
wwu, age, cnc2, fce) \
((ebra) << 28 | (ebrn) << 24 | (rwa) << 20 | (rwn) << 16 |\
(mum) << 15 | (lah) << 13 | (lbn) << 10 | (lba) << 8 |\
(dww) << 6 | (dct) << 4 | (wwu) << 3 |\
(age) << 2 | (cnc2) << 1 | (fce) << 0)
#define WEIM_BASE 0xb8002000
#define IOMUXC_BASE 0x43FAC000
#define IOMUXC_SW_MUX_CTL(x) (IOMUXC_BASE + 0xc + (x) * 4)
#define IOMUXC_SW_PAD_CTL(x) (IOMUXC_BASE + 0x154 + (x) * 4)
#define IPU_BASE 0x53fc0000
#define IPU_CONF IPU_BASE
#define IPU_CONF_PXL_ENDIAN (1<<8)
#define IPU_CONF_DU_EN (1<<7)
#define IPU_CONF_DI_EN (1<<6)
#define IPU_CONF_ADC_EN (1<<5)
#define IPU_CONF_SDC_EN (1<<4)
#define IPU_CONF_PF_EN (1<<3)
#define IPU_CONF_ROT_EN (1<<2)
#define IPU_CONF_IC_EN (1<<1)
#define IPU_CONF_SCI_EN (1<<0)
#define ARM_PPMRR 0x40000015
#define WDOG_BASE 0x53FDC000
/*
* GPIO
*/
#define GPIO1_BASE_ADDR 0x53FCC000
#define GPIO2_BASE_ADDR 0x53FD0000
#define GPIO3_BASE_ADDR 0x53FA4000
#define GPIO_DR 0x00000000 /* data register */
#define GPIO_GDIR 0x00000004 /* direction register */
#define GPIO_PSR 0x00000008 /* pad status register */
/*
* Signal Multiplexing (IOMUX)
*/
/* bits in the SW_MUX_CTL registers */
#define MUX_CTL_OUT_GPIO_DR (0 << 4)
#define MUX_CTL_OUT_FUNC (1 << 4)
#define MUX_CTL_OUT_ALT1 (2 << 4)
#define MUX_CTL_OUT_ALT2 (3 << 4)
#define MUX_CTL_OUT_ALT3 (4 << 4)
#define MUX_CTL_OUT_ALT4 (5 << 4)
#define MUX_CTL_OUT_ALT5 (6 << 4)
#define MUX_CTL_OUT_ALT6 (7 << 4)
#define MUX_CTL_IN_NONE (0 << 0)
#define MUX_CTL_IN_GPIO (1 << 0)
#define MUX_CTL_IN_FUNC (2 << 0)
#define MUX_CTL_IN_ALT1 (4 << 0)
#define MUX_CTL_IN_ALT2 (8 << 0)
#define MUX_CTL_FUNC (MUX_CTL_OUT_FUNC | MUX_CTL_IN_FUNC)
#define MUX_CTL_ALT1 (MUX_CTL_OUT_ALT1 | MUX_CTL_IN_ALT1)
#define MUX_CTL_ALT2 (MUX_CTL_OUT_ALT2 | MUX_CTL_IN_ALT2)
#define MUX_CTL_GPIO (MUX_CTL_OUT_GPIO_DR | MUX_CTL_IN_GPIO)
/* Register offsets based on IOMUXC_BASE */
/* 0x00 .. 0x7b */
#define MUX_CTL_CSPI3_MISO 0x0c
#define MUX_CTL_CSPI3_SCLK 0x0d
#define MUX_CTL_CSPI3_SPI_RDY 0x0e
#define MUX_CTL_CSPI3_MOSI 0x13
#define MUX_CTL_USBH2_DATA1 0x40
#define MUX_CTL_USBH2_DIR 0x44
#define MUX_CTL_USBH2_STP 0x45
#define MUX_CTL_USBH2_NXT 0x46
#define MUX_CTL_USBH2_DATA0 0x47
#define MUX_CTL_USBH2_CLK 0x4B
#define MUX_CTL_TXD2 0x70
#define MUX_CTL_RTS2 0x71
#define MUX_CTL_CTS2 0x72
#define MUX_CTL_RXD2 0x77
#define MUX_CTL_RTS1 0x7c
#define MUX_CTL_CTS1 0x7d
#define MUX_CTL_DTR_DCE1 0x7e
#define MUX_CTL_DSR_DCE1 0x7f
#define MUX_CTL_CSPI2_SCLK 0x80
#define MUX_CTL_CSPI2_SPI_RDY 0x81
#define MUX_CTL_RXD1 0x82
#define MUX_CTL_TXD1 0x83
#define MUX_CTL_CSPI2_MISO 0x84
#define MUX_CTL_CSPI2_SS0 0x85
#define MUX_CTL_CSPI2_SS1 0x86
#define MUX_CTL_CSPI2_SS2 0x87
#define MUX_CTL_CSPI1_SS2 0x88
#define MUX_CTL_CSPI1_SCLK 0x89
#define MUX_CTL_CSPI1_SPI_RDY 0x8a
#define MUX_CTL_CSPI2_MOSI 0x8b
#define MUX_CTL_CSPI1_MOSI 0x8c
#define MUX_CTL_CSPI1_MISO 0x8d
#define MUX_CTL_CSPI1_SS0 0x8e
#define MUX_CTL_CSPI1_SS1 0x8f
#define MUX_CTL_STXD6 0x90
#define MUX_CTL_SRXD6 0x91
#define MUX_CTL_SCK6 0x92
#define MUX_CTL_SFS6 0x93
#define MUX_CTL_STXD3 0x9C
#define MUX_CTL_SRXD3 0x9D
#define MUX_CTL_SCK3 0x9E
#define MUX_CTL_SFS3 0x9F
#define MUX_CTL_NFC_WP 0xD0
#define MUX_CTL_NFC_CE 0xD1
#define MUX_CTL_NFC_RB 0xD2
#define MUX_CTL_NFC_WE 0xD4
#define MUX_CTL_NFC_RE 0xD5
#define MUX_CTL_NFC_ALE 0xD6
#define MUX_CTL_NFC_CLE 0xD7
#define MUX_CTL_CAPTURE 0x150
#define MUX_CTL_COMPARE 0x151
/*
* Helper macros for the MUX_[contact name]__[pin function] macros
*/
#define IOMUX_MODE_POS 9
#define IOMUX_MODE(contact, mode) (((mode) << IOMUX_MODE_POS) | (contact))
/*
* These macros can be used in mx31_gpio_mux() and have the form
* MUX_[contact name]__[pin function]
*/
#define MUX_RXD1__UART1_RXD_MUX IOMUX_MODE(MUX_CTL_RXD1, MUX_CTL_FUNC)
#define MUX_TXD1__UART1_TXD_MUX IOMUX_MODE(MUX_CTL_TXD1, MUX_CTL_FUNC)
#define MUX_RTS1__UART1_RTS_B IOMUX_MODE(MUX_CTL_RTS1, MUX_CTL_FUNC)
#define MUX_CTS1__UART1_CTS_B IOMUX_MODE(MUX_CTL_CTS1, MUX_CTL_FUNC)
#define MUX_RXD2__UART2_RXD_MUX IOMUX_MODE(MUX_CTL_RXD2, MUX_CTL_FUNC)
#define MUX_TXD2__UART2_TXD_MUX IOMUX_MODE(MUX_CTL_TXD2, MUX_CTL_FUNC)
#define MUX_RTS2__UART2_RTS_B IOMUX_MODE(MUX_CTL_RTS2, MUX_CTL_FUNC)
#define MUX_CTS2__UART2_CTS_B IOMUX_MODE(MUX_CTL_CTS2, MUX_CTL_FUNC)
#define MUX_CSPI2_SS0__CSPI2_SS0_B IOMUX_MODE(MUX_CTL_CSPI2_SS0, MUX_CTL_FUNC)
#define MUX_CSPI2_SS1__CSPI2_SS1_B IOMUX_MODE(MUX_CTL_CSPI2_SS1, MUX_CTL_FUNC)
#define MUX_CSPI2_SS2__CSPI2_SS2_B IOMUX_MODE(MUX_CTL_CSPI2_SS2, MUX_CTL_FUNC)
#define MUX_CSPI2_MOSI__CSPI2_MOSI IOMUX_MODE(MUX_CTL_CSPI2_MOSI, MUX_CTL_FUNC)
#define MUX_CSPI2_MISO__CSPI2_MISO IOMUX_MODE(MUX_CTL_CSPI2_MISO, MUX_CTL_FUNC)
#define MUX_CSPI2_SPI_RDY__CSPI2_DATAREADY_B \
IOMUX_MODE(MUX_CTL_CSPI2_SPI_RDY, MUX_CTL_FUNC)
#define MUX_CSPI2_SCLK__CSPI2_CLK IOMUX_MODE(MUX_CTL_CSPI2_SCLK, MUX_CTL_FUNC)
#define MUX_CSPI1_SS0__CSPI1_SS0_B IOMUX_MODE(MUX_CTL_CSPI1_SS0, MUX_CTL_FUNC)
#define MUX_CSPI1_SS1__CSPI1_SS1_B IOMUX_MODE(MUX_CTL_CSPI1_SS1, MUX_CTL_FUNC)
#define MUX_CSPI1_SS2__CSPI1_SS2_B IOMUX_MODE(MUX_CTL_CSPI1_SS2, MUX_CTL_FUNC)
#define MUX_CSPI1_MOSI__CSPI1_MOSI IOMUX_MODE(MUX_CTL_CSPI1_MOSI, MUX_CTL_FUNC)
#define MUX_CSPI1_MISO__CSPI1_MISO IOMUX_MODE(MUX_CTL_CSPI1_MISO, MUX_CTL_FUNC)
#define MUX_CSPI1_SPI_RDY__CSPI1_DATAREADY_B \
IOMUX_MODE(MUX_CTL_CSPI1_SPI_RDY, MUX_CTL_FUNC)
#define MUX_CSPI1_SCLK__CSPI1_CLK IOMUX_MODE(MUX_CTL_CSPI1_SCLK, MUX_CTL_FUNC)
#define MUX_CSPI2_MOSI__I2C2_SCL IOMUX_MODE(MUX_CTL_CSPI2_MOSI, MUX_CTL_ALT1)
#define MUX_CSPI2_MISO__I2C2_SDA IOMUX_MODE(MUX_CTL_CSPI2_MISO, MUX_CTL_ALT1)
/* PAD control registers for SDR/DDR */
#define IOMUXC_SW_PAD_CTL_SDCKE1_SDCLK_SDCLK_B (IOMUXC_BASE + 0x26C)
#define IOMUXC_SW_PAD_CTL_CAS_SDWE_SDCKE0 (IOMUXC_BASE + 0x270)
#define IOMUXC_SW_PAD_CTL_BCLK_RW_RAS (IOMUXC_BASE + 0x274)
#define IOMUXC_SW_PAD_CTL_CS5_ECB_LBA (IOMUXC_BASE + 0x278)
#define IOMUXC_SW_PAD_CTL_CS2_CS3_CS4 (IOMUXC_BASE + 0x27C)
#define IOMUXC_SW_PAD_CTL_OE_CS0_CS1 (IOMUXC_BASE + 0x280)
#define IOMUXC_SW_PAD_CTL_DQM3_EB0_EB1 (IOMUXC_BASE + 0x284)
#define IOMUXC_SW_PAD_CTL_DQM0_DQM1_DQM2 (IOMUXC_BASE + 0x288)
#define IOMUXC_SW_PAD_CTL_SD29_SD30_SD31 (IOMUXC_BASE + 0x28C)
#define IOMUXC_SW_PAD_CTL_SD26_SD27_SD28 (IOMUXC_BASE + 0x290)
#define IOMUXC_SW_PAD_CTL_SD23_SD24_SD25 (IOMUXC_BASE + 0x294)
#define IOMUXC_SW_PAD_CTL_SD20_SD21_SD22 (IOMUXC_BASE + 0x298)
#define IOMUXC_SW_PAD_CTL_SD17_SD18_SD19 (IOMUXC_BASE + 0x29C)
#define IOMUXC_SW_PAD_CTL_SD14_SD15_SD16 (IOMUXC_BASE + 0x2A0)
#define IOMUXC_SW_PAD_CTL_SD11_SD12_SD13 (IOMUXC_BASE + 0x2A4)
#define IOMUXC_SW_PAD_CTL_SD8_SD9_SD10 (IOMUXC_BASE + 0x2A8)
#define IOMUXC_SW_PAD_CTL_SD5_SD6_SD7 (IOMUXC_BASE + 0x2AC)
#define IOMUXC_SW_PAD_CTL_SD2_SD3_SD4 (IOMUXC_BASE + 0x2B0)
#define IOMUXC_SW_PAD_CTL_SDBA0_SD0_SD1 (IOMUXC_BASE + 0x2B4)
#define IOMUXC_SW_PAD_CTL_A24_A25_SDBA1 (IOMUXC_BASE + 0x2B8)
#define IOMUXC_SW_PAD_CTL_A21_A22_A23 (IOMUXC_BASE + 0x2BC)
#define IOMUXC_SW_PAD_CTL_A18_A19_A20 (IOMUXC_BASE + 0x2C0)
#define IOMUXC_SW_PAD_CTL_A15_A16_A17 (IOMUXC_BASE + 0x2C4)
#define IOMUXC_SW_PAD_CTL_A12_A13_A14 (IOMUXC_BASE + 0x2C8)
#define IOMUXC_SW_PAD_CTL_A10_MA10_A11 (IOMUXC_BASE + 0x2CC)
#define IOMUXC_SW_PAD_CTL_A7_A8_A9 (IOMUXC_BASE + 0x2D0)
#define IOMUXC_SW_PAD_CTL_A4_A5_A6 (IOMUXC_BASE + 0x2D4)
#define IOMUXC_SW_PAD_CTL_A1_A2_A3 (IOMUXC_BASE + 0x2D8)
#define IOMUXC_SW_PAD_CTL_VPG0_VPG1_A0 (IOMUXC_BASE + 0x2DC)
/*
* Memory regions and CS
*/
#define IPU_MEM_BASE 0x70000000
#define CSD0_BASE 0x80000000
#define CSD1_BASE 0x90000000
#define CS0_BASE 0xA0000000
#define CS1_BASE 0xA8000000
#define CS2_BASE 0xB0000000
#define CS3_BASE 0xB2000000
#define CS4_BASE 0xB4000000
#define CS4_PSRAM_BASE 0xB5000000
#define CS5_BASE 0xB6000000
#define PCMCIA_MEM_BASE 0xC0000000
/*
* NAND controller
*/
#define NFC_BASE_ADDR 0xB8000000
/*
* Internal RAM (16KB)
*/
#define IRAM_BASE_ADDR 0x1FFFC000
#define IRAM_SIZE (16 * 1024)
#define MX31_AIPS1_BASE_ADDR 0x43f00000
#define IMX_USB_BASE (MX31_AIPS1_BASE_ADDR + 0x88000)
/* USB portsc */
/* values for portsc field */
#define MXC_EHCI_PHY_LOW_POWER_SUSPEND (1 << 23)
#define MXC_EHCI_FORCE_FS (1 << 24)
#define MXC_EHCI_UTMI_8BIT (0 << 28)
#define MXC_EHCI_UTMI_16BIT (1 << 28)
#define MXC_EHCI_SERIAL (1 << 29)
#define MXC_EHCI_MODE_UTMI (0 << 30)
#define MXC_EHCI_MODE_PHILIPS (1 << 30)
#define MXC_EHCI_MODE_ULPI (2 << 30)
#define MXC_EHCI_MODE_SERIAL (3 << 30)
/* values for flags field */
#define MXC_EHCI_INTERFACE_DIFF_UNI (0 << 0)
#define MXC_EHCI_INTERFACE_DIFF_BI (1 << 0)
#define MXC_EHCI_INTERFACE_SINGLE_UNI (2 << 0)
#define MXC_EHCI_INTERFACE_SINGLE_BI (3 << 0)
#define MXC_EHCI_INTERFACE_MASK (0xf)
#define MXC_EHCI_POWER_PINS_ENABLED (1 << 5)
#define MXC_EHCI_TTL_ENABLED (1 << 6)
#define MXC_EHCI_INTERNAL_PHY (1 << 7)
#define MXC_EHCI_IPPUE_DOWN (1 << 8)
#define MXC_EHCI_IPPUE_UP (1 << 9)
#endif /* __ASM_ARCH_MX31_IMX_REGS_H */
| michaelkebe/u-boot-medion-p89626 | arch/arm/include/asm/arch-mx31/imx-regs.h | C | gpl-2.0 | 30,492 |
/*
* Copyright (c) 2012, 2015, 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 com.sun.hotspot.igv.data.serialization;
import com.sun.hotspot.igv.data.*;
import com.sun.hotspot.igv.data.Properties;
import com.sun.hotspot.igv.data.services.GroupCallback;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.SwingUtilities;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class BinaryParser implements GraphParser {
private static final int BEGIN_GROUP = 0x00;
private static final int BEGIN_GRAPH = 0x01;
private static final int CLOSE_GROUP = 0x02;
private static final int POOL_NEW = 0x00;
private static final int POOL_STRING = 0x01;
private static final int POOL_ENUM = 0x02;
private static final int POOL_CLASS = 0x03;
private static final int POOL_METHOD = 0x04;
private static final int POOL_NULL = 0x05;
private static final int POOL_NODE_CLASS = 0x06;
private static final int POOL_FIELD = 0x07;
private static final int POOL_SIGNATURE = 0x08;
private static final int KLASS = 0x00;
private static final int ENUM_KLASS = 0x01;
private static final int PROPERTY_POOL = 0x00;
private static final int PROPERTY_INT = 0x01;
private static final int PROPERTY_LONG = 0x02;
private static final int PROPERTY_DOUBLE = 0x03;
private static final int PROPERTY_FLOAT = 0x04;
private static final int PROPERTY_TRUE = 0x05;
private static final int PROPERTY_FALSE = 0x06;
private static final int PROPERTY_ARRAY = 0x07;
private static final int PROPERTY_SUBGRAPH = 0x08;
private static final String NO_BLOCK = "noBlock";
private final GroupCallback callback;
private final List<Object> constantPool;
private final ByteBuffer buffer;
private final ReadableByteChannel channel;
private final GraphDocument rootDocument;
private final Deque<Folder> folderStack;
private final Deque<byte[]> hashStack;
private final ParseMonitor monitor;
private MessageDigest digest;
private enum Length {
S,
M,
L
}
private interface LengthToString {
String toString(Length l);
}
private static abstract class Member implements LengthToString {
public final Klass holder;
public final int accessFlags;
public final String name;
public Member(Klass holder, String name, int accessFlags) {
this.holder = holder;
this.accessFlags = accessFlags;
this.name = name;
}
}
private static class Method extends Member {
public final Signature signature;
public final byte[] code;
public Method(String name, Signature signature, byte[] code, Klass holder, int accessFlags) {
super(holder, name, accessFlags);
this.signature = signature;
this.code = code;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(holder).append('.').append(name).append('(');
for (int i = 0; i < signature.argTypes.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(signature.argTypes[i]);
}
sb.append(')');
return sb.toString();
}
@Override
public String toString(Length l) {
switch(l) {
case M:
return holder.toString(Length.L) + "." + name;
case S:
return holder.toString(Length.S) + "." + name;
default:
case L:
return toString();
}
}
}
private static class Signature {
public final String returnType;
public final String[] argTypes;
public Signature(String returnType, String[] argTypes) {
this.returnType = returnType;
this.argTypes = argTypes;
}
}
private static class Field extends Member {
public final String type;
public Field(String type, Klass holder, String name, int accessFlags) {
super(holder, name, accessFlags);
this.type = type;
}
@Override
public String toString() {
return holder + "." + name;
}
@Override
public String toString(Length l) {
switch(l) {
case M:
return holder.toString(Length.L) + "." + name;
case S:
return holder.toString(Length.S) + "." + name;
default:
case L:
return toString();
}
}
}
private static class Klass implements LengthToString {
public final String name;
public final String simpleName;
public Klass(String name) {
this.name = name;
String simple;
try {
simple = name.substring(name.lastIndexOf('.') + 1);
} catch (IndexOutOfBoundsException ioobe) {
simple = name;
}
this.simpleName = simple;
}
@Override
public String toString() {
return name;
}
@Override
public String toString(Length l) {
switch(l) {
case S:
return simpleName;
default:
case L:
case M:
return toString();
}
}
}
private static class EnumKlass extends Klass {
public final String[] values;
public EnumKlass(String name, String[] values) {
super(name);
this.values = values;
}
}
private static class Port {
public final boolean isList;
public final String name;
private Port(boolean isList, String name) {
this.isList = isList;
this.name = name;
}
}
private static class TypedPort extends Port {
public final EnumValue type;
private TypedPort(boolean isList, String name, EnumValue type) {
super(isList, name);
this.type = type;
}
}
private static class NodeClass {
public final String className;
public final String nameTemplate;
public final List<TypedPort> inputs;
public final List<Port> sux;
private NodeClass(String className, String nameTemplate, List<TypedPort> inputs, List<Port> sux) {
this.className = className;
this.nameTemplate = nameTemplate;
this.inputs = inputs;
this.sux = sux;
}
@Override
public String toString() {
return className;
}
}
private static class EnumValue implements LengthToString {
public EnumKlass enumKlass;
public int ordinal;
public EnumValue(EnumKlass enumKlass, int ordinal) {
this.enumKlass = enumKlass;
this.ordinal = ordinal;
}
@Override
public String toString() {
return enumKlass.simpleName + "." + enumKlass.values[ordinal];
}
@Override
public String toString(Length l) {
switch(l) {
case S:
return enumKlass.values[ordinal];
default:
case M:
case L:
return toString();
}
}
}
public BinaryParser(ReadableByteChannel channel, ParseMonitor monitor, GraphDocument rootDocument, GroupCallback callback) {
this.callback = callback;
constantPool = new ArrayList<>();
buffer = ByteBuffer.allocateDirect(256 * 1024);
buffer.flip();
this.channel = channel;
this.rootDocument = rootDocument;
folderStack = new LinkedList<>();
hashStack = new LinkedList<>();
this.monitor = monitor;
try {
this.digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
}
}
private void fill() throws IOException {
buffer.compact();
if (channel.read(buffer) < 0) {
throw new EOFException();
}
buffer.flip();
}
private void ensureAvailable(int i) throws IOException {
while (buffer.remaining() < i) {
fill();
}
buffer.mark();
byte[] result = new byte[i];
buffer.get(result);
digest.update(result);
buffer.reset();
}
private int readByte() throws IOException {
ensureAvailable(1);
return ((int)buffer.get()) & 0xff;
}
private int readInt() throws IOException {
ensureAvailable(4);
return buffer.getInt();
}
private char readShort() throws IOException {
ensureAvailable(2);
return buffer.getChar();
}
private long readLong() throws IOException {
ensureAvailable(8);
return buffer.getLong();
}
private double readDouble() throws IOException {
ensureAvailable(8);
return buffer.getDouble();
}
private float readFloat() throws IOException {
ensureAvailable(4);
return buffer.getFloat();
}
private String readString() throws IOException {
int len = readInt();
ensureAvailable(len * 2);
char[] chars = new char[len];
buffer.asCharBuffer().get(chars);
buffer.position(buffer.position() + len * 2);
return new String(chars).intern();
}
private byte[] readBytes() throws IOException {
int len = readInt();
if (len < 0) {
return null;
}
ensureAvailable(len);
byte[] data = new byte[len];
buffer.get(data);
return data;
}
private String readIntsToString() throws IOException {
int len = readInt();
if (len < 0) {
return "null";
}
ensureAvailable(len * 4);
StringBuilder sb = new StringBuilder().append('[');
for (int i = 0; i < len; i++) {
sb.append(buffer.getInt());
if (i < len - 1) {
sb.append(", ");
}
}
sb.append(']');
return sb.toString().intern();
}
private String readDoublesToString() throws IOException {
int len = readInt();
if (len < 0) {
return "null";
}
ensureAvailable(len * 8);
StringBuilder sb = new StringBuilder().append('[');
for (int i = 0; i < len; i++) {
sb.append(buffer.getDouble());
if (i < len - 1) {
sb.append(", ");
}
}
sb.append(']');
return sb.toString().intern();
}
private String readPoolObjectsToString() throws IOException {
int len = readInt();
if (len < 0) {
return "null";
}
StringBuilder sb = new StringBuilder().append('[');
for (int i = 0; i < len; i++) {
sb.append(readPoolObject(Object.class));
if (i < len - 1) {
sb.append(", ");
}
}
sb.append(']');
return sb.toString().intern();
}
private <T> T readPoolObject(Class<T> klass) throws IOException {
int type = readByte();
if (type == POOL_NULL) {
return null;
}
if (type == POOL_NEW) {
return (T) addPoolEntry(klass);
}
assert assertObjectType(klass, type);
char index = readShort();
if (index < 0 || index >= constantPool.size()) {
throw new IOException("Invalid constant pool index : " + index);
}
Object obj = constantPool.get(index);
return (T) obj;
}
private boolean assertObjectType(Class<?> klass, int type) {
switch(type) {
case POOL_CLASS:
return klass.isAssignableFrom(EnumKlass.class);
case POOL_ENUM:
return klass.isAssignableFrom(EnumValue.class);
case POOL_METHOD:
return klass.isAssignableFrom(Method.class);
case POOL_STRING:
return klass.isAssignableFrom(String.class);
case POOL_NODE_CLASS:
return klass.isAssignableFrom(NodeClass.class);
case POOL_FIELD:
return klass.isAssignableFrom(Field.class);
case POOL_SIGNATURE:
return klass.isAssignableFrom(Signature.class);
case POOL_NULL:
return true;
default:
return false;
}
}
private Object addPoolEntry(Class<?> klass) throws IOException {
char index = readShort();
int type = readByte();
assert assertObjectType(klass, type) : "Wrong object type : " + klass + " != " + type;
Object obj;
switch(type) {
case POOL_CLASS: {
String name = readString();
int klasstype = readByte();
if (klasstype == ENUM_KLASS) {
int len = readInt();
String[] values = new String[len];
for (int i = 0; i < len; i++) {
values[i] = readPoolObject(String.class);
}
obj = new EnumKlass(name, values);
} else if (klasstype == KLASS) {
obj = new Klass(name);
} else {
throw new IOException("unknown klass type : " + klasstype);
}
break;
}
case POOL_ENUM: {
EnumKlass enumClass = readPoolObject(EnumKlass.class);
int ordinal = readInt();
obj = new EnumValue(enumClass, ordinal);
break;
}
case POOL_NODE_CLASS: {
String className = readString();
String nameTemplate = readString();
int inputCount = readShort();
List<TypedPort> inputs = new ArrayList<>(inputCount);
for (int i = 0; i < inputCount; i++) {
boolean isList = readByte() != 0;
String name = readPoolObject(String.class);
EnumValue inputType = readPoolObject(EnumValue.class);
inputs.add(new TypedPort(isList, name, inputType));
}
int suxCount = readShort();
List<Port> sux = new ArrayList<>(suxCount);
for (int i = 0; i < suxCount; i++) {
boolean isList = readByte() != 0;
String name = readPoolObject(String.class);
sux.add(new Port(isList, name));
}
obj = new NodeClass(className, nameTemplate, inputs, sux);
break;
}
case POOL_METHOD: {
Klass holder = readPoolObject(Klass.class);
String name = readPoolObject(String.class);
Signature sign = readPoolObject(Signature.class);
int flags = readInt();
byte[] code = readBytes();
obj = new Method(name, sign, code, holder, flags);
break;
}
case POOL_FIELD: {
Klass holder = readPoolObject(Klass.class);
String name = readPoolObject(String.class);
String fType = readPoolObject(String.class);
int flags = readInt();
obj = new Field(fType, holder, name, flags);
break;
}
case POOL_SIGNATURE: {
int argc = readShort();
String[] args = new String[argc];
for (int i = 0; i < argc; i++) {
args[i] = readPoolObject(String.class);
}
String returnType = readPoolObject(String.class);
obj = new Signature(returnType, args);
break;
}
case POOL_STRING: {
obj = readString();
break;
}
default:
throw new IOException("unknown pool type");
}
while (constantPool.size() <= index) {
constantPool.add(null);
}
constantPool.set(index, obj);
return obj;
}
private Object readPropertyObject() throws IOException {
int type = readByte();
switch (type) {
case PROPERTY_INT:
return readInt();
case PROPERTY_LONG:
return readLong();
case PROPERTY_FLOAT:
return readFloat();
case PROPERTY_DOUBLE:
return readDouble();
case PROPERTY_TRUE:
return Boolean.TRUE;
case PROPERTY_FALSE:
return Boolean.FALSE;
case PROPERTY_POOL:
return readPoolObject(Object.class);
case PROPERTY_ARRAY:
int subType = readByte();
switch(subType) {
case PROPERTY_INT:
return readIntsToString();
case PROPERTY_DOUBLE:
return readDoublesToString();
case PROPERTY_POOL:
return readPoolObjectsToString();
default:
throw new IOException("Unknown type");
}
case PROPERTY_SUBGRAPH:
InputGraph graph = parseGraph("");
new Group(null).addElement(graph);
return graph;
default:
throw new IOException("Unknown type");
}
}
@Override
public GraphDocument parse() throws IOException {
folderStack.push(rootDocument);
hashStack.push(null);
if (monitor != null) {
monitor.setState("Starting parsing");
}
try {
while(true) {
parseRoot();
}
} catch (EOFException e) {
}
if (monitor != null) {
monitor.setState("Finished parsing");
}
return rootDocument;
}
private void parseRoot() throws IOException {
int type = readByte();
switch(type) {
case BEGIN_GRAPH: {
final Folder parent = folderStack.peek();
final InputGraph graph = parseGraph();
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
parent.addElement(graph);
}
});
break;
}
case BEGIN_GROUP: {
final Folder parent = folderStack.peek();
final Group group = parseGroup(parent);
if (callback == null || parent instanceof Group) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
parent.addElement(group);
}
});
}
folderStack.push(group);
hashStack.push(null);
if (callback != null && parent instanceof GraphDocument) {
callback.started(group);
}
break;
}
case CLOSE_GROUP: {
if (folderStack.isEmpty()) {
throw new IOException("Unbalanced groups");
}
folderStack.pop();
hashStack.pop();
break;
}
default:
throw new IOException("unknown root : " + type);
}
}
private Group parseGroup(Folder parent) throws IOException {
String name = readPoolObject(String.class);
String shortName = readPoolObject(String.class);
if (monitor != null) {
monitor.setState(shortName);
}
Method method = readPoolObject(Method.class);
int bci = readInt();
Group group = new Group(parent);
group.getProperties().setProperty("name", name);
if (method != null) {
InputMethod inMethod = new InputMethod(group, method.name, shortName, bci);
inMethod.setBytecodes("TODO");
group.setMethod(inMethod);
}
return group;
}
private InputGraph parseGraph() throws IOException {
if (monitor != null) {
monitor.updateProgress();
}
String title = readPoolObject(String.class);
digest.reset();
InputGraph graph = parseGraph(title);
byte[] d = digest.digest();
byte[] hash = hashStack.peek();
if (hash != null && Arrays.equals(hash, d)) {
graph.getProperties().setProperty("_isDuplicate", "true");
} else {
hashStack.pop();
hashStack.push(d);
}
return graph;
}
private InputGraph parseGraph(String title) throws IOException {
InputGraph graph = new InputGraph(title);
parseNodes(graph);
parseBlocks(graph);
graph.ensureNodesInBlocks();
return graph;
}
private void parseBlocks(InputGraph graph) throws IOException {
int blockCount = readInt();
List<Edge> edges = new LinkedList<>();
for (int i = 0; i < blockCount; i++) {
int id = readInt();
String name = id >= 0 ? Integer.toString(id) : NO_BLOCK;
InputBlock block = graph.addBlock(name);
int nodeCount = readInt();
for (int j = 0; j < nodeCount; j++) {
int nodeId = readInt();
if (nodeId < 0) {
continue;
}
final Properties properties = graph.getNode(nodeId).getProperties();
final String oldBlock = properties.get("block");
if(oldBlock != null) {
properties.setProperty("block", oldBlock + ", " + name);
} else {
block.addNode(nodeId);
properties.setProperty("block", name);
}
}
int edgeCount = readInt();
for (int j = 0; j < edgeCount; j++) {
int to = readInt();
edges.add(new Edge(id, to));
}
}
for (Edge e : edges) {
String fromName = e.from >= 0 ? Integer.toString(e.from) : NO_BLOCK;
String toName = e.to >= 0 ? Integer.toString(e.to) : NO_BLOCK;
graph.addBlockEdge(graph.getBlock(fromName), graph.getBlock(toName));
}
}
private void parseNodes(InputGraph graph) throws IOException {
int count = readInt();
Map<String, Object> props = new HashMap<>();
List<Edge> inputEdges = new ArrayList<>(count);
List<Edge> succEdges = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
int id = readInt();
InputNode node = new InputNode(id);
final Properties properties = node.getProperties();
NodeClass nodeClass = readPoolObject(NodeClass.class);
int preds = readByte();
if (preds > 0) {
properties.setProperty("hasPredecessor", "true");
}
properties.setProperty("idx", Integer.toString(id));
int propCount = readShort();
for (int j = 0; j < propCount; j++) {
String key = readPoolObject(String.class);
if (key.equals("hasPredecessor") || key.equals("name") || key.equals("class") || key.equals("id") || key.equals("idx")) {
key = "!data." + key;
}
Object value = readPropertyObject();
if (value instanceof InputGraph) {
InputGraph subgraph = (InputGraph) value;
subgraph.getProperties().setProperty("name", node.getId() + ":" + key);
node.addSubgraph((InputGraph) value);
} else {
properties.setProperty(key, value != null ? value.toString() : "null");
props.put(key, value);
}
}
ArrayList<Edge> currentEdges = new ArrayList<>();
int portNum = 0;
for (TypedPort p : nodeClass.inputs) {
if (p.isList) {
int size = readShort();
for (int j = 0; j < size; j++) {
int in = readInt();
if (in >= 0) {
Edge e = new Edge(in, id, (char) (preds + portNum), p.name + "[" + j + "]", p.type.toString(Length.S), true);
currentEdges.add(e);
inputEdges.add(e);
portNum++;
}
}
} else {
int in = readInt();
if (in >= 0) {
Edge e = new Edge(in, id, (char) (preds + portNum), p.name, p.type.toString(Length.S), true);
currentEdges.add(e);
inputEdges.add(e);
portNum++;
}
}
}
portNum = 0;
for (Port p : nodeClass.sux) {
if (p.isList) {
int size = readShort();
for (int j = 0; j < size; j++) {
int sux = readInt();
if (sux >= 0) {
Edge e = new Edge(id, sux, (char) portNum, p.name + "[" + j + "]", "Successor", false);
currentEdges.add(e);
succEdges.add(e);
portNum++;
}
}
} else {
int sux = readInt();
if (sux >= 0) {
Edge e = new Edge(id, sux, (char) portNum, p.name, "Successor", false);
currentEdges.add(e);
succEdges.add(e);
portNum++;
}
}
}
properties.setProperty("name", createName(currentEdges, props, nodeClass.nameTemplate));
properties.setProperty("class", nodeClass.className);
switch (nodeClass.className) {
case "BeginNode":
properties.setProperty("shortName", "B");
break;
case "EndNode":
properties.setProperty("shortName", "E");
break;
}
graph.addNode(node);
props.clear();
}
Set<InputNode> nodesWithSuccessor = new HashSet<>();
for (Edge e : succEdges) {
assert !e.input;
char fromIndex = e.num;
nodesWithSuccessor.add(graph.getNode(e.from));
char toIndex = 0;
graph.addEdge(InputEdge.createImmutable(fromIndex, toIndex, e.from, e.to, e.label, e.type));
}
for (Edge e : inputEdges) {
assert e.input;
char fromIndex = (char) (nodesWithSuccessor.contains(graph.getNode(e.from)) ? 1 : 0);
char toIndex = e.num;
graph.addEdge(InputEdge.createImmutable(fromIndex, toIndex, e.from, e.to, e.label, e.type));
}
}
private String createName(List<Edge> edges, Map<String, Object> properties, String template) {
Pattern p = Pattern.compile("\\{(p|i)#([a-zA-Z0-9$_]+)(/(l|m|s))?\\}");
Matcher m = p.matcher(template);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String name = m.group(2);
String type = m.group(1);
String result;
switch (type) {
case "i":
StringBuilder inputString = new StringBuilder();
for(Edge edge : edges) {
if (edge.label.startsWith(name) && (name.length() == edge.label.length() || edge.label.charAt(name.length()) == '[')) {
if (inputString.length() > 0) {
inputString.append(", ");
}
inputString.append(edge.from);
}
}
result = inputString.toString();
break;
case "p":
Object prop = properties.get(name);
String length = m.group(4);
if (prop == null) {
result = "?";
} else if (length != null && prop instanceof LengthToString) {
LengthToString lengthProp = (LengthToString) prop;
switch(length) {
default:
case "l":
result = lengthProp.toString(Length.L);
break;
case "m":
result = lengthProp.toString(Length.M);
break;
case "s":
result = lengthProp.toString(Length.S);
break;
}
} else {
result = prop.toString();
}
break;
default:
result = "#?#";
break;
}
result = result.replace("\\", "\\\\");
result = result.replace("$", "\\$");
m.appendReplacement(sb, result);
}
m.appendTail(sb);
return sb.toString().intern();
}
private static class Edge {
final int from;
final int to;
final char num;
final String label;
final String type;
final boolean input;
public Edge(int from, int to) {
this(from, to, (char) 0, null, null, false);
}
public Edge(int from, int to, char num, String label, String type, boolean input) {
this.from = from;
this.to = to;
this.label = label != null ? label.intern() : label;
this.type = type != null ? type.intern() : type;
this.num = num;
this.input = input;
}
}
}
| benbenolson/hotspot_9_mc | src/share/tools/IdealGraphVisualizer/Data/src/com/sun/hotspot/igv/data/serialization/BinaryParser.java | Java | gpl-2.0 | 32,231 |
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedReader;
import java.util.HashMap;
public class ParameterChecker {
HashMap<String,String[]> map = new HashMap<String,String[]>();
public ParameterChecker(BufferedReader reader) throws Exception {
String s;
while ((s = reader.readLine()) != null) {
String[] tokens = s.split("\\s");
map.put(tokens[0], tokens);
}
}
public String[] getChecks(String functionName) {
String[] checks = map.get(functionName);
if (checks == null &&
(functionName.endsWith("fv") ||
functionName.endsWith("xv") ||
functionName.endsWith("iv"))) {
functionName = functionName.substring(0, functionName.length() - 2);
checks = map.get(functionName);
}
return checks;
}
}
| rex-xxx/mt6572_x201 | frameworks/native/opengl/tools/glgen/src/ParameterChecker.java | Java | gpl-2.0 | 1,452 |
/*
* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
* Copyright (C) 2012-2013 Sony Mobile Communications AB.
*
* 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/regulator/pm8xxx-regulator.h>
#include "board-8064.h"
#define VREG_CONSUMERS(_id) \
static struct regulator_consumer_supply vreg_consumers_##_id[]
/* Regulators that are present when using either PM8921 or PM8917 */
/*
* Consumer specific regulator names:
* regulator name consumer dev_name
*/
VREG_CONSUMERS(L1) = {
REGULATOR_SUPPLY("8921_l1", NULL),
};
VREG_CONSUMERS(L2) = {
REGULATOR_SUPPLY("8921_l2", NULL),
REGULATOR_SUPPLY("mipi_csi_vdd", "msm_csid.0"),
REGULATOR_SUPPLY("mipi_csi_vdd", "msm_csid.1"),
REGULATOR_SUPPLY("mipi_csi_vdd", "msm_csid.2"),
REGULATOR_SUPPLY("lvds_pll_vdda", "lvds.0"),
REGULATOR_SUPPLY("dsi1_pll_vdda", "mipi_dsi.1"),
REGULATOR_SUPPLY("HRD_VDDD_CDC_D", "tabla2x-slim"),
REGULATOR_SUPPLY("HRD_CDC_VDDA_A_1P2V", "tabla2x-slim"),
REGULATOR_SUPPLY("dsi_pll_vdda", "mdp.0"),
};
VREG_CONSUMERS(L3) = {
REGULATOR_SUPPLY("8921_l3", NULL),
REGULATOR_SUPPLY("HSUSB_3p3", "msm_otg"),
REGULATOR_SUPPLY("HSUSB_3p3", "msm_ehci_host.0"),
};
VREG_CONSUMERS(L4) = {
REGULATOR_SUPPLY("8921_l4", NULL),
REGULATOR_SUPPLY("HSUSB_1p8", "msm_otg"),
REGULATOR_SUPPLY("iris_vddxo", "wcnss_wlan.0"),
};
VREG_CONSUMERS(L5) = {
REGULATOR_SUPPLY("8921_l5", NULL),
REGULATOR_SUPPLY("sdc_vdd", "msm_sdcc.1"),
};
VREG_CONSUMERS(L6) = {
REGULATOR_SUPPLY("8921_l6", NULL),
REGULATOR_SUPPLY("sdc_vdd", "msm_sdcc.3"),
};
VREG_CONSUMERS(L7) = {
REGULATOR_SUPPLY("8921_l7", NULL),
REGULATOR_SUPPLY("sdc_vdd_io", "msm_sdcc.3"),
};
VREG_CONSUMERS(L8) = {
REGULATOR_SUPPLY("8921_l8", NULL),
#if !defined(CONFIG_SONY_CAM_V4L2)
REGULATOR_SUPPLY("cam_vana", "4-001a"),
REGULATOR_SUPPLY("cam_vana", "4-0048"),
REGULATOR_SUPPLY("cam_vana", "4-006c"),
REGULATOR_SUPPLY("cam_vana", "4-0034"),
REGULATOR_SUPPLY("cam_vana", "4-0020"),
#else
REGULATOR_SUPPLY("cam_vana", "4-0010"),
REGULATOR_SUPPLY("cam_vana", "4-0036"),
#endif
};
VREG_CONSUMERS(L9) = {
REGULATOR_SUPPLY("8921_l9", NULL),
REGULATOR_SUPPLY("vdd", "3-0024"),
REGULATOR_SUPPLY("lc898300_dummy_vdd", "2-0049"),
REGULATOR_SUPPLY("apds9702_vdd", "2-0054"),
REGULATOR_SUPPLY("mpu3050_vdd", "2-0068"),
REGULATOR_SUPPLY("bma250_vdd", "2-0018"),
REGULATOR_SUPPLY("akm8963_vdd", "2-000c"),
REGULATOR_SUPPLY("ir-vdd", "ir_remote_control"),
};
VREG_CONSUMERS(L10) = {
REGULATOR_SUPPLY("8921_l10", NULL),
REGULATOR_SUPPLY("iris_vddpa", "wcnss_wlan.0"),
};
VREG_CONSUMERS(L11) = {
REGULATOR_SUPPLY("8921_l11", NULL),
REGULATOR_SUPPLY("dsi1_avdd", "mipi_dsi.1"),
REGULATOR_SUPPLY("lm3533_als", "0-0036"),
};
VREG_CONSUMERS(L12) = {
REGULATOR_SUPPLY("8921_l12", NULL),
#if !defined(CONFIG_SONY_CAM_V4L2)
REGULATOR_SUPPLY("cam_vdig", "4-001a"),
REGULATOR_SUPPLY("cam_vdig", "4-0048"),
REGULATOR_SUPPLY("cam_vdig", "4-006c"),
REGULATOR_SUPPLY("cam_vdig", "4-0034"),
REGULATOR_SUPPLY("cam_vdig", "4-0020"),
#else
REGULATOR_SUPPLY("cam_vdig", "4-0036"),
#endif
};
VREG_CONSUMERS(L13) = {
REGULATOR_SUPPLY("8921_l13", NULL),
REGULATOR_SUPPLY("apq_therm", "pm8xxx-adc"),
};
VREG_CONSUMERS(L14) = {
REGULATOR_SUPPLY("8921_l14", NULL),
REGULATOR_SUPPLY("vreg_xoadc", "pm8921-charger"),
REGULATOR_SUPPLY("pa_therm", "pm8xxx-adc"),
};
VREG_CONSUMERS(L15) = {
REGULATOR_SUPPLY("8921_l15", NULL),
REGULATOR_SUPPLY("lc898300_vdd", "2-0049"),
};
VREG_CONSUMERS(L16) = {
REGULATOR_SUPPLY("8921_l16", NULL),
#if !defined(CONFIG_SONY_CAM_V4L2)
REGULATOR_SUPPLY("cam_vaf", "4-001a"),
REGULATOR_SUPPLY("cam_vaf", "4-0048"),
REGULATOR_SUPPLY("cam_vaf", "4-006c"),
REGULATOR_SUPPLY("cam_vaf", "4-0034"),
REGULATOR_SUPPLY("cam_vaf", "4-0020"),
#else
REGULATOR_SUPPLY("cam_vaf", "4-0010"),
#endif
};
VREG_CONSUMERS(L17) = {
REGULATOR_SUPPLY("8921_l17", NULL),
REGULATOR_SUPPLY("touch_vdd", "3-002c"),
};
VREG_CONSUMERS(L18) = {
REGULATOR_SUPPLY("8921_l18", NULL),
};
/* Not used
VREG_CONSUMERS(L21) = {
REGULATOR_SUPPLY("8921_l21", NULL),
};
VREG_CONSUMERS(L22) = {
REGULATOR_SUPPLY("8921_l22", NULL),
};
*/
VREG_CONSUMERS(L23) = {
REGULATOR_SUPPLY("8921_l23", NULL),
REGULATOR_SUPPLY("pll_vdd", "pil_qdsp6v4.1"),
REGULATOR_SUPPLY("pll_vdd", "pil_qdsp6v4.2"),
REGULATOR_SUPPLY("HSUSB_1p8", "msm_ehci_host.0"),
REGULATOR_SUPPLY("pn544_pvvd", "0-0028"),
};
VREG_CONSUMERS(L24) = {
REGULATOR_SUPPLY("8921_l24", NULL),
REGULATOR_SUPPLY("riva_vddmx", "wcnss_wlan.0"),
};
VREG_CONSUMERS(L25) = {
REGULATOR_SUPPLY("8921_l25", NULL),
REGULATOR_SUPPLY("VDDD_CDC_D", "tabla-slim"),
REGULATOR_SUPPLY("CDC_VDDA_A_1P2V", "tabla-slim"),
REGULATOR_SUPPLY("VDDD_CDC_D", "tabla2x-slim"),
REGULATOR_SUPPLY("CDC_VDDA_A_1P2V", "tabla2x-slim"),
};
VREG_CONSUMERS(L26) = {
REGULATOR_SUPPLY("8921_l26", NULL),
REGULATOR_SUPPLY("core_vdd", "pil_qdsp6v4.0"),
};
VREG_CONSUMERS(L27) = {
REGULATOR_SUPPLY("8921_l27", NULL),
REGULATOR_SUPPLY("core_vdd", "pil_qdsp6v4.2"),
};
VREG_CONSUMERS(L28) = {
REGULATOR_SUPPLY("8921_l28", NULL),
REGULATOR_SUPPLY("core_vdd", "pil_qdsp6v4.1"),
#if defined(CONFIG_SONY_CAM_V4L2)
REGULATOR_SUPPLY("cam_vdig", "4-0010"),
#endif
};
VREG_CONSUMERS(L29) = {
REGULATOR_SUPPLY("8921_l29", NULL),
REGULATOR_SUPPLY("dsi1_vddio", "mipi_dsi.1"),
};
VREG_CONSUMERS(S2) = {
REGULATOR_SUPPLY("8921_s2", NULL),
REGULATOR_SUPPLY("iris_vddrfa", "wcnss_wlan.0"),
};
VREG_CONSUMERS(S3) = {
REGULATOR_SUPPLY("8921_s3", NULL),
REGULATOR_SUPPLY("HSUSB_VDDCX", "msm_otg"),
REGULATOR_SUPPLY("HSUSB_VDDCX", "msm_ehci_host.0"),
REGULATOR_SUPPLY("HSIC_VDDCX", "msm_hsic_host"),
REGULATOR_SUPPLY("riva_vddcx", "wcnss_wlan.0"),
REGULATOR_SUPPLY("vp_pcie", "msm_pcie"),
REGULATOR_SUPPLY("vptx_pcie", "msm_pcie"),
};
VREG_CONSUMERS(S4) = {
REGULATOR_SUPPLY("8921_s4", NULL),
REGULATOR_SUPPLY("sdc_vdd_io", "msm_sdcc.1"),
REGULATOR_SUPPLY("VDDIO_CDC", "tabla-slim"),
REGULATOR_SUPPLY("CDC_VDD_CP", "tabla-slim"),
REGULATOR_SUPPLY("CDC_VDDA_TX", "tabla-slim"),
REGULATOR_SUPPLY("CDC_VDDA_RX", "tabla-slim"),
REGULATOR_SUPPLY("VDDIO_CDC", "tabla2x-slim"),
REGULATOR_SUPPLY("CDC_VDD_CP", "tabla2x-slim"),
REGULATOR_SUPPLY("CDC_VDDA_TX", "tabla2x-slim"),
REGULATOR_SUPPLY("CDC_VDDA_RX", "tabla2x-slim"),
REGULATOR_SUPPLY("riva_vddpx", "wcnss_wlan.0"),
REGULATOR_SUPPLY("vcc_i2c", "3-005b"),
REGULATOR_SUPPLY("vcc_i2c", "3-0024"),
REGULATOR_SUPPLY("vddp", "0-0048"),
REGULATOR_SUPPLY("hdmi_lvl_tsl", "hdmi_msm.0"),
REGULATOR_SUPPLY("touch_vio", "3-002c"),
REGULATOR_SUPPLY("ir-vio-s4", "ir_remote_control"),
};
VREG_CONSUMERS(S5) = {
REGULATOR_SUPPLY("8921_s5", NULL),
REGULATOR_SUPPLY("krait0", "acpuclk-8064"),
};
VREG_CONSUMERS(S6) = {
REGULATOR_SUPPLY("8921_s6", NULL),
REGULATOR_SUPPLY("krait1", "acpuclk-8064"),
};
VREG_CONSUMERS(S7) = {
REGULATOR_SUPPLY("8921_s7", NULL),
};
VREG_CONSUMERS(S8) = {
REGULATOR_SUPPLY("8921_s8", NULL),
};
VREG_CONSUMERS(LVS1) = {
REGULATOR_SUPPLY("8921_lvs1", NULL),
REGULATOR_SUPPLY("iris_vddio", "wcnss_wlan.0"),
};
VREG_CONSUMERS(LVS3) = {
REGULATOR_SUPPLY("8921_lvs3", NULL),
};
VREG_CONSUMERS(LVS4) = {
REGULATOR_SUPPLY("8921_lvs4", NULL),
REGULATOR_SUPPLY("lc898300_vio", "2-0049"),
REGULATOR_SUPPLY("apds9702_vio", "2-0054"),
REGULATOR_SUPPLY("mpu3050_vio", "2-0068"),
REGULATOR_SUPPLY("bma250_vio", "2-0018"),
REGULATOR_SUPPLY("akm8963_vio", "2-000c"),
REGULATOR_SUPPLY("ir-vio", "ir_remote_control"),
};
VREG_CONSUMERS(LVS5) = {
REGULATOR_SUPPLY("8921_lvs5", NULL),
#if !defined(CONFIG_SONY_CAM_V4L2)
REGULATOR_SUPPLY("cam_vio", "4-001a"),
REGULATOR_SUPPLY("cam_vio", "4-0048"),
REGULATOR_SUPPLY("cam_vio", "4-006c"),
#else
REGULATOR_SUPPLY("cam_vio", "4-0010"),
REGULATOR_SUPPLY("cam_vio", "4-0036"),
#endif
#if !defined(CONFIG_SONY_CAM_V4L2)
REGULATOR_SUPPLY("cam_vio", "4-0034"),
#endif
};
VREG_CONSUMERS(LVS6) = {
REGULATOR_SUPPLY("8921_lvs6", NULL),
REGULATOR_SUPPLY("vdd_pcie_vph", "msm_pcie"),
};
VREG_CONSUMERS(LVS7) = {
REGULATOR_SUPPLY("8921_lvs7", NULL),
REGULATOR_SUPPLY("pll_vdd", "pil_riva"),
REGULATOR_SUPPLY("lvds_vdda", "lvds.0"),
REGULATOR_SUPPLY("dsi_pll_vddio", "mdp.0"),
REGULATOR_SUPPLY("hdmi_vdda", "hdmi_msm.0"),
};
VREG_CONSUMERS(USB_OTG) = {
REGULATOR_SUPPLY("8921_usb_otg", NULL),
REGULATOR_SUPPLY("vbus_otg", "msm_otg"),
};
VREG_CONSUMERS(HDMI_MVS) = {
REGULATOR_SUPPLY("8921_hdmi_mvs", NULL),
};
VREG_CONSUMERS(8821_S0) = {
REGULATOR_SUPPLY("8821_s0", NULL),
REGULATOR_SUPPLY("krait2", "acpuclk-8064"),
};
VREG_CONSUMERS(8821_S1) = {
REGULATOR_SUPPLY("8821_s1", NULL),
REGULATOR_SUPPLY("krait3", "acpuclk-8064"),
};
VREG_CONSUMERS(S1) = {
REGULATOR_SUPPLY("8921_s1", NULL),
};
VREG_CONSUMERS(LVS2) = {
REGULATOR_SUPPLY("8921_lvs2", NULL),
REGULATOR_SUPPLY("iris_vdddig", "wcnss_wlan.0"),
};
VREG_CONSUMERS(NCP) = {
REGULATOR_SUPPLY("8921_ncp", NULL),
};
VREG_CONSUMERS(EXT_5V) = {
REGULATOR_SUPPLY("ext_5v", NULL),
};
VREG_CONSUMERS(EXT_OTG_SW) = {
REGULATOR_SUPPLY("ext_otg_sw", NULL),
};
/* Regulators that are only present when using PM8917 */
VREG_CONSUMERS(8917_S1) = {
REGULATOR_SUPPLY("8921_s1", NULL),
REGULATOR_SUPPLY("iris_vdddig", "wcnss_wlan.0"),
};
VREG_CONSUMERS(L30) = {
REGULATOR_SUPPLY("8917_l30", NULL),
};
VREG_CONSUMERS(L31) = {
REGULATOR_SUPPLY("8917_l31", NULL),
};
VREG_CONSUMERS(L32) = {
REGULATOR_SUPPLY("8917_l32", NULL),
};
VREG_CONSUMERS(L33) = {
REGULATOR_SUPPLY("8917_l33", NULL),
};
VREG_CONSUMERS(L34) = {
REGULATOR_SUPPLY("8917_l34", NULL),
};
VREG_CONSUMERS(L35) = {
REGULATOR_SUPPLY("8917_l35", NULL),
};
VREG_CONSUMERS(L36) = {
REGULATOR_SUPPLY("8917_l36", NULL),
};
VREG_CONSUMERS(BOOST) = {
REGULATOR_SUPPLY("8917_boost", NULL),
REGULATOR_SUPPLY("vbus", "msm_ehci_host.0"),
REGULATOR_SUPPLY("hdmi_mvs", "hdmi_msm.0"),
};
#define PM8XXX_VREG_INIT(_id, _name, _min_uV, _max_uV, _modes, _ops, \
_apply_uV, _pull_down, _always_on, _supply_regulator, \
_system_uA, _enable_time, _reg_id) \
{ \
.init_data = { \
.constraints = { \
.valid_modes_mask = _modes, \
.valid_ops_mask = _ops, \
.min_uV = _min_uV, \
.max_uV = _max_uV, \
.input_uV = _max_uV, \
.apply_uV = _apply_uV, \
.always_on = _always_on, \
.name = _name, \
}, \
.num_consumer_supplies = \
ARRAY_SIZE(vreg_consumers_##_id), \
.consumer_supplies = vreg_consumers_##_id, \
.supply_regulator = _supply_regulator, \
}, \
.id = _reg_id, \
.pull_down_enable = _pull_down, \
.system_uA = _system_uA, \
.enable_time = _enable_time, \
}
#define PM8XXX_LDO(_id, _name, _always_on, _pull_down, _min_uV, _max_uV, \
_enable_time, _supply_regulator, _system_uA, _reg_id) \
PM8XXX_VREG_INIT(_id, _name, _min_uV, _max_uV, REGULATOR_MODE_NORMAL \
| REGULATOR_MODE_IDLE, REGULATOR_CHANGE_VOLTAGE | \
REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_MODE | \
REGULATOR_CHANGE_DRMS, 0, _pull_down, _always_on, \
_supply_regulator, _system_uA, _enable_time, _reg_id)
#define PM8XXX_NLDO1200(_id, _name, _always_on, _pull_down, _min_uV, \
_max_uV, _enable_time, _supply_regulator, _system_uA, _reg_id) \
PM8XXX_VREG_INIT(_id, _name, _min_uV, _max_uV, REGULATOR_MODE_NORMAL \
| REGULATOR_MODE_IDLE, REGULATOR_CHANGE_VOLTAGE | \
REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_MODE | \
REGULATOR_CHANGE_DRMS, 0, _pull_down, _always_on, \
_supply_regulator, _system_uA, _enable_time, _reg_id)
#define PM8XXX_SMPS(_id, _name, _always_on, _pull_down, _min_uV, _max_uV, \
_enable_time, _supply_regulator, _system_uA, _reg_id) \
PM8XXX_VREG_INIT(_id, _name, _min_uV, _max_uV, REGULATOR_MODE_NORMAL \
| REGULATOR_MODE_IDLE, REGULATOR_CHANGE_VOLTAGE | \
REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_MODE | \
REGULATOR_CHANGE_DRMS, 0, _pull_down, _always_on, \
_supply_regulator, _system_uA, _enable_time, _reg_id)
#define PM8XXX_FTSMPS(_id, _name, _always_on, _pull_down, _min_uV, _max_uV, \
_enable_time, _supply_regulator, _system_uA, _reg_id) \
PM8XXX_VREG_INIT(_id, _name, _min_uV, _max_uV, REGULATOR_MODE_NORMAL, \
REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS \
| REGULATOR_CHANGE_MODE, 0, _pull_down, _always_on, \
_supply_regulator, _system_uA, _enable_time, _reg_id)
#define PM8XXX_VS(_id, _name, _always_on, _pull_down, _enable_time, \
_supply_regulator, _reg_id) \
PM8XXX_VREG_INIT(_id, _name, 0, 0, 0, REGULATOR_CHANGE_STATUS, 0, \
_pull_down, _always_on, _supply_regulator, 0, _enable_time, \
_reg_id)
#define PM8XXX_VS300(_id, _name, _always_on, _pull_down, _enable_time, \
_supply_regulator, _reg_id) \
PM8XXX_VREG_INIT(_id, _name, 0, 0, 0, REGULATOR_CHANGE_STATUS, 0, \
_pull_down, _always_on, _supply_regulator, 0, _enable_time, \
_reg_id)
#define PM8XXX_NCP(_id, _name, _always_on, _min_uV, _max_uV, _enable_time, \
_supply_regulator, _reg_id) \
PM8XXX_VREG_INIT(_id, _name, _min_uV, _max_uV, 0, \
REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS, 0, 0, \
_always_on, _supply_regulator, 0, _enable_time, _reg_id)
#define PM8XXX_BOOST(_id, _name, _always_on, _min_uV, _max_uV, _enable_time, \
_supply_regulator, _reg_id) \
PM8XXX_VREG_INIT(_id, _name, _min_uV, _max_uV, 0, \
REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS, 0, 0, \
_always_on, _supply_regulator, 0, _enable_time, _reg_id)
/* Pin control initialization */
#define PM8XXX_PC(_id, _name, _always_on, _pin_fn, _pin_ctrl, \
_supply_regulator, _reg_id) \
{ \
.init_data = { \
.constraints = { \
.valid_ops_mask = REGULATOR_CHANGE_STATUS, \
.always_on = _always_on, \
.name = _name, \
}, \
.num_consumer_supplies = \
ARRAY_SIZE(vreg_consumers_##_id##_PC), \
.consumer_supplies = vreg_consumers_##_id##_PC, \
.supply_regulator = _supply_regulator, \
}, \
.id = _reg_id, \
.pin_fn = PM8XXX_VREG_PIN_FN_##_pin_fn, \
.pin_ctrl = _pin_ctrl, \
}
#define GPIO_VREG(_id, _reg_name, _gpio_label, _gpio, _supply_regulator, \
_active_low) \
[GPIO_VREG_ID_##_id] = { \
.init_data = { \
.constraints = { \
.valid_ops_mask = REGULATOR_CHANGE_STATUS, \
}, \
.num_consumer_supplies = \
ARRAY_SIZE(vreg_consumers_##_id), \
.consumer_supplies = vreg_consumers_##_id, \
.supply_regulator = _supply_regulator, \
}, \
.regulator_name = _reg_name, \
.gpio_label = _gpio_label, \
.gpio = _gpio, \
.active_low = _active_low, \
}
#define SAW_VREG_INIT(_id, _name, _min_uV, _max_uV) \
{ \
.constraints = { \
.name = _name, \
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE, \
.min_uV = _min_uV, \
.max_uV = _max_uV, \
}, \
.num_consumer_supplies = ARRAY_SIZE(vreg_consumers_##_id), \
.consumer_supplies = vreg_consumers_##_id, \
}
#define RPM_INIT(_id, _min_uV, _max_uV, _modes, _ops, _apply_uV, _default_uV, \
_peak_uA, _avg_uA, _pull_down, _pin_ctrl, _freq, _pin_fn, \
_force_mode, _sleep_set_force_mode, _power_mode, _state, \
_sleep_selectable, _always_on, _supply_regulator, _system_uA) \
{ \
.init_data = { \
.constraints = { \
.valid_modes_mask = _modes, \
.valid_ops_mask = _ops, \
.min_uV = _min_uV, \
.max_uV = _max_uV, \
.input_uV = _min_uV, \
.apply_uV = _apply_uV, \
.always_on = _always_on, \
}, \
.num_consumer_supplies = \
ARRAY_SIZE(vreg_consumers_##_id), \
.consumer_supplies = vreg_consumers_##_id, \
.supply_regulator = _supply_regulator, \
}, \
.id = RPM_VREG_ID_PM8921_##_id, \
.default_uV = _default_uV, \
.peak_uA = _peak_uA, \
.avg_uA = _avg_uA, \
.pull_down_enable = _pull_down, \
.pin_ctrl = _pin_ctrl, \
.freq = RPM_VREG_FREQ_##_freq, \
.pin_fn = _pin_fn, \
.force_mode = _force_mode, \
.sleep_set_force_mode = _sleep_set_force_mode, \
.power_mode = _power_mode, \
.state = _state, \
.sleep_selectable = _sleep_selectable, \
.system_uA = _system_uA, \
}
#define RPM_LDO(_id, _always_on, _pd, _sleep_selectable, _min_uV, _max_uV, \
_supply_regulator, _system_uA, _init_peak_uA) \
RPM_INIT(_id, _min_uV, _max_uV, REGULATOR_MODE_NORMAL \
| REGULATOR_MODE_IDLE, REGULATOR_CHANGE_VOLTAGE \
| REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_MODE \
| REGULATOR_CHANGE_DRMS, 0, _max_uV, _init_peak_uA, 0, _pd, \
RPM_VREG_PIN_CTRL_NONE, NONE, RPM_VREG_PIN_FN_8960_NONE, \
RPM_VREG_FORCE_MODE_8960_NONE, \
RPM_VREG_FORCE_MODE_8960_NONE, RPM_VREG_POWER_MODE_8960_PWM, \
RPM_VREG_STATE_OFF, _sleep_selectable, _always_on, \
_supply_regulator, _system_uA)
#define RPM_SMPS(_id, _always_on, _pd, _sleep_selectable, _min_uV, _max_uV, \
_supply_regulator, _system_uA, _freq, _force_mode, \
_sleep_set_force_mode) \
RPM_INIT(_id, _min_uV, _max_uV, REGULATOR_MODE_NORMAL \
| REGULATOR_MODE_IDLE, REGULATOR_CHANGE_VOLTAGE \
| REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_MODE \
| REGULATOR_CHANGE_DRMS, 0, _max_uV, _system_uA, 0, _pd, \
RPM_VREG_PIN_CTRL_NONE, _freq, RPM_VREG_PIN_FN_8960_NONE, \
RPM_VREG_FORCE_MODE_8960_##_force_mode, \
RPM_VREG_FORCE_MODE_8960_##_sleep_set_force_mode, \
RPM_VREG_POWER_MODE_8960_PWM, RPM_VREG_STATE_OFF, \
_sleep_selectable, _always_on, _supply_regulator, _system_uA)
#define RPM_VS(_id, _always_on, _pd, _sleep_selectable, _supply_regulator) \
RPM_INIT(_id, 0, 0, 0, REGULATOR_CHANGE_STATUS, 0, 0, 1000, 1000, _pd, \
RPM_VREG_PIN_CTRL_NONE, NONE, RPM_VREG_PIN_FN_8960_NONE, \
RPM_VREG_FORCE_MODE_8960_NONE, \
RPM_VREG_FORCE_MODE_8960_NONE, RPM_VREG_POWER_MODE_8960_PWM, \
RPM_VREG_STATE_OFF, _sleep_selectable, _always_on, \
_supply_regulator, 0)
#define RPM_NCP(_id, _always_on, _sleep_selectable, _min_uV, _max_uV, \
_supply_regulator, _freq) \
RPM_INIT(_id, _min_uV, _max_uV, 0, REGULATOR_CHANGE_VOLTAGE \
| REGULATOR_CHANGE_STATUS, 0, _max_uV, 1000, 1000, 0, \
RPM_VREG_PIN_CTRL_NONE, _freq, RPM_VREG_PIN_FN_8960_NONE, \
RPM_VREG_FORCE_MODE_8960_NONE, \
RPM_VREG_FORCE_MODE_8960_NONE, RPM_VREG_POWER_MODE_8960_PWM, \
RPM_VREG_STATE_OFF, _sleep_selectable, _always_on, \
_supply_regulator, 0)
/* Pin control initialization */
#define RPM_PC_INIT(_id, _always_on, _pin_fn, _pin_ctrl, _supply_regulator) \
{ \
.init_data = { \
.constraints = { \
.valid_ops_mask = REGULATOR_CHANGE_STATUS, \
.always_on = _always_on, \
}, \
.num_consumer_supplies = \
ARRAY_SIZE(vreg_consumers_##_id##_PC), \
.consumer_supplies = vreg_consumers_##_id##_PC, \
.supply_regulator = _supply_regulator, \
}, \
.id = RPM_VREG_ID_PM8921_##_id##_PC, \
.pin_fn = RPM_VREG_PIN_FN_8960_##_pin_fn, \
.pin_ctrl = _pin_ctrl, \
}
/* GPIO regulator constraints.
* Must be in sync with corresponding platform_device structures in
* board_sony_fusion3.c
*/
struct gpio_regulator_platform_data
apq8064_gpio_regulator_pdata[] __devinitdata = {
/* ID vreg_name gpio_label gpio supply active_low*/
GPIO_VREG(EXT_5V, "ext_5v", "ext_5v_en", PM8921_MPP_PM_TO_SYS(7),
NULL, 0),
GPIO_VREG(EXT_OTG_SW, "ext_otg_sw", "ext_otg_sw_en",
PM8921_GPIO_PM_TO_SYS(42), NULL, 1),
};
/* SAW regulator constraints */
struct regulator_init_data msm8064_saw_regulator_pdata_8921_s5 =
/* ID vreg_name min_uV max_uV */
SAW_VREG_INIT(S5, "8921_s5", 850000, 1300000);
struct regulator_init_data msm8064_saw_regulator_pdata_8921_s6 =
SAW_VREG_INIT(S6, "8921_s6", 850000, 1300000);
struct regulator_init_data msm8064_saw_regulator_pdata_8821_s0 =
/* ID vreg_name min_uV max_uV */
SAW_VREG_INIT(8821_S0, "8821_s0", 850000, 1300000);
struct regulator_init_data msm8064_saw_regulator_pdata_8821_s1 =
SAW_VREG_INIT(8821_S1, "8821_s1", 850000, 1300000);
/* PM8921 regulator constraints */
struct pm8xxx_regulator_platform_data
msm8064_pm8921_regulator_pdata[] __devinitdata = {
/*
* ID name always_on pd min_uV max_uV en_t supply
* system_uA reg_ID
*/
PM8XXX_NLDO1200(L26, "8921_l26", 0, 1, 375000, 1050000, 200, "8921_s7",
0, 1),
/* ID name always_on pd en_t supply reg_ID */
PM8XXX_VS300(USB_OTG, "8921_usb_otg", 0, 0, 0, NULL, 2),
PM8XXX_VS300(HDMI_MVS, "8921_hdmi_mvs", 0, 0, 0, NULL, 3),
PM8XXX_LDO(L29, "8921_l29", 0, 1, 1800000, 1800000, 200, NULL,
0, 4),
};
/* PM8917 regulator constraints */
struct pm8xxx_regulator_platform_data
msm8064_pm8917_regulator_pdata[] __devinitdata = {
/*
* ID name always_on pd min_uV max_uV en_t supply
* system_uA reg_ID
*/
PM8XXX_NLDO1200(L26, "8921_l26", 0, 1, 375000, 1050000, 200, "8921_s7",
0, 1),
PM8XXX_LDO(L30, "8917_l30", 0, 1, 1800000, 1800000, 200, NULL,
0, 2),
PM8XXX_LDO(L31, "8917_l31", 0, 1, 1800000, 1800000, 200, NULL,
0, 3),
PM8XXX_LDO(L32, "8917_l32", 0, 1, 2800000, 2800000, 200, NULL,
0, 4),
PM8XXX_LDO(L33, "8917_l33", 0, 1, 2800000, 2800000, 200, NULL,
0, 5),
PM8XXX_LDO(L34, "8917_l34", 0, 1, 1800000, 1800000, 200, NULL,
0, 6),
PM8XXX_LDO(L35, "8917_l35", 0, 1, 3000000, 3000000, 200, NULL,
0, 7),
PM8XXX_LDO(L36, "8917_l36", 0, 1, 1800000, 1800000, 200, NULL,
0, 8),
/*
* ID name always_on min_uV max_uV en_t supply reg_ID
*/
PM8XXX_BOOST(BOOST, "8917_boost", 0, 5000000, 5000000, 500, NULL, 9),
/* ID name always_on pd en_t supply reg_ID */
PM8XXX_VS300(USB_OTG, "8921_usb_otg", 0, 1, 0, "8917_boost", 10),
};
static struct rpm_regulator_init_data
apq8064_rpm_regulator_init_data[] __devinitdata = {
/* ID a_on pd ss min_uV max_uV supply sys_uA freq fm ss_fm */
RPM_SMPS(S1, 1, 1, 0, 1225000, 1225000, NULL, 100000, 3p20, NONE, NONE),
RPM_SMPS(S2, 0, 1, 0, 1300000, 1300000, NULL, 0, 1p60, NONE, NONE),
RPM_SMPS(S3, 0, 1, 1, 500000, 1150000, NULL, 100000, 4p80, NONE, NONE),
RPM_SMPS(S4, 1, 1, 0, 1800000, 1800000, NULL, 100000, 1p60, NONE, NONE),
RPM_SMPS(S7, 0, 0, 0, 1300000, 1300000, NULL, 100000, 3p20, NONE, NONE),
RPM_SMPS(S8, 0, 1, 0, 2200000, 2200000, NULL, 0, 1p60, NONE, NONE),
/* ID a_on pd ss min_uV max_uV supply sys_uA init_ip */
RPM_LDO(L1, 1, 1, 0, 1100000, 1100000, "8921_s4", 0, 1000),
RPM_LDO(L2, 0, 1, 0, 1200000, 1200000, "8921_s4", 0, 0),
RPM_LDO(L3, 0, 1, 0, 3075000, 3075000, NULL, 0, 0),
RPM_LDO(L4, 1, 1, 0, 1800000, 1800000, NULL, 0, 10000),
RPM_LDO(L5, 0, 1, 0, 2950000, 2950000, NULL, 0, 0),
RPM_LDO(L6, 0, 1, 0, 2950000, 2950000, NULL, 0, 0),
RPM_LDO(L7, 0, 1, 0, 1850000, 2950000, NULL, 0, 0),
RPM_LDO(L8, 0, 1, 0, 2800000, 2800000, NULL, 0, 0),
RPM_LDO(L9, 0, 1, 0, 2850000, 2850000, NULL, 0, 0),
RPM_LDO(L10, 0, 1, 0, 3000000, 3000000, NULL, 0, 0),
RPM_LDO(L11, 0, 1, 0, 2850000, 2850000, NULL, 0, 0),
RPM_LDO(L12, 0, 1, 0, 1200000, 1200000, "8921_s4", 0, 0),
RPM_LDO(L13, 0, 0, 0, 1740000, 1740000, NULL, 0, 0),
RPM_LDO(L14, 0, 1, 0, 1800000, 1800000, NULL, 0, 0),
RPM_LDO(L15, 0, 1, 0, 3050000, 3050000, NULL, 0, 0),
#if defined(CONFIG_SONY_CAM_V4L2)
RPM_LDO(L16, 0, 1, 0, 2700000, 2800000, NULL, 0, 0),
#else
RPM_LDO(L16, 0, 1, 0, 3050000, 3050000, NULL, 0, 0),
#endif
RPM_LDO(L17, 0, 1, 0, 3000000, 3000000, NULL, 0, 0),
RPM_LDO(L18, 0, 1, 0, 1200000, 1200000, "8921_s4", 0, 0),
/* Not used
RPM_LDO(L21, 0, 1, 0, 1800000, 1800000, NULL, 0, 0),
RPM_LDO(L22, 0, 1, 0, 2600000, 2600000, NULL, 0, 0),
*/
RPM_LDO(L23, 1, 1, 0, 1800000, 1800000, NULL, 0, 0),
RPM_LDO(L24, 0, 1, 1, 750000, 1150000, "8921_s1", 10000, 10000),
/* L26 configured in msm8064_pm8921_regulator_pdata */
RPM_LDO(L25, 1, 1, 0, 1250000, 1250000, "8921_s1", 10000, 10000),
RPM_LDO(L27, 0, 0, 0, 1100000, 1100000, "8921_s7", 0, 0),
#if defined(CONFIG_SONY_CAM_V4L2)
RPM_LDO(L28, 0, 1, 0, 1050000, 1200000, "8921_s7", 0, 0),
#else
RPM_LDO(L28, 0, 1, 0, 1050000, 1050000, "8921_s7", 0, 0),
#endif
/* L29 configured in msm8064_pm8921_regulator_pdata */
/* ID a_on pd ss supply */
RPM_VS(LVS1, 0, 1, 0, "8921_s4"),
RPM_VS(LVS3, 0, 1, 0, "8921_s4"),
RPM_VS(LVS4, 0, 1, 0, "8921_s4"),
RPM_VS(LVS5, 0, 1, 0, "8921_s4"),
RPM_VS(LVS6, 0, 1, 0, "8921_s4"),
RPM_VS(LVS7, 0, 1, 1, "8921_s4"),
/* ID a_on ss min_uV max_uV supply freq */
RPM_NCP(NCP, 0, 0, 1800000, 1800000, "8921_l6", 1p60),
};
static struct rpm_regulator_init_data
apq8064_rpm_regulator_pm8921_init_data[] __devinitdata = {
/* ID a_on pd ss supply */
RPM_VS(LVS2, 0, 1, 0, "8921_s1"),
};
int msm8064_pm8921_regulator_pdata_len __devinitdata =
ARRAY_SIZE(msm8064_pm8921_regulator_pdata);
int msm8064_pm8917_regulator_pdata_len __devinitdata =
ARRAY_SIZE(msm8064_pm8917_regulator_pdata);
#define RPM_REG_MAP(_id, _sleep_also, _voter, _supply, _dev_name) \
{ \
.vreg_id = RPM_VREG_ID_PM8921_##_id, \
.sleep_also = _sleep_also, \
.voter = _voter, \
.supply = _supply, \
.dev_name = _dev_name, \
}
static struct rpm_regulator_consumer_mapping
msm_rpm_regulator_consumer_mapping[] __devinitdata = {
RPM_REG_MAP(LVS7, 0, 1, "krait0_hfpll", "acpuclk-8064"),
RPM_REG_MAP(LVS7, 0, 2, "krait1_hfpll", "acpuclk-8064"),
RPM_REG_MAP(LVS7, 0, 4, "krait2_hfpll", "acpuclk-8064"),
RPM_REG_MAP(LVS7, 0, 5, "krait3_hfpll", "acpuclk-8064"),
RPM_REG_MAP(LVS7, 0, 6, "l2_hfpll", "acpuclk-8064"),
RPM_REG_MAP(L24, 0, 1, "krait0_mem", "acpuclk-8064"),
RPM_REG_MAP(L24, 0, 2, "krait1_mem", "acpuclk-8064"),
RPM_REG_MAP(L24, 0, 4, "krait2_mem", "acpuclk-8064"),
RPM_REG_MAP(L24, 0, 5, "krait3_mem", "acpuclk-8064"),
RPM_REG_MAP(S3, 0, 1, "krait0_dig", "acpuclk-8064"),
RPM_REG_MAP(S3, 0, 2, "krait1_dig", "acpuclk-8064"),
RPM_REG_MAP(S3, 0, 4, "krait2_dig", "acpuclk-8064"),
RPM_REG_MAP(S3, 0, 5, "krait3_dig", "acpuclk-8064"),
};
struct rpm_regulator_platform_data apq8064_rpm_regulator_pdata __devinitdata = {
.init_data = apq8064_rpm_regulator_init_data,
.num_regulators = ARRAY_SIZE(apq8064_rpm_regulator_init_data),
.version = RPM_VREG_VERSION_8960,
.vreg_id_vdd_mem = RPM_VREG_ID_PM8921_L24,
.vreg_id_vdd_dig = RPM_VREG_ID_PM8921_S3,
.requires_tcxo_workaround = true,
.consumer_map = msm_rpm_regulator_consumer_mapping,
.consumer_map_len = ARRAY_SIZE(msm_rpm_regulator_consumer_mapping),
};
/* Regulators that are only present when using PM8921 */
struct rpm_regulator_platform_data
apq8064_rpm_regulator_pm8921_pdata __devinitdata = {
.init_data = apq8064_rpm_regulator_pm8921_init_data,
.num_regulators = ARRAY_SIZE(apq8064_rpm_regulator_pm8921_init_data),
.version = RPM_VREG_VERSION_8960,
.vreg_id_vdd_mem = RPM_VREG_ID_PM8921_L24,
.vreg_id_vdd_dig = RPM_VREG_ID_PM8921_S3,
.requires_tcxo_workaround = true,
};
/*
* Fix up regulator consumer data that moves to a different regulator when
* PM8917 is used.
*/
void __init configure_apq8064_pm8917_power_grid(void)
{
static struct rpm_regulator_init_data *rpm_data;
int i;
for (i = 0; i < ARRAY_SIZE(apq8064_rpm_regulator_init_data); i++) {
rpm_data = &apq8064_rpm_regulator_init_data[i];
if (rpm_data->id == RPM_VREG_ID_PM8921_S1) {
rpm_data->init_data.consumer_supplies
= vreg_consumers_8917_S1;
rpm_data->init_data.num_consumer_supplies
= ARRAY_SIZE(vreg_consumers_8917_S1);
}
}
/*
* Switch to 8960_PM8917 rpm-regulator version so that TCXO workaround
* is applied to PM8917 regulators L25, L26, L27, and L28.
*/
apq8064_rpm_regulator_pdata.version = RPM_VREG_VERSION_8960_PM8917;
}
| nok07635/UnleaZhed_XTZ | arch/arm/mach-msm/board-sony_odin-regulator.c | C | gpl-2.0 | 28,195 |
/*
* cfg80211 scan result handling
*
* Copyright 2008 Johannes Berg <[email protected]>
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/wireless.h>
#include <linux/nl80211.h>
#include <linux/etherdevice.h>
#include <net/arp.h>
#include <net/cfg80211.h>
#include <net/cfg80211-wext.h>
#include <net/iw_handler.h>
#include "core.h"
#include "nl80211.h"
#include "wext-compat.h"
#include "rdev-ops.h"
/**
* DOC: BSS tree/list structure
*
* At the top level, the BSS list is kept in both a list in each
* registered device (@bss_list) as well as an RB-tree for faster
* lookup. In the RB-tree, entries can be looked up using their
* channel, MESHID, MESHCONF (for MBSSes) or channel, BSSID, SSID
* for other BSSes.
*
* Due to the possibility of hidden SSIDs, there's a second level
* structure, the "hidden_list" and "hidden_beacon_bss" pointer.
* The hidden_list connects all BSSes belonging to a single AP
* that has a hidden SSID, and connects beacon and probe response
* entries. For a probe response entry for a hidden SSID, the
* hidden_beacon_bss pointer points to the BSS struct holding the
* beacon's information.
*
* Reference counting is done for all these references except for
* the hidden_list, so that a beacon BSS struct that is otherwise
* not referenced has one reference for being on the bss_list and
* one for each probe response entry that points to it using the
* hidden_beacon_bss pointer. When a BSS struct that has such a
* pointer is get/put, the refcount update is also propagated to
* the referenced struct, this ensure that it cannot get removed
* while somebody is using the probe response version.
*
* Note that the hidden_beacon_bss pointer never changes, due to
* the reference counting. Therefore, no locking is needed for
* it.
*
* Also note that the hidden_beacon_bss pointer is only relevant
* if the driver uses something other than the IEs, e.g. private
* data stored stored in the BSS struct, since the beacon IEs are
* also linked into the probe response struct.
*/
/*
* Limit the number of BSS entries stored in mac80211. Each one is
* a bit over 4k at most, so this limits to roughly 4-5M of memory.
* If somebody wants to really attack this though, they'd likely
* use small beacons, and only one type of frame, limiting each of
* the entries to a much smaller size (in order to generate more
* entries in total, so overhead is bigger.)
*/
static int bss_entries_limit = 1000;
module_param(bss_entries_limit, int, 0644);
MODULE_PARM_DESC(bss_entries_limit,
"limit to number of scan BSS entries (per wiphy, default 1000)");
#define IEEE80211_SCAN_RESULT_EXPIRE (7 * HZ)
static void bss_free(struct cfg80211_internal_bss *bss)
{
struct cfg80211_bss_ies *ies;
if (WARN_ON(atomic_read(&bss->hold)))
return;
ies = (void *)rcu_access_pointer(bss->pub.beacon_ies);
if (ies && !bss->pub.hidden_beacon_bss)
kfree_rcu(ies, rcu_head);
ies = (void *)rcu_access_pointer(bss->pub.proberesp_ies);
if (ies)
kfree_rcu(ies, rcu_head);
/*
* This happens when the module is removed, it doesn't
* really matter any more save for completeness
*/
if (!list_empty(&bss->hidden_list))
list_del(&bss->hidden_list);
kfree(bss);
}
static inline void bss_ref_get(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *bss)
{
lockdep_assert_held(&dev->bss_lock);
bss->refcount++;
if (bss->pub.hidden_beacon_bss) {
bss = container_of(bss->pub.hidden_beacon_bss,
struct cfg80211_internal_bss,
pub);
bss->refcount++;
}
}
static inline void bss_ref_put(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *bss)
{
lockdep_assert_held(&dev->bss_lock);
if (bss->pub.hidden_beacon_bss) {
struct cfg80211_internal_bss *hbss;
hbss = container_of(bss->pub.hidden_beacon_bss,
struct cfg80211_internal_bss,
pub);
hbss->refcount--;
if (hbss->refcount == 0)
bss_free(hbss);
}
bss->refcount--;
if (bss->refcount == 0)
bss_free(bss);
}
static bool __cfg80211_unlink_bss(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *bss)
{
lockdep_assert_held(&dev->bss_lock);
if (!list_empty(&bss->hidden_list)) {
/*
* don't remove the beacon entry if it has
* probe responses associated with it
*/
if (!bss->pub.hidden_beacon_bss)
return false;
/*
* if it's a probe response entry break its
* link to the other entries in the group
*/
list_del_init(&bss->hidden_list);
}
list_del_init(&bss->list);
rb_erase(&bss->rbn, &dev->bss_tree);
dev->bss_entries--;
WARN_ONCE((dev->bss_entries == 0) ^ list_empty(&dev->bss_list),
"rdev bss entries[%d]/list[empty:%d] corruption\n",
dev->bss_entries, list_empty(&dev->bss_list));
bss_ref_put(dev, bss);
return true;
}
static void __cfg80211_bss_expire(struct cfg80211_registered_device *dev,
unsigned long expire_time)
{
struct cfg80211_internal_bss *bss, *tmp;
bool expired = false;
lockdep_assert_held(&dev->bss_lock);
list_for_each_entry_safe(bss, tmp, &dev->bss_list, list) {
if (atomic_read(&bss->hold))
continue;
if (!time_after(expire_time, bss->ts))
continue;
if (__cfg80211_unlink_bss(dev, bss))
expired = true;
}
if (expired)
dev->bss_generation++;
}
void ___cfg80211_scan_done(struct cfg80211_registered_device *rdev, bool leak)
{
struct cfg80211_scan_request *request;
struct wireless_dev *wdev;
#ifdef CONFIG_CFG80211_WEXT
union iwreq_data wrqu;
#endif
lockdep_assert_held(&rdev->sched_scan_mtx);
request = rdev->scan_req;
if (!request)
return;
wdev = request->wdev;
/*
* This must be before sending the other events!
* Otherwise, wpa_supplicant gets completely confused with
* wext events.
*/
if (wdev->netdev)
cfg80211_sme_scan_done(wdev->netdev);
if (request->aborted) {
nl80211_send_scan_aborted(rdev, wdev);
} else {
if (request->flags & NL80211_SCAN_FLAG_FLUSH) {
/* flush entries from previous scans */
spin_lock_bh(&rdev->bss_lock);
__cfg80211_bss_expire(rdev, request->scan_start);
spin_unlock_bh(&rdev->bss_lock);
}
nl80211_send_scan_done(rdev, wdev);
}
#ifdef CONFIG_CFG80211_WEXT
if (wdev->netdev && !request->aborted) {
memset(&wrqu, 0, sizeof(wrqu));
wireless_send_event(wdev->netdev, SIOCGIWSCAN, &wrqu, NULL);
}
#endif
if (wdev->netdev)
dev_put(wdev->netdev);
rdev->scan_req = NULL;
/*
* OK. If this is invoked with "leak" then we can't
* free this ... but we've cleaned it up anyway. The
* driver failed to call the scan_done callback, so
* all bets are off, it might still be trying to use
* the scan request or not ... if it accesses the dev
* in there (it shouldn't anyway) then it may crash.
*/
if (!leak)
kfree(request);
}
void __cfg80211_scan_done(struct work_struct *wk)
{
struct cfg80211_registered_device *rdev;
rdev = container_of(wk, struct cfg80211_registered_device,
scan_done_wk);
mutex_lock(&rdev->sched_scan_mtx);
___cfg80211_scan_done(rdev, false);
mutex_unlock(&rdev->sched_scan_mtx);
}
void cfg80211_scan_done(struct cfg80211_scan_request *request, bool aborted)
{
trace_cfg80211_scan_done(request, aborted);
WARN_ON(request != wiphy_to_dev(request->wiphy)->scan_req);
request->aborted = aborted;
queue_work(cfg80211_wq, &wiphy_to_dev(request->wiphy)->scan_done_wk);
}
EXPORT_SYMBOL(cfg80211_scan_done);
void __cfg80211_sched_scan_results(struct work_struct *wk)
{
struct cfg80211_registered_device *rdev;
struct cfg80211_sched_scan_request *request;
rdev = container_of(wk, struct cfg80211_registered_device,
sched_scan_results_wk);
mutex_lock(&rdev->sched_scan_mtx);
request = rdev->sched_scan_req;
/* we don't have sched_scan_req anymore if the scan is stopping */
if (request) {
if (request->flags & NL80211_SCAN_FLAG_FLUSH) {
/* flush entries from previous scans */
spin_lock_bh(&rdev->bss_lock);
__cfg80211_bss_expire(rdev, request->scan_start);
spin_unlock_bh(&rdev->bss_lock);
request->scan_start =
jiffies + msecs_to_jiffies(request->interval);
}
nl80211_send_sched_scan_results(rdev, request->dev);
}
mutex_unlock(&rdev->sched_scan_mtx);
}
void cfg80211_sched_scan_results(struct wiphy *wiphy)
{
trace_cfg80211_sched_scan_results(wiphy);
/* ignore if we're not scanning */
if (wiphy_to_dev(wiphy)->sched_scan_req)
queue_work(cfg80211_wq,
&wiphy_to_dev(wiphy)->sched_scan_results_wk);
}
EXPORT_SYMBOL(cfg80211_sched_scan_results);
void cfg80211_sched_scan_stopped(struct wiphy *wiphy)
{
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
trace_cfg80211_sched_scan_stopped(wiphy);
mutex_lock(&rdev->sched_scan_mtx);
__cfg80211_stop_sched_scan(rdev, true);
mutex_unlock(&rdev->sched_scan_mtx);
}
EXPORT_SYMBOL(cfg80211_sched_scan_stopped);
int __cfg80211_stop_sched_scan(struct cfg80211_registered_device *rdev,
bool driver_initiated)
{
struct net_device *dev;
lockdep_assert_held(&rdev->sched_scan_mtx);
if (!rdev->sched_scan_req)
return -ENOENT;
dev = rdev->sched_scan_req->dev;
if (!driver_initiated) {
int err = rdev_sched_scan_stop(rdev, dev);
if (err)
return err;
}
nl80211_send_sched_scan(rdev, dev, NL80211_CMD_SCHED_SCAN_STOPPED);
kfree(rdev->sched_scan_req);
rdev->sched_scan_req = NULL;
return 0;
}
void cfg80211_bss_age(struct cfg80211_registered_device *dev,
unsigned long age_secs)
{
struct cfg80211_internal_bss *bss;
unsigned long age_jiffies = msecs_to_jiffies(age_secs * MSEC_PER_SEC);
spin_lock_bh(&dev->bss_lock);
list_for_each_entry(bss, &dev->bss_list, list)
bss->ts -= age_jiffies;
spin_unlock_bh(&dev->bss_lock);
}
void cfg80211_bss_expire(struct cfg80211_registered_device *dev)
{
__cfg80211_bss_expire(dev, jiffies - IEEE80211_SCAN_RESULT_EXPIRE);
}
static bool cfg80211_bss_expire_oldest(struct cfg80211_registered_device *rdev)
{
struct cfg80211_internal_bss *bss, *oldest = NULL;
bool ret;
lockdep_assert_held(&rdev->bss_lock);
list_for_each_entry(bss, &rdev->bss_list, list) {
if (atomic_read(&bss->hold))
continue;
if (!list_empty(&bss->hidden_list) &&
!bss->pub.hidden_beacon_bss)
continue;
if (oldest && time_before(oldest->ts, bss->ts))
continue;
oldest = bss;
}
if (WARN_ON(!oldest))
return false;
/*
* The callers make sure to increase rdev->bss_generation if anything
* gets removed (and a new entry added), so there's no need to also do
* it here.
*/
ret = __cfg80211_unlink_bss(rdev, oldest);
WARN_ON(!ret);
return ret;
}
const u8 *cfg80211_find_ie(u8 eid, const u8 *ies, int len)
{
while (len > 2 && ies[0] != eid) {
len -= ies[1] + 2;
ies += ies[1] + 2;
}
if (len < 2)
return NULL;
if (len < 2 + ies[1])
return NULL;
return ies;
}
EXPORT_SYMBOL(cfg80211_find_ie);
const u8 *cfg80211_find_vendor_ie(unsigned int oui, u8 oui_type,
const u8 *ies, int len)
{
struct ieee80211_vendor_ie *ie;
const u8 *pos = ies, *end = ies + len;
int ie_oui;
while (pos < end) {
pos = cfg80211_find_ie(WLAN_EID_VENDOR_SPECIFIC, pos,
end - pos);
if (!pos)
return NULL;
ie = (struct ieee80211_vendor_ie *)pos;
/* make sure we can access ie->len */
BUILD_BUG_ON(offsetof(struct ieee80211_vendor_ie, len) != 1);
if (ie->len < sizeof(*ie))
goto cont;
ie_oui = ie->oui[0] << 16 | ie->oui[1] << 8 | ie->oui[2];
if (ie_oui == oui && ie->oui_type == oui_type)
return pos;
cont:
pos += 2 + ie->len;
}
return NULL;
}
EXPORT_SYMBOL(cfg80211_find_vendor_ie);
static bool is_bss(struct cfg80211_bss *a, const u8 *bssid,
const u8 *ssid, size_t ssid_len)
{
const struct cfg80211_bss_ies *ies;
const u8 *ssidie;
if (bssid && !ether_addr_equal(a->bssid, bssid))
return false;
if (!ssid)
return true;
ies = rcu_access_pointer(a->ies);
if (!ies)
return false;
ssidie = cfg80211_find_ie(WLAN_EID_SSID, ies->data, ies->len);
if (!ssidie)
return false;
if (ssidie[1] != ssid_len)
return false;
return memcmp(ssidie + 2, ssid, ssid_len) == 0;
}
/**
* enum bss_compare_mode - BSS compare mode
* @BSS_CMP_REGULAR: regular compare mode (for insertion and normal find)
* @BSS_CMP_HIDE_ZLEN: find hidden SSID with zero-length mode
* @BSS_CMP_HIDE_NUL: find hidden SSID with NUL-ed out mode
*/
enum bss_compare_mode {
BSS_CMP_REGULAR,
BSS_CMP_HIDE_ZLEN,
BSS_CMP_HIDE_NUL,
};
static int cmp_bss(struct cfg80211_bss *a,
struct cfg80211_bss *b,
enum bss_compare_mode mode)
{
const struct cfg80211_bss_ies *a_ies, *b_ies;
const u8 *ie1 = NULL;
const u8 *ie2 = NULL;
int i, r;
if (a->channel != b->channel)
return b->channel->center_freq - a->channel->center_freq;
a_ies = rcu_access_pointer(a->ies);
if (!a_ies)
return -1;
b_ies = rcu_access_pointer(b->ies);
if (!b_ies)
return 1;
if (WLAN_CAPABILITY_IS_STA_BSS(a->capability))
ie1 = cfg80211_find_ie(WLAN_EID_MESH_ID,
a_ies->data, a_ies->len);
if (WLAN_CAPABILITY_IS_STA_BSS(b->capability))
ie2 = cfg80211_find_ie(WLAN_EID_MESH_ID,
b_ies->data, b_ies->len);
if (ie1 && ie2) {
int mesh_id_cmp;
if (ie1[1] == ie2[1])
mesh_id_cmp = memcmp(ie1 + 2, ie2 + 2, ie1[1]);
else
mesh_id_cmp = ie2[1] - ie1[1];
ie1 = cfg80211_find_ie(WLAN_EID_MESH_CONFIG,
a_ies->data, a_ies->len);
ie2 = cfg80211_find_ie(WLAN_EID_MESH_CONFIG,
b_ies->data, b_ies->len);
if (ie1 && ie2) {
if (mesh_id_cmp)
return mesh_id_cmp;
if (ie1[1] != ie2[1])
return ie2[1] - ie1[1];
return memcmp(ie1 + 2, ie2 + 2, ie1[1]);
}
}
/*
* we can't use compare_ether_addr here since we need a < > operator.
* The binary return value of compare_ether_addr isn't enough
*/
r = memcmp(a->bssid, b->bssid, sizeof(a->bssid));
if (r)
return r;
ie1 = cfg80211_find_ie(WLAN_EID_SSID, a_ies->data, a_ies->len);
ie2 = cfg80211_find_ie(WLAN_EID_SSID, b_ies->data, b_ies->len);
if (!ie1 && !ie2)
return 0;
/*
* Note that with "hide_ssid", the function returns a match if
* the already-present BSS ("b") is a hidden SSID beacon for
* the new BSS ("a").
*/
/* sort missing IE before (left of) present IE */
if (!ie1)
return -1;
if (!ie2)
return 1;
switch (mode) {
case BSS_CMP_HIDE_ZLEN:
/*
* In ZLEN mode we assume the BSS entry we're
* looking for has a zero-length SSID. So if
* the one we're looking at right now has that,
* return 0. Otherwise, return the difference
* in length, but since we're looking for the
* 0-length it's really equivalent to returning
* the length of the one we're looking at.
*
* No content comparison is needed as we assume
* the content length is zero.
*/
return ie2[1];
case BSS_CMP_REGULAR:
default:
/* sort by length first, then by contents */
if (ie1[1] != ie2[1])
return ie2[1] - ie1[1];
return memcmp(ie1 + 2, ie2 + 2, ie1[1]);
case BSS_CMP_HIDE_NUL:
if (ie1[1] != ie2[1])
return ie2[1] - ie1[1];
/* this is equivalent to memcmp(zeroes, ie2 + 2, len) */
for (i = 0; i < ie2[1]; i++)
if (ie2[i + 2])
return -1;
return 0;
}
}
struct cfg80211_bss *cfg80211_get_bss(struct wiphy *wiphy,
struct ieee80211_channel *channel,
const u8 *bssid,
const u8 *ssid, size_t ssid_len,
u16 capa_mask, u16 capa_val)
{
struct cfg80211_registered_device *dev = wiphy_to_dev(wiphy);
struct cfg80211_internal_bss *bss, *res = NULL;
unsigned long now = jiffies;
trace_cfg80211_get_bss(wiphy, channel, bssid, ssid, ssid_len, capa_mask,
capa_val);
spin_lock_bh(&dev->bss_lock);
list_for_each_entry(bss, &dev->bss_list, list) {
if ((bss->pub.capability & capa_mask) != capa_val)
continue;
if (channel && bss->pub.channel != channel)
continue;
/* Don't get expired BSS structs */
if (time_after(now, bss->ts + IEEE80211_SCAN_RESULT_EXPIRE) &&
!atomic_read(&bss->hold))
continue;
if (is_bss(&bss->pub, bssid, ssid, ssid_len)) {
res = bss;
bss_ref_get(dev, res);
break;
}
}
spin_unlock_bh(&dev->bss_lock);
if (!res)
return NULL;
trace_cfg80211_return_bss(&res->pub);
return &res->pub;
}
EXPORT_SYMBOL(cfg80211_get_bss);
static void rb_insert_bss(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *bss)
{
struct rb_node **p = &dev->bss_tree.rb_node;
struct rb_node *parent = NULL;
struct cfg80211_internal_bss *tbss;
int cmp;
while (*p) {
parent = *p;
tbss = rb_entry(parent, struct cfg80211_internal_bss, rbn);
cmp = cmp_bss(&bss->pub, &tbss->pub, BSS_CMP_REGULAR);
if (WARN_ON(!cmp)) {
/* will sort of leak this BSS */
return;
}
if (cmp < 0)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
rb_link_node(&bss->rbn, parent, p);
rb_insert_color(&bss->rbn, &dev->bss_tree);
}
static struct cfg80211_internal_bss *
rb_find_bss(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *res,
enum bss_compare_mode mode)
{
struct rb_node *n = dev->bss_tree.rb_node;
struct cfg80211_internal_bss *bss;
int r;
while (n) {
bss = rb_entry(n, struct cfg80211_internal_bss, rbn);
r = cmp_bss(&res->pub, &bss->pub, mode);
if (r == 0)
return bss;
else if (r < 0)
n = n->rb_left;
else
n = n->rb_right;
}
return NULL;
}
static bool cfg80211_combine_bsses(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *new)
{
const struct cfg80211_bss_ies *ies;
struct cfg80211_internal_bss *bss;
const u8 *ie;
int i, ssidlen;
u8 fold = 0;
u32 n_entries = 0;
ies = rcu_access_pointer(new->pub.beacon_ies);
if (WARN_ON(!ies))
return false;
ie = cfg80211_find_ie(WLAN_EID_SSID, ies->data, ies->len);
if (!ie) {
/* nothing to do */
return true;
}
ssidlen = ie[1];
for (i = 0; i < ssidlen; i++)
fold |= ie[2 + i];
if (fold) {
/* not a hidden SSID */
return true;
}
/* This is the bad part ... */
list_for_each_entry(bss, &dev->bss_list, list) {
/*
* we're iterating all the entries anyway, so take the
* opportunity to validate the list length accounting
*/
n_entries++;
if (!ether_addr_equal(bss->pub.bssid, new->pub.bssid))
continue;
if (bss->pub.channel != new->pub.channel)
continue;
if (rcu_access_pointer(bss->pub.beacon_ies))
continue;
ies = rcu_access_pointer(bss->pub.ies);
if (!ies)
continue;
ie = cfg80211_find_ie(WLAN_EID_SSID, ies->data, ies->len);
if (!ie)
continue;
if (ssidlen && ie[1] != ssidlen)
continue;
/* that would be odd ... */
if (bss->pub.beacon_ies)
continue;
if (WARN_ON_ONCE(bss->pub.hidden_beacon_bss))
continue;
if (WARN_ON_ONCE(!list_empty(&bss->hidden_list)))
list_del(&bss->hidden_list);
/* combine them */
list_add(&bss->hidden_list, &new->hidden_list);
bss->pub.hidden_beacon_bss = &new->pub;
new->refcount += bss->refcount;
rcu_assign_pointer(bss->pub.beacon_ies,
new->pub.beacon_ies);
}
WARN_ONCE(n_entries != dev->bss_entries,
"rdev bss entries[%d]/list[len:%d] corruption\n",
dev->bss_entries, n_entries);
return true;
}
static struct cfg80211_internal_bss *
cfg80211_bss_update(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *tmp)
{
struct cfg80211_internal_bss *found = NULL;
if (WARN_ON(!tmp->pub.channel))
return NULL;
tmp->ts = jiffies;
spin_lock_bh(&dev->bss_lock);
if (WARN_ON(!rcu_access_pointer(tmp->pub.ies))) {
spin_unlock_bh(&dev->bss_lock);
return NULL;
}
found = rb_find_bss(dev, tmp, BSS_CMP_REGULAR);
if (found) {
/* Update IEs */
if (rcu_access_pointer(tmp->pub.proberesp_ies)) {
const struct cfg80211_bss_ies *old;
old = rcu_access_pointer(found->pub.proberesp_ies);
rcu_assign_pointer(found->pub.proberesp_ies,
tmp->pub.proberesp_ies);
/* Override possible earlier Beacon frame IEs */
rcu_assign_pointer(found->pub.ies,
tmp->pub.proberesp_ies);
if (old)
kfree_rcu((struct cfg80211_bss_ies *)old,
rcu_head);
} else if (rcu_access_pointer(tmp->pub.beacon_ies)) {
const struct cfg80211_bss_ies *old;
struct cfg80211_internal_bss *bss;
if (found->pub.hidden_beacon_bss &&
!list_empty(&found->hidden_list)) {
const struct cfg80211_bss_ies *f;
/*
* The found BSS struct is one of the probe
* response members of a group, but we're
* receiving a beacon (beacon_ies in the tmp
* bss is used). This can only mean that the
* AP changed its beacon from not having an
* SSID to showing it, which is confusing so
* drop this information.
*/
f = rcu_access_pointer(tmp->pub.beacon_ies);
kfree_rcu((struct cfg80211_bss_ies *)f,
rcu_head);
goto drop;
}
old = rcu_access_pointer(found->pub.beacon_ies);
rcu_assign_pointer(found->pub.beacon_ies,
tmp->pub.beacon_ies);
/* Override IEs if they were from a beacon before */
if (old == rcu_access_pointer(found->pub.ies))
rcu_assign_pointer(found->pub.ies,
tmp->pub.beacon_ies);
/* Assign beacon IEs to all sub entries */
list_for_each_entry(bss, &found->hidden_list,
hidden_list) {
const struct cfg80211_bss_ies *ies;
ies = rcu_access_pointer(bss->pub.beacon_ies);
WARN_ON(ies != old);
rcu_assign_pointer(bss->pub.beacon_ies,
tmp->pub.beacon_ies);
}
if (old)
kfree_rcu((struct cfg80211_bss_ies *)old,
rcu_head);
}
found->pub.beacon_interval = tmp->pub.beacon_interval;
found->pub.signal = tmp->pub.signal;
found->pub.capability = tmp->pub.capability;
found->ts = tmp->ts;
} else {
struct cfg80211_internal_bss *new;
struct cfg80211_internal_bss *hidden;
struct cfg80211_bss_ies *ies;
/*
* create a copy -- the "res" variable that is passed in
* is allocated on the stack since it's not needed in the
* more common case of an update
*/
new = kzalloc(sizeof(*new) + dev->wiphy.bss_priv_size,
GFP_ATOMIC);
if (!new) {
ies = (void *)rcu_dereference(tmp->pub.beacon_ies);
if (ies)
kfree_rcu(ies, rcu_head);
ies = (void *)rcu_dereference(tmp->pub.proberesp_ies);
if (ies)
kfree_rcu(ies, rcu_head);
goto drop;
}
memcpy(new, tmp, sizeof(*new));
new->refcount = 1;
INIT_LIST_HEAD(&new->hidden_list);
if (rcu_access_pointer(tmp->pub.proberesp_ies)) {
hidden = rb_find_bss(dev, tmp, BSS_CMP_HIDE_ZLEN);
if (!hidden)
hidden = rb_find_bss(dev, tmp,
BSS_CMP_HIDE_NUL);
if (hidden) {
new->pub.hidden_beacon_bss = &hidden->pub;
list_add(&new->hidden_list,
&hidden->hidden_list);
hidden->refcount++;
rcu_assign_pointer(new->pub.beacon_ies,
hidden->pub.beacon_ies);
}
} else {
/*
* Ok so we found a beacon, and don't have an entry. If
* it's a beacon with hidden SSID, we might be in for an
* expensive search for any probe responses that should
* be grouped with this beacon for updates ...
*/
if (!cfg80211_combine_bsses(dev, new)) {
kfree(new);
goto drop;
}
}
if (dev->bss_entries >= bss_entries_limit &&
!cfg80211_bss_expire_oldest(dev)) {
kfree(new);
goto drop;
}
list_add_tail(&new->list, &dev->bss_list);
dev->bss_entries++;
rb_insert_bss(dev, new);
found = new;
}
dev->bss_generation++;
bss_ref_get(dev, found);
spin_unlock_bh(&dev->bss_lock);
return found;
drop:
spin_unlock_bh(&dev->bss_lock);
return NULL;
}
static struct ieee80211_channel *
cfg80211_get_bss_channel(struct wiphy *wiphy, const u8 *ie, size_t ielen,
struct ieee80211_channel *channel)
{
const u8 *tmp;
u32 freq;
int channel_number = -1;
tmp = cfg80211_find_ie(WLAN_EID_DS_PARAMS, ie, ielen);
if (tmp && tmp[1] == 1) {
channel_number = tmp[2];
} else {
tmp = cfg80211_find_ie(WLAN_EID_HT_OPERATION, ie, ielen);
if (tmp && tmp[1] >= sizeof(struct ieee80211_ht_operation)) {
struct ieee80211_ht_operation *htop = (void *)(tmp + 2);
channel_number = htop->primary_chan;
}
}
if (channel_number < 0)
return channel;
freq = ieee80211_channel_to_frequency(channel_number, channel->band);
channel = ieee80211_get_channel(wiphy, freq);
if (!channel)
return NULL;
if (channel->flags & IEEE80211_CHAN_DISABLED)
return NULL;
return channel;
}
struct cfg80211_bss*
cfg80211_inform_bss(struct wiphy *wiphy,
struct ieee80211_channel *channel,
const u8 *bssid, u64 tsf, u16 capability,
u16 beacon_interval, const u8 *ie, size_t ielen,
s32 signal, gfp_t gfp)
{
struct cfg80211_bss_ies *ies;
struct cfg80211_internal_bss tmp = {}, *res;
if (WARN_ON(!wiphy))
return NULL;
if (WARN_ON(wiphy->signal_type == CFG80211_SIGNAL_TYPE_UNSPEC &&
(signal < 0 || signal > 100)))
return NULL;
channel = cfg80211_get_bss_channel(wiphy, ie, ielen, channel);
if (!channel)
return NULL;
memcpy(tmp.pub.bssid, bssid, ETH_ALEN);
tmp.pub.channel = channel;
tmp.pub.signal = signal;
tmp.pub.beacon_interval = beacon_interval;
tmp.pub.capability = capability;
/*
* Since we do not know here whether the IEs are from a Beacon or Probe
* Response frame, we need to pick one of the options and only use it
* with the driver that does not provide the full Beacon/Probe Response
* frame. Use Beacon frame pointer to avoid indicating that this should
* override the IEs pointer should we have received an earlier
* indication of Probe Response data.
*/
ies = kmalloc(sizeof(*ies) + ielen, gfp);
if (!ies)
return NULL;
ies->len = ielen;
ies->tsf = tsf;
memcpy(ies->data, ie, ielen);
rcu_assign_pointer(tmp.pub.beacon_ies, ies);
rcu_assign_pointer(tmp.pub.ies, ies);
res = cfg80211_bss_update(wiphy_to_dev(wiphy), &tmp);
if (!res)
return NULL;
if (res->pub.capability & WLAN_CAPABILITY_ESS)
regulatory_hint_found_beacon(wiphy, channel, gfp);
trace_cfg80211_return_bss(&res->pub);
/* cfg80211_bss_update gives us a referenced result */
return &res->pub;
}
EXPORT_SYMBOL(cfg80211_inform_bss);
struct cfg80211_bss *
cfg80211_inform_bss_frame(struct wiphy *wiphy,
struct ieee80211_channel *channel,
struct ieee80211_mgmt *mgmt, size_t len,
s32 signal, gfp_t gfp)
{
struct cfg80211_internal_bss tmp = {}, *res;
struct cfg80211_bss_ies *ies;
size_t ielen = len - offsetof(struct ieee80211_mgmt,
u.probe_resp.variable);
BUILD_BUG_ON(offsetof(struct ieee80211_mgmt, u.probe_resp.variable) !=
offsetof(struct ieee80211_mgmt, u.beacon.variable));
trace_cfg80211_inform_bss_frame(wiphy, channel, mgmt, len, signal);
if (WARN_ON(!mgmt))
return NULL;
if (WARN_ON(!wiphy))
return NULL;
if (WARN_ON(wiphy->signal_type == CFG80211_SIGNAL_TYPE_UNSPEC &&
(signal < 0 || signal > 100)))
return NULL;
if (WARN_ON(len < offsetof(struct ieee80211_mgmt, u.probe_resp.variable)))
return NULL;
channel = cfg80211_get_bss_channel(wiphy, mgmt->u.beacon.variable,
ielen, channel);
if (!channel)
return NULL;
ies = kmalloc(sizeof(*ies) + ielen, gfp);
if (!ies)
return NULL;
ies->len = ielen;
ies->tsf = le64_to_cpu(mgmt->u.probe_resp.timestamp);
memcpy(ies->data, mgmt->u.probe_resp.variable, ielen);
if (ieee80211_is_probe_resp(mgmt->frame_control))
rcu_assign_pointer(tmp.pub.proberesp_ies, ies);
else
rcu_assign_pointer(tmp.pub.beacon_ies, ies);
rcu_assign_pointer(tmp.pub.ies, ies);
memcpy(tmp.pub.bssid, mgmt->bssid, ETH_ALEN);
tmp.pub.channel = channel;
tmp.pub.signal = signal;
tmp.pub.beacon_interval = le16_to_cpu(mgmt->u.probe_resp.beacon_int);
tmp.pub.capability = le16_to_cpu(mgmt->u.probe_resp.capab_info);
res = cfg80211_bss_update(wiphy_to_dev(wiphy), &tmp);
if (!res)
return NULL;
if (res->pub.capability & WLAN_CAPABILITY_ESS)
regulatory_hint_found_beacon(wiphy, channel, gfp);
trace_cfg80211_return_bss(&res->pub);
/* cfg80211_bss_update gives us a referenced result */
return &res->pub;
}
EXPORT_SYMBOL(cfg80211_inform_bss_frame);
void cfg80211_ref_bss(struct wiphy *wiphy, struct cfg80211_bss *pub)
{
struct cfg80211_registered_device *dev = wiphy_to_dev(wiphy);
struct cfg80211_internal_bss *bss;
if (!pub)
return;
bss = container_of(pub, struct cfg80211_internal_bss, pub);
spin_lock_bh(&dev->bss_lock);
bss_ref_get(dev, bss);
spin_unlock_bh(&dev->bss_lock);
}
EXPORT_SYMBOL(cfg80211_ref_bss);
void cfg80211_put_bss(struct wiphy *wiphy, struct cfg80211_bss *pub)
{
struct cfg80211_registered_device *dev = wiphy_to_dev(wiphy);
struct cfg80211_internal_bss *bss;
if (!pub)
return;
bss = container_of(pub, struct cfg80211_internal_bss, pub);
spin_lock_bh(&dev->bss_lock);
bss_ref_put(dev, bss);
spin_unlock_bh(&dev->bss_lock);
}
EXPORT_SYMBOL(cfg80211_put_bss);
void cfg80211_unlink_bss(struct wiphy *wiphy, struct cfg80211_bss *pub)
{
struct cfg80211_registered_device *dev = wiphy_to_dev(wiphy);
struct cfg80211_internal_bss *bss;
if (WARN_ON(!pub))
return;
bss = container_of(pub, struct cfg80211_internal_bss, pub);
spin_lock_bh(&dev->bss_lock);
if (!list_empty(&bss->list)) {
if (__cfg80211_unlink_bss(dev, bss))
dev->bss_generation++;
}
spin_unlock_bh(&dev->bss_lock);
}
EXPORT_SYMBOL(cfg80211_unlink_bss);
#ifdef CONFIG_CFG80211_WEXT
int cfg80211_wext_siwscan(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct cfg80211_registered_device *rdev;
struct wiphy *wiphy;
struct iw_scan_req *wreq = NULL;
struct cfg80211_scan_request *creq = NULL;
int i, err, n_channels = 0;
enum ieee80211_band band;
if (!netif_running(dev))
return -ENETDOWN;
if (wrqu->data.length == sizeof(struct iw_scan_req))
wreq = (struct iw_scan_req *)extra;
rdev = cfg80211_get_dev_from_ifindex(dev_net(dev), dev->ifindex);
if (IS_ERR(rdev))
return PTR_ERR(rdev);
mutex_lock(&rdev->sched_scan_mtx);
if (rdev->scan_req) {
err = -EBUSY;
goto out;
}
wiphy = &rdev->wiphy;
/* Determine number of channels, needed to allocate creq */
if (wreq && wreq->num_channels)
n_channels = wreq->num_channels;
else {
for (band = 0; band < IEEE80211_NUM_BANDS; band++)
if (wiphy->bands[band])
n_channels += wiphy->bands[band]->n_channels;
}
creq = kzalloc(sizeof(*creq) + sizeof(struct cfg80211_ssid) +
n_channels * sizeof(void *),
GFP_ATOMIC);
if (!creq) {
err = -ENOMEM;
goto out;
}
creq->wiphy = wiphy;
creq->wdev = dev->ieee80211_ptr;
/* SSIDs come after channels */
creq->ssids = (void *)&creq->channels[n_channels];
creq->n_channels = n_channels;
creq->n_ssids = 1;
creq->scan_start = jiffies;
/* translate "Scan on frequencies" request */
i = 0;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
/* ignore disabled channels */
if (wiphy->bands[band]->channels[j].flags &
IEEE80211_CHAN_DISABLED)
continue;
/* If we have a wireless request structure and the
* wireless request specifies frequencies, then search
* for the matching hardware channel.
*/
if (wreq && wreq->num_channels) {
int k;
int wiphy_freq = wiphy->bands[band]->channels[j].center_freq;
for (k = 0; k < wreq->num_channels; k++) {
int wext_freq = cfg80211_wext_freq(wiphy, &wreq->channel_list[k]);
if (wext_freq == wiphy_freq)
goto wext_freq_found;
}
goto wext_freq_not_found;
}
wext_freq_found:
creq->channels[i] = &wiphy->bands[band]->channels[j];
i++;
wext_freq_not_found: ;
}
}
/* No channels found? */
if (!i) {
err = -EINVAL;
goto out;
}
/* Set real number of channels specified in creq->channels[] */
creq->n_channels = i;
/* translate "Scan for SSID" request */
if (wreq) {
if (wrqu->data.flags & IW_SCAN_THIS_ESSID) {
if (wreq->essid_len > IEEE80211_MAX_SSID_LEN) {
err = -EINVAL;
goto out;
}
memcpy(creq->ssids[0].ssid, wreq->essid, wreq->essid_len);
creq->ssids[0].ssid_len = wreq->essid_len;
}
if (wreq->scan_type == IW_SCAN_TYPE_PASSIVE)
creq->n_ssids = 0;
}
for (i = 0; i < IEEE80211_NUM_BANDS; i++)
if (wiphy->bands[i])
creq->rates[i] = (1 << wiphy->bands[i]->n_bitrates) - 1;
rdev->scan_req = creq;
err = rdev_scan(rdev, creq);
if (err) {
rdev->scan_req = NULL;
/* creq will be freed below */
} else {
nl80211_send_scan_start(rdev, dev->ieee80211_ptr);
/* creq now owned by driver */
creq = NULL;
dev_hold(dev);
}
out:
mutex_unlock(&rdev->sched_scan_mtx);
kfree(creq);
cfg80211_unlock_rdev(rdev);
return err;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwscan);
static void ieee80211_scan_add_ies(struct iw_request_info *info,
const struct cfg80211_bss_ies *ies,
char **current_ev, char *end_buf)
{
const u8 *pos, *end, *next;
struct iw_event iwe;
if (!ies)
return;
/*
* If needed, fragment the IEs buffer (at IE boundaries) into short
* enough fragments to fit into IW_GENERIC_IE_MAX octet messages.
*/
pos = ies->data;
end = pos + ies->len;
while (end - pos > IW_GENERIC_IE_MAX) {
next = pos + 2 + pos[1];
while (next + 2 + next[1] - pos < IW_GENERIC_IE_MAX)
next = next + 2 + next[1];
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVGENIE;
iwe.u.data.length = next - pos;
*current_ev = iwe_stream_add_point(info, *current_ev,
end_buf, &iwe,
(void *)pos);
pos = next;
}
if (end > pos) {
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVGENIE;
iwe.u.data.length = end - pos;
*current_ev = iwe_stream_add_point(info, *current_ev,
end_buf, &iwe,
(void *)pos);
}
}
static char *
ieee80211_bss(struct wiphy *wiphy, struct iw_request_info *info,
struct cfg80211_internal_bss *bss, char *current_ev,
char *end_buf)
{
const struct cfg80211_bss_ies *ies;
struct iw_event iwe;
const u8 *ie;
u8 *buf, *cfg, *p;
int rem, i, sig;
bool ismesh = false;
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWAP;
iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
memcpy(iwe.u.ap_addr.sa_data, bss->pub.bssid, ETH_ALEN);
current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe,
IW_EV_ADDR_LEN);
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWFREQ;
iwe.u.freq.m = ieee80211_frequency_to_channel(bss->pub.channel->center_freq);
iwe.u.freq.e = 0;
current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe,
IW_EV_FREQ_LEN);
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWFREQ;
iwe.u.freq.m = bss->pub.channel->center_freq;
iwe.u.freq.e = 6;
current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe,
IW_EV_FREQ_LEN);
if (wiphy->signal_type != CFG80211_SIGNAL_TYPE_NONE) {
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVQUAL;
iwe.u.qual.updated = IW_QUAL_LEVEL_UPDATED |
IW_QUAL_NOISE_INVALID |
IW_QUAL_QUAL_UPDATED;
switch (wiphy->signal_type) {
case CFG80211_SIGNAL_TYPE_MBM:
sig = bss->pub.signal / 100;
iwe.u.qual.level = sig;
iwe.u.qual.updated |= IW_QUAL_DBM;
if (sig < -110) /* rather bad */
sig = -110;
else if (sig > -40) /* perfect */
sig = -40;
/* will give a range of 0 .. 70 */
iwe.u.qual.qual = sig + 110;
break;
case CFG80211_SIGNAL_TYPE_UNSPEC:
iwe.u.qual.level = bss->pub.signal;
/* will give range 0 .. 100 */
iwe.u.qual.qual = bss->pub.signal;
break;
default:
/* not reached */
break;
}
current_ev = iwe_stream_add_event(info, current_ev, end_buf,
&iwe, IW_EV_QUAL_LEN);
}
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWENCODE;
if (bss->pub.capability & WLAN_CAPABILITY_PRIVACY)
iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
else
iwe.u.data.flags = IW_ENCODE_DISABLED;
iwe.u.data.length = 0;
current_ev = iwe_stream_add_point(info, current_ev, end_buf,
&iwe, "");
rcu_read_lock();
ies = rcu_dereference(bss->pub.ies);
rem = ies->len;
ie = ies->data;
while (rem >= 2) {
/* invalid data */
if (ie[1] > rem - 2)
break;
switch (ie[0]) {
case WLAN_EID_SSID:
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWESSID;
iwe.u.data.length = ie[1];
iwe.u.data.flags = 1;
current_ev = iwe_stream_add_point(info, current_ev, end_buf,
&iwe, (u8 *)ie + 2);
break;
case WLAN_EID_MESH_ID:
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWESSID;
iwe.u.data.length = ie[1];
iwe.u.data.flags = 1;
current_ev = iwe_stream_add_point(info, current_ev, end_buf,
&iwe, (u8 *)ie + 2);
break;
case WLAN_EID_MESH_CONFIG:
ismesh = true;
if (ie[1] != sizeof(struct ieee80211_meshconf_ie))
break;
buf = kmalloc(50, GFP_ATOMIC);
if (!buf)
break;
cfg = (u8 *)ie + 2;
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVCUSTOM;
sprintf(buf, "Mesh Network Path Selection Protocol ID: "
"0x%02X", cfg[0]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Path Selection Metric ID: 0x%02X",
cfg[1]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Congestion Control Mode ID: 0x%02X",
cfg[2]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Synchronization ID: 0x%02X", cfg[3]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Authentication ID: 0x%02X", cfg[4]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Formation Info: 0x%02X", cfg[5]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Capabilities: 0x%02X", cfg[6]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
kfree(buf);
break;
case WLAN_EID_SUPP_RATES:
case WLAN_EID_EXT_SUPP_RATES:
/* display all supported rates in readable format */
p = current_ev + iwe_stream_lcp_len(info);
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWRATE;
/* Those two flags are ignored... */
iwe.u.bitrate.fixed = iwe.u.bitrate.disabled = 0;
for (i = 0; i < ie[1]; i++) {
iwe.u.bitrate.value =
((ie[i + 2] & 0x7f) * 500000);
p = iwe_stream_add_value(info, current_ev, p,
end_buf, &iwe, IW_EV_PARAM_LEN);
}
current_ev = p;
break;
}
rem -= ie[1] + 2;
ie += ie[1] + 2;
}
if (bss->pub.capability & (WLAN_CAPABILITY_ESS | WLAN_CAPABILITY_IBSS) ||
ismesh) {
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWMODE;
if (ismesh)
iwe.u.mode = IW_MODE_MESH;
else if (bss->pub.capability & WLAN_CAPABILITY_ESS)
iwe.u.mode = IW_MODE_MASTER;
else
iwe.u.mode = IW_MODE_ADHOC;
current_ev = iwe_stream_add_event(info, current_ev, end_buf,
&iwe, IW_EV_UINT_LEN);
}
buf = kmalloc(31, GFP_ATOMIC);
if (buf) {
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVCUSTOM;
sprintf(buf, "tsf=%016llx", (unsigned long long)(ies->tsf));
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev, end_buf,
&iwe, buf);
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVCUSTOM;
sprintf(buf, " Last beacon: %ums ago",
elapsed_jiffies_msecs(bss->ts));
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf, &iwe, buf);
kfree(buf);
}
ieee80211_scan_add_ies(info, ies, ¤t_ev, end_buf);
rcu_read_unlock();
return current_ev;
}
static int ieee80211_scan_results(struct cfg80211_registered_device *dev,
struct iw_request_info *info,
char *buf, size_t len)
{
char *current_ev = buf;
char *end_buf = buf + len;
struct cfg80211_internal_bss *bss;
spin_lock_bh(&dev->bss_lock);
cfg80211_bss_expire(dev);
list_for_each_entry(bss, &dev->bss_list, list) {
if (buf + len - current_ev <= IW_EV_ADDR_LEN) {
spin_unlock_bh(&dev->bss_lock);
return -E2BIG;
}
current_ev = ieee80211_bss(&dev->wiphy, info, bss,
current_ev, end_buf);
}
spin_unlock_bh(&dev->bss_lock);
return current_ev - buf;
}
int cfg80211_wext_giwscan(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *data, char *extra)
{
struct cfg80211_registered_device *rdev;
int res;
if (!netif_running(dev))
return -ENETDOWN;
rdev = cfg80211_get_dev_from_ifindex(dev_net(dev), dev->ifindex);
if (IS_ERR(rdev))
return PTR_ERR(rdev);
if (rdev->scan_req) {
res = -EAGAIN;
goto out;
}
res = ieee80211_scan_results(rdev, info, extra, data->length);
data->length = 0;
if (res >= 0) {
data->length = res;
res = 0;
}
out:
cfg80211_unlock_rdev(rdev);
return res;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwscan);
#endif
| koquantam/android_kernel_samsung_grandprimeve3g-CORE | net/wireless/scan.c | C | gpl-2.0 | 40,870 |
<?php
// ********** modify blog option 'wp_mobile_template' manually to specify a theme (ex. 'vip/cnnmobile')
// WordPress Mobile Edition
//
// Copyright (c) 2002-2008 Alex King
// http://alexking.org/projects/wordpress
//
// Released under the GPL license
// http://www.opensource.org/licenses/gpl-license.php
//
// **********************************************************************
// 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.
// *****************************************************************
/*
Plugin Name: WordPress Mobile Edition
Plugin URI: http://alexking.org/projects/wordpress
Description: Show a mobile view of the post/page if the visitor is on a known mobile device. Questions on configuration, etc.? Make sure to read the README.
Author: Alex King
Author URI: http://alexking.org
Version: 2.1a-WPCOM
*/
$_SERVER['REQUEST_URI'] = ( isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $_SERVER['SCRIPT_NAME'] . (( isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '')));
function jetpack_check_mobile() {
if ( ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) || ( defined('APP_REQUEST') && APP_REQUEST ) )
return false;
if ( !isset($_SERVER["HTTP_USER_AGENT"]) || (isset($_COOKIE['akm_mobile']) && $_COOKIE['akm_mobile'] == 'false') )
return false;
if ( jetpack_mobile_exclude() )
return false;
if ( 1 == get_option('wp_mobile_disable') )
return false;
if ( isset($_COOKIE['akm_mobile']) && $_COOKIE['akm_mobile'] == 'true' )
return true;
$is_mobile = jetpack_is_mobile();
return apply_filters( 'jetpack_check_mobile', $is_mobile );
}
function jetpack_mobile_exclude() {
$exclude = false;
$pages_to_exclude = array(
'wp-admin',
'wp-comments-post.php',
'wp-mail.php',
'wp-login.php',
'wp-activate.php',
);
foreach ( $pages_to_exclude as $exclude_page ) {
if ( strstr( strtolower( $_SERVER['REQUEST_URI'] ), $exclude_page ) )
$exclude = true;
}
if ( defined( 'DOING_AJAX' ) && true === DOING_AJAX )
$exclude = false;
return $exclude;
}
function wp_mobile_get_main_template() {
remove_action( 'option_template', 'jetpack_mobile_template' );
$template = get_option( 'template' );
add_action( 'option_template', 'jetpack_mobile_template' );
return $template;
}
function wp_mobile_get_main_stylesheet() {
remove_action( 'option_stylesheet', 'jetpack_mobile_stylesheet' );
$stylesheet = get_option( 'stylesheet' );
add_action( 'option_stylesheet', 'jetpack_mobile_stylesheet' );
return $stylesheet;
}
function jetpack_mobile_stylesheet( $theme ) {
return apply_filters( 'jetpack_mobile_stylesheet', 'pub/minileven', $theme );
}
function jetpack_mobile_template( $theme ) {
return apply_filters( 'jetpack_mobile_template', 'pub/minileven', $theme );
}
function jetpack_mobile_available() {
echo '<div style="text-align:center;margin:10px 0;"><a href="'. home_url( '?ak_action=accept_mobile' ) . '">' . __( 'View Mobile Site', 'jetpack' ) . '</a></div>';
}
function jetpack_mobile_request_handler() {
global $wpdb;
if (isset($_GET['ak_action'])) {
$url = parse_url( get_bloginfo( 'url' ) );
$domain = $url['host'];
if (!empty($url['path'])) {
$path = $url['path'];
}
else {
$path = '/';
}
$redirect = false;
switch ($_GET['ak_action']) {
case 'reject_mobile':
setcookie(
'akm_mobile'
, 'false'
, time() + 300000
, $path
, $domain
);
$redirect = true;
do_action( 'mobile_reject_mobile' );
break;
case 'force_mobile':
case 'accept_mobile':
setcookie(
'akm_mobile'
, 'true'
, time() + 300000
, $path
, $domain
);
$redirect = true;
do_action( 'mobile_force_mobile' );
break;
}
if ($redirect) {
if ( isset( $_GET['redirect_to'] ) && $_GET['redirect_to'] ) {
$go = urldecode( $_GET['redirect_to'] );
} else if (!empty($_SERVER['HTTP_REFERER'])) {
$go = $_SERVER['HTTP_REFERER'];
}
else {
$go = remove_query_arg( array( 'ak_action' ) );
}
wp_safe_redirect( $go );
exit;
}
}
}
add_action('init', 'jetpack_mobile_request_handler');
function jetpack_mobile_theme_setup() {
if ( jetpack_check_mobile() ) {
// Redirect to download page if user clicked mobile app promo link in mobile footer
if ( isset( $_GET['app-download'] ) ) {
do_action( 'mobile_app_promo_download', $_GET['app-download'] );
switch ( $_GET['app-download'] ) {
case 'android':
header( 'Location: market://search?q=pname:org.wordpress.android' );
exit;
break;
case 'ios':
header( 'Location: http://itunes.apple.com/us/app/wordpress/id335703880?mt=8' );
exit;
break;
case 'blackberry':
header( 'Location: http://blackberry.wordpress.org/download/' );
exit;
break;
case 'nokia':
header( 'Location: http://nokia.wordpress.org/download/' );
exit;
break;
case 'windowsphone':
header( 'Location: http://social.zune.net/redirect?type=phoneApp&id=5f64ad85-f801-e011-9264-00237de2db9e' );
exit;
break;
}
}
add_action('stylesheet', 'jetpack_mobile_stylesheet');
add_action('template', 'jetpack_mobile_template');
add_action('option_template', 'jetpack_mobile_template');
add_action('option_stylesheet', 'jetpack_mobile_stylesheet');
if ( function_exists( 'disable_safecss_style' ) && ! get_option( 'wp_mobile_custom_css' ) )
add_action( 'init', 'disable_safecss_style', 11 );
do_action( 'mobile_setup' );
}
}
// Need a hook after plugins_loaded (since this code won't be loaded in Jetpack
// until then) but after init (because it has its own init hooks to add).
add_action( 'setup_theme', 'jetpack_mobile_theme_setup' );
if (isset($_COOKIE['akm_mobile']) && $_COOKIE['akm_mobile'] == 'false') {
add_action('wp_footer', 'jetpack_mobile_available');
}
add_action( 'wp_footer', 'mobile_admin_bar', 20 );
function mobile_admin_bar() {
global $wp_version;
if ( jetpack_is_mobile() && 1 != version_compare( $wp_version, '3.5-beta3-22631' ) ) :
// This fix was made unnecessary in http://core.trac.wordpress.org/changeset/22636
?>
<script type="text/javascript" id='mobile-admin-bar'>
jQuery( function( $ ) {
var menupop = $( '#wpadminbar .ab-top-menu > li.menupop' )
.unbind( 'mouseover' )
.unbind( 'mouseout' )
.click( function ( e ) {
$( this ).toggleClass( 'hover' );
$( '#wpadminbar .menupop' ).not( this ).removeClass( 'hover' );
} )
.children( 'a' )
.click( function( e ) {
e.preventDefault();
} );
$( '#wpadminbar' ).css( 'position', 'absolute' );
$( '#ab-reblog-box' ).css( 'position', 'absolute' );
} );
</script>
<?php
endif;
}
function jetpack_mobile_app_promo() {
?>
<script type="text/javascript">
if ( ! navigator.userAgent.match( /wp-(iphone|android|blackberry|nokia|windowsphone)/i ) ) {
if ( ( navigator.userAgent.match( /iphone/i ) ) || ( navigator.userAgent.match( /ipod/i ) ) )
document.write( '<span id="wpcom-mobile-app-promo" style="margin-top: 10px; font-size: 13px;"><strong>Now Available!</strong> <a href="/index.php?app-download=ios">Download WordPress for iOS</a></span><br /><br />' );
else if ( ( navigator.userAgent.match( /android/i ) ) )
document.write( '<span id="wpcom-mobile-app-promo" style="margin-top: 10px; font-size: 13px;"><strong>Now Available!</strong> <a href="/index.php?app-download=android">Download WordPress for Android</a></span><br /><br />' );
else if ( ( navigator.userAgent.match( /blackberry/i ) ) )
document.write( '<span id="wpcom-mobile-app-promo" style="margin-top: 10px; font-size: 13px;"><strong>Now Available!</strong> <a href="/index.php?app-download=blackberry">Download WordPress for BlackBerry</a></span><br /><br />' );
else if ( ( navigator.userAgent.match( /windows phone os/i ) ) )
document.write( '<span id="wpcom-mobile-app-promo" style="margin-top: 10px; font-size: 13px; line-height: 13px;"><strong>Now Available!</strong> <a href="/index.php?app-download=windowsphone">Download WordPress for <br />Windows Phone</a></span><br /><br />' );
else if ( ( navigator.userAgent.match( /nokia/i ) ) )
document.write( '<span id="wpcom-mobile-app-promo" style="margin-top: 10px; font-size: 13px;"><strong>Now Available!</strong> <a href="/index.php?app-download=nokia">Download WordPress for Nokia</a></span><br /><br />' );
}
</script>
<?php
}
add_action( 'wp_mobile_theme_footer', 'jetpack_mobile_app_promo' );
/**
* Adds an option to allow your Custom CSS to also be applied to the Mobile Theme.
* It's disabled by default, but this should allow people who know what they're
* doing to customize the mobile theme.
*/
function jetpack_mobile_css_settings() {
$mobile_css = get_option( 'wp_mobile_custom_css' );
?>
<div class="misc-pub-section">
<label><?php esc_html_e( 'Mobile-compatible:' , 'jetpack'); ?></label>
<span id="mobile-css-display"><?php echo $mobile_css ? __( 'Yes', 'jetpack' ) : __( 'No', 'jetpack' ); ?></span>
<a class="edit-mobile-css hide-if-no-js" href="#mobile-css"><?php echo esc_html_e( 'Edit', 'jetpack' ); ?></a>
<div id="mobile-css-select" class="hide-if-js">
<input type="hidden" name="mobile_css" id="mobile-css" value="<?php echo intval( $mobile_css ); ?>" />
<label>
<input type="checkbox" id="mobile-css-visible" <?php checked( get_option( 'wp_mobile_custom_css' ) ); ?> />
<?php esc_html_e( 'Include this CSS in the Mobile Theme', 'jetpack' ); ?>
</label>
<p>
<a class="save-mobile-css hide-if-no-js button" href="#mobile-css"><?php esc_html_e( 'OK', 'jetpack' ); ?></a>
<a class="cancel-mobile-css hide-if-no-js" href="#mobile-css"><?php esc_html_e( 'Cancel', 'jetpack' ); ?></a>
</p>
</div>
</div>
<script type="text/javascript">
jQuery( function ( $ ) {
$( '.edit-mobile-css' ).bind( 'click', function ( e ) {
e.preventDefault();
$( '#mobile-css-select' ).slideDown();
$( this ).hide();
} );
$( '.cancel-mobile-css' ).bind( 'click', function ( e ) {
e.preventDefault();
$( '#mobile-css-select' ).slideUp( function () {
$( '.edit-mobile-css' ).show();
$( '#mobile-css-visible' ).prop( 'checked', $( '#mobile-css' ).val() == '1' );
} );
} );
$( '.save-mobile-css' ).bind( 'click', function ( e ) {
e.preventDefault();
$( '#mobile-css-select' ).slideUp();
$( '#mobile-css-display' ).text( $( '#mobile-css-visible' ).prop( 'checked' ) ? 'Yes' : 'No' );
$( '#mobile-css' ).val( $( '#mobile-css-visible' ).prop( 'checked' ) ? '1' : '0' );
$( '.edit-mobile-css' ).show();
} );
} );
</script>
<?php
}
add_action( 'custom_css_submitbox_misc_actions', 'jetpack_mobile_css_settings' );
function jetpack_mobile_save_css_settings() {
update_option( 'wp_mobile_custom_css', isset( $_POST['mobile_css'] ) && ! empty( $_POST['mobile_css'] ) );
}
add_action( 'safecss_save_pre', 'jetpack_mobile_save_css_settings' );
| pankajmore/hall1 | wp-content/plugins/jetpack/modules/minileven/minileven.php | PHP | gpl-2.0 | 11,054 |
/*! scrollVert transition plugin for Cycle2; version: 20121120 */
(function($) {
"use strict";
$.fn.cycle2.transitions.scrollVert = {
before: function( opts, curr, next, fwd ) {
opts.API.stackSlides( opts, curr, next, fwd );
var height = opts.container.css('overflow','hidden').height();
opts.cssBefore = { top: fwd ? -height : height, left: 0, opacity: 1, display: 'block' };
opts.animIn = { top: 0 };
opts.animOut = { top: fwd ? height : -height };
}
};
})(jQuery);
| javalidigital/javali | wp-content/plugins/rotatingtweets/js/jquery.cycle2.scrollVert.renamed.js | JavaScript | gpl-2.0 | 521 |
<?php
namespace TYPO3\CMS\Core\Tests\Unit\Configuration\TypoScript\ConditionMatching\Fixtures;
/*
* 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!
*/
/**
* Fixture for TYPO3\CMS\Core\Utility\GeneralUtility
*/
class GeneralUtilityFixture extends \TYPO3\CMS\Core\Utility\GeneralUtility
{
/**
* @param \TYPO3\CMS\Core\Core\ApplicationContext $applicationContext
*/
public static function setApplicationContext($applicationContext)
{
static::$applicationContext = $applicationContext;
}
}
| morinfa/TYPO3.CMS | typo3/sysext/core/Tests/Unit/Configuration/TypoScript/ConditionMatching/Fixtures/GeneralUtilityFixture.php | PHP | gpl-2.0 | 889 |
/* paste-plugin.js is part of Aloha Editor project http://aloha-editor.org
*
* Aloha Editor is a WYSIWYG HTML5 inline editing library and editor.
* Copyright (c) 2010-2013 Gentics Software GmbH, Vienna, Austria.
* Contributors http://aloha-editor.org/contribution.php
*
* Aloha Editor 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 any later version.
*
* Aloha Editor 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.
*
* As an additional permission to the GNU GPL version 2, you may distribute
* non-source (e.g., minimized or compacted) forms of the Aloha-Editor
* source code without the copy of the GNU GPL normally required,
* provided you include this license notice and a URL through which
* recipients can access the Corresponding Source.
*
* @overview:
* The paste plugin intercepts all browser paste events that target aloha
* editables, and redirects the events into a hidden div. Once pasting is done
* into this div, its contents will be processed by registered content handlers
* before being copied into the active editable, at the current range.
*/
define([
'jquery',
'aloha/core',
'aloha/plugin',
'aloha/command',
'contenthandler/contenthandler-utils',
'aloha/console',
'aloha/copypaste',
'aloha/contenthandlermanager',
'util/browser'
], function (
$,
Aloha,
Plugin,
Commands,
ContentHandlerUtils,
Console,
CopyPaste,
ContentHandlerManager,
Browser
) {
'use strict';
/**
* Reference to global window object, for quicker lookup.
*
* @type {jQuery.<window>}
* @const
*/
var $WINDOW = $(window);
/**
* Whether or not the user-agent is Internet Explorer.
*
* @type {boolean}
* @const
*/
var IS_IE = !!Aloha.browser.msie;
/**
* Matches as string consisting of a single white space character.
*
* '%A0' is used instead of ' ' because it seems that IE transforms
* non-breaking spaces into atomic tokens.
*
* @type {RegExp}
* @const
*/
var PROPPING_SPACE = /^(\s|%A0)$/;
/**
* An invisible editable element used to intercept incoming pasted content
* so that it can be processed before being placed into real editables.
*
* In order to hide the editable div we use clip:rect for WebKit (Chrome,
* Safari) and Trident (IE), and width/height for Gecko (FF).
*
* @type {jQuery.<HTMLElement>}
* @const
*/
var $CLIPBOARD = $('<div style="position:absolute; ' +
'clip:rect(0px,0px,0px,0px); ' +
'width:1px; height:1px;"></div>').contentEditable(true);
/**
* Stored range, use to accomplish IE hack.
*
* @type {WrappedRange}
*/
var ieRangeBeforePaste = null;
/**
* The window's scroll position at the moment just before pasting is done
* (beforepaste and paste events).
*
* @type {object}
* @property {Number} x
* @property {Number} y
**/
var scrollPositionBeforePaste = {
x: 0,
y: 0
};
/**
* Set the selection to the given range and focus on the editable in which
* the selection is in (if any).
*
* This function is used to restore the selection to what it was before
* calling redirectPaste() at the offset of the pasting process.
*
* @param {WrappedRange} range The range to restore.
*/
function restoreSelection(range) {
CopyPaste.setSelectionAt(range);
window.scrollTo(
scrollPositionBeforePaste.x,
scrollPositionBeforePaste.y
);
}
/**
* Redirects a paste event from the given range into a specified target
* element.
*
* This function is used to cause paste events that are targeting to
* editables to instead land in an invisible clipboard div that serves as a
* staging area to handle the incoming content before actually placing it
* into the intended editable.
*
* @param {WrappedRange} range The range at the time that the paste event
* was initiated.
* @param {jQuery.<HTMLElement>} $target A jQuery object containing the DOM
* element to which the paste event
* is to be directed to.
*/
function redirect(range, $target) {
var width = 200;
// Because moving the target element to the current scroll position
// avoids jittering the viewport when the pasted content moves between
// where the range is and target.
$target.css({
top: $WINDOW.scrollTop(),
left: $WINDOW.scrollLeft() - width,
width: width,
overflow: 'hidden'
}).contents().remove();
var from = CopyPaste.getEditableAt(range);
if (from) {
from.obj.blur();
}
// Because the selection should end up inside the target element.
CopyPaste.setSelectionAt({
startContainer: $target[0],
endContainer: $target[0],
startOffset: 0,
endOffset: 0
});
$target.focus();
}
/**
* Detects a situation where paste is about to be done into a selection
* beginning inside markup that looks exactly like this:
*
* '<p> </p>'
*
* or roughly like this:
*
* '<p><br/></p>'
*
* Both markups denote a "propped" paragraph. A propped paragraph is one
* which contains content that has been placed in it for the sole purpose
* of forcing the layout engine to render the node visibly. HTML5 standard
* conformance requires that empty block elements like <p> be rendered
* invisibly, and comformant browsers like WebKit would place <br> nodes
* inside content-editable paragraphs so that they can be visible for
* editing.
*
* IE is _not_ standard comformant however, because it renders empty <p>
* with a line-height of 1. Adding a <br> elements inside it results in
* the <p> appearing with 2 lines.
*
* If we detect this situation, the white space is removed so that after
* pasting a new paragraph into the paragraph, it will not be split leaving
* an empty paragraph on top of the pasted content. Therefore when working
* in IE, a space is placed inside an empty paragraph rather than a <br>.
* Hence markup like '<p> </p>'.
*
* @param {WrappedRange} range
* @return {boolean} True if range starts in propping node.
*/
function rangeStartsAtProppedParagraph(range) {
var start = range.startContainer;
if (1 === start.nodeType) {
return ('p' === start.nodeName.toLowerCase() &&
ContentHandlerUtils.isProppedParagraph(start.outerHTML));
}
return (3 === start.nodeType &&
'p' === start.parentNode.nodeName.toLowerCase() &&
1 === start.parentNode.childNodes.length &&
PROPPING_SPACE.test(window.escape(start.data)));
}
/**
* Prepare the nodes around where pasted content is to land.
*
* @param {WrappedRange} range
*/
function prepRangeForPaste(range) {
if (rangeStartsAtProppedParagraph(range)) {
if (3 === range.startContainer.nodeType) {
range.startContainer.data = '';
} else {
range.startContainer.innerHTML = ' ';
}
range.startOffset = 0;
// Because of situations like <p>[ ]</p> or <p>[<br/>]</p>
if (range.endContainer === range.startContainer) {
range.endOffset = 0;
}
}
}
/**
* Delete the first match in a string
*
* @param {String} string String to modify
* @param {String} match Match string must be replaced
* @returns {string} Original string with the first match replaced.
*/
function deleteFirstMatch(string, match) {
return string.replace(match, '');
}
/**
* Delete the first Header tag if exists.
*
* @param htmlString
* @returns {XML|string}
*/
function deleteFirstHeaderTag(htmlString) {
var matchFirstHeaderTag = /^<h\d+.*?>/i.exec(htmlString),
startHeaderTag,
endHeaderTag;
if (matchFirstHeaderTag === null) {
return htmlString;
}
startHeaderTag = matchFirstHeaderTag[0];
endHeaderTag = '</' + startHeaderTag.substr(1);
return deleteFirstMatch(
deleteFirstMatch(htmlString, startHeaderTag),
endHeaderTag
);
}
/**
* Checks if browser and document mode are 9 or above versions.
* @param {Document} doc
* @return {boolean}
*/
function isIEorDocModeGreater9(doc) {
return Browser.ie && doc.documentMode >= 9;
}
/**
* Gets the pasted content and inserts them into the current active
* editable.
*
* @param {jQuery.<HTMLElement>} $clipboard A jQuery object containing an
* element holding the copied
* content that will be placed at
* the given range.
* @param {WrappedRange} range The range at which to place the contents
* from $clipboard.
*
* @param {function=} callback An optional callback function to call after
* pasting is completed.
*/
function paste($clipboard, range, callback) {
if (!range) {
return;
}
var content = deleteFirstHeaderTag($clipboard.html());
var handler = ContentHandlerManager.get('formatless');
content = handler ? handler.handleContent(content) : content;
// Because IE inserts an insidious nbsp into the content during pasting
// that needs to be removed. Leaving it would otherwise result in an
// empty paragraph being created right before the pasted content when
// the pasted content is a paragraph.
if (IS_IE && /^ /.test(content)) {
content = content.substring(6);
}
restoreSelection(range);
prepRangeForPaste(range);
if (Aloha.queryCommandSupported('insertHTML')) {
Aloha.execCommand('insertHTML', false, content);
} else {
Console.error(
'Common.Paste',
'Command "insertHTML" not available. Enable the plugin "common/commands".'
);
}
$clipboard.contents().remove();
if (typeof callback === 'function') {
callback();
}
}
/**
* Handles the "paste" event initiating from the $CLIPBOARD element.
*
* @param {jQuery.Event} $event Event at paste.
* @param {WrappedRange} range The range to where to direct the contents
* of the $CLIPBOARD element.
* @param {function=} onInsert Optional callback to be invoked after pasting
* is completed.
*/
function onPaste($event, range, onInsert) {
// Because we do not want the smartContentChange method to process this
// event if the metaKey property had been set.
$event.metaKey = null;
$event.stopPropagation();
// Because yeiling here allows for a small execution window to ensure
// that the pasted content has been inserted into the paste div before
// we attempt to retrieve it.
window.setTimeout(function () {
paste($CLIPBOARD, range, onInsert);
Aloha.activeEditable.smartContentChange($event);
}, 10);
}
/**
* Prepare each editable that is created to handle its paste events via the
* invisible paste div.
*
* Bind appropriate events handlers to the given editable element to be
* able to intercept paste events target tot it.
*
* TODO: Move to paste command?
* http://support.mozilla.com/en-US/kb/Granting%20JavaScript%20access%20to%20the%20clipboard
* https://code.google.com/p/zeroclipboard/
*
* @param {jQuery.<HTMLElement>} $editable jQuery object containing an
* editable DOM element.
*/
function prepare($editable) {
// Clipboard in IE can no be used, because it does not return HTML content, just text
// (http://msdn.microsoft.com/en-us/library/ie/ms536436(v=vs.85).aspx).
// We relay on range.execCommand('paste') for the paste, but for IE9 and above the pasted content
// is treated differently (it replaces '\n' by '<br>').
var doc = $editable[0].ownerDocument;
if (isIEorDocModeGreater9(doc)) {
$editable.bind('beforepaste', function ($event) {
scrollPositionBeforePaste.x = window.scrollX ||
document.documentElement.scrollLeft;
scrollPositionBeforePaste.y = window.scrollY ||
document.documentElement.scrollTop;
ieRangeBeforePaste = CopyPaste.getRange();
redirect(ieRangeBeforePaste, $CLIPBOARD);
$event.stopPropagation();
});
} else {
$editable.bind('paste', function ($event) {
scrollPositionBeforePaste.x = window.scrollX ||
document.documentElement.scrollLeft;
scrollPositionBeforePaste.y = window.scrollY ||
document.documentElement.scrollTop;
var range = CopyPaste.getRange();
redirect(range, $CLIPBOARD);
if (IS_IE) {
$event.preventDefault();
var tmpRange = document.selection.createRange();
tmpRange.execCommand('paste');
}
onPaste($event, range);
});
}
}
return Plugin.create('paste', {
settings: {},
init: function () {
$('body').append($CLIPBOARD);
Aloha.bind('aloha-editable-created', function ($event, editable) {
prepare(editable.obj);
});
if (isIEorDocModeGreater9($CLIPBOARD[0].ownerDocument)) {
// Bind a handler to the paste event of the pasteDiv to get the
// pasted content (but do this only once, not for every editable)
$CLIPBOARD.bind('paste', function ($event) {
onPaste($event, ieRangeBeforePaste, function () {
ieRangeBeforePaste = null;
});
});
}
},
/**
* Register the given paste handler
* @deprecated
* @param pasteHandler paste handler to be registered
*/
register: function (pasteHandler) {
Console.deprecated('Plugins.Paste', 'register() for pasteHandler' +
' is deprecated. Use the ' +
'ContentHandler Plugin ' +
'instead.');
}
});
});
| yrucrem/Aloha-Editor | src/plugins/common/paste/lib/paste-plugin.js | JavaScript | gpl-2.0 | 13,999 |
# SPDX-License-Identifier: GPL-2.0+
obj-$(CONFIG_TARGET_SECOMX6) += mx6.o
| CTSRD-CHERI/u-boot | board/seco/common/Makefile | Makefile | gpl-2.0 | 75 |
/*
* Copyright (C) 2002 Manuel Novoa III
* Copyright (C) 2000-2005 Erik Andersen <[email protected]>
*
* Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
*/
/* ffsl,ffsll */
#include "_string.h"
#include <strings.h>
libc_hidden_proto(ffs)
int ffs(int i)
{
#if 1
/* inlined binary search method */
char n = 1;
#if UINT_MAX == 0xffffU
/* nothing to do here -- just trying to avoiding possible problems */
#elif UINT_MAX == 0xffffffffU
if (!(i & 0xffff)) {
n += 16;
i >>= 16;
}
#else
#error ffs needs rewriting!
#endif
if (!(i & 0xff)) {
n += 8;
i >>= 8;
}
if (!(i & 0x0f)) {
n += 4;
i >>= 4;
}
if (!(i & 0x03)) {
n += 2;
i >>= 2;
}
return (i) ? (n + ((i+1) & 0x01)) : 0;
#else
/* linear search -- slow, but small */
int n;
for (n = 0 ; i ; ++n) {
i >>= 1;
}
return n;
#endif
}
libc_hidden_def(ffs)
| rhuitl/uClinux | uClibc/libc/string/ffs.c | C | gpl-2.0 | 874 |
/*
* This file is part of libbluray
* Copyright (C) 2010 William Hahne
*
* 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, see
* <http://www.gnu.org/licenses/>.
*/
package org.dvb.event;
import java.awt.event.KeyEvent;
public class UserEvent extends java.util.EventObject {
public UserEvent(Object source, int family, int type, int code,
int modifiers, long when)
{
super(source);
this.family = family;
this.type = type;
this.code = code;
this.modifiers = modifiers;
this.when = when;
}
public UserEvent(Object source, int family, char keyChar, long when)
{
super(source);
this.family = family;
this.type = KeyEvent.KEY_TYPED;
this.code = keyChar;
this.modifiers = 0;
this.when = when;
}
public int getFamily()
{
return family;
}
public int getType()
{
return type;
}
public int getCode()
{
return code;
}
public char getKeyChar()
{
return (char) code;
}
public int getModifiers()
{
return modifiers;
}
public boolean isShiftDown()
{
return (KeyEvent.SHIFT_MASK & modifiers) != 0;
}
public boolean isControlDown()
{
return (KeyEvent.CTRL_MASK & modifiers) != 0;
}
public boolean isMetaDown()
{
return (KeyEvent.META_MASK & modifiers) != 0;
}
public boolean isAltDown()
{
return (KeyEvent.ALT_MASK & modifiers) != 0;
}
public long getWhen()
{
return when;
}
public static final int UEF_KEY_EVENT = 1;
private int family;
private int type;
private int code;
private int modifiers;
private long when;
private static final long serialVersionUID = -4734616177850745290L;
}
| xucp/mpc_hc | src/thirdparty/LAVFilters/src/libbluray/src/libbluray/bdj/java/org/dvb/event/UserEvent.java | Java | gpl-3.0 | 2,454 |
//
// posix/basic_stream_descriptor.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP
#define BOOST_ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <boost/asio/posix/descriptor.hpp>
#if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \
|| defined(GENERATING_DOCUMENTATION)
namespace boost {
namespace asio {
namespace posix {
/// Provides stream-oriented descriptor functionality.
/**
* The posix::basic_stream_descriptor class template provides asynchronous and
* blocking stream-oriented descriptor functionality.
*
* @par Thread Safety
* @e Distinct @e objects: Safe.@n
* @e Shared @e objects: Unsafe.
*
* @par Concepts:
* AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream.
*/
template <typename Executor = any_io_executor>
class basic_stream_descriptor
: public basic_descriptor<Executor>
{
public:
/// The type of the executor associated with the object.
typedef Executor executor_type;
/// Rebinds the descriptor type to another executor.
template <typename Executor1>
struct rebind_executor
{
/// The descriptor type when rebound to the specified executor.
typedef basic_stream_descriptor<Executor1> other;
};
/// The native representation of a descriptor.
typedef typename basic_descriptor<Executor>::native_handle_type
native_handle_type;
/// Construct a stream descriptor without opening it.
/**
* This constructor creates a stream descriptor without opening it. The
* descriptor needs to be opened and then connected or accepted before data
* can be sent or received on it.
*
* @param ex The I/O executor that the descriptor will use, by default, to
* dispatch handlers for any asynchronous operations performed on the
* descriptor.
*/
explicit basic_stream_descriptor(const executor_type& ex)
: basic_descriptor<Executor>(ex)
{
}
/// Construct a stream descriptor without opening it.
/**
* This constructor creates a stream descriptor without opening it. The
* descriptor needs to be opened and then connected or accepted before data
* can be sent or received on it.
*
* @param context An execution context which provides the I/O executor that
* the descriptor will use, by default, to dispatch handlers for any
* asynchronous operations performed on the descriptor.
*/
template <typename ExecutionContext>
explicit basic_stream_descriptor(ExecutionContext& context,
typename enable_if<
is_convertible<ExecutionContext&, execution_context&>::value
>::type* = 0)
: basic_descriptor<Executor>(context)
{
}
/// Construct a stream descriptor on an existing native descriptor.
/**
* This constructor creates a stream descriptor object to hold an existing
* native descriptor.
*
* @param ex The I/O executor that the descriptor will use, by default, to
* dispatch handlers for any asynchronous operations performed on the
* descriptor.
*
* @param native_descriptor The new underlying descriptor implementation.
*
* @throws boost::system::system_error Thrown on failure.
*/
basic_stream_descriptor(const executor_type& ex,
const native_handle_type& native_descriptor)
: basic_descriptor<Executor>(ex, native_descriptor)
{
}
/// Construct a stream descriptor on an existing native descriptor.
/**
* This constructor creates a stream descriptor object to hold an existing
* native descriptor.
*
* @param context An execution context which provides the I/O executor that
* the descriptor will use, by default, to dispatch handlers for any
* asynchronous operations performed on the descriptor.
*
* @param native_descriptor The new underlying descriptor implementation.
*
* @throws boost::system::system_error Thrown on failure.
*/
template <typename ExecutionContext>
basic_stream_descriptor(ExecutionContext& context,
const native_handle_type& native_descriptor,
typename enable_if<
is_convertible<ExecutionContext&, execution_context&>::value
>::type* = 0)
: basic_descriptor<Executor>(context, native_descriptor)
{
}
#if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Move-construct a stream descriptor from another.
/**
* This constructor moves a stream descriptor from one object to another.
*
* @param other The other stream descriptor object from which the move
* will occur.
*
* @note Following the move, the moved-from object is in the same state as if
* constructed using the @c basic_stream_descriptor(const executor_type&)
* constructor.
*/
basic_stream_descriptor(basic_stream_descriptor&& other) BOOST_ASIO_NOEXCEPT
: descriptor(std::move(other))
{
}
/// Move-assign a stream descriptor from another.
/**
* This assignment operator moves a stream descriptor from one object to
* another.
*
* @param other The other stream descriptor object from which the move
* will occur.
*
* @note Following the move, the moved-from object is in the same state as if
* constructed using the @c basic_stream_descriptor(const executor_type&)
* constructor.
*/
basic_stream_descriptor& operator=(basic_stream_descriptor&& other)
{
descriptor::operator=(std::move(other));
return *this;
}
#endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Write some data to the descriptor.
/**
* This function is used to write data to the stream descriptor. The function
* call will block until one or more bytes of the data has been written
* successfully, or until an error occurs.
*
* @param buffers One or more data buffers to be written to the descriptor.
*
* @returns The number of bytes written.
*
* @throws boost::system::system_error Thrown on failure. An error code of
* boost::asio::error::eof indicates that the connection was closed by the
* peer.
*
* @note The write_some operation may not transmit all of the data to the
* peer. Consider using the @ref write function if you need to ensure that
* all data is written before the blocking operation completes.
*
* @par Example
* To write a single data buffer use the @ref buffer function as follows:
* @code
* descriptor.write_some(boost::asio::buffer(data, size));
* @endcode
* See the @ref buffer documentation for information on writing multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence& buffers)
{
boost::system::error_code ec;
std::size_t s = this->impl_.get_service().write_some(
this->impl_.get_implementation(), buffers, ec);
boost::asio::detail::throw_error(ec, "write_some");
return s;
}
/// Write some data to the descriptor.
/**
* This function is used to write data to the stream descriptor. The function
* call will block until one or more bytes of the data has been written
* successfully, or until an error occurs.
*
* @param buffers One or more data buffers to be written to the descriptor.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes written. Returns 0 if an error occurred.
*
* @note The write_some operation may not transmit all of the data to the
* peer. Consider using the @ref write function if you need to ensure that
* all data is written before the blocking operation completes.
*/
template <typename ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence& buffers,
boost::system::error_code& ec)
{
return this->impl_.get_service().write_some(
this->impl_.get_implementation(), buffers, ec);
}
/// Start an asynchronous write.
/**
* This function is used to asynchronously write data to the stream
* descriptor. The function call always returns immediately.
*
* @param buffers One or more data buffers to be written to the descriptor.
* Although the buffers object may be copied as necessary, ownership of the
* underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the handler is called.
*
* @param handler The handler to be called when the write operation completes.
* Copies will be made of the handler as required. The function signature of
* the handler must be:
* @code void handler(
* const boost::system::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes written.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. On
* immediate completion, invocation of the handler will be performed in a
* manner equivalent to using boost::asio::post().
*
* @note The write operation may not transmit all of the data to the peer.
* Consider using the @ref async_write function if you need to ensure that all
* data is written before the asynchronous operation completes.
*
* @par Example
* To write a single data buffer use the @ref buffer function as follows:
* @code
* descriptor.async_write_some(boost::asio::buffer(data, size), handler);
* @endcode
* See the @ref buffer documentation for information on writing multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename ConstBufferSequence,
BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code,
std::size_t)) WriteHandler
BOOST_ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler,
void (boost::system::error_code, std::size_t))
async_write_some(const ConstBufferSequence& buffers,
BOOST_ASIO_MOVE_ARG(WriteHandler) handler
BOOST_ASIO_DEFAULT_COMPLETION_TOKEN(executor_type))
{
return async_initiate<WriteHandler,
void (boost::system::error_code, std::size_t)>(
initiate_async_write_some(this), handler, buffers);
}
/// Read some data from the descriptor.
/**
* This function is used to read data from the stream descriptor. The function
* call will block until one or more bytes of data has been read successfully,
* or until an error occurs.
*
* @param buffers One or more buffers into which the data will be read.
*
* @returns The number of bytes read.
*
* @throws boost::system::system_error Thrown on failure. An error code of
* boost::asio::error::eof indicates that the connection was closed by the
* peer.
*
* @note The read_some operation may not read all of the requested number of
* bytes. Consider using the @ref read function if you need to ensure that
* the requested amount of data is read before the blocking operation
* completes.
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code
* descriptor.read_some(boost::asio::buffer(data, size));
* @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename MutableBufferSequence>
std::size_t read_some(const MutableBufferSequence& buffers)
{
boost::system::error_code ec;
std::size_t s = this->impl_.get_service().read_some(
this->impl_.get_implementation(), buffers, ec);
boost::asio::detail::throw_error(ec, "read_some");
return s;
}
/// Read some data from the descriptor.
/**
* This function is used to read data from the stream descriptor. The function
* call will block until one or more bytes of data has been read successfully,
* or until an error occurs.
*
* @param buffers One or more buffers into which the data will be read.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes read. Returns 0 if an error occurred.
*
* @note The read_some operation may not read all of the requested number of
* bytes. Consider using the @ref read function if you need to ensure that
* the requested amount of data is read before the blocking operation
* completes.
*/
template <typename MutableBufferSequence>
std::size_t read_some(const MutableBufferSequence& buffers,
boost::system::error_code& ec)
{
return this->impl_.get_service().read_some(
this->impl_.get_implementation(), buffers, ec);
}
/// Start an asynchronous read.
/**
* This function is used to asynchronously read data from the stream
* descriptor. The function call always returns immediately.
*
* @param buffers One or more buffers into which the data will be read.
* Although the buffers object may be copied as necessary, ownership of the
* underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the handler is called.
*
* @param handler The handler to be called when the read operation completes.
* Copies will be made of the handler as required. The function signature of
* the handler must be:
* @code void handler(
* const boost::system::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes read.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. On
* immediate completion, invocation of the handler will be performed in a
* manner equivalent to using boost::asio::post().
*
* @note The read operation may not read all of the requested number of bytes.
* Consider using the @ref async_read function if you need to ensure that the
* requested amount of data is read before the asynchronous operation
* completes.
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code
* descriptor.async_read_some(boost::asio::buffer(data, size), handler);
* @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename MutableBufferSequence,
BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code,
std::size_t)) ReadHandler
BOOST_ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler,
void (boost::system::error_code, std::size_t))
async_read_some(const MutableBufferSequence& buffers,
BOOST_ASIO_MOVE_ARG(ReadHandler) handler
BOOST_ASIO_DEFAULT_COMPLETION_TOKEN(executor_type))
{
return async_initiate<ReadHandler,
void (boost::system::error_code, std::size_t)>(
initiate_async_read_some(this), handler, buffers);
}
private:
class initiate_async_write_some
{
public:
typedef Executor executor_type;
explicit initiate_async_write_some(basic_stream_descriptor* self)
: self_(self)
{
}
executor_type get_executor() const BOOST_ASIO_NOEXCEPT
{
return self_->get_executor();
}
template <typename WriteHandler, typename ConstBufferSequence>
void operator()(BOOST_ASIO_MOVE_ARG(WriteHandler) handler,
const ConstBufferSequence& buffers) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a WriteHandler.
BOOST_ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
detail::non_const_lvalue<WriteHandler> handler2(handler);
self_->impl_.get_service().async_write_some(
self_->impl_.get_implementation(), buffers,
handler2.value, self_->impl_.get_executor());
}
private:
basic_stream_descriptor* self_;
};
class initiate_async_read_some
{
public:
typedef Executor executor_type;
explicit initiate_async_read_some(basic_stream_descriptor* self)
: self_(self)
{
}
executor_type get_executor() const BOOST_ASIO_NOEXCEPT
{
return self_->get_executor();
}
template <typename ReadHandler, typename MutableBufferSequence>
void operator()(BOOST_ASIO_MOVE_ARG(ReadHandler) handler,
const MutableBufferSequence& buffers) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
BOOST_ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
detail::non_const_lvalue<ReadHandler> handler2(handler);
self_->impl_.get_service().async_read_some(
self_->impl_.get_implementation(), buffers,
handler2.value, self_->impl_.get_executor());
}
private:
basic_stream_descriptor* self_;
};
};
} // namespace posix
} // namespace asio
} // namespace boost
#endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
// || defined(GENERATING_DOCUMENTATION)
#endif // BOOST_ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP
| redFrik/supercollider | external_libraries/boost/boost/asio/posix/basic_stream_descriptor.hpp | C++ | gpl-3.0 | 17,673 |
c3_chart_fn.flow = function (args) {
var $$ = this.internal,
targets, data, notfoundIds = [], orgDataCount = $$.getMaxDataCount(),
dataCount, domain, baseTarget, baseValue, length = 0, tail = 0, diff, to;
if (args.json) {
data = $$.convertJsonToData(args.json, args.keys);
}
else if (args.rows) {
data = $$.convertRowsToData(args.rows);
}
else if (args.columns) {
data = $$.convertColumnsToData(args.columns);
}
else {
return;
}
targets = $$.convertDataToTargets(data, true);
// Update/Add data
$$.data.targets.forEach(function (t) {
var found = false, i, j;
for (i = 0; i < targets.length; i++) {
if (t.id === targets[i].id) {
found = true;
if (t.values[t.values.length - 1]) {
tail = t.values[t.values.length - 1].index + 1;
}
length = targets[i].values.length;
for (j = 0; j < length; j++) {
targets[i].values[j].index = tail + j;
if (!$$.isTimeSeries()) {
targets[i].values[j].x = tail + j;
}
}
t.values = t.values.concat(targets[i].values);
targets.splice(i, 1);
break;
}
}
if (!found) { notfoundIds.push(t.id); }
});
// Append null for not found targets
$$.data.targets.forEach(function (t) {
var i, j;
for (i = 0; i < notfoundIds.length; i++) {
if (t.id === notfoundIds[i]) {
tail = t.values[t.values.length - 1].index + 1;
for (j = 0; j < length; j++) {
t.values.push({
id: t.id,
index: tail + j,
x: $$.isTimeSeries() ? $$.getOtherTargetX(tail + j) : tail + j,
value: null
});
}
}
}
});
// Generate null values for new target
if ($$.data.targets.length) {
targets.forEach(function (t) {
var i, missing = [];
for (i = $$.data.targets[0].values[0].index; i < tail; i++) {
missing.push({
id: t.id,
index: i,
x: $$.isTimeSeries() ? $$.getOtherTargetX(i) : i,
value: null
});
}
t.values.forEach(function (v) {
v.index += tail;
if (!$$.isTimeSeries()) {
v.x += tail;
}
});
t.values = missing.concat(t.values);
});
}
$$.data.targets = $$.data.targets.concat(targets); // add remained
// check data count because behavior needs to change when it's only one
dataCount = $$.getMaxDataCount();
baseTarget = $$.data.targets[0];
baseValue = baseTarget.values[0];
// Update length to flow if needed
if (isDefined(args.to)) {
length = 0;
to = $$.isTimeSeries() ? $$.parseDate(args.to) : args.to;
baseTarget.values.forEach(function (v) {
if (v.x < to) { length++; }
});
} else if (isDefined(args.length)) {
length = args.length;
}
// If only one data, update the domain to flow from left edge of the chart
if (!orgDataCount) {
if ($$.isTimeSeries()) {
if (baseTarget.values.length > 1) {
diff = baseTarget.values[baseTarget.values.length - 1].x - baseValue.x;
} else {
diff = baseValue.x - $$.getXDomain($$.data.targets)[0];
}
} else {
diff = 1;
}
domain = [baseValue.x - diff, baseValue.x];
$$.updateXDomain(null, true, true, false, domain);
} else if (orgDataCount === 1) {
if ($$.isTimeSeries()) {
diff = (baseTarget.values[baseTarget.values.length - 1].x - baseValue.x) / 2;
domain = [new Date(+baseValue.x - diff), new Date(+baseValue.x + diff)];
$$.updateXDomain(null, true, true, false, domain);
}
}
// Set targets
$$.updateTargets($$.data.targets);
// Redraw with new targets
$$.redraw({
flow: {
index: baseValue.index,
length: length,
duration: isValue(args.duration) ? args.duration : $$.config.transition_duration,
done: args.done,
orgDataCount: orgDataCount,
},
withLegend: true,
withTransition: orgDataCount > 1,
withTrimXDomain: false
});
};
c3_chart_internal_fn.generateFlow = function (args) {
var $$ = this, config = $$.config, d3 = $$.d3;
return function () {
var targets = args.targets,
flow = args.flow,
drawBar = args.drawBar,
drawLine = args.drawLine,
drawArea = args.drawArea,
cx = args.cx,
cy = args.cy,
xv = args.xv,
xForText = args.xForText,
yForText = args.yForText,
duration = args.duration;
var translateX, scaleX = 1, transform,
flowIndex = flow.index,
flowLength = flow.length,
flowStart = $$.getValueOnIndex($$.data.targets[0].values, flowIndex),
flowEnd = $$.getValueOnIndex($$.data.targets[0].values, flowIndex + flowLength),
orgDomain = $$.x.domain(), domain,
durationForFlow = flow.duration || duration,
done = flow.done || function () {},
wait = $$.generateWait();
var xgrid = $$.xgrid || d3.selectAll([]),
xgridLines = $$.xgridLines || d3.selectAll([]),
mainRegion = $$.mainRegion || d3.selectAll([]),
mainText = $$.mainText || d3.selectAll([]),
mainBar = $$.mainBar || d3.selectAll([]),
mainLine = $$.mainLine || d3.selectAll([]),
mainArea = $$.mainArea || d3.selectAll([]),
mainCircle = $$.mainCircle || d3.selectAll([]);
// set flag
$$.flowing = true;
// remove head data after rendered
$$.data.targets.forEach(function (d) {
d.values.splice(0, flowLength);
});
// update x domain to generate axis elements for flow
domain = $$.updateXDomain(targets, true, true);
// update elements related to x scale
if ($$.updateXGrid) { $$.updateXGrid(true); }
// generate transform to flow
if (!flow.orgDataCount) { // if empty
if ($$.data.targets[0].values.length !== 1) {
translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
} else {
if ($$.isTimeSeries()) {
flowStart = $$.getValueOnIndex($$.data.targets[0].values, 0);
flowEnd = $$.getValueOnIndex($$.data.targets[0].values, $$.data.targets[0].values.length - 1);
translateX = $$.x(flowStart.x) - $$.x(flowEnd.x);
} else {
translateX = diffDomain(domain) / 2;
}
}
} else if (flow.orgDataCount === 1 || flowStart.x === flowEnd.x) {
translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
} else {
if ($$.isTimeSeries()) {
translateX = ($$.x(orgDomain[0]) - $$.x(domain[0]));
} else {
translateX = ($$.x(flowStart.x) - $$.x(flowEnd.x));
}
}
scaleX = (diffDomain(orgDomain) / diffDomain(domain));
transform = 'translate(' + translateX + ',0) scale(' + scaleX + ',1)';
// hide tooltip
$$.hideXGridFocus();
$$.hideTooltip();
d3.transition().ease('linear').duration(durationForFlow).each(function () {
wait.add($$.axes.x.transition().call($$.xAxis));
wait.add(mainBar.transition().attr('transform', transform));
wait.add(mainLine.transition().attr('transform', transform));
wait.add(mainArea.transition().attr('transform', transform));
wait.add(mainCircle.transition().attr('transform', transform));
wait.add(mainText.transition().attr('transform', transform));
wait.add(mainRegion.filter($$.isRegionOnX).transition().attr('transform', transform));
wait.add(xgrid.transition().attr('transform', transform));
wait.add(xgridLines.transition().attr('transform', transform));
})
.call(wait, function () {
var i, shapes = [], texts = [], eventRects = [];
// remove flowed elements
if (flowLength) {
for (i = 0; i < flowLength; i++) {
shapes.push('.' + CLASS.shape + '-' + (flowIndex + i));
texts.push('.' + CLASS.text + '-' + (flowIndex + i));
eventRects.push('.' + CLASS.eventRect + '-' + (flowIndex + i));
}
$$.svg.selectAll('.' + CLASS.shapes).selectAll(shapes).remove();
$$.svg.selectAll('.' + CLASS.texts).selectAll(texts).remove();
$$.svg.selectAll('.' + CLASS.eventRects).selectAll(eventRects).remove();
$$.svg.select('.' + CLASS.xgrid).remove();
}
// draw again for removing flowed elements and reverting attr
xgrid
.attr('transform', null)
.attr($$.xgridAttr);
xgridLines
.attr('transform', null);
xgridLines.select('line')
.attr("x1", config.axis_rotated ? 0 : xv)
.attr("x2", config.axis_rotated ? $$.width : xv);
xgridLines.select('text')
.attr("x", config.axis_rotated ? $$.width : 0)
.attr("y", xv);
mainBar
.attr('transform', null)
.attr("d", drawBar);
mainLine
.attr('transform', null)
.attr("d", drawLine);
mainArea
.attr('transform', null)
.attr("d", drawArea);
mainCircle
.attr('transform', null)
.attr("cx", cx)
.attr("cy", cy);
mainText
.attr('transform', null)
.attr('x', xForText)
.attr('y', yForText)
.style('fill-opacity', $$.opacityForText.bind($$));
mainRegion
.attr('transform', null);
mainRegion.select('rect').filter($$.isRegionOnX)
.attr("x", $$.regionX.bind($$))
.attr("width", $$.regionWidth.bind($$));
if (config.interaction_enabled) {
$$.redrawEventRect();
}
// callback for end of flow
done();
$$.flowing = false;
});
};
};
| jdi-framework/jdi-framework.github.io | tests/js/lib/components/c3-0.4.2/src/api.flow.js | JavaScript | gpl-3.0 | 10,960 |
/*
* Copyright (C) 2010 Martin Willi
* Copyright (C) 2010 revosec AG
*
* 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. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* 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 "revocation_plugin.h"
#include <library.h>
#include "revocation_validator.h"
typedef struct private_revocation_plugin_t private_revocation_plugin_t;
/**
* private data of revocation_plugin
*/
struct private_revocation_plugin_t {
/**
* public functions
*/
revocation_plugin_t public;
/**
* Validator implementation instance.
*/
revocation_validator_t *validator;
};
METHOD(plugin_t, get_name, char*,
private_revocation_plugin_t *this)
{
return "revocation";
}
/**
* Register validator
*/
static bool plugin_cb(private_revocation_plugin_t *this,
plugin_feature_t *feature, bool reg, void *cb_data)
{
if (reg)
{
lib->credmgr->add_validator(lib->credmgr, &this->validator->validator);
}
else
{
lib->credmgr->remove_validator(lib->credmgr,
&this->validator->validator);
}
return TRUE;
}
METHOD(plugin_t, get_features, int,
private_revocation_plugin_t *this, plugin_feature_t *features[])
{
static plugin_feature_t f[] = {
PLUGIN_CALLBACK((plugin_feature_callback_t)plugin_cb, NULL),
PLUGIN_PROVIDE(CUSTOM, "revocation"),
PLUGIN_SDEPEND(CERT_ENCODE, CERT_X509_OCSP_REQUEST),
PLUGIN_SDEPEND(CERT_DECODE, CERT_X509_OCSP_RESPONSE),
PLUGIN_SDEPEND(CERT_DECODE, CERT_X509_CRL),
PLUGIN_SDEPEND(CERT_DECODE, CERT_X509),
PLUGIN_SDEPEND(FETCHER, NULL),
};
*features = f;
return countof(f);
}
METHOD(plugin_t, destroy, void,
private_revocation_plugin_t *this)
{
this->validator->destroy(this->validator);
free(this);
}
/*
* see header file
*/
plugin_t *revocation_plugin_create()
{
private_revocation_plugin_t *this;
INIT(this,
.public = {
.plugin = {
.get_name = _get_name,
.get_features = _get_features,
.destroy = _destroy,
},
},
.validator = revocation_validator_create(),
);
return &this->public.plugin;
}
| ccwf2006/one-key-ikev2-vpn | strongswan-5.5.1/src/libstrongswan/plugins/revocation/revocation_plugin.c | C | gpl-3.0 | 2,451 |
/**
* -----------------------------------------------------------------------------
* @package smartVISU
* @author Martin Gleiß
* @copyright 2012 - 2015
* @license GPL <http://www.gnu.de>
* -----------------------------------------------------------------------------
*/
{% extends "base.html" %}
{% block sidebar %}
{% include 'stats.navigation.html' %}
{% endblock %}
{% block content %}
<h1><img class="icon" src='{{ icon0 }}sani_floor_heating.png'/>Temperaturen Fußbodenheizung</h1>
<div class="preblock">
</div>
<div class="block">
<div class="set-2" data-role="collapsible-set" data-theme="c" data-content-theme="a" data-mini="true">
<div data-role="collapsible" data-collapsed="false">
<h3>Erdgeschoss</h3>
<table width="100%" style="text-align: left;">
<tr>
<td width="20%"></td>
<td width="10%">Ist</td>
<td width="10%"></td>
<td width="10%">Soll</td>
<td width="10%"></td>
<td width="10%">Heizen</td>
</tr>
</table>
{% import "widget_rtr_small.html" as smallrtr %}
{{ smallrtr.one ('srtr_kueche', 'Küche', '1/0/4/9.xxx', '1/0/3/9.xxx', '1/0/2/1.001') }}
{{ smallrtr.one ('srtr_wz', 'Wohnen', '0/0/4/9.xxx', '0/0/3/9.xxx', '0/0/2/1.001') }}
{{ smallrtr.one ('srtr_gz', 'Gäste', '2/0/4/9.xxx', '2/0/3/9.xxx', '2/0/1/5.001') }}
{{ smallrtr.one ('srtr_gwc', 'WC', '3/0/4/9.xxx', '3/0/3/9.xxx', '3/0/2/1.001') }}
{{ smallrtr.one ('srtr_dieg', 'Diele EG', '4/0/4/9.xxx', '4/0/3/9.xxx', '4/0/2/1.001') }}
</div>
</div>
</div>
<div class="block">
<div class="set-2" data-role="collapsible-set" data-theme="c" data-content-theme="a" data-mini="true">
<div data-role="collapsible" data-collapsed="false">
<h3>Dachgeschoss</h3>
<table width="100%" style="text-align: left;">
<tr>
<td width="20%"></td>
<td width="10%">Ist</td>
<td width="10%"></td>
<td width="10%">Soll</td>
<td width="10%"></td>
<td width="10%">Heizen</td>
</tr>
</table>
{% import "widget_rtr_small.html" as smallrtr %}
{{ smallrtr.one ('srtr_badog', 'Bad', '9/0/4/9.xxx', '9/0/3/9.xxx', '9/0/2/1.001') }}
{{ smallrtr.one ('srtr_sz', 'Schlafen', '6/0/4/9.xxx', '6/0/3/9.xxx', '6/0/2/1.001') }}
{{ smallrtr.one ('srtr_kz', 'Kind', '7/0/4/9.xxx', '7/0/3/9.xxx', '7/0/2/1.001') }}
{{ smallrtr.one ('srtr_az', 'Arbeiten','8/0/4/9.xxx', '8/0/3/9.xxx', '8/0/2/1.001') }}
{{ smallrtr.one ('srtr_diog', 'Diele OG', '10/0/4/9.xxx','10/0/3/9.xxx','10/0/2/1.001') }}
</div>
</div>
</div>
{% endblock %}
| bjko/smartvisu | pages/alber.eibd/stats.temperaturen.html | HTML | gpl-3.0 | 3,190 |
#include "gui_videocapture.h"
#include "ui_gui_videocapture.h"
#include "myimage.h"
GUI_VideoCapture::GUI_VideoCapture(QWidget *parent) :
QDialog(parent),
ui(new Ui::GUI_VideoCapture)
{
ui->setupUi(this);
ui->graphicsView->setScene(&gScene);
int i=0;
while (i<10){
if (!capture.open(i))
break;
if (!capture.isOpened())
break;
QString s;
s.sprintf("%d: %dx%d", i,
int(capture.get(CV_CAP_PROP_FRAME_WIDTH)),
int(capture.get(CV_CAP_PROP_FRAME_HEIGHT)));
ui->cmbCamSelect->addItem(s);
capture.release();
i++;
}
capture.open(0);
thread.capture = &capture;
connect(&thread, SIGNAL(finished()), this, SLOT(newImageReady()));
startCapture();
}
GUI_VideoCapture::~GUI_VideoCapture()
{
delete ui;
}
void GUI_VideoCapture::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void GUI_VideoCapture::hideEvent( QHideEvent *e ){
stopCapture();
QDialog::hideEvent(e);
}
void GUI_VideoCapture::startCapture(){
if (capture.isOpened()){
ui->graphicsView->setMinimumSize(
int(capture.get(CV_CAP_PROP_FRAME_WIDTH)*1.1),
int(capture.get(CV_CAP_PROP_FRAME_HEIGHT)*1.1));
timerId = startTimer(100);
}
}
void GUI_VideoCapture::stopCapture(){
killTimer( timerId );
thread.stop();
}
void GUI_VideoCapture::timerEvent(QTimerEvent *event){
thread.start();
}
void GUI_VideoCapture::newImageReady()
{
img = thread.image();
gScene.clear();
gScene.addPixmap(QPixmap::fromImage(MyImage::fromMat(img)));
gScene.update();
this->update();
}
void GUI_VideoCapture::on_cmbCamSelect_currentIndexChanged(int index)
{
if (capture.isOpened())
capture.release();
qDebug("-- Testing camera %d...", index);
capture.open(index);
startCapture();
}
| GeMoo/faceworkshop | gui_videocapture.cpp | C++ | gpl-3.0 | 2,028 |
<?php
if (str_contains($sysDescr, 'ServerIron')) {
$os = 'serveriron';
$serviron_mibs = array (
"snL4slbTotalConnections" => "FOUNDRY-SN-SW-L4-SWITCH-GROUP-MIB", // Total connections in this device
"snL4slbLimitExceeds" => "FOUNDRY-SN-SW-L4-SWITCH-GROUP-MIB", // exceeds snL4TCPSynLimit (numbers of connection per second)
"snL4slbForwardTraffic" => "FOUNDRY-SN-SW-L4-SWITCH-GROUP-MIB", // Client->Server
"snL4slbReverseTraffic" => "FOUNDRY-SN-SW-L4-SWITCH-GROUP-MIB", // Server->Client
"snL4slbFinished" => "FOUNDRY-SN-SW-L4-SWITCH-GROUP-MIB", // FIN_or_RST
"snL4FreeSessionCount" => "FOUNDRY-SN-SW-L4-SWITCH-GROUP-MIB", // Maximum sessions - used sessions
"snL4unsuccessfulConn" => "FOUNDRY-SN-SW-L4-SWITCH-GROUP-MIB", // Unsuccessfull connection
);
register_mibs($device, $serviron_mibs, "includes/discovery/os/serveriron.inc.php");
}
| NetworkNub/librenms | includes/discovery/os/serveriron.inc.php | PHP | gpl-3.0 | 982 |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Rubberduck.Refactorings.RemoveParameters;
namespace Rubberduck.UI.Refactorings
{
public partial class RemoveParametersDialog : Form, IRemoveParametersView
{
public List<Parameter> Parameters { get; set; }
private Parameter _selectedItem;
public RemoveParametersDialog()
{
InitializeComponent();
InitializeCaptions();
MethodParametersGrid.SelectionChanged += MethodParametersGrid_SelectionChanged;
MethodParametersGrid.CellMouseDoubleClick += MethodParametersGrid_CellMouseDoubleClick;
}
private void InitializeCaptions()
{
OkButton.Text = RubberduckUI.OK;
CancelDialogButton.Text = RubberduckUI.CancelButtonText;
Text = RubberduckUI.RemoveParamsDialog_Caption;
TitleLabel.Text = RubberduckUI.RemoveParamsDialog_TitleText;
InstructionsLabel.Text = RubberduckUI.RemoveParamsDialog_InstructionsLabelText;
RemoveButton.Text = RubberduckUI.Remove;
RestoreButton.Text = RubberduckUI.Restore;
}
private void MethodParametersGrid_SelectionChanged(object sender, EventArgs e)
{
SelectionChanged();
}
public void InitializeParameterGrid()
{
MethodParametersGrid.AutoGenerateColumns = false;
MethodParametersGrid.Columns.Clear();
MethodParametersGrid.DataSource = Parameters;
MethodParametersGrid.AlternatingRowsDefaultCellStyle.BackColor = Color.Lavender;
MethodParametersGrid.MultiSelect = false;
MethodParametersGrid.AllowUserToResizeRows = false;
MethodParametersGrid.AllowDrop = true;
MethodParametersGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
var column = new DataGridViewTextBoxColumn
{
Name = "Parameter",
DataPropertyName = "Name",
HeaderText = RubberduckUI.Parameter,
ReadOnly = true,
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
};
MethodParametersGrid.Columns.Add(column);
}
private void MarkAsRemovedParam()
{
if (_selectedItem != null)
{
var indexOfRemoved = Parameters.FindIndex(item => item == _selectedItem);
Parameters.ElementAt(indexOfRemoved).IsRemoved = true;
MethodParametersGrid.Rows[indexOfRemoved].DefaultCellStyle.Font = new Font(this.Font, FontStyle.Strikeout);
SelectionChanged();
}
}
private void MarkAsRestoredParam() // really just un-mark as removed, but [tag:naming-is-hard]
{
if (_selectedItem != null)
{
var indexOfRemoved = Parameters.FindIndex(item => item == _selectedItem);
Parameters.ElementAt(indexOfRemoved).IsRemoved = false;
MethodParametersGrid.Rows[indexOfRemoved].DefaultCellStyle.Font = new Font(this.Font, FontStyle.Regular);
SelectionChanged();
}
}
private void RemoveButtonClicked(object sender, EventArgs e)
{
MarkAsRemovedParam();
}
private void RestoreButtonClicked(object sender, EventArgs e)
{
MarkAsRestoredParam();
}
private void MethodParametersGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (_selectedItem == null) { return; }
if (_selectedItem.IsRemoved)
{
MarkAsRestoredParam();
}
else
{
MarkAsRemovedParam();
}
}
private int GetFirstSelectedRowIndex(int index)
{
return MethodParametersGrid.SelectedRows[index].Index;
}
private void SelectionChanged()
{
_selectedItem = MethodParametersGrid.SelectedRows.Count == 0
? null
: (Parameter)MethodParametersGrid.SelectedRows[0].DataBoundItem;
RemoveButton.Enabled = _selectedItem != null && !_selectedItem.IsRemoved;
RestoreButton.Enabled = _selectedItem != null && _selectedItem.IsRemoved;
}
}
}
| ptwales/Rubberduck | RetailCoder.VBE/UI/Refactorings/RemoveParametersDialog.cs | C# | gpl-3.0 | 4,517 |
#!/usr/bin/env python
# texi-langutils.py
# WARNING: this script can't find files included in a different directory
import sys
import re
import getopt
import os
import langdefs
def read_pipe (command):
print command
pipe = os.popen (command)
output = pipe.read ()
if pipe.close ():
print "pipe failed: %(command)s" % locals ()
return output
optlist, texi_files = getopt.getopt(sys.argv[1:],'no:d:b:i:l:',['skeleton', 'gettext', 'head-only'])
process_includes = not ('-n', '') in optlist # -n don't process @include's in texinfo files
make_gettext = ('--gettext', '') in optlist # --gettext generate a node list from a Texinfo source
make_skeleton = ('--skeleton', '') in optlist # --skeleton extract the node tree from a Texinfo source
head_only = ('--head-only', '') in optlist # --head-only only write first node in included Texinfo skeletons
output_name = 'doc.pot'
# @untranslated should be defined as a macro in Texinfo source
node_blurb = '''@untranslated
'''
doclang = ''
head_committish = read_pipe ('git rev-parse HEAD')
intro_blurb = '''\\input texinfo @c -*- coding: utf-8; mode: texinfo%(doclang)s -*-
@c This file is part of %(topfile)s
@ignore
Translation of GIT committish: %(head_committish)s
When revising a translation, copy the HEAD committish of the
version that you are working on. See TRANSLATION for details.
@end ignore
'''
end_blurb = """
@c -- SKELETON FILE --
"""
for x in optlist:
if x[0] == '-o': # -o NAME set PO output file name to NAME
output_name = x[1]
elif x[0] == '-d': # -d DIR set working directory to DIR
print 'FIXME: this is evil. use cd DIR && texi-langutils ...'
# even better, add a sane -o option
os.chdir (x[1])
elif x[0] == '-b': # -b BLURB set blurb written at each node to BLURB
node_blurb = x[1]
elif x[0] == '-i': # -i BLURB set blurb written at beginning of each file to BLURB
intro_blurb = x[1]
elif x[0] == '-l': # -l ISOLANG set documentlanguage to ISOLANG
doclang = '; documentlanguage: ' + x[1]
texinfo_with_menus_re = re.compile (r"^(\*) +([^:\n]+)::.*?$|^@(include|menu|end menu|node|(?:unnumbered|appendix)(?:(?:sub){0,2}sec)?|top|chapter|(?:sub){0,2}section|(?:major|chap|(?:sub){0,2})heading) *(.*?)$|@(rglos){(.+?)}", re.M)
texinfo_re = re.compile (r"^@(include|node|(?:unnumbered|appendix)(?:(?:sub){0,2}sec)?|top|chapter|(?:sub){0,2}section|(?:major|chap|(?:sub){0,2})heading) *(.+?)$|@(rglos){(.+?)}", re.M)
ly_string_re = re.compile (r'^([a-zA-Z]+)[\t ]*=|%+[\t ]*(.*)$|\\(?:new|context)\s+(?:[a-zA-Z]*?(?:Staff(?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\s+=\s+"?([a-zA-Z]+)"?\s+')
lsr_verbatim_ly_re = re.compile (r'% begin verbatim$')
texinfo_verbatim_ly_re = re.compile (r'^@lilypond\[.*?verbatim')
def process_texi (texifilename, i_blurb, n_blurb, write_skeleton, topfile,
output_file=None, scan_ly=False, inclusion_level=0):
try:
f = open (texifilename, 'r')
texifile = f.read ()
f.close ()
printedfilename = texifilename.replace ('../','')
includes = []
# process ly var names and comments
if output_file and (scan_ly or texifilename.endswith ('.ly')):
lines = texifile.splitlines ()
i = 0
in_verb_ly_block = False
if texifilename.endswith ('.ly'):
verbatim_ly_re = lsr_verbatim_ly_re
else:
verbatim_ly_re = texinfo_verbatim_ly_re
for i in range (len (lines)):
if verbatim_ly_re.search (lines[i]):
in_verb_ly_block = True
elif lines[i].startswith ('@end lilypond'):
in_verb_ly_block = False
elif in_verb_ly_block:
for (var, comment, context_id) in ly_string_re.findall (lines[i]):
if var:
output_file.write ('# ' + printedfilename + ':' + \
str (i + 1) + ' (variable)\n_(r"' + var + '")\n')
elif comment:
output_file.write ('# ' + printedfilename + ':' + \
str (i + 1) + ' (comment)\n_(r"' + \
comment.replace ('"', '\\"') + '")\n')
elif context_id:
output_file.write ('# ' + printedfilename + ':' + \
str (i + 1) + ' (context id)\n_(r"' + \
context_id + '")\n')
# process Texinfo node names and section titles
if write_skeleton:
g = open (os.path.basename (texifilename), 'w')
subst = globals ()
subst.update (locals ())
g.write (i_blurb % subst)
tutu = texinfo_with_menus_re.findall (texifile)
node_just_defined = ''
for item in tutu:
if item[0] == '*':
g.write ('* ' + item[1] + '::\n')
elif output_file and item[4] == 'rglos':
output_file.write ('_(r"' + item[5] + '") # @rglos in ' + printedfilename + '\n')
elif item[2] == 'menu':
g.write ('@menu\n')
elif item[2] == 'end menu':
g.write ('@end menu\n\n')
elif item[2] == 'documentlanguage':
g.write ('@documentlanguage ' + doclang + '\n')
else:
space = ' '
if item[3].startswith ('{') or not item[3].strip ():
space = ''
g.write ('@' + item[2] + space + item[3] + '\n')
if node_just_defined:
g.write ('@translationof ' + node_just_defined + '\n')
g.write (n_blurb)
node_just_defined = ''
if head_only and inclusion_level == 1:
break
elif item[2] == 'include':
includes.append (item[3])
else:
if output_file:
output_file.write ('# @' + item[2] + ' in ' + \
printedfilename + '\n_(r"' + item[3].strip () + '")\n')
if item[2] == 'node':
node_just_defined = item[3].strip ()
if not head_only:
g.write (end_blurb)
g.close ()
elif output_file and scan_ly:
toto = texinfo_re.findall (texifile)
for item in toto:
if item[0] == 'include':
includes.append(item[1])
elif item[2] == 'rglos':
output_file.write ('# @rglos in ' + printedfilename + '\n_(r"' + item[3] + '")\n')
else:
output_file.write ('# @' + item[0] + ' in ' + printedfilename + '\n_(r"' + item[1].strip ().replace ('\\', r'\\') + '")\n')
if process_includes and (not head_only or inclusion_level < 1):
dir = os.path.dirname (texifilename)
for item in includes:
process_texi (os.path.join (dir, item.strip ()), i_blurb, n_blurb,
write_skeleton, topfile, output_file, scan_ly, inclusion_level + 1)
except IOError, (errno, strerror):
sys.stderr.write ("I/O error(%s): %s: %s\n" % (errno, texifilename, strerror))
if intro_blurb != '':
intro_blurb += '\n\n'
if node_blurb != '':
node_blurb = '\n' + node_blurb + '\n\n'
if make_gettext:
node_list_filename = 'node_list'
node_list = open (node_list_filename, 'w')
node_list.write ('# -*- coding: utf-8 -*-\n')
for texi_file in texi_files:
# Urgly: scan ly comments and variable names only in English doco
is_english_doc = (
True
and not 'Documentation/cs/' in texi_file
and not 'Documentation/de/' in texi_file
and not 'Documentation/es/' in texi_file
and not 'Documentation/fr/' in texi_file
and not 'Documentation/hu/' in texi_file
and not 'Documentation/ja/' in texi_file
and not 'Documentation/it/' in texi_file
and not 'Documentation/nl/' in texi_file
and not 'Documentation/po/' in texi_file
and not 'Documentation/zh/' in texi_file
)
process_texi (texi_file, intro_blurb, node_blurb, make_skeleton,
os.path.basename (texi_file), node_list,
scan_ly=is_english_doc)
for word in ('Up:', 'Next:', 'Previous:', 'Appendix ', 'Footnotes', 'Table of Contents'):
node_list.write ('_(r"' + word + '")\n')
node_list.close ()
os.system ('xgettext --keyword=_doc -c -L Python --no-location -o ' + output_name + ' ' + node_list_filename)
else:
for texi_file in texi_files:
process_texi (texi_file, intro_blurb, node_blurb, make_skeleton,
os.path.basename (texi_file))
| thSoft/lilypond-hu | scripts/auxiliar/texi-langutils.py | Python | gpl-3.0 | 9,223 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_0) on Wed Oct 05 21:20:09 EDT 2011 -->
<TITLE>
PredicateG
</TITLE>
<META NAME="date" CONTENT="2011-10-05">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="PredicateG";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PredicateG.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../info/ephyra/querygeneration/generators/BagOfWordsG.html" title="class in info.ephyra.querygeneration.generators"><B>PREV CLASS</B></A>
<A HREF="../../../../info/ephyra/querygeneration/generators/QueryGenerator.html" title="class in info.ephyra.querygeneration.generators"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?info/ephyra/querygeneration/generators/PredicateG.html" target="_top"><B>FRAMES</B></A>
<A HREF="PredicateG.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
info.ephyra.querygeneration.generators</FONT>
<BR>
Class PredicateG</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../info/ephyra/querygeneration/generators/QueryGenerator.html" title="class in info.ephyra.querygeneration.generators">info.ephyra.querygeneration.generators.QueryGenerator</A>
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>info.ephyra.querygeneration.generators.PredicateG</B>
</PRE>
<HR>
<DL>
<DT><PRE>public class <B>PredicateG</B><DT>extends <A HREF="../../../../info/ephyra/querygeneration/generators/QueryGenerator.html" title="class in info.ephyra.querygeneration.generators">QueryGenerator</A></DL>
</PRE>
<P>
<p>The <code>PredicateG</code> query generator creates queries from the
predicates in the question string.</p>
<p>This class extends the class <code>QueryGenerator</code>.</p>
<P>
<P>
<DL>
<DT><B>Version:</B></DT>
<DD>2007-07-11</DD>
<DT><B>Author:</B></DT>
<DD>Nico Schlaefer</DD>
</DL>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../info/ephyra/querygeneration/generators/PredicateG.html#EXTRACTION_TECHNIQUES">EXTRACTION_TECHNIQUES</A></B></CODE>
<BR>
Answer extraction techniques for this query type.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../info/ephyra/querygeneration/generators/PredicateG.html#IGNORE">IGNORE</A></B></CODE>
<BR>
Words that should not be part of a query string.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private static float</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../info/ephyra/querygeneration/generators/PredicateG.html#SCORE">SCORE</A></B></CODE>
<BR>
Score assigned to queries created from predicates.</TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../info/ephyra/querygeneration/generators/PredicateG.html#PredicateG()">PredicateG</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../info/ephyra/querygeneration/Query.html" title="class in info.ephyra.querygeneration">Query</A>[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../info/ephyra/querygeneration/generators/PredicateG.html#generateQueries(info.ephyra.questionanalysis.AnalyzedQuestion)">generateQueries</A></B>(<A HREF="../../../../info/ephyra/questionanalysis/AnalyzedQuestion.html" title="class in info.ephyra.questionanalysis">AnalyzedQuestion</A> aq)</CODE>
<BR>
Generates queries from predicate-argument structures extracted from the
question string.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../info/ephyra/querygeneration/generators/PredicateG.html#getQueryString(info.ephyra.nlp.semantics.Predicate[], info.ephyra.questionanalysis.Term[], java.lang.String[])">getQueryString</A></B>(<A HREF="../../../../info/ephyra/nlp/semantics/Predicate.html" title="class in info.ephyra.nlp.semantics">Predicate</A>[] predicates,
<A HREF="../../../../info/ephyra/questionanalysis/Term.html" title="class in info.ephyra.questionanalysis">Term</A>[] terms,
java.lang.String[] kws)</CODE>
<BR>
Forms a query string from the predicates, terms and individual keywords.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="SCORE"><!-- --></A><H3>
SCORE</H3>
<PRE>
private static final float <B>SCORE</B></PRE>
<DL>
<DD>Score assigned to queries created from predicates.
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../../constant-values.html#info.ephyra.querygeneration.generators.PredicateG.SCORE">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="IGNORE"><!-- --></A><H3>
IGNORE</H3>
<PRE>
private static final java.lang.String <B>IGNORE</B></PRE>
<DL>
<DD>Words that should not be part of a query string.
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../../constant-values.html#info.ephyra.querygeneration.generators.PredicateG.IGNORE">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="EXTRACTION_TECHNIQUES"><!-- --></A><H3>
EXTRACTION_TECHNIQUES</H3>
<PRE>
private static final java.lang.String[] <B>EXTRACTION_TECHNIQUES</B></PRE>
<DL>
<DD>Answer extraction techniques for this query type.
<P>
<DL>
</DL>
</DL>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="PredicateG()"><!-- --></A><H3>
PredicateG</H3>
<PRE>
public <B>PredicateG</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getQueryString(info.ephyra.nlp.semantics.Predicate[], info.ephyra.questionanalysis.Term[], java.lang.String[])"><!-- --></A><H3>
getQueryString</H3>
<PRE>
public java.lang.String <B>getQueryString</B>(<A HREF="../../../../info/ephyra/nlp/semantics/Predicate.html" title="class in info.ephyra.nlp.semantics">Predicate</A>[] predicates,
<A HREF="../../../../info/ephyra/questionanalysis/Term.html" title="class in info.ephyra.questionanalysis">Term</A>[] terms,
java.lang.String[] kws)</PRE>
<DL>
<DD>Forms a query string from the predicates, terms and individual keywords.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>predicates</CODE> - predicates in the question<DD><CODE>terms</CODE> - terms in the question<DD><CODE>kws</CODE> - keywords in the question
<DT><B>Returns:</B><DD>query string</DL>
</DD>
</DL>
<HR>
<A NAME="generateQueries(info.ephyra.questionanalysis.AnalyzedQuestion)"><!-- --></A><H3>
generateQueries</H3>
<PRE>
public <A HREF="../../../../info/ephyra/querygeneration/Query.html" title="class in info.ephyra.querygeneration">Query</A>[] <B>generateQueries</B>(<A HREF="../../../../info/ephyra/questionanalysis/AnalyzedQuestion.html" title="class in info.ephyra.questionanalysis">AnalyzedQuestion</A> aq)</PRE>
<DL>
<DD>Generates queries from predicate-argument structures extracted from the
question string.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../info/ephyra/querygeneration/generators/QueryGenerator.html#generateQueries(info.ephyra.questionanalysis.AnalyzedQuestion)">generateQueries</A></CODE> in class <CODE><A HREF="../../../../info/ephyra/querygeneration/generators/QueryGenerator.html" title="class in info.ephyra.querygeneration.generators">QueryGenerator</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>aq</CODE> - analyzed question
<DT><B>Returns:</B><DD><code>Query</code> objects</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PredicateG.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../info/ephyra/querygeneration/generators/BagOfWordsG.html" title="class in info.ephyra.querygeneration.generators"><B>PREV CLASS</B></A>
<A HREF="../../../../info/ephyra/querygeneration/generators/QueryGenerator.html" title="class in info.ephyra.querygeneration.generators"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?info/ephyra/querygeneration/generators/PredicateG.html" target="_top"><B>FRAMES</B></A>
<A HREF="PredicateG.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| Eric-LeiYang/Openephyra | openephyra-0.1.2/doc/info/ephyra/querygeneration/generators/PredicateG.html | HTML | gpl-3.0 | 16,609 |
<?php
$hardware = "Datacom ".str_replace("dmSwitch","DM",snmp_get($device, "swChassisModel.0", "-Ovq", "DMswitch-MIB"));
$version = snmp_get($device, "swFirmwareVer.1", "-Ovq", "DMswitch-MIB");
$features = snmp_get($device, "sysDescr.0", "-Oqv", "SNMPv2-MIB");
$serial = snmp_get($device, "DMswitch-MIB::swSerialNumber.1", "-Ovq","DMswitch-MIB");
?> | neokjames/librenms | includes/polling/os/datacom.inc.php | PHP | gpl-3.0 | 351 |
/* Part of Cosmos by OpenGenus Foundation */
import java.util.ArrayList;
import java.util.List;
public class RadixSort
{
public static void main(String[] args)
{
int[] nums = {100, 5, 100, 19, 320000, 0, 67, 542, 10, 222};
radixSort(nums);
printArray(nums);
}
/**
* This method sorts a passed array of positive integers using radix sort
* @param input: the array to be sorted
*/
public static void radixSort(int[] input)
{
List<Integer>[] buckets = new ArrayList[10];
for(int i = 0; i < buckets.length; i++)//initialize buckets
buckets[i] = new ArrayList<Integer>();
int divisor = 1;
String s = Integer.toString(findMax(input));
int count = s.length();//count is the number of digits of the largest number
for(int i = 0; i < count; divisor*=10, i++)
{
for(Integer num : input)
{
assert(num >= 0);
int temp = num / divisor;
buckets[temp % 10].add(num);
}
//Load buckets back into the input array
int j = 0;
for (int k = 0; k < 10; k++)
{
for (Integer x : buckets[k])
{
input[j++] = x;
}
buckets[k].clear();
}
}
}
/**
* This method returns the maximum integer in an integer array.
* @param input: the array
* @return the maximum integer in input
*/
public static int findMax(int[] input)
{
assert(input.length != 0);
int max = input[0];
for(int i = 1; i < input.length; i++)
if(input[i] > max) max = input[i];
return max;
}
/**
* This method prints a passed array
* @param array: the array to be printed
*/
public static void printArray(int[] array)
{
System.out.print("[ ");
for(Integer i : array)
System.out.print(i+" ");
System.out.print("]");
}
}
| OpenGenus/cosmos | code/sorting/src/radix_sort/radix_sort.java | Java | gpl-3.0 | 1,938 |
/* This file is (c) 2008-2012 Konstantin Isakov <[email protected]>
* Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */
#ifndef __CONFIG_HH_INCLUDED__
#define __CONFIG_HH_INCLUDED__
#include <QVector>
#include <QString>
#include <QSize>
#include <QDateTime>
#include <QKeySequence>
#include <QSet>
#include "ex.hh"
#ifdef Q_OS_WIN
#include <QRect>
#endif
/// GoldenDict's configuration
namespace Config {
/// Dictionaries which are temporarily disabled via the dictionary bar.
typedef QSet< QString > MutedDictionaries;
#ifdef Q_OS_WIN
#pragma pack(push,4)
#endif
/// A path where to search for the dictionaries
struct Path
{
QString path;
bool recursive;
Path(): recursive( false ) {}
Path( QString const & path_, bool recursive_ ):
path( path_ ), recursive( recursive_ ) {}
bool operator == ( Path const & other ) const
{ return path == other.path && recursive == other.recursive; }
};
/// A list of paths where to search for the dictionaries
typedef QVector< Path > Paths;
/// A directory holding bunches of audiofiles, which is indexed into a separate
/// dictionary.
struct SoundDir
{
QString path, name;
QString iconFilename;
SoundDir()
{}
SoundDir( QString const & path_, QString const & name_, QString iconFilename_ = "" ):
path( path_ ), name( name_ ), iconFilename( iconFilename_ )
{}
bool operator == ( SoundDir const & other ) const
{ return path == other.path && name == other.name && iconFilename == other.iconFilename; }
};
/// A list of SoundDirs
typedef QVector< SoundDir > SoundDirs;
struct DictionaryRef
{
QString id; // Dictionrary id, which is usually an md5 hash
QString name; // Dictionary name, used to recover when its id changes
DictionaryRef()
{}
DictionaryRef( QString const & id_, QString const & name_ ):
id( id_ ), name( name_ ) {}
bool operator == ( DictionaryRef const & other ) const
{ return id == other.id && name == other.name; }
};
/// A dictionary group
struct Group
{
unsigned id;
QString name, icon;
QByteArray iconData;
QKeySequence shortcut;
QVector< DictionaryRef > dictionaries;
Config::MutedDictionaries mutedDictionaries; // Disabled via dictionary bar
Config::MutedDictionaries popupMutedDictionaries; // Disabled via dictionary bar in popup
Group(): id( 0 ) {}
bool operator == ( Group const & other ) const
{ return id == other.id && name == other.name && icon == other.icon &&
dictionaries == other.dictionaries && shortcut == other.shortcut &&
mutedDictionaries == other.mutedDictionaries &&
popupMutedDictionaries == other.popupMutedDictionaries &&
iconData == other.iconData; }
bool operator != ( Group const & other ) const
{ return ! operator == ( other ); }
};
/// All the groups
struct Groups: public QVector< Group >
{
unsigned nextId; // Id to use to create the group next time
Groups(): nextId( 1 )
{}
};
/// Proxy server configuration
struct ProxyServer
{
bool enabled;
bool useSystemProxy;
enum Type
{
Socks5 = 0,
HttpConnect,
HttpGet
} type;
QString host;
unsigned port;
QString user, password;
QString systemProxyUser, systemProxyPassword;
ProxyServer();
};
// A hotkey -- currently qt modifiers plus one or two keys
struct HotKey
{
Qt::KeyboardModifiers modifiers;
int key1, key2;
HotKey();
/// We use the first two keys of QKeySequence, with modifiers being stored
/// in the first one.
HotKey( QKeySequence const & );
QKeySequence toKeySequence() const;
};
struct FullTextSearch
{
int searchMode;
bool matchCase;
int maxArticlesPerDictionary;
int maxDistanceBetweenWords;
bool useMaxDistanceBetweenWords;
bool useMaxArticlesPerDictionary;
bool enabled;
quint32 maxDictionarySize;
QByteArray dialogGeometry;
QString disabledTypes;
FullTextSearch() :
searchMode( 0 ), matchCase( false ),
maxArticlesPerDictionary( 100 ),
maxDistanceBetweenWords( 2 ),
useMaxDistanceBetweenWords( true ),
useMaxArticlesPerDictionary( false ),
enabled( true ),
maxDictionarySize( 0 )
{}
};
/// Various user preferences
struct Preferences
{
QString interfaceLanguage; // Empty value corresponds to system default
QString helpLanguage; // Empty value corresponds to interface language
QString displayStyle; // Empty value corresponds to the default one
bool newTabsOpenAfterCurrentOne;
bool newTabsOpenInBackground;
bool hideSingleTab;
bool mruTabOrder;
bool hideMenubar;
bool enableTrayIcon;
bool startToTray;
bool closeToTray;
bool autoStart;
bool doubleClickTranslates;
bool selectWordBySingleClick;
bool escKeyHidesMainWindow;
bool alwaysOnTop;
/// An old UI mode when tranlateLine and wordList
/// are in the dockable side panel, not on the toolbar.
bool searchInDock;
bool enableMainWindowHotkey;
HotKey mainWindowHotkey;
bool enableClipboardHotkey;
HotKey clipboardHotkey;
bool enableScanPopup;
bool startWithScanPopupOn;
bool enableScanPopupModifiers;
unsigned long scanPopupModifiers; // Combination of KeyboardState::Modifier
bool scanPopupAltMode; // When you press modifier shortly after the selection
unsigned scanPopupAltModeSecs;
bool scanPopupUseUIAutomation;
bool scanPopupUseIAccessibleEx;
bool scanPopupUseGDMessage;
bool scanToMainWindow;
// Whether the word should be pronounced on page load, in main window/popup
bool pronounceOnLoadMain, pronounceOnLoadPopup;
QString audioPlaybackProgram;
bool useExternalPlayer;
bool useInternalPlayer;
ProxyServer proxyServer;
bool checkForNewReleases;
bool disallowContentFromOtherSites;
bool enableWebPlugins;
bool hideGoldenDictHeader;
qreal zoomFactor;
qreal helpZoomFactor;
int wordsZoomLevel;
unsigned maxStringsInHistory;
unsigned storeHistory;
bool alwaysExpandOptionalParts;
unsigned historyStoreInterval;
bool collapseBigArticles;
int articleSizeLimit;
unsigned short maxDictionaryRefsInContextMenu;
#ifndef Q_WS_X11
bool trackClipboardChanges;
#endif
QString addonStyle;
FullTextSearch fts;
Preferences();
};
/// A MediaWiki network dictionary definition
struct MediaWiki
{
QString id, name, url;
bool enabled;
QString icon;
MediaWiki(): enabled( false )
{}
MediaWiki( QString const & id_, QString const & name_, QString const & url_,
bool enabled_, QString const & icon_ ):
id( id_ ), name( name_ ), url( url_ ), enabled( enabled_ ), icon( icon_ ) {}
bool operator == ( MediaWiki const & other ) const
{ return id == other.id && name == other.name && url == other.url &&
enabled == other.enabled && icon == other.icon ; }
};
/// Any website which can be queried though a simple template substitution
struct WebSite
{
QString id, name, url;
bool enabled;
QString iconFilename;
WebSite(): enabled( false )
{}
WebSite( QString const & id_, QString const & name_, QString const & url_,
bool enabled_, QString const & iconFilename_ ):
id( id_ ), name( name_ ), url( url_ ), enabled( enabled_ ), iconFilename( iconFilename_ ) {}
bool operator == ( WebSite const & other ) const
{ return id == other.id && name == other.name && url == other.url &&
enabled == other.enabled && iconFilename == other.iconFilename; }
};
/// All the WebSites
typedef QVector< WebSite > WebSites;
/// Any DICT server
struct DictServer
{
QString id, name, url;
bool enabled;
QString databases;
QString strategies;
QString iconFilename;
DictServer(): enabled( false )
{}
DictServer( QString const & id_, QString const & name_, QString const & url_,
bool enabled_, QString const & databases_, QString const & strategies_,
QString const & iconFilename_ ):
id( id_ ), name( name_ ), url( url_ ), enabled( enabled_ ), databases( databases_ ),
strategies( strategies_ ), iconFilename( iconFilename_ ) {}
bool operator == ( DictServer const & other ) const
{ return id == other.id && name == other.name && url == other.url
&& enabled == other.enabled && databases == other.databases
&& strategies == other.strategies
&& iconFilename == other.iconFilename; }
};
/// All the DictServers
typedef QVector< DictServer > DictServers;
/// Hunspell configuration
struct Hunspell
{
QString dictionariesPath;
typedef QVector< QString > Dictionaries;
Dictionaries enabledDictionaries;
bool operator == ( Hunspell const & other ) const
{ return dictionariesPath == other.dictionariesPath &&
enabledDictionaries == other.enabledDictionaries; }
bool operator != ( Hunspell const & other ) const
{ return ! operator == ( other ); }
};
/// All the MediaWikis
typedef QVector< MediaWiki > MediaWikis;
/// Romaji transliteration configuration
struct Romaji
{
bool enable;
bool enableHepburn;
bool enableNihonShiki;
bool enableKunreiShiki;
bool enableHiragana;
bool enableKatakana;
Romaji();
bool operator == ( Romaji const & other ) const
{ return enable == other.enable &&
enableHepburn == other.enableHepburn &&
enableNihonShiki == other.enableNihonShiki &&
enableKunreiShiki == other.enableKunreiShiki &&
enableHiragana == other.enableHiragana &&
enableKatakana == other.enableKatakana; }
bool operator != ( Romaji const & other ) const
{ return ! operator == ( other ); }
};
struct Transliteration
{
bool enableRussianTransliteration;
bool enableGermanTransliteration;
bool enableGreekTransliteration;
bool enableBelarusianTransliteration;
Romaji romaji;
bool operator == ( Transliteration const & other ) const
{ return enableRussianTransliteration == other.enableRussianTransliteration &&
romaji == other.romaji &&
enableGermanTransliteration == other.enableGermanTransliteration &&
enableGreekTransliteration == other.enableGreekTransliteration &&
enableBelarusianTransliteration == other.enableBelarusianTransliteration;
}
bool operator != ( Transliteration const & other ) const
{ return ! operator == ( other ); }
Transliteration():
enableRussianTransliteration( false ),
enableGermanTransliteration( false ),
enableGreekTransliteration( false ),
enableBelarusianTransliteration( false )
{}
};
struct Forvo
{
bool enable;
QString apiKey;
QString languageCodes;
Forvo(): enable( false )
{}
bool operator == ( Forvo const & other ) const
{ return enable == other.enable &&
apiKey == other.apiKey &&
languageCodes == other.languageCodes;
}
bool operator != ( Forvo const & other ) const
{ return ! operator == ( other ); }
};
struct Program
{
bool enabled;
enum Type
{
Audio,
PlainText,
Html,
PrefixMatch,
MaxTypeValue
} type;
QString id, name, commandLine;
QString iconFilename;
Program(): enabled( false )
{}
Program( bool enabled_, Type type_, QString const & id_,
QString const & name_, QString const & commandLine_, QString const & iconFilename_ ):
enabled( enabled_ ), type( type_ ), id( id_ ), name( name_ ),
commandLine( commandLine_ ), iconFilename( iconFilename_ ) {}
bool operator == ( Program const & other ) const
{ return enabled == other.enabled &&
type == other.type &&
name == other.name &&
commandLine == other.commandLine &&
iconFilename == other.iconFilename;
}
bool operator != ( Program const & other ) const
{ return ! operator == ( other ); }
};
typedef QVector< Program > Programs;
struct VoiceEngine
{
bool enabled;
QString id;
QString name;
QString iconFilename;
int volume; // 0-100 allowed
int rate; // 0-100 allowed
VoiceEngine(): enabled( false )
, volume( 50 )
, rate( 50 )
{}
VoiceEngine( QString id_, QString name_, int volume_, int rate_ ):
enabled( false )
, id( id_ )
, name( name_ )
, volume( volume_ )
, rate( rate_ )
{}
bool operator == ( VoiceEngine const & other ) const
{
return enabled == other.enabled &&
id == other.id &&
name == other.name &&
iconFilename == other.iconFilename &&
volume == other.volume &&
rate == other.rate;
}
bool operator != ( VoiceEngine const & other ) const
{ return ! operator == ( other ); }
};
typedef QVector< VoiceEngine> VoiceEngines;
struct HeadwordsDialog
{
int searchMode;
bool matchCase;
bool autoApply;
QString headwordsExportPath;
QByteArray headwordsDialogGeometry;
HeadwordsDialog() :
searchMode( 0 ), matchCase( false )
, autoApply( false )
{}
};
struct Class
{
Paths paths;
SoundDirs soundDirs;
Group dictionaryOrder;
Group inactiveDictionaries;
Groups groups;
Preferences preferences;
MediaWikis mediawikis;
WebSites webSites;
DictServers dictServers;
Hunspell hunspell;
Transliteration transliteration;
Forvo forvo;
Programs programs;
VoiceEngines voiceEngines;
unsigned lastMainGroupId; // Last used group in main window
unsigned lastPopupGroupId; // Last used group in popup window
QByteArray popupWindowState; // Binary state saved by QMainWindow
QByteArray popupWindowGeometry; // Geometry saved by QMainWindow
QByteArray dictInfoGeometry; // Geometry of "Dictionary info" window
QByteArray inspectorGeometry; // Geometry of WebKit inspector window
QByteArray helpWindowGeometry; // Geometry of help window
QByteArray helpSplitterState; // Geometry of help splitter
QString historyExportPath; // Path for export/import history
QString resourceSavePath; // Path to save images/audio
QString articleSavePath; // Path to save articles
bool pinPopupWindow; // Last pin status
QByteArray mainWindowState; // Binary state saved by QMainWindow
QByteArray mainWindowGeometry; // Geometry saved by QMainWindow
MutedDictionaries mutedDictionaries; // Disabled via dictionary bar
MutedDictionaries popupMutedDictionaries; // Disabled via dictionary bar in popup
QDateTime timeForNewReleaseCheck; // Only effective if
// preferences.checkForNewReleases is set
QString skippedRelease; // Empty by default
bool showingDictBarNames;
bool usingSmallIconsInToolbars;
int maxPictureWidth; // Maximum picture width
/// Maximum size for the headwords.
/// Bigger headwords won't be indexed. For now, only in DSL.
unsigned int maxHeadwordSize;
HeadwordsDialog headwordsDialog;
#ifdef Q_OS_WIN
QRect maximizedMainWindowGeometry;
QRect normalMainWindowGeometry;
#endif
QString editDictionaryCommandLine; // Command line to call external editor for dictionary
Class(): lastMainGroupId( 0 ), lastPopupGroupId( 0 ),
pinPopupWindow( false ), showingDictBarNames( false ),
usingSmallIconsInToolbars( false ),
maxPictureWidth( 0 ), maxHeadwordSize ( 256U )
{}
Group * getGroup( unsigned id );
Group const * getGroup( unsigned id ) const;
};
#ifdef Q_OS_WIN
#pragma pack(pop)
#endif
/// Configuration-specific events. Some parts of the program need to react
/// to specific changes in configuration. The object of this class is used
/// to emit signals when such events happen -- and the listeners connect to
/// them to be notified of them.
/// This class is separate from the main Class since QObjects can't be copied.
class Events: public QObject
{
Q_OBJECT
public:
/// Signals that the value of the mutedDictionaries has changed.
/// This emits mutedDictionariesChanged() signal, so the subscribers will
/// be notified.
void signalMutedDictionariesChanged();
signals:
/// THe value of the mutedDictionaries has changed.
void mutedDictionariesChanged();
private:
};
DEF_EX( exError, "Error with the program's configuration", std::exception )
DEF_EX( exCantUseHomeDir, "Can't use home directory to store GoldenDict preferences", exError )
DEF_EX( exCantUseIndexDir, "Can't use index directory to store GoldenDict index files", exError )
DEF_EX( exCantReadConfigFile, "Can't read the configuration file", exError )
DEF_EX( exCantWriteConfigFile, "Can't write the configuration file", exError )
DEF_EX( exMalformedConfigFile, "The configuration file is malformed", exError )
/// Loads the configuration, or creates the default one if none is present
Class load() throw( exError );
/// Saves the configuration
void save( Class const & ) throw( exError );
/// Returns the configuration file name.
QString getConfigFileName();
/// Returns the main configuration directory.
QString getConfigDir() throw( exError );
/// Returns the index directory, where the indices are to be stored.
QString getIndexDir() throw( exError );
/// Returns the filename of a .pid file which should store current pid of
/// the process.
QString getPidFileName() throw( exError );
/// Returns the filename of a history file which stores search history.
QString getHistoryFileName() throw( exError );
/// Returns the user .css file name.
QString getUserCssFileName() throw( exError );
/// Returns the user .css file name used for printing only.
QString getUserCssPrintFileName() throw( exError );
/// Returns the user .css file name for the Qt interface customization.
QString getUserQtCssFileName() throw( exError );
/// Returns the program's data dir. Under Linux that would be something like
/// /usr/share/apps/goldendict, under Windows C:/Program Files/GoldenDict.
QString getProgramDataDir() throw();
/// Returns the directory storing program localizized files (.qm).
QString getLocDir() throw();
/// Returns the directory storing program help files (.qch).
QString getHelpDir() throw();
/// Returns true if the program is configured as a portable version. In that
/// mode, all the settings and indices are kept in the program's directory.
bool isPortableVersion() throw();
/// Returns directory with dictionaries for portable version. It is content/
/// in the application's directory.
QString getPortableVersionDictionaryDir() throw();
/// Returns directory with morpgologies for portable version. It is
/// content/morphology in the application's directory.
QString getPortableVersionMorphoDir() throw();
/// Returns the add-on styles directory.
QString getStylesDir() throw();
}
#endif
| debugfan/goldendict | config.hh | C++ | gpl-3.0 | 18,345 |
/*
Copyright © 2017 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#include "toxencrypt.h"
#include <tox/toxencryptsave.h>
#include <QByteArray>
#include <QDebug>
#include <QString>
#include <memory>
// functions for nice debug output
static QString getKeyDerivationError(TOX_ERR_KEY_DERIVATION error);
static QString getEncryptionError(TOX_ERR_ENCRYPTION error);
static QString getDecryptionError(TOX_ERR_DECRYPTION error);
static QString getSaltError(TOX_ERR_GET_SALT error);
/**
* @class ToxEncrypt
* @brief Encapsulates the toxencrypsave API.
* Since key derivation is work intensive and to avoid storing plaintext
* passwords in memory, use a ToxEncrypt object and encrypt() or decrypt()
* when you have to encrypt or decrypt more than once with the same password.
*/
/**
* @brief Frees the passKey before destruction.
*/
ToxEncrypt::~ToxEncrypt()
{
tox_pass_key_free(passKey);
}
/**
* @brief Constructs a ToxEncrypt object from a Tox_Pass_Key.
* @param key Derived key to use for encryption and decryption.
*/
ToxEncrypt::ToxEncrypt(Tox_Pass_Key* key)
: passKey{key}
{
}
/**
* @brief Gets the minimum number of bytes needed for isEncrypted()
* @return Minimum number of bytes needed to check if data was encrypted
* using this module.
*/
int ToxEncrypt::getMinBytes()
{
return TOX_PASS_ENCRYPTION_EXTRA_LENGTH;
}
/**
* @brief Checks if the data was encrypted by this module.
* @param ciphertext The data to check.
* @return True if the data was encrypted using this module, false otherwise.
*/
bool ToxEncrypt::isEncrypted(const QByteArray& ciphertext)
{
if (ciphertext.length() < TOX_PASS_ENCRYPTION_EXTRA_LENGTH) {
return false;
}
return tox_is_data_encrypted(reinterpret_cast<const uint8_t*>(ciphertext.constData()));
}
/**
* @brief Encrypts the plaintext with the given password.
* @return Encrypted data or empty QByteArray on failure.
* @param password Password to encrypt the data.
* @param plaintext The data to encrypt.
*/
QByteArray ToxEncrypt::encryptPass(const QString& password, const QByteArray& plaintext)
{
if (password.length() == 0) {
qWarning() << "Empty password supplied, probably not what you intended.";
}
QByteArray pass = password.toUtf8();
QByteArray ciphertext(plaintext.length() + TOX_PASS_ENCRYPTION_EXTRA_LENGTH, 0x00);
TOX_ERR_ENCRYPTION error;
tox_pass_encrypt(reinterpret_cast<const uint8_t*>(plaintext.constData()),
static_cast<size_t>(plaintext.size()),
reinterpret_cast<const uint8_t*>(pass.constData()),
static_cast<size_t>(pass.size()),
reinterpret_cast<uint8_t*>(ciphertext.data()), &error);
if (error != TOX_ERR_ENCRYPTION_OK) {
qCritical() << getEncryptionError(error);
return QByteArray{};
}
return ciphertext;
}
/**
* @brief Decrypts data encrypted with this module.
* @return The plaintext or an empty QByteArray on failure.
* @param password The password used to encrypt the data.
* @param ciphertext The encrypted data.
*/
QByteArray ToxEncrypt::decryptPass(const QString& password, const QByteArray& ciphertext)
{
if (!isEncrypted(ciphertext)) {
qWarning() << "The data was not encrypted using this module or it's corrupted.";
return QByteArray{};
}
if (password.length() == 0) {
qDebug() << "Empty password supplied, probably not what you intended.";
}
QByteArray pass = password.toUtf8();
QByteArray plaintext(ciphertext.length() - TOX_PASS_ENCRYPTION_EXTRA_LENGTH, 0x00);
TOX_ERR_DECRYPTION error;
tox_pass_decrypt(reinterpret_cast<const uint8_t*>(ciphertext.constData()),
static_cast<size_t>(ciphertext.size()),
reinterpret_cast<const uint8_t*>(pass.constData()),
static_cast<size_t>(pass.size()), reinterpret_cast<uint8_t*>(plaintext.data()),
&error);
if (error != TOX_ERR_DECRYPTION_OK) {
qWarning() << getDecryptionError(error);
return QByteArray{};
}
return plaintext;
}
/**
* @brief Factory method for the ToxEncrypt object.
* @param password Password to use for encryption.
* @return A std::unique_ptr containing a ToxEncrypt object on success, or an
* or an empty std::unique_ptr on failure.
*
* Derives a key from the password and a new random salt.
*/
std::unique_ptr<ToxEncrypt> ToxEncrypt::makeToxEncrypt(const QString& password)
{
Tox_Pass_Key* passKey = tox_pass_key_new();
QByteArray pass = password.toUtf8();
TOX_ERR_KEY_DERIVATION error;
tox_pass_key_derive(passKey, reinterpret_cast<const uint8_t*>(pass.constData()),
static_cast<size_t>(pass.length()), &error);
if (error != TOX_ERR_KEY_DERIVATION_OK) {
tox_pass_key_free(passKey);
qCritical() << getKeyDerivationError(error);
return std::unique_ptr<ToxEncrypt>{};
}
return std::unique_ptr<ToxEncrypt>(new ToxEncrypt(passKey));
}
/**
* @brief Factory method for the ToxEncrypt object.
* @param password Password to use for encryption.
* @param toxSave The data to read the salt for decryption from.
* @return A std::unique_ptr containing a ToxEncrypt object on success, or an
* or an empty std::unique_ptr on failure.
*
* Derives a key from the password and the salt read from toxSave.
*/
std::unique_ptr<ToxEncrypt> ToxEncrypt::makeToxEncrypt(const QString& password, const QByteArray& toxSave)
{
if (!isEncrypted(toxSave)) {
qWarning() << "The data was not encrypted using this module or it's corrupted.";
return std::unique_ptr<ToxEncrypt>{};
}
TOX_ERR_GET_SALT saltError;
uint8_t salt[TOX_PASS_SALT_LENGTH];
tox_get_salt(reinterpret_cast<const uint8_t*>(toxSave.constData()), salt, &saltError);
if (saltError != TOX_ERR_GET_SALT_OK) {
qWarning() << getSaltError(saltError);
return std::unique_ptr<ToxEncrypt>{};
}
Tox_Pass_Key* passKey = tox_pass_key_new();
QByteArray pass = password.toUtf8();
TOX_ERR_KEY_DERIVATION keyError;
tox_pass_key_derive_with_salt(passKey, reinterpret_cast<const uint8_t*>(pass.constData()),
static_cast<size_t>(pass.length()), salt, &keyError);
if (keyError != TOX_ERR_KEY_DERIVATION_OK) {
tox_pass_key_free(passKey);
qWarning() << getKeyDerivationError(keyError);
return std::unique_ptr<ToxEncrypt>{};
}
return std::unique_ptr<ToxEncrypt>(new ToxEncrypt(passKey));
}
/**
* @brief Encrypts the plaintext with the stored key.
* @return Encrypted data or empty QByteArray on failure.
* @param plaintext The data to encrypt.
*/
QByteArray ToxEncrypt::encrypt(const QByteArray& plaintext) const
{
if (!passKey) {
qCritical() << "The passKey is invalid.";
return QByteArray{};
}
QByteArray ciphertext(plaintext.length() + TOX_PASS_ENCRYPTION_EXTRA_LENGTH, 0x00);
TOX_ERR_ENCRYPTION error;
tox_pass_key_encrypt(passKey, reinterpret_cast<const uint8_t*>(plaintext.constData()),
static_cast<size_t>(plaintext.size()),
reinterpret_cast<uint8_t*>(ciphertext.data()), &error);
if (error != TOX_ERR_ENCRYPTION_OK) {
qCritical() << getEncryptionError(error);
return QByteArray{};
}
return ciphertext;
}
/**
* @brief Decrypts data encrypted with this module, using the stored key.
* @return The plaintext or an empty QByteArray on failure.
* @param ciphertext The encrypted data.
*/
QByteArray ToxEncrypt::decrypt(const QByteArray& ciphertext) const
{
if (!isEncrypted(ciphertext)) {
qWarning() << "The data was not encrypted using this module or it's corrupted.";
return QByteArray{};
}
QByteArray plaintext(ciphertext.length() - TOX_PASS_ENCRYPTION_EXTRA_LENGTH, 0x00);
TOX_ERR_DECRYPTION error;
tox_pass_key_decrypt(passKey, reinterpret_cast<const uint8_t*>(ciphertext.constData()),
static_cast<size_t>(ciphertext.size()),
reinterpret_cast<uint8_t*>(plaintext.data()), &error);
if (error != TOX_ERR_DECRYPTION_OK) {
qWarning() << getDecryptionError(error);
return QByteArray{};
}
return plaintext;
}
/**
* @brief Gets the error string for TOX_ERR_KEY_DERIVATION errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getKeyDerivationError(TOX_ERR_KEY_DERIVATION error)
{
switch (error) {
case TOX_ERR_KEY_DERIVATION_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_KEY_DERIVATION_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_KEY_DERIVATION_FAILED:
return QStringLiteral(
"The crypto lib was unable to derive a key from the given passphrase.");
default:
return QStringLiteral("Unknown key derivation error.");
}
}
/**
* @brief Gets the error string for TOX_ERR_ENCRYPTION errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getEncryptionError(TOX_ERR_ENCRYPTION error)
{
switch (error) {
case TOX_ERR_ENCRYPTION_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_ENCRYPTION_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_ENCRYPTION_KEY_DERIVATION_FAILED:
return QStringLiteral(
"The crypto lib was unable to derive a key from the given passphrase.");
case TOX_ERR_ENCRYPTION_FAILED:
return QStringLiteral("The encryption itself failed.");
default:
return QStringLiteral("Unknown encryption error.");
}
}
/**
* @brief Gets the error string for TOX_ERR_DECRYPTION errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getDecryptionError(TOX_ERR_DECRYPTION error)
{
switch (error) {
case TOX_ERR_DECRYPTION_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_DECRYPTION_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_DECRYPTION_INVALID_LENGTH:
return QStringLiteral(
"The input data was shorter than TOX_PASS_ENCRYPTION_EXTRA_LENGTH bytes.");
case TOX_ERR_DECRYPTION_BAD_FORMAT:
return QStringLiteral("The input data is missing the magic number or is corrupted.");
default:
return QStringLiteral("Unknown decryption error.");
}
}
/**
* @brief Gets the error string for TOX_ERR_GET_SALT errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getSaltError(TOX_ERR_GET_SALT error)
{
switch (error) {
case TOX_ERR_GET_SALT_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_GET_SALT_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_GET_SALT_BAD_FORMAT:
return QStringLiteral("The input data is missing the magic number or is corrupted.");
default:
return QStringLiteral("Unknown salt error.");
}
}
| Grokafar/qTox | src/core/toxencrypt.cpp | C++ | gpl-3.0 | 12,153 |
// Copyright (c) Aura development team - Licensed under GNU GPL
// For more information, see license file in the main folder
using Aura.Shared.Util;
using System;
namespace Aura.Msgr
{
class Program
{
static void Main(string[] args)
{
try
{
MsgrServer.Instance.Run();
}
catch (Exception ex)
{
Log.Exception(ex, "An exception occured while starting the server.");
CliUtil.Exit(1);
}
}
}
}
| Rai/aura | src/MsgrServer/Program.cs | C# | gpl-3.0 | 432 |
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2009-2015 Marianne Gagnon
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef HEADER_CONFIRM_RES_DIALOG_HPP
#define HEADER_CONFIRM_RES_DIALOG_HPP
#include "guiengine/modaldialog.hpp"
#include "utils/cpp2011.hpp"
/**
* \brief Dialog shown after a resolution switch sot he user may confirm if
* the resolution works.
* \ingroup states_screens
*/
class ConfirmResolutionDialog : public GUIEngine::ModalDialog
{
private:
/** number of seconds left before resolution is considered unplayable */
float m_remaining_time;
/** updates countdown message */
void updateMessage();
public:
ConfirmResolutionDialog();
void onEnterPressedInternal();
GUIEngine::EventPropagation processEvent(const std::string& eventSource);
virtual void onUpdate(float dt);
virtual bool onEscapePressed() OVERRIDE;
};
#endif
| Charence/stk-code | src/states_screens/dialogs/confirm_resolution_dialog.hpp | C++ | gpl-3.0 | 1,616 |
<?php
class MailTest extends PHPUnit_Framework_TestCase
{
public function testToAccessors()
{
$message = new SendGrid\Mail();
// setTo instanciates and overrides existing data
$message->setTo('bar');
$message->setTo('foo');
$this->assertEquals(1, count($message->getTos()));
$to_list = $message->getTos();
$this->assertEquals('foo', $to_list[0]);
// setTos instanciates and overrides existing data
$message->setTos(array('raz', 'ber'));
$this->assertEquals(2, count($message->getTos()));
$to_list = $message->getTos();
$this->assertEquals('raz', $to_list[0]);
$this->assertEquals('ber', $to_list[1]);
// addTo appends to existing data
$message->addTo('foo');
$message->addTo('raz');
$this->assertEquals(4, count($message->getTos()));
$to_list = $message->getTos();
$this->assertEquals('raz', $to_list[0]);
$this->assertEquals('ber', $to_list[1]);
$this->assertEquals('foo', $to_list[2]);
$this->assertEquals('raz', $to_list[3]);
// removeTo removes all occurences of data
$message->removeTo('raz');
$this->assertEquals(2, count($message->getTos()));
$to_list = $message->getTos();
$this->assertEquals('ber', $to_list[0]);
$this->assertEquals('foo', $to_list[1]);
}
public function testFromAccessors()
{
$message = new SendGrid\Mail();
$message->setFrom("[email protected]");
$message->setFromName("John Doe");
$this->assertEquals("[email protected]", $message->getFrom());
$this->assertEquals(array("[email protected]" => "John Doe"), $message->getFrom(true));
}
public function testFromNameAccessors()
{
$message = new SendGrid\Mail();
// Defaults to false
$this->assertFalse($message->getFromName());
$message->setFromName("Swift");
$this->assertEquals("Swift", $message->getFromName());
}
public function testReplyToAccessors()
{
$message = new SendGrid\Mail();
// Defaults to false
$this->assertFalse($message->getReplyTo());
$message->setReplyTo("[email protected]");
$this->assertEquals("[email protected]", $message->getReplyTo());
}
public function testCcAccessors()
{
$message = new SendGrid\Mail();
// setTo instanciates and overrides existing data
$message->setCc('bar');
$message->setCc('foo');
$this->assertEquals(1, count($message->getCcs()));
$cc_list = $message->getCcs();
$this->assertEquals('foo', $cc_list[0]);
// setTos instanciates and overrides existing data
$message->setCcs(array('raz', 'ber'));
$this->assertEquals(2, count($message->getCcs()));
$cc_list = $message->getCcs();
$this->assertEquals('raz', $cc_list[0]);
$this->assertEquals('ber', $cc_list[1]);
// addTo appends to existing data
$message->addCc('foo');
$message->addCc('raz');
$this->assertEquals(4, count($message->getCcs()));
$cc_list = $message->getCcs();
$this->assertEquals('raz', $cc_list[0]);
$this->assertEquals('ber', $cc_list[1]);
$this->assertEquals('foo', $cc_list[2]);
$this->assertEquals('raz', $cc_list[3]);
// removeTo removes all occurences of data
$message->removeCc('raz');
$this->assertEquals(2, count($message->getCcs()));
$cc_list = $message->getCcs();
$this->assertEquals('ber', $cc_list[0]);
$this->assertEquals('foo', $cc_list[1]);
}
public function testBccAccessors()
{
$message = new SendGrid\Mail();
// setTo instanciates and overrides existing data
$message->setBcc('bar');
$message->setBcc('foo');
$this->assertEquals(1, count($message->getBccs()));
$bcc_list = $message->getBccs();
$this->assertEquals('foo', $bcc_list[0]);
// setTos instanciates and overrides existing data
$message->setBccs(array('raz', 'ber'));
$this->assertEquals(2, count($message->getBccs()));
$bcc_list = $message->getBccs();
$this->assertEquals('raz', $bcc_list[0]);
$this->assertEquals('ber', $bcc_list[1]);
// addTo appends to existing data
$message->addBcc('foo');
$message->addBcc('raz');
$this->assertEquals(4, count($message->getBccs()));
$bcc_list = $message->getBccs();
$this->assertEquals('raz', $bcc_list[0]);
$this->assertEquals('ber', $bcc_list[1]);
$this->assertEquals('foo', $bcc_list[2]);
$this->assertEquals('raz', $bcc_list[3]);
// removeTo removes all occurences of data
$message->removeBcc('raz');
$this->assertEquals(2, count($message->getBccs()));
$bcc_list = $message->getBccs();
$this->assertEquals('ber', $bcc_list[0]);
$this->assertEquals('foo', $bcc_list[1]);
}
public function testSubjectAccessors()
{
$message = new SendGrid\Mail();
$message->setSubject("Test Subject");
$this->assertEquals("Test Subject", $message->getSubject());
}
public function testTextAccessors()
{
$message = new SendGrid\Mail();
$text = "sample plain text";
$message->setText($text);
$this->assertEquals($text, $message->getText());
}
public function testHTMLAccessors()
{
$message = new SendGrid\Mail();
$html = "<p style = 'color:red;'>Sample HTML text</p>";
$message->setHtml($html);
$this->assertEquals($html, $message->getHtml());
}
public function testAttachmentAccessors()
{
$message = new SendGrid\Mail();
$attachments =
array(
"path/to/file/file_1.txt",
"../file_2.txt",
"../file_3.txt"
);
$message->setAttachments($attachments);
$msg_attachments = $message->getAttachments();
$this->assertEquals(count($attachments), count($msg_attachments));
for($i = 0; $i < count($attachments); $i++)
{
$this->assertEquals($attachments[$i], $msg_attachments[$i]['file']);
}
//ensure that addAttachment appends to the list of attachments
$message->addAttachment("../file_4.png");
$attachments[] = "../file_4.png";
$msg_attachments = $message->getAttachments();
$this->assertEquals($attachments[count($attachments) - 1], $msg_attachments[count($msg_attachments) - 1]['file']);
//Setting an attachment removes all other files
$message->setAttachment("only_attachment.sad");
$this->assertEquals(1, count($message->getAttachments()));
//Remove an attachment
$message->removeAttachment("only_attachment.sad");
$this->assertEquals(0, count($message->getAttachments()));
}
public function testCategoryAccessors()
{
$message = new SendGrid\Mail();
$message->setCategory('category_0');
$this->assertEquals("{\"category\":[\"category_0\"]}", $message->getHeadersJson());
$categories = array(
"category_1",
"category_2",
"category_3",
"category_4"
);
$message->setCategories($categories);
$header = $message->getHeaders();
// ensure that the array is the same
$this->assertEquals($categories, $header['category']);
// uses valid json
$this->assertEquals("{\"category\":[\"category_1\",\"category_2\",\"category_3\",\"category_4\"]}", $message->getHeadersJson());
// ensure that addCategory appends to the list of categories
$category = "category_5";
$message->addCategory($category);
$header = $message->getHeaders();
$this->assertEquals(5, count($header['category']));
$categories[] = $category;
$this->assertEquals($categories, $header['category']);
// removeCategory removes all occurrences of a category
$message->removeCategory("category_3");
$header = $message->getHeaders();
unset($categories[2]);
$categories = array_values($categories);
$this->assertEquals(4, count($header['category']));
$this->assertEquals($categories, $header['category']);
}
public function testSubstitutionAccessors()
{
$message = new SendGrid\Mail();
$substitutions = array(
"sub_1" => array("val_1.1", "val_1.2", "val_1.3"),
"sub_2" => array("val_2.1", "val_2.2"),
"sub_3" => array("val_3.1", "val_3.2", "val_3.3", "val_3.4"),
"sub_4" => array("val_4.1", "val_4.2", "val_4.3")
);
$message->setSubstitutions($substitutions);
$header = $message->getHeaders();
$this->assertEquals($substitutions, $header['sub']);
$this->assertEquals("{\"sub\":{\"sub_1\":[\"val_1.1\",\"val_1.2\",\"val_1.3\"],\"sub_2\":[\"val_2.1\",\"val_2.2\"],\"sub_3\":[\"val_3.1\",\"val_3.2\",\"val_3.3\",\"val_3.4\"],\"sub_4\":[\"val_4.1\",\"val_4.2\",\"val_4.3\"]}}", $message->getHeadersJson());
// ensure that addSubstitution appends to the list of substitutions
$sub_vals = array("val_5.1", "val_5.2", "val_5.3", "val_5.4");
$message->addSubstitution("sub_5", $sub_vals);
$substitutions["sub_5"] = $sub_vals;
$header = $message->getHeaders();
$this->assertEquals(5, count($header['sub']));
$this->assertEquals($substitutions, $header['sub']);
}
public function testSectionAccessors()
{
$message = new SendGrid\Mail();
$sections = array(
"sub_1" => array("val_1.1", "val_1.2", "val_1.3"),
"sub_2" => array("val_2.1", "val_2.2"),
"sub_3" => array("val_3.1", "val_3.2", "val_3.3", "val_3.4"),
"sub_4" => array("val_4.1", "val_4.2", "val_4.3")
);
$message->setSections($sections);
$header = $message->getHeaders();
$this->assertEquals($sections, $header['section']);
$this->assertEquals("{\"section\":{\"sub_1\":[\"val_1.1\",\"val_1.2\",\"val_1.3\"],\"sub_2\":[\"val_2.1\",\"val_2.2\"],\"sub_3\":[\"val_3.1\",\"val_3.2\",\"val_3.3\",\"val_3.4\"],\"sub_4\":[\"val_4.1\",\"val_4.2\",\"val_4.3\"]}}", $message->getHeadersJson());
// ensure that addSubstitution appends to the list of substitutions
$section_vals = array("val_5.1", "val_5.2", "val_5.3", "val_5.4");
$message->addSection("sub_5", $section_vals);
$sections["sub_5"] = $section_vals;
$header = $message->getHeaders();
$this->assertEquals(5, count($header['section']));
$this->assertEquals($sections, $header['section']);
}
public function testUniqueArgumentsAccessors()
{
$message = new SendGrid\Mail();
$unique_arguments = array(
"sub_1" => array("val_1.1", "val_1.2", "val_1.3"),
"sub_2" => array("val_2.1", "val_2.2"),
"sub_3" => array("val_3.1", "val_3.2", "val_3.3", "val_3.4"),
"sub_4" => array("val_4.1", "val_4.2", "val_4.3")
);
$message->setUniqueArguments($unique_arguments);
$header = $message->getHeaders();
$this->assertEquals($unique_arguments, $header['unique_args']);
$this->assertEquals("{\"unique_args\":{\"sub_1\":[\"val_1.1\",\"val_1.2\",\"val_1.3\"],\"sub_2\":[\"val_2.1\",\"val_2.2\"],\"sub_3\":[\"val_3.1\",\"val_3.2\",\"val_3.3\",\"val_3.4\"],\"sub_4\":[\"val_4.1\",\"val_4.2\",\"val_4.3\"]}}", $message->getHeadersJson());
// ensure that addSubstitution appends to the list of substitutions
$unique_vals = array("val_5.1", "val_5.2", "val_5.3", "val_5.4");
$message->addUniqueArgument("sub_5", $unique_vals);
$unique_arguments["sub_5"] = $unique_vals;
$header = $message->getHeaders();
$this->assertEquals(5, count($header['unique_args']));
$this->assertEquals($unique_arguments, $header['unique_args']);
}
public function testFilterSettingsAccessors()
{
$message = new SendGrid\Mail();
$filters =
array(
"filter_1" =>
array(
"settings" =>
array(
"enable" => 1,
"setting_1" => "setting_val_1"
)
),
"filter_2" =>
array(
"settings" =>
array(
"enable" => 0,
"setting_2" => "setting_val_2",
"setting_3" => "setting_val_3"
)
),
"filter_3" =>
array(
"settings" =>
array(
"enable" => 0,
"setting_4" => "setting_val_4",
"setting_5" => "setting_val_5"
)
),
);
$message->setFilterSettings($filters);
$header = $message->getHeaders();
$this->assertEquals(count($filters), count($header['filters']));
$this->assertEquals($filters, $header['filters']);
//the addFilter appends to the filter list
$message->addFilterSetting("filter_4", "enable", 0);
$message->addFilterSetting("filter_4", "setting_6", "setting_val_6");
$message->addFilterSetting("filter_4", "setting_7", "setting_val_7");
$filters["filter_4"] =
array(
"settings" =>
array(
"enable" => 0,
"setting_6" => "setting_val_6",
"setting_7" => "setting_val_7"
)
);
$header = $message->getHeaders();
$this->assertEquals($filters, $header['filters']);
}
public function testHeaderAccessors()
{
$message = new SendGrid\Mail();
$this->assertEquals("{}", $message->getHeadersJson());
$headers =
array(
"header_1" =>
array(
"item_1" => "value_1",
"item_2" => "value_2",
"item_3" => "value_3"
),
"header_2" => "value_4",
"header_3" => "value_4",
"header_4" =>
array(
"item_4" =>
array(
"sub_item_1" => "sub_value_1",
"sub_item_2" => "sub_value_2"
)
)
);
$message->setHeaders($headers);
$this->assertEquals($headers, $message->getHeaders());
$message->addHeader("simple_header", "simple_value");
$headers["simple_header"] = "simple_value";
$this->assertEquals($headers, $message->getHeaders());
$this->assertEquals("{\"header_1\":{\"item_1\":\"value_1\",\"item_2\":\"value_2\",\"item_3\":\"value_3\"},\"header_2\":\"value_4\",\"header_3\":\"value_4\",\"header_4\":{\"item_4\":{\"sub_item_1\":\"sub_value_1\",\"sub_item_2\":\"sub_value_2\"}},\"simple_header\":\"simple_value\"}", $message->getHeadersJson());
//remove a header
$message->removeHeader("simple_header");
unset($headers["simple_header"]);
$this->assertEquals($headers, $message->getHeaders());
}
public function testUseHeaders()
{
$mail = new SendGrid\Mail();
$mail->addTo('[email protected]')->
addBcc('[email protected]')->
setFrom('[email protected]')->
setSubject('Subject')->
setHtml('Hello You');
$this->assertFalse($mail->useHeaders());
$mail->removeBcc('[email protected]');
$this->assertTrue($mail->useHeaders());
$mail->addCc('[email protected]');
$this->assertFalse($mail->useHeaders());
$mail->removeCc('[email protected]')->
setRecipientsinHeader(true);
$this->assertTrue($mail->useHeaders());
$mail->setRecipientsinHeader(false);
$this->assertFalse($mail->useHeaders());
$mail->
addBcc('[email protected]')->
addAttachment('attachment.ext');
$this->assertTrue($mail->useHeaders());
}
}
| Wikia/careers-page | wp-content/plugins/sendgrid-email-delivery-simplified/lib/sendgrid-php/Test/SendGrid/MailTest.php | PHP | gpl-3.0 | 15,858 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//-----------------------------------------------------------------------------
var BUGNUMBER = 344959;
var summary = 'Functions should not lose scope chain after exception';
var actual = '';
var expect = 'with';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
var x = "global"
with ({x:"with"})
actual = (function() { try {} catch(exc) {}; return x }());
reportCompare(expect, actual, summary + ': 1');
with ({x:"with"})
actual = (function() { try { throw 1} catch(exc) {}; return x }());
reportCompare(expect, actual, summary + ': 2');
exitFunc ('test');
}
| JasonGross/mozjs | js/src/tests/js1_5/Regress/regress-344959.js | JavaScript | mpl-2.0 | 1,091 |
/*!
* Copyright 2002 - 2017 Webdetails, a Hitachi Vantara company. All rights reserved.
*
* This software was developed by Webdetails and is provided under the terms
* of the Mozilla Public License, Version 2.0, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
define([
"cdf/Dashboard.Clean",
"cdf/components/ContentListComponent"
], function(Dashboard, ContentListComponent) {
/**
* ## The Content List Component
*/
describe("The Content List Component #", function() {
var dashboard = new Dashboard();
dashboard.init();
var contentListComponent = new ContentListComponent({
name: "folderContentComponent",
type: "contentList",
listeners: [],
htmlObject: "sampleObjectContentList",
executeAtStart: true,
mode: "3"
});
dashboard.addComponent(contentListComponent);
/**
* ## The Content List Component # allows a dashboard to execute update
*/
it("allows a dashboard to execute update", function(done) {
spyOn(contentListComponent, 'update').and.callThrough();
// listen to cdf:postExecution event
contentListComponent.once("cdf:postExecution", function() {
expect(contentListComponent.update).toHaveBeenCalled();
done();
});
dashboard.update(contentListComponent);
});
});
});
| dcleao/cdf | pentaho-js/src/test/javascript/cdf/components/ContentListComponent-spec.js | JavaScript | mpl-2.0 | 1,744 |
// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------
namespace MyTodo.WebUx.Areas.HelpPage
{
using System.Web.Http;
using System.Web.Mvc;
public class HelpPageAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "HelpPage";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"HelpPage_Default",
"Help/{action}/{apiId}",
new { controller = "Help", action = "Index", apiId = UrlParameter.Optional });
HelpPageConfig.Register(GlobalConfiguration.Configuration);
}
}
} | Evilazaro/MCSDAzureTraining | Design and Implement Cloud Services/HOLs/WATK/DeployingCloudServices/Source/Ex4-SecuringAppWithSSL/End/MyTodo.WebUx/Areas/HelpPage/HelpPageAreaRegistration.cs | C# | agpl-3.0 | 1,601 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.