code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
# Configure Rails Envinronment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment.rb", __FILE__)
require "rails/test_help"
Rails.backtrace_cleaner.remove_silencers!
| DouglasAllen/site-camping | vendor/gems/ruby/2.2.0/gems/mab-0.0.3/test/rails/test/helper.rb | Ruby | mit | 193 |
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;
}
| JanEicken/MA | libs/GeographicLib-1.43/dotnet/examples/ManagedCPP/example-Gnomonic.cpp | C++ | mit | 986 |
(function () {
'use strict';
function ContentEditController($rootScope, $scope, $routeParams, $q, $timeout, $window, $location, appState, contentResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, 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
contentEditingHelper.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.
serverValidationManager.executeAndClearAllSubscriptions();
syncTreeNode($scope.content, data.path, true);
resetLastListPageNumber($scope.content);
eventsService.emit("content.loaded", { content: $scope.content });
$scope.page.loading = false;
});
}
function createButtons(content) {
$scope.page.buttonGroupState = "init";
var buttons = contentEditingHelper.configureContentEditorButtons({
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 });
contentEditingHelper.contentEditorPerformSave({
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 resetLastListPageNumber(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.lastListViewPageViewed = 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);
resetLastListPageNumber($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 (!notificationsService.hasView()) {
notificationsService.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 });
contentEditingHelper.handleSuccessfulSave({
scope: $scope,
savedContent: data,
rebindCallback: contentEditingHelper.reBindChangedProperties($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, "relateParentDocumentOnDelete").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) {
notificationsService.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) {
notificationsService.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";
notificationsService.error(error.headline, error.content);
});
}
}, function (err) {
$scope.page.buttonRestore = "error";
notificationsService.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";
notificationsService.success("Successfully restored " + node.name + " to " + target.name);
// reload the node
getNode();
}, function (err) {
$scope.page.buttonRestore = "error";
notificationsService.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.EditorDirectiveController',
scope: {
contentId: "=",
isNew: "=?",
treeAlias: "@",
page: "=?",
saveMethod: "&",
getMethod: "&",
getScaffoldMethod: "&?"
}
};
return directive;
}
angular.module('umbraco.directives').controller('Umbraco.Editors.Content.EditorDirectiveController', ContentEditController);
angular.module('umbraco.directives').directive('contentEditor', createDirective);
})();
| abryukhov/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/common/directives/components/content/edit.controller.js | JavaScript | mit | 13,245 |
<?php
defined('C5_EXECUTE') or die("Access Denied.");
Loader::controller('/profile/edit');
Loader::model('user_private_message');
class ProfileMessagesController extends ProfileEditController {
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 = UserPrivateMessageMailbox::get($ui, UserPrivateMessageMailbox::MBTYPE_INBOX);
$sent = UserPrivateMessageMailbox::get($ui, UserPrivateMessageMailbox::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('profile_private_messages_enabled') == 1)) {
$this->set('recipient', $ui);
return true;
}
}
$this->redirect('/profile');
}
protected function getMessageMailboxID($box) {
$msgMailboxID = 0;
switch($box) {
case 'inbox':
$msgMailboxID = UserPrivateMessageMailbox::MBTYPE_INBOX;
break;
case 'sent':
$msgMailboxID = UserPrivateMessageMailbox::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 = UserPrivateMessageMailbox::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 = UserPrivateMessageMailbox::get($ui, $msgMailboxID);
$msg = UserPrivateMessage::getByID($msgID, $mailbox);
if ($ui->canReadPrivateMessage($msg)) {
$msg->markAsRead();
$this->set('subject', $msg->getFormattedMessageSubject());
$this->set('msgContent', $msg->getMessageBody());
$this->set('dateAdded', $msg->getMessageDateAdded('user', t('F d, Y \a\t g:i A')));
$this->set('author', $msg->getMessageAuthorObject());
$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 = UserPrivateMessageMailbox::get($ui, $msgMailboxID);
$msg = UserPrivateMessage::getByID($msgID, $mailbox);
if ($ui->canReadPrivateMessage($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->getMessageRelevantUserID();
$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->getFormattedMessageSubject());
$body = "\n\n\n" . $msg->getMessageDelimiter() . "\n";
$body .= t("From: %s\nDate Sent: %s\nSubject: %s", $msg->getMessageAuthorName(), $msg->getMessageDateAdded('user', t('F d, Y \a\t g:i A')), $msg->getFormattedMessageSubject());
$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("validate_send_message");
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 ValidationErrorHelper) {
$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);
}
} | clejer/concrete_ | concrete/controllers/profile/messages.php | PHP | mit | 5,679 |
#!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
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 TestFilestatCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('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 test_should_open_proc_sys_fs_file_nr(self, publish_mock, open_mock):
open_mock.return_value = StringIO('')
self.collector.collect()
open_mock.assert_called_once_with('/proc/sys/fs/file-nr')
@patch.object(Collector, 'publish')
def test_should_work_with_real_data(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()
| datafiniti/Diamond | src/collectors/filestat/test/testfilestat.py | Python | mit | 1,903 |
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.requestAnimationFrame
|| win.webkitRequestAnimationFrame
|| win.mozRequestAnimationFrame
|| win.msRequestAnimationFrame
|| function(cb) { return setTimeout(cb, 16); };
var win$1 = window;
var caf = win$1.cancelAnimationFrame
|| win$1.mozCancelAnimationFrame
|| 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+
// eslint-disable-next-line
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;
}
// https://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/
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('WebkitTransitionDuration', '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,
fixedWidthViewportWidth: 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,
autoplayButtonOutput: true,
autoplayResetOnVisibility: 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)
// https://stackoverflow.com/questions/8701015/html-localstorage-is-null-on-android-when-using-webview
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
// }
// }
// to: {
// 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];
}
}
// === define and set variables ===
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'),
fixedWidthViewportWidth = options.fixedWidthViewportWidth,
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 ? getCloneCountForLoop() : 0,
slideCountNew = !carousel ? slideCount + cloneCount : slideCount + cloneCount * 2,
hasRightDeadZone = fixedWidth && !loop && !edgePadding ? true : false,
updateIndexBeforeTransform = (!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,
moveDirectionExpected = 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 = [],
visibleNavIndexesCached = visibleNavIndexes,
navClicked = -1,
navCurrentIndex = getAbsIndex(),
navCurrentIndexCached = 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,
autoplayResetOnVisibility = getOption('autoplayResetOnVisibility'),
autoplayHtmlStrings = ['<span class=\'tns-visually-hidden\'>', ' animation</span>'],
autoplayTimer,
animating,
autoplayHoverPaused,
autoplayUserPaused,
autoplayVisibilityPaused;
}
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 = autoplayResetOnVisibility = 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 = ')';
}
}
// === COMMON FUNCTIONS === //
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 && !fixedWidthViewportWidth) {
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(fixedWidthViewportWidth / Math.min.apply(null, arr)) :
Math.max.apply(null, arr);
}
}
function getCloneCountForLoop () {
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 getInnerWrapperStyles (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 += getTrsnsitionDurationStyle(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 getTrsnsitionDurationStyle (speed) {
return getCSSPrefix(TRANSITIONDURATION, 18) + 'transition-duration:' + speed / 1000 + 's;';
}
function getAnimationDurationStyle (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.createDocumentFragment(),
fragmentAfter = doc.createDocumentFragment();
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,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
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 = getInnerWrapperStyles(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 += getTrsnsitionDurationStyle(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 += getTrsnsitionDurationStyle(speed); }
if (ANIMATIONDURATION) { str += getAnimationDurationStyle(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 = getInnerWrapperStyles(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();
updateContentWrapperHeight();
}
// 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{' + getInnerWrapperStyles(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 += getTrsnsitionDurationStyle(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 += getTrsnsitionDurationStyle(speedBP); }
if (ANIMATIONDURATION) { slideStr += getAnimationDurationStyle(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) {
doContainerTransformSilent();
}
// == 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.autoplayButtonOutput) {
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 (autoplayResetOnVisibility) { 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);
updateControlsStatus();
// 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();
toggleSlideDisplayAndEdgePadding();
updateFixedWidthInnerWrapperStyle();
events.on('indexChanged', additionalUpdates);
if (typeof onInit === 'function') { onInit(info()); }
if (nested === 'inner') { events.emit('innerLoaded', info()); }
if (disable) { disableSlider(true); }
isOn = true;
})();
// === ON RESIZE ===
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,
needContainerTransform = 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; }
toggleSlideDisplayAndEdgePadding();
}
if (breakpointZoneTem !== breakpointZone) {
speed = getOption('speed');
edgePadding = getOption('edgePadding');
gutter = getOption('gutter');
fixedWidth = getOption('fixedWidth');
if (!disable && fixedWidth !== fixedWidthTem) {
needContainerTransform = 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,
autoplayHoverPauseTem = autoplayHoverPause,
autoplayResetOnVisibilityTem = autoplayResetOnVisibility,
autoplayTextTem = autoplayText;
if (freeze) {
autoplay = autoplayHoverPause = autoplayResetOnVisibility = false;
} else {
autoplay = getOption('autoplay');
if (autoplay) {
autoplayHoverPause = getOption('autoplayHoverPause');
autoplayResetOnVisibility = getOption('autoplayResetOnVisibility');
} else {
autoplayHoverPause = autoplayResetOnVisibility = 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 !== autoplayHoverPauseTem) {
autoplayHoverPause ?
addEvents(container, hoverEvents) :
removeEvents(container, hoverEvents);
}
if (autoplayResetOnVisibility !== autoplayResetOnVisibilityTem) {
autoplayResetOnVisibility ?
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 = getInnerWrapperStyles(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) { needContainerTransform = true; }
}
if (index !== indexTem) {
events.emit('indexChanged', info());
needContainerTransform = true;
}
if (items !== itemsTem) {
additionalUpdates();
updateSlidePosition();
if (navigator.msMaxTouchPoints) { setSnapInterval(); }
}
}
// things always do regardless of breakpoint zone changing
if (!horizontal && !disable) {
getSlideOffsetTops();
updateContentWrapperHeight();
needContainerTransform = true;
}
if (needContainerTransform) {
doContainerTransformSilent();
indexCached = index;
}
updateFixedWidthInnerWrapperStyle(true);
// auto height
if ((autoHeight || !carousel) && !disable) { runAutoHeight(); }
}
// === INITIALIZATION FUNCTIONS === //
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 toggleSlideDisplayAndEdgePadding () {
// 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 updateFixedWidthInnerWrapperStyle (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 = getInnerWrapperStyles(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(); }
doContainerTransformSilent();
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, updateInnerWrapperHeight); });
}
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();
updateControlsStatus();
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 updateInnerWrapperHeight () {
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].getBoundingClientRect().top, attr;
for (var i = 1; i < slideCountNew; i++) {
attr = slideItems[i].getBoundingClientRect().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 !== navCurrentIndexCached) {
var navPrev = navItems[navCurrentIndexCached],
navCurrent = navItems[navCurrentIndex];
setAttrs(navPrev, {
'tabindex': '-1',
'aria-selected': 'false'
});
setAttrs(navCurrent, {
'tabindex': '0',
'aria-selected': 'true'
});
removeClass(navPrev, navActiveClass);
addClass(navCurrent, navActiveClass);
}
}
}
function getLowerCaseNodeName (el) {
return el.nodeName.toLowerCase();
}
function isButton (el) {
return getLowerCaseNodeName(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 updateControlsStatus () {
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 getContainerTransformValue () {
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 doContainerTransformSilent (val) {
resetDuration(container, '0s');
doContainerTransform(val);
setTimeout(function() { resetDuration(container, ''); }, 0);
}
function doContainerTransform (val, test) {
if (!val) { val = getContainerTransformValue(); }
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 = getContainerTransformValue(); }
// 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
doContainerTransform(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) { updateContentWrapperHeight(); }
} :
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 (updateIndexBeforeTransform) { 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 (!updateIndexBeforeTransform) {
var indexTem = index;
updateIndex();
if (index !== indexTem) {
events.emit('indexChanged', info());
doContainerTransformSilent();
}
}
if (autoHeight) { runAutoHeight(); }
if (nested === 'inner') { events.emit('innerLoaded', info()); }
running = false;
navCurrentIndexCached = 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 updateAutoplayButton (action, txt) {
setAttrs(autoplayButton, {'data-action': action});
autoplayButton.innerHTML = autoplayHtmlStrings[0] + action + autoplayHtmlStrings[1] + txt;
}
function startAutoplay () {
setAutoplayTimer();
if (autoplayButton) { updateAutoplayButton('stop', autoplayText[1]); }
}
function stopAutoplay () {
stopAutoplayTimer();
if (autoplayButton) { updateAutoplayButton('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();
autoplayVisibilityPaused = true;
}
} else if (autoplayVisibilityPaused) {
setAutoplayTimer();
autoplayVisibilityPaused = 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 preventDefaultBehavior (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(getLowerCaseNodeName(getTarget(e))) >= 0) {
preventDefaultBehavior(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 (!moveDirectionExpected) {
panStart = false;
return;
}
caf(rafIndex);
if (panStart) { rafIndex = raf(function(){ panUpdate(e); }); }
if (
moveDirectionExpected === '?' &&
lastPosition.x !== initPosition.x &&
lastPosition.y !== initPosition.y) {
moveDirectionExpected = getTouchDirection(toDegree(lastPosition.y - initPosition.y, lastPosition.x - initPosition.x), swipeAngle) === options.axis;
}
if (moveDirectionExpected) {
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) { moveDirectionExpected = '?'; } // 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) {
preventDefaultBehavior(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);
});
}
}
}
// === RESIZE FUNCTIONS === //
// (slideOffsetTops, index, items) => vertical_conentWrapper.height
function updateContentWrapperHeight () {
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 !== visibleNavIndexesCached) {
forEachNodeList(navItems, function(el, i) {
if (visibleNavIndexes.indexOf(i) < 0) {
hideElement(el);
} else {
showElement(el);
}
});
// cache visible nav indexes
visibleNavIndexesCached = 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,
navCurrentIndexCached: navCurrentIndexCached,
visibleNavIndexes: visibleNavIndexes,
visibleNavIndexesCached: visibleNavIndexesCached,
sheet: sheet,
event: e || {},
};
}
return {
getInfo: info,
events: events,
goTo: goTo,
play: play,
pause: pause,
isOn: isOn,
updateSliderHeight: updateInnerWrapperHeight,
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 = navCurrentIndexCached = hasControls = visibleNavIndexes = visibleNavIndexesCached =
this.getInfo = this.events = this.goTo = this.play = this.pause = this.destroy = null;
this.isOn = isOn = false;
}
};
};
return tns;
})(); | jonobr1/cdnjs | ajax/libs/tiny-slider/2.7.3/tiny-slider.js | JavaScript | mit | 89,288 |
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\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);
}
}
| minhnguyen-balance/oro_platform | vendor/composer/composer/src/Composer/Package/Archiver/BaseExcludeFilter.php | PHP | mit | 3,939 |
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.getOwnPropertyDescriptors(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__");
| ccschneidr/babel | packages/babel-plugin-transform-decorators/test/fixtures/object-methods/mutate-descriptor/exec.js | JavaScript | mit | 2,375 |
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)))
| okuta/chainer | chainer/functions/math/sign.py | Python | mit | 893 |
require "acts-as-taggable-on"
require "calagator/tag_model_extensions"
ActsAsTaggableOn::Tag.send :include, Calagator::TagModelExtensions
| kerrizor/calagator | config/initializers/load_tag_model_extensions.rb | Ruby | mit | 138 |
/*
Language: Lisp
Description: Generic lisp syntax
Author: Vasily Polovnyov <vast@whiteants.net>
Category: lisp
*/
function lisp(hljs) {
var LISP_IDENT_RE = '[a-zA-Z_\\-+\\*\\/<=>&#][a-zA-Z0-9_\\-+*\\/<=>&#!]*';
var MEC_RE = '\\|[^]*?\\|';
var LISP_SIMPLE_NUMBER_RE = '(-|\\+)?\\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: LISP_SIMPLE_NUMBER_RE, 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)\\(' + LISP_SIMPLE_NUMBER_RE + ' +' + LISP_SIMPLE_NUMBER_RE, 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;
| ealbertos/dotfiles | vscode.symlink/extensions/bierner.markdown-preview-github-styles-0.2.0/node_modules/highlight.js/lib/languages/lisp.js | JavaScript | mit | 2,398 |
/* SPDX-License-Identifier: (BSD-3-Clause OR GPL-2.0)
*
* Copyright 2008-2016 Freescale Semiconductor Inc.
* Copyright 2016,2019 NXP
*/
#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] = {
/*1*/ { KEY1SZ, LDST_CLASS_1_CCB | LDST_SRCDST_WORD_KEYSZ_REG },
{ KEY2SZ, LDST_CLASS_2_CCB | LDST_SRCDST_WORD_KEYSZ_REG },
{ DJQDA, LDST_CLASS_DECO | LDST_SRCDST_WORD_DECO_JQDAR },
{ MODE1, LDST_CLASS_1_CCB | LDST_SRCDST_WORD_MODE_REG },
{ MODE2, LDST_CLASS_2_CCB | LDST_SRCDST_WORD_MODE_REG },
{ DJQCTRL, LDST_CLASS_DECO | LDST_SRCDST_WORD_DECO_JQCTRL },
{ DATA1SZ, LDST_CLASS_1_CCB | LDST_SRCDST_WORD_DATASZ_REG },
{ DATA2SZ, LDST_CLASS_2_CCB | LDST_SRCDST_WORD_DATASZ_REG },
{ DSTAT, LDST_CLASS_DECO | LDST_SRCDST_WORD_DECO_STAT },
{ ICV1SZ, LDST_CLASS_1_CCB | LDST_SRCDST_WORD_ICVSZ_REG },
{ ICV2SZ, LDST_CLASS_2_CCB | LDST_SRCDST_WORD_ICVSZ_REG },
{ DPID, LDST_CLASS_DECO | LDST_SRCDST_WORD_PID },
{ CCTRL, LDST_SRCDST_WORD_CHACTRL },
{ ICTRL, LDST_SRCDST_WORD_IRQCTRL },
{ CLRW, LDST_SRCDST_WORD_CLRW },
{ MATH0, LDST_CLASS_DECO | LDST_SRCDST_WORD_DECO_MATH0 },
{ CSTAT, LDST_SRCDST_WORD_STAT },
{ MATH1, LDST_CLASS_DECO | LDST_SRCDST_WORD_DECO_MATH1 },
{ MATH2, LDST_CLASS_DECO | LDST_SRCDST_WORD_DECO_MATH2 },
{ AAD1SZ, LDST_CLASS_1_CCB | LDST_SRCDST_WORD_DECO_AAD_SZ },
{ MATH3, LDST_CLASS_DECO | LDST_SRCDST_WORD_DECO_MATH3 },
{ IV1SZ, LDST_CLASS_1_CCB | LDST_SRCDST_WORD_CLASS1_IV_SZ },
{ PKASZ, LDST_CLASS_1_CCB | LDST_SRCDST_WORD_PKHA_A_SZ },
{ PKBSZ, LDST_CLASS_1_CCB | LDST_SRCDST_WORD_PKHA_B_SZ },
{ PKESZ, LDST_CLASS_1_CCB | LDST_SRCDST_WORD_PKHA_E_SZ },
{ PKNSZ, LDST_CLASS_1_CCB | LDST_SRCDST_WORD_PKHA_N_SZ },
{ CONTEXT1, LDST_CLASS_1_CCB | LDST_SRCDST_BYTE_CONTEXT },
{ CONTEXT2, LDST_CLASS_2_CCB | LDST_SRCDST_BYTE_CONTEXT },
{ DESCBUF, LDST_CLASS_DECO | LDST_SRCDST_WORD_DESCBUF },
/*30*/ { JOBDESCBUF, LDST_CLASS_DECO | LDST_SRCDST_WORD_DESCBUF_JOB },
{ SHAREDESCBUF, LDST_CLASS_DECO | LDST_SRCDST_WORD_DESCBUF_SHARED },
/*32*/ { JOBDESCBUF_EFF, LDST_CLASS_DECO |
LDST_SRCDST_WORD_DESCBUF_JOB_WE },
{ SHAREDESCBUF_EFF, LDST_CLASS_DECO |
LDST_SRCDST_WORD_DESCBUF_SHARED_WE },
/*34*/ { GTR, LDST_CLASS_DECO | LDST_SRCDST_WORD_GTR },
{ STR, LDST_CLASS_DECO | LDST_SRCDST_WORD_STR }
};
/*
* 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__ */
| john-mcnamara-intel/dpdk | drivers/common/dpaax/caamflib/rta/store_cmd.h | C | mit | 5,412 |
/*!
* OOUI v0.27.2
* https://www.mediawiki.org/wiki/OOUI
*
* Copyright 2011–2018 OOUI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2018-06-06T16:16:14Z
*/
/**
* 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.oo-ui-iconElement-icon.oo-ui-tool-checkIcon {
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;
}
.oo-ui-toolbar-narrow .oo-ui-tool .oo-ui-tool-link {
padding-left: 2.85714286em;
}
.oo-ui-tool-with-label .oo-ui-tool-link {
padding: 1em 0.85714286em 0.92857143em 2.64285714em;
}
.oo-ui-tool.oo-ui-iconElement .oo-ui-iconElement-icon {
display: block;
left: 0.78571429em;
}
.oo-ui-toolbar-narrow .oo-ui-tool.oo-ui-iconElement .oo-ui-iconElement-icon {
left: 0.71428571em;
}
.oo-ui-tool .oo-ui-tool-title {
line-height: 1.07142857em;
}
.oo-ui-tool.oo-ui-widget-enabled {
-webkit-transition: background-color 100ms;
-moz-transition: background-color 100ms;
transition: background-color 100ms;
}
.oo-ui-tool.oo-ui-widget-enabled .oo-ui-tool-link:focus {
outline: 1px solid #36c;
box-shadow: inset 0 0 0 1px #36c;
z-index: 1;
}
.oo-ui-tool.oo-ui-widget-enabled .oo-ui-iconElement-icon {
opacity: 0.87;
-webkit-transition: opacity 100ms;
-moz-transition: opacity 100ms;
transition: opacity 100ms;
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
.oo-ui-tool.oo-ui-widget-enabled .oo-ui-tool-title {
-webkit-transition: color 100ms;
-moz-transition: color 100ms;
transition: color 100ms;
}
.oo-ui-tool.oo-ui-widget-enabled:hover .oo-ui-iconElement-icon {
opacity: 1;
}
.oo-ui-tool.oo-ui-widget-enabled[class*='oo-ui-flaggedElement'] .oo-ui-iconElement-icon {
opacity: 1;
}
.oo-ui-tool.oo-ui-widget-disabled .oo-ui-iconElement-icon {
opacity: 0.34;
}
.oo-ui-popupTool-popup .oo-ui-popupWidget-popup,
.oo-ui-popupTool-popup .oo-ui-popupWidget-anchor {
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;
}
.oo-ui-toolGroup-empty {
display: none;
}
.oo-ui-toolGroup-tools .oo-ui-tool-link {
text-decoration: none;
cursor: pointer;
}
.oo-ui-toolGroup-tools.oo-ui-toolGroup-disabled-tools .oo-ui-tool-link,
.oo-ui-toolGroup-tools .oo-ui-widget-disabled > .oo-ui-tool-link {
outline: 0;
cursor: default;
}
.oo-ui-toolbar-actions .oo-ui-toolGroup {
border-right: 0;
border-left: 1px solid #eaecf0;
}
.oo-ui-toolbar-actions .oo-ui-toolGroup.oo-ui-barToolGroup {
border-right-width: 0;
}
.oo-ui-toolGroup.oo-ui-widget-disabled .oo-ui-indicatorElement-indicator,
.oo-ui-toolGroup.oo-ui-widget-disabled .oo-ui-iconElement-icon {
opacity: 0.34 !important;
}
.oo-ui-barToolGroup-tools > .oo-ui-tool {
display: inline-block;
position: relative;
vertical-align: top;
}
.oo-ui-barToolGroup-tools > .oo-ui-tool > .oo-ui-tool-link {
display: block;
}
.oo-ui-barToolGroup-tools > .oo-ui-tool > .oo-ui-tool-link .oo-ui-tool-accel {
display: none;
}
.oo-ui-barToolGroup-tools > .oo-ui-tool.oo-ui-iconElement > .oo-ui-tool-link .oo-ui-tool-title {
display: none;
}
.oo-ui-barToolGroup-tools > .oo-ui-tool.oo-ui-iconElement.oo-ui-tool-with-label > .oo-ui-tool-link .oo-ui-tool-title {
display: inline-block;
}
.oo-ui-barToolGroup-tools > .oo-ui-tool.iconElement > .oo-ui-tool-link > .oo-ui-iconElement-icon {
display: block;
}
.oo-ui-barToolGroup-tools > .oo-ui-tool + .oo-ui-tool {
margin-left: -2px;
}
.oo-ui-barToolGroup-tools.oo-ui-toolGroup-enabled-tools > .oo-ui-tool:not( .oo-ui-toolGroupTool ).oo-ui-widget-enabled:hover {
background-color: #eaecf0;
}
.oo-ui-barToolGroup-tools.oo-ui-toolGroup-enabled-tools > .oo-ui-tool:not( .oo-ui-toolGroupTool ).oo-ui-widget-enabled > .oo-ui-tool-link .oo-ui-tool-title {
color: #222;
-webkit-transition: color 100ms;
-moz-transition: color 100ms;
transition: color 100ms;
}
.oo-ui-barToolGroup-tools.oo-ui-toolGroup-enabled-tools > .oo-ui-tool:not( .oo-ui-toolGroupTool ).oo-ui-tool-active {
background-color: #eaf3ff;
}
.oo-ui-barToolGroup-tools.oo-ui-toolGroup-enabled-tools > .oo-ui-tool:not( .oo-ui-toolGroupTool ).oo-ui-tool-active:hover {
background-color: rgba(41, 98, 204, 0.1);
}
.oo-ui-barToolGroup-tools.oo-ui-toolGroup-enabled-tools > .oo-ui-tool:not( .oo-ui-toolGroupTool ).oo-ui-tool-active > .oo-ui-tool-link .oo-ui-tool-title {
color: #36c;
}
.oo-ui-barToolGroup-tools.oo-ui-toolGroup-enabled-tools .oo-ui-tool.oo-ui-widget-disabled > .oo-ui-tool-link .oo-ui-tool-title,
.oo-ui-barToolGroup-tools.oo-ui-toolGroup-disabled-tools .oo-ui-tool > .oo-ui-tool-link .oo-ui-tool-title {
color: #72777d;
}
.oo-ui-popupToolGroup {
position: relative;
min-width: 3em;
}
.oo-ui-popupToolGroup-handle {
display: block;
cursor: pointer;
}
.oo-ui-popupToolGroup-handle .oo-ui-labelElement-label:not( :empty ) {
display: inline-block;
}
.oo-ui-popupToolGroup.oo-ui-widget-disabled .oo-ui-popupToolGroup-handle {
outline: 0;
cursor: default;
}
.oo-ui-popupToolGroup-tools {
display: none;
position: absolute;
z-index: 4;
}
.oo-ui-popupToolGroup-tools.oo-ui-popupToolGroup-active-tools {
display: block;
}
.oo-ui-popupToolGroup-tools .oo-ui-tool-link {
display: table;
width: 100%;
vertical-align: middle;
white-space: nowrap;
}
.oo-ui-popupToolGroup-tools .oo-ui-tool-link .oo-ui-tool-accel,
.oo-ui-popupToolGroup-tools .oo-ui-tool-link .oo-ui-tool-title {
display: table-cell;
vertical-align: middle;
}
.oo-ui-popupToolGroup-tools .oo-ui-tool-link .oo-ui-tool-accel {
text-align: right;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup {
min-width: 2.85714286em;
}
.oo-ui-popupToolGroup.oo-ui-indicatorElement:not( .oo-ui-labelElement ):not( .oo-ui-iconElement ) {
min-width: 1.85714286em;
}
.oo-ui-popupToolGroup-handle {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.oo-ui-popupToolGroup-handle .oo-ui-iconElement-icon {
left: 0.78571429em;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup-handle .oo-ui-iconElement-icon {
left: 0.64285714em;
}
.oo-ui-popupToolGroup-handle .oo-ui-indicatorElement-indicator {
background-position: center 52%;
right: 0.57142857em;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup-handle .oo-ui-indicatorElement-indicator {
right: 0.28571429em;
}
.oo-ui-popupToolGroup.oo-ui-iconElement .oo-ui-popupToolGroup-handle,
.oo-ui-popupToolGroup.oo-ui-indicatorElement .oo-ui-popupToolGroup-handle {
padding-top: 3em;
}
.oo-ui-popupToolGroup.oo-ui-iconElement.oo-ui-indicatorElement .oo-ui-popupToolGroup-handle {
padding-left: 3em;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup.oo-ui-iconElement.oo-ui-indicatorElement .oo-ui-popupToolGroup-handle {
padding-left: 2.85714286em;
}
.oo-ui-popupToolGroup.oo-ui-labelElement .oo-ui-popupToolGroup-handle {
padding: 1em 0.85714286em 0.92857143em;
}
.oo-ui-popupToolGroup.oo-ui-labelElement .oo-ui-popupToolGroup-handle .oo-ui-labelElement-label {
line-height: 1.07142857em;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup.oo-ui-labelElement .oo-ui-popupToolGroup-handle {
padding-left: 0.71428571em;
padding-right: 0.71428571em;
}
.oo-ui-popupToolGroup.oo-ui-iconElement.oo-ui-labelElement .oo-ui-popupToolGroup-handle {
padding-left: 2.64285714em;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup.oo-ui-iconElement.oo-ui-labelElement .oo-ui-popupToolGroup-handle {
padding-left: 2.5em;
}
.oo-ui-popupToolGroup.oo-ui-labelElement.oo-ui-indicatorElement .oo-ui-popupToolGroup-handle {
padding-right: 1.85714286em;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup.oo-ui-labelElement.oo-ui-indicatorElement .oo-ui-popupToolGroup-handle {
padding-right: 1.28571429em;
}
.oo-ui-popupToolGroup.oo-ui-indicatorElement .oo-ui-popupToolGroup-handle {
padding-right: 1.14285714em;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup.oo-ui-indicatorElement .oo-ui-popupToolGroup-handle {
padding-right: 0.85714286em;
}
.oo-ui-popupToolGroup:not( .oo-ui-labelElement ):not( .oo-ui-iconElement ) .oo-ui-indicatorElement-indicator {
opacity: 1;
}
.oo-ui-popupToolGroup-header {
color: #72777d;
padding: 0 0.85714286em;
font-weight: bold;
line-height: 2.28571429em;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup-header {
padding: 0 0.71428571em;
}
.oo-ui-popupToolGroup-tools {
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);
}
.oo-ui-popupToolGroup-tools .oo-ui-tool-link {
padding: 1em 0.85714286em 0.92857143em 0.85714286em;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup-tools .oo-ui-tool-link {
padding-left: 0.71428571em;
padding-right: 0.71428571em;
}
.oo-ui-popupToolGroup-tools .oo-ui-tool-link .oo-ui-tool-title {
color: #222;
}
.oo-ui-popupToolGroup-tools .oo-ui-tool-link .oo-ui-tool-accel {
color: #72777d;
line-height: 1.07142857em;
}
.oo-ui-popupToolGroup-tools .oo-ui-tool-link .oo-ui-tool-accel:not( :empty ) {
padding-left: 1.28571429em;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup-tools .oo-ui-tool-link .oo-ui-tool-accel:not( :empty ) {
padding-left: 1.14285714em;
}
.oo-ui-popupToolGroup-tools .oo-ui-iconElement .oo-ui-tool-link {
padding-left: 2.64285714em;
}
.oo-ui-toolbar-narrow .oo-ui-popupToolGroup-tools .oo-ui-iconElement .oo-ui-tool-link {
padding-left: 2.5em;
}
.oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle {
-webkit-transition: background-color 100ms, box-shadow 100ms;
-moz-transition: background-color 100ms, box-shadow 100ms;
transition: background-color 100ms, box-shadow 100ms;
}
.oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle:hover {
background-color: #eaecf0;
}
.oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle:active {
background-color: #eaf3ff;
}
.oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle .oo-ui-iconElement-icon,
.oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle .oo-ui-indicatorElement-indicator {
opacity: 0.87;
-webkit-transition: opacity 100ms;
-moz-transition: opacity 100ms;
transition: opacity 100ms;
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
.oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle:hover .oo-ui-iconElement-icon,
.oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle:active .oo-ui-iconElement-icon,
.oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle:hover .oo-ui-indicatorElement-indicator,
.oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle:active .oo-ui-indicatorElement-indicator {
opacity: 1;
}
.oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle:focus {
outline: 1px solid #36c;
box-shadow: inset 0 0 0 1px #36c;
}
.oo-ui-popupToolGroup.oo-ui-widget-enabled[class*='oo-ui-flaggedElement'] > .oo-ui-popupToolGroup-handle .oo-ui-iconElement-icon,
.oo-ui-popupToolGroup.oo-ui-widget-enabled[class*='oo-ui-flaggedElement'] > .oo-ui-popupToolGroup-handle:hover .oo-ui-iconElement-icon {
opacity: 1;
}
.oo-ui-toolbar-actions .oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle {
border-right: 1px solid transparent;
-webkit-transition: border-color 100ms;
-moz-transition: border-color 100ms;
transition: border-color 100ms;
}
.oo-ui-toolbar-actions .oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle:hover {
border-right-color: #eaecf0;
}
.oo-ui-toolbar-actions .oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle:active {
border-right-color: #eaf3ff;
}
.oo-ui-toolbar-actions .oo-ui-popupToolGroup.oo-ui-widget-enabled > .oo-ui-popupToolGroup-handle:focus {
border-right-color: #36c;
}
.oo-ui-popupToolGroup.oo-ui-popupToolGroup-active > .oo-ui-popupToolGroup-handle {
background-color: #eaf3ff;
color: #36c;
}
.oo-ui-popupToolGroup.oo-ui-popupToolGroup-active > .oo-ui-popupToolGroup-handle:hover {
background-color: rgba(41, 98, 204, 0.1);
color: #36c;
}
.oo-ui-popupToolGroup-tools .oo-ui-tool-active.oo-ui-widget-enabled .oo-ui-tool-link .oo-ui-tool-title {
color: #36c;
}
.oo-ui-popupToolGroup-tools .oo-ui-tool.oo-ui-widget-enabled .oo-ui-tool-link:focus {
outline: 0;
box-shadow: inset 0 0 0 2px #36c;
}
.oo-ui-listToolGroup-tools .oo-ui-tool {
display: block;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.oo-ui-listToolGroup-tools .oo-ui-tool.oo-ui-widget-enabled:hover {
background-color: #eaecf0;
color: #000;
}
.oo-ui-listToolGroup-tools .oo-ui-tool-active.oo-ui-widget-enabled {
background-color: #eaf3ff;
}
.oo-ui-listToolGroup-tools .oo-ui-tool-active.oo-ui-widget-enabled:hover {
background-color: rgba(41, 98, 204, 0.1);
}
.oo-ui-listToolGroup-tools .oo-ui-tool-active.oo-ui-widget-enabled .oo-ui-tool-link .oo-ui-tool-title {
color: #36c;
}
.oo-ui-listToolGroup.oo-ui-widget-disabled,
.oo-ui-listToolGroup-tools .oo-ui-tool.oo-ui-widget-disabled .oo-ui-tool-title {
color: #72777d;
}
.oo-ui-menuToolGroup-tools .oo-ui-tool {
display: block;
}
.oo-ui-menuToolGroup .oo-ui-popupToolGroup-handle {
min-width: 140px;
}
.oo-ui-toolbar-narrow .oo-ui-menuToolGroup .oo-ui-popupToolGroup-handle {
min-width: 100px;
}
.oo-ui-menuToolGroup-tools .oo-ui-tool-link .oo-ui-iconElement-icon {
left: 0.78571429em;
}
.oo-ui-toolbar-narrow .oo-ui-menuToolGroup-tools .oo-ui-tool-link .oo-ui-iconElement-icon {
left: 0.71428571em;
}
.oo-ui-menuToolGroup-tools .oo-ui-tool.oo-ui-widget-enabled:hover {
background-color: rgba(41, 98, 204, 0.1);
}
.oo-ui-menuToolGroup-tools .oo-ui-tool.oo-ui-tool-active {
background-color: #eaf3ff;
}
.oo-ui-menuToolGroup.oo-ui-widget-disabled,
.oo-ui-menuToolGroup-tools .oo-ui-tool.oo-ui-widget-disabled .oo-ui-tool-title {
color: #72777d;
}
.oo-ui-toolbar {
clear: both;
}
.oo-ui-toolbar-bar {
line-height: 1;
position: relative;
}
.oo-ui-toolbar-tools,
.oo-ui-toolbar-actions {
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.oo-ui-toolbar-tools {
display: inline;
}
.oo-ui-toolbar-popups {
position: absolute;
}
.oo-ui-toolbar-tools,
.oo-ui-toolbar-popups {
white-space: nowrap;
}
.oo-ui-toolbar-tools .oo-ui-tool,
.oo-ui-toolbar-popups .oo-ui-tool,
.oo-ui-toolbar-tools .oo-ui-popupTool-popup,
.oo-ui-toolbar-popups .oo-ui-popupTool-popup {
white-space: normal;
}
.oo-ui-toolbar-narrow .oo-ui-toolbar-tools,
.oo-ui-toolbar-narrow.oo-ui-toolbar-popups {
white-space: normal;
}
.oo-ui-toolbar-actions {
float: right;
}
.oo-ui-toolbar-actions .oo-ui-toolbar,
.oo-ui-toolbar-actions .oo-ui-buttonElement.oo-ui-labelElement > input.oo-ui-buttonElement-button,
.oo-ui-toolbar-actions .oo-ui-buttonElement.oo-ui-labelElement > .oo-ui-buttonElement-button > .oo-ui-labelElement-label {
display: inline-block;
}
.oo-ui-toolbar-actions .oo-ui-popupWidget {
-webkit-touch-callout: 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;
}
.oo-ui-toolbar-position-top > .oo-ui-toolbar-bar {
border-bottom: 1px solid #c8ccd1;
box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.1);
}
.oo-ui-toolbar-position-bottom > .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;
}
.oo-ui-toolbar-narrow-bar:after {
content: '';
display: block;
position: absolute;
top: 3em;
left: 0;
width: 100%;
height: 0;
}
.oo-ui-toolbar-narrow.oo-ui-toolbar-position-top .oo-ui-toolbar-bar:after {
border-bottom: 1px solid #c8ccd1;
}
.oo-ui-toolbar-narrow.oo-ui-toolbar-position-bottom .oo-ui-toolbar-bar:after {
border-top: 1px solid #c8ccd1;
}
.oo-ui-toolbar-actions > .oo-ui-buttonElement {
margin-right: 0;
}
.oo-ui-toolbar-actions > .oo-ui-buttonElement > .oo-ui-buttonElement-button {
border: 0;
border-radius: 0;
padding-top: 3em;
padding-left: 1.14285714em;
padding-right: 1.14285714em;
}
.oo-ui-toolbar-narrow .oo-ui-toolbar-actions > .oo-ui-buttonElement > .oo-ui-buttonElement-button {
padding-left: 0.85714286em;
padding-right: 0.85714286em;
}
.oo-ui-toolbar-actions > .oo-ui-buttonElement.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:focus {
box-shadow: inset 0 0 0 2px #36c, inset 0 0 0 3px #fff;
}
.oo-ui-toolbar-actions > .oo-ui-buttonElement.oo-ui-labelElement > .oo-ui-buttonElement-button {
padding-top: 1em;
padding-bottom: 0.92857143em;
}
.oo-ui-toolbar-actions > .oo-ui-buttonGroupWidget > .oo-ui-buttonElement > .oo-ui-buttonElement-button {
border-radius: 0;
border-width: 0 0 0 1px;
padding-top: 1em;
padding-bottom: 0.92857143em;
}
.oo-ui-toolbar-actions > .oo-ui-buttonGroupWidget > .oo-ui-popupToolGroup.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive > .oo-ui-popupToolGroup-handle {
color: #fff;
background-color: #36c;
border-color: #36c;
}
.oo-ui-toolbar-actions > .oo-ui-buttonGroupWidget > .oo-ui-popupToolGroup.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive > .oo-ui-popupToolGroup-handle:hover {
background-color: #447ff5;
border-color: #447ff5;
}
.oo-ui-toolbar-actions > .oo-ui-buttonGroupWidget > .oo-ui-popupToolGroup.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive > .oo-ui-popupToolGroup-handle:active,
.oo-ui-toolbar-actions > .oo-ui-buttonGroupWidget > .oo-ui-popupToolGroup.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive > .oo-ui-popupToolGroup-handle:active:focus,
.oo-ui-toolbar-actions > .oo-ui-buttonGroupWidget > .oo-ui-popupToolGroup.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive.oo-ui-buttonElement-pressed > .oo-ui-popupToolGroup-handle,
.oo-ui-toolbar-actions > .oo-ui-buttonGroupWidget > .oo-ui-popupToolGroup.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive.oo-ui-buttonElement-active > .oo-ui-popupToolGroup-handle,
.oo-ui-toolbar-actions > .oo-ui-buttonGroupWidget > .oo-ui-popupToolGroup.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive.oo-ui-popupToolGroup-active > .oo-ui-popupToolGroup-handle {
color: #fff;
background-color: #2a4b8d;
border-color: #2a4b8d;
box-shadow: none;
}
.oo-ui-toolbar-actions > .oo-ui-buttonGroupWidget > .oo-ui-popupToolGroup.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive > .oo-ui-popupToolGroup-handle:focus {
border-color: #36c;
box-shadow: inset 0 0 0 1px #36c, inset 0 0 0 2px #fff;
}
| joeyparrish/cdnjs | ajax/libs/oojs-ui/0.27.2/oojs-ui-toolbars-wikimediaui.css | CSS | mit | 19,286 |
define(
//begin v1.x content
{
"field-quarter-short-relative+0": "detta kv.",
"field-quarter-short-relative+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",
"field-month-narrow-relative+-1": "förra mån.",
"field-tue-narrow-relative+0": "denna tis.",
"field-tue-narrow-relative+1": "nästa tis.",
"field-thu-short-relative+0": "tors. denna vecka",
"field-day-short-relative+-1": "i går",
"field-thu-short-relative+1": "tors. nästa vecka",
"field-day-relative+0": "i dag",
"field-day-short-relative+-2": "i förrgår",
"field-day-relative+1": "i morgon",
"field-week-narrow-relative+0": "denna v.",
"field-day-relative+2": "i övermorgon",
"field-week-narrow-relative+1": "nästa v.",
"field-wed-narrow-relative+-1": "förra ons.",
"field-year-narrow": "år",
"field-era-short": "era",
"field-year-narrow-relative+0": "i år",
"field-tue-relative+0": "tisdag denna vecka",
"field-year-narrow-relative+1": "nästa år",
"field-tue-relative+1": "tisdag nästa vecka",
"field-weekdayOfMonth": "veckodag i månad",
"field-second-short": "sek",
"field-weekdayOfMonth-narrow": "veckodag i mån.",
"field-week-relative+0": "denna vecka",
"field-month-relative+0": "denna månad",
"field-week-relative+1": "nästa vecka",
"field-month-relative+1": "nästa månad",
"field-sun-narrow-relative+0": "denna sön.",
"field-mon-short-relative+0": "mån. denna vecka",
"field-sun-narrow-relative+1": "nästa sön.",
"field-mon-short-relative+1": "mån. nästa vecka",
"field-second-relative+0": "nu",
"field-weekOfMonth": "vecka i månaden",
"field-month-short": "m",
"field-day": "dag",
"field-dayOfYear-short": "dag under året",
"field-year-relative+-1": "i fjol",
"field-sat-short-relative+-1": "lör. förra veckan",
"field-hour-relative+0": "denna timme",
"field-second-short-relative+0": "nu",
"field-wed-relative+-1": "onsdag förra veckan",
"field-sat-narrow-relative+-1": "förra lör.",
"field-second": "sekund",
"field-hour-short-relative+0": "denna timme",
"field-quarter": "kvartal",
"field-week-short": "v",
"field-day-narrow-relative+0": "idag",
"field-day-narrow-relative+1": "imorgon",
"field-day-narrow-relative+2": "i övermorgon",
"field-tue-short-relative+0": "tis. denna vecka",
"field-tue-short-relative+1": "tis. nästa vecka",
"field-month-short-relative+-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",
"field-sat-short-relative+0": "lör. denna vecka",
"field-sat-short-relative+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",
"field-day-narrow-relative+-1": "igår",
"field-year-short": "år",
"field-day-narrow-relative+-2": "i förrgår",
"field-quarter-relative+-1": "förra kvartalet",
"field-dayperiod-narrow": "fm/em",
"field-week-narrow-relative+-1": "förra v.",
"field-dayOfYear": "dag under året",
"field-sat-relative+-1": "lördag förra veckan",
"field-hour": "timme",
"field-minute-narrow-relative+0": "denna minut",
"field-month-relative+-1": "förra månaden",
"field-quarter-short": "kv.",
"field-sat-narrow-relative+0": "denna lör.",
"field-fri-relative+0": "fredag denna vecka",
"field-sat-narrow-relative+1": "nästa lör.",
"field-fri-relative+1": "fredag nästa vecka",
"field-month-narrow-relative+0": "denna mån.",
"field-month-narrow-relative+1": "nästa mån.",
"field-sun-short-relative+0": "sön. denna vecka",
"field-sun-short-relative+1": "sön. nästa vecka",
"field-week-relative+-1": "förra veckan",
"field-quarter-short-relative+-1": "förra kv.",
"field-minute-short-relative+0": "denna minut",
"field-quarter-relative+0": "detta kvartal",
"field-minute-relative+0": "denna minut",
"field-quarter-relative+1": "nästa kvartal",
"field-wed-short-relative+-1": "ons. förra veckan",
"field-thu-short-relative+-1": "tors. förra veckan",
"field-year-narrow-relative+-1": "i fjol",
"field-thu-narrow-relative+-1": "förra tors.",
"field-tue-narrow-relative+-1": "förra tis.",
"field-weekOfMonth-short": "vk. i mån.",
"field-wed-short-relative+0": "ons. denna vecka",
"field-wed-short-relative+1": "ons. nästa vecka",
"field-sun-relative+-1": "söndag förra veckan",
"field-second-narrow-relative+0": "nu",
"field-weekday": "veckodag",
"field-day-short-relative+0": "i dag",
"field-quarter-narrow-relative+0": "detta kv.",
"field-sat-relative+0": "lördag denna vecka",
"field-day-short-relative+1": "i morgon",
"field-quarter-narrow-relative+1": "nästa kv.",
"field-sat-relative+1": "lördag nästa vecka",
"field-day-short-relative+2": "i övermorgon",
"field-week-short-relative+0": "denna v.",
"field-week-short-relative+1": "nästa v.",
"field-dayOfYear-narrow": "dag under året",
"field-month-short-relative+0": "denna mån.",
"field-month-short-relative+1": "nästa mån.",
"field-weekdayOfMonth-short": "veckodag i mån.",
"field-zone-narrow": "tidszon",
"field-thu-narrow-relative+0": "denna tors.",
"field-thu-narrow-relative+1": "nästa tors.",
"field-sun-narrow-relative+-1": "förra sön.",
"field-mon-short-relative+-1": "mån. förra veckan",
"field-thu-relative+0": "torsdag denna vecka",
"field-thu-relative+1": "torsdag nästa vecka",
"field-fri-short-relative+-1": "fre. förra veckan",
"field-thu-relative+-1": "torsdag förra veckan",
"field-week": "vecka",
"field-wed-narrow-relative+0": "denna ons.",
"field-wed-narrow-relative+1": "nästa ons.",
"field-quarter-narrow-relative+-1": "förra kv.",
"field-year-short-relative+0": "i år",
"field-dayperiod-short": "fm/em",
"field-year-short-relative+1": "nästa år",
"field-fri-short-relative+0": "fre. denna vecka",
"field-fri-short-relative+1": "fre. nästa vecka",
"field-week-short-relative+-1": "förra v.",
"field-hour-narrow-relative+0": "denna timme",
"field-hour-short": "tim",
"field-zone-short": "tidszon",
"field-month-narrow": "mån",
"field-hour-narrow": "h",
"field-fri-narrow-relative+-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",
"field-tue-short-relative+-1": "tis. förra veckan",
"field-minute-narrow": "m",
"field-year-short-relative+-1": "i fjol",
"field-zone": "tidszon",
"field-weekOfMonth-narrow": "vk.i mån.",
"field-weekday-narrow": "veckodag",
"field-quarter-narrow": "kv.",
"field-sun-short-relative+-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",
"field-fri-narrow-relative+0": "denna fre.",
"field-fri-narrow-relative+1": "nästa fre."
}
//end v1.x content
); | cdnjs/cdnjs | ajax/libs/dojo/1.17.1/cldr/nls/sv/dangi.js | JavaScript | mit | 7,152 |
/**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.dsmr.internal.device;
import java.util.concurrent.ScheduledExecutorService;
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.DSMRConnectorErrorEvent;
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 DSMRSerialAutoDevice implements DSMRDevice, DSMREventListener {
/**
* Enum to keep track of the internal state of {@link DSMRSerialAutoDevice}.
*/
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 SWITCHING_BAUDRATE_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(5);
/**
* This factor is multiplied with the {@link #baudrateSwitchTimeoutSeconds} and used as the duration the discovery
* of the baudrate may take.
*/
private static final int DISCOVER_TIMEOUT_FACTOR = 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 DEFAULT_PORT_SETTINGS = DSMRSerialSettings.HIGH_SPEED_SETTINGS;
private final Logger logger = LoggerFactory.getLogger(DSMRSerialAutoDevice.class);
/**
* DSMR Connector to the serial port
*/
private final DSMRSerialConnector dsmrConnector;
private final ScheduledExecutorService scheduler;
private final DSMRTelegramListener telegramListener;
/**
* Time in seconds in which period valid data is expected during discovery. If exceeded without success the baudrate
* is switched
*/
private final int baudrateSwitchTimeoutSeconds;
/**
* Serial port connection settings
*/
private DSMRSerialSettings portSettings = DEFAULT_PORT_SETTINGS;
/**
* 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 #SWITCHING_BAUDRATE_TIMEOUT_NANOS}.
*/
private long lastSwitchedBaudrateNanos;
/**
* Creates a new {@link DSMRSerialAutoDevice}
*
* @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 baudrateSwitchTimeoutSeconds timeout period for when to try other baudrate settings and end the discovery
* of the baudrate
*/
public DSMRSerialAutoDevice(SerialPortManager serialPortManager, String serialPortName, DSMREventListener listener,
ScheduledExecutorService scheduler, int baudrateSwitchTimeoutSeconds) {
this.parentListener = listener;
this.scheduler = scheduler;
this.baudrateSwitchTimeoutSeconds = baudrateSwitchTimeoutSeconds;
telegramListener = new DSMRTelegramListener(listener);
dsmrConnector = new DSMRSerialConnector(serialPortManager, serialPortName, telegramListener);
logger.debug("Initialized port '{}'", serialPortName);
}
@Override
public void start() {
stopDiscover(DeviceState.DISCOVER_SETTINGS);
portSettings = DEFAULT_PORT_SETTINGS;
telegramListener.setDsmrEventListener(this);
dsmrConnector.open(portSettings);
restartHalfTimer();
endTimeTimer = scheduler.schedule(this::endTimeScheduledCall,
baudrateSwitchTimeoutSeconds * DISCOVER_TIMEOUT_FACTOR, 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 handleTelegramReceived(P1Telegram telegram) {
if (!telegram.getCosemObjects().isEmpty()) {
stopDiscover(DeviceState.NORMAL);
parentListener.handleTelegramReceived(telegram);
logger.info("Start receiving telegrams on port {} with settings: {}", dsmrConnector.getPortName(),
portSettings);
}
}
/**
* Event handler for DSMR Port events.
*
* @param portEvent {@link DSMRConnectorErrorEvent} to handle
*/
@Override
public void handleErrorEvent(DSMRConnectorErrorEvent portEvent) {
logger.trace("Received portEvent {}", portEvent.getEventDetails());
if (portEvent == DSMRConnectorErrorEvent.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 (lastSwitchedBaudrateNanos + SWITCHING_BAUDRATE_TIMEOUT_NANOS > System.nanoTime()) {
// Ignore switching baudrate if this is called within the timeout after a previous switch.
return;
}
lastSwitchedBaudrateNanos = 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 endTimeScheduledCall() {
if (state == DeviceState.DISCOVER_SETTINGS) {
stopDiscover(DeviceState.ERROR);
parentListener.handleErrorEvent(DSMRConnectorErrorEvent.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.setDsmrEventListener(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, baudrateSwitchTimeoutSeconds, TimeUnit.SECONDS);
}
}
| afuechsel/openhab2 | addons/binding/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/DSMRSerialAutoDevice.java | Java | epl-1.0 | 9,975 |
/**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.yamahareceiver.internal.state;
import static org.openhab.binding.yamahareceiver.YamahaReceiverBindingConstants.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;
}
| johannrichard/openhab2-addons | addons/binding/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/state/ZoneControlState.java | Java | epl-1.0 | 1,158 |
/**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.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 NikoHomeControlMessageDeserializer} 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;
}
}
| aogorek/openhab2-addons | addons/binding/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/NhcMessageBase.java | Java | epl-1.0 | 1,148 |
/*
*/
#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
__i8259a_disable_irq(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);
__i8259a_disable_irq(d->irq);
spin_unlock(&i8259_irq_lock);
}
void
i8259a_mask_and_ack_irq(struct irq_data *d)
{
unsigned int irq = d->irq;
spin_lock(&i8259_irq_lock);
__i8259a_disable_irq(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 = i8259a_mask_and_ack_irq,
};
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++) {
irq_set_chip_and_handler(i, &i8259a_irq_type, handle_level_irq);
}
setup_irq(2, &cascade);
}
#if defined(CONFIG_ALPHA_GENERIC)
# 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(CONFIG_ALPHA_TSUNAMI)
# define IACK_SC TSUNAMI_IACK_SC
#elif defined(CONFIG_ALPHA_IRONGATE)
# define IACK_SC IRONGATE_IACK_SC
#endif
/*
*/
#if defined(IACK_SC)
void
isa_device_interrupt(unsigned long vector)
{
/*
*/
int j = *(vuip) IACK_SC;
j &= 0xff;
handle_irq(j);
}
#endif
#if defined(CONFIG_ALPHA_GENERIC) || !defined(IACK_SC)
void
isa_no_iack_sc_device_interrupt(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
| holyangel/LGE_G3 | arch/alpha/kernel/irq_i8259.c | C | gpl-2.0 | 3,962 |
/*
* (C) Copyright IBM Deutschland Entwicklung GmbH 2006
*
* Author: Maxim Shchetynin <maxim@de.ibm.com>
*
* Axon DDR2 device driver.
* It registers one block device per Axon's DDR2 memory bank found on a system.
* Block devices are called axonram?, their major and minor numbers are
* available in /proc/devices, /proc/partitions or in /sys/block/axonram?/dev.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#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 AXON_RAM_MODULE_NAME "axonram"
#define AXON_RAM_DEVICE_NAME "axonram"
#define AXON_RAM_MINORS_PER_DISK 16
#define AXON_RAM_BLOCK_SHIFT PAGE_SHIFT
#define AXON_RAM_BLOCK_SIZE 1 << AXON_RAM_BLOCK_SHIFT
#define AXON_RAM_SECTOR_SHIFT 9
#define AXON_RAM_SECTOR_SIZE 1 << AXON_RAM_SECTOR_SHIFT
#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
axon_ram_irq_handler(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
axon_ram_make_request(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 << AXON_RAM_SECTOR_SHIFT);
phys_end = bank->io_addr + bank->size;
transfered = 0;
bio_for_each_segment(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
axon_ram_direct_access(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 <<= AXON_RAM_SECTOR_SHIFT;
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 block_device_operations axon_ram_devops = {
.owner = THIS_MODULE,
.direct_access = axon_ram_direct_access
};
/*
*/
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 (of_address_to_resource(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",
AXON_RAM_DEVICE_NAME, axon_ram_bank_id);
rc = -ENODEV;
goto failed;
}
dev_info(&device->dev, "Register DDR2 memory device %s%d with %luMB\n",
AXON_RAM_DEVICE_NAME, 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(AXON_RAM_MINORS_PER_DISK);
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",
AXON_RAM_DEVICE_NAME, 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 >> AXON_RAM_SECTOR_SHIFT);
blk_queue_make_request(bank->disk->queue, axon_ram_make_request);
blk_queue_logical_block_size(bank->disk->queue, AXON_RAM_SECTOR_SIZE);
add_disk(bank->disk);
bank->irq_id = irq_of_parse_and_map(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, axon_ram_irq_handler,
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 = AXON_RAM_MODULE_NAME,
.owner = THIS_MODULE,
.of_match_table = axon_ram_device_id,
},
};
/*
*/
static int __init
axon_ram_init(void)
{
azfs_major = register_blkdev(azfs_major, AXON_RAM_DEVICE_NAME);
if (azfs_major < 0) {
printk(KERN_ERR "%s cannot become block device major number\n",
AXON_RAM_MODULE_NAME);
return -EFAULT;
}
azfs_minor = 0;
return platform_driver_register(&axon_ram_driver);
}
/*
*/
static void __exit
axon_ram_exit(void)
{
platform_driver_unregister(&axon_ram_driver);
unregister_blkdev(azfs_major, AXON_RAM_DEVICE_NAME);
}
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");
| curbthepain/revkernel_us990 | arch/powerpc/sysdev/axonram.c | C | gpl-2.0 | 9,433 |
/*
* Copyright (C) 2012-2013 JadeCore <http://www.pandashan.com/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#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();
}
| DeActiveDev/Core | src/server/scripts/Pandaria/HeartOfFear/boss_unsok.cpp | C++ | gpl-2.0 | 1,576 |
// Copyright 2015 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#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
{
// --- GameCube keyboard ---
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 & KEYMASK_QUESTIONMARK)
{
key[keys_held++] = KEY_QUESTIONMARK;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_INTERNATIONAL1)
{
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 & KEYMASK_RIGHTWINDOWS)
{
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
| TwitchPlaysPokemon/dolphinWatch | Source/Core/Core/HW/SI/SI_DeviceKeyboard.cpp | C++ | gpl-2.0 | 13,504 |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/namei.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/namei.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
* Directory entry file type support and forward compatibility hooks
* for B-tree directories by Theodore Ts'o (tytso@mit.edu), 1998
* Hash Tree Directory indexing (c)
* Daniel Phillips, 2001
* Hash Tree Directory indexing porting
* Christopher Li, 2002
* Hash Tree Directory indexing cleanup
* Theodore Ts'o, 2002
*/
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/time.h>
#include <linux/fcntl.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/quotaops.h>
#include <linux/buffer_head.h>
#include <linux/bio.h>
#include "ext4.h"
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include <trace/events/ext4.h>
/*
* define how far ahead to read directories while searching them.
*/
#define NAMEI_RA_CHUNKS 2
#define NAMEI_RA_BLOCKS 4
#define NAMEI_RA_SIZE (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
static struct buffer_head *ext4_append(handle_t *handle,
struct inode *inode,
ext4_lblk_t *block)
{
struct buffer_head *bh;
int err;
if (unlikely(EXT4_SB(inode->i_sb)->s_max_dir_size_kb &&
((inode->i_size >> 10) >=
EXT4_SB(inode->i_sb)->s_max_dir_size_kb)))
return ERR_PTR(-ENOSPC);
*block = inode->i_size >> inode->i_sb->s_blocksize_bits;
bh = ext4_bread(handle, inode, *block, EXT4_GET_BLOCKS_CREATE);
if (IS_ERR(bh))
return bh;
inode->i_size += inode->i_sb->s_blocksize;
EXT4_I(inode)->i_disksize = inode->i_size;
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, bh);
if (err) {
brelse(bh);
ext4_std_error(inode->i_sb, err);
return ERR_PTR(err);
}
return bh;
}
static int ext4_dx_csum_verify(struct inode *inode,
struct ext4_dir_entry *dirent);
typedef enum {
EITHER, INDEX, DIRENT
} dirblock_type_t;
#define ext4_read_dirblock(inode, block, type) \
__ext4_read_dirblock((inode), (block), (type), __func__, __LINE__)
static struct buffer_head *__ext4_read_dirblock(struct inode *inode,
ext4_lblk_t block,
dirblock_type_t type,
const char *func,
unsigned int line)
{
struct buffer_head *bh;
struct ext4_dir_entry *dirent;
int is_dx_block = 0;
bh = ext4_bread(NULL, inode, block, 0);
if (IS_ERR(bh)) {
__ext4_warning(inode->i_sb, func, line,
"inode #%lu: lblock %lu: comm %s: "
"error %ld reading directory block",
inode->i_ino, (unsigned long)block,
current->comm, PTR_ERR(bh));
return bh;
}
if (!bh) {
ext4_error_inode(inode, func, line, block,
"Directory hole found");
return ERR_PTR(-EFSCORRUPTED);
}
dirent = (struct ext4_dir_entry *) bh->b_data;
/* Determine whether or not we have an index block */
if (is_dx(inode)) {
if (block == 0)
is_dx_block = 1;
else if (ext4_rec_len_from_disk(dirent->rec_len,
inode->i_sb->s_blocksize) ==
inode->i_sb->s_blocksize)
is_dx_block = 1;
}
if (!is_dx_block && type == INDEX) {
ext4_error_inode(inode, func, line, block,
"directory leaf block found instead of index block");
return ERR_PTR(-EFSCORRUPTED);
}
if (!ext4_has_metadata_csum(inode->i_sb) ||
buffer_verified(bh))
return bh;
/*
* An empty leaf block can get mistaken for a index block; for
* this reason, we can only check the index checksum when the
* caller is sure it should be an index block.
*/
if (is_dx_block && type == INDEX) {
if (ext4_dx_csum_verify(inode, dirent))
set_buffer_verified(bh);
else {
ext4_error_inode(inode, func, line, block,
"Directory index failed checksum");
brelse(bh);
return ERR_PTR(-EFSBADCRC);
}
}
if (!is_dx_block) {
if (ext4_dirent_csum_verify(inode, dirent))
set_buffer_verified(bh);
else {
ext4_error_inode(inode, func, line, block,
"Directory block failed checksum");
brelse(bh);
return ERR_PTR(-EFSBADCRC);
}
}
return bh;
}
#ifndef assert
#define assert(test) J_ASSERT(test)
#endif
#ifdef DX_DEBUG
#define dxtrace(command) command
#else
#define dxtrace(command)
#endif
struct fake_dirent
{
__le32 inode;
__le16 rec_len;
u8 name_len;
u8 file_type;
};
struct dx_countlimit
{
__le16 limit;
__le16 count;
};
struct dx_entry
{
__le32 hash;
__le32 block;
};
/*
* dx_root_info is laid out so that if it should somehow get overlaid by a
* dirent the two low bits of the hash version will be zero. Therefore, the
* hash version mod 4 should never be 0. Sincerely, the paranoia department.
*/
struct dx_root
{
struct fake_dirent dot;
char dot_name[4];
struct fake_dirent dotdot;
char dotdot_name[4];
struct dx_root_info
{
__le32 reserved_zero;
u8 hash_version;
u8 info_length; /* 8 */
u8 indirect_levels;
u8 unused_flags;
}
info;
struct dx_entry entries[0];
};
struct dx_node
{
struct fake_dirent fake;
struct dx_entry entries[0];
};
struct dx_frame
{
struct buffer_head *bh;
struct dx_entry *entries;
struct dx_entry *at;
};
struct dx_map_entry
{
u32 hash;
u16 offs;
u16 size;
};
/*
* This goes at the end of each htree block.
*/
struct dx_tail {
u32 dt_reserved;
__le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */
};
static inline ext4_lblk_t dx_get_block(struct dx_entry *entry);
static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value);
static inline unsigned dx_get_hash(struct dx_entry *entry);
static void dx_set_hash(struct dx_entry *entry, unsigned value);
static unsigned dx_get_count(struct dx_entry *entries);
static unsigned dx_get_limit(struct dx_entry *entries);
static void dx_set_count(struct dx_entry *entries, unsigned value);
static void dx_set_limit(struct dx_entry *entries, unsigned value);
static unsigned dx_root_limit(struct inode *dir, unsigned infosize);
static unsigned dx_node_limit(struct inode *dir);
static struct dx_frame *dx_probe(struct ext4_filename *fname,
struct inode *dir,
struct dx_hash_info *hinfo,
struct dx_frame *frame);
static void dx_release(struct dx_frame *frames);
static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
unsigned blocksize, struct dx_hash_info *hinfo,
struct dx_map_entry map[]);
static void dx_sort_map(struct dx_map_entry *map, unsigned count);
static struct ext4_dir_entry_2 *dx_move_dirents(char *from, char *to,
struct dx_map_entry *offsets, int count, unsigned blocksize);
static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize);
static void dx_insert_block(struct dx_frame *frame,
u32 hash, ext4_lblk_t block);
static int ext4_htree_next_block(struct inode *dir, __u32 hash,
struct dx_frame *frame,
struct dx_frame *frames,
__u32 *start_hash);
static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
struct ext4_filename *fname,
struct ext4_dir_entry_2 **res_dir);
static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
struct inode *dir, struct inode *inode);
/* checksumming functions */
void initialize_dirent_tail(struct ext4_dir_entry_tail *t,
unsigned int blocksize)
{
memset(t, 0, sizeof(struct ext4_dir_entry_tail));
t->det_rec_len = ext4_rec_len_to_disk(
sizeof(struct ext4_dir_entry_tail), blocksize);
t->det_reserved_ft = EXT4_FT_DIR_CSUM;
}
/* Walk through a dirent block to find a checksum "dirent" at the tail */
static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode,
struct ext4_dir_entry *de)
{
struct ext4_dir_entry_tail *t;
#ifdef PARANOID
struct ext4_dir_entry *d, *top;
d = de;
top = (struct ext4_dir_entry *)(((void *)de) +
(EXT4_BLOCK_SIZE(inode->i_sb) -
sizeof(struct ext4_dir_entry_tail)));
while (d < top && d->rec_len)
d = (struct ext4_dir_entry *)(((void *)d) +
le16_to_cpu(d->rec_len));
if (d != top)
return NULL;
t = (struct ext4_dir_entry_tail *)d;
#else
t = EXT4_DIRENT_TAIL(de, EXT4_BLOCK_SIZE(inode->i_sb));
#endif
if (t->det_reserved_zero1 ||
le16_to_cpu(t->det_rec_len) != sizeof(struct ext4_dir_entry_tail) ||
t->det_reserved_zero2 ||
t->det_reserved_ft != EXT4_FT_DIR_CSUM)
return NULL;
return t;
}
static __le32 ext4_dirent_csum(struct inode *inode,
struct ext4_dir_entry *dirent, int size)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
__u32 csum;
csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
return cpu_to_le32(csum);
}
#define warn_no_space_for_csum(inode) \
__warn_no_space_for_csum((inode), __func__, __LINE__)
static void __warn_no_space_for_csum(struct inode *inode, const char *func,
unsigned int line)
{
__ext4_warning_inode(inode, func, line,
"No space for directory leaf checksum. Please run e2fsck -D.");
}
int ext4_dirent_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent)
{
struct ext4_dir_entry_tail *t;
if (!ext4_has_metadata_csum(inode->i_sb))
return 1;
t = get_dirent_tail(inode, dirent);
if (!t) {
warn_no_space_for_csum(inode);
return 0;
}
if (t->det_checksum != ext4_dirent_csum(inode, dirent,
(void *)t - (void *)dirent))
return 0;
return 1;
}
static void ext4_dirent_csum_set(struct inode *inode,
struct ext4_dir_entry *dirent)
{
struct ext4_dir_entry_tail *t;
if (!ext4_has_metadata_csum(inode->i_sb))
return;
t = get_dirent_tail(inode, dirent);
if (!t) {
warn_no_space_for_csum(inode);
return;
}
t->det_checksum = ext4_dirent_csum(inode, dirent,
(void *)t - (void *)dirent);
}
int ext4_handle_dirty_dirent_node(handle_t *handle,
struct inode *inode,
struct buffer_head *bh)
{
ext4_dirent_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
return ext4_handle_dirty_metadata(handle, inode, bh);
}
static struct dx_countlimit *get_dx_countlimit(struct inode *inode,
struct ext4_dir_entry *dirent,
int *offset)
{
struct ext4_dir_entry *dp;
struct dx_root_info *root;
int count_offset;
if (le16_to_cpu(dirent->rec_len) == EXT4_BLOCK_SIZE(inode->i_sb))
count_offset = 8;
else if (le16_to_cpu(dirent->rec_len) == 12) {
dp = (struct ext4_dir_entry *)(((void *)dirent) + 12);
if (le16_to_cpu(dp->rec_len) !=
EXT4_BLOCK_SIZE(inode->i_sb) - 12)
return NULL;
root = (struct dx_root_info *)(((void *)dp + 12));
if (root->reserved_zero ||
root->info_length != sizeof(struct dx_root_info))
return NULL;
count_offset = 32;
} else
return NULL;
if (offset)
*offset = count_offset;
return (struct dx_countlimit *)(((void *)dirent) + count_offset);
}
static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent,
int count_offset, int count, struct dx_tail *t)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
__u32 csum;
int size;
__u32 dummy_csum = 0;
int offset = offsetof(struct dx_tail, dt_checksum);
size = count_offset + (count * sizeof(struct dx_entry));
csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
csum = ext4_chksum(sbi, csum, (__u8 *)t, offset);
csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
return cpu_to_le32(csum);
}
static int ext4_dx_csum_verify(struct inode *inode,
struct ext4_dir_entry *dirent)
{
struct dx_countlimit *c;
struct dx_tail *t;
int count_offset, limit, count;
if (!ext4_has_metadata_csum(inode->i_sb))
return 1;
c = get_dx_countlimit(inode, dirent, &count_offset);
if (!c) {
EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
return 0;
}
limit = le16_to_cpu(c->limit);
count = le16_to_cpu(c->count);
if (count_offset + (limit * sizeof(struct dx_entry)) >
EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
warn_no_space_for_csum(inode);
return 0;
}
t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset,
count, t))
return 0;
return 1;
}
static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent)
{
struct dx_countlimit *c;
struct dx_tail *t;
int count_offset, limit, count;
if (!ext4_has_metadata_csum(inode->i_sb))
return;
c = get_dx_countlimit(inode, dirent, &count_offset);
if (!c) {
EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
return;
}
limit = le16_to_cpu(c->limit);
count = le16_to_cpu(c->count);
if (count_offset + (limit * sizeof(struct dx_entry)) >
EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
warn_no_space_for_csum(inode);
return;
}
t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t);
}
static inline int ext4_handle_dirty_dx_node(handle_t *handle,
struct inode *inode,
struct buffer_head *bh)
{
ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
return ext4_handle_dirty_metadata(handle, inode, bh);
}
/*
* p is at least 6 bytes before the end of page
*/
static inline struct ext4_dir_entry_2 *
ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
{
return (struct ext4_dir_entry_2 *)((char *)p +
ext4_rec_len_from_disk(p->rec_len, blocksize));
}
/*
* Future: use high four bits of block for coalesce-on-delete flags
* Mask them off for now.
*/
static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
{
return le32_to_cpu(entry->block) & 0x0fffffff;
}
static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
{
entry->block = cpu_to_le32(value);
}
static inline unsigned dx_get_hash(struct dx_entry *entry)
{
return le32_to_cpu(entry->hash);
}
static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
{
entry->hash = cpu_to_le32(value);
}
static inline unsigned dx_get_count(struct dx_entry *entries)
{
return le16_to_cpu(((struct dx_countlimit *) entries)->count);
}
static inline unsigned dx_get_limit(struct dx_entry *entries)
{
return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
}
static inline void dx_set_count(struct dx_entry *entries, unsigned value)
{
((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
}
static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
{
((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
}
static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
{
unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) -
EXT4_DIR_REC_LEN(2) - infosize;
if (ext4_has_metadata_csum(dir->i_sb))
entry_space -= sizeof(struct dx_tail);
return entry_space / sizeof(struct dx_entry);
}
static inline unsigned dx_node_limit(struct inode *dir)
{
unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0);
if (ext4_has_metadata_csum(dir->i_sb))
entry_space -= sizeof(struct dx_tail);
return entry_space / sizeof(struct dx_entry);
}
/*
* Debug
*/
#ifdef DX_DEBUG
static void dx_show_index(char * label, struct dx_entry *entries)
{
int i, n = dx_get_count (entries);
printk(KERN_DEBUG "%s index", label);
for (i = 0; i < n; i++) {
printk(KERN_CONT " %x->%lu",
i ? dx_get_hash(entries + i) : 0,
(unsigned long)dx_get_block(entries + i));
}
printk(KERN_CONT "\n");
}
struct stats
{
unsigned names;
unsigned space;
unsigned bcount;
};
static struct stats dx_show_leaf(struct inode *dir,
struct dx_hash_info *hinfo,
struct ext4_dir_entry_2 *de,
int size, int show_names)
{
unsigned names = 0, space = 0;
char *base = (char *) de;
struct dx_hash_info h = *hinfo;
printk("names: ");
while ((char *) de < base + size)
{
if (de->inode)
{
if (show_names)
{
#ifdef CONFIG_EXT4_FS_ENCRYPTION
int len;
char *name;
struct fscrypt_str fname_crypto_str =
FSTR_INIT(NULL, 0);
int res = 0;
name = de->name;
len = de->name_len;
if (ext4_encrypted_inode(dir))
res = fscrypt_get_encryption_info(dir);
if (res) {
printk(KERN_WARNING "Error setting up"
" fname crypto: %d\n", res);
}
if (!fscrypt_has_encryption_key(dir)) {
/* Directory is not encrypted */
ext4fs_dirhash(de->name,
de->name_len, &h);
printk("%*.s:(U)%x.%u ", len,
name, h.hash,
(unsigned) ((char *) de
- base));
} else {
struct fscrypt_str de_name =
FSTR_INIT(name, len);
/* Directory is encrypted */
res = fscrypt_fname_alloc_buffer(
dir, len,
&fname_crypto_str);
if (res)
printk(KERN_WARNING "Error "
"allocating crypto "
"buffer--skipping "
"crypto\n");
res = fscrypt_fname_disk_to_usr(dir,
0, 0, &de_name,
&fname_crypto_str);
if (res) {
printk(KERN_WARNING "Error "
"converting filename "
"from disk to usr"
"\n");
name = "??";
len = 2;
} else {
name = fname_crypto_str.name;
len = fname_crypto_str.len;
}
ext4fs_dirhash(de->name, de->name_len,
&h);
printk("%*.s:(E)%x.%u ", len, name,
h.hash, (unsigned) ((char *) de
- base));
fscrypt_fname_free_buffer(
&fname_crypto_str);
}
#else
int len = de->name_len;
char *name = de->name;
ext4fs_dirhash(de->name, de->name_len, &h);
printk("%*.s:%x.%u ", len, name, h.hash,
(unsigned) ((char *) de - base));
#endif
}
space += EXT4_DIR_REC_LEN(de->name_len);
names++;
}
de = ext4_next_entry(de, size);
}
printk(KERN_CONT "(%i)\n", names);
return (struct stats) { names, space, 1 };
}
struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
struct dx_entry *entries, int levels)
{
unsigned blocksize = dir->i_sb->s_blocksize;
unsigned count = dx_get_count(entries), names = 0, space = 0, i;
unsigned bcount = 0;
struct buffer_head *bh;
printk("%i indexed blocks...\n", count);
for (i = 0; i < count; i++, entries++)
{
ext4_lblk_t block = dx_get_block(entries);
ext4_lblk_t hash = i ? dx_get_hash(entries): 0;
u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
struct stats stats;
printk("%s%3u:%03u hash %8x/%8x ",levels?"":" ", i, block, hash, range);
bh = ext4_bread(NULL,dir, block, 0);
if (!bh || IS_ERR(bh))
continue;
stats = levels?
dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *)
bh->b_data, blocksize, 0);
names += stats.names;
space += stats.space;
bcount += stats.bcount;
brelse(bh);
}
if (bcount)
printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
levels ? "" : " ", names, space/bcount,
(space/bcount)*100/blocksize);
return (struct stats) { names, space, bcount};
}
#endif /* DX_DEBUG */
/*
* Probe for a directory leaf block to search.
*
* dx_probe can return ERR_BAD_DX_DIR, which means there was a format
* error in the directory index, and the caller should fall back to
* searching the directory normally. The callers of dx_probe **MUST**
* check for this error code, and make sure it never gets reflected
* back to userspace.
*/
static struct dx_frame *
dx_probe(struct ext4_filename *fname, struct inode *dir,
struct dx_hash_info *hinfo, struct dx_frame *frame_in)
{
unsigned count, indirect;
struct dx_entry *at, *entries, *p, *q, *m;
struct dx_root *root;
struct dx_frame *frame = frame_in;
struct dx_frame *ret_err = ERR_PTR(ERR_BAD_DX_DIR);
u32 hash;
memset(frame_in, 0, EXT4_HTREE_LEVEL * sizeof(frame_in[0]));
frame->bh = ext4_read_dirblock(dir, 0, INDEX);
if (IS_ERR(frame->bh))
return (struct dx_frame *) frame->bh;
root = (struct dx_root *) frame->bh->b_data;
if (root->info.hash_version != DX_HASH_TEA &&
root->info.hash_version != DX_HASH_HALF_MD4 &&
root->info.hash_version != DX_HASH_LEGACY) {
ext4_warning_inode(dir, "Unrecognised inode hash code %u",
root->info.hash_version);
goto fail;
}
if (fname)
hinfo = &fname->hinfo;
hinfo->hash_version = root->info.hash_version;
if (hinfo->hash_version <= DX_HASH_TEA)
hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
if (fname && fname_name(fname))
ext4fs_dirhash(fname_name(fname), fname_len(fname), hinfo);
hash = hinfo->hash;
if (root->info.unused_flags & 1) {
ext4_warning_inode(dir, "Unimplemented hash flags: %#06x",
root->info.unused_flags);
goto fail;
}
indirect = root->info.indirect_levels;
if (indirect >= ext4_dir_htree_level(dir->i_sb)) {
ext4_warning(dir->i_sb,
"Directory (ino: %lu) htree depth %#06x exceed"
"supported value", dir->i_ino,
ext4_dir_htree_level(dir->i_sb));
if (ext4_dir_htree_level(dir->i_sb) < EXT4_HTREE_LEVEL) {
ext4_warning(dir->i_sb, "Enable large directory "
"feature to access it");
}
goto fail;
}
entries = (struct dx_entry *)(((char *)&root->info) +
root->info.info_length);
if (dx_get_limit(entries) != dx_root_limit(dir,
root->info.info_length)) {
ext4_warning_inode(dir, "dx entry: limit %u != root limit %u",
dx_get_limit(entries),
dx_root_limit(dir, root->info.info_length));
goto fail;
}
dxtrace(printk("Look up %x", hash));
while (1) {
count = dx_get_count(entries);
if (!count || count > dx_get_limit(entries)) {
ext4_warning_inode(dir,
"dx entry: count %u beyond limit %u",
count, dx_get_limit(entries));
goto fail;
}
p = entries + 1;
q = entries + count - 1;
while (p <= q) {
m = p + (q - p) / 2;
dxtrace(printk(KERN_CONT "."));
if (dx_get_hash(m) > hash)
q = m - 1;
else
p = m + 1;
}
if (0) { // linear search cross check
unsigned n = count - 1;
at = entries;
while (n--)
{
dxtrace(printk(KERN_CONT ","));
if (dx_get_hash(++at) > hash)
{
at--;
break;
}
}
assert (at == p - 1);
}
at = p - 1;
dxtrace(printk(KERN_CONT " %x->%u\n",
at == entries ? 0 : dx_get_hash(at),
dx_get_block(at)));
frame->entries = entries;
frame->at = at;
if (!indirect--)
return frame;
frame++;
frame->bh = ext4_read_dirblock(dir, dx_get_block(at), INDEX);
if (IS_ERR(frame->bh)) {
ret_err = (struct dx_frame *) frame->bh;
frame->bh = NULL;
goto fail;
}
entries = ((struct dx_node *) frame->bh->b_data)->entries;
if (dx_get_limit(entries) != dx_node_limit(dir)) {
ext4_warning_inode(dir,
"dx entry: limit %u != node limit %u",
dx_get_limit(entries), dx_node_limit(dir));
goto fail;
}
}
fail:
while (frame >= frame_in) {
brelse(frame->bh);
frame--;
}
if (ret_err == ERR_PTR(ERR_BAD_DX_DIR))
ext4_warning_inode(dir,
"Corrupt directory, running e2fsck is recommended");
return ret_err;
}
static void dx_release(struct dx_frame *frames)
{
struct dx_root_info *info;
int i;
if (frames[0].bh == NULL)
return;
info = &((struct dx_root *)frames[0].bh->b_data)->info;
for (i = 0; i <= info->indirect_levels; i++) {
if (frames[i].bh == NULL)
break;
brelse(frames[i].bh);
frames[i].bh = NULL;
}
}
/*
* This function increments the frame pointer to search the next leaf
* block, and reads in the necessary intervening nodes if the search
* should be necessary. Whether or not the search is necessary is
* controlled by the hash parameter. If the hash value is even, then
* the search is only continued if the next block starts with that
* hash value. This is used if we are searching for a specific file.
*
* If the hash value is HASH_NB_ALWAYS, then always go to the next block.
*
* This function returns 1 if the caller should continue to search,
* or 0 if it should not. If there is an error reading one of the
* index blocks, it will a negative error code.
*
* If start_hash is non-null, it will be filled in with the starting
* hash of the next page.
*/
static int ext4_htree_next_block(struct inode *dir, __u32 hash,
struct dx_frame *frame,
struct dx_frame *frames,
__u32 *start_hash)
{
struct dx_frame *p;
struct buffer_head *bh;
int num_frames = 0;
__u32 bhash;
p = frame;
/*
* Find the next leaf page by incrementing the frame pointer.
* If we run out of entries in the interior node, loop around and
* increment pointer in the parent node. When we break out of
* this loop, num_frames indicates the number of interior
* nodes need to be read.
*/
while (1) {
if (++(p->at) < p->entries + dx_get_count(p->entries))
break;
if (p == frames)
return 0;
num_frames++;
p--;
}
/*
* If the hash is 1, then continue only if the next page has a
* continuation hash of any value. This is used for readdir
* handling. Otherwise, check to see if the hash matches the
* desired contiuation hash. If it doesn't, return since
* there's no point to read in the successive index pages.
*/
bhash = dx_get_hash(p->at);
if (start_hash)
*start_hash = bhash;
if ((hash & 1) == 0) {
if ((bhash & ~1) != hash)
return 0;
}
/*
* If the hash is HASH_NB_ALWAYS, we always go to the next
* block so no check is necessary
*/
while (num_frames--) {
bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX);
if (IS_ERR(bh))
return PTR_ERR(bh);
p++;
brelse(p->bh);
p->bh = bh;
p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
}
return 1;
}
/*
* This function fills a red-black tree with information from a
* directory block. It returns the number directory entries loaded
* into the tree. If there is an error it is returned in err.
*/
static int htree_dirblock_to_tree(struct file *dir_file,
struct inode *dir, ext4_lblk_t block,
struct dx_hash_info *hinfo,
__u32 start_hash, __u32 start_minor_hash)
{
struct buffer_head *bh;
struct ext4_dir_entry_2 *de, *top;
int err = 0, count = 0;
struct fscrypt_str fname_crypto_str = FSTR_INIT(NULL, 0), tmp_str;
dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
(unsigned long)block));
bh = ext4_read_dirblock(dir, block, DIRENT);
if (IS_ERR(bh))
return PTR_ERR(bh);
de = (struct ext4_dir_entry_2 *) bh->b_data;
top = (struct ext4_dir_entry_2 *) ((char *) de +
dir->i_sb->s_blocksize -
EXT4_DIR_REC_LEN(0));
#ifdef CONFIG_EXT4_FS_ENCRYPTION
/* Check if the directory is encrypted */
if (ext4_encrypted_inode(dir)) {
err = fscrypt_get_encryption_info(dir);
if (err < 0) {
brelse(bh);
return err;
}
err = fscrypt_fname_alloc_buffer(dir, EXT4_NAME_LEN,
&fname_crypto_str);
if (err < 0) {
brelse(bh);
return err;
}
}
#endif
for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
if (ext4_check_dir_entry(dir, NULL, de, bh,
bh->b_data, bh->b_size,
(block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
+ ((char *)de - bh->b_data))) {
/* silently ignore the rest of the block */
break;
}
ext4fs_dirhash(de->name, de->name_len, hinfo);
if ((hinfo->hash < start_hash) ||
((hinfo->hash == start_hash) &&
(hinfo->minor_hash < start_minor_hash)))
continue;
if (de->inode == 0)
continue;
if (!ext4_encrypted_inode(dir)) {
tmp_str.name = de->name;
tmp_str.len = de->name_len;
err = ext4_htree_store_dirent(dir_file,
hinfo->hash, hinfo->minor_hash, de,
&tmp_str);
} else {
int save_len = fname_crypto_str.len;
struct fscrypt_str de_name = FSTR_INIT(de->name,
de->name_len);
/* Directory is encrypted */
err = fscrypt_fname_disk_to_usr(dir, hinfo->hash,
hinfo->minor_hash, &de_name,
&fname_crypto_str);
if (err) {
count = err;
goto errout;
}
err = ext4_htree_store_dirent(dir_file,
hinfo->hash, hinfo->minor_hash, de,
&fname_crypto_str);
fname_crypto_str.len = save_len;
}
if (err != 0) {
count = err;
goto errout;
}
count++;
}
errout:
brelse(bh);
#ifdef CONFIG_EXT4_FS_ENCRYPTION
fscrypt_fname_free_buffer(&fname_crypto_str);
#endif
return count;
}
/*
* This function fills a red-black tree with information from a
* directory. We start scanning the directory in hash order, starting
* at start_hash and start_minor_hash.
*
* This function returns the number of entries inserted into the tree,
* or a negative error code.
*/
int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
__u32 start_minor_hash, __u32 *next_hash)
{
struct dx_hash_info hinfo;
struct ext4_dir_entry_2 *de;
struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
struct inode *dir;
ext4_lblk_t block;
int count = 0;
int ret, err;
__u32 hashval;
struct fscrypt_str tmp_str;
dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
start_hash, start_minor_hash));
dir = file_inode(dir_file);
if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
if (hinfo.hash_version <= DX_HASH_TEA)
hinfo.hash_version +=
EXT4_SB(dir->i_sb)->s_hash_unsigned;
hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
if (ext4_has_inline_data(dir)) {
int has_inline_data = 1;
count = htree_inlinedir_to_tree(dir_file, dir, 0,
&hinfo, start_hash,
start_minor_hash,
&has_inline_data);
if (has_inline_data) {
*next_hash = ~0;
return count;
}
}
count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
start_hash, start_minor_hash);
*next_hash = ~0;
return count;
}
hinfo.hash = start_hash;
hinfo.minor_hash = 0;
frame = dx_probe(NULL, dir, &hinfo, frames);
if (IS_ERR(frame))
return PTR_ERR(frame);
/* Add '.' and '..' from the htree header */
if (!start_hash && !start_minor_hash) {
de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
tmp_str.name = de->name;
tmp_str.len = de->name_len;
err = ext4_htree_store_dirent(dir_file, 0, 0,
de, &tmp_str);
if (err != 0)
goto errout;
count++;
}
if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
de = ext4_next_entry(de, dir->i_sb->s_blocksize);
tmp_str.name = de->name;
tmp_str.len = de->name_len;
err = ext4_htree_store_dirent(dir_file, 2, 0,
de, &tmp_str);
if (err != 0)
goto errout;
count++;
}
while (1) {
if (fatal_signal_pending(current)) {
err = -ERESTARTSYS;
goto errout;
}
cond_resched();
block = dx_get_block(frame->at);
ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
start_hash, start_minor_hash);
if (ret < 0) {
err = ret;
goto errout;
}
count += ret;
hashval = ~0;
ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
frame, frames, &hashval);
*next_hash = hashval;
if (ret < 0) {
err = ret;
goto errout;
}
/*
* Stop if: (a) there are no more entries, or
* (b) we have inserted at least one entry and the
* next hash value is not a continuation
*/
if ((ret == 0) ||
(count && ((hashval & 1) == 0)))
break;
}
dx_release(frames);
dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
"next hash: %x\n", count, *next_hash));
return count;
errout:
dx_release(frames);
return (err);
}
static inline int search_dirblock(struct buffer_head *bh,
struct inode *dir,
struct ext4_filename *fname,
unsigned int offset,
struct ext4_dir_entry_2 **res_dir)
{
return ext4_search_dir(bh, bh->b_data, dir->i_sb->s_blocksize, dir,
fname, offset, res_dir);
}
/*
* Directory block splitting, compacting
*/
/*
* Create map of hash values, offsets, and sizes, stored at end of block.
* Returns number of entries mapped.
*/
static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
unsigned blocksize, struct dx_hash_info *hinfo,
struct dx_map_entry *map_tail)
{
int count = 0;
char *base = (char *) de;
struct dx_hash_info h = *hinfo;
while ((char *) de < base + blocksize) {
if (de->name_len && de->inode) {
ext4fs_dirhash(de->name, de->name_len, &h);
map_tail--;
map_tail->hash = h.hash;
map_tail->offs = ((char *) de - base)>>2;
map_tail->size = le16_to_cpu(de->rec_len);
count++;
cond_resched();
}
/* XXX: do we need to check rec_len == 0 case? -Chris */
de = ext4_next_entry(de, blocksize);
}
return count;
}
/* Sort map by hash value */
static void dx_sort_map (struct dx_map_entry *map, unsigned count)
{
struct dx_map_entry *p, *q, *top = map + count - 1;
int more;
/* Combsort until bubble sort doesn't suck */
while (count > 2) {
count = count*10/13;
if (count - 9 < 2) /* 9, 10 -> 11 */
count = 11;
for (p = top, q = p - count; q >= map; p--, q--)
if (p->hash < q->hash)
swap(*p, *q);
}
/* Garden variety bubble sort */
do {
more = 0;
q = top;
while (q-- > map) {
if (q[1].hash >= q[0].hash)
continue;
swap(*(q+1), *q);
more = 1;
}
} while(more);
}
static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
{
struct dx_entry *entries = frame->entries;
struct dx_entry *old = frame->at, *new = old + 1;
int count = dx_get_count(entries);
assert(count < dx_get_limit(entries));
assert(old < entries + count);
memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
dx_set_hash(new, hash);
dx_set_block(new, block);
dx_set_count(entries, count + 1);
}
/*
* Test whether a directory entry matches the filename being searched for.
*
* Return: %true if the directory entry matches, otherwise %false.
*/
static inline bool ext4_match(const struct ext4_filename *fname,
const struct ext4_dir_entry_2 *de)
{
struct fscrypt_name f;
if (!de->inode)
return false;
f.usr_fname = fname->usr_fname;
f.disk_name = fname->disk_name;
#ifdef CONFIG_EXT4_FS_ENCRYPTION
f.crypto_buf = fname->crypto_buf;
#endif
return fscrypt_match_name(&f, de->name, de->name_len);
}
/*
* Returns 0 if not found, -1 on failure, and 1 on success
*/
int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size,
struct inode *dir, struct ext4_filename *fname,
unsigned int offset, struct ext4_dir_entry_2 **res_dir)
{
struct ext4_dir_entry_2 * de;
char * dlimit;
int de_len;
de = (struct ext4_dir_entry_2 *)search_buf;
dlimit = search_buf + buf_size;
while ((char *) de < dlimit) {
/* this code is executed quadratically often */
/* do minimal checking `by hand' */
if ((char *) de + de->name_len <= dlimit &&
ext4_match(fname, de)) {
/* found a match - just to be sure, do
* a full check */
if (ext4_check_dir_entry(dir, NULL, de, bh, bh->b_data,
bh->b_size, offset))
return -1;
*res_dir = de;
return 1;
}
/* prevent looping on a bad block */
de_len = ext4_rec_len_from_disk(de->rec_len,
dir->i_sb->s_blocksize);
if (de_len <= 0)
return -1;
offset += de_len;
de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
}
return 0;
}
static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block,
struct ext4_dir_entry *de)
{
struct super_block *sb = dir->i_sb;
if (!is_dx(dir))
return 0;
if (block == 0)
return 1;
if (de->inode == 0 &&
ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) ==
sb->s_blocksize)
return 1;
return 0;
}
/*
* ext4_find_entry()
*
* finds an entry in the specified directory with the wanted name. It
* returns the cache buffer in which the entry was found, and the entry
* itself (as a parameter - res_dir). It does NOT read the inode of the
* entry - you'll have to do that yourself if you want to.
*
* The returned buffer_head has ->b_count elevated. The caller is expected
* to brelse() it when appropriate.
*/
static struct buffer_head * ext4_find_entry (struct inode *dir,
const struct qstr *d_name,
struct ext4_dir_entry_2 **res_dir,
int *inlined)
{
struct super_block *sb;
struct buffer_head *bh_use[NAMEI_RA_SIZE];
struct buffer_head *bh, *ret = NULL;
ext4_lblk_t start, block;
const u8 *name = d_name->name;
size_t ra_max = 0; /* Number of bh's in the readahead
buffer, bh_use[] */
size_t ra_ptr = 0; /* Current index into readahead
buffer */
ext4_lblk_t nblocks;
int i, namelen, retval;
struct ext4_filename fname;
*res_dir = NULL;
sb = dir->i_sb;
namelen = d_name->len;
if (namelen > EXT4_NAME_LEN)
return NULL;
retval = ext4_fname_setup_filename(dir, d_name, 1, &fname);
if (retval == -ENOENT)
return NULL;
if (retval)
return ERR_PTR(retval);
if (ext4_has_inline_data(dir)) {
int has_inline_data = 1;
ret = ext4_find_inline_entry(dir, &fname, res_dir,
&has_inline_data);
if (has_inline_data) {
if (inlined)
*inlined = 1;
goto cleanup_and_exit;
}
}
if ((namelen <= 2) && (name[0] == '.') &&
(name[1] == '.' || name[1] == '\0')) {
/*
* "." or ".." will only be in the first block
* NFS may look up ".."; "." should be handled by the VFS
*/
block = start = 0;
nblocks = 1;
goto restart;
}
if (is_dx(dir)) {
ret = ext4_dx_find_entry(dir, &fname, res_dir);
/*
* On success, or if the error was file not found,
* return. Otherwise, fall back to doing a search the
* old fashioned way.
*/
if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
goto cleanup_and_exit;
dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
"falling back\n"));
}
nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
if (!nblocks) {
ret = NULL;
goto cleanup_and_exit;
}
start = EXT4_I(dir)->i_dir_start_lookup;
if (start >= nblocks)
start = 0;
block = start;
restart:
do {
/*
* We deal with the read-ahead logic here.
*/
if (ra_ptr >= ra_max) {
/* Refill the readahead buffer */
ra_ptr = 0;
if (block < start)
ra_max = start - block;
else
ra_max = nblocks - block;
ra_max = min(ra_max, ARRAY_SIZE(bh_use));
retval = ext4_bread_batch(dir, block, ra_max,
false /* wait */, bh_use);
if (retval) {
ret = ERR_PTR(retval);
ra_max = 0;
goto cleanup_and_exit;
}
}
if ((bh = bh_use[ra_ptr++]) == NULL)
goto next;
wait_on_buffer(bh);
if (!buffer_uptodate(bh)) {
EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
(unsigned long) block);
brelse(bh);
ret = ERR_PTR(-EIO);
goto cleanup_and_exit;
}
if (!buffer_verified(bh) &&
!is_dx_internal_node(dir, block,
(struct ext4_dir_entry *)bh->b_data) &&
!ext4_dirent_csum_verify(dir,
(struct ext4_dir_entry *)bh->b_data)) {
EXT4_ERROR_INODE(dir, "checksumming directory "
"block %lu", (unsigned long)block);
brelse(bh);
ret = ERR_PTR(-EFSBADCRC);
goto cleanup_and_exit;
}
set_buffer_verified(bh);
i = search_dirblock(bh, dir, &fname,
block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
if (i == 1) {
EXT4_I(dir)->i_dir_start_lookup = block;
ret = bh;
goto cleanup_and_exit;
} else {
brelse(bh);
if (i < 0)
goto cleanup_and_exit;
}
next:
if (++block >= nblocks)
block = 0;
} while (block != start);
/*
* If the directory has grown while we were searching, then
* search the last part of the directory before giving up.
*/
block = nblocks;
nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
if (block < nblocks) {
start = 0;
goto restart;
}
cleanup_and_exit:
/* Clean up the read-ahead blocks */
for (; ra_ptr < ra_max; ra_ptr++)
brelse(bh_use[ra_ptr]);
ext4_fname_free_filename(&fname);
return ret;
}
static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
struct ext4_filename *fname,
struct ext4_dir_entry_2 **res_dir)
{
struct super_block * sb = dir->i_sb;
struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
struct buffer_head *bh;
ext4_lblk_t block;
int retval;
#ifdef CONFIG_EXT4_FS_ENCRYPTION
*res_dir = NULL;
#endif
frame = dx_probe(fname, dir, NULL, frames);
if (IS_ERR(frame))
return (struct buffer_head *) frame;
do {
block = dx_get_block(frame->at);
bh = ext4_read_dirblock(dir, block, DIRENT);
if (IS_ERR(bh))
goto errout;
retval = search_dirblock(bh, dir, fname,
block << EXT4_BLOCK_SIZE_BITS(sb),
res_dir);
if (retval == 1)
goto success;
brelse(bh);
if (retval == -1) {
bh = ERR_PTR(ERR_BAD_DX_DIR);
goto errout;
}
/* Check to see if we should continue to search */
retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
frames, NULL);
if (retval < 0) {
ext4_warning_inode(dir,
"error %d reading directory index block",
retval);
bh = ERR_PTR(retval);
goto errout;
}
} while (retval == 1);
bh = NULL;
errout:
dxtrace(printk(KERN_DEBUG "%s not found\n", fname->usr_fname->name));
success:
dx_release(frames);
return bh;
}
static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
{
struct inode *inode;
struct ext4_dir_entry_2 *de;
struct buffer_head *bh;
int err;
err = fscrypt_prepare_lookup(dir, dentry, flags);
if (err)
return ERR_PTR(err);
if (dentry->d_name.len > EXT4_NAME_LEN)
return ERR_PTR(-ENAMETOOLONG);
bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
if (IS_ERR(bh))
return (struct dentry *) bh;
inode = NULL;
if (bh) {
__u32 ino = le32_to_cpu(de->inode);
brelse(bh);
if (!ext4_valid_inum(dir->i_sb, ino)) {
EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
return ERR_PTR(-EFSCORRUPTED);
}
if (unlikely(ino == dir->i_ino)) {
EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
dentry);
return ERR_PTR(-EFSCORRUPTED);
}
inode = ext4_iget_normal(dir->i_sb, ino);
if (inode == ERR_PTR(-ESTALE)) {
EXT4_ERROR_INODE(dir,
"deleted inode referenced: %u",
ino);
return ERR_PTR(-EFSCORRUPTED);
}
if (!IS_ERR(inode) && ext4_encrypted_inode(dir) &&
(S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
!fscrypt_has_permitted_context(dir, inode)) {
ext4_warning(inode->i_sb,
"Inconsistent encryption contexts: %lu/%lu",
dir->i_ino, inode->i_ino);
iput(inode);
return ERR_PTR(-EPERM);
}
}
return d_splice_alias(inode, dentry);
}
struct dentry *ext4_get_parent(struct dentry *child)
{
__u32 ino;
static const struct qstr dotdot = QSTR_INIT("..", 2);
struct ext4_dir_entry_2 * de;
struct buffer_head *bh;
bh = ext4_find_entry(d_inode(child), &dotdot, &de, NULL);
if (IS_ERR(bh))
return (struct dentry *) bh;
if (!bh)
return ERR_PTR(-ENOENT);
ino = le32_to_cpu(de->inode);
brelse(bh);
if (!ext4_valid_inum(child->d_sb, ino)) {
EXT4_ERROR_INODE(d_inode(child),
"bad parent inode number: %u", ino);
return ERR_PTR(-EFSCORRUPTED);
}
return d_obtain_alias(ext4_iget_normal(child->d_sb, ino));
}
/*
* Move count entries from end of map between two memory locations.
* Returns pointer to last entry moved.
*/
static struct ext4_dir_entry_2 *
dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
unsigned blocksize)
{
unsigned rec_len = 0;
while (count--) {
struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
(from + (map->offs<<2));
rec_len = EXT4_DIR_REC_LEN(de->name_len);
memcpy (to, de, rec_len);
((struct ext4_dir_entry_2 *) to)->rec_len =
ext4_rec_len_to_disk(rec_len, blocksize);
de->inode = 0;
map++;
to += rec_len;
}
return (struct ext4_dir_entry_2 *) (to - rec_len);
}
/*
* Compact each dir entry in the range to the minimal rec_len.
* Returns pointer to last entry in range.
*/
static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
{
struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
unsigned rec_len = 0;
prev = to = de;
while ((char*)de < base + blocksize) {
next = ext4_next_entry(de, blocksize);
if (de->inode && de->name_len) {
rec_len = EXT4_DIR_REC_LEN(de->name_len);
if (de > to)
memmove(to, de, rec_len);
to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
prev = to;
to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
}
de = next;
}
return prev;
}
/*
* Split a full leaf block to make room for a new dir entry.
* Allocate a new block, and move entries so that they are approx. equally full.
* Returns pointer to de in block into which the new entry will be inserted.
*/
static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
struct buffer_head **bh,struct dx_frame *frame,
struct dx_hash_info *hinfo)
{
unsigned blocksize = dir->i_sb->s_blocksize;
unsigned count, continued;
struct buffer_head *bh2;
ext4_lblk_t newblock;
u32 hash2;
struct dx_map_entry *map;
char *data1 = (*bh)->b_data, *data2;
unsigned split, move, size;
struct ext4_dir_entry_2 *de = NULL, *de2;
struct ext4_dir_entry_tail *t;
int csum_size = 0;
int err = 0, i;
if (ext4_has_metadata_csum(dir->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
bh2 = ext4_append(handle, dir, &newblock);
if (IS_ERR(bh2)) {
brelse(*bh);
*bh = NULL;
return (struct ext4_dir_entry_2 *) bh2;
}
BUFFER_TRACE(*bh, "get_write_access");
err = ext4_journal_get_write_access(handle, *bh);
if (err)
goto journal_error;
BUFFER_TRACE(frame->bh, "get_write_access");
err = ext4_journal_get_write_access(handle, frame->bh);
if (err)
goto journal_error;
data2 = bh2->b_data;
/* create map in the end of data2 block */
map = (struct dx_map_entry *) (data2 + blocksize);
count = dx_make_map(dir, (struct ext4_dir_entry_2 *) data1,
blocksize, hinfo, map);
map -= count;
dx_sort_map(map, count);
/* Split the existing block in the middle, size-wise */
size = 0;
move = 0;
for (i = count-1; i >= 0; i--) {
/* is more than half of this entry in 2nd half of the block? */
if (size + map[i].size/2 > blocksize/2)
break;
size += map[i].size;
move++;
}
/* map index at which we will split */
split = count - move;
hash2 = map[split].hash;
continued = hash2 == map[split - 1].hash;
dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
(unsigned long)dx_get_block(frame->at),
hash2, split, count-split));
/* Fancy dance to stay within two buffers */
de2 = dx_move_dirents(data1, data2, map + split, count - split,
blocksize);
de = dx_pack_dirents(data1, blocksize);
de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
(char *) de,
blocksize);
de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
(char *) de2,
blocksize);
if (csum_size) {
t = EXT4_DIRENT_TAIL(data2, blocksize);
initialize_dirent_tail(t, blocksize);
t = EXT4_DIRENT_TAIL(data1, blocksize);
initialize_dirent_tail(t, blocksize);
}
dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
blocksize, 1));
dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
blocksize, 1));
/* Which block gets the new entry? */
if (hinfo->hash >= hash2) {
swap(*bh, bh2);
de = de2;
}
dx_insert_block(frame, hash2 + continued, newblock);
err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
if (err)
goto journal_error;
err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
if (err)
goto journal_error;
brelse(bh2);
dxtrace(dx_show_index("frame", frame->entries));
return de;
journal_error:
brelse(*bh);
brelse(bh2);
*bh = NULL;
ext4_std_error(dir->i_sb, err);
return ERR_PTR(err);
}
int ext4_find_dest_de(struct inode *dir, struct inode *inode,
struct buffer_head *bh,
void *buf, int buf_size,
struct ext4_filename *fname,
struct ext4_dir_entry_2 **dest_de)
{
struct ext4_dir_entry_2 *de;
unsigned short reclen = EXT4_DIR_REC_LEN(fname_len(fname));
int nlen, rlen;
unsigned int offset = 0;
char *top;
de = (struct ext4_dir_entry_2 *)buf;
top = buf + buf_size - reclen;
while ((char *) de <= top) {
if (ext4_check_dir_entry(dir, NULL, de, bh,
buf, buf_size, offset))
return -EFSCORRUPTED;
if (ext4_match(fname, de))
return -EEXIST;
nlen = EXT4_DIR_REC_LEN(de->name_len);
rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
if ((de->inode ? rlen - nlen : rlen) >= reclen)
break;
de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
offset += rlen;
}
if ((char *) de > top)
return -ENOSPC;
*dest_de = de;
return 0;
}
void ext4_insert_dentry(struct inode *inode,
struct ext4_dir_entry_2 *de,
int buf_size,
struct ext4_filename *fname)
{
int nlen, rlen;
nlen = EXT4_DIR_REC_LEN(de->name_len);
rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
if (de->inode) {
struct ext4_dir_entry_2 *de1 =
(struct ext4_dir_entry_2 *)((char *)de + nlen);
de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
de = de1;
}
de->file_type = EXT4_FT_UNKNOWN;
de->inode = cpu_to_le32(inode->i_ino);
ext4_set_de_type(inode->i_sb, de, inode->i_mode);
de->name_len = fname_len(fname);
memcpy(de->name, fname_name(fname), fname_len(fname));
}
/*
* Add a new entry into a directory (leaf) block. If de is non-NULL,
* it points to a directory entry which is guaranteed to be large
* enough for new directory entry. If de is NULL, then
* add_dirent_to_buf will attempt search the directory block for
* space. It will return -ENOSPC if no space is available, and -EIO
* and -EEXIST if directory entry already exists.
*/
static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
struct inode *dir,
struct inode *inode, struct ext4_dir_entry_2 *de,
struct buffer_head *bh)
{
unsigned int blocksize = dir->i_sb->s_blocksize;
int csum_size = 0;
int err;
if (ext4_has_metadata_csum(inode->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
if (!de) {
err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
blocksize - csum_size, fname, &de);
if (err)
return err;
}
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, bh);
if (err) {
ext4_std_error(dir->i_sb, err);
return err;
}
/* By now the buffer is marked for journaling */
ext4_insert_dentry(inode, de, blocksize, fname);
/*
* XXX shouldn't update any times until successful
* completion of syscall, but too many callers depend
* on this.
*
* XXX similarly, too many callers depend on
* ext4_new_inode() setting the times, but error
* recovery deletes the inode, so the worst that can
* happen is that the times are slightly out of date
* and/or different from the directory change time.
*/
dir->i_mtime = dir->i_ctime = current_time(dir);
ext4_update_dx_flag(dir);
inode_inc_iversion(dir);
ext4_mark_inode_dirty(handle, dir);
BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_dirent_node(handle, dir, bh);
if (err)
ext4_std_error(dir->i_sb, err);
return 0;
}
/*
* This converts a one block unindexed directory to a 3 block indexed
* directory, and adds the dentry to the indexed directory.
*/
static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
struct inode *dir,
struct inode *inode, struct buffer_head *bh)
{
struct buffer_head *bh2;
struct dx_root *root;
struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
struct dx_entry *entries;
struct ext4_dir_entry_2 *de, *de2;
struct ext4_dir_entry_tail *t;
char *data1, *top;
unsigned len;
int retval;
unsigned blocksize;
ext4_lblk_t block;
struct fake_dirent *fde;
int csum_size = 0;
if (ext4_has_metadata_csum(inode->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
blocksize = dir->i_sb->s_blocksize;
dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
BUFFER_TRACE(bh, "get_write_access");
retval = ext4_journal_get_write_access(handle, bh);
if (retval) {
ext4_std_error(dir->i_sb, retval);
brelse(bh);
return retval;
}
root = (struct dx_root *) bh->b_data;
/* The 0th block becomes the root, move the dirents out */
fde = &root->dotdot;
de = (struct ext4_dir_entry_2 *)((char *)fde +
ext4_rec_len_from_disk(fde->rec_len, blocksize));
if ((char *) de >= (((char *) root) + blocksize)) {
EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
brelse(bh);
return -EFSCORRUPTED;
}
len = ((char *) root) + (blocksize - csum_size) - (char *) de;
/* Allocate new block for the 0th block's dirents */
bh2 = ext4_append(handle, dir, &block);
if (IS_ERR(bh2)) {
brelse(bh);
return PTR_ERR(bh2);
}
ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
data1 = bh2->b_data;
memcpy (data1, de, len);
de = (struct ext4_dir_entry_2 *) data1;
top = data1 + len;
while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
de = de2;
de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
(char *) de,
blocksize);
if (csum_size) {
t = EXT4_DIRENT_TAIL(data1, blocksize);
initialize_dirent_tail(t, blocksize);
}
/* Initialize the root; the dot dirents already exist */
de = (struct ext4_dir_entry_2 *) (&root->dotdot);
de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
blocksize);
memset (&root->info, 0, sizeof(root->info));
root->info.info_length = sizeof(root->info);
root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
entries = root->entries;
dx_set_block(entries, 1);
dx_set_count(entries, 1);
dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
/* Initialize as for dx_probe */
fname->hinfo.hash_version = root->info.hash_version;
if (fname->hinfo.hash_version <= DX_HASH_TEA)
fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
ext4fs_dirhash(fname_name(fname), fname_len(fname), &fname->hinfo);
memset(frames, 0, sizeof(frames));
frame = frames;
frame->entries = entries;
frame->at = entries;
frame->bh = bh;
retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
if (retval)
goto out_frames;
retval = ext4_handle_dirty_dirent_node(handle, dir, bh2);
if (retval)
goto out_frames;
de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
if (IS_ERR(de)) {
retval = PTR_ERR(de);
goto out_frames;
}
retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
out_frames:
/*
* Even if the block split failed, we have to properly write
* out all the changes we did so far. Otherwise we can end up
* with corrupted filesystem.
*/
if (retval)
ext4_mark_inode_dirty(handle, dir);
dx_release(frames);
brelse(bh2);
return retval;
}
/*
* ext4_add_entry()
*
* adds a file entry to the specified directory, using the same
* semantics as ext4_find_entry(). It returns NULL if it failed.
*
* NOTE!! The inode part of 'de' is left at 0 - which means you
* may not sleep between calling this and putting something into
* the entry, as someone else might have used it while you slept.
*/
static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
struct inode *inode)
{
struct inode *dir = d_inode(dentry->d_parent);
struct buffer_head *bh = NULL;
struct ext4_dir_entry_2 *de;
struct ext4_dir_entry_tail *t;
struct super_block *sb;
struct ext4_filename fname;
int retval;
int dx_fallback=0;
unsigned blocksize;
ext4_lblk_t block, blocks;
int csum_size = 0;
if (ext4_has_metadata_csum(inode->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
sb = dir->i_sb;
blocksize = sb->s_blocksize;
if (!dentry->d_name.len)
return -EINVAL;
retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
if (retval)
return retval;
if (ext4_has_inline_data(dir)) {
retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
if (retval < 0)
goto out;
if (retval == 1) {
retval = 0;
goto out;
}
}
if (is_dx(dir)) {
retval = ext4_dx_add_entry(handle, &fname, dir, inode);
if (!retval || (retval != ERR_BAD_DX_DIR))
goto out;
ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
dx_fallback++;
ext4_mark_inode_dirty(handle, dir);
}
blocks = dir->i_size >> sb->s_blocksize_bits;
for (block = 0; block < blocks; block++) {
bh = ext4_read_dirblock(dir, block, DIRENT);
if (IS_ERR(bh)) {
retval = PTR_ERR(bh);
bh = NULL;
goto out;
}
retval = add_dirent_to_buf(handle, &fname, dir, inode,
NULL, bh);
if (retval != -ENOSPC)
goto out;
if (blocks == 1 && !dx_fallback &&
ext4_has_feature_dir_index(sb)) {
retval = make_indexed_dir(handle, &fname, dir,
inode, bh);
bh = NULL; /* make_indexed_dir releases bh */
goto out;
}
brelse(bh);
}
bh = ext4_append(handle, dir, &block);
if (IS_ERR(bh)) {
retval = PTR_ERR(bh);
bh = NULL;
goto out;
}
de = (struct ext4_dir_entry_2 *) bh->b_data;
de->inode = 0;
de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
if (csum_size) {
t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
initialize_dirent_tail(t, blocksize);
}
retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
out:
ext4_fname_free_filename(&fname);
brelse(bh);
if (retval == 0)
ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
return retval;
}
/*
* Returns 0 for success, or a negative error value
*/
static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
struct inode *dir, struct inode *inode)
{
struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
struct dx_entry *entries, *at;
struct buffer_head *bh;
struct super_block *sb = dir->i_sb;
struct ext4_dir_entry_2 *de;
int restart;
int err;
again:
restart = 0;
frame = dx_probe(fname, dir, NULL, frames);
if (IS_ERR(frame))
return PTR_ERR(frame);
entries = frame->entries;
at = frame->at;
bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT);
if (IS_ERR(bh)) {
err = PTR_ERR(bh);
bh = NULL;
goto cleanup;
}
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, bh);
if (err)
goto journal_error;
err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
if (err != -ENOSPC)
goto cleanup;
err = 0;
/* Block full, should compress but for now just split */
dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
dx_get_count(entries), dx_get_limit(entries)));
/* Need to split index? */
if (dx_get_count(entries) == dx_get_limit(entries)) {
ext4_lblk_t newblock;
int levels = frame - frames + 1;
unsigned int icount;
int add_level = 1;
struct dx_entry *entries2;
struct dx_node *node2;
struct buffer_head *bh2;
while (frame > frames) {
if (dx_get_count((frame - 1)->entries) <
dx_get_limit((frame - 1)->entries)) {
add_level = 0;
break;
}
frame--; /* split higher index block */
at = frame->at;
entries = frame->entries;
restart = 1;
}
if (add_level && levels == ext4_dir_htree_level(sb)) {
ext4_warning(sb, "Directory (ino: %lu) index full, "
"reach max htree level :%d",
dir->i_ino, levels);
if (ext4_dir_htree_level(sb) < EXT4_HTREE_LEVEL) {
ext4_warning(sb, "Large directory feature is "
"not enabled on this "
"filesystem");
}
err = -ENOSPC;
goto cleanup;
}
icount = dx_get_count(entries);
bh2 = ext4_append(handle, dir, &newblock);
if (IS_ERR(bh2)) {
err = PTR_ERR(bh2);
goto cleanup;
}
node2 = (struct dx_node *)(bh2->b_data);
entries2 = node2->entries;
memset(&node2->fake, 0, sizeof(struct fake_dirent));
node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
sb->s_blocksize);
BUFFER_TRACE(frame->bh, "get_write_access");
err = ext4_journal_get_write_access(handle, frame->bh);
if (err)
goto journal_error;
if (!add_level) {
unsigned icount1 = icount/2, icount2 = icount - icount1;
unsigned hash2 = dx_get_hash(entries + icount1);
dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
icount1, icount2));
BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
err = ext4_journal_get_write_access(handle,
(frame - 1)->bh);
if (err)
goto journal_error;
memcpy((char *) entries2, (char *) (entries + icount1),
icount2 * sizeof(struct dx_entry));
dx_set_count(entries, icount1);
dx_set_count(entries2, icount2);
dx_set_limit(entries2, dx_node_limit(dir));
/* Which index block gets the new entry? */
if (at - entries >= icount1) {
frame->at = at = at - entries - icount1 + entries2;
frame->entries = entries = entries2;
swap(frame->bh, bh2);
}
dx_insert_block((frame - 1), hash2, newblock);
dxtrace(dx_show_index("node", frame->entries));
dxtrace(dx_show_index("node",
((struct dx_node *) bh2->b_data)->entries));
err = ext4_handle_dirty_dx_node(handle, dir, bh2);
if (err)
goto journal_error;
brelse (bh2);
err = ext4_handle_dirty_dx_node(handle, dir,
(frame - 1)->bh);
if (err)
goto journal_error;
if (restart) {
err = ext4_handle_dirty_dx_node(handle, dir,
frame->bh);
goto journal_error;
}
} else {
struct dx_root *dxroot;
memcpy((char *) entries2, (char *) entries,
icount * sizeof(struct dx_entry));
dx_set_limit(entries2, dx_node_limit(dir));
/* Set up root */
dx_set_count(entries, 1);
dx_set_block(entries + 0, newblock);
dxroot = (struct dx_root *)frames[0].bh->b_data;
dxroot->info.indirect_levels += 1;
dxtrace(printk(KERN_DEBUG
"Creating %d level index...\n",
info->indirect_levels));
err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
if (err)
goto journal_error;
err = ext4_handle_dirty_dx_node(handle, dir, bh2);
brelse(bh2);
restart = 1;
goto journal_error;
}
}
de = do_split(handle, dir, &bh, frame, &fname->hinfo);
if (IS_ERR(de)) {
err = PTR_ERR(de);
goto cleanup;
}
err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
goto cleanup;
journal_error:
ext4_std_error(dir->i_sb, err); /* this is a no-op if err == 0 */
cleanup:
brelse(bh);
dx_release(frames);
/* @restart is true means htree-path has been changed, we need to
* repeat dx_probe() to find out valid htree-path
*/
if (restart && err == 0)
goto again;
return err;
}
/*
* ext4_generic_delete_entry deletes a directory entry by merging it
* with the previous entry
*/
int ext4_generic_delete_entry(handle_t *handle,
struct inode *dir,
struct ext4_dir_entry_2 *de_del,
struct buffer_head *bh,
void *entry_buf,
int buf_size,
int csum_size)
{
struct ext4_dir_entry_2 *de, *pde;
unsigned int blocksize = dir->i_sb->s_blocksize;
int i;
i = 0;
pde = NULL;
de = (struct ext4_dir_entry_2 *)entry_buf;
while (i < buf_size - csum_size) {
if (ext4_check_dir_entry(dir, NULL, de, bh,
bh->b_data, bh->b_size, i))
return -EFSCORRUPTED;
if (de == de_del) {
if (pde)
pde->rec_len = ext4_rec_len_to_disk(
ext4_rec_len_from_disk(pde->rec_len,
blocksize) +
ext4_rec_len_from_disk(de->rec_len,
blocksize),
blocksize);
else
de->inode = 0;
inode_inc_iversion(dir);
return 0;
}
i += ext4_rec_len_from_disk(de->rec_len, blocksize);
pde = de;
de = ext4_next_entry(de, blocksize);
}
return -ENOENT;
}
static int ext4_delete_entry(handle_t *handle,
struct inode *dir,
struct ext4_dir_entry_2 *de_del,
struct buffer_head *bh)
{
int err, csum_size = 0;
if (ext4_has_inline_data(dir)) {
int has_inline_data = 1;
err = ext4_delete_inline_entry(handle, dir, de_del, bh,
&has_inline_data);
if (has_inline_data)
return err;
}
if (ext4_has_metadata_csum(dir->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, bh);
if (unlikely(err))
goto out;
err = ext4_generic_delete_entry(handle, dir, de_del,
bh, bh->b_data,
dir->i_sb->s_blocksize, csum_size);
if (err)
goto out;
BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_dirent_node(handle, dir, bh);
if (unlikely(err))
goto out;
return 0;
out:
if (err != -ENOENT)
ext4_std_error(dir->i_sb, err);
return err;
}
/*
* Set directory link count to 1 if nlinks > EXT4_LINK_MAX, or if nlinks == 2
* since this indicates that nlinks count was previously 1 to avoid overflowing
* the 16-bit i_links_count field on disk. Directories with i_nlink == 1 mean
* that subdirectory link counts are not being maintained accurately.
*
* The caller has already checked for i_nlink overflow in case the DIR_LINK
* feature is not enabled and returned -EMLINK. The is_dx() check is a proxy
* for checking S_ISDIR(inode) (since the INODE_INDEX feature will not be set
* on regular files) and to avoid creating huge/slow non-HTREE directories.
*/
static void ext4_inc_count(handle_t *handle, struct inode *inode)
{
inc_nlink(inode);
if (is_dx(inode) &&
(inode->i_nlink > EXT4_LINK_MAX || inode->i_nlink == 2))
set_nlink(inode, 1);
}
/*
* If a directory had nlink == 1, then we should let it be 1. This indicates
* directory has >EXT4_LINK_MAX subdirs.
*/
static void ext4_dec_count(handle_t *handle, struct inode *inode)
{
if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
drop_nlink(inode);
}
static int ext4_add_nondir(handle_t *handle,
struct dentry *dentry, struct inode *inode)
{
int err = ext4_add_entry(handle, dentry, inode);
if (!err) {
ext4_mark_inode_dirty(handle, inode);
unlock_new_inode(inode);
d_instantiate(dentry, inode);
return 0;
}
drop_nlink(inode);
unlock_new_inode(inode);
iput(inode);
return err;
}
/*
* By the time this is called, we already have created
* the directory cache entry for the new file, but it
* is so far negative - it has no inode.
*
* If the create succeeds, we fill in the inode information
* with d_instantiate().
*/
static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
bool excl)
{
handle_t *handle;
struct inode *inode;
int err, credits, retries = 0;
err = dquot_initialize(dir);
if (err)
return err;
credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
retry:
inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
NULL, EXT4_HT_DIR, credits);
handle = ext4_journal_current_handle();
err = PTR_ERR(inode);
if (!IS_ERR(inode)) {
inode->i_op = &ext4_file_inode_operations;
inode->i_fop = &ext4_file_operations;
ext4_set_aops(inode);
err = ext4_add_nondir(handle, dentry, inode);
if (!err && IS_DIRSYNC(dir))
ext4_handle_sync(handle);
}
if (handle)
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
static int ext4_mknod(struct inode *dir, struct dentry *dentry,
umode_t mode, dev_t rdev)
{
handle_t *handle;
struct inode *inode;
int err, credits, retries = 0;
err = dquot_initialize(dir);
if (err)
return err;
credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
retry:
inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
NULL, EXT4_HT_DIR, credits);
handle = ext4_journal_current_handle();
err = PTR_ERR(inode);
if (!IS_ERR(inode)) {
init_special_inode(inode, inode->i_mode, rdev);
inode->i_op = &ext4_special_inode_operations;
err = ext4_add_nondir(handle, dentry, inode);
if (!err && IS_DIRSYNC(dir))
ext4_handle_sync(handle);
}
if (handle)
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
static int ext4_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
{
handle_t *handle;
struct inode *inode;
int err, retries = 0;
err = dquot_initialize(dir);
if (err)
return err;
retry:
inode = ext4_new_inode_start_handle(dir, mode,
NULL, 0, NULL,
EXT4_HT_DIR,
EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
4 + EXT4_XATTR_TRANS_BLOCKS);
handle = ext4_journal_current_handle();
err = PTR_ERR(inode);
if (!IS_ERR(inode)) {
inode->i_op = &ext4_file_inode_operations;
inode->i_fop = &ext4_file_operations;
ext4_set_aops(inode);
d_tmpfile(dentry, inode);
err = ext4_orphan_add(handle, inode);
if (err)
goto err_unlock_inode;
mark_inode_dirty(inode);
unlock_new_inode(inode);
}
if (handle)
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
err_unlock_inode:
ext4_journal_stop(handle);
unlock_new_inode(inode);
return err;
}
struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
struct ext4_dir_entry_2 *de,
int blocksize, int csum_size,
unsigned int parent_ino, int dotdot_real_len)
{
de->inode = cpu_to_le32(inode->i_ino);
de->name_len = 1;
de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
blocksize);
strcpy(de->name, ".");
ext4_set_de_type(inode->i_sb, de, S_IFDIR);
de = ext4_next_entry(de, blocksize);
de->inode = cpu_to_le32(parent_ino);
de->name_len = 2;
if (!dotdot_real_len)
de->rec_len = ext4_rec_len_to_disk(blocksize -
(csum_size + EXT4_DIR_REC_LEN(1)),
blocksize);
else
de->rec_len = ext4_rec_len_to_disk(
EXT4_DIR_REC_LEN(de->name_len), blocksize);
strcpy(de->name, "..");
ext4_set_de_type(inode->i_sb, de, S_IFDIR);
return ext4_next_entry(de, blocksize);
}
static int ext4_init_new_dir(handle_t *handle, struct inode *dir,
struct inode *inode)
{
struct buffer_head *dir_block = NULL;
struct ext4_dir_entry_2 *de;
struct ext4_dir_entry_tail *t;
ext4_lblk_t block = 0;
unsigned int blocksize = dir->i_sb->s_blocksize;
int csum_size = 0;
int err;
if (ext4_has_metadata_csum(dir->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
err = ext4_try_create_inline_dir(handle, dir, inode);
if (err < 0 && err != -ENOSPC)
goto out;
if (!err)
goto out;
}
inode->i_size = 0;
dir_block = ext4_append(handle, inode, &block);
if (IS_ERR(dir_block))
return PTR_ERR(dir_block);
de = (struct ext4_dir_entry_2 *)dir_block->b_data;
ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
set_nlink(inode, 2);
if (csum_size) {
t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize);
initialize_dirent_tail(t, blocksize);
}
BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_dirent_node(handle, inode, dir_block);
if (err)
goto out;
set_buffer_verified(dir_block);
out:
brelse(dir_block);
return err;
}
static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
handle_t *handle;
struct inode *inode;
int err, credits, retries = 0;
if (EXT4_DIR_LINK_MAX(dir))
return -EMLINK;
err = dquot_initialize(dir);
if (err)
return err;
credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
retry:
inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode,
&dentry->d_name,
0, NULL, EXT4_HT_DIR, credits);
handle = ext4_journal_current_handle();
err = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_stop;
inode->i_op = &ext4_dir_inode_operations;
inode->i_fop = &ext4_dir_operations;
err = ext4_init_new_dir(handle, dir, inode);
if (err)
goto out_clear_inode;
err = ext4_mark_inode_dirty(handle, inode);
if (!err)
err = ext4_add_entry(handle, dentry, inode);
if (err) {
out_clear_inode:
clear_nlink(inode);
unlock_new_inode(inode);
ext4_mark_inode_dirty(handle, inode);
iput(inode);
goto out_stop;
}
ext4_inc_count(handle, dir);
ext4_update_dx_flag(dir);
err = ext4_mark_inode_dirty(handle, dir);
if (err)
goto out_clear_inode;
unlock_new_inode(inode);
d_instantiate(dentry, inode);
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
out_stop:
if (handle)
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
/*
* routine to check that the specified directory is empty (for rmdir)
*/
bool ext4_empty_dir(struct inode *inode)
{
unsigned int offset;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de, *de1;
struct super_block *sb;
if (ext4_has_inline_data(inode)) {
int has_inline_data = 1;
int ret;
ret = empty_inline_dir(inode, &has_inline_data);
if (has_inline_data)
return ret;
}
sb = inode->i_sb;
if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) {
EXT4_ERROR_INODE(inode, "invalid size");
return true;
}
bh = ext4_read_dirblock(inode, 0, EITHER);
if (IS_ERR(bh))
return true;
de = (struct ext4_dir_entry_2 *) bh->b_data;
de1 = ext4_next_entry(de, sb->s_blocksize);
if (le32_to_cpu(de->inode) != inode->i_ino ||
le32_to_cpu(de1->inode) == 0 ||
strcmp(".", de->name) || strcmp("..", de1->name)) {
ext4_warning_inode(inode, "directory missing '.' and/or '..'");
brelse(bh);
return true;
}
offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) +
ext4_rec_len_from_disk(de1->rec_len, sb->s_blocksize);
de = ext4_next_entry(de1, sb->s_blocksize);
while (offset < inode->i_size) {
if ((void *) de >= (void *) (bh->b_data+sb->s_blocksize)) {
unsigned int lblock;
brelse(bh);
lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
bh = ext4_read_dirblock(inode, lblock, EITHER);
if (IS_ERR(bh))
return true;
de = (struct ext4_dir_entry_2 *) bh->b_data;
}
if (ext4_check_dir_entry(inode, NULL, de, bh,
bh->b_data, bh->b_size, offset)) {
de = (struct ext4_dir_entry_2 *)(bh->b_data +
sb->s_blocksize);
offset = (offset | (sb->s_blocksize - 1)) + 1;
continue;
}
if (le32_to_cpu(de->inode)) {
brelse(bh);
return false;
}
offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
de = ext4_next_entry(de, sb->s_blocksize);
}
brelse(bh);
return true;
}
/*
* ext4_orphan_add() links an unlinked or truncated inode into a list of
* such inodes, starting at the superblock, in case we crash before the
* file is closed/deleted, or in case the inode truncate spans multiple
* transactions and the last transaction is not recovered after a crash.
*
* At filesystem recovery time, we walk this list deleting unlinked
* inodes and truncating linked inodes in ext4_orphan_cleanup().
*
* Orphan list manipulation functions must be called under i_mutex unless
* we are just creating the inode or deleting it.
*/
int ext4_orphan_add(handle_t *handle, struct inode *inode)
{
struct super_block *sb = inode->i_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_iloc iloc;
int err = 0, rc;
bool dirty = false;
if (!sbi->s_journal || is_bad_inode(inode))
return 0;
WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
!inode_is_locked(inode));
/*
* Exit early if inode already is on orphan list. This is a big speedup
* since we don't have to contend on the global s_orphan_lock.
*/
if (!list_empty(&EXT4_I(inode)->i_orphan))
return 0;
/*
* Orphan handling is only valid for files with data blocks
* being truncated, or files being unlinked. Note that we either
* hold i_mutex, or the inode can not be referenced from outside,
* so i_nlink should not be bumped due to race
*/
J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sbi->s_sbh);
if (err)
goto out;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out;
mutex_lock(&sbi->s_orphan_lock);
/*
* Due to previous errors inode may be already a part of on-disk
* orphan list. If so skip on-disk list modification.
*/
if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
(le32_to_cpu(sbi->s_es->s_inodes_count))) {
/* Insert this inode at the head of the on-disk orphan list */
NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
dirty = true;
}
list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
mutex_unlock(&sbi->s_orphan_lock);
if (dirty) {
err = ext4_handle_dirty_super(handle, sb);
rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
if (!err)
err = rc;
if (err) {
/*
* We have to remove inode from in-memory list if
* addition to on disk orphan list failed. Stray orphan
* list entries can cause panics at unmount time.
*/
mutex_lock(&sbi->s_orphan_lock);
list_del_init(&EXT4_I(inode)->i_orphan);
mutex_unlock(&sbi->s_orphan_lock);
}
}
jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
jbd_debug(4, "orphan inode %lu will point to %d\n",
inode->i_ino, NEXT_ORPHAN(inode));
out:
ext4_std_error(sb, err);
return err;
}
/*
* ext4_orphan_del() removes an unlinked or truncated inode from the list
* of such inodes stored on disk, because it is finally being cleaned up.
*/
int ext4_orphan_del(handle_t *handle, struct inode *inode)
{
struct list_head *prev;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u32 ino_next;
struct ext4_iloc iloc;
int err = 0;
if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
return 0;
WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
!inode_is_locked(inode));
/* Do this quick check before taking global s_orphan_lock. */
if (list_empty(&ei->i_orphan))
return 0;
if (handle) {
/* Grab inode buffer early before taking global s_orphan_lock */
err = ext4_reserve_inode_write(handle, inode, &iloc);
}
mutex_lock(&sbi->s_orphan_lock);
jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
prev = ei->i_orphan.prev;
list_del_init(&ei->i_orphan);
/* If we're on an error path, we may not have a valid
* transaction handle with which to update the orphan list on
* disk, but we still need to remove the inode from the linked
* list in memory. */
if (!handle || err) {
mutex_unlock(&sbi->s_orphan_lock);
goto out_err;
}
ino_next = NEXT_ORPHAN(inode);
if (prev == &sbi->s_orphan) {
jbd_debug(4, "superblock will point to %u\n", ino_next);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sbi->s_sbh);
if (err) {
mutex_unlock(&sbi->s_orphan_lock);
goto out_brelse;
}
sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
mutex_unlock(&sbi->s_orphan_lock);
err = ext4_handle_dirty_super(handle, inode->i_sb);
} else {
struct ext4_iloc iloc2;
struct inode *i_prev =
&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
jbd_debug(4, "orphan inode %lu will point to %u\n",
i_prev->i_ino, ino_next);
err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
if (err) {
mutex_unlock(&sbi->s_orphan_lock);
goto out_brelse;
}
NEXT_ORPHAN(i_prev) = ino_next;
err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
mutex_unlock(&sbi->s_orphan_lock);
}
if (err)
goto out_brelse;
NEXT_ORPHAN(inode) = 0;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out_err:
ext4_std_error(inode->i_sb, err);
return err;
out_brelse:
brelse(iloc.bh);
goto out_err;
}
static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
{
int retval;
struct inode *inode;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
handle_t *handle = NULL;
if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
return -EIO;
/* Initialize quotas before so that eventual writes go in
* separate transaction */
retval = dquot_initialize(dir);
if (retval)
return retval;
retval = dquot_initialize(d_inode(dentry));
if (retval)
return retval;
retval = -ENOENT;
bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh)
goto end_rmdir;
inode = d_inode(dentry);
retval = -EFSCORRUPTED;
if (le32_to_cpu(de->inode) != inode->i_ino)
goto end_rmdir;
retval = -ENOTEMPTY;
if (!ext4_empty_dir(inode))
goto end_rmdir;
handle = ext4_journal_start(dir, EXT4_HT_DIR,
EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
if (IS_ERR(handle)) {
retval = PTR_ERR(handle);
handle = NULL;
goto end_rmdir;
}
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
retval = ext4_delete_entry(handle, dir, de, bh);
if (retval)
goto end_rmdir;
if (!EXT4_DIR_LINK_EMPTY(inode))
ext4_warning_inode(inode,
"empty directory '%.*s' has too many links (%u)",
dentry->d_name.len, dentry->d_name.name,
inode->i_nlink);
inode->i_version++;
clear_nlink(inode);
/* There's no need to set i_disksize: the fact that i_nlink is
* zero will ensure that the right thing happens during any
* recovery. */
inode->i_size = 0;
ext4_orphan_add(handle, inode);
inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
ext4_mark_inode_dirty(handle, inode);
ext4_dec_count(handle, dir);
ext4_update_dx_flag(dir);
ext4_mark_inode_dirty(handle, dir);
end_rmdir:
brelse(bh);
if (handle)
ext4_journal_stop(handle);
return retval;
}
static int ext4_unlink(struct inode *dir, struct dentry *dentry)
{
int retval;
struct inode *inode;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
handle_t *handle = NULL;
if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
return -EIO;
trace_ext4_unlink_enter(dir, dentry);
/* Initialize quotas before so that eventual writes go
* in separate transaction */
retval = dquot_initialize(dir);
if (retval)
return retval;
retval = dquot_initialize(d_inode(dentry));
if (retval)
return retval;
retval = -ENOENT;
bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh)
goto end_unlink;
inode = d_inode(dentry);
retval = -EFSCORRUPTED;
if (le32_to_cpu(de->inode) != inode->i_ino)
goto end_unlink;
handle = ext4_journal_start(dir, EXT4_HT_DIR,
EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
if (IS_ERR(handle)) {
retval = PTR_ERR(handle);
handle = NULL;
goto end_unlink;
}
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
if (inode->i_nlink == 0) {
ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
dentry->d_name.len, dentry->d_name.name);
set_nlink(inode, 1);
}
retval = ext4_delete_entry(handle, dir, de, bh);
if (retval)
goto end_unlink;
dir->i_ctime = dir->i_mtime = current_time(dir);
ext4_update_dx_flag(dir);
ext4_mark_inode_dirty(handle, dir);
drop_nlink(inode);
if (!inode->i_nlink)
ext4_orphan_add(handle, inode);
inode->i_ctime = current_time(inode);
ext4_mark_inode_dirty(handle, inode);
end_unlink:
brelse(bh);
if (handle)
ext4_journal_stop(handle);
trace_ext4_unlink_exit(dentry, retval);
return retval;
}
static int ext4_symlink(struct inode *dir,
struct dentry *dentry, const char *symname)
{
handle_t *handle;
struct inode *inode;
int err, len = strlen(symname);
int credits;
bool encryption_required;
struct fscrypt_str disk_link;
struct fscrypt_symlink_data *sd = NULL;
if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
return -EIO;
disk_link.len = len + 1;
disk_link.name = (char *) symname;
encryption_required = (ext4_encrypted_inode(dir) ||
DUMMY_ENCRYPTION_ENABLED(EXT4_SB(dir->i_sb)));
if (encryption_required) {
err = fscrypt_get_encryption_info(dir);
if (err)
return err;
if (!fscrypt_has_encryption_key(dir))
return -ENOKEY;
disk_link.len = (fscrypt_fname_encrypted_size(dir, len) +
sizeof(struct fscrypt_symlink_data));
sd = kzalloc(disk_link.len, GFP_KERNEL);
if (!sd)
return -ENOMEM;
}
if (disk_link.len > dir->i_sb->s_blocksize) {
err = -ENAMETOOLONG;
goto err_free_sd;
}
err = dquot_initialize(dir);
if (err)
goto err_free_sd;
if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
/*
* For non-fast symlinks, we just allocate inode and put it on
* orphan list in the first transaction => we need bitmap,
* group descriptor, sb, inode block, quota blocks, and
* possibly selinux xattr blocks.
*/
credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
EXT4_XATTR_TRANS_BLOCKS;
} else {
/*
* Fast symlink. We have to add entry to directory
* (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
* allocate new inode (bitmap, group descriptor, inode block,
* quota blocks, sb is already counted in previous macros).
*/
credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
}
inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO,
&dentry->d_name, 0, NULL,
EXT4_HT_DIR, credits);
handle = ext4_journal_current_handle();
if (IS_ERR(inode)) {
if (handle)
ext4_journal_stop(handle);
err = PTR_ERR(inode);
goto err_free_sd;
}
if (encryption_required) {
struct qstr istr;
struct fscrypt_str ostr =
FSTR_INIT(sd->encrypted_path, disk_link.len);
istr.name = (const unsigned char *) symname;
istr.len = len;
err = fscrypt_fname_usr_to_disk(inode, &istr, &ostr);
if (err)
goto err_drop_inode;
sd->len = cpu_to_le16(ostr.len);
disk_link.name = (char *) sd;
inode->i_op = &ext4_encrypted_symlink_inode_operations;
}
if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
if (!encryption_required)
inode->i_op = &ext4_symlink_inode_operations;
inode_nohighmem(inode);
ext4_set_aops(inode);
/*
* We cannot call page_symlink() with transaction started
* because it calls into ext4_write_begin() which can wait
* for transaction commit if we are running out of space
* and thus we deadlock. So we have to stop transaction now
* and restart it when symlink contents is written.
*
* To keep fs consistent in case of crash, we have to put inode
* to orphan list in the mean time.
*/
drop_nlink(inode);
err = ext4_orphan_add(handle, inode);
ext4_journal_stop(handle);
handle = NULL;
if (err)
goto err_drop_inode;
err = __page_symlink(inode, disk_link.name, disk_link.len, 1);
if (err)
goto err_drop_inode;
/*
* Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
* + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
*/
handle = ext4_journal_start(dir, EXT4_HT_DIR,
EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
handle = NULL;
goto err_drop_inode;
}
set_nlink(inode, 1);
err = ext4_orphan_del(handle, inode);
if (err)
goto err_drop_inode;
} else {
/* clear the extent format for fast symlink */
ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
if (!encryption_required) {
inode->i_op = &ext4_fast_symlink_inode_operations;
inode->i_link = (char *)&EXT4_I(inode)->i_data;
}
memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
disk_link.len);
inode->i_size = disk_link.len - 1;
}
EXT4_I(inode)->i_disksize = inode->i_size;
err = ext4_add_nondir(handle, dentry, inode);
if (!err && IS_DIRSYNC(dir))
ext4_handle_sync(handle);
if (handle)
ext4_journal_stop(handle);
kfree(sd);
return err;
err_drop_inode:
if (handle)
ext4_journal_stop(handle);
clear_nlink(inode);
unlock_new_inode(inode);
iput(inode);
err_free_sd:
kfree(sd);
return err;
}
static int ext4_link(struct dentry *old_dentry,
struct inode *dir, struct dentry *dentry)
{
handle_t *handle;
struct inode *inode = d_inode(old_dentry);
int err, retries = 0;
if (inode->i_nlink >= EXT4_LINK_MAX)
return -EMLINK;
err = fscrypt_prepare_link(old_dentry, dir, dentry);
if (err)
return err;
if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
(!projid_eq(EXT4_I(dir)->i_projid,
EXT4_I(old_dentry->d_inode)->i_projid)))
return -EXDEV;
err = dquot_initialize(dir);
if (err)
return err;
retry:
handle = ext4_journal_start(dir, EXT4_HT_DIR,
(EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
if (IS_ERR(handle))
return PTR_ERR(handle);
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
inode->i_ctime = current_time(inode);
ext4_inc_count(handle, inode);
ihold(inode);
err = ext4_add_entry(handle, dentry, inode);
if (!err) {
ext4_mark_inode_dirty(handle, inode);
/* this can happen only for tmpfile being
* linked the first time
*/
if (inode->i_nlink == 1)
ext4_orphan_del(handle, inode);
d_instantiate(dentry, inode);
} else {
drop_nlink(inode);
iput(inode);
}
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
/*
* Try to find buffer head where contains the parent block.
* It should be the inode block if it is inlined or the 1st block
* if it is a normal dir.
*/
static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
struct inode *inode,
int *retval,
struct ext4_dir_entry_2 **parent_de,
int *inlined)
{
struct buffer_head *bh;
if (!ext4_has_inline_data(inode)) {
bh = ext4_read_dirblock(inode, 0, EITHER);
if (IS_ERR(bh)) {
*retval = PTR_ERR(bh);
return NULL;
}
*parent_de = ext4_next_entry(
(struct ext4_dir_entry_2 *)bh->b_data,
inode->i_sb->s_blocksize);
return bh;
}
*inlined = 1;
return ext4_get_first_inline_block(inode, parent_de, retval);
}
struct ext4_renament {
struct inode *dir;
struct dentry *dentry;
struct inode *inode;
bool is_dir;
int dir_nlink_delta;
/* entry for "dentry" */
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
int inlined;
/* entry for ".." in inode if it's a directory */
struct buffer_head *dir_bh;
struct ext4_dir_entry_2 *parent_de;
int dir_inlined;
};
static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
{
int retval;
ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
&retval, &ent->parent_de,
&ent->dir_inlined);
if (!ent->dir_bh)
return retval;
if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
return -EFSCORRUPTED;
BUFFER_TRACE(ent->dir_bh, "get_write_access");
return ext4_journal_get_write_access(handle, ent->dir_bh);
}
static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
unsigned dir_ino)
{
int retval;
ent->parent_de->inode = cpu_to_le32(dir_ino);
BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
if (!ent->dir_inlined) {
if (is_dx(ent->inode)) {
retval = ext4_handle_dirty_dx_node(handle,
ent->inode,
ent->dir_bh);
} else {
retval = ext4_handle_dirty_dirent_node(handle,
ent->inode,
ent->dir_bh);
}
} else {
retval = ext4_mark_inode_dirty(handle, ent->inode);
}
if (retval) {
ext4_std_error(ent->dir->i_sb, retval);
return retval;
}
return 0;
}
static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
unsigned ino, unsigned file_type)
{
int retval;
BUFFER_TRACE(ent->bh, "get write access");
retval = ext4_journal_get_write_access(handle, ent->bh);
if (retval)
return retval;
ent->de->inode = cpu_to_le32(ino);
if (ext4_has_feature_filetype(ent->dir->i_sb))
ent->de->file_type = file_type;
ent->dir->i_version++;
ent->dir->i_ctime = ent->dir->i_mtime =
current_time(ent->dir);
ext4_mark_inode_dirty(handle, ent->dir);
BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
if (!ent->inlined) {
retval = ext4_handle_dirty_dirent_node(handle,
ent->dir, ent->bh);
if (unlikely(retval)) {
ext4_std_error(ent->dir->i_sb, retval);
return retval;
}
}
brelse(ent->bh);
ent->bh = NULL;
return 0;
}
static int ext4_find_delete_entry(handle_t *handle, struct inode *dir,
const struct qstr *d_name)
{
int retval = -ENOENT;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
bh = ext4_find_entry(dir, d_name, &de, NULL);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (bh) {
retval = ext4_delete_entry(handle, dir, de, bh);
brelse(bh);
}
return retval;
}
static void ext4_rename_delete(handle_t *handle, struct ext4_renament *ent,
int force_reread)
{
int retval;
/*
* ent->de could have moved from under us during htree split, so make
* sure that we are deleting the right entry. We might also be pointing
* to a stale entry in the unused part of ent->bh so just checking inum
* and the name isn't enough.
*/
if (le32_to_cpu(ent->de->inode) != ent->inode->i_ino ||
ent->de->name_len != ent->dentry->d_name.len ||
strncmp(ent->de->name, ent->dentry->d_name.name,
ent->de->name_len) ||
force_reread) {
retval = ext4_find_delete_entry(handle, ent->dir,
&ent->dentry->d_name);
} else {
retval = ext4_delete_entry(handle, ent->dir, ent->de, ent->bh);
if (retval == -ENOENT) {
retval = ext4_find_delete_entry(handle, ent->dir,
&ent->dentry->d_name);
}
}
if (retval) {
ext4_warning_inode(ent->dir,
"Deleting old file: nlink %d, error=%d",
ent->dir->i_nlink, retval);
}
}
static void ext4_update_dir_count(handle_t *handle, struct ext4_renament *ent)
{
if (ent->dir_nlink_delta) {
if (ent->dir_nlink_delta == -1)
ext4_dec_count(handle, ent->dir);
else
ext4_inc_count(handle, ent->dir);
ext4_mark_inode_dirty(handle, ent->dir);
}
}
static struct inode *ext4_whiteout_for_rename(struct ext4_renament *ent,
int credits, handle_t **h)
{
struct inode *wh;
handle_t *handle;
int retries = 0;
/*
* for inode block, sb block, group summaries,
* and inode bitmap
*/
credits += (EXT4_MAXQUOTAS_TRANS_BLOCKS(ent->dir->i_sb) +
EXT4_XATTR_TRANS_BLOCKS + 4);
retry:
wh = ext4_new_inode_start_handle(ent->dir, S_IFCHR | WHITEOUT_MODE,
&ent->dentry->d_name, 0, NULL,
EXT4_HT_DIR, credits);
handle = ext4_journal_current_handle();
if (IS_ERR(wh)) {
if (handle)
ext4_journal_stop(handle);
if (PTR_ERR(wh) == -ENOSPC &&
ext4_should_retry_alloc(ent->dir->i_sb, &retries))
goto retry;
} else {
*h = handle;
init_special_inode(wh, wh->i_mode, WHITEOUT_DEV);
wh->i_op = &ext4_special_inode_operations;
}
return wh;
}
/*
* Anybody can rename anything with this: the permission checks are left to the
* higher-level routines.
*
* n.b. old_{dentry,inode) refers to the source dentry/inode
* while new_{dentry,inode) refers to the destination dentry/inode
* This comes from rename(const char *oldpath, const char *newpath)
*/
static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
unsigned int flags)
{
handle_t *handle = NULL;
struct ext4_renament old = {
.dir = old_dir,
.dentry = old_dentry,
.inode = d_inode(old_dentry),
};
struct ext4_renament new = {
.dir = new_dir,
.dentry = new_dentry,
.inode = d_inode(new_dentry),
};
int force_reread;
int retval;
struct inode *whiteout = NULL;
int credits;
u8 old_file_type;
if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) &&
(!projid_eq(EXT4_I(new_dir)->i_projid,
EXT4_I(old_dentry->d_inode)->i_projid)))
return -EXDEV;
retval = dquot_initialize(old.dir);
if (retval)
return retval;
retval = dquot_initialize(new.dir);
if (retval)
return retval;
/* Initialize quotas before so that eventual writes go
* in separate transaction */
if (new.inode) {
retval = dquot_initialize(new.inode);
if (retval)
return retval;
}
old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL);
if (IS_ERR(old.bh))
return PTR_ERR(old.bh);
/*
* Check for inode number is _not_ due to possible IO errors.
* We might rmdir the source, keep it as pwd of some process
* and merrily kill the link to whatever was created under the
* same name. Goodbye sticky bit ;-<
*/
retval = -ENOENT;
if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
goto end_rename;
new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
&new.de, &new.inlined);
if (IS_ERR(new.bh)) {
retval = PTR_ERR(new.bh);
new.bh = NULL;
goto end_rename;
}
if (new.bh) {
if (!new.inode) {
brelse(new.bh);
new.bh = NULL;
}
}
if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
ext4_alloc_da_blocks(old.inode);
credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
if (!(flags & RENAME_WHITEOUT)) {
handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
if (IS_ERR(handle)) {
retval = PTR_ERR(handle);
handle = NULL;
goto end_rename;
}
} else {
whiteout = ext4_whiteout_for_rename(&old, credits, &handle);
if (IS_ERR(whiteout)) {
retval = PTR_ERR(whiteout);
whiteout = NULL;
goto end_rename;
}
}
if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
ext4_handle_sync(handle);
if (S_ISDIR(old.inode->i_mode)) {
if (new.inode) {
retval = -ENOTEMPTY;
if (!ext4_empty_dir(new.inode))
goto end_rename;
} else {
retval = -EMLINK;
if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
goto end_rename;
}
retval = ext4_rename_dir_prepare(handle, &old);
if (retval)
goto end_rename;
}
/*
* If we're renaming a file within an inline_data dir and adding or
* setting the new dirent causes a conversion from inline_data to
* extents/blockmap, we need to force the dirent delete code to
* re-read the directory, or else we end up trying to delete a dirent
* from what is now the extent tree root (or a block map).
*/
force_reread = (new.dir->i_ino == old.dir->i_ino &&
ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
old_file_type = old.de->file_type;
if (whiteout) {
/*
* Do this before adding a new entry, so the old entry is sure
* to be still pointing to the valid old entry.
*/
retval = ext4_setent(handle, &old, whiteout->i_ino,
EXT4_FT_CHRDEV);
if (retval)
goto end_rename;
ext4_mark_inode_dirty(handle, whiteout);
}
if (!new.bh) {
retval = ext4_add_entry(handle, new.dentry, old.inode);
if (retval)
goto end_rename;
} else {
retval = ext4_setent(handle, &new,
old.inode->i_ino, old_file_type);
if (retval)
goto end_rename;
}
if (force_reread)
force_reread = !ext4_test_inode_flag(new.dir,
EXT4_INODE_INLINE_DATA);
/*
* Like most other Unix systems, set the ctime for inodes on a
* rename.
*/
old.inode->i_ctime = current_time(old.inode);
ext4_mark_inode_dirty(handle, old.inode);
if (!whiteout) {
/*
* ok, that's it
*/
ext4_rename_delete(handle, &old, force_reread);
}
if (new.inode) {
ext4_dec_count(handle, new.inode);
new.inode->i_ctime = current_time(new.inode);
}
old.dir->i_ctime = old.dir->i_mtime = current_time(old.dir);
ext4_update_dx_flag(old.dir);
if (old.dir_bh) {
retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
if (retval)
goto end_rename;
ext4_dec_count(handle, old.dir);
if (new.inode) {
/* checked ext4_empty_dir above, can't have another
* parent, ext4_dec_count() won't work for many-linked
* dirs */
clear_nlink(new.inode);
} else {
ext4_inc_count(handle, new.dir);
ext4_update_dx_flag(new.dir);
ext4_mark_inode_dirty(handle, new.dir);
}
}
ext4_mark_inode_dirty(handle, old.dir);
if (new.inode) {
ext4_mark_inode_dirty(handle, new.inode);
if (!new.inode->i_nlink)
ext4_orphan_add(handle, new.inode);
}
retval = 0;
end_rename:
brelse(old.dir_bh);
brelse(old.bh);
brelse(new.bh);
if (whiteout) {
if (retval)
drop_nlink(whiteout);
unlock_new_inode(whiteout);
iput(whiteout);
}
if (handle)
ext4_journal_stop(handle);
return retval;
}
static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
handle_t *handle = NULL;
struct ext4_renament old = {
.dir = old_dir,
.dentry = old_dentry,
.inode = d_inode(old_dentry),
};
struct ext4_renament new = {
.dir = new_dir,
.dentry = new_dentry,
.inode = d_inode(new_dentry),
};
u8 new_file_type;
int retval;
struct timespec ctime;
if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
!projid_eq(EXT4_I(new_dir)->i_projid,
EXT4_I(old_dentry->d_inode)->i_projid)) ||
(ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
!projid_eq(EXT4_I(old_dir)->i_projid,
EXT4_I(new_dentry->d_inode)->i_projid)))
return -EXDEV;
retval = dquot_initialize(old.dir);
if (retval)
return retval;
retval = dquot_initialize(new.dir);
if (retval)
return retval;
old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
&old.de, &old.inlined);
if (IS_ERR(old.bh))
return PTR_ERR(old.bh);
/*
* Check for inode number is _not_ due to possible IO errors.
* We might rmdir the source, keep it as pwd of some process
* and merrily kill the link to whatever was created under the
* same name. Goodbye sticky bit ;-<
*/
retval = -ENOENT;
if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
goto end_rename;
new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
&new.de, &new.inlined);
if (IS_ERR(new.bh)) {
retval = PTR_ERR(new.bh);
new.bh = NULL;
goto end_rename;
}
/* RENAME_EXCHANGE case: old *and* new must both exist */
if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
goto end_rename;
handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
(2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
if (IS_ERR(handle)) {
retval = PTR_ERR(handle);
handle = NULL;
goto end_rename;
}
if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
ext4_handle_sync(handle);
if (S_ISDIR(old.inode->i_mode)) {
old.is_dir = true;
retval = ext4_rename_dir_prepare(handle, &old);
if (retval)
goto end_rename;
}
if (S_ISDIR(new.inode->i_mode)) {
new.is_dir = true;
retval = ext4_rename_dir_prepare(handle, &new);
if (retval)
goto end_rename;
}
/*
* Other than the special case of overwriting a directory, parents'
* nlink only needs to be modified if this is a cross directory rename.
*/
if (old.dir != new.dir && old.is_dir != new.is_dir) {
old.dir_nlink_delta = old.is_dir ? -1 : 1;
new.dir_nlink_delta = -old.dir_nlink_delta;
retval = -EMLINK;
if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
(new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
goto end_rename;
}
new_file_type = new.de->file_type;
retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
if (retval)
goto end_rename;
retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
if (retval)
goto end_rename;
/*
* Like most other Unix systems, set the ctime for inodes on a
* rename.
*/
ctime = current_time(old.inode);
old.inode->i_ctime = ctime;
new.inode->i_ctime = ctime;
ext4_mark_inode_dirty(handle, old.inode);
ext4_mark_inode_dirty(handle, new.inode);
if (old.dir_bh) {
retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
if (retval)
goto end_rename;
}
if (new.dir_bh) {
retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
if (retval)
goto end_rename;
}
ext4_update_dir_count(handle, &old);
ext4_update_dir_count(handle, &new);
retval = 0;
end_rename:
brelse(old.dir_bh);
brelse(new.dir_bh);
brelse(old.bh);
brelse(new.bh);
if (handle)
ext4_journal_stop(handle);
return retval;
}
static int ext4_rename2(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
unsigned int flags)
{
int err;
if (unlikely(ext4_forced_shutdown(EXT4_SB(old_dir->i_sb))))
return -EIO;
if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
return -EINVAL;
err = fscrypt_prepare_rename(old_dir, old_dentry, new_dir, new_dentry,
flags);
if (err)
return err;
if (flags & RENAME_EXCHANGE) {
return ext4_cross_rename(old_dir, old_dentry,
new_dir, new_dentry);
}
return ext4_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
}
/*
* directories can handle most operations...
*/
const struct inode_operations ext4_dir_inode_operations = {
.create = ext4_create,
.lookup = ext4_lookup,
.link = ext4_link,
.unlink = ext4_unlink,
.symlink = ext4_symlink,
.mkdir = ext4_mkdir,
.rmdir = ext4_rmdir,
.mknod = ext4_mknod,
.tmpfile = ext4_tmpfile,
.rename = ext4_rename2,
.setattr = ext4_setattr,
.getattr = ext4_getattr,
.listxattr = ext4_listxattr,
.get_acl = ext4_get_acl,
.set_acl = ext4_set_acl,
.fiemap = ext4_fiemap,
};
const struct inode_operations ext4_special_inode_operations = {
.setattr = ext4_setattr,
.getattr = ext4_getattr,
.listxattr = ext4_listxattr,
.get_acl = ext4_get_acl,
.set_acl = ext4_set_acl,
};
| val2k/linux | fs/ext4/namei.c | C | gpl-2.0 | 104,545 |
<?php
if (!get_option('users_can_register')) return;
add_action('login_enqueue_scripts','sfc_register_enqueue_scripts');
function sfc_register_enqueue_scripts() {
wp_enqueue_script('jquery');
}
add_action('sfc_login_new_fb_user', 'sfc_register_redirect');
function sfc_register_redirect() {
wp_redirect(site_url('wp-login.php?action=register', 'login'));
exit;
}
remove_action('login_form','sfc_login_add_login_button');
add_action('login_form','sfc_register_add_login_button');
function sfc_register_add_login_button() {
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', 'sfc_register_form_script');
$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('sfc_register_redirect', site_url('wp-login.php?action=register', 'login') ); ?>"
width="262"
>
</fb:registration>
<?php
}
function sfc_register_form_script() {
?>
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','sfc_register_handle_signed_request');
function sfc_register_handle_signed_request() {
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 = sfc_base64_url_decode($encoded_sig);
$data = json_decode(sfc_base64_url_decode($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('sfc_register_request',$info);
}
}
}
}
} | tahitinuiarena/site | wp-content/plugins/simple-facebook-connect/sfc-register.php | PHP | gpl-2.0 | 3,192 |
<?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->getCurrentSubscribers();
$url = $this->argument('url');
if (!starts_with($url, ['http://', 'https://'])) {
$url = $this->laravel['url']->to($url);
}
$subscribers[] = ['url' => $url];
return $subscribers;
}
/**
* Get the current subscriber list.
*
* @return array
*/
protected function getCurrentSubscribers()
{
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.'],
];
}
}
| SalocinDotTEN/FindRecycler-AHKL15 | vendor/laravel/framework/src/Illuminate/Queue/Console/SubscribeCommand.php | PHP | gpl-2.0 | 3,476 |
/**********************************************************************\
* gnc-tree-view-account.h -- GtkTreeView implementation to display *
* accounts in a GtkTreeView. *
* Copyright (C) 2003,2005,2006 David Hampton <hampton@employees.org> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation; either version 2 of *
* the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, contact: *
* *
* Free Software Foundation Voice: +1-617-542-5942 *
* 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 *
* Boston, MA 02110-1301, USA gnu@gnu.org *
* *
\**********************************************************************/
/** @addtogroup GUI
@{ */
/** @addtogroup GuiTreeModel
* @{ */
/** @file gnc-tree-view-account.h
@brief GtkTreeView implementation for gnucash account tree.
@author Copyright (C) 2003,2005,2006 David Hampton <hampton@employees.org>
*/
#ifndef __GNC_TREE_VIEW_ACCOUNT_H
#define __GNC_TREE_VIEW_ACCOUNT_H
#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 GNC_TYPE_TREE_VIEW_ACCOUNT (gnc_tree_view_account_get_type ())
#define GNC_TREE_VIEW_ACCOUNT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GNC_TYPE_TREE_VIEW_ACCOUNT, GncTreeViewAccount))
#define GNC_TREE_VIEW_ACCOUNT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GNC_TYPE_TREE_VIEW_ACCOUNT, GncTreeViewAccountClass))
#define GNC_IS_TREE_VIEW_ACCOUNT(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GNC_TYPE_TREE_VIEW_ACCOUNT))
#define GNC_IS_TREE_VIEW_ACCOUNT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GNC_TYPE_TREE_VIEW_ACCOUNT))
#define GNC_TREE_VIEW_ACCOUNT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GNC_TYPE_TREE_VIEW_ACCOUNT, GncTreeViewAccountClass))
#define GNC_TREE_VIEW_ACCOUNT_NAME "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;
} GncTreeViewAccountClass;
typedef struct
{
GtkWidget *dialog;
GtkTreeModel *model;
GncTreeViewAccount *tree_view;
GHashTable *filter_override;
guint32 visible_types;
guint32 original_visible_types;
gboolean show_hidden;
gboolean original_show_hidden;
gboolean show_zero_total;
gboolean original_show_zero_total;
gboolean show_unused;
gboolean original_show_unused;
} AccountFilterDialog;
void account_filter_dialog_create(AccountFilterDialog *fd,
GncPluginPage *page);
gboolean gnc_plugin_page_account_tree_filter_accounts (Account *account,
gpointer user_data);
/* "Filter By" dialog callbacks */
void gppat_filter_show_hidden_toggled_cb (GtkToggleButton *togglebutton,
AccountFilterDialog *fd);
void gppat_filter_show_zero_toggled_cb (GtkToggleButton *togglebutton,
AccountFilterDialog *fd);
void gppat_filter_show_unused_toggled_cb (GtkToggleButton *togglebutton,
AccountFilterDialog *fd);
void gppat_filter_clear_all_cb (GtkWidget *button, AccountFilterDialog *fd);
void gppat_filter_select_all_cb (GtkWidget *button, AccountFilterDialog *fd);
void gppat_filter_select_default_cb (GtkWidget *button,
AccountFilterDialog *fd);
void gppat_filter_response_cb (GtkWidget *dialog, gint response,
AccountFilterDialog *fd);
/* Saving/Restoring */
void gnc_tree_view_account_save(GncTreeViewAccount *tree_view,
AccountFilterDialog *fd,
GKeyFile *key_file, const gchar *group_name);
void gnc_tree_view_account_restore(GncTreeViewAccount *view,
AccountFilterDialog *fd,
GKeyFile *key_file,
const gchar *group_name);
void gnc_tree_view_account_save_filter (GncTreeViewAccount *tree_view,
AccountFilterDialog *fd,
GKeyFile *key_file,
const gchar *group_name);
void gnc_tree_view_account_restore_filter (GncTreeViewAccount *view,
AccountFilterDialog *fd,
GKeyFile *key_file,
const gchar *group_name);
/* Get the GType for an GncTreeViewAccount object. */
GType gnc_tree_view_account_get_type (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 *gnc_tree_view_account_new_with_root (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 *gnc_tree_view_account_new (gboolean show_root);
/** @} */
/** @name Account Tree View Configuration
@{ */
typedef gchar * (*GncTreeViewAccountColumnSource) (Account *account,
GtkTreeViewColumn *col,
GtkCellRenderer *cell);
typedef void (*GncTreeViewAccountColumnTextEdited) (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 * gnc_tree_view_account_add_custom_column(
GncTreeViewAccount *view, const gchar *column_title,
GncTreeViewAccountColumnSource source_cb,
GncTreeViewAccountColumnTextEdited edited_cb);
GtkTreeViewColumn *gnc_tree_view_account_add_custom_column_renderer(
GncTreeViewAccount *account_view, const gchar *column_title,
GncTreeViewAccountColumnSource col_source_cb,
GncTreeViewAccountColumnTextEdited col_edited_cb,
GtkCellRenderer *renderer);
void gnc_tree_view_account_set_name_edited(GncTreeViewAccount *view,
GncTreeViewAccountColumnTextEdited edited_cb);
void gnc_tree_view_account_name_edited_cb(Account *account, GtkTreeViewColumn *col, const gchar *new_name);
void gnc_tree_view_account_set_code_edited(GncTreeViewAccount *view,
GncTreeViewAccountColumnTextEdited edited_cb);
void gnc_tree_view_account_code_edited_cb(Account *account, GtkTreeViewColumn *col, const gchar *new_code);
void gnc_tree_view_account_set_description_edited(GncTreeViewAccount *view,
GncTreeViewAccountColumnTextEdited edited_cb);
void gnc_tree_view_account_description_edited_cb(Account *account, GtkTreeViewColumn *col, const gchar *new_desc);
void gnc_tree_view_account_set_notes_edited(GncTreeViewAccount *view,
GncTreeViewAccountColumnTextEdited edited_cb);
void gnc_tree_view_account_notes_edited_cb(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 *
gnc_tree_view_account_add_property_column (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 gnc_tree_view_account_set_view_info 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 gnc_tree_view_account_get_view_info (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 gnc_tree_view_account_get_view_info 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 gnc_tree_view_account_set_view_info (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 (*gnc_tree_view_account_filter_func)(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 gnc_tree_view_account_set_filter (GncTreeViewAccount *account_view,
gnc_tree_view_account_filter_func func,
gpointer data,
GSourceFunc destroy);
/* This is a convenient filter function for use with
* gnc_tree_view_account_set_filter() and the functions in
* gnc-tree-model-account-types.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 gnc_tree_view_account_filter_by_view_info(
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 gnc_tree_view_account_refilter (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 gnc_tree_view_account_count_children (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 gnc_tree_view_account_clear_model_cache (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 * gnc_tree_view_account_get_account_from_path (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 * gnc_tree_view_account_get_account_from_iter (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 * gnc_tree_view_account_get_cursor_account (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 * gnc_tree_view_account_get_selected_account (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 gnc_tree_view_account_set_selected_account (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 * gnc_tree_view_account_get_selected_accounts (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 gnc_tree_view_account_set_selected_accounts (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 gnc_tree_view_account_select_subaccounts (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 gnc_tree_view_account_expand_to_account (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 gnc_tree_view_account_column_add_color (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 gnc_tree_view_account_set_editing_started_cb
(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 gnc_tree_view_account_set_editing_finished_cb
(GncTreeViewAccount *view, GFunc editing_finished_cb, gpointer editing_cb_data );
/** @} */
/** @} */
/** @} */
G_END_DECLS
#endif /* __GNC_TREE_VIEW_ACCOUNT_H */
| muehlburger/gnucash | gnucash/gnome-utils/gnc-tree-view-account.h | C | gpl-2.0 | 20,464 |
/**
* @package AcyMailing for Joomla!
* @version 4.8.1
* @author acyba.com
* @copyright (C) 2009-2014 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
@import url("module_default_radial_black.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, .acymailing_mootoolsbutton a:link, .acymailing_mootoolsbutton 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: -webkit-radial-gradient(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, .acymailing_mootoolsbutton a:hover, .acymailing_mootoolsbutton 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: -webkit-radial-gradient(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;}
| marcialsoto/cienciactiva | media/com_acymailing/css/module_default_radial_blue.css | CSS | gpl-2.0 | 2,751 |
<?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://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<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://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" border="0" /></a></td>
<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="draganddrop-draggableicons-dragwidget-cpp.html">draganddrop/draggableicons/dragwidget.cpp</a></li>
<li><a href="draganddrop-draggableicons-dragwidget-h.html">draganddrop/draggableicons/dragwidget.h</a></li>
<li><a href="draganddrop-draggableicons-main-cpp.html">draganddrop/draggableicons/main.cpp</a></li>
<li><a href="draganddrop-draggableicons-draggableicons-pro.html">draganddrop/draggableicons/draggableicons.pro</a></li>
<li><a href="draganddrop-draggableicons-draggableicons-qrc.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/draggableicons-example.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="dragwidget-class-definition"></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="dragwidget-class-implementation"></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>
| radekp/qtmoko | doc/html/draganddrop-draggableicons.html | HTML | gpl-2.0 | 6,846 |
<?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"
);
?>
| TTsWeb/U-232-V4 | lang/2/lang_viewnfo.php | PHP | gpl-2.0 | 237 |
/*
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
// MAIN.CPP - Entry point for the Architecture Description Language Compiler
#include "adlc.hpp"
//------------------------------Prototypes-------------------------------------
static void usage(ArchDesc& AD); // Print usage message and exit
static char *strip_ext(char *fname); // Strip off name extension
static char *base_plus_suffix(const char* base, const char *suffix);// New concatenated string
static int get_legal_text(FileBuff &fbuf, char **legal_text); // Get pointer to legal text
ArchDesc* globalAD = NULL; // global reference to Architecture Description object
const char* get_basename(const char* filename) {
const char *basename = filename;
const char *cp;
for (cp = basename; *cp; cp++) {
if (*cp == '/') {
basename = cp+1;
}
}
return basename;
}
//------------------------------main-------------------------------------------
int main(int argc, char *argv[])
{
ArchDesc AD; // Architecture Description object
globalAD = &AD;
// ResourceMark mark;
ADLParser *ADL_Parse; // ADL Parser object to parse AD file
// Check for proper arguments
if( argc == 1 ) usage(AD); // No arguments? Then print usage
// Read command line arguments and file names
for( int i = 1; i < argc; i++ ) { // For all arguments
register char *s = argv[i]; // Get option/filename
if( *s++ == '-' ) { // It's a flag? (not a filename)
if( !*s ) { // Stand-alone `-' means stdin
//********** INSERT CODE HERE **********
} else while (*s != '\0') { // While have flags on option
switch (*s++) { // Handle flag
case 'd': // Debug flag
AD._dfa_debug += 1; // Set Debug Flag
break;
case 'g': // Debug ad location flag
AD._adlocation_debug += 1; // Set Debug ad location Flag
break;
case 'o': // No Output Flag
AD._no_output ^= 1; // Toggle no_output flag
break;
case 'q': // Quiet Mode Flag
AD._quiet_mode ^= 1; // Toggle quiet_mode flag
break;
case 'w': // Disable Warnings Flag
AD._disable_warnings ^= 1; // Toggle disable_warnings flag
break;
case 'T': // Option to make DFA as many subroutine calls.
AD._dfa_small += 1; // Set Mode Flag
break;
case 'c': { // Set C++ Output file name
AD._CPP_file._name = s;
const char *base = strip_ext(strdup(s));
AD._CPP_CLONE_file._name = base_plus_suffix(base,"_clone.cpp");
AD._CPP_EXPAND_file._name = base_plus_suffix(base,"_expand.cpp");
AD._CPP_FORMAT_file._name = base_plus_suffix(base,"_format.cpp");
AD._CPP_GEN_file._name = base_plus_suffix(base,"_gen.cpp");
AD._CPP_MISC_file._name = base_plus_suffix(base,"_misc.cpp");
AD._CPP_PEEPHOLE_file._name = base_plus_suffix(base,"_peephole.cpp");
AD._CPP_PIPELINE_file._name = base_plus_suffix(base,"_pipeline.cpp");
s += strlen(s);
break;
}
case 'h': // Set C++ Output file name
AD._HPP_file._name = s; s += strlen(s);
break;
case 'v': // Set C++ Output file name
AD._VM_file._name = s; s += strlen(s);
break;
case 'a': // Set C++ Output file name
AD._DFA_file._name = s;
AD._bug_file._name = s;
s += strlen(s);
break;
case '#': // Special internal debug flag
AD._adl_debug++; // Increment internal debug level
break;
case 's': // Output which instructions are cisc-spillable
AD._cisc_spill_debug = true;
break;
case 'D': // Flag Definition
{
char* flag = s;
s += strlen(s);
char* def = strchr(flag, '=');
if (def == NULL) def = (char*)"1";
else *def++ = '\0';
AD.set_preproc_def(flag, def);
}
break;
case 'U': // Flag Un-Definition
{
char* flag = s;
s += strlen(s);
AD.set_preproc_def(flag, NULL);
}
break;
default: // Unknown option
usage(AD); // So print usage and exit
} // End of switch on options...
} // End of while have options...
} else { // Not an option; must be a filename
AD._ADL_file._name = argv[i]; // Set the input filename
// // Files for storage, based on input file name
const char *base = strip_ext(strdup(argv[i]));
char *temp = base_plus_suffix("dfa_",base);
AD._DFA_file._name = base_plus_suffix(temp,".cpp");
delete temp;
temp = base_plus_suffix("ad_",base);
AD._CPP_file._name = base_plus_suffix(temp,".cpp");
AD._CPP_CLONE_file._name = base_plus_suffix(temp,"_clone.cpp");
AD._CPP_EXPAND_file._name = base_plus_suffix(temp,"_expand.cpp");
AD._CPP_FORMAT_file._name = base_plus_suffix(temp,"_format.cpp");
AD._CPP_GEN_file._name = base_plus_suffix(temp,"_gen.cpp");
AD._CPP_MISC_file._name = base_plus_suffix(temp,"_misc.cpp");
AD._CPP_PEEPHOLE_file._name = base_plus_suffix(temp,"_peephole.cpp");
AD._CPP_PIPELINE_file._name = base_plus_suffix(temp,"_pipeline.cpp");
AD._HPP_file._name = base_plus_suffix(temp,".hpp");
delete temp;
temp = base_plus_suffix("adGlobals_",base);
AD._VM_file._name = base_plus_suffix(temp,".hpp");
delete temp;
temp = base_plus_suffix("bugs_",base);
AD._bug_file._name = base_plus_suffix(temp,".out");
delete temp;
} // End of files vs options...
} // End of while have command line arguments
// Open files used to store the matcher and its components
if (AD.open_files() == 0) return 1; // Open all input/output files
// Build the File Buffer, Parse the input, & Generate Code
FileBuff ADL_Buf(&AD._ADL_file, AD); // Create a file buffer for input file
// Get pointer to legal text at the beginning of AD file.
// It will be used in generated ad files.
char* legal_text;
int legal_sz = get_legal_text(ADL_Buf, &legal_text);
ADL_Parse = new ADLParser(ADL_Buf, AD); // Create a parser to parse the buffer
ADL_Parse->parse(); // Parse buffer & build description lists
if( AD._dfa_debug >= 1 ) { // For higher debug settings, print dump
AD.dump();
}
delete ADL_Parse; // Delete parser
// Verify that the results of the parse are consistent
AD.verify();
// Prepare to generate the result files:
AD.generateMatchLists();
AD.identify_unique_operands();
AD.identify_cisc_spill_instructions();
AD.identify_short_branches();
// Make sure every file starts with a copyright:
AD.addSunCopyright(legal_text, legal_sz, AD._HPP_file._fp); // .hpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_CLONE_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_EXPAND_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_FORMAT_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_GEN_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_MISC_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_PEEPHOLE_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_PIPELINE_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._VM_file._fp); // .hpp
AD.addSunCopyright(legal_text, legal_sz, AD._DFA_file._fp); // .cpp
// Add include guards for all .hpp files
AD.addIncludeGuardStart(AD._HPP_file, "GENERATED_ADFILES_AD_HPP"); // .hpp
AD.addIncludeGuardStart(AD._VM_file, "GENERATED_ADFILES_ADGLOBALS_HPP"); // .hpp
// Add includes
AD.addInclude(AD._CPP_file, "precompiled.hpp");
AD.addInclude(AD._CPP_file, "adfiles", get_basename(AD._VM_file._name));
AD.addInclude(AD._CPP_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_file, "memory/allocation.inline.hpp");
AD.addInclude(AD._CPP_file, "asm/macroAssembler.inline.hpp");
AD.addInclude(AD._CPP_file, "code/compiledIC.hpp");
AD.addInclude(AD._CPP_file, "code/nativeInst.hpp");
AD.addInclude(AD._CPP_file, "code/vmreg.inline.hpp");
AD.addInclude(AD._CPP_file, "gc/shared/collectedHeap.inline.hpp");
AD.addInclude(AD._CPP_file, "oops/compiledICHolder.hpp");
AD.addInclude(AD._CPP_file, "oops/markOop.hpp");
AD.addInclude(AD._CPP_file, "oops/method.hpp");
AD.addInclude(AD._CPP_file, "oops/oop.inline.hpp");
AD.addInclude(AD._CPP_file, "opto/cfgnode.hpp");
AD.addInclude(AD._CPP_file, "opto/intrinsicnode.hpp");
AD.addInclude(AD._CPP_file, "opto/locknode.hpp");
AD.addInclude(AD._CPP_file, "opto/opcodes.hpp");
AD.addInclude(AD._CPP_file, "opto/regalloc.hpp");
AD.addInclude(AD._CPP_file, "opto/regmask.hpp");
AD.addInclude(AD._CPP_file, "opto/runtime.hpp");
AD.addInclude(AD._CPP_file, "runtime/biasedLocking.hpp");
AD.addInclude(AD._CPP_file, "runtime/sharedRuntime.hpp");
AD.addInclude(AD._CPP_file, "runtime/stubRoutines.hpp");
AD.addInclude(AD._CPP_file, "utilities/growableArray.hpp");
AD.addInclude(AD._HPP_file, "memory/allocation.hpp");
AD.addInclude(AD._HPP_file, "code/nativeInst.hpp");
AD.addInclude(AD._HPP_file, "opto/machnode.hpp");
AD.addInclude(AD._HPP_file, "opto/node.hpp");
AD.addInclude(AD._HPP_file, "opto/regalloc.hpp");
AD.addInclude(AD._HPP_file, "opto/subnode.hpp");
AD.addInclude(AD._HPP_file, "opto/vectornode.hpp");
AD.addInclude(AD._CPP_CLONE_file, "precompiled.hpp");
AD.addInclude(AD._CPP_CLONE_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_EXPAND_file, "precompiled.hpp");
AD.addInclude(AD._CPP_EXPAND_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_FORMAT_file, "precompiled.hpp");
AD.addInclude(AD._CPP_FORMAT_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_GEN_file, "precompiled.hpp");
AD.addInclude(AD._CPP_GEN_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_GEN_file, "opto/cfgnode.hpp");
AD.addInclude(AD._CPP_GEN_file, "opto/locknode.hpp");
AD.addInclude(AD._CPP_MISC_file, "precompiled.hpp");
AD.addInclude(AD._CPP_MISC_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_PEEPHOLE_file, "precompiled.hpp");
AD.addInclude(AD._CPP_PEEPHOLE_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_PIPELINE_file, "precompiled.hpp");
AD.addInclude(AD._CPP_PIPELINE_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._DFA_file, "precompiled.hpp");
AD.addInclude(AD._DFA_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._DFA_file, "opto/cfgnode.hpp"); // Use PROB_MAX in predicate.
AD.addInclude(AD._DFA_file, "opto/intrinsicnode.hpp");
AD.addInclude(AD._DFA_file, "opto/matcher.hpp");
AD.addInclude(AD._DFA_file, "opto/narrowptrnode.hpp");
AD.addInclude(AD._DFA_file, "opto/opcodes.hpp");
AD.addInclude(AD._DFA_file, "opto/convertnode.hpp");
// Make sure each .cpp file starts with include lines:
// files declaring and defining generators for Mach* Objects (hpp,cpp)
// Generate the result files:
// enumerations, class definitions, object generators, and the DFA
// file containing enumeration of machine operands & instructions (hpp)
AD.addPreHeaderBlocks(AD._HPP_file._fp); // .hpp
AD.buildMachOperEnum(AD._HPP_file._fp); // .hpp
AD.buildMachOpcodesEnum(AD._HPP_file._fp); // .hpp
AD.buildMachRegisterNumbers(AD._VM_file._fp); // VM file
AD.buildMachRegisterEncodes(AD._HPP_file._fp); // .hpp file
AD.declareRegSizes(AD._HPP_file._fp); // .hpp
AD.build_pipeline_enums(AD._HPP_file._fp); // .hpp
// output definition of class "State"
AD.defineStateClass(AD._HPP_file._fp); // .hpp
// file declaring the Mach* classes derived from MachOper and MachNode
AD.declareClasses(AD._HPP_file._fp);
// declare and define maps: in the .hpp and .cpp files respectively
AD.addSourceBlocks(AD._CPP_file._fp); // .cpp
AD.addHeaderBlocks(AD._HPP_file._fp); // .hpp
AD.buildReduceMaps(AD._HPP_file._fp, AD._CPP_file._fp);
AD.buildMustCloneMap(AD._HPP_file._fp, AD._CPP_file._fp);
// build CISC_spilling oracle and MachNode::cisc_spill() methods
AD.build_cisc_spill_instructions(AD._HPP_file._fp, AD._CPP_file._fp);
// define methods for machine dependent State, MachOper, and MachNode classes
AD.defineClasses(AD._CPP_file._fp);
AD.buildMachOperGenerator(AD._CPP_GEN_file._fp);// .cpp
AD.buildMachNodeGenerator(AD._CPP_GEN_file._fp);// .cpp
// define methods for machine dependent instruction matching
AD.buildInstructMatchCheck(AD._CPP_file._fp); // .cpp
// define methods for machine dependent frame management
AD.buildFrameMethods(AD._CPP_file._fp); // .cpp
AD.generate_needs_clone_jvms(AD._CPP_file._fp);
// do this last:
AD.addPreprocessorChecks(AD._CPP_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_CLONE_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_EXPAND_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_FORMAT_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_GEN_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_MISC_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_PEEPHOLE_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_PIPELINE_file._fp); // .cpp
// define the finite automata that selects lowest cost production
AD.buildDFA(AD._DFA_file._fp);
// Add include guards for all .hpp files
AD.addIncludeGuardEnd(AD._HPP_file, "GENERATED_ADFILES_AD_HPP"); // .hpp
AD.addIncludeGuardEnd(AD._VM_file, "GENERATED_ADFILES_ADGLOBALS_HPP"); // .hpp
AD.close_files(0); // Close all input/output files
// Final printout and statistics
// cout << program;
if( AD._dfa_debug & 2 ) { // For higher debug settings, print timing info
// Timer t_stop;
// Timer t_total = t_stop - t_start; // Total running time
// cerr << "\n---Architecture Description Totals---\n";
// cerr << ", Total lines: " << TotalLines;
// float l = TotalLines;
// cerr << "\nTotal Compilation Time: " << t_total << "\n";
// float ft = (float)t_total;
// if( ft > 0.0 ) fprintf(stderr,"Lines/sec: %#5.2f\n", l/ft);
}
return (AD._syntax_errs + AD._semantic_errs + AD._internal_errs); // Bye Bye!!
}
//------------------------------usage------------------------------------------
static void usage(ArchDesc& AD)
{
printf("Architecture Description Language Compiler\n\n");
printf("Usage: adlc [-doqwTs] [-#]* [-D<FLAG>[=<DEF>]] [-U<FLAG>] [-c<CPP_FILE_NAME>] [-h<HPP_FILE_NAME>] [-a<DFA_FILE_NAME>] [-v<GLOBALS_FILE_NAME>] <ADL_FILE_NAME>\n");
printf(" d produce DFA debugging info\n");
printf(" o no output produced, syntax and semantic checking only\n");
printf(" q quiet mode, supresses all non-essential messages\n");
printf(" w suppress warning messages\n");
printf(" T make DFA as many subroutine calls\n");
printf(" s output which instructions are cisc-spillable\n");
printf(" D define preprocessor symbol\n");
printf(" U undefine preprocessor symbol\n");
printf(" c specify CPP file name (default: %s)\n", AD._CPP_file._name);
printf(" h specify HPP file name (default: %s)\n", AD._HPP_file._name);
printf(" a specify DFA output file name\n");
printf(" v specify adGlobals output file name\n");
printf(" # increment ADL debug level\n");
printf("\n");
}
//------------------------------open_file------------------------------------
int ArchDesc::open_file(bool required, ADLFILE & ADF, const char *action)
{
if (required &&
(ADF._fp = fopen(ADF._name, action)) == NULL) {
printf("ERROR: Cannot open file for %s: %s\n", action, ADF._name);
close_files(1);
return 0;
}
return 1;
}
//------------------------------open_files-------------------------------------
int ArchDesc::open_files(void)
{
if (_ADL_file._name == NULL)
{ printf("ERROR: No ADL input file specified\n"); return 0; }
if (!open_file(true , _ADL_file, "r")) { return 0; }
if (!open_file(!_no_output, _DFA_file, "w")) { return 0; }
if (!open_file(!_no_output, _HPP_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_CLONE_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_EXPAND_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_FORMAT_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_GEN_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_MISC_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_PEEPHOLE_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_PIPELINE_file, "w")) { return 0; }
if (!open_file(!_no_output, _VM_file , "w")) { return 0; }
if (!open_file(_dfa_debug != 0, _bug_file, "w")) { return 0; }
return 1;
}
//------------------------------close_file------------------------------------
void ArchDesc::close_file(int delete_out, ADLFILE& ADF)
{
if (ADF._fp) {
fclose(ADF._fp);
if (delete_out) remove(ADF._name);
}
}
//------------------------------close_files------------------------------------
void ArchDesc::close_files(int delete_out)
{
if (_ADL_file._fp) fclose(_ADL_file._fp);
close_file(delete_out, _CPP_file);
close_file(delete_out, _CPP_CLONE_file);
close_file(delete_out, _CPP_EXPAND_file);
close_file(delete_out, _CPP_FORMAT_file);
close_file(delete_out, _CPP_GEN_file);
close_file(delete_out, _CPP_MISC_file);
close_file(delete_out, _CPP_PEEPHOLE_file);
close_file(delete_out, _CPP_PIPELINE_file);
close_file(delete_out, _HPP_file);
close_file(delete_out, _DFA_file);
close_file(delete_out, _bug_file);
if (!_quiet_mode) {
printf("\n");
if (_no_output || delete_out) {
if (_ADL_file._name) printf("%s: ", _ADL_file._name);
printf("No output produced");
}
else {
if (_ADL_file._name) printf("%s --> ", _ADL_file._name);
printf("%s, %s, %s, %s, %s, %s, %s, %s, %s, %s",
_CPP_file._name,
_CPP_CLONE_file._name,
_CPP_EXPAND_file._name,
_CPP_FORMAT_file._name,
_CPP_GEN_file._name,
_CPP_MISC_file._name,
_CPP_PEEPHOLE_file._name,
_CPP_PIPELINE_file._name,
_HPP_file._name,
_DFA_file._name);
}
printf("\n");
}
}
//------------------------------strip_ext--------------------------------------
static char *strip_ext(char *fname)
{
char *ep;
if (fname) {
ep = fname + strlen(fname) - 1; // start at last character and look for '.'
while (ep >= fname && *ep != '.') --ep;
if (*ep == '.') *ep = '\0'; // truncate string at '.'
}
return fname;
}
//------------------------------base_plus_suffix-------------------------------
// New concatenated string
static char *base_plus_suffix(const char* base, const char *suffix)
{
int len = (int)strlen(base) + (int)strlen(suffix) + 1;
char* fname = new char[len];
sprintf(fname,"%s%s",base,suffix);
return fname;
}
//------------------------------get_legal_text---------------------------------
// Get pointer to legal text at the beginning of AD file.
// This code assumes that a legal text starts at the beginning of .ad files,
// is commented by "//" at each line and ends with empty line.
//
int get_legal_text(FileBuff &fbuf, char **legal_text)
{
char* legal_start = fbuf.get_line();
assert(legal_start[0] == '/' && legal_start[1] == '/', "Incorrect header of AD file");
char* legal_end = fbuf.get_line();
assert(strncmp(legal_end, "// Copyright", 12) == 0, "Incorrect header of AD file");
while(legal_end[0] == '/' && legal_end[1] == '/') {
legal_end = fbuf.get_line();
}
*legal_text = legal_start;
return (int) (legal_end - legal_start);
}
// VS2005 has its own definition, identical to this one.
#if !defined(_WIN32) || defined(_WIN64) || _MSC_VER < 1400
void *operator new( size_t size, int, const char *, int ) throw() {
return ::operator new( size );
}
#endif
| YouDiSN/OpenJDK-Research | jdk9/hotspot/src/share/vm/adlc/main.cpp | C++ | gpl-2.0 | 21,875 |
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8163346
* @summary Test hashing of extended characters in Serviceability Agent.
* @library /test/lib
* @library /lib/testlibrary
* @compile -encoding utf8 HeapDumpTest.java
* @run main/timeout=240 HeapDumpTest
*/
import static jdk.testlibrary.Asserts.assertTrue;
import java.io.IOException;
import java.io.File;
import java.util.List;
import java.util.Arrays;
import jdk.testlibrary.JDKToolLauncher;
import jdk.testlibrary.OutputAnalyzer;
import jdk.testlibrary.ProcessTools;
import jdk.test.lib.apps.LingeredApp;
import jdk.test.lib.Platform;
public class HeapDumpTest {
private static LingeredAppWithExtendedChars theApp = null;
/**
*
* @param vmArgs - tool arguments to launch jhsdb
* @return exit code of tool
*/
public static void launch(String expectedMessage, List<String> toolArgs)
throws IOException {
System.out.println("Starting LingeredApp");
try {
theApp = new LingeredAppWithExtendedChars();
LingeredApp.startApp(Arrays.asList("-Xmx256m"), theApp);
System.out.println(theApp.\u00CB);
System.out.println("Starting " + toolArgs.get(0) + " against " + theApp.getPid());
JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jhsdb");
for (String cmd : toolArgs) {
launcher.addToolArg(cmd);
}
launcher.addToolArg("--pid=" + Long.toString(theApp.getPid()));
ProcessBuilder processBuilder = new ProcessBuilder(launcher.getCommand());
processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
OutputAnalyzer output = ProcessTools.executeProcess(processBuilder);
System.out.println("stdout:");
System.out.println(output.getStdout());
System.out.println("stderr:");
System.out.println(output.getStderr());
output.shouldContain(expectedMessage);
output.shouldHaveExitValue(0);
} catch (Exception ex) {
throw new RuntimeException("Test ERROR " + ex, ex);
} finally {
LingeredApp.stopApp(theApp);
}
}
public static void launch(String expectedMessage, String... toolArgs)
throws IOException {
launch(expectedMessage, Arrays.asList(toolArgs));
}
public static void testHeapDump() throws IOException {
File dump = new File("jhsdb.jmap.heap." +
System.currentTimeMillis() + ".hprof");
if (dump.exists()) {
dump.delete();
}
launch("heap written to", "jmap",
"--binaryheap", "--dumpfile=" + dump.getAbsolutePath());
assertTrue(dump.exists() && dump.isFile(),
"Could not create dump file " + dump.getAbsolutePath());
dump.delete();
}
public static void main(String[] args) throws Exception {
if (!Platform.shouldSAAttach()) {
// Silently skip the test if we don't have enough permissions to attach
System.err.println("Error! Insufficient permissions to attach - test skipped.");
return;
}
testHeapDump();
// The test throws RuntimeException on error.
// IOException is thrown if LingeredApp can't start because of some bad
// environment condition
System.out.println("Test PASSED");
}
}
| YouDiSN/OpenJDK-Research | jdk9/jdk/test/sun/tools/jhsdb/HeapDumpTest.java | Java | gpl-2.0 | 4,479 |
/*****************************************************************************
* $Id: hash.h 2950 2005-01-18 20:09:32Z dun $
*****************************************************************************
* Copyright (C) 2003-2005 The Regents of the University of California.
* Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
* Written by Chris Dunlap <cdunlap@llnl.gov>.
*
* This file is from LSD-Tools, the LLNL Software Development Toolbox.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA.
*****************************************************************************/
#ifndef LSD_HASH_H
#define LSD_HASH_H
/*****************************************************************************
* Notes
*****************************************************************************/
/*
* 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 WITH_LSD_FATAL_ERROR_FUNC 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 WITH_LSD_NOMEM_ERROR_FUNC 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.
*/
/*****************************************************************************
* Data Types
*****************************************************************************/
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.
*/
/*****************************************************************************
* Functions
*****************************************************************************/
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 */
| garlick/gpib-utils | liblsd/hash.h | C | gpl-2.0 | 7,009 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Manager of RPC calls from plugins.
"""
from golismero.api.config import Config
__license__ = """
GoLismero 2.0 - The web knife - Copyright (C) 2011-2014
Golismero project site: https://github.com/golismero
Golismero project mail: contact@golismero-project.com
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
__all__ = ["RPCManager"]
from ..common import pickle
from ..messaging.codes import MessageCode, MSG_RPC_CODES
from ..messaging.manager import MessageManager
from functools import partial
from threading import Thread
import sys
import traceback
#------------------------------------------------------------------------------
# Decorators to automatically register RPC implementors at import time.
# Global map of RPC codes to implementors.
# dict( int -> tuple(callable, bool) )
rpcMap = {}
def implementor(rpc_code, blocking=False):
"""
RPC implementation function.
"""
return partial(_add_implementor, rpc_code, blocking)
def _add_implementor(rpc_code, blocking, fn):
# Validate the argument types.
if type(rpc_code) is not int:
raise TypeError("Expected int, got %r instead" % type(rpc_code))
if type(blocking) is not bool:
raise TypeError("Expected bool, got %r instead" % type(blocking))
if not callable(fn):
raise TypeError("Expected callable, got %r instead" % type(fn))
# Validate the RPC code.
if rpc_code in rpcMap:
try:
msg = "Duplicated RPC implementors for code %d: %s and %s"
msg %= (rpc_code, rpcMap[rpc_code][0].__name__, fn.__name__)
except Exception:
msg = "Duplicated RPC implementors for code: %d" % rpc_code
raise SyntaxError(msg)
# TODO: use introspection to validate the function signature
# Register the implementor.
rpcMap[rpc_code] = (fn, blocking)
# Return the implementor. No wrapping is needed! :)
return fn
#------------------------------------------------------------------------------
# Implementor for the special MSG_RPC_BULK code for bulk RPC calls.
@implementor(MessageCode.MSG_RPC_BULK)
def rpc_bulk(orchestrator, audit_name, rpc_code, *arguments):
# Get the implementor for the RPC code.
# Raise NotImplementedError if it's not defined.
try:
method, blocking = rpcMap[rpc_code]
except KeyError:
raise NotImplementedError("RPC code not implemented: %r" % rpc_code)
# This can't be done with blocking implementors!
if blocking:
raise NotImplementedError(
"Cannot run blocking RPC calls in bulk. Code: %r" % rpc_code)
# Prepare a partial function call to the implementor.
caller = partial(method, orchestrator, audit_name)
# Use the built-in map() function to issue all the calls.
# This ensures we support the exact same interface and functionality.
return map(caller, *arguments)
#------------------------------------------------------------------------------
# Ensures the message is received by the Orchestrator.
@implementor(MessageCode.MSG_RPC_SEND_MESSAGE)
def rpc_send_message(orchestrator, audit_name, message):
# Enqueue the ACK message.
orchestrator.enqueue_msg(message)
#------------------------------------------------------------------------------
class RPCManager (object):
"""
Executes remote procedure calls from plugins.
"""
#--------------------------------------------------------------------------
def __init__(self, orchestrator):
"""
:param orchestrator: Orchestrator instance.
:type orchestrator: Orchestrator
"""
# Keep a reference to the Orchestrator.
self.__orchestrator = orchestrator
# Keep a reference to the global RPC map (it's faster this way).
self.__rpcMap = rpcMap
# Check all RPC messages have been mapped at this point.
missing = MSG_RPC_CODES.difference(self.__rpcMap.keys())
if missing:
msg = "Missing RPC implementors for codes: %s"
msg %= ", ".join(str(x) for x in sorted(missing))
raise SyntaxError(msg)
#--------------------------------------------------------------------------
@property
def orchestrator(self):
"""
:returns: Orchestrator instance.
:rtype: Orchestrator
"""
return self.__orchestrator
#--------------------------------------------------------------------------
def execute_rpc(self, audit_name, rpc_code, response_queue, args, kwargs):
"""
Honor a remote procedure call request from a plugin.
:param audit_name: Name of the audit requesting the call.
:type audit_name: str
:param rpc_code: RPC code.
:type rpc_code: int
:param response_queue: Response queue identity.
:type response_queue: str
:param args: Positional arguments to the call.
:type args: tuple
:param kwargs: Keyword arguments to the call.
:type kwargs: dict
"""
try:
# Get the implementor for the RPC code.
# Raise NotImplementedError if it's not defined.
try:
target, blocking = self.__rpcMap[rpc_code]
except KeyError:
raise NotImplementedError(
"RPC code not implemented: %r" % rpc_code)
# If it's a blocking call...
if blocking:
# Run the implementor in a new thread.
thread = Thread(
target = self._execute_rpc_implementor_background,
args = (
Config._context,
audit_name,
target,
response_queue,
args, kwargs),
)
thread.daemon = True
thread.start()
# If it's a non-blocking call...
else:
# Call the implementor directly.
self.execute_rpc_implementor(
audit_name, target, response_queue, args, kwargs)
# Catch exceptions and send them back.
except Exception:
if response_queue:
error = self.prepare_exception(*sys.exc_info())
try:
self.orchestrator.messageManager.send(
response_queue, (False, error))
except IOError:
import warnings
warnings.warn("RPC caller died!")
pass
#--------------------------------------------------------------------------
def _execute_rpc_implementor_background(self, context, audit_name, target,
response_queue, args, kwargs):
"""
Honor a remote procedure call request from a plugin,
from a background thread. Must only be used as the entry
point for said background thread!
:param context: Plugin execution context.
:type context: PluginContext
:param audit_name: Name of the audit requesting the call.
:type audit_name: str
:param target: RPC implementor function.
:type target: callable
:param response_queue: Response queue identity.
:type response_queue: str
:param args: Positional arguments to the call.
:type args: tuple
:param kwargs: Keyword arguments to the call.
:type kwargs: dict
"""
Config._context = context
self.execute_rpc_implementor(
audit_name, target, response_queue, args, kwargs)
#--------------------------------------------------------------------------
def execute_rpc_implementor(self, audit_name, target, response_queue,
args, kwargs):
"""
Honor a remote procedure call request from a plugin.
:param audit_name: Name of the audit requesting the call.
:type audit_name: str
:param target: RPC implementor function.
:type target: callable
:param response_queue: Response queue identity.
:type response_queue: str
:param args: Positional arguments to the call.
:type args: tuple
:param kwargs: Keyword arguments to the call.
:type kwargs: dict
"""
try:
# Call the implementor and get the response.
response = target(self.orchestrator, audit_name, *args, **kwargs)
success = True
# Catch exceptions and prepare them for sending.
except Exception:
if response_queue:
response = self.prepare_exception(*sys.exc_info())
success = False
# If the call was synchronous,
# send the response/error back to the plugin.
if response_queue:
self.orchestrator.messageManager.send(
response_queue, (success, response))
#--------------------------------------------------------------------------
@staticmethod
def prepare_exception(exc_type, exc_value, exc_traceback):
"""
Prepare an exception for sending back to the plugins.
:param exc_type: Exception type.
:type exc_type: class
:param exc_value: Exception value.
:type exc_value:
:returns: Exception type, exception value
and formatted traceback. The exception value may be formatted too
and the exception type replaced by Exception if it's not possible
to serialize it for sending.
:rtype: tuple(class, object, str)
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
try:
pickle.dumps(exc_value, -1)
except Exception:
exc_value = traceback.format_exception_only(exc_type, exc_value)
try:
pickle.dumps(exc_type, -1)
except Exception:
exc_type = Exception
exc_traceback = traceback.extract_tb(exc_traceback)
return exc_type, exc_value, exc_traceback
| golismero/golismero | golismero/managers/rpcmanager.py | Python | gpl-2.0 | 10,792 |
/*
comedi/drivers/ni_labpc.c
Driver for National Instruments Lab-PC series boards and compatibles
Copyright (C) 2001, 2002, 2003 Frank Mori Hess <fmhess@users.sourceforge.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************
*/
/*
*/
/*
*/
#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 INTERVAL_SCAN_EN_BIT 0x1
/* */
#define EXT_SCAN_EN_BIT 0x2
/* */
#define EXT_CONVERT_OUT_BIT 0x4
/* */
#define ADC_DIFF_BIT 0x8
#define EXT_CONVERT_DISABLE_BIT 0x10
/* */
#define COMMAND5_REG 0x1c
/* */
#define EEPROM_WRITE_UNPROTECT_BIT 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 COUNTER_A_CONTROL_REG (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 labpc_calib_read_insn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int labpc_calib_write_insn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int labpc_eeprom_read_insn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int labpc_eeprom_write_insn(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 labpc_suggest_transfer_size(struct comedi_cmd cmd);
#endif
#ifdef CONFIG_COMEDI_PCI_DRIVERS
static int labpc_find_device(struct comedi_device *dev, int bus, int slot);
#endif
static int labpc_dio_mem_callback(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 labpc_eeprom_read_status(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,
MODE_SINGLE_CHAN_INTERVAL,
MODE_MULT_CHAN_UP,
MODE_MULT_CHAN_DOWN,
};
/* */
#define NUM_LABPC_PLUS_AI_RANGES 16
/* */
static const int labpc_plus_is_unipolar[NUM_LABPC_PLUS_AI_RANGES] = {
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
};
/* */
static const int labpc_plus_ai_gain_bits[NUM_LABPC_PLUS_AI_RANGES] = {
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 = {
NUM_LABPC_PLUS_AI_RANGES,
{
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 NUM_LABPC_1200_AI_RANGES 14
/* */
const int labpc_1200_is_unipolar[NUM_LABPC_1200_AI_RANGES] = {
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
};
EXPORT_SYMBOL_GPL(labpc_1200_is_unipolar);
/* */
const int labpc_1200_ai_gain_bits[NUM_LABPC_1200_AI_RANGES] = {
0x00,
0x20,
0x30,
0x40,
0x50,
0x60,
0x70,
0x00,
0x20,
0x30,
0x40,
0x50,
0x60,
0x70,
};
EXPORT_SYMBOL_GPL(labpc_1200_ai_gain_bits);
const struct comedi_lrange range_labpc_1200_ai = {
NUM_LABPC_1200_AI_RANGES,
{
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 AO_RANGE_IS_UNIPOLAR 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 = labpc_1200_ai_gain_bits,
.ai_range_is_unipolar = labpc_1200_is_unipolar,
.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 = labpc_1200_ai_gain_bits,
.ai_range_is_unipolar = labpc_1200_is_unipolar,
.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 = labpc_plus_ai_gain_bits,
.ai_range_is_unipolar = labpc_plus_is_unipolar,
.ai_scan_up = 0,
.memory_mapped_io = 0,
},
#ifdef CONFIG_COMEDI_PCI_DRIVERS
{
.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 = labpc_1200_ai_gain_bits,
.ai_range_is_unipolar = labpc_1200_is_unipolar,
.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 CONFIG_COMEDI_PCI_DRIVERS
static DEFINE_PCI_DEVICE_TABLE(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, labpc_dio_mem_callback,
(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 = labpc_calib_read_insn;
s->insn_write = labpc_calib_write_insn;
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 = labpc_eeprom_read_insn;
s->insn_write = labpc_eeprom_write_insn;
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 CONFIG_COMEDI_PCI_DRIVERS
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 CONFIG_COMEDI_PCI_DRIVERS
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 CONFIG_COMEDI_PCI_DRIVERS
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 CONFIG_COMEDI_PCI_DRIVERS
if (devpriv->mite)
mite_unsetup(devpriv->mite);
#endif
return 0;
};
EXPORT_SYMBOL_GPL(labpc_common_detach);
static void labpc_clear_adc_fifo(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);
spin_unlock_irqrestore(&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 MODE_SINGLE_CHAN_INTERVAL;
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 labpc_ai_chanlist_invalid(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 == MODE_SINGLE_CHAN_INTERVAL) {
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 MODE_SINGLE_CHAN_INTERVAL:
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 labpc_use_continuous_mode(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 labpc_ai_convert_period(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 labpc_set_ai_convert_period(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 labpc_ai_scan_period(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 labpc_set_ai_scan_period(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 (labpc_ai_chanlist_invalid(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);
spin_unlock_irqrestore(&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 + COUNTER_A_CONTROL_REG);
#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 = fifo_half_full_transfer;
} else
xfer = fifo_not_empty_transfer;
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->ai_range_is_unipolar[range])
devpriv->command6_bits |= ADC_UNIP_BIT;
else
devpriv->command6_bits &= ~ADC_UNIP_BIT;
/* */
if (xfer == fifo_half_full_transfer)
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 |= EXT_CONVERT_DISABLE_BIT;
/*
*/
if (labpc_use_continuous_mode(cmd) == 0) {
devpriv->command4_bits |= INTERVAL_SCAN_EN_BIT;
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 (labpc_ai_convert_period(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 + COUNTER_A_CONTROL_REG);
/* */
if (labpc_ai_scan_period(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;
}
}
labpc_clear_adc_fifo(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 = labpc_suggest_transfer_size(*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 == fifo_not_empty_transfer)
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);
spin_unlock_irqrestore(&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);
spin_unlock_irqrestore(&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->ai_range_is_unipolar[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 |= EXT_CONVERT_DISABLE_BIT;
/* */
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 + COUNTER_A_CONTROL_REG);
labpc_clear_adc_fifo(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);
spin_unlock_irqrestore(&dev->spinlock, flags);
/* */
if (thisboard->register_layout == labpc_1200_layout) {
range = CR_RANGE(insn->chanspec);
if (range & AO_RANGE_IS_UNIPOLAR)
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 labpc_calib_read_insn(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 labpc_calib_write_insn(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 labpc_eeprom_read_insn(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 labpc_eeprom_write_insn(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 labpc_suggest_transfer_size(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 (labpc_ai_convert_period(cmd) && labpc_ai_scan_period(cmd)) {
/*
*/
devpriv->divisor_b0 = (labpc_ai_scan_period(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 =
(labpc_ai_convert_period(cmd) +
(base_period / 2)) / base_period;
devpriv->divisor_b1 =
(labpc_ai_scan_period(cmd) +
(base_period / 2)) / base_period;
break;
case TRIG_ROUND_UP:
devpriv->divisor_a0 =
(labpc_ai_convert_period(cmd) + (base_period -
1)) / base_period;
devpriv->divisor_b1 =
(labpc_ai_scan_period(cmd) + (base_period -
1)) / base_period;
break;
case TRIG_ROUND_DOWN:
devpriv->divisor_a0 =
labpc_ai_convert_period(cmd) / base_period;
devpriv->divisor_b1 =
labpc_ai_scan_period(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;
/* */
labpc_set_ai_convert_period(cmd,
base_period * devpriv->divisor_a0);
labpc_set_ai_scan_period(cmd,
base_period * devpriv->divisor_b1);
/*
*/
} else if (labpc_ai_scan_period(cmd)) {
unsigned int scan_period;
scan_period = labpc_ai_scan_period(cmd);
/*
*/
i8253_cascade_ns_to_timer_2div(LABPC_TIMER_BASE,
&(devpriv->divisor_b1),
&(devpriv->divisor_b0),
&scan_period,
cmd->flags & TRIG_ROUND_MASK);
labpc_set_ai_scan_period(cmd, scan_period);
} else if (labpc_ai_convert_period(cmd)) {
unsigned int convert_period;
convert_period = labpc_ai_convert_period(cmd);
/*
*/
i8253_cascade_ns_to_timer_2div(LABPC_TIMER_BASE,
&(devpriv->divisor_a0),
&(devpriv->divisor_b0),
&convert_period,
cmd->flags & TRIG_ROUND_MASK);
labpc_set_ai_convert_period(cmd, convert_period);
}
}
static int labpc_dio_mem_callback(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 | EEPROM_WRITE_UNPROTECT_BIT;
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 & ~EEPROM_WRITE_UNPROTECT_BIT;
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 write_enable_instruction = 0x6;
const int write_instruction = 0x2;
const int write_length = 8; /* */
const int write_in_progress_bit = 0x1;
const int timeout = 10000;
int i;
/* */
for (i = 0; i < timeout; i++) {
if ((labpc_eeprom_read_status(dev) & write_in_progress_bit) ==
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 | EEPROM_WRITE_UNPROTECT_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
/* */
labpc_serial_out(dev, write_enable_instruction, 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 & ~EEPROM_WRITE_UNPROTECT_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
return 0;
}
static unsigned int labpc_eeprom_read_status(struct comedi_device *dev)
{
unsigned int value;
const int read_status_instruction = 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 | EEPROM_WRITE_UNPROTECT_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
/* */
labpc_serial_out(dev, read_status_instruction, write_length);
/* */
value = labpc_serial_in(dev);
/* */
devpriv->command5_bits &= ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
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 & ~EEPROM_WRITE_UNPROTECT_BIT;
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 CONFIG_COMEDI_PCI_DRIVERS
static int __devinit driver_labpc_pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return comedi_pci_auto_config(dev, driver_labpc.driver_name);
}
static void __devexit driver_labpc_pci_remove(struct pci_dev *dev)
{
comedi_pci_auto_unconfig(dev);
}
static struct pci_driver driver_labpc_pci_driver = {
.id_table = labpc_pci_table,
.probe = &driver_labpc_pci_probe,
.remove = __devexit_p(&driver_labpc_pci_remove)
};
static int __init driver_labpc_init_module(void)
{
int retval;
retval = comedi_driver_register(&driver_labpc);
if (retval < 0)
return retval;
driver_labpc_pci_driver.name = (char *)driver_labpc.driver_name;
return pci_register_driver(&driver_labpc_pci_driver);
}
static void __exit driver_labpc_cleanup_module(void)
{
pci_unregister_driver(&driver_labpc_pci_driver);
comedi_driver_unregister(&driver_labpc);
}
module_init(driver_labpc_init_module);
module_exit(driver_labpc_cleanup_module);
#else
static int __init driver_labpc_init_module(void)
{
return comedi_driver_register(&driver_labpc);
}
static void __exit driver_labpc_cleanup_module(void)
{
comedi_driver_unregister(&driver_labpc);
}
module_init(driver_labpc_init_module);
module_exit(driver_labpc_cleanup_module);
#endif
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| holyangel/LGE_G3 | drivers/staging/comedi/drivers/ni_labpc.c | C | gpl-2.0 | 62,708 |
<?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://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<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://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" border="0" /></a></td>
<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="demos-mainwindow-colorswatch-cpp.html">demos/mainwindow/colorswatch.cpp</a></li>
<li><a href="demos-mainwindow-colorswatch-h.html">demos/mainwindow/colorswatch.h</a></li>
<li><a href="demos-mainwindow-mainwindow-cpp.html">demos/mainwindow/mainwindow.cpp</a></li>
<li><a href="demos-mainwindow-mainwindow-h.html">demos/mainwindow/mainwindow.h</a></li>
<li><a href="demos-mainwindow-toolbar-cpp.html">demos/mainwindow/toolbar.cpp</a></li>
<li><a href="demos-mainwindow-toolbar-h.html">demos/mainwindow/toolbar.h</a></li>
<li><a href="demos-mainwindow-main-cpp.html">demos/mainwindow/main.cpp</a></li>
<li><a href="demos-mainwindow-mainwindow-pro.html">demos/mainwindow/mainwindow.pro</a></li>
<li><a href="demos-mainwindow-mainwindow-qrc.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>
| librelab/qtmoko-test | doc/html/demos-mainwindow.html | HTML | gpl-2.0 | 2,720 |
using System;
namespace Server.Items
{
[Flipable( 0xC12, 0xC13 )]
public class BrokenArmoireComponent : AddonComponent
{
public override int LabelNumber { get { return 1076262; } } // Broken Armoire
public BrokenArmoireComponent() : base( 0xC12 )
{
}
public BrokenArmoireComponent( 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 BrokenArmoireComponent(), 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();
}
}
}
| jackuoll/Pre-AOS-RunUO | Scripts/Items/Special/Broken Furniture Collection/BrokenArmoire.cs | C# | gpl-2.0 | 1,896 |
/**********************************************************************
Audacity: A Digital Audio Editor
ExpandingToolBar.cpp
Dominic Mazzoni
*******************************************************************//**
\class ExpandingToolBar
\brief A smart ToolBar class that has a "MainPanel" which is always
displayed, and an "ExtraPanel" that can be hidden to save space.
Can be docked into a ToolBarArea or floated in an ToolBarFrame;
If auto-expanding is off, behavior is very simple: clicking the
toggle button expands, clicking it again collapses.
If auto-expanding is on, behavior is a little more complicated.
When the mouse movers over a toolbar and it is collapsed, it gets
auto-expanded, and it gets auto-collapsed as soon as the mouse
leaves. However, if they manually toggle it collapsed
while it was auto-expanded, it will stay collapsed until you move
the mouse completely away and then back again later. If you
manually expand it, it will stay manually expanded until you
manually collapse it.
*//****************************************************************//**
\class ExpandingToolBarEvtHandler
\brief A custom event handler for ExpandingToolBar.
*//****************************************************************//**
\class ToolBarGrabber
\brief Draws the grabber for an ExpandingToolBar.
*//****************************************************************//**
\class ToolBarDialog
\brief A dialog based container for ExpandingToolBars providing modal
based operations.
*//****************************************************************//**
\class ToolBarFrame
\brief A miniframe based container for ExpandingToolBars providing
modeless presentation.
*//****************************************************************//**
\class ToolBarArea
\brief An alterantive to ToolBarFrame which can contain an
ExpandingToolBar. ToolBarArea is used for a 'docked' ToolBar,
ToolBarFrame for a floating one.
*//****************************************************************//**
\class ToolBarArrangement
\brief Small class that holds some layout information for an
ExpandingToolBar.
*//*******************************************************************/
#include "../Theme.h"
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/window.h>
#endif
#include <wx/wx.h>
#include <wx/dcmemory.h>
#include <wx/log.h>
#include <wx/dragimag.h>
#include <wx/arrimpl.cpp>
#include <wx/dialog.h>
#include "ExpandingToolBar.h"
#include "AButton.h"
#include "../AllThemeResources.h"
#include "../Experimental.h"
const int kToggleButtonHeight = 8;
const int kTimerInterval = 50; // every 50 ms -> ~20 updates per second
const wxRect kDummyRect = wxRect(-9999, -9999, 0, 0);
enum {
kToggleButtonID = 5000,
kTimerID
};
WX_DEFINE_OBJARRAY(wxArrayRect);
class ToolBarArrangement
{
public:
ExpandingToolBarArray childArray;
wxArrayRect rectArray;
wxArrayInt rowArray;
};
//
// ExpandingToolBar
//
BEGIN_EVENT_TABLE(ExpandingToolBar, wxPanel)
EVT_SIZE(ExpandingToolBar::OnSize)
EVT_TIMER(kTimerID, ExpandingToolBar::OnTimer)
EVT_BUTTON(kToggleButtonID, ExpandingToolBar::OnToggle)
END_EVENT_TABLE()
IMPLEMENT_CLASS(ExpandingToolBar, wxPanel)
//static
int ExpandingToolBar::msNoAutoExpandStack = 0;
ExpandingToolBar::ExpandingToolBar(wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size):
wxPanel(parent, id, pos, size),
mIsAutoExpanded(false),
mIsManualExpanded(false),
mIsExpanded(false),
mAutoExpand(true),
mFirstTime(true),
mFrameParent(NULL),
mDialogParent(NULL),
mAreaParent(NULL),
mSavedArrangement(NULL),
mDragImage(NULL),
mTopLevelParent(NULL)
{
mMainPanel = new wxPanel(this, -1,
wxDefaultPosition, wxSize(1, 1));
mExtraPanel = new wxPanel(this, -1,
wxDefaultPosition, wxSize(1, 1));
mGrabber = NULL;
ToolBarArea *toolBarParent =
dynamic_cast<ToolBarArea *>(GetParent());
if (toolBarParent)
mGrabber = new ToolBarGrabber(this, -1, this);
/// \todo check whether this is a memory leak (and check similar code)
wxImage hbar = theTheme.Image(bmpToolBarToggle);
wxColour magicColor = wxColour(0, 255, 255);
ImageArray fourStates = ImageRoll::SplitV(hbar, magicColor);
mToggleButton = new AButton(this, kToggleButtonID,
wxDefaultPosition, wxDefaultSize,
ImageRoll(ImageRoll::HorizontalRoll,
fourStates[0], magicColor),
ImageRoll(ImageRoll::HorizontalRoll,
fourStates[1], magicColor),
ImageRoll(ImageRoll::HorizontalRoll,
fourStates[2], magicColor),
ImageRoll(ImageRoll::HorizontalRoll,
fourStates[3], magicColor),
true);
mToggleButton->UseDisabledAsDownHiliteImage(true);
SetAutoLayout(true);
mTimer.SetOwner(this, kTimerID);
}
ExpandingToolBar::~ExpandingToolBar()
{
}
void ExpandingToolBar::OnSize(wxSizeEvent & WXUNUSED(event))
{
if (mFrameParent || mDialogParent || mAreaParent)
return;
// At the time of construction, it wasn't "safe" to tell
// our parent that we've just joined the window, so we check
// for it during our first OnSize event.
if (!mFrameParent) {
ToolBarFrame *toolBarParent =
dynamic_cast<ToolBarFrame *>(GetParent());
if (toolBarParent) {
// We were placed into a floating window
mFrameParent = toolBarParent;
toolBarParent->SetChild(this);
}
}
if (!mDialogParent) {
ToolBarDialog *toolBarParent =
dynamic_cast<ToolBarDialog *>(GetParent());
if (toolBarParent) {
// We were placed into a dialog
mDialogParent = toolBarParent;
toolBarParent->SetChild(this);
}
}
if (!mAreaParent) {
ToolBarArea *toolBarParent =
dynamic_cast<ToolBarArea *>(GetParent());
if (toolBarParent) {
// We were placed into an area full of other toolbars
mAreaParent = toolBarParent;
toolBarParent->AddChild(this);
}
}
}
void ExpandingToolBar::OnToggle(wxCommandEvent & WXUNUSED(event))
{
if (mIsExpanded)
Collapse();
else
Expand();
}
void ExpandingToolBar::Expand()
{
// We set both mIsManualExpanded and mIsAutoExpanded to true;
// that way if the user manually collapses the toolbar we set
// mIsManualExpanded to false but keep mIsAutoExpanded to true
// to prevent it from being auto-expanded again until the user
// actually moves the mouse completely away and back again later.
mToggleButton->PushDown();
mIsManualExpanded = true;
mIsAutoExpanded = true;
Fit();
}
void ExpandingToolBar::Collapse(bool now /* = false */)
{
// After being manually collapsed, we set mIsAutoExpanded back to
// true, which prevents it from being immediately auto-expanded
// again until after the mouse actually moves away and then
// back again later.
mToggleButton->PopUp();
mIsManualExpanded = false;
mIsAutoExpanded = false;
Fit();
mIsAutoExpanded = true;
if (now) {
mCurrentDrawerSize = mTargetDrawerSize;
MoveDrawer(wxSize(0, 0));
}
}
void ExpandingToolBar::TryAutoExpand()
{
if (mAutoExpand && msNoAutoExpandStack==0 &&
mIsManualExpanded == false && mIsAutoExpanded == false) {
mToggleButton->PushDown();
mIsAutoExpanded = true;
Fit();
}
}
void ExpandingToolBar::TryAutoCollapse()
{
#ifdef EXPERIMENTAL_ROLL_UP_DIALOG
if (mIsAutoExpanded == true && mIsManualExpanded == false) {
mToggleButton->PopUp();
mIsAutoExpanded = false;
Fit();
}
#endif
}
class ExpandingToolBarEvtHandler : public wxEvtHandler
{
public:
ExpandingToolBarEvtHandler(ExpandingToolBar *toolbar,
wxEvtHandler *inheritedEvtHandler)
{
mToolBar = toolbar;
mInheritedEvtHandler = inheritedEvtHandler;
}
virtual bool ProcessEvent(wxEvent& evt)
{
if (mToolBar->IsCursorInWindow())
mToolBar->TryAutoExpand();
else
mToolBar->TryAutoExpand();
return mInheritedEvtHandler->ProcessEvent(evt);
}
protected:
ExpandingToolBar *mToolBar;
wxEvtHandler *mInheritedEvtHandler;
DECLARE_NO_COPY_CLASS(ExpandingToolBarEvtHandler);
};
void ExpandingToolBar::RecursivelyPushEventHandlers(wxWindow *win)
{
if (!mWindowHash[win]) {
ExpandingToolBarEvtHandler *evtHandler =
new ExpandingToolBarEvtHandler(this, win->GetEventHandler());
win->PushEventHandler(evtHandler);
mWindowHash[win] = 1;
}
wxWindowList children = win->GetChildren();
typedef wxWindowList::compatibility_iterator Node;
for(Node node = children.GetFirst(); node; node = node->GetNext()) {
wxWindow *child = node->GetData();
RecursivelyPushEventHandlers(child);
}
}
bool ExpandingToolBar::Layout()
{
mMainSize = mMainPanel->GetBestSize();
mExtraSize = mExtraPanel->GetBestSize();
mButtonSize = wxSize(wxMax(mMainSize.x, mExtraSize.x),
kToggleButtonHeight);
int left = 0;
if (mGrabber) {
mGrabberSize = mGrabber->GetMinSize();
left += mGrabberSize.x;
}
else
mGrabberSize = wxSize(0, 0);
mMainPanel->SetSize(left, 0, mMainSize.x, mMainSize.y);
mToggleButton->SetSize(left, mMainSize.y, mButtonSize.x, mButtonSize.y);
mExtraPanel->SetSize(left, mMainSize.y + mButtonSize.y,
mExtraSize.x, mExtraSize.y);
if (mGrabber)
mGrabber->SetSize(0, 0, left, mMainSize.y + mButtonSize.y);
// Add event handlers to all children
//RecursivelyPushEventHandlers(this);
return true;
}
void ExpandingToolBar::Fit()
{
#ifdef EXPERIMENTAL_ROLL_UP_DIALOG
mIsExpanded = (mIsAutoExpanded || mIsManualExpanded);
#else
mIsExpanded = true;// JKC - Wedge it open at all times.
#endif
int width = mButtonSize.x + mGrabberSize.x;
wxSize baseWindowSize = wxSize(width,
mMainSize.y + mButtonSize.y);
mTargetDrawerSize = wxSize(mButtonSize.x, 0);
if (mIsExpanded)
mTargetDrawerSize.y += mExtraSize.y;
mCurrentDrawerSize.x = mTargetDrawerSize.x;
// The first time, we always update the size. Otherwise, we set
// a target size, and the actual size changes during a timer
// event.
if (mFirstTime) {
mFirstTime = false;
mCurrentDrawerSize = wxSize(mExtraSize.x, 0);
mCurrentTotalSize = baseWindowSize;
SetSizeHints(mCurrentTotalSize, mCurrentTotalSize);
SetSize(mCurrentTotalSize);
}
// wxTimers seem to be a little unreliable - sometimes they stop for
// no good reason, so this "primes" it every now and then...
mTimer.Stop();
mTimer.Start(kTimerInterval);
}
bool ExpandingToolBar::IsCursorInWindow()
{
wxPoint globalMouse = ::wxGetMousePosition();
wxPoint localMouse = ScreenToClient(globalMouse);
bool result = (localMouse.x >= 0 && localMouse.y >= 0 &&
localMouse.x < mCurrentTotalSize.x &&
localMouse.y < mCurrentTotalSize.y);
// The grabber doesn't count!
if (mGrabber && mGrabber->GetRect().Contains(localMouse))
result = false;
return result;
}
void ExpandingToolBar::ReparentExtraPanel()
{
// This is how we make sure the extra panel, which slides out
// like a drawer, appears on top of everything else in the window...
wxPoint pos;
pos.x = mGrabberSize.x;
pos.y = mMainSize.y + mButtonSize.y;
wxWindow *frame = this;
while(!frame->IsTopLevel()) {
pos += frame->GetPosition();
frame = frame->GetParent();
}
mExtraPanel->Reparent(frame);
mExtraPanel->SetPosition(pos);
}
void ExpandingToolBar::MoveDrawer(wxSize prevSize)
{
mCurrentTotalSize = wxSize(mButtonSize.x,
mMainSize.y +
mButtonSize.y +
mCurrentDrawerSize.y);
if (mFrameParent) {
// If we're in a tool window
SetSizeHints(mCurrentTotalSize, mCurrentTotalSize);
SetSize(mCurrentTotalSize);
GetParent()->Fit();
}
if (mDialogParent) {
// If we're in a dialog
SetSizeHints(mCurrentTotalSize, mCurrentTotalSize);
SetSize(mCurrentTotalSize);
GetParent()->Fit();
}
if (mAreaParent) {
// If we're in a tool area
if (mCurrentDrawerSize.y > 0 && prevSize.y == 0) {
ReparentExtraPanel();
mExtraPanel->Show();
}
mExtraPanel->SetSizeHints(mCurrentDrawerSize, mCurrentDrawerSize);
mExtraPanel->SetSize(mCurrentDrawerSize);
if (mCurrentDrawerSize.y == 0)
mExtraPanel->Hide();
}
}
void ExpandingToolBar::OnTimer(wxTimerEvent & WXUNUSED(event))
{
if (mAutoExpand && msNoAutoExpandStack==0 &&
IsCursorInWindow())
TryAutoExpand();
else if (!IsCursorInWindow())
TryAutoCollapse();
if (mCurrentDrawerSize == mTargetDrawerSize)
return;
// This accelerates the current size towards the target size;
// it's a neat way for the window to roll open, but in such a
// way that it
wxSize prevSize = mCurrentDrawerSize;
mCurrentDrawerSize = (mCurrentDrawerSize*2 + mTargetDrawerSize) / 3;
if (abs((mCurrentDrawerSize-mTargetDrawerSize).x)<2 &&
abs((mCurrentDrawerSize-mTargetDrawerSize).y)<2)
mCurrentDrawerSize = mTargetDrawerSize;
MoveDrawer(prevSize);
}
wxBitmap ExpandingToolBar::GetToolbarBitmap()
{
wxSize size = GetClientSize();
wxBitmap bitmap(size.x, size.y);
wxClientDC winDC(this);
wxMemoryDC memDC;
memDC.SelectObject(bitmap);
memDC.Blit(0, 0, size.x, size.y,
&winDC, 0, 0);
return bitmap;
}
void ExpandingToolBar::StartMoving()
{
if (!mAreaParent)
return;
int j;
mAreaParent->CollapseAll(true);
mTimer.Stop();
// This gives time for wx to finish redrawing the window that way.
// HACK: why do we need to do it so many times???
for(j=0; j<500; j++)
::wxSafeYield();
wxBitmap toolbarBitmap = GetToolbarBitmap();
msNoAutoExpandStack++;
mSavedArrangement = mAreaParent->SaveArrangement();
mAreaParent->RemoveChild(this);
mAreaParent->Refresh(true);
mTopLevelParent = this;
while(!mTopLevelParent->IsTopLevel())
mTopLevelParent = mTopLevelParent->GetParent();
wxPoint hotSpot = ScreenToClient(wxGetMousePosition());
hotSpot -= (ClientToScreen(wxPoint(0, 0)) -
mAreaParent->ClientToScreen(wxPoint(0, 0)));
mDropTargets = mAreaParent->GetDropTargets();
mDropTarget = kDummyRect;
wxColour magicColor = wxColour(0, 255, 255);
wxImage tgtImage = theTheme.Image(bmpToolBarTarget);
ImageRoll tgtImageRoll = ImageRoll(ImageRoll::VerticalRoll,
tgtImage,
magicColor);
mTargetPanel = new ImageRollPanel(mAreaParent, -1, tgtImageRoll,
wxDefaultPosition,
wxDefaultSize,
wxTRANSPARENT_WINDOW);
mTargetPanel->SetLogicalFunction(wxXOR);
mTargetPanel->SetSize(mDropTarget);
// This gives time for wx to finish redrawing the window that way.
// HACK: why do we need to do it several times???
for(j=0; j<500; j++)
::wxSafeYield();
mAreaParent->SetCapturedChild(this);
mDragImage = new wxDragImage(toolbarBitmap);
mDragImage->BeginDrag(hotSpot, mAreaParent, mTopLevelParent);
mDragImage->Show();
mDragImage->Move(ScreenToClient(wxGetMousePosition()));
}
void ExpandingToolBar::UpdateMoving()
{
if (!mAreaParent || !mSavedArrangement || !mDragImage)
return;
wxPoint cursorPos = mAreaParent->ScreenToClient(wxGetMousePosition());
wxRect prevTarget = mDropTarget;
int best_dist_sq = 99999;
int i;
for(i=0; i<(int)mDropTargets.GetCount(); i++) {
int x = (mDropTargets[i].x + (mDropTargets[i].width/2))-cursorPos.x;
int y = (mDropTargets[i].y + (mDropTargets[i].height/2))-cursorPos.y;
int dist_sq = (x*x) + (y*y);
if (dist_sq < best_dist_sq) {
best_dist_sq = dist_sq;
mDropTarget = mDropTargets[i];
}
}
if (!mAreaParent->GetRect().Contains(cursorPos))
mDropTarget = kDummyRect;
if (mDropTarget != prevTarget) {
mDragImage->Hide();
wxRect r = mDropTarget;
r.Inflate(4, 4);
mTargetPanel->SetSize(r);
#if 0
wxClientDC dc(mAreaParent);
dc.DestroyClippingRegion();
dc.SetLogicalFunction(wxINVERT);
wxRect r = prevTarget;
r.Inflate(4, 4);
dc.DrawRectangle(r);
r = mDropTarget;
r.Inflate(4, 4);
dc.DrawRectangle(r);
#endif
// This gives time for wx to finish redrawing the window that way.
// HACK: why do we need to do it so many times???
for(i=0; i<500; i++)
::wxSafeYield();
mDragImage->Show();
mDragImage->Move(ScreenToClient(wxGetMousePosition()));
}
else
mDragImage->Move(ScreenToClient(wxGetMousePosition()));
}
void ExpandingToolBar::FinishMoving()
{
if (!mAreaParent || !mSavedArrangement)
return;
delete mTargetPanel;
mAreaParent->SetCapturedChild(NULL);
mDragImage->Hide();
mDragImage->EndDrag();
msNoAutoExpandStack--;
if (mDropTarget == kDummyRect) {
mAreaParent->RestoreArrangement(mSavedArrangement);
mSavedArrangement = NULL;
}
else {
delete mSavedArrangement;
mSavedArrangement = NULL;
mAreaParent->MoveChild(this, mDropTarget);
}
// Keep all drawers closed until the user moves specifically to a
// different window
mAreaParent->CollapseAll();
mTopLevelParent->Refresh(true);
mTimer.Start(kTimerInterval);
}
//
// ToolBarGrabber
//
BEGIN_EVENT_TABLE(ToolBarGrabber, wxPanel)
EVT_PAINT(ToolBarGrabber::OnPaint)
EVT_SIZE(ToolBarGrabber::OnSize)
EVT_MOUSE_EVENTS(ToolBarGrabber::OnMouse)
END_EVENT_TABLE()
IMPLEMENT_CLASS(ToolBarGrabber, wxPanel)
ToolBarGrabber::ToolBarGrabber(wxWindow *parent,
wxWindowID id,
ExpandingToolBar *ownerToolbar,
const wxPoint& pos,
const wxSize& size):
wxPanel(parent, id, pos, size),
mOwnerToolBar(ownerToolbar)
{
wxImage grabberImages = theTheme.Image(bmpToolBarGrabber);
wxColour magicColor = wxColour(0, 255, 255);
ImageArray images = ImageRoll::SplitH(grabberImages, magicColor);
mImageRoll[0] = ImageRoll(ImageRoll::VerticalRoll,
images[0],
magicColor);
mImageRoll[1] = ImageRoll(ImageRoll::VerticalRoll,
images[1],
magicColor);
SetSizeHints(mImageRoll[0].GetMinSize(),
mImageRoll[1].GetMaxSize());
mState = 0;
}
void ToolBarGrabber::OnMouse(wxMouseEvent &event)
{
int prevState = mState;
// Handle hilighting the image if the mouse is over it
if (event.Entering())
mState = 1;
else if (event.Leaving())
mState = 0;
else {
wxSize clientSize = GetClientSize();
if (event.m_x >= 0 && event.m_y >= 0 &&
event.m_x < clientSize.x && event.m_y < clientSize.y)
mState = 1;
else
mState = 0;
}
if (event.ButtonDown())
mOwnerToolBar->StartMoving();
if (mState != prevState)
Refresh(false);
}
void ToolBarGrabber::OnPaint(wxPaintEvent & WXUNUSED(event))
{
wxPaintDC dc(this);
mImageRoll[mState].Draw(dc, GetClientRect());
}
void ToolBarGrabber::OnSize(wxSizeEvent & WXUNUSED(event))
{
Refresh(false);
}
//
// ToolBarDialog
//
BEGIN_EVENT_TABLE(ToolBarDialog, wxDialog)
END_EVENT_TABLE()
IMPLEMENT_CLASS(ToolBarDialog, wxDialog)
ToolBarDialog::ToolBarDialog(wxWindow* parent,
wxWindowID id,
const wxString& name,
const wxPoint& pos):
wxDialog(parent, id, name, pos, wxSize(1, 1),
// Workaround for bug in __WXMSW__. No close box on a wxDialog unless wxSYSTEM_MENU is used.
#ifdef __WXMSW__
wxSYSTEM_MENU |
#endif
wxCAPTION|wxCLOSE_BOX),
mChild(NULL)
{
}
ToolBarDialog::~ToolBarDialog()
{
}
void ToolBarDialog::SetChild(ExpandingToolBar *child)
{
mChild = child;
if (mChild && mChild->GetParent() != this)
mChild->Reparent(this);
Fit();
}
void ToolBarDialog::Fit()
{
if (mChild) {
wxSize childSize = mChild->GetBestSize();
// Take into account the difference between the content
// size and the frame size
wxSize curContentSize = GetClientSize();
wxSize curFrameSize = GetSize();
wxSize newFrameSize = childSize + (curFrameSize - curContentSize);
SetSizeHints(newFrameSize, newFrameSize);
SetSize(newFrameSize);
}
}
//
// ToolBarFrame
//
BEGIN_EVENT_TABLE(ToolBarFrame, wxMiniFrame)
END_EVENT_TABLE()
IMPLEMENT_CLASS(ToolBarFrame, wxMiniFrame)
ToolBarFrame::ToolBarFrame(wxWindow* parent,
wxWindowID id,
const wxString& name,
const wxPoint& pos):
wxMiniFrame(parent, id, name, pos, wxSize(1, 1),
// Workaround for bug in __WXMSW__. No close box on a miniframe unless wxSYSTEM_MENU is used.
#ifdef __WXMSW__
wxSYSTEM_MENU |
#endif
wxCAPTION|wxCLOSE_BOX),
mChild(NULL)
{
}
ToolBarFrame::~ToolBarFrame()
{
}
void ToolBarFrame::SetChild(ExpandingToolBar *child)
{
mChild = child;
if (mChild && mChild->GetParent() != this)
mChild->Reparent(this);
Fit();
}
void ToolBarFrame::Fit()
{
if (mChild) {
wxSize childSize = mChild->GetBestSize();
// Take into account the difference between the content
// size and the frame size
wxSize curContentSize = GetClientSize();
wxSize curFrameSize = GetSize();
wxSize newFrameSize = childSize + (curFrameSize - curContentSize);
SetSizeHints(newFrameSize, newFrameSize);
SetSize(newFrameSize);
}
}
//
// ToolBarArea
//
BEGIN_EVENT_TABLE(ToolBarArea, wxPanel)
EVT_SIZE(ToolBarArea::OnSize)
EVT_MOUSE_EVENTS(ToolBarArea::OnMouse)
END_EVENT_TABLE()
IMPLEMENT_CLASS(ToolBarArea, wxPanel)
ToolBarArea::ToolBarArea(wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size):
wxPanel(parent, id, pos, size),
mInOnSize(false),
mCapturedChild(NULL)
{
}
ToolBarArea::~ToolBarArea()
{
}
void ToolBarArea::ContractRow(int rowIndex)
{
// Contract all of the toolbars in a given row to their
// minimum size. This is an intermediate step in layout.
int i;
int x = 0;
for(i=0; i<(int)mChildArray.GetCount(); i++)
if (mRowArray[i] == rowIndex) {
wxPoint childPos = mChildArray[i]->GetPosition();
wxSize childMin = mChildArray[i]->GetMinSize();
mChildArray[i]->SetSize(x, childPos.y,
childMin.x, childMin.y);
x += childMin.x;
}
}
bool ToolBarArea::ExpandRow(int rowIndex)
{
// Expand all of the toolbars in a given row so that the
// whole width is filled, if possible. This is the last
// step after laying out as many toolbars as possible in
// that row. Returns false if it's not possible to fit
// all of these toolbars in one row anymore.
wxSize area = GetClientSize();
int i, j, x;
int minWidth = 0;
int leftoverSpace = 0;
int expandableCount = 0;
int toolbarCount = 0;
for(i=0; i<(int)mChildArray.GetCount(); i++)
if (mRowArray[i] == rowIndex) {
ExpandingToolBar *child = mChildArray[i];
wxSize childMin = child->GetMinSize();
wxSize childMax = child->GetMaxSize();
minWidth += childMin.x;
toolbarCount++;
if (childMax.x > childMin.x)
expandableCount++;
}
leftoverSpace = area.x - minWidth;
if (leftoverSpace <= 0) {
if (toolbarCount > 1)
return false; // not possible to fit all in one row
else
return true; // there's only one, so it doesn't matter
}
j = 0;
x = 0;
for(i=0; i<(int)mChildArray.GetCount(); i++)
if (mRowArray[i] == rowIndex) {
ExpandingToolBar *child = mChildArray[i];
wxPoint childPos = child->GetPosition();
wxSize childMin = child->GetMinSize();
wxSize childMax = child->GetMaxSize();
int width = childMin.x;
if (childMax.x > childMin.x)
width +=
(leftoverSpace * (j+1) / expandableCount) -
(leftoverSpace * (j) / expandableCount);
mChildArray[i]->SetSize(x, childPos.y,
width, childMin.y);
x += width;
j++;
}
return true; // success
}
void ToolBarArea::LayoutOne(int childIndex)
{
wxSize area = GetClientSize();
ExpandingToolBar *child = mChildArray[childIndex];
wxSize childMin = child->GetMinSize();
if (childIndex == 0) {
mRowArray[childIndex] = 0;
mChildArray[childIndex]->SetSize(0, 0, childMin.x, childMin.y);
ExpandRow(0);
#if 0
wxPoint p = mChildArray[childIndex]->GetPosition();
wxSize s = mChildArray[childIndex]->GetSize();
printf("ToolBar %d moved to row %d at (%d, %d), size (%d x %d)\n",
childIndex, mRowArray[childIndex],
p.x, p.y, s.x, s.y);
#endif
mLastLayoutSize = area;
return;
}
int prevRow = mRowArray[childIndex-1];
ContractRow(prevRow);
wxPoint prevPos = mChildArray[childIndex-1]->GetPosition();
wxSize prevSize = mChildArray[childIndex-1]->GetSize();
int prevX = prevPos.x + prevSize.x;
int availableWidth = area.x - prevX;
if (childMin.x <= availableWidth) {
// It fits into the same row
mRowArray[childIndex] = prevRow;
mChildArray[childIndex]->SetSize(prevX, prevPos.y,
childMin.x, childMin.y);
ExpandRow(prevRow);
}
else {
// Go to the next row
ExpandRow(prevRow);
mRowArray[childIndex] = prevRow + 1;
int i;
int maxRowHeight = 0;
for(i=0; i<childIndex; i++)
if (mRowArray[i] == prevRow &&
mChildArray[i]->GetSize().y > maxRowHeight)
maxRowHeight = mChildArray[i]->GetSize().y;
mChildArray[childIndex]->SetSize(0, prevPos.y + maxRowHeight,
childMin.x, childMin.y);
ExpandRow(prevRow+1);
}
// Save the size of the window the last time we moved one of the
// toolbars around. If the user does a minor resize, we try to
// preserve the layout. If the user does a major resize, we're
// allowed to redo the layout.
mLastLayoutSize = area;
#if 0
wxPoint p = mChildArray[childIndex]->GetPosition();
wxSize s = mChildArray[childIndex]->GetSize();
printf("ToolBar %d moved to row %d at (%d, %d), size (%d x %d)\n",
childIndex, mRowArray[childIndex],
p.x, p.y, s.x, s.y);
#endif
}
bool ToolBarArea::Layout()
{
// Redo the layout from scratch, preserving only the order of
// the children
int i;
for(i=0; i<(int)mChildArray.GetCount(); i++)
mRowArray[i] = -1;
for(i=0; i<(int)mChildArray.GetCount(); i++)
LayoutOne(i);
Refresh(true);
return true;
}
void ToolBarArea::AdjustLayout()
{
// Try to modify the layout as little as possible - but if that's
// impossible, redo the layout as necessary.
int row = -1;
int i, j;
for(i=0; i<(int)mChildArray.GetCount(); i++) {
if (mRowArray[i] > row) {
row = mRowArray[i];
bool success = ExpandRow(row);
if (!success) {
// Re-layout all toolbars from this row on
for(j=i; j<(int)mChildArray.GetCount(); j++)
LayoutOne(j);
return;
}
}
}
}
void ToolBarArea::Fit()
{
Fit(true, true);
}
void ToolBarArea::Fit(bool horizontal, bool vertical)
{
wxSize clientSize = GetClientSize();
wxSize minSize;
wxSize maxSize;
wxSize actualSize;
int i;
minSize.x = 0;
minSize.y = 0;
maxSize.x = 9999;
maxSize.y = 0;
for(i=0; i<(int)mChildArray.GetCount(); i++) {
wxPoint childPos = mChildArray[i]->GetPosition();
wxSize childSize = mChildArray[i]->GetSize();
if (childPos.x + childSize.x > actualSize.x) {
actualSize.x = childPos.x + childSize.x;
}
if (childSize.x > minSize.x) {
minSize.x = childSize.x;
}
if (childPos.y + childSize.y > maxSize.y) {
maxSize.y = childPos.y + childSize.y;
minSize.y = maxSize.y;
actualSize.y = maxSize.y;
}
}
if (!horizontal && actualSize.x < clientSize.x)
actualSize.x = clientSize.x;
if (!vertical && actualSize.y < clientSize.y)
actualSize.y = clientSize.y;
if (minSize != mMinSize ||
maxSize != mMaxSize) {
mMinSize = minSize;
mMaxSize = maxSize;
SetSizeHints(mMinSize, mMaxSize);
}
if (actualSize != mActualSize) {
mActualSize = actualSize;
SetSize(mActualSize);
}
}
void ToolBarArea::OnSize(wxSizeEvent & WXUNUSED(event))
{
if (mInOnSize)
return;
mInOnSize = true;
wxSize currentSize = GetClientSize();
if (abs(currentSize.x - mLastLayoutSize.x >= 100)) {
// If they resize by more than 100 pixels (horizontally),
// we totally redo the layout, preserving the order of the
// toolbars but not the exact position.
Layout();
}
else {
// If it was a minor resize, we try to preserve the positions of
// the toolbars. If this is impossible, we still redo the layout,
// of course.
AdjustLayout();
}
Fit(false, true);
mInOnSize = false;
}
void ToolBarArea::OnMouse(wxMouseEvent &evt)
{
if (mCapturedChild) {
if (evt.ButtonUp())
mCapturedChild->FinishMoving();
else if (evt.Moving() || evt.Dragging())
mCapturedChild->UpdateMoving();
}
else {
evt.Skip();
}
}
void ToolBarArea::CollapseAll(bool now)
{
int i;
for(i=0; i<(int)mChildArray.GetCount(); i++)
mChildArray[i]->Collapse(now);
}
void ToolBarArea::AddChild(ExpandingToolBar *child)
{
mChildArray.Add(child);
mRowArray.Add(-1); // unknown row
LayoutOne(mChildArray.GetCount()-1);
Fit(false, true);
}
void ToolBarArea::RemoveChild(ExpandingToolBar *child)
{
int i, j;
for(i=0; i<(int)mChildArray.GetCount(); i++) {
if (mChildArray[i] == child) {
child->Hide();
mChildArray.RemoveAt(i);
mRowArray.RemoveAt(i);
for(j=i; j<(int)mChildArray.GetCount(); j++)
mRowArray[j] = -1;
for(j=i; j<(int)mChildArray.GetCount(); j++)
LayoutOne(j);
Fit(false, true);
}
}
}
ToolBarArrangement *ToolBarArea::SaveArrangement()
{
ToolBarArrangement *arrangement = new ToolBarArrangement();
int i;
arrangement->childArray = mChildArray;
arrangement->rowArray = mRowArray;
for(i=0; i<(int)mChildArray.GetCount(); i++)
arrangement->rectArray.Add(mChildArray[i]->GetRect());
return arrangement;
}
void ToolBarArea::RestoreArrangement(ToolBarArrangement *arrangement)
{
int i;
mChildArray = arrangement->childArray;
mRowArray = arrangement->rowArray;
for(i=0; i<(int)mChildArray.GetCount(); i++) {
mChildArray[i]->SetSize(arrangement->rectArray[i]);
mChildArray[i]->Show();
}
Fit(false, true);
delete arrangement;
}
wxArrayRect ToolBarArea::GetDropTargets()
{
mDropTargets.Clear();
mDropTargetIndices.Clear();
mDropTargetRows.Clear();
int numChildren = (int)mChildArray.GetCount();
int i;
int row = -1;
if (numChildren == 0)
return mDropTargets;
for(i=0; i<numChildren; i++) {
int childRow = mRowArray[i];
wxRect childRect = mChildArray[i]->GetRect();
if (childRow != row) {
// Add a target before this child (at beginning of row only)
row = childRow;
mDropTargetIndices.Add(i);
mDropTargetRows.Add(row);
mDropTargets.Add(wxRect(childRect.x, childRect.y,
0, childRect.height));
}
// Add a target after this child (always)
mDropTargetIndices.Add(i+1);
mDropTargetRows.Add(row);
mDropTargets.Add(wxRect(childRect.x+childRect.width, childRect.y,
0, childRect.height));
}
return mDropTargets;
}
void ToolBarArea::MoveChild(ExpandingToolBar *toolBar, wxRect dropTarget)
{
int i, j;
for(i=0; i<(int)mDropTargets.GetCount(); i++) {
if (dropTarget == mDropTargets[i]) {
int newIndex = mDropTargetIndices[i];
int newRow = mDropTargetRows[i];
mChildArray.Insert(toolBar, newIndex);
mRowArray.Insert(newRow, newIndex);
for(j=newIndex+1; j<(int)mChildArray.GetCount(); j++)
mRowArray[j] = -1;
ContractRow(newRow);
mChildArray[newIndex]->Show();
for(j=newIndex; j<(int)mChildArray.GetCount(); j++)
LayoutOne(j);
Fit(false, true);
return;
}
}
}
void ToolBarArea::SetCapturedChild(ExpandingToolBar *child)
{
mCapturedChild = child;
}
| oneminot/audacity | src/widgets/ExpandingToolBar.cpp | C++ | gpl-2.0 | 33,841 |
<?php
/**
* TestLink Open Source Project - http://testlink.sourceforge.net/
* This script is distributed under the GNU General Public License 2 or later.
*
* Filename $RCSfile: reqExport.php,v $
*
* @version $Revision: 1.10 $
* @modified $Date: 2010/03/21 19:28:34 $ by $Author: franciscom $
*
* Allows users to export requirements.
*
* 20100321 - franciscom - manage export of :
* req. spec => full tree or branch (new to 1.9)
* child (direct children) requirements inside a req. spec
**/
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 = templateConfiguration();
$req_spec_mgr = new requirement_spec_mgr($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 = strings_stripSlashes($_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->get_export_file_types();
$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('all_reqspecs_in_tproject');
$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>" : 'requirement-specification>';
switch($argsObj->scope)
{
case 'tree':
$reqSpecSet = $req_spec_mgr->getFirstLevelInTestProject($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;
downloadContentsToFile($content,$fileName);
exit();
}
}
?> | qasourceinc/TestLink_1.9.5_QASourceContribution | lib/requirements/reqExport.php | PHP | gpl-2.0 | 4,583 |
/* Basic IPA utilities for type inheritance graph construction and
devirtualization.
Copyright (C) 2013-2015 Free Software Foundation, Inc.
Contributed by Jan Hubicka
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
/* 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:
build_type_inheritance_graph 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.
possible_polymorphic_call_targets 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 odr_types_equivalent_p (tree, tree, bool, bool *,
hash_set<type_pair> *,
location_t, location_t);
static bool odr_violation_reported = false;
/* Pointer set of all call targets appearing in the cache. */
static hash_set<cgraph_node *> *cached_polymorphic_call_targets;
/* 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 all_derivations_known;
/* 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 -fno-lto-odr-type-merigng. */
if (in_lto_p)
{
/* To support -fno-lto-odr-type-merigng recognize types with vtables
to have linkage. */
if (RECORD_OR_UNION_TYPE_P (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 (!DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t)))
return false;
}
return (RECORD_OR_UNION_TYPE_P (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
type_in_anonymous_namespace_p (const_tree t)
{
gcc_assert (type_with_linkage_p (t));
/* Keep -fno-lto-odr-type-merging working by recognizing classes with vtables
properly into anonymous namespaces. */
if (RECORD_OR_UNION_TYPE_P (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 type_in_anonymous_namespace_p. */
#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 -fno-lto-odr-type-merging consider types with vtables ODR. */
if (type_with_linkage_p (t) && type_in_anonymous_namespace_p (t))
return true;
if (TYPE_NAME (t) && TREE_CODE (TYPE_NAME (t)) == TYPE_DECL
&& (DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t))))
{
#ifdef ENABLE_CHECKING
/* C++ FE uses magic <anon> as assembler names of anonymous types.
verify that this match with type_in_anonymous_namespace_p. */
gcc_assert (!type_with_linkage_p (t)
|| strcmp ("<anon>",
IDENTIFIER_POINTER
(DECL_ASSEMBLER_NAME (TYPE_NAME (t))))
|| type_in_anonymous_namespace_p (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
type_all_derivations_known_p (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 (type_in_anonymous_namespace_p (t))
return true;
return (decl_function_context (TYPE_NAME (t)) != NULL);
}
/* Return TRUE if type's constructors are all visible. */
static bool
type_all_ctors_visible_p (tree t)
{
return !flag_ltrans
&& symtab->state >= CONSTRUCTION
/* We can not always use type_all_derivations_known_p.
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. */
&& type_in_anonymous_namespace_p (t);
}
/* Return TRUE if type may have instance. */
static bool
type_possibly_instantiated_p (tree t)
{
tree vtable;
varpool_node *vnode;
/* TODO: Add abstract types here. */
if (!type_all_ctors_visible_p (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 -fno-lto-odr-type-merging 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
can_be_name_hashed_p (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) && type_in_anonymous_namespace_p (t))
return htab_hash_pointer (t);
gcc_checking_assert (TYPE_NAME (t)
&& DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t)));
return IDENTIFIER_HASH_VALUE (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
can_be_vtable_hashed_p (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) && type_in_anonymous_namespace_p (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 (!type_in_anonymous_namespace_p (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 (IDENTIFIER_HASH_VALUE (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) && type_in_anonymous_namespace_p (type1))
|| (type_with_linkage_p (type2) && type_in_anonymous_namespace_p (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 -fno-lto-odr-type-merging. 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) || !DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (type1)))
|| (!TYPE_NAME (type2) || !DECL_ASSEMBLER_NAME_SET_P (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
types_odr_comparable (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)
&& polymorphic_type_binfo_p (TYPE_BINFO (t1))
&& polymorphic_type_binfo_p (TYPE_BINFO (t2))));
}
/* Return true if T1 and T2 are ODR equivalent. If ODR equivalency is not
known, be conservative and return false. */
bool
types_must_be_same_for_odr (tree t1, tree t2)
{
if (types_odr_comparable (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 TYPE_METHOD_BASETYPE (t);
if (TREE_CODE (t) == OFFSET_TYPE)
return TYPE_OFFSET_BASETYPE (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
odr_or_derived_type_p (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 (TYPE_METHOD_BASETYPE (t))
t = TYPE_METHOD_BASETYPE (t);
else
{
if (TREE_TYPE (t) && odr_or_derived_type_p (TREE_TYPE (t)))
return true;
for (t = TYPE_ARG_TYPES (t); t; t = TREE_CHAIN (t))
if (odr_or_derived_type_p (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) && type_in_anonymous_namespace_p (t1))
|| (type_with_linkage_p (t2) && type_in_anonymous_namespace_p (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> odr_vtable_hash_type;
static odr_vtable_hash_type *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
odr_subtypes_equivalent_p (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) && type_in_anonymous_namespace_p (t1))
|| (type_with_linkage_p (t2) && type_in_anonymous_namespace_p (t2)))
return false;
/* For ODR types be sure to compare their names.
To support -wno-odr-type-merging we allow one type to be non-ODR
and other ODR even though it is a violation. */
if (types_odr_comparable (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 odr_types_equivalent_p (t1, t2, false, NULL, visited, loc1, loc2);
}
/* Compare two virtual tables, PREVAILING and VTABLE and output ODR
violation warnings. */
void
compare_virtual_tables (varpool_node *prevailing, varpool_node *vtable)
{
int n1, n2;
if (DECL_VIRTUAL_P (prevailing->decl) != DECL_VIRTUAL_P (vtable->decl))
{
odr_violation_reported = true;
if (DECL_VIRTUAL_P (prevailing->decl))
{
varpool_node *tmp = prevailing;
prevailing = vtable;
vtable = tmp;
}
if (warning_at (DECL_SOURCE_LOCATION
(TYPE_NAME (DECL_CONTEXT (vtable->decl))),
OPT_Wodr,
"virtual table of type %qD violates one definition rule",
DECL_CONTEXT (vtable->decl)))
inform (DECL_SOURCE_LOCATION (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))
|| !polymorphic_type_binfo_p (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 (DECL_SOURCE_LOCATION
(TYPE_NAME (DECL_CONTEXT (vtable->decl))),
OPT_Wodr,
"virtual table of type %qD contains RTTI "
"information",
DECL_CONTEXT (vtable->decl)))
{
inform (DECL_SOURCE_LOCATION
(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
"but is prevailed by one without from other translation "
"unit");
inform (DECL_SOURCE_LOCATION
(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 (DECL_SOURCE_LOCATION
(TYPE_NAME (DECL_CONTEXT (vtable->decl))),
OPT_Wodr,
"virtual table of type %qD violates "
"one definition rule ",
DECL_CONTEXT (vtable->decl)))
{
inform (DECL_SOURCE_LOCATION
(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 (DECL_SOURCE_LOCATION
(TYPE_NAME (DECL_CONTEXT (vtable->decl))),
OPT_Wodr,
"virtual table of type %qD violates "
"one definition rule ",
DECL_CONTEXT (vtable->decl)))
{
inform (DECL_SOURCE_LOCATION
(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 (DECL_SOURCE_LOCATION
(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 (DECL_SOURCE_LOCATION
(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
"the conflicting type defined in another translation "
"unit");
inform (DECL_SOURCE_LOCATION
(TYPE_NAME (DECL_CONTEXT (ref1->referring->decl))),
"contains additional virtual method %qD",
ref1->referred->decl);
}
else
{
inform (DECL_SOURCE_LOCATION
(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 (DECL_SOURCE_LOCATION
(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 (DECL_SOURCE_LOCATION
(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
"the conflicting type defined in another translation "
"unit");
gcc_assert (TREE_CODE (ref2->referred->decl)
== FUNCTION_DECL);
inform (DECL_SOURCE_LOCATION (ref1->referred->decl),
"virtual method %qD", ref1->referred->decl);
inform (DECL_SOURCE_LOCATION (ref2->referred->decl),
"ought to match virtual method %qD but does not",
ref2->referred->decl);
}
else
inform (DECL_SOURCE_LOCATION
(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->apply_location_cache ();
if (!warning_at (DECL_SOURCE_LOCATION (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 (DECL_SOURCE_LOCATION (decl2),
"a different type is defined in another translation unit");
if (!st1)
{
st1 = st2;
st2 = NULL;
}
inform (DECL_SOURCE_LOCATION (st1),
"the first difference of corresponding definitions is field %qD",
st1);
if (st2)
decl2 = st2;
}
else if (TREE_CODE (st1) == FUNCTION_DECL)
{
inform (DECL_SOURCE_LOCATION (decl2),
"a different type is defined in another translation unit");
inform (DECL_SOURCE_LOCATION (st1),
"the first difference of corresponding definitions is method %qD",
st1);
decl2 = st2;
}
else
return;
inform (DECL_SOURCE_LOCATION (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 (odr_or_derived_type_p (t1) && odr_or_derived_type_p (t2)
&& !odr_types_equivalent_p (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
? DECL_SOURCE_LOCATION (TYPE_NAME (t1))
: UNKNOWN_LOCATION;
location_t loc_t2 = TYPE_NAME (t2) && TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL
? DECL_SOURCE_LOCATION (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) && type_in_anonymous_namespace_p (t1))
|| (type_with_linkage_p (t2) && type_in_anonymous_namespace_p (t2)))
{
if (type_with_linkage_p (t1) && !type_in_anonymous_namespace_p (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
&& DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t1))
&& DECL_ASSEMBLER_NAME_SET_P (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 (types_odr_comparable (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
gimple_canonical_types_compatible_p.
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
odr_types_equivalent_p (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) || !type_in_anonymous_namespace_p (t1));
gcc_assert (!type_with_linkage_p (t2) || !type_in_anonymous_namespace_p (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) && type_in_anonymous_namespace_p (t1))
|| (type_with_linkage_p (t2) && type_in_anonymous_namespace_p (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 (comp_type_attributes (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
useless_type_conversion_p 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 (!odr_subtypes_equivalent_p (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)
&& !odr_subtypes_equivalent_p (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 (!odr_subtypes_equivalent_p (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 (TYPE_NONALIASED_COMPONENT (t1)
== TYPE_NONALIASED_COMPONENT (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 (!odr_subtypes_equivalent_p (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 (!odr_subtypes_equivalent_p
(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)
&& polymorphic_type_binfo_p (TYPE_BINFO (t1))
!= polymorphic_type_binfo_p (TYPE_BINFO (t2)))
{
if (polymorphic_type_binfo_p (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 (!odr_subtypes_equivalent_p (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 (!gimple_compare_field_offset (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 (DECL_NONADDRESSABLE_P (f1)
== DECL_NONADDRESSABLE_P (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 (odr_subtypes_equivalent_p (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
odr_types_equivalent_p (tree type1, tree type2)
{
hash_set<type_pair> visited;
#ifdef ENABLE_CHECKING
gcc_assert (odr_or_derived_type_p (type1) && odr_or_derived_type_p (type2));
#endif
return odr_types_equivalent_p (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)
&& polymorphic_type_binfo_p (TYPE_BINFO (type)))
&& (TREE_CODE (val->type) != RECORD_TYPE || !TYPE_BINFO (val->type)
|| !polymorphic_type_binfo_p (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 (can_be_name_hashed_p (type) && !can_be_name_hashed_p (val->type))
SET_DECL_ASSEMBLER_NAME (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 (DECL_SOURCE_LOCATION (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 (types_odr_comparable (type1, type2))
{
if (!types_same_for_odr (type1, type2))
base_mismatch = true;
}
else
if (!odr_types_equivalent_p (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)
&& polymorphic_type_binfo_p (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)
&& polymorphic_type_binfo_p (TYPE_BINFO (type1))
!= polymorphic_type_binfo_p (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;
odr_violation_reported = 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 (!odr_types_equivalent_p (val->type, type,
!flag_ltrans && !val->odr_violated && !warned,
&warned, &visited,
DECL_SOURCE_LOCATION (TYPE_NAME (val->type)),
DECL_SOURCE_LOCATION (TYPE_NAME (type))))
{
merge = false;
odr_violation_reported = 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 (polymorphic_type_binfo_p (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 (polymorphic_type_binfo_p (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 possible_polymorphic_call_targets.
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 (can_be_name_hashed_p (type)
|| can_be_vtable_hashed_p (type));
/* Lookup entry, first try name hash, fallback to vtable hash. */
if (can_be_name_hashed_p (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 && can_be_vtable_hashed_p (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 && can_be_vtable_hashed_p (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 && can_be_vtable_hashed_p (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 = type_in_anonymous_namespace_p (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->all_derivations_known = type_all_derivations_known_p (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 (polymorphic_type_binfo_p (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 odr_vtable_hash_type (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
type_known_to_have_no_derivations_p (tree t)
{
return (type_all_derivations_known_p (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->all_derivations_known ? " (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 (DECL_ASSEMBLER_NAME_SET_P (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
dump_type_inheritance_graph (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
build_type_inheritance_graph (void)
{
struct symtab_node *n;
FILE *inheritance_dump_file;
int flags;
if (odr_hash)
return;
timevar_push (TV_IPA_INHERITANCE);
inheritance_dump_file = dump_begin (TDI_inheritance, &flags);
odr_hash = new odr_hash_type (23);
if (in_lto_p)
odr_vtable_hash = new odr_vtable_hash_type (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 (TYPE_METHOD_BASETYPE (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, record_target_from_binfo 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))
&& polymorphic_type_binfo_p (TYPE_BINFO (DECL_CONTEXT (n->decl))))
get_odr_type (TYPE_MAIN_VARIANT (DECL_CONTEXT (n->decl)), true);
if (inheritance_dump_file)
{
dump_type_inheritance_graph (inheritance_dump_file);
dump_end (TDI_inheritance, inheritance_dump_file);
}
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
referenced_from_vtable_p (struct cgraph_node *node)
{
int i;
struct ipa_ref *ref;
bool found = false;
if (node->externally_visible
|| DECL_EXTERNAL (node->decl)
|| node->used_from_other_partition)
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
&& referenced_from_vtable_p (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 __builtin_unreachable 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
|| !type_in_anonymous_namespace_p (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->ultimate_alias_target (&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
&& type_in_anonymous_namespace_p (DECL_CONTEXT (target))
&& (!target_node
|| !referenced_from_vtable_p (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))
{
cached_polymorphic_call_targets->add (target_node);
nodes.safe_push (target_node);
}
}
else if (completep
&& (!type_in_anonymous_namespace_p
(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
record_target_from_binfo (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 (odr_violation_reported);
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 = gimple_get_virt_method_for_binfo (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 || !DECL_CXX_DESTRUCTOR_P (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 (polymorphic_type_binfo_p (base_binfo))
record_target_from_binfo (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 CONSIDER_CONSTRUCTION is true, record to BASES_TO_CONSIDER
all cases where BASE_SKIPPED is true (because the base is abstract
class). */
static void
possible_polymorphic_call_targets_1 (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 consider_construction)
{
tree binfo = TYPE_BINFO (type->type);
unsigned int i;
auto_vec <tree, 8> type_binfos;
bool possibly_instantiated = type_possibly_instantiated_p (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 (possibly_instantiated || consider_construction)
{
record_target_from_binfo (nodes,
(!possibly_instantiated
&& type_all_derivations_known_p (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++)
possible_polymorphic_call_targets_1 (nodes, inserted,
matched_vtables,
otr_type,
type->derived_types[i],
otr_token, outer_type, offset, completep,
bases_to_consider, consider_construction);
}
/* 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 polymorphic_call_target_d
{
HOST_WIDE_INT otr_token;
ipa_polymorphic_call_context context;
odr_type type;
vec <cgraph_node *> targets;
tree decl_warning;
int type_warning;
bool complete;
bool speculative;
};
/* Polymorphic call target cache helpers. */
struct polymorphic_call_target_hasher
: pointer_hash <polymorphic_call_target_d>
{
static inline hashval_t hash (const polymorphic_call_target_d *);
static inline bool equal (const polymorphic_call_target_d *,
const polymorphic_call_target_d *);
static inline void remove (polymorphic_call_target_d *);
};
/* Return the computed hashcode for ODR_QUERY. */
inline hashval_t
polymorphic_call_target_hasher::hash (const polymorphic_call_target_d *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.speculative_outer_type)
{
hstate.merge_hash (TYPE_UID (odr_query->context.speculative_outer_type));
hstate.add_wide_int (odr_query->context.speculative_offset);
}
hstate.add_flag (odr_query->speculative);
hstate.add_flag (odr_query->context.maybe_in_construction);
hstate.add_flag (odr_query->context.maybe_derived_type);
hstate.add_flag (odr_query->context.speculative_maybe_derived_type);
hstate.commit_flag ();
return hstate.end ();
}
/* Compare cache entries T1 and T2. */
inline bool
polymorphic_call_target_hasher::equal (const polymorphic_call_target_d *t1,
const polymorphic_call_target_d *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.speculative_outer_type == t2->context.speculative_outer_type
&& t1->context.maybe_in_construction
== t2->context.maybe_in_construction
&& t1->context.maybe_derived_type == t2->context.maybe_derived_type
&& (t1->context.speculative_maybe_derived_type
== t2->context.speculative_maybe_derived_type));
}
/* Remove entry in polymorphic call target cache hash. */
inline void
polymorphic_call_target_hasher::remove (polymorphic_call_target_d *v)
{
v->targets.release ();
free (v);
}
/* Polymorphic call target query cache. */
typedef hash_table<polymorphic_call_target_hasher>
polymorphic_call_target_hash_type;
static polymorphic_call_target_hash_type *polymorphic_call_target_hash;
/* Destroy polymorphic call target query cache. */
static void
free_polymorphic_call_targets_hash ()
{
if (cached_polymorphic_call_targets)
{
delete polymorphic_call_target_hash;
polymorphic_call_target_hash = NULL;
delete cached_polymorphic_call_targets;
cached_polymorphic_call_targets = NULL;
}
}
/* When virtual function is removed, we may need to flush the cache. */
static void
devirt_node_removal_hook (struct cgraph_node *n, void *d ATTRIBUTE_UNUSED)
{
if (cached_polymorphic_call_targets
&& cached_polymorphic_call_targets->contains (n))
free_polymorphic_call_targets_hash ();
}
/* Look up base of BINFO that has virtual table VTABLE with OFFSET. */
tree
subbinfo_with_vtable_at_offset (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 (!vtable_pointer_value_to_vtable (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 (polymorphic_type_binfo_p (base_binfo))
{
base_binfo = subbinfo_with_vtable_at_offset (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
vtable_pointer_value_to_vtable (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
vtable_pointer_value_to_binfo (const_tree t)
{
tree vtable;
unsigned HOST_WIDE_INT offset;
if (!vtable_pointer_value_to_vtable (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 subbinfo_with_vtable_at_offset (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
record_targets_from_bases (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. */
&& polymorphic_type_binfo_p (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 (odr_violation_reported);
return;
}
gcc_assert (base_binfo);
if (!matched_vtables->add (BINFO_VTABLE (base_binfo)))
{
bool can_refer;
tree target = gimple_get_virt_method_for_binfo (otr_token,
base_binfo,
&can_refer);
if (!target || ! DECL_CXX_DESTRUCTOR_P (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
devirt_variable_node_removal_hook (varpool_node *n,
void *d ATTRIBUTE_UNUSED)
{
if (cached_polymorphic_call_targets
&& DECL_VIRTUAL_P (n->decl)
&& type_in_anonymous_namespace_p (DECL_CONTEXT (n->decl)))
free_polymorphic_call_targets_hash ();
}
/* 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 final_warning_record
{
gcov_type dyn_count;
vec<odr_type_warn_count> type_warnings;
hash_map<tree, decl_warn_count> decl_warnings;
};
struct final_warning_record *final_warning_records;
/* 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. INCLUDE_DERIVER_TYPES 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 *>
possible_polymorphic_call_targets (tree otr_type,
HOST_WIDE_INT otr_token,
ipa_polymorphic_call_context context,
bool *completep,
void **cache_token,
bool speculative)
{
static struct cgraph_node_hook_list *node_removal_hook_holder;
vec <cgraph_node *> nodes = vNULL;
auto_vec <tree, 8> bases_to_consider;
odr_type type, outer_type;
polymorphic_call_target_d key;
polymorphic_call_target_d **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.speculative_outer_type)
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.speculative_outer_type)
&& !context.restrict_to_inner_class (otr_type))
{
if (completep)
*completep = true;
if (cache_token)
*cache_token = NULL;
return nodes;
}
gcc_assert (!context.invalid);
/* Check that restrict_to_inner_class 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 (!cached_polymorphic_call_targets)
{
cached_polymorphic_call_targets = new hash_set<cgraph_node *>;
polymorphic_call_target_hash
= new polymorphic_call_target_hash_type (23);
if (!node_removal_hook_holder)
{
node_removal_hook_holder =
symtab->add_cgraph_removal_hook (&devirt_node_removal_hook, NULL);
symtab->add_varpool_removal_hook (&devirt_variable_node_removal_hook,
NULL);
}
}
if (in_lto_p)
{
if (context.outer_type != otr_type)
context.outer_type
= get_odr_type (context.outer_type, true)->type;
if (context.speculative_outer_type)
context.speculative_outer_type
= get_odr_type (context.speculative_outer_type, true)->type;
}
/* Look up cached answer. */
key.type = type;
key.otr_token = otr_token;
key.speculative = speculative;
key.context = context;
slot = polymorphic_call_target_hash->find_slot (&key, INSERT);
if (cache_token)
*cache_token = (void *)*slot;
if (*slot)
{
if (completep)
*completep = (*slot)->complete;
if ((*slot)->type_warning && final_warning_records)
{
final_warning_records->type_warnings[(*slot)->type_warning - 1].count++;
final_warning_records->type_warnings[(*slot)->type_warning - 1].dyn_count
+= final_warning_records->dyn_count;
}
if (!speculative && (*slot)->decl_warning && final_warning_records)
{
struct decl_warn_count *c =
final_warning_records->decl_warnings.get ((*slot)->decl_warning);
c->count++;
c->dyn_count += final_warning_records->dyn_count;
}
return (*slot)->targets;
}
complete = true;
/* Do actual search. */
timevar_push (TV_IPA_VIRTUAL_CALL);
*slot = XCNEW (polymorphic_call_target_d);
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.speculative_outer_type)
{
odr_type speculative_outer_type;
bool speculation_complete = true;
/* First insert target from type itself and check if it may have
derived types. */
speculative_outer_type = get_odr_type (context.speculative_outer_type, true);
if (TYPE_FINAL_P (speculative_outer_type->type))
context.speculative_maybe_derived_type = false;
binfo = get_binfo_at_offset (TYPE_BINFO (speculative_outer_type->type),
context.speculative_offset, otr_type);
if (binfo)
target = gimple_get_virt_method_for_binfo (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.speculative_maybe_derived_type = false;
if (type_possibly_instantiated_p (speculative_outer_type->type))
maybe_record_node (nodes, target, &inserted, can_refer, &speculation_complete);
if (binfo)
matched_vtables.add (BINFO_VTABLE (binfo));
/* Next walk recursively all derived types. */
if (context.speculative_maybe_derived_type)
for (i = 0; i < speculative_outer_type->derived_types.length(); i++)
possible_polymorphic_call_targets_1 (nodes, &inserted,
&matched_vtables,
otr_type,
speculative_outer_type->derived_types[i],
otr_token, speculative_outer_type->type,
context.speculative_offset,
&speculation_complete,
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 = gimple_get_virt_method_for_binfo (otr_token, binfo,
&can_refer);
else
{
gcc_assert (odr_violation_reported);
target = NULL;
}
/* Destructors are never called through construction virtual tables,
because the type is always known. */
if (target && DECL_CXX_DESTRUCTOR_P (target))
context.maybe_in_construction = 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 (type_possibly_instantiated_p (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++)
possible_polymorphic_call_targets_1 (nodes, &inserted,
&matched_vtables,
otr_type,
outer_type->derived_types[i],
otr_token, outer_type->type,
context.offset, &complete,
bases_to_consider,
context.maybe_in_construction);
if (!outer_type->all_derivations_known)
{
if (!speculative && final_warning_records)
{
if (complete
&& nodes.length () == 1
&& warn_suggest_final_types
&& !outer_type->derived_types.length ())
{
if (outer_type->id >= (int)final_warning_records->type_warnings.length ())
final_warning_records->type_warnings.safe_grow_cleared
(odr_types.length ());
final_warning_records->type_warnings[outer_type->id].count++;
final_warning_records->type_warnings[outer_type->id].dyn_count
+= final_warning_records->dyn_count;
final_warning_records->type_warnings[outer_type->id].type
= outer_type->type;
(*slot)->type_warning = outer_type->id + 1;
}
if (complete
&& warn_suggest_final_methods
&& nodes.length () == 1
&& types_same_for_odr (DECL_CONTEXT (nodes[0]->decl),
outer_type->type))
{
bool existed;
struct decl_warn_count &c =
final_warning_records->decl_warnings.get_or_insert
(nodes[0]->decl, &existed);
if (existed)
{
c.count++;
c.dyn_count += final_warning_records->dyn_count;
}
else
{
c.count = 1;
c.dyn_count = final_warning_records->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.maybe_in_construction)
for (i =0 ; i < MIN (nodes.length (), 2); i++)
if (DECL_CXX_DESTRUCTOR_P (nodes[i]->decl))
context.maybe_in_construction = false;
if (context.maybe_in_construction)
{
if (type != outer_type
&& (!skipped
|| (context.maybe_derived_type
&& !type_all_derivations_known_p (outer_type->type))))
record_targets_from_bases (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)",
DECL_DECLARED_INLINE_P (targets[i]->decl)
? " inline" : "");
}
fprintf (f, "\n");
}
/* Dump all possible targets of a polymorphic call. */
void
dump_possible_polymorphic_call_targets (FILE *f,
tree otr_type,
HOST_WIDE_INT otr_token,
const ipa_polymorphic_call_context &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 = possible_polymorphic_call_targets (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.maybe_in_construction ? " (base types included)" : "",
ctx.maybe_derived_type ? " (derived types included)" : "",
ctx.speculative_maybe_derived_type ? " (speculative derived types included)" : "");
len = targets.length ();
dump_targets (f, targets);
targets = possible_polymorphic_call_targets (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
possible_polymorphic_call_target_p (tree otr_type,
HOST_WIDE_INT otr_token,
const ipa_polymorphic_call_context &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))
== BUILT_IN_UNREACHABLE
|| fcode == BUILT_IN_TRAP))
return true;
if (!odr_hash)
return true;
targets = possible_polymorphic_call_targets (otr_type, otr_token, ctx, &final);
for (i = 0; i < targets.length (); i++)
if (n->semantically_equivalent_p (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
possible_polymorphic_call_target_p (tree ref,
gimple stmt,
struct cgraph_node *n)
{
ipa_polymorphic_call_context context (current_function_decl, ref, stmt);
tree call_fn = gimple_call_fn (stmt);
return possible_polymorphic_call_target_p (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
update_type_inheritance_graph (void)
{
struct cgraph_node *n;
if (!odr_hash)
return;
free_polymorphic_call_targets_hash ();
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 (TYPE_METHOD_BASETYPE (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 = flags_from_decl_or_type (n->decl);
if (flags & ECF_NORETURN)
return false;
if (lookup_attribute ("cold",
DECL_ATTRIBUTES (n->decl)))
return false;
if (n->frequency < NODE_FREQUENCY_NORMAL)
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 (!referenced_from_vtable_p (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 *
try_speculative_devirtualization (tree otr_type, HOST_WIDE_INT otr_token,
ipa_polymorphic_call_context ctx)
{
vec <cgraph_node *>targets
= possible_polymorphic_call_targets
(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)
dump_type_inheritance_graph (dump_file);
/* We can output -Wsuggest-final-methods and -Wsuggest-final-types warnings.
This is implemented by setting up final_warning_records that are updated
by get_polymorphic_call_targets.
We need to clear cache in this case to trigger recomputation of all
entries. */
if (warn_suggest_final_methods || warn_suggest_final_types)
{
final_warning_records = new (final_warning_record);
final_warning_records->type_warnings = vNULL;
final_warning_records->type_warnings.safe_grow_cleared (odr_types.length ());
free_polymorphic_call_targets_hash ();
}
FOR_EACH_DEFINED_FUNCTION (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 (final_warning_records)
final_warning_records->dyn_count = e->count;
vec <cgraph_node *>targets
= possible_polymorphic_call_targets
(e, &final, &cache_token, true);
unsigned int i;
/* Trigger warnings by calculating non-speculative targets. */
if (warn_suggest_final_methods || warn_suggest_final_types)
possible_polymorphic_call_targets (e);
if (dump_file)
dump_possible_polymorphic_call_targets
(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 remove_unreachable_nodes 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, flag_devirtualize_speculatively)
&& e->indirect_info->vptr_changed))
&& !flag_ltrans_devirtualize)
{
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, flag_devirtualize_speculatively))
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->speculative_call_info (e2, e, ref);
if (e2->callee->ultimate_alias_target ()
== likely_target->ultimate_alias_target ())
{
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 = gimple_location_safe (e->call_stmt);
dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, 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->noninterposable_alias ());
if (alias)
likely_target = alias;
}
nconverted++;
update = true;
e->make_speculative
(likely_target, e->count * 8 / 10, e->frequency * 8 / 10);
}
}
if (update)
inline_update_overall_summary (n);
}
if (warn_suggest_final_methods || warn_suggest_final_types)
{
if (warn_suggest_final_types)
{
final_warning_records->type_warnings.qsort (type_warning_cmp);
for (unsigned int i = 0;
i < final_warning_records->type_warnings.length (); i++)
if (final_warning_records->type_warnings[i].count)
{
tree type = final_warning_records->type_warnings[i].type;
int count = final_warning_records->type_warnings[i].count;
long long dyn_count
= final_warning_records->type_warnings[i].dyn_count;
if (!dyn_count)
warning_n (DECL_SOURCE_LOCATION (TYPE_NAME (type)),
OPT_Wsuggest_final_types, 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 (DECL_SOURCE_LOCATION (TYPE_NAME (type)),
OPT_Wsuggest_final_types, 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 (warn_suggest_final_methods)
{
vec<const decl_warn_count*> decl_warnings_vec = vNULL;
final_warning_records->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 (DECL_CXX_DESTRUCTOR_P (decl))
warning_n (DECL_SOURCE_LOCATION (decl),
OPT_Wsuggest_final_methods, 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 (DECL_SOURCE_LOCATION (decl),
OPT_Wsuggest_final_methods, 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 (DECL_CXX_DESTRUCTOR_P (decl))
warning_n (DECL_SOURCE_LOCATION (decl),
OPT_Wsuggest_final_methods, 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 (DECL_SOURCE_LOCATION (decl),
OPT_Wsuggest_final_methods, 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 (final_warning_records);
final_warning_records = 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 ? TODO_remove_functions : 0;
}
namespace {
const pass_data pass_data_ipa_devirt =
{
IPA_PASS, /* type */
"devirt", /* name */
OPTGROUP_NONE, /* optinfo_flags */
TV_IPA_DEVIRT, /* tv_id */
0, /* properties_required */
0, /* properties_provided */
0, /* properties_destroyed */
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 (pass_data_ipa_devirt, ctxt,
NULL, /* generate_summary */
NULL, /* write_summary */
NULL, /* read_summary */
NULL, /* write_optimization_summary */
NULL, /* read_optimization_summary */
NULL, /* stmt_fixup */
0, /* function_transform_todo_flags_start */
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
&& (flag_devirtualize_speculatively
|| (warn_suggest_final_methods
|| warn_suggest_final_types))
&& optimize);
}
virtual unsigned int execute (function *) { return ipa_devirt (); }
}; // class pass_ipa_devirt
} // anon namespace
ipa_opt_pass_d *
make_pass_ipa_devirt (gcc::context *ctxt)
{
return new pass_ipa_devirt (ctxt);
}
#include "gt-ipa-devirt.h"
| nguyentu1602/gcc | gcc/ipa-devirt.c | C | gpl-2.0 | 126,410 |
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
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 = -3229418883339488380L;
/**
* 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.COLUMNNAME_M_InOutLine_ID+"=?", 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 IllegalArgumentException("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 M_AttributeSetInstance_ID asi
* @param MovementQty qty
*/
public MInOutLineMA (MInOutLine parent, int M_AttributeSetInstance_ID, BigDecimal MovementQty)
{
this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent);
setM_InOutLine_ID(parent.getM_InOutLine_ID());
//
setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
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(",M_AttributeSetInstance_ID=").append(getM_AttributeSetInstance_ID())
.append(", Qty=").append(getMovementQty())
.append ("]");
return sb.toString ();
} // toString
} // MInOutLineMA
| erpcya/adempierePOS | base/src/org/compiere/model/MInOutLineMA.java | Java | gpl-2.0 | 4,940 |
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#ifdef PAIR_CLASS
PairStyle(lj/charmm/coul/msm,PairLJCharmmCoulMSM)
#else
#ifndef LMP_PAIR_LJ_CHARMM_COUL_MSM_H
#define LMP_PAIR_LJ_CHARMM_COUL_MSM_H
#include "pair_lj_charmm_coul_long.h"
namespace LAMMPS_NS {
class PairLJCharmmCoulMSM : public PairLJCharmmCoulLong {
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
/* ERROR/WARNING messages:
E: Illegal ... command
Self-explanatory. Check the input script syntax and compare to the
documentation for the command. You can use -echo screen as a
command-line option when running LAMMPS to see the offending line.
E: Incorrect args for pair coefficients
Self-explanatory. Check the input script or data file.
E: Pair style lj/charmm/coul/long requires atom attribute q
The atom style defined does not have these attributes.
E: Pair inner cutoff >= Pair outer cutoff
The specified cutoffs for the pair style are inconsistent.
E: Pair cutoff < Respa interior cutoff
One or more pairwise cutoffs are too short to use with the specified
rRESPA cutoffs.
E: Pair inner cutoff < Respa interior cutoff
One or more pairwise cutoffs are too short to use with the specified
rRESPA cutoffs.
E: Pair style is incompatible with KSpace style
If a pair style with a long-range Coulombic component is selected,
then a kspace style must also be used.
*/
| jcarlson23/lammps | src/KSPACE/pair_lj_charmm_coul_msm.h | C | gpl-2.0 | 2,192 |
#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 CompressionRateTable[]={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, #4\n"
"MOV R4, SP\n"
"B loc_FFD3B4C8\n"
"loc_FFD3B424:\n"
"LDR R3, =0x6E460\n"
"LDR R2, [R3]\n"
"CMP R2, #0\n"
"BNE loc_FFD3B4B4\n"
"SUB R3, R12, #2\n"
"CMP R3, #9\n"
"LDRLS PC, [PC,R3,LSL#2]\n"
"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, #0\n"
"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, #0\n"
"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, #4\n"
"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, #3\n"
"MOV R4, R0\n"
"MOVEQ R3, #4\n"
"STREQ R3, [R5]\n"
"LDR R3, =0x6E52C\n"
"MOV LR, PC\n"
"LDR PC, [R3]\n"
"LDR R2, [R5]\n"
"CMP R2, #4\n"
"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, #0\n"
"BNE loc_FFD3BB64\n"
"LDR R3, =0x6E468\n"
"LDR R2, [R3]\n"
"CMP R2, #1\n"
"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, #5\n"
"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, #1\n"
"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, #9\n"
"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, #0\n"
"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, #1\n"
"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, #1\n"
"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, #0\n"
"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, #1\n"
"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,#8]\n"
"STR R3, [SP,#4]\n"
"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, #1\n"
"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, #1\n"
"AND R0, R0, #1\n"
"STR R5, [R3,R0,LSL#2]\n"
"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, #8\n"
"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, #8\n"
"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, #8\n"
"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,#4]\n"
"MOV R0, R3\n"
"MOV R1, #0\n"
"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, #0\n"
"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, #0\n"
"MVN R1, #0x17\n"
"ADDS R5, R5, R1\n"
"MOV R4, #0\n"
"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, #1\n"
"MOV R1, R9\n"
"STMIA LR, {R7,R8}\n"
"BL sub_FFEDC0F0\n"
"CMP R10, #1\n"
"MLA R0, R9, R0, R0\n"
"BEQ loc_FFD3D3DC\n"
"SUB R3, R0, #1\n"
"MOV R3, R3,LSL#4\n"
"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#4\n"
"ADD R2, R2, #8\n"
"MOV R0, #0\n"
"ADD R12, R11, #0xC\n"
"ADD R1, R11, #8\n"
"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, #9\n"
"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, #8\n"
"STR R3, [R0]\n"
"B loc_FFD3D424\n"
"loc_FFD3D418:\n"
"ADD R3, R1, #8\n"
"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,#8]\n"
"STR R1, [R0]\n"
"LDR R1, [SP,#4]\n"
"STR R3, [R1]\n"
"B loc_FFD3D494\n"
"loc_FFD3D478:\n"
"LDR R0, [SP,#0xC]\n"
"STR R2, [R0]\n"
"LDR R1, [SP,#4]\n"
"MOV R3, #0\n"
"STR R3, [R1]\n"
"LDR R2, [SP,#8]\n"
"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,#8]\n"
"LDR R2, [R1]\n"
"CMP R2, #0\n"
"BEQ loc_FFD3D4F4\n"
"LDR R3, =0x6E7BC\n"
"LDR R1, [R3]\n"
"CMP R2, R1\n"
"BHI loc_FFD3D4F4\n"
"LDR R0, [SP,#4]\n"
"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,#4]\n"
"ADD R2, R2, #0x18\n"
"MOV R1, R2\n"
"MOV R2, #0\n"
"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#4\n"
"ADD R3, R3, R3,LSL#2\n"
"LDR R12, =0x6E820\n"
"MOV R3, R3,LSL#1\n"
"ADD R3, R3, #0xA0\n"
"LDR R2, [R12,#4]\n"
"MOV R0, R3\n"
"MOV R1, #0\n"
"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, #0\n"
"BNE loc_FFD3D59C\n"
"MOV R0, #0x3140\n"
"ADD R0, R0, #8\n"
"BL sub_FFD54E78\n"
"MOV R3, #1\n"
"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#4\n"
"MVN R3, #0x9F\n"
"ADD R2, R2, R2,LSL#2\n"
"ADD R3, R3, #0x40000000\n"
"SUB R3, R3, R2,LSL#1\n"
"LDR R1, [R0,#4]\n"
"MOV R4, R3\n"
"MOV R5, #0\n"
"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, #0\n"
"BNE loc_FFD3D60C\n"
"MOV R0, #0x3140\n"
"ADD R0, R0, #8\n"
"BL sub_FFD54E78\n"
"MOV R3, #1\n"
"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#2\n"
"ADD R2, R2, R3,LSL#1\n"
"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, #0\n"
"BNE loc_FFD3D65C\n"
"MOV R0, #0x3140\n"
"ADD R0, R0, #8\n"
"BL sub_FFD54E78\n"
"MOV R3, #1\n"
"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, #0\n"
"MOV R3, #0x18\n"
"ADDS R1, R1, R0\n"
"ADC R2, R2, #0\n"
"ADDS R1, R1, R3\n"
"ADC R2, R2, R4\n"
"CMP R2, #0\n"
"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, #0\n"
"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, #1\n"
"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, #0\n"
"LDR R1, [R3]\n"
"BEQ loc_FFD3C5F4\n"
"LDR R2, =0x6E544\n"
"LDR R3, [R2]\n"
"CMP R3, #1\n"
"BNE loc_FFD3C608\n"
"B loc_FFD3C5F8\n"
"loc_FFD3C5F4:\n"
"LDR R2, =0x6E544\n"
"loc_FFD3C5F8:\n"
"MOV R3, #0\n"
"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#1\n"
"MOV LR, R3,LSL#2\n"
"LDR R2, [R5,LR]\n"
"LDR R4, =table2\n" //+ 0xFFD3C440
"RSB R12, R2, R0\n"
"LDR R3, [R4,LR]\n"
"CMP R12, #0\n"
"RSB R0, R3, R0\n"
"BLE loc_FFD3C66C\n"
"ADD R3, R5, #4\n"
"LDR R2, [R3,LR]\n"
"CMP R2, R12\n"
"ADDGE R1, R1, #1\n"
"BGE loc_FFD3C660\n"
"ADD R3, R5, #8\n"
"LDR R2, [R3,LR]\n"
"CMP R2, R12\n"
"ADDGE R1, R1, #2\n"
"ADDLT R1, R1, #3\n"
"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, #0\n"
"BGE loc_FFD3C6A4\n"
"ADD R3, R4, #4\n"
"LDR R2, [R3,LR]\n"
"CMP R2, R0\n"
"SUBLE R1, R1, #1\n"
"BLE loc_FFD3C69C\n"
"ADD R3, R4, #8\n"
"LDR R2, [R3,LR]\n"
"CMP R2, R0\n"
"SUBLE R1, R1, #2\n"
"SUBGT R1, R1, #3\n"
"loc_FFD3C69C:\n"
"CMP R1, #0\n"
"MOVLT R1, #0\n"
"loc_FFD3C6A4:\n"
"LDR R0, =0x6E540\n"
"LDR R3, [R0]\n"
"CMP R1, R3\n"
"LDRNE R2, =0x6E544\n"
"MOVNE R3, #1\n"
"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, =CompressionRateTable\n" // + 0xFFD3C3E0
"LDR R12, [R1]\n"
"LDR R12, [R12]\n" //+
"LDR LR, [R2,R0,LSL#2]\n"
"LDR R3, =0x6E538\n"
"CMP R12, #1\n"
"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"
);
}
| arne182/chdk-eyefi | platform/a700/sub/100b/movie_rec.c | C | gpl-2.0 | 37,022 |
<?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->get_preferred_language() : $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 'pll_language_defined'
*
* @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
// see https://wordpress.org/support/topic/detect-browser-language-sometimes-setting-null-language
$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( 'pll_language_defined', $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( 'pll_cookie_expiration', 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
);
}
}
/**
* get the preferred language according to the browser preferences
* code adapted from http://www.thefutureoftheweb.com/blog/use-accept-language-header
*
* @since 1.8
*
* @return string|bool the preferred language slug or false
*/
public function get_preferred_browser_language() {
$accept_langs = array();
if ( isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
// 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['HTTP_ACCEPT_LANGUAGE'], $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 get_preferred_language() {
// 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( 'pll_preferred_language', $this->options['browser'] ? $this->get_preferred_browser_language() : 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
// thanks to Ov3rfly http://wordpress.org/support/topic/enhance-feature-when-front-page-is-visited-set-language-according-to-browser
$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->get_preferred_language(); // 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
// FIXME why this happens? http://wordpress.org/support/topic/polylang-crashes-1
// 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( 'pll_set_language_from_query', 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
// as well as when searching an empty string: http://wordpress.org/support/topic/plugin-polylang-polylang-breaks-search-in-spun-theme
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',
);
}
}
| petersondrs/interage-consultoria | wp-content/plugins/polylang/frontend/choose-lang.php | PHP | gpl-2.0 | 10,845 |
// -*- C++ -*-
// Copyright (C) 2005-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// 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
// warranty.
/**
* @file native_tree_tag.hpp
* Contains a tag for native tree-based containers
*/
#ifndef PB_DS_NATIVE_TREE_DS_TAG_HPP
#define PB_DS_NATIVE_TREE_DS_TAG_HPP
namespace __gnu_pbds
{
namespace test
{
struct native_tree_tag
{ };
} // namespace test
} // namespace __gnu_pbds
#endif
| mickael-guene/gcc | libstdc++-v3/testsuite/util/native_type/native_tree_tag.hpp | C++ | gpl-2.0 | 1,637 |
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Copyright (C) 2011 Red Hat, Inc.
*/
#ifndef NM_FIREWALL_MANAGER_H
#define NM_FIREWALL_MANAGER_H
#include <glib-object.h>
#include <dbus/dbus-glib.h>
#define FIREWALL_DBUS_SERVICE "org.fedoraproject.FirewallD1"
#define FIREWALL_DBUS_PATH "/org/fedoraproject/FirewallD1"
#define FIREWALL_DBUS_INTERFACE "org.fedoraproject.FirewallD1"
#define FIREWALL_DBUS_INTERFACE_ZONE "org.fedoraproject.FirewallD1.zone"
G_BEGIN_DECLS
#define NM_TYPE_FIREWALL_MANAGER (nm_firewall_manager_get_type ())
#define NM_FIREWALL_MANAGER(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), NM_TYPE_FIREWALL_MANAGER, NMFirewallManager))
#define NM_FIREWALL_MANAGER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), NM_TYPE_FIREWALL_MANAGER, NMFirewallManagerClass))
#define NM_IS_FIREWALL_MANAGER(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), NM_TYPE_FIREWALL_MANAGER))
#define NM_IS_FIREWALL_MANAGER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), NM_TYPE_FIREWALL_MANAGER))
#define NM_FIREWALL_MANAGER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), NM_TYPE_FIREWALL_MANAGER, NMFirewallManagerClass))
#define NM_FIREWALL_MANAGER_AVAILABLE "available"
typedef struct {
GObject parent;
} NMFirewallManager;
typedef struct {
GObjectClass parent;
/* Signals */
void (*started) (NMFirewallManager *manager);
} NMFirewallManagerClass;
GType nm_firewall_manager_get_type (void);
NMFirewallManager *nm_firewall_manager_get (void);
typedef void (*FwAddToZoneFunc) (GError *error, gpointer user_data);
gpointer nm_firewall_manager_add_or_change_zone (NMFirewallManager *mgr,
const char *iface,
const char *zone,
gboolean add,
FwAddToZoneFunc callback,
gpointer user_data);
gpointer nm_firewall_manager_remove_from_zone (NMFirewallManager *mgr,
const char *iface,
const char *zone);
void nm_firewall_manager_cancel_call (NMFirewallManager *mgr, gpointer fw_call);
#endif /* NM_FIREWALL_MANAGER_H */
| heftig/NetworkManager | src/firewall-manager/nm-firewall-manager.h | C | gpl-2.0 | 3,094 |
#include <lwk/types.h>
long
sys_getgroups(int n, gid_t gids[])
{
return 0;
}
| jnouyang/kitten | kernel/linux_syscalls/getgroups.c | C | gpl-2.0 | 79 |
// license:BSD-3-Clause
// copyright-holders:Bryan McPhail
/***************************************************************************
Desert Assault Video emulation - Bryan McPhail, mish@tendril.co.uk
I'm not sure if one of the alpha blending effects is correct (mode 0x8000,
the usual mode 0x4000 should be correct). It may be some kind of orthogonal
priority effect where it should cut a hole in other higher priority sprites
to reveal a non-alpha'd hole, or alpha against a further back tilemap.
(is this the helicopter shadow at the end of lv.1 ?)
Also, some priorities are still a little questionable.
****************************************************************************/
#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::screen_update_dassault(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->get_sprite_temp_bitmap();
bitmap_ind16* sprite_bitmap2 = &m_sprgen2->get_sprite_temp_bitmap();
/* 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); // 1
m_deco_tilegen1->tilemap_2_draw(screen, bitmap, cliprect, 0, 2); // 2
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0400, 0x0600, 0x400, 0xff); // 8
m_deco_tilegen2->tilemap_1_draw(screen, bitmap, cliprect, 0, 16); // 16
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0200, 0x0600, 0x400, 0xff); // 32
mixdassaultlayer(bitmap, sprite_bitmap2, cliprect, 0x0000, 0x0000, 0x800, 0x80); // 64?
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0000, 0x0600, 0x400, 0xff); // 128
}
else if ((priority & 3) == 1)
{
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0600, 0x0600, 0x400, 0xff); // 1
m_deco_tilegen2->tilemap_1_draw(screen, bitmap, cliprect, 0, 2); // 2
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0400, 0x0600, 0x400, 0xff); // 8
mixdassaultlayer(bitmap, sprite_bitmap2, cliprect, 0x0000, 0x0000, 0x800, 0x80); // 16?
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0200, 0x0600, 0x400, 0xff); // 32
m_deco_tilegen1->tilemap_2_draw(screen, bitmap, cliprect, 0, 64); // 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); // 1
m_deco_tilegen2->tilemap_1_draw(screen, bitmap, cliprect, 0, 2); // 2
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0400, 0x0600, 0x400, 0xff); // 8
m_deco_tilegen1->tilemap_2_draw(screen, bitmap, cliprect, 0, 16); // 16
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0200, 0x0600, 0x400, 0xff); // 32
mixdassaultlayer(bitmap, sprite_bitmap2, cliprect, 0x0000, 0x0000, 0x800, 0x80); // 64?
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;
}
| GiuseppeGorgoglione/mame | src/mame/video/dassault.cpp | C++ | gpl-2.0 | 5,152 |
// { dg-do run { target c++11 } }
// 2007-10-12 Paolo Carlini <pcarlini@suse.de>
//
// Copyright (C) 2007-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 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;
}
| mickael-guene/gcc | libstdc++-v3/testsuite/25_algorithms/is_heap/1.cc | C++ | gpl-2.0 | 1,437 |
/*
$Id: sdt.h,v 1.5 2006/01/02 18:24:24 rasc Exp $
DVBSNOOP
a dvb sniffer and mpeg2 stream analyzer tool
http://dvbsnoop.sourceforge.net/
(c) 2001-2006 Rainer.Scherg@gmx.de (rasc)
*/
void section_SDT (u_char *b, int len);
| a4tunado/dvbsnoop | src/sections/sdt.h | C | gpl-2.0 | 239 |
/*
* Copyright (C) 2010-2015 ARM Limited. All rights reserved.
*
* This program is free software and is provided to you under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence.
*
* A copy of the licence is included with the program, and can also be obtained from Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* @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 ump_get_api_version_wrapper(u32 __user *argument, struct ump_session_data *session_data)
{
_ump_uk_api_version_s version_info;
_mali_osk_errcode_t err;
/* Sanity check input parameters */
if (NULL == argument || NULL == session_data) {
MSG_ERR(("NULL parameter in ump_ioctl_get_api_version()\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 ump_ioctl_get_api_version()\n"));
return -EFAULT;
}
version_info.ctx = (void *) session_data;
err = _ump_uku_get_api_version(&version_info);
if (_MALI_OSK_ERR_OK != err) {
MSG_ERR(("_ump_uku_get_api_version() failed in ump_ioctl_get_api_version()\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 ump_ioctl_get_api_version()\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 ump_ioctl_get_api_version()\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 ump_size_get_wrapper(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 ump_cache_operations_control_wrapper(u32 __user *argument, struct ump_session_data *session_data)
{
_ump_uk_cache_operations_control_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_cache_operations_control()\n"));
return -EFAULT;
}
user_interaction.ctx = (void *) session_data;
_ump_ukk_cache_operations_control((_ump_uk_cache_operations_control_s *) &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 ump_ioctl_cache_operations_control()\n"));
return -EFAULT;
}
#endif
return 0; /* success */
}
int ump_switch_hw_usage_wrapper(u32 __user *argument, struct ump_session_data *session_data)
{
_ump_uk_switch_hw_usage_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_switch_hw_usage()\n"));
return -EFAULT;
}
user_interaction.ctx = (void *) session_data;
_ump_ukk_switch_hw_usage(&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 ump_ioctl_switch_hw_usage()\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 ump_ioctl_switch_hw_usage()\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 ump_ioctl_switch_hw_usage()\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 ump_ioctl_switch_hw_usage()\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 ump_ioctl_switch_hw_usage()\n"));
return -EFAULT;
}
#endif
return 0; /* success */
}
| kszaq/linux-amlogic | drivers/amlogic/gpu/ump/linux/ump_ukk_wrappers.c | C | gpl-2.0 | 7,996 |
/***************************************************************************
tag: Peter Soetens Wed Apr 17 16:01:31 CEST 2002 TimerThread.cpp
TimerThread.cpp - description
-------------------
begin : Wed April 17 2002
copyright : (C) 2002 Peter Soetens
email : peter.soetens@mech.kuleuven.ac.be
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; *
* version 2 of the License. *
* *
* As a special exception, you may use this file as part of a free *
* software library without restriction. Specifically, if other files *
* instantiate templates or use macros or inline functions from this *
* file, or you compile this file and link it with other files to *
* produce an executable, this file does not by itself cause the *
* resulting executable to be covered by the GNU General Public *
* License. This exception does not however invalidate any other *
* reasons why the executable file might be covered by the GNU General *
* Public License. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
#include "TimerThread.hpp"
#include "PeriodicActivity.hpp"
#include "rtt-config.h"
#include "../Time.hpp"
#include "../Logger.hpp"
#include <algorithm>
#include "../os/MutexLock.hpp"
namespace RTT {
using namespace extras;
using namespace base;
using os::MutexLock;
using namespace std;
TimerThread::TimerThreadList TimerThread::TimerThreads;
TimerThreadPtr TimerThread::Instance(int pri, double per)
{
return Instance(ORO_SCHED_RT, pri, per);
}
TimerThreadPtr TimerThread::Instance(int scheduler, int pri, double per)
{
return Instance(scheduler, pri, per, ~0);
}
TimerThreadPtr TimerThread::Instance(int scheduler, int pri, double per, unsigned cpu_affinity)
{
// Since the period is stored as nsecs, we convert per to NS in order
// to get a match.
os::CheckPriority(scheduler, pri);
TimerThreadList::iterator it = TimerThreads.begin();
while ( it != TimerThreads.end() ) {
TimerThreadPtr tptr = it->lock();
// detect old pointer.
if ( !tptr ) {
TimerThreads.erase(it);
it = TimerThreads.begin();
continue;
}
if ( tptr->getScheduler() == scheduler && tptr->getPriority() == pri && tptr->getPeriodNS() == Seconds_to_nsecs(per) ) {
return tptr;
}
++it;
}
TimerThreadPtr ret( new TimerThread(scheduler, pri, "TimerThreadInstance", per, cpu_affinity) );
TimerThreads.push_back( ret );
return ret;
}
TimerThread::TimerThread(int priority, const std::string& name, double periodicity, unsigned cpu_affinity)
: Thread( ORO_SCHED_RT, priority, periodicity, cpu_affinity, name), cleanup(false)
{
tasks.reserve(MAX_ACTIVITIES);
}
TimerThread::TimerThread(int scheduler, int priority, const std::string& name, double periodicity, unsigned cpu_affinity)
: Thread(scheduler, priority, periodicity, cpu_affinity, name), cleanup(false)
{
tasks.reserve(MAX_ACTIVITIES);
}
TimerThread::~TimerThread()
{
// make sure the thread does not run when we start deleting clocks...
this->stop();
}
bool TimerThread::addActivity( PeriodicActivity* t ) {
MutexLock lock(mutex);
if ( tasks.size() == MAX_ACTIVITIES ) {
// Logger::log() << Logger:: << "TimerThread : tasks queue full, failed to add Activity : "<< t << Logger::endl;
return false;
}
tasks.push_back( t );
// Logger::log() << Logger::Debug << "TimerThread : successfully started Activity : "<< t << Logger::endl;
return true;
}
bool TimerThread::removeActivity( PeriodicActivity* t ) {
MutexLock lock(mutex);
ActivityList::iterator it = find(tasks.begin(), tasks.end(), t);
if ( it != tasks.end() ) {
*it = 0; // clear task away
cleanup = true;
return true;
}
// Logger::log() << Logger::Debug << "TimerThread : failed to stop Activity : "<< t->getPeriod() << Logger::endl;
return false;
}
bool TimerThread::initialize() {
return true;
}
void TimerThread::finalize() {
MutexLock lock(mutex);
for( ActivityList::iterator t_iter = tasks.begin(); t_iter != tasks.end(); ++t_iter)
if ( *t_iter )
(*t_iter)->stop(); // stop() calls us back to removeActivity (recursive mutex).
if ( cleanup )
this->reorderList();
}
void TimerThread::step() {
MutexLock lock(mutex);
// The size of the tasks vector does not change during add/remove, thus
// t_iter is never invalidated.
for( ActivityList::iterator t_iter = tasks.begin(); t_iter != tasks.end(); ++t_iter)
if ( *t_iter )
(*t_iter)->step();
if ( cleanup )
this->reorderList();
}
void TimerThread::reorderList() {
// reorder the list to remove clear'ed tasks
ActivityList::iterator begin = tasks.begin();
// first zero :
PeriodicActivity* nullActivity = 0;
ActivityList::iterator it = tasks.begin();
it = find( tasks.begin(), tasks.end(), nullActivity); // First zero
begin = it+1;
while ( it != tasks.end() ) {
// Look for first non-zero after 'it' :
while ( begin != tasks.end() && *begin == 0 )
++begin;
if ( begin == tasks.end() ) { // if no task found after zero :
// Logger::log() << Logger::Error << "beginBefore resize :"<< tasks.size() << Logger::endl;
tasks.resize( it - tasks.begin() ); // cut out the items after 'it'
// Logger::log() << Logger::Error << "beginAfter resize :"<< tasks.size() << Logger::endl;
break; // This is our exit condition !
}
// first zero after begin :
ActivityList::iterator end = find ( begin, tasks.end(), nullActivity);
// if end == tasks.end() ==> next while will copy all
// if end != tasks.end() ==> next while will copy first zero's
while ( begin != end ) {
*it = *begin; // copy operation
++begin;
++it; // go to next slot to inspect.
}
}
cleanup = false;
}
}
| shyamalschandra/rtt | rtt/extras/TimerThread.cpp | C++ | gpl-2.0 | 7,933 |
/* Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/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 msm_ispif_intf_reset(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 +
ISPIF_RST_CMD_1_ADDR);
rc = wait_for_completion_interruptible(&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(ISPIF_RST_CMD_1_MASK, ispif->base +
ISPIF_RST_CMD_1_ADDR);
rc = wait_for_completion_interruptible(&ispif->reset_complete);
return rc;
}
static int msm_ispif_subdev_g_chip_ident(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 msm_ispif_sel_csid_core(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 + ISPIF_INPUT_SEL_ADDR +
(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 + ISPIF_INPUT_SEL_ADDR +
(0x200 * vfe_intf));
}
}
static void msm_ispif_enable_intf_cids(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 +
ISPIF_PIX_0_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
data |= cid_mask;
msm_camera_io_w(data, ispif->base +
ISPIF_PIX_0_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
break;
case RDI0:
data = msm_camera_io_r(ispif->base +
ISPIF_RDI_0_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
data |= cid_mask;
msm_camera_io_w(data, ispif->base +
ISPIF_RDI_0_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
break;
case PIX1:
data = msm_camera_io_r(ispif->base +
ISPIF_PIX_1_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
data |= cid_mask;
msm_camera_io_w(data, ispif->base +
ISPIF_PIX_1_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
break;
case RDI1:
data = msm_camera_io_r(ispif->base +
ISPIF_RDI_1_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
data |= cid_mask;
msm_camera_io_w(data, ispif->base +
ISPIF_RDI_1_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
break;
case RDI2:
data = msm_camera_io_r(ispif->base +
ISPIF_RDI_2_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
data |= cid_mask;
msm_camera_io_w(data, ispif->base +
ISPIF_RDI_2_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
break;
}
mutex_unlock(&ispif->mutex);
}
static int32_t msm_ispif_validate_intf_status(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 +
ISPIF_PIX_0_STATUS_ADDR + (0x200 * vfe_intf));
break;
case RDI0:
data = msm_camera_io_r(ispif->base +
ISPIF_RDI_0_STATUS_ADDR + (0x200 * vfe_intf));
break;
case PIX1:
data = msm_camera_io_r(ispif->base +
ISPIF_PIX_1_STATUS_ADDR + (0x200 * vfe_intf));
break;
case RDI1:
data = msm_camera_io_r(ispif->base +
ISPIF_RDI_1_STATUS_ADDR + (0x200 * vfe_intf));
break;
case RDI2:
data = msm_camera_io_r(ispif->base +
ISPIF_RDI_2_STATUS_ADDR + (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 msm_ispif_params_list *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 + ISPIF_IRQ_MASK_1_ADDR);
msm_camera_io_w(0x00000000, ispif->base + ISPIF_IRQ_MASK_2_ADDR);
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 = msm_ispif_validate_intf_status(ispif, intftype, vfe_intf);
if (rc < 0) {
pr_err("%s:%d failed rc %d\n", __func__, __LINE__, rc);
return rc;
}
msm_ispif_sel_csid_core(ispif, intftype, ispif_params[i].csid,
vfe_intf);
msm_ispif_enable_intf_cids(ispif, intftype,
ispif_params[i].cid_mask, vfe_intf);
}
msm_camera_io_w(ISPIF_IRQ_STATUS_MASK, ispif->base +
ISPIF_IRQ_MASK_ADDR);
msm_camera_io_w(ISPIF_IRQ_STATUS_MASK, ispif->base +
ISPIF_IRQ_CLEAR_ADDR);
msm_camera_io_w(ISPIF_IRQ_STATUS_1_MASK, ispif->base +
ISPIF_IRQ_MASK_1_ADDR);
msm_camera_io_w(ISPIF_IRQ_STATUS_1_MASK, ispif->base +
ISPIF_IRQ_CLEAR_1_ADDR);
msm_camera_io_w(ISPIF_IRQ_STATUS_2_MASK, ispif->base +
ISPIF_IRQ_MASK_2_ADDR);
msm_camera_io_w(ISPIF_IRQ_STATUS_2_MASK, ispif->base +
ISPIF_IRQ_CLEAR_2_ADDR);
msm_camera_io_w(ISPIF_IRQ_GLOBAL_CLEAR_CMD, ispif->base +
ISPIF_IRQ_GLOBAL_CLEAR_CMD_ADDR);
return rc;
}
static uint32_t msm_ispif_get_cid_mask(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 +
ISPIF_PIX_0_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
break;
case RDI0:
mask = msm_camera_io_r(ispif->base +
ISPIF_RDI_0_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
break;
case PIX1:
mask = msm_camera_io_r(ispif->base +
ISPIF_PIX_1_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
break;
case RDI1:
mask = msm_camera_io_r(ispif->base +
ISPIF_RDI_1_INTF_CID_MASK_ADDR + (0x200 * vfe_intf));
break;
case RDI2:
mask = msm_camera_io_r(ispif->base +
ISPIF_RDI_2_INTF_CID_MASK_ADDR + (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 global_intf_cmd_mask1 = 0xFFFFFFFF;
while (mask != 0) {
if (!(intfmask & (0x1 << intfnum))) {
mask >>= 1;
intfnum++;
continue;
}
cid_mask = msm_ispif_get_cid_mask(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->global_intf_cmd_mask |=
(0x3 << ((vc * 2) +
(intfnum * 8)));
ispif->global_intf_cmd_mask &=
~((0x3 & ~val) << ((vc * 2) +
(intfnum * 8)));
} else
global_intf_cmd_mask1 &=
~((0x3 & ~intf_cmd_mask)
<< ((vc * 2) + 8));
}
vc++;
cid_mask >>= 4;
}
mask >>= 1;
intfnum++;
}
msm_camera_io_w(ispif->global_intf_cmd_mask,
ispif->base + ISPIF_INTF_CMD_ADDR + (0x200 * vfe_intf));
if (global_intf_cmd_mask1 != 0xFFFFFFFF)
msm_camera_io_w(global_intf_cmd_mask1,
ispif->base + ISPIF_INTF_CMD_1_ADDR +
(0x200 * vfe_intf));
}
static int msm_ispif_abort_intf_transfer(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->global_intf_cmd_mask |= (0xFF << (intfnum * 8));
mask >>= 1;
intfnum++;
if (intfnum == RDI2)
break;
}
mutex_unlock(&ispif->mutex);
return rc;
}
static int msm_ispif_start_intf_transfer(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 = msm_ispif_intf_reset(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 msm_ispif_stop_intf_transfer(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 +
ISPIF_PIX_0_STATUS_ADDR +
(0x200 * vfe_intf))
& 0xf) != 0xf) {
CDBG("Wait for pix0 Idle\n");
}
break;
case RDI0:
while ((msm_camera_io_r(ispif->base +
ISPIF_RDI_0_STATUS_ADDR +
(0x200 * vfe_intf))
& 0xf) != 0xf) {
CDBG("Wait for rdi0 Idle\n");
}
break;
case PIX1:
while ((msm_camera_io_r(ispif->base +
ISPIF_PIX_1_STATUS_ADDR +
(0x200 * vfe_intf))
& 0xf) != 0xf) {
CDBG("Wait for pix1 Idle\n");
}
break;
case RDI1:
while ((msm_camera_io_r(ispif->base +
ISPIF_RDI_1_STATUS_ADDR +
(0x200 * vfe_intf))
& 0xf) != 0xf) {
CDBG("Wait for rdi1 Idle\n");
}
break;
case RDI2:
while ((msm_camera_io_r(ispif->base +
ISPIF_RDI_2_STATUS_ADDR +
(0x200 * vfe_intf))
& 0xf) != 0xf) {
CDBG("Wait for rdi2 Idle\n");
}
break;
default:
break;
}
if (intfnum != RDI2)
ispif->global_intf_cmd_mask |= (0xFF <<
(intfnum * 8));
}
mask >>= 1;
intfnum++;
}
mutex_unlock(&ispif->mutex);
return rc;
}
static int msm_ispif_subdev_video_s_stream(struct v4l2_subdev *sd,
int enable)
{
struct ispif_device *ispif =
(struct ispif_device *)v4l2_get_subdevdata(sd);
uint32_t cmd = enable & ((1<<ISPIF_S_STREAM_SHIFT)-1);
uint16_t intf = enable >> ISPIF_S_STREAM_SHIFT;
uint8_t vfe_intf = enable >> ISPIF_VFE_INTF_SHIFT;
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 ISPIF_ON_FRAME_BOUNDARY:
rc = msm_ispif_start_intf_transfer(ispif, intf, vfe_intf);
break;
case ISPIF_OFF_FRAME_BOUNDARY:
rc = msm_ispif_stop_intf_transfer(ispif, intf, vfe_intf);
break;
case ISPIF_OFF_IMMEDIATELY:
rc = msm_ispif_abort_intf_transfer(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, NOTIFY_AXI_RDI_SOF_COUNT,
(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) {
spin_unlock_irqrestore(&ispif_tasklet_lock,
flags);
return;
}
list_del(&qcmd->list);
spin_unlock_irqrestore(&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->ispifInterruptStatus0 = out->ispifIrqStatus0;
qcmd->ispifInterruptStatus1 = out->ispifIrqStatus1;
qcmd->ispifInterruptStatus2 = out->ispifIrqStatus2;
if (qcmd->ispifInterruptStatus0 &
ISPIF_IRQ_STATUS_PIX_SOF_MASK) {
CDBG("%s: ispif PIX irq status\n", __func__);
ispif->pix_sof_count++;
v4l2_subdev_notify(&ispif->subdev,
NOTIFY_VFE_PIX_SOF_COUNT,
(void *)&ispif->pix_sof_count);
}
if (qcmd->ispifInterruptStatus0 &
ISPIF_IRQ_STATUS_RDI0_SOF_MASK) {
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->ispifInterruptStatus1 &
ISPIF_IRQ_STATUS_RDI1_SOF_MASK) {
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->ispifInterruptStatus2 &
ISPIF_IRQ_STATUS_RDI2_SOF_MASK) {
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);
spin_unlock_irqrestore(&ispif_tasklet_lock, flags);
tasklet_schedule(&ispif->ispif_tasklet);
return;
}
static inline void msm_ispif_read_irq_status(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 +
ISPIF_IRQ_STATUS_ADDR);
out->ispifIrqStatus1 = msm_camera_io_r(ispif->base +
ISPIF_IRQ_STATUS_1_ADDR);
out->ispifIrqStatus2 = msm_camera_io_r(ispif->base +
ISPIF_IRQ_STATUS_2_ADDR);
msm_camera_io_w(out->ispifIrqStatus0,
ispif->base + ISPIF_IRQ_CLEAR_ADDR);
msm_camera_io_w(out->ispifIrqStatus1,
ispif->base + ISPIF_IRQ_CLEAR_1_ADDR);
msm_camera_io_w(out->ispifIrqStatus2,
ispif->base + ISPIF_IRQ_CLEAR_2_ADDR);
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 & ISPIF_IRQ_STATUS_MASK ||
out->ispifIrqStatus1 & ISPIF_IRQ_STATUS_1_MASK ||
out->ispifIrqStatus2 & ISPIF_IRQ_STATUS_2_MASK) {
if (out->ispifIrqStatus0 & (0x1 << RESET_DONE_IRQ))
complete(&ispif->reset_complete);
if (out->ispifIrqStatus0 & (0x1 << PIX_INTF_0_OVERFLOW_IRQ))
pr_err("%s: pix intf 0 overflow.\n", __func__);
if (out->ispifIrqStatus0 & (0x1 << RAW_INTF_0_OVERFLOW_IRQ))
pr_err("%s: rdi intf 0 overflow.\n", __func__);
if (out->ispifIrqStatus1 & (0x1 << RAW_INTF_1_OVERFLOW_IRQ))
pr_err("%s: rdi intf 1 overflow.\n", __func__);
if (out->ispifIrqStatus2 & (0x1 << RAW_INTF_2_OVERFLOW_IRQ))
pr_err("%s: rdi intf 2 overflow.\n", __func__);
if ((out->ispifIrqStatus0 & ISPIF_IRQ_STATUS_SOF_MASK) ||
(out->ispifIrqStatus1 & ISPIF_IRQ_STATUS_SOF_MASK) ||
(out->ispifIrqStatus2 & ISPIF_IRQ_STATUS_RDI2_SOF_MASK))
ispif_process_irq(ispif, out);
}
if (ispif->csid_version == CSID_VERSION_V3) {
status0 = msm_camera_io_r(ispif->base +
ISPIF_IRQ_STATUS_ADDR + 0x200);
msm_camera_io_w(status0,
ispif->base + ISPIF_IRQ_CLEAR_ADDR + 0x200);
status1 = msm_camera_io_r(ispif->base +
ISPIF_IRQ_STATUS_1_ADDR + 0x200);
msm_camera_io_w(status1,
ispif->base + ISPIF_IRQ_CLEAR_1_ADDR + 0x200);
status2 = msm_camera_io_r(ispif->base +
ISPIF_IRQ_STATUS_2_ADDR + 0x200);
msm_camera_io_w(status2,
ispif->base + ISPIF_IRQ_CLEAR_2_ADDR + 0x200);
CDBG("%s: irq vfe1 Irq_status0 = 0x%x, 1 = 0x%x, 2 = 0x%x\n",
__func__, status0, status1, status2);
}
msm_camera_io_w(ISPIF_IRQ_GLOBAL_CLEAR_CMD, ispif->base +
ISPIF_IRQ_GLOBAL_CLEAR_CMD_ADDR);
}
static irqreturn_t msm_io_ispif_irq(int irq_num, void *data)
{
struct ispif_irq_status irq;
msm_ispif_read_irq_status(&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->global_intf_cmd_mask = 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 ISPIF_SET_ON_FRAME_BOUNDARY:
case ISPIF_SET_OFF_FRAME_BOUNDARY:
case ISPIF_SET_OFF_IMMEDIATELY:
rc = msm_ispif_subdev_video_s_stream(sd, cdata.cfg.cmd);
break;
case ISPIF_RELEASE:
msm_ispif_release(ispif);
break;
default:
break;
}
return rc;
}
static long msm_ispif_subdev_ioctl(struct v4l2_subdev *sd, unsigned int cmd,
void *arg)
{
switch (cmd) {
case VIDIOC_MSM_ISPIF_CFG:
return msm_ispif_cmd(sd, arg);
default:
return -ENOIOCTLCMD;
}
}
static struct v4l2_subdev_core_ops msm_ispif_subdev_core_ops = {
.g_chip_ident = &msm_ispif_subdev_g_chip_ident,
.ioctl = &msm_ispif_subdev_ioctl,
};
static struct v4l2_subdev_video_ops msm_ispif_subdev_video_ops = {
.s_stream = &msm_ispif_subdev_video_s_stream,
};
static const struct v4l2_subdev_ops msm_ispif_subdev_ops = {
.core = &msm_ispif_subdev_core_ops,
.video = &msm_ispif_subdev_video_ops,
};
static const struct v4l2_subdev_internal_ops msm_ispif_internal_ops;
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, &msm_ispif_subdev_ops);
ispif->subdev.internal_ops = &msm_ispif_internal_ops;
ispif->subdev.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
snprintf(ispif->subdev.name,
ARRAY_SIZE(ispif->subdev.name), "msm_ispif");
v4l2_set_subdevdata(&ispif->subdev, ispif);
platform_set_drvdata(pdev, &ispif->subdev);
snprintf(ispif->subdev.name, sizeof(ispif->subdev.name),
"ispif");
mutex_init(&ispif->mutex);
if (pdev->dev.of_node)
of_property_read_u32((&pdev->dev)->of_node,
"cell-index", &pdev->id);
ispif->mem = platform_get_resource_byname(pdev,
IORESOURCE_MEM, "ispif");
if (!ispif->mem) {
pr_err("%s: no mem resource?\n", __func__);
rc = -ENODEV;
goto ispif_no_resource;
}
ispif->irq = platform_get_resource_byname(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;
msm_cam_register_subdev_node(&ispif->subdev, &sd_info);
media_entity_init(&ispif->subdev.entity, 0, NULL, 0);
ispif->subdev.entity.type = MEDIA_ENT_T_V4L2_SUBDEV;
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 msm_ispif_init_module(void)
{
return platform_driver_register(&ispif_driver);
}
static void __exit msm_ispif_exit_module(void)
{
platform_driver_unregister(&ispif_driver);
}
module_init(msm_ispif_init_module);
module_exit(msm_ispif_exit_module);
MODULE_DESCRIPTION("MSM ISP Interface driver");
MODULE_LICENSE("GPL v2");
| androidrbox/android_kernel_amazon_bueller | drivers/media/video/msm/csi/msm_ispif.c | C | gpl-2.0 | 25,457 |
/*
* #%L
* Bio-Formats Plugins for ImageJ: a collection of ImageJ plugins including the
* Bio-Formats Importer, Bio-Formats Exporter, Bio-Formats Macro Extensions,
* Data Browser and Stack Slicer.
* %%
* Copyright (C) 2006 - 2015 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
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();
}
}
| dgault/bioformats | components/bio-formats-plugins/src/loci/plugins/util/WindowTools.java | Java | gpl-2.0 | 6,353 |
/*****************************************************************************
* Copyright Statement:
* --------------------
* This software is protected by Copyright and the information contained
* herein is confidential. The software may not be copied and the information
* contained herein may not be used or disclosed except with the written
* permission of MediaTek Inc. (C) 2008
*
* BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
* SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
* LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
* WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
* LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
* RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
* THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/
#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 MTK_WDT_MODE_KEYMASK (0xff00)
#define MTK_WDT_MODE_KEY (0x22000000)
#define MTK_WDT_MODE_DUAL_MODE (0x0040)
#define MTK_WDT_MODE_IN_DIS (0x0020) /* Reserved */
#define MTK_WDT_MODE_AUTO_RESTART (0x0010) /* Reserved */
#define MTK_WDT_MODE_IRQ (0x0008)
#define MTK_WDT_MODE_EXTEN (0x0004)
#define MTK_WDT_MODE_EXT_POL (0x0002)
#define MTK_WDT_MODE_ENABLE (0x0001)
/*WDT_LENGTH*/
#define MTK_WDT_LENGTH_TIME_OUT (0xffe0)
#define MTK_WDT_LENGTH_KEYMASK (0x001f)
#define MTK_WDT_LENGTH_KEY (0x0008)
/*WDT_RESTART*/
#define MTK_WDT_RESTART_KEY (0x1971)
/*WDT_STATUS*/
#define MTK_WDT_STATUS_HWWDT_RST (0x80000000)
#define MTK_WDT_STATUS_SWWDT_RST (0x40000000)
#define MTK_WDT_STATUS_IRQWDT_RST (0x20000000)
#define MTK_WDT_STATUS_DEBUGWDT_RST (0x00080000)
#define MTK_WDT_STATUS_SPMWDT_RST (0x0001)
/*WDT_INTERVAL*/
#define MTK_WDT_INTERVAL_MASK (0x0fff)
/*WDT_SWRST*/
#define MTK_WDT_SWRST_KEY (0x1209)
/*WDT_SWSYSRST*/
#define MTK_WDT_SWSYS_RST_PWRAP_SPI_CTL_RST (0x0800)
#define MTK_WDT_SWSYS_RST_APMIXED_RST (0x0400)
#define MTK_WDT_SWSYS_RST_MD_LITE_RST (0x0200)
#define MTK_WDT_SWSYS_RST_INFRA_AO_RST (0x0100)
#define MTK_WDT_SWSYS_RST_MD_RST (0x0080)
#define MTK_WDT_SWSYS_RST_DDRPHY_RST (0x0040)
#define MTK_WDT_SWSYS_RST_IMG_RST (0x0020)
#define MTK_WDT_SWSYS_RST_VDEC_RST (0x0010)
#define MTK_WDT_SWSYS_RST_VENC_RST (0x0008)
#define MTK_WDT_SWSYS_RST_MFG_RST (0x0004)
#define MTK_WDT_SWSYS_RST_DISP_RST (0x0002)
#define MTK_WDT_SWSYS_RST_INFRA_RST (0x0001)
//#define MTK_WDT_SWSYS_RST_KEY (0x1500)
#define MTK_WDT_SWSYS_RST_KEY (0x88000000)
/*MTK_WDT_REQ_IRQ*/
#define MTK_WDT_REQ_IRQ_KEY (0x44000000)
#define MTK_WDT_REQ_IRQ_DEBUG_EN (0x80000)
#define MTK_WDT_REQ_IRQ_SPM_THERMAL_EN (0x0001)
#define MTK_WDT_REQ_IRQ_SPM_SCPSYS_EN (0x0002)
#define MTK_WDT_REQ_IRQ_THERMAL_EN (1<<18)
/*MTK_WDT_REQ_MODE*/
#define MTK_WDT_REQ_MODE_KEY (0x33000000)
#define MTK_WDT_REQ_MODE_DEBUG_EN (0x80000)
#define MTK_WDT_REQ_MODE_SPM_THERMAL (0x0001)
#define MTK_WDT_REQ_MODE_SPM_SCPSYS (0x0002)
#define MTK_WDT_REQ_MODE_THERMAL (1<<18)
#define WDT_NORMAL_REBOOT (0x01)
#define WDT_BY_PASS_PWK_REBOOT (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 mtk_wdt_check_status(void);
extern BOOL mtk_is_rgu_trigger_reset(void);
extern void mtk_arch_reset(char mode);
void rgu_swsys_reset(WD_SYS_RST_TYPE reset_type);
#endif /*__MTK_WDT_H__*/
| rimistri/mediatek | mt6732/mediatek/platform/mt6752/lk/include/platform/mtk_wdt.h | C | gpl-2.0 | 5,400 |
/****************************************************************************
**
** This file is part of the Qt Extended Opensource Package.
**
** Copyright (C) 2009 Trolltech ASA.
**
** Contact: Qt Extended Information (info@qtextended.org)
**
** This file may be used under the terms of the GNU General Public License
** version 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
#ifndef BSCIDRMCONTENTPLUGIN_H
#define BSCIDRMCONTENTPLUGIN_H
#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 startConstraintUpdates();
void pauseConstraintUpdates();
void stopConstraintUpdates();
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 BSciDrmContentPlugin : public QDrmContentPlugin
{
Q_OBJECT
public:
BSciDrmContentPlugin( QObject *parent = 0 );
virtual ~BSciDrmContentPlugin();
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 *requestContentLicense( 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 transactionTrackingChanged();
private:
QValueSpaceItem m_transactionTracking;
};
#endif
| liuyanghejerry/qtextended | src/plugins/drmagent/bscidrmagent/bscidrmcontentplugin.h | C | gpl-2.0 | 4,944 |
/*
* (C) Copyright IBM Corporation 2004, 2005
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sub license,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* IBM,
* AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef _INDIRECT_VA_PRIVATE_
#define _INDIRECT_VA_PRIVATE_
/**
* \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, GL_TEXTURE_COORD_ARRAY 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 old_DrawArrays_possible;
};
/**
* 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, GL_TEXTURE_COORD_ARRAY 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 array_info_cache_valid is true.
*/
size_t enabled_client_array_count;
/**
* \name ARRAY_INFO cache.
*
* These fields track the state of the ARRAY_INFO cache. The
* \c array_info_cache_size is the size of the actual data stored in
* \c array_info_cache. \c array_info_cache_buffer_size is the size of
* the buffer. This will always be greater than or equal to
* \c array_info_cache_size.
*
* \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 array_info_cache_size or
* \c array_info_cache_buffer_size. \c array_info_cache_base stores a
* pointer to the true start of the buffer (i.e., what malloc returned).
*/
/*@{ */
size_t array_info_cache_size;
size_t array_info_cache_buffer_size;
void *array_info_cache;
void *array_info_cache_base;
/*@} */
/**
* 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 array_info_cache_valid;
/**
* 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 old_DrawArrays_possible;
/**
* Is it possible to use the new GL X.X / ARB_vertex_buffer_object
* 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 new_DrawArrays_possible;
/**
* Active texture unit set by \c glClientActiveTexture.
*
* \sa __glXGetActiveTextureUnit
*/
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 GL_MAX_TEXTURE_UNITS.
*
* \todo
* Investigate if this should be the value of \c GL_MAX_TEXTURE_COORDS
* instead (if GL 2.0 / ARB_fragment_shader / ARB_fragment_program /
* NV_fragment_program are supported).
*/
unsigned num_texture_units;
/**
* Number of generic vertex program attribs. If GL_ARB_vertex_program
* is not supported, this will be zero. Otherwise it will be the value
* queries by calling \c glGetProgramiv with \c GL_VERTEX_PROGRAM_ARB
* and \c GL_MAX_PROGRAM_ATTRIBS_ARB.
*/
unsigned num_vertex_program_attribs;
/**
* \n Methods for implementing various GL functions.
*
* These method pointers are only valid \c array_info_cache_valid is set.
* When each function starts, it much check \c array_info_cache_valid.
* If it is not set, it must call \c fill_array_info_cache and call
* the new method.
*
* \sa fill_array_info_cache
*
* \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 active_texture_unit_stack[__GL_CLIENT_ATTRIB_STACK_DEPTH];
unsigned stack_index;
};
#endif /* _INDIRECT_VA_PRIVATE_ */
| TurboVNC/turbovnc | unix/Xvnc/extras/Mesa/src/glx/indirect_vertex_array_priv.h | C | gpl-2.0 | 9,350 |
# test2
test2
| monilitocastro/test2 | deletethis.md | Markdown | gpl-2.0 | 14 |
/* Copyright (C) 2000-2006 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
/* 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;
}
| ottok/mariadb-galera-10.0 | storage/heap/_check.c | C | gpl-2.0 | 5,942 |
<?php
/**
* @package Joomla.Administrator
* @subpackage Template.hathor
*
* @copyright (C) 2010 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
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::_('JSEARCH_FILTER_LABEL'); ?></legend>
<div class="filter-select fltrt">
<label class="selectlabel" for="client_id">
<?php echo JText::_('COM_CACHE_SELECT_CLIENT'); ?>
</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', 'COM_CACHE_NUMBER_OF_FILES', '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>
| zero-24/joomla-cms | administrator/templates/hathor/html/com_cache/cache/default.php | PHP | gpl-2.0 | 3,019 |
/****************************************************************************
*
* Copyright (c) DiBcom SA. All rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
* PURPOSE.
*
****************************************************************************/
/**************************************************************************************************
* @file "DibBridgeDragonfly.c"
* @brief Dragonfly sprecific bridge functionality.
*
***************************************************************************************************/
#include "DibBridgeConfig.h" /* Must be first include of all SDK files - Defines compilation options */
#if (USE_DRAGONFLY == 1)
#include "DibBridgeTargetDebug.h"
#include "DibBridgeCommon.h"
#include "DibBridgeTarget.h"
#include "DibBridgeMailboxHandler.h"
#include "DibBridgeTestIf.h"
#include "DibBridge.h"
#include "DibBridgeDragonflyRegisters.h"
#include "DibBridgeDragonflyTest.h"
#include "DibBridgeDragonfly.h"
#include "DibBridgeDragonflyData.h"
#include "DibBridgeData.h"
#if (DRIVER_AND_BRIDGE_MERGED == 0)
#include "DibBridgeTargetModule.h"
#endif /*DRIVER_AND_BRIDGE_MERGED */
#if (DIB_CHECK_DATA == 1)
#include "DibBridgePayloadCheckers.h"
static void DibBridgeDragonflyClearCheckStats(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 DibBridgeDragonflyReceiveMsg(struct DibBridgeContext *pContext, uint32_t * Data);
static DIBDMA DibBridgeDragonflyMsgHandler(struct DibBridgeContext *pContext, struct MsgHeader * pHeader, uint32_t * RxData);
static uint32_t DibBridgeDragonflyFormatAddress(struct DibBridgeContext *pContext, uint32_t Addr, uint8_t ByteMode);
/**
* Retreive the number of free bytes in the HOST mailbox
*/
static __inline uint32_t IntBridgeDragonflyMailboxSpace(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 IntBridgeDragonflyMailboxBytes(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;
}
/****************************************************************************
* Setup chip memory controller
****************************************************************************/
static DIBSTATUS DibBridgeDragonflySetupDma(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 = DIBBRIDGE_BIT_MODE_32;
pDmaCtx->DmaSize = pDmaCtx->DmaLen;
/*-------------- Software management of alignement issues -----------------------*/
/* 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 "DibBridgeDragonflySetupDma 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 "DibBridgeDragonflySetupDma 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 "DibBridgeDragonflySetupDma Failed Idx%d Nb %d " CRA, j, NbBytes));
return Status;
}
}
}
}
}
else
{
/*** Force 8 bits transfers ***/
pDmaCtx->Mode = DIBBRIDGE_BIT_MODE_8;
pDmaCtx->DmaSize = pDmaCtx->DmaLen;
}
/** Compute formatted chip address */
pDmaCtx->FmtChipAddr = DibBridgeDragonflyFormatAddress(pContext, pDmaCtx->ChipAddr, pDmaCtx->Mode);
return Status;
}
/****************************************************************************
* Really start target dma. Swap buffer if really need.
* ############ WARNING: host buffer will be modified #######################
****************************************************************************/
DIBDMA DibBridgeDragonflyRequestDma(struct DibBridgeContext *pContext, struct DibBridgeDmaCtx * pDmaCtx)
{
DIBDMA rc;
rc = DibBridgeTargetRequestDma(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 DibBridgeDragonflySendMsg(struct DibBridgeContext *pContext, uint32_t * Data, uint32_t Size)
{
uint8_t Status = DIBSTATUS_ERROR;
int32_t MaxRetries = DIB_BRIDGE_MAX_MAILBOX_TRY;
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 = DibBridgeRead32Reg32(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 = IntBridgeDragonflyMailboxSpace(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 = DibBridgeWriteBuffer32(pContext, Wrptr, Data, len)) != DIBSTATUS_SUCCESS)
goto End;
if((Status = DibBridgeWriteBuffer32(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 = DibBridgeWriteBuffer32(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 == OUT_MSG_UDIBADAPTER_CFG)
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;
}
/****************************************************************************
* Clear HW interrupt at host interface level
****************************************************************************/
static __inline DIBSTATUS IntBridgeDragonflyClearHostIrq(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 "DibBridgeDragonflySendAck" CRA));
/* Message header */
MsgOut.Type = MSG_TYPE_MAC;
MsgOut.MsgId = OUT_MSG_CLEAR_HOST_IRQ;
MsgOut.MsgSize = GetWords(MsgHeaderBits, 32);
MsgOut.ChipId = MASTER_IDENT;
MsgHeaderPackInit(&MsgOut, &pContext->TxSerialBuf);
status = DibBridgeDragonflySendMsg(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;
}
/****************************************************************************
* There was an interrupt. Let's check the necessary action
****************************************************************************/
static DIBDMA DibBridgeDragonflyProcessIrq(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(IntBridgeDragonflyClearHostIrq(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 = DibBridgeDragonflyReceiveMsg(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 = DibBridgeDragonflyMsgHandler(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 DibBridgeDragonflyReceiveMsg(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 = DibBridgeRead32Reg32(pContext, pContext->DragonflyRegisters.HostMbxWrPtrReg, &wrptr) != DIBSTATUS_SUCCESS))
goto End;
DIB_ASSERT((wrptr & 3) == 0);
NbBytes = IntBridgeDragonflyMailboxBytes(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 = DibBridgeReadBuffer32(pContext, rdptr, Data, len)) != DIBSTATUS_SUCCESS)
goto End;
if((Status = DibBridgeReadBuffer32(pContext, pContext->DragonflyRegisters.HostMbxStart, Data + (len / 4), NbBytes - len)) != DIBSTATUS_SUCCESS)
goto End;
}
else
{
/* The mailbox can be read in one pass */
if((Status = DibBridgeReadBuffer32(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;
}
/****************************************************************************
* Parses and processes the most prioritary messages, and passes the others
* to the upper layer. Returns the DMA state: no DMA. done or pending.
****************************************************************************/
#if (mSDK==0)
static DIBDMA DibBridgeDragonflyDataMsgHandler(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));*/
/* DIB_DEBUG(RAWTS_LOG, (CRB CRB "" CRA CRA));
DIB_DEBUG(RAWTS_LOG, (CRB "---" CRA));*/
DmaStat = DibBridgeHighDataMsgHandlerCommon(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 DibBridgeDragonflyMsgHandler(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 DibBridgeDragonflyDataMsgHandler(pContext);
}
/* ------------------------------------------------------------------------------------ */
/*This is an Info message */
else if(pHeader->MsgId == IN_MSG_FRAME_INFO && pHeader->Type == MSG_TYPE_MAC)
{
return DibBridgeDragonflyInfoMsgHandler(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 */
DibBridgeDragonflyClearCheckStats(pContext, RxData);
#endif
}
else
{
/* flush buffers after item removal */
if(pHeader->MsgId == IN_MSG_ACK_FREE_ITEM && pHeader->Type == MSG_TYPE_MAC)
DibBridgeFreeUnusedMpeBuffer(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;
}
/****************************************************************************
* Checks message coming from the RISC and acts appropriately
****************************************************************************/
static DIBSTATUS DibBridgeDragonflySendAck(struct DibBridgeContext *pContext, struct DibBridgeDmaFlags *pFlags, uint8_t failed)
{
struct MsgAckData MsgOut;
DIB_DEBUG(MAILBOX_LOG, (CRB "" CRA));
DIB_DEBUG(MAILBOX_LOG, (CRB "DibBridgeDragonflySendAck" 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 DibBridgeDragonflySendMsg(pContext, pContext->TxBuffer, MsgOut.Head.MsgSize * 4);
}
/******************************************************************************
* Dma if finished, acknowledge the firmware and do the job
******************************************************************************/
#if (mSDK == 0)
static DIBSTATUS DibBridgeDragonflyProcessDma(struct DibBridgeContext *pContext, struct DibBridgeDmaCtx * pDmaCtx)
{
DIBSTATUS ret = DIBSTATUS_ERROR;
/* every Data message need to be acknowledged */
ret = DibBridgeDragonflySendAck(pContext, &pDmaCtx->DmaFlags, 0);
if(ret == DIBSTATUS_SUCCESS)
{
/* process dma independantly of the architecture */
ret = DibBridgeProcessDmaCommon(pContext, pDmaCtx);
}
return ret;
}
#endif
/******************************************************************************
* 32 bit address formating for all dragonfly based chipsets
******************************************************************************/
static uint32_t DibBridgeDragonflyFormatAddress(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;
}
}
/******************************************************************************
* 16 bit access to non demod apb address is not working on voyager chipset
******************************************************************************/
static DIBSTATUS IntBridgeVoyagerWrite16Even(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 = DibBridgeDragonflyFormatAddress(pContext, Address + i, DIBBRIDGE_BIT_MODE_32);
wa[0] = b[i];
wa[1] = b[i + 1];
if((ret = DibBridgeTargetWrite(pContext, FormattedAddr, DIBBRIDGE_BIT_MODE_32, 4, wa) != DIBSTATUS_SUCCESS))
break;
}
return ret;
}
static DIBSTATUS IntBridgeVoyagerRead16Even(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 = DibBridgeDragonflyFormatAddress(pContext, Address + i, DIBBRIDGE_BIT_MODE_32);
if((ret = DibBridgeTargetRead(pContext, FormattedAddress, DIBBRIDGE_BIT_MODE_32, 4, wa) != DIBSTATUS_SUCCESS))
break;
b[i] = wa[0];
b[i+1] = wa[1];
}
return ret;
}
static DIBSTATUS DibBridgeVoyager1PreFormat(struct DibBridgeContext *pContext, uint8_t ByteMode, uint32_t * Addr, uint8_t IsWriteAccess, uint8_t * Buf, uint32_t Cnt)
{
if(DIB29000_APB_EVEN_ADDR(*Addr, ByteMode))
{
if(IsWriteAccess)
return IntBridgeVoyagerWrite16Even(pContext, *Addr, Buf, Cnt);
else
return IntBridgeVoyagerRead16Even(pContext, *Addr, Buf, Cnt);
}
/* address formating */
*Addr = DibBridgeDragonflyFormatAddress(pContext, *Addr, ByteMode);
return DIBSTATUS_CONTINUE;
}
static DIBSTATUS DibBridgeVoyager1PostFormat(struct DibBridgeContext *pContext, uint8_t ByteMode, uint32_t * Addr, uint8_t IsWriteAccess, uint8_t * Buf, uint32_t Cnt)
{
return DIBSTATUS_SUCCESS;
}
static DIBSTATUS DibBridgeNautilus1PreFormat(struct DibBridgeContext *pContext, uint8_t ByteMode, uint32_t * Addr, uint8_t IsWriteAccess, uint8_t * Buf, uint32_t Cnt)
{
/* address formating */
*Addr = DibBridgeDragonflyFormatAddress(pContext, *Addr, ByteMode);
return DIBSTATUS_CONTINUE;
}
static DIBSTATUS DibBridgeNautilus1PostFormat(struct DibBridgeContext *pContext, uint8_t ByteMode, uint32_t * Addr, uint8_t IsWriteAccess, uint8_t * Buf, uint32_t Cnt)
{
return DIBSTATUS_SUCCESS;
}
static uint32_t DibBridgeDragonflyIncrementFormattedAddress(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;
}
/******************************************************************************
* Assemble the slice from MpeBufCor to SliceBuf, and set SkipR and SKipC if not already set
******************************************************************************/
/*
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);
}
*/
/******************************************************************************
* return the bus architecture (32, 16 or 8 bits)
******************************************************************************/
static uint8_t DibBridgeDragonflyGetArchi(struct DibBridgeContext *pContext)
{
return DIBBRIDGE_BIT_MODE_32;
}
/******************************************************************************
* clean checker statistics
******************************************************************************/
#if (DIB_CHECK_DATA == 1)
static void DibBridgeDragonflyClearCheckStats(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 DIB_CHECK_RAWTS_DATA == 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 DibBridgeDragonflyForwardCheckStats(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 DIB_CHECK_RAWTS_DATA == 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.DiscontinuitiesCount;
Msg.ErrCnt = pContext->FilterInfo[Filter].CheckRawTs.CorruptedPacketsCount;
}
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 "DibBridgeDragonflyForwardCheckStats : 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 DibBridgeDragonflySetService(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 DibBridgeDragonflySignalBufFail(struct DibBridgeContext *pContext, struct DibBridgeDmaFlags * pFlags, uint8_t Flush)
{
return DibBridgeDragonflySendAck(pContext, pFlags, (1+Flush));
}
#if (DIB_BRIDGE_HBM_PROFILER == 1)
/**
* Send profiler info to the SPARC
*/
static DIBSTATUS DibBridgeDragonflyHbmProfiler(struct DibBridgeContext *pContext, uint8_t idx, uint8_t page, uint8_t LastFrag)
{
return DIBSTATUS_ERROR;
}
#endif
/******************************************************************************
* Configure or reconfigure SDIO endianess
******************************************************************************/
void DibBridgeDragonflyConfigureSdioEndianness(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);
}
}
/******************************************************************************
* Init nautilus software specific
******************************************************************************/
DIBSTATUS DibBridgeDragonflyChipsetInit(struct DibBridgeContext *pContext)
{
pContext->RxCnt = 0;
pContext->RxOffset = 0;
if((pContext->HostBuffer = (uint32_t *)DibBridgeTargetAllocBuf(pContext->DragonflyRegisters.HostMbxSize)) == 0)
{
return DIBSTATUS_ERROR;
}
DibBridgeDragonflyConfigureSdioEndianness(pContext);
/*
printf("DibBridgeDragonflyChipsetInit:\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;
}
/******************************************************************************
* Deinit dragonfly and voyager software specific
******************************************************************************/
void DibBridgeDragonflyChipsetDeinit(struct DibBridgeContext *pContext)
{
DibBridgeTargetFreeBuf((uint8_t *)pContext->HostBuffer, pContext->DragonflyRegisters.HostMbxSize);
}
/******************************************************************************
* Specific output message formating for dragonfly
******************************************************************************/
void DibBridgeDragonflyRegisterIf(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 = DibBridgeVoyager1PreFormat;
pContext->BridgeChipOps.PostFormat = DibBridgeVoyager1PostFormat;
#if ((DIB_BRIDGE_TESTIF_PREINIT == 1) || (DIB_BRIDGE_TESTIF_POSTINIT == 1))
pContext->BridgeChipOps.TestRegister = IntBridgeVoyager1TestRegister;
pContext->BridgeChipOps.TestExternalRam = IntBridgeVoyager1TestExternalRam;
#endif
break;
case DIB_NAUTILUS:
pContext->BridgeChipOps.PreFormat = DibBridgeNautilus1PreFormat;
pContext->BridgeChipOps.PostFormat = DibBridgeNautilus1PostFormat;
#if ((DIB_BRIDGE_TESTIF_PREINIT == 1) || (DIB_BRIDGE_TESTIF_POSTINIT == 1))
pContext->BridgeChipOps.TestRegister = IntBridgeNautilus1TestRegister;
pContext->BridgeChipOps.TestExternalRam = IntBridgeNautilus1TestExternalRam;
#endif
break;
default:
break;
}
pContext->BridgeChipOps.SendMsg = DibBridgeDragonflySendMsg;
pContext->BridgeChipOps.AssembleSlice = DibBridgeDragonflyAssembleSlice;
pContext->BridgeChipOps.SendAck = DibBridgeDragonflySendAck;
pContext->BridgeChipOps.ProcessIrq = DibBridgeDragonflyProcessIrq;
#if (mSDK == 0)
pContext->BridgeChipOps.ProcessDma = DibBridgeDragonflyProcessDma;
#else
pContext->BridgeChipOps.ProcessDma = NULL;
#endif
pContext->BridgeChipOps.SetupDma = DibBridgeDragonflySetupDma;
pContext->BridgeChipOps.RequestDma = DibBridgeDragonflyRequestDma;
pContext->BridgeChipOps.GetArch = DibBridgeDragonflyGetArchi;
pContext->BridgeChipOps.IncrementFormattedAddress = DibBridgeDragonflyIncrementFormattedAddress;
pContext->BridgeChipOps.SignalBufFail = DibBridgeDragonflySignalBufFail;
pContext->BridgeChipOps.ChipsetInit = DibBridgeDragonflyChipsetInit;
pContext->BridgeChipOps.ChipsetDeinit = DibBridgeDragonflyChipsetDeinit;
#if (DIB_BRIDGE_HBM_PROFILER == 1)
pContext->BridgeChipOps.HbmProfiler = DibBridgeDragonflyHbmProfiler;
#endif
#if (DIB_CHECK_DATA == 1)
pContext->BridgeChipOps.ClearCheckStats = DibBridgeDragonflyClearCheckStats;
pContext->BridgeChipOps.ForwardCheckStats = DibBridgeDragonflyForwardCheckStats;
#endif
#if ((DIB_BRIDGE_TESTIF_PREINIT == 1) || (DIB_BRIDGE_TESTIF_POSTINIT == 1))
pContext->BridgeChipOps.TestBasicRead = IntBridgeDragonflyTestBasicRead;
pContext->BridgeChipOps.TestInternalRam = IntBridgeDragonflyTestInternalRam;
pContext->BridgeChipOps.GetRamAddr = DibBridgeDragonflyGetRamAddr;
#endif
pContext->BridgeChipOps.SetService = DibBridgeDragonflySetService;
}
#endif /* USE_DRAGONFLY */
| fefifofum/android_kernel_bq_maxwell2plus_3.0.8 | drivers/media/dvb/rkdtv/DIBCom1009XH/Bridge/Common/Dragonfly/DibBridgeDragonfly.c | C | gpl-2.0 | 39,664 |
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) {
// http://kevin.vanzonneveld.net
// + original by: Cagri Ekin
// + improved by: Michael White (http://getsprink.com)
// + tweaked by: Jack
// + bugfixed by: Onno Marsman
// + reimplemented by: stag019
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: stag019
// + input by: Dreamer
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
// + input by: Zaide (http://zaidesthings.com/)
// + input by: David Pesta (http://davidpesta.com/)
// + input by: jeicquest
// + improved by: Brett Zamir (http://brett-zamir.me)
// % note 1: When no argument is specified, will put variables in global scope.
// % note 1: When a particular argument has been passed, and the returned value is different parse_str of PHP. For example, a=b=c&d====c
// * 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');
// * results 3: JSON.stringify(abc) === '{"3":"a","a":{"b":{"c":"def"}},"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) {
// http://kevin.vanzonneveld.net
// + original by: Thiago Mata (http://thiagomata.blog.com)
// + revised by: Jon Hohle
// + improved by: Brett Zamir (http://brett-zamir.me)
// + improved by: Diplom@t (http://difane.com/)
// + improved by: Brett Zamir (http://brett-zamir.me)
// * example 1: call_user_func_array('isNaN', ['a']);
// * returns 1: true
// * example 2: call_user_func_array('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);
}
| nikakoss/arsenal-media.net | wp-content/plugins/google-maps-ready/js/common.js | JavaScript | gpl-2.0 | 12,013 |
/*
mxb - v4l2 driver for the Multimedia eXtension Board
Copyright (C) 1998-2003 Michael Hunold <michael@mihu.de>
Visit http://www.mihu.de/linux/saa7146/mxb/
for further details about this card.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#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 MXB_BOARD_CAN_DO_VBI(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", V4L2_INPUT_TYPE_TUNER, 1, 0, V4L2_STD_PAL_BG|V4L2_STD_NTSC_M, 0 },
{ AUX1, "AUX1", V4L2_INPUT_TYPE_CAMERA, 2, 0, V4L2_STD_PAL_BG|V4L2_STD_NTSC_M, 0 },
{ AUX3, "AUX3 Composite", V4L2_INPUT_TYPE_CAMERA, 4, 0, V4L2_STD_PAL_BG|V4L2_STD_NTSC_M, 0 },
{ AUX3_YC, "AUX3 S-Video", V4L2_INPUT_TYPE_CAMERA, 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;
} input_port_selection[MXB_INPUTS] = {
{ SAA7146_HPS_SOURCE_PORT_A, SAA7146_HPS_SYNC_PORT_A },
{ SAA7146_HPS_SOURCE_PORT_A, SAA7146_HPS_SYNC_PORT_A },
{ SAA7146_HPS_SOURCE_PORT_A, SAA7146_HPS_SYNC_PORT_A },
{ SAA7146_HPS_SOURCE_PORT_A, SAA7146_HPS_SYNC_PORT_A },
};
/* 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, V4L2_CTRL_TYPE_BOOLEAN, "Mute", 0, 1, 1, 0, 0 },
};
static struct saa7146_extension_ioctls 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",
};
saa7146_i2c_adapter_prepare(dev, &mxb->i2c_adapter, SAA7146_I2C_BUS_BIT_RATE_480);
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,DECODER_SET_VBI_BYPASS, &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 = V4L2_TUNER_ANALOG_TV;
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 = V4L2_TUNER_MODE_STEREO;
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 */
saa7146_set_hps_source_and_sync(dev, input_port_selection[mxb->cur_input].hps_source, input_port_selection[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 saa7146_pci_extension_data *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 != saa7146_register_device(&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 != MXB_BOARD_CAN_DO_VBI(dev)) {
if( 0 != saa7146_register_device(&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);
saa7146_unregister_device(&mxb->video_dev,dev);
if( 0 != MXB_BOARD_CAN_DO_VBI(dev)) {
saa7146_unregister_device(&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);
*/
/* fixme: check if streaming capture
if ( 0 != dev->streaming ) {
DEB_D(("VIDIOC_S_INPUT illegal while streaming.\n"));
return -EPERM;
}
*/
mxb->cur_input = input;
saa7146_set_hps_source_and_sync(dev, input_port_selection[input].hps_source, input_port_selection[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 #1\n");
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 #3\n");
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 #1.\n");
}
/* 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 = V4L2_TUNER_ANALOG_TV;
t->capability = V4L2_TUNER_CAP_NORM | V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_LANG1 | V4L2_TUNER_CAP_LANG2 | 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: V4L2_TUNER_MODE_MONO.\n"));
break;
}
case TDA9840_DUAL_DETECT: {
t->rxsubchans = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2;
DEB_D(("VIDIOC_G_TUNER: V4L2_TUNER_MODE_LANG1.\n"));
break;
}
case TDA9840_STEREO_DETECT: {
t->rxsubchans = V4L2_TUNER_SUB_STEREO | V4L2_TUNER_SUB_MONO;
DEB_D(("VIDIOC_G_TUNER: V4L2_TUNER_MODE_STEREO.\n"));
break;
}
default: { /* TDA9840_INCORRECT_DETECT */
t->rxsubchans = V4L2_TUNER_MODE_MONO;
DEB_D(("VIDIOC_G_TUNER: TDA9840_INCORRECT_DETECT => V4L2_TUNER_MODE_MONO\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 V4L2_TUNER_MODE_STEREO: {
mxb->cur_mode = V4L2_TUNER_MODE_STEREO;
byte = TDA9840_SET_STEREO;
DEB_D(("VIDIOC_S_TUNER: V4L2_TUNER_MODE_STEREO\n"));
break;
}
case V4L2_TUNER_MODE_LANG1: {
mxb->cur_mode = V4L2_TUNER_MODE_LANG1;
byte = TDA9840_SET_LANG1;
DEB_D(("VIDIOC_S_TUNER: V4L2_TUNER_MODE_LANG1\n"));
break;
}
case V4L2_TUNER_MODE_LANG2: {
mxb->cur_mode = V4L2_TUNER_MODE_LANG2;
byte = TDA9840_SET_LANG2;
DEB_D(("VIDIOC_S_TUNER: V4L2_TUNER_MODE_LANG2\n"));
break;
}
default: { /* case V4L2_TUNER_MODE_MONO: {*/
mxb->cur_mode = V4L2_TUNER_MODE_MONO;
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 (V4L2_TUNER_ANALOG_TV != 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 saa7146_pci_extension_data mxb = {
.ext_priv = "Multimedia eXtension Board",
.ext = &extension,
};
static struct pci_device_id pci_tbl[] = {
{
.vendor = PCI_VENDOR_ID_PHILIPS,
.device = PCI_DEVICE_ID_PHILIPS_SAA7146,
.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 | V4L2_CAP_VBI_CAPTURE,
.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 != saa7146_register_extension(&extension)) {
DEB_S(("failed to register extension.\n"));
return -ENODEV;
}
return 0;
}
static void __exit mxb_cleanup_module(void)
{
saa7146_unregister_extension(&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");
| ipwndev/DSLinux-Mirror | linux-2.6.x/drivers/media/video/mxb.c | C | gpl-2.0 | 30,749 |
<?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()->setConfigurationValue('yamlform_id', 'contact');
$block->save();
$this->drupalGet('<front>');
$this->assertRaw('yamlform-submission-contact-form');
// Check contact form with default data.
$block->getPlugin()->setConfigurationValue('default_data', "name: 'John Smith'");
$block->save();
$this->drupalGet('<front>');
$this->assertRaw('yamlform-submission-contact-form');
$this->assertFieldByName('name', 'John Smith');
// Check confirmation inline form.
$block->getPlugin()->setConfigurationValue('yamlform_id', 'test_confirmation_inline');
$block->save();
$this->drupalPostForm('<front>', [], t('Submit'));
$this->assertRaw('This is a custom inline confirmation message.');
// Check confirmation message form.
$block->getPlugin()->setConfigurationValue('yamlform_id', 'test_confirmation_message');
$block->save();
$this->drupalPostForm('<front>', [], t('Submit'));
$this->assertRaw('This is a <b>custom</b> confirmation message.');
}
}
| dbethala/longwood-volunteers | modules/yamlform/src/Tests/YamlFormBlockTest.php | PHP | gpl-2.0 | 1,363 |
/*
* FCKeditor - The text editor for internet
* Copyright (C) 2003-2004 Frederico Caldeira Knabben
*
* Licensed under the terms of the GNU Lesser General Public License:
* http://www.opensource.org/licenses/lgpl-license.php
*
* For further information visit:
* http://www.fckeditor.net/
*
* File Name: fck_universalkey.css
* CSS styles for the Universal Keyboard.
*
* Version: 2.0 RC3
* Modified: 2005-02-10 18:06:16
*
* File Authors:
* Michel Staelens (michel.staelens@wanadoo.fr)
* Bernadette Cierzniak
* Abdul-Aziz Al-Oraij (top7up@hotmail.com)
*/
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;
}
| jonathonfigueroa/calendarinfusion_3.0b1 | public/scripts/fckeditor/editor/dialog/fck_universalkey/fck_universalkey.css | CSS | gpl-2.0 | 1,040 |
<?php
namespace Drupal\KernelTests\Core\Test;
use Drupal\FunctionalTests\BrowserMissingDependentModuleMethodTest;
use Drupal\FunctionalTests\BrowserMissingDependentModuleTest;
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 ::checkModuleRequirements
*/
public function testMethodRequiresModule() {
require __DIR__ . '/../../../../fixtures/BrowserMissingDependentModuleMethodTest.php';
$stub_test = new BrowserMissingDependentModuleMethodTest();
// We have to setName() to the method name we're concerned with.
$stub_test->setName('testRequiresModule');
// We cannot use $this->setExpectedException() because PHPUnit would skip
// the test before comparing the exception type.
try {
$stub_test->publicCheckRequirements();
$this->fail('Missing required module throws skipped test exception.');
}
catch (SkippedTestError $e) {
$this->assertEquals('Required modules: module_does_not_exist', $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 ::checkModuleRequirements
*/
public function testRequiresModule() {
require __DIR__ . '/../../../../fixtures/BrowserMissingDependentModuleTest.php';
$stub_test = new BrowserMissingDependentModuleTest();
// We have to setName() to the method name we're concerned with.
$stub_test->setName('testRequiresModule');
// We cannot use $this->setExpectedException() because PHPUnit would skip
// the test before comparing the exception type.
try {
$stub_test->publicCheckRequirements();
$this->fail('Missing required module throws skipped test exception.');
}
catch (SkippedTestError $e) {
$this->assertEquals('Required modules: module_does_not_exist', $e->getMessage());
}
}
}
| tobiasbuhrer/tobiasb | web/core/tests/Drupal/KernelTests/Core/Test/BrowserTestBaseTest.php | PHP | gpl-2.0 | 2,447 |
<?php
/**
* Joomla! Content Management System
*
* @copyright (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
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();
}
| zero-24/joomla-cms | libraries/src/Http/TransportInterface.php | PHP | gpl-2.0 | 1,521 |
/* Target-dependent code for GNU/Linux, architecture independent.
Copyright (C) 2009-2015 Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef LINUX_TDEP_H
#define LINUX_TDEP_H
#include "bfd.h"
struct regcache;
typedef char *(*linux_collect_thread_registers_ftype) (const struct regcache *,
ptid_t,
bfd *, char *, int *,
enum gdb_signal);
struct type *linux_get_siginfo_type (struct gdbarch *);
extern enum gdb_signal linux_gdb_signal_from_target (struct gdbarch *gdbarch,
int signal);
extern int linux_gdb_signal_to_target (struct gdbarch *gdbarch,
enum gdb_signal signal);
/* Default GNU/Linux implementation of `displaced_step_location', as
defined in gdbarch.h. Determines the entry point from AT_ENTRY in
the target auxiliary vector. */
extern CORE_ADDR linux_displaced_step_location (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 */
| npe9/binutils-gdb | gdb/linux-tdep.h | C | gpl-2.0 | 1,705 |
/**
* @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).
*/
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#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 LWIP_CHECKSUM_ON_COPY
#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, PBUF_POOL_BUFSIZE_ALIGNED can be used here. */
#define PBUF_POOL_BUFSIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(PBUF_POOL_BUFSIZE)
#if !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ
#define PBUF_POOL_IS_EMPTY()
#else /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ */
#if !NO_SYS
#ifndef PBUF_POOL_FREE_OOSEQ_QUEUE_CALL
#include "lwip/tcpip.h"
#define PBUF_POOL_FREE_OOSEQ_QUEUE_CALL() do { \
if(tcpip_callback_with_block(pbuf_free_ooseq_callback, NULL, 0) != ERR_OK) { \
SYS_ARCH_PROTECT(old_level); \
pbuf_free_ooseq_pending = 0; \
SYS_ARCH_UNPROTECT(old_level); \
} } while(0)
#endif /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
#endif /* !NO_SYS */
volatile u8_t pbuf_free_ooseq_pending;
#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;
SYS_ARCH_DECL_PROTECT(old_level);
SYS_ARCH_PROTECT(old_level);
pbuf_free_ooseq_pending = 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
pbuf_free_ooseq_callback(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 PBUF_POOL_FREE_OOSEQ_QUEUE_CALL
SYS_ARCH_DECL_PROTECT(old_level);
SYS_ARCH_PROTECT(old_level);
pbuf_free_ooseq_pending = 1;
SYS_ARCH_UNPROTECT(old_level);
#else /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
u8_t queued;
SYS_ARCH_DECL_PROTECT(old_level);
SYS_ARCH_PROTECT(old_level);
queued = pbuf_free_ooseq_pending;
pbuf_free_ooseq_pending = 1;
SYS_ARCH_UNPROTECT(old_level);
if(!queued) {
/* queue a call to pbuf_free_ooseq if not already queued */
PBUF_POOL_FREE_OOSEQ_QUEUE_CALL();
}
#endif /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
}
#endif /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ */
/**
* 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, PBUF_POOL_BUFSIZE_ALIGNED - 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 + PBUF_POOL_BUFSIZE_ALIGNED));
LWIP_ASSERT("PBUF_POOL_BUFSIZE must be bigger than MEM_ALIGNMENT",
(PBUF_POOL_BUFSIZE_ALIGNED - 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, PBUF_POOL_BUFSIZE_ALIGNED);
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 + PBUF_POOL_BUFSIZE_ALIGNED));
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 | LWIP_DBG_LEVEL_SERIOUS,
("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 LWIP_SUPPORT_CUSTOM_PBUF
/** 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 | LWIP_DBG_LEVEL_WARNING, ("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 /* LWIP_SUPPORT_CUSTOM_PBUF */
/**
* 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 header_size_increment 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 header_size_increment)
{
u16_t type;
void *payload;
u16_t increment_magnitude;
LWIP_ASSERT("p != NULL", p != NULL);
if ((header_size_increment == 0) || (p == NULL)) {
return 0;
}
if (header_size_increment < 0){
increment_magnitude = -header_size_increment;
/* 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 = header_size_increment;
#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 - header_size_increment;
/* boundary check fails? */
if ((u8_t *)p->payload < (u8_t *)p + SIZEOF_STRUCT_PBUF) {
LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
("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 ((header_size_increment < 0) && (increment_magnitude <= p->len)) {
/* increase payload pointer */
p->payload = (u8_t *)p->payload - header_size_increment;
} 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 += header_size_increment;
p->tot_len += header_size_increment;
LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_header: old %p new %p (%"S16_F")\n",
(void *)payload, (void *)p->payload, header_size_increment));
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 | LWIP_DBG_LEVEL_SERIOUS,
("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;
SYS_ARCH_DECL_PROTECT(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 LWIP_SUPPORT_CUSTOM_PBUF
/* is this a custom pbuf? */
if ((p->flags & PBUF_FLAG_IS_CUSTOM) != 0) {
struct pbuf_custom *pc = (struct pbuf_custom*)p;
LWIP_ASSERT("pc->custom_free_function != NULL", pc->custom_free_function != NULL);
pc->custom_free_function(p);
} else
#endif /* LWIP_SUPPORT_CUSTOM_PBUF */
{
/* 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)
{
SYS_ARCH_DECL_PROTECT(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 LWIP_CHECKSUM_ON_COPY
/**
* 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 /* LWIP_CHECKSUM_ON_COPY */
/** 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);
}
| jnouyang/kitten | net/pbuf.c | C | gpl-2.0 | 39,009 |
/*
*/
/*
* Copyright (C) 2000 - 2011, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#ifndef __ACOUTPUT_H__
#define __ACOUTPUT_H__
/*
*/
/* */
#define ACPI_UTILITIES 0x00000001
#define ACPI_HARDWARE 0x00000002
#define ACPI_EVENTS 0x00000004
#define ACPI_TABLES 0x00000008
#define ACPI_NAMESPACE 0x00000010
#define ACPI_PARSER 0x00000020
#define ACPI_DISPATCHER 0x00000040
#define ACPI_EXECUTER 0x00000080
#define ACPI_RESOURCES 0x00000100
#define ACPI_CA_DEBUGGER 0x00000200
#define ACPI_OS_SERVICES 0x00000400
#define ACPI_CA_DISASSEMBLER 0x00000800
/* */
#define ACPI_COMPILER 0x00001000
#define ACPI_TOOLS 0x00002000
#define ACPI_EXAMPLE 0x00004000
#define ACPI_DRIVER 0x00008000
#define DT_COMPILER 0x00010000
#define ACPI_ALL_COMPONENTS 0x0001FFFF
#define ACPI_COMPONENT_DEFAULT (ACPI_ALL_COMPONENTS)
/* */
#define ACPI_ALL_DRIVERS 0xFFFF0000
/*
*/
#define ACPI_LV_INIT 0x00000001
#define ACPI_LV_DEBUG_OBJECT 0x00000002
#define ACPI_LV_INFO 0x00000004
#define ACPI_LV_REPAIR 0x00000008
#define ACPI_LV_ALL_EXCEPTIONS 0x0000000F
/* */
#define ACPI_LV_INIT_NAMES 0x00000020
#define ACPI_LV_PARSE 0x00000040
#define ACPI_LV_LOAD 0x00000080
#define ACPI_LV_DISPATCH 0x00000100
#define ACPI_LV_EXEC 0x00000200
#define ACPI_LV_NAMES 0x00000400
#define ACPI_LV_OPREGION 0x00000800
#define ACPI_LV_BFIELD 0x00001000
#define ACPI_LV_TABLES 0x00002000
#define ACPI_LV_VALUES 0x00004000
#define ACPI_LV_OBJECTS 0x00008000
#define ACPI_LV_RESOURCES 0x00010000
#define ACPI_LV_USER_REQUESTS 0x00020000
#define ACPI_LV_PACKAGE 0x00040000
#define ACPI_LV_VERBOSITY1 0x0007FF40 | ACPI_LV_ALL_EXCEPTIONS
/* */
#define ACPI_LV_ALLOCATIONS 0x00100000
#define ACPI_LV_FUNCTIONS 0x00200000
#define ACPI_LV_OPTIMIZATIONS 0x00400000
#define ACPI_LV_VERBOSITY2 0x00700000 | ACPI_LV_VERBOSITY1
#define ACPI_LV_ALL ACPI_LV_VERBOSITY2
/* */
#define ACPI_LV_MUTEX 0x01000000
#define ACPI_LV_THREADS 0x02000000
#define ACPI_LV_IO 0x04000000
#define ACPI_LV_INTERRUPTS 0x08000000
#define ACPI_LV_VERBOSITY3 0x0F000000 | ACPI_LV_VERBOSITY2
/* */
#define ACPI_LV_AML_DISASSEMBLE 0x10000000
#define ACPI_LV_VERBOSE_INFO 0x20000000
#define ACPI_LV_FULL_TABLES 0x40000000
#define ACPI_LV_EVENTS 0x80000000
#define ACPI_LV_VERBOSE 0xF0000000
/*
*/
#define ACPI_DEBUG_LEVEL(dl) (u32) dl,ACPI_DEBUG_PARAMETERS
/*
*/
#define ACPI_DB_INIT ACPI_DEBUG_LEVEL (ACPI_LV_INIT)
#define ACPI_DB_DEBUG_OBJECT ACPI_DEBUG_LEVEL (ACPI_LV_DEBUG_OBJECT)
#define ACPI_DB_INFO ACPI_DEBUG_LEVEL (ACPI_LV_INFO)
#define ACPI_DB_REPAIR ACPI_DEBUG_LEVEL (ACPI_LV_REPAIR)
#define ACPI_DB_ALL_EXCEPTIONS ACPI_DEBUG_LEVEL (ACPI_LV_ALL_EXCEPTIONS)
/* */
#define ACPI_DB_INIT_NAMES ACPI_DEBUG_LEVEL (ACPI_LV_INIT_NAMES)
#define ACPI_DB_THREADS ACPI_DEBUG_LEVEL (ACPI_LV_THREADS)
#define ACPI_DB_PARSE ACPI_DEBUG_LEVEL (ACPI_LV_PARSE)
#define ACPI_DB_DISPATCH ACPI_DEBUG_LEVEL (ACPI_LV_DISPATCH)
#define ACPI_DB_LOAD ACPI_DEBUG_LEVEL (ACPI_LV_LOAD)
#define ACPI_DB_EXEC ACPI_DEBUG_LEVEL (ACPI_LV_EXEC)
#define ACPI_DB_NAMES ACPI_DEBUG_LEVEL (ACPI_LV_NAMES)
#define ACPI_DB_OPREGION ACPI_DEBUG_LEVEL (ACPI_LV_OPREGION)
#define ACPI_DB_BFIELD ACPI_DEBUG_LEVEL (ACPI_LV_BFIELD)
#define ACPI_DB_TABLES ACPI_DEBUG_LEVEL (ACPI_LV_TABLES)
#define ACPI_DB_FUNCTIONS ACPI_DEBUG_LEVEL (ACPI_LV_FUNCTIONS)
#define ACPI_DB_OPTIMIZATIONS ACPI_DEBUG_LEVEL (ACPI_LV_OPTIMIZATIONS)
#define ACPI_DB_VALUES ACPI_DEBUG_LEVEL (ACPI_LV_VALUES)
#define ACPI_DB_OBJECTS ACPI_DEBUG_LEVEL (ACPI_LV_OBJECTS)
#define ACPI_DB_ALLOCATIONS ACPI_DEBUG_LEVEL (ACPI_LV_ALLOCATIONS)
#define ACPI_DB_RESOURCES ACPI_DEBUG_LEVEL (ACPI_LV_RESOURCES)
#define ACPI_DB_IO ACPI_DEBUG_LEVEL (ACPI_LV_IO)
#define ACPI_DB_INTERRUPTS ACPI_DEBUG_LEVEL (ACPI_LV_INTERRUPTS)
#define ACPI_DB_USER_REQUESTS ACPI_DEBUG_LEVEL (ACPI_LV_USER_REQUESTS)
#define ACPI_DB_PACKAGE ACPI_DEBUG_LEVEL (ACPI_LV_PACKAGE)
#define ACPI_DB_MUTEX ACPI_DEBUG_LEVEL (ACPI_LV_MUTEX)
#define ACPI_DB_EVENTS ACPI_DEBUG_LEVEL (ACPI_LV_EVENTS)
#define ACPI_DB_ALL ACPI_DEBUG_LEVEL (ACPI_LV_ALL)
/* */
#define ACPI_DEBUG_DEFAULT (ACPI_LV_INFO | ACPI_LV_REPAIR)
#define ACPI_NORMAL_DEFAULT (ACPI_LV_INIT | ACPI_LV_DEBUG_OBJECT | ACPI_LV_REPAIR)
#define ACPI_DEBUG_ALL (ACPI_LV_AML_DISASSEMBLE | ACPI_LV_ALL_EXCEPTIONS | ACPI_LV_ALL)
#if defined (ACPI_DEBUG_OUTPUT) || !defined (ACPI_NO_ERROR_MESSAGES)
/*
*/
#define ACPI_MODULE_NAME(name) static const char ACPI_UNUSED_VAR _acpi_module_name[] = name;
#else
/*
*/
#define ACPI_MODULE_NAME(name)
#define _acpi_module_name ""
#endif
/*
*/
#ifndef ACPI_NO_ERROR_MESSAGES
#define AE_INFO _acpi_module_name, __LINE__
/*
*/
#define ACPI_INFO(plist) acpi_info plist
#define ACPI_WARNING(plist) acpi_warning plist
#define ACPI_EXCEPTION(plist) acpi_exception plist
#define ACPI_ERROR(plist) acpi_error plist
#define ACPI_DEBUG_OBJECT(obj,l,i) acpi_ex_do_debug_object(obj,l,i)
#else
/* */
#define ACPI_INFO(plist)
#define ACPI_WARNING(plist)
#define ACPI_EXCEPTION(plist)
#define ACPI_ERROR(plist)
#define ACPI_DEBUG_OBJECT(obj,l,i)
#endif /* */
/*
*/
#ifdef ACPI_DEBUG_OUTPUT
/*
*/
#ifndef ACPI_GET_FUNCTION_NAME
#define ACPI_GET_FUNCTION_NAME _acpi_function_name
/*
*/
#define ACPI_FUNCTION_NAME(name) static const char _acpi_function_name[] = #name;
#else
/* */
#define ACPI_FUNCTION_NAME(name)
#endif /* */
/*
*/
#define ACPI_DEBUG_PARAMETERS __LINE__, ACPI_GET_FUNCTION_NAME, _acpi_module_name, _COMPONENT
/*
*/
#define ACPI_DEBUG_PRINT(plist) acpi_debug_print plist
#define ACPI_DEBUG_PRINT_RAW(plist) acpi_debug_print_raw plist
#else
/*
*/
#define ACPI_FUNCTION_NAME(a)
#define ACPI_DEBUG_PRINT(pl)
#define ACPI_DEBUG_PRINT_RAW(pl)
#endif /* */
#endif /* */
| holyangel/LGE_G3 | include/acpi/acoutput.h | C | gpl-2.0 | 11,379 |
/*
LUFA Library
Copyright (C) Dean Camera, 2014.
dean [at] fourwalledcubicle [dot] com
www.lufa-lib.org
*/
/*
Copyright 2014 Dean Camera (dean [at] fourwalledcubicle [dot] com)
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of the author not be used in
advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
The author disclaims all warranties with regard to this
software, including all implied warranties of merchantability
and fitness. In no event shall the author be liable for any
special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether
in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of
this software.
*/
/** \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 INCLUDE_FROM_DATAFLASHMANAGER_C
#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 DataflashManager_WriteBlocks(const uint32_t BlockAddress,
uint16_t TotalBlocks)
{
uint16_t CurrDFPage = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
uint16_t CurrDFPageByte = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
bool UsingSecondBuffer = false;
/* Select the correct starting Dataflash IC for the block requested */
Dataflash_SelectChipFromPage(CurrDFPage);
#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
/* Copy selected dataflash's current page contents to the Dataflash buffer */
Dataflash_SendByte(DF_CMD_MAINMEMTOBUFF1);
Dataflash_SendAddressBytes(CurrDFPage, 0);
Dataflash_WaitWhileBusy();
#endif
/* Send the Dataflash buffer write command */
Dataflash_SendByte(DF_CMD_BUFF1WRITE);
Dataflash_SendAddressBytes(0, CurrDFPageByte);
/* Wait until endpoint is ready before continuing */
if (Endpoint_WaitUntilReady())
return;
while (TotalBlocks)
{
uint8_t BytesInBlockDiv16 = 0;
/* Write an endpoint packet sized data block to the Dataflash */
while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4))
{
/* Check if the endpoint is currently empty */
if (!(Endpoint_IsReadWriteAllowed()))
{
/* Clear the current endpoint bank */
Endpoint_ClearOUT();
/* Wait until the host has sent another packet */
if (Endpoint_WaitUntilReady())
return;
}
/* Check if end of Dataflash page reached */
if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
{
/* Write the Dataflash buffer contents back to the Dataflash page */
Dataflash_WaitWhileBusy();
Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
Dataflash_SendAddressBytes(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 (Dataflash_GetSelectedChip() == DATAFLASH_CHIP_MASK(DATAFLASH_TOTALCHIPS))
UsingSecondBuffer = !(UsingSecondBuffer);
/* Select the next Dataflash chip based on the new Dataflash page index */
Dataflash_SelectChipFromPage(CurrDFPage);
#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
/* If less than one Dataflash page remaining, copy over the existing page to preserve trailing data */
if ((TotalBlocks * (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) < (DATAFLASH_PAGE_SIZE >> 4))
{
/* Copy selected dataflash's current page contents to the Dataflash buffer */
Dataflash_WaitWhileBusy();
Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_MAINMEMTOBUFF2 : DF_CMD_MAINMEMTOBUFF1);
Dataflash_SendAddressBytes(CurrDFPage, 0);
Dataflash_WaitWhileBusy();
}
#endif
/* Send the Dataflash buffer write command */
Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2WRITE : DF_CMD_BUFF1WRITE);
Dataflash_SendAddressBytes(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 */
Dataflash_WaitWhileBusy();
Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
Dataflash_SendAddressBytes(CurrDFPage, 0x00);
Dataflash_WaitWhileBusy();
/* If the endpoint is empty, clear it ready for the next packet from the host */
if (!(Endpoint_IsReadWriteAllowed()))
Endpoint_ClearOUT();
/* Deselect all Dataflash chips */
Dataflash_DeselectChip();
}
/** 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 DataflashManager_ReadBlocks(const uint32_t BlockAddress,
uint16_t TotalBlocks)
{
uint16_t CurrDFPage = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
uint16_t CurrDFPageByte = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
/* Select the correct starting Dataflash IC for the block requested */
Dataflash_SelectChipFromPage(CurrDFPage);
/* Send the Dataflash main memory page read command */
Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
Dataflash_SendAddressBytes(CurrDFPage, CurrDFPageByte);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
Dataflash_SendByte(0x00);
/* Wait until endpoint is ready before continuing */
if (Endpoint_WaitUntilReady())
return;
while (TotalBlocks)
{
uint8_t BytesInBlockDiv16 = 0;
/* Write an endpoint packet sized data block to the Dataflash */
while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4))
{
/* Check if the endpoint is currently full */
if (!(Endpoint_IsReadWriteAllowed()))
{
/* Clear the endpoint bank to send its contents to the host */
Endpoint_ClearIN();
/* Wait until the endpoint is ready for more data */
if (Endpoint_WaitUntilReady())
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 */
Dataflash_SelectChipFromPage(CurrDFPage);
/* Send the Dataflash main memory page read command */
Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
Dataflash_SendAddressBytes(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(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
Endpoint_Write_8(Dataflash_ReceiveByte());
/* 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 (!(Endpoint_IsReadWriteAllowed()))
Endpoint_ClearIN();
/* Deselect all Dataflash chips */
Dataflash_DeselectChip();
}
/** 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 DataflashManager_WriteBlocks_RAM(const uint32_t BlockAddress,
uint16_t TotalBlocks,
uint8_t* BufferPtr)
{
uint16_t CurrDFPage = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
uint16_t CurrDFPageByte = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
bool UsingSecondBuffer = false;
/* Select the correct starting Dataflash IC for the block requested */
Dataflash_SelectChipFromPage(CurrDFPage);
#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
/* Copy selected dataflash's current page contents to the Dataflash buffer */
Dataflash_SendByte(DF_CMD_MAINMEMTOBUFF1);
Dataflash_SendAddressBytes(CurrDFPage, 0);
Dataflash_WaitWhileBusy();
#endif
/* Send the Dataflash buffer write command */
Dataflash_SendByte(DF_CMD_BUFF1WRITE);
Dataflash_SendAddressBytes(0, CurrDFPageByte);
while (TotalBlocks)
{
uint8_t BytesInBlockDiv16 = 0;
/* Write an endpoint packet sized data block to the Dataflash */
while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4))
{
/* Check if end of Dataflash page reached */
if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
{
/* Write the Dataflash buffer contents back to the Dataflash page */
Dataflash_WaitWhileBusy();
Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
Dataflash_SendAddressBytes(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 (Dataflash_GetSelectedChip() == DATAFLASH_CHIP_MASK(DATAFLASH_TOTALCHIPS))
UsingSecondBuffer = !(UsingSecondBuffer);
/* Select the next Dataflash chip based on the new Dataflash page index */
Dataflash_SelectChipFromPage(CurrDFPage);
#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
/* If less than one Dataflash page remaining, copy over the existing page to preserve trailing data */
if ((TotalBlocks * (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) < (DATAFLASH_PAGE_SIZE >> 4))
{
/* Copy selected dataflash's current page contents to the Dataflash buffer */
Dataflash_WaitWhileBusy();
Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_MAINMEMTOBUFF2 : DF_CMD_MAINMEMTOBUFF1);
Dataflash_SendAddressBytes(CurrDFPage, 0);
Dataflash_WaitWhileBusy();
}
#endif
/* Send the Dataflash buffer write command */
Dataflash_ToggleSelectedChipCS();
Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2WRITE : DF_CMD_BUFF1WRITE);
Dataflash_SendAddressBytes(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 */
Dataflash_WaitWhileBusy();
Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
Dataflash_SendAddressBytes(CurrDFPage, 0x00);
Dataflash_WaitWhileBusy();
/* Deselect all Dataflash chips */
Dataflash_DeselectChip();
}
/** 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 DataflashManager_ReadBlocks_RAM(const uint32_t BlockAddress,
uint16_t TotalBlocks,
uint8_t* BufferPtr)
{
uint16_t CurrDFPage = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
uint16_t CurrDFPageByte = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
/* Select the correct starting Dataflash IC for the block requested */
Dataflash_SelectChipFromPage(CurrDFPage);
/* Send the Dataflash main memory page read command */
Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
Dataflash_SendAddressBytes(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 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 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 */
Dataflash_SelectChipFromPage(CurrDFPage);
/* Send the Dataflash main memory page read command */
Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
Dataflash_SendAddressBytes(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++) = Dataflash_ReceiveByte();
/* 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 */
Dataflash_DeselectChip();
}
/** Disables the Dataflash memory write protection bits on the board Dataflash ICs, if enabled. */
void DataflashManager_ResetDataflashProtections(void)
{
/* Select first Dataflash chip, send the read status register command */
Dataflash_SelectChip(DATAFLASH_CHIP1);
Dataflash_SendByte(DF_CMD_GETSTATUS);
/* Check if sector protection is enabled */
if (Dataflash_ReceiveByte() & DF_STATUS_SECTORPROTECTION_ON)
{
Dataflash_ToggleSelectedChipCS();
/* Send the commands to disable sector protection */
Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[0]);
Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[1]);
Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[2]);
Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[3]);
}
/* Select second Dataflash chip (if present on selected board), send read status register command */
#if (DATAFLASH_TOTALCHIPS == 2)
Dataflash_SelectChip(DATAFLASH_CHIP2);
Dataflash_SendByte(DF_CMD_GETSTATUS);
/* Check if sector protection is enabled */
if (Dataflash_ReceiveByte() & DF_STATUS_SECTORPROTECTION_ON)
{
Dataflash_ToggleSelectedChipCS();
/* Send the commands to disable sector protection */
Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[0]);
Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[1]);
Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[2]);
Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[3]);
}
#endif
/* Deselect current Dataflash chip */
Dataflash_DeselectChip();
}
/** 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 DataflashManager_CheckDataflashOperation(void)
{
uint8_t ReturnByte;
/* Test first Dataflash IC is present and responding to commands */
Dataflash_SelectChip(DATAFLASH_CHIP1);
Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO);
ReturnByte = Dataflash_ReceiveByte();
Dataflash_DeselectChip();
/* If returned data is invalid, fail the command */
if (ReturnByte != DF_MANUFACTURER_ATMEL)
return false;
#if (DATAFLASH_TOTALCHIPS == 2)
/* Test second Dataflash IC is present and responding to commands */
Dataflash_SelectChip(DATAFLASH_CHIP2);
Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO);
ReturnByte = Dataflash_ReceiveByte();
Dataflash_DeselectChip();
/* If returned data is invalid, fail the command */
if (ReturnByte != DF_MANUFACTURER_ATMEL)
return false;
#endif
return true;
}
| ruriwo/ErgoThumb072_firmware | tmk_core/protocol/lufa/LUFA-git/Demos/Device/LowLevel/MassStorage/Lib/DataflashManager.c | C | gpl-2.0 | 19,637 |
/*
* Renesas SuperH DMA Engine support
*
* base is drivers/dma/flsdma.c
*
* Copyright (C) 2009 Nobuhiro Iwamatsu <iwamatsu.nobuhiro@renesas.com>
* Copyright (C) 2009 Renesas Solutions, Inc. All rights reserved.
* Copyright (C) 2007 Freescale Semiconductor, Inc. All rights reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* - DMA of SuperH does not have Hardware DMA chain mode.
* - MAX DMA size is 16MB.
*
*/
#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 NR_DESCS_PER_CHANNEL 32
/* */
#define LOG2_DEFAULT_XFER_SIZE 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 sh_dmae_chan_ld_cleanup(struct sh_dmae_chan *sh_chan, bool all);
static void sh_chan_xfer_ld_queue(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));
spin_unlock_irqrestore(&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);
spin_unlock_irqrestore(&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,
LOG2_DEFAULT_XFER_SIZE);
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 dma_async_tx_descriptor *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;
dma_async_tx_callback 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);
/* */
list_for_each_entry_safe(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 sh_dmae_slave_config *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)
sh_chan_xfer_ld_queue(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 sh_dmae_slave_config *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 sh_dmae_alloc_chan_resources(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 sh_dmae_slave_config *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 < NR_DESCS_PER_CHANNEL) {
desc = kzalloc(sizeof(struct sh_desc), GFP_KERNEL);
if (!desc)
break;
dma_async_tx_descriptor_init(&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 sh_dmae_free_chan_resources(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))
sh_dmae_chan_ld_cleanup(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);
list_for_each_entry_safe(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 dma_transfer_direction 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 dma_async_tx_descriptor *sh_dmae_prep_sg(struct sh_dmae_chan *sh_chan,
struct scatterlist *sgl, unsigned int sg_len, dma_addr_t *addr,
enum dma_transfer_direction 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);
spin_unlock_irqrestore(&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);
spin_unlock_irqrestore(&sh_chan->desc_lock, irq_flags);
return NULL;
}
static struct dma_async_tx_descriptor *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 dma_async_tx_descriptor *sh_dmae_prep_slave_sg(
struct dma_chan *chan, struct scatterlist *sgl, unsigned int sg_len,
enum dma_transfer_direction 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;
}
spin_unlock_irqrestore(&sh_chan->desc_lock, flags);
sh_dmae_chan_ld_cleanup(sh_chan, true);
return 0;
}
static dma_async_tx_callback __ld_cleanup(struct sh_dmae_chan *sh_chan, bool all)
{
struct sh_desc *desc, *_desc;
/* */
bool head_acked = false;
dma_cookie_t cookie = 0;
dma_async_tx_callback callback = NULL;
void *param = NULL;
unsigned long flags;
spin_lock_irqsave(&sh_chan->desc_lock, flags);
list_for_each_entry_safe(desc, _desc, &sh_chan->ld_queue, node) {
struct dma_async_tx_descriptor *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;
spin_unlock_irqrestore(&sh_chan->desc_lock, flags);
if (callback)
callback(param);
return callback;
}
/*
*/
static void sh_dmae_chan_ld_cleanup(struct sh_dmae_chan *sh_chan, bool all)
{
while (__ld_cleanup(sh_chan, all))
;
}
/* */
static void sh_chan_xfer_ld_queue(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 sh_dmae_memcpy_issue_pending(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)
sh_chan_xfer_ld_queue(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;
sh_dmae_chan_ld_cleanup(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;
}
}
spin_unlock_irqrestore(&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 < SH_DMAC_MAX_CHANNELS; 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 dma_async_tx_descriptor *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;
}
}
/* */
sh_chan_xfer_ld_queue(sh_chan);
spin_unlock_irq(&sh_chan->desc_lock);
sh_dmae_chan_ld_cleanup(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();
list_for_each_entry_rcu(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 sh_dmae_nmi_notifier __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[SH_DMAC_MAX_CHANNELS] = {};
int errirq, chan_irq[SH_DMAC_MAX_CHANNELS];
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 = platform_get_resource(pdev, IORESOURCE_MEM, 0);
/* */
dmars = platform_get_resource(pdev, IORESOURCE_MEM, 1);
/*
*/
errirq_res = platform_get_resource(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;
platform_set_drvdata(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.device_alloc_chan_resources
= sh_dmae_alloc_chan_resources;
shdev->common.device_free_chan_resources = sh_dmae_free_chan_resources;
shdev->common.device_prep_dma_memcpy = sh_dmae_prep_memcpy;
shdev->common.device_tx_status = sh_dmae_tx_status;
shdev->common.device_issue_pending = sh_dmae_memcpy_issue_pending;
/* */
shdev->common.device_prep_slave_sg = sh_dmae_prep_slave_sg;
shdev->common.device_control = sh_dmae_control;
/* */
shdev->common.copy_align = LOG2_DEFAULT_XFER_SIZE;
#if defined(CONFIG_CPU_SH4) || defined(CONFIG_ARCH_SHMOBILE)
chanirq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 1);
if (!chanirq_res)
chanirq_res = errirq_res;
else
irqres++;
if (chanirq_res == errirq_res ||
(errirq_res->flags & IORESOURCE_BITS) == IORESOURCE_IRQ_SHAREABLE)
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 &&
!platform_get_resource(pdev, IORESOURCE_IRQ, 1)) {
/* */
for (; irq_cnt < pdata->channel_num; irq_cnt++) {
if (irq_cnt < SH_DMAC_MAX_CHANNELS) {
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 >= SH_DMAC_MAX_CHANNELS) {
irq_cap = 1;
break;
}
if ((errirq_res->flags & IORESOURCE_BITS) ==
IORESOURCE_IRQ_SHAREABLE)
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 >= SH_DMAC_MAX_CHANNELS)
break;
chanirq_res = platform_get_resource(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, SH_DMAC_MAX_CHANNELS);
pm_runtime_put(&pdev->dev);
dma_async_device_register(&shdev->common);
return err;
chan_probe_err:
sh_dmae_chan_remove(shdev);
#if defined(CONFIG_CPU_SH4) || defined(CONFIG_ARCH_SHMOBILE)
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);
platform_set_drvdata(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 = platform_get_drvdata(pdev);
struct resource *res;
int errirq = platform_get_irq(pdev, 0);
dma_async_device_unregister(&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);
platform_set_drvdata(pdev, NULL);
synchronize_rcu();
kfree(shdev);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res)
release_mem_region(res->start, resource_size(res));
res = platform_get_resource(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 = platform_get_drvdata(pdev);
sh_dmae_ctl_stop(shdev);
}
static int sh_dmae_runtime_suspend(struct device *dev)
{
return 0;
}
static int sh_dmae_runtime_resume(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 sh_dmae_slave_config *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 = sh_dmae_runtime_suspend,
.runtime_resume = sh_dmae_runtime_resume,
};
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 = register_die_notifier(&sh_dmae_nmi_notifier);
if (err)
return err;
return platform_driver_probe(&sh_dmae_driver, sh_dmae_probe);
}
module_init(sh_dmae_init);
static void __exit sh_dmae_exit(void)
{
platform_driver_unregister(&sh_dmae_driver);
unregister_die_notifier(&sh_dmae_nmi_notifier);
}
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");
| aicjofs/android_kernel_lge_v500_stock | drivers/dma/shdma.c | C | gpl-2.0 | 39,306 |
/*
* Core maple bus functionality
*
* Copyright (C) 2007 - 2009 Adrian McMenamin
* Copyright (C) 2001 - 2008 Paul Mundt
* Copyright (C) 2000 - 2001 YAEGASHI Takeshi
* Copyright (C) 2001 M. R. Brown
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#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");
MODULE_SUPPORTED_DEVICE("{{SEGA, Dreamcast/Maple}}");
static void maple_dma_handler(struct work_struct *work);
static void maple_vblank_handler(struct work_struct *work);
static DECLARE_WORK(maple_dma_process, maple_dma_handler);
static DECLARE_WORK(maple_vblank_process, maple_vblank_handler);
static LIST_HEAD(maple_waitq);
static LIST_HEAD(maple_sentq);
/* */
static DEFINE_MUTEX(maple_wlist_lock);
static struct maple_driver maple_unsupported_device;
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 maple_device_specify {
int port;
int unit;
};
static bool checked[MAPLE_PORTS];
static bool empty[MAPLE_PORTS];
static struct maple_device *baseunits[MAPLE_PORTS];
/*
*/
int maple_driver_register(struct maple_driver *drv)
{
if (!drv)
return -EINVAL;
drv->drv.bus = &maple_bus_type;
return driver_register(&drv->drv);
}
EXPORT_SYMBOL_GPL(maple_driver_register);
/*
*/
void maple_driver_unregister(struct maple_driver *drv)
{
driver_unregister(&drv->drv);
}
EXPORT_SYMBOL_GPL(maple_driver_unregister);
/* */
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 maple_getcond_callback(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(maple_getcond_callback);
static int maple_dma_done(void)
{
return (__raw_readl(MAPLE_STATE) & 1) == 0;
}
static void maple_release_device(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-- > 0)
*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;
list_for_each_entry_safe(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 maple_check_matching_driver(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 = &maple_unsupported_device;
dev_set_name(&mdev->dev, "%d:0.port", mdev->port);
} else {
matched =
bus_for_each_drv(&maple_bus_type, NULL, mdev,
maple_check_matching_driver);
if (matched == 0) {
/* */
dev_info(&mdev->dev, "no driver found\n");
mdev->driver = &maple_unsupported_device;
}
dev_set_name(&mdev->dev, "%d:0%d.%lX", mdev->port,
mdev->unit, function);
}
mdev->function = function;
mdev->dev.release = &maple_release_device;
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 maple_device_specify *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 setup_maple_commands(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),
MAPLE_COMMAND_GETCOND, 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,
MAPLE_COMMAND_DEVINFO, 0, NULL);
}
}
return 0;
}
/* */
static void maple_vblank_handler(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,
setup_maple_commands);
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,
MAPLE_COMMAND_DEVINFO, 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 maple_device_specify 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, MAPLE_COMMAND_DEVINFO,
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 maple_response_devinfo(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 maple_response_fileerr(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, MAPLE_COMMAND_DEVINFO,
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)) {
list_for_each_entry_safe(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 MAPLE_RESPONSE_DEVINFO:
maple_response_devinfo(mdev, recvbuf);
atomic_set(&mdev->busy, 0);
break;
case MAPLE_RESPONSE_DATATRF:
if (mdev->callback)
mdev->callback(mq);
atomic_set(&mdev->busy, 0);
wake_up(&mdev->maple_wait);
break;
case MAPLE_RESPONSE_FILEERR:
maple_response_fileerr(mdev, recvbuf);
atomic_set(&mdev->busy, 0);
wake_up(&mdev->maple_wait);
break;
case MAPLE_RESPONSE_AGAIN:
case MAPLE_RESPONSE_BADCMD:
case MAPLE_RESPONSE_BADFUNC:
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 MAPLE_RESPONSE_ALLINFO:
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 maple_vblank_interrupt(int irq, void *dev_id)
{
schedule_work(&maple_vblank_process);
return IRQ_HANDLED;
}
static int maple_set_dma_interrupt_handler(void)
{
return request_irq(HW_EVENT_MAPLE_DMA, maple_dma_interrupt,
IRQF_SHARED, "maple bus DMA", &maple_unsupported_device);
}
static int maple_set_vblank_interrupt_handler(void)
{
return request_irq(HW_EVENT_VSYNC, maple_vblank_interrupt,
IRQF_SHARED, "maple bus VBLANK", &maple_unsupported_device);
}
static int maple_get_dma_buffer(void)
{
maple_sendbuf =
(void *) __get_free_pages(GFP_KERNEL | __GFP_ZERO,
MAPLE_DMA_PAGES);
if (!maple_sendbuf)
return -ENOMEM;
return 0;
}
static int maple_match_bus_driver(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 maple_unsupported_device = {
.drv = {
.name = "maple_unsupported_device",
.bus = &maple_bus_type,
},
};
/*
*/
struct bus_type maple_bus_type = {
.name = "maple",
.match = maple_match_bus_driver,
.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(&maple_unsupported_device.drv);
if (retval)
goto cleanup_bus;
/* */
retval = maple_get_dma_buffer();
if (retval) {
dev_err(&maple_bus, "failed to allocate DMA buffers\n");
goto cleanup_basic;
}
/* */
retval = maple_set_dma_interrupt_handler();
if (retval) {
dev_err(&maple_bus, "bus failed to grab maple "
"DMA IRQ\n");
goto cleanup_dma;
}
/* */
retval = maple_set_vblank_interrupt_handler();
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-- > 0)
maple_free_dev(mdev[i]);
goto cleanup_cache;
}
baseunits[i] = mdev[i];
atomic_set(&mdev[i]->busy, 1);
maple_add_packet(mdev[i], 0, MAPLE_COMMAND_DEVINFO, 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(&maple_unsupported_device.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);
| holyangel/LGE_G3 | drivers/sh/maple/maple.c | C | gpl-2.0 | 21,950 |
/*
* OMAP5 thermal driver.
*
* Copyright (C) 2011-2012 Texas Instruments Inc.
* Contact:
* Eduardo Valentin <eduardo.valentin@ti.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <mach/ctrl_module_core_54xx.h>
#include "omap-bandgap.h"
/* TODO: Remove this, ES2.0 samples won't allow this to be programmable*/
#define OMAP5430_MPU_TSHUT_HOT 928 /* 119 degC */
#define OMAP5430_MPU_TSHUT_COLD 900
#define OMAP5430_GPU_TSHUT_HOT 916 /* 114 degC */
#define OMAP5430_GPU_TSHUT_COLD 900
#define OMAP5430_CORE_TSHUT_HOT 943 /* 125 degC */
#define OMAP5430_CORE_TSHUT_COLD 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 temp_sensor_registers
omap5430_mpu_temp_sensor_registers = {
.temp_sensor_ctrl = OMAP5_CTRL_MODULE_CORE_TEMP_SENSOR_MPU,
.bgap_tempsoff_mask = OMAP5_BGAP_TMPSOFF_MPU_MASK,
.bgap_eocz_mask = OMAP5_BGAP_EOCZ_MPU_MASK,
.bgap_dtemp_mask = OMAP5_BGAP_DTEMP_MPU_MASK,
.bgap_mask_ctrl = OMAP5_CTRL_MODULE_CORE_BANDGAP_MASK,
.mask_hot_mask = OMAP5_MASK_HOT_MPU_MASK,
.mask_cold_mask = OMAP5_MASK_COLD_MPU_MASK,
.mask_sidlemode_mask = OMAP5_SIDLEMODE_MASK,
.mask_freeze_mask = OMAP5_FREEZE_MPU_MASK,
.mask_clear_mask = OMAP5_CLEAR_MPU_MASK,
.mask_clear_accum_mask = OMAP5_CLEAR_ACCUM_MPU_MASK,
.bgap_counter = OMAP5_CTRL_MODULE_CORE_BANDGAP_MASK,
.counter_mask = OMAP5_COUNTER_DELAY_MASK,
.bgap_threshold = OMAP5_CTRL_MODULE_CORE_BANDGAP_THRESHOLD_MPU,
.threshold_thot_mask = OMAP5_THOLD_HOT_MPU_MASK,
.threshold_tcold_mask = OMAP5_THOLD_COLD_MPU_MASK,
.tshut_threshold = OMAP5_CTRL_MODULE_CORE_BANDGAP_TSHUT_MPU,
.tshut_efuse_shift = OMAP5_TSHUT_MUXCTRL_MPU_SHIFT,
.tshut_efuse_mask = OMAP5_TSHUT_MUXCTRL_MPU_MASK,
.tshut_hot_mask = OMAP5_TSHUT_HOT_MPU_MASK,
.tshut_cold_mask = OMAP5_TSHUT_COLD_MPU_MASK,
.bgap_status = OMAP5_CTRL_MODULE_CORE_BANDGAP_STATUS,
.status_clean_stop_mask = 0x0,
.status_bgap_alert_mask = OMAP5_ALERT_MASK,
.status_hot_mask = OMAP5_HOT_MPU_MASK,
.status_cold_mask = OMAP5_COLD_MPU_MASK,
.bgap_cumul_dtemp = OMAP5_CTRL_MODULE_CORE_BANDGAP_CUMUL_DTEMP_MPU,
.ctrl_dtemp_0 = OMAP5_CTRL_MODULE_CORE_DTEMP_MPU_0,
.ctrl_dtemp_1 = OMAP5_CTRL_MODULE_CORE_DTEMP_MPU_1,
.ctrl_dtemp_2 = OMAP5_CTRL_MODULE_CORE_DTEMP_MPU_2,
.ctrl_dtemp_3 = OMAP5_CTRL_MODULE_CORE_DTEMP_MPU_3,
.ctrl_dtemp_4 = OMAP5_CTRL_MODULE_CORE_DTEMP_MPU_4,
.bgap_efuse = OMAP5_CTRL_MODULE_CORE_STD_FUSE_OPP_BGAP_MPU,
};
/*
* OMAP5430 GPU thermal sensor register offset and bit-fields
*/
static struct temp_sensor_registers
omap5430_gpu_temp_sensor_registers = {
.temp_sensor_ctrl = OMAP5_CTRL_MODULE_CORE_TEMP_SENSOR_MM,
.bgap_tempsoff_mask = OMAP5_BGAP_TMPSOFF_MM_MASK,
.bgap_eocz_mask = OMAP5_BGAP_EOCZ_MM_MASK,
.bgap_dtemp_mask = OMAP5_BGAP_DTEMP_MM_MASK,
.bgap_mask_ctrl = OMAP5_CTRL_MODULE_CORE_BANDGAP_MASK,
.mask_hot_mask = OMAP5_MASK_HOT_MM_MASK,
.mask_cold_mask = OMAP5_MASK_COLD_MM_MASK,
.mask_sidlemode_mask = OMAP5_SIDLEMODE_MASK,
.mask_freeze_mask = OMAP5_FREEZE_MM_MASK,
.mask_clear_mask = OMAP5_CLEAR_MM_MASK,
.mask_clear_accum_mask = OMAP5_CLEAR_ACCUM_MM_MASK,
.bgap_counter = OMAP5_CTRL_MODULE_CORE_BANDGAP_MASK,
.counter_mask = OMAP5_COUNTER_DELAY_MASK,
.bgap_threshold = OMAP5_CTRL_MODULE_CORE_BANDGAP_THRESHOLD_MM,
.threshold_thot_mask = OMAP5_THOLD_HOT_MM_MASK,
.threshold_tcold_mask = OMAP5_THOLD_COLD_MM_MASK,
.tshut_threshold = OMAP5_CTRL_MODULE_CORE_BANDGAP_TSHUT_MM,
.tshut_efuse_shift = OMAP5_TSHUT_MUXCTRL_MM_SHIFT,
.tshut_efuse_mask = OMAP5_TSHUT_MUXCTRL_MM_MASK,
.tshut_hot_mask = OMAP5_TSHUT_HOT_MM_MASK,
.tshut_cold_mask = OMAP5_TSHUT_COLD_MM_MASK,
.bgap_status = OMAP5_CTRL_MODULE_CORE_BANDGAP_STATUS,
.status_clean_stop_mask = 0x0,
.status_bgap_alert_mask = OMAP5_ALERT_MASK,
.status_hot_mask = OMAP5_HOT_MM_MASK,
.status_cold_mask = OMAP5_COLD_MM_MASK,
.bgap_cumul_dtemp = OMAP5_CTRL_MODULE_CORE_BANDGAP_CUMUL_DTEMP_MM,
.ctrl_dtemp_0 = OMAP5_CTRL_MODULE_CORE_DTEMP_MM_0,
.ctrl_dtemp_1 = OMAP5_CTRL_MODULE_CORE_DTEMP_MM_1,
.ctrl_dtemp_2 = OMAP5_CTRL_MODULE_CORE_DTEMP_MM_2,
.ctrl_dtemp_3 = OMAP5_CTRL_MODULE_CORE_DTEMP_MM_3,
.ctrl_dtemp_4 = OMAP5_CTRL_MODULE_CORE_DTEMP_MM_4,
.bgap_efuse = OMAP5_CTRL_MODULE_CORE_STD_FUSE_OPP_BGAP_MM,
};
/*
* OMAP5430 CORE thermal sensor register offset and bit-fields
*/
static struct temp_sensor_registers
omap5430_core_temp_sensor_registers = {
.temp_sensor_ctrl = OMAP5_CTRL_MODULE_CORE_TEMP_SENSOR_CORE,
.bgap_tempsoff_mask = OMAP5_BGAP_TMPSOFF_CORE_MASK,
.bgap_eocz_mask = OMAP5_BGAP_EOCZ_CORE_MASK,
.bgap_dtemp_mask = OMAP5_BGAP_DTEMP_CORE_MASK,
.bgap_mask_ctrl = OMAP5_CTRL_MODULE_CORE_BANDGAP_MASK,
.mask_hot_mask = OMAP5_MASK_HOT_CORE_MASK,
.mask_cold_mask = OMAP5_MASK_COLD_CORE_MASK,
.mask_sidlemode_mask = OMAP5_SIDLEMODE_MASK,
.mask_freeze_mask = OMAP5_FREEZE_CORE_MASK,
.mask_clear_mask = OMAP5_CLEAR_CORE_MASK,
.mask_clear_accum_mask = OMAP5_CLEAR_ACCUM_CORE_MASK,
.bgap_counter = OMAP5_CTRL_MODULE_CORE_BANDGAP_MASK,
.counter_mask = OMAP5_COUNTER_DELAY_MASK,
.bgap_threshold = OMAP5_CTRL_MODULE_CORE_BANDGAP_THRESHOLD_CORE,
.threshold_thot_mask = OMAP5_THOLD_HOT_CORE_MASK,
.threshold_tcold_mask = OMAP5_THOLD_COLD_CORE_MASK,
.tshut_threshold = OMAP5_CTRL_MODULE_CORE_BANDGAP_TSHUT_CORE,
.tshut_efuse_shift = OMAP5_TSHUT_MUXCTRL_CORE_SHIFT,
.tshut_efuse_mask = OMAP5_TSHUT_MUXCTRL_CORE_MASK,
.tshut_hot_mask = OMAP5_TSHUT_HOT_CORE_MASK,
.tshut_cold_mask = OMAP5_TSHUT_COLD_CORE_MASK,
.bgap_status = OMAP5_CTRL_MODULE_CORE_BANDGAP_STATUS,
.status_clean_stop_mask = 0x0,
.status_bgap_alert_mask = OMAP5_ALERT_MASK,
.status_hot_mask = OMAP5_HOT_CORE_MASK,
.status_cold_mask = OMAP5_COLD_CORE_MASK,
.bgap_cumul_dtemp = OMAP5_CTRL_MODULE_CORE_BANDGAP_CUMUL_DTEMP_CORE,
.ctrl_dtemp_0 = OMAP5_CTRL_MODULE_CORE_DTEMP_CORE_0,
.ctrl_dtemp_1 = OMAP5_CTRL_MODULE_CORE_DTEMP_CORE_1,
.ctrl_dtemp_2 = OMAP5_CTRL_MODULE_CORE_DTEMP_CORE_2,
.ctrl_dtemp_3 = OMAP5_CTRL_MODULE_CORE_DTEMP_CORE_3,
.ctrl_dtemp_4 = OMAP5_CTRL_MODULE_CORE_DTEMP_CORE_4,
.bgap_efuse = OMAP5_CTRL_MODULE_CORE_STD_FUSE_OPP_BGAP_CORE,
};
/* Thresholds and limits for OMAP5430 MPU temperature sensor */
static struct temp_sensor_data omap5430_mpu_temp_sensor_data = {
.tshut_hot = OMAP5430_MPU_TSHUT_HOT,
.tshut_cold = OMAP5430_MPU_TSHUT_COLD,
.t_hot = OMAP5430_MPU_T_HOT,
.t_cold = OMAP5430_MPU_T_COLD,
.min_freq = OMAP5430_MPU_MIN_FREQ,
.max_freq = OMAP5430_MPU_MAX_FREQ,
.max_temp = OMAP5430_MPU_MAX_TEMP,
.min_temp = OMAP5430_MPU_MIN_TEMP,
.hyst_val = OMAP5430_MPU_HYST_VAL,
.adc_start_val = OMAP5430_ES2_ADC_START_VALUE,
.adc_end_val = OMAP5430_ES2_ADC_END_VALUE,
.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 omap5430_gpu_temp_sensor_data = {
.tshut_hot = OMAP5430_GPU_TSHUT_HOT,
.tshut_cold = OMAP5430_GPU_TSHUT_COLD,
.t_hot = OMAP5430_GPU_T_HOT,
.t_cold = OMAP5430_GPU_T_COLD,
.min_freq = OMAP5430_GPU_MIN_FREQ,
.max_freq = OMAP5430_GPU_MAX_FREQ,
.max_temp = OMAP5430_GPU_MAX_TEMP,
.min_temp = OMAP5430_GPU_MIN_TEMP,
.hyst_val = OMAP5430_GPU_HYST_VAL,
.adc_start_val = OMAP5430_ES2_ADC_START_VALUE,
.adc_end_val = OMAP5430_ES2_ADC_END_VALUE,
.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 omap5430_core_temp_sensor_data = {
.tshut_hot = OMAP5430_CORE_TSHUT_HOT,
.tshut_cold = OMAP5430_CORE_TSHUT_COLD,
.t_hot = OMAP5430_CORE_T_HOT,
.t_cold = OMAP5430_CORE_T_COLD,
.min_freq = OMAP5430_CORE_MIN_FREQ,
.max_freq = OMAP5430_CORE_MAX_FREQ,
.max_temp = OMAP5430_CORE_MAX_TEMP,
.min_temp = OMAP5430_CORE_MIN_TEMP,
.hyst_val = OMAP5430_CORE_HYST_VAL,
.adc_start_val = OMAP5430_ES2_ADC_START_VALUE,
.adc_end_val = OMAP5430_ES2_ADC_END_VALUE,
.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
omap5430_adc_to_temp[
OMAP5430_ES2_ADC_END_VALUE - OMAP5430_ES2_ADC_START_VALUE + 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 = OMAP_BANDGAP_FEATURE_TSHUT_CONFIG |
OMAP_BANDGAP_FEATURE_FREEZE_BIT |
OMAP_BANDGAP_FEATURE_TALERT,
.fclock_name = "l3instr_ts_gclk_div",
.div_ck_name = "l3instr_ts_gclk_div",
.conv_table = omap5430_adc_to_temp,
.report_temperature = omap_thermal_report_temperature,
.expose_sensor = omap_thermal_expose_sensor,
.remove_sensor = omap_thermal_remove_sensor,
.sensors = {
{
.registers = &omap5430_mpu_temp_sensor_registers,
.ts_data = &omap5430_mpu_temp_sensor_data,
.domain = "cpu",
.slope = 118,
.constant = -2992,
},
{
.registers = &omap5430_gpu_temp_sensor_registers,
.ts_data = &omap5430_gpu_temp_sensor_data,
.domain = "gpu",
.slope = 61,
.constant = -1558,
},
{
.registers = &omap5430_core_temp_sensor_registers,
.ts_data = &omap5430_core_temp_sensor_data,
.domain = "core",
.slope = 0,
.constant = 0,
},
},
.sensor_count = 3,
};
| bsmitty83/kernel_omap | drivers/thermal/omap5-bg-sen-data.c | C | gpl-2.0 | 13,846 |
// Copyright (C) 2014 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <regex>
#include <testsuite_performance.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;
}
| xinchoubiology/gcc | libstdc++-v3/testsuite/performance/28_regex/range.cc | C++ | gpl-2.0 | 1,349 |
/* Copyright (c) 2014-2015, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#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 msm_camera_i2c_client i2c_client;
enum msm_camera_device_type_t iris_device_type;
struct msm_sd_subdev msm_sd;
struct mutex *iris_mutex;
enum msm_camera_i2c_data_type i2c_data_type;
struct v4l2_subdev sdev;
struct v4l2_subdev_ops *iris_v4l2_subdev_ops;
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
| jcadduono/android_kernel_lge_msm8996 | drivers/media/platform/msm/camera_v2/sensor/iris/msm_iris.h | C | gpl-2.0 | 1,746 |
/*
* linux/fs/ext4/xattr.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*
* Fix by Harrison Xing <harrison@mountainviewdata.com>.
* Ext4 code with a lot of help from Eric Jarman <ejarman@acm.org>.
* Extended attributes for symlinks and special files added per
* suggestion of Luka Renko <luka.renko@hermes.si>.
* xattr consolidation Copyright (c) 2004 James Morris <jmorris@redhat.com>,
* Red Hat Inc.
* ea-in-inode support by Alex Tomas <alex@clusterfs.com> aka bzzz
* and Andreas Gruenbacher <agruen@suse.de>.
*/
/*
* Extended attributes are stored directly in inodes (on file systems with
* inodes bigger than 128 bytes) and on additional disk blocks. The i_file_acl
* field contains the block number if an inode uses an additional block. All
* attributes must fit in the inode and one additional block. Blocks that
* contain the identical set of attributes may be shared among several inodes.
* Identical blocks are detected by keeping a cache of blocks that have
* recently been accessed.
*
* The attributes in inodes and on blocks have a different header; the entries
* are stored in the same format:
*
* +------------------+
* | header |
* | entry 1 | |
* | entry 2 | | growing downwards
* | entry 3 | v
* | four null bytes |
* | . . . |
* | value 1 | ^
* | value 3 | | growing upwards
* | value 2 | |
* +------------------+
*
* The header is followed by multiple entry descriptors. In disk blocks, the
* entry descriptors are kept sorted. In inodes, they are unsorted. The
* attribute values are aligned to the end of the block in no specific order.
*
* Locking strategy
* ----------------
* EXT4_I(inode)->i_file_acl is protected by EXT4_I(inode)->xattr_sem.
* EA blocks are only changed if they are exclusive to an inode, so
* holding xattr_sem also means that nothing but the EA block's reference
* count can change. Multiple writers to the same block are synchronized
* by the buffer lock.
*/
#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 ext4_xattr_cache_insert(struct buffer_head *);
static struct buffer_head *ext4_xattr_cache_find(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 *ext4_xattr_handler_map[] = {
[EXT4_XATTR_INDEX_USER] = &ext4_xattr_user_handler,
#ifdef CONFIG_EXT4_FS_POSIX_ACL
[EXT4_XATTR_INDEX_POSIX_ACL_ACCESS] = &ext4_xattr_acl_access_handler,
[EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT] = &ext4_xattr_acl_default_handler,
#endif
[EXT4_XATTR_INDEX_TRUSTED] = &ext4_xattr_trusted_handler,
#ifdef CONFIG_EXT4_FS_SECURITY
[EXT4_XATTR_INDEX_SECURITY] = &ext4_xattr_security_handler,
#endif
};
const struct xattr_handler *ext4_xattr_handlers[] = {
&ext4_xattr_user_handler,
&ext4_xattr_trusted_handler,
#ifdef CONFIG_EXT4_FS_POSIX_ACL
&ext4_xattr_acl_access_handler,
&ext4_xattr_acl_default_handler,
#endif
#ifdef CONFIG_EXT4_FS_SECURITY
&ext4_xattr_security_handler,
#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(ext4_xattr_handler_map))
handler = ext4_xattr_handler_map[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
ext4_xattr_check_names(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
ext4_xattr_check_block(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 ext4_xattr_check_names(BFIRST(bh), bh->b_data + bh->b_size);
}
static inline int
ext4_xattr_check_entry(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
ext4_xattr_find_entry(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 && ext4_xattr_check_entry(entry, size))
return -EIO;
return cmp ? -ENODATA : 0;
}
static int
ext4_xattr_block_get(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 (ext4_xattr_check_block(bh)) {
bad_block:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
ext4_xattr_cache_insert(bh);
entry = BFIRST(bh);
error = ext4_xattr_find_entry(&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
ext4_xattr_ibody_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_entry *entry;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
size_t size;
void *end;
int error;
if (!ext4_test_inode_state(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 = ext4_xattr_check_names(entry, end);
if (error)
goto cleanup;
error = ext4_xattr_find_entry(&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 = ext4_xattr_ibody_get(inode, name_index, name, buffer,
buffer_size);
if (error == -ENODATA)
error = ext4_xattr_block_get(inode, name_index, name, buffer,
buffer_size);
up_read(&EXT4_I(inode)->xattr_sem);
return error;
}
static int
ext4_xattr_list_entries(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
ext4_xattr_block_list(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 (ext4_xattr_check_block(bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
ext4_xattr_cache_insert(bh);
error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
static int
ext4_xattr_ibody_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = dentry->d_inode;
struct ext4_xattr_ibody_header *header;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
void *end;
int error;
if (!ext4_test_inode_state(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 = ext4_xattr_check_names(IFIRST(header), end);
if (error)
goto cleanup;
error = ext4_xattr_list_entries(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 = ext4_xattr_ibody_list(dentry, buffer, buffer_size);
if (ret < 0)
goto errout;
if (buffer) {
buffer += ret;
buffer_size -= ret;
}
ret = ext4_xattr_block_list(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 EXT4_FEATURE_COMPAT_EXT_ATTR feature of this file system is
* not set, set it.
*/
static void ext4_xattr_update_super_block(handle_t *handle,
struct super_block *sb)
{
if (EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_EXT_ATTR))
return;
if (ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh) == 0) {
EXT4_SET_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_EXT_ATTR);
ext4_handle_dirty_super(handle, sb);
}
}
/*
* Release the xattr block BH: If the reference count is > 1, decrement
* it; otherwise free the block.
*/
static void
ext4_xattr_release_block(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 = ext4_journal_get_write_access(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,
EXT4_FREE_BLOCKS_METADATA |
EXT4_FREE_BLOCKS_FORGET);
unlock_buffer(bh);
} else {
le32_add_cpu(&BHDR(bh)->h_refcount, -1);
if (ce)
mb_cache_entry_release(ce);
unlock_buffer(bh);
error = ext4_handle_dirty_metadata(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 ext4_xattr_free_space(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
ext4_xattr_set_entry(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 ext4_xattr_block_find {
struct ext4_xattr_search s;
struct buffer_head *bh;
};
static int
ext4_xattr_block_find(struct inode *inode, struct ext4_xattr_info *i,
struct ext4_xattr_block_find *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 (ext4_xattr_check_block(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 = ext4_xattr_find_entry(&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
ext4_xattr_block_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_block_find *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 = ext4_journal_get_write_access(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 = ext4_xattr_set_entry(i, s);
if (!error) {
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base),
s->here);
ext4_xattr_cache_insert(bs->bh);
}
unlock_buffer(bs->bh);
if (error == -EIO)
goto bad_block;
if (!error)
error = ext4_handle_dirty_metadata(handle,
inode,
bs->bh);
if (error)
goto cleanup;
goto inserted;
} else {
int offset = (char *)s->here - bs->bh->b_data;
unlock_buffer(bs->bh);
ext4_handle_release_buffer(handle, bs->bh);
if (ce) {
mb_cache_entry_release(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 = ext4_xattr_set_entry(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 = ext4_xattr_cache_find(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 = ext4_journal_get_write_access(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 = ext4_handle_dirty_metadata(handle,
inode,
new_bh);
if (error)
goto cleanup_dquot;
}
mb_cache_entry_release(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 = ext4_group_first_block_no(sb,
EXT4_I(inode)->i_block_group);
/* non-extent files can't have physical blocks past 2^32 */
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
/*
* take i_data_sem because we will test
* i_delalloc_reserved_flag in ext4_mb_new_blocks
*/
down_read((&EXT4_I(inode)->i_data_sem));
block = ext4_new_meta_blocks(handle, inode, goal, 0,
NULL, &error);
up_read((&EXT4_I(inode)->i_data_sem));
if (error)
goto cleanup;
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
BUG_ON(block > EXT4_MAX_BLOCK_FILE_PHYS);
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,
EXT4_FREE_BLOCKS_METADATA);
goto cleanup;
}
lock_buffer(new_bh);
error = ext4_journal_get_create_access(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);
ext4_xattr_cache_insert(new_bh);
error = ext4_handle_dirty_metadata(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)
ext4_xattr_release_block(handle, inode, bs->bh);
error = 0;
cleanup:
if (ce)
mb_cache_entry_release(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 ext4_xattr_ibody_find {
struct ext4_xattr_search s;
struct ext4_iloc iloc;
};
static int
ext4_xattr_ibody_find(struct inode *inode, struct ext4_xattr_info *i,
struct ext4_xattr_ibody_find *is)
{
struct ext4_xattr_ibody_header *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 (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
error = ext4_xattr_check_names(IFIRST(header), is->s.end);
if (error)
return error;
/* Find the named attribute. */
error = ext4_xattr_find_entry(&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
ext4_xattr_ibody_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_ibody_find *is)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_search *s = &is->s;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return -ENOSPC;
error = ext4_xattr_set_entry(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);
ext4_set_inode_state(inode, EXT4_STATE_XATTR);
} else {
header->h_magic = cpu_to_le32(0);
ext4_clear_inode_state(inode, EXT4_STATE_XATTR);
}
return 0;
}
/*
* ext4_xattr_set_handle()
*
* 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
ext4_xattr_set_handle(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 ext4_xattr_ibody_find is = {
.s = { .not_found = -ENODATA, },
};
struct ext4_xattr_block_find 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 = ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND);
ext4_set_inode_state(inode, EXT4_STATE_NO_EXPAND);
error = ext4_reserve_inode_write(handle, inode, &is.iloc);
if (error)
goto cleanup;
if (ext4_test_inode_state(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);
ext4_clear_inode_state(inode, EXT4_STATE_NEW);
}
error = ext4_xattr_ibody_find(inode, &i, &is);
if (error)
goto cleanup;
if (is.s.not_found)
error = ext4_xattr_block_find(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 = ext4_xattr_ibody_set(handle, inode, &i, &is);
else if (!bs.s.not_found)
error = ext4_xattr_block_set(handle, inode, &i, &bs);
} else {
error = ext4_xattr_ibody_set(handle, inode, &i, &is);
if (!error && !bs.s.not_found) {
i.value = NULL;
error = ext4_xattr_block_set(handle, inode, &i, &bs);
} else if (error == -ENOSPC) {
if (EXT4_I(inode)->i_file_acl && !bs.s.base) {
error = ext4_xattr_block_find(inode, &i, &bs);
if (error)
goto cleanup;
}
error = ext4_xattr_block_set(handle, inode, &i, &bs);
if (error)
goto cleanup;
if (!is.s.not_found) {
i.value = NULL;
error = ext4_xattr_ibody_set(handle, inode, &i,
&is);
}
}
}
if (!error) {
ext4_xattr_update_super_block(handle, inode->i_sb);
inode->i_ctime = ext4_current_time(inode);
if (!value)
ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND);
error = ext4_mark_iloc_dirty(handle, inode, &is.iloc);
/*
* The bh is consumed by ext4_mark_iloc_dirty, 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)
ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND);
up_write(&EXT4_I(inode)->xattr_sem);
return error;
}
/*
* ext4_xattr_set()
*
* Like ext4_xattr_set_handle, 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, EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
} else {
int error2;
error = ext4_xattr_set_handle(handle, inode, name_index, name,
value, value_len, flags);
error2 = ext4_journal_stop(handle);
if (error == -ENOSPC &&
ext4_should_retry_alloc(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 ext4_xattr_shift_entries(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 ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize,
struct ext4_inode *raw_inode, handle_t *handle)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_entry *entry, *last, *first;
struct buffer_head *bh = NULL;
struct ext4_xattr_ibody_find *is = NULL;
struct ext4_xattr_block_find *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, tried_min_extra_isize = 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 ext4_xattr_ibody_header);
free = ext4_xattr_free_space(last, &min_offs, base, &total_ino);
if (free >= new_extra_isize) {
entry = IFIRST(header);
ext4_xattr_shift_entries(entry, EXT4_I(inode)->i_extra_isize
- new_extra_isize, (void *)raw_inode +
EXT4_GOOD_OLD_INODE_SIZE + 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 (ext4_xattr_check_block(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 = ext4_xattr_free_space(first, &min_offs, base,
&total_blk);
if (free < new_extra_isize) {
if (!tried_min_extra_isize && s_min_extra_isize) {
tried_min_extra_isize++;
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 ext4_xattr_ibody_find), GFP_NOFS);
bs = kzalloc(sizeof(struct ext4_xattr_block_find), 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 (!tried_min_extra_isize &&
s_min_extra_isize) {
tried_min_extra_isize++;
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 = ext4_xattr_ibody_find(inode, &i, is);
if (error)
goto cleanup;
/* Remove the chosen entry from the inode */
error = ext4_xattr_ibody_set(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 */
ext4_xattr_shift_entries(entry, EXT4_I(inode)->i_extra_isize -
shift_bytes, (void *)raw_inode +
EXT4_GOOD_OLD_INODE_SIZE + 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 = ext4_xattr_block_find(inode, &i, bs);
if (error)
goto cleanup;
/* Add entry which was removed from the inode into the block */
error = ext4_xattr_block_set(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;
}
/*
* ext4_xattr_delete_inode()
*
* 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
ext4_xattr_delete_inode(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;
}
ext4_xattr_release_block(handle, inode, bh);
EXT4_I(inode)->i_file_acl = 0;
cleanup:
brelse(bh);
}
/*
* ext4_xattr_put_super()
*
* This is called when a file system is unmounted.
*/
void
ext4_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
/*
* ext4_xattr_cache_insert()
*
* 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
ext4_xattr_cache_insert(struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(BHDR(bh)->h_hash);
struct mb_cache_entry *ce;
int error;
ce = mb_cache_entry_alloc(ext4_xattr_cache, GFP_NOFS);
if (!ce) {
ea_bdebug(bh, "out of memory");
return;
}
error = mb_cache_entry_insert(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);
mb_cache_entry_release(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;
}
/*
* ext4_xattr_cache_find()
*
* 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 *
ext4_xattr_cache_find(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 = mb_cache_entry_find_first(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) >=
EXT4_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
EXT4_XATTR_REFCOUNT_MAX);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
#define NAME_HASH_SHIFT 5
#define VALUE_HASH_SHIFT 16
/*
* ext4_xattr_hash_entry()
*
* Compute the hash of an extended attribute.
*/
static inline void ext4_xattr_hash_entry(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;
ext4_xattr_hash_entry(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;
}
| davidmueller13/AK-Flo | fs/ext4/xattr.c | C | gpl-2.0 | 43,253 |
/*
* SuperH interrupt controller module
*
* Copyright (c) 2007 Magnus Damm
* Based on sh_timer.c and arm_timer.c by Paul Brook
* Copyright (c) 2005-2006 CodeSourcery.
*
* This code is licensed under the GPL.
*/
#include "sh_intc.h"
#include "hw.h"
#include "sh.h"
//#define DEBUG_INTC
//#define DEBUG_INTC_SOURCES
#define INTC_A7(x) ((x) & 0x1fffffff)
void sh_intc_toggle_source(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)
sh_intc_toggle_source(source, 0, 1);
else if (!level && source->asserted)
sh_intc_toggle_source(source, 0, -1);
}
int sh_intc_get_pending_vector(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 INTC_MODE_ENABLE_REG 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 INTC_MODE_ENABLE_REG;
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)
sh_intc_toggle_source(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 INTC_MODE_ENABLE_REG | 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) {
cpu_register_physical_memory_offset(P4ADDR(address), 4,
desc->iomemtype, INTC_A7(address));
cpu_register_physical_memory_offset(A7ADDR(address), 4,
desc->iomemtype, INTC_A7(address));
}
}
static void sh_intc_register_source(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 sh_intc_register_sources(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;
sh_intc_register_source(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 = cpu_register_io_memory(sh_intc_readfn,
sh_intc_writefn, desc,
DEVICE_NATIVE_ENDIAN);
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)
sh_intc_toggle_source(s, s->enable_count?0:1, s->asserted?0:1);
else
if (s->asserted)
sh_intc_toggle_source(s, 0, -1);
}
}
| SSLab-NTHU/qemu-guest-armvisor | hw/sh_intc.c | C | gpl-2.0 | 12,189 |
/*
* array.h - useful array handling header
*
* Copyright © 2009 Julien Danjou <julien@danjou.info>
* Copyright © 2008 Pierre Habouzit <madcoder@debian.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#ifndef AWESOME_COMMON_ARRAY_H
#define AWESOME_COMMON_ARRAY_H
#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
| Asido/AwesomeWM | common/array.h | C | gpl-2.0 | 8,691 |
<?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\HostedNumberOrderList;
use Twilio\Version;
/**
* @property \Twilio\Rest\Preview\HostedNumbers\HostedNumberOrderList hostedNumberOrders
* @method \Twilio\Rest\Preview\HostedNumbers\HostedNumberOrderContext 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\HostedNumberOrderList
*/
protected function getHostedNumberOrders() {
if (!$this->_hostedNumberOrders) {
$this->_hostedNumberOrders = new HostedNumberOrderList($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 call_user_func_array(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]';
}
} | Haynie-Research-and-Development/jarvis | web/webapi/sms/vendor/twilio/sdk/Twilio/Rest/Preview/HostedNumbers.php | PHP | gpl-2.0 | 2,570 |
<?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(),
'hover_action_column_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['hover_action_column_key'] != '' ) {
if ( is_array( $item[$settings['hover_action_column_key']] ) ) {
$hover_action_column_value = $item[$settings['hover_action_column_key']][0];
} else {
$hover_action_column_value = $item[$settings['hover_action_column_key']];
}
} else {
$hover_action_column_value = '';
}
if ( strstr( $action_slug, 'http' ) === false ) { // Word hover action slug.
$hover_link= pb_backupbuddy::page_url() . '&' . $action_slug . '=' . $item_id . '&value=' . $hover_action_column_value;
} else { // URL hover action slug so just append value to URL.
$hover_link = $action_slug . $hover_action_column_value;
}
echo '<a href="' . $hover_link . '" class="pb_' . pb_backupbuddy::settings( 'slug' ) . '_hoveraction_' . $action_slug . '" rel="' . $hover_action_column_value . '">' . $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="pb_backupbuddy_alert ';
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="pb_backupbuddy_disalert" 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://www.youtube.com/embed/' . urlencode( $video[0] ) . '?autoplay=1' . $video[1] . '&TB_iframe=1&width=600&height=400" class="thickbox pluginbuddy_tip" title="Video Tutorial - ' . $title . '"><img src="' . pb_backupbuddy::plugin_url() . '/pluginbuddy/images/pluginbuddy_play.png" alt="(video)" /></a>';
if ( $echo_tip === true ) {
echo $tip;
} else {
return $tip;
}
} // End video().
/*
public function media_library( $save_point, $default_options_point ) {
require_once( pb_backupbuddy::plugin_path() . '/pluginbuddy/lib/media_library/media_library.php' );
$media_library = new pluginbuddy_medialibrary( $save_point, $default_options_point );
$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.
?> | ghostego/viscom-new | wp-content/plugins/backupbuddy/pluginbuddy/classes/ui.php | PHP | gpl-2.0 | 24,642 |
/*
* Copyright (C) 2008 Analog Devices Inc.
* Licensed under the GPL-2 or later.
*/
#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 /* */
| holyangel/LGE_G3 | arch/blackfin/mach-bf561/include/mach/gpio.h | C | gpl-2.0 | 1,299 |
/* dsdefs.h
*
* This is a "dummy" version of stdio.h etc. for systems which lack one.
* Rename it is stdio.h if needed.
*
* Functions printf() and sprintf() are defined here, but neither
* of them do anything useful.
*
* Version 1.2 Dag Bruck
* 1.3 Dag Bruck Updated for DYMOLA_DSPACE.
*
* Copyright (C) 1997-2004 Dynasim AB.
* All rights reserved.
*
*/
#ifndef DSDEFS_H
#define DSDEFS_H
#if !defined(RTLAB) && !defined(LABCAR) && !defined(DYM2DS) && !defined(FMU_SOURCE_SINGLE_UNIT)
#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(FMU_SOURCE_SINGLE_UNIT)
#define assert(test) (void)0
#endif
#endif
| SmarTS-Lab/iTesla_RaPId | Examples/line_equivalent/FMU/~FMUOutput/sources/dsdefs.h | C | gpl-3.0 | 991 |
""" 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',
'unicodelittleunmarked': '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',
}
| remybaranx/qtaste | tools/jython/lib/Lib/encodings/aliases.py | Python | gpl-3.0 | 2,790 |
<?php
require_once "$CFG->dirroot/lib/formslib.php";
require_once "$CFG->dirroot/mod/facetoface/lib.php";
class mod_facetoface_sitenotice_form 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('conditionsexplanation', 'facetoface'));
// Show all custom fields
$customfields = $this->_customdata['customfields'];
facetoface_add_customfields_to_form($mform, $customfields, true);
$this->add_action_buttons();
}
}
| mynameisdongyoung/Face-to-Face2.0 | sitenotice_form.php | PHP | gpl-3.0 | 1,228 |
/*******************************************************************************
* You may amend and distribute as you like, but don't remove this header!
*
* EPPlus provides server-side generation of Excel 2007/2010 spreadsheets.
* See http://www.codeplex.com/EPPlus for details.
*
* Copyright (C) 2011 Jan Källman
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php
* If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html
*
* All code and executables are provided "as is" with no warranty either express or implied.
* The author accepts no liability for any damage or loss of business that this product may cause.
*
* Code change notes:
*
* Author Change Date
* ******************************************************************************
* Eyal Seagull Added 2012-04-03
*******************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Xml;
using OfficeOpenXml.ConditionalFormatting.Contracts;
namespace OfficeOpenXml.ConditionalFormatting
{
/// <summary>
/// ExcelConditionalFormattingTop
/// </summary>
public class ExcelConditionalFormattingTop
: ExcelConditionalFormattingRule,
IExcelConditionalFormattingTopBottomGroup
{
/****************************************************************************************/
#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 ExcelConditionalFormattingTop(
ExcelAddress address,
int priority,
ExcelWorksheet worksheet,
XmlNode itemElementNode,
XmlNamespaceManager namespaceManager)
: base(
eExcelConditionalFormattingRuleType.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 ExcelConditionalFormattingTop(
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 ExcelConditionalFormattingTop(
ExcelAddress address,
int priority,
ExcelWorksheet worksheet)
: this(
address,
priority,
worksheet,
null,
null)
{
}
#endregion Constructors
/****************************************************************************************/
}
} | wtsi-swat/eq_exporter | epplus_90cfd9a3a979/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTop.cs | C# | gpl-3.0 | 4,023 |
<?php
//============================================================+
// File name : example_052.php
// Begin : 2009-05-07
// Last Update : 2009-09-30
//
// Description : Example 052 for TCPDF class
// Certification Signature (experimental)
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com s.r.l.
// Via Della Pace, 11
// 09044 Quartucciu (CA)
// ITALY
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Certification Signature (experimental)
* @author Nicola Asuni
* @copyright 2004-2009 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
* @link http://tcpdf.org
* @license http://www.gnu.org/copyleft/lesser.html LGPL
* @since 2009-05-07
*/
require_once('../config/lang/eng.php');
require_once('../tcpdf.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, 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, PDF_HEADER_LOGO_WIDTH, 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->SetDefaultMonospacedFont(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(PDF_IMAGE_SCALE_RATIO);
//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://www.tcpdf.org',
);
// 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="#FF0000">digitally signed document</b> using the default (example) <b>tcpdf.crt</b> certificate.<br />To validate this signature you have to load the <b>tcpdf.fdf</b> on the Arobat Reader to add the certificate to List of Trusted Identities.<br /><br />For more information check the source code of this example and the source code documentation for the <i>setSignature()</i> method.<br /><br /><a href="http://www.tcpdf.org">www.tcpdf.org</a>.';
$pdf->writeHTML($text, true, 0, true, 0);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_052.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+
?>
| mfandrade/siac | vendors/tcpdf/examples/example_052.php | PHP | gpl-3.0 | 3,586 |
// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -Wno-signed-unsigned-wchar -verify=allow-signed -DSKIP_ERROR_TESTS %s
// allow-signed-no-diagnostics
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
| sabel83/metashell | 3rd/templight/clang/test/SemaCXX/wchar_t.cpp | C++ | gpl-3.0 | 1,004 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML XMLNS="http://www.w3.org/1999/xhtml">
<HEAD >
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>unixODBC</TITLE>
<META NAME="generator" CONTENT="SlickEdit">
<!-- leave this for stats -->
<LINK REL="stylesheet"
HREF="style.css"
TYPE="text/css" MEDIA="screen">
<STYLE TYPE="text/css" MEDIA="screen">
body { background: url("background.jpg"); }
#page { background: url("body.jpg") repeat-y top; border: none; }
#header { background: url("header.gif") no-repeat bottom center; }
#footer { background: url("footer.jpg") no-repeat bottom; border: none;}
#header { padding: 22px 30px 0px 30px; height: 56px; width: 690px; }
</STYLE>
</HEAD>
<BODY>
<DIV ID="page">
<DIV ID="header">
<A HREF="http://www.unixodbc.org/"><IMG
SRC="icon64.png"
ALIGN="right"
BORDER="0" HSPACE="0" VSPACE="0"></A> <H1>unixODBC</H1>
<DIV CLASS="description">
Standards compliant, open source, database connectivity for everyone.
</DIV>
</DIV>
<DIV ID="content" CLASS="widecolumn">
<DIV STYLE="text-align: center;">
<SPAN
STYLE="font-weight: bold;">
Home
</SPAN>
| <A HREF="News.html">News</A> | <A
HREF="Documentation.html">Documentation</A> | <A
HREF="Drivers.html">Drivers</A> | <A
HREF="Support.html">Support</A> | <A
HREF="Downloads.html">Downloads</A>
</DIV>
<DIV CLASS="post" ID="post-68">
<DIV CLASS="entrytext">
<TABLE>
<TR>
<TD><H2>unixODBC is...</H2></TD>
<TD><H2>News</H2></TD>
</TR>
<TR>
<TD><BR>unixODBC is an implementation of the ODBC standard which is;
<UL>
<LI>
open source
</LI>
<LI>
licensed under LGPL/GPL
</LI>
<LI>
community developed and community supported
</LI>
<LI>
proven with over a decade of active use/development
</LI>
</UL>
</TD>
<TD>
<HR STYLE="width: 100%; height: 2px;">
<SPAN STYLE="color: rgb(192, 192, 192);">
March 15th 2007
</SPAN>
<BR>
<DIV STYLE="margin-left: 40px;">
New look for unixodbc.org
<DIV STYLE="margin-left: 40px;">
The old web site was serving the project fine but it seemed
like it was about time to make it all 'fresh'. We hope you
find it more pleasing to use.
</DIV>
</DIV>
<SPAN
STYLE="color: rgb(192, 192, 192);">
October 13th 2006
</SPAN>
<BR>
<DIV STYLE="margin-left: 40px;">
2.2.12 Released<BR>
</DIV>
<A HREF="News.html"><SMALL>More...</A></TD>
</TR>
<TR>
<TD><H2>Key features...</H2></TD>
<TD><H2>Architecture</H2></TD>
</TR>
<TR>
<TD STYLE="vertical-align: top;"><BR>
<SPAN STYLE="font-weight: bold;">
Software Development Kit
</SPAN>
(SDK) - Develop ODBC applications and drivers using the C
language and the unixODBC SDK.<BR> <BR>
<SPAN STYLE="font-weight: bold;">
Driver Manager
</SPAN>
(DM) - The unixODBC DM allows the end-User to switch data
sources without recompiling/linking application source code. The
application does not have to be linked to a specific vendors
product.<BR> <BR>
<SPAN STYLE="font-weight: bold;">
Tools
</SPAN>
- unixODBC includes CrossPlatform command-line and GUI tools to
make working with ODBC easy.<BR>
</TD>
<TD STYLE="vertical-align: top;"><IMG ALIGN="LEFT"
STYLE="width: 200px; height: 175px;" ALT="" SRC="Splash.png">
<P>Applications typically
link with the unixODBC
Driver Manager (DM) which then
uses the appropriate Driver to
communicate with the data
source. The DM understands ODBC
but relies on the Driver to
understand specifics of the data
source.</P>
<P>The Driver is typically provided by the data source
Vendor. The Driver understands ODBC and the specifics of the
data source.</P>
</TD>
</TR>
</TABLE>
<BR>
<TABLE CLASS =codebox>
<TR>
<TD
STYLE="vertical-align: top; background-color: rgb(102, 102, 102); width: 33%;">
<SPAN STYLE="font-weight: bold;">
CrossPlatform<BR>
<BR>
</SPAN>
Applications built using unixODBC are compatible with the
Microsoft implementation of ODBC. unixODBC is provided with all
majour Linux distributions. unixODBC has been ported to all
majour UNIX and UNIX-like platforms;<BR>
<DIV STYLE="margin-left: 40px;">
- Linux, Solaris, SGI, etc<BR>
- VMS, OS/2, etc<BR>
</DIV>
</TD>
<TD
STYLE="vertical-align: top; background-color: rgb(102, 102, 102); width: 33%;">
<SPAN STYLE="font-weight: bold;">
CrossDatabase
</SPAN>
<BR>
<BR>
unixODBC supports drivers from all majour database vendors including;<BR>
<DIV STYLE="margin-left: 40px;">
- Oracle<BR>
- DB2<BR>
- Interbase<BR>
- Mimer<BR>
- MySQL<BR>
- others<BR>
</DIV>
</TD>
<TD
STYLE="vertical-align: top; background-color: rgb(102, 102, 102); width: 33%;">
<SPAN STYLE="font-weight: bold;">
License
</SPAN>
<BR>
<BR>
unixODBC was developed by the open source community and is provided under the LGPL and GPL licenses. Commercial applications can be developed using unixODBC without paying for a license or royalty. Free support is provided by the community.
</TD>
</TR>
<TR>
<TD STYLE="vertical-align: top;"><A
HREF="CrossPlatform.html">More...</A></TD>
<TD STYLE="vertical-align: top;"><A
HREF="CrossDatabase.html">More...</A></TD>
<TD STYLE="vertical-align: top;"><A HREF="License.html">More...</A></TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</P>
</DIV>
</DIV>
</DIV>
<DIV ID="footer">
<P>
--<BR>
<A HREF=mailto:pharvey@peterharvey.org>Peter Harvey</A>
</P>
</DIV>
</DIV>
</BODY>
</HTML>
| TextusData/Mover | thirdparty/unixODBC-2.3.1/doc/index.html | HTML | gpl-3.0 | 8,359 |
var Deferred = require('./')
var assert = require('assert')
var d = new Deferred()
var t = require('tap')
t.match(d, {
resolve: Function,
reject: Function,
promise: Object
})
| gerrytucker78/emse_capstone_project | services/node_modules/nodeunit/node_modules/tap/node_modules/trivial-deferred/test.js | JavaScript | gpl-3.0 | 181 |
<?php
/**
* The template for displaying product widget entries.
*
* This template can be overridden by copying it to yourtheme/woocommerce/content-widget-reviews.php
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* @see https://docs.woocommerce.com/document/template-structure/
* @package WooCommerce\Templates
* @version 3.4.0
*/
defined( 'ABSPATH' ) || exit;
?>
<li>
<?php do_action( 'woocommerce_widget_product_review_item_start', $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( 'woocommerce_widget_product_review_item_end', $args ); ?>
</li>
| Ninos/woocommerce | templates/content-widget-reviews.php | PHP | gpl-3.0 | 1,305 |
/**
* Aptana Studio
* Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
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);
}
/**
* MarkerManager_MarkerIDIsDefined
*/
public static String MarkerManager_MarkerIDIsDefined;
/**
* UniformResourceMarker_UniformResourceMarketInfoNull
*/
public static String UniformResourceMarker_UniformResourceMarketInfoNull;
}
| HossainKhademian/Studio3 | plugins/com.aptana.core/src/com/aptana/core/internal/resources/Messages.java | Java | gpl-3.0 | 969 |
/* radare2 - LGPL - Copyright 2017 - condret */
#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 id_storage_reallocate(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 (!id_storage_reallocate (storage, n * 2)) {
return false;
}
} else if (n != (storage->pool->last_id)) {
if (!id_storage_reallocate (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]) {
id_storage_reallocate (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)) {
id_storage_reallocate (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 r_id_storage_foreach(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);
}
| Maijin/radare2 | libr/util/idpool.c | C | gpl-3.0 | 4,681 |
url: http://sanskrit.inria.fr/cgi-bin/SKT/sktreader?t=VH;lex=SH;cache=f;st=t;us=f;cp=t;text=tathaastu;topic=;abs=f;allSol=2;mode=p;cpts=<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<title>Sanskrit Reader Companion</title>
<meta name="author" content="Gérard Huet">
<meta property="dc:datecopyrighted" content="2016">
<meta property="dc:rightsholder" content="Gérard Huet">
<meta name="keywords" content="dictionary,sanskrit,heritage,dictionnaire,sanscrit,india,inde,indology,linguistics,panini,digital humanities,cultural heritage,computational linguistics,hypertext lexicon">
<link rel="stylesheet" type="text/css" href="http://sanskrit.inria.fr/DICO/style.css" media="screen,tv">
<link rel="shortcut icon" href="http://sanskrit.inria.fr/IMAGES/favicon.ico">
<script type="text/javascript" src="http://sanskrit.inria.fr/DICO/utf82VH.js"></script>
</head>
<body class="chamois_back">
<br><h1 class="title">The Sanskrit Reader Companion</h1>
<table class="chamois_back" border="0" cellpadding="0%" cellspacing="15pt" width="100%">
<tr><td>
<p align="center">
<div class="latin16"><a class="green" href="/cgi-bin/SKT/sktgraph?t=VH;lex=SH;cache=f;st=t;us=f;cp=t;text=tathaastu;topic=;abs=f;cpts=;mode=g">✓</a> Show Summary of Solutions
</p>
Input:
<span class="red16">tathāstu</span><hr>
<br>
Sentence:
<span class="deva16" lang="sa">तथास्तु</span><br>
may be analysed as:</div><br>
<hr>
<span class="blue">Solution 1 : <a class="green" href="/cgi-bin/SKT/sktparser?t=VH;lex=SH;cache=f;st=t;us=f;cp=t;text=tathaastu;topic=;abs=f;cpts=;mode=p;n=1">✓</a></span><br>
[ <span class="blue" title="0"><b>tathā</b></span><table class="mauve_back">
<tr><th><span class="latin12"><tr><th><span class="latin12">{ adv. }[<a class="navy" href="http://sanskrit.inria.fr/DICO/28.html#tathaa"><i>tathā</i></a>]</span></th></tr></span></th></tr></table>⟨<span class="magenta">ā</span><span class="green">|</span><span class="magenta">a</span><span class="blue"> → </span><span class="red">ā</span>⟩]
<br>
[ <span class="blue" title="3"><b>astu</b></span><table class="carmin_back">
<tr><th><span class="latin12"><tr><th><span class="latin12">{ imp. [2] ac. sg. 3 }[<a class="navy" href="http://sanskrit.inria.fr/DICO/7.html#as#1"><i>as_1</i></a>]</span></th></tr></span></th></tr></table>⟨⟩]
<br>
<br>
<hr>
<span class="magenta">1</span><span class="blue"> solution</span><span class="blue"> kept among </span><span class="magenta">1</span><br>
<br>
<hr>
<br>
<br>
</td></tr></table>
<table class="pad60">
<tr><td></td></tr></table>
<div class="enpied">
<table class="bandeau"><tr><td>
<a href="http://ocaml.org"><img src="http://sanskrit.inria.fr/IMAGES/ocaml.gif" alt="Le chameau Ocaml" height="50"></a>
</td><td>
<table class="center">
<tr><td>
<a href="http://sanskrit.inria.fr/index.fr.html"><b>Top</b></a> |
<a href="http://sanskrit.inria.fr/DICO/index.fr.html"><b>Index</b></a> |
<a href="http://sanskrit.inria.fr/DICO/index.fr.html#stemmer"><b>Stemmer</b></a> |
<a href="http://sanskrit.inria.fr/DICO/grammar.fr.html"><b>Grammar</b></a> |
<a href="http://sanskrit.inria.fr/DICO/sandhi.fr.html"><b>Sandhi</b></a> |
<a href="http://sanskrit.inria.fr/DICO/reader.fr.html"><b>Reader</b></a> |
<a href="http://sanskrit.inria.fr/faq.fr.html"><b>Help</b></a> |
<a href="http://sanskrit.inria.fr/portal.fr.html"><b>Portal</b></a>
</td></tr><tr><td>
© Gérard Huet 1994-2016</td></tr></table></td><td>
<a href="http://www.inria.fr/"><img src="http://sanskrit.inria.fr/IMAGES/logo_inria.png" alt="Logo Inria" height="50"></a>
<br></td></tr></table></div>
</body>
</html>
| sanskritiitd/sanskrit | uohCorpus.fil/uoh/uoh.filteredcorpus.txt_output/upamiti-3_ext.txt.out.dict_16534_inr.html | HTML | gpl-3.0 | 3,697 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.scenes;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.Statistics;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.items.Generator;
import com.shatteredpixel.shatteredpixeldungeon.levels.Level;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndError;
import com.shatteredpixel.shatteredpixeldungeon.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.FileNotFoundException;
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 FileNotFoundException) 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
}
}
| Lobz/reforged-pixel-dungeon | src/com/shatteredpixel/shatteredpixeldungeon/scenes/InterlevelScene.java | Java | gpl-3.0 | 7,657 |
-- predictability
SET synchronous_commit = on;
DROP TABLE IF EXISTS replication_example;
SELECT 'init' FROM pg_create_logical_replication_slot('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 pg_logical_slot_get_changes('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 pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
SELECT pg_drop_replication_slot('regression_slot');
DROP TABLE IF EXISTS replication_example;
| Postgres-XL/Postgres-XL | contrib/test_decoding/sql/rewrite.sql | SQL | mpl-2.0 | 1,989 |
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# 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
# rustc-nightly-HOST-TRIPLE.tar.gz, whereas the stable compiler is named
# rustc-VERSION-HOST-TRIPLE.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://static-rust-lang-org.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 `rust-std-nightly-TRIPLE.tar.gz` for the nightly
# releases, or rust-std-VERSION-TRIPLE.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://static-rust-lang-org.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 bootstrap_rustc_docs(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://static-rust-lang-org.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 bootstrap_hsts_preload(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/transport_security_state_static.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:
pins_and_static_preloads = json.loads(content_json)
entries = {
"entries": [
{
"host": e["name"],
"include_subdomains": e.get("include_subdomains", False)
}
for e in pins_and_static_preloads["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 bootstrap_pub_suffix(self, force=False):
list_url = "https://publicsuffix.org/list/public_suffix_list.dat"
dst_filename = path.join(self.context.topdir, "resources", "public_domains.txt")
not_implemented_case = 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 not_implemented_case.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.")
| ddrmanxbxfr/servo | python/servo/bootstrap_commands.py | Python | mpl-2.0 | 14,058 |
/* TL.Point
Inspired by Leaflet
TL.Point represents a point with x and y coordinates.
================================================== */
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) + ')';
}
}; | tkandala/TimelineJS3 | source/js/dom/TL.Point.js | JavaScript | mpl-2.0 | 1,360 |
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
DROP TABLE IF EXISTS `assessment_aiclassifier`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_aiclassifier` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`classifier_set_id` int(11) NOT NULL,
`criterion_id` int(11) NOT NULL,
`classifier_data` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
KEY `assessment_aiclassifier_714175dc` (`classifier_set_id`),
KEY `assessment_aiclassifier_a36470e4` (`criterion_id`),
CONSTRAINT `classifier_set_id_refs_id_e0204c20f80cbf6` FOREIGN KEY (`classifier_set_id`) REFERENCES `assessment_aiclassifierset` (`id`),
CONSTRAINT `criterion_id_refs_id_5b95f648e6ab97f2` FOREIGN KEY (`criterion_id`) REFERENCES `assessment_criterion` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_aiclassifierset`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_aiclassifierset` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rubric_id` int(11) NOT NULL,
`created_at` datetime NOT NULL,
`algorithm_id` varchar(128) NOT NULL,
`course_id` varchar(40) NOT NULL,
`item_id` varchar(128) NOT NULL,
PRIMARY KEY (`id`),
KEY `assessment_aiclassifierset_27cb9807` (`rubric_id`),
KEY `assessment_aiclassifierset_3b1c9c31` (`created_at`),
KEY `assessment_aiclassifierset_53012c1e` (`algorithm_id`),
KEY `assessment_aiclassifierset_ff48d8e5` (`course_id`),
KEY `assessment_aiclassifierset_67b70d25` (`item_id`),
CONSTRAINT `rubric_id_refs_id_39819374c037b8e4` FOREIGN KEY (`rubric_id`) REFERENCES `assessment_rubric` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_aigradingworkflow`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_aigradingworkflow` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uuid` varchar(36) NOT NULL,
`scheduled_at` datetime NOT NULL,
`completed_at` datetime DEFAULT NULL,
`submission_uuid` varchar(128) NOT NULL,
`classifier_set_id` int(11) DEFAULT NULL,
`algorithm_id` varchar(128) NOT NULL,
`rubric_id` int(11) NOT NULL,
`assessment_id` int(11) DEFAULT NULL,
`student_id` varchar(40) NOT NULL,
`item_id` varchar(128) NOT NULL,
`course_id` varchar(40) NOT NULL,
`essay_text` longtext NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `assessment_aigradingworkflow_uuid_492e936265ecbfd2_uniq` (`uuid`),
KEY `assessment_aigradingworkflow_2bbc74ae` (`uuid`),
KEY `assessment_aigradingworkflow_4bacaa90` (`scheduled_at`),
KEY `assessment_aigradingworkflow_a2fd3af6` (`completed_at`),
KEY `assessment_aigradingworkflow_39d020e6` (`submission_uuid`),
KEY `assessment_aigradingworkflow_714175dc` (`classifier_set_id`),
KEY `assessment_aigradingworkflow_53012c1e` (`algorithm_id`),
KEY `assessment_aigradingworkflow_27cb9807` (`rubric_id`),
KEY `assessment_aigradingworkflow_c168f2dc` (`assessment_id`),
KEY `assessment_aigradingworkflow_42ff452e` (`student_id`),
KEY `assessment_aigradingworkflow_67b70d25` (`item_id`),
KEY `assessment_aigradingworkflow_ff48d8e5` (`course_id`),
CONSTRAINT `assessment_id_refs_id_2b6c2601d8478e7` FOREIGN KEY (`assessment_id`) REFERENCES `assessment_assessment` (`id`),
CONSTRAINT `classifier_set_id_refs_id_4f95ef541e9046d1` FOREIGN KEY (`classifier_set_id`) REFERENCES `assessment_aiclassifierset` (`id`),
CONSTRAINT `rubric_id_refs_id_7b31a4b7dc2a0464` FOREIGN KEY (`rubric_id`) REFERENCES `assessment_rubric` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_aitrainingworkflow`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_aitrainingworkflow` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uuid` varchar(36) NOT NULL,
`algorithm_id` varchar(128) NOT NULL,
`classifier_set_id` int(11) DEFAULT NULL,
`scheduled_at` datetime NOT NULL,
`completed_at` datetime DEFAULT NULL,
`item_id` varchar(128) NOT NULL,
`course_id` varchar(40) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `assessment_aitrainingworkflow_uuid_284fdaa93019f8ef_uniq` (`uuid`),
KEY `assessment_aitrainingworkflow_2bbc74ae` (`uuid`),
KEY `assessment_aitrainingworkflow_53012c1e` (`algorithm_id`),
KEY `assessment_aitrainingworkflow_714175dc` (`classifier_set_id`),
KEY `assessment_aitrainingworkflow_4bacaa90` (`scheduled_at`),
KEY `assessment_aitrainingworkflow_a2fd3af6` (`completed_at`),
KEY `assessment_aitrainingworkflow_67b70d25` (`item_id`),
KEY `assessment_aitrainingworkflow_ff48d8e5` (`course_id`),
CONSTRAINT `classifier_set_id_refs_id_4f31dd8e0dcc7412` FOREIGN KEY (`classifier_set_id`) REFERENCES `assessment_aiclassifierset` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_aitrainingworkflow_training_examples`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_aitrainingworkflow_training_examples` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`aitrainingworkflow_id` int(11) NOT NULL,
`trainingexample_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `assessment_aitraini_aitrainingworkflow_id_4b50cfbece05470a_uniq` (`aitrainingworkflow_id`,`trainingexample_id`),
KEY `assessment_aitrainingworkflow_training_examples_a57f9195` (`aitrainingworkflow_id`),
KEY `assessment_aitrainingworkflow_training_examples_ea4da31f` (`trainingexample_id`),
CONSTRAINT `trainingexample_id_refs_id_78a2a13b0bf13a24` FOREIGN KEY (`trainingexample_id`) REFERENCES `assessment_trainingexample` (`id`),
CONSTRAINT `aitrainingworkflow_id_refs_id_2840acb945c30582` FOREIGN KEY (`aitrainingworkflow_id`) REFERENCES `assessment_aitrainingworkflow` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_assessment`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_assessment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`submission_uuid` varchar(128) NOT NULL,
`rubric_id` int(11) NOT NULL,
`scored_at` datetime NOT NULL,
`scorer_id` varchar(40) NOT NULL,
`score_type` varchar(2) NOT NULL,
`feedback` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `assessment_assessment_39d020e6` (`submission_uuid`),
KEY `assessment_assessment_27cb9807` (`rubric_id`),
KEY `assessment_assessment_3227200` (`scored_at`),
KEY `assessment_assessment_9f54855a` (`scorer_id`),
CONSTRAINT `rubric_id_refs_id_287cd4a61ab6dbc4` FOREIGN KEY (`rubric_id`) REFERENCES `assessment_rubric` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_assessmentfeedback`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_assessmentfeedback` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`submission_uuid` varchar(128) NOT NULL,
`feedback_text` longtext NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `submission_uuid` (`submission_uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_assessmentfeedback_assessments`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_assessmentfeedback_assessments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`assessmentfeedback_id` int(11) NOT NULL,
`assessment_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `assessment_assessmen_assessmentfeedback_id_36925aaa1a839ac_uniq` (`assessmentfeedback_id`,`assessment_id`),
KEY `assessment_assessmentfeedback_assessments_58f1f0d` (`assessmentfeedback_id`),
KEY `assessment_assessmentfeedback_assessments_c168f2dc` (`assessment_id`),
CONSTRAINT `assessment_id_refs_id_170e92e6e7fd607e` FOREIGN KEY (`assessment_id`) REFERENCES `assessment_assessment` (`id`),
CONSTRAINT `assessmentfeedback_id_refs_id_226c8f1e91bbd347` FOREIGN KEY (`assessmentfeedback_id`) REFERENCES `assessment_assessmentfeedback` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_assessmentfeedback_options`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_assessmentfeedback_options` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`assessmentfeedback_id` int(11) NOT NULL,
`assessmentfeedbackoption_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `assessment_assessmen_assessmentfeedback_id_14efc9eea8f4c83_uniq` (`assessmentfeedback_id`,`assessmentfeedbackoption_id`),
KEY `assessment_assessmentfeedback_options_58f1f0d` (`assessmentfeedback_id`),
KEY `assessment_assessmentfeedback_options_4e523d64` (`assessmentfeedbackoption_id`),
CONSTRAINT `assessmentfeedbackoption_id_refs_id_597390b9cdf28acd` FOREIGN KEY (`assessmentfeedbackoption_id`) REFERENCES `assessment_assessmentfeedbackoption` (`id`),
CONSTRAINT `assessmentfeedback_id_refs_id_5383f6e95c27c412` FOREIGN KEY (`assessmentfeedback_id`) REFERENCES `assessment_assessmentfeedback` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_assessmentfeedbackoption`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_assessmentfeedbackoption` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `text` (`text`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_assessmentpart`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_assessmentpart` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`assessment_id` int(11) NOT NULL,
`option_id` int(11),
`feedback` longtext NOT NULL,
`criterion_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `assessment_assessmentpart_c168f2dc` (`assessment_id`),
KEY `assessment_assessmentpart_2f3b0dc9` (`option_id`),
KEY `assessment_assessmentpart_a36470e4` (`criterion_id`),
CONSTRAINT `criterion_id_refs_id_507d3ff2eeb3dc44` FOREIGN KEY (`criterion_id`) REFERENCES `assessment_criterion` (`id`),
CONSTRAINT `assessment_id_refs_id_5cb07795bff26444` FOREIGN KEY (`assessment_id`) REFERENCES `assessment_assessment` (`id`),
CONSTRAINT `option_id_refs_id_5353f6b204439dd5` FOREIGN KEY (`option_id`) REFERENCES `assessment_criterionoption` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_criterion`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_criterion` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rubric_id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`order_num` int(10) unsigned NOT NULL,
`prompt` longtext NOT NULL,
`label` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `assessment_criterion_27cb9807` (`rubric_id`),
CONSTRAINT `rubric_id_refs_id_48945684f2f4f3c4` FOREIGN KEY (`rubric_id`) REFERENCES `assessment_rubric` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_criterionoption`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_criterionoption` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`criterion_id` int(11) NOT NULL,
`order_num` int(10) unsigned NOT NULL,
`points` int(10) unsigned NOT NULL,
`name` varchar(100) NOT NULL,
`explanation` longtext NOT NULL,
`label` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `assessment_criterionoption_a36470e4` (`criterion_id`),
CONSTRAINT `criterion_id_refs_id_4aabcea0d2645232` FOREIGN KEY (`criterion_id`) REFERENCES `assessment_criterion` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_peerworkflow`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_peerworkflow` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` varchar(40) NOT NULL,
`item_id` varchar(128) NOT NULL,
`course_id` varchar(40) NOT NULL,
`submission_uuid` varchar(128) NOT NULL,
`created_at` datetime NOT NULL,
`completed_at` datetime DEFAULT NULL,
`grading_completed_at` datetime,
PRIMARY KEY (`id`),
UNIQUE KEY `submission_uuid` (`submission_uuid`),
KEY `assessment_peerworkflow_42ff452e` (`student_id`),
KEY `assessment_peerworkflow_67b70d25` (`item_id`),
KEY `assessment_peerworkflow_ff48d8e5` (`course_id`),
KEY `assessment_peerworkflow_3b1c9c31` (`created_at`),
KEY `assessment_peerworkflow_a2fd3af6` (`completed_at`),
KEY `assessment_peerworkflow_course_id_5ca23fddca9b630d` (`course_id`,`item_id`,`student_id`),
KEY `assessment_peerworkflow_dcd62131` (`grading_completed_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_peerworkflowitem`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_peerworkflowitem` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`scorer_id` int(11) NOT NULL,
`author_id` int(11) NOT NULL,
`submission_uuid` varchar(128) NOT NULL,
`started_at` datetime NOT NULL,
`assessment_id` int(11) DEFAULT NULL,
`scored` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `assessment_peerworkflowitem_9f54855a` (`scorer_id`),
KEY `assessment_peerworkflowitem_cc846901` (`author_id`),
KEY `assessment_peerworkflowitem_39d020e6` (`submission_uuid`),
KEY `assessment_peerworkflowitem_d6e710e4` (`started_at`),
KEY `assessment_peerworkflowitem_c168f2dc` (`assessment_id`),
CONSTRAINT `assessment_id_refs_id_61929d36f69a86a1` FOREIGN KEY (`assessment_id`) REFERENCES `assessment_assessment` (`id`),
CONSTRAINT `author_id_refs_id_5b3f4e759547df0` FOREIGN KEY (`author_id`) REFERENCES `assessment_peerworkflow` (`id`),
CONSTRAINT `scorer_id_refs_id_5b3f4e759547df0` FOREIGN KEY (`scorer_id`) REFERENCES `assessment_peerworkflow` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_rubric`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_rubric` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content_hash` varchar(40) NOT NULL,
`structure_hash` varchar(40) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `content_hash` (`content_hash`),
KEY `assessment_rubric_36e74b05` (`structure_hash`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_studenttrainingworkflow`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_studenttrainingworkflow` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`submission_uuid` varchar(128) NOT NULL,
`student_id` varchar(40) NOT NULL,
`item_id` varchar(128) NOT NULL,
`course_id` varchar(40) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `assessment_studenttrainin_submission_uuid_6d32c6477719d68f_uniq` (`submission_uuid`),
KEY `assessment_studenttrainingworkflow_39d020e6` (`submission_uuid`),
KEY `assessment_studenttrainingworkflow_42ff452e` (`student_id`),
KEY `assessment_studenttrainingworkflow_67b70d25` (`item_id`),
KEY `assessment_studenttrainingworkflow_ff48d8e5` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_studenttrainingworkflowitem`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_studenttrainingworkflowitem` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`workflow_id` int(11) NOT NULL,
`order_num` int(10) unsigned NOT NULL,
`started_at` datetime NOT NULL,
`completed_at` datetime DEFAULT NULL,
`training_example_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `assessment_studenttrainingworkf_order_num_1391289faa95b87c_uniq` (`order_num`,`workflow_id`),
KEY `assessment_studenttrainingworkflowitem_26cddbc7` (`workflow_id`),
KEY `assessment_studenttrainingworkflowitem_541d6663` (`training_example_id`),
CONSTRAINT `training_example_id_refs_id_21003d6e7d3f36e4` FOREIGN KEY (`training_example_id`) REFERENCES `assessment_trainingexample` (`id`),
CONSTRAINT `workflow_id_refs_id_5a3573250ce50a30` FOREIGN KEY (`workflow_id`) REFERENCES `assessment_studenttrainingworkflow` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_trainingexample`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_trainingexample` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`raw_answer` longtext NOT NULL,
`rubric_id` int(11) NOT NULL,
`content_hash` varchar(40) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `content_hash` (`content_hash`),
KEY `assessment_trainingexample_27cb9807` (`rubric_id`),
CONSTRAINT `rubric_id_refs_id_36f1317b7750db21` FOREIGN KEY (`rubric_id`) REFERENCES `assessment_rubric` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `assessment_trainingexample_options_selected`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assessment_trainingexample_options_selected` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`trainingexample_id` int(11) NOT NULL,
`criterionoption_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `assessment_trainingexa_trainingexample_id_60940991fb17d27d_uniq` (`trainingexample_id`,`criterionoption_id`),
KEY `assessment_trainingexample_options_selected_ea4da31f` (`trainingexample_id`),
KEY `assessment_trainingexample_options_selected_843fa247` (`criterionoption_id`),
CONSTRAINT `criterionoption_id_refs_id_16ecec54bed5a465` FOREIGN KEY (`criterionoption_id`) REFERENCES `assessment_criterionoption` (`id`),
CONSTRAINT `trainingexample_id_refs_id_797bc2db5f0faa8d` FOREIGN KEY (`trainingexample_id`) REFERENCES `assessment_trainingexample` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `auth_group`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `auth_group` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(80) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `auth_group_permissions`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `auth_group_permissions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`group_id` int(11) NOT NULL,
`permission_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `group_id` (`group_id`,`permission_id`),
KEY `auth_group_permissions_bda51c3c` (`group_id`),
KEY `auth_group_permissions_1e014c8f` (`permission_id`),
CONSTRAINT `group_id_refs_id_3cea63fe` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`),
CONSTRAINT `permission_id_refs_id_a7792de1` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `auth_permission`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `auth_permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`content_type_id` int(11) NOT NULL,
`codename` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `content_type_id` (`content_type_id`,`codename`),
KEY `auth_permission_e4470c6e` (`content_type_id`),
CONSTRAINT `content_type_id_refs_id_728de91f` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=448 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `auth_registration`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `auth_registration` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`activation_key` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
UNIQUE KEY `activation_key` (`activation_key`),
CONSTRAINT `user_id_refs_id_3fe8066a03e5b0b5` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `auth_user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `auth_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`first_name` varchar(30) NOT NULL,
`last_name` varchar(30) NOT NULL,
`email` varchar(75) NOT NULL,
`password` varchar(128) NOT NULL,
`is_staff` tinyint(1) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`is_superuser` tinyint(1) NOT NULL,
`last_login` datetime NOT NULL,
`date_joined` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `auth_user_groups`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `auth_user_groups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`group_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`,`group_id`),
KEY `auth_user_groups_fbfc09f1` (`user_id`),
KEY `auth_user_groups_bda51c3c` (`group_id`),
CONSTRAINT `user_id_refs_id_831107f1` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`),
CONSTRAINT `group_id_refs_id_f0ee9890` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `auth_user_user_permissions`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `auth_user_user_permissions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`permission_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`,`permission_id`),
KEY `auth_user_user_permissions_fbfc09f1` (`user_id`),
KEY `auth_user_user_permissions_1e014c8f` (`permission_id`),
CONSTRAINT `user_id_refs_id_f2045483` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`),
CONSTRAINT `permission_id_refs_id_67e79cb` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `auth_userprofile`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `auth_userprofile` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`language` varchar(255) NOT NULL,
`location` varchar(255) NOT NULL,
`meta` longtext NOT NULL,
`courseware` varchar(255) NOT NULL,
`gender` varchar(6),
`mailing_address` longtext,
`year_of_birth` int(11),
`level_of_education` varchar(6),
`goals` longtext,
`allow_certificate` tinyint(1) NOT NULL,
`country` varchar(2),
`city` longtext,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
KEY `auth_userprofile_52094d6e` (`name`),
KEY `auth_userprofile_8a7ac9ab` (`language`),
KEY `auth_userprofile_b54954de` (`location`),
KEY `auth_userprofile_fca3d292` (`gender`),
KEY `auth_userprofile_d85587` (`year_of_birth`),
KEY `auth_userprofile_551e365c` (`level_of_education`),
CONSTRAINT `user_id_refs_id_3daaa960628b4c11` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `bulk_email_courseauthorization`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bulk_email_courseauthorization` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_id` varchar(255) NOT NULL,
`email_enabled` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `bulk_email_courseauthorization_course_id_4f6cee675bf93275_uniq` (`course_id`),
KEY `bulk_email_courseauthorization_ff48d8e5` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `bulk_email_courseemail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bulk_email_courseemail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sender_id` int(11) DEFAULT NULL,
`slug` varchar(128) NOT NULL,
`subject` varchar(128) NOT NULL,
`html_message` longtext,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`course_id` varchar(255) NOT NULL,
`to_option` varchar(64) NOT NULL,
`text_message` longtext,
`template_name` varchar(255),
`from_addr` varchar(255),
PRIMARY KEY (`id`),
KEY `bulk_email_courseemail_901f59e9` (`sender_id`),
KEY `bulk_email_courseemail_36af87d1` (`slug`),
KEY `bulk_email_courseemail_ff48d8e5` (`course_id`),
CONSTRAINT `sender_id_refs_id_5e8b8f9870ed6279` FOREIGN KEY (`sender_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `bulk_email_courseemailtemplate`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bulk_email_courseemailtemplate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`html_template` longtext,
`plain_template` longtext,
`name` varchar(255),
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `bulk_email_optout`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bulk_email_optout` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_id` varchar(255) NOT NULL,
`user_id` int(11),
PRIMARY KEY (`id`),
UNIQUE KEY `bulk_email_optout_course_id_368f7519b2997e1a_uniq` (`course_id`,`user_id`),
KEY `bulk_email_optout_ff48d8e5` (`course_id`),
KEY `bulk_email_optout_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_fc2bac99e68e67c` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `celery_taskmeta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `celery_taskmeta` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`task_id` varchar(255) NOT NULL,
`status` varchar(50) NOT NULL,
`result` longtext,
`date_done` datetime NOT NULL,
`traceback` longtext,
`hidden` tinyint(1) NOT NULL,
`meta` longtext,
PRIMARY KEY (`id`),
UNIQUE KEY `task_id` (`task_id`),
KEY `celery_taskmeta_c91f1bf` (`hidden`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `celery_tasksetmeta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `celery_tasksetmeta` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`taskset_id` varchar(255) NOT NULL,
`result` longtext NOT NULL,
`date_done` datetime NOT NULL,
`hidden` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `taskset_id` (`taskset_id`),
KEY `celery_tasksetmeta_c91f1bf` (`hidden`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `certificates_certificatewhitelist`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `certificates_certificatewhitelist` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`course_id` varchar(255) NOT NULL,
`whitelist` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `certificates_certificatewhitelist_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_517c1c6aa7ba9306` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `certificates_generatedcertificate`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `certificates_generatedcertificate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`download_url` varchar(128) NOT NULL,
`grade` varchar(5) NOT NULL,
`course_id` varchar(255) NOT NULL,
`key` varchar(32) NOT NULL,
`distinction` tinyint(1) NOT NULL,
`status` varchar(32) NOT NULL,
`verify_uuid` varchar(32) NOT NULL,
`download_uuid` varchar(32) NOT NULL,
`name` varchar(255) NOT NULL,
`created_date` datetime NOT NULL,
`modified_date` datetime NOT NULL,
`error_reason` varchar(512) NOT NULL,
`mode` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `certificates_generatedcertifica_course_id_1389f6b2d72f5e78_uniq` (`course_id`,`user_id`),
KEY `certificates_generatedcertificate_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_6c4fb3478e23bfe2` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `circuit_servercircuit`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `circuit_servercircuit` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`schematic` longtext NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `contentstore_videouploadconfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `contentstore_videouploadconfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`change_date` datetime NOT NULL,
`changed_by_id` int(11) DEFAULT NULL,
`enabled` tinyint(1) NOT NULL,
`profile_whitelist` longtext NOT NULL,
`status_whitelist` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `contentstore_videouploadconfig_16905482` (`changed_by_id`),
CONSTRAINT `changed_by_id_refs_id_31e0e2c8209c438f` FOREIGN KEY (`changed_by_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `course_action_state_coursererunstate`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `course_action_state_coursererunstate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created_time` datetime NOT NULL,
`updated_time` datetime NOT NULL,
`created_user_id` int(11) DEFAULT NULL,
`updated_user_id` int(11) DEFAULT NULL,
`course_key` varchar(255) NOT NULL,
`action` varchar(100) NOT NULL,
`state` varchar(50) NOT NULL,
`should_display` tinyint(1) NOT NULL,
`message` varchar(1000) NOT NULL,
`source_course_key` varchar(255) NOT NULL,
`display_name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `course_action_state_coursererun_course_key_cf5da77ed3032d6_uniq` (`course_key`,`action`),
KEY `course_action_state_coursererunstate_5b876fa2` (`created_user_id`),
KEY `course_action_state_coursererunstate_ceb2e2e7` (`updated_user_id`),
KEY `course_action_state_coursererunstate_b4b47e7a` (`course_key`),
KEY `course_action_state_coursererunstate_1bd4707b` (`action`),
KEY `course_action_state_coursererunstate_ebfe36dd` (`source_course_key`),
CONSTRAINT `created_user_id_refs_id_1334640c1744bdeb` FOREIGN KEY (`created_user_id`) REFERENCES `auth_user` (`id`),
CONSTRAINT `updated_user_id_refs_id_1334640c1744bdeb` FOREIGN KEY (`updated_user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `course_creators_coursecreator`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `course_creators_coursecreator` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`state_changed` datetime NOT NULL,
`state` varchar(24) NOT NULL,
`note` varchar(512) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
CONSTRAINT `user_id_refs_id_22dd4a06a0e6044` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `course_groups_courseusergroup`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `course_groups_courseusergroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`course_id` varchar(255) NOT NULL,
`group_type` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `course_groups_courseusergroup_name_63f7511804c52f38_uniq` (`name`,`course_id`),
KEY `course_groups_courseusergroup_ff48d8e5` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `course_groups_courseusergroup_users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `course_groups_courseusergroup_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`courseusergroup_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `course_groups_courseus_courseusergroup_id_46691806058983eb_uniq` (`courseusergroup_id`,`user_id`),
KEY `course_groups_courseusergroup_users_caee1c64` (`courseusergroup_id`),
KEY `course_groups_courseusergroup_users_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_779390fdbf33b47a` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`),
CONSTRAINT `courseusergroup_id_refs_id_43167b76d26180aa` FOREIGN KEY (`courseusergroup_id`) REFERENCES `course_groups_courseusergroup` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `course_groups_courseusergrouppartitiongroup`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `course_groups_courseusergrouppartitiongroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_user_group_id` int(11) NOT NULL,
`partition_id` int(11) NOT NULL,
`group_id` int(11) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `course_user_group_id` (`course_user_group_id`),
CONSTRAINT `course_user_group_id_refs_id_48edc507145383c4` FOREIGN KEY (`course_user_group_id`) REFERENCES `course_groups_courseusergroup` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `course_modes_coursemode`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `course_modes_coursemode` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_id` varchar(255) NOT NULL,
`mode_slug` varchar(100) NOT NULL,
`mode_display_name` varchar(255) NOT NULL,
`min_price` int(11) NOT NULL,
`suggested_prices` varchar(255) NOT NULL,
`currency` varchar(8) NOT NULL,
`expiration_date` date DEFAULT NULL,
`expiration_datetime` datetime DEFAULT NULL,
`description` longtext,
PRIMARY KEY (`id`),
UNIQUE KEY `course_modes_coursemode_course_id_69505c92fc09856_uniq` (`course_id`,`currency`,`mode_slug`),
KEY `course_modes_coursemode_ff48d8e5` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `course_modes_coursemodesarchive`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `course_modes_coursemodesarchive` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_id` varchar(255) NOT NULL,
`mode_slug` varchar(100) NOT NULL,
`mode_display_name` varchar(255) NOT NULL,
`min_price` int(11) NOT NULL,
`suggested_prices` varchar(255) NOT NULL,
`currency` varchar(8) NOT NULL,
`expiration_date` date DEFAULT NULL,
`expiration_datetime` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `course_modes_coursemodesarchive_ff48d8e5` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `courseware_offlinecomputedgrade`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `courseware_offlinecomputedgrade` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`course_id` varchar(255) NOT NULL,
`created` datetime DEFAULT NULL,
`updated` datetime NOT NULL,
`gradeset` longtext,
PRIMARY KEY (`id`),
UNIQUE KEY `courseware_offlinecomputedgrade_user_id_46133bbd0926078f_uniq` (`user_id`,`course_id`),
KEY `courseware_offlinecomputedgrade_fbfc09f1` (`user_id`),
KEY `courseware_offlinecomputedgrade_ff48d8e5` (`course_id`),
KEY `courseware_offlinecomputedgrade_3216ff68` (`created`),
KEY `courseware_offlinecomputedgrade_8aac229` (`updated`),
CONSTRAINT `user_id_refs_id_7b3221f638cf339d` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `courseware_offlinecomputedgradelog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `courseware_offlinecomputedgradelog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_id` varchar(255) NOT NULL,
`created` datetime DEFAULT NULL,
`seconds` int(11) NOT NULL,
`nstudents` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `courseware_offlinecomputedgradelog_ff48d8e5` (`course_id`),
KEY `courseware_offlinecomputedgradelog_3216ff68` (`created`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `courseware_studentmodule`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `courseware_studentmodule` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`module_type` varchar(32) NOT NULL,
`module_id` varchar(255) NOT NULL,
`student_id` int(11) NOT NULL,
`state` longtext,
`grade` double DEFAULT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`max_grade` double,
`done` varchar(8) NOT NULL,
`course_id` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `courseware_studentmodule_student_id_635d77aea1256de5_uniq` (`student_id`,`module_id`,`course_id`),
KEY `courseware_studentmodule_42ff452e` (`student_id`),
KEY `courseware_studentmodule_3216ff68` (`created`),
KEY `courseware_studentmodule_6dff86b5` (`grade`),
KEY `courseware_studentmodule_5436e97a` (`modified`),
KEY `courseware_studentmodule_2d8768ff` (`module_type`),
KEY `courseware_studentmodule_f53ed95e` (`module_id`),
KEY `courseware_studentmodule_1923c03f` (`done`),
KEY `courseware_studentmodule_ff48d8e5` (`course_id`),
CONSTRAINT `student_id_refs_id_51af713179ba2570` FOREIGN KEY (`student_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `courseware_studentmodulehistory`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `courseware_studentmodulehistory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_module_id` int(11) NOT NULL,
`version` varchar(255),
`created` datetime NOT NULL,
`state` longtext,
`grade` double DEFAULT NULL,
`max_grade` double DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `courseware_studentmodulehistory_5656f5fe` (`student_module_id`),
KEY `courseware_studentmodulehistory_659105e4` (`version`),
KEY `courseware_studentmodulehistory_3216ff68` (`created`),
CONSTRAINT `student_module_id_refs_id_51904344e48636f4` FOREIGN KEY (`student_module_id`) REFERENCES `courseware_studentmodule` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `courseware_xmodulestudentinfofield`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `courseware_xmodulestudentinfofield` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`field_name` varchar(64) NOT NULL,
`value` longtext NOT NULL,
`student_id` int(11) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `courseware_xmodulestudentinfof_student_id_33f2f772c49db067_uniq` (`student_id`,`field_name`),
KEY `courseware_xmodulestudentinfofield_7e1499` (`field_name`),
KEY `courseware_xmodulestudentinfofield_42ff452e` (`student_id`),
KEY `courseware_xmodulestudentinfofield_3216ff68` (`created`),
KEY `courseware_xmodulestudentinfofield_5436e97a` (`modified`),
CONSTRAINT `student_id_refs_id_66e06928bfcfbe68` FOREIGN KEY (`student_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `courseware_xmodulestudentprefsfield`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `courseware_xmodulestudentprefsfield` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`field_name` varchar(64) NOT NULL,
`module_type` varchar(64) NOT NULL,
`value` longtext NOT NULL,
`student_id` int(11) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `courseware_xmodulestudentprefs_student_id_2a5d275498b7a407_uniq` (`student_id`,`module_type`,`field_name`),
KEY `courseware_xmodulestudentprefsfield_7e1499` (`field_name`),
KEY `courseware_xmodulestudentprefsfield_2d8768ff` (`module_type`),
KEY `courseware_xmodulestudentprefsfield_42ff452e` (`student_id`),
KEY `courseware_xmodulestudentprefsfield_3216ff68` (`created`),
KEY `courseware_xmodulestudentprefsfield_5436e97a` (`modified`),
CONSTRAINT `student_id_refs_id_32bbaa45d7b9940b` FOREIGN KEY (`student_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `courseware_xmoduleuserstatesummaryfield`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `courseware_xmoduleuserstatesummaryfield` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`field_name` varchar(64) NOT NULL,
`usage_id` varchar(255) NOT NULL,
`value` longtext NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `courseware_xmodulecontentfi_definition_id_50fa4fd570cf2f4a_uniq` (`usage_id`,`field_name`),
KEY `courseware_xmodulecontentfield_7e1499` (`field_name`),
KEY `courseware_xmodulecontentfield_1d304ded` (`usage_id`),
KEY `courseware_xmodulecontentfield_3216ff68` (`created`),
KEY `courseware_xmodulecontentfield_5436e97a` (`modified`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `dark_lang_darklangconfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dark_lang_darklangconfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`change_date` datetime NOT NULL,
`changed_by_id` int(11) DEFAULT NULL,
`enabled` tinyint(1) NOT NULL,
`released_languages` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `dark_lang_darklangconfig_16905482` (`changed_by_id`),
CONSTRAINT `changed_by_id_refs_id_3fb19c355c5fe834` FOREIGN KEY (`changed_by_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `django_admin_log`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `django_admin_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`action_time` datetime NOT NULL,
`user_id` int(11) NOT NULL,
`content_type_id` int(11) DEFAULT NULL,
`object_id` longtext,
`object_repr` varchar(200) NOT NULL,
`action_flag` smallint(5) unsigned NOT NULL,
`change_message` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `django_admin_log_fbfc09f1` (`user_id`),
KEY `django_admin_log_e4470c6e` (`content_type_id`),
CONSTRAINT `content_type_id_refs_id_288599e6` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`),
CONSTRAINT `user_id_refs_id_c8665aa` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `django_comment_client_permission`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `django_comment_client_permission` (
`name` varchar(30) NOT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `django_comment_client_permission_roles`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `django_comment_client_permission_roles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`permission_id` varchar(30) NOT NULL,
`role_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `django_comment_client_permi_permission_id_7a766da089425952_uniq` (`permission_id`,`role_id`),
KEY `django_comment_client_permission_roles_1e014c8f` (`permission_id`),
KEY `django_comment_client_permission_roles_bf07f040` (`role_id`),
CONSTRAINT `role_id_refs_id_6ccffe4ec1b5c854` FOREIGN KEY (`role_id`) REFERENCES `django_comment_client_role` (`id`),
CONSTRAINT `permission_id_refs_name_63b5ab82b6302d27` FOREIGN KEY (`permission_id`) REFERENCES `django_comment_client_permission` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `django_comment_client_role`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `django_comment_client_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`course_id` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `django_comment_client_role_ff48d8e5` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `django_comment_client_role_users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `django_comment_client_role_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `django_comment_client_role_users_role_id_78e483f531943614_uniq` (`role_id`,`user_id`),
KEY `django_comment_client_role_users_bf07f040` (`role_id`),
KEY `django_comment_client_role_users_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_60d02531441b79e7` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`),
CONSTRAINT `role_id_refs_id_282d08d1ab82c838` FOREIGN KEY (`role_id`) REFERENCES `django_comment_client_role` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `django_content_type`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `django_content_type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`app_label` varchar(100) NOT NULL,
`model` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `app_label` (`app_label`,`model`)
) ENGINE=InnoDB AUTO_INCREMENT=149 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `django_openid_auth_association`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `django_openid_auth_association` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`server_url` longtext NOT NULL,
`handle` varchar(255) NOT NULL,
`secret` longtext NOT NULL,
`issued` int(11) NOT NULL,
`lifetime` int(11) NOT NULL,
`assoc_type` longtext NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `django_openid_auth_nonce`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `django_openid_auth_nonce` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`server_url` varchar(2047) NOT NULL,
`timestamp` int(11) NOT NULL,
`salt` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `django_openid_auth_useropenid`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `django_openid_auth_useropenid` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`claimed_id` longtext NOT NULL,
`display_id` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `django_openid_auth_useropenid_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_be7162f0` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `django_session`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `django_session` (
`session_key` varchar(40) NOT NULL,
`session_data` longtext NOT NULL,
`expire_date` datetime NOT NULL,
PRIMARY KEY (`session_key`),
KEY `django_session_c25c2c28` (`expire_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `django_site`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `django_site` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`domain` varchar(100) NOT NULL,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `djcelery_crontabschedule`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `djcelery_crontabschedule` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`minute` varchar(64) NOT NULL,
`hour` varchar(64) NOT NULL,
`day_of_week` varchar(64) NOT NULL,
`day_of_month` varchar(64) NOT NULL,
`month_of_year` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `djcelery_intervalschedule`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `djcelery_intervalschedule` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`every` int(11) NOT NULL,
`period` varchar(24) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `djcelery_periodictask`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `djcelery_periodictask` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`task` varchar(200) NOT NULL,
`interval_id` int(11) DEFAULT NULL,
`crontab_id` int(11) DEFAULT NULL,
`args` longtext NOT NULL,
`kwargs` longtext NOT NULL,
`queue` varchar(200) DEFAULT NULL,
`exchange` varchar(200) DEFAULT NULL,
`routing_key` varchar(200) DEFAULT NULL,
`expires` datetime DEFAULT NULL,
`enabled` tinyint(1) NOT NULL,
`last_run_at` datetime DEFAULT NULL,
`total_run_count` int(10) unsigned NOT NULL,
`date_changed` datetime NOT NULL,
`description` longtext NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `djcelery_periodictask_17d2d99d` (`interval_id`),
KEY `djcelery_periodictask_7aa5fda` (`crontab_id`),
CONSTRAINT `interval_id_refs_id_f2054349` FOREIGN KEY (`interval_id`) REFERENCES `djcelery_intervalschedule` (`id`),
CONSTRAINT `crontab_id_refs_id_ebff5e74` FOREIGN KEY (`crontab_id`) REFERENCES `djcelery_crontabschedule` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `djcelery_periodictasks`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `djcelery_periodictasks` (
`ident` smallint(6) NOT NULL,
`last_update` datetime NOT NULL,
PRIMARY KEY (`ident`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `djcelery_taskstate`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `djcelery_taskstate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state` varchar(64) NOT NULL,
`task_id` varchar(36) NOT NULL,
`name` varchar(200) DEFAULT NULL,
`tstamp` datetime NOT NULL,
`args` longtext,
`kwargs` longtext,
`eta` datetime DEFAULT NULL,
`expires` datetime DEFAULT NULL,
`result` longtext,
`traceback` longtext,
`runtime` double DEFAULT NULL,
`retries` int(11) NOT NULL,
`worker_id` int(11) DEFAULT NULL,
`hidden` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `task_id` (`task_id`),
KEY `djcelery_taskstate_355bfc27` (`state`),
KEY `djcelery_taskstate_52094d6e` (`name`),
KEY `djcelery_taskstate_f0ba6500` (`tstamp`),
KEY `djcelery_taskstate_20fc5b84` (`worker_id`),
KEY `djcelery_taskstate_c91f1bf` (`hidden`),
CONSTRAINT `worker_id_refs_id_4e3453a` FOREIGN KEY (`worker_id`) REFERENCES `djcelery_workerstate` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `djcelery_workerstate`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `djcelery_workerstate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`hostname` varchar(255) NOT NULL,
`last_heartbeat` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `hostname` (`hostname`),
KEY `djcelery_workerstate_eb8ac7e4` (`last_heartbeat`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `edxval_coursevideo`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `edxval_coursevideo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_id` varchar(255) NOT NULL,
`video_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `edxval_coursevideo_course_id_42cecee05cff2d8c_uniq` (`course_id`,`video_id`),
KEY `edxval_coursevideo_fa26288c` (`video_id`),
CONSTRAINT `video_id_refs_id_586418447520c050` FOREIGN KEY (`video_id`) REFERENCES `edxval_video` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `edxval_encodedvideo`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `edxval_encodedvideo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`url` varchar(200) NOT NULL,
`file_size` int(10) unsigned NOT NULL,
`bitrate` int(10) unsigned NOT NULL,
`profile_id` int(11) NOT NULL,
`video_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `edxval_encodedvideo_141c6eec` (`profile_id`),
KEY `edxval_encodedvideo_fa26288c` (`video_id`),
CONSTRAINT `video_id_refs_id_7813fe29176ce1a0` FOREIGN KEY (`video_id`) REFERENCES `edxval_video` (`id`),
CONSTRAINT `profile_id_refs_id_3fd6b88b0692d754` FOREIGN KEY (`profile_id`) REFERENCES `edxval_profile` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `edxval_profile`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `edxval_profile` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`profile_name` varchar(50) NOT NULL,
`extension` varchar(10) NOT NULL,
`width` int(10) unsigned NOT NULL,
`height` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `profile_name` (`profile_name`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `edxval_subtitle`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `edxval_subtitle` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`video_id` int(11) NOT NULL,
`fmt` varchar(20) NOT NULL,
`language` varchar(8) NOT NULL,
`content` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `edxval_subtitle_fa26288c` (`video_id`),
KEY `edxval_subtitle_306df28f` (`fmt`),
KEY `edxval_subtitle_8a7ac9ab` (`language`),
CONSTRAINT `video_id_refs_id_73eaa5f6788bc3d3` FOREIGN KEY (`video_id`) REFERENCES `edxval_video` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `edxval_video`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `edxval_video` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`edx_video_id` varchar(100) NOT NULL,
`client_video_id` varchar(255) NOT NULL,
`duration` double NOT NULL,
`created` datetime NOT NULL,
`status` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `edx_video_id` (`edx_video_id`),
KEY `edxval_video_de3f5709` (`client_video_id`),
KEY `edxval_video_c9ad71dd` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `embargo_embargoedcourse`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `embargo_embargoedcourse` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_id` varchar(255) NOT NULL,
`embargoed` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `course_id` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `embargo_embargoedstate`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `embargo_embargoedstate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`change_date` datetime NOT NULL,
`changed_by_id` int(11) DEFAULT NULL,
`enabled` tinyint(1) NOT NULL,
`embargoed_countries` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `embargo_embargoedstate_16905482` (`changed_by_id`),
CONSTRAINT `changed_by_id_refs_id_3c8b83add0205d39` FOREIGN KEY (`changed_by_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `embargo_ipfilter`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `embargo_ipfilter` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`change_date` datetime NOT NULL,
`changed_by_id` int(11) DEFAULT NULL,
`enabled` tinyint(1) NOT NULL,
`whitelist` longtext NOT NULL,
`blacklist` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `embargo_ipfilter_16905482` (`changed_by_id`),
CONSTRAINT `changed_by_id_refs_id_3babbf0a22c1f5d3` FOREIGN KEY (`changed_by_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `external_auth_externalauthmap`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `external_auth_externalauthmap` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`external_id` varchar(255) NOT NULL,
`external_domain` varchar(255) NOT NULL,
`external_credentials` longtext NOT NULL,
`external_email` varchar(255) NOT NULL,
`external_name` varchar(255) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`internal_password` varchar(31) NOT NULL,
`dtcreated` datetime NOT NULL,
`dtsignup` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `external_auth_externalauthmap_external_id_7f035ef8bc4d313e_uniq` (`external_id`,`external_domain`),
UNIQUE KEY `user_id` (`user_id`),
KEY `external_auth_externalauthmap_d5e787` (`external_id`),
KEY `external_auth_externalauthmap_a570024c` (`external_domain`),
KEY `external_auth_externalauthmap_a142061d` (`external_email`),
KEY `external_auth_externalauthmap_c1a016f` (`external_name`),
CONSTRAINT `user_id_refs_id_39c4e675f8635f67` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `foldit_puzzlecomplete`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `foldit_puzzlecomplete` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`unique_user_id` varchar(50) NOT NULL,
`puzzle_id` int(11) NOT NULL,
`puzzle_set` int(11) NOT NULL,
`puzzle_subset` int(11) NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `foldit_puzzlecomplete_user_id_4c63656af6674331_uniq` (`user_id`,`puzzle_id`,`puzzle_set`,`puzzle_subset`),
KEY `foldit_puzzlecomplete_fbfc09f1` (`user_id`),
KEY `foldit_puzzlecomplete_8027477e` (`unique_user_id`),
KEY `foldit_puzzlecomplete_4798a2b8` (`puzzle_set`),
KEY `foldit_puzzlecomplete_59f06bcd` (`puzzle_subset`),
CONSTRAINT `user_id_refs_id_23bb09ab37e9437b` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `foldit_score`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `foldit_score` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`unique_user_id` varchar(50) NOT NULL,
`puzzle_id` int(11) NOT NULL,
`best_score` double NOT NULL,
`current_score` double NOT NULL,
`score_version` int(11) NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `foldit_score_fbfc09f1` (`user_id`),
KEY `foldit_score_8027477e` (`unique_user_id`),
KEY `foldit_score_3624c060` (`best_score`),
KEY `foldit_score_b4627792` (`current_score`),
CONSTRAINT `user_id_refs_id_44efb56f4c07957f` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `instructor_task_instructortask`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `instructor_task_instructortask` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`task_type` varchar(50) NOT NULL,
`course_id` varchar(255) NOT NULL,
`task_key` varchar(255) NOT NULL,
`task_input` varchar(255) NOT NULL,
`task_id` varchar(255) NOT NULL,
`task_state` varchar(50) DEFAULT NULL,
`task_output` varchar(1024) DEFAULT NULL,
`requester_id` int(11) NOT NULL,
`created` datetime DEFAULT NULL,
`updated` datetime NOT NULL,
`subtasks` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `instructor_task_instructortask_8ae638b4` (`task_type`),
KEY `instructor_task_instructortask_ff48d8e5` (`course_id`),
KEY `instructor_task_instructortask_cfc55170` (`task_key`),
KEY `instructor_task_instructortask_c00fe455` (`task_id`),
KEY `instructor_task_instructortask_731e67a4` (`task_state`),
KEY `instructor_task_instructortask_b8ca8b9f` (`requester_id`),
CONSTRAINT `requester_id_refs_id_4d6b69c6a97278e6` FOREIGN KEY (`requester_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `licenses_coursesoftware`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `licenses_coursesoftware` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`full_name` varchar(255) NOT NULL,
`url` varchar(255) NOT NULL,
`course_id` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `licenses_userlicense`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `licenses_userlicense` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`software_id` int(11) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`serial` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `licenses_userlicense_4c6ed3c1` (`software_id`),
KEY `licenses_userlicense_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_26345de02f3a1cb3` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`),
CONSTRAINT `software_id_refs_id_78738fcdf9e27be8` FOREIGN KEY (`software_id`) REFERENCES `licenses_coursesoftware` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `lms_xblock_xblockasidesconfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `lms_xblock_xblockasidesconfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`change_date` datetime NOT NULL,
`changed_by_id` int(11) DEFAULT NULL,
`enabled` tinyint(1) NOT NULL,
`disabled_blocks` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `lms_xblock_xblockasidesconfig_16905482` (`changed_by_id`),
CONSTRAINT `changed_by_id_refs_id_40c91094552627bc` FOREIGN KEY (`changed_by_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `mentoring_answer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mentoring_answer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`student_id` varchar(32) NOT NULL,
`student_input` longtext NOT NULL,
`created_on` datetime NOT NULL,
`modified_on` datetime NOT NULL,
`course_id` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `mentoring_answer_course_id_7f581fd43d0d1f77_uniq` (`course_id`,`student_id`,`name`),
KEY `mentoring_answer_52094d6e` (`name`),
KEY `mentoring_answer_42ff452e` (`student_id`),
KEY `mentoring_answer_ff48d8e5` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `mentoring_lightchild`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mentoring_lightchild` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`student_id` varchar(32) NOT NULL,
`course_id` varchar(50) NOT NULL,
`student_data` longtext NOT NULL,
`created_on` datetime NOT NULL,
`modified_on` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `mentoring_lightchild_student_id_2d3f2d211f8b8d41_uniq` (`student_id`,`course_id`,`name`),
KEY `mentoring_lightchild_52094d6e` (`name`),
KEY `mentoring_lightchild_42ff452e` (`student_id`),
KEY `mentoring_lightchild_ff48d8e5` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `milestones_coursecontentmilestone`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `milestones_coursecontentmilestone` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`course_id` varchar(255) NOT NULL,
`content_id` varchar(255) NOT NULL,
`milestone_id` int(11) NOT NULL,
`milestone_relationship_type_id` int(11) NOT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `milestones_coursecontentmilesto_course_id_68d1457cd52d6dff_uniq` (`course_id`,`content_id`,`milestone_id`),
KEY `milestones_coursecontentmilestone_ff48d8e5` (`course_id`),
KEY `milestones_coursecontentmilestone_cc8ff3c` (`content_id`),
KEY `milestones_coursecontentmilestone_9cfa291f` (`milestone_id`),
KEY `milestones_coursecontentmilestone_595c57ff` (`milestone_relationship_type_id`),
CONSTRAINT `milestone_relationship_type_id_refs_id_57f7e3570d7ab186` FOREIGN KEY (`milestone_relationship_type_id`) REFERENCES `milestones_milestonerelationshiptype` (`id`),
CONSTRAINT `milestone_id_refs_id_5c1b1e8cd7fabedc` FOREIGN KEY (`milestone_id`) REFERENCES `milestones_milestone` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `milestones_coursemilestone`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `milestones_coursemilestone` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`course_id` varchar(255) NOT NULL,
`milestone_id` int(11) NOT NULL,
`milestone_relationship_type_id` int(11) NOT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `milestones_coursemilestone_course_id_5a06e10579eab3b7_uniq` (`course_id`,`milestone_id`),
KEY `milestones_coursemilestone_ff48d8e5` (`course_id`),
KEY `milestones_coursemilestone_9cfa291f` (`milestone_id`),
KEY `milestones_coursemilestone_595c57ff` (`milestone_relationship_type_id`),
CONSTRAINT `milestone_relationship_type_id_refs_id_2c1c593f874a03b6` FOREIGN KEY (`milestone_relationship_type_id`) REFERENCES `milestones_milestonerelationshiptype` (`id`),
CONSTRAINT `milestone_id_refs_id_540108c1cd764354` FOREIGN KEY (`milestone_id`) REFERENCES `milestones_milestone` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `milestones_milestone`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `milestones_milestone` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`namespace` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`display_name` varchar(255) NOT NULL,
`description` longtext NOT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `milestones_milestone_namespace_460a2f6943016c0b_uniq` (`namespace`,`name`),
KEY `milestones_milestone_eb040977` (`namespace`),
KEY `milestones_milestone_52094d6e` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `milestones_milestonerelationshiptype`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `milestones_milestonerelationshiptype` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`name` varchar(25) NOT NULL,
`description` longtext NOT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `milestones_usermilestone`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `milestones_usermilestone` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`user_id` int(11) NOT NULL,
`milestone_id` int(11) NOT NULL,
`source` longtext NOT NULL,
`collected` datetime DEFAULT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `milestones_usermilestone_user_id_10206aa452468351_uniq` (`user_id`,`milestone_id`),
KEY `milestones_usermilestone_fbfc09f1` (`user_id`),
KEY `milestones_usermilestone_9cfa291f` (`milestone_id`),
CONSTRAINT `milestone_id_refs_id_1a7fbf83af7fa460` FOREIGN KEY (`milestone_id`) REFERENCES `milestones_milestone` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `notes_note`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notes_note` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`course_id` varchar(255) NOT NULL,
`uri` varchar(255) NOT NULL,
`text` longtext NOT NULL,
`quote` longtext NOT NULL,
`range_start` varchar(2048) NOT NULL,
`range_start_offset` int(11) NOT NULL,
`range_end` varchar(2048) NOT NULL,
`range_end_offset` int(11) NOT NULL,
`tags` longtext NOT NULL,
`created` datetime DEFAULT NULL,
`updated` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `notes_note_fbfc09f1` (`user_id`),
KEY `notes_note_ff48d8e5` (`course_id`),
KEY `notes_note_a9794fa` (`uri`),
KEY `notes_note_3216ff68` (`created`),
KEY `notes_note_8aac229` (`updated`),
CONSTRAINT `user_id_refs_id_380a4734360715cc` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `notifications_articlesubscription`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notifications_articlesubscription` (
`subscription_ptr_id` int(11) NOT NULL,
`articleplugin_ptr_id` int(11) NOT NULL,
PRIMARY KEY (`articleplugin_ptr_id`),
UNIQUE KEY `subscription_ptr_id` (`subscription_ptr_id`),
CONSTRAINT `articleplugin_ptr_id_refs_id_1bd08ac071ed584a` FOREIGN KEY (`articleplugin_ptr_id`) REFERENCES `wiki_articleplugin` (`id`),
CONSTRAINT `subscription_ptr_id_refs_id_18f7bae575c0b518` FOREIGN KEY (`subscription_ptr_id`) REFERENCES `notify_subscription` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `notify_notification`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notify_notification` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`subscription_id` int(11) DEFAULT NULL,
`message` longtext NOT NULL,
`url` varchar(200) DEFAULT NULL,
`is_viewed` tinyint(1) NOT NULL,
`is_emailed` tinyint(1) NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `notify_notification_104f5ac1` (`subscription_id`),
CONSTRAINT `subscription_id_refs_id_7a99ebc5baf93d4f` FOREIGN KEY (`subscription_id`) REFERENCES `notify_subscription` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `notify_notificationtype`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notify_notificationtype` (
`key` varchar(128) NOT NULL,
`label` varchar(128) DEFAULT NULL,
`content_type_id` int(11) DEFAULT NULL,
PRIMARY KEY (`key`),
KEY `notify_notificationtype_e4470c6e` (`content_type_id`),
CONSTRAINT `content_type_id_refs_id_4919de6f2478378` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `notify_settings`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notify_settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`interval` smallint(6) NOT NULL,
PRIMARY KEY (`id`),
KEY `notify_settings_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_2e6a6a1d9a2911e6` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `notify_subscription`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notify_subscription` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`settings_id` int(11) NOT NULL,
`notification_type_id` varchar(128) NOT NULL,
`object_id` varchar(64) DEFAULT NULL,
`send_emails` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `notify_subscription_83326d99` (`settings_id`),
KEY `notify_subscription_9955f091` (`notification_type_id`),
CONSTRAINT `notification_type_id_refs_key_25426c9bbaa41a19` FOREIGN KEY (`notification_type_id`) REFERENCES `notify_notificationtype` (`key`),
CONSTRAINT `settings_id_refs_id_2b8d6d653b7225d5` FOREIGN KEY (`settings_id`) REFERENCES `notify_settings` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `oauth2_accesstoken`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `oauth2_accesstoken` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`token` varchar(255) NOT NULL,
`client_id` int(11) NOT NULL,
`expires` datetime NOT NULL,
`scope` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `oauth2_accesstoken_fbfc09f1` (`user_id`),
KEY `oauth2_accesstoken_4a4e8ffb` (`client_id`),
KEY `oauth2_accesstoken_bfac9f99` (`token`),
CONSTRAINT `client_id_refs_id_12f62e33e566ebcc` FOREIGN KEY (`client_id`) REFERENCES `oauth2_client` (`id`),
CONSTRAINT `user_id_refs_id_55b335adc740ddb9` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `oauth2_client`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `oauth2_client` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11),
`url` varchar(200) NOT NULL,
`redirect_uri` varchar(200) NOT NULL,
`client_id` varchar(255) NOT NULL,
`client_secret` varchar(255) NOT NULL,
`client_type` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `oauth2_client_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_61238461c2e3e9a0` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `oauth2_grant`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `oauth2_grant` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`client_id` int(11) NOT NULL,
`code` varchar(255) NOT NULL,
`expires` datetime NOT NULL,
`redirect_uri` varchar(255) NOT NULL,
`scope` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `oauth2_grant_fbfc09f1` (`user_id`),
KEY `oauth2_grant_4a4e8ffb` (`client_id`),
CONSTRAINT `client_id_refs_id_728e499fb2f66ded` FOREIGN KEY (`client_id`) REFERENCES `oauth2_client` (`id`),
CONSTRAINT `user_id_refs_id_75389f4e37f50fe6` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `oauth2_provider_trustedclient`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `oauth2_provider_trustedclient` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`client_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `oauth2_provider_trustedclient_4a4e8ffb` (`client_id`),
CONSTRAINT `client_id_refs_id_12df66c5f6dfcacc` FOREIGN KEY (`client_id`) REFERENCES `oauth2_client` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `oauth2_refreshtoken`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `oauth2_refreshtoken` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`token` varchar(255) NOT NULL,
`access_token_id` int(11) NOT NULL,
`client_id` int(11) NOT NULL,
`expired` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `access_token_id` (`access_token_id`),
KEY `oauth2_refreshtoken_fbfc09f1` (`user_id`),
KEY `oauth2_refreshtoken_4a4e8ffb` (`client_id`),
CONSTRAINT `client_id_refs_id_40eff42b798730c8` FOREIGN KEY (`client_id`) REFERENCES `oauth2_client` (`id`),
CONSTRAINT `access_token_id_refs_id_18e29982df7961b9` FOREIGN KEY (`access_token_id`) REFERENCES `oauth2_accesstoken` (`id`),
CONSTRAINT `user_id_refs_id_7d0e6f3678216905` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `psychometrics_psychometricdata`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `psychometrics_psychometricdata` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`studentmodule_id` int(11) NOT NULL,
`done` tinyint(1) NOT NULL,
`attempts` int(11) NOT NULL,
`checktimes` longtext,
PRIMARY KEY (`id`),
UNIQUE KEY `studentmodule_id` (`studentmodule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `reverification_midcoursereverificationwindow`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `reverification_midcoursereverificationwindow` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_id` varchar(255) NOT NULL,
`start_date` datetime DEFAULT NULL,
`end_date` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `reverification_midcoursereverificationwindow_ff48d8e5` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_certificateitem`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_certificateitem` (
`orderitem_ptr_id` int(11) NOT NULL,
`course_id` varchar(128) NOT NULL,
`course_enrollment_id` int(11) NOT NULL,
`mode` varchar(50) NOT NULL,
PRIMARY KEY (`orderitem_ptr_id`),
KEY `shoppingcart_certificateitem_ff48d8e5` (`course_id`),
KEY `shoppingcart_certificateitem_9e513f0b` (`course_enrollment_id`),
KEY `shoppingcart_certificateitem_4160619e` (`mode`),
CONSTRAINT `course_enrollment_id_refs_id_259181e58048c435` FOREIGN KEY (`course_enrollment_id`) REFERENCES `student_courseenrollment` (`id`),
CONSTRAINT `orderitem_ptr_id_refs_id_4d598262d3ebc4d0` FOREIGN KEY (`orderitem_ptr_id`) REFERENCES `shoppingcart_orderitem` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_coupon`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_coupon` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(32) NOT NULL,
`description` varchar(255) DEFAULT NULL,
`course_id` varchar(255) NOT NULL,
`percentage_discount` int(11) NOT NULL,
`created_by_id` int(11) NOT NULL,
`created_at` datetime NOT NULL,
`is_active` tinyint(1) NOT NULL,
`expiration_date` datetime,
PRIMARY KEY (`id`),
KEY `shoppingcart_coupon_65da3d2c` (`code`),
KEY `shoppingcart_coupon_b5de30be` (`created_by_id`),
CONSTRAINT `created_by_id_refs_id_70b740220259aadc` FOREIGN KEY (`created_by_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_couponredemption`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_couponredemption` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`coupon_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `shoppingcart_couponredemption_8337030b` (`order_id`),
KEY `shoppingcart_couponredemption_fbfc09f1` (`user_id`),
KEY `shoppingcart_couponredemption_c29b2e60` (`coupon_id`),
CONSTRAINT `coupon_id_refs_id_1c5f086bc11a8022` FOREIGN KEY (`coupon_id`) REFERENCES `shoppingcart_coupon` (`id`),
CONSTRAINT `order_id_refs_id_13bbfbf0f5db1967` FOREIGN KEY (`order_id`) REFERENCES `shoppingcart_order` (`id`),
CONSTRAINT `user_id_refs_id_c543b145e9b8167` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_courseregcodeitem`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_courseregcodeitem` (
`orderitem_ptr_id` int(11) NOT NULL,
`course_id` varchar(128) NOT NULL,
`mode` varchar(50) NOT NULL,
PRIMARY KEY (`orderitem_ptr_id`),
KEY `shoppingcart_courseregcodeitem_ff48d8e5` (`course_id`),
KEY `shoppingcart_courseregcodeitem_4160619e` (`mode`),
CONSTRAINT `orderitem_ptr_id_refs_id_2ea4d9d5a466f07f` FOREIGN KEY (`orderitem_ptr_id`) REFERENCES `shoppingcart_orderitem` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_courseregcodeitemannotation`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_courseregcodeitemannotation` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_id` varchar(128) NOT NULL,
`annotation` longtext,
PRIMARY KEY (`id`),
UNIQUE KEY `course_id` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_courseregistrationcode`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_courseregistrationcode` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(32) NOT NULL,
`course_id` varchar(255) NOT NULL,
`created_by_id` int(11) NOT NULL,
`created_at` datetime NOT NULL,
`invoice_id` int(11),
`order_id` int(11),
`mode_slug` varchar(100),
PRIMARY KEY (`id`),
UNIQUE KEY `shoppingcart_courseregistrationcode_code_6614bad3cae62199_uniq` (`code`),
KEY `shoppingcart_courseregistrationcode_65da3d2c` (`code`),
KEY `shoppingcart_courseregistrationcode_ff48d8e5` (`course_id`),
KEY `shoppingcart_courseregistrationcode_b5de30be` (`created_by_id`),
KEY `shoppingcart_courseregistrationcode_59f72b12` (`invoice_id`),
KEY `shoppingcart_courseregistrationcode_8337030b` (`order_id`),
CONSTRAINT `created_by_id_refs_id_7eaaed0838397037` FOREIGN KEY (`created_by_id`) REFERENCES `auth_user` (`id`),
CONSTRAINT `invoice_id_refs_id_6e8c54da995f0ae8` FOREIGN KEY (`invoice_id`) REFERENCES `shoppingcart_invoice` (`id`),
CONSTRAINT `order_id_refs_id_6378d414be36d837` FOREIGN KEY (`order_id`) REFERENCES `shoppingcart_order` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_donation`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_donation` (
`orderitem_ptr_id` int(11) NOT NULL,
`donation_type` varchar(32) NOT NULL,
`course_id` varchar(255) NOT NULL,
PRIMARY KEY (`orderitem_ptr_id`),
KEY `shoppingcart_donation_ff48d8e5` (`course_id`),
CONSTRAINT `orderitem_ptr_id_refs_id_28d47c0cb7138a4b` FOREIGN KEY (`orderitem_ptr_id`) REFERENCES `shoppingcart_orderitem` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_donationconfiguration`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_donationconfiguration` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`change_date` datetime NOT NULL,
`changed_by_id` int(11) DEFAULT NULL,
`enabled` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `shoppingcart_donationconfiguration_16905482` (`changed_by_id`),
CONSTRAINT `changed_by_id_refs_id_28af5c44b4a26b7f` FOREIGN KEY (`changed_by_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_invoice`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_invoice` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`total_amount` double NOT NULL,
`company_name` varchar(255) NOT NULL,
`course_id` varchar(255) NOT NULL,
`internal_reference` varchar(255),
`is_valid` tinyint(1) NOT NULL,
`address_line_1` varchar(255) NOT NULL,
`address_line_2` varchar(255),
`address_line_3` varchar(255),
`city` varchar(255),
`state` varchar(255),
`zip` varchar(15),
`country` varchar(64),
`recipient_name` varchar(255) NOT NULL,
`recipient_email` varchar(255) NOT NULL,
`customer_reference_number` varchar(63),
`company_contact_name` varchar(255) NOT NULL,
`company_contact_email` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `shoppingcart_invoice_ca9021a2` (`company_name`),
KEY `shoppingcart_invoice_ff48d8e5` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_order`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`currency` varchar(8) NOT NULL,
`status` varchar(32) NOT NULL,
`purchase_time` datetime DEFAULT NULL,
`bill_to_first` varchar(64) NOT NULL,
`bill_to_last` varchar(64) NOT NULL,
`bill_to_street1` varchar(128) NOT NULL,
`bill_to_street2` varchar(128) NOT NULL,
`bill_to_city` varchar(64) NOT NULL,
`bill_to_state` varchar(8) NOT NULL,
`bill_to_postalcode` varchar(16) NOT NULL,
`bill_to_country` varchar(64) NOT NULL,
`bill_to_ccnum` varchar(8) NOT NULL,
`bill_to_cardtype` varchar(32) NOT NULL,
`processor_reply_dump` longtext NOT NULL,
`refunded_time` datetime,
`company_name` varchar(255),
`company_contact_name` varchar(255),
`company_contact_email` varchar(255),
`recipient_name` varchar(255),
`recipient_email` varchar(255),
`customer_reference_number` varchar(63),
`order_type` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
KEY `shoppingcart_order_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_a4b0342e1195673` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_orderitem`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_orderitem` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`status` varchar(32) NOT NULL,
`qty` int(11) NOT NULL,
`unit_cost` decimal(30,2) NOT NULL,
`line_desc` varchar(1024) NOT NULL,
`currency` varchar(8) NOT NULL,
`fulfilled_time` datetime,
`report_comments` longtext NOT NULL,
`refund_requested_time` datetime,
`service_fee` decimal(30,2) NOT NULL,
`list_price` decimal(30,2),
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `shoppingcart_orderitem_8337030b` (`order_id`),
KEY `shoppingcart_orderitem_fbfc09f1` (`user_id`),
KEY `shoppingcart_orderitem_c9ad71dd` (`status`),
KEY `shoppingcart_orderitem_8457f26a` (`fulfilled_time`),
KEY `shoppingcart_orderitem_416112c1` (`refund_requested_time`),
CONSTRAINT `order_id_refs_id_4fad6e867c77b3f0` FOREIGN KEY (`order_id`) REFERENCES `shoppingcart_order` (`id`),
CONSTRAINT `user_id_refs_id_608b9042d92ae410` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_paidcourseregistration`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_paidcourseregistration` (
`orderitem_ptr_id` int(11) NOT NULL,
`course_id` varchar(128) NOT NULL,
`mode` varchar(50) NOT NULL,
`course_enrollment_id` int(11),
PRIMARY KEY (`orderitem_ptr_id`),
KEY `shoppingcart_paidcourseregistration_ff48d8e5` (`course_id`),
KEY `shoppingcart_paidcourseregistration_4160619e` (`mode`),
KEY `shoppingcart_paidcourseregistration_9e513f0b` (`course_enrollment_id`),
CONSTRAINT `course_enrollment_id_refs_id_50077099dc061be6` FOREIGN KEY (`course_enrollment_id`) REFERENCES `student_courseenrollment` (`id`),
CONSTRAINT `orderitem_ptr_id_refs_id_c5c6141d8709d99` FOREIGN KEY (`orderitem_ptr_id`) REFERENCES `shoppingcart_orderitem` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_paidcourseregistrationannotation`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_paidcourseregistrationannotation` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_id` varchar(128) NOT NULL,
`annotation` longtext,
PRIMARY KEY (`id`),
UNIQUE KEY `course_id` (`course_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `shoppingcart_registrationcoderedemption`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shoppingcart_registrationcoderedemption` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11),
`registration_code_id` int(11) NOT NULL,
`redeemed_by_id` int(11) NOT NULL,
`redeemed_at` datetime DEFAULT NULL,
`course_enrollment_id` int(11),
PRIMARY KEY (`id`),
KEY `shoppingcart_registrationcoderedemption_8337030b` (`order_id`),
KEY `shoppingcart_registrationcoderedemption_d25b37dc` (`registration_code_id`),
KEY `shoppingcart_registrationcoderedemption_e151467a` (`redeemed_by_id`),
KEY `shoppingcart_registrationcoderedemption_9e513f0b` (`course_enrollment_id`),
CONSTRAINT `course_enrollment_id_refs_id_6d4e7d1dc9486127` FOREIGN KEY (`course_enrollment_id`) REFERENCES `student_courseenrollment` (`id`),
CONSTRAINT `order_id_refs_id_3e4c388753a8a5c9` FOREIGN KEY (`order_id`) REFERENCES `shoppingcart_order` (`id`),
CONSTRAINT `redeemed_by_id_refs_id_2c29fd0d4e320dc9` FOREIGN KEY (`redeemed_by_id`) REFERENCES `auth_user` (`id`),
CONSTRAINT `registration_code_id_refs_id_2b7812ae4d01e47b` FOREIGN KEY (`registration_code_id`) REFERENCES `shoppingcart_courseregistrationcode` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `social_auth_association`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `social_auth_association` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`server_url` varchar(255) NOT NULL,
`handle` varchar(255) NOT NULL,
`secret` varchar(255) NOT NULL,
`issued` int(11) NOT NULL,
`lifetime` int(11) NOT NULL,
`assoc_type` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `social_auth_code`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `social_auth_code` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(75) NOT NULL,
`code` varchar(32) NOT NULL,
`verified` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`,`code`),
KEY `social_auth_code_65da3d2c` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `social_auth_nonce`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `social_auth_nonce` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`server_url` varchar(255) NOT NULL,
`timestamp` int(11) NOT NULL,
`salt` varchar(65) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `social_auth_usersocialauth`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `social_auth_usersocialauth` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`provider` varchar(32) NOT NULL,
`uid` varchar(255) NOT NULL,
`extra_data` longtext NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `provider` (`provider`,`uid`),
KEY `social_auth_usersocialauth_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_60fa311b` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `south_migrationhistory`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `south_migrationhistory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`app_name` varchar(255) NOT NULL,
`migration` varchar(255) NOT NULL,
`applied` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=205 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `splash_splashconfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `splash_splashconfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`change_date` datetime NOT NULL,
`changed_by_id` int(11) DEFAULT NULL,
`enabled` tinyint(1) NOT NULL,
`cookie_name` longtext NOT NULL,
`cookie_allowed_values` longtext NOT NULL,
`unaffected_usernames` longtext NOT NULL,
`redirect_url` varchar(200) NOT NULL,
`unaffected_url_paths` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `splash_splashconfig_16905482` (`changed_by_id`),
CONSTRAINT `changed_by_id_refs_id_6024c0b79125b21c` FOREIGN KEY (`changed_by_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_anonymoususerid`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_anonymoususerid` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`anonymous_user_id` varchar(32) NOT NULL,
`course_id` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `anonymous_user_id` (`anonymous_user_id`),
KEY `student_anonymoususerid_fbfc09f1` (`user_id`),
KEY `student_anonymoususerid_ff48d8e5` (`course_id`),
CONSTRAINT `user_id_refs_id_23effb36c38f7a2a` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_courseaccessrole`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_courseaccessrole` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`org` varchar(64) NOT NULL,
`course_id` varchar(255) NOT NULL,
`role` varchar(64) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `student_courseaccessrole_user_id_3203176c4f474414_uniq` (`user_id`,`org`,`course_id`,`role`),
KEY `student_courseaccessrole_fbfc09f1` (`user_id`),
KEY `student_courseaccessrole_4f5f82e2` (`org`),
KEY `student_courseaccessrole_ff48d8e5` (`course_id`),
KEY `student_courseaccessrole_e0b082a1` (`role`),
CONSTRAINT `user_id_refs_id_7460a3f36ac23885` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_courseenrollment`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_courseenrollment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`course_id` varchar(255) NOT NULL,
`created` datetime DEFAULT NULL,
`is_active` tinyint(1) NOT NULL,
`mode` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `student_courseenrollment_user_id_2d2a572f07dd8e37_uniq` (`user_id`,`course_id`),
KEY `student_courseenrollment_fbfc09f1` (`user_id`),
KEY `student_courseenrollment_ff48d8e5` (`course_id`),
KEY `student_courseenrollment_3216ff68` (`created`),
CONSTRAINT `user_id_refs_id_45948fcded37bc9d` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_courseenrollmentallowed`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_courseenrollmentallowed` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`course_id` varchar(255) NOT NULL,
`created` datetime DEFAULT NULL,
`auto_enroll` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `student_courseenrollmentallowed_email_6f3eafd4a6c58591_uniq` (`email`,`course_id`),
KEY `student_courseenrollmentallowed_3904588a` (`email`),
KEY `student_courseenrollmentallowed_ff48d8e5` (`course_id`),
KEY `student_courseenrollmentallowed_3216ff68` (`created`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_dashboardconfiguration`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_dashboardconfiguration` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`change_date` datetime NOT NULL,
`changed_by_id` int(11) DEFAULT NULL,
`enabled` tinyint(1) NOT NULL,
`recent_enrollment_time_delta` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `student_dashboardconfiguration_16905482` (`changed_by_id`),
CONSTRAINT `changed_by_id_refs_id_31b94d88eec78c18` FOREIGN KEY (`changed_by_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_loginfailures`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_loginfailures` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`failure_count` int(11) NOT NULL,
`lockout_until` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `student_loginfailures_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_50dcb1c1e6a71045` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_passwordhistory`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_passwordhistory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`password` varchar(128) NOT NULL,
`time_set` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `student_passwordhistory_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_6110e7eaed0987da` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_pendingemailchange`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_pendingemailchange` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`new_email` varchar(255) NOT NULL,
`activation_key` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
UNIQUE KEY `activation_key` (`activation_key`),
KEY `student_pendingemailchange_856c86d7` (`new_email`),
CONSTRAINT `user_id_refs_id_24fa3bcda525fa67` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_pendingnamechange`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_pendingnamechange` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`new_name` varchar(255) NOT NULL,
`rationale` varchar(1024) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
CONSTRAINT `user_id_refs_id_24e959cdd9359b27` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_usersignupsource`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_usersignupsource` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`site` varchar(255) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `student_usersignupsource_e00a881a` (`site`),
KEY `student_usersignupsource_fbfc09f1` (`user_id`),
CONSTRAINT `user_id_refs_id_4ae6e32838a4bd6e` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_userstanding`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_userstanding` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`account_status` varchar(31) NOT NULL,
`changed_by_id` int(11) NOT NULL,
`standing_last_changed_at` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
KEY `student_userstanding_16905482` (`changed_by_id`),
CONSTRAINT `changed_by_id_refs_id_5ec33b2b0450a33b` FOREIGN KEY (`changed_by_id`) REFERENCES `auth_user` (`id`),
CONSTRAINT `user_id_refs_id_5ec33b2b0450a33b` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_usertestgroup`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_usertestgroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`description` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `student_usertestgroup_52094d6e` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `student_usertestgroup_users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student_usertestgroup_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`usertestgroup_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `student_usertestgroup_us_usertestgroup_id_63c588e0372991b0_uniq` (`usertestgroup_id`,`user_id`),
KEY `student_usertestgroup_users_44f27cdf` (`usertestgroup_id`),
KEY `student_usertestgroup_users_fbfc09f1` (`user_id`),
CONSTRAINT `usertestgroup_id_refs_id_78e186d36d724f9e` FOREIGN KEY (`usertestgroup_id`) REFERENCES `student_usertestgroup` (`id`),
CONSTRAINT `user_id_refs_id_412b14bf8947584c` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `submissions_score`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `submissions_score` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_item_id` int(11) NOT NULL,
`submission_id` int(11) DEFAULT NULL,
`points_earned` int(10) unsigned NOT NULL,
`points_possible` int(10) unsigned NOT NULL,
`created_at` datetime NOT NULL,
`reset` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `submissions_score_fa84001` (`student_item_id`),
KEY `submissions_score_b3d6235a` (`submission_id`),
KEY `submissions_score_3b1c9c31` (`created_at`),
CONSTRAINT `student_item_id_refs_id_33922a7f8cd97385` FOREIGN KEY (`student_item_id`) REFERENCES `submissions_studentitem` (`id`),
CONSTRAINT `submission_id_refs_id_3b63d5ec9e39cf2e` FOREIGN KEY (`submission_id`) REFERENCES `submissions_submission` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `submissions_scoresummary`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `submissions_scoresummary` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_item_id` int(11) NOT NULL,
`highest_id` int(11) NOT NULL,
`latest_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `student_item_id` (`student_item_id`),
KEY `submissions_scoresummary_d65f9365` (`highest_id`),
KEY `submissions_scoresummary_1efb24d9` (`latest_id`),
CONSTRAINT `latest_id_refs_id_37a2bc281bdc0a18` FOREIGN KEY (`latest_id`) REFERENCES `submissions_score` (`id`),
CONSTRAINT `highest_id_refs_id_37a2bc281bdc0a18` FOREIGN KEY (`highest_id`) REFERENCES `submissions_score` (`id`),
CONSTRAINT `student_item_id_refs_id_6183d6a8bd51e768` FOREIGN KEY (`student_item_id`) REFERENCES `submissions_studentitem` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `submissions_studentitem`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `submissions_studentitem` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` varchar(255) NOT NULL,
`course_id` varchar(255) NOT NULL,
`item_id` varchar(255) NOT NULL,
`item_type` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `submissions_studentitem_course_id_6a6eccbdec6ffd0b_uniq` (`course_id`,`student_id`,`item_id`),
KEY `submissions_studentitem_42ff452e` (`student_id`),
KEY `submissions_studentitem_ff48d8e5` (`course_id`),
KEY `submissions_studentitem_67b70d25` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `submissions_submission`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `submissions_submission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uuid` varchar(36) NOT NULL,
`student_item_id` int(11) NOT NULL,
`attempt_number` int(10) unsigned NOT NULL,
`submitted_at` datetime NOT NULL,
`created_at` datetime NOT NULL,
`raw_answer` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `submissions_submission_2bbc74ae` (`uuid`),
KEY `submissions_submission_fa84001` (`student_item_id`),
KEY `submissions_submission_4452d192` (`submitted_at`),
KEY `submissions_submission_3b1c9c31` (`created_at`),
CONSTRAINT `student_item_id_refs_id_1df1d83e00b5cccc` FOREIGN KEY (`student_item_id`) REFERENCES `submissions_studentitem` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `survey_surveyanswer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `survey_surveyanswer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`user_id` int(11) NOT NULL,
`form_id` int(11) NOT NULL,
`field_name` varchar(255) NOT NULL,
`field_value` varchar(1024) NOT NULL,
PRIMARY KEY (`id`),
KEY `survey_surveyanswer_fbfc09f1` (`user_id`),
KEY `survey_surveyanswer_1d0aabf2` (`form_id`),
KEY `survey_surveyanswer_7e1499` (`field_name`),
CONSTRAINT `form_id_refs_id_5a119e5cf4c79f29` FOREIGN KEY (`form_id`) REFERENCES `survey_surveyform` (`id`),
CONSTRAINT `user_id_refs_id_74dcdfa0e0ad4b5e` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `survey_surveyform`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `survey_surveyform` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`name` varchar(255) NOT NULL,
`form` longtext NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `track_trackinglog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `track_trackinglog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dtcreated` datetime NOT NULL,
`username` varchar(32) NOT NULL,
`ip` varchar(32) NOT NULL,
`event_source` varchar(32) NOT NULL,
`event_type` varchar(512) NOT NULL,
`event` longtext NOT NULL,
`agent` varchar(256) NOT NULL,
`page` varchar(512),
`time` datetime NOT NULL,
`host` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `user_api_usercoursetag`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_api_usercoursetag` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`key` varchar(255) NOT NULL,
`course_id` varchar(255) NOT NULL,
`value` longtext NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_api_usercoursetags_user_id_a734720a0483b08_uniq` (`user_id`,`course_id`,`key`),
KEY `user_api_usercoursetags_fbfc09f1` (`user_id`),
KEY `user_api_usercoursetags_45544485` (`key`),
KEY `user_api_usercoursetags_ff48d8e5` (`course_id`),
CONSTRAINT `user_id_refs_id_1d26ef6c47a9a367` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `user_api_userorgtag`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_api_userorgtag` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`user_id` int(11) NOT NULL,
`key` varchar(255) NOT NULL,
`org` varchar(255) NOT NULL,
`value` longtext NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_api_userorgtag_user_id_694f9e3322120c6f_uniq` (`user_id`,`org`,`key`),
KEY `user_api_userorgtag_user_id_694f9e3322120c6f` (`user_id`,`org`,`key`),
KEY `user_api_userorgtag_fbfc09f1` (`user_id`),
KEY `user_api_userorgtag_45544485` (`key`),
KEY `user_api_userorgtag_4f5f82e2` (`org`),
CONSTRAINT `user_id_refs_id_4fedbcc0e54b717f` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `user_api_userpreference`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_api_userpreference` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`key` varchar(255) NOT NULL,
`value` longtext NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_api_userpreference_user_id_4e4942d73f760072_uniq` (`user_id`,`key`),
KEY `user_api_userpreference_fbfc09f1` (`user_id`),
KEY `user_api_userpreference_45544485` (`key`),
CONSTRAINT `user_id_refs_id_2839c1f4f3473b9e` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `verify_student_softwaresecurephotoverification`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `verify_student_softwaresecurephotoverification` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`status` varchar(100) NOT NULL,
`status_changed` datetime NOT NULL,
`user_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`face_image_url` varchar(255) NOT NULL,
`photo_id_image_url` varchar(255) NOT NULL,
`receipt_id` varchar(255) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
`submitted_at` datetime DEFAULT NULL,
`reviewing_user_id` int(11) DEFAULT NULL,
`reviewing_service` varchar(255) NOT NULL,
`error_msg` longtext NOT NULL,
`error_code` varchar(50) NOT NULL,
`photo_id_key` longtext NOT NULL,
`window_id` int(11),
`display` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `verify_student_softwaresecurephotoverification_fbfc09f1` (`user_id`),
KEY `verify_student_softwaresecurephotoverification_8713c555` (`receipt_id`),
KEY `verify_student_softwaresecurephotoverification_3b1c9c31` (`created_at`),
KEY `verify_student_softwaresecurephotoverification_f84f7de6` (`updated_at`),
KEY `verify_student_softwaresecurephotoverification_4452d192` (`submitted_at`),
KEY `verify_student_softwaresecurephotoverification_b2c165b4` (`reviewing_user_id`),
KEY `verify_student_softwaresecurephotoverification_7343ffda` (`window_id`),
KEY `verify_student_softwaresecurephotoverification_35eebcb6` (`display`),
CONSTRAINT `reviewing_user_id_refs_id_5b90d52ad6ea4207` FOREIGN KEY (`reviewing_user_id`) REFERENCES `auth_user` (`id`),
CONSTRAINT `user_id_refs_id_5b90d52ad6ea4207` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`),
CONSTRAINT `window_id_refs_id_30f70c30fce8f38a` FOREIGN KEY (`window_id`) REFERENCES `reverification_midcoursereverificationwindow` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_article`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`current_revision_id` int(11) DEFAULT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`owner_id` int(11) DEFAULT NULL,
`group_id` int(11) DEFAULT NULL,
`group_read` tinyint(1) NOT NULL,
`group_write` tinyint(1) NOT NULL,
`other_read` tinyint(1) NOT NULL,
`other_write` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `current_revision_id` (`current_revision_id`),
KEY `wiki_article_5d52dd10` (`owner_id`),
KEY `wiki_article_bda51c3c` (`group_id`),
CONSTRAINT `group_id_refs_id_10e2d3dd108bfee4` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`),
CONSTRAINT `current_revision_id_refs_id_1d8d320ebafac304` FOREIGN KEY (`current_revision_id`) REFERENCES `wiki_articlerevision` (`id`),
CONSTRAINT `owner_id_refs_id_18073b359e14b583` FOREIGN KEY (`owner_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_articleforobject`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_articleforobject` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`article_id` int(11) NOT NULL,
`content_type_id` int(11) NOT NULL,
`object_id` int(10) unsigned NOT NULL,
`is_mptt` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `wiki_articleforobject_content_type_id_27c4cce189b3bcab_uniq` (`content_type_id`,`object_id`),
KEY `wiki_articleforobject_30525a19` (`article_id`),
KEY `wiki_articleforobject_e4470c6e` (`content_type_id`),
CONSTRAINT `content_type_id_refs_id_6b30567037828764` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`),
CONSTRAINT `article_id_refs_id_1698e37305099436` FOREIGN KEY (`article_id`) REFERENCES `wiki_article` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_articleplugin`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_articleplugin` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`article_id` int(11) NOT NULL,
`deleted` tinyint(1) NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `wiki_articleplugin_30525a19` (`article_id`),
CONSTRAINT `article_id_refs_id_64fa106f92c648ca` FOREIGN KEY (`article_id`) REFERENCES `wiki_article` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_articlerevision`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_articlerevision` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`revision_number` int(11) NOT NULL,
`user_message` longtext NOT NULL,
`automatic_log` longtext NOT NULL,
`ip_address` char(15) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`modified` datetime NOT NULL,
`created` datetime NOT NULL,
`previous_revision_id` int(11) DEFAULT NULL,
`deleted` tinyint(1) NOT NULL,
`locked` tinyint(1) NOT NULL,
`article_id` int(11) NOT NULL,
`content` longtext NOT NULL,
`title` varchar(512) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `wiki_articlerevision_article_id_4b4e7910c8e7b2d0_uniq` (`article_id`,`revision_number`),
KEY `wiki_articlerevision_fbfc09f1` (`user_id`),
KEY `wiki_articlerevision_49bc38cc` (`previous_revision_id`),
KEY `wiki_articlerevision_30525a19` (`article_id`),
CONSTRAINT `article_id_refs_id_5a3b45ce5c88570a` FOREIGN KEY (`article_id`) REFERENCES `wiki_article` (`id`),
CONSTRAINT `previous_revision_id_refs_id_7c6fe338a951e36b` FOREIGN KEY (`previous_revision_id`) REFERENCES `wiki_articlerevision` (`id`),
CONSTRAINT `user_id_refs_id_672c6e4dfbb26714` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_articlesubscription`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_articlesubscription` (
`subscription_ptr_id` int(11) NOT NULL,
`articleplugin_ptr_id` int(11) NOT NULL,
PRIMARY KEY (`articleplugin_ptr_id`),
UNIQUE KEY `subscription_ptr_id` (`subscription_ptr_id`),
CONSTRAINT `articleplugin_ptr_id_refs_id_7b2f9df4cbce00e3` FOREIGN KEY (`articleplugin_ptr_id`) REFERENCES `wiki_articleplugin` (`id`),
CONSTRAINT `subscription_ptr_id_refs_id_4ec3f6dbae89f475` FOREIGN KEY (`subscription_ptr_id`) REFERENCES `notify_subscription` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_attachment`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_attachment` (
`reusableplugin_ptr_id` int(11) NOT NULL,
`current_revision_id` int(11) DEFAULT NULL,
`original_filename` varchar(256) DEFAULT NULL,
PRIMARY KEY (`reusableplugin_ptr_id`),
UNIQUE KEY `current_revision_id` (`current_revision_id`),
CONSTRAINT `current_revision_id_refs_id_66561e6e2198feb4` FOREIGN KEY (`current_revision_id`) REFERENCES `wiki_attachmentrevision` (`id`),
CONSTRAINT `reusableplugin_ptr_id_refs_articleplugin_ptr_id_79d179a16644e87a` FOREIGN KEY (`reusableplugin_ptr_id`) REFERENCES `wiki_reusableplugin` (`articleplugin_ptr_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_attachmentrevision`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_attachmentrevision` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`revision_number` int(11) NOT NULL,
`user_message` longtext NOT NULL,
`automatic_log` longtext NOT NULL,
`ip_address` char(15) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`modified` datetime NOT NULL,
`created` datetime NOT NULL,
`previous_revision_id` int(11) DEFAULT NULL,
`deleted` tinyint(1) NOT NULL,
`locked` tinyint(1) NOT NULL,
`attachment_id` int(11) NOT NULL,
`file` varchar(100) NOT NULL,
`description` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `wiki_attachmentrevision_fbfc09f1` (`user_id`),
KEY `wiki_attachmentrevision_49bc38cc` (`previous_revision_id`),
KEY `wiki_attachmentrevision_edee6011` (`attachment_id`),
CONSTRAINT `attachment_id_refs_reusableplugin_ptr_id_33d8cf1f640583da` FOREIGN KEY (`attachment_id`) REFERENCES `wiki_attachment` (`reusableplugin_ptr_id`),
CONSTRAINT `previous_revision_id_refs_id_5521ecec0041bbf5` FOREIGN KEY (`previous_revision_id`) REFERENCES `wiki_attachmentrevision` (`id`),
CONSTRAINT `user_id_refs_id_2822eb682eaca84c` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_image`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_image` (
`revisionplugin_ptr_id` int(11) NOT NULL,
PRIMARY KEY (`revisionplugin_ptr_id`),
CONSTRAINT `revisionplugin_ptr_id_refs_articleplugin_ptr_id_1a20f885fc42a0b1` FOREIGN KEY (`revisionplugin_ptr_id`) REFERENCES `wiki_revisionplugin` (`articleplugin_ptr_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_imagerevision`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_imagerevision` (
`revisionpluginrevision_ptr_id` int(11) NOT NULL,
`image` varchar(2000),
`width` smallint(6),
`height` smallint(6),
PRIMARY KEY (`revisionpluginrevision_ptr_id`),
CONSTRAINT `revisionpluginrevision_ptr_id_refs_id_5da3ee545b9fc791` FOREIGN KEY (`revisionpluginrevision_ptr_id`) REFERENCES `wiki_revisionpluginrevision` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_reusableplugin`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_reusableplugin` (
`articleplugin_ptr_id` int(11) NOT NULL,
PRIMARY KEY (`articleplugin_ptr_id`),
CONSTRAINT `articleplugin_ptr_id_refs_id_2a5c48de4ca661fd` FOREIGN KEY (`articleplugin_ptr_id`) REFERENCES `wiki_articleplugin` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_reusableplugin_articles`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_reusableplugin_articles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`reusableplugin_id` int(11) NOT NULL,
`article_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `wiki_reusableplugin_art_reusableplugin_id_6e34ac94afa8f9f2_uniq` (`reusableplugin_id`,`article_id`),
KEY `wiki_reusableplugin_articles_28b0b358` (`reusableplugin_id`),
KEY `wiki_reusableplugin_articles_30525a19` (`article_id`),
CONSTRAINT `article_id_refs_id_854477c2f51faad` FOREIGN KEY (`article_id`) REFERENCES `wiki_article` (`id`),
CONSTRAINT `reusableplugin_id_refs_articleplugin_ptr_id_496cabe744b45e30` FOREIGN KEY (`reusableplugin_id`) REFERENCES `wiki_reusableplugin` (`articleplugin_ptr_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_revisionplugin`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_revisionplugin` (
`articleplugin_ptr_id` int(11) NOT NULL,
`current_revision_id` int(11),
PRIMARY KEY (`articleplugin_ptr_id`),
UNIQUE KEY `current_revision_id` (`current_revision_id`),
CONSTRAINT `current_revision_id_refs_id_2732d4b244938e26` FOREIGN KEY (`current_revision_id`) REFERENCES `wiki_revisionpluginrevision` (`id`),
CONSTRAINT `articleplugin_ptr_id_refs_id_2b8f815fcac31401` FOREIGN KEY (`articleplugin_ptr_id`) REFERENCES `wiki_articleplugin` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_revisionpluginrevision`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_revisionpluginrevision` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`revision_number` int(11) NOT NULL,
`user_message` longtext NOT NULL,
`automatic_log` longtext NOT NULL,
`ip_address` char(15) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`modified` datetime NOT NULL,
`created` datetime NOT NULL,
`previous_revision_id` int(11) DEFAULT NULL,
`deleted` tinyint(1) NOT NULL,
`locked` tinyint(1) NOT NULL,
`plugin_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `wiki_revisionpluginrevision_fbfc09f1` (`user_id`),
KEY `wiki_revisionpluginrevision_49bc38cc` (`previous_revision_id`),
KEY `wiki_revisionpluginrevision_2857ccbf` (`plugin_id`),
CONSTRAINT `plugin_id_refs_articleplugin_ptr_id_3e044eb541bbc69c` FOREIGN KEY (`plugin_id`) REFERENCES `wiki_revisionplugin` (`articleplugin_ptr_id`),
CONSTRAINT `previous_revision_id_refs_id_3348918678fffe43` FOREIGN KEY (`previous_revision_id`) REFERENCES `wiki_revisionpluginrevision` (`id`),
CONSTRAINT `user_id_refs_id_21540d2c32d8f395` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_simpleplugin`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_simpleplugin` (
`articleplugin_ptr_id` int(11) NOT NULL,
`article_revision_id` int(11) NOT NULL,
PRIMARY KEY (`articleplugin_ptr_id`),
KEY `wiki_simpleplugin_b3dc49fe` (`article_revision_id`),
CONSTRAINT `article_revision_id_refs_id_2252033b6df37b12` FOREIGN KEY (`article_revision_id`) REFERENCES `wiki_articlerevision` (`id`),
CONSTRAINT `articleplugin_ptr_id_refs_id_6704e8c7a25cbfd2` FOREIGN KEY (`articleplugin_ptr_id`) REFERENCES `wiki_articleplugin` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `wiki_urlpath`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wiki_urlpath` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`slug` varchar(50) DEFAULT NULL,
`site_id` int(11) NOT NULL,
`parent_id` int(11) DEFAULT NULL,
`lft` int(10) unsigned NOT NULL,
`rght` int(10) unsigned NOT NULL,
`tree_id` int(10) unsigned NOT NULL,
`level` int(10) unsigned NOT NULL,
`article_id` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
UNIQUE KEY `wiki_urlpath_site_id_124f6aa7b2cc9b82_uniq` (`site_id`,`parent_id`,`slug`),
KEY `wiki_urlpath_a951d5d6` (`slug`),
KEY `wiki_urlpath_6223029` (`site_id`),
KEY `wiki_urlpath_63f17a16` (`parent_id`),
KEY `wiki_urlpath_42b06ff6` (`lft`),
KEY `wiki_urlpath_91543e5a` (`rght`),
KEY `wiki_urlpath_efd07f28` (`tree_id`),
KEY `wiki_urlpath_2a8f42e8` (`level`),
KEY `wiki_urlpath_30525a19` (`article_id`),
CONSTRAINT `article_id_refs_id_23bd80e7971759c9` FOREIGN KEY (`article_id`) REFERENCES `wiki_article` (`id`),
CONSTRAINT `parent_id_refs_id_62afe7c752d1e703` FOREIGN KEY (`parent_id`) REFERENCES `wiki_urlpath` (`id`),
CONSTRAINT `site_id_refs_id_462d2bc7f4bbaaa2` FOREIGN KEY (`site_id`) REFERENCES `django_site` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `workflow_assessmentworkflow`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workflow_assessmentworkflow` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` varchar(100) NOT NULL,
`status_changed` datetime NOT NULL,
`submission_uuid` varchar(36) NOT NULL,
`uuid` varchar(36) NOT NULL,
`course_id` varchar(255) NOT NULL,
`item_id` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `submission_uuid` (`submission_uuid`),
UNIQUE KEY `uuid` (`uuid`),
KEY `workflow_assessmentworkflow_course_id_21b427c69fc666ad` (`course_id`,`item_id`,`status`),
KEY `workflow_assessmentworkflow_ff48d8e5` (`course_id`),
KEY `workflow_assessmentworkflow_67b70d25` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `workflow_assessmentworkflowstep`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workflow_assessmentworkflowstep` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`workflow_id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`submitter_completed_at` datetime DEFAULT NULL,
`assessment_completed_at` datetime DEFAULT NULL,
`order_num` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `workflow_assessmentworkflowstep_26cddbc7` (`workflow_id`),
CONSTRAINT `workflow_id_refs_id_4e31588b69d0b483` FOREIGN KEY (`workflow_id`) REFERENCES `workflow_assessmentworkflow` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `xblock_config_studioconfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `xblock_config_studioconfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`change_date` datetime NOT NULL,
`changed_by_id` int(11) DEFAULT NULL,
`enabled` tinyint(1) NOT NULL,
`disabled_blocks` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `xblock_config_studioconfig_16905482` (`changed_by_id`),
CONSTRAINT `changed_by_id_refs_id_3d4ae52c6ef7f7d7` FOREIGN KEY (`changed_by_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
| jazkarta/edx-platform-for-isc | common/test/db_cache/bok_choy_schema.sql | SQL | agpl-3.0 | 138,342 |
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
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.FakeJujuXDGDataHomeSuite
fake *fakeEnvAPI
}
func (s *fakeEnvSuite) SetUpTest(c *gc.C) {
s.FakeJujuXDGDataHomeSuite.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) ModelGetWithMetadata() (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 fakeModelDefaultEnvSuite struct {
testing.FakeJujuXDGDataHomeSuite
fakeAPIRoot *fakeAPIConnection
fakeDefaultsAPI *fakeModelDefaultsAPI
fakeCloudAPI *fakeCloudAPI
}
func (s *fakeModelDefaultEnvSuite) SetUpTest(c *gc.C) {
s.FakeJujuXDGDataHomeSuite.SetUpTest(c)
s.fakeAPIRoot = &fakeAPIConnection{}
s.fakeDefaultsAPI = &fakeModelDefaultsAPI{
values: map[string]interface{}{
"name": "test-model",
"special": "special value",
"running": true,
},
defaults: config.ModelDefaultAttributes{
"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 fakeModelDefaultsAPI struct {
values map[string]interface{}
cloud, region string
defaults config.ModelDefaultAttributes
err error
keys []string
}
func (f *fakeModelDefaultsAPI) Close() error {
return nil
}
func (f *fakeModelDefaultsAPI) ModelGet() (map[string]interface{}, error) {
return f.values, nil
}
func (f *fakeModelDefaultsAPI) ModelDefaults() (config.ModelDefaultAttributes, error) {
return f.defaults, nil
}
func (f *fakeModelDefaultsAPI) 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.AttributeDefaultValues{Controller: val}
}
return nil
}
func (f *fakeModelDefaultsAPI) 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 *fakeModelDefaultsAPI) ModelSet(config map[string]interface{}) error {
f.values = config
return f.err
}
func (f *fakeModelDefaultsAPI) 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
}
| gabriel-samfira/juju | cmd/juju/model/fakeenv_test.go | GO | agpl-3.0 | 4,463 |
<?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' => 'タグで絞り込み',
); ?>
| md11235/fengoffice | plugins/workspaces/language/ja_jp/lang.php | PHP | agpl-3.0 | 468 |
#!/bin/sh
# Copyright (c) 2015, 2016 Sébastien Combéfis, Virginie Van den Schrieck
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
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
| UCL-INGI/Informatique-1 | old_pythia/88_java/run.sh | Shell | agpl-3.0 | 959 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.