code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
__author__ = 'ktisha' def foo(): """ This is my docstring. There are many like it, but this one mine. My docstring is my best friend. it is my life. I must master it as I must master my life. This is my docstring. There are many like it, but this one mine. My docstring is my best friend. it is my life. I must master it as I must master my life. """
caot/intellij-community
python/testData/fillParagraph/docstringOneParagraph_after.py
Python
apache-2.0
357
package aetest import ( "hash/crc32" "net/http" "strconv" "google.golang.org/appengine/user" ) // Login causes the provided Request to act as though issued by the given user. func Login(u *user.User, req *http.Request) { req.Header.Set("X-AppEngine-User-Email", u.Email) id := u.ID if id == "" { id = strconv.Itoa(int(crc32.Checksum([]byte(u.Email), crc32.IEEETable))) } req.Header.Set("X-AppEngine-User-Id", id) req.Header.Set("X-AppEngine-User-Federated-Identity", u.Email) req.Header.Set("X-AppEngine-User-Federated-Provider", u.FederatedProvider) if u.Admin { req.Header.Set("X-AppEngine-User-Is-Admin", "1") } else { req.Header.Set("X-AppEngine-User-Is-Admin", "0") } } // Logout causes the provided Request to act as though issued by a logged-out // user. func Logout(req *http.Request) { req.Header.Del("X-AppEngine-User-Email") req.Header.Del("X-AppEngine-User-Id") req.Header.Del("X-AppEngine-User-Is-Admin") req.Header.Del("X-AppEngine-User-Federated-Identity") req.Header.Del("X-AppEngine-User-Federated-Provider") }
ae6rt/decap
web/vendor/google.golang.org/appengine/aetest/user.go
GO
mit
1,057
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Jasmine Spec Runner</title> <link rel="shortcut icon" type="image/png" href="javascripts/lib/jasmine-1.2.0/jasmine_favicon.png"> <link rel="stylesheet" type="text/css" href="javascripts/lib/jasmine-1.2.0/jasmine.css"> <script type="text/javascript" src="javascripts/lib/jasmine-1.2.0/jasmine.js"></script> <script type="text/javascript" src="javascripts/lib/jasmine-1.2.0/jasmine-html.js"></script> <!-- Load files via support/jasmine.yml --> <script type="text/javascript"> (function() { var jasmineEnv = jasmine.getEnv(); jasmineEnv.updateInterval = 1000; var htmlReporter = new jasmine.HtmlReporter(); jasmineEnv.addReporter(htmlReporter); jasmineEnv.specFilter = function(spec) { return htmlReporter.specFilter(spec); }; var currentWindowOnload = window.onload; window.onload = function() { if (currentWindowOnload) { currentWindowOnload(); } execJasmine(); }; function execJasmine() { jasmineEnv.execute(); } })(); </script> </head> <body> </body> </html>
quasoft/gtfs-editor
test/jasmine/spec/SpecRunner.html
HTML
mit
1,239
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. 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. * * ***** END LICENSE BLOCK ***** */ ace.define('ace/mode/perl', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/mode/perl_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var PerlHighlightRules = require("./perl_highlight_rules").PerlHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = PerlHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode({start: "^=(begin|item)\\b", end: "^=(cut)\\b"}); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "#"; this.blockComment = [ {start: "=begin", end: "=cut"}, {start: "=item", end: "=cut"} ]; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.$id = "ace/mode/perl"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define('ace/mode/perl_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PerlHighlightRules = function() { var keywords = ( "base|constant|continue|else|elsif|for|foreach|format|goto|if|last|local|my|next|" + "no|package|parent|redo|require|scalar|sub|unless|until|while|use|vars" ); var buildinConstants = ("ARGV|ENV|INC|SIG"); var builtinFunctions = ( "getprotobynumber|getprotobyname|getservbyname|gethostbyaddr|" + "gethostbyname|getservbyport|getnetbyaddr|getnetbyname|getsockname|" + "getpeername|setpriority|getprotoent|setprotoent|getpriority|" + "endprotoent|getservent|setservent|endservent|sethostent|socketpair|" + "getsockopt|gethostent|endhostent|setsockopt|setnetent|quotemeta|" + "localtime|prototype|getnetent|endnetent|rewinddir|wantarray|getpwuid|" + "closedir|getlogin|readlink|endgrent|getgrgid|getgrnam|shmwrite|" + "shutdown|readline|endpwent|setgrent|readpipe|formline|truncate|" + "dbmclose|syswrite|setpwent|getpwnam|getgrent|getpwent|ucfirst|sysread|" + "setpgrp|shmread|sysseek|sysopen|telldir|defined|opendir|connect|" + "lcfirst|getppid|binmode|syscall|sprintf|getpgrp|readdir|seekdir|" + "waitpid|reverse|unshift|symlink|dbmopen|semget|msgrcv|rename|listen|" + "chroot|msgsnd|shmctl|accept|unpack|exists|fileno|shmget|system|" + "unlink|printf|gmtime|msgctl|semctl|values|rindex|substr|splice|" + "length|msgget|select|socket|return|caller|delete|alarm|ioctl|index|" + "undef|lstat|times|srand|chown|fcntl|close|write|umask|rmdir|study|" + "sleep|chomp|untie|print|utime|mkdir|atan2|split|crypt|flock|chmod|" + "BEGIN|bless|chdir|semop|shift|reset|link|stat|chop|grep|fork|dump|" + "join|open|tell|pipe|exit|glob|warn|each|bind|sort|pack|eval|push|" + "keys|getc|kill|seek|sqrt|send|wait|rand|tied|read|time|exec|recv|" + "eof|chr|int|ord|exp|pos|pop|sin|log|abs|oct|hex|tie|cos|vec|END|ref|" + "map|die|uc|lc|do" ); var keywordMapper = this.createKeywordMapper({ "keyword": keywords, "constant.language": buildinConstants, "support.function": builtinFunctions }, "identifier"); this.$rules = { "start" : [ { token : "comment.doc", regex : "^=(?:begin|item)\\b", next : "block_comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", // hex regex : "0x[0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "%#|\\$#|\\.\\.\\.|\\|\\|=|>>=|<<=|<=>|&&=|=>|!~|\\^=|&=|\\|=|\\.=|x=|%=|\\/=|\\*=|\\-=|\\+=|=~|\\*\\*|\\-\\-|\\.\\.|\\|\\||&&|\\+\\+|\\->|!=|==|>=|<=|>>|<<|,|=|\\?\\:|\\^|\\||x|%|\\/|\\*|<|&|\\\\|~|!|>|\\.|\\-|\\+|\\-C|\\-b|\\-S|\\-u|\\-t|\\-p|\\-l|\\-d|\\-f|\\-g|\\-s|\\-z|\\-k|\\-e|\\-O|\\-T|\\-B|\\-M|\\-A|\\-X|\\-W|\\-c|\\-R|\\-o|\\-x|\\-w|\\-r|\\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)" }, { token : "comment", regex : "#.*$" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", regex : '.+' } ], "block_comment": [ { token: "comment.doc", regex: "^=cut\\b", next: "start" }, { defaultToken: "comment.doc" } ] }; }; oop.inherits(PerlHighlightRules, TextHighlightRules); exports.PerlHighlightRules = PerlHighlightRules; }); ace.define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; }).call(FoldMode.prototype); });
lisalj/nextm_stage
wp-content/themes/parallelus-vellum/data-types/code-editor/js/ace/src-noconflict/mode-perl.js
JavaScript
gpl-2.0
13,129
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.analysis; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.RestTestCandidate; import org.elasticsearch.test.rest.parser.RestTestParseException; import java.io.IOException; public class AnalysisPolishRestIT extends ESRestTestCase { public AnalysisPolishRestIT(@Name("yaml") RestTestCandidate testCandidate) { super(testCandidate); } @ParametersFactory public static Iterable<Object[]> parameters() throws IOException, RestTestParseException { return ESRestTestCase.createParameters(0, 1); } }
queirozfcom/elasticsearch
plugins/analysis-stempel/src/test/java/org/elasticsearch/index/analysis/AnalysisPolishRestIT.java
Java
apache-2.0
1,526
<?php /** * @package WPSEO\Admin|Google_Search_Console */ /** * Class WPSEO_GSC_Bulk_Action */ class WPSEO_GSC_Bulk_Action { /** * Setting the listener on the bulk action post */ public function __construct() { if ( wp_verify_nonce( filter_input( INPUT_POST, 'wpseo_gsc_nonce' ), 'wpseo_gsc_nonce' ) ) { $this->handle_bulk_action(); } } /** * Handles the bulk action when there is an action posted */ private function handle_bulk_action() { if ( $bulk_action = $this->determine_bulk_action() ) { $this->run_bulk_action( $bulk_action, $this->posted_issues() ); wp_redirect( filter_input( INPUT_POST, '_wp_http_referer' ) ); exit; } } /** * Determine which bulk action is selected and return that value * * @return string|bool */ private function determine_bulk_action() { // If posted action is the selected one above the table, return that value. if ( ( $action = filter_input( INPUT_POST, 'action' ) ) && $action !== '-1' ) { return $action; } // If posted action is the selected one below the table, return that value. if ( ( $action = filter_input( INPUT_POST, 'action2' ) ) && $action !== '-1' ) { return $action; } return false; } /** * Get the posted issues and return them * * @return array */ private function posted_issues() { if ( $issues = filter_input( INPUT_POST, 'wpseo_crawl_issues', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY ) ) { return $issues; } // Fallback if issues are empty. return array(); } /** * Runs the bulk action * * @param string $bulk_action Action type. * @param array $issues Set of issues to apply to. */ private function run_bulk_action( $bulk_action, $issues ) { switch ( $bulk_action ) { case 'mark_as_fixed' : array_map( array( $this, 'action_mark_as_fixed' ), $issues ); break; } } /** * Marks the issue as fixed * * @param string $issue Issue URL. * * @return string */ private function action_mark_as_fixed( $issue ) { new WPSEO_GSC_Marker( $issue ); return $issue; } }
diesousil/vanessaqualtieriwebsite
www/app/webroot/blog/wp-content/plugins/wordpress-seo/admin/google_search_console/class-gsc-bulk-action.php
PHP
gpl-2.0
2,064
package com.intellij.tasks.jira.jql.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.tasks.jira.jql.psi.JqlElementVisitor; import com.intellij.tasks.jira.jql.psi.JqlList; import com.intellij.tasks.jira.jql.psi.JqlOperand; import org.jetbrains.annotations.NotNull; /** * @author Mikhail Golubev */ public class JqlListImpl extends JqlElementImpl implements JqlList { public JqlListImpl(@NotNull ASTNode node) { super(node); } @Override public void accept(JqlElementVisitor visitor) { visitor.visitJqlList(this); } @Override public JqlOperand[] getElements() { return findChildrenByClass(JqlOperand.class); } }
liveqmock/platform-tools-idea
plugins/tasks/tasks-core/src/com/intellij/tasks/jira/jql/psi/impl/JqlListImpl.java
Java
apache-2.0
658
<!DOCTYPE html> <title>flexbox | flexcontainer via generated content</title> <link rel="author" href="http://opera.com" title="Opera Software"> <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-container"> <link rel="match" href="flexbox_generated-flex-ref.html"> <style> div { background: #3366cc; border: 1px solid black; display: flex; } div::after { content: "xxx"; background: yellow; margin: 1em; width: 200px; height: 2em; display: flex; } </style> <div></div>
js0701/chromium-crosswalk
third_party/WebKit/LayoutTests/imported/csswg-test/css-flexbox-1/flexbox_generated-nested-flex.html
HTML
bsd-3-clause
492
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Class to encapsulate an editable field that blends in with * the style of the page. The field can be fixed height, grow with its * contents, or have a min height after which it grows to its contents. * This is a goog.editor.Field, but with blending and sizing capabilities, * and avoids using an iframe whenever possible. * * @author [email protected] (Nick Santos) * @see ../demos/editor/seamlessfield.html */ goog.provide('goog.editor.SeamlessField'); goog.require('goog.cssom.iframe.style'); goog.require('goog.dom'); goog.require('goog.dom.Range'); goog.require('goog.dom.TagName'); goog.require('goog.dom.safe'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.editor.Field'); goog.require('goog.editor.icontent'); goog.require('goog.editor.icontent.FieldFormatInfo'); goog.require('goog.editor.icontent.FieldStyleInfo'); goog.require('goog.editor.node'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.html.uncheckedconversions'); goog.require('goog.log'); goog.require('goog.string.Const'); goog.require('goog.style'); /** * This class encapsulates an editable field that blends in with the * surrounding page. * To see events fired by this object, please see the base class. * * @param {string} id An identifer for the field. This is used to find the * field and the element associated with this field. * @param {Document=} opt_doc The document that the element with the given * id can be found it. * @constructor * @extends {goog.editor.Field} */ goog.editor.SeamlessField = function(id, opt_doc) { goog.editor.Field.call(this, id, opt_doc); }; goog.inherits(goog.editor.SeamlessField, goog.editor.Field); /** * @override */ goog.editor.SeamlessField.prototype.logger = goog.log.getLogger('goog.editor.SeamlessField'); // Functions dealing with field sizing. /** * The key used for listening for the "dragover" event. * @type {goog.events.Key} * @private */ goog.editor.SeamlessField.prototype.listenForDragOverEventKey_; /** * The key used for listening for the iframe "load" event. * @type {goog.events.Key} * @private */ goog.editor.SeamlessField.prototype.listenForIframeLoadEventKey_; /** * Sets the min height of this editable field's iframe. Only used in growing * mode when an iframe is used. This will cause an immediate field sizing to * update the field if necessary based on the new min height. * @param {number} height The min height specified as a number of pixels, * e.g., 75. */ goog.editor.SeamlessField.prototype.setMinHeight = function(height) { if (height == this.minHeight_) { // Do nothing if the min height isn't changing. return; } this.minHeight_ = height; if (this.usesIframe()) { this.doFieldSizingGecko(); } }; /** * Whether the field should be rendered with a fixed height, or should expand * to fit its contents. * @type {boolean} * @private */ goog.editor.SeamlessField.prototype.isFixedHeight_ = false; /** * Whether the fixed-height handling has been overridden manually. * @type {boolean} * @private */ goog.editor.SeamlessField.prototype.isFixedHeightOverridden_ = false; /** * @return {boolean} Whether the field should be rendered with a fixed * height, or should expand to fit its contents. * @override */ goog.editor.SeamlessField.prototype.isFixedHeight = function() { return this.isFixedHeight_; }; /** * @param {boolean} newVal Explicitly set whether the field should be * of a fixed-height. This overrides auto-detection. */ goog.editor.SeamlessField.prototype.overrideFixedHeight = function(newVal) { this.isFixedHeight_ = newVal; this.isFixedHeightOverridden_ = true; }; /** * Auto-detect whether the current field should have a fixed height. * @private */ goog.editor.SeamlessField.prototype.autoDetectFixedHeight_ = function() { if (!this.isFixedHeightOverridden_) { var originalElement = this.getOriginalElement(); if (originalElement) { this.isFixedHeight_ = goog.style.getComputedOverflowY(originalElement) == 'auto'; } } }; /** * Resize the iframe in response to the wrapper div changing size. * @private */ goog.editor.SeamlessField.prototype.handleOuterDocChange_ = function() { if (this.isEventStopped(goog.editor.Field.EventType.CHANGE)) { return; } this.sizeIframeToWrapperGecko_(); }; /** * Sizes the iframe to its body's height. * @private */ goog.editor.SeamlessField.prototype.sizeIframeToBodyHeightGecko_ = function() { if (this.acquireSizeIframeLockGecko_()) { var resized = false; var ifr = this.getEditableIframe(); if (ifr) { var fieldHeight = this.getIframeBodyHeightGecko_(); if (this.minHeight_) { fieldHeight = Math.max(fieldHeight, this.minHeight_); } if (parseInt(goog.style.getStyle(ifr, 'height'), 10) != fieldHeight) { ifr.style.height = fieldHeight + 'px'; resized = true; } } this.releaseSizeIframeLockGecko_(); if (resized) { this.dispatchEvent(goog.editor.Field.EventType.IFRAME_RESIZED); } } }; /** * @return {number} The height of the editable iframe's body. * @private */ goog.editor.SeamlessField.prototype.getIframeBodyHeightGecko_ = function() { var ifr = this.getEditableIframe(); var body = ifr.contentDocument.body; var htmlElement = /** @type {!HTMLElement} */ (body.parentNode); // If the iframe's height is 0, then the offsetHeight/scrollHeight of the // HTML element in the iframe can be totally wack (i.e. too large // by 50-500px). Also, in standard's mode the clientHeight is 0. if (parseInt(goog.style.getStyle(ifr, 'height'), 10) === 0) { goog.style.setStyle(ifr, 'height', 1 + 'px'); } var fieldHeight; if (goog.editor.node.isStandardsMode(body)) { // If in standards-mode, // grab the HTML element as it will contain all the field's // contents. The body's height, for example, will not include that of // floated images at the bottom in standards mode. // Note that this value include all scrollbars *except* for scrollbars // on the HTML element itself. fieldHeight = htmlElement.offsetHeight; } else { // In quirks-mode, the body-element always seems // to size to the containing window. The html-element however, // sizes to the content, and can thus end up with a value smaller // than its child body-element if the content is shrinking. // We want to make the iframe shrink too when the content shrinks, // so rather than size the iframe to the body-element, size it to // the html-element. fieldHeight = htmlElement.scrollHeight; // If there is a horizontal scroll, add in the thickness of the // scrollbar. if (htmlElement.clientHeight != htmlElement.offsetHeight) { fieldHeight += goog.editor.SeamlessField.getScrollbarWidth_(); } } return fieldHeight; }; /** * Grabs the width of a scrollbar from the browser and caches the result. * @return {number} The scrollbar width in pixels. * @private */ goog.editor.SeamlessField.getScrollbarWidth_ = function() { return goog.editor.SeamlessField.scrollbarWidth_ || (goog.editor.SeamlessField.scrollbarWidth_ = goog.style.getScrollbarWidth()); }; /** * Sizes the iframe to its container div's width. The width of the div * is controlled by its containing context, not by its contents. * if it extends outside of it's contents, then it gets a horizontal scroll. * @private */ goog.editor.SeamlessField.prototype.sizeIframeToWrapperGecko_ = function() { if (this.acquireSizeIframeLockGecko_()) { var ifr = this.getEditableIframe(); var field = this.getElement(); var resized = false; if (ifr && field) { var fieldPaddingBox; var widthDiv = /** @type {!HTMLElement} */ (ifr.parentNode); var width = widthDiv.offsetWidth; if (parseInt(goog.style.getStyle(ifr, 'width'), 10) != width) { fieldPaddingBox = goog.style.getPaddingBox(field); ifr.style.width = width + 'px'; field.style.width = width - fieldPaddingBox.left - fieldPaddingBox.right + 'px'; resized = true; } var height = widthDiv.offsetHeight; if (this.isFixedHeight() && parseInt(goog.style.getStyle(ifr, 'height'), 10) != height) { if (!fieldPaddingBox) { fieldPaddingBox = goog.style.getPaddingBox(field); } ifr.style.height = height + 'px'; field.style.height = height - fieldPaddingBox.top - fieldPaddingBox.bottom + 'px'; resized = true; } } this.releaseSizeIframeLockGecko_(); if (resized) { this.dispatchEvent(goog.editor.Field.EventType.IFRAME_RESIZED); } } }; /** * Perform all the sizing immediately. */ goog.editor.SeamlessField.prototype.doFieldSizingGecko = function() { // Because doFieldSizingGecko can be called after a setTimeout // it is possible that the field has been destroyed before this call // to do the sizing is executed. Check for field existence and do nothing // if it has already been destroyed. if (this.getElement()) { // The order of operations is important here. Sizing the iframe to the // wrapper could cause the width to change, which could change the line // wrapping, which could change the body height. So we need to do that // first, then size the iframe to fit the body height. this.sizeIframeToWrapperGecko_(); if (!this.isFixedHeight()) { this.sizeIframeToBodyHeightGecko_(); } } }; /** * Acquires a lock on resizing the field iframe. This is used to ensure that * modifications we make while in a mutation event handler don't cause * infinite loops. * @return {boolean} False if the lock is already acquired. * @private */ goog.editor.SeamlessField.prototype.acquireSizeIframeLockGecko_ = function() { if (this.sizeIframeLock_) { return false; } return this.sizeIframeLock_ = true; }; /** * Releases a lock on resizing the field iframe. This is used to ensure that * modifications we make while in a mutation event handler don't cause * infinite loops. * @private */ goog.editor.SeamlessField.prototype.releaseSizeIframeLockGecko_ = function() { this.sizeIframeLock_ = false; }; // Functions dealing with blending in with the surrounding page. /** * String containing the css rules that, if applied to a document's body, * would style that body as if it were the original element we made editable. * See goog.cssom.iframe.style.getElementContext for more details. * @type {string} * @private */ goog.editor.SeamlessField.prototype.iframeableCss_ = ''; /** * Gets the css rules that should be used to style an iframe's body as if it * were the original element that we made editable. * @param {boolean=} opt_forceRegeneration Set to true to not read the cached * copy and instead completely regenerate the css rules. * @return {string} The string containing the css rules to use. */ goog.editor.SeamlessField.prototype.getIframeableCss = function( opt_forceRegeneration) { if (!this.iframeableCss_ || opt_forceRegeneration) { var originalElement = this.getOriginalElement(); if (originalElement) { this.iframeableCss_ = goog.cssom.iframe.style.getElementContext(originalElement, opt_forceRegeneration); } } return this.iframeableCss_; }; /** * Sets the css rules that should be used inside the editable iframe. * Note: to clear the css cache between makeNotEditable/makeEditable, * call this with "" as iframeableCss. * TODO(user): Unify all these css setting methods + Nick's open * CL. This is getting ridiculous. * @param {string} iframeableCss String containing the css rules to use. */ goog.editor.SeamlessField.prototype.setIframeableCss = function(iframeableCss) { this.iframeableCss_ = iframeableCss; }; /** * Used to ensure that CSS stylings are only installed once for none * iframe seamless mode. * TODO(user): Make it a formal part of the API that you can only * set one set of styles globally. * In seamless, non-iframe mode, all the stylings would go in the * same document and conflict. * @type {boolean} * @private */ goog.editor.SeamlessField.haveInstalledCss_ = false; /** * Applies CSS from the wrapper-div to the field iframe. */ goog.editor.SeamlessField.prototype.inheritBlendedCSS = function() { // No-op if the field isn't using an iframe. if (!this.usesIframe()) { return; } var field = this.getElement(); var head = goog.dom.getDomHelper(field).getElementsByTagNameAndClass( goog.dom.TagName.HEAD)[0]; if (head) { // We created this <head>, and we know the only thing we put in there // is a <style> block. So it's safe to blow away all the children // as part of rewriting the styles. goog.dom.removeChildren(head); } // Force a cache-clearing in CssUtil - this function was called because // we're applying the 'blend' for the first time, or because we // *need* to recompute the blend. var newCSS = this.getIframeableCss(true); goog.style.installStyles(newCSS, field); }; // Overridden methods. /** @override */ goog.editor.SeamlessField.prototype.usesIframe = function() { // TODO(user): Switch Firefox to using contentEditable // rather than designMode iframe once contentEditable support // is less buggy. return !goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE; }; /** @override */ goog.editor.SeamlessField.prototype.setupMutationEventHandlersGecko = function() { goog.editor.SeamlessField.superClass_.setupMutationEventHandlersGecko.call( this); if (this.usesIframe()) { var iframe = this.getEditableIframe(); var outerDoc = iframe.ownerDocument; this.eventRegister.listen(outerDoc, goog.editor.Field.MUTATION_EVENTS_GECKO, this.handleOuterDocChange_, true); // If the images load after we do the initial sizing, then this will // force a field resize. this.listenForIframeLoadEventKey_ = goog.events.listenOnce( this.getEditableDomHelper().getWindow(), goog.events.EventType.LOAD, this.sizeIframeToBodyHeightGecko_, true, this); this.eventRegister.listen(outerDoc, 'DOMAttrModified', goog.bind(this.handleDomAttrChange, this, this.handleOuterDocChange_), true); } }; /** @override */ goog.editor.SeamlessField.prototype.handleChange = function() { if (this.isEventStopped(goog.editor.Field.EventType.CHANGE)) { return; } goog.editor.SeamlessField.superClass_.handleChange.call(this); if (this.usesIframe()) { this.sizeIframeToBodyHeightGecko_(); } }; /** @override */ goog.editor.SeamlessField.prototype.dispatchBlur = function() { if (this.isEventStopped(goog.editor.Field.EventType.BLUR)) { return; } goog.editor.SeamlessField.superClass_.dispatchBlur.call(this); // Clear the selection and restore the current range back after collapsing // it. The ideal solution would have been to just leave the range intact; but // when there are multiple fields present on the page, its important that // the selection isn't retained when we switch between the fields. We also // have to make sure that the cursor position is retained when we tab in and // out of a field and our approach addresses both these issues. // Another point to note is that we do it on a setTimeout to allow for // DOM modifications on blur. Otherwise, something like setLoremIpsum will // leave a blinking cursor in the field even though it's blurred. if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE && !goog.editor.BrowserFeature.CLEARS_SELECTION_WHEN_FOCUS_LEAVES) { var win = this.getEditableDomHelper().getWindow(); var dragging = false; goog.events.unlistenByKey(this.listenForDragOverEventKey_); this.listenForDragOverEventKey_ = goog.events.listenOnce( win.document.body, 'dragover', function() { dragging = true; }); goog.global.setTimeout(goog.bind(function() { // Do not clear the selection if we're only dragging text. // This addresses a bug on FF1.5/linux where dragging fires a blur, // but clearing the selection confuses Firefox's drag-and-drop // implementation. For more info, see http://b/1061064 if (!dragging) { if (this.editableDomHelper) { var rng = this.getRange(); // If there are multiple fields on a page, we need to make sure that // the selection isn't retained when we switch between fields. We // could have collapsed the range but there is a bug in GECKO where // the selection stays highlighted even though its backing range is // collapsed (http://b/1390115). To get around this, we clear the // selection and restore the collapsed range back in. Restoring the // range is important so that the cursor stays intact when we tab out // and into a field (See http://b/1790301 for additional details on // this). var iframeWindow = this.editableDomHelper.getWindow(); goog.dom.Range.clearSelection(iframeWindow); if (rng) { rng.collapse(true); rng.select(); } } } }, this), 0); } }; /** @override */ goog.editor.SeamlessField.prototype.turnOnDesignModeGecko = function() { goog.editor.SeamlessField.superClass_.turnOnDesignModeGecko.call(this); var doc = this.getEditableDomHelper().getDocument(); doc.execCommand('enableInlineTableEditing', false, 'false'); doc.execCommand('enableObjectResizing', false, 'false'); }; /** @override */ goog.editor.SeamlessField.prototype.installStyles = function() { if (!this.usesIframe()) { if (!goog.editor.SeamlessField.haveInstalledCss_) { if (this.cssStyles) { goog.style.installStyles(this.cssStyles, this.getElement()); } // TODO(user): this should be reset to false when the editor is quit. // In non-iframe mode, CSS styles should only be instaled once. goog.editor.SeamlessField.haveInstalledCss_ = true; } } }; /** @override */ goog.editor.SeamlessField.prototype.makeEditableInternal = function( opt_iframeSrc) { if (this.usesIframe()) { goog.editor.SeamlessField.superClass_.makeEditableInternal.call(this, opt_iframeSrc); } else { var field = this.getOriginalElement(); if (field) { this.setupFieldObject(field); field.contentEditable = true; this.injectContents(field.innerHTML, field); this.handleFieldLoad(); } } }; /** @override */ goog.editor.SeamlessField.prototype.handleFieldLoad = function() { if (this.usesIframe()) { // If the CSS inheriting code screws up (e.g. makes fonts too large) and // the field is sized off in goog.editor.Field.makeIframeField, then we need // to size it correctly, but it needs to be visible for the browser // to have fully rendered it. We need to put this on a timeout to give // the browser time to render. var self = this; goog.global.setTimeout(function() { self.doFieldSizingGecko(); }, 0); } goog.editor.SeamlessField.superClass_.handleFieldLoad.call(this); }; /** @override */ goog.editor.SeamlessField.prototype.getIframeAttributes = function() { return { 'frameBorder': 0, 'style': 'padding:0;' }; }; /** @override */ goog.editor.SeamlessField.prototype.attachIframe = function(iframe) { this.autoDetectFixedHeight_(); var field = this.getOriginalElement(); var dh = goog.dom.getDomHelper(field); // Grab the width/height values of the field before modifying any CSS // as some of the modifications affect its size (e.g. innerHTML='') // Here, we set the size of the field to fixed so there's not too much // jiggling when we set the innerHTML of the field. var oldWidth = field.style.width; var oldHeight = field.style.height; goog.style.setStyle(field, 'visibility', 'hidden'); // If there is a floated element at the bottom of the field, // then it needs a clearing div at the end to cause the clientHeight // to contain the entire field. // Also, with css re-writing, the margins of the first/last // paragraph don't seem to get included in the clientHeight. Specifically, // the extra divs below force the field's clientHeight to include the // margins on the first and last elements contained within it. var startDiv = dh.createDom(goog.dom.TagName.DIV, {'style': 'height:0;clear:both', 'innerHTML': '&nbsp;'}); var endDiv = startDiv.cloneNode(true); field.insertBefore(startDiv, field.firstChild); goog.dom.appendChild(field, endDiv); var contentBox = goog.style.getContentBoxSize(field); var width = contentBox.width; var height = contentBox.height; var html = ''; if (this.isFixedHeight()) { html = '&nbsp;'; goog.style.setStyle(field, 'position', 'relative'); goog.style.setStyle(field, 'overflow', 'visible'); goog.style.setStyle(iframe, 'position', 'absolute'); goog.style.setStyle(iframe, 'top', '0'); goog.style.setStyle(iframe, 'left', '0'); } goog.style.setSize(field, width, height); // In strict mode, browsers put blank space at the bottom and right // if a field when it has an iframe child, to fill up the remaining line // height. So make the line height = 0. if (goog.editor.node.isStandardsMode(field)) { this.originalFieldLineHeight_ = field.style.lineHeight; goog.style.setStyle(field, 'lineHeight', '0'); } goog.editor.node.replaceInnerHtml(field, html); // Set the initial size goog.style.setSize(iframe, width, height); goog.style.setSize(field, oldWidth, oldHeight); goog.style.setStyle(field, 'visibility', ''); goog.dom.appendChild(field, iframe); // Only write if its not IE HTTPS in which case we're waiting for load. if (!this.shouldLoadAsynchronously()) { var doc = iframe.contentWindow.document; if (goog.editor.node.isStandardsMode(iframe.ownerDocument)) { doc.open(); var emptyHtml = goog.html.uncheckedconversions .safeHtmlFromStringKnownToSatisfyTypeContract( goog.string.Const.from('HTML from constant string'), '<!DOCTYPE HTML><html></html>'); goog.dom.safe.documentWrite(doc, emptyHtml); doc.close(); } } }; /** @override */ goog.editor.SeamlessField.prototype.getFieldFormatInfo = function( extraStyles) { var originalElement = this.getOriginalElement(); if (originalElement) { return new goog.editor.icontent.FieldFormatInfo( this.id, goog.editor.node.isStandardsMode(originalElement), true, this.isFixedHeight(), extraStyles); } throw Error('no field'); }; /** @override */ goog.editor.SeamlessField.prototype.writeIframeContent = function( iframe, innerHtml, extraStyles) { // For seamless iframes, hide the iframe while we're laying it out to // prevent the flicker. goog.style.setStyle(iframe, 'visibility', 'hidden'); var formatInfo = this.getFieldFormatInfo(extraStyles); var styleInfo = new goog.editor.icontent.FieldStyleInfo( this.getOriginalElement(), this.cssStyles + this.getIframeableCss()); goog.editor.icontent.writeNormalInitialBlendedIframe( formatInfo, innerHtml, styleInfo, iframe); this.doFieldSizingGecko(); goog.style.setStyle(iframe, 'visibility', 'visible'); }; /** @override */ goog.editor.SeamlessField.prototype.restoreDom = function() { // TODO(user): Consider only removing the iframe if we are // restoring the original node. if (this.usesIframe()) { goog.dom.removeNode(this.getEditableIframe()); } }; /** @override */ goog.editor.SeamlessField.prototype.clearListeners = function() { goog.events.unlistenByKey(this.listenForDragOverEventKey_); goog.events.unlistenByKey(this.listenForIframeLoadEventKey_); goog.editor.SeamlessField.base(this, 'clearListeners'); };
ChildrenOfUr/Ilmenscript
web/closure-library/closure/goog/editor/seamlessfield.js
JavaScript
bsd-3-clause
24,681
<section data-ng-controller="SettingsController"> <div class="page-header"> <h1>Settings</h1> </div> <div class="row"> <nav class="col-sm-3 col-md-3"> <ul class="nav nav-pills nav-stacked"> <li data-ui-sref-active="active"> <a data-ui-sref="settings.profile">Edit Profile</a> </li> <li data-ui-sref-active="active"> <a data-ui-sref="settings.picture">Change Profile Picture</a> </li> <li data-ui-sref-active="active" data-ng-show="user.provider === 'local'"> <a data-ui-sref="settings.password">Change Password</a> </li> <li data-ui-sref-active="active"> <a data-ui-sref="settings.accounts">Manage Social Accounts</a> </li> </ul> </nav> <div class="col-sm-9 col-md-8 settings-view"> <div data-ui-view></div> </div> </div> </section>
davaaana/sanhvv
public/modules/user/views/settings/settings.client.view.html
HTML
mit
883
// SPDX-License-Identifier: GPL-2.0+ /* * dt282x.c * Comedi driver for Data Translation DT2821 series * * COMEDI - Linux Control and Measurement Device Interface * Copyright (C) 1997-8 David A. Schleef <[email protected]> */ /* * Driver: dt282x * Description: Data Translation DT2821 series (including DT-EZ) * Author: ds * Devices: [Data Translation] DT2821 (dt2821), DT2821-F-16SE (dt2821-f), * DT2821-F-8DI (dt2821-f), DT2821-G-16SE (dt2821-g), * DT2821-G-8DI (dt2821-g), DT2823 (dt2823), DT2824-PGH (dt2824-pgh), * DT2824-PGL (dt2824-pgl), DT2825 (dt2825), DT2827 (dt2827), * DT2828 (dt2828), DT2928 (dt2829), DT21-EZ (dt21-ez), DT23-EZ (dt23-ez), * DT24-EZ (dt24-ez), DT24-EZ-PGL (dt24-ez-pgl) * Status: complete * Updated: Wed, 22 Aug 2001 17:11:34 -0700 * * Configuration options: * [0] - I/O port base address * [1] - IRQ (optional, required for async command support) * [2] - DMA 1 (optional, required for async command support) * [3] - DMA 2 (optional, required for async command support) * [4] - AI jumpered for 0=single ended, 1=differential * [5] - AI jumpered for 0=straight binary, 1=2's complement * [6] - AO 0 data format (deprecated, see below) * [7] - AO 1 data format (deprecated, see below) * [8] - AI jumpered for 0=[-10,10]V, 1=[0,10], 2=[-5,5], 3=[0,5] * [9] - AO channel 0 range (deprecated, see below) * [10]- AO channel 1 range (deprecated, see below) * * Notes: * - AO commands might be broken. * - If you try to run a command on both the AI and AO subdevices * simultaneously, bad things will happen. The driver needs to * be fixed to check for this situation and return an error. * - AO range is not programmable. The AO subdevice has a range_table * containing all the possible analog output ranges. Use the range * that matches your board configuration to convert between data * values and physical units. The format of the data written to the * board is handled automatically based on the unipolar/bipolar * range that is selected. */ #include <linux/module.h> #include <linux/delay.h> #include <linux/gfp.h> #include <linux/interrupt.h> #include <linux/io.h> #include "../comedidev.h" #include "comedi_isadma.h" /* * Register map */ #define DT2821_ADCSR_REG 0x00 #define DT2821_ADCSR_ADERR BIT(15) #define DT2821_ADCSR_ADCLK BIT(9) #define DT2821_ADCSR_MUXBUSY BIT(8) #define DT2821_ADCSR_ADDONE BIT(7) #define DT2821_ADCSR_IADDONE BIT(6) #define DT2821_ADCSR_GS(x) (((x) & 0x3) << 4) #define DT2821_ADCSR_CHAN(x) (((x) & 0xf) << 0) #define DT2821_CHANCSR_REG 0x02 #define DT2821_CHANCSR_LLE BIT(15) #define DT2821_CHANCSR_TO_PRESLA(x) (((x) >> 8) & 0xf) #define DT2821_CHANCSR_NUMB(x) ((((x) - 1) & 0xf) << 0) #define DT2821_ADDAT_REG 0x04 #define DT2821_DACSR_REG 0x06 #define DT2821_DACSR_DAERR BIT(15) #define DT2821_DACSR_YSEL(x) ((x) << 9) #define DT2821_DACSR_SSEL BIT(8) #define DT2821_DACSR_DACRDY BIT(7) #define DT2821_DACSR_IDARDY BIT(6) #define DT2821_DACSR_DACLK BIT(5) #define DT2821_DACSR_HBOE BIT(1) #define DT2821_DACSR_LBOE BIT(0) #define DT2821_DADAT_REG 0x08 #define DT2821_DIODAT_REG 0x0a #define DT2821_SUPCSR_REG 0x0c #define DT2821_SUPCSR_DMAD BIT(15) #define DT2821_SUPCSR_ERRINTEN BIT(14) #define DT2821_SUPCSR_CLRDMADNE BIT(13) #define DT2821_SUPCSR_DDMA BIT(12) #define DT2821_SUPCSR_DS(x) (((x) & 0x3) << 10) #define DT2821_SUPCSR_DS_PIO DT2821_SUPCSR_DS(0) #define DT2821_SUPCSR_DS_AD_CLK DT2821_SUPCSR_DS(1) #define DT2821_SUPCSR_DS_DA_CLK DT2821_SUPCSR_DS(2) #define DT2821_SUPCSR_DS_AD_TRIG DT2821_SUPCSR_DS(3) #define DT2821_SUPCSR_BUFFB BIT(9) #define DT2821_SUPCSR_SCDN BIT(8) #define DT2821_SUPCSR_DACON BIT(7) #define DT2821_SUPCSR_ADCINIT BIT(6) #define DT2821_SUPCSR_DACINIT BIT(5) #define DT2821_SUPCSR_PRLD BIT(4) #define DT2821_SUPCSR_STRIG BIT(3) #define DT2821_SUPCSR_XTRIG BIT(2) #define DT2821_SUPCSR_XCLK BIT(1) #define DT2821_SUPCSR_BDINIT BIT(0) #define DT2821_TMRCTR_REG 0x0e #define DT2821_TMRCTR_PRESCALE(x) (((x) & 0xf) << 8) #define DT2821_TMRCTR_DIVIDER(x) ((255 - ((x) & 0xff)) << 0) /* Pacer Clock */ #define DT2821_OSC_BASE 250 /* 4 MHz (in nanoseconds) */ #define DT2821_PRESCALE(x) BIT(x) #define DT2821_PRESCALE_MAX 15 #define DT2821_DIVIDER_MAX 255 #define DT2821_OSC_MAX (DT2821_OSC_BASE * \ DT2821_PRESCALE(DT2821_PRESCALE_MAX) * \ DT2821_DIVIDER_MAX) static const struct comedi_lrange range_dt282x_ai_lo_bipolar = { 4, { BIP_RANGE(10), BIP_RANGE(5), BIP_RANGE(2.5), BIP_RANGE(1.25) } }; static const struct comedi_lrange range_dt282x_ai_lo_unipolar = { 4, { UNI_RANGE(10), UNI_RANGE(5), UNI_RANGE(2.5), UNI_RANGE(1.25) } }; static const struct comedi_lrange range_dt282x_ai_5_bipolar = { 4, { BIP_RANGE(5), BIP_RANGE(2.5), BIP_RANGE(1.25), BIP_RANGE(0.625) } }; static const struct comedi_lrange range_dt282x_ai_5_unipolar = { 4, { UNI_RANGE(5), UNI_RANGE(2.5), UNI_RANGE(1.25), UNI_RANGE(0.625) } }; static const struct comedi_lrange range_dt282x_ai_hi_bipolar = { 4, { BIP_RANGE(10), BIP_RANGE(1), BIP_RANGE(0.1), BIP_RANGE(0.02) } }; static const struct comedi_lrange range_dt282x_ai_hi_unipolar = { 4, { UNI_RANGE(10), UNI_RANGE(1), UNI_RANGE(0.1), UNI_RANGE(0.02) } }; /* * The Analog Output range is set per-channel using jumpers on the board. * All of these ranges may not be available on some DT2821 series boards. * The default jumper setting has both channels set for +/-10V output. */ static const struct comedi_lrange dt282x_ao_range = { 5, { BIP_RANGE(10), BIP_RANGE(5), BIP_RANGE(2.5), UNI_RANGE(10), UNI_RANGE(5), } }; struct dt282x_board { const char *name; unsigned int ai_maxdata; int adchan_se; int adchan_di; int ai_speed; int ispgl; int dachan; unsigned int ao_maxdata; }; static const struct dt282x_board boardtypes[] = { { .name = "dt2821", .ai_maxdata = 0x0fff, .adchan_se = 16, .adchan_di = 8, .ai_speed = 20000, .dachan = 2, .ao_maxdata = 0x0fff, }, { .name = "dt2821-f", .ai_maxdata = 0x0fff, .adchan_se = 16, .adchan_di = 8, .ai_speed = 6500, .dachan = 2, .ao_maxdata = 0x0fff, }, { .name = "dt2821-g", .ai_maxdata = 0x0fff, .adchan_se = 16, .adchan_di = 8, .ai_speed = 4000, .dachan = 2, .ao_maxdata = 0x0fff, }, { .name = "dt2823", .ai_maxdata = 0xffff, .adchan_di = 4, .ai_speed = 10000, .dachan = 2, .ao_maxdata = 0xffff, }, { .name = "dt2824-pgh", .ai_maxdata = 0x0fff, .adchan_se = 16, .adchan_di = 8, .ai_speed = 20000, }, { .name = "dt2824-pgl", .ai_maxdata = 0x0fff, .adchan_se = 16, .adchan_di = 8, .ai_speed = 20000, .ispgl = 1, }, { .name = "dt2825", .ai_maxdata = 0x0fff, .adchan_se = 16, .adchan_di = 8, .ai_speed = 20000, .ispgl = 1, .dachan = 2, .ao_maxdata = 0x0fff, }, { .name = "dt2827", .ai_maxdata = 0xffff, .adchan_di = 4, .ai_speed = 10000, .dachan = 2, .ao_maxdata = 0x0fff, }, { .name = "dt2828", .ai_maxdata = 0x0fff, .adchan_se = 4, .ai_speed = 10000, .dachan = 2, .ao_maxdata = 0x0fff, }, { .name = "dt2829", .ai_maxdata = 0xffff, .adchan_se = 8, .ai_speed = 33250, .dachan = 2, .ao_maxdata = 0xffff, }, { .name = "dt21-ez", .ai_maxdata = 0x0fff, .adchan_se = 16, .adchan_di = 8, .ai_speed = 10000, .dachan = 2, .ao_maxdata = 0x0fff, }, { .name = "dt23-ez", .ai_maxdata = 0xffff, .adchan_se = 16, .adchan_di = 8, .ai_speed = 10000, }, { .name = "dt24-ez", .ai_maxdata = 0x0fff, .adchan_se = 16, .adchan_di = 8, .ai_speed = 10000, }, { .name = "dt24-ez-pgl", .ai_maxdata = 0x0fff, .adchan_se = 16, .adchan_di = 8, .ai_speed = 10000, .ispgl = 1, }, }; struct dt282x_private { struct comedi_isadma *dma; unsigned int ad_2scomp:1; unsigned int divisor; int dacsr; /* software copies of registers */ int adcsr; int supcsr; int ntrig; int nread; int dma_dir; }; static int dt282x_prep_ai_dma(struct comedi_device *dev, int dma_index, int n) { struct dt282x_private *devpriv = dev->private; struct comedi_isadma *dma = devpriv->dma; struct comedi_isadma_desc *desc = &dma->desc[dma_index]; if (!devpriv->ntrig) return 0; if (n == 0) n = desc->maxsize; if (n > devpriv->ntrig * 2) n = devpriv->ntrig * 2; devpriv->ntrig -= n / 2; desc->size = n; comedi_isadma_set_mode(desc, devpriv->dma_dir); comedi_isadma_program(desc); return n; } static int dt282x_prep_ao_dma(struct comedi_device *dev, int dma_index, int n) { struct dt282x_private *devpriv = dev->private; struct comedi_isadma *dma = devpriv->dma; struct comedi_isadma_desc *desc = &dma->desc[dma_index]; desc->size = n; comedi_isadma_set_mode(desc, devpriv->dma_dir); comedi_isadma_program(desc); return n; } static void dt282x_disable_dma(struct comedi_device *dev) { struct dt282x_private *devpriv = dev->private; struct comedi_isadma *dma = devpriv->dma; struct comedi_isadma_desc *desc; int i; for (i = 0; i < 2; i++) { desc = &dma->desc[i]; comedi_isadma_disable(desc->chan); } } static unsigned int dt282x_ns_to_timer(unsigned int *ns, unsigned int flags) { unsigned int prescale, base, divider; for (prescale = 0; prescale <= DT2821_PRESCALE_MAX; prescale++) { if (prescale == 1) /* 0 and 1 are both divide by 1 */ continue; base = DT2821_OSC_BASE * DT2821_PRESCALE(prescale); switch (flags & CMDF_ROUND_MASK) { case CMDF_ROUND_NEAREST: default: divider = DIV_ROUND_CLOSEST(*ns, base); break; case CMDF_ROUND_DOWN: divider = (*ns) / base; break; case CMDF_ROUND_UP: divider = DIV_ROUND_UP(*ns, base); break; } if (divider <= DT2821_DIVIDER_MAX) break; } if (divider > DT2821_DIVIDER_MAX) { prescale = DT2821_PRESCALE_MAX; divider = DT2821_DIVIDER_MAX; base = DT2821_OSC_BASE * DT2821_PRESCALE(prescale); } *ns = divider * base; return DT2821_TMRCTR_PRESCALE(prescale) | DT2821_TMRCTR_DIVIDER(divider); } static void dt282x_munge(struct comedi_device *dev, struct comedi_subdevice *s, unsigned short *buf, unsigned int nbytes) { struct dt282x_private *devpriv = dev->private; unsigned int val; int i; if (nbytes % 2) dev_err(dev->class_dev, "bug! odd number of bytes from dma xfer\n"); for (i = 0; i < nbytes / 2; i++) { val = buf[i]; val &= s->maxdata; if (devpriv->ad_2scomp) val = comedi_offset_munge(s, val); buf[i] = val; } } static unsigned int dt282x_ao_setup_dma(struct comedi_device *dev, struct comedi_subdevice *s, int cur_dma) { struct dt282x_private *devpriv = dev->private; struct comedi_isadma *dma = devpriv->dma; struct comedi_isadma_desc *desc = &dma->desc[cur_dma]; unsigned int nsamples = comedi_bytes_to_samples(s, desc->maxsize); unsigned int nbytes; nbytes = comedi_buf_read_samples(s, desc->virt_addr, nsamples); if (nbytes) dt282x_prep_ao_dma(dev, cur_dma, nbytes); else dev_err(dev->class_dev, "AO underrun\n"); return nbytes; } static void dt282x_ao_dma_interrupt(struct comedi_device *dev, struct comedi_subdevice *s) { struct dt282x_private *devpriv = dev->private; struct comedi_isadma *dma = devpriv->dma; struct comedi_isadma_desc *desc = &dma->desc[dma->cur_dma]; outw(devpriv->supcsr | DT2821_SUPCSR_CLRDMADNE, dev->iobase + DT2821_SUPCSR_REG); comedi_isadma_disable(desc->chan); if (!dt282x_ao_setup_dma(dev, s, dma->cur_dma)) s->async->events |= COMEDI_CB_OVERFLOW; dma->cur_dma = 1 - dma->cur_dma; } static void dt282x_ai_dma_interrupt(struct comedi_device *dev, struct comedi_subdevice *s) { struct dt282x_private *devpriv = dev->private; struct comedi_isadma *dma = devpriv->dma; struct comedi_isadma_desc *desc = &dma->desc[dma->cur_dma]; unsigned int nsamples = comedi_bytes_to_samples(s, desc->size); int ret; outw(devpriv->supcsr | DT2821_SUPCSR_CLRDMADNE, dev->iobase + DT2821_SUPCSR_REG); comedi_isadma_disable(desc->chan); dt282x_munge(dev, s, desc->virt_addr, desc->size); ret = comedi_buf_write_samples(s, desc->virt_addr, nsamples); if (ret != desc->size) return; devpriv->nread -= nsamples; if (devpriv->nread < 0) { dev_info(dev->class_dev, "nread off by one\n"); devpriv->nread = 0; } if (!devpriv->nread) { s->async->events |= COMEDI_CB_EOA; return; } #if 0 /* clear the dual dma flag, making this the last dma segment */ /* XXX probably wrong */ if (!devpriv->ntrig) { devpriv->supcsr &= ~DT2821_SUPCSR_DDMA; outw(devpriv->supcsr, dev->iobase + DT2821_SUPCSR_REG); } #endif /* restart the channel */ dt282x_prep_ai_dma(dev, dma->cur_dma, 0); dma->cur_dma = 1 - dma->cur_dma; } static irqreturn_t dt282x_interrupt(int irq, void *d) { struct comedi_device *dev = d; struct dt282x_private *devpriv = dev->private; struct comedi_subdevice *s = dev->read_subdev; struct comedi_subdevice *s_ao = dev->write_subdev; unsigned int supcsr, adcsr, dacsr; int handled = 0; if (!dev->attached) { dev_err(dev->class_dev, "spurious interrupt\n"); return IRQ_HANDLED; } adcsr = inw(dev->iobase + DT2821_ADCSR_REG); dacsr = inw(dev->iobase + DT2821_DACSR_REG); supcsr = inw(dev->iobase + DT2821_SUPCSR_REG); if (supcsr & DT2821_SUPCSR_DMAD) { if (devpriv->dma_dir == COMEDI_ISADMA_READ) dt282x_ai_dma_interrupt(dev, s); else dt282x_ao_dma_interrupt(dev, s_ao); handled = 1; } if (adcsr & DT2821_ADCSR_ADERR) { if (devpriv->nread != 0) { dev_err(dev->class_dev, "A/D error\n"); s->async->events |= COMEDI_CB_ERROR; } handled = 1; } if (dacsr & DT2821_DACSR_DAERR) { dev_err(dev->class_dev, "D/A error\n"); s_ao->async->events |= COMEDI_CB_ERROR; handled = 1; } #if 0 if (adcsr & DT2821_ADCSR_ADDONE) { unsigned short data; data = inw(dev->iobase + DT2821_ADDAT_REG); data &= s->maxdata; if (devpriv->ad_2scomp) data = comedi_offset_munge(s, data); comedi_buf_write_samples(s, &data, 1); devpriv->nread--; if (!devpriv->nread) { s->async->events |= COMEDI_CB_EOA; } else { if (supcsr & DT2821_SUPCSR_SCDN) outw(devpriv->supcsr | DT2821_SUPCSR_STRIG, dev->iobase + DT2821_SUPCSR_REG); } handled = 1; } #endif comedi_handle_events(dev, s); if (s_ao) comedi_handle_events(dev, s_ao); return IRQ_RETVAL(handled); } static void dt282x_load_changain(struct comedi_device *dev, int n, unsigned int *chanlist) { struct dt282x_private *devpriv = dev->private; int i; outw(DT2821_CHANCSR_LLE | DT2821_CHANCSR_NUMB(n), dev->iobase + DT2821_CHANCSR_REG); for (i = 0; i < n; i++) { unsigned int chan = CR_CHAN(chanlist[i]); unsigned int range = CR_RANGE(chanlist[i]); outw(devpriv->adcsr | DT2821_ADCSR_GS(range) | DT2821_ADCSR_CHAN(chan), dev->iobase + DT2821_ADCSR_REG); } outw(DT2821_CHANCSR_NUMB(n), dev->iobase + DT2821_CHANCSR_REG); } static int dt282x_ai_timeout(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned long context) { unsigned int status; status = inw(dev->iobase + DT2821_ADCSR_REG); switch (context) { case DT2821_ADCSR_MUXBUSY: if ((status & DT2821_ADCSR_MUXBUSY) == 0) return 0; break; case DT2821_ADCSR_ADDONE: if (status & DT2821_ADCSR_ADDONE) return 0; break; default: return -EINVAL; } return -EBUSY; } /* * Performs a single A/D conversion. * - Put channel/gain into channel-gain list * - preload multiplexer * - trigger conversion and wait for it to finish */ static int dt282x_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { struct dt282x_private *devpriv = dev->private; unsigned int val; int ret; int i; /* XXX should we really be enabling the ad clock here? */ devpriv->adcsr = DT2821_ADCSR_ADCLK; outw(devpriv->adcsr, dev->iobase + DT2821_ADCSR_REG); dt282x_load_changain(dev, 1, &insn->chanspec); outw(devpriv->supcsr | DT2821_SUPCSR_PRLD, dev->iobase + DT2821_SUPCSR_REG); ret = comedi_timeout(dev, s, insn, dt282x_ai_timeout, DT2821_ADCSR_MUXBUSY); if (ret) return ret; for (i = 0; i < insn->n; i++) { outw(devpriv->supcsr | DT2821_SUPCSR_STRIG, dev->iobase + DT2821_SUPCSR_REG); ret = comedi_timeout(dev, s, insn, dt282x_ai_timeout, DT2821_ADCSR_ADDONE); if (ret) return ret; val = inw(dev->iobase + DT2821_ADDAT_REG); val &= s->maxdata; if (devpriv->ad_2scomp) val = comedi_offset_munge(s, val); data[i] = val; } return i; } static int dt282x_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_cmd *cmd) { const struct dt282x_board *board = dev->board_ptr; struct dt282x_private *devpriv = dev->private; int err = 0; unsigned int arg; /* Step 1 : check if triggers are trivially valid */ err |= comedi_check_trigger_src(&cmd->start_src, TRIG_NOW); err |= comedi_check_trigger_src(&cmd->scan_begin_src, TRIG_FOLLOW | TRIG_EXT); err |= comedi_check_trigger_src(&cmd->convert_src, TRIG_TIMER); err |= comedi_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT); err |= comedi_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE); if (err) return 1; /* Step 2a : make sure trigger sources are unique */ err |= comedi_check_trigger_is_unique(cmd->scan_begin_src); err |= comedi_check_trigger_is_unique(cmd->stop_src); /* Step 2b : and mutually compatible */ if (err) return 2; /* Step 3: check if arguments are trivially valid */ err |= comedi_check_trigger_arg_is(&cmd->start_arg, 0); err |= comedi_check_trigger_arg_is(&cmd->scan_begin_arg, 0); err |= comedi_check_trigger_arg_max(&cmd->convert_arg, DT2821_OSC_MAX); err |= comedi_check_trigger_arg_min(&cmd->convert_arg, board->ai_speed); err |= comedi_check_trigger_arg_is(&cmd->scan_end_arg, cmd->chanlist_len); if (cmd->stop_src == TRIG_COUNT) err |= comedi_check_trigger_arg_min(&cmd->stop_arg, 1); else /* TRIG_EXT | TRIG_NONE */ err |= comedi_check_trigger_arg_is(&cmd->stop_arg, 0); if (err) return 3; /* step 4: fix up any arguments */ arg = cmd->convert_arg; devpriv->divisor = dt282x_ns_to_timer(&arg, cmd->flags); err |= comedi_check_trigger_arg_is(&cmd->convert_arg, arg); if (err) return 4; return 0; } static int dt282x_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s) { struct dt282x_private *devpriv = dev->private; struct comedi_isadma *dma = devpriv->dma; struct comedi_cmd *cmd = &s->async->cmd; int ret; dt282x_disable_dma(dev); outw(devpriv->divisor, dev->iobase + DT2821_TMRCTR_REG); devpriv->supcsr = DT2821_SUPCSR_ERRINTEN; if (cmd->scan_begin_src == TRIG_FOLLOW) devpriv->supcsr = DT2821_SUPCSR_DS_AD_CLK; else devpriv->supcsr = DT2821_SUPCSR_DS_AD_TRIG; outw(devpriv->supcsr | DT2821_SUPCSR_CLRDMADNE | DT2821_SUPCSR_BUFFB | DT2821_SUPCSR_ADCINIT, dev->iobase + DT2821_SUPCSR_REG); devpriv->ntrig = cmd->stop_arg * cmd->scan_end_arg; devpriv->nread = devpriv->ntrig; devpriv->dma_dir = COMEDI_ISADMA_READ; dma->cur_dma = 0; dt282x_prep_ai_dma(dev, 0, 0); if (devpriv->ntrig) { dt282x_prep_ai_dma(dev, 1, 0); devpriv->supcsr |= DT2821_SUPCSR_DDMA; outw(devpriv->supcsr, dev->iobase + DT2821_SUPCSR_REG); } devpriv->adcsr = 0; dt282x_load_changain(dev, cmd->chanlist_len, cmd->chanlist); devpriv->adcsr = DT2821_ADCSR_ADCLK | DT2821_ADCSR_IADDONE; outw(devpriv->adcsr, dev->iobase + DT2821_ADCSR_REG); outw(devpriv->supcsr | DT2821_SUPCSR_PRLD, dev->iobase + DT2821_SUPCSR_REG); ret = comedi_timeout(dev, s, NULL, dt282x_ai_timeout, DT2821_ADCSR_MUXBUSY); if (ret) return ret; if (cmd->scan_begin_src == TRIG_FOLLOW) { outw(devpriv->supcsr | DT2821_SUPCSR_STRIG, dev->iobase + DT2821_SUPCSR_REG); } else { devpriv->supcsr |= DT2821_SUPCSR_XTRIG; outw(devpriv->supcsr, dev->iobase + DT2821_SUPCSR_REG); } return 0; } static int dt282x_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s) { struct dt282x_private *devpriv = dev->private; dt282x_disable_dma(dev); devpriv->adcsr = 0; outw(devpriv->adcsr, dev->iobase + DT2821_ADCSR_REG); devpriv->supcsr = 0; outw(devpriv->supcsr | DT2821_SUPCSR_ADCINIT, dev->iobase + DT2821_SUPCSR_REG); return 0; } static int dt282x_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { struct dt282x_private *devpriv = dev->private; unsigned int chan = CR_CHAN(insn->chanspec); unsigned int range = CR_RANGE(insn->chanspec); int i; devpriv->dacsr |= DT2821_DACSR_SSEL | DT2821_DACSR_YSEL(chan); for (i = 0; i < insn->n; i++) { unsigned int val = data[i]; s->readback[chan] = val; if (comedi_range_is_bipolar(s, range)) val = comedi_offset_munge(s, val); outw(devpriv->dacsr, dev->iobase + DT2821_DACSR_REG); outw(val, dev->iobase + DT2821_DADAT_REG); outw(devpriv->supcsr | DT2821_SUPCSR_DACON, dev->iobase + DT2821_SUPCSR_REG); } return insn->n; } static int dt282x_ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_cmd *cmd) { struct dt282x_private *devpriv = dev->private; int err = 0; unsigned int arg; /* Step 1 : check if triggers are trivially valid */ err |= comedi_check_trigger_src(&cmd->start_src, TRIG_INT); err |= comedi_check_trigger_src(&cmd->scan_begin_src, TRIG_TIMER); err |= comedi_check_trigger_src(&cmd->convert_src, TRIG_NOW); err |= comedi_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT); err |= comedi_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE); if (err) return 1; /* Step 2a : make sure trigger sources are unique */ err |= comedi_check_trigger_is_unique(cmd->stop_src); /* Step 2b : and mutually compatible */ if (err) return 2; /* Step 3: check if arguments are trivially valid */ err |= comedi_check_trigger_arg_is(&cmd->start_arg, 0); err |= comedi_check_trigger_arg_min(&cmd->scan_begin_arg, 5000); err |= comedi_check_trigger_arg_is(&cmd->convert_arg, 0); err |= comedi_check_trigger_arg_is(&cmd->scan_end_arg, cmd->chanlist_len); if (cmd->stop_src == TRIG_COUNT) err |= comedi_check_trigger_arg_min(&cmd->stop_arg, 1); else /* TRIG_EXT | TRIG_NONE */ err |= comedi_check_trigger_arg_is(&cmd->stop_arg, 0); if (err) return 3; /* step 4: fix up any arguments */ arg = cmd->scan_begin_arg; devpriv->divisor = dt282x_ns_to_timer(&arg, cmd->flags); err |= comedi_check_trigger_arg_is(&cmd->scan_begin_arg, arg); if (err) return 4; return 0; } static int dt282x_ao_inttrig(struct comedi_device *dev, struct comedi_subdevice *s, unsigned int trig_num) { struct dt282x_private *devpriv = dev->private; struct comedi_cmd *cmd = &s->async->cmd; if (trig_num != cmd->start_src) return -EINVAL; if (!dt282x_ao_setup_dma(dev, s, 0)) return -EPIPE; if (!dt282x_ao_setup_dma(dev, s, 1)) return -EPIPE; outw(devpriv->supcsr | DT2821_SUPCSR_STRIG, dev->iobase + DT2821_SUPCSR_REG); s->async->inttrig = NULL; return 1; } static int dt282x_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s) { struct dt282x_private *devpriv = dev->private; struct comedi_isadma *dma = devpriv->dma; struct comedi_cmd *cmd = &s->async->cmd; dt282x_disable_dma(dev); devpriv->supcsr = DT2821_SUPCSR_ERRINTEN | DT2821_SUPCSR_DS_DA_CLK | DT2821_SUPCSR_DDMA; outw(devpriv->supcsr | DT2821_SUPCSR_CLRDMADNE | DT2821_SUPCSR_BUFFB | DT2821_SUPCSR_DACINIT, dev->iobase + DT2821_SUPCSR_REG); devpriv->ntrig = cmd->stop_arg * cmd->chanlist_len; devpriv->nread = devpriv->ntrig; devpriv->dma_dir = COMEDI_ISADMA_WRITE; dma->cur_dma = 0; outw(devpriv->divisor, dev->iobase + DT2821_TMRCTR_REG); /* clear all bits but the DIO direction bits */ devpriv->dacsr &= (DT2821_DACSR_LBOE | DT2821_DACSR_HBOE); devpriv->dacsr |= (DT2821_DACSR_SSEL | DT2821_DACSR_DACLK | DT2821_DACSR_IDARDY); outw(devpriv->dacsr, dev->iobase + DT2821_DACSR_REG); s->async->inttrig = dt282x_ao_inttrig; return 0; } static int dt282x_ao_cancel(struct comedi_device *dev, struct comedi_subdevice *s) { struct dt282x_private *devpriv = dev->private; dt282x_disable_dma(dev); /* clear all bits but the DIO direction bits */ devpriv->dacsr &= (DT2821_DACSR_LBOE | DT2821_DACSR_HBOE); outw(devpriv->dacsr, dev->iobase + DT2821_DACSR_REG); devpriv->supcsr = 0; outw(devpriv->supcsr | DT2821_SUPCSR_DACINIT, dev->iobase + DT2821_SUPCSR_REG); return 0; } static int dt282x_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { if (comedi_dio_update_state(s, data)) outw(s->state, dev->iobase + DT2821_DIODAT_REG); data[1] = inw(dev->iobase + DT2821_DIODAT_REG); return insn->n; } static int dt282x_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { struct dt282x_private *devpriv = dev->private; unsigned int chan = CR_CHAN(insn->chanspec); unsigned int mask; int ret; if (chan < 8) mask = 0x00ff; else mask = 0xff00; ret = comedi_dio_insn_config(dev, s, insn, data, mask); if (ret) return ret; devpriv->dacsr &= ~(DT2821_DACSR_LBOE | DT2821_DACSR_HBOE); if (s->io_bits & 0x00ff) devpriv->dacsr |= DT2821_DACSR_LBOE; if (s->io_bits & 0xff00) devpriv->dacsr |= DT2821_DACSR_HBOE; outw(devpriv->dacsr, dev->iobase + DT2821_DACSR_REG); return insn->n; } static const struct comedi_lrange *const ai_range_table[] = { &range_dt282x_ai_lo_bipolar, &range_dt282x_ai_lo_unipolar, &range_dt282x_ai_5_bipolar, &range_dt282x_ai_5_unipolar }; static const struct comedi_lrange *const ai_range_pgl_table[] = { &range_dt282x_ai_hi_bipolar, &range_dt282x_ai_hi_unipolar }; static const struct comedi_lrange *opt_ai_range_lkup(int ispgl, int x) { if (ispgl) { if (x < 0 || x >= 2) x = 0; return ai_range_pgl_table[x]; } if (x < 0 || x >= 4) x = 0; return ai_range_table[x]; } static void dt282x_alloc_dma(struct comedi_device *dev, struct comedi_devconfig *it) { struct dt282x_private *devpriv = dev->private; unsigned int irq_num = it->options[1]; unsigned int dma_chan[2]; if (it->options[2] < it->options[3]) { dma_chan[0] = it->options[2]; dma_chan[1] = it->options[3]; } else { dma_chan[0] = it->options[3]; dma_chan[1] = it->options[2]; } if (!irq_num || dma_chan[0] == dma_chan[1] || dma_chan[0] < 5 || dma_chan[0] > 7 || dma_chan[1] < 5 || dma_chan[1] > 7) return; if (request_irq(irq_num, dt282x_interrupt, 0, dev->board_name, dev)) return; /* DMA uses two 4K buffers with separate DMA channels */ devpriv->dma = comedi_isadma_alloc(dev, 2, dma_chan[0], dma_chan[1], PAGE_SIZE, 0); if (!devpriv->dma) free_irq(irq_num, dev); else dev->irq = irq_num; } static void dt282x_free_dma(struct comedi_device *dev) { struct dt282x_private *devpriv = dev->private; if (devpriv) comedi_isadma_free(devpriv->dma); } static int dt282x_initialize(struct comedi_device *dev) { /* Initialize board */ outw(DT2821_SUPCSR_BDINIT, dev->iobase + DT2821_SUPCSR_REG); inw(dev->iobase + DT2821_ADCSR_REG); /* * At power up, some registers are in a well-known state. * Check them to see if a DT2821 series board is present. */ if (((inw(dev->iobase + DT2821_ADCSR_REG) & 0xfff0) != 0x7c00) || ((inw(dev->iobase + DT2821_CHANCSR_REG) & 0xf0f0) != 0x70f0) || ((inw(dev->iobase + DT2821_DACSR_REG) & 0x7c93) != 0x7c90) || ((inw(dev->iobase + DT2821_SUPCSR_REG) & 0xf8ff) != 0x0000) || ((inw(dev->iobase + DT2821_TMRCTR_REG) & 0xff00) != 0xf000)) { dev_err(dev->class_dev, "board not found\n"); return -EIO; } return 0; } static int dt282x_attach(struct comedi_device *dev, struct comedi_devconfig *it) { const struct dt282x_board *board = dev->board_ptr; struct dt282x_private *devpriv; struct comedi_subdevice *s; int ret; ret = comedi_request_region(dev, it->options[0], 0x10); if (ret) return ret; ret = dt282x_initialize(dev); if (ret) return ret; devpriv = comedi_alloc_devpriv(dev, sizeof(*devpriv)); if (!devpriv) return -ENOMEM; /* an IRQ and 2 DMA channels are required for async command support */ dt282x_alloc_dma(dev, it); ret = comedi_alloc_subdevices(dev, 3); if (ret) return ret; /* Analog Input subdevice */ s = &dev->subdevices[0]; s->type = COMEDI_SUBD_AI; s->subdev_flags = SDF_READABLE; if ((it->options[4] && board->adchan_di) || board->adchan_se == 0) { s->subdev_flags |= SDF_DIFF; s->n_chan = board->adchan_di; } else { s->subdev_flags |= SDF_COMMON; s->n_chan = board->adchan_se; } s->maxdata = board->ai_maxdata; s->range_table = opt_ai_range_lkup(board->ispgl, it->options[8]); devpriv->ad_2scomp = it->options[5] ? 1 : 0; s->insn_read = dt282x_ai_insn_read; if (dev->irq) { dev->read_subdev = s; s->subdev_flags |= SDF_CMD_READ; s->len_chanlist = s->n_chan; s->do_cmdtest = dt282x_ai_cmdtest; s->do_cmd = dt282x_ai_cmd; s->cancel = dt282x_ai_cancel; } /* Analog Output subdevice */ s = &dev->subdevices[1]; if (board->dachan) { s->type = COMEDI_SUBD_AO; s->subdev_flags = SDF_WRITABLE; s->n_chan = board->dachan; s->maxdata = board->ao_maxdata; /* ranges are per-channel, set by jumpers on the board */ s->range_table = &dt282x_ao_range; s->insn_write = dt282x_ao_insn_write; if (dev->irq) { dev->write_subdev = s; s->subdev_flags |= SDF_CMD_WRITE; s->len_chanlist = s->n_chan; s->do_cmdtest = dt282x_ao_cmdtest; s->do_cmd = dt282x_ao_cmd; s->cancel = dt282x_ao_cancel; } ret = comedi_alloc_subdev_readback(s); if (ret) return ret; } else { s->type = COMEDI_SUBD_UNUSED; } /* Digital I/O subdevice */ s = &dev->subdevices[2]; s->type = COMEDI_SUBD_DIO; s->subdev_flags = SDF_READABLE | SDF_WRITABLE; s->n_chan = 16; s->maxdata = 1; s->range_table = &range_digital; s->insn_bits = dt282x_dio_insn_bits; s->insn_config = dt282x_dio_insn_config; return 0; } static void dt282x_detach(struct comedi_device *dev) { dt282x_free_dma(dev); comedi_legacy_detach(dev); } static struct comedi_driver dt282x_driver = { .driver_name = "dt282x", .module = THIS_MODULE, .attach = dt282x_attach, .detach = dt282x_detach, .board_name = &boardtypes[0].name, .num_names = ARRAY_SIZE(boardtypes), .offset = sizeof(struct dt282x_board), }; module_comedi_driver(dt282x_driver); MODULE_AUTHOR("Comedi http://www.comedi.org"); MODULE_DESCRIPTION("Comedi driver for Data Translation DT2821 series"); MODULE_LICENSE("GPL");
BPI-SINOVOIP/BPI-Mainline-kernel
linux-5.4/drivers/staging/comedi/drivers/dt282x.c
C
gpl-2.0
30,747
/* { dg-do link } */ /* { dg-options "-O2 -fdump-tree-vrp1" } */ #include "vrp.h" void test1(int i, int j) { RANGE(i, 1, 5); RANGE(j, 7, 10); CHECK_RANGE(i + j, 8, 15); } #define UINT_MAX 2*(unsigned)__INT_MAX__ + 1 void test2(unsigned int i) { RANGE(i, UINT_MAX - 0x4, UINT_MAX - 0x1); CHECK_ANTI_RANGE(i + 0x2, 0x1, UINT_MAX - 0x3); } void test3(unsigned int i) { RANGE(i, UINT_MAX - 0x4, UINT_MAX - 0x1); CHECK_RANGE(i + 0x5, 0x0, 0x3); } void test4(unsigned int i) { RANGE(i, 2, 4); CHECK_ANTI_RANGE(i - 4, 1, UINT_MAX - 2); } void test5(unsigned int i) { RANGE(i, 2, 4); CHECK_RANGE(i - 8, UINT_MAX - 5, UINT_MAX - 3); } int main() {} /* { dg-final { scan-tree-dump-times "link_error" 0 "vrp1" } } */ /* { dg-final { cleanup-tree-dump "vrp1" } } */
sudosurootdev/gcc
gcc/testsuite/gcc.dg/tree-ssa/vrp69.c
C
gpl-2.0
781
{-# LANGUAGE MagicHash #-} module Main where import GHC.Exts go :: () -> Int# go () = 0# main = print (lazy (I# (go $ ())))
urbanslug/ghc
testsuite/tests/typecheck/should_run/T8739.hs
Haskell
bsd-3-clause
128
/* * 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. * * Copyright (C) 2013 Imagination Technologies Ltd. * * Arbitrary Monitor Support (AMON) */ int amon_cpu_avail(int cpu); int amon_cpu_start(int cpu, unsigned long pc, unsigned long sp, unsigned long gp, unsigned long a0);
AiJiaZone/linux-4.0
virt/arch/mips/include/asm/amon.h
C
gpl-2.0
409
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Recent Blog Entries Block page. * * @package block_blog_recent * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * This block simply outputs a list of links to recent blog entries, depending on * the context of the current page. */ class block_blog_recent extends block_base { function init() { $this->title = get_string('pluginname', 'block_blog_recent'); $this->content_type = BLOCK_TYPE_TEXT; } function applicable_formats() { return array('all' => true, 'my' => false, 'tag' => false); } function instance_allow_config() { return true; } function get_content() { global $CFG; if ($this->content !== NULL) { return $this->content; } // verify blog is enabled if (empty($CFG->enableblogs)) { $this->content = new stdClass(); $this->content->text = ''; if ($this->page->user_is_editing()) { $this->content->text = get_string('blogdisable', 'blog'); } return $this->content; } else if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL and (!isloggedin() or isguestuser())) { $this->content = new stdClass(); $this->content->text = ''; return $this->content; } require_once($CFG->dirroot .'/blog/lib.php'); require_once($CFG->dirroot .'/blog/locallib.php'); if (empty($this->config)) { $this->config = new stdClass(); } if (empty($this->config->recentbloginterval)) { $this->config->recentbloginterval = 8400; } if (empty($this->config->numberofrecentblogentries)) { $this->config->numberofrecentblogentries = 4; } $this->content = new stdClass(); $this->content->footer = ''; $this->content->text = ''; $context = $this->page->context; $url = new moodle_url('/blog/index.php'); $filter = array(); if ($context->contextlevel == CONTEXT_MODULE) { $filter['module'] = $context->instanceid; $a = new stdClass; $a->type = get_string('modulename', $this->page->cm->modname); $strview = get_string('viewallmodentries', 'blog', $a); $url->param('modid', $context->instanceid); } else if ($context->contextlevel == CONTEXT_COURSE) { $filter['course'] = $context->instanceid; $a = new stdClass; $a->type = get_string('course'); $strview = get_string('viewblogentries', 'blog', $a); $url->param('courseid', $context->instanceid); } else { $strview = get_string('viewsiteentries', 'blog'); } $filter['since'] = $this->config->recentbloginterval; $bloglisting = new blog_listing($filter); $entries = $bloglisting->get_entries(0, $this->config->numberofrecentblogentries, 4); if (!empty($entries)) { $entrieslist = array(); $viewblogurl = new moodle_url('/blog/index.php'); foreach ($entries as $entryid => $entry) { $viewblogurl->param('entryid', $entryid); $entrylink = html_writer::link($viewblogurl, shorten_text($entry->subject)); $entrieslist[] = $entrylink; } $this->content->text .= html_writer::alist($entrieslist, array('class'=>'list')); $viewallentrieslink = html_writer::link($url, $strview); $this->content->text .= $viewallentrieslink; } else { $this->content->text .= get_string('norecentblogentries', 'block_blog_recent'); } } }
ernestovi/ups
moodle/blocks/blog_recent/block_blog_recent.php
PHP
gpl-3.0
4,493
/* { dg-do compile } */ /* { dg-options "-O2 -ffast-math -ftree-vectorize -mavx512f" } */ #include "avx512f-floor-sfix-vec-1.c" /* { dg-final { scan-assembler-times "vrndscalepd\[^\n\]*zmm\[0-9\](?:\n|\[ \\t\]+#)" 2 } } */ /* { dg-final { scan-assembler-times "vcvttpd2dq\[^\n\]*zmm\[0-9\].{7}(?:\n|\[ \\t\]+#)" 2 } } */
selmentdev/selment-toolchain
source/gcc-latest/gcc/testsuite/gcc.target/i386/avx512f-floor-sfix-vec-2.c
C
gpl-3.0
323
/* { dg-do run } */ /* { dg-options "-O2 -mavx512vl" } */ /* { dg-require-effective-target avx512vl } */ #define AVX512VL #define AVX512F_LEN 256 #define AVX512F_LEN_HALF 128 #include "avx512f-vpmovdb-2.c" #undef AVX512F_LEN #undef AVX512F_LEN_HALF #define AVX512F_LEN 128 #define AVX512F_LEN_HALF 128 #include "avx512f-vpmovdb-2.c"
selmentdev/selment-toolchain
source/gcc-latest/gcc/testsuite/gcc.target/i386/avx512vl-vpmovdb-2.c
C
gpl-3.0
336
<?php namespace PhpParser\Node\Expr; use PhpParser\Node\Expr; /** * @property Expr $expr Expression */ class Eval_ extends Expr { /** * Constructs an eval() node. * * @param Expr $expr Expression * @param array $attributes Additional attributes */ public function __construct(Expr $expr, array $attributes = array()) { parent::__construct( array( 'expr' => $expr ), $attributes ); } }
jaschweder/SD-Trabalho-Final
webservice/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Eval_.php
PHP
apache-2.0
501
class AddProjectFinancialsView < ActiveRecord::Migration def up execute " create or replace view project_financials as with catarse_fee_percentage as ( select c.value::numeric as total, (1 - c.value::numeric) as complement from configurations c where c.name = 'catarse_fee' ), catarse_base_url as ( select c.value from configurations c where c.name = 'base_url' ) select p.id as project_id, p.name as name, u.moip_login as moip, p.goal as goal, pt.pledged as reached, pt.total_payment_service_fee as moip_tax, cp.total * pt.pledged as catarse_fee, pt.pledged * cp.complement as repass_value, to_char(p.expires_at, 'dd/mm/yyyy') as expires_at, catarse_base_url.value||'/admin/reports/backer_reports.csv?project_id='||p.id as backer_report, p.state as state from projects p join users u on u.id = p.user_id join project_totals pt on pt.project_id = p.id cross join catarse_fee_percentage cp cross join catarse_base_url " end def down execute "drop view project_financials" end end
umeshduggal/flockaway
db/migrate/20131022154220_add_project_financials_view.rb
Ruby
mit
1,253
/* Copyright (c) 2010, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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. * */ #include "vidc_type.h" #include "vcd_power_sm.h" #include "vcd_core.h" #include "vcd.h" u32 vcd_power_event( struct vcd_dev_ctxt *dev_ctxt, struct vcd_clnt_ctxt *cctxt, u32 event) { u32 rc = VCD_S_SUCCESS; VCD_MSG_MED("Device power state = %d", dev_ctxt->pwr_clk_state); VCD_MSG_MED("event = 0x%x", event); switch (event) { case VCD_EVT_PWR_DEV_INIT_BEGIN: case VCD_EVT_PWR_DEV_INIT_END: case VCD_EVT_PWR_DEV_INIT_FAIL: case VCD_EVT_PWR_DEV_TERM_BEGIN: case VCD_EVT_PWR_DEV_TERM_END: case VCD_EVT_PWR_DEV_TERM_FAIL: case VCD_EVT_PWR_DEV_SLEEP_BEGIN: case VCD_EVT_PWR_DEV_SLEEP_END: case VCD_EVT_PWR_DEV_SET_PERFLVL: case VCD_EVT_PWR_DEV_HWTIMEOUT: { rc = vcd_device_power_event(dev_ctxt, event, cctxt); break; } case VCD_EVT_PWR_CLNT_CMD_BEGIN: case VCD_EVT_PWR_CLNT_CMD_END: case VCD_EVT_PWR_CLNT_CMD_FAIL: case VCD_EVT_PWR_CLNT_PAUSE: case VCD_EVT_PWR_CLNT_RESUME: case VCD_EVT_PWR_CLNT_FIRST_FRAME: case VCD_EVT_PWR_CLNT_LAST_FRAME: case VCD_EVT_PWR_CLNT_ERRFATAL: { rc = vcd_client_power_event(dev_ctxt, cctxt, event); break; } } if (VCD_FAILED(rc)) VCD_MSG_ERROR("vcd_power_event: event 0x%x failed", event); return rc; } u32 vcd_device_power_event(struct vcd_dev_ctxt *dev_ctxt, u32 event, struct vcd_clnt_ctxt *cctxt) { u32 rc = VCD_ERR_FAIL; u32 set_perf_lvl; switch (event) { case VCD_EVT_PWR_DEV_INIT_BEGIN: { if (dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_OFF) { if (res_trk_get_max_perf_level(&dev_ctxt-> max_perf_lvl)) { if (res_trk_power_up()) { dev_ctxt->pwr_clk_state = VCD_PWRCLK_STATE_ON_NOTCLOCKED; dev_ctxt->curr_perf_lvl = 0; dev_ctxt->reqd_perf_lvl = 0; dev_ctxt->active_clnts = 0; dev_ctxt-> set_perf_lvl_pending = false; rc = vcd_enable_clock(dev_ctxt, cctxt); if (VCD_FAILED(rc)) { (void)res_trk_power_down(); dev_ctxt->pwr_clk_state = VCD_PWRCLK_STATE_OFF; } } } } break; } case VCD_EVT_PWR_DEV_INIT_END: case VCD_EVT_PWR_DEV_TERM_FAIL: case VCD_EVT_PWR_DEV_SLEEP_BEGIN: case VCD_EVT_PWR_DEV_HWTIMEOUT: { rc = vcd_gate_clock(dev_ctxt); break; } case VCD_EVT_PWR_DEV_INIT_FAIL: case VCD_EVT_PWR_DEV_TERM_END: { if (dev_ctxt->pwr_clk_state != VCD_PWRCLK_STATE_OFF) { (void)vcd_disable_clock(dev_ctxt); (void)res_trk_power_down(); dev_ctxt->pwr_clk_state = VCD_PWRCLK_STATE_OFF; dev_ctxt->curr_perf_lvl = 0; dev_ctxt->reqd_perf_lvl = 0; dev_ctxt->active_clnts = 0; dev_ctxt->set_perf_lvl_pending = false; rc = VCD_S_SUCCESS; } break; } case VCD_EVT_PWR_DEV_TERM_BEGIN: case VCD_EVT_PWR_DEV_SLEEP_END: { rc = vcd_un_gate_clock(dev_ctxt); break; } case VCD_EVT_PWR_DEV_SET_PERFLVL: { set_perf_lvl = dev_ctxt->reqd_perf_lvl > 0 ? dev_ctxt-> reqd_perf_lvl : VCD_MIN_PERF_LEVEL; rc = vcd_set_perf_level(dev_ctxt, set_perf_lvl); break; } } return rc; } u32 vcd_client_power_event( struct vcd_dev_ctxt *dev_ctxt, struct vcd_clnt_ctxt *cctxt, u32 event) { u32 rc = VCD_ERR_FAIL; switch (event) { case VCD_EVT_PWR_CLNT_CMD_BEGIN: { rc = vcd_un_gate_clock(dev_ctxt); break; } case VCD_EVT_PWR_CLNT_CMD_END: { rc = vcd_gate_clock(dev_ctxt); break; } case VCD_EVT_PWR_CLNT_CMD_FAIL: { if (!vcd_core_is_busy(dev_ctxt)) rc = vcd_gate_clock(dev_ctxt); break; } case VCD_EVT_PWR_CLNT_PAUSE: case VCD_EVT_PWR_CLNT_LAST_FRAME: case VCD_EVT_PWR_CLNT_ERRFATAL: { if (cctxt) { rc = VCD_S_SUCCESS; if (cctxt->status.req_perf_lvl) { dev_ctxt->reqd_perf_lvl -= cctxt->reqd_perf_lvl; cctxt->status.req_perf_lvl = false; rc = vcd_set_perf_level(dev_ctxt, dev_ctxt->reqd_perf_lvl); } } break; } case VCD_EVT_PWR_CLNT_RESUME: case VCD_EVT_PWR_CLNT_FIRST_FRAME: { if (cctxt) { rc = VCD_S_SUCCESS; if (!cctxt->status.req_perf_lvl) { dev_ctxt->reqd_perf_lvl += cctxt->reqd_perf_lvl; cctxt->status.req_perf_lvl = true; rc = vcd_set_perf_level(dev_ctxt, dev_ctxt->reqd_perf_lvl); } } break; } } return rc; } u32 vcd_enable_clock(struct vcd_dev_ctxt *dev_ctxt, struct vcd_clnt_ctxt *cctxt) { u32 rc = VCD_S_SUCCESS; u32 set_perf_lvl; if (dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_OFF) { VCD_MSG_ERROR("vcd_enable_clock(): Already in state " "VCD_PWRCLK_STATE_OFF\n"); rc = VCD_ERR_FAIL; } else if (dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_ON_NOTCLOCKED) { set_perf_lvl = dev_ctxt->reqd_perf_lvl > 0 ? dev_ctxt-> reqd_perf_lvl : VCD_MIN_PERF_LEVEL; rc = vcd_set_perf_level(dev_ctxt, set_perf_lvl); if (!VCD_FAILED(rc)) { if (res_trk_enable_clocks()) { dev_ctxt->pwr_clk_state = VCD_PWRCLK_STATE_ON_CLOCKED; } } else { rc = VCD_ERR_FAIL; } } if (!VCD_FAILED(rc)) dev_ctxt->active_clnts++; return rc; } u32 vcd_disable_clock(struct vcd_dev_ctxt *dev_ctxt) { u32 rc = VCD_S_SUCCESS; if (dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_OFF) { VCD_MSG_ERROR("vcd_disable_clock(): Already in state " "VCD_PWRCLK_STATE_OFF\n"); rc = VCD_ERR_FAIL; } else if (dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_ON_CLOCKED || dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_ON_CLOCKGATED) { dev_ctxt->active_clnts--; if (!dev_ctxt->active_clnts) { if (!res_trk_disable_clocks()) rc = VCD_ERR_FAIL; dev_ctxt->pwr_clk_state = VCD_PWRCLK_STATE_ON_NOTCLOCKED; dev_ctxt->curr_perf_lvl = 0; } } return rc; } u32 vcd_set_perf_level(struct vcd_dev_ctxt *dev_ctxt, u32 perf_lvl) { u32 rc = VCD_S_SUCCESS; if (!vcd_core_is_busy(dev_ctxt)) { if (res_trk_set_perf_level(perf_lvl, &dev_ctxt->curr_perf_lvl, dev_ctxt)) { dev_ctxt->set_perf_lvl_pending = false; } else { rc = VCD_ERR_FAIL; dev_ctxt->set_perf_lvl_pending = true; } } else { dev_ctxt->set_perf_lvl_pending = true; } return rc; } u32 vcd_update_clnt_perf_lvl( struct vcd_clnt_ctxt *cctxt, struct vcd_property_frame_rate *fps, u32 frm_p_units) { u32 rc = VCD_S_SUCCESS; struct vcd_dev_ctxt *dev_ctxt = cctxt->dev_ctxt; u32 new_perf_lvl; new_perf_lvl = frm_p_units * fps->fps_numerator / fps->fps_denominator; if (cctxt->status.req_perf_lvl) { dev_ctxt->reqd_perf_lvl = dev_ctxt->reqd_perf_lvl - cctxt->reqd_perf_lvl + new_perf_lvl; rc = vcd_set_perf_level(cctxt->dev_ctxt, dev_ctxt->reqd_perf_lvl); } cctxt->reqd_perf_lvl = new_perf_lvl; return rc; } u32 vcd_gate_clock(struct vcd_dev_ctxt *dev_ctxt) { u32 rc = VCD_S_SUCCESS; if (dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_OFF || dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_ON_NOTCLOCKED) { VCD_MSG_ERROR("%s(): Clk is Off or Not Clked yet\n", __func__); return VCD_ERR_FAIL; } if (dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_ON_CLOCKGATED) return rc; #if ENA_CLK_GATE if (res_trk_disable_clocks()) dev_ctxt->pwr_clk_state = VCD_PWRCLK_STATE_ON_CLOCKGATED; else rc = VCD_ERR_FAIL; #endif return rc; } u32 vcd_un_gate_clock(struct vcd_dev_ctxt *dev_ctxt) { u32 rc = VCD_S_SUCCESS; #if ENA_CLK_GATE if (dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_OFF || dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_ON_NOTCLOCKED) { VCD_MSG_ERROR("%s(): Clk is Off or Not Clked yet\n", __func__); return VCD_ERR_FAIL; } if (dev_ctxt->pwr_clk_state == VCD_PWRCLK_STATE_ON_CLOCKED) return rc; if (res_trk_enable_clocks()) dev_ctxt->pwr_clk_state = VCD_PWRCLK_STATE_ON_CLOCKED; else rc = VCD_ERR_FAIL; #endif return rc; }
mantera/WX_435_Kernel-CM7
drivers/video/msm/vidc/common/vcd/vcd_power_sm.c
C
gpl-2.0
8,314
/* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/draw/Surface.scss:1 */ .x-surface { position: absolute; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/draw/Surface.scss:5 */ .x-surface-canvas { position: absolute; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/draw/Container.scss:1 */ .x-draw-container { position: relative; -webkit-user-select: none; -moz-user-select: none; user-select: none; cursor: default; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:1 */ .x-legend { background: #fff; outline: none; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:6 */ .x-legend-horizontal { overflow-x: auto; overflow-y: hidden; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:11 */ .x-legend-horizontal .x-legend-item { display: inline-block; border-right: 1px solid #ccc; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:18 */ .x-legend-horizontal .x-legend-item:first-child { border-left: 1px solid #ccc; border-bottom-left-radius: 3px; border-top-left-radius: 3px; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:24 */ .x-legend-horizontal .x-legend-item:last-child { border-bottom-right-radius: 3px; border-top-right-radius: 3px; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:30 */ .x-legend-horizontal.x-rtl .x-legend-item:first-child { border-right: 1px solid #ccc; border-bottom-right-radius: 3px; border-top-right-radius: 3px; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:35 */ .x-legend-horizontal.x-rtl .x-legend-item:last-child { border-right: none; border-bottom-left-radius: 3px; border-top-left-radius: 3px; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:43 */ .x-legend-vertical { overflow-x: hidden; overflow-y: auto; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:48 */ .x-legend-vertical .x-legend-item { border-left: 1px solid #ccc; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:53 */ .x-legend-vertical .x-legend-item:first-child { border-top: 1px solid #ccc; border-top-left-radius: 3px; border-top-right-radius: 3px; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:59 */ .x-legend-vertical .x-legend-item:last-child { border-bottom-left-radius: 3px; border-bottom-right-radius: 3px; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:66 */ .x-legend-item-inactive { -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)"; opacity: 0.3; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:70 */ .x-legend-item { padding: 0.8em 1em 0.8em 1.8em; color: #333; background: rgba(255, 255, 255, 0); max-width: 16em; min-width: 0; font-size: 13px; font-family: helvetica, arial, verdana, sans-serif; line-height: 13px; font-weight: 300; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; position: relative; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:86 */ .x-rtl > * > .x-legend-item { padding: 0.8em 1.8em 0.8em 1em; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:90 */ .x-legend-item-marker { position: absolute; width: 0.8em; height: 0.8em; -webkit-border-radius: 0.4em; -moz-border-radius: 0.4em; -ms-border-radius: 0.4em; -o-border-radius: 0.4em; border-radius: 0.4em; -webkit-box-shadow: rgba(255, 255, 255, 0.3) 0 1px 0, rgba(0, 0, 0, 0.4) 0 1px 0 inset; -moz-box-shadow: rgba(255, 255, 255, 0.3) 0 1px 0, rgba(0, 0, 0, 0.4) 0 1px 0 inset; box-shadow: rgba(255, 255, 255, 0.3) 0 1px 0, rgba(0, 0, 0, 0.4) 0 1px 0 inset; left: 0.7em; top: 0.85em; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/sass/src/chart/legend/Legend.scss:102 */ .x-rtl > * > * > .x-legend-item-marker { right: 0.7em; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/classic/sass/src/chart/legend/Legend.scss:1 */ .x-legend-inner { display: table; text-align: center; padding: 5px; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/classic/sass/src/chart/legend/Legend.scss:8 */ .x-legend-horizontal .x-legend-inner { min-width: 100%; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/classic/sass/src/chart/legend/Legend.scss:14 */ .x-legend-vertical .x-legend-inner { min-height: 100%; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/classic/sass/src/chart/legend/Legend.scss:19 */ .x-legend-container { display: table-cell; vertical-align: middle; white-space: nowrap; line-height: 0; background: #fff; -webkit-box-shadow: rgba(255, 255, 255, 0.6) 0 1px 1px; -moz-box-shadow: rgba(255, 255, 255, 0.6) 0 1px 1px; box-shadow: rgba(255, 255, 255, 0.6) 0 1px 1px; } /* /Users/space/buildAgent/work/8cc7421dd8da164c/staging/packages/charts/classic/sass/src/chart/AbstractChart.scss:1 */ .x-chart-image { width: 100%; height: auto; }
B3Partners/flamingo
viewer/src/main/webapp/extjs/packages/charts/crisp/resources/charts-all-rtl-debug.css
CSS
agpl-3.0
6,049
// Copyright 2015 The etcd Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package mvcc import ( "sort" "sync" "github.com/google/btree" "go.uber.org/zap" ) type index interface { Get(key []byte, atRev int64) (rev, created revision, ver int64, err error) Range(key, end []byte, atRev int64) ([][]byte, []revision) Revisions(key, end []byte, atRev int64) []revision Put(key []byte, rev revision) Tombstone(key []byte, rev revision) error RangeSince(key, end []byte, rev int64) []revision Compact(rev int64) map[revision]struct{} Keep(rev int64) map[revision]struct{} Equal(b index) bool Insert(ki *keyIndex) KeyIndex(ki *keyIndex) *keyIndex } type treeIndex struct { sync.RWMutex tree *btree.BTree lg *zap.Logger } func newTreeIndex(lg *zap.Logger) index { return &treeIndex{ tree: btree.New(32), lg: lg, } } func (ti *treeIndex) Put(key []byte, rev revision) { keyi := &keyIndex{key: key} ti.Lock() defer ti.Unlock() item := ti.tree.Get(keyi) if item == nil { keyi.put(ti.lg, rev.main, rev.sub) ti.tree.ReplaceOrInsert(keyi) return } okeyi := item.(*keyIndex) okeyi.put(ti.lg, rev.main, rev.sub) } func (ti *treeIndex) Get(key []byte, atRev int64) (modified, created revision, ver int64, err error) { keyi := &keyIndex{key: key} ti.RLock() defer ti.RUnlock() if keyi = ti.keyIndex(keyi); keyi == nil { return revision{}, revision{}, 0, ErrRevisionNotFound } return keyi.get(ti.lg, atRev) } func (ti *treeIndex) KeyIndex(keyi *keyIndex) *keyIndex { ti.RLock() defer ti.RUnlock() return ti.keyIndex(keyi) } func (ti *treeIndex) keyIndex(keyi *keyIndex) *keyIndex { if item := ti.tree.Get(keyi); item != nil { return item.(*keyIndex) } return nil } func (ti *treeIndex) visit(key, end []byte, f func(ki *keyIndex)) { keyi, endi := &keyIndex{key: key}, &keyIndex{key: end} ti.RLock() defer ti.RUnlock() ti.tree.AscendGreaterOrEqual(keyi, func(item btree.Item) bool { if len(endi.key) > 0 && !item.Less(endi) { return false } f(item.(*keyIndex)) return true }) } func (ti *treeIndex) Revisions(key, end []byte, atRev int64) (revs []revision) { if end == nil { rev, _, _, err := ti.Get(key, atRev) if err != nil { return nil } return []revision{rev} } ti.visit(key, end, func(ki *keyIndex) { if rev, _, _, err := ki.get(ti.lg, atRev); err == nil { revs = append(revs, rev) } }) return revs } func (ti *treeIndex) Range(key, end []byte, atRev int64) (keys [][]byte, revs []revision) { if end == nil { rev, _, _, err := ti.Get(key, atRev) if err != nil { return nil, nil } return [][]byte{key}, []revision{rev} } ti.visit(key, end, func(ki *keyIndex) { if rev, _, _, err := ki.get(ti.lg, atRev); err == nil { revs = append(revs, rev) keys = append(keys, ki.key) } }) return keys, revs } func (ti *treeIndex) Tombstone(key []byte, rev revision) error { keyi := &keyIndex{key: key} ti.Lock() defer ti.Unlock() item := ti.tree.Get(keyi) if item == nil { return ErrRevisionNotFound } ki := item.(*keyIndex) return ki.tombstone(ti.lg, rev.main, rev.sub) } // RangeSince returns all revisions from key(including) to end(excluding) // at or after the given rev. The returned slice is sorted in the order // of revision. func (ti *treeIndex) RangeSince(key, end []byte, rev int64) []revision { keyi := &keyIndex{key: key} ti.RLock() defer ti.RUnlock() if end == nil { item := ti.tree.Get(keyi) if item == nil { return nil } keyi = item.(*keyIndex) return keyi.since(ti.lg, rev) } endi := &keyIndex{key: end} var revs []revision ti.tree.AscendGreaterOrEqual(keyi, func(item btree.Item) bool { if len(endi.key) > 0 && !item.Less(endi) { return false } curKeyi := item.(*keyIndex) revs = append(revs, curKeyi.since(ti.lg, rev)...) return true }) sort.Sort(revisions(revs)) return revs } func (ti *treeIndex) Compact(rev int64) map[revision]struct{} { available := make(map[revision]struct{}) if ti.lg != nil { ti.lg.Info("compact tree index", zap.Int64("revision", rev)) } else { plog.Printf("store.index: compact %d", rev) } ti.Lock() clone := ti.tree.Clone() ti.Unlock() clone.Ascend(func(item btree.Item) bool { keyi := item.(*keyIndex) //Lock is needed here to prevent modification to the keyIndex while //compaction is going on or revision added to empty before deletion ti.Lock() keyi.compact(ti.lg, rev, available) if keyi.isEmpty() { item := ti.tree.Delete(keyi) if item == nil { if ti.lg != nil { ti.lg.Panic("failed to delete during compaction") } else { plog.Panic("store.index: unexpected delete failure during compaction") } } } ti.Unlock() return true }) return available } // Keep finds all revisions to be kept for a Compaction at the given rev. func (ti *treeIndex) Keep(rev int64) map[revision]struct{} { available := make(map[revision]struct{}) ti.RLock() defer ti.RUnlock() ti.tree.Ascend(func(i btree.Item) bool { keyi := i.(*keyIndex) keyi.keep(rev, available) return true }) return available } func (ti *treeIndex) Equal(bi index) bool { b := bi.(*treeIndex) if ti.tree.Len() != b.tree.Len() { return false } equal := true ti.tree.Ascend(func(item btree.Item) bool { aki := item.(*keyIndex) bki := b.tree.Get(item).(*keyIndex) if !aki.equal(bki) { equal = false return false } return true }) return equal } func (ti *treeIndex) Insert(ki *keyIndex) { ti.Lock() defer ti.Unlock() ti.tree.ReplaceOrInsert(ki) }
fgimenez/kubernetes
vendor/go.etcd.io/etcd/mvcc/index.go
GO
apache-2.0
6,038
/* SPDX-License-Identifier: GPL-2.0 */ /* * zonefs filesystem driver tracepoints. * * Copyright (C) 2021 Western Digital Corporation or its affiliates. */ #undef TRACE_SYSTEM #define TRACE_SYSTEM zonefs #if !defined(_TRACE_ZONEFS_H) || defined(TRACE_HEADER_MULTI_READ) #define _TRACE_ZONEFS_H #include <linux/tracepoint.h> #include <linux/trace_seq.h> #include <linux/blkdev.h> #include "zonefs.h" #define show_dev(dev) MAJOR(dev), MINOR(dev) TRACE_EVENT(zonefs_zone_mgmt, TP_PROTO(struct inode *inode, enum req_opf op), TP_ARGS(inode, op), TP_STRUCT__entry( __field(dev_t, dev) __field(ino_t, ino) __field(int, op) __field(sector_t, sector) __field(sector_t, nr_sectors) ), TP_fast_assign( __entry->dev = inode->i_sb->s_dev; __entry->ino = inode->i_ino; __entry->op = op; __entry->sector = ZONEFS_I(inode)->i_zsector; __entry->nr_sectors = ZONEFS_I(inode)->i_zone_size >> SECTOR_SHIFT; ), TP_printk("bdev=(%d,%d), ino=%lu op=%s, sector=%llu, nr_sectors=%llu", show_dev(__entry->dev), (unsigned long)__entry->ino, blk_op_str(__entry->op), __entry->sector, __entry->nr_sectors ) ); TRACE_EVENT(zonefs_file_dio_append, TP_PROTO(struct inode *inode, ssize_t size, ssize_t ret), TP_ARGS(inode, size, ret), TP_STRUCT__entry( __field(dev_t, dev) __field(ino_t, ino) __field(sector_t, sector) __field(ssize_t, size) __field(loff_t, wpoffset) __field(ssize_t, ret) ), TP_fast_assign( __entry->dev = inode->i_sb->s_dev; __entry->ino = inode->i_ino; __entry->sector = ZONEFS_I(inode)->i_zsector; __entry->size = size; __entry->wpoffset = ZONEFS_I(inode)->i_wpoffset; __entry->ret = ret; ), TP_printk("bdev=(%d, %d), ino=%lu, sector=%llu, size=%zu, wpoffset=%llu, ret=%zu", show_dev(__entry->dev), (unsigned long)__entry->ino, __entry->sector, __entry->size, __entry->wpoffset, __entry->ret ) ); TRACE_EVENT(zonefs_iomap_begin, TP_PROTO(struct inode *inode, struct iomap *iomap), TP_ARGS(inode, iomap), TP_STRUCT__entry( __field(dev_t, dev) __field(ino_t, ino) __field(u64, addr) __field(loff_t, offset) __field(u64, length) ), TP_fast_assign( __entry->dev = inode->i_sb->s_dev; __entry->ino = inode->i_ino; __entry->addr = iomap->addr; __entry->offset = iomap->offset; __entry->length = iomap->length; ), TP_printk("bdev=(%d,%d), ino=%lu, addr=%llu, offset=%llu, length=%llu", show_dev(__entry->dev), (unsigned long)__entry->ino, __entry->addr, __entry->offset, __entry->length ) ); #endif /* _TRACE_ZONEFS_H */ #undef TRACE_INCLUDE_PATH #define TRACE_INCLUDE_PATH . #undef TRACE_INCLUDE_FILE #define TRACE_INCLUDE_FILE trace /* This part must be outside protection */ #include <trace/define_trace.h>
rperier/linux
fs/zonefs/trace.h
C
gpl-2.0
3,021
/* * Copyright (c) 2003, 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. */ @A(x=1, y=2) class B { }
rokn/Count_Words_2015
testing/openjdk2/langtools/test/tools/javac/annotations/default/B.java
Java
mit
1,077
/* * Unix SMB/CIFS implementation. * NetUserDel query * Copyright (C) Guenther Deschner 2008 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <sys/types.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netapi.h> #include "common.h" int main(int argc, const char **argv) { NET_API_STATUS status; struct libnetapi_ctx *ctx = NULL; const char *hostname = NULL; const char *username = NULL; poptContext pc; int opt; struct poptOption long_options[] = { POPT_AUTOHELP POPT_COMMON_LIBNETAPI_EXAMPLES POPT_TABLEEND }; status = libnetapi_init(&ctx); if (status != 0) { return status; } pc = poptGetContext("user_del", argc, argv, long_options, 0); poptSetOtherOptionHelp(pc, "hostname username"); while((opt = poptGetNextOpt(pc)) != -1) { } if (!poptPeekArg(pc)) { poptPrintHelp(pc, stderr, 0); goto out; } hostname = poptGetArg(pc); if (!poptPeekArg(pc)) { poptPrintHelp(pc, stderr, 0); goto out; } username = poptGetArg(pc); /* NetUserDel */ status = NetUserDel(hostname, username); if (status != 0) { printf("NetUserDel failed with: %s\n", libnetapi_get_error_string(ctx, status)); } out: libnetapi_free(ctx); poptFreeContext(pc); return status; }
zarboz/XBMC-PVR-mac
tools/darwin/depends/samba/samba-3.6.6/source3/lib/netapi/examples/user/user_del.c
C
gpl-2.0
1,881
#!/bin/bash # SPDX-License-Identifier: GPL-2.0 lib_dir=$(dirname $0)/../../../net/forwarding ALL_TESTS=" ipv4_route_addition_test ipv4_route_deletion_test ipv4_route_replacement_test ipv4_route_offload_failed_test ipv6_route_addition_test ipv6_route_deletion_test ipv6_route_replacement_test ipv6_route_offload_failed_test " NETDEVSIM_PATH=/sys/bus/netdevsim/ DEV_ADDR=1337 DEV=netdevsim${DEV_ADDR} DEVLINK_DEV=netdevsim/${DEV} SYSFS_NET_DIR=/sys/bus/netdevsim/devices/$DEV/net/ DEBUGFS_DIR=/sys/kernel/debug/netdevsim/$DEV/ NUM_NETIFS=0 source $lib_dir/lib.sh check_rt_offload_failed() { local outfile=$1; shift local line # Make sure that the first notification was emitted without # RTM_F_OFFLOAD_FAILED flag and the second with RTM_F_OFFLOAD_FAILED # flag head -n 1 $outfile | grep -q "rt_offload_failed" if [[ $? -eq 0 ]]; then return 1 fi head -n 2 $outfile | tail -n 1 | grep -q "rt_offload_failed" } check_rt_trap() { local outfile=$1; shift local line # Make sure that the first notification was emitted without RTM_F_TRAP # flag and the second with RTM_F_TRAP flag head -n 1 $outfile | grep -q "rt_trap" if [[ $? -eq 0 ]]; then return 1 fi head -n 2 $outfile | tail -n 1 | grep -q "rt_trap" } route_notify_check() { local outfile=$1; shift local expected_num_lines=$1; shift local offload_failed=${1:-0}; shift # check the monitor results lines=`wc -l $outfile | cut "-d " -f1` test $lines -eq $expected_num_lines check_err $? "$expected_num_lines notifications were expected but $lines were received" if [[ $expected_num_lines -eq 1 ]]; then return fi if [[ $offload_failed -eq 0 ]]; then check_rt_trap $outfile check_err $? "Wrong RTM_F_TRAP flags in notifications" else check_rt_offload_failed $outfile check_err $? "Wrong RTM_F_OFFLOAD_FAILED flags in notifications" fi } route_addition_check() { local ip=$1; shift local notify=$1; shift local route=$1; shift local expected_num_notifications=$1; shift local offload_failed=${1:-0}; shift ip netns exec testns1 sysctl -qw net.$ip.fib_notify_on_flag_change=$notify local outfile=$(mktemp) $IP monitor route &> $outfile & sleep 1 $IP route add $route dev dummy1 sleep 1 kill %% && wait %% &> /dev/null route_notify_check $outfile $expected_num_notifications $offload_failed rm -f $outfile $IP route del $route dev dummy1 } ipv4_route_addition_test() { RET=0 local ip="ipv4" local route=192.0.2.0/24 # Make sure a single notification will be emitted for the programmed # route. local notify=0 local expected_num_notifications=1 # route_addition_check will assign value to RET. route_addition_check $ip $notify $route $expected_num_notifications # Make sure two notifications will be emitted for the programmed route. notify=1 expected_num_notifications=2 route_addition_check $ip $notify $route $expected_num_notifications # notify=2 means emit notifications only for failed route installation, # make sure a single notification will be emitted for the programmed # route. notify=2 expected_num_notifications=1 route_addition_check $ip $notify $route $expected_num_notifications log_test "IPv4 route addition" } route_deletion_check() { local ip=$1; shift local notify=$1; shift local route=$1; shift local expected_num_notifications=$1; shift ip netns exec testns1 sysctl -qw net.$ip.fib_notify_on_flag_change=$notify $IP route add $route dev dummy1 sleep 1 local outfile=$(mktemp) $IP monitor route &> $outfile & sleep 1 $IP route del $route dev dummy1 sleep 1 kill %% && wait %% &> /dev/null route_notify_check $outfile $expected_num_notifications rm -f $outfile } ipv4_route_deletion_test() { RET=0 local ip="ipv4" local route=192.0.2.0/24 local expected_num_notifications=1 # Make sure a single notification will be emitted for the deleted route, # regardless of fib_notify_on_flag_change value. local notify=0 # route_deletion_check will assign value to RET. route_deletion_check $ip $notify $route $expected_num_notifications notify=1 route_deletion_check $ip $notify $route $expected_num_notifications log_test "IPv4 route deletion" } route_replacement_check() { local ip=$1; shift local notify=$1; shift local route=$1; shift local expected_num_notifications=$1; shift ip netns exec testns1 sysctl -qw net.$ip.fib_notify_on_flag_change=$notify $IP route add $route dev dummy1 sleep 1 local outfile=$(mktemp) $IP monitor route &> $outfile & sleep 1 $IP route replace $route dev dummy2 sleep 1 kill %% && wait %% &> /dev/null route_notify_check $outfile $expected_num_notifications rm -f $outfile $IP route del $route dev dummy2 } ipv4_route_replacement_test() { RET=0 local ip="ipv4" local route=192.0.2.0/24 $IP link add name dummy2 type dummy $IP link set dev dummy2 up # Make sure a single notification will be emitted for the new route. local notify=0 local expected_num_notifications=1 # route_replacement_check will assign value to RET. route_replacement_check $ip $notify $route $expected_num_notifications # Make sure two notifications will be emitted for the new route. notify=1 expected_num_notifications=2 route_replacement_check $ip $notify $route $expected_num_notifications # notify=2 means emit notifications only for failed route installation, # make sure a single notification will be emitted for the new route. notify=2 expected_num_notifications=1 route_replacement_check $ip $notify $route $expected_num_notifications $IP link del name dummy2 log_test "IPv4 route replacement" } ipv4_route_offload_failed_test() { RET=0 local ip="ipv4" local route=192.0.2.0/24 local offload_failed=1 echo "y"> $DEBUGFS_DIR/fib/fail_route_offload check_err $? "Failed to setup route offload to fail" # Make sure a single notification will be emitted for the programmed # route. local notify=0 local expected_num_notifications=1 route_addition_check $ip $notify $route $expected_num_notifications \ $offload_failed # Make sure two notifications will be emitted for the new route. notify=1 expected_num_notifications=2 route_addition_check $ip $notify $route $expected_num_notifications \ $offload_failed # notify=2 means emit notifications only for failed route installation, # make sure two notifications will be emitted for the new route. notify=2 expected_num_notifications=2 route_addition_check $ip $notify $route $expected_num_notifications \ $offload_failed echo "n"> $DEBUGFS_DIR/fib/fail_route_offload check_err $? "Failed to setup route offload not to fail" log_test "IPv4 route offload failed" } ipv6_route_addition_test() { RET=0 local ip="ipv6" local route=2001:db8:1::/64 # Make sure a single notification will be emitted for the programmed # route. local notify=0 local expected_num_notifications=1 route_addition_check $ip $notify $route $expected_num_notifications # Make sure two notifications will be emitted for the programmed route. notify=1 expected_num_notifications=2 route_addition_check $ip $notify $route $expected_num_notifications # notify=2 means emit notifications only for failed route installation, # make sure a single notification will be emitted for the programmed # route. notify=2 expected_num_notifications=1 route_addition_check $ip $notify $route $expected_num_notifications log_test "IPv6 route addition" } ipv6_route_deletion_test() { RET=0 local ip="ipv6" local route=2001:db8:1::/64 local expected_num_notifications=1 # Make sure a single notification will be emitted for the deleted route, # regardless of fib_notify_on_flag_change value. local notify=0 route_deletion_check $ip $notify $route $expected_num_notifications notify=1 route_deletion_check $ip $notify $route $expected_num_notifications log_test "IPv6 route deletion" } ipv6_route_replacement_test() { RET=0 local ip="ipv6" local route=2001:db8:1::/64 $IP link add name dummy2 type dummy $IP link set dev dummy2 up # Make sure a single notification will be emitted for the new route. local notify=0 local expected_num_notifications=1 route_replacement_check $ip $notify $route $expected_num_notifications # Make sure two notifications will be emitted for the new route. notify=1 expected_num_notifications=2 route_replacement_check $ip $notify $route $expected_num_notifications # notify=2 means emit notifications only for failed route installation, # make sure a single notification will be emitted for the new route. notify=2 expected_num_notifications=1 route_replacement_check $ip $notify $route $expected_num_notifications $IP link del name dummy2 log_test "IPv6 route replacement" } ipv6_route_offload_failed_test() { RET=0 local ip="ipv6" local route=2001:db8:1::/64 local offload_failed=1 echo "y"> $DEBUGFS_DIR/fib/fail_route_offload check_err $? "Failed to setup route offload to fail" # Make sure a single notification will be emitted for the programmed # route. local notify=0 local expected_num_notifications=1 route_addition_check $ip $notify $route $expected_num_notifications \ $offload_failed # Make sure two notifications will be emitted for the new route. notify=1 expected_num_notifications=2 route_addition_check $ip $notify $route $expected_num_notifications \ $offload_failed # notify=2 means emit notifications only for failed route installation, # make sure two notifications will be emitted for the new route. notify=2 expected_num_notifications=2 route_addition_check $ip $notify $route $expected_num_notifications \ $offload_failed echo "n"> $DEBUGFS_DIR/fib/fail_route_offload check_err $? "Failed to setup route offload not to fail" log_test "IPv6 route offload failed" } setup_prepare() { modprobe netdevsim &> /dev/null echo "$DEV_ADDR 1" > ${NETDEVSIM_PATH}/new_device while [ ! -d $SYSFS_NET_DIR ] ; do :; done ip netns add testns1 if [ $? -ne 0 ]; then echo "Failed to add netns \"testns1\"" exit 1 fi devlink dev reload $DEVLINK_DEV netns testns1 if [ $? -ne 0 ]; then echo "Failed to reload into netns \"testns1\"" exit 1 fi IP="ip -n testns1" $IP link add name dummy1 type dummy $IP link set dev dummy1 up } cleanup() { pre_cleanup $IP link del name dummy1 ip netns del testns1 echo "$DEV_ADDR" > ${NETDEVSIM_PATH}/del_device modprobe -r netdevsim &> /dev/null } trap cleanup EXIT setup_prepare tests_run exit $EXIT_STATUS
Linutronix/linux
tools/testing/selftests/drivers/net/netdevsim/fib_notifications.sh
Shell
gpl-2.0
10,424
#ifndef RAPIDXML_UTILS_HPP_INCLUDED #define RAPIDXML_UTILS_HPP_INCLUDED // Copyright (C) 2006, 2009 Marcin Kalicinski // Version 1.13 // Revision $DateTime: 2009/05/13 01:46:17 $ //! \file rapidxml_utils.hpp This file contains high-level rapidxml utilities that can be useful //! in certain simple scenarios. They should probably not be used if maximizing performance is the main objective. #include "rapidxml.hpp" #include <vector> #include <string> #include <fstream> #include <stdexcept> namespace rapidxml { //! Represents data loaded from a file template<class Ch = char> class file { public: //! Loads file into the memory. Data will be automatically destroyed by the destructor. //! \param filename Filename to load. file(const char *filename) { using namespace std; // Open stream basic_ifstream<Ch> stream(filename, ios::binary); if (!stream) throw runtime_error(string("cannot open file ") + filename); stream.unsetf(ios::skipws); // Determine stream size stream.seekg(0, ios::end); size_t size = stream.tellg(); stream.seekg(0); // Load data and add terminating 0 m_data.resize(size + 1); stream.read(&m_data.front(), static_cast<streamsize>(size)); m_data[size] = 0; } //! Loads file into the memory. Data will be automatically destroyed by the destructor //! \param stream Stream to load from file(std::basic_istream<Ch> &stream) { using namespace std; // Load data and add terminating 0 stream.unsetf(ios::skipws); m_data.assign(istreambuf_iterator<Ch>(stream), istreambuf_iterator<Ch>()); if (stream.fail() || stream.bad()) throw runtime_error("error reading stream"); m_data.push_back(0); } //! Gets file data. //! \return Pointer to data of file. Ch *data() { return &m_data.front(); } //! Gets file data. //! \return Pointer to data of file. const Ch *data() const { return &m_data.front(); } //! Gets file data size. //! \return Size of file data, in characters. std::size_t size() const { return m_data.size(); } private: std::vector<Ch> m_data; // File data }; //! Counts children of node. Time complexity is O(n). //! \return Number of children of node template<class Ch> inline std::size_t count_children(xml_node<Ch> *node) { xml_node<Ch> *child = node->first_node(); std::size_t count = 0; while (child) { ++count; child = child->next_sibling(); } return count; } //! Counts attributes of node. Time complexity is O(n). //! \return Number of attributes of node template<class Ch> inline std::size_t count_attributes(xml_node<Ch> *node) { xml_attribute<Ch> *attr = node->first_attribute(); std::size_t count = 0; while (attr) { ++count; attr = attr->next_attribute(); } return count; } } #endif
AndyPeterman/mrmc
xbmc/contrib/rapidxml/rapidxml_utils.hpp
C++
gpl-2.0
3,417
/* * Copyright 2012 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ #include "drmP.h" #include "radeon.h" #include "nid.h" #include "r600_dpm.h" #include "ni_dpm.h" #include "atom.h" #include <linux/math64.h> #include <linux/seq_file.h> #define MC_CG_ARB_FREQ_F0 0x0a #define MC_CG_ARB_FREQ_F1 0x0b #define MC_CG_ARB_FREQ_F2 0x0c #define MC_CG_ARB_FREQ_F3 0x0d #define SMC_RAM_END 0xC000 static const struct ni_cac_weights cac_weights_cayman_xt = { 0x15, 0x2, 0x19, 0x2, 0x8, 0x14, 0x2, 0x16, 0xE, 0x17, 0x13, 0x2B, 0x10, 0x7, 0x5, 0x5, 0x5, 0x2, 0x3, 0x9, 0x10, 0x10, 0x2B, 0xA, 0x9, 0x4, 0xD, 0xD, 0x3E, 0x18, 0x14, 0, 0x3, 0x3, 0x5, 0, 0x2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x1CC, 0, 0x164, 1, 1, 1, 1, 12, 12, 12, 0x12, 0x1F, 132, 5, 7, 0, { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0 }, true }; static const struct ni_cac_weights cac_weights_cayman_pro = { 0x16, 0x4, 0x10, 0x2, 0xA, 0x16, 0x2, 0x18, 0x10, 0x1A, 0x16, 0x2D, 0x12, 0xA, 0x6, 0x6, 0x6, 0x2, 0x4, 0xB, 0x11, 0x11, 0x2D, 0xC, 0xC, 0x7, 0x10, 0x10, 0x3F, 0x1A, 0x16, 0, 0x7, 0x4, 0x6, 1, 0x2, 0x1, 0, 0, 0, 0, 0, 0, 0x30, 0, 0x1CF, 0, 0x166, 1, 1, 1, 1, 12, 12, 12, 0x15, 0x1F, 132, 6, 6, 0, { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0 }, true }; static const struct ni_cac_weights cac_weights_cayman_le = { 0x7, 0xE, 0x1, 0xA, 0x1, 0x3F, 0x2, 0x18, 0x10, 0x1A, 0x1, 0x3F, 0x1, 0xE, 0x6, 0x6, 0x6, 0x2, 0x4, 0x9, 0x1A, 0x1A, 0x2C, 0xA, 0x11, 0x8, 0x19, 0x19, 0x1, 0x1, 0x1A, 0, 0x8, 0x5, 0x8, 0x1, 0x3, 0x1, 0, 0, 0, 0, 0, 0, 0x38, 0x38, 0x239, 0x3, 0x18A, 1, 1, 1, 1, 12, 12, 12, 0x15, 0x22, 132, 6, 6, 0, { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0 }, true }; #define NISLANDS_MGCG_SEQUENCE 300 static const u32 cayman_cgcg_cgls_default[] = { 0x000008f8, 0x00000010, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000011, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000012, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000013, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000014, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000015, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000016, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000017, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000018, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000019, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x0000001a, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x0000001b, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000020, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000021, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000022, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000023, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000024, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000025, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000026, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000027, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000028, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000029, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x0000002a, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x0000002b, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff }; #define CAYMAN_CGCG_CGLS_DEFAULT_LENGTH sizeof(cayman_cgcg_cgls_default) / (3 * sizeof(u32)) static const u32 cayman_cgcg_cgls_disable[] = { 0x000008f8, 0x00000010, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000011, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000012, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000013, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000014, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000015, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000016, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000017, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000018, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000019, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x0000001a, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x0000001b, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000020, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000021, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000022, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000023, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000024, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000025, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000026, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000027, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000028, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000029, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x0000002a, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x0000002b, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x00000644, 0x000f7902, 0x001f4180, 0x00000644, 0x000f3802, 0x001f4180 }; #define CAYMAN_CGCG_CGLS_DISABLE_LENGTH sizeof(cayman_cgcg_cgls_disable) / (3 * sizeof(u32)) static const u32 cayman_cgcg_cgls_enable[] = { 0x00000644, 0x000f7882, 0x001f4080, 0x000008f8, 0x00000010, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000011, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000012, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000013, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000014, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000015, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000016, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000017, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000018, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000019, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x0000001a, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x0000001b, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000020, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000021, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000022, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000023, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000024, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000025, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000026, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000027, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000028, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000029, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x0000002a, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x0000002b, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff }; #define CAYMAN_CGCG_CGLS_ENABLE_LENGTH sizeof(cayman_cgcg_cgls_enable) / (3 * sizeof(u32)) static const u32 cayman_mgcg_default[] = { 0x0000802c, 0xc0000000, 0xffffffff, 0x00003fc4, 0xc0000000, 0xffffffff, 0x00005448, 0x00000100, 0xffffffff, 0x000055e4, 0x00000100, 0xffffffff, 0x0000160c, 0x00000100, 0xffffffff, 0x00008984, 0x06000100, 0xffffffff, 0x0000c164, 0x00000100, 0xffffffff, 0x00008a18, 0x00000100, 0xffffffff, 0x0000897c, 0x06000100, 0xffffffff, 0x00008b28, 0x00000100, 0xffffffff, 0x00009144, 0x00800200, 0xffffffff, 0x00009a60, 0x00000100, 0xffffffff, 0x00009868, 0x00000100, 0xffffffff, 0x00008d58, 0x00000100, 0xffffffff, 0x00009510, 0x00000100, 0xffffffff, 0x0000949c, 0x00000100, 0xffffffff, 0x00009654, 0x00000100, 0xffffffff, 0x00009030, 0x00000100, 0xffffffff, 0x00009034, 0x00000100, 0xffffffff, 0x00009038, 0x00000100, 0xffffffff, 0x0000903c, 0x00000100, 0xffffffff, 0x00009040, 0x00000100, 0xffffffff, 0x0000a200, 0x00000100, 0xffffffff, 0x0000a204, 0x00000100, 0xffffffff, 0x0000a208, 0x00000100, 0xffffffff, 0x0000a20c, 0x00000100, 0xffffffff, 0x00009744, 0x00000100, 0xffffffff, 0x00003f80, 0x00000100, 0xffffffff, 0x0000a210, 0x00000100, 0xffffffff, 0x0000a214, 0x00000100, 0xffffffff, 0x000004d8, 0x00000100, 0xffffffff, 0x00009664, 0x00000100, 0xffffffff, 0x00009698, 0x00000100, 0xffffffff, 0x000004d4, 0x00000200, 0xffffffff, 0x000004d0, 0x00000000, 0xffffffff, 0x000030cc, 0x00000104, 0xffffffff, 0x0000d0c0, 0x00000100, 0xffffffff, 0x0000d8c0, 0x00000100, 0xffffffff, 0x0000802c, 0x40000000, 0xffffffff, 0x00003fc4, 0x40000000, 0xffffffff, 0x0000915c, 0x00010000, 0xffffffff, 0x00009160, 0x00030002, 0xffffffff, 0x00009164, 0x00050004, 0xffffffff, 0x00009168, 0x00070006, 0xffffffff, 0x00009178, 0x00070000, 0xffffffff, 0x0000917c, 0x00030002, 0xffffffff, 0x00009180, 0x00050004, 0xffffffff, 0x0000918c, 0x00010006, 0xffffffff, 0x00009190, 0x00090008, 0xffffffff, 0x00009194, 0x00070000, 0xffffffff, 0x00009198, 0x00030002, 0xffffffff, 0x0000919c, 0x00050004, 0xffffffff, 0x000091a8, 0x00010006, 0xffffffff, 0x000091ac, 0x00090008, 0xffffffff, 0x000091b0, 0x00070000, 0xffffffff, 0x000091b4, 0x00030002, 0xffffffff, 0x000091b8, 0x00050004, 0xffffffff, 0x000091c4, 0x00010006, 0xffffffff, 0x000091c8, 0x00090008, 0xffffffff, 0x000091cc, 0x00070000, 0xffffffff, 0x000091d0, 0x00030002, 0xffffffff, 0x000091d4, 0x00050004, 0xffffffff, 0x000091e0, 0x00010006, 0xffffffff, 0x000091e4, 0x00090008, 0xffffffff, 0x000091e8, 0x00000000, 0xffffffff, 0x000091ec, 0x00070000, 0xffffffff, 0x000091f0, 0x00030002, 0xffffffff, 0x000091f4, 0x00050004, 0xffffffff, 0x00009200, 0x00010006, 0xffffffff, 0x00009204, 0x00090008, 0xffffffff, 0x00009208, 0x00070000, 0xffffffff, 0x0000920c, 0x00030002, 0xffffffff, 0x00009210, 0x00050004, 0xffffffff, 0x0000921c, 0x00010006, 0xffffffff, 0x00009220, 0x00090008, 0xffffffff, 0x00009224, 0x00070000, 0xffffffff, 0x00009228, 0x00030002, 0xffffffff, 0x0000922c, 0x00050004, 0xffffffff, 0x00009238, 0x00010006, 0xffffffff, 0x0000923c, 0x00090008, 0xffffffff, 0x00009240, 0x00070000, 0xffffffff, 0x00009244, 0x00030002, 0xffffffff, 0x00009248, 0x00050004, 0xffffffff, 0x00009254, 0x00010006, 0xffffffff, 0x00009258, 0x00090008, 0xffffffff, 0x0000925c, 0x00070000, 0xffffffff, 0x00009260, 0x00030002, 0xffffffff, 0x00009264, 0x00050004, 0xffffffff, 0x00009270, 0x00010006, 0xffffffff, 0x00009274, 0x00090008, 0xffffffff, 0x00009278, 0x00070000, 0xffffffff, 0x0000927c, 0x00030002, 0xffffffff, 0x00009280, 0x00050004, 0xffffffff, 0x0000928c, 0x00010006, 0xffffffff, 0x00009290, 0x00090008, 0xffffffff, 0x000092a8, 0x00070000, 0xffffffff, 0x000092ac, 0x00030002, 0xffffffff, 0x000092b0, 0x00050004, 0xffffffff, 0x000092bc, 0x00010006, 0xffffffff, 0x000092c0, 0x00090008, 0xffffffff, 0x000092c4, 0x00070000, 0xffffffff, 0x000092c8, 0x00030002, 0xffffffff, 0x000092cc, 0x00050004, 0xffffffff, 0x000092d8, 0x00010006, 0xffffffff, 0x000092dc, 0x00090008, 0xffffffff, 0x00009294, 0x00000000, 0xffffffff, 0x0000802c, 0x40010000, 0xffffffff, 0x00003fc4, 0x40010000, 0xffffffff, 0x0000915c, 0x00010000, 0xffffffff, 0x00009160, 0x00030002, 0xffffffff, 0x00009164, 0x00050004, 0xffffffff, 0x00009168, 0x00070006, 0xffffffff, 0x00009178, 0x00070000, 0xffffffff, 0x0000917c, 0x00030002, 0xffffffff, 0x00009180, 0x00050004, 0xffffffff, 0x0000918c, 0x00010006, 0xffffffff, 0x00009190, 0x00090008, 0xffffffff, 0x00009194, 0x00070000, 0xffffffff, 0x00009198, 0x00030002, 0xffffffff, 0x0000919c, 0x00050004, 0xffffffff, 0x000091a8, 0x00010006, 0xffffffff, 0x000091ac, 0x00090008, 0xffffffff, 0x000091b0, 0x00070000, 0xffffffff, 0x000091b4, 0x00030002, 0xffffffff, 0x000091b8, 0x00050004, 0xffffffff, 0x000091c4, 0x00010006, 0xffffffff, 0x000091c8, 0x00090008, 0xffffffff, 0x000091cc, 0x00070000, 0xffffffff, 0x000091d0, 0x00030002, 0xffffffff, 0x000091d4, 0x00050004, 0xffffffff, 0x000091e0, 0x00010006, 0xffffffff, 0x000091e4, 0x00090008, 0xffffffff, 0x000091e8, 0x00000000, 0xffffffff, 0x000091ec, 0x00070000, 0xffffffff, 0x000091f0, 0x00030002, 0xffffffff, 0x000091f4, 0x00050004, 0xffffffff, 0x00009200, 0x00010006, 0xffffffff, 0x00009204, 0x00090008, 0xffffffff, 0x00009208, 0x00070000, 0xffffffff, 0x0000920c, 0x00030002, 0xffffffff, 0x00009210, 0x00050004, 0xffffffff, 0x0000921c, 0x00010006, 0xffffffff, 0x00009220, 0x00090008, 0xffffffff, 0x00009224, 0x00070000, 0xffffffff, 0x00009228, 0x00030002, 0xffffffff, 0x0000922c, 0x00050004, 0xffffffff, 0x00009238, 0x00010006, 0xffffffff, 0x0000923c, 0x00090008, 0xffffffff, 0x00009240, 0x00070000, 0xffffffff, 0x00009244, 0x00030002, 0xffffffff, 0x00009248, 0x00050004, 0xffffffff, 0x00009254, 0x00010006, 0xffffffff, 0x00009258, 0x00090008, 0xffffffff, 0x0000925c, 0x00070000, 0xffffffff, 0x00009260, 0x00030002, 0xffffffff, 0x00009264, 0x00050004, 0xffffffff, 0x00009270, 0x00010006, 0xffffffff, 0x00009274, 0x00090008, 0xffffffff, 0x00009278, 0x00070000, 0xffffffff, 0x0000927c, 0x00030002, 0xffffffff, 0x00009280, 0x00050004, 0xffffffff, 0x0000928c, 0x00010006, 0xffffffff, 0x00009290, 0x00090008, 0xffffffff, 0x000092a8, 0x00070000, 0xffffffff, 0x000092ac, 0x00030002, 0xffffffff, 0x000092b0, 0x00050004, 0xffffffff, 0x000092bc, 0x00010006, 0xffffffff, 0x000092c0, 0x00090008, 0xffffffff, 0x000092c4, 0x00070000, 0xffffffff, 0x000092c8, 0x00030002, 0xffffffff, 0x000092cc, 0x00050004, 0xffffffff, 0x000092d8, 0x00010006, 0xffffffff, 0x000092dc, 0x00090008, 0xffffffff, 0x00009294, 0x00000000, 0xffffffff, 0x0000802c, 0xc0000000, 0xffffffff, 0x00003fc4, 0xc0000000, 0xffffffff, 0x000008f8, 0x00000010, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000011, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000012, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000013, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000014, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000015, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000016, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000017, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000018, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000019, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x0000001a, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x0000001b, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff }; #define CAYMAN_MGCG_DEFAULT_LENGTH sizeof(cayman_mgcg_default) / (3 * sizeof(u32)) static const u32 cayman_mgcg_disable[] = { 0x0000802c, 0xc0000000, 0xffffffff, 0x000008f8, 0x00000000, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000001, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000002, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x000008f8, 0x00000003, 0xffffffff, 0x000008fc, 0xffffffff, 0xffffffff, 0x00009150, 0x00600000, 0xffffffff }; #define CAYMAN_MGCG_DISABLE_LENGTH sizeof(cayman_mgcg_disable) / (3 * sizeof(u32)) static const u32 cayman_mgcg_enable[] = { 0x0000802c, 0xc0000000, 0xffffffff, 0x000008f8, 0x00000000, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000001, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x000008f8, 0x00000002, 0xffffffff, 0x000008fc, 0x00600000, 0xffffffff, 0x000008f8, 0x00000003, 0xffffffff, 0x000008fc, 0x00000000, 0xffffffff, 0x00009150, 0x96944200, 0xffffffff }; #define CAYMAN_MGCG_ENABLE_LENGTH sizeof(cayman_mgcg_enable) / (3 * sizeof(u32)) #define NISLANDS_SYSLS_SEQUENCE 100 static const u32 cayman_sysls_default[] = { /* Register, Value, Mask bits */ 0x000055e8, 0x00000000, 0xffffffff, 0x0000d0bc, 0x00000000, 0xffffffff, 0x0000d8bc, 0x00000000, 0xffffffff, 0x000015c0, 0x000c1401, 0xffffffff, 0x0000264c, 0x000c0400, 0xffffffff, 0x00002648, 0x000c0400, 0xffffffff, 0x00002650, 0x000c0400, 0xffffffff, 0x000020b8, 0x000c0400, 0xffffffff, 0x000020bc, 0x000c0400, 0xffffffff, 0x000020c0, 0x000c0c80, 0xffffffff, 0x0000f4a0, 0x000000c0, 0xffffffff, 0x0000f4a4, 0x00680fff, 0xffffffff, 0x00002f50, 0x00000404, 0xffffffff, 0x000004c8, 0x00000001, 0xffffffff, 0x000064ec, 0x00000000, 0xffffffff, 0x00000c7c, 0x00000000, 0xffffffff, 0x00008dfc, 0x00000000, 0xffffffff }; #define CAYMAN_SYSLS_DEFAULT_LENGTH sizeof(cayman_sysls_default) / (3 * sizeof(u32)) static const u32 cayman_sysls_disable[] = { /* Register, Value, Mask bits */ 0x0000d0c0, 0x00000000, 0xffffffff, 0x0000d8c0, 0x00000000, 0xffffffff, 0x000055e8, 0x00000000, 0xffffffff, 0x0000d0bc, 0x00000000, 0xffffffff, 0x0000d8bc, 0x00000000, 0xffffffff, 0x000015c0, 0x00041401, 0xffffffff, 0x0000264c, 0x00040400, 0xffffffff, 0x00002648, 0x00040400, 0xffffffff, 0x00002650, 0x00040400, 0xffffffff, 0x000020b8, 0x00040400, 0xffffffff, 0x000020bc, 0x00040400, 0xffffffff, 0x000020c0, 0x00040c80, 0xffffffff, 0x0000f4a0, 0x000000c0, 0xffffffff, 0x0000f4a4, 0x00680000, 0xffffffff, 0x00002f50, 0x00000404, 0xffffffff, 0x000004c8, 0x00000001, 0xffffffff, 0x000064ec, 0x00007ffd, 0xffffffff, 0x00000c7c, 0x0000ff00, 0xffffffff, 0x00008dfc, 0x0000007f, 0xffffffff }; #define CAYMAN_SYSLS_DISABLE_LENGTH sizeof(cayman_sysls_disable) / (3 * sizeof(u32)) static const u32 cayman_sysls_enable[] = { /* Register, Value, Mask bits */ 0x000055e8, 0x00000001, 0xffffffff, 0x0000d0bc, 0x00000100, 0xffffffff, 0x0000d8bc, 0x00000100, 0xffffffff, 0x000015c0, 0x000c1401, 0xffffffff, 0x0000264c, 0x000c0400, 0xffffffff, 0x00002648, 0x000c0400, 0xffffffff, 0x00002650, 0x000c0400, 0xffffffff, 0x000020b8, 0x000c0400, 0xffffffff, 0x000020bc, 0x000c0400, 0xffffffff, 0x000020c0, 0x000c0c80, 0xffffffff, 0x0000f4a0, 0x000000c0, 0xffffffff, 0x0000f4a4, 0x00680fff, 0xffffffff, 0x00002f50, 0x00000903, 0xffffffff, 0x000004c8, 0x00000000, 0xffffffff, 0x000064ec, 0x00000000, 0xffffffff, 0x00000c7c, 0x00000000, 0xffffffff, 0x00008dfc, 0x00000000, 0xffffffff }; #define CAYMAN_SYSLS_ENABLE_LENGTH sizeof(cayman_sysls_enable) / (3 * sizeof(u32)) struct rv7xx_power_info *rv770_get_pi(struct radeon_device *rdev); struct evergreen_power_info *evergreen_get_pi(struct radeon_device *rdev); extern int ni_mc_load_microcode(struct radeon_device *rdev); struct ni_power_info *ni_get_pi(struct radeon_device *rdev) { struct ni_power_info *pi = rdev->pm.dpm.priv; return pi; } struct ni_ps *ni_get_ps(struct radeon_ps *rps) { struct ni_ps *ps = rps->ps_priv; return ps; } static void ni_calculate_leakage_for_v_and_t_formula(const struct ni_leakage_coeffients *coeff, u16 v, s32 t, u32 ileakage, u32 *leakage) { s64 kt, kv, leakage_w, i_leakage, vddc, temperature; i_leakage = div64_s64(drm_int2fixp(ileakage), 1000); vddc = div64_s64(drm_int2fixp(v), 1000); temperature = div64_s64(drm_int2fixp(t), 1000); kt = drm_fixp_mul(div64_s64(drm_int2fixp(coeff->at), 1000), drm_fixp_exp(drm_fixp_mul(div64_s64(drm_int2fixp(coeff->bt), 1000), temperature))); kv = drm_fixp_mul(div64_s64(drm_int2fixp(coeff->av), 1000), drm_fixp_exp(drm_fixp_mul(div64_s64(drm_int2fixp(coeff->bv), 1000), vddc))); leakage_w = drm_fixp_mul(drm_fixp_mul(drm_fixp_mul(i_leakage, kt), kv), vddc); *leakage = drm_fixp2int(leakage_w * 1000); } static void ni_calculate_leakage_for_v_and_t(struct radeon_device *rdev, const struct ni_leakage_coeffients *coeff, u16 v, s32 t, u32 i_leakage, u32 *leakage) { ni_calculate_leakage_for_v_and_t_formula(coeff, v, t, i_leakage, leakage); } bool ni_dpm_vblank_too_short(struct radeon_device *rdev) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); u32 vblank_time = r600_dpm_get_vblank_time(rdev); /* we never hit the non-gddr5 limit so disable it */ u32 switch_limit = pi->mem_gddr5 ? 450 : 0; if (vblank_time < switch_limit) return true; else return false; } static void ni_apply_state_adjust_rules(struct radeon_device *rdev, struct radeon_ps *rps) { struct ni_ps *ps = ni_get_ps(rps); struct radeon_clock_and_voltage_limits *max_limits; bool disable_mclk_switching; u32 mclk; u16 vddci; u32 max_sclk_vddc, max_mclk_vddci, max_mclk_vddc; int i; if ((rdev->pm.dpm.new_active_crtc_count > 1) || ni_dpm_vblank_too_short(rdev)) disable_mclk_switching = true; else disable_mclk_switching = false; if (rdev->pm.dpm.ac_power) max_limits = &rdev->pm.dpm.dyn_state.max_clock_voltage_on_ac; else max_limits = &rdev->pm.dpm.dyn_state.max_clock_voltage_on_dc; if (rdev->pm.dpm.ac_power == false) { for (i = 0; i < ps->performance_level_count; i++) { if (ps->performance_levels[i].mclk > max_limits->mclk) ps->performance_levels[i].mclk = max_limits->mclk; if (ps->performance_levels[i].sclk > max_limits->sclk) ps->performance_levels[i].sclk = max_limits->sclk; if (ps->performance_levels[i].vddc > max_limits->vddc) ps->performance_levels[i].vddc = max_limits->vddc; if (ps->performance_levels[i].vddci > max_limits->vddci) ps->performance_levels[i].vddci = max_limits->vddci; } } /* limit clocks to max supported clocks based on voltage dependency tables */ btc_get_max_clock_from_voltage_dependency_table(&rdev->pm.dpm.dyn_state.vddc_dependency_on_sclk, &max_sclk_vddc); btc_get_max_clock_from_voltage_dependency_table(&rdev->pm.dpm.dyn_state.vddci_dependency_on_mclk, &max_mclk_vddci); btc_get_max_clock_from_voltage_dependency_table(&rdev->pm.dpm.dyn_state.vddc_dependency_on_mclk, &max_mclk_vddc); for (i = 0; i < ps->performance_level_count; i++) { if (max_sclk_vddc) { if (ps->performance_levels[i].sclk > max_sclk_vddc) ps->performance_levels[i].sclk = max_sclk_vddc; } if (max_mclk_vddci) { if (ps->performance_levels[i].mclk > max_mclk_vddci) ps->performance_levels[i].mclk = max_mclk_vddci; } if (max_mclk_vddc) { if (ps->performance_levels[i].mclk > max_mclk_vddc) ps->performance_levels[i].mclk = max_mclk_vddc; } } /* XXX validate the min clocks required for display */ /* adjust low state */ if (disable_mclk_switching) { ps->performance_levels[0].mclk = ps->performance_levels[ps->performance_level_count - 1].mclk; ps->performance_levels[0].vddci = ps->performance_levels[ps->performance_level_count - 1].vddci; } btc_skip_blacklist_clocks(rdev, max_limits->sclk, max_limits->mclk, &ps->performance_levels[0].sclk, &ps->performance_levels[0].mclk); for (i = 1; i < ps->performance_level_count; i++) { if (ps->performance_levels[i].sclk < ps->performance_levels[i - 1].sclk) ps->performance_levels[i].sclk = ps->performance_levels[i - 1].sclk; if (ps->performance_levels[i].vddc < ps->performance_levels[i - 1].vddc) ps->performance_levels[i].vddc = ps->performance_levels[i - 1].vddc; } /* adjust remaining states */ if (disable_mclk_switching) { mclk = ps->performance_levels[0].mclk; vddci = ps->performance_levels[0].vddci; for (i = 1; i < ps->performance_level_count; i++) { if (mclk < ps->performance_levels[i].mclk) mclk = ps->performance_levels[i].mclk; if (vddci < ps->performance_levels[i].vddci) vddci = ps->performance_levels[i].vddci; } for (i = 0; i < ps->performance_level_count; i++) { ps->performance_levels[i].mclk = mclk; ps->performance_levels[i].vddci = vddci; } } else { for (i = 1; i < ps->performance_level_count; i++) { if (ps->performance_levels[i].mclk < ps->performance_levels[i - 1].mclk) ps->performance_levels[i].mclk = ps->performance_levels[i - 1].mclk; if (ps->performance_levels[i].vddci < ps->performance_levels[i - 1].vddci) ps->performance_levels[i].vddci = ps->performance_levels[i - 1].vddci; } } for (i = 1; i < ps->performance_level_count; i++) btc_skip_blacklist_clocks(rdev, max_limits->sclk, max_limits->mclk, &ps->performance_levels[i].sclk, &ps->performance_levels[i].mclk); for (i = 0; i < ps->performance_level_count; i++) btc_adjust_clock_combinations(rdev, max_limits, &ps->performance_levels[i]); for (i = 0; i < ps->performance_level_count; i++) { btc_apply_voltage_dependency_rules(&rdev->pm.dpm.dyn_state.vddc_dependency_on_sclk, ps->performance_levels[i].sclk, max_limits->vddc, &ps->performance_levels[i].vddc); btc_apply_voltage_dependency_rules(&rdev->pm.dpm.dyn_state.vddci_dependency_on_mclk, ps->performance_levels[i].mclk, max_limits->vddci, &ps->performance_levels[i].vddci); btc_apply_voltage_dependency_rules(&rdev->pm.dpm.dyn_state.vddc_dependency_on_mclk, ps->performance_levels[i].mclk, max_limits->vddc, &ps->performance_levels[i].vddc); btc_apply_voltage_dependency_rules(&rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk, rdev->clock.current_dispclk, max_limits->vddc, &ps->performance_levels[i].vddc); } for (i = 0; i < ps->performance_level_count; i++) { btc_apply_voltage_delta_rules(rdev, max_limits->vddc, max_limits->vddci, &ps->performance_levels[i].vddc, &ps->performance_levels[i].vddci); } ps->dc_compatible = true; for (i = 0; i < ps->performance_level_count; i++) { if (ps->performance_levels[i].vddc > rdev->pm.dpm.dyn_state.max_clock_voltage_on_dc.vddc) ps->dc_compatible = false; if (ps->performance_levels[i].vddc < rdev->pm.dpm.dyn_state.min_vddc_for_pcie_gen2) ps->performance_levels[i].flags &= ~ATOM_PPLIB_R600_FLAGS_PCIEGEN2; } } static void ni_cg_clockgating_default(struct radeon_device *rdev) { u32 count; const u32 *ps = NULL; ps = (const u32 *)&cayman_cgcg_cgls_default; count = CAYMAN_CGCG_CGLS_DEFAULT_LENGTH; btc_program_mgcg_hw_sequence(rdev, ps, count); } static void ni_gfx_clockgating_enable(struct radeon_device *rdev, bool enable) { u32 count; const u32 *ps = NULL; if (enable) { ps = (const u32 *)&cayman_cgcg_cgls_enable; count = CAYMAN_CGCG_CGLS_ENABLE_LENGTH; } else { ps = (const u32 *)&cayman_cgcg_cgls_disable; count = CAYMAN_CGCG_CGLS_DISABLE_LENGTH; } btc_program_mgcg_hw_sequence(rdev, ps, count); } static void ni_mg_clockgating_default(struct radeon_device *rdev) { u32 count; const u32 *ps = NULL; ps = (const u32 *)&cayman_mgcg_default; count = CAYMAN_MGCG_DEFAULT_LENGTH; btc_program_mgcg_hw_sequence(rdev, ps, count); } static void ni_mg_clockgating_enable(struct radeon_device *rdev, bool enable) { u32 count; const u32 *ps = NULL; if (enable) { ps = (const u32 *)&cayman_mgcg_enable; count = CAYMAN_MGCG_ENABLE_LENGTH; } else { ps = (const u32 *)&cayman_mgcg_disable; count = CAYMAN_MGCG_DISABLE_LENGTH; } btc_program_mgcg_hw_sequence(rdev, ps, count); } static void ni_ls_clockgating_default(struct radeon_device *rdev) { u32 count; const u32 *ps = NULL; ps = (const u32 *)&cayman_sysls_default; count = CAYMAN_SYSLS_DEFAULT_LENGTH; btc_program_mgcg_hw_sequence(rdev, ps, count); } static void ni_ls_clockgating_enable(struct radeon_device *rdev, bool enable) { u32 count; const u32 *ps = NULL; if (enable) { ps = (const u32 *)&cayman_sysls_enable; count = CAYMAN_SYSLS_ENABLE_LENGTH; } else { ps = (const u32 *)&cayman_sysls_disable; count = CAYMAN_SYSLS_DISABLE_LENGTH; } btc_program_mgcg_hw_sequence(rdev, ps, count); } static int ni_patch_single_dependency_table_based_on_leakage(struct radeon_device *rdev, struct radeon_clock_voltage_dependency_table *table) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); u32 i; if (table) { for (i = 0; i < table->count; i++) { if (0xff01 == table->entries[i].v) { if (pi->max_vddc == 0) return -EINVAL; table->entries[i].v = pi->max_vddc; } } } return 0; } static int ni_patch_dependency_tables_based_on_leakage(struct radeon_device *rdev) { int ret = 0; ret = ni_patch_single_dependency_table_based_on_leakage(rdev, &rdev->pm.dpm.dyn_state.vddc_dependency_on_sclk); ret = ni_patch_single_dependency_table_based_on_leakage(rdev, &rdev->pm.dpm.dyn_state.vddc_dependency_on_mclk); return ret; } static void ni_stop_dpm(struct radeon_device *rdev) { WREG32_P(GENERAL_PWRMGT, 0, ~GLOBAL_PWRMGT_EN); } #if 0 static int ni_notify_hw_of_power_source(struct radeon_device *rdev, bool ac_power) { if (ac_power) return (rv770_send_msg_to_smc(rdev, PPSMC_MSG_RunningOnAC) == PPSMC_Result_OK) ? 0 : -EINVAL; return 0; } #endif static PPSMC_Result ni_send_msg_to_smc_with_parameter(struct radeon_device *rdev, PPSMC_Msg msg, u32 parameter) { WREG32(SMC_SCRATCH0, parameter); return rv770_send_msg_to_smc(rdev, msg); } static int ni_restrict_performance_levels_before_switch(struct radeon_device *rdev) { if (rv770_send_msg_to_smc(rdev, PPSMC_MSG_NoForcedLevel) != PPSMC_Result_OK) return -EINVAL; return (ni_send_msg_to_smc_with_parameter(rdev, PPSMC_MSG_SetEnabledLevels, 1) == PPSMC_Result_OK) ? 0 : -EINVAL; } int ni_dpm_force_performance_level(struct radeon_device *rdev, enum radeon_dpm_forced_level level) { if (level == RADEON_DPM_FORCED_LEVEL_HIGH) { if (ni_send_msg_to_smc_with_parameter(rdev, PPSMC_MSG_SetEnabledLevels, 0) != PPSMC_Result_OK) return -EINVAL; if (ni_send_msg_to_smc_with_parameter(rdev, PPSMC_MSG_SetForcedLevels, 1) != PPSMC_Result_OK) return -EINVAL; } else if (level == RADEON_DPM_FORCED_LEVEL_LOW) { if (ni_send_msg_to_smc_with_parameter(rdev, PPSMC_MSG_SetForcedLevels, 0) != PPSMC_Result_OK) return -EINVAL; if (ni_send_msg_to_smc_with_parameter(rdev, PPSMC_MSG_SetEnabledLevels, 1) != PPSMC_Result_OK) return -EINVAL; } else if (level == RADEON_DPM_FORCED_LEVEL_AUTO) { if (ni_send_msg_to_smc_with_parameter(rdev, PPSMC_MSG_SetForcedLevels, 0) != PPSMC_Result_OK) return -EINVAL; if (ni_send_msg_to_smc_with_parameter(rdev, PPSMC_MSG_SetEnabledLevels, 0) != PPSMC_Result_OK) return -EINVAL; } rdev->pm.dpm.forced_level = level; return 0; } static void ni_stop_smc(struct radeon_device *rdev) { u32 tmp; int i; for (i = 0; i < rdev->usec_timeout; i++) { tmp = RREG32(LB_SYNC_RESET_SEL) & LB_SYNC_RESET_SEL_MASK; if (tmp != 1) break; udelay(1); } udelay(100); r7xx_stop_smc(rdev); } static int ni_process_firmware_header(struct radeon_device *rdev) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); u32 tmp; int ret; ret = rv770_read_smc_sram_dword(rdev, NISLANDS_SMC_FIRMWARE_HEADER_LOCATION + NISLANDS_SMC_FIRMWARE_HEADER_stateTable, &tmp, pi->sram_end); if (ret) return ret; pi->state_table_start = (u16)tmp; ret = rv770_read_smc_sram_dword(rdev, NISLANDS_SMC_FIRMWARE_HEADER_LOCATION + NISLANDS_SMC_FIRMWARE_HEADER_softRegisters, &tmp, pi->sram_end); if (ret) return ret; pi->soft_regs_start = (u16)tmp; ret = rv770_read_smc_sram_dword(rdev, NISLANDS_SMC_FIRMWARE_HEADER_LOCATION + NISLANDS_SMC_FIRMWARE_HEADER_mcRegisterTable, &tmp, pi->sram_end); if (ret) return ret; eg_pi->mc_reg_table_start = (u16)tmp; ret = rv770_read_smc_sram_dword(rdev, NISLANDS_SMC_FIRMWARE_HEADER_LOCATION + NISLANDS_SMC_FIRMWARE_HEADER_fanTable, &tmp, pi->sram_end); if (ret) return ret; ni_pi->fan_table_start = (u16)tmp; ret = rv770_read_smc_sram_dword(rdev, NISLANDS_SMC_FIRMWARE_HEADER_LOCATION + NISLANDS_SMC_FIRMWARE_HEADER_mcArbDramAutoRefreshTable, &tmp, pi->sram_end); if (ret) return ret; ni_pi->arb_table_start = (u16)tmp; ret = rv770_read_smc_sram_dword(rdev, NISLANDS_SMC_FIRMWARE_HEADER_LOCATION + NISLANDS_SMC_FIRMWARE_HEADER_cacTable, &tmp, pi->sram_end); if (ret) return ret; ni_pi->cac_table_start = (u16)tmp; ret = rv770_read_smc_sram_dword(rdev, NISLANDS_SMC_FIRMWARE_HEADER_LOCATION + NISLANDS_SMC_FIRMWARE_HEADER_spllTable, &tmp, pi->sram_end); if (ret) return ret; ni_pi->spll_table_start = (u16)tmp; return ret; } static void ni_read_clock_registers(struct radeon_device *rdev) { struct ni_power_info *ni_pi = ni_get_pi(rdev); ni_pi->clock_registers.cg_spll_func_cntl = RREG32(CG_SPLL_FUNC_CNTL); ni_pi->clock_registers.cg_spll_func_cntl_2 = RREG32(CG_SPLL_FUNC_CNTL_2); ni_pi->clock_registers.cg_spll_func_cntl_3 = RREG32(CG_SPLL_FUNC_CNTL_3); ni_pi->clock_registers.cg_spll_func_cntl_4 = RREG32(CG_SPLL_FUNC_CNTL_4); ni_pi->clock_registers.cg_spll_spread_spectrum = RREG32(CG_SPLL_SPREAD_SPECTRUM); ni_pi->clock_registers.cg_spll_spread_spectrum_2 = RREG32(CG_SPLL_SPREAD_SPECTRUM_2); ni_pi->clock_registers.mpll_ad_func_cntl = RREG32(MPLL_AD_FUNC_CNTL); ni_pi->clock_registers.mpll_ad_func_cntl_2 = RREG32(MPLL_AD_FUNC_CNTL_2); ni_pi->clock_registers.mpll_dq_func_cntl = RREG32(MPLL_DQ_FUNC_CNTL); ni_pi->clock_registers.mpll_dq_func_cntl_2 = RREG32(MPLL_DQ_FUNC_CNTL_2); ni_pi->clock_registers.mclk_pwrmgt_cntl = RREG32(MCLK_PWRMGT_CNTL); ni_pi->clock_registers.dll_cntl = RREG32(DLL_CNTL); ni_pi->clock_registers.mpll_ss1 = RREG32(MPLL_SS1); ni_pi->clock_registers.mpll_ss2 = RREG32(MPLL_SS2); } #if 0 static int ni_enter_ulp_state(struct radeon_device *rdev) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); if (pi->gfx_clock_gating) { WREG32_P(SCLK_PWRMGT_CNTL, 0, ~DYN_GFX_CLK_OFF_EN); WREG32_P(SCLK_PWRMGT_CNTL, GFX_CLK_FORCE_ON, ~GFX_CLK_FORCE_ON); WREG32_P(SCLK_PWRMGT_CNTL, 0, ~GFX_CLK_FORCE_ON); RREG32(GB_ADDR_CONFIG); } WREG32_P(SMC_MSG, HOST_SMC_MSG(PPSMC_MSG_SwitchToMinimumPower), ~HOST_SMC_MSG_MASK); udelay(25000); return 0; } #endif static void ni_program_response_times(struct radeon_device *rdev) { u32 voltage_response_time, backbias_response_time, acpi_delay_time, vbi_time_out; u32 vddc_dly, bb_dly, acpi_dly, vbi_dly, mclk_switch_limit; u32 reference_clock; rv770_write_smc_soft_register(rdev, NI_SMC_SOFT_REGISTER_mvdd_chg_time, 1); voltage_response_time = (u32)rdev->pm.dpm.voltage_response_time; backbias_response_time = (u32)rdev->pm.dpm.backbias_response_time; if (voltage_response_time == 0) voltage_response_time = 1000; if (backbias_response_time == 0) backbias_response_time = 1000; acpi_delay_time = 15000; vbi_time_out = 100000; reference_clock = radeon_get_xclk(rdev); vddc_dly = (voltage_response_time * reference_clock) / 1600; bb_dly = (backbias_response_time * reference_clock) / 1600; acpi_dly = (acpi_delay_time * reference_clock) / 1600; vbi_dly = (vbi_time_out * reference_clock) / 1600; mclk_switch_limit = (460 * reference_clock) / 100; rv770_write_smc_soft_register(rdev, NI_SMC_SOFT_REGISTER_delay_vreg, vddc_dly); rv770_write_smc_soft_register(rdev, NI_SMC_SOFT_REGISTER_delay_bbias, bb_dly); rv770_write_smc_soft_register(rdev, NI_SMC_SOFT_REGISTER_delay_acpi, acpi_dly); rv770_write_smc_soft_register(rdev, NI_SMC_SOFT_REGISTER_mclk_chg_timeout, vbi_dly); rv770_write_smc_soft_register(rdev, NI_SMC_SOFT_REGISTER_mc_block_delay, 0xAA); rv770_write_smc_soft_register(rdev, NI_SMC_SOFT_REGISTER_mclk_switch_lim, mclk_switch_limit); } static void ni_populate_smc_voltage_table(struct radeon_device *rdev, struct atom_voltage_table *voltage_table, NISLANDS_SMC_STATETABLE *table) { unsigned int i; for (i = 0; i < voltage_table->count; i++) { table->highSMIO[i] = 0; table->lowSMIO[i] |= cpu_to_be32(voltage_table->entries[i].smio_low); } } static void ni_populate_smc_voltage_tables(struct radeon_device *rdev, NISLANDS_SMC_STATETABLE *table) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); unsigned char i; if (eg_pi->vddc_voltage_table.count) { ni_populate_smc_voltage_table(rdev, &eg_pi->vddc_voltage_table, table); table->voltageMaskTable.highMask[NISLANDS_SMC_VOLTAGEMASK_VDDC] = 0; table->voltageMaskTable.lowMask[NISLANDS_SMC_VOLTAGEMASK_VDDC] = cpu_to_be32(eg_pi->vddc_voltage_table.mask_low); for (i = 0; i < eg_pi->vddc_voltage_table.count; i++) { if (pi->max_vddc_in_table <= eg_pi->vddc_voltage_table.entries[i].value) { table->maxVDDCIndexInPPTable = i; break; } } } if (eg_pi->vddci_voltage_table.count) { ni_populate_smc_voltage_table(rdev, &eg_pi->vddci_voltage_table, table); table->voltageMaskTable.highMask[NISLANDS_SMC_VOLTAGEMASK_VDDCI] = 0; table->voltageMaskTable.lowMask[NISLANDS_SMC_VOLTAGEMASK_VDDCI] = cpu_to_be32(eg_pi->vddc_voltage_table.mask_low); } } static int ni_populate_voltage_value(struct radeon_device *rdev, struct atom_voltage_table *table, u16 value, NISLANDS_SMC_VOLTAGE_VALUE *voltage) { unsigned int i; for (i = 0; i < table->count; i++) { if (value <= table->entries[i].value) { voltage->index = (u8)i; voltage->value = cpu_to_be16(table->entries[i].value); break; } } if (i >= table->count) return -EINVAL; return 0; } static void ni_populate_mvdd_value(struct radeon_device *rdev, u32 mclk, NISLANDS_SMC_VOLTAGE_VALUE *voltage) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); if (!pi->mvdd_control) { voltage->index = eg_pi->mvdd_high_index; voltage->value = cpu_to_be16(MVDD_HIGH_VALUE); return; } if (mclk <= pi->mvdd_split_frequency) { voltage->index = eg_pi->mvdd_low_index; voltage->value = cpu_to_be16(MVDD_LOW_VALUE); } else { voltage->index = eg_pi->mvdd_high_index; voltage->value = cpu_to_be16(MVDD_HIGH_VALUE); } } static int ni_get_std_voltage_value(struct radeon_device *rdev, NISLANDS_SMC_VOLTAGE_VALUE *voltage, u16 *std_voltage) { if (rdev->pm.dpm.dyn_state.cac_leakage_table.entries && ((u32)voltage->index < rdev->pm.dpm.dyn_state.cac_leakage_table.count)) *std_voltage = rdev->pm.dpm.dyn_state.cac_leakage_table.entries[voltage->index].vddc; else *std_voltage = be16_to_cpu(voltage->value); return 0; } static void ni_populate_std_voltage_value(struct radeon_device *rdev, u16 value, u8 index, NISLANDS_SMC_VOLTAGE_VALUE *voltage) { voltage->index = index; voltage->value = cpu_to_be16(value); } static u32 ni_get_smc_power_scaling_factor(struct radeon_device *rdev) { u32 xclk_period; u32 xclk = radeon_get_xclk(rdev); u32 tmp = RREG32(CG_CAC_CTRL) & TID_CNT_MASK; xclk_period = (1000000000UL / xclk); xclk_period /= 10000UL; return tmp * xclk_period; } static u32 ni_scale_power_for_smc(u32 power_in_watts, u32 scaling_factor) { return (power_in_watts * scaling_factor) << 2; } static u32 ni_calculate_power_boost_limit(struct radeon_device *rdev, struct radeon_ps *radeon_state, u32 near_tdp_limit) { struct ni_ps *state = ni_get_ps(radeon_state); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); u32 power_boost_limit = 0; int ret; if (ni_pi->enable_power_containment && ni_pi->use_power_boost_limit) { NISLANDS_SMC_VOLTAGE_VALUE vddc; u16 std_vddc_med; u16 std_vddc_high; u64 tmp, n, d; if (state->performance_level_count < 3) return 0; ret = ni_populate_voltage_value(rdev, &eg_pi->vddc_voltage_table, state->performance_levels[state->performance_level_count - 2].vddc, &vddc); if (ret) return 0; ret = ni_get_std_voltage_value(rdev, &vddc, &std_vddc_med); if (ret) return 0; ret = ni_populate_voltage_value(rdev, &eg_pi->vddc_voltage_table, state->performance_levels[state->performance_level_count - 1].vddc, &vddc); if (ret) return 0; ret = ni_get_std_voltage_value(rdev, &vddc, &std_vddc_high); if (ret) return 0; n = ((u64)near_tdp_limit * ((u64)std_vddc_med * (u64)std_vddc_med) * 90); d = ((u64)std_vddc_high * (u64)std_vddc_high * 100); tmp = div64_u64(n, d); if (tmp >> 32) return 0; power_boost_limit = (u32)tmp; } return power_boost_limit; } static int ni_calculate_adjusted_tdp_limits(struct radeon_device *rdev, bool adjust_polarity, u32 tdp_adjustment, u32 *tdp_limit, u32 *near_tdp_limit) { if (tdp_adjustment > (u32)rdev->pm.dpm.tdp_od_limit) return -EINVAL; if (adjust_polarity) { *tdp_limit = ((100 + tdp_adjustment) * rdev->pm.dpm.tdp_limit) / 100; *near_tdp_limit = rdev->pm.dpm.near_tdp_limit + (*tdp_limit - rdev->pm.dpm.tdp_limit); } else { *tdp_limit = ((100 - tdp_adjustment) * rdev->pm.dpm.tdp_limit) / 100; *near_tdp_limit = rdev->pm.dpm.near_tdp_limit - (rdev->pm.dpm.tdp_limit - *tdp_limit); } return 0; } static int ni_populate_smc_tdp_limits(struct radeon_device *rdev, struct radeon_ps *radeon_state) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); if (ni_pi->enable_power_containment) { NISLANDS_SMC_STATETABLE *smc_table = &ni_pi->smc_statetable; u32 scaling_factor = ni_get_smc_power_scaling_factor(rdev); u32 tdp_limit; u32 near_tdp_limit; u32 power_boost_limit; int ret; if (scaling_factor == 0) return -EINVAL; memset(smc_table, 0, sizeof(NISLANDS_SMC_STATETABLE)); ret = ni_calculate_adjusted_tdp_limits(rdev, false, /* ??? */ rdev->pm.dpm.tdp_adjustment, &tdp_limit, &near_tdp_limit); if (ret) return ret; power_boost_limit = ni_calculate_power_boost_limit(rdev, radeon_state, near_tdp_limit); smc_table->dpm2Params.TDPLimit = cpu_to_be32(ni_scale_power_for_smc(tdp_limit, scaling_factor)); smc_table->dpm2Params.NearTDPLimit = cpu_to_be32(ni_scale_power_for_smc(near_tdp_limit, scaling_factor)); smc_table->dpm2Params.SafePowerLimit = cpu_to_be32(ni_scale_power_for_smc((near_tdp_limit * NISLANDS_DPM2_TDP_SAFE_LIMIT_PERCENT) / 100, scaling_factor)); smc_table->dpm2Params.PowerBoostLimit = cpu_to_be32(ni_scale_power_for_smc(power_boost_limit, scaling_factor)); ret = rv770_copy_bytes_to_smc(rdev, (u16)(pi->state_table_start + offsetof(NISLANDS_SMC_STATETABLE, dpm2Params) + offsetof(PP_NIslands_DPM2Parameters, TDPLimit)), (u8 *)(&smc_table->dpm2Params.TDPLimit), sizeof(u32) * 4, pi->sram_end); if (ret) return ret; } return 0; } int ni_copy_and_switch_arb_sets(struct radeon_device *rdev, u32 arb_freq_src, u32 arb_freq_dest) { u32 mc_arb_dram_timing; u32 mc_arb_dram_timing2; u32 burst_time; u32 mc_cg_config; switch (arb_freq_src) { case MC_CG_ARB_FREQ_F0: mc_arb_dram_timing = RREG32(MC_ARB_DRAM_TIMING); mc_arb_dram_timing2 = RREG32(MC_ARB_DRAM_TIMING2); burst_time = (RREG32(MC_ARB_BURST_TIME) & STATE0_MASK) >> STATE0_SHIFT; break; case MC_CG_ARB_FREQ_F1: mc_arb_dram_timing = RREG32(MC_ARB_DRAM_TIMING_1); mc_arb_dram_timing2 = RREG32(MC_ARB_DRAM_TIMING2_1); burst_time = (RREG32(MC_ARB_BURST_TIME) & STATE1_MASK) >> STATE1_SHIFT; break; case MC_CG_ARB_FREQ_F2: mc_arb_dram_timing = RREG32(MC_ARB_DRAM_TIMING_2); mc_arb_dram_timing2 = RREG32(MC_ARB_DRAM_TIMING2_2); burst_time = (RREG32(MC_ARB_BURST_TIME) & STATE2_MASK) >> STATE2_SHIFT; break; case MC_CG_ARB_FREQ_F3: mc_arb_dram_timing = RREG32(MC_ARB_DRAM_TIMING_3); mc_arb_dram_timing2 = RREG32(MC_ARB_DRAM_TIMING2_3); burst_time = (RREG32(MC_ARB_BURST_TIME) & STATE3_MASK) >> STATE3_SHIFT; break; default: return -EINVAL; } switch (arb_freq_dest) { case MC_CG_ARB_FREQ_F0: WREG32(MC_ARB_DRAM_TIMING, mc_arb_dram_timing); WREG32(MC_ARB_DRAM_TIMING2, mc_arb_dram_timing2); WREG32_P(MC_ARB_BURST_TIME, STATE0(burst_time), ~STATE0_MASK); break; case MC_CG_ARB_FREQ_F1: WREG32(MC_ARB_DRAM_TIMING_1, mc_arb_dram_timing); WREG32(MC_ARB_DRAM_TIMING2_1, mc_arb_dram_timing2); WREG32_P(MC_ARB_BURST_TIME, STATE1(burst_time), ~STATE1_MASK); break; case MC_CG_ARB_FREQ_F2: WREG32(MC_ARB_DRAM_TIMING_2, mc_arb_dram_timing); WREG32(MC_ARB_DRAM_TIMING2_2, mc_arb_dram_timing2); WREG32_P(MC_ARB_BURST_TIME, STATE2(burst_time), ~STATE2_MASK); break; case MC_CG_ARB_FREQ_F3: WREG32(MC_ARB_DRAM_TIMING_3, mc_arb_dram_timing); WREG32(MC_ARB_DRAM_TIMING2_3, mc_arb_dram_timing2); WREG32_P(MC_ARB_BURST_TIME, STATE3(burst_time), ~STATE3_MASK); break; default: return -EINVAL; } mc_cg_config = RREG32(MC_CG_CONFIG) | 0x0000000F; WREG32(MC_CG_CONFIG, mc_cg_config); WREG32_P(MC_ARB_CG, CG_ARB_REQ(arb_freq_dest), ~CG_ARB_REQ_MASK); return 0; } static int ni_init_arb_table_index(struct radeon_device *rdev) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); u32 tmp; int ret; ret = rv770_read_smc_sram_dword(rdev, ni_pi->arb_table_start, &tmp, pi->sram_end); if (ret) return ret; tmp &= 0x00FFFFFF; tmp |= ((u32)MC_CG_ARB_FREQ_F1) << 24; return rv770_write_smc_sram_dword(rdev, ni_pi->arb_table_start, tmp, pi->sram_end); } static int ni_initial_switch_from_arb_f0_to_f1(struct radeon_device *rdev) { return ni_copy_and_switch_arb_sets(rdev, MC_CG_ARB_FREQ_F0, MC_CG_ARB_FREQ_F1); } static int ni_force_switch_to_arb_f0(struct radeon_device *rdev) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); u32 tmp; int ret; ret = rv770_read_smc_sram_dword(rdev, ni_pi->arb_table_start, &tmp, pi->sram_end); if (ret) return ret; tmp = (tmp >> 24) & 0xff; if (tmp == MC_CG_ARB_FREQ_F0) return 0; return ni_copy_and_switch_arb_sets(rdev, tmp, MC_CG_ARB_FREQ_F0); } static int ni_populate_memory_timing_parameters(struct radeon_device *rdev, struct rv7xx_pl *pl, SMC_NIslands_MCArbDramTimingRegisterSet *arb_regs) { u32 dram_timing; u32 dram_timing2; arb_regs->mc_arb_rfsh_rate = (u8)rv770_calculate_memory_refresh_rate(rdev, pl->sclk); radeon_atom_set_engine_dram_timings(rdev, pl->sclk, pl->mclk); dram_timing = RREG32(MC_ARB_DRAM_TIMING); dram_timing2 = RREG32(MC_ARB_DRAM_TIMING2); arb_regs->mc_arb_dram_timing = cpu_to_be32(dram_timing); arb_regs->mc_arb_dram_timing2 = cpu_to_be32(dram_timing2); return 0; } static int ni_do_program_memory_timing_parameters(struct radeon_device *rdev, struct radeon_ps *radeon_state, unsigned int first_arb_set) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); struct ni_ps *state = ni_get_ps(radeon_state); SMC_NIslands_MCArbDramTimingRegisterSet arb_regs = { 0 }; int i, ret = 0; for (i = 0; i < state->performance_level_count; i++) { ret = ni_populate_memory_timing_parameters(rdev, &state->performance_levels[i], &arb_regs); if (ret) break; ret = rv770_copy_bytes_to_smc(rdev, (u16)(ni_pi->arb_table_start + offsetof(SMC_NIslands_MCArbDramTimingRegisters, data) + sizeof(SMC_NIslands_MCArbDramTimingRegisterSet) * (first_arb_set + i)), (u8 *)&arb_regs, (u16)sizeof(SMC_NIslands_MCArbDramTimingRegisterSet), pi->sram_end); if (ret) break; } return ret; } static int ni_program_memory_timing_parameters(struct radeon_device *rdev, struct radeon_ps *radeon_new_state) { return ni_do_program_memory_timing_parameters(rdev, radeon_new_state, NISLANDS_DRIVER_STATE_ARB_INDEX); } static void ni_populate_initial_mvdd_value(struct radeon_device *rdev, struct NISLANDS_SMC_VOLTAGE_VALUE *voltage) { struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); voltage->index = eg_pi->mvdd_high_index; voltage->value = cpu_to_be16(MVDD_HIGH_VALUE); } static int ni_populate_smc_initial_state(struct radeon_device *rdev, struct radeon_ps *radeon_initial_state, NISLANDS_SMC_STATETABLE *table) { struct ni_ps *initial_state = ni_get_ps(radeon_initial_state); struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); u32 reg; int ret; table->initialState.levels[0].mclk.vMPLL_AD_FUNC_CNTL = cpu_to_be32(ni_pi->clock_registers.mpll_ad_func_cntl); table->initialState.levels[0].mclk.vMPLL_AD_FUNC_CNTL_2 = cpu_to_be32(ni_pi->clock_registers.mpll_ad_func_cntl_2); table->initialState.levels[0].mclk.vMPLL_DQ_FUNC_CNTL = cpu_to_be32(ni_pi->clock_registers.mpll_dq_func_cntl); table->initialState.levels[0].mclk.vMPLL_DQ_FUNC_CNTL_2 = cpu_to_be32(ni_pi->clock_registers.mpll_dq_func_cntl_2); table->initialState.levels[0].mclk.vMCLK_PWRMGT_CNTL = cpu_to_be32(ni_pi->clock_registers.mclk_pwrmgt_cntl); table->initialState.levels[0].mclk.vDLL_CNTL = cpu_to_be32(ni_pi->clock_registers.dll_cntl); table->initialState.levels[0].mclk.vMPLL_SS = cpu_to_be32(ni_pi->clock_registers.mpll_ss1); table->initialState.levels[0].mclk.vMPLL_SS2 = cpu_to_be32(ni_pi->clock_registers.mpll_ss2); table->initialState.levels[0].mclk.mclk_value = cpu_to_be32(initial_state->performance_levels[0].mclk); table->initialState.levels[0].sclk.vCG_SPLL_FUNC_CNTL = cpu_to_be32(ni_pi->clock_registers.cg_spll_func_cntl); table->initialState.levels[0].sclk.vCG_SPLL_FUNC_CNTL_2 = cpu_to_be32(ni_pi->clock_registers.cg_spll_func_cntl_2); table->initialState.levels[0].sclk.vCG_SPLL_FUNC_CNTL_3 = cpu_to_be32(ni_pi->clock_registers.cg_spll_func_cntl_3); table->initialState.levels[0].sclk.vCG_SPLL_FUNC_CNTL_4 = cpu_to_be32(ni_pi->clock_registers.cg_spll_func_cntl_4); table->initialState.levels[0].sclk.vCG_SPLL_SPREAD_SPECTRUM = cpu_to_be32(ni_pi->clock_registers.cg_spll_spread_spectrum); table->initialState.levels[0].sclk.vCG_SPLL_SPREAD_SPECTRUM_2 = cpu_to_be32(ni_pi->clock_registers.cg_spll_spread_spectrum_2); table->initialState.levels[0].sclk.sclk_value = cpu_to_be32(initial_state->performance_levels[0].sclk); table->initialState.levels[0].arbRefreshState = NISLANDS_INITIAL_STATE_ARB_INDEX; table->initialState.levels[0].ACIndex = 0; ret = ni_populate_voltage_value(rdev, &eg_pi->vddc_voltage_table, initial_state->performance_levels[0].vddc, &table->initialState.levels[0].vddc); if (!ret) { u16 std_vddc; ret = ni_get_std_voltage_value(rdev, &table->initialState.levels[0].vddc, &std_vddc); if (!ret) ni_populate_std_voltage_value(rdev, std_vddc, table->initialState.levels[0].vddc.index, &table->initialState.levels[0].std_vddc); } if (eg_pi->vddci_control) ni_populate_voltage_value(rdev, &eg_pi->vddci_voltage_table, initial_state->performance_levels[0].vddci, &table->initialState.levels[0].vddci); ni_populate_initial_mvdd_value(rdev, &table->initialState.levels[0].mvdd); reg = CG_R(0xffff) | CG_L(0); table->initialState.levels[0].aT = cpu_to_be32(reg); table->initialState.levels[0].bSP = cpu_to_be32(pi->dsp); if (pi->boot_in_gen2) table->initialState.levels[0].gen2PCIE = 1; else table->initialState.levels[0].gen2PCIE = 0; if (pi->mem_gddr5) { table->initialState.levels[0].strobeMode = cypress_get_strobe_mode_settings(rdev, initial_state->performance_levels[0].mclk); if (initial_state->performance_levels[0].mclk > pi->mclk_edc_enable_threshold) table->initialState.levels[0].mcFlags = NISLANDS_SMC_MC_EDC_RD_FLAG | NISLANDS_SMC_MC_EDC_WR_FLAG; else table->initialState.levels[0].mcFlags = 0; } table->initialState.levelCount = 1; table->initialState.flags |= PPSMC_SWSTATE_FLAG_DC; table->initialState.levels[0].dpm2.MaxPS = 0; table->initialState.levels[0].dpm2.NearTDPDec = 0; table->initialState.levels[0].dpm2.AboveSafeInc = 0; table->initialState.levels[0].dpm2.BelowSafeInc = 0; reg = MIN_POWER_MASK | MAX_POWER_MASK; table->initialState.levels[0].SQPowerThrottle = cpu_to_be32(reg); reg = MAX_POWER_DELTA_MASK | STI_SIZE_MASK | LTI_RATIO_MASK; table->initialState.levels[0].SQPowerThrottle_2 = cpu_to_be32(reg); return 0; } static int ni_populate_smc_acpi_state(struct radeon_device *rdev, NISLANDS_SMC_STATETABLE *table) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); u32 mpll_ad_func_cntl = ni_pi->clock_registers.mpll_ad_func_cntl; u32 mpll_ad_func_cntl_2 = ni_pi->clock_registers.mpll_ad_func_cntl_2; u32 mpll_dq_func_cntl = ni_pi->clock_registers.mpll_dq_func_cntl; u32 mpll_dq_func_cntl_2 = ni_pi->clock_registers.mpll_dq_func_cntl_2; u32 spll_func_cntl = ni_pi->clock_registers.cg_spll_func_cntl; u32 spll_func_cntl_2 = ni_pi->clock_registers.cg_spll_func_cntl_2; u32 spll_func_cntl_3 = ni_pi->clock_registers.cg_spll_func_cntl_3; u32 spll_func_cntl_4 = ni_pi->clock_registers.cg_spll_func_cntl_4; u32 mclk_pwrmgt_cntl = ni_pi->clock_registers.mclk_pwrmgt_cntl; u32 dll_cntl = ni_pi->clock_registers.dll_cntl; u32 reg; int ret; table->ACPIState = table->initialState; table->ACPIState.flags &= ~PPSMC_SWSTATE_FLAG_DC; if (pi->acpi_vddc) { ret = ni_populate_voltage_value(rdev, &eg_pi->vddc_voltage_table, pi->acpi_vddc, &table->ACPIState.levels[0].vddc); if (!ret) { u16 std_vddc; ret = ni_get_std_voltage_value(rdev, &table->ACPIState.levels[0].vddc, &std_vddc); if (!ret) ni_populate_std_voltage_value(rdev, std_vddc, table->ACPIState.levels[0].vddc.index, &table->ACPIState.levels[0].std_vddc); } if (pi->pcie_gen2) { if (pi->acpi_pcie_gen2) table->ACPIState.levels[0].gen2PCIE = 1; else table->ACPIState.levels[0].gen2PCIE = 0; } else { table->ACPIState.levels[0].gen2PCIE = 0; } } else { ret = ni_populate_voltage_value(rdev, &eg_pi->vddc_voltage_table, pi->min_vddc_in_table, &table->ACPIState.levels[0].vddc); if (!ret) { u16 std_vddc; ret = ni_get_std_voltage_value(rdev, &table->ACPIState.levels[0].vddc, &std_vddc); if (!ret) ni_populate_std_voltage_value(rdev, std_vddc, table->ACPIState.levels[0].vddc.index, &table->ACPIState.levels[0].std_vddc); } table->ACPIState.levels[0].gen2PCIE = 0; } if (eg_pi->acpi_vddci) { if (eg_pi->vddci_control) ni_populate_voltage_value(rdev, &eg_pi->vddci_voltage_table, eg_pi->acpi_vddci, &table->ACPIState.levels[0].vddci); } mpll_ad_func_cntl &= ~PDNB; mpll_ad_func_cntl_2 |= BIAS_GEN_PDNB | RESET_EN; if (pi->mem_gddr5) mpll_dq_func_cntl &= ~PDNB; mpll_dq_func_cntl_2 |= BIAS_GEN_PDNB | RESET_EN | BYPASS; mclk_pwrmgt_cntl |= (MRDCKA0_RESET | MRDCKA1_RESET | MRDCKB0_RESET | MRDCKB1_RESET | MRDCKC0_RESET | MRDCKC1_RESET | MRDCKD0_RESET | MRDCKD1_RESET); mclk_pwrmgt_cntl &= ~(MRDCKA0_PDNB | MRDCKA1_PDNB | MRDCKB0_PDNB | MRDCKB1_PDNB | MRDCKC0_PDNB | MRDCKC1_PDNB | MRDCKD0_PDNB | MRDCKD1_PDNB); dll_cntl |= (MRDCKA0_BYPASS | MRDCKA1_BYPASS | MRDCKB0_BYPASS | MRDCKB1_BYPASS | MRDCKC0_BYPASS | MRDCKC1_BYPASS | MRDCKD0_BYPASS | MRDCKD1_BYPASS); spll_func_cntl_2 &= ~SCLK_MUX_SEL_MASK; spll_func_cntl_2 |= SCLK_MUX_SEL(4); table->ACPIState.levels[0].mclk.vMPLL_AD_FUNC_CNTL = cpu_to_be32(mpll_ad_func_cntl); table->ACPIState.levels[0].mclk.vMPLL_AD_FUNC_CNTL_2 = cpu_to_be32(mpll_ad_func_cntl_2); table->ACPIState.levels[0].mclk.vMPLL_DQ_FUNC_CNTL = cpu_to_be32(mpll_dq_func_cntl); table->ACPIState.levels[0].mclk.vMPLL_DQ_FUNC_CNTL_2 = cpu_to_be32(mpll_dq_func_cntl_2); table->ACPIState.levels[0].mclk.vMCLK_PWRMGT_CNTL = cpu_to_be32(mclk_pwrmgt_cntl); table->ACPIState.levels[0].mclk.vDLL_CNTL = cpu_to_be32(dll_cntl); table->ACPIState.levels[0].mclk.mclk_value = 0; table->ACPIState.levels[0].sclk.vCG_SPLL_FUNC_CNTL = cpu_to_be32(spll_func_cntl); table->ACPIState.levels[0].sclk.vCG_SPLL_FUNC_CNTL_2 = cpu_to_be32(spll_func_cntl_2); table->ACPIState.levels[0].sclk.vCG_SPLL_FUNC_CNTL_3 = cpu_to_be32(spll_func_cntl_3); table->ACPIState.levels[0].sclk.vCG_SPLL_FUNC_CNTL_4 = cpu_to_be32(spll_func_cntl_4); table->ACPIState.levels[0].sclk.sclk_value = 0; ni_populate_mvdd_value(rdev, 0, &table->ACPIState.levels[0].mvdd); if (eg_pi->dynamic_ac_timing) table->ACPIState.levels[0].ACIndex = 1; table->ACPIState.levels[0].dpm2.MaxPS = 0; table->ACPIState.levels[0].dpm2.NearTDPDec = 0; table->ACPIState.levels[0].dpm2.AboveSafeInc = 0; table->ACPIState.levels[0].dpm2.BelowSafeInc = 0; reg = MIN_POWER_MASK | MAX_POWER_MASK; table->ACPIState.levels[0].SQPowerThrottle = cpu_to_be32(reg); reg = MAX_POWER_DELTA_MASK | STI_SIZE_MASK | LTI_RATIO_MASK; table->ACPIState.levels[0].SQPowerThrottle_2 = cpu_to_be32(reg); return 0; } static int ni_init_smc_table(struct radeon_device *rdev) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); int ret; struct radeon_ps *radeon_boot_state = rdev->pm.dpm.boot_ps; NISLANDS_SMC_STATETABLE *table = &ni_pi->smc_statetable; memset(table, 0, sizeof(NISLANDS_SMC_STATETABLE)); ni_populate_smc_voltage_tables(rdev, table); switch (rdev->pm.int_thermal_type) { case THERMAL_TYPE_NI: case THERMAL_TYPE_EMC2103_WITH_INTERNAL: table->thermalProtectType = PPSMC_THERMAL_PROTECT_TYPE_INTERNAL; break; case THERMAL_TYPE_NONE: table->thermalProtectType = PPSMC_THERMAL_PROTECT_TYPE_NONE; break; default: table->thermalProtectType = PPSMC_THERMAL_PROTECT_TYPE_EXTERNAL; break; } if (rdev->pm.dpm.platform_caps & ATOM_PP_PLATFORM_CAP_HARDWAREDC) table->systemFlags |= PPSMC_SYSTEMFLAG_GPIO_DC; if (rdev->pm.dpm.platform_caps & ATOM_PP_PLATFORM_CAP_REGULATOR_HOT) table->systemFlags |= PPSMC_SYSTEMFLAG_REGULATOR_HOT; if (rdev->pm.dpm.platform_caps & ATOM_PP_PLATFORM_CAP_STEPVDDC) table->systemFlags |= PPSMC_SYSTEMFLAG_STEPVDDC; if (pi->mem_gddr5) table->systemFlags |= PPSMC_SYSTEMFLAG_GDDR5; ret = ni_populate_smc_initial_state(rdev, radeon_boot_state, table); if (ret) return ret; ret = ni_populate_smc_acpi_state(rdev, table); if (ret) return ret; table->driverState = table->initialState; table->ULVState = table->initialState; ret = ni_do_program_memory_timing_parameters(rdev, radeon_boot_state, NISLANDS_INITIAL_STATE_ARB_INDEX); if (ret) return ret; return rv770_copy_bytes_to_smc(rdev, pi->state_table_start, (u8 *)table, sizeof(NISLANDS_SMC_STATETABLE), pi->sram_end); } static int ni_calculate_sclk_params(struct radeon_device *rdev, u32 engine_clock, NISLANDS_SMC_SCLK_VALUE *sclk) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); struct atom_clock_dividers dividers; u32 spll_func_cntl = ni_pi->clock_registers.cg_spll_func_cntl; u32 spll_func_cntl_2 = ni_pi->clock_registers.cg_spll_func_cntl_2; u32 spll_func_cntl_3 = ni_pi->clock_registers.cg_spll_func_cntl_3; u32 spll_func_cntl_4 = ni_pi->clock_registers.cg_spll_func_cntl_4; u32 cg_spll_spread_spectrum = ni_pi->clock_registers.cg_spll_spread_spectrum; u32 cg_spll_spread_spectrum_2 = ni_pi->clock_registers.cg_spll_spread_spectrum_2; u64 tmp; u32 reference_clock = rdev->clock.spll.reference_freq; u32 reference_divider; u32 fbdiv; int ret; ret = radeon_atom_get_clock_dividers(rdev, COMPUTE_ENGINE_PLL_PARAM, engine_clock, false, &dividers); if (ret) return ret; reference_divider = 1 + dividers.ref_div; tmp = (u64) engine_clock * reference_divider * dividers.post_div * 16834; do_div(tmp, reference_clock); fbdiv = (u32) tmp; spll_func_cntl &= ~(SPLL_PDIV_A_MASK | SPLL_REF_DIV_MASK); spll_func_cntl |= SPLL_REF_DIV(dividers.ref_div); spll_func_cntl |= SPLL_PDIV_A(dividers.post_div); spll_func_cntl_2 &= ~SCLK_MUX_SEL_MASK; spll_func_cntl_2 |= SCLK_MUX_SEL(2); spll_func_cntl_3 &= ~SPLL_FB_DIV_MASK; spll_func_cntl_3 |= SPLL_FB_DIV(fbdiv); spll_func_cntl_3 |= SPLL_DITHEN; if (pi->sclk_ss) { struct radeon_atom_ss ss; u32 vco_freq = engine_clock * dividers.post_div; if (radeon_atombios_get_asic_ss_info(rdev, &ss, ASIC_INTERNAL_ENGINE_SS, vco_freq)) { u32 clk_s = reference_clock * 5 / (reference_divider * ss.rate); u32 clk_v = 4 * ss.percentage * fbdiv / (clk_s * 10000); cg_spll_spread_spectrum &= ~CLK_S_MASK; cg_spll_spread_spectrum |= CLK_S(clk_s); cg_spll_spread_spectrum |= SSEN; cg_spll_spread_spectrum_2 &= ~CLK_V_MASK; cg_spll_spread_spectrum_2 |= CLK_V(clk_v); } } sclk->sclk_value = engine_clock; sclk->vCG_SPLL_FUNC_CNTL = spll_func_cntl; sclk->vCG_SPLL_FUNC_CNTL_2 = spll_func_cntl_2; sclk->vCG_SPLL_FUNC_CNTL_3 = spll_func_cntl_3; sclk->vCG_SPLL_FUNC_CNTL_4 = spll_func_cntl_4; sclk->vCG_SPLL_SPREAD_SPECTRUM = cg_spll_spread_spectrum; sclk->vCG_SPLL_SPREAD_SPECTRUM_2 = cg_spll_spread_spectrum_2; return 0; } static int ni_populate_sclk_value(struct radeon_device *rdev, u32 engine_clock, NISLANDS_SMC_SCLK_VALUE *sclk) { NISLANDS_SMC_SCLK_VALUE sclk_tmp; int ret; ret = ni_calculate_sclk_params(rdev, engine_clock, &sclk_tmp); if (!ret) { sclk->sclk_value = cpu_to_be32(sclk_tmp.sclk_value); sclk->vCG_SPLL_FUNC_CNTL = cpu_to_be32(sclk_tmp.vCG_SPLL_FUNC_CNTL); sclk->vCG_SPLL_FUNC_CNTL_2 = cpu_to_be32(sclk_tmp.vCG_SPLL_FUNC_CNTL_2); sclk->vCG_SPLL_FUNC_CNTL_3 = cpu_to_be32(sclk_tmp.vCG_SPLL_FUNC_CNTL_3); sclk->vCG_SPLL_FUNC_CNTL_4 = cpu_to_be32(sclk_tmp.vCG_SPLL_FUNC_CNTL_4); sclk->vCG_SPLL_SPREAD_SPECTRUM = cpu_to_be32(sclk_tmp.vCG_SPLL_SPREAD_SPECTRUM); sclk->vCG_SPLL_SPREAD_SPECTRUM_2 = cpu_to_be32(sclk_tmp.vCG_SPLL_SPREAD_SPECTRUM_2); } return ret; } static int ni_init_smc_spll_table(struct radeon_device *rdev) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); SMC_NISLANDS_SPLL_DIV_TABLE *spll_table; NISLANDS_SMC_SCLK_VALUE sclk_params; u32 fb_div; u32 p_div; u32 clk_s; u32 clk_v; u32 sclk = 0; int i, ret; u32 tmp; if (ni_pi->spll_table_start == 0) return -EINVAL; spll_table = kzalloc(sizeof(SMC_NISLANDS_SPLL_DIV_TABLE), GFP_KERNEL); if (spll_table == NULL) return -ENOMEM; for (i = 0; i < 256; i++) { ret = ni_calculate_sclk_params(rdev, sclk, &sclk_params); if (ret) break; p_div = (sclk_params.vCG_SPLL_FUNC_CNTL & SPLL_PDIV_A_MASK) >> SPLL_PDIV_A_SHIFT; fb_div = (sclk_params.vCG_SPLL_FUNC_CNTL_3 & SPLL_FB_DIV_MASK) >> SPLL_FB_DIV_SHIFT; clk_s = (sclk_params.vCG_SPLL_SPREAD_SPECTRUM & CLK_S_MASK) >> CLK_S_SHIFT; clk_v = (sclk_params.vCG_SPLL_SPREAD_SPECTRUM_2 & CLK_V_MASK) >> CLK_V_SHIFT; fb_div &= ~0x00001FFF; fb_div >>= 1; clk_v >>= 6; if (p_div & ~(SMC_NISLANDS_SPLL_DIV_TABLE_PDIV_MASK >> SMC_NISLANDS_SPLL_DIV_TABLE_PDIV_SHIFT)) ret = -EINVAL; if (clk_s & ~(SMC_NISLANDS_SPLL_DIV_TABLE_CLKS_MASK >> SMC_NISLANDS_SPLL_DIV_TABLE_CLKS_SHIFT)) ret = -EINVAL; if (clk_s & ~(SMC_NISLANDS_SPLL_DIV_TABLE_CLKS_MASK >> SMC_NISLANDS_SPLL_DIV_TABLE_CLKS_SHIFT)) ret = -EINVAL; if (clk_v & ~(SMC_NISLANDS_SPLL_DIV_TABLE_CLKV_MASK >> SMC_NISLANDS_SPLL_DIV_TABLE_CLKV_SHIFT)) ret = -EINVAL; if (ret) break; tmp = ((fb_div << SMC_NISLANDS_SPLL_DIV_TABLE_FBDIV_SHIFT) & SMC_NISLANDS_SPLL_DIV_TABLE_FBDIV_MASK) | ((p_div << SMC_NISLANDS_SPLL_DIV_TABLE_PDIV_SHIFT) & SMC_NISLANDS_SPLL_DIV_TABLE_PDIV_MASK); spll_table->freq[i] = cpu_to_be32(tmp); tmp = ((clk_v << SMC_NISLANDS_SPLL_DIV_TABLE_CLKV_SHIFT) & SMC_NISLANDS_SPLL_DIV_TABLE_CLKV_MASK) | ((clk_s << SMC_NISLANDS_SPLL_DIV_TABLE_CLKS_SHIFT) & SMC_NISLANDS_SPLL_DIV_TABLE_CLKS_MASK); spll_table->ss[i] = cpu_to_be32(tmp); sclk += 512; } if (!ret) ret = rv770_copy_bytes_to_smc(rdev, ni_pi->spll_table_start, (u8 *)spll_table, sizeof(SMC_NISLANDS_SPLL_DIV_TABLE), pi->sram_end); kfree(spll_table); return ret; } static int ni_populate_mclk_value(struct radeon_device *rdev, u32 engine_clock, u32 memory_clock, NISLANDS_SMC_MCLK_VALUE *mclk, bool strobe_mode, bool dll_state_on) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); u32 mpll_ad_func_cntl = ni_pi->clock_registers.mpll_ad_func_cntl; u32 mpll_ad_func_cntl_2 = ni_pi->clock_registers.mpll_ad_func_cntl_2; u32 mpll_dq_func_cntl = ni_pi->clock_registers.mpll_dq_func_cntl; u32 mpll_dq_func_cntl_2 = ni_pi->clock_registers.mpll_dq_func_cntl_2; u32 mclk_pwrmgt_cntl = ni_pi->clock_registers.mclk_pwrmgt_cntl; u32 dll_cntl = ni_pi->clock_registers.dll_cntl; u32 mpll_ss1 = ni_pi->clock_registers.mpll_ss1; u32 mpll_ss2 = ni_pi->clock_registers.mpll_ss2; struct atom_clock_dividers dividers; u32 ibias; u32 dll_speed; int ret; u32 mc_seq_misc7; ret = radeon_atom_get_clock_dividers(rdev, COMPUTE_MEMORY_PLL_PARAM, memory_clock, strobe_mode, &dividers); if (ret) return ret; if (!strobe_mode) { mc_seq_misc7 = RREG32(MC_SEQ_MISC7); if (mc_seq_misc7 & 0x8000000) dividers.post_div = 1; } ibias = cypress_map_clkf_to_ibias(rdev, dividers.whole_fb_div); mpll_ad_func_cntl &= ~(CLKR_MASK | YCLK_POST_DIV_MASK | CLKF_MASK | CLKFRAC_MASK | IBIAS_MASK); mpll_ad_func_cntl |= CLKR(dividers.ref_div); mpll_ad_func_cntl |= YCLK_POST_DIV(dividers.post_div); mpll_ad_func_cntl |= CLKF(dividers.whole_fb_div); mpll_ad_func_cntl |= CLKFRAC(dividers.frac_fb_div); mpll_ad_func_cntl |= IBIAS(ibias); if (dividers.vco_mode) mpll_ad_func_cntl_2 |= VCO_MODE; else mpll_ad_func_cntl_2 &= ~VCO_MODE; if (pi->mem_gddr5) { mpll_dq_func_cntl &= ~(CLKR_MASK | YCLK_POST_DIV_MASK | CLKF_MASK | CLKFRAC_MASK | IBIAS_MASK); mpll_dq_func_cntl |= CLKR(dividers.ref_div); mpll_dq_func_cntl |= YCLK_POST_DIV(dividers.post_div); mpll_dq_func_cntl |= CLKF(dividers.whole_fb_div); mpll_dq_func_cntl |= CLKFRAC(dividers.frac_fb_div); mpll_dq_func_cntl |= IBIAS(ibias); if (strobe_mode) mpll_dq_func_cntl &= ~PDNB; else mpll_dq_func_cntl |= PDNB; if (dividers.vco_mode) mpll_dq_func_cntl_2 |= VCO_MODE; else mpll_dq_func_cntl_2 &= ~VCO_MODE; } if (pi->mclk_ss) { struct radeon_atom_ss ss; u32 vco_freq = memory_clock * dividers.post_div; if (radeon_atombios_get_asic_ss_info(rdev, &ss, ASIC_INTERNAL_MEMORY_SS, vco_freq)) { u32 reference_clock = rdev->clock.mpll.reference_freq; u32 decoded_ref = rv740_get_decoded_reference_divider(dividers.ref_div); u32 clk_s = reference_clock * 5 / (decoded_ref * ss.rate); u32 clk_v = ss.percentage * (0x4000 * dividers.whole_fb_div + 0x800 * dividers.frac_fb_div) / (clk_s * 625); mpll_ss1 &= ~CLKV_MASK; mpll_ss1 |= CLKV(clk_v); mpll_ss2 &= ~CLKS_MASK; mpll_ss2 |= CLKS(clk_s); } } dll_speed = rv740_get_dll_speed(pi->mem_gddr5, memory_clock); mclk_pwrmgt_cntl &= ~DLL_SPEED_MASK; mclk_pwrmgt_cntl |= DLL_SPEED(dll_speed); if (dll_state_on) mclk_pwrmgt_cntl |= (MRDCKA0_PDNB | MRDCKA1_PDNB | MRDCKB0_PDNB | MRDCKB1_PDNB | MRDCKC0_PDNB | MRDCKC1_PDNB | MRDCKD0_PDNB | MRDCKD1_PDNB); else mclk_pwrmgt_cntl &= ~(MRDCKA0_PDNB | MRDCKA1_PDNB | MRDCKB0_PDNB | MRDCKB1_PDNB | MRDCKC0_PDNB | MRDCKC1_PDNB | MRDCKD0_PDNB | MRDCKD1_PDNB); mclk->mclk_value = cpu_to_be32(memory_clock); mclk->vMPLL_AD_FUNC_CNTL = cpu_to_be32(mpll_ad_func_cntl); mclk->vMPLL_AD_FUNC_CNTL_2 = cpu_to_be32(mpll_ad_func_cntl_2); mclk->vMPLL_DQ_FUNC_CNTL = cpu_to_be32(mpll_dq_func_cntl); mclk->vMPLL_DQ_FUNC_CNTL_2 = cpu_to_be32(mpll_dq_func_cntl_2); mclk->vMCLK_PWRMGT_CNTL = cpu_to_be32(mclk_pwrmgt_cntl); mclk->vDLL_CNTL = cpu_to_be32(dll_cntl); mclk->vMPLL_SS = cpu_to_be32(mpll_ss1); mclk->vMPLL_SS2 = cpu_to_be32(mpll_ss2); return 0; } static void ni_populate_smc_sp(struct radeon_device *rdev, struct radeon_ps *radeon_state, NISLANDS_SMC_SWSTATE *smc_state) { struct ni_ps *ps = ni_get_ps(radeon_state); struct rv7xx_power_info *pi = rv770_get_pi(rdev); int i; for (i = 0; i < ps->performance_level_count - 1; i++) smc_state->levels[i].bSP = cpu_to_be32(pi->dsp); smc_state->levels[ps->performance_level_count - 1].bSP = cpu_to_be32(pi->psp); } static int ni_convert_power_level_to_smc(struct radeon_device *rdev, struct rv7xx_pl *pl, NISLANDS_SMC_HW_PERFORMANCE_LEVEL *level) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); int ret; bool dll_state_on; u16 std_vddc; u32 tmp = RREG32(DC_STUTTER_CNTL); level->gen2PCIE = pi->pcie_gen2 ? ((pl->flags & ATOM_PPLIB_R600_FLAGS_PCIEGEN2) ? 1 : 0) : 0; ret = ni_populate_sclk_value(rdev, pl->sclk, &level->sclk); if (ret) return ret; level->mcFlags = 0; if (pi->mclk_stutter_mode_threshold && (pl->mclk <= pi->mclk_stutter_mode_threshold) && !eg_pi->uvd_enabled && (tmp & DC_STUTTER_ENABLE_A) && (tmp & DC_STUTTER_ENABLE_B)) level->mcFlags |= NISLANDS_SMC_MC_STUTTER_EN; if (pi->mem_gddr5) { if (pl->mclk > pi->mclk_edc_enable_threshold) level->mcFlags |= NISLANDS_SMC_MC_EDC_RD_FLAG; if (pl->mclk > eg_pi->mclk_edc_wr_enable_threshold) level->mcFlags |= NISLANDS_SMC_MC_EDC_WR_FLAG; level->strobeMode = cypress_get_strobe_mode_settings(rdev, pl->mclk); if (level->strobeMode & NISLANDS_SMC_STROBE_ENABLE) { if (cypress_get_mclk_frequency_ratio(rdev, pl->mclk, true) >= ((RREG32(MC_SEQ_MISC7) >> 16) & 0xf)) dll_state_on = ((RREG32(MC_SEQ_MISC5) >> 1) & 0x1) ? true : false; else dll_state_on = ((RREG32(MC_SEQ_MISC6) >> 1) & 0x1) ? true : false; } else { dll_state_on = false; if (pl->mclk > ni_pi->mclk_rtt_mode_threshold) level->mcFlags |= NISLANDS_SMC_MC_RTT_ENABLE; } ret = ni_populate_mclk_value(rdev, pl->sclk, pl->mclk, &level->mclk, (level->strobeMode & NISLANDS_SMC_STROBE_ENABLE) != 0, dll_state_on); } else ret = ni_populate_mclk_value(rdev, pl->sclk, pl->mclk, &level->mclk, 1, 1); if (ret) return ret; ret = ni_populate_voltage_value(rdev, &eg_pi->vddc_voltage_table, pl->vddc, &level->vddc); if (ret) return ret; ret = ni_get_std_voltage_value(rdev, &level->vddc, &std_vddc); if (ret) return ret; ni_populate_std_voltage_value(rdev, std_vddc, level->vddc.index, &level->std_vddc); if (eg_pi->vddci_control) { ret = ni_populate_voltage_value(rdev, &eg_pi->vddci_voltage_table, pl->vddci, &level->vddci); if (ret) return ret; } ni_populate_mvdd_value(rdev, pl->mclk, &level->mvdd); return ret; } static int ni_populate_smc_t(struct radeon_device *rdev, struct radeon_ps *radeon_state, NISLANDS_SMC_SWSTATE *smc_state) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_ps *state = ni_get_ps(radeon_state); u32 a_t; u32 t_l, t_h; u32 high_bsp; int i, ret; if (state->performance_level_count >= 9) return -EINVAL; if (state->performance_level_count < 2) { a_t = CG_R(0xffff) | CG_L(0); smc_state->levels[0].aT = cpu_to_be32(a_t); return 0; } smc_state->levels[0].aT = cpu_to_be32(0); for (i = 0; i <= state->performance_level_count - 2; i++) { if (eg_pi->uvd_enabled) ret = r600_calculate_at( 1000 * (i * (eg_pi->smu_uvd_hs ? 2 : 8) + 2), 100 * R600_AH_DFLT, state->performance_levels[i + 1].sclk, state->performance_levels[i].sclk, &t_l, &t_h); else ret = r600_calculate_at( 1000 * (i + 1), 100 * R600_AH_DFLT, state->performance_levels[i + 1].sclk, state->performance_levels[i].sclk, &t_l, &t_h); if (ret) { t_h = (i + 1) * 1000 - 50 * R600_AH_DFLT; t_l = (i + 1) * 1000 + 50 * R600_AH_DFLT; } a_t = be32_to_cpu(smc_state->levels[i].aT) & ~CG_R_MASK; a_t |= CG_R(t_l * pi->bsp / 20000); smc_state->levels[i].aT = cpu_to_be32(a_t); high_bsp = (i == state->performance_level_count - 2) ? pi->pbsp : pi->bsp; a_t = CG_R(0xffff) | CG_L(t_h * high_bsp / 20000); smc_state->levels[i + 1].aT = cpu_to_be32(a_t); } return 0; } static int ni_populate_power_containment_values(struct radeon_device *rdev, struct radeon_ps *radeon_state, NISLANDS_SMC_SWSTATE *smc_state) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); struct ni_ps *state = ni_get_ps(radeon_state); u32 prev_sclk; u32 max_sclk; u32 min_sclk; int i, ret; u32 tdp_limit; u32 near_tdp_limit; u32 power_boost_limit; u8 max_ps_percent; if (ni_pi->enable_power_containment == false) return 0; if (state->performance_level_count == 0) return -EINVAL; if (smc_state->levelCount != state->performance_level_count) return -EINVAL; ret = ni_calculate_adjusted_tdp_limits(rdev, false, /* ??? */ rdev->pm.dpm.tdp_adjustment, &tdp_limit, &near_tdp_limit); if (ret) return ret; power_boost_limit = ni_calculate_power_boost_limit(rdev, radeon_state, near_tdp_limit); ret = rv770_write_smc_sram_dword(rdev, pi->state_table_start + offsetof(NISLANDS_SMC_STATETABLE, dpm2Params) + offsetof(PP_NIslands_DPM2Parameters, PowerBoostLimit), ni_scale_power_for_smc(power_boost_limit, ni_get_smc_power_scaling_factor(rdev)), pi->sram_end); if (ret) power_boost_limit = 0; smc_state->levels[0].dpm2.MaxPS = 0; smc_state->levels[0].dpm2.NearTDPDec = 0; smc_state->levels[0].dpm2.AboveSafeInc = 0; smc_state->levels[0].dpm2.BelowSafeInc = 0; smc_state->levels[0].stateFlags |= power_boost_limit ? PPSMC_STATEFLAG_POWERBOOST : 0; for (i = 1; i < state->performance_level_count; i++) { prev_sclk = state->performance_levels[i-1].sclk; max_sclk = state->performance_levels[i].sclk; max_ps_percent = (i != (state->performance_level_count - 1)) ? NISLANDS_DPM2_MAXPS_PERCENT_M : NISLANDS_DPM2_MAXPS_PERCENT_H; if (max_sclk < prev_sclk) return -EINVAL; if ((max_ps_percent == 0) || (prev_sclk == max_sclk) || eg_pi->uvd_enabled) min_sclk = max_sclk; else if (1 == i) min_sclk = prev_sclk; else min_sclk = (prev_sclk * (u32)max_ps_percent) / 100; if (min_sclk < state->performance_levels[0].sclk) min_sclk = state->performance_levels[0].sclk; if (min_sclk == 0) return -EINVAL; smc_state->levels[i].dpm2.MaxPS = (u8)((NISLANDS_DPM2_MAX_PULSE_SKIP * (max_sclk - min_sclk)) / max_sclk); smc_state->levels[i].dpm2.NearTDPDec = NISLANDS_DPM2_NEAR_TDP_DEC; smc_state->levels[i].dpm2.AboveSafeInc = NISLANDS_DPM2_ABOVE_SAFE_INC; smc_state->levels[i].dpm2.BelowSafeInc = NISLANDS_DPM2_BELOW_SAFE_INC; smc_state->levels[i].stateFlags |= ((i != (state->performance_level_count - 1)) && power_boost_limit) ? PPSMC_STATEFLAG_POWERBOOST : 0; } return 0; } static int ni_populate_sq_ramping_values(struct radeon_device *rdev, struct radeon_ps *radeon_state, NISLANDS_SMC_SWSTATE *smc_state) { struct ni_power_info *ni_pi = ni_get_pi(rdev); struct ni_ps *state = ni_get_ps(radeon_state); u32 sq_power_throttle; u32 sq_power_throttle2; bool enable_sq_ramping = ni_pi->enable_sq_ramping; int i; if (state->performance_level_count == 0) return -EINVAL; if (smc_state->levelCount != state->performance_level_count) return -EINVAL; if (rdev->pm.dpm.sq_ramping_threshold == 0) return -EINVAL; if (NISLANDS_DPM2_SQ_RAMP_MAX_POWER > (MAX_POWER_MASK >> MAX_POWER_SHIFT)) enable_sq_ramping = false; if (NISLANDS_DPM2_SQ_RAMP_MIN_POWER > (MIN_POWER_MASK >> MIN_POWER_SHIFT)) enable_sq_ramping = false; if (NISLANDS_DPM2_SQ_RAMP_MAX_POWER_DELTA > (MAX_POWER_DELTA_MASK >> MAX_POWER_DELTA_SHIFT)) enable_sq_ramping = false; if (NISLANDS_DPM2_SQ_RAMP_STI_SIZE > (STI_SIZE_MASK >> STI_SIZE_SHIFT)) enable_sq_ramping = false; if (NISLANDS_DPM2_SQ_RAMP_LTI_RATIO > (LTI_RATIO_MASK >> LTI_RATIO_SHIFT)) enable_sq_ramping = false; for (i = 0; i < state->performance_level_count; i++) { sq_power_throttle = 0; sq_power_throttle2 = 0; if ((state->performance_levels[i].sclk >= rdev->pm.dpm.sq_ramping_threshold) && enable_sq_ramping) { sq_power_throttle |= MAX_POWER(NISLANDS_DPM2_SQ_RAMP_MAX_POWER); sq_power_throttle |= MIN_POWER(NISLANDS_DPM2_SQ_RAMP_MIN_POWER); sq_power_throttle2 |= MAX_POWER_DELTA(NISLANDS_DPM2_SQ_RAMP_MAX_POWER_DELTA); sq_power_throttle2 |= STI_SIZE(NISLANDS_DPM2_SQ_RAMP_STI_SIZE); sq_power_throttle2 |= LTI_RATIO(NISLANDS_DPM2_SQ_RAMP_LTI_RATIO); } else { sq_power_throttle |= MAX_POWER_MASK | MIN_POWER_MASK; sq_power_throttle2 |= MAX_POWER_DELTA_MASK | STI_SIZE_MASK | LTI_RATIO_MASK; } smc_state->levels[i].SQPowerThrottle = cpu_to_be32(sq_power_throttle); smc_state->levels[i].SQPowerThrottle_2 = cpu_to_be32(sq_power_throttle2); } return 0; } static int ni_enable_power_containment(struct radeon_device *rdev, struct radeon_ps *radeon_new_state, bool enable) { struct ni_power_info *ni_pi = ni_get_pi(rdev); PPSMC_Result smc_result; int ret = 0; if (ni_pi->enable_power_containment) { if (enable) { if (!r600_is_uvd_state(radeon_new_state->class, radeon_new_state->class2)) { smc_result = rv770_send_msg_to_smc(rdev, PPSMC_TDPClampingActive); if (smc_result != PPSMC_Result_OK) { ret = -EINVAL; ni_pi->pc_enabled = false; } else { ni_pi->pc_enabled = true; } } } else { smc_result = rv770_send_msg_to_smc(rdev, PPSMC_TDPClampingInactive); if (smc_result != PPSMC_Result_OK) ret = -EINVAL; ni_pi->pc_enabled = false; } } return ret; } static int ni_convert_power_state_to_smc(struct radeon_device *rdev, struct radeon_ps *radeon_state, NISLANDS_SMC_SWSTATE *smc_state) { struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); struct ni_ps *state = ni_get_ps(radeon_state); int i, ret; u32 threshold = state->performance_levels[state->performance_level_count - 1].sclk * 100 / 100; if (!(radeon_state->caps & ATOM_PPLIB_DISALLOW_ON_DC)) smc_state->flags |= PPSMC_SWSTATE_FLAG_DC; smc_state->levelCount = 0; if (state->performance_level_count > NISLANDS_MAX_SMC_PERFORMANCE_LEVELS_PER_SWSTATE) return -EINVAL; for (i = 0; i < state->performance_level_count; i++) { ret = ni_convert_power_level_to_smc(rdev, &state->performance_levels[i], &smc_state->levels[i]); smc_state->levels[i].arbRefreshState = (u8)(NISLANDS_DRIVER_STATE_ARB_INDEX + i); if (ret) return ret; if (ni_pi->enable_power_containment) smc_state->levels[i].displayWatermark = (state->performance_levels[i].sclk < threshold) ? PPSMC_DISPLAY_WATERMARK_LOW : PPSMC_DISPLAY_WATERMARK_HIGH; else smc_state->levels[i].displayWatermark = (i < 2) ? PPSMC_DISPLAY_WATERMARK_LOW : PPSMC_DISPLAY_WATERMARK_HIGH; if (eg_pi->dynamic_ac_timing) smc_state->levels[i].ACIndex = NISLANDS_MCREGISTERTABLE_FIRST_DRIVERSTATE_SLOT + i; else smc_state->levels[i].ACIndex = 0; smc_state->levelCount++; } rv770_write_smc_soft_register(rdev, NI_SMC_SOFT_REGISTER_watermark_threshold, cpu_to_be32(threshold / 512)); ni_populate_smc_sp(rdev, radeon_state, smc_state); ret = ni_populate_power_containment_values(rdev, radeon_state, smc_state); if (ret) ni_pi->enable_power_containment = false; ret = ni_populate_sq_ramping_values(rdev, radeon_state, smc_state); if (ret) ni_pi->enable_sq_ramping = false; return ni_populate_smc_t(rdev, radeon_state, smc_state); } static int ni_upload_sw_state(struct radeon_device *rdev, struct radeon_ps *radeon_new_state) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); u16 address = pi->state_table_start + offsetof(NISLANDS_SMC_STATETABLE, driverState); u16 state_size = sizeof(NISLANDS_SMC_SWSTATE) + ((NISLANDS_MAX_SMC_PERFORMANCE_LEVELS_PER_SWSTATE - 1) * sizeof(NISLANDS_SMC_HW_PERFORMANCE_LEVEL)); int ret; NISLANDS_SMC_SWSTATE *smc_state = kzalloc(state_size, GFP_KERNEL); if (smc_state == NULL) return -ENOMEM; ret = ni_convert_power_state_to_smc(rdev, radeon_new_state, smc_state); if (ret) goto done; ret = rv770_copy_bytes_to_smc(rdev, address, (u8 *)smc_state, state_size, pi->sram_end); done: kfree(smc_state); return ret; } static int ni_set_mc_special_registers(struct radeon_device *rdev, struct ni_mc_reg_table *table) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); u8 i, j, k; u32 temp_reg; for (i = 0, j = table->last; i < table->last; i++) { switch (table->mc_reg_address[i].s1) { case MC_SEQ_MISC1 >> 2: if (j >= SMC_NISLANDS_MC_REGISTER_ARRAY_SIZE) return -EINVAL; temp_reg = RREG32(MC_PMG_CMD_EMRS); table->mc_reg_address[j].s1 = MC_PMG_CMD_EMRS >> 2; table->mc_reg_address[j].s0 = MC_SEQ_PMG_CMD_EMRS_LP >> 2; for (k = 0; k < table->num_entries; k++) table->mc_reg_table_entry[k].mc_data[j] = ((temp_reg & 0xffff0000)) | ((table->mc_reg_table_entry[k].mc_data[i] & 0xffff0000) >> 16); j++; if (j >= SMC_NISLANDS_MC_REGISTER_ARRAY_SIZE) return -EINVAL; temp_reg = RREG32(MC_PMG_CMD_MRS); table->mc_reg_address[j].s1 = MC_PMG_CMD_MRS >> 2; table->mc_reg_address[j].s0 = MC_SEQ_PMG_CMD_MRS_LP >> 2; for(k = 0; k < table->num_entries; k++) { table->mc_reg_table_entry[k].mc_data[j] = (temp_reg & 0xffff0000) | (table->mc_reg_table_entry[k].mc_data[i] & 0x0000ffff); if (!pi->mem_gddr5) table->mc_reg_table_entry[k].mc_data[j] |= 0x100; } j++; if (j > SMC_NISLANDS_MC_REGISTER_ARRAY_SIZE) return -EINVAL; break; case MC_SEQ_RESERVE_M >> 2: temp_reg = RREG32(MC_PMG_CMD_MRS1); table->mc_reg_address[j].s1 = MC_PMG_CMD_MRS1 >> 2; table->mc_reg_address[j].s0 = MC_SEQ_PMG_CMD_MRS1_LP >> 2; for (k = 0; k < table->num_entries; k++) table->mc_reg_table_entry[k].mc_data[j] = (temp_reg & 0xffff0000) | (table->mc_reg_table_entry[k].mc_data[i] & 0x0000ffff); j++; if (j > SMC_NISLANDS_MC_REGISTER_ARRAY_SIZE) return -EINVAL; break; default: break; } } table->last = j; return 0; } static bool ni_check_s0_mc_reg_index(u16 in_reg, u16 *out_reg) { bool result = true; switch (in_reg) { case MC_SEQ_RAS_TIMING >> 2: *out_reg = MC_SEQ_RAS_TIMING_LP >> 2; break; case MC_SEQ_CAS_TIMING >> 2: *out_reg = MC_SEQ_CAS_TIMING_LP >> 2; break; case MC_SEQ_MISC_TIMING >> 2: *out_reg = MC_SEQ_MISC_TIMING_LP >> 2; break; case MC_SEQ_MISC_TIMING2 >> 2: *out_reg = MC_SEQ_MISC_TIMING2_LP >> 2; break; case MC_SEQ_RD_CTL_D0 >> 2: *out_reg = MC_SEQ_RD_CTL_D0_LP >> 2; break; case MC_SEQ_RD_CTL_D1 >> 2: *out_reg = MC_SEQ_RD_CTL_D1_LP >> 2; break; case MC_SEQ_WR_CTL_D0 >> 2: *out_reg = MC_SEQ_WR_CTL_D0_LP >> 2; break; case MC_SEQ_WR_CTL_D1 >> 2: *out_reg = MC_SEQ_WR_CTL_D1_LP >> 2; break; case MC_PMG_CMD_EMRS >> 2: *out_reg = MC_SEQ_PMG_CMD_EMRS_LP >> 2; break; case MC_PMG_CMD_MRS >> 2: *out_reg = MC_SEQ_PMG_CMD_MRS_LP >> 2; break; case MC_PMG_CMD_MRS1 >> 2: *out_reg = MC_SEQ_PMG_CMD_MRS1_LP >> 2; break; case MC_SEQ_PMG_TIMING >> 2: *out_reg = MC_SEQ_PMG_TIMING_LP >> 2; break; case MC_PMG_CMD_MRS2 >> 2: *out_reg = MC_SEQ_PMG_CMD_MRS2_LP >> 2; break; default: result = false; break; } return result; } static void ni_set_valid_flag(struct ni_mc_reg_table *table) { u8 i, j; for (i = 0; i < table->last; i++) { for (j = 1; j < table->num_entries; j++) { if (table->mc_reg_table_entry[j-1].mc_data[i] != table->mc_reg_table_entry[j].mc_data[i]) { table->valid_flag |= 1 << i; break; } } } } static void ni_set_s0_mc_reg_index(struct ni_mc_reg_table *table) { u32 i; u16 address; for (i = 0; i < table->last; i++) table->mc_reg_address[i].s0 = ni_check_s0_mc_reg_index(table->mc_reg_address[i].s1, &address) ? address : table->mc_reg_address[i].s1; } static int ni_copy_vbios_mc_reg_table(struct atom_mc_reg_table *table, struct ni_mc_reg_table *ni_table) { u8 i, j; if (table->last > SMC_NISLANDS_MC_REGISTER_ARRAY_SIZE) return -EINVAL; if (table->num_entries > MAX_AC_TIMING_ENTRIES) return -EINVAL; for (i = 0; i < table->last; i++) ni_table->mc_reg_address[i].s1 = table->mc_reg_address[i].s1; ni_table->last = table->last; for (i = 0; i < table->num_entries; i++) { ni_table->mc_reg_table_entry[i].mclk_max = table->mc_reg_table_entry[i].mclk_max; for (j = 0; j < table->last; j++) ni_table->mc_reg_table_entry[i].mc_data[j] = table->mc_reg_table_entry[i].mc_data[j]; } ni_table->num_entries = table->num_entries; return 0; } static int ni_initialize_mc_reg_table(struct radeon_device *rdev) { struct ni_power_info *ni_pi = ni_get_pi(rdev); int ret; struct atom_mc_reg_table *table; struct ni_mc_reg_table *ni_table = &ni_pi->mc_reg_table; u8 module_index = rv770_get_memory_module_index(rdev); table = kzalloc(sizeof(struct atom_mc_reg_table), GFP_KERNEL); if (!table) return -ENOMEM; WREG32(MC_SEQ_RAS_TIMING_LP, RREG32(MC_SEQ_RAS_TIMING)); WREG32(MC_SEQ_CAS_TIMING_LP, RREG32(MC_SEQ_CAS_TIMING)); WREG32(MC_SEQ_MISC_TIMING_LP, RREG32(MC_SEQ_MISC_TIMING)); WREG32(MC_SEQ_MISC_TIMING2_LP, RREG32(MC_SEQ_MISC_TIMING2)); WREG32(MC_SEQ_PMG_CMD_EMRS_LP, RREG32(MC_PMG_CMD_EMRS)); WREG32(MC_SEQ_PMG_CMD_MRS_LP, RREG32(MC_PMG_CMD_MRS)); WREG32(MC_SEQ_PMG_CMD_MRS1_LP, RREG32(MC_PMG_CMD_MRS1)); WREG32(MC_SEQ_WR_CTL_D0_LP, RREG32(MC_SEQ_WR_CTL_D0)); WREG32(MC_SEQ_WR_CTL_D1_LP, RREG32(MC_SEQ_WR_CTL_D1)); WREG32(MC_SEQ_RD_CTL_D0_LP, RREG32(MC_SEQ_RD_CTL_D0)); WREG32(MC_SEQ_RD_CTL_D1_LP, RREG32(MC_SEQ_RD_CTL_D1)); WREG32(MC_SEQ_PMG_TIMING_LP, RREG32(MC_SEQ_PMG_TIMING)); WREG32(MC_SEQ_PMG_CMD_MRS2_LP, RREG32(MC_PMG_CMD_MRS2)); ret = radeon_atom_init_mc_reg_table(rdev, module_index, table); if (ret) goto init_mc_done; ret = ni_copy_vbios_mc_reg_table(table, ni_table); if (ret) goto init_mc_done; ni_set_s0_mc_reg_index(ni_table); ret = ni_set_mc_special_registers(rdev, ni_table); if (ret) goto init_mc_done; ni_set_valid_flag(ni_table); init_mc_done: kfree(table); return ret; } static void ni_populate_mc_reg_addresses(struct radeon_device *rdev, SMC_NIslands_MCRegisters *mc_reg_table) { struct ni_power_info *ni_pi = ni_get_pi(rdev); u32 i, j; for (i = 0, j = 0; j < ni_pi->mc_reg_table.last; j++) { if (ni_pi->mc_reg_table.valid_flag & (1 << j)) { if (i >= SMC_NISLANDS_MC_REGISTER_ARRAY_SIZE) break; mc_reg_table->address[i].s0 = cpu_to_be16(ni_pi->mc_reg_table.mc_reg_address[j].s0); mc_reg_table->address[i].s1 = cpu_to_be16(ni_pi->mc_reg_table.mc_reg_address[j].s1); i++; } } mc_reg_table->last = (u8)i; } static void ni_convert_mc_registers(struct ni_mc_reg_entry *entry, SMC_NIslands_MCRegisterSet *data, u32 num_entries, u32 valid_flag) { u32 i, j; for (i = 0, j = 0; j < num_entries; j++) { if (valid_flag & (1 << j)) { data->value[i] = cpu_to_be32(entry->mc_data[j]); i++; } } } static void ni_convert_mc_reg_table_entry_to_smc(struct radeon_device *rdev, struct rv7xx_pl *pl, SMC_NIslands_MCRegisterSet *mc_reg_table_data) { struct ni_power_info *ni_pi = ni_get_pi(rdev); u32 i = 0; for (i = 0; i < ni_pi->mc_reg_table.num_entries; i++) { if (pl->mclk <= ni_pi->mc_reg_table.mc_reg_table_entry[i].mclk_max) break; } if ((i == ni_pi->mc_reg_table.num_entries) && (i > 0)) --i; ni_convert_mc_registers(&ni_pi->mc_reg_table.mc_reg_table_entry[i], mc_reg_table_data, ni_pi->mc_reg_table.last, ni_pi->mc_reg_table.valid_flag); } static void ni_convert_mc_reg_table_to_smc(struct radeon_device *rdev, struct radeon_ps *radeon_state, SMC_NIslands_MCRegisters *mc_reg_table) { struct ni_ps *state = ni_get_ps(radeon_state); int i; for (i = 0; i < state->performance_level_count; i++) { ni_convert_mc_reg_table_entry_to_smc(rdev, &state->performance_levels[i], &mc_reg_table->data[NISLANDS_MCREGISTERTABLE_FIRST_DRIVERSTATE_SLOT + i]); } } static int ni_populate_mc_reg_table(struct radeon_device *rdev, struct radeon_ps *radeon_boot_state) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); struct ni_ps *boot_state = ni_get_ps(radeon_boot_state); SMC_NIslands_MCRegisters *mc_reg_table = &ni_pi->smc_mc_reg_table; memset(mc_reg_table, 0, sizeof(SMC_NIslands_MCRegisters)); rv770_write_smc_soft_register(rdev, NI_SMC_SOFT_REGISTER_seq_index, 1); ni_populate_mc_reg_addresses(rdev, mc_reg_table); ni_convert_mc_reg_table_entry_to_smc(rdev, &boot_state->performance_levels[0], &mc_reg_table->data[0]); ni_convert_mc_registers(&ni_pi->mc_reg_table.mc_reg_table_entry[0], &mc_reg_table->data[1], ni_pi->mc_reg_table.last, ni_pi->mc_reg_table.valid_flag); ni_convert_mc_reg_table_to_smc(rdev, radeon_boot_state, mc_reg_table); return rv770_copy_bytes_to_smc(rdev, eg_pi->mc_reg_table_start, (u8 *)mc_reg_table, sizeof(SMC_NIslands_MCRegisters), pi->sram_end); } static int ni_upload_mc_reg_table(struct radeon_device *rdev, struct radeon_ps *radeon_new_state) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); struct ni_ps *ni_new_state = ni_get_ps(radeon_new_state); SMC_NIslands_MCRegisters *mc_reg_table = &ni_pi->smc_mc_reg_table; u16 address; memset(mc_reg_table, 0, sizeof(SMC_NIslands_MCRegisters)); ni_convert_mc_reg_table_to_smc(rdev, radeon_new_state, mc_reg_table); address = eg_pi->mc_reg_table_start + (u16)offsetof(SMC_NIslands_MCRegisters, data[NISLANDS_MCREGISTERTABLE_FIRST_DRIVERSTATE_SLOT]); return rv770_copy_bytes_to_smc(rdev, address, (u8 *)&mc_reg_table->data[NISLANDS_MCREGISTERTABLE_FIRST_DRIVERSTATE_SLOT], sizeof(SMC_NIslands_MCRegisterSet) * ni_new_state->performance_level_count, pi->sram_end); } static int ni_init_driver_calculated_leakage_table(struct radeon_device *rdev, PP_NIslands_CACTABLES *cac_tables) { struct ni_power_info *ni_pi = ni_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); u32 leakage = 0; unsigned int i, j, table_size; s32 t; u32 smc_leakage, max_leakage = 0; u32 scaling_factor; table_size = eg_pi->vddc_voltage_table.count; if (SMC_NISLANDS_LKGE_LUT_NUM_OF_VOLT_ENTRIES < table_size) table_size = SMC_NISLANDS_LKGE_LUT_NUM_OF_VOLT_ENTRIES; scaling_factor = ni_get_smc_power_scaling_factor(rdev); for (i = 0; i < SMC_NISLANDS_LKGE_LUT_NUM_OF_TEMP_ENTRIES; i++) { for (j = 0; j < table_size; j++) { t = (1000 * ((i + 1) * 8)); if (t < ni_pi->cac_data.leakage_minimum_temperature) t = ni_pi->cac_data.leakage_minimum_temperature; ni_calculate_leakage_for_v_and_t(rdev, &ni_pi->cac_data.leakage_coefficients, eg_pi->vddc_voltage_table.entries[j].value, t, ni_pi->cac_data.i_leakage, &leakage); smc_leakage = ni_scale_power_for_smc(leakage, scaling_factor) / 1000; if (smc_leakage > max_leakage) max_leakage = smc_leakage; cac_tables->cac_lkge_lut[i][j] = cpu_to_be32(smc_leakage); } } for (j = table_size; j < SMC_NISLANDS_LKGE_LUT_NUM_OF_VOLT_ENTRIES; j++) { for (i = 0; i < SMC_NISLANDS_LKGE_LUT_NUM_OF_TEMP_ENTRIES; i++) cac_tables->cac_lkge_lut[i][j] = cpu_to_be32(max_leakage); } return 0; } static int ni_init_simplified_leakage_table(struct radeon_device *rdev, PP_NIslands_CACTABLES *cac_tables) { struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct radeon_cac_leakage_table *leakage_table = &rdev->pm.dpm.dyn_state.cac_leakage_table; u32 i, j, table_size; u32 smc_leakage, max_leakage = 0; u32 scaling_factor; if (!leakage_table) return -EINVAL; table_size = leakage_table->count; if (eg_pi->vddc_voltage_table.count != table_size) table_size = (eg_pi->vddc_voltage_table.count < leakage_table->count) ? eg_pi->vddc_voltage_table.count : leakage_table->count; if (SMC_NISLANDS_LKGE_LUT_NUM_OF_VOLT_ENTRIES < table_size) table_size = SMC_NISLANDS_LKGE_LUT_NUM_OF_VOLT_ENTRIES; if (table_size == 0) return -EINVAL; scaling_factor = ni_get_smc_power_scaling_factor(rdev); for (j = 0; j < table_size; j++) { smc_leakage = leakage_table->entries[j].leakage; if (smc_leakage > max_leakage) max_leakage = smc_leakage; for (i = 0; i < SMC_NISLANDS_LKGE_LUT_NUM_OF_TEMP_ENTRIES; i++) cac_tables->cac_lkge_lut[i][j] = cpu_to_be32(ni_scale_power_for_smc(smc_leakage, scaling_factor)); } for (j = table_size; j < SMC_NISLANDS_LKGE_LUT_NUM_OF_VOLT_ENTRIES; j++) { for (i = 0; i < SMC_NISLANDS_LKGE_LUT_NUM_OF_TEMP_ENTRIES; i++) cac_tables->cac_lkge_lut[i][j] = cpu_to_be32(ni_scale_power_for_smc(max_leakage, scaling_factor)); } return 0; } static int ni_initialize_smc_cac_tables(struct radeon_device *rdev) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); PP_NIslands_CACTABLES *cac_tables = NULL; int i, ret; u32 reg; if (ni_pi->enable_cac == false) return 0; cac_tables = kzalloc(sizeof(PP_NIslands_CACTABLES), GFP_KERNEL); if (!cac_tables) return -ENOMEM; reg = RREG32(CG_CAC_CTRL) & ~(TID_CNT_MASK | TID_UNIT_MASK); reg |= (TID_CNT(ni_pi->cac_weights->tid_cnt) | TID_UNIT(ni_pi->cac_weights->tid_unit)); WREG32(CG_CAC_CTRL, reg); for (i = 0; i < NISLANDS_DCCAC_MAX_LEVELS; i++) ni_pi->dc_cac_table[i] = ni_pi->cac_weights->dc_cac[i]; for (i = 0; i < SMC_NISLANDS_BIF_LUT_NUM_OF_ENTRIES; i++) cac_tables->cac_bif_lut[i] = ni_pi->cac_weights->pcie_cac[i]; ni_pi->cac_data.i_leakage = rdev->pm.dpm.cac_leakage; ni_pi->cac_data.pwr_const = 0; ni_pi->cac_data.dc_cac_value = ni_pi->dc_cac_table[NISLANDS_DCCAC_LEVEL_0]; ni_pi->cac_data.bif_cac_value = 0; ni_pi->cac_data.mc_wr_weight = ni_pi->cac_weights->mc_write_weight; ni_pi->cac_data.mc_rd_weight = ni_pi->cac_weights->mc_read_weight; ni_pi->cac_data.allow_ovrflw = 0; ni_pi->cac_data.l2num_win_tdp = ni_pi->lta_window_size; ni_pi->cac_data.num_win_tdp = 0; ni_pi->cac_data.lts_truncate_n = ni_pi->lts_truncate; if (ni_pi->driver_calculate_cac_leakage) ret = ni_init_driver_calculated_leakage_table(rdev, cac_tables); else ret = ni_init_simplified_leakage_table(rdev, cac_tables); if (ret) goto done_free; cac_tables->pwr_const = cpu_to_be32(ni_pi->cac_data.pwr_const); cac_tables->dc_cacValue = cpu_to_be32(ni_pi->cac_data.dc_cac_value); cac_tables->bif_cacValue = cpu_to_be32(ni_pi->cac_data.bif_cac_value); cac_tables->AllowOvrflw = ni_pi->cac_data.allow_ovrflw; cac_tables->MCWrWeight = ni_pi->cac_data.mc_wr_weight; cac_tables->MCRdWeight = ni_pi->cac_data.mc_rd_weight; cac_tables->numWin_TDP = ni_pi->cac_data.num_win_tdp; cac_tables->l2numWin_TDP = ni_pi->cac_data.l2num_win_tdp; cac_tables->lts_truncate_n = ni_pi->cac_data.lts_truncate_n; ret = rv770_copy_bytes_to_smc(rdev, ni_pi->cac_table_start, (u8 *)cac_tables, sizeof(PP_NIslands_CACTABLES), pi->sram_end); done_free: if (ret) { ni_pi->enable_cac = false; ni_pi->enable_power_containment = false; } kfree(cac_tables); return 0; } static int ni_initialize_hardware_cac_manager(struct radeon_device *rdev) { struct ni_power_info *ni_pi = ni_get_pi(rdev); u32 reg; if (!ni_pi->enable_cac || !ni_pi->cac_configuration_required) return 0; if (ni_pi->cac_weights == NULL) return -EINVAL; reg = RREG32_CG(CG_CAC_REGION_1_WEIGHT_0) & ~(WEIGHT_TCP_SIG0_MASK | WEIGHT_TCP_SIG1_MASK | WEIGHT_TA_SIG_MASK); reg |= (WEIGHT_TCP_SIG0(ni_pi->cac_weights->weight_tcp_sig0) | WEIGHT_TCP_SIG1(ni_pi->cac_weights->weight_tcp_sig1) | WEIGHT_TA_SIG(ni_pi->cac_weights->weight_ta_sig)); WREG32_CG(CG_CAC_REGION_1_WEIGHT_0, reg); reg = RREG32_CG(CG_CAC_REGION_1_WEIGHT_1) & ~(WEIGHT_TCC_EN0_MASK | WEIGHT_TCC_EN1_MASK | WEIGHT_TCC_EN2_MASK); reg |= (WEIGHT_TCC_EN0(ni_pi->cac_weights->weight_tcc_en0) | WEIGHT_TCC_EN1(ni_pi->cac_weights->weight_tcc_en1) | WEIGHT_TCC_EN2(ni_pi->cac_weights->weight_tcc_en2)); WREG32_CG(CG_CAC_REGION_1_WEIGHT_1, reg); reg = RREG32_CG(CG_CAC_REGION_2_WEIGHT_0) & ~(WEIGHT_CB_EN0_MASK | WEIGHT_CB_EN1_MASK | WEIGHT_CB_EN2_MASK | WEIGHT_CB_EN3_MASK); reg |= (WEIGHT_CB_EN0(ni_pi->cac_weights->weight_cb_en0) | WEIGHT_CB_EN1(ni_pi->cac_weights->weight_cb_en1) | WEIGHT_CB_EN2(ni_pi->cac_weights->weight_cb_en2) | WEIGHT_CB_EN3(ni_pi->cac_weights->weight_cb_en3)); WREG32_CG(CG_CAC_REGION_2_WEIGHT_0, reg); reg = RREG32_CG(CG_CAC_REGION_2_WEIGHT_1) & ~(WEIGHT_DB_SIG0_MASK | WEIGHT_DB_SIG1_MASK | WEIGHT_DB_SIG2_MASK | WEIGHT_DB_SIG3_MASK); reg |= (WEIGHT_DB_SIG0(ni_pi->cac_weights->weight_db_sig0) | WEIGHT_DB_SIG1(ni_pi->cac_weights->weight_db_sig1) | WEIGHT_DB_SIG2(ni_pi->cac_weights->weight_db_sig2) | WEIGHT_DB_SIG3(ni_pi->cac_weights->weight_db_sig3)); WREG32_CG(CG_CAC_REGION_2_WEIGHT_1, reg); reg = RREG32_CG(CG_CAC_REGION_2_WEIGHT_2) & ~(WEIGHT_SXM_SIG0_MASK | WEIGHT_SXM_SIG1_MASK | WEIGHT_SXM_SIG2_MASK | WEIGHT_SXS_SIG0_MASK | WEIGHT_SXS_SIG1_MASK); reg |= (WEIGHT_SXM_SIG0(ni_pi->cac_weights->weight_sxm_sig0) | WEIGHT_SXM_SIG1(ni_pi->cac_weights->weight_sxm_sig1) | WEIGHT_SXM_SIG2(ni_pi->cac_weights->weight_sxm_sig2) | WEIGHT_SXS_SIG0(ni_pi->cac_weights->weight_sxs_sig0) | WEIGHT_SXS_SIG1(ni_pi->cac_weights->weight_sxs_sig1)); WREG32_CG(CG_CAC_REGION_2_WEIGHT_2, reg); reg = RREG32_CG(CG_CAC_REGION_3_WEIGHT_0) & ~(WEIGHT_XBR_0_MASK | WEIGHT_XBR_1_MASK | WEIGHT_XBR_2_MASK | WEIGHT_SPI_SIG0_MASK); reg |= (WEIGHT_XBR_0(ni_pi->cac_weights->weight_xbr_0) | WEIGHT_XBR_1(ni_pi->cac_weights->weight_xbr_1) | WEIGHT_XBR_2(ni_pi->cac_weights->weight_xbr_2) | WEIGHT_SPI_SIG0(ni_pi->cac_weights->weight_spi_sig0)); WREG32_CG(CG_CAC_REGION_3_WEIGHT_0, reg); reg = RREG32_CG(CG_CAC_REGION_3_WEIGHT_1) & ~(WEIGHT_SPI_SIG1_MASK | WEIGHT_SPI_SIG2_MASK | WEIGHT_SPI_SIG3_MASK | WEIGHT_SPI_SIG4_MASK | WEIGHT_SPI_SIG5_MASK); reg |= (WEIGHT_SPI_SIG1(ni_pi->cac_weights->weight_spi_sig1) | WEIGHT_SPI_SIG2(ni_pi->cac_weights->weight_spi_sig2) | WEIGHT_SPI_SIG3(ni_pi->cac_weights->weight_spi_sig3) | WEIGHT_SPI_SIG4(ni_pi->cac_weights->weight_spi_sig4) | WEIGHT_SPI_SIG5(ni_pi->cac_weights->weight_spi_sig5)); WREG32_CG(CG_CAC_REGION_3_WEIGHT_1, reg); reg = RREG32_CG(CG_CAC_REGION_4_WEIGHT_0) & ~(WEIGHT_LDS_SIG0_MASK | WEIGHT_LDS_SIG1_MASK | WEIGHT_SC_MASK); reg |= (WEIGHT_LDS_SIG0(ni_pi->cac_weights->weight_lds_sig0) | WEIGHT_LDS_SIG1(ni_pi->cac_weights->weight_lds_sig1) | WEIGHT_SC(ni_pi->cac_weights->weight_sc)); WREG32_CG(CG_CAC_REGION_4_WEIGHT_0, reg); reg = RREG32_CG(CG_CAC_REGION_4_WEIGHT_1) & ~(WEIGHT_BIF_MASK | WEIGHT_CP_MASK | WEIGHT_PA_SIG0_MASK | WEIGHT_PA_SIG1_MASK | WEIGHT_VGT_SIG0_MASK); reg |= (WEIGHT_BIF(ni_pi->cac_weights->weight_bif) | WEIGHT_CP(ni_pi->cac_weights->weight_cp) | WEIGHT_PA_SIG0(ni_pi->cac_weights->weight_pa_sig0) | WEIGHT_PA_SIG1(ni_pi->cac_weights->weight_pa_sig1) | WEIGHT_VGT_SIG0(ni_pi->cac_weights->weight_vgt_sig0)); WREG32_CG(CG_CAC_REGION_4_WEIGHT_1, reg); reg = RREG32_CG(CG_CAC_REGION_4_WEIGHT_2) & ~(WEIGHT_VGT_SIG1_MASK | WEIGHT_VGT_SIG2_MASK | WEIGHT_DC_SIG0_MASK | WEIGHT_DC_SIG1_MASK | WEIGHT_DC_SIG2_MASK); reg |= (WEIGHT_VGT_SIG1(ni_pi->cac_weights->weight_vgt_sig1) | WEIGHT_VGT_SIG2(ni_pi->cac_weights->weight_vgt_sig2) | WEIGHT_DC_SIG0(ni_pi->cac_weights->weight_dc_sig0) | WEIGHT_DC_SIG1(ni_pi->cac_weights->weight_dc_sig1) | WEIGHT_DC_SIG2(ni_pi->cac_weights->weight_dc_sig2)); WREG32_CG(CG_CAC_REGION_4_WEIGHT_2, reg); reg = RREG32_CG(CG_CAC_REGION_4_WEIGHT_3) & ~(WEIGHT_DC_SIG3_MASK | WEIGHT_UVD_SIG0_MASK | WEIGHT_UVD_SIG1_MASK | WEIGHT_SPARE0_MASK | WEIGHT_SPARE1_MASK); reg |= (WEIGHT_DC_SIG3(ni_pi->cac_weights->weight_dc_sig3) | WEIGHT_UVD_SIG0(ni_pi->cac_weights->weight_uvd_sig0) | WEIGHT_UVD_SIG1(ni_pi->cac_weights->weight_uvd_sig1) | WEIGHT_SPARE0(ni_pi->cac_weights->weight_spare0) | WEIGHT_SPARE1(ni_pi->cac_weights->weight_spare1)); WREG32_CG(CG_CAC_REGION_4_WEIGHT_3, reg); reg = RREG32_CG(CG_CAC_REGION_5_WEIGHT_0) & ~(WEIGHT_SQ_VSP_MASK | WEIGHT_SQ_VSP0_MASK); reg |= (WEIGHT_SQ_VSP(ni_pi->cac_weights->weight_sq_vsp) | WEIGHT_SQ_VSP0(ni_pi->cac_weights->weight_sq_vsp0)); WREG32_CG(CG_CAC_REGION_5_WEIGHT_0, reg); reg = RREG32_CG(CG_CAC_REGION_5_WEIGHT_1) & ~(WEIGHT_SQ_GPR_MASK); reg |= WEIGHT_SQ_GPR(ni_pi->cac_weights->weight_sq_gpr); WREG32_CG(CG_CAC_REGION_5_WEIGHT_1, reg); reg = RREG32_CG(CG_CAC_REGION_4_OVERRIDE_4) & ~(OVR_MODE_SPARE_0_MASK | OVR_VAL_SPARE_0_MASK | OVR_MODE_SPARE_1_MASK | OVR_VAL_SPARE_1_MASK); reg |= (OVR_MODE_SPARE_0(ni_pi->cac_weights->ovr_mode_spare_0) | OVR_VAL_SPARE_0(ni_pi->cac_weights->ovr_val_spare_0) | OVR_MODE_SPARE_1(ni_pi->cac_weights->ovr_mode_spare_1) | OVR_VAL_SPARE_1(ni_pi->cac_weights->ovr_val_spare_1)); WREG32_CG(CG_CAC_REGION_4_OVERRIDE_4, reg); reg = RREG32(SQ_CAC_THRESHOLD) & ~(VSP_MASK | VSP0_MASK | GPR_MASK); reg |= (VSP(ni_pi->cac_weights->vsp) | VSP0(ni_pi->cac_weights->vsp0) | GPR(ni_pi->cac_weights->gpr)); WREG32(SQ_CAC_THRESHOLD, reg); reg = (MCDW_WR_ENABLE | MCDX_WR_ENABLE | MCDY_WR_ENABLE | MCDZ_WR_ENABLE | INDEX(0x09D4)); WREG32(MC_CG_CONFIG, reg); reg = (READ_WEIGHT(ni_pi->cac_weights->mc_read_weight) | WRITE_WEIGHT(ni_pi->cac_weights->mc_write_weight) | ALLOW_OVERFLOW); WREG32(MC_CG_DATAPORT, reg); return 0; } static int ni_enable_smc_cac(struct radeon_device *rdev, struct radeon_ps *radeon_new_state, bool enable) { struct ni_power_info *ni_pi = ni_get_pi(rdev); int ret = 0; PPSMC_Result smc_result; if (ni_pi->enable_cac) { if (enable) { if (!r600_is_uvd_state(radeon_new_state->class, radeon_new_state->class2)) { smc_result = rv770_send_msg_to_smc(rdev, PPSMC_MSG_CollectCAC_PowerCorreln); if (ni_pi->support_cac_long_term_average) { smc_result = rv770_send_msg_to_smc(rdev, PPSMC_CACLongTermAvgEnable); if (PPSMC_Result_OK != smc_result) ni_pi->support_cac_long_term_average = false; } smc_result = rv770_send_msg_to_smc(rdev, PPSMC_MSG_EnableCac); if (PPSMC_Result_OK != smc_result) ret = -EINVAL; ni_pi->cac_enabled = (PPSMC_Result_OK == smc_result) ? true : false; } } else if (ni_pi->cac_enabled) { smc_result = rv770_send_msg_to_smc(rdev, PPSMC_MSG_DisableCac); ni_pi->cac_enabled = false; if (ni_pi->support_cac_long_term_average) { smc_result = rv770_send_msg_to_smc(rdev, PPSMC_CACLongTermAvgDisable); if (PPSMC_Result_OK != smc_result) ni_pi->support_cac_long_term_average = false; } } } return ret; } static int ni_pcie_performance_request(struct radeon_device *rdev, u8 perf_req, bool advertise) { #if defined(CONFIG_ACPI) struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); if ((perf_req == PCIE_PERF_REQ_PECI_GEN1) || (perf_req == PCIE_PERF_REQ_PECI_GEN2)) { if (eg_pi->pcie_performance_request_registered == false) radeon_acpi_pcie_notify_device_ready(rdev); eg_pi->pcie_performance_request_registered = true; return radeon_acpi_pcie_performance_request(rdev, perf_req, advertise); } else if ((perf_req == PCIE_PERF_REQ_REMOVE_REGISTRY) && eg_pi->pcie_performance_request_registered) { eg_pi->pcie_performance_request_registered = false; return radeon_acpi_pcie_performance_request(rdev, perf_req, advertise); } #endif return 0; } static int ni_advertise_gen2_capability(struct radeon_device *rdev) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); u32 tmp; tmp = RREG32_PCIE_PORT(PCIE_LC_SPEED_CNTL); if ((tmp & LC_OTHER_SIDE_EVER_SENT_GEN2) && (tmp & LC_OTHER_SIDE_SUPPORTS_GEN2)) pi->pcie_gen2 = true; else pi->pcie_gen2 = false; if (!pi->pcie_gen2) ni_pcie_performance_request(rdev, PCIE_PERF_REQ_PECI_GEN2, true); return 0; } static void ni_enable_bif_dynamic_pcie_gen2(struct radeon_device *rdev, bool enable) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); u32 tmp, bif; tmp = RREG32_PCIE_PORT(PCIE_LC_SPEED_CNTL); if ((tmp & LC_OTHER_SIDE_EVER_SENT_GEN2) && (tmp & LC_OTHER_SIDE_SUPPORTS_GEN2)) { if (enable) { if (!pi->boot_in_gen2) { bif = RREG32(CG_BIF_REQ_AND_RSP) & ~CG_CLIENT_REQ_MASK; bif |= CG_CLIENT_REQ(0xd); WREG32(CG_BIF_REQ_AND_RSP, bif); } tmp &= ~LC_HW_VOLTAGE_IF_CONTROL_MASK; tmp |= LC_HW_VOLTAGE_IF_CONTROL(1); tmp |= LC_GEN2_EN_STRAP; tmp |= LC_CLR_FAILED_SPD_CHANGE_CNT; WREG32_PCIE_PORT(PCIE_LC_SPEED_CNTL, tmp); udelay(10); tmp &= ~LC_CLR_FAILED_SPD_CHANGE_CNT; WREG32_PCIE_PORT(PCIE_LC_SPEED_CNTL, tmp); } else { if (!pi->boot_in_gen2) { bif = RREG32(CG_BIF_REQ_AND_RSP) & ~CG_CLIENT_REQ_MASK; bif |= CG_CLIENT_REQ(0xd); WREG32(CG_BIF_REQ_AND_RSP, bif); tmp &= ~LC_HW_VOLTAGE_IF_CONTROL_MASK; tmp &= ~LC_GEN2_EN_STRAP; } WREG32_PCIE_PORT(PCIE_LC_SPEED_CNTL, tmp); } } } static void ni_enable_dynamic_pcie_gen2(struct radeon_device *rdev, bool enable) { ni_enable_bif_dynamic_pcie_gen2(rdev, enable); if (enable) WREG32_P(GENERAL_PWRMGT, ENABLE_GEN2PCIE, ~ENABLE_GEN2PCIE); else WREG32_P(GENERAL_PWRMGT, 0, ~ENABLE_GEN2PCIE); } void ni_set_uvd_clock_before_set_eng_clock(struct radeon_device *rdev, struct radeon_ps *new_ps, struct radeon_ps *old_ps) { struct ni_ps *new_state = ni_get_ps(new_ps); struct ni_ps *current_state = ni_get_ps(old_ps); if ((new_ps->vclk == old_ps->vclk) && (new_ps->dclk == old_ps->dclk)) return; if (new_state->performance_levels[new_state->performance_level_count - 1].sclk >= current_state->performance_levels[current_state->performance_level_count - 1].sclk) return; radeon_set_uvd_clocks(rdev, new_ps->vclk, new_ps->dclk); } void ni_set_uvd_clock_after_set_eng_clock(struct radeon_device *rdev, struct radeon_ps *new_ps, struct radeon_ps *old_ps) { struct ni_ps *new_state = ni_get_ps(new_ps); struct ni_ps *current_state = ni_get_ps(old_ps); if ((new_ps->vclk == old_ps->vclk) && (new_ps->dclk == old_ps->dclk)) return; if (new_state->performance_levels[new_state->performance_level_count - 1].sclk < current_state->performance_levels[current_state->performance_level_count - 1].sclk) return; radeon_set_uvd_clocks(rdev, new_ps->vclk, new_ps->dclk); } void ni_dpm_setup_asic(struct radeon_device *rdev) { struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); int r; r = ni_mc_load_microcode(rdev); if (r) DRM_ERROR("Failed to load MC firmware!\n"); ni_read_clock_registers(rdev); btc_read_arb_registers(rdev); rv770_get_memory_type(rdev); if (eg_pi->pcie_performance_request) ni_advertise_gen2_capability(rdev); rv770_get_pcie_gen2_status(rdev); rv770_enable_acpi_pm(rdev); } void ni_update_current_ps(struct radeon_device *rdev, struct radeon_ps *rps) { struct ni_ps *new_ps = ni_get_ps(rps); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); eg_pi->current_rps = *rps; ni_pi->current_ps = *new_ps; eg_pi->current_rps.ps_priv = &ni_pi->current_ps; } void ni_update_requested_ps(struct radeon_device *rdev, struct radeon_ps *rps) { struct ni_ps *new_ps = ni_get_ps(rps); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_power_info *ni_pi = ni_get_pi(rdev); eg_pi->requested_rps = *rps; ni_pi->requested_ps = *new_ps; eg_pi->requested_rps.ps_priv = &ni_pi->requested_ps; } int ni_dpm_enable(struct radeon_device *rdev) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct radeon_ps *boot_ps = rdev->pm.dpm.boot_ps; int ret; if (pi->gfx_clock_gating) ni_cg_clockgating_default(rdev); if (btc_dpm_enabled(rdev)) return -EINVAL; if (pi->mg_clock_gating) ni_mg_clockgating_default(rdev); if (eg_pi->ls_clock_gating) ni_ls_clockgating_default(rdev); if (pi->voltage_control) { rv770_enable_voltage_control(rdev, true); ret = cypress_construct_voltage_tables(rdev); if (ret) { DRM_ERROR("cypress_construct_voltage_tables failed\n"); return ret; } } if (eg_pi->dynamic_ac_timing) { ret = ni_initialize_mc_reg_table(rdev); if (ret) eg_pi->dynamic_ac_timing = false; } if (pi->dynamic_ss) cypress_enable_spread_spectrum(rdev, true); if (pi->thermal_protection) rv770_enable_thermal_protection(rdev, true); rv770_setup_bsp(rdev); rv770_program_git(rdev); rv770_program_tp(rdev); rv770_program_tpp(rdev); rv770_program_sstp(rdev); cypress_enable_display_gap(rdev); rv770_program_vc(rdev); if (pi->dynamic_pcie_gen2) ni_enable_dynamic_pcie_gen2(rdev, true); ret = rv770_upload_firmware(rdev); if (ret) { DRM_ERROR("rv770_upload_firmware failed\n"); return ret; } ret = ni_process_firmware_header(rdev); if (ret) { DRM_ERROR("ni_process_firmware_header failed\n"); return ret; } ret = ni_initial_switch_from_arb_f0_to_f1(rdev); if (ret) { DRM_ERROR("ni_initial_switch_from_arb_f0_to_f1 failed\n"); return ret; } ret = ni_init_smc_table(rdev); if (ret) { DRM_ERROR("ni_init_smc_table failed\n"); return ret; } ret = ni_init_smc_spll_table(rdev); if (ret) { DRM_ERROR("ni_init_smc_spll_table failed\n"); return ret; } ret = ni_init_arb_table_index(rdev); if (ret) { DRM_ERROR("ni_init_arb_table_index failed\n"); return ret; } if (eg_pi->dynamic_ac_timing) { ret = ni_populate_mc_reg_table(rdev, boot_ps); if (ret) { DRM_ERROR("ni_populate_mc_reg_table failed\n"); return ret; } } ret = ni_initialize_smc_cac_tables(rdev); if (ret) { DRM_ERROR("ni_initialize_smc_cac_tables failed\n"); return ret; } ret = ni_initialize_hardware_cac_manager(rdev); if (ret) { DRM_ERROR("ni_initialize_hardware_cac_manager failed\n"); return ret; } ret = ni_populate_smc_tdp_limits(rdev, boot_ps); if (ret) { DRM_ERROR("ni_populate_smc_tdp_limits failed\n"); return ret; } ni_program_response_times(rdev); r7xx_start_smc(rdev); ret = cypress_notify_smc_display_change(rdev, false); if (ret) { DRM_ERROR("cypress_notify_smc_display_change failed\n"); return ret; } cypress_enable_sclk_control(rdev, true); if (eg_pi->memory_transition) cypress_enable_mclk_control(rdev, true); cypress_start_dpm(rdev); if (pi->gfx_clock_gating) ni_gfx_clockgating_enable(rdev, true); if (pi->mg_clock_gating) ni_mg_clockgating_enable(rdev, true); if (eg_pi->ls_clock_gating) ni_ls_clockgating_enable(rdev, true); rv770_enable_auto_throttle_source(rdev, RADEON_DPM_AUTO_THROTTLE_SRC_THERMAL, true); ni_update_current_ps(rdev, boot_ps); return 0; } void ni_dpm_disable(struct radeon_device *rdev) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct radeon_ps *boot_ps = rdev->pm.dpm.boot_ps; if (!btc_dpm_enabled(rdev)) return; rv770_clear_vc(rdev); if (pi->thermal_protection) rv770_enable_thermal_protection(rdev, false); ni_enable_power_containment(rdev, boot_ps, false); ni_enable_smc_cac(rdev, boot_ps, false); cypress_enable_spread_spectrum(rdev, false); rv770_enable_auto_throttle_source(rdev, RADEON_DPM_AUTO_THROTTLE_SRC_THERMAL, false); if (pi->dynamic_pcie_gen2) ni_enable_dynamic_pcie_gen2(rdev, false); if (rdev->irq.installed && r600_is_internal_thermal_sensor(rdev->pm.int_thermal_type)) { rdev->irq.dpm_thermal = false; radeon_irq_set(rdev); } if (pi->gfx_clock_gating) ni_gfx_clockgating_enable(rdev, false); if (pi->mg_clock_gating) ni_mg_clockgating_enable(rdev, false); if (eg_pi->ls_clock_gating) ni_ls_clockgating_enable(rdev, false); ni_stop_dpm(rdev); btc_reset_to_default(rdev); ni_stop_smc(rdev); ni_force_switch_to_arb_f0(rdev); ni_update_current_ps(rdev, boot_ps); } static int ni_power_control_set_level(struct radeon_device *rdev) { struct radeon_ps *new_ps = rdev->pm.dpm.requested_ps; int ret; ret = ni_restrict_performance_levels_before_switch(rdev); if (ret) return ret; ret = rv770_halt_smc(rdev); if (ret) return ret; ret = ni_populate_smc_tdp_limits(rdev, new_ps); if (ret) return ret; ret = rv770_resume_smc(rdev); if (ret) return ret; ret = rv770_set_sw_state(rdev); if (ret) return ret; return 0; } int ni_dpm_pre_set_power_state(struct radeon_device *rdev) { struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct radeon_ps requested_ps = *rdev->pm.dpm.requested_ps; struct radeon_ps *new_ps = &requested_ps; ni_update_requested_ps(rdev, new_ps); ni_apply_state_adjust_rules(rdev, &eg_pi->requested_rps); return 0; } int ni_dpm_set_power_state(struct radeon_device *rdev) { struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct radeon_ps *new_ps = &eg_pi->requested_rps; struct radeon_ps *old_ps = &eg_pi->current_rps; int ret; ret = ni_restrict_performance_levels_before_switch(rdev); if (ret) { DRM_ERROR("ni_restrict_performance_levels_before_switch failed\n"); return ret; } ni_set_uvd_clock_before_set_eng_clock(rdev, new_ps, old_ps); ret = ni_enable_power_containment(rdev, new_ps, false); if (ret) { DRM_ERROR("ni_enable_power_containment failed\n"); return ret; } ret = ni_enable_smc_cac(rdev, new_ps, false); if (ret) { DRM_ERROR("ni_enable_smc_cac failed\n"); return ret; } ret = rv770_halt_smc(rdev); if (ret) { DRM_ERROR("rv770_halt_smc failed\n"); return ret; } if (eg_pi->smu_uvd_hs) btc_notify_uvd_to_smc(rdev, new_ps); ret = ni_upload_sw_state(rdev, new_ps); if (ret) { DRM_ERROR("ni_upload_sw_state failed\n"); return ret; } if (eg_pi->dynamic_ac_timing) { ret = ni_upload_mc_reg_table(rdev, new_ps); if (ret) { DRM_ERROR("ni_upload_mc_reg_table failed\n"); return ret; } } ret = ni_program_memory_timing_parameters(rdev, new_ps); if (ret) { DRM_ERROR("ni_program_memory_timing_parameters failed\n"); return ret; } ret = rv770_resume_smc(rdev); if (ret) { DRM_ERROR("rv770_resume_smc failed\n"); return ret; } ret = rv770_set_sw_state(rdev); if (ret) { DRM_ERROR("rv770_set_sw_state failed\n"); return ret; } ni_set_uvd_clock_after_set_eng_clock(rdev, new_ps, old_ps); ret = ni_enable_smc_cac(rdev, new_ps, true); if (ret) { DRM_ERROR("ni_enable_smc_cac failed\n"); return ret; } ret = ni_enable_power_containment(rdev, new_ps, true); if (ret) { DRM_ERROR("ni_enable_power_containment failed\n"); return ret; } /* update tdp */ ret = ni_power_control_set_level(rdev); if (ret) { DRM_ERROR("ni_power_control_set_level failed\n"); return ret; } return 0; } void ni_dpm_post_set_power_state(struct radeon_device *rdev) { struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct radeon_ps *new_ps = &eg_pi->requested_rps; ni_update_current_ps(rdev, new_ps); } void ni_dpm_reset_asic(struct radeon_device *rdev) { ni_restrict_performance_levels_before_switch(rdev); rv770_set_boot_state(rdev); } union power_info { struct _ATOM_POWERPLAY_INFO info; struct _ATOM_POWERPLAY_INFO_V2 info_2; struct _ATOM_POWERPLAY_INFO_V3 info_3; struct _ATOM_PPLIB_POWERPLAYTABLE pplib; struct _ATOM_PPLIB_POWERPLAYTABLE2 pplib2; struct _ATOM_PPLIB_POWERPLAYTABLE3 pplib3; }; union pplib_clock_info { struct _ATOM_PPLIB_R600_CLOCK_INFO r600; struct _ATOM_PPLIB_RS780_CLOCK_INFO rs780; struct _ATOM_PPLIB_EVERGREEN_CLOCK_INFO evergreen; struct _ATOM_PPLIB_SUMO_CLOCK_INFO sumo; }; union pplib_power_state { struct _ATOM_PPLIB_STATE v1; struct _ATOM_PPLIB_STATE_V2 v2; }; static void ni_parse_pplib_non_clock_info(struct radeon_device *rdev, struct radeon_ps *rps, struct _ATOM_PPLIB_NONCLOCK_INFO *non_clock_info, u8 table_rev) { rps->caps = le32_to_cpu(non_clock_info->ulCapsAndSettings); rps->class = le16_to_cpu(non_clock_info->usClassification); rps->class2 = le16_to_cpu(non_clock_info->usClassification2); if (ATOM_PPLIB_NONCLOCKINFO_VER1 < table_rev) { rps->vclk = le32_to_cpu(non_clock_info->ulVCLK); rps->dclk = le32_to_cpu(non_clock_info->ulDCLK); } else if (r600_is_uvd_state(rps->class, rps->class2)) { rps->vclk = RV770_DEFAULT_VCLK_FREQ; rps->dclk = RV770_DEFAULT_DCLK_FREQ; } else { rps->vclk = 0; rps->dclk = 0; } if (rps->class & ATOM_PPLIB_CLASSIFICATION_BOOT) rdev->pm.dpm.boot_ps = rps; if (rps->class & ATOM_PPLIB_CLASSIFICATION_UVDSTATE) rdev->pm.dpm.uvd_ps = rps; } static void ni_parse_pplib_clock_info(struct radeon_device *rdev, struct radeon_ps *rps, int index, union pplib_clock_info *clock_info) { struct rv7xx_power_info *pi = rv770_get_pi(rdev); struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_ps *ps = ni_get_ps(rps); struct rv7xx_pl *pl = &ps->performance_levels[index]; ps->performance_level_count = index + 1; pl->sclk = le16_to_cpu(clock_info->evergreen.usEngineClockLow); pl->sclk |= clock_info->evergreen.ucEngineClockHigh << 16; pl->mclk = le16_to_cpu(clock_info->evergreen.usMemoryClockLow); pl->mclk |= clock_info->evergreen.ucMemoryClockHigh << 16; pl->vddc = le16_to_cpu(clock_info->evergreen.usVDDC); pl->vddci = le16_to_cpu(clock_info->evergreen.usVDDCI); pl->flags = le32_to_cpu(clock_info->evergreen.ulFlags); /* patch up vddc if necessary */ if (pl->vddc == 0xff01) { if (pi->max_vddc) pl->vddc = pi->max_vddc; } if (rps->class & ATOM_PPLIB_CLASSIFICATION_ACPI) { pi->acpi_vddc = pl->vddc; eg_pi->acpi_vddci = pl->vddci; if (ps->performance_levels[0].flags & ATOM_PPLIB_R600_FLAGS_PCIEGEN2) pi->acpi_pcie_gen2 = true; else pi->acpi_pcie_gen2 = false; } if (rps->class2 & ATOM_PPLIB_CLASSIFICATION2_ULV) { eg_pi->ulv.supported = true; eg_pi->ulv.pl = pl; } if (pi->min_vddc_in_table > pl->vddc) pi->min_vddc_in_table = pl->vddc; if (pi->max_vddc_in_table < pl->vddc) pi->max_vddc_in_table = pl->vddc; /* patch up boot state */ if (rps->class & ATOM_PPLIB_CLASSIFICATION_BOOT) { u16 vddc, vddci, mvdd; radeon_atombios_get_default_voltages(rdev, &vddc, &vddci, &mvdd); pl->mclk = rdev->clock.default_mclk; pl->sclk = rdev->clock.default_sclk; pl->vddc = vddc; pl->vddci = vddci; } if ((rps->class & ATOM_PPLIB_CLASSIFICATION_UI_MASK) == ATOM_PPLIB_CLASSIFICATION_UI_PERFORMANCE) { rdev->pm.dpm.dyn_state.max_clock_voltage_on_ac.sclk = pl->sclk; rdev->pm.dpm.dyn_state.max_clock_voltage_on_ac.mclk = pl->mclk; rdev->pm.dpm.dyn_state.max_clock_voltage_on_ac.vddc = pl->vddc; rdev->pm.dpm.dyn_state.max_clock_voltage_on_ac.vddci = pl->vddci; } } static int ni_parse_power_table(struct radeon_device *rdev) { struct radeon_mode_info *mode_info = &rdev->mode_info; struct _ATOM_PPLIB_NONCLOCK_INFO *non_clock_info; union pplib_power_state *power_state; int i, j; union pplib_clock_info *clock_info; union power_info *power_info; int index = GetIndexIntoMasterTable(DATA, PowerPlayInfo); u16 data_offset; u8 frev, crev; struct ni_ps *ps; if (!atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset)) return -EINVAL; power_info = (union power_info *)(mode_info->atom_context->bios + data_offset); rdev->pm.dpm.ps = kzalloc(sizeof(struct radeon_ps) * power_info->pplib.ucNumStates, GFP_KERNEL); if (!rdev->pm.dpm.ps) return -ENOMEM; rdev->pm.dpm.platform_caps = le32_to_cpu(power_info->pplib.ulPlatformCaps); rdev->pm.dpm.backbias_response_time = le16_to_cpu(power_info->pplib.usBackbiasTime); rdev->pm.dpm.voltage_response_time = le16_to_cpu(power_info->pplib.usVoltageTime); for (i = 0; i < power_info->pplib.ucNumStates; i++) { power_state = (union pplib_power_state *) (mode_info->atom_context->bios + data_offset + le16_to_cpu(power_info->pplib.usStateArrayOffset) + i * power_info->pplib.ucStateEntrySize); non_clock_info = (struct _ATOM_PPLIB_NONCLOCK_INFO *) (mode_info->atom_context->bios + data_offset + le16_to_cpu(power_info->pplib.usNonClockInfoArrayOffset) + (power_state->v1.ucNonClockStateIndex * power_info->pplib.ucNonClockSize)); if (power_info->pplib.ucStateEntrySize - 1) { u8 *idx; ps = kzalloc(sizeof(struct ni_ps), GFP_KERNEL); if (ps == NULL) { kfree(rdev->pm.dpm.ps); return -ENOMEM; } rdev->pm.dpm.ps[i].ps_priv = ps; ni_parse_pplib_non_clock_info(rdev, &rdev->pm.dpm.ps[i], non_clock_info, power_info->pplib.ucNonClockSize); idx = (u8 *)&power_state->v1.ucClockStateIndices[0]; for (j = 0; j < (power_info->pplib.ucStateEntrySize - 1); j++) { clock_info = (union pplib_clock_info *) (mode_info->atom_context->bios + data_offset + le16_to_cpu(power_info->pplib.usClockInfoArrayOffset) + (idx[j] * power_info->pplib.ucClockInfoSize)); ni_parse_pplib_clock_info(rdev, &rdev->pm.dpm.ps[i], j, clock_info); } } } rdev->pm.dpm.num_ps = power_info->pplib.ucNumStates; return 0; } int ni_dpm_init(struct radeon_device *rdev) { struct rv7xx_power_info *pi; struct evergreen_power_info *eg_pi; struct ni_power_info *ni_pi; struct atom_clock_dividers dividers; int ret; ni_pi = kzalloc(sizeof(struct ni_power_info), GFP_KERNEL); if (ni_pi == NULL) return -ENOMEM; rdev->pm.dpm.priv = ni_pi; eg_pi = &ni_pi->eg; pi = &eg_pi->rv7xx; rv770_get_max_vddc(rdev); eg_pi->ulv.supported = false; pi->acpi_vddc = 0; eg_pi->acpi_vddci = 0; pi->min_vddc_in_table = 0; pi->max_vddc_in_table = 0; ret = ni_parse_power_table(rdev); if (ret) return ret; ret = r600_parse_extended_power_table(rdev); if (ret) return ret; rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.entries = kzalloc(4 * sizeof(struct radeon_clock_voltage_dependency_entry), GFP_KERNEL); if (!rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.entries) { r600_free_extended_power_table(rdev); return -ENOMEM; } rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.count = 4; rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.entries[0].clk = 0; rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.entries[0].v = 0; rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.entries[1].clk = 36000; rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.entries[1].v = 720; rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.entries[2].clk = 54000; rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.entries[2].v = 810; rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.entries[3].clk = 72000; rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.entries[3].v = 900; ni_patch_dependency_tables_based_on_leakage(rdev); if (rdev->pm.dpm.voltage_response_time == 0) rdev->pm.dpm.voltage_response_time = R600_VOLTAGERESPONSETIME_DFLT; if (rdev->pm.dpm.backbias_response_time == 0) rdev->pm.dpm.backbias_response_time = R600_BACKBIASRESPONSETIME_DFLT; ret = radeon_atom_get_clock_dividers(rdev, COMPUTE_ENGINE_PLL_PARAM, 0, false, &dividers); if (ret) pi->ref_div = dividers.ref_div + 1; else pi->ref_div = R600_REFERENCEDIVIDER_DFLT; pi->rlp = RV770_RLP_DFLT; pi->rmp = RV770_RMP_DFLT; pi->lhp = RV770_LHP_DFLT; pi->lmp = RV770_LMP_DFLT; eg_pi->ats[0].rlp = RV770_RLP_DFLT; eg_pi->ats[0].rmp = RV770_RMP_DFLT; eg_pi->ats[0].lhp = RV770_LHP_DFLT; eg_pi->ats[0].lmp = RV770_LMP_DFLT; eg_pi->ats[1].rlp = BTC_RLP_UVD_DFLT; eg_pi->ats[1].rmp = BTC_RMP_UVD_DFLT; eg_pi->ats[1].lhp = BTC_LHP_UVD_DFLT; eg_pi->ats[1].lmp = BTC_LMP_UVD_DFLT; eg_pi->smu_uvd_hs = true; if (rdev->pdev->device == 0x6707) { pi->mclk_strobe_mode_threshold = 55000; pi->mclk_edc_enable_threshold = 55000; eg_pi->mclk_edc_wr_enable_threshold = 55000; } else { pi->mclk_strobe_mode_threshold = 40000; pi->mclk_edc_enable_threshold = 40000; eg_pi->mclk_edc_wr_enable_threshold = 40000; } ni_pi->mclk_rtt_mode_threshold = eg_pi->mclk_edc_wr_enable_threshold; pi->voltage_control = radeon_atom_is_voltage_gpio(rdev, SET_VOLTAGE_TYPE_ASIC_VDDC, 0); pi->mvdd_control = radeon_atom_is_voltage_gpio(rdev, SET_VOLTAGE_TYPE_ASIC_MVDDC, 0); eg_pi->vddci_control = radeon_atom_is_voltage_gpio(rdev, SET_VOLTAGE_TYPE_ASIC_VDDCI, 0); rv770_get_engine_memory_ss(rdev); pi->asi = RV770_ASI_DFLT; pi->pasi = CYPRESS_HASI_DFLT; pi->vrc = CYPRESS_VRC_DFLT; pi->power_gating = false; pi->gfx_clock_gating = true; pi->mg_clock_gating = true; pi->mgcgtssm = true; eg_pi->ls_clock_gating = false; eg_pi->sclk_deep_sleep = false; pi->dynamic_pcie_gen2 = true; if (rdev->pm.int_thermal_type != THERMAL_TYPE_NONE) pi->thermal_protection = true; else pi->thermal_protection = false; pi->display_gap = true; pi->dcodt = true; pi->ulps = true; eg_pi->dynamic_ac_timing = true; eg_pi->abm = true; eg_pi->mcls = true; eg_pi->light_sleep = true; eg_pi->memory_transition = true; #if defined(CONFIG_ACPI) eg_pi->pcie_performance_request = radeon_acpi_is_pcie_performance_request_supported(rdev); #else eg_pi->pcie_performance_request = false; #endif eg_pi->dll_default_on = false; eg_pi->sclk_deep_sleep = false; pi->mclk_stutter_mode_threshold = 0; pi->sram_end = SMC_RAM_END; rdev->pm.dpm.dyn_state.mclk_sclk_ratio = 3; rdev->pm.dpm.dyn_state.vddc_vddci_delta = 200; rdev->pm.dpm.dyn_state.min_vddc_for_pcie_gen2 = 900; rdev->pm.dpm.dyn_state.valid_sclk_values.count = ARRAY_SIZE(btc_valid_sclk); rdev->pm.dpm.dyn_state.valid_sclk_values.values = btc_valid_sclk; rdev->pm.dpm.dyn_state.valid_mclk_values.count = 0; rdev->pm.dpm.dyn_state.valid_mclk_values.values = NULL; rdev->pm.dpm.dyn_state.sclk_mclk_delta = 12500; ni_pi->cac_data.leakage_coefficients.at = 516; ni_pi->cac_data.leakage_coefficients.bt = 18; ni_pi->cac_data.leakage_coefficients.av = 51; ni_pi->cac_data.leakage_coefficients.bv = 2957; switch (rdev->pdev->device) { case 0x6700: case 0x6701: case 0x6702: case 0x6703: case 0x6718: ni_pi->cac_weights = &cac_weights_cayman_xt; break; case 0x6705: case 0x6719: case 0x671D: case 0x671C: default: ni_pi->cac_weights = &cac_weights_cayman_pro; break; case 0x6704: case 0x6706: case 0x6707: case 0x6708: case 0x6709: ni_pi->cac_weights = &cac_weights_cayman_le; break; } if (ni_pi->cac_weights->enable_power_containment_by_default) { ni_pi->enable_power_containment = true; ni_pi->enable_cac = true; ni_pi->enable_sq_ramping = true; } else { ni_pi->enable_power_containment = false; ni_pi->enable_cac = false; ni_pi->enable_sq_ramping = false; } ni_pi->driver_calculate_cac_leakage = false; ni_pi->cac_configuration_required = true; if (ni_pi->cac_configuration_required) { ni_pi->support_cac_long_term_average = true; ni_pi->lta_window_size = ni_pi->cac_weights->l2_lta_window_size; ni_pi->lts_truncate = ni_pi->cac_weights->lts_truncate; } else { ni_pi->support_cac_long_term_average = false; ni_pi->lta_window_size = 0; ni_pi->lts_truncate = 0; } ni_pi->use_power_boost_limit = true; /* make sure dc limits are valid */ if ((rdev->pm.dpm.dyn_state.max_clock_voltage_on_dc.sclk == 0) || (rdev->pm.dpm.dyn_state.max_clock_voltage_on_dc.mclk == 0)) rdev->pm.dpm.dyn_state.max_clock_voltage_on_dc = rdev->pm.dpm.dyn_state.max_clock_voltage_on_ac; return 0; } void ni_dpm_fini(struct radeon_device *rdev) { int i; for (i = 0; i < rdev->pm.dpm.num_ps; i++) { kfree(rdev->pm.dpm.ps[i].ps_priv); } kfree(rdev->pm.dpm.ps); kfree(rdev->pm.dpm.priv); kfree(rdev->pm.dpm.dyn_state.vddc_dependency_on_dispclk.entries); r600_free_extended_power_table(rdev); } void ni_dpm_print_power_state(struct radeon_device *rdev, struct radeon_ps *rps) { struct ni_ps *ps = ni_get_ps(rps); struct rv7xx_pl *pl; int i; r600_dpm_print_class_info(rps->class, rps->class2); r600_dpm_print_cap_info(rps->caps); printk("\tuvd vclk: %d dclk: %d\n", rps->vclk, rps->dclk); for (i = 0; i < ps->performance_level_count; i++) { pl = &ps->performance_levels[i]; if (rdev->family >= CHIP_TAHITI) printk("\t\tpower level %d sclk: %u mclk: %u vddc: %u vddci: %u pcie gen: %u\n", i, pl->sclk, pl->mclk, pl->vddc, pl->vddci, pl->pcie_gen + 1); else printk("\t\tpower level %d sclk: %u mclk: %u vddc: %u vddci: %u\n", i, pl->sclk, pl->mclk, pl->vddc, pl->vddci); } r600_dpm_print_ps_status(rdev, rps); } void ni_dpm_debugfs_print_current_performance_level(struct radeon_device *rdev, struct seq_file *m) { struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct radeon_ps *rps = &eg_pi->current_rps; struct ni_ps *ps = ni_get_ps(rps); struct rv7xx_pl *pl; u32 current_index = (RREG32(TARGET_AND_CURRENT_PROFILE_INDEX) & CURRENT_STATE_INDEX_MASK) >> CURRENT_STATE_INDEX_SHIFT; if (current_index >= ps->performance_level_count) { seq_printf(m, "invalid dpm profile %d\n", current_index); } else { pl = &ps->performance_levels[current_index]; seq_printf(m, "uvd vclk: %d dclk: %d\n", rps->vclk, rps->dclk); seq_printf(m, "power level %d sclk: %u mclk: %u vddc: %u vddci: %u\n", current_index, pl->sclk, pl->mclk, pl->vddc, pl->vddci); } } u32 ni_dpm_get_sclk(struct radeon_device *rdev, bool low) { struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_ps *requested_state = ni_get_ps(&eg_pi->requested_rps); if (low) return requested_state->performance_levels[0].sclk; else return requested_state->performance_levels[requested_state->performance_level_count - 1].sclk; } u32 ni_dpm_get_mclk(struct radeon_device *rdev, bool low) { struct evergreen_power_info *eg_pi = evergreen_get_pi(rdev); struct ni_ps *requested_state = ni_get_ps(&eg_pi->requested_rps); if (low) return requested_state->performance_levels[0].mclk; else return requested_state->performance_levels[requested_state->performance_level_count - 1].mclk; }
maoze/linux-3-14-for-arm
linux-3.14/drivers/gpu/drm/radeon/ni_dpm.c
C
gpl-3.0
133,021
// Type definitions for Facebook Javascript SDK // Project: https://developers.facebook.com/docs/javascript // Definitions by: Joshua Strobl <https://github.com/JoshStrobl> // Definitions: https://github.com/borisyankov/DefinitelyTyped interface FBInitParams{ appId?: string; authResponse?: string; cookie?: boolean; frictionlessRequests?: boolean; hideFlashCallback?: Function; logging?: boolean; status?: boolean; version?: string; xfbml?: boolean; } interface ShareDialogParams { method: string; // "share" href: string; } interface PageTabDialogParams { method: string; // "pagetab" app_id: string; redirect_uri?: string; display?: any; } interface RequestsDialogParams { method: string; // "apprequests" app_id: string; redirect_uri?: string; to?: string; message: string; action_type?: string; // "send" | "askfor" | "turn" object_id?: string; filters: string /* "app_users" | "app_non_users" */ | { name: string; user_ids: string[]; }; suggestions?: string[]; exclude_ids?: string[]; max_recipients?: number; data?: string; title?: string; } interface SendDialogParams { method: string; // "send" app_id: string; redirect_uri?: string; display?: any; to?: string; link: string; } interface PayDialogParams { method: string; // "pay" action: string; // "purchaseitem" product: string; quantity?: number; quantity_min?: number; quantity_max?: number; request_id?: string; pricepoint_id?: string; test_currency?: string; } declare type FBUIParams = ShareDialogParams | PageTabDialogParams | RequestsDialogParams | SendDialogParams | PayDialogParams; interface FBLoginOptions{ auth_type?: string; scope?: string; return_scopes?: boolean; enable_profile_selector?: boolean; profile_selector_ids?: string; } interface FBSDKEvents{ /* This method allows you to subscribe to a range of events, and define callback functions for when they fire. */ subscribe(event : string, callback : (fbResponseObject : Object) => any) : void; /* This method allows you to un-subscribe a callback from any events previously subscribed to using .Event.subscribe(). */ unsubscribe(event : string, callback : (fbResponseObject : Object) => any) : void; } interface FBSDKXFBML{ /* This function parses and renders XFBML markup in a document on the fly. */ parse(ParseElement?: Element) : void; parse(ParseElement?: HTMLElement) : void; } interface FBSDKCanvasPrefetcher{ /* Tells Facebook that the current page uses a specified resource. */ addStaticResource(res : string) : void; /* Controls how statistics are collected on resources used by your application. */ setCollectionMode(option : string) : void; } interface FBSDKCanvasSize{ height?: Number; width?: Number; } interface FBSDKCanvasDoneLoading{ time_delta_ms : Number; } interface FBSDKCanvas{ Prefetcher : FBSDKCanvasPrefetcher; /* Hides the HTML element passed in via the elem param from view. */ hideFlashElement(element : Element) : void; hideFlashElement(element : HTMLElement) : void; /* Displays the HTML element passed in via the elem param, after it has been hidden via FB.Canvas.hideFlashElement. */ showFlashElement(element : Element) : void; showFlashElement(element : HTMLElement) : void; /* Tells Facebook to scroll to a specific location of your canvas page. */ scrollTo(x : Number, y : Number) : void; /* Starts or stops a timer which will grow your iframe to fit the content every few milliseconds. */ setAutoGrow(stopTimer : boolean) : void; setAutoGrow(diffInterval : Number) : void; setAutoGrow(stopTimer : boolean, diffInterval : Number) : void /* Tells Facebook to resize your iframe. */ setSize(canvasSizeOptions : FBSDKCanvasSize) : void; /* Registers the callback for inline processing (i.e. without page reload) of user actions when they click on any link to the current app from Canvas */ setUrlHandler(handler?: Function) : string; /* Calls you back with an integer, in milliseconds, of the timing of the page load, beginning from the time when the first bytes arrive on the client, and ending from the point at which you call this function. */ setDoneLoading(handler?: Function) : FBSDKCanvasDoneLoading; /* Call startTimer to resume the timer after a period of time for the page load that you didn't wish to measure, which you began by calling stopTimer. */ startTimer() : void; /* Call stopTimer when you wish to stop timing the page load for a period of time */ stopTimer(handler?: (fbResponseObject : Object) => any) : void; } interface FBSDK{ /* This method is used to initialize and setup the SDK. */ init(fbInitObject : FBInitParams) : void; /* This method lets you make calls to the Graph API. */ api(path : string, method : string, callback : (fbResponseObject : Object) => any) : Object; api(path : string, params : Object, callback : (fbResponseObject : Object) => any) : Object; api(path : string, method : string, params : Object, callback : (fbResponseObject : Object) => any) : Object; /* This method is used to trigger different forms of Facebook created UI dialogs. */ ui(params : FBUIParams, handler : (fbResponseObject : Object) => any) : void; /* Allows you to determine if a user is logged in to Facebook and has authenticated your app */ getLoginStatus(handler : Function, force?: Boolean) : void; /* Calling FB.login prompts the user to authenticate your application using the Login Dialog. */ login(handler : (fbResponseObject : Object) => any, params?: FBLoginOptions): void; /* Log the user out of your site and Facebook */ logout(handler : (fbResponseObject : Object) => any) : void; /* Synchronous accessor for the current authResponse. */ getAuthResponse() : Object; Event : FBSDKEvents; XFBML : FBSDKXFBML; Canvas : FBSDKCanvas; } interface Window{ fbAsyncInit() : any; } declare module "FB" { export = FB; } declare var FB : FBSDK;
zuohaocheng/DefinitelyTyped
fbsdk/fbsdk.d.ts
TypeScript
mit
6,322
#!/usr/bin/perl # Check for malloc calls not shortly followed by initialisation. # # Known limitations: # - false negative: can't see allocations spanning more than one line # - possible false negatives, see patterns # - false positive: malloc-malloc-init-init is not accepted # - false positives: "non-standard" init functions (eg, the things being # initialised is not the first arg, or initialise struct members) # # Since false positives are expected, the results must be manually reviewed. # # Typical usage: scripts/malloc-init.pl library/*.c use warnings; use strict; use utf8; use open qw(:std utf8); my $limit = 7; my $inits = qr/memset|memcpy|_init|fread|base64_..code/; # cases to bear in mind: # # 0. foo = malloc(...); memset( foo, ... ); # 1. *foo = malloc(...); memset( *foo, ... ); # 2. type *foo = malloc(...); memset( foo, ...); # 3. foo = malloc(...); foo_init( (type *) foo ); # 4. foo = malloc(...); for(i=0..n) { init( &foo[i] ); } # # The chosen patterns are a bit relaxed, but unlikely to cause false positives # in real code (initialising *foo or &foo instead of foo will likely be caught # by functional tests). # my $id = qr/([a-zA-Z-0-9_\->\.]*)/; my $prefix = qr/\s(?:\*?|\&?|\([a-z_]* \*\))\s*/; my $name; my $line; my @bad; die "Usage: $0 file.c [...]\n" unless @ARGV; while (my $file = shift @ARGV) { open my $fh, "<", $file or die "read $file failed: $!\n"; while (<$fh>) { if( /mbedtls_malloc\(/ ) { if( /$id\s*=.*mbedtls_malloc\(/ ) { push @bad, "$file:$line:$name" if $name; $name = $1; $line = $.; } else { push @bad, "$file:$.:???" unless /return mbedtls_malloc/; } } elsif( $name && /(?:$inits)\($prefix\Q$name\E\b/ ) { undef $name; } elsif( $name && $. - $line > $limit ) { push @bad, "$file:$line:$name"; undef $name; undef $line; } } close $fh or die; } print "$_\n" for @bad;
ccw808/mtasa-blue
vendor/mbedtls/scripts/malloc-init.pl
Perl
gpl-3.0
2,028
# ***************************************************************************** # * Copyright (c) 2004, 2008 IBM Corporation # * All rights reserved. # * This program and the accompanying materials # * are made available under the terms of the BSD License # * which accompanies this distribution, and is available at # * http://www.opensource.org/licenses/bsd-license.php # * # * Contributors: # * IBM Corporation - initial implementation # ****************************************************************************/ ifndef TOP TOP = $(shell while ! test -e make.rules; do cd .. ; done; pwd) export TOP endif include $(TOP)/make.rules CFLAGS += -I../ ifeq ($(SNK_USE_MTFTP), 1) CFLAGS += -DUSE_MTFTP endif OBJS = ethernet.o ipv4.o udp.o tcp.o dns.o bootp.o \ dhcp.o ifeq ($(SNK_USE_MTFTP), 1) OBJS += mtftp.o else OBJS += tftp.o endif all: netlib.o netlib.o: $(OBJS) $(LD) $(LDFLAGS) $^ -o $@ -r clean: $(RM) -f *.o *.a *.i include $(TOP)/make.depend
KernelAnalysisPlatform/KlareDbg
tracers/qemu/decaf/roms/SLOF/clients/net-snk/app/netlib/Makefile
Makefile
gpl-3.0
984
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package generators import ( "fmt" "path/filepath" "strings" "k8s.io/gengo/args" "k8s.io/gengo/generator" "k8s.io/gengo/namer" "k8s.io/gengo/types" clientgentypes "k8s.io/kubernetes/cmd/libs/go2idl/client-gen/types" "github.com/golang/glog" ) // NameSystems returns the name system used by the generators in this package. func NameSystems() namer.NameSystems { pluralExceptions := map[string]string{ "Endpoints": "Endpoints", } return namer.NameSystems{ "public": namer.NewPublicNamer(0), "private": namer.NewPrivateNamer(0), "raw": namer.NewRawNamer("", nil), "publicPlural": namer.NewPublicPluralNamer(pluralExceptions), "allLowercasePlural": namer.NewAllLowercasePluralNamer(pluralExceptions), "lowercaseSingular": &lowercaseSingularNamer{}, } } // lowercaseSingularNamer implements Namer type lowercaseSingularNamer struct{} // Name returns t's name in all lowercase. func (n *lowercaseSingularNamer) Name(t *types.Type) string { return strings.ToLower(t.Name.Name) } // DefaultNameSystem returns the default name system for ordering the types to be // processed by the generators in this package. func DefaultNameSystem() string { return "public" } // generatedBy returns information about the arguments used to invoke // lister-gen. func generatedBy() string { return fmt.Sprintf("\n// This file was automatically generated by informer-gen\n\n") } // objectMetaForPackage returns the type of ObjectMeta used by package p. func objectMetaForPackage(p *types.Package) (*types.Type, bool, error) { generatingForPackage := false for _, t := range p.Types { // filter out types which dont have genclient=true. if extractBoolTagOrDie("genclient", t.SecondClosestCommentLines) == false { continue } generatingForPackage = true for _, member := range t.Members { if member.Name == "ObjectMeta" { return member.Type, isInternal(member), nil } } } if generatingForPackage { return nil, false, fmt.Errorf("unable to find ObjectMeta for any types in package %s", p.Path) } return nil, false, nil } // isInternal returns true if the tags for a member do not contain a json tag func isInternal(m types.Member) bool { return !strings.Contains(m.Tags, "json") } func packageForGroup(base string, group clientgentypes.Group) string { return filepath.Join(base, group.NonEmpty()) } func packageForInternalInterfaces(base string) string { return filepath.Join(base, "internalinterfaces") } // Packages makes the client package definition. func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages { boilerplate, err := arguments.LoadGoBoilerplate() if err != nil { glog.Fatalf("Failed loading boilerplate: %v", err) } boilerplate = append(boilerplate, []byte(generatedBy())...) customArgs, ok := arguments.CustomArgs.(*CustomArgs) if !ok { glog.Fatalf("Wrong CustomArgs type: %T", arguments.CustomArgs) } internalVersionPackagePath := filepath.Join(arguments.OutputPackagePath, "internalversion") externalVersionPackagePath := filepath.Join(arguments.OutputPackagePath, "externalversions") var packageList generator.Packages typesForGroupVersion := make(map[clientgentypes.GroupVersion][]*types.Type) externalGroupVersions := make(map[string]clientgentypes.GroupVersions) internalGroupVersions := make(map[string]clientgentypes.GroupVersions) for _, inputDir := range arguments.InputDirs { p := context.Universe.Package(inputDir) objectMeta, internal, err := objectMetaForPackage(p) if err != nil { glog.Fatal(err) } if objectMeta == nil { // no types in this package had genclient continue } var gv clientgentypes.GroupVersion var targetGroupVersions map[string]clientgentypes.GroupVersions if internal { lastSlash := strings.LastIndex(p.Path, "/") if lastSlash == -1 { glog.Fatalf("error constructing internal group version for package %q", p.Path) } gv.Group = clientgentypes.Group(p.Path[lastSlash+1:]) targetGroupVersions = internalGroupVersions } else { parts := strings.Split(p.Path, "/") gv.Group = clientgentypes.Group(parts[len(parts)-2]) gv.Version = clientgentypes.Version(parts[len(parts)-1]) targetGroupVersions = externalGroupVersions } var typesToGenerate []*types.Type for _, t := range p.Types { // filter out types which dont have genclient=true. if extractBoolTagOrDie("genclient", t.SecondClosestCommentLines) == false { continue } // filter out types which have noMethods if extractBoolTagOrDie("noMethods", t.SecondClosestCommentLines) == true { continue } typesToGenerate = append(typesToGenerate, t) if _, ok := typesForGroupVersion[gv]; !ok { typesForGroupVersion[gv] = []*types.Type{} } typesForGroupVersion[gv] = append(typesForGroupVersion[gv], t) } if len(typesToGenerate) == 0 { continue } icGroupName := namer.IC(gv.Group.NonEmpty()) groupVersionsEntry, ok := targetGroupVersions[icGroupName] if !ok { groupVersionsEntry = clientgentypes.GroupVersions{ Group: gv.Group, } } groupVersionsEntry.Versions = append(groupVersionsEntry.Versions, gv.Version) targetGroupVersions[icGroupName] = groupVersionsEntry orderer := namer.Orderer{Namer: namer.NewPrivateNamer(0)} typesToGenerate = orderer.OrderTypes(typesToGenerate) if internal { packageList = append(packageList, versionPackage(internalVersionPackagePath, gv, boilerplate, typesToGenerate, customArgs.InternalClientSetPackage, customArgs.ListersPackage)) } else { packageList = append(packageList, versionPackage(externalVersionPackagePath, gv, boilerplate, typesToGenerate, customArgs.VersionedClientSetPackage, customArgs.ListersPackage)) } } packageList = append(packageList, factoryInterfacePackage(externalVersionPackagePath, boilerplate, customArgs.VersionedClientSetPackage, typesForGroupVersion)) packageList = append(packageList, factoryPackage(externalVersionPackagePath, boilerplate, externalGroupVersions, customArgs.VersionedClientSetPackage, typesForGroupVersion)) for _, groupVersionsEntry := range externalGroupVersions { packageList = append(packageList, groupPackage(externalVersionPackagePath, groupVersionsEntry, boilerplate)) } packageList = append(packageList, factoryInterfacePackage(internalVersionPackagePath, boilerplate, customArgs.InternalClientSetPackage, typesForGroupVersion)) packageList = append(packageList, factoryPackage(internalVersionPackagePath, boilerplate, internalGroupVersions, customArgs.InternalClientSetPackage, typesForGroupVersion)) for _, groupVersionsEntry := range internalGroupVersions { packageList = append(packageList, groupPackage(internalVersionPackagePath, groupVersionsEntry, boilerplate)) } return packageList } func isInternalVersion(gv clientgentypes.GroupVersion) bool { return len(gv.Version) == 0 } func factoryPackage(basePackage string, boilerplate []byte, groupVersions map[string]clientgentypes.GroupVersions, clientSetPackage string, typesForGroupVersion map[clientgentypes.GroupVersion][]*types.Type) generator.Package { return &generator.DefaultPackage{ PackageName: filepath.Base(basePackage), PackagePath: basePackage, HeaderText: boilerplate, GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) { generators = append(generators, &factoryGenerator{ DefaultGen: generator.DefaultGen{ OptionalName: "factory", }, outputPackage: basePackage, imports: generator.NewImportTracker(), groupVersions: groupVersions, clientSetPackage: clientSetPackage, internalInterfacesPackage: packageForInternalInterfaces(basePackage), }) generators = append(generators, &genericGenerator{ DefaultGen: generator.DefaultGen{ OptionalName: "generic", }, outputPackage: basePackage, imports: generator.NewImportTracker(), groupVersions: groupVersions, typesForGroupVersion: typesForGroupVersion, }) return generators }, } } func factoryInterfacePackage(basePackage string, boilerplate []byte, clientSetPackage string, typesForGroupVersion map[clientgentypes.GroupVersion][]*types.Type) generator.Package { packagePath := packageForInternalInterfaces(basePackage) return &generator.DefaultPackage{ PackageName: filepath.Base(packagePath), PackagePath: packagePath, HeaderText: boilerplate, GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) { generators = append(generators, &factoryInterfaceGenerator{ DefaultGen: generator.DefaultGen{ OptionalName: "factory_interfaces", }, outputPackage: packagePath, imports: generator.NewImportTracker(), clientSetPackage: clientSetPackage, }) return generators }, } } func groupPackage(basePackage string, groupVersions clientgentypes.GroupVersions, boilerplate []byte) generator.Package { packagePath := filepath.Join(basePackage, strings.ToLower(groupVersions.Group.NonEmpty())) return &generator.DefaultPackage{ PackageName: strings.ToLower(groupVersions.Group.NonEmpty()), PackagePath: packagePath, HeaderText: boilerplate, GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) { generators = append(generators, &groupInterfaceGenerator{ DefaultGen: generator.DefaultGen{ OptionalName: "interface", }, outputPackage: packagePath, groupVersions: groupVersions, imports: generator.NewImportTracker(), internalInterfacesPackage: packageForInternalInterfaces(basePackage), }) return generators }, FilterFunc: func(c *generator.Context, t *types.Type) bool { // piggy-back on types that are tagged for client-gen return extractBoolTagOrDie("genclient", t.SecondClosestCommentLines) == true }, } } func versionPackage(basePackage string, gv clientgentypes.GroupVersion, boilerplate []byte, typesToGenerate []*types.Type, clientSetPackage, listersPackage string) generator.Package { packagePath := filepath.Join(basePackage, strings.ToLower(gv.Group.NonEmpty()), strings.ToLower(gv.Version.NonEmpty())) return &generator.DefaultPackage{ PackageName: strings.ToLower(gv.Version.NonEmpty()), PackagePath: packagePath, HeaderText: boilerplate, GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) { generators = append(generators, &versionInterfaceGenerator{ DefaultGen: generator.DefaultGen{ OptionalName: "interface", }, outputPackage: packagePath, imports: generator.NewImportTracker(), types: typesToGenerate, internalInterfacesPackage: packageForInternalInterfaces(basePackage), }) for _, t := range typesToGenerate { generators = append(generators, &informerGenerator{ DefaultGen: generator.DefaultGen{ OptionalName: strings.ToLower(t.Name.Name), }, outputPackage: packagePath, groupVersion: gv, typeToGenerate: t, imports: generator.NewImportTracker(), clientSetPackage: clientSetPackage, listersPackage: listersPackage, internalInterfacesPackage: packageForInternalInterfaces(basePackage), }) } return generators }, FilterFunc: func(c *generator.Context, t *types.Type) bool { // piggy-back on types that are tagged for client-gen return extractBoolTagOrDie("genclient", t.SecondClosestCommentLines) == true }, } }
sp-borja-juncosa/kops
vendor/k8s.io/kubernetes/cmd/libs/go2idl/informer-gen/generators/packages.go
GO
apache-2.0
12,166
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package meta import ( "fmt" "reflect" "k8s.io/client-go/1.4/pkg/api/meta/metatypes" "k8s.io/client-go/1.4/pkg/api/unversioned" "k8s.io/client-go/1.4/pkg/conversion" "k8s.io/client-go/1.4/pkg/runtime" "k8s.io/client-go/1.4/pkg/types" "github.com/golang/glog" ) // errNotList is returned when an object implements the Object style interfaces but not the List style // interfaces. var errNotList = fmt.Errorf("object does not implement the List interfaces") // ListAccessor returns a List interface for the provided object or an error if the object does // not provide List. // IMPORTANT: Objects are a superset of lists, so all Objects return List metadata. Do not use this // check to determine whether an object *is* a List. // TODO: return bool instead of error func ListAccessor(obj interface{}) (List, error) { switch t := obj.(type) { case List: return t, nil case unversioned.List: return t, nil case ListMetaAccessor: if m := t.GetListMeta(); m != nil { return m, nil } return nil, errNotList case unversioned.ListMetaAccessor: if m := t.GetListMeta(); m != nil { return m, nil } return nil, errNotList case Object: return t, nil case ObjectMetaAccessor: if m := t.GetObjectMeta(); m != nil { return m, nil } return nil, errNotList default: return nil, errNotList } } // errNotObject is returned when an object implements the List style interfaces but not the Object style // interfaces. var errNotObject = fmt.Errorf("object does not implement the Object interfaces") // Accessor takes an arbitrary object pointer and returns meta.Interface. // obj must be a pointer to an API type. An error is returned if the minimum // required fields are missing. Fields that are not required return the default // value and are a no-op if set. // TODO: return bool instead of error func Accessor(obj interface{}) (Object, error) { switch t := obj.(type) { case Object: return t, nil case ObjectMetaAccessor: if m := t.GetObjectMeta(); m != nil { return m, nil } return nil, errNotObject case List, unversioned.List, ListMetaAccessor, unversioned.ListMetaAccessor: return nil, errNotObject default: return nil, errNotObject } } // TypeAccessor returns an interface that allows retrieving and modifying the APIVersion // and Kind of an in-memory internal object. // TODO: this interface is used to test code that does not have ObjectMeta or ListMeta // in round tripping (objects which can use apiVersion/kind, but do not fit the Kube // api conventions). func TypeAccessor(obj interface{}) (Type, error) { if typed, ok := obj.(runtime.Object); ok { return objectAccessor{typed}, nil } v, err := conversion.EnforcePtr(obj) if err != nil { return nil, err } t := v.Type() if v.Kind() != reflect.Struct { return nil, fmt.Errorf("expected struct, but got %v: %v (%#v)", v.Kind(), t, v.Interface()) } typeMeta := v.FieldByName("TypeMeta") if !typeMeta.IsValid() { return nil, fmt.Errorf("struct %v lacks embedded TypeMeta type", t) } a := &genericAccessor{} if err := extractFromTypeMeta(typeMeta, a); err != nil { return nil, fmt.Errorf("unable to find type fields on %#v: %v", typeMeta, err) } return a, nil } type objectAccessor struct { runtime.Object } func (obj objectAccessor) GetKind() string { return obj.GetObjectKind().GroupVersionKind().Kind } func (obj objectAccessor) SetKind(kind string) { gvk := obj.GetObjectKind().GroupVersionKind() gvk.Kind = kind obj.GetObjectKind().SetGroupVersionKind(gvk) } func (obj objectAccessor) GetAPIVersion() string { return obj.GetObjectKind().GroupVersionKind().GroupVersion().String() } func (obj objectAccessor) SetAPIVersion(version string) { gvk := obj.GetObjectKind().GroupVersionKind() gv, err := unversioned.ParseGroupVersion(version) if err != nil { gv = unversioned.GroupVersion{Version: version} } gvk.Group, gvk.Version = gv.Group, gv.Version obj.GetObjectKind().SetGroupVersionKind(gvk) } // NewAccessor returns a MetadataAccessor that can retrieve // or manipulate resource version on objects derived from core API // metadata concepts. func NewAccessor() MetadataAccessor { return resourceAccessor{} } // resourceAccessor implements ResourceVersioner and SelfLinker. type resourceAccessor struct{} func (resourceAccessor) Kind(obj runtime.Object) (string, error) { return objectAccessor{obj}.GetKind(), nil } func (resourceAccessor) SetKind(obj runtime.Object, kind string) error { objectAccessor{obj}.SetKind(kind) return nil } func (resourceAccessor) APIVersion(obj runtime.Object) (string, error) { return objectAccessor{obj}.GetAPIVersion(), nil } func (resourceAccessor) SetAPIVersion(obj runtime.Object, version string) error { objectAccessor{obj}.SetAPIVersion(version) return nil } func (resourceAccessor) Namespace(obj runtime.Object) (string, error) { accessor, err := Accessor(obj) if err != nil { return "", err } return accessor.GetNamespace(), nil } func (resourceAccessor) SetNamespace(obj runtime.Object, namespace string) error { accessor, err := Accessor(obj) if err != nil { return err } accessor.SetNamespace(namespace) return nil } func (resourceAccessor) Name(obj runtime.Object) (string, error) { accessor, err := Accessor(obj) if err != nil { return "", err } return accessor.GetName(), nil } func (resourceAccessor) SetName(obj runtime.Object, name string) error { accessor, err := Accessor(obj) if err != nil { return err } accessor.SetName(name) return nil } func (resourceAccessor) GenerateName(obj runtime.Object) (string, error) { accessor, err := Accessor(obj) if err != nil { return "", err } return accessor.GetGenerateName(), nil } func (resourceAccessor) SetGenerateName(obj runtime.Object, name string) error { accessor, err := Accessor(obj) if err != nil { return err } accessor.SetGenerateName(name) return nil } func (resourceAccessor) UID(obj runtime.Object) (types.UID, error) { accessor, err := Accessor(obj) if err != nil { return "", err } return accessor.GetUID(), nil } func (resourceAccessor) SetUID(obj runtime.Object, uid types.UID) error { accessor, err := Accessor(obj) if err != nil { return err } accessor.SetUID(uid) return nil } func (resourceAccessor) SelfLink(obj runtime.Object) (string, error) { accessor, err := ListAccessor(obj) if err != nil { return "", err } return accessor.GetSelfLink(), nil } func (resourceAccessor) SetSelfLink(obj runtime.Object, selfLink string) error { accessor, err := ListAccessor(obj) if err != nil { return err } accessor.SetSelfLink(selfLink) return nil } func (resourceAccessor) Labels(obj runtime.Object) (map[string]string, error) { accessor, err := Accessor(obj) if err != nil { return nil, err } return accessor.GetLabels(), nil } func (resourceAccessor) SetLabels(obj runtime.Object, labels map[string]string) error { accessor, err := Accessor(obj) if err != nil { return err } accessor.SetLabels(labels) return nil } func (resourceAccessor) Annotations(obj runtime.Object) (map[string]string, error) { accessor, err := Accessor(obj) if err != nil { return nil, err } return accessor.GetAnnotations(), nil } func (resourceAccessor) SetAnnotations(obj runtime.Object, annotations map[string]string) error { accessor, err := Accessor(obj) if err != nil { return err } accessor.SetAnnotations(annotations) return nil } func (resourceAccessor) ResourceVersion(obj runtime.Object) (string, error) { accessor, err := ListAccessor(obj) if err != nil { return "", err } return accessor.GetResourceVersion(), nil } func (resourceAccessor) SetResourceVersion(obj runtime.Object, version string) error { accessor, err := ListAccessor(obj) if err != nil { return err } accessor.SetResourceVersion(version) return nil } // extractFromOwnerReference extracts v to o. v is the OwnerReferences field of an object. func extractFromOwnerReference(v reflect.Value, o *metatypes.OwnerReference) error { if err := runtime.Field(v, "APIVersion", &o.APIVersion); err != nil { return err } if err := runtime.Field(v, "Kind", &o.Kind); err != nil { return err } if err := runtime.Field(v, "Name", &o.Name); err != nil { return err } if err := runtime.Field(v, "UID", &o.UID); err != nil { return err } var controllerPtr *bool if err := runtime.Field(v, "Controller", &controllerPtr); err != nil { return err } if controllerPtr != nil { controller := *controllerPtr o.Controller = &controller } return nil } // setOwnerReference sets v to o. v is the OwnerReferences field of an object. func setOwnerReference(v reflect.Value, o *metatypes.OwnerReference) error { if err := runtime.SetField(o.APIVersion, v, "APIVersion"); err != nil { return err } if err := runtime.SetField(o.Kind, v, "Kind"); err != nil { return err } if err := runtime.SetField(o.Name, v, "Name"); err != nil { return err } if err := runtime.SetField(o.UID, v, "UID"); err != nil { return err } if o.Controller != nil { controller := *(o.Controller) if err := runtime.SetField(&controller, v, "Controller"); err != nil { return err } } return nil } // genericAccessor contains pointers to strings that can modify an arbitrary // struct and implements the Accessor interface. type genericAccessor struct { namespace *string name *string generateName *string uid *types.UID apiVersion *string kind *string resourceVersion *string selfLink *string creationTimestamp *unversioned.Time deletionTimestamp **unversioned.Time labels *map[string]string annotations *map[string]string ownerReferences reflect.Value finalizers *[]string } func (a genericAccessor) GetNamespace() string { if a.namespace == nil { return "" } return *a.namespace } func (a genericAccessor) SetNamespace(namespace string) { if a.namespace == nil { return } *a.namespace = namespace } func (a genericAccessor) GetName() string { if a.name == nil { return "" } return *a.name } func (a genericAccessor) SetName(name string) { if a.name == nil { return } *a.name = name } func (a genericAccessor) GetGenerateName() string { if a.generateName == nil { return "" } return *a.generateName } func (a genericAccessor) SetGenerateName(generateName string) { if a.generateName == nil { return } *a.generateName = generateName } func (a genericAccessor) GetUID() types.UID { if a.uid == nil { return "" } return *a.uid } func (a genericAccessor) SetUID(uid types.UID) { if a.uid == nil { return } *a.uid = uid } func (a genericAccessor) GetAPIVersion() string { return *a.apiVersion } func (a genericAccessor) SetAPIVersion(version string) { *a.apiVersion = version } func (a genericAccessor) GetKind() string { return *a.kind } func (a genericAccessor) SetKind(kind string) { *a.kind = kind } func (a genericAccessor) GetResourceVersion() string { return *a.resourceVersion } func (a genericAccessor) SetResourceVersion(version string) { *a.resourceVersion = version } func (a genericAccessor) GetSelfLink() string { return *a.selfLink } func (a genericAccessor) SetSelfLink(selfLink string) { *a.selfLink = selfLink } func (a genericAccessor) GetCreationTimestamp() unversioned.Time { return *a.creationTimestamp } func (a genericAccessor) SetCreationTimestamp(timestamp unversioned.Time) { *a.creationTimestamp = timestamp } func (a genericAccessor) GetDeletionTimestamp() *unversioned.Time { return *a.deletionTimestamp } func (a genericAccessor) SetDeletionTimestamp(timestamp *unversioned.Time) { *a.deletionTimestamp = timestamp } func (a genericAccessor) GetLabels() map[string]string { if a.labels == nil { return nil } return *a.labels } func (a genericAccessor) SetLabels(labels map[string]string) { *a.labels = labels } func (a genericAccessor) GetAnnotations() map[string]string { if a.annotations == nil { return nil } return *a.annotations } func (a genericAccessor) SetAnnotations(annotations map[string]string) { if a.annotations == nil { emptyAnnotations := make(map[string]string) a.annotations = &emptyAnnotations } *a.annotations = annotations } func (a genericAccessor) GetFinalizers() []string { if a.finalizers == nil { return nil } return *a.finalizers } func (a genericAccessor) SetFinalizers(finalizers []string) { *a.finalizers = finalizers } func (a genericAccessor) GetOwnerReferences() []metatypes.OwnerReference { var ret []metatypes.OwnerReference s := a.ownerReferences if s.Kind() != reflect.Ptr || s.Elem().Kind() != reflect.Slice { glog.Errorf("expect %v to be a pointer to slice", s) return ret } s = s.Elem() // Set the capacity to one element greater to avoid copy if the caller later append an element. ret = make([]metatypes.OwnerReference, s.Len(), s.Len()+1) for i := 0; i < s.Len(); i++ { if err := extractFromOwnerReference(s.Index(i), &ret[i]); err != nil { glog.Errorf("extractFromOwnerReference failed: %v", err) return ret } } return ret } func (a genericAccessor) SetOwnerReferences(references []metatypes.OwnerReference) { s := a.ownerReferences if s.Kind() != reflect.Ptr || s.Elem().Kind() != reflect.Slice { glog.Errorf("expect %v to be a pointer to slice", s) } s = s.Elem() newReferences := reflect.MakeSlice(s.Type(), len(references), len(references)) for i := 0; i < len(references); i++ { if err := setOwnerReference(newReferences.Index(i), &references[i]); err != nil { glog.Errorf("setOwnerReference failed: %v", err) return } } s.Set(newReferences) } // extractFromTypeMeta extracts pointers to version and kind fields from an object func extractFromTypeMeta(v reflect.Value, a *genericAccessor) error { if err := runtime.FieldPtr(v, "APIVersion", &a.apiVersion); err != nil { return err } if err := runtime.FieldPtr(v, "Kind", &a.kind); err != nil { return err } return nil }
upmc-enterprises/emmie
vendor/k8s.io/client-go/1.4/pkg/api/meta/meta.go
GO
bsd-3-clause
14,552
"use strict"; var f = require('util').format , crypto = require('crypto') , Binary = require('bson').Binary , Query = require('../connection/commands').Query , MongoError = require('../error'); var AuthSession = function(db, username, password) { this.db = db; this.username = username; this.password = password; } AuthSession.prototype.equal = function(session) { return session.db == this.db && session.username == this.username && session.password == this.password; } /** * Creates a new Plain authentication mechanism * @class * @return {Plain} A cursor instance */ var Plain = function(bson) { this.bson = bson; this.authStore = []; } /** * Authenticate * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {string} db Name of the database * @param {string} username Username * @param {string} password Password * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ Plain.prototype.auth = function(server, connections, db, username, password, callback) { var self = this; // Total connections var count = connections.length; if(count == 0) return callback(null, null); // Valid connections var numberOfValidConnections = 0; var credentialsValid = false; var errorObject = null; // For each connection we need to authenticate while(connections.length > 0) { // Execute MongoCR var execute = function(connection) { // Create payload var payload = new Binary(f("\x00%s\x00%s", username, password)); // Let's start the sasl process var command = { saslStart: 1 , mechanism: 'PLAIN' , payload: payload , autoAuthorize: 1 }; // Let's start the process server(connection, new Query(self.bson, "$external.$cmd", command, { numberToSkip: 0, numberToReturn: 1 }).toBin(), function(err, r) { // server.command("$external.$cmd" // , command // , { connection: connection }, function(err, r) { // Adjust count count = count - 1; // If we have an error if(err) { errorObject = err; } else if(r.result['$err']) { errorObject = r.result; } else if(r.result['errmsg']) { errorObject = r.result; } else { credentialsValid = true; numberOfValidConnections = numberOfValidConnections + 1; } // We have authenticated all connections if(count == 0 && numberOfValidConnections > 0) { // Store the auth details addAuthSession(self.authStore, new AuthSession(db, username, password)); // Return correct authentication callback(null, true); } else if(count == 0) { if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); callback(errorObject, false); } }); } var _execute = function(_connection) { process.nextTick(function() { execute(_connection); }); } _execute(connections.shift()); } } // Add to store only if it does not exist var addAuthSession = function(authStore, session) { var found = false; for(var i = 0; i < authStore.length; i++) { if(authStore[i].equal(session)) { found = true; break; } } if(!found) authStore.push(session); } /** * Remove authStore credentials * @method * @param {string} db Name of database we are removing authStore details about * @return {object} */ Plain.prototype.logout = function(dbName) { this.authStore = this.authStore.filter(function(x) { return x.db != dbName; }); } /** * Re authenticate pool * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ Plain.prototype.reauthenticate = function(server, connections, callback) { var authStore = this.authStore.slice(0); var err = null; var count = authStore.length; if(count == 0) return callback(null, null); // Iterate over all the auth details stored for(var i = 0; i < authStore.length; i++) { this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err, r) { if(err) err = err; count = count - 1; // Done re-authenticating if(count == 0) { callback(err, null); } }); } } /** * This is a result from a authentication strategy * * @callback authResultCallback * @param {error} error An error object. Set to null if no error present * @param {boolean} result The result of the authentication process */ module.exports = Plain;
danieloostra/mean-charlie-workspace
steve/MEAN/Mongo/QuotingDojo/node_modules/mongodb-core/lib/auth/plain.js
JavaScript
unlicense
5,041
/* * * (C) COPYRIGHT 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 mali_kbase_js_affinity.h * Affinity Manager internal APIs. */ #ifndef _KBASE_JS_AFFINITY_H_ #define _KBASE_JS_AFFINITY_H_ /** * @addtogroup base_api * @{ */ /** * @addtogroup base_kbase_api * @{ */ /** * @addtogroup kbase_js_affinity Affinity Manager internal APIs. * @{ * */ /** * @brief Decide whether it is possible to submit a job to a particular job slot in the current status * * Will check if submitting to the given job slot is allowed in the current * status. For example using job slot 2 while in soft-stoppable state and only * having 1 coregroup is not allowed by the policy. This function should be * called prior to submitting a job to a slot to make sure policy rules are not * violated. * * The following locking conditions are made on the caller: * - it must hold kbasep_js_device_data::runpool_irq::lock * * @param kbdev The kbase device structure of the device * @param js Job slot number to check for allowance */ mali_bool kbase_js_can_run_job_on_slot_no_lock(struct kbase_device *kbdev, int js); /** * @brief Compute affinity for a given job. * * Currently assumes an all-on/all-off power management policy. * Also assumes there is at least one core with tiler available. * * Returns MALI_TRUE if a valid affinity was chosen, MALI_FALSE if * no cores were available. * * @param[out] affinity Affinity bitmap computed * @param kbdev The kbase device structure of the device * @param katom Job chain of which affinity is going to be found * @param js Slot the job chain is being submitted */ mali_bool kbase_js_choose_affinity(u64 * const affinity, struct kbase_device *kbdev, struct kbase_jd_atom *katom, int js); /** * @brief Determine whether a proposed \a affinity on job slot \a js would * cause a violation of affinity restrictions. * * The following locks must be held by the caller: * - kbasep_js_device_data::runpool_irq::lock */ mali_bool kbase_js_affinity_would_violate(struct kbase_device *kbdev, int js, u64 affinity); /** * @brief Affinity tracking: retain cores used by a slot * * The following locks must be held by the caller: * - kbasep_js_device_data::runpool_irq::lock */ void kbase_js_affinity_retain_slot_cores(struct kbase_device *kbdev, int js, u64 affinity); /** * @brief Affinity tracking: release cores used by a slot * * Cores \b must be released as soon as a job is dequeued from a slot's 'submit * slots', and before another job is submitted to those slots. Otherwise, the * refcount could exceed the maximum number submittable to a slot, * BASE_JM_SUBMIT_SLOTS. * * The following locks must be held by the caller: * - kbasep_js_device_data::runpool_irq::lock */ void kbase_js_affinity_release_slot_cores(struct kbase_device *kbdev, int js, u64 affinity); /** * @brief Register a slot as blocking atoms due to affinity violations * * Once a slot has been registered, we must check after every atom completion * (including those on different slots) to see if the slot can be * unblocked. This is done by calling * kbase_js_affinity_submit_to_blocked_slots(), which will also deregister the * slot if it no long blocks atoms due to affinity violations. * * The following locks must be held by the caller: * - kbasep_js_device_data::runpool_irq::lock */ void kbase_js_affinity_slot_blocked_an_atom(struct kbase_device *kbdev, int js); /** * @brief Submit to job slots that have registered that an atom was blocked on * the slot previously due to affinity violations. * * This submits to all slots registered by * kbase_js_affinity_slot_blocked_an_atom(). If submission succeeded, then the * slot is deregistered as having blocked atoms due to affinity * violations. Otherwise it stays registered, and the next atom to complete * must attempt to submit to the blocked slots again. * * This must only be called whilst the GPU is powered - for example, when * kbdev->jsdata.nr_user_contexts_running > 0. * * The following locking conditions are made on the caller: * - it must hold kbasep_js_device_data::runpool_mutex * - it must hold kbasep_js_device_data::runpool_irq::lock */ void kbase_js_affinity_submit_to_blocked_slots(struct kbase_device *kbdev); /** * @brief Output to the Trace log the current tracked affinities on all slots */ #if KBASE_TRACE_ENABLE void kbase_js_debug_log_current_affinities(struct kbase_device *kbdev); #else /* KBASE_TRACE_ENABLE */ static INLINE void kbase_js_debug_log_current_affinities(struct kbase_device *kbdev) { } #endif /* KBASE_TRACE_ENABLE */ /** @} *//* end group kbase_js_affinity */ /** @} *//* end group base_kbase_api */ /** @} *//* end group base_api */ #endif /* _KBASE_JS_AFFINITY_H_ */
s20121035/rk3288_android5.1_repo
kernel/drivers/gpu/arm/midgard/mali_kbase_js_affinity.h
C
gpl-3.0
5,247
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2009 IITP RAS * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Pavel Boyko <[email protected]> */ #include "ns3/test.h" #include "ns3/mesh-information-element-vector.h" // All information elements: #include "ns3/ie-dot11s-beacon-timing.h" #include "ns3/ie-dot11s-configuration.h" #include "ns3/ie-dot11s-id.h" #include "ns3/ie-dot11s-metric-report.h" #include "ns3/ie-dot11s-peer-management.h" #include "ns3/ie-dot11s-peering-protocol.h" #include "ns3/ie-dot11s-perr.h" #include "ns3/ie-dot11s-prep.h" #include "ns3/ie-dot11s-preq.h" #include "ns3/ie-dot11s-rann.h" using namespace ns3; // Unit tests //----------------------------------------------------------------------------- /// Built-in self test for MeshInformationElementVector and all IE struct MeshInformationElementVectorBist : public TestCase { MeshInformationElementVectorBist () : TestCase ("Serialization test for all mesh information elements") { }; void DoRun (); }; void MeshInformationElementVectorBist::DoRun () { MeshInformationElementVector vector; { //Mesh ID test Ptr<dot11s::IeMeshId> meshId = Create<dot11s::IeMeshId> ("qwerty"); vector.AddInformationElement (meshId); } { Ptr<dot11s::IeConfiguration> config = Create<dot11s::IeConfiguration> (); vector.AddInformationElement (config); } { Ptr<dot11s::IeLinkMetricReport> report = Create<dot11s::IeLinkMetricReport> (123456); vector.AddInformationElement (report); } { Ptr<dot11s::IePeerManagement> peerMan1 = Create<dot11s::IePeerManagement> (); peerMan1->SetPeerOpen (1); Ptr<dot11s::IePeerManagement> peerMan2 = Create<dot11s::IePeerManagement> (); peerMan2->SetPeerConfirm (1, 2); Ptr<dot11s::IePeerManagement> peerMan3 = Create<dot11s::IePeerManagement> (); peerMan3->SetPeerClose (1, 2, dot11s::REASON11S_MESH_CAPABILITY_POLICY_VIOLATION); vector.AddInformationElement (peerMan1); vector.AddInformationElement (peerMan2); vector.AddInformationElement (peerMan3); } { Ptr<dot11s::IeBeaconTiming> beaconTiming = Create<dot11s::IeBeaconTiming> (); beaconTiming->AddNeighboursTimingElementUnit (1, Seconds (1.0), Seconds (4.0)); beaconTiming->AddNeighboursTimingElementUnit (2, Seconds (2.0), Seconds (3.0)); beaconTiming->AddNeighboursTimingElementUnit (3, Seconds (3.0), Seconds (2.0)); beaconTiming->AddNeighboursTimingElementUnit (4, Seconds (4.0), Seconds (1.0)); vector.AddInformationElement (beaconTiming); } { Ptr<dot11s::IeRann> rann = Create<dot11s::IeRann> (); rann->SetFlags (1); rann->SetHopcount (2); rann->SetTTL (4); rann->DecrementTtl (); NS_TEST_ASSERT_MSG_EQ (rann->GetTtl (), 3, "SetTtl works"); rann->SetOriginatorAddress (Mac48Address ("11:22:33:44:55:66")); rann->SetDestSeqNumber (5); rann->SetMetric (6); rann->IncrementMetric (2); NS_TEST_ASSERT_MSG_EQ (rann->GetMetric (), 8, "SetMetric works"); vector.AddInformationElement (rann); } { Ptr<dot11s::IePreq> preq = Create<dot11s::IePreq> (); preq->SetHopcount (0); preq->SetTTL (1); preq->SetPreqID (2); preq->SetOriginatorAddress (Mac48Address ("11:22:33:44:55:66")); preq->SetOriginatorSeqNumber (3); preq->SetLifetime (4); preq->AddDestinationAddressElement (false, false, Mac48Address ("11:11:11:11:11:11"), 5); preq->AddDestinationAddressElement (false, false, Mac48Address ("22:22:22:22:22:22"), 6); vector.AddInformationElement (preq); } { Ptr<dot11s::IePrep> prep = Create<dot11s::IePrep> (); prep->SetFlags (12); prep->SetHopcount (11); prep->SetTtl (10); prep->SetDestinationAddress (Mac48Address ("11:22:33:44:55:66")); prep->SetDestinationSeqNumber (123); prep->SetLifetime (5000); prep->SetMetric (4321); prep->SetOriginatorAddress (Mac48Address ("33:00:22:00:11:00")); prep->SetOriginatorSeqNumber (666); vector.AddInformationElement (prep); } { Ptr<dot11s::IePerr> perr = Create<dot11s::IePerr> (); dot11s::HwmpProtocol::FailedDestination dest; dest.destination = Mac48Address ("11:22:33:44:55:66"); dest.seqnum = 1; perr->AddAddressUnit (dest); dest.destination = Mac48Address ("10:20:30:40:50:60"); dest.seqnum = 2; perr->AddAddressUnit (dest); dest.destination = Mac48Address ("01:02:03:04:05:06"); dest.seqnum = 3; perr->AddAddressUnit (dest); vector.AddInformationElement (perr); } Ptr<Packet> packet = Create<Packet> (); packet->AddHeader (vector); MeshInformationElementVector resultVector; packet->RemoveHeader (resultVector); NS_TEST_ASSERT_MSG_EQ (vector, resultVector, "Roundtrip serialization of all known information elements works"); } class MeshTestSuite : public TestSuite { public: MeshTestSuite (); }; MeshTestSuite::MeshTestSuite () : TestSuite ("devices-mesh", UNIT) { AddTestCase (new MeshInformationElementVectorBist, TestCase::QUICK); } static MeshTestSuite g_meshTestSuite;
hossamkhader/ns-3
src/mesh/test/mesh-information-element-vector-test-suite.cc
C++
gpl-2.0
5,660
#!/usr/bin/env python # # Copyright 2006, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Unit test for the gtest_xml_output module""" __author__ = '[email protected] (Sean Mcafee)' import datetime import errno import os import re import sys from xml.dom import minidom, Node import gtest_test_utils import gtest_xml_test_utils GTEST_LIST_TESTS_FLAG = '--gtest_list_tests' GTEST_OUTPUT_FLAG = "--gtest_output" GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml" GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_" SUPPORTS_STACK_TRACES = False if SUPPORTS_STACK_TRACES: STACK_TRACE_TEMPLATE = '\nStack trace:\n*' else: STACK_TRACE_TEMPLATE = '' EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="23" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests"> <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/> </testsuite> <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="Fails" status="run" time="*" classname="FailedTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Value of: 2 Expected: 1%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/> <testcase name="Fails" status="run" time="*" classname="MixedResultTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Value of: 2 Expected: 1%(stack)s]]></failure> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 3&#x0A;Expected: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Value of: 3 Expected: 2%(stack)s]]></failure> </testcase> <testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/> </testsuite> <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="OutputsCData" status="run" time="*" classname="XmlQuotingTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;XML output: &lt;?xml encoding=&quot;utf-8&quot;&gt;&lt;top&gt;&lt;![CDATA[cdata text]]&gt;&lt;/top&gt;" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]&gt;<![CDATA[</top>%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="InvalidCharactersInMessage" status="run" time="*" classname="InvalidCharactersTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed Invalid characters in brackets []%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*"> <testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/> </testsuite> <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*"> <testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/> <testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/> <testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/> <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/> </testsuite> <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*"> <testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/> <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/> <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/> </testsuite> <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="HasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> </testsuite> <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/0" /> </testsuite> <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/1" /> </testsuite> <testsuite name="Single/TypeParameterizedTestCase/0" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/0" /> </testsuite> <testsuite name="Single/TypeParameterizedTestCase/1" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/1" /> </testsuite> </testsuites>""" % {'stack': STACK_TRACE_TEMPLATE} EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="0" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> </testsuites>""" GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME) SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess( [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): """ Unit test for Google Test's XML output functionality. """ # This test currently breaks on platforms that do not support typed and # type-parameterized tests, so we don't run it under them. if SUPPORTS_TYPED_TESTS: def testNonEmptyXmlOutput(self): """ Runs a test program that generates a non-empty XML output, and tests that the XML output is expected. """ self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1) def testEmptyXmlOutput(self): """Verifies XML output for a Google Test binary without actual tests. Runs a test program that generates an empty XML output, and tests that the XML output is expected. """ self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_EMPTY_XML, 0) def testTimestampValue(self): """Checks whether the timestamp attribute in the XML output is valid. Runs a test program that generates an empty XML output, and checks if the timestamp attribute in the testsuites tag is valid. """ actual = self._GetXmlOutput('gtest_no_test_unittest', 0) date_time_str = actual.documentElement.getAttributeNode('timestamp').value # datetime.strptime() is only available in Python 2.5+ so we have to # parse the expected datetime manually. match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str) self.assertTrue( re.match, 'XML datettime string %s has incorrect format' % date_time_str) date_time_from_xml = datetime.datetime( year=int(match.group(1)), month=int(match.group(2)), day=int(match.group(3)), hour=int(match.group(4)), minute=int(match.group(5)), second=int(match.group(6))) time_delta = abs(datetime.datetime.now() - date_time_from_xml) # timestamp value should be near the current local time self.assertTrue(time_delta < datetime.timedelta(seconds=600), 'time_delta is %s' % time_delta) actual.unlink() def testDefaultOutputFile(self): """ Confirms that Google Test produces an XML output file with the expected default name if no name is explicitly specified. """ output_file = os.path.join(gtest_test_utils.GetTempDir(), GTEST_DEFAULT_OUTPUT_FILE) gtest_prog_path = gtest_test_utils.GetTestExecutablePath( 'gtest_no_test_unittest') try: os.remove(output_file) except OSError, e: if e.errno != errno.ENOENT: raise p = gtest_test_utils.Subprocess( [gtest_prog_path, '%s=xml' % GTEST_OUTPUT_FLAG], working_dir=gtest_test_utils.GetTempDir()) self.assert_(p.exited) self.assertEquals(0, p.exit_code) self.assert_(os.path.isfile(output_file)) def testSuppressedXmlOutput(self): """ Tests that no XML file is generated if the default XML listener is shut down before RUN_ALL_TESTS is invoked. """ xml_path = os.path.join(gtest_test_utils.GetTempDir(), GTEST_PROGRAM_NAME + 'out.xml') if os.path.isfile(xml_path): os.remove(xml_path) command = [GTEST_PROGRAM_PATH, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path), '--shut_down_xml'] p = gtest_test_utils.Subprocess(command) if p.terminated_by_signal: # p.signal is avalable only if p.terminated_by_signal is True. self.assertFalse( p.terminated_by_signal, '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal)) else: self.assert_(p.exited) self.assertEquals(1, p.exit_code, "'%s' exited with code %s, which doesn't match " 'the expected exit code %s.' % (command, p.exit_code, 1)) self.assert_(not os.path.isfile(xml_path)) def _GetXmlOutput(self, gtest_prog_name, expected_exit_code): """ Returns the xml output generated by running the program gtest_prog_name. Furthermore, the program's exit code must be expected_exit_code. """ xml_path = os.path.join(gtest_test_utils.GetTempDir(), gtest_prog_name + 'out.xml') gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name) command = [gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] p = gtest_test_utils.Subprocess(command) if p.terminated_by_signal: self.assert_(False, '%s was killed by signal %d' % (gtest_prog_name, p.signal)) else: self.assert_(p.exited) self.assertEquals(expected_exit_code, p.exit_code, "'%s' exited with code %s, which doesn't match " 'the expected exit code %s.' % (command, p.exit_code, expected_exit_code)) actual = minidom.parse(xml_path) return actual def _TestXmlOutput(self, gtest_prog_name, expected_xml, expected_exit_code): """ Asserts that the XML document generated by running the program gtest_prog_name matches expected_xml, a string containing another XML document. Furthermore, the program's exit code must be expected_exit_code. """ actual = self._GetXmlOutput(gtest_prog_name, expected_exit_code) expected = minidom.parseString(expected_xml) self.NormalizeXml(actual.documentElement) self.AssertEquivalentNodes(expected.documentElement, actual.documentElement) expected.unlink() actual.unlink() if __name__ == '__main__': os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' gtest_test_utils.Main()
wubenqi/zutils
zutils/testing/gtest/test/gtest_xml_output_unittest.py
Python
apache-2.0
13,525
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_FOCUS_EXTERNAL_FOCUS_TRACKER_H_ #define UI_VIEWS_FOCUS_EXTERNAL_FOCUS_TRACKER_H_ #include "base/compiler_specific.h" #include "ui/views/focus/focus_manager.h" namespace views { class View; class ViewStorage; // ExternalFocusTracker tracks the last focused view which belongs to the // provided focus manager and is not either the provided parent view or one of // its descendants. This is generally used if the parent view want to return // focus to some other view once it is dismissed. The parent view and the focus // manager must exist for the duration of the tracking. If the focus manager // must be deleted before this object is deleted, make sure to call // SetFocusManager(NULL) first. // // Typical use: When a view is added to the view hierarchy, it instantiates an // ExternalFocusTracker and passes in itself and its focus manager. Then, // when that view wants to return focus to the last focused view which is not // itself and not a descandant of itself, (usually when it is being closed) // it calls FocusLastFocusedExternalView. class VIEWS_EXPORT ExternalFocusTracker : public FocusChangeListener { public: ExternalFocusTracker(View* parent_view, FocusManager* focus_manager); virtual ~ExternalFocusTracker(); // FocusChangeListener: virtual void OnWillChangeFocus(View* focused_before, View* focused_now) OVERRIDE; virtual void OnDidChangeFocus(View* focused_before, View* focused_now) OVERRIDE; // Focuses last focused view which is not a child of parent view and is not // parent view itself. Returns true if focus for a view was requested, false // otherwise. void FocusLastFocusedExternalView(); // Sets the focus manager whose focus we are tracking. |focus_manager| can // be NULL, but no focus changes will be tracked. This is useful if the focus // manager went away, but you might later want to start tracking with a new // manager later, or call FocusLastFocusedExternalView to focus the previous // view. void SetFocusManager(FocusManager* focus_manager); private: // Store the provided view. This view will be focused when // FocusLastFocusedExternalView is called. void StoreLastFocusedView(View* view); // Store the currently focused view for our view manager and register as a // listener for future focus changes. void StartTracking(); // Focus manager which we are a listener for. FocusManager* focus_manager_; // ID of the last focused view, which we store in view_storage_. int last_focused_view_storage_id_; // Used to store the last focused view which is not a child of // ExternalFocusTracker. ViewStorage* view_storage_; // The parent view of views which we should not track focus changes to. We // also do not track changes to parent_view_ itself. View* parent_view_; DISALLOW_COPY_AND_ASSIGN(ExternalFocusTracker); }; } // namespace views #endif // UI_VIEWS_FOCUS_EXTERNAL_FOCUS_TRACKER_H_
androidarmv6/android_external_chromium_org
ui/views/focus/external_focus_tracker.h
C
bsd-3-clause
3,170
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/environment.h" #include "base/files/file_path.h" #include "base/memory/scoped_ptr.h" #include "chrome/common/env_vars.h" #include "chrome/common/logging_chrome.h" #include "testing/gtest/include/gtest/gtest.h" class ChromeLoggingTest : public testing::Test { public: // Stores the current value of the log file name environment // variable and sets the variable to new_value. void SaveEnvironmentVariable(std::string new_value) { scoped_ptr<base::Environment> env(base::Environment::Create()); if (!env->GetVar(env_vars::kLogFileName, &environment_filename_)) environment_filename_ = ""; env->SetVar(env_vars::kLogFileName, new_value); } // Restores the value of the log file nave environment variable // previously saved by SaveEnvironmentVariable(). void RestoreEnvironmentVariable() { scoped_ptr<base::Environment> env(base::Environment::Create()); env->SetVar(env_vars::kLogFileName, environment_filename_); } private: std::string environment_filename_; // Saves real environment value. }; // Tests the log file name getter without an environment variable. TEST_F(ChromeLoggingTest, LogFileName) { SaveEnvironmentVariable(std::string()); base::FilePath filename = logging::GetLogFileName(); ASSERT_NE(base::FilePath::StringType::npos, filename.value().find(FILE_PATH_LITERAL("chrome_debug.log"))); RestoreEnvironmentVariable(); } // Tests the log file name getter with an environment variable. TEST_F(ChromeLoggingTest, EnvironmentLogFileName) { SaveEnvironmentVariable("test value"); base::FilePath filename = logging::GetLogFileName(); ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("test value")).value(), filename.value()); RestoreEnvironmentVariable(); }
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/browser/logging_chrome_unittest.cc
C++
gpl-3.0
1,938
define( "dojo/cldr/nls/pt/number", //begin v1.x content { "decimal": ",", "group": ".", "list": ";", "percentSign": "%", "plusSign": "+", "minusSign": "-", "exponential": "E", "perMille": "‰", "infinity": "∞", "nan": "NaN", "decimalFormat": "#,##0.###", "decimalFormat-short": "000 tri", "scientificFormat": "#E0", "percentFormat": "#,##0%", "currencyFormat": "¤#,##0.00;(¤#,##0.00)" } //end v1.x content );
niug/DirClia
web/dojo/dojo/cldr/nls/pt/number.js.uncompressed.js
JavaScript
mit
429
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions for constructing HID report descriptors. """ import struct import hid_constants def ReportDescriptor(*items): return ''.join(items) def _PackItem(tag, typ, value=0, force_length=0): """Pack a multibyte value. See Device Class Definition for Human Interface Devices (HID) Version 1.11 section 5.8. Args: tag: Item tag. typ: Item type. value: Item value. force_length: Force packing to a specific width. Returns: Packed string. """ if value == 0 and force_length <= 0: return struct.pack('<B', tag << 4 | typ << 2 | 0) elif value <= 0xff and force_length <= 1: return struct.pack('<BB', tag << 4 | typ << 2 | 1, value) elif value <= 0xffff and force_length <= 2: return struct.pack('<BH', tag << 4 | typ << 2 | 2, value) elif value <= 0xffffffff and force_length <= 4: return struct.pack('<BI', tag << 4 | typ << 2 | 3, value) else: raise NotImplementedError('Long items are not implemented.') def _DefineItem(name, tag, typ): """Create a function which encodes a HID item. Args: name: Function name. tag: Item tag. typ: Item type. Returns: A function which encodes a HID item of the given type. """ assert tag >= 0 and tag <= 0xF assert typ >= 0 and typ <= 3 def EncodeItem(value=0, force_length=0): return _PackItem(tag, typ, value, force_length) EncodeItem.__name__ = name return EncodeItem def _DefineMainItem(name, tag): """Create a function which encodes a HID Main item. See Device Class Definition for Human Interface Devices (HID) Version 1.11 section 6.2.2.4. Args: name: Function name. tag: Item tag. Returns: A function which encodes a HID item of the given type. Raises: ValueError: If the tag value is out of range. """ assert tag >= 0 and tag <= 0xF def EncodeMainItem(*properties): value = 0 for bit, is_set in properties: if is_set: value |= 1 << bit return _PackItem(tag, hid_constants.Scope.MAIN, value, force_length=1) EncodeMainItem.__name__ = name return EncodeMainItem Input = _DefineMainItem('Input', 8) Output = _DefineMainItem('Output', 9) Feature = _DefineMainItem('Feature', 11) # Input, Output and Feature Item Properties # # See Device Class Definition for Human Interface Devices (HID) Version 1.11 # section 6.2.2.5. Data = (0, False) Constant = (0, True) Array = (1, False) Variable = (1, True) Absolute = (2, False) Relative = (2, True) NoWrap = (3, False) Wrap = (3, True) Linear = (4, False) NonLinear = (4, True) PreferredState = (5, False) NoPreferred = (5, True) NoNullPosition = (6, False) NullState = (6, True) NonVolatile = (7, False) Volatile = (7, True) BitField = (8, False) BufferedBytes = (8, True) def Collection(typ, *items): start = struct.pack('<BB', 0xA1, typ) end = struct.pack('<B', 0xC0) return start + ''.join(items) + end # Global Items # # See Device Class Definition for Human Interface Devices (HID) Version 1.11 # section 6.2.2.7. UsagePage = _DefineItem('UsagePage', 0, hid_constants.Scope.GLOBAL) LogicalMinimum = _DefineItem('LogicalMinimum', 1, hid_constants.Scope.GLOBAL) LogicalMaximum = _DefineItem('LogicalMaximum', 2, hid_constants.Scope.GLOBAL) PhysicalMinimum = _DefineItem('PhysicalMinimum', 3, hid_constants.Scope.GLOBAL) PhysicalMaximum = _DefineItem('PhysicalMaximum', 4, hid_constants.Scope.GLOBAL) UnitExponent = _DefineItem('UnitExponent', 5, hid_constants.Scope.GLOBAL) Unit = _DefineItem('Unit', 6, hid_constants.Scope.GLOBAL) ReportSize = _DefineItem('ReportSize', 7, hid_constants.Scope.GLOBAL) ReportID = _DefineItem('ReportID', 8, hid_constants.Scope.GLOBAL) ReportCount = _DefineItem('ReportCount', 9, hid_constants.Scope.GLOBAL) Push = _DefineItem('Push', 10, hid_constants.Scope.GLOBAL) Pop = _DefineItem('Pop', 11, hid_constants.Scope.GLOBAL) # Local Items # # See Device Class Definition for Human Interface Devices (HID) Version 1.11 # section 6.2.2.8. Usage = _DefineItem('Usage', 0, hid_constants.Scope.LOCAL) UsageMinimum = _DefineItem('UsageMinimum', 1, hid_constants.Scope.LOCAL) UsageMaximum = _DefineItem('UsageMaximum', 2, hid_constants.Scope.LOCAL) DesignatorIndex = _DefineItem('DesignatorIndex', 3, hid_constants.Scope.LOCAL) DesignatorMinimum = _DefineItem('DesignatorMinimum', 4, hid_constants.Scope.LOCAL) DesignatorMaximum = _DefineItem('DesignatorMaximum', 5, hid_constants.Scope.LOCAL) StringIndex = _DefineItem('StringIndex', 7, hid_constants.Scope.LOCAL) StringMinimum = _DefineItem('StringMinimum', 8, hid_constants.Scope.LOCAL) StringMaximum = _DefineItem('StringMaximum', 9, hid_constants.Scope.LOCAL) Delimiter = _DefineItem('Delimiter', 10, hid_constants.Scope.LOCAL)
jaruba/chromium.src
tools/usb_gadget/hid_descriptors.py
Python
bsd-3-clause
4,931
CKEDITOR.plugins.setLang("templates","ar",{button:"القوالب",emptyListMsg:"(لم يتم تعريف أي قالب)",insertOption:"استبدال المحتوى",options:"خصائص القوالب",selectPromptMsg:"اختر القالب الذي تود وضعه في المحرر",title:"قوالب المحتوى"});
orbiten-pradeep/chesmile
webroot/dashboard/plugins/ckeditor/plugins/templates/lang/ar.js
JavaScript
mit
321
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // #include "timedata.h" #include "test/test_bitcoin.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(timedata_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(util_MedianFilter) { CMedianFilter<int> filter(5, 15); BOOST_CHECK_EQUAL(filter.median(), 15); filter.input(20); // [15 20] BOOST_CHECK_EQUAL(filter.median(), 17); filter.input(30); // [15 20 30] BOOST_CHECK_EQUAL(filter.median(), 20); filter.input(3); // [3 15 20 30] BOOST_CHECK_EQUAL(filter.median(), 17); filter.input(7); // [3 7 15 20 30] BOOST_CHECK_EQUAL(filter.median(), 15); filter.input(18); // [3 7 18 20 30] BOOST_CHECK_EQUAL(filter.median(), 18); filter.input(0); // [0 3 7 18 30] BOOST_CHECK_EQUAL(filter.median(), 7); } BOOST_AUTO_TEST_SUITE_END()
Mirobit/bitcoin
src/test/timedata_tests.cpp
C++
mit
997
<?php ///////////////////////////////////////////////////////////////// /// getID3() by James Heinrich <[email protected]> // // available at http://getid3.sourceforge.net // // or http://www.getid3.org // ///////////////////////////////////////////////////////////////// // See readme.txt for more details // ///////////////////////////////////////////////////////////////// // // // module.audio-video.quicktime.php // // module for analyzing Quicktime and MP3-in-MP4 files // // dependencies: module.audio.mp3.php // // dependencies: module.tag.id3v2.php // // /// ///////////////////////////////////////////////////////////////// getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.mp3.php', __FILE__, true); getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v2.php', __FILE__, true); // needed for ISO 639-2 language code lookup class getid3_quicktime extends getid3_handler { public $ReturnAtomData = true; public $ParseAllPossibleAtoms = false; public function Analyze() { $info = &$this->getid3->info; $info['fileformat'] = 'quicktime'; $info['quicktime']['hinting'] = false; $info['quicktime']['controller'] = 'standard'; // may be overridden if 'ctyp' atom is present fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET); $offset = 0; $atomcounter = 0; while ($offset < $info['avdataend']) { if (!getid3_lib::intValueSupported($offset)) { $info['error'][] = 'Unable to parse atom at offset '.$offset.' because beyond '.round(PHP_INT_MAX / 1073741824).'GB limit of PHP filesystem functions'; break; } fseek($this->getid3->fp, $offset, SEEK_SET); $AtomHeader = fread($this->getid3->fp, 8); $atomsize = getid3_lib::BigEndian2Int(substr($AtomHeader, 0, 4)); $atomname = substr($AtomHeader, 4, 4); // 64-bit MOV patch by jlegateØktnc*com if ($atomsize == 1) { $atomsize = getid3_lib::BigEndian2Int(fread($this->getid3->fp, 8)); } $info['quicktime'][$atomname]['name'] = $atomname; $info['quicktime'][$atomname]['size'] = $atomsize; $info['quicktime'][$atomname]['offset'] = $offset; if (($offset + $atomsize) > $info['avdataend']) { $info['error'][] = 'Atom at offset '.$offset.' claims to go beyond end-of-file (length: '.$atomsize.' bytes)'; return false; } if ($atomsize == 0) { // Furthermore, for historical reasons the list of atoms is optionally // terminated by a 32-bit integer set to 0. If you are writing a program // to read user data atoms, you should allow for the terminating 0. break; } switch ($atomname) { case 'mdat': // Media DATa atom // 'mdat' contains the actual data for the audio/video if (($atomsize > 8) && (!isset($info['avdataend_tmp']) || ($info['quicktime'][$atomname]['size'] > ($info['avdataend_tmp'] - $info['avdataoffset'])))) { $info['avdataoffset'] = $info['quicktime'][$atomname]['offset'] + 8; $OldAVDataEnd = $info['avdataend']; $info['avdataend'] = $info['quicktime'][$atomname]['offset'] + $info['quicktime'][$atomname]['size']; $getid3_temp = new getID3(); $getid3_temp->openfile($this->getid3->filename); $getid3_temp->info['avdataoffset'] = $info['avdataoffset']; $getid3_temp->info['avdataend'] = $info['avdataend']; $getid3_mp3 = new getid3_mp3($getid3_temp); if ($getid3_mp3->MPEGaudioHeaderValid($getid3_mp3->MPEGaudioHeaderDecode(fread($this->getid3->fp, 4)))) { $getid3_mp3->getOnlyMPEGaudioInfo($getid3_temp->info['avdataoffset'], false); if (!empty($getid3_temp->info['warning'])) { foreach ($getid3_temp->info['warning'] as $value) { $info['warning'][] = $value; } } if (!empty($getid3_temp->info['mpeg'])) { $info['mpeg'] = $getid3_temp->info['mpeg']; if (isset($info['mpeg']['audio'])) { $info['audio']['dataformat'] = 'mp3'; $info['audio']['codec'] = (!empty($info['mpeg']['audio']['encoder']) ? $info['mpeg']['audio']['encoder'] : (!empty($info['mpeg']['audio']['codec']) ? $info['mpeg']['audio']['codec'] : (!empty($info['mpeg']['audio']['LAME']) ? 'LAME' :'mp3'))); $info['audio']['sample_rate'] = $info['mpeg']['audio']['sample_rate']; $info['audio']['channels'] = $info['mpeg']['audio']['channels']; $info['audio']['bitrate'] = $info['mpeg']['audio']['bitrate']; $info['audio']['bitrate_mode'] = strtolower($info['mpeg']['audio']['bitrate_mode']); $info['bitrate'] = $info['audio']['bitrate']; } } } unset($getid3_mp3, $getid3_temp); $info['avdataend'] = $OldAVDataEnd; unset($OldAVDataEnd); } break; case 'free': // FREE space atom case 'skip': // SKIP atom case 'wide': // 64-bit expansion placeholder atom // 'free', 'skip' and 'wide' are just padding, contains no useful data at all break; default: $atomHierarchy = array(); $info['quicktime'][$atomname] = $this->QuicktimeParseAtom($atomname, $atomsize, fread($this->getid3->fp, $atomsize), $offset, $atomHierarchy, $this->ParseAllPossibleAtoms); break; } $offset += $atomsize; $atomcounter++; } if (!empty($info['avdataend_tmp'])) { // this value is assigned to a temp value and then erased because // otherwise any atoms beyond the 'mdat' atom would not get parsed $info['avdataend'] = $info['avdataend_tmp']; unset($info['avdataend_tmp']); } if (!isset($info['bitrate']) && isset($info['playtime_seconds'])) { $info['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds']; } if (isset($info['bitrate']) && !isset($info['audio']['bitrate']) && !isset($info['quicktime']['video'])) { $info['audio']['bitrate'] = $info['bitrate']; } if (!empty($info['playtime_seconds']) && !isset($info['video']['frame_rate']) && !empty($info['quicktime']['stts_framecount'])) { foreach ($info['quicktime']['stts_framecount'] as $key => $samples_count) { $samples_per_second = $samples_count / $info['playtime_seconds']; if ($samples_per_second > 240) { // has to be audio samples } else { $info['video']['frame_rate'] = $samples_per_second; break; } } } if (($info['audio']['dataformat'] == 'mp4') && empty($info['video']['resolution_x'])) { $info['fileformat'] = 'mp4'; $info['mime_type'] = 'audio/mp4'; unset($info['video']['dataformat']); } if (!$this->ReturnAtomData) { unset($info['quicktime']['moov']); } if (empty($info['audio']['dataformat']) && !empty($info['quicktime']['audio'])) { $info['audio']['dataformat'] = 'quicktime'; } if (empty($info['video']['dataformat']) && !empty($info['quicktime']['video'])) { $info['video']['dataformat'] = 'quicktime'; } return true; } public function QuicktimeParseAtom($atomname, $atomsize, $atom_data, $baseoffset, &$atomHierarchy, $ParseAllPossibleAtoms) { // http://developer.apple.com/techpubs/quicktime/qtdevdocs/APIREF/INDEX/atomalphaindex.htm $info = &$this->getid3->info; //$atom_parent = array_pop($atomHierarchy); $atom_parent = end($atomHierarchy); // http://www.getid3.org/phpBB3/viewtopic.php?t=1717 array_push($atomHierarchy, $atomname); $atom_structure['hierarchy'] = implode(' ', $atomHierarchy); $atom_structure['name'] = $atomname; $atom_structure['size'] = $atomsize; $atom_structure['offset'] = $baseoffset; //echo getid3_lib::PrintHexBytes(substr($atom_data, 0, 8)).'<br>'; //echo getid3_lib::PrintHexBytes(substr($atom_data, 0, 8), false).'<br><br>'; switch ($atomname) { case 'moov': // MOVie container atom case 'trak': // TRAcK container atom case 'clip': // CLIPping container atom case 'matt': // track MATTe container atom case 'edts': // EDiTS container atom case 'tref': // Track REFerence container atom case 'mdia': // MeDIA container atom case 'minf': // Media INFormation container atom case 'dinf': // Data INFormation container atom case 'udta': // User DaTA container atom case 'cmov': // Compressed MOVie container atom case 'rmra': // Reference Movie Record Atom case 'rmda': // Reference Movie Descriptor Atom case 'gmhd': // Generic Media info HeaDer atom (seen on QTVR) $atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms); break; case 'ilst': // Item LiST container atom $atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms); // some "ilst" atoms contain data atoms that have a numeric name, and the data is far more accessible if the returned array is compacted $allnumericnames = true; foreach ($atom_structure['subatoms'] as $subatomarray) { if (!is_integer($subatomarray['name']) || (count($subatomarray['subatoms']) != 1)) { $allnumericnames = false; break; } } if ($allnumericnames) { $newData = array(); foreach ($atom_structure['subatoms'] as $subatomarray) { foreach ($subatomarray['subatoms'] as $newData_subatomarray) { unset($newData_subatomarray['hierarchy'], $newData_subatomarray['name']); $newData[$subatomarray['name']] = $newData_subatomarray; break; } } $atom_structure['data'] = $newData; unset($atom_structure['subatoms']); } break; case "\x00\x00\x00\x01": case "\x00\x00\x00\x02": case "\x00\x00\x00\x03": case "\x00\x00\x00\x04": case "\x00\x00\x00\x05": $atomname = getid3_lib::BigEndian2Int($atomname); $atom_structure['name'] = $atomname; $atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms); break; case 'stbl': // Sample TaBLe container atom $atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms); $isVideo = false; $framerate = 0; $framecount = 0; foreach ($atom_structure['subatoms'] as $key => $value_array) { if (isset($value_array['sample_description_table'])) { foreach ($value_array['sample_description_table'] as $key2 => $value_array2) { if (isset($value_array2['data_format'])) { switch ($value_array2['data_format']) { case 'avc1': case 'mp4v': // video data $isVideo = true; break; case 'mp4a': // audio data break; } } } } elseif (isset($value_array['time_to_sample_table'])) { foreach ($value_array['time_to_sample_table'] as $key2 => $value_array2) { if (isset($value_array2['sample_count']) && isset($value_array2['sample_duration']) && ($value_array2['sample_duration'] > 0)) { $framerate = round($info['quicktime']['time_scale'] / $value_array2['sample_duration'], 3); $framecount = $value_array2['sample_count']; } } } } if ($isVideo && $framerate) { $info['quicktime']['video']['frame_rate'] = $framerate; $info['video']['frame_rate'] = $info['quicktime']['video']['frame_rate']; } if ($isVideo && $framecount) { $info['quicktime']['video']['frame_count'] = $framecount; } break; case 'aART': // Album ARTist case 'catg': // CaTeGory case 'covr': // COVeR artwork case 'cpil': // ComPILation case 'cprt': // CoPyRighT case 'desc': // DESCription case 'disk': // DISK number case 'egid': // Episode Global ID case 'gnre': // GeNRE case 'keyw': // KEYWord case 'ldes': case 'pcst': // PodCaST case 'pgap': // GAPless Playback case 'purd': // PURchase Date case 'purl': // Podcast URL case 'rati': case 'rndu': case 'rpdu': case 'rtng': // RaTiNG case 'stik': case 'tmpo': // TeMPO (BPM) case 'trkn': // TRacK Number case 'tves': // TV EpiSode case 'tvnn': // TV Network Name case 'tvsh': // TV SHow Name case 'tvsn': // TV SeasoN case 'akID': // iTunes store account type case 'apID': case 'atID': case 'cmID': case 'cnID': case 'geID': case 'plID': case 'sfID': // iTunes store country case '©alb': // ALBum case '©art': // ARTist case '©ART': case '©aut': case '©cmt': // CoMmenT case '©com': // COMposer case '©cpy': case '©day': // content created year case '©dir': case '©ed1': case '©ed2': case '©ed3': case '©ed4': case '©ed5': case '©ed6': case '©ed7': case '©ed8': case '©ed9': case '©enc': case '©fmt': case '©gen': // GENre case '©grp': // GRouPing case '©hst': case '©inf': case '©lyr': // LYRics case '©mak': case '©mod': case '©nam': // full NAMe case '©ope': case '©PRD': case '©prd': case '©prf': case '©req': case '©src': case '©swr': case '©too': // encoder case '©trk': // TRacK case '©url': case '©wrn': case '©wrt': // WRiTer case '----': // itunes specific if ($atom_parent == 'udta') { // User data atom handler $atom_structure['data_length'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 2)); $atom_structure['language_id'] = getid3_lib::BigEndian2Int(substr($atom_data, 2, 2)); $atom_structure['data'] = substr($atom_data, 4); $atom_structure['language'] = $this->QuicktimeLanguageLookup($atom_structure['language_id']); if (empty($info['comments']['language']) || (!in_array($atom_structure['language'], $info['comments']['language']))) { $info['comments']['language'][] = $atom_structure['language']; } } else { // Apple item list box atom handler $atomoffset = 0; if (substr($atom_data, 2, 2) == "\x10\xB5") { // not sure what it means, but observed on iPhone4 data. // Each $atom_data has 2 bytes of datasize, plus 0x10B5, then data while ($atomoffset < strlen($atom_data)) { $boxsmallsize = getid3_lib::BigEndian2Int(substr($atom_data, $atomoffset, 2)); $boxsmalltype = substr($atom_data, $atomoffset + 2, 2); $boxsmalldata = substr($atom_data, $atomoffset + 4, $boxsmallsize); if ($boxsmallsize <= 1) { $info['warning'][] = 'Invalid QuickTime atom smallbox size "'.$boxsmallsize.'" in atom "'.$atomname.'" at offset: '.($atom_structure['offset'] + $atomoffset); $atom_structure['data'] = null; $atomoffset = strlen($atom_data); break; } switch ($boxsmalltype) { case "\x10\xB5": $atom_structure['data'] = $boxsmalldata; break; default: $info['warning'][] = 'Unknown QuickTime smallbox type: "'.getid3_lib::PrintHexBytes($boxsmalltype).'" at offset '.$baseoffset; $atom_structure['data'] = $atom_data; break; } $atomoffset += (4 + $boxsmallsize); } } else { while ($atomoffset < strlen($atom_data)) { $boxsize = getid3_lib::BigEndian2Int(substr($atom_data, $atomoffset, 4)); $boxtype = substr($atom_data, $atomoffset + 4, 4); $boxdata = substr($atom_data, $atomoffset + 8, $boxsize - 8); if ($boxsize <= 1) { $info['warning'][] = 'Invalid QuickTime atom box size "'.$boxsize.'" in atom "'.$atomname.'" at offset: '.($atom_structure['offset'] + $atomoffset); $atom_structure['data'] = null; $atomoffset = strlen($atom_data); break; } $atomoffset += $boxsize; switch ($boxtype) { case 'mean': case 'name': $atom_structure[$boxtype] = substr($boxdata, 4); break; case 'data': $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($boxdata, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($boxdata, 1, 3)); switch ($atom_structure['flags_raw']) { case 0: // data flag case 21: // tmpo/cpil flag switch ($atomname) { case 'cpil': case 'pcst': case 'pgap': $atom_structure['data'] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 1)); break; case 'tmpo': $atom_structure['data'] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 2)); break; case 'disk': case 'trkn': $num = getid3_lib::BigEndian2Int(substr($boxdata, 10, 2)); $num_total = getid3_lib::BigEndian2Int(substr($boxdata, 12, 2)); $atom_structure['data'] = empty($num) ? '' : $num; $atom_structure['data'] .= empty($num_total) ? '' : '/'.$num_total; break; case 'gnre': $GenreID = getid3_lib::BigEndian2Int(substr($boxdata, 8, 4)); $atom_structure['data'] = getid3_id3v1::LookupGenreName($GenreID - 1); break; case 'rtng': $atom_structure[$atomname] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 1)); $atom_structure['data'] = $this->QuicktimeContentRatingLookup($atom_structure[$atomname]); break; case 'stik': $atom_structure[$atomname] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 1)); $atom_structure['data'] = $this->QuicktimeSTIKLookup($atom_structure[$atomname]); break; case 'sfID': $atom_structure[$atomname] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 4)); $atom_structure['data'] = $this->QuicktimeStoreFrontCodeLookup($atom_structure[$atomname]); break; case 'egid': case 'purl': $atom_structure['data'] = substr($boxdata, 8); break; default: $atom_structure['data'] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 4)); } break; case 1: // text flag case 13: // image flag default: $atom_structure['data'] = substr($boxdata, 8); break; } break; default: $info['warning'][] = 'Unknown QuickTime box type: "'.getid3_lib::PrintHexBytes($boxtype).'" at offset '.$baseoffset; $atom_structure['data'] = $atom_data; } } } } $this->CopyToAppropriateCommentsSection($atomname, $atom_structure['data'], $atom_structure['name']); break; case 'play': // auto-PLAY atom $atom_structure['autoplay'] = (bool) getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $info['quicktime']['autoplay'] = $atom_structure['autoplay']; break; case 'WLOC': // Window LOCation atom $atom_structure['location_x'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 2)); $atom_structure['location_y'] = getid3_lib::BigEndian2Int(substr($atom_data, 2, 2)); break; case 'LOOP': // LOOPing atom case 'SelO': // play SELection Only atom case 'AllF': // play ALL Frames atom $atom_structure['data'] = getid3_lib::BigEndian2Int($atom_data); break; case 'name': // case 'MCPS': // Media Cleaner PRo case '@PRM': // adobe PReMiere version case '@PRQ': // adobe PRemiere Quicktime version $atom_structure['data'] = $atom_data; break; case 'cmvd': // Compressed MooV Data atom // Code by ubergeekØubergeek*tv based on information from // http://developer.apple.com/quicktime/icefloe/dispatch012.html $atom_structure['unCompressedSize'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4)); $CompressedFileData = substr($atom_data, 4); if ($UncompressedHeader = @gzuncompress($CompressedFileData)) { $atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($UncompressedHeader, 0, $atomHierarchy, $ParseAllPossibleAtoms); } else { $info['warning'][] = 'Error decompressing compressed MOV atom at offset '.$atom_structure['offset']; } break; case 'dcom': // Data COMpression atom $atom_structure['compression_id'] = $atom_data; $atom_structure['compression_text'] = $this->QuicktimeDCOMLookup($atom_data); break; case 'rdrf': // Reference movie Data ReFerence atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); $atom_structure['flags']['internal_data'] = (bool) ($atom_structure['flags_raw'] & 0x000001); $atom_structure['reference_type_name'] = substr($atom_data, 4, 4); $atom_structure['reference_length'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4)); switch ($atom_structure['reference_type_name']) { case 'url ': $atom_structure['url'] = $this->NoNullString(substr($atom_data, 12)); break; case 'alis': $atom_structure['file_alias'] = substr($atom_data, 12); break; case 'rsrc': $atom_structure['resource_alias'] = substr($atom_data, 12); break; default: $atom_structure['data'] = substr($atom_data, 12); break; } break; case 'rmqu': // Reference Movie QUality atom $atom_structure['movie_quality'] = getid3_lib::BigEndian2Int($atom_data); break; case 'rmcs': // Reference Movie Cpu Speed atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['cpu_speed_rating'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); break; case 'rmvc': // Reference Movie Version Check atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['gestalt_selector'] = substr($atom_data, 4, 4); $atom_structure['gestalt_value_mask'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4)); $atom_structure['gestalt_value'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 4)); $atom_structure['gestalt_check_type'] = getid3_lib::BigEndian2Int(substr($atom_data, 14, 2)); break; case 'rmcd': // Reference Movie Component check atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['component_type'] = substr($atom_data, 4, 4); $atom_structure['component_subtype'] = substr($atom_data, 8, 4); $atom_structure['component_manufacturer'] = substr($atom_data, 12, 4); $atom_structure['component_flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 16, 4)); $atom_structure['component_flags_mask'] = getid3_lib::BigEndian2Int(substr($atom_data, 20, 4)); $atom_structure['component_min_version'] = getid3_lib::BigEndian2Int(substr($atom_data, 24, 4)); break; case 'rmdr': // Reference Movie Data Rate atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['data_rate'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $atom_structure['data_rate_bps'] = $atom_structure['data_rate'] * 10; break; case 'rmla': // Reference Movie Language Atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['language_id'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); $atom_structure['language'] = $this->QuicktimeLanguageLookup($atom_structure['language_id']); if (empty($info['comments']['language']) || (!in_array($atom_structure['language'], $info['comments']['language']))) { $info['comments']['language'][] = $atom_structure['language']; } break; case 'rmla': // Reference Movie Language Atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['track_id'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); break; case 'ptv ': // Print To Video - defines a movie's full screen mode // http://developer.apple.com/documentation/QuickTime/APIREF/SOURCESIV/at_ptv-_pg.htm $atom_structure['display_size_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 2)); $atom_structure['reserved_1'] = getid3_lib::BigEndian2Int(substr($atom_data, 2, 2)); // hardcoded: 0x0000 $atom_structure['reserved_2'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); // hardcoded: 0x0000 $atom_structure['slide_show_flag'] = getid3_lib::BigEndian2Int(substr($atom_data, 6, 1)); $atom_structure['play_on_open_flag'] = getid3_lib::BigEndian2Int(substr($atom_data, 7, 1)); $atom_structure['flags']['play_on_open'] = (bool) $atom_structure['play_on_open_flag']; $atom_structure['flags']['slide_show'] = (bool) $atom_structure['slide_show_flag']; $ptv_lookup[0] = 'normal'; $ptv_lookup[1] = 'double'; $ptv_lookup[2] = 'half'; $ptv_lookup[3] = 'full'; $ptv_lookup[4] = 'current'; if (isset($ptv_lookup[$atom_structure['display_size_raw']])) { $atom_structure['display_size'] = $ptv_lookup[$atom_structure['display_size_raw']]; } else { $info['warning'][] = 'unknown "ptv " display constant ('.$atom_structure['display_size_raw'].')'; } break; case 'stsd': // Sample Table Sample Description atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $stsdEntriesDataOffset = 8; for ($i = 0; $i < $atom_structure['number_entries']; $i++) { $atom_structure['sample_description_table'][$i]['size'] = getid3_lib::BigEndian2Int(substr($atom_data, $stsdEntriesDataOffset, 4)); $stsdEntriesDataOffset += 4; $atom_structure['sample_description_table'][$i]['data_format'] = substr($atom_data, $stsdEntriesDataOffset, 4); $stsdEntriesDataOffset += 4; $atom_structure['sample_description_table'][$i]['reserved'] = getid3_lib::BigEndian2Int(substr($atom_data, $stsdEntriesDataOffset, 6)); $stsdEntriesDataOffset += 6; $atom_structure['sample_description_table'][$i]['reference_index'] = getid3_lib::BigEndian2Int(substr($atom_data, $stsdEntriesDataOffset, 2)); $stsdEntriesDataOffset += 2; $atom_structure['sample_description_table'][$i]['data'] = substr($atom_data, $stsdEntriesDataOffset, ($atom_structure['sample_description_table'][$i]['size'] - 4 - 4 - 6 - 2)); $stsdEntriesDataOffset += ($atom_structure['sample_description_table'][$i]['size'] - 4 - 4 - 6 - 2); $atom_structure['sample_description_table'][$i]['encoder_version'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 0, 2)); $atom_structure['sample_description_table'][$i]['encoder_revision'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 2, 2)); $atom_structure['sample_description_table'][$i]['encoder_vendor'] = substr($atom_structure['sample_description_table'][$i]['data'], 4, 4); switch ($atom_structure['sample_description_table'][$i]['encoder_vendor']) { case "\x00\x00\x00\x00": // audio tracks $atom_structure['sample_description_table'][$i]['audio_channels'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 8, 2)); $atom_structure['sample_description_table'][$i]['audio_bit_depth'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 10, 2)); $atom_structure['sample_description_table'][$i]['audio_compression_id'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 12, 2)); $atom_structure['sample_description_table'][$i]['audio_packet_size'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 14, 2)); $atom_structure['sample_description_table'][$i]['audio_sample_rate'] = getid3_lib::FixedPoint16_16(substr($atom_structure['sample_description_table'][$i]['data'], 16, 4)); // video tracks // http://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap3/qtff3.html $atom_structure['sample_description_table'][$i]['temporal_quality'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 8, 4)); $atom_structure['sample_description_table'][$i]['spatial_quality'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 12, 4)); $atom_structure['sample_description_table'][$i]['width'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 16, 2)); $atom_structure['sample_description_table'][$i]['height'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 18, 2)); $atom_structure['sample_description_table'][$i]['resolution_x'] = getid3_lib::FixedPoint16_16(substr($atom_structure['sample_description_table'][$i]['data'], 24, 4)); $atom_structure['sample_description_table'][$i]['resolution_y'] = getid3_lib::FixedPoint16_16(substr($atom_structure['sample_description_table'][$i]['data'], 28, 4)); $atom_structure['sample_description_table'][$i]['data_size'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 32, 4)); $atom_structure['sample_description_table'][$i]['frame_count'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 36, 2)); $atom_structure['sample_description_table'][$i]['compressor_name'] = substr($atom_structure['sample_description_table'][$i]['data'], 38, 4); $atom_structure['sample_description_table'][$i]['pixel_depth'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 42, 2)); $atom_structure['sample_description_table'][$i]['color_table_id'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 44, 2)); switch ($atom_structure['sample_description_table'][$i]['data_format']) { case '2vuY': case 'avc1': case 'cvid': case 'dvc ': case 'dvcp': case 'gif ': case 'h263': case 'jpeg': case 'kpcd': case 'mjpa': case 'mjpb': case 'mp4v': case 'png ': case 'raw ': case 'rle ': case 'rpza': case 'smc ': case 'SVQ1': case 'SVQ3': case 'tiff': case 'v210': case 'v216': case 'v308': case 'v408': case 'v410': case 'yuv2': $info['fileformat'] = 'mp4'; $info['video']['fourcc'] = $atom_structure['sample_description_table'][$i]['data_format']; // http://www.getid3.org/phpBB3/viewtopic.php?t=1550 //if ((!empty($atom_structure['sample_description_table'][$i]['width']) && !empty($atom_structure['sample_description_table'][$i]['width'])) && (empty($info['video']['resolution_x']) || empty($info['video']['resolution_y']) || (number_format($info['video']['resolution_x'], 6) != number_format(round($info['video']['resolution_x']), 6)) || (number_format($info['video']['resolution_y'], 6) != number_format(round($info['video']['resolution_y']), 6)))) { // ugly check for floating point numbers if (!empty($atom_structure['sample_description_table'][$i]['width']) && !empty($atom_structure['sample_description_table'][$i]['height'])) { // assume that values stored here are more important than values stored in [tkhd] atom $info['video']['resolution_x'] = $atom_structure['sample_description_table'][$i]['width']; $info['video']['resolution_y'] = $atom_structure['sample_description_table'][$i]['height']; $info['quicktime']['video']['resolution_x'] = $info['video']['resolution_x']; $info['quicktime']['video']['resolution_y'] = $info['video']['resolution_y']; } break; case 'qtvr': $info['video']['dataformat'] = 'quicktimevr'; break; case 'mp4a': default: $info['quicktime']['audio']['codec'] = $this->QuicktimeAudioCodecLookup($atom_structure['sample_description_table'][$i]['data_format']); $info['quicktime']['audio']['sample_rate'] = $atom_structure['sample_description_table'][$i]['audio_sample_rate']; $info['quicktime']['audio']['channels'] = $atom_structure['sample_description_table'][$i]['audio_channels']; $info['quicktime']['audio']['bit_depth'] = $atom_structure['sample_description_table'][$i]['audio_bit_depth']; $info['audio']['codec'] = $info['quicktime']['audio']['codec']; $info['audio']['sample_rate'] = $info['quicktime']['audio']['sample_rate']; $info['audio']['channels'] = $info['quicktime']['audio']['channels']; $info['audio']['bits_per_sample'] = $info['quicktime']['audio']['bit_depth']; switch ($atom_structure['sample_description_table'][$i]['data_format']) { case 'raw ': // PCM case 'alac': // Apple Lossless Audio Codec $info['audio']['lossless'] = true; break; default: $info['audio']['lossless'] = false; break; } break; } break; default: switch ($atom_structure['sample_description_table'][$i]['data_format']) { case 'mp4s': $info['fileformat'] = 'mp4'; break; default: // video atom $atom_structure['sample_description_table'][$i]['video_temporal_quality'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 8, 4)); $atom_structure['sample_description_table'][$i]['video_spatial_quality'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 12, 4)); $atom_structure['sample_description_table'][$i]['video_frame_width'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 16, 2)); $atom_structure['sample_description_table'][$i]['video_frame_height'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 18, 2)); $atom_structure['sample_description_table'][$i]['video_resolution_x'] = getid3_lib::FixedPoint16_16(substr($atom_structure['sample_description_table'][$i]['data'], 20, 4)); $atom_structure['sample_description_table'][$i]['video_resolution_y'] = getid3_lib::FixedPoint16_16(substr($atom_structure['sample_description_table'][$i]['data'], 24, 4)); $atom_structure['sample_description_table'][$i]['video_data_size'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 28, 4)); $atom_structure['sample_description_table'][$i]['video_frame_count'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 32, 2)); $atom_structure['sample_description_table'][$i]['video_encoder_name_len'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 34, 1)); $atom_structure['sample_description_table'][$i]['video_encoder_name'] = substr($atom_structure['sample_description_table'][$i]['data'], 35, $atom_structure['sample_description_table'][$i]['video_encoder_name_len']); $atom_structure['sample_description_table'][$i]['video_pixel_color_depth'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 66, 2)); $atom_structure['sample_description_table'][$i]['video_color_table_id'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 68, 2)); $atom_structure['sample_description_table'][$i]['video_pixel_color_type'] = (($atom_structure['sample_description_table'][$i]['video_pixel_color_depth'] > 32) ? 'grayscale' : 'color'); $atom_structure['sample_description_table'][$i]['video_pixel_color_name'] = $this->QuicktimeColorNameLookup($atom_structure['sample_description_table'][$i]['video_pixel_color_depth']); if ($atom_structure['sample_description_table'][$i]['video_pixel_color_name'] != 'invalid') { $info['quicktime']['video']['codec_fourcc'] = $atom_structure['sample_description_table'][$i]['data_format']; $info['quicktime']['video']['codec_fourcc_lookup'] = $this->QuicktimeVideoCodecLookup($atom_structure['sample_description_table'][$i]['data_format']); $info['quicktime']['video']['codec'] = (($atom_structure['sample_description_table'][$i]['video_encoder_name_len'] > 0) ? $atom_structure['sample_description_table'][$i]['video_encoder_name'] : $atom_structure['sample_description_table'][$i]['data_format']); $info['quicktime']['video']['color_depth'] = $atom_structure['sample_description_table'][$i]['video_pixel_color_depth']; $info['quicktime']['video']['color_depth_name'] = $atom_structure['sample_description_table'][$i]['video_pixel_color_name']; $info['video']['codec'] = $info['quicktime']['video']['codec']; $info['video']['bits_per_sample'] = $info['quicktime']['video']['color_depth']; } $info['video']['lossless'] = false; $info['video']['pixel_aspect_ratio'] = (float) 1; break; } break; } switch (strtolower($atom_structure['sample_description_table'][$i]['data_format'])) { case 'mp4a': $info['audio']['dataformat'] = 'mp4'; $info['quicktime']['audio']['codec'] = 'mp4'; break; case '3ivx': case '3iv1': case '3iv2': $info['video']['dataformat'] = '3ivx'; break; case 'xvid': $info['video']['dataformat'] = 'xvid'; break; case 'mp4v': $info['video']['dataformat'] = 'mpeg4'; break; case 'divx': case 'div1': case 'div2': case 'div3': case 'div4': case 'div5': case 'div6': $info['video']['dataformat'] = 'divx'; break; default: // do nothing break; } unset($atom_structure['sample_description_table'][$i]['data']); } break; case 'stts': // Sample Table Time-to-Sample atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $sttsEntriesDataOffset = 8; //$FrameRateCalculatorArray = array(); $frames_count = 0; for ($i = 0; $i < $atom_structure['number_entries']; $i++) { $atom_structure['time_to_sample_table'][$i]['sample_count'] = getid3_lib::BigEndian2Int(substr($atom_data, $sttsEntriesDataOffset, 4)); $sttsEntriesDataOffset += 4; $atom_structure['time_to_sample_table'][$i]['sample_duration'] = getid3_lib::BigEndian2Int(substr($atom_data, $sttsEntriesDataOffset, 4)); $sttsEntriesDataOffset += 4; $frames_count += $atom_structure['time_to_sample_table'][$i]['sample_count']; // THIS SECTION REPLACED WITH CODE IN "stbl" ATOM //if (!empty($info['quicktime']['time_scale']) && ($atom_structure['time_to_sample_table'][$i]['sample_duration'] > 0)) { // $stts_new_framerate = $info['quicktime']['time_scale'] / $atom_structure['time_to_sample_table'][$i]['sample_duration']; // if ($stts_new_framerate <= 60) { // // some atoms have durations of "1" giving a very large framerate, which probably is not right // $info['video']['frame_rate'] = max($info['video']['frame_rate'], $stts_new_framerate); // } //} // //$FrameRateCalculatorArray[($info['quicktime']['time_scale'] / $atom_structure['time_to_sample_table'][$i]['sample_duration'])] += $atom_structure['time_to_sample_table'][$i]['sample_count']; } $info['quicktime']['stts_framecount'][] = $frames_count; //$sttsFramesTotal = 0; //$sttsSecondsTotal = 0; //foreach ($FrameRateCalculatorArray as $frames_per_second => $frame_count) { // if (($frames_per_second > 60) || ($frames_per_second < 1)) { // // not video FPS information, probably audio information // $sttsFramesTotal = 0; // $sttsSecondsTotal = 0; // break; // } // $sttsFramesTotal += $frame_count; // $sttsSecondsTotal += $frame_count / $frames_per_second; //} //if (($sttsFramesTotal > 0) && ($sttsSecondsTotal > 0)) { // if (($sttsFramesTotal / $sttsSecondsTotal) > $info['video']['frame_rate']) { // $info['video']['frame_rate'] = $sttsFramesTotal / $sttsSecondsTotal; // } //} break; case 'stss': // Sample Table Sync Sample (key frames) atom if ($ParseAllPossibleAtoms) { $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $stssEntriesDataOffset = 8; for ($i = 0; $i < $atom_structure['number_entries']; $i++) { $atom_structure['time_to_sample_table'][$i] = getid3_lib::BigEndian2Int(substr($atom_data, $stssEntriesDataOffset, 4)); $stssEntriesDataOffset += 4; } } break; case 'stsc': // Sample Table Sample-to-Chunk atom if ($ParseAllPossibleAtoms) { $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $stscEntriesDataOffset = 8; for ($i = 0; $i < $atom_structure['number_entries']; $i++) { $atom_structure['sample_to_chunk_table'][$i]['first_chunk'] = getid3_lib::BigEndian2Int(substr($atom_data, $stscEntriesDataOffset, 4)); $stscEntriesDataOffset += 4; $atom_structure['sample_to_chunk_table'][$i]['samples_per_chunk'] = getid3_lib::BigEndian2Int(substr($atom_data, $stscEntriesDataOffset, 4)); $stscEntriesDataOffset += 4; $atom_structure['sample_to_chunk_table'][$i]['sample_description'] = getid3_lib::BigEndian2Int(substr($atom_data, $stscEntriesDataOffset, 4)); $stscEntriesDataOffset += 4; } } break; case 'stsz': // Sample Table SiZe atom if ($ParseAllPossibleAtoms) { $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['sample_size'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4)); $stszEntriesDataOffset = 12; if ($atom_structure['sample_size'] == 0) { for ($i = 0; $i < $atom_structure['number_entries']; $i++) { $atom_structure['sample_size_table'][$i] = getid3_lib::BigEndian2Int(substr($atom_data, $stszEntriesDataOffset, 4)); $stszEntriesDataOffset += 4; } } } break; case 'stco': // Sample Table Chunk Offset atom if ($ParseAllPossibleAtoms) { $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $stcoEntriesDataOffset = 8; for ($i = 0; $i < $atom_structure['number_entries']; $i++) { $atom_structure['chunk_offset_table'][$i] = getid3_lib::BigEndian2Int(substr($atom_data, $stcoEntriesDataOffset, 4)); $stcoEntriesDataOffset += 4; } } break; case 'co64': // Chunk Offset 64-bit (version of "stco" that supports > 2GB files) if ($ParseAllPossibleAtoms) { $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $stcoEntriesDataOffset = 8; for ($i = 0; $i < $atom_structure['number_entries']; $i++) { $atom_structure['chunk_offset_table'][$i] = getid3_lib::BigEndian2Int(substr($atom_data, $stcoEntriesDataOffset, 8)); $stcoEntriesDataOffset += 8; } } break; case 'dref': // Data REFerence atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $drefDataOffset = 8; for ($i = 0; $i < $atom_structure['number_entries']; $i++) { $atom_structure['data_references'][$i]['size'] = getid3_lib::BigEndian2Int(substr($atom_data, $drefDataOffset, 4)); $drefDataOffset += 4; $atom_structure['data_references'][$i]['type'] = substr($atom_data, $drefDataOffset, 4); $drefDataOffset += 4; $atom_structure['data_references'][$i]['version'] = getid3_lib::BigEndian2Int(substr($atom_data, $drefDataOffset, 1)); $drefDataOffset += 1; $atom_structure['data_references'][$i]['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, $drefDataOffset, 3)); // hardcoded: 0x0000 $drefDataOffset += 3; $atom_structure['data_references'][$i]['data'] = substr($atom_data, $drefDataOffset, ($atom_structure['data_references'][$i]['size'] - 4 - 4 - 1 - 3)); $drefDataOffset += ($atom_structure['data_references'][$i]['size'] - 4 - 4 - 1 - 3); $atom_structure['data_references'][$i]['flags']['self_reference'] = (bool) ($atom_structure['data_references'][$i]['flags_raw'] & 0x001); } break; case 'gmin': // base Media INformation atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['graphics_mode'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); $atom_structure['opcolor_red'] = getid3_lib::BigEndian2Int(substr($atom_data, 6, 2)); $atom_structure['opcolor_green'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 2)); $atom_structure['opcolor_blue'] = getid3_lib::BigEndian2Int(substr($atom_data, 10, 2)); $atom_structure['balance'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 2)); $atom_structure['reserved'] = getid3_lib::BigEndian2Int(substr($atom_data, 14, 2)); break; case 'smhd': // Sound Media information HeaDer atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['balance'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); $atom_structure['reserved'] = getid3_lib::BigEndian2Int(substr($atom_data, 6, 2)); break; case 'vmhd': // Video Media information HeaDer atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); $atom_structure['graphics_mode'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); $atom_structure['opcolor_red'] = getid3_lib::BigEndian2Int(substr($atom_data, 6, 2)); $atom_structure['opcolor_green'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 2)); $atom_structure['opcolor_blue'] = getid3_lib::BigEndian2Int(substr($atom_data, 10, 2)); $atom_structure['flags']['no_lean_ahead'] = (bool) ($atom_structure['flags_raw'] & 0x001); break; case 'hdlr': // HanDLeR reference atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['component_type'] = substr($atom_data, 4, 4); $atom_structure['component_subtype'] = substr($atom_data, 8, 4); $atom_structure['component_manufacturer'] = substr($atom_data, 12, 4); $atom_structure['component_flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 16, 4)); $atom_structure['component_flags_mask'] = getid3_lib::BigEndian2Int(substr($atom_data, 20, 4)); $atom_structure['component_name'] = $this->Pascal2String(substr($atom_data, 24)); if (($atom_structure['component_subtype'] == 'STpn') && ($atom_structure['component_manufacturer'] == 'zzzz')) { $info['video']['dataformat'] = 'quicktimevr'; } break; case 'mdhd': // MeDia HeaDer atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['creation_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $atom_structure['modify_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4)); $atom_structure['time_scale'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 4)); $atom_structure['duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 16, 4)); $atom_structure['language_id'] = getid3_lib::BigEndian2Int(substr($atom_data, 20, 2)); $atom_structure['quality'] = getid3_lib::BigEndian2Int(substr($atom_data, 22, 2)); if ($atom_structure['time_scale'] == 0) { $info['error'][] = 'Corrupt Quicktime file: mdhd.time_scale == zero'; return false; } $info['quicktime']['time_scale'] = (isset($info['quicktime']['time_scale']) ? max($info['quicktime']['time_scale'], $atom_structure['time_scale']) : $atom_structure['time_scale']); $atom_structure['creation_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['creation_time']); $atom_structure['modify_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['modify_time']); $atom_structure['playtime_seconds'] = $atom_structure['duration'] / $atom_structure['time_scale']; $atom_structure['language'] = $this->QuicktimeLanguageLookup($atom_structure['language_id']); if (empty($info['comments']['language']) || (!in_array($atom_structure['language'], $info['comments']['language']))) { $info['comments']['language'][] = $atom_structure['language']; } break; case 'pnot': // Preview atom $atom_structure['modification_date'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4)); // "standard Macintosh format" $atom_structure['version_number'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); // hardcoded: 0x00 $atom_structure['atom_type'] = substr($atom_data, 6, 4); // usually: 'PICT' $atom_structure['atom_index'] = getid3_lib::BigEndian2Int(substr($atom_data, 10, 2)); // usually: 0x01 $atom_structure['modification_date_unix'] = getid3_lib::DateMac2Unix($atom_structure['modification_date']); break; case 'crgn': // Clipping ReGioN atom $atom_structure['region_size'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 2)); // The Region size, Region boundary box, $atom_structure['boundary_box'] = getid3_lib::BigEndian2Int(substr($atom_data, 2, 8)); // and Clipping region data fields $atom_structure['clipping_data'] = substr($atom_data, 10); // constitute a QuickDraw region. break; case 'load': // track LOAD settings atom $atom_structure['preload_start_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4)); $atom_structure['preload_duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $atom_structure['preload_flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4)); $atom_structure['default_hints_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 4)); $atom_structure['default_hints']['double_buffer'] = (bool) ($atom_structure['default_hints_raw'] & 0x0020); $atom_structure['default_hints']['high_quality'] = (bool) ($atom_structure['default_hints_raw'] & 0x0100); break; case 'tmcd': // TiMe CoDe atom case 'chap': // CHAPter list atom case 'sync': // SYNChronization atom case 'scpt': // tranSCriPT atom case 'ssrc': // non-primary SouRCe atom for ($i = 0; $i < (strlen($atom_data) % 4); $i++) { $atom_structure['track_id'][$i] = getid3_lib::BigEndian2Int(substr($atom_data, $i * 4, 4)); } break; case 'elst': // Edit LiST atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); for ($i = 0; $i < $atom_structure['number_entries']; $i++ ) { $atom_structure['edit_list'][$i]['track_duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($i * 12) + 0, 4)); $atom_structure['edit_list'][$i]['media_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($i * 12) + 4, 4)); $atom_structure['edit_list'][$i]['media_rate'] = getid3_lib::FixedPoint16_16(substr($atom_data, 8 + ($i * 12) + 8, 4)); } break; case 'kmat': // compressed MATte atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000 $atom_structure['matte_data_raw'] = substr($atom_data, 4); break; case 'ctab': // Color TABle atom $atom_structure['color_table_seed'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4)); // hardcoded: 0x00000000 $atom_structure['color_table_flags'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); // hardcoded: 0x8000 $atom_structure['color_table_size'] = getid3_lib::BigEndian2Int(substr($atom_data, 6, 2)) + 1; for ($colortableentry = 0; $colortableentry < $atom_structure['color_table_size']; $colortableentry++) { $atom_structure['color_table'][$colortableentry]['alpha'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($colortableentry * 8) + 0, 2)); $atom_structure['color_table'][$colortableentry]['red'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($colortableentry * 8) + 2, 2)); $atom_structure['color_table'][$colortableentry]['green'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($colortableentry * 8) + 4, 2)); $atom_structure['color_table'][$colortableentry]['blue'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($colortableentry * 8) + 6, 2)); } break; case 'mvhd': // MoVie HeaDer atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); $atom_structure['creation_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $atom_structure['modify_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4)); $atom_structure['time_scale'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 4)); $atom_structure['duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 16, 4)); $atom_structure['preferred_rate'] = getid3_lib::FixedPoint16_16(substr($atom_data, 20, 4)); $atom_structure['preferred_volume'] = getid3_lib::FixedPoint8_8(substr($atom_data, 24, 2)); $atom_structure['reserved'] = substr($atom_data, 26, 10); $atom_structure['matrix_a'] = getid3_lib::FixedPoint16_16(substr($atom_data, 36, 4)); $atom_structure['matrix_b'] = getid3_lib::FixedPoint16_16(substr($atom_data, 40, 4)); $atom_structure['matrix_u'] = getid3_lib::FixedPoint2_30(substr($atom_data, 44, 4)); $atom_structure['matrix_c'] = getid3_lib::FixedPoint16_16(substr($atom_data, 48, 4)); $atom_structure['matrix_d'] = getid3_lib::FixedPoint16_16(substr($atom_data, 52, 4)); $atom_structure['matrix_v'] = getid3_lib::FixedPoint2_30(substr($atom_data, 56, 4)); $atom_structure['matrix_x'] = getid3_lib::FixedPoint16_16(substr($atom_data, 60, 4)); $atom_structure['matrix_y'] = getid3_lib::FixedPoint16_16(substr($atom_data, 64, 4)); $atom_structure['matrix_w'] = getid3_lib::FixedPoint2_30(substr($atom_data, 68, 4)); $atom_structure['preview_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 72, 4)); $atom_structure['preview_duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 76, 4)); $atom_structure['poster_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 80, 4)); $atom_structure['selection_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 84, 4)); $atom_structure['selection_duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 88, 4)); $atom_structure['current_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 92, 4)); $atom_structure['next_track_id'] = getid3_lib::BigEndian2Int(substr($atom_data, 96, 4)); if ($atom_structure['time_scale'] == 0) { $info['error'][] = 'Corrupt Quicktime file: mvhd.time_scale == zero'; return false; } $atom_structure['creation_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['creation_time']); $atom_structure['modify_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['modify_time']); $info['quicktime']['time_scale'] = (isset($info['quicktime']['time_scale']) ? max($info['quicktime']['time_scale'], $atom_structure['time_scale']) : $atom_structure['time_scale']); $info['quicktime']['display_scale'] = $atom_structure['matrix_a']; $info['playtime_seconds'] = $atom_structure['duration'] / $atom_structure['time_scale']; break; case 'tkhd': // TracK HeaDer atom $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); $atom_structure['creation_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $atom_structure['modify_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4)); $atom_structure['trackid'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 4)); $atom_structure['reserved1'] = getid3_lib::BigEndian2Int(substr($atom_data, 16, 4)); $atom_structure['duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 20, 4)); $atom_structure['reserved2'] = getid3_lib::BigEndian2Int(substr($atom_data, 24, 8)); $atom_structure['layer'] = getid3_lib::BigEndian2Int(substr($atom_data, 32, 2)); $atom_structure['alternate_group'] = getid3_lib::BigEndian2Int(substr($atom_data, 34, 2)); $atom_structure['volume'] = getid3_lib::FixedPoint8_8(substr($atom_data, 36, 2)); $atom_structure['reserved3'] = getid3_lib::BigEndian2Int(substr($atom_data, 38, 2)); // http://developer.apple.com/library/mac/#documentation/QuickTime/RM/MovieBasics/MTEditing/K-Chapter/11MatrixFunctions.html // http://developer.apple.com/library/mac/#documentation/QuickTime/qtff/QTFFChap4/qtff4.html#//apple_ref/doc/uid/TP40000939-CH206-18737 $atom_structure['matrix_a'] = getid3_lib::FixedPoint16_16(substr($atom_data, 40, 4)); $atom_structure['matrix_b'] = getid3_lib::FixedPoint16_16(substr($atom_data, 44, 4)); $atom_structure['matrix_u'] = getid3_lib::FixedPoint2_30(substr($atom_data, 48, 4)); $atom_structure['matrix_c'] = getid3_lib::FixedPoint16_16(substr($atom_data, 52, 4)); $atom_structure['matrix_d'] = getid3_lib::FixedPoint16_16(substr($atom_data, 56, 4)); $atom_structure['matrix_v'] = getid3_lib::FixedPoint2_30(substr($atom_data, 60, 4)); $atom_structure['matrix_x'] = getid3_lib::FixedPoint16_16(substr($atom_data, 64, 4)); $atom_structure['matrix_y'] = getid3_lib::FixedPoint16_16(substr($atom_data, 68, 4)); $atom_structure['matrix_w'] = getid3_lib::FixedPoint2_30(substr($atom_data, 72, 4)); $atom_structure['width'] = getid3_lib::FixedPoint16_16(substr($atom_data, 76, 4)); $atom_structure['height'] = getid3_lib::FixedPoint16_16(substr($atom_data, 80, 4)); $atom_structure['flags']['enabled'] = (bool) ($atom_structure['flags_raw'] & 0x0001); $atom_structure['flags']['in_movie'] = (bool) ($atom_structure['flags_raw'] & 0x0002); $atom_structure['flags']['in_preview'] = (bool) ($atom_structure['flags_raw'] & 0x0004); $atom_structure['flags']['in_poster'] = (bool) ($atom_structure['flags_raw'] & 0x0008); $atom_structure['creation_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['creation_time']); $atom_structure['modify_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['modify_time']); if ($atom_structure['flags']['enabled'] == 1) { if (!isset($info['video']['resolution_x']) || !isset($info['video']['resolution_y'])) { $info['video']['resolution_x'] = $atom_structure['width']; $info['video']['resolution_y'] = $atom_structure['height']; } $info['video']['resolution_x'] = max($info['video']['resolution_x'], $atom_structure['width']); $info['video']['resolution_y'] = max($info['video']['resolution_y'], $atom_structure['height']); $info['quicktime']['video']['resolution_x'] = $info['video']['resolution_x']; $info['quicktime']['video']['resolution_y'] = $info['video']['resolution_y']; } else { // see: http://www.getid3.org/phpBB3/viewtopic.php?t=1295 //if (isset($info['video']['resolution_x'])) { unset($info['video']['resolution_x']); } //if (isset($info['video']['resolution_y'])) { unset($info['video']['resolution_y']); } //if (isset($info['quicktime']['video'])) { unset($info['quicktime']['video']); } } break; case 'iods': // Initial Object DeScriptor atom // http://www.koders.com/c/fid1FAB3E762903DC482D8A246D4A4BF9F28E049594.aspx?s=windows.h // http://libquicktime.sourcearchive.com/documentation/1.0.2plus-pdebian/iods_8c-source.html $offset = 0; $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1)); $offset += 1; $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 3)); $offset += 3; $atom_structure['mp4_iod_tag'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1)); $offset += 1; $atom_structure['length'] = $this->quicktime_read_mp4_descr_length($atom_data, $offset); //$offset already adjusted by quicktime_read_mp4_descr_length() $atom_structure['object_descriptor_id'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 2)); $offset += 2; $atom_structure['od_profile_level'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1)); $offset += 1; $atom_structure['scene_profile_level'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1)); $offset += 1; $atom_structure['audio_profile_id'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1)); $offset += 1; $atom_structure['video_profile_id'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1)); $offset += 1; $atom_structure['graphics_profile_level'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1)); $offset += 1; $atom_structure['num_iods_tracks'] = ($atom_structure['length'] - 7) / 6; // 6 bytes would only be right if all tracks use 1-byte length fields for ($i = 0; $i < $atom_structure['num_iods_tracks']; $i++) { $atom_structure['track'][$i]['ES_ID_IncTag'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1)); $offset += 1; $atom_structure['track'][$i]['length'] = $this->quicktime_read_mp4_descr_length($atom_data, $offset); //$offset already adjusted by quicktime_read_mp4_descr_length() $atom_structure['track'][$i]['track_id'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 4)); $offset += 4; } $atom_structure['audio_profile_name'] = $this->QuicktimeIODSaudioProfileName($atom_structure['audio_profile_id']); $atom_structure['video_profile_name'] = $this->QuicktimeIODSvideoProfileName($atom_structure['video_profile_id']); break; case 'ftyp': // FileTYPe (?) atom (for MP4 it seems) $atom_structure['signature'] = substr($atom_data, 0, 4); $atom_structure['unknown_1'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4)); $atom_structure['fourcc'] = substr($atom_data, 8, 4); break; case 'mdat': // Media DATa atom case 'free': // FREE space atom case 'skip': // SKIP atom case 'wide': // 64-bit expansion placeholder atom // 'mdat' data is too big to deal with, contains no useful metadata // 'free', 'skip' and 'wide' are just padding, contains no useful data at all // When writing QuickTime files, it is sometimes necessary to update an atom's size. // It is impossible to update a 32-bit atom to a 64-bit atom since the 32-bit atom // is only 8 bytes in size, and the 64-bit atom requires 16 bytes. Therefore, QuickTime // puts an 8-byte placeholder atom before any atoms it may have to update the size of. // In this way, if the atom needs to be converted from a 32-bit to a 64-bit atom, the // placeholder atom can be overwritten to obtain the necessary 8 extra bytes. // The placeholder atom has a type of kWideAtomPlaceholderType ( 'wide' ). break; case 'nsav': // NoSAVe atom // http://developer.apple.com/technotes/tn/tn2038.html $atom_structure['data'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4)); break; case 'ctyp': // Controller TYPe atom (seen on QTVR) // http://homepages.slingshot.co.nz/~helmboy/quicktime/formats/qtm-layout.txt // some controller names are: // 0x00 + 'std' for linear movie // 'none' for no controls $atom_structure['ctyp'] = substr($atom_data, 0, 4); $info['quicktime']['controller'] = $atom_structure['ctyp']; switch ($atom_structure['ctyp']) { case 'qtvr': $info['video']['dataformat'] = 'quicktimevr'; break; } break; case 'pano': // PANOrama track (seen on QTVR) $atom_structure['pano'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4)); break; case 'hint': // HINT track case 'hinf': // case 'hinv': // case 'hnti': // $info['quicktime']['hinting'] = true; break; case 'imgt': // IMaGe Track reference (kQTVRImageTrackRefType) (seen on QTVR) for ($i = 0; $i < ($atom_structure['size'] - 8); $i += 4) { $atom_structure['imgt'][] = getid3_lib::BigEndian2Int(substr($atom_data, $i, 4)); } break; // Observed-but-not-handled atom types are just listed here to prevent warnings being generated case 'FXTC': // Something to do with Adobe After Effects (?) case 'PrmA': case 'code': case 'FIEL': // this is NOT "fiel" (Field Ordering) as describe here: http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap3/chapter_4_section_2.html case 'tapt': // TrackApertureModeDimensionsAID - http://developer.apple.com/documentation/QuickTime/Reference/QT7-1_Update_Reference/Constants/Constants.html // tapt seems to be used to compute the video size [http://www.getid3.org/phpBB3/viewtopic.php?t=838] // * http://lists.apple.com/archives/quicktime-api/2006/Aug/msg00014.html // * http://handbrake.fr/irclogs/handbrake-dev/handbrake-dev20080128_pg2.html case 'ctts':// STCompositionOffsetAID - http://developer.apple.com/documentation/QuickTime/Reference/QTRef_Constants/Reference/reference.html case 'cslg':// STCompositionShiftLeastGreatestAID - http://developer.apple.com/documentation/QuickTime/Reference/QTRef_Constants/Reference/reference.html case 'sdtp':// STSampleDependencyAID - http://developer.apple.com/documentation/QuickTime/Reference/QTRef_Constants/Reference/reference.html case 'stps':// STPartialSyncSampleAID - http://developer.apple.com/documentation/QuickTime/Reference/QTRef_Constants/Reference/reference.html //$atom_structure['data'] = $atom_data; break; case '©xyz': // GPS latitude+longitude+altitude $atom_structure['data'] = $atom_data; if (preg_match('#([\\+\\-][0-9\\.]+)([\\+\\-][0-9\\.]+)([\\+\\-][0-9\\.]+)?/$#i', $atom_data, $matches)) { @list($all, $latitude, $longitude, $altitude) = $matches; $info['quicktime']['comments']['gps_latitude'][] = floatval($latitude); $info['quicktime']['comments']['gps_longitude'][] = floatval($longitude); if (!empty($altitude)) { $info['quicktime']['comments']['gps_altitude'][] = floatval($altitude); } } else { $info['warning'][] = 'QuickTime atom "©xyz" data does not match expected data pattern at offset '.$baseoffset.'. Please report as getID3() bug.'; } break; case 'NCDT': // http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html // Nikon-specific QuickTime tags found in the NCDT atom of MOV videos from some Nikon cameras such as the Coolpix S8000 and D5100 $atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 4, $atomHierarchy, $ParseAllPossibleAtoms); break; case 'NCTH': // Nikon Camera THumbnail image case 'NCVW': // Nikon Camera preVieW image // http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html if (preg_match('/^\xFF\xD8\xFF/', $atom_data)) { $atom_structure['data'] = $atom_data; $atom_structure['image_mime'] = 'image/jpeg'; $atom_structure['description'] = (($atomname == 'NCTH') ? 'Nikon Camera Thumbnail Image' : (($atomname == 'NCVW') ? 'Nikon Camera Preview Image' : 'Nikon preview image')); $info['quicktime']['comments']['picture'][] = array('image_mime'=>$atom_structure['image_mime'], 'data'=>$atom_data, 'description'=>$atom_structure['description']); } break; case 'NCHD': // MakerNoteVersion // http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html $atom_structure['data'] = $atom_data; break; case 'NCTG': // NikonTags // http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html#NCTG $atom_structure['data'] = $this->QuicktimeParseNikonNCTG($atom_data); break; case 'NCDB': // NikonTags // http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html $atom_structure['data'] = $atom_data; break; case "\x00\x00\x00\x00": case 'meta': // METAdata atom // some kind of metacontainer, may contain a big data dump such as: // mdta keys  mdtacom.apple.quicktime.make (mdtacom.apple.quicktime.creationdate ,mdtacom.apple.quicktime.location.ISO6709 $mdtacom.apple.quicktime.software !mdtacom.apple.quicktime.model ilst   data DEApple 0  (data DE2011-05-11T17:54:04+0200 2  *data DE+52.4936+013.3897+040.247/   data DE4.3.1  data DEiPhone 4 // http://www.geocities.com/xhelmboyx/quicktime/formats/qti-layout.txt $atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1)); $atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); $atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom(substr($atom_data, 4), $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms); //$atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms); break; case 'data': // metaDATA atom // seems to be 2 bytes language code (ASCII), 2 bytes unknown (set to 0x10B5 in sample I have), remainder is useful data $atom_structure['language'] = substr($atom_data, 4 + 0, 2); $atom_structure['unknown'] = getid3_lib::BigEndian2Int(substr($atom_data, 4 + 2, 2)); $atom_structure['data'] = substr($atom_data, 4 + 4); break; default: $info['warning'][] = 'Unknown QuickTime atom type: "'.$atomname.'" ('.trim(getid3_lib::PrintHexBytes($atomname)).') at offset '.$baseoffset; $atom_structure['data'] = $atom_data; break; } array_pop($atomHierarchy); return $atom_structure; } public function QuicktimeParseContainerAtom($atom_data, $baseoffset, &$atomHierarchy, $ParseAllPossibleAtoms) { //echo 'QuicktimeParseContainerAtom('.substr($atom_data, 4, 4).') @ '.$baseoffset.'<br><br>'; $atom_structure = false; $subatomoffset = 0; $subatomcounter = 0; if ((strlen($atom_data) == 4) && (getid3_lib::BigEndian2Int($atom_data) == 0x00000000)) { return false; } while ($subatomoffset < strlen($atom_data)) { $subatomsize = getid3_lib::BigEndian2Int(substr($atom_data, $subatomoffset + 0, 4)); $subatomname = substr($atom_data, $subatomoffset + 4, 4); $subatomdata = substr($atom_data, $subatomoffset + 8, $subatomsize - 8); if ($subatomsize == 0) { // Furthermore, for historical reasons the list of atoms is optionally // terminated by a 32-bit integer set to 0. If you are writing a program // to read user data atoms, you should allow for the terminating 0. return $atom_structure; } $atom_structure[$subatomcounter] = $this->QuicktimeParseAtom($subatomname, $subatomsize, $subatomdata, $baseoffset + $subatomoffset, $atomHierarchy, $ParseAllPossibleAtoms); $subatomoffset += $subatomsize; $subatomcounter++; } return $atom_structure; } public function quicktime_read_mp4_descr_length($data, &$offset) { // http://libquicktime.sourcearchive.com/documentation/2:1.0.2plus-pdebian-2build1/esds_8c-source.html $num_bytes = 0; $length = 0; do { $b = ord(substr($data, $offset++, 1)); $length = ($length << 7) | ($b & 0x7F); } while (($b & 0x80) && ($num_bytes++ < 4)); return $length; } public function QuicktimeLanguageLookup($languageid) { // http://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html#//apple_ref/doc/uid/TP40000939-CH206-34353 static $QuicktimeLanguageLookup = array(); if (empty($QuicktimeLanguageLookup)) { $QuicktimeLanguageLookup[0] = 'English'; $QuicktimeLanguageLookup[1] = 'French'; $QuicktimeLanguageLookup[2] = 'German'; $QuicktimeLanguageLookup[3] = 'Italian'; $QuicktimeLanguageLookup[4] = 'Dutch'; $QuicktimeLanguageLookup[5] = 'Swedish'; $QuicktimeLanguageLookup[6] = 'Spanish'; $QuicktimeLanguageLookup[7] = 'Danish'; $QuicktimeLanguageLookup[8] = 'Portuguese'; $QuicktimeLanguageLookup[9] = 'Norwegian'; $QuicktimeLanguageLookup[10] = 'Hebrew'; $QuicktimeLanguageLookup[11] = 'Japanese'; $QuicktimeLanguageLookup[12] = 'Arabic'; $QuicktimeLanguageLookup[13] = 'Finnish'; $QuicktimeLanguageLookup[14] = 'Greek'; $QuicktimeLanguageLookup[15] = 'Icelandic'; $QuicktimeLanguageLookup[16] = 'Maltese'; $QuicktimeLanguageLookup[17] = 'Turkish'; $QuicktimeLanguageLookup[18] = 'Croatian'; $QuicktimeLanguageLookup[19] = 'Chinese (Traditional)'; $QuicktimeLanguageLookup[20] = 'Urdu'; $QuicktimeLanguageLookup[21] = 'Hindi'; $QuicktimeLanguageLookup[22] = 'Thai'; $QuicktimeLanguageLookup[23] = 'Korean'; $QuicktimeLanguageLookup[24] = 'Lithuanian'; $QuicktimeLanguageLookup[25] = 'Polish'; $QuicktimeLanguageLookup[26] = 'Hungarian'; $QuicktimeLanguageLookup[27] = 'Estonian'; $QuicktimeLanguageLookup[28] = 'Lettish'; $QuicktimeLanguageLookup[28] = 'Latvian'; $QuicktimeLanguageLookup[29] = 'Saamisk'; $QuicktimeLanguageLookup[29] = 'Lappish'; $QuicktimeLanguageLookup[30] = 'Faeroese'; $QuicktimeLanguageLookup[31] = 'Farsi'; $QuicktimeLanguageLookup[31] = 'Persian'; $QuicktimeLanguageLookup[32] = 'Russian'; $QuicktimeLanguageLookup[33] = 'Chinese (Simplified)'; $QuicktimeLanguageLookup[34] = 'Flemish'; $QuicktimeLanguageLookup[35] = 'Irish'; $QuicktimeLanguageLookup[36] = 'Albanian'; $QuicktimeLanguageLookup[37] = 'Romanian'; $QuicktimeLanguageLookup[38] = 'Czech'; $QuicktimeLanguageLookup[39] = 'Slovak'; $QuicktimeLanguageLookup[40] = 'Slovenian'; $QuicktimeLanguageLookup[41] = 'Yiddish'; $QuicktimeLanguageLookup[42] = 'Serbian'; $QuicktimeLanguageLookup[43] = 'Macedonian'; $QuicktimeLanguageLookup[44] = 'Bulgarian'; $QuicktimeLanguageLookup[45] = 'Ukrainian'; $QuicktimeLanguageLookup[46] = 'Byelorussian'; $QuicktimeLanguageLookup[47] = 'Uzbek'; $QuicktimeLanguageLookup[48] = 'Kazakh'; $QuicktimeLanguageLookup[49] = 'Azerbaijani'; $QuicktimeLanguageLookup[50] = 'AzerbaijanAr'; $QuicktimeLanguageLookup[51] = 'Armenian'; $QuicktimeLanguageLookup[52] = 'Georgian'; $QuicktimeLanguageLookup[53] = 'Moldavian'; $QuicktimeLanguageLookup[54] = 'Kirghiz'; $QuicktimeLanguageLookup[55] = 'Tajiki'; $QuicktimeLanguageLookup[56] = 'Turkmen'; $QuicktimeLanguageLookup[57] = 'Mongolian'; $QuicktimeLanguageLookup[58] = 'MongolianCyr'; $QuicktimeLanguageLookup[59] = 'Pashto'; $QuicktimeLanguageLookup[60] = 'Kurdish'; $QuicktimeLanguageLookup[61] = 'Kashmiri'; $QuicktimeLanguageLookup[62] = 'Sindhi'; $QuicktimeLanguageLookup[63] = 'Tibetan'; $QuicktimeLanguageLookup[64] = 'Nepali'; $QuicktimeLanguageLookup[65] = 'Sanskrit'; $QuicktimeLanguageLookup[66] = 'Marathi'; $QuicktimeLanguageLookup[67] = 'Bengali'; $QuicktimeLanguageLookup[68] = 'Assamese'; $QuicktimeLanguageLookup[69] = 'Gujarati'; $QuicktimeLanguageLookup[70] = 'Punjabi'; $QuicktimeLanguageLookup[71] = 'Oriya'; $QuicktimeLanguageLookup[72] = 'Malayalam'; $QuicktimeLanguageLookup[73] = 'Kannada'; $QuicktimeLanguageLookup[74] = 'Tamil'; $QuicktimeLanguageLookup[75] = 'Telugu'; $QuicktimeLanguageLookup[76] = 'Sinhalese'; $QuicktimeLanguageLookup[77] = 'Burmese'; $QuicktimeLanguageLookup[78] = 'Khmer'; $QuicktimeLanguageLookup[79] = 'Lao'; $QuicktimeLanguageLookup[80] = 'Vietnamese'; $QuicktimeLanguageLookup[81] = 'Indonesian'; $QuicktimeLanguageLookup[82] = 'Tagalog'; $QuicktimeLanguageLookup[83] = 'MalayRoman'; $QuicktimeLanguageLookup[84] = 'MalayArabic'; $QuicktimeLanguageLookup[85] = 'Amharic'; $QuicktimeLanguageLookup[86] = 'Tigrinya'; $QuicktimeLanguageLookup[87] = 'Galla'; $QuicktimeLanguageLookup[87] = 'Oromo'; $QuicktimeLanguageLookup[88] = 'Somali'; $QuicktimeLanguageLookup[89] = 'Swahili'; $QuicktimeLanguageLookup[90] = 'Ruanda'; $QuicktimeLanguageLookup[91] = 'Rundi'; $QuicktimeLanguageLookup[92] = 'Chewa'; $QuicktimeLanguageLookup[93] = 'Malagasy'; $QuicktimeLanguageLookup[94] = 'Esperanto'; $QuicktimeLanguageLookup[128] = 'Welsh'; $QuicktimeLanguageLookup[129] = 'Basque'; $QuicktimeLanguageLookup[130] = 'Catalan'; $QuicktimeLanguageLookup[131] = 'Latin'; $QuicktimeLanguageLookup[132] = 'Quechua'; $QuicktimeLanguageLookup[133] = 'Guarani'; $QuicktimeLanguageLookup[134] = 'Aymara'; $QuicktimeLanguageLookup[135] = 'Tatar'; $QuicktimeLanguageLookup[136] = 'Uighur'; $QuicktimeLanguageLookup[137] = 'Dzongkha'; $QuicktimeLanguageLookup[138] = 'JavaneseRom'; $QuicktimeLanguageLookup[32767] = 'Unspecified'; } if (($languageid > 138) && ($languageid < 32767)) { /* ISO Language Codes - http://www.loc.gov/standards/iso639-2/php/code_list.php Because the language codes specified by ISO 639-2/T are three characters long, they must be packed to fit into a 16-bit field. The packing algorithm must map each of the three characters, which are always lowercase, into a 5-bit integer and then concatenate these integers into the least significant 15 bits of a 16-bit integer, leaving the 16-bit integer's most significant bit set to zero. One algorithm for performing this packing is to treat each ISO character as a 16-bit integer. Subtract 0x60 from the first character and multiply by 2^10 (0x400), subtract 0x60 from the second character and multiply by 2^5 (0x20), subtract 0x60 from the third character, and add the three 16-bit values. This will result in a single 16-bit value with the three codes correctly packed into the 15 least significant bits and the most significant bit set to zero. */ $iso_language_id = ''; $iso_language_id .= chr((($languageid & 0x7C00) >> 10) + 0x60); $iso_language_id .= chr((($languageid & 0x03E0) >> 5) + 0x60); $iso_language_id .= chr((($languageid & 0x001F) >> 0) + 0x60); $QuicktimeLanguageLookup[$languageid] = getid3_id3v2::LanguageLookup($iso_language_id); } return (isset($QuicktimeLanguageLookup[$languageid]) ? $QuicktimeLanguageLookup[$languageid] : 'invalid'); } public function QuicktimeVideoCodecLookup($codecid) { static $QuicktimeVideoCodecLookup = array(); if (empty($QuicktimeVideoCodecLookup)) { $QuicktimeVideoCodecLookup['.SGI'] = 'SGI'; $QuicktimeVideoCodecLookup['3IV1'] = '3ivx MPEG-4 v1'; $QuicktimeVideoCodecLookup['3IV2'] = '3ivx MPEG-4 v2'; $QuicktimeVideoCodecLookup['3IVX'] = '3ivx MPEG-4'; $QuicktimeVideoCodecLookup['8BPS'] = 'Planar RGB'; $QuicktimeVideoCodecLookup['avc1'] = 'H.264/MPEG-4 AVC'; $QuicktimeVideoCodecLookup['avr '] = 'AVR-JPEG'; $QuicktimeVideoCodecLookup['b16g'] = '16Gray'; $QuicktimeVideoCodecLookup['b32a'] = '32AlphaGray'; $QuicktimeVideoCodecLookup['b48r'] = '48RGB'; $QuicktimeVideoCodecLookup['b64a'] = '64ARGB'; $QuicktimeVideoCodecLookup['base'] = 'Base'; $QuicktimeVideoCodecLookup['clou'] = 'Cloud'; $QuicktimeVideoCodecLookup['cmyk'] = 'CMYK'; $QuicktimeVideoCodecLookup['cvid'] = 'Cinepak'; $QuicktimeVideoCodecLookup['dmb1'] = 'OpenDML JPEG'; $QuicktimeVideoCodecLookup['dvc '] = 'DVC-NTSC'; $QuicktimeVideoCodecLookup['dvcp'] = 'DVC-PAL'; $QuicktimeVideoCodecLookup['dvpn'] = 'DVCPro-NTSC'; $QuicktimeVideoCodecLookup['dvpp'] = 'DVCPro-PAL'; $QuicktimeVideoCodecLookup['fire'] = 'Fire'; $QuicktimeVideoCodecLookup['flic'] = 'FLC'; $QuicktimeVideoCodecLookup['gif '] = 'GIF'; $QuicktimeVideoCodecLookup['h261'] = 'H261'; $QuicktimeVideoCodecLookup['h263'] = 'H263'; $QuicktimeVideoCodecLookup['IV41'] = 'Indeo4'; $QuicktimeVideoCodecLookup['jpeg'] = 'JPEG'; $QuicktimeVideoCodecLookup['kpcd'] = 'PhotoCD'; $QuicktimeVideoCodecLookup['mjpa'] = 'Motion JPEG-A'; $QuicktimeVideoCodecLookup['mjpb'] = 'Motion JPEG-B'; $QuicktimeVideoCodecLookup['msvc'] = 'Microsoft Video1'; $QuicktimeVideoCodecLookup['myuv'] = 'MPEG YUV420'; $QuicktimeVideoCodecLookup['path'] = 'Vector'; $QuicktimeVideoCodecLookup['png '] = 'PNG'; $QuicktimeVideoCodecLookup['PNTG'] = 'MacPaint'; $QuicktimeVideoCodecLookup['qdgx'] = 'QuickDrawGX'; $QuicktimeVideoCodecLookup['qdrw'] = 'QuickDraw'; $QuicktimeVideoCodecLookup['raw '] = 'RAW'; $QuicktimeVideoCodecLookup['ripl'] = 'WaterRipple'; $QuicktimeVideoCodecLookup['rpza'] = 'Video'; $QuicktimeVideoCodecLookup['smc '] = 'Graphics'; $QuicktimeVideoCodecLookup['SVQ1'] = 'Sorenson Video 1'; $QuicktimeVideoCodecLookup['SVQ1'] = 'Sorenson Video 3'; $QuicktimeVideoCodecLookup['syv9'] = 'Sorenson YUV9'; $QuicktimeVideoCodecLookup['tga '] = 'Targa'; $QuicktimeVideoCodecLookup['tiff'] = 'TIFF'; $QuicktimeVideoCodecLookup['WRAW'] = 'Windows RAW'; $QuicktimeVideoCodecLookup['WRLE'] = 'BMP'; $QuicktimeVideoCodecLookup['y420'] = 'YUV420'; $QuicktimeVideoCodecLookup['yuv2'] = 'ComponentVideo'; $QuicktimeVideoCodecLookup['yuvs'] = 'ComponentVideoUnsigned'; $QuicktimeVideoCodecLookup['yuvu'] = 'ComponentVideoSigned'; } return (isset($QuicktimeVideoCodecLookup[$codecid]) ? $QuicktimeVideoCodecLookup[$codecid] : ''); } public function QuicktimeAudioCodecLookup($codecid) { static $QuicktimeAudioCodecLookup = array(); if (empty($QuicktimeAudioCodecLookup)) { $QuicktimeAudioCodecLookup['.mp3'] = 'Fraunhofer MPEG Layer-III alias'; $QuicktimeAudioCodecLookup['aac '] = 'ISO/IEC 14496-3 AAC'; $QuicktimeAudioCodecLookup['agsm'] = 'Apple GSM 10:1'; $QuicktimeAudioCodecLookup['alac'] = 'Apple Lossless Audio Codec'; $QuicktimeAudioCodecLookup['alaw'] = 'A-law 2:1'; $QuicktimeAudioCodecLookup['conv'] = 'Sample Format'; $QuicktimeAudioCodecLookup['dvca'] = 'DV'; $QuicktimeAudioCodecLookup['dvi '] = 'DV 4:1'; $QuicktimeAudioCodecLookup['eqal'] = 'Frequency Equalizer'; $QuicktimeAudioCodecLookup['fl32'] = '32-bit Floating Point'; $QuicktimeAudioCodecLookup['fl64'] = '64-bit Floating Point'; $QuicktimeAudioCodecLookup['ima4'] = 'Interactive Multimedia Association 4:1'; $QuicktimeAudioCodecLookup['in24'] = '24-bit Integer'; $QuicktimeAudioCodecLookup['in32'] = '32-bit Integer'; $QuicktimeAudioCodecLookup['lpc '] = 'LPC 23:1'; $QuicktimeAudioCodecLookup['MAC3'] = 'Macintosh Audio Compression/Expansion (MACE) 3:1'; $QuicktimeAudioCodecLookup['MAC6'] = 'Macintosh Audio Compression/Expansion (MACE) 6:1'; $QuicktimeAudioCodecLookup['mixb'] = '8-bit Mixer'; $QuicktimeAudioCodecLookup['mixw'] = '16-bit Mixer'; $QuicktimeAudioCodecLookup['mp4a'] = 'ISO/IEC 14496-3 AAC'; $QuicktimeAudioCodecLookup['MS'."\x00\x02"] = 'Microsoft ADPCM'; $QuicktimeAudioCodecLookup['MS'."\x00\x11"] = 'DV IMA'; $QuicktimeAudioCodecLookup['MS'."\x00\x55"] = 'Fraunhofer MPEG Layer III'; $QuicktimeAudioCodecLookup['NONE'] = 'No Encoding'; $QuicktimeAudioCodecLookup['Qclp'] = 'Qualcomm PureVoice'; $QuicktimeAudioCodecLookup['QDM2'] = 'QDesign Music 2'; $QuicktimeAudioCodecLookup['QDMC'] = 'QDesign Music 1'; $QuicktimeAudioCodecLookup['ratb'] = '8-bit Rate'; $QuicktimeAudioCodecLookup['ratw'] = '16-bit Rate'; $QuicktimeAudioCodecLookup['raw '] = 'raw PCM'; $QuicktimeAudioCodecLookup['sour'] = 'Sound Source'; $QuicktimeAudioCodecLookup['sowt'] = 'signed/two\'s complement (Little Endian)'; $QuicktimeAudioCodecLookup['str1'] = 'Iomega MPEG layer II'; $QuicktimeAudioCodecLookup['str2'] = 'Iomega MPEG *layer II'; $QuicktimeAudioCodecLookup['str3'] = 'Iomega MPEG **layer II'; $QuicktimeAudioCodecLookup['str4'] = 'Iomega MPEG ***layer II'; $QuicktimeAudioCodecLookup['twos'] = 'signed/two\'s complement (Big Endian)'; $QuicktimeAudioCodecLookup['ulaw'] = 'mu-law 2:1'; } return (isset($QuicktimeAudioCodecLookup[$codecid]) ? $QuicktimeAudioCodecLookup[$codecid] : ''); } public function QuicktimeDCOMLookup($compressionid) { static $QuicktimeDCOMLookup = array(); if (empty($QuicktimeDCOMLookup)) { $QuicktimeDCOMLookup['zlib'] = 'ZLib Deflate'; $QuicktimeDCOMLookup['adec'] = 'Apple Compression'; } return (isset($QuicktimeDCOMLookup[$compressionid]) ? $QuicktimeDCOMLookup[$compressionid] : ''); } public function QuicktimeColorNameLookup($colordepthid) { static $QuicktimeColorNameLookup = array(); if (empty($QuicktimeColorNameLookup)) { $QuicktimeColorNameLookup[1] = '2-color (monochrome)'; $QuicktimeColorNameLookup[2] = '4-color'; $QuicktimeColorNameLookup[4] = '16-color'; $QuicktimeColorNameLookup[8] = '256-color'; $QuicktimeColorNameLookup[16] = 'thousands (16-bit color)'; $QuicktimeColorNameLookup[24] = 'millions (24-bit color)'; $QuicktimeColorNameLookup[32] = 'millions+ (32-bit color)'; $QuicktimeColorNameLookup[33] = 'black & white'; $QuicktimeColorNameLookup[34] = '4-gray'; $QuicktimeColorNameLookup[36] = '16-gray'; $QuicktimeColorNameLookup[40] = '256-gray'; } return (isset($QuicktimeColorNameLookup[$colordepthid]) ? $QuicktimeColorNameLookup[$colordepthid] : 'invalid'); } public function QuicktimeSTIKLookup($stik) { static $QuicktimeSTIKLookup = array(); if (empty($QuicktimeSTIKLookup)) { $QuicktimeSTIKLookup[0] = 'Movie'; $QuicktimeSTIKLookup[1] = 'Normal'; $QuicktimeSTIKLookup[2] = 'Audiobook'; $QuicktimeSTIKLookup[5] = 'Whacked Bookmark'; $QuicktimeSTIKLookup[6] = 'Music Video'; $QuicktimeSTIKLookup[9] = 'Short Film'; $QuicktimeSTIKLookup[10] = 'TV Show'; $QuicktimeSTIKLookup[11] = 'Booklet'; $QuicktimeSTIKLookup[14] = 'Ringtone'; $QuicktimeSTIKLookup[21] = 'Podcast'; } return (isset($QuicktimeSTIKLookup[$stik]) ? $QuicktimeSTIKLookup[$stik] : 'invalid'); } public function QuicktimeIODSaudioProfileName($audio_profile_id) { static $QuicktimeIODSaudioProfileNameLookup = array(); if (empty($QuicktimeIODSaudioProfileNameLookup)) { $QuicktimeIODSaudioProfileNameLookup = array( 0x00 => 'ISO Reserved (0x00)', 0x01 => 'Main Audio Profile @ Level 1', 0x02 => 'Main Audio Profile @ Level 2', 0x03 => 'Main Audio Profile @ Level 3', 0x04 => 'Main Audio Profile @ Level 4', 0x05 => 'Scalable Audio Profile @ Level 1', 0x06 => 'Scalable Audio Profile @ Level 2', 0x07 => 'Scalable Audio Profile @ Level 3', 0x08 => 'Scalable Audio Profile @ Level 4', 0x09 => 'Speech Audio Profile @ Level 1', 0x0A => 'Speech Audio Profile @ Level 2', 0x0B => 'Synthetic Audio Profile @ Level 1', 0x0C => 'Synthetic Audio Profile @ Level 2', 0x0D => 'Synthetic Audio Profile @ Level 3', 0x0E => 'High Quality Audio Profile @ Level 1', 0x0F => 'High Quality Audio Profile @ Level 2', 0x10 => 'High Quality Audio Profile @ Level 3', 0x11 => 'High Quality Audio Profile @ Level 4', 0x12 => 'High Quality Audio Profile @ Level 5', 0x13 => 'High Quality Audio Profile @ Level 6', 0x14 => 'High Quality Audio Profile @ Level 7', 0x15 => 'High Quality Audio Profile @ Level 8', 0x16 => 'Low Delay Audio Profile @ Level 1', 0x17 => 'Low Delay Audio Profile @ Level 2', 0x18 => 'Low Delay Audio Profile @ Level 3', 0x19 => 'Low Delay Audio Profile @ Level 4', 0x1A => 'Low Delay Audio Profile @ Level 5', 0x1B => 'Low Delay Audio Profile @ Level 6', 0x1C => 'Low Delay Audio Profile @ Level 7', 0x1D => 'Low Delay Audio Profile @ Level 8', 0x1E => 'Natural Audio Profile @ Level 1', 0x1F => 'Natural Audio Profile @ Level 2', 0x20 => 'Natural Audio Profile @ Level 3', 0x21 => 'Natural Audio Profile @ Level 4', 0x22 => 'Mobile Audio Internetworking Profile @ Level 1', 0x23 => 'Mobile Audio Internetworking Profile @ Level 2', 0x24 => 'Mobile Audio Internetworking Profile @ Level 3', 0x25 => 'Mobile Audio Internetworking Profile @ Level 4', 0x26 => 'Mobile Audio Internetworking Profile @ Level 5', 0x27 => 'Mobile Audio Internetworking Profile @ Level 6', 0x28 => 'AAC Profile @ Level 1', 0x29 => 'AAC Profile @ Level 2', 0x2A => 'AAC Profile @ Level 4', 0x2B => 'AAC Profile @ Level 5', 0x2C => 'High Efficiency AAC Profile @ Level 2', 0x2D => 'High Efficiency AAC Profile @ Level 3', 0x2E => 'High Efficiency AAC Profile @ Level 4', 0x2F => 'High Efficiency AAC Profile @ Level 5', 0xFE => 'Not part of MPEG-4 audio profiles', 0xFF => 'No audio capability required', ); } return (isset($QuicktimeIODSaudioProfileNameLookup[$audio_profile_id]) ? $QuicktimeIODSaudioProfileNameLookup[$audio_profile_id] : 'ISO Reserved / User Private'); } public function QuicktimeIODSvideoProfileName($video_profile_id) { static $QuicktimeIODSvideoProfileNameLookup = array(); if (empty($QuicktimeIODSvideoProfileNameLookup)) { $QuicktimeIODSvideoProfileNameLookup = array( 0x00 => 'Reserved (0x00) Profile', 0x01 => 'Simple Profile @ Level 1', 0x02 => 'Simple Profile @ Level 2', 0x03 => 'Simple Profile @ Level 3', 0x08 => 'Simple Profile @ Level 0', 0x10 => 'Simple Scalable Profile @ Level 0', 0x11 => 'Simple Scalable Profile @ Level 1', 0x12 => 'Simple Scalable Profile @ Level 2', 0x15 => 'AVC/H264 Profile', 0x21 => 'Core Profile @ Level 1', 0x22 => 'Core Profile @ Level 2', 0x32 => 'Main Profile @ Level 2', 0x33 => 'Main Profile @ Level 3', 0x34 => 'Main Profile @ Level 4', 0x42 => 'N-bit Profile @ Level 2', 0x51 => 'Scalable Texture Profile @ Level 1', 0x61 => 'Simple Face Animation Profile @ Level 1', 0x62 => 'Simple Face Animation Profile @ Level 2', 0x63 => 'Simple FBA Profile @ Level 1', 0x64 => 'Simple FBA Profile @ Level 2', 0x71 => 'Basic Animated Texture Profile @ Level 1', 0x72 => 'Basic Animated Texture Profile @ Level 2', 0x81 => 'Hybrid Profile @ Level 1', 0x82 => 'Hybrid Profile @ Level 2', 0x91 => 'Advanced Real Time Simple Profile @ Level 1', 0x92 => 'Advanced Real Time Simple Profile @ Level 2', 0x93 => 'Advanced Real Time Simple Profile @ Level 3', 0x94 => 'Advanced Real Time Simple Profile @ Level 4', 0xA1 => 'Core Scalable Profile @ Level1', 0xA2 => 'Core Scalable Profile @ Level2', 0xA3 => 'Core Scalable Profile @ Level3', 0xB1 => 'Advanced Coding Efficiency Profile @ Level 1', 0xB2 => 'Advanced Coding Efficiency Profile @ Level 2', 0xB3 => 'Advanced Coding Efficiency Profile @ Level 3', 0xB4 => 'Advanced Coding Efficiency Profile @ Level 4', 0xC1 => 'Advanced Core Profile @ Level 1', 0xC2 => 'Advanced Core Profile @ Level 2', 0xD1 => 'Advanced Scalable Texture @ Level1', 0xD2 => 'Advanced Scalable Texture @ Level2', 0xE1 => 'Simple Studio Profile @ Level 1', 0xE2 => 'Simple Studio Profile @ Level 2', 0xE3 => 'Simple Studio Profile @ Level 3', 0xE4 => 'Simple Studio Profile @ Level 4', 0xE5 => 'Core Studio Profile @ Level 1', 0xE6 => 'Core Studio Profile @ Level 2', 0xE7 => 'Core Studio Profile @ Level 3', 0xE8 => 'Core Studio Profile @ Level 4', 0xF0 => 'Advanced Simple Profile @ Level 0', 0xF1 => 'Advanced Simple Profile @ Level 1', 0xF2 => 'Advanced Simple Profile @ Level 2', 0xF3 => 'Advanced Simple Profile @ Level 3', 0xF4 => 'Advanced Simple Profile @ Level 4', 0xF5 => 'Advanced Simple Profile @ Level 5', 0xF7 => 'Advanced Simple Profile @ Level 3b', 0xF8 => 'Fine Granularity Scalable Profile @ Level 0', 0xF9 => 'Fine Granularity Scalable Profile @ Level 1', 0xFA => 'Fine Granularity Scalable Profile @ Level 2', 0xFB => 'Fine Granularity Scalable Profile @ Level 3', 0xFC => 'Fine Granularity Scalable Profile @ Level 4', 0xFD => 'Fine Granularity Scalable Profile @ Level 5', 0xFE => 'Not part of MPEG-4 Visual profiles', 0xFF => 'No visual capability required', ); } return (isset($QuicktimeIODSvideoProfileNameLookup[$video_profile_id]) ? $QuicktimeIODSvideoProfileNameLookup[$video_profile_id] : 'ISO Reserved Profile'); } public function QuicktimeContentRatingLookup($rtng) { static $QuicktimeContentRatingLookup = array(); if (empty($QuicktimeContentRatingLookup)) { $QuicktimeContentRatingLookup[0] = 'None'; $QuicktimeContentRatingLookup[2] = 'Clean'; $QuicktimeContentRatingLookup[4] = 'Explicit'; } return (isset($QuicktimeContentRatingLookup[$rtng]) ? $QuicktimeContentRatingLookup[$rtng] : 'invalid'); } public function QuicktimeStoreAccountTypeLookup($akid) { static $QuicktimeStoreAccountTypeLookup = array(); if (empty($QuicktimeStoreAccountTypeLookup)) { $QuicktimeStoreAccountTypeLookup[0] = 'iTunes'; $QuicktimeStoreAccountTypeLookup[1] = 'AOL'; } return (isset($QuicktimeStoreAccountTypeLookup[$akid]) ? $QuicktimeStoreAccountTypeLookup[$akid] : 'invalid'); } public function QuicktimeStoreFrontCodeLookup($sfid) { static $QuicktimeStoreFrontCodeLookup = array(); if (empty($QuicktimeStoreFrontCodeLookup)) { $QuicktimeStoreFrontCodeLookup[143460] = 'Australia'; $QuicktimeStoreFrontCodeLookup[143445] = 'Austria'; $QuicktimeStoreFrontCodeLookup[143446] = 'Belgium'; $QuicktimeStoreFrontCodeLookup[143455] = 'Canada'; $QuicktimeStoreFrontCodeLookup[143458] = 'Denmark'; $QuicktimeStoreFrontCodeLookup[143447] = 'Finland'; $QuicktimeStoreFrontCodeLookup[143442] = 'France'; $QuicktimeStoreFrontCodeLookup[143443] = 'Germany'; $QuicktimeStoreFrontCodeLookup[143448] = 'Greece'; $QuicktimeStoreFrontCodeLookup[143449] = 'Ireland'; $QuicktimeStoreFrontCodeLookup[143450] = 'Italy'; $QuicktimeStoreFrontCodeLookup[143462] = 'Japan'; $QuicktimeStoreFrontCodeLookup[143451] = 'Luxembourg'; $QuicktimeStoreFrontCodeLookup[143452] = 'Netherlands'; $QuicktimeStoreFrontCodeLookup[143461] = 'New Zealand'; $QuicktimeStoreFrontCodeLookup[143457] = 'Norway'; $QuicktimeStoreFrontCodeLookup[143453] = 'Portugal'; $QuicktimeStoreFrontCodeLookup[143454] = 'Spain'; $QuicktimeStoreFrontCodeLookup[143456] = 'Sweden'; $QuicktimeStoreFrontCodeLookup[143459] = 'Switzerland'; $QuicktimeStoreFrontCodeLookup[143444] = 'United Kingdom'; $QuicktimeStoreFrontCodeLookup[143441] = 'United States'; } return (isset($QuicktimeStoreFrontCodeLookup[$sfid]) ? $QuicktimeStoreFrontCodeLookup[$sfid] : 'invalid'); } public function QuicktimeParseNikonNCTG($atom_data) { // http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html#NCTG // Nikon-specific QuickTime tags found in the NCDT atom of MOV videos from some Nikon cameras such as the Coolpix S8000 and D5100 // Data is stored as records of: // * 4 bytes record type // * 2 bytes size of data field type: // 0x0001 = flag (size field *= 1-byte) // 0x0002 = char (size field *= 1-byte) // 0x0003 = DWORD+ (size field *= 2-byte), values are stored CDAB // 0x0004 = QWORD+ (size field *= 4-byte), values are stored EFGHABCD // 0x0005 = float (size field *= 8-byte), values are stored aaaabbbb where value is aaaa/bbbb; possibly multiple sets of values appended together // 0x0007 = bytes (size field *= 1-byte), values are stored as ?????? // 0x0008 = ????? (size field *= 2-byte), values are stored as ?????? // * 2 bytes data size field // * ? bytes data (string data may be null-padded; datestamp fields are in the format "2011:05:25 20:24:15") // all integers are stored BigEndian $NCTGtagName = array( 0x00000001 => 'Make', 0x00000002 => 'Model', 0x00000003 => 'Software', 0x00000011 => 'CreateDate', 0x00000012 => 'DateTimeOriginal', 0x00000013 => 'FrameCount', 0x00000016 => 'FrameRate', 0x00000022 => 'FrameWidth', 0x00000023 => 'FrameHeight', 0x00000032 => 'AudioChannels', 0x00000033 => 'AudioBitsPerSample', 0x00000034 => 'AudioSampleRate', 0x02000001 => 'MakerNoteVersion', 0x02000005 => 'WhiteBalance', 0x0200000b => 'WhiteBalanceFineTune', 0x0200001e => 'ColorSpace', 0x02000023 => 'PictureControlData', 0x02000024 => 'WorldTime', 0x02000032 => 'UnknownInfo', 0x02000083 => 'LensType', 0x02000084 => 'Lens', ); $offset = 0; $datalength = strlen($atom_data); $parsed = array(); while ($offset < $datalength) { //echo getid3_lib::PrintHexBytes(substr($atom_data, $offset, 4)).'<br>'; $record_type = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 4)); $offset += 4; $data_size_type = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 2)); $offset += 2; $data_size = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 2)); $offset += 2; switch ($data_size_type) { case 0x0001: // 0x0001 = flag (size field *= 1-byte) $data = getid3_lib::BigEndian2Int(substr($atom_data, $offset, $data_size * 1)); $offset += ($data_size * 1); break; case 0x0002: // 0x0002 = char (size field *= 1-byte) $data = substr($atom_data, $offset, $data_size * 1); $offset += ($data_size * 1); $data = rtrim($data, "\x00"); break; case 0x0003: // 0x0003 = DWORD+ (size field *= 2-byte), values are stored CDAB $data = ''; for ($i = $data_size - 1; $i >= 0; $i--) { $data .= substr($atom_data, $offset + ($i * 2), 2); } $data = getid3_lib::BigEndian2Int($data); $offset += ($data_size * 2); break; case 0x0004: // 0x0004 = QWORD+ (size field *= 4-byte), values are stored EFGHABCD $data = ''; for ($i = $data_size - 1; $i >= 0; $i--) { $data .= substr($atom_data, $offset + ($i * 4), 4); } $data = getid3_lib::BigEndian2Int($data); $offset += ($data_size * 4); break; case 0x0005: // 0x0005 = float (size field *= 8-byte), values are stored aaaabbbb where value is aaaa/bbbb; possibly multiple sets of values appended together $data = array(); for ($i = 0; $i < $data_size; $i++) { $numerator = getid3_lib::BigEndian2Int(substr($atom_data, $offset + ($i * 8) + 0, 4)); $denomninator = getid3_lib::BigEndian2Int(substr($atom_data, $offset + ($i * 8) + 4, 4)); if ($denomninator == 0) { $data[$i] = false; } else { $data[$i] = (double) $numerator / $denomninator; } } $offset += (8 * $data_size); if (count($data) == 1) { $data = $data[0]; } break; case 0x0007: // 0x0007 = bytes (size field *= 1-byte), values are stored as ?????? $data = substr($atom_data, $offset, $data_size * 1); $offset += ($data_size * 1); break; case 0x0008: // 0x0008 = ????? (size field *= 2-byte), values are stored as ?????? $data = substr($atom_data, $offset, $data_size * 2); $offset += ($data_size * 2); break; default: echo 'QuicktimeParseNikonNCTG()::unknown $data_size_type: '.$data_size_type.'<br>'; break 2; } switch ($record_type) { case 0x00000011: // CreateDate case 0x00000012: // DateTimeOriginal $data = strtotime($data); break; case 0x0200001e: // ColorSpace switch ($data) { case 1: $data = 'sRGB'; break; case 2: $data = 'Adobe RGB'; break; } break; case 0x02000023: // PictureControlData $PictureControlAdjust = array(0=>'default', 1=>'quick', 2=>'full'); $FilterEffect = array(0x80=>'off', 0x81=>'yellow', 0x82=>'orange', 0x83=>'red', 0x84=>'green', 0xff=>'n/a'); $ToningEffect = array(0x80=>'b&w', 0x81=>'sepia', 0x82=>'cyanotype', 0x83=>'red', 0x84=>'yellow', 0x85=>'green', 0x86=>'blue-green', 0x87=>'blue', 0x88=>'purple-blue', 0x89=>'red-purple', 0xff=>'n/a'); $data = array( 'PictureControlVersion' => substr($data, 0, 4), 'PictureControlName' => rtrim(substr($data, 4, 20), "\x00"), 'PictureControlBase' => rtrim(substr($data, 24, 20), "\x00"), //'?' => substr($data, 44, 4), 'PictureControlAdjust' => $PictureControlAdjust[ord(substr($data, 48, 1))], 'PictureControlQuickAdjust' => ord(substr($data, 49, 1)), 'Sharpness' => ord(substr($data, 50, 1)), 'Contrast' => ord(substr($data, 51, 1)), 'Brightness' => ord(substr($data, 52, 1)), 'Saturation' => ord(substr($data, 53, 1)), 'HueAdjustment' => ord(substr($data, 54, 1)), 'FilterEffect' => $FilterEffect[ord(substr($data, 55, 1))], 'ToningEffect' => $ToningEffect[ord(substr($data, 56, 1))], 'ToningSaturation' => ord(substr($data, 57, 1)), ); break; case 0x02000024: // WorldTime // http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html#WorldTime // timezone is stored as offset from GMT in minutes $timezone = getid3_lib::BigEndian2Int(substr($data, 0, 2)); if ($timezone & 0x8000) { $timezone = 0 - (0x10000 - $timezone); } $timezone /= 60; $dst = (bool) getid3_lib::BigEndian2Int(substr($data, 2, 1)); switch (getid3_lib::BigEndian2Int(substr($data, 3, 1))) { case 2: $datedisplayformat = 'D/M/Y'; break; case 1: $datedisplayformat = 'M/D/Y'; break; case 0: default: $datedisplayformat = 'Y/M/D'; break; } $data = array('timezone'=>floatval($timezone), 'dst'=>$dst, 'display'=>$datedisplayformat); break; case 0x02000083: // LensType $data = array( //'_' => $data, 'mf' => (bool) ($data & 0x01), 'd' => (bool) ($data & 0x02), 'g' => (bool) ($data & 0x04), 'vr' => (bool) ($data & 0x08), ); break; } $tag_name = (isset($NCTGtagName[$record_type]) ? $NCTGtagName[$record_type] : '0x'.str_pad(dechex($record_type), 8, '0', STR_PAD_LEFT)); $parsed[$tag_name] = $data; } return $parsed; } public function CopyToAppropriateCommentsSection($keyname, $data, $boxname='') { static $handyatomtranslatorarray = array(); if (empty($handyatomtranslatorarray)) { $handyatomtranslatorarray['©cpy'] = 'copyright'; $handyatomtranslatorarray['©day'] = 'creation_date'; // iTunes 4.0 $handyatomtranslatorarray['©dir'] = 'director'; $handyatomtranslatorarray['©ed1'] = 'edit1'; $handyatomtranslatorarray['©ed2'] = 'edit2'; $handyatomtranslatorarray['©ed3'] = 'edit3'; $handyatomtranslatorarray['©ed4'] = 'edit4'; $handyatomtranslatorarray['©ed5'] = 'edit5'; $handyatomtranslatorarray['©ed6'] = 'edit6'; $handyatomtranslatorarray['©ed7'] = 'edit7'; $handyatomtranslatorarray['©ed8'] = 'edit8'; $handyatomtranslatorarray['©ed9'] = 'edit9'; $handyatomtranslatorarray['©fmt'] = 'format'; $handyatomtranslatorarray['©inf'] = 'information'; $handyatomtranslatorarray['©prd'] = 'producer'; $handyatomtranslatorarray['©prf'] = 'performers'; $handyatomtranslatorarray['©req'] = 'system_requirements'; $handyatomtranslatorarray['©src'] = 'source_credit'; $handyatomtranslatorarray['©wrt'] = 'writer'; // http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt $handyatomtranslatorarray['©nam'] = 'title'; // iTunes 4.0 $handyatomtranslatorarray['©cmt'] = 'comment'; // iTunes 4.0 $handyatomtranslatorarray['©wrn'] = 'warning'; $handyatomtranslatorarray['©hst'] = 'host_computer'; $handyatomtranslatorarray['©mak'] = 'make'; $handyatomtranslatorarray['©mod'] = 'model'; $handyatomtranslatorarray['©PRD'] = 'product'; $handyatomtranslatorarray['©swr'] = 'software'; $handyatomtranslatorarray['©aut'] = 'author'; $handyatomtranslatorarray['©ART'] = 'artist'; $handyatomtranslatorarray['©trk'] = 'track'; $handyatomtranslatorarray['©alb'] = 'album'; // iTunes 4.0 $handyatomtranslatorarray['©com'] = 'comment'; $handyatomtranslatorarray['©gen'] = 'genre'; // iTunes 4.0 $handyatomtranslatorarray['©ope'] = 'composer'; $handyatomtranslatorarray['©url'] = 'url'; $handyatomtranslatorarray['©enc'] = 'encoder'; // http://atomicparsley.sourceforge.net/mpeg-4files.html $handyatomtranslatorarray['©art'] = 'artist'; // iTunes 4.0 $handyatomtranslatorarray['aART'] = 'album_artist'; $handyatomtranslatorarray['trkn'] = 'track_number'; // iTunes 4.0 $handyatomtranslatorarray['disk'] = 'disc_number'; // iTunes 4.0 $handyatomtranslatorarray['gnre'] = 'genre'; // iTunes 4.0 $handyatomtranslatorarray['©too'] = 'encoder'; // iTunes 4.0 $handyatomtranslatorarray['tmpo'] = 'bpm'; // iTunes 4.0 $handyatomtranslatorarray['cprt'] = 'copyright'; // iTunes 4.0? $handyatomtranslatorarray['cpil'] = 'compilation'; // iTunes 4.0 $handyatomtranslatorarray['covr'] = 'picture'; // iTunes 4.0 $handyatomtranslatorarray['rtng'] = 'rating'; // iTunes 4.0 $handyatomtranslatorarray['©grp'] = 'grouping'; // iTunes 4.2 $handyatomtranslatorarray['stik'] = 'stik'; // iTunes 4.9 $handyatomtranslatorarray['pcst'] = 'podcast'; // iTunes 4.9 $handyatomtranslatorarray['catg'] = 'category'; // iTunes 4.9 $handyatomtranslatorarray['keyw'] = 'keyword'; // iTunes 4.9 $handyatomtranslatorarray['purl'] = 'podcast_url'; // iTunes 4.9 $handyatomtranslatorarray['egid'] = 'episode_guid'; // iTunes 4.9 $handyatomtranslatorarray['desc'] = 'description'; // iTunes 5.0 $handyatomtranslatorarray['©lyr'] = 'lyrics'; // iTunes 5.0 $handyatomtranslatorarray['tvnn'] = 'tv_network_name'; // iTunes 6.0 $handyatomtranslatorarray['tvsh'] = 'tv_show_name'; // iTunes 6.0 $handyatomtranslatorarray['tvsn'] = 'tv_season'; // iTunes 6.0 $handyatomtranslatorarray['tves'] = 'tv_episode'; // iTunes 6.0 $handyatomtranslatorarray['purd'] = 'purchase_date'; // iTunes 6.0.2 $handyatomtranslatorarray['pgap'] = 'gapless_playback'; // iTunes 7.0 // http://www.geocities.com/xhelmboyx/quicktime/formats/mp4-layout.txt // boxnames: /* $handyatomtranslatorarray['iTunSMPB'] = 'iTunSMPB'; $handyatomtranslatorarray['iTunNORM'] = 'iTunNORM'; $handyatomtranslatorarray['Encoding Params'] = 'Encoding Params'; $handyatomtranslatorarray['replaygain_track_gain'] = 'replaygain_track_gain'; $handyatomtranslatorarray['replaygain_track_peak'] = 'replaygain_track_peak'; $handyatomtranslatorarray['replaygain_track_minmax'] = 'replaygain_track_minmax'; $handyatomtranslatorarray['MusicIP PUID'] = 'MusicIP PUID'; $handyatomtranslatorarray['MusicBrainz Artist Id'] = 'MusicBrainz Artist Id'; $handyatomtranslatorarray['MusicBrainz Album Id'] = 'MusicBrainz Album Id'; $handyatomtranslatorarray['MusicBrainz Album Artist Id'] = 'MusicBrainz Album Artist Id'; $handyatomtranslatorarray['MusicBrainz Track Id'] = 'MusicBrainz Track Id'; $handyatomtranslatorarray['MusicBrainz Disc Id'] = 'MusicBrainz Disc Id'; // http://age.hobba.nl/audio/tag_frame_reference.html $handyatomtranslatorarray['PLAY_COUNTER'] = 'play_counter'; // Foobar2000 - http://www.getid3.org/phpBB3/viewtopic.php?t=1355 $handyatomtranslatorarray['MEDIATYPE'] = 'mediatype'; // Foobar2000 - http://www.getid3.org/phpBB3/viewtopic.php?t=1355 */ } $info = &$this->getid3->info; $comment_key = ''; if ($boxname && ($boxname != $keyname)) { $comment_key = (isset($handyatomtranslatorarray[$boxname]) ? $handyatomtranslatorarray[$boxname] : $boxname); } elseif (isset($handyatomtranslatorarray[$keyname])) { $comment_key = $handyatomtranslatorarray[$keyname]; } if ($comment_key) { if ($comment_key == 'picture') { if (!is_array($data)) { $image_mime = ''; if (preg_match('#^\x89\x50\x4E\x47\x0D\x0A\x1A\x0A#', $data)) { $image_mime = 'image/png'; } elseif (preg_match('#^\xFF\xD8\xFF#', $data)) { $image_mime = 'image/jpeg'; } elseif (preg_match('#^GIF#', $data)) { $image_mime = 'image/gif'; } elseif (preg_match('#^BM#', $data)) { $image_mime = 'image/bmp'; } $data = array('data'=>$data, 'image_mime'=>$image_mime); } } $info['quicktime']['comments'][$comment_key][] = $data; } return true; } public function NoNullString($nullterminatedstring) { // remove the single null terminator on null terminated strings if (substr($nullterminatedstring, strlen($nullterminatedstring) - 1, 1) === "\x00") { return substr($nullterminatedstring, 0, strlen($nullterminatedstring) - 1); } return $nullterminatedstring; } public function Pascal2String($pascalstring) { // Pascal strings have 1 unsigned byte at the beginning saying how many chars (1-255) are in the string return substr($pascalstring, 1); } }
nao-pon/HypCommon
xoops_trust_path/class/hyp_common/getid3/module.audio-video.quicktime.php
PHP
gpl-2.0
115,900
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.rss; import org.apache.camel.builder.RouteBuilder; import org.junit.AfterClass; import org.junit.BeforeClass; public class RssPollingConsumerWithBasicAuthTest extends RssPollingConsumerTest { @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("rss:http://localhost:" + JettyTestServer.getInstance().port + "/?splitEntries=false&username=camel&password=camelPass").to("mock:result"); } }; } @BeforeClass public static void startServer() { JettyTestServer.getInstance().startServer(); } @AfterClass public static void stopServer() { JettyTestServer.getInstance().stopServer(); } }
sabre1041/camel
components/camel-rss/src/test/java/org/apache/camel/component/rss/RssPollingConsumerWithBasicAuthTest.java
Java
apache-2.0
1,652
/* Test the `vld1Q_dups8' ARM Neon intrinsic. */ /* This file was autogenerated by neon-testgen. */ /* { dg-do assemble } */ /* { dg-require-effective-target arm_neon_ok } */ /* { dg-options "-save-temps -O0" } */ /* { dg-add-options arm_neon } */ #include "arm_neon.h" void test_vld1Q_dups8 (void) { int8x16_t out_int8x16_t; out_int8x16_t = vld1q_dup_s8 (0); } /* { dg-final { scan-assembler "vld1\.8\[ \]+\\\{((\[dD\]\[0-9\]+\\\[\\\]-\[dD\]\[0-9\]+\\\[\\\])|(\[dD\]\[0-9\]+\\\[\\\], \[dD\]\[0-9\]+\\\[\\\]))\\\}, \\\[\[rR\]\[0-9\]+\(:\[0-9\]+\)?\\\]!?\(\[ \]+@\[a-zA-Z0-9 \]+\)?\n" } } */ /* { dg-final { cleanup-saved-temps } } */
the-linix-project/linix-kernel-source
gccsrc/gcc-4.7.2/gcc/testsuite/gcc.target/arm/neon/vld1Q_dups8.c
C
bsd-2-clause
647
/* Copyright (c) 2012-2013, 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/sched.h> #include <mach/socinfo.h> #include "kgsl.h" #include "adreno.h" #include "kgsl_sharedmem.h" #include "kgsl_cffdump.h" #include "a3xx_reg.h" #include "adreno_a3xx_trace.h" /* * Set of registers to dump for A3XX on postmortem and snapshot. * Registers in pairs - first value is the start offset, second * is the stop offset (inclusive) */ const unsigned int a3xx_registers[] = { 0x0000, 0x0002, 0x0010, 0x0012, 0x0018, 0x0018, 0x0020, 0x0027, 0x0029, 0x002b, 0x002e, 0x0033, 0x0040, 0x0042, 0x0050, 0x005c, 0x0060, 0x006c, 0x0080, 0x0082, 0x0084, 0x0088, 0x0090, 0x00e5, 0x00ea, 0x00ed, 0x0100, 0x0100, 0x0110, 0x0123, 0x01c0, 0x01c1, 0x01c3, 0x01c5, 0x01c7, 0x01c7, 0x01d5, 0x01d9, 0x01dc, 0x01dd, 0x01ea, 0x01ea, 0x01ee, 0x01f1, 0x01f5, 0x01f5, 0x01fc, 0x01ff, 0x0440, 0x0440, 0x0443, 0x0443, 0x0445, 0x0445, 0x044d, 0x044f, 0x0452, 0x0452, 0x0454, 0x046f, 0x047c, 0x047c, 0x047f, 0x047f, 0x0578, 0x057f, 0x0600, 0x0602, 0x0605, 0x0607, 0x060a, 0x060e, 0x0612, 0x0614, 0x0c01, 0x0c02, 0x0c06, 0x0c1d, 0x0c3d, 0x0c3f, 0x0c48, 0x0c4b, 0x0c80, 0x0c80, 0x0c88, 0x0c8b, 0x0ca0, 0x0cb7, 0x0cc0, 0x0cc1, 0x0cc6, 0x0cc7, 0x0ce4, 0x0ce5, 0x0e41, 0x0e45, 0x0e64, 0x0e65, 0x0e80, 0x0e82, 0x0e84, 0x0e89, 0x0ea0, 0x0ea1, 0x0ea4, 0x0ea7, 0x0ec4, 0x0ecb, 0x0ee0, 0x0ee0, 0x0f00, 0x0f01, 0x0f03, 0x0f09, 0x2040, 0x2040, 0x2044, 0x2044, 0x2048, 0x204d, 0x2068, 0x2069, 0x206c, 0x206d, 0x2070, 0x2070, 0x2072, 0x2072, 0x2074, 0x2075, 0x2079, 0x207a, 0x20c0, 0x20d3, 0x20e4, 0x20ef, 0x2100, 0x2109, 0x210c, 0x210c, 0x210e, 0x210e, 0x2110, 0x2111, 0x2114, 0x2115, 0x21e4, 0x21e4, 0x21ea, 0x21ea, 0x21ec, 0x21ed, 0x21f0, 0x21f0, 0x2240, 0x227e, 0x2280, 0x228b, 0x22c0, 0x22c0, 0x22c4, 0x22ce, 0x22d0, 0x22d8, 0x22df, 0x22e6, 0x22e8, 0x22e9, 0x22ec, 0x22ec, 0x22f0, 0x22f7, 0x22ff, 0x22ff, 0x2340, 0x2343, 0x2440, 0x2440, 0x2444, 0x2444, 0x2448, 0x244d, 0x2468, 0x2469, 0x246c, 0x246d, 0x2470, 0x2470, 0x2472, 0x2472, 0x2474, 0x2475, 0x2479, 0x247a, 0x24c0, 0x24d3, 0x24e4, 0x24ef, 0x2500, 0x2509, 0x250c, 0x250c, 0x250e, 0x250e, 0x2510, 0x2511, 0x2514, 0x2515, 0x25e4, 0x25e4, 0x25ea, 0x25ea, 0x25ec, 0x25ed, 0x25f0, 0x25f0, 0x2640, 0x267e, 0x2680, 0x268b, 0x26c0, 0x26c0, 0x26c4, 0x26ce, 0x26d0, 0x26d8, 0x26df, 0x26e6, 0x26e8, 0x26e9, 0x26ec, 0x26ec, 0x26f0, 0x26f7, 0x26ff, 0x26ff, 0x2740, 0x2743, 0x300C, 0x300E, 0x301C, 0x301D, 0x302A, 0x302A, 0x302C, 0x302D, 0x3030, 0x3031, 0x3034, 0x3036, 0x303C, 0x303C, 0x305E, 0x305F, }; const unsigned int a3xx_registers_count = ARRAY_SIZE(a3xx_registers) / 2; /* Removed the following HLSQ register ranges from being read during * fault tolerance since reading the registers may cause the device to hang: */ const unsigned int a3xx_hlsq_registers[] = { 0x0e00, 0x0e05, 0x0e0c, 0x0e0c, 0x0e22, 0x0e23, 0x2200, 0x2212, 0x2214, 0x2217, 0x221a, 0x221a, 0x2600, 0x2612, 0x2614, 0x2617, 0x261a, 0x261a, }; const unsigned int a3xx_hlsq_registers_count = ARRAY_SIZE(a3xx_hlsq_registers) / 2; /* The set of additional registers to be dumped for A330 */ const unsigned int a330_registers[] = { 0x1d0, 0x1d0, 0x1d4, 0x1d4, 0x453, 0x453, }; const unsigned int a330_registers_count = ARRAY_SIZE(a330_registers) / 2; /* Simple macro to facilitate bit setting in the gmem2sys and sys2gmem * functions. */ #define _SET(_shift, _val) ((_val) << (_shift)) /* EN/CLR mask for the VBIF counters we care about */ #define VBIF_PERF_MASK (VBIF_PERF_CNT_0 | VBIF_PERF_PWR_CNT_0) #define RBBM_PERF_ENABLE_MASK (RBBM_RBBM_CTL_ENABLE_PWR_CTR1) #define RBBM_PERF_RESET_MASK (RBBM_RBBM_CTL_RESET_PWR_CTR1) /* **************************************************************************** * * Context state shadow structure: * * +---------------------+------------+-------------+---------------------+---+ * | ALU Constant Shadow | Reg Shadow | C&V Buffers | Shader Instr Shadow |Tex| * +---------------------+------------+-------------+---------------------+---+ * * 8K - ALU Constant Shadow (8K aligned) * 4K - H/W Register Shadow (8K aligned) * 5K - Command and Vertex Buffers * 8K - Shader Instruction Shadow * ~6K - Texture Constant Shadow * * *************************************************************************** */ /* Sizes of all sections in state shadow memory */ #define ALU_SHADOW_SIZE (8*1024) /* 8KB */ #define REG_SHADOW_SIZE (4*1024) /* 4KB */ #define CMD_BUFFER_SIZE (5*1024) /* 5KB */ #define TEX_SIZE_MEM_OBJECTS 896 /* bytes */ #define TEX_SIZE_MIPMAP 1936 /* bytes */ #define TEX_SIZE_SAMPLER_OBJ 256 /* bytes */ #define TEX_SHADOW_SIZE \ ((TEX_SIZE_MEM_OBJECTS + TEX_SIZE_MIPMAP + \ TEX_SIZE_SAMPLER_OBJ)*2) /* ~6KB */ #define SHADER_SHADOW_SIZE (8*1024) /* 8KB */ /* Total context size, excluding GMEM shadow */ #define CONTEXT_SIZE \ (ALU_SHADOW_SIZE+REG_SHADOW_SIZE + \ CMD_BUFFER_SIZE+SHADER_SHADOW_SIZE + \ TEX_SHADOW_SIZE) /* Offsets to different sections in context shadow memory */ #define REG_OFFSET ALU_SHADOW_SIZE #define CMD_OFFSET (REG_OFFSET+REG_SHADOW_SIZE) #define SHADER_OFFSET (CMD_OFFSET+CMD_BUFFER_SIZE) #define TEX_OFFSET (SHADER_OFFSET+SHADER_SHADOW_SIZE) #define VS_TEX_OFFSET_MEM_OBJECTS TEX_OFFSET #define VS_TEX_OFFSET_MIPMAP (VS_TEX_OFFSET_MEM_OBJECTS+TEX_SIZE_MEM_OBJECTS) #define VS_TEX_OFFSET_SAMPLER_OBJ (VS_TEX_OFFSET_MIPMAP+TEX_SIZE_MIPMAP) #define FS_TEX_OFFSET_MEM_OBJECTS \ (VS_TEX_OFFSET_SAMPLER_OBJ+TEX_SIZE_SAMPLER_OBJ) #define FS_TEX_OFFSET_MIPMAP (FS_TEX_OFFSET_MEM_OBJECTS+TEX_SIZE_MEM_OBJECTS) #define FS_TEX_OFFSET_SAMPLER_OBJ (FS_TEX_OFFSET_MIPMAP+TEX_SIZE_MIPMAP) /* The offset for fragment shader data in HLSQ context */ #define SSIZE (16*1024) #define HLSQ_SAMPLER_OFFSET 0x000 #define HLSQ_MEMOBJ_OFFSET 0x400 #define HLSQ_MIPMAP_OFFSET 0x800 /* Use shadow RAM */ #define HLSQ_SHADOW_BASE (0x10000+SSIZE*2) #define REG_TO_MEM_LOOP_COUNT_SHIFT 18 #define BUILD_PC_DRAW_INITIATOR(prim_type, source_select, index_size, \ vis_cull_mode) \ (((prim_type) << PC_DRAW_INITIATOR_PRIM_TYPE) | \ ((source_select) << PC_DRAW_INITIATOR_SOURCE_SELECT) | \ ((index_size & 1) << PC_DRAW_INITIATOR_INDEX_SIZE) | \ ((index_size >> 1) << PC_DRAW_INITIATOR_SMALL_INDEX) | \ ((vis_cull_mode) << PC_DRAW_INITIATOR_VISIBILITY_CULLING_MODE) | \ (1 << PC_DRAW_INITIATOR_PRE_DRAW_INITIATOR_ENABLE)) /* * List of context registers (starting from dword offset 0x2000). * Each line contains start and end of a range of registers. */ static const unsigned int context_register_ranges[] = { A3XX_GRAS_CL_CLIP_CNTL, A3XX_GRAS_CL_CLIP_CNTL, A3XX_GRAS_CL_GB_CLIP_ADJ, A3XX_GRAS_CL_GB_CLIP_ADJ, A3XX_GRAS_CL_VPORT_XOFFSET, A3XX_GRAS_CL_VPORT_ZSCALE, A3XX_GRAS_SU_POINT_MINMAX, A3XX_GRAS_SU_POINT_SIZE, A3XX_GRAS_SU_POLY_OFFSET_SCALE, A3XX_GRAS_SU_POLY_OFFSET_OFFSET, A3XX_GRAS_SU_MODE_CONTROL, A3XX_GRAS_SU_MODE_CONTROL, A3XX_GRAS_SC_CONTROL, A3XX_GRAS_SC_CONTROL, A3XX_GRAS_SC_SCREEN_SCISSOR_TL, A3XX_GRAS_SC_SCREEN_SCISSOR_BR, A3XX_GRAS_SC_WINDOW_SCISSOR_TL, A3XX_GRAS_SC_WINDOW_SCISSOR_BR, A3XX_RB_MODE_CONTROL, A3XX_RB_MRT_BLEND_CONTROL3, A3XX_RB_BLEND_RED, A3XX_RB_COPY_DEST_INFO, A3XX_RB_DEPTH_CONTROL, A3XX_RB_DEPTH_CONTROL, A3XX_PC_VSTREAM_CONTROL, A3XX_PC_VSTREAM_CONTROL, A3XX_PC_VERTEX_REUSE_BLOCK_CNTL, A3XX_PC_VERTEX_REUSE_BLOCK_CNTL, A3XX_PC_PRIM_VTX_CNTL, A3XX_PC_RESTART_INDEX, A3XX_HLSQ_CONTROL_0_REG, A3XX_HLSQ_CONST_FSPRESV_RANGE_REG, A3XX_HLSQ_CL_NDRANGE_0_REG, A3XX_HLSQ_CL_NDRANGE_0_REG, A3XX_HLSQ_CL_NDRANGE_2_REG, A3XX_HLSQ_CL_CONTROL_1_REG, A3XX_HLSQ_CL_KERNEL_CONST_REG, A3XX_HLSQ_CL_KERNEL_GROUP_Z_REG, A3XX_HLSQ_CL_WG_OFFSET_REG, A3XX_HLSQ_CL_WG_OFFSET_REG, A3XX_VFD_CONTROL_0, A3XX_VFD_VS_THREADING_THRESHOLD, A3XX_SP_SP_CTRL_REG, A3XX_SP_SP_CTRL_REG, A3XX_SP_VS_CTRL_REG0, A3XX_SP_VS_OUT_REG_7, A3XX_SP_VS_VPC_DST_REG_0, A3XX_SP_VS_PVT_MEM_SIZE_REG, A3XX_SP_VS_LENGTH_REG, A3XX_SP_FS_PVT_MEM_SIZE_REG, A3XX_SP_FS_FLAT_SHAD_MODE_REG_0, A3XX_SP_FS_FLAT_SHAD_MODE_REG_1, A3XX_SP_FS_OUTPUT_REG, A3XX_SP_FS_OUTPUT_REG, A3XX_SP_FS_MRT_REG_0, A3XX_SP_FS_IMAGE_OUTPUT_REG_3, A3XX_SP_FS_LENGTH_REG, A3XX_SP_FS_LENGTH_REG, A3XX_TPL1_TP_VS_TEX_OFFSET, A3XX_TPL1_TP_FS_BORDER_COLOR_BASE_ADDR, A3XX_VPC_ATTR, A3XX_VPC_VARY_CYLWRAP_ENABLE_1, }; /* Global registers that need to be saved separately */ static const unsigned int global_registers[] = { A3XX_GRAS_CL_USER_PLANE_X0, A3XX_GRAS_CL_USER_PLANE_Y0, A3XX_GRAS_CL_USER_PLANE_Z0, A3XX_GRAS_CL_USER_PLANE_W0, A3XX_GRAS_CL_USER_PLANE_X1, A3XX_GRAS_CL_USER_PLANE_Y1, A3XX_GRAS_CL_USER_PLANE_Z1, A3XX_GRAS_CL_USER_PLANE_W1, A3XX_GRAS_CL_USER_PLANE_X2, A3XX_GRAS_CL_USER_PLANE_Y2, A3XX_GRAS_CL_USER_PLANE_Z2, A3XX_GRAS_CL_USER_PLANE_W2, A3XX_GRAS_CL_USER_PLANE_X3, A3XX_GRAS_CL_USER_PLANE_Y3, A3XX_GRAS_CL_USER_PLANE_Z3, A3XX_GRAS_CL_USER_PLANE_W3, A3XX_GRAS_CL_USER_PLANE_X4, A3XX_GRAS_CL_USER_PLANE_Y4, A3XX_GRAS_CL_USER_PLANE_Z4, A3XX_GRAS_CL_USER_PLANE_W4, A3XX_GRAS_CL_USER_PLANE_X5, A3XX_GRAS_CL_USER_PLANE_Y5, A3XX_GRAS_CL_USER_PLANE_Z5, A3XX_GRAS_CL_USER_PLANE_W5, A3XX_VSC_BIN_SIZE, A3XX_VSC_PIPE_CONFIG_0, A3XX_VSC_PIPE_CONFIG_1, A3XX_VSC_PIPE_CONFIG_2, A3XX_VSC_PIPE_CONFIG_3, A3XX_VSC_PIPE_CONFIG_4, A3XX_VSC_PIPE_CONFIG_5, A3XX_VSC_PIPE_CONFIG_6, A3XX_VSC_PIPE_CONFIG_7, A3XX_VSC_PIPE_DATA_ADDRESS_0, A3XX_VSC_PIPE_DATA_ADDRESS_1, A3XX_VSC_PIPE_DATA_ADDRESS_2, A3XX_VSC_PIPE_DATA_ADDRESS_3, A3XX_VSC_PIPE_DATA_ADDRESS_4, A3XX_VSC_PIPE_DATA_ADDRESS_5, A3XX_VSC_PIPE_DATA_ADDRESS_6, A3XX_VSC_PIPE_DATA_ADDRESS_7, A3XX_VSC_PIPE_DATA_LENGTH_0, A3XX_VSC_PIPE_DATA_LENGTH_1, A3XX_VSC_PIPE_DATA_LENGTH_2, A3XX_VSC_PIPE_DATA_LENGTH_3, A3XX_VSC_PIPE_DATA_LENGTH_4, A3XX_VSC_PIPE_DATA_LENGTH_5, A3XX_VSC_PIPE_DATA_LENGTH_6, A3XX_VSC_PIPE_DATA_LENGTH_7, A3XX_VSC_SIZE_ADDRESS }; #define GLOBAL_REGISTER_COUNT ARRAY_SIZE(global_registers) /* A scratchpad used to build commands during context create */ static struct tmp_ctx { unsigned int *cmd; /* Next available dword in C&V buffer */ /* Addresses in comamnd buffer where registers are saved */ uint32_t reg_values[GLOBAL_REGISTER_COUNT]; uint32_t gmem_base; /* Base GPU address of GMEM */ } tmp_ctx; #ifndef GSL_CONTEXT_SWITCH_CPU_SYNC /* * Function for executing dest = ( (reg & and) ROL rol ) | or */ static unsigned int *rmw_regtomem(unsigned int *cmd, unsigned int reg, unsigned int and, unsigned int rol, unsigned int or, unsigned int dest) { /* CP_SCRATCH_REG2 = (CP_SCRATCH_REG2 & 0x00000000) | reg */ *cmd++ = cp_type3_packet(CP_REG_RMW, 3); *cmd++ = (1 << 30) | A3XX_CP_SCRATCH_REG2; *cmd++ = 0x00000000; /* AND value */ *cmd++ = reg; /* OR address */ /* CP_SCRATCH_REG2 = ( (CP_SCRATCH_REG2 & and) ROL rol ) | or */ *cmd++ = cp_type3_packet(CP_REG_RMW, 3); *cmd++ = (rol << 24) | A3XX_CP_SCRATCH_REG2; *cmd++ = and; /* AND value */ *cmd++ = or; /* OR value */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_CP_SCRATCH_REG2; *cmd++ = dest; return cmd; } #endif static void build_regconstantsave_cmds(struct adreno_device *adreno_dev, struct adreno_context *drawctxt) { unsigned int *cmd = tmp_ctx.cmd; unsigned int *start; unsigned int i; drawctxt->constant_save_commands[0].hostptr = cmd; drawctxt->constant_save_commands[0].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); cmd++; start = cmd; *cmd++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmd++ = 0; #ifndef CONFIG_MSM_KGSL_DISABLE_SHADOW_WRITES /* * Context registers are already shadowed; just need to * disable shadowing to prevent corruption. */ *cmd++ = cp_type3_packet(CP_LOAD_CONSTANT_CONTEXT, 3); *cmd++ = (drawctxt->gpustate.gpuaddr + REG_OFFSET) & 0xFFFFE000; *cmd++ = 4 << 16; /* regs, start=0 */ *cmd++ = 0x0; /* count = 0 */ #else /* * Make sure the HW context has the correct register values before * reading them. */ /* Write context registers into shadow */ for (i = 0; i < ARRAY_SIZE(context_register_ranges) / 2; i++) { unsigned int start = context_register_ranges[i * 2]; unsigned int end = context_register_ranges[i * 2 + 1]; *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = ((end - start + 1) << REG_TO_MEM_LOOP_COUNT_SHIFT) | start; *cmd++ = ((drawctxt->gpustate.gpuaddr + REG_OFFSET) & 0xFFFFE000) + (start - 0x2000) * 4; } #endif /* Need to handle some of the global registers separately */ for (i = 0; i < ARRAY_SIZE(global_registers); i++) { *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = global_registers[i]; *cmd++ = tmp_ctx.reg_values[i]; } /* Save vertex shader constants */ *cmd++ = cp_type3_packet(CP_COND_EXEC, 4); *cmd++ = drawctxt->cond_execs[2].gpuaddr >> 2; *cmd++ = drawctxt->cond_execs[2].gpuaddr >> 2; *cmd++ = 0x0000FFFF; *cmd++ = 3; /* EXEC_COUNT */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); drawctxt->constant_save_commands[1].hostptr = cmd; drawctxt->constant_save_commands[1].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); /* From fixup: dwords = SP_VS_CTRL_REG1.VSCONSTLENGTH / 4 src = (HLSQ_SHADOW_BASE + 0x2000) / 4 From register spec: SP_VS_CTRL_REG1.VSCONSTLENGTH [09:00]: 0-512, unit = 128bits. */ *cmd++ = 0; /* (dwords << REG_TO_MEM_LOOP_COUNT_SHIFT) | src */ /* ALU constant shadow base */ *cmd++ = drawctxt->gpustate.gpuaddr & 0xfffffffc; /* Save fragment shader constants */ *cmd++ = cp_type3_packet(CP_COND_EXEC, 4); *cmd++ = drawctxt->cond_execs[3].gpuaddr >> 2; *cmd++ = drawctxt->cond_execs[3].gpuaddr >> 2; *cmd++ = 0x0000FFFF; *cmd++ = 3; /* EXEC_COUNT */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); drawctxt->constant_save_commands[2].hostptr = cmd; drawctxt->constant_save_commands[2].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); /* From fixup: dwords = SP_FS_CTRL_REG1.FSCONSTLENGTH / 4 src = (HLSQ_SHADOW_BASE + 0x2000 + SSIZE) / 4 From register spec: SP_FS_CTRL_REG1.FSCONSTLENGTH [09:00]: 0-512, unit = 128bits. */ *cmd++ = 0; /* (dwords << REG_TO_MEM_LOOP_COUNT_SHIFT) | src */ /* From fixup: base = drawctxt->gpustate.gpuaddr (ALU constant shadow base) offset = SP_FS_OBJ_OFFSET_REG.CONSTOBJECTSTARTOFFSET From register spec: SP_FS_OBJ_OFFSET_REG.CONSTOBJECTSTARTOFFSET [16:24]: Constant object start offset in on chip RAM, 128bit aligned dst = base + offset Because of the base alignment we can use dst = base | offset */ *cmd++ = 0; /* dst */ /* Save VS texture memory objects */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = ((TEX_SIZE_MEM_OBJECTS / 4) << REG_TO_MEM_LOOP_COUNT_SHIFT) | ((HLSQ_SHADOW_BASE + HLSQ_MEMOBJ_OFFSET) / 4); *cmd++ = (drawctxt->gpustate.gpuaddr + VS_TEX_OFFSET_MEM_OBJECTS) & 0xfffffffc; /* Save VS texture mipmap pointers */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = ((TEX_SIZE_MIPMAP / 4) << REG_TO_MEM_LOOP_COUNT_SHIFT) | ((HLSQ_SHADOW_BASE + HLSQ_MIPMAP_OFFSET) / 4); *cmd++ = (drawctxt->gpustate.gpuaddr + VS_TEX_OFFSET_MIPMAP) & 0xfffffffc; /* Save VS texture sampler objects */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = ((TEX_SIZE_SAMPLER_OBJ / 4) << REG_TO_MEM_LOOP_COUNT_SHIFT) | ((HLSQ_SHADOW_BASE + HLSQ_SAMPLER_OFFSET) / 4); *cmd++ = (drawctxt->gpustate.gpuaddr + VS_TEX_OFFSET_SAMPLER_OBJ) & 0xfffffffc; /* Save FS texture memory objects */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = ((TEX_SIZE_MEM_OBJECTS / 4) << REG_TO_MEM_LOOP_COUNT_SHIFT) | ((HLSQ_SHADOW_BASE + HLSQ_MEMOBJ_OFFSET + SSIZE) / 4); *cmd++ = (drawctxt->gpustate.gpuaddr + FS_TEX_OFFSET_MEM_OBJECTS) & 0xfffffffc; /* Save FS texture mipmap pointers */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = ((TEX_SIZE_MIPMAP / 4) << REG_TO_MEM_LOOP_COUNT_SHIFT) | ((HLSQ_SHADOW_BASE + HLSQ_MIPMAP_OFFSET + SSIZE) / 4); *cmd++ = (drawctxt->gpustate.gpuaddr + FS_TEX_OFFSET_MIPMAP) & 0xfffffffc; /* Save FS texture sampler objects */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = ((TEX_SIZE_SAMPLER_OBJ / 4) << REG_TO_MEM_LOOP_COUNT_SHIFT) | ((HLSQ_SHADOW_BASE + HLSQ_SAMPLER_OFFSET + SSIZE) / 4); *cmd++ = (drawctxt->gpustate.gpuaddr + FS_TEX_OFFSET_SAMPLER_OBJ) & 0xfffffffc; /* Create indirect buffer command for above command sequence */ create_ib1(drawctxt, drawctxt->regconstant_save, start, cmd); tmp_ctx.cmd = cmd; } unsigned int adreno_a3xx_rbbm_clock_ctl_default(struct adreno_device *adreno_dev) { if (adreno_is_a305(adreno_dev)) return A305_RBBM_CLOCK_CTL_DEFAULT; else if (adreno_is_a305c(adreno_dev)) return A305C_RBBM_CLOCK_CTL_DEFAULT; else if (adreno_is_a320(adreno_dev)) return A320_RBBM_CLOCK_CTL_DEFAULT; else if (adreno_is_a330v2(adreno_dev)) return A330v2_RBBM_CLOCK_CTL_DEFAULT; else if (adreno_is_a330(adreno_dev)) return A330_RBBM_CLOCK_CTL_DEFAULT; else if (adreno_is_a305b(adreno_dev)) return A305B_RBBM_CLOCK_CTL_DEFAULT; BUG_ON(1); } /* Copy GMEM contents to system memory shadow. */ static unsigned int *build_gmem2sys_cmds(struct adreno_device *adreno_dev, struct adreno_context *drawctxt, struct gmem_shadow_t *shadow) { unsigned int *cmds = tmp_ctx.cmd; unsigned int *start = cmds; *cmds++ = cp_type0_packet(A3XX_RBBM_CLOCK_CTL, 1); *cmds++ = adreno_a3xx_rbbm_clock_ctl_default(adreno_dev); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_RB_MODE_CONTROL); /* RB_MODE_CONTROL */ *cmds++ = _SET(RB_MODECONTROL_RENDER_MODE, RB_RESOLVE_PASS) | _SET(RB_MODECONTROL_MARB_CACHE_SPLIT_MODE, 1) | _SET(RB_MODECONTROL_PACKER_TIMER_ENABLE, 1); /* RB_RENDER_CONTROL */ *cmds++ = _SET(RB_RENDERCONTROL_BIN_WIDTH, shadow->width >> 5) | _SET(RB_RENDERCONTROL_DISABLE_COLOR_PIPE, 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_RB_COPY_CONTROL); /* RB_COPY_CONTROL */ *cmds++ = _SET(RB_COPYCONTROL_RESOLVE_CLEAR_MODE, RB_CLEAR_MODE_RESOLVE) | _SET(RB_COPYCONTROL_COPY_GMEM_BASE, tmp_ctx.gmem_base >> 14); /* RB_COPY_DEST_BASE */ *cmds++ = _SET(RB_COPYDESTBASE_COPY_DEST_BASE, shadow->gmemshadow.gpuaddr >> 5); /* RB_COPY_DEST_PITCH */ *cmds++ = _SET(RB_COPYDESTPITCH_COPY_DEST_PITCH, (shadow->pitch * 4) / 32); /* RB_COPY_DEST_INFO */ *cmds++ = _SET(RB_COPYDESTINFO_COPY_DEST_TILE, RB_TILINGMODE_LINEAR) | _SET(RB_COPYDESTINFO_COPY_DEST_FORMAT, RB_R8G8B8A8_UNORM) | _SET(RB_COPYDESTINFO_COPY_COMPONENT_ENABLE, 0X0F) | _SET(RB_COPYDESTINFO_COPY_DEST_ENDIAN, RB_ENDIAN_NONE); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_GRAS_SC_CONTROL); /* GRAS_SC_CONTROL */ *cmds++ = _SET(GRAS_SC_CONTROL_RENDER_MODE, 2); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_VFD_CONTROL_0); /* VFD_CONTROL_0 */ *cmds++ = _SET(VFD_CTRLREG0_TOTALATTRTOVS, 4) | _SET(VFD_CTRLREG0_PACKETSIZE, 2) | _SET(VFD_CTRLREG0_STRMDECINSTRCNT, 1) | _SET(VFD_CTRLREG0_STRMFETCHINSTRCNT, 1); /* VFD_CONTROL_1 */ *cmds++ = _SET(VFD_CTRLREG1_MAXSTORAGE, 1) | _SET(VFD_CTRLREG1_REGID4VTX, 252) | _SET(VFD_CTRLREG1_REGID4INST, 252); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_VFD_FETCH_INSTR_0_0); /* VFD_FETCH_INSTR_0_0 */ *cmds++ = _SET(VFD_FETCHINSTRUCTIONS_FETCHSIZE, 11) | _SET(VFD_FETCHINSTRUCTIONS_BUFSTRIDE, 12) | _SET(VFD_FETCHINSTRUCTIONS_STEPRATE, 1); /* VFD_FETCH_INSTR_1_0 */ *cmds++ = _SET(VFD_BASEADDR_BASEADDR, shadow->quad_vertices.gpuaddr); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_VFD_DECODE_INSTR_0); /* VFD_DECODE_INSTR_0 */ *cmds++ = _SET(VFD_DECODEINSTRUCTIONS_WRITEMASK, 0x0F) | _SET(VFD_DECODEINSTRUCTIONS_CONSTFILL, 1) | _SET(VFD_DECODEINSTRUCTIONS_FORMAT, 2) | _SET(VFD_DECODEINSTRUCTIONS_SHIFTCNT, 12) | _SET(VFD_DECODEINSTRUCTIONS_LASTCOMPVALID, 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_HLSQ_CONTROL_0_REG); /* HLSQ_CONTROL_0_REG */ *cmds++ = _SET(HLSQ_CTRL0REG_FSTHREADSIZE, HLSQ_FOUR_PIX_QUADS) | _SET(HLSQ_CTRL0REG_FSSUPERTHREADENABLE, 1) | _SET(HLSQ_CTRL0REG_RESERVED2, 1) | _SET(HLSQ_CTRL0REG_SPCONSTFULLUPDATE, 1); /* HLSQ_CONTROL_1_REG */ *cmds++ = _SET(HLSQ_CTRL1REG_VSTHREADSIZE, HLSQ_TWO_VTX_QUADS) | _SET(HLSQ_CTRL1REG_VSSUPERTHREADENABLE, 1); /* HLSQ_CONTROL_2_REG */ *cmds++ = _SET(HLSQ_CTRL2REG_PRIMALLOCTHRESHOLD, 31); /* HLSQ_CONTROL_3_REG */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_HLSQ_VS_CONTROL_REG); /* HLSQ_VS_CONTROL_REG */ *cmds++ = _SET(HLSQ_VSCTRLREG_VSINSTRLENGTH, 1); /* HLSQ_FS_CONTROL_REG */ *cmds++ = _SET(HLSQ_FSCTRLREG_FSCONSTLENGTH, 1) | _SET(HLSQ_FSCTRLREG_FSCONSTSTARTOFFSET, 128) | _SET(HLSQ_FSCTRLREG_FSINSTRLENGTH, 1); /* HLSQ_CONST_VSPRESV_RANGE_REG */ *cmds++ = 0x00000000; /* HLSQ_CONST_FSPRESV_RANGE_REQ */ *cmds++ = _SET(HLSQ_CONSTFSPRESERVEDRANGEREG_STARTENTRY, 32) | _SET(HLSQ_CONSTFSPRESERVEDRANGEREG_ENDENTRY, 32); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_SP_FS_LENGTH_REG); /* SP_FS_LENGTH_REG */ *cmds++ = _SET(SP_SHADERLENGTH_LEN, 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_SP_SP_CTRL_REG); /* SP_SP_CTRL_REG */ *cmds++ = _SET(SP_SPCTRLREG_SLEEPMODE, 1) | _SET(SP_SPCTRLREG_LOMODE, 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 12); *cmds++ = CP_REG(A3XX_SP_VS_CTRL_REG0); /* SP_VS_CTRL_REG0 */ *cmds++ = _SET(SP_VSCTRLREG0_VSTHREADMODE, SP_MULTI) | _SET(SP_VSCTRLREG0_VSINSTRBUFFERMODE, SP_BUFFER_MODE) | _SET(SP_VSCTRLREG0_VSICACHEINVALID, 1) | _SET(SP_VSCTRLREG0_VSFULLREGFOOTPRINT, 1) | _SET(SP_VSCTRLREG0_VSTHREADSIZE, SP_TWO_VTX_QUADS) | _SET(SP_VSCTRLREG0_VSSUPERTHREADMODE, 1) | _SET(SP_VSCTRLREG0_VSLENGTH, 1); /* SP_VS_CTRL_REG1 */ *cmds++ = _SET(SP_VSCTRLREG1_VSINITIALOUTSTANDING, 4); /* SP_VS_PARAM_REG */ *cmds++ = _SET(SP_VSPARAMREG_PSIZEREGID, 252); /* SP_VS_OUT_REG_0 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG_1 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG_2 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG_3 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG_4 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG_5 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG_6 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG_7 */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 7); *cmds++ = CP_REG(A3XX_SP_VS_VPC_DST_REG_0); /* SP_VS_VPC_DST_REG_0 */ *cmds++ = 0x00000000; /* SP_VS_VPC_DST_REG_1 */ *cmds++ = 0x00000000; /* SP_VS_VPC_DST_REG_2 */ *cmds++ = 0x00000000; /* SP_VS_VPC_DST_REG_3 */ *cmds++ = 0x00000000; /* SP_VS_OBJ_OFFSET_REG */ *cmds++ = 0x00000000; /* SP_VS_OBJ_START_REG */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 6); *cmds++ = CP_REG(A3XX_SP_VS_LENGTH_REG); /* SP_VS_LENGTH_REG */ *cmds++ = _SET(SP_SHADERLENGTH_LEN, 1); /* SP_FS_CTRL_REG0 */ *cmds++ = _SET(SP_FSCTRLREG0_FSTHREADMODE, SP_MULTI) | _SET(SP_FSCTRLREG0_FSINSTRBUFFERMODE, SP_BUFFER_MODE) | _SET(SP_FSCTRLREG0_FSICACHEINVALID, 1) | _SET(SP_FSCTRLREG0_FSHALFREGFOOTPRINT, 1) | _SET(SP_FSCTRLREG0_FSINOUTREGOVERLAP, 1) | _SET(SP_FSCTRLREG0_FSTHREADSIZE, SP_FOUR_PIX_QUADS) | _SET(SP_FSCTRLREG0_FSSUPERTHREADMODE, 1) | _SET(SP_FSCTRLREG0_FSLENGTH, 1); /* SP_FS_CTRL_REG1 */ *cmds++ = _SET(SP_FSCTRLREG1_FSCONSTLENGTH, 1) | _SET(SP_FSCTRLREG1_HALFPRECVAROFFSET, 63); /* SP_FS_OBJ_OFFSET_REG */ *cmds++ = _SET(SP_OBJOFFSETREG_CONSTOBJECTSTARTOFFSET, 128) | _SET(SP_OBJOFFSETREG_SHADEROBJOFFSETINIC, 127); /* SP_FS_OBJ_START_REG */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_SP_FS_FLAT_SHAD_MODE_REG_0); /* SP_FS_FLAT_SHAD_MODE_REG_0 */ *cmds++ = 0x00000000; /* SP_FS_FLAT_SHAD_MODE_REG_1 */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_SP_FS_OUTPUT_REG); /* SP_FS_OUTPUT_REG */ *cmds++ = _SET(SP_IMAGEOUTPUTREG_DEPTHOUTMODE, SP_PIXEL_BASED); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_SP_FS_MRT_REG_0); /* SP_FS_MRT_REG_0 */ *cmds++ = _SET(SP_FSMRTREG_PRECISION, 1); /* SP_FS_MRT_REG_1 */ *cmds++ = 0x00000000; /* SP_FS_MRT_REG_2 */ *cmds++ = 0x00000000; /* SP_FS_MRT_REG_3 */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 11); *cmds++ = CP_REG(A3XX_VPC_ATTR); /* VPC_ATTR */ *cmds++ = _SET(VPC_VPCATTR_THRHDASSIGN, 1) | _SET(VPC_VPCATTR_LMSIZE, 1); /* VPC_PACK */ *cmds++ = 0x00000000; /* VPC_VARRYING_INTERUPT_MODE_0 */ *cmds++ = 0x00000000; /* VPC_VARRYING_INTERUPT_MODE_1 */ *cmds++ = 0x00000000; /* VPC_VARRYING_INTERUPT_MODE_2 */ *cmds++ = 0x00000000; /* VPC_VARRYING_INTERUPT_MODE_3 */ *cmds++ = 0x00000000; /* VPC_VARYING_PS_REPL_MODE_0 */ *cmds++ = 0x00000000; /* VPC_VARYING_PS_REPL_MODE_1 */ *cmds++ = 0x00000000; /* VPC_VARYING_PS_REPL_MODE_2 */ *cmds++ = 0x00000000; /* VPC_VARYING_PS_REPL_MODE_3 */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_LOAD_STATE, 10); *cmds++ = (0 << CP_LOADSTATE_DSTOFFSET_SHIFT) | (HLSQ_DIRECT << CP_LOADSTATE_STATESRC_SHIFT) | (HLSQ_BLOCK_ID_SP_VS << CP_LOADSTATE_STATEBLOCKID_SHIFT) | (1 << CP_LOADSTATE_NUMOFUNITS_SHIFT); *cmds++ = (HLSQ_SP_VS_INSTR << CP_LOADSTATE_STATETYPE_SHIFT) | (0 << CP_LOADSTATE_EXTSRCADDR_SHIFT); /* (sy)(rpt3)mov.f32f32 r0.y, (r)r1.y; */ *cmds++ = 0x00000000; *cmds++ = 0x13001000; /* end; */ *cmds++ = 0x00000000; *cmds++ = 0x00000000; /* nop; */ *cmds++ = 0x00000000; *cmds++ = 0x00000000; /* nop; */ *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_VFD_PERFCOUNTER0_SELECT, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_LOAD_STATE, 10); *cmds++ = (0 << CP_LOADSTATE_DSTOFFSET_SHIFT) | (HLSQ_DIRECT << CP_LOADSTATE_STATESRC_SHIFT) | (HLSQ_BLOCK_ID_SP_FS << CP_LOADSTATE_STATEBLOCKID_SHIFT) | (1 << CP_LOADSTATE_NUMOFUNITS_SHIFT); *cmds++ = (HLSQ_SP_FS_INSTR << CP_LOADSTATE_STATETYPE_SHIFT) | (0 << CP_LOADSTATE_EXTSRCADDR_SHIFT); /* (sy)(rpt3)mov.f32f32 r0.y, (r)c0.x; */ *cmds++ = 0x00000000; *cmds++ = 0x30201b00; /* end; */ *cmds++ = 0x00000000; *cmds++ = 0x03000000; /* nop; */ *cmds++ = 0x00000000; *cmds++ = 0x00000000; /* nop; */ *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_VFD_PERFCOUNTER0_SELECT, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_MSAA_CONTROL); /* RB_MSAA_CONTROL */ *cmds++ = _SET(RB_MSAACONTROL_MSAA_DISABLE, 1) | _SET(RB_MSAACONTROL_SAMPLE_MASK, 0xFFFF); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_DEPTH_CONTROL); /* RB_DEPTH_CONTROL */ *cmds++ = _SET(RB_DEPTHCONTROL_Z_TEST_FUNC, RB_FRAG_NEVER); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_STENCIL_CONTROL); /* RB_STENCIL_CONTROL */ *cmds++ = _SET(RB_STENCILCONTROL_STENCIL_FUNC, RB_REF_NEVER) | _SET(RB_STENCILCONTROL_STENCIL_FAIL, RB_STENCIL_KEEP) | _SET(RB_STENCILCONTROL_STENCIL_ZPASS, RB_STENCIL_KEEP) | _SET(RB_STENCILCONTROL_STENCIL_ZFAIL, RB_STENCIL_KEEP) | _SET(RB_STENCILCONTROL_STENCIL_FUNC_BF, RB_REF_NEVER) | _SET(RB_STENCILCONTROL_STENCIL_FAIL_BF, RB_STENCIL_KEEP) | _SET(RB_STENCILCONTROL_STENCIL_ZPASS_BF, RB_STENCIL_KEEP) | _SET(RB_STENCILCONTROL_STENCIL_ZFAIL_BF, RB_STENCIL_KEEP); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_GRAS_SU_MODE_CONTROL); /* GRAS_SU_MODE_CONTROL */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_MRT_CONTROL0); /* RB_MRT_CONTROL0 */ *cmds++ = _SET(RB_MRTCONTROL_READ_DEST_ENABLE, 1) | _SET(RB_MRTCONTROL_ROP_CODE, 12) | _SET(RB_MRTCONTROL_DITHER_MODE, RB_DITHER_ALWAYS) | _SET(RB_MRTCONTROL_COMPONENT_ENABLE, 0xF); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_RB_MRT_BLEND_CONTROL0); /* RB_MRT_BLEND_CONTROL0 */ *cmds++ = _SET(RB_MRTBLENDCONTROL_RGB_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_RGB_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_RGB_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_ALPHA_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_ALPHA_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_CLAMP_ENABLE, 1); /* RB_MRT_CONTROL1 */ *cmds++ = _SET(RB_MRTCONTROL_READ_DEST_ENABLE, 1) | _SET(RB_MRTCONTROL_DITHER_MODE, RB_DITHER_DISABLE) | _SET(RB_MRTCONTROL_COMPONENT_ENABLE, 0xF); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_RB_MRT_BLEND_CONTROL1); /* RB_MRT_BLEND_CONTROL1 */ *cmds++ = _SET(RB_MRTBLENDCONTROL_RGB_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_RGB_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_RGB_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_ALPHA_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_ALPHA_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_CLAMP_ENABLE, 1); /* RB_MRT_CONTROL2 */ *cmds++ = _SET(RB_MRTCONTROL_READ_DEST_ENABLE, 1) | _SET(RB_MRTCONTROL_DITHER_MODE, RB_DITHER_DISABLE) | _SET(RB_MRTCONTROL_COMPONENT_ENABLE, 0xF); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_RB_MRT_BLEND_CONTROL2); /* RB_MRT_BLEND_CONTROL2 */ *cmds++ = _SET(RB_MRTBLENDCONTROL_RGB_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_RGB_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_RGB_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_ALPHA_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_ALPHA_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_CLAMP_ENABLE, 1); /* RB_MRT_CONTROL3 */ *cmds++ = _SET(RB_MRTCONTROL_READ_DEST_ENABLE, 1) | _SET(RB_MRTCONTROL_DITHER_MODE, RB_DITHER_DISABLE) | _SET(RB_MRTCONTROL_COMPONENT_ENABLE, 0xF); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_MRT_BLEND_CONTROL3); /* RB_MRT_BLEND_CONTROL3 */ *cmds++ = _SET(RB_MRTBLENDCONTROL_RGB_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_RGB_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_RGB_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_ALPHA_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_ALPHA_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_CLAMP_ENABLE, 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_VFD_INDEX_MIN); /* VFD_INDEX_MIN */ *cmds++ = 0x00000000; /* VFD_INDEX_MAX */ *cmds++ = 0x155; /* VFD_INSTANCEID_OFFSET */ *cmds++ = 0x00000000; /* VFD_INDEX_OFFSET */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_VFD_VS_THREADING_THRESHOLD); /* VFD_VS_THREADING_THRESHOLD */ *cmds++ = _SET(VFD_THREADINGTHRESHOLD_REGID_THRESHOLD, 15) | _SET(VFD_THREADINGTHRESHOLD_REGID_VTXCNT, 252); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_TPL1_TP_VS_TEX_OFFSET); /* TPL1_TP_VS_TEX_OFFSET */ *cmds++ = 0; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_TPL1_TP_FS_TEX_OFFSET); /* TPL1_TP_FS_TEX_OFFSET */ *cmds++ = _SET(TPL1_TPTEXOFFSETREG_SAMPLEROFFSET, 16) | _SET(TPL1_TPTEXOFFSETREG_MEMOBJOFFSET, 16) | _SET(TPL1_TPTEXOFFSETREG_BASETABLEPTR, 224); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_PC_PRIM_VTX_CNTL); /* PC_PRIM_VTX_CNTL */ *cmds++ = _SET(PC_PRIM_VTX_CONTROL_POLYMODE_FRONT_PTYPE, PC_DRAW_TRIANGLES) | _SET(PC_PRIM_VTX_CONTROL_POLYMODE_BACK_PTYPE, PC_DRAW_TRIANGLES) | _SET(PC_PRIM_VTX_CONTROL_PROVOKING_VTX_LAST, 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_GRAS_SC_WINDOW_SCISSOR_TL); /* GRAS_SC_WINDOW_SCISSOR_TL */ *cmds++ = 0x00000000; /* GRAS_SC_WINDOW_SCISSOR_BR */ *cmds++ = _SET(GRAS_SC_WINDOW_SCISSOR_BR_BR_X, shadow->width - 1) | _SET(GRAS_SC_WINDOW_SCISSOR_BR_BR_Y, shadow->height - 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_GRAS_SC_SCREEN_SCISSOR_TL); /* GRAS_SC_SCREEN_SCISSOR_TL */ *cmds++ = 0x00000000; /* GRAS_SC_SCREEN_SCISSOR_BR */ *cmds++ = _SET(GRAS_SC_SCREEN_SCISSOR_BR_BR_X, shadow->width - 1) | _SET(GRAS_SC_SCREEN_SCISSOR_BR_BR_Y, shadow->height - 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_GRAS_CL_VPORT_XOFFSET); /* GRAS_CL_VPORT_XOFFSET */ *cmds++ = 0x00000000; /* GRAS_CL_VPORT_XSCALE */ *cmds++ = _SET(GRAS_CL_VPORT_XSCALE_VPORT_XSCALE, 0x3f800000); /* GRAS_CL_VPORT_YOFFSET */ *cmds++ = 0x00000000; /* GRAS_CL_VPORT_YSCALE */ *cmds++ = _SET(GRAS_CL_VPORT_YSCALE_VPORT_YSCALE, 0x3f800000); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_GRAS_CL_VPORT_ZOFFSET); /* GRAS_CL_VPORT_ZOFFSET */ *cmds++ = 0x00000000; /* GRAS_CL_VPORT_ZSCALE */ *cmds++ = _SET(GRAS_CL_VPORT_ZSCALE_VPORT_ZSCALE, 0x3f800000); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_GRAS_CL_CLIP_CNTL); /* GRAS_CL_CLIP_CNTL */ *cmds++ = _SET(GRAS_CL_CLIP_CNTL_CLIP_DISABLE, 1) | _SET(GRAS_CL_CLIP_CNTL_ZFAR_CLIP_DISABLE, 1) | _SET(GRAS_CL_CLIP_CNTL_VP_CLIP_CODE_IGNORE, 1) | _SET(GRAS_CL_CLIP_CNTL_VP_XFORM_DISABLE, 1) | _SET(GRAS_CL_CLIP_CNTL_PERSP_DIVISION_DISABLE, 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_GRAS_CL_GB_CLIP_ADJ); /* GRAS_CL_GB_CLIP_ADJ */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; /* oxili_generate_context_roll_packets */ *cmds++ = cp_type0_packet(A3XX_SP_VS_CTRL_REG0, 1); *cmds++ = 0x00000400; *cmds++ = cp_type0_packet(A3XX_SP_FS_CTRL_REG0, 1); *cmds++ = 0x00000400; *cmds++ = cp_type0_packet(A3XX_SP_VS_PVT_MEM_SIZE_REG, 1); *cmds++ = 0x00008000; /* SP_VS_MEM_SIZE_REG */ *cmds++ = cp_type0_packet(A3XX_SP_FS_PVT_MEM_SIZE_REG, 1); *cmds++ = 0x00008000; /* SP_FS_MEM_SIZE_REG */ /* Clear cache invalidate bit when re-loading the shader control regs */ *cmds++ = cp_type0_packet(A3XX_SP_VS_CTRL_REG0, 1); *cmds++ = _SET(SP_VSCTRLREG0_VSTHREADMODE, SP_MULTI) | _SET(SP_VSCTRLREG0_VSINSTRBUFFERMODE, SP_BUFFER_MODE) | _SET(SP_VSCTRLREG0_VSFULLREGFOOTPRINT, 1) | _SET(SP_VSCTRLREG0_VSTHREADSIZE, SP_TWO_VTX_QUADS) | _SET(SP_VSCTRLREG0_VSSUPERTHREADMODE, 1) | _SET(SP_VSCTRLREG0_VSLENGTH, 1); *cmds++ = cp_type0_packet(A3XX_SP_FS_CTRL_REG0, 1); *cmds++ = _SET(SP_FSCTRLREG0_FSTHREADMODE, SP_MULTI) | _SET(SP_FSCTRLREG0_FSINSTRBUFFERMODE, SP_BUFFER_MODE) | _SET(SP_FSCTRLREG0_FSHALFREGFOOTPRINT, 1) | _SET(SP_FSCTRLREG0_FSINOUTREGOVERLAP, 1) | _SET(SP_FSCTRLREG0_FSTHREADSIZE, SP_FOUR_PIX_QUADS) | _SET(SP_FSCTRLREG0_FSSUPERTHREADMODE, 1) | _SET(SP_FSCTRLREG0_FSLENGTH, 1); *cmds++ = cp_type0_packet(A3XX_SP_VS_PVT_MEM_SIZE_REG, 1); *cmds++ = 0x00000000; /* SP_VS_MEM_SIZE_REG */ *cmds++ = cp_type0_packet(A3XX_SP_FS_PVT_MEM_SIZE_REG, 1); *cmds++ = 0x00000000; /* SP_FS_MEM_SIZE_REG */ /* end oxili_generate_context_roll_packets */ /* * Resolve using two draw calls with a dummy register * write in between. This is a HLM workaround * that should be removed later. */ *cmds++ = cp_type3_packet(CP_DRAW_INDX_2, 6); *cmds++ = 0x00000000; /* Viz query info */ *cmds++ = BUILD_PC_DRAW_INITIATOR(PC_DI_PT_TRILIST, PC_DI_SRC_SEL_IMMEDIATE, PC_DI_INDEX_SIZE_32_BIT, PC_DI_IGNORE_VISIBILITY); *cmds++ = 0x00000003; /* Num indices */ *cmds++ = 0x00000000; /* Index 0 */ *cmds++ = 0x00000001; /* Index 1 */ *cmds++ = 0x00000002; /* Index 2 */ *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_HLSQ_CL_CONTROL_0_REG); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_DRAW_INDX_2, 6); *cmds++ = 0x00000000; /* Viz query info */ *cmds++ = BUILD_PC_DRAW_INITIATOR(PC_DI_PT_TRILIST, PC_DI_SRC_SEL_IMMEDIATE, PC_DI_INDEX_SIZE_32_BIT, PC_DI_IGNORE_VISIBILITY); *cmds++ = 0x00000003; /* Num indices */ *cmds++ = 0x00000002; /* Index 0 */ *cmds++ = 0x00000001; /* Index 1 */ *cmds++ = 0x00000003; /* Index 2 */ *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_HLSQ_CL_CONTROL_0_REG); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; /* Create indirect buffer command for above command sequence */ create_ib1(drawctxt, shadow->gmem_save, start, cmds); return cmds; } static void build_shader_save_cmds(struct adreno_device *adreno_dev, struct adreno_context *drawctxt) { unsigned int *cmd = tmp_ctx.cmd; unsigned int *start; /* Reserve space for boolean values used for COND_EXEC packet */ drawctxt->cond_execs[0].hostptr = cmd; drawctxt->cond_execs[0].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); *cmd++ = 0; drawctxt->cond_execs[1].hostptr = cmd; drawctxt->cond_execs[1].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); *cmd++ = 0; drawctxt->shader_save_commands[0].hostptr = cmd; drawctxt->shader_save_commands[0].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); *cmd++ = 0; drawctxt->shader_save_commands[1].hostptr = cmd; drawctxt->shader_save_commands[1].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); *cmd++ = 0; start = cmd; /* Save vertex shader */ *cmd++ = cp_type3_packet(CP_COND_EXEC, 4); *cmd++ = drawctxt->cond_execs[0].gpuaddr >> 2; *cmd++ = drawctxt->cond_execs[0].gpuaddr >> 2; *cmd++ = 0x0000FFFF; *cmd++ = 3; /* EXEC_COUNT */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); drawctxt->shader_save_commands[2].hostptr = cmd; drawctxt->shader_save_commands[2].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); /* From fixup: dwords = SP_VS_CTRL_REG0.VS_LENGTH * 8 From regspec: SP_VS_CTRL_REG0.VS_LENGTH [31:24]: VS length, unit = 256bits. If bit31 is 1, it means overflow or any long shader. src = (HLSQ_SHADOW_BASE + 0x1000)/4 */ *cmd++ = 0; /*(dwords << REG_TO_MEM_LOOP_COUNT_SHIFT) | src */ *cmd++ = (drawctxt->gpustate.gpuaddr + SHADER_OFFSET) & 0xfffffffc; /* Save fragment shader */ *cmd++ = cp_type3_packet(CP_COND_EXEC, 4); *cmd++ = drawctxt->cond_execs[1].gpuaddr >> 2; *cmd++ = drawctxt->cond_execs[1].gpuaddr >> 2; *cmd++ = 0x0000FFFF; *cmd++ = 3; /* EXEC_COUNT */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); drawctxt->shader_save_commands[3].hostptr = cmd; drawctxt->shader_save_commands[3].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); /* From fixup: dwords = SP_FS_CTRL_REG0.FS_LENGTH * 8 From regspec: SP_FS_CTRL_REG0.FS_LENGTH [31:24]: FS length, unit = 256bits. If bit31 is 1, it means overflow or any long shader. fs_offset = SP_FS_OBJ_OFFSET_REG.SHADEROBJOFFSETINIC * 32 From regspec: SP_FS_OBJ_OFFSET_REG.SHADEROBJOFFSETINIC [31:25]: First instruction of the whole shader will be stored from the offset in instruction cache, unit = 256bits, a cache line. It can start from 0 if no VS available. src = (HLSQ_SHADOW_BASE + 0x1000 + SSIZE + fs_offset)/4 */ *cmd++ = 0; /*(dwords << REG_TO_MEM_LOOP_COUNT_SHIFT) | src */ *cmd++ = (drawctxt->gpustate.gpuaddr + SHADER_OFFSET + (SHADER_SHADOW_SIZE / 2)) & 0xfffffffc; /* Create indirect buffer command for above command sequence */ create_ib1(drawctxt, drawctxt->shader_save, start, cmd); tmp_ctx.cmd = cmd; } /* * Make an IB to modify context save IBs with the correct shader instruction * and constant sizes and offsets. */ static void build_save_fixup_cmds(struct adreno_device *adreno_dev, struct adreno_context *drawctxt) { unsigned int *cmd = tmp_ctx.cmd; unsigned int *start = cmd; /* Flush HLSQ lazy updates */ *cmd++ = cp_type3_packet(CP_EVENT_WRITE, 1); *cmd++ = 0x7; /* HLSQ_FLUSH */ *cmd++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmd++ = 0; *cmd++ = cp_type0_packet(A3XX_UCHE_CACHE_INVALIDATE0_REG, 2); *cmd++ = 0x00000000; /* No start addr for full invalidate */ *cmd++ = (unsigned int) UCHE_ENTIRE_CACHE << UCHE_INVALIDATE1REG_ALLORPORTION | UCHE_OP_INVALIDATE << UCHE_INVALIDATE1REG_OPCODE | 0; /* No end addr for full invalidate */ /* Make sure registers are flushed */ *cmd++ = cp_type3_packet(CP_CONTEXT_UPDATE, 1); *cmd++ = 0; #ifdef GSL_CONTEXT_SWITCH_CPU_SYNC /* Save shader sizes */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_VS_CTRL_REG0; *cmd++ = drawctxt->shader_save_commands[2].gpuaddr; *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_FS_CTRL_REG0; *cmd++ = drawctxt->shader_save_commands[3].gpuaddr; /* Save shader offsets */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_FS_OBJ_OFFSET_REG; *cmd++ = drawctxt->shader_save_commands[1].gpuaddr; /* Save constant sizes */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_VS_CTRL_REG1; *cmd++ = drawctxt->constant_save_commands[1].gpuaddr; *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_FS_CTRL_REG1; *cmd++ = drawctxt->constant_save_commands[2].gpuaddr; /* Save FS constant offset */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_FS_OBJ_OFFSET_REG; *cmd++ = drawctxt->constant_save_commands[0].gpuaddr; /* Save VS instruction store mode */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_VS_CTRL_REG0; *cmd++ = drawctxt->cond_execs[0].gpuaddr; /* Save FS instruction store mode */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_FS_CTRL_REG0; *cmd++ = drawctxt->cond_execs[1].gpuaddr; #else /* Shader save */ cmd = rmw_regtomem(cmd, A3XX_SP_VS_CTRL_REG0, 0x7f000000, 11+REG_TO_MEM_LOOP_COUNT_SHIFT, (HLSQ_SHADOW_BASE + 0x1000) / 4, drawctxt->shader_save_commands[2].gpuaddr); /* CP_SCRATCH_REG2 = (CP_SCRATCH_REG2 & 0x00000000) | SP_FS_CTRL_REG0 */ *cmd++ = cp_type3_packet(CP_REG_RMW, 3); *cmd++ = (1 << 30) | A3XX_CP_SCRATCH_REG2; *cmd++ = 0x00000000; /* AND value */ *cmd++ = A3XX_SP_FS_CTRL_REG0; /* OR address */ /* CP_SCRATCH_REG2 = ( (CP_SCRATCH_REG2 & 0x7f000000) >> 21 ) | ((HLSQ_SHADOW_BASE+0x1000+SSIZE)/4) */ *cmd++ = cp_type3_packet(CP_REG_RMW, 3); *cmd++ = ((11 + REG_TO_MEM_LOOP_COUNT_SHIFT) << 24) | A3XX_CP_SCRATCH_REG2; *cmd++ = 0x7f000000; /* AND value */ *cmd++ = (HLSQ_SHADOW_BASE + 0x1000 + SSIZE) / 4; /* OR value */ /* * CP_SCRATCH_REG3 = (CP_SCRATCH_REG3 & 0x00000000) | * SP_FS_OBJ_OFFSET_REG */ *cmd++ = cp_type3_packet(CP_REG_RMW, 3); *cmd++ = (1 << 30) | A3XX_CP_SCRATCH_REG3; *cmd++ = 0x00000000; /* AND value */ *cmd++ = A3XX_SP_FS_OBJ_OFFSET_REG; /* OR address */ /* * CP_SCRATCH_REG3 = ( (CP_SCRATCH_REG3 & 0xfe000000) >> 25 ) | * 0x00000000 */ *cmd++ = cp_type3_packet(CP_REG_RMW, 3); *cmd++ = A3XX_CP_SCRATCH_REG3; *cmd++ = 0xfe000000; /* AND value */ *cmd++ = 0x00000000; /* OR value */ /* * CP_SCRATCH_REG2 = (CP_SCRATCH_REG2 & 0xffffffff) | CP_SCRATCH_REG3 */ *cmd++ = cp_type3_packet(CP_REG_RMW, 3); *cmd++ = (1 << 30) | A3XX_CP_SCRATCH_REG2; *cmd++ = 0xffffffff; /* AND value */ *cmd++ = A3XX_CP_SCRATCH_REG3; /* OR address */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_CP_SCRATCH_REG2; *cmd++ = drawctxt->shader_save_commands[3].gpuaddr; /* Constant save */ cmd = rmw_regtomem(cmd, A3XX_SP_VS_CTRL_REG1, 0x000003ff, 2 + REG_TO_MEM_LOOP_COUNT_SHIFT, (HLSQ_SHADOW_BASE + 0x2000) / 4, drawctxt->constant_save_commands[1].gpuaddr); cmd = rmw_regtomem(cmd, A3XX_SP_FS_CTRL_REG1, 0x000003ff, 2 + REG_TO_MEM_LOOP_COUNT_SHIFT, (HLSQ_SHADOW_BASE + 0x2000 + SSIZE) / 4, drawctxt->constant_save_commands[2].gpuaddr); cmd = rmw_regtomem(cmd, A3XX_SP_FS_OBJ_OFFSET_REG, 0x00ff0000, 18, drawctxt->gpustate.gpuaddr & 0xfffffe00, drawctxt->constant_save_commands[2].gpuaddr + sizeof(unsigned int)); /* Modify constant save conditionals */ cmd = rmw_regtomem(cmd, A3XX_SP_VS_CTRL_REG1, 0x000003ff, 0, 0, drawctxt->cond_execs[2].gpuaddr); cmd = rmw_regtomem(cmd, A3XX_SP_FS_CTRL_REG1, 0x000003ff, 0, 0, drawctxt->cond_execs[3].gpuaddr); /* Save VS instruction store mode */ cmd = rmw_regtomem(cmd, A3XX_SP_VS_CTRL_REG0, 0x00000002, 31, 0, drawctxt->cond_execs[0].gpuaddr); /* Save FS instruction store mode */ cmd = rmw_regtomem(cmd, A3XX_SP_FS_CTRL_REG0, 0x00000002, 31, 0, drawctxt->cond_execs[1].gpuaddr); #endif create_ib1(drawctxt, drawctxt->save_fixup, start, cmd); tmp_ctx.cmd = cmd; } /****************************************************************************/ /* Functions to build context restore IBs */ /****************************************************************************/ static unsigned int *build_sys2gmem_cmds(struct adreno_device *adreno_dev, struct adreno_context *drawctxt, struct gmem_shadow_t *shadow) { unsigned int *cmds = tmp_ctx.cmd; unsigned int *start = cmds; *cmds++ = cp_type0_packet(A3XX_RBBM_CLOCK_CTL, 1); *cmds++ = adreno_a3xx_rbbm_clock_ctl_default(adreno_dev); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_HLSQ_CONTROL_0_REG); /* HLSQ_CONTROL_0_REG */ *cmds++ = _SET(HLSQ_CTRL0REG_FSTHREADSIZE, HLSQ_FOUR_PIX_QUADS) | _SET(HLSQ_CTRL0REG_FSSUPERTHREADENABLE, 1) | _SET(HLSQ_CTRL0REG_SPSHADERRESTART, 1) | _SET(HLSQ_CTRL0REG_CHUNKDISABLE, 1) | _SET(HLSQ_CTRL0REG_SPCONSTFULLUPDATE, 1); /* HLSQ_CONTROL_1_REG */ *cmds++ = _SET(HLSQ_CTRL1REG_VSTHREADSIZE, HLSQ_TWO_VTX_QUADS) | _SET(HLSQ_CTRL1REG_VSSUPERTHREADENABLE, 1); /* HLSQ_CONTROL_2_REG */ *cmds++ = _SET(HLSQ_CTRL2REG_PRIMALLOCTHRESHOLD, 31); /* HLSQ_CONTROL3_REG */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_RB_MRT_BUF_INFO0); /* RB_MRT_BUF_INFO0 */ *cmds++ = _SET(RB_MRTBUFINFO_COLOR_FORMAT, RB_R8G8B8A8_UNORM) | _SET(RB_MRTBUFINFO_COLOR_TILE_MODE, RB_TILINGMODE_32X32) | _SET(RB_MRTBUFINFO_COLOR_BUF_PITCH, (shadow->gmem_pitch * 4 * 8) / 256); /* RB_MRT_BUF_BASE0 */ *cmds++ = _SET(RB_MRTBUFBASE_COLOR_BUF_BASE, tmp_ctx.gmem_base >> 5); /* Texture samplers */ *cmds++ = cp_type3_packet(CP_LOAD_STATE, 4); *cmds++ = (16 << CP_LOADSTATE_DSTOFFSET_SHIFT) | (HLSQ_DIRECT << CP_LOADSTATE_STATESRC_SHIFT) | (HLSQ_BLOCK_ID_TP_TEX << CP_LOADSTATE_STATEBLOCKID_SHIFT) | (1 << CP_LOADSTATE_NUMOFUNITS_SHIFT); *cmds++ = (HLSQ_TP_TEX_SAMPLERS << CP_LOADSTATE_STATETYPE_SHIFT) | (0 << CP_LOADSTATE_EXTSRCADDR_SHIFT); *cmds++ = 0x00000240; *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_VFD_PERFCOUNTER0_SELECT, 1); *cmds++ = 0x00000000; /* Texture memobjs */ *cmds++ = cp_type3_packet(CP_LOAD_STATE, 6); *cmds++ = (16 << CP_LOADSTATE_DSTOFFSET_SHIFT) | (HLSQ_DIRECT << CP_LOADSTATE_STATESRC_SHIFT) | (HLSQ_BLOCK_ID_TP_TEX << CP_LOADSTATE_STATEBLOCKID_SHIFT) | (1 << CP_LOADSTATE_NUMOFUNITS_SHIFT); *cmds++ = (HLSQ_TP_TEX_MEMOBJ << CP_LOADSTATE_STATETYPE_SHIFT) | (0 << CP_LOADSTATE_EXTSRCADDR_SHIFT); *cmds++ = 0x4cc06880; *cmds++ = shadow->height | (shadow->width << 14); *cmds++ = (shadow->pitch*4*8) << 9; *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_VFD_PERFCOUNTER0_SELECT, 1); *cmds++ = 0x00000000; /* Mipmap bases */ *cmds++ = cp_type3_packet(CP_LOAD_STATE, 16); *cmds++ = (224 << CP_LOADSTATE_DSTOFFSET_SHIFT) | (HLSQ_DIRECT << CP_LOADSTATE_STATESRC_SHIFT) | (HLSQ_BLOCK_ID_TP_MIPMAP << CP_LOADSTATE_STATEBLOCKID_SHIFT) | (14 << CP_LOADSTATE_NUMOFUNITS_SHIFT); *cmds++ = (HLSQ_TP_MIPMAP_BASE << CP_LOADSTATE_STATETYPE_SHIFT) | (0 << CP_LOADSTATE_EXTSRCADDR_SHIFT); *cmds++ = shadow->gmemshadow.gpuaddr; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_VFD_PERFCOUNTER0_SELECT, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_HLSQ_VS_CONTROL_REG); /* HLSQ_VS_CONTROL_REG */ *cmds++ = _SET(HLSQ_VSCTRLREG_VSINSTRLENGTH, 1); /* HLSQ_FS_CONTROL_REG */ *cmds++ = _SET(HLSQ_FSCTRLREG_FSCONSTLENGTH, 1) | _SET(HLSQ_FSCTRLREG_FSCONSTSTARTOFFSET, 128) | _SET(HLSQ_FSCTRLREG_FSINSTRLENGTH, 2); /* HLSQ_CONST_VSPRESV_RANGE_REG */ *cmds++ = 0x00000000; /* HLSQ_CONST_FSPRESV_RANGE_REG */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_SP_FS_LENGTH_REG); /* SP_FS_LENGTH_REG */ *cmds++ = _SET(SP_SHADERLENGTH_LEN, 2); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 12); *cmds++ = CP_REG(A3XX_SP_VS_CTRL_REG0); /* SP_VS_CTRL_REG0 */ *cmds++ = _SET(SP_VSCTRLREG0_VSTHREADMODE, SP_MULTI) | _SET(SP_VSCTRLREG0_VSINSTRBUFFERMODE, SP_BUFFER_MODE) | _SET(SP_VSCTRLREG0_VSICACHEINVALID, 1) | _SET(SP_VSCTRLREG0_VSFULLREGFOOTPRINT, 2) | _SET(SP_VSCTRLREG0_VSTHREADSIZE, SP_TWO_VTX_QUADS) | _SET(SP_VSCTRLREG0_VSLENGTH, 1); /* SP_VS_CTRL_REG1 */ *cmds++ = _SET(SP_VSCTRLREG1_VSINITIALOUTSTANDING, 8); /* SP_VS_PARAM_REG */ *cmds++ = _SET(SP_VSPARAMREG_POSREGID, 4) | _SET(SP_VSPARAMREG_PSIZEREGID, 252) | _SET(SP_VSPARAMREG_TOTALVSOUTVAR, 1); /* SP_VS_OUT_REG0 */ *cmds++ = _SET(SP_VSOUTREG_COMPMASK0, 3); /* SP_VS_OUT_REG1 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG2 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG3 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG4 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG5 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG6 */ *cmds++ = 0x00000000; /* SP_VS_OUT_REG7 */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 7); *cmds++ = CP_REG(A3XX_SP_VS_VPC_DST_REG_0); /* SP_VS_VPC_DST_REG0 */ *cmds++ = _SET(SP_VSVPCDSTREG_OUTLOC0, 8); /* SP_VS_VPC_DST_REG1 */ *cmds++ = 0x00000000; /* SP_VS_VPC_DST_REG2 */ *cmds++ = 0x00000000; /* SP_VS_VPC_DST_REG3 */ *cmds++ = 0x00000000; /* SP_VS_OBJ_OFFSET_REG */ *cmds++ = 0x00000000; /* SP_VS_OBJ_START_REG */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 6); *cmds++ = CP_REG(A3XX_SP_VS_LENGTH_REG); /* SP_VS_LENGTH_REG */ *cmds++ = _SET(SP_SHADERLENGTH_LEN, 1); /* SP_FS_CTRL_REG0 */ *cmds++ = _SET(SP_FSCTRLREG0_FSTHREADMODE, SP_MULTI) | _SET(SP_FSCTRLREG0_FSINSTRBUFFERMODE, SP_BUFFER_MODE) | _SET(SP_FSCTRLREG0_FSICACHEINVALID, 1) | _SET(SP_FSCTRLREG0_FSHALFREGFOOTPRINT, 1) | _SET(SP_FSCTRLREG0_FSFULLREGFOOTPRINT, 1) | _SET(SP_FSCTRLREG0_FSINOUTREGOVERLAP, 1) | _SET(SP_FSCTRLREG0_FSTHREADSIZE, SP_FOUR_PIX_QUADS) | _SET(SP_FSCTRLREG0_FSSUPERTHREADMODE, 1) | _SET(SP_FSCTRLREG0_PIXLODENABLE, 1) | _SET(SP_FSCTRLREG0_FSLENGTH, 2); /* SP_FS_CTRL_REG1 */ *cmds++ = _SET(SP_FSCTRLREG1_FSCONSTLENGTH, 1) | _SET(SP_FSCTRLREG1_FSINITIALOUTSTANDING, 2) | _SET(SP_FSCTRLREG1_HALFPRECVAROFFSET, 63); /* SP_FS_OBJ_OFFSET_REG */ *cmds++ = _SET(SP_OBJOFFSETREG_CONSTOBJECTSTARTOFFSET, 128) | _SET(SP_OBJOFFSETREG_SHADEROBJOFFSETINIC, 126); /* SP_FS_OBJ_START_REG */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_SP_FS_FLAT_SHAD_MODE_REG_0); /* SP_FS_FLAT_SHAD_MODE_REG0 */ *cmds++ = 0x00000000; /* SP_FS_FLAT_SHAD_MODE_REG1 */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_SP_FS_OUTPUT_REG); /* SP_FS_OUT_REG */ *cmds++ = _SET(SP_FSOUTREG_PAD0, SP_PIXEL_BASED); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_SP_FS_MRT_REG_0); /* SP_FS_MRT_REG0 */ *cmds++ = _SET(SP_FSMRTREG_PRECISION, 1); /* SP_FS_MRT_REG1 */ *cmds++ = 0; /* SP_FS_MRT_REG2 */ *cmds++ = 0; /* SP_FS_MRT_REG3 */ *cmds++ = 0; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 11); *cmds++ = CP_REG(A3XX_VPC_ATTR); /* VPC_ATTR */ *cmds++ = _SET(VPC_VPCATTR_TOTALATTR, 2) | _SET(VPC_VPCATTR_THRHDASSIGN, 1) | _SET(VPC_VPCATTR_LMSIZE, 1); /* VPC_PACK */ *cmds++ = _SET(VPC_VPCPACK_NUMFPNONPOSVAR, 2) | _SET(VPC_VPCPACK_NUMNONPOSVSVAR, 2); /* VPC_VARYING_INTERP_MODE_0 */ *cmds++ = 0x00000000; /* VPC_VARYING_INTERP_MODE1 */ *cmds++ = 0x00000000; /* VPC_VARYING_INTERP_MODE2 */ *cmds++ = 0x00000000; /* VPC_VARYING_IINTERP_MODE3 */ *cmds++ = 0x00000000; /* VPC_VARRYING_PS_REPL_MODE_0 */ *cmds++ = _SET(VPC_VPCVARPSREPLMODE_COMPONENT08, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT09, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0A, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0B, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0C, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0D, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0E, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0F, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT10, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT11, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT12, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT13, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT14, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT15, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT16, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT17, 2); /* VPC_VARRYING_PS_REPL_MODE_1 */ *cmds++ = _SET(VPC_VPCVARPSREPLMODE_COMPONENT08, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT09, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0A, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0B, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0C, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0D, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0E, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0F, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT10, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT11, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT12, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT13, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT14, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT15, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT16, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT17, 2); /* VPC_VARRYING_PS_REPL_MODE_2 */ *cmds++ = _SET(VPC_VPCVARPSREPLMODE_COMPONENT08, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT09, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0A, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0B, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0C, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0D, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0E, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0F, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT10, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT11, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT12, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT13, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT14, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT15, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT16, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT17, 2); /* VPC_VARRYING_PS_REPL_MODE_3 */ *cmds++ = _SET(VPC_VPCVARPSREPLMODE_COMPONENT08, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT09, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0A, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0B, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0C, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0D, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0E, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT0F, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT10, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT11, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT12, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT13, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT14, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT15, 2) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT16, 1) | _SET(VPC_VPCVARPSREPLMODE_COMPONENT17, 2); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_SP_SP_CTRL_REG); /* SP_SP_CTRL_REG */ *cmds++ = _SET(SP_SPCTRLREG_SLEEPMODE, 1) | _SET(SP_SPCTRLREG_LOMODE, 1); /* Load vertex shader */ *cmds++ = cp_type3_packet(CP_LOAD_STATE, 10); *cmds++ = (0 << CP_LOADSTATE_DSTOFFSET_SHIFT) | (HLSQ_DIRECT << CP_LOADSTATE_STATESRC_SHIFT) | (HLSQ_BLOCK_ID_SP_VS << CP_LOADSTATE_STATEBLOCKID_SHIFT) | (1 << CP_LOADSTATE_NUMOFUNITS_SHIFT); *cmds++ = (HLSQ_SP_VS_INSTR << CP_LOADSTATE_STATETYPE_SHIFT) | (0 << CP_LOADSTATE_EXTSRCADDR_SHIFT); /* (sy)end; */ *cmds++ = 0x00000000; *cmds++ = 0x13001000; /* nop; */ *cmds++ = 0x00000000; *cmds++ = 0x00000000; /* nop; */ *cmds++ = 0x00000000; *cmds++ = 0x00000000; /* nop; */ *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_VFD_PERFCOUNTER0_SELECT, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; /* Load fragment shader */ *cmds++ = cp_type3_packet(CP_LOAD_STATE, 18); *cmds++ = (0 << CP_LOADSTATE_DSTOFFSET_SHIFT) | (HLSQ_DIRECT << CP_LOADSTATE_STATESRC_SHIFT) | (HLSQ_BLOCK_ID_SP_FS << CP_LOADSTATE_STATEBLOCKID_SHIFT) | (2 << CP_LOADSTATE_NUMOFUNITS_SHIFT); *cmds++ = (HLSQ_SP_FS_INSTR << CP_LOADSTATE_STATETYPE_SHIFT) | (0 << CP_LOADSTATE_EXTSRCADDR_SHIFT); /* (sy)(rpt1)bary.f (ei)r0.z, (r)0, r0.x; */ *cmds++ = 0x00002000; *cmds++ = 0x57309902; /* (rpt5)nop; */ *cmds++ = 0x00000000; *cmds++ = 0x00000500; /* sam (f32)r0.xyzw, r0.z, s#0, t#0; */ *cmds++ = 0x00000005; *cmds++ = 0xa0c01f00; /* (sy)mov.f32f32 r1.x, r0.x; */ *cmds++ = 0x00000000; *cmds++ = 0x30040b00; /* mov.f32f32 r1.y, r0.y; */ *cmds++ = 0x00000000; *cmds++ = 0x03000000; /* mov.f32f32 r1.z, r0.z; */ *cmds++ = 0x00000000; *cmds++ = 0x00000000; /* mov.f32f32 r1.w, r0.w; */ *cmds++ = 0x00000000; *cmds++ = 0x00000000; /* end; */ *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_VFD_PERFCOUNTER0_SELECT, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_VFD_CONTROL_0); /* VFD_CONTROL_0 */ *cmds++ = _SET(VFD_CTRLREG0_TOTALATTRTOVS, 8) | _SET(VFD_CTRLREG0_PACKETSIZE, 2) | _SET(VFD_CTRLREG0_STRMDECINSTRCNT, 2) | _SET(VFD_CTRLREG0_STRMFETCHINSTRCNT, 2); /* VFD_CONTROL_1 */ *cmds++ = _SET(VFD_CTRLREG1_MAXSTORAGE, 2) | _SET(VFD_CTRLREG1_REGID4VTX, 252) | _SET(VFD_CTRLREG1_REGID4INST, 252); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_VFD_FETCH_INSTR_0_0); /* VFD_FETCH_INSTR_0_0 */ *cmds++ = _SET(VFD_FETCHINSTRUCTIONS_FETCHSIZE, 7) | _SET(VFD_FETCHINSTRUCTIONS_BUFSTRIDE, 8) | _SET(VFD_FETCHINSTRUCTIONS_SWITCHNEXT, 1) | _SET(VFD_FETCHINSTRUCTIONS_STEPRATE, 1); /* VFD_FETCH_INSTR_1_0 */ *cmds++ = _SET(VFD_BASEADDR_BASEADDR, shadow->quad_vertices_restore.gpuaddr); /* VFD_FETCH_INSTR_0_1 */ *cmds++ = _SET(VFD_FETCHINSTRUCTIONS_FETCHSIZE, 11) | _SET(VFD_FETCHINSTRUCTIONS_BUFSTRIDE, 12) | _SET(VFD_FETCHINSTRUCTIONS_INDEXDECODE, 1) | _SET(VFD_FETCHINSTRUCTIONS_STEPRATE, 1); /* VFD_FETCH_INSTR_1_1 */ *cmds++ = _SET(VFD_BASEADDR_BASEADDR, shadow->quad_vertices_restore.gpuaddr + 16); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_VFD_DECODE_INSTR_0); /* VFD_DECODE_INSTR_0 */ *cmds++ = _SET(VFD_DECODEINSTRUCTIONS_WRITEMASK, 0x0F) | _SET(VFD_DECODEINSTRUCTIONS_CONSTFILL, 1) | _SET(VFD_DECODEINSTRUCTIONS_FORMAT, 1) | _SET(VFD_DECODEINSTRUCTIONS_SHIFTCNT, 8) | _SET(VFD_DECODEINSTRUCTIONS_LASTCOMPVALID, 1) | _SET(VFD_DECODEINSTRUCTIONS_SWITCHNEXT, 1); /* VFD_DECODE_INSTR_1 */ *cmds++ = _SET(VFD_DECODEINSTRUCTIONS_WRITEMASK, 0x0F) | _SET(VFD_DECODEINSTRUCTIONS_CONSTFILL, 1) | _SET(VFD_DECODEINSTRUCTIONS_FORMAT, 2) | _SET(VFD_DECODEINSTRUCTIONS_REGID, 4) | _SET(VFD_DECODEINSTRUCTIONS_SHIFTCNT, 12) | _SET(VFD_DECODEINSTRUCTIONS_LASTCOMPVALID, 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_DEPTH_CONTROL); /* RB_DEPTH_CONTROL */ *cmds++ = _SET(RB_DEPTHCONTROL_Z_TEST_FUNC, RB_FRAG_LESS); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_STENCIL_CONTROL); /* RB_STENCIL_CONTROL */ *cmds++ = _SET(RB_STENCILCONTROL_STENCIL_FUNC, RB_REF_ALWAYS) | _SET(RB_STENCILCONTROL_STENCIL_FAIL, RB_STENCIL_KEEP) | _SET(RB_STENCILCONTROL_STENCIL_ZPASS, RB_STENCIL_KEEP) | _SET(RB_STENCILCONTROL_STENCIL_ZFAIL, RB_STENCIL_KEEP) | _SET(RB_STENCILCONTROL_STENCIL_FUNC_BF, RB_REF_ALWAYS) | _SET(RB_STENCILCONTROL_STENCIL_FAIL_BF, RB_STENCIL_KEEP) | _SET(RB_STENCILCONTROL_STENCIL_ZPASS_BF, RB_STENCIL_KEEP) | _SET(RB_STENCILCONTROL_STENCIL_ZFAIL_BF, RB_STENCIL_KEEP); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_MODE_CONTROL); /* RB_MODE_CONTROL */ *cmds++ = _SET(RB_MODECONTROL_RENDER_MODE, RB_RENDERING_PASS) | _SET(RB_MODECONTROL_MARB_CACHE_SPLIT_MODE, 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_RENDER_CONTROL); /* RB_RENDER_CONTROL */ *cmds++ = _SET(RB_RENDERCONTROL_BIN_WIDTH, shadow->width >> 5) | _SET(RB_RENDERCONTROL_ALPHA_TEST_FUNC, 7); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_MSAA_CONTROL); /* RB_MSAA_CONTROL */ *cmds++ = _SET(RB_MSAACONTROL_MSAA_DISABLE, 1) | _SET(RB_MSAACONTROL_SAMPLE_MASK, 0xFFFF); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_MRT_CONTROL0); /* RB_MRT_CONTROL0 */ *cmds++ = _SET(RB_MRTCONTROL_ROP_CODE, 12) | _SET(RB_MRTCONTROL_DITHER_MODE, RB_DITHER_DISABLE) | _SET(RB_MRTCONTROL_COMPONENT_ENABLE, 0xF); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_RB_MRT_BLEND_CONTROL0); /* RB_MRT_BLENDCONTROL0 */ *cmds++ = _SET(RB_MRTBLENDCONTROL_RGB_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_RGB_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_RGB_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_ALPHA_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_ALPHA_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_ALPHA_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_CLAMP_ENABLE, 1); /* RB_MRT_CONTROL1 */ *cmds++ = _SET(RB_MRTCONTROL_READ_DEST_ENABLE, 1) | _SET(RB_MRTCONTROL_ROP_CODE, 12) | _SET(RB_MRTCONTROL_DITHER_MODE, RB_DITHER_ALWAYS) | _SET(RB_MRTCONTROL_COMPONENT_ENABLE, 0xF); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_RB_MRT_BLEND_CONTROL1); /* RB_MRT_BLENDCONTROL1 */ *cmds++ = _SET(RB_MRTBLENDCONTROL_RGB_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_RGB_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_RGB_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_ALPHA_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_ALPHA_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_ALPHA_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_CLAMP_ENABLE, 1); /* RB_MRT_CONTROL2 */ *cmds++ = _SET(RB_MRTCONTROL_READ_DEST_ENABLE, 1) | _SET(RB_MRTCONTROL_ROP_CODE, 12) | _SET(RB_MRTCONTROL_DITHER_MODE, RB_DITHER_ALWAYS) | _SET(RB_MRTCONTROL_COMPONENT_ENABLE, 0xF); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_RB_MRT_BLEND_CONTROL2); /* RB_MRT_BLENDCONTROL2 */ *cmds++ = _SET(RB_MRTBLENDCONTROL_RGB_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_RGB_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_RGB_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_ALPHA_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_ALPHA_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_ALPHA_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_CLAMP_ENABLE, 1); /* RB_MRT_CONTROL3 */ *cmds++ = _SET(RB_MRTCONTROL_READ_DEST_ENABLE, 1) | _SET(RB_MRTCONTROL_ROP_CODE, 12) | _SET(RB_MRTCONTROL_DITHER_MODE, RB_DITHER_ALWAYS) | _SET(RB_MRTCONTROL_COMPONENT_ENABLE, 0xF); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_RB_MRT_BLEND_CONTROL3); /* RB_MRT_BLENDCONTROL3 */ *cmds++ = _SET(RB_MRTBLENDCONTROL_RGB_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_RGB_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_RGB_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_ALPHA_SRC_FACTOR, RB_FACTOR_ONE) | _SET(RB_MRTBLENDCONTROL_ALPHA_BLEND_OPCODE, RB_BLEND_OP_ADD) | _SET(RB_MRTBLENDCONTROL_ALPHA_DEST_FACTOR, RB_FACTOR_ZERO) | _SET(RB_MRTBLENDCONTROL_CLAMP_ENABLE, 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_VFD_INDEX_MIN); /* VFD_INDEX_MIN */ *cmds++ = 0x00000000; /* VFD_INDEX_MAX */ *cmds++ = 340; /* VFD_INDEX_OFFSET */ *cmds++ = 0x00000000; /* TPL1_TP_VS_TEX_OFFSET */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_VFD_VS_THREADING_THRESHOLD); /* VFD_VS_THREADING_THRESHOLD */ *cmds++ = _SET(VFD_THREADINGTHRESHOLD_REGID_THRESHOLD, 15) | _SET(VFD_THREADINGTHRESHOLD_REGID_VTXCNT, 252); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_TPL1_TP_VS_TEX_OFFSET); /* TPL1_TP_VS_TEX_OFFSET */ *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_TPL1_TP_FS_TEX_OFFSET); /* TPL1_TP_FS_TEX_OFFSET */ *cmds++ = _SET(TPL1_TPTEXOFFSETREG_SAMPLEROFFSET, 16) | _SET(TPL1_TPTEXOFFSETREG_MEMOBJOFFSET, 16) | _SET(TPL1_TPTEXOFFSETREG_BASETABLEPTR, 224); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_GRAS_SC_CONTROL); /* GRAS_SC_CONTROL */ /*cmds++ = _SET(GRAS_SC_CONTROL_RASTER_MODE, 1); *cmds++ = _SET(GRAS_SC_CONTROL_RASTER_MODE, 1) |*/ *cmds++ = 0x04001000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_GRAS_SU_MODE_CONTROL); /* GRAS_SU_MODE_CONTROL */ *cmds++ = _SET(GRAS_SU_CTRLMODE_LINEHALFWIDTH, 2); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_GRAS_SC_WINDOW_SCISSOR_TL); /* GRAS_SC_WINDOW_SCISSOR_TL */ *cmds++ = 0x00000000; /* GRAS_SC_WINDOW_SCISSOR_BR */ *cmds++ = _SET(GRAS_SC_WINDOW_SCISSOR_BR_BR_X, shadow->width - 1) | _SET(GRAS_SC_WINDOW_SCISSOR_BR_BR_Y, shadow->height - 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_GRAS_SC_SCREEN_SCISSOR_TL); /* GRAS_SC_SCREEN_SCISSOR_TL */ *cmds++ = 0x00000000; /* GRAS_SC_SCREEN_SCISSOR_BR */ *cmds++ = _SET(GRAS_SC_SCREEN_SCISSOR_BR_BR_X, shadow->width - 1) | _SET(GRAS_SC_SCREEN_SCISSOR_BR_BR_Y, shadow->height - 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 5); *cmds++ = CP_REG(A3XX_GRAS_CL_VPORT_XOFFSET); /* GRAS_CL_VPORT_XOFFSET */ *cmds++ = 0x00000000; /* GRAS_CL_VPORT_XSCALE */ *cmds++ = _SET(GRAS_CL_VPORT_XSCALE_VPORT_XSCALE, 0x3F800000); /* GRAS_CL_VPORT_YOFFSET */ *cmds++ = 0x00000000; /* GRAS_CL_VPORT_YSCALE */ *cmds++ = _SET(GRAS_CL_VPORT_YSCALE_VPORT_YSCALE, 0x3F800000); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 3); *cmds++ = CP_REG(A3XX_GRAS_CL_VPORT_ZOFFSET); /* GRAS_CL_VPORT_ZOFFSET */ *cmds++ = 0x00000000; /* GRAS_CL_VPORT_ZSCALE */ *cmds++ = _SET(GRAS_CL_VPORT_ZSCALE_VPORT_ZSCALE, 0x3F800000); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_GRAS_CL_CLIP_CNTL); /* GRAS_CL_CLIP_CNTL */ *cmds++ = _SET(GRAS_CL_CLIP_CNTL_IJ_PERSP_CENTER, 1); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_SP_FS_IMAGE_OUTPUT_REG_0); /* SP_FS_IMAGE_OUTPUT_REG_0 */ *cmds++ = _SET(SP_IMAGEOUTPUTREG_MRTFORMAT, SP_R8G8B8A8_UNORM); *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_PC_PRIM_VTX_CNTL); /* PC_PRIM_VTX_CONTROL */ *cmds++ = _SET(PC_PRIM_VTX_CONTROL_STRIDE_IN_VPC, 2) | _SET(PC_PRIM_VTX_CONTROL_POLYMODE_FRONT_PTYPE, PC_DRAW_TRIANGLES) | _SET(PC_PRIM_VTX_CONTROL_POLYMODE_BACK_PTYPE, PC_DRAW_TRIANGLES) | _SET(PC_PRIM_VTX_CONTROL_PROVOKING_VTX_LAST, 1); /* oxili_generate_context_roll_packets */ *cmds++ = cp_type0_packet(A3XX_SP_VS_CTRL_REG0, 1); *cmds++ = 0x00000400; *cmds++ = cp_type0_packet(A3XX_SP_FS_CTRL_REG0, 1); *cmds++ = 0x00000400; *cmds++ = cp_type0_packet(A3XX_SP_VS_PVT_MEM_SIZE_REG, 1); *cmds++ = 0x00008000; /* SP_VS_MEM_SIZE_REG */ *cmds++ = cp_type0_packet(A3XX_SP_FS_PVT_MEM_SIZE_REG, 1); *cmds++ = 0x00008000; /* SP_FS_MEM_SIZE_REG */ /* Clear cache invalidate bit when re-loading the shader control regs */ *cmds++ = cp_type0_packet(A3XX_SP_VS_CTRL_REG0, 1); *cmds++ = _SET(SP_VSCTRLREG0_VSTHREADMODE, SP_MULTI) | _SET(SP_VSCTRLREG0_VSINSTRBUFFERMODE, SP_BUFFER_MODE) | _SET(SP_VSCTRLREG0_VSFULLREGFOOTPRINT, 2) | _SET(SP_VSCTRLREG0_VSTHREADSIZE, SP_TWO_VTX_QUADS) | _SET(SP_VSCTRLREG0_VSLENGTH, 1); *cmds++ = cp_type0_packet(A3XX_SP_FS_CTRL_REG0, 1); *cmds++ = _SET(SP_FSCTRLREG0_FSTHREADMODE, SP_MULTI) | _SET(SP_FSCTRLREG0_FSINSTRBUFFERMODE, SP_BUFFER_MODE) | _SET(SP_FSCTRLREG0_FSHALFREGFOOTPRINT, 1) | _SET(SP_FSCTRLREG0_FSFULLREGFOOTPRINT, 1) | _SET(SP_FSCTRLREG0_FSINOUTREGOVERLAP, 1) | _SET(SP_FSCTRLREG0_FSTHREADSIZE, SP_FOUR_PIX_QUADS) | _SET(SP_FSCTRLREG0_FSSUPERTHREADMODE, 1) | _SET(SP_FSCTRLREG0_FSLENGTH, 2); *cmds++ = cp_type0_packet(A3XX_SP_VS_PVT_MEM_SIZE_REG, 1); *cmds++ = 0x00000000; /* SP_VS_MEM_SIZE_REG */ *cmds++ = cp_type0_packet(A3XX_SP_FS_PVT_MEM_SIZE_REG, 1); *cmds++ = 0x00000000; /* SP_FS_MEM_SIZE_REG */ /* end oxili_generate_context_roll_packets */ *cmds++ = cp_type3_packet(CP_DRAW_INDX, 3); *cmds++ = 0x00000000; /* Viz query info */ *cmds++ = BUILD_PC_DRAW_INITIATOR(PC_DI_PT_RECTLIST, PC_DI_SRC_SEL_AUTO_INDEX, PC_DI_INDEX_SIZE_16_BIT, PC_DI_IGNORE_VISIBILITY); *cmds++ = 0x00000002; /* Num indices */ /* Create indirect buffer command for above command sequence */ create_ib1(drawctxt, shadow->gmem_restore, start, cmds); return cmds; } static void build_regrestore_cmds(struct adreno_device *adreno_dev, struct adreno_context *drawctxt) { unsigned int *start = tmp_ctx.cmd; unsigned int *cmd = start; unsigned int *lcc_start; int i; /* Flush HLSQ lazy updates */ *cmd++ = cp_type3_packet(CP_EVENT_WRITE, 1); *cmd++ = 0x7; /* HLSQ_FLUSH */ *cmd++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmd++ = 0; *cmd++ = cp_type0_packet(A3XX_UCHE_CACHE_INVALIDATE0_REG, 2); *cmd++ = 0x00000000; /* No start addr for full invalidate */ *cmd++ = (unsigned int) UCHE_ENTIRE_CACHE << UCHE_INVALIDATE1REG_ALLORPORTION | UCHE_OP_INVALIDATE << UCHE_INVALIDATE1REG_OPCODE | 0; /* No end addr for full invalidate */ lcc_start = cmd; /* deferred cp_type3_packet(CP_LOAD_CONSTANT_CONTEXT, ???); */ cmd++; #ifdef CONFIG_MSM_KGSL_DISABLE_SHADOW_WRITES /* Force mismatch */ *cmd++ = ((drawctxt->gpustate.gpuaddr + REG_OFFSET) & 0xFFFFE000) | 1; #else *cmd++ = (drawctxt->gpustate.gpuaddr + REG_OFFSET) & 0xFFFFE000; #endif for (i = 0; i < ARRAY_SIZE(context_register_ranges) / 2; i++) { cmd = reg_range(cmd, context_register_ranges[i * 2], context_register_ranges[i * 2 + 1]); } lcc_start[0] = cp_type3_packet(CP_LOAD_CONSTANT_CONTEXT, (cmd - lcc_start) - 1); #ifdef CONFIG_MSM_KGSL_DISABLE_SHADOW_WRITES lcc_start[2] |= (0 << 24) | (4 << 16); /* Disable shadowing. */ #else lcc_start[2] |= (1 << 24) | (4 << 16); #endif for (i = 0; i < ARRAY_SIZE(global_registers); i++) { *cmd++ = cp_type0_packet(global_registers[i], 1); tmp_ctx.reg_values[i] = virt2gpu(cmd, &drawctxt->gpustate); *cmd++ = 0x00000000; } create_ib1(drawctxt, drawctxt->reg_restore, start, cmd); tmp_ctx.cmd = cmd; } static void build_constantrestore_cmds(struct adreno_device *adreno_dev, struct adreno_context *drawctxt) { unsigned int *cmd = tmp_ctx.cmd; unsigned int *start = cmd; unsigned int mode = 4; /* Indirect mode */ unsigned int stateblock; unsigned int numunits; unsigned int statetype; drawctxt->cond_execs[2].hostptr = cmd; drawctxt->cond_execs[2].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); *cmd++ = 0; drawctxt->cond_execs[3].hostptr = cmd; drawctxt->cond_execs[3].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); *cmd++ = 0; #ifndef CONFIG_MSM_KGSL_DISABLE_SHADOW_WRITES *cmd++ = cp_type3_packet(CP_LOAD_CONSTANT_CONTEXT, 3); *cmd++ = (drawctxt->gpustate.gpuaddr + REG_OFFSET) & 0xFFFFE000; *cmd++ = 4 << 16; *cmd++ = 0x0; #endif /* HLSQ full update */ *cmd++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmd++ = CP_REG(A3XX_HLSQ_CONTROL_0_REG); *cmd++ = 0x68000240; /* A3XX_HLSQ_CONTROL_0_REG */ #ifndef CONFIG_MSM_KGSL_DISABLE_SHADOW_WRITES /* Re-enable shadowing */ *cmd++ = cp_type3_packet(CP_LOAD_CONSTANT_CONTEXT, 3); *cmd++ = (drawctxt->gpustate.gpuaddr + REG_OFFSET) & 0xFFFFE000; *cmd++ = (4 << 16) | (1 << 24); *cmd++ = 0x0; #endif /* Load vertex shader constants */ *cmd++ = cp_type3_packet(CP_COND_EXEC, 4); *cmd++ = drawctxt->cond_execs[2].gpuaddr >> 2; *cmd++ = drawctxt->cond_execs[2].gpuaddr >> 2; *cmd++ = 0x0000ffff; *cmd++ = 3; /* EXEC_COUNT */ *cmd++ = cp_type3_packet(CP_LOAD_STATE, 2); drawctxt->constant_load_commands[0].hostptr = cmd; drawctxt->constant_load_commands[0].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); /* From fixup: mode = 4 (indirect) stateblock = 4 (Vertex constants) numunits = SP_VS_CTRL_REG1.VSCONSTLENGTH * 2; (256bit units) From register spec: SP_VS_CTRL_REG1.VSCONSTLENGTH [09:00]: 0-512, unit = 128bits. ord1 = (numunits<<22) | (stateblock<<19) | (mode<<16); */ *cmd++ = 0; /* ord1 */ *cmd++ = ((drawctxt->gpustate.gpuaddr) & 0xfffffffc) | 1; /* Load fragment shader constants */ *cmd++ = cp_type3_packet(CP_COND_EXEC, 4); *cmd++ = drawctxt->cond_execs[3].gpuaddr >> 2; *cmd++ = drawctxt->cond_execs[3].gpuaddr >> 2; *cmd++ = 0x0000ffff; *cmd++ = 3; /* EXEC_COUNT */ *cmd++ = cp_type3_packet(CP_LOAD_STATE, 2); drawctxt->constant_load_commands[1].hostptr = cmd; drawctxt->constant_load_commands[1].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); /* From fixup: mode = 4 (indirect) stateblock = 6 (Fragment constants) numunits = SP_FS_CTRL_REG1.FSCONSTLENGTH * 2; (256bit units) From register spec: SP_FS_CTRL_REG1.FSCONSTLENGTH [09:00]: 0-512, unit = 128bits. ord1 = (numunits<<22) | (stateblock<<19) | (mode<<16); */ *cmd++ = 0; /* ord1 */ drawctxt->constant_load_commands[2].hostptr = cmd; drawctxt->constant_load_commands[2].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); /* From fixup: base = drawctxt->gpustate.gpuaddr (ALU constant shadow base) offset = SP_FS_OBJ_OFFSET_REG.CONSTOBJECTSTARTOFFSET From register spec: SP_FS_OBJ_OFFSET_REG.CONSTOBJECTSTARTOFFSET [16:24]: Constant object start offset in on chip RAM, 128bit aligned ord2 = base + offset | 1 Because of the base alignment we can use ord2 = base | offset | 1 */ *cmd++ = 0; /* ord2 */ /* Restore VS texture memory objects */ stateblock = 0; statetype = 1; numunits = (TEX_SIZE_MEM_OBJECTS / 7) / 4; *cmd++ = cp_type3_packet(CP_LOAD_STATE, 2); *cmd++ = (numunits << 22) | (stateblock << 19) | (mode << 16); *cmd++ = ((drawctxt->gpustate.gpuaddr + VS_TEX_OFFSET_MEM_OBJECTS) & 0xfffffffc) | statetype; /* Restore VS texture mipmap addresses */ stateblock = 1; statetype = 1; numunits = TEX_SIZE_MIPMAP / 4; *cmd++ = cp_type3_packet(CP_LOAD_STATE, 2); *cmd++ = (numunits << 22) | (stateblock << 19) | (mode << 16); *cmd++ = ((drawctxt->gpustate.gpuaddr + VS_TEX_OFFSET_MIPMAP) & 0xfffffffc) | statetype; /* Restore VS texture sampler objects */ stateblock = 0; statetype = 0; numunits = (TEX_SIZE_SAMPLER_OBJ / 2) / 4; *cmd++ = cp_type3_packet(CP_LOAD_STATE, 2); *cmd++ = (numunits << 22) | (stateblock << 19) | (mode << 16); *cmd++ = ((drawctxt->gpustate.gpuaddr + VS_TEX_OFFSET_SAMPLER_OBJ) & 0xfffffffc) | statetype; /* Restore FS texture memory objects */ stateblock = 2; statetype = 1; numunits = (TEX_SIZE_MEM_OBJECTS / 7) / 4; *cmd++ = cp_type3_packet(CP_LOAD_STATE, 2); *cmd++ = (numunits << 22) | (stateblock << 19) | (mode << 16); *cmd++ = ((drawctxt->gpustate.gpuaddr + FS_TEX_OFFSET_MEM_OBJECTS) & 0xfffffffc) | statetype; /* Restore FS texture mipmap addresses */ stateblock = 3; statetype = 1; numunits = TEX_SIZE_MIPMAP / 4; *cmd++ = cp_type3_packet(CP_LOAD_STATE, 2); *cmd++ = (numunits << 22) | (stateblock << 19) | (mode << 16); *cmd++ = ((drawctxt->gpustate.gpuaddr + FS_TEX_OFFSET_MIPMAP) & 0xfffffffc) | statetype; /* Restore FS texture sampler objects */ stateblock = 2; statetype = 0; numunits = (TEX_SIZE_SAMPLER_OBJ / 2) / 4; *cmd++ = cp_type3_packet(CP_LOAD_STATE, 2); *cmd++ = (numunits << 22) | (stateblock << 19) | (mode << 16); *cmd++ = ((drawctxt->gpustate.gpuaddr + FS_TEX_OFFSET_SAMPLER_OBJ) & 0xfffffffc) | statetype; create_ib1(drawctxt, drawctxt->constant_restore, start, cmd); tmp_ctx.cmd = cmd; } static void build_shader_restore_cmds(struct adreno_device *adreno_dev, struct adreno_context *drawctxt) { unsigned int *cmd = tmp_ctx.cmd; unsigned int *start = cmd; /* Vertex shader */ *cmd++ = cp_type3_packet(CP_COND_EXEC, 4); *cmd++ = drawctxt->cond_execs[0].gpuaddr >> 2; *cmd++ = drawctxt->cond_execs[0].gpuaddr >> 2; *cmd++ = 1; *cmd++ = 3; /* EXEC_COUNT */ *cmd++ = cp_type3_packet(CP_LOAD_STATE, 2); drawctxt->shader_load_commands[0].hostptr = cmd; drawctxt->shader_load_commands[0].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); /* From fixup: mode = 4 (indirect) stateblock = 4 (Vertex shader) numunits = SP_VS_CTRL_REG0.VS_LENGTH From regspec: SP_VS_CTRL_REG0.VS_LENGTH [31:24]: VS length, unit = 256bits. If bit31 is 1, it means overflow or any long shader. ord1 = (numunits<<22) | (stateblock<<19) | (mode<<11) */ *cmd++ = 0; /*ord1 */ *cmd++ = (drawctxt->gpustate.gpuaddr + SHADER_OFFSET) & 0xfffffffc; /* Fragment shader */ *cmd++ = cp_type3_packet(CP_COND_EXEC, 4); *cmd++ = drawctxt->cond_execs[1].gpuaddr >> 2; *cmd++ = drawctxt->cond_execs[1].gpuaddr >> 2; *cmd++ = 1; *cmd++ = 3; /* EXEC_COUNT */ *cmd++ = cp_type3_packet(CP_LOAD_STATE, 2); drawctxt->shader_load_commands[1].hostptr = cmd; drawctxt->shader_load_commands[1].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); /* From fixup: mode = 4 (indirect) stateblock = 6 (Fragment shader) numunits = SP_FS_CTRL_REG0.FS_LENGTH From regspec: SP_FS_CTRL_REG0.FS_LENGTH [31:24]: FS length, unit = 256bits. If bit31 is 1, it means overflow or any long shader. ord1 = (numunits<<22) | (stateblock<<19) | (mode<<11) */ *cmd++ = 0; /*ord1 */ *cmd++ = (drawctxt->gpustate.gpuaddr + SHADER_OFFSET + (SHADER_SHADOW_SIZE / 2)) & 0xfffffffc; create_ib1(drawctxt, drawctxt->shader_restore, start, cmd); tmp_ctx.cmd = cmd; } static void build_hlsqcontrol_restore_cmds(struct adreno_device *adreno_dev, struct adreno_context *drawctxt) { unsigned int *cmd = tmp_ctx.cmd; unsigned int *start = cmd; *cmd++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmd++ = CP_REG(A3XX_HLSQ_CONTROL_0_REG); drawctxt->hlsqcontrol_restore_commands[0].hostptr = cmd; drawctxt->hlsqcontrol_restore_commands[0].gpuaddr = virt2gpu(cmd, &drawctxt->gpustate); *cmd++ = 0; /* Create indirect buffer command for above command sequence */ create_ib1(drawctxt, drawctxt->hlsqcontrol_restore, start, cmd); tmp_ctx.cmd = cmd; } /* IB that modifies the shader and constant sizes and offsets in restore IBs. */ static void build_restore_fixup_cmds(struct adreno_device *adreno_dev, struct adreno_context *drawctxt) { unsigned int *cmd = tmp_ctx.cmd; unsigned int *start = cmd; #ifdef GSL_CONTEXT_SWITCH_CPU_SYNC /* Save shader sizes */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_VS_CTRL_REG0; *cmd++ = drawctxt->shader_load_commands[0].gpuaddr; *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_FS_CTRL_REG0; *cmd++ = drawctxt->shader_load_commands[1].gpuaddr; /* Save constant sizes */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_VS_CTRL_REG1; *cmd++ = drawctxt->constant_load_commands[0].gpuaddr; *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_FS_CTRL_REG1; *cmd++ = drawctxt->constant_load_commands[1].gpuaddr; /* Save constant offsets */ *cmd++ = cp_type3_packet(CP_REG_TO_MEM, 2); *cmd++ = A3XX_SP_FS_OBJ_OFFSET_REG; *cmd++ = drawctxt->constant_load_commands[2].gpuaddr; #else /* Save shader sizes */ cmd = rmw_regtomem(cmd, A3XX_SP_VS_CTRL_REG0, 0x7f000000, 30, (4 << 19) | (4 << 16), drawctxt->shader_load_commands[0].gpuaddr); cmd = rmw_regtomem(cmd, A3XX_SP_FS_CTRL_REG0, 0x7f000000, 30, (6 << 19) | (4 << 16), drawctxt->shader_load_commands[1].gpuaddr); /* Save constant sizes */ cmd = rmw_regtomem(cmd, A3XX_SP_VS_CTRL_REG1, 0x000003ff, 23, (4 << 19) | (4 << 16), drawctxt->constant_load_commands[0].gpuaddr); cmd = rmw_regtomem(cmd, A3XX_SP_FS_CTRL_REG1, 0x000003ff, 23, (6 << 19) | (4 << 16), drawctxt->constant_load_commands[1].gpuaddr); /* Modify constant restore conditionals */ cmd = rmw_regtomem(cmd, A3XX_SP_VS_CTRL_REG1, 0x000003ff, 0, 0, drawctxt->cond_execs[2].gpuaddr); cmd = rmw_regtomem(cmd, A3XX_SP_FS_CTRL_REG1, 0x000003ff, 0, 0, drawctxt->cond_execs[3].gpuaddr); /* Save fragment constant shadow offset */ cmd = rmw_regtomem(cmd, A3XX_SP_FS_OBJ_OFFSET_REG, 0x00ff0000, 18, (drawctxt->gpustate.gpuaddr & 0xfffffe00) | 1, drawctxt->constant_load_commands[2].gpuaddr); #endif /* Use mask value to avoid flushing HLSQ which would cause the HW to discard all the shader data */ cmd = rmw_regtomem(cmd, A3XX_HLSQ_CONTROL_0_REG, 0x9ffffdff, 0, 0, drawctxt->hlsqcontrol_restore_commands[0].gpuaddr); create_ib1(drawctxt, drawctxt->restore_fixup, start, cmd); tmp_ctx.cmd = cmd; } static int a3xx_create_gpustate_shadow(struct adreno_device *adreno_dev, struct adreno_context *drawctxt) { build_regrestore_cmds(adreno_dev, drawctxt); build_constantrestore_cmds(adreno_dev, drawctxt); build_hlsqcontrol_restore_cmds(adreno_dev, drawctxt); build_regconstantsave_cmds(adreno_dev, drawctxt); build_shader_save_cmds(adreno_dev, drawctxt); build_shader_restore_cmds(adreno_dev, drawctxt); build_restore_fixup_cmds(adreno_dev, drawctxt); build_save_fixup_cmds(adreno_dev, drawctxt); return 0; } /* create buffers for saving/restoring registers, constants, & GMEM */ static int a3xx_create_gmem_shadow(struct adreno_device *adreno_dev, struct adreno_context *drawctxt) { int result; calc_gmemsize(&drawctxt->context_gmem_shadow, adreno_dev->gmem_size); tmp_ctx.gmem_base = adreno_dev->gmem_base; result = kgsl_allocate(&drawctxt->context_gmem_shadow.gmemshadow, drawctxt->base.proc_priv->pagetable, drawctxt->context_gmem_shadow.size); if (result) return result; build_quad_vtxbuff(drawctxt, &drawctxt->context_gmem_shadow, &tmp_ctx.cmd); tmp_ctx.cmd = build_gmem2sys_cmds(adreno_dev, drawctxt, &drawctxt->context_gmem_shadow); tmp_ctx.cmd = build_sys2gmem_cmds(adreno_dev, drawctxt, &drawctxt->context_gmem_shadow); kgsl_cache_range_op(&drawctxt->context_gmem_shadow.gmemshadow, KGSL_CACHE_OP_FLUSH); return 0; } static void a3xx_drawctxt_detach(struct adreno_context *drawctxt) { kgsl_sharedmem_free(&drawctxt->gpustate); kgsl_sharedmem_free(&drawctxt->context_gmem_shadow.gmemshadow); } static int a3xx_drawctxt_save(struct adreno_device *adreno_dev, struct adreno_context *context); static int a3xx_drawctxt_restore(struct adreno_device *adreno_dev, struct adreno_context *context); static const struct adreno_context_ops a3xx_legacy_ctx_ops = { .save = a3xx_drawctxt_save, .restore = a3xx_drawctxt_restore, .detach = a3xx_drawctxt_detach, }; static int a3xx_drawctxt_create(struct adreno_device *adreno_dev, struct adreno_context *drawctxt) { int ret; /* * Nothing to do here if the context is using preambles and doesn't need * GMEM save/restore */ if ((drawctxt->base.flags & KGSL_CONTEXT_PREAMBLE) && (drawctxt->base.flags & KGSL_CONTEXT_NO_GMEM_ALLOC)) { drawctxt->ops = &adreno_preamble_ctx_ops; return 0; } drawctxt->ops = &a3xx_legacy_ctx_ops; ret = kgsl_allocate(&drawctxt->gpustate, drawctxt->base.proc_priv->pagetable, CONTEXT_SIZE); if (ret) return ret; kgsl_sharedmem_set(&adreno_dev->dev, &drawctxt->gpustate, 0, 0, CONTEXT_SIZE); tmp_ctx.cmd = drawctxt->gpustate.hostptr + CMD_OFFSET; if (!(drawctxt->base.flags & KGSL_CONTEXT_PREAMBLE)) { ret = a3xx_create_gpustate_shadow(adreno_dev, drawctxt); if (ret) goto done; set_bit(ADRENO_CONTEXT_SHADER_SAVE, &drawctxt->priv); } if (!(drawctxt->base.flags & KGSL_CONTEXT_NO_GMEM_ALLOC)) ret = a3xx_create_gmem_shadow(adreno_dev, drawctxt); done: if (ret) kgsl_sharedmem_free(&drawctxt->gpustate); return ret; } static int a3xx_drawctxt_save(struct adreno_device *adreno_dev, struct adreno_context *context) { struct kgsl_device *device = &adreno_dev->dev; int ret; if (context->state == ADRENO_CONTEXT_STATE_INVALID) return 0; if (!(context->base.flags & KGSL_CONTEXT_PREAMBLE)) { /* Fixup self modifying IBs for save operations */ ret = adreno_ringbuffer_issuecmds(device, context, KGSL_CMD_FLAGS_NONE, context->save_fixup, 3); if (ret) return ret; /* save registers and constants. */ ret = adreno_ringbuffer_issuecmds(device, context, KGSL_CMD_FLAGS_NONE, context->regconstant_save, 3); if (ret) return ret; if (test_bit(ADRENO_CONTEXT_SHADER_SAVE, &context->priv)) { /* Save shader instructions */ ret = adreno_ringbuffer_issuecmds(device, context, KGSL_CMD_FLAGS_PMODE, context->shader_save, 3); if (ret) return ret; set_bit(ADRENO_CONTEXT_SHADER_RESTORE, &context->priv); } } if (test_bit(ADRENO_CONTEXT_GMEM_SAVE, &context->priv)) { /* * Save GMEM (note: changes shader. shader must * already be saved.) */ kgsl_cffdump_syncmem(context->base.device, &context->gpustate, context->context_gmem_shadow.gmem_save[1], context->context_gmem_shadow.gmem_save[2] << 2, true); ret = adreno_ringbuffer_issuecmds(device, context, KGSL_CMD_FLAGS_PMODE, context->context_gmem_shadow. gmem_save, 3); if (ret) return ret; set_bit(ADRENO_CONTEXT_GMEM_RESTORE, &context->priv); } return 0; } static int a3xx_drawctxt_restore(struct adreno_device *adreno_dev, struct adreno_context *context) { struct kgsl_device *device = &adreno_dev->dev; int ret; /* do the common part */ ret = adreno_context_restore(adreno_dev, context); if (ret) return ret; /* * Restore GMEM. (note: changes shader. * Shader must not already be restored.) */ if (test_bit(ADRENO_CONTEXT_GMEM_RESTORE, &context->priv)) { kgsl_cffdump_syncmem(context->base.device, &context->gpustate, context->context_gmem_shadow.gmem_restore[1], context->context_gmem_shadow.gmem_restore[2] << 2, true); ret = adreno_ringbuffer_issuecmds(device, context, KGSL_CMD_FLAGS_PMODE, context->context_gmem_shadow. gmem_restore, 3); if (ret) return ret; clear_bit(ADRENO_CONTEXT_GMEM_RESTORE, &context->priv); } if (!(context->base.flags & KGSL_CONTEXT_PREAMBLE)) { ret = adreno_ringbuffer_issuecmds(device, context, KGSL_CMD_FLAGS_NONE, context->reg_restore, 3); if (ret) return ret; /* Fixup self modifying IBs for restore operations */ ret = adreno_ringbuffer_issuecmds(device, context, KGSL_CMD_FLAGS_NONE, context->restore_fixup, 3); if (ret) return ret; ret = adreno_ringbuffer_issuecmds(device, context, KGSL_CMD_FLAGS_NONE, context->constant_restore, 3); if (ret) return ret; if (test_bit(ADRENO_CONTEXT_SHADER_RESTORE, &context->priv)) { ret = adreno_ringbuffer_issuecmds(device, context, KGSL_CMD_FLAGS_NONE, context->shader_restore, 3); if (ret) return ret; } /* Restore HLSQ_CONTROL_0 register */ ret = adreno_ringbuffer_issuecmds(device, context, KGSL_CMD_FLAGS_NONE, context->hlsqcontrol_restore, 3); } return ret; } static const unsigned int _a3xx_pwron_fixup_fs_instructions[] = { 0x00000000, 0x302CC300, 0x00000000, 0x302CC304, 0x00000000, 0x302CC308, 0x00000000, 0x302CC30C, 0x00000000, 0x302CC310, 0x00000000, 0x302CC314, 0x00000000, 0x302CC318, 0x00000000, 0x302CC31C, 0x00000000, 0x302CC320, 0x00000000, 0x302CC324, 0x00000000, 0x302CC328, 0x00000000, 0x302CC32C, 0x00000000, 0x302CC330, 0x00000000, 0x302CC334, 0x00000000, 0x302CC338, 0x00000000, 0x302CC33C, 0x00000000, 0x00000400, 0x00020000, 0x63808003, 0x00060004, 0x63828007, 0x000A0008, 0x6384800B, 0x000E000C, 0x6386800F, 0x00120010, 0x63888013, 0x00160014, 0x638A8017, 0x001A0018, 0x638C801B, 0x001E001C, 0x638E801F, 0x00220020, 0x63908023, 0x00260024, 0x63928027, 0x002A0028, 0x6394802B, 0x002E002C, 0x6396802F, 0x00320030, 0x63988033, 0x00360034, 0x639A8037, 0x003A0038, 0x639C803B, 0x003E003C, 0x639E803F, 0x00000000, 0x00000400, 0x00000003, 0x80D60003, 0x00000007, 0x80D60007, 0x0000000B, 0x80D6000B, 0x0000000F, 0x80D6000F, 0x00000013, 0x80D60013, 0x00000017, 0x80D60017, 0x0000001B, 0x80D6001B, 0x0000001F, 0x80D6001F, 0x00000023, 0x80D60023, 0x00000027, 0x80D60027, 0x0000002B, 0x80D6002B, 0x0000002F, 0x80D6002F, 0x00000033, 0x80D60033, 0x00000037, 0x80D60037, 0x0000003B, 0x80D6003B, 0x0000003F, 0x80D6003F, 0x00000000, 0x03000000, 0x00000000, 0x00000000, }; /** * adreno_a3xx_pwron_fixup_init() - Initalize a special command buffer to run a * post-power collapse shader workaround * @adreno_dev: Pointer to a adreno_device struct * * Some targets require a special workaround shader to be executed after * power-collapse. Construct the IB once at init time and keep it * handy * * Returns: 0 on success or negative on error */ int adreno_a3xx_pwron_fixup_init(struct adreno_device *adreno_dev) { unsigned int *cmds; int count = ARRAY_SIZE(_a3xx_pwron_fixup_fs_instructions); int ret; /* Return if the fixup is already in place */ if (test_bit(ADRENO_DEVICE_PWRON_FIXUP, &adreno_dev->priv)) return 0; ret = kgsl_allocate_contiguous(&adreno_dev->pwron_fixup, PAGE_SIZE); if (ret) return ret; adreno_dev->pwron_fixup.flags |= KGSL_MEMFLAGS_GPUREADONLY; cmds = adreno_dev->pwron_fixup.hostptr; *cmds++ = cp_type0_packet(A3XX_UCHE_CACHE_INVALIDATE0_REG, 2); *cmds++ = 0x00000000; *cmds++ = 0x90000000; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_REG_RMW, 3); *cmds++ = A3XX_RBBM_CLOCK_CTL; *cmds++ = 0xFFFCFFFF; *cmds++ = 0x00010000; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CONTROL_0_REG, 1); *cmds++ = 0x1E000150; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_HLSQ_CONTROL_0_REG); *cmds++ = 0x1E000150; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CONTROL_0_REG, 1); *cmds++ = 0x1E000150; *cmds++ = cp_type0_packet(A3XX_HLSQ_CONTROL_1_REG, 1); *cmds++ = 0x00000040; *cmds++ = cp_type0_packet(A3XX_HLSQ_CONTROL_2_REG, 1); *cmds++ = 0x80000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CONTROL_3_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_VS_CONTROL_REG, 1); *cmds++ = 0x00000001; *cmds++ = cp_type0_packet(A3XX_HLSQ_FS_CONTROL_REG, 1); *cmds++ = 0x0D001002; *cmds++ = cp_type0_packet(A3XX_HLSQ_CONST_VSPRESV_RANGE_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CONST_FSPRESV_RANGE_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_NDRANGE_0_REG, 1); *cmds++ = 0x00401101; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_NDRANGE_1_REG, 1); *cmds++ = 0x00000400; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_NDRANGE_2_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_NDRANGE_3_REG, 1); *cmds++ = 0x00000001; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_NDRANGE_4_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_NDRANGE_5_REG, 1); *cmds++ = 0x00000001; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_NDRANGE_6_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_CONTROL_0_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_CONTROL_1_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_KERNEL_CONST_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_KERNEL_GROUP_X_REG, 1); *cmds++ = 0x00000010; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_KERNEL_GROUP_Y_REG, 1); *cmds++ = 0x00000001; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_KERNEL_GROUP_Z_REG, 1); *cmds++ = 0x00000001; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_WG_OFFSET_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_SP_CTRL_REG, 1); *cmds++ = 0x00040000; *cmds++ = cp_type0_packet(A3XX_SP_VS_CTRL_REG0, 1); *cmds++ = 0x0000000A; *cmds++ = cp_type0_packet(A3XX_SP_VS_CTRL_REG1, 1); *cmds++ = 0x00000001; *cmds++ = cp_type0_packet(A3XX_SP_VS_PARAM_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_OUT_REG_0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_OUT_REG_1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_OUT_REG_2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_OUT_REG_3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_OUT_REG_4, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_OUT_REG_5, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_OUT_REG_6, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_OUT_REG_7, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_VPC_DST_REG_0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_VPC_DST_REG_1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_VPC_DST_REG_2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_VPC_DST_REG_3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_OBJ_OFFSET_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_OBJ_START_REG, 1); *cmds++ = 0x00000004; *cmds++ = cp_type0_packet(A3XX_SP_VS_PVT_MEM_PARAM_REG, 1); *cmds++ = 0x04008001; *cmds++ = cp_type0_packet(A3XX_SP_VS_PVT_MEM_ADDR_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_PVT_MEM_SIZE_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_VS_LENGTH_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_CTRL_REG0, 1); *cmds++ = 0x0DB0400A; *cmds++ = cp_type0_packet(A3XX_SP_FS_CTRL_REG1, 1); *cmds++ = 0x00300402; *cmds++ = cp_type0_packet(A3XX_SP_FS_OBJ_OFFSET_REG, 1); *cmds++ = 0x00010000; *cmds++ = cp_type0_packet(A3XX_SP_FS_OBJ_START_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_PVT_MEM_PARAM_REG, 1); *cmds++ = 0x04008001; *cmds++ = cp_type0_packet(A3XX_SP_FS_PVT_MEM_ADDR_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_PVT_MEM_SIZE_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_FLAT_SHAD_MODE_REG_0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_FLAT_SHAD_MODE_REG_1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_OUTPUT_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_MRT_REG_0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_MRT_REG_1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_MRT_REG_2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_MRT_REG_3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_IMAGE_OUTPUT_REG_0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_IMAGE_OUTPUT_REG_1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_IMAGE_OUTPUT_REG_2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_IMAGE_OUTPUT_REG_3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_SP_FS_LENGTH_REG, 1); *cmds++ = 0x0000000D; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_CLIP_CNTL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_GB_CLIP_ADJ, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_VPORT_XOFFSET, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_VPORT_XSCALE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_VPORT_YOFFSET, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_VPORT_YSCALE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_VPORT_ZOFFSET, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_VPORT_ZSCALE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_X0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Y0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Z0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_W0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_X1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Y1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Z1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_W1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_X2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Y2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Z2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_W2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_X3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Y3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Z3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_W3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_X4, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Y4, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Z4, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_W4, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_X5, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Y5, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_Z5, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_CL_USER_PLANE_W5, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_SU_POINT_MINMAX, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_SU_POINT_SIZE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_SU_POLY_OFFSET_OFFSET, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_SU_POLY_OFFSET_SCALE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_SU_MODE_CONTROL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_SC_CONTROL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_SC_SCREEN_SCISSOR_TL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_SC_SCREEN_SCISSOR_BR, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_SC_WINDOW_SCISSOR_BR, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_SC_WINDOW_SCISSOR_TL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_TSE_DEBUG_ECO, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_PERFCOUNTER0_SELECT, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_PERFCOUNTER1_SELECT, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_PERFCOUNTER2_SELECT, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_GRAS_PERFCOUNTER3_SELECT, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MODE_CONTROL, 1); *cmds++ = 0x00008000; *cmds++ = cp_type0_packet(A3XX_RB_RENDER_CONTROL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MSAA_CONTROL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_ALPHA_REFERENCE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_CONTROL0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_CONTROL1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_CONTROL2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_CONTROL3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BUF_INFO0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BUF_INFO1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BUF_INFO2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BUF_INFO3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BUF_BASE0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BUF_BASE1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BUF_BASE2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BUF_BASE3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BLEND_CONTROL0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BLEND_CONTROL1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BLEND_CONTROL2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_MRT_BLEND_CONTROL3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_BLEND_RED, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_BLEND_GREEN, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_BLEND_BLUE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_BLEND_ALPHA, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_CLEAR_COLOR_DW0, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_CLEAR_COLOR_DW1, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_CLEAR_COLOR_DW2, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_CLEAR_COLOR_DW3, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_COPY_CONTROL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_COPY_DEST_BASE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_COPY_DEST_PITCH, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_COPY_DEST_INFO, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_DEPTH_CONTROL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_DEPTH_CLEAR, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_DEPTH_BUF_INFO, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_DEPTH_BUF_PITCH, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_STENCIL_CONTROL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_STENCIL_CLEAR, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_STENCIL_BUF_INFO, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_STENCIL_BUF_PITCH, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_STENCIL_REF_MASK, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_STENCIL_REF_MASK_BF, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_LRZ_VSC_CONTROL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_WINDOW_OFFSET, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_SAMPLE_COUNT_CONTROL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_SAMPLE_COUNT_ADDR, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_Z_CLAMP_MIN, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_Z_CLAMP_MAX, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_GMEM_BASE_ADDR, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_DEBUG_ECO_CONTROLS_ADDR, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_PERFCOUNTER0_SELECT, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_PERFCOUNTER1_SELECT, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_RB_FRAME_BUFFER_DIMENSION, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_LOAD_STATE, 4); *cmds++ = (1 << CP_LOADSTATE_DSTOFFSET_SHIFT) | (0 << CP_LOADSTATE_STATESRC_SHIFT) | (6 << CP_LOADSTATE_STATEBLOCKID_SHIFT) | (1 << CP_LOADSTATE_NUMOFUNITS_SHIFT); *cmds++ = (1 << CP_LOADSTATE_STATETYPE_SHIFT) | (0 << CP_LOADSTATE_EXTSRCADDR_SHIFT); *cmds++ = 0x00400000; *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_LOAD_STATE, 4); *cmds++ = (2 << CP_LOADSTATE_DSTOFFSET_SHIFT) | (6 << CP_LOADSTATE_STATEBLOCKID_SHIFT) | (1 << CP_LOADSTATE_NUMOFUNITS_SHIFT); *cmds++ = (1 << CP_LOADSTATE_STATETYPE_SHIFT); *cmds++ = 0x00400220; *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_LOAD_STATE, 4); *cmds++ = (6 << CP_LOADSTATE_STATEBLOCKID_SHIFT) | (1 << CP_LOADSTATE_NUMOFUNITS_SHIFT); *cmds++ = (1 << CP_LOADSTATE_STATETYPE_SHIFT); *cmds++ = 0x00000000; *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_LOAD_STATE, 2 + count); *cmds++ = (6 << CP_LOADSTATE_STATEBLOCKID_SHIFT) | (13 << CP_LOADSTATE_NUMOFUNITS_SHIFT); *cmds++ = 0x00000000; memcpy(cmds, _a3xx_pwron_fixup_fs_instructions, count << 2); cmds += count; *cmds++ = cp_type3_packet(CP_EXEC_CL, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CL_CONTROL_0_REG, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type0_packet(A3XX_HLSQ_CONTROL_0_REG, 1); *cmds++ = 0x1E000150; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2); *cmds++ = CP_REG(A3XX_HLSQ_CONTROL_0_REG); *cmds++ = 0x1E000050; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_REG_RMW, 3); *cmds++ = A3XX_RBBM_CLOCK_CTL; *cmds++ = 0xFFFCFFFF; *cmds++ = 0x00000000; *cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1); *cmds++ = 0x00000000; /* * Remember the number of dwords in the command buffer for when we * program the indirect buffer call in the ringbuffer */ adreno_dev->pwron_fixup_dwords = (cmds - (unsigned int *) adreno_dev->pwron_fixup.hostptr); /* Mark the flag in ->priv to show that we have the fix */ set_bit(ADRENO_DEVICE_PWRON_FIXUP, &adreno_dev->priv); return 0; } static int a3xx_rb_init(struct adreno_device *adreno_dev, struct adreno_ringbuffer *rb) { unsigned int *cmds, cmds_gpu; cmds = adreno_ringbuffer_allocspace(rb, NULL, 18); if (cmds == NULL) return -ENOMEM; cmds_gpu = rb->buffer_desc.gpuaddr + sizeof(uint) * (rb->wptr - 18); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, cp_type3_packet(CP_ME_INIT, 17)); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x000003f7); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000000); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000000); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000000); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000080); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000100); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000180); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00006600); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000150); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x0000014e); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000154); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000001); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000000); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000000); /* Protected mode control - turned off for A3XX */ GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000000); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000000); GSL_RB_WRITE(rb->device, cmds, cmds_gpu, 0x00000000); adreno_ringbuffer_submit(rb); return 0; } static void a3xx_err_callback(struct adreno_device *adreno_dev, int bit) { struct kgsl_device *device = &adreno_dev->dev; const char *err = ""; switch (bit) { case A3XX_INT_RBBM_AHB_ERROR: { unsigned int reg; kgsl_regread(device, A3XX_RBBM_AHB_ERROR_STATUS, &reg); /* * Return the word address of the erroring register so that it * matches the register specification */ KGSL_DRV_CRIT(device, "RBBM | AHB bus error | %s | addr=%x | ports=%x:%x\n", reg & (1 << 28) ? "WRITE" : "READ", (reg & 0xFFFFF) >> 2, (reg >> 20) & 0x3, (reg >> 24) & 0x3); /* Clear the error */ kgsl_regwrite(device, A3XX_RBBM_AHB_CMD, (1 << 3)); goto done; } case A3XX_INT_RBBM_REG_TIMEOUT: err = "RBBM: AHB register timeout"; break; case A3XX_INT_RBBM_ME_MS_TIMEOUT: err = "RBBM: ME master split timeout"; break; case A3XX_INT_RBBM_PFP_MS_TIMEOUT: err = "RBBM: PFP master split timeout"; break; case A3XX_INT_RBBM_ATB_BUS_OVERFLOW: err = "RBBM: ATB bus oveflow"; break; case A3XX_INT_VFD_ERROR: err = "VFD: Out of bounds access"; break; case A3XX_INT_CP_T0_PACKET_IN_IB: err = "ringbuffer TO packet in IB interrupt"; break; case A3XX_INT_CP_OPCODE_ERROR: err = "ringbuffer opcode error interrupt"; break; case A3XX_INT_CP_RESERVED_BIT_ERROR: err = "ringbuffer reserved bit error interrupt"; break; case A3XX_INT_CP_HW_FAULT: err = "ringbuffer hardware fault"; break; case A3XX_INT_CP_REG_PROTECT_FAULT: err = "ringbuffer protected mode error interrupt"; break; case A3XX_INT_CP_AHB_ERROR_HALT: err = "ringbuffer AHB error interrupt"; break; case A3XX_INT_MISC_HANG_DETECT: err = "MISC: GPU hang detected"; break; case A3XX_INT_UCHE_OOB_ACCESS: err = "UCHE: Out of bounds access"; break; default: return; } KGSL_DRV_CRIT(device, "%s\n", err); kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_OFF); done: /* Trigger a fault in the dispatcher - this will effect a restart */ adreno_dispatcher_irq_fault(device); } static void a3xx_cp_callback(struct adreno_device *adreno_dev, int irq) { struct kgsl_device *device = &adreno_dev->dev; device->pwrctrl.irq_last = 1; queue_work(device->work_queue, &device->ts_expired_ws); adreno_dispatcher_schedule(device); } static int a3xx_perfcounter_enable_pwr(struct kgsl_device *device, unsigned int counter) { unsigned int in, out; if (counter > 1) return -EINVAL; kgsl_regread(device, A3XX_RBBM_RBBM_CTL, &in); if (counter == 0) out = in | RBBM_RBBM_CTL_RESET_PWR_CTR0; else out = in | RBBM_RBBM_CTL_RESET_PWR_CTR1; kgsl_regwrite(device, A3XX_RBBM_RBBM_CTL, out); if (counter == 0) out = in | RBBM_RBBM_CTL_ENABLE_PWR_CTR0; else out = in | RBBM_RBBM_CTL_ENABLE_PWR_CTR1; kgsl_regwrite(device, A3XX_RBBM_RBBM_CTL, out); return 0; } static int a3xx_perfcounter_enable_vbif(struct kgsl_device *device, unsigned int counter, unsigned int countable) { unsigned int in, out, bit, sel; if (counter > 1 || countable > 0x7f) return -EINVAL; kgsl_regread(device, A3XX_VBIF_PERF_CNT_EN, &in); kgsl_regread(device, A3XX_VBIF_PERF_CNT_SEL, &sel); if (counter == 0) { bit = VBIF_PERF_CNT_0; sel = (sel & ~VBIF_PERF_CNT_0_SEL_MASK) | countable; } else { bit = VBIF_PERF_CNT_1; sel = (sel & ~VBIF_PERF_CNT_1_SEL_MASK) | (countable << VBIF_PERF_CNT_1_SEL); } out = in | bit; kgsl_regwrite(device, A3XX_VBIF_PERF_CNT_SEL, sel); kgsl_regwrite(device, A3XX_VBIF_PERF_CNT_CLR, bit); kgsl_regwrite(device, A3XX_VBIF_PERF_CNT_CLR, 0); kgsl_regwrite(device, A3XX_VBIF_PERF_CNT_EN, out); return 0; } static int a3xx_perfcounter_enable_vbif_pwr(struct kgsl_device *device, unsigned int counter) { unsigned int in, out, bit; if (counter > 2) return -EINVAL; kgsl_regread(device, A3XX_VBIF_PERF_CNT_EN, &in); if (counter == 0) bit = VBIF_PERF_PWR_CNT_0; else if (counter == 1) bit = VBIF_PERF_PWR_CNT_1; else bit = VBIF_PERF_PWR_CNT_2; out = in | bit; kgsl_regwrite(device, A3XX_VBIF_PERF_CNT_CLR, bit); kgsl_regwrite(device, A3XX_VBIF_PERF_CNT_CLR, 0); kgsl_regwrite(device, A3XX_VBIF_PERF_CNT_EN, out); return 0; } /* * a3xx_perfcounter_enable - Configure a performance counter for a countable * @adreno_dev - Adreno device to configure * @group - Desired performance counter group * @counter - Desired performance counter in the group * @countable - Desired countable * * Physically set up a counter within a group with the desired countable * Return 0 on success else error code */ static int a3xx_perfcounter_enable(struct adreno_device *adreno_dev, unsigned int group, unsigned int counter, unsigned int countable) { struct kgsl_device *device = &adreno_dev->dev; struct adreno_perfcount_register *reg; /* Special cases */ if (group == KGSL_PERFCOUNTER_GROUP_PWR) return a3xx_perfcounter_enable_pwr(device, counter); else if (group == KGSL_PERFCOUNTER_GROUP_VBIF) return a3xx_perfcounter_enable_vbif(device, counter, countable); else if (group == KGSL_PERFCOUNTER_GROUP_VBIF_PWR) return a3xx_perfcounter_enable_vbif_pwr(device, counter); if (group >= adreno_dev->gpudev->perfcounters->group_count) return -EINVAL; if ((0 == adreno_dev->gpudev->perfcounters->groups[group].reg_count) || (counter >= adreno_dev->gpudev->perfcounters->groups[group].reg_count)) return -EINVAL; reg = &(adreno_dev->gpudev->perfcounters->groups[group].regs[counter]); /* Select the desired perfcounter */ kgsl_regwrite(device, reg->select, countable); return 0; } static uint64_t a3xx_perfcounter_read_pwr(struct adreno_device *adreno_dev, unsigned int counter) { struct kgsl_device *device = &adreno_dev->dev; struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters; struct adreno_perfcount_register *reg; unsigned int in, out, lo = 0, hi = 0; unsigned int enable_bit; if (counter > 1) return 0; if (0 == counter) enable_bit = RBBM_RBBM_CTL_ENABLE_PWR_CTR0; else enable_bit = RBBM_RBBM_CTL_ENABLE_PWR_CTR1; /* freeze counter */ adreno_readreg(adreno_dev, ADRENO_REG_RBBM_RBBM_CTL, &in); out = (in & ~enable_bit); adreno_writereg(adreno_dev, ADRENO_REG_RBBM_RBBM_CTL, out); reg = &counters->groups[KGSL_PERFCOUNTER_GROUP_PWR].regs[counter]; kgsl_regread(device, reg->offset, &lo); kgsl_regread(device, reg->offset + 1, &hi); /* restore the counter control value */ adreno_writereg(adreno_dev, ADRENO_REG_RBBM_RBBM_CTL, in); return (((uint64_t) hi) << 32) | lo; } static uint64_t a3xx_perfcounter_read_vbif(struct adreno_device *adreno_dev, unsigned int counter) { struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters; struct kgsl_device *device = &adreno_dev->dev; struct adreno_perfcount_register *reg; unsigned int in, out, lo = 0, hi = 0; if (counter > 1) return 0; /* freeze counter */ kgsl_regread(device, A3XX_VBIF_PERF_CNT_EN, &in); if (counter == 0) out = (in & ~VBIF_PERF_CNT_0); else out = (in & ~VBIF_PERF_CNT_1); kgsl_regwrite(device, A3XX_VBIF_PERF_CNT_EN, out); reg = &counters->groups[KGSL_PERFCOUNTER_GROUP_VBIF].regs[counter]; kgsl_regread(device, reg->offset, &lo); kgsl_regread(device, reg->offset + 1, &hi); /* restore the perfcounter value */ kgsl_regwrite(device, A3XX_VBIF_PERF_CNT_EN, in); return (((uint64_t) hi) << 32) | lo; } static uint64_t a3xx_perfcounter_read_vbif_pwr(struct adreno_device *adreno_dev, unsigned int counter) { struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters; struct kgsl_device *device = &adreno_dev->dev; struct adreno_perfcount_register *reg; unsigned int in, out, lo = 0, hi = 0; if (counter > 2) return 0; /* freeze counter */ kgsl_regread(device, A3XX_VBIF_PERF_CNT_EN, &in); if (0 == counter) out = (in & ~VBIF_PERF_PWR_CNT_0); else out = (in & ~VBIF_PERF_PWR_CNT_2); kgsl_regwrite(device, A3XX_VBIF_PERF_CNT_EN, out); reg = &counters->groups[KGSL_PERFCOUNTER_GROUP_VBIF_PWR].regs[counter]; kgsl_regread(device, reg->offset, &lo); kgsl_regread(device, reg->offset + 1, &hi); /* restore the perfcounter value */ kgsl_regwrite(device, A3XX_VBIF_PERF_CNT_EN, in); return (((uint64_t) hi) << 32) | lo; } static uint64_t a3xx_perfcounter_read(struct adreno_device *adreno_dev, unsigned int group, unsigned int counter) { struct kgsl_device *device = &adreno_dev->dev; struct adreno_perfcount_register *reg; unsigned int lo = 0, hi = 0; unsigned int offset; unsigned int in, out; if (group == KGSL_PERFCOUNTER_GROUP_VBIF_PWR) return a3xx_perfcounter_read_vbif_pwr(adreno_dev, counter); if (group == KGSL_PERFCOUNTER_GROUP_VBIF) return a3xx_perfcounter_read_vbif(adreno_dev, counter); if (group == KGSL_PERFCOUNTER_GROUP_PWR) return a3xx_perfcounter_read_pwr(adreno_dev, counter); if (group >= adreno_dev->gpudev->perfcounters->group_count) return 0; if ((0 == adreno_dev->gpudev->perfcounters->groups[group].reg_count) || (counter >= adreno_dev->gpudev->perfcounters->groups[group].reg_count)) return 0; reg = &(adreno_dev->gpudev->perfcounters->groups[group].regs[counter]); /* Freeze the counter */ kgsl_regread(device, A3XX_RBBM_PERFCTR_CTL, &in); out = in & ~RBBM_PERFCTR_CTL_ENABLE; kgsl_regwrite(device, A3XX_RBBM_PERFCTR_CTL, out); offset = reg->offset; /* Read the values */ kgsl_regread(device, offset, &lo); kgsl_regread(device, offset + 1, &hi); /* Re-Enable the counter */ kgsl_regwrite(device, A3XX_RBBM_PERFCTR_CTL, in); return (((uint64_t) hi) << 32) | lo; } /* * values cannot be loaded into physical performance * counters belonging to these groups. */ static inline int loadable_perfcounter_group(unsigned int groupid) { return ((groupid == KGSL_PERFCOUNTER_GROUP_VBIF_PWR) || (groupid == KGSL_PERFCOUNTER_GROUP_VBIF) || (groupid == KGSL_PERFCOUNTER_GROUP_PWR)) ? 0 : 1; } /* * Return true if the countable is used and not broken */ static inline int active_countable(unsigned int countable) { return ((countable != KGSL_PERFCOUNTER_NOT_USED) && (countable != KGSL_PERFCOUNTER_BROKEN)); } /** * a3xx_perfcounter_save() - Save the physical performance counter values * @adreno_dev - Adreno device whose registers need to be saved * * Read all the physical performance counter's values and save them * before GPU power collapse. */ static void a3xx_perfcounter_save(struct adreno_device *adreno_dev) { struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters; struct adreno_perfcount_group *group; unsigned int regid, groupid; for (groupid = 0; groupid < counters->group_count; groupid++) { if (!loadable_perfcounter_group(groupid)) continue; group = &(counters->groups[groupid]); /* group/counter iterator */ for (regid = 0; regid < group->reg_count; regid++) { if (!active_countable(group->regs[regid].countable)) continue; group->regs[regid].value = adreno_dev->gpudev->perfcounter_read( adreno_dev, groupid, regid); } } } /** * a3xx_perfcounter_write() - Write the physical performance counter values. * @adreno_dev - Adreno device whose registers are to be written to. * @group - group to which the physical counter belongs to. * @counter - register id of the physical counter to which the value is * written to. * * This function loads the 64 bit saved value into the particular physical * counter by enabling the corresponding bit in A3XX_RBBM_PERFCTR_LOAD_CMD* * register. */ static void a3xx_perfcounter_write(struct adreno_device *adreno_dev, unsigned int group, unsigned int counter) { struct kgsl_device *device = &(adreno_dev->dev); struct adreno_perfcount_register *reg; unsigned int val; reg = &(adreno_dev->gpudev->perfcounters->groups[group].regs[counter]); /* Clear the load cmd registers */ kgsl_regwrite(device, A3XX_RBBM_PERFCTR_LOAD_CMD0, 0); kgsl_regwrite(device, A3XX_RBBM_PERFCTR_LOAD_CMD1, 0); /* Write the saved value to PERFCTR_LOAD_VALUE* registers. */ kgsl_regwrite(device, A3XX_RBBM_PERFCTR_LOAD_VALUE_LO, (uint32_t)reg->value); kgsl_regwrite(device, A3XX_RBBM_PERFCTR_LOAD_VALUE_HI, (uint32_t)(reg->value >> 32)); /* * Set the load bit in PERFCTR_LOAD_CMD for the physical counter * we want to restore. The value in PERFCTR_LOAD_VALUE* is loaded * into the corresponding physical counter. */ if (reg->load_bit < 32) { val = 1 << reg->load_bit; kgsl_regwrite(device, A3XX_RBBM_PERFCTR_LOAD_CMD0, val); } else { val = 1 << (reg->load_bit - 32); kgsl_regwrite(device, A3XX_RBBM_PERFCTR_LOAD_CMD1, val); } } /** * a3xx_perfcounter_restore() - Restore the physical performance counter values. * @adreno_dev - Adreno device whose registers are to be restored. * * This function together with a3xx_perfcounter_save make sure that performance * counters are coherent across GPU power collapse. */ static void a3xx_perfcounter_restore(struct adreno_device *adreno_dev) { struct kgsl_device *device = &adreno_dev->dev; struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters; struct adreno_perfcount_group *group; unsigned int regid, groupid; for (groupid = 0; groupid < counters->group_count; groupid++) { if (!loadable_perfcounter_group(groupid)) continue; group = &(counters->groups[groupid]); /* group/counter iterator */ for (regid = 0; regid < group->reg_count; regid++) { if (!active_countable(group->regs[regid].countable)) continue; a3xx_perfcounter_write(adreno_dev, groupid, regid); } } /* Clear the load cmd registers */ kgsl_regwrite(device, A3XX_RBBM_PERFCTR_LOAD_CMD0, 0); kgsl_regwrite(device, A3XX_RBBM_PERFCTR_LOAD_CMD1, 0); } #define A3XX_IRQ_CALLBACK(_c) { .func = _c } #define A3XX_INT_MASK \ ((1 << A3XX_INT_RBBM_AHB_ERROR) | \ (1 << A3XX_INT_RBBM_ATB_BUS_OVERFLOW) | \ (1 << A3XX_INT_CP_T0_PACKET_IN_IB) | \ (1 << A3XX_INT_CP_OPCODE_ERROR) | \ (1 << A3XX_INT_CP_RESERVED_BIT_ERROR) | \ (1 << A3XX_INT_CP_HW_FAULT) | \ (1 << A3XX_INT_CP_IB1_INT) | \ (1 << A3XX_INT_CP_IB2_INT) | \ (1 << A3XX_INT_CP_RB_INT) | \ (1 << A3XX_INT_CP_REG_PROTECT_FAULT) | \ (1 << A3XX_INT_CP_AHB_ERROR_HALT) | \ (1 << A3XX_INT_UCHE_OOB_ACCESS)) static struct { void (*func)(struct adreno_device *, int); } a3xx_irq_funcs[] = { A3XX_IRQ_CALLBACK(NULL), /* 0 - RBBM_GPU_IDLE */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 1 - RBBM_AHB_ERROR */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 2 - RBBM_REG_TIMEOUT */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 3 - RBBM_ME_MS_TIMEOUT */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 4 - RBBM_PFP_MS_TIMEOUT */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 5 - RBBM_ATB_BUS_OVERFLOW */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 6 - RBBM_VFD_ERROR */ A3XX_IRQ_CALLBACK(NULL), /* 7 - CP_SW */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 8 - CP_T0_PACKET_IN_IB */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 9 - CP_OPCODE_ERROR */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 10 - CP_RESERVED_BIT_ERROR */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 11 - CP_HW_FAULT */ A3XX_IRQ_CALLBACK(NULL), /* 12 - CP_DMA */ A3XX_IRQ_CALLBACK(a3xx_cp_callback), /* 13 - CP_IB2_INT */ A3XX_IRQ_CALLBACK(a3xx_cp_callback), /* 14 - CP_IB1_INT */ A3XX_IRQ_CALLBACK(a3xx_cp_callback), /* 15 - CP_RB_INT */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 16 - CP_REG_PROTECT_FAULT */ A3XX_IRQ_CALLBACK(NULL), /* 17 - CP_RB_DONE_TS */ A3XX_IRQ_CALLBACK(NULL), /* 18 - CP_VS_DONE_TS */ A3XX_IRQ_CALLBACK(NULL), /* 19 - CP_PS_DONE_TS */ A3XX_IRQ_CALLBACK(NULL), /* 20 - CP_CACHE_FLUSH_TS */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 21 - CP_AHB_ERROR_FAULT */ A3XX_IRQ_CALLBACK(NULL), /* 22 - Unused */ A3XX_IRQ_CALLBACK(NULL), /* 23 - Unused */ A3XX_IRQ_CALLBACK(NULL), /* 24 - MISC_HANG_DETECT */ A3XX_IRQ_CALLBACK(a3xx_err_callback), /* 25 - UCHE_OOB_ACCESS */ /* 26 to 31 - Unused */ }; static irqreturn_t a3xx_irq_handler(struct adreno_device *adreno_dev) { struct kgsl_device *device = &adreno_dev->dev; irqreturn_t ret = IRQ_NONE; unsigned int status, tmp; int i; kgsl_regread(&adreno_dev->dev, A3XX_RBBM_INT_0_STATUS, &status); for (tmp = status, i = 0; tmp && i < ARRAY_SIZE(a3xx_irq_funcs); i++) { if (tmp & 1) { if (a3xx_irq_funcs[i].func != NULL) { a3xx_irq_funcs[i].func(adreno_dev, i); ret = IRQ_HANDLED; } else { KGSL_DRV_CRIT(device, "Unhandled interrupt bit %x\n", i); } } tmp >>= 1; } trace_kgsl_a3xx_irq_status(device, status); if (status) kgsl_regwrite(&adreno_dev->dev, A3XX_RBBM_INT_CLEAR_CMD, status); return ret; } static void a3xx_irq_control(struct adreno_device *adreno_dev, int state) { struct kgsl_device *device = &adreno_dev->dev; if (state) kgsl_regwrite(device, A3XX_RBBM_INT_0_MASK, A3XX_INT_MASK); else kgsl_regwrite(device, A3XX_RBBM_INT_0_MASK, 0); } static unsigned int a3xx_irq_pending(struct adreno_device *adreno_dev) { unsigned int status; kgsl_regread(&adreno_dev->dev, A3XX_RBBM_INT_0_STATUS, &status); return (status & A3XX_INT_MASK) ? 1 : 0; } static unsigned int counter_delta(struct adreno_device *adreno_dev, unsigned int reg, unsigned int *counter) { struct kgsl_device *device = &adreno_dev->dev; unsigned int val; unsigned int ret = 0; /* Read the value */ if (reg == ADRENO_REG_RBBM_PERFCTR_PWR_1_LO) adreno_readreg(adreno_dev, reg, &val); else kgsl_regread(device, reg, &val); /* Return 0 for the first read */ if (*counter != 0) { if (val < *counter) ret = (0xFFFFFFFF - *counter) + val; else ret = val - *counter; } *counter = val; return ret; } /* * a3xx_busy_cycles() - Returns number of gpu cycles * @adreno_dev: Pointer to device ehose cycles are checked * * Returns number of busy cycles since the last time this function is called * Function is common between a3xx and a4xx devices */ void a3xx_busy_cycles(struct adreno_device *adreno_dev, struct adreno_busy_data *data) { struct adreno_busy_data *busy = &adreno_dev->busy_data; struct kgsl_device *device = &adreno_dev->dev; memset(data, 0, sizeof(*data)); data->gpu_busy = counter_delta(adreno_dev, ADRENO_REG_RBBM_PERFCTR_PWR_1_LO, &busy->gpu_busy); if (device->pwrctrl.bus_control) { data->vbif_ram_cycles = counter_delta(adreno_dev, adreno_dev->ram_cycles_lo, &busy->vbif_ram_cycles); data->vbif_starved_ram = counter_delta(adreno_dev, A3XX_VBIF_PERF_PWR_CNT0_LO, &busy->vbif_starved_ram); } } struct a3xx_vbif_data { unsigned int reg; unsigned int val; }; /* VBIF registers start after 0x3000 so use 0x0 as end of list marker */ static struct a3xx_vbif_data a305_vbif[] = { /* Set up 16 deep read/write request queues */ { A3XX_VBIF_IN_RD_LIM_CONF0, 0x10101010 }, { A3XX_VBIF_IN_RD_LIM_CONF1, 0x10101010 }, { A3XX_VBIF_OUT_RD_LIM_CONF0, 0x10101010 }, { A3XX_VBIF_OUT_WR_LIM_CONF0, 0x10101010 }, { A3XX_VBIF_DDR_OUT_MAX_BURST, 0x0000303 }, { A3XX_VBIF_IN_WR_LIM_CONF0, 0x10101010 }, { A3XX_VBIF_IN_WR_LIM_CONF1, 0x10101010 }, /* Enable WR-REQ */ { A3XX_VBIF_GATE_OFF_WRREQ_EN, 0x0000FF }, /* Set up round robin arbitration between both AXI ports */ { A3XX_VBIF_ARB_CTL, 0x00000030 }, /* Set up AOOO */ { A3XX_VBIF_OUT_AXI_AOOO_EN, 0x0000003C }, { A3XX_VBIF_OUT_AXI_AOOO, 0x003C003C }, {0, 0}, }; static struct a3xx_vbif_data a305b_vbif[] = { { A3XX_VBIF_IN_RD_LIM_CONF0, 0x00181818 }, { A3XX_VBIF_IN_WR_LIM_CONF0, 0x00181818 }, { A3XX_VBIF_OUT_RD_LIM_CONF0, 0x00000018 }, { A3XX_VBIF_OUT_WR_LIM_CONF0, 0x00000018 }, { A3XX_VBIF_DDR_OUT_MAX_BURST, 0x00000303 }, { A3XX_VBIF_ROUND_ROBIN_QOS_ARB, 0x0003 }, {0, 0}, }; static struct a3xx_vbif_data a305c_vbif[] = { { A3XX_VBIF_IN_RD_LIM_CONF0, 0x00101010 }, { A3XX_VBIF_IN_WR_LIM_CONF0, 0x00101010 }, { A3XX_VBIF_OUT_RD_LIM_CONF0, 0x00000010 }, { A3XX_VBIF_OUT_WR_LIM_CONF0, 0x00000010 }, { A3XX_VBIF_DDR_OUT_MAX_BURST, 0x00000101 }, { A3XX_VBIF_ARB_CTL, 0x00000010 }, /* Set up AOOO */ { A3XX_VBIF_OUT_AXI_AOOO_EN, 0x00000007 }, { A3XX_VBIF_OUT_AXI_AOOO, 0x00070007 }, {0, 0}, }; static struct a3xx_vbif_data a320_vbif[] = { /* Set up 16 deep read/write request queues */ { A3XX_VBIF_IN_RD_LIM_CONF0, 0x10101010 }, { A3XX_VBIF_IN_RD_LIM_CONF1, 0x10101010 }, { A3XX_VBIF_OUT_RD_LIM_CONF0, 0x10101010 }, { A3XX_VBIF_OUT_WR_LIM_CONF0, 0x10101010 }, { A3XX_VBIF_DDR_OUT_MAX_BURST, 0x0000303 }, { A3XX_VBIF_IN_WR_LIM_CONF0, 0x10101010 }, { A3XX_VBIF_IN_WR_LIM_CONF1, 0x10101010 }, /* Enable WR-REQ */ { A3XX_VBIF_GATE_OFF_WRREQ_EN, 0x0000FF }, /* Set up round robin arbitration between both AXI ports */ { A3XX_VBIF_ARB_CTL, 0x00000030 }, /* Set up AOOO */ { A3XX_VBIF_OUT_AXI_AOOO_EN, 0x0000003C }, { A3XX_VBIF_OUT_AXI_AOOO, 0x003C003C }, /* Enable 1K sort */ { A3XX_VBIF_ABIT_SORT, 0x000000FF }, { A3XX_VBIF_ABIT_SORT_CONF, 0x000000A4 }, {0, 0}, }; static struct a3xx_vbif_data a330_vbif[] = { /* Set up 16 deep read/write request queues */ { A3XX_VBIF_IN_RD_LIM_CONF0, 0x18181818 }, { A3XX_VBIF_IN_RD_LIM_CONF1, 0x00001818 }, { A3XX_VBIF_OUT_RD_LIM_CONF0, 0x00001818 }, { A3XX_VBIF_OUT_WR_LIM_CONF0, 0x00001818 }, { A3XX_VBIF_DDR_OUT_MAX_BURST, 0x0000303 }, { A3XX_VBIF_IN_WR_LIM_CONF0, 0x18181818 }, { A3XX_VBIF_IN_WR_LIM_CONF1, 0x00001818 }, /* Enable WR-REQ */ { A3XX_VBIF_GATE_OFF_WRREQ_EN, 0x00003F }, /* Set up round robin arbitration between both AXI ports */ { A3XX_VBIF_ARB_CTL, 0x00000030 }, /* Set up VBIF_ROUND_ROBIN_QOS_ARB */ { A3XX_VBIF_ROUND_ROBIN_QOS_ARB, 0x0001 }, /* Set up AOOO */ { A3XX_VBIF_OUT_AXI_AOOO_EN, 0x0000003F }, { A3XX_VBIF_OUT_AXI_AOOO, 0x003F003F }, /* Enable 1K sort */ { A3XX_VBIF_ABIT_SORT, 0x0001003F }, { A3XX_VBIF_ABIT_SORT_CONF, 0x000000A4 }, /* Disable VBIF clock gating. This is to enable AXI running * higher frequency than GPU. */ { A3XX_VBIF_CLKON, 1 }, {0, 0}, }; /* * Most of the VBIF registers on 8974v2 have the correct values at power on, so * we won't modify those if we don't need to */ static struct a3xx_vbif_data a330v2_vbif[] = { /* Enable 1k sort */ { A3XX_VBIF_ABIT_SORT, 0x0001003F }, { A3XX_VBIF_ABIT_SORT_CONF, 0x000000A4 }, /* Enable WR-REQ */ { A3XX_VBIF_GATE_OFF_WRREQ_EN, 0x00003F }, { A3XX_VBIF_DDR_OUT_MAX_BURST, 0x0000303 }, /* Set up VBIF_ROUND_ROBIN_QOS_ARB */ { A3XX_VBIF_ROUND_ROBIN_QOS_ARB, 0x0003 }, {0, 0}, }; static struct { int(*devfunc)(struct adreno_device *); struct a3xx_vbif_data *vbif; } a3xx_vbif_platforms[] = { { adreno_is_a305, a305_vbif }, { adreno_is_a305c, a305c_vbif }, { adreno_is_a320, a320_vbif }, /* A330v2 needs to be ahead of A330 so the right device matches */ { adreno_is_a330v2, a330v2_vbif }, { adreno_is_a330, a330_vbif }, { adreno_is_a305b, a305b_vbif }, }; /* * Define the available perfcounter groups - these get used by * adreno_perfcounter_get and adreno_perfcounter_put */ static struct adreno_perfcount_register a3xx_perfcounters_cp[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_CP_0_LO, 0, A3XX_CP_PERFCOUNTER_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_rbbm[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_RBBM_0_LO, 1, A3XX_RBBM_PERFCOUNTER0_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_RBBM_1_LO, 2, A3XX_RBBM_PERFCOUNTER1_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_pc[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_PC_0_LO, 3, A3XX_PC_PERFCOUNTER0_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_PC_1_LO, 4, A3XX_PC_PERFCOUNTER1_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_PC_2_LO, 5, A3XX_PC_PERFCOUNTER2_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_PC_3_LO, 6, A3XX_PC_PERFCOUNTER3_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_vfd[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_VFD_0_LO, 7, A3XX_VFD_PERFCOUNTER0_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_VFD_1_LO, 8, A3XX_VFD_PERFCOUNTER1_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_hlsq[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_HLSQ_0_LO, 9, A3XX_HLSQ_PERFCOUNTER0_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_HLSQ_1_LO, 10, A3XX_HLSQ_PERFCOUNTER1_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_HLSQ_2_LO, 11, A3XX_HLSQ_PERFCOUNTER2_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_HLSQ_3_LO, 12, A3XX_HLSQ_PERFCOUNTER3_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_HLSQ_4_LO, 13, A3XX_HLSQ_PERFCOUNTER4_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_HLSQ_5_LO, 14, A3XX_HLSQ_PERFCOUNTER5_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_vpc[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_VPC_0_LO, 15, A3XX_VPC_PERFCOUNTER0_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_VPC_1_LO, 16, A3XX_VPC_PERFCOUNTER1_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_tse[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_TSE_0_LO, 17, A3XX_GRAS_PERFCOUNTER0_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_TSE_1_LO, 18, A3XX_GRAS_PERFCOUNTER1_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_ras[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_RAS_0_LO, 19, A3XX_GRAS_PERFCOUNTER2_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_RAS_1_LO, 20, A3XX_GRAS_PERFCOUNTER3_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_uche[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_UCHE_0_LO, 21, A3XX_UCHE_PERFCOUNTER0_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_UCHE_1_LO, 22, A3XX_UCHE_PERFCOUNTER1_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_UCHE_2_LO, 23, A3XX_UCHE_PERFCOUNTER2_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_UCHE_3_LO, 24, A3XX_UCHE_PERFCOUNTER3_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_UCHE_4_LO, 25, A3XX_UCHE_PERFCOUNTER4_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_UCHE_5_LO, 26, A3XX_UCHE_PERFCOUNTER5_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_tp[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_TP_0_LO, 27, A3XX_TP_PERFCOUNTER0_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_TP_1_LO, 28, A3XX_TP_PERFCOUNTER1_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_TP_2_LO, 29, A3XX_TP_PERFCOUNTER2_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_TP_3_LO, 30, A3XX_TP_PERFCOUNTER3_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_TP_4_LO, 31, A3XX_TP_PERFCOUNTER4_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_TP_5_LO, 32, A3XX_TP_PERFCOUNTER5_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_sp[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_SP_0_LO, 33, A3XX_SP_PERFCOUNTER0_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_SP_1_LO, 34, A3XX_SP_PERFCOUNTER1_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_SP_2_LO, 35, A3XX_SP_PERFCOUNTER2_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_SP_3_LO, 36, A3XX_SP_PERFCOUNTER3_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_SP_4_LO, 37, A3XX_SP_PERFCOUNTER4_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_SP_5_LO, 38, A3XX_SP_PERFCOUNTER5_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_SP_6_LO, 39, A3XX_SP_PERFCOUNTER6_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_SP_7_LO, 40, A3XX_SP_PERFCOUNTER7_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_rb[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_RB_0_LO, 41, A3XX_RB_PERFCOUNTER0_SELECT }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_RB_1_LO, 42, A3XX_RB_PERFCOUNTER1_SELECT }, }; static struct adreno_perfcount_register a3xx_perfcounters_pwr[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_PWR_0_LO, -1, 0 }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_RBBM_PERFCTR_PWR_1_LO, -1, 0 }, }; static struct adreno_perfcount_register a3xx_perfcounters_vbif[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_VBIF_PERF_CNT0_LO, -1, 0 }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_VBIF_PERF_CNT1_LO, -1, 0 }, }; static struct adreno_perfcount_register a3xx_perfcounters_vbif_pwr[] = { { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_VBIF_PERF_PWR_CNT0_LO, -1, 0 }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_VBIF_PERF_PWR_CNT1_LO, -1, 0 }, { KGSL_PERFCOUNTER_NOT_USED, 0, 0, A3XX_VBIF_PERF_PWR_CNT2_LO, -1, 0 }, }; static struct adreno_perfcount_group a3xx_perfcounter_groups[] = { ADRENO_PERFCOUNTER_GROUP(a3xx, cp), ADRENO_PERFCOUNTER_GROUP(a3xx, rbbm), ADRENO_PERFCOUNTER_GROUP(a3xx, pc), ADRENO_PERFCOUNTER_GROUP(a3xx, vfd), ADRENO_PERFCOUNTER_GROUP(a3xx, hlsq), ADRENO_PERFCOUNTER_GROUP(a3xx, vpc), ADRENO_PERFCOUNTER_GROUP(a3xx, tse), ADRENO_PERFCOUNTER_GROUP(a3xx, ras), ADRENO_PERFCOUNTER_GROUP(a3xx, uche), ADRENO_PERFCOUNTER_GROUP(a3xx, tp), ADRENO_PERFCOUNTER_GROUP(a3xx, sp), ADRENO_PERFCOUNTER_GROUP(a3xx, rb), ADRENO_PERFCOUNTER_GROUP_FLAGS(a3xx, pwr, ADRENO_PERFCOUNTER_GROUP_FIXED), ADRENO_PERFCOUNTER_GROUP(a3xx, vbif), ADRENO_PERFCOUNTER_GROUP_FLAGS(a3xx, vbif_pwr, ADRENO_PERFCOUNTER_GROUP_FIXED), }; static struct adreno_perfcounters a3xx_perfcounters = { a3xx_perfcounter_groups, ARRAY_SIZE(a3xx_perfcounter_groups), }; static inline int _get_counter(struct adreno_device *adreno_dev, int group, int countable, unsigned int *lo, unsigned int *hi) { int ret = 0; if (*lo == 0) { *hi = 0; ret = adreno_perfcounter_get(adreno_dev, group, countable, lo, PERFCOUNTER_FLAG_KERNEL); if (ret == 0) *hi = *lo + 1; else { struct kgsl_device *device = &adreno_dev->dev; KGSL_DRV_ERR(device, "Unable to allocate fault detect performance counter %d/%d\n", group, countable); KGSL_DRV_ERR(device, "GPU fault detect will be less reliable\n"); } } return ret; } static inline void _put_counter(struct adreno_device *adreno_dev, int group, int countable, unsigned int *lo, unsigned int *hi) { if (*lo != 0) { adreno_perfcounter_put(adreno_dev, group, countable, PERFCOUNTER_FLAG_KERNEL); } *lo = 0; *hi = 0; } /** * a3xx_fault_detect_start() - Allocate performance counters used for fast fault * detection * @adreno_dev: Pointer to an adreno_device structure * * Allocate the series of performance counters that should be periodically * checked to verify that the GPU is still moving */ void a3xx_fault_detect_start(struct adreno_device *adreno_dev) { _get_counter(adreno_dev, KGSL_PERFCOUNTER_GROUP_SP, SP_ALU_ACTIVE_CYCLES, &ft_detect_regs[6], &ft_detect_regs[7]); _get_counter(adreno_dev, KGSL_PERFCOUNTER_GROUP_SP, SP0_ICL1_MISSES, &ft_detect_regs[8], &ft_detect_regs[9]); _get_counter(adreno_dev, KGSL_PERFCOUNTER_GROUP_SP, SP_FS_CFLOW_INSTRUCTIONS, &ft_detect_regs[10], &ft_detect_regs[11]); _get_counter(adreno_dev, KGSL_PERFCOUNTER_GROUP_TSE, TSE_INPUT_PRIM_NUM, &ft_detect_regs[12], &ft_detect_regs[13]); } /** * a3xx_fault_detect_stop() - Release performance counters used for fast fault * detection * @adreno_dev: Pointer to an adreno_device structure * * Release the counters allocated in a3xx_fault_detect_start */ void a3xx_fault_detect_stop(struct adreno_device *adreno_dev) { _put_counter(adreno_dev, KGSL_PERFCOUNTER_GROUP_SP, SP_ALU_ACTIVE_CYCLES, &ft_detect_regs[6], &ft_detect_regs[7]); _put_counter(adreno_dev, KGSL_PERFCOUNTER_GROUP_SP, SP0_ICL1_MISSES, &ft_detect_regs[8], &ft_detect_regs[9]); _put_counter(adreno_dev, KGSL_PERFCOUNTER_GROUP_SP, SP_FS_CFLOW_INSTRUCTIONS, &ft_detect_regs[10], &ft_detect_regs[11]); _put_counter(adreno_dev, KGSL_PERFCOUNTER_GROUP_TSE, TSE_INPUT_PRIM_NUM, &ft_detect_regs[12], &ft_detect_regs[13]); } /** * a3xx_perfcounter_close() - Put counters that were initialized in * a3xx_perfcounter_init * @adreno_dev: Pointer to an adreno_device structure */ static void a3xx_perfcounter_close(struct adreno_device *adreno_dev) { adreno_perfcounter_put(adreno_dev, KGSL_PERFCOUNTER_GROUP_PWR, 1, PERFCOUNTER_FLAG_KERNEL); adreno_perfcounter_put(adreno_dev, KGSL_PERFCOUNTER_GROUP_VBIF_PWR, 0, PERFCOUNTER_FLAG_KERNEL); adreno_perfcounter_put(adreno_dev, KGSL_PERFCOUNTER_GROUP_VBIF, VBIF_AXI_TOTAL_BEATS, PERFCOUNTER_FLAG_KERNEL); if (adreno_dev->fast_hang_detect) a3xx_fault_detect_stop(adreno_dev); } /** * a3xx_perfcounter_init() - Allocate performance counters for use in the kernel * @adreno_dev: Pointer to an adreno_device structure */ static int a3xx_perfcounter_init(struct adreno_device *adreno_dev) { int ret; struct kgsl_device *device = &adreno_dev->dev; /* SP[3] counter is broken on a330 so disable it if a330 device */ if (adreno_is_a330(adreno_dev)) a3xx_perfcounters_sp[3].countable = KGSL_PERFCOUNTER_BROKEN; if (adreno_dev->fast_hang_detect) a3xx_fault_detect_start(adreno_dev); /* Reserve and start countable 1 in the PWR perfcounter group */ ret = adreno_perfcounter_get(adreno_dev, KGSL_PERFCOUNTER_GROUP_PWR, 1, NULL, PERFCOUNTER_FLAG_KERNEL); if (device->pwrctrl.bus_control) { /* VBIF waiting for RAM */ ret |= adreno_perfcounter_get(adreno_dev, KGSL_PERFCOUNTER_GROUP_VBIF_PWR, 0, NULL, PERFCOUNTER_FLAG_KERNEL); /* VBIF DDR cycles */ ret |= adreno_perfcounter_get(adreno_dev, KGSL_PERFCOUNTER_GROUP_VBIF, VBIF_AXI_TOTAL_BEATS, &adreno_dev->ram_cycles_lo, PERFCOUNTER_FLAG_KERNEL); } /* Default performance counter profiling to false */ adreno_dev->profile.enabled = false; return ret; } /** * a3xx_protect_init() - Initializes register protection on a3xx * @device: Pointer to the device structure * Performs register writes to enable protected access to sensitive * registers */ static void a3xx_protect_init(struct kgsl_device *device) { /* enable access protection to privileged registers */ kgsl_regwrite(device, A3XX_CP_PROTECT_CTRL, 0x00000007); /* RBBM registers */ kgsl_regwrite(device, A3XX_CP_PROTECT_REG_0, 0x63000040); kgsl_regwrite(device, A3XX_CP_PROTECT_REG_1, 0x62000080); kgsl_regwrite(device, A3XX_CP_PROTECT_REG_2, 0x600000CC); kgsl_regwrite(device, A3XX_CP_PROTECT_REG_3, 0x60000108); kgsl_regwrite(device, A3XX_CP_PROTECT_REG_4, 0x64000140); kgsl_regwrite(device, A3XX_CP_PROTECT_REG_5, 0x66000400); /* CP registers */ kgsl_regwrite(device, A3XX_CP_PROTECT_REG_6, 0x65000700); kgsl_regwrite(device, A3XX_CP_PROTECT_REG_7, 0x610007D8); kgsl_regwrite(device, A3XX_CP_PROTECT_REG_8, 0x620007E0); kgsl_regwrite(device, A3XX_CP_PROTECT_REG_9, 0x61001178); kgsl_regwrite(device, A3XX_CP_PROTECT_REG_A, 0x64001180); /* RB registers */ kgsl_regwrite(device, A3XX_CP_PROTECT_REG_B, 0x60003300); /* VBIF registers */ kgsl_regwrite(device, A3XX_CP_PROTECT_REG_C, 0x6B00C000); } static void a3xx_start(struct adreno_device *adreno_dev) { struct kgsl_device *device = &adreno_dev->dev; struct a3xx_vbif_data *vbif = NULL; int i; for (i = 0; i < ARRAY_SIZE(a3xx_vbif_platforms); i++) { if (a3xx_vbif_platforms[i].devfunc(adreno_dev)) { vbif = a3xx_vbif_platforms[i].vbif; break; } } BUG_ON(vbif == NULL); while (vbif->reg != 0) { kgsl_regwrite(device, vbif->reg, vbif->val); vbif++; } /* Make all blocks contribute to the GPU BUSY perf counter */ kgsl_regwrite(device, A3XX_RBBM_GPU_BUSY_MASKED, 0xFFFFFFFF); /* Tune the hystersis counters for SP and CP idle detection */ kgsl_regwrite(device, A3XX_RBBM_SP_HYST_CNT, 0x10); kgsl_regwrite(device, A3XX_RBBM_WAIT_IDLE_CLOCKS_CTL, 0x10); /* Enable the RBBM error reporting bits. This lets us get useful information on failure */ kgsl_regwrite(device, A3XX_RBBM_AHB_CTL0, 0x00000001); /* Enable AHB error reporting */ kgsl_regwrite(device, A3XX_RBBM_AHB_CTL1, 0xA6FFFFFF); /* Turn on the power counters */ kgsl_regwrite(device, A3XX_RBBM_RBBM_CTL, 0x00030000); /* Turn on hang detection - this spews a lot of useful information * into the RBBM registers on a hang */ kgsl_regwrite(device, A3XX_RBBM_INTERFACE_HANG_INT_CTL, (1 << 16) | 0xFFF); /* Enable 64-byte cacheline size. HW Default is 32-byte (0x000000E0). */ kgsl_regwrite(device, A3XX_UCHE_CACHE_MODE_CONTROL_REG, 0x00000001); /* Enable Clock gating */ kgsl_regwrite(device, A3XX_RBBM_CLOCK_CTL, adreno_a3xx_rbbm_clock_ctl_default(adreno_dev)); if (adreno_is_a330v2(adreno_dev)) kgsl_regwrite(device, A3XX_RBBM_GPR0_CTL, A330v2_RBBM_GPR0_CTL_DEFAULT); else if (adreno_is_a330(adreno_dev)) kgsl_regwrite(device, A3XX_RBBM_GPR0_CTL, A330_RBBM_GPR0_CTL_DEFAULT); /* Set the OCMEM base address for A330 */ if (adreno_is_a330(adreno_dev) || adreno_is_a305b(adreno_dev)) { kgsl_regwrite(device, A3XX_RB_GMEM_BASE_ADDR, (unsigned int)(adreno_dev->ocmem_base >> 14)); } /* Turn on protection */ a3xx_protect_init(device); /* Turn on performance counters */ kgsl_regwrite(device, A3XX_RBBM_PERFCTR_CTL, 0x01); /* the CP_DEBUG register offset and value are same as A2XX */ kgsl_regwrite(device, REG_CP_DEBUG, A2XX_CP_DEBUG_DEFAULT); memset(&adreno_dev->busy_data, 0, sizeof(adreno_dev->busy_data)); } /** * a3xx_coresight_enable() - Enables debugging through coresight * debug bus for adreno a3xx devices. * @device: Pointer to GPU device structure */ int a3xx_coresight_enable(struct kgsl_device *device) { mutex_lock(&device->mutex); if (!kgsl_active_count_get(device)) { kgsl_regwrite(device, A3XX_RBBM_DEBUG_BUS_CTL, 0x0001093F); kgsl_regwrite(device, A3XX_RBBM_DEBUG_BUS_STB_CTL0, 0x00000000); kgsl_regwrite(device, A3XX_RBBM_DEBUG_BUS_STB_CTL1, 0xFFFFFFFE); kgsl_regwrite(device, A3XX_RBBM_INT_TRACE_BUS_CTL, 0x00201111); kgsl_regwrite(device, A3XX_RBBM_EXT_TRACE_BUS_CTL, 0x89100010); kgsl_regwrite(device, A3XX_RBBM_EXT_TRACE_STOP_CNT, 0x00017fff); kgsl_regwrite(device, A3XX_RBBM_EXT_TRACE_START_CNT, 0x0001000f); kgsl_regwrite(device, A3XX_RBBM_EXT_TRACE_PERIOD_CNT , 0x0001ffff); kgsl_regwrite(device, A3XX_RBBM_EXT_TRACE_CMD, 0x00000001); kgsl_active_count_put(device); } mutex_unlock(&device->mutex); return 0; } /** * a3xx_coresight_disable() - Disables debugging through coresight * debug bus for adreno a3xx devices. * @device: Pointer to GPU device structure */ void a3xx_coresight_disable(struct kgsl_device *device) { mutex_lock(&device->mutex); if (!kgsl_active_count_get(device)) { kgsl_regwrite(device, A3XX_RBBM_DEBUG_BUS_CTL, 0x0); kgsl_regwrite(device, A3XX_RBBM_DEBUG_BUS_STB_CTL0, 0x0); kgsl_regwrite(device, A3XX_RBBM_DEBUG_BUS_STB_CTL1, 0x0); kgsl_regwrite(device, A3XX_RBBM_INT_TRACE_BUS_CTL, 0x0); kgsl_regwrite(device, A3XX_RBBM_EXT_TRACE_BUS_CTL, 0x0); kgsl_regwrite(device, A3XX_RBBM_EXT_TRACE_STOP_CNT, 0x0); kgsl_regwrite(device, A3XX_RBBM_EXT_TRACE_START_CNT, 0x0); kgsl_regwrite(device, A3XX_RBBM_EXT_TRACE_PERIOD_CNT , 0x0); kgsl_regwrite(device, A3XX_RBBM_EXT_TRACE_CMD, 0x0); kgsl_active_count_put(device); } mutex_unlock(&device->mutex); } static void a3xx_coresight_write_reg(struct kgsl_device *device, unsigned int wordoffset, unsigned int val) { mutex_lock(&device->mutex); if (!kgsl_active_count_get(device)) { kgsl_regwrite(device, wordoffset, val); kgsl_active_count_put(device); } mutex_unlock(&device->mutex); } void a3xx_coresight_config_debug_reg(struct kgsl_device *device, int debug_reg, unsigned int val) { switch (debug_reg) { case DEBUG_BUS_CTL: a3xx_coresight_write_reg(device, A3XX_RBBM_DEBUG_BUS_CTL, val); break; case TRACE_STOP_CNT: a3xx_coresight_write_reg(device, A3XX_RBBM_EXT_TRACE_STOP_CNT, val); break; case TRACE_START_CNT: a3xx_coresight_write_reg(device, A3XX_RBBM_EXT_TRACE_START_CNT, val); break; case TRACE_PERIOD_CNT: a3xx_coresight_write_reg(device, A3XX_RBBM_EXT_TRACE_PERIOD_CNT, val); break; case TRACE_CMD: a3xx_coresight_write_reg(device, A3XX_RBBM_EXT_TRACE_CMD, val); break; case TRACE_BUS_CTL: a3xx_coresight_write_reg(device, A3XX_RBBM_EXT_TRACE_BUS_CTL, val); break; } } /* * a3xx_soft_reset() - Soft reset GPU * @adreno_dev: Pointer to adreno device * * Soft reset the GPU by doing a AHB write of value 1 to RBBM_SW_RESET * register. This is used when we want to reset the GPU without * turning off GFX power rail. The reset when asserted resets * all the HW logic, restores GPU registers to default state and * flushes out pending VBIF transactions. */ static void a3xx_soft_reset(struct adreno_device *adreno_dev) { struct kgsl_device *device = &adreno_dev->dev; unsigned int reg; kgsl_regwrite(device, A3XX_RBBM_SW_RESET_CMD, 1); /* * Do a dummy read to get a brief read cycle delay for the reset to take * effect */ kgsl_regread(device, A3XX_RBBM_SW_RESET_CMD, &reg); kgsl_regwrite(device, A3XX_RBBM_SW_RESET_CMD, 0); } /* Defined in adreno_a3xx_snapshot.c */ void *a3xx_snapshot(struct adreno_device *adreno_dev, void *snapshot, int *remain, int hang); static void a3xx_postmortem_dump(struct adreno_device *adreno_dev) { struct kgsl_device *device = &adreno_dev->dev; unsigned int r1, r2, r3, rbbm_status; unsigned int cp_stat, rb_count; kgsl_regread(device, REG_RBBM_STATUS, &rbbm_status); KGSL_LOG_DUMP(device, "RBBM: STATUS = %08X\n", rbbm_status); { struct log_field lines[] = { {rbbm_status & BIT(0), "HI busy "}, {rbbm_status & BIT(1), "CP ME busy "}, {rbbm_status & BIT(2), "CP PFP busy "}, {rbbm_status & BIT(14), "CP NRT busy "}, {rbbm_status & BIT(15), "VBIF busy "}, {rbbm_status & BIT(16), "TSE busy "}, {rbbm_status & BIT(17), "RAS busy "}, {rbbm_status & BIT(18), "RB busy "}, {rbbm_status & BIT(19), "PC DCALL bsy"}, {rbbm_status & BIT(20), "PC VSD busy "}, {rbbm_status & BIT(21), "VFD busy "}, {rbbm_status & BIT(22), "VPC busy "}, {rbbm_status & BIT(23), "UCHE busy "}, {rbbm_status & BIT(24), "SP busy "}, {rbbm_status & BIT(25), "TPL1 busy "}, {rbbm_status & BIT(26), "MARB busy "}, {rbbm_status & BIT(27), "VSC busy "}, {rbbm_status & BIT(28), "ARB busy "}, {rbbm_status & BIT(29), "HLSQ busy "}, {rbbm_status & BIT(30), "GPU bsy noHC"}, {rbbm_status & BIT(31), "GPU busy "}, }; adreno_dump_fields(device, " STATUS=", lines, ARRAY_SIZE(lines)); } kgsl_regread(device, REG_CP_RB_BASE, &r1); kgsl_regread(device, REG_CP_RB_CNTL, &r2); rb_count = 2 << (r2 & (BIT(6) - 1)); kgsl_regread(device, REG_CP_RB_RPTR_ADDR, &r3); KGSL_LOG_DUMP(device, "CP_RB: BASE = %08X | CNTL = %08X | RPTR_ADDR = %08X" "| rb_count = %08X\n", r1, r2, r3, rb_count); kgsl_regread(device, REG_CP_RB_RPTR, &r1); kgsl_regread(device, REG_CP_RB_WPTR, &r2); kgsl_regread(device, REG_CP_RB_RPTR_WR, &r3); KGSL_LOG_DUMP(device, "CP_RB: BASE = %08X | CNTL = %08X | RPTR_ADDR = %08X" "| rb_count = %08X\n", r1, r2, r3, rb_count); kgsl_regread(device, REG_CP_RB_RPTR, &r1); kgsl_regread(device, REG_CP_RB_WPTR, &r2); kgsl_regread(device, REG_CP_RB_RPTR_WR, &r3); KGSL_LOG_DUMP(device, " RPTR = %08X | WPTR = %08X | RPTR_WR = %08X" "\n", r1, r2, r3); kgsl_regread(device, REG_CP_IB1_BASE, &r1); kgsl_regread(device, REG_CP_IB1_BUFSZ, &r2); KGSL_LOG_DUMP(device, "CP_IB1: BASE = %08X | BUFSZ = %d\n", r1, r2); kgsl_regread(device, REG_CP_ME_CNTL, &r1); kgsl_regread(device, REG_CP_ME_STATUS, &r2); KGSL_LOG_DUMP(device, "CP_ME: CNTL = %08X | STATUS = %08X\n", r1, r2); kgsl_regread(device, REG_CP_STAT, &cp_stat); KGSL_LOG_DUMP(device, "CP_STAT = %08X\n", cp_stat); #ifndef CONFIG_MSM_KGSL_PSTMRTMDMP_CP_STAT_NO_DETAIL { struct log_field lns[] = { {cp_stat & BIT(0), "WR_BSY 0"}, {cp_stat & BIT(1), "RD_RQ_BSY 1"}, {cp_stat & BIT(2), "RD_RTN_BSY 2"}, }; adreno_dump_fields(device, " MIU=", lns, ARRAY_SIZE(lns)); } { struct log_field lns[] = { {cp_stat & BIT(5), "RING_BUSY 5"}, {cp_stat & BIT(6), "NDRCTS_BSY 6"}, {cp_stat & BIT(7), "NDRCT2_BSY 7"}, {cp_stat & BIT(9), "ST_BUSY 9"}, {cp_stat & BIT(10), "BUSY 10"}, }; adreno_dump_fields(device, " CSF=", lns, ARRAY_SIZE(lns)); } { struct log_field lns[] = { {cp_stat & BIT(11), "RNG_Q_BSY 11"}, {cp_stat & BIT(12), "NDRCTS_Q_B12"}, {cp_stat & BIT(13), "NDRCT2_Q_B13"}, {cp_stat & BIT(16), "ST_QUEUE_B16"}, {cp_stat & BIT(17), "PFP_BUSY 17"}, }; adreno_dump_fields(device, " RING=", lns, ARRAY_SIZE(lns)); } { struct log_field lns[] = { {cp_stat & BIT(3), "RBIU_BUSY 3"}, {cp_stat & BIT(4), "RCIU_BUSY 4"}, {cp_stat & BIT(8), "EVENT_BUSY 8"}, {cp_stat & BIT(18), "MQ_RG_BSY 18"}, {cp_stat & BIT(19), "MQ_NDRS_BS19"}, {cp_stat & BIT(20), "MQ_NDR2_BS20"}, {cp_stat & BIT(21), "MIU_WC_STL21"}, {cp_stat & BIT(22), "CP_NRT_BSY22"}, {cp_stat & BIT(23), "3D_BUSY 23"}, {cp_stat & BIT(26), "ME_BUSY 26"}, {cp_stat & BIT(27), "RB_FFO_BSY27"}, {cp_stat & BIT(28), "CF_FFO_BSY28"}, {cp_stat & BIT(29), "PS_FFO_BSY29"}, {cp_stat & BIT(30), "VS_FFO_BSY30"}, {cp_stat & BIT(31), "CP_BUSY 31"}, }; adreno_dump_fields(device, " CP_STT=", lns, ARRAY_SIZE(lns)); } #endif kgsl_regread(device, A3XX_RBBM_INT_0_STATUS, &r1); KGSL_LOG_DUMP(device, "MSTR_INT_SGNL = %08X\n", r1); { struct log_field ints[] = { {r1 & BIT(0), "RBBM_GPU_IDLE 0"}, {r1 & BIT(1), "RBBM_AHB_ERROR 1"}, {r1 & BIT(2), "RBBM_REG_TIMEOUT 2"}, {r1 & BIT(3), "RBBM_ME_MS_TIMEOUT 3"}, {r1 & BIT(4), "RBBM_PFP_MS_TIMEOUT 4"}, {r1 & BIT(5), "RBBM_ATB_BUS_OVERFLOW 5"}, {r1 & BIT(6), "VFD_ERROR 6"}, {r1 & BIT(7), "CP_SW_INT 7"}, {r1 & BIT(8), "CP_T0_PACKET_IN_IB 8"}, {r1 & BIT(9), "CP_OPCODE_ERROR 9"}, {r1 & BIT(10), "CP_RESERVED_BIT_ERROR 10"}, {r1 & BIT(11), "CP_HW_FAULT 11"}, {r1 & BIT(12), "CP_DMA 12"}, {r1 & BIT(13), "CP_IB2_INT 13"}, {r1 & BIT(14), "CP_IB1_INT 14"}, {r1 & BIT(15), "CP_RB_INT 15"}, {r1 & BIT(16), "CP_REG_PROTECT_FAULT 16"}, {r1 & BIT(17), "CP_RB_DONE_TS 17"}, {r1 & BIT(18), "CP_VS_DONE_TS 18"}, {r1 & BIT(19), "CP_PS_DONE_TS 19"}, {r1 & BIT(20), "CACHE_FLUSH_TS 20"}, {r1 & BIT(21), "CP_AHB_ERROR_HALT 21"}, {r1 & BIT(24), "MISC_HANG_DETECT 24"}, {r1 & BIT(25), "UCHE_OOB_ACCESS 25"}, }; adreno_dump_fields(device, "INT_SGNL=", ints, ARRAY_SIZE(ints)); } } /* Register offset defines for A3XX */ static unsigned int a3xx_register_offsets[ADRENO_REG_REGISTER_MAX] = { ADRENO_REG_DEFINE(ADRENO_REG_CP_DEBUG, REG_CP_DEBUG), ADRENO_REG_DEFINE(ADRENO_REG_CP_ME_RAM_WADDR, REG_CP_ME_RAM_WADDR), ADRENO_REG_DEFINE(ADRENO_REG_CP_ME_RAM_DATA, REG_CP_ME_RAM_DATA), ADRENO_REG_DEFINE(ADRENO_REG_CP_PFP_UCODE_DATA, A3XX_CP_PFP_UCODE_DATA), ADRENO_REG_DEFINE(ADRENO_REG_CP_PFP_UCODE_ADDR, A3XX_CP_PFP_UCODE_ADDR), ADRENO_REG_DEFINE(ADRENO_REG_CP_WFI_PEND_CTR, A3XX_CP_WFI_PEND_CTR), ADRENO_REG_DEFINE(ADRENO_REG_CP_RB_BASE, REG_CP_RB_BASE), ADRENO_REG_DEFINE(ADRENO_REG_CP_RB_RPTR_ADDR, REG_CP_RB_RPTR_ADDR), ADRENO_REG_DEFINE(ADRENO_REG_CP_RB_RPTR, REG_CP_RB_RPTR), ADRENO_REG_DEFINE(ADRENO_REG_CP_RB_WPTR, REG_CP_RB_WPTR), ADRENO_REG_DEFINE(ADRENO_REG_CP_PROTECT_CTRL, A3XX_CP_PROTECT_CTRL), ADRENO_REG_DEFINE(ADRENO_REG_CP_ME_CNTL, REG_CP_ME_CNTL), ADRENO_REG_DEFINE(ADRENO_REG_CP_RB_CNTL, REG_CP_RB_CNTL), ADRENO_REG_DEFINE(ADRENO_REG_CP_IB1_BASE, REG_CP_IB1_BASE), ADRENO_REG_DEFINE(ADRENO_REG_CP_IB1_BUFSZ, REG_CP_IB1_BUFSZ), ADRENO_REG_DEFINE(ADRENO_REG_CP_IB2_BASE, REG_CP_IB2_BASE), ADRENO_REG_DEFINE(ADRENO_REG_CP_IB2_BUFSZ, REG_CP_IB2_BUFSZ), ADRENO_REG_DEFINE(ADRENO_REG_CP_TIMESTAMP, REG_CP_TIMESTAMP), ADRENO_REG_DEFINE(ADRENO_REG_SCRATCH_ADDR, REG_SCRATCH_ADDR), ADRENO_REG_DEFINE(ADRENO_REG_SCRATCH_UMSK, REG_SCRATCH_UMSK), ADRENO_REG_DEFINE(ADRENO_REG_RBBM_STATUS, A3XX_RBBM_STATUS), ADRENO_REG_DEFINE(ADRENO_REG_RBBM_PERFCTR_CTL, A3XX_RBBM_PERFCTR_CTL), ADRENO_REG_DEFINE(ADRENO_REG_RBBM_PERFCTR_LOAD_CMD0, A3XX_RBBM_PERFCTR_LOAD_CMD0), ADRENO_REG_DEFINE(ADRENO_REG_RBBM_PERFCTR_LOAD_CMD1, A3XX_RBBM_PERFCTR_LOAD_CMD1), ADRENO_REG_DEFINE(ADRENO_REG_RBBM_PERFCTR_PWR_1_LO, A3XX_RBBM_PERFCTR_PWR_1_LO), ADRENO_REG_DEFINE(ADRENO_REG_RBBM_INT_0_MASK, A3XX_RBBM_INT_0_MASK), ADRENO_REG_DEFINE(ADRENO_REG_RBBM_INT_0_STATUS, A3XX_RBBM_INT_0_STATUS), ADRENO_REG_DEFINE(ADRENO_REG_RBBM_AHB_ERROR_STATUS, A3XX_RBBM_AHB_ERROR_STATUS), ADRENO_REG_DEFINE(ADRENO_REG_VPC_VPC_DEBUG_RAM_SEL, A3XX_VPC_VPC_DEBUG_RAM_SEL), ADRENO_REG_DEFINE(ADRENO_REG_VPC_VPC_DEBUG_RAM_READ, A3XX_VPC_VPC_DEBUG_RAM_READ), ADRENO_REG_DEFINE(ADRENO_REG_VSC_PIPE_DATA_ADDRESS_0, A3XX_VSC_PIPE_DATA_ADDRESS_0), ADRENO_REG_DEFINE(ADRENO_REG_VSC_PIPE_DATA_LENGTH_7, A3XX_VSC_PIPE_DATA_LENGTH_7), ADRENO_REG_DEFINE(ADRENO_REG_VSC_SIZE_ADDRESS, A3XX_VSC_SIZE_ADDRESS), ADRENO_REG_DEFINE(ADRENO_REG_VFD_CONTROL_0, A3XX_VFD_CONTROL_0), ADRENO_REG_DEFINE(ADRENO_REG_VFD_FETCH_INSTR_0_0, A3XX_VFD_FETCH_INSTR_0_0), ADRENO_REG_DEFINE(ADRENO_REG_VFD_FETCH_INSTR_1_F, A3XX_VFD_FETCH_INSTR_1_F), ADRENO_REG_DEFINE(ADRENO_REG_VFD_INDEX_MAX, A3XX_VFD_INDEX_MAX), ADRENO_REG_DEFINE(ADRENO_REG_SP_VS_PVT_MEM_ADDR_REG, A3XX_SP_VS_PVT_MEM_ADDR_REG), ADRENO_REG_DEFINE(ADRENO_REG_SP_FS_PVT_MEM_ADDR_REG, A3XX_SP_FS_PVT_MEM_ADDR_REG), ADRENO_REG_DEFINE(ADRENO_REG_SP_VS_OBJ_START_REG, A3XX_SP_VS_OBJ_START_REG), ADRENO_REG_DEFINE(ADRENO_REG_SP_FS_OBJ_START_REG, A3XX_SP_FS_OBJ_START_REG), ADRENO_REG_DEFINE(ADRENO_REG_PA_SC_AA_CONFIG, REG_PA_SC_AA_CONFIG), ADRENO_REG_DEFINE(ADRENO_REG_RBBM_PM_OVERRIDE2, REG_RBBM_PM_OVERRIDE2), ADRENO_REG_DEFINE(ADRENO_REG_SCRATCH_REG2, REG_SCRATCH_REG2), ADRENO_REG_DEFINE(ADRENO_REG_SQ_GPR_MANAGEMENT, REG_SQ_GPR_MANAGEMENT), ADRENO_REG_DEFINE(ADRENO_REG_SQ_INST_STORE_MANAGMENT, REG_SQ_INST_STORE_MANAGMENT), ADRENO_REG_DEFINE(ADRENO_REG_TC_CNTL_STATUS, REG_TC_CNTL_STATUS), ADRENO_REG_DEFINE(ADRENO_REG_TP0_CHICKEN, REG_TP0_CHICKEN), ADRENO_REG_DEFINE(ADRENO_REG_RBBM_RBBM_CTL, A3XX_RBBM_RBBM_CTL), }; struct adreno_reg_offsets a3xx_reg_offsets = { .offsets = a3xx_register_offsets, .offset_0 = ADRENO_REG_REGISTER_MAX, }; struct adreno_gpudev adreno_a3xx_gpudev = { .reg_offsets = &a3xx_reg_offsets, .perfcounters = &a3xx_perfcounters, .ctxt_create = a3xx_drawctxt_create, .rb_init = a3xx_rb_init, .perfcounter_init = a3xx_perfcounter_init, .perfcounter_close = a3xx_perfcounter_close, .perfcounter_save = a3xx_perfcounter_save, .perfcounter_restore = a3xx_perfcounter_restore, .irq_control = a3xx_irq_control, .irq_handler = a3xx_irq_handler, .irq_pending = a3xx_irq_pending, .busy_cycles = a3xx_busy_cycles, .start = a3xx_start, .snapshot = a3xx_snapshot, .perfcounter_enable = a3xx_perfcounter_enable, .perfcounter_read = a3xx_perfcounter_read, .perfcounter_write = a3xx_perfcounter_write, .coresight_enable = a3xx_coresight_enable, .coresight_disable = a3xx_coresight_disable, .coresight_config_debug_reg = a3xx_coresight_config_debug_reg, .fault_detect_start = a3xx_fault_detect_start, .fault_detect_stop = a3xx_fault_detect_stop, .soft_reset = a3xx_soft_reset, .postmortem_dump = a3xx_postmortem_dump, };
ryrzy/LG-D802-G2-_Android_KK_D802v20a
drivers/gpu/msm/adreno_a3xx.c
C
gpl-2.0
158,805
/* * Copyright (C) 2000, 2001, 2002, 2003 Håkan Hjort <[email protected]> * * This file is part of libdvdread. * * libdvdread 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. * * libdvdread 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 libdvdread; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include "bswap.h" #include "dvdread/nav_types.h" #include "dvdread/nav_read.h" #include "dvdread_internal.h" #include "dvdread/bitreader.h" #define getbits_init dvdread_getbits_init #define getbits dvdread_getbits void navRead_PCI(pci_t *pci, unsigned char *buffer) { int32_t i, j; getbits_state_t state; if (!getbits_init(&state, buffer)) abort(); /* Passed NULL pointers */ /* pci pci_gi */ pci->pci_gi.nv_pck_lbn = getbits(&state, 32 ); pci->pci_gi.vobu_cat = getbits(&state, 16 ); pci->pci_gi.zero1 = getbits(&state, 16 ); pci->pci_gi.vobu_uop_ctl.zero = getbits(&state, 7 ); pci->pci_gi.vobu_uop_ctl.video_pres_mode_change = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.karaoke_audio_pres_mode_change = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.angle_change = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.subpic_stream_change = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.audio_stream_change = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.pause_on = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.still_off = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.button_select_or_activate = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.resume = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.chapter_menu_call = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.angle_menu_call = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.audio_menu_call = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.subpic_menu_call = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.root_menu_call = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.title_menu_call = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.backward_scan = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.forward_scan = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.next_pg_search = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.prev_or_top_pg_search = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.time_or_chapter_search = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.go_up = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.stop = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.title_play = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.chapter_search_or_play = getbits(&state, 1 ); pci->pci_gi.vobu_uop_ctl.title_or_time_play = getbits(&state, 1 ); pci->pci_gi.vobu_s_ptm = getbits(&state, 32 ); pci->pci_gi.vobu_e_ptm = getbits(&state, 32 ); pci->pci_gi.vobu_se_e_ptm = getbits(&state, 32 ); pci->pci_gi.e_eltm.hour = getbits(&state, 8 ); pci->pci_gi.e_eltm.minute = getbits(&state, 8 ); pci->pci_gi.e_eltm.second = getbits(&state, 8 ); pci->pci_gi.e_eltm.frame_u = getbits(&state, 8 ); for(i = 0; i < 32; i++) pci->pci_gi.vobu_isrc[i] = getbits(&state, 8 ); /* pci nsml_agli */ for(i = 0; i < 9; i++) pci->nsml_agli.nsml_agl_dsta[i] = getbits(&state, 32 ); /* pci hli hli_gi */ pci->hli.hl_gi.hli_ss = getbits(&state, 16 ); pci->hli.hl_gi.hli_s_ptm = getbits(&state, 32 ); pci->hli.hl_gi.hli_e_ptm = getbits(&state, 32 ); pci->hli.hl_gi.btn_se_e_ptm = getbits(&state, 32 ); pci->hli.hl_gi.zero1 = getbits(&state, 2 ); pci->hli.hl_gi.btngr_ns = getbits(&state, 2 ); pci->hli.hl_gi.zero2 = getbits(&state, 1 ); pci->hli.hl_gi.btngr1_dsp_ty = getbits(&state, 3 ); pci->hli.hl_gi.zero3 = getbits(&state, 1 ); pci->hli.hl_gi.btngr2_dsp_ty = getbits(&state, 3 ); pci->hli.hl_gi.zero4 = getbits(&state, 1 ); pci->hli.hl_gi.btngr3_dsp_ty = getbits(&state, 3 ); pci->hli.hl_gi.btn_ofn = getbits(&state, 8 ); pci->hli.hl_gi.btn_ns = getbits(&state, 8 ); pci->hli.hl_gi.nsl_btn_ns = getbits(&state, 8 ); pci->hli.hl_gi.zero5 = getbits(&state, 8 ); pci->hli.hl_gi.fosl_btnn = getbits(&state, 8 ); pci->hli.hl_gi.foac_btnn = getbits(&state, 8 ); /* pci hli btn_colit */ for(i = 0; i < 3; i++) for(j = 0; j < 2; j++) pci->hli.btn_colit.btn_coli[i][j] = getbits(&state, 32 ); /* NOTE: I've had to change the structure from the disk layout to get * the packing to work with Sun's Forte C compiler. */ /* pci hli btni */ for(i = 0; i < 36; i++) { pci->hli.btnit[i].btn_coln = getbits(&state, 2 ); pci->hli.btnit[i].x_start = getbits(&state, 10 ); pci->hli.btnit[i].zero1 = getbits(&state, 2 ); pci->hli.btnit[i].x_end = getbits(&state, 10 ); pci->hli.btnit[i].auto_action_mode = getbits(&state, 2 ); pci->hli.btnit[i].y_start = getbits(&state, 10 ); pci->hli.btnit[i].zero2 = getbits(&state, 2 ); pci->hli.btnit[i].y_end = getbits(&state, 10 ); pci->hli.btnit[i].zero3 = getbits(&state, 2 ); pci->hli.btnit[i].up = getbits(&state, 6 ); pci->hli.btnit[i].zero4 = getbits(&state, 2 ); pci->hli.btnit[i].down = getbits(&state, 6 ); pci->hli.btnit[i].zero5 = getbits(&state, 2 ); pci->hli.btnit[i].left = getbits(&state, 6 ); pci->hli.btnit[i].zero6 = getbits(&state, 2 ); pci->hli.btnit[i].right = getbits(&state, 6 ); /* pci vm_cmd */ for(j = 0; j < 8; j++) pci->hli.btnit[i].cmd.bytes[j] = getbits(&state, 8 ); } #ifndef NDEBUG /* Asserts */ /* pci pci gi */ CHECK_VALUE(pci->pci_gi.zero1 == 0); /* pci hli hli_gi */ CHECK_VALUE(pci->hli.hl_gi.zero1 == 0); CHECK_VALUE(pci->hli.hl_gi.zero2 == 0); CHECK_VALUE(pci->hli.hl_gi.zero3 == 0); CHECK_VALUE(pci->hli.hl_gi.zero4 == 0); CHECK_VALUE(pci->hli.hl_gi.zero5 == 0); /* Are there buttons defined here? */ if((pci->hli.hl_gi.hli_ss & 0x03) != 0) { CHECK_VALUE(pci->hli.hl_gi.btn_ns != 0); CHECK_VALUE(pci->hli.hl_gi.btngr_ns != 0); } else { CHECK_VALUE((pci->hli.hl_gi.btn_ns != 0 && pci->hli.hl_gi.btngr_ns != 0) || (pci->hli.hl_gi.btn_ns == 0 && pci->hli.hl_gi.btngr_ns == 0)); } /* pci hli btnit */ for(i = 0; i < pci->hli.hl_gi.btngr_ns; i++) { for(j = 0; j < (36 / pci->hli.hl_gi.btngr_ns); j++) { int n = (36 / pci->hli.hl_gi.btngr_ns) * i + j; CHECK_VALUE(pci->hli.btnit[n].zero1 == 0); CHECK_VALUE(pci->hli.btnit[n].zero2 == 0); CHECK_VALUE(pci->hli.btnit[n].zero3 == 0); CHECK_VALUE(pci->hli.btnit[n].zero4 == 0); CHECK_VALUE(pci->hli.btnit[n].zero5 == 0); CHECK_VALUE(pci->hli.btnit[n].zero6 == 0); if (j < pci->hli.hl_gi.btn_ns) { CHECK_VALUE(pci->hli.btnit[n].x_start <= pci->hli.btnit[n].x_end); CHECK_VALUE(pci->hli.btnit[n].y_start <= pci->hli.btnit[n].y_end); CHECK_VALUE(pci->hli.btnit[n].up <= pci->hli.hl_gi.btn_ns); CHECK_VALUE(pci->hli.btnit[n].down <= pci->hli.hl_gi.btn_ns); CHECK_VALUE(pci->hli.btnit[n].left <= pci->hli.hl_gi.btn_ns); CHECK_VALUE(pci->hli.btnit[n].right <= pci->hli.hl_gi.btn_ns); /* vmcmd_verify(pci->hli.btnit[n].cmd); */ } else { int k; CHECK_VALUE(pci->hli.btnit[n].btn_coln == 0); CHECK_VALUE(pci->hli.btnit[n].auto_action_mode == 0); CHECK_VALUE(pci->hli.btnit[n].x_start == 0); CHECK_VALUE(pci->hli.btnit[n].y_start == 0); CHECK_VALUE(pci->hli.btnit[n].x_end == 0); CHECK_VALUE(pci->hli.btnit[n].y_end == 0); CHECK_VALUE(pci->hli.btnit[n].up == 0); CHECK_VALUE(pci->hli.btnit[n].down == 0); CHECK_VALUE(pci->hli.btnit[n].left == 0); CHECK_VALUE(pci->hli.btnit[n].right == 0); for (k = 0; k < 8; k++) CHECK_VALUE(pci->hli.btnit[n].cmd.bytes[k] == 0); /* CHECK_ZERO? */ } } } #endif /* !NDEBUG */ } void navRead_DSI(dsi_t *dsi, unsigned char *buffer) { int i; getbits_state_t state; if (!getbits_init(&state, buffer)) abort(); /* Passed NULL pointers */ /* dsi dsi gi */ dsi->dsi_gi.nv_pck_scr = getbits(&state, 32 ); dsi->dsi_gi.nv_pck_lbn = getbits(&state, 32 ); dsi->dsi_gi.vobu_ea = getbits(&state, 32 ); dsi->dsi_gi.vobu_1stref_ea = getbits(&state, 32 ); dsi->dsi_gi.vobu_2ndref_ea = getbits(&state, 32 ); dsi->dsi_gi.vobu_3rdref_ea = getbits(&state, 32 ); dsi->dsi_gi.vobu_vob_idn = getbits(&state, 16 ); dsi->dsi_gi.zero1 = getbits(&state, 8 ); dsi->dsi_gi.vobu_c_idn = getbits(&state, 8 ); dsi->dsi_gi.c_eltm.hour = getbits(&state, 8 ); dsi->dsi_gi.c_eltm.minute = getbits(&state, 8 ); dsi->dsi_gi.c_eltm.second = getbits(&state, 8 ); dsi->dsi_gi.c_eltm.frame_u = getbits(&state, 8 ); /* dsi sml pbi */ dsi->sml_pbi.category = getbits(&state, 16 ); dsi->sml_pbi.ilvu_ea = getbits(&state, 32 ); dsi->sml_pbi.ilvu_sa = getbits(&state, 32 ); dsi->sml_pbi.size = getbits(&state, 16 ); dsi->sml_pbi.vob_v_s_s_ptm = getbits(&state, 32 ); dsi->sml_pbi.vob_v_e_e_ptm = getbits(&state, 32 ); for(i = 0; i < 8; i++) { dsi->sml_pbi.vob_a[i].stp_ptm1 = getbits(&state, 32 ); dsi->sml_pbi.vob_a[i].stp_ptm2 = getbits(&state, 32 ); dsi->sml_pbi.vob_a[i].gap_len1 = getbits(&state, 32 ); dsi->sml_pbi.vob_a[i].gap_len2 = getbits(&state, 32 ); } /* dsi sml agli */ for(i = 0; i < 9; i++) { dsi->sml_agli.data[ i ].address = getbits(&state, 32 ); dsi->sml_agli.data[ i ].size = getbits(&state, 16 ); } /* dsi vobu sri */ dsi->vobu_sri.next_video = getbits(&state, 32 ); for(i = 0; i < 19; i++) dsi->vobu_sri.fwda[i] = getbits(&state, 32 ); dsi->vobu_sri.next_vobu = getbits(&state, 32 ); dsi->vobu_sri.prev_vobu = getbits(&state, 32 ); for(i = 0; i < 19; i++) dsi->vobu_sri.bwda[i] = getbits(&state, 32 ); dsi->vobu_sri.prev_video = getbits(&state, 32 ); /* dsi synci */ for(i = 0; i < 8; i++) dsi->synci.a_synca[i] = getbits(&state, 16 ); for(i = 0; i < 32; i++) dsi->synci.sp_synca[i] = getbits(&state, 32 ); /* Asserts */ /* dsi dsi gi */ CHECK_VALUE(dsi->dsi_gi.zero1 == 0); }
onetechgenius/XBMCast2TV
lib/libdvd/libdvdread/src/nav_read.c
C
gpl-2.0
10,734
<div class="apiDetail"> <div> <h2><span>Array(String) / JSON</span><span class="path">setting.async.</span>otherParam</h2> <h3>Overview<span class="h3_info">[ depends on <span class="highlight_green">jquery.ztree.core</span> js ]</span></h3> <div class="desc"> <p></p> <div class="longdesc"> <p>The query parameters of the Ajax request. (key - value) It is valid when <span class="highlight_red">[setting.async.enable = true]</span></p> <p>Default: [ ]</p> </div> </div> <h3>Array(String) Format</h3> <div class="desc"> <p>Can be an empty array. e.g. [ ]. The array should contain key value pairs, e.g. [key, value]. (Either or [key] or [key, value, key] is wrong!!)</p> </div> <h3>JSON Format</h3> <div class="desc"> <p>Use JSON hash data to set the key-value pairs. e.g. { key1:value1, key2:value2 }</p> </div> <h3>Examples of setting</h3> <h4>1. Using Array(String) Format</h4> <pre xmlns=""><code>var setting = { async: { enable: true, url: "http://host/getNode.php", <span style="color:red">otherParam: ["id", "1", "name", "test"]</span> } }; when zTree sends the ajax request, the query string will be like this: id=1&name=test</code></pre> <h4>2. Using JSON data Format</h4> <pre xmlns=""><code>var setting = { async: { enable: true, url: "http://host/getNode.php", <span style="color:red">otherParam: { "id":"1", "name":"test"}</span> } }; when zTree sends the ajax request, the query string will be like this: id=1&name=test</code></pre> </div> </div>
h819/spring-boot
ztree/src/main/resources/static/zTree/api/en/setting.async.otherParam.html
HTML
apache-2.0
1,506
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'showblocks', 'si', { toolbar: 'කොටස පෙන්නන්න' });
vousk/jsdelivr
files/ckeditor/4.3.0/plugins/showblocks/lang/si.js
JavaScript
mit
248
/* Copyright (c) 2013-2016, 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 __A3XX_H #define __A3XX_H #include "a3xx_reg.h" #define A3XX_IRQ_FLAGS \ { BIT(A3XX_INT_RBBM_GPU_IDLE), "RBBM_GPU_IDLE" }, \ { BIT(A3XX_INT_RBBM_AHB_ERROR), "RBBM_AHB_ERR" }, \ { BIT(A3XX_INT_RBBM_REG_TIMEOUT), "RBBM_REG_TIMEOUT" }, \ { BIT(A3XX_INT_RBBM_ME_MS_TIMEOUT), "RBBM_ME_MS_TIMEOUT" }, \ { BIT(A3XX_INT_RBBM_PFP_MS_TIMEOUT), "RBBM_PFP_MS_TIMEOUT" }, \ { BIT(A3XX_INT_RBBM_ATB_BUS_OVERFLOW), "RBBM_ATB_BUS_OVERFLOW" }, \ { BIT(A3XX_INT_VFD_ERROR), "RBBM_VFD_ERROR" }, \ { BIT(A3XX_INT_CP_SW_INT), "CP_SW" }, \ { BIT(A3XX_INT_CP_T0_PACKET_IN_IB), "CP_T0_PACKET_IN_IB" }, \ { BIT(A3XX_INT_CP_OPCODE_ERROR), "CP_OPCODE_ERROR" }, \ { BIT(A3XX_INT_CP_RESERVED_BIT_ERROR), "CP_RESERVED_BIT_ERROR" }, \ { BIT(A3XX_INT_CP_HW_FAULT), "CP_HW_FAULT" }, \ { BIT(A3XX_INT_CP_DMA), "CP_DMA" }, \ { BIT(A3XX_INT_CP_IB2_INT), "CP_IB2_INT" }, \ { BIT(A3XX_INT_CP_IB1_INT), "CP_IB1_INT" }, \ { BIT(A3XX_INT_CP_RB_INT), "CP_RB_INT" }, \ { BIT(A3XX_INT_CP_REG_PROTECT_FAULT), "CP_REG_PROTECT_FAULT" }, \ { BIT(A3XX_INT_CP_RB_DONE_TS), "CP_RB_DONE_TS" }, \ { BIT(A3XX_INT_CP_VS_DONE_TS), "CP_VS_DONE_TS" }, \ { BIT(A3XX_INT_CP_PS_DONE_TS), "CP_PS_DONE_TS" }, \ { BIT(A3XX_INT_CACHE_FLUSH_TS), "CACHE_FLUSH_TS" }, \ { BIT(A3XX_INT_CP_AHB_ERROR_HALT), "CP_AHB_ERROR_HALT" }, \ { BIT(A3XX_INT_MISC_HANG_DETECT), "MISC_HANG_DETECT" }, \ { BIT(A3XX_INT_UCHE_OOB_ACCESS), "UCHE_OOB_ACCESS" } unsigned int a3xx_irq_pending(struct adreno_device *adreno_dev); int a3xx_microcode_read(struct adreno_device *adreno_dev); int a3xx_microcode_load(struct adreno_device *adreno_dev, unsigned int start_type); int a3xx_perfcounter_enable(struct adreno_device *adreno_dev, unsigned int group, unsigned int counter, unsigned int countable); uint64_t a3xx_perfcounter_read(struct adreno_device *adreno_dev, unsigned int group, unsigned int counter); void a3xx_a4xx_err_callback(struct adreno_device *adreno_dev, int bit); void a3xx_snapshot(struct adreno_device *adreno_dev, struct kgsl_snapshot *snapshot); #endif /*__A3XX_H */
butkevicius/motorola-moto-z-permissive-kernel
kernel/drivers/gpu/msm/adreno_a3xx.h
C
gpl-2.0
2,579
/* * Copyright 2004-2007 Freescale Semiconductor, Inc. All Rights Reserved. * Copyright 2008 Juergen Beisert, [email protected] * * This contains i.MX27-specific hardware definitions. For those * hardware pieces that are common between i.MX21 and i.MX27, have a * look at mx2x.h. * * 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 __MACH_MX27_H__ #define __MACH_MX27_H__ #define MX27_AIPI_BASE_ADDR 0x10000000 #define MX27_AIPI_SIZE SZ_1M #define MX27_DMA_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x01000) #define MX27_WDOG_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x02000) #define MX27_GPT1_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x03000) #define MX27_GPT2_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x04000) #define MX27_GPT3_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x05000) #define MX27_PWM_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x06000) #define MX27_RTC_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x07000) #define MX27_KPP_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x08000) #define MX27_OWIRE_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x09000) #define MX27_UART1_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x0a000) #define MX27_UART2_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x0b000) #define MX27_UART3_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x0c000) #define MX27_UART4_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x0d000) #define MX27_CSPI1_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x0e000) #define MX27_CSPI2_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x0f000) #define MX27_SSI1_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x10000) #define MX27_SSI2_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x11000) #define MX27_I2C1_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x12000) #define MX27_SDHC1_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x13000) #define MX27_SDHC2_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x14000) #define MX27_GPIO_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x15000) #define MX27_GPIO1_BASE_ADDR (MX27_GPIO_BASE_ADDR + 0x000) #define MX27_GPIO2_BASE_ADDR (MX27_GPIO_BASE_ADDR + 0x100) #define MX27_GPIO3_BASE_ADDR (MX27_GPIO_BASE_ADDR + 0x200) #define MX27_GPIO4_BASE_ADDR (MX27_GPIO_BASE_ADDR + 0x300) #define MX27_GPIO5_BASE_ADDR (MX27_GPIO_BASE_ADDR + 0x400) #define MX27_GPIO6_BASE_ADDR (MX27_GPIO_BASE_ADDR + 0x500) #define MX27_AUDMUX_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x16000) #define MX27_CSPI3_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x17000) #define MX27_MSHC_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x18000) #define MX27_GPT4_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x19000) #define MX27_GPT5_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x1a000) #define MX27_UART5_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x1b000) #define MX27_UART6_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x1c000) #define MX27_I2C2_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x1d000) #define MX27_SDHC3_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x1e000) #define MX27_GPT6_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x1f000) #define MX27_LCDC_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x21000) #define MX27_SLCDC_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x22000) #define MX27_VPU_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x23000) #define MX27_USB_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x24000) #define MX27_USB_OTG_BASE_ADDR (MX27_USB_BASE_ADDR + 0x0000) #define MX27_USB_HS1_BASE_ADDR (MX27_USB_BASE_ADDR + 0x0200) #define MX27_USB_HS2_BASE_ADDR (MX27_USB_BASE_ADDR + 0x0400) #define MX27_SAHARA_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x25000) #define MX27_EMMAPP_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x26000) #define MX27_EMMAPRP_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x26400) #define MX27_CCM_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x27000) #define MX27_SYSCTRL_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x27800) #define MX27_IIM_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x28000) #define MX27_RTIC_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x2a000) #define MX27_FEC_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x2b000) #define MX27_SCC_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x2c000) #define MX27_ETB_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x3b000) #define MX27_ETB_RAM_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x3c000) #define MX27_JAM_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x3e000) #define MX27_MAX_BASE_ADDR (MX27_AIPI_BASE_ADDR + 0x3f000) #define MX27_AVIC_BASE_ADDR 0x10040000 /* ROM patch */ #define MX27_ROMP_BASE_ADDR 0x10041000 #define MX27_SAHB1_BASE_ADDR 0x80000000 #define MX27_SAHB1_SIZE SZ_1M #define MX27_CSI_BASE_ADDR (MX27_SAHB1_BASE_ADDR + 0x0000) #define MX27_ATA_BASE_ADDR (MX27_SAHB1_BASE_ADDR + 0x1000) /* Memory regions and CS */ #define MX27_SDRAM_BASE_ADDR 0xa0000000 #define MX27_CSD1_BASE_ADDR 0xb0000000 #define MX27_CS0_BASE_ADDR 0xc0000000 #define MX27_CS1_BASE_ADDR 0xc8000000 #define MX27_CS2_BASE_ADDR 0xd0000000 #define MX27_CS3_BASE_ADDR 0xd2000000 #define MX27_CS4_BASE_ADDR 0xd4000000 #define MX27_CS5_BASE_ADDR 0xd6000000 /* NAND, SDRAM, WEIM, M3IF, EMI controllers */ #define MX27_X_MEMC_BASE_ADDR 0xd8000000 #define MX27_X_MEMC_SIZE SZ_1M #define MX27_NFC_BASE_ADDR (MX27_X_MEMC_BASE_ADDR) #define MX27_SDRAMC_BASE_ADDR (MX27_X_MEMC_BASE_ADDR + 0x1000) #define MX27_WEIM_BASE_ADDR (MX27_X_MEMC_BASE_ADDR + 0x2000) #define MX27_M3IF_BASE_ADDR (MX27_X_MEMC_BASE_ADDR + 0x3000) #define MX27_PCMCIA_CTL_BASE_ADDR (MX27_X_MEMC_BASE_ADDR + 0x4000) #define MX27_WEIM_CSCRx_BASE_ADDR(cs) (MX27_WEIM_BASE_ADDR + (cs) * 0x10) #define MX27_WEIM_CSCRxU(cs) (MX27_WEIM_CSCRx_BASE_ADDR(cs)) #define MX27_WEIM_CSCRxL(cs) (MX27_WEIM_CSCRx_BASE_ADDR(cs) + 0x4) #define MX27_WEIM_CSCRxA(cs) (MX27_WEIM_CSCRx_BASE_ADDR(cs) + 0x8) #define MX27_PCMCIA_MEM_BASE_ADDR 0xdc000000 /* IRAM */ #define MX27_IRAM_BASE_ADDR 0xffff4c00 /* internal ram */ #define MX27_IO_P2V(x) IMX_IO_P2V(x) #define MX27_IO_ADDRESS(x) IOMEM(MX27_IO_P2V(x)) /* fixed interrupt numbers */ #include <asm/irq.h> #define MX27_INT_I2C2 (NR_IRQS_LEGACY + 1) #define MX27_INT_GPT6 (NR_IRQS_LEGACY + 2) #define MX27_INT_GPT5 (NR_IRQS_LEGACY + 3) #define MX27_INT_GPT4 (NR_IRQS_LEGACY + 4) #define MX27_INT_RTIC (NR_IRQS_LEGACY + 5) #define MX27_INT_CSPI3 (NR_IRQS_LEGACY + 6) #define MX27_INT_MSHC (NR_IRQS_LEGACY + 7) #define MX27_INT_GPIO (NR_IRQS_LEGACY + 8) #define MX27_INT_SDHC3 (NR_IRQS_LEGACY + 9) #define MX27_INT_SDHC2 (NR_IRQS_LEGACY + 10) #define MX27_INT_SDHC1 (NR_IRQS_LEGACY + 11) #define MX27_INT_I2C1 (NR_IRQS_LEGACY + 12) #define MX27_INT_SSI2 (NR_IRQS_LEGACY + 13) #define MX27_INT_SSI1 (NR_IRQS_LEGACY + 14) #define MX27_INT_CSPI2 (NR_IRQS_LEGACY + 15) #define MX27_INT_CSPI1 (NR_IRQS_LEGACY + 16) #define MX27_INT_UART4 (NR_IRQS_LEGACY + 17) #define MX27_INT_UART3 (NR_IRQS_LEGACY + 18) #define MX27_INT_UART2 (NR_IRQS_LEGACY + 19) #define MX27_INT_UART1 (NR_IRQS_LEGACY + 20) #define MX27_INT_KPP (NR_IRQS_LEGACY + 21) #define MX27_INT_RTC (NR_IRQS_LEGACY + 22) #define MX27_INT_PWM (NR_IRQS_LEGACY + 23) #define MX27_INT_GPT3 (NR_IRQS_LEGACY + 24) #define MX27_INT_GPT2 (NR_IRQS_LEGACY + 25) #define MX27_INT_GPT1 (NR_IRQS_LEGACY + 26) #define MX27_INT_WDOG (NR_IRQS_LEGACY + 27) #define MX27_INT_PCMCIA (NR_IRQS_LEGACY + 28) #define MX27_INT_NFC (NR_IRQS_LEGACY + 29) #define MX27_INT_ATA (NR_IRQS_LEGACY + 30) #define MX27_INT_CSI (NR_IRQS_LEGACY + 31) #define MX27_INT_DMACH0 (NR_IRQS_LEGACY + 32) #define MX27_INT_DMACH1 (NR_IRQS_LEGACY + 33) #define MX27_INT_DMACH2 (NR_IRQS_LEGACY + 34) #define MX27_INT_DMACH3 (NR_IRQS_LEGACY + 35) #define MX27_INT_DMACH4 (NR_IRQS_LEGACY + 36) #define MX27_INT_DMACH5 (NR_IRQS_LEGACY + 37) #define MX27_INT_DMACH6 (NR_IRQS_LEGACY + 38) #define MX27_INT_DMACH7 (NR_IRQS_LEGACY + 39) #define MX27_INT_DMACH8 (NR_IRQS_LEGACY + 40) #define MX27_INT_DMACH9 (NR_IRQS_LEGACY + 41) #define MX27_INT_DMACH10 (NR_IRQS_LEGACY + 42) #define MX27_INT_DMACH11 (NR_IRQS_LEGACY + 43) #define MX27_INT_DMACH12 (NR_IRQS_LEGACY + 44) #define MX27_INT_DMACH13 (NR_IRQS_LEGACY + 45) #define MX27_INT_DMACH14 (NR_IRQS_LEGACY + 46) #define MX27_INT_DMACH15 (NR_IRQS_LEGACY + 47) #define MX27_INT_UART6 (NR_IRQS_LEGACY + 48) #define MX27_INT_UART5 (NR_IRQS_LEGACY + 49) #define MX27_INT_FEC (NR_IRQS_LEGACY + 50) #define MX27_INT_EMMAPRP (NR_IRQS_LEGACY + 51) #define MX27_INT_EMMAPP (NR_IRQS_LEGACY + 52) #define MX27_INT_VPU (NR_IRQS_LEGACY + 53) #define MX27_INT_USB_HS1 (NR_IRQS_LEGACY + 54) #define MX27_INT_USB_HS2 (NR_IRQS_LEGACY + 55) #define MX27_INT_USB_OTG (NR_IRQS_LEGACY + 56) #define MX27_INT_SCC_SMN (NR_IRQS_LEGACY + 57) #define MX27_INT_SCC_SCM (NR_IRQS_LEGACY + 58) #define MX27_INT_SAHARA (NR_IRQS_LEGACY + 59) #define MX27_INT_SLCDC (NR_IRQS_LEGACY + 60) #define MX27_INT_LCDC (NR_IRQS_LEGACY + 61) #define MX27_INT_IIM (NR_IRQS_LEGACY + 62) #define MX27_INT_CCM (NR_IRQS_LEGACY + 63) /* fixed DMA request numbers */ #define MX27_DMA_REQ_CSPI3_RX 1 #define MX27_DMA_REQ_CSPI3_TX 2 #define MX27_DMA_REQ_EXT 3 #define MX27_DMA_REQ_MSHC 4 #define MX27_DMA_REQ_SDHC2 6 #define MX27_DMA_REQ_SDHC1 7 #define MX27_DMA_REQ_SSI2_RX0 8 #define MX27_DMA_REQ_SSI2_TX0 9 #define MX27_DMA_REQ_SSI2_RX1 10 #define MX27_DMA_REQ_SSI2_TX1 11 #define MX27_DMA_REQ_SSI1_RX0 12 #define MX27_DMA_REQ_SSI1_TX0 13 #define MX27_DMA_REQ_SSI1_RX1 14 #define MX27_DMA_REQ_SSI1_TX1 15 #define MX27_DMA_REQ_CSPI2_RX 16 #define MX27_DMA_REQ_CSPI2_TX 17 #define MX27_DMA_REQ_CSPI1_RX 18 #define MX27_DMA_REQ_CSPI1_TX 19 #define MX27_DMA_REQ_UART4_RX 20 #define MX27_DMA_REQ_UART4_TX 21 #define MX27_DMA_REQ_UART3_RX 22 #define MX27_DMA_REQ_UART3_TX 23 #define MX27_DMA_REQ_UART2_RX 24 #define MX27_DMA_REQ_UART2_TX 25 #define MX27_DMA_REQ_UART1_RX 26 #define MX27_DMA_REQ_UART1_TX 27 #define MX27_DMA_REQ_ATA_TX 28 #define MX27_DMA_REQ_ATA_RCV 29 #define MX27_DMA_REQ_CSI_STAT 30 #define MX27_DMA_REQ_CSI_RX 31 #define MX27_DMA_REQ_UART5_TX 32 #define MX27_DMA_REQ_UART5_RX 33 #define MX27_DMA_REQ_UART6_TX 34 #define MX27_DMA_REQ_UART6_RX 35 #define MX27_DMA_REQ_SDHC3 36 #define MX27_DMA_REQ_NFC 37 #endif /* ifndef __MACH_MX27_H__ */
AiJiaZone/linux-4.0
virt/arch/arm/mach-imx/mx27.h
C
gpl-2.0
10,393
google_calendar.css: google_calendar.sass sass --trace -t expanded google_calendar.sass google_calendar.css
diogocs1/comps
web/addons/google_calendar/static/src/css/Makefile
Makefile
apache-2.0
111
from io import BytesIO class CallbackFileWrapper(object): """ Small wrapper around a fp object which will tee everything read into a buffer, and when that file is closed it will execute a callback with the contents of that buffer. All attributes are proxied to the underlying file object. This class uses members with a double underscore (__) leading prefix so as not to accidentally shadow an attribute. """ def __init__(self, fp, callback): self.__buf = BytesIO() self.__fp = fp self.__callback = callback def __getattr__(self, name): # The vaguaries of garbage collection means that self.__fp is # not always set. By using __getattribute__ and the private # name[0] allows looking up the attribute value and raising an # AttributeError when it doesn't exist. This stop thigns from # infinitely recursing calls to getattr in the case where # self.__fp hasn't been set. # # [0] https://docs.python.org/2/reference/expressions.html#atom-identifiers fp = self.__getattribute__('_CallbackFileWrapper__fp') return getattr(fp, name) def __is_fp_closed(self): try: return self.__fp.fp is None except AttributeError: pass try: return self.__fp.closed except AttributeError: pass # We just don't cache it then. # TODO: Add some logging here... return False def read(self, amt=None): data = self.__fp.read(amt) self.__buf.write(data) if self.__is_fp_closed(): if self.__callback: self.__callback(self.__buf.getvalue()) # We assign this to None here, because otherwise we can get into # really tricky problems where the CPython interpreter dead locks # because the callback is holding a reference to something which # has a __del__ method. Setting this to None breaks the cycle # and allows the garbage collector to do it's thing normally. self.__callback = None return data
zwChan/VATEC
~/eb-virt/Lib/site-packages/pip/_vendor/cachecontrol/filewrapper.py
Python
apache-2.0
2,168
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapreduce; import org.apache.hadoop.util.StringUtils; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.JobStatus.State; import org.apache.hadoop.mapreduce.v2.api.records.JobId; import org.apache.hadoop.mapreduce.v2.api.records.JobReport; import org.apache.hadoop.mapreduce.v2.api.records.JobState; import org.apache.hadoop.mapreduce.v2.api.records.TaskState; import org.apache.hadoop.mapreduce.v2.api.records.TaskType; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.QueueState; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.util.Records; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestTypeConverter { @Test public void testEnums() throws Exception { for (YarnApplicationState applicationState : YarnApplicationState.values()) { TypeConverter.fromYarn(applicationState, FinalApplicationStatus.FAILED); } // ad hoc test of NEW_SAVING, which is newly added Assert.assertEquals(State.PREP, TypeConverter.fromYarn( YarnApplicationState.NEW_SAVING, FinalApplicationStatus.FAILED)); for (TaskType taskType : TaskType.values()) { TypeConverter.fromYarn(taskType); } for (JobState jobState : JobState.values()) { TypeConverter.fromYarn(jobState); } for (QueueState queueState : QueueState.values()) { TypeConverter.fromYarn(queueState); } for (TaskState taskState : TaskState.values()) { TypeConverter.fromYarn(taskState); } } @Test public void testFromYarn() throws Exception { int appStartTime = 612354; int appFinishTime = 612355; YarnApplicationState state = YarnApplicationState.RUNNING; ApplicationId applicationId = ApplicationId.newInstance(0, 0); ApplicationReport applicationReport = Records .newRecord(ApplicationReport.class); applicationReport.setApplicationId(applicationId); applicationReport.setYarnApplicationState(state); applicationReport.setStartTime(appStartTime); applicationReport.setFinishTime(appFinishTime); applicationReport.setUser("TestTypeConverter-user"); ApplicationResourceUsageReport appUsageRpt = Records .newRecord(ApplicationResourceUsageReport.class); Resource r = Records.newRecord(Resource.class); r.setMemory(2048); appUsageRpt.setNeededResources(r); appUsageRpt.setNumReservedContainers(1); appUsageRpt.setNumUsedContainers(3); appUsageRpt.setReservedResources(r); appUsageRpt.setUsedResources(r); applicationReport.setApplicationResourceUsageReport(appUsageRpt); JobStatus jobStatus = TypeConverter.fromYarn(applicationReport, "dummy-jobfile"); Assert.assertEquals(appStartTime, jobStatus.getStartTime()); Assert.assertEquals(appFinishTime, jobStatus.getFinishTime()); Assert.assertEquals(state.toString(), jobStatus.getState().toString()); } @Test public void testFromYarnApplicationReport() { ApplicationId mockAppId = mock(ApplicationId.class); when(mockAppId.getClusterTimestamp()).thenReturn(12345L); when(mockAppId.getId()).thenReturn(6789); ApplicationReport mockReport = mock(ApplicationReport.class); when(mockReport.getTrackingUrl()).thenReturn("dummy-tracking-url"); when(mockReport.getApplicationId()).thenReturn(mockAppId); when(mockReport.getYarnApplicationState()).thenReturn(YarnApplicationState.KILLED); when(mockReport.getUser()).thenReturn("dummy-user"); when(mockReport.getQueue()).thenReturn("dummy-queue"); String jobFile = "dummy-path/job.xml"; try { JobStatus status = TypeConverter.fromYarn(mockReport, jobFile); } catch (NullPointerException npe) { Assert.fail("Type converstion from YARN fails for jobs without " + "ApplicationUsageReport"); } ApplicationResourceUsageReport appUsageRpt = Records .newRecord(ApplicationResourceUsageReport.class); Resource r = Records.newRecord(Resource.class); r.setMemory(2048); appUsageRpt.setNeededResources(r); appUsageRpt.setNumReservedContainers(1); appUsageRpt.setNumUsedContainers(3); appUsageRpt.setReservedResources(r); appUsageRpt.setUsedResources(r); when(mockReport.getApplicationResourceUsageReport()).thenReturn(appUsageRpt); JobStatus status = TypeConverter.fromYarn(mockReport, jobFile); Assert.assertNotNull("fromYarn returned null status", status); Assert.assertEquals("jobFile set incorrectly", "dummy-path/job.xml", status.getJobFile()); Assert.assertEquals("queue set incorrectly", "dummy-queue", status.getQueue()); Assert.assertEquals("trackingUrl set incorrectly", "dummy-tracking-url", status.getTrackingUrl()); Assert.assertEquals("user set incorrectly", "dummy-user", status.getUsername()); Assert.assertEquals("schedulingInfo set incorrectly", "dummy-tracking-url", status.getSchedulingInfo()); Assert.assertEquals("jobId set incorrectly", 6789, status.getJobID().getId()); Assert.assertEquals("state set incorrectly", JobStatus.State.KILLED, status.getState()); Assert.assertEquals("needed mem info set incorrectly", 2048, status.getNeededMem()); Assert.assertEquals("num rsvd slots info set incorrectly", 1, status.getNumReservedSlots()); Assert.assertEquals("num used slots info set incorrectly", 3, status.getNumUsedSlots()); Assert.assertEquals("rsvd mem info set incorrectly", 2048, status.getReservedMem()); Assert.assertEquals("used mem info set incorrectly", 2048, status.getUsedMem()); } @Test public void testFromYarnQueueInfo() { org.apache.hadoop.yarn.api.records.QueueInfo queueInfo = Records .newRecord(org.apache.hadoop.yarn.api.records.QueueInfo.class); queueInfo.setQueueState(org.apache.hadoop.yarn.api.records.QueueState.STOPPED); org.apache.hadoop.mapreduce.QueueInfo returned = TypeConverter.fromYarn(queueInfo, new Configuration()); Assert.assertEquals("queueInfo translation didn't work.", returned.getState().toString(), StringUtils.toLowerCase(queueInfo.getQueueState().toString())); } /** * Test that child queues are converted too during conversion of the parent * queue */ @Test public void testFromYarnQueue() { //Define child queue org.apache.hadoop.yarn.api.records.QueueInfo child = Mockito.mock(org.apache.hadoop.yarn.api.records.QueueInfo.class); Mockito.when(child.getQueueState()).thenReturn(QueueState.RUNNING); //Define parent queue org.apache.hadoop.yarn.api.records.QueueInfo queueInfo = Mockito.mock(org.apache.hadoop.yarn.api.records.QueueInfo.class); List<org.apache.hadoop.yarn.api.records.QueueInfo> children = new ArrayList<org.apache.hadoop.yarn.api.records.QueueInfo>(); children.add(child); //Add one child Mockito.when(queueInfo.getChildQueues()).thenReturn(children); Mockito.when(queueInfo.getQueueState()).thenReturn(QueueState.RUNNING); //Call the function we're testing org.apache.hadoop.mapreduce.QueueInfo returned = TypeConverter.fromYarn(queueInfo, new Configuration()); //Verify that the converted queue has the 1 child we had added Assert.assertEquals("QueueInfo children weren't properly converted", returned.getQueueChildren().size(), 1); } @Test public void testFromYarnJobReport() throws Exception { int jobStartTime = 612354; int jobFinishTime = 612355; JobState state = JobState.RUNNING; JobId jobId = Records.newRecord(JobId.class); JobReport jobReport = Records.newRecord(JobReport.class); ApplicationId applicationId = ApplicationId.newInstance(0, 0); jobId.setAppId(applicationId); jobId.setId(0); jobReport.setJobId(jobId); jobReport.setJobState(state); jobReport.setStartTime(jobStartTime); jobReport.setFinishTime(jobFinishTime); jobReport.setUser("TestTypeConverter-user"); JobStatus jobStatus = TypeConverter.fromYarn(jobReport, "dummy-jobfile"); Assert.assertEquals(jobStartTime, jobStatus.getStartTime()); Assert.assertEquals(jobFinishTime, jobStatus.getFinishTime()); Assert.assertEquals(state.toString(), jobStatus.getState().toString()); } }
samuelan/hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/test/java/org/apache/hadoop/mapreduce/TestTypeConverter.java
Java
apache-2.0
9,510
/* Simple DirectMedia Layer Copyright (C) 1997-2016 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "SDL_config.h" #ifndef _SDL_winrtopengles_h #define _SDL_winrtopengles_h #if SDL_VIDEO_DRIVER_WINRT && SDL_VIDEO_OPENGL_EGL #include "../SDL_sysvideo.h" #include "../SDL_egl_c.h" /* OpenGLES functions */ #define WINRT_GLES_GetAttribute SDL_EGL_GetAttribute #define WINRT_GLES_GetProcAddress SDL_EGL_GetProcAddress #define WINRT_GLES_SetSwapInterval SDL_EGL_SetSwapInterval #define WINRT_GLES_GetSwapInterval SDL_EGL_GetSwapInterval #define WINRT_GLES_DeleteContext SDL_EGL_DeleteContext extern int WINRT_GLES_LoadLibrary(_THIS, const char *path); extern void WINRT_GLES_UnloadLibrary(_THIS); extern SDL_GLContext WINRT_GLES_CreateContext(_THIS, SDL_Window * window); extern void WINRT_GLES_SwapWindow(_THIS, SDL_Window * window); extern int WINRT_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); #ifdef __cplusplus /* Typedefs for ANGLE/WinRT's C++-based native-display and native-window types, * which are used when calling eglGetDisplay and eglCreateWindowSurface. */ typedef Microsoft::WRL::ComPtr<IUnknown> WINRT_EGLNativeWindowType_Old; /* Function pointer typedefs for 'old' ANGLE/WinRT's functions, which may * require that C++ objects be passed in: */ typedef EGLDisplay (EGLAPIENTRY *eglGetDisplay_Old_Function)(WINRT_EGLNativeWindowType_Old); typedef EGLSurface (EGLAPIENTRY *eglCreateWindowSurface_Old_Function)(EGLDisplay, EGLConfig, WINRT_EGLNativeWindowType_Old, const EGLint *); typedef HRESULT (EGLAPIENTRY *CreateWinrtEglWindow_Old_Function)(Microsoft::WRL::ComPtr<IUnknown>, int, IUnknown ** result); #endif /* __cplusplus */ /* Function pointer typedefs for 'new' ANGLE/WinRT functions, which, unlike * the old functions, do not require C++ support and work with plain C. */ typedef EGLDisplay (EGLAPIENTRY *eglGetPlatformDisplayEXT_Function)(EGLenum, void *, const EGLint *); #endif /* SDL_VIDEO_DRIVER_WINRT && SDL_VIDEO_OPENGL_EGL */ #endif /* _SDL_winrtopengles_h */ /* vi: set ts=4 sw=4 expandtab: */
0xc0dec/kiln
vendor/SDL/2.0.4/src/video/winrt/SDL_winrtopengles.h
C
mit
2,913
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //! [0] extern Q_CORE_EXPORT int qt_ntfs_permission_lookup; //! [0] //! [1] qt_ntfs_permission_lookup++; // turn checking on qt_ntfs_permission_lookup--; // turn it off again //! [1]
klickagent/phantomjs
src/qt/qtbase/src/corelib/doc/snippets/ntfsp.cpp
C++
bsd-3-clause
2,186
/* Copyright (c) 2013, 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/kernel.h> #include <linux/platform_device.h> #include <linux/err.h> #include <linux/hrtimer.h> #include <linux/module.h> #include <linux/gpio.h> #include <mach/pmic.h> #include <linux/regulator/consumer.h> #include <linux/workqueue.h> #include <linux/of_gpio.h> #include "../staging/android/timed_output.h" /* default timeout */ #define VIB_DEFAULT_TIMEOUT 10000 struct msm_vib { struct hrtimer vib_timer; struct timed_output_dev timed_dev; struct work_struct work; struct workqueue_struct *queue; int state; int timeout; int motor_en; struct mutex lock; int pmic_gpio_enabled; }; static void set_vibrator(int motor_en, int on) { pr_info("[VIB] %s, on=%d\n",__func__, on); gpio_set_value(motor_en, on); } static void vibrator_enable(struct timed_output_dev *dev, int value) { struct msm_vib *vib = container_of(dev, struct msm_vib, timed_dev); mutex_lock(&vib->lock); hrtimer_cancel(&vib->vib_timer); if (value == 0) { pr_info("[VIB] OFF\n"); vib->state = 0; } else { pr_info("[VIB] ON, Duration : %d msec\n" , value); vib->state = 1; if (value == 0x7fffffff){ pr_info("[VIB] No Use Timer %d \n", value); } else { value = (value > vib->timeout ? vib->timeout : value); hrtimer_start(&vib->vib_timer, ktime_set(value / 1000, (value % 1000) * 1000000), HRTIMER_MODE_REL); } } mutex_unlock(&vib->lock); queue_work(vib->queue, &vib->work); } static void msm_vibrator_update(struct work_struct *work) { struct msm_vib *vib = container_of(work, struct msm_vib, work); set_vibrator(vib->motor_en, vib->state); } static int vibrator_get_time(struct timed_output_dev *dev) { struct msm_vib *vib = container_of(dev, struct msm_vib, timed_dev); if (hrtimer_active(&vib->vib_timer)) { ktime_t r = hrtimer_get_remaining(&vib->vib_timer); return (int)ktime_to_us(r); } else return 0; } static enum hrtimer_restart vibrator_timer_func(struct hrtimer *timer) { struct msm_vib *vib = container_of(timer, struct msm_vib, vib_timer); vib->state = 0; queue_work(vib->queue, &vib->work); return HRTIMER_NORESTART; } #ifdef CONFIG_PM static int msm_vibrator_suspend(struct device *dev) { struct msm_vib *vib = dev_get_drvdata(dev); pr_info("[VIB] %s\n",__func__); hrtimer_cancel(&vib->vib_timer); cancel_work_sync(&vib->work); /* turn-off vibrator */ set_vibrator(vib->motor_en, 0); return 0; } #endif static SIMPLE_DEV_PM_OPS(vibrator_pm_ops, msm_vibrator_suspend, NULL); static int msm_vibrator_probe(struct platform_device *pdev) { struct msm_vib *vib; int rc = 0; pr_info("[VIB] %s\n",__func__); vib = devm_kzalloc(&pdev->dev, sizeof(*vib), GFP_KERNEL); if (!vib) { pr_err("%s : Failed to allocate memory\n", __func__); return -ENOMEM; } vib->motor_en = of_get_named_gpio(pdev->dev.of_node, "samsung,motor-en", 0); if (!gpio_is_valid(vib->motor_en)) { pr_err("%s:%d, reset gpio not specified\n", __func__, __LINE__); return -EINVAL; } vib->pmic_gpio_enabled = of_property_read_bool(pdev->dev.of_node, "samsung,is_pmic_vib_en"); #ifdef CONFIG_SEC_AFYON_PROJECT vib->pmic_gpio_enabled = 0; #endif printk(KERN_ALERT " VIB PMIC GPIO ENABLED Flag is %d \n", vib->pmic_gpio_enabled); if (!(vib->pmic_gpio_enabled)){ rc = gpio_tlmm_config(GPIO_CFG(vib->motor_en, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); if (rc < 0) { pr_err("%s: gpio_tlmm_config is failed\n",__func__); gpio_free(vib->motor_en); return rc; } } vib->timeout = VIB_DEFAULT_TIMEOUT; INIT_WORK(&vib->work, msm_vibrator_update); mutex_init(&vib->lock); vib->queue = create_singlethread_workqueue("msm_vibrator"); if (!vib->queue) { pr_err("%s(): can't create workqueue\n", __func__); return -ENOMEM; } hrtimer_init(&vib->vib_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); vib->vib_timer.function = vibrator_timer_func; vib->timed_dev.name = "vibrator"; vib->timed_dev.get_time = vibrator_get_time; vib->timed_dev.enable = vibrator_enable; dev_set_drvdata(&pdev->dev, vib); rc = timed_output_dev_register(&vib->timed_dev); if (rc < 0) { pr_err("[VIB] timed_output_dev_register fail (rc=%d)\n", rc); goto err_read_vib; } return 0; err_read_vib: destroy_workqueue(vib->queue); return rc; } static int msm_vibrator_remove(struct platform_device *pdev) { struct msm_vib *vib = dev_get_drvdata(&pdev->dev); destroy_workqueue(vib->queue); mutex_destroy(&vib->lock); return 0; } static const struct of_device_id vib_motor_match[] = { { .compatible = "vibrator", }, {} }; static struct platform_driver msm_vibrator_platdrv = { .driver = { .name = "msm_vibrator", .owner = THIS_MODULE, .of_match_table = vib_motor_match, .pm = &vibrator_pm_ops, }, .probe = msm_vibrator_probe, .remove = __devexit_p(msm_vibrator_remove), }; static int __init msm_timed_vibrator_init(void) { pr_info("[VIB] %s\n",__func__); return platform_driver_register(&msm_vibrator_platdrv); } void __exit msm_timed_vibrator_exit(void) { platform_driver_unregister(&msm_vibrator_platdrv); } module_init(msm_timed_vibrator_init); module_exit(msm_timed_vibrator_exit); MODULE_DESCRIPTION("timed output vibrator device"); MODULE_LICENSE("GPL v2");
DirtyUnicorns/android_kernel_samsung_ks01lte
drivers/motor/msm_vibrator.c
C
gpl-2.0
5,789
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 1998, 1999 Frodo Looijaard <[email protected]> and * Philip Edelbrock <[email protected]> * Copyright (C) 2003 Greg Kroah-Hartman <[email protected]> * Copyright (C) 2003 IBM Corp. * Copyright (C) 2004 Jean Delvare <[email protected]> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/device.h> #include <linux/capability.h> #include <linux/jiffies.h> #include <linux/i2c.h> #include <linux/mutex.h> /* Addresses to scan */ static const unsigned short normal_i2c[] = { 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, I2C_CLIENT_END }; /* Size of EEPROM in bytes */ #define EEPROM_SIZE 256 /* possible types of eeprom devices */ enum eeprom_nature { UNKNOWN, VAIO, }; /* Each client has this additional data */ struct eeprom_data { struct mutex update_lock; u8 valid; /* bitfield, bit!=0 if slice is valid */ unsigned long last_updated[8]; /* In jiffies, 8 slices */ u8 data[EEPROM_SIZE]; /* Register values */ enum eeprom_nature nature; }; static void eeprom_update_client(struct i2c_client *client, u8 slice) { struct eeprom_data *data = i2c_get_clientdata(client); int i; mutex_lock(&data->update_lock); if (!(data->valid & (1 << slice)) || time_after(jiffies, data->last_updated[slice] + 300 * HZ)) { dev_dbg(&client->dev, "Starting eeprom update, slice %u\n", slice); if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK)) { for (i = slice << 5; i < (slice + 1) << 5; i += 32) if (i2c_smbus_read_i2c_block_data(client, i, 32, data->data + i) != 32) goto exit; } else { for (i = slice << 5; i < (slice + 1) << 5; i += 2) { int word = i2c_smbus_read_word_data(client, i); if (word < 0) goto exit; data->data[i] = word & 0xff; data->data[i + 1] = word >> 8; } } data->last_updated[slice] = jiffies; data->valid |= (1 << slice); } exit: mutex_unlock(&data->update_lock); } static ssize_t eeprom_read(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct i2c_client *client = to_i2c_client(kobj_to_dev(kobj)); struct eeprom_data *data = i2c_get_clientdata(client); u8 slice; /* Only refresh slices which contain requested bytes */ for (slice = off >> 5; slice <= (off + count - 1) >> 5; slice++) eeprom_update_client(client, slice); /* Hide Vaio private settings to regular users: - BIOS passwords: bytes 0x00 to 0x0f - UUID: bytes 0x10 to 0x1f - Serial number: 0xc0 to 0xdf */ if (data->nature == VAIO && !capable(CAP_SYS_ADMIN)) { int i; for (i = 0; i < count; i++) { if ((off + i <= 0x1f) || (off + i >= 0xc0 && off + i <= 0xdf)) buf[i] = 0; else buf[i] = data->data[off + i]; } } else { memcpy(buf, &data->data[off], count); } return count; } static const struct bin_attribute eeprom_attr = { .attr = { .name = "eeprom", .mode = S_IRUGO, }, .size = EEPROM_SIZE, .read = eeprom_read, }; /* Return 0 if detection is successful, -ENODEV otherwise */ static int eeprom_detect(struct i2c_client *client, struct i2c_board_info *info) { struct i2c_adapter *adapter = client->adapter; /* EDID EEPROMs are often 24C00 EEPROMs, which answer to all addresses 0x50-0x57, but we only care about 0x50. So decline attaching to addresses >= 0x51 on DDC buses */ if (!(adapter->class & I2C_CLASS_SPD) && client->addr >= 0x51) return -ENODEV; /* There are four ways we can read the EEPROM data: (1) I2C block reads (faster, but unsupported by most adapters) (2) Word reads (128% overhead) (3) Consecutive byte reads (88% overhead, unsafe) (4) Regular byte data reads (265% overhead) The third and fourth methods are not implemented by this driver because all known adapters support one of the first two. */ if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_READ_WORD_DATA) && !i2c_check_functionality(adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK)) return -ENODEV; strlcpy(info->type, "eeprom", I2C_NAME_SIZE); return 0; } static int eeprom_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct i2c_adapter *adapter = client->adapter; struct eeprom_data *data; data = devm_kzalloc(&client->dev, sizeof(struct eeprom_data), GFP_KERNEL); if (!data) return -ENOMEM; memset(data->data, 0xff, EEPROM_SIZE); i2c_set_clientdata(client, data); mutex_init(&data->update_lock); data->nature = UNKNOWN; /* Detect the Vaio nature of EEPROMs. We use the "PCG-" or "VGN-" prefix as the signature. */ if (client->addr == 0x57 && i2c_check_functionality(adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA)) { char name[4]; name[0] = i2c_smbus_read_byte_data(client, 0x80); name[1] = i2c_smbus_read_byte_data(client, 0x81); name[2] = i2c_smbus_read_byte_data(client, 0x82); name[3] = i2c_smbus_read_byte_data(client, 0x83); if (!memcmp(name, "PCG-", 4) || !memcmp(name, "VGN-", 4)) { dev_info(&client->dev, "Vaio EEPROM detected, " "enabling privacy protection\n"); data->nature = VAIO; } } /* Let the users know they are using deprecated driver */ dev_notice(&client->dev, "eeprom driver is deprecated, please use at24 instead\n"); /* create the sysfs eeprom file */ return sysfs_create_bin_file(&client->dev.kobj, &eeprom_attr); } static int eeprom_remove(struct i2c_client *client) { sysfs_remove_bin_file(&client->dev.kobj, &eeprom_attr); return 0; } static const struct i2c_device_id eeprom_id[] = { { "eeprom", 0 }, { } }; static struct i2c_driver eeprom_driver = { .driver = { .name = "eeprom", }, .probe = eeprom_probe, .remove = eeprom_remove, .id_table = eeprom_id, .class = I2C_CLASS_DDC | I2C_CLASS_SPD, .detect = eeprom_detect, .address_list = normal_i2c, }; module_i2c_driver(eeprom_driver); MODULE_AUTHOR("Frodo Looijaard <[email protected]> and " "Philip Edelbrock <[email protected]> and " "Greg Kroah-Hartman <[email protected]>"); MODULE_DESCRIPTION("I2C EEPROM driver"); MODULE_LICENSE("GPL");
CSE3320/kernel-code
linux-5.8/drivers/misc/eeprom/eeprom.c
C
gpl-2.0
6,110
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <EGL/egl.h> #include "base/command_line.h" #include "gpu/command_buffer/client/gles2_lib.h" #include "gpu/gles2_conform_support/egl/display.h" #include "ui/gl/gl_context.h" #include "ui/gl/gl_surface.h" #if REGAL_STATIC_EGL extern "C" { typedef EGLContext RegalSystemContext; #define REGAL_DECL REGAL_DECL void RegalMakeCurrent( RegalSystemContext ctx ); } // extern "C" #endif namespace { void SetCurrentError(EGLint error_code) { } template<typename T> T EglError(EGLint error_code, T return_value) { SetCurrentError(error_code); return return_value; } template<typename T> T EglSuccess(T return_value) { SetCurrentError(EGL_SUCCESS); return return_value; } EGLint ValidateDisplay(EGLDisplay dpy) { if (dpy == EGL_NO_DISPLAY) return EGL_BAD_DISPLAY; egl::Display* display = static_cast<egl::Display*>(dpy); if (!display->is_initialized()) return EGL_NOT_INITIALIZED; return EGL_SUCCESS; } EGLint ValidateDisplayConfig(EGLDisplay dpy, EGLConfig config) { EGLint error_code = ValidateDisplay(dpy); if (error_code != EGL_SUCCESS) return error_code; egl::Display* display = static_cast<egl::Display*>(dpy); if (!display->IsValidConfig(config)) return EGL_BAD_CONFIG; return EGL_SUCCESS; } EGLint ValidateDisplaySurface(EGLDisplay dpy, EGLSurface surface) { EGLint error_code = ValidateDisplay(dpy); if (error_code != EGL_SUCCESS) return error_code; egl::Display* display = static_cast<egl::Display*>(dpy); if (!display->IsValidSurface(surface)) return EGL_BAD_SURFACE; return EGL_SUCCESS; } EGLint ValidateDisplayContext(EGLDisplay dpy, EGLContext context) { EGLint error_code = ValidateDisplay(dpy); if (error_code != EGL_SUCCESS) return error_code; egl::Display* display = static_cast<egl::Display*>(dpy); if (!display->IsValidContext(context)) return EGL_BAD_CONTEXT; return EGL_SUCCESS; } } // namespace extern "C" { EGLint eglGetError() { // TODO(alokp): Fix me. return EGL_SUCCESS; } EGLDisplay eglGetDisplay(EGLNativeDisplayType display_id) { return new egl::Display(display_id); } EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor) { if (dpy == EGL_NO_DISPLAY) return EglError(EGL_BAD_DISPLAY, EGL_FALSE); egl::Display* display = static_cast<egl::Display*>(dpy); if (!display->Initialize()) return EglError(EGL_NOT_INITIALIZED, EGL_FALSE); int argc = 1; const char* const argv[] = { "dummy" }; CommandLine::Init(argc, argv); gfx::GLSurface::InitializeOneOff(); *major = 1; *minor = 4; return EglSuccess(EGL_TRUE); } EGLBoolean eglTerminate(EGLDisplay dpy) { EGLint error_code = ValidateDisplay(dpy); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_FALSE); egl::Display* display = static_cast<egl::Display*>(dpy); delete display; return EglSuccess(EGL_TRUE); } const char* eglQueryString(EGLDisplay dpy, EGLint name) { EGLint error_code = ValidateDisplay(dpy); if (error_code != EGL_SUCCESS) return EglError(error_code, static_cast<const char*>(NULL)); switch (name) { case EGL_CLIENT_APIS: return EglSuccess("OpenGL_ES"); case EGL_EXTENSIONS: return EglSuccess(""); case EGL_VENDOR: return EglSuccess("Google Inc."); case EGL_VERSION: return EglSuccess("1.4"); default: return EglError(EGL_BAD_PARAMETER, static_cast<const char*>(NULL)); } } EGLBoolean eglChooseConfig(EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs, EGLint config_size, EGLint* num_config) { EGLint error_code = ValidateDisplay(dpy); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_FALSE); if (num_config == NULL) return EglError(EGL_BAD_PARAMETER, EGL_FALSE); egl::Display* display = static_cast<egl::Display*>(dpy); if (!display->ChooseConfigs(configs, config_size, num_config)) return EglError(EGL_BAD_ATTRIBUTE, EGL_FALSE); return EglSuccess(EGL_TRUE); } EGLBoolean eglGetConfigs(EGLDisplay dpy, EGLConfig* configs, EGLint config_size, EGLint* num_config) { EGLint error_code = ValidateDisplay(dpy); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_FALSE); if (num_config == NULL) return EglError(EGL_BAD_PARAMETER, EGL_FALSE); egl::Display* display = static_cast<egl::Display*>(dpy); if (!display->GetConfigs(configs, config_size, num_config)) return EglError(EGL_BAD_ATTRIBUTE, EGL_FALSE); return EglSuccess(EGL_TRUE); } EGLBoolean eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint* value) { EGLint error_code = ValidateDisplayConfig(dpy, config); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_FALSE); egl::Display* display = static_cast<egl::Display*>(dpy); if (!display->GetConfigAttrib(config, attribute, value)) return EglError(EGL_BAD_ATTRIBUTE, EGL_FALSE); return EglSuccess(EGL_TRUE); } EGLSurface eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint* attrib_list) { EGLint error_code = ValidateDisplayConfig(dpy, config); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_NO_SURFACE); egl::Display* display = static_cast<egl::Display*>(dpy); if (!display->IsValidNativeWindow(win)) return EglError(EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE); EGLSurface surface = display->CreateWindowSurface(config, win, attrib_list); if (surface == EGL_NO_SURFACE) return EglError(EGL_BAD_ALLOC, EGL_NO_SURFACE); return EglSuccess(surface); } EGLSurface eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint* attrib_list) { return EGL_NO_SURFACE; } EGLSurface eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint* attrib_list) { return EGL_NO_SURFACE; } EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface surface) { EGLint error_code = ValidateDisplaySurface(dpy, surface); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_FALSE); egl::Display* display = static_cast<egl::Display*>(dpy); display->DestroySurface(surface); return EglSuccess(EGL_TRUE); } EGLBoolean eglQuerySurface(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint* value) { return EGL_FALSE; } EGLBoolean eglBindAPI(EGLenum api) { return EGL_FALSE; } EGLenum eglQueryAPI() { return EGL_OPENGL_ES_API; } EGLBoolean eglWaitClient(void) { return EGL_FALSE; } EGLBoolean eglReleaseThread(void) { return EGL_FALSE; } EGLSurface eglCreatePbufferFromClientBuffer(EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint* attrib_list) { return EGL_NO_SURFACE; } EGLBoolean eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value) { return EGL_FALSE; } EGLBoolean eglBindTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer) { return EGL_FALSE; } EGLBoolean eglReleaseTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer) { return EGL_FALSE; } EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval) { return EGL_FALSE; } EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint* attrib_list) { EGLint error_code = ValidateDisplayConfig(dpy, config); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_NO_CONTEXT); if (share_context != EGL_NO_CONTEXT) { error_code = ValidateDisplayContext(dpy, share_context); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_NO_CONTEXT); } egl::Display* display = static_cast<egl::Display*>(dpy); EGLContext context = display->CreateContext( config, share_context, attrib_list); if (context == EGL_NO_CONTEXT) return EglError(EGL_BAD_ALLOC, EGL_NO_CONTEXT); return EglSuccess(context); } EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx) { EGLint error_code = ValidateDisplayContext(dpy, ctx); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_FALSE); egl::Display* display = static_cast<egl::Display*>(dpy); display->DestroyContext(ctx); return EGL_TRUE; } EGLBoolean eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) { if (ctx != EGL_NO_CONTEXT) { EGLint error_code = ValidateDisplaySurface(dpy, draw); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_FALSE); error_code = ValidateDisplaySurface(dpy, read); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_FALSE); error_code = ValidateDisplayContext(dpy, ctx); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_FALSE); } egl::Display* display = static_cast<egl::Display*>(dpy); if (!display->MakeCurrent(draw, read, ctx)) return EglError(EGL_CONTEXT_LOST, EGL_FALSE); #if REGAL_STATIC_EGL RegalMakeCurrent(ctx); #endif return EGL_TRUE; } EGLContext eglGetCurrentContext() { return EGL_NO_CONTEXT; } EGLSurface eglGetCurrentSurface(EGLint readdraw) { return EGL_NO_SURFACE; } EGLDisplay eglGetCurrentDisplay() { return EGL_NO_DISPLAY; } EGLBoolean eglQueryContext(EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint* value) { return EGL_FALSE; } EGLBoolean eglWaitGL() { return EGL_FALSE; } EGLBoolean eglWaitNative(EGLint engine) { return EGL_FALSE; } EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface surface) { EGLint error_code = ValidateDisplaySurface(dpy, surface); if (error_code != EGL_SUCCESS) return EglError(error_code, EGL_FALSE); egl::Display* display = static_cast<egl::Display*>(dpy); display->SwapBuffers(surface); return EglSuccess(EGL_TRUE); } EGLBoolean eglCopyBuffers(EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target) { return EGL_FALSE; } /* Now, define eglGetProcAddress using the generic function ptr. type */ __eglMustCastToProperFunctionPointerType eglGetProcAddress(const char* procname) { return gles2::GetGLFunctionPointer(procname); } } // extern "C"
plxaye/chromium
src/gpu/gles2_conform_support/egl/egl.cc
C++
apache-2.0
11,483
/* * Linux network driver for QLogic BR-series Converged Network Adapter. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License (GPL) 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. */ /* * Copyright (c) 2005-2014 Brocade Communications Systems, Inc. * Copyright (c) 2014-2015 QLogic Corporation * All rights reserved * www.qlogic.com */ #include "bfa_cee.h" #include "bfi_cna.h" #include "bfa_ioc.h" static void bfa_cee_format_lldp_cfg(struct bfa_cee_lldp_cfg *lldp_cfg); static void bfa_cee_format_cee_cfg(void *buffer); static void bfa_cee_format_cee_cfg(void *buffer) { struct bfa_cee_attr *cee_cfg = buffer; bfa_cee_format_lldp_cfg(&cee_cfg->lldp_remote); } static void bfa_cee_stats_swap(struct bfa_cee_stats *stats) { u32 *buffer = (u32 *)stats; int i; for (i = 0; i < (sizeof(struct bfa_cee_stats) / sizeof(u32)); i++) { buffer[i] = ntohl(buffer[i]); } } static void bfa_cee_format_lldp_cfg(struct bfa_cee_lldp_cfg *lldp_cfg) { lldp_cfg->time_to_live = ntohs(lldp_cfg->time_to_live); lldp_cfg->enabled_system_cap = ntohs(lldp_cfg->enabled_system_cap); } /** * bfa_cee_attr_meminfo - Returns the size of the DMA memory needed by CEE attributes */ static u32 bfa_cee_attr_meminfo(void) { return roundup(sizeof(struct bfa_cee_attr), BFA_DMA_ALIGN_SZ); } /** * bfa_cee_stats_meminfo - Returns the size of the DMA memory needed by CEE stats */ static u32 bfa_cee_stats_meminfo(void) { return roundup(sizeof(struct bfa_cee_stats), BFA_DMA_ALIGN_SZ); } /** * bfa_cee_get_attr_isr - CEE ISR for get-attributes responses from f/w * * @cee: Pointer to the CEE module * @status: Return status from the f/w */ static void bfa_cee_get_attr_isr(struct bfa_cee *cee, enum bfa_status status) { cee->get_attr_status = status; if (status == BFA_STATUS_OK) { memcpy(cee->attr, cee->attr_dma.kva, sizeof(struct bfa_cee_attr)); bfa_cee_format_cee_cfg(cee->attr); } cee->get_attr_pending = false; if (cee->cbfn.get_attr_cbfn) cee->cbfn.get_attr_cbfn(cee->cbfn.get_attr_cbarg, status); } /** * bfa_cee_get_attr_isr - CEE ISR for get-stats responses from f/w * * @cee: Pointer to the CEE module * @status: Return status from the f/w */ static void bfa_cee_get_stats_isr(struct bfa_cee *cee, enum bfa_status status) { cee->get_stats_status = status; if (status == BFA_STATUS_OK) { memcpy(cee->stats, cee->stats_dma.kva, sizeof(struct bfa_cee_stats)); bfa_cee_stats_swap(cee->stats); } cee->get_stats_pending = false; if (cee->cbfn.get_stats_cbfn) cee->cbfn.get_stats_cbfn(cee->cbfn.get_stats_cbarg, status); } /** * bfa_cee_get_attr_isr() * * @brief CEE ISR for reset-stats responses from f/w * * @param[in] cee - Pointer to the CEE module * status - Return status from the f/w * * @return void */ static void bfa_cee_reset_stats_isr(struct bfa_cee *cee, enum bfa_status status) { cee->reset_stats_status = status; cee->reset_stats_pending = false; if (cee->cbfn.reset_stats_cbfn) cee->cbfn.reset_stats_cbfn(cee->cbfn.reset_stats_cbarg, status); } /** * bfa_nw_cee_meminfo - Returns the size of the DMA memory needed by CEE module */ u32 bfa_nw_cee_meminfo(void) { return bfa_cee_attr_meminfo() + bfa_cee_stats_meminfo(); } /** * bfa_nw_cee_mem_claim - Initialized CEE DMA Memory * * @cee: CEE module pointer * @dma_kva: Kernel Virtual Address of CEE DMA Memory * @dma_pa: Physical Address of CEE DMA Memory */ void bfa_nw_cee_mem_claim(struct bfa_cee *cee, u8 *dma_kva, u64 dma_pa) { cee->attr_dma.kva = dma_kva; cee->attr_dma.pa = dma_pa; cee->stats_dma.kva = dma_kva + bfa_cee_attr_meminfo(); cee->stats_dma.pa = dma_pa + bfa_cee_attr_meminfo(); cee->attr = (struct bfa_cee_attr *) dma_kva; cee->stats = (struct bfa_cee_stats *) (dma_kva + bfa_cee_attr_meminfo()); } /** * bfa_cee_get_attr - Send the request to the f/w to fetch CEE attributes. * * @cee: Pointer to the CEE module data structure. * * Return: status */ enum bfa_status bfa_nw_cee_get_attr(struct bfa_cee *cee, struct bfa_cee_attr *attr, bfa_cee_get_attr_cbfn_t cbfn, void *cbarg) { struct bfi_cee_get_req *cmd; BUG_ON(!((cee != NULL) && (cee->ioc != NULL))); if (!bfa_nw_ioc_is_operational(cee->ioc)) return BFA_STATUS_IOC_FAILURE; if (cee->get_attr_pending) return BFA_STATUS_DEVBUSY; cee->get_attr_pending = true; cmd = (struct bfi_cee_get_req *) cee->get_cfg_mb.msg; cee->attr = attr; cee->cbfn.get_attr_cbfn = cbfn; cee->cbfn.get_attr_cbarg = cbarg; bfi_h2i_set(cmd->mh, BFI_MC_CEE, BFI_CEE_H2I_GET_CFG_REQ, bfa_ioc_portid(cee->ioc)); bfa_dma_be_addr_set(cmd->dma_addr, cee->attr_dma.pa); bfa_nw_ioc_mbox_queue(cee->ioc, &cee->get_cfg_mb, NULL, NULL); return BFA_STATUS_OK; } /** * bfa_cee_isrs - Handles Mail-box interrupts for CEE module. */ static void bfa_cee_isr(void *cbarg, struct bfi_mbmsg *m) { union bfi_cee_i2h_msg_u *msg; struct bfi_cee_get_rsp *get_rsp; struct bfa_cee *cee = (struct bfa_cee *) cbarg; msg = (union bfi_cee_i2h_msg_u *) m; get_rsp = (struct bfi_cee_get_rsp *) m; switch (msg->mh.msg_id) { case BFI_CEE_I2H_GET_CFG_RSP: bfa_cee_get_attr_isr(cee, get_rsp->cmd_status); break; case BFI_CEE_I2H_GET_STATS_RSP: bfa_cee_get_stats_isr(cee, get_rsp->cmd_status); break; case BFI_CEE_I2H_RESET_STATS_RSP: bfa_cee_reset_stats_isr(cee, get_rsp->cmd_status); break; default: BUG_ON(1); } } /** * bfa_cee_notify - CEE module heart-beat failure handler. * * @event: IOC event type */ static void bfa_cee_notify(void *arg, enum bfa_ioc_event event) { struct bfa_cee *cee; cee = (struct bfa_cee *) arg; switch (event) { case BFA_IOC_E_DISABLED: case BFA_IOC_E_FAILED: if (cee->get_attr_pending) { cee->get_attr_status = BFA_STATUS_FAILED; cee->get_attr_pending = false; if (cee->cbfn.get_attr_cbfn) { cee->cbfn.get_attr_cbfn( cee->cbfn.get_attr_cbarg, BFA_STATUS_FAILED); } } if (cee->get_stats_pending) { cee->get_stats_status = BFA_STATUS_FAILED; cee->get_stats_pending = false; if (cee->cbfn.get_stats_cbfn) { cee->cbfn.get_stats_cbfn( cee->cbfn.get_stats_cbarg, BFA_STATUS_FAILED); } } if (cee->reset_stats_pending) { cee->reset_stats_status = BFA_STATUS_FAILED; cee->reset_stats_pending = false; if (cee->cbfn.reset_stats_cbfn) { cee->cbfn.reset_stats_cbfn( cee->cbfn.reset_stats_cbarg, BFA_STATUS_FAILED); } } break; default: break; } } /** * bfa_nw_cee_attach - CEE module-attach API * * @cee: Pointer to the CEE module data structure * @ioc: Pointer to the ioc module data structure * @dev: Pointer to the device driver module data structure. * The device driver specific mbox ISR functions have * this pointer as one of the parameters. */ void bfa_nw_cee_attach(struct bfa_cee *cee, struct bfa_ioc *ioc, void *dev) { BUG_ON(!(cee != NULL)); cee->dev = dev; cee->ioc = ioc; bfa_nw_ioc_mbox_regisr(cee->ioc, BFI_MC_CEE, bfa_cee_isr, cee); bfa_ioc_notify_init(&cee->ioc_notify, bfa_cee_notify, cee); bfa_nw_ioc_notify_register(cee->ioc, &cee->ioc_notify); }
AiJiaZone/linux-4.0
virt/drivers/net/ethernet/brocade/bna/bfa_cee.c
C
gpl-2.0
7,407
var Fiber = require('fibers'); var ii; var fn = Fiber(function() { for (ii = 0; ii < 1000; ++ii) { try { Fiber.yield(); } catch (err) {} } }); fn.run(); fn.reset(); ii === 1000 && console.log('pass');
moyalco/littleb
wrappers/nbind/node_modules/fibers/test/unwind.js
JavaScript
mit
212
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2014-2017, The Linux Foundation. All rights reserved. * Copyright (c) 2017, Linaro Ltd. */ #include <linux/completion.h> #include <linux/module.h> #include <linux/notifier.h> #include <linux/rpmsg.h> #include <linux/remoteproc/qcom_rproc.h> /** * struct do_cleanup_msg - The data structure for an SSR do_cleanup message * version: The G-Link SSR protocol version * command: The G-Link SSR command - do_cleanup * seq_num: Sequence number * name_len: Length of the name of the subsystem being restarted * name: G-Link edge name of the subsystem being restarted */ struct do_cleanup_msg { __le32 version; __le32 command; __le32 seq_num; __le32 name_len; char name[32]; }; /** * struct cleanup_done_msg - The data structure for an SSR cleanup_done message * version: The G-Link SSR protocol version * response: The G-Link SSR response to a do_cleanup command, cleanup_done * seq_num: Sequence number */ struct cleanup_done_msg { __le32 version; __le32 response; __le32 seq_num; }; /** * G-Link SSR protocol commands */ #define GLINK_SSR_DO_CLEANUP 0 #define GLINK_SSR_CLEANUP_DONE 1 struct glink_ssr { struct device *dev; struct rpmsg_endpoint *ept; struct notifier_block nb; u32 seq_num; struct completion completion; }; /* Notifier list for all registered glink_ssr instances */ static BLOCKING_NOTIFIER_HEAD(ssr_notifiers); /** * qcom_glink_ssr_notify() - notify GLINK SSR about stopped remoteproc * @ssr_name: name of the remoteproc that has been stopped */ void qcom_glink_ssr_notify(const char *ssr_name) { blocking_notifier_call_chain(&ssr_notifiers, 0, (void *)ssr_name); } EXPORT_SYMBOL_GPL(qcom_glink_ssr_notify); static int qcom_glink_ssr_callback(struct rpmsg_device *rpdev, void *data, int len, void *priv, u32 addr) { struct cleanup_done_msg *msg = data; struct glink_ssr *ssr = dev_get_drvdata(&rpdev->dev); if (len < sizeof(*msg)) { dev_err(ssr->dev, "message too short\n"); return -EINVAL; } if (le32_to_cpu(msg->version) != 0) return -EINVAL; if (le32_to_cpu(msg->response) != GLINK_SSR_CLEANUP_DONE) return 0; if (le32_to_cpu(msg->seq_num) != ssr->seq_num) { dev_err(ssr->dev, "invalid sequence number of response\n"); return -EINVAL; } complete(&ssr->completion); return 0; } static int qcom_glink_ssr_notifier_call(struct notifier_block *nb, unsigned long event, void *data) { struct glink_ssr *ssr = container_of(nb, struct glink_ssr, nb); struct do_cleanup_msg msg; char *ssr_name = data; int ret; ssr->seq_num++; reinit_completion(&ssr->completion); memset(&msg, 0, sizeof(msg)); msg.command = cpu_to_le32(GLINK_SSR_DO_CLEANUP); msg.seq_num = cpu_to_le32(ssr->seq_num); msg.name_len = cpu_to_le32(strlen(ssr_name)); strlcpy(msg.name, ssr_name, sizeof(msg.name)); ret = rpmsg_send(ssr->ept, &msg, sizeof(msg)); if (ret < 0) dev_err(ssr->dev, "failed to send cleanup message\n"); ret = wait_for_completion_timeout(&ssr->completion, HZ); if (!ret) dev_err(ssr->dev, "timeout waiting for cleanup done message\n"); return NOTIFY_DONE; } static int qcom_glink_ssr_probe(struct rpmsg_device *rpdev) { struct glink_ssr *ssr; ssr = devm_kzalloc(&rpdev->dev, sizeof(*ssr), GFP_KERNEL); if (!ssr) return -ENOMEM; init_completion(&ssr->completion); ssr->dev = &rpdev->dev; ssr->ept = rpdev->ept; ssr->nb.notifier_call = qcom_glink_ssr_notifier_call; dev_set_drvdata(&rpdev->dev, ssr); return blocking_notifier_chain_register(&ssr_notifiers, &ssr->nb); } static void qcom_glink_ssr_remove(struct rpmsg_device *rpdev) { struct glink_ssr *ssr = dev_get_drvdata(&rpdev->dev); blocking_notifier_chain_unregister(&ssr_notifiers, &ssr->nb); } static const struct rpmsg_device_id qcom_glink_ssr_match[] = { { "glink_ssr" }, {} }; static struct rpmsg_driver qcom_glink_ssr_driver = { .probe = qcom_glink_ssr_probe, .remove = qcom_glink_ssr_remove, .callback = qcom_glink_ssr_callback, .id_table = qcom_glink_ssr_match, .drv = { .name = "qcom_glink_ssr", }, }; module_rpmsg_driver(qcom_glink_ssr_driver);
CSE3320/kernel-code
linux-5.8/drivers/rpmsg/qcom_glink_ssr.c
C
gpl-2.0
4,144
var fs = require('graceful-fs') var path = require('path') var mkdirp = require('mkdirp') var osenv = require('osenv') var rimraf = require('rimraf') var test = require('tap').test var common = require('../common-tap.js') var pkg = path.join(__dirname, 'install-at-locally') var EXEC_OPTS = { cwd: pkg } var json = { name: 'install-at-locally', version: '0.0.0' } test('setup', function (t) { cleanup() t.end() }) test('\'npm install ./[email protected]\' should install local pkg', function (t) { var target = './[email protected]' setup(target) common.npm(['install', target], EXEC_OPTS, function (err, code) { var p = path.resolve(pkg, 'node_modules/install-at-locally/package.json') t.ifError(err, 'install local package successful') t.equal(code, 0, 'npm install exited with code') t.ok(JSON.parse(fs.readFileSync(p, 'utf8'))) t.end() }) }) test('\'npm install install/at/locally@./[email protected]\' should install local pkg', function (t) { var target = 'install/at/locally@./[email protected]' setup(target) common.npm(['install', target], EXEC_OPTS, function (err, code) { var p = path.resolve(pkg, 'node_modules/install-at-locally/package.json') t.ifError(err, 'install local package in explicit directory successful') t.equal(code, 0, 'npm install exited with code') t.ok(JSON.parse(fs.readFileSync(p, 'utf8'))) t.end() }) }) test('cleanup', function (t) { cleanup() t.end() }) function cleanup () { process.chdir(osenv.tmpdir()) rimraf.sync(pkg) } function setup (target) { cleanup() var root = path.resolve(pkg, target) mkdirp.sync(root) fs.writeFileSync( path.join(root, 'package.json'), JSON.stringify(json, null, 2) ) mkdirp.sync(path.resolve(pkg, 'node_modules')) process.chdir(pkg) }
markredballoon/clivemizen
wp-content/themes/redballoon/bootstrap/npm/test/tap/install-at-locally.js
JavaScript
gpl-2.0
1,792
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var stylesInDom = {}, memoize = function(fn) { var memo; return function () { if (typeof memo === "undefined") memo = fn.apply(this, arguments); return memo; }; }, isOldIE = memoize(function() { return /msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase()); }), getHeadElement = memoize(function () { return document.head || document.getElementsByTagName("head")[0]; }), singletonElement = null, singletonCounter = 0, styleElementsInsertedAtTop = []; module.exports = function(list, options) { if(typeof DEBUG !== "undefined" && DEBUG) { if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment"); } options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page if (typeof options.singleton === "undefined") options.singleton = isOldIE(); // By default, add <style> tags to the bottom of <head>. if (typeof options.insertAt === "undefined") options.insertAt = "bottom"; var styles = listToStyles(list); addStylesToDom(styles, options); return function update(newList) { var mayRemove = []; for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; domStyle.refs--; mayRemove.push(domStyle); } if(newList) { var newStyles = listToStyles(newList); addStylesToDom(newStyles, options); } for(var i = 0; i < mayRemove.length; i++) { var domStyle = mayRemove[i]; if(domStyle.refs === 0) { for(var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j](); delete stylesInDom[domStyle.id]; } } }; } function addStylesToDom(styles, options) { for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; if(domStyle) { domStyle.refs++; for(var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j](item.parts[j]); } for(; j < item.parts.length; j++) { domStyle.parts.push(addStyle(item.parts[j], options)); } } else { var parts = []; for(var j = 0; j < item.parts.length; j++) { parts.push(addStyle(item.parts[j], options)); } stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts}; } } } function listToStyles(list) { var styles = []; var newStyles = {}; for(var i = 0; i < list.length; i++) { var item = list[i]; var id = item[0]; var css = item[1]; var media = item[2]; var sourceMap = item[3]; var part = {css: css, media: media, sourceMap: sourceMap}; if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]}); else newStyles[id].parts.push(part); } return styles; } function insertStyleElement(options, styleElement) { var head = getHeadElement(); var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1]; if (options.insertAt === "top") { if(!lastStyleElementInsertedAtTop) { head.insertBefore(styleElement, head.firstChild); } else if(lastStyleElementInsertedAtTop.nextSibling) { head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling); } else { head.appendChild(styleElement); } styleElementsInsertedAtTop.push(styleElement); } else if (options.insertAt === "bottom") { head.appendChild(styleElement); } else { throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'."); } } function removeStyleElement(styleElement) { styleElement.parentNode.removeChild(styleElement); var idx = styleElementsInsertedAtTop.indexOf(styleElement); if(idx >= 0) { styleElementsInsertedAtTop.splice(idx, 1); } } function createStyleElement(options) { var styleElement = document.createElement("style"); styleElement.type = "text/css"; insertStyleElement(options, styleElement); return styleElement; } function createLinkElement(options) { var linkElement = document.createElement("link"); linkElement.rel = "stylesheet"; insertStyleElement(options, linkElement); return linkElement; } function addStyle(obj, options) { var styleElement, update, remove; if (options.singleton) { var styleIndex = singletonCounter++; styleElement = singletonElement || (singletonElement = createStyleElement(options)); update = applyToSingletonTag.bind(null, styleElement, styleIndex, false); remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true); } else if(obj.sourceMap && typeof URL === "function" && typeof URL.createObjectURL === "function" && typeof URL.revokeObjectURL === "function" && typeof Blob === "function" && typeof btoa === "function") { styleElement = createLinkElement(options); update = updateLink.bind(null, styleElement); remove = function() { removeStyleElement(styleElement); if(styleElement.href) URL.revokeObjectURL(styleElement.href); }; } else { styleElement = createStyleElement(options); update = applyToTag.bind(null, styleElement); remove = function() { removeStyleElement(styleElement); }; } update(obj); return function updateStyle(newObj) { if(newObj) { if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) return; update(obj = newObj); } else { remove(); } }; } var replaceText = (function () { var textStore = []; return function (index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; })(); function applyToSingletonTag(styleElement, index, remove, obj) { var css = remove ? "" : obj.css; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = styleElement.childNodes; if (childNodes[index]) styleElement.removeChild(childNodes[index]); if (childNodes.length) { styleElement.insertBefore(cssNode, childNodes[index]); } else { styleElement.appendChild(cssNode); } } } function applyToTag(styleElement, obj) { var css = obj.css; var media = obj.media; if(media) { styleElement.setAttribute("media", media) } if(styleElement.styleSheet) { styleElement.styleSheet.cssText = css; } else { while(styleElement.firstChild) { styleElement.removeChild(styleElement.firstChild); } styleElement.appendChild(document.createTextNode(css)); } } function updateLink(linkElement, obj) { var css = obj.css; var sourceMap = obj.sourceMap; if(sourceMap) { // http://stackoverflow.com/a/26603875 css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */"; } var blob = new Blob([css], { type: "text/css" }); var oldSrc = linkElement.href; linkElement.href = URL.createObjectURL(blob); if(oldSrc) URL.revokeObjectURL(oldSrc); }
mo-norant/FinHeartBel
website/node_modules/style-loader/addStyles.js
JavaScript
gpl-3.0
6,906
// Copyright (c) 2016 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache License, Version 2.0 (the "License"). // You may not use this product except in compliance with the License. // // This product may include a number of subcomponents with separate copyright notices and // license terms. Your use of these subcomponents is subject to the terms and conditions // of the subcomponent's license, as noted in the LICENSE file. package photon import ( "encoding/json" "time" ) // Contains functionality for tasks API. type TasksAPI struct { client *Client } var taskUrl string = rootUrl + "/tasks" // Gets a task by ID. func (api *TasksAPI) Get(id string) (task *Task, err error) { res, err := api.client.restClient.Get(api.client.Endpoint+taskUrl+"/"+id, api.client.options.TokenOptions) if err != nil { return } defer res.Body.Close() result, err := getTask(getError(res)) return result, err } // Gets all tasks, using options to filter the results. // If options is nil, no filtering will occur. func (api *TasksAPI) GetAll(options *TaskGetOptions) (result *TaskList, err error) { uri := api.client.Endpoint + taskUrl if options != nil { uri += getQueryString(options) } res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions) if err != nil { return } result = &TaskList{} err = json.Unmarshal(res, result) return } // Waits for a task to complete by polling the tasks API until a task returns with // the state COMPLETED or ERROR. Will wait no longer than the duration specified by timeout. func (api *TasksAPI) WaitTimeout(id string, timeout time.Duration) (task *Task, err error) { start := time.Now() numErrors := 0 maxErrors := api.client.options.TaskRetryCount for time.Since(start) < timeout { task, err = api.Get(id) if err != nil { switch err.(type) { // If an ApiError comes back, something is wrong, return the error to the caller case ApiError: return // For other errors, retry before giving up default: numErrors++ if numErrors > maxErrors { return } } } else { // Reset the error count any time a successful call is made numErrors = 0 if task.State == "COMPLETED" { return } if task.State == "ERROR" { err = TaskError{task.ID, getFailedStep(task)} return } } time.Sleep(api.client.options.TaskPollDelay) } err = TaskTimeoutError{id} return } // Waits for a task to complete by polling the tasks API until a task returns with // the state COMPLETED or ERROR. func (api *TasksAPI) Wait(id string) (task *Task, err error) { return api.WaitTimeout(id, api.client.options.TaskPollTimeout) } // Gets the failed step in the task to get error details for failed task. func getFailedStep(task *Task) (step Step) { var errorStep Step for _, s := range task.Steps { if s.State == "ERROR" { errorStep = s break } } return errorStep }
kgrygiel/autoscaler
vertical-pod-autoscaler/vendor/github.com/vmware/photon-controller-go-sdk/photon/tasks.go
GO
apache-2.0
2,961
<?php # # Markdown Extra - A text-to-HTML conversion tool for web writers # # PHP Markdown & Extra # Copyright (c) 2004-2012 Michel Fortin # <http://michelf.com/projects/php-markdown/> # # Original Markdown # Copyright (c) 2004-2006 John Gruber # <http://daringfireball.net/projects/markdown/> # # # Markdown Parser Class # class Markdown_Parser { # Regex to match balanced [brackets]. # Needed to insert a maximum bracked depth while converting to PHP. public $nested_brackets_depth = 6; public $nested_brackets_re; public $nested_url_parenthesis_depth = 4; public $nested_url_parenthesis_re; # Table of hash values for escaped characters: public $escape_chars = '\`*_{}[]()>#+-.!'; public $escape_chars_re; # Change to ">" for HTML output. public $empty_element_suffix = ' />'; public $tab_width = 4; # Change to `true` to disallow markup or entities. public $no_markup = false; public $no_entities = false; # Predefined urls and titles for reference links and images. public $predef_urls = array(); public $predef_titles = array(); public function __construct() { # # Constructor function. Initialize appropriate member variables. # $this->_initDetab(); $this->prepareItalicsAndBold(); $this->nested_brackets_re = str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth). str_repeat('\])*', $this->nested_brackets_depth); $this->nested_url_parenthesis_re = str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth). str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth); $this->escape_chars_re = '['.preg_quote($this->escape_chars).']'; # Sort document, block, and span gamut in ascendent priority order. asort($this->document_gamut); asort($this->block_gamut); asort($this->span_gamut); } # Internal hashes used during transformation. public $urls = array(); public $titles = array(); public $html_hashes = array(); # Status flag to avoid invalid nesting. public $in_anchor = false; public function setup() { # # Called before the transformation process starts to setup parser # states. # # Clear global hashes. $this->urls = $this->predef_urls; $this->titles = $this->predef_titles; $this->html_hashes = array(); $in_anchor = false; } public function teardown() { # # Called after the transformation process to clear any variable # which may be taking up memory unnecessarly. # $this->urls = array(); $this->titles = array(); $this->html_hashes = array(); } public function transform($text) { # # Main function. Performs some preprocessing on the input text # and pass it through the document gamut. # $this->setup(); # Remove UTF-8 BOM and marker character in input, if present. $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text); # Standardize line endings: # DOS to Unix and Mac to Unix $text = preg_replace('{\r\n?}', "\n", $text); # Make sure $text ends with a couple of newlines: $text .= "\n\n"; # Convert all tabs to spaces. $text = $this->detab($text); # Turn block-level HTML blocks into hash entries $text = $this->hashHTMLBlocks($text); # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ ]*\n+/ . $text = preg_replace('/^[ ]+$/m', '', $text); # Run document gamut methods. foreach ($this->document_gamut as $method => $priority) { $text = $this->$method($text); } $this->teardown(); return $text . "\n"; } public $document_gamut = array( # Strip link definitions, store in hashes. "stripLinkDefinitions" => 20, "runBasicBlockGamut" => 30, ); public function stripLinkDefinitions($text) { # # Strips link definitions from text, stores the URLs and titles in # hash references. # $less_than_tab = $this->tab_width - 1; # Link defs are in the form: ^[id]: url "optional title" $text = preg_replace_callback('{ ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 [ ]* \n? # maybe *one* newline [ ]* (?: <(.+?)> # url = $2 | (\S+?) # url = $3 ) [ ]* \n? # maybe one newline [ ]* (?: (?<=\s) # lookbehind for whitespace ["(] (.*?) # title = $4 [")] [ ]* )? # title is optional (?:\n+|\Z) }xm', array(&$this, '_stripLinkDefinitions_callback'), $text); return $text; } public function _stripLinkDefinitions_callback($matches) { $link_id = strtolower($matches[1]); $url = $matches[2] == '' ? $matches[3] : $matches[2]; $this->urls[$link_id] = $url; $this->titles[$link_id] =& $matches[4]; return ''; # String that will replace the block } public function hashHTMLBlocks($text) { if ($this->no_markup) return $text; $less_than_tab = $this->tab_width - 1; # Hashify HTML blocks: # We only want to do this for block-level HTML tags, such as headers, # lists, and tables. That's because we still want to wrap <p>s around # "paragraphs" that are wrapped in non-block-level tags, such as anchors, # phrase emphasis, and spans. The list of tags we're looking for is # hard-coded: # # * List "a" is made of tags which can be both inline or block-level. # These will be treated block-level when the start tag is alone on # its line, otherwise they're not matched here and will be taken as # inline later. # * List "b" is made of tags which are always block-level; # $block_tags_a_re = 'ins|del'; $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. 'script|noscript|form|fieldset|iframe|math'; # Regular expression for the content of a block tag. $nested_tags_level = 4; $attr = ' (?> # optional tag attributes \s # starts with whitespace (?> [^>"/]+ # text outside quotes | /+(?!>) # slash not followed by ">" | "[^"]*" # text inside double quotes (tolerate ">") | \'[^\']*\' # text inside single quotes (tolerate ">") )* )? '; $content = str_repeat(' (?> [^<]+ # content without tag | <\2 # nested opening tag '.$attr.' # attributes (?> /> | >', $nested_tags_level). # end of opening tag '.*?'. # last level nested tag content str_repeat(' </\2\s*> # closing nested tag ) | <(?!/\2\s*> # other tags with a different name ) )*', $nested_tags_level); $content2 = str_replace('\2', '\3', $content); # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. $text = preg_replace_callback('{(?> (?> (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in $1 # Match from `\n<tag>` to `</tag>\n`, handling nested tags # in between. [ ]{0,'.$less_than_tab.'} <('.$block_tags_b_re.')# start tag = $2 '.$attr.'> # attributes followed by > and \n '.$content.' # content, support nesting </\2> # the matching end tag [ ]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document | # Special version for tags of group a. [ ]{0,'.$less_than_tab.'} <('.$block_tags_a_re.')# start tag = $3 '.$attr.'>[ ]*\n # attributes followed by > '.$content2.' # content, support nesting </\3> # the matching end tag [ ]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document | # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. [ ]{0,'.$less_than_tab.'} <(hr) # start tag = $2 '.$attr.' # attributes /?> # the matching end tag [ ]* (?=\n{2,}|\Z) # followed by a blank line or end of document | # Special case for standalone HTML comments: [ ]{0,'.$less_than_tab.'} (?s: <!-- .*? --> ) [ ]* (?=\n{2,}|\Z) # followed by a blank line or end of document | # PHP and ASP-style processor instructions (<? and <%) [ ]{0,'.$less_than_tab.'} (?s: <([?%]) # $2 .*? \2> ) [ ]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) )}Sxmi', array(&$this, '_hashHTMLBlocks_callback'), $text); return $text; } public function _hashHTMLBlocks_callback($matches) { $text = $matches[1]; $key = $this->hashBlock($text); return "\n\n$key\n\n"; } public function hashPart($text, $boundary = 'X') { # # Called whenever a tag must be hashed when a function insert an atomic # element in the text stream. Passing $text to through this function gives # a unique text-token which will be reverted back when calling unhash. # # The $boundary argument specify what character should be used to surround # the token. By convension, "B" is used for block elements that needs not # to be wrapped into paragraph tags at the end, ":" is used for elements # that are word separators and "X" is used in the general case. # # Swap back any tag hash found in $text so we do not have to `unhash` # multiple times at the end. $text = $this->unhash($text); # Then hash the block. static $i = 0; $key = "$boundary\x1A" . ++$i . $boundary; $this->html_hashes[$key] = $text; return $key; # String that will replace the tag. } public function hashBlock($text) { # # Shortcut function for hashPart with block-level boundaries. # return $this->hashPart($text, 'B'); } public $block_gamut = array( # # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. # "doHeaders" => 10, "doHorizontalRules" => 20, "doLists" => 40, "doCodeBlocks" => 50, "doBlockQuotes" => 60, ); public function runBlockGamut($text) { # # Run block gamut tranformations. # # We need to escape raw HTML in Markdown source before doing anything # else. This need to be done for each block, and not only at the # begining in the Markdown function since hashed blocks can be part of # list items and could have been indented. Indented blocks would have # been seen as a code block in a previous pass of hashHTMLBlocks. $text = $this->hashHTMLBlocks($text); return $this->runBasicBlockGamut($text); } public function runBasicBlockGamut($text) { # # Run block gamut tranformations, without hashing HTML blocks. This is # useful when HTML blocks are known to be already hashed, like in the first # whole-document pass. # foreach ($this->block_gamut as $method => $priority) { $text = $this->$method($text); } # Finally form paragraph and restore hashed blocks. $text = $this->formParagraphs($text); return $text; } public function doHorizontalRules($text) { # Do Horizontal Rules: return preg_replace( '{ ^[ ]{0,3} # Leading space ([-*_]) # $1: First marker (?> # Repeated marker group [ ]{0,2} # Zero, one, or two spaces. \1 # Marker character ){2,} # Group repeated at least twice [ ]* # Tailing spaces $ # End of line. }mx', "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n", $text); } public $span_gamut = array( # # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. # # Process character escapes, code spans, and inline HTML # in one shot. "parseSpan" => -30, # Process anchor and image tags. Images must come first, # because ![foo][f] looks like an anchor. "doImages" => 10, "doAnchors" => 20, # Make links out of things like `<http://example.com/>` # Must come after doAnchors, because you can use < and > # delimiters in inline links like [this](<url>). "doAutoLinks" => 30, "encodeAmpsAndAngles" => 40, "doItalicsAndBold" => 50, "doHardBreaks" => 60, ); public function runSpanGamut($text) { # # Run span gamut tranformations. # foreach ($this->span_gamut as $method => $priority) { $text = $this->$method($text); } return $text; } public function doHardBreaks($text) { # Do hard breaks: return preg_replace_callback('/ {2,}\n/', array(&$this, '_doHardBreaks_callback'), $text); } public function _doHardBreaks_callback($matches) { return $this->hashPart("<br$this->empty_element_suffix\n"); } public function doAnchors($text) { # # Turn Markdown link shortcuts into XHTML <a> tags. # if ($this->in_anchor) return $text; $this->in_anchor = true; # # First, handle reference-style links: [link text] [id] # $text = preg_replace_callback('{ ( # wrap whole match in $1 \[ ('.$this->nested_brackets_re.') # link text = $2 \] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (.*?) # id = $3 \] ) }xs', array(&$this, '_doAnchors_reference_callback'), $text); # # Next, inline-style links: [link text](url "optional title") # $text = preg_replace_callback('{ ( # wrap whole match in $1 \[ ('.$this->nested_brackets_re.') # link text = $2 \] \( # literal paren [ \n]* (?: <(.+?)> # href = $3 | ('.$this->nested_url_parenthesis_re.') # href = $4 ) [ \n]* ( # $5 ([\'"]) # quote char = $6 (.*?) # Title = $7 \6 # matching quote [ \n]* # ignore any spaces/tabs between closing quote and ) )? # title is optional \) ) }xs', array(&$this, '_doAnchors_inline_callback'), $text); # # Last, handle reference-style shortcuts: [link text] # These must come last in case you've also got [link text][1] # or [link text](/foo) # $text = preg_replace_callback('{ ( # wrap whole match in $1 \[ ([^\[\]]+) # link text = $2; can\'t contain [ or ] \] ) }xs', array(&$this, '_doAnchors_reference_callback'), $text); $this->in_anchor = false; return $text; } public function _doAnchors_reference_callback($matches) { $whole_match = $matches[1]; $link_text = $matches[2]; $link_id =& $matches[3]; if ($link_id == "") { # for shortcut links like [this][] or [this]. $link_id = $link_text; } # lower-case and turn embedded newlines into spaces $link_id = strtolower($link_id); $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); if (isset($this->urls[$link_id])) { $url = $this->urls[$link_id]; $url = $this->encodeAttribute($url); $result = "<a href=\"$url\""; if ( isset( $this->titles[$link_id] ) ) { $title = $this->titles[$link_id]; $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; } $link_text = $this->runSpanGamut($link_text); $result .= ">$link_text</a>"; $result = $this->hashPart($result); } else { $result = $whole_match; } return $result; } public function _doAnchors_inline_callback($matches) { $whole_match = $matches[1]; $link_text = $this->runSpanGamut($matches[2]); $url = $matches[3] == '' ? $matches[4] : $matches[3]; $title =& $matches[7]; $url = $this->encodeAttribute($url); $result = "<a href=\"$url\""; if (isset($title)) { $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; } $link_text = $this->runSpanGamut($link_text); $result .= ">$link_text</a>"; return $this->hashPart($result); } public function doImages($text) { # # Turn Markdown image shortcuts into <img> tags. # # # First, handle reference-style labeled images: ![alt text][id] # $text = preg_replace_callback('{ ( # wrap whole match in $1 !\[ ('.$this->nested_brackets_re.') # alt text = $2 \] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (.*?) # id = $3 \] ) }xs', array(&$this, '_doImages_reference_callback'), $text); # # Next, handle inline images: ![alt text](url "optional title") # Don't forget: encode * and _ # $text = preg_replace_callback('{ ( # wrap whole match in $1 !\[ ('.$this->nested_brackets_re.') # alt text = $2 \] \s? # One optional whitespace character \( # literal paren [ \n]* (?: <(\S*)> # src url = $3 | ('.$this->nested_url_parenthesis_re.') # src url = $4 ) [ \n]* ( # $5 ([\'"]) # quote char = $6 (.*?) # title = $7 \6 # matching quote [ \n]* )? # title is optional \) ) }xs', array(&$this, '_doImages_inline_callback'), $text); return $text; } public function _doImages_reference_callback($matches) { $whole_match = $matches[1]; $alt_text = $matches[2]; $link_id = strtolower($matches[3]); if ($link_id == "") { $link_id = strtolower($alt_text); # for shortcut links like ![this][]. } $alt_text = $this->encodeAttribute($alt_text); if (isset($this->urls[$link_id])) { $url = $this->encodeAttribute($this->urls[$link_id]); $result = "<img src=\"$url\" alt=\"$alt_text\""; if (isset($this->titles[$link_id])) { $title = $this->titles[$link_id]; $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; } $result .= $this->empty_element_suffix; $result = $this->hashPart($result); } else { # If there's no such link ID, leave intact: $result = $whole_match; } return $result; } public function _doImages_inline_callback($matches) { $whole_match = $matches[1]; $alt_text = $matches[2]; $url = $matches[3] == '' ? $matches[4] : $matches[3]; $title =& $matches[7]; $alt_text = $this->encodeAttribute($alt_text); $url = $this->encodeAttribute($url); $result = "<img src=\"$url\" alt=\"$alt_text\""; if (isset($title)) { $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; # $title already quoted } $result .= $this->empty_element_suffix; return $this->hashPart($result); } public function doHeaders($text) { # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- # $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx', array(&$this, '_doHeaders_callback_setext'), $text); # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 # $text = preg_replace_callback('{ ^(\#{1,6}) # $1 = string of #\'s [ ]* (.+?) # $2 = Header text [ ]* \#* # optional closing #\'s (not counted) \n+ }xm', array(&$this, '_doHeaders_callback_atx'), $text); return $text; } public function _doHeaders_callback_setext($matches) { # Terrible hack to check we haven't found an empty list item. if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) return $matches[0]; $level = $matches[2]{0} == '=' ? 1 : 2; $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>"; return "\n" . $this->hashBlock($block) . "\n\n"; } public function _doHeaders_callback_atx($matches) { $level = strlen($matches[1]); $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>"; return "\n" . $this->hashBlock($block) . "\n\n"; } public function doLists($text) { # # Form HTML ordered (numbered) and unordered (bulleted) lists. # $less_than_tab = $this->tab_width - 1; # Re-usable patterns to match list item bullets and number markers: $marker_ul_re = '[*+-]'; $marker_ol_re = '\d+[\.]'; $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; $markers_relist = array( $marker_ul_re => $marker_ol_re, $marker_ol_re => $marker_ul_re, ); foreach ($markers_relist as $marker_re => $other_marker_re) { # Re-usable pattern to match any entirel ul or ol list: $whole_list_re = ' ( # $1 = whole list ( # $2 ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces ('.$marker_re.') # $4 = first list item marker [ ]+ ) (?s:.+?) ( # $5 \z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ ]* '.$marker_re.'[ ]+ ) | (?= # Lookahead for another kind of list \n \3 # Must have the same indentation '.$other_marker_re.'[ ]+ ) ) ) '; // mx # We use a different prefix before nested lists than top-level lists. # See extended comment in _ProcessListItems(). if ($this->list_level) { $text = preg_replace_callback('{ ^ '.$whole_list_re.' }mx', array(&$this, '_doLists_callback'), $text); } else { $text = preg_replace_callback('{ (?:(?<=\n)\n|\A\n?) # Must eat the newline '.$whole_list_re.' }mx', array(&$this, '_doLists_callback'), $text); } } return $text; } public function _doLists_callback($matches) { # Re-usable patterns to match list item bullets and number markers: $marker_ul_re = '[*+-]'; $marker_ol_re = '\d+[\.]'; $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; $list = $matches[1]; $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol"; $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re ); $list .= "\n"; $result = $this->processListItems($list, $marker_any_re); $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>"); return "\n". $result ."\n\n"; } var $list_level = 0; public function processListItems($list_str, $marker_any_re) { # # Process the contents of a single ordered or unordered list, splitting it # into individual list items. # # The $this->list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". $this->list_level++; # trim trailing blank lines: $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); $list_str = preg_replace_callback('{ (\n)? # leading line = $1 (^[ ]*) # leading whitespace = $2 ('.$marker_any_re.' # list marker and space = $3 (?:[ ]+|(?=\n)) # space only required if item is not empty ) ((?s:.*?)) # list item text = $4 (?:(\n+(?=\n))|\n) # tailing blank line = $5 (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n)))) }xm', array(&$this, '_processListItems_callback'), $list_str); $this->list_level--; return $list_str; } public function _processListItems_callback($matches) { $item = $matches[4]; $leading_line =& $matches[1]; $leading_space =& $matches[2]; $marker_space = $matches[3]; $tailing_blank_line =& $matches[5]; if ($leading_line || $tailing_blank_line || preg_match('/\n{2,}/', $item)) { # Replace marker with the appropriate whitespace indentation $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item; $item = $this->runBlockGamut($this->outdent($item)."\n"); } else { # Recursion for sub-lists: $item = $this->doLists($this->outdent($item)); $item = preg_replace('/\n+$/', '', $item); $item = $this->runSpanGamut($item); } return "<li>" . $item . "</li>\n"; } public function doCodeBlocks($text) { # # Process Markdown `<pre><code>` blocks. # $text = preg_replace_callback('{ (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?> [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc }xm', array(&$this, '_doCodeBlocks_callback'), $text); return $text; } public function _doCodeBlocks_callback($matches) { $codeblock = $matches[1]; $codeblock = $this->outdent($codeblock); $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES); # trim leading newlines and trailing newlines $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock); $codeblock = "<pre><code>$codeblock\n</code></pre>"; return "\n\n".$this->hashBlock($codeblock)."\n\n"; } public function makeCodeSpan($code) { # # Create a code span markup for $code. Called from handleSpanToken. # $code = htmlspecialchars(trim($code), ENT_NOQUOTES); return $this->hashPart("<code>$code</code>"); } public $em_relist = array( '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)', '*' => '(?<=\S|^)(?<!\*)\*(?!\*)', '_' => '(?<=\S|^)(?<!_)_(?!_)', ); public $strong_relist = array( '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)', '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)', '__' => '(?<=\S|^)(?<!_)__(?!_)', ); public $em_strong_relist = array( '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)', '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)', '___' => '(?<=\S|^)(?<!_)___(?!_)', ); public $em_strong_prepared_relist; public function prepareItalicsAndBold() { # # Prepare regular expressions for searching emphasis tokens in any # context. # foreach ($this->em_relist as $em => $em_re) { foreach ($this->strong_relist as $strong => $strong_re) { # Construct list of allowed token expressions. $token_relist = array(); if (isset($this->em_strong_relist["$em$strong"])) { $token_relist[] = $this->em_strong_relist["$em$strong"]; } $token_relist[] = $em_re; $token_relist[] = $strong_re; # Construct master expression from list. $token_re = '{('. implode('|', $token_relist) .')}'; $this->em_strong_prepared_relist["$em$strong"] = $token_re; } } } public function doItalicsAndBold($text) { $token_stack = array(''); $text_stack = array(''); $em = ''; $strong = ''; $tree_char_em = false; while (1) { # # Get prepared regular expression for seraching emphasis tokens # in current context. # $token_re = $this->em_strong_prepared_relist["$em$strong"]; # # Each loop iteration search for the next emphasis token. # Each token is then passed to handleSpanToken. # $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); $text_stack[0] .= $parts[0]; $token =& $parts[1]; $text =& $parts[2]; if (empty($token)) { # Reached end of text span: empty stack without emitting. # any more emphasis. while ($token_stack[0]) { $text_stack[1] .= array_shift($token_stack); $text_stack[0] .= array_shift($text_stack); } break; } $token_len = strlen($token); if ($tree_char_em) { # Reached closing marker while inside a three-char emphasis. if ($token_len == 3) { # Three-char closing marker, close em and strong. array_shift($token_stack); $span = array_shift($text_stack); $span = $this->runSpanGamut($span); $span = "<strong><em>$span</em></strong>"; $text_stack[0] .= $this->hashPart($span); $em = ''; $strong = ''; } else { # Other closing marker: close one em or strong and # change current token state to match the other $token_stack[0] = str_repeat($token{0}, 3-$token_len); $tag = $token_len == 2 ? "strong" : "em"; $span = $text_stack[0]; $span = $this->runSpanGamut($span); $span = "<$tag>$span</$tag>"; $text_stack[0] = $this->hashPart($span); $$tag = ''; # $$tag stands for $em or $strong } $tree_char_em = false; } else if ($token_len == 3) { if ($em) { # Reached closing marker for both em and strong. # Closing strong marker: for ($i = 0; $i < 2; ++$i) { $shifted_token = array_shift($token_stack); $tag = strlen($shifted_token) == 2 ? "strong" : "em"; $span = array_shift($text_stack); $span = $this->runSpanGamut($span); $span = "<$tag>$span</$tag>"; $text_stack[0] .= $this->hashPart($span); $$tag = ''; # $$tag stands for $em or $strong } } else { # Reached opening three-char emphasis marker. Push on token # stack; will be handled by the special condition above. $em = $token{0}; $strong = "$em$em"; array_unshift($token_stack, $token); array_unshift($text_stack, ''); $tree_char_em = true; } } else if ($token_len == 2) { if ($strong) { # Unwind any dangling emphasis marker: if (strlen($token_stack[0]) == 1) { $text_stack[1] .= array_shift($token_stack); $text_stack[0] .= array_shift($text_stack); } # Closing strong marker: array_shift($token_stack); $span = array_shift($text_stack); $span = $this->runSpanGamut($span); $span = "<strong>$span</strong>"; $text_stack[0] .= $this->hashPart($span); $strong = ''; } else { array_unshift($token_stack, $token); array_unshift($text_stack, ''); $strong = $token; } } else { # Here $token_len == 1 if ($em) { if (strlen($token_stack[0]) == 1) { # Closing emphasis marker: array_shift($token_stack); $span = array_shift($text_stack); $span = $this->runSpanGamut($span); $span = "<em>$span</em>"; $text_stack[0] .= $this->hashPart($span); $em = ''; } else { $text_stack[0] .= $token; } } else { array_unshift($token_stack, $token); array_unshift($text_stack, ''); $em = $token; } } } return $text_stack[0]; } public function doBlockQuotes($text) { $text = preg_replace_callback('/ ( # Wrap whole match in $1 (?> ^[ ]*>[ ]? # ">" at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) /xm', array(&$this, '_doBlockQuotes_callback'), $text); return $text; } public function _doBlockQuotes_callback($matches) { $bq = $matches[1]; # trim one level of quoting - trim whitespace-only lines $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq); $bq = $this->runBlockGamut($bq); # recurse $bq = preg_replace('/^/m', " ", $bq); # These leading spaces cause problem with <pre> content, # so we need to fix that: $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx', array(&$this, '_doBlockQuotes_callback2'), $bq); return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n"; } public function _doBlockQuotes_callback2($matches) { $pre = $matches[1]; $pre = preg_replace('/^ /m', '', $pre); return $pre; } public function formParagraphs($text) { # # Params: # $text - string to process with html <p> tags # # Strip leading and trailing lines: $text = preg_replace('/\A\n+|\n+\z/', '', $text); $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); # # Wrap <p> tags and unhashify HTML blocks # foreach ($grafs as $key => $value) { if (!preg_match('/^B\x1A[0-9]+B$/', $value)) { # Is a paragraph. $value = $this->runSpanGamut($value); $value = preg_replace('/^([ ]*)/', "<p>", $value); $value .= "</p>"; $grafs[$key] = $this->unhash($value); } else { # Is a block. # Modify elements of @grafs in-place... $graf = $value; $block = $this->html_hashes[$graf]; $graf = $block; // if (preg_match('{ // \A // ( # $1 = <div> tag // <div \s+ // [^>]* // \b // markdown\s*=\s* ([\'"]) # $2 = attr quote char // 1 // \2 // [^>]* // > // ) // ( # $3 = contents // .* // ) // (</div>) # $4 = closing tag // \z // }xs', $block, $matches)) // { // list(, $div_open, , $div_content, $div_close) = $matches; // // # We can't call Markdown(), because that resets the hash; // # that initialization code should be pulled into its own sub, though. // $div_content = $this->hashHTMLBlocks($div_content); // // # Run document gamut methods on the content. // foreach ($this->document_gamut as $method => $priority) { // $div_content = $this->$method($div_content); // } // // $div_open = preg_replace( // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open); // // $graf = $div_open . "\n" . $div_content . "\n" . $div_close; // } $grafs[$key] = $graf; } } return implode("\n\n", $grafs); } public function encodeAttribute($text) { # # Encode text for a double-quoted HTML attribute. This function # is *not* suitable for attributes enclosed in single quotes. # $text = $this->encodeAmpsAndAngles($text); $text = str_replace('"', '&quot;', $text); return $text; } public function encodeAmpsAndAngles($text) { # # Smart processing for ampersands and angle brackets that need to # be encoded. Valid character entities are left alone unless the # no-entities mode is set. # if ($this->no_entities) { $text = str_replace('&', '&amp;', $text); } else { # Ampersand-encoding based entirely on Nat Irons's Amputator # MT plugin: <http://bumppo.net/projects/amputator/> $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/', '&amp;', $text);; } # Encode remaining <'s $text = str_replace('<', '&lt;', $text); return $text; } public function doAutoLinks($text) { $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i', array(&$this, '_doAutoLinks_url_callback'), $text); # Email addresses: <[email protected]> $text = preg_replace_callback('{ < (?:mailto:)? ( (?: [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+ | ".*?" ) \@ (?: [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+ | \[[\d.a-fA-F:]+\] # IPv4 & IPv6 ) ) > }xi', array(&$this, '_doAutoLinks_email_callback'), $text); return $text; } public function _doAutoLinks_url_callback($matches) { $url = $this->encodeAttribute($matches[1]); $link = "<a href=\"$url\">$url</a>"; return $this->hashPart($link); } public function _doAutoLinks_email_callback($matches) { $address = $matches[1]; $link = $this->encodeEmailAddress($address); return $this->hashPart($link); } public function encodeEmailAddress($addr) { # # Input: an email address, e.g. "[email protected]" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111; # &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111; # &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c; # &#101;&#46;&#x63;&#111;&#x6d;</a></p> # # Based by a filter by Matthew Wickline, posted to BBEdit-Talk. # With some optimizations by Milian Wolff. # $addr = "mailto:" . $addr; $chars = preg_split('/(?<!^)(?!$)/', $addr); $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed. foreach ($chars as $key => $char) { $ord = ord($char); # Ignore non-ascii chars. if ($ord < 128) { $r = ($seed * (1 + $key)) % 100; # Pseudo-random function. # roughly 10% raw, 45% hex, 45% dec # '@' *must* be encoded. I insist. if ($r > 90 && $char != '@') /* do nothing */; else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';'; else $chars[$key] = '&#'.$ord.';'; } } $addr = implode('', $chars); $text = implode('', array_slice($chars, 7)); # text without `mailto:` $addr = "<a href=\"$addr\">$text</a>"; return $addr; } public function parseSpan($str) { # # Take the string $str and parse it into tokens, hashing embeded HTML, # escaped characters and handling code spans. # $output = ''; $span_re = '{ ( \\\\'.$this->escape_chars_re.' | (?<![`\\\\]) `+ # code span marker '.( $this->no_markup ? '' : ' | <!-- .*? --> # comment | <\?.*?\?> | <%.*?%> # processing instruction | <[/!$]?[-a-zA-Z0-9:_]+ # regular tags (?> \s (?>[^"\'>]+|"[^"]*"|\'[^\']*\')* )? > ').' ) }xs'; while (1) { # # Each loop iteration seach for either the next tag, the next # openning code span marker, or the next escaped character. # Each token is then passed to handleSpanToken. # $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE); # Create token from text preceding tag. if ($parts[0] != "") { $output .= $parts[0]; } # Check if we reach the end. if (isset($parts[1])) { $output .= $this->handleSpanToken($parts[1], $parts[2]); $str = $parts[2]; } else { break; } } return $output; } public function handleSpanToken($token, &$str) { # # Handle $token provided by parseSpan by determining its nature and # returning the corresponding value that should replace it. # switch ($token{0}) { case "\\": return $this->hashPart("&#". ord($token{1}). ";"); case "`": # Search for end marker in remaining text. if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm', $str, $matches)) { $str = $matches[2]; $codespan = $this->makeCodeSpan($matches[1]); return $this->hashPart($codespan); } return $token; // return as text since no ending marker found. default: return $this->hashPart($token); } } public function outdent($text) { # # Remove one level of line-leading tabs or spaces # return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text); } # String length function for detab. `_initDetab` will create a function to # hanlde UTF-8 if the default function does not exist. public $utf8_strlen = 'mb_strlen'; public function detab($text) { # # Replace tabs with the appropriate amount of space. # # For each line we separate the line in blocks delemited by # tab characters. Then we reconstruct every line by adding the # appropriate number of space between each blocks. $text = preg_replace_callback('/^.*\t.*$/m', array(&$this, '_detab_callback'), $text); return $text; } public function _detab_callback($matches) { $line = $matches[0]; $strlen = $this->utf8_strlen; # strlen function for UTF-8. # Split in blocks. $blocks = explode("\t", $line); # Add each blocks to the line. $line = $blocks[0]; unset($blocks[0]); # Do not add first block twice. foreach ($blocks as $block) { # Calculate amount of space, insert spaces, insert block. $amount = $this->tab_width - $strlen($line, 'UTF-8') % $this->tab_width; $line .= str_repeat(" ", $amount) . $block; } return $line; } public function _initDetab() { # # Check for the availability of the function in the `utf8_strlen` property # (initially `mb_strlen`). If the function is not available, create a # function that will loosely count the number of UTF-8 characters with a # regular expression. # if (function_exists($this->utf8_strlen)) return; $this->utf8_strlen = create_function('$text', 'return preg_match_all( "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/", $text, $m);'); } public function unhash($text) { # # Swap back in all the tags hashed by _HashHTMLBlocks. # return preg_replace_callback('/(.)\x1A[0-9]+\1/', array(&$this, '_unhash_callback'), $text); } public function _unhash_callback($matches) { return $this->html_hashes[$matches[0]]; } } # # Markdown Extra Parser Class # class MarkdownExtra_Parser extends Markdown_Parser { # Prefix for footnote ids. public $fn_id_prefix = ""; # Optional title attribute for footnote links and backlinks. public $fn_link_title = ''; public $fn_backlink_title = ''; # Optional class attribute for footnote links and backlinks. public $fn_link_class = ''; public $fn_backlink_class = ''; # Predefined abbreviations. public $predef_abbr = array(); public function __construct() { # # Constructor function. Initialize the parser object. # # Add extra escapable characters before parent constructor # initialize the table. $this->escape_chars .= ':|'; # Insert extra document, block, and span transformations. # Parent constructor will do the sorting. $this->document_gamut += array( "doFencedCodeBlocks" => 5, "stripFootnotes" => 15, "stripAbbreviations" => 25, "appendFootnotes" => 50, ); $this->block_gamut += array( "doFencedCodeBlocks" => 5, "doTables" => 15, "doDefLists" => 45, ); $this->span_gamut += array( "doFootnotes" => 5, "doAbbreviations" => 70, ); parent::__construct(); } # Extra variables used during extra transformations. public $footnotes = array(); public $footnotes_ordered = array(); public $abbr_desciptions = array(); public $abbr_word_re = ''; # Give the current footnote number. public $footnote_counter = 1; public function setup() { # # Setting up Extra-specific variables. # parent::setup(); $this->footnotes = array(); $this->footnotes_ordered = array(); $this->abbr_desciptions = array(); $this->abbr_word_re = ''; $this->footnote_counter = 1; foreach ($this->predef_abbr as $abbr_word => $abbr_desc) { if ($this->abbr_word_re) $this->abbr_word_re .= '|'; $this->abbr_word_re .= preg_quote($abbr_word); $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); } } public function teardown() { # # Clearing Extra-specific variables. # $this->footnotes = array(); $this->footnotes_ordered = array(); $this->abbr_desciptions = array(); $this->abbr_word_re = ''; parent::teardown(); } ### HTML Block Parser ### # Tags that are always treated as block tags: public $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend'; # Tags treated as block tags only if the opening tag is alone on it's line: public $context_block_tags_re = 'script|noscript|math|ins|del'; # Tags where markdown="1" default to span mode: public $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address'; # Tags which must not have their contents modified, no matter where # they appear: public $clean_tags_re = 'script|math'; # Tags that do not need to be closed. public $auto_close_tags_re = 'hr|img'; public function hashHTMLBlocks($text) { # # Hashify HTML Blocks and "clean tags". # # We only want to do this for block-level HTML tags, such as headers, # lists, and tables. That's because we still want to wrap <p>s around # "paragraphs" that are wrapped in non-block-level tags, such as anchors, # phrase emphasis, and spans. The list of tags we're looking for is # hard-coded. # # This works by calling _HashHTMLBlocks_InMarkdown, which then calls # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1" # attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag. # These two functions are calling each other. It's recursive! # # # Call the HTML-in-Markdown hasher. # list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text); return $text; } public function _hashHTMLBlocks_inMarkdown($text, $indent = 0, $enclosing_tag_re = '', $span = false) { # # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags. # # * $indent is the number of space to be ignored when checking for code # blocks. This is important because if we don't take the indent into # account, something like this (which looks right) won't work as expected: # # <div> # <div markdown="1"> # Hello World. <-- Is this a Markdown code block or text? # </div> <-- Is this a Markdown code block or a real tag? # <div> # # If you don't like this, just don't indent the tag on which # you apply the markdown="1" attribute. # # * If $enclosing_tag_re is not empty, stops at the first unmatched closing # tag with that name. Nested tags supported. # # * If $span is true, text inside must treated as span. So any double # newline will be replaced by a single newline so that it does not create # paragraphs. # # Returns an array of that form: ( processed text , remaining text ) # if ($text === '') return array('', ''); # Regex to check for the presense of newlines around a block tag. $newline_before_re = '/(?:^\n?|\n\n)*$/'; $newline_after_re = '{ ^ # Start of text following the tag. (?>[ ]*<!--.*?-->)? # Optional comment. [ ]*\n # Must be followed by newline. }xs'; # Regex to match any tag. $block_tag_re = '{ ( # $2: Capture hole tag. </? # Any opening or closing tag. (?> # Tag name. '.$this->block_tags_re.' | '.$this->context_block_tags_re.' | '.$this->clean_tags_re.' | (?!\s)'.$enclosing_tag_re.' ) (?: (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name. (?> ".*?" | # Double quotes (can contain `>`) \'.*?\' | # Single quotes (can contain `>`) .+? # Anything but quotes and `>`. )*? )? > # End of tag. | <!-- .*? --> # HTML Comment | <\?.*?\?> | <%.*?%> # Processing instruction | <!\[CDATA\[.*?\]\]> # CData Block | # Code span marker `+ '. ( !$span ? ' # If not in span. | # Indented code block (?: ^[ ]*\n | ^ | \n[ ]*\n ) [ ]{'.($indent+4).'}[^\n]* \n (?> (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n )* | # Fenced code block marker (?> ^ | \n ) [ ]{0,'.($indent).'}~~~+[ ]*\n ' : '' ). ' # End (if not is span). ) }xs'; $depth = 0; # Current depth inside the tag tree. $parsed = ""; # Parsed text that will be returned. # # Loop through every tag until we find the closing tag of the parent # or loop until reaching the end of text if no parent tag specified. # do { # # Split the text using the first $tag_match pattern found. # Text before pattern will be first in the array, text after # pattern will be at the end, and between will be any catches made # by the pattern. # $parts = preg_split($block_tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); # If in Markdown span mode, add a empty-string span-level hash # after each newline to prevent triggering any block element. if ($span) { $void = $this->hashPart("", ':'); $newline = "$void\n"; $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void; } $parsed .= $parts[0]; # Text before current tag. # If end of $text has been reached. Stop loop. if (count($parts) < 3) { $text = ""; break; } $tag = $parts[1]; # Tag to handle. $text = $parts[2]; # Remaining text after current tag. $tag_re = preg_quote($tag); # For use in a regular expression. # # Check for: Code span marker # if ($tag{0} == "`") { # Find corresponding end marker. $tag_re = preg_quote($tag); if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)'.$tag_re.'(?!`)}', $text, $matches)) { # End marker found: pass text unchanged until marker. $parsed .= $tag . $matches[0]; $text = substr($text, strlen($matches[0])); } else { # Unmatched marker: just skip it. $parsed .= $tag; } } # # Check for: Fenced code block marker. # else if (preg_match('{^\n?[ ]{0,'.($indent+3).'}~}', $tag)) { # Fenced code block marker: find matching end marker. $tag_re = preg_quote(trim($tag)); if (preg_match('{^(?>.*\n)+?[ ]{0,'.($indent).'}'.$tag_re.'[ ]*\n}', $text, $matches)) { # End marker found: pass text unchanged until marker. $parsed .= $tag . $matches[0]; $text = substr($text, strlen($matches[0])); } else { # No end marker: just skip it. $parsed .= $tag; } } # # Check for: Indented code block. # else if ($tag{0} == "\n" || $tag{0} == " ") { # Indented code block: pass it unchanged, will be handled # later. $parsed .= $tag; } # # Check for: Opening Block level tag or # Opening Context Block tag (like ins and del) # used as a block tag (tag is alone on it's line). # else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) || ( preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) && preg_match($newline_before_re, $parsed) && preg_match($newline_after_re, $text) ) ) { # Need to parse tag and following text using the HTML parser. list($block_text, $text) = $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true); # Make sure it stays outside of any paragraph by adding newlines. $parsed .= "\n\n$block_text\n\n"; } # # Check for: Clean tag (like script, math) # HTML Comments, processing instructions. # else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) || $tag{1} == '!' || $tag{1} == '?') { # Need to parse tag and following text using the HTML parser. # (don't check for markdown attribute) list($block_text, $text) = $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false); $parsed .= $block_text; } # # Check for: Tag with same name as enclosing tag. # else if ($enclosing_tag_re !== '' && # Same name as enclosing tag. preg_match('{^</?(?:'.$enclosing_tag_re.')\b}', $tag)) { # # Increase/decrease nested tag count. # if ($tag{1} == '/') $depth--; else if ($tag{strlen($tag)-2} != '/') $depth++; if ($depth < 0) { # # Going out of parent element. Clean up and break so we # return to the calling function. # $text = $tag . $text; break; } $parsed .= $tag; } else { $parsed .= $tag; } } while ($depth >= 0); return array($parsed, $text); } public function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) { # # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags. # # * Calls $hash_method to convert any blocks. # * Stops when the first opening tag closes. # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed. # (it is not inside clean tags) # # Returns an array of that form: ( processed text , remaining text ) # if ($text === '') return array('', ''); # Regex to match `markdown` attribute inside of a tag. $markdown_attr_re = ' { \s* # Eat whitespace before the `markdown` attribute markdown \s*=\s* (?> (["\']) # $1: quote delimiter (.*?) # $2: attribute value \1 # matching delimiter | ([^\s>]*) # $3: unquoted attribute value ) () # $4: make $3 always defined (avoid warnings) }xs'; # Regex to match any tag. $tag_re = '{ ( # $2: Capture hole tag. </? # Any opening or closing tag. [\w:$]+ # Tag name. (?: (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name. (?> ".*?" | # Double quotes (can contain `>`) \'.*?\' | # Single quotes (can contain `>`) .+? # Anything but quotes and `>`. )*? )? > # End of tag. | <!-- .*? --> # HTML Comment | <\?.*?\?> | <%.*?%> # Processing instruction | <!\[CDATA\[.*?\]\]> # CData Block ) }xs'; $original_text = $text; # Save original text in case of faliure. $depth = 0; # Current depth inside the tag tree. $block_text = ""; # Temporary text holder for current text. $parsed = ""; # Parsed text that will be returned. # # Get the name of the starting tag. # (This pattern makes $base_tag_name_re safe without quoting.) # if (preg_match('/^<([\w:$]*)\b/', $text, $matches)) $base_tag_name_re = $matches[1]; # # Loop through every tag until we find the corresponding closing tag. # do { # # Split the text using the first $tag_match pattern found. # Text before pattern will be first in the array, text after # pattern will be at the end, and between will be any catches made # by the pattern. # $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); if (count($parts) < 3) { # # End of $text reached with unbalenced tag(s). # In that case, we return original text unchanged and pass the # first character as filtered to prevent an infinite loop in the # parent function. # return array($original_text{0}, substr($original_text, 1)); } $block_text .= $parts[0]; # Text before current tag. $tag = $parts[1]; # Tag to handle. $text = $parts[2]; # Remaining text after current tag. # # Check for: Auto-close tag (like <hr/>) # Comments and Processing Instructions. # if (preg_match('{^</?(?:'.$this->auto_close_tags_re.')\b}', $tag) || $tag{1} == '!' || $tag{1} == '?') { # Just add the tag to the block as if it was text. $block_text .= $tag; } else { # # Increase/decrease nested tag count. Only do so if # the tag's name match base tag's. # if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) { if ($tag{1} == '/') $depth--; else if ($tag{strlen($tag)-2} != '/') $depth++; } # # Check for `markdown="1"` attribute and handle it. # if ($md_attr && preg_match($markdown_attr_re, $tag, $attr_m) && preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3])) { # Remove `markdown` attribute from opening tag. $tag = preg_replace($markdown_attr_re, '', $tag); # Check if text inside this tag must be parsed in span mode. $this->mode = $attr_m[2] . $attr_m[3]; $span_mode = $this->mode == 'span' || $this->mode != 'block' && preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag); # Calculate indent before tag. if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) { $strlen = $this->utf8_strlen; $indent = $strlen($matches[1], 'UTF-8'); } else { $indent = 0; } # End preceding block with this tag. $block_text .= $tag; $parsed .= $this->$hash_method($block_text); # Get enclosing tag name for the ParseMarkdown function. # (This pattern makes $tag_name_re safe without quoting.) preg_match('/^<([\w:$]*)\b/', $tag, $matches); $tag_name_re = $matches[1]; # Parse the content using the HTML-in-Markdown parser. list ($block_text, $text) = $this->_hashHTMLBlocks_inMarkdown($text, $indent, $tag_name_re, $span_mode); # Outdent markdown text. if ($indent > 0) { $block_text = preg_replace("/^[ ]{1,$indent}/m", "", $block_text); } # Append tag content to parsed text. if (!$span_mode) $parsed .= "\n\n$block_text\n\n"; else $parsed .= "$block_text"; # Start over a new block. $block_text = ""; } else $block_text .= $tag; } } while ($depth > 0); # # Hash last block text that wasn't processed inside the loop. # $parsed .= $this->$hash_method($block_text); return array($parsed, $text); } public function hashClean($text) { # # Called whenever a tag must be hashed when a function insert a "clean" tag # in $text, it pass through this function and is automaticaly escaped, # blocking invalid nested overlap. # return $this->hashPart($text, 'C'); } public function doHeaders($text) { # # Redefined to add id attribute support. # # Setext-style headers: # Header 1 {#header1} # ======== # # Header 2 {#header2} # -------- # $text = preg_replace_callback( '{ (^.+?) # $1: Header text (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # $2: Id attribute [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer }mx', array(&$this, '_doHeaders_callback_setext'), $text); # atx-style headers: # # Header 1 {#header1} # ## Header 2 {#header2} # ## Header 2 with closing hashes ## {#header3} # ... # ###### Header 6 {#header2} # $text = preg_replace_callback('{ ^(\#{1,6}) # $1 = string of #\'s [ ]* (.+?) # $2 = Header text [ ]* \#* # optional closing #\'s (not counted) (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # id attribute [ ]* \n+ }xm', array(&$this, '_doHeaders_callback_atx'), $text); return $text; } public function _doHeaders_attr($attr) { if (empty($attr)) return ""; return " id=\"$attr\""; } public function _doHeaders_callback_setext($matches) { if ($matches[3] == '-' && preg_match('{^- }', $matches[1])) return $matches[0]; $level = $matches[3]{0} == '=' ? 1 : 2; $attr = $this->_doHeaders_attr($id =& $matches[2]); $block = "<h$level$attr>".$this->runSpanGamut($matches[1])."</h$level>"; return "\n" . $this->hashBlock($block) . "\n\n"; } public function _doHeaders_callback_atx($matches) { $level = strlen($matches[1]); $attr = $this->_doHeaders_attr($id =& $matches[3]); $block = "<h$level$attr>".$this->runSpanGamut($matches[2])."</h$level>"; return "\n" . $this->hashBlock($block) . "\n\n"; } public function doTables($text) { # # Form HTML tables. # $less_than_tab = $this->tab_width - 1; # # Find tables with leading pipe. # # | Header 1 | Header 2 # | -------- | -------- # | Cell 1 | Cell 2 # | Cell 3 | Cell 4 # $text = preg_replace_callback(' { ^ # Start of a line [ ]{0,'.$less_than_tab.'} # Allowed whitespace. [|] # Optional leading pipe (present) (.+) \n # $1: Header row (at least one pipe) [ ]{0,'.$less_than_tab.'} # Allowed whitespace. [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline ( # $3: Cells (?> [ ]* # Allowed whitespace. [|] .* \n # Row content. )* ) (?=\n|\Z) # Stop at final double newline. }xm', array(&$this, '_doTable_leadingPipe_callback'), $text); # # Find tables without leading pipe. # # Header 1 | Header 2 # -------- | -------- # Cell 1 | Cell 2 # Cell 3 | Cell 4 # $text = preg_replace_callback(' { ^ # Start of a line [ ]{0,'.$less_than_tab.'} # Allowed whitespace. (\S.*[|].*) \n # $1: Header row (at least one pipe) [ ]{0,'.$less_than_tab.'} # Allowed whitespace. ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline ( # $3: Cells (?> .* [|] .* \n # Row content )* ) (?=\n|\Z) # Stop at final double newline. }xm', array(&$this, '_DoTable_callback'), $text); return $text; } public function _doTable_leadingPipe_callback($matches) { $head = $matches[1]; $underline = $matches[2]; $content = $matches[3]; # Remove leading pipe for each row. $content = preg_replace('/^ *[|]/m', '', $content); return $this->_doTable_callback(array($matches[0], $head, $underline, $content)); } public function _doTable_callback($matches) { $head = $matches[1]; $underline = $matches[2]; $content = $matches[3]; # Remove any tailing pipes for each line. $head = preg_replace('/[|] *$/m', '', $head); $underline = preg_replace('/[|] *$/m', '', $underline); $content = preg_replace('/[|] *$/m', '', $content); # Reading alignement from header underline. $separators = preg_split('/ *[|] */', $underline); foreach ($separators as $n => $s) { if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"'; else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"'; else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"'; else $attr[$n] = ''; } # Parsing span elements, including code spans, character escapes, # and inline HTML tags, so that pipes inside those gets ignored. $head = $this->parseSpan($head); $headers = preg_split('/ *[|] */', $head); $col_count = count($headers); # Write column headers. $text = "<table>\n"; $text .= "<thead>\n"; $text .= "<tr>\n"; foreach ($headers as $n => $header) $text .= " <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n"; $text .= "</tr>\n"; $text .= "</thead>\n"; # Split content by row. $rows = explode("\n", trim($content, "\n")); $text .= "<tbody>\n"; foreach ($rows as $row) { # Parsing span elements, including code spans, character escapes, # and inline HTML tags, so that pipes inside those gets ignored. $row = $this->parseSpan($row); # Split row by cell. $row_cells = preg_split('/ *[|] */', $row, $col_count); $row_cells = array_pad($row_cells, $col_count, ''); $text .= "<tr>\n"; foreach ($row_cells as $n => $cell) $text .= " <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n"; $text .= "</tr>\n"; } $text .= "</tbody>\n"; $text .= "</table>"; return $this->hashBlock($text) . "\n"; } public function doDefLists($text) { # # Form HTML definition lists. # $less_than_tab = $this->tab_width - 1; # Re-usable pattern to match any entire dl list: $whole_list_re = '(?> ( # $1 = whole list ( # $2 [ ]{0,'.$less_than_tab.'} ((?>.*\S.*\n)+) # $3 = defined term \n? [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition ) (?s:.+?) ( # $4 \z | \n{2,} (?=\S) (?! # Negative lookahead for another term [ ]{0,'.$less_than_tab.'} (?: \S.*\n )+? # defined term \n? [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition ) (?! # Negative lookahead for another definition [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition ) ) ) )'; // mx $text = preg_replace_callback('{ (?>\A\n?|(?<=\n\n)) '.$whole_list_re.' }mx', array(&$this, '_doDefLists_callback'), $text); return $text; } public function _doDefLists_callback($matches) { # Re-usable patterns to match list item bullets and number markers: $list = $matches[1]; # Turn double returns into triple returns, so that we can make a # paragraph for the last item in a list, if necessary: $result = trim($this->processDefListItems($list)); $result = "<dl>\n" . $result . "\n</dl>"; return $this->hashBlock($result) . "\n\n"; } public function processDefListItems($list_str) { # # Process the contents of a single definition list, splitting it # into individual term and definition list items. # $less_than_tab = $this->tab_width - 1; # trim trailing blank lines: $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); # Process definition terms. $list_str = preg_replace_callback('{ (?>\A\n?|\n\n+) # leading line ( # definition terms = $1 [ ]{0,'.$less_than_tab.'} # leading whitespace (?![:][ ]|[ ]) # negative lookahead for a definition # mark (colon) or more whitespace. (?> \S.* \n)+? # actual term (not whitespace). ) (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed # with a definition mark. }xm', array(&$this, '_processDefListItems_callback_dt'), $list_str); # Process actual definitions. $list_str = preg_replace_callback('{ \n(\n+)? # leading line = $1 ( # marker space = $2 [ ]{0,'.$less_than_tab.'} # whitespace before colon [:][ ]+ # definition mark (colon) ) ((?s:.+?)) # definition text = $3 (?= \n+ # stop at next definition mark, (?: # next term or end of text [ ]{0,'.$less_than_tab.'} [:][ ] | <dt> | \z ) ) }xm', array(&$this, '_processDefListItems_callback_dd'), $list_str); return $list_str; } public function _processDefListItems_callback_dt($matches) { $terms = explode("\n", trim($matches[1])); $text = ''; foreach ($terms as $term) { $term = $this->runSpanGamut(trim($term)); $text .= "\n<dt>" . $term . "</dt>"; } return $text . "\n"; } public function _processDefListItems_callback_dd($matches) { $leading_line = $matches[1]; $marker_space = $matches[2]; $def = $matches[3]; if ($leading_line || preg_match('/\n{2,}/', $def)) { # Replace marker with the appropriate whitespace indentation $def = str_repeat(' ', strlen($marker_space)) . $def; $def = $this->runBlockGamut($this->outdent($def . "\n\n")); $def = "\n". $def ."\n"; } else { $def = rtrim($def); $def = $this->runSpanGamut($this->outdent($def)); } return "\n<dd>" . $def . "</dd>\n"; } public function doFencedCodeBlocks($text) { # # Adding the fenced code block syntax to regular Markdown: # # ~~~ # Code block # ~~~ # $less_than_tab = $this->tab_width; $text = preg_replace_callback('{ (?:\n|\A) # 1: Opening marker ( ~{3,} # Marker: three tilde or more. ) [ ]* \n # Whitespace and newline following marker. # 2: Content ( (?> (?!\1 [ ]* \n) # Not a closing marker. .*\n+ )+ ) # Closing marker. \1 [ ]* \n }xm', array(&$this, '_doFencedCodeBlocks_callback'), $text); return $text; } public function _doFencedCodeBlocks_callback($matches) { $codeblock = $matches[2]; $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES); $codeblock = preg_replace_callback('/^\n+/', array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock); $codeblock = "<pre><code>$codeblock</code></pre>"; return "\n\n".$this->hashBlock($codeblock)."\n\n"; } public function _doFencedCodeBlocks_newlines($matches) { return str_repeat("<br$this->empty_element_suffix", strlen($matches[0])); } # # Redefining emphasis markers so that emphasis by underscore does not # work in the middle of a word. # public $em_relist = array( '' => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?=\S|$)(?![\.,:;]\s)', '*' => '(?<=\S|^)(?<!\*)\*(?!\*)', '_' => '(?<=\S|^)(?<!_)_(?![a-zA-Z0-9_])', ); public $strong_relist = array( '' => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?=\S|$)(?![\.,:;]\s)', '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)', '__' => '(?<=\S|^)(?<!_)__(?![a-zA-Z0-9_])', ); public $em_strong_relist = array( '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?=\S|$)(?![\.,:;]\s)', '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)', '___' => '(?<=\S|^)(?<!_)___(?![a-zA-Z0-9_])', ); public function formParagraphs($text) { # # Params: # $text - string to process with html <p> tags # # Strip leading and trailing lines: $text = preg_replace('/\A\n+|\n+\z/', '', $text); $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); # # Wrap <p> tags and unhashify HTML blocks # foreach ($grafs as $key => $value) { $value = trim($this->runSpanGamut($value)); # Check if this should be enclosed in a paragraph. # Clean tag hashes & block tag hashes are left alone. $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value); if ($is_p) { $value = "<p>$value</p>"; } $grafs[$key] = $value; } # Join grafs in one text, then unhash HTML tags. $text = implode("\n\n", $grafs); # Finish by removing any tag hashes still present in $text. $text = $this->unhash($text); return $text; } ### Footnotes public function stripFootnotes($text) { # # Strips link definitions from text, stores the URLs and titles in # hash references. # $less_than_tab = $this->tab_width - 1; # Link defs are in the form: [^id]: url "optional title" $text = preg_replace_callback('{ ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?: # note_id = $1 [ ]* \n? # maybe *one* newline ( # text = $2 (no blank lines allowed) (?: .+ # actual text | \n # newlines but (?!\[\^.+?\]:\s)# negative lookahead for footnote marker. (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed # by non-indented content )* ) }xm', array(&$this, '_stripFootnotes_callback'), $text); return $text; } public function _stripFootnotes_callback($matches) { $note_id = $this->fn_id_prefix . $matches[1]; $this->footnotes[$note_id] = $this->outdent($matches[2]); return ''; # String that will replace the block } public function doFootnotes($text) { # # Replace footnote references in $text [^id] with a special text-token # which will be replaced by the actual footnote marker in appendFootnotes. # if (!$this->in_anchor) { $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text); } return $text; } public function appendFootnotes($text) { # # Append footnote list to text. # $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', array(&$this, '_appendFootnotes_callback'), $text); if (!empty($this->footnotes_ordered)) { $text .= "\n\n"; $text .= "<div class=\"footnotes\">\n"; $text .= "<hr". $this->empty_element_suffix ."\n"; $text .= "<ol>\n\n"; $attr = " rev=\"footnote\""; if ($this->fn_backlink_class != "") { $class = $this->fn_backlink_class; $class = $this->encodeAttribute($class); $attr .= " class=\"$class\""; } if ($this->fn_backlink_title != "") { $title = $this->fn_backlink_title; $title = $this->encodeAttribute($title); $attr .= " title=\"$title\""; } $num = 0; while (!empty($this->footnotes_ordered)) { $footnote = reset($this->footnotes_ordered); $note_id = key($this->footnotes_ordered); unset($this->footnotes_ordered[$note_id]); $footnote .= "\n"; # Need to append newline before parsing. $footnote = $this->runBlockGamut("$footnote\n"); $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', array(&$this, '_appendFootnotes_callback'), $footnote); $attr = str_replace("%%", ++$num, $attr); $note_id = $this->encodeAttribute($note_id); # Add backlink to last paragraph; create new paragraph if needed. $backlink = "<a href=\"#fnref:$note_id\"$attr>&#8617;</a>"; if (preg_match('{</p>$}', $footnote)) { $footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>"; } else { $footnote .= "\n\n<p>$backlink</p>"; } $text .= "<li id=\"fn:$note_id\">\n"; $text .= $footnote . "\n"; $text .= "</li>\n\n"; } $text .= "</ol>\n"; $text .= "</div>"; } return $text; } public function _appendFootnotes_callback($matches) { $node_id = $this->fn_id_prefix . $matches[1]; # Create footnote marker only if it has a corresponding footnote *and* # the footnote hasn't been used by another marker. if (isset($this->footnotes[$node_id])) { # Transfert footnote content to the ordered list. $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id]; unset($this->footnotes[$node_id]); $num = $this->footnote_counter++; $attr = " rel=\"footnote\""; if ($this->fn_link_class != "") { $class = $this->fn_link_class; $class = $this->encodeAttribute($class); $attr .= " class=\"$class\""; } if ($this->fn_link_title != "") { $title = $this->fn_link_title; $title = $this->encodeAttribute($title); $attr .= " title=\"$title\""; } $attr = str_replace("%%", $num, $attr); $node_id = $this->encodeAttribute($node_id); return "<sup id=\"fnref:$node_id\">". "<a href=\"#fn:$node_id\"$attr>$num</a>". "</sup>"; } return "[^".$matches[1]."]"; } ### Abbreviations ### public function stripAbbreviations($text) { # # Strips abbreviations from text, stores titles in hash references. # $less_than_tab = $this->tab_width - 1; # Link defs are in the form: [id]*: url "optional title" $text = preg_replace_callback('{ ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1 (.*) # text = $2 (no blank lines allowed) }xm', array(&$this, '_stripAbbreviations_callback'), $text); return $text; } public function _stripAbbreviations_callback($matches) { $abbr_word = $matches[1]; $abbr_desc = $matches[2]; if ($this->abbr_word_re) $this->abbr_word_re .= '|'; $this->abbr_word_re .= preg_quote($abbr_word); $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); return ''; # String that will replace the block } public function doAbbreviations($text) { # # Find defined abbreviations in text and wrap them in <abbr> elements. # if ($this->abbr_word_re) { // cannot use the /x modifier because abbr_word_re may // contain significant spaces: $text = preg_replace_callback('{'. '(?<![\w\x1A])'. '(?:'.$this->abbr_word_re.')'. '(?![\w\x1A])'. '}', array(&$this, '_doAbbreviations_callback'), $text); } return $text; } public function _doAbbreviations_callback($matches) { $abbr = $matches[0]; if (isset($this->abbr_desciptions[$abbr])) { $desc = $this->abbr_desciptions[$abbr]; if (empty($desc)) { return $this->hashPart("<abbr>$abbr</abbr>"); } else { $desc = $this->encodeAttribute($desc); return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>"); } } else { return $matches[0]; } } }
Wyden971/IpMotors
yiiframework/vendors/markdown/markdown.php
PHP
unlicense
74,111
/** * FixedDataTable v0.4.0 * * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["FixedDataTable"] = factory(require("react")); else root["FixedDataTable"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_29__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(13); __webpack_require__(15); __webpack_require__(17); __webpack_require__(19); __webpack_require__(21); __webpack_require__(23); __webpack_require__(1); __webpack_require__(5); __webpack_require__(7); __webpack_require__(9); __webpack_require__(11); module.exports = __webpack_require__(25); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { // removed by extract-text-webpack-plugin /***/ }, /* 2 */, /* 3 */, /* 4 */, /* 5 */ /***/ function(module, exports, __webpack_require__) { // removed by extract-text-webpack-plugin /***/ }, /* 6 */, /* 7 */ /***/ function(module, exports, __webpack_require__) { // removed by extract-text-webpack-plugin /***/ }, /* 8 */, /* 9 */ /***/ function(module, exports, __webpack_require__) { // removed by extract-text-webpack-plugin /***/ }, /* 10 */, /* 11 */ /***/ function(module, exports, __webpack_require__) { // removed by extract-text-webpack-plugin /***/ }, /* 12 */, /* 13 */ /***/ function(module, exports, __webpack_require__) { // removed by extract-text-webpack-plugin /***/ }, /* 14 */, /* 15 */ /***/ function(module, exports, __webpack_require__) { // removed by extract-text-webpack-plugin /***/ }, /* 16 */, /* 17 */ /***/ function(module, exports, __webpack_require__) { // removed by extract-text-webpack-plugin /***/ }, /* 18 */, /* 19 */ /***/ function(module, exports, __webpack_require__) { // removed by extract-text-webpack-plugin /***/ }, /* 20 */, /* 21 */ /***/ function(module, exports, __webpack_require__) { // removed by extract-text-webpack-plugin /***/ }, /* 22 */, /* 23 */ /***/ function(module, exports, __webpack_require__) { // removed by extract-text-webpack-plugin /***/ }, /* 24 */, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableRoot */ 'use strict'; var FixedDataTable = __webpack_require__(26); var FixedDataTableColumn = __webpack_require__(46); var FixedDataTableColumnGroup = __webpack_require__(45); var FixedDataTableRoot = { Column: FixedDataTableColumn, ColumnGroup: FixedDataTableColumnGroup, Table: FixedDataTable }; FixedDataTableRoot.version = '0.4.0'; module.exports = FixedDataTableRoot; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTable.react * @typechecks */ /* jslint bitwise: true */ 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var FixedDataTableHelper = __webpack_require__(43); var React = __webpack_require__(28); var ReactComponentWithPureRenderMixin = __webpack_require__(47); var ReactWheelHandler = __webpack_require__(50); var Scrollbar = __webpack_require__(58); var FixedDataTableBufferedRows = __webpack_require__(70); var FixedDataTableColumnResizeHandle = __webpack_require__(85); var FixedDataTableRow = __webpack_require__(75); var FixedDataTableScrollHelper = __webpack_require__(86); var FixedDataTableWidthHelper = __webpack_require__(27); var cloneWithProps = __webpack_require__(30); var cx = __webpack_require__(64); var debounceCore = __webpack_require__(88); var emptyFunction = __webpack_require__(51); var invariant = __webpack_require__(69); var joinClasses = __webpack_require__(84); var shallowEqual = __webpack_require__(89); var translateDOMPositionXY = __webpack_require__(65); var PropTypes = React.PropTypes; var ReactChildren = React.Children; var renderToString = FixedDataTableHelper.renderToString; var EMPTY_OBJECT = {}; var BORDER_HEIGHT = 1; /** * Data grid component with fixed or scrollable header and columns. * * The layout of the data table is as follows: * * ``` * +---------------------------------------------------+ * | Fixed Column Group | Scrollable Column Group | * | Header | Header | * | | | * +---------------------------------------------------+ * | | | * | Fixed Header Columns | Scrollable Header Columns | * | | | * +-----------------------+---------------------------+ * | | | * | Fixed Body Columns | Scrollable Body Columns | * | | | * +-----------------------+---------------------------+ * | | | * | Fixed Footer Columns | Scrollable Footer Columns | * | | | * +-----------------------+---------------------------+ * ``` * * - Fixed Column Group Header: These are the headers for a group * of columns if included in the table that do not scroll * vertically or horizontally. * * - Scrollable Column Group Header: The header for a group of columns * that do not move while scrolling vertically, but move horizontally * with the horizontal scrolling. * * - Fixed Header Columns: The header columns that do not move while scrolling * vertically or horizontally. * * - Scrollable Header Columns: The header columns that do not move * while scrolling vertically, but move horizontally with the horizontal * scrolling. * * - Fixed Body Columns: The body columns that do not move while scrolling * horizontally, but move vertically with the vertical scrolling. * * - Scrollable Body Columns: The body columns that move while scrolling * vertically or horizontally. */ var FixedDataTable = React.createClass({ displayName: 'FixedDataTable', propTypes: { /** * Pixel width of table. If all columns do not fit, * a horizontal scrollbar will appear. */ width: PropTypes.number.isRequired, /** * Pixel height of table. If all rows do not fit, * a vertical scrollbar will appear. * * Either `height` or `maxHeight` must be specified. */ height: PropTypes.number, /** * Maximum pixel height of table. If all rows do not fit, * a vertical scrollbar will appear. * * Either `height` or `maxHeight` must be specified. */ maxHeight: PropTypes.number, /** * Pixel height of table's owner, this is used in a managed scrolling * situation when you want to slide the table up from below the fold * without having to constantly update the height on every scroll tick. * Instead, vary this property on scroll. By using `ownerHeight`, we * over-render the table while making sure the footer and horizontal * scrollbar of the table are visible when the current space for the table * in view is smaller than the final, over-flowing height of table. It * allows us to avoid resizing and reflowing table when it is moving in the * view. * * This is used if `ownerHeight < height` (or `maxHeight`). */ ownerHeight: PropTypes.number, overflowX: PropTypes.oneOf(['hidden', 'auto']), overflowY: PropTypes.oneOf(['hidden', 'auto']), /** * Number of rows in the table. */ rowsCount: PropTypes.number.isRequired, /** * Pixel height of rows unless `rowHeightGetter` is specified and returns * different value. */ rowHeight: PropTypes.number.isRequired, /** * If specified, `rowHeightGetter(index)` is called for each row and the * returned value overrides `rowHeight` for particular row. */ rowHeightGetter: PropTypes.func, /** * To get rows to display in table, `rowGetter(index)` * is called. `rowGetter` should be smart enough to handle async * fetching of data and return temporary objects * while data is being fetched. */ rowGetter: PropTypes.func.isRequired, /** * To get any additional CSS classes that should be added to a row, * `rowClassNameGetter(index)` is called. */ rowClassNameGetter: PropTypes.func, /** * Pixel height of the column group header. */ groupHeaderHeight: PropTypes.number, /** * Pixel height of header. */ headerHeight: PropTypes.number.isRequired, /** * Function that is called to get the data for the header row. * If the function returns null, the header will be set to the * Column's label property. */ headerDataGetter: PropTypes.func, /** * Pixel height of footer. */ footerHeight: PropTypes.number, /** * DEPRECATED - use footerDataGetter instead. * Data that will be passed to footer cell renderers. */ footerData: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), /** * Function that is called to get the data for the footer row. */ footerDataGetter: PropTypes.func, /** * Value of horizontal scroll. */ scrollLeft: PropTypes.number, /** * Index of column to scroll to. */ scrollToColumn: PropTypes.number, /** * Value of vertical scroll. */ scrollTop: PropTypes.number, /** * Index of row to scroll to. */ scrollToRow: PropTypes.number, /** * Callback that is called when scrolling starts with current horizontal * and vertical scroll values. */ onScrollStart: PropTypes.func, /** * Callback that is called when scrolling ends or stops with new horizontal * and vertical scroll values. */ onScrollEnd: PropTypes.func, /** * Callback that is called when `rowHeightGetter` returns a different height * for a row than the `rowHeight` prop. This is necessary because initially * table estimates heights of some parts of the content. */ onContentHeightChange: PropTypes.func, /** * Callback that is called when a row is clicked. */ onRowClick: PropTypes.func, /** * Callback that is called when a row is double clicked. */ onRowDoubleClick: PropTypes.func, /** * Callback that is called when a mouse-down event happens on a row. */ onRowMouseDown: PropTypes.func, /** * Callback that is called when a mouse-enter event happens on a row. */ onRowMouseEnter: PropTypes.func, /** * Callback that is called when a mouse-leave event happens on a row. */ onRowMouseLeave: PropTypes.func, /** * Callback that is called when resizer has been released * and column needs to be updated. * * Required if the isResizable property is true on any column. * * ``` * function( * newColumnWidth: number, * dataKey: string, * ) * ``` */ onColumnResizeEndCallback: PropTypes.func, /** * Whether a column is currently being resized. */ isColumnResizing: PropTypes.bool }, getDefaultProps: function getDefaultProps() /*object*/{ return { footerHeight: 0, groupHeaderHeight: 0, headerHeight: 0, scrollLeft: 0, scrollTop: 0 }; }, getInitialState: function getInitialState() /*object*/{ var props = this.props; var viewportHeight = (props.height === undefined ? props.maxHeight : props.height) - (props.headerHeight || 0) - (props.footerHeight || 0) - (props.groupHeaderHeight || 0); this._scrollHelper = new FixedDataTableScrollHelper(props.rowsCount, props.rowHeight, viewportHeight, props.rowHeightGetter); if (props.scrollTop) { this._scrollHelper.scrollTo(props.scrollTop); } this._didScrollStop = debounceCore(this._didScrollStop, 160, this); return this._calculateState(this.props); }, componentWillMount: function componentWillMount() { var scrollToRow = this.props.scrollToRow; if (scrollToRow !== undefined && scrollToRow !== null) { this._rowToScrollTo = scrollToRow; } var scrollToColumn = this.props.scrollToColumn; if (scrollToColumn !== undefined && scrollToColumn !== null) { this._columnToScrollTo = scrollToColumn; } this._wheelHandler = new ReactWheelHandler(this._onWheel, this._shouldHandleWheelX, this._shouldHandleWheelY); }, _shouldHandleWheelX: function _shouldHandleWheelX( /*number*/delta) /*boolean*/{ if (this.props.overflowX === 'hidden') { return false; } delta = Math.round(delta); if (delta === 0) { return false; } return delta < 0 && this.state.scrollX > 0 || delta >= 0 && this.state.scrollX < this.state.maxScrollX; }, _shouldHandleWheelY: function _shouldHandleWheelY( /*number*/delta) /*boolean*/{ if (this.props.overflowY === 'hidden' || delta === 0) { return false; } delta = Math.round(delta); if (delta === 0) { return false; } return delta < 0 && this.state.scrollY > 0 || delta >= 0 && this.state.scrollY < this.state.maxScrollY; }, _reportContentHeight: function _reportContentHeight() { var scrollContentHeight = this.state.scrollContentHeight; var reservedHeight = this.state.reservedHeight; var requiredHeight = scrollContentHeight + reservedHeight; var contentHeight; var useMaxHeight = this.props.height === undefined; if (useMaxHeight && this.props.maxHeight > requiredHeight) { contentHeight = requiredHeight; } else if (this.state.height > requiredHeight && this.props.ownerHeight) { contentHeight = Math.max(requiredHeight, this.props.ownerHeight); } else { contentHeight = this.state.height + this.state.maxScrollY; } if (contentHeight !== this._contentHeight && this.props.onContentHeightChange) { this.props.onContentHeightChange(contentHeight); } this._contentHeight = contentHeight; }, componentDidMount: function componentDidMount() { this._reportContentHeight(); }, componentWillReceiveProps: function componentWillReceiveProps( /*object*/nextProps) { var scrollToRow = nextProps.scrollToRow; if (scrollToRow !== undefined && scrollToRow !== null) { this._rowToScrollTo = scrollToRow; } var scrollToColumn = nextProps.scrollToColumn; if (scrollToColumn !== undefined && scrollToColumn !== null) { this._columnToScrollTo = scrollToColumn; } var newOverflowX = nextProps.overflowX; var newOverflowY = nextProps.overflowY; if (newOverflowX !== this.props.overflowX || newOverflowY !== this.props.overflowY) { this._wheelHandler = new ReactWheelHandler(this._onWheel, newOverflowX !== 'hidden', // Should handle horizontal scroll newOverflowY !== 'hidden' // Should handle vertical scroll ); } this.setState(this._calculateState(nextProps, this.state)); }, componentDidUpdate: function componentDidUpdate() { this._reportContentHeight(); }, render: function render() /*object*/{ var state = this.state; var props = this.props; var groupHeader; if (state.useGroupHeader) { groupHeader = React.createElement(FixedDataTableRow, { key: 'group_header', className: joinClasses(cx('fixedDataTableLayout/header'), cx('public/fixedDataTable/header')), data: state.groupHeaderData, width: state.width, height: state.groupHeaderHeight, index: 0, zIndex: 1, offsetTop: 0, scrollLeft: state.scrollX, fixedColumns: state.groupHeaderFixedColumns, scrollableColumns: state.groupHeaderScrollableColumns }); } var maxScrollY = this.state.maxScrollY; var showScrollbarX = state.maxScrollX > 0 && state.overflowX !== 'hidden'; var showScrollbarY = maxScrollY > 0 && state.overflowY !== 'hidden'; var scrollbarXHeight = showScrollbarX ? Scrollbar.SIZE : 0; var scrollbarYHeight = state.height - scrollbarXHeight - 2 * BORDER_HEIGHT - state.footerHeight; var headerOffsetTop = state.useGroupHeader ? state.groupHeaderHeight : 0; var bodyOffsetTop = headerOffsetTop + state.headerHeight; scrollbarYHeight -= bodyOffsetTop; var bottomSectionOffset = 0; var footOffsetTop = props.maxHeight != null ? bodyOffsetTop + state.bodyHeight : bodyOffsetTop + scrollbarYHeight; var rowsContainerHeight = footOffsetTop + state.footerHeight; if (props.ownerHeight !== undefined && props.ownerHeight < state.height) { bottomSectionOffset = props.ownerHeight - state.height; footOffsetTop = Math.min(footOffsetTop, props.ownerHeight - state.footerHeight - scrollbarXHeight); scrollbarYHeight = Math.max(0, footOffsetTop - bodyOffsetTop); } var verticalScrollbar; if (showScrollbarY) { verticalScrollbar = React.createElement(Scrollbar, { size: scrollbarYHeight, contentSize: scrollbarYHeight + maxScrollY, onScroll: this._onVerticalScroll, verticalTop: bodyOffsetTop, position: state.scrollY }); } var horizontalScrollbar; if (showScrollbarX) { var scrollbarXWidth = state.width; horizontalScrollbar = React.createElement(HorizontalScrollbar, { contentSize: scrollbarXWidth + state.maxScrollX, offset: bottomSectionOffset, onScroll: this._onHorizontalScroll, position: state.scrollX, size: scrollbarXWidth }); } var dragKnob = React.createElement(FixedDataTableColumnResizeHandle, { height: state.height, initialWidth: state.columnResizingData.width || 0, minWidth: state.columnResizingData.minWidth || 0, maxWidth: state.columnResizingData.maxWidth || Number.MAX_VALUE, visible: !!state.isColumnResizing, leftOffset: state.columnResizingData.left || 0, knobHeight: state.headerHeight, initialEvent: state.columnResizingData.initialEvent, onColumnResizeEnd: props.onColumnResizeEndCallback, columnKey: state.columnResizingData.key }); var footer = null; if (state.footerHeight) { var footerData = props.footerDataGetter ? props.footerDataGetter() : props.footerData; footer = React.createElement(FixedDataTableRow, { key: 'footer', className: joinClasses(cx('fixedDataTableLayout/footer'), cx('public/fixedDataTable/footer')), data: footerData, fixedColumns: state.footFixedColumns, height: state.footerHeight, index: -1, zIndex: 1, offsetTop: footOffsetTop, scrollableColumns: state.footScrollableColumns, scrollLeft: state.scrollX, width: state.width }); } var rows = this._renderRows(bodyOffsetTop); var header = React.createElement(FixedDataTableRow, { key: 'header', className: joinClasses(cx('fixedDataTableLayout/header'), cx('public/fixedDataTable/header')), data: state.headData, width: state.width, height: state.headerHeight, index: -1, zIndex: 1, offsetTop: headerOffsetTop, scrollLeft: state.scrollX, fixedColumns: state.headFixedColumns, scrollableColumns: state.headScrollableColumns, onColumnResize: this._onColumnResize }); var topShadow; var bottomShadow; if (state.scrollY) { topShadow = React.createElement('div', { className: joinClasses(cx('fixedDataTableLayout/topShadow'), cx('public/fixedDataTable/topShadow')), style: { top: bodyOffsetTop } }); } if (state.ownerHeight != null && state.ownerHeight < state.height && state.scrollContentHeight + state.reservedHeight > state.ownerHeight || state.scrollY < maxScrollY) { bottomShadow = React.createElement('div', { className: joinClasses(cx('fixedDataTableLayout/bottomShadow'), cx('public/fixedDataTable/bottomShadow')), style: { top: footOffsetTop } }); } return React.createElement( 'div', { className: joinClasses(cx('fixedDataTableLayout/main'), cx('public/fixedDataTable/main')), onWheel: this._wheelHandler.onWheel, style: { height: state.height, width: state.width } }, React.createElement( 'div', { className: cx('fixedDataTableLayout/rowsContainer'), style: { height: rowsContainerHeight, width: state.width } }, dragKnob, groupHeader, header, rows, footer, topShadow, bottomShadow ), verticalScrollbar, horizontalScrollbar ); }, _renderRows: function _renderRows( /*number*/offsetTop) /*object*/{ var state = this.state; return React.createElement(FixedDataTableBufferedRows, { defaultRowHeight: state.rowHeight, firstRowIndex: state.firstRowIndex, firstRowOffset: state.firstRowOffset, fixedColumns: state.bodyFixedColumns, height: state.bodyHeight, offsetTop: offsetTop, onRowClick: state.onRowClick, onRowDoubleClick: state.onRowDoubleClick, onRowMouseDown: state.onRowMouseDown, onRowMouseEnter: state.onRowMouseEnter, onRowMouseLeave: state.onRowMouseLeave, rowClassNameGetter: state.rowClassNameGetter, rowsCount: state.rowsCount, rowGetter: state.rowGetter, rowHeightGetter: state.rowHeightGetter, scrollLeft: state.scrollX, scrollableColumns: state.bodyScrollableColumns, showLastRowBorder: true, width: state.width, rowPositionGetter: this._scrollHelper.getRowPosition }); }, /** * This is called when a cell that is in the header of a column has its * resizer knob clicked on. It displays the resizer and puts in the correct * location on the table. */ _onColumnResize: function _onColumnResize( /*number*/combinedWidth, /*number*/leftOffset, /*number*/cellWidth, /*?number*/cellMinWidth, /*?number*/cellMaxWidth, /*number|string*/columnKey, /*object*/event) { this.setState({ isColumnResizing: true, columnResizingData: { left: leftOffset + combinedWidth - cellWidth, width: cellWidth, minWidth: cellMinWidth, maxWidth: cellMaxWidth, initialEvent: { clientX: event.clientX, clientY: event.clientY, preventDefault: emptyFunction }, key: columnKey } }); }, _areColumnSettingsIdentical: function _areColumnSettingsIdentical(oldColumns, newColumns) { if (oldColumns.length !== newColumns.length) { return false; } for (var index = 0; index < oldColumns.length; ++index) { if (!shallowEqual(oldColumns[index].props, newColumns[index].props)) { return false; } } return true; }, _populateColumnsAndColumnData: function _populateColumnsAndColumnData(columns, columnGroups, oldState) { var canReuseColumnSettings = false; var canReuseColumnGroupSettings = false; if (oldState && oldState.columns) { canReuseColumnSettings = this._areColumnSettingsIdentical(columns, oldState.columns); } if (oldState && oldState.columnGroups && columnGroups) { canReuseColumnGroupSettings = this._areColumnSettingsIdentical(columnGroups, oldState.columnGroups); } var columnInfo = {}; if (canReuseColumnSettings) { columnInfo.bodyFixedColumns = oldState.bodyFixedColumns; columnInfo.bodyScrollableColumns = oldState.bodyScrollableColumns; columnInfo.headFixedColumns = oldState.headFixedColumns; columnInfo.headScrollableColumns = oldState.headScrollableColumns; columnInfo.footFixedColumns = oldState.footFixedColumns; columnInfo.footScrollableColumns = oldState.footScrollableColumns; } else { var bodyColumnTypes = this._splitColumnTypes(columns); columnInfo.bodyFixedColumns = bodyColumnTypes.fixed; columnInfo.bodyScrollableColumns = bodyColumnTypes.scrollable; var headColumnTypes = this._splitColumnTypes(this._createHeadColumns(columns)); columnInfo.headFixedColumns = headColumnTypes.fixed; columnInfo.headScrollableColumns = headColumnTypes.scrollable; var footColumnTypes = this._splitColumnTypes(this._createFootColumns(columns)); columnInfo.footFixedColumns = footColumnTypes.fixed; columnInfo.footScrollableColumns = footColumnTypes.scrollable; } if (canReuseColumnGroupSettings) { columnInfo.groupHeaderFixedColumns = oldState.groupHeaderFixedColumns; columnInfo.groupHeaderScrollableColumns = oldState.groupHeaderScrollableColumns; } else { if (columnGroups) { columnInfo.groupHeaderData = this._getGroupHeaderData(columnGroups); columnGroups = this._createGroupHeaderColumns(columnGroups); var groupHeaderColumnTypes = this._splitColumnTypes(columnGroups); columnInfo.groupHeaderFixedColumns = groupHeaderColumnTypes.fixed; columnInfo.groupHeaderScrollableColumns = groupHeaderColumnTypes.scrollable; } } columnInfo.headData = this._getHeadData(columns); return columnInfo; }, _calculateState: function _calculateState( /*object*/props, /*?object*/oldState) /*object*/{ invariant(props.height !== undefined || props.maxHeight !== undefined, 'You must set either a height or a maxHeight'); var children = []; ReactChildren.forEach(props.children, function (child, index) { if (child == null) { return; } invariant(child.type.__TableColumnGroup__ || child.type.__TableColumn__, 'child type should be <FixedDataTableColumn /> or ' + '<FixedDataTableColumnGroup />'); children.push(child); }); var useGroupHeader = false; if (children.length && children[0].type.__TableColumnGroup__) { useGroupHeader = true; } var firstRowIndex = oldState && oldState.firstRowIndex || 0; var firstRowOffset = oldState && oldState.firstRowOffset || 0; var scrollX, scrollY; if (oldState && props.overflowX !== 'hidden') { scrollX = oldState.scrollX; } else { scrollX = props.scrollLeft; } if (oldState && props.overflowY !== 'hidden') { scrollY = oldState.scrollY; } else { scrollState = this._scrollHelper.scrollTo(props.scrollTop); firstRowIndex = scrollState.index; firstRowOffset = scrollState.offset; scrollY = scrollState.position; } if (this._rowToScrollTo !== undefined) { scrollState = this._scrollHelper.scrollRowIntoView(this._rowToScrollTo); firstRowIndex = scrollState.index; firstRowOffset = scrollState.offset; scrollY = scrollState.position; delete this._rowToScrollTo; } var groupHeaderHeight = useGroupHeader ? props.groupHeaderHeight : 0; if (oldState && props.rowsCount !== oldState.rowsCount) { // Number of rows changed, try to scroll to the row from before the // change var viewportHeight = (props.height === undefined ? props.maxHeight : props.height) - (props.headerHeight || 0) - (props.footerHeight || 0) - (props.groupHeaderHeight || 0); this._scrollHelper = new FixedDataTableScrollHelper(props.rowsCount, props.rowHeight, viewportHeight, props.rowHeightGetter); var scrollState = this._scrollHelper.scrollToRow(firstRowIndex, firstRowOffset); firstRowIndex = scrollState.index; firstRowOffset = scrollState.offset; scrollY = scrollState.position; } else if (oldState && props.rowHeightGetter !== oldState.rowHeightGetter) { this._scrollHelper.setRowHeightGetter(props.rowHeightGetter); } var columnResizingData; if (props.isColumnResizing) { columnResizingData = oldState && oldState.columnResizingData; } else { columnResizingData = EMPTY_OBJECT; } var columns; var columnGroups; if (useGroupHeader) { var columnGroupSettings = FixedDataTableWidthHelper.adjustColumnGroupWidths(children, props.width); columns = columnGroupSettings.columns; columnGroups = columnGroupSettings.columnGroups; } else { columns = FixedDataTableWidthHelper.adjustColumnWidths(children, props.width); } var columnInfo = this._populateColumnsAndColumnData(columns, columnGroups, oldState); if (this._columnToScrollTo !== undefined) { // If selected column is a fixed column, don't scroll var fixedColumnsCount = columnInfo.bodyFixedColumns.length; if (this._columnToScrollTo >= fixedColumnsCount) { var totalFixedColumnsWidth = 0; var i, column; for (i = 0; i < columnInfo.bodyFixedColumns.length; ++i) { column = columnInfo.bodyFixedColumns[i]; totalFixedColumnsWidth += column.props.width; } var scrollableColumnIndex = this._columnToScrollTo - fixedColumnsCount; var previousColumnsWidth = 0; for (i = 0; i < scrollableColumnIndex; ++i) { column = columnInfo.bodyScrollableColumns[i]; previousColumnsWidth += column.props.width; } var availableScrollWidth = props.width - totalFixedColumnsWidth; var selectedColumnWidth = columnInfo.bodyScrollableColumns[this._columnToScrollTo - fixedColumnsCount].props.width; var minAcceptableScrollPosition = previousColumnsWidth + selectedColumnWidth - availableScrollWidth; if (scrollX < minAcceptableScrollPosition) { scrollX = minAcceptableScrollPosition; } if (scrollX > previousColumnsWidth) { scrollX = previousColumnsWidth; } } delete this._columnToScrollTo; } var useMaxHeight = props.height === undefined; var height = Math.round(useMaxHeight ? props.maxHeight : props.height); var totalHeightReserved = props.footerHeight + props.headerHeight + groupHeaderHeight + 2 * BORDER_HEIGHT; var bodyHeight = height - totalHeightReserved; var scrollContentHeight = this._scrollHelper.getContentHeight(); var totalHeightNeeded = scrollContentHeight + totalHeightReserved; var scrollContentWidth = FixedDataTableWidthHelper.getTotalWidth(columns); var horizontalScrollbarVisible = scrollContentWidth > props.width && props.overflowX !== 'hidden'; if (horizontalScrollbarVisible) { bodyHeight -= Scrollbar.SIZE; totalHeightNeeded += Scrollbar.SIZE; totalHeightReserved += Scrollbar.SIZE; } var maxScrollX = Math.max(0, scrollContentWidth - props.width); var maxScrollY = Math.max(0, scrollContentHeight - bodyHeight); scrollX = Math.min(scrollX, maxScrollX); scrollY = Math.min(scrollY, maxScrollY); if (!maxScrollY) { // no vertical scrollbar necessary, use the totals we tracked so we // can shrink-to-fit vertically if (useMaxHeight) { height = totalHeightNeeded; } bodyHeight = totalHeightNeeded - totalHeightReserved; } this._scrollHelper.setViewportHeight(bodyHeight); // The order of elements in this object metters and bringing bodyHeight, // height or useGroupHeader to the top can break various features var newState = _extends({ isColumnResizing: oldState && oldState.isColumnResizing }, columnInfo, props, { columns: columns, columnGroups: columnGroups, columnResizingData: columnResizingData, firstRowIndex: firstRowIndex, firstRowOffset: firstRowOffset, horizontalScrollbarVisible: horizontalScrollbarVisible, maxScrollX: maxScrollX, maxScrollY: maxScrollY, reservedHeight: totalHeightReserved, scrollContentHeight: scrollContentHeight, scrollX: scrollX, scrollY: scrollY, // These properties may overwrite properties defined in // columnInfo and props bodyHeight: bodyHeight, height: height, groupHeaderHeight: groupHeaderHeight, useGroupHeader: useGroupHeader }); // Both `headData` and `groupHeaderData` are generated by // `FixedDataTable` will be passed to each header cell to render. // In order to prevent over-rendering the cells, we do not pass the // new `headData` or `groupHeaderData` // if they haven't changed. if (oldState) { if (oldState.headData && newState.headData && shallowEqual(oldState.headData, newState.headData)) { newState.headData = oldState.headData; } if (oldState.groupHeaderData && newState.groupHeaderData && shallowEqual(oldState.groupHeaderData, newState.groupHeaderData)) { newState.groupHeaderData = oldState.groupHeaderData; } } return newState; }, _createGroupHeaderColumns: function _createGroupHeaderColumns( /*array*/columnGroups) /*array*/{ var newColumnGroups = []; for (var i = 0; i < columnGroups.length; ++i) { newColumnGroups[i] = cloneWithProps(columnGroups[i], { dataKey: i, children: undefined, columnData: columnGroups[i].props.columnGroupData, cellRenderer: columnGroups[i].props.groupHeaderRenderer || renderToString, isHeaderCell: true }); } return newColumnGroups; }, _createHeadColumns: function _createHeadColumns( /*array*/columns) /*array*/{ var headColumns = []; for (var i = 0; i < columns.length; ++i) { var columnProps = columns[i].props; headColumns.push(cloneWithProps(columns[i], { cellRenderer: columnProps.headerRenderer || renderToString, columnData: columnProps.columnData, dataKey: columnProps.dataKey, isHeaderCell: true, label: columnProps.label })); } return headColumns; }, _createFootColumns: function _createFootColumns( /*array*/columns) /*array*/{ var footColumns = []; for (var i = 0; i < columns.length; ++i) { var columnProps = columns[i].props; footColumns.push(cloneWithProps(columns[i], { cellRenderer: columnProps.footerRenderer || renderToString, columnData: columnProps.columnData, dataKey: columnProps.dataKey, isFooterCell: true })); } return footColumns; }, _getHeadData: function _getHeadData( /*array*/columns) /*?object*/{ if (!this.props.headerDataGetter) { return null; } var headData = {}; for (var i = 0; i < columns.length; ++i) { var columnProps = columns[i].props; headData[columnProps.dataKey] = this.props.headerDataGetter(columnProps.dataKey); } return headData; }, _getGroupHeaderData: function _getGroupHeaderData( /*array*/columnGroups) /*array*/{ var groupHeaderData = []; for (var i = 0; i < columnGroups.length; ++i) { groupHeaderData[i] = columnGroups[i].props.label || ''; } return groupHeaderData; }, _splitColumnTypes: function _splitColumnTypes( /*array*/columns) /*object*/{ var fixedColumns = []; var scrollableColumns = []; for (var i = 0; i < columns.length; ++i) { if (columns[i].props.fixed) { fixedColumns.push(columns[i]); } else { scrollableColumns.push(columns[i]); } } return { fixed: fixedColumns, scrollable: scrollableColumns }; }, _onWheel: function _onWheel( /*number*/deltaX, /*number*/deltaY) { if (this.isMounted()) { if (!this._isScrolling) { this._didScrollStart(); } var x = this.state.scrollX; if (Math.abs(deltaY) > Math.abs(deltaX) && this.props.overflowY !== 'hidden') { var scrollState = this._scrollHelper.scrollBy(Math.round(deltaY)); var maxScrollY = Math.max(0, scrollState.contentHeight - this.state.bodyHeight); this.setState({ firstRowIndex: scrollState.index, firstRowOffset: scrollState.offset, scrollY: scrollState.position, scrollContentHeight: scrollState.contentHeight, maxScrollY: maxScrollY }); } else if (deltaX && this.props.overflowX !== 'hidden') { x += deltaX; x = x < 0 ? 0 : x; x = x > this.state.maxScrollX ? this.state.maxScrollX : x; this.setState({ scrollX: x }); } this._didScrollStop(); } }, _onHorizontalScroll: function _onHorizontalScroll( /*number*/scrollPos) { if (this.isMounted() && scrollPos !== this.state.scrollX) { if (!this._isScrolling) { this._didScrollStart(); } this.setState({ scrollX: scrollPos }); this._didScrollStop(); } }, _onVerticalScroll: function _onVerticalScroll( /*number*/scrollPos) { if (this.isMounted() && scrollPos !== this.state.scrollY) { if (!this._isScrolling) { this._didScrollStart(); } var scrollState = this._scrollHelper.scrollTo(Math.round(scrollPos)); this.setState({ firstRowIndex: scrollState.index, firstRowOffset: scrollState.offset, scrollY: scrollState.position, scrollContentHeight: scrollState.contentHeight }); this._didScrollStop(); } }, _didScrollStart: function _didScrollStart() { if (this.isMounted() && !this._isScrolling) { this._isScrolling = true; if (this.props.onScrollStart) { this.props.onScrollStart(this.state.scrollX, this.state.scrollY); } } }, _didScrollStop: function _didScrollStop() { if (this.isMounted() && this._isScrolling) { this._isScrolling = false; if (this.props.onScrollEnd) { this.props.onScrollEnd(this.state.scrollX, this.state.scrollY); } } } }); var HorizontalScrollbar = React.createClass({ displayName: 'HorizontalScrollbar', mixins: [ReactComponentWithPureRenderMixin], propTypes: { contentSize: PropTypes.number.isRequired, offset: PropTypes.number.isRequired, onScroll: PropTypes.func.isRequired, position: PropTypes.number.isRequired, size: PropTypes.number.isRequired }, render: function render() /*object*/{ var outerContainerStyle = { height: Scrollbar.SIZE, width: this.props.size }; var innerContainerStyle = { height: Scrollbar.SIZE, position: 'absolute', overflow: 'hidden', width: this.props.size }; translateDOMPositionXY(innerContainerStyle, 0, this.props.offset); return React.createElement( 'div', { className: joinClasses(cx('fixedDataTableLayout/horizontalScrollbar'), cx('public/fixedDataTable/horizontalScrollbar')), style: outerContainerStyle }, React.createElement( 'div', { style: innerContainerStyle }, React.createElement(Scrollbar, _extends({}, this.props, { isOpaque: true, orientation: 'horizontal', offset: undefined })) ) ); } }); module.exports = FixedDataTable; // isColumnResizing should be overwritten by value from props if // avaialble /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableWidthHelper * @typechecks */ 'use strict'; var React = __webpack_require__(28); var cloneWithProps = __webpack_require__(30); function getTotalWidth( /*array*/columns) /*number*/{ var totalWidth = 0; for (var i = 0; i < columns.length; ++i) { totalWidth += columns[i].props.width; } return totalWidth; } function getTotalFlexGrow( /*array*/columns) /*number*/{ var totalFlexGrow = 0; for (var i = 0; i < columns.length; ++i) { totalFlexGrow += columns[i].props.flexGrow || 0; } return totalFlexGrow; } function distributeFlexWidth( /*array*/columns, /*number*/flexWidth) /*object*/{ if (flexWidth <= 0) { return { columns: columns, width: getTotalWidth(columns) }; } var remainingFlexGrow = getTotalFlexGrow(columns); var remainingFlexWidth = flexWidth; var newColumns = []; var totalWidth = 0; for (var i = 0; i < columns.length; ++i) { var column = columns[i]; if (!column.props.flexGrow) { totalWidth += column.props.width; newColumns.push(column); continue; } var columnFlexWidth = Math.floor(column.props.flexGrow / remainingFlexGrow * remainingFlexWidth); var newColumnWidth = Math.floor(column.props.width + columnFlexWidth); totalWidth += newColumnWidth; remainingFlexGrow -= column.props.flexGrow; remainingFlexWidth -= columnFlexWidth; newColumns.push(cloneWithProps(column, { width: newColumnWidth })); } return { columns: newColumns, width: totalWidth }; } function adjustColumnGroupWidths( /*array*/columnGroups, /*number*/expectedWidth) /*object*/{ var allColumns = []; var i; for (i = 0; i < columnGroups.length; ++i) { React.Children.forEach(columnGroups[i].props.children, function (column) { allColumns.push(column); }); } var columnsWidth = getTotalWidth(allColumns); var remainingFlexGrow = getTotalFlexGrow(allColumns); var remainingFlexWidth = Math.max(expectedWidth - columnsWidth, 0); var newAllColumns = []; var newColumnGroups = []; for (i = 0; i < columnGroups.length; ++i) { var columnGroup = columnGroups[i]; var currentColumns = []; React.Children.forEach(columnGroup.props.children, function (column) { currentColumns.push(column); }); var columnGroupFlexGrow = getTotalFlexGrow(currentColumns); var columnGroupFlexWidth = Math.floor(columnGroupFlexGrow / remainingFlexGrow * remainingFlexWidth); var newColumnSettings = distributeFlexWidth(currentColumns, columnGroupFlexWidth); remainingFlexGrow -= columnGroupFlexGrow; remainingFlexWidth -= columnGroupFlexWidth; for (var j = 0; j < newColumnSettings.columns.length; ++j) { newAllColumns.push(newColumnSettings.columns[j]); } newColumnGroups.push(cloneWithProps(columnGroup, { width: newColumnSettings.width })); } return { columns: newAllColumns, columnGroups: newColumnGroups }; } function adjustColumnWidths( /*array*/columns, /*number*/expectedWidth) /*array*/{ var columnsWidth = getTotalWidth(columns); if (columnsWidth < expectedWidth) { return distributeFlexWidth(columns, expectedWidth - columnsWidth).columns; } return columns; } var FixedDataTableWidthHelper = { getTotalWidth: getTotalWidth, getTotalFlexGrow: getTotalFlexGrow, distributeFlexWidth: distributeFlexWidth, adjustColumnWidths: adjustColumnWidths, adjustColumnGroupWidths: adjustColumnGroupWidths }; module.exports = FixedDataTableWidthHelper; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule React */ 'use strict'; module.exports = __webpack_require__(29); /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_29__; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule cloneWithProps */ 'use strict'; module.exports = __webpack_require__(31); /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only * @providesModule cloneWithProps */ 'use strict'; var ReactElement = __webpack_require__(33); var ReactPropTransferer = __webpack_require__(40); var keyOf = __webpack_require__(42); var warning = __webpack_require__(37); var CHILDREN_PROP = keyOf({children: null}); /** * Sometimes you want to change the props of a child passed to you. Usually * this is to add a CSS class. * * @param {ReactElement} child child element you'd like to clone * @param {object} props props you'd like to modify. className and style will be * merged automatically. * @return {ReactElement} a clone of child with props merged in. */ function cloneWithProps(child, props) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( !child.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.' ) : null); } var newProps = ReactPropTransferer.mergeProps(props, child.props); // Use `child.props.children` if it is provided. if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { newProps.children = child.props.children; } // The current API doesn't retain _owner and _context, which is why this // doesn't use ReactElement.cloneAndReplaceProps. return ReactElement.createElement(child.type, newProps); } module.exports = cloneWithProps; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { currentQueue[queueIndex].run(); } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ 'use strict'; var ReactContext = __webpack_require__(34); var ReactCurrentOwner = __webpack_require__(39); var assign = __webpack_require__(35); var warning = __webpack_require__(37); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== process.env.NODE_ENV ? warning( false, 'Don\'t set the %s property of the React element. Instead, ' + 'specify the correct value when initially creating the element.', key ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== process.env.NODE_ENV) { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = {props: props, originalProps: assign({}, props)}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if ("production" !== process.env.NODE_ENV) { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if ("production" !== process.env.NODE_ENV) { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function(element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return new ReactElement( element.type, key, ref, owner, element._context, props ); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactContext */ 'use strict'; var assign = __webpack_require__(35); var emptyObject = __webpack_require__(36); var warning = __webpack_require__(37); var didWarn = false; /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: emptyObject, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'}, () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( didWarn, 'withContext is deprecated and will be removed in a future version. ' + 'Use a wrapper component with getChildContext instead.' ) : null); didWarn = true; } var result; var previousContext = ReactContext.current; ReactContext.current = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyObject */ "use strict"; var emptyObject = {}; if ("production" !== process.env.NODE_ENV) { Object.freeze(emptyObject); } module.exports = emptyObject; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule warning */ "use strict"; var emptyFunction = __webpack_require__(38); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("production" !== process.env.NODE_ENV) { warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || /^[s\W]*$/.test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];}); console.warn(message); try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function() { return this; }; emptyFunction.thatReturnsArgument = function(arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTransferer */ 'use strict'; var assign = __webpack_require__(35); var emptyFunction = __webpack_require__(38); var joinClasses = __webpack_require__(41); /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return assign({}, b, a); }); /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { return transferInto(assign({}, oldProps), newProps); } }; module.exports = ReactPropTransferer; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule joinClasses * @typechecks static-only */ 'use strict'; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} classes * @return {string} */ function joinClasses(className/*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableHelper * @typechecks */ 'use strict'; var Locale = __webpack_require__(44); var React = __webpack_require__(28); var FixedDataTableColumnGroup = __webpack_require__(45); var FixedDataTableColumn = __webpack_require__(46); var cloneWithProps = __webpack_require__(30); var DIR_SIGN = Locale.isRTL() ? -1 : +1; // A cell up to 5px outside of the visible area will still be considered visible var CELL_VISIBILITY_TOLERANCE = 5; // used for flyouts function renderToString(value) /*string*/{ if (value === null || value === undefined) { return ''; } else { return String(value); } } /** * Helper method to execute a callback against all columns given the children * of a table. * @param {?object|array} children * Children of a table. * @param {function} callback * Function to excecute for each column. It is passed the column. */ function forEachColumn(children, callback) { React.Children.forEach(children, function (child) { if (child.type === FixedDataTableColumnGroup) { forEachColumn(child.props.children, callback); } else if (child.type === FixedDataTableColumn) { callback(child); } }); } /** * Helper method to map columns to new columns. This takes into account column * groups and will generate a new column group if its columns change. * @param {?object|array} children * Children of a table. * @param {function} callback * Function to excecute for each column. It is passed the column and should * return a result column. */ function mapColumns(children, callback) { var newChildren = []; React.Children.forEach(children, function (originalChild) { var newChild = originalChild; // The child is either a column group or a column. If it is a column group // we need to iterate over its columns and then potentially generate a // new column group if (originalChild.type === FixedDataTableColumnGroup) { var haveColumnsChanged = false; var newColumns = []; forEachColumn(originalChild.props.children, function (originalcolumn) { var newColumn = callback(originalcolumn); if (newColumn !== originalcolumn) { haveColumnsChanged = true; } newColumns.push(newColumn); }); // If the column groups columns have changed clone the group and supply // new children if (haveColumnsChanged) { newChild = cloneWithProps(originalChild, { key: originalChild.key, children: newColumns }); } } else if (originalChild.type === FixedDataTableColumn) { newChild = callback(originalChild); } newChildren.push(newChild); }); return newChildren; } var FixedDataTableHelper = { DIR_SIGN: DIR_SIGN, CELL_VISIBILITY_TOLERANCE: CELL_VISIBILITY_TOLERANCE, renderToString: renderToString, forEachColumn: forEachColumn, mapColumns: mapColumns }; module.exports = FixedDataTableHelper; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Locale */ "use strict"; // Hard code this for now. var Locale = { isRTL: function isRTL() { return false; }, getDirection: function getDirection() { return "LTR"; } }; module.exports = Locale; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableColumnGroup.react * @typechecks */ 'use strict'; var React = __webpack_require__(28); var PropTypes = React.PropTypes; /** * Component that defines the attributes of a table column group. */ var FixedDataTableColumnGroup = React.createClass({ displayName: 'FixedDataTableColumnGroup', statics: { __TableColumnGroup__: true }, propTypes: { /** * The horizontal alignment of the table cell content. */ align: PropTypes.oneOf(['left', 'center', 'right']), /** * Controls if the column group is fixed when scrolling in the X axis. */ fixed: PropTypes.bool, /** * Bucket for any data to be passed into column group renderer functions. */ columnGroupData: PropTypes.object, /** * The column group's header label. */ label: PropTypes.string, /** * The cell renderer that returns React-renderable content for a table * column group header. If it's not specified, the label from props will * be rendered as header content. * ``` * function( * label: ?string, * cellDataKey: string, * columnGroupData: any, * rowData: array<?object>, // array of labels of all columnGroups * width: number * ): ?$jsx * ``` */ groupHeaderRenderer: PropTypes.func }, getDefaultProps: function getDefaultProps() /*object*/{ return { fixed: false }; }, render: function render() { if (true) { throw new Error('Component <FixedDataTableColumnGroup /> should never render'); } return null; } }); module.exports = FixedDataTableColumnGroup; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableColumn.react * @typechecks */ 'use strict'; var React = __webpack_require__(28); var PropTypes = React.PropTypes; /** * Component that defines the attributes of table column. */ var FixedDataTableColumn = React.createClass({ displayName: 'FixedDataTableColumn', statics: { __TableColumn__: true }, propTypes: { /** * The horizontal alignment of the table cell content. */ align: PropTypes.oneOf(['left', 'center', 'right']), /** * className for this column's header cell. */ headerClassName: PropTypes.string, /** * className for this column's footer cell. */ footerClassName: PropTypes.string, /** * className for each of this column's data cells. */ cellClassName: PropTypes.string, /** * The cell renderer that returns React-renderable content for table cell. * ``` * function( * cellData: any, * cellDataKey: string, * rowData: object, * rowIndex: number, * columnData: any, * width: number * ): ?$jsx * ``` */ cellRenderer: PropTypes.func, /** * The getter `function(string_cellDataKey, object_rowData)` that returns * the cell data for the `cellRenderer`. * If not provided, the cell data will be collected from * `rowData[cellDataKey]` instead. The value that `cellDataGetter` returns * will be used to determine whether the cell should re-render. */ cellDataGetter: PropTypes.func, /** * The key to retrieve the cell data from the data row. Provided key type * must be either `string` or `number`. Since we use this * for keys, it must be specified for each column. */ dataKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, /** * Controls if the column is fixed when scrolling in the X axis. */ fixed: PropTypes.bool, /** * The cell renderer that returns React-renderable content for table column * header. * ``` * function( * label: ?string, * cellDataKey: string, * columnData: any, * rowData: array<?object>, * width: number * ): ?$jsx * ``` */ headerRenderer: PropTypes.func, /** * The cell renderer that returns React-renderable content for table column * footer. * ``` * function( * label: ?string, * cellDataKey: string, * columnData: any, * rowData: array<?object>, * width: number * ): ?$jsx * ``` */ footerRenderer: PropTypes.func, /** * Bucket for any data to be passed into column renderer functions. */ columnData: PropTypes.object, /** * The column's header label. */ label: PropTypes.string, /** * The pixel width of the column. */ width: PropTypes.number.isRequired, /** * If this is a resizable column this is its minimum pixel width. */ minWidth: PropTypes.number, /** * If this is a resizable column this is its maximum pixel width. */ maxWidth: PropTypes.number, /** * The grow factor relative to other columns. Same as the flex-grow API * from http://www.w3.org/TR/css3-flexbox/. Basically, take any available * extra width and distribute it proportionally according to all columns' * flexGrow values. Defaults to zero (no-flexing). */ flexGrow: PropTypes.number, /** * Whether the column can be resized with the * FixedDataTableColumnResizeHandle. Please note that if a column * has a flex grow, once you resize the column this will be set to 0. * * This property only provides the UI for the column resizing. If this * is set to true, you will need ot se the onColumnResizeEndCallback table * property and render your columns appropriately. */ isResizable: PropTypes.bool, /** * Experimental feature * Whether cells in this column can be removed from document when outside * of viewport as a result of horizontal scrolling. * Setting this property to true allows the table to not render cells in * particular column that are outside of viewport for visible rows. This * allows to create table with many columns and not have vertical scrolling * performance drop. * Setting the property to false will keep previous behaviour and keep * cell rendered if the row it belongs to is visible. */ allowCellsRecycling: PropTypes.bool }, getDefaultProps: function getDefaultProps() /*object*/{ return { allowCellsRecycling: false, fixed: false }; }, render: function render() { if (true) { throw new Error('Component <FixedDataTableColumn /> should never render'); } return null; } }); module.exports = FixedDataTableColumn; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentWithPureRenderMixin */ 'use strict'; module.exports = __webpack_require__(48); /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentWithPureRenderMixin */ 'use strict'; var shallowEqual = __webpack_require__(49); /** * If your React component's render function is "pure", e.g. it will render the * same result given the same props and state, provide this Mixin for a * considerable performance boost. * * Most React components have pure render functions. * * Example: * * var ReactComponentWithPureRenderMixin = * require('ReactComponentWithPureRenderMixin'); * React.createClass({ * mixins: [ReactComponentWithPureRenderMixin], * * render: function() { * return <div className={this.props.className}>foo</div>; * } * }); * * Note: This only checks shallow equality for props and state. If these contain * complex data structures this mixin may have false-negatives for deeper * differences. Only mixin to components which have simple props and state, or * use `forceUpdate()` when you know deep data structures have changed. */ var ReactComponentWithPureRenderMixin = { shouldComponentUpdate: function(nextProps, nextState) { return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); } }; module.exports = ReactComponentWithPureRenderMixin; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual */ 'use strict'; /** * Performs equality by iterating through keys on an object and returning * false when any key has values which are not strictly equal between * objA and objB. Returns true when the values of all keys are strictly equal. * * @return {boolean} */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } var key; // Test for A's keys different from B. for (key in objA) { if (objA.hasOwnProperty(key) && (!objB.hasOwnProperty(key) || objA[key] !== objB[key])) { return false; } } // Test for B's keys missing from A. for (key in objB) { if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * This is utility that hanlds onWheel events and calls provided wheel * callback with correct frame rate. * * @providesModule ReactWheelHandler * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var emptyFunction = __webpack_require__(51); var normalizeWheel = __webpack_require__(52); var requestAnimationFramePolyfill = __webpack_require__(56); var ReactWheelHandler = (function () { /** * onWheel is the callback that will be called with right frame rate if * any wheel events happened * onWheel should is to be called with two arguments: deltaX and deltaY in * this order */ function ReactWheelHandler( /*function*/onWheel, /*boolean|function*/handleScrollX, /*boolean|function*/handleScrollY, /*?boolean|?function*/stopPropagation) { _classCallCheck(this, ReactWheelHandler); this._animationFrameID = null; this._deltaX = 0; this._deltaY = 0; this._didWheel = this._didWheel.bind(this); if (typeof handleScrollX !== 'function') { handleScrollX = handleScrollX ? emptyFunction.thatReturnsTrue : emptyFunction.thatReturnsFalse; } if (typeof handleScrollY !== 'function') { handleScrollY = handleScrollY ? emptyFunction.thatReturnsTrue : emptyFunction.thatReturnsFalse; } if (typeof stopPropagation !== 'function') { stopPropagation = stopPropagation ? emptyFunction.thatReturnsTrue : emptyFunction.thatReturnsFalse; } this._handleScrollX = handleScrollX; this._handleScrollY = handleScrollY; this._stopPropagation = stopPropagation; this._onWheelCallback = onWheel; this.onWheel = this.onWheel.bind(this); } _createClass(ReactWheelHandler, [{ key: 'onWheel', value: function onWheel( /*object*/event) { var normalizedEvent = normalizeWheel(event); var deltaX = this._deltaX + normalizedEvent.pixelX; var deltaY = this._deltaY + normalizedEvent.pixelY; var handleScrollX = this._handleScrollX(deltaX, deltaY); var handleScrollY = this._handleScrollY(deltaY, deltaX); if (!handleScrollX && !handleScrollY) { return; } this._deltaX += handleScrollX ? normalizedEvent.pixelX : 0; this._deltaY += handleScrollY ? normalizedEvent.pixelY : 0; event.preventDefault(); var changed; if (this._deltaX !== 0 || this._deltaY !== 0) { if (this._stopPropagation()) { event.stopPropagation(); } changed = true; } if (changed === true && this._animationFrameID === null) { this._animationFrameID = requestAnimationFramePolyfill(this._didWheel); } } }, { key: '_didWheel', value: function _didWheel() { this._animationFrameID = null; this._onWheelCallback(this._deltaX, this._deltaY); this._deltaX = 0; this._deltaY = 0; } }]); return ReactWheelHandler; })(); module.exports = ReactWheelHandler; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ "use strict"; function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule normalizeWheel * @typechecks */ 'use strict'; var UserAgent_DEPRECATED = __webpack_require__(53); var isEventSupported = __webpack_require__(54); // Reasonable defaults var PIXEL_STEP = 10; var LINE_HEIGHT = 40; var PAGE_HEIGHT = 800; /** * Mouse wheel (and 2-finger trackpad) support on the web sucks. It is * complicated, thus this doc is long and (hopefully) detailed enough to answer * your questions. * * If you need to react to the mouse wheel in a predictable way, this code is * like your bestest friend. * hugs * * * As of today, there are 4 DOM event types you can listen to: * * 'wheel' -- Chrome(31+), FF(17+), IE(9+) * 'mousewheel' -- Chrome, IE(6+), Opera, Safari * 'MozMousePixelScroll' -- FF(3.5 only!) (2010-2013) -- don't bother! * 'DOMMouseScroll' -- FF(0.9.7+) since 2003 * * So what to do? The is the best: * * normalizeWheel.getEventType(); * * In your event callback, use this code to get sane interpretation of the * deltas. This code will return an object with properties: * * spinX -- normalized spin speed (use for zoom) - x plane * spinY -- " - y plane * pixelX -- normalized distance (to pixels) - x plane * pixelY -- " - y plane * * Wheel values are provided by the browser assuming you are using the wheel to * scroll a web page by a number of lines or pixels (or pages). Values can vary * significantly on different platforms and browsers, forgetting that you can * scroll at different speeds. Some devices (like trackpads) emit more events * at smaller increments with fine granularity, and some emit massive jumps with * linear speed or acceleration. * * This code does its best to normalize the deltas for you: * * - spin is trying to normalize how far the wheel was spun (or trackpad * dragged). This is super useful for zoom support where you want to * throw away the chunky scroll steps on the PC and make those equal to * the slow and smooth tiny steps on the Mac. Key data: This code tries to * resolve a single slow step on a wheel to 1. * * - pixel is normalizing the desired scroll delta in pixel units. You'll * get the crazy differences between browsers, but at least it'll be in * pixels! * * - positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This * should translate to positive value zooming IN, negative zooming OUT. * This matches the newer 'wheel' event. * * Why are there spinX, spinY (or pixels)? * * - spinX is a 2-finger side drag on the trackpad, and a shift + wheel turn * with a mouse. It results in side-scrolling in the browser by default. * * - spinY is what you expect -- it's the classic axis of a mouse wheel. * * - I dropped spinZ/pixelZ. It is supported by the DOM 3 'wheel' event and * probably is by browsers in conjunction with fancy 3D controllers .. but * you know. * * Implementation info: * * Examples of 'wheel' event if you scroll slowly (down) by one step with an * average mouse: * * OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120) * OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12) * OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A) * Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120) * Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120) * * On the trackpad: * * OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6) * OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A) * * On other/older browsers.. it's more complicated as there can be multiple and * also missing delta values. * * The 'wheel' event is more standard: * * http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents * * The basics is that it includes a unit, deltaMode (pixels, lines, pages), and * deltaX, deltaY and deltaZ. Some browsers provide other values to maintain * backward compatibility with older events. Those other values help us * better normalize spin speed. Example of what the browsers provide: * * | event.wheelDelta | event.detail * ------------------+------------------+-------------- * Safari v5/OS X | -120 | 0 * Safari v5/Win7 | -120 | 0 * Chrome v17/OS X | -120 | 0 * Chrome v17/Win7 | -120 | 0 * IE9/Win7 | -120 | undefined * Firefox v4/OS X | undefined | 1 * Firefox v4/Win7 | undefined | 3 * */ function normalizeWheel( /*object*/event) /*object*/{ var sX = 0, sY = 0, // spinX, spinY pX = 0, pY = 0; // pixelX, pixelY // Legacy if ('detail' in event) { sY = event.detail; } if ('wheelDelta' in event) { sY = -event.wheelDelta / 120; } if ('wheelDeltaY' in event) { sY = -event.wheelDeltaY / 120; } if ('wheelDeltaX' in event) { sX = -event.wheelDeltaX / 120; } // side scrolling on FF with DOMMouseScroll if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) { sX = sY; sY = 0; } pX = sX * PIXEL_STEP; pY = sY * PIXEL_STEP; if ('deltaY' in event) { pY = event.deltaY; } if ('deltaX' in event) { pX = event.deltaX; } if ((pX || pY) && event.deltaMode) { if (event.deltaMode == 1) { // delta in LINE units pX *= LINE_HEIGHT; pY *= LINE_HEIGHT; } else { // delta in PAGE units pX *= PAGE_HEIGHT; pY *= PAGE_HEIGHT; } } // Fall-back if spin cannot be determined if (pX && !sX) { sX = pX < 1 ? -1 : 1; } if (pY && !sY) { sY = pY < 1 ? -1 : 1; } return { spinX: sX, spinY: sY, pixelX: pX, pixelY: pY }; } /** * The best combination if you prefer spinX + spinY normalization. It favors * the older DOMMouseScroll for Firefox, as FF does not include wheelDelta with * 'wheel' event, making spin speed determination impossible. */ normalizeWheel.getEventType = function () /*string*/{ return UserAgent_DEPRECATED.firefox() ? 'DOMMouseScroll' : isEventSupported('wheel') ? 'wheel' : 'mousewheel'; }; module.exports = normalizeWheel; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2004-present Facebook. All Rights Reserved. * * @providesModule UserAgent_DEPRECATED */ /** * Provides entirely client-side User Agent and OS detection. You should prefer * the non-deprecated UserAgent module when possible, which exposes our * authoritative server-side PHP-based detection to the client. * * Usage is straightforward: * * if (UserAgent_DEPRECATED.ie()) { * // IE * } * * You can also do version checks: * * if (UserAgent_DEPRECATED.ie() >= 7) { * // IE7 or better * } * * The browser functions will return NaN if the browser does not match, so * you can also do version compares the other way: * * if (UserAgent_DEPRECATED.ie() < 7) { * // IE6 or worse * } * * Note that the version is a float and may include a minor version number, * so you should always use range operators to perform comparisons, not * strict equality. * * **Note:** You should **strongly** prefer capability detection to browser * version detection where it's reasonable: * * http://www.quirksmode.org/js/support.html * * Further, we have a large number of mature wrapper functions and classes * which abstract away many browser irregularities. Check the documentation, * grep for things, or ask on [email protected] before writing yet * another copy of "event || window.event". * */ 'use strict'; var _populated = false; // Browsers var _ie, _firefox, _opera, _webkit, _chrome; // Actual IE browser for compatibility mode var _ie_real_version; // Platforms var _osx, _windows, _linux, _android; // Architectures var _win64; // Devices var _iphone, _ipad, _native; var _mobile; function _populate() { if (_populated) { return; } _populated = true; // To work around buggy JS libraries that can't handle multi-digit // version numbers, Opera 10's user agent string claims it's Opera // 9, then later includes a Version/X.Y field: // // Opera/9.80 (foo) Presto/2.2.15 Version/10.10 var uas = navigator.userAgent; var agent = /(?:MSIE.(\d+\.\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\d+\.\d+))|(?:Opera(?:.+Version.|.)(\d+\.\d+))|(?:AppleWebKit.(\d+(?:\.\d+)?))|(?:Trident\/\d+\.\d+.*rv:(\d+\.\d+))/.exec(uas); var os = /(Mac OS X)|(Windows)|(Linux)/.exec(uas); _iphone = /\b(iPhone|iP[ao]d)/.exec(uas); _ipad = /\b(iP[ao]d)/.exec(uas); _android = /Android/i.exec(uas); _native = /FBAN\/\w+;/i.exec(uas); _mobile = /Mobile/i.exec(uas); // Note that the IE team blog would have you believe you should be checking // for 'Win64; x64'. But MSDN then reveals that you can actually be coming // from either x64 or ia64; so ultimately, you should just check for Win64 // as in indicator of whether you're in 64-bit IE. 32-bit IE on 64-bit // Windows will send 'WOW64' instead. _win64 = !!/Win64/.exec(uas); if (agent) { _ie = agent[1] ? parseFloat(agent[1]) : agent[5] ? parseFloat(agent[5]) : NaN; // IE compatibility mode if (_ie && document && document.documentMode) { _ie = document.documentMode; } // grab the "true" ie version from the trident token if available var trident = /(?:Trident\/(\d+.\d+))/.exec(uas); _ie_real_version = trident ? parseFloat(trident[1]) + 4 : _ie; _firefox = agent[2] ? parseFloat(agent[2]) : NaN; _opera = agent[3] ? parseFloat(agent[3]) : NaN; _webkit = agent[4] ? parseFloat(agent[4]) : NaN; if (_webkit) { // We do not add the regexp to the above test, because it will always // match 'safari' only since 'AppleWebKit' appears before 'Chrome' in // the userAgent string. agent = /(?:Chrome\/(\d+\.\d+))/.exec(uas); _chrome = agent && agent[1] ? parseFloat(agent[1]) : NaN; } else { _chrome = NaN; } } else { _ie = _firefox = _opera = _chrome = _webkit = NaN; } if (os) { if (os[1]) { // Detect OS X version. If no version number matches, set _osx to true. // Version examples: 10, 10_6_1, 10.7 // Parses version number as a float, taking only first two sets of // digits. If only one set of digits is found, returns just the major // version number. var ver = /(?:Mac OS X (\d+(?:[._]\d+)?))/.exec(uas); _osx = ver ? parseFloat(ver[1].replace('_', '.')) : true; } else { _osx = false; } _windows = !!os[2]; _linux = !!os[3]; } else { _osx = _windows = _linux = false; } } var UserAgent_DEPRECATED = { /** * Check if the UA is Internet Explorer. * * * @return float|NaN Version number (if match) or NaN. */ ie: function ie() { return _populate() || _ie; }, /** * Check if we're in Internet Explorer compatibility mode. * * @return bool true if in compatibility mode, false if * not compatibility mode or not ie */ ieCompatibilityMode: function ieCompatibilityMode() { return _populate() || _ie_real_version > _ie; }, /** * Whether the browser is 64-bit IE. Really, this is kind of weak sauce; we * only need this because Skype can't handle 64-bit IE yet. We need to remove * this when we don't need it -- tracked by #601957. */ ie64: function ie64() { return UserAgent_DEPRECATED.ie() && _win64; }, /** * Check if the UA is Firefox. * * * @return float|NaN Version number (if match) or NaN. */ firefox: function firefox() { return _populate() || _firefox; }, /** * Check if the UA is Opera. * * * @return float|NaN Version number (if match) or NaN. */ opera: function opera() { return _populate() || _opera; }, /** * Check if the UA is WebKit. * * * @return float|NaN Version number (if match) or NaN. */ webkit: function webkit() { return _populate() || _webkit; }, /** * For Push * WILL BE REMOVED VERY SOON. Use UserAgent_DEPRECATED.webkit */ safari: function safari() { return UserAgent_DEPRECATED.webkit(); }, /** * Check if the UA is a Chrome browser. * * * @return float|NaN Version number (if match) or NaN. */ chrome: function chrome() { return _populate() || _chrome; }, /** * Check if the user is running Windows. * * @return bool `true' if the user's OS is Windows. */ windows: function windows() { return _populate() || _windows; }, /** * Check if the user is running Mac OS X. * * @return float|bool Returns a float if a version number is detected, * otherwise true/false. */ osx: function osx() { return _populate() || _osx; }, /** * Check if the user is running Linux. * * @return bool `true' if the user's OS is some flavor of Linux. */ linux: function linux() { return _populate() || _linux; }, /** * Check if the user is running on an iPhone or iPod platform. * * @return bool `true' if the user is running some flavor of the * iPhone OS. */ iphone: function iphone() { return _populate() || _iphone; }, mobile: function mobile() { return _populate() || (_iphone || _ipad || _android || _mobile); }, nativeApp: function nativeApp() { // webviews inside of the native apps return _populate() || _native; }, android: function android() { return _populate() || _android; }, ipad: function ipad() { return _populate() || _ipad; } }; module.exports = UserAgent_DEPRECATED; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ 'use strict'; var ExecutionEnvironment = __webpack_require__(55); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = (eventName in document); if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ /*jslint evil: true */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule requestAnimationFramePolyfill */ 'use strict'; var emptyFunction = __webpack_require__(51); var nativeRequestAnimationFrame = __webpack_require__(57); var lastTime = 0; /** * Here is the native and polyfill version of requestAnimationFrame. * Please don't use it directly and use requestAnimationFrame module instead. */ var requestAnimationFrame = nativeRequestAnimationFrame || function (callback) { var currTime = Date.now(); var timeDelay = Math.max(0, 16 - (currTime - lastTime)); lastTime = currTime + timeDelay; return global.setTimeout(function () { callback(Date.now()); }, timeDelay); }; // Works around a rare bug in Safari 6 where the first request is never invoked. requestAnimationFrame(emptyFunction); module.exports = requestAnimationFrame; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule nativeRequestAnimationFrame */ "use strict"; var nativeRequestAnimationFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame || global.msRequestAnimationFrame; module.exports = nativeRequestAnimationFrame; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Scrollbar.react * @typechecks */ 'use strict'; var DOMMouseMoveTracker = __webpack_require__(59); var Keys = __webpack_require__(62); var React = __webpack_require__(28); var ReactComponentWithPureRenderMixin = __webpack_require__(47); var ReactWheelHandler = __webpack_require__(50); var cssVar = __webpack_require__(63); var cx = __webpack_require__(64); var emptyFunction = __webpack_require__(51); var translateDOMPositionXY = __webpack_require__(65); var PropTypes = React.PropTypes; var UNSCROLLABLE_STATE = { position: 0, scrollable: false }; var FACE_MARGIN = parseInt(cssVar('scrollbar-face-margin'), 10); var FACE_MARGIN_2 = FACE_MARGIN * 2; var FACE_SIZE_MIN = 30; var KEYBOARD_SCROLL_AMOUNT = 40; var _lastScrolledScrollbar = null; var Scrollbar = React.createClass({ displayName: 'Scrollbar', mixins: [ReactComponentWithPureRenderMixin], propTypes: { contentSize: PropTypes.number.isRequired, defaultPosition: PropTypes.number, isOpaque: PropTypes.bool, orientation: PropTypes.oneOf(['vertical', 'horizontal']), onScroll: PropTypes.func, position: PropTypes.number, size: PropTypes.number.isRequired, trackColor: PropTypes.oneOf(['gray']), zIndex: PropTypes.number, verticalTop: PropTypes.number }, getInitialState: function getInitialState() /*object*/{ var props = this.props; return this._calculateState(props.position || props.defaultPosition || 0, props.size, props.contentSize, props.orientation); }, componentWillReceiveProps: function componentWillReceiveProps( /*object*/nextProps) { var controlledPosition = nextProps.position; if (controlledPosition === undefined) { this._setNextState(this._calculateState(this.state.position, nextProps.size, nextProps.contentSize, nextProps.orientation)); } else { this._setNextState(this._calculateState(controlledPosition, nextProps.size, nextProps.contentSize, nextProps.orientation), nextProps); } }, getDefaultProps: function getDefaultProps() /*object*/{ return { defaultPosition: 0, isOpaque: false, onScroll: emptyFunction, orientation: 'vertical', zIndex: 99 }; }, render: function render() /*?object*/{ if (!this.state.scrollable) { return null; } var size = this.props.size; var mainStyle; var faceStyle; var isHorizontal = this.state.isHorizontal; var isVertical = !isHorizontal; var isActive = this.state.focused || this.state.isDragging; var faceSize = this.state.faceSize; var isOpaque = this.props.isOpaque; var verticalTop = this.props.verticalTop || 0; var mainClassName = cx({ 'ScrollbarLayout/main': true, 'ScrollbarLayout/mainVertical': isVertical, 'ScrollbarLayout/mainHorizontal': isHorizontal, 'public/Scrollbar/main': true, 'public/Scrollbar/mainOpaque': isOpaque, 'public/Scrollbar/mainActive': isActive }); var faceClassName = cx({ 'ScrollbarLayout/face': true, 'ScrollbarLayout/faceHorizontal': isHorizontal, 'ScrollbarLayout/faceVertical': isVertical, 'public/Scrollbar/faceActive': isActive, 'public/Scrollbar/face': true }); var position = this.state.position * this.state.scale + FACE_MARGIN; if (isHorizontal) { mainStyle = { width: size }; faceStyle = { width: faceSize - FACE_MARGIN_2 }; translateDOMPositionXY(faceStyle, position, 0); } else { mainStyle = { top: verticalTop, height: size }; faceStyle = { height: faceSize - FACE_MARGIN_2 }; translateDOMPositionXY(faceStyle, 0, position); } mainStyle.zIndex = this.props.zIndex; if (this.props.trackColor === 'gray') { mainStyle.backgroundColor = cssVar('fbui-desktop-background-light'); } return React.createElement( 'div', { onFocus: this._onFocus, onBlur: this._onBlur, onKeyDown: this._onKeyDown, onMouseDown: this._onMouseDown, onWheel: this._wheelHandler.onWheel, className: mainClassName, style: mainStyle, tabIndex: 0 }, React.createElement('div', { ref: 'face', className: faceClassName, style: faceStyle }) ); }, componentWillMount: function componentWillMount() { var isHorizontal = this.props.orientation === 'horizontal'; var onWheel = isHorizontal ? this._onWheelX : this._onWheelY; this._wheelHandler = new ReactWheelHandler(onWheel, this._shouldHandleX, // Should hanlde horizontal scroll this._shouldHandleY // Should handle vertical scroll ); }, componentDidMount: function componentDidMount() { this._mouseMoveTracker = new DOMMouseMoveTracker(this._onMouseMove, this._onMouseMoveEnd, document.documentElement); if (this.props.position !== undefined && this.state.position !== this.props.position) { this._didScroll(); } }, componentWillUnmount: function componentWillUnmount() { this._nextState = null; this._mouseMoveTracker.releaseMouseMoves(); if (_lastScrolledScrollbar === this) { _lastScrolledScrollbar = null; } delete this._mouseMoveTracker; }, scrollBy: function scrollBy( /*number*/delta) { this._onWheel(delta); }, _shouldHandleX: function _shouldHandleX( /*number*/delta) /*boolean*/{ return this.props.orientation === 'horizontal' ? this._shouldHandleChange(delta) : false; }, _shouldHandleY: function _shouldHandleY( /*number*/delta) /*boolean*/{ return this.props.orientation !== 'horizontal' ? this._shouldHandleChange(delta) : false; }, _shouldHandleChange: function _shouldHandleChange( /*number*/delta) /*boolean*/{ var nextState = this._calculateState(this.state.position + delta, this.props.size, this.props.contentSize, this.props.orientation); return nextState.position !== this.state.position; }, _calculateState: function _calculateState( /*number*/position, /*number*/size, /*number*/contentSize, /*string*/orientation) /*object*/{ if (size < 1 || contentSize <= size) { return UNSCROLLABLE_STATE; } var stateKey = '' + position + '_' + size + '_' + contentSize + '_' + orientation; if (this._stateKey === stateKey) { return this._stateForKey; } // There are two types of positions here. // 1) Phisical position: changed by mouse / keyboard // 2) Logical position: changed by props. // The logical position will be kept as as internal state and the `render()` // function will translate it into physical position to render. var isHorizontal = orientation === 'horizontal'; var scale = size / contentSize; var faceSize = size * scale; if (faceSize < FACE_SIZE_MIN) { scale = (size - FACE_SIZE_MIN) / (contentSize - FACE_SIZE_MIN); faceSize = FACE_SIZE_MIN; } var scrollable = true; var maxPosition = contentSize - size; if (position < 0) { position = 0; } else if (position > maxPosition) { position = maxPosition; } var isDragging = this._mouseMoveTracker ? this._mouseMoveTracker.isDragging() : false; // This function should only return flat values that can be compared quiclky // by `ReactComponentWithPureRenderMixin`. var state = { faceSize: faceSize, isDragging: isDragging, isHorizontal: isHorizontal, position: position, scale: scale, scrollable: scrollable }; // cache the state for later use. this._stateKey = stateKey; this._stateForKey = state; return state; }, _onWheelY: function _onWheelY( /*number*/deltaX, /*number*/deltaY) { this._onWheel(deltaY); }, _onWheelX: function _onWheelX( /*number*/deltaX, /*number*/deltaY) { this._onWheel(deltaX); }, _onWheel: function _onWheel( /*number*/delta) { var props = this.props; // The mouse may move faster then the animation frame does. // Use `requestAnimationFrame` to avoid over-updating. this._setNextState(this._calculateState(this.state.position + delta, props.size, props.contentSize, props.orientation)); }, _onMouseDown: function _onMouseDown( /*object*/event) { var nextState; if (event.target !== React.findDOMNode(this.refs.face)) { // Both `offsetX` and `layerX` are non-standard DOM property but they are // magically available for browsers somehow. var nativeEvent = event.nativeEvent; var position = this.state.isHorizontal ? nativeEvent.offsetX || nativeEvent.layerX : nativeEvent.offsetY || nativeEvent.layerY; // MouseDown on the scroll-track directly, move the center of the // scroll-face to the mouse position. var props = this.props; position = position / this.state.scale; nextState = this._calculateState(position - this.state.faceSize * 0.5 / this.state.scale, props.size, props.contentSize, props.orientation); } else { nextState = {}; } nextState.focused = true; this._setNextState(nextState); this._mouseMoveTracker.captureMouseMoves(event); // Focus the node so it may receive keyboard event. React.findDOMNode(this).focus(); }, _onMouseMove: function _onMouseMove( /*number*/deltaX, /*number*/deltaY) { var props = this.props; var delta = this.state.isHorizontal ? deltaX : deltaY; delta = delta / this.state.scale; this._setNextState(this._calculateState(this.state.position + delta, props.size, props.contentSize, props.orientation)); }, _onMouseMoveEnd: function _onMouseMoveEnd() { this._nextState = null; this._mouseMoveTracker.releaseMouseMoves(); this.setState({ isDragging: false }); }, _onKeyDown: function _onKeyDown( /*object*/event) { var keyCode = event.keyCode; if (keyCode === Keys.TAB) { // Let focus move off the scrollbar. return; } var distance = KEYBOARD_SCROLL_AMOUNT; var direction = 0; if (this.state.isHorizontal) { switch (keyCode) { case Keys.HOME: direction = -1; distance = this.props.contentSize; break; case Keys.LEFT: direction = -1; break; case Keys.RIGHT: direction = 1; break; default: return; } } if (!this.state.isHorizontal) { switch (keyCode) { case Keys.SPACE: if (event.shiftKey) { direction = -1; } else { direction = 1; } break; case Keys.HOME: direction = -1; distance = this.props.contentSize; break; case Keys.UP: direction = -1; break; case Keys.DOWN: direction = 1; break; case Keys.PAGE_UP: direction = -1; distance = this.props.size; break; case Keys.PAGE_DOWN: direction = 1; distance = this.props.size; break; default: return; } } event.preventDefault(); var props = this.props; this._setNextState(this._calculateState(this.state.position + distance * direction, props.size, props.contentSize, props.orientation)); }, _onFocus: function _onFocus() { this.setState({ focused: true }); }, _onBlur: function _onBlur() { this.setState({ focused: false }); }, _blur: function _blur() { if (this.isMounted()) { try { this._onBlur(); React.findDOMNode(this).blur(); } catch (oops) {} } }, _setNextState: function _setNextState( /*object*/nextState, /*?object*/props) { props = props || this.props; var controlledPosition = props.position; var willScroll = this.state.position !== nextState.position; if (controlledPosition === undefined) { var callback = willScroll ? this._didScroll : undefined; this.setState(nextState, callback); } else if (controlledPosition === nextState.position) { this.setState(nextState); } else { // Scrolling is controlled. Don't update the state and let the owner // to update the scrollbar instead. if (nextState.position !== undefined && nextState.position !== this.state.position) { this.props.onScroll(nextState.position); } return; } if (willScroll && _lastScrolledScrollbar !== this) { _lastScrolledScrollbar && _lastScrolledScrollbar._blur(); _lastScrolledScrollbar = this; } }, _didScroll: function _didScroll() { this.props.onScroll(this.state.position); } }); Scrollbar.KEYBOARD_SCROLL_AMOUNT = KEYBOARD_SCROLL_AMOUNT; Scrollbar.SIZE = parseInt(cssVar('scrollbar-size'), 10); module.exports = Scrollbar; // pass /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * This class listens to events on the document and then updates a react * component through callbacks. * Please note that captureMouseMove must be called in * order to initialize listeners on mousemove and mouseup. * releaseMouseMove must be called to remove them. It is important to * call releaseMouseMoves since mousemove is expensive to listen to. * * @providesModule DOMMouseMoveTracker * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var EventListener = __webpack_require__(60); var cancelAnimationFramePolyfill = __webpack_require__(61); var requestAnimationFramePolyfill = __webpack_require__(56); var DOMMouseMoveTracker = (function () { /** * onMove is the callback that will be called on every mouse move. * onMoveEnd is called on mouse up when movement has ended. */ function DOMMouseMoveTracker( /*function*/onMove, /*function*/onMoveEnd, /*DOMElement*/domNode) { _classCallCheck(this, DOMMouseMoveTracker); this._isDragging = false; this._animationFrameID = null; this._domNode = domNode; this._onMove = onMove; this._onMoveEnd = onMoveEnd; this._onMouseMove = this._onMouseMove.bind(this); this._onMouseUp = this._onMouseUp.bind(this); this._didMouseMove = this._didMouseMove.bind(this); } _createClass(DOMMouseMoveTracker, [{ key: 'captureMouseMoves', /** * This is to set up the listeners for listening to mouse move * and mouse up signaling the movement has ended. Please note that these * listeners are added at the document.body level. It takes in an event * in order to grab inital state. */ value: function captureMouseMoves( /*object*/event) { if (!this._eventMoveToken && !this._eventUpToken) { this._eventMoveToken = EventListener.listen(this._domNode, 'mousemove', this._onMouseMove); this._eventUpToken = EventListener.listen(this._domNode, 'mouseup', this._onMouseUp); } if (!this._isDragging) { this._deltaX = 0; this._deltaY = 0; this._isDragging = true; this._x = event.clientX; this._y = event.clientY; } event.preventDefault(); } }, { key: 'releaseMouseMoves', /** * These releases all of the listeners on document.body. */ value: function releaseMouseMoves() { if (this._eventMoveToken && this._eventUpToken) { this._eventMoveToken.remove(); this._eventMoveToken = null; this._eventUpToken.remove(); this._eventUpToken = null; } if (this._animationFrameID !== null) { cancelAnimationFramePolyfill(this._animationFrameID); this._animationFrameID = null; } if (this._isDragging) { this._isDragging = false; this._x = null; this._y = null; } } }, { key: 'isDragging', /** * Returns whether or not if the mouse movement is being tracked. */ value: function isDragging() /*boolean*/{ return this._isDragging; } }, { key: '_onMouseMove', /** * Calls onMove passed into constructor and updates internal state. */ value: function _onMouseMove( /*object*/event) { var x = event.clientX; var y = event.clientY; this._deltaX += x - this._x; this._deltaY += y - this._y; if (this._animationFrameID === null) { // The mouse may move faster then the animation frame does. // Use `requestAnimationFramePolyfill` to avoid over-updating. this._animationFrameID = requestAnimationFramePolyfill(this._didMouseMove); } this._x = x; this._y = y; event.preventDefault(); } }, { key: '_didMouseMove', value: function _didMouseMove() { this._animationFrameID = null; this._onMove(this._deltaX, this._deltaY); this._deltaX = 0; this._deltaY = 0; } }, { key: '_onMouseUp', /** * Calls onMoveEnd passed into constructor and updates internal state. */ value: function _onMouseUp() { if (this._animationFrameID) { this._didMouseMove(); } this._onMoveEnd(); } }]); return DOMMouseMoveTracker; })(); module.exports = DOMMouseMoveTracker; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventListener * @typechecks */ 'use strict'; var emptyFunction = __webpack_require__(51); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function listen(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function remove() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function remove() { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function capture(target, eventType, callback) { if (!target.addEventListener) { if (true) { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } else { target.addEventListener(eventType, callback, true); return { remove: function remove() { target.removeEventListener(eventType, callback, true); } }; } }, registerDefault: function registerDefault() {} }; module.exports = EventListener; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule cancelAnimationFramePolyfill */ /** * Here is the native and polyfill version of cancelAnimationFrame. * Please don't use it directly and use cancelAnimationFrame module instead. */ "use strict"; var cancelAnimationFrame = global.cancelAnimationFrame || global.webkitCancelAnimationFrame || global.mozCancelAnimationFrame || global.oCancelAnimationFrame || global.msCancelAnimationFrame || global.clearTimeout; module.exports = cancelAnimationFrame; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Keys */ "use strict"; module.exports = { BACKSPACE: 8, TAB: 9, RETURN: 13, ALT: 18, ESC: 27, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, DELETE: 46, COMMA: 188, PERIOD: 190, A: 65, Z: 90, ZERO: 48, NUMPAD_0: 96, NUMPAD_9: 105 }; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule cssVar * @typechecks */ 'use strict'; var CSS_VARS = { 'scrollbar-face-active-color': '#7d7d7d', 'scrollbar-face-color': '#c2c2c2', 'scrollbar-face-margin': '4px', 'scrollbar-face-radius': '6px', 'scrollbar-size': '15px', 'scrollbar-size-large': '17px', 'scrollbar-track-color': 'rgba(255, 255, 255, 0.8)', 'fbui-white': '#fff', 'fbui-desktop-background-light': '#f6f7f8' }; /** * @param {string} name */ function cssVar(name) { if (CSS_VARS.hasOwnProperty(name)) { return CSS_VARS[name]; } throw new Error('cssVar' + '("' + name + '"): Unexpected class transformation.'); } cssVar.CSS_VARS = CSS_VARS; module.exports = cssVar; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule cx */ 'use strict'; var slashReplaceRegex = /\//g; var cache = {}; function getClassName(className) { if (cache[className]) { return cache[className]; } cache[className] = className.replace(slashReplaceRegex, '_'); return cache[className]; } /** * This function is used to mark string literals representing CSS class names * so that they can be transformed statically. This allows for modularization * and minification of CSS class names. * * In static_upstream, this function is actually implemented, but it should * eventually be replaced with something more descriptive, and the transform * that is used in the main stack should be ported for use elsewhere. * * @param string|object className to modularize, or an object of key/values. * In the object case, the values are conditions that * determine if the className keys should be included. * @param [string ...] Variable list of classNames in the string case. * @return string Renderable space-separated CSS className. */ function cx(classNames) { var classNamesArray; if (typeof classNames == 'object') { classNamesArray = Object.keys(classNames).filter(function (className) { return classNames[className]; }); } else { classNamesArray = Array.prototype.slice.call(arguments); } return classNamesArray.map(getClassName).join(' '); } module.exports = cx; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule translateDOMPositionXY * @typechecks */ 'use strict'; var BrowserSupportCore = __webpack_require__(66); var getVendorPrefixedName = __webpack_require__(67); var TRANSFORM = getVendorPrefixedName('transform'); var BACKFACE_VISIBILITY = getVendorPrefixedName('backfaceVisibility'); var translateDOMPositionXY = (function () { if (BrowserSupportCore.hasCSSTransforms()) { var ua = global.window ? global.window.navigator.userAgent : 'UNKNOWN'; var isSafari = /Safari\//.test(ua) && !/Chrome\//.test(ua); // It appears that Safari messes up the composition order // of GPU-accelerated layers // (see bug https://bugs.webkit.org/show_bug.cgi?id=61824). // Use 2D translation instead. if (!isSafari && BrowserSupportCore.hasCSS3DTransforms()) { return function ( /*object*/style, /*number*/x, /*number*/y) { style[TRANSFORM] = 'translate3d(' + x + 'px,' + y + 'px,0)'; style[BACKFACE_VISIBILITY] = 'hidden'; }; } else { return function ( /*object*/style, /*number*/x, /*number*/y) { style[TRANSFORM] = 'translate(' + x + 'px,' + y + 'px)'; }; } } else { return function ( /*object*/style, /*number*/x, /*number*/y) { style.left = x + 'px'; style.top = y + 'px'; }; } })(); module.exports = translateDOMPositionXY; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BrowserSupportCore */ 'use strict'; var getVendorPrefixedName = __webpack_require__(67); var BrowserSupportCore = { /** * @return {bool} True if browser supports css animations. */ hasCSSAnimations: function hasCSSAnimations() { return !!getVendorPrefixedName('animationName'); }, /** * @return {bool} True if browser supports css transforms. */ hasCSSTransforms: function hasCSSTransforms() { return !!getVendorPrefixedName('transform'); }, /** * @return {bool} True if browser supports css 3d transforms. */ hasCSS3DTransforms: function hasCSS3DTransforms() { return !!getVendorPrefixedName('perspective'); }, /** * @return {bool} True if browser supports css transitions. */ hasCSSTransitions: function hasCSSTransitions() { return !!getVendorPrefixedName('transition'); } }; module.exports = BrowserSupportCore; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getVendorPrefixedName * @typechecks */ 'use strict'; var ExecutionEnvironment = __webpack_require__(55); var camelize = __webpack_require__(68); var invariant = __webpack_require__(69); var memoized = {}; var prefixes = ['Webkit', 'ms', 'Moz', 'O']; var prefixRegex = new RegExp('^(' + prefixes.join('|') + ')'); var testStyle = ExecutionEnvironment.canUseDOM ? document.createElement('div').style : {}; function getWithPrefix(name) { for (var i = 0; i < prefixes.length; i++) { var prefixedName = prefixes[i] + name; if (prefixedName in testStyle) { return prefixedName; } } return null; } /** * @param {string} property Name of a css property to check for. * @return {?string} property name supported in the browser, or null if not * supported. */ function getVendorPrefixedName(property) { var name = camelize(property); if (memoized[name] === undefined) { var capitalizedName = name.charAt(0).toUpperCase() + name.slice(1); if (prefixRegex.test(capitalizedName)) { invariant(false, 'getVendorPrefixedName must only be called with unprefixed' + 'CSS property names. It was called with %s', property); } memoized[name] = name in testStyle ? name : getWithPrefix(capitalizedName); } return memoized[name]; } module.exports = getVendorPrefixedName; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelize * @typechecks */ "use strict"; var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function invariant(condition, format, a, b, c, d, e, f) { if (true) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error('Invariant Violation: ' + format.replace(/%s/g, function () { return args[argIndex++]; })); } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableBufferedRows.react * @typechecks */ 'use strict'; var React = __webpack_require__(28); var FixedDataTableRowBuffer = __webpack_require__(71); var FixedDataTableRow = __webpack_require__(75); var cx = __webpack_require__(64); var emptyFunction = __webpack_require__(51); var joinClasses = __webpack_require__(84); var translateDOMPositionXY = __webpack_require__(65); var PropTypes = React.PropTypes; var FixedDataTableBufferedRows = React.createClass({ displayName: 'FixedDataTableBufferedRows', propTypes: { defaultRowHeight: PropTypes.number.isRequired, firstRowIndex: PropTypes.number.isRequired, firstRowOffset: PropTypes.number.isRequired, fixedColumns: PropTypes.array.isRequired, height: PropTypes.number.isRequired, offsetTop: PropTypes.number.isRequired, onRowClick: PropTypes.func, onRowDoubleClick: PropTypes.func, onRowMouseDown: PropTypes.func, onRowMouseEnter: PropTypes.func, onRowMouseLeave: PropTypes.func, rowClassNameGetter: PropTypes.func, rowsCount: PropTypes.number.isRequired, rowGetter: PropTypes.func.isRequired, rowHeightGetter: PropTypes.func, rowPositionGetter: PropTypes.func.isRequired, scrollLeft: PropTypes.number.isRequired, scrollableColumns: PropTypes.array.isRequired, showLastRowBorder: PropTypes.bool, width: PropTypes.number.isRequired }, getInitialState: function getInitialState() /*object*/{ this._rowBuffer = new FixedDataTableRowBuffer(this.props.rowsCount, this.props.defaultRowHeight, this.props.height, this._getRowHeight); return { rowsToRender: this._rowBuffer.getRows(this.props.firstRowIndex, this.props.firstRowOffset) }; }, componentWillMount: function componentWillMount() { this._staticRowArray = []; }, componentDidMount: function componentDidMount() { this._bufferUpdateTimer = setTimeout(this._updateBuffer, 1000); }, componentWillReceiveProps: function componentWillReceiveProps( /*object*/nextProps) { if (nextProps.rowsCount !== this.props.rowsCount || nextProps.defaultRowHeight !== this.props.defaultRowHeight || nextProps.height !== this.props.height) { this._rowBuffer = new FixedDataTableRowBuffer(nextProps.rowsCount, nextProps.defaultRowHeight, nextProps.height, this._getRowHeight); } this.setState({ rowsToRender: this._rowBuffer.getRows(nextProps.firstRowIndex, nextProps.firstRowOffset) }); if (this._bufferUpdateTimer) { clearTimeout(this._bufferUpdateTimer); } this._bufferUpdateTimer = setTimeout(this._updateBuffer, 400); }, _updateBuffer: function _updateBuffer() { this._bufferUpdateTimer = null; if (this.isMounted()) { this.setState({ rowsToRender: this._rowBuffer.getRowsWithUpdatedBuffer() }); } }, shouldComponentUpdate: function shouldComponentUpdate() /*boolean*/{ // Don't add PureRenderMixin to this component please. return true; }, componentWillUnmount: function componentWillUnmount() { this._staticRowArray.length = 0; }, render: function render() /*object*/{ var props = this.props; var rowClassNameGetter = props.rowClassNameGetter || emptyFunction; var rowGetter = props.rowGetter; var rowPositionGetter = props.rowPositionGetter; var rowsToRender = this.state.rowsToRender; this._staticRowArray.length = rowsToRender.length; for (var i = 0; i < rowsToRender.length; ++i) { var rowIndex = rowsToRender[i]; var currentRowHeight = this._getRowHeight(rowIndex); var rowOffsetTop = rowPositionGetter(rowIndex); var hasBottomBorder = rowIndex === props.rowsCount - 1 && props.showLastRowBorder; this._staticRowArray[i] = React.createElement(FixedDataTableRow, { key: i, index: rowIndex, data: rowGetter(rowIndex), width: props.width, height: currentRowHeight, scrollLeft: Math.round(props.scrollLeft), offsetTop: Math.round(rowOffsetTop), fixedColumns: props.fixedColumns, scrollableColumns: props.scrollableColumns, onClick: props.onRowClick, onMouseDown: props.onRowMouseDown, onMouseEnter: props.onRowMouseEnter, onMouseLeave: props.onRowMouseLeave, className: joinClasses(rowClassNameGetter(rowIndex), cx('public/fixedDataTable/bodyRow'), cx({ 'fixedDataTableLayout/hasBottomBorder': hasBottomBorder, 'public/fixedDataTable/hasBottomBorder': hasBottomBorder })) }); } var firstRowPosition = props.rowPositionGetter(props.firstRowIndex); var style = { position: 'absolute' }; translateDOMPositionXY(style, 0, props.firstRowOffset - firstRowPosition + props.offsetTop); return React.createElement( 'div', { style: style }, this._staticRowArray ); }, _getRowHeight: function _getRowHeight( /*number*/index) /*number*/{ return this.props.rowHeightGetter ? this.props.rowHeightGetter(index) : this.props.defaultRowHeight; } }); module.exports = FixedDataTableBufferedRows; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableRowBuffer * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var IntegerBufferSet = __webpack_require__(72); var clamp = __webpack_require__(74); var invariant = __webpack_require__(69); var MIN_BUFFER_ROWS = 3; var MAX_BUFFER_ROWS = 6; // FixedDataTableRowBuffer is a helper class that executes row buffering // logic for FixedDataTable. It figures out which rows should be rendered // and in which positions. var FixedDataTableRowBuffer = (function () { function FixedDataTableRowBuffer( /*number*/rowsCount, /*number*/defaultRowHeight, /*number*/viewportHeight, /*?function*/rowHeightGetter) { _classCallCheck(this, FixedDataTableRowBuffer); invariant(defaultRowHeight !== 0, 'defaultRowHeight musn\'t be equal 0 in FixedDataTableRowBuffer'); this._bufferSet = new IntegerBufferSet(); this._defaultRowHeight = defaultRowHeight; this._viewportRowsBegin = 0; this._viewportRowsEnd = 0; this._maxVisibleRowCount = Math.ceil(viewportHeight / defaultRowHeight) + 1; this._bufferRowsCount = clamp(MIN_BUFFER_ROWS, Math.floor(this._maxVisibleRowCount / 2), MAX_BUFFER_ROWS); this._rowsCount = rowsCount; this._rowHeightGetter = rowHeightGetter; this._rows = []; this._viewportHeight = viewportHeight; this.getRows = this.getRows.bind(this); this.getRowsWithUpdatedBuffer = this.getRowsWithUpdatedBuffer.bind(this); } _createClass(FixedDataTableRowBuffer, [{ key: 'getRowsWithUpdatedBuffer', value: function getRowsWithUpdatedBuffer() /*array*/{ var remainingBufferRows = 2 * this._bufferRowsCount; var bufferRowIndex = Math.max(this._viewportRowsBegin - this._bufferRowsCount, 0); while (bufferRowIndex < this._viewportRowsBegin) { this._addRowToBuffer(bufferRowIndex, this._viewportRowsBegin, this._viewportRowsEnd - 1); bufferRowIndex++; remainingBufferRows--; } bufferRowIndex = this._viewportRowsEnd; while (bufferRowIndex < this._rowsCount && remainingBufferRows > 0) { this._addRowToBuffer(bufferRowIndex, this._viewportRowsBegin, this._viewportRowsEnd - 1); bufferRowIndex++; remainingBufferRows--; } return this._rows; } }, { key: 'getRows', value: function getRows( /*number*/firstRowIndex, /*number*/firstRowOffset) /*array*/{ var top = firstRowOffset; var totalHeight = top; var rowIndex = firstRowIndex; var endIndex = Math.min(firstRowIndex + this._maxVisibleRowCount, this._rowsCount); this._viewportRowsBegin = firstRowIndex; while (rowIndex < endIndex || totalHeight < this._viewportHeight && rowIndex < this._rowsCount) { this._addRowToBuffer(rowIndex, firstRowIndex, endIndex - 1); totalHeight += this._rowHeightGetter(rowIndex); ++rowIndex; // Store index after the last viewport row as end, to be able to // distinguish when there are no rows rendered in viewport this._viewportRowsEnd = rowIndex; } return this._rows; } }, { key: '_addRowToBuffer', value: function _addRowToBuffer( /*number*/rowIndex, /*number*/firstViewportRowIndex, /*number*/lastViewportRowIndex) { var rowPosition = this._bufferSet.getValuePosition(rowIndex); var viewportRowsCount = lastViewportRowIndex - firstViewportRowIndex + 1; var allowedRowsCount = viewportRowsCount + this._bufferRowsCount * 2; if (rowPosition === null && this._bufferSet.getSize() >= allowedRowsCount) { rowPosition = this._bufferSet.replaceFurthestValuePosition(firstViewportRowIndex, lastViewportRowIndex, rowIndex); } if (rowPosition === null) { // We can't reuse any of existing positions for this row. We have to // create new position rowPosition = this._bufferSet.getNewPositionForValue(rowIndex); this._rows[rowPosition] = rowIndex; } else { // This row already is in the table with rowPosition position or it // can replace row that is in that position this._rows[rowPosition] = rowIndex; } } }]); return FixedDataTableRowBuffer; })(); module.exports = FixedDataTableRowBuffer; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule IntegerBufferSet * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Heap = __webpack_require__(73); var invariant = __webpack_require__(69); // Data structure that allows to store values and assign positions to them // in a way to minimize changing positions of stored values when new ones are // added or when some values are replaced. Stored elements are alwasy assigned // a consecutive set of positoins startin from 0 up to count of elements less 1 // Following actions can be executed // * get position assigned to given value (null if value is not stored) // * create new entry for new value and get assigned position back // * replace value that is furthest from specified value range with new value // and get it's position back // All operations take amortized log(n) time where n is number of elements in // the set. var IntegerBufferSet = (function () { function IntegerBufferSet() { _classCallCheck(this, IntegerBufferSet); this._valueToPositionMap = {}; this._size = 0; this._smallValues = new Heap([], // Initial data in the heap this._smallerComparator); this._largeValues = new Heap([], // Initial data in the heap this._greaterComparator); this.getNewPositionForValue = this.getNewPositionForValue.bind(this); this.getValuePosition = this.getValuePosition.bind(this); this.getSize = this.getSize.bind(this); this.replaceFurthestValuePosition = this.replaceFurthestValuePosition.bind(this); } _createClass(IntegerBufferSet, [{ key: 'getSize', value: function getSize() /*number*/{ return this._size; } }, { key: 'getValuePosition', value: function getValuePosition( /*number*/value) /*?number*/{ if (this._valueToPositionMap[value] === undefined) { return null; } return this._valueToPositionMap[value]; } }, { key: 'getNewPositionForValue', value: function getNewPositionForValue( /*number*/value) /*number*/{ invariant(this._valueToPositionMap[value] === undefined, 'Shouldn\'t try to find new position for value already stored in BufferSet'); var newPosition = this._size; this._size++; this._pushToHeaps(newPosition, value); this._valueToPositionMap[value] = newPosition; return newPosition; } }, { key: 'replaceFurthestValuePosition', value: function replaceFurthestValuePosition( /*number*/lowValue, /*number*/highValue, /*number*/newValue) /*?number*/{ invariant(this._valueToPositionMap[newValue] === undefined, 'Shouldn\'t try to replace values with value already stored value in ' + 'BufferSet'); this._cleanHeaps(); if (this._smallValues.empty() || this._largeValues.empty()) { // Threre are currently no values stored. We will have to create new // position for this value. return null; } var minValue = this._smallValues.peek().value; var maxValue = this._largeValues.peek().value; if (minValue >= lowValue && maxValue <= highValue) { // All values currently stored are necessary, we can't reuse any of them. return null; } var valueToReplace; if (lowValue - minValue > maxValue - highValue) { // minValue is further from provided range. We will reuse it's position. valueToReplace = minValue; this._smallValues.pop(); } else { valueToReplace = maxValue; this._largeValues.pop(); } var position = this._valueToPositionMap[valueToReplace]; delete this._valueToPositionMap[valueToReplace]; this._valueToPositionMap[newValue] = position; this._pushToHeaps(position, newValue); return position; } }, { key: '_pushToHeaps', value: function _pushToHeaps( /*number*/position, /*number*/value) { var element = { position: position, value: value }; // We can reuse the same object in both heaps, because we don't mutate them this._smallValues.push(element); this._largeValues.push(element); } }, { key: '_cleanHeaps', value: function _cleanHeaps() { // We not usually only remove object from one heap while moving value. // Here we make sure that there is no stale data on top of heaps. this._cleanHeap(this._smallValues); this._cleanHeap(this._largeValues); var minHeapSize = Math.min(this._smallValues.size(), this._largeValues.size()); var maxHeapSize = Math.max(this._smallValues.size(), this._largeValues.size()); if (maxHeapSize > 10 * minHeapSize) { // There are many old values in one of heaps. We nned to get rid of them // to not use too avoid memory leaks this._recreateHeaps(); } } }, { key: '_recreateHeaps', value: function _recreateHeaps() { var sourceHeap = this._smallValues.size() < this._largeValues.size() ? this._smallValues : this._largeValues; var newSmallValues = new Heap([], // Initial data in the heap this._smallerComparator); var newLargeValues = new Heap([], // Initial datat in the heap this._greaterComparator); while (!sourceHeap.empty()) { var element = sourceHeap.pop(); // Push all stil valid elements to new heaps if (this._valueToPositionMap[element.value] !== undefined) { newSmallValues.push(element); newLargeValues.push(element); } } this._smallValues = newSmallValues; this._largeValues = newLargeValues; } }, { key: '_cleanHeap', value: function _cleanHeap( /*object*/heap) { while (!heap.empty() && this._valueToPositionMap[heap.peek().value] === undefined) { heap.pop(); } } }, { key: '_smallerComparator', value: function _smallerComparator( /*object*/lhs, /*object*/rhs) /*boolean*/{ return lhs.value < rhs.value; } }, { key: '_greaterComparator', value: function _greaterComparator( /*object*/lhs, /*object*/rhs) /*boolean*/{ return lhs.value > rhs.value; } }]); return IntegerBufferSet; })(); module.exports = IntegerBufferSet; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Heap * @typechecks * @preventMunge */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } /* * @param {*} a * @param {*} b * @return {boolean} */ function defaultComparator(a, b) { return a < b; } var Heap = (function () { function Heap(items, comparator) { _classCallCheck(this, Heap); this._items = items || []; this._size = this._items.length; this._comparator = comparator || defaultComparator; this._heapify(); } _createClass(Heap, [{ key: 'empty', /* * @return {boolean} */ value: function empty() { return this._size === 0; } }, { key: 'pop', /* * @return {*} */ value: function pop() { if (this._size === 0) { return; } var elt = this._items[0]; var lastElt = this._items.pop(); this._size--; if (this._size > 0) { this._items[0] = lastElt; this._sinkDown(0); } return elt; } }, { key: 'push', /* * @param {*} item */ value: function push(item) { this._items[this._size++] = item; this._bubbleUp(this._size - 1); } }, { key: 'size', /* * @return {number} */ value: function size() { return this._size; } }, { key: 'peek', /* * @return {*} */ value: function peek() { if (this._size === 0) { return; } return this._items[0]; } }, { key: '_heapify', value: function _heapify() { for (var index = Math.floor((this._size + 1) / 2); index >= 0; index--) { this._sinkDown(index); } } }, { key: '_bubbleUp', /* * @parent {number} index */ value: function _bubbleUp(index) { var elt = this._items[index]; while (index > 0) { var parentIndex = Math.floor((index + 1) / 2) - 1; var parentElt = this._items[parentIndex]; // if parentElt < elt, stop if (this._comparator(parentElt, elt)) { return; } // swap this._items[parentIndex] = elt; this._items[index] = parentElt; index = parentIndex; } } }, { key: '_sinkDown', /* * @parent {number} index */ value: function _sinkDown(index) { var elt = this._items[index]; while (true) { var leftChildIndex = 2 * (index + 1) - 1; var rightChildIndex = 2 * (index + 1); var swapIndex = -1; if (leftChildIndex < this._size) { var leftChild = this._items[leftChildIndex]; if (this._comparator(leftChild, elt)) { swapIndex = leftChildIndex; } } if (rightChildIndex < this._size) { var rightChild = this._items[rightChildIndex]; if (this._comparator(rightChild, elt)) { if (swapIndex === -1 || this._comparator(rightChild, this._items[swapIndex])) { swapIndex = rightChildIndex; } } } // if we don't have a swap, stop if (swapIndex === -1) { return; } this._items[index] = this._items[swapIndex]; this._items[swapIndex] = elt; index = swapIndex; } } }]); return Heap; })(); module.exports = Heap; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule clamp * @typechecks */ /** * @param {number} min * @param {number} value * @param {number} max * @return {number} */ "use strict"; function clamp(min, value, max) { if (value < min) { return min; } if (value > max) { return max; } return value; } module.exports = clamp; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableRow.react * @typechecks */ 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(28); var ReactComponentWithPureRenderMixin = __webpack_require__(47); var FixedDataTableCellGroup = __webpack_require__(76); var cx = __webpack_require__(64); var joinClasses = __webpack_require__(84); var translateDOMPositionXY = __webpack_require__(65); var PropTypes = React.PropTypes; /** * Component that renders the row for <FixedDataTable />. * This component should not be used directly by developer. Instead, * only <FixedDataTable /> should use the component internally. */ var FixedDataTableRowImpl = React.createClass({ displayName: 'FixedDataTableRowImpl', mixins: [ReactComponentWithPureRenderMixin], propTypes: { /** * The row data to render. The data format can be a simple Map object * or an Array of data. */ data: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), /** * Array of <FixedDataTableColumn /> for the fixed columns. */ fixedColumns: PropTypes.array.isRequired, /** * Height of the row. */ height: PropTypes.number.isRequired, /** * The row index. */ index: PropTypes.number.isRequired, /** * Array of <FixedDataTableColumn /> for the scrollable columns. */ scrollableColumns: PropTypes.array.isRequired, /** * The distance between the left edge of the table and the leftmost portion * of the row currently visible in the table. */ scrollLeft: PropTypes.number.isRequired, /** * Width of the row. */ width: PropTypes.number.isRequired, /** * Fire when a row is clicked. */ onClick: PropTypes.func, /** * Fire when a row is double clicked. */ onDoubleClick: PropTypes.func, /** * Callback for when resizer knob (in FixedDataTableCell) is clicked * to initialize resizing. Please note this is only on the cells * in the header. * @param number combinedWidth * @param number leftOffset * @param number cellWidth * @param number|string columnKey * @param object event */ onColumnResize: PropTypes.func }, render: function render() /*object*/{ var style = { width: this.props.width, height: this.props.height }; var className = cx({ 'fixedDataTableRowLayout/main': true, 'public/fixedDataTableRow/main': true, 'public/fixedDataTableRow/highlighted': this.props.index % 2 === 1, 'public/fixedDataTableRow/odd': this.props.index % 2 === 1, 'public/fixedDataTableRow/even': this.props.index % 2 === 0 }); var isHeaderOrFooterRow = this.props.index === -1; if (!this.props.data && !isHeaderOrFooterRow) { return React.createElement('div', { className: joinClasses(className, this.props.className), style: style }); } var fixedColumnsWidth = this._getColumnsWidth(this.props.fixedColumns); var fixedColumns = React.createElement(FixedDataTableCellGroup, { key: 'fixed_cells', height: this.props.height, left: 0, width: fixedColumnsWidth, zIndex: 2, columns: this.props.fixedColumns, data: this.props.data, onColumnResize: this.props.onColumnResize, rowHeight: this.props.height, rowIndex: this.props.index }); var columnsShadow = this._renderColumnsShadow(fixedColumnsWidth); var scrollableColumns = React.createElement(FixedDataTableCellGroup, { key: 'scrollable_cells', height: this.props.height, left: this.props.scrollLeft, offsetLeft: fixedColumnsWidth, width: this.props.width - fixedColumnsWidth, zIndex: 0, columns: this.props.scrollableColumns, data: this.props.data, onColumnResize: this.props.onColumnResize, rowHeight: this.props.height, rowIndex: this.props.index }); return React.createElement( 'div', { className: joinClasses(className, this.props.className), onClick: this.props.onClick ? this._onClick : null, onDoubleClick: this.props.onDoubleClick ? this._onDoubleClick : null, onMouseDown: this.props.onMouseDown ? this._onMouseDown : null, onMouseEnter: this.props.onMouseEnter ? this._onMouseEnter : null, onMouseLeave: this.props.onMouseLeave ? this._onMouseLeave : null, style: style }, React.createElement( 'div', { className: cx('fixedDataTableRowLayout/body') }, fixedColumns, scrollableColumns, columnsShadow ) ); }, _getColumnsWidth: function _getColumnsWidth( /*array*/columns) /*number*/{ var width = 0; for (var i = 0; i < columns.length; ++i) { width += columns[i].props.width; } return width; }, _renderColumnsShadow: function _renderColumnsShadow( /*number*/left) /*?object*/{ if (left > 0) { var className = cx({ 'fixedDataTableRowLayout/fixedColumnsDivider': true, 'fixedDataTableRowLayout/columnsShadow': this.props.scrollLeft > 0, 'public/fixedDataTableRow/fixedColumnsDivider': true, 'public/fixedDataTableRow/columnsShadow': this.props.scrollLeft > 0 }); var style = { left: left, height: this.props.height }; return React.createElement('div', { className: className, style: style }); } }, _onClick: function _onClick( /*object*/event) { this.props.onClick(event, this.props.index, this.props.data); }, _onDoubleClick: function _onDoubleClick( /*object*/event) { this.props.onDoubleClick(event, this.props.index, this.props.data); }, _onMouseDown: function _onMouseDown( /*object*/event) { this.props.onMouseDown(event, this.props.index, this.props.data); }, _onMouseEnter: function _onMouseEnter( /*object*/event) { this.props.onMouseEnter(event, this.props.index, this.props.data); }, _onMouseLeave: function _onMouseLeave( /*object*/event) { this.props.onMouseLeave(event, this.props.index, this.props.data); } }); var FixedDataTableRow = React.createClass({ displayName: 'FixedDataTableRow', mixins: [ReactComponentWithPureRenderMixin], propTypes: { /** * Height of the row. */ height: PropTypes.number.isRequired, /** * Z-index on which the row will be displayed. Used e.g. for keeping * header and footer in front of other rows. */ zIndex: PropTypes.number, /** * The vertical position where the row should render itself */ offsetTop: PropTypes.number.isRequired, /** * Width of the row. */ width: PropTypes.number.isRequired }, render: function render() /*object*/{ var style = { width: this.props.width, height: this.props.height, zIndex: this.props.zIndex ? this.props.zIndex : 0 }; translateDOMPositionXY(style, 0, this.props.offsetTop); return React.createElement( 'div', { style: style, className: cx('fixedDataTableRowLayout/rowWrapper') }, React.createElement(FixedDataTableRowImpl, _extends({}, this.props, { offsetTop: undefined, zIndex: undefined })) ); } }); module.exports = FixedDataTableRow; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableCellGroup.react * @typechecks */ 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var FixedDataTableHelper = __webpack_require__(43); var ImmutableObject = __webpack_require__(77); var React = __webpack_require__(28); var ReactComponentWithPureRenderMixin = __webpack_require__(47); var FixedDataTableCell = __webpack_require__(83); var cx = __webpack_require__(64); var renderToString = FixedDataTableHelper.renderToString; var translateDOMPositionXY = __webpack_require__(65); var PropTypes = React.PropTypes; var DIR_SIGN = FixedDataTableHelper.DIR_SIGN; var EMPTY_OBJECT = new ImmutableObject({}); var FixedDataTableCellGroupImpl = React.createClass({ displayName: 'FixedDataTableCellGroupImpl', mixins: [ReactComponentWithPureRenderMixin], propTypes: { /** * Array of <FixedDataTableColumn />. */ columns: PropTypes.array.isRequired, /** * The row data to render. The data format can be a simple Map object * or an Array of data. */ data: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), left: PropTypes.number, onColumnResize: PropTypes.func, rowHeight: PropTypes.number.isRequired, rowIndex: PropTypes.number.isRequired, width: PropTypes.number.isRequired, zIndex: PropTypes.number.isRequired }, render: function render() /*object*/{ var props = this.props; var columns = props.columns; var cells = new Array(columns.length); var currentPosition = 0; for (var i = 0, j = columns.length; i < j; i++) { var columnProps = columns[i].props; if (!columnProps.allowCellsRecycling || currentPosition - props.left <= props.width && currentPosition - props.left + columnProps.width >= 0) { var key = 'cell_' + i; cells[i] = this._renderCell(props.data, props.rowIndex, props.rowHeight, columnProps, currentPosition, key); } currentPosition += columnProps.width; } var contentWidth = this._getColumnsWidth(columns); var style = { height: props.height, position: 'absolute', width: contentWidth, zIndex: props.zIndex }; translateDOMPositionXY(style, -1 * DIR_SIGN * props.left, 0); return React.createElement( 'div', { className: cx('fixedDataTableCellGroupLayout/cellGroup'), style: style }, cells ); }, _renderCell: function _renderCell( /*?object|array*/rowData, /*number*/rowIndex, /*number*/height, /*object*/columnProps, /*number*/left, /*string*/key) /*object*/{ var cellRenderer = columnProps.cellRenderer || renderToString; var columnData = columnProps.columnData || EMPTY_OBJECT; var cellDataKey = columnProps.dataKey; var isFooterCell = columnProps.isFooterCell; var isHeaderCell = columnProps.isHeaderCell; var cellData; if (isHeaderCell || isFooterCell) { if (rowData == null || rowData[cellDataKey] == null) { cellData = columnProps.label; } else { cellData = rowData[cellDataKey]; } } else { var cellDataGetter = columnProps.cellDataGetter; cellData = cellDataGetter ? cellDataGetter(cellDataKey, rowData) : rowData[cellDataKey]; } var cellIsResizable = columnProps.isResizable && this.props.onColumnResize; var onColumnResize = cellIsResizable ? this.props.onColumnResize : null; var className; if (isHeaderCell || isFooterCell) { className = isHeaderCell ? columnProps.headerClassName : columnProps.footerClassName; } else { className = columnProps.cellClassName; } return React.createElement(FixedDataTableCell, { align: columnProps.align, cellData: cellData, cellDataKey: cellDataKey, cellRenderer: cellRenderer, className: className, columnData: columnData, height: height, isFooterCell: isFooterCell, isHeaderCell: isHeaderCell, key: key, maxWidth: columnProps.maxWidth, minWidth: columnProps.minWidth, onColumnResize: onColumnResize, rowData: rowData, rowIndex: rowIndex, width: columnProps.width, left: left }); }, _getColumnsWidth: function _getColumnsWidth(columns) { var width = 0; for (var i = 0; i < columns.length; ++i) { width += columns[i].props.width; } return width; } }); var FixedDataTableCellGroup = React.createClass({ displayName: 'FixedDataTableCellGroup', mixins: [ReactComponentWithPureRenderMixin], propTypes: { /** * Height of the row. */ height: PropTypes.number.isRequired, offsetLeft: PropTypes.number, /** * Z-index on which the row will be displayed. Used e.g. for keeping * header and footer in front of other rows. */ zIndex: PropTypes.number.isRequired }, getDefaultProps: function getDefaultProps() /*object*/{ return { offsetLeft: 0 }; }, render: function render() /*object*/{ var _props = this.props; var offsetLeft = _props.offsetLeft; var props = _objectWithoutProperties(_props, ['offsetLeft']); var style = { height: props.height }; if (DIR_SIGN === 1) { style.left = offsetLeft; } else { style.right = offsetLeft; } var onColumnResize = props.onColumnResize ? this._onColumnResize : null; return React.createElement( 'div', { style: style, className: cx('fixedDataTableCellGroupLayout/cellGroupWrapper') }, React.createElement(FixedDataTableCellGroupImpl, _extends({}, props, { onColumnResize: onColumnResize })) ); }, _onColumnResize: function _onColumnResize( /*number*/left, /*number*/width, /*?number*/minWidth, /*?number*/maxWidth, /*string|number*/cellDataKey, /*object*/event) { this.props.onColumnResize && this.props.onColumnResize(this.props.offsetLeft, left - this.props.left + width, width, minWidth, maxWidth, cellDataKey, event); } }); module.exports = FixedDataTableCellGroup; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ImmutableObject * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } var ImmutableValue = __webpack_require__(78); var invariant = __webpack_require__(69); var keyOf = __webpack_require__(80); var mergeHelpers = __webpack_require__(81); var checkMergeObjectArgs = mergeHelpers.checkMergeObjectArgs; var isTerminal = mergeHelpers.isTerminal; var SECRET_KEY = keyOf({ _DONT_EVER_TYPE_THIS_SECRET_KEY: null }); /** * Static methods creating and operating on instances of `ImmutableValue`. */ function assertImmutable(immutable) { invariant(immutable instanceof ImmutableValue, 'ImmutableObject: Attempted to set fields on an object that is not an ' + 'instance of ImmutableValue.'); } /** * Static methods for reasoning about instances of `ImmutableObject`. Execute * the freeze commands in `__DEV__` mode to alert the programmer that something * is attempting to mutate. Since freezing is very expensive, we avoid doing it * at all in production. */ var ImmutableObject = (function (_ImmutableValue) { /** * @arguments {array<object>} The arguments is an array of objects that, when * merged together, will form the immutable objects. */ function ImmutableObject() { _classCallCheck(this, ImmutableObject); _get(Object.getPrototypeOf(ImmutableObject.prototype), 'constructor', this).call(this, ImmutableValue[SECRET_KEY]); ImmutableValue.mergeAllPropertiesInto(this, arguments); if (true) { ImmutableValue.deepFreezeRootNode(this); } } _inherits(ImmutableObject, _ImmutableValue); _createClass(ImmutableObject, null, [{ key: 'create', /** * DEPRECATED - prefer to instantiate with new ImmutableObject(). * * @arguments {array<object>} The arguments is an array of objects that, when * merged together, will form the immutable objects. */ value: function create() { var obj = Object.create(ImmutableObject.prototype); ImmutableObject.apply(obj, arguments); return obj; } }, { key: 'set', /** * Returns a new `ImmutableValue` that is identical to the supplied * `ImmutableValue` but with the specified changes, `put`. Any keys that are * in the intersection of `immutable` and `put` retain the ordering of * `immutable`. New keys are placed after keys that exist in `immutable`. * * @param {ImmutableValue} immutable Starting object. * @param {?object} put Fields to merge into the object. * @return {ImmutableValue} The result of merging in `put` fields. */ value: function set(immutable, put) { assertImmutable(immutable); invariant(typeof put === 'object' && put !== undefined && !Array.isArray(put), 'Invalid ImmutableMap.set argument `put`'); return new ImmutableObject(immutable, put); } }, { key: 'setProperty', /** * Sugar for `ImmutableObject.set(ImmutableObject, {fieldName: putField})`. * Look out for key crushing: Use `keyOf()` to guard against it. * * @param {ImmutableValue} immutableObject Object on which to set properties. * @param {string} fieldName Name of the field to set. * @param {*} putField Value of the field to set. * @return {ImmutableValue} new ImmutableValue as described in `set`. */ value: function setProperty(immutableObject, fieldName, putField) { var put = {}; put[fieldName] = putField; return ImmutableObject.set(immutableObject, put); } }, { key: 'deleteProperty', /** * Returns a new immutable object with the given field name removed. * Look out for key crushing: Use `keyOf()` to guard against it. * * @param {ImmutableObject} immutableObject from which to delete the key. * @param {string} droppedField Name of the field to delete. * @return {ImmutableObject} new ImmutableObject without the key */ value: function deleteProperty(immutableObject, droppedField) { var copy = {}; for (var key in immutableObject) { if (key !== droppedField && immutableObject.hasOwnProperty(key)) { copy[key] = immutableObject[key]; } } return new ImmutableObject(copy); } }, { key: 'setDeep', /** * Returns a new `ImmutableValue` that is identical to the supplied object but * with the supplied changes recursively applied. * * Experimental. Likely does not handle `Arrays` correctly. * * @param {ImmutableValue} immutable Object on which to set fields. * @param {object} put Fields to merge into the object. * @return {ImmutableValue} The result of merging in `put` fields. */ value: function setDeep(immutable, put) { assertImmutable(immutable); return _setDeep(immutable, put); } }, { key: 'values', /** * Retrieves an ImmutableObject's values as an array. * * @param {ImmutableValue} immutable * @return {array} */ value: function values(immutable) { return Object.keys(immutable).map(function (key) { return immutable[key]; }); } }]); return ImmutableObject; })(ImmutableValue); function _setDeep(obj, put) { checkMergeObjectArgs(obj, put); var totalNewFields = {}; // To maintain the order of the keys, copy the base object's entries first. var keys = Object.keys(obj); for (var ii = 0; ii < keys.length; ii++) { var key = keys[ii]; if (!put.hasOwnProperty(key)) { totalNewFields[key] = obj[key]; } else if (isTerminal(obj[key]) || isTerminal(put[key])) { totalNewFields[key] = put[key]; } else { totalNewFields[key] = _setDeep(obj[key], put[key]); } } // Apply any new keys that the base obj didn't have. var newKeys = Object.keys(put); for (ii = 0; ii < newKeys.length; ii++) { var newKey = newKeys[ii]; if (obj.hasOwnProperty(newKey)) { continue; } totalNewFields[newKey] = put[newKey]; } return obj instanceof ImmutableValue ? new ImmutableObject(totalNewFields) : put instanceof ImmutableValue ? new ImmutableObject(totalNewFields) : totalNewFields; } module.exports = ImmutableObject; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ImmutableValue * @typechecks */ 'use strict'; var invariant = __webpack_require__(69); var isNode = __webpack_require__(79); var keyOf = __webpack_require__(80); var SECRET_KEY = keyOf({ _DONT_EVER_TYPE_THIS_SECRET_KEY: null }); /** * `ImmutableValue` provides a guarantee of immutability at developer time when * strict mode is used. The extra computations required to enforce immutability * are stripped out in production for performance reasons. `ImmutableValue` * guarantees to enforce immutability for enumerable, own properties. This * allows easy wrapping of `ImmutableValue` with the ability to store * non-enumerable properties on the instance that only your static methods * reason about. In order to achieve IE8 compatibility (which doesn't have the * ability to define non-enumerable properties), modules that want to build * their own reasoning of `ImmutableValue`s and store computations can define * their non-enumerable properties under the name `toString`, and in IE8 only * define a standard property called `toString` which will mistakenly be * considered not enumerable due to its name (but only in IE8). The only * limitation is that no one can store their own `toString` property. * https://developer.mozilla.org/en-US/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug */ var ImmutableValue = (function () { /** * An instance of `ImmutableValue` appears to be a plain JavaScript object, * except `instanceof ImmutableValue` evaluates to `true`, and it is deeply * frozen in development mode. * * @param {number} secret Ensures this isn't accidentally constructed outside * of convenience constructors. If created outside of a convenience * constructor, may not be frozen. Forbidding that use case for now until we * have a better API. */ function ImmutableValue(secret) { _classCallCheck(this, ImmutableValue); invariant(secret === ImmutableValue[SECRET_KEY], 'Only certain classes should create instances of `ImmutableValue`.' + 'You probably want something like ImmutableValueObject.create.'); } _createClass(ImmutableValue, null, [{ key: 'mergeAllPropertiesInto', /** * Helper method for classes that make use of `ImmutableValue`. * @param {ImmutableValue} destination Object to merge properties into. * @param {object} propertyObjects List of objects to merge into * `destination`. */ value: function mergeAllPropertiesInto(destination, propertyObjects) { var argLength = propertyObjects.length; for (var i = 0; i < argLength; i++) { _extends(destination, propertyObjects[i]); } } }, { key: 'deepFreezeRootNode', /** * Freezes the supplied object deeply. Other classes may implement their own * version based on this. * * @param {*} object The object to freeze. */ value: function deepFreezeRootNode(object) { if (isNode(object)) { return; // Don't try to freeze DOM nodes. } Object.freeze(object); // First freeze the object. for (var prop in object) { if (object.hasOwnProperty(prop)) { ImmutableValue.recurseDeepFreeze(object[prop]); } } Object.seal(object); } }, { key: 'recurseDeepFreeze', /** * Differs from `deepFreezeRootNode`, in that we first check if this is a * necessary recursion. If the object is already an `ImmutableValue`, then the * recursion is unnecessary as it is already frozen. That check obviously * wouldn't work for the root node version `deepFreezeRootNode`! */ value: function recurseDeepFreeze(object) { if (isNode(object) || !ImmutableValue.shouldRecurseFreeze(object)) { return; // Don't try to freeze DOM nodes. } Object.freeze(object); // First freeze the object. for (var prop in object) { if (object.hasOwnProperty(prop)) { ImmutableValue.recurseDeepFreeze(object[prop]); } } Object.seal(object); } }, { key: 'shouldRecurseFreeze', /** * Checks if an object should be deep frozen. Instances of `ImmutableValue` * are assumed to have already been deep frozen, so we can have large * `__DEV__` time savings by skipping freezing of them. * * @param {*} object The object to check. * @return {boolean} Whether or not deep freeze is needed. */ value: function shouldRecurseFreeze(object) { return typeof object === 'object' && !(object instanceof ImmutableValue) && object !== null; } }]); return ImmutableValue; })(); ImmutableValue._DONT_EVER_TYPE_THIS_SECRET_KEY = Math.random(); module.exports = ImmutableValue; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isNode * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ 'use strict'; function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ "use strict"; var keyOf = function keyOf(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule mergeHelpers * * requiresPolyfills: Array.isArray */ 'use strict'; var invariant = __webpack_require__(69); var keyMirror = __webpack_require__(82); /** * Maximum number of levels to traverse. Will catch circular structures. * @const */ var MAX_MERGE_DEPTH = 36; /** * We won't worry about edge cases like new String('x') or new Boolean(true). * Functions and Dates are considered terminals, and arrays are not. * @param {*} o The item/object/value to test. * @return {boolean} true iff the argument is a terminal. */ var isTerminal = function isTerminal(o) { return typeof o !== 'object' || o instanceof Date || o === null; }; var mergeHelpers = { MAX_MERGE_DEPTH: MAX_MERGE_DEPTH, isTerminal: isTerminal, /** * Converts null/undefined values into empty object. * * @param {?Object=} arg Argument to be normalized (nullable optional) * @return {!Object} */ normalizeMergeArg: function normalizeMergeArg(arg) { return arg === undefined || arg === null ? {} : arg; }, /** * If merging Arrays, a merge strategy *must* be supplied. If not, it is * likely the caller's fault. If this function is ever called with anything * but `one` and `two` being `Array`s, it is the fault of the merge utilities. * * @param {*} one Array to merge into. * @param {*} two Array to merge from. */ checkMergeArrayArgs: function checkMergeArrayArgs(one, two) { invariant(Array.isArray(one) && Array.isArray(two), 'Tried to merge arrays, instead got %s and %s.', one, two); }, /** * @param {*} one Object to merge into. * @param {*} two Object to merge from. */ checkMergeObjectArgs: function checkMergeObjectArgs(one, two) { mergeHelpers.checkMergeObjectArg(one); mergeHelpers.checkMergeObjectArg(two); }, /** * @param {*} arg */ checkMergeObjectArg: function checkMergeObjectArg(arg) { invariant(!isTerminal(arg) && !Array.isArray(arg), 'Tried to merge an object, instead got %s.', arg); }, /** * @param {*} arg */ checkMergeIntoObjectArg: function checkMergeIntoObjectArg(arg) { invariant((!isTerminal(arg) || typeof arg === 'function') && !Array.isArray(arg), 'Tried to merge into an object, instead got %s.', arg); }, /** * Checks that a merge was not given a circular object or an object that had * too great of depth. * * @param {number} Level of recursion to validate against maximum. */ checkMergeLevel: function checkMergeLevel(level) { invariant(level < MAX_MERGE_DEPTH, 'Maximum deep merge depth exceeded. You may be attempting to merge ' + 'circular structures in an unsupported way.'); }, /** * Checks that the supplied merge strategy is valid. * * @param {string} Array merge strategy. */ checkArrayStrategy: function checkArrayStrategy(strategy) { invariant(strategy === undefined || strategy in mergeHelpers.ArrayStrategies, 'You must provide an array strategy to deep merge functions to ' + 'instruct the deep merge how to resolve merging two arrays.'); }, /** * Set of possible behaviors of merge algorithms when encountering two Arrays * that must be merged together. * - `clobber`: The left `Array` is ignored. * - `indexByIndex`: The result is achieved by recursively deep merging at * each index. (not yet supported.) */ ArrayStrategies: keyMirror({ Clobber: true, IndexByIndex: true }) }; module.exports = mergeHelpers; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyMirror * @typechecks static-only */ 'use strict'; var invariant = __webpack_require__(69); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function keyMirror(obj) { var ret = {}; var key; invariant(obj instanceof Object && !Array.isArray(obj), 'keyMirror(...): Argument must be an object.'); for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableCell.react * @typechecks */ 'use strict'; var FixedDataTableHelper = __webpack_require__(43); var ImmutableObject = __webpack_require__(77); var React = __webpack_require__(28); var ReactComponentWithPureRenderMixin = __webpack_require__(47); var cloneWithProps = __webpack_require__(30); var cx = __webpack_require__(64); var joinClasses = __webpack_require__(84); var DIR_SIGN = FixedDataTableHelper.DIR_SIGN; var PropTypes = React.PropTypes; var DEFAULT_PROPS = new ImmutableObject({ align: 'left', highlighted: false, isFooterCell: false, isHeaderCell: false }); var FixedDataTableCell = React.createClass({ displayName: 'FixedDataTableCell', mixins: [ReactComponentWithPureRenderMixin], propTypes: { align: PropTypes.oneOf(['left', 'center', 'right']), className: PropTypes.string, highlighted: PropTypes.bool, isFooterCell: PropTypes.bool, isHeaderCell: PropTypes.bool, width: PropTypes.number.isRequired, minWidth: PropTypes.number, maxWidth: PropTypes.number, height: PropTypes.number.isRequired, /** * The cell data that will be passed to `cellRenderer` to render. */ cellData: PropTypes.any, /** * The key to retrieve the cell data from the `rowData`. */ cellDataKey: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.number.isRequired]), /** * The function to render the `cellData`. */ cellRenderer: PropTypes.func.isRequired, /** * The column data that will be passed to `cellRenderer` to render. */ columnData: PropTypes.any, /** * The row data that will be passed to `cellRenderer` to render. */ rowData: PropTypes.oneOfType([PropTypes.object.isRequired, PropTypes.array.isRequired]), /** * The row index that will be passed to `cellRenderer` to render. */ rowIndex: PropTypes.number.isRequired, /** * Callback for when resizer knob (in FixedDataTableCell) is clicked * to initialize resizing. Please note this is only on the cells * in the header. * @param number combinedWidth * @param number left * @param number width * @param number minWidth * @param number maxWidth * @param number|string columnKey * @param object event */ onColumnResize: PropTypes.func, /** * The left offset in pixels of the cell. */ left: PropTypes.number }, getDefaultProps: function getDefaultProps() /*object*/{ return DEFAULT_PROPS; }, render: function render() /*object*/{ var props = this.props; var style = { height: props.height, width: props.width }; if (DIR_SIGN === 1) { style.left = props.left; } else { style.right = props.left; } var className = joinClasses(cx({ 'fixedDataTableCellLayout/main': true, 'fixedDataTableCellLayout/lastChild': props.lastChild, 'fixedDataTableCellLayout/alignRight': props.align === 'right', 'fixedDataTableCellLayout/alignCenter': props.align === 'center', 'public/fixedDataTableCell/alignRight': props.align === 'right', 'public/fixedDataTableCell/highlighted': props.highlighted, 'public/fixedDataTableCell/main': true }), props.className); var content; if (props.isHeaderCell || props.isFooterCell) { content = props.cellRenderer(props.cellData, props.cellDataKey, props.columnData, props.rowData, props.width); } else { content = props.cellRenderer(props.cellData, props.cellDataKey, props.rowData, props.rowIndex, props.columnData, props.width); } var contentClass = cx('public/fixedDataTableCell/cellContent'); if (React.isValidElement(content)) { content = cloneWithProps(content, { key: content.key, className: contentClass }); } else { content = React.createElement( 'div', { className: contentClass }, content ); } var columnResizerComponent; if (props.onColumnResize) { var columnResizerStyle = { height: props.height }; columnResizerComponent = React.createElement( 'div', { className: cx('fixedDataTableCellLayout/columnResizerContainer'), style: columnResizerStyle, onMouseDown: this._onColumnResizerMouseDown }, React.createElement('div', { className: joinClasses(cx('fixedDataTableCellLayout/columnResizerKnob'), cx('public/fixedDataTableCell/columnResizerKnob')), style: columnResizerStyle }) ); } var innerStyle = { height: props.height, width: props.width }; return React.createElement( 'div', { className: className, style: style }, columnResizerComponent, React.createElement( 'div', { className: joinClasses(cx('fixedDataTableCellLayout/wrap1'), cx('public/fixedDataTableCell/wrap1')), style: innerStyle }, React.createElement( 'div', { className: joinClasses(cx('fixedDataTableCellLayout/wrap2'), cx('public/fixedDataTableCell/wrap2')) }, React.createElement( 'div', { className: joinClasses(cx('fixedDataTableCellLayout/wrap3'), cx('public/fixedDataTableCell/wrap3')) }, content ) ) ) ); }, _onColumnResizerMouseDown: function _onColumnResizerMouseDown( /*object*/event) { this.props.onColumnResize(this.props.left, this.props.width, this.props.minWidth, this.props.maxWidth, this.props.cellDataKey, event); } }); module.exports = FixedDataTableCell; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule joinClasses * @typechecks static-only */ 'use strict'; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} className * @return {string} */ function joinClasses(className /*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * This is to be used with the FixedDataTable. It is a read line * that when you click on a column that is resizable appears and allows * you to resize the corresponding column. * * @providesModule FixedDataTableColumnResizeHandle.react * @typechecks */ 'use strict'; var DOMMouseMoveTracker = __webpack_require__(59); var Locale = __webpack_require__(44); var React = __webpack_require__(28); var ReactComponentWithPureRenderMixin = __webpack_require__(47); var clamp = __webpack_require__(74); var cx = __webpack_require__(64); var PropTypes = React.PropTypes; var FixedDataTableColumnResizeHandle = React.createClass({ displayName: 'FixedDataTableColumnResizeHandle', mixins: [ReactComponentWithPureRenderMixin], propTypes: { visible: PropTypes.bool.isRequired, /** * This is the height of the line */ height: PropTypes.number.isRequired, /** * Offset from left border of the table, please note * that the line is a border on diff. So this is really the * offset of the column itself. */ leftOffset: PropTypes.number.isRequired, /** * Height of the clickable region of the line. * This is assumed to be at the top of the line. */ knobHeight: PropTypes.number.isRequired, /** * The line is a border on a diff, so this is essentially * the width of column. */ initialWidth: PropTypes.number, /** * The minimum width this dragger will collapse to */ minWidth: PropTypes.number, /** * The maximum width this dragger will collapse to */ maxWidth: PropTypes.number, /** * Initial click event on the header cell. */ initialEvent: PropTypes.object, /** * When resizing is complete this is called. */ onColumnResizeEnd: PropTypes.func, /** * Column key for the column being resized. */ columnKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) }, getInitialState: function getInitialState() /*object*/{ return { width: 0, cursorDelta: 0 }; }, componentWillReceiveProps: function componentWillReceiveProps( /*object*/newProps) { if (newProps.initialEvent && !this._mouseMoveTracker.isDragging()) { this._mouseMoveTracker.captureMouseMoves(newProps.initialEvent); this.setState({ width: newProps.initialWidth, cursorDelta: newProps.initialWidth }); } }, componentDidMount: function componentDidMount() { this._mouseMoveTracker = new DOMMouseMoveTracker(this._onMove, this._onColumnResizeEnd, document.body); }, componentWillUnmount: function componentWillUnmount() { this._mouseMoveTracker.releaseMouseMoves(); this._mouseMoveTracker = null; }, render: function render() /*object*/{ var style = { width: this.state.width, height: this.props.height }; if (Locale.isRTL()) { style.right = this.props.leftOffset; } else { style.left = this.props.leftOffset; } return React.createElement( 'div', { className: cx({ 'fixedDataTableColumnResizerLineLayout/main': true, 'fixedDataTableColumnResizerLineLayout/hiddenElem': !this.props.visible, 'public/fixedDataTableColumnResizerLine/main': true }), style: style }, React.createElement('div', { className: cx('fixedDataTableColumnResizerLineLayout/mouseArea'), style: { height: this.props.height } }) ); }, _onMove: function _onMove( /*number*/deltaX) { if (Locale.isRTL()) { deltaX = -deltaX; } var newWidth = this.state.cursorDelta + deltaX; var newColumnWidth = clamp(this.props.minWidth, newWidth, this.props.maxWidth); // Please note cursor delta is the different between the currently width // and the new width. this.setState({ width: newColumnWidth, cursorDelta: newWidth }); }, _onColumnResizeEnd: function _onColumnResizeEnd() { this._mouseMoveTracker.releaseMouseMoves(); this.props.onColumnResizeEnd(this.state.width, this.props.columnKey); } }); module.exports = FixedDataTableColumnResizeHandle; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableScrollHelper * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var PrefixIntervalTree = __webpack_require__(87); var clamp = __webpack_require__(74); var BUFFER_ROWS = 5; var NO_ROWS_SCROLL_RESULT = { index: 0, offset: 0, position: 0, contentHeight: 0 }; var FixedDataTableScrollHelper = (function () { function FixedDataTableScrollHelper( /*number*/rowCount, /*number*/defaultRowHeight, /*number*/viewportHeight, /*?function*/rowHeightGetter) { _classCallCheck(this, FixedDataTableScrollHelper); this._rowOffsets = PrefixIntervalTree.uniform(rowCount, defaultRowHeight); this._storedHeights = new Array(rowCount); for (var i = 0; i < rowCount; ++i) { this._storedHeights[i] = defaultRowHeight; } this._rowCount = rowCount; this._position = 0; this._contentHeight = rowCount * defaultRowHeight; this._defaultRowHeight = defaultRowHeight; this._rowHeightGetter = rowHeightGetter ? rowHeightGetter : function () { return defaultRowHeight; }; this._viewportHeight = viewportHeight; this.scrollRowIntoView = this.scrollRowIntoView.bind(this); this.setViewportHeight = this.setViewportHeight.bind(this); this.scrollBy = this.scrollBy.bind(this); this.scrollTo = this.scrollTo.bind(this); this.scrollToRow = this.scrollToRow.bind(this); this.setRowHeightGetter = this.setRowHeightGetter.bind(this); this.getContentHeight = this.getContentHeight.bind(this); this.getRowPosition = this.getRowPosition.bind(this); this._updateHeightsInViewport(0, 0); } _createClass(FixedDataTableScrollHelper, [{ key: 'setRowHeightGetter', value: function setRowHeightGetter( /*function*/rowHeightGetter) { this._rowHeightGetter = rowHeightGetter; } }, { key: 'setViewportHeight', value: function setViewportHeight( /*number*/viewportHeight) { this._viewportHeight = viewportHeight; } }, { key: 'getContentHeight', value: function getContentHeight() /*number*/{ return this._contentHeight; } }, { key: '_updateHeightsInViewport', value: function _updateHeightsInViewport( /*number*/firstRowIndex, /*number*/firstRowOffset) { var top = firstRowOffset; var index = firstRowIndex; while (top <= this._viewportHeight && index < this._rowCount) { this._updateRowHeight(index); top += this._storedHeights[index]; index++; } } }, { key: '_updateHeightsAboveViewport', value: function _updateHeightsAboveViewport( /*number*/firstRowIndex) { var index = firstRowIndex - 1; while (index >= 0 && index >= firstRowIndex - BUFFER_ROWS) { var delta = this._updateRowHeight(index); this._position += delta; index--; } } }, { key: '_updateRowHeight', value: function _updateRowHeight( /*number*/rowIndex) /*number*/{ if (rowIndex < 0 || rowIndex >= this._rowCount) { return 0; } var newHeight = this._rowHeightGetter(rowIndex); if (newHeight !== this._storedHeights[rowIndex]) { var change = newHeight - this._storedHeights[rowIndex]; this._rowOffsets.set(rowIndex, newHeight); this._storedHeights[rowIndex] = newHeight; this._contentHeight += change; return change; } return 0; } }, { key: 'getRowPosition', value: function getRowPosition( /*number*/rowIndex) /*number*/{ this._updateRowHeight(rowIndex); return this._rowOffsets.sumUntil(rowIndex); } }, { key: 'scrollBy', value: function scrollBy( /*number*/delta) /*object*/{ if (this._rowCount === 0) { return NO_ROWS_SCROLL_RESULT; } var firstRow = this._rowOffsets.greatestLowerBound(this._position); firstRow = clamp(0, firstRow, Math.max(this._rowCount - 1, 0)); var firstRowPosition = this._rowOffsets.sumUntil(firstRow); var rowIndex = firstRow; var position = this._position; var rowHeightChange = this._updateRowHeight(rowIndex); if (firstRowPosition !== 0) { position += rowHeightChange; } var visibleRowHeight = this._storedHeights[rowIndex] - (position - firstRowPosition); if (delta >= 0) { while (delta > 0 && rowIndex < this._rowCount) { if (delta < visibleRowHeight) { position += delta; delta = 0; } else { delta -= visibleRowHeight; position += visibleRowHeight; rowIndex++; } if (rowIndex < this._rowCount) { this._updateRowHeight(rowIndex); visibleRowHeight = this._storedHeights[rowIndex]; } } } else if (delta < 0) { delta = -delta; var invisibleRowHeight = this._storedHeights[rowIndex] - visibleRowHeight; while (delta > 0 && rowIndex >= 0) { if (delta < invisibleRowHeight) { position -= delta; delta = 0; } else { position -= invisibleRowHeight; delta -= invisibleRowHeight; rowIndex--; } if (rowIndex >= 0) { var change = this._updateRowHeight(rowIndex); invisibleRowHeight = this._storedHeights[rowIndex]; position += change; } } } var maxPosition = this._contentHeight - this._viewportHeight; position = clamp(0, position, maxPosition); this._position = position; var firstRowIndex = this._rowOffsets.greatestLowerBound(position); firstRowIndex = clamp(0, firstRowIndex, Math.max(this._rowCount - 1, 0)); firstRowPosition = this._rowOffsets.sumUntil(firstRowIndex); var firstRowOffset = firstRowPosition - position; this._updateHeightsInViewport(firstRowIndex, firstRowOffset); this._updateHeightsAboveViewport(firstRowIndex); return { index: firstRowIndex, offset: firstRowOffset, position: this._position, contentHeight: this._contentHeight }; } }, { key: '_getRowAtEndPosition', value: function _getRowAtEndPosition( /*number*/rowIndex) /*number*/{ // We need to update enough rows above the selected one to be sure that when // we scroll to selected position all rows between first shown and selected // one have most recent heights computed and will not resize this._updateRowHeight(rowIndex); var currentRowIndex = rowIndex; var top = this._storedHeights[currentRowIndex]; while (top < this._viewportHeight && currentRowIndex >= 0) { currentRowIndex--; if (currentRowIndex >= 0) { this._updateRowHeight(currentRowIndex); top += this._storedHeights[currentRowIndex]; } } var position = this._rowOffsets.sumTo(rowIndex) - this._viewportHeight; if (position < 0) { position = 0; } return position; } }, { key: 'scrollTo', value: function scrollTo( /*number*/position) /*object*/{ if (this._rowCount === 0) { return NO_ROWS_SCROLL_RESULT; } if (position <= 0) { // If position less than or equal to 0 first row should be fully visible // on top this._position = 0; this._updateHeightsInViewport(0, 0); return { index: 0, offset: 0, position: this._position, contentHeight: this._contentHeight }; } else if (position >= this._contentHeight - this._viewportHeight) { // If position is equal to or greater than max scroll value, we need // to make sure to have bottom border of last row visible. var rowIndex = this._rowCount - 1; position = this._getRowAtEndPosition(rowIndex); } this._position = position; var firstRowIndex = this._rowOffsets.greatestLowerBound(position); firstRowIndex = clamp(0, firstRowIndex, Math.max(this._rowCount - 1, 0)); var firstRowPosition = this._rowOffsets.sumUntil(firstRowIndex); var firstRowOffset = firstRowPosition - position; this._updateHeightsInViewport(firstRowIndex, firstRowOffset); this._updateHeightsAboveViewport(firstRowIndex); return { index: firstRowIndex, offset: firstRowOffset, position: this._position, contentHeight: this._contentHeight }; } }, { key: 'scrollToRow', /** * Allows to scroll to selected row with specified offset. It always * brings that row to top of viewport with that offset */ value: function scrollToRow( /*number*/rowIndex, /*number*/offset) /*object*/{ rowIndex = clamp(0, rowIndex, Math.max(this._rowCount - 1, 0)); offset = clamp(-this._storedHeights[rowIndex], offset, 0); var firstRow = this._rowOffsets.sumUntil(rowIndex); return this.scrollTo(firstRow - offset); } }, { key: 'scrollRowIntoView', /** * Allows to scroll to selected row by bringing it to viewport with minimal * scrolling. This that if row is fully visible, scroll will not be changed. * If top border of row is above top of viewport it will be scrolled to be * fully visible on the top of viewport. If the bottom border of row is * below end of viewport, it will be scrolled up to be fully visible on the * bottom of viewport. */ value: function scrollRowIntoView( /*number*/rowIndex) /*object*/{ rowIndex = clamp(0, rowIndex, Math.max(this._rowCount - 1, 0)); var rowBegin = this._rowOffsets.sumUntil(rowIndex); var rowEnd = rowBegin + this._storedHeights[rowIndex]; if (rowBegin < this._position) { return this.scrollTo(rowBegin); } else if (this._position + this._viewportHeight < rowEnd) { var position = this._getRowAtEndPosition(rowIndex); return this.scrollTo(position); } return this.scrollTo(this._position); } }]); return FixedDataTableScrollHelper; })(); module.exports = FixedDataTableScrollHelper; /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PrefixIntervalTree * @flow * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var invariant = __webpack_require__(69); var parent = function parent(node) { return Math.floor(node / 2); }; var Int32Array = global.Int32Array || function (size) { var xs = []; for (var i = size - 1; i >= 0; --i) { xs[i] = 0; } return xs; }; /** * Computes the next power of 2 after or equal to x. */ function ceilLog2(x) { var y = 1; while (y < x) { y *= 2; } return y; } /** * A prefix interval tree stores an numeric array and the partial sums of that * array. It is optimized for updating the values of the array without * recomputing all of the partial sums. * * - O(ln n) update * - O(1) lookup * - O(ln n) compute a partial sum * - O(n) space * * Note that the sequence of partial sums is one longer than the array, so that * the first partial sum is always 0, and the last partial sum is the sum of the * entire array. */ var PrefixIntervalTree = (function () { function PrefixIntervalTree(xs) { _classCallCheck(this, PrefixIntervalTree); this._size = xs.length; this._half = ceilLog2(this._size); this._heap = new Int32Array(2 * this._half); var i; for (i = 0; i < this._size; ++i) { this._heap[this._half + i] = xs[i]; } for (i = this._half - 1; i > 0; --i) { this._heap[i] = this._heap[2 * i] + this._heap[2 * i + 1]; } } _createClass(PrefixIntervalTree, [{ key: 'set', value: function set(index, value) { invariant(0 <= index && index < this._size, 'Index out of range %s', index); var node = this._half + index; this._heap[node] = value; node = parent(node); for (; node !== 0; node = parent(node)) { this._heap[node] = this._heap[2 * node] + this._heap[2 * node + 1]; } } }, { key: 'get', value: function get(index) { invariant(0 <= index && index < this._size, 'Index out of range %s', index); var node = this._half + index; return this._heap[node]; } }, { key: 'getSize', value: function getSize() { return this._size; } }, { key: 'sumUntil', /** * Returns the sum get(0) + get(1) + ... + get(end - 1). */ value: function sumUntil(end) { invariant(0 <= end && end < this._size + 1, 'Index out of range %s', end); if (end === 0) { return 0; } var node = this._half + end - 1; var sum = this._heap[node]; for (; node !== 1; node = parent(node)) { if (node % 2 === 1) { sum += this._heap[node - 1]; } } return sum; } }, { key: 'sumTo', /** * Returns the sum get(0) + get(1) + ... + get(inclusiveEnd). */ value: function sumTo(inclusiveEnd) { invariant(0 <= inclusiveEnd && inclusiveEnd < this._size, 'Index out of range %s', inclusiveEnd); return this.sumUntil(inclusiveEnd + 1); } }, { key: 'sum', /** * Returns the sum get(begin) + get(begin + 1) + ... + get(end - 1). */ value: function sum(begin, end) { invariant(begin <= end, 'Begin must precede end'); return this.sumUntil(end) - this.sumUntil(begin); } }, { key: 'greatestLowerBound', /** * Returns the smallest i such that 0 <= i <= size and sumUntil(i) <= t, or * -1 if no such i exists. */ value: function greatestLowerBound(t) { if (t < 0) { return -1; } var node = 1; if (this._heap[node] <= t) { return this._size; } while (node < this._half) { var leftSum = this._heap[2 * node]; if (t < leftSum) { node = 2 * node; } else { node = 2 * node + 1; t -= leftSum; } } return node - this._half; } }, { key: 'greatestStrictLowerBound', /** * Returns the smallest i such that 0 <= i <= size and sumUntil(i) < t, or * -1 if no such i exists. */ value: function greatestStrictLowerBound(t) { if (t <= 0) { return -1; } var node = 1; if (this._heap[node] < t) { return this._size; } while (node < this._half) { var leftSum = this._heap[2 * node]; if (t <= leftSum) { node = 2 * node; } else { node = 2 * node + 1; t -= leftSum; } } return node - this._half; } }, { key: 'leastUpperBound', /** * Returns the smallest i such that 0 <= i <= size and t <= sumUntil(i), or * size + 1 if no such i exists. */ value: function leastUpperBound(t) { return this.greatestStrictLowerBound(t) + 1; } }, { key: 'leastStrictUpperBound', /** * Returns the smallest i such that 0 <= i <= size and t < sumUntil(i), or * size + 1 if no such i exists. */ value: function leastStrictUpperBound(t) { return this.greatestLowerBound(t) + 1; } }], [{ key: 'uniform', value: function uniform(size, initialValue) { var xs = []; for (var i = size - 1; i >= 0; --i) { xs[i] = initialValue; } return new PrefixIntervalTree(xs); } }, { key: 'empty', value: function empty(size) { return PrefixIntervalTree.uniform(size, 0); } }]); return PrefixIntervalTree; })(); module.exports = PrefixIntervalTree; /** * Number of elements in the array */ /** * Half the size of the heap. It is also the number of non-leaf nodes, and the * index of the first element in the heap. Always a power of 2. */ /** * Binary heap */ /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule debounceCore * @typechecks */ /** * Invokes the given callback after a specified number of milliseconds have * elapsed, ignoring subsequent calls. * * For example, if you wanted to update a preview after the user stops typing * you could do the following: * * elem.addEventListener('keyup', debounce(this.updatePreview, 250), false); * * The returned function has a reset method which can be called to cancel a * pending invocation. * * var debouncedUpdatePreview = debounce(this.updatePreview, 250); * elem.addEventListener('keyup', debouncedUpdatePreview, false); * * // later, to cancel pending calls * debouncedUpdatePreview.reset(); * * @param {function} func - the function to debounce * @param {number} wait - how long to wait in milliseconds * @param {*} context - optional context to invoke the function in * @param {?function} setTimeoutFunc - an implementation of setTimeout * if nothing is passed in the default setTimeout function is used * @param {?function} clearTimeoutFunc - an implementation of clearTimeout * if nothing is passed in the default clearTimeout function is used */ "use strict"; function debounce(func, wait, context, setTimeoutFunc, clearTimeoutFunc) { setTimeoutFunc = setTimeoutFunc || setTimeout; clearTimeoutFunc = clearTimeoutFunc || clearTimeout; var timeout; function debouncer() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } debouncer.reset(); var callback = function callback() { func.apply(context, args); }; callback.__SMmeta = func.__SMmeta; timeout = setTimeoutFunc(callback, wait); } debouncer.reset = function () { clearTimeoutFunc(timeout); }; return debouncer; } module.exports = debounce; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual */ 'use strict'; /** * Performs equality by iterating through keys on an object and returning * false when any key has values which are not strictly equal between * objA and objB. Returns true when the values of all keys are strictly equal. * * @return {boolean} */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB); for (var i = 0; i < keysA.length; i++) { if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } module.exports = shallowEqual; /***/ } /******/ ]) }); ;
ljharb/cdnjs
ajax/libs/fixed-data-table/0.4.0/fixed-data-table.js
JavaScript
mit
243,392
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace OneHandedUse_TailoredMultipleViews { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage_OneHanded : Page { public MainPage_OneHanded() { this.InitializeComponent(); } } }
washcycle/Windows-universal-samples
xaml_tailoredmultipleviews/CS/TailoredMultipleViews/MainPage_OneHanded.xaml.cs
C#
mit
853
/* * Copyright (C) 2011 Jake Wharton * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.sample.demos; import android.app.SearchManager; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.os.Bundle; import android.provider.BaseColumns; import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.widget.SearchView; public class SearchViews extends SherlockActivity implements SearchView.OnQueryTextListener, SearchView.OnSuggestionListener { private static final String[] COLUMNS = { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, }; private SuggestionsAdapter mSuggestionsAdapter; @Override public boolean onCreateOptionsMenu(Menu menu) { //Used to put dark icons on light action bar boolean isLight = SampleList.THEME == R.style.Theme_Sherlock_Light; //Create the search view SearchView searchView = new SearchView(getSupportActionBar().getThemedContext()); searchView.setQueryHint("Search for countries…"); searchView.setOnQueryTextListener(this); searchView.setOnSuggestionListener(this); if (mSuggestionsAdapter == null) { MatrixCursor cursor = new MatrixCursor(COLUMNS); cursor.addRow(new String[]{"1", "'Murica"}); cursor.addRow(new String[]{"2", "Canada"}); cursor.addRow(new String[]{"3", "Denmark"}); mSuggestionsAdapter = new SuggestionsAdapter(getSupportActionBar().getThemedContext(), cursor); } searchView.setSuggestionsAdapter(mSuggestionsAdapter); menu.add("Search") .setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.abs__ic_search) .setActionView(searchView) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW); return true; } @Override protected void onCreate(Bundle savedInstanceState) { setTheme(SampleList.THEME); //Used for theme switching in samples super.onCreate(savedInstanceState); setContentView(R.layout.text); ((TextView)findViewById(R.id.text)).setText(R.string.search_views_content); } @Override public boolean onQueryTextSubmit(String query) { Toast.makeText(this, "You searched for: " + query, Toast.LENGTH_LONG).show(); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } @Override public boolean onSuggestionSelect(int position) { return false; } @Override public boolean onSuggestionClick(int position) { Cursor c = (Cursor) mSuggestionsAdapter.getItem(position); String query = c.getString(c.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1)); Toast.makeText(this, "Suggestion clicked: " + query, Toast.LENGTH_LONG).show(); return true; } private class SuggestionsAdapter extends CursorAdapter { public SuggestionsAdapter(Context context, Cursor c) { super(context, c, 0); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); View v = inflater.inflate(android.R.layout.simple_list_item_1, parent, false); return v; } @Override public void bindView(View view, Context context, Cursor cursor) { TextView tv = (TextView) view; final int textIndex = cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1); tv.setText(cursor.getString(textIndex)); } } }
sbazzaza/tournama
src/client_library/ActionBarSherlock-4.4.0/actionbarsherlock-samples/demos/src/com/actionbarsherlock/sample/demos/SearchViews.java
Java
gpl-2.0
4,579
/* * Copyright 2008-2011 Freescale Semiconductor, Inc. * * (C) Copyright 2000 * Wolfgang Denk, DENX Software Engineering, [email protected]. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <asm/fsl_law.h> #include <asm/mmu.h> struct law_entry law_table[] = { SET_LAW(CONFIG_SYS_FLASH_BASE_PHYS, LAW_SIZE_256M, LAW_TRGT_IF_LBC), #ifdef CONFIG_SYS_BMAN_MEM_PHYS SET_LAW(CONFIG_SYS_BMAN_MEM_PHYS, LAW_SIZE_2M, LAW_TRGT_IF_BMAN), #endif #ifdef CONFIG_SYS_QMAN_MEM_PHYS SET_LAW(CONFIG_SYS_QMAN_MEM_PHYS, LAW_SIZE_2M, LAW_TRGT_IF_QMAN), #endif #ifdef PIXIS_BASE_PHYS SET_LAW(PIXIS_BASE_PHYS, LAW_SIZE_4K, LAW_TRGT_IF_LBC), #endif #ifdef CPLD_BASE_PHYS SET_LAW(CPLD_BASE_PHYS, LAW_SIZE_4K, LAW_TRGT_IF_LBC), #endif #ifdef CONFIG_SYS_DCSRBAR_PHYS /* Limit DCSR to 32M to access NPC Trace Buffer */ SET_LAW(CONFIG_SYS_DCSRBAR_PHYS, LAW_SIZE_32M, LAW_TRGT_IF_DCSR), #endif #ifdef CONFIG_SYS_NAND_BASE_PHYS SET_LAW(CONFIG_SYS_NAND_BASE_PHYS, LAW_SIZE_1M, LAW_TRGT_IF_LBC), #endif }; int num_law_entries = ARRAY_SIZE(law_table);
lxl1140989/dmsdk
uboot/u-boot-dm6291/board/freescale/common/p_corenet/law.c
C
gpl-2.0
1,805
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Text Area dialog window. --> <html> <head> <title>Text Area Properties</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta content="noindex, nofollow" name="robots"> <script src="common/fck_dialog_common.js" type="text/javascript"></script> <script type="text/javascript"> var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; // Gets the document DOM var oDOM = oEditor.FCK.EditorDocument ; var oActiveEl = dialog.Selection.GetSelectedElement() ; window.onload = function() { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage(document) ; if ( oActiveEl && oActiveEl.tagName == 'TEXTAREA' ) { GetE('txtName').value = oActiveEl.name ; GetE('txtCols').value = GetAttribute( oActiveEl, 'cols' ) ; GetE('txtRows').value = GetAttribute( oActiveEl, 'rows' ) ; } else oActiveEl = null ; dialog.SetOkButton( true ) ; dialog.SetAutoSize( true ) ; SelectField( 'txtName' ) ; } function Ok() { oEditor.FCKUndo.SaveUndoStep() ; oActiveEl = CreateNamedElement( oEditor, oActiveEl, 'TEXTAREA', {name: GetE('txtName').value} ) ; SetAttribute( oActiveEl, 'cols', GetE('txtCols').value ) ; SetAttribute( oActiveEl, 'rows', GetE('txtRows').value ) ; return true ; } </script> </head> <body style="overflow: hidden"> <table height="100%" width="100%"> <tr> <td align="center"> <table border="0" cellpadding="0" cellspacing="0" width="80%"> <tr> <td> <span fckLang="DlgTextareaName">Name</span><br> <input type="text" id="txtName" style="WIDTH: 100%"> <span fckLang="DlgTextareaCols">Collumns</span><br> <input id="txtCols" type="text" size="5"> <br> <span fckLang="DlgTextareaRows">Rows</span><br> <input id="txtRows" type="text" size="5"> </td> </tr> </table> </td> </tr> </table> </body> </html>
anoam/limb
wysiwyg/shared/fckeditor/editor/dialog/fck_textarea.html
HTML
lgpl-2.1
2,697
// @declaration: true interface foo { foo(); f2 (f: ()=> void); }
billti/TypeScript
tests/cases/compiler/interfaceOnly.ts
TypeScript
apache-2.0
77
// SPDX-License-Identifier: GPL-2.0-or-later /* * av7110_av.c: audio and video MPEG decoder stuff * * Copyright (C) 1999-2002 Ralph Metzler * & Marcus Metzler for convergence integrated media GmbH * * originally based on code by: * Copyright (C) 1998,1999 Christian Theiss <[email protected]> * * the project's page is at https://linuxtv.org */ #include <linux/ethtool.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/delay.h> #include <linux/fs.h> #include "av7110.h" #include "av7110_hw.h" #include "av7110_av.h" #include "av7110_ipack.h" /* MPEG-2 (ISO 13818 / H.222.0) stream types */ #define PROG_STREAM_MAP 0xBC #define PRIVATE_STREAM1 0xBD #define PADDING_STREAM 0xBE #define PRIVATE_STREAM2 0xBF #define AUDIO_STREAM_S 0xC0 #define AUDIO_STREAM_E 0xDF #define VIDEO_STREAM_S 0xE0 #define VIDEO_STREAM_E 0xEF #define ECM_STREAM 0xF0 #define EMM_STREAM 0xF1 #define DSM_CC_STREAM 0xF2 #define ISO13522_STREAM 0xF3 #define PROG_STREAM_DIR 0xFF #define PTS_DTS_FLAGS 0xC0 //pts_dts flags #define PTS_ONLY 0x80 #define PTS_DTS 0xC0 #define TS_SIZE 188 #define TRANS_ERROR 0x80 #define PAY_START 0x40 #define TRANS_PRIO 0x20 #define PID_MASK_HI 0x1F //flags #define TRANS_SCRMBL1 0x80 #define TRANS_SCRMBL2 0x40 #define ADAPT_FIELD 0x20 #define PAYLOAD 0x10 #define COUNT_MASK 0x0F // adaptation flags #define DISCON_IND 0x80 #define RAND_ACC_IND 0x40 #define ES_PRI_IND 0x20 #define PCR_FLAG 0x10 #define OPCR_FLAG 0x08 #define SPLICE_FLAG 0x04 #define TRANS_PRIV 0x02 #define ADAP_EXT_FLAG 0x01 // adaptation extension flags #define LTW_FLAG 0x80 #define PIECE_RATE 0x40 #define SEAM_SPLICE 0x20 static void p_to_t(u8 const *buf, long int length, u16 pid, u8 *counter, struct dvb_demux_feed *feed); static int write_ts_to_decoder(struct av7110 *av7110, int type, const u8 *buf, size_t len); int av7110_record_cb(struct dvb_filter_pes2ts *p2t, u8 *buf, size_t len) { struct dvb_demux_feed *dvbdmxfeed = (struct dvb_demux_feed *) p2t->priv; if (!(dvbdmxfeed->ts_type & TS_PACKET)) return 0; if (buf[3] == 0xe0) // video PES do not have a length in TS buf[4] = buf[5] = 0; if (dvbdmxfeed->ts_type & TS_PAYLOAD_ONLY) return dvbdmxfeed->cb.ts(buf, len, NULL, 0, &dvbdmxfeed->feed.ts, NULL); else return dvb_filter_pes2ts(p2t, buf, len, 1); } static int dvb_filter_pes2ts_cb(void *priv, unsigned char *data) { struct dvb_demux_feed *dvbdmxfeed = (struct dvb_demux_feed *) priv; dvbdmxfeed->cb.ts(data, 188, NULL, 0, &dvbdmxfeed->feed.ts, NULL); return 0; } int av7110_av_start_record(struct av7110 *av7110, int av, struct dvb_demux_feed *dvbdmxfeed) { int ret = 0; struct dvb_demux *dvbdmx = dvbdmxfeed->demux; dprintk(2, "av7110:%p, , dvb_demux_feed:%p\n", av7110, dvbdmxfeed); if (av7110->playing || (av7110->rec_mode & av)) return -EBUSY; av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Stop, 0); dvbdmx->recording = 1; av7110->rec_mode |= av; switch (av7110->rec_mode) { case RP_AUDIO: dvb_filter_pes2ts_init(&av7110->p2t[0], dvbdmx->pesfilter[0]->pid, dvb_filter_pes2ts_cb, (void *) dvbdmx->pesfilter[0]); ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Record, 2, AudioPES, 0); break; case RP_VIDEO: dvb_filter_pes2ts_init(&av7110->p2t[1], dvbdmx->pesfilter[1]->pid, dvb_filter_pes2ts_cb, (void *) dvbdmx->pesfilter[1]); ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Record, 2, VideoPES, 0); break; case RP_AV: dvb_filter_pes2ts_init(&av7110->p2t[0], dvbdmx->pesfilter[0]->pid, dvb_filter_pes2ts_cb, (void *) dvbdmx->pesfilter[0]); dvb_filter_pes2ts_init(&av7110->p2t[1], dvbdmx->pesfilter[1]->pid, dvb_filter_pes2ts_cb, (void *) dvbdmx->pesfilter[1]); ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Record, 2, AV_PES, 0); break; } return ret; } int av7110_av_start_play(struct av7110 *av7110, int av) { int ret = 0; dprintk(2, "av7110:%p, \n", av7110); if (av7110->rec_mode) return -EBUSY; if (av7110->playing & av) return -EBUSY; av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Stop, 0); if (av7110->playing == RP_NONE) { av7110_ipack_reset(&av7110->ipack[0]); av7110_ipack_reset(&av7110->ipack[1]); } av7110->playing |= av; switch (av7110->playing) { case RP_AUDIO: ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Play, 2, AudioPES, 0); break; case RP_VIDEO: ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Play, 2, VideoPES, 0); av7110->sinfo = 0; break; case RP_AV: av7110->sinfo = 0; ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Play, 2, AV_PES, 0); break; } return ret; } int av7110_av_stop(struct av7110 *av7110, int av) { int ret = 0; dprintk(2, "av7110:%p, \n", av7110); if (!(av7110->playing & av) && !(av7110->rec_mode & av)) return 0; av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Stop, 0); if (av7110->playing) { av7110->playing &= ~av; switch (av7110->playing) { case RP_AUDIO: ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Play, 2, AudioPES, 0); break; case RP_VIDEO: ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Play, 2, VideoPES, 0); break; case RP_NONE: ret = av7110_set_vidmode(av7110, av7110->vidmode); break; } } else { av7110->rec_mode &= ~av; switch (av7110->rec_mode) { case RP_AUDIO: ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Record, 2, AudioPES, 0); break; case RP_VIDEO: ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Record, 2, VideoPES, 0); break; case RP_NONE: break; } } return ret; } int av7110_pes_play(void *dest, struct dvb_ringbuffer *buf, int dlen) { int len; u32 sync; u16 blen; if (!dlen) { wake_up(&buf->queue); return -1; } while (1) { len = dvb_ringbuffer_avail(buf); if (len < 6) { wake_up(&buf->queue); return -1; } sync = DVB_RINGBUFFER_PEEK(buf, 0) << 24; sync |= DVB_RINGBUFFER_PEEK(buf, 1) << 16; sync |= DVB_RINGBUFFER_PEEK(buf, 2) << 8; sync |= DVB_RINGBUFFER_PEEK(buf, 3); if (((sync &~ 0x0f) == 0x000001e0) || ((sync &~ 0x1f) == 0x000001c0) || (sync == 0x000001bd)) break; printk("resync\n"); DVB_RINGBUFFER_SKIP(buf, 1); } blen = DVB_RINGBUFFER_PEEK(buf, 4) << 8; blen |= DVB_RINGBUFFER_PEEK(buf, 5); blen += 6; if (len < blen || blen > dlen) { //printk("buffer empty - avail %d blen %u dlen %d\n", len, blen, dlen); wake_up(&buf->queue); return -1; } dvb_ringbuffer_read(buf, dest, (size_t) blen); dprintk(2, "pread=0x%08lx, pwrite=0x%08lx\n", (unsigned long) buf->pread, (unsigned long) buf->pwrite); wake_up(&buf->queue); return blen; } int av7110_set_volume(struct av7110 *av7110, unsigned int volleft, unsigned int volright) { unsigned int vol, val, balance = 0; int err; dprintk(2, "av7110:%p, \n", av7110); av7110->mixer.volume_left = volleft; av7110->mixer.volume_right = volright; switch (av7110->adac_type) { case DVB_ADAC_TI: volleft = (volleft * 256) / 1036; volright = (volright * 256) / 1036; if (volleft > 0x3f) volleft = 0x3f; if (volright > 0x3f) volright = 0x3f; if ((err = SendDAC(av7110, 3, 0x80 + volleft))) return err; return SendDAC(av7110, 4, volright); case DVB_ADAC_CRYSTAL: volleft = 127 - volleft / 2; volright = 127 - volright / 2; i2c_writereg(av7110, 0x20, 0x03, volleft); i2c_writereg(av7110, 0x20, 0x04, volright); return 0; case DVB_ADAC_MSP34x0: vol = (volleft > volright) ? volleft : volright; val = (vol * 0x73 / 255) << 8; if (vol > 0) balance = ((volright - volleft) * 127) / vol; msp_writereg(av7110, MSP_WR_DSP, 0x0001, balance << 8); msp_writereg(av7110, MSP_WR_DSP, 0x0000, val); /* loudspeaker */ msp_writereg(av7110, MSP_WR_DSP, 0x0006, val); /* headphonesr */ return 0; case DVB_ADAC_MSP34x5: vol = (volleft > volright) ? volleft : volright; val = (vol * 0x73 / 255) << 8; if (vol > 0) balance = ((volright - volleft) * 127) / vol; msp_writereg(av7110, MSP_WR_DSP, 0x0001, balance << 8); msp_writereg(av7110, MSP_WR_DSP, 0x0000, val); /* loudspeaker */ return 0; } return 0; } int av7110_set_vidmode(struct av7110 *av7110, enum av7110_video_mode mode) { int ret; dprintk(2, "av7110:%p, \n", av7110); ret = av7110_fw_cmd(av7110, COMTYPE_ENCODER, LoadVidCode, 1, mode); if (!ret && !av7110->playing) { ret = ChangePIDs(av7110, av7110->pids[DMX_PES_VIDEO], av7110->pids[DMX_PES_AUDIO], av7110->pids[DMX_PES_TELETEXT], 0, av7110->pids[DMX_PES_PCR]); if (!ret) ret = av7110_fw_cmd(av7110, COMTYPE_PIDFILTER, Scan, 0); } return ret; } static enum av7110_video_mode sw2mode[16] = { AV7110_VIDEO_MODE_PAL, AV7110_VIDEO_MODE_NTSC, AV7110_VIDEO_MODE_NTSC, AV7110_VIDEO_MODE_PAL, AV7110_VIDEO_MODE_NTSC, AV7110_VIDEO_MODE_NTSC, AV7110_VIDEO_MODE_PAL, AV7110_VIDEO_MODE_NTSC, AV7110_VIDEO_MODE_PAL, AV7110_VIDEO_MODE_PAL, AV7110_VIDEO_MODE_PAL, AV7110_VIDEO_MODE_PAL, AV7110_VIDEO_MODE_PAL, AV7110_VIDEO_MODE_PAL, AV7110_VIDEO_MODE_PAL, AV7110_VIDEO_MODE_PAL, }; static int get_video_format(struct av7110 *av7110, u8 *buf, int count) { int i; int hsize, vsize; int sw; u8 *p; int ret = 0; dprintk(2, "av7110:%p, \n", av7110); if (av7110->sinfo) return 0; for (i = 7; i < count - 10; i++) { p = buf + i; if (p[0] || p[1] || p[2] != 0x01 || p[3] != 0xb3) continue; p += 4; hsize = ((p[1] &0xF0) >> 4) | (p[0] << 4); vsize = ((p[1] &0x0F) << 8) | (p[2]); sw = (p[3] & 0x0F); ret = av7110_set_vidmode(av7110, sw2mode[sw]); if (!ret) { dprintk(2, "playback %dx%d fr=%d\n", hsize, vsize, sw); av7110->sinfo = 1; } break; } return ret; } /**************************************************************************** * I/O buffer management and control ****************************************************************************/ static inline long aux_ring_buffer_write(struct dvb_ringbuffer *rbuf, const u8 *buf, unsigned long count) { unsigned long todo = count; int free; while (todo > 0) { if (dvb_ringbuffer_free(rbuf) < 2048) { if (wait_event_interruptible(rbuf->queue, (dvb_ringbuffer_free(rbuf) >= 2048))) return count - todo; } free = dvb_ringbuffer_free(rbuf); if (free > todo) free = todo; dvb_ringbuffer_write(rbuf, buf, free); todo -= free; buf += free; } return count - todo; } static void play_video_cb(u8 *buf, int count, void *priv) { struct av7110 *av7110 = (struct av7110 *) priv; dprintk(2, "av7110:%p, \n", av7110); if ((buf[3] & 0xe0) == 0xe0) { get_video_format(av7110, buf, count); aux_ring_buffer_write(&av7110->avout, buf, count); } else aux_ring_buffer_write(&av7110->aout, buf, count); } static void play_audio_cb(u8 *buf, int count, void *priv) { struct av7110 *av7110 = (struct av7110 *) priv; dprintk(2, "av7110:%p, \n", av7110); aux_ring_buffer_write(&av7110->aout, buf, count); } #define FREE_COND_TS (dvb_ringbuffer_free(rb) >= 4096) static ssize_t ts_play(struct av7110 *av7110, const char __user *buf, unsigned long count, int nonblock, int type) { struct dvb_ringbuffer *rb; u8 *kb; unsigned long todo = count; dprintk(2, "%s: type %d cnt %lu\n", __func__, type, count); rb = (type) ? &av7110->avout : &av7110->aout; kb = av7110->kbuf[type]; if (!kb) return -ENOBUFS; if (nonblock && !FREE_COND_TS) return -EWOULDBLOCK; while (todo >= TS_SIZE) { if (!FREE_COND_TS) { if (nonblock) return count - todo; if (wait_event_interruptible(rb->queue, FREE_COND_TS)) return count - todo; } if (copy_from_user(kb, buf, TS_SIZE)) return -EFAULT; write_ts_to_decoder(av7110, type, kb, TS_SIZE); todo -= TS_SIZE; buf += TS_SIZE; } return count - todo; } #define FREE_COND (dvb_ringbuffer_free(&av7110->avout) >= 20 * 1024 && \ dvb_ringbuffer_free(&av7110->aout) >= 20 * 1024) static ssize_t dvb_play(struct av7110 *av7110, const char __user *buf, unsigned long count, int nonblock, int type) { unsigned long todo = count, n; dprintk(2, "av7110:%p, \n", av7110); if (!av7110->kbuf[type]) return -ENOBUFS; if (nonblock && !FREE_COND) return -EWOULDBLOCK; while (todo > 0) { if (!FREE_COND) { if (nonblock) return count - todo; if (wait_event_interruptible(av7110->avout.queue, FREE_COND)) return count - todo; } n = todo; if (n > IPACKS * 2) n = IPACKS * 2; if (copy_from_user(av7110->kbuf[type], buf, n)) return -EFAULT; av7110_ipack_instant_repack(av7110->kbuf[type], n, &av7110->ipack[type]); todo -= n; buf += n; } return count - todo; } static ssize_t dvb_play_kernel(struct av7110 *av7110, const u8 *buf, unsigned long count, int nonblock, int type) { unsigned long todo = count, n; dprintk(2, "av7110:%p, \n", av7110); if (!av7110->kbuf[type]) return -ENOBUFS; if (nonblock && !FREE_COND) return -EWOULDBLOCK; while (todo > 0) { if (!FREE_COND) { if (nonblock) return count - todo; if (wait_event_interruptible(av7110->avout.queue, FREE_COND)) return count - todo; } n = todo; if (n > IPACKS * 2) n = IPACKS * 2; av7110_ipack_instant_repack(buf, n, &av7110->ipack[type]); todo -= n; buf += n; } return count - todo; } static ssize_t dvb_aplay(struct av7110 *av7110, const char __user *buf, unsigned long count, int nonblock, int type) { unsigned long todo = count, n; dprintk(2, "av7110:%p, \n", av7110); if (!av7110->kbuf[type]) return -ENOBUFS; if (nonblock && dvb_ringbuffer_free(&av7110->aout) < 20 * 1024) return -EWOULDBLOCK; while (todo > 0) { if (dvb_ringbuffer_free(&av7110->aout) < 20 * 1024) { if (nonblock) return count - todo; if (wait_event_interruptible(av7110->aout.queue, (dvb_ringbuffer_free(&av7110->aout) >= 20 * 1024))) return count-todo; } n = todo; if (n > IPACKS * 2) n = IPACKS * 2; if (copy_from_user(av7110->kbuf[type], buf, n)) return -EFAULT; av7110_ipack_instant_repack(av7110->kbuf[type], n, &av7110->ipack[type]); todo -= n; buf += n; } return count - todo; } void av7110_p2t_init(struct av7110_p2t *p, struct dvb_demux_feed *feed) { memset(p->pes, 0, TS_SIZE); p->counter = 0; p->pos = 0; p->frags = 0; if (feed) p->feed = feed; } static void clear_p2t(struct av7110_p2t *p) { memset(p->pes, 0, TS_SIZE); // p->counter = 0; p->pos = 0; p->frags = 0; } static int find_pes_header(u8 const *buf, long int length, int *frags) { int c = 0; int found = 0; *frags = 0; while (c < length - 3 && !found) { if (buf[c] == 0x00 && buf[c + 1] == 0x00 && buf[c + 2] == 0x01) { switch ( buf[c + 3] ) { case PROG_STREAM_MAP: case PRIVATE_STREAM2: case PROG_STREAM_DIR: case ECM_STREAM : case EMM_STREAM : case PADDING_STREAM : case DSM_CC_STREAM : case ISO13522_STREAM: case PRIVATE_STREAM1: case AUDIO_STREAM_S ... AUDIO_STREAM_E: case VIDEO_STREAM_S ... VIDEO_STREAM_E: found = 1; break; default: c++; break; } } else c++; } if (c == length - 3 && !found) { if (buf[length - 1] == 0x00) *frags = 1; if (buf[length - 2] == 0x00 && buf[length - 1] == 0x00) *frags = 2; if (buf[length - 3] == 0x00 && buf[length - 2] == 0x00 && buf[length - 1] == 0x01) *frags = 3; return -1; } return c; } void av7110_p2t_write(u8 const *buf, long int length, u16 pid, struct av7110_p2t *p) { int c, c2, l, add; int check, rest; c = 0; c2 = 0; if (p->frags){ check = 0; switch(p->frags) { case 1: if (buf[c] == 0x00 && buf[c + 1] == 0x01) { check = 1; c += 2; } break; case 2: if (buf[c] == 0x01) { check = 1; c++; } break; case 3: check = 1; } if (check) { switch (buf[c]) { case PROG_STREAM_MAP: case PRIVATE_STREAM2: case PROG_STREAM_DIR: case ECM_STREAM : case EMM_STREAM : case PADDING_STREAM : case DSM_CC_STREAM : case ISO13522_STREAM: case PRIVATE_STREAM1: case AUDIO_STREAM_S ... AUDIO_STREAM_E: case VIDEO_STREAM_S ... VIDEO_STREAM_E: p->pes[0] = 0x00; p->pes[1] = 0x00; p->pes[2] = 0x01; p->pes[3] = buf[c]; p->pos = 4; memcpy(p->pes + p->pos, buf + c, (TS_SIZE - 4) - p->pos); c += (TS_SIZE - 4) - p->pos; p_to_t(p->pes, (TS_SIZE - 4), pid, &p->counter, p->feed); clear_p2t(p); break; default: c = 0; break; } } p->frags = 0; } if (p->pos) { c2 = find_pes_header(buf + c, length - c, &p->frags); if (c2 >= 0 && c2 < (TS_SIZE - 4) - p->pos) l = c2+c; else l = (TS_SIZE - 4) - p->pos; memcpy(p->pes + p->pos, buf, l); c += l; p->pos += l; p_to_t(p->pes, p->pos, pid, &p->counter, p->feed); clear_p2t(p); } add = 0; while (c < length) { c2 = find_pes_header(buf + c + add, length - c - add, &p->frags); if (c2 >= 0) { c2 += c + add; if (c2 > c){ p_to_t(buf + c, c2 - c, pid, &p->counter, p->feed); c = c2; clear_p2t(p); add = 0; } else add = 1; } else { l = length - c; rest = l % (TS_SIZE - 4); l -= rest; p_to_t(buf + c, l, pid, &p->counter, p->feed); memcpy(p->pes, buf + c + l, rest); p->pos = rest; c = length; } } } static int write_ts_header2(u16 pid, u8 *counter, int pes_start, u8 *buf, u8 length) { int i; int c = 0; int fill; u8 tshead[4] = { 0x47, 0x00, 0x00, 0x10 }; fill = (TS_SIZE - 4) - length; if (pes_start) tshead[1] = 0x40; if (fill) tshead[3] = 0x30; tshead[1] |= (u8)((pid & 0x1F00) >> 8); tshead[2] |= (u8)(pid & 0x00FF); tshead[3] |= ((*counter)++ & 0x0F); memcpy(buf, tshead, 4); c += 4; if (fill) { buf[4] = fill - 1; c++; if (fill > 1) { buf[5] = 0x00; c++; } for (i = 6; i < fill + 4; i++) { buf[i] = 0xFF; c++; } } return c; } static void p_to_t(u8 const *buf, long int length, u16 pid, u8 *counter, struct dvb_demux_feed *feed) { int l, pes_start; u8 obuf[TS_SIZE]; long c = 0; pes_start = 0; if (length > 3 && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01) switch (buf[3]) { case PROG_STREAM_MAP: case PRIVATE_STREAM2: case PROG_STREAM_DIR: case ECM_STREAM : case EMM_STREAM : case PADDING_STREAM : case DSM_CC_STREAM : case ISO13522_STREAM: case PRIVATE_STREAM1: case AUDIO_STREAM_S ... AUDIO_STREAM_E: case VIDEO_STREAM_S ... VIDEO_STREAM_E: pes_start = 1; break; default: break; } while (c < length) { memset(obuf, 0, TS_SIZE); if (length - c >= (TS_SIZE - 4)){ l = write_ts_header2(pid, counter, pes_start, obuf, (TS_SIZE - 4)); memcpy(obuf + l, buf + c, TS_SIZE - l); c += TS_SIZE - l; } else { l = write_ts_header2(pid, counter, pes_start, obuf, length - c); memcpy(obuf + l, buf + c, TS_SIZE - l); c = length; } feed->cb.ts(obuf, 188, NULL, 0, &feed->feed.ts, NULL); pes_start = 0; } } static int write_ts_to_decoder(struct av7110 *av7110, int type, const u8 *buf, size_t len) { struct ipack *ipack = &av7110->ipack[type]; if (buf[1] & TRANS_ERROR) { av7110_ipack_reset(ipack); return -1; } if (!(buf[3] & PAYLOAD)) return -1; if (buf[1] & PAY_START) av7110_ipack_flush(ipack); if (buf[3] & ADAPT_FIELD) { len -= buf[4] + 1; buf += buf[4] + 1; if (!len) return 0; } av7110_ipack_instant_repack(buf + 4, len - 4, ipack); return 0; } int av7110_write_to_decoder(struct dvb_demux_feed *feed, const u8 *buf, size_t len) { struct dvb_demux *demux = feed->demux; struct av7110 *av7110 = (struct av7110 *) demux->priv; dprintk(2, "av7110:%p, \n", av7110); if (av7110->full_ts && demux->dmx.frontend->source != DMX_MEMORY_FE) return 0; switch (feed->pes_type) { case 0: if (av7110->audiostate.stream_source == AUDIO_SOURCE_MEMORY) return -EINVAL; break; case 1: if (av7110->videostate.stream_source == VIDEO_SOURCE_MEMORY) return -EINVAL; break; default: return -1; } return write_ts_to_decoder(av7110, feed->pes_type, buf, len); } /****************************************************************************** * Video MPEG decoder events ******************************************************************************/ void dvb_video_add_event(struct av7110 *av7110, struct video_event *event) { struct dvb_video_events *events = &av7110->video_events; int wp; spin_lock_bh(&events->lock); wp = (events->eventw + 1) % MAX_VIDEO_EVENT; if (wp == events->eventr) { events->overflow = 1; events->eventr = (events->eventr + 1) % MAX_VIDEO_EVENT; } //FIXME: timestamp? memcpy(&events->events[events->eventw], event, sizeof(struct video_event)); events->eventw = wp; spin_unlock_bh(&events->lock); wake_up_interruptible(&events->wait_queue); } static int dvb_video_get_event (struct av7110 *av7110, struct video_event *event, int flags) { struct dvb_video_events *events = &av7110->video_events; if (events->overflow) { events->overflow = 0; return -EOVERFLOW; } if (events->eventw == events->eventr) { int ret; if (flags & O_NONBLOCK) return -EWOULDBLOCK; ret = wait_event_interruptible(events->wait_queue, events->eventw != events->eventr); if (ret < 0) return ret; } spin_lock_bh(&events->lock); memcpy(event, &events->events[events->eventr], sizeof(struct video_event)); events->eventr = (events->eventr + 1) % MAX_VIDEO_EVENT; spin_unlock_bh(&events->lock); return 0; } /****************************************************************************** * DVB device file operations ******************************************************************************/ static __poll_t dvb_video_poll(struct file *file, poll_table *wait) { struct dvb_device *dvbdev = file->private_data; struct av7110 *av7110 = dvbdev->priv; __poll_t mask = 0; dprintk(2, "av7110:%p, \n", av7110); if ((file->f_flags & O_ACCMODE) != O_RDONLY) poll_wait(file, &av7110->avout.queue, wait); poll_wait(file, &av7110->video_events.wait_queue, wait); if (av7110->video_events.eventw != av7110->video_events.eventr) mask = EPOLLPRI; if ((file->f_flags & O_ACCMODE) != O_RDONLY) { if (av7110->playing) { if (FREE_COND) mask |= (EPOLLOUT | EPOLLWRNORM); } else { /* if not playing: may play if asked for */ mask |= (EPOLLOUT | EPOLLWRNORM); } } return mask; } static ssize_t dvb_video_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct dvb_device *dvbdev = file->private_data; struct av7110 *av7110 = dvbdev->priv; unsigned char c; dprintk(2, "av7110:%p, \n", av7110); if ((file->f_flags & O_ACCMODE) == O_RDONLY) return -EPERM; if (av7110->videostate.stream_source != VIDEO_SOURCE_MEMORY) return -EPERM; if (get_user(c, buf)) return -EFAULT; if (c == 0x47 && count % TS_SIZE == 0) return ts_play(av7110, buf, count, file->f_flags & O_NONBLOCK, 1); else return dvb_play(av7110, buf, count, file->f_flags & O_NONBLOCK, 1); } static __poll_t dvb_audio_poll(struct file *file, poll_table *wait) { struct dvb_device *dvbdev = file->private_data; struct av7110 *av7110 = dvbdev->priv; __poll_t mask = 0; dprintk(2, "av7110:%p, \n", av7110); poll_wait(file, &av7110->aout.queue, wait); if (av7110->playing) { if (dvb_ringbuffer_free(&av7110->aout) >= 20 * 1024) mask |= (EPOLLOUT | EPOLLWRNORM); } else /* if not playing: may play if asked for */ mask = (EPOLLOUT | EPOLLWRNORM); return mask; } static ssize_t dvb_audio_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct dvb_device *dvbdev = file->private_data; struct av7110 *av7110 = dvbdev->priv; unsigned char c; dprintk(2, "av7110:%p, \n", av7110); if (av7110->audiostate.stream_source != AUDIO_SOURCE_MEMORY) { printk(KERN_ERR "not audio source memory\n"); return -EPERM; } if (get_user(c, buf)) return -EFAULT; if (c == 0x47 && count % TS_SIZE == 0) return ts_play(av7110, buf, count, file->f_flags & O_NONBLOCK, 0); else return dvb_aplay(av7110, buf, count, file->f_flags & O_NONBLOCK, 0); } static u8 iframe_header[] = { 0x00, 0x00, 0x01, 0xe0, 0x00, 0x00, 0x80, 0x00, 0x00 }; #define MIN_IFRAME 400000 static int play_iframe(struct av7110 *av7110, char __user *buf, unsigned int len, int nonblock) { unsigned i, n; int progressive = 0; int match = 0; dprintk(2, "av7110:%p, \n", av7110); if (len == 0) return 0; if (!(av7110->playing & RP_VIDEO)) { if (av7110_av_start_play(av7110, RP_VIDEO) < 0) return -EBUSY; } /* search in buf for instances of 00 00 01 b5 1? */ for (i = 0; i < len; i++) { unsigned char c; if (get_user(c, buf + i)) return -EFAULT; if (match == 5) { progressive = c & 0x08; match = 0; } if (c == 0x00) { match = (match == 1 || match == 2) ? 2 : 1; continue; } switch (match++) { case 2: if (c == 0x01) continue; break; case 3: if (c == 0xb5) continue; break; case 4: if ((c & 0xf0) == 0x10) continue; break; } match = 0; } /* setting n always > 1, fixes problems when playing stillframes consisting of I- and P-Frames */ n = MIN_IFRAME / len + 1; /* FIXME: nonblock? */ dvb_play_kernel(av7110, iframe_header, sizeof(iframe_header), 0, 1); for (i = 0; i < n; i++) dvb_play(av7110, buf, len, 0, 1); av7110_ipack_flush(&av7110->ipack[1]); if (progressive) return vidcom(av7110, AV_VIDEO_CMD_FREEZE, 1); else return 0; } #ifdef CONFIG_COMPAT struct compat_video_still_picture { compat_uptr_t iFrame; int32_t size; }; #define VIDEO_STILLPICTURE32 _IOW('o', 30, struct compat_video_still_picture) struct compat_video_event { __s32 type; /* unused, make sure to use atomic time for y2038 if it ever gets used */ compat_long_t timestamp; union { video_size_t size; unsigned int frame_rate; /* in frames per 1000sec */ unsigned char vsync_field; /* unknown/odd/even/progressive */ } u; }; #define VIDEO_GET_EVENT32 _IOR('o', 28, struct compat_video_event) static int dvb_compat_video_get_event(struct av7110 *av7110, struct compat_video_event *event, int flags) { struct video_event ev; int ret; ret = dvb_video_get_event(av7110, &ev, flags); *event = (struct compat_video_event) { .type = ev.type, .timestamp = ev.timestamp, .u.size = ev.u.size, }; return ret; } #endif static int dvb_video_ioctl(struct file *file, unsigned int cmd, void *parg) { struct dvb_device *dvbdev = file->private_data; struct av7110 *av7110 = dvbdev->priv; unsigned long arg = (unsigned long) parg; int ret = 0; dprintk(1, "av7110:%p, cmd=%04x\n", av7110,cmd); if ((file->f_flags & O_ACCMODE) == O_RDONLY) { if ( cmd != VIDEO_GET_STATUS && cmd != VIDEO_GET_EVENT && cmd != VIDEO_GET_SIZE ) { return -EPERM; } } if (mutex_lock_interruptible(&av7110->ioctl_mutex)) return -ERESTARTSYS; switch (cmd) { case VIDEO_STOP: av7110->videostate.play_state = VIDEO_STOPPED; if (av7110->videostate.stream_source == VIDEO_SOURCE_MEMORY) ret = av7110_av_stop(av7110, RP_VIDEO); else ret = vidcom(av7110, AV_VIDEO_CMD_STOP, av7110->videostate.video_blank ? 0 : 1); if (!ret) av7110->trickmode = TRICK_NONE; break; case VIDEO_PLAY: av7110->trickmode = TRICK_NONE; if (av7110->videostate.play_state == VIDEO_FREEZED) { av7110->videostate.play_state = VIDEO_PLAYING; ret = vidcom(av7110, AV_VIDEO_CMD_PLAY, 0); if (ret) break; } if (av7110->videostate.stream_source == VIDEO_SOURCE_MEMORY) { if (av7110->playing == RP_AV) { ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Stop, 0); if (ret) break; av7110->playing &= ~RP_VIDEO; } ret = av7110_av_start_play(av7110, RP_VIDEO); } if (!ret) ret = vidcom(av7110, AV_VIDEO_CMD_PLAY, 0); if (!ret) av7110->videostate.play_state = VIDEO_PLAYING; break; case VIDEO_FREEZE: av7110->videostate.play_state = VIDEO_FREEZED; if (av7110->playing & RP_VIDEO) ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Pause, 0); else ret = vidcom(av7110, AV_VIDEO_CMD_FREEZE, 1); if (!ret) av7110->trickmode = TRICK_FREEZE; break; case VIDEO_CONTINUE: if (av7110->playing & RP_VIDEO) ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Continue, 0); if (!ret) ret = vidcom(av7110, AV_VIDEO_CMD_PLAY, 0); if (!ret) { av7110->videostate.play_state = VIDEO_PLAYING; av7110->trickmode = TRICK_NONE; } break; case VIDEO_SELECT_SOURCE: av7110->videostate.stream_source = (video_stream_source_t) arg; break; case VIDEO_SET_BLANK: av7110->videostate.video_blank = (int) arg; break; case VIDEO_GET_STATUS: memcpy(parg, &av7110->videostate, sizeof(struct video_status)); break; #ifdef CONFIG_COMPAT case VIDEO_GET_EVENT32: ret = dvb_compat_video_get_event(av7110, parg, file->f_flags); break; #endif case VIDEO_GET_EVENT: ret = dvb_video_get_event(av7110, parg, file->f_flags); break; case VIDEO_GET_SIZE: memcpy(parg, &av7110->video_size, sizeof(video_size_t)); break; case VIDEO_SET_DISPLAY_FORMAT: { video_displayformat_t format = (video_displayformat_t) arg; switch (format) { case VIDEO_PAN_SCAN: av7110->display_panscan = VID_PAN_SCAN_PREF; break; case VIDEO_LETTER_BOX: av7110->display_panscan = VID_VC_AND_PS_PREF; break; case VIDEO_CENTER_CUT_OUT: av7110->display_panscan = VID_CENTRE_CUT_PREF; break; default: ret = -EINVAL; } if (ret < 0) break; av7110->videostate.display_format = format; ret = av7110_fw_cmd(av7110, COMTYPE_ENCODER, SetPanScanType, 1, av7110->display_panscan); break; } case VIDEO_SET_FORMAT: if (arg > 1) { ret = -EINVAL; break; } av7110->display_ar = arg; ret = av7110_fw_cmd(av7110, COMTYPE_ENCODER, SetMonitorType, 1, (u16) arg); break; #ifdef CONFIG_COMPAT case VIDEO_STILLPICTURE32: { struct compat_video_still_picture *pic = (struct compat_video_still_picture *) parg; av7110->videostate.stream_source = VIDEO_SOURCE_MEMORY; dvb_ringbuffer_flush_spinlock_wakeup(&av7110->avout); ret = play_iframe(av7110, compat_ptr(pic->iFrame), pic->size, file->f_flags & O_NONBLOCK); break; } #endif case VIDEO_STILLPICTURE: { struct video_still_picture *pic = (struct video_still_picture *) parg; av7110->videostate.stream_source = VIDEO_SOURCE_MEMORY; dvb_ringbuffer_flush_spinlock_wakeup(&av7110->avout); ret = play_iframe(av7110, pic->iFrame, pic->size, file->f_flags & O_NONBLOCK); break; } case VIDEO_FAST_FORWARD: //note: arg is ignored by firmware if (av7110->playing & RP_VIDEO) ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Scan_I, 2, AV_PES, 0); else ret = vidcom(av7110, AV_VIDEO_CMD_FFWD, arg); if (!ret) { av7110->trickmode = TRICK_FAST; av7110->videostate.play_state = VIDEO_PLAYING; } break; case VIDEO_SLOWMOTION: if (av7110->playing&RP_VIDEO) { if (av7110->trickmode != TRICK_SLOW) ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Slow, 2, 0, 0); if (!ret) ret = vidcom(av7110, AV_VIDEO_CMD_SLOW, arg); } else { ret = vidcom(av7110, AV_VIDEO_CMD_PLAY, 0); if (!ret) ret = vidcom(av7110, AV_VIDEO_CMD_STOP, 0); if (!ret) ret = vidcom(av7110, AV_VIDEO_CMD_SLOW, arg); } if (!ret) { av7110->trickmode = TRICK_SLOW; av7110->videostate.play_state = VIDEO_PLAYING; } break; case VIDEO_GET_CAPABILITIES: *(int *)parg = VIDEO_CAP_MPEG1 | VIDEO_CAP_MPEG2 | VIDEO_CAP_SYS | VIDEO_CAP_PROG; break; case VIDEO_CLEAR_BUFFER: dvb_ringbuffer_flush_spinlock_wakeup(&av7110->avout); av7110_ipack_reset(&av7110->ipack[1]); if (av7110->playing == RP_AV) { ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Play, 2, AV_PES, 0); if (ret) break; if (av7110->trickmode == TRICK_FAST) ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Scan_I, 2, AV_PES, 0); if (av7110->trickmode == TRICK_SLOW) { ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Slow, 2, 0, 0); if (!ret) ret = vidcom(av7110, AV_VIDEO_CMD_SLOW, arg); } if (av7110->trickmode == TRICK_FREEZE) ret = vidcom(av7110, AV_VIDEO_CMD_STOP, 1); } break; case VIDEO_SET_STREAMTYPE: break; default: ret = -ENOIOCTLCMD; break; } mutex_unlock(&av7110->ioctl_mutex); return ret; } static int dvb_audio_ioctl(struct file *file, unsigned int cmd, void *parg) { struct dvb_device *dvbdev = file->private_data; struct av7110 *av7110 = dvbdev->priv; unsigned long arg = (unsigned long) parg; int ret = 0; dprintk(1, "av7110:%p, cmd=%04x\n", av7110,cmd); if (((file->f_flags & O_ACCMODE) == O_RDONLY) && (cmd != AUDIO_GET_STATUS)) return -EPERM; if (mutex_lock_interruptible(&av7110->ioctl_mutex)) return -ERESTARTSYS; switch (cmd) { case AUDIO_STOP: if (av7110->audiostate.stream_source == AUDIO_SOURCE_MEMORY) ret = av7110_av_stop(av7110, RP_AUDIO); else ret = audcom(av7110, AUDIO_CMD_MUTE); if (!ret) av7110->audiostate.play_state = AUDIO_STOPPED; break; case AUDIO_PLAY: if (av7110->audiostate.stream_source == AUDIO_SOURCE_MEMORY) ret = av7110_av_start_play(av7110, RP_AUDIO); if (!ret) ret = audcom(av7110, AUDIO_CMD_UNMUTE); if (!ret) av7110->audiostate.play_state = AUDIO_PLAYING; break; case AUDIO_PAUSE: ret = audcom(av7110, AUDIO_CMD_MUTE); if (!ret) av7110->audiostate.play_state = AUDIO_PAUSED; break; case AUDIO_CONTINUE: if (av7110->audiostate.play_state == AUDIO_PAUSED) { av7110->audiostate.play_state = AUDIO_PLAYING; ret = audcom(av7110, AUDIO_CMD_UNMUTE | AUDIO_CMD_PCM16); } break; case AUDIO_SELECT_SOURCE: av7110->audiostate.stream_source = (audio_stream_source_t) arg; break; case AUDIO_SET_MUTE: { ret = audcom(av7110, arg ? AUDIO_CMD_MUTE : AUDIO_CMD_UNMUTE); if (!ret) av7110->audiostate.mute_state = (int) arg; break; } case AUDIO_SET_AV_SYNC: av7110->audiostate.AV_sync_state = (int) arg; ret = audcom(av7110, arg ? AUDIO_CMD_SYNC_ON : AUDIO_CMD_SYNC_OFF); break; case AUDIO_SET_BYPASS_MODE: if (FW_VERSION(av7110->arm_app) < 0x2621) ret = -EINVAL; av7110->audiostate.bypass_mode = (int)arg; break; case AUDIO_CHANNEL_SELECT: av7110->audiostate.channel_select = (audio_channel_select_t) arg; switch(av7110->audiostate.channel_select) { case AUDIO_STEREO: ret = audcom(av7110, AUDIO_CMD_STEREO); if (!ret) { if (av7110->adac_type == DVB_ADAC_CRYSTAL) i2c_writereg(av7110, 0x20, 0x02, 0x49); else if (av7110->adac_type == DVB_ADAC_MSP34x5) msp_writereg(av7110, MSP_WR_DSP, 0x0008, 0x0220); } break; case AUDIO_MONO_LEFT: ret = audcom(av7110, AUDIO_CMD_MONO_L); if (!ret) { if (av7110->adac_type == DVB_ADAC_CRYSTAL) i2c_writereg(av7110, 0x20, 0x02, 0x4a); else if (av7110->adac_type == DVB_ADAC_MSP34x5) msp_writereg(av7110, MSP_WR_DSP, 0x0008, 0x0200); } break; case AUDIO_MONO_RIGHT: ret = audcom(av7110, AUDIO_CMD_MONO_R); if (!ret) { if (av7110->adac_type == DVB_ADAC_CRYSTAL) i2c_writereg(av7110, 0x20, 0x02, 0x45); else if (av7110->adac_type == DVB_ADAC_MSP34x5) msp_writereg(av7110, MSP_WR_DSP, 0x0008, 0x0210); } break; default: ret = -EINVAL; break; } break; case AUDIO_GET_STATUS: memcpy(parg, &av7110->audiostate, sizeof(struct audio_status)); break; case AUDIO_GET_CAPABILITIES: if (FW_VERSION(av7110->arm_app) < 0x2621) *(unsigned int *)parg = AUDIO_CAP_LPCM | AUDIO_CAP_MP1 | AUDIO_CAP_MP2; else *(unsigned int *)parg = AUDIO_CAP_LPCM | AUDIO_CAP_DTS | AUDIO_CAP_AC3 | AUDIO_CAP_MP1 | AUDIO_CAP_MP2; break; case AUDIO_CLEAR_BUFFER: dvb_ringbuffer_flush_spinlock_wakeup(&av7110->aout); av7110_ipack_reset(&av7110->ipack[0]); if (av7110->playing == RP_AV) ret = av7110_fw_cmd(av7110, COMTYPE_REC_PLAY, __Play, 2, AV_PES, 0); break; case AUDIO_SET_ID: break; case AUDIO_SET_MIXER: { struct audio_mixer *amix = (struct audio_mixer *)parg; ret = av7110_set_volume(av7110, amix->volume_left, amix->volume_right); break; } case AUDIO_SET_STREAMTYPE: break; default: ret = -ENOIOCTLCMD; } mutex_unlock(&av7110->ioctl_mutex); return ret; } static int dvb_video_open(struct inode *inode, struct file *file) { struct dvb_device *dvbdev = file->private_data; struct av7110 *av7110 = dvbdev->priv; int err; dprintk(2, "av7110:%p, \n", av7110); if ((err = dvb_generic_open(inode, file)) < 0) return err; if ((file->f_flags & O_ACCMODE) != O_RDONLY) { dvb_ringbuffer_flush_spinlock_wakeup(&av7110->aout); dvb_ringbuffer_flush_spinlock_wakeup(&av7110->avout); av7110->video_blank = 1; av7110->audiostate.AV_sync_state = 1; av7110->videostate.stream_source = VIDEO_SOURCE_DEMUX; /* empty event queue */ av7110->video_events.eventr = av7110->video_events.eventw = 0; } return 0; } static int dvb_video_release(struct inode *inode, struct file *file) { struct dvb_device *dvbdev = file->private_data; struct av7110 *av7110 = dvbdev->priv; dprintk(2, "av7110:%p, \n", av7110); if ((file->f_flags & O_ACCMODE) != O_RDONLY) { av7110_av_stop(av7110, RP_VIDEO); } return dvb_generic_release(inode, file); } static int dvb_audio_open(struct inode *inode, struct file *file) { struct dvb_device *dvbdev = file->private_data; struct av7110 *av7110 = dvbdev->priv; int err = dvb_generic_open(inode, file); dprintk(2, "av7110:%p, \n", av7110); if (err < 0) return err; dvb_ringbuffer_flush_spinlock_wakeup(&av7110->aout); av7110->audiostate.stream_source = AUDIO_SOURCE_DEMUX; return 0; } static int dvb_audio_release(struct inode *inode, struct file *file) { struct dvb_device *dvbdev = file->private_data; struct av7110 *av7110 = dvbdev->priv; dprintk(2, "av7110:%p, \n", av7110); av7110_av_stop(av7110, RP_AUDIO); return dvb_generic_release(inode, file); } /****************************************************************************** * driver registration ******************************************************************************/ static const struct file_operations dvb_video_fops = { .owner = THIS_MODULE, .write = dvb_video_write, .unlocked_ioctl = dvb_generic_ioctl, .compat_ioctl = dvb_generic_ioctl, .open = dvb_video_open, .release = dvb_video_release, .poll = dvb_video_poll, .llseek = noop_llseek, }; static struct dvb_device dvbdev_video = { .priv = NULL, .users = 6, .readers = 5, /* arbitrary */ .writers = 1, .fops = &dvb_video_fops, .kernel_ioctl = dvb_video_ioctl, }; static const struct file_operations dvb_audio_fops = { .owner = THIS_MODULE, .write = dvb_audio_write, .unlocked_ioctl = dvb_generic_ioctl, .compat_ioctl = dvb_generic_ioctl, .open = dvb_audio_open, .release = dvb_audio_release, .poll = dvb_audio_poll, .llseek = noop_llseek, }; static struct dvb_device dvbdev_audio = { .priv = NULL, .users = 1, .writers = 1, .fops = &dvb_audio_fops, .kernel_ioctl = dvb_audio_ioctl, }; int av7110_av_register(struct av7110 *av7110) { av7110->audiostate.AV_sync_state = 0; av7110->audiostate.mute_state = 0; av7110->audiostate.play_state = AUDIO_STOPPED; av7110->audiostate.stream_source = AUDIO_SOURCE_DEMUX; av7110->audiostate.channel_select = AUDIO_STEREO; av7110->audiostate.bypass_mode = 0; av7110->videostate.video_blank = 0; av7110->videostate.play_state = VIDEO_STOPPED; av7110->videostate.stream_source = VIDEO_SOURCE_DEMUX; av7110->videostate.video_format = VIDEO_FORMAT_4_3; av7110->videostate.display_format = VIDEO_LETTER_BOX; av7110->display_ar = VIDEO_FORMAT_4_3; av7110->display_panscan = VID_VC_AND_PS_PREF; init_waitqueue_head(&av7110->video_events.wait_queue); spin_lock_init(&av7110->video_events.lock); av7110->video_events.eventw = av7110->video_events.eventr = 0; av7110->video_events.overflow = 0; memset(&av7110->video_size, 0, sizeof (video_size_t)); dvb_register_device(&av7110->dvb_adapter, &av7110->video_dev, &dvbdev_video, av7110, DVB_DEVICE_VIDEO, 0); dvb_register_device(&av7110->dvb_adapter, &av7110->audio_dev, &dvbdev_audio, av7110, DVB_DEVICE_AUDIO, 0); return 0; } void av7110_av_unregister(struct av7110 *av7110) { dvb_unregister_device(av7110->audio_dev); dvb_unregister_device(av7110->video_dev); } int av7110_av_init(struct av7110 *av7110) { void (*play[])(u8 *, int, void *) = { play_audio_cb, play_video_cb }; int i, ret; for (i = 0; i < 2; i++) { struct ipack *ipack = av7110->ipack + i; ret = av7110_ipack_init(ipack, IPACKS, play[i]); if (ret < 0) { if (i) av7110_ipack_free(--ipack); goto out; } ipack->data = av7110; } dvb_ringbuffer_init(&av7110->avout, av7110->iobuf, AVOUTLEN); dvb_ringbuffer_init(&av7110->aout, av7110->iobuf + AVOUTLEN, AOUTLEN); av7110->kbuf[0] = (u8 *)(av7110->iobuf + AVOUTLEN + AOUTLEN + BMPLEN); av7110->kbuf[1] = av7110->kbuf[0] + 2 * IPACKS; out: return ret; } void av7110_av_exit(struct av7110 *av7110) { av7110_ipack_free(&av7110->ipack[0]); av7110_ipack_free(&av7110->ipack[1]); }
rperier/linux
drivers/staging/media/av7110/av7110_av.c
C
gpl-2.0
41,132
#include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/gpio.h> #include <linux/spi/spi.h> #include <linux/delay.h> #include "fbtft.h" #define DRVNAME "fb_ssd1331" #define WIDTH 96 #define HEIGHT 64 #define GAMMA_NUM 1 #define GAMMA_LEN 63 #define DEFAULT_GAMMA "0 2 2 2 2 2 2 2 " \ "2 2 2 2 2 2 2 2 " \ "2 2 2 2 2 2 2 2 " \ "2 2 2 2 2 2 2 2 " \ "2 2 2 2 2 2 2 2 " \ "2 2 2 2 2 2 2 2 " \ "2 2 2 2 2 2 2 2 " \ "2 2 2 2 2 2 2" \ static int init_display(struct fbtft_par *par) { fbtft_par_dbg(DEBUG_INIT_DISPLAY, par, "%s()\n", __func__); par->fbtftops.reset(par); write_reg(par, 0xae); /* Display Off */ write_reg(par, 0xa0, 0x70 | (par->bgr << 2)); /* Set Colour Depth */ write_reg(par, 0x72); /* RGB colour */ write_reg(par, 0xa1, 0x00); /* Set Display Start Line */ write_reg(par, 0xa2, 0x00); /* Set Display Offset */ write_reg(par, 0xa4); /* NORMALDISPLAY */ write_reg(par, 0xa8, 0x3f); /* Set multiplex */ write_reg(par, 0xad, 0x8e); /* Set master */ /* write_reg(par, 0xb0, 0x0b); Set power mode */ write_reg(par, 0xb1, 0x31); /* Precharge */ write_reg(par, 0xb3, 0xf0); /* Clock div */ write_reg(par, 0x8a, 0x64); /* Precharge A */ write_reg(par, 0x8b, 0x78); /* Precharge B */ write_reg(par, 0x8c, 0x64); /* Precharge C */ write_reg(par, 0xbb, 0x3a); /* Precharge level */ write_reg(par, 0xbe, 0x3e); /* vcomh */ write_reg(par, 0x87, 0x06); /* Master current */ write_reg(par, 0x81, 0x91); /* Contrast A */ write_reg(par, 0x82, 0x50); /* Contrast B */ write_reg(par, 0x83, 0x7d); /* Contrast C */ write_reg(par, 0xaf); /* Set Sleep Mode Display On */ return 0; } static void set_addr_win(struct fbtft_par *par, int xs, int ys, int xe, int ye) { fbtft_par_dbg(DEBUG_SET_ADDR_WIN, par, "%s(xs=%d, ys=%d, xe=%d, ye=%d)\n", __func__, xs, ys, xe, ye); write_reg(par, 0x15, xs, xe); write_reg(par, 0x75, ys, ye); } static void write_reg8_bus8(struct fbtft_par *par, int len, ...) { va_list args; int i, ret; u8 *buf = (u8 *)par->buf; if (unlikely(par->debug & DEBUG_WRITE_REGISTER)) { va_start(args, len); for (i = 0; i < len; i++) buf[i] = (u8)va_arg(args, unsigned int); va_end(args); fbtft_par_dbg_hex(DEBUG_WRITE_REGISTER, par, par->info->device, u8, buf, len, "%s: ", __func__); } va_start(args, len); *buf = (u8)va_arg(args, unsigned int); if (par->gpio.dc != -1) gpio_set_value(par->gpio.dc, 0); ret = par->fbtftops.write(par, par->buf, sizeof(u8)); if (ret < 0) { va_end(args); dev_err(par->info->device, "write() failed and returned %d\n", ret); return; } len--; if (len) { i = len; while (i--) *buf++ = (u8)va_arg(args, unsigned int); ret = par->fbtftops.write(par, par->buf, len * (sizeof(u8))); if (ret < 0) { va_end(args); dev_err(par->info->device, "write() failed and returned %d\n", ret); return; } } if (par->gpio.dc != -1) gpio_set_value(par->gpio.dc, 1); va_end(args); } /* Grayscale Lookup Table GS1 - GS63 The driver Gamma curve contains the relative values between the entries in the Lookup table. From datasheet: 8.8 Gray Scale Decoder there are total 180 Gamma Settings (Setting 0 to Setting 180) available for the Gray Scale table. The gray scale is defined in incremental way, with reference to the length of previous table entry: Setting of GS1 has to be >= 0 Setting of GS2 has to be > Setting of GS1 +1 Setting of GS3 has to be > Setting of GS2 +1 : Setting of GS63 has to be > Setting of GS62 +1 */ static int set_gamma(struct fbtft_par *par, unsigned long *curves) { unsigned long tmp[GAMMA_NUM * GAMMA_LEN]; int i, acc = 0; fbtft_par_dbg(DEBUG_INIT_DISPLAY, par, "%s()\n", __func__); for (i = 0; i < 63; i++) { if (i > 0 && curves[i] < 2) { dev_err(par->info->device, "Illegal value in Grayscale Lookup Table at index %d. " \ "Must be greater than 1\n", i); return -EINVAL; } acc += curves[i]; tmp[i] = acc; if (acc > 180) { dev_err(par->info->device, "Illegal value(s) in Grayscale Lookup Table. " \ "At index=%d, the accumulated value has exceeded 180\n", i); return -EINVAL; } } write_reg(par, 0xB8, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], tmp[5], tmp[6], tmp[7], tmp[8], tmp[9], tmp[10], tmp[11], tmp[12], tmp[13], tmp[14], tmp[15], tmp[16], tmp[17], tmp[18], tmp[19], tmp[20], tmp[21], tmp[22], tmp[23], tmp[24], tmp[25], tmp[26], tmp[27], tmp[28], tmp[29], tmp[30], tmp[31], tmp[32], tmp[33], tmp[34], tmp[35], tmp[36], tmp[37], tmp[38], tmp[39], tmp[40], tmp[41], tmp[42], tmp[43], tmp[44], tmp[45], tmp[46], tmp[47], tmp[48], tmp[49], tmp[50], tmp[51], tmp[52], tmp[53], tmp[54], tmp[55], tmp[56], tmp[57], tmp[58], tmp[59], tmp[60], tmp[61], tmp[62]); return 0; } static int blank(struct fbtft_par *par, bool on) { fbtft_par_dbg(DEBUG_BLANK, par, "%s(blank=%s)\n", __func__, on ? "true" : "false"); if (on) write_reg(par, 0xAE); else write_reg(par, 0xAF); return 0; } static struct fbtft_display display = { .regwidth = 8, .width = WIDTH, .height = HEIGHT, .gamma_num = GAMMA_NUM, .gamma_len = GAMMA_LEN, .gamma = DEFAULT_GAMMA, .fbtftops = { .write_register = write_reg8_bus8, .init_display = init_display, .set_addr_win = set_addr_win, .set_gamma = set_gamma, .blank = blank, }, }; FBTFT_REGISTER_DRIVER(DRVNAME, "solomon,ssd1331", &display); MODULE_ALIAS("spi:" DRVNAME); MODULE_ALIAS("platform:" DRVNAME); MODULE_ALIAS("spi:ssd1331"); MODULE_ALIAS("platform:ssd1331"); MODULE_DESCRIPTION("SSD1331 OLED Driver"); MODULE_AUTHOR("Alec Smecher (adapted from SSD1351 by James Davies)"); MODULE_LICENSE("GPL");
EvanHa/rbp
linux/drivers/staging/fbtft/fb_ssd1331.c
C
lgpl-3.0
5,648
require 'formula' class Librsync < Formula homepage 'http://librsync.sourceforge.net/' url 'https://downloads.sourceforge.net/project/librsync/librsync/0.9.7/librsync-0.9.7.tar.gz' sha1 'd575eb5cae7a815798220c3afeff5649d3e8b4ab' bottle do cellar :any revision 1 sha1 "754e34fcd1236debb7152e61204364deaa108855" => :yosemite sha1 "3e79aad6623c2332eaa5c650bc9b28e4caf56b9e" => :mavericks sha1 "a0a54b67a85e2e626a4eb9e11b9222afe44351a0" => :mountain_lion end option :universal depends_on 'popt' def install ENV.universal_binary if build.universal? ENV.append 'CFLAGS', '-std=gnu89' system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}", "--enable-shared" inreplace 'libtool' do |s| s.gsub! /compiler_flags=$/, "compiler_flags=' #{ENV.cflags}'" s.gsub! /linker_flags=$/, "linker_flags=' #{ENV.ldflags}'" end system "make install" end end
robotblake/homebrew
Library/Formula/librsync.rb
Ruby
bsd-2-clause
1,080
module TZInfo module Definitions module GMT include TimezoneDefinition linked_timezone 'GMT', 'Etc/GMT' end end end
apcomplete/devise_security_questions
vendor/ruby/gems/tzinfo-0.3.39/lib/tzinfo/definitions/GMT.rb
Ruby
mit
147
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Paginator * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Paginator_Adapter_DbSelect */ require_once 'Zend/Paginator/Adapter/DbSelect.php'; /** * @category Zend * @package Zend_Paginator * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Paginator_Adapter_DbTableSelect extends Zend_Paginator_Adapter_DbSelect { /** * Returns a Zend_Db_Table_Rowset_Abstract of items for a page. * * @param integer $offset Page offset * @param integer $itemCountPerPage Number of items per page * @return Zend_Db_Table_Rowset_Abstract */ public function getItems($offset, $itemCountPerPage) { $this->_select->limit($itemCountPerPage, $offset); return $this->_select->getTable()->fetchAll($this->_select); } }
angusty/symfony-study
vendor/Zend/Paginator/Adapter/DbTableSelect.php
PHP
mit
1,557
'use strict' var tap = require('tap') var test = tap.test var sinon = require('sinon') var shimmer = require('../index.js') test('shimmer initialization', function (t) { t.plan(4) t.doesNotThrow(function () { shimmer() }) var mock = sinon.expectation .create('logger') .withArgs('no original function undefined to wrap') .once() t.doesNotThrow(function () { shimmer({logger: mock}) }, "initializer doesn't throw") t.doesNotThrow(function () { shimmer.wrap() }, "invoking the wrap method with no params doesn't throw") t.doesNotThrow(function () { mock.verify() }, 'logger method was called with the expected message') }) test('shimmer initialized with non-function logger', function (t) { t.plan(2) var mock = sinon.expectation .create('logger') .withArgs("new logger isn't a function, not replacing") .once() shimmer({logger: mock}) t.doesNotThrow(function () { shimmer({logger: {ham: 'chunx'}}) }, "even bad initialization doesn't throw") t.doesNotThrow(function () { mock.verify() }, 'logger initialization failed in the expected way') })
ek1437/PeerTutor
www.peertutor.com/node_modules/shimmer/test/init.tap.js
JavaScript
apache-2.0
1,130
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "Scenario10_DeleteAFile.xaml.h" using namespace SDKTemplate; using namespace concurrency; using namespace Platform; using namespace Windows::Storage; using namespace Windows::UI::Xaml; Scenario10::Scenario10() : rootPage(MainPage::Current) { InitializeComponent(); rootPage->Initialize(); rootPage->ValidateFile(); DeleteFileButton->Click += ref new RoutedEventHandler(this, &Scenario10::DeleteFileButton_Click); } void Scenario10::DeleteFileButton_Click(Object^ sender, RoutedEventArgs^ e) { StorageFile^ file = rootPage->SampleFile; if (file != nullptr) { String^ fileName = file->Name; // Deletes the file create_task(file->DeleteAsync()).then([this, fileName](task<void> task) { try { task.get(); rootPage->SampleFile = nullptr; rootPage->NotifyUser("The file '" + fileName + "' was deleted", NotifyType::StatusMessage); } catch (COMException^ ex) { rootPage->HandleFileNotFoundException(ex); } }); } else { rootPage->NotifyUserFileNotExist(); } }
williamsrz/Windows-universal-samples
fileaccess/cpp/scenario10_deleteafile.xaml.cpp
C++
mit
1,647
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.disruptor.vm; import org.apache.camel.ContextTestSupport; import org.apache.camel.ExchangePattern; import org.apache.camel.builder.RouteBuilder; /** * */ public class DisruptorVmMultipleConsumersIssueTest extends ContextTestSupport { public void testDisruptorVmMultipleConsumersIssue() throws Exception { getMockEndpoint("mock:a").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:b").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:c").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:d").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:e").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:done").expectedBodiesReceived("Hello World"); template.sendBody("direct:inbox", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:inbox") .to(ExchangePattern.InOut, "disruptor-vm:foo?timeout=5000") .to("mock:done"); from("disruptor-vm:foo?multipleConsumers=true") .to("log:a") .to("mock:a"); from("disruptor-vm:foo?multipleConsumers=true") .to("log:b") .to("mock:b"); from("disruptor-vm:foo?multipleConsumers=true") .to("log:c") .to("mock:c"); from("disruptor-vm:foo?multipleConsumers=true") .to("log:d") .to("mock:d"); from("disruptor-vm:foo?multipleConsumers=true") .to("log:e") .to("mock:e"); } }; } }
coderczp/camel
components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/vm/DisruptorVmMultipleConsumersIssueTest.java
Java
apache-2.0
2,796
/* * xfi linux driver. * * Copyright (C) 2008, Creative Technology Ltd. All Rights Reserved. * * This source file is released under GPL v2 license (no other versions). * See the COPYING file included in the main directory of this source * distribution for the license terms and conditions. */ #include <linux/init.h> #include <linux/pci.h> #include <linux/moduleparam.h> #include <linux/pci_ids.h> #include <linux/module.h> #include <sound/core.h> #include <sound/initval.h> #include "ctatc.h" #include "cthardware.h" MODULE_AUTHOR("Creative Technology Ltd"); MODULE_DESCRIPTION("X-Fi driver version 1.03"); MODULE_LICENSE("GPL v2"); MODULE_SUPPORTED_DEVICE("{{Creative Labs, Sound Blaster X-Fi}"); static unsigned int reference_rate = 48000; static unsigned int multiple = 2; MODULE_PARM_DESC(reference_rate, "Reference rate (default=48000)"); module_param(reference_rate, uint, S_IRUGO); MODULE_PARM_DESC(multiple, "Rate multiplier (default=2)"); module_param(multiple, uint, S_IRUGO); static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; static unsigned int subsystem[SNDRV_CARDS]; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for Creative X-Fi driver"); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for Creative X-Fi driver"); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable Creative X-Fi driver"); module_param_array(subsystem, int, NULL, 0444); MODULE_PARM_DESC(subsystem, "Override subsystem ID for Creative X-Fi driver"); static DEFINE_PCI_DEVICE_TABLE(ct_pci_dev_ids) = { /* only X-Fi is supported, so... */ { PCI_DEVICE(PCI_VENDOR_ID_CREATIVE, PCI_DEVICE_ID_CREATIVE_20K1), .driver_data = ATC20K1, }, { PCI_DEVICE(PCI_VENDOR_ID_CREATIVE, PCI_DEVICE_ID_CREATIVE_20K2), .driver_data = ATC20K2, }, { 0, } }; MODULE_DEVICE_TABLE(pci, ct_pci_dev_ids); static int ct_card_probe(struct pci_dev *pci, const struct pci_device_id *pci_id) { static int dev; struct snd_card *card; struct ct_atc *atc; int err; if (dev >= SNDRV_CARDS) return -ENODEV; if (!enable[dev]) { dev++; return -ENOENT; } err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE, 0, &card); if (err) return err; if ((reference_rate != 48000) && (reference_rate != 44100)) { printk(KERN_ERR "ctxfi: Invalid reference_rate value %u!!!\n", reference_rate); printk(KERN_ERR "ctxfi: The valid values for reference_rate " "are 48000 and 44100, Value 48000 is assumed.\n"); reference_rate = 48000; } if ((multiple != 1) && (multiple != 2) && (multiple != 4)) { printk(KERN_ERR "ctxfi: Invalid multiple value %u!!!\n", multiple); printk(KERN_ERR "ctxfi: The valid values for multiple are " "1, 2 and 4, Value 2 is assumed.\n"); multiple = 2; } err = ct_atc_create(card, pci, reference_rate, multiple, pci_id->driver_data, subsystem[dev], &atc); if (err < 0) goto error; card->private_data = atc; /* Create alsa devices supported by this card */ err = ct_atc_create_alsa_devs(atc); if (err < 0) goto error; strcpy(card->driver, "SB-XFi"); strcpy(card->shortname, "Creative X-Fi"); snprintf(card->longname, sizeof(card->longname), "%s %s %s", card->shortname, atc->chip_name, atc->model_name); err = snd_card_register(card); if (err < 0) goto error; pci_set_drvdata(pci, card); dev++; return 0; error: snd_card_free(card); return err; } static void ct_card_remove(struct pci_dev *pci) { snd_card_free(pci_get_drvdata(pci)); } #ifdef CONFIG_PM_SLEEP static int ct_card_suspend(struct device *dev) { struct snd_card *card = dev_get_drvdata(dev); struct ct_atc *atc = card->private_data; return atc->suspend(atc); } static int ct_card_resume(struct device *dev) { struct snd_card *card = dev_get_drvdata(dev); struct ct_atc *atc = card->private_data; return atc->resume(atc); } static SIMPLE_DEV_PM_OPS(ct_card_pm, ct_card_suspend, ct_card_resume); #define CT_CARD_PM_OPS &ct_card_pm #else #define CT_CARD_PM_OPS NULL #endif static struct pci_driver ct_driver = { .name = KBUILD_MODNAME, .id_table = ct_pci_dev_ids, .probe = ct_card_probe, .remove = ct_card_remove, .driver = { .pm = CT_CARD_PM_OPS, }, }; module_pci_driver(ct_driver);
waterzhou/zynqlinux
sound/pci/ctxfi/xfi.c
C
gpl-2.0
4,372
/* * Copyright (c) 2012, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LayoutUnit_h #define LayoutUnit_h #include <limits.h> #include <limits> #include <math.h> #include <stdlib.h> #include <wtf/MathExtras.h> #include <wtf/SaturatedArithmetic.h> namespace WebCore { #ifdef NDEBUG #define REPORT_OVERFLOW(doesOverflow) ((void)0) #else #define REPORT_OVERFLOW(doesOverflow) do \ if (!(doesOverflow)) { \ WTFReportError(__FILE__, __LINE__, WTF_PRETTY_FUNCTION, "!(%s)", #doesOverflow); \ } \ while (0) #endif static const int kFixedPointDenominator = 64; #if ENABLE(SUBPIXEL_LAYOUT) static const int kEffectiveFixedPointDenominator = kFixedPointDenominator; #else static const int kEffectiveFixedPointDenominator = 1; #endif const int intMaxForLayoutUnit = INT_MAX / kEffectiveFixedPointDenominator; const int intMinForLayoutUnit = INT_MIN / kEffectiveFixedPointDenominator; class LayoutUnit { public: LayoutUnit() : m_value(0) { } #if ENABLE(SUBPIXEL_LAYOUT) LayoutUnit(int value) { setValue(value); } LayoutUnit(unsigned short value) { setValue(value); } LayoutUnit(unsigned value) { setValue(value); } LayoutUnit(unsigned long value) { #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) m_value = clampTo<int>(value * kEffectiveFixedPointDenominator); #else REPORT_OVERFLOW(isInBounds(static_cast<unsigned>(value))); m_value = value * kEffectiveFixedPointDenominator; #endif } LayoutUnit(unsigned long long value) { #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) m_value = clampTo<int>(value * kEffectiveFixedPointDenominator); #else REPORT_OVERFLOW(isInBounds(static_cast<unsigned>(value))); m_value = static_cast<int>(value * kEffectiveFixedPointDenominator); #endif } LayoutUnit(float value) { #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) m_value = clampTo<float>(value * kEffectiveFixedPointDenominator, static_cast<float>(INT_MIN), static_cast<float>(INT_MAX)); #else REPORT_OVERFLOW(isInBounds(value)); m_value = value * kEffectiveFixedPointDenominator; #endif } LayoutUnit(double value) { #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) m_value = clampTo<double>(value * kEffectiveFixedPointDenominator, static_cast<double>(INT_MIN), static_cast<double>(INT_MAX)); #else REPORT_OVERFLOW(isInBounds(value)); m_value = value * kEffectiveFixedPointDenominator; #endif } #else LayoutUnit(int value) { REPORT_OVERFLOW(isInBounds(value)); m_value = value; } LayoutUnit(unsigned short value) { REPORT_OVERFLOW(isInBounds(value)); m_value = value; } LayoutUnit(unsigned value) { REPORT_OVERFLOW(isInBounds(value)); m_value = clampTo<int>(value); } LayoutUnit(unsigned long long value) { REPORT_OVERFLOW(isInBounds(static_cast<unsigned>(value))); m_value = clampTo<int>(value); } LayoutUnit(unsigned long value) { REPORT_OVERFLOW(isInBounds(static_cast<unsigned>(value))); m_value = clampTo<int>(value); } LayoutUnit(float value) { REPORT_OVERFLOW(isInBounds(value)); m_value = clampTo<int>(value); } LayoutUnit(double value) { REPORT_OVERFLOW(isInBounds(value)); m_value = clampTo<int>(value); } #endif static LayoutUnit fromFloatCeil(float value) { LayoutUnit v; #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) v.m_value = clampToInteger(ceilf(value * kEffectiveFixedPointDenominator)); #else REPORT_OVERFLOW(isInBounds(value)); v.m_value = ceilf(value * kEffectiveFixedPointDenominator); #endif return v; } static LayoutUnit fromFloatFloor(float value) { LayoutUnit v; #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) v.m_value = clampToInteger(floorf(value * kEffectiveFixedPointDenominator)); #else REPORT_OVERFLOW(isInBounds(value)); v.m_value = floorf(value * kEffectiveFixedPointDenominator); #endif return v; } static LayoutUnit fromFloatRound(float value) { #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) if (value >= 0) return clamp(value + epsilon() / 2.0f); return clamp(value - epsilon() / 2.0f); #else if (value >= 0) { REPORT_OVERFLOW(isInBounds(value + epsilon() / 2.0f)); return LayoutUnit(value + epsilon() / 2.0f); } REPORT_OVERFLOW(isInBounds(value - epsilon() / 2.0f)); return LayoutUnit(value - epsilon() / 2.0f); #endif } #if ENABLE(SUBPIXEL_LAYOUT) int toInt() const { return m_value / kEffectiveFixedPointDenominator; } float toFloat() const { return static_cast<float>(m_value) / kEffectiveFixedPointDenominator; } double toDouble() const { return static_cast<double>(m_value) / kEffectiveFixedPointDenominator; } float ceilToFloat() const { float floatValue = toFloat(); if (static_cast<int>(floatValue * kEffectiveFixedPointDenominator) == m_value) return floatValue; if (floatValue > 0) return nextafterf(floatValue, std::numeric_limits<float>::max()); return nextafterf(floatValue, std::numeric_limits<float>::min()); } #else int toInt() const { return m_value; } float toFloat() const { return static_cast<float>(m_value); } double toDouble() const { return static_cast<double>(m_value); } float ceilToFloat() const { return toFloat(); } #endif unsigned toUnsigned() const { REPORT_OVERFLOW(m_value >= 0); return toInt(); } operator int() const { return toInt(); } operator unsigned() const { return toUnsigned(); } operator float() const { return toFloat(); } operator double() const { return toDouble(); } operator bool() const { return m_value; } LayoutUnit operator++(int) { m_value += kEffectiveFixedPointDenominator; return *this; } inline int rawValue() const { return m_value; } inline void setRawValue(int value) { m_value = value; } void setRawValue(long long value) { REPORT_OVERFLOW(value > std::numeric_limits<int>::min() && value < std::numeric_limits<int>::max()); m_value = static_cast<int>(value); } LayoutUnit abs() const { LayoutUnit returnValue; returnValue.setRawValue(::abs(m_value)); return returnValue; } #if OS(DARWIN) int wtf_ceil() const #else int ceil() const #endif { #if ENABLE(SUBPIXEL_LAYOUT) #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) if (UNLIKELY(m_value >= INT_MAX - kEffectiveFixedPointDenominator + 1)) return intMaxForLayoutUnit; #endif if (m_value >= 0) return (m_value + kEffectiveFixedPointDenominator - 1) / kEffectiveFixedPointDenominator; return toInt(); #else return m_value; #endif } int round() const { #if ENABLE(SUBPIXEL_LAYOUT) && ENABLE(SATURATED_LAYOUT_ARITHMETIC) if (m_value > 0) return saturatedAddition(rawValue(), kEffectiveFixedPointDenominator / 2) / kEffectiveFixedPointDenominator; return saturatedSubtraction(rawValue(), (kEffectiveFixedPointDenominator / 2) - 1) / kEffectiveFixedPointDenominator; #elif ENABLE(SUBPIXEL_LAYOUT) if (m_value > 0) return (m_value + (kEffectiveFixedPointDenominator / 2)) / kEffectiveFixedPointDenominator; return (m_value - ((kEffectiveFixedPointDenominator / 2) - 1)) / kEffectiveFixedPointDenominator; #else return m_value; #endif } int floor() const { #if ENABLE(SUBPIXEL_LAYOUT) #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) if (UNLIKELY(m_value <= INT_MIN + kEffectiveFixedPointDenominator - 1)) return intMinForLayoutUnit; #endif if (m_value >= 0) return toInt(); return (m_value - kEffectiveFixedPointDenominator + 1) / kEffectiveFixedPointDenominator; #else return m_value; #endif } LayoutUnit fraction() const { // Add the fraction to the size (as opposed to the full location) to avoid overflows. // Compute fraction using the mod operator to preserve the sign of the value as it may affect rounding. LayoutUnit fraction; fraction.setRawValue(rawValue() % kEffectiveFixedPointDenominator); return fraction; } #if ENABLE(SUBPIXEL_LAYOUT) bool mightBeSaturated() const { return rawValue() == std::numeric_limits<int>::max() || rawValue() == std::numeric_limits<int>::min(); } static float epsilon() { return 1.0f / kEffectiveFixedPointDenominator; } #else static int epsilon() { return 0; } #endif static const LayoutUnit max() { LayoutUnit m; m.m_value = std::numeric_limits<int>::max(); return m; } static const LayoutUnit min() { LayoutUnit m; m.m_value = std::numeric_limits<int>::min(); return m; } // Versions of max/min that are slightly smaller/larger than max/min() to allow for roinding without overflowing. static const LayoutUnit nearlyMax() { LayoutUnit m; m.m_value = std::numeric_limits<int>::max() - kEffectiveFixedPointDenominator / 2; return m; } static const LayoutUnit nearlyMin() { LayoutUnit m; m.m_value = std::numeric_limits<int>::min() + kEffectiveFixedPointDenominator / 2; return m; } static LayoutUnit clamp(double value) { return clampTo<LayoutUnit>(value, LayoutUnit::min(), LayoutUnit::max()); } private: static bool isInBounds(int value) { return ::abs(value) <= std::numeric_limits<int>::max() / kEffectiveFixedPointDenominator; } static bool isInBounds(unsigned value) { return value <= static_cast<unsigned>(std::numeric_limits<int>::max()) / kEffectiveFixedPointDenominator; } static bool isInBounds(double value) { return ::fabs(value) <= std::numeric_limits<int>::max() / kEffectiveFixedPointDenominator; } inline void setValue(int value) { #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) if (value > intMaxForLayoutUnit) m_value = std::numeric_limits<int>::max(); else if (value < intMinForLayoutUnit) m_value = std::numeric_limits<int>::min(); else m_value = value * kEffectiveFixedPointDenominator; #else REPORT_OVERFLOW(isInBounds(value)); m_value = value * kEffectiveFixedPointDenominator; #endif } inline void setValue(unsigned value) { #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) if (value >= static_cast<unsigned>(intMaxForLayoutUnit)) m_value = std::numeric_limits<int>::max(); else m_value = value * kEffectiveFixedPointDenominator; #else REPORT_OVERFLOW(isInBounds(value)); m_value = value * kEffectiveFixedPointDenominator; #endif } int m_value; }; inline bool operator<=(const LayoutUnit& a, const LayoutUnit& b) { return a.rawValue() <= b.rawValue(); } inline bool operator<=(const LayoutUnit& a, float b) { return a.toFloat() <= b; } inline bool operator<=(const LayoutUnit& a, int b) { return a <= LayoutUnit(b); } inline bool operator<=(const float a, const LayoutUnit& b) { return a <= b.toFloat(); } inline bool operator<=(const int a, const LayoutUnit& b) { return LayoutUnit(a) <= b; } inline bool operator>=(const LayoutUnit& a, const LayoutUnit& b) { return a.rawValue() >= b.rawValue(); } inline bool operator>=(const LayoutUnit& a, int b) { return a >= LayoutUnit(b); } inline bool operator>=(const float a, const LayoutUnit& b) { return a >= b.toFloat(); } inline bool operator>=(const LayoutUnit& a, float b) { return a.toFloat() >= b; } inline bool operator>=(const int a, const LayoutUnit& b) { return LayoutUnit(a) >= b; } inline bool operator<(const LayoutUnit& a, const LayoutUnit& b) { return a.rawValue() < b.rawValue(); } inline bool operator<(const LayoutUnit& a, int b) { return a < LayoutUnit(b); } inline bool operator<(const LayoutUnit& a, float b) { return a.toFloat() < b; } inline bool operator<(const LayoutUnit& a, double b) { return a.toDouble() < b; } inline bool operator<(const int a, const LayoutUnit& b) { return LayoutUnit(a) < b; } inline bool operator<(const float a, const LayoutUnit& b) { return a < b.toFloat(); } inline bool operator>(const LayoutUnit& a, const LayoutUnit& b) { return a.rawValue() > b.rawValue(); } inline bool operator>(const LayoutUnit& a, double b) { return a.toDouble() > b; } inline bool operator>(const LayoutUnit& a, float b) { return a.toFloat() > b; } inline bool operator>(const LayoutUnit& a, int b) { return a > LayoutUnit(b); } inline bool operator>(const int a, const LayoutUnit& b) { return LayoutUnit(a) > b; } inline bool operator>(const float a, const LayoutUnit& b) { return a > b.toFloat(); } inline bool operator>(const double a, const LayoutUnit& b) { return a > b.toDouble(); } inline bool operator!=(const LayoutUnit& a, const LayoutUnit& b) { return a.rawValue() != b.rawValue(); } inline bool operator!=(const LayoutUnit& a, float b) { return a != LayoutUnit(b); } inline bool operator!=(const int a, const LayoutUnit& b) { return LayoutUnit(a) != b; } inline bool operator!=(const LayoutUnit& a, int b) { return a != LayoutUnit(b); } inline bool operator==(const LayoutUnit& a, const LayoutUnit& b) { return a.rawValue() == b.rawValue(); } inline bool operator==(const LayoutUnit& a, int b) { return a == LayoutUnit(b); } inline bool operator==(const int a, const LayoutUnit& b) { return LayoutUnit(a) == b; } inline bool operator==(const LayoutUnit& a, float b) { return a.toFloat() == b; } inline bool operator==(const float a, const LayoutUnit& b) { return a == b.toFloat(); } // For multiplication that's prone to overflow, this bounds it to LayoutUnit::max() and ::min() inline LayoutUnit boundedMultiply(const LayoutUnit& a, const LayoutUnit& b) { #if ENABLE(SUBPIXEL_LAYOUT) int64_t result = static_cast<int64_t>(a.rawValue()) * static_cast<int64_t>(b.rawValue()) / kEffectiveFixedPointDenominator; int32_t high = static_cast<int32_t>(result >> 32); int32_t low = static_cast<int32_t>(result); uint32_t saturated = (static_cast<uint32_t>(a.rawValue() ^ b.rawValue()) >> 31) + std::numeric_limits<int>::max(); // If the higher 32 bits does not match the lower 32 with sign extension the operation overflowed. if (high != low >> 31) result = saturated; LayoutUnit returnVal; returnVal.setRawValue(static_cast<int>(result)); return returnVal; #else // FIXME: Should be bounded even in the non-subpixel case. return a.rawValue() * b.rawValue(); #endif } inline LayoutUnit operator*(const LayoutUnit& a, const LayoutUnit& b) { #if ENABLE(SUBPIXEL_LAYOUT) && ENABLE(SATURATED_LAYOUT_ARITHMETIC) return boundedMultiply(a, b); #elif ENABLE(SUBPIXEL_LAYOUT) LayoutUnit returnVal; long long rawVal = static_cast<long long>(a.rawValue()) * b.rawValue() / kEffectiveFixedPointDenominator; returnVal.setRawValue(rawVal); return returnVal; #else return a.rawValue() * b.rawValue(); #endif } inline double operator*(const LayoutUnit& a, double b) { return a.toDouble() * b; } inline float operator*(const LayoutUnit& a, float b) { return a.toFloat() * b; } inline LayoutUnit operator*(const LayoutUnit& a, int b) { return a * LayoutUnit(b); } inline LayoutUnit operator*(const LayoutUnit& a, unsigned short b) { return a * LayoutUnit(b); } inline LayoutUnit operator*(const LayoutUnit& a, unsigned b) { return a * LayoutUnit(b); } inline LayoutUnit operator*(const LayoutUnit& a, unsigned long b) { return a * LayoutUnit(b); } inline LayoutUnit operator*(const LayoutUnit& a, unsigned long long b) { return a * LayoutUnit(b); } inline LayoutUnit operator*(unsigned short a, const LayoutUnit& b) { return LayoutUnit(a) * b; } inline LayoutUnit operator*(unsigned a, const LayoutUnit& b) { return LayoutUnit(a) * b; } inline LayoutUnit operator*(unsigned long a, const LayoutUnit& b) { return LayoutUnit(a) * b; } inline LayoutUnit operator*(unsigned long long a, const LayoutUnit& b) { return LayoutUnit(a) * b; } inline LayoutUnit operator*(const int a, const LayoutUnit& b) { return LayoutUnit(a) * b; } inline float operator*(const float a, const LayoutUnit& b) { return a * b.toFloat(); } inline double operator*(const double a, const LayoutUnit& b) { return a * b.toDouble(); } inline LayoutUnit operator/(const LayoutUnit& a, const LayoutUnit& b) { #if ENABLE(SUBPIXEL_LAYOUT) LayoutUnit returnVal; long long rawVal = static_cast<long long>(kEffectiveFixedPointDenominator) * a.rawValue() / b.rawValue(); #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) returnVal.setRawValue(clampTo<int>(rawVal)); #else returnVal.setRawValue(rawVal); #endif return returnVal; #else return a.rawValue() / b.rawValue(); #endif } inline float operator/(const LayoutUnit& a, float b) { return a.toFloat() / b; } inline double operator/(const LayoutUnit& a, double b) { return a.toDouble() / b; } inline LayoutUnit operator/(const LayoutUnit& a, int b) { return a / LayoutUnit(b); } inline LayoutUnit operator/(const LayoutUnit& a, unsigned short b) { return a / LayoutUnit(b); } inline LayoutUnit operator/(const LayoutUnit& a, unsigned b) { return a / LayoutUnit(b); } inline LayoutUnit operator/(const LayoutUnit& a, unsigned long b) { return a / LayoutUnit(b); } inline LayoutUnit operator/(const LayoutUnit& a, unsigned long long b) { return a / LayoutUnit(b); } inline float operator/(const float a, const LayoutUnit& b) { return a / b.toFloat(); } inline double operator/(const double a, const LayoutUnit& b) { return a / b.toDouble(); } inline LayoutUnit operator/(const int a, const LayoutUnit& b) { return LayoutUnit(a) / b; } inline LayoutUnit operator/(unsigned short a, const LayoutUnit& b) { return LayoutUnit(a) / b; } inline LayoutUnit operator/(unsigned a, const LayoutUnit& b) { return LayoutUnit(a) / b; } inline LayoutUnit operator/(unsigned long a, const LayoutUnit& b) { return LayoutUnit(a) / b; } inline LayoutUnit operator/(unsigned long long a, const LayoutUnit& b) { return LayoutUnit(a) / b; } inline LayoutUnit operator+(const LayoutUnit& a, const LayoutUnit& b) { LayoutUnit returnVal; #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) returnVal.setRawValue(saturatedAddition(a.rawValue(), b.rawValue())); #else returnVal.setRawValue(a.rawValue() + b.rawValue()); #endif return returnVal; } inline LayoutUnit operator+(const LayoutUnit& a, int b) { return a + LayoutUnit(b); } inline float operator+(const LayoutUnit& a, float b) { return a.toFloat() + b; } inline double operator+(const LayoutUnit& a, double b) { return a.toDouble() + b; } inline LayoutUnit operator+(const int a, const LayoutUnit& b) { return LayoutUnit(a) + b; } inline float operator+(const float a, const LayoutUnit& b) { return a + b.toFloat(); } inline double operator+(const double a, const LayoutUnit& b) { return a + b.toDouble(); } inline LayoutUnit operator-(const LayoutUnit& a, const LayoutUnit& b) { LayoutUnit returnVal; #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) returnVal.setRawValue(saturatedSubtraction(a.rawValue(), b.rawValue())); #else returnVal.setRawValue(a.rawValue() - b.rawValue()); #endif return returnVal; } inline LayoutUnit operator-(const LayoutUnit& a, int b) { return a - LayoutUnit(b); } inline LayoutUnit operator-(const LayoutUnit& a, unsigned b) { return a - LayoutUnit(b); } inline float operator-(const LayoutUnit& a, float b) { return a.toFloat() - b; } inline LayoutUnit operator-(const int a, const LayoutUnit& b) { return LayoutUnit(a) - b; } inline float operator-(const float a, const LayoutUnit& b) { return a - b.toFloat(); } inline LayoutUnit operator-(const LayoutUnit& a) { LayoutUnit returnVal; returnVal.setRawValue(-a.rawValue()); return returnVal; } // For returning the remainder after a division with integer results. inline LayoutUnit intMod(const LayoutUnit& a, const LayoutUnit& b) { #if ENABLE(SUBPIXEL_LAYOUT) // This calculates the modulo so that: a = static_cast<int>(a / b) * b + intMod(a, b). LayoutUnit returnVal; returnVal.setRawValue(a.rawValue() % b.rawValue()); return returnVal; #else return a.rawValue() % b.rawValue(); #endif } inline LayoutUnit operator%(const LayoutUnit& a, const LayoutUnit& b) { #if ENABLE(SUBPIXEL_LAYOUT) // This calculates the modulo so that: a = (a / b) * b + a % b. LayoutUnit returnVal; long long rawVal = (static_cast<long long>(kEffectiveFixedPointDenominator) * a.rawValue()) % b.rawValue(); returnVal.setRawValue(rawVal / kEffectiveFixedPointDenominator); return returnVal; #else return a.rawValue() % b.rawValue(); #endif } inline LayoutUnit operator%(const LayoutUnit& a, int b) { return a % LayoutUnit(b); } inline LayoutUnit operator%(int a, const LayoutUnit& b) { return LayoutUnit(a) % b; } inline LayoutUnit& operator+=(LayoutUnit& a, const LayoutUnit& b) { #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) a.setRawValue(saturatedAddition(a.rawValue(), b.rawValue())); #else a = a + b; #endif return a; } inline LayoutUnit& operator+=(LayoutUnit& a, int b) { a = a + b; return a; } inline LayoutUnit& operator+=(LayoutUnit& a, float b) { a = a + b; return a; } inline float& operator+=(float& a, const LayoutUnit& b) { a = a + b; return a; } inline LayoutUnit& operator-=(LayoutUnit& a, int b) { a = a - b; return a; } inline LayoutUnit& operator-=(LayoutUnit& a, const LayoutUnit& b) { #if ENABLE(SATURATED_LAYOUT_ARITHMETIC) a.setRawValue(saturatedSubtraction(a.rawValue(), b.rawValue())); #else a = a - b; #endif return a; } inline LayoutUnit& operator-=(LayoutUnit& a, float b) { a = a - b; return a; } inline float& operator-=(float& a, const LayoutUnit& b) { a = a - b; return a; } inline LayoutUnit& operator*=(LayoutUnit& a, const LayoutUnit& b) { a = a * b; return a; } // operator*=(LayoutUnit& a, int b) is supported by the operator above plus LayoutUnit(int). inline LayoutUnit& operator*=(LayoutUnit& a, float b) { a = a * b; return a; } inline float& operator*=(float& a, const LayoutUnit& b) { a = a * b; return a; } inline LayoutUnit& operator/=(LayoutUnit& a, const LayoutUnit& b) { a = a / b; return a; } // operator/=(LayoutUnit& a, int b) is supported by the operator above plus LayoutUnit(int). inline LayoutUnit& operator/=(LayoutUnit& a, float b) { a = a / b; return a; } inline float& operator/=(float& a, const LayoutUnit& b) { a = a / b; return a; } inline int snapSizeToPixel(LayoutUnit size, LayoutUnit location) { LayoutUnit fraction = location.fraction(); return (fraction + size).round() - fraction.round(); } inline int roundToInt(LayoutUnit value) { return value.round(); } inline int floorToInt(LayoutUnit value) { return value.floor(); } inline LayoutUnit roundedLayoutUnit(float value) { #if ENABLE(SUBPIXEL_LAYOUT) return LayoutUnit::fromFloatRound(value); #else return static_cast<int>(lroundf(value)); #endif } inline LayoutUnit ceiledLayoutUnit(float value) { #if ENABLE(SUBPIXEL_LAYOUT) return LayoutUnit::fromFloatCeil(value); #else return ceilf(value); #endif } inline LayoutUnit absoluteValue(const LayoutUnit& value) { return value.abs(); } inline LayoutUnit layoutMod(const LayoutUnit& numerator, const LayoutUnit& denominator) { return numerator % denominator; } inline bool isIntegerValue(const LayoutUnit value) { return value.toInt() == value; } } // namespace WebCore #endif // LayoutUnit_h
klim-iv/phantomjs-qt5
src/webkit/Source/WebCore/platform/LayoutUnit.h
C
bsd-3-clause
25,415
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "a.m.", "p.m." ], "DAY": [ "Domingo", "Lunes", "Martes", "Mi\u00e9rcoles", "Jueves", "Viernes", "S\u00e1bado" ], "ERANAMES": [ "BCE", "d.C." ], "ERAS": [ "BCE", "d.C." ], "MONTH": [ "Qulla puquy", "Hatun puquy", "Pauqar waray", "Ayriwa", "Aymuray", "Inti raymi", "Anta Sitwa", "Qhapaq Sitwa", "Uma raymi", "Kantaray", "Ayamarq\u02bca", "Kapaq Raymi" ], "SHORTDAY": [ "Dom", "Lun", "Mar", "Mi\u00e9", "Jue", "Vie", "Sab" ], "SHORTMONTH": [ "Qul", "Hat", "Pau", "Ayr", "Aym", "Int", "Ant", "Qha", "Uma", "Kan", "Aya", "Kap" ], "fullDate": "EEEE, d MMMM, y", "longDate": "y MMMM d", "medium": "y MMM d hh:mm:ss a", "mediumDate": "y MMM d", "mediumTime": "hh:mm:ss a", "short": "dd/MM/y hh:mm a", "shortDate": "dd/MM/y", "shortTime": "hh:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "Bs", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4\u00a0-", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "qu-bo", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
vvp5511/VelvetPath
webapp/Scripts/i18n/angular-locale_qu-bo.js
JavaScript
gpl-3.0
2,457
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.builder; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.camel.ContextTestSupport; /** * */ public class ProxyBuilderTest extends ContextTestSupport { public void testSayFoo() throws Exception { Foo foo = new ProxyBuilder(context).endpoint("direct:start").build(Foo.class); Future<String> future = foo.sayHello("Camel"); assertNotNull(future); assertFalse("Should not be done", future.isDone()); assertEquals("Hello Camel", future.get(5, TimeUnit.SECONDS)); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .delay(1000) .transform(body().prepend("Hello ")); } }; } interface Foo { Future<String> sayHello(String body); } }
logzio/camel
camel-core/src/test/java/org/apache/camel/builder/ProxyBuilderTest.java
Java
apache-2.0
1,818
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "IDBKeyRange.h" #include "DOMRequestState.h" #include "IDBBindingUtilities.h" #include "IDBDatabaseException.h" #include "IDBKey.h" #if ENABLE(INDEXED_DATABASE) namespace WebCore { PassRefPtr<IDBKeyRange> IDBKeyRange::create(PassRefPtr<IDBKey> prpKey) { RefPtr<IDBKey> key = prpKey; return adoptRef(new IDBKeyRange(key, key, LowerBoundClosed, UpperBoundClosed)); } IDBKeyRange::IDBKeyRange(PassRefPtr<IDBKey> lower, PassRefPtr<IDBKey> upper, LowerBoundType lowerType, UpperBoundType upperType) : m_lower(lower) , m_upper(upper) , m_lowerType(lowerType) , m_upperType(upperType) { } ScriptValue IDBKeyRange::lowerValue(ScriptExecutionContext* context) const { DOMRequestState requestState(context); return idbKeyToScriptValue(&requestState, m_lower); } ScriptValue IDBKeyRange::upperValue(ScriptExecutionContext* context) const { DOMRequestState requestState(context); return idbKeyToScriptValue(&requestState, m_upper); } PassRefPtr<IDBKeyRange> IDBKeyRange::only(PassRefPtr<IDBKey> prpKey, ExceptionCode& ec) { RefPtr<IDBKey> key = prpKey; if (!key || !key->isValid()) { ec = IDBDatabaseException::DataError; return 0; } return IDBKeyRange::create(key, key, LowerBoundClosed, UpperBoundClosed); } PassRefPtr<IDBKeyRange> IDBKeyRange::only(ScriptExecutionContext* context, const ScriptValue& keyValue, ExceptionCode& ec) { DOMRequestState requestState(context); RefPtr<IDBKey> key = scriptValueToIDBKey(&requestState, keyValue); if (!key || !key->isValid()) { ec = IDBDatabaseException::DataError; return 0; } return IDBKeyRange::create(key, key, LowerBoundClosed, UpperBoundClosed); } PassRefPtr<IDBKeyRange> IDBKeyRange::lowerBound(ScriptExecutionContext* context, const ScriptValue& boundValue, bool open, ExceptionCode& ec) { DOMRequestState requestState(context); RefPtr<IDBKey> bound = scriptValueToIDBKey(&requestState, boundValue); if (!bound || !bound->isValid()) { ec = IDBDatabaseException::DataError; return 0; } return IDBKeyRange::create(bound, 0, open ? LowerBoundOpen : LowerBoundClosed, UpperBoundOpen); } PassRefPtr<IDBKeyRange> IDBKeyRange::upperBound(ScriptExecutionContext* context, const ScriptValue& boundValue, bool open, ExceptionCode& ec) { DOMRequestState requestState(context); RefPtr<IDBKey> bound = scriptValueToIDBKey(&requestState, boundValue); if (!bound || !bound->isValid()) { ec = IDBDatabaseException::DataError; return 0; } return IDBKeyRange::create(0, bound, LowerBoundOpen, open ? UpperBoundOpen : UpperBoundClosed); } PassRefPtr<IDBKeyRange> IDBKeyRange::bound(ScriptExecutionContext* context, const ScriptValue& lowerValue, const ScriptValue& upperValue, bool lowerOpen, bool upperOpen, ExceptionCode& ec) { DOMRequestState requestState(context); RefPtr<IDBKey> lower = scriptValueToIDBKey(&requestState, lowerValue); RefPtr<IDBKey> upper = scriptValueToIDBKey(&requestState, upperValue); if (!lower || !lower->isValid() || !upper || !upper->isValid()) { ec = IDBDatabaseException::DataError; return 0; } if (upper->isLessThan(lower.get())) { ec = IDBDatabaseException::DataError; return 0; } if (upper->isEqual(lower.get()) && (lowerOpen || upperOpen)) { ec = IDBDatabaseException::DataError; return 0; } return IDBKeyRange::create(lower, upper, lowerOpen ? LowerBoundOpen : LowerBoundClosed, upperOpen ? UpperBoundOpen : UpperBoundClosed); } bool IDBKeyRange::isOnlyKey() const { if (m_lowerType != LowerBoundClosed || m_upperType != UpperBoundClosed) return false; ASSERT(m_lower); ASSERT(m_upper); return m_lower->isEqual(m_upper.get()); } } // namespace WebCore #endif // ENABLE(INDEXED_DATABASE)
klim-iv/phantomjs-qt5
src/webkit/Source/WebCore/Modules/indexeddb/IDBKeyRange.cpp
C++
bsd-3-clause
5,238
/* Copyright (c) 2010, Code Aurora Forum. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Code Aurora Forum, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef _VCD_CLIENT_SM_H_ #define _VCD_CLIENT_SM_H_ #include "vcd_api.h" #include "vcd_ddl_api.h" struct vcd_clnt_state_table; struct vcd_clnt_state_ctxt; struct vcd_clnt_ctxt; enum vcd_clnt_state_enum { VCD_CLIENT_STATE_NULL = 0, VCD_CLIENT_STATE_OPEN, VCD_CLIENT_STATE_STARTING, VCD_CLIENT_STATE_RUN, VCD_CLIENT_STATE_FLUSHING, VCD_CLIENT_STATE_PAUSING, VCD_CLIENT_STATE_PAUSED, VCD_CLIENT_STATE_STOPPING, VCD_CLIENT_STATE_EOS, VCD_CLIENT_STATE_INVALID, VCD_CLIENT_STATE_MAX, VCD_CLIENT_STATE_32BIT = 0x7FFFFFFF }; #define CLIENT_STATE_EVENT_NUMBER(ppf) \ ((u32 *) (&(((struct vcd_clnt_state_table*)0)->ev_hdlr.ppf)) - \ (u32 *) (&(((struct vcd_clnt_state_table*)0)->ev_hdlr.pf_close)) + 1) struct vcd_clnt_state_table { struct { u32(*pf_close) (struct vcd_clnt_ctxt *cctxt); u32(*pf_encode_start) (struct vcd_clnt_ctxt *cctxt); u32(*pf_encode_frame) (struct vcd_clnt_ctxt *cctxt, struct vcd_frame_data *input_frame); u32(*pf_decode_start) (struct vcd_clnt_ctxt *cctxt, struct vcd_sequence_hdr *seq_hdr); u32(*pf_decode_frame) (struct vcd_clnt_ctxt *cctxt, struct vcd_frame_data *input_frame); u32(*pf_pause) (struct vcd_clnt_ctxt *cctxt); u32(*pf_resume) (struct vcd_clnt_ctxt *cctxt); u32(*pf_flush) (struct vcd_clnt_ctxt *cctxt, u32 mode); u32(*pf_stop) (struct vcd_clnt_ctxt *cctxt); u32(*pf_set_property) (struct vcd_clnt_ctxt *cctxt, struct vcd_property_hdr *prop_hdr, void *prop); u32(*pf_get_property) (struct vcd_clnt_ctxt *cctxt, struct vcd_property_hdr *prop_hdr, void *prop); u32(*pf_set_buffer_requirements) (struct vcd_clnt_ctxt *cctxt, enum vcd_buffer_type vcd_buffer_type, struct vcd_buffer_requirement *buffer_req); u32(*pf_get_buffer_requirements) (struct vcd_clnt_ctxt *cctxt, enum vcd_buffer_type vcd_buffer_type, struct vcd_buffer_requirement *buffer_req); u32(*pf_set_buffer) (struct vcd_clnt_ctxt *cctxt, enum vcd_buffer_type vcd_buffer_type, void *buffer, size_t buf_size); u32(*pf_allocate_buffer) (struct vcd_clnt_ctxt *cctxt, enum vcd_buffer_type vcd_buffer_type, size_t sz, void **virt_addr, phys_addr_t *phys_addr); u32(*pf_free_buffer) (struct vcd_clnt_ctxt *cctxt, enum vcd_buffer_type vcd_buffer_type, void *buf); u32(*pf_fill_output_buffer) (struct vcd_clnt_ctxt *cctxt, struct vcd_frame_data *buffer); void (*pf_clnt_cb) (struct vcd_clnt_ctxt *cctxt, u32 event, u32 status, void *payload, u32 size, u32 *ddl_handle, void *const client_data); } ev_hdlr; void (*pf_entry) (struct vcd_clnt_ctxt *cctxt, s32 state_event_type); void (*pf_exit) (struct vcd_clnt_ctxt *cctxt, s32 state_event_type); }; struct vcd_clnt_state_ctxt { const struct vcd_clnt_state_table *state_table; enum vcd_clnt_state_enum state; }; extern void vcd_do_client_state_transition(struct vcd_clnt_ctxt *cctxt, enum vcd_clnt_state_enum to_state, u32 ev_code); extern const struct vcd_clnt_state_table *vcd_get_client_state_table( enum vcd_clnt_state_enum state); #endif
amitnarkhede/MadKernel_cooper
drivers/misc/video_core/720p/vcd/vcd_client_sm.h
C
gpl-2.0
4,593
#ifndef __ASM_MACH_MIPS_IRQ_H #define __ASM_MACH_MIPS_IRQ_H #define NR_IRQS 256 #include_next <irq.h> #endif /* __ASM_MACH_MIPS_IRQ_H */
AiJiaZone/linux-4.0
virt/arch/mips/include/asm/mach-malta/irq.h
C
gpl-2.0
141
#ifndef _system_wait_h #define _system_wait_h /* Unix SMB/CIFS implementation. waitpid system include wrappers Copyright (C) Andrew Tridgell 2004 ** NOTE! The following LGPL license applies to the replace ** library. This does NOT imply that all of Samba is released ** under the LGPL 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 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_SYS_WAIT_H #include <sys/wait.h> #endif #include <signal.h> #ifndef SIGCLD #define SIGCLD SIGCHLD #endif #ifndef SIGNAL_CAST #define SIGNAL_CAST (RETSIGTYPE (*)(int)) #endif #ifdef HAVE_SETJMP_H #include <setjmp.h> #endif #ifndef SA_RESETHAND #define SA_RESETHAND SA_ONESHOT #endif #if !defined(HAVE_SIG_ATOMIC_T_TYPE) typedef int sig_atomic_t; #endif #if !defined(HAVE_WAITPID) && defined(HAVE_WAIT4) int rep_waitpid(pid_t pid,int *status,int options) #endif #endif
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/third_party/talloc/libreplace/system/wait.h
C
mit
1,471
## Generating Zsh Completion for your cobra.Command Cobra supports native Zsh completion generated from the root `cobra.Command`. The generated completion script should be put somewhere in your `$fpath` named `_<YOUR COMMAND>`. ### What's Supported * Completion for all non-hidden subcommands using their `.Short` description. * Completion for all non-hidden flags using the following rules: * Filename completion works by marking the flag with `cmd.MarkFlagFilename...` family of commands. * The requirement for argument to the flag is decided by the `.NoOptDefVal` flag value - if it's empty then completion will expect an argument. * Flags of one of the various `*Array` and `*Slice` types supports multiple specifications (with or without argument depending on the specific type). * Completion of positional arguments using the following rules: * Argument position for all options below starts at `1`. If argument position `0` is requested it will raise an error. * Use `command.MarkZshCompPositionalArgumentFile` to complete filenames. Glob patterns (e.g. `"*.log"`) are optional - if not specified it will offer to complete all file types. * Use `command.MarkZshCompPositionalArgumentWords` to offer specific words for completion. At least one word is required. * It's possible to specify completion for some arguments and leave some unspecified (e.g. offer words for second argument but nothing for first argument). This will cause no completion for first argument but words completion for second argument. * If no argument completion was specified for 1st argument (but optionally was specified for 2nd) and the command has `ValidArgs` it will be used as completion options for 1st argument. * Argument completions only offered for commands with no subcommands. ### What's not yet Supported * Custom completion scripts are not supported yet (We should probably create zsh specific one, doesn't make sense to re-use the bash one as the functions will be different). * Whatever other feature you're looking for and doesn't exist :)
cilium-team/cilium
vendor/github.com/spf13/cobra/zsh_completions.md
Markdown
apache-2.0
2,113
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright 2007 University of Washington * Copyright (C) 1999, 2000 Kunihiro Ishiguro, Toshiaki Takada * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: Tom Henderson ([email protected]) * * Kunihiro Ishigura, Toshiaki Takada (GNU Zebra) are attributed authors * of the quagga 0.99.7/src/ospfd/ospf_spf.c code which was ported here */ #include "ns3/test.h" #include "ns3/global-route-manager-impl.h" #include "ns3/candidate-queue.h" #include "ns3/simulator.h" #include <cstdlib> // for rand() using namespace ns3; class GlobalRouteManagerImplTestCase : public TestCase { public: GlobalRouteManagerImplTestCase(); virtual void DoRun (void); }; GlobalRouteManagerImplTestCase::GlobalRouteManagerImplTestCase() : TestCase ("GlobalRouteManagerImplTestCase") { } void GlobalRouteManagerImplTestCase::DoRun (void) { CandidateQueue candidate; for (int i = 0; i < 100; ++i) { SPFVertex *v = new SPFVertex; v->SetDistanceFromRoot (std::rand () % 100); candidate.Push (v); } for (int i = 0; i < 100; ++i) { SPFVertex *v = candidate.Pop (); delete v; v = 0; } // Build fake link state database; four routers (0-3), 3 point-to-point // links // // n0 // \ link 0 // \ link 2 // n2 -------------------------n3 // / // / link 1 // n1 // // link0: 10.1.1.1/30, 10.1.1.2/30 // link1: 10.1.2.1/30, 10.1.2.2/30 // link2: 10.1.3.1/30, 10.1.3.2/30 // // Router 0 GlobalRoutingLinkRecord* lr0 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::PointToPoint, "0.0.0.2", // router ID 0.0.0.2 "10.1.1.1", // local ID 1); // metric GlobalRoutingLinkRecord* lr1 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::StubNetwork, "10.1.1.1", "255.255.255.252", 1); GlobalRoutingLSA* lsa0 = new GlobalRoutingLSA (); lsa0->SetLSType (GlobalRoutingLSA::RouterLSA); lsa0->SetLinkStateId ("0.0.0.0"); lsa0->SetAdvertisingRouter ("0.0.0.0"); lsa0->AddLinkRecord (lr0); lsa0->AddLinkRecord (lr1); // Router 1 GlobalRoutingLinkRecord* lr2 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::PointToPoint, "0.0.0.2", "10.1.2.1", 1); GlobalRoutingLinkRecord* lr3 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::StubNetwork, "10.1.2.1", "255.255.255.252", 1); GlobalRoutingLSA* lsa1 = new GlobalRoutingLSA (); lsa1->SetLSType (GlobalRoutingLSA::RouterLSA); lsa1->SetLinkStateId ("0.0.0.1"); lsa1->SetAdvertisingRouter ("0.0.0.1"); lsa1->AddLinkRecord (lr2); lsa1->AddLinkRecord (lr3); // Router 2 GlobalRoutingLinkRecord* lr4 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::PointToPoint, "0.0.0.0", "10.1.1.2", 1); GlobalRoutingLinkRecord* lr5 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::StubNetwork, "10.1.1.2", "255.255.255.252", 1); GlobalRoutingLinkRecord* lr6 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::PointToPoint, "0.0.0.1", "10.1.2.2", 1); GlobalRoutingLinkRecord* lr7 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::StubNetwork, "10.1.2.2", "255.255.255.252", 1); GlobalRoutingLinkRecord* lr8 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::PointToPoint, "0.0.0.3", "10.1.3.2", 1); GlobalRoutingLinkRecord* lr9 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::StubNetwork, "10.1.3.2", "255.255.255.252", 1); GlobalRoutingLSA* lsa2 = new GlobalRoutingLSA (); lsa2->SetLSType (GlobalRoutingLSA::RouterLSA); lsa2->SetLinkStateId ("0.0.0.2"); lsa2->SetAdvertisingRouter ("0.0.0.2"); lsa2->AddLinkRecord (lr4); lsa2->AddLinkRecord (lr5); lsa2->AddLinkRecord (lr6); lsa2->AddLinkRecord (lr7); lsa2->AddLinkRecord (lr8); lsa2->AddLinkRecord (lr9); // Router 3 GlobalRoutingLinkRecord* lr10 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::PointToPoint, "0.0.0.2", "10.1.2.1", 1); GlobalRoutingLinkRecord* lr11 = new GlobalRoutingLinkRecord ( GlobalRoutingLinkRecord::StubNetwork, "10.1.2.1", "255.255.255.252", 1); GlobalRoutingLSA* lsa3 = new GlobalRoutingLSA (); lsa3->SetLSType (GlobalRoutingLSA::RouterLSA); lsa3->SetLinkStateId ("0.0.0.3"); lsa3->SetAdvertisingRouter ("0.0.0.3"); lsa3->AddLinkRecord (lr10); lsa3->AddLinkRecord (lr11); // Test the database GlobalRouteManagerLSDB* srmlsdb = new GlobalRouteManagerLSDB (); srmlsdb->Insert (lsa0->GetLinkStateId (), lsa0); srmlsdb->Insert (lsa1->GetLinkStateId (), lsa1); srmlsdb->Insert (lsa2->GetLinkStateId (), lsa2); srmlsdb->Insert (lsa3->GetLinkStateId (), lsa3); NS_ASSERT (lsa2 == srmlsdb->GetLSA (lsa2->GetLinkStateId ())); // next, calculate routes based on the manually created LSDB GlobalRouteManagerImpl* srm = new GlobalRouteManagerImpl (); srm->DebugUseLsdb (srmlsdb); // manually add in an LSDB // Note-- this will succeed without any nodes in the topology // because the NodeList is empty srm->DebugSPFCalculate (lsa0->GetLinkStateId ()); // node n0 Simulator::Run (); /// \todo here we should do some verification of the routes built Simulator::Destroy (); // This delete clears the srm, which deletes the LSDB, which clears // all of the LSAs, which each destroys the attached LinkRecords. delete srm; /// \todo Testing // No testing has actually been done other than making sure that this code // does not crash } static class GlobalRouteManagerImplTestSuite : public TestSuite { public: GlobalRouteManagerImplTestSuite() : TestSuite ("global-route-manager-impl", UNIT) { AddTestCase (new GlobalRouteManagerImplTestCase (), TestCase::QUICK); } } g_globalRoutingManagerImplTestSuite;
jaredivey/ns-3-sdn
src/internet/test/global-route-manager-impl-test-suite.cc
C++
gpl-2.0
6,634
// { dg-do compile { target c++11 } } enum class Col { red, yellow, green }; int x = Col::red; // { dg-error "cannot convert" } Col y = Col::red; void f() { if (y) { } // { dg-error "could not convert" } } enum direction { left='l', right='r' }; void g() { // OK direction d; // OK d = left; // OK d = direction::right; } enum class altitude { high='h', low='l' }; void h() { altitude a; a = high; // { dg-error "not declared in this scope" } a = altitude::low; }
selmentdev/selment-toolchain
source/gcc-latest/gcc/testsuite/g++.dg/cpp0x/scoped_enum_examples.C
C++
gpl-3.0
661
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.language.constant; import org.apache.camel.Expression; import org.apache.camel.IsSingleton; import org.apache.camel.Predicate; import org.apache.camel.builder.ExpressionBuilder; import org.apache.camel.spi.Language; import org.apache.camel.util.ExpressionToPredicateAdapter; /** * A language for constant expressions. */ public class ConstantLanguage implements Language, IsSingleton { public static Expression constant(Object value) { return ExpressionBuilder.constantExpression(value); } public Predicate createPredicate(String expression) { return ExpressionToPredicateAdapter.toPredicate(createExpression(expression)); } public Expression createExpression(String expression) { return ConstantLanguage.constant(expression); } public boolean isSingleton() { return true; } }
coderczp/camel
camel-core/src/main/java/org/apache/camel/language/constant/ConstantLanguage.java
Java
apache-2.0
1,686
<!DOCTYPE html> <html> <head> <title>Leaflet debug page</title> <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css" /> <script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet-src.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../screen.css" /> <link rel="stylesheet" href="../../dist/MarkerCluster.css" /> <link rel="stylesheet" href="../../dist/MarkerCluster.Default.css" /> <script src="../../src/DistanceGrid.js"></script> <script src="../../src/MarkerCluster.js"></script> <script src="../../src/MarkerClusterGroup.js"></script> <script src="../../src/MarkerCluster.QuickHull.js"></script> <script src="../../src/MarkerCluster.Spiderfier.js"></script> </head> <body> <div id="map"></div> <button id="doit">open popup</button><br/> <span>Bug <a href="https://github.com/danzel/Leaflet.markercluster/issues/286">#286 (from @Grsmto)</a>. Click the button. The cluster should spiderfy and show the popup, old behaviour did nothing.</span><br/> <span id="time"></span> <script type="text/javascript"> var tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }), latlng = new L.LatLng(50.5, 30.51); var map = new L.Map('map', {center: latlng, zoom: 18, layers: [tiles]}); var markers = new L.MarkerClusterGroup(); var markersList = []; for (var i = 0; i < 3; i++) { var m = new L.Marker(latlng); m.bindPopup('asdasd' + i); markersList.push(m); markers.addLayer(m); } map.addLayer(markers); L.DomUtil.get('doit').onclick = function () { //debugger; markers.zoomToShowLayer(markersList[0], function () { markersList[0].openPopup(); }); }; </script> </body> </html>
angrycactus/dkan
webroot/profiles/dkan/libraries/leaflet_markercluster/example/old-bugs/zoomtoshowlayer-doesnt-zoom-if-centered-on.html
HTML
gpl-2.0
1,857
/* * Copyright (C) 2003, 2004, 2005 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @class WebView; @class WebDataSource; @class NSURLAuthenticationChallenge; @class NSURLResponse; @class NSURLRequest; /*! @category WebResourceLoadDelegate @discussion Implementors of this protocol will receive messages indicating that a resource is about to be loaded, data has been received for a resource, an error has been received for a resource, and completion of a resource load. Implementors are also given the opportunity to mutate requests before they are sent. The various progress methods of this protocol all receive an identifier as the parameter. This identifier can be used to track messages associated with a single resource. For example, a single resource may generate multiple resource:willSendRequest:redirectResponse:fromDataSource: messages as it's URL is redirected. */ @interface NSObject (WebResourceLoadDelegate) /*! @method webView:identifierForInitialRequest:fromDataSource: @param webView The WebView sending the message. @param request The request about to be sent. @param dataSource The datasource that initiated the load. @discussion An implementor of WebResourceLoadDelegate should provide an identifier that can be used to track the load of a single resource. This identifier will be passed as the first argument for all of the other WebResourceLoadDelegate methods. The identifier is useful to track changes to a resources request, which will be provided by one or more calls to resource:willSendRequest:redirectResponse:fromDataSource:. @result An identifier that will be passed back to the implementor for each callback. The identifier will be retained. */ - (id)webView:(WebView *)sender identifierForInitialRequest:(NSURLRequest *)request fromDataSource:(WebDataSource *)dataSource; /*! @method webView:resource:willSendRequest:redirectResponse:fromDataSource: @discussion This message is sent before a load is initiated. The request may be modified as necessary by the receiver. @param webView The WebView sending the message. @param identifier An identifier that can be used to track the progress of a resource load across multiple call backs. @param request The request about to be sent. @param redirectResponse If the request is being made in response to a redirect we received, the response that conveyed that redirect. @param dataSource The dataSource that initiated the load. @result Returns the request, which may be mutated by the implementor, although typically will be request. */ - (NSURLRequest *)webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)dataSource; /*! @method webView:resource:didReceiveAuthenticationChallenge:fromDataSource: @abstract Start authentication for the resource, providing a challenge @discussion Call useCredential::, continueWithoutCredential or cancel on the challenge when done. @param challenge The NSURLAuthenticationChallenge to start authentication for @discussion If you do not implement this delegate method, WebKit will handle authentication automatically by prompting with a sheet on the window that the WebView is associated with. */ - (void)webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource; /*! @method webView:resource:didCancelAuthenticationChallenge:fromDataSource: @abstract Cancel authentication for a given request @param challenge The NSURLAuthenticationChallenge for which to cancel authentication */ - (void)webView:(WebView *)sender resource:(id)identifier didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource; /*! @method webView:resource:didReceiveResponse:fromDataSource: @abstract This message is sent after a response has been received for this load. @param webView The WebView sending the message. @param identifier An identifier that can be used to track the progress of a resource load across multiple call backs. @param response The response for the request. @param dataSource The dataSource that initiated the load. @discussion In some rare cases, multiple responses may be received for a single load. This occurs with multipart/x-mixed-replace, or "server push". In this case, the client should assume that each new response resets progress so far for the resource back to 0, and should check the new response for the expected content length. */ - (void)webView:(WebView *)sender resource:(id)identifier didReceiveResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)dataSource; /*! @method webView:resource:didReceiveContentLength:fromDataSource: @discussion Multiple of these messages may be sent as data arrives. @param webView The WebView sending the message. @param identifier An identifier that can be used to track the progress of a resource load across multiple call backs. @param length The amount of new data received. This is not the total amount, just the new amount received. @param dataSource The dataSource that initiated the load. */ - (void)webView:(WebView *)sender resource:(id)identifier didReceiveContentLength:(NSInteger)length fromDataSource:(WebDataSource *)dataSource; /*! @method webView:resource:didFinishLoadingFromDataSource: @discussion This message is sent after a load has successfully completed. @param webView The WebView sending the message. @param identifier An identifier that can be used to track the progress of a resource load across multiple call backs. @param dataSource The dataSource that initiated the load. */ - (void)webView:(WebView *)sender resource:(id)identifier didFinishLoadingFromDataSource:(WebDataSource *)dataSource; /*! @method webView:resource:didFailLoadingWithError:fromDataSource: @discussion This message is sent after a load has failed to load due to an error. @param webView The WebView sending the message. @param identifier An identifier that can be used to track the progress of a resource load across multiple call backs. @param error The error associated with this load. @param dataSource The dataSource that initiated the load. */ - (void)webView:(WebView *)sender resource:(id)identifier didFailLoadingWithError:(NSError *)error fromDataSource:(WebDataSource *)dataSource; /*! @method webView:plugInFailedWithError:dataSource: @discussion Called when a plug-in is not found, fails to load or is not available for some reason. @param webView The WebView sending the message. @param error The plug-in error. In the userInfo dictionary of the error, the object for the NSErrorFailingURLKey key is a URL string of the SRC attribute, the object for the WebKitErrorPlugInNameKey key is a string of the plug-in's name, the object for the WebKitErrorPlugInPageURLStringKey key is a URL string of the PLUGINSPAGE attribute and the object for the WebKitErrorMIMETypeKey key is a string of the TYPE attribute. Some, none or all of the mentioned attributes can be present in the userInfo. The error returns nil for userInfo when none are present. @param dataSource The dataSource that contains the plug-in. */ - (void)webView:(WebView *)sender plugInFailedWithError:(NSError *)error dataSource:(WebDataSource *)dataSource; @end
nawawi/wkhtmltopdf
webkit/Source/WebKit/mac/WebView/WebResourceLoadDelegate.h
C
lgpl-3.0
9,166
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Collections.Tests { /// <summary> /// Contains tests that ensure the correctness of any class that implements the generic /// IDictionary interface /// </summary> public abstract partial class IDictionary_Generic_Tests<TKey, TValue> : ICollection_Generic_Tests<KeyValuePair<TKey, TValue>> { [Theory] [MemberData(nameof(ValidCollectionSizes))] public void KeyValuePair_Deconstruct(int size) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(size); Assert.All(dictionary, (entry) => { TKey key; TValue value; entry.Deconstruct(out key, out value); Assert.Equal(entry.Key, key); Assert.Equal(entry.Value, value); key = default(TKey); value = default(TValue); (key, value) = entry; Assert.Equal(entry.Key, key); Assert.Equal(entry.Value, value); }); } } }
dotnet-bot/corefx
src/Common/tests/System/Collections/IDictionary.Generic.Tests.netcoreapp.cs
C#
mit
1,303
<?php namespace Drupal\Tests\block_content\Functional; use Drupal\block_content\Entity\BlockContent; use Drupal\block_content\Entity\BlockContentType; use Drupal\Component\Utility\Unicode; use Drupal\content_translation\Tests\ContentTranslationUITestBase; /** * Tests the block content translation UI. * * @group block_content */ class BlockContentTranslationUITest extends ContentTranslationUITestBase { /** * Modules to enable. * * @var array */ public static $modules = [ 'language', 'content_translation', 'block', 'field_ui', 'block_content' ]; /** * {@inheritdoc} */ protected $defaultCacheContexts = [ 'languages:language_interface', 'session', 'theme', 'url.path', 'url.query_args', 'user.permissions', 'user.roles:authenticated', ]; /** * {@inheritdoc} */ protected function setUp() { $this->entityTypeId = 'block_content'; $this->bundle = 'basic'; $this->testLanguageSelector = FALSE; parent::setUp(); $this->drupalPlaceBlock('page_title_block'); } /** * {@inheritdoc} */ protected function setupBundle() { // Create the basic bundle since it is provided by standard. $bundle = BlockContentType::create([ 'id' => $this->bundle, 'label' => $this->bundle, 'revision' => FALSE ]); $bundle->save(); } /** * {@inheritdoc} */ public function getTranslatorPermissions() { return array_merge(parent::getTranslatorPermissions(), [ 'translate any entity', 'access administration pages', 'administer blocks', 'administer block_content fields' ]); } /** * Creates a custom block. * * @param bool|string $title * (optional) Title of block. When no value is given uses a random name. * Defaults to FALSE. * @param bool|string $bundle * (optional) Bundle name. When no value is given, defaults to * $this->bundle. Defaults to FALSE. * * @return \Drupal\block_content\Entity\BlockContent * Created custom block. */ protected function createBlockContent($title = FALSE, $bundle = FALSE) { $title = $title ?: $this->randomMachineName(); $bundle = $bundle ?: $this->bundle; $block_content = BlockContent::create([ 'info' => $title, 'type' => $bundle, 'langcode' => 'en' ]); $block_content->save(); return $block_content; } /** * {@inheritdoc} */ protected function getNewEntityValues($langcode) { return ['info' => Unicode::strtolower($this->randomMachineName())] + parent::getNewEntityValues($langcode); } /** * Returns an edit array containing the values to be posted. */ protected function getEditValues($values, $langcode, $new = FALSE) { $edit = parent::getEditValues($values, $langcode, $new); foreach ($edit as $property => $value) { if ($property == 'info') { $edit['info[0][value]'] = $value; unset($edit[$property]); } } return $edit; } /** * {@inheritdoc} */ protected function doTestBasicTranslation() { parent::doTestBasicTranslation(); // Ensure that a block translation can be created using the same description // as in the original language. $default_langcode = $this->langcodes[0]; $values = $this->getNewEntityValues($default_langcode); $storage = \Drupal::entityManager()->getStorage($this->entityTypeId); /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */ $entity = $storage->create(['type' => 'basic'] + $values); $entity->save(); $entity->addTranslation('it', $values); try { $message = 'Blocks can have translations with the same "info" value.'; $entity->save(); $this->pass($message); } catch (\Exception $e) { $this->fail($message); } // Check that the translate operation link is shown. $this->drupalGet('admin/structure/block/block-content'); $this->assertLinkByHref('block/' . $entity->id() . '/translations'); } /** * Test that no metadata is stored for a disabled bundle. */ public function testDisabledBundle() { // Create a bundle that does not have translation enabled. $disabled_bundle = $this->randomMachineName(); $bundle = BlockContentType::create([ 'id' => $disabled_bundle, 'label' => $disabled_bundle, 'revision' => FALSE ]); $bundle->save(); // Create a block content for each bundle. $enabled_block_content = $this->createBlockContent(); $disabled_block_content = $this->createBlockContent(FALSE, $bundle->id()); // Make sure that only a single row was inserted into the block table. $rows = db_query('SELECT * FROM {block_content_field_data} WHERE id = :id', [':id' => $enabled_block_content->id()])->fetchAll(); $this->assertEqual(1, count($rows)); } /** * {@inheritdoc} */ protected function doTestTranslationEdit() { $storage = $this->container->get('entity_type.manager') ->getStorage($this->entityTypeId); $storage->resetCache([$this->entityId]); $entity = $storage->load($this->entityId); $languages = $this->container->get('language_manager')->getLanguages(); foreach ($this->langcodes as $langcode) { // We only want to test the title for non-english translations. if ($langcode != 'en') { $options = ['language' => $languages[$langcode]]; $url = $entity->urlInfo('edit-form', $options); $this->drupalGet($url); $title = t('<em>Edit @type</em> @title [%language translation]', [ '@type' => $entity->bundle(), '@title' => $entity->getTranslation($langcode)->label(), '%language' => $languages[$langcode]->getName(), ]); $this->assertRaw($title); } } } }
jigish-addweb/d8commerce
web/core/modules/block_content/tests/src/Functional/BlockContentTranslationUITest.php
PHP
gpl-2.0
5,817
/* * smc911x.c * This is a driver for SMSC's LAN911{5,6,7,8} single-chip Ethernet devices. * * Copyright (C) 2005 Sensoria Corp * Derived from the unified SMC91x driver by Nicolas Pitre * and the smsc911x.c reference driver by SMSC * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Arguments: * watchdog = TX watchdog timeout * tx_fifo_kb = Size of TX FIFO in KB * * History: * 04/16/05 Dustin McIntire Initial version */ static const char version[] = "smc911x.c: v1.0 04-16-2005 by Dustin McIntire <[email protected]>\n"; /* Debugging options */ #define ENABLE_SMC_DEBUG_RX 0 #define ENABLE_SMC_DEBUG_TX 0 #define ENABLE_SMC_DEBUG_DMA 0 #define ENABLE_SMC_DEBUG_PKTS 0 #define ENABLE_SMC_DEBUG_MISC 0 #define ENABLE_SMC_DEBUG_FUNC 0 #define SMC_DEBUG_RX ((ENABLE_SMC_DEBUG_RX ? 1 : 0) << 0) #define SMC_DEBUG_TX ((ENABLE_SMC_DEBUG_TX ? 1 : 0) << 1) #define SMC_DEBUG_DMA ((ENABLE_SMC_DEBUG_DMA ? 1 : 0) << 2) #define SMC_DEBUG_PKTS ((ENABLE_SMC_DEBUG_PKTS ? 1 : 0) << 3) #define SMC_DEBUG_MISC ((ENABLE_SMC_DEBUG_MISC ? 1 : 0) << 4) #define SMC_DEBUG_FUNC ((ENABLE_SMC_DEBUG_FUNC ? 1 : 0) << 5) #ifndef SMC_DEBUG #define SMC_DEBUG ( SMC_DEBUG_RX | \ SMC_DEBUG_TX | \ SMC_DEBUG_DMA | \ SMC_DEBUG_PKTS | \ SMC_DEBUG_MISC | \ SMC_DEBUG_FUNC \ ) #endif #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/errno.h> #include <linux/ioport.h> #include <linux/crc32.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/spinlock.h> #include <linux/ethtool.h> #include <linux/mii.h> #include <linux/workqueue.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <asm/io.h> #include "smc911x.h" /* * Transmit timeout, default 5 seconds. */ static int watchdog = 5000; module_param(watchdog, int, 0400); MODULE_PARM_DESC(watchdog, "transmit timeout in milliseconds"); static int tx_fifo_kb=8; module_param(tx_fifo_kb, int, 0400); MODULE_PARM_DESC(tx_fifo_kb,"transmit FIFO size in KB (1<x<15)(default=8)"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:smc911x"); /* * The internal workings of the driver. If you are changing anything * here with the SMC stuff, you should have the datasheet and know * what you are doing. */ #define CARDNAME "smc911x" /* * Use power-down feature of the chip */ #define POWER_DOWN 1 #if SMC_DEBUG > 0 #define DBG(n, args...) \ do { \ if (SMC_DEBUG & (n)) \ printk(args); \ } while (0) #define PRINTK(args...) printk(args) #else #define DBG(n, args...) do { } while (0) #define PRINTK(args...) printk(KERN_DEBUG args) #endif #if SMC_DEBUG_PKTS > 0 static void PRINT_PKT(u_char *buf, int length) { int i; int remainder; int lines; lines = length / 16; remainder = length % 16; for (i = 0; i < lines ; i ++) { int cur; for (cur = 0; cur < 8; cur++) { u_char a, b; a = *buf++; b = *buf++; printk("%02x%02x ", a, b); } printk("\n"); } for (i = 0; i < remainder/2 ; i++) { u_char a, b; a = *buf++; b = *buf++; printk("%02x%02x ", a, b); } printk("\n"); } #else #define PRINT_PKT(x...) do { } while (0) #endif /* this enables an interrupt in the interrupt mask register */ #define SMC_ENABLE_INT(lp, x) do { \ unsigned int __mask; \ __mask = SMC_GET_INT_EN((lp)); \ __mask |= (x); \ SMC_SET_INT_EN((lp), __mask); \ } while (0) /* this disables an interrupt from the interrupt mask register */ #define SMC_DISABLE_INT(lp, x) do { \ unsigned int __mask; \ __mask = SMC_GET_INT_EN((lp)); \ __mask &= ~(x); \ SMC_SET_INT_EN((lp), __mask); \ } while (0) /* * this does a soft reset on the device */ static void smc911x_reset(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); unsigned int reg, timeout=0, resets=1, irq_cfg; unsigned long flags; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); /* Take out of PM setting first */ if ((SMC_GET_PMT_CTRL(lp) & PMT_CTRL_READY_) == 0) { /* Write to the bytetest will take out of powerdown */ SMC_SET_BYTE_TEST(lp, 0); timeout=10; do { udelay(10); reg = SMC_GET_PMT_CTRL(lp) & PMT_CTRL_READY_; } while (--timeout && !reg); if (timeout == 0) { PRINTK("%s: smc911x_reset timeout waiting for PM restore\n", dev->name); return; } } /* Disable all interrupts */ spin_lock_irqsave(&lp->lock, flags); SMC_SET_INT_EN(lp, 0); spin_unlock_irqrestore(&lp->lock, flags); while (resets--) { SMC_SET_HW_CFG(lp, HW_CFG_SRST_); timeout=10; do { udelay(10); reg = SMC_GET_HW_CFG(lp); /* If chip indicates reset timeout then try again */ if (reg & HW_CFG_SRST_TO_) { PRINTK("%s: chip reset timeout, retrying...\n", dev->name); resets++; break; } } while (--timeout && (reg & HW_CFG_SRST_)); } if (timeout == 0) { PRINTK("%s: smc911x_reset timeout waiting for reset\n", dev->name); return; } /* make sure EEPROM has finished loading before setting GPIO_CFG */ timeout=1000; while (--timeout && (SMC_GET_E2P_CMD(lp) & E2P_CMD_EPC_BUSY_)) udelay(10); if (timeout == 0){ PRINTK("%s: smc911x_reset timeout waiting for EEPROM busy\n", dev->name); return; } /* Initialize interrupts */ SMC_SET_INT_EN(lp, 0); SMC_ACK_INT(lp, -1); /* Reset the FIFO level and flow control settings */ SMC_SET_HW_CFG(lp, (lp->tx_fifo_kb & 0xF) << 16); //TODO: Figure out what appropriate pause time is SMC_SET_FLOW(lp, FLOW_FCPT_ | FLOW_FCEN_); SMC_SET_AFC_CFG(lp, lp->afc_cfg); /* Set to LED outputs */ SMC_SET_GPIO_CFG(lp, 0x70070000); /* * Deassert IRQ for 1*10us for edge type interrupts * and drive IRQ pin push-pull */ irq_cfg = (1 << 24) | INT_CFG_IRQ_EN_ | INT_CFG_IRQ_TYPE_; #ifdef SMC_DYNAMIC_BUS_CONFIG if (lp->cfg.irq_polarity) irq_cfg |= INT_CFG_IRQ_POL_; #endif SMC_SET_IRQ_CFG(lp, irq_cfg); /* clear anything saved */ if (lp->pending_tx_skb != NULL) { dev_kfree_skb (lp->pending_tx_skb); lp->pending_tx_skb = NULL; dev->stats.tx_errors++; dev->stats.tx_aborted_errors++; } } /* * Enable Interrupts, Receive, and Transmit */ static void smc911x_enable(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); unsigned mask, cfg, cr; unsigned long flags; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); spin_lock_irqsave(&lp->lock, flags); SMC_SET_MAC_ADDR(lp, dev->dev_addr); /* Enable TX */ cfg = SMC_GET_HW_CFG(lp); cfg &= HW_CFG_TX_FIF_SZ_ | 0xFFF; cfg |= HW_CFG_SF_; SMC_SET_HW_CFG(lp, cfg); SMC_SET_FIFO_TDA(lp, 0xFF); /* Update TX stats on every 64 packets received or every 1 sec */ SMC_SET_FIFO_TSL(lp, 64); SMC_SET_GPT_CFG(lp, GPT_CFG_TIMER_EN_ | 10000); SMC_GET_MAC_CR(lp, cr); cr |= MAC_CR_TXEN_ | MAC_CR_HBDIS_; SMC_SET_MAC_CR(lp, cr); SMC_SET_TX_CFG(lp, TX_CFG_TX_ON_); /* Add 2 byte padding to start of packets */ SMC_SET_RX_CFG(lp, (2<<8) & RX_CFG_RXDOFF_); /* Turn on receiver and enable RX */ if (cr & MAC_CR_RXEN_) DBG(SMC_DEBUG_RX, "%s: Receiver already enabled\n", dev->name); SMC_SET_MAC_CR(lp, cr | MAC_CR_RXEN_); /* Interrupt on every received packet */ SMC_SET_FIFO_RSA(lp, 0x01); SMC_SET_FIFO_RSL(lp, 0x00); /* now, enable interrupts */ mask = INT_EN_TDFA_EN_ | INT_EN_TSFL_EN_ | INT_EN_RSFL_EN_ | INT_EN_GPT_INT_EN_ | INT_EN_RXDFH_INT_EN_ | INT_EN_RXE_EN_ | INT_EN_PHY_INT_EN_; if (IS_REV_A(lp->revision)) mask|=INT_EN_RDFL_EN_; else { mask|=INT_EN_RDFO_EN_; } SMC_ENABLE_INT(lp, mask); spin_unlock_irqrestore(&lp->lock, flags); } /* * this puts the device in an inactive state */ static void smc911x_shutdown(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); unsigned cr; unsigned long flags; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", CARDNAME, __func__); /* Disable IRQ's */ SMC_SET_INT_EN(lp, 0); /* Turn of Rx and TX */ spin_lock_irqsave(&lp->lock, flags); SMC_GET_MAC_CR(lp, cr); cr &= ~(MAC_CR_TXEN_ | MAC_CR_RXEN_ | MAC_CR_HBDIS_); SMC_SET_MAC_CR(lp, cr); SMC_SET_TX_CFG(lp, TX_CFG_STOP_TX_); spin_unlock_irqrestore(&lp->lock, flags); } static inline void smc911x_drop_pkt(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); unsigned int fifo_count, timeout, reg; DBG(SMC_DEBUG_FUNC | SMC_DEBUG_RX, "%s: --> %s\n", CARDNAME, __func__); fifo_count = SMC_GET_RX_FIFO_INF(lp) & 0xFFFF; if (fifo_count <= 4) { /* Manually dump the packet data */ while (fifo_count--) SMC_GET_RX_FIFO(lp); } else { /* Fast forward through the bad packet */ SMC_SET_RX_DP_CTRL(lp, RX_DP_CTRL_FFWD_BUSY_); timeout=50; do { udelay(10); reg = SMC_GET_RX_DP_CTRL(lp) & RX_DP_CTRL_FFWD_BUSY_; } while (--timeout && reg); if (timeout == 0) { PRINTK("%s: timeout waiting for RX fast forward\n", dev->name); } } } /* * This is the procedure to handle the receipt of a packet. * It should be called after checking for packet presence in * the RX status FIFO. It must be called with the spin lock * already held. */ static inline void smc911x_rcv(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); unsigned int pkt_len, status; struct sk_buff *skb; unsigned char *data; DBG(SMC_DEBUG_FUNC | SMC_DEBUG_RX, "%s: --> %s\n", dev->name, __func__); status = SMC_GET_RX_STS_FIFO(lp); DBG(SMC_DEBUG_RX, "%s: Rx pkt len %d status 0x%08x\n", dev->name, (status & 0x3fff0000) >> 16, status & 0xc000ffff); pkt_len = (status & RX_STS_PKT_LEN_) >> 16; if (status & RX_STS_ES_) { /* Deal with a bad packet */ dev->stats.rx_errors++; if (status & RX_STS_CRC_ERR_) dev->stats.rx_crc_errors++; else { if (status & RX_STS_LEN_ERR_) dev->stats.rx_length_errors++; if (status & RX_STS_MCAST_) dev->stats.multicast++; } /* Remove the bad packet data from the RX FIFO */ smc911x_drop_pkt(dev); } else { /* Receive a valid packet */ /* Alloc a buffer with extra room for DMA alignment */ skb = netdev_alloc_skb(dev, pkt_len+32); if (unlikely(skb == NULL)) { PRINTK( "%s: Low memory, rcvd packet dropped.\n", dev->name); dev->stats.rx_dropped++; smc911x_drop_pkt(dev); return; } /* Align IP header to 32 bits * Note that the device is configured to add a 2 * byte padding to the packet start, so we really * want to write to the orignal data pointer */ data = skb->data; skb_reserve(skb, 2); skb_put(skb,pkt_len-4); #ifdef SMC_USE_DMA { unsigned int fifo; /* Lower the FIFO threshold if possible */ fifo = SMC_GET_FIFO_INT(lp); if (fifo & 0xFF) fifo--; DBG(SMC_DEBUG_RX, "%s: Setting RX stat FIFO threshold to %d\n", dev->name, fifo & 0xff); SMC_SET_FIFO_INT(lp, fifo); /* Setup RX DMA */ SMC_SET_RX_CFG(lp, RX_CFG_RX_END_ALGN16_ | ((2<<8) & RX_CFG_RXDOFF_)); lp->rxdma_active = 1; lp->current_rx_skb = skb; SMC_PULL_DATA(lp, data, (pkt_len+2+15) & ~15); /* Packet processing deferred to DMA RX interrupt */ } #else SMC_SET_RX_CFG(lp, RX_CFG_RX_END_ALGN4_ | ((2<<8) & RX_CFG_RXDOFF_)); SMC_PULL_DATA(lp, data, pkt_len+2+3); DBG(SMC_DEBUG_PKTS, "%s: Received packet\n", dev->name); PRINT_PKT(data, ((pkt_len - 4) <= 64) ? pkt_len - 4 : 64); skb->protocol = eth_type_trans(skb, dev); netif_rx(skb); dev->stats.rx_packets++; dev->stats.rx_bytes += pkt_len-4; #endif } } /* * This is called to actually send a packet to the chip. */ static void smc911x_hardware_send_pkt(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); struct sk_buff *skb; unsigned int cmdA, cmdB, len; unsigned char *buf; DBG(SMC_DEBUG_FUNC | SMC_DEBUG_TX, "%s: --> %s\n", dev->name, __func__); BUG_ON(lp->pending_tx_skb == NULL); skb = lp->pending_tx_skb; lp->pending_tx_skb = NULL; /* cmdA {25:24] data alignment [20:16] start offset [10:0] buffer length */ /* cmdB {31:16] pkt tag [10:0] length */ #ifdef SMC_USE_DMA /* 16 byte buffer alignment mode */ buf = (char*)((u32)(skb->data) & ~0xF); len = (skb->len + 0xF + ((u32)skb->data & 0xF)) & ~0xF; cmdA = (1<<24) | (((u32)skb->data & 0xF)<<16) | TX_CMD_A_INT_FIRST_SEG_ | TX_CMD_A_INT_LAST_SEG_ | skb->len; #else buf = (char*)((u32)skb->data & ~0x3); len = (skb->len + 3 + ((u32)skb->data & 3)) & ~0x3; cmdA = (((u32)skb->data & 0x3) << 16) | TX_CMD_A_INT_FIRST_SEG_ | TX_CMD_A_INT_LAST_SEG_ | skb->len; #endif /* tag is packet length so we can use this in stats update later */ cmdB = (skb->len << 16) | (skb->len & 0x7FF); DBG(SMC_DEBUG_TX, "%s: TX PKT LENGTH 0x%04x (%d) BUF 0x%p CMDA 0x%08x CMDB 0x%08x\n", dev->name, len, len, buf, cmdA, cmdB); SMC_SET_TX_FIFO(lp, cmdA); SMC_SET_TX_FIFO(lp, cmdB); DBG(SMC_DEBUG_PKTS, "%s: Transmitted packet\n", dev->name); PRINT_PKT(buf, len <= 64 ? len : 64); /* Send pkt via PIO or DMA */ #ifdef SMC_USE_DMA lp->current_tx_skb = skb; SMC_PUSH_DATA(lp, buf, len); /* DMA complete IRQ will free buffer and set jiffies */ #else SMC_PUSH_DATA(lp, buf, len); dev->trans_start = jiffies; dev_kfree_skb_irq(skb); #endif if (!lp->tx_throttle) { netif_wake_queue(dev); } SMC_ENABLE_INT(lp, INT_EN_TDFA_EN_ | INT_EN_TSFL_EN_); } /* * Since I am not sure if I will have enough room in the chip's ram * to store the packet, I call this routine which either sends it * now, or set the card to generates an interrupt when ready * for the packet. */ static int smc911x_hard_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); unsigned int free; unsigned long flags; DBG(SMC_DEBUG_FUNC | SMC_DEBUG_TX, "%s: --> %s\n", dev->name, __func__); spin_lock_irqsave(&lp->lock, flags); BUG_ON(lp->pending_tx_skb != NULL); free = SMC_GET_TX_FIFO_INF(lp) & TX_FIFO_INF_TDFREE_; DBG(SMC_DEBUG_TX, "%s: TX free space %d\n", dev->name, free); /* Turn off the flow when running out of space in FIFO */ if (free <= SMC911X_TX_FIFO_LOW_THRESHOLD) { DBG(SMC_DEBUG_TX, "%s: Disabling data flow due to low FIFO space (%d)\n", dev->name, free); /* Reenable when at least 1 packet of size MTU present */ SMC_SET_FIFO_TDA(lp, (SMC911X_TX_FIFO_LOW_THRESHOLD)/64); lp->tx_throttle = 1; netif_stop_queue(dev); } /* Drop packets when we run out of space in TX FIFO * Account for overhead required for: * * Tx command words 8 bytes * Start offset 15 bytes * End padding 15 bytes */ if (unlikely(free < (skb->len + 8 + 15 + 15))) { printk("%s: No Tx free space %d < %d\n", dev->name, free, skb->len); lp->pending_tx_skb = NULL; dev->stats.tx_errors++; dev->stats.tx_dropped++; spin_unlock_irqrestore(&lp->lock, flags); dev_kfree_skb(skb); return NETDEV_TX_OK; } #ifdef SMC_USE_DMA { /* If the DMA is already running then defer this packet Tx until * the DMA IRQ starts it */ if (lp->txdma_active) { DBG(SMC_DEBUG_TX | SMC_DEBUG_DMA, "%s: Tx DMA running, deferring packet\n", dev->name); lp->pending_tx_skb = skb; netif_stop_queue(dev); spin_unlock_irqrestore(&lp->lock, flags); return NETDEV_TX_OK; } else { DBG(SMC_DEBUG_TX | SMC_DEBUG_DMA, "%s: Activating Tx DMA\n", dev->name); lp->txdma_active = 1; } } #endif lp->pending_tx_skb = skb; smc911x_hardware_send_pkt(dev); spin_unlock_irqrestore(&lp->lock, flags); return NETDEV_TX_OK; } /* * This handles a TX status interrupt, which is only called when: * - a TX error occurred, or * - TX of a packet completed. */ static void smc911x_tx(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); unsigned int tx_status; DBG(SMC_DEBUG_FUNC | SMC_DEBUG_TX, "%s: --> %s\n", dev->name, __func__); /* Collect the TX status */ while (((SMC_GET_TX_FIFO_INF(lp) & TX_FIFO_INF_TSUSED_) >> 16) != 0) { DBG(SMC_DEBUG_TX, "%s: Tx stat FIFO used 0x%04x\n", dev->name, (SMC_GET_TX_FIFO_INF(lp) & TX_FIFO_INF_TSUSED_) >> 16); tx_status = SMC_GET_TX_STS_FIFO(lp); dev->stats.tx_packets++; dev->stats.tx_bytes+=tx_status>>16; DBG(SMC_DEBUG_TX, "%s: Tx FIFO tag 0x%04x status 0x%04x\n", dev->name, (tx_status & 0xffff0000) >> 16, tx_status & 0x0000ffff); /* count Tx errors, but ignore lost carrier errors when in * full-duplex mode */ if ((tx_status & TX_STS_ES_) && !(lp->ctl_rfduplx && !(tx_status & 0x00000306))) { dev->stats.tx_errors++; } if (tx_status & TX_STS_MANY_COLL_) { dev->stats.collisions+=16; dev->stats.tx_aborted_errors++; } else { dev->stats.collisions+=(tx_status & TX_STS_COLL_CNT_) >> 3; } /* carrier error only has meaning for half-duplex communication */ if ((tx_status & (TX_STS_LOC_ | TX_STS_NO_CARR_)) && !lp->ctl_rfduplx) { dev->stats.tx_carrier_errors++; } if (tx_status & TX_STS_LATE_COLL_) { dev->stats.collisions++; dev->stats.tx_aborted_errors++; } } } /*---PHY CONTROL AND CONFIGURATION-----------------------------------------*/ /* * Reads a register from the MII Management serial interface */ static int smc911x_phy_read(struct net_device *dev, int phyaddr, int phyreg) { struct smc911x_local *lp = netdev_priv(dev); unsigned int phydata; SMC_GET_MII(lp, phyreg, phyaddr, phydata); DBG(SMC_DEBUG_MISC, "%s: phyaddr=0x%x, phyreg=0x%02x, phydata=0x%04x\n", __func__, phyaddr, phyreg, phydata); return phydata; } /* * Writes a register to the MII Management serial interface */ static void smc911x_phy_write(struct net_device *dev, int phyaddr, int phyreg, int phydata) { struct smc911x_local *lp = netdev_priv(dev); DBG(SMC_DEBUG_MISC, "%s: phyaddr=0x%x, phyreg=0x%x, phydata=0x%x\n", __func__, phyaddr, phyreg, phydata); SMC_SET_MII(lp, phyreg, phyaddr, phydata); } /* * Finds and reports the PHY address (115 and 117 have external * PHY interface 118 has internal only */ static void smc911x_phy_detect(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); int phyaddr; unsigned int cfg, id1, id2; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); lp->phy_type = 0; /* * Scan all 32 PHY addresses if necessary, starting at * PHY#1 to PHY#31, and then PHY#0 last. */ switch(lp->version) { case CHIP_9115: case CHIP_9117: case CHIP_9215: case CHIP_9217: cfg = SMC_GET_HW_CFG(lp); if (cfg & HW_CFG_EXT_PHY_DET_) { cfg &= ~HW_CFG_PHY_CLK_SEL_; cfg |= HW_CFG_PHY_CLK_SEL_CLK_DIS_; SMC_SET_HW_CFG(lp, cfg); udelay(10); /* Wait for clocks to stop */ cfg |= HW_CFG_EXT_PHY_EN_; SMC_SET_HW_CFG(lp, cfg); udelay(10); /* Wait for clocks to stop */ cfg &= ~HW_CFG_PHY_CLK_SEL_; cfg |= HW_CFG_PHY_CLK_SEL_EXT_PHY_; SMC_SET_HW_CFG(lp, cfg); udelay(10); /* Wait for clocks to stop */ cfg |= HW_CFG_SMI_SEL_; SMC_SET_HW_CFG(lp, cfg); for (phyaddr = 1; phyaddr < 32; ++phyaddr) { /* Read the PHY identifiers */ SMC_GET_PHY_ID1(lp, phyaddr & 31, id1); SMC_GET_PHY_ID2(lp, phyaddr & 31, id2); /* Make sure it is a valid identifier */ if (id1 != 0x0000 && id1 != 0xffff && id1 != 0x8000 && id2 != 0x0000 && id2 != 0xffff && id2 != 0x8000) { /* Save the PHY's address */ lp->mii.phy_id = phyaddr & 31; lp->phy_type = id1 << 16 | id2; break; } } if (phyaddr < 32) /* Found an external PHY */ break; } default: /* Internal media only */ SMC_GET_PHY_ID1(lp, 1, id1); SMC_GET_PHY_ID2(lp, 1, id2); /* Save the PHY's address */ lp->mii.phy_id = 1; lp->phy_type = id1 << 16 | id2; } DBG(SMC_DEBUG_MISC, "%s: phy_id1=0x%x, phy_id2=0x%x phyaddr=0x%d\n", dev->name, id1, id2, lp->mii.phy_id); } /* * Sets the PHY to a configuration as determined by the user. * Called with spin_lock held. */ static int smc911x_phy_fixed(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); int phyaddr = lp->mii.phy_id; int bmcr; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); /* Enter Link Disable state */ SMC_GET_PHY_BMCR(lp, phyaddr, bmcr); bmcr |= BMCR_PDOWN; SMC_SET_PHY_BMCR(lp, phyaddr, bmcr); /* * Set our fixed capabilities * Disable auto-negotiation */ bmcr &= ~BMCR_ANENABLE; if (lp->ctl_rfduplx) bmcr |= BMCR_FULLDPLX; if (lp->ctl_rspeed == 100) bmcr |= BMCR_SPEED100; /* Write our capabilities to the phy control register */ SMC_SET_PHY_BMCR(lp, phyaddr, bmcr); /* Re-Configure the Receive/Phy Control register */ bmcr &= ~BMCR_PDOWN; SMC_SET_PHY_BMCR(lp, phyaddr, bmcr); return 1; } /** * smc911x_phy_reset - reset the phy * @dev: net device * @phy: phy address * * Issue a software reset for the specified PHY and * wait up to 100ms for the reset to complete. We should * not access the PHY for 50ms after issuing the reset. * * The time to wait appears to be dependent on the PHY. * */ static int smc911x_phy_reset(struct net_device *dev, int phy) { struct smc911x_local *lp = netdev_priv(dev); int timeout; unsigned long flags; unsigned int reg; DBG(SMC_DEBUG_FUNC, "%s: --> %s()\n", dev->name, __func__); spin_lock_irqsave(&lp->lock, flags); reg = SMC_GET_PMT_CTRL(lp); reg &= ~0xfffff030; reg |= PMT_CTRL_PHY_RST_; SMC_SET_PMT_CTRL(lp, reg); spin_unlock_irqrestore(&lp->lock, flags); for (timeout = 2; timeout; timeout--) { msleep(50); spin_lock_irqsave(&lp->lock, flags); reg = SMC_GET_PMT_CTRL(lp); spin_unlock_irqrestore(&lp->lock, flags); if (!(reg & PMT_CTRL_PHY_RST_)) { /* extra delay required because the phy may * not be completed with its reset * when PHY_BCR_RESET_ is cleared. 256us * should suffice, but use 500us to be safe */ udelay(500); break; } } return reg & PMT_CTRL_PHY_RST_; } /** * smc911x_phy_powerdown - powerdown phy * @dev: net device * @phy: phy address * * Power down the specified PHY */ static void smc911x_phy_powerdown(struct net_device *dev, int phy) { struct smc911x_local *lp = netdev_priv(dev); unsigned int bmcr; /* Enter Link Disable state */ SMC_GET_PHY_BMCR(lp, phy, bmcr); bmcr |= BMCR_PDOWN; SMC_SET_PHY_BMCR(lp, phy, bmcr); } /** * smc911x_phy_check_media - check the media status and adjust BMCR * @dev: net device * @init: set true for initialisation * * Select duplex mode depending on negotiation state. This * also updates our carrier state. */ static void smc911x_phy_check_media(struct net_device *dev, int init) { struct smc911x_local *lp = netdev_priv(dev); int phyaddr = lp->mii.phy_id; unsigned int bmcr, cr; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); if (mii_check_media(&lp->mii, netif_msg_link(lp), init)) { /* duplex state has changed */ SMC_GET_PHY_BMCR(lp, phyaddr, bmcr); SMC_GET_MAC_CR(lp, cr); if (lp->mii.full_duplex) { DBG(SMC_DEBUG_MISC, "%s: Configuring for full-duplex mode\n", dev->name); bmcr |= BMCR_FULLDPLX; cr |= MAC_CR_RCVOWN_; } else { DBG(SMC_DEBUG_MISC, "%s: Configuring for half-duplex mode\n", dev->name); bmcr &= ~BMCR_FULLDPLX; cr &= ~MAC_CR_RCVOWN_; } SMC_SET_PHY_BMCR(lp, phyaddr, bmcr); SMC_SET_MAC_CR(lp, cr); } } /* * Configures the specified PHY through the MII management interface * using Autonegotiation. * Calls smc911x_phy_fixed() if the user has requested a certain config. * If RPC ANEG bit is set, the media selection is dependent purely on * the selection by the MII (either in the MII BMCR reg or the result * of autonegotiation.) If the RPC ANEG bit is cleared, the selection * is controlled by the RPC SPEED and RPC DPLX bits. */ static void smc911x_phy_configure(struct work_struct *work) { struct smc911x_local *lp = container_of(work, struct smc911x_local, phy_configure); struct net_device *dev = lp->netdev; int phyaddr = lp->mii.phy_id; int my_phy_caps; /* My PHY capabilities */ int my_ad_caps; /* My Advertised capabilities */ int status; unsigned long flags; DBG(SMC_DEBUG_FUNC, "%s: --> %s()\n", dev->name, __func__); /* * We should not be called if phy_type is zero. */ if (lp->phy_type == 0) return; if (smc911x_phy_reset(dev, phyaddr)) { printk("%s: PHY reset timed out\n", dev->name); return; } spin_lock_irqsave(&lp->lock, flags); /* * Enable PHY Interrupts (for register 18) * Interrupts listed here are enabled */ SMC_SET_PHY_INT_MASK(lp, phyaddr, PHY_INT_MASK_ENERGY_ON_ | PHY_INT_MASK_ANEG_COMP_ | PHY_INT_MASK_REMOTE_FAULT_ | PHY_INT_MASK_LINK_DOWN_); /* If the user requested no auto neg, then go set his request */ if (lp->mii.force_media) { smc911x_phy_fixed(dev); goto smc911x_phy_configure_exit; } /* Copy our capabilities from MII_BMSR to MII_ADVERTISE */ SMC_GET_PHY_BMSR(lp, phyaddr, my_phy_caps); if (!(my_phy_caps & BMSR_ANEGCAPABLE)) { printk(KERN_INFO "Auto negotiation NOT supported\n"); smc911x_phy_fixed(dev); goto smc911x_phy_configure_exit; } /* CSMA capable w/ both pauses */ my_ad_caps = ADVERTISE_CSMA | ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM; if (my_phy_caps & BMSR_100BASE4) my_ad_caps |= ADVERTISE_100BASE4; if (my_phy_caps & BMSR_100FULL) my_ad_caps |= ADVERTISE_100FULL; if (my_phy_caps & BMSR_100HALF) my_ad_caps |= ADVERTISE_100HALF; if (my_phy_caps & BMSR_10FULL) my_ad_caps |= ADVERTISE_10FULL; if (my_phy_caps & BMSR_10HALF) my_ad_caps |= ADVERTISE_10HALF; /* Disable capabilities not selected by our user */ if (lp->ctl_rspeed != 100) my_ad_caps &= ~(ADVERTISE_100BASE4|ADVERTISE_100FULL|ADVERTISE_100HALF); if (!lp->ctl_rfduplx) my_ad_caps &= ~(ADVERTISE_100FULL|ADVERTISE_10FULL); /* Update our Auto-Neg Advertisement Register */ SMC_SET_PHY_MII_ADV(lp, phyaddr, my_ad_caps); lp->mii.advertising = my_ad_caps; /* * Read the register back. Without this, it appears that when * auto-negotiation is restarted, sometimes it isn't ready and * the link does not come up. */ udelay(10); SMC_GET_PHY_MII_ADV(lp, phyaddr, status); DBG(SMC_DEBUG_MISC, "%s: phy caps=0x%04x\n", dev->name, my_phy_caps); DBG(SMC_DEBUG_MISC, "%s: phy advertised caps=0x%04x\n", dev->name, my_ad_caps); /* Restart auto-negotiation process in order to advertise my caps */ SMC_SET_PHY_BMCR(lp, phyaddr, BMCR_ANENABLE | BMCR_ANRESTART); smc911x_phy_check_media(dev, 1); smc911x_phy_configure_exit: spin_unlock_irqrestore(&lp->lock, flags); } /* * smc911x_phy_interrupt * * Purpose: Handle interrupts relating to PHY register 18. This is * called from the "hard" interrupt handler under our private spinlock. */ static void smc911x_phy_interrupt(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); int phyaddr = lp->mii.phy_id; int status; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); if (lp->phy_type == 0) return; smc911x_phy_check_media(dev, 0); /* read to clear status bits */ SMC_GET_PHY_INT_SRC(lp, phyaddr,status); DBG(SMC_DEBUG_MISC, "%s: PHY interrupt status 0x%04x\n", dev->name, status & 0xffff); DBG(SMC_DEBUG_MISC, "%s: AFC_CFG 0x%08x\n", dev->name, SMC_GET_AFC_CFG(lp)); } /*--- END PHY CONTROL AND CONFIGURATION-------------------------------------*/ /* * This is the main routine of the driver, to handle the device when * it needs some attention. */ static irqreturn_t smc911x_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; struct smc911x_local *lp = netdev_priv(dev); unsigned int status, mask, timeout; unsigned int rx_overrun=0, cr, pkts; unsigned long flags; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); spin_lock_irqsave(&lp->lock, flags); /* Spurious interrupt check */ if ((SMC_GET_IRQ_CFG(lp) & (INT_CFG_IRQ_INT_ | INT_CFG_IRQ_EN_)) != (INT_CFG_IRQ_INT_ | INT_CFG_IRQ_EN_)) { spin_unlock_irqrestore(&lp->lock, flags); return IRQ_NONE; } mask = SMC_GET_INT_EN(lp); SMC_SET_INT_EN(lp, 0); /* set a timeout value, so I don't stay here forever */ timeout = 8; do { status = SMC_GET_INT(lp); DBG(SMC_DEBUG_MISC, "%s: INT 0x%08x MASK 0x%08x OUTSIDE MASK 0x%08x\n", dev->name, status, mask, status & ~mask); status &= mask; if (!status) break; /* Handle SW interrupt condition */ if (status & INT_STS_SW_INT_) { SMC_ACK_INT(lp, INT_STS_SW_INT_); mask &= ~INT_EN_SW_INT_EN_; } /* Handle various error conditions */ if (status & INT_STS_RXE_) { SMC_ACK_INT(lp, INT_STS_RXE_); dev->stats.rx_errors++; } if (status & INT_STS_RXDFH_INT_) { SMC_ACK_INT(lp, INT_STS_RXDFH_INT_); dev->stats.rx_dropped+=SMC_GET_RX_DROP(lp); } /* Undocumented interrupt-what is the right thing to do here? */ if (status & INT_STS_RXDF_INT_) { SMC_ACK_INT(lp, INT_STS_RXDF_INT_); } /* Rx Data FIFO exceeds set level */ if (status & INT_STS_RDFL_) { if (IS_REV_A(lp->revision)) { rx_overrun=1; SMC_GET_MAC_CR(lp, cr); cr &= ~MAC_CR_RXEN_; SMC_SET_MAC_CR(lp, cr); DBG(SMC_DEBUG_RX, "%s: RX overrun\n", dev->name); dev->stats.rx_errors++; dev->stats.rx_fifo_errors++; } SMC_ACK_INT(lp, INT_STS_RDFL_); } if (status & INT_STS_RDFO_) { if (!IS_REV_A(lp->revision)) { SMC_GET_MAC_CR(lp, cr); cr &= ~MAC_CR_RXEN_; SMC_SET_MAC_CR(lp, cr); rx_overrun=1; DBG(SMC_DEBUG_RX, "%s: RX overrun\n", dev->name); dev->stats.rx_errors++; dev->stats.rx_fifo_errors++; } SMC_ACK_INT(lp, INT_STS_RDFO_); } /* Handle receive condition */ if ((status & INT_STS_RSFL_) || rx_overrun) { unsigned int fifo; DBG(SMC_DEBUG_RX, "%s: RX irq\n", dev->name); fifo = SMC_GET_RX_FIFO_INF(lp); pkts = (fifo & RX_FIFO_INF_RXSUSED_) >> 16; DBG(SMC_DEBUG_RX, "%s: Rx FIFO pkts %d, bytes %d\n", dev->name, pkts, fifo & 0xFFFF ); if (pkts != 0) { #ifdef SMC_USE_DMA unsigned int fifo; if (lp->rxdma_active){ DBG(SMC_DEBUG_RX | SMC_DEBUG_DMA, "%s: RX DMA active\n", dev->name); /* The DMA is already running so up the IRQ threshold */ fifo = SMC_GET_FIFO_INT(lp) & ~0xFF; fifo |= pkts & 0xFF; DBG(SMC_DEBUG_RX, "%s: Setting RX stat FIFO threshold to %d\n", dev->name, fifo & 0xff); SMC_SET_FIFO_INT(lp, fifo); } else #endif smc911x_rcv(dev); } SMC_ACK_INT(lp, INT_STS_RSFL_); } /* Handle transmit FIFO available */ if (status & INT_STS_TDFA_) { DBG(SMC_DEBUG_TX, "%s: TX data FIFO space available irq\n", dev->name); SMC_SET_FIFO_TDA(lp, 0xFF); lp->tx_throttle = 0; #ifdef SMC_USE_DMA if (!lp->txdma_active) #endif netif_wake_queue(dev); SMC_ACK_INT(lp, INT_STS_TDFA_); } /* Handle transmit done condition */ #if 1 if (status & (INT_STS_TSFL_ | INT_STS_GPT_INT_)) { DBG(SMC_DEBUG_TX | SMC_DEBUG_MISC, "%s: Tx stat FIFO limit (%d) /GPT irq\n", dev->name, (SMC_GET_FIFO_INT(lp) & 0x00ff0000) >> 16); smc911x_tx(dev); SMC_SET_GPT_CFG(lp, GPT_CFG_TIMER_EN_ | 10000); SMC_ACK_INT(lp, INT_STS_TSFL_); SMC_ACK_INT(lp, INT_STS_TSFL_ | INT_STS_GPT_INT_); } #else if (status & INT_STS_TSFL_) { DBG(SMC_DEBUG_TX, "%s: TX status FIFO limit (%d) irq\n", dev->name, ); smc911x_tx(dev); SMC_ACK_INT(lp, INT_STS_TSFL_); } if (status & INT_STS_GPT_INT_) { DBG(SMC_DEBUG_RX, "%s: IRQ_CFG 0x%08x FIFO_INT 0x%08x RX_CFG 0x%08x\n", dev->name, SMC_GET_IRQ_CFG(lp), SMC_GET_FIFO_INT(lp), SMC_GET_RX_CFG(lp)); DBG(SMC_DEBUG_RX, "%s: Rx Stat FIFO Used 0x%02x " "Data FIFO Used 0x%04x Stat FIFO 0x%08x\n", dev->name, (SMC_GET_RX_FIFO_INF(lp) & 0x00ff0000) >> 16, SMC_GET_RX_FIFO_INF(lp) & 0xffff, SMC_GET_RX_STS_FIFO_PEEK(lp)); SMC_SET_GPT_CFG(lp, GPT_CFG_TIMER_EN_ | 10000); SMC_ACK_INT(lp, INT_STS_GPT_INT_); } #endif /* Handle PHY interrupt condition */ if (status & INT_STS_PHY_INT_) { DBG(SMC_DEBUG_MISC, "%s: PHY irq\n", dev->name); smc911x_phy_interrupt(dev); SMC_ACK_INT(lp, INT_STS_PHY_INT_); } } while (--timeout); /* restore mask state */ SMC_SET_INT_EN(lp, mask); DBG(SMC_DEBUG_MISC, "%s: Interrupt done (%d loops)\n", dev->name, 8-timeout); spin_unlock_irqrestore(&lp->lock, flags); return IRQ_HANDLED; } #ifdef SMC_USE_DMA static void smc911x_tx_dma_irq(int dma, void *data) { struct net_device *dev = (struct net_device *)data; struct smc911x_local *lp = netdev_priv(dev); struct sk_buff *skb = lp->current_tx_skb; unsigned long flags; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); DBG(SMC_DEBUG_TX | SMC_DEBUG_DMA, "%s: TX DMA irq handler\n", dev->name); /* Clear the DMA interrupt sources */ SMC_DMA_ACK_IRQ(dev, dma); BUG_ON(skb == NULL); dma_unmap_single(NULL, tx_dmabuf, tx_dmalen, DMA_TO_DEVICE); dev->trans_start = jiffies; dev_kfree_skb_irq(skb); lp->current_tx_skb = NULL; if (lp->pending_tx_skb != NULL) smc911x_hardware_send_pkt(dev); else { DBG(SMC_DEBUG_TX | SMC_DEBUG_DMA, "%s: No pending Tx packets. DMA disabled\n", dev->name); spin_lock_irqsave(&lp->lock, flags); lp->txdma_active = 0; if (!lp->tx_throttle) { netif_wake_queue(dev); } spin_unlock_irqrestore(&lp->lock, flags); } DBG(SMC_DEBUG_TX | SMC_DEBUG_DMA, "%s: TX DMA irq completed\n", dev->name); } static void smc911x_rx_dma_irq(int dma, void *data) { struct net_device *dev = (struct net_device *)data; unsigned long ioaddr = dev->base_addr; struct smc911x_local *lp = netdev_priv(dev); struct sk_buff *skb = lp->current_rx_skb; unsigned long flags; unsigned int pkts; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); DBG(SMC_DEBUG_RX | SMC_DEBUG_DMA, "%s: RX DMA irq handler\n", dev->name); /* Clear the DMA interrupt sources */ SMC_DMA_ACK_IRQ(dev, dma); dma_unmap_single(NULL, rx_dmabuf, rx_dmalen, DMA_FROM_DEVICE); BUG_ON(skb == NULL); lp->current_rx_skb = NULL; PRINT_PKT(skb->data, skb->len); skb->protocol = eth_type_trans(skb, dev); dev->stats.rx_packets++; dev->stats.rx_bytes += skb->len; netif_rx(skb); spin_lock_irqsave(&lp->lock, flags); pkts = (SMC_GET_RX_FIFO_INF(lp) & RX_FIFO_INF_RXSUSED_) >> 16; if (pkts != 0) { smc911x_rcv(dev); }else { lp->rxdma_active = 0; } spin_unlock_irqrestore(&lp->lock, flags); DBG(SMC_DEBUG_RX | SMC_DEBUG_DMA, "%s: RX DMA irq completed. DMA RX FIFO PKTS %d\n", dev->name, pkts); } #endif /* SMC_USE_DMA */ #ifdef CONFIG_NET_POLL_CONTROLLER /* * Polling receive - used by netconsole and other diagnostic tools * to allow network i/o with interrupts disabled. */ static void smc911x_poll_controller(struct net_device *dev) { disable_irq(dev->irq); smc911x_interrupt(dev->irq, dev); enable_irq(dev->irq); } #endif /* Our watchdog timed out. Called by the networking layer */ static void smc911x_timeout(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); int status, mask; unsigned long flags; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); spin_lock_irqsave(&lp->lock, flags); status = SMC_GET_INT(lp); mask = SMC_GET_INT_EN(lp); spin_unlock_irqrestore(&lp->lock, flags); DBG(SMC_DEBUG_MISC, "%s: INT 0x%02x MASK 0x%02x\n", dev->name, status, mask); /* Dump the current TX FIFO contents and restart */ mask = SMC_GET_TX_CFG(lp); SMC_SET_TX_CFG(lp, mask | TX_CFG_TXS_DUMP_ | TX_CFG_TXD_DUMP_); /* * Reconfiguring the PHY doesn't seem like a bad idea here, but * smc911x_phy_configure() calls msleep() which calls schedule_timeout() * which calls schedule(). Hence we use a work queue. */ if (lp->phy_type != 0) schedule_work(&lp->phy_configure); /* We can accept TX packets again */ dev->trans_start = jiffies; /* prevent tx timeout */ netif_wake_queue(dev); } /* * This routine will, depending on the values passed to it, * either make it accept multicast packets, go into * promiscuous mode (for TCPDUMP and cousins) or accept * a select set of multicast packets */ static void smc911x_set_multicast_list(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); unsigned int multicast_table[2]; unsigned int mcr, update_multicast = 0; unsigned long flags; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); spin_lock_irqsave(&lp->lock, flags); SMC_GET_MAC_CR(lp, mcr); spin_unlock_irqrestore(&lp->lock, flags); if (dev->flags & IFF_PROMISC) { DBG(SMC_DEBUG_MISC, "%s: RCR_PRMS\n", dev->name); mcr |= MAC_CR_PRMS_; } /* * Here, I am setting this to accept all multicast packets. * I don't need to zero the multicast table, because the flag is * checked before the table is */ else if (dev->flags & IFF_ALLMULTI || netdev_mc_count(dev) > 16) { DBG(SMC_DEBUG_MISC, "%s: RCR_ALMUL\n", dev->name); mcr |= MAC_CR_MCPAS_; } /* * This sets the internal hardware table to filter out unwanted * multicast packets before they take up memory. * * The SMC chip uses a hash table where the high 6 bits of the CRC of * address are the offset into the table. If that bit is 1, then the * multicast packet is accepted. Otherwise, it's dropped silently. * * To use the 6 bits as an offset into the table, the high 1 bit is * the number of the 32 bit register, while the low 5 bits are the bit * within that register. */ else if (!netdev_mc_empty(dev)) { struct netdev_hw_addr *ha; /* Set the Hash perfec mode */ mcr |= MAC_CR_HPFILT_; /* start with a table of all zeros: reject all */ memset(multicast_table, 0, sizeof(multicast_table)); netdev_for_each_mc_addr(ha, dev) { u32 position; /* upper 6 bits are used as hash index */ position = ether_crc(ETH_ALEN, ha->addr)>>26; multicast_table[position>>5] |= 1 << (position&0x1f); } /* be sure I get rid of flags I might have set */ mcr &= ~(MAC_CR_PRMS_ | MAC_CR_MCPAS_); /* now, the table can be loaded into the chipset */ update_multicast = 1; } else { DBG(SMC_DEBUG_MISC, "%s: ~(MAC_CR_PRMS_|MAC_CR_MCPAS_)\n", dev->name); mcr &= ~(MAC_CR_PRMS_ | MAC_CR_MCPAS_); /* * since I'm disabling all multicast entirely, I need to * clear the multicast list */ memset(multicast_table, 0, sizeof(multicast_table)); update_multicast = 1; } spin_lock_irqsave(&lp->lock, flags); SMC_SET_MAC_CR(lp, mcr); if (update_multicast) { DBG(SMC_DEBUG_MISC, "%s: update mcast hash table 0x%08x 0x%08x\n", dev->name, multicast_table[0], multicast_table[1]); SMC_SET_HASHL(lp, multicast_table[0]); SMC_SET_HASHH(lp, multicast_table[1]); } spin_unlock_irqrestore(&lp->lock, flags); } /* * Open and Initialize the board * * Set up everything, reset the card, etc.. */ static int smc911x_open(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); /* * Check that the address is valid. If its not, refuse * to bring the device up. The user must specify an * address using ifconfig eth0 hw ether xx:xx:xx:xx:xx:xx */ if (!is_valid_ether_addr(dev->dev_addr)) { PRINTK("%s: no valid ethernet hw addr\n", __func__); return -EINVAL; } /* reset the hardware */ smc911x_reset(dev); /* Configure the PHY, initialize the link state */ smc911x_phy_configure(&lp->phy_configure); /* Turn on Tx + Rx */ smc911x_enable(dev); netif_start_queue(dev); return 0; } /* * smc911x_close * * this makes the board clean up everything that it can * and not talk to the outside world. Caused by * an 'ifconfig ethX down' */ static int smc911x_close(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); netif_stop_queue(dev); netif_carrier_off(dev); /* clear everything */ smc911x_shutdown(dev); if (lp->phy_type != 0) { /* We need to ensure that no calls to * smc911x_phy_configure are pending. */ cancel_work_sync(&lp->phy_configure); smc911x_phy_powerdown(dev, lp->mii.phy_id); } if (lp->pending_tx_skb) { dev_kfree_skb(lp->pending_tx_skb); lp->pending_tx_skb = NULL; } return 0; } /* * Ethtool support */ static int smc911x_ethtool_getsettings(struct net_device *dev, struct ethtool_cmd *cmd) { struct smc911x_local *lp = netdev_priv(dev); int ret, status; unsigned long flags; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); cmd->maxtxpkt = 1; cmd->maxrxpkt = 1; if (lp->phy_type != 0) { spin_lock_irqsave(&lp->lock, flags); ret = mii_ethtool_gset(&lp->mii, cmd); spin_unlock_irqrestore(&lp->lock, flags); } else { cmd->supported = SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_TP | SUPPORTED_AUI; if (lp->ctl_rspeed == 10) ethtool_cmd_speed_set(cmd, SPEED_10); else if (lp->ctl_rspeed == 100) ethtool_cmd_speed_set(cmd, SPEED_100); cmd->autoneg = AUTONEG_DISABLE; if (lp->mii.phy_id==1) cmd->transceiver = XCVR_INTERNAL; else cmd->transceiver = XCVR_EXTERNAL; cmd->port = 0; SMC_GET_PHY_SPECIAL(lp, lp->mii.phy_id, status); cmd->duplex = (status & (PHY_SPECIAL_SPD_10FULL_ | PHY_SPECIAL_SPD_100FULL_)) ? DUPLEX_FULL : DUPLEX_HALF; ret = 0; } return ret; } static int smc911x_ethtool_setsettings(struct net_device *dev, struct ethtool_cmd *cmd) { struct smc911x_local *lp = netdev_priv(dev); int ret; unsigned long flags; if (lp->phy_type != 0) { spin_lock_irqsave(&lp->lock, flags); ret = mii_ethtool_sset(&lp->mii, cmd); spin_unlock_irqrestore(&lp->lock, flags); } else { if (cmd->autoneg != AUTONEG_DISABLE || cmd->speed != SPEED_10 || (cmd->duplex != DUPLEX_HALF && cmd->duplex != DUPLEX_FULL) || (cmd->port != PORT_TP && cmd->port != PORT_AUI)) return -EINVAL; lp->ctl_rfduplx = cmd->duplex == DUPLEX_FULL; ret = 0; } return ret; } static void smc911x_ethtool_getdrvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { strncpy(info->driver, CARDNAME, sizeof(info->driver)); strncpy(info->version, version, sizeof(info->version)); strncpy(info->bus_info, dev_name(dev->dev.parent), sizeof(info->bus_info)); } static int smc911x_ethtool_nwayreset(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); int ret = -EINVAL; unsigned long flags; if (lp->phy_type != 0) { spin_lock_irqsave(&lp->lock, flags); ret = mii_nway_restart(&lp->mii); spin_unlock_irqrestore(&lp->lock, flags); } return ret; } static u32 smc911x_ethtool_getmsglevel(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); return lp->msg_enable; } static void smc911x_ethtool_setmsglevel(struct net_device *dev, u32 level) { struct smc911x_local *lp = netdev_priv(dev); lp->msg_enable = level; } static int smc911x_ethtool_getregslen(struct net_device *dev) { /* System regs + MAC regs + PHY regs */ return (((E2P_CMD - ID_REV)/4 + 1) + (WUCSR - MAC_CR)+1 + 32) * sizeof(u32); } static void smc911x_ethtool_getregs(struct net_device *dev, struct ethtool_regs* regs, void *buf) { struct smc911x_local *lp = netdev_priv(dev); unsigned long flags; u32 reg,i,j=0; u32 *data = (u32*)buf; regs->version = lp->version; for(i=ID_REV;i<=E2P_CMD;i+=4) { data[j++] = SMC_inl(lp, i); } for(i=MAC_CR;i<=WUCSR;i++) { spin_lock_irqsave(&lp->lock, flags); SMC_GET_MAC_CSR(lp, i, reg); spin_unlock_irqrestore(&lp->lock, flags); data[j++] = reg; } for(i=0;i<=31;i++) { spin_lock_irqsave(&lp->lock, flags); SMC_GET_MII(lp, i, lp->mii.phy_id, reg); spin_unlock_irqrestore(&lp->lock, flags); data[j++] = reg & 0xFFFF; } } static int smc911x_ethtool_wait_eeprom_ready(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); unsigned int timeout; int e2p_cmd; e2p_cmd = SMC_GET_E2P_CMD(lp); for(timeout=10;(e2p_cmd & E2P_CMD_EPC_BUSY_) && timeout; timeout--) { if (e2p_cmd & E2P_CMD_EPC_TIMEOUT_) { PRINTK("%s: %s timeout waiting for EEPROM to respond\n", dev->name, __func__); return -EFAULT; } mdelay(1); e2p_cmd = SMC_GET_E2P_CMD(lp); } if (timeout == 0) { PRINTK("%s: %s timeout waiting for EEPROM CMD not busy\n", dev->name, __func__); return -ETIMEDOUT; } return 0; } static inline int smc911x_ethtool_write_eeprom_cmd(struct net_device *dev, int cmd, int addr) { struct smc911x_local *lp = netdev_priv(dev); int ret; if ((ret = smc911x_ethtool_wait_eeprom_ready(dev))!=0) return ret; SMC_SET_E2P_CMD(lp, E2P_CMD_EPC_BUSY_ | ((cmd) & (0x7<<28)) | ((addr) & 0xFF)); return 0; } static inline int smc911x_ethtool_read_eeprom_byte(struct net_device *dev, u8 *data) { struct smc911x_local *lp = netdev_priv(dev); int ret; if ((ret = smc911x_ethtool_wait_eeprom_ready(dev))!=0) return ret; *data = SMC_GET_E2P_DATA(lp); return 0; } static inline int smc911x_ethtool_write_eeprom_byte(struct net_device *dev, u8 data) { struct smc911x_local *lp = netdev_priv(dev); int ret; if ((ret = smc911x_ethtool_wait_eeprom_ready(dev))!=0) return ret; SMC_SET_E2P_DATA(lp, data); return 0; } static int smc911x_ethtool_geteeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data) { u8 eebuf[SMC911X_EEPROM_LEN]; int i, ret; for(i=0;i<SMC911X_EEPROM_LEN;i++) { if ((ret=smc911x_ethtool_write_eeprom_cmd(dev, E2P_CMD_EPC_CMD_READ_, i ))!=0) return ret; if ((ret=smc911x_ethtool_read_eeprom_byte(dev, &eebuf[i]))!=0) return ret; } memcpy(data, eebuf+eeprom->offset, eeprom->len); return 0; } static int smc911x_ethtool_seteeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data) { int i, ret; /* Enable erase */ if ((ret=smc911x_ethtool_write_eeprom_cmd(dev, E2P_CMD_EPC_CMD_EWEN_, 0 ))!=0) return ret; for(i=eeprom->offset;i<(eeprom->offset+eeprom->len);i++) { /* erase byte */ if ((ret=smc911x_ethtool_write_eeprom_cmd(dev, E2P_CMD_EPC_CMD_ERASE_, i ))!=0) return ret; /* write byte */ if ((ret=smc911x_ethtool_write_eeprom_byte(dev, *data))!=0) return ret; if ((ret=smc911x_ethtool_write_eeprom_cmd(dev, E2P_CMD_EPC_CMD_WRITE_, i ))!=0) return ret; } return 0; } static int smc911x_ethtool_geteeprom_len(struct net_device *dev) { return SMC911X_EEPROM_LEN; } static const struct ethtool_ops smc911x_ethtool_ops = { .get_settings = smc911x_ethtool_getsettings, .set_settings = smc911x_ethtool_setsettings, .get_drvinfo = smc911x_ethtool_getdrvinfo, .get_msglevel = smc911x_ethtool_getmsglevel, .set_msglevel = smc911x_ethtool_setmsglevel, .nway_reset = smc911x_ethtool_nwayreset, .get_link = ethtool_op_get_link, .get_regs_len = smc911x_ethtool_getregslen, .get_regs = smc911x_ethtool_getregs, .get_eeprom_len = smc911x_ethtool_geteeprom_len, .get_eeprom = smc911x_ethtool_geteeprom, .set_eeprom = smc911x_ethtool_seteeprom, }; /* * smc911x_findirq * * This routine has a simple purpose -- make the SMC chip generate an * interrupt, so an auto-detect routine can detect it, and find the IRQ, */ static int __devinit smc911x_findirq(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); int timeout = 20; unsigned long cookie; DBG(SMC_DEBUG_FUNC, "--> %s\n", __func__); cookie = probe_irq_on(); /* * Force a SW interrupt */ SMC_SET_INT_EN(lp, INT_EN_SW_INT_EN_); /* * Wait until positive that the interrupt has been generated */ do { int int_status; udelay(10); int_status = SMC_GET_INT_EN(lp); if (int_status & INT_EN_SW_INT_EN_) break; /* got the interrupt */ } while (--timeout); /* * there is really nothing that I can do here if timeout fails, * as autoirq_report will return a 0 anyway, which is what I * want in this case. Plus, the clean up is needed in both * cases. */ /* and disable all interrupts again */ SMC_SET_INT_EN(lp, 0); /* and return what I found */ return probe_irq_off(cookie); } static const struct net_device_ops smc911x_netdev_ops = { .ndo_open = smc911x_open, .ndo_stop = smc911x_close, .ndo_start_xmit = smc911x_hard_start_xmit, .ndo_tx_timeout = smc911x_timeout, .ndo_set_rx_mode = smc911x_set_multicast_list, .ndo_change_mtu = eth_change_mtu, .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = eth_mac_addr, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = smc911x_poll_controller, #endif }; /* * Function: smc911x_probe(unsigned long ioaddr) * * Purpose: * Tests to see if a given ioaddr points to an SMC911x chip. * Returns a 0 on success * * Algorithm: * (1) see if the endian word is OK * (1) see if I recognize the chip ID in the appropriate register * * Here I do typical initialization tasks. * * o Initialize the structure if needed * o print out my vanity message if not done so already * o print out what type of hardware is detected * o print out the ethernet address * o find the IRQ * o set up my private data * o configure the dev structure with my subroutines * o actually GRAB the irq. * o GRAB the region */ static int __devinit smc911x_probe(struct net_device *dev) { struct smc911x_local *lp = netdev_priv(dev); int i, retval; unsigned int val, chip_id, revision; const char *version_string; unsigned long irq_flags; DBG(SMC_DEBUG_FUNC, "%s: --> %s\n", dev->name, __func__); /* First, see if the endian word is recognized */ val = SMC_GET_BYTE_TEST(lp); DBG(SMC_DEBUG_MISC, "%s: endian probe returned 0x%04x\n", CARDNAME, val); if (val != 0x87654321) { printk(KERN_ERR "Invalid chip endian 0x%08x\n",val); retval = -ENODEV; goto err_out; } /* * check if the revision register is something that I * recognize. These might need to be added to later, * as future revisions could be added. */ chip_id = SMC_GET_PN(lp); DBG(SMC_DEBUG_MISC, "%s: id probe returned 0x%04x\n", CARDNAME, chip_id); for(i=0;chip_ids[i].id != 0; i++) { if (chip_ids[i].id == chip_id) break; } if (!chip_ids[i].id) { printk(KERN_ERR "Unknown chip ID %04x\n", chip_id); retval = -ENODEV; goto err_out; } version_string = chip_ids[i].name; revision = SMC_GET_REV(lp); DBG(SMC_DEBUG_MISC, "%s: revision = 0x%04x\n", CARDNAME, revision); /* At this point I'll assume that the chip is an SMC911x. */ DBG(SMC_DEBUG_MISC, "%s: Found a %s\n", CARDNAME, chip_ids[i].name); /* Validate the TX FIFO size requested */ if ((tx_fifo_kb < 2) || (tx_fifo_kb > 14)) { printk(KERN_ERR "Invalid TX FIFO size requested %d\n", tx_fifo_kb); retval = -EINVAL; goto err_out; } /* fill in some of the fields */ lp->version = chip_ids[i].id; lp->revision = revision; lp->tx_fifo_kb = tx_fifo_kb; /* Reverse calculate the RX FIFO size from the TX */ lp->tx_fifo_size=(lp->tx_fifo_kb<<10) - 512; lp->rx_fifo_size= ((0x4000 - 512 - lp->tx_fifo_size) / 16) * 15; /* Set the automatic flow control values */ switch(lp->tx_fifo_kb) { /* * AFC_HI is about ((Rx Data Fifo Size)*2/3)/64 * AFC_LO is AFC_HI/2 * BACK_DUR is about 5uS*(AFC_LO) rounded down */ case 2:/* 13440 Rx Data Fifo Size */ lp->afc_cfg=0x008C46AF;break; case 3:/* 12480 Rx Data Fifo Size */ lp->afc_cfg=0x0082419F;break; case 4:/* 11520 Rx Data Fifo Size */ lp->afc_cfg=0x00783C9F;break; case 5:/* 10560 Rx Data Fifo Size */ lp->afc_cfg=0x006E374F;break; case 6:/* 9600 Rx Data Fifo Size */ lp->afc_cfg=0x0064328F;break; case 7:/* 8640 Rx Data Fifo Size */ lp->afc_cfg=0x005A2D7F;break; case 8:/* 7680 Rx Data Fifo Size */ lp->afc_cfg=0x0050287F;break; case 9:/* 6720 Rx Data Fifo Size */ lp->afc_cfg=0x0046236F;break; case 10:/* 5760 Rx Data Fifo Size */ lp->afc_cfg=0x003C1E6F;break; case 11:/* 4800 Rx Data Fifo Size */ lp->afc_cfg=0x0032195F;break; /* * AFC_HI is ~1520 bytes less than RX Data Fifo Size * AFC_LO is AFC_HI/2 * BACK_DUR is about 5uS*(AFC_LO) rounded down */ case 12:/* 3840 Rx Data Fifo Size */ lp->afc_cfg=0x0024124F;break; case 13:/* 2880 Rx Data Fifo Size */ lp->afc_cfg=0x0015073F;break; case 14:/* 1920 Rx Data Fifo Size */ lp->afc_cfg=0x0006032F;break; default: PRINTK("%s: ERROR -- no AFC_CFG setting found", dev->name); break; } DBG(SMC_DEBUG_MISC | SMC_DEBUG_TX | SMC_DEBUG_RX, "%s: tx_fifo %d rx_fifo %d afc_cfg 0x%08x\n", CARDNAME, lp->tx_fifo_size, lp->rx_fifo_size, lp->afc_cfg); spin_lock_init(&lp->lock); /* Get the MAC address */ SMC_GET_MAC_ADDR(lp, dev->dev_addr); /* now, reset the chip, and put it into a known state */ smc911x_reset(dev); /* * If dev->irq is 0, then the device has to be banged on to see * what the IRQ is. * * Specifying an IRQ is done with the assumption that the user knows * what (s)he is doing. No checking is done!!!! */ if (dev->irq < 1) { int trials; trials = 3; while (trials--) { dev->irq = smc911x_findirq(dev); if (dev->irq) break; /* kick the card and try again */ smc911x_reset(dev); } } if (dev->irq == 0) { printk("%s: Couldn't autodetect your IRQ. Use irq=xx.\n", dev->name); retval = -ENODEV; goto err_out; } dev->irq = irq_canonicalize(dev->irq); /* Fill in the fields of the device structure with ethernet values. */ ether_setup(dev); dev->netdev_ops = &smc911x_netdev_ops; dev->watchdog_timeo = msecs_to_jiffies(watchdog); dev->ethtool_ops = &smc911x_ethtool_ops; INIT_WORK(&lp->phy_configure, smc911x_phy_configure); lp->mii.phy_id_mask = 0x1f; lp->mii.reg_num_mask = 0x1f; lp->mii.force_media = 0; lp->mii.full_duplex = 0; lp->mii.dev = dev; lp->mii.mdio_read = smc911x_phy_read; lp->mii.mdio_write = smc911x_phy_write; /* * Locate the phy, if any. */ smc911x_phy_detect(dev); /* Set default parameters */ lp->msg_enable = NETIF_MSG_LINK; lp->ctl_rfduplx = 1; lp->ctl_rspeed = 100; #ifdef SMC_DYNAMIC_BUS_CONFIG irq_flags = lp->cfg.irq_flags; #else irq_flags = IRQF_SHARED | SMC_IRQ_SENSE; #endif /* Grab the IRQ */ retval = request_irq(dev->irq, smc911x_interrupt, irq_flags, dev->name, dev); if (retval) goto err_out; #ifdef SMC_USE_DMA lp->rxdma = SMC_DMA_REQUEST(dev, smc911x_rx_dma_irq); lp->txdma = SMC_DMA_REQUEST(dev, smc911x_tx_dma_irq); lp->rxdma_active = 0; lp->txdma_active = 0; dev->dma = lp->rxdma; #endif retval = register_netdev(dev); if (retval == 0) { /* now, print out the card info, in a short format.. */ printk("%s: %s (rev %d) at %#lx IRQ %d", dev->name, version_string, lp->revision, dev->base_addr, dev->irq); #ifdef SMC_USE_DMA if (lp->rxdma != -1) printk(" RXDMA %d ", lp->rxdma); if (lp->txdma != -1) printk("TXDMA %d", lp->txdma); #endif printk("\n"); if (!is_valid_ether_addr(dev->dev_addr)) { printk("%s: Invalid ethernet MAC address. Please " "set using ifconfig\n", dev->name); } else { /* Print the Ethernet address */ printk("%s: Ethernet addr: %pM\n", dev->name, dev->dev_addr); } if (lp->phy_type == 0) { PRINTK("%s: No PHY found\n", dev->name); } else if ((lp->phy_type & ~0xff) == LAN911X_INTERNAL_PHY_ID) { PRINTK("%s: LAN911x Internal PHY\n", dev->name); } else { PRINTK("%s: External PHY 0x%08x\n", dev->name, lp->phy_type); } } err_out: #ifdef SMC_USE_DMA if (retval) { if (lp->rxdma != -1) { SMC_DMA_FREE(dev, lp->rxdma); } if (lp->txdma != -1) { SMC_DMA_FREE(dev, lp->txdma); } } #endif return retval; } /* * smc911x_init(void) * * Output: * 0 --> there is a device * anything else, error */ static int __devinit smc911x_drv_probe(struct platform_device *pdev) { struct net_device *ndev; struct resource *res; struct smc911x_local *lp; unsigned int *addr; int ret; DBG(SMC_DEBUG_FUNC, "--> %s\n", __func__); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { ret = -ENODEV; goto out; } /* * Request the regions. */ if (!request_mem_region(res->start, SMC911X_IO_EXTENT, CARDNAME)) { ret = -EBUSY; goto out; } ndev = alloc_etherdev(sizeof(struct smc911x_local)); if (!ndev) { ret = -ENOMEM; goto release_1; } SET_NETDEV_DEV(ndev, &pdev->dev); ndev->dma = (unsigned char)-1; ndev->irq = platform_get_irq(pdev, 0); lp = netdev_priv(ndev); lp->netdev = ndev; #ifdef SMC_DYNAMIC_BUS_CONFIG { struct smc911x_platdata *pd = pdev->dev.platform_data; if (!pd) { ret = -EINVAL; goto release_both; } memcpy(&lp->cfg, pd, sizeof(lp->cfg)); } #endif addr = ioremap(res->start, SMC911X_IO_EXTENT); if (!addr) { ret = -ENOMEM; goto release_both; } platform_set_drvdata(pdev, ndev); lp->base = addr; ndev->base_addr = res->start; ret = smc911x_probe(ndev); if (ret != 0) { platform_set_drvdata(pdev, NULL); iounmap(addr); release_both: free_netdev(ndev); release_1: release_mem_region(res->start, SMC911X_IO_EXTENT); out: printk("%s: not found (%d).\n", CARDNAME, ret); } #ifdef SMC_USE_DMA else { lp->physaddr = res->start; lp->dev = &pdev->dev; } #endif return ret; } static int __devexit smc911x_drv_remove(struct platform_device *pdev) { struct net_device *ndev = platform_get_drvdata(pdev); struct smc911x_local *lp = netdev_priv(ndev); struct resource *res; DBG(SMC_DEBUG_FUNC, "--> %s\n", __func__); platform_set_drvdata(pdev, NULL); unregister_netdev(ndev); free_irq(ndev->irq, ndev); #ifdef SMC_USE_DMA { if (lp->rxdma != -1) { SMC_DMA_FREE(dev, lp->rxdma); } if (lp->txdma != -1) { SMC_DMA_FREE(dev, lp->txdma); } } #endif iounmap(lp->base); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); release_mem_region(res->start, SMC911X_IO_EXTENT); free_netdev(ndev); return 0; } static int smc911x_drv_suspend(struct platform_device *dev, pm_message_t state) { struct net_device *ndev = platform_get_drvdata(dev); struct smc911x_local *lp = netdev_priv(ndev); DBG(SMC_DEBUG_FUNC, "--> %s\n", __func__); if (ndev) { if (netif_running(ndev)) { netif_device_detach(ndev); smc911x_shutdown(ndev); #if POWER_DOWN /* Set D2 - Energy detect only setting */ SMC_SET_PMT_CTRL(lp, 2<<12); #endif } } return 0; } static int smc911x_drv_resume(struct platform_device *dev) { struct net_device *ndev = platform_get_drvdata(dev); DBG(SMC_DEBUG_FUNC, "--> %s\n", __func__); if (ndev) { struct smc911x_local *lp = netdev_priv(ndev); if (netif_running(ndev)) { smc911x_reset(ndev); if (lp->phy_type != 0) smc911x_phy_configure(&lp->phy_configure); smc911x_enable(ndev); netif_device_attach(ndev); } } return 0; } static struct platform_driver smc911x_driver = { .probe = smc911x_drv_probe, .remove = __devexit_p(smc911x_drv_remove), .suspend = smc911x_drv_suspend, .resume = smc911x_drv_resume, .driver = { .name = CARDNAME, .owner = THIS_MODULE, }, }; module_platform_driver(smc911x_driver);
giantdisaster/btrfs
drivers/net/ethernet/smsc/smc911x.c
C
gpl-2.0
58,939
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Test gd functionality. * * @package core * @category phpunit * @copyright 2015 Andrew Nicols <[email protected]> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * A set of tests for some of the gd functionality within Moodle. * * @package core * @category phpunit * @copyright 2015 Andrew Nicols <[email protected]> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class core_gdlib_testcase extends basic_testcase { private $fixturepath = null; public function setUp() { $this->fixturepath = __DIR__ . DIRECTORY_SEPARATOR . 'fixtures' . DIRECTORY_SEPARATOR; } public function test_generate_image_thumbnail() { global $CFG; require_once($CFG->libdir . '/gdlib.php'); // Test with meaningless data. // Now use a fixture. $pngpath = $this->fixturepath . 'gd-logo.png'; $pngthumb = generate_image_thumbnail($pngpath, 24, 24); $this->assertTrue(is_string($pngthumb)); // And check that the generated image was of the correct proportions and mimetype. $imageinfo = getimagesizefromstring($pngthumb); $this->assertEquals(24, $imageinfo[0]); $this->assertEquals(24, $imageinfo[1]); $this->assertEquals('image/png', $imageinfo['mime']); } public function test_generate_image_thumbnail_from_string() { global $CFG; require_once($CFG->libdir . '/gdlib.php'); // Test with meaningless data. // First empty values. $this->assertFalse(generate_image_thumbnail_from_string('', 24, 24)); $this->assertFalse(generate_image_thumbnail_from_string('invalid', 0, 24)); $this->assertFalse(generate_image_thumbnail_from_string('invalid', 24, 0)); // Now an invalid string. $this->assertFalse(generate_image_thumbnail_from_string('invalid', 24, 24)); // Now use a fixture. $pngpath = $this->fixturepath . 'gd-logo.png'; $pngdata = file_get_contents($pngpath); $pngthumb = generate_image_thumbnail_from_string($pngdata, 24, 24); $this->assertTrue(is_string($pngthumb)); // And check that the generated image was of the correct proportions and mimetype. $imageinfo = getimagesizefromstring($pngthumb); $this->assertEquals(24, $imageinfo[0]); $this->assertEquals(24, $imageinfo[1]); $this->assertEquals('image/png', $imageinfo['mime']); } public function test_resize_image() { global $CFG; require_once($CFG->libdir . '/gdlib.php'); $pngpath = $this->fixturepath . 'gd-logo.png'; // Preferred height. $newpng = resize_image($pngpath, null, 24); $this->assertTrue(is_string($newpng)); $imageinfo = getimagesizefromstring($newpng); $this->assertEquals(89, $imageinfo[0]); $this->assertEquals(24, $imageinfo[1]); $this->assertEquals('image/png', $imageinfo['mime']); // Preferred width. $newpng = resize_image($pngpath, 100, null); $this->assertTrue(is_string($newpng)); $imageinfo = getimagesizefromstring($newpng); $this->assertEquals(100, $imageinfo[0]); $this->assertEquals(26, $imageinfo[1]); $this->assertEquals('image/png', $imageinfo['mime']); // Preferred width and height. $newpng = resize_image($pngpath, 50, 50); $this->assertTrue(is_string($newpng)); $imageinfo = getimagesizefromstring($newpng); $this->assertEquals(50, $imageinfo[0]); $this->assertEquals(13, $imageinfo[1]); $this->assertEquals('image/png', $imageinfo['mime']); } public function test_resize_image_from_image() { global $CFG; require_once($CFG->libdir . '/gdlib.php'); $pngpath = $this->fixturepath . 'gd-logo.png'; $origimageinfo = getimagesize($pngpath); $imagecontent = file_get_contents($pngpath); // Preferred height. $imageresource = imagecreatefromstring($imagecontent); $newpng = resize_image_from_image($imageresource, $origimageinfo, null, 24); $this->assertTrue(is_string($newpng)); $imageinfo = getimagesizefromstring($newpng); $this->assertEquals(89, $imageinfo[0]); $this->assertEquals(24, $imageinfo[1]); $this->assertEquals('image/png', $imageinfo['mime']); // Preferred width. $imageresource = imagecreatefromstring($imagecontent); $newpng = resize_image_from_image($imageresource, $origimageinfo, 100, null); $this->assertTrue(is_string($newpng)); $imageinfo = getimagesizefromstring($newpng); $this->assertEquals(100, $imageinfo[0]); $this->assertEquals(26, $imageinfo[1]); $this->assertEquals('image/png', $imageinfo['mime']); // Preferred width and height. $imageresource = imagecreatefromstring($imagecontent); $newpng = resize_image_from_image($imageresource, $origimageinfo, 50, 50); $this->assertTrue(is_string($newpng)); $imageinfo = getimagesizefromstring($newpng); $this->assertEquals(50, $imageinfo[0]); $this->assertEquals(13, $imageinfo[1]); $this->assertEquals('image/png', $imageinfo['mime']); } }
derhelge/moodle
lib/tests/gdlib_test.php
PHP
gpl-3.0
6,051
// OS dependant type definition #ifndef __OS_TYPE_H__ #define __OS_TYPE_H__ #ifdef _WIN32 #include <WinSock2.h> #include <WinBase.h> #include <Windows.h> #include <direct.h> #else #ifdef __APPLE__ #include <sys/event.h> #include <sys/time.h> #include <sys/syscall.h> // syscall(SYS_gettid) #else #include <sys/epoll.h> #endif #include <pthread.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <netdb.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <stdint.h> // define int8_t ... #include <signal.h> #include <unistd.h> #define closesocket close #define ioctlsocket ioctl #endif #include <stdexcept> #ifdef __GNUC__ #include <ext/hash_map> using namespace __gnu_cxx; namespace __gnu_cxx { template<> struct hash<std::string> { size_t operator()(const std::string& x) const { return hash<const char*>()(x.c_str()); } }; } #else #include <hash_map> using namespace stdext; #endif #ifdef _WIN32 typedef char int8_t; typedef short int16_t; typedef int int32_t; typedef long long int64_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; typedef unsigned long long uint64_t; typedef int socklen_t; #else typedef int SOCKET; typedef int BOOL; #ifndef __APPLE__ const int TRUE = 1; const int FALSE = 0; #endif const int SOCKET_ERROR = -1; const int INVALID_SOCKET = -1; #endif typedef unsigned char uchar_t; typedef int net_handle_t; typedef int conn_handle_t; enum { NETLIB_OK = 0, NETLIB_ERROR = -1 }; #define NETLIB_INVALID_HANDLE -1 enum { NETLIB_MSG_CONNECT = 1, NETLIB_MSG_CONFIRM, NETLIB_MSG_READ, NETLIB_MSG_WRITE, NETLIB_MSG_CLOSE, NETLIB_MSG_TIMER, NETLIB_MSG_LOOP }; const uint32_t INVALID_UINT32 = (uint32_t) -1; const uint32_t INVALID_VALUE = 0; typedef void (*callback_t)(void* callback_data, uint8_t msg, uint32_t handle, void* pParam); #endif
veraicon/TeamTalk
server/src/base/ostype.h
C
apache-2.0
2,334