answer stringlengths 15 1.25M |
|---|
"""The tests for the heat control thermostat."""
import unittest
from homeassistant.bootstrap import _setup_component
from homeassistant.const import (
<API key>,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_ON,
STATE_OFF,
TEMP_CELSIUS,
)
from homeassistant.components import thermostat
from tests.common import <API key>
ENTITY = 'thermostat.test'
ENT_SENSOR = 'sensor.test'
ENT_SWITCH = 'switch.test'
MIN_TEMP = 3.0
MAX_TEMP = 65.0
TARGET_TEMP = 42.0
class <API key>(unittest.TestCase):
"""Test the Heat Control thermostat with custom config."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = <API key>()
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def <API key>(self):
"""Test set up heat_control with missing config values."""
config = {
'name': 'test',
'target_sensor': ENT_SENSOR
}
self.assertFalse(_setup_component(self.hass, 'thermostat', {
'thermostat': config}))
def test_valid_conf(self):
"""Test set up heat_control with valid config values."""
self.assertTrue(_setup_component(self.hass, 'thermostat',
{'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR}}))
def <API key>(self):
"""Test set up heat_control with sensor to trigger update at init."""
self.hass.states.set(ENT_SENSOR, 22.0, {
<API key>: TEMP_CELSIUS
})
thermostat.setup(self.hass, {'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR
}})
state = self.hass.states.get(ENTITY)
self.assertEqual(
TEMP_CELSIUS, state.attributes.get('unit_of_measurement'))
self.assertEqual(22.0, state.attributes.get('current_temperature'))
class <API key>(unittest.TestCase):
"""Test the Heat Control thermostat."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = <API key>()
self.hass.config.temperature_unit = TEMP_CELSIUS
thermostat.setup(self.hass, {'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR
}})
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def <API key>(self):
"""Test the setting of defaults to unknown."""
self.assertEqual('unknown', self.hass.states.get(ENTITY).state)
def <API key>(self):
"""Test the setup with default parameters."""
state = self.hass.states.get(ENTITY)
self.assertEqual(7, state.attributes.get('min_temp'))
self.assertEqual(35, state.attributes.get('max_temp'))
self.assertEqual(None, state.attributes.get('temperature'))
def <API key>(self):
"""Test the setup with custom parameters."""
thermostat.setup(self.hass, {'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR,
'min_temp': MIN_TEMP,
'max_temp': MAX_TEMP,
'target_temp': TARGET_TEMP
}})
state = self.hass.states.get(ENTITY)
self.assertEqual(MIN_TEMP, state.attributes.get('min_temp'))
self.assertEqual(MAX_TEMP, state.attributes.get('max_temp'))
self.assertEqual(TARGET_TEMP, state.attributes.get('temperature'))
self.assertEqual(str(TARGET_TEMP), self.hass.states.get(ENTITY).state)
def <API key>(self):
"""Test the setting of the target temperature."""
thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done()
self.assertEqual('30.0', self.hass.states.get(ENTITY).state)
def <API key>(self):
"""Test sensor that have bad unit."""
self._setup_sensor(22.0, unit='bad_unit')
self.hass.pool.block_till_done()
state = self.hass.states.get(ENTITY)
self.assertEqual(None, state.attributes.get('unit_of_measurement'))
self.assertEqual(None, state.attributes.get('current_temperature'))
def <API key>(self):
"""Test sensor that have None as state."""
self._setup_sensor(None)
self.hass.pool.block_till_done()
state = self.hass.states.get(ENTITY)
self.assertEqual(None, state.attributes.get('unit_of_measurement'))
self.assertEqual(None, state.attributes.get('current_temperature'))
def <API key>(self):
"""Test if target temperature turn heater on."""
self._setup_switch(False)
self._setup_sensor(25)
self.hass.pool.block_till_done()
thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_ON, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def <API key>(self):
"""Test if target temperature turn heater off."""
self._setup_switch(True)
self._setup_sensor(30)
self.hass.pool.block_till_done()
thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_OFF, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def <API key>(self):
"""Test if temperature change turn heater on."""
self._setup_switch(False)
thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done()
self._setup_sensor(25)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_ON, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def <API key>(self):
"""Test if temperature change turn heater off."""
self._setup_switch(True)
thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done()
self._setup_sensor(30)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_OFF, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def _setup_sensor(self, temp, unit=TEMP_CELSIUS):
"""Setup the test sensor."""
self.hass.states.set(ENT_SENSOR, temp, {
<API key>: unit
})
def _setup_switch(self, is_on):
"""Setup the test switch."""
self.hass.states.set(ENT_SWITCH, STATE_ON if is_on else STATE_OFF)
self.calls = []
def log_call(call):
"""Log service calls."""
self.calls.append(call)
self.hass.services.register('switch', SERVICE_TURN_ON, log_call)
self.hass.services.register('switch', SERVICE_TURN_OFF, log_call) |
package org.spongycastle.crypto.test;
import org.spongycastle.crypto.Digest;
import org.spongycastle.crypto.digests.SHA256Digest;
/**
* standard vector test for SHA-256 from FIPS Draft 180-2.
*
* Note, the first two vectors are _not_ from the draft, the last three are.
*/
public class SHA256DigestTest
extends DigestTest
{
private static String[] messages =
{
"",
"a",
"abc",
"<API key>"
};
private static String[] digests =
{
"<SHA256-like>",
"<SHA256-like>",
"<SHA256-like>",
"<SHA256-like>"
};
// 1 million 'a'
static private String million_a_digest = "<SHA256-like>";
SHA256DigestTest()
{
super(new SHA256Digest(), messages, digests);
}
public void performTest()
{
super.performTest();
millionATest(million_a_digest);
}
protected Digest cloneDigest(Digest digest)
{
return new SHA256Digest((SHA256Digest)digest);
}
protected Digest cloneDigest(byte[] encodedState)
{
return new SHA256Digest(encodedState);
}
public static void main(
String[] args)
{
runTest(new SHA256DigestTest());
}
} |
<?php
namespace DesignPatterns\Tests\Specification;
use DesignPatterns\Specification\PriceSpecification;
use DesignPatterns\Specification\Item;
/**
* SpecificationTest tests the specification pattern
*/
class SpecificationTest extends \<API key>
{
public function <API key>()
{
$item = new Item(100);
$spec = new PriceSpecification();
$this->assertTrue($spec->isSatisfiedBy($item));
$spec->setMaxPrice(50);
$this->assertFalse($spec->isSatisfiedBy($item));
$spec->setMaxPrice(150);
$this->assertTrue($spec->isSatisfiedBy($item));
$spec->setMinPrice(101);
$this->assertFalse($spec->isSatisfiedBy($item));
$spec->setMinPrice(100);
$this->assertTrue($spec->isSatisfiedBy($item));
}
public function <API key>()
{
$item = new Item(100);
$spec = new PriceSpecification();
$not = $spec->not();
$this->assertFalse($not->isSatisfiedBy($item));
$spec->setMaxPrice(50);
$this->assertTrue($not->isSatisfiedBy($item));
$spec->setMaxPrice(150);
$this->assertFalse($not->isSatisfiedBy($item));
$spec->setMinPrice(101);
$this->assertTrue($not->isSatisfiedBy($item));
$spec->setMinPrice(100);
$this->assertFalse($not->isSatisfiedBy($item));
}
public function <API key>()
{
$spec1 = new PriceSpecification();
$spec2 = new PriceSpecification();
$plus = $spec1->plus($spec2);
$item = new Item(100);
$this->assertTrue($plus->isSatisfiedBy($item));
$spec1->setMaxPrice(150);
$spec2->setMinPrice(50);
$this->assertTrue($plus->isSatisfiedBy($item));
$spec1->setMaxPrice(150);
$spec2->setMinPrice(101);
$this->assertFalse($plus->isSatisfiedBy($item));
$spec1->setMaxPrice(99);
$spec2->setMinPrice(50);
$this->assertFalse($plus->isSatisfiedBy($item));
}
public function <API key>()
{
$spec1 = new PriceSpecification();
$spec2 = new PriceSpecification();
$either = $spec1->either($spec2);
$item = new Item(100);
$this->assertTrue($either->isSatisfiedBy($item));
$spec1->setMaxPrice(150);
$spec2->setMaxPrice(150);
$this->assertTrue($either->isSatisfiedBy($item));
$spec1->setMaxPrice(150);
$spec2->setMaxPrice(0);
$this->assertTrue($either->isSatisfiedBy($item));
$spec1->setMaxPrice(0);
$spec2->setMaxPrice(150);
$this->assertTrue($either->isSatisfiedBy($item));
$spec1->setMaxPrice(99);
$spec2->setMaxPrice(99);
$this->assertFalse($either->isSatisfiedBy($item));
}
} |
<!DOCTYPE html>
<html>
<body>
%username% edited item at board %boardname%:<br>
%title%<br>
%description%<br>
%duedate%<br>
%assignee%<br>
%category%<br>
%points%<br>
%position%<br>
<a href="http://%hostname%/#/boards/%boardid%">Navigate to board!</a>
</body>
</html> |
/* Capstone Disassembly Engine */
/* By Nguyen Anh Quynh <aquynh@gmail.com>, 2013-2015 */
#ifdef CAPSTONE_HAS_SPARC
#include "../../utils.h"
#include "../../MCRegisterInfo.h"
#include "SparcDisassembler.h"
#include "SparcInstPrinter.h"
#include "SparcMapping.h"
static cs_err init(cs_struct *ud)
{
MCRegisterInfo *mri;
// verify if requested mode is valid
if (ud->mode & ~(CS_MODE_BIG_ENDIAN | CS_MODE_V9))
return CS_ERR_MODE;
mri = cs_mem_malloc(sizeof(*mri));
Sparc_init(mri);
ud->printer = Sparc_printInst;
ud->printer_info = mri;
ud->getinsn_info = mri;
ud->disasm = <API key>;
ud->post_printer = Sparc_post_printer;
ud->reg_name = Sparc_reg_name;
ud->insn_id = Sparc_get_insn_id;
ud->insn_name = Sparc_insn_name;
ud->group_name = Sparc_group_name;
return CS_ERR_OK;
}
static cs_err option(cs_struct *handle, cs_opt_type type, size_t value)
{
if (type == CS_OPT_SYNTAX)
handle->syntax = (int) value;
return CS_ERR_OK;
}
void Sparc_enable(void)
{
arch_init[CS_ARCH_SPARC] = init;
arch_option[CS_ARCH_SPARC] = option;
// support this arch
all_arch |= (1 << CS_ARCH_SPARC);
}
#endif |
<!DOCTYPE html>
<html class="minimal">
<title>Canvas test: 2d.pattern.paint.norepeat.outside</title>
<script src="../tests.js"></script>
<link rel="stylesheet" href="../tests.css">
<link rel="prev" href="minimal.2d.pattern.paint.norepeat.basic.html" title="2d.pattern.paint.norepeat.basic">
<link rel="next" href="minimal.2d.pattern.paint.norepeat.coord1.html" title="2d.pattern.paint.norepeat.coord1">
<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="green-100x50.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
_addTest(function(canvas, ctx) {
ctx.fillStyle = '#f00';
ctx.fillRect(0, 0, 100, 50);
var img = document.getElementById('red.png');
var pattern = ctx.createPattern(img, 'no-repeat');
ctx.fillStyle = '#0f0';
ctx.fillRect(0, 0, 100, 50);
ctx.fillStyle = pattern;
ctx.fillRect(0, -50, 100, 50);
ctx.fillRect(-100, 0, 100, 50);
ctx.fillRect(0, 50, 100, 50);
ctx.fillRect(100, 0, 100, 50);
_assertPixel(canvas, 1,1, 0,255,0,255, "1,1", "0,255,0,255");
_assertPixel(canvas, 98,1, 0,255,0,255, "98,1", "0,255,0,255");
_assertPixel(canvas, 1,48, 0,255,0,255, "1,48", "0,255,0,255");
_assertPixel(canvas, 98,48, 0,255,0,255, "98,48", "0,255,0,255");
});
</script>
<img src="../images/red.png" id="red.png" class="resource"> |
"function"==typeof jQuery&&jQuery(document).ready(function(e){function n(){!1!==s?o():t()}function o(){r=new google.maps.LatLng(s[0],s[1]),a()}function t(){var e=new google.maps.Geocoder;e.geocode({address:d},function(e,n){n==google.maps.GeocoderStatus.OK&&(r=e[0].geometry.location,a())})}function a(){var n={zoom:parseInt(<API key>.zoom),center:r,mapTypeId:google.maps.MapTypeId.ROADMAP};p.map=new google.maps.Map(i,n);var o={map:p.map,title:g,position:r};e("body").trigger("map-created.tribe",[p.map,i,n]),"undefined"!==<API key>.pin_url&&<API key>.pin_url&&(o.icon=<API key>.pin_url),new google.maps.Marker(o)}var i,r,p,d,s,g;"undefined"!=typeof <API key>&&e.each(<API key>.addresses,function(e,o){i=document.getElementById("tribe-events-gmap-"+e),null!==i&&(p="undefined"!=typeof o?o:{},d="undefined"!=typeof o.address&&o.address,s="undefined"!=typeof o.coords&&o.coords,g=o.title,n())})}); |
angular.module('merchello.plugins.braintree').controller('Merchello.Plugins.GatewayProviders.Dialogs.<API key>',
['$scope', '<API key>',
function($scope, <API key>) {
$scope.providerSettings = {};
function init() {
var json = JSON.parse($scope.dialogData.provider.extendedData.getValue('<API key>'));
$scope.providerSettings = <API key>.transform(json);
$scope.$watch(function () {
return $scope.providerSettings;
}, function (newValue, oldValue) {
$scope.dialogData.provider.extendedData.setValue('<API key>', angular.toJson(newValue));
}, true);
}
// initialize the controller
init();
}]); |
// object code form for any purpose and without fee is hereby granted,
// restricted rights notice below appear in all supporting
// documentation.
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// (Rights in Technical Data and Computer Software), as applicable.
// DESCRIPTION:
// Source file for the ObjectARX application command "BRBBLOCK".
#include "brsample_pch.h" //precompiled header
//This is been defined for future use. all headers should be under this guard.
// include here
void
dumpBblock()
{
AcBr::ErrorStatus returnValue = AcBr::eOk;
// Select the entity by type
AcBrEntity* pEnt = NULL;
AcDb::SubentType subType = AcDb::kNullSubentType;
returnValue = selectEntityByType(pEnt, subType);
if (returnValue != AcBr::eOk) {
acutPrintf(ACRX_T("\n Error in selectEntityByType:"));
errorReport(returnValue);
delete pEnt;
return;
}
AcGeBoundBlock3d bblock;
returnValue = pEnt->getBoundBlock(bblock);
if (returnValue != AcBr::eOk) {
acutPrintf(ACRX_T("\n Error in AcBrEntity::getBoundBlock:"));
errorReport(returnValue);
delete pEnt;
return;
}
delete pEnt;
AcGePoint3d min, max;
bblock.getMinMaxPoints(min, max);
bblockReport(min, max);
return;
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="generator" content="JsDoc Toolkit" />
<title>JsDoc Reference - _global_</title>
<link rel="stylesheet" href="../static/default.css" type="text/css" media="screen" charset="utf-8" />
</head>
<body>
<!-- begin static/header.html -->
<div id="header">
</div>
<!-- end static/header.html -->
<div id="index">
<div id="docs">
</div>
<h2>Index</h2>
<ul class="classList">
<li><a href="../files.html">File Index</a></li>
<li><a href="../index.html">Class Index</a></li>
<li><a href="../symbolindex.html">Symbol Index</a></li>
</ul>
<h2>Classes</h2>
<ul class="classList">
<li><i><a href="../symbols/_global_.html">_global_</a></i></li>
<li><a href="../symbols/hasher.html">hasher</a></li>
</ul>
</div>
<div id="symbolList">
<!-- constructor list -->
<!-- end constructor list -->
<!-- properties list -->
<!-- end properties list -->
<!-- function summary -->
<!-- end function summary -->
<!-- events summary -->
<!-- end events summary -->
</div>
<div id="content">
<h1 class="classTitle">
Built-In Namespace _global_
</h1>
<p class="description">
</p>
<hr />
</div>
<div class="fineprint" style="clear:both;text-align:center">
Documentation generated by <a href="http://code.google.com/p/jsdoc-toolkit/" target="_blankt">JsDoc Toolkit</a> 2.4.0 on Mon Nov 11 2013 15:19:04 GMT-0200 (BRST)
| template based on Steffen Siering <a href="http://github.com/urso/jsdoc-simple">jsdoc-simple</a>.
</div>
</body>
</html> |
using ArmyOfCreatures.Logic.Creatures;
namespace ArmyOfCreatures.Logic
{
public interface ICreaturesFactory
{
Creature CreateCreature(string name);
}
} |
using namespace System;
using namespace NETGeographicLib;
int main(array<System::String ^> ^/*args*/)
{
try {
Geodesic^ geod = gcnew Geodesic(); // WGS84
const double lat0 = 48 + 50/60.0, lon0 = 2 + 20/60.0; // Paris
Gnomonic^ proj = gcnew Gnomonic(geod);
{
// Sample forward calculation
double lat = 50.9, lon = 1.8; // Calais
double x, y;
proj->Forward(lat0, lon0, lat, lon, x, y);
Console::WriteLine(String::Format("X: {0} Y: {1}", x, y));
}
{
// Sample reverse calculation
double x = -38e3, y = 230e3;
double lat, lon;
proj->Reverse(lat0, lon0, x, y, lat, lon);
Console::WriteLine(String::Format("Latitude: {0} Longitude: {1}", lat, lon));
}
}
catch (GeographicErr^ e) {
Console::WriteLine(String::Format("Caught exception: {0}", e->Message));
return -1;
}
return 0;
} |
(function () {
'use strict';
function <API key>($rootScope, $scope, $routeParams, $q, $timeout, $window, $location, appState, contentResource, entityResource, navigationService, <API key>, angularHelper, <API key>, <API key>, treeService, fileManager, formHelper, umbRequestHelper, keyboardService, umbModelMapper, editorState, $http, eventsService, relationResource) {
var evts = [];
//setup scope vars
$scope.defaultButton = null;
$scope.subButtons = [];
$scope.page = {};
$scope.page.loading = false;
$scope.page.menu = {};
$scope.page.menu.currentNode = null;
$scope.page.menu.currentSection = appState.getSectionState("currentSection");
$scope.page.listViewPath = null;
$scope.page.isNew = $scope.isNew ? true : false;
$scope.page.buttonGroupState = "init";
$scope.allowOpen = true;
function init(content) {
createButtons(content);
editorState.set($scope.content);
//We fetch all ancestors of the node to generate the footer breadcrumb navigation
if (!$scope.page.isNew) {
if (content.parentId && content.parentId !== -1) {
entityResource.getAncestors(content.id, "document")
.then(function (anc) {
$scope.ancestors = anc;
});
}
}
evts.push(eventsService.on("editors.content.changePublishDate", function (event, args) {
createButtons(args.node);
}));
evts.push(eventsService.on("editors.content.changeUnpublishDate", function (event, args) {
createButtons(args.node);
}));
// We don't get the info tab from the server from version 7.8 so we need to manually add it
<API key>.addInfoTab($scope.content.tabs);
}
function getNode() {
$scope.page.loading = true;
//we are editing so get the content item from the server
$scope.getMethod()($scope.contentId)
.then(function (data) {
$scope.content = data;
if (data.isChildOfListView && data.trashed === false) {
$scope.page.listViewPath = ($routeParams.page) ?
"/content/content/edit/" + data.parentId + "?page=" + $routeParams.page :
"/content/content/edit/" + data.parentId;
}
init($scope.content);
//in one particular special case, after we've created a new item we redirect back to the edit
// route but there might be server validation errors in the collection which we need to display
// after the redirect, so we will bind all subscriptions which will show the server validation errors
// if there are any and then clear them so the collection no longer persists them.
<API key>.<API key>();
syncTreeNode($scope.content, data.path, true);
<API key>($scope.content);
eventsService.emit("content.loaded", { content: $scope.content });
$scope.page.loading = false;
});
}
function createButtons(content) {
$scope.page.buttonGroupState = "init";
var buttons = <API key>.<API key>({
create: $scope.page.isNew,
content: content,
methods: {
saveAndPublish: $scope.saveAndPublish,
sendToPublish: $scope.sendToPublish,
save: $scope.save,
unPublish: $scope.unPublish
}
});
$scope.defaultButton = buttons.defaultButton;
$scope.subButtons = buttons.subButtons;
}
/** Syncs the content item to it's tree node - this occurs on first load and after saving */
function syncTreeNode(content, path, initialLoad) {
if (!$scope.content.isChildOfListView) {
navigationService.syncTree({ tree: $scope.treeAlias, path: path.split(","), forceReload: initialLoad !== true }).then(function (syncArgs) {
$scope.page.menu.currentNode = syncArgs.node;
});
}
else if (initialLoad === true) {
//it's a child item, just sync the ui node to the parent
navigationService.syncTree({ tree: $scope.treeAlias, path: path.substring(0, path.lastIndexOf(",")).split(","), forceReload: initialLoad !== true });
//if this is a child of a list view and it's the initial load of the editor, we need to get the tree node
// from the server so that we can load in the actions menu.
umbRequestHelper.resourcePromise(
$http.get(content.treeNodeUrl),
'Failed to retrieve data for child node ' + content.id).then(function (node) {
$scope.page.menu.currentNode = node;
});
}
}
// This is a helper method to reduce the amount of code repitition for actions: Save, Publish, SendToPublish
function performSave(args) {
var deferred = $q.defer();
$scope.page.buttonGroupState = "busy";
eventsService.emit("content.saving", { content: $scope.content, action: args.action });
<API key>.<API key>({
statusMessage: args.statusMessage,
saveMethod: args.saveMethod,
scope: $scope,
content: $scope.content,
action: args.action
}).then(function (data) {
//success
init($scope.content);
syncTreeNode($scope.content, data.path);
$scope.page.buttonGroupState = "success";
deferred.resolve(data);
eventsService.emit("content.saved", { content: $scope.content, action: args.action });
}, function (err) {
//error
if (err) {
editorState.set($scope.content);
}
$scope.page.buttonGroupState = "error";
deferred.reject(err);
});
return deferred.promise;
}
function <API key>(content) {
// We're using rootScope to store the page number for list views, so if returning to the list
// we can restore the page. If we've moved on to edit a piece of content that's not the list or it's children
// we should remove this so as not to confuse if navigating to a different list
if (!content.isChildOfListView && !content.isContainer) {
$rootScope.<API key> = null;
}
}
if ($scope.page.isNew) {
$scope.page.loading = true;
//we are creating so get an empty content item
$scope.getScaffoldMethod()()
.then(function (data) {
$scope.content = data;
init($scope.content);
<API key>($scope.content);
$scope.page.loading = false;
eventsService.emit("content.newReady", { content: $scope.content });
});
}
else {
getNode();
}
$scope.unPublish = function () {
// raising the event triggers the confirmation dialog
if (!<API key>.hasView()) {
<API key>.add({ view: "confirmunpublish" });
}
$scope.page.buttonGroupState = "busy";
// actioning the dialog raises the confirmUnpublish event, act on it here
var actioned = $rootScope.$on("content.confirmUnpublish", function(event, confirmed) {
if (confirmed && formHelper.submitForm({ scope: $scope, statusMessage: "Unpublishing...", skipValidation: true })) {
eventsService.emit("content.unpublishing", { content: $scope.content });
contentResource.unPublish($scope.content.id)
.then(function (data) {
formHelper.resetForm({ scope: $scope, notifications: data.notifications });
<API key>.<API key>({
scope: $scope,
savedContent: data,
rebindCallback: <API key>.<API key>($scope.content, data)
});
init($scope.content);
syncTreeNode($scope.content, data.path);
$scope.page.buttonGroupState = "success";
eventsService.emit("content.unpublished", { content: $scope.content });
}, function(err) {
formHelper.showNotifications(err.data);
$scope.page.buttonGroupState = 'error';
});
} else {
$scope.page.buttonGroupState = "init";
}
// unsubscribe to avoid queueing notifications
// listener is re-bound when the unpublish button is clicked so it is created just-in-time
actioned();
});
};
$scope.sendToPublish = function () {
return performSave({ saveMethod: contentResource.sendToPublish, statusMessage: "Sending...", action: "sendToPublish" });
};
$scope.saveAndPublish = function () {
return performSave({ saveMethod: contentResource.publish, statusMessage: "Publishing...", action: "publish" });
};
$scope.save = function () {
return performSave({ saveMethod: $scope.saveMethod(), statusMessage: "Saving...", action: "save" });
};
$scope.preview = function (content) {
if (!$scope.busy) {
// Chromes popup blocker will kick in if a window is opened
// without the initial scoped request. This trick will fix that.
var previewWindow = $window.open('preview/?init=true&id=' + content.id, 'umbpreview');
// Build the correct path so both /#/ and #/ work.
var redirect = Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath + '/preview/?id=' + content.id;
//The user cannot save if they don't have access to do that, in which case we just want to preview
//and that's it otherwise they'll get an unauthorized access message
if (!_.contains(content.allowedActions, "A")) {
previewWindow.location.href = redirect;
}
else {
$scope.save().then(function (data) {
previewWindow.location.href = redirect;
});
}
}
};
$scope.restore = function (content) {
$scope.page.buttonRestore = "busy";
relationResource.getByChildId(content.id, "<API key>").then(function (data) {
var relation = null;
var target = null;
var error = { headline: "Cannot automatically restore this item", content: "Use the Move menu item to move it manually"};
if (data.length == 0) {
<API key>.error(error.headline, "There is no 'restore' relation found for this node. Use the Move menu item to move it manually.");
$scope.page.buttonRestore = "error";
return;
}
relation = data[0];
if (relation.parentId == -1) {
target = { id: -1, name: "Root" };
moveNode(content, target);
} else {
contentResource.getById(relation.parentId).then(function (data) {
target = data;
// make sure the target item isn't in the recycle bin
if(target.path.indexOf("-20") !== -1) {
<API key>.error(error.headline, "The item you want to restore it under (" + target.name + ") is in the recycle bin. Use the Move menu item to move the item manually.");
$scope.page.buttonRestore = "error";
return;
}
moveNode(content, target);
}, function (err) {
$scope.page.buttonRestore = "error";
<API key>.error(error.headline, error.content);
});
}
}, function (err) {
$scope.page.buttonRestore = "error";
<API key>.error(error.headline, error.content);
});
};
function moveNode(node, target) {
contentResource.move({ "parentId": target.id, "id": node.id })
.then(function (path) {
// remove the node that we're working on
if($scope.page.menu.currentNode) {
treeService.removeNode($scope.page.menu.currentNode);
}
// sync the destination node
navigationService.syncTree({ tree: "content", path: path, forceReload: true, activate: false });
$scope.page.buttonRestore = "success";
<API key>.success("Successfully restored " + node.name + " to " + target.name);
// reload the node
getNode();
}, function (err) {
$scope.page.buttonRestore = "error";
<API key>.error("Cannot automatically restore this item", err);
});
}
//ensure to unregister from all events!
$scope.$on('$destroy', function () {
for (var e in evts) {
eventsService.unsubscribe(evts[e]);
}
});
}
function createDirective() {
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/content/edit.html',
controller: 'Umbraco.Editors.Content.<API key>',
scope: {
contentId: "=",
isNew: "=?",
treeAlias: "@",
page: "=?",
saveMethod: "&",
getMethod: "&",
getScaffoldMethod: "&?"
}
};
return directive;
}
angular.module('umbraco.directives').controller('Umbraco.Editors.Content.<API key>', <API key>);
angular.module('umbraco.directives').directive('contentEditor', createDirective);
})(); |
<?php
defined('C5_EXECUTE') or die("Access Denied.");
Loader::controller('/profile/edit');
Loader::model('<API key>');
class <API key> extends <API key> {
public function __construct() {
parent::__construct();
}
public function on_start() {
parent::on_start();
$this->error = Loader::helper('validation/error');
$this->set('vt', Loader::helper('validation/token'));
$this->set('text', Loader::helper('text'));
}
public function view() {
$u = new User();
$ui = UserInfo::getByID($u->getUserID());
$inbox = <API key>::get($ui, <API key>::MBTYPE_INBOX);
$sent = <API key>::get($ui, <API key>::MBTYPE_SENT);
$this->set('inbox', $inbox);
$this->set('sent', $sent);
}
protected function validateUser($uID) {
if ($uID > 0) {
$ui = UserInfo::getByID($uID);
if ((is_object($ui)) && ($ui->getAttribute('<API key>') == 1)) {
$this->set('recipient', $ui);
return true;
}
}
$this->redirect('/profile');
}
protected function getMessageMailboxID($box) {
$msgMailboxID = 0;
switch($box) {
case 'inbox':
$msgMailboxID = <API key>::MBTYPE_INBOX;
break;
case 'sent':
$msgMailboxID = <API key>::MBTYPE_SENT;
break;
default:
$msgMailboxID = $box;
break;
}
return $msgMailboxID;
}
public function view_mailbox($box) {
$msgMailboxID = $this->getMessageMailboxID($box);
$u = new User();
$ui = UserInfo::getByID($u->getUserID());
$mailbox = <API key>::get($ui, $msgMailboxID);
if (is_object($mailbox)) {
$messageList = $mailbox->getMessageList();
$messages = $messageList->getPage();
$this->set('messages', $messages);
$this->set('messageList', $messageList);
}
// also, we have to mark all messages in this mailbox as no longer "new"
$mailbox->removeNewStatus();
$this->set('mailbox', $box);
}
public function view_message($box, $msgID) {
$msgMailboxID = $this->getMessageMailboxID($box);
$u = new User();
$ui = UserInfo::getByID($u->getUserID());
$mailbox = <API key>::get($ui, $msgMailboxID);
$msg = UserPrivateMessage::getByID($msgID, $mailbox);
if ($ui-><API key>($msg)) {
$msg->markAsRead();
$this->set('subject', $msg-><API key>());
$this->set('msgContent', $msg->getMessageBody());
$this->set('dateAdded', $msg->getMessageDateAdded('user', t('F d, Y \a\t g:i A')));
$this->set('author', $msg-><API key>());
$this->set('msg', $msg);
$this->set('box', $box);
$this->set('backURL', View::url('/profile/messages', 'view_mailbox', $box));
$valt = Loader::helper('validation/token');
$token = $valt->generate('delete_message_' . $msgID);
$this->set('deleteURL', View::url('/profile/messages', 'delete_message', $box, $msgID, $token));
}
}
public function delete_message($box, $msgID, $token) {
$valt = Loader::helper('validation/token');
if (!$valt->validate('delete_message_' . $msgID, $token)) {
$this->error->add($valt->getErrorMessage());
}
$msgMailboxID = $this->getMessageMailboxID($box);
$u = new User();
$ui = UserInfo::getByID($u->getUserID());
$mailbox = <API key>::get($ui, $msgMailboxID);
$msg = UserPrivateMessage::getByID($msgID, $mailbox);
if ($ui-><API key>($msg) && (!$this->error->has())) {
$msg->delete();
$this->redirect('/profile/messages', 'view_mailbox', $box);
}
print $this->view();
}
public function write($uID) {
$this->validateUser($uID);
$this->set('backURL', View::url('/profile', 'view', $uID));
}
public function reply($boxID, $msgID) {
$msg = UserPrivateMessage::getByID($msgID);
$uID = $msg-><API key>();
$this->validateUser($uID);
$this->set('backURL', View::url('/profile/messages', 'view_message', $boxID, $msgID));
$this->set('msgID', $msgID);
$this->set('box', $boxID);
$this->set('msg', $msg);
$this->set('msgSubject', $msg-><API key>());
$body = "\n\n\n" . $msg->getMessageDelimiter() . "\n";
$body .= t("From: %s\nDate Sent: %s\nSubject: %s", $msg-><API key>(), $msg->getMessageDateAdded('user', t('F d, Y \a\t g:i A')), $msg-><API key>());
$body .= "\n\n" . $msg->getMessageBody();
$this->set('msgBody', $body);
}
public function send() {
$uID = $this->post('uID');
if ($this->post('msgID') > 0) {
$msgID = $this->post('msgID');
$box = $this->post('box');
$this->reply($box, $msgID);
} else {
$this->write($uID);
}
$vf = Loader::helper('validation/form');
$vf->setData($this->post());
$vf->addRequired('msgBody', t("You haven't written a message!"));
$vf->addRequiredToken("<API key>");
if ($vf->test()) {
$u = new User();
$sender = UserInfo::getByID($u->getUserID());
$r = $sender->sendPrivateMessage($this->get('recipient'), $this->post('msgSubject'), $this->post('msgBody'), $this->get('msg'));
if ($r instanceof <API key>) {
$this->error = $r;
} else {
if ($this->post('msgID') > 0) {
$this->redirect('/profile/messages', 'reply_complete', $box, $msgID);
} else {
$this->redirect('/profile/messages', 'send_complete', $uID);
}
}
} else {
$this->error = $vf->getError();
}
}
public function send_complete($uID) {
$this->validateUser($uID);
}
public function reply_complete($box, $msgID) {
$this->reply($box, $msgID);
}
public function on_before_render() {
$this->set('error', $this->error);
}
} |
#!/usr/bin/python
# coding=utf-8
from test import CollectorTestCase
from test import <API key>
from test import unittest
from mock import Mock
from mock import patch
try:
from cStringIO import StringIO
StringIO # workaround for pyflakes issue #13
except ImportError:
from StringIO import StringIO
from diamond.collector import Collector
from filestat import FilestatCollector
class <API key>(CollectorTestCase):
def setUp(self):
config = <API key>('FilestatCollector', {
'interval': 10
})
self.collector = FilestatCollector(config, None)
def test_import(self):
self.assertTrue(FilestatCollector)
@patch('__builtin__.open')
@patch('os.access', Mock(return_value=True))
@patch.object(Collector, 'publish')
def <API key>(self, publish_mock, open_mock):
open_mock.return_value = StringIO('')
self.collector.collect()
open_mock.<API key>('/proc/sys/fs/file-nr')
@patch.object(Collector, 'publish')
def <API key>(self, publish_mock):
FilestatCollector.PROC = self.getFixturePath('proc_sys_fs_file-nr')
self.collector.collect()
metrics = {
'assigned': 576,
'unused': 0,
'max': 4835852
}
self.setDocExample(collector=self.collector.__class__.__name__,
metrics=metrics,
defaultpath=self.collector.config['path'])
self.assertPublishedMany(publish_mock, metrics)
if __name__ == "__main__":
unittest.main() |
var tns = (function (){
// keys
if (!Object.keys) {
Object.keys = function (object) {
var keys = [];
for (var name in object) {
if (Object.prototype.hasOwnProperty.call(object, name)) {
keys.push(name);
}
}
return keys;
};
}
// ChildNode.remove
(function () {
"use strict";
if(!("remove" in Element.prototype)){
Element.prototype.remove = function(){
if(this.parentNode) {
this.parentNode.removeChild(this);
}
};
}
})();
var win = window;
var raf = win.<API key>
|| win.<API key>
|| win.<API key>
|| win.<API key>
|| function(cb) { return setTimeout(cb, 16); };
var win$1 = window;
var caf = win$1.<API key>
|| win$1.<API key>
|| function(id){ clearTimeout(id); };
function extend() {
var obj, name, copy,
target = arguments[0] || {},
i = 1,
length = arguments.length;
for (; i < length; i++) {
if ((obj = arguments[i]) !== null) {
for (name in obj) {
copy = obj[name];
if (target === copy) {
continue;
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
}
function checkStorageValue (value) {
return ['true', 'false'].indexOf(value) >= 0 ? JSON.parse(value) : value;
}
function setLocalStorage(key, value) {
localStorage.setItem(key, value);
return value;
}
function getSlideId() {
var id = window.tnsId;
window.tnsId = !id ? 1 : id + 1;
return 'tns' + window.tnsId;
}
function getBody () {
var doc = document,
body = doc.body;
if (!body) {
body = doc.createElement('body');
body.fake = true;
}
return body;
}
var docElement = document.documentElement;
function setFakeBody (body) {
var docOverflow = '';
if (body.fake) {
docOverflow = docElement.style.overflow;
//avoid crashing IE8, if background image is used
body.style.background = '';
//Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
body.style.overflow = docElement.style.overflow = 'hidden';
docElement.appendChild(body);
}
return docOverflow;
}
function resetFakeBody (body, docOverflow) {
if (body.fake) {
body.remove();
docElement.style.overflow = docOverflow;
// Trigger layout so kinetic scrolling isn't disabled in iOS6+
// <API key>
docElement.offsetHeight;
}
}
// get css-calc
function calc() {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
div = doc.createElement('div'),
result = false;
body.appendChild(div);
try {
var vals = ['calc(10px)', '-moz-calc(10px)', '-webkit-calc(10px)'], val;
for (var i = 0; i < 3; i++) {
val = vals[i];
div.style.width = val;
if (div.offsetWidth === 10) {
result = val.replace('(10px)', '');
break;
}
}
} catch (e) {}
body.fake ? resetFakeBody(body, docOverflow) : div.remove();
return result;
}
// get subpixel support value
function subpixelLayout() {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
parent = doc.createElement('div'),
child1 = doc.createElement('div'),
child2,
supported;
parent.style.cssText = 'width: 10px';
child1.style.cssText = 'float: left; width: 5.5px; height: 10px;';
child2 = child1.cloneNode(true);
parent.appendChild(child1);
parent.appendChild(child2);
body.appendChild(parent);
supported = child1.offsetTop !== child2.offsetTop;
body.fake ? resetFakeBody(body, docOverflow) : parent.remove();
return supported;
}
function mediaquerySupport () {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
div = doc.createElement('div'),
style = doc.createElement('style'),
rule = '@media all and (min-width:1px){.tns-mq-test{position:absolute}}',
position;
style.type = 'text/css';
div.className = 'tns-mq-test';
body.appendChild(style);
body.appendChild(div);
if (style.styleSheet) {
style.styleSheet.cssText = rule;
} else {
style.appendChild(doc.createTextNode(rule));
}
position = window.getComputedStyle ? window.getComputedStyle(div).position : div.currentStyle['position'];
body.fake ? resetFakeBody(body, docOverflow) : div.remove();
return position === "absolute";
}
// create and append style sheet
function createStyleSheet (media) {
// Create the <style> tag
var style = document.createElement("style");
// style.setAttribute("type", "text/css");
// Add a media (and/or media query) here if you'd like!
// style.setAttribute("media", "screen")
// style.setAttribute("media", "only screen and (max-width : 1024px)")
if (media) { style.setAttribute("media", media); }
// WebKit hack :(
// style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.querySelector('head').appendChild(style);
return style.sheet ? style.sheet : style.styleSheet;
}
// cross browsers addRule method
function addCSSRule(sheet, selector, rules, index) {
// return raf(function() {
'insertRule' in sheet ?
sheet.insertRule(selector + '{' + rules + '}', index) :
sheet.addRule(selector, rules, index);
}
function getCssRulesLength(sheet) {
var rule = ('insertRule' in sheet) ? sheet.cssRules : sheet.rules;
return rule.length;
}
function toDegree (y, x) {
return Math.atan2(y, x) * (180 / Math.PI);
}
function getTouchDirection(angle, range) {
var direction = false,
gap = Math.abs(90 - Math.abs(angle));
if (gap >= 90 - range) {
direction = 'horizontal';
} else if (gap <= range) {
direction = 'vertical';
}
return direction;
}
function forEachNodeList (arr, callback, scope) {
for (var i = 0, l = arr.length; i < l; i++) {
callback.call(scope, arr[i], i);
}
}
var classListSupport = 'classList' in document.createElement('_');
var hasClass = classListSupport ?
function (el, str) { return el.classList.contains(str); } :
function (el, str) { return el.className.indexOf(str) >= 0; };
var addClass = classListSupport ?
function (el, str) {
if (!hasClass(el, str)) { el.classList.add(str); }
} :
function (el, str) {
if (!hasClass(el, str)) { el.className += ' ' + str; }
};
var removeClass = classListSupport ?
function (el, str) {
if (hasClass(el, str)) { el.classList.remove(str); }
} :
function (el, str) {
if (hasClass(el, str)) { el.className = el.className.replace(str, ''); }
};
function hasAttr(el, attr) {
return el.hasAttribute(attr);
}
function getAttr(el, attr) {
return el.getAttribute(attr);
}
function isNodeList(el) {
// Only NodeList has the "item()" function
return typeof el.item !== "undefined";
}
function setAttrs(els, attrs) {
els = (isNodeList(els) || els instanceof Array) ? els : [els];
if (Object.prototype.toString.call(attrs) !== '[object Object]') { return; }
for (var i = els.length; i
for(var key in attrs) {
els[i].setAttribute(key, attrs[key]);
}
}
}
function removeAttrs(els, attrs) {
els = (isNodeList(els) || els instanceof Array) ? els : [els];
attrs = (attrs instanceof Array) ? attrs : [attrs];
var attrLength = attrs.length;
for (var i = els.length; i
for (var j = attrLength; j
els[i].removeAttribute(attrs[j]);
}
}
}
function removeElementStyles(el) {
el.style.cssText = '';
}
function arrayFromNodeList (nl) {
var arr = [];
for (var i = 0, l = nl.length; i < l; i++) {
arr.push(nl[i]);
}
return arr;
}
function hideElement(el) {
if (!hasAttr(el, 'hidden')) {
setAttrs(el, {'hidden': ''});
}
}
function showElement(el) {
if (hasAttr(el, 'hidden')) {
removeAttrs(el, 'hidden');
}
}
function isVisible(el) {
return el.offsetWidth > 0 && el.offsetHeight > 0;
}
function whichProperty(props){
if (typeof props === 'string') {
var arr = [props],
Props = props.charAt(0).toUpperCase() + props.substr(1),
prefixes = ['Webkit', 'Moz', 'ms', 'O'];
prefixes.forEach(function(prefix) {
if (prefix !== 'ms' || props === 'transform') {
arr.push(prefix + Props);
}
});
props = arr;
}
var el = document.createElement('fakeelement'),
len = props.length;
for(var i = 0; i < props.length; i++){
var prop = props[i];
if( el.style[prop] !== undefined ){ return prop; }
}
return false; // explicit for ie9-
}
function has3D(tf){
if (!window.getComputedStyle) { return false; }
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
el = doc.createElement('p'),
has3d,
cssTF = tf.length > 9 ? '-' + tf.slice(0, -9).toLowerCase() + '-' : '';
cssTF += 'transform';
// Add it to the body to get the computed style
body.insertBefore(el, null);
el.style[tf] = 'translate3d(1px,1px,1px)';
has3d = window.getComputedStyle(el).getPropertyValue(cssTF);
body.fake ? resetFakeBody(body, docOverflow) : el.remove();
return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}
// get transitionend, animationend based on transitionDuration
// @propin: string
// @propOut: string, first-letter uppercase
// Usage: getEndProperty('<API key>', 'Transition') => webkitTransitionEnd
function getEndProperty(propIn, propOut) {
var endProp = false;
if (/^Webkit/.test(propIn)) {
endProp = 'webkit' + propOut + 'End';
} else if (/^O/.test(propIn)) {
endProp = 'o' + propOut + 'End';
} else if (propIn) {
endProp = propOut.toLowerCase() + 'end';
}
return endProp;
}
// Test via a getter in the options object to see if the passive property is accessed
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supportsPassive = true;
}
});
window.addEventListener("test", null, opts);
} catch (e) {}
var passiveOption = supportsPassive ? { passive: true } : false;
function addEvents(el, obj) {
for (var prop in obj) {
var option = (prop === 'touchstart' || prop === 'touchmove') ? passiveOption : false;
el.addEventListener(prop, obj[prop], option);
}
}
function removeEvents(el, obj) {
for (var prop in obj) {
var option = ['touchstart', 'touchmove'].indexOf(prop) >= 0 ? passiveOption : false;
el.removeEventListener(prop, obj[prop], option);
}
}
function Events() {
return {
topics: {},
on: function (eventName, fn) {
this.topics[eventName] = this.topics[eventName] || [];
this.topics[eventName].push(fn);
},
off: function(eventName, fn) {
if (this.topics[eventName]) {
for (var i = 0; i < this.topics[eventName].length; i++) {
if (this.topics[eventName][i] === fn) {
this.topics[eventName].splice(i, 1);
break;
}
}
}
},
emit: function (eventName, data) {
if (this.topics[eventName]) {
this.topics[eventName].forEach(function(fn) {
fn(data);
});
}
}
};
}
function jsTransform(element, attr, prefix, postfix, to, duration, callback) {
var tick = Math.min(duration, 10),
unit = (to.indexOf('%') >= 0) ? '%' : 'px',
to = to.replace(unit, ''),
from = Number(element.style[attr].replace(prefix, '').replace(postfix, '').replace(unit, '')),
positionTick = (to - from) / duration * tick,
running;
setTimeout(moveElement, tick);
function moveElement() {
duration -= tick;
from += positionTick;
element.style[attr] = prefix + from + unit + postfix;
if (duration > 0) {
setTimeout(moveElement, tick);
} else {
callback();
}
}
}
// Format: IIFE
var tns = function(options) {
options = extend({
container: '.slider',
mode: 'carousel',
axis: 'horizontal',
items: 1,
gutter: 0,
edgePadding: 0,
fixedWidth: false,
<API key>: false,
slideBy: 1,
controls: true,
controlsText: ['prev', 'next'],
controlsContainer: false,
prevButton: false,
nextButton: false,
nav: true,
navContainer: false,
navAsThumbnails: false,
arrowKeys: false,
speed: 300,
autoplay: false,
autoplayTimeout: 5000,
autoplayDirection: 'forward',
autoplayText: ['start', 'stop'],
autoplayHoverPause: false,
autoplayButton: false,
<API key>: true,
<API key>: true,
// animateIn: 'tns-fadeIn',
// animateOut: 'tns-fadeOut',
// animateNormal: 'tns-normal',
// animateDelay: false,
loop: true,
rewind: false,
autoHeight: false,
responsive: false,
lazyload: false,
touch: true,
mouseDrag: false,
swipeAngle: 15,
nested: false,
freezable: true,
// startIndex: 0,
onInit: false,
useLocalStorage: true
}, options || {});
var doc = document,
win = window,
KEYS = {
ENTER: 13,
SPACE: 32,
PAGEUP: 33,
PAGEDOWN: 34,
END: 35,
HOME: 36,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
},
CALC,
SUBPIXEL,
CSSMQ,
TRANSFORM,
HAS3D,
TRANSITIONDURATION,
TRANSITIONDELAY,
ANIMATIONDURATION,
ANIMATIONDELAY,
TRANSITIONEND,
ANIMATIONEND,
localStorageAccess = true;
if (options.useLocalStorage) {
// check browser version and local storage
// if browser upgraded,
// 1. delete browser ralated data from local storage and
// 2. recheck these options and save them to local storage
var browserInfo = navigator.userAgent,
tnsStorage = {};
// tC => calc
// tSP => subpixel
// tMQ => mediaquery
// tTf => transform
// tTDu => transitionDuration
// tTDe => transitionDelay
// tADu => animationDuration
// tADe => animationDelay
// tTE => transitionEnd
// tAE => animationEnd
try {
tnsStorage = localStorage;
// remove storage when browser version changes
if (tnsStorage['tnsApp'] && tnsStorage['tnsApp'] !== browserInfo) {
['tC', 'tSP', 'tMQ', 'tTf', 't3D', 'tTDu', 'tTDe', 'tADu', 'tADe', 'tTE', 'tAE'].forEach(function(item) { tnsStorage.removeItem(item); });
}
// update browserInfo
tnsStorage['tnsApp'] = browserInfo;
} catch(e) {
localStorageAccess = false;
}
// reset tnsStorage when localStorage is null (on some versions of Chrome Mobile #134)
if (!localStorage) {
tnsStorage = {};
localStorageAccess = false;
}
// get browser related data from local storage if they exist
// otherwise, run the functions again and save these data to local storage
// checkStorageValue() convert non-string value to its original value: 'true' > true
if (localStorageAccess) {
if (tnsStorage['tC']) {
CALC = checkStorageValue(tnsStorage['tC']);
SUBPIXEL = checkStorageValue(tnsStorage['tSP']);
CSSMQ = checkStorageValue(tnsStorage['tMQ']);
TRANSFORM = checkStorageValue(tnsStorage['tTf']);
HAS3D = checkStorageValue(tnsStorage['t3D']);
TRANSITIONDURATION = checkStorageValue(tnsStorage['tTDu']);
TRANSITIONDELAY = checkStorageValue(tnsStorage['tTDe']);
ANIMATIONDURATION = checkStorageValue(tnsStorage['tADu']);
ANIMATIONDELAY = checkStorageValue(tnsStorage['tADe']);
TRANSITIONEND = checkStorageValue(tnsStorage['tTE']);
ANIMATIONEND = checkStorageValue(tnsStorage['tAE']);
} else {
CALC = setLocalStorage('tC', calc());
SUBPIXEL = setLocalStorage('tSP', subpixelLayout());
CSSMQ = setLocalStorage('tMQ', mediaquerySupport());
TRANSFORM = setLocalStorage('tTf', whichProperty('transform'));
HAS3D = setLocalStorage('t3D', has3D(TRANSFORM));
TRANSITIONDURATION = setLocalStorage('tTDu', whichProperty('transitionDuration'));
TRANSITIONDELAY = setLocalStorage('tTDe', whichProperty('transitionDelay'));
ANIMATIONDURATION = setLocalStorage('tADu', whichProperty('animationDuration'));
ANIMATIONDELAY = setLocalStorage('tADe', whichProperty('animationDelay'));
TRANSITIONEND = setLocalStorage('tTE', getEndProperty(TRANSITIONDURATION, 'Transition'));
ANIMATIONEND = setLocalStorage('tAE', getEndProperty(ANIMATIONDURATION, 'Animation'));
}
}
} else {
localStorageAccess = false;
}
if (!localStorageAccess) {
CALC = calc();
SUBPIXEL = subpixelLayout();
CSSMQ = mediaquerySupport();
TRANSFORM = whichProperty('transform');
HAS3D = has3D(TRANSFORM);
TRANSITIONDURATION = whichProperty('transitionDuration');
TRANSITIONDELAY = whichProperty('transitionDelay');
ANIMATIONDURATION = whichProperty('animationDuration');
ANIMATIONDELAY = whichProperty('animationDelay');
TRANSITIONEND = getEndProperty(TRANSITIONDURATION, 'Transition');
ANIMATIONEND = getEndProperty(ANIMATIONDURATION, 'Animation');
}
// reset SUBPIXEL for IE8
if (!CSSMQ) { SUBPIXEL = false; }
// get element nodes from selectors
var supportConsoleWarn = win.console && typeof win.console.warn === "function";
var list = ['container', 'controlsContainer', 'prevButton', 'nextButton', 'navContainer', 'autoplayButton'];
for (var i = list.length; i
var item = list[i];
if (typeof options[item] === 'string') {
var el = doc.querySelector(options[item]);
if (el && el.nodeName) {
options[item] = el;
} else {
if (supportConsoleWarn) { console.warn('Can\'t find', options[item]); }
return;
}
}
}
// make sure at least 1 slide
if (options.container.children && options.container.children.length < 1) {
if (supportConsoleWarn) { console.warn('No slides found in', options.container); }
return;
}
// update responsive
// from: {
// 300: 2,
// 800: {
// loop: false
// 300: {
// items: 2
// 800: {
// loop: false
if (options.responsive) {
var resTem = {}, res = options.responsive;
for(var key in res) {
var val = res[key];
resTem[key] = typeof val === 'number' ? {items: val} : val;
}
options.responsive = resTem;
resTem = null;
// apply responsive[0] to options and remove it
if (0 in options.responsive) {
options = extend(options, options.responsive[0]);
delete options.responsive[0];
}
}
var carousel = options.mode === 'carousel' ? true : false;
if (!carousel) {
options.axis = 'horizontal';
// options.rewind = false;
// options.loop = true;
options.edgePadding = false;
var animateIn = 'tns-fadeIn',
animateOut = 'tns-fadeOut',
animateDelay = false,
animateNormal = options.animateNormal || 'tns-normal';
if (TRANSITIONEND && ANIMATIONEND) {
animateIn = options.animateIn || animateIn;
animateOut = options.animateOut || animateOut;
animateDelay = options.animateDelay || animateDelay;
}
}
var horizontal = options.axis === 'horizontal' ? true : false,
outerWrapper = doc.createElement('div'),
innerWrapper = doc.createElement('div'),
container = options.container,
containerParent = container.parentNode,
slideItems = container.children,
slideCount = slideItems.length,
vpInner,
responsive = options.responsive,
responsiveItems = [],
breakpoints = false,
breakpointZone = 0,
windowWidth = getWindowWidth(),
isOn;
if (options.fixedWidth) { var vpOuter = getViewportWidth(containerParent); }
if (responsive) {
breakpoints = Object.keys(responsive)
.map(function (x) { return parseInt(x); })
.sort(function (a, b) { return a - b; });
// get all responsive items
breakpoints.forEach(function(bp) {
responsiveItems = responsiveItems.concat(Object.keys(responsive[bp]));
});
// remove duplicated items
var arr = [];
responsiveItems.forEach(function (item) { if (arr.indexOf(item) < 0) { arr.push(item); } });
responsiveItems = arr;
setBreakpointZone();
}
var items = getOption('items'),
slideBy = getOption('slideBy') === 'page' ? items : getOption('slideBy'),
nested = options.nested,
gutter = getOption('gutter'),
edgePadding = getOption('edgePadding'),
fixedWidth = getOption('fixedWidth'),
<API key> = options.<API key>,
arrowKeys = getOption('arrowKeys'),
speed = getOption('speed'),
rewind = options.rewind,
loop = rewind ? false : options.loop,
autoHeight = getOption('autoHeight'),
sheet = createStyleSheet(),
lazyload = options.lazyload,
slideOffsetTops, // collection of slide offset tops
slideItemsOut = [],
hasEdgePadding = checkOption('edgePadding'),
cloneCount = loop ? <API key>() : 0,
slideCountNew = !carousel ? slideCount + cloneCount : slideCount + cloneCount * 2,
hasRightDeadZone = fixedWidth && !loop && !edgePadding ? true : false,
<API key> = (!carousel || !loop) ? true : false,
// transform
transformAttr = horizontal ? 'left' : 'top',
transformPrefix = '',
transformPostfix = '',
// index
startIndex = getOption('startIndex'),
index = startIndex ? updateStartIndex(startIndex) : !carousel ? 0 : cloneCount,
indexCached = index,
indexMin = 0,
indexMax = getIndexMax(),
// resize
resizeTimer,
swipeAngle = options.swipeAngle,
<API key> = swipeAngle ? '?' : true,
running = false,
onInit = options.onInit,
events = new Events(),
// id, class
containerIdCached = container.id,
classContainer = ' tns-slider tns-' + options.mode,
slideId = container.id || getSlideId(),
disable = getOption('disable'),
freezable = options.freezable,
freeze = disable ? true : freezable ? slideCount <= items : false,
frozen,
importantStr = nested === 'inner' ? ' !important' : '',
controlsEvents = {
'click': onControlsClick,
'keydown': onControlsKeydown
},
navEvents = {
'click': onNavClick,
'keydown': onNavKeydown
},
hoverEvents = {
'mouseover': mouseoverPause,
'mouseout': mouseoutRestart
},
visibilityEvent = {'visibilitychange': onVisibilityChange},
docmentKeydownEvent = {'keydown': onDocumentKeydown},
touchEvents = {
'touchstart': onPanStart,
'touchmove': onPanMove,
'touchend': onPanEnd,
'touchcancel': onPanEnd
}, dragEvents = {
'mousedown': onPanStart,
'mousemove': onPanMove,
'mouseup': onPanEnd,
'mouseleave': onPanEnd
},
hasControls = checkOption('controls'),
hasNav = checkOption('nav'),
navAsThumbnails = options.navAsThumbnails,
hasAutoplay = checkOption('autoplay'),
hasTouch = checkOption('touch'),
hasMouseDrag = checkOption('mouseDrag'),
slideActiveClass = 'tns-slide-active',
imgCompleteClass = 'tns-complete',
imgEvents = {
'load': imgLoadedOrError,
'error': imgLoadedOrError
},
imgsComplete;
// controls
if (hasControls) {
var controls = getOption('controls'),
controlsText = getOption('controlsText'),
controlsContainer = options.controlsContainer,
prevButton = options.prevButton,
nextButton = options.nextButton,
prevIsButton,
nextIsButton;
}
// nav
if (hasNav) {
var nav = getOption('nav'),
navContainer = options.navContainer,
navItems,
visibleNavIndexes = [],
<API key> = visibleNavIndexes,
navClicked = -1,
navCurrentIndex = getAbsIndex(),
<API key> = navCurrentIndex,
navActiveClass = 'tns-nav-active';
}
// autoplay
if (hasAutoplay) {
var autoplay = getOption('autoplay'),
autoplayTimeout = getOption('autoplayTimeout'),
autoplayDirection = options.autoplayDirection === 'forward' ? 1 : -1,
autoplayText = getOption('autoplayText'),
autoplayHoverPause = getOption('autoplayHoverPause'),
autoplayButton = options.autoplayButton,
<API key> = getOption('<API key>'),
autoplayHtmlStrings = ['<span class=\'tns-visually-hidden\'>', ' animation</span>'],
autoplayTimer,
animating,
autoplayHoverPaused,
autoplayUserPaused,
<API key>;
}
if (hasTouch || hasMouseDrag) {
var initPosition = {},
lastPosition = {},
translateInit,
disX,
disY,
panStart = false,
rafIndex = 0,
getDist = horizontal ?
function(a, b) { return a.x - b.x; } :
function(a, b) { return a.y - b.y; };
}
// touch
if (hasTouch) {
var touch = getOption('touch');
}
// mouse drag
if (hasMouseDrag) {
var mouseDrag = getOption('mouseDrag');
}
// disable slider when slidecount <= items
if (freeze) {
controls = nav = touch = mouseDrag = arrowKeys = autoplay = autoplayHoverPause = <API key> = false;
}
if (TRANSFORM) {
transformAttr = TRANSFORM;
transformPrefix = 'translate';
if (HAS3D) {
transformPrefix += horizontal ? '3d(' : '3d(0px, ';
transformPostfix = horizontal ? ', 0px, 0px)' : ', 0px)';
} else {
transformPrefix += horizontal ? 'X(' : 'Y(';
transformPostfix = ')';
}
}
function getIndexMax () {
return carousel || loop ? Math.max(0, slideCountNew - items) : slideCountNew - 1;
}
function updateStartIndex (indexTem) {
indexTem = indexTem%slideCount;
if (indexTem < 0) { indexTem += slideCount; }
indexTem = Math.min(indexTem, slideCountNew - items);
return indexTem;
}
function getAbsIndex (i) {
if (i === undefined) { i = index; }
if (carousel) {
while (i < cloneCount) { i += slideCount; }
i -= cloneCount;
}
return i ? i%slideCount : i;
}
function getItemsMax () {
if (fixedWidth && !<API key>) {
return slideCount - 1;
} else {
var str = fixedWidth ? 'fixedWidth' : 'items',
arr = [];
if (fixedWidth || options[str] < slideCount) { arr.push(options[str]); }
if (breakpoints && responsiveItems.indexOf(str) >= 0) {
breakpoints.forEach(function(bp) {
var tem = responsive[bp][str];
if (tem && (fixedWidth || tem < slideCount)) { arr.push(tem); }
});
}
if (!arr.length) { arr.push(0); }
return fixedWidth ? Math.ceil(<API key> / Math.min.apply(null, arr)) :
Math.max.apply(null, arr);
}
}
function <API key> () {
var itemsMax = getItemsMax(),
result = carousel ? Math.ceil((itemsMax * 5 - slideCount)/2) : (itemsMax * 4 - slideCount);
result = Math.max(itemsMax, result);
return hasEdgePadding ? result + 1 : result;
}
function getWindowWidth () {
return win.innerWidth || doc.documentElement.clientWidth || doc.body.clientWidth;
}
function getViewportWidth (el) {
return el.clientWidth || getViewportWidth(el.parentNode);
}
function checkOption (item) {
var result = options[item];
if (!result && breakpoints && responsiveItems.indexOf(item) >= 0) {
breakpoints.forEach(function (bp) {
if (responsive[bp][item]) { result = true; }
});
}
return result;
}
function getOption (item, viewport) {
viewport = viewport ? viewport : windowWidth;
var obj = {
slideBy: 'page',
edgePadding: false
},
result;
if (!carousel && item in obj) {
result = obj[item];
} else {
if (item === 'items' && getOption('fixedWidth')) {
result = Math.floor(vpOuter / (getOption('fixedWidth') + getOption('gutter')));
} else if (item === 'autoHeight' && nested === 'outer') {
result = true;
} else {
result = options[item];
if (breakpoints && responsiveItems.indexOf(item) >= 0) {
for (var i = 0, len = breakpoints.length; i < len; i++) {
var bp = breakpoints[i];
if (viewport >= bp) {
if (item in responsive[bp]) { result = responsive[bp][item]; }
} else { break; }
}
}
}
}
if (item === 'slideBy' && result === 'page') { result = getOption('items'); }
return result;
}
function getSlideMarginLeft (i) {
var str = CALC ?
CALC + '(' + i * 100 + '% / ' + slideCountNew + ')' :
i * 100 / slideCountNew + '%';
return str;
}
function <API key> (edgePaddingTem, gutterTem, fixedWidthTem, speedTem) {
var str = '';
if (edgePaddingTem) {
var gap = edgePaddingTem;
if (gutterTem) { gap += gutterTem; }
if (fixedWidthTem) {
str = 'margin: 0px ' + (vpOuter%(fixedWidthTem + gutterTem) + gutterTem) / 2 + 'px;';
} else {
str = horizontal ?
'margin: 0 ' + edgePaddingTem + 'px 0 ' + gap + 'px;' :
'padding: ' + gap + 'px 0 ' + edgePaddingTem + 'px 0;';
}
} else if (gutterTem && !fixedWidthTem) {
var gutterTemUnit = '-' + gutterTem + 'px',
dir = horizontal ? gutterTemUnit + ' 0 0' : '0 ' + gutterTemUnit + ' 0';
str = 'margin: 0 ' + dir + ';';
}
if (TRANSITIONDURATION && speedTem) { str += <API key>(speedTem); }
return str;
}
function getContainerWidth (fixedWidthTem, gutterTem, itemsTem) {
var str;
if (fixedWidthTem) {
str = (fixedWidthTem + gutterTem) * slideCountNew + 'px';
} else {
str = CALC ?
CALC + '(' + slideCountNew * 100 + '% / ' + itemsTem + ')' :
slideCountNew * 100 / itemsTem + '%';
}
return str;
}
function getSlideWidthStyle (fixedWidthTem, gutterTem, itemsTem) {
var str = '';
if (horizontal) {
str = 'width:';
if (fixedWidthTem) {
str += (fixedWidthTem + gutterTem) + 'px';
} else {
var dividend = carousel ? slideCountNew : itemsTem;
str += CALC ?
CALC + '(100% / ' + dividend + ')' :
100 / dividend + '%';
}
str += importantStr + ';';
}
return str;
}
function getSlideGutterStyle (gutterTem) {
var str = '';
// gutter maybe interger || 0
// so can't use 'if (gutter)'
if (gutterTem !== false) {
var prop = horizontal ? 'padding-' : 'margin-',
dir = horizontal ? 'right' : 'bottom';
str = prop + dir + ': ' + gutterTem + 'px;';
}
return str;
}
function getCSSPrefix (name, num) {
var prefix = name.substring(0, name.length - num).toLowerCase();
if (prefix) { prefix = '-' + prefix + '-'; }
return prefix;
}
function <API key> (speed) {
return getCSSPrefix(TRANSITIONDURATION, 18) + 'transition-duration:' + speed / 1000 + 's;';
}
function <API key> (speed) {
return getCSSPrefix(ANIMATIONDURATION, 17) + 'animation-duration:' + speed / 1000 + 's;';
}
(function sliderInit () {
// First thing first, wrap container with 'outerWrapper > innerWrapper',
// to get the correct view width
outerWrapper.appendChild(innerWrapper);
containerParent.insertBefore(outerWrapper, container);
innerWrapper.appendChild(container);
vpInner = getViewportWidth(innerWrapper);
var classOuter = 'tns-outer',
classInner = 'tns-inner',
hasGutter = checkOption('gutter');
if (carousel) {
if (horizontal) {
if (checkOption('edgePadding') || hasGutter && !options.fixedWidth) {
classOuter += ' tns-ovh';
} else {
classInner += ' tns-ovh';
}
} else {
classInner += ' tns-ovh';
}
} else if (hasGutter) {
classOuter += ' tns-ovh';
}
outerWrapper.className = classOuter;
innerWrapper.className = classInner;
innerWrapper.id = slideId + '-iw';
if (autoHeight) { innerWrapper.className += ' tns-ah'; }
// set container properties
if (container.id === '') { container.id = slideId; }
classContainer += SUBPIXEL ? ' tns-subpixel' : ' tns-no-subpixel';
classContainer += CALC ? ' tns-calc' : ' tns-no-calc';
if (carousel) { classContainer += ' tns-' + options.axis; }
container.className += classContainer;
// add event
if (carousel && TRANSITIONEND) {
var eve = {};
eve[TRANSITIONEND] = onTransitionEnd;
addEvents(container, eve);
}
// delete datas after init
classOuter = classInner = null;
// add id, class, aria attributes
// before clone slides
for (var x = 0; x < slideCount; x++) {
var item = slideItems[x];
if (!item.id) { item.id = slideId + '-item' + x; }
addClass(item, 'tns-item');
if (!carousel && animateNormal) { addClass(item, animateNormal); }
setAttrs(item, {
'aria-hidden': 'true',
'tabindex': '-1'
});
}
// clone slides
if (loop || edgePadding) {
var fragmentBefore = doc.<API key>(),
fragmentAfter = doc.<API key>();
for (var j = cloneCount; j
var num = j%slideCount,
cloneFirst = slideItems[num].cloneNode(true);
removeAttrs(cloneFirst, 'id');
fragmentAfter.insertBefore(cloneFirst, fragmentAfter.firstChild);
if (carousel) {
var cloneLast = slideItems[slideCount - 1 - num].cloneNode(true);
removeAttrs(cloneLast, 'id');
fragmentBefore.appendChild(cloneLast);
}
}
container.insertBefore(fragmentBefore, container.firstChild);
container.appendChild(fragmentAfter);
slideItems = container.children;
}
// add image events
if (checkOption('autoHeight') || !carousel) {
var imgs = container.querySelectorAll('img');
// check all image complete status
// add complete class if true
forEachNodeList(imgs, function(img) {
addEvents(img, imgEvents);
var src = img.src;
img.src = "data:image/gif;base64,<API key>///<API key>==";
img.src = src;
});
// set imgsComplete to true
// when all images are compulete (loaded or error)
raf(function(){ checkImagesLoaded(arrayFromNodeList(imgs), function() {
imgsComplete = true;
}); });
}
// activate visible slides
// add aria attrs
// set animation classes and left value for gallery slider
// use slide count when slides are fewer than items
for (var i = index, l = index + Math.min(slideCount, items); i < l; i++) {
var item = slideItems[i];
setAttrs(item, {'aria-hidden': 'false'});
removeAttrs(item, ['tabindex']);
addClass(item, slideActiveClass);
if (!carousel) {
item.style.left = (i - index) * 100 / items + '%';
addClass(item, animateIn);
removeClass(item, animateNormal);
}
}
if (carousel && horizontal) {
// set font-size rules
// for modern browsers
if (SUBPIXEL) {
// set slides font-size first
addCSSRule(sheet, '#' + slideId + ' > .tns-item', 'font-size:' + win.getComputedStyle(slideItems[0]).fontSize + ';', getCssRulesLength(sheet));
addCSSRule(sheet, '#' + slideId, 'font-size:0;', getCssRulesLength(sheet));
// slide left margin
// for IE8 & webkit browsers (no subpixel)
} else {
forEachNodeList(slideItems, function (slide, i) {
slide.style.marginLeft = getSlideMarginLeft(i);
});
}
}
// all browsers which support CSS transitions support CSS media queries
if (CSSMQ) {
// inner wrapper styles
var str = <API key>(options.edgePadding, options.gutter, options.fixedWidth, options.speed);
addCSSRule(sheet, '#' + slideId + '-iw', str, getCssRulesLength(sheet));
// container styles
if (carousel) {
str = horizontal ? 'width:' + getContainerWidth(options.fixedWidth, options.gutter, options.items) + ';' : '';
if (TRANSITIONDURATION) { str += <API key>(speed); }
addCSSRule(sheet, '#' + slideId, str, getCssRulesLength(sheet));
}
// slide styles
if (horizontal || options.gutter) {
str = getSlideWidthStyle(options.fixedWidth, options.gutter, options.items) +
getSlideGutterStyle(options.gutter);
// set gallery items transition-duration
if (!carousel) {
if (TRANSITIONDURATION) { str += <API key>(speed); }
if (ANIMATIONDURATION) { str += <API key>(speed); }
}
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
// non CSS mediaqueries: IE8
// ## update inner wrapper, container, slides if needed
// set inline styles for inner wrapper & container
// insert stylesheet (one line) for slides only (since slides are many)
} else {
// inner wrapper styles
innerWrapper.style.cssText = <API key>(edgePadding, gutter, fixedWidth);
// container styles
if (carousel && horizontal) {
container.style.width = getContainerWidth(fixedWidth, gutter, items);
}
// slide styles
if (horizontal || gutter) {
var str = getSlideWidthStyle(fixedWidth, gutter, items) +
getSlideGutterStyle(gutter);
// append to the last line
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
}
if (!horizontal && !disable) {
getSlideOffsetTops();
<API key>();
}
// media queries
if (responsive && CSSMQ) {
breakpoints.forEach(function(bp) {
var opts = responsive[bp],
str = '',
innerWrapperStr = '',
containerStr = '',
slideStr = '',
itemsBP = getOption('items', bp),
fixedWidthBP = getOption('fixedWidth', bp),
speedBP = getOption('speed', bp),
edgePaddingBP = getOption('edgePadding', bp),
gutterBP = getOption('gutter', bp);
// inner wrapper string
if ('edgePadding' in opts || 'gutter' in opts) {
innerWrapperStr = '#' + slideId + '-iw{' + <API key>(edgePaddingBP, gutterBP, fixedWidthBP, speedBP) + '}';
}
// container string
if (carousel && horizontal && ('fixedWidth' in opts || 'gutter' in opts || 'items' in opts)) {
containerStr = 'width:' + getContainerWidth(fixedWidthBP, gutterBP, itemsBP) + ';';
}
if (TRANSITIONDURATION && 'speed' in opts) {
containerStr += <API key>(speedBP);
}
if (containerStr) {
containerStr = '#' + slideId + '{' + containerStr + '}';
}
// slide string
if ('fixedWidth' in opts || checkOption('fixedWidth') && 'gutter' in opts || !carousel && 'items' in opts) {
slideStr += getSlideWidthStyle(fixedWidthBP, gutterBP, itemsBP);
}
if ('gutter' in opts) {
slideStr += getSlideGutterStyle(gutterBP);
}
// set gallery items transition-duration
if (!carousel && 'speed' in opts) {
if (TRANSITIONDURATION) { slideStr += <API key>(speedBP); }
if (ANIMATIONDURATION) { slideStr += <API key>(speedBP); }
}
if (slideStr) { slideStr = '#' + slideId + ' > .tns-item{' + slideStr + '}'; }
// add up
str = innerWrapperStr + containerStr + slideStr;
if (str) {
sheet.insertRule('@media (min-width: ' + bp / 16 + 'em) {' + str + '}', sheet.cssRules.length);
}
});
}
// set container transform property
if (carousel && !disable) {
<API key>();
}
// == msInit ==
// for IE10
if (navigator.msMaxTouchPoints) {
addClass(container, 'ms-touch');
addEvents(container, {'scroll': ie10Scroll});
setSnapInterval();
}
// == navInit ==
if (hasNav) {
var initIndex = !carousel ? 0 : cloneCount;
// customized nav
// will not hide the navs in case they're thumbnails
if (navContainer) {
setAttrs(navContainer, {'aria-label': 'Carousel Pagination'});
navItems = navContainer.children;
forEachNodeList(navItems, function (item, i) {
setAttrs(item, {
'data-nav': i,
'tabindex': '-1',
'aria-selected': 'false',
'aria-controls': slideItems[initIndex + i].id,
});
});
// generated nav
} else {
var navHtml = '',
hiddenStr = navAsThumbnails ? '' : 'hidden';
for (var i = 0; i < slideCount; i++) {
// hide nav items by default
navHtml += '<button data-nav="' + i +'" tabindex="-1" aria-selected="false" aria-controls="' + slideItems[initIndex + i].id + '" ' + hiddenStr + ' type="button"></button>';
}
navHtml = '<div class="tns-nav" aria-label="Carousel Pagination">' + navHtml + '</div>';
outerWrapper.insertAdjacentHTML('afterbegin', navHtml);
navContainer = outerWrapper.querySelector('.tns-nav');
navItems = navContainer.children;
}
updateNavVisibility();
// add transition
if (TRANSITIONDURATION) {
var prefix = TRANSITIONDURATION.substring(0, TRANSITIONDURATION.length - 18).toLowerCase(),
str = 'transition: all ' + speed / 1000 + 's';
if (prefix) {
str = '-' + prefix + '-' + str;
}
addCSSRule(sheet, '[aria-controls^=' + slideId + '-item]', str, getCssRulesLength(sheet));
}
setAttrs(navItems[navCurrentIndex], {'tabindex': '0', 'aria-selected': 'true'});
addClass(navItems[navCurrentIndex], navActiveClass);
// add events
addEvents(navContainer, navEvents);
if (!nav) { hideElement(navContainer); }
}
// == autoplayInit ==
if (hasAutoplay) {
var txt = autoplay ? 'stop' : 'start';
if (autoplayButton) {
setAttrs(autoplayButton, {'data-action': txt});
} else if (options.<API key>) {
innerWrapper.insertAdjacentHTML('beforebegin', '<button data-action="' + txt + '" type="button">' + autoplayHtmlStrings[0] + txt + autoplayHtmlStrings[1] + autoplayText[0] + '</button>');
autoplayButton = outerWrapper.querySelector('[data-action]');
}
// add event
if (autoplayButton) {
addEvents(autoplayButton, {'click': toggleAutoplay});
}
if (!autoplay) {
if (autoplayButton) {
hideElement(autoplayButton);
}
} else {
startAutoplay();
if (autoplayHoverPause) { addEvents(container, hoverEvents); }
if (<API key>) { addEvents(container, visibilityEvent); }
}
}
// == controlsInit ==
if (hasControls) {
if (controlsContainer || (prevButton && nextButton)) {
if (controlsContainer) {
prevButton = controlsContainer.children[0];
nextButton = controlsContainer.children[1];
setAttrs(controlsContainer, {
'aria-label': 'Carousel Navigation',
'tabindex': '0'
});
setAttrs(controlsContainer.children, {
'aria-controls': slideId,
'tabindex': '-1',
});
}
setAttrs(prevButton, {'data-controls' : 'prev'});
setAttrs(nextButton, {'data-controls' : 'next'});
} else {
outerWrapper.insertAdjacentHTML('afterbegin', '<div class="tns-controls" aria-label="Carousel Navigation" tabindex="0"><button data-controls="prev" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[0] + '</button><button data-controls="next" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[1] + '</button></div>');
controlsContainer = outerWrapper.querySelector('.tns-controls');
prevButton = controlsContainer.children[0];
nextButton = controlsContainer.children[1];
}
prevIsButton = isButton(prevButton);
nextIsButton = isButton(nextButton);
<API key>();
// add events
if (controlsContainer) {
addEvents(controlsContainer, controlsEvents);
} else {
addEvents(prevButton, controlsEvents);
addEvents(nextButton, controlsEvents);
}
if (!controls) { hideElement(controlsContainer); }
}
// if (!navigator.msMaxTouchPoints) {
if (carousel) {
if (touch) { addEvents(container, touchEvents); }
if (mouseDrag) { addEvents(container, dragEvents); }
}
if (arrowKeys) { addEvents(doc, docmentKeydownEvent); }
if (nested === 'inner') {
events.on('outerResized', function () {
resizeTasks();
events.emit('innerLoaded', info());
});
} else {
addEvents(win, {'resize': onResize});
}
if (nested === 'outer') {
events.on('innerLoaded', runAutoHeight);
} else if ((autoHeight || !carousel) && !disable) {
runAutoHeight();
}
lazyLoad();
<API key>();
<API key>();
events.on('indexChanged', additionalUpdates);
if (typeof onInit === 'function') { onInit(info()); }
if (nested === 'inner') { events.emit('innerLoaded', info()); }
if (disable) { disableSlider(true); }
isOn = true;
})();
function onResize (e) {
raf(function(){ resizeTasks(getEvent(e)); });
}
function resizeTasks (e) {
if (!isOn) { return; }
windowWidth = getWindowWidth();
if (nested === 'outer') { events.emit('outerResized', info(e)); }
var breakpointZoneTem = breakpointZone,
indexTem = index,
itemsTem = items,
freezeTem = freeze,
<API key> = false;
if (fixedWidth) { vpOuter = getViewportWidth(outerWrapper); }
vpInner = getViewportWidth(innerWrapper);
if (breakpoints) { setBreakpointZone(); }
// things do when breakpoint zone change
if (breakpointZoneTem !== breakpointZone || fixedWidth) {
var slideByTem = slideBy,
arrowKeysTem = arrowKeys,
autoHeightTem = autoHeight,
fixedWidthTem = fixedWidth,
edgePaddingTem = edgePadding,
gutterTem = gutter,
disableTem = disable;
// update variables
items = getOption('items');
slideBy = getOption('slideBy');
disable = getOption('disable');
freeze = disable ? true : freezable ? slideCount <= items : false;
if (items !== itemsTem) {
indexMax = getIndexMax();
// check index before transform in case
// slider reach the right edge then items become bigger
updateIndex();
}
if (disable !== disableTem) {
disableSlider(disable);
}
if (freeze !== freezeTem) {
// reset index to initial status
if (freeze) { index = !carousel ? 0 : cloneCount; }
<API key>();
}
if (breakpointZoneTem !== breakpointZone) {
speed = getOption('speed');
edgePadding = getOption('edgePadding');
gutter = getOption('gutter');
fixedWidth = getOption('fixedWidth');
if (!disable && fixedWidth !== fixedWidthTem) {
<API key> = true;
}
autoHeight = getOption('autoHeight');
if (autoHeight !== autoHeightTem) {
if (!autoHeight) { innerWrapper.style.height = ''; }
}
}
arrowKeys = freeze ? false : getOption('arrowKeys');
if (arrowKeys !== arrowKeysTem) {
arrowKeys ?
addEvents(doc, docmentKeydownEvent) :
removeEvents(doc, docmentKeydownEvent);
}
if (hasControls) {
var controlsTem = controls,
controlsTextTem = controlsText;
controls = freeze ? false : getOption('controls');
controlsText = getOption('controlsText');
if (controls !== controlsTem) {
controls ?
showElement(controlsContainer) :
hideElement(controlsContainer);
}
if (controlsText !== controlsTextTem) {
prevButton.innerHTML = controlsText[0];
nextButton.innerHTML = controlsText[1];
}
}
if (hasNav) {
var navTem = nav;
nav = freeze ? false : getOption('nav');
if (nav !== navTem) {
if (nav) {
showElement(navContainer);
updateNavVisibility();
} else {
hideElement(navContainer);
}
}
}
if (hasTouch) {
var touchTem = touch;
touch = freeze ? false : getOption('touch');
if (touch !== touchTem && carousel) {
touch ?
addEvents(container, touchEvents) :
removeEvents(container, touchEvents);
}
}
if (hasMouseDrag) {
var mouseDragTem = mouseDrag;
mouseDrag = freeze ? false : getOption('mouseDrag');
if (mouseDrag !== mouseDragTem && carousel) {
mouseDrag ?
addEvents(container, dragEvents) :
removeEvents(container, dragEvents);
}
}
if (hasAutoplay) {
var autoplayTem = autoplay,
<API key> = autoplayHoverPause,
<API key> = <API key>,
autoplayTextTem = autoplayText;
if (freeze) {
autoplay = autoplayHoverPause = <API key> = false;
} else {
autoplay = getOption('autoplay');
if (autoplay) {
autoplayHoverPause = getOption('autoplayHoverPause');
<API key> = getOption('<API key>');
} else {
autoplayHoverPause = <API key> = false;
}
}
autoplayText = getOption('autoplayText');
autoplayTimeout = getOption('autoplayTimeout');
if (autoplay !== autoplayTem) {
if (autoplay) {
if (autoplayButton) { showElement(autoplayButton); }
if (!animating && !autoplayUserPaused) { startAutoplay(); }
} else {
if (autoplayButton) { hideElement(autoplayButton); }
if (animating) { stopAutoplay(); }
}
}
if (autoplayHoverPause !== <API key>) {
autoplayHoverPause ?
addEvents(container, hoverEvents) :
removeEvents(container, hoverEvents);
}
if (<API key> !== <API key>) {
<API key> ?
addEvents(doc, visibilityEvent) :
removeEvents(doc, visibilityEvent);
}
if (autoplayButton && autoplayText !== autoplayTextTem) {
var i = autoplay ? 1 : 0,
html = autoplayButton.innerHTML,
len = html.length - autoplayTextTem[i].length;
if (html.substring(len) === autoplayTextTem[i]) {
autoplayButton.innerHTML = html.substring(0, len) + autoplayText[i];
}
}
}
// IE8
// ## update inner wrapper, container, slides if needed
// set inline styles for inner wrapper & container
// insert stylesheet (one line) for slides only (since slides are many)
if (!CSSMQ) {
// inner wrapper styles
if (!freeze && (edgePadding !== edgePaddingTem || gutter !== gutterTem)) {
innerWrapper.style.cssText = <API key>(edgePadding, gutter, fixedWidth);
}
// container styles
if (carousel && horizontal && (fixedWidth !== fixedWidthTem || gutter !== gutterTem || items !== itemsTem)) {
container.style.width = getContainerWidth(fixedWidth, gutter, items);
}
// slide styles
if (horizontal && (items !== itemsTem || gutter !== gutterTem || fixedWidth != fixedWidthTem)) {
var str = getSlideWidthStyle(fixedWidth, gutter, items) +
getSlideGutterStyle(gutter);
// remove the last line and
// add new styles
sheet.removeRule(getCssRulesLength(sheet) - 1);
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
if (!fixedWidth) { <API key> = true; }
}
if (index !== indexTem) {
events.emit('indexChanged', info());
<API key> = true;
}
if (items !== itemsTem) {
additionalUpdates();
updateSlidePosition();
if (navigator.msMaxTouchPoints) { setSnapInterval(); }
}
}
// things always do regardless of breakpoint zone changing
if (!horizontal && !disable) {
getSlideOffsetTops();
<API key>();
<API key> = true;
}
if (<API key>) {
<API key>();
indexCached = index;
}
<API key>(true);
// auto height
if ((autoHeight || !carousel) && !disable) { runAutoHeight(); }
}
function setBreakpointZone () {
breakpointZone = 0;
breakpoints.forEach(function(bp, i) {
if (windowWidth >= bp) { breakpointZone = i + 1; }
});
}
function loopNumber (num, min, max) {
return index >= indexMin && index <= indexMax ? index : index > indexMax ? index - slideCount : index + slideCount;
}
function cutindexber (index, min, indexMax) {
return index >= indexMin && index <= indexMax ? index : index > indexMax ? indexMax : indexMin;
}
// (slideBy, indexMin, indexMax) => index
var updateIndex = (function () {
return loop ?
carousel ?
// loop + carousel
function () {
var leftEdge = indexMin,
rightEdge = indexMax;
leftEdge += slideBy;
rightEdge -= slideBy;
// adjust edges when edge padding is true
// or fixed-width slider with extra space on the right side
if (edgePadding) {
leftEdge += 1;
rightEdge -= 1;
} else if (fixedWidth) {
var gt = gutter ? gutter : 0;
if (vpOuter%(fixedWidth + gt) > gt) { rightEdge -= 1; }
}
if (cloneCount) {
if (index > rightEdge) {
index -= slideCount;
} else if (index < leftEdge) {
index += slideCount;
}
}
} :
// loop + gallery
function() {
if (index > indexMax) {
while (index >= indexMin + slideCount) { index -= slideCount; }
} else if (index < indexMin) {
while (index <= indexMax - slideCount) { index += slideCount; }
}
} :
// non-loop
function() {
index = (index >= indexMin && index <= indexMax) ? index :
index > indexMax ? indexMax : indexMin;
};
})();
function <API key> () {
// if (cloneCount) {
// if (fixedWidth && cloneCount) {
var str = 'tns-transparent';
if (freeze) {
if (!frozen) {
// remove edge padding from inner wrapper
if (edgePadding) { innerWrapper.style.margin = '0px'; }
// add class tns-transparent to cloned slides
if (cloneCount) {
for (var i = cloneCount; i
if (carousel) { addClass(slideItems[i], str); }
addClass(slideItems[slideCountNew - i - 1], str);
}
}
frozen = true;
}
} else if (frozen) {
// restore edge padding for inner wrapper
// for mordern browsers
if (edgePadding && !fixedWidth && CSSMQ) { innerWrapper.style.margin = ''; }
// remove class tns-transparent to cloned slides
if (cloneCount) {
for (var i = cloneCount; i
if (carousel) { removeClass(slideItems[i], str); }
removeClass(slideItems[slideCountNew - i - 1], str);
}
}
frozen = false;
}
}
function <API key> (resize) {
if (fixedWidth && edgePadding) {
// remove edge padding when freeze or viewport narrower than one slide
if (freeze || vpOuter <= (fixedWidth + gutter)) {
if (innerWrapper.style.margin !== '0px') { innerWrapper.style.margin = '0px'; }
// update edge padding on resize
} else if (resize) {
innerWrapper.style.cssText = <API key>(edgePadding, gutter, fixedWidth);
}
}
}
function disableSlider (disable) {
var len = slideItems.length;
if (disable) {
sheet.disabled = true;
container.className = container.className.replace(classContainer.substring(1), '');
removeElementStyles(container);
if (loop) {
for (var j = cloneCount; j
if (carousel) { hideElement(slideItems[j]); }
hideElement(slideItems[len - j - 1]);
}
}
// vertical slider
if (!horizontal || !carousel) { removeElementStyles(innerWrapper); }
// gallery
if (!carousel) {
for (var i = index, l = index + slideCount; i < l; i++) {
var item = slideItems[i];
removeElementStyles(item);
removeClass(item, animateIn);
removeClass(item, animateNormal);
}
}
} else {
sheet.disabled = false;
container.className += classContainer;
// vertical slider: get offsetTops before container transform
if (!horizontal) { getSlideOffsetTops(); }
<API key>();
if (loop) {
for (var j = cloneCount; j
if (carousel) { showElement(slideItems[j]); }
showElement(slideItems[len - j - 1]);
}
}
// gallery
if (!carousel) {
for (var i = index, l = index + slideCount; i < l; i++) {
var item = slideItems[i],
classN = i < index + items ? animateIn : animateNormal;
item.style.left = (i - index) * 100 / items + '%';
addClass(item, classN);
}
}
}
}
// lazyload
function lazyLoad () {
if (lazyload && !disable) {
var i = index,
len = index + items;
if (edgePadding) {
i -=1;
len +=1;
}
i = Math.max(i, 0);
len = Math.min(len, slideCountNew);
for(; i < len; i++) {
forEachNodeList(slideItems[i].querySelectorAll('.tns-lazy-img'), function (img) {
// stop propagationl transitionend event to container
var eve = {};
eve[TRANSITIONEND] = function (e) { e.stopPropagation(); };
addEvents(img, eve);
if (!hasClass(img, 'loaded')) {
img.src = getAttr(img, 'data-src');
addClass(img, 'loaded');
}
});
}
}
}
function imgLoadedOrError (e) {
var img = getTarget(e);
addClass(img, imgCompleteClass);
removeEvents(img, imgEvents);
}
function getImageArray (slideStart, slideRange) {
var imgs = [];
for (var i = slideStart, l = slideStart + slideRange; i < l; i++) {
forEachNodeList(slideItems[i].querySelectorAll('img'), function (img) {
imgs.push(img);
});
}
return imgs;
}
// check if all visible images are loaded
// and update container height if it's done
function runAutoHeight () {
var imgs = autoHeight ?
getImageArray(index, items) :
getImageArray(cloneCount, slideCount);
raf(function(){ checkImagesLoaded(imgs, <API key>); });
}
function checkImagesLoaded (imgs, cb) {
// directly execute callback function if all images are complete
if (imgsComplete) { return cb(); }
// check selected image classes otherwise
imgs.forEach(function (img, index) {
if (hasClass(img, imgCompleteClass)) { imgs.splice(index, 1); }
});
// execute callback function if selected images are all complete
if (!imgs.length) { return cb(); }
// otherwise execute this functiona again
raf(function(){ checkImagesLoaded(imgs, cb); });
}
function additionalUpdates () {
lazyLoad();
updateSlideStatus();
<API key>();
updateNavVisibility();
updateNavStatus();
}
function getMaxSlideHeight (slideStart, slideRange) {
var heights = [];
for (var i = slideStart, l = slideStart + slideRange; i < l; i++) {
heights.push(slideItems[i].offsetHeight);
}
return Math.max.apply(null, heights);
}
// update inner wrapper height
// 1. get the max-height of the visible slides
// 2. set transitionDuration to speed
// 3. update inner wrapper height to max-height
// 4. set transitionDuration to 0s after transition done
function <API key> () {
var maxHeight = autoHeight ?
getMaxSlideHeight(index, items) :
getMaxSlideHeight(cloneCount, slideCount);
if (innerWrapper.style.height !== maxHeight) { innerWrapper.style.height = maxHeight + 'px'; }
}
// get the distance from the top edge of the first slide to each slide
// (init) => slideOffsetTops
function getSlideOffsetTops () {
slideOffsetTops = [0];
var topFirst = slideItems[0].<API key>().top, attr;
for (var i = 1; i < slideCountNew; i++) {
attr = slideItems[i].<API key>().top;
slideOffsetTops.push(attr - topFirst);
}
}
// set snapInterval (for IE10)
function setSnapInterval () {
outerWrapper.style.msScrollSnapPointsX = 'snapInterval(0%, ' + (100 / items) + '%)';
}
// update slide
function updateSlideStatus () {
var l = index + Math.min(slideCount, items);
for (var i = slideCountNew; i
var item = slideItems[i];
// visible slides
if (i >= index && i < l) {
if (hasAttr(item, 'tabindex')) {
setAttrs(item, {'aria-hidden': 'false'});
removeAttrs(item, ['tabindex']);
addClass(item, slideActiveClass);
}
// hidden slides
} else {
if (!hasAttr(item, 'tabindex')) {
setAttrs(item, {
'aria-hidden': 'true',
'tabindex': '-1'
});
}
if (hasClass(item, slideActiveClass)) {
removeClass(item, slideActiveClass);
}
}
}
}
// gallery: update slide position
function updateSlidePosition () {
if (!carousel) {
var l = index + Math.min(slideCount, items);
for (var i = slideCountNew; i
var item = slideItems[i];
if (i >= index && i < l) {
// add transitions to visible slides when adjusting their positions
addClass(item, 'tns-moving');
item.style.left = (i - index) * 100 / items + '%';
addClass(item, animateIn);
removeClass(item, animateNormal);
} else if (item.style.left) {
item.style.left = '';
addClass(item, animateNormal);
removeClass(item, animateIn);
}
// remove outlet animation
removeClass(item, animateOut);
}
// removing '.tns-moving'
setTimeout(function() {
forEachNodeList(slideItems, function(el) {
removeClass(el, 'tns-moving');
});
}, 300);
}
}
// set tabindex & aria-selected on Nav
function updateNavStatus () {
// get current nav
if (nav) {
navCurrentIndex = navClicked !== -1 ? navClicked : getAbsIndex();
navClicked = -1;
if (navCurrentIndex !== <API key>) {
var navPrev = navItems[<API key>],
navCurrent = navItems[navCurrentIndex];
setAttrs(navPrev, {
'tabindex': '-1',
'aria-selected': 'false'
});
setAttrs(navCurrent, {
'tabindex': '0',
'aria-selected': 'true'
});
removeClass(navPrev, navActiveClass);
addClass(navCurrent, navActiveClass);
}
}
}
function <API key> (el) {
return el.nodeName.toLowerCase();
}
function isButton (el) {
return <API key>(el) === 'button';
}
function isAriaDisabled (el) {
return el.getAttribute('aria-disabled') === 'true';
}
function disEnableElement (isButton, el, val) {
if (isButton) {
el.disabled = val;
} else {
el.setAttribute('aria-disabled', val.toString());
}
}
// set 'disabled' to true on controls when reach the edges
function <API key> () {
if (!controls || rewind || loop) { return; }
var prevDisabled = (prevIsButton) ? prevButton.disabled : isAriaDisabled(prevButton),
nextDisabled = (nextIsButton) ? nextButton.disabled : isAriaDisabled(nextButton),
disablePrev = (index === indexMin) ? true : false,
disableNext = (!rewind && index === indexMax) ? true : false;
if (disablePrev && !prevDisabled) {
disEnableElement(prevIsButton, prevButton, true);
}
if (!disablePrev && prevDisabled) {
disEnableElement(prevIsButton, prevButton, false);
}
if (disableNext && !nextDisabled) {
disEnableElement(nextIsButton, nextButton, true);
}
if (!disableNext && nextDisabled) {
disEnableElement(nextIsButton, nextButton, false);
}
}
// set duration
function resetDuration (el, str) {
if (TRANSITIONDURATION) { el.style[TRANSITIONDURATION] = str; }
}
function <API key> () {
var val;
if (horizontal) {
if (fixedWidth) {
val = - (fixedWidth + gutter) * index + 'px';
} else {
var denominator = TRANSFORM ? slideCountNew : items;
val = - index * 100 / denominator + '%';
}
} else {
val = - slideOffsetTops[index] + 'px';
}
return val;
}
function <API key> (val) {
resetDuration(container, '0s');
<API key>(val);
setTimeout(function() { resetDuration(container, ''); }, 0);
}
function <API key> (val, test) {
if (!val) { val = <API key>(); }
container.style[transformAttr] = transformPrefix + val + transformPostfix;
}
function animateSlide (number, classOut, classIn, isOut) {
var l = number + items;
if (!loop) { l = Math.min(l, slideCountNew); }
for (var i = number; i < l; i++) {
var item = slideItems[i];
// set item positions
if (!isOut) { item.style.left = (i - index) * 100 / items + '%'; }
if (animateDelay && TRANSITIONDELAY) {
item.style[TRANSITIONDELAY] = item.style[ANIMATIONDELAY] = animateDelay * (i - number) / 1000 + 's';
}
removeClass(item, classOut);
addClass(item, classIn);
if (isOut) { slideItemsOut.push(item); }
}
}
// make transfer after click/drag:
// 1. change 'transform' property for mordern browsers
// 2. change 'left' property for legacy browsers
var transformCore = (function () {
return carousel ?
function (duration, distance) {
if (!distance) { distance = <API key>(); }
// constrain the distance when non-loop no-edgePadding fixedWidth reaches the right edge
if (hasRightDeadZone && index === indexMax) {
distance = - ((fixedWidth + gutter) * slideCountNew - vpInner) + 'px';
}
if (TRANSITIONDURATION || !duration) {
// for morden browsers with non-zero duration or
// zero duration for all browsers
<API key>(distance);
// run fallback function manually
// when duration is 0 / container is hidden
if (!duration || !isVisible(container)) { onTransitionEnd(); }
} else {
// for old browser with non-zero duration
jsTransform(container, transformAttr, transformPrefix, transformPostfix, distance, speed, onTransitionEnd);
}
if (!horizontal) { <API key>(); }
} :
function (duration) {
slideItemsOut = [];
var eve = {};
eve[TRANSITIONEND] = eve[ANIMATIONEND] = onTransitionEnd;
removeEvents(slideItems[indexCached], eve);
addEvents(slideItems[index], eve);
animateSlide(indexCached, animateIn, animateOut, true);
animateSlide(index, animateNormal, animateIn);
// run fallback function manually
// when transition or animation not supported / duration is 0
if (!TRANSITIONEND || !ANIMATIONEND || !duration) { onTransitionEnd(); }
};
})();
function doTransform (duration, distance) {
// check duration is defined and is a number
if (isNaN(duration)) { duration = speed; }
// if container is hidden, set duration to 0
// to fix an issue where browser doesn't fire ontransitionend on hidden element
if (animating && !isVisible(container)) { duration = 0; }
transformCore(duration, distance);
}
function render (e, sliderMoved) {
if (<API key>) { updateIndex(); }
// render when slider was moved (touch or drag) even though index may not change
if (index !== indexCached || sliderMoved) {
// events
events.emit('indexChanged', info());
events.emit('transitionStart', info());
// pause autoplay when click or keydown from user
if (animating && e && ['click', 'keydown'].indexOf(e.type) >= 0) { stopAutoplay(); }
running = true;
doTransform();
}
}
/*
* Transfer prefixed properties to the same format
* CSS: -Webkit-Transform => webkittransform
* JS: WebkitTransform => webkittransform
* @param {string} str - property
*
*/
function strTrans (str) {
return str.toLowerCase().replace(/-/g, '');
}
// AFTER TRANSFORM
// Things need to be done after a transfer:
// 1. check index
// 2. add classes to visible slide
// 3. disable controls buttons when reach the first/last slide in non-loop slider
// 4. update nav status
// 5. lazyload images
// 6. update container height
function onTransitionEnd (event) {
// check running on gallery mode
// make sure trantionend/animationend events run only once
if (carousel || running) {
events.emit('transitionEnd', info(event));
if (!carousel && slideItemsOut.length > 0) {
for (var i = 0; i < slideItemsOut.length; i++) {
var item = slideItemsOut[i];
// set item positions
item.style.left = '';
if (ANIMATIONDELAY && TRANSITIONDELAY) {
item.style[ANIMATIONDELAY] = '';
item.style[TRANSITIONDELAY] = '';
}
removeClass(item, animateOut);
addClass(item, animateNormal);
}
}
/* update slides, nav, controls after checking ...
* => legacy browsers who don't support 'event'
* have to check event first, otherwise event.target will cause an error
* => or 'gallery' mode:
* + event target is slide item
* => or 'carousel' mode:
* + event target is container,
* + event.property is the same with transform attribute
*/
if (!event ||
!carousel && event.target.parentNode === container ||
event.target === container && strTrans(event.propertyName) === strTrans(transformAttr)) {
if (!<API key>) {
var indexTem = index;
updateIndex();
if (index !== indexTem) {
events.emit('indexChanged', info());
<API key>();
}
}
if (autoHeight) { runAutoHeight(); }
if (nested === 'inner') { events.emit('innerLoaded', info()); }
running = false;
<API key> = navCurrentIndex;
indexCached = index;
}
}
}
// # ACTIONS
function goTo (targetIndex, e) {
if (freeze) { return; }
// prev slideBy
if (targetIndex === 'prev') {
onControlsClick(e, -1);
// next slideBy
} else if (targetIndex === 'next') {
onControlsClick(e, 1);
// go to exact slide
} else {
if (running) { onTransitionEnd(); }
// } else if (!running) {
var absIndex = getAbsIndex(),
indexGap = 0;
if (absIndex < 0) { absIndex += slideCount; }
if (targetIndex === 'first') {
indexGap = - absIndex;
} else if (targetIndex === 'last') {
indexGap = carousel ? slideCount - items - absIndex : slideCount - 1 - absIndex;
} else {
if (typeof targetIndex !== 'number') { targetIndex = parseInt(targetIndex); }
if (!isNaN(targetIndex)) {
var absTargetIndex = getAbsIndex(targetIndex);
if (absTargetIndex < 0) { absTargetIndex += slideCount; }
indexGap = absTargetIndex - absIndex;
}
}
index += indexGap;
// if index is changed, start rendering
if (getAbsIndex(index) !== getAbsIndex(indexCached)) {
render(e);
}
}
}
// on controls click
function onControlsClick (e, dir) {
// if (!running) {
if (running) { onTransitionEnd(); }
var passEventObject;
if (!dir) {
e = getEvent(e);
var target = e.target || e.srcElement;
while (target !== controlsContainer && [prevButton, nextButton].indexOf(target) < 0) { target = target.parentNode; }
var targetIn = [prevButton, nextButton].indexOf(target);
if (targetIn >= 0) {
passEventObject = true;
dir = targetIn === 0 ? -1 : 1;
}
}
if (rewind) {
if (index === indexMin && dir === -1) {
goTo('last', e);
return;
} else if (index === indexMax && dir === 1) {
goTo(0, e);
return;
}
}
if (dir) {
index += slideBy * dir;
// pass e when click control buttons or keydown
render((passEventObject || (e && e.type === 'keydown')) ? e : null);
}
}
// on nav click
function onNavClick (e) {
// if (!running) {
if (running) { onTransitionEnd(); }
e = getEvent(e);
var target = e.target || e.srcElement,
navIndex;
// find the clicked nav item
while (target !== navContainer && !hasAttr(target, 'data-nav')) { target = target.parentNode; }
if (hasAttr(target, 'data-nav')) {
navIndex = navClicked = [].indexOf.call(navItems, target);
goTo(navIndex + cloneCount, e);
}
}
// autoplay functions
function setAutoplayTimer () {
autoplayTimer = setInterval(function () {
onControlsClick(null, autoplayDirection);
}, autoplayTimeout);
animating = true;
}
function stopAutoplayTimer () {
clearInterval(autoplayTimer);
animating = false;
}
function <API key> (action, txt) {
setAttrs(autoplayButton, {'data-action': action});
autoplayButton.innerHTML = autoplayHtmlStrings[0] + action + autoplayHtmlStrings[1] + txt;
}
function startAutoplay () {
setAutoplayTimer();
if (autoplayButton) { <API key>('stop', autoplayText[1]); }
}
function stopAutoplay () {
stopAutoplayTimer();
if (autoplayButton) { <API key>('start', autoplayText[0]); }
}
// programaitcally play/pause the slider
function play () {
if (autoplay && !animating) {
startAutoplay();
autoplayUserPaused = false;
}
}
function pause () {
if (animating) {
stopAutoplay();
autoplayUserPaused = true;
}
}
function toggleAutoplay () {
if (animating) {
stopAutoplay();
autoplayUserPaused = true;
} else {
startAutoplay();
autoplayUserPaused = false;
}
}
function onVisibilityChange () {
if (doc.hidden) {
if (animating) {
stopAutoplayTimer();
<API key> = true;
}
} else if (<API key>) {
setAutoplayTimer();
<API key> = false;
}
}
function mouseoverPause () {
if (animating) {
stopAutoplayTimer();
autoplayHoverPaused = true;
}
}
function mouseoutRestart () {
if (autoplayHoverPaused) {
setAutoplayTimer();
autoplayHoverPaused = false;
}
}
// keydown events on document
function onDocumentKeydown (e) {
e = getEvent(e);
switch(e.keyCode) {
case KEYS.LEFT:
onControlsClick(e, -1);
break;
case KEYS.RIGHT:
onControlsClick(e, 1);
}
}
// on key control
function onControlsKeydown (e) {
e = getEvent(e);
var code = e.keyCode;
switch (code) {
case KEYS.LEFT:
case KEYS.UP:
case KEYS.PAGEUP:
if (!prevButton.disabled) {
onControlsClick(e, -1);
}
break;
case KEYS.RIGHT:
case KEYS.DOWN:
case KEYS.PAGEDOWN:
if (!nextButton.disabled) {
onControlsClick(e, 1);
}
break;
case KEYS.HOME:
goTo(0, e);
break;
case KEYS.END:
goTo(slideCount - 1, e);
break;
}
}
// set focus
function setFocus (focus) {
focus.focus();
}
// on key nav
function onNavKeydown (e) {
var curElement = doc.activeElement;
if (!hasAttr(curElement, 'data-nav')) { return; }
e = getEvent(e);
var code = e.keyCode,
navIndex = [].indexOf.call(navItems, curElement),
len = visibleNavIndexes.length,
current = visibleNavIndexes.indexOf(navIndex);
if (options.navContainer) {
len = slideCount;
current = navIndex;
}
function getNavIndex (num) {
return options.navContainer ? num : visibleNavIndexes[num];
}
switch(code) {
case KEYS.LEFT:
case KEYS.PAGEUP:
if (current > 0) { setFocus(navItems[getNavIndex(current - 1)]); }
break;
case KEYS.UP:
case KEYS.HOME:
if (current > 0) { setFocus(navItems[getNavIndex(0)]); }
break;
case KEYS.RIGHT:
case KEYS.PAGEDOWN:
if (current < len - 1) { setFocus(navItems[getNavIndex(current + 1)]); }
break;
case KEYS.DOWN:
case KEYS.END:
if (current < len - 1) { setFocus(navItems[getNavIndex(len - 1)]); }
break;
// Can't use onNavClick here,
// Because onNavClick require event.target as nav items
case KEYS.ENTER:
case KEYS.SPACE:
navClicked = navIndex;
goTo(navIndex + cloneCount, e);
break;
}
}
// IE10 scroll function
function ie10Scroll () {
transformCore(0, container.scrollLeft);
indexCached = index;
}
function getEvent (e) {
e = e || win.event;
return isTouchEvent(e) ? e.changedTouches[0] : e;
}
function getTarget (e) {
return e.target || win.event.srcElement;
}
function isTouchEvent (e) {
return e.type.indexOf('touch') >= 0;
}
function <API key> (e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
function onPanStart (e) {
if (running) { onTransitionEnd(); }
panStart = true;
caf(rafIndex);
rafIndex = raf(function(){ panUpdate(e); });
var $ = getEvent(e);
events.emit(isTouchEvent(e) ? 'touchStart' : 'dragStart', info(e));
if (!isTouchEvent(e) && ['img', 'a'].indexOf(<API key>(getTarget(e))) >= 0) {
<API key>(e);
}
lastPosition.x = initPosition.x = parseInt($.clientX);
lastPosition.y = initPosition.y = parseInt($.clientY);
translateInit = parseFloat(container.style[transformAttr].replace(transformPrefix, '').replace(transformPostfix, ''));
resetDuration(container, '0s');
}
function onPanMove (e) {
if (panStart) {
var $ = getEvent(e);
lastPosition.x = parseInt($.clientX);
lastPosition.y = parseInt($.clientY);
}
}
function panUpdate (e) {
if (!<API key>) {
panStart = false;
return;
}
caf(rafIndex);
if (panStart) { rafIndex = raf(function(){ panUpdate(e); }); }
if (
<API key> === '?' &&
lastPosition.x !== initPosition.x &&
lastPosition.y !== initPosition.y) {
<API key> = getTouchDirection(toDegree(lastPosition.y - initPosition.y, lastPosition.x - initPosition.x), swipeAngle) === options.axis;
}
if (<API key>) {
events.emit(isTouchEvent(e) ? 'touchMove' : 'dragMove', info(e));
var x = translateInit,
dist = getDist(lastPosition, initPosition);
if (!horizontal || fixedWidth) {
x += dist;
x += 'px';
} else {
var percentageX = TRANSFORM ? dist * items * 100 / (vpInner * slideCountNew): dist * 100 / vpInner;
x += percentageX;
x += '%';
}
container.style[transformAttr] = transformPrefix + x + transformPostfix;
}
}
function onPanEnd (e) {
if (swipeAngle) { <API key> = '?'; } // reset
if (panStart) {
caf(rafIndex);
resetDuration(container, '');
panStart = false;
var $ = getEvent(e);
lastPosition.x = parseInt($.clientX);
lastPosition.y = parseInt($.clientY);
var dist = getDist(lastPosition, initPosition);
// initPosition = {x:0, y:0}; // reset positions
// lastPosition = {x:0, y:0}; // reset positions
if (Math.abs(dist) >= 5) {
// drag vs click
if (!isTouchEvent(e)) {
// prevent "click"
var target = getTarget(e);
addEvents(target, {'click': function preventClick (e) {
<API key>(e);
removeEvents(target, {'click': preventClick});
}});
}
rafIndex = raf(function() {
events.emit(isTouchEvent(e) ? 'touchEnd' : 'dragEnd', info(e));
if (horizontal) {
var indexMoved = - dist * items / vpInner;
indexMoved = dist > 0 ? Math.floor(indexMoved) : Math.ceil(indexMoved);
index += indexMoved;
} else {
var moved = - (translateInit + dist);
if (moved <= 0) {
index = indexMin;
} else if (moved >= slideOffsetTops[slideOffsetTops.length - 1]) {
index = indexMax;
} else {
var i = 0;
do {
i++;
index = dist < 0 ? i + 1 : i;
} while (i < slideCountNew && moved >= slideOffsetTops[i + 1]);
}
}
render(e, dist);
});
}
}
}
// (slideOffsetTops, index, items) => <API key>.height
function <API key> () {
innerWrapper.style.height = slideOffsetTops[index + items] - slideOffsetTops[index] + 'px';
}
/*
* get nav item indexes per items
* add 1 more if the nav items cann't cover all slides
* [0, 1, 2, 3, 4] / 3 => [0, 3]
*/
function getVisibleNavIndex () {
// reset visibleNavIndexes
visibleNavIndexes = [];
var absIndexMin = getAbsIndex()%items;
while (absIndexMin < slideCount) {
if (carousel && !loop && absIndexMin + items > slideCount) { absIndexMin = slideCount - items; }
visibleNavIndexes.push(absIndexMin);
absIndexMin += items;
}
// nav count * items < slide count means
// some slides can not be displayed only by nav clicking
if (loop && visibleNavIndexes.length * items < slideCount ||
!loop && visibleNavIndexes[0] > 0) {
visibleNavIndexes.unshift(0);
}
}
/*
* 1. update visible nav items list
* 2. add "hidden" attributes to previous visible nav items
* 3. remove "hidden" attrubutes to new visible nav items
*/
function updateNavVisibility () {
if (!nav || navAsThumbnails) { return; }
getVisibleNavIndex();
if (visibleNavIndexes !== <API key>) {
forEachNodeList(navItems, function(el, i) {
if (visibleNavIndexes.indexOf(i) < 0) {
hideElement(el);
} else {
showElement(el);
}
});
// cache visible nav indexes
<API key> = visibleNavIndexes;
}
}
function info (e) {
return {
container: container,
slideItems: slideItems,
navContainer: navContainer,
navItems: navItems,
controlsContainer: controlsContainer,
hasControls: hasControls,
prevButton: prevButton,
nextButton: nextButton,
items: items,
slideBy: slideBy,
cloneCount: cloneCount,
slideCount: slideCount,
slideCountNew: slideCountNew,
index: index,
indexCached: indexCached,
navCurrentIndex: navCurrentIndex,
<API key>: <API key>,
visibleNavIndexes: visibleNavIndexes,
<API key>: <API key>,
sheet: sheet,
event: e || {},
};
}
return {
getInfo: info,
events: events,
goTo: goTo,
play: play,
pause: pause,
isOn: isOn,
updateSliderHeight: <API key>,
rebuild: function() {
return tns(options);
},
destroy: function () {
// remove win event listeners
removeEvents(win, {'resize': onResize});
// remove arrowKeys eventlistener
removeEvents(doc, docmentKeydownEvent);
// sheet
sheet.disabled = true;
// cloned items
if (loop) {
for (var j = cloneCount; j
if (carousel) { slideItems[0].remove(); }
slideItems[slideItems.length - 1].remove();
}
}
// Slide Items
var slideClasses = ['tns-item', slideActiveClass];
if (!carousel) { slideClasses = slideClasses.concat('tns-normal', animateIn); }
for (var i = slideCount; i
var slide = slideItems[i];
if (slide.id.indexOf(slideId + '-item') >= 0) { slide.id = ''; }
slideClasses.forEach(function(cl) { removeClass(slide, cl); });
}
removeAttrs(slideItems, ['style', 'aria-hidden', 'tabindex']);
slideItems = slideId = slideCount = slideCountNew = cloneCount = null;
// controls
if (controls) {
removeEvents(controlsContainer, controlsEvents);
if (options.controlsContainer) {
removeAttrs(controlsContainer, ['aria-label', 'tabindex']);
removeAttrs(controlsContainer.children, ['aria-controls', 'aria-disabled', 'tabindex']);
}
controlsContainer = prevButton = nextButton = null;
}
// nav
if (nav) {
removeEvents(navContainer, navEvents);
if (options.navContainer) {
removeAttrs(navContainer, ['aria-label']);
removeAttrs(navItems, ['aria-selected', 'aria-controls', 'tabindex']);
}
navContainer = navItems = null;
}
// auto
if (autoplay) {
clearInterval(autoplayTimer);
if (autoplayButton) {
removeEvents(autoplayButton, {'click': toggleAutoplay});
}
removeEvents(container, hoverEvents);
removeEvents(container, visibilityEvent);
if (options.autoplayButton) {
removeAttrs(autoplayButton, ['data-action']);
}
}
// container
container.id = containerIdCached || '';
container.className = container.className.replace(classContainer, '');
removeElementStyles(container);
if (carousel && TRANSITIONEND) {
var eve = {};
eve[TRANSITIONEND] = onTransitionEnd;
removeEvents(container, eve);
}
removeEvents(container, touchEvents);
removeEvents(container, dragEvents);
// outerWrapper
containerParent.insertBefore(container, outerWrapper);
outerWrapper.remove();
outerWrapper = innerWrapper = container =
index = indexCached = items = slideBy = navCurrentIndex = <API key> = hasControls = visibleNavIndexes = <API key> =
this.getInfo = this.events = this.goTo = this.play = this.pause = this.destroy = null;
this.isOn = isOn = false;
}
};
};
return tns;
})(); |
<?php
namespace Composer\Package\Archiver;
use Symfony\Component\Finder;
/**
* @author Nils Adermann <naderman@naderman.de>
*/
abstract class BaseExcludeFilter
{
/**
* @var string
*/
protected $sourcePath;
/**
* @var array
*/
protected $excludePatterns;
/**
* @param string $sourcePath Directory containing sources to be filtered
*/
public function __construct($sourcePath)
{
$this->sourcePath = $sourcePath;
$this->excludePatterns = array();
}
/**
* Checks the given path against all exclude patterns in this filter
*
* Negated patterns overwrite exclude decisions of previous filters.
*
* @param string $relativePath The file's path relative to the sourcePath
* @param bool $exclude Whether a previous filter wants to exclude this file
*
* @return bool Whether the file should be excluded
*/
public function filter($relativePath, $exclude)
{
foreach ($this->excludePatterns as $patternData) {
list($pattern, $negate, $stripLeadingSlash) = $patternData;
if ($stripLeadingSlash) {
$path = substr($relativePath, 1);
} else {
$path = $relativePath;
}
if (preg_match($pattern, $path)) {
$exclude = !$negate;
}
}
return $exclude;
}
/**
* Processes a file containing exclude rules of different formats per line
*
* @param array $lines A set of lines to be parsed
* @param callback $lineParser The parser to be used on each line
*
* @return array Exclude patterns to be used in filter()
*/
protected function parseLines(array $lines, $lineParser)
{
return array_filter(
array_map(
function ($line) use ($lineParser) {
$line = trim($line);
$commentHash = strpos($line, '
if ($commentHash !== false) {
$line = substr($line, 0, $commentHash);
}
if ($line) {
return call_user_func($lineParser, $line);
}
return null;
}, $lines),
function ($pattern) {
return $pattern !== null;
}
);
}
/**
* Generates a set of exclude patterns for filter() from gitignore rules
*
* @param array $rules A list of exclude rules in gitignore syntax
*
* @return array Exclude patterns
*/
protected function generatePatterns($rules)
{
$patterns = array();
foreach ($rules as $rule) {
$patterns[] = $this->generatePattern($rule);
}
return $patterns;
}
/**
* Generates an exclude pattern for filter() from a gitignore rule
*
* @param string $rule An exclude rule in gitignore syntax
*
* @return array An exclude pattern
*/
protected function generatePattern($rule)
{
$negate = false;
$pattern = '
if (strlen($rule) && $rule[0] === '!') {
$negate = true;
$rule = substr($rule, 1);
}
if (strlen($rule) && $rule[0] === '/') {
$pattern .= '^/';
$rule = substr($rule, 1);
} elseif (false === strpos($rule, '/') || strlen($rule) - 1 === strpos($rule, '/')) {
$pattern .= '/';
}
$pattern .= substr(Finder\Glob::toRegex($rule), 2, -2);
return array($pattern . '#', $negate, false);
}
} |
function dec(target, name, descriptor) {
assert(target);
assert.equal(typeof name, "string");
assert.equal(typeof descriptor, "object");
target.decoratedProps = (target.decoratedProps || []).concat([name]);
let value = descriptor.value;
Object.assign(descriptor, {
enumerable: name.indexOf("enum") !== -1,
configurable: name.indexOf("conf") !== -1,
writable: name.indexOf("write") !== -1,
value: function(...args) {
return "__" + value.apply(this, args) + "__";
},
});
}
const inst = {
@dec
enumconfwrite(){
return 1;
},
@dec
enumconf(){
return 2;
},
@dec
enumwrite(){
return 3;
},
@dec
enum(){
return 4;
},
@dec
confwrite(){
return 5;
},
@dec
conf(){
return 6;
},
@dec
write(){
return 7;
},
@dec
_(){
return 8;
},
}
assert(inst.hasOwnProperty('decoratedProps'));
assert.deepEqual(inst.decoratedProps, [
"enumconfwrite",
"enumconf",
"enumwrite",
"enum",
"confwrite",
"conf",
"write",
"_",
]);
const descs = Object.<API key>(inst);
assert(descs.enumconfwrite.enumerable);
assert(descs.enumconfwrite.writable);
assert(descs.enumconfwrite.configurable);
assert.equal(inst.enumconfwrite(), "__1__");
assert(descs.enumconf.enumerable);
assert.equal(descs.enumconf.writable, false);
assert(descs.enumconf.configurable);
assert.equal(inst.enumconf(), "__2__");
assert(descs.enumwrite.enumerable);
assert(descs.enumwrite.writable);
assert.equal(descs.enumwrite.configurable, false);
assert.equal(inst.enumwrite(), "__3__");
assert(descs.enum.enumerable);
assert.equal(descs.enum.writable, false);
assert.equal(descs.enum.configurable, false);
assert.equal(inst.enum(), "__4__");
assert.equal(descs.confwrite.enumerable, false);
assert(descs.confwrite.writable);
assert(descs.confwrite.configurable);
assert.equal(inst.confwrite(), "__5__");
assert.equal(descs.conf.enumerable, false);
assert.equal(descs.conf.writable, false);
assert(descs.conf.configurable);
assert.equal(inst.conf(), "__6__");
assert.equal(descs.write.enumerable, false);
assert(descs.write.writable);
assert.equal(descs.write.configurable, false);
assert.equal(inst.write(), "__7__");
assert.equal(descs._.enumerable, false);
assert.equal(descs._.writable, false);
assert.equal(descs._.configurable, false);
assert.equal(inst._(), "__8__"); |
import chainer
from chainer import backend
from chainer import utils
def sign(x):
"""Elementwise sign function.
For a given input :math:`x`, this function returns :math:`sgn(x)`
defined as
.. math::
sgn(x) = \\left \\{ \\begin{array}{cc}
-1 & {\\rm if~x < 0} \\\\
0 & {\\rm if~x = 0} \\\\
1 & {\\rm if~x > 0} \\\\
\\end{array} \\right.
.. note::
The gradient of this function is ``None`` everywhere and therefore
unchains the computational graph.
Args:
x (:class:`~chainer.Variable` or :ref:`ndarray`):
Input variable for which the sign is computed.
Returns:
~chainer.Variable: Output variable.
"""
if isinstance(x, chainer.variable.Variable):
x = x.array
xp = backend.get_array_module(x)
return chainer.as_variable(utils.force_array(xp.sign(x))) |
function lisp(hljs) {
var LISP_IDENT_RE = '[a-zA-Z_\\-+\\*\\/<=>&#][a-zA-Z0-9_\\-+*\\/<=>&#!]*';
var MEC_RE = '\\|[^]*?\\|';
var <API key> = '(-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|-)?\\d+)?';
var LITERAL = {
className: 'literal',
begin: '\\b(t{1}|nil)\\b'
};
var NUMBER = {
className: 'number',
variants: [
{begin: <API key>, relevance: 0},
{begin: '#(b|B)[0-1]+(/[0-1]+)?'},
{begin: '#(o|O)[0-7]+(/[0-7]+)?'},
{begin: '#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?'},
{begin: '#(c|C)\\(' + <API key> + ' +' + <API key>, end: '\\)'}
]
};
var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null});
var COMMENT = hljs.COMMENT(
';', '$',
{
relevance: 0
}
);
var VARIABLE = {
begin: '\\*', end: '\\*'
};
var KEYWORD = {
className: 'symbol',
begin: '[:&]' + LISP_IDENT_RE
};
var IDENT = {
begin: LISP_IDENT_RE,
relevance: 0
};
var MEC = {
begin: MEC_RE
};
var QUOTED_LIST = {
begin: '\\(', end: '\\)',
contains: ['self', LITERAL, STRING, NUMBER, IDENT]
};
var QUOTED = {
contains: [NUMBER, STRING, VARIABLE, KEYWORD, QUOTED_LIST, IDENT],
variants: [
{
begin: '[\'`]\\(', end: '\\)'
},
{
begin: '\\(quote ', end: '\\)',
keywords: {name: 'quote'}
},
{
begin: '\'' + MEC_RE
}
]
};
var QUOTED_ATOM = {
variants: [
{begin: '\'' + LISP_IDENT_RE},
{begin: '#\'' + LISP_IDENT_RE + '(::' + LISP_IDENT_RE + ')*'}
]
};
var LIST = {
begin: '\\(\\s*', end: '\\)'
};
var BODY = {
endsWithParent: true,
relevance: 0
};
LIST.contains = [
{
className: 'name',
variants: [
{
begin: LISP_IDENT_RE,
relevance: 0,
},
{begin: MEC_RE}
]
},
BODY
];
BODY.contains = [QUOTED, QUOTED_ATOM, LIST, LITERAL, NUMBER, STRING, COMMENT, VARIABLE, KEYWORD, MEC, IDENT];
return {
name: 'Lisp',
illegal: /\S/,
contains: [
NUMBER,
hljs.SHEBANG(),
LITERAL,
STRING,
COMMENT,
QUOTED,
QUOTED_ATOM,
LIST,
IDENT
]
};
}
module.exports = lisp; |
#ifndef __RTA_STORE_CMD_H__
#define __RTA_STORE_CMD_H__
extern enum rta_sec_era rta_sec_era;
static const uint32_t store_src_table[][2] = {
{ KEY1SZ, LDST_CLASS_1_CCB | <API key> },
{ KEY2SZ, LDST_CLASS_2_CCB | <API key> },
{ DJQDA, LDST_CLASS_DECO | <API key> },
{ MODE1, LDST_CLASS_1_CCB | <API key> },
{ MODE2, LDST_CLASS_2_CCB | <API key> },
{ DJQCTRL, LDST_CLASS_DECO | <API key> },
{ DATA1SZ, LDST_CLASS_1_CCB | <API key> },
{ DATA2SZ, LDST_CLASS_2_CCB | <API key> },
{ DSTAT, LDST_CLASS_DECO | <API key> },
{ ICV1SZ, LDST_CLASS_1_CCB | <API key> },
{ ICV2SZ, LDST_CLASS_2_CCB | <API key> },
{ DPID, LDST_CLASS_DECO | <API key> },
{ CCTRL, <API key> },
{ ICTRL, <API key> },
{ CLRW, <API key> },
{ MATH0, LDST_CLASS_DECO | <API key> },
{ CSTAT, <API key> },
{ MATH1, LDST_CLASS_DECO | <API key> },
{ MATH2, LDST_CLASS_DECO | <API key> },
{ AAD1SZ, LDST_CLASS_1_CCB | <API key> },
{ MATH3, LDST_CLASS_DECO | <API key> },
{ IV1SZ, LDST_CLASS_1_CCB | <API key> },
{ PKASZ, LDST_CLASS_1_CCB | <API key> },
{ PKBSZ, LDST_CLASS_1_CCB | <API key> },
{ PKESZ, LDST_CLASS_1_CCB | <API key> },
{ PKNSZ, LDST_CLASS_1_CCB | <API key> },
{ CONTEXT1, LDST_CLASS_1_CCB | <API key> },
{ CONTEXT2, LDST_CLASS_2_CCB | <API key> },
{ DESCBUF, LDST_CLASS_DECO | <API key> },
{ JOBDESCBUF, LDST_CLASS_DECO | <API key> },
{ SHAREDESCBUF, LDST_CLASS_DECO | <API key> },
{ JOBDESCBUF_EFF, LDST_CLASS_DECO |
<API key> },
{ SHAREDESCBUF_EFF, LDST_CLASS_DECO |
<API key> },
{ GTR, LDST_CLASS_DECO | <API key> },
{ STR, LDST_CLASS_DECO | <API key> }
};
/*
* Allowed STORE sources for each SEC ERA.
* Values represent the number of entries from source_src_table[] that are
* supported.
*/
static const unsigned int store_src_table_sz[] = {29, 31, 33, 33,
33, 33, 35, 35,
35, 35};
static inline int
rta_store(struct program *program, uint64_t src,
uint16_t offset, uint64_t dst, uint32_t length,
uint32_t flags)
{
uint32_t opcode = 0, val;
int ret = -EINVAL;
unsigned int start_pc = program->current_pc;
if (flags & SEQ)
opcode = CMD_SEQ_STORE;
else
opcode = CMD_STORE;
/* parameters check */
if ((flags & IMMED) && (flags & SGF)) {
pr_err("STORE: Invalid flag. SEC PC: %d; Instr: %d\n",
program->current_pc, program->current_instruction);
goto err;
}
if ((flags & IMMED) && (offset != 0)) {
pr_err("STORE: Invalid flag. SEC PC: %d; Instr: %d\n",
program->current_pc, program->current_instruction);
goto err;
}
if ((flags & SEQ) && ((src == JOBDESCBUF) || (src == SHAREDESCBUF) ||
(src == JOBDESCBUF_EFF) ||
(src == SHAREDESCBUF_EFF))) {
pr_err("STORE: Invalid SRC type. SEC PC: %d; Instr: %d\n",
program->current_pc, program->current_instruction);
goto err;
}
if (flags & IMMED)
opcode |= LDST_IMM;
if ((flags & SGF) || (flags & VLF))
opcode |= LDST_VLF;
/*
* source for data to be stored can be specified as:
* - register location; set in src field[9-15];
* - if IMMED flag is set, data is set in value field [0-31];
* user can give this value as actual value or pointer to data
*/
if (!(flags & IMMED)) {
ret = __rta_map_opcode((uint32_t)src, store_src_table,
store_src_table_sz[rta_sec_era], &val);
if (ret < 0) {
pr_err("STORE: Invalid source. SEC PC: %d; Instr: %d\n",
program->current_pc,
program->current_instruction);
goto err;
}
opcode |= val;
}
/* DESC BUFFER: length / offset values are specified in 4-byte words */
if ((src == DESCBUF) || (src == JOBDESCBUF) || (src == SHAREDESCBUF) ||
(src == JOBDESCBUF_EFF) || (src == SHAREDESCBUF_EFF)) {
opcode |= (length >> 2);
opcode |= (uint32_t)((offset >> 2) << LDST_OFFSET_SHIFT);
} else {
opcode |= length;
opcode |= (uint32_t)(offset << LDST_OFFSET_SHIFT);
}
__rta_out32(program, opcode);
program->current_instruction++;
if ((src == JOBDESCBUF) || (src == SHAREDESCBUF) ||
(src == JOBDESCBUF_EFF) || (src == SHAREDESCBUF_EFF))
return (int)start_pc;
/* for STORE, a pointer to where the data will be stored if needed */
if (!(flags & SEQ))
__rta_out64(program, program->ps, dst);
/* for IMMED data, place the data here */
if (flags & IMMED)
__rta_inline_data(program, src, flags & __COPY_MASK, length);
return (int)start_pc;
err:
program->first_error_pc = start_pc;
program->current_instruction++;
return ret;
}
#endif /* __RTA_STORE_CMD_H__ */ |
/**
* WikimediaUI Base v0.10.0
* Wikimedia Foundation user interface base variables
*/
.oo-ui-tool {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.oo-ui-tool.oo-ui-widget > .oo-ui-tool-link > .oo-ui-iconWidget.<API key>.<API key> {
display: none;
}
.oo-ui-tool .oo-ui-tool-link {
position: relative;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding-top: 3em;
padding-left: 3em;
}
.<API key> .oo-ui-tool .oo-ui-tool-link {
padding-left: 2.85714286em;
}
.<API key> .oo-ui-tool-link {
padding: 1em 0.85714286em 0.92857143em 2.64285714em;
}
.oo-ui-tool.oo-ui-iconElement .<API key> {
display: block;
left: 0.78571429em;
}
.<API key> .oo-ui-tool.oo-ui-iconElement .<API key> {
left: 0.71428571em;
}
.oo-ui-tool .oo-ui-tool-title {
line-height: 1.07142857em;
}
.oo-ui-tool.<API key> {
-webkit-transition: background-color 100ms;
-moz-transition: background-color 100ms;
transition: background-color 100ms;
}
.oo-ui-tool.<API key> .oo-ui-tool-link:focus {
outline: 1px solid #36c;
box-shadow: inset 0 0 0 1px #36c;
z-index: 1;
}
.oo-ui-tool.<API key> .<API key> {
opacity: 0.87;
-webkit-transition: opacity 100ms;
-moz-transition: opacity 100ms;
transition: opacity 100ms;
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
.oo-ui-tool.<API key> .oo-ui-tool-title {
-webkit-transition: color 100ms;
-moz-transition: color 100ms;
transition: color 100ms;
}
.oo-ui-tool.<API key>:hover .<API key> {
opacity: 1;
}
.oo-ui-tool.<API key>[class*='<API key>'] .<API key> {
opacity: 1;
}
.oo-ui-tool.<API key> .<API key> {
opacity: 0.34;
}
.<API key> .<API key>,
.<API key> .<API key> {
z-index: 4;
}
.oo-ui-toolGroupTool > .oo-ui-toolGroup {
border-right: 0;
}
.oo-ui-toolGroup {
display: inline-block;
vertical-align: middle;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
border-right: 1px solid #eaecf0;
}
.<API key> {
display: none;
}
.<API key> .oo-ui-tool-link {
text-decoration: none;
cursor: pointer;
}
.<API key>.<API key> .oo-ui-tool-link,
.<API key> .<API key> > .oo-ui-tool-link {
outline: 0;
cursor: default;
}
.<API key> .oo-ui-toolGroup {
border-right: 0;
border-left: 1px solid #eaecf0;
}
.<API key> .oo-ui-toolGroup.oo-ui-barToolGroup {
border-right-width: 0;
}
.oo-ui-toolGroup.<API key> .<API key>,
.oo-ui-toolGroup.<API key> .<API key> {
opacity: 0.34 !important;
}
.<API key> > .oo-ui-tool {
display: inline-block;
position: relative;
vertical-align: top;
}
.<API key> > .oo-ui-tool > .oo-ui-tool-link {
display: block;
}
.<API key> > .oo-ui-tool > .oo-ui-tool-link .oo-ui-tool-accel {
display: none;
}
.<API key> > .oo-ui-tool.oo-ui-iconElement > .oo-ui-tool-link .oo-ui-tool-title {
display: none;
}
.<API key> > .oo-ui-tool.oo-ui-iconElement.<API key> > .oo-ui-tool-link .oo-ui-tool-title {
display: inline-block;
}
.<API key> > .oo-ui-tool.iconElement > .oo-ui-tool-link > .<API key> {
display: block;
}
.<API key> > .oo-ui-tool + .oo-ui-tool {
margin-left: -2px;
}
.<API key>.<API key> > .oo-ui-tool:not( .oo-ui-toolGroupTool ).<API key>:hover {
background-color: #eaecf0;
}
.<API key>.<API key> > .oo-ui-tool:not( .oo-ui-toolGroupTool ).<API key> > .oo-ui-tool-link .oo-ui-tool-title {
color: #222;
-webkit-transition: color 100ms;
-moz-transition: color 100ms;
transition: color 100ms;
}
.<API key>.<API key> > .oo-ui-tool:not( .oo-ui-toolGroupTool ).oo-ui-tool-active {
background-color: #eaf3ff;
}
.<API key>.<API key> > .oo-ui-tool:not( .oo-ui-toolGroupTool ).oo-ui-tool-active:hover {
background-color: rgba(41, 98, 204, 0.1);
}
.<API key>.<API key> > .oo-ui-tool:not( .oo-ui-toolGroupTool ).oo-ui-tool-active > .oo-ui-tool-link .oo-ui-tool-title {
color: #36c;
}
.<API key>.<API key> .oo-ui-tool.<API key> > .oo-ui-tool-link .oo-ui-tool-title,
.<API key>.<API key> .oo-ui-tool > .oo-ui-tool-link .oo-ui-tool-title {
color: #72777d;
}
.<API key> {
position: relative;
min-width: 3em;
}
.<API key> {
display: block;
cursor: pointer;
}
.<API key> .<API key>:not( :empty ) {
display: inline-block;
}
.<API key>.<API key> .<API key> {
outline: 0;
cursor: default;
}
.<API key> {
display: none;
position: absolute;
z-index: 4;
}
.<API key>.<API key> {
display: block;
}
.<API key> .oo-ui-tool-link {
display: table;
width: 100%;
vertical-align: middle;
white-space: nowrap;
}
.<API key> .oo-ui-tool-link .oo-ui-tool-accel,
.<API key> .oo-ui-tool-link .oo-ui-tool-title {
display: table-cell;
vertical-align: middle;
}
.<API key> .oo-ui-tool-link .oo-ui-tool-accel {
text-align: right;
}
.<API key> .<API key> {
min-width: 2.85714286em;
}
.<API key>.<API key>:not( .oo-ui-labelElement ):not( .oo-ui-iconElement ) {
min-width: 1.85714286em;
}
.<API key> {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.<API key> .<API key> {
left: 0.78571429em;
}
.<API key> .<API key> .<API key> {
left: 0.64285714em;
}
.<API key> .<API key> {
background-position: center 52%;
right: 0.57142857em;
}
.<API key> .<API key> .<API key> {
right: 0.28571429em;
}
.<API key>.oo-ui-iconElement .<API key>,
.<API key>.<API key> .<API key> {
padding-top: 3em;
}
.<API key>.oo-ui-iconElement.<API key> .<API key> {
padding-left: 3em;
}
.<API key> .<API key>.oo-ui-iconElement.<API key> .<API key> {
padding-left: 2.85714286em;
}
.<API key>.oo-ui-labelElement .<API key> {
padding: 1em 0.85714286em 0.92857143em;
}
.<API key>.oo-ui-labelElement .<API key> .<API key> {
line-height: 1.07142857em;
}
.<API key> .<API key>.oo-ui-labelElement .<API key> {
padding-left: 0.71428571em;
padding-right: 0.71428571em;
}
.<API key>.oo-ui-iconElement.oo-ui-labelElement .<API key> {
padding-left: 2.64285714em;
}
.<API key> .<API key>.oo-ui-iconElement.oo-ui-labelElement .<API key> {
padding-left: 2.5em;
}
.<API key>.oo-ui-labelElement.<API key> .<API key> {
padding-right: 1.85714286em;
}
.<API key> .<API key>.oo-ui-labelElement.<API key> .<API key> {
padding-right: 1.28571429em;
}
.<API key>.<API key> .<API key> {
padding-right: 1.14285714em;
}
.<API key> .<API key>.<API key> .<API key> {
padding-right: 0.85714286em;
}
.<API key>:not( .oo-ui-labelElement ):not( .oo-ui-iconElement ) .<API key> {
opacity: 1;
}
.<API key> {
color: #72777d;
padding: 0 0.85714286em;
font-weight: bold;
line-height: 2.28571429em;
}
.<API key> .<API key> {
padding: 0 0.71428571em;
}
.<API key> {
background-color: #fff;
min-width: 16em;
margin: 0 -1px;
border: 1px solid #c8ccd1;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.25);
}
.<API key> .oo-ui-tool-link {
padding: 1em 0.85714286em 0.92857143em 0.85714286em;
}
.<API key> .<API key> .oo-ui-tool-link {
padding-left: 0.71428571em;
padding-right: 0.71428571em;
}
.<API key> .oo-ui-tool-link .oo-ui-tool-title {
color: #222;
}
.<API key> .oo-ui-tool-link .oo-ui-tool-accel {
color: #72777d;
line-height: 1.07142857em;
}
.<API key> .oo-ui-tool-link .oo-ui-tool-accel:not( :empty ) {
padding-left: 1.28571429em;
}
.<API key> .<API key> .oo-ui-tool-link .oo-ui-tool-accel:not( :empty ) {
padding-left: 1.14285714em;
}
.<API key> .oo-ui-iconElement .oo-ui-tool-link {
padding-left: 2.64285714em;
}
.<API key> .<API key> .oo-ui-iconElement .oo-ui-tool-link {
padding-left: 2.5em;
}
.<API key>.<API key> > .<API key> {
-webkit-transition: background-color 100ms, box-shadow 100ms;
-moz-transition: background-color 100ms, box-shadow 100ms;
transition: background-color 100ms, box-shadow 100ms;
}
.<API key>.<API key> > .<API key>:hover {
background-color: #eaecf0;
}
.<API key>.<API key> > .<API key>:active {
background-color: #eaf3ff;
}
.<API key>.<API key> > .<API key> .<API key>,
.<API key>.<API key> > .<API key> .<API key> {
opacity: 0.87;
-webkit-transition: opacity 100ms;
-moz-transition: opacity 100ms;
transition: opacity 100ms;
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
.<API key>.<API key> > .<API key>:hover .<API key>,
.<API key>.<API key> > .<API key>:active .<API key>,
.<API key>.<API key> > .<API key>:hover .<API key>,
.<API key>.<API key> > .<API key>:active .<API key> {
opacity: 1;
}
.<API key>.<API key> > .<API key>:focus {
outline: 1px solid #36c;
box-shadow: inset 0 0 0 1px #36c;
}
.<API key>.<API key>[class*='<API key>'] > .<API key> .<API key>,
.<API key>.<API key>[class*='<API key>'] > .<API key>:hover .<API key> {
opacity: 1;
}
.<API key> .<API key>.<API key> > .<API key> {
border-right: 1px solid transparent;
-webkit-transition: border-color 100ms;
-moz-transition: border-color 100ms;
transition: border-color 100ms;
}
.<API key> .<API key>.<API key> > .<API key>:hover {
border-right-color: #eaecf0;
}
.<API key> .<API key>.<API key> > .<API key>:active {
border-right-color: #eaf3ff;
}
.<API key> .<API key>.<API key> > .<API key>:focus {
border-right-color: #36c;
}
.<API key>.<API key> > .<API key> {
background-color: #eaf3ff;
color: #36c;
}
.<API key>.<API key> > .<API key>:hover {
background-color: rgba(41, 98, 204, 0.1);
color: #36c;
}
.<API key> .oo-ui-tool-active.<API key> .oo-ui-tool-link .oo-ui-tool-title {
color: #36c;
}
.<API key> .oo-ui-tool.<API key> .oo-ui-tool-link:focus {
outline: 0;
box-shadow: inset 0 0 0 2px #36c;
}
.<API key> .oo-ui-tool {
display: block;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.<API key> .oo-ui-tool.<API key>:hover {
background-color: #eaecf0;
color: #000;
}
.<API key> .oo-ui-tool-active.<API key> {
background-color: #eaf3ff;
}
.<API key> .oo-ui-tool-active.<API key>:hover {
background-color: rgba(41, 98, 204, 0.1);
}
.<API key> .oo-ui-tool-active.<API key> .oo-ui-tool-link .oo-ui-tool-title {
color: #36c;
}
.oo-ui-listToolGroup.<API key>,
.<API key> .oo-ui-tool.<API key> .oo-ui-tool-title {
color: #72777d;
}
.<API key> .oo-ui-tool {
display: block;
}
.oo-ui-menuToolGroup .<API key> {
min-width: 140px;
}
.<API key> .oo-ui-menuToolGroup .<API key> {
min-width: 100px;
}
.<API key> .oo-ui-tool-link .<API key> {
left: 0.78571429em;
}
.<API key> .<API key> .oo-ui-tool-link .<API key> {
left: 0.71428571em;
}
.<API key> .oo-ui-tool.<API key>:hover {
background-color: rgba(41, 98, 204, 0.1);
}
.<API key> .oo-ui-tool.oo-ui-tool-active {
background-color: #eaf3ff;
}
.oo-ui-menuToolGroup.<API key>,
.<API key> .oo-ui-tool.<API key> .oo-ui-tool-title {
color: #72777d;
}
.oo-ui-toolbar {
clear: both;
}
.oo-ui-toolbar-bar {
line-height: 1;
position: relative;
}
.oo-ui-toolbar-tools,
.<API key> {
-<API key>: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.oo-ui-toolbar-tools {
display: inline;
}
.<API key> {
position: absolute;
}
.oo-ui-toolbar-tools,
.<API key> {
white-space: nowrap;
}
.oo-ui-toolbar-tools .oo-ui-tool,
.<API key> .oo-ui-tool,
.oo-ui-toolbar-tools .<API key>,
.<API key> .<API key> {
white-space: normal;
}
.<API key> .oo-ui-toolbar-tools,
.<API key>.<API key> {
white-space: normal;
}
.<API key> {
float: right;
}
.<API key> .oo-ui-toolbar,
.<API key> .oo-ui-buttonElement.oo-ui-labelElement > input.<API key>,
.<API key> .oo-ui-buttonElement.oo-ui-labelElement > .<API key> > .<API key> {
display: inline-block;
}
.<API key> .oo-ui-popupWidget {
-<API key>: default;
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
user-select: text;
}
.oo-ui-toolbar-bar {
background-color: #fff;
color: #222;
}
.<API key> > .oo-ui-toolbar-bar {
border-bottom: 1px solid #c8ccd1;
box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.1);
}
.<API key> > .oo-ui-toolbar-bar {
border-top: 1px solid #c8ccd1;
box-shadow: 0 -1px 1px 0 rgba(0, 0, 0, 0.1);
}
.oo-ui-toolbar-bar .oo-ui-toolbar-bar {
background-color: transparent;
border: 0;
box-shadow: none;
}
.<API key>:after {
content: '';
display: block;
position: absolute;
top: 3em;
left: 0;
width: 100%;
height: 0;
}
.<API key>.<API key> .oo-ui-toolbar-bar:after {
border-bottom: 1px solid #c8ccd1;
}
.<API key>.<API key> .oo-ui-toolbar-bar:after {
border-top: 1px solid #c8ccd1;
}
.<API key> > .oo-ui-buttonElement {
margin-right: 0;
}
.<API key> > .oo-ui-buttonElement > .<API key> {
border: 0;
border-radius: 0;
padding-top: 3em;
padding-left: 1.14285714em;
padding-right: 1.14285714em;
}
.<API key> .<API key> > .oo-ui-buttonElement > .<API key> {
padding-left: 0.85714286em;
padding-right: 0.85714286em;
}
.<API key> > .oo-ui-buttonElement.<API key>.<API key>.<API key> > .<API key>:focus {
box-shadow: inset 0 0 0 2px #36c, inset 0 0 0 3px #fff;
}
.<API key> > .oo-ui-buttonElement.oo-ui-labelElement > .<API key> {
padding-top: 1em;
padding-bottom: 0.92857143em;
}
.<API key> > .<API key> > .oo-ui-buttonElement > .<API key> {
border-radius: 0;
border-width: 0 0 0 1px;
padding-top: 1em;
padding-bottom: 0.92857143em;
}
.<API key> > .<API key> > .<API key>.<API key>.<API key>.<API key> > .<API key> {
color: #fff;
background-color: #36c;
border-color: #36c;
}
.<API key> > .<API key> > .<API key>.<API key>.<API key>.<API key> > .<API key>:hover {
background-color: #447ff5;
border-color: #447ff5;
}
.<API key> > .<API key> > .<API key>.<API key>.<API key>.<API key> > .<API key>:active,
.<API key> > .<API key> > .<API key>.<API key>.<API key>.<API key> > .<API key>:active:focus,
.<API key> > .<API key> > .<API key>.<API key>.<API key>.<API key>.<API key> > .<API key>,
.<API key> > .<API key> > .<API key>.<API key>.<API key>.<API key>.<API key> > .<API key>,
.<API key> > .<API key> > .<API key>.<API key>.<API key>.<API key>.<API key> > .<API key> {
color: #fff;
background-color: #2a4b8d;
border-color: #2a4b8d;
box-shadow: none;
}
.<API key> > .<API key> > .<API key>.<API key>.<API key>.<API key> > .<API key>:focus {
border-color: #36c;
box-shadow: inset 0 0 0 1px #36c, inset 0 0 0 2px #fff;
} |
define(
//begin v1.x content
{
"<API key>+0": "detta kv.",
"<API key>+1": "nästa kv.",
"field-tue-relative+-1": "tisdag förra veckan",
"field-year": "år",
"field-wed-relative+0": "onsdag denna vecka",
"field-wed-relative+1": "onsdag nästa vecka",
"field-minute": "minut",
"<API key>+-1": "förra mån.",
"<API key>+0": "denna tis.",
"<API key>+1": "nästa tis.",
"<API key>+0": "tors. denna vecka",
"<API key>+-1": "i går",
"<API key>+1": "tors. nästa vecka",
"field-day-relative+0": "i dag",
"<API key>+-2": "i förrgår",
"field-day-relative+1": "i morgon",
"<API key>+0": "denna v.",
"field-day-relative+2": "i övermorgon",
"<API key>+1": "nästa v.",
"<API key>+-1": "förra ons.",
"field-year-narrow": "år",
"field-era-short": "era",
"<API key>+0": "i år",
"field-tue-relative+0": "tisdag denna vecka",
"<API key>+1": "nästa år",
"field-tue-relative+1": "tisdag nästa vecka",
"<API key>": "veckodag i månad",
"field-second-short": "sek",
"<API key>": "veckodag i mån.",
"field-week-relative+0": "denna vecka",
"<API key>+0": "denna månad",
"field-week-relative+1": "nästa vecka",
"<API key>+1": "nästa månad",
"<API key>+0": "denna sön.",
"<API key>+0": "mån. denna vecka",
"<API key>+1": "nästa sön.",
"<API key>+1": "mån. nästa vecka",
"<API key>+0": "nu",
"field-weekOfMonth": "vecka i månaden",
"field-month-short": "m",
"field-day": "dag",
"<API key>": "dag under året",
"field-year-relative+-1": "i fjol",
"<API key>+-1": "lör. förra veckan",
"field-hour-relative+0": "denna timme",
"<API key>+0": "nu",
"field-wed-relative+-1": "onsdag förra veckan",
"<API key>+-1": "förra lör.",
"field-second": "sekund",
"<API key>+0": "denna timme",
"field-quarter": "kvartal",
"field-week-short": "v",
"<API key>+0": "idag",
"<API key>+1": "imorgon",
"<API key>+2": "i övermorgon",
"<API key>+0": "tis. denna vecka",
"<API key>+1": "tis. nästa vecka",
"<API key>+-1": "förra mån.",
"field-mon-relative+-1": "måndag förra veckan",
"field-month": "månad",
"field-day-narrow": "dag",
"field-minute-short": "min",
"field-dayperiod": "fm/em",
"<API key>+0": "lör. denna vecka",
"<API key>+1": "lör. nästa vecka",
"field-second-narrow": "s",
"field-mon-relative+0": "måndag denna vecka",
"field-mon-relative+1": "måndag nästa vecka",
"<API key>+-1": "igår",
"field-year-short": "år",
"<API key>+-2": "i förrgår",
"<API key>+-1": "förra kvartalet",
"<API key>": "fm/em",
"<API key>+-1": "förra v.",
"field-dayOfYear": "dag under året",
"field-sat-relative+-1": "lördag förra veckan",
"field-hour": "timme",
"<API key>+0": "denna minut",
"<API key>+-1": "förra månaden",
"field-quarter-short": "kv.",
"<API key>+0": "denna lör.",
"field-fri-relative+0": "fredag denna vecka",
"<API key>+1": "nästa lör.",
"field-fri-relative+1": "fredag nästa vecka",
"<API key>+0": "denna mån.",
"<API key>+1": "nästa mån.",
"<API key>+0": "sön. denna vecka",
"<API key>+1": "sön. nästa vecka",
"field-week-relative+-1": "förra veckan",
"<API key>+-1": "förra kv.",
"<API key>+0": "denna minut",
"<API key>+0": "detta kvartal",
"<API key>+0": "denna minut",
"<API key>+1": "nästa kvartal",
"<API key>+-1": "ons. förra veckan",
"<API key>+-1": "tors. förra veckan",
"<API key>+-1": "i fjol",
"<API key>+-1": "förra tors.",
"<API key>+-1": "förra tis.",
"<API key>": "vk. i mån.",
"<API key>+0": "ons. denna vecka",
"<API key>+1": "ons. nästa vecka",
"field-sun-relative+-1": "söndag förra veckan",
"<API key>+0": "nu",
"field-weekday": "veckodag",
"<API key>+0": "i dag",
"<API key>+0": "detta kv.",
"field-sat-relative+0": "lördag denna vecka",
"<API key>+1": "i morgon",
"<API key>+1": "nästa kv.",
"field-sat-relative+1": "lördag nästa vecka",
"<API key>+2": "i övermorgon",
"<API key>+0": "denna v.",
"<API key>+1": "nästa v.",
"<API key>": "dag under året",
"<API key>+0": "denna mån.",
"<API key>+1": "nästa mån.",
"<API key>": "veckodag i mån.",
"field-zone-narrow": "tidszon",
"<API key>+0": "denna tors.",
"<API key>+1": "nästa tors.",
"<API key>+-1": "förra sön.",
"<API key>+-1": "mån. förra veckan",
"field-thu-relative+0": "torsdag denna vecka",
"field-thu-relative+1": "torsdag nästa vecka",
"<API key>+-1": "fre. förra veckan",
"field-thu-relative+-1": "torsdag förra veckan",
"field-week": "vecka",
"<API key>+0": "denna ons.",
"<API key>+1": "nästa ons.",
"<API key>+-1": "förra kv.",
"<API key>+0": "i år",
"<API key>": "fm/em",
"<API key>+1": "nästa år",
"<API key>+0": "fre. denna vecka",
"<API key>+1": "fre. nästa vecka",
"<API key>+-1": "förra v.",
"<API key>+0": "denna timme",
"field-hour-short": "tim",
"field-zone-short": "tidszon",
"field-month-narrow": "mån",
"field-hour-narrow": "h",
"<API key>+-1": "förra fre.",
"field-year-relative+0": "i år",
"field-year-relative+1": "nästa år",
"field-era-narrow": "era",
"field-fri-relative+-1": "fredag förra veckan",
"<API key>+-1": "tis. förra veckan",
"field-minute-narrow": "m",
"<API key>+-1": "i fjol",
"field-zone": "tidszon",
"<API key>": "vk.i mån.",
"<API key>": "veckodag",
"<API key>": "kv.",
"<API key>+-1": "sön. förra veckan",
"field-day-relative+-1": "i går",
"field-day-relative+-2": "i förrgår",
"field-weekday-short": "veckodag",
"field-sun-relative+0": "söndag denna vecka",
"field-sun-relative+1": "söndag nästa vecka",
"field-day-short": "dag",
"field-week-narrow": "v",
"field-era": "era",
"<API key>+0": "denna fre.",
"<API key>+1": "nästa fre."
}
//end v1.x content
); |
package org.openhab.binding.dsmr.internal.device;
import java.util.concurrent.<API key>;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.io.transport.serial.SerialPortManager;
import org.openhab.binding.dsmr.internal.device.connector.<API key>;
import org.openhab.binding.dsmr.internal.device.connector.DSMRSerialConnector;
import org.openhab.binding.dsmr.internal.device.connector.DSMRSerialSettings;
import org.openhab.binding.dsmr.internal.device.p1telegram.P1Telegram;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* DSMR Serial device that auto discovers the serial port speed.
*
* @author M. Volaart - Initial contribution
* @author Hilbrand Bouwkamp - New class. Simplified states and contains code specific to discover the serial port
* settings automatically.
*/
@NonNullByDefault
public class <API key> implements DSMRDevice, DSMREventListener {
/**
* Enum to keep track of the internal state of {@link <API key>}.
*/
enum DeviceState {
/**
* Discovers the settings of the serial port.
*/
DISCOVER_SETTINGS,
/**
* Device is receiving telegram data from the serial port.
*/
NORMAL,
/**
* Communication with serial port isn't working.
*/
ERROR
}
/**
* When switching baudrate ignore any errors received with the given time frame. Switching baudrate causes errors
* and should not be interpreted as reading errors.
*/
private static final long <API key> = TimeUnit.SECONDS.toNanos(5);
/**
* This factor is multiplied with the {@link #<API key>} and used as the duration the discovery
* of the baudrate may take.
*/
private static final int <API key> = 4;
/*
* Februari 2017
* Due to the Dutch Smart Meter program where every residence is provided
* a smart for free and the smart meters are DSMR V4 or higher
* we assume the majority of meters communicate with HIGH_SPEED_SETTINGS
* For older meters this means initializing is taking probably 1 minute
*/
private static final DSMRSerialSettings <API key> = DSMRSerialSettings.HIGH_SPEED_SETTINGS;
private final Logger logger = LoggerFactory.getLogger(<API key>.class);
/**
* DSMR Connector to the serial port
*/
private final DSMRSerialConnector dsmrConnector;
private final <API key> scheduler;
private final <API key> telegramListener;
/**
* Time in seconds in which period valid data is expected during discovery. If exceeded without success the baudrate
* is switched
*/
private final int <API key>;
/**
* Serial port connection settings
*/
private DSMRSerialSettings portSettings = <API key>;
/**
* Keeps track of the state this instance is in.
*/
private DeviceState state = DeviceState.NORMAL;
/**
* Timer for handling discovery of a single setting.
*/
private @Nullable ScheduledFuture<?> halfTimeTimer;
/**
* Timer for handling end of discovery.
*/
private @Nullable ScheduledFuture<?> endTimeTimer;
/**
* The listener of the class handling the connector events
*/
private DSMREventListener parentListener;
/**
* Time in nanos the last time the baudrate was switched. This is used during discovery ignore errors retrieved
* after switching baudrate for the period set in {@link #<API key>}.
*/
private long <API key>;
/**
* Creates a new {@link <API key>}
*
* @param serialPortManager the manager to get a new serial port connecting from
* @param serialPortName the port name (e.g. /dev/ttyUSB0 or COM1)
* @param listener the parent {@link DSMREventListener}
* @param scheduler the scheduler to use with the baudrate switching timers
* @param <API key> timeout period for when to try other baudrate settings and end the discovery
* of the baudrate
*/
public <API key>(SerialPortManager serialPortManager, String serialPortName, DSMREventListener listener,
<API key> scheduler, int <API key>) {
this.parentListener = listener;
this.scheduler = scheduler;
this.<API key> = <API key>;
telegramListener = new <API key>(listener);
dsmrConnector = new DSMRSerialConnector(serialPortManager, serialPortName, telegramListener);
logger.debug("Initialized port '{}'", serialPortName);
}
@Override
public void start() {
stopDiscover(DeviceState.DISCOVER_SETTINGS);
portSettings = <API key>;
telegramListener.<API key>(this);
dsmrConnector.open(portSettings);
restartHalfTimer();
endTimeTimer = scheduler.schedule(this::<API key>,
<API key> * <API key>, TimeUnit.SECONDS);
}
@Override
public void restart() {
if (state == DeviceState.ERROR) {
stop();
start();
} else if (state == DeviceState.NORMAL) {
dsmrConnector.restart(portSettings);
}
}
@Override
public synchronized void stop() {
dsmrConnector.close();
stopDiscover(state);
logger.trace("stopped with state:{}", state);
}
/**
* Handle if telegrams are received.
*
* @param telegram the details of the received telegram
*/
@Override
public void <API key>(P1Telegram telegram) {
if (!telegram.getCosemObjects().isEmpty()) {
stopDiscover(DeviceState.NORMAL);
parentListener.<API key>(telegram);
logger.info("Start receiving telegrams on port {} with settings: {}", dsmrConnector.getPortName(),
portSettings);
}
}
/**
* Event handler for DSMR Port events.
*
* @param portEvent {@link <API key>} to handle
*/
@Override
public void handleErrorEvent(<API key> portEvent) {
logger.trace("Received portEvent {}", portEvent.getEventDetails());
if (portEvent == <API key>.READ_ERROR) {
switchBaudrate();
} else {
logger.debug("Error during discovery of port settings: {}, current state:{}.", portEvent.getEventDetails(),
state);
stopDiscover(DeviceState.ERROR);
parentListener.handleErrorEvent(portEvent);
}
}
/**
* @param lenientMode the lenientMode to set
*/
@Override
public void setLenientMode(boolean lenientMode) {
telegramListener.setLenientMode(lenientMode);
}
/**
* @return Returns the state of the instance. Used for testing only.
*/
DeviceState getState() {
return state;
}
/**
* Switches the baudrate on the serial port.
*/
private void switchBaudrate() {
if (<API key> + <API key> > System.nanoTime()) {
// Ignore switching baudrate if this is called within the timeout after a previous switch.
return;
}
<API key> = System.nanoTime();
if (state == DeviceState.DISCOVER_SETTINGS) {
restartHalfTimer();
logger.debug(
"Discover port settings is running for half time now and still nothing discovered, switching baudrate and retrying");
portSettings = portSettings == DSMRSerialSettings.HIGH_SPEED_SETTINGS
? DSMRSerialSettings.LOW_SPEED_SETTINGS
: DSMRSerialSettings.HIGH_SPEED_SETTINGS;
dsmrConnector.setSerialPortParams(portSettings);
}
}
/**
* Stops the discovery process as triggered by the end timer. It will only act if the discovery process was still
* running.
*/
private void <API key>() {
if (state == DeviceState.DISCOVER_SETTINGS) {
stopDiscover(DeviceState.ERROR);
parentListener.handleErrorEvent(<API key>.DONT_EXISTS);
}
}
/**
* Stops the discovery of port speed process and sets the state with which it should be stopped.
*
* @param state the state with which the process was stopped.
*/
private void stopDiscover(DeviceState state) {
telegramListener.<API key>(parentListener);
logger.debug("Stop discovery of port settings.");
if (halfTimeTimer != null) {
halfTimeTimer.cancel(true);
halfTimeTimer = null;
}
if (endTimeTimer != null) {
endTimeTimer.cancel(true);
endTimeTimer = null;
}
this.state = state;
}
/**
* Method to (re)start the switching baudrate timer.
*/
private void restartHalfTimer() {
if (halfTimeTimer != null) {
halfTimeTimer.cancel(true);
}
halfTimeTimer = scheduler.schedule(this::switchBaudrate, <API key>, TimeUnit.SECONDS);
}
} |
package org.openhab.binding.yamahareceiver.internal.state;
import static org.openhab.binding.yamahareceiver.<API key>.VALUE_EMPTY;
/**
* The state of a specific zone of a Yamaha receiver.
*
* @author David Graeff <david.graeff@web.de>
*
*/
public class ZoneControlState {
public boolean power = false;
// User visible name of the input channel for the current zone
public String inputName = VALUE_EMPTY;
// The ID of the input channel that is used as xml tags (for example NET_RADIO, HDMI_1).
// This may differ from what the AVR returns in Input/Input_Sel ("NET RADIO", "HDMI1")
public String inputID = VALUE_EMPTY;
public String surroundProgram = VALUE_EMPTY;
public float volumeDB = 0.0f; // volume in dB
public boolean mute = false;
public int dialogueLevel = 0;
} |
package org.openhab.binding.nikohomecontrol.internal.protocol;
/**
* Class {@link NhcMessageBase} used as base class for output from gson for cmd or event feedback from Niko Home
* Control. This class only contains the common base fields required for the deserializer
* {@link <API key>} to select the specific formats implemented in {@link NhcMessageMap},
* {@link NhcMessageListMap}, {@link NhcMessageCmd}.
* <p>
*
* @author Mark Herwege - Initial Contribution
*/
abstract class NhcMessageBase {
private String cmd;
private String event;
String getCmd() {
return this.cmd;
}
void setCmd(String cmd) {
this.cmd = cmd;
}
String getEvent() {
return this.event;
}
void setEvent(String event) {
this.event = event;
}
} |
#include <linux/init.h>
#include <linux/cache.h>
#include <linux/sched.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <asm/io.h>
#include "proto.h"
#include "irq_impl.h"
static unsigned int cached_irq_mask = 0xffff;
static DEFINE_SPINLOCK(i8259_irq_lock);
static inline void
i8259_update_irq_hw(unsigned int irq, unsigned long mask)
{
int port = 0x21;
if (irq & 8) mask >>= 8;
if (irq & 8) port = 0xA1;
outb(mask, port);
}
inline void
i8259a_enable_irq(struct irq_data *d)
{
spin_lock(&i8259_irq_lock);
i8259_update_irq_hw(d->irq, cached_irq_mask &= ~(1 << d->irq));
spin_unlock(&i8259_irq_lock);
}
static inline void
<API key>(unsigned int irq)
{
i8259_update_irq_hw(irq, cached_irq_mask |= 1 << irq);
}
void
i8259a_disable_irq(struct irq_data *d)
{
spin_lock(&i8259_irq_lock);
<API key>(d->irq);
spin_unlock(&i8259_irq_lock);
}
void
<API key>(struct irq_data *d)
{
unsigned int irq = d->irq;
spin_lock(&i8259_irq_lock);
<API key>(irq);
if (irq >= 8) {
outb(0xE0 | (irq - 8), 0xa0);
irq = 2;
}
outb(0xE0 | irq, 0x20);
spin_unlock(&i8259_irq_lock);
}
struct irq_chip i8259a_irq_type = {
.name = "XT-PIC",
.irq_unmask = i8259a_enable_irq,
.irq_mask = i8259a_disable_irq,
.irq_mask_ack = <API key>,
};
void __init
init_i8259a_irqs(void)
{
static struct irqaction cascade = {
.handler = no_action,
.name = "cascade",
};
long i;
outb(0xff, 0x21);
outb(0xff, 0xA1);
for (i = 0; i < 16; i++) {
<API key>(i, &i8259a_irq_type, handle_level_irq);
}
setup_irq(2, &cascade);
}
#if defined(<API key>)
# define IACK_SC alpha_mv.iack_sc
#elif defined(CONFIG_ALPHA_APECS)
# define IACK_SC APECS_IACK_SC
#elif defined(CONFIG_ALPHA_LCA)
# define IACK_SC LCA_IACK_SC
#elif defined(CONFIG_ALPHA_CIA)
# define IACK_SC CIA_IACK_SC
#elif defined(CONFIG_ALPHA_PYXIS)
# define IACK_SC PYXIS_IACK_SC
#elif defined(CONFIG_ALPHA_TITAN)
# define IACK_SC TITAN_IACK_SC
#elif defined(<API key>)
# define IACK_SC TSUNAMI_IACK_SC
#elif defined(<API key>)
# define IACK_SC IRONGATE_IACK_SC
#endif
#if defined(IACK_SC)
void
<API key>(unsigned long vector)
{
int j = *(vuip) IACK_SC;
j &= 0xff;
handle_irq(j);
}
#endif
#if defined(<API key>) || !defined(IACK_SC)
void
<API key>(unsigned long vector)
{
unsigned long pic;
pic = inb(0x20) | (inb(0xA0) << 8);
pic &= 0xFFFB;
while (pic) {
int j = ffz(~pic);
pic &= pic - 1;
handle_irq(j);
}
}
#endif |
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/genhd.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/irqreturn.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/mod_devicetable.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/of_device.h>
#include <linux/of_platform.h>
#include <asm/page.h>
#include <asm/prom.h>
#define <API key> "axonram"
#define <API key> "axonram"
#define <API key> 16
#define <API key> PAGE_SHIFT
#define AXON_RAM_BLOCK_SIZE 1 << <API key>
#define <API key> 9
#define <API key> 1 << <API key>
#define AXON_RAM_IRQ_FLAGS IRQF_SHARED | IRQF_TRIGGER_RISING
static int azfs_major, azfs_minor;
struct axon_ram_bank {
struct platform_device *device;
struct gendisk *disk;
unsigned int irq_id;
unsigned long ph_addr;
unsigned long io_addr;
unsigned long size;
unsigned long ecc_counter;
};
static ssize_t
axon_ram_sysfs_ecc(struct device *dev, struct device_attribute *attr, char *buf)
{
struct platform_device *device = to_platform_device(dev);
struct axon_ram_bank *bank = device->dev.platform_data;
BUG_ON(!bank);
return sprintf(buf, "%ld\n", bank->ecc_counter);
}
static DEVICE_ATTR(ecc, S_IRUGO, axon_ram_sysfs_ecc, NULL);
static irqreturn_t
<API key>(int irq, void *dev)
{
struct platform_device *device = dev;
struct axon_ram_bank *bank = device->dev.platform_data;
BUG_ON(!bank);
dev_err(&device->dev, "Correctable memory error occurred\n");
bank->ecc_counter++;
return IRQ_HANDLED;
}
static void
<API key>(struct request_queue *queue, struct bio *bio)
{
struct axon_ram_bank *bank = bio->bi_bdev->bd_disk->private_data;
unsigned long phys_mem, phys_end;
void *user_mem;
struct bio_vec *vec;
unsigned int transfered;
unsigned short idx;
phys_mem = bank->io_addr + (bio->bi_sector << <API key>);
phys_end = bank->io_addr + bank->size;
transfered = 0;
<API key>(vec, bio, idx) {
if (unlikely(phys_mem + vec->bv_len > phys_end)) {
bio_io_error(bio);
return;
}
user_mem = page_address(vec->bv_page) + vec->bv_offset;
if (bio_data_dir(bio) == READ)
memcpy(user_mem, (void *) phys_mem, vec->bv_len);
else
memcpy((void *) phys_mem, user_mem, vec->bv_len);
phys_mem += vec->bv_len;
transfered += vec->bv_len;
}
bio_endio(bio, 0);
}
static int
<API key>(struct block_device *device, sector_t sector,
void **kaddr, unsigned long *pfn)
{
struct axon_ram_bank *bank = device->bd_disk->private_data;
loff_t offset;
offset = sector;
if (device->bd_part != NULL)
offset += device->bd_part->start_sect;
offset <<= <API key>;
if (offset >= bank->size) {
dev_err(&bank->device->dev, "Access outside of address space\n");
return -ERANGE;
}
*kaddr = (void *)(bank->ph_addr + offset);
*pfn = virt_to_phys(kaddr) >> PAGE_SHIFT;
return 0;
}
static const struct <API key> axon_ram_devops = {
.owner = THIS_MODULE,
.direct_access = <API key>
};
static int axon_ram_probe(struct platform_device *device)
{
static int axon_ram_bank_id = -1;
struct axon_ram_bank *bank;
struct resource resource;
int rc = 0;
axon_ram_bank_id++;
dev_info(&device->dev, "Found memory controller on %s\n",
device->dev.of_node->full_name);
bank = kzalloc(sizeof(struct axon_ram_bank), GFP_KERNEL);
if (bank == NULL) {
dev_err(&device->dev, "Out of memory\n");
rc = -ENOMEM;
goto failed;
}
device->dev.platform_data = bank;
bank->device = device;
if (<API key>(device->dev.of_node, 0, &resource) != 0) {
dev_err(&device->dev, "Cannot access device tree\n");
rc = -EFAULT;
goto failed;
}
bank->size = resource_size(&resource);
if (bank->size == 0) {
dev_err(&device->dev, "No DDR2 memory found for %s%d\n",
<API key>, axon_ram_bank_id);
rc = -ENODEV;
goto failed;
}
dev_info(&device->dev, "Register DDR2 memory device %s%d with %luMB\n",
<API key>, axon_ram_bank_id, bank->size >> 20);
bank->ph_addr = resource.start;
bank->io_addr = (unsigned long) ioremap_prot(
bank->ph_addr, bank->size, _PAGE_NO_CACHE);
if (bank->io_addr == 0) {
dev_err(&device->dev, "ioremap() failed\n");
rc = -EFAULT;
goto failed;
}
bank->disk = alloc_disk(<API key>);
if (bank->disk == NULL) {
dev_err(&device->dev, "Cannot register disk\n");
rc = -EFAULT;
goto failed;
}
bank->disk->major = azfs_major;
bank->disk->first_minor = azfs_minor;
bank->disk->fops = &axon_ram_devops;
bank->disk->private_data = bank;
bank->disk->driverfs_dev = &device->dev;
sprintf(bank->disk->disk_name, "%s%d",
<API key>, axon_ram_bank_id);
bank->disk->queue = blk_alloc_queue(GFP_KERNEL);
if (bank->disk->queue == NULL) {
dev_err(&device->dev, "Cannot register disk queue\n");
rc = -EFAULT;
goto failed;
}
set_capacity(bank->disk, bank->size >> <API key>);
<API key>(bank->disk->queue, <API key>);
<API key>(bank->disk->queue, <API key>);
add_disk(bank->disk);
bank->irq_id = <API key>(device->dev.of_node, 0);
if (bank->irq_id == NO_IRQ) {
dev_err(&device->dev, "Cannot access ECC interrupt ID\n");
rc = -EFAULT;
goto failed;
}
rc = request_irq(bank->irq_id, <API key>,
AXON_RAM_IRQ_FLAGS, bank->disk->disk_name, device);
if (rc != 0) {
dev_err(&device->dev, "Cannot register ECC interrupt handler\n");
bank->irq_id = NO_IRQ;
rc = -EFAULT;
goto failed;
}
rc = device_create_file(&device->dev, &dev_attr_ecc);
if (rc != 0) {
dev_err(&device->dev, "Cannot create sysfs file\n");
rc = -EFAULT;
goto failed;
}
azfs_minor += bank->disk->minors;
return 0;
failed:
if (bank != NULL) {
if (bank->irq_id != NO_IRQ)
free_irq(bank->irq_id, device);
if (bank->disk != NULL) {
if (bank->disk->major > 0)
unregister_blkdev(bank->disk->major,
bank->disk->disk_name);
del_gendisk(bank->disk);
}
device->dev.platform_data = NULL;
if (bank->io_addr != 0)
iounmap((void __iomem *) bank->io_addr);
kfree(bank);
}
return rc;
}
static int
axon_ram_remove(struct platform_device *device)
{
struct axon_ram_bank *bank = device->dev.platform_data;
BUG_ON(!bank || !bank->disk);
device_remove_file(&device->dev, &dev_attr_ecc);
free_irq(bank->irq_id, device);
del_gendisk(bank->disk);
iounmap((void __iomem *) bank->io_addr);
kfree(bank);
return 0;
}
static struct of_device_id axon_ram_device_id[] = {
{
.type = "dma-memory"
},
{}
};
static struct platform_driver axon_ram_driver = {
.probe = axon_ram_probe,
.remove = axon_ram_remove,
.driver = {
.name = <API key>,
.owner = THIS_MODULE,
.of_match_table = axon_ram_device_id,
},
};
static int __init
axon_ram_init(void)
{
azfs_major = register_blkdev(azfs_major, <API key>);
if (azfs_major < 0) {
printk(KERN_ERR "%s cannot become block device major number\n",
<API key>);
return -EFAULT;
}
azfs_minor = 0;
return <API key>(&axon_ram_driver);
}
static void __exit
axon_ram_exit(void)
{
<API key>(&axon_ram_driver);
unregister_blkdev(azfs_major, <API key>);
}
module_init(axon_ram_init);
module_exit(axon_ram_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Maxim Shchetynin <maxim@de.ibm.com>");
MODULE_DESCRIPTION("Axon DDR2 RAM device driver for IBM Cell BE"); |
#include "GameObjectAI.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "heart_of_fear.h"
// Zorlok - 62980
class boss_unsok : public CreatureScript
{
public:
boss_unsok() : CreatureScript("boss_unsok") { }
struct boss_unsokAI : public BossAI
{
boss_unsokAI(Creature* creature) : BossAI(creature, DATA_UNSOK)
{
pInstance = creature->GetInstanceScript();
}
InstanceScript* pInstance;
EventMap events;
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_unsokAI(creature);
}
};
void AddSC_boss_unsok()
{
new boss_unsok();
} |
#include "Core/HW/SI/SI_DeviceKeyboard.h"
#include <cstring>
#include "Common/ChunkFile.h"
#include "Common/CommonTypes.h"
#include "Common/Logging/Log.h"
#include "Common/Swap.h"
#include "Core/HW/GCKeyboard.h"
#include "InputCommon/KeyboardStatus.h"
namespace SerialInterface
{
CSIDevice_Keyboard::CSIDevice_Keyboard(SIDevices device, int device_number)
: ISIDevice(device, device_number)
{
}
int CSIDevice_Keyboard::RunBuffer(u8* buffer, int request_length)
{
// For debug logging only
ISIDevice::RunBuffer(buffer, request_length);
// Read the command
const auto command = static_cast<EBufferCommands>(buffer[0]);
// Handle it
switch (command)
{
case CMD_RESET:
case CMD_ID:
{
u32 id = Common::swap32(SI_GC_KEYBOARD);
std::memcpy(buffer, &id, sizeof(id));
return sizeof(id);
}
case CMD_DIRECT:
{
INFO_LOG_FMT(SERIALINTERFACE, "Keyboard - Direct (Request Length: {})", request_length);
u32 high, low;
GetData(high, low);
for (int i = 0; i < 4; i++)
{
buffer[i + 0] = (high >> (24 - (i * 8))) & 0xff;
buffer[i + 4] = (low >> (24 - (i * 8))) & 0xff;
}
return sizeof(high) + sizeof(low);
}
default:
{
ERROR_LOG_FMT(SERIALINTERFACE, "Unknown SI command ({:#x})", command);
}
break;
}
return 0;
}
KeyboardStatus CSIDevice_Keyboard::GetKeyboardStatus() const
{
return Keyboard::GetStatus(m_device_number);
}
bool CSIDevice_Keyboard::GetData(u32& hi, u32& low)
{
KeyboardStatus key_status = GetKeyboardStatus();
u8 key[3] = {0x00, 0x00, 0x00};
MapKeys(key_status, key);
u8 checksum = key[0] ^ key[1] ^ key[2] ^ m_counter;
hi = m_counter << 24;
low = key[0] << 24 | key[1] << 16 | key[2] << 8 | checksum;
return true;
}
void CSIDevice_Keyboard::SendCommand(u32 command, u8 poll)
{
UCommand keyboard_command(command);
switch (keyboard_command.command)
{
case 0x00:
break;
case CMD_POLL:
{
m_counter++;
m_counter &= 15;
}
break;
default:
{
ERROR_LOG_FMT(SERIALINTERFACE, "Unknown direct command ({:#x})", command);
}
break;
}
}
void CSIDevice_Keyboard::DoState(PointerWrap& p)
{
p.Do(m_counter);
}
void CSIDevice_Keyboard::MapKeys(const KeyboardStatus& key_status, u8* key)
{
u8 keys_held = 0;
const u8 MAX_KEYS_HELD = 3;
if (key_status.key0x & KEYMASK_HOME)
{
key[keys_held++] = KEY_HOME;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_END)
{
key[keys_held++] = KEY_END;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_PGUP)
{
key[keys_held++] = KEY_PGUP;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_PGDN)
{
key[keys_held++] = KEY_PGDN;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_SCROLLLOCK)
{
key[keys_held++] = KEY_SCROLLLOCK;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_A)
{
key[keys_held++] = KEY_A;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_B)
{
key[keys_held++] = KEY_B;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_C)
{
key[keys_held++] = KEY_C;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_D)
{
key[keys_held++] = KEY_D;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_E)
{
key[keys_held++] = KEY_E;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_F)
{
key[keys_held++] = KEY_F;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_G)
{
key[keys_held++] = KEY_G;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_H)
{
key[keys_held++] = KEY_H;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_I)
{
key[keys_held++] = KEY_I;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_J)
{
key[keys_held++] = KEY_J;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_K)
{
key[keys_held++] = KEY_K;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_L)
{
key[keys_held++] = KEY_L;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_M)
{
key[keys_held++] = KEY_M;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_N)
{
key[keys_held++] = KEY_N;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_O)
{
key[keys_held++] = KEY_O;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_P)
{
key[keys_held++] = KEY_P;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_Q)
{
key[keys_held++] = KEY_Q;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_R)
{
key[keys_held++] = KEY_R;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_S)
{
key[keys_held++] = KEY_S;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_T)
{
key[keys_held++] = KEY_T;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_U)
{
key[keys_held++] = KEY_U;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_V)
{
key[keys_held++] = KEY_V;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_W)
{
key[keys_held++] = KEY_W;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_X)
{
key[keys_held++] = KEY_X;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_Y)
{
key[keys_held++] = KEY_Y;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_Z)
{
key[keys_held++] = KEY_Z;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_1)
{
key[keys_held++] = KEY_1;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_2)
{
key[keys_held++] = KEY_2;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_3)
{
key[keys_held++] = KEY_3;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_4)
{
key[keys_held++] = KEY_4;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_5)
{
key[keys_held++] = KEY_5;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_6)
{
key[keys_held++] = KEY_6;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_7)
{
key[keys_held++] = KEY_7;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_8)
{
key[keys_held++] = KEY_8;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_9)
{
key[keys_held++] = KEY_9;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_0)
{
key[keys_held++] = KEY_0;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_MINUS)
{
key[keys_held++] = KEY_MINUS;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_PLUS)
{
key[keys_held++] = KEY_PLUS;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_PRINTSCR)
{
key[keys_held++] = KEY_PRINTSCR;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_BRACE_OPEN)
{
key[keys_held++] = KEY_BRACE_OPEN;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_BRACE_CLOSE)
{
key[keys_held++] = KEY_BRACE_CLOSE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_COLON)
{
key[keys_held++] = KEY_COLON;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_QUOTE)
{
key[keys_held++] = KEY_QUOTE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_HASH)
{
key[keys_held++] = KEY_HASH;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_COMMA)
{
key[keys_held++] = KEY_COMMA;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_PERIOD)
{
key[keys_held++] = KEY_PERIOD;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & <API key>)
{
key[keys_held++] = KEY_QUESTIONMARK;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & <API key>)
{
key[keys_held++] = KEY_INTERNATIONAL1;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F1)
{
key[keys_held++] = KEY_F1;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F2)
{
key[keys_held++] = KEY_F2;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F3)
{
key[keys_held++] = KEY_F3;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F4)
{
key[keys_held++] = KEY_F4;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F5)
{
key[keys_held++] = KEY_F5;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F6)
{
key[keys_held++] = KEY_F6;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F7)
{
key[keys_held++] = KEY_F7;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F8)
{
key[keys_held++] = KEY_F8;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F9)
{
key[keys_held++] = KEY_F9;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F10)
{
key[keys_held++] = KEY_F10;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F11)
{
key[keys_held++] = KEY_F11;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_F12)
{
key[keys_held++] = KEY_F12;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_ESC)
{
key[keys_held++] = KEY_ESC;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_INSERT)
{
key[keys_held++] = KEY_INSERT;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_DELETE)
{
key[keys_held++] = KEY_DELETE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_TILDE)
{
key[keys_held++] = KEY_TILDE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_BACKSPACE)
{
key[keys_held++] = KEY_BACKSPACE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_TAB)
{
key[keys_held++] = KEY_TAB;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_CAPSLOCK)
{
key[keys_held++] = KEY_CAPSLOCK;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_LEFTSHIFT)
{
key[keys_held++] = KEY_LEFTSHIFT;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_RIGHTSHIFT)
{
key[keys_held++] = KEY_RIGHTSHIFT;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_LEFTCONTROL)
{
key[keys_held++] = KEY_LEFTCONTROL;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_RIGHTALT)
{
key[keys_held++] = KEY_RIGHTALT;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_LEFTWINDOWS)
{
key[keys_held++] = KEY_LEFTWINDOWS;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_SPACE)
{
key[keys_held++] = KEY_SPACE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & <API key>)
{
key[keys_held++] = KEY_RIGHTWINDOWS;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_MENU)
{
key[keys_held++] = KEY_MENU;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key5x & KEYMASK_LEFTARROW)
{
key[keys_held++] = KEY_LEFTARROW;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key5x & KEYMASK_DOWNARROW)
{
key[keys_held++] = KEY_DOWNARROW;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key5x & KEYMASK_UPARROW)
{
key[keys_held++] = KEY_UPARROW;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key5x & KEYMASK_RIGHTARROW)
{
key[keys_held++] = KEY_RIGHTARROW;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key5x & KEYMASK_ENTER)
{
key[keys_held++] = KEY_ENTER;
if (keys_held >= MAX_KEYS_HELD)
return;
}
}
} // namespace SerialInterface |
<?php
if (!get_option('users_can_register')) return;
add_action('<API key>','<API key>');
function <API key>() {
wp_enqueue_script('jquery');
}
add_action('<API key>', '<API key>');
function <API key>() {
wp_redirect(site_url('wp-login.php?action=register', 'login'));
exit;
}
remove_action('login_form','<API key>');
add_action('login_form','<API key>');
function <API key>() {
global $action;
if ($action == 'login') echo '<p><fb:login-button v="2" registration-url="'.site_url('wp-login.php?action=register', 'login').'" scope="email,user_website" onlogin="window.location.reload();" /></p><br />';
}
add_action('register_form','sfc_register_form');
function sfc_register_form() {
add_action('sfc_async_init', '<API key>');
$fields = json_encode( apply_filters('sfc_register_fields',array(
array('name'=>'name', 'view'=>'prefilled'),
array('name'=>'username', 'description'=>__('Choose a username','sfc'), 'type'=>'text'),
array('name'=>'email'),
array('name'=>'captcha'),
)
) );
?>
<fb:registration
fields='<?php echo $fields; ?>'
redirect-uri="<?php echo apply_filters('<API key>', site_url('wp-login.php?action=register', 'login') ); ?>"
width="262"
>
</fb:registration>
<?php
}
function <API key>() {
?>
jQuery('#registerform p').hide();
jQuery('#reg_passmail').show();
<?php
}
add_action('register_form','sfc_add_base_js',20);
// catch the signed request
add_action('login_form_register','<API key>');
function <API key>() {
global $wpdb;
$options = get_option('sfc_options');
if (!empty($_POST['signed_request'])) {
list($encoded_sig, $payload) = explode('.', $_POST['signed_request'], 2);
// decode the data
$sig = <API key>($encoded_sig);
$data = json_decode(<API key>($payload), true);
if (!isset($data['algorithm']) || strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
return;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $options['app_secret'], true);
if ($sig !== $expected_sig) {
return;
}
if (isset($data['registration'])) {
$info = $data['registration'];
if (isset($info['username']) && isset($info['email'])) {
// first check to see if this user already exists in the db
$user_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_email = %s", $info['email']) );
if ($user_id) {
$fbuid = $data['user_id'];
update_usermeta($user_id, 'fbuid', $fbuid); // connect the account so we don't have to query this again
// redirect to admin and exit
wp_redirect( add_query_arg( array('updated' => 'true'), self_admin_url( 'profile.php' ) ) );
exit;
} else {
// new user, set the registration info
$_POST['user_login'] = $info['username'];
$_POST['user_email'] = $info['email'];
do_action('<API key>',$info);
}
}
}
}
} |
<?php
namespace Illuminate\Queue\Console;
use Exception;
use RuntimeException;
use Illuminate\Queue\IronQueue;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
/**
* @deprecated since version 5.1
*/
class SubscribeCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'queue:subscribe';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Subscribe a URL to an Iron.io push queue';
/**
* The queue meta information from Iron.io.
*
* @var object
*/
protected $meta;
/**
* Execute the console command.
*
* @return void
*
* @throws \RuntimeException
*/
public function fire()
{
$iron = $this->laravel['queue']->connection();
if (!$iron instanceof IronQueue) {
throw new RuntimeException('Iron.io based queue must be default.');
}
$iron->getIron()->updateQueue($this->argument('queue'), $this->getQueueOptions());
$this->line('<info>Queue subscriber added:</info> <comment>'.$this->argument('url').'</comment>');
}
/**
* Get the queue options.
*
* @return array
*/
protected function getQueueOptions()
{
return [
'push_type' => $this->getPushType(), 'subscribers' => $this->getSubscriberList(),
];
}
/**
* Get the push type for the queue.
*
* @return string
*/
protected function getPushType()
{
if ($this->option('type')) {
return $this->option('type');
}
try {
return $this->getQueue()->push_type;
} catch (Exception $e) {
return 'multicast';
}
}
/**
* Get the current subscribers for the queue.
*
* @return array
*/
protected function getSubscriberList()
{
$subscribers = $this-><API key>();
$url = $this->argument('url');
if (!starts_with($url, ['http:
$url = $this->laravel['url']->to($url);
}
$subscribers[] = ['url' => $url];
return $subscribers;
}
/**
* Get the current subscriber list.
*
* @return array
*/
protected function <API key>()
{
try {
return $this->getQueue()->subscribers;
} catch (Exception $e) {
return [];
}
}
/**
* Get the queue information from Iron.io.
*
* @return object
*/
protected function getQueue()
{
if (isset($this->meta)) {
return $this->meta;
}
return $this->meta = $this->laravel['queue']->getIron()->getQueue($this->argument('queue'));
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['queue', InputArgument::REQUIRED, 'The name of Iron.io queue.'],
['url', InputArgument::REQUIRED, 'The URL to be subscribed.'],
];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['type', null, InputOption::VALUE_OPTIONAL, 'The push type for the queue.'],
];
}
} |
/** @addtogroup GUI
@{ */
/** @addtogroup GuiTreeModel
* @{ */
#ifndef <API key>
#define <API key>
#include <gtk/gtk.h>
#include "gnc-tree-view.h"
#include "gnc-ui-util.h"
#include "gnc-plugin-page.h"
G_BEGIN_DECLS
/* type macros */
#define <API key> (<API key> ())
#define <API key>(obj) (<API key> ((obj), <API key>, GncTreeViewAccount))
#define <API key>(klass) (<API key> ((klass), <API key>, <API key>))
#define <API key>(obj) (<API key> ((obj), <API key>))
#define <API key>(klass) (<API key> ((klass), <API key>))
#define <API key>(obj) (<API key> ((obj), <API key>, <API key>))
#define <API key> "GncTreeViewAccount"
/* typedefs & structures */
typedef struct AccountViewInfo_s AccountViewInfo;
struct AccountViewInfo_s
{
gboolean include_type[NUM_ACCOUNT_TYPES];
gboolean show_hidden;
};
typedef struct
{
GncTreeView gnc_tree_view;
int stamp;
} GncTreeViewAccount;
typedef struct
{
GncTreeViewClass gnc_tree_view;
} <API key>;
typedef struct
{
GtkWidget *dialog;
GtkTreeModel *model;
GncTreeViewAccount *tree_view;
GHashTable *filter_override;
guint32 visible_types;
guint32 <API key>;
gboolean show_hidden;
gboolean <API key>;
gboolean show_zero_total;
gboolean <API key>;
gboolean show_unused;
gboolean <API key>;
} AccountFilterDialog;
void <API key>(AccountFilterDialog *fd,
GncPluginPage *page);
gboolean <API key> (Account *account,
gpointer user_data);
/* "Filter By" dialog callbacks */
void <API key> (GtkToggleButton *togglebutton,
AccountFilterDialog *fd);
void <API key> (GtkToggleButton *togglebutton,
AccountFilterDialog *fd);
void <API key> (GtkToggleButton *togglebutton,
AccountFilterDialog *fd);
void <API key> (GtkWidget *button, AccountFilterDialog *fd);
void <API key> (GtkWidget *button, AccountFilterDialog *fd);
void <API key> (GtkWidget *button,
AccountFilterDialog *fd);
void <API key> (GtkWidget *dialog, gint response,
AccountFilterDialog *fd);
/* Saving/Restoring */
void <API key>(GncTreeViewAccount *tree_view,
AccountFilterDialog *fd,
GKeyFile *key_file, const gchar *group_name);
void <API key>(GncTreeViewAccount *view,
AccountFilterDialog *fd,
GKeyFile *key_file,
const gchar *group_name);
void <API key> (GncTreeViewAccount *tree_view,
AccountFilterDialog *fd,
GKeyFile *key_file,
const gchar *group_name);
void <API key> (GncTreeViewAccount *view,
AccountFilterDialog *fd,
GKeyFile *key_file,
const gchar *group_name);
/* Get the GType for an GncTreeViewAccount object. */
GType <API key> (void);
/** @name Account Tree View Constructors
@{ */
/** Create a new account tree view. This view may or may not show a
* pseudo top-level account. The gnucash engine does not have a
* single top level account (it has a list of top level accounts),
* but this code provides one so that it can be used with all parts
* of the gnucash gui.
*
* @param root The account to use as the first level of the created tree.
*
* @param show_root Show the pseudo top-level account in this view.
*
* @return A pointer to a new account tree view.
*/
GtkTreeView *<API key> (Account *root,
gboolean show_root);
/** Create a new account tree view. This view may or may not show a
* pseudo top-level account. The gnucash engine does not have a
* single top level account (it has a list of top level accounts),
* but this code provides one so that it can be used with all parts
* of the gnucash gui. The first level of accounts in the created
* tree will be the top level of accounts in the current book.
*
* @param show_root Show the pseudo top-level account in this view.
*
* @return A pointer to a new account tree view.
*/
GtkTreeView *<API key> (gboolean show_root);
/** @name Account Tree View Configuration
@{ */
typedef gchar * (*<API key>) (Account *account,
GtkTreeViewColumn *col,
GtkCellRenderer *cell);
typedef void (*<API key>) (Account *account,
GtkTreeViewColumn *col,
const gchar *new_text);
/** Add a new custom column to the set of columns in an account tree
* view. This column will be visible as soon as it is added and will
* query the provided functions to determine what data to display.
* The TreeView will own the resulting TreeViewColumn, but caller may
* set any additional properties they wish.
*
* @param view A pointer to an account tree view.
*
* @param column_title The title for this new column.
*
* @param source_cb A callback function that is expected to provide
* the data to be displayed.
*
* @param edited_cb A callback function that will be called if the
* user edits the displayed data.
*/
GtkTreeViewColumn * <API key>(
GncTreeViewAccount *view, const gchar *column_title,
<API key> source_cb,
<API key> edited_cb);
GtkTreeViewColumn *<API key>(
GncTreeViewAccount *account_view, const gchar *column_title,
<API key> col_source_cb,
<API key> col_edited_cb,
GtkCellRenderer *renderer);
void <API key>(GncTreeViewAccount *view,
<API key> edited_cb);
void <API key>(Account *account, GtkTreeViewColumn *col, const gchar *new_name);
void <API key>(GncTreeViewAccount *view,
<API key> edited_cb);
void <API key>(Account *account, GtkTreeViewColumn *col, const gchar *new_code);
void <API key>(GncTreeViewAccount *view,
<API key> edited_cb);
void <API key>(Account *account, GtkTreeViewColumn *col, const gchar *new_desc);
void <API key>(GncTreeViewAccount *view,
<API key> edited_cb);
void <API key>(Account *account, GtkTreeViewColumn *col, const gchar *new_notes);
/** Add a new column to the set of columns in an account tree view.
* This column will be visible as soon as it is added and will
* display the contents of the specified account property
*
* @param view A pointer to an account tree view.
*
* @param column_title The title for this new column.
*
* @param propname The g_object_property name of the desired
* value. This must be a string property.
*/
GtkTreeViewColumn *
<API key> (GncTreeViewAccount *view,
const gchar *column_title,
const gchar *propname);
/** @name Account Tree View Filtering
@{ */
/** Given pointers to an account tree and old style filter block, this
* function will copy the current configuration of the account tree
* widget into the data block. This may be used in conjunction with
* the <API key> function to modify the
* filters on an existing account tree.
*
* @param account_view A pointer to an account tree view.
*
* @param avi A pointer to an old style filter block to fill in.
*/
void <API key> (GncTreeViewAccount *account_view,
AccountViewInfo *avi);
/** Given pointers to an account tree and old style filter block, this
* function will applies the settings specified to the current
* configuration of the account tree widget. This may be used in
* conjunction with the <API key> function
* to modify the filters on an existing account tree.
*
* @param account_view A pointer to an account tree view.
*
* @param avi A pointer to an old style filter block to apply to the
* view.
*/
void <API key> (GncTreeViewAccount *account_view,
AccountViewInfo *avi);
/** This is the description of a filter function used by the account tree.
*
* @param account The account to be tested.
*
* @param data The data provided when the filter function was added.
*
* @return TRUE if the account should be displayed.
*/
typedef gboolean (*<API key>)(Account *account, gpointer data);
/** This function attaches a filter function to the given account
* tree. This function will be called for each account that the view
* thinks should possibly show. The filter may perform any actions
* necessary on the account to decide whether it should be shown or
* not. (I.E. Check type, placeholder status, etc.) If the filter
* returns TRUE then the account will be displayed.
*
* @param account_view A pointer to an account tree view.
*
* @param func A filtration function that is called on individual
* elements in the tree. If this function returns TRUE, the account
* will be displayed.
*
* @param data A data block passed into each instance of the function.
*
* @param destroy A function to destroy the data block. This
* function will be called when the filter is destroyed. may be
* NULL.
*/
void <API key> (GncTreeViewAccount *account_view,
<API key> func,
gpointer data,
GSourceFunc destroy);
/* This is a convenient filter function for use with
* <API key>() and the functions in
* <API key>.h. If you have some view that is
* backed by the "account types" tree model, you can get a guint32
* from that view's tree selection. Then, you can use that account
* type selection as a filter for the account tree view. This also
* can filter by whether an account is hidden or not.
*/
gboolean <API key>(
Account* acct, gpointer data);
/** This function forces the account tree filter to be evaluated. It
* may be necessary to call this function if the initial state of the
* view is incorrect. This appears to only be necessary if the
* filter affects one of the top level accounts in gnucash.
*
* @note This calls a function in gtk that is annotated in the
* sources as being slow. You have been warned.
*
* @param view A pointer to an account tree view.
*/
void <API key> (GncTreeViewAccount *view);
/** @name Account Tree View Get/Set Functions
@{ */
/** This function determines if an account in the account tree view
* has any visible children.
*
* @param view A pointer to an account tree view.
*
* @param account A pointer to the account to check.
*
* @return The number of children of the specified account. Returns 0
* on error.
*/
gint <API key> (GncTreeViewAccount *view,
Account *account);
/** This function clears the tree model account cache so the values will
* be updated/refreshed.
*
* @param view A pointer to an account tree view.
*
*/
void <API key> (GncTreeViewAccount *view);
/** This function returns the account associated with the specified
* path. This function is useful in selection callbacks on an
* account tree widget.
*
* @param view A pointer to an account tree view.
*
* @param path A path specifying a node in the account tree.
*
* @return The account associated with this path.
*/
Account * <API key> (GncTreeViewAccount *view,
GtkTreePath *path);
/** This function returns the account associated with the specified
* iter. This function is useful in selection callbacks on an
* account tree widget.
*
* @param model The model provided to the callback function.
*
* @param iter The iter provided to the callback function.
*
* @return The account associated with this iter.
*/
Account * <API key> (GtkTreeModel *model,
GtkTreeIter *iter);
/** This function returns the account in the account tree view at the
* current location of the cursor. (The outline frame. Usually is
* selected and therefore filled in, but not always.)
*
* @param view A pointer to an account tree view.
*
* @return The account at the cursor.
*/
Account * <API key> (GncTreeViewAccount *view);
/** This function returns the account associated with the selected
* item in the account tree view.
*
* @note It only makes sense to call this function when the account
* tree is set to select a single item. There is a different
* function to use when the tree supports multiple selections.
*
* @param view A pointer to an account tree view.
*
* @return The selected account, or NULL if no account was selected.
*/
Account * <API key> (GncTreeViewAccount *view);
/** This function selects an account in the account tree view. All
* other accounts will be unselected. In addition, this function
* collapses the entire tree and then expands only the path to the
* selected account, making the item easy to find. In general, this
* routine only need be called when initially putting up a window
* containing an account tree view widget.
*
* @note It only makes sense to call this function when the account
* tree is set to select a single item. There is a different
* function to use when the tree supports multiple selections.
*
* @param view A pointer to an account tree view.
*
* @param account A pointer to the account to select.
*/
void <API key> (GncTreeViewAccount *view,
Account *account);
/** This function returns a list of the accounts associated with the
* selected items in the account tree view.
*
* @note It only makes sense to call this function when the account
* tree is set to select multiple items. There is a different
* function to use when the tree supports single selection.
*
* @param view A pointer to an account tree view.
*
* @return A list of accounts, or NULL if no account was selected.
*/
GList * <API key> (GncTreeViewAccount *view);
/** This function selects a set of accounts in the account tree view.
* All other accounts will be unselected. In addition, this function
* collapses the entire tree and then expands only the path to the
* selected accounts, making them easy to find. In general, this
* routine only need be called when initially putting up a window
* containing an account tree view widget.
*
* @note It only makes sense to call this function when the account
* tree is set to select a single item. There is a different
* function to use when the tree supports multiple selections.
*
* @note It is the responsibility of the caller to free the returned
* list.
*
* @param view A pointer to an account tree view.
*
* @param account_list A list of accounts to select.
*
* @param show_last Force the window to scroll to the last account
* selected.
*/
void <API key> (GncTreeViewAccount *view,
GList *account_list,
gboolean show_last);
/** This function selects all sub-accounts of an account in the
* account tree view. All other accounts will be unselected.
*
* @note It only makes sense to call this function when the account
* tree is set to select multiple items. There is a different
* function to use when the tree supports multiple selections.
*
* @param view A pointer to an account tree view.
*
* @param account A pointer to the account whose children should be
* selected.
*/
void <API key> (GncTreeViewAccount *view,
Account *account);
/** This function forces the account tree expand whatever levels are
* necessary to make the specified account visible.
*
* @param view A pointer to an account tree view.
*
* @param account A pointer to the account to show.
*/
void <API key> (GncTreeViewAccount *view, Account *account);
/** Add the account color background data function to the GncTreeViewAccount column to
* show or not the column background in the account color.
*/
void <API key> (GncTreeViewAccount *view, GtkTreeViewColumn *col);
/** Setup the callback for when the user starts editing the account tree so actions can be disabled
* like the delete menu option as required.
*/
void <API key>
(GncTreeViewAccount *view, GFunc editing_started_cb, gpointer editing_cb_data );
/** Setup the callback for when the user finishes editing the account tree so actions can be enabled
* like the delete menu option as required.
*/
void <API key>
(GncTreeViewAccount *view, GFunc editing_finished_cb, gpointer editing_cb_data );
G_END_DECLS
#endif /* <API key> */ |
@import url("<API key>.css");
.acymailing_module .inputbox:hover{
border:1px solid #bfd8e1 !important;
border-bottom:1px solid #9dbcc7 !important;
-moz-box-shadow: inset 0 0 3px 3px #e2eef2 !important;
-webkit-box-shadow: inset 0 0 3px 3px#e2eef2 !important;}
.acymailing_module .inputbox:focus{
border:1px solid #6A9195 !important;}
.acysubbuttons .button, .acysubbuttons button.validate, .<API key> a:link, .<API key> a:visited {
color:#fff !important;
border:1px solid #6A9195 !important;
-moz-border-radius:5px !important;
text-shadow:1px 1px 1px #666 !important;
background-image: radial-gradient(top, #dae9ee 21%, #6A9195 58%) !important;
background-image: -o-radial-gradient(top, #dae9ee 21%, #6A9195 58%) !important;
background-image: -moz-radial-gradient(top, #dae9ee 21%, #6A9195 58%) !important;
background-image: -<API key>(top, #dae9ee 21%, #6A9195 58%) !important;
background-image: -ms-radial-gradient(top, #dae9ee 21%, #6A9195 58%) !important;
background: -ms-radial-gradient(top, ellipse cover, #dae9ee 0%,#6A9195 100%);
background: radial-gradient(top, ellipse cover, #dae9ee 0%,#6A9195 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#dae9ee', endColorstr='#6A9195',GradientType=1 ) !important;
}
.acysubbuttons .button:hover, .acysubbuttons button.validate:hover, .<API key> a:hover, .<API key> a:active {
color:#fff !important;
border:1px solid #68a2b2 !important;
-moz-border-radius:5px !important;
text-shadow:1px 1px 1px #666 !important;
background-image: radial-gradient(top, #dae9ee 21%, #68a2b2 58%) !important;
background-image: -o-radial-gradient(top, #dae9ee 21%, #68a2b2 58%) !important;
background-image: -moz-radial-gradient(top, #dae9ee 21%, #68a2b2 58%) !important;
background-image: -<API key>(top, #dae9ee 21%, #68a2b2 58%) !important;
background-image: -ms-radial-gradient(top, #dae9ee 21%, #68a2b2 58%) !important;
background: -ms-radial-gradient(top, ellipse cover, #dae9ee 0%,#68a2b2 100%);
background: radial-gradient(top, ellipse cover, #dae9ee 0%,#68a2b2 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#dae9ee', endColorstr='#68a2b2',GradientType=1 ) !important;
}
.acymailing_module form a:hover, .acymailing_module form a:active, .acymailing_module form a:focus{
color:#79adb2!important;
text-decoration:underline !important;
background-color:transparent !important;} |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http:
<head>
<title>Qt 4.4: Draggable Icons Example</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http:
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="namespaces.html"><font color="#004faf">All Namespaces</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="mainclasses.html"><font color="#004faf">Main Classes</font></a> · <a href="groups.html"><font color="#004faf">Grouped Classes</font></a> · <a href="modules.html"><font color="#004faf">Modules</font></a> · <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"></td></tr></table><h1 class="title">Draggable Icons Example<br /><span class="subtitle"></span>
</h1>
<p>Files:</p>
<ul>
<li><a href="<API key>.html">draganddrop/draggableicons/dragwidget.cpp</a></li>
<li><a href="<API key>.html">draganddrop/draggableicons/dragwidget.h</a></li>
<li><a href="<API key>.html">draganddrop/draggableicons/main.cpp</a></li>
<li><a href="<API key>.html">draganddrop/draggableicons/draggableicons.pro</a></li>
<li><a href="<API key>.html">draganddrop/draggableicons/draggableicons.qrc</a></li>
</ul>
<p>The Draggable Icons example shows how to drag and drop image data between widgets in the same application, and between different applications.</p>
<p align="center"><img src="images/<API key>.png" /></p><p>In many situations where drag and drop is used, the user starts dragging from a particular widget and drops the payload onto another widget. In this example, we subclass <a href="qlabel.html">QLabel</a> to create labels that we use as drag sources, and place them inside <a href="qwidget.html">QWidget</a>s that serve as both containers and drop sites.</p>
<p>In addition, when a drag and drop operation occurs, we want to send more than just an image. We also want to send information about where the user clicked in the image so that the user can place it precisely on the drop target. This level of detail means that we must create a custom MIME type for our data.</p>
<a name="<API key>"></a>
<h2>DragWidget Class Definition</h2>
<p>The icon widgets that we use to display icons are subclassed from <a href="qlabel.html">QLabel</a>:</p>
<pre> class DragWidget : public QFrame
{
public:
DragWidget(QWidget *parent=0);
protected:
void dragEnterEvent(QDragEnterEvent *event);
void dragMoveEvent(QDragMoveEvent *event);
void dropEvent(QDropEvent *event);
void mousePressEvent(QMouseEvent *event);
};</pre>
<p>Since the <a href="qlabel.html">QLabel</a> class provides most of what we require for the icon, we only need to reimplement the <a href="qwidget.html#mousePressEvent">QWidget::mousePressEvent</a>() to provide drag and drop facilities.</p>
<a name="<API key>"></a>
<h2>DragWidget Class Implementation</h2>
<p>The <tt>DragWidget</tt> constructor sets an attribute on the widget that ensures that it will be deleted when it is closed:</p>
<pre> DragWidget::DragWidget(QWidget *parent)
: QFrame(parent)
{
setMinimumSize(200, 200);
setFrameStyle(QFrame::Sunken | QFrame::StyledPanel);
setAcceptDrops(true);
QLabel *boatIcon = new QLabel(this);
boatIcon->setPixmap(QPixmap(":/images/boat.png"));
boatIcon->move(20, 20);
boatIcon->show();
boatIcon->setAttribute(Qt::WA_DeleteOnClose);
QLabel *carIcon = new QLabel(this);
carIcon->setPixmap(QPixmap(":/images/car.png"));
carIcon->move(120, 20);
carIcon->show();
carIcon->setAttribute(Qt::WA_DeleteOnClose);
QLabel *houseIcon = new QLabel(this);
houseIcon->setPixmap(QPixmap(":/images/house.png"));
houseIcon->move(20, 120);
houseIcon->show();
houseIcon->setAttribute(Qt::WA_DeleteOnClose);
}</pre>
<p>To enable dragging from the icon, we need to act on a mouse press event. We do this by reimplementing <a href="qwidget.html#mousePressEvent">QWidget::mousePressEvent</a>() and setting up a <a href="qdrag.html">QDrag</a> object.</p>
<pre> void DragWidget::mousePressEvent(QMouseEvent *event)
{
QLabel *child = static_cast<QLabel*>(childAt(event->pos()));
if (!child)
return;
QPixmap pixmap = *child->pixmap();
QByteArray itemData;
QDataStream dataStream(&itemData, QIODevice::WriteOnly);
dataStream << pixmap << QPoint(event->pos() - child->pos());</pre>
<p>Since we will be sending pixmap data for the icon and information about the user's click in the icon widget, we construct a <a href="qbytearray.html">QByteArray</a> and package up the details using a <a href="qdatastream.html">QDataStream</a>.</p>
<p>For interoperability, drag and drop operations describe the data they contain using MIME types. In Qt, we describe this data using a <a href="qmimedata.html">QMimeData</a> object:</p>
<pre> QMimeData *mimeData = new QMimeData;
mimeData->setData("application/x-dnditemdata", itemData);</pre>
<p>We choose an unofficial MIME type for this purpose, and supply the <a href="qbytearray.html">QByteArray</a> to the MIME data object.</p>
<p>The drag and drop operation itself is handled by a <a href="qdrag.html">QDrag</a> object:</p>
<pre> QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->setPixmap(pixmap);
drag->setHotSpot(event->pos() - child->pos());</pre>
<p>Here, we pass the data to the drag object, set a pixmap that will be shown alongside the cursor during the operation, and define the position of a hot spot that places the position of this pixmap under the cursor.</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%" align="left">Copyright © 2008 Nokia</td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.4.3</div></td>
</tr></table></div></address></body>
</html> |
<?php
$lang = array(
#Texts
'text_puke' => "Puke",
'text_nfofor' => "NFO for ",
'text_forbest' => "For best visual result, install the ",
'text_linedraw' => "MS Linedraw",
'text_font' => " font",
'text_stdhead' => "View Nfo"
);
?> |
#ifndef LSD_HASH_H
#define LSD_HASH_H
/*
* If an item's key is modified after insertion, the hash will be unable to
* locate it if the new key should hash to a different slot in the table.
*
* If NDEBUG is not defined, internal debug code will be enabled; this is
* intended for development use only. Production code should define NDEBUG.
*
* If <API key> is defined, the linker will expect to
* find an external lsd_fatal_error(file,line,mesg) function. By default,
* lsd_fatal_error(file,line,mesg) is a macro definition that aborts.
* This macro may be redefined to invoke another routine instead.
*
* If <API key> is defined, the linker will expect to
* find an external lsd_nomem_error(file,line,mesg) function. By default,
* lsd_nomem_error(file,line,mesg) is a macro definition that returns NULL.
* This macro may be redefined to invoke another routine instead.
*
* If WITH_PTHREADS is defined, these routines will be thread-safe.
*/
typedef struct hash * hash_t;
/*
* Hash table opaque data type.
*/
typedef unsigned int (*hash_key_f) (const void *key);
/*
* Function prototype for the hash function responsible for converting
* the data's [key] into an unsigned integer hash value.
*/
typedef int (*hash_cmp_f) (const void *key1, const void *key2);
/*
* Function prototype for comparing two keys.
* Returns zero if both keys are equal; o/w, returns nonzero.
*/
typedef void (*hash_del_f) (void *data);
/*
* Function prototype for de-allocating a data item stored within a hash.
* This function is responsible for freeing all memory associated with
* the [data] item, including any subordinate items.
*/
typedef int (*hash_arg_f) (void *data, const void *key, void *arg);
/*
* Function prototype for operating on each element in the hash table.
* The function will be invoked once for each [data] item in the hash,
* with the item's [key] and the specified [arg] being passed in as args.
*/
hash_t hash_create (int size,
hash_key_f key_f, hash_cmp_f cmp_f, hash_del_f del_f);
/*
* Creates and returns a new hash table on success.
* Returns lsd_nomem_error() with errno=ENOMEM if memory allocation fails.
* Returns NULL with errno=EINVAL if [keyf] or [cmpf] is not specified.
* The [size] is the number of slots in the table; a larger table requires
* more memory, but generally provide quicker access times. If set <= 0,
* the default size is used.
* The [keyf] function converts a key into a hash value.
* The [cmpf] function determines whether two keys are equal.
* The [delf] function de-allocates memory used by items in the hash;
* if set to NULL, memory associated with these items will not be freed
* when the hash is destroyed.
*/
void hash_destroy (hash_t h);
/*
* Destroys hash table [h]. If a deletion function was specified when the
* hash was created, it will be called for each item contained within.
* Abadoning a hash without calling hash_destroy() will cause a memory leak.
*/
int hash_is_empty (hash_t h);
/*
* Returns non-zero if hash table [h] is empty; o/w, returns zero.
*/
int hash_count (hash_t h);
/*
* Returns the number of items in hash table [h].
*/
void * hash_find (hash_t h, const void *key);
/*
* Searches for the item corresponding to [key] in hash table [h].
* Returns a ptr to the found item's data on success.
* Returns NULL with errno=0 if no matching item is found.
* Returns NULL with errno=EINVAL if [key] is not specified.
*/
void * hash_insert (hash_t h, const void *key, void *data);
/*
* Inserts [data] with the corresponding [key] into hash table [h];
* note that it is permissible for [key] to be set equal to [data].
* Returns a ptr to the inserted item's data on success.
* Returns NULL with errno=EEXIST if [key] already exists in the hash.
* Returns NULL with errno=EINVAL if [key] or [data] is not specified.
* Returns lsd_nomem_error() with errno=ENOMEM if memory allocation fails.
*/
void * hash_remove (hash_t h, const void *key);
/*
* Removes the item corresponding to [key] from hash table [h].
* Returns a ptr to the removed item's data on success.
* Returns NULL with errno=0 if no matching item is found.
* Returns NULL with errno=EINVAL if [key] is not specified.
*/
int hash_delete_if (hash_t h, hash_arg_f argf, void *arg);
/*
* Conditionally deletes (and de-allocates) items from hash table [h].
* The [argf] function is invoked once for each item in the hash, with
* [arg] being passed in as an argument. Items for which [argf] returns
* greater-than-zero are deleted.
* Returns the number of items deleted.
* Returns -1 with errno=EINVAL if [argf] is not specified.
*/
int hash_for_each (hash_t h, hash_arg_f argf, void *arg);
/*
* Invokes the [argf] function once for each item in hash table [h],
* with [arg] being passed in as an argument.
* Returns the number of items for which [argf] returns greater-than-zero.
* Returns -1 with errno=EINVAL if [argf] is not specified.
*/
unsigned int hash_key_string (const char *str);
/*
* A hash_key_f function that hashes the string [str].
*/
#endif /* !LSD_HASH_H */ |
#undef LABPC_DEBUG
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/io.h>
#include "../comedidev.h"
#include <linux/delay.h>
#include <asm/dma.h>
#include "8253.h"
#include "8255.h"
#include "mite.h"
#include "comedi_fc.h"
#include "ni_labpc.h"
#define DRV_NAME "ni_labpc"
#define LABPC_SIZE 32
#define LABPC_TIMER_BASE 500
#define COMMAND1_REG 0x0
#define ADC_GAIN_MASK (0x7 << 4)
#define ADC_CHAN_BITS(x) ((x) & 0x7)
#define ADC_SCAN_EN_BIT 0x80
#define COMMAND2_REG 0x1
#define PRETRIG_BIT 0x1
#define HWTRIG_BIT 0x2
#define SWTRIG_BIT 0x4
#define CASCADE_BIT 0x8
#define DAC_PACED_BIT(channel) (0x40 << ((channel) & 0x1))
#define COMMAND3_REG 0x2
#define DMA_EN_BIT 0x1
#define DIO_INTR_EN_BIT 0x2
#define DMATC_INTR_EN_BIT 0x4
#define TIMER_INTR_EN_BIT 0x8
#define ERR_INTR_EN_BIT 0x10
#define ADC_FNE_INTR_EN_BIT 0x20
#define ADC_CONVERT_REG 0x3
#define DAC_LSB_REG(channel) (0x4 + 2 * ((channel) & 0x1))
#define DAC_MSB_REG(channel) (0x5 + 2 * ((channel) & 0x1))
#define ADC_CLEAR_REG 0x8
#define DMATC_CLEAR_REG 0xa
#define TIMER_CLEAR_REG 0xc
#define COMMAND6_REG 0xe
#define ADC_COMMON_BIT 0x1
#define ADC_UNIP_BIT 0x2
#define DAC_UNIP_BIT(channel) (0x4 << ((channel) & 0x1))
#define ADC_FHF_INTR_EN_BIT 0x20
#define A1_INTR_EN_BIT 0x40
#define ADC_SCAN_UP_BIT 0x80
#define COMMAND4_REG 0xf
#define <API key> 0x1
#define EXT_SCAN_EN_BIT 0x2
#define EXT_CONVERT_OUT_BIT 0x4
#define ADC_DIFF_BIT 0x8
#define <API key> 0x10
#define COMMAND5_REG 0x1c
#define <API key> 0x4
#define DITHER_EN_BIT 0x8
#define CALDAC_LOAD_BIT 0x10
#define SCLOCK_BIT 0x20
#define SDATA_BIT 0x40
#define EEPROM_EN_BIT 0x80
#define INTERVAL_COUNT_REG 0x1e
#define INTERVAL_LOAD_REG 0x1f
#define INTERVAL_LOAD_BITS 0x1
#define STATUS1_REG 0x0
#define DATA_AVAIL_BIT 0x1
#define OVERRUN_BIT 0x2
#define OVERFLOW_BIT 0x4
#define TIMER_BIT 0x8
#define DMATC_BIT 0x10
#define EXT_TRIG_BIT 0x40
#define STATUS2_REG 0x1d
#define EEPROM_OUT_BIT 0x1
#define A1_TC_BIT 0x2
#define FNHF_BIT 0x4
#define ADC_FIFO_REG 0xa
#define DIO_BASE_REG 0x10
#define COUNTER_A_BASE_REG 0x14
#define <API key> (COUNTER_A_BASE_REG + 0x3)
#define INIT_A0_BITS 0x14
#define INIT_A1_BITS 0x70
#define COUNTER_B_BASE_REG 0x18
static int labpc_attach(struct comedi_device *dev, struct comedi_devconfig *it);
static int labpc_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
static irqreturn_t labpc_interrupt(int irq, void *d);
static int labpc_drain_fifo(struct comedi_device *dev);
#ifdef CONFIG_ISA_DMA_API
static void labpc_drain_dma(struct comedi_device *dev);
static void handle_isa_dma(struct comedi_device *dev);
#endif
static void labpc_drain_dregs(struct comedi_device *dev);
static int labpc_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd);
static int labpc_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
static int labpc_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int labpc_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int labpc_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int <API key>(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int <API key>(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int <API key>(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int <API key>(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data);
static void labpc_adc_timing(struct comedi_device *dev, struct comedi_cmd *cmd);
#ifdef CONFIG_ISA_DMA_API
static unsigned int <API key>(struct comedi_cmd cmd);
#endif
#ifdef <API key>
static int labpc_find_device(struct comedi_device *dev, int bus, int slot);
#endif
static int <API key>(int dir, int port, int data,
unsigned long arg);
static void labpc_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int num_bits);
static unsigned int labpc_serial_in(struct comedi_device *dev);
static unsigned int labpc_eeprom_read(struct comedi_device *dev,
unsigned int address);
static unsigned int <API key>(struct comedi_device *dev);
static int labpc_eeprom_write(struct comedi_device *dev,
unsigned int address,
unsigned int value);
static void write_caldac(struct comedi_device *dev, unsigned int channel,
unsigned int value);
enum scan_mode {
MODE_SINGLE_CHAN,
<API key>,
MODE_MULT_CHAN_UP,
MODE_MULT_CHAN_DOWN,
};
#define <API key> 16
static const int <API key>[<API key>] = {
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
};
static const int <API key>[<API key>] = {
0x00,
0x10,
0x20,
0x30,
0x40,
0x50,
0x60,
0x70,
0x00,
0x10,
0x20,
0x30,
0x40,
0x50,
0x60,
0x70,
};
static const struct comedi_lrange range_labpc_plus_ai = {
<API key>,
{
BIP_RANGE(5),
BIP_RANGE(4),
BIP_RANGE(2.5),
BIP_RANGE(1),
BIP_RANGE(0.5),
BIP_RANGE(0.25),
BIP_RANGE(0.1),
BIP_RANGE(0.05),
UNI_RANGE(10),
UNI_RANGE(8),
UNI_RANGE(5),
UNI_RANGE(2),
UNI_RANGE(1),
UNI_RANGE(0.5),
UNI_RANGE(0.2),
UNI_RANGE(0.1),
}
};
#define <API key> 14
const int <API key>[<API key>] = {
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
};
EXPORT_SYMBOL_GPL(<API key>);
const int <API key>[<API key>] = {
0x00,
0x20,
0x30,
0x40,
0x50,
0x60,
0x70,
0x00,
0x20,
0x30,
0x40,
0x50,
0x60,
0x70,
};
EXPORT_SYMBOL_GPL(<API key>);
const struct comedi_lrange range_labpc_1200_ai = {
<API key>,
{
BIP_RANGE(5),
BIP_RANGE(2.5),
BIP_RANGE(1),
BIP_RANGE(0.5),
BIP_RANGE(0.25),
BIP_RANGE(0.1),
BIP_RANGE(0.05),
UNI_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(2),
UNI_RANGE(1),
UNI_RANGE(0.5),
UNI_RANGE(0.2),
UNI_RANGE(0.1),
}
};
EXPORT_SYMBOL_GPL(range_labpc_1200_ai);
#define <API key> 0x1
static const struct comedi_lrange range_labpc_ao = {
2,
{
BIP_RANGE(5),
UNI_RANGE(10),
}
};
static inline unsigned int labpc_inb(unsigned long address)
{
return inb(address);
}
static inline void labpc_outb(unsigned int byte, unsigned long address)
{
outb(byte, address);
}
static inline unsigned int labpc_readb(unsigned long address)
{
return readb((void *)address);
}
static inline void labpc_writeb(unsigned int byte, unsigned long address)
{
writeb(byte, (void *)address);
}
static const struct labpc_board_struct labpc_boards[] = {
{
.name = "lab-pc-1200",
.ai_speed = 10000,
.bustype = isa_bustype,
.register_layout = labpc_1200_layout,
.has_ao = 1,
.ai_range_table = &range_labpc_1200_ai,
.ai_range_code = <API key>,
.<API key> = <API key>,
.ai_scan_up = 1,
.memory_mapped_io = 0,
},
{
.name = "lab-pc-1200ai",
.ai_speed = 10000,
.bustype = isa_bustype,
.register_layout = labpc_1200_layout,
.has_ao = 0,
.ai_range_table = &range_labpc_1200_ai,
.ai_range_code = <API key>,
.<API key> = <API key>,
.ai_scan_up = 1,
.memory_mapped_io = 0,
},
{
.name = "lab-pc+",
.ai_speed = 12000,
.bustype = isa_bustype,
.register_layout = labpc_plus_layout,
.has_ao = 1,
.ai_range_table = &range_labpc_plus_ai,
.ai_range_code = <API key>,
.<API key> = <API key>,
.ai_scan_up = 0,
.memory_mapped_io = 0,
},
#ifdef <API key>
{
.name = "pci-1200",
.device_id = 0x161,
.ai_speed = 10000,
.bustype = pci_bustype,
.register_layout = labpc_1200_layout,
.has_ao = 1,
.ai_range_table = &range_labpc_1200_ai,
.ai_range_code = <API key>,
.<API key> = <API key>,
.ai_scan_up = 1,
.memory_mapped_io = 1,
},
{
.name = DRV_NAME,
.bustype = pci_bustype,
},
#endif
};
#define thisboard ((struct labpc_board_struct *)dev->board_ptr)
static const int dma_buffer_size = 0xff00;
static const int sample_size = 2;
#define devpriv ((struct labpc_private *)dev->private)
static struct comedi_driver driver_labpc = {
.driver_name = DRV_NAME,
.module = THIS_MODULE,
.attach = labpc_attach,
.detach = labpc_common_detach,
.num_names = ARRAY_SIZE(labpc_boards),
.board_name = &labpc_boards[0].name,
.offset = sizeof(struct labpc_board_struct),
};
#ifdef <API key>
static <API key>(labpc_pci_table) = {
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x161)},
{0}
};
MODULE_DEVICE_TABLE(pci, labpc_pci_table);
#endif
static inline int labpc_counter_load(struct comedi_device *dev,
unsigned long base_address,
unsigned int counter_number,
unsigned int count, unsigned int mode)
{
if (thisboard->memory_mapped_io)
return i8254_mm_load((void *)base_address, 0, counter_number,
count, mode);
else
return i8254_load(base_address, 0, counter_number, count, mode);
}
int labpc_common_attach(struct comedi_device *dev, unsigned long iobase,
unsigned int irq, unsigned int dma_chan)
{
struct comedi_subdevice *s;
int i;
unsigned long isr_flags;
#ifdef CONFIG_ISA_DMA_API
unsigned long dma_flags;
#endif
short lsb, msb;
printk(KERN_ERR "comedi%d: ni_labpc: %s, io 0x%lx", dev->minor,
thisboard->name,
iobase);
if (irq)
printk(", irq %u", irq);
if (dma_chan)
printk(", dma %u", dma_chan);
printk("\n");
if (iobase == 0) {
printk(KERN_ERR "io base address is zero!\n");
return -EINVAL;
}
if (thisboard->bustype == isa_bustype) {
if (!request_region(iobase, LABPC_SIZE,
driver_labpc.driver_name)) {
printk(KERN_ERR "I/O port conflict\n");
return -EIO;
}
}
dev->iobase = iobase;
if (thisboard->memory_mapped_io) {
devpriv->read_byte = labpc_readb;
devpriv->write_byte = labpc_writeb;
} else {
devpriv->read_byte = labpc_inb;
devpriv->write_byte = labpc_outb;
}
devpriv->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
devpriv->write_byte(devpriv->command4_bits, dev->iobase + COMMAND4_REG);
if (thisboard->register_layout == labpc_1200_layout) {
devpriv->write_byte(devpriv->command5_bits,
dev->iobase + COMMAND5_REG);
devpriv->write_byte(devpriv->command6_bits,
dev->iobase + COMMAND6_REG);
}
if (irq) {
isr_flags = 0;
if (thisboard->bustype == pci_bustype
|| thisboard->bustype == pcmcia_bustype)
isr_flags |= IRQF_SHARED;
if (request_irq(irq, labpc_interrupt, isr_flags,
driver_labpc.driver_name, dev)) {
printk(KERN_ERR "unable to allocate irq %u\n", irq);
return -EINVAL;
}
}
dev->irq = irq;
#ifdef CONFIG_ISA_DMA_API
if (dma_chan > 3) {
printk(KERN_ERR " invalid dma channel %u\n", dma_chan);
return -EINVAL;
} else if (dma_chan) {
devpriv->dma_buffer =
kmalloc(dma_buffer_size, GFP_KERNEL | GFP_DMA);
if (devpriv->dma_buffer == NULL) {
printk(KERN_ERR " failed to allocate dma buffer\n");
return -ENOMEM;
}
if (request_dma(dma_chan, driver_labpc.driver_name)) {
printk(KERN_ERR " failed to allocate dma channel %u\n",
dma_chan);
return -EINVAL;
}
devpriv->dma_chan = dma_chan;
dma_flags = claim_dma_lock();
disable_dma(devpriv->dma_chan);
set_dma_mode(devpriv->dma_chan, DMA_MODE_READ);
release_dma_lock(dma_flags);
}
#endif
dev->board_name = thisboard->name;
if (alloc_subdevices(dev, 5) < 0)
return -ENOMEM;
s = dev->subdevices + 0;
dev->read_subdev = s;
s->type = COMEDI_SUBD_AI;
s->subdev_flags =
SDF_READABLE | SDF_GROUND | SDF_COMMON | SDF_DIFF | SDF_CMD_READ;
s->n_chan = 8;
s->len_chanlist = 8;
s->maxdata = (1 << 12) - 1;
s->range_table = thisboard->ai_range_table;
s->do_cmd = labpc_ai_cmd;
s->do_cmdtest = labpc_ai_cmdtest;
s->insn_read = labpc_ai_rinsn;
s->cancel = labpc_cancel;
s = dev->subdevices + 1;
if (thisboard->has_ao) {
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_GROUND;
s->n_chan = NUM_AO_CHAN;
s->maxdata = (1 << 12) - 1;
s->range_table = &range_labpc_ao;
s->insn_read = labpc_ao_rinsn;
s->insn_write = labpc_ao_winsn;
for (i = 0; i < s->n_chan; i++) {
devpriv->ao_value[i] = s->maxdata / 2;
lsb = devpriv->ao_value[i] & 0xff;
msb = (devpriv->ao_value[i] >> 8) & 0xff;
devpriv->write_byte(lsb, dev->iobase + DAC_LSB_REG(i));
devpriv->write_byte(msb, dev->iobase + DAC_MSB_REG(i));
}
} else {
s->type = COMEDI_SUBD_UNUSED;
}
s = dev->subdevices + 2;
if (thisboard->memory_mapped_io)
subdev_8255_init(dev, s, <API key>,
(unsigned long)(dev->iobase + DIO_BASE_REG));
else
subdev_8255_init(dev, s, NULL, dev->iobase + DIO_BASE_REG);
s = dev->subdevices + 3;
if (thisboard->register_layout == labpc_1200_layout) {
s->type = COMEDI_SUBD_CALIB;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
s->n_chan = 16;
s->maxdata = 0xff;
s->insn_read = <API key>;
s->insn_write = <API key>;
for (i = 0; i < s->n_chan; i++)
write_caldac(dev, i, s->maxdata / 2);
} else
s->type = COMEDI_SUBD_UNUSED;
s = dev->subdevices + 4;
if (thisboard->register_layout == labpc_1200_layout) {
s->type = COMEDI_SUBD_MEMORY;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
s->n_chan = EEPROM_SIZE;
s->maxdata = 0xff;
s->insn_read = <API key>;
s->insn_write = <API key>;
for (i = 0; i < EEPROM_SIZE; i++)
devpriv->eeprom_data[i] = labpc_eeprom_read(dev, i);
#ifdef LABPC_DEBUG
printk(KERN_ERR " eeprom:");
for (i = 0; i < EEPROM_SIZE; i++)
printk(" %i:0x%x ", i, devpriv->eeprom_data[i]);
printk("\n");
#endif
} else
s->type = COMEDI_SUBD_UNUSED;
return 0;
}
EXPORT_SYMBOL_GPL(labpc_common_attach);
static int labpc_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
unsigned long iobase = 0;
unsigned int irq = 0;
unsigned int dma_chan = 0;
#ifdef <API key>
int retval;
#endif
if (alloc_private(dev, sizeof(struct labpc_private)) < 0)
return -ENOMEM;
switch (thisboard->bustype) {
case isa_bustype:
#ifdef CONFIG_ISA_DMA_API
iobase = it->options[0];
irq = it->options[1];
dma_chan = it->options[2];
#else
printk(KERN_ERR " this driver has not been built with ISA DMA "
"support.\n");
return -EINVAL;
#endif
break;
case pci_bustype:
#ifdef <API key>
retval = labpc_find_device(dev, it->options[0], it->options[1]);
if (retval < 0)
return retval;
retval = mite_setup(devpriv->mite);
if (retval < 0)
return retval;
iobase = (unsigned long)devpriv->mite->daq_io_addr;
irq = mite_irq(devpriv->mite);
#else
printk(KERN_ERR " this driver has not been built with PCI "
"support.\n");
return -EINVAL;
#endif
break;
case pcmcia_bustype:
printk
(" this driver does not support pcmcia cards, use ni_labpc_cs.o\n");
return -EINVAL;
break;
default:
printk(KERN_ERR "bug! couldn't determine board type\n");
return -EINVAL;
break;
}
return labpc_common_attach(dev, iobase, irq, dma_chan);
}
#ifdef <API key>
static int labpc_find_device(struct comedi_device *dev, int bus, int slot)
{
struct mite_struct *mite;
int i;
for (mite = mite_devices; mite; mite = mite->next) {
if (mite->used)
continue;
if (bus || slot) {
if (bus != mite->pcidev->bus->number
|| slot != PCI_SLOT(mite->pcidev->devfn))
continue;
}
for (i = 0; i < driver_labpc.num_names; i++) {
if (labpc_boards[i].bustype != pci_bustype)
continue;
if (mite_device_id(mite) == labpc_boards[i].device_id) {
devpriv->mite = mite;
dev->board_ptr = &labpc_boards[i];
return 0;
}
}
}
printk(KERN_ERR "no device found\n");
mite_list_devices();
return -EIO;
}
#endif
int labpc_common_detach(struct comedi_device *dev)
{
printk(KERN_ERR "comedi%d: ni_labpc: detach\n", dev->minor);
if (dev->subdevices)
subdev_8255_cleanup(dev, dev->subdevices + 2);
#ifdef CONFIG_ISA_DMA_API
kfree(devpriv->dma_buffer);
if (devpriv->dma_chan)
free_dma(devpriv->dma_chan);
#endif
if (dev->irq)
free_irq(dev->irq, dev);
if (thisboard->bustype == isa_bustype && dev->iobase)
release_region(dev->iobase, LABPC_SIZE);
#ifdef <API key>
if (devpriv->mite)
mite_unsetup(devpriv->mite);
#endif
return 0;
};
EXPORT_SYMBOL_GPL(labpc_common_detach);
static void <API key>(const struct comedi_device *dev)
{
devpriv->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
}
static int labpc_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
unsigned long flags;
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
<API key>(&dev->spinlock, flags);
devpriv->command3_bits = 0;
devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
return 0;
}
static enum scan_mode labpc_ai_scan_mode(const struct comedi_cmd *cmd)
{
if (cmd->chanlist_len == 1)
return MODE_SINGLE_CHAN;
if (cmd->chanlist == NULL)
return MODE_MULT_CHAN_UP;
if (CR_CHAN(cmd->chanlist[0]) == CR_CHAN(cmd->chanlist[1]))
return <API key>;
if (CR_CHAN(cmd->chanlist[0]) < CR_CHAN(cmd->chanlist[1]))
return MODE_MULT_CHAN_UP;
if (CR_CHAN(cmd->chanlist[0]) > CR_CHAN(cmd->chanlist[1]))
return MODE_MULT_CHAN_DOWN;
printk(KERN_ERR "ni_labpc: bug! this should never happen\n");
return 0;
}
static int <API key>(const struct comedi_device *dev,
const struct comedi_cmd *cmd)
{
int mode, channel, range, aref, i;
if (cmd->chanlist == NULL)
return 0;
mode = labpc_ai_scan_mode(cmd);
if (mode == MODE_SINGLE_CHAN)
return 0;
if (mode == <API key>) {
if (cmd->chanlist_len > 0xff) {
comedi_error(dev,
"ni_labpc: chanlist too long for single channel interval mode\n");
return 1;
}
}
channel = CR_CHAN(cmd->chanlist[0]);
range = CR_RANGE(cmd->chanlist[0]);
aref = CR_AREF(cmd->chanlist[0]);
for (i = 0; i < cmd->chanlist_len; i++) {
switch (mode) {
case <API key>:
if (CR_CHAN(cmd->chanlist[i]) != channel) {
comedi_error(dev,
"channel scanning order specified in chanlist is not supported by hardware.\n");
return 1;
}
break;
case MODE_MULT_CHAN_UP:
if (CR_CHAN(cmd->chanlist[i]) != i) {
comedi_error(dev,
"channel scanning order specified in chanlist is not supported by hardware.\n");
return 1;
}
break;
case MODE_MULT_CHAN_DOWN:
if (CR_CHAN(cmd->chanlist[i]) !=
cmd->chanlist_len - i - 1) {
comedi_error(dev,
"channel scanning order specified in chanlist is not supported by hardware.\n");
return 1;
}
break;
default:
printk(KERN_ERR "ni_labpc: bug! in chanlist check\n");
return 1;
break;
}
if (CR_RANGE(cmd->chanlist[i]) != range) {
comedi_error(dev,
"entries in chanlist must all have the same range\n");
return 1;
}
if (CR_AREF(cmd->chanlist[i]) != aref) {
comedi_error(dev,
"entries in chanlist must all have the same reference\n");
return 1;
}
}
return 0;
}
static int <API key>(const struct comedi_cmd *cmd)
{
if (labpc_ai_scan_mode(cmd) == MODE_SINGLE_CHAN)
return 1;
if (cmd->scan_begin_src == TRIG_FOLLOW)
return 1;
return 0;
}
static unsigned int <API key>(const struct comedi_cmd *cmd)
{
if (cmd->convert_src != TRIG_TIMER)
return 0;
if (labpc_ai_scan_mode(cmd) == MODE_SINGLE_CHAN &&
cmd->scan_begin_src == TRIG_TIMER)
return cmd->scan_begin_arg;
return cmd->convert_arg;
}
static void <API key>(struct comedi_cmd *cmd, unsigned int ns)
{
if (cmd->convert_src != TRIG_TIMER)
return;
if (labpc_ai_scan_mode(cmd) == MODE_SINGLE_CHAN &&
cmd->scan_begin_src == TRIG_TIMER) {
cmd->scan_begin_arg = ns;
if (cmd->convert_arg > cmd->scan_begin_arg)
cmd->convert_arg = cmd->scan_begin_arg;
} else
cmd->convert_arg = ns;
}
static unsigned int <API key>(const struct comedi_cmd *cmd)
{
if (cmd->scan_begin_src != TRIG_TIMER)
return 0;
if (labpc_ai_scan_mode(cmd) == MODE_SINGLE_CHAN &&
cmd->convert_src == TRIG_TIMER)
return 0;
return cmd->scan_begin_arg;
}
static void <API key>(struct comedi_cmd *cmd, unsigned int ns)
{
if (cmd->scan_begin_src != TRIG_TIMER)
return;
if (labpc_ai_scan_mode(cmd) == MODE_SINGLE_CHAN &&
cmd->convert_src == TRIG_TIMER)
return;
cmd->scan_begin_arg = ns;
}
static int labpc_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd)
{
int err = 0;
int tmp, tmp2;
int stop_mask;
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW | TRIG_EXT;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_TIMER | TRIG_FOLLOW | TRIG_EXT;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
stop_mask = TRIG_COUNT | TRIG_NONE;
if (thisboard->register_layout == labpc_1200_layout)
stop_mask |= TRIG_EXT;
cmd->stop_src &= stop_mask;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
if (cmd->start_src != TRIG_NOW && cmd->start_src != TRIG_EXT)
err++;
if (cmd->scan_begin_src != TRIG_TIMER &&
cmd->scan_begin_src != TRIG_FOLLOW &&
cmd->scan_begin_src != TRIG_EXT)
err++;
if (cmd->convert_src != TRIG_TIMER && cmd->convert_src != TRIG_EXT)
err++;
if (cmd->stop_src != TRIG_COUNT &&
cmd->stop_src != TRIG_EXT && cmd->stop_src != TRIG_NONE)
err++;
if (cmd->start_src == TRIG_EXT && cmd->stop_src == TRIG_EXT)
err++;
if (err)
return 2;
if (cmd->start_arg == TRIG_NOW && cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
if (!cmd->chanlist_len)
err++;
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->convert_src == TRIG_TIMER) {
if (cmd->convert_arg < thisboard->ai_speed) {
cmd->convert_arg = thisboard->ai_speed;
err++;
}
}
if (cmd->scan_begin_src == TRIG_TIMER) {
if (cmd->convert_src == TRIG_TIMER &&
cmd->scan_begin_arg <
cmd->convert_arg * cmd->chanlist_len) {
cmd->scan_begin_arg =
cmd->convert_arg * cmd->chanlist_len;
err++;
}
if (cmd->scan_begin_arg <
thisboard->ai_speed * cmd->chanlist_len) {
cmd->scan_begin_arg =
thisboard->ai_speed * cmd->chanlist_len;
err++;
}
}
switch (cmd->stop_src) {
case TRIG_COUNT:
if (!cmd->stop_arg) {
cmd->stop_arg = 1;
err++;
}
break;
case TRIG_NONE:
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
break;
default:
break;
}
if (err)
return 3;
tmp = cmd->convert_arg;
tmp2 = cmd->scan_begin_arg;
labpc_adc_timing(dev, cmd);
if (tmp != cmd->convert_arg || tmp2 != cmd->scan_begin_arg)
err++;
if (err)
return 4;
if (<API key>(dev, cmd))
return 5;
return 0;
}
static int labpc_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
int channel, range, aref;
#ifdef CONFIG_ISA_DMA_API
unsigned long irq_flags;
#endif
int ret;
struct comedi_async *async = s->async;
struct comedi_cmd *cmd = &async->cmd;
enum transfer_type xfer;
unsigned long flags;
if (!dev->irq) {
comedi_error(dev, "no irq assigned, cannot perform command");
return -1;
}
range = CR_RANGE(cmd->chanlist[0]);
aref = CR_AREF(cmd->chanlist[0]);
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
<API key>(&dev->spinlock, flags);
devpriv->command3_bits = 0;
devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
if (cmd->stop_src == TRIG_COUNT)
devpriv->count = cmd->stop_arg * cmd->chanlist_len;
if (cmd->stop_src == TRIG_EXT) {
ret = labpc_counter_load(dev, dev->iobase + COUNTER_A_BASE_REG,
1, 3, 0);
if (ret < 0) {
comedi_error(dev, "error loading counter a1");
return -1;
}
} else /*
*/
devpriv->write_byte(INIT_A1_BITS,
dev->iobase + <API key>);
#ifdef CONFIG_ISA_DMA_API
if (devpriv->dma_chan &&
(cmd->flags & (TRIG_WAKE_EOS | TRIG_RT)) == 0 &&
thisboard->bustype == isa_bustype) {
xfer = isa_dma_transfer;
} else
#endif
if (thisboard->register_layout == labpc_1200_layout &&
(cmd->flags & TRIG_WAKE_EOS) == 0 &&
(cmd->stop_src != TRIG_COUNT || devpriv->count > 256)) {
xfer = <API key>;
} else
xfer = <API key>;
devpriv->current_transfer = xfer;
if (thisboard->register_layout == labpc_1200_layout) {
if (aref != AREF_GROUND)
devpriv->command6_bits |= ADC_COMMON_BIT;
else
devpriv->command6_bits &= ~ADC_COMMON_BIT;
if (thisboard-><API key>[range])
devpriv->command6_bits |= ADC_UNIP_BIT;
else
devpriv->command6_bits &= ~ADC_UNIP_BIT;
if (xfer == <API key>)
devpriv->command6_bits |= ADC_FHF_INTR_EN_BIT;
else
devpriv->command6_bits &= ~ADC_FHF_INTR_EN_BIT;
if (cmd->stop_src == TRIG_EXT)
devpriv->command6_bits |= A1_INTR_EN_BIT;
else
devpriv->command6_bits &= ~A1_INTR_EN_BIT;
if (labpc_ai_scan_mode(cmd) == MODE_MULT_CHAN_UP)
devpriv->command6_bits |= ADC_SCAN_UP_BIT;
else
devpriv->command6_bits &= ~ADC_SCAN_UP_BIT;
devpriv->write_byte(devpriv->command6_bits,
dev->iobase + COMMAND6_REG);
}
devpriv->command1_bits = 0;
if (labpc_ai_scan_mode(cmd) == MODE_MULT_CHAN_UP)
channel = CR_CHAN(cmd->chanlist[cmd->chanlist_len - 1]);
else
channel = CR_CHAN(cmd->chanlist[0]);
if (labpc_ai_scan_mode(cmd) != MODE_SINGLE_CHAN && aref == AREF_DIFF)
channel *= 2;
devpriv->command1_bits |= ADC_CHAN_BITS(channel);
devpriv->command1_bits |= thisboard->ai_range_code[range];
devpriv->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
if (labpc_ai_scan_mode(cmd) == MODE_MULT_CHAN_UP ||
labpc_ai_scan_mode(cmd) == MODE_MULT_CHAN_DOWN) {
devpriv->command1_bits |= ADC_SCAN_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command1_bits,
dev->iobase + COMMAND1_REG);
}
devpriv->command4_bits = 0;
if (cmd->convert_src != TRIG_EXT)
devpriv->command4_bits |= <API key>;
if (<API key>(cmd) == 0) {
devpriv->command4_bits |= <API key>;
if (cmd->scan_begin_src == TRIG_EXT)
devpriv->command4_bits |= EXT_SCAN_EN_BIT;
}
if (aref == AREF_DIFF)
devpriv->command4_bits |= ADC_DIFF_BIT;
devpriv->write_byte(devpriv->command4_bits, dev->iobase + COMMAND4_REG);
devpriv->write_byte(cmd->chanlist_len,
dev->iobase + INTERVAL_COUNT_REG);
devpriv->write_byte(INTERVAL_LOAD_BITS,
dev->iobase + INTERVAL_LOAD_REG);
if (cmd->convert_src == TRIG_TIMER || cmd->scan_begin_src == TRIG_TIMER) {
labpc_adc_timing(dev, cmd);
ret = labpc_counter_load(dev, dev->iobase + COUNTER_B_BASE_REG,
0, devpriv->divisor_b0, 3);
if (ret < 0) {
comedi_error(dev, "error loading counter b0");
return -1;
}
}
if (<API key>(cmd)) {
ret = labpc_counter_load(dev, dev->iobase + COUNTER_A_BASE_REG,
0, devpriv->divisor_a0, 2);
if (ret < 0) {
comedi_error(dev, "error loading counter a0");
return -1;
}
} else
devpriv->write_byte(INIT_A0_BITS,
dev->iobase + <API key>);
if (<API key>(cmd)) {
ret = labpc_counter_load(dev, dev->iobase + COUNTER_B_BASE_REG,
1, devpriv->divisor_b1, 2);
if (ret < 0) {
comedi_error(dev, "error loading counter b1");
return -1;
}
}
<API key>(dev);
#ifdef CONFIG_ISA_DMA_API
if (xfer == isa_dma_transfer) {
irq_flags = claim_dma_lock();
disable_dma(devpriv->dma_chan);
clear_dma_ff(devpriv->dma_chan);
set_dma_addr(devpriv->dma_chan,
virt_to_bus(devpriv->dma_buffer));
devpriv->dma_transfer_size = <API key>(*cmd);
if (cmd->stop_src == TRIG_COUNT &&
devpriv->count * sample_size < devpriv->dma_transfer_size) {
devpriv->dma_transfer_size =
devpriv->count * sample_size;
}
set_dma_count(devpriv->dma_chan, devpriv->dma_transfer_size);
enable_dma(devpriv->dma_chan);
release_dma_lock(irq_flags);
devpriv->command3_bits |= DMA_EN_BIT | DMATC_INTR_EN_BIT;
} else
devpriv->command3_bits &= ~DMA_EN_BIT & ~DMATC_INTR_EN_BIT;
#endif
devpriv->command3_bits |= ERR_INTR_EN_BIT;
if (xfer == <API key>)
devpriv->command3_bits |= ADC_FNE_INTR_EN_BIT;
else
devpriv->command3_bits &= ~ADC_FNE_INTR_EN_BIT;
devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->command2_bits |= CASCADE_BIT;
switch (cmd->start_src) {
case TRIG_EXT:
devpriv->command2_bits |= HWTRIG_BIT;
devpriv->command2_bits &= ~PRETRIG_BIT & ~SWTRIG_BIT;
break;
case TRIG_NOW:
devpriv->command2_bits |= SWTRIG_BIT;
devpriv->command2_bits &= ~PRETRIG_BIT & ~HWTRIG_BIT;
break;
default:
comedi_error(dev, "bug with start_src");
return -1;
break;
}
switch (cmd->stop_src) {
case TRIG_EXT:
devpriv->command2_bits |= HWTRIG_BIT | PRETRIG_BIT;
break;
case TRIG_COUNT:
case TRIG_NONE:
break;
default:
comedi_error(dev, "bug with stop_src");
return -1;
}
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
<API key>(&dev->spinlock, flags);
return 0;
}
static irqreturn_t labpc_interrupt(int irq, void *d)
{
struct comedi_device *dev = d;
struct comedi_subdevice *s = dev->read_subdev;
struct comedi_async *async;
struct comedi_cmd *cmd;
if (dev->attached == 0) {
comedi_error(dev, "premature interrupt");
return IRQ_HANDLED;
}
async = s->async;
cmd = &async->cmd;
async->events = 0;
devpriv->status1_bits = devpriv->read_byte(dev->iobase + STATUS1_REG);
if (thisboard->register_layout == labpc_1200_layout)
devpriv->status2_bits =
devpriv->read_byte(dev->iobase + STATUS2_REG);
if ((devpriv->status1_bits & (DMATC_BIT | TIMER_BIT | OVERFLOW_BIT |
OVERRUN_BIT | DATA_AVAIL_BIT)) == 0
&& (devpriv->status2_bits & A1_TC_BIT) == 0
&& (devpriv->status2_bits & FNHF_BIT)) {
return IRQ_NONE;
}
if (devpriv->status1_bits & OVERRUN_BIT) {
devpriv->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
comedi_event(dev, s);
comedi_error(dev, "overrun");
return IRQ_HANDLED;
}
#ifdef CONFIG_ISA_DMA_API
if (devpriv->current_transfer == isa_dma_transfer) {
if (devpriv->status1_bits & DMATC_BIT ||
(thisboard->register_layout == labpc_1200_layout
&& devpriv->status2_bits & A1_TC_BIT)) {
handle_isa_dma(dev);
}
} else
#endif
labpc_drain_fifo(dev);
if (devpriv->status1_bits & TIMER_BIT) {
comedi_error(dev, "handled timer interrupt?");
devpriv->write_byte(0x1, dev->iobase + TIMER_CLEAR_REG);
}
if (devpriv->status1_bits & OVERFLOW_BIT) {
devpriv->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
comedi_event(dev, s);
comedi_error(dev, "overflow");
return IRQ_HANDLED;
}
if (cmd->stop_src == TRIG_EXT) {
if (devpriv->status2_bits & A1_TC_BIT) {
labpc_drain_dregs(dev);
labpc_cancel(dev, s);
async->events |= COMEDI_CB_EOA;
}
}
if (cmd->stop_src == TRIG_COUNT) {
if (devpriv->count == 0) {
labpc_cancel(dev, s);
async->events |= COMEDI_CB_EOA;
}
}
comedi_event(dev, s);
return IRQ_HANDLED;
}
static int labpc_drain_fifo(struct comedi_device *dev)
{
unsigned int lsb, msb;
short data;
struct comedi_async *async = dev->read_subdev->async;
const int timeout = 10000;
unsigned int i;
devpriv->status1_bits = devpriv->read_byte(dev->iobase + STATUS1_REG);
for (i = 0; (devpriv->status1_bits & DATA_AVAIL_BIT) && i < timeout;
i++) {
if (async->cmd.stop_src == TRIG_COUNT) {
if (devpriv->count == 0)
break;
devpriv->count
}
lsb = devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
msb = devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
data = (msb << 8) | lsb;
cfc_write_to_buffer(dev->read_subdev, data);
devpriv->status1_bits =
devpriv->read_byte(dev->iobase + STATUS1_REG);
}
if (i == timeout) {
comedi_error(dev, "ai timeout, fifo never empties");
async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
return -1;
}
return 0;
}
#ifdef CONFIG_ISA_DMA_API
static void labpc_drain_dma(struct comedi_device *dev)
{
struct comedi_subdevice *s = dev->read_subdev;
struct comedi_async *async = s->async;
int status;
unsigned long flags;
unsigned int max_points, num_points, residue, leftover;
int i;
status = devpriv->status1_bits;
flags = claim_dma_lock();
disable_dma(devpriv->dma_chan);
clear_dma_ff(devpriv->dma_chan);
max_points = devpriv->dma_transfer_size / sample_size;
residue = get_dma_residue(devpriv->dma_chan) / sample_size;
num_points = max_points - residue;
if (devpriv->count < num_points && async->cmd.stop_src == TRIG_COUNT)
num_points = devpriv->count;
leftover = 0;
if (async->cmd.stop_src != TRIG_COUNT) {
leftover = devpriv->dma_transfer_size / sample_size;
} else if (devpriv->count > num_points) {
leftover = devpriv->count - num_points;
if (leftover > max_points)
leftover = max_points;
}
for (i = 0; i < num_points; i++)
cfc_write_to_buffer(s, devpriv->dma_buffer[i]);
if (async->cmd.stop_src == TRIG_COUNT)
devpriv->count -= num_points;
set_dma_addr(devpriv->dma_chan, virt_to_bus(devpriv->dma_buffer));
set_dma_count(devpriv->dma_chan, leftover * sample_size);
release_dma_lock(flags);
async->events |= COMEDI_CB_BLOCK;
}
static void handle_isa_dma(struct comedi_device *dev)
{
labpc_drain_dma(dev);
enable_dma(devpriv->dma_chan);
devpriv->write_byte(0x1, dev->iobase + DMATC_CLEAR_REG);
}
#endif
static void labpc_drain_dregs(struct comedi_device *dev)
{
#ifdef CONFIG_ISA_DMA_API
if (devpriv->current_transfer == isa_dma_transfer)
labpc_drain_dma(dev);
#endif
labpc_drain_fifo(dev);
}
static int labpc_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i, n;
int chan, range;
int lsb, msb;
int timeout = 1000;
unsigned long flags;
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
<API key>(&dev->spinlock, flags);
devpriv->command3_bits = 0;
devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
devpriv->command1_bits = 0;
chan = CR_CHAN(insn->chanspec);
range = CR_RANGE(insn->chanspec);
devpriv->command1_bits |= thisboard->ai_range_code[range];
if (CR_AREF(insn->chanspec) == AREF_DIFF)
chan *= 2;
devpriv->command1_bits |= ADC_CHAN_BITS(chan);
devpriv->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
if (thisboard->register_layout == labpc_1200_layout) {
if (CR_AREF(insn->chanspec) != AREF_GROUND)
devpriv->command6_bits |= ADC_COMMON_BIT;
else
devpriv->command6_bits &= ~ADC_COMMON_BIT;
if (thisboard-><API key>[range])
devpriv->command6_bits |= ADC_UNIP_BIT;
else
devpriv->command6_bits &= ~ADC_UNIP_BIT;
devpriv->command6_bits &= ~ADC_FHF_INTR_EN_BIT;
devpriv->command6_bits &= ~A1_INTR_EN_BIT;
devpriv->write_byte(devpriv->command6_bits,
dev->iobase + COMMAND6_REG);
}
devpriv->command4_bits = 0;
devpriv->command4_bits |= <API key>;
if (CR_AREF(insn->chanspec) == AREF_DIFF)
devpriv->command4_bits |= ADC_DIFF_BIT;
devpriv->write_byte(devpriv->command4_bits, dev->iobase + COMMAND4_REG);
devpriv->write_byte(INIT_A0_BITS, dev->iobase + <API key>);
<API key>(dev);
for (n = 0; n < insn->n; n++) {
devpriv->write_byte(0x1, dev->iobase + ADC_CONVERT_REG);
for (i = 0; i < timeout; i++) {
if (devpriv->read_byte(dev->iobase +
STATUS1_REG) & DATA_AVAIL_BIT)
break;
udelay(1);
}
if (i == timeout) {
comedi_error(dev, "timeout");
return -ETIME;
}
lsb = devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
msb = devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
data[n] = (msb << 8) | lsb;
}
return n;
}
static int labpc_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int channel, range;
unsigned long flags;
int lsb, msb;
channel = CR_CHAN(insn->chanspec);
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->command2_bits &= ~DAC_PACED_BIT(channel);
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
<API key>(&dev->spinlock, flags);
if (thisboard->register_layout == labpc_1200_layout) {
range = CR_RANGE(insn->chanspec);
if (range & <API key>)
devpriv->command6_bits |= DAC_UNIP_BIT(channel);
else
devpriv->command6_bits &= ~DAC_UNIP_BIT(channel);
devpriv->write_byte(devpriv->command6_bits,
dev->iobase + COMMAND6_REG);
}
lsb = data[0] & 0xff;
msb = (data[0] >> 8) & 0xff;
devpriv->write_byte(lsb, dev->iobase + DAC_LSB_REG(channel));
devpriv->write_byte(msb, dev->iobase + DAC_MSB_REG(channel));
devpriv->ao_value[channel] = data[0];
return 1;
}
static int labpc_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
data[0] = devpriv->ao_value[CR_CHAN(insn->chanspec)];
return 1;
}
static int <API key>(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
data[0] = devpriv->caldac[CR_CHAN(insn->chanspec)];
return 1;
}
static int <API key>(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int channel = CR_CHAN(insn->chanspec);
write_caldac(dev, channel, data[0]);
return 1;
}
static int <API key>(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
data[0] = devpriv->eeprom_data[CR_CHAN(insn->chanspec)];
return 1;
}
static int <API key>(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int channel = CR_CHAN(insn->chanspec);
int ret;
if (channel < 16 || channel > 127) {
printk
("eeprom writes are only allowed to channels 16 through 127 (the pointer and user areas)");
return -EINVAL;
}
ret = labpc_eeprom_write(dev, channel, data[0]);
if (ret < 0)
return ret;
return 1;
}
#ifdef CONFIG_ISA_DMA_API
static unsigned int <API key>(struct comedi_cmd cmd)
{
unsigned int size;
unsigned int freq;
if (cmd.convert_src == TRIG_TIMER)
freq = 1000000000 / cmd.convert_arg;
else
freq = 0xffffffff;
size = (freq / 3) * sample_size;
if (size > dma_buffer_size)
size = dma_buffer_size - dma_buffer_size % sample_size;
else if (size < sample_size)
size = sample_size;
return size;
}
#endif
static void labpc_adc_timing(struct comedi_device *dev, struct comedi_cmd *cmd)
{
const int max_counter_value = 0x10000;
const int min_counter_value = 2;
unsigned int base_period;
if (<API key>(cmd) && <API key>(cmd)) {
devpriv->divisor_b0 = (<API key>(cmd) - 1) /
(LABPC_TIMER_BASE * max_counter_value) + 1;
if (devpriv->divisor_b0 < min_counter_value)
devpriv->divisor_b0 = min_counter_value;
if (devpriv->divisor_b0 > max_counter_value)
devpriv->divisor_b0 = max_counter_value;
base_period = LABPC_TIMER_BASE * devpriv->divisor_b0;
switch (cmd->flags & TRIG_ROUND_MASK) {
default:
case TRIG_ROUND_NEAREST:
devpriv->divisor_a0 =
(<API key>(cmd) +
(base_period / 2)) / base_period;
devpriv->divisor_b1 =
(<API key>(cmd) +
(base_period / 2)) / base_period;
break;
case TRIG_ROUND_UP:
devpriv->divisor_a0 =
(<API key>(cmd) + (base_period -
1)) / base_period;
devpriv->divisor_b1 =
(<API key>(cmd) + (base_period -
1)) / base_period;
break;
case TRIG_ROUND_DOWN:
devpriv->divisor_a0 =
<API key>(cmd) / base_period;
devpriv->divisor_b1 =
<API key>(cmd) / base_period;
break;
}
if (devpriv->divisor_a0 < min_counter_value)
devpriv->divisor_a0 = min_counter_value;
if (devpriv->divisor_a0 > max_counter_value)
devpriv->divisor_a0 = max_counter_value;
if (devpriv->divisor_b1 < min_counter_value)
devpriv->divisor_b1 = min_counter_value;
if (devpriv->divisor_b1 > max_counter_value)
devpriv->divisor_b1 = max_counter_value;
<API key>(cmd,
base_period * devpriv->divisor_a0);
<API key>(cmd,
base_period * devpriv->divisor_b1);
} else if (<API key>(cmd)) {
unsigned int scan_period;
scan_period = <API key>(cmd);
<API key>(LABPC_TIMER_BASE,
&(devpriv->divisor_b1),
&(devpriv->divisor_b0),
&scan_period,
cmd->flags & TRIG_ROUND_MASK);
<API key>(cmd, scan_period);
} else if (<API key>(cmd)) {
unsigned int convert_period;
convert_period = <API key>(cmd);
<API key>(LABPC_TIMER_BASE,
&(devpriv->divisor_a0),
&(devpriv->divisor_b0),
&convert_period,
cmd->flags & TRIG_ROUND_MASK);
<API key>(cmd, convert_period);
}
}
static int <API key>(int dir, int port, int data,
unsigned long iobase)
{
if (dir) {
writeb(data, (void *)(iobase + port));
return 0;
} else {
return readb((void *)(iobase + port));
}
}
static void labpc_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int value_width)
{
int i;
for (i = 1; i <= value_width; i++) {
devpriv->command5_bits &= ~SCLOCK_BIT;
if (value & (1 << (value_width - i)))
devpriv->command5_bits |= SDATA_BIT;
else
devpriv->command5_bits &= ~SDATA_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits,
dev->iobase + COMMAND5_REG);
devpriv->command5_bits |= SCLOCK_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits,
dev->iobase + COMMAND5_REG);
}
}
static unsigned int labpc_serial_in(struct comedi_device *dev)
{
unsigned int value = 0;
int i;
const int value_width = 8;
for (i = 1; i <= value_width; i++) {
devpriv->command5_bits |= SCLOCK_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits,
dev->iobase + COMMAND5_REG);
devpriv->command5_bits &= ~SCLOCK_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits,
dev->iobase + COMMAND5_REG);
udelay(1);
devpriv->status2_bits =
devpriv->read_byte(dev->iobase + STATUS2_REG);
if (devpriv->status2_bits & EEPROM_OUT_BIT)
value |= 1 << (value_width - i);
}
return value;
}
static unsigned int labpc_eeprom_read(struct comedi_device *dev,
unsigned int address)
{
unsigned int value;
const int read_instruction = 0x3;
const int write_length = 8;
devpriv->command5_bits &= ~EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
devpriv->command5_bits |= EEPROM_EN_BIT | <API key>;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
labpc_serial_out(dev, read_instruction, write_length);
labpc_serial_out(dev, address, write_length);
value = labpc_serial_in(dev);
devpriv->command5_bits &= ~EEPROM_EN_BIT & ~<API key>;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
return value;
}
static int labpc_eeprom_write(struct comedi_device *dev,
unsigned int address, unsigned int value)
{
const int <API key> = 0x6;
const int write_instruction = 0x2;
const int write_length = 8;
const int <API key> = 0x1;
const int timeout = 10000;
int i;
for (i = 0; i < timeout; i++) {
if ((<API key>(dev) & <API key>) ==
0)
break;
}
if (i == timeout) {
comedi_error(dev, "eeprom write timed out");
return -ETIME;
}
devpriv->eeprom_data[address] = value;
devpriv->command5_bits &= ~EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
devpriv->command5_bits |= EEPROM_EN_BIT | <API key>;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
labpc_serial_out(dev, <API key>, write_length);
devpriv->command5_bits &= ~EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
devpriv->command5_bits |= EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
labpc_serial_out(dev, write_instruction, write_length);
labpc_serial_out(dev, address, write_length);
labpc_serial_out(dev, value, write_length);
devpriv->command5_bits &= ~EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
devpriv->command5_bits &= ~EEPROM_EN_BIT & ~<API key>;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
return 0;
}
static unsigned int <API key>(struct comedi_device *dev)
{
unsigned int value;
const int <API key> = 0x5;
const int write_length = 8;
devpriv->command5_bits &= ~EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
devpriv->command5_bits |= EEPROM_EN_BIT | <API key>;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
labpc_serial_out(dev, <API key>, write_length);
value = labpc_serial_in(dev);
devpriv->command5_bits &= ~EEPROM_EN_BIT & ~<API key>;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
return value;
}
static void write_caldac(struct comedi_device *dev, unsigned int channel,
unsigned int value)
{
if (value == devpriv->caldac[channel])
return;
devpriv->caldac[channel] = value;
devpriv->command5_bits &=
~CALDAC_LOAD_BIT & ~EEPROM_EN_BIT & ~<API key>;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
labpc_serial_out(dev, channel, 4);
labpc_serial_out(dev, value, 8);
devpriv->command5_bits |= CALDAC_LOAD_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
devpriv->command5_bits &= ~CALDAC_LOAD_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
}
#ifdef <API key>
static int __devinit <API key>(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return <API key>(dev, driver_labpc.driver_name);
}
static void __devexit <API key>(struct pci_dev *dev)
{
<API key>(dev);
}
static struct pci_driver <API key> = {
.id_table = labpc_pci_table,
.probe = &<API key>,
.remove = __devexit_p(&<API key>)
};
static int __init <API key>(void)
{
int retval;
retval = <API key>(&driver_labpc);
if (retval < 0)
return retval;
<API key>.name = (char *)driver_labpc.driver_name;
return pci_register_driver(&<API key>);
}
static void __exit <API key>(void)
{
<API key>(&<API key>);
<API key>(&driver_labpc);
}
module_init(<API key>);
module_exit(<API key>);
#else
static int __init <API key>(void)
{
return <API key>(&driver_labpc);
}
static void __exit <API key>(void)
{
<API key>(&driver_labpc);
}
module_init(<API key>);
module_exit(<API key>);
#endif
MODULE_AUTHOR("Comedi http:
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL"); |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http:
<head>
<title>Qt 4.4: Main Window</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http:
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="namespaces.html"><font color="#004faf">All Namespaces</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="mainclasses.html"><font color="#004faf">Main Classes</font></a> · <a href="groups.html"><font color="#004faf">Grouped Classes</font></a> · <a href="modules.html"><font color="#004faf">Modules</font></a> · <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"></td></tr></table><h1 class="title">Main Window<br /><span class="subtitle"></span>
</h1>
<p>Files:</p>
<ul>
<li><a href="<API key>.html">demos/mainwindow/colorswatch.cpp</a></li>
<li><a href="<API key>.html">demos/mainwindow/colorswatch.h</a></li>
<li><a href="<API key>.html">demos/mainwindow/mainwindow.cpp</a></li>
<li><a href="<API key>.html">demos/mainwindow/mainwindow.h</a></li>
<li><a href="<API key>.html">demos/mainwindow/toolbar.cpp</a></li>
<li><a href="<API key>.html">demos/mainwindow/toolbar.h</a></li>
<li><a href="<API key>.html">demos/mainwindow/main.cpp</a></li>
<li><a href="<API key>.html">demos/mainwindow/mainwindow.pro</a></li>
<li><a href="<API key>.html">demos/mainwindow/mainwindow.qrc</a></li>
</ul>
<p>The Main Window demonstration shows Qt's extensive support for tool bars, dock windows, menus, and other standard application features.</p>
<p align="center"><img src="images/mainwindow-demo.png" /></p><p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%" align="left">Copyright © 2008 Nokia</td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.4.3</div></td>
</tr></table></div></address></body>
</html> |
using System;
namespace Server.Items
{
[Flipable( 0xC12, 0xC13 )]
public class <API key> : AddonComponent
{
public override int LabelNumber { get { return 1076262; } } // Broken Armoire
public <API key>() : base( 0xC12 )
{
}
public <API key>( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
public class BrokenArmoireAddon : BaseAddon
{
public override BaseAddonDeed Deed { get { return new BrokenArmoireDeed(); } }
[Constructable]
public BrokenArmoireAddon() : base()
{
AddComponent( new <API key>(), 0, 0, 0 );
}
public BrokenArmoireAddon( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
public class BrokenArmoireDeed : BaseAddonDeed
{
public override BaseAddon Addon { get { return new BrokenArmoireAddon(); } }
public override int LabelNumber { get { return 1076262; } } // Broken Armoire
[Constructable]
public BrokenArmoireDeed() : base()
{
LootType = LootType.Blessed;
}
public BrokenArmoireDeed( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
} |
*******************************************************************//**
*//**
*//**
*//**
*//**
*//**
*//**
*/
void ExpandingToolBar::Collapse(bool now /* = false */) |
<?php
require_once("../../config.inc.php");
require_once("csv.inc.php");
require_once("xml.inc.php");
require_once("common.php");
require_once("requirements.inc.php");
testlinkInitPage($db,false,false,"checkRights");
$templateCfg = <API key>();
$req_spec_mgr = new <API key>($db);
$args = init_args();
$gui = initializeGui($args,$req_spec_mgr);
switch($args->doAction)
{
case 'export':
$smarty = new TLSmarty();
$smarty->assign('gui', $gui);
$smarty->display($templateCfg->template_dir . $templateCfg->default_template);
break;
case 'doExport':
doExport($args,$req_spec_mgr);
break;
}
/**
* checkRights
*
*/
function checkRights(&$db,&$user)
{
return $user->hasRight($db,'mgt_view_req');
}
/**
* init_args
*
*/
function init_args()
{
$_REQUEST = <API key>($_REQUEST);
$args = new stdClass();
$args->doAction = isset($_REQUEST['doAction']) ? $_REQUEST['doAction'] : 'export';
$args->exportType = isset($_REQUEST['exportType']) ? $_REQUEST['exportType'] : null;
$args->req_spec_id = isset($_REQUEST['req_spec_id']) ? $_REQUEST['req_spec_id'] : null;
$args->export_filename = isset($_REQUEST['export_filename']) ? $_REQUEST['export_filename'] : "";
$args->tproject_id = isset($_REQUEST['tproject_id']) ? $_REQUEST['tproject_id'] : 0;
if( $args->tproject_id == 0 )
{
$args->tproject_id = isset($_SESSION['testprojectID']) ? $_SESSION['testprojectID'] : 0;
}
$args->scope = isset($_REQUEST['scope']) ? $_REQUEST['scope'] : 'items';
return $args;
}
/**
* initializeGui
*
*/
function initializeGui(&$argsObj,&$req_spec_mgr)
{
$gui = new stdClass();
$gui->exportTypes = $req_spec_mgr-><API key>();
$gui->exportType = $argsObj->exportType;
$gui->scope = $argsObj->scope;
$gui->tproject_id = $argsObj->tproject_id;
switch($argsObj->scope)
{
case 'tree':
$gui->req_spec['title'] = lang_get('<API key>');
$gui->req_spec_id = 0;
$exportFileName = 'all-req.xml';
break;
case 'branch':
$gui->req_spec = $req_spec_mgr->get_by_id($argsObj->req_spec_id);
$gui->req_spec_id = $argsObj->req_spec_id;
$exportFileName = $gui->req_spec['title'] . '-req-spec.xml';
break;
case 'items':
$gui->req_spec = $req_spec_mgr->get_by_id($argsObj->req_spec_id);
$gui->req_spec_id = $argsObj->req_spec_id;
$exportFileName = $gui->req_spec['title'] . '-child_req.xml';
break;
}
$gui->export_filename = trim($argsObj->export_filename);
if($gui->export_filename == "")
{
$gui->export_filename = $exportFileName;
}
return $gui;
}
/**
* doExport
*
*/
function doExport(&$argsObj,&$req_spec_mgr)
{
$pfn = null;
switch($argsObj->exportType)
{
case 'csv':
$requirements_map = $req_spec_mgr->get_requirements($argsObj->req_spec_id);
$pfn = "exportReqDataToCSV";
$fileName = 'reqs.csv';
$content = $pfn($requirements_map);
break;
case 'XML':
$pfn = "exportReqSpecToXML";
$fileName = 'reqs.xml';
$content = TL_XMLEXPORT_HEADER;
$optionsForExport['RECURSIVE'] = $argsObj->scope == 'items' ? false : true;
$openTag = $argsObj->scope == 'items' ? "requirements>" : '<API key>>';
switch($argsObj->scope)
{
case 'tree':
$reqSpecSet = $req_spec_mgr-><API key>($argsObj->tproject_id);
$reqSpecSet = array_keys($reqSpecSet);
break;
case 'branch':
case 'items':
$reqSpecSet = array($argsObj->req_spec_id);
break;
}
$content .= "<" . $openTag . "\n";
if(!is_null($reqSpecSet))
{
foreach($reqSpecSet as $reqSpecID)
{
$content .= $req_spec_mgr->$pfn($reqSpecID,$argsObj->tproject_id,$optionsForExport);
}
}
$content .= "</" . $openTag . "\n";
break;
}
if ($pfn)
{
$fileName = is_null($argsObj->export_filename) ? $fileName : $argsObj->export_filename;
<API key>($content,$fileName);
exit();
}
}
?> |
/* Brief vocabulary:
ODR = One Definition Rule
In short, the ODR states that:
1 In any translation unit, a template, type, function, or object can
have no more than one definition. Some of these can have any number
of declarations. A definition provides an instance.
2 In the entire program, an object or non-inline function cannot have
more than one definition; if an object or function is used, it must
have exactly one definition. You can declare an object or function
that is never used, in which case you don't have to provide
a definition. In no event can there be more than one definition.
3 Some things, like types, templates, and extern inline functions, can
be defined in more than one translation unit. For a given entity,
each definition must be the same. Non-extern objects and functions
in different translation units are different entities, even if their
names and types are the same.
OTR = OBJ_TYPE_REF
This is the Gimple representation of type information of a polymorphic call.
It contains two parameters:
otr_type is a type of class whose method is called.
otr_token is the index into virtual table where address is taken.
BINFO
This is the type inheritance information attached to each tree
RECORD_TYPE by the C++ frontend. It provides information about base
types and virtual tables.
BINFO is linked to the RECORD_TYPE by TYPE_BINFO.
BINFO also links to its type by BINFO_TYPE and to the virtual table by
BINFO_VTABLE.
Base types of a given type are enumerated by BINFO_BASE_BINFO
vector. Members of this vectors are not BINFOs associated
with a base type. Rather they are new copies of BINFOs
(base BINFOs). Their virtual tables may differ from
virtual table of the base type. Also BINFO_OFFSET specifies
offset of the base within the type.
In the case of single inheritance, the virtual table is shared
and BINFO_VTABLE of base BINFO is NULL. In the case of multiple
inheritance the individual virtual tables are pointer to by
BINFO_VTABLE of base binfos (that differs of BINFO_VTABLE of
binfo associated to the base type).
BINFO lookup for a given base type and offset can be done by
get_binfo_at_offset. It returns proper BINFO whose virtual table
can be used for lookup of virtual methods associated with the
base type.
token
This is an index of virtual method in virtual table associated
to the type defining it. Token can be looked up from OBJ_TYPE_REF
or from DECL_VINDEX of a given virtual table.
polymorphic (indirect) call
This is callgraph representation of virtual method call. Every
polymorphic call contains otr_type and otr_token taken from
original OBJ_TYPE_REF at callgraph construction time.
What we do here:
<API key> triggers a construction of the type inheritance
graph.
We reconstruct it based on types of methods we see in the unit.
This means that the graph is not complete. Types with no methods are not
inserted into the graph. Also types without virtual methods are not
represented at all, though it may be easy to add this.
The inheritance graph is represented as follows:
Vertices are structures odr_type. Every odr_type may correspond
to one or more tree type nodes that are equivalent by ODR rule.
(the multiple type nodes appear only with linktime optimization)
Edges are represented by odr_type->base and odr_type->derived_types.
At the moment we do not track offsets of types for multiple inheritance.
Adding this is easy.
<API key> returns, given an parameters found in
indirect polymorphic edge all possible polymorphic call targets of the call.
pass_ipa_devirt performs simple speculative devirtualization.
*/
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "backend.h"
#include "tree.h"
#include "gimple.h"
#include "rtl.h"
#include "alias.h"
#include "fold-const.h"
#include "print-tree.h"
#include "calls.h"
#include "cgraph.h"
#include "flags.h"
#include "insn-config.h"
#include "expmed.h"
#include "dojump.h"
#include "explow.h"
#include "emit-rtl.h"
#include "varasm.h"
#include "stmt.h"
#include "expr.h"
#include "tree-pass.h"
#include "target.h"
#include "ipa-utils.h"
#include "internal-fn.h"
#include "gimple-fold.h"
#include "alloc-pool.h"
#include "symbol-summary.h"
#include "ipa-prop.h"
#include "ipa-inline.h"
#include "diagnostic.h"
#include "tree-dfa.h"
#include "demangle.h"
#include "dbgcnt.h"
#include "gimple-pretty-print.h"
#include "stor-layout.h"
#include "intl.h"
#include "lto-streamer.h"
/* Hash based set of pairs of types. */
struct type_pair
{
tree first;
tree second;
};
template <>
struct default_hash_traits <type_pair> : typed_noop_remove <type_pair>
{
typedef type_pair value_type;
typedef type_pair compare_type;
static hashval_t
hash (type_pair p)
{
return TYPE_UID (p.first) ^ TYPE_UID (p.second);
}
static bool
is_empty (type_pair p)
{
return p.first == NULL;
}
static bool
is_deleted (type_pair p ATTRIBUTE_UNUSED)
{
return false;
}
static bool
equal (const type_pair &a, const type_pair &b)
{
return a.first==b.first && a.second == b.second;
}
static void
mark_empty (type_pair &e)
{
e.first = NULL;
}
};
static bool <API key> (tree, tree, bool, bool *,
hash_set<type_pair> *,
location_t, location_t);
static bool <API key> = false;
/* Pointer set of all call targets appearing in the cache. */
static hash_set<cgraph_node *> *<API key>;
/* The node of type inheritance graph. For each type unique in
One Definition Rule (ODR) sense, we produce one node linking all
main variants of types equivalent to it, bases and derived types. */
struct GTY(()) odr_type_d
{
/* leader type. */
tree type;
/* All bases; built only for main variants of types. */
vec<odr_type> GTY((skip)) bases;
/* All derived types with virtual methods seen in unit;
built only for main variants of types. */
vec<odr_type> GTY((skip)) derived_types;
/* All equivalent types, if more than one. */
vec<tree, va_gc> *types;
/* Set of all equivalent types, if NON-NULL. */
hash_set<tree> * GTY((skip)) types_set;
/* Unique ID indexing the type in odr_types array. */
int id;
/* Is it in anonymous namespace? */
bool anonymous_namespace;
/* Do we know about all derivations of given type? */
bool <API key>;
/* Did we report ODR violation here? */
bool odr_violated;
/* Set when virtual table without RTTI previaled table with. */
bool rtti_broken;
};
/* Return true if T is a type with linkage defined. */
bool
type_with_linkage_p (const_tree t)
{
/* Builtin types do not define linkage, their TYPE_CONTEXT is NULL. */
if (!TYPE_CONTEXT (t)
|| !TYPE_NAME (t) || TREE_CODE (TYPE_NAME (t)) != TYPE_DECL
|| !TYPE_STUB_DECL (t))
return false;
/* In LTO do not get confused by non-C++ produced types or types built
with -<API key>. */
if (in_lto_p)
{
/* To support -<API key> recognize types with vtables
to have linkage. */
if (<API key> (t)
&& TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)))
return true;
/* Do not accept any other types - we do not know if they were produced
by C++ FE. */
if (!<API key> (TYPE_NAME (t)))
return false;
}
return (<API key> (t)
|| TREE_CODE (t) == ENUMERAL_TYPE);
}
/* Return true if T is in anonymous namespace.
This works only on those C++ types with linkage defined. */
bool
<API key> (const_tree t)
{
gcc_assert (type_with_linkage_p (t));
/* Keep -<API key> working by recognizing classes with vtables
properly into anonymous namespaces. */
if (<API key> (t)
&& TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)))
return (TYPE_STUB_DECL (t) && !TREE_PUBLIC (TYPE_STUB_DECL (t)));
if (TYPE_STUB_DECL (t) && !TREE_PUBLIC (TYPE_STUB_DECL (t)))
{
/* C++ FE uses magic <anon> as assembler names of anonymous types.
verify that this match with <API key>. */
#ifdef ENABLE_CHECKING
if (in_lto_p)
gcc_assert (!strcmp ("<anon>",
IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (TYPE_NAME (t)))));
#endif
return true;
}
return false;
}
/* Return true of T is type with One Definition Rule info attached.
It means that either it is anonymous type or it has assembler name
set. */
bool
odr_type_p (const_tree t)
{
/* We do not have this information when not in LTO, but we do not need
to care, since it is used only for type merging. */
gcc_checking_assert (in_lto_p || flag_lto);
/* To support -<API key> consider types with vtables ODR. */
if (type_with_linkage_p (t) && <API key> (t))
return true;
if (TYPE_NAME (t) && TREE_CODE (TYPE_NAME (t)) == TYPE_DECL
&& (<API key> (TYPE_NAME (t))))
{
#ifdef ENABLE_CHECKING
/* C++ FE uses magic <anon> as assembler names of anonymous types.
verify that this match with <API key>. */
gcc_assert (!type_with_linkage_p (t)
|| strcmp ("<anon>",
IDENTIFIER_POINTER
(DECL_ASSEMBLER_NAME (TYPE_NAME (t))))
|| <API key> (t));
#endif
return true;
}
return false;
}
/* Return TRUE if all derived types of T are known and thus
we may consider the walk of derived type complete.
This is typically true only for final anonymous namespace types and types
defined within functions (that may be COMDAT and thus shared across units,
but with the same set of derived types). */
bool
<API key> (const_tree t)
{
if (TYPE_FINAL_P (t))
return true;
if (flag_ltrans)
return false;
/* Non-C++ types may have IDENTIFIER_NODE here, do not crash. */
if (!TYPE_NAME (t) || TREE_CODE (TYPE_NAME (t)) != TYPE_DECL)
return true;
if (<API key> (t))
return true;
return (<API key> (TYPE_NAME (t)) != NULL);
}
/* Return TRUE if type's constructors are all visible. */
static bool
<API key> (tree t)
{
return !flag_ltrans
&& symtab->state >= CONSTRUCTION
/* We can not always use <API key>.
For function local types we must assume case where
the function is COMDAT and shared in between units.
TODO: These cases are quite easy to get, but we need
to keep track of C++ privatizing via -Wno-weak
as well as the IPA privatizing. */
&& <API key> (t);
}
/* Return TRUE if type may have instance. */
static bool
<API key> (tree t)
{
tree vtable;
varpool_node *vnode;
/* TODO: Add abstract types here. */
if (!<API key> (t))
return true;
vtable = BINFO_VTABLE (TYPE_BINFO (t));
if (TREE_CODE (vtable) == POINTER_PLUS_EXPR)
vtable = TREE_OPERAND (TREE_OPERAND (vtable, 0), 0);
vnode = varpool_node::get (vtable);
return vnode && vnode->definition;
}
/* Hash used to unify ODR types based on their mangled name and for anonymous
namespace types. */
struct odr_name_hasher : pointer_hash <odr_type_d>
{
typedef union tree_node *compare_type;
static inline hashval_t hash (const odr_type_d *);
static inline bool equal (const odr_type_d *, const tree_node *);
static inline void remove (odr_type_d *);
};
/* Has used to unify ODR types based on their associated virtual table.
This hash is needed to keep -<API key> to work and contains
only polymorphic types. Types with mangled names are inserted to both. */
struct odr_vtable_hasher:odr_name_hasher
{
static inline hashval_t hash (const odr_type_d *);
static inline bool equal (const odr_type_d *, const tree_node *);
};
/* Return type that was declared with T's name so that T is an
qualified variant of it. */
static inline tree
main_odr_variant (const_tree t)
{
if (TYPE_NAME (t) && TREE_CODE (TYPE_NAME (t)) == TYPE_DECL)
return TREE_TYPE (TYPE_NAME (t));
/* Unnamed types and non-C++ produced types can be compared by variants. */
else
return TYPE_MAIN_VARIANT (t);
}
static bool
<API key> (tree t)
{
return (!in_lto_p || odr_type_p (t));
}
/* Hash type by its ODR name. */
static hashval_t
hash_odr_name (const_tree t)
{
gcc_checking_assert (main_odr_variant (t) == t);
/* If not in LTO, all main variants are unique, so we can do
pointer hash. */
if (!in_lto_p)
return htab_hash_pointer (t);
/* Anonymous types are unique. */
if (type_with_linkage_p (t) && <API key> (t))
return htab_hash_pointer (t);
gcc_checking_assert (TYPE_NAME (t)
&& <API key> (TYPE_NAME (t)));
return <API key> (DECL_ASSEMBLER_NAME (TYPE_NAME (t)));
}
/* Return the computed hashcode for ODR_TYPE. */
inline hashval_t
odr_name_hasher::hash (const odr_type_d *odr_type)
{
return hash_odr_name (odr_type->type);
}
static bool
<API key> (tree t)
{
/* vtable hashing can distinguish only main variants. */
if (TYPE_MAIN_VARIANT (t) != t)
return false;
/* Anonymous namespace types are always handled by name hash. */
if (type_with_linkage_p (t) && <API key> (t))
return false;
return (TREE_CODE (t) == RECORD_TYPE
&& TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)));
}
/* Hash type by assembler name of its vtable. */
static hashval_t
hash_odr_vtable (const_tree t)
{
tree v = BINFO_VTABLE (TYPE_BINFO (TYPE_MAIN_VARIANT (t)));
inchash::hash hstate;
gcc_checking_assert (in_lto_p);
gcc_checking_assert (!<API key> (t));
gcc_checking_assert (TREE_CODE (t) == RECORD_TYPE
&& TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)));
gcc_checking_assert (main_odr_variant (t) == t);
if (TREE_CODE (v) == POINTER_PLUS_EXPR)
{
add_expr (TREE_OPERAND (v, 1), hstate);
v = TREE_OPERAND (TREE_OPERAND (v, 0), 0);
}
hstate.add_wide_int (<API key> (DECL_ASSEMBLER_NAME (v)));
return hstate.end ();
}
/* Return the computed hashcode for ODR_TYPE. */
inline hashval_t
odr_vtable_hasher::hash (const odr_type_d *odr_type)
{
return hash_odr_vtable (odr_type->type);
}
/* For languages with One Definition Rule, work out if
types are the same based on their name.
This is non-trivial for LTO where minor differences in
the type representation may have prevented type merging
to merge two copies of otherwise equivalent type.
Until we start streaming mangled type names, this function works
only for polymorphic types.
When STRICT is true, we compare types by their names for purposes of
ODR violation warnings. When strict is false, we consider variants
equivalent, becuase it is all that matters for devirtualization machinery.
*/
bool
types_same_for_odr (const_tree type1, const_tree type2, bool strict)
{
gcc_checking_assert (TYPE_P (type1) && TYPE_P (type2));
type1 = main_odr_variant (type1);
type2 = main_odr_variant (type2);
if (!strict)
{
type1 = TYPE_MAIN_VARIANT (type1);
type2 = TYPE_MAIN_VARIANT (type2);
}
if (type1 == type2)
return true;
if (!in_lto_p)
return false;
/* Check for anonymous namespaces. Those have !TREE_PUBLIC
on the corresponding TYPE_STUB_DECL. */
if ((type_with_linkage_p (type1) && <API key> (type1))
|| (type_with_linkage_p (type2) && <API key> (type2)))
return false;
/* ODR name of the type is set in DECL_ASSEMBLER_NAME of its TYPE_NAME.
Ideally we should never need types without ODR names here. It can however
happen in two cases:
1) for builtin types that are not streamed but rebuilt in lto/lto-lang.c
Here testing for equivalence is safe, since their MAIN_VARIANTs are
unique.
2) for units streamed with -<API key>. Here we can't
establish precise ODR equivalency, but for correctness we care only
about equivalency on complete polymorphic types. For these we can
compare assembler names of their virtual tables. */
if ((!TYPE_NAME (type1) || !<API key> (TYPE_NAME (type1)))
|| (!TYPE_NAME (type2) || !<API key> (TYPE_NAME (type2))))
{
/* See if types are obviously different (i.e. different codes
or polymorphic wrt non-polymorphic). This is not strictly correct
for ODR violating programs, but we can't do better without streaming
ODR names. */
if (TREE_CODE (type1) != TREE_CODE (type2))
return false;
if (TREE_CODE (type1) == RECORD_TYPE
&& (TYPE_BINFO (type1) == NULL_TREE)
!= (TYPE_BINFO (type2) == NULL_TREE))
return false;
if (TREE_CODE (type1) == RECORD_TYPE && TYPE_BINFO (type1)
&& (BINFO_VTABLE (TYPE_BINFO (type1)) == NULL_TREE)
!= (BINFO_VTABLE (TYPE_BINFO (type2)) == NULL_TREE))
return false;
/* At the moment we have no way to establish ODR equivalence at LTO
other than comparing virtual table pointers of polymorphic types.
Eventually we should start saving mangled names in TYPE_NAME.
Then this condition will become non-trivial. */
if (TREE_CODE (type1) == RECORD_TYPE
&& TYPE_BINFO (type1) && TYPE_BINFO (type2)
&& BINFO_VTABLE (TYPE_BINFO (type1))
&& BINFO_VTABLE (TYPE_BINFO (type2)))
{
tree v1 = BINFO_VTABLE (TYPE_BINFO (type1));
tree v2 = BINFO_VTABLE (TYPE_BINFO (type2));
gcc_assert (TREE_CODE (v1) == POINTER_PLUS_EXPR
&& TREE_CODE (v2) == POINTER_PLUS_EXPR);
return (operand_equal_p (TREE_OPERAND (v1, 1),
TREE_OPERAND (v2, 1), 0)
&& DECL_ASSEMBLER_NAME
(TREE_OPERAND (TREE_OPERAND (v1, 0), 0))
== DECL_ASSEMBLER_NAME
(TREE_OPERAND (TREE_OPERAND (v2, 0), 0)));
}
gcc_unreachable ();
}
return (DECL_ASSEMBLER_NAME (TYPE_NAME (type1))
== DECL_ASSEMBLER_NAME (TYPE_NAME (type2)));
}
/* Return true if we can decide on ODR equivalency.
In non-LTO it is always decide, in LTO however it depends in the type has
ODR info attached.
When STRICT is false, compare main variants. */
bool
<API key> (tree t1, tree t2, bool strict)
{
return (!in_lto_p
|| (strict ? (main_odr_variant (t1) == main_odr_variant (t2)
&& main_odr_variant (t1))
: TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
|| (odr_type_p (t1) && odr_type_p (t2))
|| (TREE_CODE (t1) == RECORD_TYPE && TREE_CODE (t2) == RECORD_TYPE
&& TYPE_BINFO (t1) && TYPE_BINFO (t2)
&& <API key> (TYPE_BINFO (t1))
&& <API key> (TYPE_BINFO (t2))));
}
/* Return true if T1 and T2 are ODR equivalent. If ODR equivalency is not
known, be conservative and return false. */
bool
<API key> (tree t1, tree t2)
{
if (<API key> (t1, t2))
return types_same_for_odr (t1, t2);
else
return TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2);
}
/* If T is compound type, return type it is based on. */
static tree
compound_type_base (const_tree t)
{
if (TREE_CODE (t) == ARRAY_TYPE
|| POINTER_TYPE_P (t)
|| TREE_CODE (t) == COMPLEX_TYPE
|| VECTOR_TYPE_P (t))
return TREE_TYPE (t);
if (TREE_CODE (t) == METHOD_TYPE)
return <API key> (t);
if (TREE_CODE (t) == OFFSET_TYPE)
return <API key> (t);
return NULL_TREE;
}
/* Return true if T is either ODR type or compound type based from it.
If the function return true, we know that T is a type originating from C++
source even at link-time. */
bool
<API key> (const_tree t)
{
do
{
if (odr_type_p (t))
return true;
/* Function type is a tricky one. Basically we can consider it
ODR derived if return type or any of the parameters is.
We need to check all parameters because LTO streaming merges
common types (such as void) and they are not considered ODR then. */
if (TREE_CODE (t) == FUNCTION_TYPE)
{
if (<API key> (t))
t = <API key> (t);
else
{
if (TREE_TYPE (t) && <API key> (TREE_TYPE (t)))
return true;
for (t = TYPE_ARG_TYPES (t); t; t = TREE_CHAIN (t))
if (<API key> (TREE_VALUE (t)))
return true;
return false;
}
}
else
t = compound_type_base (t);
}
while (t);
return t;
}
/* Compare types T1 and T2 and return true if they are
equivalent. */
inline bool
odr_name_hasher::equal (const odr_type_d *o1, const tree_node *t2)
{
tree t1 = o1->type;
gcc_checking_assert (main_odr_variant (t2) == t2);
gcc_checking_assert (main_odr_variant (t1) == t1);
if (t1 == t2)
return true;
if (!in_lto_p)
return false;
/* Check for anonymous namespaces. Those have !TREE_PUBLIC
on the corresponding TYPE_STUB_DECL. */
if ((type_with_linkage_p (t1) && <API key> (t1))
|| (type_with_linkage_p (t2) && <API key> (t2)))
return false;
gcc_checking_assert (DECL_ASSEMBLER_NAME (TYPE_NAME (t1)));
gcc_checking_assert (DECL_ASSEMBLER_NAME (TYPE_NAME (t2)));
return (DECL_ASSEMBLER_NAME (TYPE_NAME (t1))
== DECL_ASSEMBLER_NAME (TYPE_NAME (t2)));
}
/* Compare types T1 and T2 and return true if they are
equivalent. */
inline bool
odr_vtable_hasher::equal (const odr_type_d *o1, const tree_node *t2)
{
tree t1 = o1->type;
gcc_checking_assert (main_odr_variant (t2) == t2);
gcc_checking_assert (main_odr_variant (t1) == t1);
gcc_checking_assert (in_lto_p);
t1 = TYPE_MAIN_VARIANT (t1);
t2 = TYPE_MAIN_VARIANT (t2);
if (t1 == t2)
return true;
tree v1 = BINFO_VTABLE (TYPE_BINFO (t1));
tree v2 = BINFO_VTABLE (TYPE_BINFO (t2));
return (operand_equal_p (TREE_OPERAND (v1, 1),
TREE_OPERAND (v2, 1), 0)
&& DECL_ASSEMBLER_NAME
(TREE_OPERAND (TREE_OPERAND (v1, 0), 0))
== DECL_ASSEMBLER_NAME
(TREE_OPERAND (TREE_OPERAND (v2, 0), 0)));
}
/* Free ODR type V. */
inline void
odr_name_hasher::remove (odr_type_d *v)
{
v->bases.release ();
v->derived_types.release ();
if (v->types_set)
delete v->types_set;
ggc_free (v);
}
/* ODR type hash used to look up ODR type based on tree type node. */
typedef hash_table<odr_name_hasher> odr_hash_type;
static odr_hash_type *odr_hash;
typedef hash_table<odr_vtable_hasher> <API key>;
static <API key> *odr_vtable_hash;
/* ODR types are also stored into ODR_TYPE vector to allow consistent
walking. Bases appear before derived types. Vector is garbage collected
so we won't end up visiting empty types. */
static GTY(()) vec <odr_type, va_gc> *odr_types_ptr;
#define odr_types (*odr_types_ptr)
/* Set TYPE_BINFO of TYPE and its variants to BINFO. */
void
set_type_binfo (tree type, tree binfo)
{
for (; type; type = TYPE_NEXT_VARIANT (type))
if (COMPLETE_TYPE_P (type))
TYPE_BINFO (type) = binfo;
else
gcc_assert (!TYPE_BINFO (type));
}
/* Compare T2 and T2 based on name or structure. */
static bool
<API key> (tree t1, tree t2,
hash_set<type_pair> *visited,
location_t loc1, location_t loc2)
{
/* This can happen in incomplete types that should be handled earlier. */
gcc_assert (t1 && t2);
t1 = main_odr_variant (t1);
t2 = main_odr_variant (t2);
if (t1 == t2)
return true;
/* Anonymous namespace types must match exactly. */
if ((type_with_linkage_p (t1) && <API key> (t1))
|| (type_with_linkage_p (t2) && <API key> (t2)))
return false;
/* For ODR types be sure to compare their names.
To support -<API key> we allow one type to be non-ODR
and other ODR even though it is a violation. */
if (<API key> (t1, t2, true))
{
if (!types_same_for_odr (t1, t2, true))
return false;
/* Limit recursion: If subtypes are ODR types and we know
that they are same, be happy. */
if (!odr_type_p (t1) || !get_odr_type (t1, true)->odr_violated)
return true;
}
/* Component types, builtins and possibly violating ODR types
have to be compared structurally. */
if (TREE_CODE (t1) != TREE_CODE (t2))
return false;
if (AGGREGATE_TYPE_P (t1)
&& (TYPE_NAME (t1) == NULL_TREE) != (TYPE_NAME (t2) == NULL_TREE))
return false;
type_pair pair={t1,t2};
if (TYPE_UID (t1) > TYPE_UID (t2))
{
pair.first = t2;
pair.second = t1;
}
if (visited->add (pair))
return true;
return <API key> (t1, t2, false, NULL, visited, loc1, loc2);
}
/* Compare two virtual tables, PREVAILING and VTABLE and output ODR
violation warnings. */
void
<API key> (varpool_node *prevailing, varpool_node *vtable)
{
int n1, n2;
if (DECL_VIRTUAL_P (prevailing->decl) != DECL_VIRTUAL_P (vtable->decl))
{
<API key> = true;
if (DECL_VIRTUAL_P (prevailing->decl))
{
varpool_node *tmp = prevailing;
prevailing = vtable;
vtable = tmp;
}
if (warning_at (<API key>
(TYPE_NAME (DECL_CONTEXT (vtable->decl))),
OPT_Wodr,
"virtual table of type %qD violates one definition rule",
DECL_CONTEXT (vtable->decl)))
inform (<API key> (prevailing->decl),
"variable of same assembler name as the virtual table is "
"defined in another translation unit");
return;
}
if (!prevailing->definition || !vtable->definition)
return;
/* If we do not stream ODR type info, do not bother to do useful compare. */
if (!TYPE_BINFO (DECL_CONTEXT (vtable->decl))
|| !<API key> (TYPE_BINFO (DECL_CONTEXT (vtable->decl))))
return;
odr_type class_type = get_odr_type (DECL_CONTEXT (vtable->decl), true);
if (class_type->odr_violated)
return;
for (n1 = 0, n2 = 0; true; n1++, n2++)
{
struct ipa_ref *ref1, *ref2;
bool end1, end2;
end1 = !prevailing->iterate_reference (n1, ref1);
end2 = !vtable->iterate_reference (n2, ref2);
/* !DECL_VIRTUAL_P means RTTI entry;
We warn when RTTI is lost because non-RTTI previals; we silently
accept the other case. */
while (!end2
&& (end1
|| (DECL_ASSEMBLER_NAME (ref1->referred->decl)
!= DECL_ASSEMBLER_NAME (ref2->referred->decl)
&& TREE_CODE (ref1->referred->decl) == FUNCTION_DECL))
&& TREE_CODE (ref2->referred->decl) != FUNCTION_DECL)
{
if (!class_type->rtti_broken
&& warning_at (<API key>
(TYPE_NAME (DECL_CONTEXT (vtable->decl))),
OPT_Wodr,
"virtual table of type %qD contains RTTI "
"information",
DECL_CONTEXT (vtable->decl)))
{
inform (<API key>
(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
"but is prevailed by one without from other translation "
"unit");
inform (<API key>
(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
"RTTI will not work on this type");
class_type->rtti_broken = true;
}
n2++;
end2 = !vtable->iterate_reference (n2, ref2);
}
while (!end1
&& (end2
|| (DECL_ASSEMBLER_NAME (ref2->referred->decl)
!= DECL_ASSEMBLER_NAME (ref1->referred->decl)
&& TREE_CODE (ref2->referred->decl) == FUNCTION_DECL))
&& TREE_CODE (ref1->referred->decl) != FUNCTION_DECL)
{
n1++;
end1 = !prevailing->iterate_reference (n1, ref1);
}
/* Finished? */
if (end1 && end2)
{
/* Extra paranoia; compare the sizes. We do not have information
about virtual inheritance offsets, so just be sure that these
match.
Do this as very last check so the not very informative error
is not output too often. */
if (DECL_SIZE (prevailing->decl) != DECL_SIZE (vtable->decl))
{
class_type->odr_violated = true;
if (warning_at (<API key>
(TYPE_NAME (DECL_CONTEXT (vtable->decl))),
OPT_Wodr,
"virtual table of type %qD violates "
"one definition rule ",
DECL_CONTEXT (vtable->decl)))
{
inform (<API key>
(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
"the conflicting type defined in another translation "
"unit has virtual table of different size");
}
}
return;
}
if (!end1 && !end2)
{
if (DECL_ASSEMBLER_NAME (ref1->referred->decl)
== DECL_ASSEMBLER_NAME (ref2->referred->decl))
continue;
class_type->odr_violated = true;
/* If the loops above stopped on non-virtual pointer, we have
mismatch in RTTI information mangling. */
if (TREE_CODE (ref1->referred->decl) != FUNCTION_DECL
&& TREE_CODE (ref2->referred->decl) != FUNCTION_DECL)
{
if (warning_at (<API key>
(TYPE_NAME (DECL_CONTEXT (vtable->decl))),
OPT_Wodr,
"virtual table of type %qD violates "
"one definition rule ",
DECL_CONTEXT (vtable->decl)))
{
inform (<API key>
(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
"the conflicting type defined in another translation "
"unit with different RTTI information");
}
return;
}
/* At this point both REF1 and REF2 points either to virtual table
or virtual method. If one points to virtual table and other to
method we can complain the same way as if one table was shorter
than other pointing out the extra method. */
if (TREE_CODE (ref1->referred->decl)
!= TREE_CODE (ref2->referred->decl))
{
if (TREE_CODE (ref1->referred->decl) == VAR_DECL)
end1 = true;
else if (TREE_CODE (ref2->referred->decl) == VAR_DECL)
end2 = true;
}
}
class_type->odr_violated = true;
/* Complain about size mismatch. Either we have too many virutal
functions or too many virtual table pointers. */
if (end1 || end2)
{
if (end1)
{
varpool_node *tmp = prevailing;
prevailing = vtable;
vtable = tmp;
ref1 = ref2;
}
if (warning_at (<API key>
(TYPE_NAME (DECL_CONTEXT (vtable->decl))),
OPT_Wodr,
"virtual table of type %qD violates "
"one definition rule",
DECL_CONTEXT (vtable->decl)))
{
if (TREE_CODE (ref1->referring->decl) == FUNCTION_DECL)
{
inform (<API key>
(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
"the conflicting type defined in another translation "
"unit");
inform (<API key>
(TYPE_NAME (DECL_CONTEXT (ref1->referring->decl))),
"contains additional virtual method %qD",
ref1->referred->decl);
}
else
{
inform (<API key>
(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
"the conflicting type defined in another translation "
"unit has virtual table with more entries");
}
}
return;
}
/* And in the last case we have either mistmatch in between two virtual
methods or two virtual table pointers. */
if (warning_at (<API key>
(TYPE_NAME (DECL_CONTEXT (vtable->decl))), OPT_Wodr,
"virtual table of type %qD violates "
"one definition rule ",
DECL_CONTEXT (vtable->decl)))
{
if (TREE_CODE (ref1->referred->decl) == FUNCTION_DECL)
{
inform (<API key>
(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
"the conflicting type defined in another translation "
"unit");
gcc_assert (TREE_CODE (ref2->referred->decl)
== FUNCTION_DECL);
inform (<API key> (ref1->referred->decl),
"virtual method %qD", ref1->referred->decl);
inform (<API key> (ref2->referred->decl),
"ought to match virtual method %qD but does not",
ref2->referred->decl);
}
else
inform (<API key>
(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
"the conflicting type defined in another translation "
"unit has virtual table with different contents");
return;
}
}
}
/* Output ODR violation warning about T1 and T2 with REASON.
Display location of ST1 and ST2 if REASON speaks about field or
method of the type.
If WARN is false, do nothing. Set WARNED if warning was indeed
output. */
void
warn_odr (tree t1, tree t2, tree st1, tree st2,
bool warn, bool *warned, const char *reason)
{
tree decl2 = TYPE_NAME (t2);
if (warned)
*warned = false;
if (!warn || !TYPE_NAME(t1))
return;
/* ODR warnings are output druing LTO streaming; we must apply location
cache for potential warnings to be output correctly. */
if (lto_location_cache::current_cache)
lto_location_cache::current_cache-><API key> ();
if (!warning_at (<API key> (TYPE_NAME (t1)), OPT_Wodr,
"type %qT violates the C++ One Definition Rule",
t1))
return;
if (!st1 && !st2)
;
/* For FIELD_DECL support also case where one of fields is
NULL - this is used when the structures have mismatching number of
elements. */
else if (!st1 || TREE_CODE (st1) == FIELD_DECL)
{
inform (<API key> (decl2),
"a different type is defined in another translation unit");
if (!st1)
{
st1 = st2;
st2 = NULL;
}
inform (<API key> (st1),
"the first difference of corresponding definitions is field %qD",
st1);
if (st2)
decl2 = st2;
}
else if (TREE_CODE (st1) == FUNCTION_DECL)
{
inform (<API key> (decl2),
"a different type is defined in another translation unit");
inform (<API key> (st1),
"the first difference of corresponding definitions is method %qD",
st1);
decl2 = st2;
}
else
return;
inform (<API key> (decl2), reason);
if (warned)
*warned = true;
}
/* Return ture if T1 and T2 are incompatible and we want to recusively
dive into them from warn_type_mismatch to give sensible answer. */
static bool
type_mismatch_p (tree t1, tree t2)
{
if (<API key> (t1) && <API key> (t2)
&& !<API key> (t1, t2))
return true;
return !types_compatible_p (t1, t2);
}
/* Types T1 and T2 was found to be incompatible in a context they can't
(either used to declare a symbol of same assembler name or unified by
ODR rule). We already output warning about this, but if possible, output
extra information on how the types mismatch.
This is hard to do in general. We basically handle the common cases.
If LOC1 and LOC2 are meaningful locations, use it in the case the types
themselves do no thave one.*/
void
warn_types_mismatch (tree t1, tree t2, location_t loc1, location_t loc2)
{
/* Location of type is known only if it has TYPE_NAME and the name is
TYPE_DECL. */
location_t loc_t1 = TYPE_NAME (t1) && TREE_CODE (TYPE_NAME (t1)) == TYPE_DECL
? <API key> (TYPE_NAME (t1))
: UNKNOWN_LOCATION;
location_t loc_t2 = TYPE_NAME (t2) && TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL
? <API key> (TYPE_NAME (t2))
: UNKNOWN_LOCATION;
bool loc_t2_useful = false;
/* With LTO it is a common case that the location of both types match.
See if T2 has a location that is different from T1. If so, we will
inform user about the location.
Do not consider the location passed to us in LOC1/LOC2 as those are
already output. */
if (loc_t2 > BUILTINS_LOCATION && loc_t2 != loc_t1)
{
if (loc_t1 <= BUILTINS_LOCATION)
loc_t2_useful = true;
else
{
expanded_location xloc1 = expand_location (loc_t1);
expanded_location xloc2 = expand_location (loc_t2);
if (strcmp (xloc1.file, xloc2.file)
|| xloc1.line != xloc2.line
|| xloc1.column != xloc2.column)
loc_t2_useful = true;
}
}
if (loc_t1 <= BUILTINS_LOCATION)
loc_t1 = loc1;
if (loc_t2 <= BUILTINS_LOCATION)
loc_t2 = loc2;
location_t loc = loc_t1 <= BUILTINS_LOCATION ? loc_t2 : loc_t1;
/* It is a quite common bug to reference anonymous namespace type in
non-anonymous namespace class. */
if ((type_with_linkage_p (t1) && <API key> (t1))
|| (type_with_linkage_p (t2) && <API key> (t2)))
{
if (type_with_linkage_p (t1) && !<API key> (t1))
{
std::swap (t1, t2);
std::swap (loc_t1, loc_t2);
}
gcc_assert (TYPE_NAME (t1) && TYPE_NAME (t2)
&& TREE_CODE (TYPE_NAME (t1)) == TYPE_DECL
&& TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL);
/* Most of the time, the type names will match, do not be unnecesarily
verbose. */
if (IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (t1)))
!= IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (t2))))
inform (loc_t1,
"type %qT defined in anonymous namespace can not match "
"type %qT across the translation unit boundary",
t1, t2);
else
inform (loc_t1,
"type %qT defined in anonymous namespace can not match "
"across the translation unit boundary",
t1);
if (loc_t2_useful)
inform (loc_t2,
"the incompatible type defined in another translation unit");
return;
}
/* If types have mangled ODR names and they are different, it is most
informative to output those.
This also covers types defined in different namespaces. */
if (TYPE_NAME (t1) && TYPE_NAME (t2)
&& TREE_CODE (TYPE_NAME (t1)) == TYPE_DECL
&& TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL
&& <API key> (TYPE_NAME (t1))
&& <API key> (TYPE_NAME (t2))
&& DECL_ASSEMBLER_NAME (TYPE_NAME (t1))
!= DECL_ASSEMBLER_NAME (TYPE_NAME (t2)))
{
char *name1 = xstrdup (cplus_demangle
(IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (TYPE_NAME (t1))),
DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES));
char *name2 = cplus_demangle
(IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (TYPE_NAME (t2))),
DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES);
if (name1 && name2 && strcmp (name1, name2))
{
inform (loc_t1,
"type name %<%s%> should match type name %<%s%>",
name1, name2);
if (loc_t2_useful)
inform (loc_t2,
"the incompatible type is defined here");
free (name1);
return;
}
free (name1);
}
/* A tricky case are compound types. Often they appear the same in source
code and the mismatch is dragged in by type they are build from.
Look for those differences in subtypes and try to be informative. In other
cases just output nothing because the source code is probably different
and in this case we already output a all necessary info. */
if (!TYPE_NAME (t1) || !TYPE_NAME (t2))
{
if (TREE_CODE (t1) == TREE_CODE (t2))
{
if (TREE_CODE (t1) == ARRAY_TYPE
&& COMPLETE_TYPE_P (t1) && COMPLETE_TYPE_P (t2))
{
tree i1 = TYPE_DOMAIN (t1);
tree i2 = TYPE_DOMAIN (t2);
if (i1 && i2
&& TYPE_MAX_VALUE (i1)
&& TYPE_MAX_VALUE (i2)
&& !operand_equal_p (TYPE_MAX_VALUE (i1),
TYPE_MAX_VALUE (i2), 0))
{
inform (loc,
"array types have different bounds");
return;
}
}
if ((POINTER_TYPE_P (t1) || TREE_CODE (t1) == ARRAY_TYPE)
&& type_mismatch_p (TREE_TYPE (t1), TREE_TYPE (t2)))
warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc_t1, loc_t2);
else if (TREE_CODE (t1) == METHOD_TYPE
|| TREE_CODE (t1) == FUNCTION_TYPE)
{
tree parms1 = NULL, parms2 = NULL;
int count = 1;
if (type_mismatch_p (TREE_TYPE (t1), TREE_TYPE (t2)))
{
inform (loc, "return value type mismatch");
warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc_t1,
loc_t2);
return;
}
if (prototype_p (t1) && prototype_p (t2))
for (parms1 = TYPE_ARG_TYPES (t1), parms2 = TYPE_ARG_TYPES (t2);
parms1 && parms2;
parms1 = TREE_CHAIN (parms1), parms2 = TREE_CHAIN (parms2),
count++)
{
if (type_mismatch_p (TREE_VALUE (parms1), TREE_VALUE (parms2)))
{
if (count == 1 && TREE_CODE (t1) == METHOD_TYPE)
inform (loc,
"implicit this pointer type mismatch");
else
inform (loc,
"type mismatch in parameter %i",
count - (TREE_CODE (t1) == METHOD_TYPE));
warn_types_mismatch (TREE_VALUE (parms1),
TREE_VALUE (parms2),
loc_t1, loc_t2);
return;
}
}
if (parms1 || parms2)
{
inform (loc,
"types have different parameter counts");
return;
}
}
}
return;
}
if (<API key> (t1, t2, true)
&& types_same_for_odr (t1, t2, true))
inform (loc_t1,
"type %qT itself violate the C++ One Definition Rule", t1);
/* Prevent pointless warnings like "struct aa" should match "struct aa". */
else if (TYPE_NAME (t1) == TYPE_NAME (t2)
&& TREE_CODE (t1) == TREE_CODE (t2) && !loc_t2_useful)
return;
else
inform (loc_t1, "type %qT should match type %qT",
t1, t2);
if (loc_t2_useful)
inform (loc_t2, "the incompatible type is defined here");
}
/* Compare T1 and T2, report ODR violations if WARN is true and set
WARNED to true if anything is reported. Return true if types match.
If true is returned, the types are also compatible in the sense of
<API key>.
If LOC1 and LOC2 is not UNKNOWN_LOCATION it may be used to output a warning
about the type if the type itself do not have location. */
static bool
<API key> (tree t1, tree t2, bool warn, bool *warned,
hash_set<type_pair> *visited,
location_t loc1, location_t loc2)
{
/* Check first for the obvious case of pointer identity. */
if (t1 == t2)
return true;
gcc_assert (!type_with_linkage_p (t1) || !<API key> (t1));
gcc_assert (!type_with_linkage_p (t2) || !<API key> (t2));
/* Can't be the same type if the types don't have the same code. */
if (TREE_CODE (t1) != TREE_CODE (t2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a different type is defined in another translation unit"));
return false;
}
if (TYPE_QUALS (t1) != TYPE_QUALS (t2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type with different qualifiers is defined in another "
"translation unit"));
return false;
}
if ((type_with_linkage_p (t1) && <API key> (t1))
|| (type_with_linkage_p (t2) && <API key> (t2)))
{
/* We can not trip this when comparing ODR types, only when trying to
match different ODR derivations from different declarations.
So WARN should be always false. */
gcc_assert (!warn);
return false;
}
if (<API key> (t1, t2) != 1)
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type with different attributes "
"is defined in another translation unit"));
return false;
}
if (TREE_CODE (t1) == ENUMERAL_TYPE
&& TYPE_VALUES (t1) && TYPE_VALUES (t2))
{
tree v1, v2;
for (v1 = TYPE_VALUES (t1), v2 = TYPE_VALUES (t2);
v1 && v2 ; v1 = TREE_CHAIN (v1), v2 = TREE_CHAIN (v2))
{
if (TREE_PURPOSE (v1) != TREE_PURPOSE (v2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("an enum with different value name"
" is defined in another translation unit"));
return false;
}
if (TREE_VALUE (v1) != TREE_VALUE (v2)
&& !operand_equal_p (DECL_INITIAL (TREE_VALUE (v1)),
DECL_INITIAL (TREE_VALUE (v2)), 0))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("an enum with different values is defined"
" in another translation unit"));
return false;
}
}
if (v1 || v2)
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("an enum with mismatching number of values "
"is defined in another translation unit"));
return false;
}
}
/* Non-aggregate types can be handled cheaply. */
if (INTEGRAL_TYPE_P (t1)
|| SCALAR_FLOAT_TYPE_P (t1)
|| FIXED_POINT_TYPE_P (t1)
|| TREE_CODE (t1) == VECTOR_TYPE
|| TREE_CODE (t1) == COMPLEX_TYPE
|| TREE_CODE (t1) == OFFSET_TYPE
|| POINTER_TYPE_P (t1))
{
if (TYPE_PRECISION (t1) != TYPE_PRECISION (t2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type with different precision is defined "
"in another translation unit"));
return false;
}
if (TYPE_UNSIGNED (t1) != TYPE_UNSIGNED (t2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type with different signedness is defined "
"in another translation unit"));
return false;
}
if (TREE_CODE (t1) == INTEGER_TYPE
&& TYPE_STRING_FLAG (t1) != TYPE_STRING_FLAG (t2))
{
/* char WRT uint_8? */
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a different type is defined in another "
"translation unit"));
return false;
}
/* For canonical type comparisons we do not want to build SCCs
so we cannot compare pointed-to types. But we can, for now,
require the same pointed-to type kind and match what
<API key> would do. */
if (POINTER_TYPE_P (t1))
{
if (TYPE_ADDR_SPACE (TREE_TYPE (t1))
!= TYPE_ADDR_SPACE (TREE_TYPE (t2)))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("it is defined as a pointer in different address "
"space in another translation unit"));
return false;
}
if (!<API key> (TREE_TYPE (t1), TREE_TYPE (t2),
visited, loc1, loc2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("it is defined as a pointer to different type "
"in another translation unit"));
if (warn && warned)
warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2),
loc1, loc2);
return false;
}
}
if ((TREE_CODE (t1) == VECTOR_TYPE || TREE_CODE (t1) == COMPLEX_TYPE)
&& !<API key> (TREE_TYPE (t1), TREE_TYPE (t2),
visited, loc1, loc2))
{
/* Probably specific enough. */
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a different type is defined "
"in another translation unit"));
if (warn && warned)
warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc1, loc2);
return false;
}
}
/* Do type-specific comparisons. */
else switch (TREE_CODE (t1))
{
case ARRAY_TYPE:
{
/* Array types are the same if the element types are the same and
the number of elements are the same. */
if (!<API key> (TREE_TYPE (t1), TREE_TYPE (t2),
visited, loc1, loc2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a different type is defined in another "
"translation unit"));
if (warn && warned)
warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc1, loc2);
}
gcc_assert (TYPE_STRING_FLAG (t1) == TYPE_STRING_FLAG (t2));
gcc_assert (<API key> (t1)
== <API key> (t2));
tree i1 = TYPE_DOMAIN (t1);
tree i2 = TYPE_DOMAIN (t2);
/* For an incomplete external array, the type domain can be
NULL_TREE. Check this condition also. */
if (i1 == NULL_TREE || i2 == NULL_TREE)
return true;
tree min1 = TYPE_MIN_VALUE (i1);
tree min2 = TYPE_MIN_VALUE (i2);
tree max1 = TYPE_MAX_VALUE (i1);
tree max2 = TYPE_MAX_VALUE (i2);
/* In C++, minimums should be always 0. */
gcc_assert (min1 == min2);
if (!operand_equal_p (max1, max2, 0))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("an array of different size is defined "
"in another translation unit"));
return false;
}
}
break;
case METHOD_TYPE:
case FUNCTION_TYPE:
/* Function types are the same if the return type and arguments types
are the same. */
if (!<API key> (TREE_TYPE (t1), TREE_TYPE (t2),
visited, loc1, loc2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("has different return value "
"in another translation unit"));
if (warn && warned)
warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc1, loc2);
return false;
}
if (TYPE_ARG_TYPES (t1) == TYPE_ARG_TYPES (t2)
|| !prototype_p (t1) || !prototype_p (t2))
return true;
else
{
tree parms1, parms2;
for (parms1 = TYPE_ARG_TYPES (t1), parms2 = TYPE_ARG_TYPES (t2);
parms1 && parms2;
parms1 = TREE_CHAIN (parms1), parms2 = TREE_CHAIN (parms2))
{
if (!<API key>
(TREE_VALUE (parms1), TREE_VALUE (parms2), visited,
loc1, loc2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("has different parameters in another "
"translation unit"));
if (warn && warned)
warn_types_mismatch (TREE_VALUE (parms1),
TREE_VALUE (parms2), loc1, loc2);
return false;
}
}
if (parms1 || parms2)
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("has different parameters "
"in another translation unit"));
return false;
}
return true;
}
case RECORD_TYPE:
case UNION_TYPE:
case QUAL_UNION_TYPE:
{
tree f1, f2;
/* For aggregate types, all the fields must be the same. */
if (COMPLETE_TYPE_P (t1) && COMPLETE_TYPE_P (t2))
{
if (TYPE_BINFO (t1) && TYPE_BINFO (t2)
&& <API key> (TYPE_BINFO (t1))
!= <API key> (TYPE_BINFO (t2)))
{
if (<API key> (TYPE_BINFO (t1)))
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type defined in another translation unit "
"is not polymorphic"));
else
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type defined in another translation unit "
"is polymorphic"));
return false;
}
for (f1 = TYPE_FIELDS (t1), f2 = TYPE_FIELDS (t2);
f1 || f2;
f1 = TREE_CHAIN (f1), f2 = TREE_CHAIN (f2))
{
/* Skip non-fields. */
while (f1 && TREE_CODE (f1) != FIELD_DECL)
f1 = TREE_CHAIN (f1);
while (f2 && TREE_CODE (f2) != FIELD_DECL)
f2 = TREE_CHAIN (f2);
if (!f1 || !f2)
break;
if (DECL_VIRTUAL_P (f1) != DECL_VIRTUAL_P (f2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type with different virtual table pointers"
" is defined in another translation unit"));
return false;
}
if (DECL_ARTIFICIAL (f1) != DECL_ARTIFICIAL (f2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type with different bases is defined "
"in another translation unit"));
return false;
}
if (DECL_NAME (f1) != DECL_NAME (f2)
&& !DECL_ARTIFICIAL (f1))
{
warn_odr (t1, t2, f1, f2, warn, warned,
G_("a field with different name is defined "
"in another translation unit"));
return false;
}
if (!<API key> (TREE_TYPE (f1),
TREE_TYPE (f2), visited,
loc1, loc2))
{
/* Do not warn about artificial fields and just go into
generic field mismatch warning. */
if (DECL_ARTIFICIAL (f1))
break;
warn_odr (t1, t2, f1, f2, warn, warned,
G_("a field of same name but different type "
"is defined in another translation unit"));
if (warn && warned)
warn_types_mismatch (TREE_TYPE (f1), TREE_TYPE (f2), loc1, loc2);
return false;
}
if (!<API key> (f1, f2))
{
/* Do not warn about artificial fields and just go into
generic field mismatch warning. */
if (DECL_ARTIFICIAL (f1))
break;
warn_odr (t1, t2, f1, f2, warn, warned,
G_("fields has different layout "
"in another translation unit"));
return false;
}
gcc_assert (<API key> (f1)
== <API key> (f2));
}
/* If one aggregate has more fields than the other, they
are not the same. */
if (f1 || f2)
{
if ((f1 && DECL_VIRTUAL_P (f1)) || (f2 && DECL_VIRTUAL_P (f2)))
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type with different virtual table pointers"
" is defined in another translation unit"));
else if ((f1 && DECL_ARTIFICIAL (f1))
|| (f2 && DECL_ARTIFICIAL (f2)))
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type with different bases is defined "
"in another translation unit"));
else
warn_odr (t1, t2, f1, f2, warn, warned,
G_("a type with different number of fields "
"is defined in another translation unit"));
return false;
}
if ((TYPE_MAIN_VARIANT (t1) == t1 || TYPE_MAIN_VARIANT (t2) == t2)
&& COMPLETE_TYPE_P (TYPE_MAIN_VARIANT (t1))
&& COMPLETE_TYPE_P (TYPE_MAIN_VARIANT (t2))
&& odr_type_p (TYPE_MAIN_VARIANT (t1))
&& odr_type_p (TYPE_MAIN_VARIANT (t2))
&& (TYPE_METHODS (TYPE_MAIN_VARIANT (t1))
!= TYPE_METHODS (TYPE_MAIN_VARIANT (t2))))
{
/* Currently free_lang_data sets TYPE_METHODS to error_mark_node
if it is non-NULL so this loop will never realy execute. */
if (TYPE_METHODS (TYPE_MAIN_VARIANT (t1)) != error_mark_node
&& TYPE_METHODS (TYPE_MAIN_VARIANT (t2)) != error_mark_node)
for (f1 = TYPE_METHODS (TYPE_MAIN_VARIANT (t1)),
f2 = TYPE_METHODS (TYPE_MAIN_VARIANT (t2));
f1 && f2 ; f1 = DECL_CHAIN (f1), f2 = DECL_CHAIN (f2))
{
if (DECL_ASSEMBLER_NAME (f1) != DECL_ASSEMBLER_NAME (f2))
{
warn_odr (t1, t2, f1, f2, warn, warned,
G_("a different method of same type "
"is defined in another "
"translation unit"));
return false;
}
if (DECL_VIRTUAL_P (f1) != DECL_VIRTUAL_P (f2))
{
warn_odr (t1, t2, f1, f2, warn, warned,
G_("s definition that differs by virtual "
"keyword in another translation unit"));
return false;
}
if (DECL_VINDEX (f1) != DECL_VINDEX (f2))
{
warn_odr (t1, t2, f1, f2, warn, warned,
G_("virtual table layout differs "
"in another translation unit"));
return false;
}
if (<API key> (TREE_TYPE (f1),
TREE_TYPE (f2), visited,
loc1, loc2))
{
warn_odr (t1, t2, f1, f2, warn, warned,
G_("method with incompatible type is "
"defined in another translation unit"));
return false;
}
}
if ((f1 == NULL) != (f2 == NULL))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type with different number of methods "
"is defined in another translation unit"));
return false;
}
}
}
break;
}
case VOID_TYPE:
case NULLPTR_TYPE:
break;
default:
debug_tree (t1);
gcc_unreachable ();
}
/* Those are better to come last as they are utterly uninformative. */
if (TYPE_SIZE (t1) && TYPE_SIZE (t2)
&& !operand_equal_p (TYPE_SIZE (t1), TYPE_SIZE (t2), 0))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type with different size "
"is defined in another translation unit"));
return false;
}
if (COMPLETE_TYPE_P (t1) && COMPLETE_TYPE_P (t2)
&& TYPE_ALIGN (t1) != TYPE_ALIGN (t2))
{
warn_odr (t1, t2, NULL, NULL, warn, warned,
G_("a type with different alignment "
"is defined in another translation unit"));
return false;
}
gcc_assert (!TYPE_SIZE_UNIT (t1) || !TYPE_SIZE_UNIT (t2)
|| operand_equal_p (TYPE_SIZE_UNIT (t1),
TYPE_SIZE_UNIT (t2), 0));
return true;
}
/* Return true if TYPE1 and TYPE2 are equivalent for One Definition Rule. */
bool
<API key> (tree type1, tree type2)
{
hash_set<type_pair> visited;
#ifdef ENABLE_CHECKING
gcc_assert (<API key> (type1) && <API key> (type2));
#endif
return <API key> (type1, type2, false, NULL,
&visited, UNKNOWN_LOCATION, UNKNOWN_LOCATION);
}
/* TYPE is equivalent to VAL by ODR, but its tree representation differs
from VAL->type. This may happen in LTO where tree merging did not merge
all variants of the same type or due to ODR violation.
Analyze and report ODR violations and add type to duplicate list.
If TYPE is more specified than VAL->type, prevail VAL->type. Also if
this is first time we see definition of a class return true so the
base types are analyzed. */
static bool
add_type_duplicate (odr_type val, tree type)
{
bool build_bases = false;
bool prevail = false;
bool odr_must_violate = false;
if (!val->types_set)
val->types_set = new hash_set<tree>;
/* Chose polymorphic type as leader (this happens only in case of ODR
violations. */
if ((TREE_CODE (type) == RECORD_TYPE && TYPE_BINFO (type)
&& <API key> (TYPE_BINFO (type)))
&& (TREE_CODE (val->type) != RECORD_TYPE || !TYPE_BINFO (val->type)
|| !<API key> (TYPE_BINFO (val->type))))
{
prevail = true;
build_bases = true;
}
/* Always prefer complete type to be the leader. */
else if (!COMPLETE_TYPE_P (val->type) && COMPLETE_TYPE_P (type))
{
prevail = true;
build_bases = TYPE_BINFO (type);
}
else if (COMPLETE_TYPE_P (val->type) && !COMPLETE_TYPE_P (type))
;
else if (TREE_CODE (val->type) == ENUMERAL_TYPE
&& TREE_CODE (type) == ENUMERAL_TYPE
&& !TYPE_VALUES (val->type) && TYPE_VALUES (type))
prevail = true;
else if (TREE_CODE (val->type) == RECORD_TYPE
&& TREE_CODE (type) == RECORD_TYPE
&& TYPE_BINFO (type) && !TYPE_BINFO (val->type))
{
gcc_assert (!val->bases.length ());
build_bases = true;
prevail = true;
}
if (prevail)
std::swap (val->type, type);
val->types_set->add (type);
/* If we now have a mangled name, be sure to record it to val->type
so ODR hash can work. */
if (<API key> (type) && !<API key> (val->type))
<API key> (TYPE_NAME (val->type),
DECL_ASSEMBLER_NAME (TYPE_NAME (type)));
bool merge = true;
bool base_mismatch = false;
unsigned int i;
bool warned = false;
hash_set<type_pair> visited;
gcc_assert (in_lto_p);
vec_safe_push (val->types, type);
/* If both are class types, compare the bases. */
if (COMPLETE_TYPE_P (type) && COMPLETE_TYPE_P (val->type)
&& TREE_CODE (val->type) == RECORD_TYPE
&& TREE_CODE (type) == RECORD_TYPE
&& TYPE_BINFO (val->type) && TYPE_BINFO (type))
{
if (BINFO_N_BASE_BINFOS (TYPE_BINFO (type))
!= BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)))
{
if (!flag_ltrans && !warned && !val->odr_violated)
{
tree extra_base;
warn_odr (type, val->type, NULL, NULL, !warned, &warned,
"a type with the same name but different "
"number of polymorphic bases is "
"defined in another translation unit");
if (warned)
{
if (BINFO_N_BASE_BINFOS (TYPE_BINFO (type))
> BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)))
extra_base = BINFO_BASE_BINFO
(TYPE_BINFO (type),
BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)));
else
extra_base = BINFO_BASE_BINFO
(TYPE_BINFO (val->type),
BINFO_N_BASE_BINFOS (TYPE_BINFO (type)));
tree extra_base_type = BINFO_TYPE (extra_base);
inform (<API key> (TYPE_NAME (extra_base_type)),
"the extra base is defined here");
}
}
base_mismatch = true;
}
else
for (i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type)); i++)
{
tree base1 = BINFO_BASE_BINFO (TYPE_BINFO (type), i);
tree base2 = BINFO_BASE_BINFO (TYPE_BINFO (val->type), i);
tree type1 = BINFO_TYPE (base1);
tree type2 = BINFO_TYPE (base2);
if (<API key> (type1, type2))
{
if (!types_same_for_odr (type1, type2))
base_mismatch = true;
}
else
if (!<API key> (type1, type2))
base_mismatch = true;
if (base_mismatch)
{
if (!warned && !val->odr_violated)
{
warn_odr (type, val->type, NULL, NULL,
!warned, &warned,
"a type with the same name but different base "
"type is defined in another translation unit");
if (warned)
warn_types_mismatch (type1, type2,
UNKNOWN_LOCATION, UNKNOWN_LOCATION);
}
break;
}
if (BINFO_OFFSET (base1) != BINFO_OFFSET (base2))
{
base_mismatch = true;
if (!warned && !val->odr_violated)
warn_odr (type, val->type, NULL, NULL,
!warned, &warned,
"a type with the same name but different base "
"layout is defined in another translation unit");
break;
}
/* One of bases is not of complete type. */
if (!TYPE_BINFO (type1) != !TYPE_BINFO (type2))
{
/* If we have a polymorphic type info specified for TYPE1
but not for TYPE2 we possibly missed a base when recording
VAL->type earlier.
Be sure this does not happen. */
if (TYPE_BINFO (type1)
&& <API key> (TYPE_BINFO (type1))
&& !build_bases)
odr_must_violate = true;
break;
}
/* One base is polymorphic and the other not.
This ought to be diagnosed earlier, but do not ICE in the
checking bellow. */
else if (TYPE_BINFO (type1)
&& <API key> (TYPE_BINFO (type1))
!= <API key> (TYPE_BINFO (type2)))
{
if (!warned && !val->odr_violated)
warn_odr (type, val->type, NULL, NULL,
!warned, &warned,
"a base of the type is polymorphic only in one "
"translation unit");
base_mismatch = true;
break;
}
}
if (base_mismatch)
{
merge = false;
<API key> = true;
val->odr_violated = true;
if (symtab->dump_file)
{
fprintf (symtab->dump_file, "ODR base violation\n");
print_node (symtab->dump_file, "", val->type, 0);
putc ('\n',symtab->dump_file);
print_node (symtab->dump_file, "", type, 0);
putc ('\n',symtab->dump_file);
}
}
}
/* Next compare memory layout. */
if (!<API key> (val->type, type,
!flag_ltrans && !val->odr_violated && !warned,
&warned, &visited,
<API key> (TYPE_NAME (val->type)),
<API key> (TYPE_NAME (type))))
{
merge = false;
<API key> = true;
val->odr_violated = true;
if (symtab->dump_file)
{
fprintf (symtab->dump_file, "ODR violation\n");
print_node (symtab->dump_file, "", val->type, 0);
putc ('\n',symtab->dump_file);
print_node (symtab->dump_file, "", type, 0);
putc ('\n',symtab->dump_file);
}
}
gcc_assert (val->odr_violated || !odr_must_violate);
/* Sanity check that all bases will be build same way again. */
#ifdef ENABLE_CHECKING
if (COMPLETE_TYPE_P (type) && COMPLETE_TYPE_P (val->type)
&& TREE_CODE (val->type) == RECORD_TYPE
&& TREE_CODE (type) == RECORD_TYPE
&& TYPE_BINFO (val->type) && TYPE_BINFO (type)
&& !val->odr_violated
&& !base_mismatch && val->bases.length ())
{
unsigned int num_poly_bases = 0;
unsigned int j;
for (i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type)); i++)
if (<API key> (BINFO_BASE_BINFO
(TYPE_BINFO (type), i)))
num_poly_bases++;
gcc_assert (num_poly_bases == val->bases.length ());
for (j = 0, i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type));
i++)
if (<API key> (BINFO_BASE_BINFO
(TYPE_BINFO (type), i)))
{
odr_type base = get_odr_type
(BINFO_TYPE
(BINFO_BASE_BINFO (TYPE_BINFO (type),
i)),
true);
gcc_assert (val->bases[j] == base);
j++;
}
}
#endif
/* Regularize things a little. During LTO same types may come with
different BINFOs. Either because their virtual table was
not merged by tree merging and only later at decl merging or
because one type comes with external vtable, while other
with internal. We want to merge equivalent binfos to conserve
memory and streaming overhead.
The external vtables are more harmful: they contain references
to external declarations of methods that may be defined in the
merged LTO unit. For this reason we absolutely need to remove
them and replace by internal variants. Not doing so will lead
to incomplete answers from <API key>.
FIXME: disable for now; because ODR types are now build during
streaming in, the variants do not need to be linked to the type,
yet. We need to do the merging in cleanup pass to be implemented
soon. */
if (!flag_ltrans && merge
&& 0
&& TREE_CODE (val->type) == RECORD_TYPE
&& TREE_CODE (type) == RECORD_TYPE
&& TYPE_BINFO (val->type) && TYPE_BINFO (type)
&& TYPE_MAIN_VARIANT (type) == type
&& TYPE_MAIN_VARIANT (val->type) == val->type
&& BINFO_VTABLE (TYPE_BINFO (val->type))
&& BINFO_VTABLE (TYPE_BINFO (type)))
{
tree master_binfo = TYPE_BINFO (val->type);
tree v1 = BINFO_VTABLE (master_binfo);
tree v2 = BINFO_VTABLE (TYPE_BINFO (type));
if (TREE_CODE (v1) == POINTER_PLUS_EXPR)
{
gcc_assert (TREE_CODE (v2) == POINTER_PLUS_EXPR
&& operand_equal_p (TREE_OPERAND (v1, 1),
TREE_OPERAND (v2, 1), 0));
v1 = TREE_OPERAND (TREE_OPERAND (v1, 0), 0);
v2 = TREE_OPERAND (TREE_OPERAND (v2, 0), 0);
}
gcc_assert (DECL_ASSEMBLER_NAME (v1)
== DECL_ASSEMBLER_NAME (v2));
if (DECL_EXTERNAL (v1) && !DECL_EXTERNAL (v2))
{
unsigned int i;
set_type_binfo (val->type, TYPE_BINFO (type));
for (i = 0; i < val->types->length (); i++)
{
if (TYPE_BINFO ((*val->types)[i])
== master_binfo)
set_type_binfo ((*val->types)[i], TYPE_BINFO (type));
}
BINFO_TYPE (TYPE_BINFO (type)) = val->type;
}
else
set_type_binfo (type, master_binfo);
}
return build_bases;
}
/* Get ODR type hash entry for TYPE. If INSERT is true, create
possibly new entry. */
odr_type
get_odr_type (tree type, bool insert)
{
odr_type_d **slot = NULL;
odr_type_d **vtable_slot = NULL;
odr_type val = NULL;
hashval_t hash;
bool build_bases = false;
bool insert_to_odr_array = false;
int base_id = -1;
type = main_odr_variant (type);
gcc_checking_assert (<API key> (type)
|| <API key> (type));
/* Lookup entry, first try name hash, fallback to vtable hash. */
if (<API key> (type))
{
hash = hash_odr_name (type);
slot = odr_hash->find_slot_with_hash (type, hash,
insert ? INSERT : NO_INSERT);
}
if ((!slot || !*slot) && in_lto_p && <API key> (type))
{
hash = hash_odr_vtable (type);
vtable_slot = odr_vtable_hash->find_slot_with_hash (type, hash,
insert ? INSERT : NO_INSERT);
}
if (!slot && !vtable_slot)
return NULL;
/* See if we already have entry for type. */
if ((slot && *slot) || (vtable_slot && *vtable_slot))
{
if (slot && *slot)
{
val = *slot;
#ifdef ENABLE_CHECKING
if (in_lto_p && <API key> (type))
{
hash = hash_odr_vtable (type);
vtable_slot = odr_vtable_hash->find_slot_with_hash (type, hash,
NO_INSERT);
gcc_assert (!vtable_slot || *vtable_slot == *slot);
vtable_slot = NULL;
}
#endif
}
else if (*vtable_slot)
val = *vtable_slot;
if (val->type != type
&& (!val->types_set || !val->types_set->add (type)))
{
gcc_assert (insert);
/* We have type duplicate, but it may introduce vtable name or
mangled name; be sure to keep hashes in sync. */
if (in_lto_p && <API key> (type)
&& (!vtable_slot || !*vtable_slot))
{
if (!vtable_slot)
{
hash = hash_odr_vtable (type);
vtable_slot = odr_vtable_hash->find_slot_with_hash
(type, hash, INSERT);
gcc_checking_assert (!*vtable_slot || *vtable_slot == val);
}
*vtable_slot = val;
}
if (slot && !*slot)
*slot = val;
build_bases = add_type_duplicate (val, type);
}
}
else
{
val = ggc_cleared_alloc<odr_type_d> ();
val->type = type;
val->bases = vNULL;
val->derived_types = vNULL;
if (type_with_linkage_p (type))
val->anonymous_namespace = <API key> (type);
else
val->anonymous_namespace = 0;
build_bases = COMPLETE_TYPE_P (val->type);
insert_to_odr_array = true;
if (slot)
*slot = val;
if (vtable_slot)
*vtable_slot = val;
}
if (build_bases && TREE_CODE (type) == RECORD_TYPE && TYPE_BINFO (type)
&& type_with_linkage_p (type)
&& type == TYPE_MAIN_VARIANT (type))
{
tree binfo = TYPE_BINFO (type);
unsigned int i;
gcc_assert (BINFO_TYPE (TYPE_BINFO (val->type)) == type);
val-><API key> = <API key> (type);
for (i = 0; i < BINFO_N_BASE_BINFOS (binfo); i++)
/* For now record only polymorphic types. other are
pointless for devirtualization and we can not precisely
determine ODR equivalency of these during LTO. */
if (<API key> (BINFO_BASE_BINFO (binfo, i)))
{
tree base_type= BINFO_TYPE (BINFO_BASE_BINFO (binfo, i));
odr_type base = get_odr_type (base_type, true);
gcc_assert (TYPE_MAIN_VARIANT (base_type) == base_type);
base->derived_types.safe_push (val);
val->bases.safe_push (base);
if (base->id > base_id)
base_id = base->id;
}
}
/* Ensure that type always appears after bases. */
if (insert_to_odr_array)
{
if (odr_types_ptr)
val->id = odr_types.length ();
vec_safe_push (odr_types_ptr, val);
}
else if (base_id > val->id)
{
odr_types[val->id] = 0;
/* Be sure we did not recorded any derived types; these may need
renumbering too. */
gcc_assert (val->derived_types.length() == 0);
if (odr_types_ptr)
val->id = odr_types.length ();
vec_safe_push (odr_types_ptr, val);
}
return val;
}
/* Add TYPE od ODR type hash. */
void
register_odr_type (tree type)
{
if (!odr_hash)
{
odr_hash = new odr_hash_type (23);
if (in_lto_p)
odr_vtable_hash = new <API key> (23);
}
/* Arrange things to be nicer and insert main variants first.
??? fundamental prerecorded types do not have mangled names; this
makes it possible that non-ODR type is main_odr_variant of ODR type.
Things may get smoother if LTO FE set mangled name of those types same
way as C++ FE does. */
if (odr_type_p (main_odr_variant (TYPE_MAIN_VARIANT (type)))
&& odr_type_p (TYPE_MAIN_VARIANT (type)))
get_odr_type (TYPE_MAIN_VARIANT (type), true);
if (TYPE_MAIN_VARIANT (type) != type && odr_type_p (main_odr_variant (type)))
get_odr_type (type, true);
}
/* Return true if type is known to have no derivations. */
bool
<API key> (tree t)
{
return (<API key> (t)
&& (TYPE_FINAL_P (t)
|| (odr_hash
&& !get_odr_type (t, true)->derived_types.length())));
}
/* Dump ODR type T and all its derived types. INDENT specifies indentation for
recursive printing. */
static void
dump_odr_type (FILE *f, odr_type t, int indent=0)
{
unsigned int i;
fprintf (f, "%*s type %i: ", indent * 2, "", t->id);
print_generic_expr (f, t->type, TDF_SLIM);
fprintf (f, "%s", t->anonymous_namespace ? " (anonymous namespace)":"");
fprintf (f, "%s\n", t-><API key> ? " (derivations known)":"");
if (TYPE_NAME (t->type))
{
/*fprintf (f, "%*s defined at: %s:%i\n", indent * 2, "",
DECL_SOURCE_FILE (TYPE_NAME (t->type)),
DECL_SOURCE_LINE (TYPE_NAME (t->type)));*/
if (<API key> (TYPE_NAME (t->type)))
fprintf (f, "%*s mangled name: %s\n", indent * 2, "",
IDENTIFIER_POINTER
(DECL_ASSEMBLER_NAME (TYPE_NAME (t->type))));
}
if (t->bases.length ())
{
fprintf (f, "%*s base odr type ids: ", indent * 2, "");
for (i = 0; i < t->bases.length (); i++)
fprintf (f, " %i", t->bases[i]->id);
fprintf (f, "\n");
}
if (t->derived_types.length ())
{
fprintf (f, "%*s derived types:\n", indent * 2, "");
for (i = 0; i < t->derived_types.length (); i++)
dump_odr_type (f, t->derived_types[i], indent + 1);
}
fprintf (f, "\n");
}
/* Dump the type inheritance graph. */
static void
<API key> (FILE *f)
{
unsigned int i;
if (!odr_types_ptr)
return;
fprintf (f, "\n\nType inheritance graph:\n");
for (i = 0; i < odr_types.length (); i++)
{
if (odr_types[i] && odr_types[i]->bases.length () == 0)
dump_odr_type (f, odr_types[i]);
}
for (i = 0; i < odr_types.length (); i++)
{
if (odr_types[i] && odr_types[i]->types && odr_types[i]->types->length ())
{
unsigned int j;
fprintf (f, "Duplicate tree types for odr type %i\n", i);
print_node (f, "", odr_types[i]->type, 0);
for (j = 0; j < odr_types[i]->types->length (); j++)
{
tree t;
fprintf (f, "duplicate #%i\n", j);
print_node (f, "", (*odr_types[i]->types)[j], 0);
t = (*odr_types[i]->types)[j];
while (TYPE_P (t) && TYPE_CONTEXT (t))
{
t = TYPE_CONTEXT (t);
print_node (f, "", t, 0);
}
putc ('\n',f);
}
}
}
}
/* Initialize IPA devirt and build inheritance tree graph. */
void
<API key> (void)
{
struct symtab_node *n;
FILE *<API key>;
int flags;
if (odr_hash)
return;
timevar_push (TV_IPA_INHERITANCE);
<API key> = dump_begin (TDI_inheritance, &flags);
odr_hash = new odr_hash_type (23);
if (in_lto_p)
odr_vtable_hash = new <API key> (23);
/* We reconstruct the graph starting of types of all methods seen in the
the unit. */
FOR_EACH_SYMBOL (n)
if (is_a <cgraph_node *> (n)
&& DECL_VIRTUAL_P (n->decl)
&& n->real_symbol_p ())
get_odr_type (<API key> (TREE_TYPE (n->decl)), true);
/* Look also for virtual tables of types that do not define any methods.
We need it in a case where class B has virtual base of class A
re-defining its virtual method and there is class C with no virtual
methods with B as virtual base.
Here we output B's virtual method in two variant - for non-virtual
and virtual inheritance. B's virtual table has non-virtual version,
while C's has virtual.
For this reason we need to know about C in order to include both
variants of B. More correctly, <API key> should
add both variants of the method when walking B, but we have no
link in between them.
We rely on fact that either the method is exported and thus we
assume it is called externally or C is in anonymous namespace and
thus we will see the vtable. */
else if (is_a <varpool_node *> (n)
&& DECL_VIRTUAL_P (n->decl)
&& TREE_CODE (DECL_CONTEXT (n->decl)) == RECORD_TYPE
&& TYPE_BINFO (DECL_CONTEXT (n->decl))
&& <API key> (TYPE_BINFO (DECL_CONTEXT (n->decl))))
get_odr_type (TYPE_MAIN_VARIANT (DECL_CONTEXT (n->decl)), true);
if (<API key>)
{
<API key> (<API key>);
dump_end (TDI_inheritance, <API key>);
}
timevar_pop (TV_IPA_INHERITANCE);
}
/* Return true if N has reference from live virtual table
(and thus can be a destination of polymorphic call).
Be conservatively correct when callgraph is not built or
if the method may be referred externally. */
static bool
<API key> (struct cgraph_node *node)
{
int i;
struct ipa_ref *ref;
bool found = false;
if (node->externally_visible
|| DECL_EXTERNAL (node->decl)
|| node-><API key>)
return true;
/* Keep this test constant time.
It is unlikely this can happen except for the case where speculative
devirtualization introduced many speculative edges to this node.
In this case the target is very likely alive anyway. */
if (node->ref_list.referring.length () > 100)
return true;
/* We need references built. */
if (symtab->state <= CONSTRUCTION)
return true;
for (i = 0; node->iterate_referring (i, ref); i++)
if ((ref->use == IPA_REF_ALIAS
&& <API key> (dyn_cast<cgraph_node *> (ref->referring)))
|| (ref->use == IPA_REF_ADDR
&& TREE_CODE (ref->referring->decl) == VAR_DECL
&& DECL_VIRTUAL_P (ref->referring->decl)))
{
found = true;
break;
}
return found;
}
/* If TARGET has associated node, record it in the NODES array.
CAN_REFER specify if program can refer to the target directly.
if TARGET is unknown (NULL) or it can not be inserted (for example because
its body was already removed and there is no way to refer to it), clear
COMPLETEP. */
static void
maybe_record_node (vec <cgraph_node *> &nodes,
tree target, hash_set<tree> *inserted,
bool can_refer,
bool *completep)
{
struct cgraph_node *target_node, *alias_target;
enum availability avail;
/* cxa_pure_virtual and <API key> do not need to be added into
list of targets; the runtime effect of calling them is undefined.
Only "real" virtual methods should be accounted. */
if (target && TREE_CODE (TREE_TYPE (target)) != METHOD_TYPE)
return;
if (!can_refer)
{
/* The only case when method of anonymous namespace becomes unreferable
is when we completely optimized it out. */
if (flag_ltrans
|| !target
|| !<API key> (DECL_CONTEXT (target)))
*completep = false;
return;
}
if (!target)
return;
target_node = cgraph_node::get (target);
/* Prefer alias target over aliases, so we do not get confused by
fake duplicates. */
if (target_node)
{
alias_target = target_node-><API key> (&avail);
if (target_node != alias_target
&& avail >= AVAIL_AVAILABLE
&& target_node->get_availability ())
target_node = alias_target;
}
/* Method can only be called by polymorphic call if any
of vtables referring to it are alive.
While this holds for non-anonymous functions, too, there are
cases where we want to keep them in the list; for example
inline functions with -fno-weak are static, but we still
may devirtualize them when instance comes from other unit.
The same holds for LTO.
Currently we ignore these functions in speculative devirtualization.
??? Maybe it would make sense to be more aggressive for LTO even
elsewhere. */
if (!flag_ltrans
&& <API key> (DECL_CONTEXT (target))
&& (!target_node
|| !<API key> (target_node)))
;
/* See if TARGET is useful function we can deal with. */
else if (target_node != NULL
&& (TREE_PUBLIC (target)
|| DECL_EXTERNAL (target)
|| target_node->definition)
&& target_node->real_symbol_p ())
{
gcc_assert (!target_node->global.inlined_to);
gcc_assert (target_node->real_symbol_p ());
if (!inserted->add (target))
{
<API key>->add (target_node);
nodes.safe_push (target_node);
}
}
else if (completep
&& (!<API key>
(DECL_CONTEXT (target))
|| flag_ltrans))
*completep = false;
}
/* See if BINFO's type matches OUTER_TYPE. If so, look up
BINFO of subtype of OTR_TYPE at OFFSET and in that BINFO find
method in vtable and insert method to NODES array
or BASES_TO_CONSIDER if this array is non-NULL.
Otherwise recurse to base BINFOs.
This matches what get_binfo_at_offset does, but with offset
being unknown.
TYPE_BINFOS is a stack of BINFOS of types with defined
virtual table seen on way from class type to BINFO.
MATCHED_VTABLES tracks virtual tables we already did lookup
for virtual function in. INSERTED tracks nodes we already
inserted.
ANONYMOUS is true if BINFO is part of anonymous namespace.
Clear COMPLETEP when we hit unreferable target.
*/
static void
<API key> (vec <cgraph_node *> &nodes,
vec <tree> *bases_to_consider,
tree binfo,
tree otr_type,
vec <tree> &type_binfos,
HOST_WIDE_INT otr_token,
tree outer_type,
HOST_WIDE_INT offset,
hash_set<tree> *inserted,
hash_set<tree> *matched_vtables,
bool anonymous,
bool *completep)
{
tree type = BINFO_TYPE (binfo);
int i;
tree base_binfo;
if (BINFO_VTABLE (binfo))
type_binfos.safe_push (binfo);
if (types_same_for_odr (type, outer_type))
{
int i;
tree type_binfo = NULL;
/* Look up BINFO with virtual table. For normal types it is always last
binfo on stack. */
for (i = type_binfos.length () - 1; i >= 0; i
if (BINFO_OFFSET (type_binfos[i]) == BINFO_OFFSET (binfo))
{
type_binfo = type_binfos[i];
break;
}
if (BINFO_VTABLE (binfo))
type_binfos.pop ();
/* If this is duplicated BINFO for base shared by virtual inheritance,
we may not have its associated vtable. This is not a problem, since
we will walk it on the other path. */
if (!type_binfo)
return;
tree inner_binfo = get_binfo_at_offset (type_binfo,
offset, otr_type);
if (!inner_binfo)
{
gcc_assert (<API key>);
return;
}
/* For types in anonymous namespace first check if the respective vtable
is alive. If not, we know the type can't be called. */
if (!flag_ltrans && anonymous)
{
tree vtable = BINFO_VTABLE (inner_binfo);
varpool_node *vnode;
if (TREE_CODE (vtable) == POINTER_PLUS_EXPR)
vtable = TREE_OPERAND (TREE_OPERAND (vtable, 0), 0);
vnode = varpool_node::get (vtable);
if (!vnode || !vnode->definition)
return;
}
gcc_assert (inner_binfo);
if (bases_to_consider
? !matched_vtables->contains (BINFO_VTABLE (inner_binfo))
: !matched_vtables->add (BINFO_VTABLE (inner_binfo)))
{
bool can_refer;
tree target = <API key> (otr_token,
inner_binfo,
&can_refer);
if (!bases_to_consider)
maybe_record_node (nodes, target, inserted, can_refer, completep);
/* Destructors are never called via construction vtables. */
else if (!target || !<API key> (target))
bases_to_consider->safe_push (target);
}
return;
}
/* Walk bases. */
for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
/* Walking bases that have no virtual method is pointless exercise. */
if (<API key> (base_binfo))
<API key> (nodes, bases_to_consider, base_binfo, otr_type,
type_binfos,
otr_token, outer_type, offset, inserted,
matched_vtables, anonymous, completep);
if (BINFO_VTABLE (binfo))
type_binfos.pop ();
}
/* Look up virtual methods matching OTR_TYPE (with OFFSET and OTR_TOKEN)
of TYPE, insert them to NODES, recurse into derived nodes.
INSERTED is used to avoid duplicate insertions of methods into NODES.
MATCHED_VTABLES are used to avoid duplicate walking vtables.
Clear COMPLETEP if unreferable target is found.
If <API key> is true, record to BASES_TO_CONSIDER
all cases where BASE_SKIPPED is true (because the base is abstract
class). */
static void
<API key> (vec <cgraph_node *> &nodes,
hash_set<tree> *inserted,
hash_set<tree> *matched_vtables,
tree otr_type,
odr_type type,
HOST_WIDE_INT otr_token,
tree outer_type,
HOST_WIDE_INT offset,
bool *completep,
vec <tree> &bases_to_consider,
bool <API key>)
{
tree binfo = TYPE_BINFO (type->type);
unsigned int i;
auto_vec <tree, 8> type_binfos;
bool <API key> = <API key> (type->type);
/* We may need to consider types w/o instances because of possible derived
types using their methods either directly or via construction vtables.
We are safe to skip them when all derivations are known, since we will
handle them later.
This is done by recording them to BASES_TO_CONSIDER array. */
if (<API key> || <API key>)
{
<API key> (nodes,
(!<API key>
&& <API key> (type->type))
? &bases_to_consider : NULL,
binfo, otr_type, type_binfos, otr_token,
outer_type, offset,
inserted, matched_vtables,
type->anonymous_namespace, completep);
}
for (i = 0; i < type->derived_types.length (); i++)
<API key> (nodes, inserted,
matched_vtables,
otr_type,
type->derived_types[i],
otr_token, outer_type, offset, completep,
bases_to_consider, <API key>);
}
/* Cache of queries for polymorphic call targets.
Enumerating all call targets may get expensive when there are many
polymorphic calls in the program, so we memoize all the previous
queries and avoid duplicated work. */
struct <API key>
{
HOST_WIDE_INT otr_token;
<API key> context;
odr_type type;
vec <cgraph_node *> targets;
tree decl_warning;
int type_warning;
bool complete;
bool speculative;
};
/* Polymorphic call target cache helpers. */
struct <API key>
: pointer_hash <<API key>>
{
static inline hashval_t hash (const <API key> *);
static inline bool equal (const <API key> *,
const <API key> *);
static inline void remove (<API key> *);
};
/* Return the computed hashcode for ODR_QUERY. */
inline hashval_t
<API key>::hash (const <API key> *odr_query)
{
inchash::hash hstate (odr_query->otr_token);
hstate.add_wide_int (odr_query->type->id);
hstate.merge_hash (TYPE_UID (odr_query->context.outer_type));
hstate.add_wide_int (odr_query->context.offset);
if (odr_query->context.<API key>)
{
hstate.merge_hash (TYPE_UID (odr_query->context.<API key>));
hstate.add_wide_int (odr_query->context.speculative_offset);
}
hstate.add_flag (odr_query->speculative);
hstate.add_flag (odr_query->context.<API key>);
hstate.add_flag (odr_query->context.maybe_derived_type);
hstate.add_flag (odr_query->context.<API key>);
hstate.commit_flag ();
return hstate.end ();
}
/* Compare cache entries T1 and T2. */
inline bool
<API key>::equal (const <API key> *t1,
const <API key> *t2)
{
return (t1->type == t2->type && t1->otr_token == t2->otr_token
&& t1->speculative == t2->speculative
&& t1->context.offset == t2->context.offset
&& t1->context.speculative_offset == t2->context.speculative_offset
&& t1->context.outer_type == t2->context.outer_type
&& t1->context.<API key> == t2->context.<API key>
&& t1->context.<API key>
== t2->context.<API key>
&& t1->context.maybe_derived_type == t2->context.maybe_derived_type
&& (t1->context.<API key>
== t2->context.<API key>));
}
/* Remove entry in polymorphic call target cache hash. */
inline void
<API key>::remove (<API key> *v)
{
v->targets.release ();
free (v);
}
/* Polymorphic call target query cache. */
typedef hash_table<<API key>>
<API key>;
static <API key> *<API key>;
/* Destroy polymorphic call target query cache. */
static void
<API key> ()
{
if (<API key>)
{
delete <API key>;
<API key> = NULL;
delete <API key>;
<API key> = NULL;
}
}
/* When virtual function is removed, we may need to flush the cache. */
static void
<API key> (struct cgraph_node *n, void *d ATTRIBUTE_UNUSED)
{
if (<API key>
&& <API key>->contains (n))
<API key> ();
}
/* Look up base of BINFO that has virtual table VTABLE with OFFSET. */
tree
<API key> (tree binfo, unsigned HOST_WIDE_INT offset,
tree vtable)
{
tree v = BINFO_VTABLE (binfo);
int i;
tree base_binfo;
unsigned HOST_WIDE_INT this_offset;
if (v)
{
if (!<API key> (v, &v, &this_offset))
gcc_unreachable ();
if (offset == this_offset
&& DECL_ASSEMBLER_NAME (v) == DECL_ASSEMBLER_NAME (vtable))
return binfo;
}
for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
if (<API key> (base_binfo))
{
base_binfo = <API key> (base_binfo, offset, vtable);
if (base_binfo)
return base_binfo;
}
return NULL;
}
/* T is known constant value of virtual table pointer.
Store virtual table to V and its offset to OFFSET.
Return false if T does not look like virtual table reference. */
bool
<API key> (const_tree t, tree *v,
unsigned HOST_WIDE_INT *offset)
{
/* We expect &MEM[(void *)&virtual_table + 16B].
We obtain object's BINFO from the context of the virtual table.
This one contains pointer to virtual table represented via
POINTER_PLUS_EXPR. Verify that this pointer matches what
we propagated through.
In the case of virtual inheritance, the virtual tables may
be nested, i.e. the offset may be different from 16 and we may
need to dive into the type representation. */
if (TREE_CODE (t) == ADDR_EXPR
&& TREE_CODE (TREE_OPERAND (t, 0)) == MEM_REF
&& TREE_CODE (TREE_OPERAND (TREE_OPERAND (t, 0), 0)) == ADDR_EXPR
&& TREE_CODE (TREE_OPERAND (TREE_OPERAND (t, 0), 1)) == INTEGER_CST
&& (TREE_CODE (TREE_OPERAND (TREE_OPERAND (TREE_OPERAND (t, 0), 0), 0))
== VAR_DECL)
&& DECL_VIRTUAL_P (TREE_OPERAND (TREE_OPERAND
(TREE_OPERAND (t, 0), 0), 0)))
{
*v = TREE_OPERAND (TREE_OPERAND (TREE_OPERAND (t, 0), 0), 0);
*offset = tree_to_uhwi (TREE_OPERAND (TREE_OPERAND (t, 0), 1));
return true;
}
/* Alternative representation, used by C++ frontend is POINTER_PLUS_EXPR.
We need to handle it when T comes from static variable initializer or
BINFO. */
if (TREE_CODE (t) == POINTER_PLUS_EXPR)
{
*offset = tree_to_uhwi (TREE_OPERAND (t, 1));
t = TREE_OPERAND (t, 0);
}
else
*offset = 0;
if (TREE_CODE (t) != ADDR_EXPR)
return false;
*v = TREE_OPERAND (t, 0);
return true;
}
/* T is known constant value of virtual table pointer. Return BINFO of the
instance type. */
tree
<API key> (const_tree t)
{
tree vtable;
unsigned HOST_WIDE_INT offset;
if (!<API key> (t, &vtable, &offset))
return NULL_TREE;
/* FIXME: for stores of construction vtables we return NULL,
because we do not have BINFO for those. Eventually we should fix
our representation to allow this case to be handled, too.
In the case we see store of BINFO we however may assume
that standard folding will be able to cope with it. */
return <API key> (TYPE_BINFO (DECL_CONTEXT (vtable)),
offset, vtable);
}
/* Walk bases of OUTER_TYPE that contain OTR_TYPE at OFFSET.
Look up their respective virtual methods for OTR_TOKEN and OTR_TYPE
and insert them in NODES.
MATCHED_VTABLES and INSERTED is used to avoid duplicated work. */
static void
<API key> (tree otr_type,
HOST_WIDE_INT otr_token,
tree outer_type,
HOST_WIDE_INT offset,
vec <cgraph_node *> &nodes,
hash_set<tree> *inserted,
hash_set<tree> *matched_vtables,
bool *completep)
{
while (true)
{
HOST_WIDE_INT pos, size;
tree base_binfo;
tree fld;
if (types_same_for_odr (outer_type, otr_type))
return;
for (fld = TYPE_FIELDS (outer_type); fld; fld = DECL_CHAIN (fld))
{
if (TREE_CODE (fld) != FIELD_DECL)
continue;
pos = int_bit_position (fld);
size = tree_to_shwi (DECL_SIZE (fld));
if (pos <= offset && (pos + size) > offset
/* Do not get confused by zero sized bases. */
&& <API key> (TYPE_BINFO (TREE_TYPE (fld))))
break;
}
/* Within a class type we should always find corresponding fields. */
gcc_assert (fld && TREE_CODE (TREE_TYPE (fld)) == RECORD_TYPE);
/* Nonbase types should have been stripped by outer_class_type. */
gcc_assert (DECL_ARTIFICIAL (fld));
outer_type = TREE_TYPE (fld);
offset -= pos;
base_binfo = get_binfo_at_offset (TYPE_BINFO (outer_type),
offset, otr_type);
if (!base_binfo)
{
gcc_assert (<API key>);
return;
}
gcc_assert (base_binfo);
if (!matched_vtables->add (BINFO_VTABLE (base_binfo)))
{
bool can_refer;
tree target = <API key> (otr_token,
base_binfo,
&can_refer);
if (!target || ! <API key> (target))
maybe_record_node (nodes, target, inserted, can_refer, completep);
matched_vtables->add (BINFO_VTABLE (base_binfo));
}
}
}
/* When virtual table is removed, we may need to flush the cache. */
static void
<API key> (varpool_node *n,
void *d ATTRIBUTE_UNUSED)
{
if (<API key>
&& DECL_VIRTUAL_P (n->decl)
&& <API key> (DECL_CONTEXT (n->decl)))
<API key> ();
}
/* Record about how many calls would benefit from given type to be final. */
struct odr_type_warn_count
{
tree type;
int count;
gcov_type dyn_count;
};
/* Record about how many calls would benefit from given method to be final. */
struct decl_warn_count
{
tree decl;
int count;
gcov_type dyn_count;
};
/* Information about type and decl warnings. */
struct <API key>
{
gcov_type dyn_count;
vec<odr_type_warn_count> type_warnings;
hash_map<tree, decl_warn_count> decl_warnings;
};
struct <API key> *<API key>;
/* Return vector containing possible targets of polymorphic call of type
OTR_TYPE calling method OTR_TOKEN within type of OTR_OUTER_TYPE and OFFSET.
If INCLUDE_BASES is true, walk also base types of OUTER_TYPES containing
OTR_TYPE and include their virtual method. This is useful for types
possibly in construction or destruction where the virtual table may
temporarily change to one of base types. <API key> make
us to walk the inheritance graph for all derivations.
If COMPLETEP is non-NULL, store true if the list is complete.
CACHE_TOKEN (if non-NULL) will get stored to an unique ID of entry
in the target cache. If user needs to visit every target list
just once, it can memoize them.
If SPECULATIVE is set, the list will not contain targets that
are not speculatively taken.
Returned vector is placed into cache. It is NOT caller's responsibility
to free it. The vector can be freed on cgraph_remove_node call if
the particular node is a virtual function present in the cache. */
vec <cgraph_node *>
<API key> (tree otr_type,
HOST_WIDE_INT otr_token,
<API key> context,
bool *completep,
void **cache_token,
bool speculative)
{
static struct <API key> *<API key>;
vec <cgraph_node *> nodes = vNULL;
auto_vec <tree, 8> bases_to_consider;
odr_type type, outer_type;
<API key> key;
<API key> **slot;
unsigned int i;
tree binfo, target;
bool complete;
bool can_refer = false;
bool skipped = false;
otr_type = TYPE_MAIN_VARIANT (otr_type);
/* If ODR is not initialized or the context is invalid, return empty
incomplete list. */
if (!odr_hash || context.invalid || !TYPE_BINFO (otr_type))
{
if (completep)
*completep = context.invalid;
if (cache_token)
*cache_token = NULL;
return nodes;
}
/* Do not bother to compute speculative info when user do not asks for it. */
if (!speculative || !context.<API key>)
context.clear_speculation ();
type = get_odr_type (otr_type, true);
/* Recording type variants would waste results cache. */
gcc_assert (!context.outer_type
|| TYPE_MAIN_VARIANT (context.outer_type) == context.outer_type);
/* Look up the outer class type we want to walk.
If we fail to do so, the context is invalid. */
if ((context.outer_type || context.<API key>)
&& !context.<API key> (otr_type))
{
if (completep)
*completep = true;
if (cache_token)
*cache_token = NULL;
return nodes;
}
gcc_assert (!context.invalid);
/* Check that <API key> kept the main variant. */
gcc_assert (!context.outer_type
|| TYPE_MAIN_VARIANT (context.outer_type) == context.outer_type);
/* We canonicalize our query, so we do not need extra hashtable entries. */
/* Without outer type, we have no use for offset. Just do the
basic search from inner type. */
if (!context.outer_type)
context.clear_outer_type (otr_type);
/* We need to update our hierarchy if the type does not exist. */
outer_type = get_odr_type (context.outer_type, true);
/* If the type is complete, there are no derivations. */
if (TYPE_FINAL_P (outer_type->type))
context.maybe_derived_type = false;
/* Initialize query cache. */
if (!<API key>)
{
<API key> = new hash_set<cgraph_node *>;
<API key>
= new <API key> (23);
if (!<API key>)
{
<API key> =
symtab-><API key> (&<API key>, NULL);
symtab-><API key> (&<API key>,
NULL);
}
}
if (in_lto_p)
{
if (context.outer_type != otr_type)
context.outer_type
= get_odr_type (context.outer_type, true)->type;
if (context.<API key>)
context.<API key>
= get_odr_type (context.<API key>, true)->type;
}
/* Look up cached answer. */
key.type = type;
key.otr_token = otr_token;
key.speculative = speculative;
key.context = context;
slot = <API key>->find_slot (&key, INSERT);
if (cache_token)
*cache_token = (void *)*slot;
if (*slot)
{
if (completep)
*completep = (*slot)->complete;
if ((*slot)->type_warning && <API key>)
{
<API key>->type_warnings[(*slot)->type_warning - 1].count++;
<API key>->type_warnings[(*slot)->type_warning - 1].dyn_count
+= <API key>->dyn_count;
}
if (!speculative && (*slot)->decl_warning && <API key>)
{
struct decl_warn_count *c =
<API key>->decl_warnings.get ((*slot)->decl_warning);
c->count++;
c->dyn_count += <API key>->dyn_count;
}
return (*slot)->targets;
}
complete = true;
/* Do actual search. */
timevar_push (TV_IPA_VIRTUAL_CALL);
*slot = XCNEW (<API key>);
if (cache_token)
*cache_token = (void *)*slot;
(*slot)->type = type;
(*slot)->otr_token = otr_token;
(*slot)->context = context;
(*slot)->speculative = speculative;
hash_set<tree> inserted;
hash_set<tree> matched_vtables;
/* First insert targets we speculatively identified as likely. */
if (context.<API key>)
{
odr_type <API key>;
bool <API key> = true;
/* First insert target from type itself and check if it may have
derived types. */
<API key> = get_odr_type (context.<API key>, true);
if (TYPE_FINAL_P (<API key>->type))
context.<API key> = false;
binfo = get_binfo_at_offset (TYPE_BINFO (<API key>->type),
context.speculative_offset, otr_type);
if (binfo)
target = <API key> (otr_token, binfo,
&can_refer);
else
target = NULL;
/* In the case we get complete method, we don't need
to walk derivations. */
if (target && DECL_FINAL_P (target))
context.<API key> = false;
if (<API key> (<API key>->type))
maybe_record_node (nodes, target, &inserted, can_refer, &<API key>);
if (binfo)
matched_vtables.add (BINFO_VTABLE (binfo));
/* Next walk recursively all derived types. */
if (context.<API key>)
for (i = 0; i < <API key>->derived_types.length(); i++)
<API key> (nodes, &inserted,
&matched_vtables,
otr_type,
<API key>->derived_types[i],
otr_token, <API key>->type,
context.speculative_offset,
&<API key>,
bases_to_consider,
false);
}
if (!speculative || !nodes.length ())
{
/* First see virtual method of type itself. */
binfo = get_binfo_at_offset (TYPE_BINFO (outer_type->type),
context.offset, otr_type);
if (binfo)
target = <API key> (otr_token, binfo,
&can_refer);
else
{
gcc_assert (<API key>);
target = NULL;
}
/* Destructors are never called through construction virtual tables,
because the type is always known. */
if (target && <API key> (target))
context.<API key> = false;
if (target)
{
/* In the case we get complete method, we don't need
to walk derivations. */
if (DECL_FINAL_P (target))
context.maybe_derived_type = false;
}
/* If OUTER_TYPE is abstract, we know we are not seeing its instance. */
if (<API key> (outer_type->type))
maybe_record_node (nodes, target, &inserted, can_refer, &complete);
else
skipped = true;
if (binfo)
matched_vtables.add (BINFO_VTABLE (binfo));
/* Next walk recursively all derived types. */
if (context.maybe_derived_type)
{
for (i = 0; i < outer_type->derived_types.length(); i++)
<API key> (nodes, &inserted,
&matched_vtables,
otr_type,
outer_type->derived_types[i],
otr_token, outer_type->type,
context.offset, &complete,
bases_to_consider,
context.<API key>);
if (!outer_type-><API key>)
{
if (!speculative && <API key>)
{
if (complete
&& nodes.length () == 1
&& <API key>
&& !outer_type->derived_types.length ())
{
if (outer_type->id >= (int)<API key>->type_warnings.length ())
<API key>->type_warnings.safe_grow_cleared
(odr_types.length ());
<API key>->type_warnings[outer_type->id].count++;
<API key>->type_warnings[outer_type->id].dyn_count
+= <API key>->dyn_count;
<API key>->type_warnings[outer_type->id].type
= outer_type->type;
(*slot)->type_warning = outer_type->id + 1;
}
if (complete
&& <API key>
&& nodes.length () == 1
&& types_same_for_odr (DECL_CONTEXT (nodes[0]->decl),
outer_type->type))
{
bool existed;
struct decl_warn_count &c =
<API key>->decl_warnings.get_or_insert
(nodes[0]->decl, &existed);
if (existed)
{
c.count++;
c.dyn_count += <API key>->dyn_count;
}
else
{
c.count = 1;
c.dyn_count = <API key>->dyn_count;
c.decl = nodes[0]->decl;
}
(*slot)->decl_warning = nodes[0]->decl;
}
}
complete = false;
}
}
if (!speculative)
{
/* Destructors are never called through construction virtual tables,
because the type is always known. One of entries may be
cxa_pure_virtual so look to at least two of them. */
if (context.<API key>)
for (i =0 ; i < MIN (nodes.length (), 2); i++)
if (<API key> (nodes[i]->decl))
context.<API key> = false;
if (context.<API key>)
{
if (type != outer_type
&& (!skipped
|| (context.maybe_derived_type
&& !<API key> (outer_type->type))))
<API key> (otr_type, otr_token, outer_type->type,
context.offset, nodes, &inserted,
&matched_vtables, &complete);
if (skipped)
maybe_record_node (nodes, target, &inserted, can_refer, &complete);
for (i = 0; i < bases_to_consider.length(); i++)
maybe_record_node (nodes, bases_to_consider[i], &inserted, can_refer, &complete);
}
}
}
(*slot)->targets = nodes;
(*slot)->complete = complete;
if (completep)
*completep = complete;
timevar_pop (TV_IPA_VIRTUAL_CALL);
return nodes;
}
bool
add_decl_warning (const tree &key ATTRIBUTE_UNUSED, const decl_warn_count &value,
vec<const decl_warn_count*> *vec)
{
vec->safe_push (&value);
return true;
}
/* Dump target list TARGETS into FILE. */
static void
dump_targets (FILE *f, vec <cgraph_node *> targets)
{
unsigned int i;
for (i = 0; i < targets.length (); i++)
{
char *name = NULL;
if (in_lto_p)
name = cplus_demangle_v3 (targets[i]->asm_name (), 0);
fprintf (f, " %s/%i", name ? name : targets[i]->name (), targets[i]->order);
if (in_lto_p)
free (name);
if (!targets[i]->definition)
fprintf (f, " (no definition%s)",
<API key> (targets[i]->decl)
? " inline" : "");
}
fprintf (f, "\n");
}
/* Dump all possible targets of a polymorphic call. */
void
<API key> (FILE *f,
tree otr_type,
HOST_WIDE_INT otr_token,
const <API key> &ctx)
{
vec <cgraph_node *> targets;
bool final;
odr_type type = get_odr_type (TYPE_MAIN_VARIANT (otr_type), false);
unsigned int len;
if (!type)
return;
targets = <API key> (otr_type, otr_token,
ctx,
&final, NULL, false);
fprintf (f, " Targets of polymorphic call of type %i:", type->id);
print_generic_expr (f, type->type, TDF_SLIM);
fprintf (f, " token %i\n", (int)otr_token);
ctx.dump (f);
fprintf (f, " %s%s%s%s\n ",
final ? "This is a complete list." :
"This is partial list; extra targets may be defined in other units.",
ctx.<API key> ? " (base types included)" : "",
ctx.maybe_derived_type ? " (derived types included)" : "",
ctx.<API key> ? " (speculative derived types included)" : "");
len = targets.length ();
dump_targets (f, targets);
targets = <API key> (otr_type, otr_token,
ctx,
&final, NULL, true);
if (targets.length () != len)
{
fprintf (f, " Speculative targets:");
dump_targets (f, targets);
}
gcc_assert (targets.length () <= len);
fprintf (f, "\n");
}
/* Return true if N can be possibly target of a polymorphic call of
OTR_TYPE/OTR_TOKEN. */
bool
<API key> (tree otr_type,
HOST_WIDE_INT otr_token,
const <API key> &ctx,
struct cgraph_node *n)
{
vec <cgraph_node *> targets;
unsigned int i;
enum built_in_function fcode;
bool final;
if (TREE_CODE (TREE_TYPE (n->decl)) == FUNCTION_TYPE
&& ((fcode = DECL_FUNCTION_CODE (n->decl))
== <API key>
|| fcode == BUILT_IN_TRAP))
return true;
if (!odr_hash)
return true;
targets = <API key> (otr_type, otr_token, ctx, &final);
for (i = 0; i < targets.length (); i++)
if (n-><API key> (targets[i]))
return true;
/* At a moment we allow middle end to dig out new external declarations
as a targets of polymorphic calls. */
if (!final && !n->definition)
return true;
return false;
}
/* Return true if N can be possibly target of a polymorphic call of
OBJ_TYPE_REF expression REF in STMT. */
bool
<API key> (tree ref,
gimple stmt,
struct cgraph_node *n)
{
<API key> context (<API key>, ref, stmt);
tree call_fn = gimple_call_fn (stmt);
return <API key> (obj_type_ref_class (call_fn),
tree_to_uhwi
(OBJ_TYPE_REF_TOKEN (call_fn)),
context,
n);
}
/* After callgraph construction new external nodes may appear.
Add them into the graph. */
void
<API key> (void)
{
struct cgraph_node *n;
if (!odr_hash)
return;
<API key> ();
timevar_push (TV_IPA_INHERITANCE);
/* We reconstruct the graph starting from types of all methods seen in the
the unit. */
FOR_EACH_FUNCTION (n)
if (DECL_VIRTUAL_P (n->decl)
&& !n->definition
&& n->real_symbol_p ())
get_odr_type (<API key> (TREE_TYPE (n->decl)), true);
timevar_pop (TV_IPA_INHERITANCE);
}
/* Return true if N looks like likely target of a polymorphic call.
Rule out cxa_pure_virtual, noreturns, function declared cold and
other obvious cases. */
bool
likely_target_p (struct cgraph_node *n)
{
int flags;
/* cxa_pure_virtual and similar things are not likely. */
if (TREE_CODE (TREE_TYPE (n->decl)) != METHOD_TYPE)
return false;
flags = <API key> (n->decl);
if (flags & ECF_NORETURN)
return false;
if (lookup_attribute ("cold",
DECL_ATTRIBUTES (n->decl)))
return false;
if (n->frequency < <API key>)
return false;
/* If there are no live virtual tables referring the target,
the only way the target can be called is an instance coming from other
compilation unit; speculative devirtualization is built around an
assumption that won't happen. */
if (!<API key> (n))
return false;
return true;
}
/* Compare type warning records P1 and P2 and choose one with larger count;
helper for qsort. */
int
type_warning_cmp (const void *p1, const void *p2)
{
const odr_type_warn_count *t1 = (const odr_type_warn_count *)p1;
const odr_type_warn_count *t2 = (const odr_type_warn_count *)p2;
if (t1->dyn_count < t2->dyn_count)
return 1;
if (t1->dyn_count > t2->dyn_count)
return -1;
return t2->count - t1->count;
}
/* Compare decl warning records P1 and P2 and choose one with larger count;
helper for qsort. */
int
decl_warning_cmp (const void *p1, const void *p2)
{
const decl_warn_count *t1 = *(const decl_warn_count * const *)p1;
const decl_warn_count *t2 = *(const decl_warn_count * const *)p2;
if (t1->dyn_count < t2->dyn_count)
return 1;
if (t1->dyn_count > t2->dyn_count)
return -1;
return t2->count - t1->count;
}
/* Try to speculatively devirtualize call to OTR_TYPE with OTR_TOKEN with
context CTX. */
struct cgraph_node *
<API key> (tree otr_type, HOST_WIDE_INT otr_token,
<API key> ctx)
{
vec <cgraph_node *>targets
= <API key>
(otr_type, otr_token, ctx, NULL, NULL, true);
unsigned int i;
struct cgraph_node *likely_target = NULL;
for (i = 0; i < targets.length (); i++)
if (likely_target_p (targets[i]))
{
if (likely_target)
return NULL;
likely_target = targets[i];
}
if (!likely_target
||!likely_target->definition
|| DECL_EXTERNAL (likely_target->decl))
return NULL;
/* Don't use an implicitly-declared destructor (c++/58678). */
struct cgraph_node *non_thunk_target
= likely_target->function_symbol ();
if (DECL_ARTIFICIAL (non_thunk_target->decl))
return NULL;
if (likely_target->get_availability () <= AVAIL_INTERPOSABLE
&& likely_target->can_be_discarded_p ())
return NULL;
return likely_target;
}
/* The ipa-devirt pass.
When polymorphic call has only one likely target in the unit,
turn it into a speculative call. */
static unsigned int
ipa_devirt (void)
{
struct cgraph_node *n;
hash_set<void *> bad_call_targets;
struct cgraph_edge *e;
int npolymorphic = 0, nspeculated = 0, nconverted = 0, ncold = 0;
int nmultiple = 0, noverwritable = 0, ndevirtualized = 0, nnotdefined = 0;
int nwrong = 0, nok = 0, nexternal = 0, nartificial = 0;
int ndropped = 0;
if (!odr_types_ptr)
return 0;
if (dump_file)
<API key> (dump_file);
/* We can output -<API key> and -<API key> warnings.
This is implemented by setting up <API key> that are updated
by <API key>.
We need to clear cache in this case to trigger recomputation of all
entries. */
if (<API key> || <API key>)
{
<API key> = new (<API key>);
<API key>->type_warnings = vNULL;
<API key>->type_warnings.safe_grow_cleared (odr_types.length ());
<API key> ();
}
<API key> (n)
{
bool update = false;
if (!opt_for_fn (n->decl, flag_devirtualize))
continue;
if (dump_file && n->indirect_calls)
fprintf (dump_file, "\n\nProcesing function %s/%i\n",
n->name (), n->order);
for (e = n->indirect_calls; e; e = e->next_callee)
if (e->indirect_info->polymorphic)
{
struct cgraph_node *likely_target = NULL;
void *cache_token;
bool final;
if (<API key>)
<API key>->dyn_count = e->count;
vec <cgraph_node *>targets
= <API key>
(e, &final, &cache_token, true);
unsigned int i;
/* Trigger warnings by calculating non-speculative targets. */
if (<API key> || <API key>)
<API key> (e);
if (dump_file)
<API key>
(dump_file, e);
npolymorphic++;
/* See if the call can be devirtualized by means of ipa-prop's
polymorphic call context propagation. If not, we can just
forget about this call being polymorphic and avoid some heavy
lifting in <API key> that will otherwise try to
keep all possible targets alive until inlining and in the inliner
itself.
This may need to be revisited once we add further ways to use
the may edges, but it is a resonable thing to do right now. */
if ((e->indirect_info->param_index == -1
|| (!opt_for_fn (n->decl, <API key>)
&& e->indirect_info->vptr_changed))
&& !<API key>)
{
e->indirect_info->polymorphic = false;
ndropped++;
if (dump_file)
fprintf (dump_file, "Dropping polymorphic call info;"
" it can not be used by ipa-prop\n");
}
if (!opt_for_fn (n->decl, <API key>))
continue;
if (!e->maybe_hot_p ())
{
if (dump_file)
fprintf (dump_file, "Call is cold\n\n");
ncold++;
continue;
}
if (e->speculative)
{
if (dump_file)
fprintf (dump_file, "Call is already speculated\n\n");
nspeculated++;
/* When dumping see if we agree with speculation. */
if (!dump_file)
continue;
}
if (bad_call_targets.contains (cache_token))
{
if (dump_file)
fprintf (dump_file, "Target list is known to be useless\n\n");
nmultiple++;
continue;
}
for (i = 0; i < targets.length (); i++)
if (likely_target_p (targets[i]))
{
if (likely_target)
{
likely_target = NULL;
if (dump_file)
fprintf (dump_file, "More than one likely target\n\n");
nmultiple++;
break;
}
likely_target = targets[i];
}
if (!likely_target)
{
bad_call_targets.add (cache_token);
continue;
}
/* This is reached only when dumping; check if we agree or disagree
with the speculation. */
if (e->speculative)
{
struct cgraph_edge *e2;
struct ipa_ref *ref;
e-><API key> (e2, e, ref);
if (e2->callee-><API key> ()
== likely_target-><API key> ())
{
fprintf (dump_file, "We agree with speculation\n\n");
nok++;
}
else
{
fprintf (dump_file, "We disagree with speculation\n\n");
nwrong++;
}
continue;
}
if (!likely_target->definition)
{
if (dump_file)
fprintf (dump_file, "Target is not a definition\n\n");
nnotdefined++;
continue;
}
/* Do not introduce new references to external symbols. While we
can handle these just well, it is common for programs to
incorrectly with headers defining methods they are linked
with. */
if (DECL_EXTERNAL (likely_target->decl))
{
if (dump_file)
fprintf (dump_file, "Target is external\n\n");
nexternal++;
continue;
}
/* Don't use an implicitly-declared destructor (c++/58678). */
struct cgraph_node *non_thunk_target
= likely_target->function_symbol ();
if (DECL_ARTIFICIAL (non_thunk_target->decl))
{
if (dump_file)
fprintf (dump_file, "Target is artificial\n\n");
nartificial++;
continue;
}
if (likely_target->get_availability () <= AVAIL_INTERPOSABLE
&& likely_target->can_be_discarded_p ())
{
if (dump_file)
fprintf (dump_file, "Target is overwritable\n\n");
noverwritable++;
continue;
}
else if (dbg_cnt (devirt))
{
if (dump_enabled_p ())
{
location_t locus = <API key> (e->call_stmt);
dump_printf_loc (<API key>, locus,
"speculatively devirtualizing call in %s/%i to %s/%i\n",
n->name (), n->order,
likely_target->name (),
likely_target->order);
}
if (!likely_target->can_be_discarded_p ())
{
cgraph_node *alias;
alias = dyn_cast<cgraph_node *> (likely_target-><API key> ());
if (alias)
likely_target = alias;
}
nconverted++;
update = true;
e->make_speculative
(likely_target, e->count * 8 / 10, e->frequency * 8 / 10);
}
}
if (update)
<API key> (n);
}
if (<API key> || <API key>)
{
if (<API key>)
{
<API key>->type_warnings.qsort (type_warning_cmp);
for (unsigned int i = 0;
i < <API key>->type_warnings.length (); i++)
if (<API key>->type_warnings[i].count)
{
tree type = <API key>->type_warnings[i].type;
int count = <API key>->type_warnings[i].count;
long long dyn_count
= <API key>->type_warnings[i].dyn_count;
if (!dyn_count)
warning_n (<API key> (TYPE_NAME (type)),
<API key>, count,
"Declaring type %qD final "
"would enable devirtualization of %i call",
"Declaring type %qD final "
"would enable devirtualization of %i calls",
type,
count);
else
warning_n (<API key> (TYPE_NAME (type)),
<API key>, count,
"Declaring type %qD final "
"would enable devirtualization of %i call "
"executed %lli times",
"Declaring type %qD final "
"would enable devirtualization of %i calls "
"executed %lli times",
type,
count,
dyn_count);
}
}
if (<API key>)
{
vec<const decl_warn_count*> decl_warnings_vec = vNULL;
<API key>->decl_warnings.traverse
<vec<const decl_warn_count *> *, add_decl_warning> (&decl_warnings_vec);
decl_warnings_vec.qsort (decl_warning_cmp);
for (unsigned int i = 0; i < decl_warnings_vec.length (); i++)
{
tree decl = decl_warnings_vec[i]->decl;
int count = decl_warnings_vec[i]->count;
long long dyn_count = decl_warnings_vec[i]->dyn_count;
if (!dyn_count)
if (<API key> (decl))
warning_n (<API key> (decl),
<API key>, count,
"Declaring virtual destructor of %qD final "
"would enable devirtualization of %i call",
"Declaring virtual destructor of %qD final "
"would enable devirtualization of %i calls",
DECL_CONTEXT (decl), count);
else
warning_n (<API key> (decl),
<API key>, count,
"Declaring method %qD final "
"would enable devirtualization of %i call",
"Declaring method %qD final "
"would enable devirtualization of %i calls",
decl, count);
else if (<API key> (decl))
warning_n (<API key> (decl),
<API key>, count,
"Declaring virtual destructor of %qD final "
"would enable devirtualization of %i call "
"executed %lli times",
"Declaring virtual destructor of %qD final "
"would enable devirtualization of %i calls "
"executed %lli times",
DECL_CONTEXT (decl), count, dyn_count);
else
warning_n (<API key> (decl),
<API key>, count,
"Declaring method %qD final "
"would enable devirtualization of %i call "
"executed %lli times",
"Declaring method %qD final "
"would enable devirtualization of %i calls "
"executed %lli times",
decl, count, dyn_count);
}
}
delete (<API key>);
<API key> = 0;
}
if (dump_file)
fprintf (dump_file,
"%i polymorphic calls, %i devirtualized,"
" %i speculatively devirtualized, %i cold\n"
"%i have multiple targets, %i overwritable,"
" %i already speculated (%i agree, %i disagree),"
" %i external, %i not defined, %i artificial, %i infos dropped\n",
npolymorphic, ndevirtualized, nconverted, ncold,
nmultiple, noverwritable, nspeculated, nok, nwrong,
nexternal, nnotdefined, nartificial, ndropped);
return ndevirtualized || ndropped ? <API key> : 0;
}
namespace {
const pass_data <API key> =
{
IPA_PASS, /* type */
"devirt", /* name */
OPTGROUP_NONE, /* optinfo_flags */
TV_IPA_DEVIRT, /* tv_id */
0, /* properties_required */
0, /* properties_provided */
0, /* <API key> */
0, /* todo_flags_start */
( TODO_dump_symtab ), /* todo_flags_finish */
};
class pass_ipa_devirt : public ipa_opt_pass_d
{
public:
pass_ipa_devirt (gcc::context *ctxt)
: ipa_opt_pass_d (<API key>, ctxt,
NULL, /* generate_summary */
NULL, /* write_summary */
NULL, /* read_summary */
NULL, /* <API key> */
NULL, /* <API key> */
NULL, /* stmt_fixup */
0, /* <API key> */
NULL, /* function_transform */
NULL) /* variable_transform */
{}
/* opt_pass methods: */
virtual bool gate (function *)
{
/* In LTO, always run the IPA passes and decide on function basis if the
pass is enabled. */
if (in_lto_p)
return true;
return (flag_devirtualize
&& (<API key>
|| (<API key>
|| <API key>))
&& optimize);
}
virtual unsigned int execute (function *) { return ipa_devirt (); }
}; // class pass_ipa_devirt
} // anon namespace
ipa_opt_pass_d *
<API key> (gcc::context *ctxt)
{
return new pass_ipa_devirt (ctxt);
}
#include "gt-ipa-devirt.h" |
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.List;
import java.util.Properties;
import org.compiere.util.DB;
/**
* Shipment Material Allocation
*
* @author Jorg Janke
* @version $Id: MInOutLineMA.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class MInOutLineMA extends X_M_InOutLineMA
{
private static final long serialVersionUID = -<API key>;
/**
* Get Material Allocations for Line
* @param ctx context
* @param M_InOutLine_ID line
* @param trxName trx
* @return allocations
*/
public static MInOutLineMA[] get (Properties ctx, int M_InOutLine_ID, String trxName)
{
Query query = MTable.get(ctx, MInOutLineMA.Table_Name)
.createQuery(I_M_InOutLineMA.<API key>+"=?", trxName);
query.setParameters(M_InOutLine_ID);
List<MInOutLineMA> list = query.list();
MInOutLineMA[] retValue = new MInOutLineMA[list.size ()];
list.toArray (retValue);
return retValue;
} // get
/**
* Delete all Material Allocation for InOut
* @param M_InOut_ID shipment
* @param trxName transaction
* @return number of rows deleted or -1 for error
*/
public static int deleteInOutMA (int M_InOut_ID, String trxName)
{
String sql = "DELETE FROM M_InOutLineMA ma WHERE EXISTS "
+ "(SELECT * FROM M_InOutLine l WHERE l.M_InOutLine_ID=ma.M_InOutLine_ID"
+ " AND M_InOut_ID=" + M_InOut_ID + ")";
return DB.executeUpdate(sql, trxName);
} // deleteInOutMA
/**
* Delete all Material Allocation for InOutLine
* @param M_InOutLine_ID Shipment Line
* @param trxName transaction
* @return number of rows deleted or -1 for error
*/
public static int deleteInOutLineMA (int M_InOutLine_ID, String trxName)
{
String sql = "DELETE FROM M_InOutLineMA ma WHERE ma.M_InOutLine_ID=?";
return DB.executeUpdate(sql, M_InOutLine_ID, trxName);
} // deleteInOutLineMA
// /** Logger */
// private static CLogger s_log = CLogger.getCLogger (MInOutLineMA.class);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param M_InOutLineMA_ID ignored
* @param trxName trx
*/
public MInOutLineMA (Properties ctx, int M_InOutLineMA_ID, String trxName)
{
super (ctx, M_InOutLineMA_ID, trxName);
if (M_InOutLineMA_ID != 0)
throw new <API key>("Multi-Key");
} // MInOutLineMA
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MInOutLineMA (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MInOutLineMA
/**
* Parent Constructor
* @param parent parent
* @param <API key> asi
* @param MovementQty qty
*/
public MInOutLineMA (MInOutLine parent, int <API key>, BigDecimal MovementQty)
{
this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent);
setM_InOutLine_ID(parent.getM_InOutLine_ID());
<API key>(<API key>);
setMovementQty(MovementQty);
} // MInOutLineMA
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MInOutLineMA[");
sb.append("M_InOutLine_ID=").append(getM_InOutLine_ID())
.append(",<API key>=").append(<API key>())
.append(", Qty=").append(getMovementQty())
.append ("]");
return sb.toString ();
} // toString
} // MInOutLineMA |
#ifdef PAIR_CLASS
PairStyle(lj/charmm/coul/msm,PairLJCharmmCoulMSM)
#else
#ifndef <API key>
#define <API key>
#include "<API key>.h"
namespace LAMMPS_NS {
class PairLJCharmmCoulMSM : public <API key> {
public:
PairLJCharmmCoulMSM(class LAMMPS *);
virtual ~PairLJCharmmCoulMSM(){};
virtual void compute(int, int);
virtual double single(int, int, int, int, double, double, double, double &);
virtual void compute_outer(int, int);
virtual void *extract(const char *, int &);
};
}
#endif
#endif |
#include "conf.h"
int *video_quality = &conf.video_quality;
int *video_mode = &conf.video_mode;
long def_table1[9]={0x2000,0x38D,0x788,0x5800,0x9C5,0x14B8,0x10000,0x1C6A,0x3C45};
long def_table2[9]={0x1CCD,-0x2E1,-0x579,0x4F33,-0x7EB,-0xF0C,0xE666,-0x170A,-0x2BC6};
long table1[9], table2[9];
void change_video_tables(int a, int b){
int i;
for (i=0;i<9;i++) {table1[i]=(def_table1[i]*a)/b; table2[i]=(def_table2[i]*a)/b;}
}
long <API key>[]={0x60, 0x5D, 0x5A, 0x57, 0x54, 0x51, 0x4D, 0x48, 0x42, 0x3B, 0x32, 0x29, 0x22, 0x1D, 0x17, 0x14, 0x10, 0xE, 0xB, 9, 7, 6, 5, 4, 3, 2, 1};
void __attribute__((naked,noinline)) movie_record_task(){
asm volatile(
"STMFD SP!, {R4,LR}\n"
"SUB SP, SP,
"MOV R4, SP\n"
"B loc_FFD3B4C8\n"
"loc_FFD3B424:\n"
"LDR R3, =0x6E460\n"
"LDR R2, [R3]\n"
"CMP R2,
"BNE loc_FFD3B4B4\n"
"SUB R3, R12,
"CMP R3,
"LDRLS PC, [PC,R3,LSL
"B loc_FFD3B4B4\n"
".long loc_FFD3B474\n"
".long loc_FFD3B48C\n"
".long loc_FFD3B494\n"
".long loc_FFD3B49C\n"
".long loc_FFD3B47C\n"
".long loc_FFD3B4A4\n"
".long loc_FFD3B484\n"
".long loc_FFD3B4B4\n"
".long loc_FFD3B4AC\n"
".long loc_FFD3B46C\n"
"loc_FFD3B46C:\n"
"BL sub_FFD3B560\n"
"B loc_FFD3B4B0\n"
"loc_FFD3B474:\n"
"BL unlock_optical_zoom\n"
"BL sub_FFD3B714\n"
"B loc_FFD3B4B0\n"
"loc_FFD3B47C:\n"
"BL sub_FFD3BAE8_my\n"
"B loc_FFD3B4B0\n"
"loc_FFD3B484:\n"
"BL sub_FFD3BF1C\n"
"B loc_FFD3B4B0\n"
"loc_FFD3B48C:\n"
"BL sub_FFD3BD80\n"
"B loc_FFD3B4B0\n"
"loc_FFD3B494:\n"
"BL sub_FFD3C08C\n"
"B loc_FFD3B4B0\n"
"loc_FFD3B49C:\n"
"BL sub_FFD3C250\n"
"B loc_FFD3B4B0\n"
"loc_FFD3B4A4:\n"
"BL sub_FFD3BFA4\n"
"B loc_FFD3B4B0\n"
"loc_FFD3B4AC:\n"
"BL sub_FFD3BDD0\n"
"loc_FFD3B4B0:\n"
"LDR R1, [SP]\n"
"loc_FFD3B4B4:\n"
"LDR R3, =0x6E394\n"
"MOV R2,
"STR R2, [R1]\n"
"LDR R0, [R3]\n"
"BL sub_FFC104D8\n"
"loc_FFD3B4C8:\n"
"LDR R3, =0x6E390\n"
"MOV R1, R4\n"
"LDR R0, [R3]\n"
"MOV R2,
"BL sub_FFC100C0\n"
"LDR R0, [SP]\n"
"LDR R12, [R0]\n"
"CMP R12, #0xC\n"
"MOV R1, R0\n"
"BNE loc_FFD3B424\n"
"LDR R3, =0x6E38C\n"
"LDR R0, [R3]\n"
"BL sub_FFC10E54\n"
"BL sub_FFC1161C\n"
"ADD SP, SP,
"LDMFD SP!, {R4,PC}\n"
);
}
void __attribute__((naked,noinline)) sub_FFD3BAE8_my(){
asm volatile(
"STMFD SP!, {R4-R11,LR}\n"
"LDR R5, =0x6E47C\n"
"SUB SP, SP, #0x34\n"
"LDR R3, [R5]\n"
"CMP R3,
"MOV R4, R0\n"
"MOVEQ R3,
"STREQ R3, [R5]\n"
"LDR R3, =0x6E52C\n"
"MOV LR, PC\n"
"LDR PC, [R3]\n"
"LDR R2, [R5]\n"
"CMP R2,
"BNE loc_FFD3BCAC\n"
"ADD R0, SP, #0x30\n"
"ADD R1, SP, #0x2C\n"
"ADD R2, SP, #0x28\n"
"ADD R3, SP, #0x24\n"
"BL sub_FFD3D1BC_my\n"
"CMP R0,
"BNE loc_FFD3BB64\n"
"LDR R3, =0x6E468\n"
"LDR R2, [R3]\n"
"CMP R2,
"BNE loc_FFD3BB78\n"
"LDR R2, =0x6E4C0\n"
"LDR R1, =0x6E494\n"
"LDR R12, [R2]\n"
"LDR R3, [R1]\n"
"CMP R12, R3\n"
"BCC loc_FFD3BB78\n"
"loc_FFD3BB64:\n"
"BL sub_FFD3BCF8\n"
"BL sub_FFD3BEF8\n"
"MOV R3,
"STR R3, [R5]\n"
"B loc_FFD3BCAC\n"
"loc_FFD3BB78:\n"
"LDR R12, =0x6E4C8\n"
"LDR R11, =0x6E4D4\n"
"LDMIB R4, {R0-R2}\n"
"LDR R10, [R12]\n"
"LDR R7, [R11]\n"
"LDR R4, [SP,#0x2C]\n"
"LDR R5, [SP,#0x28]\n"
"LDR R6, [SP,#0x24]\n"
"LDR R8, =0x6E46C\n"
"LDR R3, [SP,#0x30]\n"
"ADD R12, SP, #0x20\n"
"ADD LR, SP, #0x1C\n"
"MOV R9,
"STMEA SP, {R4-R6,R12}\n"
"STR R10, [SP,#0x10]\n"
"STR R7, [SP,#0x14]\n"
"STR LR, [SP,#0x18]\n"
"STR R9, [R8]\n"
"BL sub_FFC84328\n"
"LDR R3, =0x6E384\n"
"MOV R1, #0x3E8\n"
"LDR R0, [R3]\n"
"BL sub_FFC10C6C\n"
"CMP R0,
"BNE loc_FFD3BBEC\n"
"BL sub_FFD3D9CC\n"
"LDR R3, =0x6E47C\n"
"LDR R0, =0xFFD3BAD0\n"
"B loc_FFD3BC04\n"
"loc_FFD3BBEC:\n"
"LDR R5, [SP,#0x1C]\n"
"CMP R5,
"BEQ loc_FFD3BC10\n"
"BL sub_FFD3D9CC\n"
"LDR R3, =0x6E47C\n"
"LDR R0, =0xFFD3BADC\n"
"loc_FFD3BC04:\n"
"STR R9, [R3]\n"
"BL sub_FFD50948\n"
"B loc_FFD3BCAC\n"
"loc_FFD3BC10:\n"
"BL sub_FFC84494\n"
"LDR R0, [SP,#0x30]\n"
"LDR R1, [SP,#0x20]\n"
"BL sub_FFD3D6F0\n"
"LDR R4, =0x6E4C0\n"
"LDR R3, [R4]\n"
"ADD R3, R3,
"LDR R0, [SP,#0x20]\n"
"MOV R1, R11\n"
"STR R3, [R4]\n"
"MOV R2, R5\n"
"BL sub_FFD3C5AC_my\n"
"LDR R3, =0x6E4E0\n"
"LDR R1, [R4]\n"
"LDR R2, [R3]\n"
"LDR R12, =0x6E4DC\n"
"MUL R0, R2, R1\n"
"LDR R1, [R12]\n"
"BL sub_FFEDC0F0\n"
"LDR R7, =0x6E4D8\n"
"LDR R3, [R7]\n"
"MOV R4, R0\n"
"CMP R3, R4\n"
"BNE loc_FFD3BC84\n"
"LDR R6, =0x6E470\n"
"LDR R3, [R6]\n"
"CMP R3,
"BNE loc_FFD3BCA0\n"
"B loc_FFD3BC88\n"
"loc_FFD3BC84:\n"
"LDR R6, =0x6E470\n"
"loc_FFD3BC88:\n"
"LDR R3, =0x6E510\n"
"MOV R0, R4\n"
"MOV LR, PC\n"
"LDR PC, [R3]\n"
"STR R5, [R6]\n"
"STR R4, [R7]\n"
"loc_FFD3BCA0:\n"
"LDR R2, =0x6E46C\n"
"MOV R3,
"STR R3, [R2]\n"
"loc_FFD3BCAC:\n"
"ADD SP, SP, #0x34\n"
"LDMFD SP!, {R4-R11,PC}\n"
);
}
void __attribute__((naked,noinline)) sub_FFD3D1BC_my(){
asm volatile(
"STMFD SP!, {R4-R11,LR}\n"
"LDR R5, =0x6E7D4\n"
"SUB SP, SP, #0x14\n"
"LDR LR, [R5]\n"
"LDR R12, =0x6E7EC\n"
"ADD LR, LR,
"LDR R4, [R12]\n"
"STR LR, [R5]\n"
"LDR R12, =0x6E86C\n"
"STR R0, [SP,#0x10]\n"
"STR R1, [SP,#0xC]\n"
"STR R2, [SP,
"STR R3, [SP,
"CMP LR, R4\n"
"LDR R11, [R12]\n"
"MOVHI R0, #0x80000001\n"
"BHI loc_FFD3D6A4\n"
"LDR R3, =0x6E850\n"
"MOV R0, LR\n"
"LDR R1, [R3]\n"
"BL sub_FFEDC780\n"
"CMP R0,
"BNE loc_FFD3D3DC\n"
"LDR R0, =0x6E874\n"
"LDR R1, =0x6E7C0\n"
"LDR R3, [R0]\n"
"LDR R2, [R1]\n"
"CMP R3, R2\n"
"LDREQ R3, =0x6E870\n"
"LDREQ R5, [R3]\n"
"MOVNE R5, R2\n"
"LDR R3, =0x6E7D4\n"
"LDR R2, =0x6E850\n"
"LDR R0, [R3]\n"
"LDR R1, [R2]\n"
"BL sub_FFEDC0F0\n"
"LDR R3, =0x6E7C8\n"
"ADD R0, R0,
"AND R0, R0,
"STR R5, [R3,R0,LSL
"LDR R3, =0x6E7BC\n"
"LDR R2, [R3]\n"
"CMP R5, R2\n"
"BHI loc_FFD3D28C\n"
"LDR R4, =0x6E80C\n"
"LDR R3, [R4]\n"
"ADD R3, R5, R3\n"
"ADD R3, R3,
"CMP R2, R3\n"
"BCS loc_FFD3D290\n"
"loc_FFD3D284:\n"
"MOV R0, #0x80000003\n"
"B loc_FFD3D6A4\n"
"loc_FFD3D28C:\n"
"LDR R4, =0x6E80C\n"
"loc_FFD3D290:\n"
"LDR R3, [R4]\n"
"LDR R2, =0x6E874\n"
"ADD R1, R5, R3\n"
"LDR R3, [R2]\n"
"ADD R2, R1,
"CMP R2, R3\n"
"BLS loc_FFD3D2DC\n"
"LDR R2, =0x6E870\n"
"LDR R0, =0x6E7BC\n"
"RSB R3, R3, R1\n"
"LDR R1, [R2]\n"
"ADD R3, R3,
"LDR R2, [R0]\n"
"ADD R1, R1, R3\n"
"CMP R2, R1\n"
"BCC loc_FFD3D284\n"
"LDR R3, =0x6E7C0\n"
"STR R1, [R3]\n"
"B loc_FFD3D2E4\n"
"loc_FFD3D2DC:\n"
"LDR R3, =0x6E7C0\n"
"STR R2, [R3]\n"
"loc_FFD3D2E4:\n"
"LDR R3, [R4]\n"
"LDR R12, =0x6E820\n"
"ADD R3, R3, #0x18\n"
"LDR R2, [R12,
"MOV R0, R3\n"
"MOV R1,
"CMP R1, R2\n"
"BHI loc_FFD3D528\n"
"BNE loc_FFD3D314\n"
"LDR R3, [R12]\n"
"CMP R0, R3\n"
"BHI loc_FFD3D528\n"
"loc_FFD3D314:\n"
"LDR R4, [R4]\n"
"LDR LR, =0x6E828\n"
"STR R4, [SP]\n"
"LDR R12, =0x6E820\n"
"LDR R3, =0x6E7D4\n"
"LDMIA LR, {R7,R8}\n"
"LDMIA R12, {R5,R6}\n"
"LDR R10, [R3]\n"
"LDR R2, =0x6E850\n"
"MOV R3, R4\n"
"MOV R4,
"ADDS R7, R7, R3\n"
"ADC R8, R8, R4\n"
"LDR R9, [R2]\n"
"SUBS R5, R5, R3\n"
"SBC R6, R6, R4\n"
"MVN R2,
"MVN R1, #0x17\n"
"ADDS R5, R5, R1\n"
"MOV R4,
"MOV R3, #0x18\n"
"ADC R6, R6, R2\n"
"ADDS R7, R7, R3\n"
"ADC R8, R8, R4\n"
"STMIA R12, {R5,R6}\n"
"SUB R0, R10,
"MOV R1, R9\n"
"STMIA LR, {R7,R8}\n"
"BL sub_FFEDC0F0\n"
"CMP R10,
"MLA R0, R9, R0, R0\n"
"BEQ loc_FFD3D3DC\n"
"SUB R3, R0,
"MOV R3, R3,LSL
"ADD R4, R11, #0x10\n"
"ADD R5, R11, #0x14\n"
"LDR R1, [R5,R3]\n"
"LDR R2, [R4,R3]\n"
"LDR LR, =0x62773130\n"
"ADD R2, R2, R1\n"
"MOV R3, R0,LSL
"ADD R2, R2,
"MOV R0,
"ADD R12, R11, #0xC\n"
"ADD R1, R11,
"STR LR, [R1,R3]\n"
"STR R0, [R12,R3]\n"
"STR R2, [R4,R3]\n"
"LDR R0, [SP]\n"
"STR R0, [R5,R3]\n"
"loc_FFD3D3DC:\n"
"LDR R2, =0x6E7C0\n"
"LDR R3, =0x6E874\n"
"LDR R1, [R2]\n"
"LDR R0, [R3]\n"
"ADD R3, R1,
"CMP R3, R0\n"
"BLS loc_FFD3D418\n"
"LDR R2, =0x6E870\n"
"LDR R3, [R2]\n"
"ADD R3, R3, R1\n"
"RSB R3, R0, R3\n"
"LDR R0, [SP,#0x10]\n"
"ADD R3, R3,
"STR R3, [R0]\n"
"B loc_FFD3D424\n"
"loc_FFD3D418:\n"
"ADD R3, R1,
"LDR R1, [SP,#0x10]\n"
"STR R3, [R1]\n"
"loc_FFD3D424:\n"
"LDR R2, [SP,#0x10]\n"
"LDR R1, =0x6E81C\n"
"LDR R3, =0x6E874\n"
"LDR R12, [R2]\n"
"LDR R2, [R1]\n"
"LDR R0, [R3]\n"
"ADD R3, R12, R2\n"
"CMP R3, R0\n"
"BLS loc_FFD3D478\n"
"LDR R2, [SP,#0xC]\n"
"RSB R0, R12, R0\n"
"STR R0, [R2]\n"
"LDR R2, =0x6E870\n"
"LDR R3, [R1]\n"
"LDR R1, [R2]\n"
"RSB R3, R0, R3\n"
"LDR R0, [SP,
"STR R1, [R0]\n"
"LDR R1, [SP,
"STR R3, [R1]\n"
"B loc_FFD3D494\n"
"loc_FFD3D478:\n"
"LDR R0, [SP,#0xC]\n"
"STR R2, [R0]\n"
"LDR R1, [SP,
"MOV R3,
"STR R3, [R1]\n"
"LDR R2, [SP,
"STR R3, [R2]\n"
"loc_FFD3D494:\n"
"LDR R0, =0x6E7C0\n"
"LDR R1, =0x6E7BC\n"
"LDR R3, [R0]\n"
"LDR R2, [R1]\n"
"CMP R3, R2\n"
"BHI loc_FFD3D4C0\n"
"LDR R0, [SP,#0xC]\n"
"LDR R3, [R0]\n"
"ADD R3, R12, R3\n"
"CMP R2, R3\n"
"BCC loc_FFD3D284\n"
"loc_FFD3D4C0:\n"
"LDR R1, [SP,
"LDR R2, [R1]\n"
"CMP R2,
"BEQ loc_FFD3D4F4\n"
"LDR R3, =0x6E7BC\n"
"LDR R1, [R3]\n"
"CMP R2, R1\n"
"BHI loc_FFD3D4F4\n"
"LDR R0, [SP,
"LDR R3, [R0]\n"
"ADD R3, R2, R3\n"
"CMP R1, R3\n"
"BCC loc_FFD3D284\n"
"loc_FFD3D4F4:\n"
"LDR R3, =0x6E81C\n"
"LDR R0, =0x6E820\n"
"LDR R2, [R3]\n"
"LDR R3, [R0,
"ADD R2, R2, #0x18\n"
"MOV R1, R2\n"
"MOV R2,
"CMP R2, R3\n"
"BHI loc_FFD3D528\n"
"BNE loc_FFD3D530\n"
"LDR R3, [R0]\n"
"CMP R1, R3\n"
"BLS loc_FFD3D530\n"
"loc_FFD3D528:\n"
"MOV R0, #0x80000005\n"
"B loc_FFD3D6A4\n"
"loc_FFD3D530:\n"
"LDR R1, =0x6E804\n"
"LDR R0, =0x6E850\n"
"LDR R3, [R1]\n"
"LDR R2, [R0]\n"
"ADD R3, R3, R2,LSL
"ADD R3, R3, R3,LSL
"LDR R12, =0x6E820\n"
"MOV R3, R3,LSL
"ADD R3, R3, #0xA0\n"
"LDR R2, [R12,
"MOV R0, R3\n"
"MOV R1,
"CMP R1, R2\n"
"BHI loc_FFD3D578\n"
"BNE loc_FFD3D59C\n"
"LDR R3, [R12]\n"
"CMP R0, R3\n"
"BLS loc_FFD3D59C\n"
"loc_FFD3D578:\n"
"LDR R4, =0x6E838\n"
"LDR R1, [R4]\n"
"CMP R1,
"BNE loc_FFD3D59C\n"
"MOV R0, #0x3140\n"
"ADD R0, R0,
"BL sub_FFD54E78\n"
"MOV R3,
"STR R3, [R4]\n"
"loc_FFD3D59C:\n"
"LDR R1, =0x6E804\n"
"LDR R0, =0x6E850\n"
"LDR R2, [R1]\n"
"LDR R3, [R0]\n"
"LDR R0, =0x6E828\n"
"ADD R2, R2, R3,LSL
"MVN R3, #0x9F\n"
"ADD R2, R2, R2,LSL
"ADD R3, R3, #0x40000000\n"
"SUB R3, R3, R2,LSL
"LDR R1, [R0,
"MOV R4, R3\n"
"MOV R5,
"CMP R1, R5\n"
"BHI loc_FFD3D5E8\n"
"BNE loc_FFD3D60C\n"
"LDR R3, [R0]\n"
"CMP R3, R4\n"
"BLS loc_FFD3D60C\n"
"loc_FFD3D5E8:\n"
"LDR R4, =0x6E838\n"
"LDR R1, [R4]\n"
"CMP R1,
"BNE loc_FFD3D60C\n"
"MOV R0, #0x3140\n"
"ADD R0, R0,
"BL sub_FFD54E78\n"
"MOV R3,
"STR R3, [R4]\n"
"loc_FFD3D60C:\n"
"LDR R3, =0x6E850\n"
"LDR R0, =0x6E7EC\n"
"LDR R2, [R3]\n"
"LDR R12, =0x6E7D4\n"
"LDR R1, [R0]\n"
"ADD R3, R2, R2,LSL
"ADD R2, R2, R3,LSL
"LDR R0, [R12]\n"
"RSB R1, R2, R1\n"
"CMP R0, R1\n"
"BLS loc_FFD3D65C\n"
"LDR R4, =0x6E838\n"
"LDR R1, [R4]\n"
"CMP R1,
"BNE loc_FFD3D65C\n"
"MOV R0, #0x3140\n"
"ADD R0, R0,
"BL sub_FFD54E78\n"
"MOV R3,
"STR R3, [R4]\n"
"loc_FFD3D65C:\n"
"LDR R3, =0x6E828\n"
"LDR R12, =0x6E81C\n"
"LDMIA R3, {R1,R2}\n"
"LDR R0, [R12]\n"
"MOV R4,
"MOV R3, #0x18\n"
"ADDS R1, R1, R0\n"
"ADC R2, R2,
"ADDS R1, R1, R3\n"
"ADC R2, R2, R4\n"
"CMP R2,
"BHI loc_FFD3D698\n"
"BNE loc_FFD3D6A0\n"
"CMP R1, #0x40000000\n"
// "BLS loc_FFD3D6A0\n" // -
"B loc_FFD3D6A0\n"
"loc_FFD3D698:\n"
"MOV R0, #0x80000007\n"
"B loc_FFD3D6A4\n"
"loc_FFD3D6A0:\n"
"MOV R0,
"loc_FFD3D6A4:\n"
"ADD SP, SP, #0x14\n"
"LDMFD SP!, {R4-R11,PC}\n"
);
}
void __attribute__((naked,noinline)) sub_FFD3C5AC_my(){
asm volatile(
"CMP R2,
"STMFD SP!, {R4-R7,LR}\n"
"MOV R7, R0\n"
"MOV R6, R1\n"
"MOVEQ R3, #0x79\n"
"STREQ R3, [R6]\n"
"LDMEQFD SP!, {R4-R7,PC}\n"
"LDR R12, =0x6E538\n"
"LDR R0, [R12]\n"
"LDR R3, =0x6E540\n"
"CMP R0,
"LDR R1, [R3]\n"
"BEQ loc_FFD3C5F4\n"
"LDR R2, =0x6E544\n"
"LDR R3, [R2]\n"
"CMP R3,
"BNE loc_FFD3C608\n"
"B loc_FFD3C5F8\n"
"loc_FFD3C5F4:\n"
"LDR R2, =0x6E544\n"
"loc_FFD3C5F8:\n"
"MOV R3,
"STR R3, [R2]\n"
"STR R7, [R12]\n"
"B loc_FFD3C6C0\n"
"loc_FFD3C608:\n"
"LDR R2, =0x6E53C\n"
"LDR R3, [R2]\n"
"LDR R5, =table1\n" //+ 0xFFD3C41C
"ADD R3, R3, R3,LSL
"MOV LR, R3,LSL
"LDR R2, [R5,LR]\n"
"LDR R4, =table2\n" //+ 0xFFD3C440
"RSB R12, R2, R0\n"
"LDR R3, [R4,LR]\n"
"CMP R12,
"RSB R0, R3, R0\n"
"BLE loc_FFD3C66C\n"
"ADD R3, R5,
"LDR R2, [R3,LR]\n"
"CMP R2, R12\n"
"ADDGE R1, R1,
"BGE loc_FFD3C660\n"
"ADD R3, R5,
"LDR R2, [R3,LR]\n"
"CMP R2, R12\n"
"ADDGE R1, R1,
"ADDLT R1, R1,
"loc_FFD3C660:\n"
// "CMP R1, #0xE\n" // -
// "MOVGE R1, #0xE\n" // -
"CMP R1, #0x1A\n" // +
"MOVGE R1, #0x1A\n" // +
"B loc_FFD3C6A4\n"
"loc_FFD3C66C:\n"
"CMP R0,
"BGE loc_FFD3C6A4\n"
"ADD R3, R4,
"LDR R2, [R3,LR]\n"
"CMP R2, R0\n"
"SUBLE R1, R1,
"BLE loc_FFD3C69C\n"
"ADD R3, R4,
"LDR R2, [R3,LR]\n"
"CMP R2, R0\n"
"SUBLE R1, R1,
"SUBGT R1, R1,
"loc_FFD3C69C:\n"
"CMP R1,
"MOVLT R1,
"loc_FFD3C6A4:\n"
"LDR R0, =0x6E540\n"
"LDR R3, [R0]\n"
"CMP R1, R3\n"
"LDRNE R2, =0x6E544\n"
"MOVNE R3,
"STRNE R1, [R0]\n"
"STRNE R3, [R2]\n"
"loc_FFD3C6C0:\n"
"LDR R3, =0x6E540\n"
// "LDR R1, =0x6088\n" // -
"LDR R1, =video_mode\n"
"LDR R0, [R3]\n"
"LDR R2, =<API key>\n" // + 0xFFD3C3E0
"LDR R12, [R1]\n"
"LDR R12, [R12]\n"
"LDR LR, [R2,R0,LSL
"LDR R3, =0x6E538\n"
"CMP R12,
"STR R7, [R3]\n"
"STR LR, [R6]\n"
// "MOVEQ R3, #0xB\n" // -
"LDREQ R3, =video_quality\n"
"LDREQ R3, [R3]\n"
"LDREQ R3, [R3]\n"
"STREQ R3, [R6]\n"
"BL mute_on_zoom\n"
"LDMFD SP!, {R4-R7,PC}\n"
);
} |
<?php
/**
* base class to choose the language
*
* @since 1.2
*/
abstract class PLL_Choose_Lang {
public $links_model, $model, $options;
public $curlang;
/**
* constructor
*
* @since 1.2
*
* @param object $polylang
*/
public function __construct( &$polylang ) {
$this->links_model = &$polylang->links_model;
$this->model = &$polylang->model;
$this->options = &$polylang->options;
$this->curlang = &$polylang->curlang;
}
/**
* sets the language for ajax requests
* and setup actions
* any child class must call this method if it overrides it
*
* @since 1.8
*/
public function init() {
if ( PLL_AJAX_ON_FRONT || false === stripos( $_SERVER['SCRIPT_FILENAME'], 'index.php' ) ) {
$this->set_language( empty( $_REQUEST['lang'] ) ? $this-><API key>() : $this->model->get_language( $_REQUEST['lang'] ) );
}
add_action( 'pre_comment_on_post', array( &$this, 'pre_comment_on_post' ) ); // sets the language of comment
add_action( 'parse_query', array( &$this, 'parse_main_query' ), 2 ); // sets the language in special cases
}
/**
* writes language cookie
* loads user defined translations
* fires the action '<API key>'
*
* @since 1.2
*
* @param object $curlang current language
*/
protected function set_language( $curlang ) {
// don't set the language a second time
if ( isset( $this->curlang ) ) {
return;
}
// final check in case $curlang has an unexpected value
$this->curlang = ( $curlang instanceof PLL_Language ) ? $curlang : $this->model->get_language( $this->options['default_lang'] );
$this->maybe_setcookie();
$GLOBALS['text_direction'] = $this->curlang->is_rtl ? 'rtl' : 'ltr';
/**
* Fires when the current language is defined
*
* @since 0.9.5
*
* @param string $slug current language code
* @param object $curlang current language object
*/
do_action( '<API key>', $this->curlang->slug, $this->curlang );
}
/**
* set a cookie to remember the language.
* possibility to set PLL_COOKIE to false will disable cookie although it will break some functionalities
*
* @since 1.5
*/
protected function maybe_setcookie() {
// check headers have not been sent to avoid ugly error
// cookie domain must be set to false for localhost ( default value for COOKIE_DOMAIN ) thanks to Stephen Harris.
if ( ! headers_sent() && PLL_COOKIE !== false && ( ! isset( $_COOKIE[ PLL_COOKIE ] ) || $_COOKIE[ PLL_COOKIE ] != $this->curlang->slug ) ) {
/**
* Filter the Polylang cookie duration
*
* @since 1.8
*
* @param int $duration cookie duration in seconds
*/
$expiration = apply_filters( '<API key>', YEAR_IN_SECONDS );
setcookie(
PLL_COOKIE,
$this->curlang->slug,
time() + $expiration,
COOKIEPATH,
2 == $this->options['force_lang'] ? parse_url( $this->links_model->home, PHP_URL_HOST ) : COOKIE_DOMAIN
);
}
}
public function <API key>() {
$accept_langs = array();
if ( isset( $_SERVER['<API key>'] ) ) {
// break up string into pieces ( languages and q factors )
preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*( 1|0\.[0-9]+))?/i', $_SERVER['<API key>'], $lang_parse );
$k = $lang_parse[1];
$v = $lang_parse[4];
if ( $n = count( $k ) ) {
// set default to 1 for any without q factor
foreach ( $v as $key => $val ) {
if ( '' === $val ) {
$v[ $key ] = 1;
}
}
// bubble sort ( need a stable sort for Android, so can't use a PHP sort function )
if ( $n > 1 ) {
for ( $i = 2; $i <= $n; $i++ ) {
for ( $j = 0; $j <= $n - 2; $j++ ) {
if ( $v[ $j ] < $v[ $j + 1 ] ) {
// swap values
$temp = $v[ $j ];
$v[ $j ] = $v[ $j + 1 ];
$v[ $j + 1 ] = $temp;
//swap keys
$temp = $k[ $j ];
$k[ $j ] = $k[ $j + 1 ];
$k[ $j + 1 ] = $temp;
}
}
}
}
$accept_langs = array_combine( $k,$v );
}
}
// looks through sorted list and use first one that matches our language list
$listlanguages = $this->model->get_languages_list( array( 'hide_empty' => true ) ); // hides languages with no post
foreach ( array_keys( $accept_langs ) as $accept_lang ) {
// first loop to match the exact locale
foreach ( $listlanguages as $language ) {
if ( 0 === strcasecmp( $accept_lang, $language->get_locale( 'display' ) ) ) {
return $language->slug;
}
}
// second loop to match the language set
foreach ( $listlanguages as $language ) {
if ( 0 === stripos( $accept_lang, $language->slug ) || 0 === stripos( $language->get_locale( 'display' ), $accept_lang ) ) {
return $language->slug;
}
}
}
return false;
}
/**
* returns the language according to browser preference or the default language
*
* @since 0.1
*
* @return object browser preferred language or default language
*/
public function <API key>() {
// check first if the user was already browsing this site
if ( isset( $_COOKIE[ PLL_COOKIE ] ) ) {
return $this->model->get_language( $_COOKIE[ PLL_COOKIE ] );
}
/**
* Filter the visitor's preferred language (normally set first by cookie
* if this is not the first visit, then by the browser preferences).
* If no preferred language has been found or set by this filter,
* Polylang fallbacks to the default language
*
* @since 1.0
*
* @param string $language preferred language code
*/
$slug = apply_filters( '<API key>', $this->options['browser'] ? $this-><API key>() : false );
// return default if there is no preferences in the browser or preferences does not match our languages or it is requested not to use the browser preference
return ( $lang = $this->model->get_language( $slug ) ) ? $lang : $this->model->get_language( $this->options['default_lang'] );
}
/**
* sets the language when home page is resquested
*
* @since 1.2
*/
protected function home_language() {
// test referer in case PLL_COOKIE is set to false
$language = $this->options['hide_default'] && ( ( isset( $_SERVER['HTTP_REFERER'] ) && in_array( parse_url( $_SERVER['HTTP_REFERER'], PHP_URL_HOST ), $this->links_model->get_hosts() ) ) || ! $this->options['browser'] ) ?
$this->model->get_language( $this->options['default_lang'] ) :
$this-><API key>(); // sets the language according to browser preference or default language
$this->set_language( $language );
}
/**
* to call when the home page has been requested
* make sure to call this after 'setup_theme' has been fired as we need $wp_query
* performs a redirection to the home page in the current language if needed
*
* @since 0.9
*/
public function home_requested() {
// we are already on the right page
if ( $this->options['default_lang'] == $this->curlang->slug && $this->options['hide_default'] ) {
$this->set_lang_query_var( $GLOBALS['wp_query'], $this->curlang );
/**
* Fires when the site root page is requested
*
* @since 1.8
*/
do_action( 'pll_home_requested' );
}
// redirect to the home page in the right language
// test to avoid crash if get_home_url returns something wrong
// don't redirect if $_POST is not empty as it could break other plugins
// don't forget the query string which may be added by plugins
elseif ( is_string( $redirect = $this->curlang->home_url ) && empty( $_POST ) ) {
$redirect = empty( $_SERVER['QUERY_STRING'] ) ? $redirect : $redirect . ( $this->links_model->using_permalinks ? '?' : '&' ) . $_SERVER['QUERY_STRING'];
/**
* When a visitor reaches the site home, Polylang redirects to the home page in the correct language.
* This filter allows plugins to modify the redirected url or prevent this redirection
*
* @since 1.1.1
*
* @param string $redirect the url the visitor will be redirected to
*/
if ( $redirect = apply_filters( 'pll_redirect_home', $redirect ) ) {
wp_redirect( $redirect );
exit;
}
}
}
/**
* set the language when posting a comment
*
* @since 0.8.4
*
* @param int $post_id the post beeing commented
*/
public function pre_comment_on_post( $post_id ) {
$this->set_language( $this->model->post->get_language( $post_id ) );
}
/**
* modifies some main query vars for home page and page for posts
* to enable one home page ( and one page for posts ) per language
*
* @since 1.2
*
* @param object $query instance of WP_Query
*/
public function parse_main_query( $query ) {
if ( ! $query->is_main_query() ) {
return;
}
/**
* This filter allows to set the language based on information contained in the main query
*
* @since 1.8
*
* @param bool|object $lang false or language object
* @param object $query WP_Query object
*/
if ( $lang = apply_filters( '<API key>', false, $query ) ) {
$this->set_language( $lang );
$this->set_lang_query_var( $query, $this->curlang );
}
// sets is_home on translated home page when it displays posts
// is_home must be true on page 2, 3... too
if ( 'posts' == get_option( 'show_on_front' ) && ( count( $query->query ) == 1 || ( is_paged() && count( $query->query ) == 2 ) || ( isset( $query->query['s'] ) && ! $query->query['s'] ) ) && $lang = get_query_var( 'lang' ) ) {
$lang = $this->model->get_language( $lang );
$this->set_language( $lang ); // sets the language now otherwise it will be too late to filter sticky posts !
$query->is_home = true;
$query->is_archive = $query->is_tax = false;
}
}
/**
* sets the language in query
* optimized for ( needs ) WP 3.5+
*
* @since 1.3
*/
public function set_lang_query_var( &$query, $lang ) {
// defining directly the tax_query ( rather than setting 'lang' avoids transforming the query by WP )
$query->query_vars['tax_query'][] = array(
'taxonomy' => 'language',
'field' => 'term_taxonomy_id', // since WP 3.5
'terms' => $lang->term_taxonomy_id,
'operator' => 'IN',
);
}
} |
// 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
// Foundation; either version 3, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// along with this library; see the file COPYING3. If not see
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
/**
* @file native_tree_tag.hpp
* Contains a tag for native tree-based containers
*/
#ifndef <API key>
#define <API key>
namespace __gnu_pbds
{
namespace test
{
struct native_tree_tag
{ };
} // namespace test
} // namespace __gnu_pbds
#endif |
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
#ifndef <API key>
#define <API key>
#include <glib-object.h>
#include <dbus/dbus-glib.h>
#define <API key> "org.fedoraproject.FirewallD1"
#define FIREWALL_DBUS_PATH "/org/fedoraproject/FirewallD1"
#define <API key> "org.fedoraproject.FirewallD1"
#define <API key> "org.fedoraproject.FirewallD1.zone"
G_BEGIN_DECLS
#define <API key> (<API key> ())
#define NM_FIREWALL_MANAGER(obj) (<API key> ((obj), <API key>, NMFirewallManager))
#define <API key>(klass) (<API key> ((klass), <API key>, <API key>))
#define <API key>(obj) (<API key> ((obj), <API key>))
#define <API key>(klass) (<API key> ((klass), <API key>))
#define <API key>(obj) (<API key> ((obj), <API key>, <API key>))
#define <API key> "available"
typedef struct {
GObject parent;
} NMFirewallManager;
typedef struct {
GObjectClass parent;
/* Signals */
void (*started) (NMFirewallManager *manager);
} <API key>;
GType <API key> (void);
NMFirewallManager *<API key> (void);
typedef void (*FwAddToZoneFunc) (GError *error, gpointer user_data);
gpointer <API key> (NMFirewallManager *mgr,
const char *iface,
const char *zone,
gboolean add,
FwAddToZoneFunc callback,
gpointer user_data);
gpointer <API key> (NMFirewallManager *mgr,
const char *iface,
const char *zone);
void <API key> (NMFirewallManager *mgr, gpointer fw_call);
#endif /* <API key> */ |
#include <lwk/types.h>
long
sys_getgroups(int n, gid_t gids[])
{
return 0;
} |
#include "emu.h"
#include "includes/dassault.h"
void dassault_state::video_start()
{
m_sprgen1->alloc_sprite_bitmap();
m_sprgen2->alloc_sprite_bitmap();
}
void dassault_state::mixdassaultlayer(bitmap_rgb32 &bitmap, bitmap_ind16* sprite_bitmap, const rectangle &cliprect, UINT16 pri, UINT16 primask, UINT16 penbase, UINT8 alpha)
{
int y, x;
const pen_t *paldata = &m_palette->pen(0);
UINT16* srcline;
UINT32* dstline;
for (y=cliprect.min_y;y<=cliprect.max_y;y++)
{
srcline=&sprite_bitmap->pix16(y,0);
dstline=&bitmap.pix32(y,0);
for (x=cliprect.min_x;x<=cliprect.max_x;x++)
{
UINT16 pix = srcline[x];
if ((pix & primask) != pri)
continue;
if (pix&0xf)
{
UINT16 pen = pix&0x1ff;
if (pix & 0x800) pen += 0x200;
if (alpha!=0xff)
{
if (pix&0x600)
{
UINT32 base = dstline[x];
dstline[x] = alpha_blend_r32(base, paldata[pen+penbase], alpha);
}
else
{
dstline[x] = paldata[pen+penbase];
}
}
else
{
dstline[x] = paldata[pen+penbase];
}
}
}
}
}
/* are the priorities 100% correct? they're the same as they were before conversion to DECO52 sprite device, but if (for example) you walk to the side of the crates in the first part of the game you appear over them... */
UINT32 dassault_state::<API key>(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
address_space &space = machine().driver_data()->generic_space();
UINT16 flip = m_deco_tilegen1->pf_control_r(space, 0, 0xffff);
UINT16 priority = m_decocomn->priority_r(space, 0, 0xffff);
m_sprgen2->draw_sprites(bitmap, cliprect, m_spriteram2->buffer(), 0x400, false);
m_sprgen1->draw_sprites(bitmap, cliprect, m_spriteram->buffer(), 0x400, false);
bitmap_ind16* sprite_bitmap1 = &m_sprgen1-><API key>();
bitmap_ind16* sprite_bitmap2 = &m_sprgen2-><API key>();
/* Update tilemaps */
flip_screen_set(BIT(flip, 7));
m_deco_tilegen1->pf_update(nullptr, m_pf2_rowscroll);
m_deco_tilegen2->pf_update(nullptr, m_pf4_rowscroll);
/* Draw playfields/update priority bitmap */
screen.priority().fill(0, cliprect);
bitmap.fill(m_palette->pen(3072), cliprect);
m_deco_tilegen2->tilemap_2_draw(screen, bitmap, cliprect, TILEMAP_DRAW_OPAQUE, 0);
/* The middle playfields can be swapped priority-wise */
if ((priority & 3) == 0)
{
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0600, 0x0600, 0x400, 0xff);
m_deco_tilegen1->tilemap_2_draw(screen, bitmap, cliprect, 0, 2);
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0400, 0x0600, 0x400, 0xff);
m_deco_tilegen2->tilemap_1_draw(screen, bitmap, cliprect, 0, 16);
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0200, 0x0600, 0x400, 0xff);
mixdassaultlayer(bitmap, sprite_bitmap2, cliprect, 0x0000, 0x0000, 0x800, 0x80);
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0000, 0x0600, 0x400, 0xff); // 128
}
else if ((priority & 3) == 1)
{
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0600, 0x0600, 0x400, 0xff);
m_deco_tilegen2->tilemap_1_draw(screen, bitmap, cliprect, 0, 2);
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0400, 0x0600, 0x400, 0xff);
mixdassaultlayer(bitmap, sprite_bitmap2, cliprect, 0x0000, 0x0000, 0x800, 0x80);
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0200, 0x0600, 0x400, 0xff);
m_deco_tilegen1->tilemap_2_draw(screen, bitmap, cliprect, 0, 64);
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0000, 0x0600, 0x400, 0xff); // 128
}
else if ((priority & 3) == 3)
{
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0600, 0x0600, 0x400, 0xff);
m_deco_tilegen2->tilemap_1_draw(screen, bitmap, cliprect, 0, 2);
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0400, 0x0600, 0x400, 0xff);
m_deco_tilegen1->tilemap_2_draw(screen, bitmap, cliprect, 0, 16);
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0200, 0x0600, 0x400, 0xff);
mixdassaultlayer(bitmap, sprite_bitmap2, cliprect, 0x0000, 0x0000, 0x800, 0x80);
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0000, 0x0600, 0x400, 0xff); // 128
}
else
{
/* Unused */
}
m_deco_tilegen1->tilemap_1_draw(screen, bitmap, cliprect, 0, 0);
return 0;
} |
// { dg-do run { target c++11 } }
// 2007-10-12 Paolo Carlini <pcarlini@suse.de>
// 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
// 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,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// with this library; see the file COPYING3. If not see
// 25.3.6 Heap operations [lib.alg.heap.operations]
#include <algorithm>
#include <functional>
#include <testsuite_hooks.h>
int A[] = {9, 8, 6, 7, 7, 5, 5, 3, 6, 4, 1, 2, 3, 4};
int B[] = {1, 3, 2, 4, 4, 6, 3, 5, 5, 7, 7, 6, 8, 9};
const int N = sizeof(A) / sizeof(int);
void
test01()
{
for (int i = 0; i <= N; ++i)
{
VERIFY( std::is_heap(A, A + i) );
VERIFY( std::is_heap(A, A + i, std::less<int>()) );
VERIFY( std::is_heap(B, B + i, std::greater<int>()) );
VERIFY( (i < 2) || !std::is_heap(B, B + i) );
}
}
int
main()
{
test01();
return 0;
} |
void section_SDT (u_char *b, int len); |
/**
* @file ump_ukk_wrappers.c
* Defines the wrapper functions which turn Linux IOCTL calls into _ukk_ calls
*/
#include <asm/uaccess.h> /* user space access */
#include "ump_osk.h"
#include "ump_uk_types.h"
#include "ump_ukk.h"
#include "ump_kernel_common.h"
/*
* IOCTL operation; Negotiate version of IOCTL API
*/
int <API key>(u32 __user *argument, struct ump_session_data *session_data)
{
<API key> version_info;
_mali_osk_errcode_t err;
/* Sanity check input parameters */
if (NULL == argument || NULL == session_data) {
MSG_ERR(("NULL parameter in <API key>()\n"));
return -ENOTTY;
}
/* Copy the user space memory to kernel space (so we safely can read it) */
if (0 != copy_from_user(&version_info, argument, sizeof(version_info))) {
MSG_ERR(("copy_from_user() in <API key>()\n"));
return -EFAULT;
}
version_info.ctx = (void *) session_data;
err = <API key>(&version_info);
if (_MALI_OSK_ERR_OK != err) {
MSG_ERR(("<API key>() failed in <API key>()\n"));
return map_errcode(err);
}
version_info.ctx = NULL;
/* Copy ouput data back to user space */
if (0 != copy_to_user(argument, &version_info, sizeof(version_info))) {
MSG_ERR(("copy_to_user() failed in <API key>()\n"));
return -EFAULT;
}
return 0; /* success */
}
/*
* IOCTL operation; Release reference to specified UMP memory.
*/
int ump_release_wrapper(u32 __user *argument, struct ump_session_data *session_data)
{
_ump_uk_release_s release_args;
_mali_osk_errcode_t err;
/* Sanity check input parameters */
if (NULL == session_data) {
MSG_ERR(("NULL parameter in ump_ioctl_release()\n"));
return -ENOTTY;
}
/* Copy the user space memory to kernel space (so we safely can read it) */
if (0 != copy_from_user(&release_args, argument, sizeof(release_args))) {
MSG_ERR(("copy_from_user() in <API key>()\n"));
return -EFAULT;
}
release_args.ctx = (void *) session_data;
err = _ump_ukk_release(&release_args);
if (_MALI_OSK_ERR_OK != err) {
MSG_ERR(("_ump_ukk_release() failed in ump_ioctl_release()\n"));
return map_errcode(err);
}
return 0; /* success */
}
/*
* IOCTL operation; Return size for specified UMP memory.
*/
int <API key>(u32 __user *argument, struct ump_session_data *session_data)
{
_ump_uk_size_get_s user_interaction;
_mali_osk_errcode_t err;
/* Sanity check input parameters */
if (NULL == argument || NULL == session_data) {
MSG_ERR(("NULL parameter in ump_ioctl_size_get()\n"));
return -ENOTTY;
}
if (0 != copy_from_user(&user_interaction, argument, sizeof(user_interaction))) {
MSG_ERR(("copy_from_user() in ump_ioctl_size_get()\n"));
return -EFAULT;
}
user_interaction.ctx = (void *) session_data;
err = _ump_ukk_size_get(&user_interaction);
if (_MALI_OSK_ERR_OK != err) {
MSG_ERR(("_ump_ukk_size_get() failed in ump_ioctl_size_get()\n"));
return map_errcode(err);
}
user_interaction.ctx = NULL;
if (0 != copy_to_user(argument, &user_interaction, sizeof(user_interaction))) {
MSG_ERR(("copy_to_user() failed in ump_ioctl_size_get()\n"));
return -EFAULT;
}
return 0; /* success */
}
/*
* IOCTL operation; Do cache maintenance on specified UMP memory.
*/
int ump_msync_wrapper(u32 __user *argument, struct ump_session_data *session_data)
{
_ump_uk_msync_s user_interaction;
/* Sanity check input parameters */
if (NULL == argument || NULL == session_data) {
MSG_ERR(("NULL parameter in ump_ioctl_size_get()\n"));
return -ENOTTY;
}
if (0 != copy_from_user(&user_interaction, argument, sizeof(user_interaction))) {
MSG_ERR(("copy_from_user() in ump_ioctl_msync()\n"));
return -EFAULT;
}
user_interaction.ctx = (void *) session_data;
_ump_ukk_msync(&user_interaction);
user_interaction.ctx = NULL;
if (0 != copy_to_user(argument, &user_interaction, sizeof(user_interaction))) {
MSG_ERR(("copy_to_user() failed in ump_ioctl_msync()\n"));
return -EFAULT;
}
return 0; /* success */
}
int <API key>(u32 __user *argument, struct ump_session_data *session_data)
{
<API key> user_interaction;
/* Sanity check input parameters */
if (NULL == argument || NULL == session_data) {
MSG_ERR(("NULL parameter in ump_ioctl_size_get()\n"));
return -ENOTTY;
}
if (0 != copy_from_user(&user_interaction, argument, sizeof(user_interaction))) {
MSG_ERR(("copy_from_user() in <API key>()\n"));
return -EFAULT;
}
user_interaction.ctx = (void *) session_data;
<API key>((<API key> *) &user_interaction);
user_interaction.ctx = NULL;
#if 0 /* No data to copy back */
if (0 != copy_to_user(argument, &user_interaction, sizeof(user_interaction))) {
MSG_ERR(("copy_to_user() failed in <API key>()\n"));
return -EFAULT;
}
#endif
return 0; /* success */
}
int <API key>(u32 __user *argument, struct ump_session_data *session_data)
{
<API key> user_interaction;
/* Sanity check input parameters */
if (NULL == argument || NULL == session_data) {
MSG_ERR(("NULL parameter in ump_ioctl_size_get()\n"));
return -ENOTTY;
}
if (0 != copy_from_user(&user_interaction, argument, sizeof(user_interaction))) {
MSG_ERR(("copy_from_user() in <API key>()\n"));
return -EFAULT;
}
user_interaction.ctx = (void *) session_data;
<API key>(&user_interaction);
user_interaction.ctx = NULL;
#if 0 /* No data to copy back */
if (0 != copy_to_user(argument, &user_interaction, sizeof(user_interaction))) {
MSG_ERR(("copy_to_user() failed in <API key>()\n"));
return -EFAULT;
}
#endif
return 0; /* success */
}
int ump_lock_wrapper(u32 __user *argument, struct ump_session_data *session_data)
{
_ump_uk_lock_s user_interaction;
/* Sanity check input parameters */
if (NULL == argument || NULL == session_data) {
MSG_ERR(("NULL parameter in ump_ioctl_size_get()\n"));
return -ENOTTY;
}
if (0 != copy_from_user(&user_interaction, argument, sizeof(user_interaction))) {
MSG_ERR(("copy_from_user() in <API key>()\n"));
return -EFAULT;
}
user_interaction.ctx = (void *) session_data;
_ump_ukk_lock(&user_interaction);
user_interaction.ctx = NULL;
#if 0 /* No data to copy back */
if (0 != copy_to_user(argument, &user_interaction, sizeof(user_interaction))) {
MSG_ERR(("copy_to_user() failed in <API key>()\n"));
return -EFAULT;
}
#endif
return 0; /* success */
}
int ump_unlock_wrapper(u32 __user *argument, struct ump_session_data *session_data)
{
_ump_uk_unlock_s user_interaction;
/* Sanity check input parameters */
if (NULL == argument || NULL == session_data) {
MSG_ERR(("NULL parameter in ump_ioctl_size_get()\n"));
return -ENOTTY;
}
if (0 != copy_from_user(&user_interaction, argument, sizeof(user_interaction))) {
MSG_ERR(("copy_from_user() in <API key>()\n"));
return -EFAULT;
}
user_interaction.ctx = (void *) session_data;
_ump_ukk_unlock(&user_interaction);
user_interaction.ctx = NULL;
#if 0 /* No data to copy back */
if (0 != copy_to_user(argument, &user_interaction, sizeof(user_interaction))) {
MSG_ERR(("copy_to_user() failed in <API key>()\n"));
return -EFAULT;
}
#endif
return 0; /* success */
} |
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <mach/gpio.h>
#include <mach/camera.h>
#include "msm_ispif.h"
#include "msm.h"
#include "msm_ispif_hwreg.h"
#define V4L2_IDENT_ISPIF 50001
#define CSID_VERSION_V2 0x02000011
#define CSID_VERSION_V3 0x30000000
#define MAX_CID 15
static atomic_t ispif_irq_cnt;
static spinlock_t ispif_tasklet_lock;
static struct list_head ispif_tasklet_q;
static int <API key>(struct ispif_device *ispif,
uint16_t intfmask, uint8_t vfe_intf)
{
int rc = 0;
uint32_t data = (0x1 << STROBED_RST_EN);
uint16_t intfnum = 0, mask = intfmask;
while (mask != 0) {
if (!(intfmask & (0x1 << intfnum))) {
mask >>= 1;
intfnum++;
continue;
}
switch (intfnum) {
case PIX0:
data |= (0x1 << PIX_0_VFE_RST_STB) |
(0x1 << PIX_0_CSID_RST_STB);
ispif->pix_sof_count = 0;
break;
case RDI0:
data |= (0x1 << RDI_0_VFE_RST_STB) |
(0x1 << RDI_0_CSID_RST_STB);
ispif->rdi0_sof_count = 0;
break;
case PIX1:
data |= (0x1 << PIX_1_VFE_RST_STB) |
(0x1 << PIX_1_CSID_RST_STB);
break;
case RDI1:
data |= (0x1 << RDI_1_VFE_RST_STB) |
(0x1 << RDI_1_CSID_RST_STB);
ispif->rdi1_sof_count = 0;
break;
case RDI2:
data |= (0x1 << RDI_2_VFE_RST_STB) |
(0x1 << RDI_2_CSID_RST_STB);
ispif->rdi2_sof_count = 0;
break;
default:
rc = -EINVAL;
break;
}
mask >>= 1;
intfnum++;
} /*end while */
if (data > 0x1) {
if (vfe_intf == VFE0)
msm_camera_io_w(data, ispif->base + ISPIF_RST_CMD_ADDR);
else
msm_camera_io_w(data, ispif->base +
<API key>);
rc = <API key>(&ispif->reset_complete);
}
return rc;
}
static int msm_ispif_reset(struct ispif_device *ispif)
{
int rc = 0;
ispif->pix_sof_count = 0;
msm_camera_io_w(ISPIF_RST_CMD_MASK, ispif->base + ISPIF_RST_CMD_ADDR);
if (ispif->csid_version == CSID_VERSION_V3)
msm_camera_io_w(<API key>, ispif->base +
<API key>);
rc = <API key>(&ispif->reset_complete);
return rc;
}
static int <API key>(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *chip)
{
BUG_ON(!chip);
chip->ident = V4L2_IDENT_ISPIF;
chip->revision = 0;
return 0;
}
static void <API key>(struct ispif_device *ispif,
uint8_t intftype, uint8_t csid, uint8_t vfe_intf)
{
int rc = 0;
uint32_t data = 0;
if (ispif->csid_version <= CSID_VERSION_V2) {
if (ispif->ispif_clk[intftype] == NULL) {
pr_err("%s: ispif NULL clk\n", __func__);
return;
}
rc = clk_set_rate(ispif->ispif_clk[intftype], csid);
if (rc < 0)
pr_err("%s: clk_set_rate failed %d\n", __func__, rc);
}
data = msm_camera_io_r(ispif->base + <API key> +
(0x200 * vfe_intf));
switch (intftype) {
case PIX0:
data &= ~(0x3);
data |= csid;
break;
case RDI0:
data &= ~(0x3 << 4);
data |= (csid << 4);
break;
case PIX1:
data &= ~(0x3 << 8);
data |= (csid << 8);
break;
case RDI1:
data &= ~(0x3 << 12);
data |= (csid << 12);
break;
case RDI2:
data &= ~(0x3 << 20);
data |= (csid << 20);
break;
}
if (data) {
msm_camera_io_w(data, ispif->base + <API key> +
(0x200 * vfe_intf));
}
}
static void <API key>(struct ispif_device *ispif,
uint8_t intftype, uint16_t cid_mask, uint8_t vfe_intf)
{
uint32_t data = 0;
mutex_lock(&ispif->mutex);
switch (intftype) {
case PIX0:
data = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
data |= cid_mask;
msm_camera_io_w(data, ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case RDI0:
data = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
data |= cid_mask;
msm_camera_io_w(data, ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case PIX1:
data = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
data |= cid_mask;
msm_camera_io_w(data, ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case RDI1:
data = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
data |= cid_mask;
msm_camera_io_w(data, ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case RDI2:
data = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
data |= cid_mask;
msm_camera_io_w(data, ispif->base +
<API key> + (0x200 * vfe_intf));
break;
}
mutex_unlock(&ispif->mutex);
}
static int32_t <API key>(struct ispif_device *ispif,
uint8_t intftype, uint8_t vfe_intf)
{
int32_t rc = 0;
uint32_t data = 0;
mutex_lock(&ispif->mutex);
switch (intftype) {
case PIX0:
data = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case RDI0:
data = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case PIX1:
data = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case RDI1:
data = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case RDI2:
data = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
break;
}
if ((data & 0xf) != 0xf)
rc = -EBUSY;
mutex_unlock(&ispif->mutex);
return rc;
}
static int msm_ispif_config(struct ispif_device *ispif,
struct <API key> *params_list)
{
uint32_t params_len;
struct msm_ispif_params *ispif_params;
int rc = 0, i = 0;
uint8_t intftype;
uint8_t vfe_intf;
params_len = params_list->len;
ispif_params = params_list->params;
CDBG("Enable interface\n");
msm_camera_io_w(0x00000000, ispif->base + ISPIF_IRQ_MASK_ADDR);
msm_camera_io_w(0x00000000, ispif->base + <API key>);
msm_camera_io_w(0x00000000, ispif->base + <API key>);
for (i = 0; i < params_len; i++) {
intftype = ispif_params[i].intftype;
vfe_intf = ispif_params[i].vfe_intf;
CDBG("%s intftype %x, vfe_intf %d, csid %d\n", __func__,
intftype, vfe_intf, ispif_params[i].csid);
if ((intftype >= INTF_MAX) ||
(ispif->csid_version <= CSID_VERSION_V2 &&
vfe_intf > VFE0) ||
(ispif->csid_version == CSID_VERSION_V3 &&
vfe_intf >= VFE_MAX)) {
pr_err("%s: intftype / vfe intf not valid\n",
__func__);
return -EINVAL;
}
rc = <API key>(ispif, intftype, vfe_intf);
if (rc < 0) {
pr_err("%s:%d failed rc %d\n", __func__, __LINE__, rc);
return rc;
}
<API key>(ispif, intftype, ispif_params[i].csid,
vfe_intf);
<API key>(ispif, intftype,
ispif_params[i].cid_mask, vfe_intf);
}
msm_camera_io_w(<API key>, ispif->base +
ISPIF_IRQ_MASK_ADDR);
msm_camera_io_w(<API key>, ispif->base +
<API key>);
msm_camera_io_w(<API key>, ispif->base +
<API key>);
msm_camera_io_w(<API key>, ispif->base +
<API key>);
msm_camera_io_w(<API key>, ispif->base +
<API key>);
msm_camera_io_w(<API key>, ispif->base +
<API key>);
msm_camera_io_w(<API key>, ispif->base +
<API key>);
return rc;
}
static uint32_t <API key>(struct ispif_device *ispif,
uint16_t intftype, uint8_t vfe_intf)
{
uint32_t mask = 0;
switch (intftype) {
case PIX0:
mask = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case RDI0:
mask = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case PIX1:
mask = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case RDI1:
mask = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
break;
case RDI2:
mask = msm_camera_io_r(ispif->base +
<API key> + (0x200 * vfe_intf));
break;
default:
break;
}
return mask;
}
static void msm_ispif_intf_cmd(struct ispif_device *ispif, uint16_t intfmask,
uint8_t intf_cmd_mask, uint8_t vfe_intf)
{
uint8_t vc = 0, val = 0;
uint16_t mask = intfmask, intfnum = 0;
uint32_t cid_mask = 0;
uint32_t <API key> = 0xFFFFFFFF;
while (mask != 0) {
if (!(intfmask & (0x1 << intfnum))) {
mask >>= 1;
intfnum++;
continue;
}
cid_mask = <API key>(ispif, intfnum, vfe_intf);
vc = 0;
while (cid_mask != 0) {
if ((cid_mask & 0xf) != 0x0) {
if (intfnum != RDI2) {
val = (intf_cmd_mask>>(vc*2)) & 0x3;
ispif-><API key> |=
(0x3 << ((vc * 2) +
(intfnum * 8)));
ispif-><API key> &=
~((0x3 & ~val) << ((vc * 2) +
(intfnum * 8)));
} else
<API key> &=
~((0x3 & ~intf_cmd_mask)
<< ((vc * 2) + 8));
}
vc++;
cid_mask >>= 4;
}
mask >>= 1;
intfnum++;
}
msm_camera_io_w(ispif-><API key>,
ispif->base + ISPIF_INTF_CMD_ADDR + (0x200 * vfe_intf));
if (<API key> != 0xFFFFFFFF)
msm_camera_io_w(<API key>,
ispif->base + <API key> +
(0x200 * vfe_intf));
}
static int <API key>(struct ispif_device *ispif,
uint16_t intfmask, uint8_t vfe_intf)
{
int rc = 0;
uint8_t intf_cmd_mask = 0xAA;
uint16_t intfnum = 0, mask = intfmask;
mutex_lock(&ispif->mutex);
CDBG("%s intfmask %x intf_cmd_mask %x\n", __func__, intfmask,
intf_cmd_mask);
msm_ispif_intf_cmd(ispif, intfmask, intf_cmd_mask, vfe_intf);
while (mask != 0) {
if (intfmask & (0x1 << intfnum))
ispif-><API key> |= (0xFF << (intfnum * 8));
mask >>= 1;
intfnum++;
if (intfnum == RDI2)
break;
}
mutex_unlock(&ispif->mutex);
return rc;
}
static int <API key>(struct ispif_device *ispif,
uint16_t intfmask, uint8_t vfe_intf)
{
uint8_t intf_cmd_mask = 0x55;
int rc = 0;
mutex_lock(&ispif->mutex);
rc = <API key>(ispif, intfmask, vfe_intf);
CDBG("%s intfmask start after%x intf_cmd_mask %x\n", __func__, intfmask,
intf_cmd_mask);
msm_ispif_intf_cmd(ispif, intfmask, intf_cmd_mask, vfe_intf);
mutex_unlock(&ispif->mutex);
return rc;
}
static int <API key>(struct ispif_device *ispif,
uint16_t intfmask, uint8_t vfe_intf)
{
int rc = 0;
uint8_t intf_cmd_mask = 0x00;
uint16_t intfnum = 0, mask = intfmask;
mutex_lock(&ispif->mutex);
CDBG("%s intfmask %x intf_cmd_mask %x\n", __func__, intfmask,
intf_cmd_mask);
msm_ispif_intf_cmd(ispif, intfmask, intf_cmd_mask, vfe_intf);
while (mask != 0) {
if (intfmask & (0x1 << intfnum)) {
switch (intfnum) {
case PIX0:
while ((msm_camera_io_r(ispif->base +
<API key> +
(0x200 * vfe_intf))
& 0xf) != 0xf) {
CDBG("Wait for pix0 Idle\n");
}
break;
case RDI0:
while ((msm_camera_io_r(ispif->base +
<API key> +
(0x200 * vfe_intf))
& 0xf) != 0xf) {
CDBG("Wait for rdi0 Idle\n");
}
break;
case PIX1:
while ((msm_camera_io_r(ispif->base +
<API key> +
(0x200 * vfe_intf))
& 0xf) != 0xf) {
CDBG("Wait for pix1 Idle\n");
}
break;
case RDI1:
while ((msm_camera_io_r(ispif->base +
<API key> +
(0x200 * vfe_intf))
& 0xf) != 0xf) {
CDBG("Wait for rdi1 Idle\n");
}
break;
case RDI2:
while ((msm_camera_io_r(ispif->base +
<API key> +
(0x200 * vfe_intf))
& 0xf) != 0xf) {
CDBG("Wait for rdi2 Idle\n");
}
break;
default:
break;
}
if (intfnum != RDI2)
ispif-><API key> |= (0xFF <<
(intfnum * 8));
}
mask >>= 1;
intfnum++;
}
mutex_unlock(&ispif->mutex);
return rc;
}
static int <API key>(struct v4l2_subdev *sd,
int enable)
{
struct ispif_device *ispif =
(struct ispif_device *)v4l2_get_subdevdata(sd);
uint32_t cmd = enable & ((1<<<API key>)-1);
uint16_t intf = enable >> <API key>;
uint8_t vfe_intf = enable >> <API key>;
int rc = -EINVAL;
CDBG("%s enable %x, cmd %x, intf %x\n", __func__, enable, cmd, intf);
BUG_ON(!ispif);
if ((ispif->csid_version <= CSID_VERSION_V2 && vfe_intf > VFE0) ||
(ispif->csid_version == CSID_VERSION_V3 &&
vfe_intf >= VFE_MAX)) {
pr_err("%s invalid csid version %x && vfe intf %d\n", __func__,
ispif->csid_version, vfe_intf);
return rc;
}
switch (cmd) {
case <API key>:
rc = <API key>(ispif, intf, vfe_intf);
break;
case <API key>:
rc = <API key>(ispif, intf, vfe_intf);
break;
case <API key>:
rc = <API key>(ispif, intf, vfe_intf);
break;
default:
break;
}
return rc;
}
static void send_rdi_sof(struct ispif_device *ispif,
enum msm_ispif_intftype interface, int count)
{
struct rdi_count_msg sof_msg;
sof_msg.rdi_interface = interface;
sof_msg.count = count;
v4l2_subdev_notify(&ispif->subdev, <API key>,
(void *)&sof_msg);
}
static void ispif_do_tasklet(unsigned long data)
{
unsigned long flags;
struct ispif_isr_queue_cmd *qcmd = NULL;
struct ispif_device *ispif;
ispif = (struct ispif_device *)data;
while (atomic_read(&ispif_irq_cnt)) {
spin_lock_irqsave(&ispif_tasklet_lock, flags);
qcmd = list_first_entry(&ispif_tasklet_q,
struct ispif_isr_queue_cmd, list);
atomic_sub(1, &ispif_irq_cnt);
if (!qcmd) {
<API key>(&ispif_tasklet_lock,
flags);
return;
}
list_del(&qcmd->list);
<API key>(&ispif_tasklet_lock,
flags);
kfree(qcmd);
}
}
static void ispif_process_irq(struct ispif_device *ispif,
struct ispif_irq_status *out)
{
unsigned long flags;
struct ispif_isr_queue_cmd *qcmd;
qcmd = kzalloc(sizeof(struct ispif_isr_queue_cmd),
GFP_ATOMIC);
if (!qcmd) {
pr_err("ispif_process_irq: qcmd malloc failed!\n");
return;
}
qcmd-><API key> = out->ispifIrqStatus0;
qcmd-><API key> = out->ispifIrqStatus1;
qcmd-><API key> = out->ispifIrqStatus2;
if (qcmd-><API key> &
<API key>) {
CDBG("%s: ispif PIX irq status\n", __func__);
ispif->pix_sof_count++;
v4l2_subdev_notify(&ispif->subdev,
<API key>,
(void *)&ispif->pix_sof_count);
}
if (qcmd-><API key> &
<API key>) {
ispif->rdi0_sof_count++;
CDBG("%s: ispif RDI0 irq status, counter = %d",
__func__, ispif->rdi0_sof_count);
send_rdi_sof(ispif, RDI_0, ispif->rdi0_sof_count);
}
if (qcmd-><API key> &
<API key>) {
ispif->rdi1_sof_count++;
CDBG("%s: ispif RDI1 irq status, counter = %d",
__func__, ispif->rdi1_sof_count);
send_rdi_sof(ispif, RDI_1, ispif->rdi1_sof_count);
}
if (qcmd-><API key> &
<API key>) {
ispif->rdi2_sof_count++;
CDBG("%s: ispif RDI2 irq status, counter = %d",
__func__, ispif->rdi2_sof_count);
send_rdi_sof(ispif, RDI_2, ispif->rdi2_sof_count);
}
spin_lock_irqsave(&ispif_tasklet_lock, flags);
list_add_tail(&qcmd->list, &ispif_tasklet_q);
atomic_add(1, &ispif_irq_cnt);
<API key>(&ispif_tasklet_lock, flags);
tasklet_schedule(&ispif->ispif_tasklet);
return;
}
static inline void <API key>(struct ispif_irq_status *out,
void *data)
{
uint32_t status0 = 0, status1 = 0, status2 = 0;
struct ispif_device *ispif = (struct ispif_device *)data;
out->ispifIrqStatus0 = msm_camera_io_r(ispif->base +
<API key>);
out->ispifIrqStatus1 = msm_camera_io_r(ispif->base +
<API key>);
out->ispifIrqStatus2 = msm_camera_io_r(ispif->base +
<API key>);
msm_camera_io_w(out->ispifIrqStatus0,
ispif->base + <API key>);
msm_camera_io_w(out->ispifIrqStatus1,
ispif->base + <API key>);
msm_camera_io_w(out->ispifIrqStatus2,
ispif->base + <API key>);
CDBG("%s: irq vfe0 Irq_status0 = 0x%x, 1 = 0x%x, 2 = 0x%x\n",
__func__, out->ispifIrqStatus0, out->ispifIrqStatus1,
out->ispifIrqStatus2);
if (out->ispifIrqStatus0 & <API key> ||
out->ispifIrqStatus1 & <API key> ||
out->ispifIrqStatus2 & <API key>) {
if (out->ispifIrqStatus0 & (0x1 << RESET_DONE_IRQ))
complete(&ispif->reset_complete);
if (out->ispifIrqStatus0 & (0x1 << <API key>))
pr_err("%s: pix intf 0 overflow.\n", __func__);
if (out->ispifIrqStatus0 & (0x1 << <API key>))
pr_err("%s: rdi intf 0 overflow.\n", __func__);
if (out->ispifIrqStatus1 & (0x1 << <API key>))
pr_err("%s: rdi intf 1 overflow.\n", __func__);
if (out->ispifIrqStatus2 & (0x1 << <API key>))
pr_err("%s: rdi intf 2 overflow.\n", __func__);
if ((out->ispifIrqStatus0 & <API key>) ||
(out->ispifIrqStatus1 & <API key>) ||
(out->ispifIrqStatus2 & <API key>))
ispif_process_irq(ispif, out);
}
if (ispif->csid_version == CSID_VERSION_V3) {
status0 = msm_camera_io_r(ispif->base +
<API key> + 0x200);
msm_camera_io_w(status0,
ispif->base + <API key> + 0x200);
status1 = msm_camera_io_r(ispif->base +
<API key> + 0x200);
msm_camera_io_w(status1,
ispif->base + <API key> + 0x200);
status2 = msm_camera_io_r(ispif->base +
<API key> + 0x200);
msm_camera_io_w(status2,
ispif->base + <API key> + 0x200);
CDBG("%s: irq vfe1 Irq_status0 = 0x%x, 1 = 0x%x, 2 = 0x%x\n",
__func__, status0, status1, status2);
}
msm_camera_io_w(<API key>, ispif->base +
<API key>);
}
static irqreturn_t msm_io_ispif_irq(int irq_num, void *data)
{
struct ispif_irq_status irq;
<API key>(&irq, data);
return IRQ_HANDLED;
}
static struct msm_cam_clk_info ispif_8960_clk_info[] = {
{"csi_pix_clk", 0},
{"csi_rdi_clk", 0},
{"csi_pix1_clk", 0},
{"csi_rdi1_clk", 0},
{"csi_rdi2_clk", 0},
};
static int msm_ispif_init(struct ispif_device *ispif,
const uint32_t *csid_version)
{
int rc = 0;
CDBG("%s called %d\n", __func__, __LINE__);
if (ispif->ispif_state == ISPIF_POWER_UP) {
pr_err("%s: ispif invalid state %d\n", __func__,
ispif->ispif_state);
rc = -EINVAL;
return rc;
}
spin_lock_init(&ispif_tasklet_lock);
INIT_LIST_HEAD(&ispif_tasklet_q);
rc = request_irq(ispif->irq->start, msm_io_ispif_irq,
IRQF_TRIGGER_RISING, "ispif", ispif);
ispif-><API key> = 0xFFFFFFFF;
init_completion(&ispif->reset_complete);
tasklet_init(&ispif->ispif_tasklet,
ispif_do_tasklet, (unsigned long)ispif);
ispif->csid_version = *csid_version;
if (ispif->csid_version < CSID_VERSION_V2) {
rc = msm_cam_clk_enable(&ispif->pdev->dev, ispif_8960_clk_info,
ispif->ispif_clk, 2, 1);
if (rc < 0)
return rc;
} else if (ispif->csid_version == CSID_VERSION_V2) {
rc = msm_cam_clk_enable(&ispif->pdev->dev, ispif_8960_clk_info,
ispif->ispif_clk, ARRAY_SIZE(ispif_8960_clk_info), 1);
if (rc < 0)
return rc;
}
rc = msm_ispif_reset(ispif);
ispif->ispif_state = ISPIF_POWER_UP;
return rc;
}
static void msm_ispif_release(struct ispif_device *ispif)
{
if (ispif->ispif_state != ISPIF_POWER_UP) {
pr_err("%s: ispif invalid state %d\n", __func__,
ispif->ispif_state);
return;
}
CDBG("%s, free_irq\n", __func__);
free_irq(ispif->irq->start, ispif);
tasklet_kill(&ispif->ispif_tasklet);
if (ispif->csid_version < CSID_VERSION_V2) {
msm_cam_clk_enable(&ispif->pdev->dev, ispif_8960_clk_info,
ispif->ispif_clk, 2, 0);
} else if (ispif->csid_version == CSID_VERSION_V2) {
msm_cam_clk_enable(&ispif->pdev->dev, ispif_8960_clk_info,
ispif->ispif_clk, ARRAY_SIZE(ispif_8960_clk_info), 0);
}
ispif->ispif_state = ISPIF_POWER_DOWN;
}
static long msm_ispif_cmd(struct v4l2_subdev *sd, void *arg)
{
long rc = 0;
struct ispif_cfg_data cdata;
struct ispif_device *ispif =
(struct ispif_device *)v4l2_get_subdevdata(sd);
if (copy_from_user(&cdata, (void *)arg, sizeof(struct ispif_cfg_data)))
return -EFAULT;
CDBG("%s cfgtype = %d\n", __func__, cdata.cfgtype);
switch (cdata.cfgtype) {
case ISPIF_INIT:
CDBG("%s csid_version = %x\n", __func__,
cdata.cfg.csid_version);
rc = msm_ispif_init(ispif, &cdata.cfg.csid_version);
break;
case ISPIF_SET_CFG:
CDBG("%s len = %d, intftype = %d,.cid_mask = %d, csid = %d\n",
__func__,
cdata.cfg.ispif_params.len,
cdata.cfg.ispif_params.params[0].intftype,
cdata.cfg.ispif_params.params[0].cid_mask,
cdata.cfg.ispif_params.params[0].csid);
rc = msm_ispif_config(ispif, &cdata.cfg.ispif_params);
break;
case <API key>:
case <API key>:
case <API key>:
rc = <API key>(sd, cdata.cfg.cmd);
break;
case ISPIF_RELEASE:
msm_ispif_release(ispif);
break;
default:
break;
}
return rc;
}
static long <API key>(struct v4l2_subdev *sd, unsigned int cmd,
void *arg)
{
switch (cmd) {
case <API key>:
return msm_ispif_cmd(sd, arg);
default:
return -ENOIOCTLCMD;
}
}
static struct <API key> <API key> = {
.g_chip_ident = &<API key>,
.ioctl = &<API key>,
};
static struct <API key> <API key> = {
.s_stream = &<API key>,
};
static const struct v4l2_subdev_ops <API key> = {
.core = &<API key>,
.video = &<API key>,
};
static const struct <API key> <API key>;
static int __devinit ispif_probe(struct platform_device *pdev)
{
int rc = 0;
struct msm_cam_subdev_info sd_info;
struct ispif_device *ispif;
CDBG("%s\n", __func__);
ispif = kzalloc(sizeof(struct ispif_device), GFP_KERNEL);
if (!ispif) {
pr_err("%s: no enough memory\n", __func__);
return -ENOMEM;
}
v4l2_subdev_init(&ispif->subdev, &<API key>);
ispif->subdev.internal_ops = &<API key>;
ispif->subdev.flags |= <API key>;
snprintf(ispif->subdev.name,
ARRAY_SIZE(ispif->subdev.name), "msm_ispif");
v4l2_set_subdevdata(&ispif->subdev, ispif);
<API key>(pdev, &ispif->subdev);
snprintf(ispif->subdev.name, sizeof(ispif->subdev.name),
"ispif");
mutex_init(&ispif->mutex);
if (pdev->dev.of_node)
<API key>((&pdev->dev)->of_node,
"cell-index", &pdev->id);
ispif->mem = <API key>(pdev,
IORESOURCE_MEM, "ispif");
if (!ispif->mem) {
pr_err("%s: no mem resource?\n", __func__);
rc = -ENODEV;
goto ispif_no_resource;
}
ispif->irq = <API key>(pdev,
IORESOURCE_IRQ, "ispif");
if (!ispif->irq) {
pr_err("%s: no irq resource?\n", __func__);
rc = -ENODEV;
goto ispif_no_resource;
}
ispif->io = request_mem_region(ispif->mem->start,
resource_size(ispif->mem), pdev->name);
if (!ispif->io) {
pr_err("%s: no valid mem region\n", __func__);
rc = -EBUSY;
goto ispif_no_resource;
}
ispif->base = ioremap(ispif->mem->start,
resource_size(ispif->mem));
if (!ispif->base) {
rc = -ENOMEM;
goto ispif_no_mem;
}
ispif->pdev = pdev;
sd_info.sdev_type = ISPIF_DEV;
sd_info.sd_index = pdev->id;
sd_info.irq_num = ispif->irq->start;
<API key>(&ispif->subdev, &sd_info);
media_entity_init(&ispif->subdev.entity, 0, NULL, 0);
ispif->subdev.entity.type = <API key>;
ispif->subdev.entity.group_id = ISPIF_DEV;
ispif->subdev.entity.name = pdev->name;
ispif->subdev.entity.revision = ispif->subdev.devnode->num;
ispif->ispif_state = ISPIF_POWER_DOWN;
return 0;
ispif_no_mem:
release_mem_region(ispif->mem->start,
resource_size(ispif->mem));
ispif_no_resource:
mutex_destroy(&ispif->mutex);
kfree(ispif);
return rc;
}
static const struct of_device_id msm_ispif_dt_match[] = {
{.compatible = "qcom,ispif"},
};
MODULE_DEVICE_TABLE(of, msm_ispif_dt_match);
static struct platform_driver ispif_driver = {
.probe = ispif_probe,
.driver = {
.name = MSM_ISPIF_DRV_NAME,
.owner = THIS_MODULE,
.of_match_table = msm_ispif_dt_match,
},
};
static int __init <API key>(void)
{
return <API key>(&ispif_driver);
}
static void __exit <API key>(void)
{
<API key>(&ispif_driver);
}
module_init(<API key>);
module_exit(<API key>);
MODULE_DESCRIPTION("MSM ISP Interface driver");
MODULE_LICENSE("GPL v2"); |
package loci.plugins.util;
import ij.IJ;
import ij.ImageJ;
import ij.gui.GenericDialog;
import java.awt.BorderLayout;
import java.awt.Checkbox;
import java.awt.Choice;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.ScrollPane;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.Window;
import java.util.List;
import java.util.StringTokenizer;
import loci.common.DebugTools;
import loci.plugins.BF;
/**
* Utility methods for managing ImageJ dialogs and windows.
*/
public final class WindowTools {
// -- Constructor --
private WindowTools() { }
// -- Utility methods --
/** Adds AWT scroll bars to the given container. */
public static void addScrollBars(Container pane) {
GridBagLayout layout = (GridBagLayout) pane.getLayout();
// extract components
int count = pane.getComponentCount();
Component[] c = new Component[count];
GridBagConstraints[] gbc = new GridBagConstraints[count];
for (int i=0; i<count; i++) {
c[i] = pane.getComponent(i);
gbc[i] = layout.getConstraints(c[i]);
}
// clear components
pane.removeAll();
layout.invalidateLayout(pane);
// create new container panel
Panel newPane = new Panel();
GridBagLayout newLayout = new GridBagLayout();
newPane.setLayout(newLayout);
for (int i=0; i<count; i++) {
newLayout.setConstraints(c[i], gbc[i]);
newPane.add(c[i]);
}
// HACK - get preferred size for container panel
// NB: don't know a better way:
// - newPane.getPreferredSize() doesn't work
// - newLayout.preferredLayoutSize(newPane) doesn't work
Frame f = new Frame();
f.setLayout(new BorderLayout());
f.add(newPane, BorderLayout.CENTER);
f.pack();
final Dimension size = newPane.getSize();
f.remove(newPane);
f.dispose();
// compute best size for scrollable viewport
size.width += 25;
size.height += 15;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int maxWidth = 7 * screen.width / 8;
int maxHeight = 3 * screen.height / 4;
if (size.width > maxWidth) size.width = maxWidth;
if (size.height > maxHeight) size.height = maxHeight;
// create scroll pane
ScrollPane scroll = new ScrollPane() {
@Override
public Dimension getPreferredSize() {
return size;
}
};
scroll.add(newPane);
// add scroll pane to original container
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
layout.setConstraints(scroll, constraints);
pane.add(scroll);
}
/**
* Places the given window at a nice location on screen, either centered
* below the ImageJ window if there is one, or else centered on screen.
*/
public static void placeWindow(Window w) {
Dimension size = w.getSize();
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
ImageJ ij = IJ.getInstance();
Point p = new Point();
if (ij == null) {
// center config window on screen
p.x = (screen.width - size.width) / 2;
p.y = (screen.height - size.height) / 2;
}
else {
// place config window below ImageJ window
Rectangle ijBounds = ij.getBounds();
p.x = ijBounds.x + (ijBounds.width - size.width) / 2;
p.y = ijBounds.y + ijBounds.height + 5;
}
// nudge config window away from screen edges
final int pad = 10;
if (p.x < pad) p.x = pad;
else if (p.x + size.width + pad > screen.width) {
p.x = screen.width - size.width - pad;
}
if (p.y < pad) p.y = pad;
else if (p.y + size.height + pad > screen.height) {
p.y = screen.height - size.height - pad;
}
w.setLocation(p);
}
/** Reports the given exception with stack trace in an ImageJ error dialog. */
public static void reportException(Throwable t) {
reportException(t, false, null);
}
/** Reports the given exception with stack trace in an ImageJ error dialog. */
public static void reportException(Throwable t, boolean quiet) {
reportException(t, quiet, null);
}
/** Reports the given exception with stack trace in an ImageJ error dialog. */
public static void reportException(Throwable t, boolean quiet, String msg) {
if (quiet) return;
BF.status(quiet, "");
if (t != null) {
String s = DebugTools.getStackTrace(t);
StringTokenizer st = new StringTokenizer(s, "\n\r");
while (st.hasMoreTokens()) IJ.log(st.nextToken());
}
if (msg != null) IJ.error("Bio-Formats Importer", msg);
}
@SuppressWarnings("unchecked")
public static List<TextField> getNumericFields(GenericDialog gd) {
return gd.getNumericFields();
}
@SuppressWarnings("unchecked")
public static List<Checkbox> getCheckboxes(GenericDialog gd) {
return gd.getCheckboxes();
}
@SuppressWarnings("unchecked")
public static List<Choice> getChoices(GenericDialog gd) {
return gd.getChoices();
}
} |
#ifndef __MTK_WDT_H__
#define __MTK_WDT_H__
#define ENABLE_WDT_MODULE (1) // Module switch
#define LK_WDT_DISABLE (0)
#define MTK_WDT_BASE TOPRGU_BASE
#define MTK_WDT_MODE (MTK_WDT_BASE+0x0000)
#define MTK_WDT_LENGTH (MTK_WDT_BASE+0x0004)
#define MTK_WDT_RESTART (MTK_WDT_BASE+0x0008)
#define MTK_WDT_STATUS (MTK_WDT_BASE+0x000C)
#define MTK_WDT_INTERVAL (MTK_WDT_BASE+0x0010)
#define MTK_WDT_SWRST (MTK_WDT_BASE+0x0014)
#define MTK_WDT_SWSYSRST (MTK_WDT_BASE+0x0018)
#define MTK_WDT_NONRST_REG (MTK_WDT_BASE+0x0020)
#define MTK_WDT_NONRST_REG2 (MTK_WDT_BASE+0x0024)
#define MTK_WDT_REQ_MODE (MTK_WDT_BASE+0x0030)
#define MTK_WDT_REQ_IRQ_EN (MTK_WDT_BASE+0x0034)
#define MTK_WDT_DRAMC_CTL (MTK_WDT_BASE+0x0040)
/*WDT_MODE*/
#define <API key> (0xff00)
#define MTK_WDT_MODE_KEY (0x22000000)
#define <API key> (0x0040)
#define MTK_WDT_MODE_IN_DIS (0x0020) /* Reserved */
#define <API key> (0x0010) /* Reserved */
#define MTK_WDT_MODE_IRQ (0x0008)
#define MTK_WDT_MODE_EXTEN (0x0004)
#define <API key> (0x0002)
#define MTK_WDT_MODE_ENABLE (0x0001)
/*WDT_LENGTH*/
#define <API key> (0xffe0)
#define <API key> (0x001f)
#define MTK_WDT_LENGTH_KEY (0x0008)
/*WDT_RESTART*/
#define MTK_WDT_RESTART_KEY (0x1971)
/*WDT_STATUS*/
#define <API key> (0x80000000)
#define <API key> (0x40000000)
#define <API key> (0x20000000)
#define <API key> (0x00080000)
#define <API key> (0x0001)
/*WDT_INTERVAL*/
#define <API key> (0x0fff)
/*WDT_SWRST*/
#define MTK_WDT_SWRST_KEY (0x1209)
/*WDT_SWSYSRST*/
#define <API key> (0x0800)
#define <API key> (0x0400)
#define <API key> (0x0200)
#define <API key> (0x0100)
#define <API key> (0x0080)
#define <API key> (0x0040)
#define <API key> (0x0020)
#define <API key> (0x0010)
#define <API key> (0x0008)
#define <API key> (0x0004)
#define <API key> (0x0002)
#define <API key> (0x0001)
//#define <API key> (0x1500)
#define <API key> (0x88000000)
/*MTK_WDT_REQ_IRQ*/
#define MTK_WDT_REQ_IRQ_KEY (0x44000000)
#define <API key> (0x80000)
#define <API key> (0x0001)
#define <API key> (0x0002)
#define <API key> (1<<18)
/*MTK_WDT_REQ_MODE*/
#define <API key> (0x33000000)
#define <API key> (0x80000)
#define <API key> (0x0001)
#define <API key> (0x0002)
#define <API key> (1<<18)
#define WDT_NORMAL_REBOOT (0x01)
#define <API key> (0x02)
#define WDT_NOT_WDT_REBOOT (0x00)
typedef enum wd_swsys_reset_type {
WD_MD_RST,
}WD_SYS_RST_TYPE;
extern void mtk_wdt_init(void);
//extern void mtk_wdt_reset(void);
//extern unsigned int <API key>(void);
extern BOOL <API key>(void);
extern void mtk_arch_reset(char mode);
void rgu_swsys_reset(WD_SYS_RST_TYPE reset_type);
#endif /*__MTK_WDT_H__*/ |
#ifndef <API key>
#define <API key>
#include <QDrmContentPlugin>
#include "bscidrm.h"
#include <qtopiaglobal.h>
#include <QValueSpaceItem>
class BSciContentLicense : public QDrmContentLicense
{
Q_OBJECT
public:
BSciContentLicense( const QContent &content, QDrmRights::Permission permission, QDrmContent::LicenseOptions options, TFileHandle f, SBSciContentAccess *ops );
virtual ~BSciContentLicense();
virtual QContent content() const;
virtual QDrmRights::Permission permission() const;
virtual QDrmContent::RenderState renderState() const;
public slots:
virtual void renderStateChanged( const QContent &content, QDrmContent::RenderState state );
protected:
void <API key>();
void <API key>();
void <API key>();
void expireLicense();
void timerEvent( QTimerEvent * event );
private:
QContent m_content;
QDrmRights::Permission m_permission;
QDrmContent::RenderState m_renderState;
QDrmContent::LicenseOptions m_options;
TFileHandle file;
SBSciContentAccess *fileOps;
int timerId;
QDateTime lastUpdate;
};
class BSciPreviewLicense : public QDrmContentLicense
{
Q_OBJECT
public:
BSciPreviewLicense( const QContent &content );
virtual ~BSciPreviewLicense();
virtual QContent content() const;
virtual QDrmRights::Permission permission() const;
virtual QDrmContent::RenderState renderState() const;
public slots:
virtual void renderStateChanged( const QContent &content, QDrmContent::RenderState state );
private:
QContent m_content;
QDrmContent::RenderState m_renderState;
};
class BSciReadDevice : public QIODevice
{
Q_OBJECT
public:
BSciReadDevice( const QString &drmFile, QDrmRights::Permission permission );
~BSciReadDevice();
bool open( QIODevice::OpenMode mode );
void close();
bool seek( qint64 pos );
qint64 size() const;
protected:
qint64 readData( char * data, qint64 maxlen );
qint64 writeData( const char * data, qint64 len );
private:
const QByteArray fileName;
QDrmRights::Permission permission;
TFileHandle file;
SBSciContentAccess *fileOps;
};
class <API key> : public QDrmContentPlugin
{
Q_OBJECT
public:
<API key>( QObject *parent = 0 );
virtual ~<API key>();
virtual QStringList keys() const;
virtual QStringList types() const;
virtual QList< QPair< QString, QString > > httpHeaders() const;
virtual bool isProtected( const QString &filePath ) const;
virtual QDrmRights::Permissions permissions( const QString &filePath );
virtual bool activate( const QContent &content, QDrmRights::Permission permission, QWidget *focus );
virtual void activate( const QContent &content, QWidget *focus );
virtual void reactivate( const QContent &content, QDrmRights::Permission permission, QWidget *focus );
virtual QDrmRights getRights( const QString &filePath, QDrmRights::Permission permission );
virtual QDrmContentLicense *<API key>( const QContent &content, QDrmRights::Permission permission, QDrmContent::LicenseOptions options );
virtual QIODevice *createDecoder( const QString &filePath, QDrmRights::Permission permission );
virtual bool canActivate( const QString &filePath );
virtual qint64 unencryptedSize( const QString &filePath );
virtual QAbstractFileEngine *create( const QString &fileName ) const;
virtual bool deleteFile( const QString &filePath );
virtual bool installContent( const QString &filePath, QContent *content );
virtual bool updateContent( QContent *content );
protected:
enum MetaData
{
ContentType,
ContentUrl,
ContentVersion,
Title,
Description,
Copyright,
Author,
IconUri,
InfoUrl,
RightsIssuerUrl
};
bool installMessageFile( const QString &filePath );
bool registerFile( const QString &filePath );
QMap< MetaData, QString > getMetaData( const QString &filePath );
private slots:
void <API key>();
private:
QValueSpaceItem <API key>;
};
#endif |
#ifndef <API key>
#define <API key>
/**
* \file indirect_va_private.h
*
* \author Ian Romanick <idr@us.ibm.com>
*/
#include <inttypes.h>
#include "glxclient.h"
#include "indirect.h"
#include <GL/glxproto.h>
/**
* State descriptor for a single array of vertex data.
*/
struct array_state
{
/**
* Pointer to the application supplied data.
*/
const void *data;
/**
* Enum representing the type of the application supplied data.
*/
GLenum data_type;
/**
* Stride value supplied by the application. This value is not used
* internally. It is only kept so that it can be queried by the
* application using glGet*v.
*/
GLsizei user_stride;
/**
* Calculated size, in bytes, of a single element in the array. This
* is calculated based on \c count and the size of the data type
* represented by \c data_type.
*/
GLsizei element_size;
/**
* Actual byte-stride from one element to the next. This value will
* be equal to either \c user_stride or \c element_stride.
*/
GLsizei true_stride;
/**
* Number of data values in each element.
*/
GLint count;
/**
* "Normalized" data is on the range [0,1] (unsigned) or [-1,1] (signed).
* This is used for mapping integral types to floating point types.
*/
GLboolean normalized;
/**
* Pre-calculated GLX protocol command header.
* This contains two 16-bit words: the command length and the command
* opcode.
*/
uint16_t header[2];
/**
* Set to \c GL_TRUE if this array is enabled. Otherwise, it is set
* to \c GL_FALSE.
*/
GLboolean enabled;
/**
* For multi-arrayed data (e.g., texture coordinates, generic vertex
* program attributes, etc.), this specifies which array this is.
*/
unsigned index;
/**
* Per-array-type key. For most arrays, this will be the GL enum for
* that array (e.g., GL_VERTEX_ARRAY for vertex data, GL_NORMAL_ARRAY
* for normal data, <API key> for texture coordinate data,
* etc.).
*/
GLenum key;
/**
* If this array can be used with the "classic" \c glDrawArrays protocol,
* this is set to \c GL_TRUE. Otherwise, it is set to \c GL_FALSE.
*/
GLboolean <API key>;
};
/**
* Array state that is pushed / poped by \c glPushClientAttrib and
* \c glPopClientAttrib.
*/
struct array_stack_state
{
/**
* Pointer to the application supplied data.
*/
const void *data;
/**
* Enum representing the type of the application supplied data.
*/
GLenum data_type;
/**
* Stride value supplied by the application. This value is not used
* internally. It is only kept so that it can be queried by the
* application using glGet*v.
*/
GLsizei user_stride;
/**
* Number of data values in each element.
*/
GLint count;
/**
* Per-array-type key. For most arrays, this will be the GL enum for
* that array (e.g., GL_VERTEX_ARRAY for vertex data, GL_NORMAL_ARRAY
* for normal data, <API key> for texture coordinate data,
* etc.).
*/
GLenum key;
/**
* For multi-arrayed data (e.g., texture coordinates, generic vertex
* program attributes, etc.), this specifies which array this is.
*/
unsigned index;
/**
* Set to \c GL_TRUE if this array is enabled. Otherwise, it is set
* to \c GL_FALSE.
*/
GLboolean enabled;
};
/**
* Collection of all the vertex array state.
*/
struct array_state_vector
{
/**
* Number of arrays tracked by \c ::arrays.
*/
size_t num_arrays;
/**
* Array of vertex array state. This array contains all of the valid
* vertex arrays. If a vertex array isn't in this array, then it isn't
* valid. For example, if an implementation does not support
* EXT_fog_coord, there won't be a GL_FOG_COORD_ARRAY entry in this
* array.
*/
struct array_state *arrays;
/**
* Number of currently enabled client-side arrays. The value of this
* field is only valid if \c <API key> is true.
*/
size_t <API key>;
/**
* \name ARRAY_INFO cache.
*
* These fields track the state of the ARRAY_INFO cache. The
* \c <API key> is the size of the actual data stored in
* \c array_info_cache. \c <API key> is the size of
* the buffer. This will always be greater than or equal to
* \c <API key>.
*
* \note
* There are some bytes of extra data before \c array_info_cache that is
* used to hold the header for RenderLarge commands. This is
* \b not included in \c <API key> or
* \c <API key>. \c <API key> stores a
* pointer to the true start of the buffer (i.e., what malloc returned).
*/
size_t <API key>;
size_t <API key>;
void *array_info_cache;
void *<API key>;
/**
* Is the cache of ARRAY_INFO data valid? The cache can become invalid
* when one of several state changes occur. Among these chages are
* modifying the array settings for an enabled array and enabling /
* disabling an array.
*/
GLboolean <API key>;
/**
* Is it possible to use the GL 1.1 / EXT_vertex_arrays protocol? Use
* of this protocol is disabled with really old servers (i.e., servers
* that don't support GL 1.1 or EXT_vertex_arrays) or when an environment
* variable is set.
*
* \todo
* GL 1.1 and EXT_vertex_arrays use identical protocol, but have different
* opcodes for \c glDrawArrays. For servers that advertise one or the
* other, there should be a way to select which opcode to use.
*/
GLboolean <API key>;
/**
* Is it possible to use the new GL X.X / <API key>
* protocol?
*
* \todo
* This protocol has not yet been defined by the ARB, but is currently a
* work in progress. This field is a place-holder.
*/
GLboolean <API key>;
/**
* Active texture unit set by \c <API key>.
*
* \sa <API key>
*/
unsigned active_texture_unit;
/**
* Number of supported texture units. Even if ARB_multitexture /
* GL 1.3 are not supported, this will be at least 1. When multitexture
* is supported, this will be the value queried by calling
* \c glGetIntegerv with \c <API key>.
*
* \todo
* Investigate if this should be the value of \c <API key>
* instead (if GL 2.0 / ARB_fragment_shader / <API key> /
* NV_fragment_program are supported).
*/
unsigned num_texture_units;
/**
* Number of generic vertex program attribs. If <API key>
* is not supported, this will be zero. Otherwise it will be the value
* queries by calling \c glGetProgramiv with \c <API key>
* and \c <API key>.
*/
unsigned <API key>;
/**
* \n Methods for implementing various GL functions.
*
* These method pointers are only valid \c <API key> is set.
* When each function starts, it much check \c <API key>.
* If it is not set, it must call \c <API key> and call
* the new method.
*
* \sa <API key>
*
* \todo
* Write code to plug these functions directly into the dispatch table.
*/
void (*DrawArrays) (GLenum, GLint, GLsizei);
void (*DrawElements) (GLenum mode, GLsizei count, GLenum type,
const GLvoid * indices);
struct array_stack_state *stack;
unsigned <API key>[<API key>];
unsigned stack_index;
};
#endif /* <API key> */ |
/* Check that heap-structure is ok */
#include "heapdef.h"
static int check_one_key(HP_KEYDEF *keydef, uint keynr, ulong records,
ulong blength, my_bool print_status);
static int check_one_rb_key(HP_INFO *info, uint keynr, ulong records,
my_bool print_status);
/*
Check if keys and rows are ok in a heap table
SYNOPSIS
heap_check_heap()
info Table handler
print_status Prints some extra status
NOTES
Doesn't change the state of the table handler
RETURN VALUES
0 ok
1 error
*/
int heap_check_heap(HP_INFO *info, my_bool print_status)
{
int error;
uint key;
ulong records=0, deleted=0, pos, next_block;
HP_SHARE *share=info->s;
HP_INFO save_info= *info; /* Needed because scan_init */
DBUG_ENTER("heap_check_heap");
for (error=key= 0 ; key < share->keys ; key++)
{
if (share->keydef[key].algorithm == HA_KEY_ALG_BTREE)
error|= check_one_rb_key(info, key, share->records, print_status);
else
error|= check_one_key(share->keydef + key, key, share->records,
share->blength, print_status);
}
/*
This is basicly the same code as in hp_scan, but we repeat it here to
get shorter DBUG log file.
*/
for (pos=next_block= 0 ; ; pos++)
{
if (pos < next_block)
{
info->current_ptr+= share->block.recbuffer;
}
else
{
next_block+= share->block.records_in_block;
if (next_block >= share->records+share->deleted)
{
next_block= share->records+share->deleted;
if (pos >= next_block)
break; /* End of file */
}
}
hp_find_record(info,pos);
if (!info->current_ptr[share->reclength])
deleted++;
else
records++;
}
if (records != share->records || deleted != share->deleted)
{
DBUG_PRINT("error",("Found rows: %lu (%lu) deleted %lu (%lu)",
records, (ulong) share->records,
deleted, (ulong) share->deleted));
error= 1;
}
*info= save_info;
DBUG_RETURN(error);
}
static int check_one_key(HP_KEYDEF *keydef, uint keynr, ulong records,
ulong blength, my_bool print_status)
{
int error;
ulong i,found,max_links,seek,links;
ulong rec_link; /* Only used with debugging */
ulong hash_buckets_found;
HASH_INFO *hash_info;
error=0;
hash_buckets_found= 0;
for (i=found=max_links=seek=0 ; i < records ; i++)
{
hash_info=hp_find_hash(&keydef->block,i);
if (hash_info->hash_of_key != hp_rec_hashnr(keydef, hash_info->ptr_to_rec))
{
DBUG_PRINT("error",
("Found row with wrong hash_of_key at position %lu", i));
error= 1;
}
if (hp_mask(hash_info->hash_of_key, blength, records) == i)
{
found++;
seek++;
links=1;
while ((hash_info=hash_info->next_key) && found < records + 1)
{
seek+= ++links;
if ((rec_link= hp_mask(hash_info->hash_of_key, blength, records)) != i)
{
DBUG_PRINT("error",
("Record in wrong link: Link %lu Record: 0x%lx Record-link %lu",
i, (long) hash_info->ptr_to_rec, rec_link));
error=1;
}
else
found++;
}
if (links > max_links) max_links=links;
hash_buckets_found++;
}
}
if (found != records)
{
DBUG_PRINT("error",("Found %ld of %ld records", found, records));
error=1;
}
if (keydef->hash_buckets != hash_buckets_found)
{
DBUG_PRINT("error",("Found %ld buckets, stats shows %ld buckets",
hash_buckets_found, (long) keydef->hash_buckets));
error=1;
}
DBUG_PRINT("info",
("key: %u records: %ld seeks: %lu max links: %lu "
"hitrate: %.2f buckets: %lu",
keynr, records,seek,max_links,
(float) seek / (float) (records ? records : 1),
hash_buckets_found));
if (print_status)
printf("Key: %u records: %ld seeks: %lu max links: %lu "
"hitrate: %.2f buckets: %lu\n",
keynr, records, seek, max_links,
(float) seek / (float) (records ? records : 1),
hash_buckets_found);
return error;
}
static int check_one_rb_key(HP_INFO *info, uint keynr, ulong records,
my_bool print_status)
{
HP_KEYDEF *keydef= info->s->keydef + keynr;
int error= 0;
ulong found= 0;
uchar *key, *recpos;
uint key_length;
uint not_used[2];
if ((key= tree_search_edge(&keydef->rb_tree, info->parents,
&info->last_pos, offsetof(TREE_ELEMENT, left))))
{
do
{
memcpy(&recpos, key + (*keydef->get_key_length)(keydef,key), sizeof(uchar*));
key_length= hp_rb_make_key(keydef, info->recbuf, recpos, 0);
if (ha_key_cmp(keydef->seg, (uchar*) info->recbuf, (uchar*) key,
key_length, SEARCH_FIND | SEARCH_SAME, not_used))
{
error= 1;
DBUG_PRINT("error",("Record in wrong link: key: %u Record: 0x%lx\n",
keynr, (long) recpos));
}
else
found++;
key= tree_search_next(&keydef->rb_tree, &info->last_pos,
offsetof(TREE_ELEMENT, left),
offsetof(TREE_ELEMENT, right));
} while (key);
}
if (found != records)
{
DBUG_PRINT("error",("Found %lu of %lu records", found, records));
error= 1;
}
if (print_status)
printf("Key: %d records: %ld\n", keynr, records);
return error;
} |
<?php
defined('_JEXEC') or die;
$listOrder = $this->escape($this->state->get('list.ordering'));
$listDirn = $this->escape($this->state->get('list.direction'));
?>
<form action="<?php echo JRoute::_('index.php?option=com_cache'); ?>" method="post" name="adminForm" id="adminForm">
<?php if (!empty( $this->sidebar)) : ?>
<div id="j-sidebar-container" class="span2">
<?php echo $this->sidebar; ?>
</div>
<div id="j-main-container" class="span10">
<?php else : ?>
<div id="j-main-container">
<?php endif;?>
<fieldset id="filter-bar">
<legend class="element-invisible"><?php echo JText::_('<API key>'); ?></legend>
<div class="filter-select fltrt">
<label class="selectlabel" for="client_id">
<?php echo JText::_('<API key>'); ?>
</label>
<select name="client_id" id="client_id">
<?php echo JHtml::_('select.options', CacheHelper::getClientOptions(), 'value', 'text', $this->state->get('client_id'));?>
</select>
<button type="submit" id="filter-go">
<?php echo JText::_('JSUBMIT'); ?></button>
</div>
</fieldset>
<div class="clr"> </div>
<table class="adminlist">
<thead>
<tr>
<th class="checkmark-col">
<input type="checkbox" name="checkall-toggle" value="" title="<?php echo JText::_('JGLOBAL_CHECK_ALL'); ?>" onclick="Joomla.checkAll(this)" />
</th>
<th class="title nowrap">
<?php echo JHtml::_('grid.sort', 'COM_CACHE_GROUP', 'group', $listDirn, $listOrder); ?>
</th>
<th class="width-5 center nowrap">
<?php echo JHtml::_('grid.sort', '<API key>', 'count', $listDirn, $listOrder); ?>
</th>
<th class="width-10 center">
<?php echo JHtml::_('grid.sort', 'COM_CACHE_SIZE', 'size', $listDirn, $listOrder); ?>
</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach ($this->data as $folder => $item) : ?>
<tr class="row<?php echo $i % 2; ?>">
<td>
<input type="checkbox" id="cb<?php echo $i;?>" name="cid[]" value="<?php echo $item->group; ?>" onclick="Joomla.isChecked(this.checked);" />
</td>
<td>
<span class="bold">
<?php echo $item->group; ?>
</span>
</td>
<td class="center">
<?php echo $item->count; ?>
</td>
<td class="center">
<?php echo JHtml::_('number.bytes', $item->size*1024); ?>
</td>
</tr>
<?php $i++; endforeach; ?>
</tbody>
</table>
<?php echo $this->pagination->getListFooter(); ?>
<input type="hidden" name="task" value="" />
<input type="hidden" name="boxchecked" value="0" />
<input type="hidden" name="client" value="<?php echo $this->client->id;?>" />
<input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>" />
<input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form> |
#include "DibBridgeConfig.h" /* Must be first include of all SDK files - Defines compilation options */
#if (USE_DRAGONFLY == 1)
#include "<API key>.h"
#include "DibBridgeCommon.h"
#include "DibBridgeTarget.h"
#include "<API key>.h"
#include "DibBridgeTestIf.h"
#include "DibBridge.h"
#include "<API key>.h"
#include "<API key>.h"
#include "DibBridgeDragonfly.h"
#include "<API key>.h"
#include "DibBridgeData.h"
#if (<API key> == 0)
#include "<API key>.h"
#endif /*<API key> */
#if (DIB_CHECK_DATA == 1)
#include "<API key>.h"
static void <API key>(struct DibBridgeContext *pContext, uint32_t * RxData);
#endif
#define MAC_IRQ (1 << 1)
#define IRQ_POL_MSK (1 << 4)
void IntBridgeGetCpt(struct DibBridgeContext *pContext, uint16_t * Data);
/* Bridge 2 Driver message handling function prototype */
void DibB2DFwdMsg(struct DibBridgeContext *pContext, uint32_t Nb, uint16_t * buf);
static uint32_t <API key>(struct DibBridgeContext *pContext, uint32_t * Data);
static DIBDMA <API key>(struct DibBridgeContext *pContext, struct MsgHeader * pHeader, uint32_t * RxData);
static uint32_t <API key>(struct DibBridgeContext *pContext, uint32_t Addr, uint8_t ByteMode);
/**
* Retreive the number of free bytes in the HOST mailbox
*/
static __inline uint32_t <API key>(uint32_t rdptr, uint32_t wrptr, uint32_t Size)
{
uint32_t free;
if(rdptr == wrptr)
free = Size;
else if(rdptr > wrptr)
free = (rdptr-wrptr);
else
free = Size-(wrptr - rdptr);
DIB_ASSERT(free >= 4);
free -= 4;
return free;
}
/**
* Retreive the number of available bytes in the HOST mailbox
*/
static __inline uint32_t <API key>(uint32_t rdptr, uint32_t wrptr, uint32_t Size)
{
uint32_t nbbytes;
if(rdptr == wrptr)
nbbytes = 0;
else if(wrptr > rdptr)
nbbytes = (wrptr-rdptr);
else
nbbytes = Size-(rdptr - wrptr);
return nbbytes;
}
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, struct DibBridgeDmaCtx * pDmaCtx)
{
DIBSTATUS Status = DIBSTATUS_SUCCESS;
unsigned char Disable32bitDma = 0;
#if (HIGH_SPEED_DMA == 1)
/*** Voyager Host issue is supported => Disable 32 bits DMA when the chip used is Voyager ***/
#if (ENG3_COMPATIBILITY == 1)
if (pContext->DibChip == DIB_VOYAGER)
{
Disable32bitDma = 1;
}
#else
/*** Voyager Host issue is not supported => 32 bits DMA can be used ***/
Disable32bitDma = 0;
#endif
#else
/*** HIGH_SPEED_DMA not supported ***/
Disable32bitDma = 1;
#endif
/*** Use 32 bits transfer. Check alignment ***/
if (Disable32bitDma == 0)
{
uint32_t NbBytes, j;
pDmaCtx->Mode = <API key>;
pDmaCtx->DmaSize = pDmaCtx->DmaLen;
/* particular case where only one 32 bit word is involved */
if((pDmaCtx->ChipAddr & 0xFFFFFFFC) == (((pDmaCtx->ChipAddr+pDmaCtx->DmaSize-1) & 0xFFFFFFFC)))
{
for(j=0; j<pDmaCtx->DmaSize; j++)
{
if(pDmaCtx->Dir == DIBBRIDGE_DMA_READ)
Status = DibBridgeReadReg8(pContext, pDmaCtx->ChipAddr + j, pDmaCtx->pHostAddr + j);
else
Status = DibBridgeWriteReg8(pContext, pDmaCtx->ChipAddr + j, pDmaCtx->pHostAddr[j]);
if(Status != DIBSTATUS_SUCCESS)
{
DIB_DEBUG(PORT_ERR, (CRB "<API key> Failed Idx%d Nb %d " CRA, j, pDmaCtx->DmaSize));
return Status;
}
}
pDmaCtx->ChipAddr += pDmaCtx->DmaSize;
pDmaCtx->pHostAddr += pDmaCtx->DmaSize;
pDmaCtx->DmaSize = 0;
}
/* general case: alignement issues are at the beginning and at the end */
else
{
/* beginning */
if(pDmaCtx->ChipAddr & 3)
{
NbBytes = 4 - (pDmaCtx->ChipAddr & 3);
for(j=0; j<NbBytes; j++)
{
if(pDmaCtx->Dir == DIBBRIDGE_DMA_READ)
Status = DibBridgeReadReg8(pContext, pDmaCtx->ChipAddr + j, pDmaCtx->pHostAddr + j);
else
Status = DibBridgeWriteReg8(pContext, pDmaCtx->ChipAddr + j, pDmaCtx->pHostAddr[j]);
if(Status != DIBSTATUS_SUCCESS)
{
DIB_DEBUG(PORT_ERR, (CRB "<API key> Failed Idx%d Nb %d " CRA, j, NbBytes));
return Status;
}
}
pDmaCtx->DmaSize -= NbBytes;
pDmaCtx->ChipAddr += NbBytes;
pDmaCtx->pHostAddr += NbBytes;
}
/* at the end */
if((pDmaCtx->ChipAddr+pDmaCtx->DmaSize) & 3)
{
NbBytes = ((pDmaCtx->ChipAddr + pDmaCtx->DmaSize) & 3);
/* do not transfert these NbBytes in the main transfert */
pDmaCtx->DmaSize -= NbBytes;
for(j=0; j<NbBytes; j++)
{
if(pDmaCtx->Dir == DIBBRIDGE_DMA_READ)
Status = DibBridgeReadReg8(pContext, pDmaCtx->ChipAddr + pDmaCtx->DmaSize + j, pDmaCtx->pHostAddr + pDmaCtx->DmaSize + j);
else
Status = DibBridgeWriteReg8(pContext, pDmaCtx->ChipAddr + pDmaCtx->DmaSize + j, pDmaCtx->pHostAddr[j + pDmaCtx->DmaSize]);
if(Status != DIBSTATUS_SUCCESS)
{
DIB_DEBUG(PORT_ERR, (CRB "<API key> Failed Idx%d Nb %d " CRA, j, NbBytes));
return Status;
}
}
}
}
}
else
{
/*** Force 8 bits transfers ***/
pDmaCtx->Mode = <API key>;
pDmaCtx->DmaSize = pDmaCtx->DmaLen;
}
/** Compute formatted chip address */
pDmaCtx->FmtChipAddr = <API key>(pContext, pDmaCtx->ChipAddr, pDmaCtx->Mode);
return Status;
}
DIBDMA <API key>(struct DibBridgeContext *pContext, struct DibBridgeDmaCtx * pDmaCtx)
{
DIBDMA rc;
rc = <API key>(pContext, pDmaCtx);
return rc;
}
/**
* Sends a message to SPARC
* Warning!!!!!! the message MUST be a set of uint32_t or int32_t, and the use of
* bit Mask is forbidden cause behave differently on little and big endian arch
* @param pContext: bridge context
* param Data: aligned 32 bits Data pointer. Reference the whole message
* param Size: number of bytes of the message
* WARNING: the Data buffer can be swapped by this function and should not be used after this call!!!
*/
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, uint32_t * Data, uint32_t Size)
{
uint8_t Status = DIBSTATUS_ERROR;
int32_t MaxRetries = <API key>;
uint32_t Rdptr;
uint32_t Wrptr;
uint32_t Free;
DIB_ASSERT((Size & 3) == 0);
DIB_ASSERT((Data));
DIB_ASSERT(Size >= 4);
DIB_DEBUG(MAILBOX_LOG, (CRB "+SendMsg() Request=> Msg : %x, Size %d" CRA, *Data, Size));
/* Check if there is space in msgbox */
if((Status = DibBridgeReadReg32(pContext, pContext->DragonflyRegisters.MacMbxWrPtrReg, &Wrptr)) != DIBSTATUS_SUCCESS)
goto End;
DIB_ASSERT((Wrptr & 3) == 0);
/* Ensure we have enought place in the mailbow to post this message */
while(MaxRetries > 0)
{
/* Get MAC read pointer (implemented as follower) */
if((Status = <API key>(pContext, pContext->DragonflyRegisters.MacMbxRdPtrReg, &Rdptr)) != DIBSTATUS_SUCCESS)
goto End;
DIB_ASSERT((Rdptr & 3) == 0);
DIB_ASSERT((Rdptr >= pContext->DragonflyRegisters.MacMbxStart && Rdptr < pContext->DragonflyRegisters.MacMbxEnd));
/* Do not allow to write last byte, this is to avoid overflow when rd==wr msg box is empty */
Free = <API key>(Rdptr, Wrptr, pContext->DragonflyRegisters.MacMbxSize);
/* get the number of 32 bits words available */
if(Size > Free)
{
DibMSleep(1);
MaxRetries
}
else
{
/* break successfully the loop */
MaxRetries=-1;
}
}
if(MaxRetries < 0)
{
struct MsgHeader MsgIn;
DIB_DEBUG(MAILBOX_LOG, (CRB "SendMsg() %d bytes available in msg box." CRA, Free));
SerialBufInit(&pContext->RxSerialBuf, Data, 32);
MsgHeaderUnpack(&pContext->RxSerialBuf, &MsgIn);
if(Wrptr + Size > pContext->DragonflyRegisters.MacMbxEnd)
{
uint32_t len;
/* Transfer must be done in two step */
len = pContext->DragonflyRegisters.MacMbxEnd - Wrptr;
if((Status = <API key>(pContext, Wrptr, Data, len)) != DIBSTATUS_SUCCESS)
goto End;
if((Status = <API key>(pContext, pContext->DragonflyRegisters.MacMbxStart, Data + (len >> 2), Size - len)) != DIBSTATUS_SUCCESS)
goto End;
Wrptr = pContext->DragonflyRegisters.MacMbxStart + Size - len;
}
else
{
/* Transfer can be done in a single step */
if((Status = <API key>(pContext, Wrptr, Data, Size)) != DIBSTATUS_SUCCESS)
goto End;
Wrptr += Size;
}
if(Wrptr == pContext->DragonflyRegisters.MacMbxEnd)
Wrptr = pContext->DragonflyRegisters.MacMbxStart;
/* Update rd pointer (this trigger an irq in the firmware) */
Status = DibBridgeWriteReg32(pContext, pContext->DragonflyRegisters.MacMbxWrPtrReg, Wrptr);
if (MsgIn.MsgId == <API key>)
DibMSleep(50);
}
else
{
DIB_DEBUG(MAILBOX_ERR, (CRB "-SendMsg() Failed Msg box full" CRA));
Status = DIBSTATUS_ERROR;
}
DIB_DEBUG(MAILBOX_LOG, (CRB "-SendMsg()" CRA));
End:
return Status;
}
static __inline DIBSTATUS <API key>(struct DibBridgeContext *pContext)
{
DIBSTATUS status = DIBSTATUS_SUCCESS;
#if CLEAR_HOST_IRQ_MODE == CLEAR_BY_MESSAGE
/* Workaround for concurrent access to apb and demod */
struct MsgHeader MsgOut;
DIB_DEBUG(MAILBOX_LOG, (CRB "<API key>" CRA));
/* Message header */
MsgOut.Type = MSG_TYPE_MAC;
MsgOut.MsgId = <API key>;
MsgOut.MsgSize = GetWords(MsgHeaderBits, 32);
MsgOut.ChipId = MASTER_IDENT;
MsgHeaderPackInit(&MsgOut, &pContext->TxSerialBuf);
status = <API key>(pContext, pContext->TxBuffer, MsgOut.MsgSize * 4);
#endif
#if CLEAR_HOST_IRQ_MODE == CLEAR_BY_REGISTER
uint32_t tmp;
status = DibBridgeReadReg32(pContext, REG_HIF_INT_STAT, &tmp); /* Clear HW IRQ */
#endif
return status;
}
static DIBDMA <API key>(struct DibBridgeContext *pContext)
{
DIBDMA DmaStatus = DIB_NO_IRQ;
struct MsgHeader MsgIn;
uint32_t * RxData;
if(pContext->RxCnt == 0)
{
#if (INTERRUPT_MODE != USE_POLLING)
/* clear hardware interrrupt in anycase since we received interrupt */
if(<API key>(pContext) != DIBSTATUS_SUCCESS)
return DIB_DEV_FAILED; /* Device failed to respond */
#endif
DIB_ASSERT(pContext->HostBuffer);
pContext->RxOffset = 0;
/* Read N messages if possible */
pContext->RxCnt = <API key>(pContext, pContext->HostBuffer);
}
/* Process the N messages */
if(pContext->RxCnt > 0)
{
RxData = &pContext->HostBuffer[pContext->RxOffset];
SerialBufInit(&pContext->RxSerialBuf, RxData, 32);
MsgHeaderUnpack(&pContext->RxSerialBuf, &MsgIn);
SerialBufRestart(&pContext->RxSerialBuf);
if((pContext->RxCnt < (MsgIn.MsgSize>>2)) || (MsgIn.MsgSize > pContext->DragonflyRegisters.HostMbxSize))
{
DIB_DEBUG(MAILBOX_ERR, (CRB "+RecvMsg() => ERROR: MsgSize %d" CRA, MsgIn.MsgSize));
DIB_DEBUG(MAILBOX_ERR,(CRB "NbBytes received %d" CRA,pContext->RxCnt));
pContext->RxCnt = 0;
}
else
{
DmaStatus = <API key>(pContext, &MsgIn, RxData);
pContext->RxOffset += MsgIn.MsgSize;
pContext->RxCnt -= (MsgIn.MsgSize << 2);
}
}
return DmaStatus;
}
/**
* Reads ONE message from one of the risc
* @param pContext: bridge context
* @param Data: Buffer owning the message, header included
* @param nb_words: number of 32 bit words available in the mailbox
* @return number of 32 bit words of the message
*/
static uint32_t <API key>(struct DibBridgeContext *pContext, uint32_t * Data)
{
uint32_t NbBytes;
uint32_t rdptr;
uint32_t wrptr;
DIBSTATUS Status = DIBSTATUS_SUCCESS;
/* Check if there is space in msgbox */
if((Status = DibBridgeReadReg32(pContext, pContext->DragonflyRegisters.HostMbxRdPtrReg, &rdptr) != DIBSTATUS_SUCCESS))
goto End;
if((Status = <API key>(pContext, pContext->DragonflyRegisters.HostMbxWrPtrReg, &wrptr) != DIBSTATUS_SUCCESS))
goto End;
DIB_ASSERT((wrptr & 3) == 0);
NbBytes = <API key>(rdptr, wrptr, pContext->DragonflyRegisters.HostMbxSize);
DIB_ASSERT((NbBytes & 3) == 0);
if(NbBytes > 0)
{
uint32_t len = 0;
DIB_DEBUG(IRQ_LOG, (CRB "IRQ HOST, NbBytes in mailbox = %d" CRA, NbBytes));
if(rdptr + NbBytes > pContext->DragonflyRegisters.HostMbxEnd)
{
/* The mailbox must be read in two parts */
len = pContext->DragonflyRegisters.HostMbxEnd - rdptr;
if((Status = <API key>(pContext, rdptr, Data, len)) != DIBSTATUS_SUCCESS)
goto End;
if((Status = <API key>(pContext, pContext->DragonflyRegisters.HostMbxStart, Data + (len / 4), NbBytes - len)) != DIBSTATUS_SUCCESS)
goto End;
}
else
{
/* The mailbox can be read in one pass */
if((Status = <API key>(pContext, rdptr, Data, NbBytes)) != DIBSTATUS_SUCCESS)
goto End;
}
if((Status = DibBridgeWriteReg32(pContext, pContext->DragonflyRegisters.HostMbxRdPtrReg, wrptr) != DIBSTATUS_SUCCESS))
goto End;
}
End:
if(Status == DIBSTATUS_SUCCESS)
return NbBytes;
else
return 0;
}
#if (mSDK==0)
static DIBDMA <API key>(struct DibBridgeContext * pContext)
{
struct DibBridgeDmaFlags flags;
struct MsgData MsgIn;
DIBDMA DmaStat;
MsgDataUnpack(&pContext->RxSerialBuf, &MsgIn);
/*
struct timeval Time;
gettimeofday(&Time, NULL);
*/
flags.Type = MSG_DATA_TYPE(MsgIn.Format);
flags.ItemHdl = MSG_DATA_ITEM_INDEX(MsgIn.Format);
flags.BlockId = MSG_DATA_BLOCK_ID(MsgIn.Format);
flags.BlockType= MSG_DATA_BLOCK_TYPE(MsgIn.Format);
flags.FirstFrag= MSG_DATA_FIRST_FRAG(MsgIn.Format);
flags.LastFrag = MSG_DATA_LAST_FRAG(MsgIn.Format);
flags.NbRows = MSG_DATA_NB_ROWS(MsgIn.Format);
flags.FrameId = MSG_DATA_FRAME_ID(MsgIn.Format);
if(flags.Type == FORMAT_MPE || flags.Type == FORMAT_LAST_FRG || flags.Type == FORMAT_FLUSH_SVC)
{
flags.Prefetch = MSG_DATA_BLOCK_TYPE(MsgIn.Format);
}
else
{
flags.Prefetch = 0;
}
DIB_DEBUG(RAWTS_LOG, (CRB "Min %d Max %d Addr %08x Len %d Rows %d FLAGS : s %d t %d b %d ff %d lf %d frm %d fw %08x" CRA,
MsgIn.Min, MsgIn.Max, MsgIn.Add, MsgIn.Len, flags.NbRows,
flags.ItemHdl, flags.Type, flags.BlockId, flags.FirstFrag, flags.LastFrag, flags.FrameId, MsgIn.Min));
/*
DIB_DEBUG(RAWTS_LOG, (CRB "%d : %d IN_MSG_DATA Type %d len %u" CRA, (int)Time.tv_sec, (int)Time.tv_usec, flags.Type, MsgIn.Len));
DIB_DEBUG(RAWTS_ERR, (CRB "%d : %f IN_MSG_DATA Type %d len %u" CRA, (int)Time.tv_sec, (float)((float)Time.tv_usec/1000.0f), flags.Type, MsgIn.Len));*/
DmaStat = <API key>(pContext, MsgIn.Min, MsgIn.Max, MsgIn.Add, MsgIn.Len, &flags);
if(DmaStat == DIB_NO_DMA)
{
DIB_DEBUG(MAILBOX_LOG, (CRB "Spec: Received unknown Type for Data message: %d" CRA, flags.Type));
}
return DmaStat; /* Tells do we have a pending DMA or not */
}
#endif
static DIBDMA <API key>(struct DibBridgeContext *pContext, struct MsgHeader * pHeader, uint32_t * RxData)
{
if(pHeader->MsgSize > 0)
{
DIB_DEBUG(MAILBOX_LOG, (CRB "+RecvMsg() => Msg : id %d, Size %d" CRA, pHeader->MsgId, pHeader->MsgSize));
/* Now we have one message, let's check the Type of it */
DIB_DEBUG(IRQ_LOG, (CRB "IRQ: MSG %d, Size %d" CRA, pHeader->MsgId, pHeader->MsgSize));
/* It can be either Data (0), CPT (1) or a message to passed up (>= 2) */
#if (mSDK == 0)
if(pHeader->MsgId == IN_MSG_DATA && pHeader->Type == MSG_TYPE_MAC)
{
/* This is Data message */
return <API key>(pContext);
}
/*This is an Info message */
else if(pHeader->MsgId == IN_MSG_FRAME_INFO && pHeader->Type == MSG_TYPE_MAC)
{
return <API key>(pContext, RxData, pHeader->MsgSize);
}
else if(pHeader->MsgId == IN_MSG_CTL_MONIT && pHeader->Type == MSG_TYPE_MAC)
{
#if (DIB_CHECK_DATA == 1)
/* Clear Bridge checker statistics */
<API key>(pContext, RxData);
#endif
}
else
{
/* flush buffers after item removal */
if(pHeader->MsgId == <API key> && pHeader->Type == MSG_TYPE_MAC)
<API key>(pContext);
/* Other: the whole message will be passed up */
DIB_DEBUG(MAILBOX_LOG, (CRB "MSG IN (%d) forwarded " CRA, pHeader->MsgId));
DibB2DFwdMsg(pContext, (pHeader->MsgSize << 2) /*in bytes*/, (uint16_t*)RxData);
}
#else
DIB_DEBUG(MAILBOX_LOG, (CRB "MSG IN (%d) forwarded " CRA, pHeader->MsgId));
DibB2DFwdMsg(pContext, (pHeader->MsgSize << 2) /*in bytes*/, (uint16_t*)RxData);
#endif
}
return DIB_NO_DMA;
}
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, struct DibBridgeDmaFlags *pFlags, uint8_t failed)
{
struct MsgAckData MsgOut;
DIB_DEBUG(MAILBOX_LOG, (CRB "" CRA));
DIB_DEBUG(MAILBOX_LOG, (CRB "<API key>" CRA));
/* Message header */
MsgOut.Head.Type = MSG_TYPE_MAC;
MsgOut.Head.MsgId = (failed > 1) ? 1 : 0; /* DF1 - RESET ; DF0 - ACK */
MsgOut.Head.MsgSize = GetWords(MsgAckDataBits, 32);
MsgOut.Head.ChipId = MASTER_IDENT;
MsgOut.Status = failed;
/*pContext->FecOffset is not used for dragonfly based chipset */
MsgOut.Format = SET_DATA_FORMAT(pFlags->ItemHdl,
pFlags->Type,
pFlags->FirstFrag,
pFlags->LastFrag,
pFlags->NbRows,
pFlags->BlockType,
pFlags->BlockId,
pFlags->FrameId);
MsgAckDataPackInit(&MsgOut, &pContext->TxSerialBuf);
return <API key>(pContext, pContext->TxBuffer, MsgOut.Head.MsgSize * 4);
}
#if (mSDK == 0)
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, struct DibBridgeDmaCtx * pDmaCtx)
{
DIBSTATUS ret = DIBSTATUS_ERROR;
/* every Data message need to be acknowledged */
ret = <API key>(pContext, &pDmaCtx->DmaFlags, 0);
if(ret == DIBSTATUS_SUCCESS)
{
/* process dma independantly of the architecture */
ret = <API key>(pContext, pDmaCtx);
}
return ret;
}
#endif
static uint32_t <API key>(struct DibBridgeContext *pContext, uint32_t Addr, uint8_t ByteMode)
{
switch(pContext->HostIfMode)
{
case eSRAM:
return DF_ADDR_TO_SRAM(Addr, ByteMode, 1, 0);
case eSDIO:
return DF_ADDR_TO_SDIO(Addr, 1);
case eSPI:
return DF_ADDR_TO_SPI(Addr, ByteMode, 1);
default:
return Addr;
}
}
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, uint32_t Address, uint8_t *b, uint32_t len)
{
uint8_t wa[4] = { 0 };
uint32_t i, FormattedAddr;
DIBSTATUS ret = DIBSTATUS_SUCCESS;
for (i = 0; i < len; i += 2)
{
FormattedAddr = <API key>(pContext, Address + i, <API key>);
wa[0] = b[i];
wa[1] = b[i + 1];
if((ret = <API key>(pContext, FormattedAddr, <API key>, 4, wa) != DIBSTATUS_SUCCESS))
break;
}
return ret;
}
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, uint32_t Address, uint8_t *b, uint32_t len)
{
uint8_t wa[4] = { 0 };
uint32_t i, FormattedAddress;
DIBSTATUS ret = DIBSTATUS_SUCCESS;
for (i = 0; i < len; i += 2)
{
FormattedAddress = <API key>(pContext, Address + i, <API key>);
if((ret = DibBridgeTargetRead(pContext, FormattedAddress, <API key>, 4, wa) != DIBSTATUS_SUCCESS))
break;
b[i] = wa[0];
b[i+1] = wa[1];
}
return ret;
}
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, uint8_t ByteMode, uint32_t * Addr, uint8_t IsWriteAccess, uint8_t * Buf, uint32_t Cnt)
{
if(<API key>(*Addr, ByteMode))
{
if(IsWriteAccess)
return <API key>(pContext, *Addr, Buf, Cnt);
else
return <API key>(pContext, *Addr, Buf, Cnt);
}
/* address formating */
*Addr = <API key>(pContext, *Addr, ByteMode);
return DIBSTATUS_CONTINUE;
}
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, uint8_t ByteMode, uint32_t * Addr, uint8_t IsWriteAccess, uint8_t * Buf, uint32_t Cnt)
{
return DIBSTATUS_SUCCESS;
}
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, uint8_t ByteMode, uint32_t * Addr, uint8_t IsWriteAccess, uint8_t * Buf, uint32_t Cnt)
{
/* address formating */
*Addr = <API key>(pContext, *Addr, ByteMode);
return DIBSTATUS_CONTINUE;
}
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, uint8_t ByteMode, uint32_t * Addr, uint8_t IsWriteAccess, uint8_t * Buf, uint32_t Cnt)
{
return DIBSTATUS_SUCCESS;
}
static uint32_t <API key>(struct DibBridgeContext *pContext, uint32_t InFmtAddr, int32_t Offset)
{
uint32_t OutFmtAddr = 0, ByteMode, Addr;
switch(pContext->HostIfMode)
{
case eSRAM:
Addr = DF_SRAM_TO_ADDR(InFmtAddr);
Addr += Offset;
ByteMode = (InFmtAddr & 0x06000000) >> 25;
OutFmtAddr = DF_ADDR_TO_SRAM(Addr, ByteMode, 1, 0);
break;
case eSDIO:
Addr = DF_SDIO_TO_ADDR(InFmtAddr);
Addr += Offset;
OutFmtAddr = DF_ADDR_TO_SDIO(Addr, 1);
break;
case eI2C:
OutFmtAddr = InFmtAddr+Offset;
break;
case eSPI:
Addr = DF_SPI_TO_ADDR(InFmtAddr);
Addr += Offset;
ByteMode = (InFmtAddr & 0x30000000) >> 28;
OutFmtAddr = DF_ADDR_TO_SPI(Addr, ByteMode, 1);
break;
default:
break;
}
return OutFmtAddr;
}
/*
void DisplaySliceBuf(uint8_t *pSliceBuf, uint32_t NbRows, uint32_t NbCols)
{
uint32_t i,j;
printf(CRB "" CRA);
for(i=0; i<NbRows; i++)
{
for(j=0; j<NbCols; j++)
{
printf("%02x ",pSliceBuf[i+j*NbRows]);
}
printf(CRB "" CRA);
}
printf(CRB "" CRA);
}
*/
static uint8_t <API key>(struct DibBridgeContext *pContext)
{
return <API key>;
}
#if (DIB_CHECK_DATA == 1)
static void <API key>(struct DibBridgeContext *pContext, uint32_t * RxData)
{
enum DibDataType FilterType;
struct MsgCtrlMonit Msg;
ELEM_HDL ItemHdl;
FILTER_HDL FilterHdl;
MsgCtrlMonitUnpack(&pContext->RxSerialBuf, &Msg);
ItemHdl = Msg.ItemId;
/* When ClearMonit message, clear Bridge monitoring info */
if(Msg.Cmd == 1)
{
FilterHdl = pContext->ItSvc[ItemHdl].FilterParent;
FilterType = pContext->FilterInfo[ItemHdl].DataType;
/* DVB-H: Clear IP and RTP checker data */
if((FilterType == eMPEFEC) || (FilterType == eMPEIFEC))
{
pContext->ItSvc[ItemHdl].CcFailCnt = 0;
pContext->ItSvc[ItemHdl].ErrCnt = 0;
pContext->ItSvc[ItemHdl].CurCc = 0xffff;
}
if((FilterType == eDAB))
{
pContext->ItSvc[ItemHdl].CcFailCnt = 0;
pContext->ItSvc[ItemHdl].ErrCnt = 0;
pContext->ItSvc[ItemHdl].CurCc = 0;
pContext->ItSvc[ItemHdl].DataLenRx = 0;
pContext->ItSvc[ItemHdl].NbMaxFrames = 0;
}
#if DIB_CHECK_CMMB_DATA == 1
else if(FilterType == eCMMBSVC)
{
pContext->ItSvc[ItemHdl].CcFailCnt = 0;
pContext->ItSvc[ItemHdl].ErrCnt = 0;
pContext->ItSvc[ItemHdl].CurCc = 0xffff;
}
#endif
#if <API key> == 1
/* DVB-T: Clear RAWTS checker data */
else if (FilterType == eTS)
{
DibSetMemory(&pContext->FilterInfo[FilterHdl].CheckRawTs, 0, sizeof(struct CheckRawTs));
}
#endif
DIB_DEBUG(MAILBOX_LOG, (CRB "Clear checker stats for Item %d" CRA, ItemHdl));
}
}
/** Build a message for driver to summarize ip checking */
/* XXX this should not go in the official release */
static void <API key>(struct DibBridgeContext *pContext, ELEM_HDL Item)
{
struct MsgChecker Msg;
FILTER_HDL Filter = pContext->ItSvc[Item].FilterParent;
/* Message header */
Msg.Head.Type = MSG_TYPE_MAC;
Msg.Head.MsgId = IN_MSG_CHECKER;
Msg.Head.MsgSize = GetWords(MsgCheckerBits, 32);
Msg.Head.ChipId = HOST_IDENT;
Msg.ItemId = Item;
#if <API key> == 1
if((pContext->FilterInfo[Filter].DataType == eTS) || (pContext->FilterInfo[Filter].DataType == eTDMB))
{
Msg.Total = pContext->FilterInfo[Filter].CheckRawTs.TotalNbPackets;
Msg.CcFailCnt = pContext->FilterInfo[Filter].CheckRawTs.<API key>;
Msg.ErrCnt = pContext->FilterInfo[Filter].CheckRawTs.<API key>;
}
else
#endif
#if DIB_CHECK_CMMB_DATA == 1
if(pContext->FilterInfo[Filter].DataType == eCMMBSVC)
{
Msg.CcFailCnt = pContext->ItSvc[Item].CcFailCnt;
Msg.ErrCnt = pContext->ItSvc[Item].ErrCnt;
}
else
#endif
#if DIB_CHECK_MSC_DATA == 1
if(pContext->FilterInfo[Filter].DataType == eDAB)
{
#if DIB_DAB_DATA == 1
Msg.Total = pContext->ItSvc[Item].NbMaxFrames;
#endif
Msg.CcFailCnt = pContext->ItSvc[Item].CcFailCnt;
Msg.ErrCnt = pContext->ItSvc[Item].ErrCnt;
}
else
#endif
if ((pContext->FilterInfo[Filter].DataType == eMPEFEC) || (pContext->FilterInfo[Filter].DataType == eMPEIFEC))
{
Msg.CcFailCnt = pContext->ItSvc[Item].CcFailCnt;
Msg.ErrCnt = pContext->ItSvc[Item].ErrCnt;
}
else
{
DIB_DEBUG(MAILBOX_ERR, (CRB "<API key> : unsupported data type" CRA));
return;
}
MsgCheckerPackInit(&Msg, &pContext->TxSerialBuf);
DibB2DFwdMsg(pContext, Msg.Head.MsgSize * 4, (uint16_t *)pContext->TxBuffer);
}
#endif
/**
* associate svc to item. Nothing to do cause we have no idea of what is a svc
* @param pContext pointer to the bridge context
* @param svc firefly's service (only useful in firefly's case)
* @param item item's number concerned
*/
static void <API key>(struct DibBridgeContext *pContext, uint8_t Svc, ELEM_HDL ItemHdl, FILTER_HDL FilterHdl, enum DibDataType DataType, enum DibDataMode DataMode)
{
}
/**
* Indicate to the firmware that buffer reception is aborted due to buffer overflow or memory consideration
* @param pContext: bridge context
* @param SvcNb: service number that failed
*/
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, struct DibBridgeDmaFlags * pFlags, uint8_t Flush)
{
return <API key>(pContext, pFlags, (1+Flush));
}
#if (<API key> == 1)
/**
* Send profiler info to the SPARC
*/
static DIBSTATUS <API key>(struct DibBridgeContext *pContext, uint8_t idx, uint8_t page, uint8_t LastFrag)
{
return DIBSTATUS_ERROR;
}
#endif
void <API key>(struct DibBridgeContext *pContext)
{
uint32_t Jedec32;
uint16_t Jedec16;
uint32_t InvJedec;
InvJedec = pContext->DragonflyRegisters.JedecValue;
DibBridgeSwap32((uint8_t*)&InvJedec, 4);
/* toggle sdio endianess if default configuration is not good */
DibBridgeReadReg32(pContext, pContext->DragonflyRegisters.JedecAddr, &Jedec32);
DibBridgeReadReg16(pContext, pContext->DragonflyRegisters.JedecAddr, &Jedec16);
if((Jedec32 == InvJedec) || (Jedec16 == InvJedec >> 16))
{
DibBridgeWriteReg32(pContext, REG_HIF_SDIO_IRQ_EN, 0x0A000000);
}
}
DIBSTATUS <API key>(struct DibBridgeContext *pContext)
{
pContext->RxCnt = 0;
pContext->RxOffset = 0;
if((pContext->HostBuffer = (uint32_t *)<API key>(pContext->DragonflyRegisters.HostMbxSize)) == 0)
{
return DIBSTATUS_ERROR;
}
<API key>(pContext);
/*
printf("<API key>:\n");
printf(" JedecAddr = %08x\n", pContext->DragonflyRegisters.JedecAddr );
printf(" JedecValue = %08x\n", pContext->DragonflyRegisters.JedecValue );
printf(" MAC_MBOX_SIZE = %d\n" , pContext->DragonflyRegisters.MacMbxSize );
printf(" MAC_MBOX_END = %08x\n", pContext->DragonflyRegisters.MacMbxEnd );
printf(" MAC_MBOX_START = %08x\n", pContext->DragonflyRegisters.MacMbxStart );
printf(" HOST_MBOX_SIZE = %d\n" , pContext->DragonflyRegisters.HostMbxSize );
printf(" HOST_MBOX_END = %08x\n", pContext->DragonflyRegisters.HostMbxEnd );
printf(" HOST_MBOX_START = %08x\n", pContext->DragonflyRegisters.HostMbxStart );
printf(" HOST_MBOX_RD_PTR = %08x\n", pContext->DragonflyRegisters.HostMbxRdPtrReg);
printf(" HOST_MBOX_WR_PTR = %08x\n", pContext->DragonflyRegisters.HostMbxWrPtrReg);
printf(" MAC_MBOX_RD_PTR = %08x\n", pContext->DragonflyRegisters.MacMbxRdPtrReg );
printf(" MAC_MBOX_WR_PTR = %08x\n", pContext->DragonflyRegisters.MacMbxWrPtrReg );
*/
return DIBSTATUS_SUCCESS;
}
void <API key>(struct DibBridgeContext *pContext)
{
<API key>((uint8_t *)pContext->HostBuffer, pContext->DragonflyRegisters.HostMbxSize);
}
void <API key>(struct DibBridgeContext *pContext, uint32_t * Config)
{
/* upack dragonflu based register config */
pContext->DragonflyRegisters.JedecAddr = Config[0];
pContext->DragonflyRegisters.JedecValue = Config[1];
pContext->DragonflyRegisters.MacMbxSize = Config[2];
pContext->DragonflyRegisters.MacMbxStart = Config[3];
pContext->DragonflyRegisters.MacMbxEnd = Config[4];
pContext->DragonflyRegisters.HostMbxSize = Config[5];
pContext->DragonflyRegisters.HostMbxStart = Config[6];
pContext->DragonflyRegisters.HostMbxEnd = Config[7];
pContext->DragonflyRegisters.HostMbxRdPtrReg = Config[8];
pContext->DragonflyRegisters.HostMbxWrPtrReg = Config[9];
pContext->DragonflyRegisters.MacMbxRdPtrReg = Config[10];
pContext->DragonflyRegisters.MacMbxWrPtrReg = Config[11];
/* specific architecture functions */
switch(pContext->DibChip)
{
case DIB_VOYAGER:
pContext->BridgeChipOps.PreFormat = <API key>;
pContext->BridgeChipOps.PostFormat = <API key>;
#if ((<API key> == 1) || (<API key> == 1))
pContext->BridgeChipOps.TestRegister = <API key>;
pContext->BridgeChipOps.TestExternalRam = <API key>;
#endif
break;
case DIB_NAUTILUS:
pContext->BridgeChipOps.PreFormat = <API key>;
pContext->BridgeChipOps.PostFormat = <API key>;
#if ((<API key> == 1) || (<API key> == 1))
pContext->BridgeChipOps.TestRegister = <API key>;
pContext->BridgeChipOps.TestExternalRam = <API key>;
#endif
break;
default:
break;
}
pContext->BridgeChipOps.SendMsg = <API key>;
pContext->BridgeChipOps.AssembleSlice = <API key>;
pContext->BridgeChipOps.SendAck = <API key>;
pContext->BridgeChipOps.ProcessIrq = <API key>;
#if (mSDK == 0)
pContext->BridgeChipOps.ProcessDma = <API key>;
#else
pContext->BridgeChipOps.ProcessDma = NULL;
#endif
pContext->BridgeChipOps.SetupDma = <API key>;
pContext->BridgeChipOps.RequestDma = <API key>;
pContext->BridgeChipOps.GetArch = <API key>;
pContext->BridgeChipOps.<API key> = <API key>;
pContext->BridgeChipOps.SignalBufFail = <API key>;
pContext->BridgeChipOps.ChipsetInit = <API key>;
pContext->BridgeChipOps.ChipsetDeinit = <API key>;
#if (<API key> == 1)
pContext->BridgeChipOps.HbmProfiler = <API key>;
#endif
#if (DIB_CHECK_DATA == 1)
pContext->BridgeChipOps.ClearCheckStats = <API key>;
pContext->BridgeChipOps.ForwardCheckStats = <API key>;
#endif
#if ((<API key> == 1) || (<API key> == 1))
pContext->BridgeChipOps.TestBasicRead = <API key>;
pContext->BridgeChipOps.TestInternalRam = <API key>;
pContext->BridgeChipOps.GetRamAddr = <API key>;
#endif
pContext->BridgeChipOps.SetService = <API key>;
}
#endif /* USE_DRAGONFLY */ |
jQuery.fn.nextInArray = function(element) {
var nextId = 0;
for(var i = 0; i < this.length; i++) {
if(this[i] == element) {
nextId = i + 1;
break;
}
}
if(nextId > this.length-1)
nextId = 0;
return this[nextId];
};
jQuery.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return jQuery(':input', this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
jQuery.fn.tagName = function() {
return this.get(0).tagName;
};
jQuery.fn.exists = function(){
return (jQuery(this).size() > 0 ? true : false);
};
function isNumber(val) {
return /^\d+/.test(val);
}
jQuery.fn.serializeAnything = function(addData) {
var toReturn = [];
var els = jQuery(this).find(':input').get();
jQuery.each(els, function() {
if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
var val = jQuery(this).val();
toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
}
});
if(typeof(addData) != 'undefined') {
for(var key in addData)
toReturn.push(key + "=" + addData[key]);
}
return toReturn.join("&").replace(/%20/g, "+");
};
jQuery.fn.hasScrollBarH = function() {
return this.get(0).scrollHeight > this.height();
};
jQuery.fn.hasScrollBarV = function() {
console.log(this.get(0).scrollWidth, this.width(), this.get(0).scrollHeight, this.height());
return this.get(0).scrollWidth > this.width();
};
function str_replace(haystack, needle, replacement) {
var temp = haystack.split(needle);
return temp.join(replacement);
}
/**
* @see php html::nameToClassId($name) method
**/
function nameToClassId(name) {
return str_replace(
str_replace(name, ']', ''),
'[', ''
);
}
function strpos( haystack, needle, offset){
var i = haystack.indexOf( needle, offset ); // returns -1
return i >= 0 ? i : false;
}
function extend(Child, Parent) {
var F = function() { };
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.superclass = Parent.prototype;
}
function toeRedirect(url) {
document.location.href = url;
}
function toeReload() {
document.location.reload();
}
jQuery.fn.toeRebuildSelect = function(data, useIdAsValue, val) {
if(jQuery(this).tagName() == 'SELECT' && typeof(data) == 'object') {
if(jQuery(data).size() > 0) {
if(typeof(val) == 'undefined')
val = false;
if(jQuery(this).children('option').length) {
jQuery(this).children('option').remove();
}
if(typeof(useIdAsValue) == 'undefined')
useIdAsValue = false;
var selected = '';
for(var id in data) {
selected = '';
if(val && ((useIdAsValue && id == val) || (data[id] == val)))
selected = 'selected';
jQuery(this).append('<option value="'+ (useIdAsValue ? id : data[id])+ '" '+ selected+ '>'+ data[id]+ '</option>');
}
}
}
}
/**
* We will not use just jQUery.inArray because it is work incorrect for objects
* @return mixed - key that was found element or -1 if not
*/
function toeInArray(needle, haystack) {
if(typeof(haystack) == 'object') {
for(var k in haystack) {
if(haystack[ k ] == needle)
return k;
}
} else if(typeof(haystack) == 'array') {
return jQuery.inArray(needle, haystack);
}
return -1;
}
jQuery.fn.setReadonly = function() {
jQuery(this).addClass('toeReadonly').attr('readonly', 'readonly');
}
jQuery.fn.unsetReadonly = function() {
jQuery(this).removeClass('toeReadonly').removeAttr('readonly', 'readonly');
}
jQuery.fn.getClassId = function(pref, test) {
var classId = jQuery(this).attr('class');
classId = classId.substr( strpos(classId, pref+ '_') );
if(strpos(classId, ' '))
classId = classId.substr( 0, strpos(classId, ' ') );
classId = classId.split('_');
classId = classId[1];
return classId;
}
function toeTextIncDec(textFieldId, inc) {
var value = parseInt(jQuery('#'+ textFieldId).val());
if(isNaN(value))
value = 0;
if(!(inc < 0 && value < 1)) {
value += inc;
}
jQuery('#'+ textFieldId).val(value);
}
/**
* Make first letter of string in upper case
* @param str string - string to convert
* @return string converted string - first letter in upper case
*/
function toeStrFirstUp(str) {
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
function parseStr (str, array) {
// + original by: Cagri Ekin
// + tweaked by: Jack
// + bugfixed by: Onno Marsman
// + reimplemented by: stag019
// + bugfixed by: stag019
// + input by: Dreamer
// + input by: jeicquest
// % note 1: When no argument is specified, will put variables in global scope.
// * example 1: var arr = {};
// * example 1: parse_str('first=foo&second=bar', arr);
// * results 1: arr == { first: 'foo', second: 'bar' }
// * example 2: var arr = {};
// * example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr);
// * results 2: arr == { str_a: "Jack and Jill didn't see the well." }
// * example 3: var abc = {3:'a'};
// * example 3: parse_str('abc[a][b]["c"]=def&abc[q]=t+5');
var strArr = String(str).replace(/^&/, '').replace(/&$/, '').split('&'),
sal = strArr.length,
i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value,
postLeftBracketPos, keys, keysLen,
fixStr = function (str) {
return decodeURIComponent(str.replace(/\+/g, '%20'));
};
// Comented by Alexey Bolotov
/*
if (!array) {
array = this.window;
}*/
if (!array) {
array = {};
}
for (i = 0; i < sal; i++) {
tmp = strArr[i].split('=');
key = fixStr(tmp[0]);
value = (tmp.length < 2) ? '' : fixStr(tmp[1]);
while (key.charAt(0) === ' ') {
key = key.slice(1);
}
if (key.indexOf('\x00') > -1) {
key = key.slice(0, key.indexOf('\x00'));
}
if (key && key.charAt(0) !== '[') {
keys = [];
postLeftBracketPos = 0;
for (j = 0; j < key.length; j++) {
if (key.charAt(j) === '[' && !postLeftBracketPos) {
postLeftBracketPos = j + 1;
} else if (key.charAt(j) === ']') {
if (postLeftBracketPos) {
if (!keys.length) {
keys.push(key.slice(0, postLeftBracketPos - 1));
}
keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos));
postLeftBracketPos = 0;
if (key.charAt(j + 1) !== '[') {
break;
}
}
}
}
if (!keys.length) {
keys = [key];
}
for (j = 0; j < keys[0].length; j++) {
chr = keys[0].charAt(j);
if (chr === ' ' || chr === '.' || chr === '[') {
keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
}
if (chr === '[') {
break;
}
}
obj = array;
for (j = 0, keysLen = keys.length; j < keysLen; j++) {
key = keys[j].replace(/^['"]/, '').replace(/['"]$/, '');
lastIter = j !== keys.length - 1;
lastObj = obj;
if ((key !== '' && key !== ' ') || j === 0) {
if (obj[key] === undef) {
obj[key] = {};
}
obj = obj[key];
} else { // To insert new dimension
ct = -1;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
if (+p > ct && p.match(/^\d+$/g)) {
ct = +p;
}
}
}
key = ct + 1;
}
}
lastObj[key] = value;
}
}
return array;
}
function toeListable(params) {
this.params = jQuery.extend({}, params);
this.table = jQuery(this.params.table);
this.paging = jQuery(this.params.paging);
this.perPage = this.params.perPage;
this.list = this.params.list;
this.count = this.params.count;
this.page = this.params.page;
this.pagingCallback = this.params.pagingCallback;
var self = this;
this.draw = function(list, count) {
this.table.find('tr').not('.gmpExample, .gmpTblHeader').remove();
var exampleRow = this.table.find('.gmpExample');
for(var i in list) {
var newRow = exampleRow.clone();
for(var key in list[i]) {
var element = newRow.find('.'+ key);
if(element.size()) {
var valueTo = element.attr('valueTo');
if(valueTo) {
var newValue = list[i][key];
var prevValue = element.attr(valueTo);
if(prevValue)
newValue = prevValue+ ' '+ newValue;
element.attr(valueTo, newValue);
} else
element.html(list[i][key]);
}
}
newRow.removeClass('gmpExample').show();
this.table.append(newRow);
}
if(this.paging) {
this.paging.html('');
if(count && count > list.length && this.perPage) {
for(var i = 1; i <= Math.ceil(count/this.perPage); i++) {
var newPageId = i-1
, newElement = (newPageId == this.page) ? jQuery('<b/>') : jQuery('<a/>');
if(newPageId != this.page) {
newElement.attr('href', '#'+ newPageId)
.click(function(){
if(self.pagingCallback && typeof(self.pagingCallback) == 'function') {
self.pagingCallback(parseInt(jQuery(this).attr('href').replace('
return false;
}
});
}
newElement.addClass('toePagingElement').html(i);
this.paging.append(newElement);
}
}
}
}
if(this.list)
this.draw(this.list, this.count);
}
function setCookieGmp(c_name, value, exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function getCookieGmp(name) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
return null;
}
function getImgSize(url, callback) {
jQuery('<img/>').attr('src', url).load(function(){
callback({w: this.width, h: this.height});
});
}
function callUserFuncArray(cb, parameters) {
// + revised by: Jon Hohle
// * example 1: <API key>('isNaN', ['a']);
// * returns 1: true
// * example 2: <API key>('isNaN', [1]);
// * returns 2: false
var func;
if (typeof cb === 'string') {
func = (typeof this[cb] === 'function') ? this[cb] : func = (new Function(null, 'return ' + cb))();
}
else if (Object.prototype.toString.call(cb) === '[object Array]') {
func = (typeof cb[0] == 'string') ? eval(cb[0] + "['" + cb[1] + "']") : func = cb[0][cb[1]];
}
else if (typeof cb === 'function') {
func = cb;
}
if (typeof func !== 'function') {
throw new Error(func + ' is not a valid function');
}
return (typeof cb[0] === 'string') ? func.apply(eval(cb[0]), parameters) : (typeof cb[0] !== 'object') ? func.apply(null, parameters) : func.apply(cb[0], parameters);
} |
#define DEBUG_VARIABLE debug
#include <media/saa7146_vv.h>
#include <media/tuner.h>
#include <linux/video_decoder.h>
#include "mxb.h"
#include "tea6415c.h"
#include "tea6420.h"
#include "tda9840.h"
#define I2C_SAA7111 0x24
#define <API key>(dev) (dev->revision != 0)
/* global variable */
static int mxb_num = 0;
/* initial frequence the tuner will be tuned to.
in verden (lower saxony, germany) 4148 is a
channel called "phoenix" */
static int freq = 4148;
module_param(freq, int, 0644);
MODULE_PARM_DESC(freq, "initial frequency the tuner will be tuned to while setup");
static int debug = 0;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off device debugging (default:off).");
#define MXB_INPUTS 4
enum { TUNER, AUX1, AUX3, AUX3_YC };
static struct v4l2_input mxb_inputs[MXB_INPUTS] = {
{ TUNER, "Tuner", <API key>, 1, 0, V4L2_STD_PAL_BG|V4L2_STD_NTSC_M, 0 },
{ AUX1, "AUX1", <API key>, 2, 0, V4L2_STD_PAL_BG|V4L2_STD_NTSC_M, 0 },
{ AUX3, "AUX3 Composite", <API key>, 4, 0, V4L2_STD_PAL_BG|V4L2_STD_NTSC_M, 0 },
{ AUX3_YC, "AUX3 S-Video", <API key>, 4, 0, V4L2_STD_PAL_BG|V4L2_STD_NTSC_M, 0 },
};
/* this array holds the information, which port of the saa7146 each
input actually uses. the mxb uses port 0 for every input */
static struct {
int hps_source;
int hps_sync;
} <API key>[MXB_INPUTS] = {
{ <API key>, <API key> },
{ <API key>, <API key> },
{ <API key>, <API key> },
{ <API key>, <API key> },
};
/* this array holds the information of the audio source (mxb_audios),
which has to be switched corresponding to the video source (mxb_channels) */
static int video_audio_connect[MXB_INPUTS] =
{ 0, 1, 3, 3 };
/* these are the necessary input-output-pins for bringing one audio source
(see above) to the CD-output */
static struct tea6420_multiplex TEA6420_cd[MXB_AUDIOS+1][2] =
{
{{1,1,0},{1,1,0}}, /* Tuner */
{{5,1,0},{6,1,0}}, /* AUX 1 */
{{4,1,0},{6,1,0}}, /* AUX 2 */
{{3,1,0},{6,1,0}}, /* AUX 3 */
{{1,1,0},{3,1,0}}, /* Radio */
{{1,1,0},{2,1,0}}, /* CD-Rom */
{{6,1,0},{6,1,0}} /* Mute */
};
/* these are the necessary input-output-pins for bringing one audio source
(see above) to the line-output */
static struct tea6420_multiplex TEA6420_line[MXB_AUDIOS+1][2] =
{
{{2,3,0},{1,2,0}},
{{5,3,0},{6,2,0}},
{{4,3,0},{6,2,0}},
{{3,3,0},{6,2,0}},
{{2,3,0},{3,2,0}},
{{2,3,0},{2,2,0}},
{{6,3,0},{6,2,0}} /* Mute */
};
#define MAXCONTROLS 1
static struct v4l2_queryctrl mxb_controls[] = {
{ V4L2_CID_AUDIO_MUTE, <API key>, "Mute", 0, 1, 1, 0, 0 },
};
static struct <API key> ioctls[] = {
{ VIDIOC_ENUMINPUT, SAA7146_EXCLUSIVE },
{ VIDIOC_G_INPUT, SAA7146_EXCLUSIVE },
{ VIDIOC_S_INPUT, SAA7146_EXCLUSIVE },
{ VIDIOC_QUERYCTRL, SAA7146_BEFORE },
{ VIDIOC_G_CTRL, SAA7146_BEFORE },
{ VIDIOC_S_CTRL, SAA7146_BEFORE },
{ VIDIOC_G_TUNER, SAA7146_EXCLUSIVE },
{ VIDIOC_S_TUNER, SAA7146_EXCLUSIVE },
{ VIDIOC_G_FREQUENCY, SAA7146_EXCLUSIVE },
{ VIDIOC_S_FREQUENCY, SAA7146_EXCLUSIVE },
{ VIDIOC_G_AUDIO, SAA7146_EXCLUSIVE },
{ VIDIOC_S_AUDIO, SAA7146_EXCLUSIVE },
{ MXB_S_AUDIO_CD, SAA7146_EXCLUSIVE }, /* custom control */
{ MXB_S_AUDIO_LINE, SAA7146_EXCLUSIVE }, /* custom control */
{ 0, 0 }
};
struct mxb
{
struct video_device *video_dev;
struct video_device *vbi_dev;
struct i2c_adapter i2c_adapter;
struct i2c_client* saa7111a;
struct i2c_client* tda9840;
struct i2c_client* tea6415c;
struct i2c_client* tuner;
struct i2c_client* tea6420_1;
struct i2c_client* tea6420_2;
int cur_mode; /* current audio mode (mono, stereo, ...) */
int cur_input; /* current input */
int cur_mute; /* current mute status */
struct v4l2_frequency cur_freq; /* current frequency the tuner is tuned to */
};
static struct saa7146_extension extension;
static int mxb_probe(struct saa7146_dev* dev)
{
struct mxb* mxb = NULL;
struct i2c_client *client;
struct list_head *item;
int result;
if ((result = request_module("saa7111")) < 0) {
printk("mxb: saa7111 i2c module not available.\n");
return -ENODEV;
}
if ((result = request_module("tuner")) < 0) {
printk("mxb: tuner i2c module not available.\n");
return -ENODEV;
}
if ((result = request_module("tea6420")) < 0) {
printk("mxb: tea6420 i2c module not available.\n");
return -ENODEV;
}
if ((result = request_module("tea6415c")) < 0) {
printk("mxb: tea6415c i2c module not available.\n");
return -ENODEV;
}
if ((result = request_module("tda9840")) < 0) {
printk("mxb: tda9840 i2c module not available.\n");
return -ENODEV;
}
mxb = (struct mxb*)kmalloc(sizeof(struct mxb), GFP_KERNEL);
if( NULL == mxb ) {
DEB_D(("not enough kernel memory.\n"));
return -ENOMEM;
}
memset(mxb, 0x0, sizeof(struct mxb));
mxb->i2c_adapter = (struct i2c_adapter) {
.class = I2C_CLASS_TV_ANALOG,
.name = "mxb",
};
<API key>(dev, &mxb->i2c_adapter, <API key>);
if(i2c_add_adapter(&mxb->i2c_adapter) < 0) {
DEB_S(("cannot register i2c-device. skipping.\n"));
kfree(mxb);
return -EFAULT;
}
/* loop through all i2c-devices on the bus and look who is there */
list_for_each(item,&mxb->i2c_adapter.clients) {
client = list_entry(item, struct i2c_client, list);
if( I2C_TEA6420_1 == client->addr )
mxb->tea6420_1 = client;
if( I2C_TEA6420_2 == client->addr )
mxb->tea6420_2 = client;
if( I2C_TEA6415C_2 == client->addr )
mxb->tea6415c = client;
if( I2C_TDA9840 == client->addr )
mxb->tda9840 = client;
if( I2C_SAA7111 == client->addr )
mxb->saa7111a = client;
if( 0x60 == client->addr )
mxb->tuner = client;
}
/* check if all devices are present */
if( 0 == mxb->tea6420_1 || 0 == mxb->tea6420_2 || 0 == mxb->tea6415c
|| 0 == mxb->tda9840 || 0 == mxb->saa7111a || 0 == mxb->tuner ) {
printk("mxb: did not find all i2c devices. aborting\n");
i2c_del_adapter(&mxb->i2c_adapter);
kfree(mxb);
return -ENODEV;
}
/* all devices are present, probe was successful */
/* we store the pointer in our private data field */
dev->ext_priv = mxb;
return 0;
}
/* some init data for the saa7740, the so-called 'sound arena module'.
there are no specs available, so we simply use some init values */
static struct {
int length;
char data[9];
} mxb_saa7740_init[] = {
{ 3, { 0x80, 0x00, 0x00 } },{ 3, { 0x80, 0x89, 0x00 } },
{ 3, { 0x80, 0xb0, 0x0a } },{ 3, { 0x00, 0x00, 0x00 } },
{ 3, { 0x49, 0x00, 0x00 } },{ 3, { 0x4a, 0x00, 0x00 } },
{ 3, { 0x4b, 0x00, 0x00 } },{ 3, { 0x4c, 0x00, 0x00 } },
{ 3, { 0x4d, 0x00, 0x00 } },{ 3, { 0x4e, 0x00, 0x00 } },
{ 3, { 0x4f, 0x00, 0x00 } },{ 3, { 0x50, 0x00, 0x00 } },
{ 3, { 0x51, 0x00, 0x00 } },{ 3, { 0x52, 0x00, 0x00 } },
{ 3, { 0x53, 0x00, 0x00 } },{ 3, { 0x54, 0x00, 0x00 } },
{ 3, { 0x55, 0x00, 0x00 } },{ 3, { 0x56, 0x00, 0x00 } },
{ 3, { 0x57, 0x00, 0x00 } },{ 3, { 0x58, 0x00, 0x00 } },
{ 3, { 0x59, 0x00, 0x00 } },{ 3, { 0x5a, 0x00, 0x00 } },
{ 3, { 0x5b, 0x00, 0x00 } },{ 3, { 0x5c, 0x00, 0x00 } },
{ 3, { 0x5d, 0x00, 0x00 } },{ 3, { 0x5e, 0x00, 0x00 } },
{ 3, { 0x5f, 0x00, 0x00 } },{ 3, { 0x60, 0x00, 0x00 } },
{ 3, { 0x61, 0x00, 0x00 } },{ 3, { 0x62, 0x00, 0x00 } },
{ 3, { 0x63, 0x00, 0x00 } },{ 3, { 0x64, 0x00, 0x00 } },
{ 3, { 0x65, 0x00, 0x00 } },{ 3, { 0x66, 0x00, 0x00 } },
{ 3, { 0x67, 0x00, 0x00 } },{ 3, { 0x68, 0x00, 0x00 } },
{ 3, { 0x69, 0x00, 0x00 } },{ 3, { 0x6a, 0x00, 0x00 } },
{ 3, { 0x6b, 0x00, 0x00 } },{ 3, { 0x6c, 0x00, 0x00 } },
{ 3, { 0x6d, 0x00, 0x00 } },{ 3, { 0x6e, 0x00, 0x00 } },
{ 3, { 0x6f, 0x00, 0x00 } },{ 3, { 0x70, 0x00, 0x00 } },
{ 3, { 0x71, 0x00, 0x00 } },{ 3, { 0x72, 0x00, 0x00 } },
{ 3, { 0x73, 0x00, 0x00 } },{ 3, { 0x74, 0x00, 0x00 } },
{ 3, { 0x75, 0x00, 0x00 } },{ 3, { 0x76, 0x00, 0x00 } },
{ 3, { 0x77, 0x00, 0x00 } },{ 3, { 0x41, 0x00, 0x42 } },
{ 3, { 0x42, 0x10, 0x42 } },{ 3, { 0x43, 0x20, 0x42 } },
{ 3, { 0x44, 0x30, 0x42 } },{ 3, { 0x45, 0x00, 0x01 } },
{ 3, { 0x46, 0x00, 0x01 } },{ 3, { 0x47, 0x00, 0x01 } },
{ 3, { 0x48, 0x00, 0x01 } },
{ 9, { 0x01, 0x03, 0xc5, 0x5c, 0x7a, 0x85, 0x01, 0x00, 0x54 } },
{ 9, { 0x21, 0x03, 0xc5, 0x5c, 0x7a, 0x85, 0x01, 0x00, 0x54 } },
{ 9, { 0x09, 0x0b, 0xb4, 0x6b, 0x74, 0x85, 0x95, 0x00, 0x34 } },
{ 9, { 0x29, 0x0b, 0xb4, 0x6b, 0x74, 0x85, 0x95, 0x00, 0x34 } },
{ 9, { 0x11, 0x17, 0x43, 0x62, 0x68, 0x89, 0xd1, 0xff, 0xb0 } },
{ 9, { 0x31, 0x17, 0x43, 0x62, 0x68, 0x89, 0xd1, 0xff, 0xb0 } },
{ 9, { 0x19, 0x20, 0x62, 0x51, 0x5a, 0x95, 0x19, 0x01, 0x50 } },
{ 9, { 0x39, 0x20, 0x62, 0x51, 0x5a, 0x95, 0x19, 0x01, 0x50 } },
{ 9, { 0x05, 0x3e, 0xd2, 0x69, 0x4e, 0x9a, 0x51, 0x00, 0xf0 } },
{ 9, { 0x25, 0x3e, 0xd2, 0x69, 0x4e, 0x9a, 0x51, 0x00, 0xf0 } },
{ 9, { 0x0d, 0x3d, 0xa1, 0x40, 0x7d, 0x9f, 0x29, 0xfe, 0x14 } },
{ 9, { 0x2d, 0x3d, 0xa1, 0x40, 0x7d, 0x9f, 0x29, 0xfe, 0x14 } },
{ 9, { 0x15, 0x73, 0xa1, 0x50, 0x5d, 0xa6, 0xf5, 0xfe, 0x38 } },
{ 9, { 0x35, 0x73, 0xa1, 0x50, 0x5d, 0xa6, 0xf5, 0xfe, 0x38 } },
{ 9, { 0x1d, 0xed, 0xd0, 0x68, 0x29, 0xb4, 0xe1, 0x00, 0xb8 } },
{ 9, { 0x3d, 0xed, 0xd0, 0x68, 0x29, 0xb4, 0xe1, 0x00, 0xb8 } },
{ 3, { 0x80, 0xb3, 0x0a } },
{-1, { 0} }
};
static const unsigned char mxb_saa7111_init[] = {
0x00, 0x00, /* 00 - ID byte */
0x01, 0x00, /* 01 - reserved */
/*front end */
0x02, 0xd8, /* 02 - FUSE=x, GUDL=x, MODE=x */
0x03, 0x23, /* 03 - HLNRS=0, VBSL=1, WPOFF=0, HOLDG=0, GAFIX=0, GAI1=256, GAI2=256 */
0x04, 0x00, /* 04 - GAI1=256 */
0x05, 0x00, /* 05 - GAI2=256 */
/* decoder */
0x06, 0xf0, /* 06 - HSB at xx(50Hz) / xx(60Hz) pixels after end of last line */
0x07, 0x30, /* 07 - HSS at xx(50Hz) / xx(60Hz) pixels after end of last line */
0x08, 0xa8, /* 08 - AUFD=x, FSEL=x, EXFIL=x, VTRC=x, HPLL=x, VNOI=x */
0x09, 0x02, /* 09 - BYPS=x, PREF=x, BPSS=x, VBLB=x, UPTCV=x, APER=x */
0x0a, 0x80, /* 0a - BRIG=128 */
0x0b, 0x47, /* 0b - CONT=1.109 */
0x0c, 0x40, /* 0c - SATN=1.0 */
0x0d, 0x00, /* 0d - HUE=0 */
0x0e, 0x01, /* 0e - CDTO=0, CSTD=0, DCCF=0, FCTC=0, CHBW=1 */
0x0f, 0x00, /* 0f - reserved */
0x10, 0xd0, /* 10 - OFTS=x, HDEL=x, VRLN=x, YDEL=x */
0x11, 0x8c, /* 11 - GPSW=x, CM99=x, FECO=x, COMPO=x, OEYC=1, OEHV=1, VIPB=0, COLO=0 */
0x12, 0x80, /* 12 - xx output control 2 */
0x13, 0x30, /* 13 - xx output control 3 */
0x14, 0x00, /* 14 - reserved */
0x15, 0x15, /* 15 - VBI */
0x16, 0x04, /* 16 - VBI */
0x17, 0x00, /* 17 - VBI */
};
/* bring hardware to a sane state. this has to be done, just in case someone
wants to capture from this device before it has been properly initialized.
the capture engine would badly fail, because no valid signal arrives on the
saa7146, thus leading to timeouts and stuff. */
static int mxb_init_done(struct saa7146_dev* dev)
{
struct mxb* mxb = (struct mxb*)dev->ext_priv;
struct video_decoder_init init;
struct i2c_msg msg;
struct tuner_setup tun_setup;
int i = 0, err = 0;
struct tea6415c_multiplex vm;
/* select video mode in saa7111a */
i = VIDEO_MODE_PAL;
/* fixme: currently pointless: gets overwritten by configuration below */
mxb->saa7111a->driver->command(mxb->saa7111a,DECODER_SET_NORM, &i);
/* write configuration to saa7111a */
init.data = mxb_saa7111_init;
init.len = sizeof(mxb_saa7111_init);
mxb->saa7111a->driver->command(mxb->saa7111a,DECODER_INIT, &init);
/* select tuner-output on saa7111a */
i = 0;
mxb->saa7111a->driver->command(mxb->saa7111a,DECODER_SET_INPUT, &i);
/* enable vbi bypass */
i = 1;
mxb->saa7111a->driver->command(mxb->saa7111a,<API key>, &i);
/* select a tuner type */
tun_setup.mode_mask = T_ANALOG_TV;
tun_setup.addr = ADDR_UNSET;
tun_setup.type = TUNER_PHILIPS_PAL;
mxb->tuner->driver->command(mxb->tuner,TUNER_SET_TYPE_ADDR, &tun_setup);
/* tune in some frequency on tuner */
mxb->cur_freq.tuner = 0;
mxb->cur_freq.type = <API key>;
mxb->cur_freq.frequency = freq;
mxb->tuner->driver->command(mxb->tuner, VIDIOC_S_FREQUENCY,
&mxb->cur_freq);
/* mute audio on tea6420s */
mxb->tea6420_1->driver->command(mxb->tea6420_1,TEA6420_SWITCH, &TEA6420_line[6][0]);
mxb->tea6420_2->driver->command(mxb->tea6420_2,TEA6420_SWITCH, &TEA6420_line[6][1]);
mxb->tea6420_1->driver->command(mxb->tea6420_1,TEA6420_SWITCH, &TEA6420_cd[6][0]);
mxb->tea6420_2->driver->command(mxb->tea6420_2,TEA6420_SWITCH, &TEA6420_cd[6][1]);
/* switch to tuner-channel on tea6415c*/
vm.out = 17;
vm.in = 3;
mxb->tea6415c->driver->command(mxb->tea6415c,TEA6415C_SWITCH, &vm);
/* select tuner-output on multicable on tea6415c*/
vm.in = 3;
vm.out = 13;
mxb->tea6415c->driver->command(mxb->tea6415c,TEA6415C_SWITCH, &vm);
/* the rest for mxb */
mxb->cur_input = 0;
mxb->cur_mute = 1;
mxb->cur_mode = <API key>;
mxb->tda9840->driver->command(mxb->tda9840, TDA9840_SWITCH, &mxb->cur_mode);
/* check if the saa7740 (aka 'sound arena module') is present
on the mxb. if so, we must initialize it. due to lack of
informations about the saa7740, the values were reverse
engineered. */
msg.addr = 0x1b;
msg.flags = 0;
msg.len = mxb_saa7740_init[0].length;
msg.buf = &mxb_saa7740_init[0].data[0];
if( 1 == (err = i2c_transfer(&mxb->i2c_adapter, &msg, 1))) {
/* the sound arena module is a pos, that's probably the reason
philips refuses to hand out a datasheet for the saa7740...
it seems to screw up the i2c bus, so we disable fast irq
based i2c transactions here and rely on the slow and safe
polling method ... */
extension.flags &= ~SAA7146_USE_I2C_IRQ;
for(i = 1;;i++) {
if( -1 == mxb_saa7740_init[i].length ) {
break;
}
msg.len = mxb_saa7740_init[i].length;
msg.buf = &mxb_saa7740_init[i].data[0];
if( 1 != (err = i2c_transfer(&mxb->i2c_adapter, &msg, 1))) {
DEB_D(("failed to initialize 'sound arena module'.\n"));
goto err;
}
}
INFO(("'sound arena module' detected.\n"));
}
err:
/* the rest for saa7146: you should definitely set some basic values
for the input-port handling of the saa7146. */
/* ext->saa has been filled by the core driver */
/* some stuff is done via variables */
<API key>(dev, <API key>[mxb->cur_input].hps_source, <API key>[mxb->cur_input].hps_sync);
/* some stuff is done via direct write to the registers */
/* this is ugly, but because of the fact that this is completely
hardware dependend, it should be done directly... */
saa7146_write(dev, DD1_STREAM_B, 0x00000000);
saa7146_write(dev, DD1_INIT, 0x02000200);
saa7146_write(dev, MC2, (MASK_09 | MASK_25 | MASK_10 | MASK_26));
return 0;
}
/* interrupt-handler. this gets called when irq_mask is != 0.
it must clear the interrupt-bits in irq_mask it has handled */
/*
void mxb_irq_bh(struct saa7146_dev* dev, u32* irq_mask)
{
struct mxb* mxb = (struct mxb*)dev->ext_priv;
}
*/
static struct saa7146_ext_vv vv_data;
/* this function only gets called when the probing was successful */
static int mxb_attach(struct saa7146_dev* dev, struct <API key> *info)
{
struct mxb* mxb = (struct mxb*)dev->ext_priv;
DEB_EE(("dev:%p\n",dev));
/* checking for i2c-devices can be omitted here, because we
already did this in "mxb_vl42_probe" */
saa7146_vv_init(dev,&vv_data);
if( 0 != <API key>(&mxb->video_dev, dev, "mxb", VFL_TYPE_GRABBER)) {
ERR(("cannot register capture v4l2 device. skipping.\n"));
return -1;
}
/* initialization stuff (vbi) (only for revision > 0 and for extensions which want it)*/
if( 0 != <API key>(dev)) {
if( 0 != <API key>(&mxb->vbi_dev, dev, "mxb", VFL_TYPE_VBI)) {
ERR(("cannot register vbi v4l2 device. skipping.\n"));
}
}
i2c_use_client(mxb->tea6420_1);
i2c_use_client(mxb->tea6420_2);
i2c_use_client(mxb->tea6415c);
i2c_use_client(mxb->tda9840);
i2c_use_client(mxb->saa7111a);
i2c_use_client(mxb->tuner);
printk("mxb: found 'Multimedia eXtension Board'-%d.\n",mxb_num);
mxb_num++;
mxb_init_done(dev);
return 0;
}
static int mxb_detach(struct saa7146_dev* dev)
{
struct mxb* mxb = (struct mxb*)dev->ext_priv;
DEB_EE(("dev:%p\n",dev));
i2c_release_client(mxb->tea6420_1);
i2c_release_client(mxb->tea6420_2);
i2c_release_client(mxb->tea6415c);
i2c_release_client(mxb->tda9840);
i2c_release_client(mxb->saa7111a);
i2c_release_client(mxb->tuner);
<API key>(&mxb->video_dev,dev);
if( 0 != <API key>(dev)) {
<API key>(&mxb->vbi_dev,dev);
}
saa7146_vv_release(dev);
mxb_num
i2c_del_adapter(&mxb->i2c_adapter);
kfree(mxb);
return 0;
}
static int mxb_ioctl(struct saa7146_fh *fh, unsigned int cmd, void *arg)
{
struct saa7146_dev *dev = fh->dev;
struct mxb* mxb = (struct mxb*)dev->ext_priv;
struct saa7146_vv *vv = dev->vv_data;
switch(cmd) {
case VIDIOC_ENUMINPUT:
{
struct v4l2_input *i = arg;
DEB_EE(("VIDIOC_ENUMINPUT %d.\n",i->index));
if( i->index < 0 || i->index >= MXB_INPUTS) {
return -EINVAL;
}
memcpy(i, &mxb_inputs[i->index], sizeof(struct v4l2_input));
return 0;
}
/* the saa7146 provides some controls (brightness, contrast, saturation)
which gets registered *after* this function. because of this we have
to return with a value != 0 even if the function succeded.. */
case VIDIOC_QUERYCTRL:
{
struct v4l2_queryctrl *qc = arg;
int i;
for (i = MAXCONTROLS - 1; i >= 0; i
if (mxb_controls[i].id == qc->id) {
*qc = mxb_controls[i];
DEB_D(("VIDIOC_QUERYCTRL %d.\n",qc->id));
return 0;
}
}
return -EAGAIN;
}
case VIDIOC_G_CTRL:
{
struct v4l2_control *vc = arg;
int i;
for (i = MAXCONTROLS - 1; i >= 0; i
if (mxb_controls[i].id == vc->id) {
break;
}
}
if( i < 0 ) {
return -EAGAIN;
}
switch (vc->id ) {
case V4L2_CID_AUDIO_MUTE: {
vc->value = mxb->cur_mute;
DEB_D(("VIDIOC_G_CTRL V4L2_CID_AUDIO_MUTE:%d.\n",vc->value));
return 0;
}
}
DEB_EE(("VIDIOC_G_CTRL V4L2_CID_AUDIO_MUTE:%d.\n",vc->value));
return 0;
}
case VIDIOC_S_CTRL:
{
struct v4l2_control *vc = arg;
int i = 0;
for (i = MAXCONTROLS - 1; i >= 0; i
if (mxb_controls[i].id == vc->id) {
break;
}
}
if( i < 0 ) {
return -EAGAIN;
}
switch (vc->id ) {
case V4L2_CID_AUDIO_MUTE: {
mxb->cur_mute = vc->value;
if( 0 == vc->value ) {
/* switch the audio-source */
mxb->tea6420_1->driver->command(mxb->tea6420_1,TEA6420_SWITCH, &TEA6420_line[video_audio_connect[mxb->cur_input]][0]);
mxb->tea6420_2->driver->command(mxb->tea6420_2,TEA6420_SWITCH, &TEA6420_line[video_audio_connect[mxb->cur_input]][1]);
} else {
mxb->tea6420_1->driver->command(mxb->tea6420_1,TEA6420_SWITCH, &TEA6420_line[6][0]);
mxb->tea6420_2->driver->command(mxb->tea6420_2,TEA6420_SWITCH, &TEA6420_line[6][1]);
}
DEB_EE(("VIDIOC_S_CTRL, V4L2_CID_AUDIO_MUTE: %d.\n",vc->value));
break;
}
}
return 0;
}
case VIDIOC_G_INPUT:
{
int *input = (int *)arg;
*input = mxb->cur_input;
DEB_EE(("VIDIOC_G_INPUT %d.\n",*input));
return 0;
}
case VIDIOC_S_INPUT:
{
int input = *(int *)arg;
struct tea6415c_multiplex vm;
int i = 0;
DEB_EE(("VIDIOC_S_INPUT %d.\n",input));
if (input < 0 || input >= MXB_INPUTS) {
return -EINVAL;
}
/* fixme: locke das setzen des inputs mit hilfe des mutexes
down(&dev->lock);
video_mux(dev,*i);
up(&dev->lock);
*/
mxb->cur_input = input;
<API key>(dev, <API key>[input].hps_source, <API key>[input].hps_sync);
/* prepare switching of tea6415c and saa7111a;
have a look at the 'background'-file for further informations */
switch( input ) {
case TUNER:
{
i = 0;
vm.in = 3;
vm.out = 17;
if ( 0 != mxb->tea6415c->driver->command(mxb->tea6415c,TEA6415C_SWITCH, &vm)) {
printk("VIDIOC_S_INPUT: could not address tea6415c
return -EFAULT;
}
/* connect tuner-output always to multicable */
vm.in = 3;
vm.out = 13;
break;
}
case AUX3_YC:
{
/* nothing to be done here. aux3_yc is
directly connected to the saa711a */
i = 5;
break;
}
case AUX3:
{
/* nothing to be done here. aux3 is
directly connected to the saa711a */
i = 1;
break;
}
case AUX1:
{
i = 0;
vm.in = 1;
vm.out = 17;
break;
}
}
/* switch video in tea6415c only if necessary */
switch( input ) {
case TUNER:
case AUX1:
{
if ( 0 != mxb->tea6415c->driver->command(mxb->tea6415c,TEA6415C_SWITCH, &vm)) {
printk("VIDIOC_S_INPUT: could not address tea6415c
return -EFAULT;
}
break;
}
default:
{
break;
}
}
/* switch video in saa7111a */
if ( 0 != mxb->saa7111a->driver->command(mxb->saa7111a,DECODER_SET_INPUT, &i)) {
printk("VIDIOC_S_INPUT: could not address saa7111a
}
/* switch the audio-source only if necessary */
if( 0 == mxb->cur_mute ) {
mxb->tea6420_1->driver->command(mxb->tea6420_1,TEA6420_SWITCH, &TEA6420_line[video_audio_connect[input]][0]);
mxb->tea6420_2->driver->command(mxb->tea6420_2,TEA6420_SWITCH, &TEA6420_line[video_audio_connect[input]][1]);
}
return 0;
}
case VIDIOC_G_TUNER:
{
struct v4l2_tuner *t = arg;
int byte = 0;
if( 0 != t->index ) {
DEB_D(("VIDIOC_G_TUNER: channel %d does not have a tuner attached.\n", t->index));
return -EINVAL;
}
DEB_EE(("VIDIOC_G_TUNER: %d\n", t->index));
memset(t,0,sizeof(*t));
strcpy(t->name, "Television");
t->type = <API key>;
t->capability = V4L2_TUNER_CAP_NORM | <API key> | <API key> | <API key> | V4L2_TUNER_CAP_SAP;
t->rangelow = 772; /* 48.25 MHZ / 62.5 kHz = 772, see fi1216mk2-specs, page 2 */
t->rangehigh = 13684; /* 855.25 MHz / 62.5 kHz = 13684 */
/* FIXME: add the real signal strength here */
t->signal = 0xffff;
t->afc = 0;
mxb->tda9840->driver->command(mxb->tda9840,TDA9840_DETECT, &byte);
t->audmode = mxb->cur_mode;
if( byte < 0 ) {
t->rxsubchans = V4L2_TUNER_SUB_MONO;
} else {
switch(byte) {
case TDA9840_MONO_DETECT: {
t->rxsubchans = V4L2_TUNER_SUB_MONO;
DEB_D(("VIDIOC_G_TUNER: <API key>.\n"));
break;
}
case TDA9840_DUAL_DETECT: {
t->rxsubchans = <API key> | <API key>;
DEB_D(("VIDIOC_G_TUNER: <API key>.\n"));
break;
}
case <API key>: {
t->rxsubchans = <API key> | V4L2_TUNER_SUB_MONO;
DEB_D(("VIDIOC_G_TUNER: <API key>.\n"));
break;
}
default: { /* <API key> */
t->rxsubchans = <API key>;
DEB_D(("VIDIOC_G_TUNER: <API key> => <API key>\n"));
break;
}
}
}
return 0;
}
case VIDIOC_S_TUNER:
{
struct v4l2_tuner *t = arg;
int result = 0;
int byte = 0;
if( 0 != t->index ) {
DEB_D(("VIDIOC_S_TUNER: channel %d does not have a tuner attached.\n",t->index));
return -EINVAL;
}
switch(t->audmode) {
case <API key>: {
mxb->cur_mode = <API key>;
byte = TDA9840_SET_STEREO;
DEB_D(("VIDIOC_S_TUNER: <API key>\n"));
break;
}
case <API key>: {
mxb->cur_mode = <API key>;
byte = TDA9840_SET_LANG1;
DEB_D(("VIDIOC_S_TUNER: <API key>\n"));
break;
}
case <API key>: {
mxb->cur_mode = <API key>;
byte = TDA9840_SET_LANG2;
DEB_D(("VIDIOC_S_TUNER: <API key>\n"));
break;
}
default: { /* case <API key>: {*/
mxb->cur_mode = <API key>;
byte = TDA9840_SET_MONO;
DEB_D(("VIDIOC_S_TUNER: TDA9840_SET_MONO\n"));
break;
}
}
if( 0 != (result = mxb->tda9840->driver->command(mxb->tda9840, TDA9840_SWITCH, &byte))) {
printk("VIDIOC_S_TUNER error. result:%d, byte:%d\n",result,byte);
}
return 0;
}
case VIDIOC_G_FREQUENCY:
{
struct v4l2_frequency *f = arg;
if(0 != mxb->cur_input) {
DEB_D(("VIDIOC_G_FREQ: channel %d does not have a tuner!\n",mxb->cur_input));
return -EINVAL;
}
*f = mxb->cur_freq;
DEB_EE(("VIDIOC_G_FREQ: freq:0x%08x.\n", mxb->cur_freq.frequency));
return 0;
}
case VIDIOC_S_FREQUENCY:
{
struct v4l2_frequency *f = arg;
if (0 != f->tuner)
return -EINVAL;
if (<API key> != f->type)
return -EINVAL;
if(0 != mxb->cur_input) {
DEB_D(("VIDIOC_S_FREQ: channel %d does not have a tuner!\n",mxb->cur_input));
return -EINVAL;
}
mxb->cur_freq = *f;
DEB_EE(("VIDIOC_S_FREQUENCY: freq:0x%08x.\n", mxb->cur_freq.frequency));
/* tune in desired frequency */
mxb->tuner->driver->command(mxb->tuner, VIDIOC_S_FREQUENCY, &mxb->cur_freq);
/* hack: changing the frequency should invalidate the vbi-counter (=> alevt) */
spin_lock(&dev->slock);
vv->vbi_fieldcount = 0;
spin_unlock(&dev->slock);
return 0;
}
case MXB_S_AUDIO_CD:
{
int i = *(int*)arg;
if( i < 0 || i >= MXB_AUDIOS ) {
DEB_D(("illegal argument to MXB_S_AUDIO_CD: i:%d.\n",i));
return -EINVAL;
}
DEB_EE(("MXB_S_AUDIO_CD: i:%d.\n",i));
mxb->tea6420_1->driver->command(mxb->tea6420_1,TEA6420_SWITCH, &TEA6420_cd[i][0]);
mxb->tea6420_2->driver->command(mxb->tea6420_2,TEA6420_SWITCH, &TEA6420_cd[i][1]);
return 0;
}
case MXB_S_AUDIO_LINE:
{
int i = *(int*)arg;
if( i < 0 || i >= MXB_AUDIOS ) {
DEB_D(("illegal argument to MXB_S_AUDIO_LINE: i:%d.\n",i));
return -EINVAL;
}
DEB_EE(("MXB_S_AUDIO_LINE: i:%d.\n",i));
mxb->tea6420_1->driver->command(mxb->tea6420_1,TEA6420_SWITCH, &TEA6420_line[i][0]);
mxb->tea6420_2->driver->command(mxb->tea6420_2,TEA6420_SWITCH, &TEA6420_line[i][1]);
return 0;
}
case VIDIOC_G_AUDIO:
{
struct v4l2_audio *a = arg;
if( a->index < 0 || a->index > MXB_INPUTS ) {
DEB_D(("VIDIOC_G_AUDIO %d out of range.\n",a->index));
return -EINVAL;
}
DEB_EE(("VIDIOC_G_AUDIO %d.\n",a->index));
memcpy(a, &mxb_audios[video_audio_connect[mxb->cur_input]], sizeof(struct v4l2_audio));
return 0;
}
case VIDIOC_S_AUDIO:
{
struct v4l2_audio *a = arg;
DEB_D(("VIDIOC_S_AUDIO %d.\n",a->index));
return 0;
}
default:
/*
DEB2(printk("does not handle this ioctl.\n"));
*/
return -ENOIOCTLCMD;
}
return 0;
}
static int std_callback(struct saa7146_dev* dev, struct saa7146_standard *std)
{
struct mxb* mxb = (struct mxb*)dev->ext_priv;
int zero = 0;
int one = 1;
if(V4L2_STD_PAL_I == std->id ) {
DEB_D(("VIDIOC_S_STD: setting mxb for PAL_I.\n"));
/* set the 7146 gpio register -- I don't know what this does exactly */
saa7146_write(dev, GPIO_CTRL, 0x00404050);
/* unset the 7111 gpio register -- I don't know what this does exactly */
mxb->saa7111a->driver->command(mxb->saa7111a,DECODER_SET_GPIO, &zero);
} else {
DEB_D(("VIDIOC_S_STD: setting mxb for PAL/NTSC/SECAM.\n"));
/* set the 7146 gpio register -- I don't know what this does exactly */
saa7146_write(dev, GPIO_CTRL, 0x00404050);
/* set the 7111 gpio register -- I don't know what this does exactly */
mxb->saa7111a->driver->command(mxb->saa7111a,DECODER_SET_GPIO, &one);
}
return 0;
}
static struct saa7146_standard standard[] = {
{
.name = "PAL-BG", .id = V4L2_STD_PAL_BG,
.v_offset = 0x17, .v_field = 288,
.h_offset = 0x14, .h_pixels = 680,
.v_max_out = 576, .h_max_out = 768,
}, {
.name = "PAL-I", .id = V4L2_STD_PAL_I,
.v_offset = 0x17, .v_field = 288,
.h_offset = 0x14, .h_pixels = 680,
.v_max_out = 576, .h_max_out = 768,
}, {
.name = "NTSC", .id = V4L2_STD_NTSC,
.v_offset = 0x16, .v_field = 240,
.h_offset = 0x06, .h_pixels = 708,
.v_max_out = 480, .h_max_out = 640,
}, {
.name = "SECAM", .id = V4L2_STD_SECAM,
.v_offset = 0x14, .v_field = 288,
.h_offset = 0x14, .h_pixels = 720,
.v_max_out = 576, .h_max_out = 768,
}
};
static struct <API key> mxb = {
.ext_priv = "Multimedia eXtension Board",
.ext = &extension,
};
static struct pci_device_id pci_tbl[] = {
{
.vendor = <API key>,
.device = <API key>,
.subvendor = 0x0000,
.subdevice = 0x0000,
.driver_data = (unsigned long)&mxb,
}, {
.vendor = 0,
}
};
MODULE_DEVICE_TABLE(pci, pci_tbl);
static struct saa7146_ext_vv vv_data = {
.inputs = MXB_INPUTS,
.capabilities = V4L2_CAP_TUNER | <API key>,
.stds = &standard[0],
.num_stds = sizeof(standard)/sizeof(struct saa7146_standard),
.std_callback = &std_callback,
.ioctls = &ioctls[0],
.ioctl = mxb_ioctl,
};
static struct saa7146_extension extension = {
.name = MXB_IDENTIFIER,
.flags = SAA7146_USE_I2C_IRQ,
.pci_tbl = &pci_tbl[0],
.module = THIS_MODULE,
.probe = mxb_probe,
.attach = mxb_attach,
.detach = mxb_detach,
.irq_mask = 0,
.irq_func = NULL,
};
static int __init mxb_init_module(void)
{
if( 0 != <API key>(&extension)) {
DEB_S(("failed to register extension.\n"));
return -ENODEV;
}
return 0;
}
static void __exit mxb_cleanup_module(void)
{
<API key>(&extension);
}
module_init(mxb_init_module);
module_exit(mxb_cleanup_module);
MODULE_DESCRIPTION("video4linux-2 driver for the Siemens-Nixdorf 'Multimedia eXtension board'");
MODULE_AUTHOR("Michael Hunold <michael@mihu.de>");
MODULE_LICENSE("GPL"); |
<?php
namespace Drupal\yamlform\Tests;
/**
* Tests for form block.
*
* @group YamlForm
*/
class YamlFormBlockTest extends YamlFormTestBase {
/**
* Tests form block.
*/
public function testBlock() {
// Place block.
$block = $this->drupalPlaceBlock('yamlform_block');
// Check contact form.
$block->getPlugin()-><API key>('yamlform_id', 'contact');
$block->save();
$this->drupalGet('<front>');
$this->assertRaw('<API key>');
// Check contact form with default data.
$block->getPlugin()-><API key>('default_data', "name: 'John Smith'");
$block->save();
$this->drupalGet('<front>');
$this->assertRaw('<API key>');
$this->assertFieldByName('name', 'John Smith');
// Check confirmation inline form.
$block->getPlugin()-><API key>('yamlform_id', '<API key>');
$block->save();
$this->drupalPostForm('<front>', [], t('Submit'));
$this->assertRaw('This is a custom inline confirmation message.');
// Check confirmation message form.
$block->getPlugin()-><API key>('yamlform_id', '<API key>');
$block->save();
$this->drupalPostForm('<front>', [], t('Submit'));
$this->assertRaw('This is a <b>custom</b> confirmation message.');
}
} |
BODY, TEXTAREA, INPUT, TD, SELECT
{
font-family: Tahoma,verdana,arial,sans-serif;
}
DIV
{
position: absolute;
}
.simple
{
font-size: 11pt;
}
.double
{
font-size: 9pt;
}
.simpledia
{
color: red;
font-size: 11pt;
}
.doubledia
{
color: red;
font-size: 9pt;
}
.action
{
color: white;
font-size: 7pt;
}
.clavier
{
color: blue;
font-size: 7pt;
}
.sign
{
color: gray;
font-size: 7pt;
} |
<?php
namespace Drupal\KernelTests\Core\Test;
use Drupal\FunctionalTests\<API key>;
use Drupal\FunctionalTests\<API key>;
use Drupal\KernelTests\KernelTestBase;
use PHPUnit\Framework\SkippedTestError;
/**
* @group Test
* @group FunctionalTests
*
* @coversDefaultClass \Drupal\Tests\BrowserTestBase
*/
class BrowserTestBaseTest extends KernelTestBase {
/**
* Tests that a test method is skipped when it requires a module not present.
*
* In order to catch checkRequirements() regressions, we have to make a new
* test object and run checkRequirements() here.
*
* @covers ::checkRequirements
* @covers ::<API key>
*/
public function <API key>() {
require __DIR__ . '/../../../../fixtures/<API key>.php';
$stub_test = new <API key>();
// We have to setName() to the method name we're concerned with.
$stub_test->setName('testRequiresModule');
// We cannot use $this-><API key>() because PHPUnit would skip
// the test before comparing the exception type.
try {
$stub_test-><API key>();
$this->fail('Missing required module throws skipped test exception.');
}
catch (SkippedTestError $e) {
$this->assertEquals('Required modules: <API key>', $e->getMessage());
}
}
/**
* Tests that a test case is skipped when it requires a module not present.
*
* In order to catch checkRequirements() regressions, we have to make a new
* test object and run checkRequirements() here.
*
* @covers ::checkRequirements
* @covers ::<API key>
*/
public function testRequiresModule() {
require __DIR__ . '/../../../../fixtures/<API key>.php';
$stub_test = new <API key>();
// We have to setName() to the method name we're concerned with.
$stub_test->setName('testRequiresModule');
// We cannot use $this-><API key>() because PHPUnit would skip
// the test before comparing the exception type.
try {
$stub_test-><API key>();
$this->fail('Missing required module throws skipped test exception.');
}
catch (SkippedTestError $e) {
$this->assertEquals('Required modules: <API key>', $e->getMessage());
}
}
} |
<?php
namespace Joomla\CMS\Http;
defined('JPATH_PLATFORM') or die;
use Joomla\Registry\Registry;
use Joomla\CMS\Uri\Uri;
/**
* HTTP transport class interface.
*
* @since 1.7.3
*/
interface TransportInterface
{
/**
* Constructor.
*
* @param Registry $options Client options object.
*
* @since 1.7.3
*/
public function __construct(Registry $options);
/**
* Send a request to the server and return a HttpResponse object with the response.
*
* @param string $method The HTTP method for sending the request.
* @param Uri $uri The URI to the resource to request.
* @param mixed $data Either an associative array or a string to be sent with the request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
* @param string $userAgent The optional user agent string to send with the request.
*
* @return Response
*
* @since 1.7.3
*/
public function request($method, Uri $uri, $data = null, array $headers = null, $timeout = null, $userAgent = null);
/**
* Method to check if HTTP transport is available for use
*
* @return boolean True if available else false
*
* @since 3.0.0
*/
public static function isSupported();
} |
#ifndef LINUX_TDEP_H
#define LINUX_TDEP_H
#include "bfd.h"
struct regcache;
typedef char *(*<API key>) (const struct regcache *,
ptid_t,
bfd *, char *, int *,
enum gdb_signal);
struct type *<API key> (struct gdbarch *);
extern enum gdb_signal <API key> (struct gdbarch *gdbarch,
int signal);
extern int <API key> (struct gdbarch *gdbarch,
enum gdb_signal signal);
/* Default GNU/Linux implementation of `<API key>', as
defined in gdbarch.h. Determines the entry point from AT_ENTRY in
the target auxiliary vector. */
extern CORE_ADDR <API key> (struct gdbarch *gdbarch);
extern void linux_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch);
extern int linux_is_uclinux (void);
#endif /* linux-tdep.h */ |
/**
* @file
* Packet buffer management
*
* Packets are built from the pbuf data structure. It supports dynamic
* memory allocation for packet contents or can reference externally
* managed packet contents both in RAM and ROM. Quick allocation for
* incoming packets is provided through pools with fixed sized pbufs.
*
* A packet may span over multiple pbufs, chained as a singly linked
* list. This is called a "pbuf chain".
*
* Multiple packets may be queued, also using this singly linked list.
* This is called a "packet queue".
*
* So, a packet queue consists of one or more pbuf chains, each of
* which consist of one or more pbufs. CURRENTLY, PACKET QUEUES ARE
* NOT SUPPORTED!!! Use helper structs to queue multiple packets.
*
* The differences between a pbuf chain and a packet queue are very
* precise but subtle.
*
* The last pbuf of a packet has a ->tot_len field that equals the
* ->len field. It can be found by traversing the list. If the last
* pbuf of a packet has a ->next field other than NULL, more packets
* are on the queue.
*
* Therefore, looping through a pbuf of a single packet, has an
* loop end condition (tot_len == p->len), NOT (next == NULL).
*/
#include "lwip/opt.h"
#include "lwip/stats.h"
#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/memp.h"
#include "lwip/pbuf.h"
#include "lwip/sys.h"
#if LWIP_TCP && TCP_QUEUE_OOSEQ
#include "lwip/tcp_impl.h"
#endif
#if <API key>
#include "lwip/inet_chksum.h"
#endif
#include <lwk/string.h>
#define SIZEOF_STRUCT_PBUF LWIP_MEM_ALIGN_SIZE(sizeof(struct pbuf))
/* Since the pool is created in memp, PBUF_POOL_BUFSIZE will be automatically
aligned there. Therefore, <API key> can be used here. */
#define <API key> LWIP_MEM_ALIGN_SIZE(PBUF_POOL_BUFSIZE)
#if !LWIP_TCP || !TCP_QUEUE_OOSEQ || !<API key>
#define PBUF_POOL_IS_EMPTY()
#else /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || !<API key> */
#if !NO_SYS
#ifndef <API key>
#include "lwip/tcpip.h"
#define <API key>() do { \
if(<API key>(<API key>, NULL, 0) != ERR_OK) { \
SYS_ARCH_PROTECT(old_level); \
<API key> = 0; \
SYS_ARCH_UNPROTECT(old_level); \
} } while(0)
#endif /* <API key> */
#endif /* !NO_SYS */
volatile u8_t <API key>;
#define PBUF_POOL_IS_EMPTY() pbuf_pool_is_empty()
/**
* Attempt to reclaim some memory from queued out-of-sequence TCP segments
* if we run out of pool pbufs. It's better to give priority to new packets
* if we're running out.
*
* This must be done in the correct thread context therefore this function
* can only be used with NO_SYS=0 and through tcpip_callback.
*/
#if !NO_SYS
static
#endif /* !NO_SYS */
void
pbuf_free_ooseq(void)
{
struct tcp_pcb* pcb;
<API key>(old_level);
SYS_ARCH_PROTECT(old_level);
<API key> = 0;
SYS_ARCH_UNPROTECT(old_level);
for (pcb = tcp_active_pcbs; NULL != pcb; pcb = pcb->next) {
if (NULL != pcb->ooseq) {
/** Free the ooseq pbufs of one PCB only */
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free_ooseq: freeing out-of-sequence pbufs\n"));
tcp_segs_free(pcb->ooseq);
pcb->ooseq = NULL;
return;
}
}
}
#if !NO_SYS
/**
* Just a callback function for tcpip_timeout() that calls pbuf_free_ooseq().
*/
static void
<API key>(void *arg)
{
LWIP_UNUSED_ARG(arg);
pbuf_free_ooseq();
}
#endif /* !NO_SYS */
/** Queue a call to pbuf_free_ooseq if not already queued. */
static void
pbuf_pool_is_empty(void)
{
#ifndef <API key>
<API key>(old_level);
SYS_ARCH_PROTECT(old_level);
<API key> = 1;
SYS_ARCH_UNPROTECT(old_level);
#else /* <API key> */
u8_t queued;
<API key>(old_level);
SYS_ARCH_PROTECT(old_level);
queued = <API key>;
<API key> = 1;
SYS_ARCH_UNPROTECT(old_level);
if(!queued) {
/* queue a call to pbuf_free_ooseq if not already queued */
<API key>();
}
#endif /* <API key> */
}
#endif /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || !<API key> */
/**
* Allocates a pbuf of the given type (possibly a chain for PBUF_POOL type).
*
* The actual memory allocated for the pbuf is determined by the
* layer at which the pbuf is allocated and the requested size
* (from the size parameter).
*
* @param layer flag to define header size
* @param length size of the pbuf's payload
* @param type this parameter decides how and where the pbuf
* should be allocated as follows:
*
* - PBUF_RAM: buffer memory for pbuf is allocated as one large
* chunk. This includes protocol headers as well.
* - PBUF_ROM: no buffer memory is allocated for the pbuf, even for
* protocol headers. Additional headers must be prepended
* by allocating another pbuf and chain in to the front of
* the ROM pbuf. It is assumed that the memory used is really
* similar to ROM in that it is immutable and will not be
* changed. Memory which is dynamic should generally not
* be attached to PBUF_ROM pbufs. Use PBUF_REF instead.
* - PBUF_REF: no buffer memory is allocated for the pbuf, even for
* protocol headers. It is assumed that the pbuf is only
* being used in a single thread. If the pbuf gets queued,
* then pbuf_take should be called to copy the buffer.
* - PBUF_POOL: the pbuf is allocated as a pbuf chain, with pbufs from
* the pbuf pool that is allocated during pbuf_init().
*
* @return the allocated pbuf. If multiple pbufs where allocated, this
* is the first pbuf of a pbuf chain.
*/
struct pbuf *
pbuf_alloc(pbuf_layer layer, u16_t length, pbuf_type type)
{
struct pbuf *p, *q, *r;
u16_t offset;
s32_t rem_len; /* remaining length */
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F")\n", length));
/* determine header offset */
switch (layer) {
case PBUF_TRANSPORT:
/* add room for transport (often TCP) layer header */
offset = PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN;
break;
case PBUF_IP:
/* add room for IP layer header */
offset = PBUF_LINK_HLEN + PBUF_IP_HLEN;
break;
case PBUF_LINK:
/* add room for link layer header */
offset = PBUF_LINK_HLEN;
break;
case PBUF_RAW:
offset = 0;
break;
default:
LWIP_ASSERT("pbuf_alloc: bad pbuf layer", 0);
return NULL;
}
switch (type) {
case PBUF_POOL:
/* allocate head of pbuf chain into p */
p = (struct pbuf *)memp_malloc(MEMP_PBUF_POOL);
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc: allocated pbuf %p\n", (void *)p));
if (p == NULL) {
PBUF_POOL_IS_EMPTY();
return NULL;
}
p->type = type;
p->next = NULL;
/* make the payload pointer point 'offset' bytes into pbuf data memory */
p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + (SIZEOF_STRUCT_PBUF + offset)));
LWIP_ASSERT("pbuf_alloc: pbuf p->payload properly aligned",
((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
/* the total length of the pbuf chain is the requested size */
p->tot_len = length;
/* set the length of the first pbuf in the chain */
p->len = LWIP_MIN(length, <API key> - LWIP_MEM_ALIGN_SIZE(offset));
LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
((u8_t*)p->payload + p->len <=
(u8_t*)p + SIZEOF_STRUCT_PBUF + <API key>));
LWIP_ASSERT("PBUF_POOL_BUFSIZE must be bigger than MEM_ALIGNMENT",
(<API key> - LWIP_MEM_ALIGN_SIZE(offset)) > 0 );
/* set reference count (needed here in case we fail) */
p->ref = 1;
/* now allocate the tail of the pbuf chain */
/* remember first pbuf for linkage in next iteration */
r = p;
/* remaining length to be allocated */
rem_len = length - p->len;
/* any remaining pbufs to be allocated? */
while (rem_len > 0) {
q = (struct pbuf *)memp_malloc(MEMP_PBUF_POOL);
if (q == NULL) {
PBUF_POOL_IS_EMPTY();
/* free chain so far allocated */
pbuf_free(p);
/* bail out unsuccesfully */
return NULL;
}
q->type = type;
q->flags = 0;
q->next = NULL;
/* make previous pbuf point to this pbuf */
r->next = q;
/* set total length of this pbuf and next in chain */
LWIP_ASSERT("rem_len < max_u16_t", rem_len < 0xffff);
q->tot_len = (u16_t)rem_len;
/* this pbuf length is pool size, unless smaller sized tail */
q->len = LWIP_MIN((u16_t)rem_len, <API key>);
q->payload = (void *)((u8_t *)q + SIZEOF_STRUCT_PBUF);
LWIP_ASSERT("pbuf_alloc: pbuf q->payload properly aligned",
((mem_ptr_t)q->payload % MEM_ALIGNMENT) == 0);
LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
((u8_t*)p->payload + p->len <=
(u8_t*)p + SIZEOF_STRUCT_PBUF + <API key>));
q->ref = 1;
/* calculate remaining length to be allocated */
rem_len -= q->len;
/* remember this pbuf for linkage in next iteration */
r = q;
}
/* end of chain */
/*r->next = NULL;*/
break;
case PBUF_RAM:
/* If pbuf is to be allocated in RAM, allocate memory for it. */
p = (struct pbuf*)mem_malloc(LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF + offset) + LWIP_MEM_ALIGN_SIZE(length));
if (p == NULL) {
return NULL;
}
/* Set up internal structure of the pbuf. */
p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + SIZEOF_STRUCT_PBUF + offset));
p->len = p->tot_len = length;
p->next = NULL;
p->type = type;
LWIP_ASSERT("pbuf_alloc: pbuf->payload properly aligned",
((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
break;
/* pbuf references existing (non-volatile static constant) ROM payload? */
case PBUF_ROM:
/* pbuf references existing (externally allocated) RAM payload? */
case PBUF_REF:
/* only allocate memory for the pbuf structure */
p = (struct pbuf *)memp_malloc(MEMP_PBUF);
if (p == NULL) {
LWIP_DEBUGF(PBUF_DEBUG | <API key>,
("pbuf_alloc: Could not allocate MEMP_PBUF for PBUF_%s.\n",
(type == PBUF_ROM) ? "ROM" : "REF"));
return NULL;
}
/* caller must set this field properly, afterwards */
p->payload = NULL;
p->len = p->tot_len = length;
p->next = NULL;
p->type = type;
break;
default:
LWIP_ASSERT("pbuf_alloc: erroneous type", 0);
return NULL;
}
/* set reference count */
p->ref = 1;
/* set flags */
p->flags = 0;
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F") == %p\n", length, (void *)p));
return p;
}
#if <API key>
/** Initialize a custom pbuf (already allocated).
*
* @param layer flag to define header size
* @param length size of the pbuf's payload
* @param type type of the pbuf (only used to treat the pbuf accordingly, as
* this function allocates no memory)
* @param p pointer to the custom pbuf to initialize (already allocated)
* @param payload_mem pointer to the buffer that is used for payload and headers,
* must be at least big enough to hold 'length' plus the header size,
* may be NULL if set later.
* ATTENTION: The caller is responsible for correct alignment of this buffer!!
* @param payload_mem_len the size of the 'payload_mem' buffer, must be at least
* big enough to hold 'length' plus the header size
*/
struct pbuf*
pbuf_alloced_custom(pbuf_layer l, u16_t length, pbuf_type type, struct pbuf_custom *p,
void *payload_mem, u16_t payload_mem_len)
{
u16_t offset;
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloced_custom(length=%"U16_F")\n", length));
/* determine header offset */
switch (l) {
case PBUF_TRANSPORT:
/* add room for transport (often TCP) layer header */
offset = PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN;
break;
case PBUF_IP:
/* add room for IP layer header */
offset = PBUF_LINK_HLEN + PBUF_IP_HLEN;
break;
case PBUF_LINK:
/* add room for link layer header */
offset = PBUF_LINK_HLEN;
break;
case PBUF_RAW:
offset = 0;
break;
default:
LWIP_ASSERT("pbuf_alloced_custom: bad pbuf layer", 0);
return NULL;
}
if (LWIP_MEM_ALIGN_SIZE(offset) + length > payload_mem_len) {
LWIP_DEBUGF(PBUF_DEBUG | <API key>, ("pbuf_alloced_custom(length=%"U16_F") buffer too short\n", length));
return NULL;
}
p->pbuf.next = NULL;
if (payload_mem != NULL) {
p->pbuf.payload = (u8_t *)payload_mem + LWIP_MEM_ALIGN_SIZE(offset);
} else {
p->pbuf.payload = NULL;
}
p->pbuf.flags = PBUF_FLAG_IS_CUSTOM;
p->pbuf.len = p->pbuf.tot_len = length;
p->pbuf.type = type;
p->pbuf.ref = 1;
return &p->pbuf;
}
#endif /* <API key> */
/**
* Shrink a pbuf chain to a desired length.
*
* @param p pbuf to shrink.
* @param new_len desired new length of pbuf chain
*
* Depending on the desired length, the first few pbufs in a chain might
* be skipped and left unchanged. The new last pbuf in the chain will be
* resized, and any remaining pbufs will be freed.
*
* @note If the pbuf is ROM/REF, only the ->tot_len and ->len fields are adjusted.
* @note May not be called on a packet queue.
*
* @note Despite its name, pbuf_realloc cannot grow the size of a pbuf (chain).
*/
void
pbuf_realloc(struct pbuf *p, u16_t new_len)
{
struct pbuf *q;
u16_t rem_len; /* remaining length */
s32_t grow;
LWIP_ASSERT("pbuf_realloc: p != NULL", p != NULL);
LWIP_ASSERT("pbuf_realloc: sane p->type", p->type == PBUF_POOL ||
p->type == PBUF_ROM ||
p->type == PBUF_RAM ||
p->type == PBUF_REF);
/* desired length larger than current length? */
if (new_len >= p->tot_len) {
/* enlarging not yet supported */
return;
}
/* the pbuf chain grows by (new_len - p->tot_len) bytes
* (which may be negative in case of shrinking) */
grow = new_len - p->tot_len;
/* first, step over any pbufs that should remain in the chain */
rem_len = new_len;
q = p;
/* should this pbuf be kept? */
while (rem_len > q->len) {
/* decrease remaining length by pbuf length */
rem_len -= q->len;
/* decrease total length indicator */
LWIP_ASSERT("grow < max_u16_t", grow < 0xffff);
q->tot_len += (u16_t)grow;
/* proceed to next pbuf in chain */
q = q->next;
LWIP_ASSERT("pbuf_realloc: q != NULL", q != NULL);
}
/* we have now reached the new last pbuf (in q) */
/* rem_len == desired length for pbuf q */
/* shrink allocated memory for PBUF_RAM */
/* (other types merely adjust their length fields */
if ((q->type == PBUF_RAM) && (rem_len != q->len)) {
/* reallocate and adjust the length of the pbuf that will be split */
q = (struct pbuf *)mem_trim(q, (u16_t)((u8_t *)q->payload - (u8_t *)q) + rem_len);
LWIP_ASSERT("mem_trim returned q == NULL", q != NULL);
}
/* adjust length fields for new last pbuf */
q->len = rem_len;
q->tot_len = q->len;
/* any remaining pbufs in chain? */
if (q->next != NULL) {
/* free remaining pbufs in chain */
pbuf_free(q->next);
}
/* q is last packet in chain */
q->next = NULL;
}
/**
* Adjusts the payload pointer to hide or reveal headers in the payload.
*
* Adjusts the ->payload pointer so that space for a header
* (dis)appears in the pbuf payload.
*
* The ->payload, ->tot_len and ->len fields are adjusted.
*
* @param p pbuf to change the header size.
* @param <API key> Number of bytes to increment header size which
* increases the size of the pbuf. New space is on the front.
* (Using a negative value decreases the header size.)
* If hdr_size_inc is 0, this function does nothing and returns succesful.
*
* PBUF_ROM and PBUF_REF type buffers cannot have their sizes increased, so
* the call will fail. A check is made that the increase in header size does
* not move the payload pointer in front of the start of the buffer.
* @return non-zero on failure, zero on success.
*
*/
u8_t
pbuf_header(struct pbuf *p, s16_t <API key>)
{
u16_t type;
void *payload;
u16_t increment_magnitude;
LWIP_ASSERT("p != NULL", p != NULL);
if ((<API key> == 0) || (p == NULL)) {
return 0;
}
if (<API key> < 0){
increment_magnitude = -<API key>;
/* Check that we aren't going to move off the end of the pbuf */
LWIP_ERROR("increment_magnitude <= p->len", (increment_magnitude <= p->len), return 1;);
} else {
increment_magnitude = <API key>;
#if 0
/* Can't assert these as some callers speculatively call
pbuf_header() to see if it's OK. Will return 1 below instead. */
/* Check that we've got the correct type of pbuf to work with */
LWIP_ASSERT("p->type == PBUF_RAM || p->type == PBUF_POOL",
p->type == PBUF_RAM || p->type == PBUF_POOL);
/* Check that we aren't going to move off the beginning of the pbuf */
LWIP_ASSERT("p->payload - increment_magnitude >= p + SIZEOF_STRUCT_PBUF",
(u8_t *)p->payload - increment_magnitude >= (u8_t *)p + SIZEOF_STRUCT_PBUF);
#endif
}
type = p->type;
/* remember current payload pointer */
payload = p->payload;
/* pbuf types containing payloads? */
if (type == PBUF_RAM || type == PBUF_POOL) {
/* set new payload pointer */
p->payload = (u8_t *)p->payload - <API key>;
/* boundary check fails? */
if ((u8_t *)p->payload < (u8_t *)p + SIZEOF_STRUCT_PBUF) {
LWIP_DEBUGF( PBUF_DEBUG | <API key>,
("pbuf_header: failed as %p < %p (not enough space for new header size)\n",
(void *)p->payload, (void *)(p + 1)));
/* restore old payload pointer */
p->payload = payload;
/* bail out unsuccesfully */
return 1;
}
/* pbuf types refering to external payloads? */
} else if (type == PBUF_REF || type == PBUF_ROM) {
/* hide a header in the payload? */
if ((<API key> < 0) && (increment_magnitude <= p->len)) {
/* increase payload pointer */
p->payload = (u8_t *)p->payload - <API key>;
} else {
/* cannot expand payload to front (yet!)
* bail out unsuccesfully */
return 1;
}
} else {
/* Unknown type */
LWIP_ASSERT("bad pbuf type", 0);
return 1;
}
/* modify pbuf length fields */
p->len += <API key>;
p->tot_len += <API key>;
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_header: old %p new %p (%"S16_F")\n",
(void *)payload, (void *)p->payload, <API key>));
return 0;
}
/**
* Dereference a pbuf chain or queue and deallocate any no-longer-used
* pbufs at the head of this chain or queue.
*
* Decrements the pbuf reference count. If it reaches zero, the pbuf is
* deallocated.
*
* For a pbuf chain, this is repeated for each pbuf in the chain,
* up to the first pbuf which has a non-zero reference count after
* decrementing. So, when all reference counts are one, the whole
* chain is free'd.
*
* @param p The pbuf (chain) to be dereferenced.
*
* @return the number of pbufs that were de-allocated
* from the head of the chain.
*
* @note MUST NOT be called on a packet queue (Not verified to work yet).
* @note the reference counter of a pbuf equals the number of pointers
* that refer to the pbuf (or into the pbuf).
*
* @internal examples:
*
* Assuming existing chains a->b->c with the following reference
* counts, calling pbuf_free(a) results in:
*
* 1->2->3 becomes ...1->3
* 3->3->3 becomes 2->3->3
* 1->1->2 becomes ......1
* 2->1->1 becomes 1->1->1
* 1->1->1 becomes .......
*
*/
u8_t
pbuf_free(struct pbuf *p)
{
u16_t type;
struct pbuf *q;
u8_t count;
if (p == NULL) {
LWIP_ASSERT("p != NULL", p != NULL);
/* if assertions are disabled, proceed with debug output */
LWIP_DEBUGF(PBUF_DEBUG | <API key>,
("pbuf_free(p == NULL) was called.\n"));
return 0;
}
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free(%p)\n", (void *)p));
PERF_START;
LWIP_ASSERT("pbuf_free: sane type",
p->type == PBUF_RAM || p->type == PBUF_ROM ||
p->type == PBUF_REF || p->type == PBUF_POOL);
count = 0;
/* de-allocate all consecutive pbufs from the head of the chain that
* obtain a zero reference count after decrementing*/
while (p != NULL) {
u16_t ref;
<API key>(old_level);
/* Since decrementing ref cannot be guaranteed to be a single machine operation
* we must protect it. We put the new ref into a local variable to prevent
* further protection. */
SYS_ARCH_PROTECT(old_level);
/* all pbufs in a chain are referenced at least once */
LWIP_ASSERT("pbuf_free: p->ref > 0", p->ref > 0);
/* decrease reference count (number of pointers to pbuf) */
ref = --(p->ref);
SYS_ARCH_UNPROTECT(old_level);
/* this pbuf is no longer referenced to? */
if (ref == 0) {
/* remember next pbuf in chain for next iteration */
q = p->next;
LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: deallocating %p\n", (void *)p));
type = p->type;
#if <API key>
/* is this a custom pbuf? */
if ((p->flags & PBUF_FLAG_IS_CUSTOM) != 0) {
struct pbuf_custom *pc = (struct pbuf_custom*)p;
LWIP_ASSERT("pc-><API key> != NULL", pc-><API key> != NULL);
pc-><API key>(p);
} else
#endif /* <API key> */
{
/* is this a pbuf from the pool? */
if (type == PBUF_POOL) {
memp_free(MEMP_PBUF_POOL, p);
/* is this a ROM or RAM referencing pbuf? */
} else if (type == PBUF_ROM || type == PBUF_REF) {
memp_free(MEMP_PBUF, p);
/* type == PBUF_RAM */
} else {
mem_free(p);
}
}
count++;
/* proceed to next pbuf */
p = q;
/* p->ref > 0, this pbuf is still referenced to */
/* (and so the remaining pbufs in chain as well) */
} else {
LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: %p has ref %"U16_F", ending here.\n", (void *)p, ref));
/* stop walking through the chain */
p = NULL;
}
}
PERF_STOP("pbuf_free");
/* return number of de-allocated pbufs */
return count;
}
/**
* Count number of pbufs in a chain
*
* @param p first pbuf of chain
* @return the number of pbufs in a chain
*/
u8_t
pbuf_clen(struct pbuf *p)
{
u8_t len;
len = 0;
while (p != NULL) {
++len;
p = p->next;
}
return len;
}
/**
* Increment the reference count of the pbuf.
*
* @param p pbuf to increase reference counter of
*
*/
void
pbuf_ref(struct pbuf *p)
{
<API key>(old_level);
/* pbuf given? */
if (p != NULL) {
SYS_ARCH_PROTECT(old_level);
++(p->ref);
SYS_ARCH_UNPROTECT(old_level);
}
}
/**
* Concatenate two pbufs (each may be a pbuf chain) and take over
* the caller's reference of the tail pbuf.
*
* @note The caller MAY NOT reference the tail pbuf afterwards.
* Use pbuf_chain() for that purpose.
*
* @see pbuf_chain()
*/
void
pbuf_cat(struct pbuf *h, struct pbuf *t)
{
struct pbuf *p;
LWIP_ERROR("(h != NULL) && (t != NULL) (programmer violates API)",
((h != NULL) && (t != NULL)), return;);
/* proceed to last pbuf of chain */
for (p = h; p->next != NULL; p = p->next) {
/* add total length of second chain to all totals of first chain */
p->tot_len += t->tot_len;
}
/* { p is last pbuf of first h chain, p->next == NULL } */
LWIP_ASSERT("p->tot_len == p->len (of last pbuf in chain)", p->tot_len == p->len);
LWIP_ASSERT("p->next == NULL", p->next == NULL);
/* add total length of second chain to last pbuf total of first chain */
p->tot_len += t->tot_len;
/* chain last pbuf of head (p) with first of tail (t) */
p->next = t;
/* p->next now references t, but the caller will drop its reference to t,
* so netto there is no change to the reference count of t.
*/
}
/**
* Chain two pbufs (or pbuf chains) together.
*
* The caller MUST call pbuf_free(t) once it has stopped
* using it. Use pbuf_cat() instead if you no longer use t.
*
* @param h head pbuf (chain)
* @param t tail pbuf (chain)
* @note The pbufs MUST belong to the same packet.
* @note MAY NOT be called on a packet queue.
*
* The ->tot_len fields of all pbufs of the head chain are adjusted.
* The ->next field of the last pbuf of the head chain is adjusted.
* The ->ref field of the first pbuf of the tail chain is adjusted.
*
*/
void
pbuf_chain(struct pbuf *h, struct pbuf *t)
{
pbuf_cat(h, t);
/* t is now referenced by h */
pbuf_ref(t);
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_chain: %p references %p\n", (void *)h, (void *)t));
}
/**
* Dechains the first pbuf from its succeeding pbufs in the chain.
*
* Makes p->tot_len field equal to p->len.
* @param p pbuf to dechain
* @return remainder of the pbuf chain, or NULL if it was de-allocated.
* @note May not be called on a packet queue.
*/
struct pbuf *
pbuf_dechain(struct pbuf *p)
{
struct pbuf *q;
u8_t tail_gone = 1;
/* tail */
q = p->next;
/* pbuf has successor in chain? */
if (q != NULL) {
/* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
LWIP_ASSERT("p->tot_len == p->len + q->tot_len", q->tot_len == p->tot_len - p->len);
/* enforce invariant if assertion is disabled */
q->tot_len = p->tot_len - p->len;
/* decouple pbuf from remainder */
p->next = NULL;
/* total length of pbuf p is its own length only */
p->tot_len = p->len;
/* q is no longer referenced by p, free it */
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_dechain: unreferencing %p\n", (void *)q));
tail_gone = pbuf_free(q);
if (tail_gone > 0) {
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE,
("pbuf_dechain: deallocated %p (as it is no longer referenced)\n", (void *)q));
}
/* return remaining tail or NULL if deallocated */
}
/* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
LWIP_ASSERT("p->tot_len == p->len", p->tot_len == p->len);
return ((tail_gone > 0) ? NULL : q);
}
/**
*
* Create PBUF_RAM copies of pbufs.
*
* Used to queue packets on behalf of the lwIP stack, such as
* ARP based queueing.
*
* @note You MUST explicitly use p = pbuf_take(p);
*
* @note Only one packet is copied, no packet queue!
*
* @param p_to pbuf destination of the copy
* @param p_from pbuf source of the copy
*
* @return ERR_OK if pbuf was copied
* ERR_ARG if one of the pbufs is NULL or p_to is not big
* enough to hold p_from
*/
err_t
pbuf_copy(struct pbuf *p_to, struct pbuf *p_from)
{
u16_t offset_to=0, offset_from=0, len;
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy(%p, %p)\n",
(void*)p_to, (void*)p_from));
/* is the target big enough to hold the source? */
LWIP_ERROR("pbuf_copy: target not big enough to hold source", ((p_to != NULL) &&
(p_from != NULL) && (p_to->tot_len >= p_from->tot_len)), return ERR_ARG;);
/* iterate through pbuf chain */
do
{
/* copy one part of the original chain */
if ((p_to->len - offset_to) >= (p_from->len - offset_from)) {
/* complete current p_from fits into current p_to */
len = p_from->len - offset_from;
} else {
/* current p_from does not fit into current p_to */
len = p_to->len - offset_to;
}
MEMCPY((u8_t*)p_to->payload + offset_to, (u8_t*)p_from->payload + offset_from, len);
offset_to += len;
offset_from += len;
LWIP_ASSERT("offset_to <= p_to->len", offset_to <= p_to->len);
LWIP_ASSERT("offset_from <= p_from->len", offset_from <= p_from->len);
if (offset_from >= p_from->len) {
/* on to next p_from (if any) */
offset_from = 0;
p_from = p_from->next;
}
if (offset_to == p_to->len) {
/* on to next p_to (if any) */
offset_to = 0;
p_to = p_to->next;
LWIP_ERROR("p_to != NULL", (p_to != NULL) || (p_from == NULL) , return ERR_ARG;);
}
if((p_from != NULL) && (p_from->len == p_from->tot_len)) {
/* don't copy more than one packet! */
LWIP_ERROR("pbuf_copy() does not allow packet queues!\n",
(p_from->next == NULL), return ERR_VAL;);
}
if((p_to != NULL) && (p_to->len == p_to->tot_len)) {
/* don't copy more than one packet! */
LWIP_ERROR("pbuf_copy() does not allow packet queues!\n",
(p_to->next == NULL), return ERR_VAL;);
}
} while (p_from);
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy: end of chain reached.\n"));
return ERR_OK;
}
/**
* Copy (part of) the contents of a packet buffer
* to an application supplied buffer.
*
* @param buf the pbuf from which to copy data
* @param dataptr the application supplied buffer
* @param len length of data to copy (dataptr must be big enough). No more
* than buf->tot_len will be copied, irrespective of len
* @param offset offset into the packet buffer from where to begin copying len bytes
* @return the number of bytes copied, or 0 on failure
*/
u16_t
pbuf_copy_partial(struct pbuf *buf, void *dataptr, u16_t len, u16_t offset)
{
struct pbuf *p;
u16_t left;
u16_t buf_copy_len;
u16_t copied_total = 0;
LWIP_ERROR("pbuf_copy_partial: invalid buf", (buf != NULL), return 0;);
LWIP_ERROR("pbuf_copy_partial: invalid dataptr", (dataptr != NULL), return 0;);
left = 0;
if((buf == NULL) || (dataptr == NULL)) {
return 0;
}
/* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
for(p = buf; len != 0 && p != NULL; p = p->next) {
if ((offset != 0) && (offset >= p->len)) {
/* don't copy from this buffer -> on to the next */
offset -= p->len;
} else {
/* copy from this buffer. maybe only partially. */
buf_copy_len = p->len - offset;
if (buf_copy_len > len)
buf_copy_len = len;
/* copy the necessary parts of the buffer */
MEMCPY(&((char*)dataptr)[left], &((char*)p->payload)[offset], buf_copy_len);
copied_total += buf_copy_len;
left += buf_copy_len;
len -= buf_copy_len;
offset = 0;
}
}
return copied_total;
}
/**
* Copy application supplied data into a pbuf.
* This function can only be used to copy the equivalent of buf->tot_len data.
*
* @param buf pbuf to fill with data
* @param dataptr application supplied data buffer
* @param len length of the application supplied data buffer
*
* @return ERR_OK if successful, ERR_MEM if the pbuf is not big enough
*/
err_t
pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len)
{
struct pbuf *p;
u16_t buf_copy_len;
u16_t total_copy_len = len;
u16_t copied_total = 0;
LWIP_ERROR("pbuf_take: invalid buf", (buf != NULL), return 0;);
LWIP_ERROR("pbuf_take: invalid dataptr", (dataptr != NULL), return 0;);
if ((buf == NULL) || (dataptr == NULL) || (buf->tot_len < len)) {
return ERR_ARG;
}
/* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
for(p = buf; total_copy_len != 0; p = p->next) {
LWIP_ASSERT("pbuf_take: invalid pbuf", p != NULL);
buf_copy_len = total_copy_len;
if (buf_copy_len > p->len) {
/* this pbuf cannot hold all remaining data */
buf_copy_len = p->len;
}
/* copy the necessary parts of the buffer */
MEMCPY(p->payload, &((char*)dataptr)[copied_total], buf_copy_len);
total_copy_len -= buf_copy_len;
copied_total += buf_copy_len;
}
LWIP_ASSERT("did not copy all data", total_copy_len == 0 && copied_total == len);
return ERR_OK;
}
/**
* Creates a single pbuf out of a queue of pbufs.
*
* @remark: Either the source pbuf 'p' is freed by this function or the original
* pbuf 'p' is returned, therefore the caller has to check the result!
*
* @param p the source pbuf
* @param layer pbuf_layer of the new pbuf
*
* @return a new, single pbuf (p->next is NULL)
* or the old pbuf if allocation fails
*/
struct pbuf*
pbuf_coalesce(struct pbuf *p, pbuf_layer layer)
{
struct pbuf *q;
err_t err;
if (p->next == NULL) {
return p;
}
q = pbuf_alloc(layer, p->tot_len, PBUF_RAM);
if (q == NULL) {
/* @todo: what do we do now? */
return p;
}
err = pbuf_copy(q, p);
LWIP_ASSERT("pbuf_copy failed", err == ERR_OK);
pbuf_free(p);
return q;
}
#if <API key>
/**
* Copies data into a single pbuf (*not* into a pbuf queue!) and updates
* the checksum while copying
*
* @param p the pbuf to copy data into
* @param start_offset offset of p->payload where to copy the data to
* @param dataptr data to copy into the pbuf
* @param len length of data to copy into the pbuf
* @param chksum pointer to the checksum which is updated
* @return ERR_OK if successful, another error if the data does not fit
* within the (first) pbuf (no pbuf queues!)
*/
err_t
pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr,
u16_t len, u16_t *chksum)
{
u32_t acc;
u16_t copy_chksum;
char *dst_ptr;
LWIP_ASSERT("p != NULL", p != NULL);
LWIP_ASSERT("dataptr != NULL", dataptr != NULL);
LWIP_ASSERT("chksum != NULL", chksum != NULL);
LWIP_ASSERT("len != 0", len != 0);
if ((start_offset >= p->len) || (start_offset + len > p->len)) {
return ERR_ARG;
}
dst_ptr = ((char*)p->payload) + start_offset;
copy_chksum = LWIP_CHKSUM_COPY(dst_ptr, dataptr, len);
if ((start_offset & 1) != 0) {
copy_chksum = SWAP_BYTES_IN_WORD(copy_chksum);
}
acc = *chksum;
acc += copy_chksum;
*chksum = FOLD_U32T(acc);
return ERR_OK;
}
#endif /* <API key> */
/** Get one byte from the specified position in a pbuf
* WARNING: returns zero for offset >= p->tot_len
*
* @param p pbuf to parse
* @param offset offset into p of the byte to return
* @return byte at an offset into p OR ZERO IF 'offset' >= p->tot_len
*/
u8_t
pbuf_get_at(struct pbuf* p, u16_t offset)
{
u16_t copy_from = offset;
struct pbuf* q = p;
/* get the correct pbuf */
while ((q != NULL) && (q->len <= copy_from)) {
copy_from -= q->len;
q = q->next;
}
/* return requested data if pbuf is OK */
if ((q != NULL) && (q->len > copy_from)) {
return ((u8_t*)q->payload)[copy_from];
}
return 0;
}
/** Compare pbuf contents at specified offset with memory s2, both of length n
*
* @param p pbuf to compare
* @param offset offset into p at wich to start comparing
* @param s2 buffer to compare
* @param n length of buffer to compare
* @return zero if equal, nonzero otherwise
* (0xffff if p is too short, diffoffset+1 otherwise)
*/
u16_t
pbuf_memcmp(struct pbuf* p, u16_t offset, const void* s2, u16_t n)
{
u16_t start = offset;
struct pbuf* q = p;
/* get the correct pbuf */
while ((q != NULL) && (q->len <= start)) {
start -= q->len;
q = q->next;
}
/* return requested data if pbuf is OK */
if ((q != NULL) && (q->len > start)) {
u16_t i;
for(i = 0; i < n; i++) {
u8_t a = pbuf_get_at(q, start + i);
u8_t b = ((u8_t*)s2)[i];
if (a != b) {
return i+1;
}
}
return 0;
}
return 0xffff;
}
/** Find occurrence of mem (with length mem_len) in pbuf p, starting at offset
* start_offset.
*
* @param p pbuf to search, maximum length is 0xFFFE since 0xFFFF is used as
* return value 'not found'
* @param mem search for the contents of this buffer
* @param mem_len length of 'mem'
* @param start_offset offset into p at which to start searching
* @return 0xFFFF if substr was not found in p or the index where it was found
*/
u16_t
pbuf_memfind(struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset)
{
u16_t i;
u16_t max = p->tot_len - mem_len;
if (p->tot_len >= mem_len + start_offset) {
for(i = start_offset; i <= max; ) {
u16_t plus = pbuf_memcmp(p, i, mem, mem_len);
if (plus == 0) {
return i;
} else {
i += plus;
}
}
}
return 0xFFFF;
}
/** Find occurrence of substr with length substr_len in pbuf p, start at offset
* start_offset
* WARNING: in contrast to strstr(), this one does not stop at the first \0 in
* the pbuf/source string!
*
* @param p pbuf to search, maximum length is 0xFFFE since 0xFFFF is used as
* return value 'not found'
* @param substr string to search for in p, maximum length is 0xFFFE
* @return 0xFFFF if substr was not found in p or the index where it was found
*/
u16_t
pbuf_strstr(struct pbuf* p, const char* substr)
{
size_t substr_len;
if ((substr == NULL) || (substr[0] == 0) || (p->tot_len == 0xFFFF)) {
return 0xFFFF;
}
substr_len = strlen(substr);
if (substr_len >= 0xFFFF) {
return 0xFFFF;
}
return pbuf_memfind(p, substr, (u16_t)substr_len, 0);
} |
/** \file
*
* Functions to manage the physical Dataflash media, including reading and writing of
* blocks of data. These functions are called by the SCSI layer when data must be stored
* or retrieved to/from the physical storage media. If a different media is used (such
* as a SD card or EEPROM), functions similar to these will need to be generated.
*/
#define <API key>
#include "DataflashManager.h"
/** Writes blocks (OS blocks, not Dataflash pages) to the storage medium, the board Dataflash IC(s), from
* the pre-selected data OUT endpoint. This routine reads in OS sized blocks from the endpoint and writes
* them to the Dataflash in Dataflash page sized blocks.
*
* \param[in] BlockAddress Data block starting address for the write sequence
* \param[in] TotalBlocks Number of blocks of data to write
*/
void <API key>(const uint32_t BlockAddress,
uint16_t TotalBlocks)
{
uint16_t CurrDFPage = ((BlockAddress * <API key>) / DATAFLASH_PAGE_SIZE);
uint16_t CurrDFPageByte = ((BlockAddress * <API key>) % DATAFLASH_PAGE_SIZE);
uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
bool UsingSecondBuffer = false;
/* Select the correct starting Dataflash IC for the block requested */
<API key>(CurrDFPage);
#if (DATAFLASH_PAGE_SIZE > <API key>)
/* Copy selected dataflash's current page contents to the Dataflash buffer */
Dataflash_SendByte(<API key>);
<API key>(CurrDFPage, 0);
<API key>();
#endif
/* Send the Dataflash buffer write command */
Dataflash_SendByte(DF_CMD_BUFF1WRITE);
<API key>(0, CurrDFPageByte);
/* Wait until endpoint is ready before continuing */
if (<API key>())
return;
while (TotalBlocks)
{
uint8_t BytesInBlockDiv16 = 0;
/* Write an endpoint packet sized data block to the Dataflash */
while (BytesInBlockDiv16 < (<API key> >> 4))
{
/* Check if the endpoint is currently empty */
if (!(<API key>()))
{
/* Clear the current endpoint bank */
Endpoint_ClearOUT();
/* Wait until the host has sent another packet */
if (<API key>())
return;
}
/* Check if end of Dataflash page reached */
if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
{
/* Write the Dataflash buffer contents back to the Dataflash page */
<API key>();
Dataflash_SendByte(UsingSecondBuffer ? <API key> : <API key>);
<API key>(CurrDFPage, 0);
/* Reset the Dataflash buffer counter, increment the page counter */
CurrDFPageByteDiv16 = 0;
CurrDFPage++;
/* Once all the Dataflash ICs have had their first buffers filled, switch buffers to maintain throughput */
if (<API key>() == DATAFLASH_CHIP_MASK(<API key>))
UsingSecondBuffer = !(UsingSecondBuffer);
/* Select the next Dataflash chip based on the new Dataflash page index */
<API key>(CurrDFPage);
#if (DATAFLASH_PAGE_SIZE > <API key>)
/* If less than one Dataflash page remaining, copy over the existing page to preserve trailing data */
if ((TotalBlocks * (<API key> >> 4)) < (DATAFLASH_PAGE_SIZE >> 4))
{
/* Copy selected dataflash's current page contents to the Dataflash buffer */
<API key>();
Dataflash_SendByte(UsingSecondBuffer ? <API key> : <API key>);
<API key>(CurrDFPage, 0);
<API key>();
}
#endif
/* Send the Dataflash buffer write command */
Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2WRITE : DF_CMD_BUFF1WRITE);
<API key>(0, 0);
}
/* Write one 16-byte chunk of data to the Dataflash */
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
Dataflash_SendByte(Endpoint_Read_8());
/* Increment the Dataflash page 16 byte block counter */
CurrDFPageByteDiv16++;
/* Increment the block 16 byte block counter */
BytesInBlockDiv16++;
/* Check if the current command is being aborted by the host */
if (IsMassStoreReset)
return;
}
/* Decrement the blocks remaining counter */
TotalBlocks
}
/* Write the Dataflash buffer contents back to the Dataflash page */
<API key>();
Dataflash_SendByte(UsingSecondBuffer ? <API key> : <API key>);
<API key>(CurrDFPage, 0x00);
<API key>();
/* If the endpoint is empty, clear it ready for the next packet from the host */
if (!(<API key>()))
Endpoint_ClearOUT();
/* Deselect all Dataflash chips */
<API key>();
}
/** Reads blocks (OS blocks, not Dataflash pages) from the storage medium, the board Dataflash IC(s), into
* the pre-selected data IN endpoint. This routine reads in Dataflash page sized blocks from the Dataflash
* and writes them in OS sized blocks to the endpoint.
*
* \param[in] BlockAddress Data block starting address for the read sequence
* \param[in] TotalBlocks Number of blocks of data to read
*/
void <API key>(const uint32_t BlockAddress,
uint16_t TotalBlocks)
{
uint16_t CurrDFPage = ((BlockAddress * <API key>) / DATAFLASH_PAGE_SIZE);
uint16_t CurrDFPageByte = ((BlockAddress * <API key>) % DATAFLASH_PAGE_SIZE);
uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
/* Select the correct starting Dataflash IC for the block requested */
<API key>(CurrDFPage);
/* Send the Dataflash main memory page read command */
Dataflash_SendByte(<API key>);
<API key>(CurrDFPage, CurrDFPageByte);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
/* Wait until endpoint is ready before continuing */
if (<API key>())
return;
while (TotalBlocks)
{
uint8_t BytesInBlockDiv16 = 0;
/* Write an endpoint packet sized data block to the Dataflash */
while (BytesInBlockDiv16 < (<API key> >> 4))
{
/* Check if the endpoint is currently full */
if (!(<API key>()))
{
/* Clear the endpoint bank to send its contents to the host */
Endpoint_ClearIN();
/* Wait until the endpoint is ready for more data */
if (<API key>())
return;
}
/* Check if end of Dataflash page reached */
if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
{
/* Reset the Dataflash buffer counter, increment the page counter */
CurrDFPageByteDiv16 = 0;
CurrDFPage++;
/* Select the next Dataflash chip based on the new Dataflash page index */
<API key>(CurrDFPage);
/* Send the Dataflash main memory page read command */
Dataflash_SendByte(<API key>);
<API key>(CurrDFPage, 0);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
}
/* Read one 16-byte chunk of data from the Dataflash */
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
Endpoint_Write_8(<API key>());
/* Increment the Dataflash page 16 byte block counter */
CurrDFPageByteDiv16++;
/* Increment the block 16 byte block counter */
BytesInBlockDiv16++;
/* Check if the current command is being aborted by the host */
if (IsMassStoreReset)
return;
}
/* Decrement the blocks remaining counter */
TotalBlocks
}
/* If the endpoint is full, send its contents to the host */
if (!(<API key>()))
Endpoint_ClearIN();
/* Deselect all Dataflash chips */
<API key>();
}
/** Writes blocks (OS blocks, not Dataflash pages) to the storage medium, the board Dataflash IC(s), from
* the given RAM buffer. This routine reads in OS sized blocks from the buffer and writes them to the
* Dataflash in Dataflash page sized blocks. This can be linked to FAT libraries to write files to the
* Dataflash.
*
* \param[in] BlockAddress Data block starting address for the write sequence
* \param[in] TotalBlocks Number of blocks of data to write
* \param[in] BufferPtr Pointer to the data source RAM buffer
*/
void <API key>(const uint32_t BlockAddress,
uint16_t TotalBlocks,
uint8_t* BufferPtr)
{
uint16_t CurrDFPage = ((BlockAddress * <API key>) / DATAFLASH_PAGE_SIZE);
uint16_t CurrDFPageByte = ((BlockAddress * <API key>) % DATAFLASH_PAGE_SIZE);
uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
bool UsingSecondBuffer = false;
/* Select the correct starting Dataflash IC for the block requested */
<API key>(CurrDFPage);
#if (DATAFLASH_PAGE_SIZE > <API key>)
/* Copy selected dataflash's current page contents to the Dataflash buffer */
Dataflash_SendByte(<API key>);
<API key>(CurrDFPage, 0);
<API key>();
#endif
/* Send the Dataflash buffer write command */
Dataflash_SendByte(DF_CMD_BUFF1WRITE);
<API key>(0, CurrDFPageByte);
while (TotalBlocks)
{
uint8_t BytesInBlockDiv16 = 0;
/* Write an endpoint packet sized data block to the Dataflash */
while (BytesInBlockDiv16 < (<API key> >> 4))
{
/* Check if end of Dataflash page reached */
if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
{
/* Write the Dataflash buffer contents back to the Dataflash page */
<API key>();
Dataflash_SendByte(UsingSecondBuffer ? <API key> : <API key>);
<API key>(CurrDFPage, 0);
/* Reset the Dataflash buffer counter, increment the page counter */
CurrDFPageByteDiv16 = 0;
CurrDFPage++;
/* Once all the Dataflash ICs have had their first buffers filled, switch buffers to maintain throughput */
if (<API key>() == DATAFLASH_CHIP_MASK(<API key>))
UsingSecondBuffer = !(UsingSecondBuffer);
/* Select the next Dataflash chip based on the new Dataflash page index */
<API key>(CurrDFPage);
#if (DATAFLASH_PAGE_SIZE > <API key>)
/* If less than one Dataflash page remaining, copy over the existing page to preserve trailing data */
if ((TotalBlocks * (<API key> >> 4)) < (DATAFLASH_PAGE_SIZE >> 4))
{
/* Copy selected dataflash's current page contents to the Dataflash buffer */
<API key>();
Dataflash_SendByte(UsingSecondBuffer ? <API key> : <API key>);
<API key>(CurrDFPage, 0);
<API key>();
}
#endif
/* Send the Dataflash buffer write command */
<API key>();
Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2WRITE : DF_CMD_BUFF1WRITE);
<API key>(0, 0);
}
/* Write one 16-byte chunk of data to the Dataflash */
for (uint8_t ByteNum = 0; ByteNum < 16; ByteNum++)
Dataflash_SendByte(*(BufferPtr++));
/* Increment the Dataflash page 16 byte block counter */
CurrDFPageByteDiv16++;
/* Increment the block 16 byte block counter */
BytesInBlockDiv16++;
}
/* Decrement the blocks remaining counter */
TotalBlocks
}
/* Write the Dataflash buffer contents back to the Dataflash page */
<API key>();
Dataflash_SendByte(UsingSecondBuffer ? <API key> : <API key>);
<API key>(CurrDFPage, 0x00);
<API key>();
/* Deselect all Dataflash chips */
<API key>();
}
/** Reads blocks (OS blocks, not Dataflash pages) from the storage medium, the board Dataflash IC(s), into
* the preallocated RAM buffer. This routine reads in Dataflash page sized blocks from the Dataflash
* and writes them in OS sized blocks to the given buffer. This can be linked to FAT libraries to read
* the files stored on the Dataflash.
*
* \param[in] BlockAddress Data block starting address for the read sequence
* \param[in] TotalBlocks Number of blocks of data to read
* \param[out] BufferPtr Pointer to the data destination RAM buffer
*/
void <API key>(const uint32_t BlockAddress,
uint16_t TotalBlocks,
uint8_t* BufferPtr)
{
uint16_t CurrDFPage = ((BlockAddress * <API key>) / DATAFLASH_PAGE_SIZE);
uint16_t CurrDFPageByte = ((BlockAddress * <API key>) % DATAFLASH_PAGE_SIZE);
uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
/* Select the correct starting Dataflash IC for the block requested */
<API key>(CurrDFPage);
/* Send the Dataflash main memory page read command */
Dataflash_SendByte(<API key>);
<API key>(CurrDFPage, CurrDFPageByte);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
while (TotalBlocks)
{
uint8_t BytesInBlockDiv16 = 0;
/* Write an endpoint packet sized data block to the Dataflash */
while (BytesInBlockDiv16 < (<API key> >> 4))
{
/* Check if end of Dataflash page reached */
if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
{
/* Reset the Dataflash buffer counter, increment the page counter */
CurrDFPageByteDiv16 = 0;
CurrDFPage++;
/* Select the next Dataflash chip based on the new Dataflash page index */
<API key>(CurrDFPage);
/* Send the Dataflash main memory page read command */
Dataflash_SendByte(<API key>);
<API key>(CurrDFPage, 0);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
}
/* Read one 16-byte chunk of data from the Dataflash */
for (uint8_t ByteNum = 0; ByteNum < 16; ByteNum++)
*(BufferPtr++) = <API key>();
/* Increment the Dataflash page 16 byte block counter */
CurrDFPageByteDiv16++;
/* Increment the block 16 byte block counter */
BytesInBlockDiv16++;
}
/* Decrement the blocks remaining counter */
TotalBlocks
}
/* Deselect all Dataflash chips */
<API key>();
}
/** Disables the Dataflash memory write protection bits on the board Dataflash ICs, if enabled. */
void <API key>(void)
{
/* Select first Dataflash chip, send the read status register command */
<API key>(DATAFLASH_CHIP1);
Dataflash_SendByte(DF_CMD_GETSTATUS);
/* Check if sector protection is enabled */
if (<API key>() & <API key>)
{
<API key>();
/* Send the commands to disable sector protection */
Dataflash_SendByte(<API key>[0]);
Dataflash_SendByte(<API key>[1]);
Dataflash_SendByte(<API key>[2]);
Dataflash_SendByte(<API key>[3]);
}
/* Select second Dataflash chip (if present on selected board), send read status register command */
#if (<API key> == 2)
<API key>(DATAFLASH_CHIP2);
Dataflash_SendByte(DF_CMD_GETSTATUS);
/* Check if sector protection is enabled */
if (<API key>() & <API key>)
{
<API key>();
/* Send the commands to disable sector protection */
Dataflash_SendByte(<API key>[0]);
Dataflash_SendByte(<API key>[1]);
Dataflash_SendByte(<API key>[2]);
Dataflash_SendByte(<API key>[3]);
}
#endif
/* Deselect current Dataflash chip */
<API key>();
}
/** Performs a simple test on the attached Dataflash IC(s) to ensure that they are working.
*
* \return Boolean \c true if all media chips are working, \c false otherwise
*/
bool <API key>(void)
{
uint8_t ReturnByte;
/* Test first Dataflash IC is present and responding to commands */
<API key>(DATAFLASH_CHIP1);
Dataflash_SendByte(<API key>);
ReturnByte = <API key>();
<API key>();
/* If returned data is invalid, fail the command */
if (ReturnByte != <API key>)
return false;
#if (<API key> == 2)
/* Test second Dataflash IC is present and responding to commands */
<API key>(DATAFLASH_CHIP2);
Dataflash_SendByte(<API key>);
ReturnByte = <API key>();
<API key>();
/* If returned data is invalid, fail the command */
if (ReturnByte != <API key>)
return false;
#endif
return true;
} |
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/dmaengine.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/sh_dma.h>
#include <linux/notifier.h>
#include <linux/kdebug.h>
#include <linux/spinlock.h>
#include <linux/rculist.h>
#include "dmaengine.h"
#include "shdma.h"
enum sh_dmae_desc_status {
DESC_IDLE,
DESC_PREPARED,
DESC_SUBMITTED,
DESC_COMPLETED,
DESC_WAITING,
};
#define <API key> 32
#define <API key> 2
static DEFINE_SPINLOCK(sh_dmae_lock);
static LIST_HEAD(sh_dmae_devices);
static unsigned long sh_dmae_slave_used[BITS_TO_LONGS(SH_DMA_SLAVE_NUMBER)];
static void <API key>(struct sh_dmae_chan *sh_chan, bool all);
static void <API key>(struct sh_dmae_chan *sh_chan);
static void chclr_write(struct sh_dmae_chan *sh_dc, u32 data)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_dc);
__raw_writel(data, shdev->chan_reg +
shdev->pdata->channel[sh_dc->id].chclr_offset);
}
static void sh_dmae_writel(struct sh_dmae_chan *sh_dc, u32 data, u32 reg)
{
__raw_writel(data, sh_dc->base + reg / sizeof(u32));
}
static u32 sh_dmae_readl(struct sh_dmae_chan *sh_dc, u32 reg)
{
return __raw_readl(sh_dc->base + reg / sizeof(u32));
}
static u16 dmaor_read(struct sh_dmae_device *shdev)
{
u32 __iomem *addr = shdev->chan_reg + DMAOR / sizeof(u32);
if (shdev->pdata->dmaor_is_32bit)
return __raw_readl(addr);
else
return __raw_readw(addr);
}
static void dmaor_write(struct sh_dmae_device *shdev, u16 data)
{
u32 __iomem *addr = shdev->chan_reg + DMAOR / sizeof(u32);
if (shdev->pdata->dmaor_is_32bit)
__raw_writel(data, addr);
else
__raw_writew(data, addr);
}
static void chcr_write(struct sh_dmae_chan *sh_dc, u32 data)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_dc);
__raw_writel(data, sh_dc->base + shdev->chcr_offset / sizeof(u32));
}
static u32 chcr_read(struct sh_dmae_chan *sh_dc)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_dc);
return __raw_readl(sh_dc->base + shdev->chcr_offset / sizeof(u32));
}
static void sh_dmae_ctl_stop(struct sh_dmae_device *shdev)
{
unsigned short dmaor;
unsigned long flags;
spin_lock_irqsave(&sh_dmae_lock, flags);
dmaor = dmaor_read(shdev);
dmaor_write(shdev, dmaor & ~(DMAOR_NMIF | DMAOR_AE | DMAOR_DME));
<API key>(&sh_dmae_lock, flags);
}
static int sh_dmae_rst(struct sh_dmae_device *shdev)
{
unsigned short dmaor;
unsigned long flags;
spin_lock_irqsave(&sh_dmae_lock, flags);
dmaor = dmaor_read(shdev) & ~(DMAOR_NMIF | DMAOR_AE | DMAOR_DME);
if (shdev->pdata->chclr_present) {
int i;
for (i = 0; i < shdev->pdata->channel_num; i++) {
struct sh_dmae_chan *sh_chan = shdev->chan[i];
if (sh_chan)
chclr_write(sh_chan, 0);
}
}
dmaor_write(shdev, dmaor | shdev->pdata->dmaor_init);
dmaor = dmaor_read(shdev);
<API key>(&sh_dmae_lock, flags);
if (dmaor & (DMAOR_AE | DMAOR_NMIF)) {
dev_warn(shdev->common.dev, "Can't initialize DMAOR.\n");
return -EIO;
}
if (shdev->pdata->dmaor_init & ~dmaor)
dev_warn(shdev->common.dev,
"DMAOR=0x%x hasn't latched the initial value 0x%x.\n",
dmaor, shdev->pdata->dmaor_init);
return 0;
}
static bool dmae_is_busy(struct sh_dmae_chan *sh_chan)
{
u32 chcr = chcr_read(sh_chan);
if ((chcr & (CHCR_DE | CHCR_TE)) == CHCR_DE)
return true;
return false;
}
static unsigned int calc_xmit_shift(struct sh_dmae_chan *sh_chan, u32 chcr)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
struct sh_dmae_pdata *pdata = shdev->pdata;
int cnt = ((chcr & pdata->ts_low_mask) >> pdata->ts_low_shift) |
((chcr & pdata->ts_high_mask) >> pdata->ts_high_shift);
if (cnt >= pdata->ts_shift_num)
cnt = 0;
return pdata->ts_shift[cnt];
}
static u32 log2size_to_chcr(struct sh_dmae_chan *sh_chan, int l2size)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
struct sh_dmae_pdata *pdata = shdev->pdata;
int i;
for (i = 0; i < pdata->ts_shift_num; i++)
if (pdata->ts_shift[i] == l2size)
break;
if (i == pdata->ts_shift_num)
i = 0;
return ((i << pdata->ts_low_shift) & pdata->ts_low_mask) |
((i << pdata->ts_high_shift) & pdata->ts_high_mask);
}
static void dmae_set_reg(struct sh_dmae_chan *sh_chan, struct sh_dmae_regs *hw)
{
sh_dmae_writel(sh_chan, hw->sar, SAR);
sh_dmae_writel(sh_chan, hw->dar, DAR);
sh_dmae_writel(sh_chan, hw->tcr >> sh_chan->xmit_shift, TCR);
}
static void dmae_start(struct sh_dmae_chan *sh_chan)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
u32 chcr = chcr_read(sh_chan);
if (shdev->pdata->needs_tend_set)
sh_dmae_writel(sh_chan, 0xFFFFFFFF, TEND);
chcr |= CHCR_DE | shdev->chcr_ie_bit;
chcr_write(sh_chan, chcr & ~CHCR_TE);
}
static void dmae_halt(struct sh_dmae_chan *sh_chan)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
u32 chcr = chcr_read(sh_chan);
chcr &= ~(CHCR_DE | CHCR_TE | shdev->chcr_ie_bit);
chcr_write(sh_chan, chcr);
}
static void dmae_init(struct sh_dmae_chan *sh_chan)
{
u32 chcr = DM_INC | SM_INC | 0x400 | log2size_to_chcr(sh_chan,
<API key>);
sh_chan->xmit_shift = calc_xmit_shift(sh_chan, chcr);
chcr_write(sh_chan, chcr);
}
static int dmae_set_chcr(struct sh_dmae_chan *sh_chan, u32 val)
{
if (dmae_is_busy(sh_chan))
return -EBUSY;
sh_chan->xmit_shift = calc_xmit_shift(sh_chan, val);
chcr_write(sh_chan, val);
return 0;
}
static int dmae_set_dmars(struct sh_dmae_chan *sh_chan, u16 val)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
struct sh_dmae_pdata *pdata = shdev->pdata;
const struct sh_dmae_channel *chan_pdata = &pdata->channel[sh_chan->id];
u16 __iomem *addr = shdev->dmars;
unsigned int shift = chan_pdata->dmars_bit;
if (dmae_is_busy(sh_chan))
return -EBUSY;
if (pdata->no_dmars)
return 0;
if (!addr)
addr = (u16 __iomem *)shdev->chan_reg;
addr += chan_pdata->dmars / sizeof(u16);
__raw_writew((__raw_readw(addr) & (0xff00 >> shift)) | (val << shift),
addr);
return 0;
}
static dma_cookie_t sh_dmae_tx_submit(struct <API key> *tx)
{
struct sh_desc *desc = tx_to_sh_desc(tx), *chunk, *last = desc, *c;
struct sh_dmae_chan *sh_chan = to_sh_chan(tx->chan);
struct sh_dmae_slave *param = tx->chan->private;
<API key> callback = tx->callback;
dma_cookie_t cookie;
bool power_up;
spin_lock_irq(&sh_chan->desc_lock);
if (list_empty(&sh_chan->ld_queue))
power_up = true;
else
power_up = false;
cookie = dma_cookie_assign(tx);
<API key>(chunk, c, desc->node.prev, node) {
if (chunk != desc && (chunk->mark == DESC_IDLE ||
chunk->async_tx.cookie > 0 ||
chunk->async_tx.cookie == -EBUSY ||
&chunk->node == &sh_chan->ld_free))
break;
chunk->mark = DESC_SUBMITTED;
chunk->async_tx.callback = NULL;
chunk->cookie = cookie;
list_move_tail(&chunk->node, &sh_chan->ld_queue);
last = chunk;
}
last->async_tx.callback = callback;
last->async_tx.callback_param = tx->callback_param;
dev_dbg(sh_chan->dev, "submit #%d@%p on %d: %x[%d] -> %x\n",
tx->cookie, &last->async_tx, sh_chan->id,
desc->hw.sar, desc->hw.tcr, desc->hw.dar);
if (power_up) {
sh_chan->pm_state = DMAE_PM_BUSY;
pm_runtime_get(sh_chan->dev);
spin_unlock_irq(&sh_chan->desc_lock);
pm_runtime_barrier(sh_chan->dev);
spin_lock_irq(&sh_chan->desc_lock);
if (sh_chan->pm_state != DMAE_PM_ESTABLISHED) {
dev_dbg(sh_chan->dev, "Bring up channel %d\n",
sh_chan->id);
if (param) {
const struct <API key> *cfg =
param->config;
dmae_set_dmars(sh_chan, cfg->mid_rid);
dmae_set_chcr(sh_chan, cfg->chcr);
} else {
dmae_init(sh_chan);
}
if (sh_chan->pm_state == DMAE_PM_PENDING)
<API key>(sh_chan);
sh_chan->pm_state = DMAE_PM_ESTABLISHED;
}
} else {
sh_chan->pm_state = DMAE_PM_PENDING;
}
spin_unlock_irq(&sh_chan->desc_lock);
return cookie;
}
static struct sh_desc *sh_dmae_get_desc(struct sh_dmae_chan *sh_chan)
{
struct sh_desc *desc;
list_for_each_entry(desc, &sh_chan->ld_free, node)
if (desc->mark != DESC_PREPARED) {
BUG_ON(desc->mark != DESC_IDLE);
list_del(&desc->node);
return desc;
}
return NULL;
}
static const struct <API key> *sh_dmae_find_slave(
struct sh_dmae_chan *sh_chan, struct sh_dmae_slave *param)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
struct sh_dmae_pdata *pdata = shdev->pdata;
int i;
if (param->slave_id >= SH_DMA_SLAVE_NUMBER)
return NULL;
for (i = 0; i < pdata->slave_num; i++)
if (pdata->slave[i].slave_id == param->slave_id)
return pdata->slave + i;
return NULL;
}
static int <API key>(struct dma_chan *chan)
{
struct sh_dmae_chan *sh_chan = to_sh_chan(chan);
struct sh_desc *desc;
struct sh_dmae_slave *param = chan->private;
int ret;
if (param) {
const struct <API key> *cfg;
cfg = sh_dmae_find_slave(sh_chan, param);
if (!cfg) {
ret = -EINVAL;
goto efindslave;
}
if (test_and_set_bit(param->slave_id, sh_dmae_slave_used)) {
ret = -EBUSY;
goto etestused;
}
param->config = cfg;
}
while (sh_chan->descs_allocated < <API key>) {
desc = kzalloc(sizeof(struct sh_desc), GFP_KERNEL);
if (!desc)
break;
<API key>(&desc->async_tx,
&sh_chan->common);
desc->async_tx.tx_submit = sh_dmae_tx_submit;
desc->mark = DESC_IDLE;
list_add(&desc->node, &sh_chan->ld_free);
sh_chan->descs_allocated++;
}
if (!sh_chan->descs_allocated) {
ret = -ENOMEM;
goto edescalloc;
}
return sh_chan->descs_allocated;
edescalloc:
if (param)
clear_bit(param->slave_id, sh_dmae_slave_used);
etestused:
efindslave:
chan->private = NULL;
return ret;
}
static void <API key>(struct dma_chan *chan)
{
struct sh_dmae_chan *sh_chan = to_sh_chan(chan);
struct sh_desc *desc, *_desc;
LIST_HEAD(list);
spin_lock_irq(&sh_chan->desc_lock);
dmae_halt(sh_chan);
spin_unlock_irq(&sh_chan->desc_lock);
if (!list_empty(&sh_chan->ld_queue))
<API key>(sh_chan, true);
if (chan->private) {
struct sh_dmae_slave *param = chan->private;
clear_bit(param->slave_id, sh_dmae_slave_used);
chan->private = NULL;
}
spin_lock_irq(&sh_chan->desc_lock);
list_splice_init(&sh_chan->ld_free, &list);
sh_chan->descs_allocated = 0;
spin_unlock_irq(&sh_chan->desc_lock);
<API key>(desc, _desc, &list, node)
kfree(desc);
}
static struct sh_desc *sh_dmae_add_desc(struct sh_dmae_chan *sh_chan,
unsigned long flags, dma_addr_t *dest, dma_addr_t *src, size_t *len,
struct sh_desc **first, enum <API key> direction)
{
struct sh_desc *new;
size_t copy_size;
if (!*len)
return NULL;
new = sh_dmae_get_desc(sh_chan);
if (!new) {
dev_err(sh_chan->dev, "No free link descriptor available\n");
return NULL;
}
copy_size = min(*len, (size_t)SH_DMA_TCR_MAX + 1);
new->hw.sar = *src;
new->hw.dar = *dest;
new->hw.tcr = copy_size;
if (!*first) {
new->async_tx.cookie = -EBUSY;
*first = new;
} else {
new->async_tx.cookie = -EINVAL;
}
dev_dbg(sh_chan->dev,
"chaining (%u/%u)@%x -> %x with %p, cookie %d, shift %d\n",
copy_size, *len, *src, *dest, &new->async_tx,
new->async_tx.cookie, sh_chan->xmit_shift);
new->mark = DESC_PREPARED;
new->async_tx.flags = flags;
new->direction = direction;
*len -= copy_size;
if (direction == DMA_MEM_TO_MEM || direction == DMA_MEM_TO_DEV)
*src += copy_size;
if (direction == DMA_MEM_TO_MEM || direction == DMA_DEV_TO_MEM)
*dest += copy_size;
return new;
}
static struct <API key> *sh_dmae_prep_sg(struct sh_dmae_chan *sh_chan,
struct scatterlist *sgl, unsigned int sg_len, dma_addr_t *addr,
enum <API key> direction, unsigned long flags)
{
struct scatterlist *sg;
struct sh_desc *first = NULL, *new = NULL ;
LIST_HEAD(tx_list);
int chunks = 0;
unsigned long irq_flags;
int i;
if (!sg_len)
return NULL;
for_each_sg(sgl, sg, sg_len, i)
chunks += (sg_dma_len(sg) + SH_DMA_TCR_MAX) /
(SH_DMA_TCR_MAX + 1);
spin_lock_irqsave(&sh_chan->desc_lock, irq_flags);
for_each_sg(sgl, sg, sg_len, i) {
dma_addr_t sg_addr = sg_dma_address(sg);
size_t len = sg_dma_len(sg);
if (!len)
goto err_get_desc;
do {
dev_dbg(sh_chan->dev, "Add SG #%d@%p[%d], dma %llx\n",
i, sg, len, (unsigned long long)sg_addr);
if (direction == DMA_DEV_TO_MEM)
new = sh_dmae_add_desc(sh_chan, flags,
&sg_addr, addr, &len, &first,
direction);
else
new = sh_dmae_add_desc(sh_chan, flags,
addr, &sg_addr, &len, &first,
direction);
if (!new)
goto err_get_desc;
new->chunks = chunks
list_add_tail(&new->node, &tx_list);
} while (len);
}
if (new != first)
new->async_tx.cookie = -ENOSPC;
list_splice_tail(&tx_list, &sh_chan->ld_free);
<API key>(&sh_chan->desc_lock, irq_flags);
return &first->async_tx;
err_get_desc:
list_for_each_entry(new, &tx_list, node)
new->mark = DESC_IDLE;
list_splice(&tx_list, &sh_chan->ld_free);
<API key>(&sh_chan->desc_lock, irq_flags);
return NULL;
}
static struct <API key> *sh_dmae_prep_memcpy(
struct dma_chan *chan, dma_addr_t dma_dest, dma_addr_t dma_src,
size_t len, unsigned long flags)
{
struct sh_dmae_chan *sh_chan;
struct scatterlist sg;
if (!chan || !len)
return NULL;
sh_chan = to_sh_chan(chan);
sg_init_table(&sg, 1);
sg_set_page(&sg, pfn_to_page(PFN_DOWN(dma_src)), len,
offset_in_page(dma_src));
sg_dma_address(&sg) = dma_src;
sg_dma_len(&sg) = len;
return sh_dmae_prep_sg(sh_chan, &sg, 1, &dma_dest, DMA_MEM_TO_MEM,
flags);
}
static struct <API key> *<API key>(
struct dma_chan *chan, struct scatterlist *sgl, unsigned int sg_len,
enum <API key> direction, unsigned long flags,
void *context)
{
struct sh_dmae_slave *param;
struct sh_dmae_chan *sh_chan;
dma_addr_t slave_addr;
if (!chan)
return NULL;
sh_chan = to_sh_chan(chan);
param = chan->private;
if (!param || !sg_len) {
dev_warn(sh_chan->dev, "%s: bad parameter: %p, %d, %d\n",
__func__, param, sg_len, param ? param->slave_id : -1);
return NULL;
}
slave_addr = param->config->addr;
return sh_dmae_prep_sg(sh_chan, sgl, sg_len, &slave_addr,
direction, flags);
}
static int sh_dmae_control(struct dma_chan *chan, enum dma_ctrl_cmd cmd,
unsigned long arg)
{
struct sh_dmae_chan *sh_chan = to_sh_chan(chan);
unsigned long flags;
if (cmd != DMA_TERMINATE_ALL)
return -ENXIO;
if (!chan)
return -EINVAL;
spin_lock_irqsave(&sh_chan->desc_lock, flags);
dmae_halt(sh_chan);
if (!list_empty(&sh_chan->ld_queue)) {
struct sh_desc *desc = list_entry(sh_chan->ld_queue.next,
struct sh_desc, node);
desc->partial = (desc->hw.tcr - sh_dmae_readl(sh_chan, TCR)) <<
sh_chan->xmit_shift;
}
<API key>(&sh_chan->desc_lock, flags);
<API key>(sh_chan, true);
return 0;
}
static <API key> __ld_cleanup(struct sh_dmae_chan *sh_chan, bool all)
{
struct sh_desc *desc, *_desc;
bool head_acked = false;
dma_cookie_t cookie = 0;
<API key> callback = NULL;
void *param = NULL;
unsigned long flags;
spin_lock_irqsave(&sh_chan->desc_lock, flags);
<API key>(desc, _desc, &sh_chan->ld_queue, node) {
struct <API key> *tx = &desc->async_tx;
BUG_ON(tx->cookie > 0 && tx->cookie != desc->cookie);
BUG_ON(desc->mark != DESC_SUBMITTED &&
desc->mark != DESC_COMPLETED &&
desc->mark != DESC_WAITING);
if (!all && desc->mark == DESC_SUBMITTED &&
desc->cookie != cookie)
break;
if (tx->cookie > 0)
cookie = tx->cookie;
if (desc->mark == DESC_COMPLETED && desc->chunks == 1) {
if (sh_chan->common.completed_cookie != desc->cookie - 1)
dev_dbg(sh_chan->dev,
"Completing cookie %d, expected %d\n",
desc->cookie,
sh_chan->common.completed_cookie + 1);
sh_chan->common.completed_cookie = desc->cookie;
}
if (desc->mark == DESC_COMPLETED && tx->callback) {
desc->mark = DESC_WAITING;
callback = tx->callback;
param = tx->callback_param;
dev_dbg(sh_chan->dev, "descriptor #%d@%p on %d callback\n",
tx->cookie, tx, sh_chan->id);
BUG_ON(desc->chunks != 1);
break;
}
if (tx->cookie > 0 || tx->cookie == -EBUSY) {
if (desc->mark == DESC_COMPLETED) {
BUG_ON(tx->cookie < 0);
desc->mark = DESC_WAITING;
}
head_acked = async_tx_test_ack(tx);
} else {
switch (desc->mark) {
case DESC_COMPLETED:
desc->mark = DESC_WAITING;
case DESC_WAITING:
if (head_acked)
async_tx_ack(&desc->async_tx);
}
}
dev_dbg(sh_chan->dev, "descriptor %p #%d completed.\n",
tx, tx->cookie);
if (((desc->mark == DESC_COMPLETED ||
desc->mark == DESC_WAITING) &&
async_tx_test_ack(&desc->async_tx)) || all) {
desc->mark = DESC_IDLE;
list_move(&desc->node, &sh_chan->ld_free);
if (list_empty(&sh_chan->ld_queue)) {
dev_dbg(sh_chan->dev, "Bring down channel %d\n", sh_chan->id);
pm_runtime_put(sh_chan->dev);
}
}
}
if (all && !callback)
sh_chan->common.completed_cookie = sh_chan->common.cookie;
<API key>(&sh_chan->desc_lock, flags);
if (callback)
callback(param);
return callback;
}
static void <API key>(struct sh_dmae_chan *sh_chan, bool all)
{
while (__ld_cleanup(sh_chan, all))
;
}
static void <API key>(struct sh_dmae_chan *sh_chan)
{
struct sh_desc *desc;
if (dmae_is_busy(sh_chan))
return;
list_for_each_entry(desc, &sh_chan->ld_queue, node)
if (desc->mark == DESC_SUBMITTED) {
dev_dbg(sh_chan->dev, "Queue #%d to %d: %u@%x -> %x\n",
desc->async_tx.cookie, sh_chan->id,
desc->hw.tcr, desc->hw.sar, desc->hw.dar);
dmae_set_reg(sh_chan, &desc->hw);
dmae_start(sh_chan);
break;
}
}
static void <API key>(struct dma_chan *chan)
{
struct sh_dmae_chan *sh_chan = to_sh_chan(chan);
spin_lock_irq(&sh_chan->desc_lock);
if (sh_chan->pm_state == DMAE_PM_ESTABLISHED)
<API key>(sh_chan);
else
sh_chan->pm_state = DMAE_PM_PENDING;
spin_unlock_irq(&sh_chan->desc_lock);
}
static enum dma_status sh_dmae_tx_status(struct dma_chan *chan,
dma_cookie_t cookie,
struct dma_tx_state *txstate)
{
struct sh_dmae_chan *sh_chan = to_sh_chan(chan);
enum dma_status status;
unsigned long flags;
<API key>(sh_chan, false);
spin_lock_irqsave(&sh_chan->desc_lock, flags);
status = dma_cookie_status(chan, cookie, txstate);
if (status != DMA_SUCCESS) {
struct sh_desc *desc;
status = DMA_ERROR;
list_for_each_entry(desc, &sh_chan->ld_queue, node)
if (desc->cookie == cookie) {
status = DMA_IN_PROGRESS;
break;
}
}
<API key>(&sh_chan->desc_lock, flags);
return status;
}
static irqreturn_t sh_dmae_interrupt(int irq, void *data)
{
irqreturn_t ret = IRQ_NONE;
struct sh_dmae_chan *sh_chan = data;
u32 chcr;
spin_lock(&sh_chan->desc_lock);
chcr = chcr_read(sh_chan);
if (chcr & CHCR_TE) {
dmae_halt(sh_chan);
ret = IRQ_HANDLED;
tasklet_schedule(&sh_chan->tasklet);
}
spin_unlock(&sh_chan->desc_lock);
return ret;
}
static bool sh_dmae_reset(struct sh_dmae_device *shdev)
{
unsigned int handled = 0;
int i;
sh_dmae_ctl_stop(shdev);
for (i = 0; i < <API key>; i++) {
struct sh_dmae_chan *sh_chan = shdev->chan[i];
struct sh_desc *desc;
LIST_HEAD(dl);
if (!sh_chan)
continue;
spin_lock(&sh_chan->desc_lock);
dmae_halt(sh_chan);
list_splice_init(&sh_chan->ld_queue, &dl);
if (!list_empty(&dl)) {
dev_dbg(sh_chan->dev, "Bring down channel %d\n", sh_chan->id);
pm_runtime_put(sh_chan->dev);
}
sh_chan->pm_state = DMAE_PM_ESTABLISHED;
spin_unlock(&sh_chan->desc_lock);
list_for_each_entry(desc, &dl, node) {
struct <API key> *tx = &desc->async_tx;
desc->mark = DESC_IDLE;
if (tx->callback)
tx->callback(tx->callback_param);
}
spin_lock(&sh_chan->desc_lock);
list_splice(&dl, &sh_chan->ld_free);
spin_unlock(&sh_chan->desc_lock);
handled++;
}
sh_dmae_rst(shdev);
return !!handled;
}
static irqreturn_t sh_dmae_err(int irq, void *data)
{
struct sh_dmae_device *shdev = data;
if (!(dmaor_read(shdev) & DMAOR_AE))
return IRQ_NONE;
sh_dmae_reset(data);
return IRQ_HANDLED;
}
static void dmae_do_tasklet(unsigned long data)
{
struct sh_dmae_chan *sh_chan = (struct sh_dmae_chan *)data;
struct sh_desc *desc;
u32 sar_buf = sh_dmae_readl(sh_chan, SAR);
u32 dar_buf = sh_dmae_readl(sh_chan, DAR);
spin_lock_irq(&sh_chan->desc_lock);
list_for_each_entry(desc, &sh_chan->ld_queue, node) {
if (desc->mark == DESC_SUBMITTED &&
((desc->direction == DMA_DEV_TO_MEM &&
(desc->hw.dar + desc->hw.tcr) == dar_buf) ||
(desc->hw.sar + desc->hw.tcr) == sar_buf)) {
dev_dbg(sh_chan->dev, "done #%d@%p dst %u\n",
desc->async_tx.cookie, &desc->async_tx,
desc->hw.dar);
desc->mark = DESC_COMPLETED;
break;
}
}
<API key>(sh_chan);
spin_unlock_irq(&sh_chan->desc_lock);
<API key>(sh_chan, false);
}
static bool sh_dmae_nmi_notify(struct sh_dmae_device *shdev)
{
if ((dmaor_read(shdev) & DMAOR_NMIF) == 0)
return false;
return sh_dmae_reset(shdev);
}
static int sh_dmae_nmi_handler(struct notifier_block *self,
unsigned long cmd, void *data)
{
struct sh_dmae_device *shdev;
int ret = NOTIFY_DONE;
bool triggered;
if (!in_nmi())
return NOTIFY_DONE;
rcu_read_lock();
<API key>(shdev, &sh_dmae_devices, node) {
triggered = sh_dmae_nmi_notify(shdev);
if (triggered == true)
ret = NOTIFY_OK;
}
rcu_read_unlock();
return ret;
}
static struct notifier_block <API key> __read_mostly = {
.notifier_call = sh_dmae_nmi_handler,
.priority = 1,
};
static int __devinit sh_dmae_chan_probe(struct sh_dmae_device *shdev, int id,
int irq, unsigned long flags)
{
int err;
const struct sh_dmae_channel *chan_pdata = &shdev->pdata->channel[id];
struct platform_device *pdev = to_platform_device(shdev->common.dev);
struct sh_dmae_chan *new_sh_chan;
new_sh_chan = kzalloc(sizeof(struct sh_dmae_chan), GFP_KERNEL);
if (!new_sh_chan) {
dev_err(shdev->common.dev,
"No free memory for allocating dma channels!\n");
return -ENOMEM;
}
new_sh_chan->pm_state = DMAE_PM_ESTABLISHED;
new_sh_chan->common.device = &shdev->common;
dma_cookie_init(&new_sh_chan->common);
new_sh_chan->dev = shdev->common.dev;
new_sh_chan->id = id;
new_sh_chan->irq = irq;
new_sh_chan->base = shdev->chan_reg + chan_pdata->offset / sizeof(u32);
tasklet_init(&new_sh_chan->tasklet, dmae_do_tasklet,
(unsigned long)new_sh_chan);
spin_lock_init(&new_sh_chan->desc_lock);
INIT_LIST_HEAD(&new_sh_chan->ld_queue);
INIT_LIST_HEAD(&new_sh_chan->ld_free);
list_add_tail(&new_sh_chan->common.device_node,
&shdev->common.channels);
shdev->common.chancnt++;
if (pdev->id >= 0)
snprintf(new_sh_chan->dev_id, sizeof(new_sh_chan->dev_id),
"sh-dmae%d.%d", pdev->id, new_sh_chan->id);
else
snprintf(new_sh_chan->dev_id, sizeof(new_sh_chan->dev_id),
"sh-dma%d", new_sh_chan->id);
err = request_irq(irq, &sh_dmae_interrupt, flags,
new_sh_chan->dev_id, new_sh_chan);
if (err) {
dev_err(shdev->common.dev, "DMA channel %d request_irq error "
"with return %d\n", id, err);
goto err_no_irq;
}
shdev->chan[id] = new_sh_chan;
return 0;
err_no_irq:
list_del(&new_sh_chan->common.device_node);
kfree(new_sh_chan);
return err;
}
static void sh_dmae_chan_remove(struct sh_dmae_device *shdev)
{
int i;
for (i = shdev->common.chancnt - 1 ; i >= 0 ; i
if (shdev->chan[i]) {
struct sh_dmae_chan *sh_chan = shdev->chan[i];
free_irq(sh_chan->irq, sh_chan);
list_del(&sh_chan->common.device_node);
kfree(sh_chan);
shdev->chan[i] = NULL;
}
}
shdev->common.chancnt = 0;
}
static int __init sh_dmae_probe(struct platform_device *pdev)
{
struct sh_dmae_pdata *pdata = pdev->dev.platform_data;
unsigned long irqflags = IRQF_DISABLED,
chan_flag[<API key>] = {};
int errirq, chan_irq[<API key>];
int err, i, irq_cnt = 0, irqres = 0, irq_cap = 0;
struct sh_dmae_device *shdev;
struct resource *chan, *dmars, *errirq_res, *chanirq_res;
if (!pdata || !pdata->channel_num)
return -ENODEV;
chan = <API key>(pdev, IORESOURCE_MEM, 0);
dmars = <API key>(pdev, IORESOURCE_MEM, 1);
errirq_res = <API key>(pdev, IORESOURCE_IRQ, 0);
if (!chan || !errirq_res)
return -ENODEV;
if (!request_mem_region(chan->start, resource_size(chan), pdev->name)) {
dev_err(&pdev->dev, "DMAC register region already claimed\n");
return -EBUSY;
}
if (dmars && !request_mem_region(dmars->start, resource_size(dmars), pdev->name)) {
dev_err(&pdev->dev, "DMAC DMARS region already claimed\n");
err = -EBUSY;
goto ermrdmars;
}
err = -ENOMEM;
shdev = kzalloc(sizeof(struct sh_dmae_device), GFP_KERNEL);
if (!shdev) {
dev_err(&pdev->dev, "Not enough memory\n");
goto ealloc;
}
shdev->chan_reg = ioremap(chan->start, resource_size(chan));
if (!shdev->chan_reg)
goto emapchan;
if (dmars) {
shdev->dmars = ioremap(dmars->start, resource_size(dmars));
if (!shdev->dmars)
goto emapdmars;
}
shdev->pdata = pdata;
if (pdata->chcr_offset)
shdev->chcr_offset = pdata->chcr_offset;
else
shdev->chcr_offset = CHCR;
if (pdata->chcr_ie_bit)
shdev->chcr_ie_bit = pdata->chcr_ie_bit;
else
shdev->chcr_ie_bit = CHCR_IE;
<API key>(pdev, shdev);
shdev->common.dev = &pdev->dev;
pm_runtime_enable(&pdev->dev);
pm_runtime_get_sync(&pdev->dev);
spin_lock_irq(&sh_dmae_lock);
list_add_tail_rcu(&shdev->node, &sh_dmae_devices);
spin_unlock_irq(&sh_dmae_lock);
err = sh_dmae_rst(shdev);
if (err)
goto rst_err;
INIT_LIST_HEAD(&shdev->common.channels);
if (!pdata->slave_only)
dma_cap_set(DMA_MEMCPY, shdev->common.cap_mask);
if (pdata->slave && pdata->slave_num)
dma_cap_set(DMA_SLAVE, shdev->common.cap_mask);
shdev->common.<API key>
= <API key>;
shdev->common.<API key> = <API key>;
shdev->common.<API key> = sh_dmae_prep_memcpy;
shdev->common.device_tx_status = sh_dmae_tx_status;
shdev->common.<API key> = <API key>;
shdev->common.<API key> = <API key>;
shdev->common.device_control = sh_dmae_control;
shdev->common.copy_align = <API key>;
#if defined(CONFIG_CPU_SH4) || defined(<API key>)
chanirq_res = <API key>(pdev, IORESOURCE_IRQ, 1);
if (!chanirq_res)
chanirq_res = errirq_res;
else
irqres++;
if (chanirq_res == errirq_res ||
(errirq_res->flags & IORESOURCE_BITS) == <API key>)
irqflags = IRQF_SHARED;
errirq = errirq_res->start;
err = request_irq(errirq, sh_dmae_err, irqflags,
"DMAC Address Error", shdev);
if (err) {
dev_err(&pdev->dev,
"DMA failed requesting irq #%d, error %d\n",
errirq, err);
goto eirq_err;
}
#else
chanirq_res = errirq_res;
#endif
if (chanirq_res->start == chanirq_res->end &&
!<API key>(pdev, IORESOURCE_IRQ, 1)) {
for (; irq_cnt < pdata->channel_num; irq_cnt++) {
if (irq_cnt < <API key>) {
chan_irq[irq_cnt] = chanirq_res->start;
chan_flag[irq_cnt] = IRQF_SHARED;
} else {
irq_cap = 1;
break;
}
}
} else {
do {
for (i = chanirq_res->start; i <= chanirq_res->end; i++) {
if (irq_cnt >= <API key>) {
irq_cap = 1;
break;
}
if ((errirq_res->flags & IORESOURCE_BITS) ==
<API key>)
chan_flag[irq_cnt] = IRQF_SHARED;
else
chan_flag[irq_cnt] = IRQF_DISABLED;
dev_dbg(&pdev->dev,
"Found IRQ %d for channel %d\n",
i, irq_cnt);
chan_irq[irq_cnt++] = i;
}
if (irq_cnt >= <API key>)
break;
chanirq_res = <API key>(pdev,
IORESOURCE_IRQ, ++irqres);
} while (irq_cnt < pdata->channel_num && chanirq_res);
}
for (i = 0; i < irq_cnt; i++) {
err = sh_dmae_chan_probe(shdev, i, chan_irq[i], chan_flag[i]);
if (err)
goto chan_probe_err;
}
if (irq_cap)
dev_notice(&pdev->dev, "Attempting to register %d DMA "
"channels when a maximum of %d are supported.\n",
pdata->channel_num, <API key>);
pm_runtime_put(&pdev->dev);
<API key>(&shdev->common);
return err;
chan_probe_err:
sh_dmae_chan_remove(shdev);
#if defined(CONFIG_CPU_SH4) || defined(<API key>)
free_irq(errirq, shdev);
eirq_err:
#endif
rst_err:
spin_lock_irq(&sh_dmae_lock);
list_del_rcu(&shdev->node);
spin_unlock_irq(&sh_dmae_lock);
pm_runtime_put(&pdev->dev);
pm_runtime_disable(&pdev->dev);
if (dmars)
iounmap(shdev->dmars);
<API key>(pdev, NULL);
emapdmars:
iounmap(shdev->chan_reg);
synchronize_rcu();
emapchan:
kfree(shdev);
ealloc:
if (dmars)
release_mem_region(dmars->start, resource_size(dmars));
ermrdmars:
release_mem_region(chan->start, resource_size(chan));
return err;
}
static int __exit sh_dmae_remove(struct platform_device *pdev)
{
struct sh_dmae_device *shdev = <API key>(pdev);
struct resource *res;
int errirq = platform_get_irq(pdev, 0);
<API key>(&shdev->common);
if (errirq > 0)
free_irq(errirq, shdev);
spin_lock_irq(&sh_dmae_lock);
list_del_rcu(&shdev->node);
spin_unlock_irq(&sh_dmae_lock);
sh_dmae_chan_remove(shdev);
pm_runtime_disable(&pdev->dev);
if (shdev->dmars)
iounmap(shdev->dmars);
iounmap(shdev->chan_reg);
<API key>(pdev, NULL);
synchronize_rcu();
kfree(shdev);
res = <API key>(pdev, IORESOURCE_MEM, 0);
if (res)
release_mem_region(res->start, resource_size(res));
res = <API key>(pdev, IORESOURCE_MEM, 1);
if (res)
release_mem_region(res->start, resource_size(res));
return 0;
}
static void sh_dmae_shutdown(struct platform_device *pdev)
{
struct sh_dmae_device *shdev = <API key>(pdev);
sh_dmae_ctl_stop(shdev);
}
static int <API key>(struct device *dev)
{
return 0;
}
static int <API key>(struct device *dev)
{
struct sh_dmae_device *shdev = dev_get_drvdata(dev);
return sh_dmae_rst(shdev);
}
#ifdef CONFIG_PM
static int sh_dmae_suspend(struct device *dev)
{
return 0;
}
static int sh_dmae_resume(struct device *dev)
{
struct sh_dmae_device *shdev = dev_get_drvdata(dev);
int i, ret;
ret = sh_dmae_rst(shdev);
if (ret < 0)
dev_err(dev, "Failed to reset!\n");
for (i = 0; i < shdev->pdata->channel_num; i++) {
struct sh_dmae_chan *sh_chan = shdev->chan[i];
struct sh_dmae_slave *param = sh_chan->common.private;
if (!sh_chan->descs_allocated)
continue;
if (param) {
const struct <API key> *cfg = param->config;
dmae_set_dmars(sh_chan, cfg->mid_rid);
dmae_set_chcr(sh_chan, cfg->chcr);
} else {
dmae_init(sh_chan);
}
}
return 0;
}
#else
#define sh_dmae_suspend NULL
#define sh_dmae_resume NULL
#endif
const struct dev_pm_ops sh_dmae_pm = {
.suspend = sh_dmae_suspend,
.resume = sh_dmae_resume,
.runtime_suspend = <API key>,
.runtime_resume = <API key>,
};
static struct platform_driver sh_dmae_driver = {
.remove = __exit_p(sh_dmae_remove),
.shutdown = sh_dmae_shutdown,
.driver = {
.owner = THIS_MODULE,
.name = "sh-dma-engine",
.pm = &sh_dmae_pm,
},
};
static int __init sh_dmae_init(void)
{
int err = <API key>(&<API key>);
if (err)
return err;
return <API key>(&sh_dmae_driver, sh_dmae_probe);
}
module_init(sh_dmae_init);
static void __exit sh_dmae_exit(void)
{
<API key>(&sh_dmae_driver);
<API key>(&<API key>);
}
module_exit(sh_dmae_exit);
MODULE_AUTHOR("Nobuhiro Iwamatsu <iwamatsu.nobuhiro@renesas.com>");
MODULE_DESCRIPTION("Renesas SH DMA Engine driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:sh-dma-engine"); |
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/maple.h>
#include <linux/dma-mapping.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <asm/cacheflush.h>
#include <asm/dma.h>
#include <asm/io.h>
#include <mach/dma.h>
#include <mach/sysasic.h>
MODULE_AUTHOR("Adrian McMenamin <adrian@mcmen.demon.co.uk>");
MODULE_DESCRIPTION("Maple bus driver for Dreamcast");
MODULE_LICENSE("GPL v2");
<API key>("{{SEGA, Dreamcast/Maple}}");
static void maple_dma_handler(struct work_struct *work);
static void <API key>(struct work_struct *work);
static DECLARE_WORK(maple_dma_process, maple_dma_handler);
static DECLARE_WORK(<API key>, <API key>);
static LIST_HEAD(maple_waitq);
static LIST_HEAD(maple_sentq);
static DEFINE_MUTEX(maple_wlist_lock);
static struct maple_driver <API key>;
static struct device maple_bus;
static int subdevice_map[MAPLE_PORTS];
static unsigned long *maple_sendbuf, *maple_sendptr, *maple_lastptr;
static unsigned long maple_pnp_time;
static int started, scanning, fullscan;
static struct kmem_cache *maple_queue_cache;
struct <API key> {
int port;
int unit;
};
static bool checked[MAPLE_PORTS];
static bool empty[MAPLE_PORTS];
static struct maple_device *baseunits[MAPLE_PORTS];
int <API key>(struct maple_driver *drv)
{
if (!drv)
return -EINVAL;
drv->drv.bus = &maple_bus_type;
return driver_register(&drv->drv);
}
EXPORT_SYMBOL_GPL(<API key>);
void <API key>(struct maple_driver *drv)
{
driver_unregister(&drv->drv);
}
EXPORT_SYMBOL_GPL(<API key>);
static void maple_dma_reset(void)
{
__raw_writel(MAPLE_MAGIC, MAPLE_RESET);
__raw_writel(1, MAPLE_TRIGTYPE);
__raw_writel(MAPLE_2MBPS | MAPLE_TIMEOUT(0xFFFF), MAPLE_SPEED);
__raw_writel(virt_to_phys(maple_sendbuf), MAPLE_DMAADDR);
__raw_writel(1, MAPLE_ENABLE);
}
void <API key>(struct maple_device *dev,
void (*callback) (struct mapleq *mq),
unsigned long interval, unsigned long function)
{
dev->callback = callback;
dev->interval = interval;
dev->function = cpu_to_be32(function);
dev->when = jiffies;
}
EXPORT_SYMBOL_GPL(<API key>);
static int maple_dma_done(void)
{
return (__raw_readl(MAPLE_STATE) & 1) == 0;
}
static void <API key>(struct device *dev)
{
struct maple_device *mdev;
struct mapleq *mq;
mdev = to_maple_dev(dev);
mq = mdev->mq;
kmem_cache_free(maple_queue_cache, mq->recvbuf);
kfree(mq);
kfree(mdev);
}
int maple_add_packet(struct maple_device *mdev, u32 function, u32 command,
size_t length, void *data)
{
int ret = 0;
void *sendbuf = NULL;
if (length) {
sendbuf = kzalloc(length * 4, GFP_KERNEL);
if (!sendbuf) {
ret = -ENOMEM;
goto out;
}
((__be32 *)sendbuf)[0] = cpu_to_be32(function);
}
mdev->mq->command = command;
mdev->mq->length = length;
if (length > 1)
memcpy(sendbuf + 4, data, (length - 1) * 4);
mdev->mq->sendbuf = sendbuf;
mutex_lock(&maple_wlist_lock);
list_add_tail(&mdev->mq->list, &maple_waitq);
mutex_unlock(&maple_wlist_lock);
out:
return ret;
}
EXPORT_SYMBOL_GPL(maple_add_packet);
static struct mapleq *maple_allocq(struct maple_device *mdev)
{
struct mapleq *mq;
mq = kzalloc(sizeof(*mq), GFP_KERNEL);
if (!mq)
goto failed_nomem;
INIT_LIST_HEAD(&mq->list);
mq->dev = mdev;
mq->recvbuf = kmem_cache_zalloc(maple_queue_cache, GFP_KERNEL);
if (!mq->recvbuf)
goto failed_p2;
mq->recvbuf->buf = &((mq->recvbuf->bufx)[0]);
return mq;
failed_p2:
kfree(mq);
failed_nomem:
dev_err(&mdev->dev, "could not allocate memory for device (%d, %d)\n",
mdev->port, mdev->unit);
return NULL;
}
static struct maple_device *maple_alloc_dev(int port, int unit)
{
struct maple_device *mdev;
mdev = kzalloc(sizeof(*mdev), GFP_KERNEL);
if (!mdev)
return NULL;
mdev->port = port;
mdev->unit = unit;
mdev->mq = maple_allocq(mdev);
if (!mdev->mq) {
kfree(mdev);
return NULL;
}
mdev->dev.bus = &maple_bus_type;
mdev->dev.parent = &maple_bus;
init_waitqueue_head(&mdev->maple_wait);
return mdev;
}
static void maple_free_dev(struct maple_device *mdev)
{
kmem_cache_free(maple_queue_cache, mdev->mq->recvbuf);
kfree(mdev->mq);
kfree(mdev);
}
static void maple_build_block(struct mapleq *mq)
{
int port, unit, from, to, len;
unsigned long *lsendbuf = mq->sendbuf;
port = mq->dev->port & 3;
unit = mq->dev->unit;
len = mq->length;
from = port << 6;
to = (port << 6) | (unit > 0 ? (1 << (unit - 1)) & 0x1f : 0x20);
*maple_lastptr &= 0x7fffffff;
maple_lastptr = maple_sendptr;
*maple_sendptr++ = (port << 16) | len | 0x80000000;
*maple_sendptr++ = virt_to_phys(mq->recvbuf->buf);
*maple_sendptr++ =
mq->command | (to << 8) | (from << 16) | (len << 24);
while (len
*maple_sendptr++ = *lsendbuf++;
}
static void maple_send(void)
{
int i, maple_packets = 0;
struct mapleq *mq, *nmq;
if (!maple_dma_done())
return;
__raw_writel(0, MAPLE_ENABLE);
if (!list_empty(&maple_sentq))
goto finish;
mutex_lock(&maple_wlist_lock);
if (list_empty(&maple_waitq)) {
mutex_unlock(&maple_wlist_lock);
goto finish;
}
maple_lastptr = maple_sendbuf;
maple_sendptr = maple_sendbuf;
<API key>(mq, nmq, &maple_waitq, list) {
maple_build_block(mq);
list_del_init(&mq->list);
list_add_tail(&mq->list, &maple_sentq);
if (maple_packets++ > MAPLE_MAXPACKETS)
break;
}
mutex_unlock(&maple_wlist_lock);
if (maple_packets > 0) {
for (i = 0; i < (1 << MAPLE_DMA_PAGES); i++)
dma_cache_sync(0, maple_sendbuf + i * PAGE_SIZE,
PAGE_SIZE, DMA_BIDIRECTIONAL);
}
finish:
maple_dma_reset();
}
static int <API key>(struct device_driver *driver,
void *devptr)
{
struct maple_driver *maple_drv;
struct maple_device *mdev;
mdev = devptr;
maple_drv = to_maple_driver(driver);
if (mdev->devinfo.function & cpu_to_be32(maple_drv->function))
return 1;
return 0;
}
static void maple_detach_driver(struct maple_device *mdev)
{
device_unregister(&mdev->dev);
}
static void maple_attach_driver(struct maple_device *mdev)
{
char *p, *recvbuf;
unsigned long function;
int matched, error;
recvbuf = mdev->mq->recvbuf->buf;
memcpy(&mdev->devinfo.function, recvbuf + 4, 4);
memcpy(&mdev->devinfo.function_data[0], recvbuf + 8, 12);
memcpy(&mdev->devinfo.area_code, recvbuf + 20, 1);
memcpy(&mdev->devinfo.connector_direction, recvbuf + 21, 1);
memcpy(&mdev->devinfo.product_name[0], recvbuf + 22, 30);
memcpy(&mdev->devinfo.standby_power, recvbuf + 112, 2);
memcpy(&mdev->devinfo.max_power, recvbuf + 114, 2);
memcpy(mdev->product_name, mdev->devinfo.product_name, 30);
mdev->product_name[30] = '\0';
memcpy(mdev->product_licence, mdev->devinfo.product_licence, 60);
mdev->product_licence[60] = '\0';
for (p = mdev->product_name + 29; mdev->product_name <= p; p
if (*p == ' ')
*p = '\0';
else
break;
for (p = mdev->product_licence + 59; mdev->product_licence <= p; p
if (*p == ' ')
*p = '\0';
else
break;
function = be32_to_cpu(mdev->devinfo.function);
dev_info(&mdev->dev, "detected %s: function 0x%lX: at (%d, %d)\n",
mdev->product_name, function, mdev->port, mdev->unit);
if (function > 0x200) {
function = 0;
mdev->driver = &<API key>;
dev_set_name(&mdev->dev, "%d:0.port", mdev->port);
} else {
matched =
bus_for_each_drv(&maple_bus_type, NULL, mdev,
<API key>);
if (matched == 0) {
dev_info(&mdev->dev, "no driver found\n");
mdev->driver = &<API key>;
}
dev_set_name(&mdev->dev, "%d:0%d.%lX", mdev->port,
mdev->unit, function);
}
mdev->function = function;
mdev->dev.release = &<API key>;
atomic_set(&mdev->busy, 0);
error = device_register(&mdev->dev);
if (error) {
dev_warn(&mdev->dev, "could not register device at"
" (%d, %d), with error 0x%X\n", mdev->unit,
mdev->port, error);
maple_free_dev(mdev);
mdev = NULL;
return;
}
}
static int check_maple_device(struct device *device, void *portptr)
{
struct <API key> *ds;
struct maple_device *mdev;
ds = portptr;
mdev = to_maple_dev(device);
if (mdev->port == ds->port && mdev->unit == ds->unit)
return 1;
return 0;
}
static int <API key>(struct device *device, void *ignored)
{
int add;
struct maple_device *mdev = to_maple_dev(device);
if (mdev->interval > 0 && atomic_read(&mdev->busy) == 0 &&
time_after(jiffies, mdev->when)) {
add = maple_add_packet(mdev,
be32_to_cpu(mdev->devinfo.function),
<API key>, 1, NULL);
if (!add)
mdev->when = jiffies + mdev->interval;
} else {
if (time_after(jiffies, maple_pnp_time))
if (atomic_read(&mdev->busy) == 0) {
atomic_set(&mdev->busy, 1);
maple_add_packet(mdev, 0,
<API key>, 0, NULL);
}
}
return 0;
}
static void <API key>(struct work_struct *work)
{
int x, locking;
struct maple_device *mdev;
if (!maple_dma_done())
return;
__raw_writel(0, MAPLE_ENABLE);
if (!list_empty(&maple_sentq))
goto finish;
bus_for_each_dev(&maple_bus_type, NULL, NULL,
<API key>);
if (time_after(jiffies, maple_pnp_time)) {
for (x = 0; x < MAPLE_PORTS; x++) {
if (checked[x] && empty[x]) {
mdev = baseunits[x];
if (!mdev)
break;
atomic_set(&mdev->busy, 1);
locking = maple_add_packet(mdev, 0,
<API key>, 0, NULL);
if (!locking)
break;
}
}
maple_pnp_time = jiffies + MAPLE_PNP_INTERVAL;
}
finish:
maple_send();
}
static void maple_map_subunits(struct maple_device *mdev, int submask)
{
int retval, k, devcheck;
struct maple_device *mdev_add;
struct <API key> ds;
ds.port = mdev->port;
for (k = 0; k < 5; k++) {
ds.unit = k + 1;
retval =
bus_for_each_dev(&maple_bus_type, NULL, &ds,
check_maple_device);
if (retval) {
submask = submask >> 1;
continue;
}
devcheck = submask & 0x01;
if (devcheck) {
mdev_add = maple_alloc_dev(mdev->port, k + 1);
if (!mdev_add)
return;
atomic_set(&mdev_add->busy, 1);
maple_add_packet(mdev_add, 0, <API key>,
0, NULL);
scanning = 1;
}
submask = submask >> 1;
}
}
static void maple_clean_submap(struct maple_device *mdev)
{
int killbit;
killbit = (mdev->unit > 0 ? (1 << (mdev->unit - 1)) & 0x1f : 0x20);
killbit = ~killbit;
killbit &= 0xFF;
subdevice_map[mdev->port] = subdevice_map[mdev->port] & killbit;
}
static void maple_response_none(struct maple_device *mdev)
{
maple_clean_submap(mdev);
if (likely(mdev->unit != 0)) {
if (mdev->can_unload) {
if (!mdev->can_unload(mdev)) {
atomic_set(&mdev->busy, 2);
wake_up(&mdev->maple_wait);
return;
}
}
dev_info(&mdev->dev, "detaching device at (%d, %d)\n",
mdev->port, mdev->unit);
maple_detach_driver(mdev);
return;
} else {
if (!started || !fullscan) {
if (checked[mdev->port] == false) {
checked[mdev->port] = true;
empty[mdev->port] = true;
dev_info(&mdev->dev, "no devices"
" to port %d\n", mdev->port);
}
return;
}
}
atomic_set(&mdev->busy, 0);
}
static void <API key>(struct maple_device *mdev,
char *recvbuf)
{
char submask;
if (!started || (scanning == 2) || !fullscan) {
if ((mdev->unit == 0) && (checked[mdev->port] == false)) {
checked[mdev->port] = true;
maple_attach_driver(mdev);
} else {
if (mdev->unit != 0)
maple_attach_driver(mdev);
if (mdev->unit == 0) {
empty[mdev->port] = false;
maple_attach_driver(mdev);
}
}
}
if (mdev->unit == 0) {
submask = recvbuf[2] & 0x1F;
if (submask ^ subdevice_map[mdev->port]) {
maple_map_subunits(mdev, submask);
subdevice_map[mdev->port] = submask;
}
}
}
static void <API key>(struct maple_device *mdev, void *recvbuf)
{
if (mdev->fileerr_handler) {
mdev->fileerr_handler(mdev, recvbuf);
return;
} else
dev_warn(&mdev->dev, "device at (%d, %d) reports"
"file error 0x%X\n", mdev->port, mdev->unit,
((int *)recvbuf)[1]);
}
static void maple_port_rescan(void)
{
int i;
struct maple_device *mdev;
fullscan = 1;
for (i = 0; i < MAPLE_PORTS; i++) {
if (checked[i] == false) {
fullscan = 0;
mdev = baseunits[i];
maple_add_packet(mdev, 0, <API key>,
0, NULL);
}
}
}
static void maple_dma_handler(struct work_struct *work)
{
struct mapleq *mq, *nmq;
struct maple_device *mdev;
char *recvbuf;
enum maple_code code;
if (!maple_dma_done())
return;
__raw_writel(0, MAPLE_ENABLE);
if (!list_empty(&maple_sentq)) {
<API key>(mq, nmq, &maple_sentq, list) {
mdev = mq->dev;
recvbuf = mq->recvbuf->buf;
dma_cache_sync(&mdev->dev, recvbuf, 0x400,
DMA_FROM_DEVICE);
code = recvbuf[0];
kfree(mq->sendbuf);
list_del_init(&mq->list);
switch (code) {
case MAPLE_RESPONSE_NONE:
maple_response_none(mdev);
break;
case <API key>:
<API key>(mdev, recvbuf);
atomic_set(&mdev->busy, 0);
break;
case <API key>:
if (mdev->callback)
mdev->callback(mq);
atomic_set(&mdev->busy, 0);
wake_up(&mdev->maple_wait);
break;
case <API key>:
<API key>(mdev, recvbuf);
atomic_set(&mdev->busy, 0);
wake_up(&mdev->maple_wait);
break;
case <API key>:
case <API key>:
case <API key>:
dev_warn(&mdev->dev, "non-fatal error"
" 0x%X at (%d, %d)\n", code,
mdev->port, mdev->unit);
atomic_set(&mdev->busy, 0);
break;
case <API key>:
dev_notice(&mdev->dev, "extended"
" device information request for (%d, %d)"
" but call is not supported\n", mdev->port,
mdev->unit);
atomic_set(&mdev->busy, 0);
break;
case MAPLE_RESPONSE_OK:
atomic_set(&mdev->busy, 0);
wake_up(&mdev->maple_wait);
break;
default:
break;
}
}
if (scanning == 1) {
maple_send();
scanning = 2;
} else
scanning = 0;
if (!fullscan)
maple_port_rescan();
started = 1;
}
maple_send();
}
static irqreturn_t maple_dma_interrupt(int irq, void *dev_id)
{
schedule_work(&maple_dma_process);
return IRQ_HANDLED;
}
static irqreturn_t <API key>(int irq, void *dev_id)
{
schedule_work(&<API key>);
return IRQ_HANDLED;
}
static int <API key>(void)
{
return request_irq(HW_EVENT_MAPLE_DMA, maple_dma_interrupt,
IRQF_SHARED, "maple bus DMA", &<API key>);
}
static int <API key>(void)
{
return request_irq(HW_EVENT_VSYNC, <API key>,
IRQF_SHARED, "maple bus VBLANK", &<API key>);
}
static int <API key>(void)
{
maple_sendbuf =
(void *) __get_free_pages(GFP_KERNEL | __GFP_ZERO,
MAPLE_DMA_PAGES);
if (!maple_sendbuf)
return -ENOMEM;
return 0;
}
static int <API key>(struct device *devptr,
struct device_driver *drvptr)
{
struct maple_driver *maple_drv = to_maple_driver(drvptr);
struct maple_device *maple_dev = to_maple_dev(devptr);
if (maple_dev->devinfo.function == 0xFFFFFFFF)
return 0;
else if (maple_dev->devinfo.function &
cpu_to_be32(maple_drv->function))
return 1;
return 0;
}
static int maple_bus_uevent(struct device *dev,
struct kobj_uevent_env *env)
{
return 0;
}
static void maple_bus_release(struct device *dev)
{
}
static struct maple_driver <API key> = {
.drv = {
.name = "<API key>",
.bus = &maple_bus_type,
},
};
struct bus_type maple_bus_type = {
.name = "maple",
.match = <API key>,
.uevent = maple_bus_uevent,
};
EXPORT_SYMBOL_GPL(maple_bus_type);
static struct device maple_bus = {
.init_name = "maple",
.release = maple_bus_release,
};
static int __init maple_bus_init(void)
{
int retval, i;
struct maple_device *mdev[MAPLE_PORTS];
__raw_writel(0, MAPLE_ENABLE);
retval = device_register(&maple_bus);
if (retval)
goto cleanup;
retval = bus_register(&maple_bus_type);
if (retval)
goto cleanup_device;
retval = driver_register(&<API key>.drv);
if (retval)
goto cleanup_bus;
retval = <API key>();
if (retval) {
dev_err(&maple_bus, "failed to allocate DMA buffers\n");
goto cleanup_basic;
}
retval = <API key>();
if (retval) {
dev_err(&maple_bus, "bus failed to grab maple "
"DMA IRQ\n");
goto cleanup_dma;
}
retval = <API key>();
if (retval) {
dev_err(&maple_bus, "bus failed to grab VBLANK IRQ\n");
goto cleanup_irq;
}
maple_queue_cache = KMEM_CACHE(maple_buffer, SLAB_HWCACHE_ALIGN);
if (!maple_queue_cache)
goto cleanup_bothirqs;
INIT_LIST_HEAD(&maple_waitq);
INIT_LIST_HEAD(&maple_sentq);
for (i = 0; i < MAPLE_PORTS; i++) {
checked[i] = false;
empty[i] = false;
mdev[i] = maple_alloc_dev(i, 0);
if (!mdev[i]) {
while (i
maple_free_dev(mdev[i]);
goto cleanup_cache;
}
baseunits[i] = mdev[i];
atomic_set(&mdev[i]->busy, 1);
maple_add_packet(mdev[i], 0, <API key>, 0, NULL);
subdevice_map[i] = 0;
}
maple_pnp_time = jiffies + HZ;
maple_send();
dev_info(&maple_bus, "bus core now registered\n");
return 0;
cleanup_cache:
kmem_cache_destroy(maple_queue_cache);
cleanup_bothirqs:
free_irq(HW_EVENT_VSYNC, 0);
cleanup_irq:
free_irq(HW_EVENT_MAPLE_DMA, 0);
cleanup_dma:
free_pages((unsigned long) maple_sendbuf, MAPLE_DMA_PAGES);
cleanup_basic:
driver_unregister(&<API key>.drv);
cleanup_bus:
bus_unregister(&maple_bus_type);
cleanup_device:
device_unregister(&maple_bus);
cleanup:
printk(KERN_ERR "Maple bus registration failed\n");
return retval;
}
fs_initcall(maple_bus_init); |
#include <mach/<API key>.h>
#include "omap-bandgap.h"
/* TODO: Remove this, ES2.0 samples won't allow this to be programmable*/
#define <API key> 928 /* 119 degC */
#define <API key> 900
#define <API key> 916 /* 114 degC */
#define <API key> 900
#define <API key> 943 /* 125 degC */
#define <API key> 900
/*
* OMAP5430 has three instances of thermal sensor for MPU, GPU & CORE,
* need to describe the individual registers and bit fields.
*/
/*
* OMAP5430 MPU thermal sensor register offset and bit-fields
*/
static struct <API key>
<API key> = {
.temp_sensor_ctrl = <API key>,
.bgap_tempsoff_mask = <API key>,
.bgap_eocz_mask = <API key>,
.bgap_dtemp_mask = <API key>,
.bgap_mask_ctrl = <API key>,
.mask_hot_mask = <API key>,
.mask_cold_mask = <API key>,
.mask_sidlemode_mask = <API key>,
.mask_freeze_mask = <API key>,
.mask_clear_mask = <API key>,
.<API key> = <API key>,
.bgap_counter = <API key>,
.counter_mask = <API key>,
.bgap_threshold = <API key>,
.threshold_thot_mask = <API key>,
.<API key> = <API key>,
.tshut_threshold = <API key>,
.tshut_efuse_shift = <API key>,
.tshut_efuse_mask = <API key>,
.tshut_hot_mask = <API key>,
.tshut_cold_mask = <API key>,
.bgap_status = <API key>,
.<API key> = 0x0,
.<API key> = OMAP5_ALERT_MASK,
.status_hot_mask = OMAP5_HOT_MPU_MASK,
.status_cold_mask = OMAP5_COLD_MPU_MASK,
.bgap_cumul_dtemp = <API key>,
.ctrl_dtemp_0 = <API key>,
.ctrl_dtemp_1 = <API key>,
.ctrl_dtemp_2 = <API key>,
.ctrl_dtemp_3 = <API key>,
.ctrl_dtemp_4 = <API key>,
.bgap_efuse = <API key>,
};
/*
* OMAP5430 GPU thermal sensor register offset and bit-fields
*/
static struct <API key>
<API key> = {
.temp_sensor_ctrl = <API key>,
.bgap_tempsoff_mask = <API key>,
.bgap_eocz_mask = <API key>,
.bgap_dtemp_mask = <API key>,
.bgap_mask_ctrl = <API key>,
.mask_hot_mask = <API key>,
.mask_cold_mask = <API key>,
.mask_sidlemode_mask = <API key>,
.mask_freeze_mask = <API key>,
.mask_clear_mask = OMAP5_CLEAR_MM_MASK,
.<API key> = <API key>,
.bgap_counter = <API key>,
.counter_mask = <API key>,
.bgap_threshold = <API key>,
.threshold_thot_mask = <API key>,
.<API key> = <API key>,
.tshut_threshold = <API key>,
.tshut_efuse_shift = <API key>,
.tshut_efuse_mask = <API key>,
.tshut_hot_mask = <API key>,
.tshut_cold_mask = <API key>,
.bgap_status = <API key>,
.<API key> = 0x0,
.<API key> = OMAP5_ALERT_MASK,
.status_hot_mask = OMAP5_HOT_MM_MASK,
.status_cold_mask = OMAP5_COLD_MM_MASK,
.bgap_cumul_dtemp = <API key>,
.ctrl_dtemp_0 = <API key>,
.ctrl_dtemp_1 = <API key>,
.ctrl_dtemp_2 = <API key>,
.ctrl_dtemp_3 = <API key>,
.ctrl_dtemp_4 = <API key>,
.bgap_efuse = <API key>,
};
/*
* OMAP5430 CORE thermal sensor register offset and bit-fields
*/
static struct <API key>
<API key> = {
.temp_sensor_ctrl = <API key>,
.bgap_tempsoff_mask = <API key>,
.bgap_eocz_mask = <API key>,
.bgap_dtemp_mask = <API key>,
.bgap_mask_ctrl = <API key>,
.mask_hot_mask = <API key>,
.mask_cold_mask = <API key>,
.mask_sidlemode_mask = <API key>,
.mask_freeze_mask = <API key>,
.mask_clear_mask = <API key>,
.<API key> = <API key>,
.bgap_counter = <API key>,
.counter_mask = <API key>,
.bgap_threshold = <API key>,
.threshold_thot_mask = <API key>,
.<API key> = <API key>,
.tshut_threshold = <API key>,
.tshut_efuse_shift = <API key>,
.tshut_efuse_mask = <API key>,
.tshut_hot_mask = <API key>,
.tshut_cold_mask = <API key>,
.bgap_status = <API key>,
.<API key> = 0x0,
.<API key> = OMAP5_ALERT_MASK,
.status_hot_mask = OMAP5_HOT_CORE_MASK,
.status_cold_mask = <API key>,
.bgap_cumul_dtemp = <API key>,
.ctrl_dtemp_0 = <API key>,
.ctrl_dtemp_1 = <API key>,
.ctrl_dtemp_2 = <API key>,
.ctrl_dtemp_3 = <API key>,
.ctrl_dtemp_4 = <API key>,
.bgap_efuse = <API key>,
};
/* Thresholds and limits for OMAP5430 MPU temperature sensor */
static struct temp_sensor_data <API key> = {
.tshut_hot = <API key>,
.tshut_cold = <API key>,
.t_hot = OMAP5430_MPU_T_HOT,
.t_cold = OMAP5430_MPU_T_COLD,
.min_freq = <API key>,
.max_freq = <API key>,
.max_temp = <API key>,
.min_temp = <API key>,
.hyst_val = <API key>,
.adc_start_val = <API key>,
.adc_end_val = <API key>,
.update_int1 = 1000,
.update_int2 = 2000,
.stats_en = 1,
.avg_number = 20,
.avg_period = 100,
.safe_temp_trend = 50,
};
/* Thresholds and limits for OMAP5430 GPU temperature sensor */
static struct temp_sensor_data <API key> = {
.tshut_hot = <API key>,
.tshut_cold = <API key>,
.t_hot = OMAP5430_GPU_T_HOT,
.t_cold = OMAP5430_GPU_T_COLD,
.min_freq = <API key>,
.max_freq = <API key>,
.max_temp = <API key>,
.min_temp = <API key>,
.hyst_val = <API key>,
.adc_start_val = <API key>,
.adc_end_val = <API key>,
.update_int1 = 1000,
.update_int2 = 2000,
.stats_en = 1,
.avg_number = 20,
.avg_period = 100,
.safe_temp_trend = 50,
};
/* Thresholds and limits for OMAP5430 CORE temperature sensor */
static struct temp_sensor_data <API key> = {
.tshut_hot = <API key>,
.tshut_cold = <API key>,
.t_hot = OMAP5430_CORE_T_HOT,
.t_cold = <API key>,
.min_freq = <API key>,
.max_freq = <API key>,
.max_temp = <API key>,
.min_temp = <API key>,
.hyst_val = <API key>,
.adc_start_val = <API key>,
.adc_end_val = <API key>,
.update_int1 = 1000,
.update_int2 = 2000,
.stats_en = 1,
.avg_number = 20,
.avg_period = 100,
.safe_temp_trend = 50,
};
/*
* OMAP54xx ES2.0 : Temperature values in milli degree celsius
* ADC code values from 540 to 945
*/
static int
<API key>[
<API key> - <API key> + 1] = {
/* Index 540 - 549 */
-40000, -40000, -40000, -40000, -39800, -39400, -39000, -38600, -38200,
-37800,
/* Index 550 - 559 */
-37400, -37000, -36600, -36200, -35800, -35300, -34700, -34200, -33800,
-33400,
/* Index 560 - 569 */
-33000, -32600, -32200, -31800, -31400, -31000, -30600, -30200, -29800,
-29400,
/* Index 570 - 579 */
-29000, -28600, -28200, -27700, -27100, -26600, -26200, -25800, -25400,
-25000,
/* Index 580 - 589 */
-24600, -24200, -23800, -23400, -23000, -22600, -22200, -21600, -21400,
-21000,
/* Index 590 - 599 */
-20500, -19900, -19400, -19000, -18600, -18200, -17800, -17400, -17000,
-16600,
/* Index 600 - 609 */
-16200, -15800, -15400, -15000, -14600, -14200, -13800, -13400, -13000,
-12500,
/* Index 610 - 619 */
-11900, -11400, -11000, -10600, -10200, -9800, -9400, -9000, -8600,
-8200,
/* Index 620 - 629 */
-7800, -7400, -7000, -6600, -6200, -5800, -5400, -5000, -4500, -3900,
/* Index 630 - 639 */
-3400, -3000, -2600, -2200, -1800, -1400, -1000, -600, -200, 200,
/* Index 640 - 649 */
600, 1000, 1400, 1800, 2200, 2600, 3000, 3400, 3900, 4500,
/* Index 650 - 659 */
5000, 5400, 5800, 6200, 6600, 7000, 7400, 7800, 8200, 8600,
/* Index 660 - 669 */
9000, 9400, 9800, 10200, 10600, 11000, 11400, 11800, 12200, 12700,
/* Index 670 - 679 */
13300, 13800, 14200, 14600, 15000, 15400, 15800, 16200, 16600, 17000,
/* Index 680 - 689 */
17400, 17800, 18200, 18600, 19000, 19400, 19800, 20200, 20600, 21100,
/* Index 690 - 699 */
21400, 21900, 22500, 23000, 23400, 23800, 24200, 24600, 25000, 25400,
/* Index 700 - 709 */
25800, 26200, 26600, 27000, 27400, 27800, 28200, 28600, 29000, 29400,
/* Index 710 - 719 */
29800, 30200, 30600, 31000, 31400, 31900, 32500, 33000, 33400, 33800,
/* Index 720 - 729 */
34200, 34600, 35000, 35400, 35800, 36200, 36600, 37000, 37400, 37800,
/* Index 730 - 739 */
38200, 38600, 39000, 39400, 39800, 40200, 40600, 41000, 41400, 41800,
/* Index 740 - 749 */
42200, 42600, 43100, 43700, 44200, 44600, 45000, 45400, 45800, 46200,
/* Index 750 - 759 */
46600, 47000, 47400, 47800, 48200, 48600, 49000, 49400, 49800, 50200,
/* Index 760 - 769 */
50600, 51000, 51400, 51800, 52200, 52600, 53000, 53400, 53800, 54200,
/* Index 770 - 779 */
54600, 55000, 55400, 55900, 56500, 57000, 57400, 57800, 58200, 58600,
/* Index 780 - 789 */
59000, 59400, 59800, 60200, 60600, 61000, 61400, 61800, 62200, 62600,
/* Index 790 - 799 */
63000, 63400, 63800, 64200, 64600, 65000, 65400, 65800, 66200, 66600,
/* Index 800 - 809 */
67000, 67400, 67800, 68200, 68600, 69000, 69400, 69800, 70200, 70600,
/* Index 810 - 819 */
71000, 71500, 72100, 72600, 73000, 73400, 73800, 74200, 74600, 75000,
/* Index 820 - 829 */
75400, 75800, 76200, 76600, 77000, 77400, 77800, 78200, 78600, 79000,
/* Index 830 - 839 */
79400, 79800, 80200, 80600, 81000, 81400, 81800, 82200, 82600, 83000,
/* Index 840 - 849 */
83400, 83800, 84200, 84600, 85000, 85400, 85800, 86200, 86600, 87000,
/* Index 850 - 859 */
87400, 87800, 88200, 88600, 89000, 89400, 89800, 90200, 90600, 91000,
/* Index 860 - 869 */
91400, 91800, 92200, 92600, 93000, 93400, 93800, 94200, 94600, 95000,
/* Index 870 - 879 */
95400, 95800, 96200, 96600, 97000, 97500, 98100, 98600, 99000, 99400,
/* Index 880 - 889 */
99800, 100200, 100600, 101000, 101400, 101800, 102200, 102600, 103000,
103400,
/* Index 890 - 899 */
103800, 104200, 104600, 105000, 105400, 105800, 106200, 106600, 107000,
107400,
/* Index 900 - 909 */
107800, 108200, 108600, 109000, 109400, 109800, 110200, 110600, 111000,
111400,
/* Index 910 - 919 */
111800, 112200, 112600, 113000, 113400, 113800, 114200, 114600, 115000,
115400,
/* Index 920 - 929 */
115800, 116200, 116600, 117000, 117400, 117800, 118200, 118600, 119000,
119400,
/* Index 930 - 939 */
119800, 120200, 120600, 121000, 121400, 121800, 122400, 122600, 123000,
123400,
/* Index 940 - 945 */
123800, 1242000, 124600, 124900, 125000, 125000,
};
/* OMAP54xx ES2.0 data */
/* TODO : Need to update the slope/constant for ES2.0 silicon */
struct omap_bandgap_data omap5430_data = {
.features = <API key> |
<API key> |
<API key>,
.fclock_name = "l3instr_ts_gclk_div",
.div_ck_name = "l3instr_ts_gclk_div",
.conv_table = <API key>,
.report_temperature = <API key>,
.expose_sensor = <API key>,
.remove_sensor = <API key>,
.sensors = {
{
.registers = &<API key>,
.ts_data = &<API key>,
.domain = "cpu",
.slope = 118,
.constant = -2992,
},
{
.registers = &<API key>,
.ts_data = &<API key>,
.domain = "gpu",
.slope = 61,
.constant = -1558,
},
{
.registers = &<API key>,
.ts_data = &<API key>,
.domain = "core",
.slope = 0,
.constant = 0,
},
},
.sensor_count = 3,
}; |
// 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
// 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,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// with this library; see the file COPYING3. If not see
#include <regex>
#include <<API key>.h>
using namespace __gnu_test;
int main()
{
time_counter time;
resource_counter resource;
start_counters(time, resource);
// this should get compiled to just L"[abcd]"
auto re = std::wregex(L'[' + std::wstring(300, L'a') + L"bc"
+ std::wstring(1000, 'a') + L"d]");
bool ok = true;
for (int i = 0; i < 100000; ++i)
ok = ok && (std::regex_match(L"b", re) && std::regex_match(L"d", re));
stop_counters(time, resource);
report_performance(__FILE__, "", time, resource);
return ok ? 0 : 1;
} |
#ifndef MSM_IRIS_H
#define MSM_IRIS_H
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <soc/qcom/camera2.h>
#include <media/v4l2-subdev.h>
#include <media/msmb_camera.h>
#include "msm_camera_i2c.h"
#include "msm_camera_dt_util.h"
#include "msm_camera_io_util.h"
#define DEFINE_MSM_MUTEX(mutexname) \
static struct mutex mutexname = __MUTEX_INITIALIZER(mutexname)
#define MSM_IRIS_MAX_VREGS (10)
struct msm_iris_ctrl_t;
enum msm_iris_state_t {
IRIS_ENABLE_STATE,
IRIS_OPS_ACTIVE,
IRIS_OPS_INACTIVE,
IRIS_DISABLE_STATE,
};
struct msm_iris_vreg {
struct camera_vreg_t *cam_vreg;
void *data[MSM_IRIS_MAX_VREGS];
int num_vreg;
};
struct msm_iris_ctrl_t {
struct i2c_driver *i2c_driver;
struct platform_driver *pdriver;
struct platform_device *pdev;
struct <API key> i2c_client;
enum <API key> iris_device_type;
struct msm_sd_subdev msm_sd;
struct mutex *iris_mutex;
enum <API key> i2c_data_type;
struct v4l2_subdev sdev;
struct v4l2_subdev_ops *<API key>;
void *user_data;
uint16_t i2c_tbl_index;
enum cci_i2c_master_t cci_master;
uint32_t subdev_id;
enum msm_iris_state_t iris_state;
struct msm_iris_vreg vreg_cfg;
};
#endif |
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/mbcache.h>
#include <linux/quotaops.h>
#include <linux/rwsem.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
#include "acl.h"
#define BHDR(bh) ((struct ext4_xattr_header *)((bh)->b_data))
#define ENTRY(ptr) ((struct ext4_xattr_entry *)(ptr))
#define BFIRST(bh) ENTRY(BHDR(bh)+1)
#define IS_LAST_ENTRY(entry) (*(__u32 *)(entry) == 0)
#ifdef EXT4_XATTR_DEBUG
# define ea_idebug(inode, f...) do { \
printk(KERN_DEBUG "inode %s:%lu: ", \
inode->i_sb->s_id, inode->i_ino); \
printk(f); \
printk("\n"); \
} while (0)
# define ea_bdebug(bh, f...) do { \
char b[BDEVNAME_SIZE]; \
printk(KERN_DEBUG "block %s:%lu: ", \
bdevname(bh->b_bdev, b), \
(unsigned long) bh->b_blocknr); \
printk(f); \
printk("\n"); \
} while (0)
#else
# define ea_idebug(inode, fmt, ...) no_printk(fmt, ##__VA_ARGS__)
# define ea_bdebug(bh, fmt, ...) no_printk(fmt, ##__VA_ARGS__)
#endif
static void <API key>(struct buffer_head *);
static struct buffer_head *<API key>(struct inode *,
struct ext4_xattr_header *,
struct mb_cache_entry **);
static void ext4_xattr_rehash(struct ext4_xattr_header *,
struct ext4_xattr_entry *);
static int ext4_xattr_list(struct dentry *dentry, char *buffer,
size_t buffer_size);
static struct mb_cache *ext4_xattr_cache;
static const struct xattr_handler *<API key>[] = {
[<API key>] = &<API key>,
#ifdef <API key>
[<API key>] = &<API key>,
[<API key>] = &<API key>,
#endif
[<API key>] = &<API key>,
#ifdef <API key>
[<API key>] = &<API key>,
#endif
};
const struct xattr_handler *ext4_xattr_handlers[] = {
&<API key>,
&<API key>,
#ifdef <API key>
&<API key>,
&<API key>,
#endif
#ifdef <API key>
&<API key>,
#endif
NULL
};
static inline const struct xattr_handler *
ext4_xattr_handler(int name_index)
{
const struct xattr_handler *handler = NULL;
if (name_index > 0 && name_index < ARRAY_SIZE(<API key>))
handler = <API key>[name_index];
return handler;
}
/*
* Inode operation listxattr()
*
* dentry->d_inode->i_mutex: don't care
*/
ssize_t
ext4_listxattr(struct dentry *dentry, char *buffer, size_t size)
{
return ext4_xattr_list(dentry, buffer, size);
}
static int
<API key>(struct ext4_xattr_entry *entry, void *end)
{
while (!IS_LAST_ENTRY(entry)) {
struct ext4_xattr_entry *next = EXT4_XATTR_NEXT(entry);
if ((void *)next >= end)
return -EIO;
entry = next;
}
return 0;
}
static inline int
<API key>(struct buffer_head *bh)
{
if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1))
return -EIO;
return <API key>(BFIRST(bh), bh->b_data + bh->b_size);
}
static inline int
<API key>(struct ext4_xattr_entry *entry, size_t size)
{
size_t value_size = le32_to_cpu(entry->e_value_size);
if (entry->e_value_block != 0 || value_size > size ||
le16_to_cpu(entry->e_value_offs) + value_size > size)
return -EIO;
return 0;
}
static int
<API key>(struct ext4_xattr_entry **pentry, int name_index,
const char *name, size_t size, int sorted)
{
struct ext4_xattr_entry *entry;
size_t name_len;
int cmp = 1;
if (name == NULL)
return -EINVAL;
name_len = strlen(name);
entry = *pentry;
for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
cmp = name_index - entry->e_name_index;
if (!cmp)
cmp = name_len - entry->e_name_len;
if (!cmp)
cmp = memcmp(name, entry->e_name, name_len);
if (cmp <= 0 && (sorted || cmp == 0))
break;
}
*pentry = entry;
if (!cmp && <API key>(entry, size))
return -EIO;
return cmp ? -ENODATA : 0;
}
static int
<API key>(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct buffer_head *bh = NULL;
struct ext4_xattr_entry *entry;
size_t size;
int error;
ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
name_index, name, buffer, (long)buffer_size);
error = -ENODATA;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (<API key>(bh)) {
bad_block:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
<API key>(bh);
entry = BFIRST(bh);
error = <API key>(&entry, name_index, name, bh->b_size, 1);
if (error == -EIO)
goto bad_block;
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),
size);
}
error = size;
cleanup:
brelse(bh);
return error;
}
static int
<API key>(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct <API key> *header;
struct ext4_xattr_entry *entry;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
size_t size;
void *end;
int error;
if (!<API key>(inode, EXT4_STATE_XATTR))
return -ENODATA;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = <API key>(entry, end);
if (error)
goto cleanup;
error = <API key>(&entry, name_index, name,
end - (void *)entry, 0);
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
memcpy(buffer, (void *)IFIRST(header) +
le16_to_cpu(entry->e_value_offs), size);
}
error = size;
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext4_xattr_get()
*
* Copy an extended attribute into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
int
ext4_xattr_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
int error;
down_read(&EXT4_I(inode)->xattr_sem);
error = <API key>(inode, name_index, name, buffer,
buffer_size);
if (error == -ENODATA)
error = <API key>(inode, name_index, name, buffer,
buffer_size);
up_read(&EXT4_I(inode)->xattr_sem);
return error;
}
static int
<API key>(struct dentry *dentry, struct ext4_xattr_entry *entry,
char *buffer, size_t buffer_size)
{
size_t rest = buffer_size;
for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
const struct xattr_handler *handler =
ext4_xattr_handler(entry->e_name_index);
if (handler) {
size_t size = handler->list(dentry, buffer, rest,
entry->e_name,
entry->e_name_len,
handler->flags);
if (buffer) {
if (size > rest)
return -ERANGE;
buffer += size;
}
rest -= size;
}
}
return buffer_size - rest;
}
static int
<API key>(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = dentry->d_inode;
struct buffer_head *bh = NULL;
int error;
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
error = 0;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (<API key>(bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
<API key>(bh);
error = <API key>(dentry, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
static int
<API key>(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = dentry->d_inode;
struct <API key> *header;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
void *end;
int error;
if (!<API key>(inode, EXT4_STATE_XATTR))
return 0;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = <API key>(IFIRST(header), end);
if (error)
goto cleanup;
error = <API key>(dentry, IFIRST(header),
buffer, buffer_size);
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext4_xattr_list()
*
* Copy a list of attribute names into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
static int
ext4_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
int ret, ret2;
down_read(&EXT4_I(dentry->d_inode)->xattr_sem);
ret = ret2 = <API key>(dentry, buffer, buffer_size);
if (ret < 0)
goto errout;
if (buffer) {
buffer += ret;
buffer_size -= ret;
}
ret = <API key>(dentry, buffer, buffer_size);
if (ret < 0)
goto errout;
ret += ret2;
errout:
up_read(&EXT4_I(dentry->d_inode)->xattr_sem);
return ret;
}
/*
* If the <API key> feature of this file system is
* not set, set it.
*/
static void <API key>(handle_t *handle,
struct super_block *sb)
{
if (<API key>(sb, <API key>))
return;
if (<API key>(handle, EXT4_SB(sb)->s_sbh) == 0) {
<API key>(sb, <API key>);
<API key>(handle, sb);
}
}
/*
* Release the xattr block BH: If the reference count is > 1, decrement
* it; otherwise free the block.
*/
static void
<API key>(handle_t *handle, struct inode *inode,
struct buffer_head *bh)
{
struct mb_cache_entry *ce = NULL;
int error = 0;
ce = mb_cache_entry_get(ext4_xattr_cache, bh->b_bdev, bh->b_blocknr);
error = <API key>(handle, bh);
if (error)
goto out;
lock_buffer(bh);
if (BHDR(bh)->h_refcount == cpu_to_le32(1)) {
ea_bdebug(bh, "refcount now=0; freeing");
if (ce)
mb_cache_entry_free(ce);
get_bh(bh);
ext4_free_blocks(handle, inode, bh, 0, 1,
<API key> |
<API key>);
unlock_buffer(bh);
} else {
le32_add_cpu(&BHDR(bh)->h_refcount, -1);
if (ce)
<API key>(ce);
unlock_buffer(bh);
error = <API key>(handle, inode, bh);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
dquot_free_block(inode, EXT4_C2B(EXT4_SB(inode->i_sb), 1));
ea_bdebug(bh, "refcount now=%d; releasing",
le32_to_cpu(BHDR(bh)->h_refcount));
}
out:
ext4_std_error(inode->i_sb, error);
return;
}
/*
* Find the available free space for EAs. This also returns the total number of
* bytes used by EA entries.
*/
static size_t <API key>(struct ext4_xattr_entry *last,
size_t *min_offs, void *base, int *total)
{
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
*total += EXT4_XATTR_LEN(last->e_name_len);
if (!last->e_value_block && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < *min_offs)
*min_offs = offs;
}
}
return (*min_offs - ((void *)last - base) - sizeof(__u32));
}
struct ext4_xattr_info {
int name_index;
const char *name;
const void *value;
size_t value_len;
};
struct ext4_xattr_search {
struct ext4_xattr_entry *first;
void *base;
void *end;
struct ext4_xattr_entry *here;
int not_found;
};
static int
<API key>(struct ext4_xattr_info *i, struct ext4_xattr_search *s)
{
struct ext4_xattr_entry *last;
size_t free, min_offs = s->end - s->base, name_len = strlen(i->name);
/* Compute min_offs and last. */
last = s->first;
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < min_offs)
min_offs = offs;
}
}
free = min_offs - ((void *)last - s->base) - sizeof(__u32);
if (!s->not_found) {
if (!s->here->e_value_block && s->here->e_value_size) {
size_t size = le32_to_cpu(s->here->e_value_size);
free += EXT4_XATTR_SIZE(size);
}
free += EXT4_XATTR_LEN(name_len);
}
if (i->value) {
if (free < EXT4_XATTR_SIZE(i->value_len) ||
free < EXT4_XATTR_LEN(name_len) +
EXT4_XATTR_SIZE(i->value_len))
return -ENOSPC;
}
if (i->value && s->not_found) {
/* Insert the new name. */
size_t size = EXT4_XATTR_LEN(name_len);
size_t rest = (void *)last - (void *)s->here + sizeof(__u32);
memmove((void *)s->here + size, s->here, rest);
memset(s->here, 0, size);
s->here->e_name_index = i->name_index;
s->here->e_name_len = name_len;
memcpy(s->here->e_name, i->name, name_len);
} else {
if (!s->here->e_value_block && s->here->e_value_size) {
void *first_val = s->base + min_offs;
size_t offs = le16_to_cpu(s->here->e_value_offs);
void *val = s->base + offs;
size_t size = EXT4_XATTR_SIZE(
le32_to_cpu(s->here->e_value_size));
if (i->value && size == EXT4_XATTR_SIZE(i->value_len)) {
/* The old and the new value have the same
size. Just replace. */
s->here->e_value_size =
cpu_to_le32(i->value_len);
memset(val + size - EXT4_XATTR_PAD, 0,
EXT4_XATTR_PAD); /* Clear pad bytes. */
memcpy(val, i->value, i->value_len);
return 0;
}
/* Remove the old value. */
memmove(first_val + size, first_val, val - first_val);
memset(first_val, 0, size);
s->here->e_value_size = 0;
s->here->e_value_offs = 0;
min_offs += size;
/* Adjust all value offsets. */
last = s->first;
while (!IS_LAST_ENTRY(last)) {
size_t o = le16_to_cpu(last->e_value_offs);
if (!last->e_value_block &&
last->e_value_size && o < offs)
last->e_value_offs =
cpu_to_le16(o + size);
last = EXT4_XATTR_NEXT(last);
}
}
if (!i->value) {
/* Remove the old name. */
size_t size = EXT4_XATTR_LEN(name_len);
last = ENTRY((void *)last - size);
memmove(s->here, (void *)s->here + size,
(void *)last - (void *)s->here + sizeof(__u32));
memset(last, 0, size);
}
}
if (i->value) {
/* Insert the new value. */
s->here->e_value_size = cpu_to_le32(i->value_len);
if (i->value_len) {
size_t size = EXT4_XATTR_SIZE(i->value_len);
void *val = s->base + min_offs - size;
s->here->e_value_offs = cpu_to_le16(min_offs - size);
memset(val + size - EXT4_XATTR_PAD, 0,
EXT4_XATTR_PAD); /* Clear the pad bytes. */
memcpy(val, i->value, i->value_len);
}
}
return 0;
}
struct <API key> {
struct ext4_xattr_search s;
struct buffer_head *bh;
};
static int
<API key>(struct inode *inode, struct ext4_xattr_info *i,
struct <API key> *bs)
{
struct super_block *sb = inode->i_sb;
int error;
ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
i->name_index, i->name, i->value, (long)i->value_len);
if (EXT4_I(inode)->i_file_acl) {
/* The inode already has an extended attribute block. */
bs->bh = sb_bread(sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bs->bh)
goto cleanup;
ea_bdebug(bs->bh, "b_count=%d, refcount=%d",
atomic_read(&(bs->bh->b_count)),
le32_to_cpu(BHDR(bs->bh)->h_refcount));
if (<API key>(bs->bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
/* Find the named attribute. */
bs->s.base = BHDR(bs->bh);
bs->s.first = BFIRST(bs->bh);
bs->s.end = bs->bh->b_data + bs->bh->b_size;
bs->s.here = bs->s.first;
error = <API key>(&bs->s.here, i->name_index,
i->name, bs->bh->b_size, 1);
if (error && error != -ENODATA)
goto cleanup;
bs->s.not_found = error;
}
error = 0;
cleanup:
return error;
}
static int
<API key>(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct <API key> *bs)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *new_bh = NULL;
struct ext4_xattr_search *s = &bs->s;
struct mb_cache_entry *ce = NULL;
int error = 0;
#define header(x) ((struct ext4_xattr_header *)(x))
if (i->value && i->value_len > sb->s_blocksize)
return -ENOSPC;
if (s->base) {
ce = mb_cache_entry_get(ext4_xattr_cache, bs->bh->b_bdev,
bs->bh->b_blocknr);
error = <API key>(handle, bs->bh);
if (error)
goto cleanup;
lock_buffer(bs->bh);
if (header(s->base)->h_refcount == cpu_to_le32(1)) {
if (ce) {
mb_cache_entry_free(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "modifying in-place");
error = <API key>(i, s);
if (!error) {
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base),
s->here);
<API key>(bs->bh);
}
unlock_buffer(bs->bh);
if (error == -EIO)
goto bad_block;
if (!error)
error = <API key>(handle,
inode,
bs->bh);
if (error)
goto cleanup;
goto inserted;
} else {
int offset = (char *)s->here - bs->bh->b_data;
unlock_buffer(bs->bh);
<API key>(handle, bs->bh);
if (ce) {
<API key>(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "cloning");
s->base = kmalloc(bs->bh->b_size, GFP_NOFS);
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
memcpy(s->base, BHDR(bs->bh), bs->bh->b_size);
s->first = ENTRY(header(s->base)+1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->here = ENTRY(s->base + offset);
s->end = s->base + bs->bh->b_size;
}
} else {
/* Allocate a buffer where we construct the new block. */
s->base = kzalloc(sb->s_blocksize, GFP_NOFS);
/* assert(header == s->base) */
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
header(s->base)->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
header(s->base)->h_blocks = cpu_to_le32(1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->first = ENTRY(header(s->base)+1);
s->here = ENTRY(header(s->base)+1);
s->end = s->base + sb->s_blocksize;
}
error = <API key>(i, s);
if (error == -EIO)
goto bad_block;
if (error)
goto cleanup;
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base), s->here);
inserted:
if (!IS_LAST_ENTRY(s->first)) {
new_bh = <API key>(inode, header(s->base), &ce);
if (new_bh) {
/* We found an identical block in the cache. */
if (new_bh == bs->bh)
ea_bdebug(new_bh, "keeping");
else {
/* The old block is released after updating
the inode. */
error = dquot_alloc_block(inode,
EXT4_C2B(EXT4_SB(sb), 1));
if (error)
goto cleanup;
error = <API key>(handle,
new_bh);
if (error)
goto cleanup_dquot;
lock_buffer(new_bh);
le32_add_cpu(&BHDR(new_bh)->h_refcount, 1);
ea_bdebug(new_bh, "reusing; refcount now=%d",
le32_to_cpu(BHDR(new_bh)->h_refcount));
unlock_buffer(new_bh);
error = <API key>(handle,
inode,
new_bh);
if (error)
goto cleanup_dquot;
}
<API key>(ce);
ce = NULL;
} else if (bs->bh && s->base == bs->bh->b_data) {
/* We were modifying this block in-place. */
ea_bdebug(bs->bh, "keeping this block");
new_bh = bs->bh;
get_bh(new_bh);
} else {
/* We need to allocate a new block */
ext4_fsblk_t goal, block;
goal = <API key>(sb,
EXT4_I(inode)->i_block_group);
/* non-extent files can't have physical blocks past 2^32 */
if (!(<API key>(inode, EXT4_INODE_EXTENTS)))
goal = goal & <API key>;
/*
* take i_data_sem because we will test
* <API key> in ext4_mb_new_blocks
*/
down_read((&EXT4_I(inode)->i_data_sem));
block = <API key>(handle, inode, goal, 0,
NULL, &error);
up_read((&EXT4_I(inode)->i_data_sem));
if (error)
goto cleanup;
if (!(<API key>(inode, EXT4_INODE_EXTENTS)))
BUG_ON(block > <API key>);
ea_idebug(inode, "creating block %llu",
(unsigned long long)block);
new_bh = sb_getblk(sb, block);
if (!new_bh) {
error = -ENOMEM;
getblk_failed:
ext4_free_blocks(handle, inode, NULL, block, 1,
<API key>);
goto cleanup;
}
lock_buffer(new_bh);
error = <API key>(handle, new_bh);
if (error) {
unlock_buffer(new_bh);
error = -EIO;
goto getblk_failed;
}
memcpy(new_bh->b_data, s->base, new_bh->b_size);
set_buffer_uptodate(new_bh);
unlock_buffer(new_bh);
<API key>(new_bh);
error = <API key>(handle,
inode, new_bh);
if (error)
goto cleanup;
}
}
/* Update the inode. */
EXT4_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
/* Drop the previous xattr block. */
if (bs->bh && bs->bh != new_bh)
<API key>(handle, inode, bs->bh);
error = 0;
cleanup:
if (ce)
<API key>(ce);
brelse(new_bh);
if (!(bs->bh && s->base == bs->bh->b_data))
kfree(s->base);
return error;
cleanup_dquot:
dquot_free_block(inode, EXT4_C2B(EXT4_SB(sb), 1));
goto cleanup;
bad_block:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
goto cleanup;
#undef header
}
struct <API key> {
struct ext4_xattr_search s;
struct ext4_iloc iloc;
};
static int
<API key>(struct inode *inode, struct ext4_xattr_info *i,
struct <API key> *is)
{
struct <API key> *header;
struct ext4_inode *raw_inode;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return 0;
raw_inode = ext4_raw_inode(&is->iloc);
header = IHDR(inode, raw_inode);
is->s.base = is->s.first = IFIRST(header);
is->s.here = is->s.first;
is->s.end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
if (<API key>(inode, EXT4_STATE_XATTR)) {
error = <API key>(IFIRST(header), is->s.end);
if (error)
return error;
/* Find the named attribute. */
error = <API key>(&is->s.here, i->name_index,
i->name, is->s.end -
(void *)is->s.base, 0);
if (error && error != -ENODATA)
return error;
is->s.not_found = error;
}
return 0;
}
static int
<API key>(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct <API key> *is)
{
struct <API key> *header;
struct ext4_xattr_search *s = &is->s;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return -ENOSPC;
error = <API key>(i, s);
if (error)
return error;
header = IHDR(inode, ext4_raw_inode(&is->iloc));
if (!IS_LAST_ENTRY(s->first)) {
header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
<API key>(inode, EXT4_STATE_XATTR);
} else {
header->h_magic = cpu_to_le32(0);
<API key>(inode, EXT4_STATE_XATTR);
}
return 0;
}
/*
* <API key>()
*
* Create, replace or remove an extended attribute for this inode. Value
* is NULL to remove an existing extended attribute, and non-NULL to
* either replace an existing extended attribute, or create a new extended
* attribute. The flags XATTR_REPLACE and XATTR_CREATE
* specify that an extended attribute must exist and must not exist
* previous to the call, respectively.
*
* Returns 0, or a negative error number on failure.
*/
int
<API key>(handle_t *handle, struct inode *inode, int name_index,
const char *name, const void *value, size_t value_len,
int flags)
{
struct ext4_xattr_info i = {
.name_index = name_index,
.name = name,
.value = value,
.value_len = value_len,
};
struct <API key> is = {
.s = { .not_found = -ENODATA, },
};
struct <API key> bs = {
.s = { .not_found = -ENODATA, },
};
unsigned long no_expand;
int error;
if (!name)
return -EINVAL;
if (strlen(name) > 255)
return -ERANGE;
down_write(&EXT4_I(inode)->xattr_sem);
no_expand = <API key>(inode, <API key>);
<API key>(inode, <API key>);
error = <API key>(handle, inode, &is.iloc);
if (error)
goto cleanup;
if (<API key>(inode, EXT4_STATE_NEW)) {
struct ext4_inode *raw_inode = ext4_raw_inode(&is.iloc);
memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
<API key>(inode, EXT4_STATE_NEW);
}
error = <API key>(inode, &i, &is);
if (error)
goto cleanup;
if (is.s.not_found)
error = <API key>(inode, &i, &bs);
if (error)
goto cleanup;
if (is.s.not_found && bs.s.not_found) {
error = -ENODATA;
if (flags & XATTR_REPLACE)
goto cleanup;
error = 0;
if (!value)
goto cleanup;
} else {
error = -EEXIST;
if (flags & XATTR_CREATE)
goto cleanup;
}
if (!value) {
if (!is.s.not_found)
error = <API key>(handle, inode, &i, &is);
else if (!bs.s.not_found)
error = <API key>(handle, inode, &i, &bs);
} else {
error = <API key>(handle, inode, &i, &is);
if (!error && !bs.s.not_found) {
i.value = NULL;
error = <API key>(handle, inode, &i, &bs);
} else if (error == -ENOSPC) {
if (EXT4_I(inode)->i_file_acl && !bs.s.base) {
error = <API key>(inode, &i, &bs);
if (error)
goto cleanup;
}
error = <API key>(handle, inode, &i, &bs);
if (error)
goto cleanup;
if (!is.s.not_found) {
i.value = NULL;
error = <API key>(handle, inode, &i,
&is);
}
}
}
if (!error) {
<API key>(handle, inode->i_sb);
inode->i_ctime = ext4_current_time(inode);
if (!value)
<API key>(inode, <API key>);
error = <API key>(handle, inode, &is.iloc);
/*
* The bh is consumed by <API key>, even with
* error != 0.
*/
is.iloc.bh = NULL;
if (IS_SYNC(inode))
ext4_handle_sync(handle);
}
cleanup:
brelse(is.iloc.bh);
brelse(bs.bh);
if (no_expand == 0)
<API key>(inode, <API key>);
up_write(&EXT4_I(inode)->xattr_sem);
return error;
}
/*
* ext4_xattr_set()
*
* Like <API key>, but start from an inode. This extended
* attribute modification is a filesystem transaction by itself.
*
* Returns 0, or a negative error number on failure.
*/
int
ext4_xattr_set(struct inode *inode, int name_index, const char *name,
const void *value, size_t value_len, int flags)
{
handle_t *handle;
int error, retries = 0;
retry:
handle = ext4_journal_start(inode, <API key>(inode->i_sb));
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
} else {
int error2;
error = <API key>(handle, inode, name_index, name,
value, value_len, flags);
error2 = ext4_journal_stop(handle);
if (error == -ENOSPC &&
<API key>(inode->i_sb, &retries))
goto retry;
if (error == 0)
error = error2;
}
return error;
}
/*
* Shift the EA entries in the inode to create space for the increased
* i_extra_isize.
*/
static void <API key>(struct ext4_xattr_entry *entry,
int value_offs_shift, void *to,
void *from, size_t n, int blocksize)
{
struct ext4_xattr_entry *last = entry;
int new_offs;
/* Adjust the value offsets of the entries */
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
new_offs = le16_to_cpu(last->e_value_offs) +
value_offs_shift;
BUG_ON(new_offs + le32_to_cpu(last->e_value_size)
> blocksize);
last->e_value_offs = cpu_to_le16(new_offs);
}
}
/* Shift the entries by n bytes */
memmove(to, from, n);
}
/*
* Expand an inode by new_extra_isize bytes when EAs are present.
* Returns 0 on success or negative error number on failure.
*/
int <API key>(struct inode *inode, int new_extra_isize,
struct ext4_inode *raw_inode, handle_t *handle)
{
struct <API key> *header;
struct ext4_xattr_entry *entry, *last, *first;
struct buffer_head *bh = NULL;
struct <API key> *is = NULL;
struct <API key> *bs = NULL;
char *buffer = NULL, *b_entry_name = NULL;
size_t min_offs, free;
int total_ino, total_blk;
void *base, *start, *end;
int extra_isize = 0, error = 0, <API key> = 0;
int s_min_extra_isize = le16_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_min_extra_isize);
down_write(&EXT4_I(inode)->xattr_sem);
retry:
if (EXT4_I(inode)->i_extra_isize >= new_extra_isize) {
up_write(&EXT4_I(inode)->xattr_sem);
return 0;
}
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
/*
* Check if enough free space is available in the inode to shift the
* entries ahead by new_extra_isize.
*/
base = start = entry;
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
min_offs = end - base;
last = entry;
total_ino = sizeof(struct <API key>);
free = <API key>(last, &min_offs, base, &total_ino);
if (free >= new_extra_isize) {
entry = IFIRST(header);
<API key>(entry, EXT4_I(inode)->i_extra_isize
- new_extra_isize, (void *)raw_inode +
<API key> + new_extra_isize,
(void *)header, total_ino,
inode->i_sb->s_blocksize);
EXT4_I(inode)->i_extra_isize = new_extra_isize;
error = 0;
goto cleanup;
}
/*
* Enough free space isn't available in the inode, check if
* EA block can hold new_extra_isize bytes.
*/
if (EXT4_I(inode)->i_file_acl) {
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
if (<API key>(bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
base = BHDR(bh);
first = BFIRST(bh);
end = bh->b_data + bh->b_size;
min_offs = end - base;
free = <API key>(first, &min_offs, base,
&total_blk);
if (free < new_extra_isize) {
if (!<API key> && s_min_extra_isize) {
<API key>++;
new_extra_isize = s_min_extra_isize;
brelse(bh);
goto retry;
}
error = -1;
goto cleanup;
}
} else {
free = inode->i_sb->s_blocksize;
}
while (new_extra_isize > 0) {
size_t offs, size, entry_size;
struct ext4_xattr_entry *small_entry = NULL;
struct ext4_xattr_info i = {
.value = NULL,
.value_len = 0,
};
unsigned int total_size; /* EA entry size + value size */
unsigned int shift_bytes; /* No. of bytes to shift EAs by? */
unsigned int min_total_size = ~0U;
is = kzalloc(sizeof(struct <API key>), GFP_NOFS);
bs = kzalloc(sizeof(struct <API key>), GFP_NOFS);
if (!is || !bs) {
error = -ENOMEM;
goto cleanup;
}
is->s.not_found = -ENODATA;
bs->s.not_found = -ENODATA;
is->iloc.bh = NULL;
bs->bh = NULL;
last = IFIRST(header);
/* Find the entry best suited to be pushed into EA block */
entry = NULL;
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
total_size =
EXT4_XATTR_SIZE(le32_to_cpu(last->e_value_size)) +
EXT4_XATTR_LEN(last->e_name_len);
if (total_size <= free && total_size < min_total_size) {
if (total_size < new_extra_isize) {
small_entry = last;
} else {
entry = last;
min_total_size = total_size;
}
}
}
if (entry == NULL) {
if (small_entry) {
entry = small_entry;
} else {
if (!<API key> &&
s_min_extra_isize) {
<API key>++;
new_extra_isize = s_min_extra_isize;
kfree(is); is = NULL;
kfree(bs); bs = NULL;
goto retry;
}
error = -1;
goto cleanup;
}
}
offs = le16_to_cpu(entry->e_value_offs);
size = le32_to_cpu(entry->e_value_size);
entry_size = EXT4_XATTR_LEN(entry->e_name_len);
i.name_index = entry->e_name_index,
buffer = kmalloc(EXT4_XATTR_SIZE(size), GFP_NOFS);
b_entry_name = kmalloc(entry->e_name_len + 1, GFP_NOFS);
if (!buffer || !b_entry_name) {
error = -ENOMEM;
goto cleanup;
}
/* Save the entry name and the entry value */
memcpy(buffer, (void *)IFIRST(header) + offs,
EXT4_XATTR_SIZE(size));
memcpy(b_entry_name, entry->e_name, entry->e_name_len);
b_entry_name[entry->e_name_len] = '\0';
i.name = b_entry_name;
error = ext4_get_inode_loc(inode, &is->iloc);
if (error)
goto cleanup;
error = <API key>(inode, &i, is);
if (error)
goto cleanup;
/* Remove the chosen entry from the inode */
error = <API key>(handle, inode, &i, is);
if (error)
goto cleanup;
entry = IFIRST(header);
if (entry_size + EXT4_XATTR_SIZE(size) >= new_extra_isize)
shift_bytes = new_extra_isize;
else
shift_bytes = entry_size + size;
/* Adjust the offsets and shift the remaining entries ahead */
<API key>(entry, EXT4_I(inode)->i_extra_isize -
shift_bytes, (void *)raw_inode +
<API key> + extra_isize + shift_bytes,
(void *)header, total_ino - entry_size,
inode->i_sb->s_blocksize);
extra_isize += shift_bytes;
new_extra_isize -= shift_bytes;
EXT4_I(inode)->i_extra_isize = extra_isize;
i.name = b_entry_name;
i.value = buffer;
i.value_len = size;
error = <API key>(inode, &i, bs);
if (error)
goto cleanup;
/* Add entry which was removed from the inode into the block */
error = <API key>(handle, inode, &i, bs);
if (error)
goto cleanup;
kfree(b_entry_name);
kfree(buffer);
b_entry_name = NULL;
buffer = NULL;
brelse(is->iloc.bh);
kfree(is);
kfree(bs);
}
brelse(bh);
up_write(&EXT4_I(inode)->xattr_sem);
return 0;
cleanup:
kfree(b_entry_name);
kfree(buffer);
if (is)
brelse(is->iloc.bh);
kfree(is);
kfree(bs);
brelse(bh);
up_write(&EXT4_I(inode)->xattr_sem);
return error;
}
/*
* <API key>()
*
* Free extended attribute resources associated with this inode. This
* is called immediately before an inode is freed. We have exclusive
* access to the inode.
*/
void
<API key>(handle_t *handle, struct inode *inode)
{
struct buffer_head *bh = NULL;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %llu read error",
EXT4_I(inode)->i_file_acl);
goto cleanup;
}
if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
goto cleanup;
}
<API key>(handle, inode, bh);
EXT4_I(inode)->i_file_acl = 0;
cleanup:
brelse(bh);
}
/*
* <API key>()
*
* This is called when a file system is unmounted.
*/
void
<API key>(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
/*
* <API key>()
*
* Create a new entry in the extended attribute cache, and insert
* it unless such an entry is already in the cache.
*
* Returns 0, or a negative error number on failure.
*/
static void
<API key>(struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(BHDR(bh)->h_hash);
struct mb_cache_entry *ce;
int error;
ce = <API key>(ext4_xattr_cache, GFP_NOFS);
if (!ce) {
ea_bdebug(bh, "out of memory");
return;
}
error = <API key>(ce, bh->b_bdev, bh->b_blocknr, hash);
if (error) {
mb_cache_entry_free(ce);
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache");
error = 0;
}
} else {
ea_bdebug(bh, "inserting [%x]", (int)hash);
<API key>(ce);
}
}
/*
* ext4_xattr_cmp()
*
* Compare two extended attribute blocks for equality.
*
* Returns 0 if the blocks are equal, 1 if they differ, and
* a negative error number on errors.
*/
static int
ext4_xattr_cmp(struct ext4_xattr_header *header1,
struct ext4_xattr_header *header2)
{
struct ext4_xattr_entry *entry1, *entry2;
entry1 = ENTRY(header1+1);
entry2 = ENTRY(header2+1);
while (!IS_LAST_ENTRY(entry1)) {
if (IS_LAST_ENTRY(entry2))
return 1;
if (entry1->e_hash != entry2->e_hash ||
entry1->e_name_index != entry2->e_name_index ||
entry1->e_name_len != entry2->e_name_len ||
entry1->e_value_size != entry2->e_value_size ||
memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
return 1;
if (entry1->e_value_block != 0 || entry2->e_value_block != 0)
return -EIO;
if (memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
(char *)header2 + le16_to_cpu(entry2->e_value_offs),
le32_to_cpu(entry1->e_value_size)))
return 1;
entry1 = EXT4_XATTR_NEXT(entry1);
entry2 = EXT4_XATTR_NEXT(entry2);
}
if (!IS_LAST_ENTRY(entry2))
return 1;
return 0;
}
/*
* <API key>()
*
* Find an identical extended attribute block.
*
* Returns a pointer to the block found, or NULL if such a block was
* not found or an error occurred.
*/
static struct buffer_head *
<API key>(struct inode *inode, struct ext4_xattr_header *header,
struct mb_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = <API key>(ext4_xattr_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %lu read error",
(unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
<API key>) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
<API key>);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = <API key>(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
#define NAME_HASH_SHIFT 5
#define VALUE_HASH_SHIFT 16
/*
* <API key>()
*
* Compute the hash of an extended attribute.
*/
static inline void <API key>(struct ext4_xattr_header *header,
struct ext4_xattr_entry *entry)
{
__u32 hash = 0;
char *name = entry->e_name;
int n;
for (n = 0; n < entry->e_name_len; n++) {
hash = (hash << NAME_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
*name++;
}
if (entry->e_value_block == 0 && entry->e_value_size != 0) {
__le32 *value = (__le32 *)((char *)header +
le16_to_cpu(entry->e_value_offs));
for (n = (le32_to_cpu(entry->e_value_size) +
EXT4_XATTR_ROUND) >> EXT4_XATTR_PAD_BITS; n; n
hash = (hash << VALUE_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
le32_to_cpu(*value++);
}
}
entry->e_hash = cpu_to_le32(hash);
}
#undef NAME_HASH_SHIFT
#undef VALUE_HASH_SHIFT
#define BLOCK_HASH_SHIFT 16
/*
* ext4_xattr_rehash()
*
* Re-compute the extended attribute hash value after an entry has changed.
*/
static void ext4_xattr_rehash(struct ext4_xattr_header *header,
struct ext4_xattr_entry *entry)
{
struct ext4_xattr_entry *here;
__u32 hash = 0;
<API key>(header, entry);
here = ENTRY(header+1);
while (!IS_LAST_ENTRY(here)) {
if (!here->e_hash) {
/* Block is not shared if an entry's hash value == 0 */
hash = 0;
break;
}
hash = (hash << BLOCK_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - BLOCK_HASH_SHIFT)) ^
le32_to_cpu(here->e_hash);
here = EXT4_XATTR_NEXT(here);
}
header->h_hash = cpu_to_le32(hash);
}
#undef BLOCK_HASH_SHIFT
int __init
ext4_init_xattr(void)
{
ext4_xattr_cache = mb_cache_create("ext4_xattr", 6);
if (!ext4_xattr_cache)
return -ENOMEM;
return 0;
}
void
ext4_exit_xattr(void)
{
if (ext4_xattr_cache)
mb_cache_destroy(ext4_xattr_cache);
ext4_xattr_cache = NULL;
} |
#include "sh_intc.h"
#include "hw.h"
#include "sh.h"
//#define DEBUG_INTC
//#define DEBUG_INTC_SOURCES
#define INTC_A7(x) ((x) & 0x1fffffff)
void <API key>(struct intc_source *source,
int enable_adj, int assert_adj)
{
int enable_changed = 0;
int pending_changed = 0;
int old_pending;
if ((source->enable_count == source->enable_max) && (enable_adj == -1))
enable_changed = -1;
source->enable_count += enable_adj;
if (source->enable_count == source->enable_max)
enable_changed = 1;
source->asserted += assert_adj;
old_pending = source->pending;
source->pending = source->asserted &&
(source->enable_count == source->enable_max);
if (old_pending != source->pending)
pending_changed = 1;
if (pending_changed) {
if (source->pending) {
source->parent->pending++;
if (source->parent->pending == 1)
cpu_interrupt(first_cpu, CPU_INTERRUPT_HARD);
}
else {
source->parent->pending
if (source->parent->pending == 0)
cpu_reset_interrupt(first_cpu, CPU_INTERRUPT_HARD);
}
}
if (enable_changed || assert_adj || pending_changed) {
#ifdef DEBUG_INTC_SOURCES
printf("sh_intc: (%d/%d/%d/%d) interrupt source 0x%x %s%s%s\n",
source->parent->pending,
source->asserted,
source->enable_count,
source->enable_max,
source->vect,
source->asserted ? "asserted " :
assert_adj ? "deasserted" : "",
enable_changed == 1 ? "enabled " :
enable_changed == -1 ? "disabled " : "",
source->pending ? "pending" : "");
#endif
}
}
static void sh_intc_set_irq (void *opaque, int n, int level)
{
struct intc_desc *desc = opaque;
struct intc_source *source = &(desc->sources[n]);
if (level && !source->asserted)
<API key>(source, 0, 1);
else if (!level && source->asserted)
<API key>(source, 0, -1);
}
int <API key>(struct intc_desc *desc, int imask)
{
unsigned int i;
/* slow: use a linked lists of pending sources instead */
/* wrong: take interrupt priority into account (one list per priority) */
if (imask == 0x0f) {
return -1; /* FIXME, update code to include priority per source */
}
for (i = 0; i < desc->nr_sources; i++) {
struct intc_source *source = desc->sources + i;
if (source->pending) {
#ifdef DEBUG_INTC_SOURCES
printf("sh_intc: (%d) returning interrupt source 0x%x\n",
desc->pending, source->vect);
#endif
return source->vect;
}
}
abort();
}
#define INTC_MODE_NONE 0
#define INTC_MODE_DUAL_SET 1
#define INTC_MODE_DUAL_CLR 2
#define <API key> 3
#define INTC_MODE_MASK_REG 4
#define INTC_MODE_IS_PRIO 8
static unsigned int sh_intc_mode(unsigned long address,
unsigned long set_reg, unsigned long clr_reg)
{
if ((address != INTC_A7(set_reg)) &&
(address != INTC_A7(clr_reg)))
return INTC_MODE_NONE;
if (set_reg && clr_reg) {
if (address == INTC_A7(set_reg))
return INTC_MODE_DUAL_SET;
else
return INTC_MODE_DUAL_CLR;
}
if (set_reg)
return <API key>;
else
return INTC_MODE_MASK_REG;
}
static void sh_intc_locate(struct intc_desc *desc,
unsigned long address,
unsigned long **datap,
intc_enum **enums,
unsigned int *first,
unsigned int *width,
unsigned int *modep)
{
unsigned int i, mode;
/* this is slow but works for now */
if (desc->mask_regs) {
for (i = 0; i < desc->nr_mask_regs; i++) {
struct intc_mask_reg *mr = desc->mask_regs + i;
mode = sh_intc_mode(address, mr->set_reg, mr->clr_reg);
if (mode == INTC_MODE_NONE)
continue;
*modep = mode;
*datap = &mr->value;
*enums = mr->enum_ids;
*first = mr->reg_width - 1;
*width = 1;
return;
}
}
if (desc->prio_regs) {
for (i = 0; i < desc->nr_prio_regs; i++) {
struct intc_prio_reg *pr = desc->prio_regs + i;
mode = sh_intc_mode(address, pr->set_reg, pr->clr_reg);
if (mode == INTC_MODE_NONE)
continue;
*modep = mode | INTC_MODE_IS_PRIO;
*datap = &pr->value;
*enums = pr->enum_ids;
*first = (pr->reg_width / pr->field_width) - 1;
*width = pr->field_width;
return;
}
}
abort();
}
static void sh_intc_toggle_mask(struct intc_desc *desc, intc_enum id,
int enable, int is_group)
{
struct intc_source *source = desc->sources + id;
if (!id)
return;
if (!source->next_enum_id && (!source->enable_max || !source->vect)) {
#ifdef DEBUG_INTC_SOURCES
printf("sh_intc: reserved interrupt source %d modified\n", id);
#endif
return;
}
if (source->vect)
<API key>(source, enable ? 1 : -1, 0);
#ifdef DEBUG_INTC
else {
printf("setting interrupt group %d to %d\n", id, !!enable);
}
#endif
if ((is_group || !source->vect) && source->next_enum_id) {
sh_intc_toggle_mask(desc, source->next_enum_id, enable, 1);
}
#ifdef DEBUG_INTC
if (!source->vect) {
printf("setting interrupt group %d to %d - done\n", id, !!enable);
}
#endif
}
static uint32_t sh_intc_read(void *opaque, target_phys_addr_t offset)
{
struct intc_desc *desc = opaque;
intc_enum *enum_ids = NULL;
unsigned int first = 0;
unsigned int width = 0;
unsigned int mode = 0;
unsigned long *valuep;
#ifdef DEBUG_INTC
printf("sh_intc_read 0x%lx\n", (unsigned long) offset);
#endif
sh_intc_locate(desc, (unsigned long)offset, &valuep,
&enum_ids, &first, &width, &mode);
return *valuep;
}
static void sh_intc_write(void *opaque, target_phys_addr_t offset,
uint32_t value)
{
struct intc_desc *desc = opaque;
intc_enum *enum_ids = NULL;
unsigned int first = 0;
unsigned int width = 0;
unsigned int mode = 0;
unsigned int k;
unsigned long *valuep;
unsigned long mask;
#ifdef DEBUG_INTC
printf("sh_intc_write 0x%lx 0x%08x\n", (unsigned long) offset, value);
#endif
sh_intc_locate(desc, (unsigned long)offset, &valuep,
&enum_ids, &first, &width, &mode);
switch (mode) {
case <API key> | INTC_MODE_IS_PRIO: break;
case INTC_MODE_DUAL_SET: value |= *valuep; break;
case INTC_MODE_DUAL_CLR: value = *valuep & ~value; break;
default: abort();
}
for (k = 0; k <= first; k++) {
mask = ((1 << width) - 1) << ((first - k) * width);
if ((*valuep & mask) == (value & mask))
continue;
#if 0
printf("k = %d, first = %d, enum = %d, mask = 0x%08x\n",
k, first, enum_ids[k], (unsigned int)mask);
#endif
sh_intc_toggle_mask(desc, enum_ids[k], value & mask, 0);
}
*valuep = value;
#ifdef DEBUG_INTC
printf("sh_intc_write 0x%lx -> 0x%08x\n", (unsigned long) offset, value);
#endif
}
static CPUReadMemoryFunc * const sh_intc_readfn[] = {
sh_intc_read,
sh_intc_read,
sh_intc_read
};
static CPUWriteMemoryFunc * const sh_intc_writefn[] = {
sh_intc_write,
sh_intc_write,
sh_intc_write
};
struct intc_source *sh_intc_source(struct intc_desc *desc, intc_enum id)
{
if (id)
return desc->sources + id;
return NULL;
}
static void sh_intc_register(struct intc_desc *desc,
unsigned long address)
{
if (address) {
<API key>(P4ADDR(address), 4,
desc->iomemtype, INTC_A7(address));
<API key>(A7ADDR(address), 4,
desc->iomemtype, INTC_A7(address));
}
}
static void <API key>(struct intc_desc *desc,
intc_enum source,
struct intc_group *groups,
int nr_groups)
{
unsigned int i, k;
struct intc_source *s;
if (desc->mask_regs) {
for (i = 0; i < desc->nr_mask_regs; i++) {
struct intc_mask_reg *mr = desc->mask_regs + i;
for (k = 0; k < ARRAY_SIZE(mr->enum_ids); k++) {
if (mr->enum_ids[k] != source)
continue;
s = sh_intc_source(desc, mr->enum_ids[k]);
if (s)
s->enable_max++;
}
}
}
if (desc->prio_regs) {
for (i = 0; i < desc->nr_prio_regs; i++) {
struct intc_prio_reg *pr = desc->prio_regs + i;
for (k = 0; k < ARRAY_SIZE(pr->enum_ids); k++) {
if (pr->enum_ids[k] != source)
continue;
s = sh_intc_source(desc, pr->enum_ids[k]);
if (s)
s->enable_max++;
}
}
}
if (groups) {
for (i = 0; i < nr_groups; i++) {
struct intc_group *gr = groups + i;
for (k = 0; k < ARRAY_SIZE(gr->enum_ids); k++) {
if (gr->enum_ids[k] != source)
continue;
s = sh_intc_source(desc, gr->enum_ids[k]);
if (s)
s->enable_max++;
}
}
}
}
void <API key>(struct intc_desc *desc,
struct intc_vect *vectors,
int nr_vectors,
struct intc_group *groups,
int nr_groups)
{
unsigned int i, k;
struct intc_source *s;
for (i = 0; i < nr_vectors; i++) {
struct intc_vect *vect = vectors + i;
<API key>(desc, vect->enum_id, groups, nr_groups);
s = sh_intc_source(desc, vect->enum_id);
if (s)
s->vect = vect->vect;
#ifdef DEBUG_INTC_SOURCES
printf("sh_intc: registered source %d -> 0x%04x (%d/%d)\n",
vect->enum_id, s->vect, s->enable_count, s->enable_max);
#endif
}
if (groups) {
for (i = 0; i < nr_groups; i++) {
struct intc_group *gr = groups + i;
s = sh_intc_source(desc, gr->enum_id);
s->next_enum_id = gr->enum_ids[0];
for (k = 1; k < ARRAY_SIZE(gr->enum_ids); k++) {
if (!gr->enum_ids[k])
continue;
s = sh_intc_source(desc, gr->enum_ids[k - 1]);
s->next_enum_id = gr->enum_ids[k];
}
#ifdef DEBUG_INTC_SOURCES
printf("sh_intc: registered group %d (%d/%d)\n",
gr->enum_id, s->enable_count, s->enable_max);
#endif
}
}
}
int sh_intc_init(struct intc_desc *desc,
int nr_sources,
struct intc_mask_reg *mask_regs,
int nr_mask_regs,
struct intc_prio_reg *prio_regs,
int nr_prio_regs)
{
unsigned int i;
desc->pending = 0;
desc->nr_sources = nr_sources;
desc->mask_regs = mask_regs;
desc->nr_mask_regs = nr_mask_regs;
desc->prio_regs = prio_regs;
desc->nr_prio_regs = nr_prio_regs;
i = sizeof(struct intc_source) * nr_sources;
desc->sources = qemu_mallocz(i);
for (i = 0; i < desc->nr_sources; i++) {
struct intc_source *source = desc->sources + i;
source->parent = desc;
}
desc->irqs = qemu_allocate_irqs(sh_intc_set_irq, desc, nr_sources);
desc->iomemtype = <API key>(sh_intc_readfn,
sh_intc_writefn, desc,
<API key>);
if (desc->mask_regs) {
for (i = 0; i < desc->nr_mask_regs; i++) {
struct intc_mask_reg *mr = desc->mask_regs + i;
sh_intc_register(desc, mr->set_reg);
sh_intc_register(desc, mr->clr_reg);
}
}
if (desc->prio_regs) {
for (i = 0; i < desc->nr_prio_regs; i++) {
struct intc_prio_reg *pr = desc->prio_regs + i;
sh_intc_register(desc, pr->set_reg);
sh_intc_register(desc, pr->clr_reg);
}
}
return 0;
}
/* Assert level <n> IRL interrupt.
0:deassert. 1:lowest priority,... 15:highest priority. */
void sh_intc_set_irl(void *opaque, int n, int level)
{
struct intc_source *s = opaque;
int i, irl = level ^ 15;
for (i = 0; (s = sh_intc_source(s->parent, s->next_enum_id)); i++) {
if (i == irl)
<API key>(s, s->enable_count?0:1, s->asserted?0:1);
else
if (s->asserted)
<API key>(s, 0, -1);
}
} |
#ifndef <API key>
#define <API key>
#include <stdlib.h>
#include "common/util.h"
/** Common array type */
#define ARRAY_TYPE(type_t, pfx) \
typedef struct pfx##_array_t { \
type_t *tab; \
int len, size; \
} pfx##_array_t;
#define foreach(var, array) \
for(int __foreach_index_##var = 0; \
__foreach_index_##var < (array).len; \
__foreach_index_##var = (array).len) \
for(typeof((array).tab) var = &(array).tab[__foreach_index_##var]; \
(__foreach_index_##var < (array).len) && \
(var = &(array).tab[__foreach_index_##var]); \
++__foreach_index_##var)
/** Common array functions */
#define ARRAY_COMMON_FUNCS(type_t, pfx, dtor) \
static inline pfx##_array_t * pfx##_array_new(void) { \
return p_new(pfx##_array_t, 1); \
} \
static inline void pfx##_array_init(pfx##_array_t *arr) { \
p_clear(arr, 1); \
} \
static inline void pfx##_array_wipe(pfx##_array_t *arr) { \
for (int i = 0; i < arr->len; i++) { \
dtor(&arr->tab[i]); \
} \
p_delete(&arr->tab); \
} \
static inline void pfx##_array_delete(pfx##_array_t **arrp) { \
if (*arrp) { \
pfx##_array_wipe(*arrp); \
p_delete(arrp); \
} \
} \
\
static inline void pfx##_array_grow(pfx##_array_t *arr, int newlen) { \
p_grow(&arr->tab, newlen, &arr->size); \
} \
static inline void \
pfx##_array_splice(pfx##_array_t *arr, int pos, int len, \
type_t items[], int count) \
{ \
assert (pos >= 0 && len >= 0 && count >= 0); \
assert (pos <= arr->len && pos + len <= arr->len); \
if (len != count) { \
pfx##_array_grow(arr, arr->len + count - len); \
memmove(arr->tab + pos + count, arr->tab + pos + len, \
(arr->len - pos - len) * sizeof(*items)); \
arr->len += count - len; \
} \
memcpy(arr->tab + pos, items, count * sizeof(*items)); \
} \
static inline type_t pfx##_array_take(pfx##_array_t *arr, int pos) { \
type_t res = arr->tab[pos]; \
pfx##_array_splice(arr, pos, 1, NULL, 0); \
return res; \
} \
static inline int pfx##_array_indexof(pfx##_array_t *arr, type_t *e) \
{ \
return e - arr->tab; \
} \
static inline type_t pfx##_array_remove(pfx##_array_t *arr, type_t *e) \
{ \
return pfx##_array_take(arr, pfx##_array_indexof(arr, e)); \
}
/** Non-ordered array functions */
#define ARRAY_FUNCS(type_t, pfx, dtor) \
ARRAY_COMMON_FUNCS(type_t, pfx, dtor) \
static inline void \
pfx##_array_push(pfx##_array_t *arr, type_t e) \
{ \
pfx##_array_splice(arr, 0, 0, &e, 1); \
} \
static inline void pfx##_array_append(pfx##_array_t *arr, type_t e) { \
pfx##_array_splice(arr, arr->len, 0, &e, 1); \
} \
/** Binary ordered array functions */
#define BARRAY_FUNCS(type_t, pfx, dtor, cmp) \
ARRAY_COMMON_FUNCS(type_t, pfx, dtor) \
static inline void \
pfx##_array_insert(pfx##_array_t *arr, type_t e) \
{ \
int l = 0, r = arr->len; \
while(l < r) \
{ \
int i = (r + l) / 2; \
int res = cmp(&e, &arr->tab[i]); \
if(res == 0) \
return; /* Already added, ignore */ \
if(res < 0) \
r = i; \
else \
l = i + 1; \
} \
pfx##_array_splice(arr, r, 0, &e, 1); \
} \
static inline type_t * \
pfx##_array_lookup(pfx##_array_t *arr, type_t *e) \
{ \
return bsearch(e, arr->tab, arr->len, sizeof(type_t), cmp); \
}
#define DO_ARRAY(type_t, pfx, dtor) \
ARRAY_TYPE(type_t, pfx) \
ARRAY_FUNCS(type_t, pfx, dtor)
#define DO_BARRAY(type_t, pfx, dtor, cmp) \
ARRAY_TYPE(type_t, pfx) \
BARRAY_FUNCS(type_t, pfx, dtor, cmp)
#endif
// vim: filetype=c:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80 |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Preview;
use Twilio\Domain;
use Twilio\Exceptions\TwilioException;
use Twilio\Rest\Preview\HostedNumbers\<API key>;
use Twilio\Version;
/**
* @property \Twilio\Rest\Preview\HostedNumbers\<API key> hostedNumberOrders
* @method \Twilio\Rest\Preview\HostedNumbers\<API key> hostedNumberOrders(string $sid)
*/
class HostedNumbers extends Version {
protected $_hostedNumberOrders = null;
/**
* Construct the HostedNumbers version of Preview
*
* @param \Twilio\Domain $domain Domain that contains the version
* @return \Twilio\Rest\Preview\HostedNumbers HostedNumbers version of Preview
*/
public function __construct(Domain $domain) {
parent::__construct($domain);
$this->version = 'HostedNumbers';
}
/**
* @return \Twilio\Rest\Preview\HostedNumbers\<API key>
*/
protected function <API key>() {
if (!$this->_hostedNumberOrders) {
$this->_hostedNumberOrders = new <API key>($this);
}
return $this->_hostedNumberOrders;
}
/**
* Magic getter to lazy load root resources
*
* @param string $name Resource to return
* @return \Twilio\ListResource The requested resource
* @throws \Twilio\Exceptions\TwilioException For unknown resource
*/
public function __get($name) {
$method = 'get' . ucfirst($name);
if (method_exists($this, $method)) {
return $this->$method();
}
throw new TwilioException('Unknown resource ' . $name);
}
/**
* Magic caller to get resource contexts
*
* @param string $name Resource to return
* @param array $arguments Context parameters
* @return \Twilio\InstanceContext The requested resource context
* @throws \Twilio\Exceptions\TwilioException For unknown resource
*/
public function __call($name, $arguments) {
$property = $this->$name;
if (method_exists($property, 'getContext')) {
return <API key>(array($property, 'getContext'), $arguments);
}
throw new TwilioException('Resource does not have a context');
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString() {
return '[Twilio.Preview.HostedNumbers]';
}
} |
<?php
/* pluginbuddy_ui class
*
* Handles typical user interface items used in WordPress development.
*
* @author Dustin Bolton
* @version 1.0.0
*/
class pb_backupbuddy_ui {
private $_tab_interface_tag = '';
/* pluginbuddy_ui->start_metabox()
*
* Starts a metabox. Use with end_metabox().
* @see pluginbuddy_ui->end_metabox
*
* @param string $title Title to display for the metabox.
* @param boolean $echo Echos if true; else returns.
* @param boolean/string $small_or_css true: size is limited smaller. false: size is limited larger. If a string then interpreted as CSS.
* @return null/string Returns null if $echo is true; else returns string with HTML.
*/
public function start_metabox( $title, $echo = true, $small_or_css = false ) {
if ( $small_or_css === false ) { // Large size.
$css = 'width: 70%; min-width: 720px;';
} elseif ( $small_or_css === true ) { // Small size.
$css = 'width: 20%; min-width: 250px;';
} else { // String so interpret as CSS.
$css = $small_or_css;
}
$css .= ' padding-top: 0; margin-top: 10px; cursor: auto;';
$response = '<div class="metabox-holder postbox" style="' . $css . '">
<h3 class="hndle" style="cursor: auto;"><span>' . $title . '</span></h3>
<div class="inside">';
if ( $echo === true ) {
echo $response;
} else {
return $response;
}
} // End start_metabox().
/* pluginbuddy_ui->end_metabox()
*
* Ends a metabox. Use with start_metabox().
* @see pluginbuddy_ui->start_metabox
*
* @param boolean $echo Echos if true; else returns.
* @return null/string Returns null if $echo is true; else returns string with HTML.
*/
public function end_metabox( $echo = true ) {
$response = ' </div>
</div>';
if ( $echo === true ) {
echo $response;
} else {
return $response;
}
} // End end_metabox().
/* pluginbuddy_ui->title()
*
* Displays a styled, properly formatted title for pages.
*
* @param string $title Title to display.
* @param boolean $echo Whether or not to echo the string or return.
* @return null/string Returns null if $echo is true; else returns string with HTML.
*/
public function title( $title, $echo = true ) {
$return = '<h2><img src="' . pb_backupbuddy::plugin_url() . '/images/icon_32x32.png" style="vertical-align: -7px;"> ' . $title . '</h2><br />';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End title().
/* pluginbuddy_ui->button()
*
* Displays a nice pretty styled button. How nice. Always returns.
*
* @param string $url URL (href) for the button to link to.
* @param string $text Text to display in the button.
* @param string $title Optional title text to display on hover in the title tag.
* @param boolean $primary (optional) Whether or not this is a primary button. Primary buttons are blue and strong where default non-primary is grey and gentle.
* @param string $additional_class (optional) Additional CSS class to apply to button. Useful for thickbox or other JS stuff.
* @param string $id (optional) HTML ID to apply. Useful for JS.
* @return string HTML string for the button.
*/
public function button( $url, $text, $title = '', $primary = false, $additional_class = '', $id = '' ) {
if ( $primary === false ) {
return '<a class="button secondary-button ' . $additional_class . '" style="margin-top: 3px;" id="' . $id . '" title="' . $title . '" href="' . $url . '">' . $text . '</a>';
} else {
return '<a class="button button-primary ' . $additional_class . '" style="margin-top: 3px;" id="' . $id . '" title="' . $title . '" href="' . $url . '">' . $text . '</a>';
}
} // End button().
/* pluginbuddy_ui->note()
*
* Display text in a subtle way.
*
* @param string $text Text of note.
* @param boolean $echo Whether or not to echo the string or return.
* @return null/string Returns null if $echo is true; else returns string with HTML.
*/
public static function note( $text, $echo = true ) {
$return = '<span class="description"><i>' . $text . '</i></span>';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End note().
/* pluginbuddy_ui->list_table()
*
* Displays a nice table with multiple columns, rows, bulk actions, hover actions, etc similar to WordPress posts table.
* Currently only supports echo of output.
*
* @param array $items Array of rows to display. Each row array contains an array with the columns. Typically set in controller.
* Ex: array( array( 'blue', 'red' ), array( 'brown', 'green' ) ).
* If the value for an item is an array then the first value will be assigned to the rel tag of any hover actions. If not
* an array then the value itself will be put in the rel tag. If an array the second value will be the one displayed in the column.
* BackupBuddy needed the displayed item in the column to be a link (for downloading backups) but the backup file as the rel.
* @param array $settings Array of all the various settings. Merged with defaults prior to usage. Typically set in view.
* See $default_settings at beginning of function for available settings.
* Ex: $settings = array(
* 'action' => pb_backupbuddy::plugin_url(),
* 'columns' => array( 'Group Name', 'Images', 'Shortcode' ),
* 'hover_actions' => array( 'edit' => 'Edit Group Settings' ), // Slug can be a URL. In this case the value of the hovered row will be appended to the end of the URL. TODO: Make the first hover action be the link for the first listed item.
* 'bulk_actions' => array( 'delete_images' => 'Delete' ),
* );
* @return null
*/
public static function list_table( $items, $settings ) {
$default_settings = array(
'columns' => array(),
'hover_actions' => array(),
'bulk_actions' => array(),
'<API key>' => '', // int of column to set value= in URL and rel tag= for using in JS.
'action' => '',
'reorder' => '',
'after_bulk' => '',
'css' => '',
);
// Merge defaults.
$settings = array_merge( $default_settings, $settings );
// Function to iterate through bulk actions. Top and bottom set are the same.
if ( !function_exists( 'bulk_actions' ) ) {
function bulk_actions( $settings, $hover_note = false ) {
if ( count( $settings['bulk_actions'] ) > 0 ) {
echo '<div style="padding-bottom: 3px; padding-top: 3px;">';
if ( count( $settings['bulk_actions'] ) == 1 ) {
foreach( $settings['bulk_actions'] as $action_slug => $action_title ) {
echo '<input type="hidden" name="bulk_action" value="' . $action_slug . '">';
echo '<input type="submit" name="do_bulk_action" value="' . $action_title . '" class="button secondary-button">';
}
} else {
echo '<select name="bulk_action" class="actions">';
foreach ( $settings['bulk_actions'] as $action_slug => $action_title ) {
echo '<option>Bulk Actions</option>';
echo '<option value="' . $action_slug . '">' . $action_title . '</option>';
}
echo '</select> ';
//echo self::button( '#', 'Apply' );
echo '<input type="submit" name="do_bulk_action" value="Apply" class="button secondary-button">';
}
echo ' ';
echo $settings['after_bulk'];
echo '<div class="alignright actions">';
if ( $hover_note === true ) {
echo pb_backupbuddy::$ui->note( 'Hover over items above for additional options.' );
}
if ( $settings['reorder'] != '' ) {
echo ' <input type="submit" name="save_order" id="save_order" value="Save Order" class="button-secondary" />';
}
echo '</div>';
echo '</div>';
}
} // End subfunction bulk_actions().
} // End if function does not exist.
if ( $settings['action'] != '' ) {
echo '<form method="post" action="' . $settings['action'] . '">';
pb_backupbuddy::nonce();
if ( $settings['reorder'] != '' ) {
echo '<input type="hidden" name="order" value="" id="pb_order">';
}
}
echo '<div style="width: 70%; min-width: 720px; ' . $settings['css'] . '">';
// Display bulk actions (top).
bulk_actions( $settings );
echo '<table class="widefat"';
echo ' id="test">';
echo ' <thead>
<tr class="thead">';
if ( count( $settings['bulk_actions'] ) > 0 ) {
echo' <th scope="col" class="check-column"><input type="checkbox" class="check-all-entries" /></th>';
}
foreach ( $settings['columns'] as $column ) {
echo '<th>' . $column . '</th>';
}
echo ' </tr>
</thead>
<tfoot>
<tr class="thead">';
if ( count( $settings['bulk_actions'] ) > 0 ) {
echo' <th scope="col" class="check-column"><input type="checkbox" class="check-all-entries" /></th>';
}
foreach ( $settings['columns'] as $column ) {
echo '<th>' . $column . '</th>';
}
echo ' </tr>
</tfoot>
<tbody';
if ( $settings['reorder'] != '' ) {
echo ' class="pb_reorder"';
}
echo '>';
// LOOP THROUGH EACH ROW.
foreach ( (array)$items as $item_id => $item ) {
echo ' <tr class="entry-row alternate" id="pb_rowitem-' . $item_id . '">';
if ( count( $settings['bulk_actions'] ) > 0 ) {
echo' <th scope="row" class="check-column"><input type="checkbox" name="items[]" class="entries" value="' . $item_id . '"></th>';
}
echo ' <td>';
if ( is_array( $item['0'] ) ) {
if ( $item['0'][1] == '' ) {
echo ' ';
} else {
echo $item['0'][1];
}
} else {
if ( $item['0'] == '' ) {
echo ' ';
} else {
echo $item['0'];
}
}
echo ' <div class="row-actions">'; // style="margin:0; padding:0;"
$i = 0;
foreach ( $settings['hover_actions'] as $action_slug => $action_title ) { // Display all hover actions.
$i++;
if ( $settings['<API key>'] != '' ) {
if ( is_array( $item[$settings['<API key>']] ) ) {
$<API key> = $item[$settings['<API key>']][0];
} else {
$<API key> = $item[$settings['<API key>']];
}
} else {
$<API key> = '';
}
if ( strstr( $action_slug, 'http' ) === false ) { // Word hover action slug.
$hover_link= pb_backupbuddy::page_url() . '&' . $action_slug . '=' . $item_id . '&value=' . $<API key>;
} else { // URL hover action slug so just append value to URL.
$hover_link = $action_slug . $<API key>;
}
echo '<a href="' . $hover_link . '" class="pb_' . pb_backupbuddy::settings( 'slug' ) . '_hoveraction_' . $action_slug . '" rel="' . $<API key> . '">' . $action_title . '</a>';
if ( $i < count( $settings['hover_actions'] ) ) {
echo ' | ';
}
}
echo ' </div>
</td>';
if ( $settings['reorder'] != '' ) {
$count = count( $item ) + 1; // Extra row for reordering.
} else {
$count = count( $item );
}
// LOOP THROUGH COLUMNS FOR THIS ROW.
for ( $i = 1; $i < $count; $i++ ) {
echo '<td';
if ( $settings['reorder'] != '' ) {
if ( $i == $settings['reorder'] ) {
echo ' class="pb_draghandle" align="center"';
}
}
echo '>';
if ( ( $settings['reorder'] != '' ) && ( $i == ( $settings['reorder'] ) ) ) {
echo '<img src="' . pb_backupbuddy::plugin_url() . '/pluginbuddy/images/draghandle.png" alt="Click and drag to reorder">';
} else {
if ( $item[$i] == '' ) {
echo ' ';
} else {
echo $item[$i];
}
}
echo '</td>';
}
echo ' </tr>';
}
echo ' </tbody>';
echo '</table>';
// Display bulk actions (bottom).
bulk_actions( $settings, true );
echo '</div>';
if ( $settings['action'] != '' ) {
echo '</form>';
}
} // End list_table().
/**
* pb_backupbuddy::get_feed()
*
* Gets an RSS or other feed and inserts it as a list of links...
*
* @param string $feed URL to the feed.
* @param int $limit Number of items to retrieve.
* @param string $append HTML to include in the list. Should usually be <li> items including the <li> code.
* @param string $replace String to replace in every title returned. ie twitter includes your own username at the beginning of each line.
* @return string
*/
public function get_feed( $feed, $limit, $append = '', $replace = '' ) {
$return = '';
$feed_html = get_transient( md5( $feed ) );
if ( false === $feed_html ) {
$feed_html = '';
require_once(ABSPATH.WPINC.'/feed.php');
$rss = fetch_feed( $feed );
if ( is_wp_error( $rss ) ) {
$return .= '{Temporarily unable to load feed.}';
return $return;
}
$maxitems = $rss->get_item_quantity( $limit ); // Limit
$rss_items = $rss->get_items(0, $maxitems);
}
$return .= '<ul class="pluginbuddy-nodecor" style="margin-left: 10px;">';
if ( $feed_html == '' ) {
foreach ( (array) $rss_items as $item ) {
$feed_html .= '<li style="list-style-type: none;"><a href="' . $item->get_permalink() . '" target="_new">';
$title = $item->get_title(); //, ENT_NOQUOTES, 'UTF-8');
if ( $replace != '' ) {
$title = str_replace( $replace, '', $title );
}
if ( strlen( $title ) < 30 ) {
$feed_html .= $title;
} else {
$feed_html .= substr( $title, 0, 32 ) . ' ...';
}
$feed_html .= '</a></li>';
}
set_transient( md5( $feed ), $feed_html, 300 ); // expires in 300secs aka 5min
} else {
//echo 'CACHED';
}
$return .= $feed_html;
$return .= $append;
$return .= '</ul>';
return $return;
} // End get_feed().
/**
* pb_backupbuddy::tip()
*
* Displays a message to the user when they hover over the question mark. Gracefully falls back to normal tooltip.
* HTML is supposed within tooltips.
*
* @param string $message Actual message to show to user.
* @param string $title Title of message to show to user. This is displayed at top of tip in bigger letters. Default is blank. (optional)
* @param boolean $echo_tip Whether to echo the tip (default; true), or return the tip (false). (optional)
* @return string/null If not echoing tip then the string will be returned. When echoing there is no return.
*/
public function tip( $message, $title = '', $echo_tip = true ) {
$tip = ' <a class="pluginbuddy_tip" title="' . $title . ' - ' . $message . '"><img src="' . pb_backupbuddy::plugin_url() . '/pluginbuddy/images/pluginbuddy_tip.png" alt="(?)" /></a>';
if ( $echo_tip === true ) {
echo $tip;
} else {
return $tip;
}
} // End tip().
/**
* pb_backupbuddy::alert()
*
* Displays a message to the user at the top of the page when in the dashboard.
*
* @param string $message Message you want to display to the user.
* @param boolean $error OPTIONAL! true indicates this alert is an error and displays as red. Default: false
* @param int $error_code OPTIONAL! Error code number to use in linking in the wiki for easy reference.
* @return null
*/
public function alert( $message, $error = false, $error_code = '', $rel_tag = '' ) {
$log_error = false;
echo '<div id="message" style="padding: 9px;" rel="' . $rel_tag . '" class="<API key> ';
if ( $error === false ) {
echo 'updated fade';
} else {
echo 'error';
$log_error = true;
}
if ( $error_code != '' ) {
$message .= ' <a href="http://ithemes.com/codex/page/' . pb_backupbuddy::settings( 'name' ) . ':_Error_Codes#' . $error_code . '" target="_new"><i>' . pb_backupbuddy::settings( 'name' ) . ' Error Code ' . $error_code . ' - Click for more details.</i></a>';
$log_error = true;
}
if ( $log_error === true ) {
pb_backupbuddy::log( $message . ' Error Code: ' . $error_code, 'error' );
}
echo '" >' . $message . '</div>';
} // End alert().
/**
* pb_backupbuddy::disalert()
*
* Displays a DISMISSABLE message to the user at the top of the page when in the dashboard.
*
* @param string $message Message you want to display to the user.
* @param boolean $error OPTIONAL! true indicates this alert is an error and displays as red. Default: false
* @param int $error_code OPTIONAL! Error code number to use in linking in the wiki for easy reference.
* @return null
*/
public function disalert( $unique_id, $message, $error = false ) {
if ( ! isset( pb_backupbuddy::$options['disalerts'][$unique_id] ) ) {
$message = '<a style="float: right;" class="<API key>" href="#" title="' . __( 'Dismiss this alert. Unhide dismissed alerts on the Getting Started page.', 'it-l10n-backupbuddy' ) . '" alt="' . pb_backupbuddy::ajax_url( 'disalert' ) . '">' . __( 'Dismiss', 'it-l10n-backupbuddy' ) . '</a><div style="margin-right: 60px;">' . $message . '</div>';
$this->alert( $message, $error, '', $unique_id );
} else {
echo '<!-- Previously Dismissed Alert: `' . htmlentities( $message ) . '` -->';
}
return;
} // End alert().
/**
* pb_backupbuddy::video()
*
* Displays a YouTube video to the user when they hover over the question video mark.
* HTML is supposed within tooltips.
*
* @param string $video_key YouTube video key from the URL ?v=VIDEO_KEY_HERE -- To jump to a certain timestamp add #SECONDS to the end of the key, where SECONDS is the number of seconds into the video to start at. Example to start 65 seconds into a video: 9ZHWGjBr84s#65. This must be in seconds format.
* @param string $title Title of message to show to user. This is displayed at top of tip in bigger letters. Default is blank. (optional)
* @param boolean $echo_tip Whether to echo the tip (default; true), or return the tip (false). (optional)
* @return string/null If not echoing tip then the string will be returned. When echoing there is no return.
*/
public function video( $video_key, $title = '', $echo_tip = true ) {
if ( !defined( 'PB_IMPORTBUDDY' ) ) {
global $wp_scripts;
if ( is_object( $wp_scripts ) ) {
if ( !in_array( 'thickbox', $wp_scripts->done ) ) {
wp_enqueue_script( 'thickbox' );
wp_print_scripts( 'thickbox' );
wp_print_styles( 'thickbox' );
}
}
}
if ( strstr( $video_key, '
$video = explode( '#', $video_key );
$video[1] = '&start=' . $video[1];
} else {
$video[0] = $video_key;
$video[1] = '';
}
$tip = '<a target="_new" href="http:
if ( $echo_tip === true ) {
echo $tip;
} else {
return $tip;
}
} // End video().
/*
public function media_library( $save_point, $<API key> ) {
require_once( pb_backupbuddy::plugin_path() . '/pluginbuddy/lib/media_library/media_library.php' );
$media_library = new <API key>( $save_point, $<API key> );
$media_library->display();
}
*/
/* start_tabs()
*
* Starts a tabbed interface.
* @see end_tabs().
*
* @param string $interface_tag Tag/slug for this entire tabbed interface. Should be unique.
* @param array $tabs Array containing an array of settings for this tabbed interface. Ex: array( array( 'title'> 'my title', 'slug' => 'mytabs' ) );
* Optional setting with key `ajax_url` may define a URL for AJAX loading.
* @param string $css Additional CSS to apply to main outer div. (optional)
* @param boolean $echo Echo output instead of returning. (optional)
* @param int $active_tab_index Tab to start as active/selected.
* @return null/string null if $echo = false, all data otherwise.
*/
public function start_tabs( $interface_tag, $tabs, $css = '', $echo = true, $active_tab_index = 0 ) {
$this->_tab_interface_tag = $interface_tag;
pb_backupbuddy::load_script( 'jquery-ui-tabs' );
$prefix = 'pb_' . pb_backupbuddy::settings( 'slug' ) . '_'; // pb_PLUGINSLUG_
$return = '';
$return .= '<script type="text/javascript">';
$return .= ' jQuery(document).ready(function() {';
$return .= ' jQuery("#' . $prefix . $this->_tab_interface_tag . '_tabs").tabs({ active: ' . $active_tab_index . ' });';
$return .= ' });';
$return .= '</script>';
$return .= '<div id="' . $prefix . $this->_tab_interface_tag . '_tabs" style="' . $css . '">';
$return .= '<ul>';
foreach( $tabs as $tab ) {
if ( ! isset( $tab['css'] ) ) {
$tab['css'] = '';
}
if ( isset( $tab['ajax'] ) && ( $tab['ajax_url'] != '' ) ) { // AJAX tab.
$return .= '<li><a href="' . $tab['ajax_url'] . '"><span>' . $tab['title'] . '</span></a></li>';
} else { // Standard; NO AJAX.
$return .= '<li style="' . $tab['css'] . '"><a href="#' . $prefix . $this->_tab_interface_tag . '_tab_' . $tab['slug'] . '"><span>' . $tab['title'] . '</span></a></li>';
}
}
$return .= '</ul>';
$return .= '<br>';
$return .= '<div class="tabs-borderwrap">';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End start_tabs().
/* end_tabs()
*
* Closes off a tabbed interface.
* @see start_tabs().
*
* @param boolean $echo Echo output instead of returning. (optional)
* @return null/string null if $echo = false, all data otherwise.
*/
public function end_tabs( $echo = true ) {
$return = '';
$return .= ' </div>';
$return .= '</div>';
$this->_tab_interface_tag = '';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End end_tabs().
/* start_tab()
*
* Opens the start of an individual page to be loaded by a tab.
* @see end_tab().
*
* @param string $tab_tag Unique tag for this tab section. Must match the tag defined when creating the tab interface.
* @param boolean $echo Echo output instead of returning. (optional)
* @return null/string null if $echo = false, all data otherwise.
*/
public function start_tab( $tab_tag, $echo = true ) {
$prefix = 'pb_' . pb_backupbuddy::settings( 'slug' ) . '_'; // pb_PLUGINSLUG_
$return = '';
$return .= '<div id="' . $prefix . $this->_tab_interface_tag . '_tab_' . $tab_tag . '">';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End start_tab().
/* end_tab()
*
* Closes this tab section.
* @see start_tab().
*
* @param string $tab_tag Unique tag for this tab section. Must match the tag defined when creating the tab interface.
* @param boolean $echo Echo output instead of returning. (optional)
* @return null/string null if $echo = false, all data otherwise.
*/
public function end_tab( $echo = true ) {
$return = '</div>';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End end_tab().
/* ajax_header()
*
* Output HTML headers when using AJAX.
*
* @param boolean $js Whether or not to load javascript. Default false.
* @param bool $padding Whether or not to padd wrapper div. Default has padding.
* @return
*/
function ajax_header( $js = true, $padding = true ) {
echo '<head>';
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
echo '<title>PluginBuddy</title>';
wp_print_styles( 'global' );
wp_print_styles( 'wp-admin' );
wp_print_styles( 'colors-fresh' );
wp_print_styles( 'colors-fresh' );
if ( $js === true ) {
wp_enqueue_script( 'jquery' );
wp_print_scripts( 'jquery' );
}
//echo '<link rel="stylesheet" href="' . pb_backupbuddy::plugin_url(); . '/css/admin.css" type="text/css" media="all" />';
pb_backupbuddy::load_script( 'admin.js', true );
pb_backupbuddy::load_style( 'admin.css', true );
pb_backupbuddy::load_script( 'tooltip.js', true );
echo '<body class="wp-core-ui">';
if ( $padding === true ) {
echo '<div style="padding: 8px; padding-left: 12px; padding-right: 12px;">';
} else {
echo '<div>';
}
} // End ajax_header().
function ajax_footer() {
echo '</body>';
echo '</div>';
echo '</head>';
echo '</html>';
} // End ajax_footer().
} // End class pluginbuddy_ui.
?> |
#ifndef _MACH_GPIO_H_
#define _MACH_GPIO_H_
#define MAX_BLACKFIN_GPIOS 48
#define GPIO_PF0 0
#define GPIO_PF1 1
#define GPIO_PF2 2
#define GPIO_PF3 3
#define GPIO_PF4 4
#define GPIO_PF5 5
#define GPIO_PF6 6
#define GPIO_PF7 7
#define GPIO_PF8 8
#define GPIO_PF9 9
#define GPIO_PF10 10
#define GPIO_PF11 11
#define GPIO_PF12 12
#define GPIO_PF13 13
#define GPIO_PF14 14
#define GPIO_PF15 15
#define GPIO_PF16 16
#define GPIO_PF17 17
#define GPIO_PF18 18
#define GPIO_PF19 19
#define GPIO_PF20 20
#define GPIO_PF21 21
#define GPIO_PF22 22
#define GPIO_PF23 23
#define GPIO_PF24 24
#define GPIO_PF25 25
#define GPIO_PF26 26
#define GPIO_PF27 27
#define GPIO_PF28 28
#define GPIO_PF29 29
#define GPIO_PF30 30
#define GPIO_PF31 31
#define GPIO_PF32 32
#define GPIO_PF33 33
#define GPIO_PF34 34
#define GPIO_PF35 35
#define GPIO_PF36 36
#define GPIO_PF37 37
#define GPIO_PF38 38
#define GPIO_PF39 39
#define GPIO_PF40 40
#define GPIO_PF41 41
#define GPIO_PF42 42
#define GPIO_PF43 43
#define GPIO_PF44 44
#define GPIO_PF45 45
#define GPIO_PF46 46
#define GPIO_PF47 47
#define PORT_FIO0 GPIO_PF0
#define PORT_FIO1 GPIO_PF16
#define PORT_FIO2 GPIO_PF32
#include <mach-common/ports-f.h>
#endif |
#ifndef DSDEFS_H
#define DSDEFS_H
#if !defined(RTLAB) && !defined(LABCAR) && !defined(DYM2DS) && !defined(<API key>)
#if defined(NO_FILE) || ( defined(DYMOLA_DSPACE) && !defined(__STDIO_H) )
#define FILE int
#define fpos_t unsigned int
#if defined(DYMOLA_DSPACE)
#define __STDIO_H
#endif
#endif
#if defined(DYMOLA_DSPACE)
static int printf(const char* format, ...)
{ return 0; }
static int sprintf(char* s, const char* format, ...)
{ s[0] = '\0'; return 0; }
#endif
#endif
#if !defined(assert) && !defined(DYM2DS) && !defined(<API key>)
#define assert(test) (void)0
#endif
#endif |
""" Encoding Aliases Support
This module is used by the encodings package search function to
map encodings names to module names.
Note that the search function converts the encoding names to lower
case and replaces hyphens with underscores *before* performing the
lookup.
"""
aliases = {
# Latin-1
'latin': 'latin_1',
'latin1': 'latin_1',
# UTF-7
'utf7': 'utf_7',
'u7': 'utf_7',
# UTF-8
'utf': 'utf_8',
'utf8': 'utf_8',
'u8': 'utf_8',
'utf8@ucs2': 'utf_8',
'utf8@ucs4': 'utf_8',
# UTF-16
'utf16': 'utf_16',
'u16': 'utf_16',
'utf_16be': 'utf_16_be',
'utf_16le': 'utf_16_le',
'unicodebigunmarked': 'utf_16_be',
'<API key>': 'utf_16_le',
# ASCII
'us_ascii': 'ascii',
'ansi_x3.4_1968': 'ascii', # used on Linux
'ansi_x3_4_1968': 'ascii', # used on BSD?
'646': 'ascii', # used on Solaris
# EBCDIC
'ebcdic_cp_us': 'cp037',
'ibm039': 'cp037',
'ibm1140': 'cp1140',
# ISO
'8859': 'latin_1',
'iso8859': 'latin_1',
'iso8859_1': 'latin_1',
'iso_8859_1': 'latin_1',
'iso_8859_10': 'iso8859_10',
'iso_8859_13': 'iso8859_13',
'iso_8859_14': 'iso8859_14',
'iso_8859_15': 'iso8859_15',
'iso_8859_2': 'iso8859_2',
'iso_8859_3': 'iso8859_3',
'iso_8859_4': 'iso8859_4',
'iso_8859_5': 'iso8859_5',
'iso_8859_6': 'iso8859_6',
'iso_8859_7': 'iso8859_7',
'iso_8859_8': 'iso8859_8',
'iso_8859_9': 'iso8859_9',
# Mac
'maclatin2': 'mac_latin2',
'maccentraleurope': 'mac_latin2',
'maccyrillic': 'mac_cyrillic',
'macgreek': 'mac_greek',
'maciceland': 'mac_iceland',
'macroman': 'mac_roman',
'macturkish': 'mac_turkish',
# Windows
'windows_1251': 'cp1251',
'windows_1252': 'cp1252',
'windows_1254': 'cp1254',
'windows_1255': 'cp1255',
'windows_1256': 'cp1256',
'windows_1257': 'cp1257',
'windows_1258': 'cp1258',
# MBCS
'dbcs': 'mbcs',
# Code pages
'437': 'cp437',
# CJK
# The codecs for these encodings are not distributed with the
# Python core, but are included here for reference, since the
# locale module relies on having these aliases available.
'jis_7': 'jis_7',
'iso_2022_jp': 'jis_7',
'ujis': 'euc_jp',
'ajec': 'euc_jp',
'eucjp': 'euc_jp',
'tis260': 'tactis',
'sjis': 'shift_jis',
# Content transfer/compression encodings
'rot13': 'rot_13',
'base64': 'base64_codec',
'base_64': 'base64_codec',
'zlib': 'zlib_codec',
'zip': 'zlib_codec',
'hex': 'hex_codec',
'uu': 'uu_codec',
'quopri': 'quopri_codec',
'quotedprintable': 'quopri_codec',
'quoted_printable': 'quopri_codec',
} |
<?php
require_once "$CFG->dirroot/lib/formslib.php";
require_once "$CFG->dirroot/mod/facetoface/lib.php";
class <API key> extends moodleform {
function definition()
{
$mform =& $this->_form;
$mform->addElement('header', 'general', get_string('general', 'form'));
$mform->addElement('hidden', 'id', $this->_customdata['id']);
$mform->addElement('text', 'name', get_string('name'), 'maxlength="255" size="50"');
$mform->addRule('name', null, 'required', null, 'client');
$mform->setType('name', PARAM_MULTILANG);
$mform->addElement('htmleditor', 'text', get_string('noticetext', 'facetoface'), array('rows' => 10, 'cols' => 64));
$mform->setType('text', PARAM_RAW);
$mform->addRule('text', null, 'required', null, 'client');
$mform->addElement('header', 'conditions', get_string('conditions', 'facetoface'));
$mform->addElement('html', get_string('<API key>', 'facetoface'));
// Show all custom fields
$customfields = $this->_customdata['customfields'];
<API key>($mform, $customfields, true);
$this->add_action_buttons();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Xml;
using OfficeOpenXml.<API key>.Contracts;
namespace OfficeOpenXml.<API key>
{
<summary>
<API key>
</summary>
public class <API key>
: <API key>,
<API key>
{
#region Constructors
<summary>
</summary>
<param name="priority"></param>
<param name="address"></param>
<param name="worksheet"></param>
<param name="itemElementNode"></param>
<param name="namespaceManager"></param>
internal <API key>(
ExcelAddress address,
int priority,
ExcelWorksheet worksheet,
XmlNode itemElementNode,
XmlNamespaceManager namespaceManager)
: base(
<API key>.Top,
address,
priority,
worksheet,
itemElementNode,
(namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager)
{
if (itemElementNode==null) //Set default values and create attributes if needed
{
Bottom = false;
Percent = false;
Rank = 10; // First 10 values
}
}
<summary>
</summary>
<param name="priority"></param>
<param name="address"></param>
<param name="worksheet"></param>
<param name="itemElementNode"></param>
internal <API key>(
ExcelAddress address,
int priority,
ExcelWorksheet worksheet,
XmlNode itemElementNode)
: this(
address,
priority,
worksheet,
itemElementNode,
null)
{
}
<summary>
</summary>
<param name="priority"></param>
<param name="address"></param>
<param name="worksheet"></param>
internal <API key>(
ExcelAddress address,
int priority,
ExcelWorksheet worksheet)
: this(
address,
priority,
worksheet,
null,
null)
{
}
#endregion Constructors
}
} |
<?php
// File name : example_052.php
// Begin : 2009-05-07
// Last Update : 2009-09-30
// Description : Example 052 for TCPDF class
// Certification Signature (experimental)
// Nicola Asuni
// Tecnick.com s.r.l.
// Via Della Pace, 11
// 09044 Quartucciu (CA)
// ITALY
// info@tecnick.com
require_once('../config/lang/eng.php');
require_once('../tcpdf.php');
// create new PDF document
$pdf = new TCPDF(<API key>, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 052');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, <API key>, PDF_HEADER_TITLE, PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf-><API key>(PDF_FONT_MONOSPACED);
//set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
//set image scale factor
$pdf->setImageScale(<API key>);
//set some language-dependent strings
$pdf->setLanguageArray($l);
// set certificate file
$certificate = 'file://../tcpdf.crt';
// set additional information
$info = array(
'Name' => 'TCPDF',
'Location' => 'Office',
'Reason' => 'Testing TCPDF',
'ContactInfo' => 'http:
);
// set document signature
$pdf->setSignature($certificate, $certificate, 'tcpdfdemo', '', 2, $info);
// set font
$pdf->SetFont('helvetica', '', 10);
// add a page
$pdf->AddPage();
// print a line of text
$text = 'This is a <b color="
$pdf->writeHTML($text, true, 0, true, 0);
//Close and output PDF document
$pdf->Output('example_052.pdf', 'I');
// END OF FILE
?> |
// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -<API key> -verify=allow-signed -DSKIP_ERROR_TESTS %s
// <API key>
wchar_t x;
void f(wchar_t p) {
wchar_t x;
unsigned wchar_t y; // expected-error {{'wchar_t' cannot be signed or unsigned}}
signed wchar_t z; // expected-error {{'wchar_t' cannot be signed or unsigned}}
++x;
}
// PR4502
wchar_t const c = L'c';
int a[c == L'c' ? 1 : -1];
// PR5917
template<typename _CharT>
struct basic_string {
};
template<typename _CharT>
basic_string<_CharT> operator+ (const basic_string<_CharT>&, _CharT);
int t(void) {
basic_string<wchar_t>() + L'-';
return (0);
}
// rdar://8040728
wchar_t in[] = L"\x434" "\x434"; // No warning
#ifndef SKIP_ERROR_TESTS
// Verify that we do not crash when assigning wchar_t* to another pointer type.
void assignment(wchar_t *x) {
char *y;
y = x; // expected-error {{incompatible pointer types assigning to 'char *' from 'wchar_t *'}}
}
#endif |
var Deferred = require('./')
var assert = require('assert')
var d = new Deferred()
var t = require('tap')
t.match(d, {
resolve: Function,
reject: Function,
promise: Object
}) |
<?php
defined( 'ABSPATH' ) || exit;
?>
<li>
<?php do_action( '<API key>', $args ); ?>
<a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
<?php echo $product->get_image(); ?>
<span class="product-title"><?php echo $product->get_name(); ?></span>
</a>
<?php echo wc_get_rating_html( intval( get_comment_meta( $comment->comment_ID, 'rating', true ) ) ); ?>
<span class="reviewer"><?php echo sprintf( esc_html__( 'by %s', 'woocommerce' ), get_comment_author( $comment->comment_ID ) ); ?></span>
<?php do_action( '<API key>', $args ); ?>
</li> |
package com.aptana.core.internal.resources;
import org.eclipse.osgi.util.NLS;
/**
*
* @author Ingo Muschenetz
*
*/
public final class Messages extends NLS
{
private static final String BUNDLE_NAME = "com.aptana.core.internal.resources.messages"; //$NON-NLS-1$
private Messages()
{
}
static
{
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
/**
* <API key>
*/
public static String <API key>;
/**
* <API key>
*/
public static String <API key>;
} |
#include <r_util.h>
#include <r_types.h>
ut32 get_msb(ut32 v) {
int i;
for (i = 31; i > (-1); i
if (v & (0x1 << i)) {
return (v & (0x1 << i));
}
}
return 0;
}
R_API RIDPool* r_id_pool_new(ut32 start_id, ut32 last_id) {
RIDPool* pool = NULL;
if (start_id < last_id) {
pool = R_NEW0 (RIDPool);
if (!pool) {
return NULL;
}
pool->next_id = pool->start_id = start_id;
pool->last_id = last_id;
}
return pool;
}
R_API bool r_id_pool_grab_id(RIDPool* pool, ut32* grabber) {
if (!pool || !grabber) {
return false;
}
if (pool->freed_ids) {
ut32 grab = (ut32) (size_t)r_queue_dequeue (pool->freed_ids);
*grabber = (ut32) grab;
if (r_queue_is_empty (pool->freed_ids)) {
r_queue_free (pool->freed_ids);
pool->freed_ids = NULL;
}
return true;
}
if (pool->next_id < pool->last_id) {
*grabber = pool->next_id;
pool->next_id++;
return true;
}
return false;
}
R_API bool r_id_pool_kick_id(RIDPool* pool, ut32 kick) {
if (!pool || (kick < pool->start_id) || (pool->start_id == pool->next_id)) {
return false;
}
if (kick == (pool->next_id - 1)) {
pool->next_id
return true;
}
if (!pool->freed_ids) {
pool->freed_ids = r_queue_new (2);
}
r_queue_enqueue (pool->freed_ids, (void*) (size_t) kick);
return true;
}
R_API void r_id_pool_free(RIDPool* pool) {
if (pool && pool->freed_ids) {
r_queue_free (pool->freed_ids);
}
free (pool);
}
R_API RIDStorage* r_id_storage_new(ut32 start_id, ut32 last_id) {
RIDPool* pool;
RIDStorage* storage = NULL;
if ((start_id < 16) && (pool = r_id_pool_new (start_id, last_id))) {
storage = R_NEW0 (RIDStorage);
if (!storage) {
return NULL;
}
storage->pool = pool;
}
return storage;
}
static bool <API key>(RIDStorage* storage, ut32 size) {
void* data;
if (!storage) {
return false;
}
if (storage->size == size) {
return true;
}
if (storage->size > size) {
storage->data = realloc (storage->data, size * sizeof(void*));
storage->size = size;
return true;
}
data = storage->data;
storage->data = R_NEWS0 (void*, size);
if (data) {
memcpy (storage->data, data, storage->size * sizeof(void*));
}
storage->size = size;
return true;
}
R_API bool r_id_storage_set(RIDStorage* storage, void* data, ut32 id) {
ut32 n;
if (!storage || !storage->pool || (id >= storage->pool->next_id)) {
return false;
}
n = get_msb (id + 1);
if (n > (storage->size - (storage->size / 4))) {
if (n < (storage->pool->last_id / 2)) {
if (!<API key> (storage, n * 2)) {
return false;
}
} else if (n != (storage->pool->last_id)) {
if (!<API key> (storage, storage->pool->last_id)) {
return false;
}
}
}
storage->data[id] = data;
if (id > storage->top_id) {
storage->top_id = id;
}
return true;
}
R_API bool r_id_storage_add(RIDStorage* storage, void* data, ut32* id) {
if (!storage || !r_id_pool_grab_id (storage->pool, id)) {
return false;
}
return r_id_storage_set (storage, data, *id);
}
R_API void* r_id_storage_get(RIDStorage* storage, ut32 id) {
if (!storage || !storage->data || (storage->size <= id)) {
return NULL;
}
return storage->data[id];
}
R_API void r_id_storage_delete(RIDStorage* storage, ut32 id) {
if (!storage || !storage->data || (storage->size <= id)) {
return;
}
storage->data[id] = NULL;
if (id == storage->top_id) {
while (storage->top_id && !storage->data[storage->top_id]) {
storage->top_id
}
if (!storage->top_id) {
if(storage->data[storage->top_id]) {
<API key> (storage, 2);
} else {
RIDPool* pool = r_id_pool_new (storage->pool->start_id, storage->pool->last_id);
R_FREE (storage->data);
storage->size = 0;
r_id_pool_free (storage->pool);
storage->pool = pool;
return;
}
} else if ((storage->top_id + 1) < (storage->size / 4)) {
<API key> (storage, storage->size / 2);
}
}
r_id_pool_kick_id (storage->pool, id);
}
R_API void* r_id_storage_take(RIDStorage* storage, ut32 id) {
void* ret = r_id_storage_get (storage, id);
r_id_storage_delete (storage, id);
return ret;
}
R_API bool <API key>(RIDStorage* storage, RIDStorageForeachCb cb, void* user) {
ut32 i;
if (!cb || !storage || !storage->data) {
return false;
}
for (i = 0; i < storage->top_id; i++) {
if (storage->data[i]) {
if (!cb (user, storage->data[i], i)) {
return false;
}
}
}
if (storage->data[i]) {
return cb (user, storage->data[i], i);
}
return true;
}
R_API void r_id_storage_free(RIDStorage* storage) {
if (storage) {
r_id_pool_free (storage->pool);
free (storage->data);
}
free (storage);
} |
package com.shatteredpixel.<API key>.scenes;
import com.shatteredpixel.<API key>.Assets;
import com.shatteredpixel.<API key>.Dungeon;
import com.shatteredpixel.<API key>.Statistics;
import com.shatteredpixel.<API key>.actors.Actor;
import com.shatteredpixel.<API key>.items.Generator;
import com.shatteredpixel.<API key>.levels.Level;
import com.shatteredpixel.<API key>.windows.WndError;
import com.shatteredpixel.<API key>.windows.WndStory;
import com.watabou.noosa.BitmapText;
import com.watabou.noosa.Camera;
import com.watabou.noosa.Game;
import com.watabou.noosa.audio.Music;
import com.watabou.noosa.audio.Sample;
import java.io.<API key>;
import java.io.IOException;
public class InterlevelScene extends PixelScene {
private static final float TIME_TO_FADE = 0.3f;
private static final String TXT_DESCENDING = "Descending...";
private static final String TXT_ASCENDING = "Ascending...";
private static final String TXT_LOADING = "Loading...";
private static final String TXT_RESURRECTING= "Resurrecting...";
private static final String TXT_RETURNING = "Returning...";
private static final String TXT_FALLING = "Falling...";
private static final String ERR_FILE_NOT_FOUND = "Save file not found. If this error persists after restarting, " +
"it may mean this save game is corrupted. Sorry about that.";
private static final String ERR_IO = "Cannot read save file. If this error persists after restarting, " +
"it may mean this save game is corrupted. Sorry about that.";
public static enum Mode {
DESCEND, ASCEND, CONTINUE, RESURRECT, RETURN, FALL
};
public static Mode mode;
public static int returnDepth;
public static int returnPos;
public static boolean noStory = false;
public static boolean fallIntoPit;
private enum Phase {
FADE_IN, STATIC, FADE_OUT
};
private Phase phase;
private float timeLeft;
private BitmapText message;
private Thread thread;
private Exception error = null;
@Override
public void create() {
super.create();
String text = "";
switch (mode) {
case DESCEND:
text = TXT_DESCENDING;
break;
case ASCEND:
text = TXT_ASCENDING;
break;
case CONTINUE:
text = TXT_LOADING;
break;
case RESURRECT:
text = TXT_RESURRECTING;
break;
case RETURN:
text = TXT_RETURNING;
break;
case FALL:
text = TXT_FALLING;
break;
}
message = PixelScene.createText( text, 9 );
message.measure();
message.x = (Camera.main.width - message.width()) / 2;
message.y = (Camera.main.height - message.height()) / 2;
add( message );
phase = Phase.FADE_IN;
timeLeft = TIME_TO_FADE;
thread = new Thread() {
@Override
public void run() {
try {
Generator.reset();
switch (mode) {
case DESCEND:
descend();
break;
case ASCEND:
ascend();
break;
case CONTINUE:
restore();
break;
case RESURRECT:
resurrect();
break;
case RETURN:
returnTo();
break;
case FALL:
fall();
break;
}
if ((Dungeon.depth % 5) == 0) {
Sample.INSTANCE.load( Assets.SND_BOSS );
}
} catch (Exception e) {
error = e;
}
if (phase == Phase.STATIC && error == null) {
phase = Phase.FADE_OUT;
timeLeft = TIME_TO_FADE;
}
}
};
thread.start();
}
@Override
public void update() {
super.update();
float p = timeLeft / TIME_TO_FADE;
switch (phase) {
case FADE_IN:
message.alpha( 1 - p );
if ((timeLeft -= Game.elapsed) <= 0) {
if (!thread.isAlive() && error == null) {
phase = Phase.FADE_OUT;
timeLeft = TIME_TO_FADE;
} else {
phase = Phase.STATIC;
}
}
break;
case FADE_OUT:
message.alpha( p );
if (mode == Mode.CONTINUE || (mode == Mode.DESCEND && Dungeon.depth == 1)) {
Music.INSTANCE.volume( p );
}
if ((timeLeft -= Game.elapsed) <= 0) {
Game.switchScene( GameScene.class );
}
break;
case STATIC:
if (error != null) {
String errorMsg;
if (error instanceof <API key>) errorMsg = ERR_FILE_NOT_FOUND;
else if (error instanceof IOException) errorMsg = ERR_IO;
else throw new RuntimeException("fatal error occured while moving between floors", error);
add( new WndError( errorMsg ) {
public void onBackPressed() {
super.onBackPressed();
Game.switchScene( StartScene.class );
};
} );
error = null;
}
break;
}
}
private void descend() throws IOException {
Actor.fixTime();
if (Dungeon.hero == null) {
Dungeon.init();
if (noStory) {
Dungeon.chapters.add( WndStory.ID_SEWERS );
noStory = false;
}
} else {
Dungeon.saveLevel();
}
Level level;
if (Dungeon.depth >= Statistics.deepestFloor) {
level = Dungeon.newLevel();
} else {
Dungeon.depth++;
level = Dungeon.loadLevel( Dungeon.hero.heroClass );
}
Dungeon.switchLevel( level, level.entrance );
}
private void fall() throws IOException {
Actor.fixTime();
Dungeon.saveLevel();
Level level;
if (Dungeon.depth >= Statistics.deepestFloor) {
level = Dungeon.newLevel();
} else {
Dungeon.depth++;
level = Dungeon.loadLevel( Dungeon.hero.heroClass );
}
Dungeon.switchLevel( level, fallIntoPit ? level.pitCell() : level.randomRespawnCell() );
}
private void ascend() throws IOException {
Actor.fixTime();
Dungeon.saveLevel();
Dungeon.depth
Level level = Dungeon.loadLevel( Dungeon.hero.heroClass );
Dungeon.switchLevel( level, level.exit );
}
private void returnTo() throws IOException {
Actor.fixTime();
Dungeon.saveLevel();
Dungeon.depth = returnDepth;
Level level = Dungeon.loadLevel( Dungeon.hero.heroClass );
Dungeon.switchLevel( level, Level.resizingNeeded ? level.adjustPos( returnPos ) : returnPos );
}
private void restore() throws IOException {
Actor.fixTime();
Dungeon.loadGame( StartScene.curClass );
if (Dungeon.depth == -1) {
Dungeon.depth = Statistics.deepestFloor;
Dungeon.switchLevel( Dungeon.loadLevel( StartScene.curClass ), -1 );
} else {
Level level = Dungeon.loadLevel( StartScene.curClass );
Dungeon.switchLevel( level, Level.resizingNeeded ? level.adjustPos( Dungeon.hero.pos ) : Dungeon.hero.pos );
}
}
private void resurrect() throws IOException {
Actor.fixTime();
if (Dungeon.level.locked) {
Dungeon.hero.resurrect( Dungeon.depth );
Dungeon.depth
Level level = Dungeon.newLevel();
Dungeon.switchLevel( level, level.entrance );
} else {
Dungeon.hero.resurrect( -1 );
Dungeon.resetLevel();
}
}
@Override
protected void onBackPressed() {
//Do nothing
}
} |
-- predictability
SET synchronous_commit = on;
DROP TABLE IF EXISTS replication_example;
SELECT 'init' FROM <API key>('regression_slot', 'test_decoding');
CREATE TABLE replication_example(id SERIAL PRIMARY KEY, somedata int, text varchar(120));
INSERT INTO replication_example(somedata) VALUES (1);
SELECT data FROM <API key>('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
BEGIN;
INSERT INTO replication_example(somedata) VALUES (2);
ALTER TABLE replication_example ADD COLUMN testcolumn1 int;
INSERT INTO replication_example(somedata, testcolumn1) VALUES (3, 1);
COMMIT;
BEGIN;
INSERT INTO replication_example(somedata) VALUES (3);
ALTER TABLE replication_example ADD COLUMN testcolumn2 int;
INSERT INTO replication_example(somedata, testcolumn1, testcolumn2) VALUES (4, 2, 1);
COMMIT;
VACUUM FULL pg_am;
VACUUM FULL pg_amop;
VACUUM FULL pg_proc;
VACUUM FULL pg_opclass;
VACUUM FULL pg_type;
VACUUM FULL pg_index;
VACUUM FULL pg_database;
-- repeated rewrites that fail
BEGIN;
CLUSTER pg_class USING pg_class_oid_index;
CLUSTER pg_class USING pg_class_oid_index;
ROLLBACK;
-- repeated rewrites that succeed
BEGIN;
CLUSTER pg_class USING pg_class_oid_index;
CLUSTER pg_class USING pg_class_oid_index;
CLUSTER pg_class USING pg_class_oid_index;
COMMIT;
-- repeated rewrites in different transactions
VACUUM FULL pg_class;
VACUUM FULL pg_class;
INSERT INTO replication_example(somedata, testcolumn1) VALUES (5, 3);
BEGIN;
INSERT INTO replication_example(somedata, testcolumn1) VALUES (6, 4);
ALTER TABLE replication_example ADD COLUMN testcolumn3 int;
INSERT INTO replication_example(somedata, testcolumn1, testcolumn3) VALUES (7, 5, 1);
COMMIT;
-- make old files go away
CHECKPOINT;
SELECT data FROM <API key>('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
SELECT <API key>('regression_slot');
DROP TABLE IF EXISTS replication_example; |
# file at the top-level directory of this distribution.
# option. This file may not be copied, modified, or distributed
# except according to those terms.
from __future__ import absolute_import, print_function, unicode_literals
import base64
import json
import os
import os.path as path
import re
import shutil
import sys
import urllib2
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
import servo.bootstrap as bootstrap
from servo.command_base import CommandBase, BIN_SUFFIX
from servo.util import download_bytes, download_file, extract, host_triple
@CommandProvider
class MachCommands(CommandBase):
@Command('env',
description='Print environment setup commands',
category='bootstrap')
def env(self):
env = self.build_env()
print("export PATH=%s" % env["PATH"])
if sys.platform == "darwin":
print("export DYLD_LIBRARY_PATH=%s" % env["DYLD_LIBRARY_PATH"])
else:
print("export LD_LIBRARY_PATH=%s" % env["LD_LIBRARY_PATH"])
@Command('bootstrap',
description='Install required packages for building.',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Boostrap without confirmation')
def bootstrap(self, force=False):
return bootstrap.bootstrap(self.context, force=force)
@Command('bootstrap-rust',
description='Download the Rust compiler',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Force download even if a copy already exists')
@CommandArgument('--target',
action='append',
default=[],
help='Download rust stdlib for specified target')
@CommandArgument('--stable',
action='store_true',
help='Use stable rustc version')
def bootstrap_rustc(self, force=False, target=[], stable=False):
self.set_use_stable_rust(stable)
version = self.rust_version()
rust_path = self.rust_path()
rust_dir = path.join(self.context.sharedir, "rust", rust_path)
install_dir = path.join(self.context.sharedir, "rust", version)
if not self.config["build"]["llvm-assertions"]:
install_dir += "-alt"
if not force and path.exists(path.join(rust_dir, "rustc", "bin", "rustc" + BIN_SUFFIX)):
print("Rust compiler already downloaded.", end=" ")
print("Use |bootstrap-rust --force| to download again.")
else:
if path.isdir(rust_dir):
shutil.rmtree(rust_dir)
os.makedirs(rust_dir)
# The nightly Rust compiler is hosted on the nightly server under the date with a name
# <API key>.tar.gz, whereas the stable compiler is named
# <API key>.tar.gz. We just need to pull down and extract it,
# giving a directory name that will be the same as the tarball name (rustc is
# in that directory).
if stable:
tarball = "rustc-%s-%s.tar.gz" % (version, host_triple())
rustc_url = "https://<API key>.s3.amazonaws.com/dist/" + tarball
else:
tarball = "%s/rustc-nightly-%s.tar.gz" % (version, host_triple())
base_url = "https://s3.amazonaws.com/rust-lang-ci/rustc-builds"
if not self.config["build"]["llvm-assertions"]:
base_url += "-alt"
rustc_url = base_url + "/" + tarball
tgz_file = rust_dir + '-rustc.tar.gz'
download_file("Rust compiler", rustc_url, tgz_file)
print("Extracting Rust compiler...")
extract(tgz_file, install_dir)
print("Rust compiler ready.")
# Each Rust stdlib has a name of the form `<API key>.tar.gz` for the nightly
# releases, or <API key>.tar.gz for stable releases, with
# a directory of the name `rust-std-TRIPLE` inside and then a `lib` directory.
# This `lib` directory needs to be extracted and merged with the `rustc/lib`
# directory from the host compiler above.
nightly_suffix = "" if stable else "-nightly"
stable_version = "-{}".format(version) if stable else ""
lib_dir = path.join(install_dir,
"rustc{}{}-{}".format(nightly_suffix, stable_version, host_triple()),
"rustc", "lib", "rustlib")
# ensure that the libs for the host's target is downloaded
host_target = host_triple()
if host_target not in target:
target.append(host_target)
for target_triple in target:
target_lib_dir = path.join(lib_dir, target_triple)
if path.exists(target_lib_dir):
# No need to check for force. If --force the directory is already deleted
print("Rust lib for target {} already downloaded.".format(target_triple), end=" ")
print("Use |bootstrap-rust --force| to download again.")
continue
if self.use_stable_rust():
std_url = ("https://<API key>.s3.amazonaws.com/dist/rust-std-%s-%s.tar.gz"
% (version, target_triple))
tgz_file = install_dir + ('rust-std-%s-%s.tar.gz' % (version, target_triple))
else:
std_url = ("https://s3.amazonaws.com/rust-lang-ci/rustc-builds/%s/rust-std-nightly-%s.tar.gz"
% (version, target_triple))
tgz_file = install_dir + ('rust-std-nightly-%s.tar.gz' % target_triple)
download_file("Host rust library for target %s" % target_triple, std_url, tgz_file)
print("Extracting Rust stdlib for target %s..." % target_triple)
extract(tgz_file, install_dir)
shutil.copytree(path.join(install_dir,
"rust-std%s%s-%s" % (nightly_suffix, stable_version, target_triple),
"rust-std-%s" % target_triple, "lib", "rustlib", target_triple),
path.join(install_dir,
"rustc%s%s-%s" % (nightly_suffix, stable_version, host_triple()),
"rustc", "lib", "rustlib", target_triple))
shutil.rmtree(path.join(install_dir,
"rust-std%s%s-%s" % (nightly_suffix, stable_version, target_triple)))
print("Rust {} libs ready.".format(target_triple))
@Command('bootstrap-rust-docs',
description='Download the Rust documentation',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Force download even if docs already exist')
def <API key>(self, force=False):
self.ensure_bootstrapped()
rust_root = self.config["tools"]["rust-root"]
docs_dir = path.join(rust_root, "doc")
if not force and path.exists(docs_dir):
print("Rust docs already downloaded.", end=" ")
print("Use |bootstrap-rust-docs --force| to download again.")
return
if path.isdir(docs_dir):
shutil.rmtree(docs_dir)
docs_name = self.rust_path().replace("rustc-", "rust-docs-")
docs_url = ("https://<API key>.s3.amazonaws.com/dist/rust-docs-nightly-%s.tar.gz"
% host_triple())
tgz_file = path.join(rust_root, 'doc.tar.gz')
download_file("Rust docs", docs_url, tgz_file)
print("Extracting Rust docs...")
temp_dir = path.join(rust_root, "temp_docs")
if path.isdir(temp_dir):
shutil.rmtree(temp_dir)
extract(tgz_file, temp_dir)
shutil.move(path.join(temp_dir, docs_name.split("/")[1],
"rust-docs", "share", "doc", "rust", "html"),
docs_dir)
shutil.rmtree(temp_dir)
print("Rust docs ready.")
@Command('bootstrap-cargo',
description='Download the Cargo build tool',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Force download even if cargo already exists')
def bootstrap_cargo(self, force=False):
cargo_dir = path.join(self.context.sharedir, "cargo",
self.cargo_build_id())
if not force and path.exists(path.join(cargo_dir, "cargo", "bin", "cargo" + BIN_SUFFIX)):
print("Cargo already downloaded.", end=" ")
print("Use |bootstrap-cargo --force| to download again.")
return
if path.isdir(cargo_dir):
shutil.rmtree(cargo_dir)
os.makedirs(cargo_dir)
tgz_file = "cargo-nightly-%s.tar.gz" % host_triple()
nightly_url = "https://s3.amazonaws.com/rust-lang-ci/cargo-builds/%s/%s" % \
(self.cargo_build_id(), tgz_file)
download_file("Cargo nightly", nightly_url, tgz_file)
print("Extracting Cargo nightly...")
nightly_dir = path.join(cargo_dir,
path.basename(tgz_file).replace(".tar.gz", ""))
extract(tgz_file, cargo_dir, movedir=nightly_dir)
print("Cargo ready.")
@Command('update-hsts-preload',
description='Download the HSTS preload list',
category='bootstrap')
def <API key>(self, force=False):
preload_filename = "hsts_preload.json"
preload_path = path.join(self.context.topdir, "resources")
chromium_hsts_url = "https://chromium.googlesource.com/chromium/src" + \
"/net/+/master/http/<API key>.json?format=TEXT"
try:
content_base64 = download_bytes("Chromium HSTS preload list", chromium_hsts_url)
except urllib2.URLError:
print("Unable to download chromium HSTS preload list; are you connected to the internet?")
sys.exit(1)
content_decoded = base64.b64decode(content_base64)
# The chromium "json" has single line comments in it which, of course,
# are non-standard/non-valid json. Simply strip them out before parsing
content_json = re.sub(r'(^|\s+)//.*$', '', content_decoded, flags=re.MULTILINE)
try:
<API key> = json.loads(content_json)
entries = {
"entries": [
{
"host": e["name"],
"include_subdomains": e.get("include_subdomains", False)
}
for e in <API key>["entries"]
]
}
with open(path.join(preload_path, preload_filename), 'w') as fd:
json.dump(entries, fd, indent=4)
except ValueError, e:
print("Unable to parse chromium HSTS preload list, has the format changed?")
sys.exit(1)
@Command('update-pub-domains',
description='Download the public domains list and update resources/public_domains.txt',
category='bootstrap')
def <API key>(self, force=False):
list_url = "https://publicsuffix.org/list/public_suffix_list.dat"
dst_filename = path.join(self.context.topdir, "resources", "public_domains.txt")
<API key> = re.compile(r'^[^*]+\*')
try:
content = download_bytes("Public suffix list", list_url)
except urllib2.URLError:
print("Unable to download the public suffix list; are you connected to the internet?")
sys.exit(1)
lines = [l.strip() for l in content.decode("utf8").split("\n")]
suffixes = [l for l in lines if not l.startswith("//") and not l == ""]
with open(dst_filename, "wb") as fo:
for suffix in suffixes:
if <API key>.match(suffix):
print("Warning: the new list contains a case that servo can't handle: %s" % suffix)
fo.write(suffix.encode("idna") + "\n")
@Command('clean-nightlies',
description='Clean unused nightly builds of Rust and Cargo',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Actually remove stuff')
def clean_nightlies(self, force=False):
rust_current = self.rust_path().split('/')[0]
cargo_current = self.cargo_build_id()
print("Current Rust version: " + rust_current)
print("Current Cargo version: " + cargo_current)
removing_anything = False
for current, base in [(rust_current, "rust"), (cargo_current, "cargo")]:
base = path.join(self.context.sharedir, base)
for name in os.listdir(base):
if name != current:
removing_anything = True
name = path.join(base, name)
if force:
print("Removing " + name)
if os.path.isdir(name):
shutil.rmtree(name)
else:
os.remove(name)
else:
print("Would remove " + name)
if not removing_anything:
print("Nothing to remove.")
elif not force:
print("Nothing done. "
"Run `./mach clean-nightlies -f` to actually remove.") |
TL.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
this.x = (round ? Math.round(x) : x);
this.y = (round ? Math.round(y) : y);
};
TL.Point.prototype = {
add: function (point) {
return this.clone()._add(point);
},
_add: function (point) {
this.x += point.x;
this.y += point.y;
return this;
},
subtract: function (point) {
return this.clone()._subtract(point);
},
// destructive subtract (faster)
_subtract: function (point) {
this.x -= point.x;
this.y -= point.y;
return this;
},
divideBy: function (num, round) {
return new TL.Point(this.x / num, this.y / num, round);
},
multiplyBy: function (num) {
return new TL.Point(this.x * num, this.y * num);
},
distanceTo: function (point) {
var x = point.x - this.x,
y = point.y - this.y;
return Math.sqrt(x * x + y * y);
},
round: function () {
return this.clone()._round();
},
// destructive round
_round: function () {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
return this;
},
clone: function () {
return new TL.Point(this.x, this.y);
},
toString: function () {
return 'Point(' +
TL.Util.formatNum(this.x) + ', ' +
TL.Util.formatNum(this.y) + ')';
}
}; |
package model_test
import (
"errors"
gc "gopkg.in/check.v1"
"gopkg.in/juju/names.v2"
"github.com/juju/juju/api"
jujucloud "github.com/juju/juju/cloud"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/testing"
)
// ModelConfig related fake environment for testing.
type fakeEnvSuite struct {
testing.<API key>
fake *fakeEnvAPI
}
func (s *fakeEnvSuite) SetUpTest(c *gc.C) {
s.<API key>.SetUpTest(c)
s.fake = &fakeEnvAPI{
values: map[string]interface{}{
"name": "test-model",
"special": "special value",
"running": true,
},
defaults: config.ConfigValues{
"attr": {Value: "foo", Source: "default"},
"attr2": {Value: "bar", Source: "controller"},
"attr3": {Value: "baz", Source: "region"},
},
}
}
type fakeEnvAPI struct {
values map[string]interface{}
cloud, region string
defaults config.ConfigValues
err error
keys []string
resetKeys []string
}
func (f *fakeEnvAPI) Close() error {
return nil
}
func (f *fakeEnvAPI) ModelGet() (map[string]interface{}, error) {
return f.values, nil
}
func (f *fakeEnvAPI) <API key>() (config.ConfigValues, error) {
result := make(config.ConfigValues)
for name, val := range f.values {
result[name] = config.ConfigValue{Value: val, Source: "model"}
}
return result, nil
}
func (f *fakeEnvAPI) ModelSet(config map[string]interface{}) error {
f.values = config
return f.err
}
func (f *fakeEnvAPI) ModelUnset(keys ...string) error {
f.resetKeys = keys
return f.err
}
// ModelDefaults related fake environment for testing.
type <API key> struct {
testing.<API key>
fakeAPIRoot *fakeAPIConnection
fakeDefaultsAPI *<API key>
fakeCloudAPI *fakeCloudAPI
}
func (s *<API key>) SetUpTest(c *gc.C) {
s.<API key>.SetUpTest(c)
s.fakeAPIRoot = &fakeAPIConnection{}
s.fakeDefaultsAPI = &<API key>{
values: map[string]interface{}{
"name": "test-model",
"special": "special value",
"running": true,
},
defaults: config.<API key>{
"attr": {Default: "foo"},
"attr2": {
Controller: "bar",
Regions: []config.RegionDefaultValue{{
"dummy-region",
"dummy-value",
}, {
"another-region",
"another-value",
}}},
},
}
s.fakeCloudAPI = &fakeCloudAPI{
clouds: map[string]jujucloud.Cloud{
"cloud-dummy": {
Type: "dummy-cloud",
Regions: []jujucloud.Region{
{Name: "dummy-region"},
{Name: "another-region"},
},
},
},
}
}
type fakeAPIConnection struct {
api.Connection
}
func (*fakeAPIConnection) Close() error {
return nil
}
type <API key> struct {
values map[string]interface{}
cloud, region string
defaults config.<API key>
err error
keys []string
}
func (f *<API key>) Close() error {
return nil
}
func (f *<API key>) ModelGet() (map[string]interface{}, error) {
return f.values, nil
}
func (f *<API key>) ModelDefaults() (config.<API key>, error) {
return f.defaults, nil
}
func (f *<API key>) SetModelDefaults(cloud, region string, cfg map[string]interface{}) error {
if f.err != nil {
return f.err
}
f.cloud = cloud
f.region = region
for name, val := range cfg {
f.defaults[name] = config.<API key>{Controller: val}
}
return nil
}
func (f *<API key>) UnsetModelDefaults(cloud, region string, keys ...string) error {
if f.err != nil {
return f.err
}
f.cloud = cloud
f.region = region
for _, key := range keys {
delete(f.defaults, key)
}
return nil
}
func (f *<API key>) ModelSet(config map[string]interface{}) error {
f.values = config
return f.err
}
func (f *<API key>) ModelUnset(keys ...string) error {
f.keys = keys
return f.err
}
type fakeCloudAPI struct {
clouds map[string]jujucloud.Cloud
}
func (f *fakeCloudAPI) Close() error { return nil }
func (f *fakeCloudAPI) DefaultCloud() (names.CloudTag, error) {
return names.NewCloudTag("dummy"), nil
}
func (f *fakeCloudAPI) Cloud(name names.CloudTag) (jujucloud.Cloud, error) {
var (
c jujucloud.Cloud
ok bool
)
if c, ok = f.clouds[name.String()]; !ok {
return jujucloud.Cloud{}, errors.New("Unknown cloud")
}
return c, nil
} |
<?php return array(
'field workspace description' => '',
'workspace description' => '',
'add new workspace' => '',
'add your first workspace' => '',
'you have no workspaces yet' => '',
'filter by workspaces' => '',
'filter by tags' => '',
); ?> |
#!/bin/sh
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
set -e
cp -R input/Q1.java Q1.java
javac -cp ".:input/lib/pythia.jar" Q1.java 2> output/q1.err
java -cp ".:input/lib/opencsv-2.3.jar:input/lib/pythia.jar" Q1 1> output/q1.out 2> output/q1.err |
package org.kuali.kfs.module.cg.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.kuali.kfs.module.cg.CGPropertyConstants;
import org.kuali.kfs.module.cg.service.<API key>;
/**
* Service with methods related to the Contracts & Grants Billing (CGB) enhancement.
*/
public class <API key> implements <API key> {
@Override
public List<String> <API key>() {
List<String> <API key> = new ArrayList<String>();
<API key>.add(CGPropertyConstants.SectionId.<API key>);
<API key>.add(CGPropertyConstants.SectionId.<API key>);
<API key>.add(CGPropertyConstants.SectionId.<API key>);
<API key>.add(CGPropertyConstants.SectionId.<API key>);
<API key>.add(CGPropertyConstants.SectionId.<API key>);
return <API key>;
}
@Override
public List<String> <API key>() {
List<String> <API key> = new ArrayList<String>();
<API key>.add(CGPropertyConstants.SectionId.<API key>);
<API key>.add(CGPropertyConstants.SectionId.<API key>);
<API key>.add(CGPropertyConstants.SectionId.<API key>);
<API key>.add(CGPropertyConstants.SectionId.<API key>);
return <API key>;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.