answer
stringlengths
15
1.25M
angular.module('ualib.imageCarousel', ['angular-carousel']) .constant('VIEW_IMAGES_URL', '//wwwdev2.lib.ua.edu/erCarousel/api/slides/active') .factory('<API key>', ['$http', 'VIEW_IMAGES_URL', function <API key>($http, url){ return { getData: function(){ return $http({method: 'GET', url: url, params: {}}); } }; }]) .controller('imageCarouselCtrl', ['$scope', '$q', '<API key>', function imageCarouselCtrl($scope, $q, <API key>){ $scope.slides = null; function loadImages(slides, i, len, deferred){ i = i ? i : 0; len = len ? len : slides.length; deferred = deferred ? deferred : $q.defer(); if (len < 1){ deferred.resolve(slides); } else{ var image = new Image(); image.onload = function(){ slides[i].styles = 'url('+this.src+')'; slides[i].image = this; if (i+1 === len){ deferred.resolve(slides); } else { i++; loadImages(slides, i, len, deferred); } }; image.src = slides[i].image; } return deferred.promise; } <API key>.getData() .success(function(data) { loadImages(data.slides).then(function(slides){ $scope.slides = slides; }); }) .error(function(data, status, headers, config) { console.log(data); }); }]) .directive('ualibImageCarousel', [ function() { return { restrict: 'AC', controller: 'imageCarouselCtrl', link: function(scope, elm, attrs, Ctrl){ var toggleLock = false; scope.isLocked = false; scope.pause = function(){ toggleLock = true; scope.isLocked = true; }; scope.play = function(){ toggleLock = false; scope.isLocked = false; }; scope.mouseToggle = function(){ if (!toggleLock){ scope.isLocked = !scope.isLocked; } }; } }; }]);
import { ListWrapper } from 'angular2/src/facade/collection'; import { stringify, isBlank } from 'angular2/src/facade/lang'; import { BaseException, WrappedException } from 'angular2/src/facade/exceptions'; function <API key>(keys) { var res = []; for (var i = 0; i < keys.length; ++i) { if (ListWrapper.contains(res, keys[i])) { res.push(keys[i]); return res; } else { res.push(keys[i]); } } return res; } function <API key>(keys) { if (keys.length > 1) { var reversed = <API key>(ListWrapper.reversed(keys)); var tokenStrs = reversed.map(k => stringify(k.token)); return " (" + tokenStrs.join(' -> ') + ")"; } else { return ""; } } /** * Base class for all errors arising from misconfigured providers. */ export class <API key> extends BaseException { constructor(injector, key, <API key>) { super("DI Exception"); this.keys = [key]; this.injectors = [injector]; this.<API key> = <API key>; this.message = this.<API key>(this.keys); } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); this.message = this.<API key>(this.keys); } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } export class NoProviderError extends <API key> { constructor(injector, key) { super(injector, key, function (keys) { var first = stringify(ListWrapper.first(keys).token); return `No provider for ${first}!${<API key>(keys)}`; }); } } export class <API key> extends <API key> { constructor(injector, key) { super(injector, key, function (keys) { return `Cannot instantiate cyclic dependency!${<API key>(keys)}`; }); } } export class InstantiationError extends WrappedException { constructor(injector, originalException, originalStack, key) { super("DI Exception", originalException, originalStack, null); this.keys = [key]; this.injectors = [injector]; } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); } get wrapperMessage() { var first = stringify(ListWrapper.first(this.keys).token); return `Error during instantiation of ${first}!${<API key>(this.keys)}.`; } get causeKey() { return this.keys[0]; } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } export class <API key> extends BaseException { constructor(provider) { super("Invalid provider - only instances of Provider and Type are allowed, got: " + provider.toString()); } } export class NoAnnotationError extends BaseException { constructor(typeOrFunc, params) { super(NoAnnotationError._genMessage(typeOrFunc, params)); } static _genMessage(typeOrFunc, params) { var signature = []; for (var i = 0, ii = params.length; i < ii; i++) { var parameter = params[i]; if (isBlank(parameter) || parameter.length == 0) { signature.push('?'); } else { signature.push(parameter.map(stringify).join(' ')); } } return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" + signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.'; } } export class OutOfBoundsError extends BaseException { constructor(index) { super(`Index ${index} is out-of-bounds.`); } } // TODO: add a working example after alpha38 is released export class <API key> extends BaseException { constructor(provider1, provider2) { super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " + provider2.toString()); } } //# sourceMappingURL=exceptions.js.map
Map Navigation Hash (History) =================== # Overview Uses dojo/router to enable zooming to next or previous extent using the browser forward and back buttons. The geographic map center and map zoom level is placed on the url. # CMV Configuration Include the following code in js/config/viewer.js: javascript navhash: { include: true, id: 'navhash', type: 'invisible', path: 'viewer/dijit/MapNavigationHash/MapNavigationHash', title: 'Map Navigation Hash', options: { map: true } } # Usage Example appurl.com/index.htlm#/_longitude_/_latitude_/_zoomLevel_ The application will automatically update the url hash on pan and zoom. Users may also manually edit the route to go to a specific long, lat, and zoom level. A user can bookmark the url in the browser and, on load, the app will zoom and pan to the bookmarked location. [Click for demo](http://brianbunker.github.com/cmv-widgets) Screen from Sample page: ![Screenshot](./screenshot.png)
function SendItemsToOutput { Param ( [parameter()] [PSObject[]]$items, [parameter(Mandatory=$true)] [string[]]$typeName ) foreach ($i in $items) { $i.PSObject.TypeNames.Insert(0, $typeName) Write-Output $i } }
<?php namespace Codeception\Command; use Codeception\Configuration; use Codeception\Lib\Generator\Snapshot as SnapshotGenerator; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Generates Snapshot. * Snapshot can be used to test dynamical data. * If suite name is provided, an actor class will be included into placeholder * * * `codecept g:snapshot UserEmails` * * `codecept g:snapshot Products` * * `codecept g:snapshot acceptance UserEmails` */ class GenerateSnapshot extends Command { use Shared\FileSystem; use Shared\Config; protected function configure() { $this->setDefinition([ new InputArgument('suite', InputArgument::REQUIRED, 'Suite name or snapshot name)'), new InputArgument('snapshot', InputArgument::OPTIONAL, 'Name of snapshot'), ]); parent::configure(); } public function getDescription() { return 'Generates empty Snapshot class'; } public function execute(InputInterface $input, OutputInterface $output) { $suite = $input->getArgument('suite'); $class = $input->getArgument('snapshot'); if (!$class) { $class = $suite; $suite = null; } $conf = $suite ? $this->getSuiteConfig($suite) : $this->getGlobalConfig(); if ($suite) { $suite = DIRECTORY_SEPARATOR . ucfirst($suite); } $path = $this->createDirectoryFor(Configuration::supportDir() . 'Snapshot' . $suite, $class); $filename = $path . $this->getShortClassName($class) . '.php'; $output->writeln($filename); $gen = new SnapshotGenerator($conf, ucfirst($suite) . '\\' . $class); $res = $this->createFile($filename, $gen->produce()); if (!$res) { $output->writeln("<error>Snapshot $filename already exists</error>"); exit; } $output->writeln("<info>Snapshot was created in $filename</info>"); } }
import {ENTER} from '@angular/cdk/keycodes'; import {CommonModule} from '@angular/common'; import {NgModule} from '@angular/core'; import { ErrorStateMatcher, MatCommonModule, MatRippleModule, } from '@angular/<API key>/mdc-core'; import {MatChip, <API key>} from './chip'; import {<API key>, <API key>} from './<API key>'; import {MatChipEditInput} from './chip-edit-input'; import {MatChipGrid} from './chip-grid'; import {MatChipAvatar, MatChipRemove, MatChipTrailingIcon} from './chip-icons'; import {MatChipInput} from './chip-input'; import {MatChipListbox} from './chip-listbox'; import {MatChipRow} from './chip-row'; import {MatChipOption} from './chip-option'; import {MatChipSet} from './chip-set'; const CHIP_DECLARATIONS = [ MatChip, MatChipAvatar, <API key>, MatChipEditInput, MatChipGrid, MatChipInput, MatChipListbox, MatChipOption, MatChipRemove, MatChipRow, MatChipSet, MatChipTrailingIcon, ]; @NgModule({ imports: [MatCommonModule, CommonModule, MatRippleModule], exports: [MatCommonModule, CHIP_DECLARATIONS], declarations: CHIP_DECLARATIONS, providers: [ ErrorStateMatcher, { provide: <API key>, useValue: { separatorKeyCodes: [ENTER] } as <API key> } ] }) export class MatChipsModule { }
// by DotNetNuke Corporation // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // of the Software. // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Net; using System.Net.Http; using System.Threading; using System.Web; using System.Web.Http; using DotNetNuke.Application; using DotNetNuke.Common; using DotNetNuke.Entities.Controllers; using DotNetNuke.Entities.Portals; using DotNetNuke.Services.Localization; using DotNetNuke.Web.Api; namespace DotNetNuke.Web.InternalServices { [RequireHost] public class <API key> : DnnApiController { private const string <API key> = "<API key>{0}"; private const string <API key> = "<API key>{0}"; public class ClosePageDto { public bool IsHidden { get; set; } } public class EmailDto { public string Email { get; set; } } [HttpGet] public HttpResponseMessage <API key>() { var isHidden = HostController.Instance.GetBoolean(String.Format(<API key>, PortalSettings.UserId), false); var userEmailAddress = PortalSettings.UserInfo.Email; var request = HttpContext.Current.Request; var builder = new UriBuilder { Scheme = request.Url.Scheme, Host = "www.dnnsoftware.com", Path = "Community/Download/Manuals", Query = "src=dnn" // parameter to judge the effectiveness of this as a channel (i.e. the number of click through) }; var userManualUrl = builder.Uri.AbsoluteUri; return Request.CreateResponse(HttpStatusCode.OK, new { IsHidden = isHidden, EmailAddress = userEmailAddress, UserManualUrl = userManualUrl }); } [HttpPost] public HttpResponseMessage <API key>(ClosePageDto dto) { HostController.Instance.Update(String.Format(<API key>, PortalSettings.UserId), dto.IsHidden.ToString()); HostController.Instance.Update(String.Format(<API key>, PortalSettings.UserId), "false"); return Request.CreateResponse(HttpStatusCode.OK, "Success"); } [HttpPost] public HttpResponseMessage <API key>(EmailDto dto) { HostController.Instance.Update("<API key>", dto.Email); return Request.CreateResponse(HttpStatusCode.OK, "Success"); } [HttpGet] public HttpResponseMessage GetContentUrl() { var request = HttpContext.Current.Request; var builder = new UriBuilder { Scheme = request.Url.Scheme, Host = "www.dnnsoftware.com", Path = String.Format("DesktopModules/DNNCorp/GettingStarted/{0}/{1}/index.html", DotNetNukeContext.Current.Application.Name.Replace(".", "_"), DotNetNukeContext.Current.Application.Version.ToString(3)), Query = String.Format("locale={0}", Thread.CurrentThread.CurrentUICulture) }; var contentUrl = builder.Uri.AbsoluteUri; var fallbackUrl = Globals.AddHTTP(request.Url.Host + Globals.ResolveUrl("~/Portals/_default/<API key>.htm")); var isValid = IsValidUrl(contentUrl); return Request.CreateResponse(HttpStatusCode.OK, new { Url = isValid ? contentUrl : fallbackUrl }); } <summary> Checks if url does not return server or protocol errors </summary> <param name="url">Url to check</param> <returns></returns> private static bool IsValidUrl(string url) { HttpWebResponse response = null; try { var request = WebRequest.Create(url); request.Timeout = 5000; // set the timeout to 5 seconds to keep the user from waiting too long for the page to load request.Method = "HEAD"; // get only the header information - no need to download any content response = request.GetResponse() as HttpWebResponse; if (response == null) { return false; } var statusCode = (int)response.StatusCode; if (statusCode >= 500 && statusCode <= 510) // server errors { return false; } } catch { return false; } finally { if (response != null) { response.Close(); } } return true; } } }
// Help functions /* * Return a string with all helper functions whose name contains the 'substring'; * if the 'searchDescription' is true, then also search the function description"); */ function getHelp(substring, searchDescription) { return framework.getJavaScriptHelp(".*(?i:" + substring + ").*", searchDescription); } framework.addJavaScriptHelp("help", "substring, fileName", "output all the helper functions whose name contains the given 'substring'"); function help(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, false), fileName); } else if (arguments.length > 0) { write(getHelp(substring, false)); } else { write(getHelp("", false)); } } framework.addJavaScriptHelp("apropos", "substring, fileName", "output all the helper functions whose name or description contains the given 'substring'"); function apropos(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, true), fileName); } else if (arguments.length > 0) { write(getHelp(substring, true)); } else { write(getHelp("", true)); } } framework.addJavaScriptHelp("helpRegex", "regex, fileName", "output all helper functions whose name matches 'regex'"); function helpRegex(regex, fileName) { if (arguments.length > 1) { write(framework.getJavaScriptHelp(regex, false), fileName); } else if (arguments.length > 0) { write(framework.getJavaScriptHelp(regex, false)); } }
FullCalendar.globalLocales.push(function () { 'use strict'; var it = { code: 'it', week: { dow: 1, // Monday is the first day of the week. doy: 4, // The week that contains Jan 4th is the first week of the year. }, buttonText: { prev: 'Prec', next: 'Succ', today: 'Oggi', month: 'Mese', week: 'Settimana', day: 'Giorno', list: 'Agenda', }, weekText: 'Sm', allDayText: 'Tutto il giorno', moreLinkText(n) { return '+altri ' + n }, noEventsText: 'Non ci sono eventi da visualizzare', }; return it; }());
// Use of this source code is governed by a BSD-style package get import ( "errors" "internal/testenv" "io/ioutil" "os" "path" "path/filepath" "testing" "cmd/go/internal/web" ) // Test that <API key> creates the correct RepoRoot for a given importPath. // TODO(cmang): Add tests for SVN and BZR. func <API key>(t *testing.T) { testenv.<API key>(t) tests := []struct { path string want *repoRoot }{ { "github.com/golang/groupcache", &repoRoot{ vcs: vcsGit, repo: "https://github.com/golang/groupcache", }, }, // Unicode letters in directories (issue 18660). { "github.com/user/unicode/испытание", &repoRoot{ vcs: vcsGit, repo: "https://github.com/user/unicode", }, }, // IBM DevOps Services tests { "hub.jazz.net/git/user1/pkgname", &repoRoot{ vcs: vcsGit, repo: "https://hub.jazz.net/git/user1/pkgname", }, }, { "hub.jazz.net/git/user1/pkgname/submodule/submodule/submodule", &repoRoot{ vcs: vcsGit, repo: "https://hub.jazz.net/git/user1/pkgname", }, }, { "hub.jazz.net", nil, }, { "hub2.jazz.net", nil, }, { "hub.jazz.net/someotherprefix", nil, }, { "hub.jazz.net/someotherprefix/user1/pkgname", nil, }, // Spaces are not valid in user names or package names { "hub.jazz.net/git/User 1/pkgname", nil, }, { "hub.jazz.net/git/user1/pkg name", nil, }, // Dots are not valid in user names { "hub.jazz.net/git/user.1/pkgname", nil, }, { "hub.jazz.net/git/user/pkg.name", &repoRoot{ vcs: vcsGit, repo: "https://hub.jazz.net/git/user/pkg.name", }, }, // User names cannot have uppercase letters { "hub.jazz.net/git/USER/pkgname", nil, }, // OpenStack tests { "git.openstack.org/openstack/swift", &repoRoot{ vcs: vcsGit, repo: "https://git.openstack.org/openstack/swift", }, }, // Trailing .git is less preferred but included for // compatibility purposes while the same source needs to // be compilable on both old and new go { "git.openstack.org/openstack/swift.git", &repoRoot{ vcs: vcsGit, repo: "https://git.openstack.org/openstack/swift.git", }, }, { "git.openstack.org/openstack/swift/go/hummingbird", &repoRoot{ vcs: vcsGit, repo: "https://git.openstack.org/openstack/swift", }, }, { "git.openstack.org", nil, }, { "git.openstack.org/openstack", nil, }, // Spaces are not valid in package name { "git.apache.org/package name/path/to/lib", nil, }, // Should have ".git" suffix { "git.apache.org/package-name/path/to/lib", nil, }, { "git.apache.org/package-name.git", &repoRoot{ vcs: vcsGit, repo: "https://git.apache.org/package-name.git", }, }, { "git.apache.org/package-name_2.x.git/path/to/lib", &repoRoot{ vcs: vcsGit, repo: "https://git.apache.org/package-name_2.x.git", }, }, { "chiselapp.com/user/kyle/repository/fossilgg", &repoRoot{ vcs: vcsFossil, repo: "https://chiselapp.com/user/kyle/repository/fossilgg", }, }, { // must have a user/$name/repository/$repo path "chiselapp.com/kyle/repository/fossilgg", nil, }, { "chiselapp.com/user/kyle/fossilgg", nil, }, } for _, test := range tests { got, err := <API key>(test.path, web.Secure) want := test.want if want == nil { if err == nil { t.Errorf("<API key>(%q): Error expected but not received", test.path) } continue } if err != nil { t.Errorf("<API key>(%q): %v", test.path, err) continue } if got.vcs.name != want.vcs.name || got.repo != want.repo { t.Errorf("<API key>(%q) = VCS(%s) Repo(%s), want VCS(%s) Repo(%s)", test.path, got.vcs, got.repo, want.vcs, want.repo) } } } // Test that vcsFromDir correctly inspects a given directory and returns the right VCS and root. func TestFromDir(t *testing.T) { tempDir, err := ioutil.TempDir("", "vcstest") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempDir) for j, vcs := range vcsList { dir := filepath.Join(tempDir, "example.com", vcs.name, "."+vcs.cmd) if j&1 == 0 { err := os.MkdirAll(dir, 0755) if err != nil { t.Fatal(err) } } else { err := os.MkdirAll(filepath.Dir(dir), 0755) if err != nil { t.Fatal(err) } f, err := os.Create(dir) if err != nil { t.Fatal(err) } f.Close() } want := repoRoot{ vcs: vcs, root: path.Join("example.com", vcs.name), } var got repoRoot got.vcs, got.root, err = vcsFromDir(dir, tempDir) if err != nil { t.Errorf("FromDir(%q, %q): %v", dir, tempDir, err) continue } if got.vcs.name != want.vcs.name || got.root != want.root { t.Errorf("FromDir(%q, %q) = VCS(%s) Root(%s), want VCS(%s) Root(%s)", dir, tempDir, got.vcs, got.root, want.vcs, want.root) } } } func TestIsSecure(t *testing.T) { tests := []struct { vcs *vcsCmd url string secure bool }{ {vcsGit, "http://example.com/foo.git", false}, {vcsGit, "https://example.com/foo.git", true}, {vcsBzr, "http://example.com/foo.bzr", false}, {vcsBzr, "https://example.com/foo.bzr", true}, {vcsSvn, "http://example.com/svn", false}, {vcsSvn, "https://example.com/svn", true}, {vcsHg, "http://example.com/foo.hg", false}, {vcsHg, "https://example.com/foo.hg", true}, {vcsGit, "ssh://user@example.com/foo.git", true}, {vcsGit, "user@server:path/to/repo.git", false}, {vcsGit, "user@server:", false}, {vcsGit, "server:repo.git", false}, {vcsGit, "server:path/to/repo.git", false}, {vcsGit, "example.com:path/to/repo.git", false}, {vcsGit, "path/that/contains/a:colon/repo.git", false}, {vcsHg, "ssh://user@example.com/path/to/repo.hg", true}, {vcsFossil, "http://example.com/foo", false}, {vcsFossil, "https://example.com/foo", true}, } for _, test := range tests { secure := test.vcs.isSecure(test.url) if secure != test.secure { t.Errorf("%s isSecure(%q) = %t; want %t", test.vcs, test.url, secure, test.secure) } } } func <API key>(t *testing.T) { tests := []struct { vcs *vcsCmd url string secure bool }{ // Same as TestIsSecure to verify same behavior. {vcsGit, "http://example.com/foo.git", false}, {vcsGit, "https://example.com/foo.git", true}, {vcsBzr, "http://example.com/foo.bzr", false}, {vcsBzr, "https://example.com/foo.bzr", true}, {vcsSvn, "http://example.com/svn", false}, {vcsSvn, "https://example.com/svn", true}, {vcsHg, "http://example.com/foo.hg", false}, {vcsHg, "https://example.com/foo.hg", true}, {vcsGit, "user@server:path/to/repo.git", false}, {vcsGit, "user@server:", false}, {vcsGit, "server:repo.git", false}, {vcsGit, "server:path/to/repo.git", false}, {vcsGit, "example.com:path/to/repo.git", false}, {vcsGit, "path/that/contains/a:colon/repo.git", false}, {vcsHg, "ssh://user@example.com/path/to/repo.hg", true}, // New behavior. {vcsGit, "ssh://user@example.com/foo.git", false}, {vcsGit, "foo://example.com/bar.git", true}, {vcsHg, "foo://example.com/bar.hg", false}, {vcsSvn, "foo://example.com/svn", false}, {vcsBzr, "foo://example.com/bar.bzr", false}, } defer os.Unsetenv("GIT_ALLOW_PROTOCOL") os.Setenv("GIT_ALLOW_PROTOCOL", "https:foo") for _, test := range tests { secure := test.vcs.isSecure(test.url) if secure != test.secure { t.Errorf("%s isSecure(%q) = %t; want %t", test.vcs, test.url, secure, test.secure) } } } func TestMatchGoImport(t *testing.T) { tests := []struct { imports []metaImport path string mi metaImport err error }{ { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo", mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/", mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo", mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/fooa", mi: metaImport{Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar/baz", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar/baz/qux", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar/baz/", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com", err: errors.New("pathologically short path"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "different.example.com/user/foo", err: errors.New("meta tags do not match import path"), }, } for _, test := range tests { mi, err := matchGoImport(test.imports, test.path) if mi != test.mi { t.Errorf("unexpected metaImport; got %v, want %v", mi, test.mi) } got := err want := test.err if (got == nil) != (want == nil) { t.Errorf("unexpected error; got %v, want %v", got, want) } } } func <API key>(t *testing.T) { tests := []struct { root string err string }{ { root: "", err: "no scheme", }, { root: "http: err: "", }, { root: "a: err: "", }, { root: "a err: "invalid scheme", }, { root: "-config: err: "invalid scheme", }, } for _, test := range tests { err := <API key>(test.root) if err == nil { if test.err != "" { t.Errorf("<API key>(%q) = nil, want %q", test.root, test.err) } } else if test.err == "" { if err != nil { t.Errorf("<API key>(%q) = %q, want nil", test.root, test.err) } } else if err.Error() != test.err { t.Errorf("<API key>(%q) = %q, want %q", test.root, err, test.err) } } }
{% if site.staticman.repository and site.staticman.branch %} <div class="staticman-comments"> <div class="page__comments"> <!-- Start static comments --> <div class="js-comments"> {% if site.data.comments[page.slug] %} <h3 class="<API key>">{{ site.data.ui-text[site.locale].comments_title | default: "Comments" }}</h3> {% assign comments = site.data.comments[page.slug] | sort %} {% for comment in comments %} {% assign email = comment[1].email %} {% assign name = comment[1].name %} {% assign url = comment[1].url %} {% assign date = comment[1].date %} {% assign message = comment[1].message %} {% include staticman-comment.html index=forloop.index email=email name=name url=url date=date message=message %} {% endfor %} {% endif %} </div> <!-- End static comments --> <!-- Start new comment form --> <div class="page__comments-form"> <h3 class="<API key>">{{ site.data.ui-text[site.locale].comments_label | default: "Leave a Comment" }}</h3> <p class="small">{{ site.data.ui-text[site.locale].comment_form_info | default: "Your email address will not be published. Required fields are marked" }} <span class="required">*</span></p> <form id="new_comment" class="page__comments-form js-form form" method="post"> <div class="form-group"> <label for="<API key>">{{ site.data.ui-text[site.locale].<API key> | default: "Comment" }} <small class="required">*</small></label><br> <textarea type="text" rows="12" cols="36" id="<API key>" name="fields[message]" tabindex="1"></textarea> <div class="small help-block"><a href="https://daringfireball.net/projects/markdown/">{{ site.data.ui-text[site.locale].<API key> | default: "Markdown is supported." }}</a></div> </div> <div class="form-group"> <label for="comment-form-name">{{ site.data.ui-text[site.locale].<API key> | default: "Name" }} <small class="required">*</small></label> <input type="text" id="comment-form-name" name="fields[name]" tabindex="2" /> </div> <div class="form-group"> <label for="comment-form-email">{{ site.data.ui-text[site.locale].<API key> | default: "Email address" }} <small class="required">*</small></label> <input type="email" id="comment-form-email" name="fields[email]" tabindex="3" /> </div> <div class="form-group"> <label for="comment-form-url">{{ site.data.ui-text[site.locale].<API key> | default: "Website (optional)" }}</label> <input type="url" id="comment-form-url" name="fields[url]" tabindex="4"/> </div> <div class="form-group hidden" style="display: none;"> <input type="hidden" name="options[origin]" value="{{ page.url | absolute_url }}"> <input type="hidden" name="options[slug]" value="{{ page.slug }}"> <label for="<API key>">Not used. Leave blank if you are a human.</label> <input type="text" id="<API key>" name="fields[hidden]" autocomplete="off"/> {% if site.staticman.reCaptcha.siteKey %}<input type="hidden" name="options[reCaptcha][siteKey]" value="{{ site.staticman.reCaptcha.siteKey }}">{% endif %} {% if site.staticman.reCaptcha.secret %}<input type="hidden" name="options[reCaptcha][secret]" value="{{ site.staticman.reCaptcha.secret }}">{% endif %} </div> <!-- Start comment form alert messaging --> <p class="hidden js-notice"> <strong class="<API key> hidden">{{ site.data.ui-text[site.locale].comment_success_msg | default: "Thanks for your comment! It will show on the site once it has been approved." }}</strong> <strong class="<API key> hidden">{{ site.data.ui-text[site.locale].comment_error_msg | default: "Sorry, there was an error with your submission. Please make sure all required fields have been completed and try again." }}</strong> </p> <!-- End comment form alert messaging --> {% if site.staticman.reCaptcha.siteKey %} <div class="form-group"> <div class="g-recaptcha" data-sitekey="{{ site.staticman.reCaptcha.siteKey }}"></div> </div> {% endif %} <div class="form-group"> <button type="submit" id="comment-form-submit" tabindex="5" class="btn btn--primary btn--large">{{ site.data.ui-text[site.locale].comment_btn_submit | default: "Submit Comment" }}</button> <button type="submit" id="<API key>" tabindex="5" class="btn btn--primary btn--large hidden" disabled>{{ site.data.ui-text[site.locale].<API key> | default: "Submitted" }}</button> </div> </form> </div> <!-- End new comment form --> <!-- Load reCaptcha if site key is set --> {% if site.staticman.reCaptcha.siteKey %} <script async src="https: {% endif %} </div> <!-- Load script to handle comment form submission --> <!-- doing something a bit funky here because I want to be careful not to include JQuery twice! --> <script> if (typeof jQuery == 'undefined') { document.write('<script src="{{ "/js/jquery-1.11.2.min.js" | relative_url }}"></scr' + 'ipt>'); } </script> <script src="{{ "/js/staticman.js" | relative_url }}"></script> </div> {% endif %}
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData // package to your project. /#define <API key> using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Web; using System.Web.Http; #if <API key> using System.Web.Http.OData; #endif namespace TheBigCatProject.Server.Areas.HelpPage { <summary> Use this class to customize the Help Page. For example you can set a custom <see cref="System.Web.Http.Description.<API key>"/> to supply the documentation or you can provide the samples for the requests/responses. </summary> public static class HelpPageConfig { [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "TheBigCatProject.Server.Areas.HelpPage.TextSample.#ctor(System.String)", Justification = "End users may choose to merge this string with existing localized resources.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "bsonspec", Justification = "Part of a URI.")] public static void Register(HttpConfiguration config) { / Uncomment the following to use the documentation from XML documentation file. //config.<API key>(new <API key>(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); / Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. / Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type / formats by the available formatters. //config.SetSampleObjects(new Dictionary<Type, object> // {typeof(string), "sample string"}, // {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}} // Extend the following to provide factories for types not handled automatically (those lacking parameterless // constructors) or for which you prefer to use non-default property values. Line below provides a fallback // since automatic handling will fail and GeneratePageResult handles only a single type. #if <API key> config.<API key>().<API key>.Add(GeneratePageResult); #endif // Extend the following to use a preset object directly as the sample for all actions that support a media // type, regardless of the body parameter or return type. The lines below avoid display of binary content. // The <API key> (if available) is not used to serialize the TextSample object. config.<API key>( new TextSample("Binary JSON content. See http://bsonspec.org for details."), new <API key>("application/bson")); / Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format / and have IEnumerable<string> as the body parameter or return type. //config.SetSampleForType("[0]=foo&[1]=bar", new <API key>("application/<API key>"), typeof(IEnumerable<string>)); / Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" / and action named "Put". //config.SetSampleRequest("1234", new <API key>("text/plain"), "Values", "Put"); / Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" / on the controller named "Values" and action named "Get" with parameter "id". //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new <API key>("image/png"), "Values", "Get", "id"); / Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>. / The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. //config.<API key>(typeof(string), "Values", "Get"); / Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>. / The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. //config.<API key>(typeof(string), "Values", "Post"); } #if <API key> private static object GeneratePageResult(<API key> sampleGenerator, Type type) { if (type.IsGenericType) { Type openGenericType = type.<API key>(); if (openGenericType == typeof(PageResult<>)) { // Get the T in PageResult<T> Type[] typeParameters = type.GetGenericArguments(); Debug.Assert(typeParameters.Length == 1); // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor Type itemsType = typeof(List<>).MakeGenericType(typeParameters); object items = sampleGenerator.GetSampleObject(itemsType); // Fill in the other information needed to invoke the PageResult<T> constuctor Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; object[] parameters = new object[] { items, null, (long)ObjectGenerator.<API key>, }; // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor ConstructorInfo constructor = type.GetConstructor(parameterTypes); return constructor.Invoke(parameters); } } return null; } #endif } }
<?php namespace Hateoas\Tests\Expression; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\ExpressionLanguage\Node\Node; use Symfony\Component\ExpressionLanguage\ParsedExpression; use Hateoas\Tests\TestCase; use Hateoas\Expression\ExpressionEvaluator; use Hateoas\Expression\<API key>; class <API key> extends TestCase { public function testNullEvaluate() { $<API key> = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $<API key> ->parse($this->arg->any()) ->shouldNotBeCalled() ; $expressionEvaluator = new ExpressionEvaluator($<API key>->reveal()); $this ->string($expressionEvaluator->evaluate('hello', null)) ->isEqualTo('hello') ; } public function testEvaluate() { $data = new \StdClass(); $<API key> = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $<API key> ->parse('"42"', array('object')) ->willReturn($parsedExpression = new ParsedExpression('', new Node())) ; $<API key> ->evaluate($parsedExpression, array('object' => $data)) ->willReturn('42') ; $expressionEvaluator = new ExpressionEvaluator($<API key>->reveal()); $this ->string($expressionEvaluator->evaluate('expr("42")', $data)) ->isEqualTo('42') ; } public function testEvaluateArray() { $parsedExpressions = array( new ParsedExpression('a', new Node()), new ParsedExpression('aa', new Node()), new ParsedExpression('aaa', new Node()), ); $data = new \StdClass(); $ELProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $ELProphecy->parse('a', array('object'))->willReturn($parsedExpressions[0])->shouldBeCalledTimes(1); $ELProphecy->parse('aa', array('object'))->willReturn($parsedExpressions[1])->shouldBeCalledTimes(1); $ELProphecy->parse('aaa', array('object'))->willReturn($parsedExpressions[2])->shouldBeCalledTimes(1); $ELProphecy->evaluate($parsedExpressions[0], array('object' => $data))->willReturn(1); $ELProphecy->evaluate($parsedExpressions[1], array('object' => $data))->willReturn(2); $ELProphecy->evaluate($parsedExpressions[2], array('object' => $data))->willReturn(3); $expressionEvaluator = new ExpressionEvaluator($ELProphecy->reveal()); $array = array( 'expr(a)' => 'expr(aa)', 'hello' => array('expr(aaa)'), ); $this ->array($expressionEvaluator->evaluateArray($array, $data)) ->isEqualTo(array( 1 => 2, 'hello' => array(3), )) ; } public function <API key>() { $data = new \StdClass(); $<API key> = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $<API key> ->parse('name', array('name', 'object')) ->willReturn($parsedExpression = new ParsedExpression('', new Node())) ->shouldBeCalledTimes(1) ; $<API key> ->evaluate($parsedExpression, array('object' => $data, 'name' => 'Adrien')) ->willReturn('Adrien') ->shouldBeCalledTimes(1) ; $expressionEvaluator = new ExpressionEvaluator($<API key>->reveal()); $expressionEvaluator->setContextVariable('name', 'Adrien'); $this ->string($expressionEvaluator->evaluate('expr(name)', $data)) ->isEqualTo('Adrien') ; } public function <API key>() { $expressionEvaluator = new ExpressionEvaluator(new ExpressionLanguage()); $expressionEvaluator->registerFunction(new <API key>()); $this ->string($expressionEvaluator->evaluate('expr(hello("toto"))', null)) ->isEqualTo('Hello, toto!') ; } } class <API key> implements <API key> { public function getName() { return 'hello'; } public function getCompiler() { return function ($value) { return sprintf('$hello_helper->hello(%s)', $value); }; } public function getEvaluator() { return function (array $context, $value) { return $context['hello_helper']->hello($value); }; } public function getContextVariables() { return array('hello_helper' => $this); } public function hello($name) { return sprintf('Hello, %s!', $name); } }
<?php /** * Pro customizer section. * * @since 1.0.0 * @access public */ class Epsilon_Section_Pro extends <API key> { /** * The type of customize section being rendered. * * @since 1.0.0 * @access public * @var string */ public $type = 'epsilon-section-pro'; /** * Custom pro button URL. * * @since 1.0.0 * @access public * @var string */ public $button_url = ''; /** * Custom pro button text. * * @since 1.0.0 * @access public * @var string */ public $button_text = ''; /** * Used to disable the upsells * * @var bool */ public $allowed = true; /** * Epsilon_Section_Pro constructor. * * @param <API key> $manager * @param string $id * @param array $args */ public function __construct( <API key> $manager, $id, array $args = array() ) { $this->allowed = apply_filters( '<API key>', true ); $manager-><API key>( 'Epsilon_Section_Pro' ); parent::__construct( $manager, $id, $args ); } /** * Add custom parameters to pass to the JS via JSON. * * @since 1.0.0 * @access public */ public function json() { $json = parent::json(); $json['button_url'] = $this->button_url; $json['button_text'] = esc_html( $this->button_text ); $json['allowed'] = $this->allowed; return $json; } /** * Outputs the Underscore.js template. * * @since 1.0.0 * @access public * @return void */ protected function render_template() { ?> <?php if ( $this->allowed ) : //@formatter:off ?> <li id="accordion-section-{{ data.id }}" class="accordion-section control-section control-section-{{ data.type }} cannot-expand"> <h3 class="<API key> <API key>"> {{ data.title }} <# if ( data.button_url ) { #> <a href="{{ data.button_url }}" class="button alignright" target="_blank"> {{ data.button_text }}</a> < </h3> </li> <?php //@formatter:on ?> <?php endif; ?> <?php } }
<summary> This class handles user ID, session ID, time stamp, and sends a user message, optionally including system specs, when the game starts </summary> using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System; using System.Net; #if !UNITY_WEBPLAYER && !UNITY_NACL && !UNITY_FLASH && !UNITY_WP8 && !UNITY_METRO && !UNITY_PS3 using System.Net.NetworkInformation; using System.Security.Cryptography; using System.Text; #endif public class GA_GenericInfo { #region public values <summary> The ID of the user/player. A unique ID will be determined the first time the player plays. If an ID has already been created for a player this ID will be used. </summary> public string UserID { get { if ((_userID == null || _userID == string.Empty) && !GA.SettingsGA.CustomUserID) { _userID = GetUserUUID(); } return _userID; } } <summary> The ID of the current session. A unique ID will be determined when the game starts. This ID will be used for the remainder of the play session. </summary> public string SessionID { get { if (_sessionID == null) { _sessionID = GetSessionUUID(); } return _sessionID; } } <summary> The current UTC date/time in seconds </summary> /*public string TimeStamp { get { return ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(); } }*/ #endregion #region private values private string _userID = string.Empty; private string _sessionID; private bool _settingUserID; #endregion #region public methods <summary> Gets generic system information at the beginning of a play session </summary> <param name="inclSpecs"> Determines if all the system specs should be included <see cref="System.Bool"/> </param> <returns> The message to submit to the GA server is a dictionary of all the relevant parameters (containing user ID, session ID, system information, language information, date/time, build version) <see cref="Dictionary<System.String, System.Object>"/> </returns> public List<Hashtable> GetGenericInfo(string message) { List<Hashtable> systemspecs = new List<Hashtable>(); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "unity_sdk " + GA_Settings.VERSION, message)); #if !UNITY_IPHONE systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "os:"+SystemInfo.operatingSystem, message)); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "processor_type:"+SystemInfo.processorType, message)); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_name:"+SystemInfo.graphicsDeviceName, message)); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_version:"+SystemInfo.<API key>, message)); // Unity provides lots of additional system info which might be worth tracking for some games: //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "process_count:"+SystemInfo.processorCount.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sys_mem_size:"+SystemInfo.systemMemorySize.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_mem_size:"+SystemInfo.graphicsMemorySize.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_vendor:"+SystemInfo.<API key>, message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_id:"+SystemInfo.graphicsDeviceID.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_vendor_id:"+SystemInfo.<API key>.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_shader_level:"+SystemInfo.graphicsShaderLevel.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_pixel_fillrate:"+SystemInfo.<API key>.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_shadows:"+SystemInfo.supportsShadows.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_render_textures:"+SystemInfo.<API key>.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_image_effects:"+SystemInfo.<API key>.ToString(), message)); #else systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "os:iOS", message)); #endif return systemspecs; } <summary> Gets a universally unique ID to represent the user. User ID should be device specific to allow tracking across different games on the same device: -- Android uses <API key>. -- iOS/PC/Mac uses the first MAC addresses available. -- Webplayer uses <API key>. Note: The unique user ID is based on the ODIN specifications. See http://code.google.com/p/odinmobile/ for more information on ODIN. </summary> <returns> The generated UUID <see cref="System.String"/> </returns> public static string GetUserUUID() { #if UNITY_IPHONE && !UNITY_EDITOR string uid = GA.SettingsGA.GetUniqueIDiOS(); if (uid == null) { return ""; } else if (uid != "OLD") { if (uid.StartsWith("VENDOR-")) return uid.Remove(0, 7); else return uid; } #endif #if UNITY_ANDROID && !UNITY_EDITOR string uid = GA.SettingsGA.<API key>(); if (!string.IsNullOrEmpty(uid)) { return uid; } #endif #if UNITY_WEBPLAYER || UNITY_NACL || UNITY_WP8 || UNITY_METRO || UNITY_PS3 return SystemInfo.<API key>; #elif !UNITY_FLASH try { NetworkInterface[] nics = NetworkInterface.<API key>(); string mac = ""; foreach (NetworkInterface adapter in nics) { PhysicalAddress address = adapter.GetPhysicalAddress(); if (address.ToString() != "" && mac == "") { mac = GA_Submit.CreateSha1Hash(address.ToString()); } } return mac; } catch { return SystemInfo.<API key>; } #else return GetSessionUUID(); #endif } <summary> Gets a universally unique ID to represent the session. </summary> <returns> The generated UUID <see cref="System.String"/> </returns> public static string GetSessionUUID() { #if !UNITY_FLASH return Guid.NewGuid().ToString(); #else string returnValue = ""; for (int i = 0; i < 12; i++) { returnValue += UnityEngine.Random.Range(0, 10).ToString(); } return returnValue; #endif } <summary> Sets the session ID. If newSessionID is null then a random UUID will be generated, otherwise newSessionID will be used as the session ID. </summary> <param name="newSessionID">New session I.</param> public void SetSessionUUID(string newSessionID) { if (newSessionID == null) { _sessionID = GetSessionUUID(); } else { _sessionID = newSessionID; } } <summary> Do not call this method (instead use GA_static_api.Settings.SetCustomUserID)! Only the GA class should call this method. </summary> <param name="customID"> The custom user ID - this should be unique for each user </param> public void SetCustomUserID(string customID) { _userID = customID; } #endregion #region private methods <summary> Adds detailed system specifications regarding the users/players device to the parameters. </summary> <param name="parameters"> The parameters which will be sent to the server <see cref="Dictionary<System.String, System.Object>"/> </param> private Hashtable AddSystemSpecs(GA_Error.SeverityType severity, string type, string message) { string addmessage = ""; if (message != "") addmessage = ": " + message; Hashtable parameters = new Hashtable() { { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Severity], severity.ToString() }, { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Message], type + addmessage }, { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Level], GA.SettingsGA.CustomArea.Equals(string.Empty)?Application.loadedLevelName:GA.SettingsGA.CustomArea } }; return parameters; } <summary> Gets the users system type </summary> <returns> String determining the system the user is currently running <see cref="System.String"/> </returns> public static string GetSystem() { #if <API key> return "MAC"; #elif <API key> return "PC"; #elif UNITY_WEBPLAYER return "WEBPLAYER"; #elif UNITY_WII return "WII"; #elif UNITY_IPHONE return "IPHONE"; #elif UNITY_ANDROID return "ANDROID"; #elif UNITY_PS3 return "PS3"; #elif UNITY_XBOX360 return "XBOX"; #elif UNITY_FLASH return "FLASH"; #elif <API key> return "LINUX"; #elif UNITY_NACL return "NACL"; #elif <API key> return "DASHBOARD_WIDGET"; #elif UNITY_METRO return "WINDOWS_STORE_APP"; #elif UNITY_WP8 return "WINDOWS_PHONE_8"; #elif UNITY_BLACKBERRY return "BLACKBERRY"; #else return "UNKNOWN"; #endif } #endregion }
import {OverlayRef, <API key>} from '../core'; import {AnimationEvent} from '@angular/animations'; import {DialogPosition} from './dialog-config'; import {Observable} from 'rxjs/Observable'; import {Subject} from 'rxjs/Subject'; import {MdDialogContainer} from './dialog-container'; import 'rxjs/add/operator/filter'; // TODO(jelbourn): resizing // TODO(jelbourn): afterOpen and beforeClose /** * Reference to a dialog opened via the MdDialog service. */ export class MdDialogRef<T> { /** The instance of component opened into the dialog. */ componentInstance: T; /** Subject for notifying the user that the dialog has finished closing. */ private _afterClosed: Subject<any> = new Subject(); /** Result to be passed to afterClosed. */ private _result: any; constructor(private _overlayRef: OverlayRef, public _containerInstance: MdDialogContainer) { _containerInstance.<API key> .filter((event: AnimationEvent) => event.toState === 'exit') .subscribe(() => { this._overlayRef.dispose(); this.componentInstance = null; }, null, () => { this._afterClosed.next(this._result); this._afterClosed.complete(); }); } /** * Close the dialog. * @param dialogResult Optional result to return to the dialog opener. */ close(dialogResult?: any): void { this._result = dialogResult; this._containerInstance._state = 'exit'; this._overlayRef.detachBackdrop(); // Transition the backdrop in parallel with the dialog. } /** * Gets an observable that is notified when the dialog is finished closing. */ afterClosed(): Observable<any> { return this._afterClosed.asObservable(); } /** * Updates the dialog's position. * @param position New dialog position. */ updatePosition(position?: DialogPosition): this { let strategy = this.<API key>(); if (position && (position.left || position.right)) { position.left ? strategy.left(position.left) : strategy.right(position.right); } else { strategy.centerHorizontally(); } if (position && (position.top || position.bottom)) { position.top ? strategy.top(position.top) : strategy.bottom(position.bottom); } else { strategy.centerVertically(); } this._overlayRef.updatePosition(); return this; } /** * Updates the dialog's width and height. * @param width New width of the dialog. * @param height New height of the dialog. */ updateSize(width = 'auto', height = 'auto'): this { this.<API key>().width(width).height(height); this._overlayRef.updatePosition(); return this; } /** Fetches the position strategy object from the overlay ref. */ private <API key>(): <API key> { return this._overlayRef.getState().positionStrategy as <API key>; } }
import java.util.Comparator; abc.sort(Comparator.naturalOrder());
module RR module Errors class <API key> < RRError end end end
#include "../../../Common/Common.h" #if (ARCH == ARCH_XMEGA) #define <API key> #include "../Serial.h" FILE USARTSerialStream; int Serial_putchar(char DataByte, FILE *Stream) { USART_t* USART = fdev_get_udata(Stream); Serial_SendByte(USART, DataByte); return 0; } int Serial_getchar(FILE *Stream) { USART_t* USART = fdev_get_udata(Stream); if (!(<API key>(USART))) return _FDEV_EOF; return Serial_ReceiveByte(USART); } int <API key>(FILE *Stream) { USART_t* USART = fdev_get_udata(Stream); while (!(<API key>(USART))); return Serial_ReceiveByte(USART); } void Serial_SendString_P(USART_t* const USART, const char* FlashStringPtr) { uint8_t CurrByte; while ((CurrByte = pgm_read_byte(FlashStringPtr)) != 0x00) { Serial_SendByte(USART, CurrByte); FlashStringPtr++; } } void Serial_SendString(USART_t* const USART, const char* StringPtr) { uint8_t CurrByte; while ((CurrByte = *StringPtr) != 0x00) { Serial_SendByte(USART, CurrByte); StringPtr++; } } void Serial_SendData(USART_t* const USART, const void* Buffer, uint16_t Length) { while (Length Serial_SendByte(USART, *((uint8_t*)Buffer++)); } void Serial_CreateStream(USART_t* USART, FILE* Stream) { if (!(Stream)) { Stream = &USARTSerialStream; stdin = Stream; stdout = Stream; } *Stream = (FILE)FDEV_SETUP_STREAM(Serial_putchar, Serial_getchar, _FDEV_SETUP_RW); fdev_set_udata(Stream, USART); } void <API key>(USART_t* USART, FILE* Stream) { if (!(Stream)) { Stream = &USARTSerialStream; stdin = Stream; stdout = Stream; } *Stream = (FILE)FDEV_SETUP_STREAM(Serial_putchar, <API key>, _FDEV_SETUP_RW); fdev_set_udata(Stream, USART); } #endif
<?php namespace PhpOffice\PhpWord\Element; /** * Container abstract class * * @method Text addText(string $text, mixed $fStyle = null, mixed $pStyle = null) * @method TextRun addTextRun(mixed $pStyle = null) * @method Bookmark addBookmark(string $name) * @method Link addLink(string $target, string $text = null, mixed $fStyle = null, mixed $pStyle = null, boolean $internal = false) * @method PreserveText addPreserveText(string $text, mixed $fStyle = null, mixed $pStyle = null) * @method void addTextBreak(int $count = 1, mixed $fStyle = null, mixed $pStyle = null) * @method ListItem addListItem(string $txt, int $depth = 0, mixed $font = null, mixed $list = null, mixed $para = null) * @method ListItemRun addListItemRun(int $depth = 0, mixed $listStyle = null, mixed $pStyle = null) * @method Footnote addFootnote(mixed $pStyle = null) * @method Endnote addEndnote(mixed $pStyle = null) * @method CheckBox addCheckBox(string $name, $text, mixed $fStyle = null, mixed $pStyle = null) * @method Title addTitle(mixed $text, int $depth = 1) * @method TOC addTOC(mixed $fontStyle = null, mixed $tocStyle = null, int $minDepth = 1, int $maxDepth = 9) * @method PageBreak addPageBreak() * @method Table addTable(mixed $style = null) * @method Image addImage(string $source, mixed $style = null, bool $isWatermark = false, $name = null) * @method OLEObject addOLEObject(string $source, mixed $style = null) * @method TextBox addTextBox(mixed $style = null) * @method Field addField(string $type = null, array $properties = array(), array $options = array(), mixed $text = null) * @method Line addLine(mixed $lineStyle = null) * @method Shape addShape(string $type, mixed $style = null) * @method Chart addChart(string $type, array $categories, array $values, array $style = null, $seriesName = null) * @method FormField addFormField(string $type, mixed $fStyle = null, mixed $pStyle = null) * @method SDT addSDT(string $type) * * @method \PhpOffice\PhpWord\Element\OLEObject addObject(string $source, mixed $style = null) deprecated, use addOLEObject instead * * @since 0.10.0 */ abstract class AbstractContainer extends AbstractElement { /** * Elements collection * * @var \PhpOffice\PhpWord\Element\AbstractElement[] */ protected $elements = array(); /** * Container type Section|Header|Footer|Footnote|Endnote|Cell|TextRun|TextBox|ListItemRun|TrackChange * * @var string */ protected $container; /** * Magic method to catch all 'addElement' variation * * This removes addText, addTextRun, etc. When adding new element, we have to * add the model in the class docblock with `@method`. * * Warning: This makes capitalization matters, e.g. addCheckbox or addcheckbox won't work. * * @param mixed $function * @param mixed $args * @return \PhpOffice\PhpWord\Element\AbstractElement */ public function __call($function, $args) { $elements = array( 'Text', 'TextRun', 'Bookmark', 'Link', 'PreserveText', 'TextBreak', 'ListItem', 'ListItemRun', 'Table', 'Image', 'Object', 'OLEObject', 'Footnote', 'Endnote', 'CheckBox', 'TextBox', 'Field', 'Line', 'Shape', 'Title', 'TOC', 'PageBreak', 'Chart', 'FormField', 'SDT', 'Comment', ); $functions = array(); foreach ($elements as $element) { $functions['add' . strtolower($element)] = $element == 'Object' ? 'OLEObject' : $element; } // Run valid `add` command $function = strtolower($function); if (isset($functions[$function])) { $element = $functions[$function]; // Special case for TextBreak // @todo Remove the `$count` parameter in 1.0.0 to make this element similiar to other elements? if ($element == 'TextBreak') { list($count, $fontStyle, $paragraphStyle) = array_pad($args, 3, null); if ($count === null) { $count = 1; } for ($i = 1; $i <= $count; $i++) { $this->addElement($element, $fontStyle, $paragraphStyle); } } else { // All other elements array_unshift($args, $element); // Prepend element name to the beginning of args array return <API key>(array($this, 'addElement'), $args); } } return null; } /** * Add element * * Each element has different number of parameters passed * * @param string $elementName * @return \PhpOffice\PhpWord\Element\AbstractElement */ protected function addElement($elementName) { $elementClass = __NAMESPACE__ . '\\' . $elementName; $this->checkValidity($elementName); // Get arguments $args = func_get_args(); $withoutP = in_array($this->container, array('TextRun', 'Footnote', 'Endnote', 'ListItemRun', 'Field')); if ($withoutP && ($elementName == 'Text' || $elementName == 'PreserveText')) { $args[3] = null; // Remove paragraph style for texts in textrun } // Create element using reflection $reflection = new \ReflectionClass($elementClass); $elementArgs = $args; array_shift($elementArgs); // Shift the $elementName off the beginning of array /** @var \PhpOffice\PhpWord\Element\AbstractElement $element Type hint */ $element = $reflection->newInstanceArgs($elementArgs); // Set parent container $element->setParentContainer($this); $element->setElementIndex($this->countElements() + 1); $element->setElementId(); $this->elements[] = $element; return $element; } /** * Get all elements * * @return \PhpOffice\PhpWord\Element\AbstractElement[] */ public function getElements() { return $this->elements; } /** * Returns the element at the requested position * * @param int $index * @return \PhpOffice\PhpWord\Element\AbstractElement|null */ public function getElement($index) { if (array_key_exists($index, $this->elements)) { return $this->elements[$index]; } return null; } /** * Removes the element at requested index * * @param int|\PhpOffice\PhpWord\Element\AbstractElement $toRemove */ public function removeElement($toRemove) { if (is_int($toRemove) && array_key_exists($toRemove, $this->elements)) { unset($this->elements[$toRemove]); } elseif ($toRemove instanceof \PhpOffice\PhpWord\Element\AbstractElement) { foreach ($this->elements as $key => $element) { if ($element->getElementId() === $toRemove->getElementId()) { unset($this->elements[$key]); return; } } } } /** * Count elements * * @return int */ public function countElements() { return count($this->elements); } /** * Check if a method is allowed for the current container * * @param string $method * * @throws \<API key> * @return bool */ private function checkValidity($method) { $generalContainers = array( 'Section', 'Header', 'Footer', 'Footnote', 'Endnote', 'Cell', 'TextRun', 'TextBox', 'ListItemRun', 'TrackChange', ); $validContainers = array( 'Text' => $generalContainers, 'Bookmark' => $generalContainers, 'Link' => $generalContainers, 'TextBreak' => $generalContainers, 'Image' => $generalContainers, 'OLEObject' => $generalContainers, 'Field' => $generalContainers, 'Line' => $generalContainers, 'Shape' => $generalContainers, 'FormField' => $generalContainers, 'SDT' => $generalContainers, 'TrackChange' => $generalContainers, 'TextRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox', 'TrackChange', 'ListItemRun'), 'ListItem' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), 'ListItemRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), 'Table' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), 'CheckBox' => array('Section', 'Header', 'Footer', 'Cell', 'TextRun'), 'TextBox' => array('Section', 'Header', 'Footer', 'Cell'), 'Footnote' => array('Section', 'TextRun', 'Cell', 'ListItemRun'), 'Endnote' => array('Section', 'TextRun', 'Cell'), 'PreserveText' => array('Section', 'Header', 'Footer', 'Cell'), 'Title' => array('Section', 'Cell'), 'TOC' => array('Section'), 'PageBreak' => array('Section'), 'Chart' => array('Section', 'Cell'), ); // Special condition, e.g. preservetext can only exists in cell when // the cell is located in header or footer $validSubcontainers = array( 'PreserveText' => array(array('Cell'), array('Header', 'Footer', 'Section')), 'Footnote' => array(array('Cell', 'TextRun'), array('Section')), 'Endnote' => array(array('Cell', 'TextRun'), array('Section')), ); // Check if a method is valid for current container if (isset($validContainers[$method])) { if (!in_array($this->container, $validContainers[$method])) { throw new \<API key>("Cannot add {$method} in {$this->container}."); } } // Check if a method is valid for current container, located in other container if (isset($validSubcontainers[$method])) { $rules = $validSubcontainers[$method]; $containers = $rules[0]; $allowedDocParts = $rules[1]; foreach ($containers as $container) { if ($this->container == $container && !in_array($this->getDocPart(), $allowedDocParts)) { throw new \<API key>("Cannot add {$method} in {$this->container}."); } } } return true; } /** * Create textrun element * * @deprecated 0.10.0 * * @param mixed $paragraphStyle * * @return \PhpOffice\PhpWord\Element\TextRun * * @codeCoverageIgnore */ public function createTextRun($paragraphStyle = null) { return $this->addTextRun($paragraphStyle); } /** * Create footnote element * * @deprecated 0.10.0 * * @param mixed $paragraphStyle * * @return \PhpOffice\PhpWord\Element\Footnote * * @codeCoverageIgnore */ public function createFootnote($paragraphStyle = null) { return $this->addFootnote($paragraphStyle); } }
using OfficeDevPnP.MSGraphAPIDemo.Components; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using OfficeDevPnP.MSGraphAPIDemo.Models; using System.Threading; namespace OfficeDevPnP.MSGraphAPIDemo.Controllers { public class FilesController : Controller { // GET: Files public ActionResult Index() { return View(); } public ActionResult PlayWithFiles() { var drive = FilesHelper.<API key>(); var root = FilesHelper.<API key>(); var childrenItems = FilesHelper.ListFolderChildren(drive.Id, root.Id); var newFileOnRoot = UploadSampleFile(drive, root, Server.MapPath("~/AppIcon.png")); // Collect information about children items in the root folder StringBuilder sb = new StringBuilder(); String oneFolderId = null; foreach (var item in childrenItems) { if (item.Folder != null) { sb.AppendFormat("Found folder {0} with {1} child items.\n", item.Name, item.Folder.ChildCount); if (item.Name == "One Folder") { oneFolderId = item.Id; } } else { sb.AppendFormat("Found file {0}.\n", item.Name); } } var filesLog = sb.ToString(); // Create a new folder in the root folder var newFolder = FilesHelper.CreateFolder(drive.Id, root.Id, new Models.DriveItem { Name = $"Folder Created via API - {DateTime.Now.GetHashCode()}", Folder = new Models.Folder { }, }); var newFile = UploadSampleFile(drive, newFolder, Server.MapPath("~/AppIcon.png")); UpdateSampleFile(drive, newFile, Server.MapPath("~/SP2016-MinRoles.jpg")); // Create another folder in the root folder var anotherFolder = FilesHelper.CreateFolder(drive.Id, root.Id, new Models.DriveItem { Name = $"Folder Created via API - {DateTime.Now.GetHashCode()}", Folder = new Models.Folder { }, }); var movedItem = FilesHelper.MoveDriveItem(drive.Id, newFile.Id, "moved.jpg", anotherFolder.Name); var movedFolder = FilesHelper.MoveDriveItem(drive.Id, anotherFolder.Id, "Moved Folder", newFolder.Name); var searchResult = FilesHelper.Search("PnPLogo", drive.Id, root.Id); if (searchResult != null && searchResult.Count > 0) { var firstFileResult = searchResult.FirstOrDefault(i => i.File != null); try { var thumbnails = FilesHelper.GetFileThumbnails(drive.Id, firstFileResult.Id); var thumbnailMedium = FilesHelper.GetFileThumbnail(drive.Id, firstFileResult.Id, Models.ThumbnailSize.Medium); var thumbnailImage = FilesHelper.<API key>(drive.Id, firstFileResult.Id, Models.ThumbnailSize.Medium); } catch (Exception) { // Something wrong while getting the thumbnail, // We will have to handle it properly ... } } if (newFileOnRoot != null) { var permission = FilesHelper.<API key>(newFileOnRoot.Id, "0"); FilesHelper.DeleteFile(drive.Id, newFileOnRoot.Id); } try { var sharingPermission = FilesHelper.CreateSharingLink(newFolder.Id, SharingLinkType.View, SharingLinkScope.Anonymous); } catch (Exception) { // Something wrong while getting the sharing link, // We will have to handle it properly ... } if (!String.IsNullOrEmpty(oneFolderId)) { var newFolderChildren = FilesHelper.ListFolderChildren(drive.Id, newFolder.Id); var file = newFolderChildren.FirstOrDefault(f => f.Name == "moved.jpg"); if (file != null) { String jpegContentType = "image/jpeg"; Stream fileContent = FilesHelper.GetFileContent(drive.Id, file.Id, jpegContentType); return (base.File(fileContent, jpegContentType, file.Name)); } } return View("Index"); } private Models.DriveItem UploadSampleFile(Models.Drive drive, Models.DriveItem newFolder, String filePath) { Models.DriveItem result = null; Stream memPhoto = getFileContent(filePath); try { if (memPhoto.Length > 0) { String contentType = "image/png"; result = FilesHelper.UploadFile(drive.Id, newFolder.Id, new Models.DriveItem { File = new Models.File { }, Name = "PnPLogo.png", ConflictBehavior = "rename", }, memPhoto, contentType); } } catch (Exception ex) { // Handle the exception } return (result); } private void UpdateSampleFile(Drive drive, DriveItem newFile, String filePath) { FilesHelper.RenameFile(drive.Id, newFile.Id, "SP2016-MinRoles.jpg"); Stream memPhoto = getFileContent(filePath); try { if (memPhoto.Length > 0) { String contentType = "image/jpeg"; FilesHelper.UpdateFileContent( drive.Id, newFile.Id, memPhoto, contentType); } } catch (Exception ex) { // Handle the exception } } private static Stream getFileContent(String filePath) { MemoryStream memPhoto = new MemoryStream(); using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { Byte[] newPhoto = new Byte[fs.Length]; fs.Read(newPhoto, 0, (Int32)(fs.Length - 1)); memPhoto.Write(newPhoto, 0, newPhoto.Length); memPhoto.Position = 0; } return memPhoto; } } }
/* @flow */ /*eslint-disable no-undef, no-unused-vars, no-console*/ import _, { compose, pipe, curry, filter, find, isNil, repeat, replace, zipWith } from "ramda"; import { describe, it } from 'flow-typed-test'; const ns: Array<number> = [1, 2, 3, 4, 5]; const ss: Array<string> = ["one", "two", "three", "four"]; const obj: { [k: string]: number } = { a: 1, c: 2 }; const objMixed: { [k: string]: mixed } = { a: 1, c: "d" }; const os: Array<{ [k: string]: * }> = [{ a: 1, c: "d" }, { b: 2 }]; const str: string = "hello world"; // Math { const partDiv: (a: number) => number = _.divide(6); const div: number = _.divide(6, 2); //$FlowExpectedError const div2: number = _.divide(6, true); } // String { const ss: Array<string | void> = _.match(/h/, "b"); describe('replace', () => { it('should supports replace by string', () => { const r1: string = replace(",", "|", "b,d,d"); const r2: string = replace(",")("|", "b,d,d"); const r3: string = replace(",")("|")("b,d,d"); const r4: string = replace(",", "|")("b,d,d"); }); it('should supports replace by RegExp', () => { const r1: string = replace(/[,]/, "|", "b,d,d"); const r2: string = replace(/[,]/)("|", "b,d,d"); const r3: string = replace(/[,]/)("|")("b,d,d"); const r4: string = replace(/[,]/, "|")("b,d,d"); }); it('should supports replace by RegExp with replacement fn', () => { const fn = (match: string, g1: string): string => g1; const r1: string = replace(/([,])d/, fn, "b,d,d"); const r2: string = replace(/([,])d/)(fn, "b,d,d"); const r3: string = replace(/([,])d/)(fn)("b,d,d"); const r4: string = replace(/([,])d/, fn)("b,d,d"); }); }); const ss2: Array<string> = _.split(",", "b,d,d"); const ss1: boolean = _.test(/h/, "b"); const s: string = _.trim("s"); const x: string = _.head("one"); const sss: string = _.concat("H", "E"); const sss1: string = _.concat("H")("E"); const ssss: string = _.drop(1, "EF"); const ssss1: string = _.drop(1)("E"); const ssss2: string = _.dropLast(1, "EF"); const ys: string = _.nth(2, "curry"); const ys1: string = _.nth(2)("curry"); } //Type { const x: boolean = _.is(Number, 1); const x1: boolean = isNil(1); // should refine type const x1a: ?{ a: number } = { a: 1 }; //$FlowExpectedError x1a.a; if (!isNil(x1a)) { x1a.a; } const x2: boolean = _.propIs(1, "num", { num: 1 }); }
'use strict'; exports.up = function (knex) { return knex.schema.createTable('<API key>', function (t) { t.increments(); t.string('name'); }); }; exports.down = function (knex) { return knex.schema.dropTable('<API key>'); };
#include <stdio.h> #include <string.h> int is_prime(char*); int main() { char input[11]; fgets(input, 11, stdin); printf("%d", is_prime(input)); return 0; } int is_prime(char* input) { int i, length, number = 0; length = input[strlen(input) - 1] == '\n' ? strlen(input) - 1 : strlen(input); for (i = 0; i < length; i++) { if (input[i] < '0' || input[i] > '9') { return -1; } } for (i = 0; i < length; i++) { number += input[i] - '0'; if (i != length - 1) { number *= 10; } } if (number == 0 || number == 1) { return 0; } for (i = 2; i < number; i++) { if (number % i == 0 && i != number) { return 0; } } return 1; }
( function ( THREE ) { THREE.Raycaster = function ( origin, direction, near, far ) { this.ray = new THREE.Ray( origin, direction ); // normalized ray.direction required for accurate distance calculations if( this.ray.direction.lengthSq() > 0 ) { this.ray.direction.normalize(); } this.near = near || 0; this.far = far || Infinity; }; var sphere = new THREE.Sphere(); var localRay = new THREE.Ray(); var facePlane = new THREE.Plane(); var intersectPoint = new THREE.Vector3(); var matrixPosition = new THREE.Vector3(); var inverseMatrix = new THREE.Matrix4(); var descSort = function ( a, b ) { return a.distance - b.distance; }; var intersectObject = function ( object, raycaster, intersects ) { if ( object instanceof THREE.Particle ) { matrixPosition.<API key>( object.matrixWorld ); var distance = raycaster.ray.distanceToPoint( matrixPosition ); if ( distance > object.scale.x ) { return intersects; } intersects.push( { distance: distance, point: object.position, face: null, object: object } ); } else if ( object instanceof THREE.Mesh ) { // Checking boundingSphere distance to ray matrixPosition.<API key>( object.matrixWorld ); sphere.set( matrixPosition, object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() ); if ( ! raycaster.ray.<API key>( sphere ) ) { return intersects; } // Checking faces var geometry = object.geometry; var vertices = geometry.vertices; var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial; var objectMaterials = isFaceMaterial === true ? object.material.materials : null; var side = object.material.side; var a, b, c, d; var precision = raycaster.precision; object.matrixRotationWorld.extractRotation( object.matrixWorld ); inverseMatrix.getInverse( object.matrixWorld ); localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { var face = geometry.faces[ f ]; var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material; if ( material === undefined ) continue; facePlane.<API key>( face.normal, vertices[face.a] ); var planeDistance = localRay.distanceToPlane( facePlane ); // bail if raycaster and plane are parallel if ( Math.abs( planeDistance ) < precision ) continue; // if negative distance, then plane is behind raycaster if ( planeDistance < 0 ) continue; // check if we hit the wrong side of a single sided face side = material.side; if( side !== THREE.DoubleSide ) { var planeSign = localRay.direction.dot( facePlane.normal ); if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue; } // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue; intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy if ( face instanceof THREE.Face3 ) { a = vertices[ face.a ]; b = vertices[ face.b ]; c = vertices[ face.c ]; if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue; } else if ( face instanceof THREE.Face4 ) { a = vertices[ face.a ]; b = vertices[ face.b ]; c = vertices[ face.c ]; d = vertices[ face.d ]; if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) && ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue; } else { // This is added because if we call out of this if/else group when none of the cases // match it will add a point to the intersection list erroneously. throw Error( "face type not supported" ); } intersects.push( { distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't point: raycaster.ray.at( planeDistance ), face: face, faceIndex: f, object: object } ); } } }; var <API key> = function ( object, raycaster, intersects ) { var descendants = object.getDescendants(); for ( var i = 0, l = descendants.length; i < l; i ++ ) { intersectObject( descendants[ i ], raycaster, intersects ); } }; THREE.Raycaster.prototype.precision = 0.0001; THREE.Raycaster.prototype.set = function ( origin, direction ) { this.ray.set( origin, direction ); // normalized ray.direction required for accurate distance calculations if( this.ray.direction.length() > 0 ) { this.ray.direction.normalize(); } }; THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) { var intersects = []; if ( recursive === true ) { <API key>( object, this, intersects ); } intersectObject( object, this, intersects ); intersects.sort( descSort ); return intersects; }; THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) { var intersects = []; for ( var i = 0, l = objects.length; i < l; i ++ ) { intersectObject( objects[ i ], this, intersects ); if ( recursive === true ) { <API key>( objects[ i ], this, intersects ); } } intersects.sort( descSort ); return intersects; }; }( THREE ) );
module Facter::Util::Virtual # virt_what is a delegating helper method intended to make it easier to stub # the system call without affecting other calls to # Facter::Util::Resolution.exec def self.virt_what(command = "virt-what") Facter::Util::Resolution.exec command end # lspci is a delegating helper method intended to make it easier to stub the # system call without affecting other calls to Facter::Util::Resolution.exec def self.lspci(command = "lspci 2>/dev/null") Facter::Util::Resolution.exec command end def self.openvz? FileTest.directory?("/proc/vz") and not self.openvz_cloudlinux? end # So one can either have #6728 work on OpenVZ or Cloudlinux. Whoo. def self.openvz_type return false unless self.openvz? return false unless FileTest.exists?( '/proc/self/status' ) envid = Facter::Util::Resolution.exec( 'grep "envID" /proc/self/status' ) if envid =~ /^envID:\s+0$/i return 'openvzhn' elsif envid =~ /^envID:\s+(\d+)$/i return 'openvzve' end end # Cloudlinux uses OpenVZ to a degree, but always has an empty /proc/vz/ and # has /proc/lve/list present def self.openvz_cloudlinux?
'use strict'; require('../../modules/es.weak-set'); require('../../modules/esnext.weak-set.from'); var WeakSet = require('../../internals/path').WeakSet; var weakSetfrom = WeakSet.from; module.exports = function from(source, mapFn, thisArg) { return weakSetfrom.call(typeof this === 'function' ? this : WeakSet, source, mapFn, thisArg); };
/** @babel */ /** @jsx etch.dom **/ import etch from 'etch'; export default class WelcomeView { constructor(props) { this.props = props; etch.initialize(this); this.element.addEventListener('click', event => { const link = event.target.closest('a'); if (link && link.dataset.event) { this.props.reporterProxy.sendEvent( `clicked-welcome-${link.dataset.event}-link` ); } }); } <API key>() { atom.config.set('welcome.showOnStartup', this.checked); } update() {} serialize() { return { deserializer: 'WelcomeView', uri: this.props.uri }; } render() { return ( <div className="welcome"> <div className="welcome-container"> <header className="welcome-header"> <a href="https://atom.io/"> <svg className="welcome-logo" width="330px" height="68px" viewBox="0 0 330 68" version="1.1" > <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" > <g transform="translate(2.000000, 1.000000)"> <g transform="translate(96.000000, 8.000000)" fill="currentColor" > <path d="M185.498,3.399 C185.498,2.417 186.34,1.573 187.324,1.573 L187.674,1.573 C188.447,1.573 189.01,1.995 189.5,2.628 L208.676,30.862 L227.852,2.628 C228.272,1.995 228.905,1.573 229.676,1.573 L230.028,1.573 C231.01,1.573 231.854,2.417 231.854,3.399 L231.854,49.403 C231.854,50.387 231.01,51.231 230.028,51.231 C229.044,51.231 228.202,50.387 228.202,49.403 L228.202,8.246 L210.151,34.515 C209.729,35.148 209.237,35.428 208.606,35.428 C207.973,35.428 207.481,35.148 207.061,34.515 L189.01,8.246 L189.01,49.475 C189.01,50.457 188.237,51.231 187.254,51.231 C186.27,51.231 185.498,50.458 185.498,49.475 L185.498,3.399 L185.498,3.399 Z" /> <path d="M113.086,26.507 L113.086,26.367 C113.086,12.952 122.99,0.941 137.881,0.941 C152.77,0.941 162.533,12.811 162.533,26.225 L162.533,26.367 C162.533,39.782 152.629,51.792 137.74,51.792 C122.85,51.792 113.086,39.923 113.086,26.507 M158.74,26.507 L158.74,26.367 C158.74,14.216 149.89,4.242 137.74,4.242 C125.588,4.242 116.879,14.075 116.879,26.225 L116.879,26.367 C116.879,38.518 125.729,48.491 137.881,48.491 C150.031,48.491 158.74,38.658 158.74,26.507" /> <path d="M76.705,5.155 L60.972,5.155 C60.06,5.155 59.287,4.384 59.287,3.469 C59.287,2.556 60.059,1.783 60.972,1.783 L96.092,1.783 C97.004,1.783 97.778,2.555 97.778,3.469 C97.778,4.383 97.005,5.155 96.092,5.155 L80.358,5.155 L80.358,49.405 C80.358,50.387 79.516,51.231 78.532,51.231 C77.55,51.231 76.706,50.387 76.706,49.405 L76.706,5.155 L76.705,5.155 Z" /> <path d="M0.291,48.562 L21.291,3.05 C21.783,1.995 22.485,1.292 23.75,1.292 L23.891,1.292 C25.155,1.292 25.858,1.995 26.348,3.05 L47.279,48.421 C47.49,48.843 47.56,49.194 47.56,49.546 C47.56,50.458 46.788,51.231 45.803,51.231 C44.961,51.231 44.329,50.599 43.978,49.826 L38.219,37.183 L9.21,37.183 L3.45,49.897 C3.099,50.739 2.538,51.231 1.694,51.231 C0.781,51.231 0.008,50.529 0.008,49.685 C0.009,49.404 0.08,48.983 0.291,48.562 L0.291,48.562 Z M36.673,33.882 L23.749,5.437 L10.755,33.882 L36.673,33.882 L36.673,33.882 Z" /> </g> <g> <path d="M40.363,32.075 C40.874,34.44 39.371,36.77 37.006,37.282 C34.641,37.793 32.311,36.29 31.799,33.925 C31.289,31.56 32.791,29.23 35.156,28.718 C37.521,28.207 39.851,29.71 40.363,32.075" fill="currentColor" /> <path d="M48.578,28.615 C56.851,45.587 58.558,61.581 52.288,64.778 C45.822,68.076 33.326,56.521 24.375,38.969 C15.424,21.418 13.409,4.518 19.874,1.221 C22.689,-0.216 26.648,1.166 30.959,4.629" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> <path d="M7.64,39.45 C2.806,36.94 -0.009,33.915 0.154,30.79 C0.531,23.542 16.787,18.497 36.462,19.52 C56.137,20.544 71.781,27.249 71.404,34.497 C71.241,37.622 68.127,40.338 63.06,42.333" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> <path d="M28.828,59.354 C23.545,63.168 18.843,64.561 15.902,62.653 C9.814,58.702 13.572,42.102 24.296,25.575 C35.02,9.048 48.649,-1.149 54.736,2.803 C57.566,4.639 58.269,9.208 57.133,15.232" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> </g> </g> </g> </svg> <h1 className="welcome-title"> A hackable text editor for the 21<sup>st</sup> Century </h1> </a> </header> <section className="welcome-panel"> <p>For help, please visit</p> <ul> <li> The{' '} <a href="https: dataset={{ event: 'atom-docs' }} > Atom docs </a>{' '} for Guides and the API reference. </li> <li> The Atom forum at{' '} <a href="https://github.com/atom/atom/discussions" dataset={{ event: 'discussions' }} > Github Discussions </a> </li> <li> The{' '} <a href="https://github.com/atom" dataset={{ event: 'atom-org' }} > Atom org </a> . This is where all GitHub-created Atom packages can be found. </li> </ul> </section> <section className="welcome-panel"> <label> <input className="input-checkbox" type="checkbox" checked={atom.config.get('welcome.showOnStartup')} onchange={this.<API key>} /> Show Welcome Guide when opening Atom </label> </section> <footer className="welcome-footer"> <a href="https://atom.io/" dataset={{ event: 'footer-atom-io' }}> atom.io </a>{' '} <span className="text-subtle">×</span>{' '} <a className="icon icon-octoface" href="https://github.com/" dataset={{ event: 'footer-octocat' }} /> </footer> </div> </div> ); } getURI() { return this.props.uri; } getTitle() { return 'Welcome'; } isEqual(other) { return other instanceof WelcomeView; } }
title: Rule no-multi-spaces layout: doc <!-- Note: No pull requests accepted for this file. See README.md in the root directory for details. --> # Disallow multiple spaces (no-multi-spaces) (fixable) The `--fix` option on the [command line](../user-guide/<API key>#fix) automatically fixes problems reported by this rule. Multiple spaces in a row that are not used for indentation are typically mistakes. For example: js if(foo === "bar") {} It's hard to tell, but there are two spaces between `foo` and `===`. Multiple spaces such as this are generally frowned upon in favor of single spaces: js if(foo === "bar") {} ## Rule Details This rule aims to disallow multiple whitespace around logical expressions, conditional expressions, declarations, array elements, object properties, sequences and function parameters. Examples of **incorrect** code for this rule: js /*eslint no-multi-spaces: "error"*/ var a = 1; if(foo === "bar") {} a << b var arr = [1, 2]; a ? b: c Examples of **correct** code for this rule: js /*eslint no-multi-spaces: "error"*/ var a = 1; if(foo === "bar") {} a << b var arr = [1, 2]; a ? b: c ## Options To avoid contradictions if some other rules require multiple spaces, this rule has an option to ignore certain node types in the abstract syntax tree (AST) of JavaScript code. exceptions The `exceptions` object expects property names to be AST node types as defined by [ESTree](https: Only the `Property` node type is ignored by default, because for the [key-spacing](key-spacing) rule some alignment options require multiple spaces in properties of object literals. Examples of **correct** code for the default `"exceptions": { "Property": true }` option: js /*eslint no-multi-spaces: "error"*/ /*eslint key-spacing: ["error", { align: "value" }]*/ var obj = { first: "first", second: "second" }; Examples of **incorrect** code for the `"exceptions": { "Property": false }` option: js /*eslint no-multi-spaces: ["error", { exceptions: { "Property": false } }]*/ /*eslint key-spacing: ["error", { align: "value" }]*/ var obj = { first: "first", second: "second" }; Examples of **correct** code for the `"exceptions": { "BinaryExpression": true }` option: js /*eslint no-multi-spaces: ["error", { exceptions: { "BinaryExpression": true } }]*/ var a = 1 * 2; Examples of **correct** code for the `"exceptions": { "VariableDeclarator": true }` option: js /*eslint no-multi-spaces: ["error", { exceptions: { "VariableDeclarator": true } }]*/ var someVar = 'foo'; var someOtherVar = 'barBaz'; Examples of **correct** code for the `"exceptions": { "ImportDeclaration": true }` option: js /*eslint no-multi-spaces: ["error", { exceptions: { "ImportDeclaration": true } }]*/ import mod from 'mod'; import someOtherMod from 'some-other-mod'; ## When Not To Use It If you don't want to check and disallow multiple spaces, then you should turn this rule off. ## Related Rules * [key-spacing](key-spacing) * [space-infix-ops](space-infix-ops) * [space-in-brackets](space-in-brackets) (deprecated) * [space-in-parens](space-in-parens) * [<API key>](<API key>) * [space-unary-ops](space-unary-ops) * [<API key>](<API key>) ## Version This rule was introduced in ESLint 0.9.0. ## Resources * [Rule source](https://github.com/eslint/eslint/tree/master/lib/rules/no-multi-spaces.js) * [Documentation source](https://github.com/eslint/eslint/tree/master/docs/rules/no-multi-spaces.md)
using System; using System.IO; namespace Piranha.IO { <summary> Interface for creating an media provider. </summary> public interface IMedia { <summary> Gets the binary data for the given media object. </summary> <param name="media">The media object</param> <returns>The binary data</returns> byte[] Get(Models.Media media); <summary> Saves the given binary data for the given media object. </summary> <param name="media">The media object</param> <param name="bytes">The binary data</param> void Put(Models.Media media, byte[] bytes); <summary> Saves the binary data available in the stream in the given media object. </summary> <param name="media">The media object</param> <param name="stream">The stream</param> void Put(Models.Media media, Stream stream); <summary> Deletes the binary data for the given media object. </summary> <param name="media">The media object</param> void Delete(Models.Media media); } }
<?php namespace PragmaRX\Tracker\Data\Repositories; use PragmaRX\Tracker\Support\RefererParser; class Referer extends Repository { /** * @var RefererParser */ private $refererParser; /** * @var */ private $currentUrl; /** * @var */ private $searchTermModel; /** * Create repository instance. * * @param RefererParser $refererParser */ public function __construct($model, $searchTermModel, $currentUrl, RefererParser $refererParser) { parent::__construct($model); $this->refererParser = $refererParser; $this->currentUrl = $currentUrl; $this->searchTermModel = $searchTermModel; } /** * @param $refererUrl * @param $host * @param $domain_id * @return mixed */ public function store($refererUrl, $host, $domain_id) { $attributes = array( 'url' => $refererUrl, 'host' => $host, 'domain_id' => $domain_id, 'medium' => null, 'source' => null, 'search_terms_hash' => null ); $parsed = $this->refererParser->parse($refererUrl, $this->currentUrl); if ($parsed->isKnown()) { $attributes['medium'] = $parsed->getMedium(); $attributes['source'] = $parsed->getSource(); $attributes['search_terms_hash'] = sha1($parsed->getSearchTerm()); } $referer = $this->findOrCreate( $attributes, array('url', 'search_terms_hash') ); $referer = $this->find($referer); if ($parsed->isKnown()) { $this->storeSearchTerms($referer, $parsed); } return $referer->id; } private function storeSearchTerms($referer, $parsed) { foreach (explode(' ', $parsed->getSearchTerm()) as $term) { $this->findOrCreate( array( 'referer_id' => $referer->id, 'search_term' => $term ), array('referer_id', 'search_term'), $created, $this->searchTermModel ); } } }
'use strict'; angular.module('sw.plugin.split', ['sw.plugins']) .factory('split', function ($q) { return { execute: execute }; function execute (url, swagger) { var deferred = $q.defer(); if (swagger && swagger.swagger && !swagger.tags) { var tags = {}; angular.forEach(swagger.paths, function (path, key) { var t = key.replace(/^\/?([^\/]+).*$/g, '$1'); tags[t] = true; angular.forEach(path, function (method) { if (!method.tags || !method.tags.length) { method.tags = [t]; } }); }); swagger.tags = []; Object.keys(tags).forEach(function (tag) { swagger.tags.push({name: tag}); }); } deferred.resolve(true); return deferred.promise; } }) .run(function (plugins, split) { plugins.add(plugins.BEFORE_PARSE, split); });
namespace Microsoft.DocAsCode.Build.Engine.Incrementals { public sealed class ProcessorStepInfo { <summary> The name of processor step. </summary> public string Name { get; set; } <summary> The context hash for incremental. </summary> public string <API key> { get; set; } <summary> The file link for context info. </summary> public string ContextInfoFile { get; set; } public override bool Equals(object obj) { var another = obj as ProcessorStepInfo; if (another == null) { return false; } return Name == another.Name && <API key> == another.<API key>; } public override int GetHashCode() { return Name?.GetHashCode() ?? 0; } } }
(function($) { $(window).load(function() { // will first fade out the loading animation $("#status").fadeOut("slow"); // will fade out the whole DIV that covers the website. $("#preloader").delay(500).fadeOut("slow").remove(); $('.js #hero .hero-image img').addClass("animated fadeInUpBig"); $('.js #hero .buttons a.trial').addClass("animated shake"); }) var toggle_button = $("<a>", { id: "toggle-btn", html : "Menu", title: "Menu", href : " ); var nav_wrap = $('nav#nav-wrap') var nav = $("ul#nav"); /* id JS is enabled, remove the two a.mobile-btns and dynamically prepend a.toggle-btn to #nav-wrap */ nav_wrap.find('a.mobile-btn').remove(); nav_wrap.prepend(toggle_button); toggle_button.on("click", function(e) { e.preventDefault(); nav.slideToggle("fast"); }); if (toggle_button.is(':visible')) nav.addClass('mobile'); $(window).resize(function(){ if (toggle_button.is(':visible')) nav.addClass('mobile'); else nav.removeClass('mobile'); }); $('ul#nav li a').on("click", function(){ if (nav.hasClass('mobile')) nav.fadeOut('fast'); }); setTimeout(function() { $('h1.responsive-headline').fitText(1.2, { minFontSize: '25px', maxFontSize: '40px' }); }, 100); $('.smoothscroll').on('click', function (e) { e.preventDefault(); var target = this.hash, $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 800, 'swing', function () { window.location.hash = target; }); }); var sections = $("section"), navigation_links = $("#nav-wrap a"); sections.waypoint( { handler: function(event, direction) { var active_section; active_section = $(this); if (direction === "up") active_section = active_section.prev(); var active_link = $('#nav-wrap a[href="#' + active_section.attr("id") + '"]'); navigation_links.parent().removeClass("current"); active_link.parent().addClass("current"); }, offset: '35%' }); $('.js .design').waypoint(function() { $('.js .design .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .responsive').waypoint(function() { $('.js .responsive .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .cross-browser').waypoint(function() { $('.js .cross-browser .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .video').waypoint(function() { $('.js .video .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js #subscribe').waypoint(function() { $('.js #subscribe input[type="email"]').addClass( 'animated fadeInLeftBig show' ); $('.js #subscribe input[type="submit"]').addClass( 'animated fadeInRightBig show' ); }, { offset: 'bottom-in-view' }); animation_speed: 'fast', /* fast/slow/normal */ slideshow: false, /* false OR interval time in ms */ autoplay_slideshow: false, /* true/false */ opacity: 0.80, /* Value between 0 and 1 */ show_title: true, /* true/false */ allow_resize: true, /* Resize the photos bigger than viewport. true/false */ <API key>: '/', /* The separator for the gallery counter 1 "of" 2 */ theme: 'pp_default', /* light_rounded / dark_rounded / light_square / dark_square / facebook */ hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */ wmode: 'opaque', /* Set the flash wmode attribute */ autoplay: true, /* Automatically start videos: True/False */ modal: false, /* If set to true, only the close button will close the window */ overlay_gallery: false, /* If set to true, a gallery will overlay the fullscreen image on mouse over */ keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/modules/<API key>', ['highcharts'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'parts-gantt/<API key>.js', [_modules['parts/Globals.js']], function (H) { var addEvent = H.addEvent, Axis = H.Axis, PlotLineOrBand = H.PlotLineOrBand, merge = H.merge, wrap = H.wrap; var defaultConfig = { /** * Show an indicator on the axis for the current date and time. Can be a * boolean or a configuration object similar to * [xAxis.plotLines](#xAxis.plotLines). * * @sample gantt/<API key>/demo * Current date indicator enabled * @sample gantt/<API key>/object-config * Current date indicator with custom options * * @type {boolean|*} * @default true * @extends xAxis.plotLines * @excluding value * @product gantt * @apioption xAxis.<API key> */ <API key>: true, color: '#ccd6eb', width: 2, label: { /** * Format of the label. This options is passed as the fist argument to * [dateFormat](/class-reference/Highcharts#dateFormat) function. * * @type {string} * @default '%a, %b %d %Y, %H:%M' * @product gantt * @apioption xAxis.<API key>.label.format */ format: '%a, %b %d %Y, %H:%M', formatter: function (value, format) { return H.dateFormat(format, value); }, rotation: 0, style: { fontSize: '10px' } } }; /* eslint-disable no-invalid-this */ addEvent(Axis, 'afterSetOptions', function () { var options = this.options, cdiOptions = options.<API key>; if (cdiOptions) { cdiOptions = typeof cdiOptions === 'object' ? merge(defaultConfig, cdiOptions) : merge(defaultConfig); cdiOptions.value = new Date(); if (!options.plotLines) { options.plotLines = []; } options.plotLines.push(cdiOptions); } }); addEvent(PlotLineOrBand, 'render', function () { // If the label already exists, update its text if (this.label) { this.label.attr({ text: this.getLabelText(this.options.label) }); } }); wrap(PlotLineOrBand.prototype, 'getLabelText', function (defaultMethod, defaultLabelOptions) { var options = this.options; if (options.<API key> && options.label && typeof options.label.formatter === 'function') { options.value = new Date(); return options.label.formatter .call(this, options.value, options.label.format); } return defaultMethod.call(this, defaultLabelOptions); }); }); _registerModule(_modules, 'masters/modules/<API key>.src.js', [], function () { }); }));
<?php namespace Illuminate\Support; use stdClass; use Countable; use Exception; use ArrayAccess; use Traversable; use ArrayIterator; use CachingIterator; use JsonSerializable; use IteratorAggregate; use Illuminate\Support\Debug\Dumper; use Illuminate\Support\Traits\Macroable; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Contracts\Support\Arrayable; class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable { use Macroable; /** * The items contained in the collection. * * @var array */ protected $items = []; /** * The methods that can be proxied. * * @var array */ protected static $proxies = [ 'average', 'avg', 'contains', 'each', 'every', 'filter', 'first', 'flatMap', 'keyBy', 'map', 'partition', 'reject', 'sortBy', 'sortByDesc', 'sum', ]; /** * Create a new collection. * * @param mixed $items * @return void */ public function __construct($items = []) { $this->items = $this->getArrayableItems($items); } /** * Create a new collection instance if the value isn't one already. * * @param mixed $items * @return static */ public static function make($items = []) { return new static($items); } /** * Wrap the given value in a collection if applicable. * * @param mixed $value * @return static */ public static function wrap($value) { return $value instanceof self ? new static($value) : new static(Arr::wrap($value)); } /** * Get the underlying items from the given collection if applicable. * * @param array|static $value * @return array */ public static function unwrap($value) { return $value instanceof self ? $value->all() : $value; } /** * Create a new collection by invoking the callback a given amount of times. * * @param int $number * @param callable $callback * @return static */ public static function times($number, callable $callback = null) { if ($number < 1) { return new static; } if (is_null($callback)) { return new static(range(1, $number)); } return (new static(range(1, $number)))->map($callback); } /** * Get all of the items in the collection. * * @return array */ public function all() { return $this->items; } /** * Get the average value of a given key. * * @param callable|string|null $callback * @return mixed */ public function avg($callback = null) { if ($count = $this->count()) { return $this->sum($callback) / $count; } } /** * Alias for the "avg" method. * * @param callable|string|null $callback * @return mixed */ public function average($callback = null) { return $this->avg($callback); } /** * Get the median of a given key. * * @param null $key * @return mixed */ public function median($key = null) { $count = $this->count(); if ($count == 0) { return; } $values = (isset($key) ? $this->pluck($key) : $this) ->sort()->values(); $middle = (int) ($count / 2); if ($count % 2) { return $values->get($middle); } return (new static([ $values->get($middle - 1), $values->get($middle), ]))->average(); } /** * Get the mode of a given key. * * @param mixed $key * @return array|null */ public function mode($key = null) { $count = $this->count(); if ($count == 0) { return; } $collection = isset($key) ? $this->pluck($key) : $this; $counts = new self; $collection->each(function ($value) use ($counts) { $counts[$value] = isset($counts[$value]) ? $counts[$value] + 1 : 1; }); $sorted = $counts->sort(); $highestValue = $sorted->last(); return $sorted->filter(function ($value) use ($highestValue) { return $value == $highestValue; })->sort()->keys()->all(); } /** * Collapse the collection of items into a single array. * * @return static */ public function collapse() { return new static(Arr::collapse($this->items)); } /** * Determine if an item exists in the collection. * * @param mixed $key * @param mixed $operator * @param mixed $value * @return bool */ public function contains($key, $operator = null, $value = null) { if (func_num_args() == 1) { if ($this->useAsCallable($key)) { $placeholder = new stdClass; return $this->first($key, $placeholder) !== $placeholder; } return in_array($key, $this->items); } return $this->contains($this->operatorForWhere(...func_get_args())); } /** * Determine if an item exists in the collection using strict comparison. * * @param mixed $key * @param mixed $value * @return bool */ public function containsStrict($key, $value = null) { if (func_num_args() == 2) { return $this->contains(function ($item) use ($key, $value) { return data_get($item, $key) === $value; }); } if ($this->useAsCallable($key)) { return ! is_null($this->first($key)); } return in_array($key, $this->items, true); } /** * Cross join with the given lists, returning all possible permutations. * * @param mixed ...$lists * @return static */ public function crossJoin(...$lists) { return new static(Arr::crossJoin( $this->items, ...array_map([$this, 'getArrayableItems'], $lists) )); } /** * Dump the collection and end the script. * * @return void */ public function dd(...$args) { http_response_code(500); <API key>([$this, 'dump'], $args); die(1); } /** * Dump the collection. * * @return $this */ public function dump() { (new static(func_get_args())) ->push($this) ->each(function ($item) { (new Dumper)->dump($item); }); return $this; } /** * Get the items in the collection that are not present in the given items. * * @param mixed $items * @return static */ public function diff($items) { return new static(array_diff($this->items, $this->getArrayableItems($items))); } /** * Get the items in the collection whose keys and values are not present in the given items. * * @param mixed $items * @return static */ public function diffAssoc($items) { return new static(array_diff_assoc($this->items, $this->getArrayableItems($items))); } /** * Get the items in the collection whose keys are not present in the given items. * * @param mixed $items * @return static */ public function diffKeys($items) { return new static(array_diff_key($this->items, $this->getArrayableItems($items))); } /** * Execute a callback over each item. * * @param callable $callback * @return $this */ public function each(callable $callback) { foreach ($this->items as $key => $item) { if ($callback($item, $key) === false) { break; } } return $this; } /** * Execute a callback over each nested chunk of items. * * @param callable $callback * @return static */ public function eachSpread(callable $callback) { return $this->each(function ($chunk, $key) use ($callback) { $chunk[] = $key; return $callback(...$chunk); }); } /** * Determine if all items in the collection pass the given test. * * @param string|callable $key * @param mixed $operator * @param mixed $value * @return bool */ public function every($key, $operator = null, $value = null) { if (func_num_args() == 1) { $callback = $this->valueRetriever($key); foreach ($this->items as $k => $v) { if (! $callback($v, $k)) { return false; } } return true; } return $this->every($this->operatorForWhere(...func_get_args())); } /** * Get all items except for those with the specified keys. * * @param \Illuminate\Support\Collection|mixed $keys * @return static */ public function except($keys) { if ($keys instanceof self) { $keys = $keys->all(); } elseif (! is_array($keys)) { $keys = func_get_args(); } return new static(Arr::except($this->items, $keys)); } /** * Run a filter over each of the items. * * @param callable|null $callback * @return static */ public function filter(callable $callback = null) { if ($callback) { return new static(Arr::where($this->items, $callback)); } return new static(array_filter($this->items)); } /** * Apply the callback if the value is truthy. * * @param bool $value * @param callable $callback * @param callable $default * @return mixed */ public function when($value, callable $callback, callable $default = null) { if ($value) { return $callback($this, $value); } elseif ($default) { return $default($this, $value); } return $this; } /** * Apply the callback if the value is falsy. * * @param bool $value * @param callable $callback * @param callable $default * @return mixed */ public function unless($value, callable $callback, callable $default = null) { return $this->when(! $value, $callback, $default); } /** * Filter items by the given key value pair. * * @param string $key * @param mixed $operator * @param mixed $value * @return static */ public function where($key, $operator, $value = null) { return $this->filter($this->operatorForWhere(...func_get_args())); } /** * Get an operator checker callback. * * @param string $key * @param string $operator * @param mixed $value * @return \Closure */ protected function operatorForWhere($key, $operator, $value = null) { if (func_num_args() == 2) { $value = $operator; $operator = '='; } return function ($item) use ($key, $operator, $value) { $retrieved = data_get($item, $key); $strings = array_filter([$retrieved, $value], function ($value) { return is_string($value) || (is_object($value) && method_exists($value, '__toString')); }); if (count($strings) < 2 && count(array_filter([$retrieved, $value], 'is_object')) == 1) { return in_array($operator, ['!=', '<>', '!==']); } switch ($operator) { default: case '=': case '==': return $retrieved == $value; case '!=': case '<>': return $retrieved != $value; case '<': return $retrieved < $value; case '>': return $retrieved > $value; case '<=': return $retrieved <= $value; case '>=': return $retrieved >= $value; case '===': return $retrieved === $value; case '!==': return $retrieved !== $value; } }; } /** * Filter items by the given key value pair using strict comparison. * * @param string $key * @param mixed $value * @return static */ public function whereStrict($key, $value) { return $this->where($key, '===', $value); } /** * Filter items by the given key value pair. * * @param string $key * @param mixed $values * @param bool $strict * @return static */ public function whereIn($key, $values, $strict = false) { $values = $this->getArrayableItems($values); return $this->filter(function ($item) use ($key, $values, $strict) { return in_array(data_get($item, $key), $values, $strict); }); } /** * Filter items by the given key value pair using strict comparison. * * @param string $key * @param mixed $values * @return static */ public function whereInStrict($key, $values) { return $this->whereIn($key, $values, true); } /** * Filter items by the given key value pair. * * @param string $key * @param mixed $values * @param bool $strict * @return static */ public function whereNotIn($key, $values, $strict = false) { $values = $this->getArrayableItems($values); return $this->reject(function ($item) use ($key, $values, $strict) { return in_array(data_get($item, $key), $values, $strict); }); } /** * Filter items by the given key value pair using strict comparison. * * @param string $key * @param mixed $values * @return static */ public function whereNotInStrict($key, $values) { return $this->whereNotIn($key, $values, true); } /** * Get the first item from the collection. * * @param callable|null $callback * @param mixed $default * @return mixed */ public function first(callable $callback = null, $default = null) { return Arr::first($this->items, $callback, $default); } /** * Get the first item by the given key value pair. * * @param string $key * @param mixed $operator * @param mixed $value * @return static */ public function firstWhere($key, $operator, $value = null) { return $this->first($this->operatorForWhere(...func_get_args())); } /** * Get a flattened array of the items in the collection. * * @param int $depth * @return static */ public function flatten($depth = INF) { return new static(Arr::flatten($this->items, $depth)); } /** * Flip the items in the collection. * * @return static */ public function flip() { return new static(array_flip($this->items)); } /** * Remove an item from the collection by key. * * @param string|array $keys * @return $this */ public function forget($keys) { foreach ((array) $keys as $key) { $this->offsetUnset($key); } return $this; } /** * Get an item from the collection by key. * * @param mixed $key * @param mixed $default * @return mixed */ public function get($key, $default = null) { if ($this->offsetExists($key)) { return $this->items[$key]; } return value($default); } /** * Group an associative array by a field or using a callback. * * @param callable|string $groupBy * @param bool $preserveKeys * @return static */ public function groupBy($groupBy, $preserveKeys = false) { if (is_array($groupBy)) { $nextGroups = $groupBy; $groupBy = array_shift($nextGroups); } $groupBy = $this->valueRetriever($groupBy); $results = []; foreach ($this->items as $key => $value) { $groupKeys = $groupBy($value, $key); if (! is_array($groupKeys)) { $groupKeys = [$groupKeys]; } foreach ($groupKeys as $groupKey) { $groupKey = is_bool($groupKey) ? (int) $groupKey : $groupKey; if (! array_key_exists($groupKey, $results)) { $results[$groupKey] = new static; } $results[$groupKey]->offsetSet($preserveKeys ? $key : null, $value); } } $result = new static($results); if (! empty($nextGroups)) { return $result->map->groupBy($nextGroups, $preserveKeys); } return $result; } /** * Key an associative array by a field or using a callback. * * @param callable|string $keyBy * @return static */ public function keyBy($keyBy) { $keyBy = $this->valueRetriever($keyBy); $results = []; foreach ($this->items as $key => $item) { $resolvedKey = $keyBy($item, $key); if (is_object($resolvedKey)) { $resolvedKey = (string) $resolvedKey; } $results[$resolvedKey] = $item; } return new static($results); } /** * Determine if an item exists in the collection by key. * * @param mixed $key * @return bool */ public function has($key) { $keys = is_array($key) ? $key : func_get_args(); foreach ($keys as $value) { if (! $this->offsetExists($value)) { return false; } } return true; } /** * Concatenate values of a given key as a string. * * @param string $value * @param string $glue * @return string */ public function implode($value, $glue = null) { $first = $this->first(); if (is_array($first) || is_object($first)) { return implode($glue, $this->pluck($value)->all()); } return implode($value, $this->items); } /** * Intersect the collection with the given items. * * @param mixed $items * @return static */ public function intersect($items) { return new static(array_intersect($this->items, $this->getArrayableItems($items))); } /** * Intersect the collection with the given items by key. * * @param mixed $items * @return static */ public function intersectByKeys($items) { return new static(array_intersect_key( $this->items, $this->getArrayableItems($items) )); } /** * Determine if the collection is empty or not. * * @return bool */ public function isEmpty() { return empty($this->items); } /** * Determine if the collection is not empty. * * @return bool */ public function isNotEmpty() { return ! $this->isEmpty(); } /** * Determine if the given value is callable, but not a string. * * @param mixed $value * @return bool */ protected function useAsCallable($value) { return ! is_string($value) && is_callable($value); } /** * Get the keys of the collection items. * * @return static */ public function keys() { return new static(array_keys($this->items)); } /** * Get the last item from the collection. * * @param callable|null $callback * @param mixed $default * @return mixed */ public function last(callable $callback = null, $default = null) { return Arr::last($this->items, $callback, $default); } /** * Get the values of a given key. * * @param string|array $value * @param string|null $key * @return static */ public function pluck($value, $key = null) { return new static(Arr::pluck($this->items, $value, $key)); } /** * Run a map over each of the items. * * @param callable $callback * @return static */ public function map(callable $callback) { $keys = array_keys($this->items); $items = array_map($callback, $this->items, $keys); return new static(array_combine($keys, $items)); } /** * Run a map over each nested chunk of items. * * @param callable $callback * @return static */ public function mapSpread(callable $callback) { return $this->map(function ($chunk, $key) use ($callback) { $chunk[] = $key; return $callback(...$chunk); }); } /** * Run a dictionary map over the items. * * The callback should return an associative array with a single key/value pair. * * @param callable $callback * @return static */ public function mapToDictionary(callable $callback) { $dictionary = $this->map($callback)->reduce(function ($groups, $pair) { $groups[key($pair)][] = reset($pair); return $groups; }, []); return new static($dictionary); } /** * Run a grouping map over the items. * * The callback should return an associative array with a single key/value pair. * * @param callable $callback * @return static */ public function mapToGroups(callable $callback) { $groups = $this->mapToDictionary($callback); return $groups->map([$this, 'make']); } /** * Run an associative map over each of the items. * * The callback should return an associative array with a single key/value pair. * * @param callable $callback * @return static */ public function mapWithKeys(callable $callback) { $result = []; foreach ($this->items as $key => $value) { $assoc = $callback($value, $key); foreach ($assoc as $mapKey => $mapValue) { $result[$mapKey] = $mapValue; } } return new static($result); } /** * Map a collection and flatten the result by a single level. * * @param callable $callback * @return static */ public function flatMap(callable $callback) { return $this->map($callback)->collapse(); } /** * Map the values into a new class. * * @param string $class * @return static */ public function mapInto($class) { return $this->map(function ($value, $key) use ($class) { return new $class($value, $key); }); } /** * Get the max value of a given key. * * @param callable|string|null $callback * @return mixed */ public function max($callback = null) { $callback = $this->valueRetriever($callback); return $this->filter(function ($value) { return ! is_null($value); })->reduce(function ($result, $item) use ($callback) { $value = $callback($item); return is_null($result) || $value > $result ? $value : $result; }); } /** * Merge the collection with the given items. * * @param mixed $items * @return static */ public function merge($items) { return new static(array_merge($this->items, $this->getArrayableItems($items))); } /** * Create a collection by using this collection for keys and another for its values. * * @param mixed $values * @return static */ public function combine($values) { return new static(array_combine($this->all(), $this->getArrayableItems($values))); } /** * Union the collection with the given items. * * @param mixed $items * @return static */ public function union($items) { return new static($this->items + $this->getArrayableItems($items)); } /** * Get the min value of a given key. * * @param callable|string|null $callback * @return mixed */ public function min($callback = null) { $callback = $this->valueRetriever($callback); return $this->filter(function ($value) { return ! is_null($value); })->reduce(function ($result, $item) use ($callback) { $value = $callback($item); return is_null($result) || $value < $result ? $value : $result; }); } /** * Create a new collection consisting of every n-th element. * * @param int $step * @param int $offset * @return static */ public function nth($step, $offset = 0) { $new = []; $position = 0; foreach ($this->items as $item) { if ($position % $step === $offset) { $new[] = $item; } $position++; } return new static($new); } /** * Get the items with the specified keys. * * @param mixed $keys * @return static */ public function only($keys) { if (is_null($keys)) { return new static($this->items); } if ($keys instanceof self) { $keys = $keys->all(); } $keys = is_array($keys) ? $keys : func_get_args(); return new static(Arr::only($this->items, $keys)); } /** * "Paginate" the collection by slicing it into a smaller collection. * * @param int $page * @param int $perPage * @return static */ public function forPage($page, $perPage) { $offset = max(0, ($page - 1) * $perPage); return $this->slice($offset, $perPage); } /** * Partition the collection into two arrays using the given callback or key. * * @param callable|string $callback * @return static */ public function partition($callback) { $partitions = [new static, new static]; $callback = $this->valueRetriever($callback); foreach ($this->items as $key => $item) { $partitions[(int) ! $callback($item, $key)][$key] = $item; } return new static($partitions); } /** * Pass the collection to the given callback and return the result. * * @param callable $callback * @return mixed */ public function pipe(callable $callback) { return $callback($this); } /** * Get and remove the last item from the collection. * * @return mixed */ public function pop() { return array_pop($this->items); } /** * Push an item onto the beginning of the collection. * * @param mixed $value * @param mixed $key * @return $this */ public function prepend($value, $key = null) { $this->items = Arr::prepend($this->items, $value, $key); return $this; } /** * Push an item onto the end of the collection. * * @param mixed $value * @return $this */ public function push($value) { $this->offsetSet(null, $value); return $this; } /** * Push all of the given items onto the collection. * * @param \Traversable $source * @return $this */ public function concat($source) { $result = new static($this); foreach ($source as $item) { $result->push($item); } return $result; } /** * Get and remove an item from the collection. * * @param mixed $key * @param mixed $default * @return mixed */ public function pull($key, $default = null) { return Arr::pull($this->items, $key, $default); } /** * Put an item in the collection by key. * * @param mixed $key * @param mixed $value * @return $this */ public function put($key, $value) { $this->offsetSet($key, $value); return $this; } /** * Get one or a specified number of items randomly from the collection. * * @param int|null $number * @return mixed * * @throws \<API key> */ public function random($number = null) { if (is_null($number)) { return Arr::random($this->items); } return new static(Arr::random($this->items, $number)); } /** * Reduce the collection to a single value. * * @param callable $callback * @param mixed $initial * @return mixed */ public function reduce(callable $callback, $initial = null) { return array_reduce($this->items, $callback, $initial); } /** * Create a collection of all elements that do not pass a given truth test. * * @param callable|mixed $callback * @return static */ public function reject($callback) { if ($this->useAsCallable($callback)) { return $this->filter(function ($value, $key) use ($callback) { return ! $callback($value, $key); }); } return $this->filter(function ($item) use ($callback) { return $item != $callback; }); } /** * Reverse items order. * * @return static */ public function reverse() { return new static(array_reverse($this->items, true)); } /** * Search the collection for a given value and return the corresponding key if successful. * * @param mixed $value * @param bool $strict * @return mixed */ public function search($value, $strict = false) { if (! $this->useAsCallable($value)) { return array_search($value, $this->items, $strict); } foreach ($this->items as $key => $item) { if (call_user_func($value, $item, $key)) { return $key; } } return false; } /** * Get and remove the first item from the collection. * * @return mixed */ public function shift() { return array_shift($this->items); } /** * Shuffle the items in the collection. * * @param int $seed * @return static */ public function shuffle($seed = null) { $items = $this->items; if (is_null($seed)) { shuffle($items); } else { srand($seed); usort($items, function () { return rand(-1, 1); }); } return new static($items); } /** * Slice the underlying collection array. * * @param int $offset * @param int $length * @return static */ public function slice($offset, $length = null) { return new static(array_slice($this->items, $offset, $length, true)); } /** * Split a collection into a certain number of groups. * * @param int $numberOfGroups * @return static */ public function split($numberOfGroups) { if ($this->isEmpty()) { return new static; } $groupSize = ceil($this->count() / $numberOfGroups); return $this->chunk($groupSize); } /** * Chunk the underlying collection array. * * @param int $size * @return static */ public function chunk($size) { if ($size <= 0) { return new static; } $chunks = []; foreach (array_chunk($this->items, $size, true) as $chunk) { $chunks[] = new static($chunk); } return new static($chunks); } /** * Sort through each item with a callback. * * @param callable|null $callback * @return static */ public function sort(callable $callback = null) { $items = $this->items; $callback ? uasort($items, $callback) : asort($items); return new static($items); } /** * Sort the collection using the given callback. * * @param callable|string $callback * @param int $options * @param bool $descending * @return static */ public function sortBy($callback, $options = SORT_REGULAR, $descending = false) { $results = []; $callback = $this->valueRetriever($callback); // First we will loop through the items and get the comparator from a callback // function which we were given. Then, we will sort the returned values and // and grab the corresponding values for the sorted keys from this array. foreach ($this->items as $key => $value) { $results[$key] = $callback($value, $key); } $descending ? arsort($results, $options) : asort($results, $options); // Once we have sorted all of the keys in the array, we will loop through them // and grab the corresponding model so we can set the underlying items list // to the sorted version. Then we'll just return the collection instance. foreach (array_keys($results) as $key) { $results[$key] = $this->items[$key]; } return new static($results); } /** * Sort the collection in descending order using the given callback. * * @param callable|string $callback * @param int $options * @return static */ public function sortByDesc($callback, $options = SORT_REGULAR) { return $this->sortBy($callback, $options, true); } /** * Splice a portion of the underlying collection array. * * @param int $offset * @param int|null $length * @param mixed $replacement * @return static */ public function splice($offset, $length = null, $replacement = []) { if (func_num_args() == 1) { return new static(array_splice($this->items, $offset)); } return new static(array_splice($this->items, $offset, $length, $replacement)); } /** * Get the sum of the given values. * * @param callable|string|null $callback * @return mixed */ public function sum($callback = null) { if (is_null($callback)) { return array_sum($this->items); } $callback = $this->valueRetriever($callback); return $this->reduce(function ($result, $item) use ($callback) { return $result + $callback($item); }, 0); } /** * Take the first or last {$limit} items. * * @param int $limit * @return static */ public function take($limit) { if ($limit < 0) { return $this->slice($limit, abs($limit)); } return $this->slice(0, $limit); } /** * Pass the collection to the given callback and then return it. * * @param callable $callback * @return $this */ public function tap(callable $callback) { $callback(new static($this->items)); return $this; } /** * Transform each item in the collection using a callback. * * @param callable $callback * @return $this */ public function transform(callable $callback) { $this->items = $this->map($callback)->all(); return $this; } /** * Return only unique items from the collection array. * * @param string|callable|null $key * @param bool $strict * @return static */ public function unique($key = null, $strict = false) { if (is_null($key)) { return new static(array_unique($this->items, SORT_REGULAR)); } $callback = $this->valueRetriever($key); $exists = []; return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) { if (in_array($id = $callback($item, $key), $exists, $strict)) { return true; } $exists[] = $id; }); } /** * Return only unique items from the collection array using strict comparison. * * @param string|callable|null $key * @return static */ public function uniqueStrict($key = null) { return $this->unique($key, true); } /** * Reset the keys on the underlying array. * * @return static */ public function values() { return new static(array_values($this->items)); } /** * Get a value retrieving callback. * * @param string $value * @return callable */ protected function valueRetriever($value) { if ($this->useAsCallable($value)) { return $value; } return function ($item) use ($value) { return data_get($item, $value); }; } /** * Zip the collection together with one or more arrays. * * e.g. new Collection([1, 2, 3])->zip([4, 5, 6]); * => [[1, 4], [2, 5], [3, 6]] * * @param mixed ...$items * @return static */ public function zip($items) { $arrayableItems = array_map(function ($items) { return $this->getArrayableItems($items); }, func_get_args()); $params = array_merge([function () { return new static(func_get_args()); }, $this->items], $arrayableItems); return new static(<API key>('array_map', $params)); } /** * Pad collection to the specified length with a value. * * @param int $size * @param mixed $value * @return static */ public function pad($size, $value) { return new static(array_pad($this->items, $size, $value)); } /** * Get the collection of items as a plain array. * * @return array */ public function toArray() { return array_map(function ($value) { return $value instanceof Arrayable ? $value->toArray() : $value; }, $this->items); } /** * Convert the object into something JSON serializable. * * @return array */ public function jsonSerialize() { return array_map(function ($value) { if ($value instanceof JsonSerializable) { return $value->jsonSerialize(); } elseif ($value instanceof Jsonable) { return json_decode($value->toJson(), true); } elseif ($value instanceof Arrayable) { return $value->toArray(); } return $value; }, $this->items); } /** * Get the collection of items as JSON. * * @param int $options * @return string */ public function toJson($options = 0) { return json_encode($this->jsonSerialize(), $options); } /** * Get an iterator for the items. * * @return \ArrayIterator */ public function getIterator() { return new ArrayIterator($this->items); } /** * Get a CachingIterator instance. * * @param int $flags * @return \CachingIterator */ public function getCachingIterator($flags = CachingIterator::CALL_TOSTRING) { return new CachingIterator($this->getIterator(), $flags); } /** * Count the number of items in the collection. * * @return int */ public function count() { return count($this->items); } /** * Get a base Support collection instance from this collection. * * @return \Illuminate\Support\Collection */ public function toBase() { return new self($this); } /** * Determine if an item exists at an offset. * * @param mixed $key * @return bool */ public function offsetExists($key) { return array_key_exists($key, $this->items); } /** * Get an item at a given offset. * * @param mixed $key * @return mixed */ public function offsetGet($key) { return $this->items[$key]; } /** * Set the item at a given offset. * * @param mixed $key * @param mixed $value * @return void */ public function offsetSet($key, $value) { if (is_null($key)) { $this->items[] = $value; } else { $this->items[$key] = $value; } } /** * Unset the item at a given offset. * * @param string $key * @return void */ public function offsetUnset($key) { unset($this->items[$key]); } /** * Convert the collection to its string representation. * * @return string */ public function __toString() { return $this->toJson(); } /** * Results array of items from Collection or Arrayable. * * @param mixed $items * @return array */ protected function getArrayableItems($items) { if (is_array($items)) { return $items; } elseif ($items instanceof self) { return $items->all(); } elseif ($items instanceof Arrayable) { return $items->toArray(); } elseif ($items instanceof Jsonable) { return json_decode($items->toJson(), true); } elseif ($items instanceof JsonSerializable) { return $items->jsonSerialize(); } elseif ($items instanceof Traversable) { return iterator_to_array($items); } return (array) $items; } /** * Add a method to the list of proxied methods. * * @param string $method * @return void */ public static function proxy($method) { static::$proxies[] = $method; } /** * Dynamically access collection proxies. * * @param string $key * @return mixed * * @throws \Exception */ public function __get($key) { if (! in_array($key, static::$proxies)) { throw new Exception("Property [{$key}] does not exist on this collection instance."); } return new <API key>($this, $key); } }
/*<API key> <API key> XX XX XX BasicBlock XX XX XX XX XX <API key> <API key> */ #ifndef _BLOCK_H_ #define _BLOCK_H_ #include "vartype.h" // For "var_types.h" #include "_typeinfo.h" // Defines VARSET_TP #include "varset.h" #include "blockset.h" #include "jitstd.h" #include "bitvec.h" #include "simplerhash.h" typedef BitVec EXPSET_TP; #if LARGE_EXPSET #define EXPSET_SZ 64 #else #define EXPSET_SZ 32 #endif typedef BitVec ASSERT_TP; typedef BitVec_ValArg_T ASSERT_VALARG_TP; typedef BitVec_ValRet_T ASSERT_VALRET_TP; /***************************************************************************** * * Each basic block ends with a jump which is described as a value * of the following enumeration. */ DECLARE_TYPED_ENUM(BBjumpKinds, BYTE) { BBJ_EHFINALLYRET, // block ends with 'endfinally' (for finally or fault) BBJ_EHFILTERRET, // block ends with 'endfilter' BBJ_EHCATCHRET, // block ends with a leave out of a catch (only #if FEATURE_EH_FUNCLETS) BBJ_THROW, // block ends with 'throw' BBJ_RETURN, // block ends with 'ret' BBJ_NONE, // block flows into the next one (no jump) BBJ_ALWAYS, // block always jumps to the target BBJ_LEAVE, // block always jumps to the target, maybe out of guarded // region. Used temporarily until importing BBJ_CALLFINALLY, // block always calls the target finally BBJ_COND, // block conditionally jumps to the target BBJ_SWITCH, // block ends with a switch statement BBJ_COUNT } <API key>(BBjumpKinds, BYTE) struct GenTree; struct GenTreeStmt; struct BasicBlock; class Compiler; class typeInfo; struct BasicBlockList; struct flowList; struct EHblkDsc; #if <API key> struct FlatFPStateX87; #endif /***************************************************************************** * * The following describes a switch block. * * Things to know: * 1. If bbsHasDefault is true, the default case is the last one in the array of basic block addresses * namely bbsDstTab[bbsCount - 1]. * 2. bbsCount must be at least 1, for the default case. bbsCount cannot be zero. It appears that the ECMA spec * allows for a degenerate switch with zero cases. Normally, the optimizer will optimize degenerate * switches with just a default case to a BBJ_ALWAYS branch, and a switch with just two cases to a BBJ_COND. * However, in debuggable code, we might not do that, so bbsCount might be 1. */ struct BBswtDesc { unsigned bbsCount; // count of cases (includes 'default' if bbsHasDefault) BasicBlock** bbsDstTab; // case label table address bool bbsHasDefault; BBswtDesc() : bbsHasDefault(true) { } void removeDefault() { assert(bbsHasDefault); assert(bbsCount > 0); bbsHasDefault = false; bbsCount } BasicBlock* getDefault() { assert(bbsHasDefault); assert(bbsCount > 0); return bbsDstTab[bbsCount - 1]; } }; struct StackEntry { GenTree* val; typeInfo seTypeInfo; }; enum ThisInitState { TIS_Bottom, // We don't know anything about the 'this' pointer. TIS_Uninit, // The 'this' pointer for this constructor is known to be uninitialized. TIS_Init, // The 'this' pointer for this constructor is known to be initialized. TIS_Top, // This results from merging the state of two blocks one with TIS_Unint and the other with TIS_Init. // We use this in fault blocks to prevent us from accessing the 'this' pointer, but otherwise // allowing the fault block to generate code. }; struct EntryState { ThisInitState thisInitialized : 8; // used to track whether the this ptr is initialized (we could use // fewer bits here) unsigned esStackDepth : 24; // size of esStack StackEntry* esStack; // ptr to stack }; // Enumeration of the kinds of memory whose state changes the compiler tracks enum MemoryKind { ByrefExposed = 0, // Includes anything byrefs can read/write (everything in GcHeap, address-taken locals, // unmanaged heap, callers' locals, etc.) GcHeap, // Includes actual GC heap, and also static fields MemoryKindCount, // Number of MemoryKinds }; #ifdef DEBUG const char* const memoryKindNames[] = {"ByrefExposed", "GcHeap"}; #endif // DEBUG // Bitmask describing a set of memory kinds (usable in bitfields) typedef unsigned int MemoryKindSet; // Bitmask for a MemoryKindSet containing just the specified MemoryKind inline MemoryKindSet memoryKindSet(MemoryKind memoryKind) { return (1U << memoryKind); } // Bitmask for a MemoryKindSet containing the specified MemoryKinds template <typename... MemoryKinds> inline MemoryKindSet memoryKindSet(MemoryKind memoryKind, MemoryKinds... memoryKinds) { return memoryKindSet(memoryKind) | memoryKindSet(memoryKinds...); } // Bitmask containing all the MemoryKinds const MemoryKindSet fullMemoryKindSet = (1 << MemoryKindCount) - 1; // Bitmask containing no MemoryKinds const MemoryKindSet emptyMemoryKindSet = 0; // Standard iterator class for iterating through MemoryKinds class MemoryKindIterator { int value; public: explicit inline MemoryKindIterator(int val) : value(val) { } inline MemoryKindIterator& operator++() { ++value; return *this; } inline MemoryKindIterator operator++(int) { return MemoryKindIterator(value++); } inline MemoryKind operator*() { return static_cast<MemoryKind>(value); } friend bool operator==(const MemoryKindIterator& left, const MemoryKindIterator& right) { return left.value == right.value; } friend bool operator!=(const MemoryKindIterator& left, const MemoryKindIterator& right) { return left.value != right.value; } }; // Empty struct that allows enumerating memory kinds via `for(MemoryKind kind : allMemoryKinds())` struct allMemoryKinds { inline allMemoryKinds() { } inline MemoryKindIterator begin() { return MemoryKindIterator(0); } inline MemoryKindIterator end() { return MemoryKindIterator(MemoryKindCount); } }; // This encapsulates the "exception handling" successors of a block. That is, // if a basic block BB1 occurs in a try block, we consider the first basic block // BB2 of the corresponding handler to be an "EH successor" of BB1. Because we // make the conservative assumption that control flow can jump from a try block // to its handler at any time, the immediate (regular control flow) // predecessor(s) of the the first block of a try block are also considered to // have the first block of the handler as an EH successor. This makes variables that // are "live-in" to the handler become "live-out" for these try-predecessor block, // so that they become live-in to the try -- which we require. class EHSuccessorIter { // The current compilation. Compiler* m_comp; // The block whose EH successors we are iterating over. BasicBlock* m_block; // The current "regular" successor of "m_block" that we're considering. BasicBlock* m_curRegSucc; // The current try block. If non-null, then the current successor "m_curRegSucc" // is the first block of the handler of this block. While this try block has // enclosing try's that also start with "m_curRegSucc", the corresponding handlers will be // further EH successors. EHblkDsc* m_curTry; // The number of "regular" (i.e., non-exceptional) successors that remain to // be considered. If BB1 has successor BB2, and BB2 is the first block of a // try block, then we consider the catch block of BB2's try to be an EH // successor of BB1. This captures the iteration over the successors of BB1 // for this purpose. (In reverse order; we're done when this field is 0). int m_remainingRegSuccs; // Requires that "m_curTry" is NULL. Determines whether there is, as // discussed just above, a regular successor that's the first block of a // try; if so, sets "m_curTry" to that try block. (As noted above, selecting // the try containing the current regular successor as the "current try" may cause // multiple first-blocks of catches to be yielded as EH successors: trys enclosing // the current try are also included if they also start with the current EH successor.) void FindNextRegSuccTry(); public: // Returns the standard "end" iterator. EHSuccessorIter() : m_comp(nullptr), m_block(nullptr), m_curRegSucc(nullptr), m_curTry(nullptr), m_remainingRegSuccs(0) { } // Initializes the iterator to represent the EH successors of "block". EHSuccessorIter(Compiler* comp, BasicBlock* block); // Go on to the next EH successor. void operator++(void); // Requires that "this" is not equal to the standard "end" iterator. Returns the // current EH successor. BasicBlock* operator*(); // Returns "true" iff "*this" is equal to "ehsi" -- ignoring the "m_comp" // and "m_block" fields. bool operator==(const EHSuccessorIter& ehsi) { // Ignore the compiler; we'll assume that's the same. return m_curTry == ehsi.m_curTry && m_remainingRegSuccs == ehsi.m_remainingRegSuccs; } bool operator!=(const EHSuccessorIter& ehsi) { return !((*this) == ehsi); } }; // Yields both normal and EH successors (in that order) in one iteration. class AllSuccessorIter { // Normal succ state. Compiler* m_comp; BasicBlock* m_blk; unsigned m_normSucc; unsigned m_numNormSuccs; EHSuccessorIter m_ehIter; // True iff m_blk is a BBJ_CALLFINALLY block, and the current try block of m_ehIter, // the first block of whose handler would be next yielded, is the jump target of m_blk. inline bool <API key>(); public: inline AllSuccessorIter() { } // Initializes "this" to iterate over all successors of "block." inline AllSuccessorIter(Compiler* comp, BasicBlock* block); // Used for constructing an appropriate "end" iter. Should be called with // the number of normal successors of the block being iterated. AllSuccessorIter(unsigned numSuccs) : m_normSucc(numSuccs), m_numNormSuccs(numSuccs), m_ehIter() { } // Go on to the next successor. inline void operator++(void); // Requires that "this" is not equal to the standard "end" iterator. Returns the // current successor. inline BasicBlock* operator*(); // Returns "true" iff "*this" is equal to "asi" -- ignoring the "m_comp" // and "m_block" fields. bool operator==(const AllSuccessorIter& asi) { return m_normSucc == asi.m_normSucc && m_ehIter == asi.m_ehIter; } bool operator!=(const AllSuccessorIter& asi) { return !((*this) == asi); } }; // BasicBlock: describes a basic block in the flowgraph. // Note that this type derives from LIR::Range in order to make the LIR // utilities that are polymorphic over basic block and scratch ranges // faster and simpler. struct BasicBlock : private LIR::Range { friend class LIR; BasicBlock* bbNext; // next BB in ascending PC offset order BasicBlock* bbPrev; void setNext(BasicBlock* next) { bbNext = next; if (next) { next->bbPrev = this; } } unsigned __int64 bbFlags; // see BBF_xxxx below unsigned bbNum; // the block's number unsigned bbPostOrderNum; // the block's post order number in the graph. unsigned bbRefs; // number of blocks that can reach here, either by fall-through or a branch. If this falls to zero, // the block is unreachable. #define BBF_VISITED 0x00000001 // BB visited during optimizations #define BBF_MARKED 0x00000002 // BB marked during optimizations #define BBF_CHANGED 0x00000004 // input/output of this block has changed #define BBF_REMOVED 0x00000008 // BB has been removed from bb-list #define BBF_DONT_REMOVE 0x00000010 // BB should not be removed during flow graph optimizations #define BBF_IMPORTED 0x00000020 // BB byte-code has been imported #define BBF_INTERNAL 0x00000040 // BB has been added by the compiler #define <API key> 0x00000080 // BB has verification exception #define BBF_TRY_BEG 0x00000100 // BB starts a 'try' block #define BBF_FUNCLET_BEG 0x00000200 // BB is the beginning of a funclet #define BBF_HAS_NULLCHECK 0x00000400 // BB contains a null check #define BBF_NEEDS_GCPOLL 0x00000800 // This BB is the source of a back edge and needs a GC Poll #define BBF_RUN_RARELY 0x00001000 // BB is rarely run (catch clauses, blocks with throws etc) #define BBF_LOOP_HEAD 0x00002000 // BB is the head of a loop #define BBF_LOOP_CALL0 0x00004000 // BB starts a loop that sometimes won't call #define BBF_LOOP_CALL1 0x00008000 // BB starts a loop that will always call #define BBF_HAS_LABEL 0x00010000 // BB needs a label #define BBF_JMP_TARGET 0x00020000 // BB is a target of an implicit/explicit jump #define BBF_HAS_JMP 0x00040000 // BB executes a JMP instruction (instead of return) #define BBF_GC_SAFE_POINT 0x00080000 // BB has a GC safe point (a call). More abstractly, BB does not // require a (further) poll -- this may be because this BB has a // call, or, in some cases, because the BB occurs in a loop, and // we've determined that all paths in the loop body leading to BB // include a call. #define BBF_HAS_VTABREF 0x00100000 // BB contains reference of vtable #define BBF_HAS_IDX_LEN 0x00200000 // BB contains simple index or length expressions on an array local var. #define BBF_HAS_NEWARRAY 0x00400000 // BB contains 'new' of an array #define BBF_HAS_NEWOBJ 0x00800000 // BB contains 'new' of an object type. #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) #define BBF_FINALLY_TARGET 0x01000000 // BB is the target of a finally return: where a finally will return during // non-exceptional flow. Because the ARM calling sequence for calling a // finally explicitly sets the return address to the finally target and jumps // to the finally, instead of using a call instruction, ARM needs this to // generate correct code at the finally target, to allow for proper stack // unwind from within a non-exceptional call to a finally. #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) #define BBF_BACKWARD_JUMP 0x02000000 // BB is surrounded by a backward jump/switch arc #define BBF_RETLESS_CALL 0x04000000 // BBJ_CALLFINALLY that will never return (and therefore, won't need a paired // BBJ_ALWAYS); see isBBCallAlwaysPair(). #define BBF_LOOP_PREHEADER 0x08000000 // BB is a loop preheader block #define BBF_COLD 0x10000000 // BB is cold #define BBF_PROF_WEIGHT 0x20000000 // BB weight is computed from profile data #ifdef LEGACY_BACKEND #define BBF_FORWARD_SWITCH 0x40000000 // Aux flag used in FP codegen to know if a jmptable entry has been forwarded #else // !LEGACY_BACKEND #define BBF_IS_LIR 0x40000000 // Set if the basic block contains LIR (as opposed to HIR) #endif // LEGACY_BACKEND #define BBF_KEEP_BBJ_ALWAYS 0x80000000 // A special BBJ_ALWAYS block, used by EH code generation. Keep the jump kind // as BBJ_ALWAYS. Used for the paired BBJ_ALWAYS block following the // BBJ_CALLFINALLY block, as well as, on x86, the final step block out of a // finally. #define <API key> 0x100000000 // First block of a cloned finally region #define <API key> 0x200000000 // Last block of a cloned finally region // Flags that relate blocks to loop structure. #define BBF_LOOP_FLAGS (BBF_LOOP_PREHEADER | BBF_LOOP_HEAD | BBF_LOOP_CALL0 | BBF_LOOP_CALL1) bool isRunRarely() const { return ((bbFlags & BBF_RUN_RARELY) != 0); } bool isLoopHead() const { return ((bbFlags & BBF_LOOP_HEAD) != 0); } // Flags to update when two blocks are compacted #define BBF_COMPACT_UPD \ (BBF_CHANGED | BBF_GC_SAFE_POINT | BBF_HAS_JMP | BBF_NEEDS_GCPOLL | BBF_HAS_IDX_LEN | BBF_BACKWARD_JUMP | \ BBF_HAS_NEWARRAY | BBF_HAS_NEWOBJ) // Flags a block should not have had before it is split. #ifdef LEGACY_BACKEND #define BBF_SPLIT_NONEXIST \ (BBF_CHANGED | BBF_LOOP_HEAD | BBF_LOOP_CALL0 | BBF_LOOP_CALL1 | BBF_RETLESS_CALL | BBF_LOOP_PREHEADER | \ BBF_COLD | BBF_FORWARD_SWITCH) #else // !LEGACY_BACKEND #define BBF_SPLIT_NONEXIST \ (BBF_CHANGED | BBF_LOOP_HEAD | BBF_LOOP_CALL0 | BBF_LOOP_CALL1 | BBF_RETLESS_CALL | BBF_LOOP_PREHEADER | BBF_COLD) #endif // LEGACY_BACKEND // Flags lost by the top block when a block is split. // Note, this is a conservative guess. // For example, the top block might or might not have BBF_GC_SAFE_POINT, // but we assume it does not have BBF_GC_SAFE_POINT any more. #define BBF_SPLIT_LOST (BBF_GC_SAFE_POINT | BBF_HAS_JMP | BBF_KEEP_BBJ_ALWAYS | <API key>) // Flags gained by the bottom block when a block is split. // Note, this is a conservative guess. // For example, the bottom block might or might not have BBF_HAS_NEWARRAY, // but we assume it has BBF_HAS_NEWARRAY. // TODO: Should BBF_RUN_RARELY be added to BBF_SPLIT_GAINED ? #define BBF_SPLIT_GAINED \ (BBF_DONT_REMOVE | BBF_HAS_LABEL | BBF_HAS_JMP | BBF_BACKWARD_JUMP | BBF_HAS_IDX_LEN | BBF_HAS_NEWARRAY | \ BBF_PROF_WEIGHT | BBF_HAS_NEWOBJ | BBF_KEEP_BBJ_ALWAYS | <API key>) #ifndef __GNUC__ // GCC doesn't like C_ASSERT at global scope <API key>((BBF_SPLIT_NONEXIST & BBF_SPLIT_LOST) == 0); <API key>((BBF_SPLIT_NONEXIST & BBF_SPLIT_GAINED) == 0); #endif #ifdef DEBUG void dspFlags(); // Print the flags unsigned dspCheapPreds(); // Print the predecessors (bbCheapPreds) unsigned dspPreds(); // Print the predecessors (bbPreds) unsigned dspSuccs(Compiler* compiler); // Print the successors. The 'compiler' argument determines whether EH // regions are printed: see NumSucc() for details. void dspJumpKind(); // Print the block jump kind (e.g., BBJ_NONE, BBJ_COND, etc.). void dspBlockHeader(Compiler* compiler, bool showKind = true, bool showFlags = false, bool showPreds = true); // Print a simple basic block header for various output, including a // list of predecessors and successors. #endif // DEBUG typedef unsigned weight_t; // Type used to hold block and edge weights // Note that for CLR v2.0 and earlier our // block weights were stored using unsigned shorts #define BB_UNITY_WEIGHT 100 // how much a normal execute once block weights #define BB_LOOP_WEIGHT 8 // how much more loops are weighted #define BB_ZERO_WEIGHT 0 #define BB_MAX_WEIGHT ULONG_MAX // we're using an 'unsigned' for the weight #define BB_VERY_HOT_WEIGHT 256 // how many average hits a BB has (per BBT scenario run) for this block // to be considered as very hot weight_t bbWeight; // The dynamic execution weight of this block // getBBWeight -- get the normalized weight of this block unsigned getBBWeight(Compiler* comp); // setBBWeight -- if the block weight is not derived from a profile, then set the weight to the input // weight, but make sure to not overflow BB_MAX_WEIGHT void setBBWeight(unsigned weight) { if (!(this->bbFlags & BBF_PROF_WEIGHT)) { this->bbWeight = min(weight, BB_MAX_WEIGHT); } } // modifyBBWeight -- same as setBBWeight, but also make sure that if the block is rarely run, it stays that // way, and if it's not rarely run then its weight never drops below 1. void modifyBBWeight(unsigned weight) { if (this->bbWeight != BB_ZERO_WEIGHT) { setBBWeight(max(weight, 1)); } } // setBBProfileWeight -- Set the profile-derived weight for a basic block void setBBProfileWeight(unsigned weight) { this->bbFlags |= BBF_PROF_WEIGHT; // Check if the multiplication by BB_UNITY_WEIGHT will overflow. this->bbWeight = (weight <= BB_MAX_WEIGHT / BB_UNITY_WEIGHT) ? weight * BB_UNITY_WEIGHT : BB_MAX_WEIGHT; } // this block will inherit the same weight and relevant bbFlags as bSrc void inheritWeight(BasicBlock* bSrc) { this->bbWeight = bSrc->bbWeight; if (bSrc->bbFlags & BBF_PROF_WEIGHT) { this->bbFlags |= BBF_PROF_WEIGHT; } else { this->bbFlags &= ~BBF_PROF_WEIGHT; } if (this->bbWeight == 0) { this->bbFlags |= BBF_RUN_RARELY; } else { this->bbFlags &= ~BBF_RUN_RARELY; } } // Similar to inheritWeight(), but we're splitting a block (such as creating blocks for qmark removal). // So, specify a percentage (0 to 99; if it's 100, just use inheritWeight()) of the weight that we're // going to inherit. Since the number isn't exact, clear the BBF_PROF_WEIGHT flag. void <API key>(BasicBlock* bSrc, unsigned percentage) { assert(0 <= percentage && percentage < 100); // Check for overflow if (bSrc->bbWeight * 100 <= bSrc->bbWeight) { this->bbWeight = bSrc->bbWeight; } else { this->bbWeight = bSrc->bbWeight * percentage / 100; } this->bbFlags &= ~BBF_PROF_WEIGHT; if (this->bbWeight == 0) { this->bbFlags |= BBF_RUN_RARELY; } else { this->bbFlags &= ~BBF_RUN_RARELY; } } // makeBlockHot() // This is used to override any profiling data // and force a block to be in the hot region. // We only call this method for handler entry point // and only when <API key> is 1. // Doing this helps fgReorderBlocks() by telling // it to try to move these blocks into the hot region. // Note that we do this strictly as an optimization, // not for correctness. <API key>() // will find all handler entry points and ensure that // for now we don't place them in the cold section. void makeBlockHot() { if (this->bbWeight == BB_ZERO_WEIGHT) { this->bbFlags &= ~BBF_RUN_RARELY; // Clear any RarelyRun flag this->bbFlags &= ~BBF_PROF_WEIGHT; // Clear any profile-derived flag this->bbWeight = 1; } } bool isMaxBBWeight() { return (bbWeight == BB_MAX_WEIGHT); } // Returns "true" if the block is empty. Empty here means there are no statement // trees *except* PHI definitions. bool isEmpty(); // Returns "true" iff "this" is the first block of a BBJ_CALLFINALLY/BBJ_ALWAYS pair -- // a block corresponding to an exit from the try of a try/finally. In the flow graph, // this becomes a block that calls the finally, and a second, immediately // following empty block (in the bbNext chain) to which the finally will return, and which // branches unconditionally to the next block to be executed outside the try/finally. // Note that code is often generated differently than this description. For example, on ARM, // the target of the BBJ_ALWAYS is loaded in LR (the return register), and a direct jump is // made to the 'finally'. The effect is that the 'finally' returns directly to the target of // the BBJ_ALWAYS. A "retless" BBJ_CALLFINALLY is one that has no corresponding BBJ_ALWAYS. // This can happen if the finally is known to not return (e.g., it contains a 'throw'). In // that case, the BBJ_CALLFINALLY flags has BBF_RETLESS_CALL set. Note that ARM never has // "retless" BBJ_CALLFINALLY blocks due to a requirement to use the BBJ_ALWAYS for // generating code. bool isBBCallAlwaysPair() { #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) if (this->bbJumpKind == BBJ_CALLFINALLY) #else if ((this->bbJumpKind == BBJ_CALLFINALLY) && !(this->bbFlags & BBF_RETLESS_CALL)) #endif { #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // On ARM, there are no retless BBJ_CALLFINALLY. assert(!(this->bbFlags & BBF_RETLESS_CALL)); #endif // Some asserts that the next block is a BBJ_ALWAYS of the proper form. assert(this->bbNext != nullptr); assert(this->bbNext->bbJumpKind == BBJ_ALWAYS); assert(this->bbNext->bbFlags & BBF_KEEP_BBJ_ALWAYS); assert(this->bbNext->isEmpty()); return true; } else { return false; } } BBjumpKinds bbJumpKind; // jump (if any) at the end of this block /* The following union describes the jump target(s) of this block */ union { unsigned bbJumpOffs; // PC offset (temporary only) BasicBlock* bbJumpDest; // basic block BBswtDesc* bbJumpSwt; // switch descriptor }; // NumSucc() gives the number of successors, and GetSucc() allows one to iterate over them. // The behavior of both for blocks that end in BBJ_EHFINALLYRET (a return from a finally or fault block) // depends on whether "comp" is non-null. If it is null, then the block is considered to have no // successor. If it is non-null, we figure out the actual successors. Some cases will want one behavior, // other cases the other. For example, IL verification requires that these blocks end in an empty operand // stack, and since the dataflow analysis of IL verification is concerned only with the contents of the // operand stack, we can consider the finally block to have no successors. But a more general dataflow // analysis that is tracking the contents of local variables might want to consider *all* successors, // and would pass the current Compiler object. // Similarly, BBJ_EHFILTERRET blocks are assumed to have no successors if "comp" is null; if non-null, // NumSucc/GetSucc yields the first block of the try blocks handler. // Also, the behavior for switches changes depending on the value of "comp". If it is null, then all // switch successors are returned. If it is non-null, then only unique switch successors are returned; // the duplicate successors are omitted. // Note that for BBJ_COND, which has two successors (fall through and condition true branch target), // only the unique targets are returned. Thus, if both targets are the same, NumSucc() will only return 1 // instead of 2. // Returns the number of successors of "this". unsigned NumSucc(Compiler* comp = nullptr); // Returns the "i"th successor. Requires (0 <= i < NumSucc()). BasicBlock* GetSucc(unsigned i, Compiler* comp = nullptr); BasicBlock* GetUniquePred(Compiler* comp); BasicBlock* GetUniqueSucc(); unsigned countOfInEdges() const { return bbRefs; } __declspec(property(get = getBBTreeList, put = setBBTreeList)) GenTree* bbTreeList; // the body of the block. GenTree* getBBTreeList() const { return m_firstNode; } void setBBTreeList(GenTree* tree) { m_firstNode = tree; } EntryState* bbEntryState; // verifier tracked state of all entries in stack. #define NO_BASE_TMP UINT_MAX // base# to use when we have none unsigned bbStkTempsIn; // base# for input stack temps unsigned bbStkTempsOut; // base# for output stack temps #define MAX_XCPTN_INDEX (USHRT_MAX - 1) // It would be nice to make bbTryIndex and bbHndIndex private, but there is still code that uses them directly, // especially Compiler::fgNewBBinRegion() and friends. // index, into the compHndBBtab table, of innermost 'try' clause containing the BB (used for raising exceptions). // Stored as index + 1; 0 means "no try index". unsigned short bbTryIndex; // index, into the compHndBBtab table, of innermost handler (filter, catch, fault/finally) containing the BB. // Stored as index + 1; 0 means "no handler index". unsigned short bbHndIndex; // Given two EH indices that are either bbTryIndex or bbHndIndex (or related), determine if index1 might be more // deeply nested than index2. Both index1 and index2 are in the range [0..compHndBBtabCount], where 0 means // "main function" and otherwise the value is an index into compHndBBtab[]. Note that "sibling" EH regions will // have a numeric index relationship that doesn't indicate nesting, whereas a more deeply nested region must have // a lower index than the region it is nested within. Note that if you compare a single block's bbTryIndex and // bbHndIndex, there is guaranteed to be a nesting relationship, since that block can't be simultaneously in two // sibling EH regions. In that case, "maybe" is actually "definitely". static bool <API key>(unsigned index1, unsigned index2) { if (index1 == 0) { // index1 is in the main method. It can't be more deeply nested than index2. return false; } else if (index2 == 0) { // index1 represents an EH region, whereas index2 is the main method. Thus, index1 is more deeply nested. assert(index1 > 0); return true; } else { // If index1 has a smaller index, it might be more deeply nested than index2. assert(index1 > 0); assert(index2 > 0); return index1 < index2; } } // catch type: class token of handler, or one of BBCT_*. Only set on first block of catch handler. unsigned bbCatchTyp; bool hasTryIndex() const { return bbTryIndex != 0; } bool hasHndIndex() const { return bbHndIndex != 0; } unsigned getTryIndex() const { assert(bbTryIndex != 0); return bbTryIndex - 1; } unsigned getHndIndex() const { assert(bbHndIndex != 0); return bbHndIndex - 1; } void setTryIndex(unsigned val) { bbTryIndex = (unsigned short)(val + 1); assert(bbTryIndex != 0); } void setHndIndex(unsigned val) { bbHndIndex = (unsigned short)(val + 1); assert(bbHndIndex != 0); } void clearTryIndex() { bbTryIndex = 0; } void clearHndIndex() { bbHndIndex = 0; } void copyEHRegion(const BasicBlock* from) { bbTryIndex = from->bbTryIndex; bbHndIndex = from->bbHndIndex; } static bool sameTryRegion(const BasicBlock* blk1, const BasicBlock* blk2) { return blk1->bbTryIndex == blk2->bbTryIndex; } static bool sameHndRegion(const BasicBlock* blk1, const BasicBlock* blk2) { return blk1->bbHndIndex == blk2->bbHndIndex; } static bool sameEHRegion(const BasicBlock* blk1, const BasicBlock* blk2) { return sameTryRegion(blk1, blk2) && sameHndRegion(blk1, blk2); } // Some non-zero value that will not collide with real tokens for bbCatchTyp #define BBCT_NONE 0x00000000 #define BBCT_FAULT 0xFFFFFFFC #define BBCT_FINALLY 0xFFFFFFFD #define BBCT_FILTER 0xFFFFFFFE #define BBCT_FILTER_HANDLER 0xFFFFFFFF #define handlerGetsXcptnObj(hndTyp) ((hndTyp) != BBCT_NONE && (hndTyp) != BBCT_FAULT && (hndTyp) != BBCT_FINALLY) // TODO-Cleanup: Get rid of bbStkDepth and use bbStackDepthOnEntry() instead union { unsigned short bbStkDepth; // stack depth on entry unsigned short bbFPinVars; // number of inner enregistered FP vars }; // Basic block predecessor lists. Early in compilation, some phases might need to compute "cheap" predecessor // lists. These are stored in bbCheapPreds, computed by fgComputeCheapPreds(). If bbCheapPreds is valid, // in 'bbPreds', and then maintained throughout compilation. 'fgComputePredsDone' will be 'true' after the // full predecessor lists are created. See the comment at fgComputeCheapPreds() to see how those differ from // the "full" variant. union { BasicBlockList* bbCheapPreds; // ptr to list of cheap predecessors (used before normal preds are computed) flowList* bbPreds; // ptr to list of predecessors }; BlockSet bbReach; // Set of all blocks that can reach this one BasicBlock* bbIDom; // Represent the closest dominator to this block (called the Immediate // Dominator) used to compute the dominance tree. unsigned bbDfsNum; // The index of this block in DFS reverse post order // relative to the flow graph. #if ASSERTION_PROP // A set of blocks which dominate this one *except* the normal entry block. This is lazily initialized // and used only by Assertion Prop, intersected with fgEnterBlks! BlockSet bbDoms; #endif IL_OFFSET bbCodeOffs; // IL offset of the beginning of the block IL_OFFSET bbCodeOffsEnd; // IL offset past the end of the block. Thus, the [bbCodeOffs..bbCodeOffsEnd) // range is not inclusive of the end offset. The count of IL bytes in the block // is bbCodeOffsEnd - bbCodeOffs, assuming neither are BAD_IL_OFFSET. #ifdef DEBUG void dspBlockILRange(); // Display the block's IL range as [XXX...YYY), where XXX and YYY might be "???" for // BAD_IL_OFFSET. #endif // DEBUG VARSET_TP bbVarUse; // variables used by block (before an assignment) VARSET_TP bbVarDef; // variables assigned by block (before a use) VARSET_TP bbLiveIn; // variables live on entry VARSET_TP bbLiveOut; // variables live on exit // Use, def, live in/out information for the implicit memory variable. MemoryKindSet bbMemoryUse : MemoryKindCount; // must be set for any MemoryKinds this block references MemoryKindSet bbMemoryDef : MemoryKindCount; // must be set for any MemoryKinds this block mutates MemoryKindSet bbMemoryLiveIn : MemoryKindCount; MemoryKindSet bbMemoryLiveOut : MemoryKindCount; MemoryKindSet bbMemoryHavoc : MemoryKindCount; // If true, at some point the block does an operation // that leaves memory in an unknown state. (E.g., // unanalyzed call, store through unknown pointer...) // We want to make phi functions for the special implicit var memory. But since this is not a real // lclVar, and thus has no local #, we can't use a GenTreePhiArg. Instead, we use this struct. struct MemoryPhiArg { unsigned m_ssaNum; // SSA# for incoming value. MemoryPhiArg* m_nextArg; // Next arg in the list, else NULL. unsigned GetSsaNum() { return m_ssaNum; } MemoryPhiArg(unsigned ssaNum, MemoryPhiArg* nextArg = nullptr) : m_ssaNum(ssaNum), m_nextArg(nextArg) { } void* operator new(size_t sz, class Compiler* comp); }; static MemoryPhiArg* EmptyMemoryPhiDef; // Special value (0x1, FWIW) to represent a to-be-filled in Phi arg list // for Heap. MemoryPhiArg* bbMemorySsaPhiFunc[MemoryKindCount]; // If the "in" Heap SSA var is not a phi definition, this value // is NULL. // Otherwise, it is either the special value EmptyMemoryPhiDefn, to indicate // that Heap needs a phi definition on entry, or else it is the linked list // of the phi arguments. unsigned bbMemorySsaNumIn[MemoryKindCount]; // The SSA # of memory on entry to the block. unsigned bbMemorySsaNumOut[MemoryKindCount]; // The SSA # of memory on exit from the block. VARSET_TP bbScope; // variables in scope over the block void InitVarSets(class Compiler* comp); /* The following are the standard bit sets for dataflow analysis. * We perform CSE and range-checks at the same time * and assertion propagation separately, * thus we can union them since the two operations are completely disjunct. */ union { EXPSET_TP bbCseGen; // CSEs computed by block #if ASSERTION_PROP ASSERT_TP bbAssertionGen; // value assignments computed by block #endif }; union { #if ASSERTION_PROP ASSERT_TP bbAssertionKill; // value assignments killed by block #endif }; union { EXPSET_TP bbCseIn; // CSEs available on entry #if ASSERTION_PROP ASSERT_TP bbAssertionIn; // value assignments available on entry #endif }; union { EXPSET_TP bbCseOut; // CSEs available on exit #if ASSERTION_PROP ASSERT_TP bbAssertionOut; // value assignments available on exit #endif }; void* bbEmitCookie; #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) void* <API key>; #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) #ifdef VERIFIER stackDesc bbStackIn; // stack descriptor for input stackDesc bbStackOut; // stack descriptor for output verTypeVal* bbTypesIn; // list of variable types on input verTypeVal* bbTypesOut; // list of variable types on output #endif // VERIFIER #if <API key> FlatFPStateX87* bbFPStateX87; // State of FP stack on entry to the basic block #endif // <API key> /* The following fields used for loop detection */ typedef unsigned char loopNumber; static const unsigned NOT_IN_LOOP = UCHAR_MAX; #ifdef DEBUG // This is the label a loop gets as part of the second, reachability-based // loop discovery mechanism. This is apparently only used for debugging. // We hope we'll eventually just have one loop-discovery mechanism, and this will go away. loopNumber bbLoopNum; // set to 'n' for a loop #n header #endif // DEBUG loopNumber bbNatLoopNum; // Index, in optLoopTable, of most-nested loop that contains this block, // or else NOT_IN_LOOP if this block is not in a loop. #define MAX_LOOP_NUM 16 // we're using a 'short' for the mask #define LOOP_MASK_TP unsigned // must be big enough for a mask #if MEASURE_BLOCK_SIZE static size_t s_Size; static size_t s_Count; #endif // MEASURE_BLOCK_SIZE bool bbFallsThrough(); // Our slop fraction is 1/128 of the block weight rounded off static weight_t GetSlopFraction(weight_t weightBlk) { return ((weightBlk + 64) / 128); } // Given an the edge b1 -> b2, calculate the slop fraction by // using the higher of the two block weights static weight_t GetSlopFraction(BasicBlock* b1, BasicBlock* b2) { return GetSlopFraction(max(b1->bbWeight, b2->bbWeight)); } #ifdef DEBUG unsigned bbTgtStkDepth; // Native stack depth on entry (for throw-blocks) static unsigned s_nMaxTrees; // The max # of tree nodes in any BB unsigned bbStmtNum; // The statement number of the first stmt in this block // This is used in integrity checks. We semi-randomly pick a traversal stamp, label all blocks // in the BB list with that stamp (in this field); then we can tell if (e.g.) predecessors are // still in the BB list by whether they have the same stamp (with high probability). unsigned bbTraversalStamp; #endif // DEBUG ThisInitState bbThisOnEntry(); unsigned bbStackDepthOnEntry(); void bbSetStack(void* stackBuffer); StackEntry* bbStackOnEntry(); void bbSetRunRarely(); // "bbNum" is one-based (for unknown reasons); it is sometimes useful to have the corresponding // zero-based number for use as an array index. unsigned bbInd() { assert(bbNum > 0); return bbNum - 1; } GenTreeStmt* firstStmt() const; GenTreeStmt* lastStmt() const; GenTreeStmt* lastTopLevelStmt(); GenTree* firstNode(); GenTree* lastNode(); bool containsStatement(GenTree* statement); bool endsWithJmpMethod(Compiler* comp); bool endsWithTailCall(Compiler* comp, bool fastTailCallsOnly, bool <API key>, GenTree** tailCall); bool <API key>(Compiler* comp, bool fastTailCallsOnly = false); bool <API key>(Compiler* comp, GenTree** tailCall); // Returns the first statement in the statement list of "this" that is // not an SSA definition (a lcl = phi(...) assignment). GenTreeStmt* FirstNonPhiDef(); GenTree* <API key>(); BasicBlock() : #if ASSERTION_PROP <API key>(bbDoms, BlockSetOps::UninitVal()) , #endif // ASSERTION_PROP VARSET_INIT_NOCOPY(bbLiveIn, VarSetOps::UninitVal()) , VARSET_INIT_NOCOPY(bbLiveOut, VarSetOps::UninitVal()) { } private: EHSuccessorIter StartEHSuccs(Compiler* comp) { return EHSuccessorIter(comp, this); } EHSuccessorIter EndEHSuccs() { return EHSuccessorIter(); } friend struct EHSuccs; AllSuccessorIter StartAllSuccs(Compiler* comp) { return AllSuccessorIter(comp, this); } AllSuccessorIter EndAllSuccs(Compiler* comp) { return AllSuccessorIter(NumSucc(comp)); } friend struct AllSuccs; public: // Iteratable collection of the EH successors of a block. class EHSuccs { Compiler* m_comp; BasicBlock* m_block; public: EHSuccs(Compiler* comp, BasicBlock* block) : m_comp(comp), m_block(block) { } EHSuccessorIter begin() { return m_block->StartEHSuccs(m_comp); } EHSuccessorIter end() { return EHSuccessorIter(); } }; EHSuccs GetEHSuccs(Compiler* comp) { return EHSuccs(comp, this); } class AllSuccs { Compiler* m_comp; BasicBlock* m_block; public: AllSuccs(Compiler* comp, BasicBlock* block) : m_comp(comp), m_block(block) { } AllSuccessorIter begin() { return m_block->StartAllSuccs(m_comp); } AllSuccessorIter end() { return AllSuccessorIter(m_block->NumSucc(m_comp)); } }; AllSuccs GetAllSuccs(Compiler* comp) { return AllSuccs(comp, this); } // Try to clone block state and statements from `from` block to `to` block (which must be new/empty), // optionally replacing uses of local `varNum` with IntCns `varVal`. Return true if all statements // in the block are cloned successfully, false (with partially-populated `to` block) if one fails. static bool CloneBlockState( Compiler* compiler, BasicBlock* to, const BasicBlock* from, unsigned varNum = (unsigned)-1, int varVal = 0); void MakeLIR(GenTree* firstNode, GenTree* lastNode); bool IsLIR(); }; template <> struct PtrKeyFuncs<BasicBlock> : public KeyFuncsDefEquals<const BasicBlock*> { public: // Make sure hashing is deterministic and not on "ptr." static unsigned GetHashCode(const BasicBlock* ptr); }; // A set of blocks. typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, bool, <API key>> BlkSet; // A map of block -> set of blocks, can be used as sparse block trees. typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, BlkSet*, <API key>> BlkToBlkSetMap; // Map from Block to Block. Used for a variety of purposes. typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, BasicBlock*, <API key>> BlockToBlockMap; // In compiler terminology the control flow between two BasicBlocks // is typically referred to as an "edge". Most well known are the // backward branches for loops, which are often called "back-edges". // "struct flowList" is the type that represents our control flow edges. // This type is a linked list of zero or more "edges". // (The list of zero edges is represented by NULL.) // Every BasicBlock has a field called bbPreds of this type. This field // represents the list of "edges" that flow into this BasicBlock. // The flowList type only stores the BasicBlock* of the source for the // control flow edge. The destination block for the control flow edge // is implied to be the block which contained the bbPreds field. // For a switch branch target there may be multiple "edges" that have // the same source block (and destination block). We need to count the // number of these edges so that during optimization we will know when // we have zero of them. Rather than have extra flowList entries we // increment the flDupCount field. // When we have Profile weight for the BasicBlocks we can usually compute // the number of times each edge was executed by examining the adjacent // BasicBlock weights. As we are doing for BasicBlocks, we call the number // of times that a control flow edge was executed the "edge weight". // In order to compute the edge weights we need to use a bounded range // for every edge weight. These two fields, 'flEdgeWeightMin' and 'flEdgeWeightMax' // are used to hold a bounded range. Most often these will converge such // that both values are the same and that value is the exact edge weight. // Sometimes we are left with a rage of possible values between [Min..Max] // which represents an inexact edge weight. // and is incrementally kept up to date. // The edge weight are computed by Compiler::<API key>() // the edge weights are used to straighten conditional branches // by Compiler::fgReorderBlocks() // We have a simpler struct, BasicBlockList, which is simply a singly-linked // list of blocks. This is used for various purposes, but one is as a "cheap" // predecessor list, computed by fgComputeCheapPreds(), and stored as a list // on BasicBlock pointed to by bbCheapPreds. struct BasicBlockList { BasicBlockList* next; // The next BasicBlock in the list, nullptr for end of list. BasicBlock* block; // The BasicBlock of interest. BasicBlockList() : next(nullptr), block(nullptr) { } BasicBlockList(BasicBlock* blk, BasicBlockList* rest) : next(rest), block(blk) { } }; struct flowList { flowList* flNext; // The next BasicBlock in the list, nullptr for end of list. BasicBlock* flBlock; // The BasicBlock of interest. BasicBlock::weight_t flEdgeWeightMin; BasicBlock::weight_t flEdgeWeightMax; unsigned flDupCount; // The count of duplicate "edges" (use only for switch stmts) // These two methods are used to set new values for flEdgeWeightMin and flEdgeWeightMax // they are used only during the computation of the edge weights // They return false if the newWeight is not between the current [min..max] // when slop is non-zero we allow for the case where our weights might be off by 'slop' bool <API key>(BasicBlock::weight_t newWeight, BasicBlock::weight_t slop, bool* wbUsedSlop); bool <API key>(BasicBlock::weight_t newWeight, BasicBlock::weight_t slop, bool* wbUsedSlop); flowList() : flNext(nullptr), flBlock(nullptr), flEdgeWeightMin(0), flEdgeWeightMax(0), flDupCount(0) { } flowList(BasicBlock* blk, flowList* rest) : flNext(rest), flBlock(blk), flEdgeWeightMin(0), flEdgeWeightMax(0), flDupCount(0) { } }; // This enum represents a pre/post-visit action state to emulate a depth-first // spanning tree traversal of a tree or graph. enum DfsStackState { DSS_Invalid, // The initialized, invalid error state DSS_Pre, // The DFS pre-order (first visit) traversal state DSS_Post // The DFS post-order (last visit) traversal state }; // These structs represents an entry in a stack used to emulate a non-recursive // depth-first spanning tree traversal of a graph. The entry contains either a // block pointer or a block number depending on which is more useful. struct DfsBlockEntry { DfsStackState dfsStackState; // The pre/post traversal action for this entry BasicBlock* dfsBlock; // The corresponding block for the action DfsBlockEntry() : dfsStackState(DSS_Invalid), dfsBlock(nullptr) { } DfsBlockEntry(DfsStackState state, BasicBlock* basicBlock) : dfsStackState(state), dfsBlock(basicBlock) { } }; struct DfsNumEntry { DfsStackState dfsStackState; // The pre/post traversal action for this entry unsigned dfsNum; // The corresponding block number for the action DfsNumEntry() : dfsStackState(DSS_Invalid), dfsNum(0) { } DfsNumEntry(DfsStackState state, unsigned bbNum) : dfsStackState(state), dfsNum(bbNum) { } }; extern BasicBlock* __cdecl verAllocBasicBlock(); #ifdef DEBUG extern void __cdecl verDispBasicBlocks(); #endif /***************************************************************************** * * The following call-backs supplied by the client; it's used by the code * emitter to convert a basic block to its corresponding emitter cookie. */ void* emitCodeGetCookie(BasicBlock* block); AllSuccessorIter::AllSuccessorIter(Compiler* comp, BasicBlock* block) : m_comp(comp), m_blk(block), m_normSucc(0), m_numNormSuccs(block->NumSucc(comp)), m_ehIter(comp, block) { if (<API key>()) { ++m_ehIter; } } bool AllSuccessorIter::<API key>() { return (m_blk->bbJumpKind == BBJ_CALLFINALLY) && (m_ehIter != EHSuccessorIter()) && (m_blk->bbJumpDest == (*m_ehIter)); } void AllSuccessorIter::operator++(void) { if (m_normSucc < m_numNormSuccs) { m_normSucc++; } else { ++m_ehIter; // If the original block whose successors we're iterating over // is a BBJ_CALLFINALLY, that finally clause's first block // will be yielded as a normal successor. Don't also yield as // an exceptional successor. if (<API key>()) { ++m_ehIter; } } } // Requires that "this" is not equal to the standard "end" iterator. Returns the // current successor. BasicBlock* AllSuccessorIter::operator*() { if (m_normSucc < m_numNormSuccs) { return m_blk->GetSucc(m_normSucc, m_comp); } else { return *m_ehIter; } } #endif // _BLOCK_H_
// FBO.h #pragma once #if defined(_WIN32) #include <windows.h> #endif #ifdef __APPLE__ #include <OpenGL/glu.h> #else #include <GL/glu.h> #endif struct FBO { GLuint id, tex, depth; GLuint w, h; }; void allocateFBO(FBO&, int w, int h); void deallocateFBO(FBO&); void bindFBO(const FBO&, float fboScale=1.0f); void unbindFBO();
export interface <API key> { /** * Card number */ number: string; /** * Expiry month */ expMonth: number; /** * Expiry year */ expYear: number; /** * CVC / CVV */ cvc?: string; /** * Cardholder name */ name?: string; /** * Address line 1 */ address_line1?: string; /** * Address line 2 */ address_line2?: string; /** * City */ address_city?: string; /** * State / Province */ address_state?: string; /** * Country */ address_country?: string; /** * Postal code / ZIP Code */ postal_code?: string; /** * 3-letter ISO code for currency */ currency?: string; } /** * @beta * @name Stripe * @description * A plugin that allows you to use Stripe's Native SDKs for Android and iOS. * * @usage * ``` * import { Stripe } from 'ionic-native'; * * Stripe.setPublishableKey('my_publishable_key'); * * let card = { * number: '4242424242424242', * expMonth: 12, * expYear: 2020, * cvc: 220 * }; * * Stripe.createToken(card) * .then(token => console.log(token)) * .catch(error => console.error(error)); * * ``` * * @interfaces * <API key> */ export declare class Stripe { /** * Set publishable key * @param publishableKey {string} Publishable key * @return {Promise<void>} */ static setPublishableKey(publishableKey: string): Promise<void>; /** * Create Credit Card Token * @param params {<API key>} Credit card information * @return {Promise<string>} returns a promise that resolves with the token, or reject with an error */ static createCardToken(params: <API key>): Promise<string>; }
require 'helper' class TestRepeaterWeek < TestCase def setup @now = Time.local(2006, 8, 16, 14, 0, 0, 0) end def test_next_future weeks = Chronic::RepeaterWeek.new(:week) weeks.start = @now next_week = weeks.next(:future) assert_equal Time.local(2006, 8, 20), next_week.begin assert_equal Time.local(2006, 8, 27), next_week.end next_next_week = weeks.next(:future) assert_equal Time.local(2006, 8, 27), next_next_week.begin assert_equal Time.local(2006, 9, 3), next_next_week.end end def test_next_past weeks = Chronic::RepeaterWeek.new(:week) weeks.start = @now last_week = weeks.next(:past) assert_equal Time.local(2006, 8, 6), last_week.begin assert_equal Time.local(2006, 8, 13), last_week.end last_last_week = weeks.next(:past) assert_equal Time.local(2006, 7, 30), last_last_week.begin assert_equal Time.local(2006, 8, 6), last_last_week.end end def test_this_future weeks = Chronic::RepeaterWeek.new(:week) weeks.start = @now this_week = weeks.this(:future) assert_equal Time.local(2006, 8, 16, 15), this_week.begin assert_equal Time.local(2006, 8, 20), this_week.end end def test_this_past weeks = Chronic::RepeaterWeek.new(:week) weeks.start = @now this_week = weeks.this(:past) assert_equal Time.local(2006, 8, 13, 0), this_week.begin assert_equal Time.local(2006, 8, 16, 14), this_week.end end def test_offset span = Chronic::Span.new(@now, @now + 1) offset_span = Chronic::RepeaterWeek.new(:week).offset(span, 3, :future) assert_equal Time.local(2006, 9, 6, 14), offset_span.begin assert_equal Time.local(2006, 9, 6, 14, 0, 1), offset_span.end end def <API key> weeks = Chronic::RepeaterWeek.new(:week, :week_start => :monday) weeks.start = @now next_week = weeks.next(:future) assert_equal Time.local(2006, 8, 21), next_week.begin assert_equal Time.local(2006, 8, 28), next_week.end next_next_week = weeks.next(:future) assert_equal Time.local(2006, 8, 28), next_next_week.begin assert_equal Time.local(2006, 9, 4), next_next_week.end end def <API key> weeks = Chronic::RepeaterWeek.new(:week, :week_start => :monday) weeks.start = @now last_week = weeks.next(:past) assert_equal Time.local(2006, 8, 7), last_week.begin assert_equal Time.local(2006, 8, 14), last_week.end last_last_week = weeks.next(:past) assert_equal Time.local(2006, 7, 31), last_last_week.begin assert_equal Time.local(2006, 8, 7), last_last_week.end end def <API key> weeks = Chronic::RepeaterWeek.new(:week, :week_start => :monday) weeks.start = @now this_week = weeks.this(:future) assert_equal Time.local(2006, 8, 16, 15), this_week.begin assert_equal Time.local(2006, 8, 21), this_week.end end def <API key> weeks = Chronic::RepeaterWeek.new(:week, :week_start => :monday) weeks.start = @now this_week = weeks.this(:past) assert_equal Time.local(2006, 8, 14, 0), this_week.begin assert_equal Time.local(2006, 8, 16, 14), this_week.end end def <API key> weeks = Chronic::RepeaterWeek.new(:week, :week_start => :monday) span = Chronic::Span.new(@now, @now + 1) offset_span = weeks.offset(span, 3, :future) assert_equal Time.local(2006, 9, 6, 14), offset_span.begin assert_equal Time.local(2006, 9, 6, 14, 0, 1), offset_span.end end end
<?php namespace OC\User; use OC\Hooks\PublicEmitter; use OCP\IUserManager; /** * Class Manager * * Hooks available in scope \OC\User: * - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword) * - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword) * - preDelete(\OC\User\User $user) * - postDelete(\OC\User\User $user) * - preCreateUser(string $uid, string $password) * - postCreateUser(\OC\User\User $user, string $password) * * @package OC\User */ class Manager extends PublicEmitter implements IUserManager { /** * @var \OC_User_Interface[] $backends */ private $backends = array(); /** * @var \OC\User\User[] $cachedUsers */ private $cachedUsers = array(); /** * @var \OC\AllConfig $config */ private $config; /** * @param \OC\AllConfig $config */ public function __construct($config = null) { $this->config = $config; $cachedUsers = $this->cachedUsers; $this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) { $i = array_search($user, $cachedUsers); if ($i !== false) { unset($cachedUsers[$i]); } }); $this->listen('\OC\User', 'postLogin', function ($user) { $user-><API key>(); }); $this->listen('\OC\User', 'postRememberedLogin', function ($user) { $user-><API key>(); }); } /** * register a user backend * * @param \OC_User_Interface $backend */ public function registerBackend($backend) { $this->backends[] = $backend; } /** * remove a user backend * * @param \OC_User_Interface $backend */ public function removeBackend($backend) { $this->cachedUsers = array(); if (($i = array_search($backend, $this->backends)) !== false) { unset($this->backends[$i]); } } /** * remove all user backends */ public function clearBackends() { $this->cachedUsers = array(); $this->backends = array(); } /** * get a user by user id * * @param string $uid * @return \OC\User\User */ public function get($uid) { if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends return $this->cachedUsers[$uid]; } foreach ($this->backends as $backend) { if ($backend->userExists($uid)) { return $this->getUserObject($uid, $backend); } } return null; } /** * get or construct the user object * * @param string $uid * @param \OC_User_Interface $backend * @return \OC\User\User */ protected function getUserObject($uid, $backend) { if (isset($this->cachedUsers[$uid])) { return $this->cachedUsers[$uid]; } $this->cachedUsers[$uid] = new User($uid, $backend, $this, $this->config); return $this->cachedUsers[$uid]; } /** * check if a user exists * * @param string $uid * @return bool */ public function userExists($uid) { $user = $this->get($uid); return ($user !== null); } /** * remove deleted user from cache * * @param string $uid * @return bool */ public function delete($uid) { if (isset($this->cachedUsers[$uid])) { unset($this->cachedUsers[$uid]); return true; } return false; } /** * Check if the password is valid for the user * * @param string $loginname * @param string $password * @return mixed the User object on success, false otherwise */ public function checkPassword($loginname, $password) { foreach ($this->backends as $backend) { if ($backend->implementsActions(\<API key>)) { $uid = $backend->checkPassword($loginname, $password); if ($uid !== false) { return $this->getUserObject($uid, $backend); } } } $remoteAddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''; $forwardedFor = isset($_SERVER['<API key>']) ? $_SERVER['<API key>'] : ''; \OC::$server->getLogger()->warning('Login failed: \''. $loginname .'\' (Remote IP: \''. $remoteAddr .'\', X-Forwarded-For: \''. $forwardedFor .'\')', array('app' => 'core')); return false; } /** * search by user id * * @param string $pattern * @param int $limit * @param int $offset * @return \OC\User\User[] */ public function search($pattern, $limit = null, $offset = null) { $users = array(); foreach ($this->backends as $backend) { $backendUsers = $backend->getUsers($pattern, $limit, $offset); if (is_array($backendUsers)) { foreach ($backendUsers as $uid) { $users[$uid] = $this->getUserObject($uid, $backend); } } } uasort($users, function ($a, $b) { /** * @var \OC\User\User $a * @var \OC\User\User $b */ return strcmp($a->getUID(), $b->getUID()); }); return $users; } /** * search by displayName * * @param string $pattern * @param int $limit * @param int $offset * @return \OC\User\User[] */ public function searchDisplayName($pattern, $limit = null, $offset = null) { $users = array(); foreach ($this->backends as $backend) { $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset); if (is_array($backendUsers)) { foreach ($backendUsers as $uid => $displayName) { $users[] = $this->getUserObject($uid, $backend); } } } usort($users, function ($a, $b) { /** * @var \OC\User\User $a * @var \OC\User\User $b */ return strcmp($a->getDisplayName(), $b->getDisplayName()); }); return $users; } /** * @param string $uid * @param string $password * @throws \Exception * @return bool|\OC\User\User the created user of false */ public function createUser($uid, $password) { $l = \OC_L10N::get('lib'); // Check the name for bad characters // Allowed are: "a-z", "A-Z", "0-9" and "_.@-" if (preg_match('/[^a-zA-Z0-9 _\.@\-]/', $uid)) { throw new \Exception($l->t('Only the following characters are allowed in a username:' . ' "a-z", "A-Z", "0-9", and "_.@-"')); } // No empty username if (trim($uid) == '') { throw new \Exception($l->t('A valid username must be provided')); } // No empty password if (trim($password) == '') { throw new \Exception($l->t('A valid password must be provided')); } // Check if user already exists if ($this->userExists($uid)) { throw new \Exception($l->t('The username is already being used')); } $this->emit('\OC\User', 'preCreateUser', array($uid, $password)); foreach ($this->backends as $backend) { if ($backend->implementsActions(\<API key>)) { $backend->createUser($uid, $password); $user = $this->getUserObject($uid, $backend); $this->emit('\OC\User', 'postCreateUser', array($user, $password)); return $user; } } return false; } /** * returns how many users per backend exist (if supported by backend) * * @return array an array of backend class as key and count number as value */ public function countUsers() { $userCountStatistics = array(); foreach ($this->backends as $backend) { if ($backend->implementsActions(\<API key>)) { $backendusers = $backend->countUsers(); if($backendusers !== false) { if(isset($userCountStatistics[get_class($backend)])) { $userCountStatistics[get_class($backend)] += $backendusers; } else { $userCountStatistics[get_class($backend)] = $backendusers; } } } } return $userCountStatistics; } }
var dep = require('./dep'); dep('');
package org.multibit.hd.ui.views.wizards.appearance_settings; import com.google.common.base.Optional; import org.multibit.hd.ui.views.wizards.AbstractWizard; import org.multibit.hd.ui.views.wizards.<API key>; import java.util.Map; /** * <p>Wizard to provide the following to UI for "appearance" wizard:</p> * <ol> * <li>Enter details</li> * </ol> * * @since 0.0.1 * */ public class <API key> extends AbstractWizard<<API key>> { public <API key>(<API key> model) { super(model, false, Optional.absent()); } @Override protected void <API key>(Map<String, <API key>> wizardViewMap) { // Use the wizard parameter to retrieve the appropriate mode wizardViewMap.put( <API key>.<API key>.name(), new <API key>(this, <API key>.<API key>.name()) ); } }
// TODO: This doesn't pass on android 64bit CI... // Figure out why! #![cfg(not(target_os = "android"))] use mio::{Events, Poll, PollOpt, Ready, Token}; use mio::net::UdpSocket; use bytes::{Buf, MutBuf, RingBuf, SliceBuf}; use std::str; use std::net::IpAddr; use localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf, localhost: IpAddr, shutdown: bool, } impl UdpHandler { fn new(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler { let sock = UdpSocket::bind(&"127.0.0.1:12345".parse().unwrap()).unwrap(); UdpHandler { tx: tx, rx: rx, msg: msg, buf: SliceBuf::wrap(msg.as_bytes()), rx_buf: RingBuf::new(1024), localhost: sock.local_addr().unwrap().ip(), shutdown: false, } } fn handle_read(&mut self, _: &mut Poll, token: Token, _: Ready) { match token { LISTENER => { debug!("We are receiving a datagram now..."); match unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()) } { Ok((cnt, addr)) => { unsafe { MutBuf::advance(&mut self.rx_buf, cnt); } assert_eq!(addr.ip(), self.localhost); } res => panic!("unexpected result: {:?}", res), } assert!(str::from_utf8(self.rx_buf.bytes()).unwrap() == self.msg); self.shutdown = true; }, _ => () } } fn handle_write(&mut self, _: &mut Poll, token: Token, _: Ready) { match token { SENDER => { let addr = self.rx.local_addr().unwrap(); let cnt = self.tx.send_to(self.buf.bytes(), &addr).unwrap(); self.buf.advance(cnt); }, _ => () } } } #[test] pub fn test_multicast() { drop(::env_logger::init()); debug!("Starting <API key>"); let mut poll = Poll::new().unwrap(); let addr = localhost(); let any = "0.0.0.0:0".parse().unwrap(); let tx = UdpSocket::bind(&any).unwrap(); let rx = UdpSocket::bind(&addr).unwrap(); info!("Joining group 227.1.1.100"); let any = "0.0.0.0".parse().unwrap(); rx.join_multicast_v4(&"227.1.1.100".parse().unwrap(), &any).unwrap(); info!("Joining group 227.1.1.101"); rx.join_multicast_v4(&"227.1.1.101".parse().unwrap(), &any).unwrap(); info!("Registering SENDER"); poll.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap(); info!("Registering LISTENER"); poll.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap(); let mut events = Events::with_capacity(1024); let mut handler = UdpHandler::new(tx, rx, "hello world"); info!("Starting event loop to test with..."); while !handler.shutdown { poll.poll(&mut events, None).unwrap(); for event in &events { if event.readiness().is_readable() { handler.handle_read(&mut poll, event.token(), event.readiness()); } if event.readiness().is_writable() { handler.handle_write(&mut poll, event.token(), event.readiness()); } } } }
#ifndef __modelrepository_h #define __modelrepository_h #include "editor/imodelrepository.h" class AresEdit3DView; class AppAresEditWX; class <API key>; class FactoriesValue; class ObjectsValue; class TemplatesValue; class ClassesValue; class ActionsValue; class WizardsValue; /** * The model repository. */ class ModelRepository : public scfImplementation1<ModelRepository, iModelRepository> { private: AppAresEditWX* app; csRef<<API key>> <API key>; csRef<FactoriesValue> factoriesValue; csRef<ObjectsValue> objectsValue; csRef<TemplatesValue> templatesValue; csRef<ClassesValue> classesValue; csRef<ActionsValue> actionsValue; csRef<WizardsValue> <API key>; csRef<WizardsValue> questWizardsValue; Debug drawing enabled. public: ModelRepository (AresEdit3DView* view3d, AppAresEditWX* app); virtual ~ModelRepository (); ObjectsValue* GetObjectsValueInt () { return objectsValue; } TemplatesValue* <API key> () { return templatesValue; } // Refresh the models after load or save. virtual void Refresh (); virtual Ares::Value* <API key> () const; virtual Ares::Value* GetFactoriesValue () const; virtual Ares::Value* GetObjectsValue () const; virtual Ares::Value* GetTemplatesValue () const; virtual csRef<Ares::Value> <API key> () const; virtual csRef<Ares::Value> GetAssetsValue () const; virtual csRef<Ares::Value> GetResourcesValue () const; virtual csRef<Ares::Value> GetQuestsValue () const; virtual Ares::Value* GetClassesValue () const; virtual Ares::Value* GetActionsValue () const; virtual Ares::Value* <API key> () const; virtual Ares::Value* <API key> () const; virtual csRef<Ares::Value> <API key> () const; virtual csRef<Ares::Value> <API key> (const char* pcname) const; virtual void RefreshObjectsValue (); virtual iDynamicObject* <API key> (Ares::Value* value); virtual iObject* <API key> (Ares::Value* value); virtual iAsset* GetAssetFromAssets (Ares::Value* value); virtual size_t <API key> (iDynamicObject* dynobj); virtual size_t <API key> (iCelEntityTemplate* tpl); }; #endif // __modelrepository_h
layout: center permalink: /404.html # 404 Sorry, we can't seem to find this page's pixylls. <div class="mt3"> <a href="{{ site.baseurl }}/" class="button button-blue button-big">Home</a> <a href="{{ site.baseurl }}/about/" class="button button-blue button-big">About</a> </div>
package scorex.network.peer import java.net.InetSocketAddress //todo: add optional nonce case class PeerInfo(lastSeen: Long, nonce: Option[Long] = None, nodeName: Option[String] = None) trait PeerDatabase { def <API key>(peer: InetSocketAddress, peerInfo: PeerInfo): Unit def knownPeers(forSelf: Boolean): Map[InetSocketAddress, PeerInfo] def blacklistPeer(peer: InetSocketAddress): Unit def blacklistedPeers(): Seq[String] def isBlacklisted(address: InetSocketAddress): Boolean }
package org.opendaylight.controller.netconf.<API key>.mapping.attributes.toxml; import com.google.common.base.Preconditions; import org.opendaylight.controller.netconf.<API key>.util.Util; import org.w3c.dom.Document; import java.util.List; import java.util.Map; public class <API key> extends <API key> { /** * @param document * @param key */ public <API key>(Document document, String key) { super(document, key); } protected Object preprocess(Object value) { Util.checkType(value, Map.class); Preconditions.checkArgument(((Map)value).size() == 1, "Unexpected number of values in %s, expected 1", value); Object listOfStrings = ((Map) value).values().iterator().next(); Util.checkType(listOfStrings, List.class); StringBuilder b = new StringBuilder(); for (Object character: (List)listOfStrings) { Util.checkType(character, String.class); b.append(character); } return b.toString(); } }
package org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.openhealthtools.mdht.emf.w3c.xhtml.Code; import org.openhealthtools.mdht.emf.w3c.xhtml.MifClassType; import org.openhealthtools.mdht.emf.w3c.xhtml.StyleSheet; import org.openhealthtools.mdht.emf.w3c.xhtml.XhtmlPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Code</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getClass_ <em>Class</em>}</li> * <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getLang <em>Lang</em>}</li> * <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getStyle <em>Style</em>}</li> * </ul> * </p> * * @generated */ public class CodeImpl extends InlineImpl implements Code { /** * The default value of the '{@link #getClass_() <em>Class</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getClass_() * @generated * @ordered */ protected static final MifClassType CLASS_EDEFAULT = MifClassType.INSERTED; /** * The cached value of the '{@link #getClass_() <em>Class</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getClass_() * @generated * @ordered */ protected MifClassType class_ = CLASS_EDEFAULT; /** * This is true if the Class attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean classESet; /** * The default value of the '{@link #getLang() <em>Lang</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLang() * @generated * @ordered */ protected static final String LANG_EDEFAULT = null; /** * The cached value of the '{@link #getLang() <em>Lang</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLang() * @generated * @ordered */ protected String lang = LANG_EDEFAULT; /** * The default value of the '{@link #getStyle() <em>Style</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStyle() * @generated * @ordered */ protected static final StyleSheet STYLE_EDEFAULT = StyleSheet.REQUIREMENT; /** * The cached value of the '{@link #getStyle() <em>Style</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStyle() * @generated * @ordered */ protected StyleSheet style = STYLE_EDEFAULT; /** * This is true if the Style attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean styleESet; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CodeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return XhtmlPackage.Literals.CODE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MifClassType getClass_() { return class_; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setClass(MifClassType newClass) { MifClassType oldClass = class_; class_ = newClass == null ? CLASS_EDEFAULT : newClass; boolean oldClassESet = classESet; classESet = true; if (<API key>()) { eNotify(new ENotificationImpl( this, Notification.SET, XhtmlPackage.CODE__CLASS, oldClass, class_, !oldClassESet)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void unsetClass() { MifClassType oldClass = class_; boolean oldClassESet = classESet; class_ = CLASS_EDEFAULT; classESet = false; if (<API key>()) { eNotify(new ENotificationImpl( this, Notification.UNSET, XhtmlPackage.CODE__CLASS, oldClass, CLASS_EDEFAULT, oldClassESet)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isSetClass() { return classESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLang() { return lang; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLang(String newLang) { String oldLang = lang; lang = newLang; if (<API key>()) { eNotify(new ENotificationImpl(this, Notification.SET, XhtmlPackage.CODE__LANG, oldLang, lang)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public StyleSheet getStyle() { return style; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStyle(StyleSheet newStyle) { StyleSheet oldStyle = style; style = newStyle == null ? STYLE_EDEFAULT : newStyle; boolean oldStyleESet = styleESet; styleESet = true; if (<API key>()) { eNotify(new ENotificationImpl( this, Notification.SET, XhtmlPackage.CODE__STYLE, oldStyle, style, !oldStyleESet)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void unsetStyle() { StyleSheet oldStyle = style; boolean oldStyleESet = styleESet; style = STYLE_EDEFAULT; styleESet = false; if (<API key>()) { eNotify(new ENotificationImpl( this, Notification.UNSET, XhtmlPackage.CODE__STYLE, oldStyle, STYLE_EDEFAULT, oldStyleESet)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isSetStyle() { return styleESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case XhtmlPackage.CODE__CLASS: return getClass_(); case XhtmlPackage.CODE__LANG: return getLang(); case XhtmlPackage.CODE__STYLE: return getStyle(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case XhtmlPackage.CODE__CLASS: setClass((MifClassType) newValue); return; case XhtmlPackage.CODE__LANG: setLang((String) newValue); return; case XhtmlPackage.CODE__STYLE: setStyle((StyleSheet) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case XhtmlPackage.CODE__CLASS: unsetClass(); return; case XhtmlPackage.CODE__LANG: setLang(LANG_EDEFAULT); return; case XhtmlPackage.CODE__STYLE: unsetStyle(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case XhtmlPackage.CODE__CLASS: return isSetClass(); case XhtmlPackage.CODE__LANG: return LANG_EDEFAULT == null ? lang != null : !LANG_EDEFAULT.equals(lang); case XhtmlPackage.CODE__STYLE: return isSetStyle(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) { return super.toString(); } StringBuffer result = new StringBuffer(super.toString()); result.append(" (class: "); if (classESet) { result.append(class_); } else { result.append("<unset>"); } result.append(", lang: "); result.append(lang); result.append(", style: "); if (styleESet) { result.append(style); } else { result.append("<unset>"); } result.append(')'); return result.toString(); } } // CodeImpl
/* _XOPEN_SOURCE is needed to bring in the header for ptsname */ #define _XOPEN_SOURCE #include <sys/types.h> #include <sys/ioctl.h> #include <fcntl.h> #include <termios.h> #include <unistd.h> #include <stdbool.h> /** * This is taken from R. W. Stevens book. * Alain Magloire. */ void set_noecho(int fd) { struct termios stermios; if (tcgetattr(fd, &stermios) < 0) { return ; } /* turn off echo */ stermios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL); /* Turn off the NL to CR/NL mapping ou output. */ /*stermios.c_oflag &= ~(ONLCR);*/ stermios.c_iflag |= (IGNCR); tcsetattr(fd, TCSANOW, &stermios); } int ptys_open(int fdm, const char *pts_name, bool acquire) { int fds; /* following should allocate controlling terminal */ fds = open(pts_name, O_RDWR); if (fds < 0) { close(fdm); return -5; } #if defined(TIOCSCTTY) if (acquire) { /* TIOCSCTTY is the BSD way to acquire a controlling terminal. */ if (ioctl(fds, TIOCSCTTY, (char *) 0) < 0) { // ignore error: this is expected in console-mode } } #endif return fds; }
package com.vectrace.MercurialEclipse.commands; import java.io.File; import java.util.List; import org.eclipse.core.runtime.Assert; /** * A command to invoke hg definitely outside of an hg root. */ public class RootlessHgCommand extends <API key> { public RootlessHgCommand(String command, String uiName) { this(command, uiName, null); } public RootlessHgCommand(String command, String uiName, File workingDir) { super(uiName, null, workingDir, false); Assert.isNotNull(command); this.command = command; } // operations /** * @see com.vectrace.MercurialEclipse.commands.<API key>#customizeCommands(java.util.List) */ @Override protected void customizeCommands(List<String> cmd) { cmd.add(1, "-y"); } /** * @see com.vectrace.MercurialEclipse.commands.<API key>#getExecutable() */ @Override protected String getExecutable() { return HgClients.getExecutable(); } }
#include "parser.h" #include "test.h" int main(int argc, char *argv[]) { BOOL ret; char *fname, *test; int fd; struct stat st; io_struct ps; if (argc < 3) { printf("usage: vluke <structure> <file>\n"); exit(1); } test = argv[1]; fname = argv[2]; fd = open(fname,O_RDONLY); if (fd == -1) { perror(fname); exit(1); } fstat(fd, &st); io_init(&ps, 0, MARSHALL); ps.is_dynamic=True; io_read(&ps, fd, st.st_size, 0); ps.data_offset = 0; ps.buffer_size = ps.grow_size; ps.io = UNMARSHALL; ps.autoalign = OPTION_autoalign; ret = run_test(test, &ps, PARSE_SCALARS|PARSE_BUFFERS); printf("\nret=%s\n", ret?"OK":"Bad"); printf("Trailer is %d bytes\n\n", ps.grow_size - ps.data_offset); if (ps.grow_size - ps.data_offset > 0) { dump_data(0, ps.data_p + ps.data_offset, ps.grow_size - ps.data_offset); } return !ret; }
package org.opennms.smoketest; import org.junit.Before; import org.junit.Test; public class ChartsPageTest extends <API key> { @Before public void setUp() throws Exception { super.setUp(); clickAndWait("link=Charts"); } @Test public void testChartsPage() throws Exception { waitForText("Charts"); waitForElement("css=img[alt=sample-bar-chart]"); waitForElement("css=img[alt=sample-bar-chart2]"); waitForElement("css=img[alt=sample-bar-chart3]"); } }
#ifndef TABLEDICT_H #define TABLEDICT_H #include <fcitx-utils/utf8.h> #include <fcitx-config/fcitx-config.h> #include <fcitx-config/hotkey.h> #include <fcitx-utils/memory.h> #define MAX_CODE_LENGTH 30 #define PHRASE_MAX_LENGTH 10 #define FH_MAX_LENGTH 10 #define <API key> 1024 #define AUTO_PHRASE_COUNT 10000 #define SINGLE_HZ_COUNT 66000 #define RECORDTYPE_NORMAL 0x0 #define RECORDTYPE_PINYIN 0x1 #define <API key> 0x2 #define RECORDTYPE_PROMPT 0x3 struct _FcitxTableState; typedef enum _ADJUSTORDER { AD_NO = 0, AD_FAST = 1, AD_FREQ = 2 } ADJUSTORDER; typedef struct _FH { char strFH[FH_MAX_LENGTH * 2 + 1]; } FH; typedef struct _RULE_RULE { unsigned char iFlag; // 1 --> 0 --> unsigned char iWhich; unsigned char iIndex; } RULE_RULE; typedef struct _RULE { unsigned char iWords; unsigned char iFlag; //1 --> iWords 0 --> iWords RULE_RULE *rule; } RULE; typedef struct _RECORD { char *strCode; char *strHZ; struct _RECORD *next; struct _RECORD *prev; unsigned int iHit; unsigned int iIndex; int8_t type; } RECORD; typedef struct _AUTOPHRASE { char *strHZ; char *strCode; char iSelected; struct _AUTOPHRASE *next; } AUTOPHRASE; typedef struct _RECORD_INDEX { RECORD *record; char cCode; } RECORD_INDEX; typedef struct _SINGLE_HZ { char strHZ[UTF8_MAX_LENGTH + 1]; } SINGLE_HZ; typedef struct _TableMetaData { FcitxGenericConfig config; char *uniqueName; char *strName; char *strIconName; char *strPath; ADJUSTORDER tableOrder; int iPriority; boolean bUsePY; char cPinyin; int <API key>; int <API key>; boolean bSendRawPreedit; char *strEndCode; boolean bUseMatchingKey; char cMatchingKey; boolean bTableExactMatch; boolean bAutoPhrase; boolean bAutoPhrasePhrase; int iAutoPhraseLength; int <API key>; //N0-1- boolean bPromptTableCode; char *strSymbol; char *strSymbolFile; char *strChoose; char *langCode; char *kbdlayout; boolean customPrompt; boolean <API key>; boolean <API key>; boolean <API key>; boolean bIgnorePunc; FcitxHotkey <API key>[2]; FcitxHotkey <API key>[2]; boolean bEnabled; struct _FcitxTableState* owner; struct _TableDict* tableDict; } TableMetaData; typedef struct _TableDict { char* strInputCode; RECORD_INDEX* recordIndex; unsigned char iCodeLength; unsigned char iPYCodeLength; char* strIgnoreChars; unsigned char bRule; RULE* rule; unsigned int iRecordCount; RECORD* tableSingleHZ[SINGLE_HZ_COUNT]; RECORD* tableSingleHZCons[SINGLE_HZ_COUNT]; unsigned int iTableIndex; boolean bHasPinyin; RECORD* currentRecord; RECORD* recordHead; int iFH; FH* fh; char* strNewPhraseCode; AUTOPHRASE* autoPhrase; AUTOPHRASE* insertPoint; int iAutoPhrase; int iTableChanged; int iHZLastInputCount; SINGLE_HZ hzLastInput[PHRASE_MAX_LENGTH]; //Records last HZ input RECORD* promptCode[256]; FcitxMemoryPool* pool; } TableDict; boolean LoadTableDict(TableMetaData* tableMetaData); void SaveTableDict(TableMetaData* tableMetaData); void FreeTableDict(TableMetaData* tableMetaData); void TableInsertPhrase(TableDict* tableDict, const char *strCode, const char *strHZ); RECORD *TableFindPhrase(const TableDict* tableDict, const char *strHZ); boolean <API key>(TableDict* tableDict, char* strHZ); void <API key>(TableMetaData* tableMetaData, char iCount); RECORD *TableHasPhrase(const TableDict* tableDict, const char *strCode, const char *strHZ); void TableDelPhraseByHZ(TableDict* tableDict, const char *strHZ); void TableDelPhrase(TableDict* tableDict, RECORD * record); void <API key>(TableMetaData* tableMetaData, RECORD * record); int TableCompareCode(const TableMetaData* tableMetaData, const char *strUser, const char *strDict); int <API key>(TableMetaData* tableMetaData, const char* strCodeInput); void TableResetFlags(TableDict* tableDict); boolean IsInputKey(const TableDict* tableDict, int iKey); boolean IsEndKey(const TableMetaData* tableMetaData, char cChar); boolean IsIgnoreChar(const TableDict* tableDict, char cChar); unsigned int CalHZIndex(char *strHZ); boolean HasMatchingKey(const TableMetaData* tableMetaData, const char* strCodeInput); <API key>(TableMetaData); #endif // kate: indent-mode cstyle; space-indent on; indent-width 0;
<?php defined('GANTRY_VERSION') or die(); /** * Base class for all Gantry custom features. * * @package gantry * @subpackage core */ class GantryLayout { var $render_params = array(); function render($params = array()){ global $gantry; ob_start(); return ob_get_clean(); } function _getParams($params = array()){ $ret = new stdClass(); $ret_array = array_merge($this->render_params, $params); foreach($ret_array as $param_name => $param_value){ $ret->$param_name = $param_value; } return $ret; } }
<?php class WikiLeaksBridge extends BridgeAbstract { const NAME = 'WikiLeaks'; const URI = 'https://wikileaks.org'; const DESCRIPTION = 'Returns the latest news or articles from WikiLeaks'; const MAINTAINER = 'logmanoriginal'; const PARAMETERS = array( array( 'category' => array( 'name' => 'Category', 'type' => 'list', 'required' => true, 'title' => 'Select your category', 'values' => array( 'News' => '-News-', 'Leaks' => array( 'All' => '-Leaks-', 'Intelligence' => '+-Intelligence-+', 'Global Economy' => '+-Global-Economy-+', 'International Politics' => '+-<API key>-+', 'Corporations' => '+-Corporations-+', 'Government' => '+-Government-+', 'War & Military' => '+-War-Military-+' ) ), 'defaultValue' => 'news' ), 'teaser' => array( 'name' => 'Show teaser', 'type' => 'checkbox', 'required' => false, 'title' => 'If checked feeds will display the teaser', 'defaultValue' => true ) ) ); public function collectData(){ $html = getSimpleHTMLDOM($this->getURI()); // News are presented differently switch($this->getInput('category')) { case '-News-': $this->loadNewsItems($html); break; default: $this->loadLeakItems($html); } } public function getURI(){ if(!is_null($this->getInput('category'))) { return static::URI . '/' . $this->getInput('category') . '.html'; } return parent::getURI(); } public function getName(){ if(!is_null($this->getInput('category'))) { $category = array_search( $this->getInput('category'), static::PARAMETERS[0]['category']['values'] ); if($category === false) { $category = array_search( $this->getInput('category'), static::PARAMETERS[0]['category']['values']['Leaks'] ); } return $category . ' - ' . static::NAME; } return parent::getName(); } private function loadNewsItems($html){ $articles = $html->find('div.news-articles ul li'); if(is_null($articles) || count($articles) === 0) { return; } foreach($articles as $article) { $item = array(); $item['title'] = $article->find('h3', 0)->plaintext; $item['uri'] = static::URI . $article->find('h3 a', 0)->href; $item['content'] = $article->find('div.introduction', 0)->plaintext; $item['timestamp'] = strtotime($article->find('div.timestamp', 0)->plaintext); $this->items[] = $item; } } private function loadLeakItems($html){ $articles = $html->find('li.tile'); if(is_null($articles) || count($articles) === 0) { return; } foreach($articles as $article) { $item = array(); $item['title'] = $article->find('h2', 0)->plaintext; $item['uri'] = static::URI . $article->find('a', 0)->href; $teaser = static::URI . '/' . $article->find('div.teaser img', 0)->src; if($this->getInput('teaser')) { $item['content'] = '<img src="' . $teaser . '" /><p>' . $article->find('div.intro', 0)->plaintext . '</p>'; } else { $item['content'] = $article->find('div.intro', 0)->plaintext; } $item['timestamp'] = strtotime($article->find('div.timestamp', 0)->plaintext); $item['enclosures'] = array($teaser); $this->items[] = $item; } } }
#include <linux/kernel.h> #include <linux/module.h> #include <linux/spi/spi.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/completion.h> #include <linux/sched.h> #include <linux/gpio.h> #include <linux/rmi.h> #define COMMS_DEBUG 0 #define FF_DEBUG 0 #define <API key> 0xa0fd #define SPI_V2_UNIFIED_READ 0xc0 #define SPI_V2_WRITE 0x40 #define <API key> 0xc8 #define <API key> 0xca #define <API key> 65 #define <API key> 65 #define <API key> 0 #define RMI_V1_READ_FLAG 0x80 #define <API key> 0x00FF #define RMI_SPI_PAGE(addr) (((addr) >> 8) & 0x80) #define <API key> 13 static char *spi_v1_proto_name = "spi"; static char *spi_v2_proto_name = "spiv2"; struct rmi_spi_data { struct mutex page_mutex; int page; int (*set_page) (struct rmi_phys_device *phys, u8 page); bool split_read_pending; int enabled; int irq; int irq_flags; struct rmi_phys_device *phys; struct completion irq_comp; /* Following are used when polling. */ struct hrtimer poll_timer; struct work_struct poll_work; int poll_interval; }; static irqreturn_t rmi_spi_hard_irq(int irq, void *p) { struct rmi_phys_device *phys = p; struct rmi_spi_data *data = phys->data; struct <API key> *pdata = phys->dev->platform_data; if (data->split_read_pending && gpio_get_value(pdata->attn_gpio) == pdata->attn_polarity) { phys->info.attn_count++; complete(&data->irq_comp); return IRQ_HANDLED; } return IRQ_WAKE_THREAD; } static irqreturn_t rmi_spi_irq_thread(int irq, void *p) { struct rmi_phys_device *phys = p; struct rmi_device *rmi_dev = phys->rmi_dev; struct rmi_driver *driver = rmi_dev->driver; struct <API key> *pdata = phys->dev->platform_data; if (gpio_get_value(pdata->attn_gpio) == pdata->attn_polarity) { phys->info.attn_count++; if (driver && driver->irq_handler) driver->irq_handler(rmi_dev, irq); } return IRQ_HANDLED; } static void spi_poll_work(struct work_struct *work) { struct rmi_spi_data *data = container_of(work, struct rmi_spi_data, poll_work); struct rmi_device *rmi_dev = data->phys->rmi_dev; struct rmi_driver *driver = rmi_dev->driver; if (driver && driver->irq_handler) driver->irq_handler(rmi_dev, 0); } /* This is the timer function for polling - it simply has to schedule work * and restart the timer. */ static enum hrtimer_restart spi_poll_timer(struct hrtimer *timer) { struct rmi_spi_data *data = container_of(timer, struct rmi_spi_data, poll_timer); if (!work_pending(&data->poll_work)) schedule_work(&data->poll_work); hrtimer_start(&data->poll_timer, ktime_set(0, data->poll_interval), HRTIMER_MODE_REL); return HRTIMER_NORESTART; } static int rmi_spi_xfer(struct rmi_phys_device *phys, const u8 *txbuf, unsigned n_tx, u8 *rxbuf, unsigned n_rx) { struct spi_device *client = to_spi_device(phys->dev); struct rmi_spi_data *v2_data = phys->data; struct <API key> *pdata = phys->dev->platform_data; int status; struct spi_message message; struct spi_transfer *xfers; int total_bytes = n_tx + n_rx; u8 local_buf[total_bytes]; int xfer_count = 0; int xfer_index = 0; int block_delay = n_rx > 0 ? pdata->spi_data.block_delay_us : 0; int byte_delay = n_rx > 1 ? pdata->spi_data.read_delay_us : 0; int write_delay = n_tx > 1 ? pdata->spi_data.write_delay_us : 0; #if FF_DEBUG bool bad_data = true; #endif #if COMMS_DEBUG || FF_DEBUG int i; #endif if (v2_data->split_read_pending) { block_delay = n_rx > 0 ? pdata->spi_data.<API key> : 0; byte_delay = n_tx > 1 ? pdata->spi_data.<API key> : 0; write_delay = 0; } if (n_tx) { phys->info.tx_count++; phys->info.tx_bytes += n_tx; if (write_delay) xfer_count += n_tx; else xfer_count += 1; } if (n_rx) { phys->info.rx_count++; phys->info.rx_bytes += n_rx; if (byte_delay) xfer_count += n_rx; else xfer_count += 1; } xfers = kcalloc(xfer_count, sizeof(struct spi_transfer), GFP_KERNEL); if (!xfers) return -ENOMEM; spi_message_init(&message); if (n_tx) { if (write_delay) { for (xfer_index = 0; xfer_index < n_tx; xfer_index++) { memset(&xfers[xfer_index], 0, sizeof(struct spi_transfer)); xfers[xfer_index].len = 1; xfers[xfer_index].delay_usecs = write_delay; xfers[xfer_index].tx_buf = txbuf + xfer_index; <API key>(&xfers[xfer_index], &message); } } else { memset(&xfers[0], 0, sizeof(struct spi_transfer)); xfers[0].len = n_tx; <API key>(&xfers[0], &message); memcpy(local_buf, txbuf, n_tx); xfers[0].tx_buf = local_buf; xfer_index++; } if (block_delay) xfers[xfer_index-1].delay_usecs = block_delay; } if (n_rx) { if (byte_delay) { int buffer_offset = n_tx; for (; xfer_index < xfer_count; xfer_index++) { memset(&xfers[xfer_index], 0, sizeof(struct spi_transfer)); xfers[xfer_index].len = 1; xfers[xfer_index].delay_usecs = byte_delay; xfers[xfer_index].rx_buf = local_buf + buffer_offset; buffer_offset++; <API key>(&xfers[xfer_index], &message); } } else { memset(&xfers[xfer_index], 0, sizeof(struct spi_transfer)); xfers[xfer_index].len = n_rx; xfers[xfer_index].rx_buf = local_buf + n_tx; <API key>(&xfers[xfer_index], &message); xfer_index++; } } #if COMMS_DEBUG if (n_tx) { dev_dbg(&client->dev, "SPI sends %d bytes: ", n_tx); for (i = 0; i < n_tx; i++) pr_info("%02X ", txbuf[i]); pr_info("\n"); } #endif /* do the i/o */ if (pdata->spi_data.cs_assert) { status = pdata->spi_data.cs_assert( pdata->spi_data.cs_assert_data, true); if (status) { dev_err(phys->dev, "Failed to assert CS, code %d.\n", status); /* nonzero means error */ status = -1; goto error_exit; } else status = 0; } if (pdata->spi_data.pre_delay_us) udelay(pdata->spi_data.pre_delay_us); status = spi_sync(client, &message); if (pdata->spi_data.post_delay_us) udelay(pdata->spi_data.post_delay_us); if (pdata->spi_data.cs_assert) { status = pdata->spi_data.cs_assert( pdata->spi_data.cs_assert_data, false); if (status) { dev_err(phys->dev, "Failed to deassert CS. code %d.\n", status); /* nonzero means error */ status = -1; goto error_exit; } else status = 0; } if (status == 0) { memcpy(rxbuf, local_buf + n_tx, n_rx); status = message.status; } else { phys->info.tx_errs++; phys->info.rx_errs++; dev_err(phys->dev, "spi_sync failed with error code %d.", status); } #if COMMS_DEBUG if (n_rx) { dev_dbg(&client->dev, "SPI received %d bytes: ", n_rx); for (i = 0; i < n_rx; i++) pr_info("%02X ", rxbuf[i]); pr_info("\n"); } #endif #if FF_DEBUG if (n_rx) { for (i = 0; i < n_rx; i++) { if (rxbuf[i] != 0xFF) { bad_data = false; break; } } if (bad_data) { phys->info.rx_errs++; dev_err(phys->dev, "BAD READ %lu out of %lu.\n", phys->info.rx_errs, phys->info.rx_count); } } #endif error_exit: kfree(xfers); return status; } static int <API key>(struct rmi_phys_device *phys, u16 addr, u8 *buf, int len) { struct rmi_spi_data *data = phys->data; u8 txbuf[len + 4]; int error; txbuf[0] = SPI_V2_WRITE; txbuf[1] = (addr >> 8) & 0x00FF; txbuf[2] = addr & 0x00FF; txbuf[3] = len; memcpy(&txbuf[4], buf, len); mutex_lock(&data->page_mutex); if (RMI_SPI_PAGE(addr) != data->page) { error = data->set_page(phys, RMI_SPI_PAGE(addr)); if (error < 0) goto exit; } error = rmi_spi_xfer(phys, buf, len + 4, NULL, 0); if (error < 0) goto exit; error = len; exit: mutex_unlock(&data->page_mutex); return error; } static int rmi_spi_v2_write(struct rmi_phys_device *phys, u16 addr, u8 data) { int error = <API key>(phys, addr, &data, 1); return (error == 1) ? 0 : error; } static int <API key>(struct rmi_phys_device *phys, u16 addr, u8 *buf, int len) { struct rmi_spi_data *data = phys->data; unsigned char txbuf[len + 2]; int error; txbuf[0] = addr >> 8; txbuf[1] = addr; memcpy(txbuf+2, buf, len); mutex_lock(&data->page_mutex); if (RMI_SPI_PAGE(addr) != data->page) { error = data->set_page(phys, RMI_SPI_PAGE(addr)); if (error < 0) goto exit; } error = rmi_spi_xfer(phys, txbuf, len + 2, NULL, 0); if (error < 0) goto exit; error = len; exit: mutex_unlock(&data->page_mutex); return error; } static int rmi_spi_v1_write(struct rmi_phys_device *phys, u16 addr, u8 data) { int error = <API key>(phys, addr, &data, 1); return (error == 1) ? 0 : error; } static int <API key>(struct rmi_phys_device *phys, u16 addr, u8 *buf, int len) { struct rmi_spi_data *data = phys->data; u8 txbuf[4]; u8 rxbuf[len + 1]; /* one extra byte for read length */ int error; txbuf[0] = <API key>; txbuf[1] = (addr >> 8) & 0x00FF; txbuf[2] = addr & 0x00ff; txbuf[3] = len; mutex_lock(&data->page_mutex); if (RMI_SPI_PAGE(addr) != data->page) { error = data->set_page(phys, RMI_SPI_PAGE(addr)); if (error < 0) goto exit; } data->split_read_pending = true; error = rmi_spi_xfer(phys, txbuf, 4, NULL, 0); if (error < 0) { data->split_read_pending = false; goto exit; } wait_for_completion(&data->irq_comp); txbuf[0] = <API key>; txbuf[1] = 0; error = rmi_spi_xfer(phys, txbuf, 2, rxbuf, len + 1); data->split_read_pending = false; if (error < 0) goto exit; /* first byte is length */ if (rxbuf[0] != len) { error = -EIO; goto exit; } memcpy(buf, rxbuf + 1, len); error = len; exit: mutex_unlock(&data->page_mutex); return error; } static int <API key>(struct rmi_phys_device *phys, u16 addr, u8 *buf, int len) { struct rmi_spi_data *data = phys->data; u8 txbuf[4]; int error; txbuf[0] = SPI_V2_UNIFIED_READ; txbuf[1] = (addr >> 8) & 0x00FF; txbuf[2] = addr & 0x00ff; txbuf[3] = len; mutex_lock(&data->page_mutex); if (RMI_SPI_PAGE(addr) != data->page) { error = data->set_page(phys, RMI_SPI_PAGE(addr)); if (error < 0) goto exit; } error = rmi_spi_xfer(phys, txbuf, 4, buf, len); if (error < 0) goto exit; error = len; exit: mutex_unlock(&data->page_mutex); return error; } static int rmi_spi_v2_read(struct rmi_phys_device *phys, u16 addr, u8 *buf) { int error = <API key>(phys, addr, buf, 1); return (error == 1) ? 0 : error; } static int <API key>(struct rmi_phys_device *phys, u16 addr, u8 *buf, int len) { struct rmi_spi_data *data = phys->data; u8 txbuf[2]; int error; txbuf[0] = (addr >> 8) | RMI_V1_READ_FLAG; txbuf[1] = addr; mutex_lock(&data->page_mutex); if (RMI_SPI_PAGE(addr) != data->page) { error = data->set_page(phys, RMI_SPI_PAGE(addr)); if (error < 0) goto exit; } error = rmi_spi_xfer(phys, txbuf, 2, buf, len); if (error < 0) goto exit; error = len; exit: mutex_unlock(&data->page_mutex); return error; } static int rmi_spi_v1_read(struct rmi_phys_device *phys, u16 addr, u8 *buf) { int error = <API key>(phys, addr, buf, 1); return (error == 1) ? 0 : error; } #define <API key> 1 static int rmi_spi_v1_set_page(struct rmi_phys_device *phys, u8 page) { struct rmi_spi_data *data = phys->data; u8 txbuf[] = {<API key> >> 8, <API key> & 0xFF, page}; int error; error = rmi_spi_xfer(phys, txbuf, sizeof(txbuf), NULL, 0); if (error < 0) { dev_err(phys->dev, "Failed to set page select, code: %d.\n", error); return error; } data->page = page; return <API key>; } static int rmi_spi_v2_set_page(struct rmi_phys_device *phys, u8 page) { struct rmi_spi_data *data = phys->data; u8 txbuf[] = {SPI_V2_WRITE, <API key> >> 8, <API key> & 0xFF, <API key>, page}; int error; error = rmi_spi_xfer(phys, txbuf, sizeof(txbuf), NULL, 0); if (error < 0) { dev_err(phys->dev, "Failed to set page select, code: %d.\n", error); return error; } data->page = page; return <API key>; } static int acquire_attn_irq(struct rmi_spi_data *data) { int retval; struct rmi_phys_device *rmi_phys = data->phys; retval = <API key>(data->irq, rmi_spi_hard_irq, rmi_spi_irq_thread, data->irq_flags, dev_name(rmi_phys->dev), rmi_phys); if (retval < 0) { dev_err(&(rmi_phys->rmi_dev->dev), "<API key> " "failed, code: %d.\n", retval); } return retval; } static int setup_attn(struct rmi_spi_data *data) { int retval; struct rmi_phys_device *rmi_phys = data->phys; struct <API key> *pdata = rmi_phys->dev->platform_data; retval = acquire_attn_irq(data); if (retval < 0) return retval; #if defined(CONFIG_RMI4_DEV) retval = gpio_export(pdata->attn_gpio, false); if (retval) { dev_warn(&(rmi_phys->rmi_dev->dev), "WARNING: Failed to export ATTN gpio!\n"); retval = 0; } else { retval = gpio_export_link(&(rmi_phys->rmi_dev->dev), "attn", pdata->attn_gpio); if (retval) { dev_warn(&(rmi_phys->rmi_dev->dev), "WARNING: " "Failed to symlink ATTN gpio!\n"); retval = 0; } else { dev_info(&(rmi_phys->rmi_dev->dev), "%s: Exported GPIO %d.", __func__, pdata->attn_gpio); } } #endif /* CONFIG_RMI4_DEV */ return retval; } static int setup_polling(struct rmi_spi_data *data) { INIT_WORK(&data->poll_work, spi_poll_work); hrtimer_init(&data->poll_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); data->poll_timer.function = spi_poll_timer; hrtimer_start(&data->poll_timer, ktime_set(1, 0), HRTIMER_MODE_REL); return 0; } static int enable_device(struct rmi_phys_device *phys) { int retval = 0; struct rmi_spi_data *data = phys->data; if (data->enabled) { dev_dbg(phys->dev, "Physical device already enabled.\n"); return 0; } retval = acquire_attn_irq(data); if (retval) goto error_exit; data->enabled = true; dev_dbg(phys->dev, "Physical device enabled.\n"); return 0; error_exit: dev_err(phys->dev, "Failed to enable physical device. Code=%d.\n", retval); return retval; } static void disable_device(struct rmi_phys_device *phys) { struct rmi_spi_data *data = phys->data; if (!data->enabled) { dev_warn(phys->dev, "Physical device already disabled.\n"); return; } disable_irq(data->irq); free_irq(data->irq, data->phys); dev_dbg(phys->dev, "Physical device disabled.\n"); data->enabled = false; } #define DUMMY_READ_SLEEP_US 10 static int <API key>(struct rmi_phys_device *rmi_phys) { u8 buf[6]; int error; int i; /* Some SPI subsystems return 0 for the very first read you do. So * we use this dummy read to get that out of the way. */ error = <API key>(rmi_phys, <API key>, buf, sizeof(buf)); if (error < 0) { dev_err(rmi_phys->dev, "dummy read failed with %d.\n", error); return error; } udelay(DUMMY_READ_SLEEP_US); /* Force page select to 0. */ error = rmi_spi_v1_set_page(rmi_phys, 0x00); if (error < 0) return error; /* Now read the first PDT entry. We know where this is, and if the * RMI4 device is out there, these 6 bytes will be something other * than all 0x00 or 0xFF. We need to check for 0x00 and 0xFF, * because many (maybe all) SPI implementations will return all 0x00 * or all 0xFF on read if the device is not connected. */ error = <API key>(rmi_phys, <API key>, buf, sizeof(buf)); if (error < 0) { dev_err(rmi_phys->dev, "probe read failed with %d.\n", error); return error; } for (i = 0; i < sizeof(buf); i++) { if (buf[i] != 0x00 && buf[i] != 0xFF) return error; } dev_err(rmi_phys->dev, "probe read returned invalid block.\n"); return -ENODEV; } static int __devinit rmi_spi_probe(struct spi_device *spi) { struct rmi_phys_device *rmi_phys; struct rmi_spi_data *data; struct <API key> *pdata = spi->dev.platform_data; u8 buf[2]; int retval; if (!pdata) { dev_err(&spi->dev, "no platform data\n"); return -EINVAL; } if (spi->master->flags & <API key>) return -EINVAL; spi->bits_per_word = 8; spi->mode = SPI_MODE_3; retval = spi_setup(spi); if (retval < 0) { dev_err(&spi->dev, "spi_setup failed!\n"); return retval; } rmi_phys = kzalloc(sizeof(struct rmi_phys_device), GFP_KERNEL); if (!rmi_phys) return -ENOMEM; data = kzalloc(sizeof(struct rmi_spi_data), GFP_KERNEL); if (!data) { retval = -ENOMEM; goto err_phys; } data->enabled = true; /* We plan to come up enabled. */ data->irq = gpio_to_irq(pdata->attn_gpio); data->irq_flags = (pdata->attn_polarity == <API key>) ? IRQF_TRIGGER_RISING : <API key>; data->phys = rmi_phys; rmi_phys->data = data; rmi_phys->dev = &spi->dev; rmi_phys->write = rmi_spi_v1_write; rmi_phys->write_block = <API key>; rmi_phys->read = rmi_spi_v1_read; rmi_phys->read_block = <API key>; rmi_phys->enable_device = enable_device; rmi_phys->disable_device = disable_device; data->set_page = rmi_spi_v1_set_page; rmi_phys->info.proto = spi_v1_proto_name; mutex_init(&data->page_mutex); dev_set_drvdata(&spi->dev, rmi_phys); pdata->spi_data.block_delay_us = pdata->spi_data.block_delay_us ? pdata->spi_data.block_delay_us : <API key>; pdata->spi_data.read_delay_us = pdata->spi_data.read_delay_us ? pdata->spi_data.read_delay_us : <API key>; pdata->spi_data.write_delay_us = pdata->spi_data.write_delay_us ? pdata->spi_data.write_delay_us : <API key>; pdata->spi_data.<API key> = pdata->spi_data.<API key> ? pdata->spi_data.<API key> : <API key>; pdata->spi_data.<API key> = pdata->spi_data.<API key> ? pdata->spi_data.<API key> : <API key>; if (pdata->gpio_config) { retval = pdata->gpio_config(pdata->gpio_data, true); if (retval < 0) { dev_err(&spi->dev, "Failed to setup GPIOs, code: %d.\n", retval); goto err_data; } } retval = <API key>(rmi_phys); if (retval < 0) goto err_data; /* check if this is an SPI v2 device */ retval = <API key>(rmi_phys, <API key>, buf, 2); if (retval < 0) { dev_err(&spi->dev, "failed to get SPI version number!\n"); goto err_data; } dev_dbg(&spi->dev, "SPI version is %d", buf[0]); if (buf[0] == 1) { /* SPIv2 */ rmi_phys->write = rmi_spi_v2_write; rmi_phys->write_block = <API key>; rmi_phys->read = rmi_spi_v2_read; data->set_page = rmi_spi_v2_set_page; rmi_phys->info.proto = spi_v2_proto_name; if (pdata->attn_gpio > 0) { init_completion(&data->irq_comp); rmi_phys->read_block = <API key>; } else { dev_warn(&spi->dev, "WARNING: SPI V2 detected, but no " "attention GPIO was specified. This is unlikely" " to work well.\n"); rmi_phys->read_block = <API key>; } } else if (buf[0] != 0) { dev_err(&spi->dev, "Unrecognized SPI version %d.\n", buf[0]); retval = -ENODEV; goto err_data; } retval = <API key>(rmi_phys); if (retval) { dev_err(&spi->dev, "failed to register physical driver\n"); goto err_data; } if (pdata->attn_gpio > 0) { retval = setup_attn(data); if (retval < 0) goto err_unregister; } else { retval = setup_polling(data); if (retval < 0) goto err_unregister; } dev_info(&spi->dev, "registered RMI SPI driver\n"); return 0; err_unregister: <API key>(rmi_phys); err_data: kfree(data); err_phys: kfree(rmi_phys); return retval; } static int __devexit rmi_spi_remove(struct spi_device *spi) { struct rmi_phys_device *phys = dev_get_drvdata(&spi->dev); struct <API key> *pd = spi->dev.platform_data; <API key>(phys); kfree(phys->data); kfree(phys); if (pd->gpio_config) pd->gpio_config(&spi->dev, false); return 0; } static const struct spi_device_id rmi_id[] = { { "rmi", 0 }, { "rmi_spi", 0 }, { } }; MODULE_DEVICE_TABLE(spi, rmi_id); static struct spi_driver rmi_spi_driver = { .driver = { .owner = THIS_MODULE, .name = "rmi_spi", }, .id_table = rmi_id, .probe = rmi_spi_probe, .remove = __devexit_p(rmi_spi_remove), }; static int __init rmi_spi_init(void) { return spi_register_driver(&rmi_spi_driver); } static void __exit rmi_spi_exit(void) { <API key>(&rmi_spi_driver); } MODULE_AUTHOR("Christopher Heiny <cheiny@synaptics.com>"); MODULE_DESCRIPTION("RMI SPI driver"); MODULE_LICENSE("GPL"); module_init(rmi_spi_init); module_exit(rmi_spi_exit);
SUBROUTINE sla_DTPS2C (XI, ETA, RA, DEC, RAZ1, DECZ1, : RAZ2, DECZ2, N) *+ * - - - - - - - * D T P S 2 C * - - - - - - - * * From the tangent plane coordinates of a star of known RA,Dec, * determine the RA,Dec of the tangent point. * * (double precision) * * Given: * XI,ETA d tangent plane rectangular coordinates * RA,DEC d spherical coordinates * * Returned: * RAZ1,DECZ1 d spherical coordinates of tangent point, solution 1 * RAZ2,DECZ2 d spherical coordinates of tangent point, solution 2 * N i number of solutions: * 0 = no solutions returned (note 2) * 1 = only the first solution is useful (note 3) * 2 = both solutions are useful (note 3) * * Notes: * * 1 The RAZ1 and RAZ2 values are returned in the range 0-2pi. * * 2 Cases where there is no solution can only arise near the poles. * For example, it is clearly impossible for a star at the pole * itself to have a non-zero XI value, and hence it is * meaningless to ask where the tangent point would have to be * to bring about this combination of XI and DEC. * * 3 Also near the poles, cases can arise where there are two useful * solutions. The argument N indicates whether the second of the * two solutions returned is useful. N=1 indicates only one useful * solution, the usual case; under these circumstances, the second * solution corresponds to the "over-the-pole" case, and this is * reflected in the values of RAZ2 and DECZ2 which are returned. * * 4 The DECZ1 and DECZ2 values are returned in the range +/-pi, but * in the usual, non-pole-crossing, case, the range is +/-pi/2. * * 5 This routine is the spherical equivalent of the routine sla_DTPV2C. * * Called: sla_DRANRM * * P.T.Wallace Starlink 5 June 1995 * * Copyright (C) 1995 Rutherford Appleton Laboratory * * License: * 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 (see SLA_CONDITIONS); if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * *- IMPLICIT NONE DOUBLE PRECISION XI,ETA,RA,DEC,RAZ1,DECZ1,RAZ2,DECZ2 INTEGER N DOUBLE PRECISION X2,Y2,SD,CD,SDF,R2,R,S,C DOUBLE PRECISION sla_DRANRM X2=XI*XI Y2=ETA*ETA SD=SIN(DEC) CD=COS(DEC) SDF=SD*SQRT(1D0+X2+Y2) R2=CD*CD*(1D0+Y2)-SD*SD*X2 IF (R2.GE.0D0) THEN R=SQRT(R2) S=SDF-ETA*R C=SDF*ETA+R IF (XI.EQ.0D0.AND.R.EQ.0D0) R=1D0 RAZ1=sla_DRANRM(RA-ATAN2(XI,R)) DECZ1=ATAN2(S,C) R=-R S=SDF-ETA*R C=SDF*ETA+R RAZ2=sla_DRANRM(RA-ATAN2(XI,R)) DECZ2=ATAN2(S,C) IF (ABS(SDF).LT.1D0) THEN N=1 ELSE N=2 END IF ELSE N=0 END IF END
#include <KFL/KFL.hpp> #include <KFL/ResIdentifier.hpp> #ifdef <API key> #include <windows.h> #else #include <dlfcn.h> #endif #include <KFL/DllLoader.hpp> namespace KlayGE { DllLoader::DllLoader() : dll_handle_(nullptr) { } DllLoader::~DllLoader() { this->Free(); } bool DllLoader::Load(std::string const & dll_name) { #ifdef <API key> #ifdef <API key> dll_handle_ = static_cast<void*>(::LoadLibraryExA(dll_name.c_str(), nullptr, 0)); #else std::wstring wname; Convert(wname, dll_name); dll_handle_ = static_cast<void*>(::LoadPackagedLibrary(wname.c_str(), 0)); #endif #else dll_handle_ = ::dlopen(dll_name.c_str(), RTLD_LAZY); #endif return (dll_handle_ != nullptr); } void DllLoader::Free() { if (dll_handle_) { #ifdef <API key> ::FreeLibrary(static_cast<HMODULE>(dll_handle_)); #else ::dlclose(dll_handle_); #endif } } void* DllLoader::GetProcAddress(std::string const & proc_name) { #ifdef <API key> return reinterpret_cast<void*>(::GetProcAddress(static_cast<HMODULE>(dll_handle_), proc_name.c_str())); #else return ::dlsym(dll_handle_, proc_name.c_str()); #endif } }
ccflags-y += -I$(srctree)/drivers/misc/mediatek/thermal/fakeHeader/ ccflags-y += -I$(srctree)/drivers/misc/mediatek/base/power/include/ ccflags-y += -I$(srctree)/drivers/misc/mediatek/base/power/spm_v1 ccflags-y += -I$(srctree)/drivers/misc/mediatek/base/power/cpuidle_v1/ ifeq ($(CONFIG_ARCH_MT6580),y) ccflags-y += -I$(srctree)/drivers/misc/mediatek/video/$(MTK_PLATFORM)/videox/ ccflags-y += -I$(srctree)/drivers/misc/mediatek/video/$(MTK_PLATFORM)/dispsys/ ccflags-y += -I$(srctree)/drivers/misc/mediatek/video/include/ ccflags-y += -I$(srctree)/drivers/misc/mediatek/cmdq/v2/ ccflags-y += -I$(srctree)/drivers/misc/mediatek/cmdq/v2/$(MTK_PLATFORM)/ ccflags-y += -I$(srctree)/drivers/misc/mediatek/lcm/inc/ endif obj-y += mt_spm_mtcmos.o obj-y += mt_clkmgr_common.o obj-y += mt_clkmgr.o obj-y += mt_golden_setting.o obj-y += mt_clkbuf_ctl.o obj-y += mt_pm_init.o obj-y += mt_sleep.o obj-y += mt_cpufreq.o obj-y += mt_gpufreq.o obj-y += mt_ptp.o obj-y += mt_dcm.o obj-y += mt-smp.o obj-y += hotplug.o obj-y += mt-headsmp.o obj-y += mt_hotplug.o obj-y += <API key>.o obj-y += <API key>.o obj-y += <API key>.o obj-y += <API key>.o obj-y += <API key>.o obj-y += <API key>.o
#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include "typedefs.h" #include "vsite.h" #include "macros.h" #include "smalloc.h" #include "nrnb.h" #include "vec.h" #include "mvdata.h" #include "network.h" #include "mshift.h" #include "pbc.h" #include "domdec.h" #include "partdec.h" #include "mtop_util.h" /* Routines to send/recieve coordinates and force * of constructing atoms. */ static void move_construct_x(t_comm_vsites *vsitecomm, rvec x[], t_commrec *cr) { rvec *sendbuf; rvec *recvbuf; int i,ia; sendbuf = vsitecomm->send_buf; recvbuf = vsitecomm->recv_buf; /* Prepare pulse left by copying to send buffer */ for(i=0;i<vsitecomm-><API key>;i++) { ia = vsitecomm-><API key>[i]; copy_rvec(x[ia],sendbuf[i]); } /* Pulse coordinates left */ gmx_tx_rx_real(cr,GMX_LEFT,(real *)sendbuf,3*vsitecomm-><API key>,GMX_RIGHT,(real *)recvbuf,3*vsitecomm-><API key>); /* Copy from receive buffer to coordinate array */ for(i=0;i<vsitecomm-><API key>;i++) { ia = vsitecomm-><API key>[i]; copy_rvec(recvbuf[i],x[ia]); } /* Prepare pulse right by copying to send buffer */ for(i=0;i<vsitecomm-><API key>;i++) { ia = vsitecomm-><API key>[i]; copy_rvec(x[ia],sendbuf[i]); } /* Pulse coordinates right */ gmx_tx_rx_real(cr,GMX_RIGHT,(real *)sendbuf,3*vsitecomm-><API key>,GMX_LEFT,(real *)recvbuf,3*vsitecomm-><API key>); /* Copy from receive buffer to coordinate array */ for(i=0;i<vsitecomm-><API key>;i++) { ia = vsitecomm-><API key>[i]; copy_rvec(recvbuf[i],x[ia]); } } static void move_construct_f(t_comm_vsites *vsitecomm, rvec f[], t_commrec *cr) { rvec *sendbuf; rvec *recvbuf; int i,ia; sendbuf = vsitecomm->send_buf; recvbuf = vsitecomm->recv_buf; /* Prepare pulse right by copying to send buffer */ for(i=0;i<vsitecomm-><API key>;i++) { ia = vsitecomm-><API key>[i]; copy_rvec(f[ia],sendbuf[i]); clear_rvec(f[ia]); /* Zero it here after moving, just to simplify debug book-keeping... */ } /* Pulse forces right */ gmx_tx_rx_real(cr,GMX_RIGHT,(real *)sendbuf,3*vsitecomm-><API key>,GMX_LEFT,(real *)recvbuf,3*vsitecomm-><API key>); /* Copy from receive buffer to coordinate array */ for(i=0;i<vsitecomm-><API key>;i++) { ia = vsitecomm-><API key>[i]; rvec_inc(f[ia],recvbuf[i]); } /* Prepare pulse left by copying to send buffer */ for(i=0;i<vsitecomm-><API key>;i++) { ia = vsitecomm-><API key>[i]; copy_rvec(f[ia],sendbuf[i]); clear_rvec(f[ia]); /* Zero it here after moving, just to simplify debug book-keeping... */ } /* Pulse coordinates left */ gmx_tx_rx_real(cr,GMX_LEFT,(real *)sendbuf,3*vsitecomm-><API key>,GMX_RIGHT,(real *)recvbuf,3*vsitecomm-><API key>); /* Copy from receive buffer to coordinate array */ for(i=0;i<vsitecomm-><API key>;i++) { ia = vsitecomm-><API key>[i]; rvec_inc(f[ia],recvbuf[i]); } /* All forces are now on the home processors */ } static void <API key>(t_comm_vsites *vsitecomm, rvec f[]) { int i,ia; for(i=0;i<vsitecomm-><API key>;i++) { ia = vsitecomm-><API key>[i]; clear_rvec(f[ia]); } for(i=0;i<vsitecomm-><API key>;i++) { ia = vsitecomm-><API key>[i]; clear_rvec(f[ia]); } } static int pbc_rvec_sub(const t_pbc *pbc,const rvec xi,const rvec xj,rvec dx) { if (pbc) { return pbc_dx_aiuc(pbc,xi,xj,dx); } else { rvec_sub(xi,xj,dx); return CENTRAL; } } /* Vsite construction routines */ static void constr_vsite2(rvec xi,rvec xj,rvec x,real a,t_pbc *pbc) { real b; rvec dx; b=1.0-a; /* 1 flop */ if (pbc) { pbc_dx_aiuc(pbc,xj,xi,dx); x[XX] = xi[XX] + a*dx[XX]; x[YY] = xi[YY] + a*dx[YY]; x[ZZ] = xi[ZZ] + a*dx[ZZ]; } else { x[XX] = b*xi[XX] + a*xj[XX]; x[YY] = b*xi[YY] + a*xj[YY]; x[ZZ] = b*xi[ZZ] + a*xj[ZZ]; /* 9 Flops */ } /* TOTAL: 10 flops */ } static void constr_vsite3(rvec xi,rvec xj,rvec xk,rvec x,real a,real b, t_pbc *pbc) { real c; rvec dxj,dxk; c=1.0-a-b; /* 2 flops */ if (pbc) { pbc_dx_aiuc(pbc,xj,xi,dxj); pbc_dx_aiuc(pbc,xk,xi,dxk); x[XX] = xi[XX] + a*dxj[XX] + b*dxk[XX]; x[YY] = xi[YY] + a*dxj[YY] + b*dxk[YY]; x[ZZ] = xi[ZZ] + a*dxj[ZZ] + b*dxk[ZZ]; } else { x[XX] = c*xi[XX] + a*xj[XX] + b*xk[XX]; x[YY] = c*xi[YY] + a*xj[YY] + b*xk[YY]; x[ZZ] = c*xi[ZZ] + a*xj[ZZ] + b*xk[ZZ]; /* 15 Flops */ } /* TOTAL: 17 flops */ } static void constr_vsite3FD(rvec xi,rvec xj,rvec xk,rvec x,real a,real b, t_pbc *pbc) { rvec xij,xjk,temp; real c; pbc_rvec_sub(pbc,xj,xi,xij); pbc_rvec_sub(pbc,xk,xj,xjk); /* 6 flops */ /* temp goes from i to a point on the line jk */ temp[XX] = xij[XX] + a*xjk[XX]; temp[YY] = xij[YY] + a*xjk[YY]; temp[ZZ] = xij[ZZ] + a*xjk[ZZ]; /* 6 flops */ c=b*gmx_invsqrt(iprod(temp,temp)); /* 6 + 10 flops */ x[XX] = xi[XX] + c*temp[XX]; x[YY] = xi[YY] + c*temp[YY]; x[ZZ] = xi[ZZ] + c*temp[ZZ]; /* 6 Flops */ /* TOTAL: 34 flops */ } static void constr_vsite3FAD(rvec xi,rvec xj,rvec xk,rvec x,real a,real b, t_pbc *pbc) { rvec xij,xjk,xp; real a1,b1,c1,invdij; pbc_rvec_sub(pbc,xj,xi,xij); pbc_rvec_sub(pbc,xk,xj,xjk); /* 6 flops */ invdij = gmx_invsqrt(iprod(xij,xij)); c1 = invdij * invdij * iprod(xij,xjk); xp[XX] = xjk[XX] - c1*xij[XX]; xp[YY] = xjk[YY] - c1*xij[YY]; xp[ZZ] = xjk[ZZ] - c1*xij[ZZ]; a1 = a*invdij; b1 = b*gmx_invsqrt(iprod(xp,xp)); x[XX] = xi[XX] + a1*xij[XX] + b1*xp[XX]; x[YY] = xi[YY] + a1*xij[YY] + b1*xp[YY]; x[ZZ] = xi[ZZ] + a1*xij[ZZ] + b1*xp[ZZ]; /* 12 Flops */ /* TOTAL: 63 flops */ } static void constr_vsite3OUT(rvec xi,rvec xj,rvec xk,rvec x, real a,real b,real c,t_pbc *pbc) { rvec xij,xik,temp; pbc_rvec_sub(pbc,xj,xi,xij); pbc_rvec_sub(pbc,xk,xi,xik); cprod(xij,xik,temp); /* 15 Flops */ x[XX] = xi[XX] + a*xij[XX] + b*xik[XX] + c*temp[XX]; x[YY] = xi[YY] + a*xij[YY] + b*xik[YY] + c*temp[YY]; x[ZZ] = xi[ZZ] + a*xij[ZZ] + b*xik[ZZ] + c*temp[ZZ]; /* 18 Flops */ /* TOTAL: 33 flops */ } static void constr_vsite4FD(rvec xi,rvec xj,rvec xk,rvec xl,rvec x, real a,real b,real c,t_pbc *pbc) { rvec xij,xjk,xjl,temp; real d; pbc_rvec_sub(pbc,xj,xi,xij); pbc_rvec_sub(pbc,xk,xj,xjk); pbc_rvec_sub(pbc,xl,xj,xjl); /* 9 flops */ /* temp goes from i to a point on the plane jkl */ temp[XX] = xij[XX] + a*xjk[XX] + b*xjl[XX]; temp[YY] = xij[YY] + a*xjk[YY] + b*xjl[YY]; temp[ZZ] = xij[ZZ] + a*xjk[ZZ] + b*xjl[ZZ]; /* 12 flops */ d=c*gmx_invsqrt(iprod(temp,temp)); /* 6 + 10 flops */ x[XX] = xi[XX] + d*temp[XX]; x[YY] = xi[YY] + d*temp[YY]; x[ZZ] = xi[ZZ] + d*temp[ZZ]; /* 6 Flops */ /* TOTAL: 43 flops */ } static void constr_vsite4FDN(rvec xi,rvec xj,rvec xk,rvec xl,rvec x, real a,real b,real c,t_pbc *pbc) { rvec xij,xik,xil,ra,rb,rja,rjb,rm; real d; pbc_rvec_sub(pbc,xj,xi,xij); pbc_rvec_sub(pbc,xk,xi,xik); pbc_rvec_sub(pbc,xl,xi,xil); /* 9 flops */ ra[XX] = a*xik[XX]; ra[YY] = a*xik[YY]; ra[ZZ] = a*xik[ZZ]; rb[XX] = b*xil[XX]; rb[YY] = b*xil[YY]; rb[ZZ] = b*xil[ZZ]; /* 6 flops */ rvec_sub(ra,xij,rja); rvec_sub(rb,xij,rjb); /* 6 flops */ cprod(rja,rjb,rm); /* 9 flops */ d=c*gmx_invsqrt(norm2(rm)); /* 5+5+1 flops */ x[XX] = xi[XX] + d*rm[XX]; x[YY] = xi[YY] + d*rm[YY]; x[ZZ] = xi[ZZ] + d*rm[ZZ]; /* 6 Flops */ /* TOTAL: 47 flops */ } static int constr_vsiten(t_iatom *ia, t_iparams ip[], rvec *x, t_pbc *pbc) { rvec xs,x1,dx; dvec dsum; int n3,av,ai,i; real a; n3 = 3*ip[ia[0]].vsiten.n; av = ia[1]; ai = ia[2]; copy_rvec(x[ai],x1); clear_dvec(dsum); for(i=3; i<n3; i+=3) { ai = ia[i+2]; a = ip[ia[i]].vsiten.a; if (pbc) { pbc_dx_aiuc(pbc,x[ai],x1,dx); } else { rvec_sub(x[ai],x1,dx); } dsum[XX] += a*dx[XX]; dsum[YY] += a*dx[YY]; dsum[ZZ] += a*dx[ZZ]; /* 9 Flops */ } x[av][XX] = x1[XX] + dsum[XX]; x[av][YY] = x1[YY] + dsum[YY]; x[av][ZZ] = x1[ZZ] + dsum[ZZ]; return n3; } void construct_vsites(FILE *log,gmx_vsite_t *vsite, rvec x[],t_nrnb *nrnb, real dt,rvec *v, t_iparams ip[],t_ilist ilist[], int ePBC,gmx_bool bMolPBC,t_graph *graph, t_commrec *cr,matrix box) { rvec xpbc,xv,vv,dx; real a1,b1,c1,inv_dt; int i,inc,ii,nra,nr,tp,ftype; t_iatom avsite,ai,aj,ak,al,pbc_atom; t_iatom *ia; t_pbc pbc,*pbc_null,*pbc_null2; gmx_bool bDomDec; int *vsite_pbc,ishift; rvec reftmp,vtmp,rtmp; bDomDec = cr && DOMAINDECOMP(cr); /* We only need to do pbc when we have inter-cg vsites */ if (ePBC != epbcNONE && (bDomDec || bMolPBC) && vsite->n_intercg_vsite) { /* This is wasting some CPU time as we now do this multiple times * per MD step. But how often do we have vsites with full pbc? */ pbc_null = set_pbc_dd(&pbc,ePBC,cr!=NULL ? cr->dd : NULL,FALSE,box); } else { pbc_null = NULL; } if (cr) { if (bDomDec) { dd_move_x_vsites(cr->dd,box,x); } else if (vsite->bPDvsitecomm) { /* I'm not sure whether the periodicity and shift are guaranteed * to be consistent between different nodes when running e.g. polymers * in parallel. In this special case we thus unshift/shift, * but only when necessary. This is to make sure the coordinates * we move don't end up a box away... */ if (graph) unshift_self(graph,box,x); move_construct_x(vsite->vsitecomm,x,cr); if (graph) shift_self(graph,box,x); } } if (v) { inv_dt = 1.0/dt; } else { inv_dt = 1.0; } pbc_null2 = NULL; for(ftype=0; (ftype<F_NRE); ftype++) { if (<API key>[ftype].flags & IF_VSITE) { nra = <API key>[ftype].nratoms; nr = ilist[ftype].nr; ia = ilist[ftype].iatoms; if (pbc_null) { vsite_pbc = vsite->vsite_pbc_loc[ftype-F_VSITE2]; } else { vsite_pbc = NULL; } for(i=0; (i<nr); ) { tp = ia[0]; /* if (ftype != idef->functype[tp]) gmx_incons("Function types for vsites wrong"); */ /* The vsite and constructing atoms */ avsite = ia[1]; ai = ia[2]; aj = ia[3]; /* Constants for constructing vsites */ a1 = ip[tp].vsite.a; /* Check what kind of pbc we need to use */ if (vsite_pbc) { pbc_atom = vsite_pbc[i/(1+nra)]; if (pbc_atom > -2) { if (pbc_atom >= 0) { /* We need to copy the coordinates here, * single for single atom cg's pbc_atom is the vsite itself. */ copy_rvec(x[pbc_atom],xpbc); } pbc_null2 = pbc_null; } else { pbc_null2 = NULL; } } else { pbc_atom = -2; } /* Copy the old position */ copy_rvec(x[avsite],xv); /* Construct the vsite depending on type */ inc = nra+1; switch (ftype) { case F_VSITE2: constr_vsite2(x[ai],x[aj],x[avsite],a1,pbc_null2); break; case F_VSITE3: ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3(x[ai],x[aj],x[ak],x[avsite],a1,b1,pbc_null2); break; case F_VSITE3FD: ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3FD(x[ai],x[aj],x[ak],x[avsite],a1,b1,pbc_null2); break; case F_VSITE3FAD: ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3FAD(x[ai],x[aj],x[ak],x[avsite],a1,b1,pbc_null2); break; case F_VSITE3OUT: ak = ia[4]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite3OUT(x[ai],x[aj],x[ak],x[avsite],a1,b1,c1,pbc_null2); break; case F_VSITE4FD: ak = ia[4]; al = ia[5]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite4FD(x[ai],x[aj],x[ak],x[al],x[avsite],a1,b1,c1, pbc_null2); break; case F_VSITE4FDN: ak = ia[4]; al = ia[5]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite4FDN(x[ai],x[aj],x[ak],x[al],x[avsite],a1,b1,c1, pbc_null2); break; case F_VSITEN: inc = constr_vsiten(ia,ip,x,pbc_null2); break; default: gmx_fatal(FARGS,"No such vsite type %d in %s, line %d", ftype,__FILE__,__LINE__); } if (pbc_atom >= 0) { /* Match the pbc of this vsite to the rest of its charge group */ ishift = pbc_dx_aiuc(pbc_null,x[avsite],xpbc,dx); if (ishift != CENTRAL) rvec_add(xpbc,dx,x[avsite]); } if (v) { /* Calculate velocity of vsite... */ rvec_sub(x[avsite],xv,vv); svmul(inv_dt,vv,v[avsite]); } /* Increment loop variables */ i += inc; ia += inc; } } } } static void spread_vsite2(t_iatom ia[],real a, rvec x[],rvec f[],rvec fshift[], t_pbc *pbc,t_graph *g) { rvec fi,fj,dx; t_iatom av,ai,aj; ivec di; real b; int siv,sij; av = ia[1]; ai = ia[2]; aj = ia[3]; svmul(1-a,f[av],fi); svmul( a,f[av],fj); /* 7 flop */ rvec_inc(f[ai],fi); rvec_inc(f[aj],fj); /* 6 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g,ai),SHIFT_IVEC(g,av),di); siv = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,ai),SHIFT_IVEC(g,aj),di); sij = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc,x[ai],x[av],dx); sij = pbc_dx_aiuc(pbc,x[ai],x[aj],dx); } else { siv = CENTRAL; sij = CENTRAL; } if (fshift && (siv != CENTRAL || sij != CENTRAL)) { rvec_inc(fshift[siv],f[av]); rvec_dec(fshift[CENTRAL],fi); rvec_dec(fshift[sij],fj); } /* TOTAL: 13 flops */ } void <API key>(FILE *log,gmx_vsite_t *vsite, gmx_mtop_t *mtop,rvec x[]) { int as,mb,mol; gmx_molblock_t *molb; gmx_moltype_t *molt; as = 0; for(mb=0; mb<mtop->nmolblock; mb++) { molb = &mtop->molblock[mb]; molt = &mtop->moltype[molb->type]; for(mol=0; mol<molb->nmol; mol++) { construct_vsites(log,vsite,x+as,NULL,0.0,NULL, mtop->ffparams.iparams,molt->ilist, epbcNONE,TRUE,NULL,NULL,NULL); as += molt->atoms.nr; } } } static void spread_vsite3(t_iatom ia[],real a,real b, rvec x[],rvec f[],rvec fshift[], t_pbc *pbc,t_graph *g) { rvec fi,fj,fk,dx; atom_id av,ai,aj,ak; ivec di; int siv,sij,sik; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; svmul(1-a-b,f[av],fi); svmul( a,f[av],fj); svmul( b,f[av],fk); /* 11 flops */ rvec_inc(f[ai],fi); rvec_inc(f[aj],fj); rvec_inc(f[ak],fk); /* 9 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g,ai),SHIFT_IVEC(g,ia[1]),di); siv = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,ai),SHIFT_IVEC(g,aj),di); sij = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,ai),SHIFT_IVEC(g,ak),di); sik = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc,x[ai],x[av],dx); sij = pbc_dx_aiuc(pbc,x[ai],x[aj],dx); sik = pbc_dx_aiuc(pbc,x[ai],x[ak],dx); } else { siv = CENTRAL; sij = CENTRAL; sik = CENTRAL; } if (fshift && (siv!=CENTRAL || sij!=CENTRAL || sik!=CENTRAL)) { rvec_inc(fshift[siv],f[av]); rvec_dec(fshift[CENTRAL],fi); rvec_dec(fshift[sij],fj); rvec_dec(fshift[sik],fk); } /* TOTAL: 20 flops */ } static void spread_vsite3FD(t_iatom ia[],real a,real b, rvec x[],rvec f[],rvec fshift[], t_pbc *pbc,t_graph *g) { real fx,fy,fz,c,invl,fproj,a1; rvec xvi,xij,xjk,xix,fv,temp; t_iatom av,ai,aj,ak; int svi,sji,skj,d; ivec di; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; copy_rvec(f[av],fv); sji = pbc_rvec_sub(pbc,x[aj],x[ai],xij); skj = pbc_rvec_sub(pbc,x[ak],x[aj],xjk); /* 6 flops */ /* xix goes from i to point x on the line jk */ xix[XX]=xij[XX]+a*xjk[XX]; xix[YY]=xij[YY]+a*xjk[YY]; xix[ZZ]=xij[ZZ]+a*xjk[ZZ]; /* 6 flops */ invl=gmx_invsqrt(iprod(xix,xix)); c=b*invl; /* 4 + ?10? flops */ fproj=iprod(xix,fv)*invl*invl; /* = (xix . f)/(xix . xix) */ temp[XX]=c*(fv[XX]-fproj*xix[XX]); temp[YY]=c*(fv[YY]-fproj*xix[YY]); temp[ZZ]=c*(fv[ZZ]-fproj*xix[ZZ]); /* c is already calculated in constr_vsite3FD storing c somewhere will save 26 flops! */ a1=1-a; f[ai][XX] += fv[XX] - temp[XX]; f[ai][YY] += fv[YY] - temp[YY]; f[ai][ZZ] += fv[ZZ] - temp[ZZ]; f[aj][XX] += a1*temp[XX]; f[aj][YY] += a1*temp[YY]; f[aj][ZZ] += a1*temp[ZZ]; f[ak][XX] += a*temp[XX]; f[ak][YY] += a*temp[YY]; f[ak][ZZ] += a*temp[ZZ]; /* 19 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g,ia[1]),SHIFT_IVEC(g,ai),di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,aj),SHIFT_IVEC(g,ai),di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,ak),SHIFT_IVEC(g,aj),di); skj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc,x[av],x[ai],xvi); } else { svi = CENTRAL; } if (fshift && (svi!=CENTRAL || sji!=CENTRAL || skj!=CENTRAL)) { rvec_dec(fshift[svi],fv); fshift[CENTRAL][XX] += fv[XX] - (1 + a)*temp[XX]; fshift[CENTRAL][YY] += fv[YY] - (1 + a)*temp[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - (1 + a)*temp[ZZ]; fshift[ sji][XX] += temp[XX]; fshift[ sji][YY] += temp[YY]; fshift[ sji][ZZ] += temp[ZZ]; fshift[ skj][XX] += a*temp[XX]; fshift[ skj][YY] += a*temp[YY]; fshift[ skj][ZZ] += a*temp[ZZ]; } /* TOTAL: 61 flops */ } static void spread_vsite3FAD(t_iatom ia[],real a,real b, rvec x[],rvec f[],rvec fshift[], t_pbc *pbc,t_graph *g) { rvec xvi,xij,xjk,xperp,Fpij,Fppp,fv,f1,f2,f3; real a1,b1,c1,c2,invdij,invdij2,invdp,fproj; t_iatom av,ai,aj,ak; int svi,sji,skj,d; ivec di; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; copy_rvec(f[ia[1]],fv); sji = pbc_rvec_sub(pbc,x[aj],x[ai],xij); skj = pbc_rvec_sub(pbc,x[ak],x[aj],xjk); /* 6 flops */ invdij = gmx_invsqrt(iprod(xij,xij)); invdij2 = invdij * invdij; c1 = iprod(xij,xjk) * invdij2; xperp[XX] = xjk[XX] - c1*xij[XX]; xperp[YY] = xjk[YY] - c1*xij[YY]; xperp[ZZ] = xjk[ZZ] - c1*xij[ZZ]; /* xperp in plane ijk, perp. to ij */ invdp = gmx_invsqrt(iprod(xperp,xperp)); a1 = a*invdij; b1 = b*invdp; /* 45 flops */ /* a1, b1 and c1 are already calculated in constr_vsite3FAD storing them somewhere will save 45 flops! */ fproj=iprod(xij ,fv)*invdij2; svmul(fproj, xij, Fpij); /* proj. f on xij */ svmul(iprod(xperp,fv)*invdp*invdp,xperp,Fppp); /* proj. f on xperp */ svmul(b1*fproj, xperp,f3); /* 23 flops */ rvec_sub(fv,Fpij,f1); /* f1 = f - Fpij */ rvec_sub(f1,Fppp,f2); /* f2 = f - Fpij - Fppp */ for (d=0; (d<DIM); d++) { f1[d]*=a1; f2[d]*=b1; } /* 12 flops */ c2=1+c1; f[ai][XX] += fv[XX] - f1[XX] + c1*f2[XX] + f3[XX]; f[ai][YY] += fv[YY] - f1[YY] + c1*f2[YY] + f3[YY]; f[ai][ZZ] += fv[ZZ] - f1[ZZ] + c1*f2[ZZ] + f3[ZZ]; f[aj][XX] += f1[XX] - c2*f2[XX] - f3[XX]; f[aj][YY] += f1[YY] - c2*f2[YY] - f3[YY]; f[aj][ZZ] += f1[ZZ] - c2*f2[ZZ] - f3[ZZ]; f[ak][XX] += f2[XX]; f[ak][YY] += f2[YY]; f[ak][ZZ] += f2[ZZ]; /* 30 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g,ia[1]),SHIFT_IVEC(g,ai),di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,aj),SHIFT_IVEC(g,ai),di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,ak),SHIFT_IVEC(g,aj),di); skj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc,x[av],x[ai],xvi); } else { svi = CENTRAL; } if (fshift && (svi!=CENTRAL || sji!=CENTRAL || skj!=CENTRAL)) { rvec_dec(fshift[svi],fv); fshift[CENTRAL][XX] += fv[XX] - f1[XX] - (1-c1)*f2[XX] + f3[XX]; fshift[CENTRAL][YY] += fv[YY] - f1[YY] - (1-c1)*f2[YY] + f3[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - f1[ZZ] - (1-c1)*f2[ZZ] + f3[ZZ]; fshift[ sji][XX] += f1[XX] - c1 *f2[XX] - f3[XX]; fshift[ sji][YY] += f1[YY] - c1 *f2[YY] - f3[YY]; fshift[ sji][ZZ] += f1[ZZ] - c1 *f2[ZZ] - f3[ZZ]; fshift[ skj][XX] += f2[XX]; fshift[ skj][YY] += f2[YY]; fshift[ skj][ZZ] += f2[ZZ]; } /* TOTAL: 113 flops */ } static void spread_vsite3OUT(t_iatom ia[],real a,real b,real c, rvec x[],rvec f[],rvec fshift[], t_pbc *pbc,t_graph *g) { rvec xvi,xij,xik,fv,fj,fk; real cfx,cfy,cfz; atom_id av,ai,aj,ak; ivec di; int svi,sji,ski; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; sji = pbc_rvec_sub(pbc,x[aj],x[ai],xij); ski = pbc_rvec_sub(pbc,x[ak],x[ai],xik); /* 6 Flops */ copy_rvec(f[av],fv); cfx = c*fv[XX]; cfy = c*fv[YY]; cfz = c*fv[ZZ]; /* 3 Flops */ fj[XX] = a*fv[XX] - xik[ZZ]*cfy + xik[YY]*cfz; fj[YY] = xik[ZZ]*cfx + a*fv[YY] - xik[XX]*cfz; fj[ZZ] = -xik[YY]*cfx + xik[XX]*cfy + a*fv[ZZ]; fk[XX] = b*fv[XX] + xij[ZZ]*cfy - xij[YY]*cfz; fk[YY] = -xij[ZZ]*cfx + b*fv[YY] + xij[XX]*cfz; fk[ZZ] = xij[YY]*cfx - xij[XX]*cfy + b*fv[ZZ]; /* 30 Flops */ f[ai][XX] += fv[XX] - fj[XX] - fk[XX]; f[ai][YY] += fv[YY] - fj[YY] - fk[YY]; f[ai][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ]; rvec_inc(f[aj],fj); rvec_inc(f[ak],fk); /* 15 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g,ia[1]),SHIFT_IVEC(g,ai),di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,aj),SHIFT_IVEC(g,ai),di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,ak),SHIFT_IVEC(g,ai),di); ski = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc,x[av],x[ai],xvi); } else { svi = CENTRAL; } if (fshift && (svi!=CENTRAL || sji!=CENTRAL || ski!=CENTRAL)) { rvec_dec(fshift[svi],fv); fshift[CENTRAL][XX] += fv[XX] - fj[XX] - fk[XX]; fshift[CENTRAL][YY] += fv[YY] - fj[YY] - fk[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ]; rvec_inc(fshift[sji],fj); rvec_inc(fshift[ski],fk); } /* TOTAL: 54 flops */ } static void spread_vsite4FD(t_iatom ia[],real a,real b,real c, rvec x[],rvec f[],rvec fshift[], t_pbc *pbc,t_graph *g) { real d,invl,fproj,a1; rvec xvi,xij,xjk,xjl,xix,fv,temp; atom_id av,ai,aj,ak,al; ivec di; int svi,sji,skj,slj,m; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; al = ia[5]; sji = pbc_rvec_sub(pbc,x[aj],x[ai],xij); skj = pbc_rvec_sub(pbc,x[ak],x[aj],xjk); slj = pbc_rvec_sub(pbc,x[al],x[aj],xjl); /* 9 flops */ /* xix goes from i to point x on the plane jkl */ for(m=0; m<DIM; m++) xix[m] = xij[m] + a*xjk[m] + b*xjl[m]; /* 12 flops */ invl=gmx_invsqrt(iprod(xix,xix)); d=c*invl; /* 4 + ?10? flops */ copy_rvec(f[av],fv); fproj=iprod(xix,fv)*invl*invl; /* = (xix . f)/(xix . xix) */ for(m=0; m<DIM; m++) temp[m] = d*(fv[m] - fproj*xix[m]); /* c is already calculated in constr_vsite3FD storing c somewhere will save 35 flops! */ a1 = 1 - a - b; for(m=0; m<DIM; m++) { f[ai][m] += fv[m] - temp[m]; f[aj][m] += a1*temp[m]; f[ak][m] += a*temp[m]; f[al][m] += b*temp[m]; } /* 26 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g,ia[1]),SHIFT_IVEC(g,ai),di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,aj),SHIFT_IVEC(g,ai),di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,ak),SHIFT_IVEC(g,aj),di); skj = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,al),SHIFT_IVEC(g,aj),di); slj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc,x[av],x[ai],xvi); } else { svi = CENTRAL; } if (fshift && (svi!=CENTRAL || sji!=CENTRAL || skj!=CENTRAL || slj!=CENTRAL)) { rvec_dec(fshift[svi],fv); for(m=0; m<DIM; m++) { fshift[CENTRAL][m] += fv[m] - (1 + a + b)*temp[m]; fshift[ sji][m] += temp[m]; fshift[ skj][m] += a*temp[m]; fshift[ slj][m] += b*temp[m]; } } /* TOTAL: 77 flops */ } static void spread_vsite4FDN(t_iatom ia[],real a,real b,real c, rvec x[],rvec f[],rvec fshift[], t_pbc *pbc,t_graph *g) { rvec xvi,xij,xik,xil,ra,rb,rja,rjb,rab,rm,rt; rvec fv,fj,fk,fl; real invrm,denom; real cfx,cfy,cfz; ivec di; int av,ai,aj,ak,al; int svi,sij,sik,sil; /* DEBUG: check atom indices */ av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; al = ia[5]; copy_rvec(f[av],fv); sij = pbc_rvec_sub(pbc,x[aj],x[ai],xij); sik = pbc_rvec_sub(pbc,x[ak],x[ai],xik); sil = pbc_rvec_sub(pbc,x[al],x[ai],xil); /* 9 flops */ ra[XX] = a*xik[XX]; ra[YY] = a*xik[YY]; ra[ZZ] = a*xik[ZZ]; rb[XX] = b*xil[XX]; rb[YY] = b*xil[YY]; rb[ZZ] = b*xil[ZZ]; /* 6 flops */ rvec_sub(ra,xij,rja); rvec_sub(rb,xij,rjb); rvec_sub(rb,ra,rab); /* 9 flops */ cprod(rja,rjb,rm); /* 9 flops */ invrm=gmx_invsqrt(norm2(rm)); denom=invrm*invrm; /* 5+5+2 flops */ cfx = c*invrm*fv[XX]; cfy = c*invrm*fv[YY]; cfz = c*invrm*fv[ZZ]; /* 6 Flops */ cprod(rm,rab,rt); /* 9 flops */ rt[XX] *= denom; rt[YY] *= denom; rt[ZZ] *= denom; /* 3flops */ fj[XX] = ( -rm[XX]*rt[XX]) * cfx + ( rab[ZZ]-rm[YY]*rt[XX]) * cfy + (-rab[YY]-rm[ZZ]*rt[XX]) * cfz; fj[YY] = (-rab[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + ( rab[XX]-rm[ZZ]*rt[YY]) * cfz; fj[ZZ] = ( rab[YY]-rm[XX]*rt[ZZ]) * cfx + (-rab[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 30 flops */ cprod(rjb,rm,rt); /* 9 flops */ rt[XX] *= denom*a; rt[YY] *= denom*a; rt[ZZ] *= denom*a; /* 3flops */ fk[XX] = ( -rm[XX]*rt[XX]) * cfx + (-a*rjb[ZZ]-rm[YY]*rt[XX]) * cfy + ( a*rjb[YY]-rm[ZZ]*rt[XX]) * cfz; fk[YY] = ( a*rjb[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + (-a*rjb[XX]-rm[ZZ]*rt[YY]) * cfz; fk[ZZ] = (-a*rjb[YY]-rm[XX]*rt[ZZ]) * cfx + ( a*rjb[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 36 flops */ cprod(rm,rja,rt); /* 9 flops */ rt[XX] *= denom*b; rt[YY] *= denom*b; rt[ZZ] *= denom*b; /* 3flops */ fl[XX] = ( -rm[XX]*rt[XX]) * cfx + ( b*rja[ZZ]-rm[YY]*rt[XX]) * cfy + (-b*rja[YY]-rm[ZZ]*rt[XX]) * cfz; fl[YY] = (-b*rja[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + ( b*rja[XX]-rm[ZZ]*rt[YY]) * cfz; fl[ZZ] = ( b*rja[YY]-rm[XX]*rt[ZZ]) * cfx + (-b*rja[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 36 flops */ f[ai][XX] += fv[XX] - fj[XX] - fk[XX] - fl[XX]; f[ai][YY] += fv[YY] - fj[YY] - fk[YY] - fl[YY]; f[ai][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ] - fl[ZZ]; rvec_inc(f[aj],fj); rvec_inc(f[ak],fk); rvec_inc(f[al],fl); /* 21 flops */ if (g) { ivec_sub(SHIFT_IVEC(g,av),SHIFT_IVEC(g,ai),di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,aj),SHIFT_IVEC(g,ai),di); sij = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,ak),SHIFT_IVEC(g,ai),di); sik = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g,al),SHIFT_IVEC(g,ai),di); sil = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc,x[av],x[ai],xvi); } else { svi = CENTRAL; } if (fshift && (svi!=CENTRAL || sij!=CENTRAL || sik!=CENTRAL || sil!=CENTRAL)) { rvec_dec(fshift[svi],fv); fshift[CENTRAL][XX] += fv[XX] - fj[XX] - fk[XX] - fl[XX]; fshift[CENTRAL][YY] += fv[YY] - fj[YY] - fk[YY] - fl[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ] - fl[ZZ]; rvec_inc(fshift[sij],fj); rvec_inc(fshift[sik],fk); rvec_inc(fshift[sil],fl); } /* Total: 207 flops (Yuck!) */ } static int spread_vsiten(t_iatom ia[],t_iparams ip[], rvec x[],rvec f[],rvec fshift[], t_pbc *pbc,t_graph *g) { rvec xv,dx,fi; int n3,av,i,ai; real a; ivec di; int siv; n3 = 3*ip[ia[0]].vsiten.n; av = ia[1]; copy_rvec(x[av],xv); for(i=0; i<n3; i+=3) { ai = ia[i+2]; if (g) { ivec_sub(SHIFT_IVEC(g,ai),SHIFT_IVEC(g,av),di); siv = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc,x[ai],xv,dx); } else { siv = CENTRAL; } a = ip[ia[i]].vsiten.a; svmul(a,f[av],fi); rvec_inc(f[ai],fi); if (fshift && siv != CENTRAL) { rvec_inc(fshift[siv],fi); rvec_dec(fshift[CENTRAL],fi); } /* 6 Flops */ } return n3; } void spread_vsite_f(FILE *log,gmx_vsite_t *vsite, rvec x[],rvec f[],rvec *fshift, t_nrnb *nrnb,t_idef *idef, int ePBC,gmx_bool bMolPBC,t_graph *g,matrix box, t_commrec *cr) { real a1,b1,c1; int i,inc,m,nra,nr,tp,ftype; int nd2,nd3,nd3FD,nd3FAD,nd3OUT,nd4FD,nd4FDN,ndN; t_iatom *ia; t_iparams *ip; t_pbc pbc,*pbc_null,*pbc_null2; int *vsite_pbc; /* We only need to do pbc when we have inter-cg vsites */ if ((DOMAINDECOMP(cr) || bMolPBC) && vsite->n_intercg_vsite) { /* This is wasting some CPU time as we now do this multiple times * per MD step. But how often do we have vsites with full pbc? */ pbc_null = set_pbc_dd(&pbc,ePBC,cr->dd,FALSE,box); } else { pbc_null = NULL; } if (DOMAINDECOMP(cr)) { dd_clear_f_vsites(cr->dd,f); } else if (PARTDECOMP(cr) && vsite->vsitecomm != NULL) { <API key>(vsite->vsitecomm,f); } ip = idef->iparams; nd2 = 0; nd3 = 0; nd3FD = 0; nd3FAD = 0; nd3OUT = 0; nd4FD = 0; nd4FDN = 0; ndN = 0; /* this loop goes backwards to be able to build * * higher type vsites from lower types */ pbc_null2 = NULL; for(ftype=F_NRE-1; (ftype>=0); ftype if (<API key>[ftype].flags & IF_VSITE) { nra = <API key>[ftype].nratoms; nr = idef->il[ftype].nr; ia = idef->il[ftype].iatoms; if (pbc_null) { vsite_pbc = vsite->vsite_pbc_loc[ftype-F_VSITE2]; } else { vsite_pbc = NULL; } for(i=0; (i<nr); ) { /* Check if we need to apply pbc for this vsite */ if (vsite_pbc) { if (vsite_pbc[i/(1+nra)] > -2) pbc_null2 = pbc_null; else pbc_null2 = NULL; } tp = ia[0]; if (ftype != idef->functype[tp]) gmx_incons("Functiontypes for vsites wrong"); /* Constants for constructing */ a1 = ip[tp].vsite.a; /* Construct the vsite depending on type */ inc = nra+1; switch (ftype) { case F_VSITE2: spread_vsite2(ia,a1,x,f,fshift,pbc_null2,g); nd2++; break; case F_VSITE3: b1 = ip[tp].vsite.b; spread_vsite3(ia,a1,b1,x,f,fshift,pbc_null2,g); nd3++; break; case F_VSITE3FD: b1 = ip[tp].vsite.b; spread_vsite3FD(ia,a1,b1,x,f,fshift,pbc_null2,g); nd3FD++; break; case F_VSITE3FAD: b1 = ip[tp].vsite.b; spread_vsite3FAD(ia,a1,b1,x,f,fshift,pbc_null2,g); nd3FAD++; break; case F_VSITE3OUT: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite3OUT(ia,a1,b1,c1,x,f,fshift,pbc_null2,g); nd3OUT++; break; case F_VSITE4FD: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite4FD(ia,a1,b1,c1,x,f,fshift,pbc_null2,g); nd4FD++; break; case F_VSITE4FDN: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite4FDN(ia,a1,b1,c1,x,f,fshift,pbc_null2,g); nd4FDN++; break; case F_VSITEN: inc = spread_vsiten(ia,ip,x,f,fshift,pbc_null2,g); ndN += inc; break; default: gmx_fatal(FARGS,"No such vsite type %d in %s, line %d", ftype,__FILE__,__LINE__); } clear_rvec(f[ia[1]]); /* Increment loop variables */ i += inc; ia += inc; } } } inc_nrnb(nrnb,eNR_VSITE2, nd2 ); inc_nrnb(nrnb,eNR_VSITE3, nd3 ); inc_nrnb(nrnb,eNR_VSITE3FD, nd3FD ); inc_nrnb(nrnb,eNR_VSITE3FAD,nd3FAD ); inc_nrnb(nrnb,eNR_VSITE3OUT,nd3OUT ); inc_nrnb(nrnb,eNR_VSITE4FD, nd4FD ); inc_nrnb(nrnb,eNR_VSITE4FDN,nd4FDN ); inc_nrnb(nrnb,eNR_VSITEN, ndN ); if (DOMAINDECOMP(cr)) { dd_move_f_vsites(cr->dd,f,fshift); } else if (vsite->bPDvsitecomm) { /* We only move forces here, and they are independent of shifts */ move_construct_f(vsite->vsitecomm,f,cr); } } static int *atom2cg(t_block *cgs) { int *a2cg,cg,i; snew(a2cg,cgs->index[cgs->nr]); for(cg=0; cg<cgs->nr; cg++) { for(i=cgs->index[cg]; i<cgs->index[cg+1]; i++) a2cg[i] = cg; } return a2cg; } static int count_intercg_vsite(gmx_mtop_t *mtop) { int mb,mt,ftype,nral,i,cg,a; gmx_molblock_t *molb; gmx_moltype_t *molt; int *a2cg; t_ilist *il; t_iatom *ia; int n_intercg_vsite; n_intercg_vsite = 0; for(mb=0; mb<mtop->nmolblock; mb++) { molb = &mtop->molblock[mb]; molt = &mtop->moltype[molb->type]; a2cg = atom2cg(&molt->cgs); for(ftype=0; ftype<F_NRE; ftype++) { if (<API key>[ftype].flags & IF_VSITE) { nral = NRAL(ftype); il = &molt->ilist[ftype]; ia = il->iatoms; for(i=0; i<il->nr; i+=1+nral) { cg = a2cg[ia[1+i]]; for(a=1; a<nral; a++) { if (a2cg[ia[1+a]] != cg) { n_intercg_vsite += molb->nmol; break; } } } } } sfree(a2cg); } return n_intercg_vsite; } static int **get_vsite_pbc(t_iparams *iparams,t_ilist *ilist, t_atom *atom,t_mdatoms *md, t_block *cgs,int *a2cg) { int ftype,nral,i,j,vsi,vsite,cg_v,cg_c,a,nc3=0; t_ilist *il; t_iatom *ia; int **vsite_pbc,*vsite_pbc_f; char *pbc_set; gmx_bool <API key>; /* Make an array that tells if the pbc of an atom is set */ snew(pbc_set,cgs->index[cgs->nr]); /* PBC is set for all non vsites */ for(a=0; a<cgs->index[cgs->nr]; a++) { if ((atom && atom[a].ptype != eptVSite) || (md && md->ptype[a] != eptVSite)) { pbc_set[a] = 1; } } snew(vsite_pbc,F_VSITEN-F_VSITE2+1); for(ftype=0; ftype<F_NRE; ftype++) { if (<API key>[ftype].flags & IF_VSITE) { nral = NRAL(ftype); il = &ilist[ftype]; ia = il->iatoms; snew(vsite_pbc[ftype-F_VSITE2],il->nr/(1+nral)); vsite_pbc_f = vsite_pbc[ftype-F_VSITE2]; i = 0; while (i < il->nr) { vsi = i/(1+nral); vsite = ia[i+1]; cg_v = a2cg[vsite]; /* A value of -2 signals that this vsite and its contructing * atoms are all within the same cg, so no pbc is required. */ vsite_pbc_f[vsi] = -2; /* Check if constructing atoms are outside the vsite's cg */ nc3 = 0; if (ftype == F_VSITEN) { nc3 = 3*iparams[ia[i]].vsiten.n; for(j=0; j<nc3; j+=3) { if (a2cg[ia[i+j+2]] != cg_v) vsite_pbc_f[vsi] = -1; } } else { for(a=1; a<nral; a++) { if (a2cg[ia[i+1+a]] != cg_v) vsite_pbc_f[vsi] = -1; } } if (vsite_pbc_f[vsi] == -1) { /* Check if this is the first processed atom of a vsite only cg */ <API key> = TRUE; for(a=cgs->index[cg_v]; a<cgs->index[cg_v+1]; a++) { /* Non-vsites already have pbc set, so simply check for pbc_set */ if (pbc_set[a]) { <API key> = FALSE; break; } } if (<API key>) { /* First processed atom of a vsite only charge group. * The pbc of the input coordinates to construct_vsites * should be preserved. */ vsite_pbc_f[vsi] = vsite; } else if (cg_v != a2cg[ia[1+i+1]]) { /* This vsite has a different charge group index * than it's first constructing atom * and the charge group has more than one atom, * search for the first normal particle * or vsite that already had its pbc defined. * If nothing is found, use full pbc for this vsite. */ for(a=cgs->index[cg_v]; a<cgs->index[cg_v+1]; a++) { if (a != vsite && pbc_set[a]) { vsite_pbc_f[vsi] = a; if (gmx_debug_at) fprintf(debug,"vsite %d match pbc with atom %d\n", vsite+1,a+1); break; } } if (gmx_debug_at) fprintf(debug,"vsite atom %d cg %d - %d pbc atom %d\n", vsite+1,cgs->index[cg_v]+1,cgs->index[cg_v+1], vsite_pbc_f[vsi]+1); } } if (ftype == F_VSITEN) { /* The other entries in vsite_pbc_f are not used for center vsites */ i += nc3; } else { i += 1+nral; } /* This vsite now has its pbc defined */ pbc_set[vsite] = 1; } } } sfree(pbc_set); return vsite_pbc; } gmx_vsite_t *init_vsite(gmx_mtop_t *mtop,t_commrec *cr) { int nvsite,i; int *a2cg,cg; gmx_vsite_t *vsite; int mt; gmx_moltype_t *molt; /* check if there are vsites */ nvsite = 0; for(i=0; i<F_NRE; i++) { if (<API key>[i].flags & IF_VSITE) { nvsite += <API key>(mtop,i); } } if (nvsite == 0) { return NULL; } snew(vsite,1); vsite->n_intercg_vsite = count_intercg_vsite(mtop); if (vsite->n_intercg_vsite > 0 && DOMAINDECOMP(cr)) { vsite->nvsite_pbc_molt = mtop->nmoltype; snew(vsite->vsite_pbc_molt,vsite->nvsite_pbc_molt); for(mt=0; mt<mtop->nmoltype; mt++) { molt = &mtop->moltype[mt]; /* Make an atom to charge group index */ a2cg = atom2cg(&molt->cgs); vsite->vsite_pbc_molt[mt] = get_vsite_pbc(mtop->ffparams.iparams, molt->ilist, molt->atoms.atom,NULL, &molt->cgs,a2cg); sfree(a2cg); } snew(vsite-><API key>,F_VSITEN-F_VSITE2+1); snew(vsite->vsite_pbc_loc ,F_VSITEN-F_VSITE2+1); } return vsite; } void set_vsite_top(gmx_vsite_t *vsite,gmx_localtop_t *top,t_mdatoms *md, t_commrec *cr) { int *a2cg; /* Make an atom to charge group index */ a2cg = atom2cg(&top->cgs); if (vsite->n_intercg_vsite > 0) { vsite->vsite_pbc_loc = get_vsite_pbc(top->idef.iparams, top->idef.il,NULL,md, &top->cgs,a2cg); if (PARTDECOMP(cr)) { snew(vsite->vsitecomm,1); vsite->bPDvsitecomm = <API key>(&(top->idef),cr,vsite->vsitecomm); } } sfree(a2cg); }
// modification, are permitted provided that the following conditions are // met: // 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 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // 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. #pragma once #include "CSSPrimitiveValue.h" #include <wtf/text/StringView.h> namespace WebCore { enum CSSParserTokenType { IdentToken = 0, FunctionToken, AtKeywordToken, HashToken, UrlToken, BadUrlToken, DelimiterToken, NumberToken, PercentageToken, DimensionToken, IncludeMatchToken, DashMatchToken, PrefixMatchToken, SuffixMatchToken, SubstringMatchToken, ColumnToken, UnicodeRangeToken, WhitespaceToken, CDOToken, CDCToken, ColonToken, SemicolonToken, CommaToken, <API key>, <API key>, LeftBracketToken, RightBracketToken, LeftBraceToken, RightBraceToken, StringToken, BadStringToken, EOFToken, CommentToken, }; enum NumericSign { NoSign, PlusSign, MinusSign, }; enum NumericValueType { IntegerValueType, NumberValueType, }; enum HashTokenType { HashTokenId, <API key>, }; class CSSParserToken { <API key>; public: enum BlockType { NotBlock, BlockStart, BlockEnd, }; CSSParserToken(CSSParserTokenType, BlockType = NotBlock); CSSParserToken(CSSParserTokenType, StringView, BlockType = NotBlock); CSSParserToken(CSSParserTokenType, UChar); // for DelimiterToken CSSParserToken(CSSParserTokenType, double, NumericValueType, NumericSign); // for NumberToken CSSParserToken(CSSParserTokenType, UChar32, UChar32); // for UnicodeRangeToken CSSParserToken(HashTokenType, StringView); bool operator==(const CSSParserToken& other) const; bool operator!=(const CSSParserToken& other) const { return !(*this == other); } // Converts NumberToken to DimensionToken. void <API key>(StringView); // Converts NumberToken to PercentageToken. void convertToPercentage(); CSSParserTokenType type() const { return static_cast<CSSParserTokenType>(m_type); } StringView value() const { if (m_valueIs8Bit) return StringView(static_cast<const LChar*>(m_valueDataCharRaw), m_valueLength); return StringView(static_cast<const UChar*>(m_valueDataCharRaw), m_valueLength); } UChar delimiter() const; NumericSign numericSign() const; NumericValueType numericValueType() const; double numericValue() const; HashTokenType getHashTokenType() const { ASSERT(m_type == HashToken); return m_hashTokenType; } BlockType getBlockType() const { return static_cast<BlockType>(m_blockType); } CSSPrimitiveValue::UnitType unitType() const { return static_cast<CSSPrimitiveValue::UnitType>(m_unit); } UChar32 unicodeRangeStart() const { ASSERT(m_type == UnicodeRangeToken); return m_unicodeRange.start; } UChar32 unicodeRangeEnd() const { ASSERT(m_type == UnicodeRangeToken); return m_unicodeRange.end; } CSSValueID id() const; CSSValueID functionId() const; bool hasStringBacking() const; CSSPropertyID <API key>() const; void serialize(StringBuilder&) const; CSSParser<API key>(const StringView&) const; private: void <API key>(StringView string) { m_valueLength = string.length(); m_valueIs8Bit = string.is8Bit(); m_valueDataCharRaw = m_valueIs8Bit ? const_cast<void*>(static_cast<const void*>(string.characters8())) : const_cast<void*>(static_cast<const void*>(string.characters16())); } unsigned m_type : 6; // CSSParserTokenType unsigned m_blockType : 2; // BlockType unsigned m_numericValueType : 1; // NumericValueType unsigned m_numericSign : 2; // NumericSign unsigned m_unit : 7; // CSSPrimitiveValue::UnitType bool <API key>(const CSSParserToken& other) const; // m_value... is an unpacked StringView so that we can pack it // tightly with the rest of this object for a smaller object size. bool m_valueIs8Bit : 1; unsigned m_valueLength; void* m_valueDataCharRaw; // Either LChar* or UChar*. union { UChar m_delimiter; HashTokenType m_hashTokenType; double m_numericValue; mutable int m_id; struct { UChar32 start; UChar32 end; } m_unicodeRange; }; }; } // namespace WebCore
CKEDITOR.plugins.setLang( 'magicline', 'it', { title: 'Inserisci paragrafo qui' } );
#ifndef <API key> #define <API key> // This header is included to get the nested declaration of Packet structure. #include "webrtc/base/scoped_ptr.h" #include "webrtc/modules/rtp_rtcp/include/fec_receiver.h" #include "webrtc/modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "webrtc/modules/rtp_rtcp/source/<API key>.h" #include "webrtc/typedefs.h" namespace webrtc { class <API key>; class FecReceiverImpl : public FecReceiver { public: FecReceiverImpl(RtpData* callback); virtual ~FecReceiverImpl(); int32_t <API key>(const RTPHeader& rtp_header, const uint8_t* incoming_rtp_packet, size_t packet_length, uint8_t ulpfec_payload_type) override; int32_t ProcessReceivedFec() override; FecPacketCounter GetPacketCounter() const override; private: rtc::scoped_ptr<<API key>> crit_sect_; RtpData* <API key>; <API key>* fec_; // TODO(holmer): In the current version <API key> is never more // than one packet, since we process FEC every time a new packet // arrives. We should remove the list. <API key>::ReceivedPacketList <API key>; <API key>::RecoveredPacketList <API key>; FecPacketCounter packet_counter_; }; } // namespace webrtc #endif // <API key>
#include <linux/module.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/interrupt.h> #include <linux/err.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/ioport.h> #include <linux/pm_runtime.h> #include <linux/device.h> #include <linux/pm_qos_params.h> #include <mach/msm_hsusb_hw.h> #include <mach/msm72k_otg.h> #include <mach/msm_hsusb.h> #include <linux/debugfs.h> #include <linux/uaccess.h> #include <mach/clk.h> #include <mach/msm_xo.h> #define MSM_USB_BASE (dev->regs) #define <API key> (msecs_to_jiffies(10)) #define DRIVER_NAME "msm_otg" static void otg_reset(struct otg_transceiver *xceiv, int phy_reset); static void <API key>(int online); static void <API key>(int online); struct msm_otg *the_msm_otg; static int is_host(void) { struct msm_otg *dev = the_msm_otg; if (dev->pmic_id_notif_supp) return dev->pmic_id_status ? 0 : 1; else if (dev->pdata->otg_mode == OTG_ID) return (OTGSC_ID & readl(USB_OTGSC)) ? 0 : 1; else return !test_bit(ID, &dev->inputs); } static int is_b_sess_vld(void) { struct msm_otg *dev = the_msm_otg; if (dev->pdata->otg_mode == OTG_ID) return (OTGSC_BSV & readl(USB_OTGSC)) ? 1 : 0; else return test_bit(B_SESS_VLD, &dev->inputs); } static unsigned ulpi_read(struct msm_otg *dev, unsigned reg) { unsigned ret, timeout = 100000; unsigned long flags; spin_lock_irqsave(&dev->lock, flags); /* initiate read operation */ writel(ULPI_RUN | ULPI_READ | ULPI_ADDR(reg), USB_ULPI_VIEWPORT); /* wait for completion */ while ((readl(USB_ULPI_VIEWPORT) & ULPI_RUN) && (--timeout)) cpu_relax(); if (timeout == 0) { pr_err("%s: timeout %08x\n", __func__, readl(USB_ULPI_VIEWPORT)); <API key>(&dev->lock, flags); return 0xffffffff; } ret = ULPI_DATA_READ(readl(USB_ULPI_VIEWPORT)); <API key>(&dev->lock, flags); return ret; } static int ulpi_write(struct msm_otg *dev, unsigned val, unsigned reg) { unsigned timeout = 10000; unsigned long flags; spin_lock_irqsave(&dev->lock, flags); /* initiate write operation */ writel(ULPI_RUN | ULPI_WRITE | ULPI_ADDR(reg) | ULPI_DATA(val), USB_ULPI_VIEWPORT); /* wait for completion */ while ((readl(USB_ULPI_VIEWPORT) & ULPI_RUN) && (--timeout)) ; if (timeout == 0) { pr_err("%s: timeout\n", __func__); <API key>(&dev->lock, flags); return -1; } <API key>(&dev->lock, flags); return 0; } static int usb_ulpi_write(struct otg_transceiver *xceiv, u32 val, u32 reg) { struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); return ulpi_write(dev, val, reg); } static int usb_ulpi_read(struct otg_transceiver *xceiv, u32 reg) { struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); return ulpi_read(dev, reg); } #ifdef CONFIG_USB_EHCI_MSM static void enable_idgnd(struct msm_otg *dev) { /* Do nothing if instead of ID pin, USER controls mode switch */ if (dev->pdata->otg_mode == OTG_USER_CONTROL) return; ulpi_write(dev, (1<<4), 0x0E); ulpi_write(dev, (1<<4), 0x11); writel(readl(USB_OTGSC) | OTGSC_IDIE, USB_OTGSC); } static void disable_idgnd(struct msm_otg *dev) { /* Do nothing if instead of ID pin, USER controls mode switch */ if (dev->pdata->otg_mode == OTG_USER_CONTROL) return; ulpi_write(dev, (1<<4), 0x0F); ulpi_write(dev, (1<<4), 0x12); writel(readl(USB_OTGSC) & ~OTGSC_IDIE, USB_OTGSC); } #endif static void enable_idabc(struct msm_otg *dev) { #ifdef CONFIG_USB_MSM_ACA ulpi_write(dev, (1<<5), 0x0E); ulpi_write(dev, (1<<5), 0x11); #endif } static void disable_idabc(struct msm_otg *dev) { #ifdef CONFIG_USB_MSM_ACA ulpi_write(dev, (1<<5), 0x0F); ulpi_write(dev, (1<<5), 0x12); #endif } static void enable_sess_valid(struct msm_otg *dev) { /* Do nothing if instead of ID pin, USER controls mode switch */ if (dev->pdata->otg_mode == OTG_USER_CONTROL) return; ulpi_write(dev, (1<<2), 0x0E); ulpi_write(dev, (1<<2), 0x11); writel(readl(USB_OTGSC) | OTGSC_BSVIE, USB_OTGSC); } static void disable_sess_valid(struct msm_otg *dev) { /* Do nothing if instead of ID pin, USER controls mode switch */ if (dev->pdata->otg_mode == OTG_USER_CONTROL) return; ulpi_write(dev, (1<<2), 0x0F); ulpi_write(dev, (1<<2), 0x12); writel(readl(USB_OTGSC) & ~OTGSC_BSVIE, USB_OTGSC); } #ifdef CONFIG_USB_MSM_ACA static void set_aca_id_inputs(struct msm_otg *dev) { u8 phy_ints; phy_ints = ulpi_read(dev, 0x13); pr_debug("phy_ints = %x\n", phy_ints); clear_bit(ID_A, &dev->inputs); clear_bit(ID_B, &dev->inputs); clear_bit(ID_C, &dev->inputs); if (phy_id_state_a(phy_ints)) { pr_debug("ID_A set\n"); set_bit(ID_A, &dev->inputs); set_bit(A_BUS_REQ, &dev->inputs); } else if (phy_id_state_b(phy_ints)) { pr_debug("ID_B set\n"); set_bit(ID_B, &dev->inputs); } else if (phy_id_state_c(phy_ints)) { pr_debug("ID_C set\n"); set_bit(ID_C, &dev->inputs); } } #define get_aca_bmaxpower(dev) (dev->b_max_power) #define set_aca_bmaxpower(dev, power) (dev->b_max_power = power) #else #define get_aca_bmaxpower(dev) 0 #define set_aca_bmaxpower(dev, power) #endif static inline void <API key>(struct msm_otg *dev) { unsigned res = 0; if (!dev->pdata || dev->pdata->pemp_level == <API key>) return; res = ulpi_read(dev, ULPI_CONFIG_REG3); res &= ~(<API key>); if (dev->pdata->pemp_level != <API key>) res |= dev->pdata->pemp_level; ulpi_write(dev, res, ULPI_CONFIG_REG3); } static inline void set_cdr_auto_reset(struct msm_otg *dev) { unsigned res = 0; if (!dev->pdata || dev->pdata->cdr_autoreset == <API key>) return; res = ulpi_read(dev, ULPI_DIGOUT_CTRL); if (dev->pdata->cdr_autoreset == <API key>) res &= ~ULPI_CDR_AUTORESET; else res |= ULPI_CDR_AUTORESET; ulpi_write(dev, res, ULPI_DIGOUT_CTRL); } static inline void set_se1_gating(struct msm_otg *dev) { unsigned res = 0; if (!dev->pdata || dev->pdata->se1_gating == SE1_GATING_DEFAULT) return; res = ulpi_read(dev, ULPI_DIGOUT_CTRL); if (dev->pdata->se1_gating == SE1_GATING_ENABLE) res &= ~ULPI_SE1_GATE; else res |= ULPI_SE1_GATE; ulpi_write(dev, res, ULPI_DIGOUT_CTRL); } static inline void <API key>(struct msm_otg *dev) { unsigned res = 0; if (!dev->pdata || dev->pdata->drv_ampl == <API key>) return; res = ulpi_read(dev, ULPI_CONFIG_REG2); res &= ~ULPI_DRV_AMPL_MASK; if (dev->pdata->drv_ampl != <API key>) res |= dev->pdata->drv_ampl; ulpi_write(dev, res, ULPI_CONFIG_REG2); } static const char *state_string(enum usb_otg_state state) { switch (state) { case OTG_STATE_A_IDLE: return "a_idle"; case <API key>: return "a_wait_vrise"; case <API key>: return "a_wait_bcon"; case OTG_STATE_A_HOST: return "a_host"; case OTG_STATE_A_SUSPEND: return "a_suspend"; case <API key>: return "a_peripheral"; case <API key>: return "a_wait_vfall"; case <API key>: return "a_vbus_err"; case OTG_STATE_B_IDLE: return "b_idle"; case <API key>: return "b_srp_init"; case <API key>: return "b_peripheral"; case <API key>: return "b_wait_acon"; case OTG_STATE_B_HOST: return "b_host"; default: return "UNDEFINED"; } } static const char *timer_string(int bit) { switch (bit) { case A_WAIT_VRISE: return "a_wait_vrise"; case A_WAIT_VFALL: return "a_wait_vfall"; case B_SRP_FAIL: return "b_srp_fail"; case A_WAIT_BCON: return "a_wait_bcon"; case A_AIDL_BDIS: return "a_aidl_bdis"; case A_BIDL_ADIS: return "a_bidl_adis"; case B_ASE0_BRST: return "b_ase0_brst"; default: return "UNDEFINED"; } } /* Prevent idle power collapse(pc) while operating in peripheral mode */ static void <API key>(struct msm_otg *dev, int vote) { struct <API key> *pdata = dev->pdata; u32 swfi_latency = 0; if (pdata) swfi_latency = pdata->swfi_latency + 1; if (vote) <API key>(pdata->pm_qos_req_dma, swfi_latency); else <API key>(pdata->pm_qos_req_dma, <API key>); } /* If USB Core is running its protocol engine based on PCLK, * PCLK must be running at >60Mhz for correct HSUSB operation and * USB core cannot tolerate frequency changes on PCLK. For such * USB cores, vote for maximum clk frequency on pclk source */ static void <API key>(struct msm_otg *dev, int vote) { if (!<API key>(&dev->otg)) return; if (dev->pdata->usb_in_sps) { if (vote) clk_set_min_rate(dev->dfab_clk, 64000000); else clk_set_min_rate(dev->dfab_clk, 0); return; } if (vote) clk_enable(dev->pdata->ebi1_clk); else clk_disable(dev->pdata->ebi1_clk); } /* Controller gives interrupt for every 1 mesc if 1MSIE is set in OTGSC. * This interrupt can be used as a timer source and OTG timers can be * implemented. But hrtimers on MSM hardware can give atleast 1/32 KHZ * precision. This precision is more than enough for OTG timers. */ static enum hrtimer_restart msm_otg_timer_func(struct hrtimer *_timer) { struct msm_otg *dev = container_of(_timer, struct msm_otg, timer); /* Phy lockup issues are observed when VBUS Valid interrupt is * enabled. Hence set A_VBUS_VLD upon timer exipration. */ if (dev->active_tmout == A_WAIT_VRISE) set_bit(A_VBUS_VLD, &dev->inputs); else set_bit(dev->active_tmout, &dev->tmouts); pr_debug("expired %s timer\n", timer_string(dev->active_tmout)); queue_work(dev->wq, &dev->sm_work); return HRTIMER_NORESTART; } static void msm_otg_del_timer(struct msm_otg *dev) { int bit = dev->active_tmout; pr_debug("deleting %s timer. remaining %lld msec \n", timer_string(bit), div_s64(ktime_to_us(<API key>(&dev->timer)), 1000)); hrtimer_cancel(&dev->timer); clear_bit(bit, &dev->tmouts); } static void msm_otg_start_timer(struct msm_otg *dev, int time, int bit) { clear_bit(bit, &dev->tmouts); dev->active_tmout = bit; pr_debug("starting %s timer\n", timer_string(bit)); hrtimer_start(&dev->timer, ktime_set(time / 1000, (time % 1000) * 1000000), HRTIMER_MODE_REL); } /* No two otg timers run in parallel. So one hrtimer is sufficient */ static void msm_otg_init_timer(struct msm_otg *dev) { hrtimer_init(&dev->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); dev->timer.function = msm_otg_timer_func; } static const char *event_string(enum usb_otg_event event) { switch (event) { case <API key>: return "DEV_CONN_TMOUT"; case <API key>: return "<API key>"; case <API key>: return "HUB_NOT_SUPPORTED"; case <API key>: return "DEV_NOT_SUPPORTED,"; case <API key>: return "HNP_FAILED"; case <API key>: return "NO_RESP_FOR_SRP"; default: return "UNDEFINED"; } } static int msm_otg_send_event(struct otg_transceiver *xceiv, enum usb_otg_event event) { char module_name[16]; char udev_event[128]; char *envp[] = { module_name, udev_event, NULL }; int ret; pr_debug("sending %s event\n", event_string(event)); snprintf(module_name, 16, "MODULE=%s", DRIVER_NAME); snprintf(udev_event, 128, "EVENT=%s", event_string(event)); ret = kobject_uevent_env(&xceiv->dev->kobj, KOBJ_CHANGE, envp); if (ret < 0) pr_info("uevent sending failed with ret = %d\n", ret); return ret; } static int msm_otg_start_hnp(struct otg_transceiver *xceiv) { struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); enum usb_otg_state state; unsigned long flags; spin_lock_irqsave(&dev->lock, flags); state = dev->otg.state; <API key>(&dev->lock, flags); if (state != OTG_STATE_A_HOST) { pr_err("HNP can not be initiated in %s state\n", state_string(state)); return -EINVAL; } pr_debug("A-Host: HNP initiated\n"); clear_bit(A_BUS_REQ, &dev->inputs); wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); return 0; } static int msm_otg_start_srp(struct otg_transceiver *xceiv) { struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); u32 val; int ret = 0; enum usb_otg_state state; unsigned long flags; spin_lock_irqsave(&dev->lock, flags); state = dev->otg.state; <API key>(&dev->lock, flags); if (state != OTG_STATE_B_IDLE) { pr_err("SRP can not be initiated in %s state\n", state_string(state)); ret = -EINVAL; goto out; } if ((jiffies - dev->b_last_se0_sess) < msecs_to_jiffies(TB_SRP_INIT)) { pr_debug("initial conditions of SRP are not met. Try again" "after some time\n"); ret = -EAGAIN; goto out; } /* Harware auto assist data pulsing: Data pulse is given * for 7msec; wait for vbus */ val = readl(USB_OTGSC); writel((val & ~OTGSC_INTR_STS_MASK) | OTGSC_HADP, USB_OTGSC); /* VBUS plusing is obsoleted in OTG 2.0 supplement */ out: return ret; } static int msm_otg_set_power(struct otg_transceiver *xceiv, unsigned mA) { static enum chg_type curr_chg = <API key>; struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); struct <API key> *pdata = dev->pdata; enum chg_type new_chg = atomic_read(&dev->chg_type); unsigned charge = mA; /* Call chg_connected only if the charger has changed */ if (new_chg != curr_chg && pdata->chg_connected) { curr_chg = new_chg; pdata->chg_connected(new_chg); } /* Always use USB_IDCHG_MAX for charging in ID_B and ID_C */ if (test_bit(ID_C, &dev->inputs) || test_bit(ID_B, &dev->inputs)) charge = USB_IDCHG_MAX; pr_debug("Charging with %dmA current\n", charge); /* Call vbus_draw only if the charger is of known type */ if (pdata->chg_vbus_draw && new_chg != <API key>) pdata->chg_vbus_draw(charge); if (new_chg == <API key>) { wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); } return 0; } static int msm_otg_set_clk(struct otg_transceiver *xceiv, int on) { struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); if (!dev || (dev != the_msm_otg)) return -ENODEV; if (on) /* enable clocks */ clk_enable(dev->hs_clk); else clk_disable(dev->hs_clk); return 0; } static void <API key>(struct otg_transceiver *xceiv, int on) { struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); struct <API key> *pdata = dev->pdata; if (!xceiv->gadget) return; if (on) { if (pdata->setup_gpio) pdata->setup_gpio(<API key>); /* vote for minimum dma_latency to prevent idle * power collapse(pc) while running in peripheral mode. */ <API key>(dev, 1); /* increment the clk reference count so that * it would be still on when disabled from * low power mode routine */ if (dev->pdata-><API key>) clk_enable(dev->hs_pclk); <API key>(xceiv->gadget); } else { atomic_set(&dev->chg_type, <API key>); <API key>(xceiv->gadget); /* decrement the clk reference count so that * it would be off when disabled from * low power mode routine */ if (dev->pdata-><API key>) clk_disable(dev->hs_pclk); <API key>(dev, 0); if (pdata->setup_gpio) pdata->setup_gpio(USB_SWITCH_DISABLE); } } static void msm_otg_start_host(struct otg_transceiver *xceiv, int on) { struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); struct <API key> *pdata = dev->pdata; if (!xceiv->host) return; if (dev->start_host) { /* Some targets, e.g. ST1.5, use GPIO to choose b/w connector */ if (on && pdata->setup_gpio) pdata->setup_gpio(USB_SWITCH_HOST); /* increment or decrement the clk reference count * to avoid usb h/w lockup issues when low power * mode is initiated and vbus is on. */ if (dev->pdata-><API key>) { if (on) clk_enable(dev->hs_pclk); else clk_disable(dev->hs_pclk); } dev->start_host(xceiv->host, on); if (!on && pdata->setup_gpio) pdata->setup_gpio(USB_SWITCH_DISABLE); } } static int msm_otg_suspend(struct msm_otg *dev) { unsigned long timeout; int vbus = 0; unsigned ret; enum chg_type chg_type = atomic_read(&dev->chg_type); unsigned long flags; disable_irq(dev->irq); if (atomic_read(&dev->in_lpm)) goto out; #ifdef CONFIG_USB_MSM_ACA /* * ACA interrupts are disabled before entering into LPM. * If LPM is allowed in host mode with accessory charger * connected or only accessory charger is connected, * there is a chance that charger is removed and we will * not know about it. * * REVISIT * * Allowing LPM in case of gadget bus suspend is tricky. * Bus suspend can happen in two states. * 1. ID_float: Allowing LPM has pros and cons. If LPM is allowed * and accessory charger is connected, we miss ID_float --> ID_C * transition where we could draw large amount of current * compared to the suspend current. * 2. ID_C: We can not allow LPM. If accessory charger is removed * we should not draw more than what host could supply which will * be less compared to accessory charger. * * For simplicity, LPM is not allowed in bus suspend. */ if ((test_bit(ID, &dev->inputs) && test_bit(B_SESS_VLD, &dev->inputs) && chg_type != <API key>) || test_bit(ID_A, &dev->inputs)) goto out; /* Disable ID_abc interrupts else it causes spurious interrupt */ disable_idabc(dev); #endif ulpi_read(dev, 0x14);/* clear PHY interrupt latch register */ /* * Turn on PHY comparators if, * 1. USB wall charger is connected (bus suspend is not supported) * 2. Host bus suspend * 3. host is supported, but, id is not routed to pmic * 4. peripheral is supported, but, vbus is not routed to pmic */ if ((dev->otg.gadget && chg_type == <API key>) || (dev->otg.host && is_host()) || (dev->otg.host && !dev->pmic_id_notif_supp) || (dev->otg.gadget && !dev-><API key>)) { ulpi_write(dev, 0x01, 0x30); } ulpi_write(dev, 0x08, 0x09);/* turn off PLL on integrated phy */ timeout = jiffies + msecs_to_jiffies(500); disable_phy_clk(); while (!is_phy_clk_disabled()) { if (time_after(jiffies, timeout)) { pr_err("%s: Unable to suspend phy\n", __func__); /* * Start otg state machine in default state upon * phy suspend failure*/ spin_lock_irqsave(&dev->lock, flags); dev->otg.state = OTG_STATE_UNDEFINED; <API key>(&dev->lock, flags); queue_work(dev->wq, &dev->sm_work); goto out; } msleep(1); /* check if there are any pending interrupts*/ if (((readl(USB_OTGSC) & OTGSC_INTR_MASK) >> 8) & readl(USB_OTGSC)) { enable_idabc(dev); goto out; } } writel(readl(USB_USBCMD) | ASYNC_INTR_CTRL | ULPI_STP_CTRL, USB_USBCMD); if (dev->hs_pclk) clk_disable(dev->hs_pclk); if (dev->hs_cclk) clk_disable(dev->hs_cclk); /* usb phy no more require TCXO clock, hence vote for TCXO disable*/ ret = msm_xo_mode_vote(dev->xo_handle, MSM_XO_MODE_OFF); if (ret) pr_err("%s failed to devote for" "TCXO D1 buffer%d\n", __func__, ret); if (device_may_wakeup(dev->otg.dev)) { enable_irq_wake(dev->irq); if (dev->vbus_on_irq) enable_irq_wake(dev->vbus_on_irq); } <API key>(dev, 0); atomic_set(&dev->in_lpm, 1); if (!vbus && dev-><API key>) { pr_debug("phy can power collapse: (%d)\n", <API key>(dev)); if (<API key>(dev) && dev->pdata->ldo_enable) { pr_debug("disabling the regulators\n"); dev->pdata->ldo_enable(0); } } /* phy can interrupts when vddcx is at 0.75, so irrespective * of pmic notification support, configure vddcx @0.75 */ if (dev->pdata->config_vddcx) dev->pdata->config_vddcx(0); pr_info("%s: usb in low power mode\n", __func__); out: enable_irq(dev->irq); return 0; } static int msm_otg_resume(struct msm_otg *dev) { unsigned temp; unsigned ret; if (!atomic_read(&dev->in_lpm)) return 0; /* vote for vddcx, as PHY cannot tolerate vddcx below 1.0V */ if (dev->pdata->config_vddcx) { ret = dev->pdata->config_vddcx(1); if (ret) { pr_err("%s: unable to enable vddcx digital core:%d\n", __func__, ret); } } if (dev->pdata->ldo_set_voltage) dev->pdata->ldo_set_voltage(3400); /* Vote for TCXO when waking up the phy */ ret = msm_xo_mode_vote(dev->xo_handle, MSM_XO_MODE_ON); if (ret) pr_err("%s failed to vote for" "TCXO D1 buffer%d\n", __func__, ret); <API key>(dev, 1); if (dev->hs_pclk) clk_enable(dev->hs_pclk); if (dev->hs_cclk) clk_enable(dev->hs_cclk); temp = readl(USB_USBCMD); temp &= ~ASYNC_INTR_CTRL; temp &= ~ULPI_STP_CTRL; writel(temp, USB_USBCMD); if (device_may_wakeup(dev->otg.dev)) { disable_irq_wake(dev->irq); if (dev->vbus_on_irq) disable_irq_wake(dev->vbus_on_irq); } atomic_set(&dev->in_lpm, 0); pr_info("%s: usb exited from low power mode\n", __func__); return 0; } static void msm_otg_get_resume(struct msm_otg *dev) { #ifdef CONFIG_PM_RUNTIME <API key>(dev->otg.dev); pm_runtime_resume(dev->otg.dev); #else msm_otg_resume(dev); #endif } static void msm_otg_put_suspend(struct msm_otg *dev) { #ifdef CONFIG_PM_RUNTIME pm_runtime_put_sync(dev->otg.dev); #else msm_otg_suspend(dev); #endif } static void msm_otg_resume_w(struct work_struct *w) { struct msm_otg *dev = container_of(w, struct msm_otg, otg_resume_work); unsigned long timeout; msm_otg_get_resume(dev); if (!is_phy_clk_disabled()) goto phy_resumed; timeout = jiffies + usecs_to_jiffies(100); enable_phy_clk(); while (is_phy_clk_disabled()) { if (time_after(jiffies, timeout)) { pr_err("%s: Unable to wakeup phy\n", __func__); /* Reset both phy and link */ otg_reset(&dev->otg, 1); break; } udelay(10); } phy_resumed: /* Enable Idabc interrupts as these were disabled before entering LPM */ enable_idabc(dev); /* If resume signalling finishes before lpm exit, PCD is not set in * USBSTS register. Drive resume signal to the downstream device now * so that host driver can process the upcoming port change interrupt.*/ if (is_host() || test_bit(ID_A, &dev->inputs)) writel(readl(USB_PORTSC) | PORTSC_FPR, USB_PORTSC); /* Enable irq which was disabled before scheduling this work. * But don't release wake_lock, as we got async interrupt and * there will be some work pending for OTG state machine. */ enable_irq(dev->irq); } static int msm_otg_set_suspend(struct otg_transceiver *xceiv, int suspend) { struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); enum usb_otg_state state; unsigned long flags; if (!dev || (dev != the_msm_otg)) return -ENODEV; spin_lock_irqsave(&dev->lock, flags); state = dev->otg.state; <API key>(&dev->lock, flags); pr_debug("suspend request in state: %s\n", state_string(state)); if (suspend) { switch (state) { #ifndef <API key> case <API key>: msm_otg_put_suspend(dev); break; #endif case OTG_STATE_A_HOST: clear_bit(A_BUS_REQ, &dev->inputs); wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); break; case <API key>: if (xceiv->gadget->b_hnp_enable) { set_bit(A_BUS_SUSPEND, &dev->inputs); set_bit(B_BUS_REQ, &dev->inputs); wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); } break; case <API key>: msm_otg_start_timer(dev, TA_BIDL_ADIS, A_BIDL_ADIS); break; default: break; } } else { unsigned long timeout; switch (state) { case <API key>: /* A-peripheral observed activity on bus. * clear A_BIDL_ADIS timer. */ msm_otg_del_timer(dev); break; case OTG_STATE_A_SUSPEND: /* Remote wakeup or resume */ set_bit(A_BUS_REQ, &dev->inputs); spin_lock_irqsave(&dev->lock, flags); dev->otg.state = OTG_STATE_A_HOST; <API key>(&dev->lock, flags); if (test_bit(ID_A, &dev->inputs) && (get_aca_bmaxpower(dev) < USB_IDCHG_MIN)) msm_otg_set_power(xceiv, USB_IDCHG_MIN - get_aca_bmaxpower(dev)); break; default: break; } if (suspend == atomic_read(&dev->in_lpm)) return 0; disable_irq(dev->irq); if (dev-><API key>) if (<API key>(dev) && dev->pdata->ldo_enable) dev->pdata->ldo_enable(1); msm_otg_get_resume(dev); if (!is_phy_clk_disabled()) goto out; timeout = jiffies + usecs_to_jiffies(100); enable_phy_clk(); while (is_phy_clk_disabled()) { if (time_after(jiffies, timeout)) { pr_err("%s: Unable to wakeup phy\n", __func__); /* Reset both phy and link */ otg_reset(&dev->otg, 1); break; } udelay(10); } out: enable_idabc(dev); enable_irq(dev->irq); } return 0; } static int <API key>(struct otg_transceiver *xceiv, struct usb_gadget *gadget) { struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); if (!dev || (dev != the_msm_otg)) return -ENODEV; if (!gadget) { <API key>(xceiv, 0); dev->otg.gadget = 0; disable_sess_valid(dev); if (!dev->otg.host) disable_idabc(dev); return 0; } dev->otg.gadget = gadget; pr_info("peripheral driver registered w/ tranceiver\n"); wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); return 0; } #ifdef CONFIG_USB_EHCI_MSM static int usbdev_notify(struct notifier_block *self, unsigned long action, void *device) { enum usb_otg_state state; struct msm_otg *dev = container_of(self, struct msm_otg, usbdev_nb); struct usb_device *udev = device; int work = 1; /* Interested in only devices directly connected * to root hub directly. */ if (!udev->parent || udev->parent->parent) goto out; spin_lock_irq(&dev->lock); state = dev->otg.state; spin_unlock_irq(&dev->lock); switch (state) { case <API key>: if (action == USB_DEVICE_ADD) { pr_debug("B_CONN set\n"); set_bit(B_CONN, &dev->inputs); if (udev->actconfig) { set_aca_bmaxpower(dev, udev->actconfig->desc.bMaxPower * 2); goto do_work; } if (udev->portnum == udev->bus->otg_port) set_aca_bmaxpower(dev, USB_IB_UNCFG); else set_aca_bmaxpower(dev, 100); } break; case OTG_STATE_A_HOST: if (action == USB_DEVICE_REMOVE) { pr_debug("B_CONN clear\n"); clear_bit(B_CONN, &dev->inputs); set_aca_bmaxpower(dev, 0); } break; default: work = 0; break; } do_work: if (work) { wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); } out: return NOTIFY_OK; } static int msm_otg_set_host(struct otg_transceiver *xceiv, struct usb_bus *host) { struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); if (!dev || (dev != the_msm_otg)) return -ENODEV; if (!dev->start_host) return -ENODEV; if (!host) { msm_otg_start_host(xceiv, REQUEST_STOP); <API key>(&dev->usbdev_nb); dev->otg.host = 0; dev->start_host = 0; disable_idgnd(dev); if (!dev->otg.gadget) disable_idabc(dev); return 0; } #ifdef CONFIG_USB_OTG host->otg_port = 1; #endif dev->usbdev_nb.notifier_call = usbdev_notify; usb_register_notify(&dev->usbdev_nb); dev->otg.host = host; pr_info("host driver registered w/ tranceiver\n"); #ifndef CONFIG_USB_MSM_72K wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); #endif return 0; } #endif void <API key>(int id) { struct msm_otg *dev = the_msm_otg; if (id == dev->pmic_id_status) return; wake_lock(&dev->wlock); if (id) { set_bit(ID, &dev->inputs); dev->pmic_id_status = 1; } else { clear_bit(ID, &dev->inputs); set_bit(A_BUS_REQ, &dev->inputs); dev->pmic_id_status = 0; } queue_work(dev->wq, &dev->sm_work); } void <API key>(int online) { struct msm_otg *dev = the_msm_otg; if (!atomic_read(&dev->in_lpm) || !online) return; wake_lock(&dev->wlock); set_bit(B_SESS_VLD, &dev->inputs); queue_work(dev->wq, &dev->sm_work); } static irqreturn_t msm_otg_irq(int irq, void *data) { struct msm_otg *dev = data; u32 otgsc, sts, pc, sts_mask; irqreturn_t ret = IRQ_HANDLED; int work = 0; enum usb_otg_state state; if (atomic_read(&dev->in_lpm)) { disable_irq_nosync(dev->irq); wake_lock(&dev->wlock); queue_work(dev->wq, &dev->otg_resume_work); goto out; } /* Return immediately if instead of ID pin, USER controls mode switch */ if (dev->pdata->otg_mode == OTG_USER_CONTROL) return IRQ_NONE; otgsc = readl(USB_OTGSC); sts = readl(USB_USBSTS); sts_mask = (otgsc & OTGSC_INTR_MASK) >> 8; if (!((otgsc & sts_mask) || (sts & STS_PCI))) { ret = IRQ_NONE; goto out; } spin_lock(&dev->lock); state = dev->otg.state; spin_unlock(&dev->lock); pr_debug("IRQ state: %s\n", state_string(state)); pr_debug("otgsc = %x\n", otgsc); if ((otgsc & OTGSC_IDIE) && (otgsc & OTGSC_IDIS)) { if (otgsc & OTGSC_ID) { pr_debug("Id set\n"); set_bit(ID, &dev->inputs); } else { pr_debug("Id clear\n"); /* Assert a_bus_req to supply power on * VBUS when Micro/Mini-A cable is connected * with out user intervention. */ set_bit(A_BUS_REQ, &dev->inputs); clear_bit(ID, &dev->inputs); } writel(otgsc, USB_OTGSC); work = 1; } else if (otgsc & OTGSC_BSVIS) { writel(otgsc, USB_OTGSC); /* BSV interrupt comes when operating as an A-device * (VBUS on/off). * But, handle BSV when charger is removed from ACA in ID_A */ if ((state >= OTG_STATE_A_IDLE) && !test_bit(ID_A, &dev->inputs)) goto out; if (otgsc & OTGSC_BSV) { pr_debug("BSV set\n"); set_bit(B_SESS_VLD, &dev->inputs); } else { pr_debug("BSV clear\n"); clear_bit(B_SESS_VLD, &dev->inputs); } work = 1; } else if (otgsc & OTGSC_DPIS) { pr_debug("DPIS detected\n"); writel(otgsc, USB_OTGSC); set_bit(A_SRP_DET, &dev->inputs); set_bit(A_BUS_REQ, &dev->inputs); work = 1; } else if (sts & STS_PCI) { pc = readl(USB_PORTSC); pr_debug("portsc = %x\n", pc); ret = IRQ_NONE; /* HCD Acks PCI interrupt. We use this to switch * between different OTG states. */ work = 1; switch (state) { case OTG_STATE_A_SUSPEND: if (dev->otg.host->b_hnp_enable && (pc & PORTSC_CSC) && !(pc & PORTSC_CCS)) { pr_debug("B_CONN clear\n"); clear_bit(B_CONN, &dev->inputs); } break; case <API key>: if ((pc & PORTSC_CSC) && (pc & PORTSC_CCS)) { pr_debug("A_CONN set\n"); set_bit(A_CONN, &dev->inputs); /* Clear ASE0_BRST timer */ msm_otg_del_timer(dev); } break; case OTG_STATE_B_HOST: if ((pc & PORTSC_CSC) && !(pc & PORTSC_CCS)) { pr_debug("A_CONN clear\n"); clear_bit(A_CONN, &dev->inputs); } break; default: work = 0; break; } } if (work) { #ifdef CONFIG_USB_MSM_ACA /* With ACA, ID can change bcoz of BSVIS as well, so update */ if ((otgsc & OTGSC_IDIS) || (otgsc & OTGSC_BSVIS)) set_aca_id_inputs(dev); #endif wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); } out: return ret; } #define <API key> 5 #define <API key> 10 static void phy_clk_reset(struct msm_otg *dev) { unsigned rc; enum clk_reset_action assert = CLK_RESET_ASSERT; if (dev->pdata-><API key>) assert = CLK_RESET_DEASSERT; rc = clk_reset(dev->phy_reset_clk, assert); if (rc) { pr_err("%s: phy clk assert failed\n", __func__); return; } msleep(1); rc = clk_reset(dev->phy_reset_clk, !assert); if (rc) { pr_err("%s: phy clk deassert failed\n", __func__); return; } msleep(1); } static unsigned <API key>(struct msm_otg *dev, unsigned reg) { int temp; unsigned res; for (temp = 0; temp < <API key>; temp++) { res = ulpi_read(dev, reg); if (res != 0xffffffff) return res; phy_clk_reset(dev); } pr_err("%s: ulpi read failed for %d times\n", __func__, <API key>); return -1; } static int <API key>(struct msm_otg *dev, unsigned val, unsigned reg) { int temp, res; for (temp = 0; temp < <API key>; temp++) { res = ulpi_write(dev, val, reg); if (!res) return 0; phy_clk_reset(dev); } pr_err("%s: ulpi write failed for %d times\n", __func__, <API key>); return -1; } /* some of the older targets does not turn off the PLL * if onclock bit is set and clocksuspendM bit is on, * hence clear them too and initiate the suspend mode * by clearing SupendM bit. */ static inline int turn_off_phy_pll(struct msm_otg *dev) { unsigned res; res = <API key>(dev, ULPI_CONFIG_REG1); if (res == 0xffffffff) return -ETIMEDOUT; res = <API key>(dev, res & ~(ULPI_ONCLOCK), ULPI_CONFIG_REG1); if (res) return -ETIMEDOUT; res = <API key>(dev, ULPI_CLOCK_SUSPENDM, ULPI_IFC_CTRL_CLR); if (res) return -ETIMEDOUT; /*Clear SuspendM bit to initiate suspend mode */ res = <API key>(dev, ULPI_SUSPENDM, ULPI_FUNC_CTRL_CLR); if (res) return -ETIMEDOUT; return res; } static inline int <API key>(struct msm_otg *dev) { unsigned res; res = <API key>(dev, ULPI_DEBUG); if (res == 0xffffffff) return -ETIMEDOUT; if (!(res & ULPI_CALIB_STS) && ULPI_CALIB_VAL(res)) return 0; return -1; } static int <API key>(struct msm_otg *dev) { int i = 0; unsigned long res; do { res = turn_off_phy_pll(dev); if (res) return -ETIMEDOUT; /* bring phy out of suspend */ phy_clk_reset(dev); res = <API key>(dev); if (!res) return res; i++; } while (i < <API key>); return res; } static int msm_otg_phy_reset(struct msm_otg *dev) { unsigned rc; unsigned temp; unsigned long timeout; rc = clk_reset(dev->hs_clk, CLK_RESET_ASSERT); if (rc) { pr_err("%s: usb hs clk assert failed\n", __func__); return -1; } phy_clk_reset(dev); rc = clk_reset(dev->hs_clk, CLK_RESET_DEASSERT); if (rc) { pr_err("%s: usb hs clk deassert failed\n", __func__); return -1; } /* select ULPI phy */ temp = (readl(USB_PORTSC) & ~PORTSC_PTS); writel(temp | PORTSC_PTS_ULPI, USB_PORTSC); rc = <API key>(dev); if (rc) return rc; /* TBD: There are two link resets. One is below and other one * is done immediately after this function. See if we can * eliminate one of these. */ writel(USBCMD_RESET, USB_USBCMD); timeout = jiffies + <API key>; do { if (time_after(jiffies, timeout)) { pr_err("msm_otg: usb link reset timeout\n"); break; } msleep(1); } while (readl(USB_USBCMD) & USBCMD_RESET); if (readl(USB_USBCMD) & USBCMD_RESET) { pr_err("%s: usb core reset failed\n", __func__); return -1; } return 0; } static void otg_reset(struct otg_transceiver *xceiv, int phy_reset) { struct msm_otg *dev = container_of(xceiv, struct msm_otg, otg); unsigned long timeout; u32 mode, work = 0; clk_enable(dev->hs_clk); if (!phy_reset) goto reset_link; if (dev->pdata->phy_reset) dev->pdata->phy_reset(dev->regs); else msm_otg_phy_reset(dev); /*disable all phy interrupts*/ ulpi_write(dev, 0xFF, 0x0F); ulpi_write(dev, 0xFF, 0x12); msleep(100); reset_link: writel(USBCMD_RESET, USB_USBCMD); timeout = jiffies + <API key>; do { if (time_after(jiffies, timeout)) { pr_err("msm_otg: usb link reset timeout\n"); break; } msleep(1); } while (readl(USB_USBCMD) & USBCMD_RESET); /* select ULPI phy */ writel(0x80000000, USB_PORTSC); <API key>(dev); set_cdr_auto_reset(dev); <API key>(dev); set_se1_gating(dev); writel(0x0, USB_AHB_BURST); writel(0x00, USB_AHB_MODE); clk_disable(dev->hs_clk); if ((xceiv->gadget && xceiv->gadget->is_a_peripheral) || test_bit(ID, &dev->inputs)) mode = USBMODE_SDIS | USBMODE_DEVICE; else mode = USBMODE_SDIS | USBMODE_HOST; writel(mode, USB_USBMODE); if (dev->otg.gadget) { enable_sess_valid(dev); /* Due to the above 100ms delay, interrupts from PHY are * sometimes missed during fast plug-in/plug-out of cable. * Check for such cases here. */ if (is_b_sess_vld() && !test_bit(B_SESS_VLD, &dev->inputs)) { pr_debug("%s: handle missing BSV event\n", __func__); set_bit(B_SESS_VLD, &dev->inputs); work = 1; } else if (!is_b_sess_vld() && test_bit(B_SESS_VLD, &dev->inputs)) { pr_debug("%s: handle missing !BSV event\n", __func__); clear_bit(B_SESS_VLD, &dev->inputs); work = 1; } } #ifdef CONFIG_USB_EHCI_MSM if (dev->otg.host && !dev->pmic_id_notif_supp) { enable_idgnd(dev); /* Handle missing ID_GND interrupts during fast PIPO */ if (is_host() && test_bit(ID, &dev->inputs)) { pr_debug("%s: handle missing ID_GND event\n", __func__); clear_bit(ID, &dev->inputs); work = 1; } else if (!is_host() && !test_bit(ID, &dev->inputs)) { pr_debug("%s: handle missing !ID_GND event\n", __func__); set_bit(ID, &dev->inputs); work = 1; } } else { disable_idgnd(dev); } #endif enable_idabc(dev); if (work) { wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); } } static void msm_otg_sm_work(struct work_struct *w) { struct msm_otg *dev = container_of(w, struct msm_otg, sm_work); enum chg_type chg_type = atomic_read(&dev->chg_type); int ret; int work = 0; enum usb_otg_state state; if (atomic_read(&dev->in_lpm)) msm_otg_set_suspend(&dev->otg, 0); spin_lock_irq(&dev->lock); state = dev->otg.state; spin_unlock_irq(&dev->lock); switch (state) { case OTG_STATE_UNDEFINED: /* Reset both phy and link */ otg_reset(&dev->otg, 1); #ifdef CONFIG_USB_MSM_ACA set_aca_id_inputs(dev); #endif if (dev->pdata->otg_mode == OTG_USER_CONTROL) { if ((dev->pdata->usb_mode == USB_PERIPHERAL_MODE) || !dev->otg.host) { set_bit(ID, &dev->inputs); set_bit(B_SESS_VLD, &dev->inputs); } } else { if (!dev->otg.host || !is_host()) set_bit(ID, &dev->inputs); if (dev->otg.gadget && is_b_sess_vld()) set_bit(B_SESS_VLD, &dev->inputs); } spin_lock_irq(&dev->lock); if ((test_bit(ID, &dev->inputs)) && !test_bit(ID_A, &dev->inputs)) { dev->otg.state = OTG_STATE_B_IDLE; } else { set_bit(A_BUS_REQ, &dev->inputs); dev->otg.state = OTG_STATE_A_IDLE; } spin_unlock_irq(&dev->lock); work = 1; break; case OTG_STATE_B_IDLE: dev->otg.default_a = 0; if (!test_bit(ID, &dev->inputs) || test_bit(ID_A, &dev->inputs)) { pr_debug("!id || id_A\n"); clear_bit(B_BUS_REQ, &dev->inputs); otg_reset(&dev->otg, 0); spin_lock_irq(&dev->lock); dev->otg.state = OTG_STATE_A_IDLE; spin_unlock_irq(&dev->lock); msm_otg_set_power(&dev->otg, 0); work = 1; } else if (test_bit(B_SESS_VLD, &dev->inputs) && !test_bit(ID_B, &dev->inputs)) { pr_debug("b_sess_vld\n"); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); msm_otg_set_power(&dev->otg, 0); <API key>(&dev->otg, 1); } else if (test_bit(B_BUS_REQ, &dev->inputs)) { pr_debug("b_sess_end && b_bus_req\n"); ret = msm_otg_start_srp(&dev->otg); if (ret < 0) { /* notify user space */ clear_bit(B_BUS_REQ, &dev->inputs); work = 1; break; } spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); msm_otg_start_timer(dev, TB_SRP_FAIL, B_SRP_FAIL); break; } else if (test_bit(ID_B, &dev->inputs)) { atomic_set(&dev->chg_type, USB_CHG_TYPE__SDP); msm_otg_set_power(&dev->otg, USB_IDCHG_MAX); } else { msm_otg_set_power(&dev->otg, 0); pr_debug("entering into lpm\n"); msm_otg_put_suspend(dev); if (dev->pdata->ldo_set_voltage) dev->pdata->ldo_set_voltage(3075); } break; case <API key>: if (!test_bit(ID, &dev->inputs) || test_bit(ID_A, &dev->inputs) || test_bit(ID_C, &dev->inputs) || (test_bit(B_SESS_VLD, &dev->inputs) && !test_bit(ID_B, &dev->inputs))) { pr_debug("!id || id_a/c || b_sess_vld+!id_b\n"); msm_otg_del_timer(dev); spin_lock_irq(&dev->lock); dev->otg.state = OTG_STATE_B_IDLE; spin_unlock_irq(&dev->lock); work = 1; } else if (test_bit(B_SRP_FAIL, &dev->tmouts)) { pr_debug("b_srp_fail\n"); /* notify user space */ msm_otg_send_event(&dev->otg, <API key>); clear_bit(B_BUS_REQ, &dev->inputs); clear_bit(B_SRP_FAIL, &dev->tmouts); spin_lock_irq(&dev->lock); dev->otg.state = OTG_STATE_B_IDLE; spin_unlock_irq(&dev->lock); dev->b_last_se0_sess = jiffies; work = 1; } break; case <API key>: if (!test_bit(ID, &dev->inputs) || test_bit(ID_A, &dev->inputs) || test_bit(ID_B, &dev->inputs) || !test_bit(B_SESS_VLD, &dev->inputs)) { pr_debug("!id || id_a/b || !b_sess_vld\n"); clear_bit(B_BUS_REQ, &dev->inputs); spin_lock_irq(&dev->lock); dev->otg.state = OTG_STATE_B_IDLE; spin_unlock_irq(&dev->lock); <API key>(&dev->otg, 0); dev->b_last_se0_sess = jiffies; /* Workaround: Reset phy after session */ otg_reset(&dev->otg, 1); /* come back later to put hardware in * lpm. This removes addition checks in * suspend routine for missing BSV */ work = 1; } else if (test_bit(B_BUS_REQ, &dev->inputs) && dev->otg.gadget->b_hnp_enable && test_bit(A_BUS_SUSPEND, &dev->inputs)) { pr_debug("b_bus_req && b_hnp_en && a_bus_suspend\n"); msm_otg_start_timer(dev, TB_ASE0_BRST, B_ASE0_BRST); <API key>(&dev->otg, 0); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); /* start HCD even before A-device enable * pull-up to meet HNP timings. */ dev->otg.host->is_b_host = 1; msm_otg_start_host(&dev->otg, REQUEST_START); } else if (test_bit(ID_C, &dev->inputs)) { atomic_set(&dev->chg_type, USB_CHG_TYPE__SDP); msm_otg_set_power(&dev->otg, USB_IDCHG_MAX); } else if (chg_type == <API key>) { #ifdef CONFIG_USB_MSM_ACA del_timer_sync(&dev->id_timer); #endif /* Workaround: Reset PHY in SE1 state */ otg_reset(&dev->otg, 1); pr_debug("entering into lpm with wall-charger\n"); msm_otg_put_suspend(dev); /* Allow idle power collapse */ <API key>(dev, 0); } break; case <API key>: if (!test_bit(ID, &dev->inputs) || test_bit(ID_A, &dev->inputs) || test_bit(ID_B, &dev->inputs) || !test_bit(B_SESS_VLD, &dev->inputs)) { pr_debug("!id || id_a/b || !b_sess_vld\n"); msm_otg_del_timer(dev); /* A-device is physically disconnected during * HNP. Remove HCD. */ msm_otg_start_host(&dev->otg, REQUEST_STOP); dev->otg.host->is_b_host = 0; clear_bit(B_BUS_REQ, &dev->inputs); clear_bit(A_BUS_SUSPEND, &dev->inputs); dev->b_last_se0_sess = jiffies; spin_lock_irq(&dev->lock); dev->otg.state = OTG_STATE_B_IDLE; spin_unlock_irq(&dev->lock); /* Workaround: Reset phy after session */ otg_reset(&dev->otg, 1); work = 1; } else if (test_bit(A_CONN, &dev->inputs)) { pr_debug("a_conn\n"); clear_bit(A_BUS_SUSPEND, &dev->inputs); spin_lock_irq(&dev->lock); dev->otg.state = OTG_STATE_B_HOST; spin_unlock_irq(&dev->lock); if (test_bit(ID_C, &dev->inputs)) { atomic_set(&dev->chg_type, USB_CHG_TYPE__SDP); msm_otg_set_power(&dev->otg, USB_IDCHG_MAX); } } else if (test_bit(B_ASE0_BRST, &dev->tmouts)) { /* TODO: A-device may send reset after * enabling HNP; a_bus_resume case is * not handled for now. */ pr_debug("b_ase0_brst_tmout\n"); msm_otg_send_event(&dev->otg, <API key>); msm_otg_start_host(&dev->otg, REQUEST_STOP); dev->otg.host->is_b_host = 0; clear_bit(B_ASE0_BRST, &dev->tmouts); clear_bit(A_BUS_SUSPEND, &dev->inputs); clear_bit(B_BUS_REQ, &dev->inputs); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); <API key>(&dev->otg, 1); } else if (test_bit(ID_C, &dev->inputs)) { atomic_set(&dev->chg_type, USB_CHG_TYPE__SDP); msm_otg_set_power(&dev->otg, USB_IDCHG_MAX); } break; case OTG_STATE_B_HOST: /* B_BUS_REQ is not exposed to user space. So * it must be A_CONN for now. */ if (!test_bit(B_BUS_REQ, &dev->inputs) || !test_bit(A_CONN, &dev->inputs)) { pr_debug("!b_bus_req || !a_conn\n"); clear_bit(A_CONN, &dev->inputs); clear_bit(B_BUS_REQ, &dev->inputs); msm_otg_start_host(&dev->otg, REQUEST_STOP); dev->otg.host->is_b_host = 0; spin_lock_irq(&dev->lock); dev->otg.state = OTG_STATE_B_IDLE; spin_unlock_irq(&dev->lock); /* Workaround: Reset phy after session */ otg_reset(&dev->otg, 1); work = 1; } else if (test_bit(ID_C, &dev->inputs)) { atomic_set(&dev->chg_type, USB_CHG_TYPE__SDP); msm_otg_set_power(&dev->otg, USB_IDCHG_MAX); } break; case OTG_STATE_A_IDLE: dev->otg.default_a = 1; if (test_bit(ID, &dev->inputs) && !test_bit(ID_A, &dev->inputs)) { pr_debug("id && !id_a\n"); dev->otg.default_a = 0; otg_reset(&dev->otg, 0); spin_lock_irq(&dev->lock); dev->otg.state = OTG_STATE_B_IDLE; spin_unlock_irq(&dev->lock); msm_otg_set_power(&dev->otg, 0); work = 1; } else if (!test_bit(A_BUS_DROP, &dev->inputs) && (test_bit(A_SRP_DET, &dev->inputs) || test_bit(A_BUS_REQ, &dev->inputs))) { pr_debug("!a_bus_drop && (a_srp_det || a_bus_req)\n"); clear_bit(A_SRP_DET, &dev->inputs); /* Disable SRP detection */ writel((readl(USB_OTGSC) & ~OTGSC_INTR_STS_MASK) & ~OTGSC_DPIE, USB_OTGSC); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); /* ACA: ID_A: Stop charging untill enumeration */ if (test_bit(ID_A, &dev->inputs)) msm_otg_set_power(&dev->otg, 0); else dev->pdata->vbus_power(USB_PHY_INTEGRATED, 1); msm_otg_start_timer(dev, TA_WAIT_VRISE, A_WAIT_VRISE); /* no need to schedule work now */ } else { pr_debug("No session requested\n"); /* A-device is not providing power on VBUS. * Enable SRP detection. */ writel((readl(USB_OTGSC) & ~OTGSC_INTR_STS_MASK) | OTGSC_DPIE, USB_OTGSC); msm_otg_put_suspend(dev); } break; case <API key>: if ((test_bit(ID, &dev->inputs) && !test_bit(ID_A, &dev->inputs)) || test_bit(A_BUS_DROP, &dev->inputs) || test_bit(A_WAIT_VRISE, &dev->tmouts)) { pr_debug("id || a_bus_drop || a_wait_vrise_tmout\n"); clear_bit(A_BUS_REQ, &dev->inputs); msm_otg_del_timer(dev); dev->pdata->vbus_power(USB_PHY_INTEGRATED, 0); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); msm_otg_start_timer(dev, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (test_bit(A_VBUS_VLD, &dev->inputs)) { pr_debug("a_vbus_vld\n"); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); if (TA_WAIT_BCON > 0) msm_otg_start_timer(dev, TA_WAIT_BCON, A_WAIT_BCON); /* Start HCD to detect peripherals. */ msm_otg_start_host(&dev->otg, REQUEST_START); } break; case <API key>: if ((test_bit(ID, &dev->inputs) && !test_bit(ID_A, &dev->inputs)) || test_bit(A_BUS_DROP, &dev->inputs) || test_bit(A_WAIT_BCON, &dev->tmouts)) { pr_debug("id_f/b/c || a_bus_drop ||" "a_wait_bcon_tmout\n"); if (test_bit(A_WAIT_BCON, &dev->tmouts)) msm_otg_send_event(&dev->otg, <API key>); msm_otg_del_timer(dev); clear_bit(A_BUS_REQ, &dev->inputs); msm_otg_start_host(&dev->otg, REQUEST_STOP); /* Reset both phy and link */ otg_reset(&dev->otg, 1); /* ACA: ID_A with NO accessory, just the A plug is * attached to ACA: Use IDCHG_MAX for charging */ if (test_bit(ID_A, &dev->inputs)) msm_otg_set_power(&dev->otg, USB_IDCHG_MAX); else dev->pdata->vbus_power(USB_PHY_INTEGRATED, 0); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); msm_otg_start_timer(dev, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (test_bit(B_CONN, &dev->inputs)) { pr_debug("b_conn\n"); msm_otg_del_timer(dev); /* HCD is added already. just move to * A_HOST state. */ spin_lock_irq(&dev->lock); dev->otg.state = OTG_STATE_A_HOST; spin_unlock_irq(&dev->lock); if (test_bit(ID_A, &dev->inputs)) { atomic_set(&dev->chg_type, USB_CHG_TYPE__SDP); msm_otg_set_power(&dev->otg, USB_IDCHG_MIN - get_aca_bmaxpower(dev)); } } else if (!test_bit(A_VBUS_VLD, &dev->inputs)) { pr_debug("!a_vbus_vld\n"); msm_otg_del_timer(dev); msm_otg_start_host(&dev->otg, REQUEST_STOP); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); /* Reset both phy and link */ otg_reset(&dev->otg, 1); } else if (test_bit(ID_A, &dev->inputs)) { dev->pdata->vbus_power(USB_PHY_INTEGRATED, 0); } else if (!test_bit(ID, &dev->inputs)) { dev->pdata->vbus_power(USB_PHY_INTEGRATED, 1); } break; case OTG_STATE_A_HOST: if ((test_bit(ID, &dev->inputs) && !test_bit(ID_A, &dev->inputs)) || test_bit(A_BUS_DROP, &dev->inputs)) { pr_debug("id_f/b/c || a_bus_drop\n"); clear_bit(B_CONN, &dev->inputs); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); msm_otg_start_host(&dev->otg, REQUEST_STOP); /* Reset both phy and link */ otg_reset(&dev->otg, 1); if (!test_bit(ID_A, &dev->inputs)) dev->pdata->vbus_power(USB_PHY_INTEGRATED, 0); msm_otg_start_timer(dev, TA_WAIT_VFALL, A_WAIT_VFALL); msm_otg_set_power(&dev->otg, 0); } else if (!test_bit(A_VBUS_VLD, &dev->inputs)) { pr_debug("!a_vbus_vld\n"); clear_bit(B_CONN, &dev->inputs); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); msm_otg_start_host(&dev->otg, REQUEST_STOP); /* Reset both phy and link */ otg_reset(&dev->otg, 1); /* no work */ } else if (!test_bit(A_BUS_REQ, &dev->inputs)) { /* a_bus_req is de-asserted when root hub is * suspended or HNP is in progress. */ pr_debug("!a_bus_req\n"); spin_lock_irq(&dev->lock); dev->otg.state = OTG_STATE_A_SUSPEND; spin_unlock_irq(&dev->lock); if (dev->otg.host->b_hnp_enable) { msm_otg_start_timer(dev, TA_AIDL_BDIS, A_AIDL_BDIS); } else { /* No HNP. Root hub suspended */ msm_otg_put_suspend(dev); } if (test_bit(ID_A, &dev->inputs)) msm_otg_set_power(&dev->otg, USB_IDCHG_MIN - USB_IB_UNCFG); } else if (!test_bit(B_CONN, &dev->inputs)) { pr_debug("!b_conn\n"); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); if (TA_WAIT_BCON > 0) msm_otg_start_timer(dev, TA_WAIT_BCON, A_WAIT_BCON); } else if (test_bit(ID_A, &dev->inputs)) { dev->pdata->vbus_power(USB_PHY_INTEGRATED, 0); msm_otg_set_power(&dev->otg, USB_IDCHG_MIN - get_aca_bmaxpower(dev)); } else if (!test_bit(ID, &dev->inputs)) { atomic_set(&dev->chg_type, <API key>); msm_otg_set_power(&dev->otg, 0); dev->pdata->vbus_power(USB_PHY_INTEGRATED, 1); } break; case OTG_STATE_A_SUSPEND: if ((test_bit(ID, &dev->inputs) && !test_bit(ID_A, &dev->inputs)) || test_bit(A_BUS_DROP, &dev->inputs) || test_bit(A_AIDL_BDIS, &dev->tmouts)) { pr_debug("id_f/b/c || a_bus_drop ||" "a_aidl_bdis_tmout\n"); if (test_bit(A_AIDL_BDIS, &dev->tmouts)) msm_otg_send_event(&dev->otg, <API key>); msm_otg_del_timer(dev); clear_bit(B_CONN, &dev->inputs); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); msm_otg_start_host(&dev->otg, REQUEST_STOP); dev->pdata->vbus_power(USB_PHY_INTEGRATED, 0); /* Reset both phy and link */ otg_reset(&dev->otg, 1); if (!test_bit(ID_A, &dev->inputs)) dev->pdata->vbus_power(USB_PHY_INTEGRATED, 0); msm_otg_start_timer(dev, TA_WAIT_VFALL, A_WAIT_VFALL); msm_otg_set_power(&dev->otg, 0); } else if (!test_bit(A_VBUS_VLD, &dev->inputs)) { pr_debug("!a_vbus_vld\n"); msm_otg_del_timer(dev); clear_bit(B_CONN, &dev->inputs); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); msm_otg_start_host(&dev->otg, REQUEST_STOP); /* Reset both phy and link */ otg_reset(&dev->otg, 1); } else if (!test_bit(B_CONN, &dev->inputs) && dev->otg.host->b_hnp_enable) { pr_debug("!b_conn && b_hnp_enable"); /* Clear AIDL_BDIS timer */ msm_otg_del_timer(dev); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); msm_otg_start_host(&dev->otg, REQUEST_HNP_SUSPEND); /* We may come here even when B-dev is physically * disconnected during HNP. We go back to host * role if bus is idle for BIDL_ADIS time. */ dev->otg.gadget->is_a_peripheral = 1; <API key>(&dev->otg, 1); /* If ID_A: we can charge in a_peripheral as well */ if (test_bit(ID_A, &dev->inputs)) { atomic_set(&dev->chg_type, USB_CHG_TYPE__SDP); msm_otg_set_power(&dev->otg, USB_IDCHG_MIN - USB_IB_UNCFG); } } else if (!test_bit(B_CONN, &dev->inputs) && !dev->otg.host->b_hnp_enable) { pr_debug("!b_conn && !b_hnp_enable"); /* bus request is dropped during suspend. * acquire again for next device. */ set_bit(A_BUS_REQ, &dev->inputs); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); if (TA_WAIT_BCON > 0) msm_otg_start_timer(dev, TA_WAIT_BCON, A_WAIT_BCON); msm_otg_set_power(&dev->otg, 0); } else if (test_bit(ID_A, &dev->inputs)) { dev->pdata->vbus_power(USB_PHY_INTEGRATED, 0); atomic_set(&dev->chg_type, USB_CHG_TYPE__SDP); msm_otg_set_power(&dev->otg, USB_IDCHG_MIN - USB_IB_UNCFG); } else if (!test_bit(ID, &dev->inputs)) { msm_otg_set_power(&dev->otg, 0); dev->pdata->vbus_power(USB_PHY_INTEGRATED, 1); } break; case <API key>: if ((test_bit(ID, &dev->inputs) && !test_bit(ID_A, &dev->inputs)) || test_bit(A_BUS_DROP, &dev->inputs)) { pr_debug("id _f/b/c || a_bus_drop\n"); /* Clear BIDL_ADIS timer */ msm_otg_del_timer(dev); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); <API key>(&dev->otg, 0); dev->otg.gadget->is_a_peripheral = 0; /* HCD was suspended before. Stop it now */ msm_otg_start_host(&dev->otg, REQUEST_STOP); /* Reset both phy and link */ otg_reset(&dev->otg, 1); if (!test_bit(ID_A, &dev->inputs)) dev->pdata->vbus_power(USB_PHY_INTEGRATED, 0); msm_otg_start_timer(dev, TA_WAIT_VFALL, A_WAIT_VFALL); msm_otg_set_power(&dev->otg, 0); } else if (!test_bit(A_VBUS_VLD, &dev->inputs)) { pr_debug("!a_vbus_vld\n"); /* Clear BIDL_ADIS timer */ msm_otg_del_timer(dev); spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); <API key>(&dev->otg, 0); dev->otg.gadget->is_a_peripheral = 0; /* HCD was suspended before. Stop it now */ msm_otg_start_host(&dev->otg, REQUEST_STOP); } else if (test_bit(A_BIDL_ADIS, &dev->tmouts)) { pr_debug("a_bidl_adis_tmout\n"); <API key>(&dev->otg, 0); dev->otg.gadget->is_a_peripheral = 0; spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); set_bit(A_BUS_REQ, &dev->inputs); msm_otg_start_host(&dev->otg, REQUEST_HNP_RESUME); if (TA_WAIT_BCON > 0) msm_otg_start_timer(dev, TA_WAIT_BCON, A_WAIT_BCON); msm_otg_set_power(&dev->otg, 0); } else if (test_bit(ID_A, &dev->inputs)) { dev->pdata->vbus_power(USB_PHY_INTEGRATED, 0); atomic_set(&dev->chg_type, USB_CHG_TYPE__SDP); msm_otg_set_power(&dev->otg, USB_IDCHG_MIN - USB_IB_UNCFG); } else if (!test_bit(ID, &dev->inputs)) { msm_otg_set_power(&dev->otg, 0); dev->pdata->vbus_power(USB_PHY_INTEGRATED, 1); } break; case <API key>: if (test_bit(A_WAIT_VFALL, &dev->tmouts)) { clear_bit(A_VBUS_VLD, &dev->inputs); spin_lock_irq(&dev->lock); dev->otg.state = OTG_STATE_A_IDLE; spin_unlock_irq(&dev->lock); work = 1; } break; case <API key>: if ((test_bit(ID, &dev->inputs) && !test_bit(ID_A, &dev->inputs)) || test_bit(A_BUS_DROP, &dev->inputs) || test_bit(A_CLR_ERR, &dev->inputs)) { spin_lock_irq(&dev->lock); dev->otg.state = <API key>; spin_unlock_irq(&dev->lock); if (!test_bit(ID_A, &dev->inputs)) dev->pdata->vbus_power(USB_PHY_INTEGRATED, 0); msm_otg_start_timer(dev, TA_WAIT_VFALL, A_WAIT_VFALL); msm_otg_set_power(&dev->otg, 0); } break; default: pr_err("invalid OTG state\n"); } if (work) queue_work(dev->wq, &dev->sm_work); #ifdef CONFIG_USB_MSM_ACA /* Start id_polling if (ID_FLOAT&BSV) || ID_A/B/C */ if ((test_bit(ID, &dev->inputs) && test_bit(B_SESS_VLD, &dev->inputs) && chg_type != <API key>) || test_bit(ID_A, &dev->inputs)) { mod_timer(&dev->id_timer, jiffies + msecs_to_jiffies(OTG_ID_POLL_MS)); return; } del_timer(&dev->id_timer); #endif /* IRQ/sysfs may queue work. Check work_pending. otherwise * we might endup releasing wakelock after it is acquired * in IRQ/sysfs. */ if (!work_pending(&dev->sm_work) && !hrtimer_active(&dev->timer) && !work_pending(&dev->otg_resume_work)) wake_unlock(&dev->wlock); } #ifdef CONFIG_USB_MSM_ACA static void msm_otg_id_func(unsigned long _dev) { struct msm_otg *dev = (struct msm_otg *) _dev; u8 phy_ints; if (atomic_read(&dev->in_lpm)) msm_otg_set_suspend(&dev->otg, 0); phy_ints = ulpi_read(dev, 0x13); /* If id_gnd happened then stop and let isr take care of this */ if (phy_id_state_gnd(phy_ints)) goto out; if ((test_bit(ID_A, &dev->inputs) == phy_id_state_a(phy_ints)) && (test_bit(ID_B, &dev->inputs) == phy_id_state_b(phy_ints)) && (test_bit(ID_C, &dev->inputs) == phy_id_state_c(phy_ints))) { mod_timer(&dev->id_timer, jiffies + msecs_to_jiffies(OTG_ID_POLL_MS)); goto out; } else { set_aca_id_inputs(dev); } wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); out: return; } #endif #ifdef CONFIG_USB_OTG static ssize_t set_pwr_down(struct device *_dev, struct device_attribute *attr, const char *buf, size_t count) { struct msm_otg *dev = the_msm_otg; int value; enum usb_otg_state state; spin_lock_irq(&dev->lock); state = dev->otg.state; spin_unlock_irq(&dev->lock); /* Applicable for only A-Device */ if (state <= OTG_STATE_A_IDLE) return -EINVAL; sscanf(buf, "%d", &value); if (test_bit(A_BUS_DROP, &dev->inputs) != !!value) { change_bit(A_BUS_DROP, &dev->inputs); wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); } return count; } static DEVICE_ATTR(pwr_down, S_IRUGO | S_IWUSR, NULL, set_pwr_down); static ssize_t set_srp_req(struct device *_dev, struct device_attribute *attr, const char *buf, size_t count) { struct msm_otg *dev = the_msm_otg; enum usb_otg_state state; spin_lock_irq(&dev->lock); state = dev->otg.state; spin_unlock_irq(&dev->lock); if (state != OTG_STATE_B_IDLE) return -EINVAL; set_bit(B_BUS_REQ, &dev->inputs); wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); return count; } static DEVICE_ATTR(srp_req, S_IRUGO | S_IWUSR, NULL, set_srp_req); static ssize_t set_clr_err(struct device *_dev, struct device_attribute *attr, const char *buf, size_t count) { struct msm_otg *dev = the_msm_otg; enum usb_otg_state state; spin_lock_irq(&dev->lock); state = dev->otg.state; spin_unlock_irq(&dev->lock); if (state == <API key>) { set_bit(A_CLR_ERR, &dev->inputs); wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); } return count; } static DEVICE_ATTR(clr_err, S_IRUGO | S_IWUSR, NULL, set_clr_err); static struct attribute *msm_otg_attrs[] = { &dev_attr_pwr_down.attr, &dev_attr_srp_req.attr, &dev_attr_clr_err.attr, NULL, }; static struct attribute_group msm_otg_attr_grp = { .attrs = msm_otg_attrs, }; #endif #ifdef CONFIG_DEBUG_FS static int otg_open(struct inode *inode, struct file *file) { file->private_data = inode->i_private; return 0; } static ssize_t otg_mode_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct msm_otg *dev = file->private_data; int ret = count; int work = 0; unsigned long flags; spin_lock_irqsave(&dev->lock, flags); if (!memcmp(buf, "none", count - 1)) { clear_bit(B_SESS_VLD, &dev->inputs); set_bit(ID, &dev->inputs); work = 1; } else if (!memcmp(buf, "peripheral", count - 1)) { set_bit(B_SESS_VLD, &dev->inputs); set_bit(ID, &dev->inputs); work = 1; } else if (!memcmp(buf, "host", count - 1)) { clear_bit(B_SESS_VLD, &dev->inputs); clear_bit(ID, &dev->inputs); set_bit(A_BUS_REQ, &dev->inputs); work = 1; } else { pr_info("%s: unknown mode specified\n", __func__); ret = -EINVAL; } <API key>(&dev->lock, flags); if (work) { wake_lock(&dev->wlock); queue_work(dev->wq, &dev->sm_work); } return ret; } const struct file_operations otgfs_fops = { .open = otg_open, .write = otg_mode_write, }; struct dentry *otg_debug_root; struct dentry *otg_debug_mode; #endif static int otg_debugfs_init(struct msm_otg *dev) { #ifdef CONFIG_DEBUG_FS otg_debug_root = debugfs_create_dir("otg", NULL); if (!otg_debug_root) return -ENOENT; otg_debug_mode = debugfs_create_file("mode", 0222, otg_debug_root, dev, &otgfs_fops); if (!otg_debug_mode) { debugfs_remove(otg_debug_root); otg_debug_root = NULL; return -ENOENT; } #endif return 0; } static void otg_debugfs_cleanup(void) { #ifdef CONFIG_DEBUG_FS debugfs_remove(otg_debug_mode); debugfs_remove(otg_debug_root); #endif } struct otg_io_access_ops msm_otg_io_ops = { .read = usb_ulpi_read, .write = usb_ulpi_write, }; static int __init msm_otg_probe(struct platform_device *pdev) { int ret = 0; struct resource *res; struct msm_otg *dev; dev = kzalloc(sizeof(struct msm_otg), GFP_KERNEL); if (!dev) return -ENOMEM; dev->otg.dev = &pdev->dev; dev->pdata = pdev->dev.platform_data; if (!dev->pdata) { ret = -ENODEV; goto free_dev; } #ifdef CONFIG_USB_EHCI_MSM if (!dev->pdata->vbus_power) { ret = -ENODEV; goto free_dev; } #endif if (dev->pdata->rpc_connect) { ret = dev->pdata->rpc_connect(1); pr_debug("%s: rpc_connect(%d)\n", __func__, ret); if (ret) { pr_err("%s: rpc connect failed\n", __func__); ret = -ENODEV; goto free_dev; } } dev->hs_clk = clk_get(&pdev->dev, "usb_hs_clk"); if (IS_ERR(dev->hs_clk)) { pr_err("%s: failed to get usb_hs_clk\n", __func__); ret = PTR_ERR(dev->hs_clk); goto rpc_fail; } clk_set_rate(dev->hs_clk, 60000000); if (dev->pdata->usb_in_sps) { dev->dfab_clk = clk_get(0, "dfab_clk"); if (IS_ERR(dev->dfab_clk)) { pr_err("%s: failed to get dfab clk\n", __func__); ret = PTR_ERR(dev->dfab_clk); goto put_hs_clk; } } /* If USB Core is running its protocol engine based on PCLK, * PCLK must be running at >60Mhz for correct HSUSB operation and * USB core cannot tolerate frequency changes on PCLK. For such * USB cores, vote for maximum clk frequency on pclk source */ dev->pdata->pm_qos_req_dma = pm_qos_add_request(<API key>, <API key>); if (<API key>(&dev->otg) && !dev->pdata->usb_in_sps) { dev->pdata->ebi1_clk = clk_get(NULL, "ebi1_usb_clk"); if (IS_ERR(dev->pdata->ebi1_clk)) { ret = PTR_ERR(dev->pdata->ebi1_clk); goto put_dfab_clk; } clk_set_rate(dev->pdata->ebi1_clk, INT_MAX); <API key>(dev, 1); } if (!dev->pdata->pclk_is_hw_gated) { dev->hs_pclk = clk_get(&pdev->dev, "usb_hs_pclk"); if (IS_ERR(dev->hs_pclk)) { pr_err("%s: failed to get usb_hs_pclk\n", __func__); ret = PTR_ERR(dev->hs_pclk); goto put_ebi_clk; } clk_enable(dev->hs_pclk); } if (dev->pdata->core_clk) { dev->hs_cclk = clk_get(&pdev->dev, "usb_hs_core_clk"); if (IS_ERR(dev->hs_cclk)) { pr_err("%s: failed to get usb_hs_core_clk\n", __func__); ret = PTR_ERR(dev->hs_cclk); goto put_hs_pclk; } clk_enable(dev->hs_cclk); } if (!dev->pdata->phy_reset) { dev->phy_reset_clk = clk_get(&pdev->dev, "usb_phy_clk"); if (IS_ERR(dev->phy_reset_clk)) { pr_err("%s: failed to get usb_phy_clk\n", __func__); ret = PTR_ERR(dev->phy_reset_clk); goto put_hs_cclk; } } res = <API key>(pdev, IORESOURCE_MEM, 0); if (!res) { pr_err("%s: failed to get platform resource mem\n", __func__); ret = -ENODEV; goto put_phy_clk; } dev->regs = ioremap(res->start, resource_size(res)); if (!dev->regs) { pr_err("%s: ioremap failed\n", __func__); ret = -ENOMEM; goto put_phy_clk; } dev->irq = platform_get_irq(pdev, 0); if (!dev->irq) { pr_err("%s: platform_get_irq failed\n", __func__); ret = -ENODEV; goto free_regs; } dev->xo_handle = msm_xo_get(MSM_XO_TCXO_D1, "usb"); if (IS_ERR(dev->xo_handle)) { pr_err(" %s not able to get the handle" "to vote for TCXO D1 buffer\n", __func__); ret = PTR_ERR(dev->xo_handle); goto free_regs; } ret = msm_xo_mode_vote(dev->xo_handle, MSM_XO_MODE_ON); if (ret) { pr_err("%s failed to vote for TCXO" "D1 buffer%d\n", __func__, ret); goto free_xo_handle; } msm_otg_init_timer(dev); INIT_WORK(&dev->sm_work, msm_otg_sm_work); INIT_WORK(&dev->otg_resume_work, msm_otg_resume_w); spin_lock_init(&dev->lock); wake_lock_init(&dev->wlock, WAKE_LOCK_SUSPEND, "msm_otg"); dev->wq = <API key>("k_otg"); if (!dev->wq) { ret = -ENOMEM; goto free_wlock; } if (dev->pdata->init_gpio) { ret = dev->pdata->init_gpio(1); if (ret) { pr_err("%s: gpio init failed with err:%d\n", __func__, ret); goto free_wq; } } /* To reduce phy power consumption and to avoid external LDO * on the board, PMIC comparators can be used to detect VBUS * session change. */ if (dev->pdata-><API key>) { ret = dev->pdata-><API key> (&<API key>, 1); if (!ret) { dev-><API key> = 1; } else if (ret != -ENOTSUPP) { pr_err("%s: <API key>() failed, err:%d\n", __func__, ret); goto free_gpio; } } if (dev->pdata->pmic_id_notif_init) { ret = dev->pdata->pmic_id_notif_init(&<API key>, 1); if (!ret) { dev->pmic_id_notif_supp = 1; /* * As a part of usb initialization checks the id * by that time if pmic doesn't generate ID interrupt, * then it assumes that micro-A cable is connected * (as default pmic_id_status is 0, which indicates * as micro-A cable) and moving to Host mode and * ignoring the BSession Valid interrupts. * For now assigning default id_status as 1 * (which indicates as micro-B) */ dev->pmic_id_status = 1; } else if (ret != -ENOTSUPP) { pr_err("%s: pmic_id_ notif_init failed err:%d", __func__, ret); goto <API key>; } } if (dev->pdata->pmic_vbus_irq) dev->vbus_on_irq = dev->pdata->pmic_vbus_irq; /* vote for vddcx, as PHY cannot tolerate vddcx below 1.0V */ if (dev->pdata->init_vddcx) { ret = dev->pdata->init_vddcx(1); if (ret) { pr_err("%s: unable to enable vddcx digital core:%d\n", __func__, ret); goto free_pmic_id_notif; } } if (dev->pdata->ldo_init) { ret = dev->pdata->ldo_init(1); if (ret) { pr_err("%s: ldo_init failed with err:%d\n", __func__, ret); goto free_config_vddcx; } } if (dev->pdata->ldo_enable) { ret = dev->pdata->ldo_enable(1); if (ret) { pr_err("%s: ldo_enable failed with err:%d\n", __func__, ret); goto free_ldo_init; } } /* ACk all pending interrupts and clear interrupt enable registers */ writel((readl(USB_OTGSC) & ~OTGSC_INTR_MASK), USB_OTGSC); writel(readl(USB_USBSTS), USB_USBSTS); writel(0, USB_USBINTR); ret = request_irq(dev->irq, msm_otg_irq, IRQF_SHARED, "msm_otg", dev); if (ret) { pr_err("%s: request irq failed\n", __func__); goto free_ldo_enable; } the_msm_otg = dev; dev->otg.set_peripheral = <API key>; #ifdef CONFIG_USB_EHCI_MSM dev->otg.set_host = msm_otg_set_host; #endif dev->otg.set_suspend = msm_otg_set_suspend; dev->otg.start_hnp = msm_otg_start_hnp; dev->otg.send_event = msm_otg_send_event; dev->otg.set_power = msm_otg_set_power; dev->set_clk = msm_otg_set_clk; dev->reset = otg_reset; dev->otg.io_ops = &msm_otg_io_ops; if (otg_set_transceiver(&dev->otg)) { WARN_ON(1); goto free_otg_irq; } #ifdef CONFIG_USB_MSM_ACA /* Link doesnt support id_a/b/c interrupts, hence polling * needs to be done to support ACA charger */ init_timer(&dev->id_timer); dev->id_timer.function = msm_otg_id_func; dev->id_timer.data = (unsigned long) dev; #endif atomic_set(&dev->chg_type, <API key>); if (dev->pdata->chg_init && dev->pdata->chg_init(1)) pr_err("%s: chg_init failed\n", __func__); device_init_wakeup(&pdev->dev, 1); ret = <API key>(&pdev->dev); if (ret < 0) pr_err("%s: pm_runtime: Fail to set active\n", __func__); ret = 0; pm_runtime_enable(&pdev->dev); pm_runtime_get(&pdev->dev); ret = otg_debugfs_init(dev); if (ret) { pr_err("%s: otg_debugfs_init failed\n", __func__); goto chg_deinit; } #ifdef CONFIG_USB_OTG ret = sysfs_create_group(&pdev->dev.kobj, &msm_otg_attr_grp); if (ret < 0) { pr_err("%s: Failed to create the sysfs entry\n", __func__); otg_debugfs_cleanup(); goto chg_deinit; } #endif return 0; chg_deinit: if (dev->pdata->chg_init) dev->pdata->chg_init(0); free_otg_irq: free_irq(dev->irq, dev); free_ldo_enable: if (dev->pdata->ldo_enable) dev->pdata->ldo_enable(0); if (dev->pdata->setup_gpio) dev->pdata->setup_gpio(USB_SWITCH_DISABLE); free_ldo_init: if (dev->pdata->ldo_init) dev->pdata->ldo_init(0); free_config_vddcx: if (dev->pdata->init_vddcx) dev->pdata->init_vddcx(0); free_pmic_id_notif: if (dev->pdata->pmic_id_notif_init && dev->pmic_id_notif_supp) dev->pdata->pmic_id_notif_init(&<API key>, 0); <API key>: if (dev->pdata-><API key> && dev-><API key>) dev->pdata-><API key>(&<API key>, 0); free_gpio: if (dev->pdata->init_gpio) dev->pdata->init_gpio(0); free_wq: destroy_workqueue(dev->wq); free_wlock: wake_lock_destroy(&dev->wlock); free_xo_handle: msm_xo_put(dev->xo_handle); free_regs: iounmap(dev->regs); put_phy_clk: if (dev->phy_reset_clk) clk_put(dev->phy_reset_clk); put_hs_cclk: if (dev->hs_cclk) { clk_disable(dev->hs_cclk); clk_put(dev->hs_cclk); } put_hs_pclk: if (dev->hs_pclk) { clk_disable(dev->hs_pclk); clk_put(dev->hs_pclk); } put_ebi_clk: clk_put(dev->pdata->ebi1_clk); put_dfab_clk: if (dev->dfab_clk) { clk_set_min_rate(dev->dfab_clk, 0); clk_put(dev->dfab_clk); } put_hs_clk: if (dev->hs_clk) clk_put(dev->hs_clk); rpc_fail: if (dev->pdata->rpc_connect) dev->pdata->rpc_connect(0); free_dev: kfree(dev); return ret; } static int __exit msm_otg_remove(struct platform_device *pdev) { struct msm_otg *dev = the_msm_otg; otg_debugfs_cleanup(); #ifdef CONFIG_USB_OTG sysfs_remove_group(&pdev->dev.kobj, &msm_otg_attr_grp); #endif destroy_workqueue(dev->wq); wake_lock_destroy(&dev->wlock); if (dev->pdata->setup_gpio) dev->pdata->setup_gpio(USB_SWITCH_DISABLE); if (dev->pdata->init_vddcx) dev->pdata->init_vddcx(0); if (dev->pdata->ldo_enable) dev->pdata->ldo_enable(0); if (dev->pdata->ldo_init) dev->pdata->ldo_init(0); if (dev-><API key>) dev->pdata-><API key>(&<API key>, 0); if (dev->pmic_id_notif_supp) dev->pdata->pmic_id_notif_init(&<API key>, 0); #ifdef CONFIG_USB_MSM_ACA del_timer_sync(&dev->id_timer); #endif if (dev->pdata->chg_init) dev->pdata->chg_init(0); free_irq(dev->irq, pdev); iounmap(dev->regs); if (dev->hs_cclk) { clk_disable(dev->hs_cclk); clk_put(dev->hs_cclk); } if (dev->hs_pclk) { clk_disable(dev->hs_pclk); clk_put(dev->hs_pclk); } if (dev->hs_clk) clk_put(dev->hs_clk); if (dev->phy_reset_clk) clk_put(dev->phy_reset_clk); if (dev->pdata->rpc_connect) dev->pdata->rpc_connect(0); msm_xo_put(dev->xo_handle); pm_runtime_put(&pdev->dev); pm_runtime_disable(&pdev->dev); kfree(dev); <API key>(dev->pdata->pm_qos_req_dma); clk_put(dev->pdata->ebi1_clk); return 0; } static int <API key>(struct device *dev) { struct msm_otg *otg = the_msm_otg; dev_dbg(dev, "pm_runtime: suspending...\n"); msm_otg_suspend(otg); return 0; } static int <API key>(struct device *dev) { struct msm_otg *otg = the_msm_otg; dev_dbg(dev, "pm_runtime: resuming...\n"); msm_otg_resume(otg); return 0; } static int <API key>(struct device *dev) { dev_dbg(dev, "pm_runtime: idling...\n"); return 0; } static struct dev_pm_ops msm_otg_dev_pm_ops = { .runtime_suspend = <API key>, .runtime_resume = <API key>, .runtime_idle = <API key>, }; static struct platform_driver msm_otg_driver = { .remove = __exit_p(msm_otg_remove), .driver = { .name = DRIVER_NAME, .owner = THIS_MODULE, .pm = &msm_otg_dev_pm_ops, }, }; static int __init msm_otg_init(void) { return <API key>(&msm_otg_driver, msm_otg_probe); } static void __exit msm_otg_exit(void) { <API key>(&msm_otg_driver); } module_init(msm_otg_init); module_exit(msm_otg_exit); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("MSM usb transceiver driver"); MODULE_VERSION("1.00");
/* ScriptData SDName: <API key> SD%Complete: 50 SDComment: SDCategory: Hellfire Ramparts EndScriptData */ #include "precompiled.h" #include "hellfire_ramparts.h" instance_ramparts::instance_ramparts(Map* pMap) : ScriptedInstance(pMap), m_uiSentryCounter(0) { Initialize(); } void instance_ramparts::Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); } void instance_ramparts::OnCreatureCreate(Creature* pCreature) { switch (pCreature->GetEntry()) { case NPC_VAZRUDEN_HERALD: case NPC_VAZRUDEN: <API key>[pCreature->GetEntry()] = pCreature->GetObjectGuid(); break; case NPC_HELLFIRE_SENTRY: m_lSentryGUIDs.push_back(pCreature->GetObjectGuid()); break; } } void instance_ramparts::OnObjectCreate(GameObject* pGo) { switch (pGo->GetEntry()) { case GO_FEL_IRON_CHEST: case GO_FEL_IRON_CHEST_H: m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid(); break; } } void instance_ramparts::SetData(uint32 uiType, uint32 uiData) { debug_log("SD2: Instance Ramparts: SetData received for type %u with data %u",uiType,uiData); switch (uiType) { case TYPE_VAZRUDEN: if (uiData == DONE && m_auiEncounter[1] == DONE) DoRespawnGameObject(instance->IsRegularDifficulty() ? GO_FEL_IRON_CHEST : GO_FEL_IRON_CHEST_H, HOUR); if (uiData == FAIL && m_auiEncounter[0] != FAIL) DoFailVazruden(); m_auiEncounter[0] = uiData; break; case TYPE_NAZAN: if (uiData == SPECIAL) { ++m_uiSentryCounter; if (m_uiSentryCounter == 2) m_auiEncounter[1] = uiData; return; } if (uiData == DONE && m_auiEncounter[0] == DONE) { DoRespawnGameObject(instance->IsRegularDifficulty() ? GO_FEL_IRON_CHEST : GO_FEL_IRON_CHEST_H, HOUR); <API key>(instance->IsRegularDifficulty() ? GO_FEL_IRON_CHEST : GO_FEL_IRON_CHEST_H, GO_FLAG_NO_INTERACT, false); } if (uiData == FAIL && m_auiEncounter[1] != FAIL) DoFailVazruden(); m_auiEncounter[1] = uiData; break; } } uint32 instance_ramparts::GetData(uint32 uiType) { if (uiType == TYPE_VAZRUDEN) return m_auiEncounter[0]; if (uiType == TYPE_NAZAN) return m_auiEncounter[1]; return 0; } void instance_ramparts::DoFailVazruden() { // Store FAIL for both types m_auiEncounter[0] = FAIL; m_auiEncounter[1] = FAIL; // Restore Sentries (counter and respawn them) m_uiSentryCounter = 0; for (GuidList::const_iterator itr = m_lSentryGUIDs.begin(); itr != m_lSentryGUIDs.end(); ++itr) { if (Creature* pSentry = instance->GetCreature(*itr)) pSentry->Respawn(); } // Respawn or Reset Vazruden the herald if (Creature* pVazruden = <API key>(NPC_VAZRUDEN_HERALD)) { if (!pVazruden->isAlive()) pVazruden->Respawn(); else { if (ScriptedAI* pVazrudenAI = dynamic_cast<ScriptedAI*> (pVazruden->AI())) pVazrudenAI->Reset(); } } // Despawn Vazruden if (Creature* pVazruden = <API key>(NPC_VAZRUDEN)) pVazruden->ForcedDespawn(); } InstanceData* <API key>(Map* pMap) { return new instance_ramparts(pMap); } void <API key>() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "instance_ramparts"; pNewScript->GetInstanceData = &<API key>; pNewScript->RegisterSelf(); }
// { <API key> "fr_FR.ISO8859-15" } // 2001-07-17 Benjamin Kosnik <bkoz@redhat.com> // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // with this library; see the file COPYING3. If not see // 22.2.7.1.1 messages members #include <locale> #include <testsuite_hooks.h> void test02() { using namespace std; typedef std::messages<char>::catalog catalog; typedef std::messages<char>::string_type string_type; // This is defined through CXXFLAGS in scripts/testsuite_flags[.in]. const char* dir = LOCALEDIR; // basic construction locale loc_fr = locale(ISO_8859(15,fr_FR)); VERIFY( locale::classic() != loc_fr ); // cache the messages facets const messages<char>& mssg_fr = use_facet<messages<char> >(loc_fr); // catalog open(const string&, const locale&) const; // string_type get(catalog, int, int, const string_type& ) const; // void close(catalog) const; // Check French (fr_FR) locale. catalog cat_fr = mssg_fr.open("libstdc++", loc_fr, dir); string s01 = mssg_fr.get(cat_fr, 0, 0, "please"); string s02 = mssg_fr.get(cat_fr, 0, 0, "thank you"); VERIFY ( s01 == "s'il vous plaît" ); VERIFY ( s02 == "merci" ); mssg_fr.close(cat_fr); } int main() { test02(); return 0; }
<?php // security - hide paths if (!defined('ADODB_DIR')) die(); class ADODB_sybase extends ADOConnection { var $databaseType = "sybase"; var $dataProvider = 'sybase'; var $replaceQuote = "''"; // string to use to replace quotes var $fmtDate = "'Y-m-d'"; var $fmtTimeStamp = "'Y-m-d H:i:s'"; var $hasInsertID = true; var $hasAffectedRows = true; var $metaTablesSQL="select name from sysobjects where type='U' or type='V'"; var $metaColumnsSQL = "SELECT c.column_name, c.column_type, c.width FROM syscolumn c, systable t WHERE t.table_name='%s' AND c.table_id=t.table_id AND t.table_type='BASE'"; /* "select c.name,t.name,c.length from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'"; */ var $concat_operator = '+'; var $arrayClass = '<API key>'; var $sysDate = 'GetDate()'; var $leftOuter = '*='; var $rightOuter = '=*'; function ADODB_sybase() { } // might require begintrans -- committrans function _insertid() { return $this->GetOne('select @@identity'); } // might require begintrans -- committrans function _affectedrows() { return $this->GetOne('select @@rowcount'); } function BeginTrans() { if ($this->transOff) return true; $this->transCnt += 1; $this->Execute('BEGIN TRAN'); return true; } function CommitTrans($ok=true) { if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); $this->transCnt -= 1; $this->Execute('COMMIT TRAN'); return true; } function RollbackTrans() { if ($this->transOff) return true; $this->transCnt -= 1; $this->Execute('ROLLBACK TRAN'); return true; } // http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4 function RowLock($tables,$where,$flds='top 1 null as ignore') { if (!$this->_hastrans) $this->BeginTrans(); $tables = str_replace(',',' HOLDLOCK,',$tables); return $this->GetOne("select $flds from $tables HOLDLOCK where $where"); } function SelectDB($dbName) { $this->database = $dbName; $this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions if ($this->_connectionID) { return @sybase_select_db($dbName); } else return false; } /* Returns: the last error message from previous database operation Note: This function is NOT available for Microsoft SQL Server. */ function ErrorMsg() { if ($this->_logsql) return $this->_errorMsg; if (function_exists('<API key>')) $this->_errorMsg = <API key>(); else $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : 'SYBASE error messages not supported on this platform'; return $this->_errorMsg; } // returns true or false function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('sybase_connect')) return null; $this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword); if ($this->_connectionID === false) return false; if ($argDatabasename) return $this->SelectDB($argDatabasename); return true; } // returns true or false function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('sybase_connect')) return null; $this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword); if ($this->_connectionID === false) return false; if ($argDatabasename) return $this->SelectDB($argDatabasename); return true; } // returns query ID if successful, otherwise false function _query($sql,$inputarr) { global $ADODB_COUNTRECS; if ($ADODB_COUNTRECS == false && ADODB_PHPVER >= 0x4300) return <API key>($sql,$this->_connectionID); else return sybase_query($sql,$this->_connectionID); } // See http://www.isug.com/Sybase_FAQ/ASE/section6.2.html#6.2.12 function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) { if ($secs2cache > 0) {// we do not cache rowcount, so we have to load entire recordset $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); return $rs; } $nrows = (integer) $nrows; $offset = (integer) $offset; $cnt = ($nrows >= 0) ? $nrows : 999999999; if ($offset > 0 && $cnt) $cnt += $offset; $this->Execute("set rowcount $cnt"); $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,0); $this->Execute("set rowcount 0"); return $rs; } // returns true or false function _close() { return @sybase_close($this->_connectionID); } function UnixDate($v) { return <API key>::UnixDate($v); } function UnixTimeStamp($v) { return <API key>::UnixTimeStamp($v); } # Added 2003-10-05 by Chris Phillipson # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version // Format date column in sql string given an input format that understands Y M D function SQLDate($fmt, $col=false) { if (!$col) $col = $this->sysTimeStamp; $s = ''; $len = strlen($fmt); for ($i=0; $i < $len; $i++) { if ($s) $s .= '+'; $ch = $fmt[$i]; switch($ch) { case 'Y': case 'y': $s .= "datename(yy,$col)"; break; case 'M': $s .= "convert(char(3),$col,0)"; break; case 'm': $s .= "replace(str(month($col),2),' ','0')"; break; case 'Q': case 'q': $s .= "datename(qq,$col)"; break; case 'D': case 'd': $s .= "replace(str(datepart(dd,$col),2),' ','0')"; break; case 'h': $s .= "substring(convert(char(14),$col,0),13,2)"; break; case 'H': $s .= "replace(str(datepart(hh,$col),2),' ','0')"; break; case 'i': $s .= "replace(str(datepart(mi,$col),2),' ','0')"; break; case 's': $s .= "replace(str(datepart(ss,$col),2),' ','0')"; break; case 'a': case 'A': $s .= "substring(convert(char(19),$col,0),18,2)"; break; default: if ($ch == '\\') { $i++; $ch = substr($fmt,$i,1); } $s .= $this->qstr($ch); break; } } return $s; } # Added 2003-10-07 by Chris Phillipson # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version function MetaPrimaryKeys($table) { $sql = "SELECT c.column_name " . "FROM syscolumn c, systable t " . "WHERE t.table_name='$table' AND c.table_id=t.table_id " . "AND t.table_type='BASE' " . "AND c.pkey = 'Y' " . "ORDER BY c.column_id"; $a = $this->GetCol($sql); if ($a && sizeof($a)>0) return $a; return false; } } global $ADODB_sybase_mths; $ADODB_sybase_mths = array( 'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6, 'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12); class ADORecordset_sybase extends ADORecordSet { var $databaseType = "sybase"; var $canSeek = true; // _mths works only in non-localised system var $_mths = array('JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12); function ADORecordset_sybase($id,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC; else $this->fetchMode = $mode; $this->ADORecordSet($id,$mode); } /* Returns: an object containing field information. Get column information in the Recordset object. fetchField() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by fetchField() is retrieved. */ function &FetchField($fieldOffset = -1) { if ($fieldOffset != -1) { $o = @sybase_fetch_field($this->_queryID, $fieldOffset); } else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ $o = @sybase_fetch_field($this->_queryID); } // older versions of PHP did not support type, only numeric if ($o && !isset($o->type)) $o->type = ($o->numeric) ? 'float' : 'varchar'; return $o; } function _initrs() { global $ADODB_COUNTRECS; $this->_numOfRows = ($ADODB_COUNTRECS)? @sybase_num_rows($this->_queryID):-1; $this->_numOfFields = @sybase_num_fields($this->_queryID); } function _seek($row) { return @sybase_data_seek($this->_queryID, $row); } function _fetch($ignore_fields=false) { if ($this->fetchMode == ADODB_FETCH_NUM) { $this->fields = @sybase_fetch_row($this->_queryID); } else if ($this->fetchMode == ADODB_FETCH_ASSOC) { $this->fields = @sybase_fetch_row($this->_queryID); if (is_array($this->fields)) { $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE); return true; } return false; } else { $this->fields = @sybase_fetch_array($this->_queryID); } if ( is_array($this->fields)) { return true; } return false; } /* close() only needs to be called if you are worried about using too much memory while your script is running. All associated result memory for the specified result identifier will automatically be freed. */ function _close() { return @sybase_free_result($this->_queryID); } // sybase/mssql uses a default date like Dec 30 2000 12:00AM function UnixDate($v) { return <API key>::UnixDate($v); } function UnixTimeStamp($v) { return <API key>::UnixTimeStamp($v); } } class <API key> extends ADORecordSet_array { function <API key>($id=-1) { $this->ADORecordSet_array($id); } // sybase/mssql uses a default date like Dec 30 2000 12:00AM function UnixDate($v) { global $ADODB_sybase_mths; //Dec 30 2000 12:00AM if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})" ,$v, $rr)) return parent::UnixDate($v); if ($rr[3] <= <API key>) return 0; $themth = substr(strtoupper($rr[1]),0,3); $themth = $ADODB_sybase_mths[$themth]; if ($themth <= 0) return false; // h-m-s-MM-DD-YY return mktime(0,0,0,$themth,$rr[2],$rr[3]); } function UnixTimeStamp($v) { global $ADODB_sybase_mths; //11.02.2001 Toni Tunkkari toni.tunkkari@finebyte.com //Changed [0-9] to [0-9 ] in day conversion if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})" ,$v, $rr)) return parent::UnixTimeStamp($v); if ($rr[3] <= <API key>) return 0; $themth = substr(strtoupper($rr[1]),0,3); $themth = $ADODB_sybase_mths[$themth]; if ($themth <= 0) return false; switch (strtoupper($rr[6])) { case 'P': if ($rr[4]<12) $rr[4] += 12; break; case 'A': if ($rr[4]==12) $rr[4] = 0; break; default: break; } // h-m-s-MM-DD-YY return mktime($rr[4],$rr[5],0,$themth,$rr[2],$rr[3]); } } ?>
#ifndef <API key> #define <API key> #include <configs/ti_am335x_common.h> #define <API key> 3589 /* Until the next sync */ #define CONFIG_MACH_TYPE <API key> /* Clock Defines */ #define V_OSCK 24000000 /* Clock output from T2 */ #define V_SCLK (V_OSCK) /* Custom script for NOR */ #define CONFIG_SYS_LDSCRIPT "board/ti/am335x/u-boot.lds" /* Always 128 KiB env size */ #define CONFIG_ENV_SIZE (128 << 10) #ifdef CONFIG_NAND #define NANDARGS \ "mtdids=" MTDIDS_DEFAULT "\0" \ "mtdparts=" MTDPARTS_DEFAULT "\0" \ "nandargs=setenv bootargs console=${console} " \ "${optargs} " \ "root=${nandroot} " \ "rootfstype=${nandrootfstype}\0" \ "dfu_alt_info_nand=" DFU_ALT_INFO_NAND "\0" \ "nandroot=ubi0:rootfs rw ubi.mtd=7,2048\0" \ "nandrootfstype=ubifs rootwait=1\0" \ "nandsrcaddr=0x280000\0" \ "nandboot=echo Booting from nand ...; " \ "run nandargs; " \ "nand read ${loadaddr} ${nandsrcaddr} ${nandimgsize}; " \ "bootz ${loadaddr}\0" \ "nandimgsize=0x500000\0" #else #define NANDARGS "" #endif #define <API key> #ifndef CONFIG_SPL_BUILD #define <API key> \ "loadaddr=0x80200000\0" \ "fdtaddr=0x80F80000\0" \ "fdt_high=0xffffffff\0" \ "boot_fdt=try\0" \ "rdaddr=0x81000000\0" \ "bootpart=0:2\0" \ "bootdir=/boot\0" \ "bootfile=zImage\0" \ "fdtfile=undefined\0" \ "console=ttyO0,115200n8\0" \ "optargs=\0" \ "dfu_alt_info_mmc=" DFU_ALT_INFO_MMC "\0" \ "dfu_alt_info_emmc=rawemmc mmc 0 3751936\0" \ "mmcdev=0\0" \ "mmcroot=/dev/mmcblk0p2 ro\0" \ "mmcrootfstype=ext4 rootwait\0" \ "rootpath=/export/rootfs\0" \ "nfsopts=nolock\0" \ "static_ip=${ipaddr}:${serverip}:${gatewayip}:${netmask}:${hostname}" \ "::off\0" \ "ramroot=/dev/ram0 rw ramdisk_size=65536 initrd=${rdaddr},64M\0" \ "ramrootfstype=ext2\0" \ "mmcargs=setenv bootargs console=${console} " \ "${optargs} " \ "root=${mmcroot} " \ "rootfstype=${mmcrootfstype}\0" \ "spiroot=/dev/mtdblock4 rw\0" \ "spirootfstype=jffs2\0" \ "spisrcaddr=0xe0000\0" \ "spiimgsize=0x362000\0" \ "spibusno=0\0" \ "spiargs=setenv bootargs console=${console} " \ "${optargs} " \ "root=${spiroot} " \ "rootfstype=${spirootfstype}\0" \ "netargs=setenv bootargs console=${console} " \ "${optargs} " \ "root=/dev/nfs " \ "nfsroot=${serverip}:${rootpath},${nfsopts} rw " \ "ip=dhcp\0" \ "bootenv=uEnv.txt\0" \ "loadbootenv=load mmc ${mmcdev} ${loadaddr} ${bootenv}\0" \ "importbootenv=echo Importing environment from mmc ...; " \ "env import -t $loadaddr $filesize\0" \ "dfu_alt_info_ram=" DFU_ALT_INFO_RAM "\0" \ "ramargs=setenv bootargs console=${console} " \ "${optargs} " \ "root=${ramroot} " \ "rootfstype=${ramrootfstype}\0" \ "loadramdisk=load mmc ${mmcdev} ${rdaddr} ramdisk.gz\0" \ "loadimage=load mmc ${bootpart} ${loadaddr} ${bootdir}/${bootfile}\0" \ "loadfdt=load mmc ${bootpart} ${fdtaddr} ${bootdir}/${fdtfile}\0" \ "mmcloados=run mmcargs; " \ "if test ${boot_fdt} = yes || test ${boot_fdt} = try; then " \ "if run loadfdt; then " \ "bootz ${loadaddr} - ${fdtaddr}; " \ "else " \ "if test ${boot_fdt} = try; then " \ "bootz; " \ "else " \ "echo WARN: Cannot load the DT; " \ "fi; " \ "fi; " \ "else " \ "bootz; " \ "fi;\0" \ "mmcboot=mmc dev ${mmcdev}; " \ "if mmc rescan; then " \ "echo SD/MMC found on device ${mmcdev};" \ "if run loadbootenv; then " \ "echo Loaded environment from ${bootenv};" \ "run importbootenv;" \ "fi;" \ "if test -n $uenvcmd; then " \ "echo Running uenvcmd ...;" \ "run uenvcmd;" \ "fi;" \ "if run loadimage; then " \ "run mmcloados;" \ "fi;" \ "fi;\0" \ "spiboot=echo Booting from spi ...; " \ "run spiargs; " \ "sf probe ${spibusno}:0; " \ "sf read ${loadaddr} ${spisrcaddr} ${spiimgsize}; " \ "bootz ${loadaddr}\0" \ "netboot=echo Booting from network ...; " \ "setenv autoload no; " \ "dhcp; " \ "tftp ${loadaddr} ${bootfile}; " \ "tftp ${fdtaddr} ${fdtfile}; " \ "run netargs; " \ "bootz ${loadaddr} - ${fdtaddr}\0" \ "ramboot=echo Booting from ramdisk ...; " \ "run ramargs; " \ "bootz ${loadaddr} ${rdaddr} ${fdtaddr}\0" \ "findfdt="\ "if test $board_name = A335BONE; then " \ "setenv fdtfile am335x-bone.dtb; fi; " \ "if test $board_name = A335BNLT; then " \ "setenv fdtfile am335x-boneblack.dtb; fi; " \ "if test $board_name = A33515BB; then " \ "setenv fdtfile am335x-evm.dtb; fi; " \ "if test $board_name = A335X_SK; then " \ "setenv fdtfile am335x-evmsk.dtb; fi; " \ "if test $fdtfile = undefined; then " \ "echo WARNING: Could not determine device tree to use; fi; \0" \ NANDARGS #endif #define CONFIG_BOOTCOMMAND \ "run findfdt; " \ "run mmcboot;" \ "setenv mmcdev 1; " \ "setenv bootpart 1:2; " \ "run mmcboot;" \ "run nandboot;" /* NS16550 Configuration */ #define <API key> 0x44e09000 /* Base EVM has UART0 */ #define <API key> 0x48022000 /* UART1 */ #define <API key> 0x48024000 /* UART2 */ #define <API key> 0x481a6000 /* UART3 */ #define <API key> 0x481a8000 /* UART4 */ #define <API key> 0x481aa000 /* UART5 */ #define CONFIG_BAUDRATE 115200 /* I2C Configuration */ #define CONFIG_CMD_EEPROM #define <API key> #define <API key> 0x50 /* Main EEPROM */ #define <API key> 2 #define <API key> /* PMIC support */ #define <API key> #define <API key> /* SPL */ #ifndef CONFIG_NOR_BOOT #define <API key> #define <API key> /* CPSW support */ #define <API key> /* USB gadget RNDIS */ #define <API key> /* General network SPL, both CPSW and USB gadget RNDIS */ #define <API key> #define <API key> #define <API key> "AM335x U-Boot SPL" /* SPI flash. */ #define <API key> #define <API key> #define CONFIG_SPL_SPI_LOAD #define CONFIG_SPL_SPI_BUS 0 #define CONFIG_SPL_SPI_CS 0 #define <API key> 0x20000 #define CONFIG_SPL_LDSCRIPT "$(CPUDIR)/am33xx/u-boot-spl.lds" #ifdef CONFIG_NAND #define <API key> #define <API key> (<API key> / \ <API key>) #define <API key> 2048 #define <API key> 64 #define <API key> (128*1024) #define <API key> <API key> #define <API key> { 2, 3, 4, 5, 6, 7, 8, 9, \ 10, 11, 12, 13, 14, 15, 16, 17, \ 18, 19, 20, 21, 22, 23, 24, 25, \ 26, 27, 28, 29, 30, 31, 32, 33, \ 34, 35, 36, 37, 38, 39, 40, 41, \ 42, 43, 44, 45, 46, 47, 48, 49, \ 50, 51, 52, 53, 54, 55, 56, 57, } #define <API key> 512 #define <API key> 14 #define <API key> <API key> #define <API key> 0x80000 #endif #endif /* * For NOR boot, we must set this to the start of where NOR is mapped * in memory. */ #ifdef CONFIG_NOR_BOOT #define <API key> 0x08000000 #endif /* * USB configuration. We enable MUSB support, both for host and for * gadget. We set USB0 as peripheral and USB1 as host, based on the * board schematic and physical port wired to each. Then for host we * add mass storage support and for gadget we add both RNDIS ethernet * and DFU. */ #define <API key> #define <API key> #define CONFIG_MUSB_GADGET #define <API key> #define <API key> #define CONFIG_USB_GADGET #define <API key> #define <API key> #define <API key> 2 #define CONFIG_MUSB_HOST #define CONFIG_AM335X_USB0 #define <API key> MUSB_PERIPHERAL #define CONFIG_AM335X_USB1 #define <API key> MUSB_HOST #ifdef CONFIG_MUSB_HOST #define CONFIG_CMD_USB #define CONFIG_USB_STORAGE #endif #ifdef CONFIG_MUSB_GADGET #define CONFIG_USB_ETHER #define <API key> #define <API key> "de:ad:be:af:00:00" /* USB TI's IDs */ #define <API key> 0x0403 #define <API key> 0xBD00 #define <API key> "Texas Instruments" #endif /* CONFIG_MUSB_GADGET */ #if defined(CONFIG_SPL_BUILD) && defined(<API key>) /* disable host part of MUSB in SPL */ #undef CONFIG_MUSB_HOST /* * Disable CPSW SPL support so we fit within the 101KiB limit. */ #undef <API key> #endif /* USB Device Firmware Update support */ #define CONFIG_DFU_FUNCTION #define CONFIG_DFU_MMC #define CONFIG_CMD_DFU #define DFU_ALT_INFO_MMC \ "boot part 0 1;" \ "rootfs part 0 2;" \ "MLO fat 0 1;" \ "MLO.raw mmc 100 100;" \ "u-boot.img.raw mmc 300 400;" \ "spl-os-args.raw mmc 80 80;" \ "spl-os-image.raw mmc 900 2000;" \ "spl-os-args fat 0 1;" \ "spl-os-image fat 0 1;" \ "u-boot.img fat 0 1;" \ "uEnv.txt fat 0 1" #ifdef CONFIG_NAND #define CONFIG_DFU_NAND #define DFU_ALT_INFO_NAND \ "SPL part 0 1;" \ "SPL.backup1 part 0 2;" \ "SPL.backup2 part 0 3;" \ "SPL.backup3 part 0 4;" \ "u-boot part 0 5;" \ "u-boot-spl-os part 0 6;" \ "kernel part 0 8;" \ "rootfs part 0 9" #endif #define CONFIG_DFU_RAM #define DFU_ALT_INFO_RAM \ "kernel ram 0x80200000 0xD80000;" \ "fdt ram 0x80F80000 0x80000;" \ "ramdisk ram 0x81000000 0x4000000" /* * Default to using SPI for environment, etc. * 0x000000 - 0x020000 : SPL (128KiB) * 0x020000 - 0x0A0000 : U-Boot (512KiB) * 0x0A0000 - 0x0BFFFF : First copy of U-Boot Environment (128KiB) * 0x0C0000 - 0x0DFFFF : Second copy of U-Boot Environment (128KiB) * 0x0E0000 - 0x442000 : Linux Kernel * 0x442000 - 0x800000 : Userland */ #if defined(CONFIG_SPI_BOOT) #define <API key> #define <API key> #define <API key> <API key> #define <API key> (4 << 10) /* 4 KB sectors */ #define CONFIG_ENV_OFFSET (768 << 10) /* 768 KiB in */ #define <API key> (896 << 10) /* 896 KiB in */ #define MTDIDS_DEFAULT "nor0=m25p80-flash.0" #define MTDPARTS_DEFAULT "mtdparts=m25p80-flash.0:128k(SPL)," \ "512k(u-boot),128k(u-boot-env1)," \ "128k(u-boot-env2),3464k(kernel)," \ "-(rootfs)" #elif defined(CONFIG_EMMC_BOOT) #undef <API key> #define <API key> #define <API key> 1 #define <API key> 2 #define CONFIG_ENV_OFFSET 0x0 #define <API key> (CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE) #define <API key> #endif /* SPI flash. */ #define CONFIG_CMD_SF #define CONFIG_SPI_FLASH #define <API key> #define <API key> 24000000 /* Network. */ #define CONFIG_PHY_GIGE #define CONFIG_PHYLIB #define CONFIG_PHY_ADDR 0 #define CONFIG_PHY_SMSC /* NAND support */ #ifdef CONFIG_NAND #define CONFIG_CMD_NAND #define <API key> 1 #if !defined(CONFIG_SPI_BOOT) && !defined(CONFIG_NOR_BOOT) #define MTDIDS_DEFAULT "nand0=omap2-nand.0" #define MTDPARTS_DEFAULT "mtdparts=omap2-nand.0:128k(SPL)," \ "128k(SPL.backup1)," \ "128k(SPL.backup2)," \ "128k(SPL.backup3),1792k(u-boot)," \ "128k(u-boot-spl-os)," \ "128k(u-boot-env),5m(kernel),-(rootfs)" #define <API key> #define CONFIG_ENV_OFFSET 0x260000 /* environment starts here */ #define <API key> (128 << 10) /* 128 KiB */ #endif #endif /* * NOR Size = 16 MiB * Number of Sectors/Blocks = 128 * Sector Size = 128 KiB * Word length = 16 bits * Default layout: * 0x000000 - 0x07FFFF : U-Boot (512 KiB) * 0x080000 - 0x09FFFF : First copy of U-Boot Environment (128 KiB) * 0x0A0000 - 0x0BFFFF : Second copy of U-Boot Environment (128 KiB) * 0x0C0000 - 0x4BFFFF : Linux Kernel (4 MiB) * 0x4C0000 - 0xFFFFFF : Userland (11 MiB + 256 KiB) */ #if defined(CONFIG_NOR) #undef CONFIG_SYS_NO_FLASH #define CONFIG_CMD_FLASH #define <API key> #define <API key> #define <API key> #define <API key> #define <API key> #define <API key> 128 #define <API key> 1 #define <API key> (0x08000000) #define <API key> FLASH_CFI_16BIT #define <API key> <API key> #ifdef CONFIG_NOR_BOOT #define <API key> #define <API key> (128 << 10) /* 128 KiB */ #define CONFIG_ENV_OFFSET (512 << 10) /* 512 KiB */ #define <API key> (768 << 10) /* 768 KiB */ #define MTDIDS_DEFAULT "nor0=physmap-flash.0" #define MTDPARTS_DEFAULT "mtdparts=physmap-flash.0:" \ "512k(u-boot)," \ "128k(u-boot-env1)," \ "128k(u-boot-env2)," \ "4m(kernel),-(rootfs)" #endif #endif /* NOR support */ #endif /* ! <API key> */
/* * Scripts for spells with <API key> and SPELLFAMILY_GENERIC spells used by deathknight players. * Ordered alphabetically using scriptname. * Scriptnames of files in this file should be prefixed with "spell_dk_". */ #include "ScriptMgr.h" #include "SpellScript.h" #include "SpellAuraEffects.h" #include "Unit.h" #include "Player.h" #include "Pet.h" enum HunterPetCalculate { <API key> = 19591, <API key> = 20784, <API key> = 34666, <API key> = 34667, <API key> = 34675, <API key> = 34902, <API key> = 34903, <API key> = 34904, <API key> = 61017, <API key> = 34453, }; enum WarlockPetCalculate { <API key> = 35695, <API key> = 35697, <API key> = 34947, <API key> = 34956, <API key> = 34957, <API key> = 34958, <API key> = 61013, ENTRY_FELGUARD = 17252, ENTRY_VOIDWALKER = 1860, ENTRY_FELHUNTER = 417, ENTRY_SUCCUBUS = 1863, ENTRY_IMP = 416, <API key> = 56247, }; enum DKPetCalculate { <API key> = 51906, <API key> = 54566, <API key> = 51996, <API key> = 61697, <API key> = 55620, <API key> = 24207, <API key> = 58686, }; enum ShamanPetCalculate { <API key> = 35674, <API key> = 35675, <API key> = 35676, <API key> = 61783, }; enum MiscPetCalculate { <API key> = 44559, <API key> = 61679, SPELL_PET_UNK_01 = 67561, SPELL_PET_UNK_02 = 67557, }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritSpell = 0.0f; // Crit from Intellect CritSpell += owner-><API key>(); // Increase crit from <API key> CritSpell += owner-><API key>(<API key>); // Increase crit from <API key> CritSpell += owner-><API key>(<API key>); // Increase crit spell from spell crit ratings CritSpell += owner->GetRatingBonusValue(CR_CRIT_SPELL); amount += int32(CritSpell); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritMelee = 0.0f; // Crit from Agility CritMelee += owner-><API key>(); // Increase crit from <API key> CritMelee += owner-><API key>(<API key>); // Increase crit from <API key> CritMelee += owner-><API key>(<API key>); // Increase crit melee from melee crit ratings CritMelee += owner->GetRatingBonusValue(CR_CRIT_MELEE); amount += int32(CritMelee); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitMelee = 0.0f; // Increase hit from <API key> HitMelee += owner-><API key>(<API key>); // Increase hit melee from meele hit ratings HitMelee += owner->GetRatingBonusValue(CR_HIT_MELEE); amount += int32(HitMelee); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitSpell = 0.0f; // Increase hit from <API key> HitSpell += owner-><API key>(<API key>); // Increase hit spell from spell hit ratings HitSpell += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitSpell); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float Expertise = 0.0f; // Increase hit from <API key> Expertise += owner-><API key>(<API key>); // Increase Expertise from Expertise ratings Expertise += owner->GetRatingBonusValue(CR_EXPERTISE); amount += int32(Expertise); } } void Register() OVERRIDE { switch (m_scriptSpellId) { case <API key>: DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); break; case <API key>: DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); break; case <API key>: case <API key>: DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_2, <API key>); break; case <API key>: // case <API key>: DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); break; default: break; } } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; _tempBonus = 0; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = CalculatePct(owner->GetStat(STAT_STAMINA), 75); amount += ownerBonus; } } void ApplyEffect(AuraEffect const* /* aurEff */, <API key> /*mode*/) { if (Unit* pet = GetUnitOwner()) if (_tempBonus) { PetLevelInfo const* pInfo = sObjectMgr->GetPetLevelInfo(pet->GetEntry(), pet->getLevel()); uint32 healthMod = 0; uint32 baseHealth = pInfo->health; switch (pet->GetEntry()) { case ENTRY_IMP: healthMod = uint32(_tempBonus * 8.4f); break; case ENTRY_FELGUARD: case ENTRY_VOIDWALKER: healthMod = _tempBonus * 11; break; case ENTRY_SUCCUBUS: healthMod = uint32(_tempBonus * 9.1f); break; case ENTRY_FELHUNTER: healthMod = uint32(_tempBonus * 9.5f); break; default: healthMod = 0; break; } if (healthMod) pet->ToPet()->SetCreateHealth(baseHealth + healthMod); } } void RemoveEffect(AuraEffect const* /* aurEff */, <API key> /*mode*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) { PetLevelInfo const* pInfo = sObjectMgr->GetPetLevelInfo(pet->GetEntry(), pet->getLevel()); pet->ToPet()->SetCreateHealth(pInfo->health); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { int32 fire = int32(owner->GetUInt32Value(<API key> + SPELL_SCHOOL_FIRE)) - owner->GetUInt32Value(<API key> + SPELL_SCHOOL_FIRE); int32 shadow = int32(owner->GetUInt32Value(<API key> + SPELL_SCHOOL_SHADOW)) - owner->GetUInt32Value(<API key> + SPELL_SCHOOL_SHADOW); int32 maximum = (fire > shadow) ? fire : shadow; if (maximum < 0) maximum = 0; float bonusAP = maximum * 0.57f; amount += bonusAP; // Glyph of felguard if (pet->GetEntry() == ENTRY_FELGUARD) { if (AuraEffect* /* aurEff */ect = owner->GetAuraEffect(56246, EFFECT_0)) { float base_attPower = pet->GetModifierValue(<API key>, BASE_VALUE) * pet->GetModifierValue(<API key>, BASE_PCT); amount += CalculatePct(amount+base_attPower, /* aurEff */ect->GetAmount()); } } } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { //the damage bonus used for pets is either fire or shadow damage, whatever is higher int32 fire = int32(owner->GetUInt32Value(<API key> + SPELL_SCHOOL_FIRE)) - owner->GetUInt32Value(<API key> + SPELL_SCHOOL_FIRE); int32 shadow = int32(owner->GetUInt32Value(<API key> + SPELL_SCHOOL_SHADOW)) - owner->GetUInt32Value(<API key> + SPELL_SCHOOL_SHADOW); int32 maximum = (fire > shadow) ? fire : shadow; float bonusDamage = 0.0f; if (maximum > 0) bonusDamage = maximum * 0.15f; amount += bonusDamage; } } void Register() OVERRIDE { OnEffectRemove += AuraEffectRemoveFn(<API key>::RemoveEffect, EFFECT_0, SPELL_AURA_MOD_STAT, <API key>); AfterEffectApply += AuraEffectApplyFn(<API key>::ApplyEffect, EFFECT_0, SPELL_AURA_MOD_STAT, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, SPELL_AURA_MOD_STAT); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_2, <API key>); } private: uint32 _tempBonus; }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; _tempBonus = 0; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetStat(STAT_INTELLECT), 30); amount += ownerBonus; _tempBonus = ownerBonus; } } void ApplyEffect(AuraEffect const* /* aurEff */, <API key> /*mode*/) { if (Unit* pet = GetUnitOwner()) if (_tempBonus) { PetLevelInfo const* pInfo = sObjectMgr->GetPetLevelInfo(pet->GetEntry(), pet->getLevel()); uint32 manaMod = 0; uint32 baseMana = pInfo->mana; switch (pet->GetEntry()) { case ENTRY_IMP: manaMod = uint32(_tempBonus * 4.9f); break; case ENTRY_VOIDWALKER: case ENTRY_SUCCUBUS: case ENTRY_FELHUNTER: case ENTRY_FELGUARD: manaMod = uint32(_tempBonus * 11.5f); break; default: manaMod = 0; break; } if (manaMod) pet->ToPet()->SetCreateMana(baseMana + manaMod); } } void RemoveEffect(AuraEffect const* /* aurEff */, <API key> /*mode*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) { PetLevelInfo const* pInfo = sObjectMgr->GetPetLevelInfo(pet->GetEntry(), pet->getLevel()); pet->ToPet()->SetCreateMana(pInfo->mana); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetArmor(), 35); amount += ownerBonus; } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_FIRE), 40); amount += ownerBonus; } } void Register() OVERRIDE { OnEffectRemove += AuraEffectRemoveFn(<API key>::RemoveEffect, EFFECT_0, SPELL_AURA_MOD_STAT, <API key>); AfterEffectApply += AuraEffectApplyFn(<API key>::ApplyEffect, EFFECT_0, SPELL_AURA_MOD_STAT, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, SPELL_AURA_MOD_STAT); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_2, <API key>); } private: uint32 _tempBonus; }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_FROST), 40); amount += ownerBonus; } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_ARCANE), 40); amount += ownerBonus; } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_NATURE), 40); amount += ownerBonus; } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_2, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_SHADOW), 40); amount += ownerBonus; } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitMelee = 0.0f; // Increase hit from <API key> HitMelee += owner-><API key>(<API key>); // Increase hit spell from spell hit ratings HitMelee += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitMelee); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitSpell = 0.0f; // Increase hit from <API key> HitSpell += owner-><API key>(<API key>); // Increase hit spell from spell hit ratings HitSpell += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitSpell); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float Expertise = 0.0f; // Increase hit from <API key> Expertise += owner-><API key>(<API key>); // Increase hit spell from spell hit ratings Expertise += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(Expertise); } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_2, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritSpell = 0.0f; // Crit from Intellect CritSpell += owner-><API key>(); // Increase crit from <API key> CritSpell += owner-><API key>(<API key>); // Increase crit from <API key> CritSpell += owner-><API key>(<API key>); // Increase crit spell from spell crit ratings CritSpell += owner->GetRatingBonusValue(CR_CRIT_SPELL); if (AuraApplication* <API key> = owner-><API key>(54347)) if (Aura* <API key> = <API key>->GetBase()) if (AuraEffect* <API key> = <API key>->GetEffect(EFFECT_0)) amount += CalculatePct(CritSpell, <API key>->GetAmount()); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritMelee = 0.0f; // Crit from Agility CritMelee += owner-><API key>(); // Increase crit from <API key> CritMelee += owner-><API key>(<API key>); // Increase crit from <API key> CritMelee += owner-><API key>(<API key>); // Increase crit melee from melee crit ratings CritMelee += owner->GetRatingBonusValue(CR_CRIT_MELEE); if (AuraApplication* <API key> = owner-><API key>(54347)) if (Aura* <API key> = <API key>->GetBase()) if (AuraEffect* <API key> = <API key>->GetEffect(EFFECT_0)) amount += CalculatePct(CritMelee, <API key>->GetAmount()); } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; // this doesnt actually fit in here class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (GetCaster()->GetOwner()->ToPlayer()) { switch (GetCaster()->GetEntry()) { case ENTRY_VOIDWALKER: amount += -16; break; case ENTRY_FELHUNTER: amount += -20; break; case ENTRY_SUCCUBUS: case ENTRY_FELGUARD: amount += 5; break; } } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) if (AuraEffect* /* aurEff */ect = owner->GetAuraEffect(<API key>, EFFECT_0)) amount += /* aurEff */ect->GetAmount(); } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::CalculateAmount, EFFECT_0, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitMelee = 0.0f; // Increase hit from <API key> HitMelee += owner-><API key>(<API key>); // Increase hit melee from meele hit ratings HitMelee += owner->GetRatingBonusValue(CR_HIT_MELEE); amount += int32(HitMelee); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitSpell = 0.0f; // Increase hit from <API key> HitSpell += owner-><API key>(<API key>); // Increase hit spell from spell hit ratings HitSpell += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitSpell); } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float mod = 0.45f; float ownerBonus = 0.0f; PetSpellMap::const_iterator itr = (pet->ToPet()->m_spells.find(62758)); // Wild Hunt rank 1 if (itr == pet->ToPet()->m_spells.end()) itr = pet->ToPet()->m_spells.find(62762); // Wild Hunt rank 2 if (itr != pet->ToPet()->m_spells.end()) // If pet has Wild Hunt { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value AddPct(mod, spellInfo->Effects[EFFECT_0].CalcValue()); } ownerBonus = owner->GetStat(STAT_STAMINA)*mod; amount += ownerBonus; } } void ApplyEffect(AuraEffect const* /* aurEff */, <API key> /*mode*/) { if (Unit* pet = GetUnitOwner()) if (_tempHealth) pet->SetHealth(_tempHealth); } void RemoveEffect(AuraEffect const* /* aurEff */, <API key> /*mode*/) { if (Unit* pet = GetUnitOwner()) _tempHealth = pet->GetHealth(); } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float mod = 1.0f; //Hunter contribution modifier float bonusAP = 0.0f; PetSpellMap::const_iterator itr = (pet->ToPet()->m_spells.find(62758)); // Wild Hunt rank 1 if (itr == pet->ToPet()->m_spells.end()) itr = pet->ToPet()->m_spells.find(62762); // Wild Hunt rank 2 if (itr != pet->ToPet()->m_spells.end()) // If pet has Wild Hunt { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value mod += CalculatePct(1.0f, spellInfo->Effects[EFFECT_1].CalcValue()); } bonusAP = owner-><API key>(RANGED_ATTACK) * 0.22f * mod; amount += bonusAP; } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float mod = 1.0f; //Hunter contribution modifier float bonusDamage = 0.0f; PetSpellMap::const_iterator itr = (pet->ToPet()->m_spells.find(62758)); // Wild Hunt rank 1 if (itr == pet->ToPet()->m_spells.end()) itr = pet->ToPet()->m_spells.find(62762); // Wild Hunt rank 2 if (itr != pet->ToPet()->m_spells.end()) // If pet has Wild Hunt { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value mod += CalculatePct(1.0f, spellInfo->Effects[EFFECT_1].CalcValue()); } bonusDamage = owner-><API key>(RANGED_ATTACK) * 0.1287f * mod; amount += bonusDamage; } } void Register() OVERRIDE { OnEffectRemove += AuraEffectRemoveFn(<API key>::RemoveEffect, EFFECT_0, SPELL_AURA_MOD_STAT, <API key>); AfterEffectApply += AuraEffectApplyFn(<API key>::ApplyEffect, EFFECT_0, SPELL_AURA_MOD_STAT, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, SPELL_AURA_MOD_STAT); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_2, <API key>); } private: uint32 _tempHealth; }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_FROST), 40); amount += ownerBonus; } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_FIRE), 40); amount += ownerBonus; } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_NATURE), 40); amount += ownerBonus; } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_2, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_SHADOW), 40); amount += ownerBonus; } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_ARCANE), 40); amount += ownerBonus; } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetArmor(), 35); amount += ownerBonus; } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_2, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitMelee = 0.0f; // Increase hit from <API key> HitMelee += owner-><API key>(<API key>); // Increase hit melee from meele hit ratings HitMelee += owner->GetRatingBonusValue(CR_HIT_MELEE); amount += int32(HitMelee); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitSpell = 0.0f; // Increase hit from <API key> HitSpell += owner-><API key>(<API key>); // Increase hit spell from spell hit ratings HitSpell += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitSpell); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float Expertise = 0.0f; // Increase hit from <API key> Expertise += owner-><API key>(<API key>); // Increase Expertise from Expertise ratings Expertise += owner->GetRatingBonusValue(CR_EXPERTISE); amount += int32(Expertise); } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_2, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritSpell = 0.0f; // Crit from Intellect // CritSpell += owner-><API key>(); // Increase crit from <API key> // CritSpell += owner-><API key>(<API key>); // Increase crit from <API key> // CritSpell += owner-><API key>(<API key>); // Increase crit spell from spell crit ratings // CritSpell += owner->GetRatingBonusValue(CR_CRIT_SPELL); amount += (CritSpell*0.8f); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritMelee = 0.0f; // Crit from Agility // CritMelee += owner-><API key>(); // Increase crit from <API key> // CritMelee += owner-><API key>(<API key>); // Increase crit from <API key> // CritMelee += owner-><API key>(<API key>); // Increase crit melee from melee crit ratings // CritMelee += owner->GetRatingBonusValue(CR_CRIT_MELEE); amount += (CritMelee*0.8f); } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (GetCaster()->GetOwner()->ToPlayer()) { // Pet's base damage changes depending on happiness if (GetCaster()->IsPet() && GetCaster()->ToPet()->IsHunterPet()) { switch (GetCaster()->ToPet()->GetHappinessState()) { case HAPPY: // 125% of normal damage amount += 25.0f; break; case CONTENT: // 100% of normal damage, nothing to modify break; case UNHAPPY: // 75% of normal damage amount += -25.0f; break; } } // Cobra Reflexes if (AuraEffect* cobraReflexes = GetCaster()-><API key>(61682, EFFECT_0)) amount -= cobraReflexes->GetAmount(); } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { if (AuraEffect* /* aurEff */ect = owner-><API key>(<API key>, EFFECT_1)) amount = /* aurEff */ect->GetAmount(); else amount = 0; } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (Unit* owner = pet->GetOwner()) { // Army of the dead ghoul if (pet->GetEntry() == <API key>) amount = -90; // Night of the dead else if (Aura* aur = owner-><API key>(<API key>)) amount = aur->GetSpellInfo()->Effects[EFFECT_2].CalcValue(); } } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; _tempHealth = 0; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (pet->IsGuardian()) { if (Unit* owner = pet->GetOwner()) { float mod = 0.3f; // Ravenous Dead. Check just if owner has Ravenous Dead since it's effect is not an aura if (AuraEffect const* aurEff = owner->GetAuraEffect(<API key>, <API key>, 3010, 0)) mod += aurEff->GetSpellInfo()->Effects[EFFECT_1].CalcValue()/100; // Ravenous Dead edits the original scale // Glyph of the Ghoul if (AuraEffect const* aurEff = owner->GetAuraEffect(<API key>, 0)) mod += aurEff->GetAmount()/100; float ownerBonus = float(owner->GetStat(STAT_STAMINA)) * mod; amount += ownerBonus; } } } } void ApplyEffect(AuraEffect const* /* aurEff */, <API key> /*mode*/) { if (Unit* pet = GetUnitOwner()) if (_tempHealth) pet->SetHealth(_tempHealth); } void RemoveEffect(AuraEffect const* /* aurEff */, <API key> /*mode*/) { if (Unit* pet = GetUnitOwner()) _tempHealth = pet->GetHealth(); } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsGuardian()) return; Unit* owner = pet->GetOwner(); if (!owner) return; float mod = 0.7f; // Ravenous Dead AuraEffect const* aurEff = NULL; // Check just if owner has Ravenous Dead since it's effect is not an aura aurEff = owner->GetAuraEffect(<API key>, <API key>, 3010, 0); if (aurEff) { mod += CalculatePct(mod, aurEff->GetSpellInfo()->Effects[EFFECT_1].CalcValue()); // Ravenous Dead edits the original scale } // Glyph of the Ghoul aurEff = owner->GetAuraEffect(58686, 0); if (aurEff) mod += CalculatePct(1.0f, aurEff->GetAmount()); // Glyph of the Ghoul adds a flat value to the scale mod float ownerBonus = float(owner->GetStat(STAT_STRENGTH)) * mod; amount += ownerBonus; } } void Register() OVERRIDE { OnEffectRemove += AuraEffectRemoveFn(<API key>::RemoveEffect, EFFECT_0, SPELL_AURA_MOD_STAT, <API key>); AfterEffectApply += AuraEffectApplyFn(<API key>::ApplyEffect, EFFECT_0, SPELL_AURA_MOD_STAT, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, SPELL_AURA_MOD_STAT); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, SPELL_AURA_MOD_STAT); } private: uint32 _tempHealth; }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HasteMelee = 0.0f; // Increase hit from <API key> HasteMelee += (1-owner->m_modAttackSpeedPct[BASE_ATTACK])*100; amount += int32(HasteMelee); } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitMelee = 0.0f; // Increase hit from <API key> HitMelee += owner-><API key>(<API key>); // Increase hit melee from meele hit ratings HitMelee += owner->GetRatingBonusValue(CR_HIT_MELEE); amount += int32(HitMelee); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitSpell = 0.0f; // Increase hit from <API key> HitSpell += owner-><API key>(<API key>); // Increase hit spell from spell hit ratings HitSpell += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitSpell); } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; class <API key> : public SpellScriptLoader { public: <API key>() : SpellScriptLoader("<API key>") { } class <API key> : public AuraScript { PrepareAuraScript(<API key>); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { Unit* owner = pet->GetOwner(); if (!owner) return; if (pet->IsGuardian()) ((Guardian*)pet)->SetBonusDamage(owner-><API key>(BASE_ATTACK)); amount += owner->CalculateDamage(BASE_ATTACK, true, true); } } void <API key>(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HasteMelee = 0.0f; // Increase hit from <API key> HasteMelee += (1-owner->m_modAttackSpeedPct[BASE_ATTACK])*100; amount += int32(HasteMelee); } } void Register() OVERRIDE { DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_0, <API key>); DoEffectCalcAmount += <API key>(<API key>::<API key>, EFFECT_1, <API key>); } }; AuraScript* GetAuraScript() const OVERRIDE { return new <API key>(); } }; void <API key>() { new <API key>(); }
#include <linux/module.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/completion.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/pagemap.h> #include <linux/err.h> #include <linux/leds.h> #include <linux/scatterlist.h> #include <linux/log2.h> #include <linux/regulator/consumer.h> #include <linux/pm_runtime.h> #include <linux/pm_wakeup.h> #include <linux/suspend.h> #include <linux/fault-inject.h> #include <linux/random.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/wakelock.h> #include <trace/events/mmc.h> #include <linux/mmc/card.h> #include <linux/mmc/host.h> #include <linux/mmc/mmc.h> #include <linux/mmc/sd.h> #include <linux/mmc/slot-gpio.h> #include "core.h" #include "bus.h" #include "host.h" #include "sdio_bus.h" #include "mmc_ops.h" #include "sd_ops.h" #include "sdio_ops.h" /* If the device is not responding */ #define MMC_CORE_TIMEOUT_MS (10 * 60 * 1000) /* 10 minute timeout */ /* * Background operations can take a long time, depending on the housekeeping * operations the card has to perform. */ #define <API key> (4 * 60 * 1000) /* max time to wait in ms */ static struct workqueue_struct *workqueue; static struct wake_lock <API key>; static const unsigned freqs[] = { 400000, 300000, 200000, 100000 }; /* * Enabling software CRCs on the data blocks can be a significant (30%) * performance cost, and for other reasons may not always be desired. * So we allow it it to be disabled. */ bool use_spi_crc = 1; module_param(use_spi_crc, bool, 0); /* * Internal function. Schedule delayed work in the MMC work queue. */ static int <API key>(struct delayed_work *work, unsigned long delay) { wake_lock(&<API key>); return queue_delayed_work(workqueue, work, delay); } /* * Internal function. Flush all scheduled work from the MMC work queue. */ static void <API key>(void) { flush_workqueue(workqueue); } #ifdef <API key> /* * Internal function. Inject random data errors. * If mmc_data is NULL no errors are injected. */ static void <API key>(struct mmc_host *host, struct mmc_request *mrq) { struct mmc_command *cmd = mrq->cmd; struct mmc_data *data = mrq->data; static const int data_errors[] = { -ETIMEDOUT, -EILSEQ, -EIO, }; if (!data) return; if (cmd->error || data->error || !should_fail(&host->fail_mmc_request, data->blksz * data->blocks)) return; data->error = data_errors[prandom_u32() % ARRAY_SIZE(data_errors)]; data->bytes_xfered = (prandom_u32() % (data->bytes_xfered >> 9)) << 9; } #else /* <API key> */ static inline void <API key>(struct mmc_host *host, struct mmc_request *mrq) { } #endif /* <API key> */ /** * mmc_request_done - finish processing an MMC request * @host: MMC host which completed request * @mrq: MMC request which request * * MMC drivers should call this function when they have completed * their processing of a request. */ void mmc_request_done(struct mmc_host *host, struct mmc_request *mrq) { struct mmc_command *cmd = mrq->cmd; int err = cmd->error; if (err && cmd->retries && mmc_host_is_spi(host)) { if (cmd->resp[0] & <API key>) cmd->retries = 0; } if (err && cmd->retries && !mmc_card_removed(host->card)) { /* * Request starter must handle retries - see * <API key>(). */ if (mrq->done) mrq->done(mrq); } else { <API key>(host, mrq); led_trigger_event(host->led, LED_OFF); pr_debug("%s: req done (CMD%u): %d: %08x %08x %08x %08x\n", mmc_hostname(host), cmd->opcode, err, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); if (mrq->data) { pr_debug("%s: %d bytes transferred: %d\n", mmc_hostname(host), mrq->data->bytes_xfered, mrq->data->error); <API key>(cmd->opcode, cmd->arg, mrq->data); } if (mrq->stop) { pr_debug("%s: (CMD%u): %d: %08x %08x %08x %08x\n", mmc_hostname(host), mrq->stop->opcode, mrq->stop->error, mrq->stop->resp[0], mrq->stop->resp[1], mrq->stop->resp[2], mrq->stop->resp[3]); } if (mrq->done) mrq->done(mrq); <API key>(host); } } EXPORT_SYMBOL(mmc_request_done); static void mmc_start_request(struct mmc_host *host, struct mmc_request *mrq) { #ifdef CONFIG_MMC_DEBUG unsigned int i, sz; struct scatterlist *sg; #endif if (mrq->sbc) { pr_debug("<%s: starting CMD%u arg %08x flags %08x>\n", mmc_hostname(host), mrq->sbc->opcode, mrq->sbc->arg, mrq->sbc->flags); } pr_debug("%s: starting CMD%u arg %08x flags %08x\n", mmc_hostname(host), mrq->cmd->opcode, mrq->cmd->arg, mrq->cmd->flags); if (mrq->data) { pr_debug("%s: blksz %d blocks %d flags %08x " "tsac %d ms nsac %d\n", mmc_hostname(host), mrq->data->blksz, mrq->data->blocks, mrq->data->flags, mrq->data->timeout_ns / 1000000, mrq->data->timeout_clks); } if (mrq->stop) { pr_debug("%s: CMD%u arg %08x flags %08x\n", mmc_hostname(host), mrq->stop->opcode, mrq->stop->arg, mrq->stop->flags); } WARN_ON(!host->claimed); mrq->cmd->error = 0; mrq->cmd->mrq = mrq; if (mrq->data) { BUG_ON(mrq->data->blksz > host->max_blk_size); BUG_ON(mrq->data->blocks > host->max_blk_count); BUG_ON(mrq->data->blocks * mrq->data->blksz > host->max_req_size); #ifdef CONFIG_MMC_DEBUG sz = 0; for_each_sg(mrq->data->sg, sg, mrq->data->sg_len, i) sz += sg->length; BUG_ON(sz != mrq->data->blocks * mrq->data->blksz); #endif mrq->cmd->data = mrq->data; mrq->data->error = 0; mrq->data->mrq = mrq; if (mrq->stop) { mrq->data->stop = mrq->stop; mrq->stop->error = 0; mrq->stop->mrq = mrq; } } mmc_host_clk_hold(host); led_trigger_event(host->led, LED_FULL); host->ops->request(host, mrq); } /** * mmc_start_bkops - start BKOPS for supported cards * @card: MMC card to start BKOPS * @form_exception: A flag to indicate if this function was * called due to an exception raised by the card * * Start background operations whenever requested. * When the urgent BKOPS bit is set in a R1 command response * then background operations should be started immediately. */ void mmc_start_bkops(struct mmc_card *card, bool from_exception) { int err; int timeout; bool use_busy_signal; BUG_ON(!card); if (!card->ext_csd.bkops_en || <API key>(card)) return; err = <API key>(card); if (err) { pr_err("%s: Failed to read bkops status: %d\n", mmc_hostname(card->host), err); return; } if (!card->ext_csd.raw_bkops_status) return; if (card->ext_csd.raw_bkops_status < <API key> && from_exception) return; mmc_claim_host(card->host); if (card->ext_csd.raw_bkops_status >= <API key>) { timeout = <API key>; use_busy_signal = true; } else { timeout = 0; use_busy_signal = false; } err = __mmc_switch(card, <API key>, EXT_CSD_BKOPS_START, 1, timeout, use_busy_signal, true, false); if (err) { pr_warn("%s: Error %d starting bkops\n", mmc_hostname(card->host), err); goto out; } /* * For urgent bkops status (LEVEL_2 and more) * bkops executed synchronously, otherwise * the operation is in progress */ if (!use_busy_signal) <API key>(card); out: mmc_release_host(card->host); } EXPORT_SYMBOL(mmc_start_bkops); /* * mmc_wait_data_done() - done callback for data request * @mrq: done data request * * Wakes up mmc context, passed as a callback to host controller driver */ static void mmc_wait_data_done(struct mmc_request *mrq) { mrq->host->context_info.is_done_rcv = true; <API key>(&mrq->host->context_info.wait); } static void mmc_wait_done(struct mmc_request *mrq) { complete(&mrq->completion); } /* *<API key>() - starts data request * @host: MMC host to start the request * @mrq: data request to start * * Sets the done callback to be called when request is completed by the card. * Starts data mmc request execution */ static int <API key>(struct mmc_host *host, struct mmc_request *mrq) { mrq->done = mmc_wait_data_done; mrq->host = host; if (mmc_card_removed(host->card)) { mrq->cmd->error = -ENOMEDIUM; mmc_wait_data_done(mrq); return -ENOMEDIUM; } mmc_start_request(host, mrq); return 0; } static int __mmc_start_req(struct mmc_host *host, struct mmc_request *mrq) { init_completion(&mrq->completion); mrq->done = mmc_wait_done; if (mmc_card_removed(host->card)) { mrq->cmd->error = -ENOMEDIUM; complete(&mrq->completion); return -ENOMEDIUM; } mmc_start_request(host, mrq); return 0; } /* * <API key>() - wait for request completed * @host: MMC host to prepare the command. * @mrq: MMC request to wait for * * Blocks MMC context till host controller will ack end of data request * execution or new request notification arrives from the block layer. * Handles command retries. * * Returns enum mmc_blk_status after checking errors. */ static int <API key>(struct mmc_host *host, struct mmc_request *mrq, struct mmc_async_req *next_req) { struct mmc_command *cmd; struct mmc_context_info *context_info = &host->context_info; int err; unsigned long flags; while (1) { <API key>(context_info->wait, (context_info->is_done_rcv || context_info->is_new_req)); spin_lock_irqsave(&context_info->lock, flags); context_info->is_waiting_last_req = false; <API key>(&context_info->lock, flags); if (context_info->is_done_rcv) { context_info->is_done_rcv = false; context_info->is_new_req = false; cmd = mrq->cmd; if (!cmd->error || !cmd->retries || mmc_card_removed(host->card)) { err = host->areq->err_check(host->card, host->areq); break; /* return err */ } else { pr_info("%s: req failed (CMD%u): %d, retrying...\n", mmc_hostname(host), cmd->opcode, cmd->error); cmd->retries cmd->error = 0; host->ops->request(host, mrq); continue; /* wait for done/new event again */ } } else if (context_info->is_new_req) { context_info->is_new_req = false; if (!next_req) { err = MMC_BLK_NEW_REQUEST; break; /* return err */ } } } return err; } static void <API key>(struct mmc_host *host, struct mmc_request *mrq) { struct mmc_command *cmd; while (1) { wait_for_completion(&mrq->completion); cmd = mrq->cmd; /* * If host has timed out waiting for the sanitize * to complete, card might be still in programming state * so let's try to bring the card out of programming * state. */ if (cmd->sanitize_busy && cmd->error == -ETIMEDOUT) { if (!mmc_interrupt_hpi(host->card)) { pr_warn("%s: %s: Interrupted sanitize\n", mmc_hostname(host), __func__); cmd->error = 0; break; } else { pr_err("%s: %s: Failed to interrupt sanitize\n", mmc_hostname(host), __func__); } } if (!cmd->error || !cmd->retries || mmc_card_removed(host->card)) break; pr_debug("%s: req failed (CMD%u): %d, retrying...\n", mmc_hostname(host), cmd->opcode, cmd->error); cmd->retries cmd->error = 0; host->ops->request(host, mrq); } } /** * mmc_pre_req - Prepare for a new request * @host: MMC host to prepare command * @mrq: MMC request to prepare for * @is_first_req: true if there is no previous started request * that may run in parellel to this call, otherwise false * * mmc_pre_req() is called in prior to mmc_start_req() to let * host prepare for the new request. Preparation of a request may be * performed while another request is running on the host. */ static void mmc_pre_req(struct mmc_host *host, struct mmc_request *mrq, bool is_first_req) { if (host->ops->pre_req) { mmc_host_clk_hold(host); host->ops->pre_req(host, mrq, is_first_req); <API key>(host); } } /** * mmc_post_req - Post process a completed request * @host: MMC host to post process command * @mrq: MMC request to post process for * @err: Error, if non zero, clean up any resources made in pre_req * * Let the host post process a completed request. Post processing of * a request may be performed while another reuqest is running. */ static void mmc_post_req(struct mmc_host *host, struct mmc_request *mrq, int err) { if (host->ops->post_req) { mmc_host_clk_hold(host); host->ops->post_req(host, mrq, err); <API key>(host); } } /** * mmc_start_req - start a non-blocking request * @host: MMC host to start command * @areq: async request to start * @error: out parameter returns 0 for success, otherwise non zero * * Start a new MMC custom command request for a host. * If there is on ongoing async request wait for completion * of that request and start the new one and return. * Does not wait for the new request to complete. * * Returns the completed request, NULL in case of none completed. * Wait for the an ongoing request (previoulsy started) to complete and * return the completed request. If there is no ongoing request, NULL * is returned without waiting. NULL is not an error condition. */ struct mmc_async_req *mmc_start_req(struct mmc_host *host, struct mmc_async_req *areq, int *error) { int err = 0; int start_err = 0; struct mmc_async_req *data = host->areq; /* Prepare a new request */ if (areq) mmc_pre_req(host, areq->mrq, !host->areq); if (host->areq) { err = <API key>(host, host->areq->mrq, areq); if (err == MMC_BLK_NEW_REQUEST) { if (error) *error = err; /* * The previous request was not completed, * nothing to return */ return NULL; } /* * Check BKOPS urgency for each R1 response */ if (host->card && mmc_card_mmc(host->card) && ((mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1) || (mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1B)) && (host->areq->mrq->cmd->resp[0] & R1_EXCEPTION_EVENT)) { /* Cancel the prepared request */ if (areq) mmc_post_req(host, areq->mrq, -EINVAL); mmc_start_bkops(host->card, true); /* prepare the request again */ if (areq) mmc_pre_req(host, areq->mrq, !host->areq); } } if (!err && areq) { <API key>(areq->mrq->cmd->opcode, areq->mrq->cmd->arg, areq->mrq->data); start_err = <API key>(host, areq->mrq); } if (host->areq) mmc_post_req(host, host->areq->mrq, 0); /* Cancel a prepared request if it was not started. */ if ((err || start_err) && areq) mmc_post_req(host, areq->mrq, -EINVAL); if (err) host->areq = NULL; else host->areq = areq; if (error) *error = err; return data; } EXPORT_SYMBOL(mmc_start_req); /** * mmc_wait_for_req - start a request and wait for completion * @host: MMC host to start command * @mrq: MMC request to start * * Start a new MMC custom command request for a host, and wait * for the command to complete. Does not attempt to parse the * response. */ void mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq) { __mmc_start_req(host, mrq); <API key>(host, mrq); } EXPORT_SYMBOL(mmc_wait_for_req); /** * mmc_interrupt_hpi - Issue for High priority Interrupt * @card: the MMC card associated with the HPI transfer * * Issued High Priority Interrupt, and check for card status * until out-of prg-state. */ int mmc_interrupt_hpi(struct mmc_card *card) { int err; u32 status; unsigned long prg_wait; BUG_ON(!card); if (!card->ext_csd.hpi_en) { pr_info("%s: HPI enable bit unset\n", mmc_hostname(card->host)); return 1; } mmc_claim_host(card->host); err = mmc_send_status(card, &status); if (err) { pr_err("%s: Get card status fail\n", mmc_hostname(card->host)); goto out; } switch (R1_CURRENT_STATE(status)) { case R1_STATE_IDLE: case R1_STATE_READY: case R1_STATE_STBY: case R1_STATE_TRAN: /* * In idle and transfer states, HPI is not needed and the caller * can issue the next intended command immediately */ goto out; case R1_STATE_PRG: break; default: pr_debug("%s: HPI cannot be sent. Card state=%d\n", mmc_hostname(card->host), R1_CURRENT_STATE(status)); err = -EINVAL; goto out; } err = mmc_send_hpi_cmd(card, &status); if (err) goto out; prg_wait = jiffies + msecs_to_jiffies(card->ext_csd.out_of_int_time); do { err = mmc_send_status(card, &status); if (!err && R1_CURRENT_STATE(status) == R1_STATE_TRAN) break; if (time_after(jiffies, prg_wait)) err = -ETIMEDOUT; } while (!err); out: mmc_release_host(card->host); return err; } EXPORT_SYMBOL(mmc_interrupt_hpi); /** * mmc_wait_for_cmd - start a command and wait for completion * @host: MMC host to start command * @cmd: MMC command to start * @retries: maximum number of retries * * Start a new MMC command for a host, and wait for the command * to complete. Return any error that occurred while the command * was executing. Do not attempt to parse the response. */ int mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd, int retries) { struct mmc_request mrq = {NULL}; WARN_ON(!host->claimed); memset(cmd->resp, 0, sizeof(cmd->resp)); cmd->retries = retries; mrq.cmd = cmd; cmd->data = NULL; mmc_wait_for_req(host, &mrq); return cmd->error; } EXPORT_SYMBOL(mmc_wait_for_cmd); /** * mmc_stop_bkops - stop ongoing BKOPS * @card: MMC card to check BKOPS * * Send HPI command to stop ongoing background operations to * allow rapid servicing of foreground operations, e.g. read/ * writes. Wait until the card comes out of the programming state * to avoid errors in servicing read/write requests. */ int mmc_stop_bkops(struct mmc_card *card) { int err = 0; BUG_ON(!card); err = mmc_interrupt_hpi(card); /* * If err is EINVAL, we can't issue an HPI. * It should complete the BKOPS. */ if (!err || (err == -EINVAL)) { <API key>(card); err = 0; } return err; } EXPORT_SYMBOL(mmc_stop_bkops); int <API key>(struct mmc_card *card) { int err; u8 *ext_csd; /* * In future work, we should consider storing the entire ext_csd. */ ext_csd = kmalloc(512, GFP_KERNEL); if (!ext_csd) { pr_err("%s: could not allocate buffer to receive the ext_csd.\n", mmc_hostname(card->host)); return -ENOMEM; } mmc_claim_host(card->host); err = mmc_send_ext_csd(card, ext_csd); mmc_release_host(card->host); if (err) goto out; card->ext_csd.raw_bkops_status = ext_csd[<API key>]; card->ext_csd.<API key> = ext_csd[<API key>]; out: kfree(ext_csd); return err; } EXPORT_SYMBOL(<API key>); /** * <API key> - set the timeout for a data command * @data: data phase for command * @card: the MMC card associated with the data transfer * * Computes the data timeout parameters according to the * correct algorithm given the card type. */ void <API key>(struct mmc_data *data, const struct mmc_card *card) { unsigned int mult; /* * SDIO cards only define an upper 1 s limit on access. */ if (mmc_card_sdio(card)) { data->timeout_ns = 1000000000; data->timeout_clks = 0; return; } /* * SD cards use a 100 multiplier rather than 10 */ mult = mmc_card_sd(card) ? 100 : 10; /* * Scale up the multiplier (and therefore the timeout) by * the r2w factor for writes. */ if (data->flags & MMC_DATA_WRITE) mult <<= card->csd.r2w_factor; data->timeout_ns = card->csd.tacc_ns * mult; data->timeout_clks = card->csd.tacc_clks * mult; /* * SD cards also have an upper limit on the timeout. */ if (mmc_card_sd(card)) { unsigned int timeout_us, limit_us; timeout_us = data->timeout_ns / 1000; if (mmc_host_clk_rate(card->host)) timeout_us += data->timeout_clks * 1000 / (mmc_host_clk_rate(card->host) / 1000); if (data->flags & MMC_DATA_WRITE) /* * The MMC spec "It is strongly recommended * for hosts to implement more than 500ms * timeout value even if the card indicates * the 250ms maximum busy length." Even the * previous value of 300ms is known to be * insufficient for some cards. */ limit_us = 3000000; else limit_us = 100000; /* * SDHC cards always use these fixed values. */ if (timeout_us > limit_us || mmc_card_blockaddr(card)) { data->timeout_ns = limit_us * 1000; data->timeout_clks = 0; } /* assign limit value if invalid */ if (timeout_us == 0) data->timeout_ns = limit_us * 1000; } /* * Some cards require longer data read timeout than indicated in CSD. * Address this by setting the read timeout to a "reasonably high" * value. For the cards tested, 300ms has proven enough. If necessary, * this value can be increased if other problematic cards require this. */ if (<API key>(card) && data->flags & MMC_DATA_READ) { data->timeout_ns = 300000000; data->timeout_clks = 0; } /* * Some cards need very high timeouts if driven in SPI mode. * The worst observed timeout was 900ms after writing a * continuous stream of data until the internal logic * overflowed. */ if (mmc_host_is_spi(card->host)) { if (data->flags & MMC_DATA_WRITE) { if (data->timeout_ns < 1000000000) data->timeout_ns = 1000000000; } else { if (data->timeout_ns < 100000000) data->timeout_ns = 100000000; /* 100ms */ } } } EXPORT_SYMBOL(<API key>); /** * mmc_align_data_size - pads a transfer size to a more optimal value * @card: the MMC card associated with the data transfer * @sz: original transfer size * * Pads the original data size with a number of extra bytes in * order to avoid controller bugs and/or performance hits * (e.g. some controllers revert to PIO for certain sizes). * * Returns the improved size, which might be unmodified. * * Note that this function is only relevant when issuing a * single scatter gather entry. */ unsigned int mmc_align_data_size(struct mmc_card *card, unsigned int sz) { /* * FIXME: We don't have a system for the controller to tell * the core about its problems yet, so for now we just 32-bit * align the size. */ sz = ((sz + 3) / 4) * 4; return sz; } EXPORT_SYMBOL(mmc_align_data_size); /** * __mmc_claim_host - exclusively claim a host * @host: mmc host to claim * @abort: whether or not the operation should be aborted * * Claim a host for a set of operations. If @abort is non null and * dereference a non-zero value then this will return prematurely with * that non-zero value without acquiring the lock. Returns zero * with the lock held otherwise. */ int __mmc_claim_host(struct mmc_host *host, atomic_t *abort) { DECLARE_WAITQUEUE(wait, current); unsigned long flags; int stop; might_sleep(); add_wait_queue(&host->wq, &wait); spin_lock_irqsave(&host->lock, flags); while (1) { set_current_state(<API key>); stop = abort ? atomic_read(abort) : 0; if (stop || !host->claimed || host->claimer == current) break; <API key>(&host->lock, flags); schedule(); spin_lock_irqsave(&host->lock, flags); } set_current_state(TASK_RUNNING); if (!stop) { host->claimed = 1; host->claimer = current; host->claim_cnt += 1; } else wake_up(&host->wq); <API key>(&host->lock, flags); remove_wait_queue(&host->wq, &wait); if (host->ops->enable && !stop && host->claim_cnt == 1) host->ops->enable(host); return stop; } EXPORT_SYMBOL(__mmc_claim_host); /** * mmc_release_host - release a host * @host: mmc host to release * * Release a MMC host, allowing others to claim the host * for their operations. */ void mmc_release_host(struct mmc_host *host) { unsigned long flags; WARN_ON(!host->claimed); if (host->ops->disable && host->claim_cnt == 1) host->ops->disable(host); spin_lock_irqsave(&host->lock, flags); if (--host->claim_cnt) { /* Release for nested claim */ <API key>(&host->lock, flags); } else { host->claimed = 0; host->claimer = NULL; <API key>(&host->lock, flags); wake_up(&host->wq); } } EXPORT_SYMBOL(mmc_release_host); /* * This is a helper function, which fetches a runtime pm reference for the * card device and also claims the host. */ void mmc_get_card(struct mmc_card *card) { pm_runtime_get_sync(&card->dev); mmc_claim_host(card->host); } EXPORT_SYMBOL(mmc_get_card); /* * This is a helper function, which releases the host and drops the runtime * pm reference for the card device. */ void mmc_put_card(struct mmc_card *card) { mmc_release_host(card->host); <API key>(&card->dev); <API key>(&card->dev); } EXPORT_SYMBOL(mmc_put_card); /* * Internal function that does the actual ios call to the host driver, * optionally printing some debug output. */ static inline void mmc_set_ios(struct mmc_host *host) { struct mmc_ios *ios = &host->ios; pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u " "width %u timing %u\n", mmc_hostname(host), ios->clock, ios->bus_mode, ios->power_mode, ios->chip_select, ios->vdd, ios->bus_width, ios->timing); if (ios->clock > 0) mmc_set_ungated(host); host->ops->set_ios(host, ios); } /* * Control chip select pin on a host. */ void mmc_set_chip_select(struct mmc_host *host, int mode) { mmc_host_clk_hold(host); host->ios.chip_select = mode; mmc_set_ios(host); <API key>(host); } /* * Sets the host clock to the highest possible frequency that * is below "hz". */ static void __mmc_set_clock(struct mmc_host *host, unsigned int hz) { WARN_ON(hz && hz < host->f_min); if (hz > host->f_max) hz = host->f_max; host->ios.clock = hz; mmc_set_ios(host); } void mmc_set_clock(struct mmc_host *host, unsigned int hz) { mmc_host_clk_hold(host); __mmc_set_clock(host, hz); <API key>(host); } #ifdef CONFIG_MMC_CLKGATE /* * This gates the clock by setting it to 0 Hz. */ void mmc_gate_clock(struct mmc_host *host) { unsigned long flags; spin_lock_irqsave(&host->clk_lock, flags); host->clk_old = host->ios.clock; host->ios.clock = 0; host->clk_gated = true; <API key>(&host->clk_lock, flags); mmc_set_ios(host); } /* * This restores the clock from gating by using the cached * clock value. */ void mmc_ungate_clock(struct mmc_host *host) { /* * We should previously have gated the clock, so the clock shall * be 0 here! The clock may however be 0 during initialization, * when some request operations are performed before setting * the frequency. When ungate is requested in that situation * we just ignore the call. */ if (host->clk_old) { BUG_ON(host->ios.clock); /* This call will also set host->clk_gated to false */ __mmc_set_clock(host, host->clk_old); } } void mmc_set_ungated(struct mmc_host *host) { unsigned long flags; /* * We've been given a new frequency while the clock is gated, * so make sure we regard this as ungating it. */ spin_lock_irqsave(&host->clk_lock, flags); host->clk_gated = false; <API key>(&host->clk_lock, flags); } #else void mmc_set_ungated(struct mmc_host *host) { } #endif /* * Change the bus mode (open drain/push-pull) of a host. */ void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode) { mmc_host_clk_hold(host); host->ios.bus_mode = mode; mmc_set_ios(host); <API key>(host); } /* * Change data bus width of a host. */ void mmc_set_bus_width(struct mmc_host *host, unsigned int width) { mmc_host_clk_hold(host); host->ios.bus_width = width; mmc_set_ios(host); <API key>(host); } /** * <API key> - Convert a voltage to the OCR bit number * @vdd: voltage (mV) * @low_bits: prefer low bits in boundary cases * * This function returns the OCR bit number according to the provided @vdd * value. If conversion is not possible a negative errno value returned. * * Depending on the @low_bits flag the function prefers low or high OCR bits * on boundary voltages. For example, * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33); * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34); * * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21). */ static int <API key>(int vdd, bool low_bits) { const int max_bit = ilog2(MMC_VDD_35_36); int bit; if (vdd < 1650 || vdd > 3600) return -EINVAL; if (vdd >= 1650 && vdd <= 1950) return ilog2(MMC_VDD_165_195); if (low_bits) vdd -= 1; /* Base 2000 mV, step 100 mV, bit's base 8. */ bit = (vdd - 2000) / 100 + 8; if (bit > max_bit) return max_bit; return bit; } /** * <API key> - Convert a voltage range to the OCR mask * @vdd_min: minimum voltage value (mV) * @vdd_max: maximum voltage value (mV) * * This function returns the OCR mask bits according to the provided @vdd_min * and @vdd_max values. If conversion is not possible the function returns 0. * * Notes wrt boundary cases: * This function sets the OCR bits for all boundary voltages, for example * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 | * MMC_VDD_34_35 mask. */ u32 <API key>(int vdd_min, int vdd_max) { u32 mask = 0; if (vdd_max < vdd_min) return 0; /* Prefer high bits for the boundary vdd_max values. */ vdd_max = <API key>(vdd_max, false); if (vdd_max < 0) return 0; /* Prefer low bits for the boundary vdd_min values. */ vdd_min = <API key>(vdd_min, true); if (vdd_min < 0) return 0; /* Fill the mask, from max bit to min bit. */ while (vdd_max >= vdd_min) mask |= 1 << vdd_max return mask; } EXPORT_SYMBOL(<API key>); #ifdef CONFIG_OF /** * <API key> - return mask of supported voltages * @np: The device node need to be parsed. * @mask: mask of voltages available for MMC/SD/SDIO * * 1. Return zero on success. * 2. Return negative errno: voltage-range is invalid. */ int <API key>(struct device_node *np, u32 *mask) { const u32 *voltage_ranges; int num_ranges, i; voltage_ranges = of_get_property(np, "voltage-ranges", &num_ranges); num_ranges = num_ranges / sizeof(*voltage_ranges) / 2; if (!voltage_ranges || !num_ranges) { pr_info("%s: voltage-ranges unspecified\n", np->full_name); return -EINVAL; } for (i = 0; i < num_ranges; i++) { const int j = i * 2; u32 ocr_mask; ocr_mask = <API key>( be32_to_cpu(voltage_ranges[j]), be32_to_cpu(voltage_ranges[j + 1])); if (!ocr_mask) { pr_err("%s: voltage-range #%d is invalid\n", np->full_name, i); return -EINVAL; } *mask |= ocr_mask; } return 0; } EXPORT_SYMBOL(<API key>); #endif /* CONFIG_OF */ #ifdef CONFIG_REGULATOR /** * <API key> - return mask of supported voltages * @supply: regulator to use * * This returns either a negative errno, or a mask of voltages that * can be provided to MMC/SD/SDIO devices using the specified voltage * regulator. This would normally be called before registering the * MMC host adapter. */ int <API key>(struct regulator *supply) { int result = 0; int count; int i; int vdd_uV; int vdd_mV; count = <API key>(supply); if (count < 0) return count; for (i = 0; i < count; i++) { vdd_uV = <API key>(supply, i); if (vdd_uV <= 0) continue; vdd_mV = vdd_uV / 1000; result |= <API key>(vdd_mV, vdd_mV); } if (!result) { vdd_uV = <API key>(supply); if (vdd_uV <= 0) return vdd_uV; vdd_mV = vdd_uV / 1000; result = <API key>(vdd_mV, vdd_mV); } return result; } EXPORT_SYMBOL_GPL(<API key>); /** * <API key> - set regulator to match host->ios voltage * @mmc: the host to regulate * @supply: regulator to use * @vdd_bit: zero for power off, else a bit number (host->ios.vdd) * * Returns zero on success, else negative errno. * * MMC host drivers may use this to enable or disable a regulator using * a particular supply voltage. This would normally be called from the * set_ios() method. */ int <API key>(struct mmc_host *mmc, struct regulator *supply, unsigned short vdd_bit) { int result = 0; int min_uV, max_uV; if (vdd_bit) { int tmp; /* * REVISIT <API key>() may have set some * bits this regulator doesn't quite support ... don't * be too picky, most cards and regulators are OK with * a 0.1V range goof (it's a small error percentage). */ tmp = vdd_bit - ilog2(MMC_VDD_165_195); if (tmp == 0) { min_uV = 1650 * 1000; max_uV = 1950 * 1000; } else { min_uV = 1900 * 1000 + tmp * 100 * 1000; max_uV = min_uV + 100 * 1000; } result = <API key>(supply, min_uV, max_uV); if (result == 0 && !mmc->regulator_enabled) { result = regulator_enable(supply); if (!result) mmc->regulator_enabled = true; } } else if (mmc->regulator_enabled) { result = regulator_disable(supply); if (result == 0) mmc->regulator_enabled = false; } if (result) dev_err(mmc_dev(mmc), "could not set regulator OCR (%d)\n", result); return result; } EXPORT_SYMBOL_GPL(<API key>); #endif /* CONFIG_REGULATOR */ int <API key>(struct mmc_host *mmc) { struct device *dev = mmc_dev(mmc); int ret; mmc->supply.vmmc = <API key>(dev, "vmmc"); mmc->supply.vqmmc = <API key>(dev, "vqmmc"); if (IS_ERR(mmc->supply.vmmc)) { if (PTR_ERR(mmc->supply.vmmc) == -EPROBE_DEFER) return -EPROBE_DEFER; dev_info(dev, "No vmmc regulator found\n"); } else { ret = <API key>(mmc->supply.vmmc); if (ret > 0) mmc->ocr_avail = ret; else dev_warn(dev, "Failed getting OCR mask: %d\n", ret); } if (IS_ERR(mmc->supply.vqmmc)) { if (PTR_ERR(mmc->supply.vqmmc) == -EPROBE_DEFER) return -EPROBE_DEFER; dev_info(dev, "No vqmmc regulator found\n"); } return 0; } EXPORT_SYMBOL_GPL(<API key>); /* * Mask off any voltages we don't support and select * the lowest voltage */ u32 mmc_select_voltage(struct mmc_host *host, u32 ocr) { int bit; /* * Sanity check the voltages that the card claims to * support. */ if (ocr & 0x7F) { dev_warn(mmc_dev(host), "card claims to support voltages below defined range\n"); ocr &= ~0x7F; } ocr &= host->ocr_avail; if (!ocr) { dev_warn(mmc_dev(host), "no support for card's volts\n"); return 0; } if (host->caps2 & <API key>) { bit = ffs(ocr) - 1; ocr &= 3 << bit; mmc_power_cycle(host, ocr); } else { bit = fls(ocr) - 1; ocr &= 3 << bit; if (bit != host->ios.vdd) dev_warn(mmc_dev(host), "exceeding card's volts\n"); } return ocr; } int <API key>(struct mmc_host *host, int signal_voltage) { int err = 0; int old_signal_voltage = host->ios.signal_voltage; host->ios.signal_voltage = signal_voltage; if (host->ops-><API key>) { mmc_host_clk_hold(host); err = host->ops-><API key>(host, &host->ios); <API key>(host); } if (err) host->ios.signal_voltage = old_signal_voltage; return err; } int <API key>(struct mmc_host *host, int signal_voltage, u32 ocr) { struct mmc_command cmd = {0}; int err = 0; u32 clock; BUG_ON(!host); /* * Send CMD11 only if the request is to switch the card to * 1.8V signalling. */ if (signal_voltage == <API key>) return <API key>(host, signal_voltage); /* * If we cannot switch voltages, return failure so the caller * can continue without UHS mode */ if (!host->ops-><API key>) return -EPERM; if (!host->ops->card_busy) pr_warn("%s: cannot verify signal voltage switch\n", mmc_hostname(host)); cmd.opcode = SD_SWITCH_VOLTAGE; cmd.arg = 0; cmd.flags = MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(host, &cmd, 0); if (err) return err; if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR)) return -EIO; mmc_host_clk_hold(host); /* * The card should drive cmd and dat[0:3] low immediately * after the response of cmd11, but wait 1 ms to be sure */ mmc_delay(1); if (host->ops->card_busy && !host->ops->card_busy(host)) { err = -EAGAIN; goto power_cycle; } /* * During a signal voltage level switch, the clock must be gated * for 5 ms according to the SD spec */ clock = host->ios.clock; host->ios.clock = 0; mmc_set_ios(host); if (<API key>(host, signal_voltage)) { /* * Voltages may not have been switched, but we've already * sent CMD11, so a power cycle is required anyway */ err = -EAGAIN; goto power_cycle; } /* Keep clock gated for at least 5 ms */ mmc_delay(5); host->ios.clock = clock; mmc_set_ios(host); /* Wait for at least 1 ms according to spec */ mmc_delay(1); /* * Failure to switch is indicated by the card holding * dat[0:3] low */ if (host->ops->card_busy && host->ops->card_busy(host)) err = -EAGAIN; power_cycle: if (err) { pr_debug("%s: Signal voltage switch failed, " "power cycling card\n", mmc_hostname(host)); mmc_power_cycle(host, ocr); } <API key>(host); return err; } /* * Select timing parameters for host. */ void mmc_set_timing(struct mmc_host *host, unsigned int timing) { mmc_host_clk_hold(host); host->ios.timing = timing; mmc_set_ios(host); <API key>(host); } /* * Select appropriate driver type for host. */ void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type) { mmc_host_clk_hold(host); host->ios.drv_type = drv_type; mmc_set_ios(host); <API key>(host); } /* * Apply power to the MMC stack. This is a two-stage process. * First, we enable power to the card without the clock running. * We then wait a bit for the power to stabilise. Finally, * enable the bus drivers and clock to the card. * * We must _NOT_ enable the clock prior to power stablising. * * If a host does all the power sequencing itself, ignore the * initial MMC_POWER_UP stage. */ void mmc_power_up(struct mmc_host *host, u32 ocr) { if (host->ios.power_mode == MMC_POWER_ON) return; mmc_host_clk_hold(host); host->ios.vdd = fls(ocr) - 1; if (mmc_host_is_spi(host)) host->ios.chip_select = MMC_CS_HIGH; else host->ios.chip_select = MMC_CS_DONTCARE; host->ios.bus_mode = <API key>; host->ios.power_mode = MMC_POWER_UP; host->ios.bus_width = MMC_BUS_WIDTH_1; host->ios.timing = MMC_TIMING_LEGACY; mmc_set_ios(host); /* Try to set signal voltage to 3.3V but fall back to 1.8v or 1.2v */ if (<API key>(host, <API key>) == 0) dev_dbg(mmc_dev(host), "Initial signal voltage of 3.3v\n"); else if (<API key>(host, <API key>) == 0) dev_dbg(mmc_dev(host), "Initial signal voltage of 1.8v\n"); else if (<API key>(host, <API key>) == 0) dev_dbg(mmc_dev(host), "Initial signal voltage of 1.2v\n"); /* * This delay should be sufficient to allow the power supply * to reach the minimum voltage. */ mmc_delay(10); host->ios.clock = host->f_init; host->ios.power_mode = MMC_POWER_ON; mmc_set_ios(host); /* * This delay must be at least 74 clock sizes, or 1 ms, or the * time required to reach a stable voltage. */ mmc_delay(10); <API key>(host); } void mmc_power_off(struct mmc_host *host) { if (host->ios.power_mode == MMC_POWER_OFF) return; mmc_host_clk_hold(host); host->ios.clock = 0; host->ios.vdd = 0; if (!mmc_host_is_spi(host)) { host->ios.bus_mode = <API key>; host->ios.chip_select = MMC_CS_DONTCARE; } host->ios.power_mode = MMC_POWER_OFF; host->ios.bus_width = MMC_BUS_WIDTH_1; host->ios.timing = MMC_TIMING_LEGACY; mmc_set_ios(host); /* * Some configurations, such as the 802.11 SDIO card in the OLPC * XO-1.5, require a short delay after poweroff before the card * can be successfully turned on again. */ mmc_delay(1); <API key>(host); } void mmc_power_cycle(struct mmc_host *host, u32 ocr) { mmc_power_off(host); /* Wait at least 1 ms according to SD spec */ mmc_delay(1); mmc_power_up(host, ocr); } /* * Cleanup when the last reference to the bus operator is dropped. */ static void __mmc_release_bus(struct mmc_host *host) { BUG_ON(!host); BUG_ON(host->bus_refs); BUG_ON(!host->bus_dead); host->bus_ops = NULL; } /* * Increase reference count of bus operator */ static inline void mmc_bus_get(struct mmc_host *host) { unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->bus_refs++; <API key>(&host->lock, flags); } /* * Decrease reference count of bus operator and free it if * it is the last reference. */ static inline void mmc_bus_put(struct mmc_host *host) { unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->bus_refs if ((host->bus_refs == 0) && host->bus_ops) __mmc_release_bus(host); <API key>(&host->lock, flags); } /* * Assign a mmc bus handler to a host. Only one bus handler may control a * host at any given time. */ void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops) { unsigned long flags; BUG_ON(!host); BUG_ON(!ops); WARN_ON(!host->claimed); spin_lock_irqsave(&host->lock, flags); BUG_ON(host->bus_ops); BUG_ON(host->bus_refs); host->bus_ops = ops; host->bus_refs = 1; host->bus_dead = 0; <API key>(&host->lock, flags); } /* * Remove the current bus handler from a host. */ void mmc_detach_bus(struct mmc_host *host) { unsigned long flags; BUG_ON(!host); WARN_ON(!host->claimed); WARN_ON(!host->bus_ops); spin_lock_irqsave(&host->lock, flags); host->bus_dead = 1; <API key>(&host->lock, flags); mmc_bus_put(host); } static void _mmc_detect_change(struct mmc_host *host, unsigned long delay, bool cd_irq) { #ifdef CONFIG_MMC_DEBUG unsigned long flags; spin_lock_irqsave(&host->lock, flags); WARN_ON(host->removed); <API key>(&host->lock, flags); #endif /* * If the device is configured as wakeup, we prevent a new sleep for * 5 s to give provision for user space to consume the event. */ if (cd_irq && !(host->caps & MMC_CAP_NEEDS_POLL) && device_can_wakeup(mmc_dev(host))) pm_wakeup_event(mmc_dev(host), 5000); host->detect_change = 1; <API key>(&host->detect, delay); } /** * mmc_detect_change - process change of state on a MMC socket * @host: host which changed state. * @delay: optional delay to wait before detection (jiffies) * * MMC drivers should call this when they detect a card has been * inserted or removed. The MMC layer will confirm that any * present card is still functional, and initialize any newly * inserted. */ void mmc_detect_change(struct mmc_host *host, unsigned long delay) { _mmc_detect_change(host, delay, true); } EXPORT_SYMBOL(mmc_detect_change); void mmc_init_erase(struct mmc_card *card) { unsigned int sz; if (is_power_of_2(card->erase_size)) card->erase_shift = ffs(card->erase_size) - 1; else card->erase_shift = 0; /* * It is possible to erase an arbitrarily large area of an SD or MMC * card. That is not desirable because it can take a long time * (minutes) potentially delaying more important I/O, and also the * timeout calculations become increasingly hugely over-estimated. * Consequently, 'pref_erase' is defined as a guide to limit erases * to that size and alignment. * * For SD cards that define Allocation Unit size, limit erases to one * Allocation Unit at a time. For MMC cards that define High Capacity * Erase Size, whether it is switched on or not, limit to that size. * Otherwise just have a stab at a good value. For modern cards it * will end up being 4MiB. Note that if the value is too small, it * can end up taking longer to erase. */ if (mmc_card_sd(card) && card->ssr.au) { card->pref_erase = card->ssr.au; card->erase_shift = ffs(card->ssr.au) - 1; } else if (card->ext_csd.hc_erase_size) { card->pref_erase = card->ext_csd.hc_erase_size; } else if (card->erase_size) { sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11; if (sz < 128) card->pref_erase = 512 * 1024 / 512; else if (sz < 512) card->pref_erase = 1024 * 1024 / 512; else if (sz < 1024) card->pref_erase = 2 * 1024 * 1024 / 512; else card->pref_erase = 4 * 1024 * 1024 / 512; if (card->pref_erase < card->erase_size) card->pref_erase = card->erase_size; else { sz = card->pref_erase % card->erase_size; if (sz) card->pref_erase += card->erase_size - sz; } } else card->pref_erase = 0; } static unsigned int <API key>(struct mmc_card *card, unsigned int arg, unsigned int qty) { unsigned int erase_timeout; if (arg == MMC_DISCARD_ARG || (arg == MMC_TRIM_ARG && card->ext_csd.rev >= 6)) { erase_timeout = card->ext_csd.trim_timeout; } else if (card->ext_csd.erase_group_def & 1) { /* High Capacity Erase Group Size uses HC timeouts */ if (arg == MMC_TRIM_ARG) erase_timeout = card->ext_csd.trim_timeout; else erase_timeout = card->ext_csd.hc_erase_timeout; } else { /* CSD Erase Group Size uses write timeout */ unsigned int mult = (10 << card->csd.r2w_factor); unsigned int timeout_clks = card->csd.tacc_clks * mult; unsigned int timeout_us; /* Avoid overflow: e.g. tacc_ns=80000000 mult=1280 */ if (card->csd.tacc_ns < 1000000) timeout_us = (card->csd.tacc_ns * mult) / 1000; else timeout_us = (card->csd.tacc_ns / 1000) * mult; /* * ios.clock is only a target. The real clock rate might be * less but not that much less, so fudge it by multiplying by 2. */ timeout_clks <<= 1; timeout_us += (timeout_clks * 1000) / (mmc_host_clk_rate(card->host) / 1000); erase_timeout = timeout_us / 1000; /* * Theoretically, the calculation could underflow so round up * to 1ms in that case. */ if (!erase_timeout) erase_timeout = 1; } /* Multiplier for secure operations */ if (arg & MMC_SECURE_ARGS) { if (arg == <API key>) erase_timeout *= card->ext_csd.sec_erase_mult; else erase_timeout *= card->ext_csd.sec_trim_mult; } erase_timeout *= qty; /* * Ensure at least a 1 second timeout for SPI as per * '<API key>()' */ if (mmc_host_is_spi(card->host) && erase_timeout < 1000) erase_timeout = 1000; return erase_timeout; } static unsigned int <API key>(struct mmc_card *card, unsigned int arg, unsigned int qty) { unsigned int erase_timeout; if (card->ssr.erase_timeout) { /* Erase timeout specified in SD Status Register (SSR) */ erase_timeout = card->ssr.erase_timeout * qty + card->ssr.erase_offset; } else { /* * Erase timeout not specified in SD Status Register (SSR) so * use 250ms per write block. */ erase_timeout = 250 * qty; } /* Must not be less than 1 second */ if (erase_timeout < 1000) erase_timeout = 1000; return erase_timeout; } static unsigned int mmc_erase_timeout(struct mmc_card *card, unsigned int arg, unsigned int qty) { if (mmc_card_sd(card)) return <API key>(card, arg, qty); else return <API key>(card, arg, qty); } static int mmc_do_erase(struct mmc_card *card, unsigned int from, unsigned int to, unsigned int arg) { struct mmc_command cmd = {0}; unsigned int qty = 0; unsigned long timeout; unsigned int fr, nr; int err; fr = from; nr = to - from + 1; <API key>(arg, fr, nr); /* * qty is used to calculate the erase timeout which depends on how many * erase groups (or allocation units in SD terminology) are affected. * We count erasing part of an erase group as one erase group. * For SD, the allocation units are always a power of 2. For MMC, the * erase group size is almost certainly also power of 2, but it does not * seem to insist on that in the JEDEC standard, so we fall back to * division in that case. SD may not specify an allocation unit size, * in which case the timeout is based on the number of write blocks. * * Note that the timeout for secure trim 2 will only be correct if the * number of erase groups specified is the same as the total of all * preceding secure trim 1 commands. Since the power may have been * lost since the secure trim 1 commands occurred, it is generally * impossible to calculate the secure trim 2 timeout correctly. */ if (card->erase_shift) qty += ((to >> card->erase_shift) - (from >> card->erase_shift)) + 1; else if (mmc_card_sd(card)) qty += to - from + 1; else qty += ((to / card->erase_size) - (from / card->erase_size)) + 1; if (!mmc_card_blockaddr(card)) { from <<= 9; to <<= 9; } if (mmc_card_sd(card)) cmd.opcode = <API key>; else cmd.opcode = <API key>; cmd.arg = from; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) { pr_err("mmc_erase: group start error %d, " "status %#x\n", err, cmd.resp[0]); err = -EIO; goto out; } memset(&cmd, 0, sizeof(struct mmc_command)); if (mmc_card_sd(card)) cmd.opcode = SD_ERASE_WR_BLK_END; else cmd.opcode = MMC_ERASE_GROUP_END; cmd.arg = to; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) { pr_err("mmc_erase: group end error %d, status % err, cmd.resp[0]); err = -EIO; goto out; } memset(&cmd, 0, sizeof(struct mmc_command)); cmd.opcode = MMC_ERASE; cmd.arg = arg; cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; cmd.busy_timeout = mmc_erase_timeout(card, arg, qty); err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) { pr_err("mmc_erase: erase error %d, status % err, cmd.resp[0]); err = -EIO; goto out; } if (mmc_host_is_spi(card->host)) goto out; timeout = jiffies + msecs_to_jiffies(MMC_CORE_TIMEOUT_MS); do { memset(&cmd, 0, sizeof(struct mmc_command)); cmd.opcode = MMC_SEND_STATUS; cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_R1 | MMC_CMD_AC; /* Do not retry else we can't see errors */ err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err || (cmd.resp[0] & 0xFDF92000)) { pr_err("error %d requesting status % err, cmd.resp[0]); err = -EIO; goto out; } /* Timeout if the device never becomes ready for data and * never leaves the program state. */ if (time_after(jiffies, timeout)) { pr_err("%s: Card stuck in programming state! %s\n", mmc_hostname(card->host), __func__); err = -EIO; goto out; } } while (!(cmd.resp[0] & R1_READY_FOR_DATA) || (R1_CURRENT_STATE(cmd.resp[0]) == R1_STATE_PRG)); out: <API key>(arg, fr, nr); return err; } /** * mmc_erase - erase sectors. * @card: card to erase * @from: first sector to erase * @nr: number of sectors to erase * @arg: erase command argument (SD supports only %MMC_ERASE_ARG) * * Caller must claim host before calling this function. */ int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr, unsigned int arg) { unsigned int rem, to = from + nr; if (!(card->host->caps & MMC_CAP_ERASE) || !(card->csd.cmdclass & CCC_ERASE)) return -EOPNOTSUPP; if (!card->erase_size) return -EOPNOTSUPP; if (mmc_card_sd(card) && arg != MMC_ERASE_ARG) return -EOPNOTSUPP; if ((arg & MMC_SECURE_ARGS) && !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN)) return -EOPNOTSUPP; if ((arg & MMC_TRIM_ARGS) && !(card->ext_csd.sec_feature_support & <API key>)) return -EOPNOTSUPP; if (arg == <API key>) { if (from % card->erase_size || nr % card->erase_size) return -EINVAL; } if (arg == MMC_ERASE_ARG) { rem = from % card->erase_size; if (rem) { rem = card->erase_size - rem; from += rem; if (nr > rem) nr -= rem; else return 0; } rem = nr % card->erase_size; if (rem) nr -= rem; } if (nr == 0) return 0; to = from + nr; if (to <= from) return -EINVAL; /* 'from' and 'to' are inclusive */ to -= 1; return mmc_do_erase(card, from, to, arg); } EXPORT_SYMBOL(mmc_erase); int mmc_can_erase(struct mmc_card *card) { if ((card->host->caps & MMC_CAP_ERASE) && (card->csd.cmdclass & CCC_ERASE) && card->erase_size) return 1; return 0; } EXPORT_SYMBOL(mmc_can_erase); int mmc_can_trim(struct mmc_card *card) { if (card->ext_csd.sec_feature_support & <API key>) return 1; return 0; } EXPORT_SYMBOL(mmc_can_trim); int mmc_can_discard(struct mmc_card *card) { /* * As there's no way to detect the discard support bit at v4.5 * use the s/w feature support filed. */ if (card->ext_csd.feature_support & MMC_DISCARD_FEATURE) return 1; return 0; } EXPORT_SYMBOL(mmc_can_discard); int mmc_can_sanitize(struct mmc_card *card) { if (!mmc_can_trim(card) && !mmc_can_erase(card)) return 0; if (card->ext_csd.sec_feature_support & <API key>) return 1; return 0; } EXPORT_SYMBOL(mmc_can_sanitize); int <API key>(struct mmc_card *card) { if ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN) && !(card->quirks & <API key>)) return 1; return 0; } EXPORT_SYMBOL(<API key>); int <API key>(struct mmc_card *card, unsigned int from, unsigned int nr) { if (!card->erase_size) return 0; if (from % card->erase_size || nr % card->erase_size) return 0; return 1; } EXPORT_SYMBOL(<API key>); static unsigned int <API key>(struct mmc_card *card, unsigned int arg) { struct mmc_host *host = card->host; unsigned int max_discard, x, y, qty = 0, max_qty, timeout; unsigned int last_timeout = 0; if (card->erase_shift) max_qty = UINT_MAX >> card->erase_shift; else if (mmc_card_sd(card)) max_qty = UINT_MAX; else max_qty = UINT_MAX / card->erase_size; /* Find the largest qty with an OK timeout */ do { y = 0; for (x = 1; x && x <= max_qty && max_qty - x >= qty; x <<= 1) { timeout = mmc_erase_timeout(card, arg, qty + x); if (timeout > host->max_busy_timeout) break; if (timeout < last_timeout) break; last_timeout = timeout; y = x; } qty += y; } while (y); if (!qty) return 0; if (qty == 1) return 1; /* Convert qty to sectors */ if (card->erase_shift) max_discard = --qty << card->erase_shift; else if (mmc_card_sd(card)) max_discard = qty; else max_discard = --qty * card->erase_size; return max_discard; } unsigned int <API key>(struct mmc_card *card) { struct mmc_host *host = card->host; unsigned int max_discard, max_trim; if (!host->max_busy_timeout) return UINT_MAX; /* * Without erase_group_def set, MMC erase timeout depends on clock * frequence which can change. In that case, the best choice is * just the preferred erase size. */ if (mmc_card_mmc(card) && !(card->ext_csd.erase_group_def & 1)) return card->pref_erase; max_discard = <API key>(card, MMC_ERASE_ARG); if (mmc_can_trim(card)) { max_trim = <API key>(card, MMC_TRIM_ARG); if (max_trim < max_discard) max_discard = max_trim; } else if (max_discard < card->erase_size) { max_discard = 0; } pr_debug("%s: calculated max. discard sectors %u for timeout %u ms\n", mmc_hostname(host), max_discard, host->max_busy_timeout); return max_discard; } EXPORT_SYMBOL(<API key>); int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen) { struct mmc_command cmd = {0}; if (mmc_card_blockaddr(card) || mmc_card_ddr52(card)) return 0; cmd.opcode = MMC_SET_BLOCKLEN; cmd.arg = blocklen; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; return mmc_wait_for_cmd(card->host, &cmd, 5); } EXPORT_SYMBOL(mmc_set_blocklen); int mmc_set_blockcount(struct mmc_card *card, unsigned int blockcount, bool is_rel_write) { struct mmc_command cmd = {0}; cmd.opcode = MMC_SET_BLOCK_COUNT; cmd.arg = blockcount & 0x0000FFFF; if (is_rel_write) cmd.arg |= 1 << 31; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; return mmc_wait_for_cmd(card->host, &cmd, 5); } EXPORT_SYMBOL(mmc_set_blockcount); static void <API key>(struct mmc_host *host) { if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset) return; mmc_host_clk_hold(host); host->ops->hw_reset(host); <API key>(host); } int mmc_can_reset(struct mmc_card *card) { u8 rst_n_function; if (!mmc_card_mmc(card)) return 0; rst_n_function = card->ext_csd.rst_n_function; if ((rst_n_function & <API key>) != <API key>) return 0; return 1; } EXPORT_SYMBOL(mmc_can_reset); static int mmc_do_hw_reset(struct mmc_host *host, int check) { struct mmc_card *card = host->card; if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset) return -EOPNOTSUPP; if (!card) return -EINVAL; if (!mmc_can_reset(card)) return -EOPNOTSUPP; mmc_host_clk_hold(host); mmc_set_clock(host, host->f_init); host->ops->hw_reset(host); /* If the reset has happened, then a status command will fail */ if (check) { struct mmc_command cmd = {0}; int err; cmd.opcode = MMC_SEND_STATUS; if (!mmc_host_is_spi(card->host)) cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (!err) { <API key>(host); return -ENOSYS; } } if (mmc_host_is_spi(host)) { host->ios.chip_select = MMC_CS_HIGH; host->ios.bus_mode = <API key>; } else { host->ios.chip_select = MMC_CS_DONTCARE; host->ios.bus_mode = <API key>; } host->ios.bus_width = MMC_BUS_WIDTH_1; host->ios.timing = MMC_TIMING_LEGACY; mmc_set_ios(host); <API key>(host); return host->bus_ops->power_restore(host); } int mmc_hw_reset(struct mmc_host *host) { return mmc_do_hw_reset(host, 0); } EXPORT_SYMBOL(mmc_hw_reset); int mmc_hw_reset_check(struct mmc_host *host) { return mmc_do_hw_reset(host, 1); } EXPORT_SYMBOL(mmc_hw_reset_check); static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq) { host->f_init = freq; #ifdef CONFIG_MMC_DEBUG pr_info("%s: %s: trying to init card at %u Hz\n", mmc_hostname(host), __func__, host->f_init); #endif mmc_power_up(host, host->ocr_avail); /* * Some eMMCs (with VCCQ always on) may not be reset after power up, so * do a hardware reset if possible. */ <API key>(host); /* * sdio_reset sends CMD52 to reset card. Since we do not know * if the card is being re-initialized, just send it. CMD52 * should be ignored by SD/eMMC cards. */ sdio_reset(host); mmc_go_idle(host); mmc_send_if_cond(host, host->ocr_avail); /* Order's important: probe SDIO, then SD, then MMC */ if (!mmc_attach_sdio(host)) return 0; if (!mmc_attach_sd(host)) return 0; if (!mmc_attach_mmc(host)) return 0; mmc_power_off(host); return -EIO; } int <API key>(struct mmc_host *host) { int ret; if (host->caps & <API key>) return 0; if (!host->card || mmc_card_removed(host->card)) return 1; ret = host->bus_ops->alive(host); /* * Card detect status and alive check may be out of sync if card is * removed slowly, when card detect switch changes while card/slot * pads are still contacted in hardware (refer to "SD Card Mechanical * Addendum, Appendix C: Card Detection Switch"). So reschedule a * detect work 200ms later for this case. */ if (!ret && host->ops->get_cd && !host->ops->get_cd(host)) { mmc_detect_change(host, msecs_to_jiffies(200)); pr_debug("%s: card removed too slowly\n", mmc_hostname(host)); } if (ret) { <API key>(host->card); pr_debug("%s: card remove detected\n", mmc_hostname(host)); } return ret; } int <API key>(struct mmc_host *host) { struct mmc_card *card = host->card; int ret; WARN_ON(!host->claimed); if (!card) return 1; ret = mmc_card_removed(card); /* * The card will be considered unchanged unless we have been asked to * detect a change or host requires polling to provide card detection. */ if (!host->detect_change && !(host->caps & MMC_CAP_NEEDS_POLL)) return ret; host->detect_change = 0; if (!ret) { ret = <API key>(host); if (ret && (host->caps & MMC_CAP_NEEDS_POLL)) { /* * Schedule a detect work as soon as possible to let a * rescan handle the card removal. */ cancel_delayed_work(&host->detect); _mmc_detect_change(host, 0, false); } } return ret; } EXPORT_SYMBOL(<API key>); void mmc_rescan(struct work_struct *work) { struct mmc_host *host = container_of(work, struct mmc_host, detect.work); int i; bool extend_wakelock = false; if (host->trigger_card_event && host->ops->card_event) { host->ops->card_event(host); host->trigger_card_event = false; } if (host->rescan_disable) return; /* If there is a non-removable card registered, only scan once */ if ((host->caps & <API key>) && host->rescan_entered) return; host->rescan_entered = 1; mmc_bus_get(host); /* * if there is a _removable_ card registered, check whether it is * still present */ if (host->bus_ops && !host->bus_dead && !(host->caps & <API key>)) host->bus_ops->detect(host); host->detect_change = 0; /* If the card was removed the bus will be marked * as dead - extend the wakelock so userspace * can respond */ if (host->bus_dead) extend_wakelock = 1; /* * Let mmc_bus_put() free the bus/bus_ops if we've found that * the card is no longer present. */ mmc_bus_put(host); mmc_bus_get(host); /* if there still is a card present, stop here */ if (host->bus_ops != NULL) { mmc_bus_put(host); goto out; } /* * Only we can add a new handler, so it's safe to * release the lock here. */ mmc_bus_put(host); if (!(host->caps & <API key>) && host->ops->get_cd && host->ops->get_cd(host) == 0) { mmc_claim_host(host); mmc_power_off(host); mmc_release_host(host); goto out; } mmc_claim_host(host); for (i = 0; i < ARRAY_SIZE(freqs); i++) { if (!mmc_rescan_try_freq(host, max(freqs[i], host->f_min))) { extend_wakelock = true; break; } if (freqs[i] <= host->f_min) break; } mmc_release_host(host); out: if (extend_wakelock) wake_lock_timeout(&<API key>, HZ / 2); else wake_unlock(&<API key>); if (host->caps & MMC_CAP_NEEDS_POLL) <API key>(&host->detect, HZ); } void mmc_start_host(struct mmc_host *host) { host->f_init = max(freqs[0], host->f_min); host->rescan_disable = 0; host->ios.power_mode = MMC_POWER_UNDEFINED; if (host->caps2 & <API key>) mmc_power_off(host); else mmc_power_up(host, host->ocr_avail); <API key>(host); _mmc_detect_change(host, 0, false); } void mmc_stop_host(struct mmc_host *host) { #ifdef CONFIG_MMC_DEBUG unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->removed = 1; <API key>(&host->lock, flags); #endif if (host->slot.cd_irq >= 0) disable_irq(host->slot.cd_irq); host->rescan_disable = 1; <API key>(&host->detect); <API key>(); /* clear pm flags now and let card drivers set them as needed */ host->pm_flags = 0; mmc_bus_get(host); if (host->bus_ops && !host->bus_dead) { /* Calling bus_ops->remove() with a claimed host can deadlock */ host->bus_ops->remove(host); mmc_claim_host(host); mmc_detach_bus(host); mmc_power_off(host); mmc_release_host(host); mmc_bus_put(host); return; } mmc_bus_put(host); BUG_ON(host->card); mmc_power_off(host); } int mmc_power_save_host(struct mmc_host *host) { int ret = 0; #ifdef CONFIG_MMC_DEBUG pr_info("%s: %s: powering down\n", mmc_hostname(host), __func__); #endif mmc_bus_get(host); if (!host->bus_ops || host->bus_dead) { mmc_bus_put(host); return -EINVAL; } if (host->bus_ops->power_save) ret = host->bus_ops->power_save(host); mmc_bus_put(host); mmc_power_off(host); return ret; } EXPORT_SYMBOL(mmc_power_save_host); int <API key>(struct mmc_host *host) { int ret; #ifdef CONFIG_MMC_DEBUG pr_info("%s: %s: powering up\n", mmc_hostname(host), __func__); #endif mmc_bus_get(host); if (!host->bus_ops || host->bus_dead) { mmc_bus_put(host); return -EINVAL; } mmc_power_up(host, host->card->ocr); ret = host->bus_ops->power_restore(host); mmc_bus_put(host); return ret; } EXPORT_SYMBOL(<API key>); /* * Flush the cache to the non-volatile storage. */ int mmc_flush_cache(struct mmc_card *card) { int err = 0; if (mmc_card_mmc(card) && (card->ext_csd.cache_size > 0) && (card->ext_csd.cache_ctrl & 1)) { err = mmc_switch(card, <API key>, EXT_CSD_FLUSH_CACHE, 1, 0); if (err) pr_err("%s: cache flush error %d\n", mmc_hostname(card->host), err); } return err; } EXPORT_SYMBOL(mmc_flush_cache); #ifdef CONFIG_PM /* Do the card removal on suspend if card is assumed removeable * Do that in pm notifier while userspace isn't yet frozen, so we will be able to sync the card. */ int mmc_pm_notify(struct notifier_block *notify_block, unsigned long mode, void *unused) { struct mmc_host *host = container_of( notify_block, struct mmc_host, pm_notify); unsigned long flags; int err = 0; switch (mode) { case <API key>: case PM_SUSPEND_PREPARE: spin_lock_irqsave(&host->lock, flags); host->rescan_disable = 1; <API key>(&host->lock, flags); <API key>(&host->detect); if (!host->bus_ops) break; /* Validate prerequisites for suspend */ if (host->bus_ops->pre_suspend) err = host->bus_ops->pre_suspend(host); if (!err) break; /* Calling bus_ops->remove() with a claimed host can deadlock */ host->bus_ops->remove(host); mmc_claim_host(host); mmc_detach_bus(host); mmc_power_off(host); mmc_release_host(host); host->pm_flags = 0; break; case PM_POST_SUSPEND: case PM_POST_HIBERNATION: case PM_POST_RESTORE: spin_lock_irqsave(&host->lock, flags); host->rescan_disable = 0; <API key>(&host->lock, flags); _mmc_detect_change(host, 0, false); } return 0; } #endif /** * <API key>() - init synchronization context * @host: mmc host * * Init struct context_info needed to implement asynchronous * request mechanism, used by mmc core, host driver and mmc requests * supplier. */ void <API key>(struct mmc_host *host) { spin_lock_init(&host->context_info.lock); host->context_info.is_new_req = false; host->context_info.is_done_rcv = false; host->context_info.is_waiting_last_req = false; init_waitqueue_head(&host->context_info.wait); } #ifdef <API key> void <API key>(struct mmc_host *host, struct sdio_cis *cis, struct sdio_cccr *cccr, struct sdio_embedded_func *funcs, int num_funcs) { host->embedded_sdio_data.cis = cis; host->embedded_sdio_data.cccr = cccr; host->embedded_sdio_data.funcs = funcs; host->embedded_sdio_data.num_funcs = num_funcs; } EXPORT_SYMBOL(<API key>); #endif static int __init mmc_init(void) { int ret; workqueue = <API key>("kmmcd", 0); if (!workqueue) return -ENOMEM; wake_lock_init(&<API key>, WAKE_LOCK_SUSPEND, "mmc_delayed_work"); ret = mmc_register_bus(); if (ret) goto destroy_workqueue; ret = <API key>(); if (ret) goto unregister_bus; ret = sdio_register_bus(); if (ret) goto <API key>; return 0; <API key>: <API key>(); unregister_bus: mmc_unregister_bus(); destroy_workqueue: destroy_workqueue(workqueue); wake_lock_destroy(&<API key>); return ret; } static void __exit mmc_exit(void) { sdio_unregister_bus(); <API key>(); mmc_unregister_bus(); destroy_workqueue(workqueue); wake_lock_destroy(&<API key>); } subsys_initcall(mmc_init); module_exit(mmc_exit); MODULE_LICENSE("GPL");
<?php use Ctct\Util\CurlResponse; use Ctct\Services\ListService; use Ctct\Util\RestClient; use Ctct\Components\Contacts\ContactList; class ListServiceUnitTest extends <API key> { private $restClient; private $listService; public function setUp() { $this->restClient = $this->getMock('Ctct\Util\RestClientInterface'); $this->listService = new ListService("apikey", $this->restClient); } public function testGetLists() { $curlResponse = CurlResponse::create(JsonLoader::getListsJson(), array('http_code' => 200)); $this->restClient->expects($this->once()) ->method('get') ->with() ->will($this->returnValue($curlResponse)); $response = $this->listService->getLists('access_token'); $this->assertInstanceOf("Ctct\Components\Contacts\ContactList", $response[0]); $this->assertEquals(1, $response[0]->id); $this->assertEquals("General Interest", $response[0]->name); $this->assertEquals("ACTIVE", $response[0]->status); $this->assertEquals(17, $response[0]->contact_count); $this->assertEquals(3, $response[1]->id); $this->assertEquals("mod_Test List 1", $response[1]->name); $this->assertEquals("HIDDEN", $response[1]->status); $this->assertEquals(18, $response[1]->contact_count); } public function <API key>() { $curlResponse = CurlResponse::create(JsonLoader::getListsJson(), array('http_code' => 200)); $this->restClient->expects($this->once()) ->method('get') ->with() ->will($this->returnValue($curlResponse)); $response = $this->listService->getLists('access_token', array('modified_since' => '2013-01-12T20:04:59.436Z')); $this->assertInstanceOf("Ctct\Components\Contacts\ContactList", $response[0]); $this->assertEquals(1, $response[0]->id); $this->assertEquals("General Interest", $response[0]->name); $this->assertEquals("ACTIVE", $response[0]->status); $this->assertEquals(17, $response[0]->contact_count); $this->assertEquals(3, $response[1]->id); $this->assertEquals("mod_Test List 1", $response[1]->name); $this->assertEquals("HIDDEN", $response[1]->status); $this->assertEquals(18, $response[1]->contact_count); } public function testGetList() { $curlResponse = CurlResponse::create(JsonLoader::getListJson(), array('http_code' => 200)); $this->restClient->expects($this->once()) ->method('get') ->with() ->will($this->returnValue($curlResponse)); $list = $this->listService->getList('access_token', 6); $this->assertInstanceOf("Ctct\Components\Contacts\ContactList", $list); $this->assertEquals(6, $list->id); $this->assertEquals("Test List 4", $list->name); $this->assertEquals("HIDDEN", $list->status); $this->assertEquals(19, $list->contact_count); } public function testAddList() { $curlResponse = CurlResponse::create(JsonLoader::getListJson(), array('http_code' => 204)); $this->restClient->expects($this->once()) ->method('post') ->with() ->will($this->returnValue($curlResponse)); $list = $this->listService->addList('access_token', new ContactList()); $this->assertInstanceOf("Ctct\Components\Contacts\ContactList", $list); $this->assertEquals(6, $list->id); $this->assertEquals("Test List 4", $list->name); $this->assertEquals("HIDDEN", $list->status); $this->assertEquals(19, $list->contact_count); } public function testUpdateList() { $curlResponse = CurlResponse::create(JsonLoader::getListJson(), array('http_code' => 200)); $this->restClient->expects($this->once()) ->method('put') ->with() ->will($this->returnValue($curlResponse)); $list = $this->listService->updateList('access_token', new ContactList()); $this->assertInstanceOf("Ctct\Components\Contacts\ContactList", $list); $this->assertEquals(6, $list->id); $this->assertEquals("Test List 4", $list->name); $this->assertEquals("HIDDEN", $list->status); $this->assertEquals(19, $list->contact_count); } public function <API key>() { $curlResponse = CurlResponse::create(JsonLoader::getContactsJson(), array('http_code' => 200)); $this->restClient->expects($this->once()) ->method('get') ->with() ->will($this->returnValue($curlResponse)); $response = $this->listService->getContactsFromList('access_token', 1); $this->assertInstanceOf("Ctct\Components\ResultSet", $response); $contact = $response->results[1]; $this->assertEquals(231, $contact->id); $this->assertEquals("ACTIVE", $contact->status); $this->assertEquals("", $contact->fax); $this->assertEquals("", $contact->prefix_name); $this->assertEquals("Jimmy", $contact->first_name); $this->assertEquals("", $contact->middle_name); $this->assertEquals("Roving", $contact->last_name); $this->assertEquals("Bear Tamer", $contact->job_title); $this->assertEquals("Animal Trainer Pro", $contact->company_name); $this->assertEquals("details", $contact->source_details); $this->assertEquals(false, $contact->confirmed); $this->assertEquals("", $contact->source); // custom fields $this->assertEquals("CustomField1", $contact->custom_fields[0]->name); $this->assertEquals("1", $contact->custom_fields[0]->value); //addresses $this->assertEquals("Suite 101", $contact->addresses[0]->line1); $this->assertEquals("line2", $contact->addresses[0]->line2); $this->assertEquals("line3", $contact->addresses[0]->line3); $this->assertEquals("Brookfield", $contact->addresses[0]->city); $this->assertEquals("PERSONAL", $contact->addresses[0]->address_type); $this->assertEquals("WI", $contact->addresses[0]->state_code); $this->assertEquals("us", $contact->addresses[0]->country_code); $this->assertEquals("53027", $contact->addresses[0]->postal_code); $this->assertEquals("", $contact->addresses[0]->sub_postal_code); //notes $this->assertEquals(0, count($contact->notes)); //lists $this->assertEquals(1, $contact->lists[0]->id); $this->assertEquals("ACTIVE", $contact->lists[0]->status); // EmailAddress $this->assertEquals("ACTIVE", $contact->email_addresses[0]->status); $this->assertEquals("<API key>", $contact->email_addresses[0]->confirm_status); $this->assertEquals("ACTION_BY_OWNER", $contact->email_addresses[0]->opt_in_source); $this->assertEquals("2012-06-22T10:29:09.976Z", $contact->email_addresses[0]->opt_in_date); $this->assertEquals("", $contact->email_addresses[0]->opt_out_date); $this->assertEquals("anothertest@roving.com", $contact->email_addresses[0]->email_address); } }
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http: <!-- /home/qt/mkdist-qt-4.4.3-1222864207/<API key>.4.3/doc/src/tutorials/tutorial.qdoc --> <head> <title>Qt 4.4: Qt Tutorial 12 - Hanging in the Air the Way Bricks Don't</title> <link rel="prev" href="<API key>.html" /> <link rel="contents" href="tutorials-tutorial.html" /> <link rel="next" href="<API key>.html" /> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><a href="http: <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="namespaces.html"><font color="#004faf">All&nbsp;Namespaces</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td> <td align="right" valign="top" width="230"></td></tr></table><p> [Previous: <a href="<API key>.html">Chapter 11</a>] [<a href="tutorials-tutorial.html">Qt Tutorial</a>] [Next: <a href="<API key>.html">Chapter 13</a>] </p> <h1 class="title">Qt Tutorial 12 - Hanging in the Air the Way Bricks Don't<br /><span class="subtitle"></span> </h1> <p>Files:</p> <ul> <li><a href="<API key>.html">tutorials/tutorial/t12/cannonfield.cpp</a></li> <li><a href="<API key>.html">tutorials/tutorial/t12/cannonfield.h</a></li> <li><a href="<API key>.html">tutorials/tutorial/t12/lcdrange.cpp</a></li> <li><a href="<API key>.html">tutorials/tutorial/t12/lcdrange.h</a></li> <li><a href="<API key>.html">tutorials/tutorial/t12/main.cpp</a></li> <li><a href="<API key>.html">tutorials/tutorial/t12/t12.pro</a></li> </ul> <p align="center"><img src="images/t12.png" alt="Screenshot of Chapter 12" /></p><p>In this example, we extend our <tt>LCDRange</tt> class to include a text label. We also provide something to shoot at.</p> <a name="<API key>"></a> <h2>Line by Line Walkthrough</h2> <a name="t12-lcdrange-h"></a> <h3><a href="<API key>.html">t12/lcdrange.h</a></h3> <p>The <tt>LCDRange</tt> now has a text label.</p> <pre> class QLabel; class QSlider;</pre> <p>We forward declare <a href="qlabel.html">QLabel</a> and <a href="qslider.html">QSlider</a> because we want to use pointers to them in the class definition. We could also use <tt>#include</tt>, but that would slow down compilation for nothing.</p> <pre> class LCDRange : public QWidget { Q_OBJECT public: LCDRange(QWidget *parent = 0); LCDRange(const QString &amp;text, QWidget *parent = 0);</pre> <p>We have added a new constructor that sets the label text in addition to the parent.</p> <pre> QString text() const;</pre> <p>This function returns the label text.</p> <pre> void setText(const QString &amp;text);</pre> <p>This slot sets the label text.</p> <pre> private: void init();</pre> <p>Because we now have two constructors, we have chosen to put the common initialization in the private <tt>init()</tt> function.</p> <pre> QLabel *label;</pre> <p>We also have a new private variable: a <a href="qlabel.html">QLabel</a>. <a href="qlabel.html">QLabel</a> is one of Qt's standard widgets and can show a text or a <a href="qpixmap.html">QPixmap</a> with or without a frame.</p> <a name="t12-lcdrange-cpp"></a> <h3><a href="<API key>.html">t12/lcdrange.cpp</a></h3> <pre> LCDRange::LCDRange(QWidget *parent) : QWidget(parent) { init(); }</pre> <p>This constructor calls the <tt>init()</tt> function, which contains the common initialization code.</p> <pre> LCDRange::LCDRange(const QString &amp;text, QWidget *parent) : QWidget(parent) { init(); setText(text); }</pre> <p>This constructor first calls <tt>init()</tt> and then sets the label text.</p> <pre> void LCDRange::init() { QLCDNumber *lcd = new QLCDNumber(2); lcd-&gt;setSegmentStyle(QLCDNumber::Filled); slider = new QSlider(Qt::Horizontal); slider-&gt;setRange(0, 99); slider-&gt;setValue(0); label = new QLabel; label-&gt;setAlignment(Qt::AlignHCenter | Qt::AlignTop); connect(slider, SIGNAL(valueChanged(int)), lcd, SLOT(display(int))); connect(slider, SIGNAL(valueChanged(int)), this, SIGNAL(valueChanged(int))); QVBoxLayout *layout = new QVBoxLayout; layout-&gt;addWidget(lcd); layout-&gt;addWidget(slider); layout-&gt;addWidget(label); setLayout(layout); setFocusProxy(slider); }</pre> <p>The setup of <tt>lcd</tt> and <tt>slider</tt> is the same as in the previous chapter. Next we create a <a href="qlabel.html">QLabel</a> and tell it to align the contents centered horizontally and to the top vertically. The <a href="qobject.html#connect">QObject::connect</a>() calls have also been taken from the previous chapter.</p> <pre> QString LCDRange::text() const { return label-&gt;text(); }</pre> <p>This function returns the label text.</p> <pre> void LCDRange::setText(const QString &amp;text) { label-&gt;setText(text); }</pre> <p>This function sets the label text.</p> <a name="t12-cannonfield-h"></a> <h3><a href="<API key>.html">t12/cannonfield.h</a></h3> <p>The <tt>CannonField</tt> now has two new signals: <tt>hit()</tt> and <tt>missed()</tt>. In addition, it contains a target.</p> <pre> void newTarget();</pre> <p>This slot creates a target at a new position.</p> <pre> signals: void hit(); void missed();</pre> <p>The <tt>hit()</tt> signal is emitted when a shot hits the target. The <tt>missed()</tt> signal is emitted when the shot moves beyond the right or bottom edge of the widget (i.e&#x2e;, it is certain that it has not and will not hit the target).</p> <pre> void paintTarget(QPainter &amp;painter);</pre> <p>This private function paints the target.</p> <pre> QRect targetRect() const;</pre> <p>This private function returns the enclosing rectangle of the target.</p> <pre> QPoint target;</pre> <p>This private variable contains the center point of the target.</p> <a name="t12-cannonfield-cpp"></a> <h3><a href="<API key>.html">t12/cannonfield.cpp</a></h3> <pre> #include &lt;stdlib.h&gt;</pre> <p>We include the <tt>&lt;stdlib.h&gt;</tt> header file because we need the <tt>qrand()</tt> function.</p> <pre> newTarget();</pre> <p>This line has been added to the constructor. It creates a &quot;random&quot; position for the target. In fact, the <tt>newTarget()</tt> function will try to paint the target. Because we are in a constructor, the <tt>CannonField</tt> widget is invisible. Qt guarantees that no harm is done when calling <a href="qwidget.html#update">QWidget::update</a>() on a hidden widget.</p> <pre> void CannonField::newTarget() { static bool firstTime = true; if (firstTime) { firstTime = false; QTime midnight(0, 0, 0); qsrand(midnight.secsTo(QTime::currentTime())); } target = QPoint(200 + qrand() % 190, 10 + qrand() % 255); update(); }</pre> <p>This private function creates a target center point at a new random position.</p> <p>We use the <tt>qrand()</tt> function to fetch random integers. The <tt>qrand()</tt> function normally returns the same series of numbers each time you run a program. This would make the target appear at the same position every time. To avoid this, we must set a random seed the first time this function is called. The random seed must also be random in order to avoid equal random number series. The solution is to use the number of seconds that have passed since midnight as a pseudo-random value.</p> <p>First we create a static <tt>bool</tt> local variable. A static variable like this one is guaranteed to keep its value between calls to the function.</p> <p>The <tt>if</tt> test will succeed only the first time this function is called because we set <tt>firstTime</tt> to <tt>false</tt> inside the <tt>if</tt> block.</p> <p>Then we create the <a href="qtime.html">QTime</a> object <tt>midnight</tt>, which represents the time 00:00:00. Next we fetch the number of seconds from midnight until now and use it as a random seed. See the documentation for <a href="qdate.html">QDate</a>, <a href="qtime.html">QTime</a>, and <a href="qdatetime.html">QDateTime</a> for more information.</p> <p>Finally we calculate the target's center point. We keep it within the rectangle (<i>x</i> = 200, <i>y</i> = 35, <i>width</i> = 190, <i>height</i> = 255), i.e&#x2e;, the possible <i>x</i> and <i>y</i> values are 200 to 389 and 35 to 289, respectively) in a coordinate system where we put <i>y</i> position 0 at the bottom edge of the widget and let <i>y</i> values increase upwards <i>x</i> is as normal, with 0 at the left edge and with <i>x</i> values increasing to the right.</p> <p>By experimentation we have found this to always be in reach of the shot.</p> <pre> void CannonField::moveShot() { QRegion region = shotRect(); ++timerCount; QRect shotR = shotRect();</pre> <p>This part of the timer event has not changed from the previous chapter.</p> <pre> if (shotR.intersects(targetRect())) { autoShootTimer-&gt;stop(); emit hit();</pre> <p>This <tt>if</tt> statement checks whether the shot rectangle intersects the target rectangle. If it does, the shot has hit the target (ouch!). We stop the shoot timer and emit the <tt>hit()</tt> signal to tell the outside world that a target was destroyed, and return.</p> <p>Note that we could have created a new target on the spot, but because the <tt>CannonField</tt> is a component we leave such decisions to the user of the component.</p> <pre> } else if (shotR.x() &gt; width() || shotR.y() &gt; height()) { autoShootTimer-&gt;stop(); emit missed();</pre> <p>This <tt>if</tt> statement is the same as in the previous chapter, except that it now emits the <tt>missed()</tt> signal to tell the outside world about the failure.</p> <pre> } else { region = region.unite(shotR); } update(region); }</pre> <p>And the rest of the function is as before.</p> <p><tt>CannonField::paintEvent()</tt> is as before, except that this has been added:</p> <pre> paintTarget(painter);</pre> <p>This line makes sure that the target is also painted when necessary.</p> <pre> void CannonField::paintTarget(QPainter &amp;painter) { painter.setPen(Qt::black); painter.setBrush(Qt::red); painter.drawRect(targetRect()); }</pre> <p>This private function paints the target; a rectangle filled with red and with a black outline.</p> <pre> QRect CannonField::targetRect() const { QRect result(0, 0, 20, 10); result.moveCenter(QPoint(target.x(), height() - 1 - target.y())); return result; }</pre> <p>This private function returns the enclosing rectangle of the target. Remember from <tt>newTarget()</tt> that the <tt>target</tt> point uses <i>y</i> coordinate 0 at the bottom of the widget. We calculate the point in widget coordinates before we call <a href="qrect.html#moveCenter">QRect::moveCenter</a>().</p> <p>The reason we have chosen this coordinate mapping is to fix the distance between the target and the bottom of the widget. Remember that the widget can be resized by the user or the program at any time.</p> <a name="t12-main-cpp"></a> <h3><a href="<API key>.html">t12/main.cpp</a></h3> <p>There are no new members in the <tt>MyWidget</tt> class, but we have slightly changed the constructor to set the new <tt>LCDRange</tt> text labels.</p> <pre> LCDRange *angle = new LCDRange(tr(&quot;ANGLE&quot;));</pre> <p>We set the angle text label to &quot;ANGLE&quot;.</p> <pre> LCDRange *force = new LCDRange(tr(&quot;FORCE&quot;));</pre> <p>We set the force text label to &quot;FORCE&quot;.</p> <a name="<API key>"></a> <h2>Running the Application</h2> <p>The <tt>LCDRange</tt> widgets look a bit strange: When resizing <tt>MyWidget</tt>, the built-in layout management in <a href="qvboxlayout.html">QVBoxLayout</a> gives the labels too much space and the rest not enough; making the space between the two <tt>LCDRange</tt> widgets change size. We'll fix that in the next chapter.</p> <a name="exercises"></a> <h2>Exercises</h2> <p>Make a cheat button that, when pressed, makes the <tt>CannonField</tt> display the shot trajectory for five seconds.</p> <p>If you did the &quot;round shot&quot; exercise from the previous chapter, try changing the <tt>shotRect()</tt> to a <tt>shotRegion()</tt> that returns a <a href="qregion.html">QRegion</a> so you can have really accurate collision detection.</p> <p>Make a moving target.</p> <p>Make sure that the target is always created entirely on-screen.</p> <p>Make sure that the widget cannot be resized so that the target isn't visible. [Hint: <a href="qwidget.html#minimumSize-prop">QWidget::setMinimumSize</a>() is your friend.]</p> <p>Not easy; make it possible to have several shots in the air at the same time. [Hint: Make a <tt>Shot</tt> class.]</p> <p> [Previous: <a href="<API key>.html">Chapter 11</a>] [<a href="tutorials-tutorial.html">Qt Tutorial</a>] [Next: <a href="<API key>.html">Chapter 13</a>] </p> <p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td width="30%" align="left">Copyright &copy; 2008 Nokia</td> <td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td> <td width="30%" align="right"><div align="right">Qt 4.4.3</div></td> </tr></table></div></address></body> </html>
/* Embedded CSS Before moving to full version - check twice! NO DUPLICATES */ #icon-wpcf { background: url('../images/logo-32.png') no-repeat; } #icon-wpcf-access { background: url('../images/access-icon-32x32.png') no-repeat; } #icon-wpcf-search { background: url('../images/search_36x34.png') no-repeat; } .wpcf-ajax-loading { background: url('../images/ajax-loader-big.gif') no-repeat; width: 32px; height: 32px; } .<API key> { background: url('../images/ajax-loader-small.gif') no-repeat; width: 16px; height: 16px; } /* FORMS */ .wpcf-form-fieldset { background-color: #ffffff; padding: 0 15px 15px 15px; border: 1px solid #cccccc; border-color: #cccccc; margin: 15px 0 25px 0; } .wpcf-form-fieldset fieldset { margin-bottom: 0; } .wpcf-fields-form fieldset { width: auto; } .wpcf-form-fieldset legend { font-weight: bold; } .wpcf-form-fieldset .legend-collapsed { padding-left: 15px; background-image: url('../images/expand.png'); background-repeat: no-repeat; background-position: 0px 2px; cursor: pointer; } .wpcf-form-fieldset .legend-expanded { padding-left: 15px; background-image: url('../images/collapse.png'); background-repeat: no-repeat; background-position: 0px 3px; cursor: pointer; } .wpcf-form-fieldset .collapsed { display: none; } .wpcf-form-item { margin-bottom: 25px; } .wpcf-form-fieldset .wpcf-form-item:first-child { margin-top: 5px; } .wpcf-form-item .wpcf-form-item { margin-bottom: 0; } .wpcf-form-submit { margin-top: 15px; } .<API key> { font-size: 0.85em; font-style: italic; margin-bottom: 5px; } .<API key> { font-size: 1em; font-style: normal; margin: 10px 0; } .wpcf-form-textarea { width: 100%; } .<API key>, .<API key>, .<API key> { font-size: 1em; font-style: normal; margin-bottom: 5px; } .wpcf-form-label { white-space: nowrap; } .<API key> { font-size: 1em; font-weight: bold; display: block; } .wpcf-form-textfield { width: 200px; } .wpcf-form-item-file label { font-size: 1em; font-weight: bold; display: block; } .<API key> label, .<API key>, .<API key>, .<API key> { font-size: 1em; font-weight: bold; } .<API key> label { display: block; } .wpcf-form-error { background-color: #ffffe0; border: 1px solid #e6db55; padding: 5px 10px; width: auto; margin: 10px 0; display: block; } input.wpcf-form-error { background-color: #F8F8F8; border-color: Red !important; } .<API key> { float: left; width: 250px; margin-top: 0; margin-left: 450px; /* position: absolute;*/ position: fixed; /* THIS IS ALSO SET IN JS AFTER ADDING SCROLL */ clear: both; z-index: 12; } .<API key> fieldset { width: 250px; background-color: #ffffff; } .<API key> a.<API key> { margin: 3px 5px 2px 0; float: left; } .wpcf-fields-form .ui-draggable .wpcf-form-fieldset .wpcf-form-fieldset legend { cursor: pointer; } .wpcf-fields-form .ui-sortable { padding: 0 0 10px 0; } .wpcf-fields-form .<API key> { border: 1px dashed #CCCCCC; width: auto; visibility: visible !important; } .<API key>, .<API key> { float: left; margin-top: 10px; margin-top: 3px; margin-right: 5px; } .<API key> { cursor: move; } .wpcf-fields-form .taxonomy-title { margin-top: 10px; font-style: italic; } /* LIST */ #wpcf_groups_list th { white-space: nowrap; } #<API key> { width: 250px; } #<API key> { width: 200px; } #<API key> { width: 400px; } /* STRANGE */ #ui-datepicker-div { display: none; } .wpcf-shortcode { margin-top: 5px; } .wpcf-pointer { cursor: pointer; } .<API key> { padding: 0; margin: 0; width: 100%; border: 1px solid #D2D2D2; } .<API key> td { padding: 5px 10px; margin: 0; } .<API key> thead tr { background-color: #E8E8E8; font-weight: bold; } .<API key> thead td { border-bottom: 1px solid #D2D2D2; } .<API key> tbody tr:nth-child(odd) { background-color: #F7F7F7; } .<API key> tbody tr:nth-child(even) { background-color: #EEEEEE; } .<API key> td .textfield{ width: 100%; } .<API key> { cursor: move; } /* TYPES FORM */ #<API key>, #<API key>, #<API key>, #<API key>, #<API key>, .<API key> { margin-bottom: 20px; padding-bottom: 5px; } #<API key> td, #<API key> td, #<API key> td, #<API key> td, #<API key> td, .<API key> td { border: none; } #<API key> tbody tr td:first-child { text-align: right; } #<API key> tbody tr:first-child td { padding-top: 10px; } #<API key> input { width: 100%; } #<API key> label { font-weight: normal; } #<API key> tbody table { margin-top: 5px; } #<API key> tbody table td { padding: 0; vertical-align: middle; } #<API key> tbody table tr td:first-child { text-align: right; } #<API key> tbody table label { font-weight: normal; } #<API key> tbody tr td:first-child { text-align: right; } #<API key> tbody label { font-weight: normal; } #<API key> tbody td { vertical-align: middle; } #<API key> .<API key> { font-size: 0.9em; line-height: 1.2em; } #<API key> tbody tr:first-child td { padding-top: 15px; } #<API key> { margin: 0 0 20px 0; } /*CHECKBOXES*/ .<API key> { position: absolute; } .<API key> img { cursor: pointer; } .<API key> legend { background-position: 15px 2px !important; background-repeat: no-repeat; cursor: pointer; padding-left: 30px !important; } .wpcf-message { padding: 0 0.6em; border-radius: 3px 3px 3px 3px; border-style: solid; border-width: 1px; margin: 1em 0 1em 0; } .wpcf-error { background-color: #FFEBE8; border-color: #CC0000; padding: 5px; } .<API key> { margin-bottom: 10px; } .wpcf-help-link { display:inline-block; min-height:19px; height:19px; font-size:11px !important; line-height:19px; min-width:19px; padding-left:20px; padding-top:4px; background:url('../../common/res/images/question.png') no-repeat 0 6px; text-decoration:none !important; position:relative; z-index:100; /*color:#FFFFFF !important;*/ float:right; margin: -20px 45px 0 0; } .wpcf-help-link:hover { text-decoration:underline !important; color:#d54e21 !important; background-position:0 -19px; } .<API key> { position: absolute; margin: -18px 0 0 40px; } .<API key> { position: absolute; margin: -18px 0 0 125px; } .wpcf-loading { width: 20px; height: 16px; background: url('../images/wpspin.gif') no-repeat 2px 0; display: inline-block; } .wpcf-hide { display: none; } .wpcf-show { /*display: block;*/ } /* SETTINGS PAGE */ .horlist { margin-bottom: 12px; } .horlist li { float: left; line-height: 20px; margin-right: 10px; } #wpcf-ajax * { width: auto; } #wpcf-ajax #wpcontent { margin: 0px; } #wpcf-ajax #wpbody-content{ padding: 20px; width: 80%; } #wpcf-ajax #wpfooter { clear: both; display: none; } .<API key> { display: block; padding: 10px 0; outline: 0 !important; border: 0 !important; } .<API key> a:hover, .<API key> a:active, .<API key> a:focus { outline: 0 !important; border: 0 !important; } .modman-inline-table { margin-top: 20px; } .wpcf-pagination-top { margin-bottom: 10px; } .types-ajax #wpwrap { margin-top: 20px; } .types-small-italic { font-size: 0.9em; font-style: italic; } .types-ajax #screen-meta-links, .types-ajax #screen-meta { display: none; }
#include "htckbdhandler.h" #include <QFile> #include <QTextStream> #include <QSocketNotifier> #include <QDebug> #include <fcntl.h> #include <unistd.h> #include <htckbdmap.h> #include <linux/input.h> htcKbdHandler::htcKbdHandler(const QString &device) : modifiers(Qt::NoModifier), capsLock(false) { setObjectName("Htc keyboard Handler"); kbdFD = ::open(device.toLocal8Bit().constData(), O_RDONLY, 0); if (kbdFD >= 0) { m_notify = new QSocketNotifier(kbdFD, QSocketNotifier::Read, this); connect(m_notify, SIGNAL(activated(int)), this, SLOT(processEvent())); } else qWarning("Cannot open %s", device.toLocal8Bit().constData()); } htcKbdHandler::~htcKbdHandler() { } void htcKbdHandler::processEvent() { #define MAX_EVENT 10 struct input_event events[MAX_EVENT]; unsigned int i; int n = read(kbdFD, &events, sizeof(struct input_event) * MAX_EVENT); for (i = 0 ; i < n / sizeof(struct input_event) ; ++i) processEvent(events[i]); } void htcKbdHandler::processEvent(struct input_event event) { static struct input_event previous = { {0, 0}, 0, 0, 0}; static uint previous_nb = 0; struct QWSKeyMap key; if (event.code > keyMSize || event.code == 0) return; #define MIN_REPEAT 5 key = htcuniversalKeyMap[event.code]; if ((event.code == previous.code && (previous.value == 0 ? !event.value : event.value)) && (key.key_code == Qt::Key_Control || key.key_code == Qt::Key_Shift || key.key_code == Qt::Key_CapsLock || key.key_code == Qt::Key_Alt || previous_nb++ <= MIN_REPEAT)) return; if (event.code != previous.code) previous_nb = 0; if (key.key_code == Qt::Key_Control) modifiers ^= Qt::ControlModifier; if (key.key_code == Qt::Key_Shift) modifiers ^= Qt::ShiftModifier; if (key.key_code == Qt::Key_Alt) modifiers ^= Qt::AltModifier; if (key.key_code == Qt::Key_CapsLock && event.value == 0) capsLock = !capsLock; ushort unicode = key.unicode; if (modifiers & Qt::ShiftModifier && !capsLock) unicode = key.shift_unicode; else if (modifiers & Qt::ControlModifier) unicode = key.ctrl_unicode; else if (modifiers & Qt::AltModifier) unicode = key.alt_unicode; else if (capsLock && !(modifiers & Qt::ShiftModifier)) unicode = key.shift_unicode; processKeyEvent(unicode, key.key_code, modifiers, event.value != 0, false); previous = event; }
// <API key>: GPL-2.0+ #include <linux/time.h> #include <linux/fs.h> #include <linux/jbd2.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/pagemap.h> #include <linux/jiffies.h> #include <linux/crc32.h> #include <linux/writeback.h> #include <linux/backing-dev.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/bitops.h> #include <trace/events/jbd2.h> /* * IO end handler for temporary buffer_heads handling writes to the journal. */ static void <API key>(struct buffer_head *bh, int uptodate) { struct buffer_head *orig_bh = bh->b_private; BUFFER_TRACE(bh, ""); if (uptodate) set_buffer_uptodate(bh); else <API key>(bh); if (orig_bh) { clear_bit_unlock(BH_Shadow, &orig_bh->b_state); <API key>(); wake_up_bit(&orig_bh->b_state, BH_Shadow); } unlock_buffer(bh); } /* * When an ext4 file is truncated, it is possible that some pages are not * successfully freed, because they are attached to a committing transaction. * After the transaction commits, these pages are left on the LRU, with no * ->mapping, and with attached buffers. These pages are trivially reclaimable * by the VM, but their apparent absence upsets the VM accounting, and it makes * the numbers in /proc/meminfo look odd. * * So here, we have a buffer which has just come off the forget list. Look to * see if we can strip all buffers from the backing page. * * Called under lock_journal(), and possibly under <API key>. The * caller provided us with a ref against the buffer, and we drop that here. */ static void release_buffer_page(struct buffer_head *bh) { struct page *page; if (buffer_dirty(bh)) goto nope; if (atomic_read(&bh->b_count) != 1) goto nope; page = bh->b_page; if (!page) goto nope; if (page->mapping) goto nope; /* OK, it's a truncated page */ if (!trylock_page(page)) goto nope; get_page(page); __brelse(bh); try_to_free_buffers(page); unlock_page(page); put_page(page); return; nope: __brelse(bh); } static void <API key>(journal_t *j, struct buffer_head *bh) { struct commit_header *h; __u32 csum; if (!<API key>(j)) return; h = (struct commit_header *)(bh->b_data); h->h_chksum_type = 0; h->h_chksum_size = 0; h->h_chksum[0] = 0; csum = jbd2_chksum(j, j->j_csum_seed, bh->b_data, j->j_blocksize); h->h_chksum[0] = cpu_to_be32(csum); } /* * Done it all: now submit the commit record. We should have * cleaned up our previous buffers by now, so if we are in abort * mode we can now just skip the rest of the journal write * entirely. * * Returns 1 if the journal needs to be aborted or 0 on success */ static int <API key>(journal_t *journal, transaction_t *commit_transaction, struct buffer_head **cbh, __u32 crc32_sum) { struct commit_header *tmp; struct buffer_head *bh; int ret; struct timespec64 now; *cbh = NULL; if (is_journal_aborted(journal)) return 0; bh = <API key>(commit_transaction, JBD2_COMMIT_BLOCK); if (!bh) return 1; tmp = (struct commit_header *)bh->b_data; <API key>(&now); tmp->h_commit_sec = cpu_to_be64(now.tv_sec); tmp->h_commit_nsec = cpu_to_be32(now.tv_nsec); if (<API key>(journal)) { tmp->h_chksum_type = JBD2_CRC32_CHKSUM; tmp->h_chksum_size = <API key>; tmp->h_chksum[0] = cpu_to_be32(crc32_sum); } <API key>(journal, bh); BUFFER_TRACE(bh, "submit commit block"); lock_buffer(bh); clear_buffer_dirty(bh); set_buffer_uptodate(bh); bh->b_end_io = <API key>; if (journal->j_flags & JBD2_BARRIER && !<API key>(journal)) ret = submit_bh(REQ_OP_WRITE, REQ_SYNC | REQ_PREFLUSH | REQ_FUA, bh); else ret = submit_bh(REQ_OP_WRITE, REQ_SYNC, bh); *cbh = bh; return ret; } /* * This function along with <API key> * allows to write the commit record asynchronously. */ static int <API key>(journal_t *journal, struct buffer_head *bh) { int ret = 0; clear_buffer_dirty(bh); wait_on_buffer(bh); if (unlikely(!buffer_uptodate(bh))) ret = -EIO; put_bh(bh); /* One for getblk() */ return ret; } /* * write the filemap data using writepage() <API key>. * We don't do block allocation here even for delalloc. We don't * use writepages() because with dealyed allocation we may be doing * block allocation in writepages(). */ static int <API key>(struct address_space *mapping, loff_t dirty_start, loff_t dirty_end) { int ret; struct writeback_control wbc = { .sync_mode = WB_SYNC_ALL, .nr_to_write = mapping->nrpages * 2, .range_start = dirty_start, .range_end = dirty_end, }; ret = generic_writepages(mapping, &wbc); return ret; } /* * Submit all the data buffers of inode associated with the transaction to * disk. * * We are in a committing transaction. Therefore no new inode can be added to * our inode list. We use JI_COMMIT_RUNNING flag to protect inode we currently * operate on from being released while we write out pages. */ static int <API key>(journal_t *journal, transaction_t *commit_transaction) { struct jbd2_inode *jinode; int err, ret = 0; struct address_space *mapping; spin_lock(&journal->j_list_lock); list_for_each_entry(jinode, &commit_transaction->t_inode_list, i_list) { loff_t dirty_start = jinode->i_dirty_start; loff_t dirty_end = jinode->i_dirty_end; if (!(jinode->i_flags & JI_WRITE_DATA)) continue; mapping = jinode->i_vfs_inode->i_mapping; jinode->i_flags |= JI_COMMIT_RUNNING; spin_unlock(&journal->j_list_lock); /* * submit the inode data buffers. We use writepage * instead of writepages. Because writepages can do * block allocation with delalloc. We need to write * only allocated blocks here. */ <API key>(jinode->i_vfs_inode); err = <API key>(mapping, dirty_start, dirty_end); if (!ret) ret = err; spin_lock(&journal->j_list_lock); J_ASSERT(jinode->i_transaction == commit_transaction); jinode->i_flags &= ~JI_COMMIT_RUNNING; smp_mb(); wake_up_bit(&jinode->i_flags, __JI_COMMIT_RUNNING); } spin_unlock(&journal->j_list_lock); return ret; } /* * Wait for data submitted for writeout, refile inodes to proper * transaction if needed. * */ static int <API key>(journal_t *journal, transaction_t *commit_transaction) { struct jbd2_inode *jinode, *next_i; int err, ret = 0; /* For locking, see the comment in <API key>() */ spin_lock(&journal->j_list_lock); list_for_each_entry(jinode, &commit_transaction->t_inode_list, i_list) { loff_t dirty_start = jinode->i_dirty_start; loff_t dirty_end = jinode->i_dirty_end; if (!(jinode->i_flags & JI_WAIT_DATA)) continue; jinode->i_flags |= JI_COMMIT_RUNNING; spin_unlock(&journal->j_list_lock); err = <API key>( jinode->i_vfs_inode->i_mapping, dirty_start, dirty_end); if (!ret) ret = err; spin_lock(&journal->j_list_lock); jinode->i_flags &= ~JI_COMMIT_RUNNING; smp_mb(); wake_up_bit(&jinode->i_flags, __JI_COMMIT_RUNNING); } /* Now refile inode to proper lists */ <API key>(jinode, next_i, &commit_transaction->t_inode_list, i_list) { list_del(&jinode->i_list); if (jinode->i_next_transaction) { jinode->i_transaction = jinode->i_next_transaction; jinode->i_next_transaction = NULL; list_add(&jinode->i_list, &jinode->i_transaction->t_inode_list); } else { jinode->i_transaction = NULL; jinode->i_dirty_start = 0; jinode->i_dirty_end = 0; } } spin_unlock(&journal->j_list_lock); return ret; } static __u32 jbd2_checksum_data(__u32 crc32_sum, struct buffer_head *bh) { struct page *page = bh->b_page; char *addr; __u32 checksum; addr = kmap_atomic(page); checksum = crc32_be(crc32_sum, (void *)(addr + offset_in_page(bh->b_data)), bh->b_size); kunmap_atomic(addr); return checksum; } static void write_tag_block(journal_t *j, journal_block_tag_t *tag, unsigned long long block) { tag->t_blocknr = cpu_to_be32(block & (u32)~0); if (<API key>(j)) tag->t_blocknr_high = cpu_to_be32((block >> 31) >> 1); } static void <API key>(journal_t *j, journal_block_tag_t *tag, struct buffer_head *bh, __u32 sequence) { <API key> *tag3 = (<API key> *)tag; struct page *page = bh->b_page; __u8 *addr; __u32 csum32; __be32 seq; if (!<API key>(j)) return; seq = cpu_to_be32(sequence); addr = kmap_atomic(page); csum32 = jbd2_chksum(j, j->j_csum_seed, (__u8 *)&seq, sizeof(seq)); csum32 = jbd2_chksum(j, csum32, addr + offset_in_page(bh->b_data), bh->b_size); kunmap_atomic(addr); if (<API key>(j)) tag3->t_checksum = cpu_to_be32(csum32); else tag->t_checksum = cpu_to_be16(csum32); } /* * <API key> * * The primary function for committing a transaction to the log. This * function is called by the journal thread to begin a complete commit. */ void <API key>(journal_t *journal) { struct transaction_stats_s stats; transaction_t *commit_transaction; struct journal_head *jh; struct buffer_head *descriptor; struct buffer_head **wbuf = journal->j_wbuf; int bufs; int flags; int err; unsigned long long blocknr; ktime_t start_time; u64 commit_time; char *tagp = NULL; journal_block_tag_t *tag = NULL; int space_left = 0; int first_tag = 0; int tag_flag; int i; int tag_bytes = journal_tag_bytes(journal); struct buffer_head *cbh = NULL; /* For transactional checksums */ __u32 crc32_sum = ~0; struct blk_plug plug; /* Tail of the journal */ unsigned long first_block; tid_t first_tid; int update_tail; int csum_size = 0; LIST_HEAD(io_bufs); LIST_HEAD(log_bufs); if (<API key>(journal)) csum_size = sizeof(struct <API key>); /* * First job: lock down the current transaction and wait for * all outstanding updates to complete. */ /* Do we need to erase the effects of a prior jbd2_journal_flush? */ if (journal->j_flags & JBD2_FLUSHED) { jbd_debug(3, "super block updated\n"); mutex_lock_io(&journal->j_checkpoint_mutex); /* * We hold j_checkpoint_mutex so tail cannot change under us. * We don't need any special data guarantees for writing sb * since journal is empty and it is ok for write to be * flushed only with transaction commit. */ <API key>(journal, journal->j_tail_sequence, journal->j_tail, REQ_SYNC); mutex_unlock(&journal->j_checkpoint_mutex); } else { jbd_debug(3, "superblock not updated\n"); } J_ASSERT(journal-><API key> != NULL); J_ASSERT(journal-><API key> == NULL); commit_transaction = journal-><API key>; <API key>(journal, commit_transaction); jbd_debug(1, "JBD2: starting commit of transaction %d\n", commit_transaction->t_tid); write_lock(&journal->j_state_lock); J_ASSERT(commit_transaction->t_state == T_RUNNING); commit_transaction->t_state = T_LOCKED; <API key>(journal, commit_transaction); stats.run.rs_wait = commit_transaction->t_max_wait; stats.run.rs_request_delay = 0; stats.run.rs_locked = jiffies; if (commit_transaction->t_requested) stats.run.rs_request_delay = jbd2_time_diff(commit_transaction->t_requested, stats.run.rs_locked); stats.run.rs_running = jbd2_time_diff(commit_transaction->t_start, stats.run.rs_locked); spin_lock(&commit_transaction->t_handle_lock); while (atomic_read(&commit_transaction->t_updates)) { DEFINE_WAIT(wait); prepare_to_wait(&journal->j_wait_updates, &wait, <API key>); if (atomic_read(&commit_transaction->t_updates)) { spin_unlock(&commit_transaction->t_handle_lock); write_unlock(&journal->j_state_lock); schedule(); write_lock(&journal->j_state_lock); spin_lock(&commit_transaction->t_handle_lock); } finish_wait(&journal->j_wait_updates, &wait); } spin_unlock(&commit_transaction->t_handle_lock); J_ASSERT (atomic_read(&commit_transaction-><API key>) <= journal-><API key>); /* * First thing we are allowed to do is to discard any remaining * BJ_Reserved buffers. Note, it is _not_ permissible to assume * that there are no such buffers: if a large filesystem * operation like a truncate needs to split itself over multiple * transactions, then it may try to do a <API key>() while * there are still BJ_Reserved buffers outstanding. These must * be released cleanly from the current transaction. * * In this case, the filesystem must still reserve write access * again before modifying the buffer in the new transaction, but * we do not require it to remember exactly which old buffers it * has reserved. This is consistent with the existing behaviour * that multiple <API key>() calls to the same * buffer are perfectly permissible. */ while (commit_transaction->t_reserved_list) { jh = commit_transaction->t_reserved_list; JBUFFER_TRACE(jh, "reserved, unused: refile"); /* * A <API key>()+<API key>() may * leave undo-committed data. */ if (jh->b_committed_data) { struct buffer_head *bh = jh2bh(jh); jbd_lock_bh_state(bh); jbd2_free(jh->b_committed_data, bh->b_size); jh->b_committed_data = NULL; jbd_unlock_bh_state(bh); } <API key>(journal, jh); } /* * Now try to drop any written-back buffers from the journal's * checkpoint lists. We do this *before* commit because it potentially * frees some memory */ spin_lock(&journal->j_list_lock); <API key>(journal, false); spin_unlock(&journal->j_list_lock); jbd_debug(3, "JBD2: commit phase 1\n"); /* * Clear revoked flag to reflect there is no revoked buffers * in the next transaction which is going to be started. */ <API key>(journal); /* * Switch to a new revoke table. */ <API key>(journal); /* * Reserved credits cannot be claimed anymore, free them */ atomic_sub(atomic_read(&journal->j_reserved_credits), &commit_transaction-><API key>); <API key>(journal, commit_transaction); stats.run.rs_flushing = jiffies; stats.run.rs_locked = jbd2_time_diff(stats.run.rs_locked, stats.run.rs_flushing); commit_transaction->t_state = T_FLUSH; journal-><API key> = commit_transaction; journal-><API key> = NULL; start_time = ktime_get(); commit_transaction->t_log_start = journal->j_head; wake_up(&journal-><API key>); write_unlock(&journal->j_state_lock); jbd_debug(3, "JBD2: commit phase 2a\n"); /* * Now start flushing things to disk, in the order they appear * on the transaction lists. Data blocks go first. */ err = <API key>(journal, commit_transaction); if (err) jbd2_journal_abort(journal, err); blk_start_plug(&plug); <API key>(commit_transaction, &log_bufs); jbd_debug(3, "JBD2: commit phase 2b\n"); /* * Way to go: we have now written out all of the data for a * transaction! Now comes the tricky part: we need to write out * metadata. Loop over the transaction's entire buffer list: */ write_lock(&journal->j_state_lock); commit_transaction->t_state = T_COMMIT; write_unlock(&journal->j_state_lock); <API key>(journal, commit_transaction); stats.run.rs_logging = jiffies; stats.run.rs_flushing = jbd2_time_diff(stats.run.rs_flushing, stats.run.rs_logging); stats.run.rs_blocks = atomic_read(&commit_transaction-><API key>); stats.run.rs_blocks_logged = 0; J_ASSERT(commit_transaction->t_nr_buffers <= atomic_read(&commit_transaction-><API key>)); err = 0; bufs = 0; descriptor = NULL; while (commit_transaction->t_buffers) { /* Find the next buffer to be journaled... */ jh = commit_transaction->t_buffers; /* If we're in abort mode, we just un-journal the buffer and release it. */ if (is_journal_aborted(journal)) { <API key>(jh2bh(jh)); JBUFFER_TRACE(jh, "journal is aborting: refile"); <API key>(jh, jh->b_frozen_data ? jh->b_frozen_triggers : jh->b_triggers); <API key>(journal, jh); /* If that was the last one, we need to clean up * any descriptor buffers which may have been * already allocated, even if we are now * aborting. */ if (!commit_transaction->t_buffers) goto start_journal_io; continue; } /* Make sure we have a descriptor block in which to record the metadata buffer. */ if (!descriptor) { J_ASSERT (bufs == 0); jbd_debug(4, "JBD2: get descriptor\n"); descriptor = <API key>( commit_transaction, <API key>); if (!descriptor) { jbd2_journal_abort(journal, -EIO); continue; } jbd_debug(4, "JBD2: got buffer %llu (%p)\n", (unsigned long long)descriptor->b_blocknr, descriptor->b_data); tagp = &descriptor->b_data[sizeof(journal_header_t)]; space_left = descriptor->b_size - sizeof(journal_header_t); first_tag = 1; set_buffer_jwrite(descriptor); set_buffer_dirty(descriptor); wbuf[bufs++] = descriptor; /* Record it so that we can wait for IO completion later */ BUFFER_TRACE(descriptor, "ph3: file as descriptor"); jbd2_file_log_bh(&log_bufs, descriptor); } /* Where is the buffer to be written? */ err = <API key>(journal, &blocknr); /* If the block mapping failed, just abandon the buffer and repeat this loop: we'll fall into the refile-on-abort condition above. */ if (err) { jbd2_journal_abort(journal, err); continue; } /* * start_this_handle() uses <API key> to determine * the free space in the log, but this counter is changed * by <API key>() also. */ atomic_dec(&commit_transaction-><API key>); /* Bump b_count to prevent truncate from stumbling over the shadowed buffer! @@@ This can go if we ever get rid of the shadow pairing of buffers. */ atomic_inc(&jh2bh(jh)->b_count); /* * Make a temporary IO buffer with which to write it out * (this will requeue the metadata buffer to BJ_Shadow). */ set_bit(BH_JWrite, &jh2bh(jh)->b_state); JBUFFER_TRACE(jh, "ph3: write metadata"); flags = <API key>(commit_transaction, jh, &wbuf[bufs], blocknr); if (flags < 0) { jbd2_journal_abort(journal, flags); continue; } jbd2_file_log_bh(&io_bufs, wbuf[bufs]); /* Record the new block's tag in the current descriptor buffer */ tag_flag = 0; if (flags & 1) tag_flag |= JBD2_FLAG_ESCAPE; if (!first_tag) tag_flag |= JBD2_FLAG_SAME_UUID; tag = (journal_block_tag_t *) tagp; write_tag_block(journal, tag, jh2bh(jh)->b_blocknr); tag->t_flags = cpu_to_be16(tag_flag); <API key>(journal, tag, wbuf[bufs], commit_transaction->t_tid); tagp += tag_bytes; space_left -= tag_bytes; bufs++; if (first_tag) { memcpy (tagp, journal->j_uuid, 16); tagp += 16; space_left -= 16; first_tag = 0; } /* If there's no more to do, or if the descriptor is full, let the IO rip! */ if (bufs == journal->j_wbufsize || commit_transaction->t_buffers == NULL || space_left < tag_bytes + 16 + csum_size) { jbd_debug(4, "JBD2: Submit %d IOs\n", bufs); /* Write an end-of-descriptor marker before submitting the IOs. "tag" still points to the last tag we set up. */ tag->t_flags |= cpu_to_be16(JBD2_FLAG_LAST_TAG); start_journal_io: if (descriptor) <API key>(journal, descriptor); for (i = 0; i < bufs; i++) { struct buffer_head *bh = wbuf[i]; /* * Compute checksum. */ if (<API key>(journal)) { crc32_sum = jbd2_checksum_data(crc32_sum, bh); } lock_buffer(bh); clear_buffer_dirty(bh); set_buffer_uptodate(bh); bh->b_end_io = <API key>; submit_bh(REQ_OP_WRITE, REQ_SYNC, bh); } cond_resched(); /* Force a new descriptor to be generated next time round the loop. */ descriptor = NULL; bufs = 0; } } err = <API key>(journal, commit_transaction); if (err) { printk(KERN_WARNING "JBD2: Detected IO errors while flushing file data " "on %s\n", journal->j_devname); if (journal->j_flags & <API key>) jbd2_journal_abort(journal, err); err = 0; } /* * Get current oldest transaction in the log before we issue flush * to the filesystem device. After the flush we can be sure that * blocks of all older transactions are checkpointed to persistent * storage and we will be safe to update journal start in the * superblock with the numbers we get here. */ update_tail = <API key>(journal, &first_tid, &first_block); write_lock(&journal->j_state_lock); if (update_tail) { long freed = first_block - journal->j_tail; if (first_block < journal->j_tail) freed += journal->j_last - journal->j_first; /* Update tail only if we free significant amount of space */ if (freed < journal->j_maxlen / 4) update_tail = 0; } J_ASSERT(commit_transaction->t_state == T_COMMIT); commit_transaction->t_state = T_COMMIT_DFLUSH; write_unlock(&journal->j_state_lock); /* * If the journal is not located on the file system device, * then we must flush the file system device before we issue * the commit record */ if (commit_transaction->t_need_data_flush && (journal->j_fs_dev != journal->j_dev) && (journal->j_flags & JBD2_BARRIER)) blkdev_issue_flush(journal->j_fs_dev, GFP_NOFS, NULL); /* Done it all: now write the commit record asynchronously. */ if (<API key>(journal)) { err = <API key>(journal, commit_transaction, &cbh, crc32_sum); if (err) <API key>(journal); } blk_finish_plug(&plug); /* Lo and behold: we have just managed to send a transaction to the log. Before we can commit it, wait for the IO so far to complete. Control buffers being written are on the transaction's t_log_list queue, and metadata buffers are on the io_bufs list. Wait for the buffers in reverse order. That way we are less likely to be woken up until all IOs have completed, and so we incur less scheduling load. */ jbd_debug(3, "JBD2: commit phase 3\n"); while (!list_empty(&io_bufs)) { struct buffer_head *bh = list_entry(io_bufs.prev, struct buffer_head, b_assoc_buffers); wait_on_buffer(bh); cond_resched(); if (unlikely(!buffer_uptodate(bh))) err = -EIO; jbd2_unfile_log_bh(bh); stats.run.rs_blocks_logged++; BUFFER_TRACE(bh, "dumping temporary bh"); __brelse(bh); J_ASSERT_BH(bh, atomic_read(&bh->b_count) == 0); free_buffer_head(bh); /* We also have to refile the corresponding shadowed buffer */ jh = commit_transaction->t_shadow_list->b_tprev; bh = jh2bh(jh); clear_buffer_jwrite(bh); J_ASSERT_BH(bh, buffer_jbddirty(bh)); J_ASSERT_BH(bh, !buffer_shadow(bh)); /* The metadata is now released for reuse, but we need to remember it against this transaction so that when we finally commit, we can do any checkpointing required. */ JBUFFER_TRACE(jh, "file as BJ_Forget"); <API key>(jh, commit_transaction, BJ_Forget); JBUFFER_TRACE(jh, "brelse shadowed buffer"); __brelse(bh); } J_ASSERT (commit_transaction->t_shadow_list == NULL); jbd_debug(3, "JBD2: commit phase 4\n"); /* Here we wait for the revoke record and descriptor record buffers */ while (!list_empty(&log_bufs)) { struct buffer_head *bh; bh = list_entry(log_bufs.prev, struct buffer_head, b_assoc_buffers); wait_on_buffer(bh); cond_resched(); if (unlikely(!buffer_uptodate(bh))) err = -EIO; BUFFER_TRACE(bh, "ph5: control buffer writeout done: unfile"); clear_buffer_jwrite(bh); jbd2_unfile_log_bh(bh); stats.run.rs_blocks_logged++; __brelse(bh); /* One for getblk */ /* AKPM: bforget here */ } if (err) jbd2_journal_abort(journal, err); jbd_debug(3, "JBD2: commit phase 5\n"); write_lock(&journal->j_state_lock); J_ASSERT(commit_transaction->t_state == T_COMMIT_DFLUSH); commit_transaction->t_state = T_COMMIT_JFLUSH; write_unlock(&journal->j_state_lock); if (!<API key>(journal)) { err = <API key>(journal, commit_transaction, &cbh, crc32_sum); if (err) <API key>(journal); } if (cbh) err = <API key>(journal, cbh); stats.run.rs_blocks_logged++; if (<API key>(journal) && journal->j_flags & JBD2_BARRIER) { blkdev_issue_flush(journal->j_dev, GFP_NOFS, NULL); } if (err) jbd2_journal_abort(journal, err); /* * Now disk caches for filesystem device are flushed so we are safe to * erase checkpointed transactions from the log by updating journal * superblock. */ if (update_tail) <API key>(journal, first_tid, first_block); /* End of a transaction! Finally, we can do checkpoint processing: any buffers committed as a result of this transaction can be removed from any checkpoint list it was on before. */ jbd_debug(3, "JBD2: commit phase 6\n"); J_ASSERT(list_empty(&commit_transaction->t_inode_list)); J_ASSERT(commit_transaction->t_buffers == NULL); J_ASSERT(commit_transaction->t_checkpoint_list == NULL); J_ASSERT(commit_transaction->t_shadow_list == NULL); restart_loop: /* * As there are other places (<API key>()) adding buffers * to this list we have to be careful and hold the j_list_lock. */ spin_lock(&journal->j_list_lock); while (commit_transaction->t_forget) { transaction_t *cp_transaction; struct buffer_head *bh; int try_to_free = 0; jh = commit_transaction->t_forget; spin_unlock(&journal->j_list_lock); bh = jh2bh(jh); /* * Get a reference so that bh cannot be freed before we are * done with it. */ get_bh(bh); jbd_lock_bh_state(bh); J_ASSERT_JH(jh, jh->b_transaction == commit_transaction); /* * If there is undo-protected committed data against * this buffer, then we can remove it now. If it is a * buffer needing such protection, the old frozen_data * field now points to a committed version of the * buffer, so rotate that field to the new committed * data. * * Otherwise, we can just throw away the frozen data now. * * We also know that the frozen data has already fired * its triggers if they exist, so we can clear that too. */ if (jh->b_committed_data) { jbd2_free(jh->b_committed_data, bh->b_size); jh->b_committed_data = NULL; if (jh->b_frozen_data) { jh->b_committed_data = jh->b_frozen_data; jh->b_frozen_data = NULL; jh->b_frozen_triggers = NULL; } } else if (jh->b_frozen_data) { jbd2_free(jh->b_frozen_data, bh->b_size); jh->b_frozen_data = NULL; jh->b_frozen_triggers = NULL; } spin_lock(&journal->j_list_lock); cp_transaction = jh->b_cp_transaction; if (cp_transaction) { JBUFFER_TRACE(jh, "remove from old cp transaction"); cp_transaction->t_chp_stats.cs_dropped++; <API key>(jh); } /* Only re-checkpoint the buffer_head if it is marked * dirty. If the buffer was added to the BJ_Forget list * by jbd2_journal_forget, it may no longer be dirty and * there's no point in keeping a checkpoint record for * it. */ /* * A buffer which has been freed while still being journaled by * a previous transaction. */ if (buffer_freed(bh)) { /* * If the running transaction is the one containing * "add to orphan" operation (b_next_transaction != * NULL), we have to wait for that transaction to * commit before we can really get rid of the buffer. * So just clear b_modified to not confuse transaction * credit accounting and refile the buffer to * BJ_Forget of the running transaction. If the just * committed transaction contains "add to orphan" * operation, we can completely invalidate the buffer * now. We are rather through in that since the * buffer may be still accessible when blocksize < * pagesize and it is attached to the last partial * page. */ jh->b_modified = 0; if (!jh->b_next_transaction) { clear_buffer_freed(bh); <API key>(bh); clear_buffer_mapped(bh); clear_buffer_new(bh); clear_buffer_req(bh); bh->b_bdev = NULL; } } if (buffer_jbddirty(bh)) { JBUFFER_TRACE(jh, "add to new checkpointing trans"); <API key>(jh, commit_transaction); if (is_journal_aborted(journal)) <API key>(bh); } else { J_ASSERT_BH(bh, !buffer_dirty(bh)); /* * The buffer on BJ_Forget list and not jbddirty means * it has been freed by this transaction and hence it * could not have been reallocated until this * transaction has committed. *BUT* it could be * reallocated once we have written all the data to * disk and before we process the buffer on BJ_Forget * list. */ if (!jh->b_next_transaction) try_to_free = 1; } JBUFFER_TRACE(jh, "refile or unfile buffer"); <API key>(jh); jbd_unlock_bh_state(bh); if (try_to_free) release_buffer_page(bh); /* Drops bh reference */ else __brelse(bh); cond_resched_lock(&journal->j_list_lock); } spin_unlock(&journal->j_list_lock); /* * This is a bit sleazy. We use j_list_lock to protect transition * of a transaction into T_FINISHED state and calling * <API key>(). Otherwise we could race with * other checkpointing code processing the transaction... */ write_lock(&journal->j_state_lock); spin_lock(&journal->j_list_lock); /* * Now recheck if some buffers did not get attached to the transaction * while the lock was dropped... */ if (commit_transaction->t_forget) { spin_unlock(&journal->j_list_lock); write_unlock(&journal->j_state_lock); goto restart_loop; } /* Add the transaction to the checkpoint list * <API key>() can not destroy transaction * under us because it is not marked as T_FINISHED yet */ if (journal-><API key> == NULL) { journal-><API key> = commit_transaction; commit_transaction->t_cpnext = commit_transaction; commit_transaction->t_cpprev = commit_transaction; } else { commit_transaction->t_cpnext = journal-><API key>; commit_transaction->t_cpprev = commit_transaction->t_cpnext->t_cpprev; commit_transaction->t_cpnext->t_cpprev = commit_transaction; commit_transaction->t_cpprev->t_cpnext = commit_transaction; } spin_unlock(&journal->j_list_lock); /* Done with this transaction! */ jbd_debug(3, "JBD2: commit phase 7\n"); J_ASSERT(commit_transaction->t_state == T_COMMIT_JFLUSH); commit_transaction->t_start = jiffies; stats.run.rs_logging = jbd2_time_diff(stats.run.rs_logging, commit_transaction->t_start); /* * File the transaction statistics */ stats.ts_tid = commit_transaction->t_tid; stats.run.rs_handle_count = atomic_read(&commit_transaction->t_handle_count); <API key>(journal->j_fs_dev->bd_dev, commit_transaction->t_tid, &stats.run); stats.ts_requested = (commit_transaction->t_requested) ? 1 : 0; commit_transaction->t_state = T_COMMIT_CALLBACK; J_ASSERT(commit_transaction == journal-><API key>); journal->j_commit_sequence = commit_transaction->t_tid; journal-><API key> = NULL; commit_time = ktime_to_ns(ktime_sub(ktime_get(), start_time)); /* * weight the commit time higher than the average time so we don't * react too strongly to vast changes in the commit time */ if (likely(journal-><API key>)) journal-><API key> = (commit_time + journal-><API key>*3) / 4; else journal-><API key> = commit_time; write_unlock(&journal->j_state_lock); if (journal->j_commit_callback) journal->j_commit_callback(journal, commit_transaction); <API key>(journal, commit_transaction); jbd_debug(1, "JBD2: commit %d complete, head %d\n", journal->j_commit_sequence, journal->j_tail_sequence); write_lock(&journal->j_state_lock); spin_lock(&journal->j_list_lock); commit_transaction->t_state = T_FINISHED; /* Check if the transaction can be dropped now that we are finished */ if (commit_transaction->t_checkpoint_list == NULL && commit_transaction-><API key> == NULL) { <API key>(journal, commit_transaction); <API key>(commit_transaction); } spin_unlock(&journal->j_list_lock); write_unlock(&journal->j_state_lock); wake_up(&journal->j_wait_done_commit); /* * Calculate overall stats */ spin_lock(&journal->j_history_lock); journal->j_stats.ts_tid++; journal->j_stats.ts_requested += stats.ts_requested; journal->j_stats.run.rs_wait += stats.run.rs_wait; journal->j_stats.run.rs_request_delay += stats.run.rs_request_delay; journal->j_stats.run.rs_running += stats.run.rs_running; journal->j_stats.run.rs_locked += stats.run.rs_locked; journal->j_stats.run.rs_flushing += stats.run.rs_flushing; journal->j_stats.run.rs_logging += stats.run.rs_logging; journal->j_stats.run.rs_handle_count += stats.run.rs_handle_count; journal->j_stats.run.rs_blocks += stats.run.rs_blocks; journal->j_stats.run.rs_blocks_logged += stats.run.rs_blocks_logged; spin_unlock(&journal->j_history_lock); }
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Tests for file writability * * is_writable() returns TRUE on Windows servers * when you really can't write to the file * as the OS reports to PHP as FALSE only if the * read-only attribute is marked. Ugh? * * @access private * @return void */ function is_really_writable($file) { if (is_dir($file)) { $file = rtrim($file, '/').'/'.md5(rand(1,100)); if (($fp = @fopen($file, 'ab')) === FALSE) { return FALSE; } fclose($fp); @chmod($file, 0777); @unlink($file); return TRUE; } elseif (($fp = @fopen($file, 'ab')) === FALSE) { return FALSE; } fclose($fp); return TRUE; } /** * Class registry * * This function acts as a singleton. If the requested class does not * exist it is instantiated and set to a static variable. If it has * previously been instantiated the variable is returned. * * @access public * @param string the class name being requested * @param bool optional flag that lets classes get loaded but not instantiated * @return object */ function &load_class($class, $instantiate = TRUE) { static $objects = array(); // Does the class exist? If so, we're done... if (isset($objects[$class])) { return $objects[$class]; } // If the requested class does not exist in the application/libraries // folder we'll load the native class from the system/libraries folder. if (file_exists(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT)) { require(BASEPATH.'libraries/'.$class.EXT); require(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT); $is_subclass = TRUE; } else { if (file_exists(APPPATH.'libraries/'.$class.EXT)) { require(APPPATH.'libraries/'.$class.EXT); $is_subclass = FALSE; } else { require(BASEPATH.'libraries/'.$class.EXT); $is_subclass = FALSE; } } if ($instantiate == FALSE) { $objects[$class] = TRUE; return $objects[$class]; } if ($is_subclass == TRUE) { $name = config_item('subclass_prefix').$class; $objects[$class] =& new $name(); return $objects[$class]; } $name = ($class != 'Controller') ? 'CI_'.$class : $class; $objects[$class] =& new $name(); return $objects[$class]; } /** * Loads the main config.php file * * @access private * @return array */ function &get_config() { static $main_conf; if ( ! isset($main_conf)) { if ( ! file_exists(APPPATH.'config/config'.EXT)) { exit('The configuration file config'.EXT.' does not exist.'); } require(APPPATH.'config/config'.EXT); if ( ! isset($config) OR ! is_array($config)) { exit('Your config file does not appear to be formatted correctly.'); } $main_conf[0] =& $config; } return $main_conf[0]; } /** * Gets a config item * * @access public * @return mixed */ function config_item($item) { static $config_item = array(); if ( ! isset($config_item[$item])) { $config =& get_config(); if ( ! isset($config[$item])) { return FALSE; } $config_item[$item] = $config[$item]; } return $config_item[$item]; } /** * Error Handler * * This function lets us invoke the exception class and * display errors using the standard error template located * in application/errors/errors.php * This function will send the error page directly to the * browser and exit. * * @access public * @return void */ function show_error($message) { $error =& load_class('Exceptions'); echo $error->show_error('An Error Was Encountered', $message); exit; } /** * 404 Page Handler * * This function is similar to the show_error() function above * However, instead of the standard error template it displays * 404 errors. * * @access public * @return void */ function show_404($page = '') { $error =& load_class('Exceptions'); $error->show_404($page); exit; } /** * Error Logging Interface * * We use this as a simple mechanism to access the logging * class and send messages to be logged. * * @access public * @return void */ function log_message($level = 'error', $message, $php_error = FALSE) { static $LOG; $config =& get_config(); if ($config['log_threshold'] == 0) { return; } $LOG =& load_class('Log'); $LOG->write_log($level, $message, $php_error); } /** * Exception Handler * * This is the custom exception handler that is declaired at the top * of Codeigniter.php. The main reason we use this is permit * PHP errors to be logged in our own log files since we may * not have access to server logs. Since this function * effectively intercepts PHP errors, however, we also need * to display errors based on the current error_reporting level. * We do that with the use of a PHP error template. * * @access private * @return void */ function _exception_handler($severity, $message, $filepath, $line) { // We don't bother with "strict" notices since they will fill up // the log file with information that isn't normally very // helpful. For example, if you are running PHP 5 and you // use version 4 style class functions (without prefixes // like "public", "private", etc.) you'll get notices telling // you that these have been deprecated. if ($severity == E_STRICT) { return; } $error =& load_class('Exceptions'); // Should we display the error? // We'll get the current error_reporting level and add its bits // with the severity bits to find out. if (($severity & error_reporting()) == $severity) { $error->show_php_error($severity, $message, $filepath, $line); } // Should we log the error? No? We're done... $config =& get_config(); if ($config['log_threshold'] == 0) { return; } $error->log_exception($severity, $message, $filepath, $line); } ?>
/* $Id: opencore_amr.h 4335 2013-01-29 08:09:15Z ming $ */ #ifndef <API key> #define <API key> #include <pjmedia-codec/types.h> /** * @defgroup PJMED_OC_AMR OpenCORE AMR Codec * @ingroup <API key> * @brief AMRCodec wrapper for OpenCORE AMR codec * @{ */ PJ_BEGIN_DECL /** * Bitmask options to be passed during AMR codec factory initialization. */ enum pjmedia_amr_options { PJMEDIA_AMR_NO_NB = 1, /**< Disable narrowband mode. */ PJMEDIA_AMR_NO_WB = 2, /**< Disable wideband mode. */ }; /** * Settings. Use #<API key>/wb_set_config() to * activate. */ typedef struct <API key> { /** * Control whether to use octent align. */ pj_bool_t octet_align; /** * Set the bitrate. */ unsigned bitrate; } <API key>; typedef <API key> <API key>; typedef <API key> <API key>; /** * Initialize and register AMR codec factory to pjmedia endpoint. * * @param endpt The pjmedia endpoint. * @param options Bitmask of pjmedia_amr_options (default=0). * * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) <API key>(pjmedia_endpt* endpt, unsigned options); /** * Initialize and register AMR codec factory using default settings to * pjmedia endpoint. * * @param endpt The pjmedia endpoint. * * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) <API key>(pjmedia_endpt* endpt); /** * Unregister AMR codec factory from pjmedia endpoint and deinitialize * the OpenCORE codec library. * * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) <API key>(void); /** * Initialize and register AMR-NB codec factory to pjmedia endpoint. Calling * this function will automatically initialize AMR codec factory without * the wideband mode (i.e. it is equivalent to calling * #<API key>() with PJMEDIA_AMR_NO_WB). Application * should call #<API key>() instead if wishing to use * both modes. * * @param endpt The pjmedia endpoint. * * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) <API key>(pjmedia_endpt* endpt); /** * Unregister AMR-NB codec factory from pjmedia endpoint and deinitialize * the OpenCORE codec library. * * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) <API key>(void); /** * Set AMR-NB parameters. * * @param cfg The settings; * * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) <API key>( const <API key>* cfg); /** * Set AMR-WB parameters. * * @param cfg The settings; * * @return PJ_SUCCESS on success. */ PJ_DECL(pj_status_t) <API key>( const <API key>* cfg); PJ_END_DECL #endif /* <API key> */
#ifndef QMATRIX4X4_H #define QMATRIX4X4_H #include <QtGui/qvector3d.h> #include <QtGui/qvector4d.h> #include <QtGui/qquaternion.h> #include <QtGui/qgenericmatrix.h> #include <QtCore/qrect.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_MATRIX4X4 class QMatrix; class QTransform; class QVariant; class Q_GUI_EXPORT QMatrix4x4 { public: inline QMatrix4x4() { setToIdentity(); } explicit QMatrix4x4(const qreal *values); inline QMatrix4x4(qreal m11, qreal m12, qreal m13, qreal m14, qreal m21, qreal m22, qreal m23, qreal m24, qreal m31, qreal m32, qreal m33, qreal m34, qreal m41, qreal m42, qreal m43, qreal m44); template <int N, int M> explicit QMatrix4x4(const QGenericMatrix<N, M, qreal>& matrix); QMatrix4x4(const qreal *values, int cols, int rows); QMatrix4x4(const QTransform& transform); QMatrix4x4(const QMatrix& matrix); inline const qreal& operator()(int row, int column) const; inline qreal& operator()(int row, int column); inline QVector4D column(int index) const; inline void setColumn(int index, const QVector4D& value); inline QVector4D row(int index) const; inline void setRow(int index, const QVector4D& value); inline bool isIdentity() const; inline void setToIdentity(); inline void fill(qreal value); qreal determinant() const; QMatrix4x4 inverted(bool *invertible = 0) const; QMatrix4x4 transposed() const; QMatrix3x3 normalMatrix() const; inline QMatrix4x4& operator+=(const QMatrix4x4& other); inline QMatrix4x4& operator-=(const QMatrix4x4& other); inline QMatrix4x4& operator*=(const QMatrix4x4& other); inline QMatrix4x4& operator*=(qreal factor); QMatrix4x4& operator/=(qreal divisor); inline bool operator==(const QMatrix4x4& other) const; inline bool operator!=(const QMatrix4x4& other) const; friend QMatrix4x4 operator+(const QMatrix4x4& m1, const QMatrix4x4& m2); friend QMatrix4x4 operator-(const QMatrix4x4& m1, const QMatrix4x4& m2); friend QMatrix4x4 operator*(const QMatrix4x4& m1, const QMatrix4x4& m2); #ifndef QT_NO_VECTOR3D friend QVector3D operator*(const QMatrix4x4& matrix, const QVector3D& vector); friend QVector3D operator*(const QVector3D& vector, const QMatrix4x4& matrix); #endif #ifndef QT_NO_VECTOR4D friend QVector4D operator*(const QVector4D& vector, const QMatrix4x4& matrix); friend QVector4D operator*(const QMatrix4x4& matrix, const QVector4D& vector); #endif friend QPoint operator*(const QPoint& point, const QMatrix4x4& matrix); friend QPointF operator*(const QPointF& point, const QMatrix4x4& matrix); friend QMatrix4x4 operator-(const QMatrix4x4& matrix); friend QPoint operator*(const QMatrix4x4& matrix, const QPoint& point); friend QPointF operator*(const QMatrix4x4& matrix, const QPointF& point); friend QMatrix4x4 operator*(qreal factor, const QMatrix4x4& matrix); friend QMatrix4x4 operator*(const QMatrix4x4& matrix, qreal factor); friend Q_GUI_EXPORT QMatrix4x4 operator/(const QMatrix4x4& matrix, qreal divisor); friend inline bool qFuzzyCompare(const QMatrix4x4& m1, const QMatrix4x4& m2); #ifndef QT_NO_VECTOR3D void scale(const QVector3D& vector); void translate(const QVector3D& vector); void rotate(qreal angle, const QVector3D& vector); #endif void scale(qreal x, qreal y); void scale(qreal x, qreal y, qreal z); void scale(qreal factor); void translate(qreal x, qreal y); void translate(qreal x, qreal y, qreal z); void rotate(qreal angle, qreal x, qreal y, qreal z = 0.0f); #ifndef QT_NO_QUATERNION void rotate(const QQuaternion& quaternion); #endif void ortho(const QRect& rect); void ortho(const QRectF& rect); void ortho(qreal left, qreal right, qreal bottom, qreal top, qreal nearPlane, qreal farPlane); void frustum(qreal left, qreal right, qreal bottom, qreal top, qreal nearPlane, qreal farPlane); void perspective(qreal angle, qreal aspect, qreal nearPlane, qreal farPlane); #ifndef QT_NO_VECTOR3D void lookAt(const QVector3D& eye, const QVector3D& center, const QVector3D& up); #endif void flipCoordinates(); void copyDataTo(qreal *values) const; QMatrix toAffine() const; QTransform toTransform() const; QTransform toTransform(qreal distanceToPlane) const; QPoint map(const QPoint& point) const; QPointF map(const QPointF& point) const; #ifndef QT_NO_VECTOR3D QVector3D map(const QVector3D& point) const; QVector3D mapVector(const QVector3D& vector) const; #endif #ifndef QT_NO_VECTOR4D QVector4D map(const QVector4D& point) const; #endif QRect mapRect(const QRect& rect) const; QRectF mapRect(const QRectF& rect) const; template <int N, int M> QGenericMatrix<N, M, qreal> toGenericMatrix() const; inline qreal *data(); inline const qreal *data() const { return *m; } inline const qreal *constData() const { return *m; } void optimize(); operator QVariant() const; #ifndef QT_NO_DEBUG_STREAM friend Q_GUI_EXPORT QDebug operator<<(QDebug dbg, const QMatrix4x4 &m); #endif private: qreal m[4][4]; // Column-major order to match OpenGL. int flagBits; // Flag bits from the enum below. enum { Identity = 0x0001, // Identity matrix General = 0x0002, // General matrix, unknown contents Translation = 0x0004, // Contains a simple translation Scale = 0x0008, // Contains a simple scale Rotation = 0x0010 // Contains a simple rotation }; // Construct without initializing identity matrix. QMatrix4x4(int) { flagBits = General; } QMatrix4x4 orthonormalInverse() const; void projectedRotate(qreal angle, qreal x, qreal y, qreal z); friend class QGraphicsRotation; }; Q_DECLARE_TYPEINFO(QMatrix4x4, Q_MOVABLE_TYPE); inline QMatrix4x4::QMatrix4x4 (qreal m11, qreal m12, qreal m13, qreal m14, qreal m21, qreal m22, qreal m23, qreal m24, qreal m31, qreal m32, qreal m33, qreal m34, qreal m41, qreal m42, qreal m43, qreal m44) { m[0][0] = m11; m[0][1] = m21; m[0][2] = m31; m[0][3] = m41; m[1][0] = m12; m[1][1] = m22; m[1][2] = m32; m[1][3] = m42; m[2][0] = m13; m[2][1] = m23; m[2][2] = m33; m[2][3] = m43; m[3][0] = m14; m[3][1] = m24; m[3][2] = m34; m[3][3] = m44; flagBits = General; } template <int N, int M> Q_INLINE_TEMPLATE QMatrix4x4::QMatrix4x4 (const QGenericMatrix<N, M, qreal>& matrix) { const qreal *values = matrix.constData(); for (int matrixCol = 0; matrixCol < 4; ++matrixCol) { for (int matrixRow = 0; matrixRow < 4; ++matrixRow) { if (matrixCol < N && matrixRow < M) m[matrixCol][matrixRow] = values[matrixCol * M + matrixRow]; else if (matrixCol == matrixRow) m[matrixCol][matrixRow] = 1.0f; else m[matrixCol][matrixRow] = 0.0f; } } flagBits = General; } template <int N, int M> QGenericMatrix<N, M, qreal> QMatrix4x4::toGenericMatrix() const { QGenericMatrix<N, M, qreal> result; qreal *values = result.data(); for (int matrixCol = 0; matrixCol < N; ++matrixCol) { for (int matrixRow = 0; matrixRow < M; ++matrixRow) { if (matrixCol < 4 && matrixRow < 4) values[matrixCol * M + matrixRow] = m[matrixCol][matrixRow]; else if (matrixCol == matrixRow) values[matrixCol * M + matrixRow] = 1.0f; else values[matrixCol * M + matrixRow] = 0.0f; } } return result; } inline const qreal& QMatrix4x4::operator()(int aRow, int aColumn) const { Q_ASSERT(aRow >= 0 && aRow < 4 && aColumn >= 0 && aColumn < 4); return m[aColumn][aRow]; } inline qreal& QMatrix4x4::operator()(int aRow, int aColumn) { Q_ASSERT(aRow >= 0 && aRow < 4 && aColumn >= 0 && aColumn < 4); flagBits = General; return m[aColumn][aRow]; } inline QVector4D QMatrix4x4::column(int index) const { Q_ASSERT(index >= 0 && index < 4); return QVector4D(m[index][0], m[index][1], m[index][2], m[index][3]); } inline void QMatrix4x4::setColumn(int index, const QVector4D& value) { Q_ASSERT(index >= 0 && index < 4); m[index][0] = value.x(); m[index][1] = value.y(); m[index][2] = value.z(); m[index][3] = value.w(); flagBits = General; } inline QVector4D QMatrix4x4::row(int index) const { Q_ASSERT(index >= 0 && index < 4); return QVector4D(m[0][index], m[1][index], m[2][index], m[3][index]); } inline void QMatrix4x4::setRow(int index, const QVector4D& value) { Q_ASSERT(index >= 0 && index < 4); m[0][index] = value.x(); m[1][index] = value.y(); m[2][index] = value.z(); m[3][index] = value.w(); flagBits = General; } Q_GUI_EXPORT QMatrix4x4 operator/(const QMatrix4x4& matrix, qreal divisor); inline bool QMatrix4x4::isIdentity() const { if (flagBits == Identity) return true; if (m[0][0] != 1.0f || m[0][1] != 0.0f || m[0][2] != 0.0f) return false; if (m[0][3] != 0.0f || m[1][0] != 0.0f || m[1][1] != 1.0f) return false; if (m[1][2] != 0.0f || m[1][3] != 0.0f || m[2][0] != 0.0f) return false; if (m[2][1] != 0.0f || m[2][2] != 1.0f || m[2][3] != 0.0f) return false; if (m[3][0] != 0.0f || m[3][1] != 0.0f || m[3][2] != 0.0f) return false; return (m[3][3] == 1.0f); } inline void QMatrix4x4::setToIdentity() { m[0][0] = 1.0f; m[0][1] = 0.0f; m[0][2] = 0.0f; m[0][3] = 0.0f; m[1][0] = 0.0f; m[1][1] = 1.0f; m[1][2] = 0.0f; m[1][3] = 0.0f; m[2][0] = 0.0f; m[2][1] = 0.0f; m[2][2] = 1.0f; m[2][3] = 0.0f; m[3][0] = 0.0f; m[3][1] = 0.0f; m[3][2] = 0.0f; m[3][3] = 1.0f; flagBits = Identity; } inline void QMatrix4x4::fill(qreal value) { m[0][0] = value; m[0][1] = value; m[0][2] = value; m[0][3] = value; m[1][0] = value; m[1][1] = value; m[1][2] = value; m[1][3] = value; m[2][0] = value; m[2][1] = value; m[2][2] = value; m[2][3] = value; m[3][0] = value; m[3][1] = value; m[3][2] = value; m[3][3] = value; flagBits = General; } inline QMatrix4x4& QMatrix4x4::operator+=(const QMatrix4x4& other) { m[0][0] += other.m[0][0]; m[0][1] += other.m[0][1]; m[0][2] += other.m[0][2]; m[0][3] += other.m[0][3]; m[1][0] += other.m[1][0]; m[1][1] += other.m[1][1]; m[1][2] += other.m[1][2]; m[1][3] += other.m[1][3]; m[2][0] += other.m[2][0]; m[2][1] += other.m[2][1]; m[2][2] += other.m[2][2]; m[2][3] += other.m[2][3]; m[3][0] += other.m[3][0]; m[3][1] += other.m[3][1]; m[3][2] += other.m[3][2]; m[3][3] += other.m[3][3]; flagBits = General; return *this; } inline QMatrix4x4& QMatrix4x4::operator-=(const QMatrix4x4& other) { m[0][0] -= other.m[0][0]; m[0][1] -= other.m[0][1]; m[0][2] -= other.m[0][2]; m[0][3] -= other.m[0][3]; m[1][0] -= other.m[1][0]; m[1][1] -= other.m[1][1]; m[1][2] -= other.m[1][2]; m[1][3] -= other.m[1][3]; m[2][0] -= other.m[2][0]; m[2][1] -= other.m[2][1]; m[2][2] -= other.m[2][2]; m[2][3] -= other.m[2][3]; m[3][0] -= other.m[3][0]; m[3][1] -= other.m[3][1]; m[3][2] -= other.m[3][2]; m[3][3] -= other.m[3][3]; flagBits = General; return *this; } inline QMatrix4x4& QMatrix4x4::operator*=(const QMatrix4x4& other) { if (flagBits == Identity) { *this = other; return *this; } else if (other.flagBits == Identity) { return *this; } else { *this = *this * other; return *this; } } inline QMatrix4x4& QMatrix4x4::operator*=(qreal factor) { m[0][0] *= factor; m[0][1] *= factor; m[0][2] *= factor; m[0][3] *= factor; m[1][0] *= factor; m[1][1] *= factor; m[1][2] *= factor; m[1][3] *= factor; m[2][0] *= factor; m[2][1] *= factor; m[2][2] *= factor; m[2][3] *= factor; m[3][0] *= factor; m[3][1] *= factor; m[3][2] *= factor; m[3][3] *= factor; flagBits = General; return *this; } inline bool QMatrix4x4::operator==(const QMatrix4x4& other) const { return m[0][0] == other.m[0][0] && m[0][1] == other.m[0][1] && m[0][2] == other.m[0][2] && m[0][3] == other.m[0][3] && m[1][0] == other.m[1][0] && m[1][1] == other.m[1][1] && m[1][2] == other.m[1][2] && m[1][3] == other.m[1][3] && m[2][0] == other.m[2][0] && m[2][1] == other.m[2][1] && m[2][2] == other.m[2][2] && m[2][3] == other.m[2][3] && m[3][0] == other.m[3][0] && m[3][1] == other.m[3][1] && m[3][2] == other.m[3][2] && m[3][3] == other.m[3][3]; } inline bool QMatrix4x4::operator!=(const QMatrix4x4& other) const { return m[0][0] != other.m[0][0] || m[0][1] != other.m[0][1] || m[0][2] != other.m[0][2] || m[0][3] != other.m[0][3] || m[1][0] != other.m[1][0] || m[1][1] != other.m[1][1] || m[1][2] != other.m[1][2] || m[1][3] != other.m[1][3] || m[2][0] != other.m[2][0] || m[2][1] != other.m[2][1] || m[2][2] != other.m[2][2] || m[2][3] != other.m[2][3] || m[3][0] != other.m[3][0] || m[3][1] != other.m[3][1] || m[3][2] != other.m[3][2] || m[3][3] != other.m[3][3]; } inline QMatrix4x4 operator+(const QMatrix4x4& m1, const QMatrix4x4& m2) { QMatrix4x4 m(1); m.m[0][0] = m1.m[0][0] + m2.m[0][0]; m.m[0][1] = m1.m[0][1] + m2.m[0][1]; m.m[0][2] = m1.m[0][2] + m2.m[0][2]; m.m[0][3] = m1.m[0][3] + m2.m[0][3]; m.m[1][0] = m1.m[1][0] + m2.m[1][0]; m.m[1][1] = m1.m[1][1] + m2.m[1][1]; m.m[1][2] = m1.m[1][2] + m2.m[1][2]; m.m[1][3] = m1.m[1][3] + m2.m[1][3]; m.m[2][0] = m1.m[2][0] + m2.m[2][0]; m.m[2][1] = m1.m[2][1] + m2.m[2][1]; m.m[2][2] = m1.m[2][2] + m2.m[2][2]; m.m[2][3] = m1.m[2][3] + m2.m[2][3]; m.m[3][0] = m1.m[3][0] + m2.m[3][0]; m.m[3][1] = m1.m[3][1] + m2.m[3][1]; m.m[3][2] = m1.m[3][2] + m2.m[3][2]; m.m[3][3] = m1.m[3][3] + m2.m[3][3]; return m; } inline QMatrix4x4 operator-(const QMatrix4x4& m1, const QMatrix4x4& m2) { QMatrix4x4 m(1); m.m[0][0] = m1.m[0][0] - m2.m[0][0]; m.m[0][1] = m1.m[0][1] - m2.m[0][1]; m.m[0][2] = m1.m[0][2] - m2.m[0][2]; m.m[0][3] = m1.m[0][3] - m2.m[0][3]; m.m[1][0] = m1.m[1][0] - m2.m[1][0]; m.m[1][1] = m1.m[1][1] - m2.m[1][1]; m.m[1][2] = m1.m[1][2] - m2.m[1][2]; m.m[1][3] = m1.m[1][3] - m2.m[1][3]; m.m[2][0] = m1.m[2][0] - m2.m[2][0]; m.m[2][1] = m1.m[2][1] - m2.m[2][1]; m.m[2][2] = m1.m[2][2] - m2.m[2][2]; m.m[2][3] = m1.m[2][3] - m2.m[2][3]; m.m[3][0] = m1.m[3][0] - m2.m[3][0]; m.m[3][1] = m1.m[3][1] - m2.m[3][1]; m.m[3][2] = m1.m[3][2] - m2.m[3][2]; m.m[3][3] = m1.m[3][3] - m2.m[3][3]; return m; } inline QMatrix4x4 operator*(const QMatrix4x4& m1, const QMatrix4x4& m2) { if (m1.flagBits == QMatrix4x4::Identity) return m2; else if (m2.flagBits == QMatrix4x4::Identity) return m1; QMatrix4x4 m(1); m.m[0][0] = m1.m[0][0] * m2.m[0][0] + m1.m[1][0] * m2.m[0][1] + m1.m[2][0] * m2.m[0][2] + m1.m[3][0] * m2.m[0][3]; m.m[0][1] = m1.m[0][1] * m2.m[0][0] + m1.m[1][1] * m2.m[0][1] + m1.m[2][1] * m2.m[0][2] + m1.m[3][1] * m2.m[0][3]; m.m[0][2] = m1.m[0][2] * m2.m[0][0] + m1.m[1][2] * m2.m[0][1] + m1.m[2][2] * m2.m[0][2] + m1.m[3][2] * m2.m[0][3]; m.m[0][3] = m1.m[0][3] * m2.m[0][0] + m1.m[1][3] * m2.m[0][1] + m1.m[2][3] * m2.m[0][2] + m1.m[3][3] * m2.m[0][3]; m.m[1][0] = m1.m[0][0] * m2.m[1][0] + m1.m[1][0] * m2.m[1][1] + m1.m[2][0] * m2.m[1][2] + m1.m[3][0] * m2.m[1][3]; m.m[1][1] = m1.m[0][1] * m2.m[1][0] + m1.m[1][1] * m2.m[1][1] + m1.m[2][1] * m2.m[1][2] + m1.m[3][1] * m2.m[1][3]; m.m[1][2] = m1.m[0][2] * m2.m[1][0] + m1.m[1][2] * m2.m[1][1] + m1.m[2][2] * m2.m[1][2] + m1.m[3][2] * m2.m[1][3]; m.m[1][3] = m1.m[0][3] * m2.m[1][0] + m1.m[1][3] * m2.m[1][1] + m1.m[2][3] * m2.m[1][2] + m1.m[3][3] * m2.m[1][3]; m.m[2][0] = m1.m[0][0] * m2.m[2][0] + m1.m[1][0] * m2.m[2][1] + m1.m[2][0] * m2.m[2][2] + m1.m[3][0] * m2.m[2][3]; m.m[2][1] = m1.m[0][1] * m2.m[2][0] + m1.m[1][1] * m2.m[2][1] + m1.m[2][1] * m2.m[2][2] + m1.m[3][1] * m2.m[2][3]; m.m[2][2] = m1.m[0][2] * m2.m[2][0] + m1.m[1][2] * m2.m[2][1] + m1.m[2][2] * m2.m[2][2] + m1.m[3][2] * m2.m[2][3]; m.m[2][3] = m1.m[0][3] * m2.m[2][0] + m1.m[1][3] * m2.m[2][1] + m1.m[2][3] * m2.m[2][2] + m1.m[3][3] * m2.m[2][3]; m.m[3][0] = m1.m[0][0] * m2.m[3][0] + m1.m[1][0] * m2.m[3][1] + m1.m[2][0] * m2.m[3][2] + m1.m[3][0] * m2.m[3][3]; m.m[3][1] = m1.m[0][1] * m2.m[3][0] + m1.m[1][1] * m2.m[3][1] + m1.m[2][1] * m2.m[3][2] + m1.m[3][1] * m2.m[3][3]; m.m[3][2] = m1.m[0][2] * m2.m[3][0] + m1.m[1][2] * m2.m[3][1] + m1.m[2][2] * m2.m[3][2] + m1.m[3][2] * m2.m[3][3]; m.m[3][3] = m1.m[0][3] * m2.m[3][0] + m1.m[1][3] * m2.m[3][1] + m1.m[2][3] * m2.m[3][2] + m1.m[3][3] * m2.m[3][3]; return m; } #ifndef QT_NO_VECTOR3D inline QVector3D operator*(const QVector3D& vector, const QMatrix4x4& matrix) { qreal x, y, z, w; x = vector.x() * matrix.m[0][0] + vector.y() * matrix.m[0][1] + vector.z() * matrix.m[0][2] + matrix.m[0][3]; y = vector.x() * matrix.m[1][0] + vector.y() * matrix.m[1][1] + vector.z() * matrix.m[1][2] + matrix.m[1][3]; z = vector.x() * matrix.m[2][0] + vector.y() * matrix.m[2][1] + vector.z() * matrix.m[2][2] + matrix.m[2][3]; w = vector.x() * matrix.m[3][0] + vector.y() * matrix.m[3][1] + vector.z() * matrix.m[3][2] + matrix.m[3][3]; if (w == 1.0f) return QVector3D(x, y, z); else return QVector3D(x / w, y / w, z / w); } inline QVector3D operator*(const QMatrix4x4& matrix, const QVector3D& vector) { qreal x, y, z, w; if (matrix.flagBits == QMatrix4x4::Identity) { return vector; } else if (matrix.flagBits == QMatrix4x4::Translation) { return QVector3D(vector.x() + matrix.m[3][0], vector.y() + matrix.m[3][1], vector.z() + matrix.m[3][2]); } else if (matrix.flagBits == (QMatrix4x4::Translation | QMatrix4x4::Scale)) { return QVector3D(vector.x() * matrix.m[0][0] + matrix.m[3][0], vector.y() * matrix.m[1][1] + matrix.m[3][1], vector.z() * matrix.m[2][2] + matrix.m[3][2]); } else if (matrix.flagBits == QMatrix4x4::Scale) { return QVector3D(vector.x() * matrix.m[0][0], vector.y() * matrix.m[1][1], vector.z() * matrix.m[2][2]); } else { x = vector.x() * matrix.m[0][0] + vector.y() * matrix.m[1][0] + vector.z() * matrix.m[2][0] + matrix.m[3][0]; y = vector.x() * matrix.m[0][1] + vector.y() * matrix.m[1][1] + vector.z() * matrix.m[2][1] + matrix.m[3][1]; z = vector.x() * matrix.m[0][2] + vector.y() * matrix.m[1][2] + vector.z() * matrix.m[2][2] + matrix.m[3][2]; w = vector.x() * matrix.m[0][3] + vector.y() * matrix.m[1][3] + vector.z() * matrix.m[2][3] + matrix.m[3][3]; if (w == 1.0f) return QVector3D(x, y, z); else return QVector3D(x / w, y / w, z / w); } } #endif #ifndef QT_NO_VECTOR4D inline QVector4D operator*(const QVector4D& vector, const QMatrix4x4& matrix) { qreal x, y, z, w; x = vector.x() * matrix.m[0][0] + vector.y() * matrix.m[0][1] + vector.z() * matrix.m[0][2] + vector.w() * matrix.m[0][3]; y = vector.x() * matrix.m[1][0] + vector.y() * matrix.m[1][1] + vector.z() * matrix.m[1][2] + vector.w() * matrix.m[1][3]; z = vector.x() * matrix.m[2][0] + vector.y() * matrix.m[2][1] + vector.z() * matrix.m[2][2] + vector.w() * matrix.m[2][3]; w = vector.x() * matrix.m[3][0] + vector.y() * matrix.m[3][1] + vector.z() * matrix.m[3][2] + vector.w() * matrix.m[3][3]; return QVector4D(x, y, z, w); } inline QVector4D operator*(const QMatrix4x4& matrix, const QVector4D& vector) { qreal x, y, z, w; x = vector.x() * matrix.m[0][0] + vector.y() * matrix.m[1][0] + vector.z() * matrix.m[2][0] + vector.w() * matrix.m[3][0]; y = vector.x() * matrix.m[0][1] + vector.y() * matrix.m[1][1] + vector.z() * matrix.m[2][1] + vector.w() * matrix.m[3][1]; z = vector.x() * matrix.m[0][2] + vector.y() * matrix.m[1][2] + vector.z() * matrix.m[2][2] + vector.w() * matrix.m[3][2]; w = vector.x() * matrix.m[0][3] + vector.y() * matrix.m[1][3] + vector.z() * matrix.m[2][3] + vector.w() * matrix.m[3][3]; return QVector4D(x, y, z, w); } #endif inline QPoint operator*(const QPoint& point, const QMatrix4x4& matrix) { qreal xin, yin; qreal x, y, w; xin = point.x(); yin = point.y(); x = xin * matrix.m[0][0] + yin * matrix.m[0][1] + matrix.m[0][3]; y = xin * matrix.m[1][0] + yin * matrix.m[1][1] + matrix.m[1][3]; w = xin * matrix.m[3][0] + yin * matrix.m[3][1] + matrix.m[3][3]; if (w == 1.0f) return QPoint(qRound(x), qRound(y)); else return QPoint(qRound(x / w), qRound(y / w)); } inline QPointF operator*(const QPointF& point, const QMatrix4x4& matrix) { qreal xin, yin; qreal x, y, w; xin = point.x(); yin = point.y(); x = xin * matrix.m[0][0] + yin * matrix.m[0][1] + matrix.m[0][3]; y = xin * matrix.m[1][0] + yin * matrix.m[1][1] + matrix.m[1][3]; w = xin * matrix.m[3][0] + yin * matrix.m[3][1] + matrix.m[3][3]; if (w == 1.0f) { return QPointF(qreal(x), qreal(y)); } else { return QPointF(qreal(x / w), qreal(y / w)); } } inline QPoint operator*(const QMatrix4x4& matrix, const QPoint& point) { qreal xin, yin; qreal x, y, w; xin = point.x(); yin = point.y(); if (matrix.flagBits == QMatrix4x4::Identity) { return point; } else if (matrix.flagBits == QMatrix4x4::Translation) { return QPoint(qRound(xin + matrix.m[3][0]), qRound(yin + matrix.m[3][1])); } else if (matrix.flagBits == (QMatrix4x4::Translation | QMatrix4x4::Scale)) { return QPoint(qRound(xin * matrix.m[0][0] + matrix.m[3][0]), qRound(yin * matrix.m[1][1] + matrix.m[3][1])); } else if (matrix.flagBits == QMatrix4x4::Scale) { return QPoint(qRound(xin * matrix.m[0][0]), qRound(yin * matrix.m[1][1])); } else { x = xin * matrix.m[0][0] + yin * matrix.m[1][0] + matrix.m[3][0]; y = xin * matrix.m[0][1] + yin * matrix.m[1][1] + matrix.m[3][1]; w = xin * matrix.m[0][3] + yin * matrix.m[1][3] + matrix.m[3][3]; if (w == 1.0f) return QPoint(qRound(x), qRound(y)); else return QPoint(qRound(x / w), qRound(y / w)); } } inline QPointF operator*(const QMatrix4x4& matrix, const QPointF& point) { qreal xin, yin; qreal x, y, w; xin = point.x(); yin = point.y(); if (matrix.flagBits == QMatrix4x4::Identity) { return point; } else if (matrix.flagBits == QMatrix4x4::Translation) { return QPointF(xin + matrix.m[3][0], yin + matrix.m[3][1]); } else if (matrix.flagBits == (QMatrix4x4::Translation | QMatrix4x4::Scale)) { return QPointF(xin * matrix.m[0][0] + matrix.m[3][0], yin * matrix.m[1][1] + matrix.m[3][1]); } else if (matrix.flagBits == QMatrix4x4::Scale) { return QPointF(xin * matrix.m[0][0], yin * matrix.m[1][1]); } else { x = xin * matrix.m[0][0] + yin * matrix.m[1][0] + matrix.m[3][0]; y = xin * matrix.m[0][1] + yin * matrix.m[1][1] + matrix.m[3][1]; w = xin * matrix.m[0][3] + yin * matrix.m[1][3] + matrix.m[3][3]; if (w == 1.0f) { return QPointF(qreal(x), qreal(y)); } else { return QPointF(qreal(x / w), qreal(y / w)); } } } inline QMatrix4x4 operator-(const QMatrix4x4& matrix) { QMatrix4x4 m(1); m.m[0][0] = -matrix.m[0][0]; m.m[0][1] = -matrix.m[0][1]; m.m[0][2] = -matrix.m[0][2]; m.m[0][3] = -matrix.m[0][3]; m.m[1][0] = -matrix.m[1][0]; m.m[1][1] = -matrix.m[1][1]; m.m[1][2] = -matrix.m[1][2]; m.m[1][3] = -matrix.m[1][3]; m.m[2][0] = -matrix.m[2][0]; m.m[2][1] = -matrix.m[2][1]; m.m[2][2] = -matrix.m[2][2]; m.m[2][3] = -matrix.m[2][3]; m.m[3][0] = -matrix.m[3][0]; m.m[3][1] = -matrix.m[3][1]; m.m[3][2] = -matrix.m[3][2]; m.m[3][3] = -matrix.m[3][3]; return m; } inline QMatrix4x4 operator*(qreal factor, const QMatrix4x4& matrix) { QMatrix4x4 m(1); m.m[0][0] = matrix.m[0][0] * factor; m.m[0][1] = matrix.m[0][1] * factor; m.m[0][2] = matrix.m[0][2] * factor; m.m[0][3] = matrix.m[0][3] * factor; m.m[1][0] = matrix.m[1][0] * factor; m.m[1][1] = matrix.m[1][1] * factor; m.m[1][2] = matrix.m[1][2] * factor; m.m[1][3] = matrix.m[1][3] * factor; m.m[2][0] = matrix.m[2][0] * factor; m.m[2][1] = matrix.m[2][1] * factor; m.m[2][2] = matrix.m[2][2] * factor; m.m[2][3] = matrix.m[2][3] * factor; m.m[3][0] = matrix.m[3][0] * factor; m.m[3][1] = matrix.m[3][1] * factor; m.m[3][2] = matrix.m[3][2] * factor; m.m[3][3] = matrix.m[3][3] * factor; return m; } inline QMatrix4x4 operator*(const QMatrix4x4& matrix, qreal factor) { QMatrix4x4 m(1); m.m[0][0] = matrix.m[0][0] * factor; m.m[0][1] = matrix.m[0][1] * factor; m.m[0][2] = matrix.m[0][2] * factor; m.m[0][3] = matrix.m[0][3] * factor; m.m[1][0] = matrix.m[1][0] * factor; m.m[1][1] = matrix.m[1][1] * factor; m.m[1][2] = matrix.m[1][2] * factor; m.m[1][3] = matrix.m[1][3] * factor; m.m[2][0] = matrix.m[2][0] * factor; m.m[2][1] = matrix.m[2][1] * factor; m.m[2][2] = matrix.m[2][2] * factor; m.m[2][3] = matrix.m[2][3] * factor; m.m[3][0] = matrix.m[3][0] * factor; m.m[3][1] = matrix.m[3][1] * factor; m.m[3][2] = matrix.m[3][2] * factor; m.m[3][3] = matrix.m[3][3] * factor; return m; } inline bool qFuzzyCompare(const QMatrix4x4& m1, const QMatrix4x4& m2) { return qFuzzyCompare(m1.m[0][0], m2.m[0][0]) && qFuzzyCompare(m1.m[0][1], m2.m[0][1]) && qFuzzyCompare(m1.m[0][2], m2.m[0][2]) && qFuzzyCompare(m1.m[0][3], m2.m[0][3]) && qFuzzyCompare(m1.m[1][0], m2.m[1][0]) && qFuzzyCompare(m1.m[1][1], m2.m[1][1]) && qFuzzyCompare(m1.m[1][2], m2.m[1][2]) && qFuzzyCompare(m1.m[1][3], m2.m[1][3]) && qFuzzyCompare(m1.m[2][0], m2.m[2][0]) && qFuzzyCompare(m1.m[2][1], m2.m[2][1]) && qFuzzyCompare(m1.m[2][2], m2.m[2][2]) && qFuzzyCompare(m1.m[2][3], m2.m[2][3]) && qFuzzyCompare(m1.m[3][0], m2.m[3][0]) && qFuzzyCompare(m1.m[3][1], m2.m[3][1]) && qFuzzyCompare(m1.m[3][2], m2.m[3][2]) && qFuzzyCompare(m1.m[3][3], m2.m[3][3]); } inline QPoint QMatrix4x4::map(const QPoint& point) const { return *this * point; } inline QPointF QMatrix4x4::map(const QPointF& point) const { return *this * point; } #ifndef QT_NO_VECTOR3D inline QVector3D QMatrix4x4::map(const QVector3D& point) const { return *this * point; } inline QVector3D QMatrix4x4::mapVector(const QVector3D& vector) const { if (flagBits == Identity || flagBits == Translation) { return vector; } else if (flagBits == Scale || flagBits == (Translation | Scale)) { return QVector3D(vector.x() * m[0][0], vector.y() * m[1][1], vector.z() * m[2][2]); } else { return QVector3D(vector.x() * m[0][0] + vector.y() * m[1][0] + vector.z() * m[2][0], vector.x() * m[0][1] + vector.y() * m[1][1] + vector.z() * m[2][1], vector.x() * m[0][2] + vector.y() * m[1][2] + vector.z() * m[2][2]); } } #endif #ifndef QT_NO_VECTOR4D inline QVector4D QMatrix4x4::map(const QVector4D& point) const { return *this * point; } #endif inline qreal *QMatrix4x4::data() { // We have to assume that the caller will modify the matrix elements, // so we flip it over to "General" mode. flagBits = General; return *m; } #ifndef QT_NO_DEBUG_STREAM Q_GUI_EXPORT QDebug operator<<(QDebug dbg, const QMatrix4x4 &m); #endif #ifndef QT_NO_DATASTREAM Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QMatrix4x4 &); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QMatrix4x4 &); #endif #ifdef QT_DEPRECATED template <int N, int M> QT_DEPRECATED QMatrix4x4 <API key>(const QGenericMatrix<N, M, qreal>& matrix) { return QMatrix4x4(matrix.constData(), N, M); } template <int N, int M> QT_DEPRECATED QGenericMatrix<N, M, qreal> <API key>(const QMatrix4x4& matrix) { QGenericMatrix<N, M, qreal> result; const qreal *m = matrix.constData(); qreal *values = result.data(); for (int col = 0; col < N; ++col) { for (int row = 0; row < M; ++row) { if (col < 4 && row < 4) values[col * M + row] = m[col * 4 + row]; else if (col == row) values[col * M + row] = 1.0f; else values[col * M + row] = 0.0f; } } return result; } #endif #endif QT_END_NAMESPACE QT_END_HEADER #endif
<?php $installer = $this; /* @var $installer <API key> */ $installer->startSetup(); $installer->getConnection()->addColumn($this->getTable('<API key>'), '<API key>', 'tinyint(1) unsigned NOT NULL DEFAULT 0'); $installer->endSetup();
#include <linux/version.h> #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,38)) #ifndef AUTOCONF_INCLUDED #include <linux/config.h> #endif #endif #if defined(SUPPORT_DRI_DRM) #define PVR_MOD_STATIC #else #if defined(LDM_PLATFORM) #define <API key> #define PVR_LDM_MODULE #else #if defined(LDM_PCI) #define PVR_LDM_PCI_MODULE #define PVR_LDM_MODULE #endif #endif #define PVR_MOD_STATIC static #endif #if defined(<API key>) #if !defined(NO_HARDWARE) #define <API key> #endif #endif #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/proc_fs.h> #if defined(SUPPORT_DRI_DRM) #include <drm/drmP.h> #if defined(<API key>) #include "env_perproc.h" #endif #endif #if defined(<API key>) #include <linux/platform_device.h> #endif #if defined(PVR_LDM_PCI_MODULE) #include <linux/pci.h> #endif #if defined(DEBUG) && defined(<API key>) #include <asm/uaccess.h> #endif #include "img_defs.h" #include "services.h" #include "kerneldisplay.h" #include "kernelbuffer.h" #include "syscommon.h" #include "pvrmmap.h" #include "mutils.h" #include "mm.h" #include "mmap.h" #include "mutex.h" #include "pvr_debug.h" #include "srvkm.h" #include "perproc.h" #include "handle.h" #include "pvr_bridge_km.h" #include "proc.h" #include "pvrmodule.h" #include "private_data.h" #include "lock.h" #include "linkage.h" #if defined(SUPPORT_DRI_DRM) #include "pvr_drm.h" #endif #define DRVNAME PVRSRV_MODNAME #define DEVNAME PVRSRV_MODNAME #if defined(SUPPORT_DRI_DRM) #define PRIVATE_DATA(pFile) ((pFile)->driver_priv) #else #define PRIVATE_DATA(pFile) ((pFile)->private_data) #endif <API key>(DEVNAME); #if defined(PVRSRV_NEED_PVR_DPF) #include <linux/moduleparam.h> extern IMG_UINT32 gPVRDebugLevel; module_param(gPVRDebugLevel, uint, 0644); MODULE_PARM_DESC(gPVRDebugLevel, "Sets the level of debug output (default 0x7)"); #endif EXPORT_SYMBOL(<API key>); EXPORT_SYMBOL(<API key>); #if defined(PVR_LDM_MODULE) static struct class *psPvrClass; #endif #if !defined(SUPPORT_DRI_DRM) static int AssignedMajorNumber; static int PVRSRVOpen(struct inode* pInode, struct file* pFile); static int PVRSRVRelease(struct inode* pInode, struct file* pFile); static struct file_operations pvrsrv_fops = { .owner=THIS_MODULE, .unlocked_ioctl = <API key>, .open=PVRSRVOpen, .release=PVRSRVRelease, .mmap=PVRMMap, }; #endif PVRSRV_LINUX_MUTEX gPVRSRVLock; IMG_UINT32 gui32ReleasePID; #if defined(DEBUG) && defined(<API key>) static IMG_UINT32 gPVRPowerLevel; #endif #if defined(PVR_LDM_MODULE) #if defined(<API key>) #define LDM_DEV struct platform_device #define LDM_DRV struct platform_driver #endif #if defined(PVR_LDM_PCI_MODULE) #define LDM_DEV struct pci_dev #define LDM_DRV struct pci_driver #endif #if defined(<API key>) static int PVRSRVDriverRemove(LDM_DEV *device); static int PVRSRVDriverProbe(LDM_DEV *device); #endif #if defined(PVR_LDM_PCI_MODULE) static void PVRSRVDriverRemove(LDM_DEV *device); static int PVRSRVDriverProbe(LDM_DEV *device, const struct pci_device_id *id); #endif static int PVRSRVDriverSuspend(LDM_DEV *device, pm_message_t state); static void <API key>(LDM_DEV *device); static int PVRSRVDriverResume(LDM_DEV *device); #if defined(PVR_LDM_PCI_MODULE) struct pci_device_id powervr_id_table[] __devinitdata = { {PCI_DEVICE(<API key>, <API key>)}, #if defined (<API key>) {PCI_DEVICE(<API key>, <API key>)}, #endif {0} }; MODULE_DEVICE_TABLE(pci, powervr_id_table); #endif #if defined(<API key>) static struct platform_device_id powervr_id_table[] __devinitdata = { {SYS_SGX_DEV_NAME, 0}, {} }; #endif static LDM_DRV powervr_driver = { #if defined(<API key>) .driver = { .name = DRVNAME, }, #endif #if defined(PVR_LDM_PCI_MODULE) .name = DRVNAME, #endif #if defined(PVR_LDM_PCI_MODULE) || defined(<API key>) .id_table = powervr_id_table, #endif .probe = PVRSRVDriverProbe, #if defined(<API key>) .remove = PVRSRVDriverRemove, #endif #if defined(PVR_LDM_PCI_MODULE) .remove = __devexit_p(PVRSRVDriverRemove), #endif .suspend = PVRSRVDriverSuspend, .resume = PVRSRVDriverResume, .shutdown = <API key>, }; LDM_DEV *gpsPVRLDMDev; #if defined(MODULE) && defined(<API key>) && \ !defined(<API key>) static void PVRSRVDeviceRelease(struct device unref__ *pDevice) { } static struct platform_device powervr_device = { .name = DEVNAME, .id = -1, .dev = { .release = PVRSRVDeviceRelease } }; #endif #if defined(<API key>) static int PVRSRVDriverProbe(LDM_DEV *pDevice) #endif #if defined(PVR_LDM_PCI_MODULE) static int __devinit PVRSRVDriverProbe(LDM_DEV *pDevice, const struct pci_device_id *id) #endif { SYS_DATA *psSysData; PVR_TRACE(("PVRSRVDriverProbe(pDevice=%p)", pDevice)); #if 0 if (<API key>((IMG_PVOID)pDevice) != PVRSRV_OK) { return -EINVAL; } #endif psSysData = <API key>(); if ( psSysData == IMG_NULL) { gpsPVRLDMDev = pDevice; if (SysInitialise() != PVRSRV_OK) { return -ENODEV; } } return 0; } #if defined (<API key>) static int PVRSRVDriverRemove(LDM_DEV *pDevice) #endif #if defined(PVR_LDM_PCI_MODULE) static void __devexit PVRSRVDriverRemove(LDM_DEV *pDevice) #endif { SYS_DATA *psSysData; PVR_TRACE(("PVRSRVDriverRemove(pDevice=%p)", pDevice)); SysAcquireData(&psSysData); #if defined(DEBUG) && defined(<API key>) if (gPVRPowerLevel != 0) { if (<API key>(<API key>) == PVRSRV_OK) { gPVRPowerLevel = 0; } } #endif (void) SysDeinitialise(psSysData); gpsPVRLDMDev = IMG_NULL; #if 0 if (<API key>((IMG_PVOID)pDevice) != PVRSRV_OK) { return -EINVAL; } #endif #if defined (<API key>) return 0; #endif #if defined (PVR_LDM_PCI_MODULE) return; #endif } #endif #if defined(PVR_LDM_MODULE) || defined(<API key>) PVR_MOD_STATIC void <API key>(LDM_DEV *pDevice) { PVR_TRACE(("<API key>(pDevice=%p)", pDevice)); (void) <API key>(<API key>); } #endif #if defined(PVR_LDM_MODULE) || defined(SUPPORT_DRI_DRM) #if defined(SUPPORT_DRI_DRM) && !defined(<API key>) int PVRSRVDriverSuspend(struct drm_device *pDevice, pm_message_t state) #else PVR_MOD_STATIC int PVRSRVDriverSuspend(LDM_DEV *pDevice, pm_message_t state) #endif { #if !(defined(DEBUG) && defined(<API key>) && !defined(SUPPORT_DRI_DRM)) PVR_TRACE(( "PVRSRVDriverSuspend(pDevice=%p)", pDevice)); if (<API key>(<API key>) != PVRSRV_OK) { return -EINVAL; } #endif return 0; } #if defined(SUPPORT_DRI_DRM) && !defined(<API key>) int PVRSRVDriverResume(struct drm_device *pDevice) #else PVR_MOD_STATIC int PVRSRVDriverResume(LDM_DEV *pDevice) #endif { #if !(defined(DEBUG) && defined(<API key>) && !defined(SUPPORT_DRI_DRM)) PVR_TRACE(("PVRSRVDriverResume(pDevice=%p)", pDevice)); if (<API key>(<API key>) != PVRSRV_OK) { return -EINVAL; } #endif return 0; } #endif #if defined(DEBUG) && defined(<API key>) && !defined(SUPPORT_DRI_DRM) IMG_INT <API key>(struct file *file, const IMG_CHAR *buffer, IMG_UINT32 count, IMG_VOID *data) { IMG_CHAR data_buffer[2]; IMG_UINT32 PVRPowerLevel; if (count != sizeof(data_buffer)) { return -EINVAL; } else { if (copy_from_user(data_buffer, buffer, count)) return -EINVAL; if (data_buffer[count - 1] != '\n') return -EINVAL; PVRPowerLevel = data_buffer[0] - '0'; if (PVRPowerLevel != gPVRPowerLevel) { if (PVRPowerLevel != 0) { if (<API key>(<API key>) != PVRSRV_OK) { return -EINVAL; } } else { if (<API key>(<API key>) != PVRSRV_OK) { return -EINVAL; } } gPVRPowerLevel = PVRPowerLevel; } } return (count); } void <API key>(struct seq_file *sfile,void* el) { seq_printf(sfile, "%lu\n", gPVRPowerLevel); } #endif #if defined(SUPPORT_DRI_DRM) int PVRSRVOpen(struct drm_device unref__ *dev, struct drm_file *pFile) #else static int PVRSRVOpen(struct inode unref__ * pInode, struct file *pFile) #endif { <API key> *psPrivateData; IMG_HANDLE hBlockAlloc; int iRet = -ENOMEM; PVRSRV_ERROR eError; IMG_UINT32 ui32PID; #if defined(SUPPORT_DRI_DRM) && defined(<API key>) <API key> *psEnvPerProc; #endif LinuxLockMutex(&gPVRSRVLock); ui32PID = <API key>(); if (<API key>(ui32PID, 0) != PVRSRV_OK) goto err_unlock; #if defined(SUPPORT_DRI_DRM) && defined(<API key>) psEnvPerProc = <API key>(ui32PID); if (psEnvPerProc == IMG_NULL) { PVR_DPF((PVR_DBG_ERROR, "%s: No per-process private data", __FUNCTION__)); goto err_unlock; } #endif eError = OSAllocMem(<API key>, sizeof(<API key>), (IMG_PVOID *)&psPrivateData, &hBlockAlloc, "File Private Data"); if(eError != PVRSRV_OK) goto err_unlock; #if defined (<API key>) psPrivateData->hKernelMemInfo = 0; #else psPrivateData->hKernelMemInfo = NULL; #endif #if defined(SUPPORT_DRI_DRM) && defined(<API key>) psPrivateData->psDRMFile = pFile; list_add_tail(&psPrivateData->sDRMAuthListItem, &psEnvPerProc->sDRMAuthListHead); #endif psPrivateData->ui32OpenPID = ui32PID; psPrivateData->hBlockAlloc = hBlockAlloc; PRIVATE_DATA(pFile) = psPrivateData; iRet = 0; err_unlock: LinuxUnLockMutex(&gPVRSRVLock); return iRet; } #if defined(SUPPORT_DRI_DRM) void PVRSRVRelease(void *pvPrivData) #else static int PVRSRVRelease(struct inode unref__ * pInode, struct file *pFile) #endif { <API key> *psPrivateData; LinuxLockMutex(&gPVRSRVLock); #if defined(SUPPORT_DRI_DRM) psPrivateData = (<API key> *)pvPrivData; #else psPrivateData = PRIVATE_DATA(pFile); #endif if (psPrivateData != IMG_NULL) { #if defined(SUPPORT_DRI_DRM) && defined(<API key>) list_del(&psPrivateData->sDRMAuthListItem); #endif gui32ReleasePID = psPrivateData->ui32OpenPID; <API key>(psPrivateData->ui32OpenPID); gui32ReleasePID = 0; OSFreeMem(<API key>, sizeof(<API key>), psPrivateData, psPrivateData->hBlockAlloc); #if !defined(SUPPORT_DRI_DRM) PRIVATE_DATA(pFile) = IMG_NULL; #endif } LinuxUnLockMutex(&gPVRSRVLock); #if !defined(SUPPORT_DRI_DRM) return 0; #endif } #if defined(SUPPORT_DRI_DRM) int PVRCore_Init(void) #else static int __init PVRCore_Init(void) #endif { int error; #if !defined(PVR_LDM_MODULE) PVRSRV_ERROR eError; #else struct device *psDev; #endif #if !defined(SUPPORT_DRI_DRM) PVRDPFInit(); #endif PVR_TRACE(("PVRCore_Init")); LinuxInitMutex(&gPVRSRVLock); if (CreateProcEntries ()) { error = -ENOMEM; return error; } if (PVROSFuncInit() != PVRSRV_OK) { error = -ENOMEM; goto init_failed; } PVRLinuxMUtilsInit(); if(LinuxMMInit() != PVRSRV_OK) { error = -ENOMEM; goto init_failed; } LinuxBridgeInit(); PVRMMapInit(); #if defined(PVR_LDM_MODULE) #if defined(<API key>) if ((error = <API key>(&powervr_driver)) != 0) { PVR_DPF((PVR_DBG_ERROR, "PVRCore_Init: unable to register platform driver (%d)", error)); goto init_failed; } #if defined(MODULE) && !defined(<API key>) if ((error = <API key>(&powervr_device)) != 0) { <API key>(&powervr_driver); PVR_DPF((PVR_DBG_ERROR, "PVRCore_Init: unable to register platform device (%d)", error)); goto init_failed; } #endif #endif #if defined(PVR_LDM_PCI_MODULE) if ((error = pci_register_driver(&powervr_driver)) != 0) { PVR_DPF((PVR_DBG_ERROR, "PVRCore_Init: unable to register PCI driver (%d)", error)); goto init_failed; } #endif #else if ((eError = SysInitialise()) != PVRSRV_OK) { error = -ENODEV; #if defined(TCF_REV) && (TCF_REV == 110) if(eError == <API key>) { printk("\nAtlas wrapper (FPGA image) version mismatch"); error = -ENODEV; } #endif goto init_failed; } #endif #if !defined(SUPPORT_DRI_DRM) AssignedMajorNumber = register_chrdev(0, DEVNAME, &pvrsrv_fops); if (AssignedMajorNumber <= 0) { PVR_DPF((PVR_DBG_ERROR, "PVRCore_Init: unable to get major number")); error = -EBUSY; goto sys_deinit; } PVR_TRACE(("PVRCore_Init: major device %d", AssignedMajorNumber)); #endif #if defined(PVR_LDM_MODULE) psPvrClass = class_create(THIS_MODULE, "pvr"); if (IS_ERR(psPvrClass)) { PVR_DPF((PVR_DBG_ERROR, "PVRCore_Init: unable to create class (%ld)", PTR_ERR(psPvrClass))); error = -EBUSY; goto unregister_device; } psDev = device_create(psPvrClass, NULL, MKDEV(AssignedMajorNumber, 0), #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,26)) NULL, #endif DEVNAME); if (IS_ERR(psDev)) { PVR_DPF((PVR_DBG_ERROR, "PVRCore_Init: unable to create device (%ld)", PTR_ERR(psDev))); error = -EBUSY; goto destroy_class; } #endif return 0; #if defined(PVR_LDM_MODULE) destroy_class: class_destroy(psPvrClass); unregister_device: unregister_chrdev((IMG_UINT)AssignedMajorNumber, DRVNAME); #endif #if !defined(SUPPORT_DRI_DRM) sys_deinit: #endif #if defined(PVR_LDM_MODULE) #if defined(PVR_LDM_PCI_MODULE) <API key>(&powervr_driver); #endif #if defined (<API key>) #if defined(MODULE) && !defined(<API key>) <API key>(&powervr_device); #endif <API key>(&powervr_driver); #endif #else { SYS_DATA *psSysData; psSysData = <API key>(); if (psSysData != IMG_NULL) { (void) SysDeinitialise(psSysData); } } #endif init_failed: PVRMMapCleanup(); LinuxMMCleanup(); LinuxBridgeDeInit(); PVROSFuncDeInit(); RemoveProcEntries(); return error; } #if defined(SUPPORT_DRI_DRM) void PVRCore_Cleanup(void) #else static void __exit PVRCore_Cleanup(void) #endif { #if !defined(PVR_LDM_MODULE) SYS_DATA *psSysData; #endif PVR_TRACE(("PVRCore_Cleanup")); #if !defined(PVR_LDM_MODULE) SysAcquireData(&psSysData); #endif #if defined(PVR_LDM_MODULE) device_destroy(psPvrClass, MKDEV(AssignedMajorNumber, 0)); class_destroy(psPvrClass); #endif #if !defined(SUPPORT_DRI_DRM) #if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22)) if ( #endif unregister_chrdev((IMG_UINT)AssignedMajorNumber, DRVNAME) #if !(LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22)) ; #else ) { PVR_DPF((PVR_DBG_ERROR," can't unregister device major %d", AssignedMajorNumber)); } #endif #endif #if defined(PVR_LDM_MODULE) #if defined(PVR_LDM_PCI_MODULE) <API key>(&powervr_driver); #endif #if defined (<API key>) #if defined(MODULE) && !defined(<API key>) <API key>(&powervr_device); #endif <API key>(&powervr_driver); #endif #else #if defined(DEBUG) && defined(<API key>) if (gPVRPowerLevel != 0) { if (<API key>(<API key>) == PVRSRV_OK) { gPVRPowerLevel = 0; } } #endif (void) SysDeinitialise(psSysData); #endif PVRMMapCleanup(); LinuxMMCleanup(); LinuxBridgeDeInit(); PVROSFuncDeInit(); RemoveProcEntries(); PVR_TRACE(("PVRCore_Cleanup: unloading")); } #if !defined(SUPPORT_DRI_DRM) module_init(PVRCore_Init); module_exit(PVRCore_Cleanup); #endif
#include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/irq.h> #include <linux/miscdevice.h> #include <asm/uaccess.h> #include <linux/delay.h> #include <linux/input.h> #include <linux/workqueue.h> #include <linux/freezer.h> #include <mach/rt5501.h> #include <linux/mutex.h> #include <linux/debugfs.h> #include <linux/gpio.h> #include <linux/module.h> #include <linux/mfd/pm8xxx/pm8921.h> #include <linux/mfd/pm8xxx/pm8921.h> #include <mach/htc_headset_mgr.h> #include <linux/wakelock.h> #include <mach/htc_acoustic_pmic.h> #include <linux/jiffies.h> #undef pr_info #undef pr_err #define pr_info(fmt, ...) pr_aud_info(fmt, ##__VA_ARGS__) #define pr_err(fmt, ...) pr_aud_err(fmt, ##__VA_ARGS__) #ifdef <API key> #define DEBUG (1) #else #define DEBUG (1) #endif #define AMP_ON_CMD_LEN 7 #define RETRY_CNT 5 #define DRIVER_NAME "RT5501" struct headset_query { struct mutex mlock; struct mutex gpiolock; struct delayed_work hs_imp_detec_work; struct wake_lock hs_wake_lock; struct wake_lock gpio_wake_lock; enum <API key> hs_qstatus; enum RT5501_STATUS rt5501_status; enum HEADSET_OM headsetom; enum RT5501_Mode curmode; enum AMP_GPIO_STATUS gpiostatus; enum AMP_S4_STATUS s4status; int action_on; int gpio_off_cancel; struct mutex actionlock; struct delayed_work volume_ramp_work; struct delayed_work gpio_off_work; }; static struct i2c_client *this_client; static struct <API key> *pdata; static int rt5501Connect = 0; static int MFG_MODE = 0; struct rt5501_config_data rt5501_config_data; static struct mutex hp_amp_lock; static int rt5501_opened; static int last_spkamp_state; struct rt5501_config RT5501_AMP_ON = {6,{{0x1,0x1c},{0x2,0x00},{0x7,0x7f},{0x9,0x1},{0xa,0x0},{0xb,0xc7},}}; struct rt5501_config RT5501_AMP_INIT = {11,{{0,0xc0},{0x81,0x30},{0x87,0xf6},{0x93,0x8d},{0x95,0x7d},{0xa4,0x52},\ {0x96,0xae},{0x97,0x13},{0x99,0x35},{0x9b,0x68},{0x9d,0x68},}}; struct rt5501_config RT5501_AMP_MUTE = {1,{{0x1,0xC7},}};; struct rt5501_config RT5501_AMP_OFF = {1,{{0x0,0x1},}}; static int rt5501_write_reg(u8 reg, u8 val); static int <API key>(char *txData, int length); static int rt5501_i2c_read(char *rxData, int length); static void hs_imp_detec_func(struct work_struct *work); static int <API key>(char *rxData, unsigned char addr); static int rt5501_i2c_write(struct rt5501_reg_data *txData, int length); static void set_amp(int on, struct rt5501_config *i2c_command); struct headset_query rt5501_query; static struct workqueue_struct *hs_wq; static struct workqueue_struct *ramp_wq; static struct workqueue_struct *gpio_wq; static int high_imp = 0; #if 0 static int query_playback(void *pdata) { return 0; } #endif static int <API key>(int on) { if(on) { pr_info("%s: headset in ++\n",__func__); mutex_lock(&rt5501_query.mlock); rt5501_query.hs_qstatus = <API key>; rt5501_query.headsetom = <API key>; mutex_unlock(&rt5501_query.mlock); <API key>(&rt5501_query.hs_imp_detec_work); mutex_lock(&rt5501_query.gpiolock); mutex_lock(&rt5501_query.mlock); if(rt5501_query.rt5501_status == RT5501_PLAYBACK) { if(high_imp) { rt5501_write_reg(1,0x7); rt5501_write_reg(0xb1,0x81); } else { rt5501_write_reg(1,0xc7); } last_spkamp_state = 0; pr_info("%s: OFF\n", __func__); rt5501_query.rt5501_status = RT5501_SUSPEND; } pr_info("%s: headset in --\n",__func__); mutex_unlock(&rt5501_query.mlock); mutex_unlock(&rt5501_query.gpiolock); queue_delayed_work(hs_wq,&rt5501_query.hs_imp_detec_work,msecs_to_jiffies(5)); pr_info("%s: headset in --2\n",__func__); } else { pr_info("%s: headset remove ++\n",__func__); flush_work_sync(&rt5501_query.volume_ramp_work.work); mutex_lock(&rt5501_query.mlock); rt5501_query.hs_qstatus = RT5501_QUERY_OFF; rt5501_query.headsetom = <API key>; mutex_unlock(&rt5501_query.mlock); <API key>(&rt5501_query.hs_imp_detec_work); mutex_lock(&rt5501_query.gpiolock); mutex_lock(&rt5501_query.mlock); if(rt5501_query.rt5501_status == RT5501_PLAYBACK) { if(high_imp) { rt5501_write_reg(1,0x7); rt5501_write_reg(0xb1,0x81); } else { rt5501_write_reg(1,0xc7); } last_spkamp_state = 0; pr_info("%s: OFF\n", __func__); rt5501_query.rt5501_status = RT5501_SUSPEND; } rt5501_query.curmode = RT5501_MODE_OFF; pr_info("%s: headset remove --1\n",__func__); if(high_imp) { int closegpio = 0; if((rt5501_query.gpiostatus == AMP_GPIO_OFF) && pdata->gpio_rt5501_spk_en) { if(rt5501_query.s4status == AMP_S4_AUTO) { <API key>(); rt5501_query.s4status = AMP_S4_PWM; msleep(1); } pr_info("%s: enable gpio %d\n",__func__,pdata->gpio_rt5501_spk_en); <API key>(pdata->gpio_rt5501_spk_en, 1); rt5501_query.gpiostatus = AMP_GPIO_ON; closegpio = 1; msleep(1); } pr_info("%s: reset rt5501\n",__func__); rt5501_write_reg(0x0,0x4); mdelay(1); rt5501_write_reg(0x1,0xc7); high_imp = 0; if(closegpio && (rt5501_query.gpiostatus == AMP_GPIO_ON) && pdata->gpio_rt5501_spk_en) { pr_info("%s: disable gpio %d\n",__func__,pdata->gpio_rt5501_spk_en); <API key>(pdata->gpio_rt5501_spk_en, 0); rt5501_query.gpiostatus = AMP_GPIO_OFF; if(rt5501_query.s4status == AMP_S4_PWM) { <API key>(); rt5501_query.s4status = AMP_S4_AUTO; } } } mutex_unlock(&rt5501_query.mlock); mutex_unlock(&rt5501_query.gpiolock); pr_info("%s: headset remove --2\n",__func__); } return 0; } static int rt5501_write_reg(u8 reg, u8 val) { int err; struct i2c_msg msg[1]; unsigned char data[2]; msg->addr = this_client->addr; msg->flags = 0; msg->len = 2; msg->buf = data; data[0] = reg; data[1] = val; pr_info("%s: write reg 0x%x val 0x%x\n",__func__,data[0],data[1]); err = i2c_transfer(this_client->adapter, msg, 1); if (err >= 0) return 0; else { pr_info("%s: write error error %d\n",__func__,err); return err; } } static int rt5501_i2c_write(struct rt5501_reg_data *txData, int length) { int i, retry, pass = 0; char buf[2]; struct i2c_msg msg[] = { { .addr = this_client->addr, .flags = 0, .len = 2, .buf = buf, }, }; for (i = 0; i < length; i++) { buf[0] = txData[i].addr; buf[1] = txData[i].val; #if DEBUG pr_info("%s:i2c_write addr 0x%x val 0x%x\n", __func__,buf[0], buf[1]); #endif msg->buf = buf; retry = RETRY_CNT; pass = 0; while (retry if (i2c_transfer(this_client->adapter, msg, 1) < 0) { pr_err("%s: I2C transfer error %d retry %d\n", __func__, i, retry); msleep(20); } else { pass = 1; break; } } if (pass == 0) { pr_err("I2C transfer error, retry fail\n"); return -EIO; } } return 0; } static int <API key>(char *txData, int length) { int i, retry, pass = 0; char buf[2]; struct i2c_msg msg[] = { { .addr = this_client->addr, .flags = 0, .len = 2, .buf = buf, }, }; for (i = 0; i < length; i++) { buf[0] = i; buf[1] = txData[i]; #if DEBUG pr_info("i2c_write %d=%x\n", i, buf[1]); #endif msg->buf = buf; retry = RETRY_CNT; pass = 0; while (retry if (i2c_transfer(this_client->adapter, msg, 1) < 0) { pr_err("%s: I2C transfer error %d retry %d\n", __func__, i, retry); msleep(20); } else { pass = 1; break; } } if (pass == 0) { pr_err("I2C transfer error, retry fail\n"); return -EIO; } } return 0; } static int rt5501_i2c_read(char *rxData, int length) { int rc; struct i2c_msg msgs[] = { { .addr = this_client->addr, .flags = I2C_M_RD, .len = length, .buf = rxData, }, }; rc = i2c_transfer(this_client->adapter, msgs, 1); if (rc < 0) { pr_err("%s: transfer error %d\n", __func__, rc); return rc; } { int i = 0; for (i = 0; i < length; i++) pr_info("i2c_read %s: rx[%d] = 0x%x\n", __func__, i, \ rxData[i]); } return 0; } static int <API key>(char *rxData, unsigned char addr) { int rc; struct i2c_msg msgs[] = { { .addr = this_client->addr, .flags = 0, .len = 1, .buf = rxData, }, { .addr = this_client->addr, .flags = I2C_M_RD, .len = 1, .buf = rxData, }, }; if(!rxData) return -1; *rxData = addr; rc = i2c_transfer(this_client->adapter, &msgs[0], 1); if (rc < 0) { pr_err("%s: transfer error %d\n", __func__, rc); return rc; } rc = i2c_transfer(this_client->adapter, &msgs[1], 1); if (rc < 0) { pr_err("%s: transfer error %d\n", __func__, rc); return rc; } pr_info("%s:i2c_read addr 0x%x value = 0x%x\n", __func__, addr, *rxData); return 0; } static int rt5501_open(struct inode *inode, struct file *file) { int rc = 0; mutex_lock(&hp_amp_lock); if (rt5501_opened) { pr_err("%s: busy\n", __func__); rc = -EBUSY; goto done; } rt5501_opened = 1; done: mutex_unlock(&hp_amp_lock); return rc; } static int rt5501_release(struct inode *inode, struct file *file) { mutex_lock(&hp_amp_lock); rt5501_opened = 0; mutex_unlock(&hp_amp_lock); return 0; } #if 0 static int init_rt5501(void) { int ret; ret = rt5501_i2c_write(RT5501_AMP_INIT.reg, RT5501_AMP_INIT.reg_len); if(ret < 0) { pr_err("init rt5501 error %d\n",ret); return ret; } #if 0 ret = rt5501_i2c_write(RT5501_AMP_ON.reg, RT5501_AMP_ON.reg_len); if(ret < 0) { pr_err("init rt5501 to playback error %d\n",ret); return ret; } ret = rt5501_i2c_write(RT5501_AMP_MUTE.reg, RT5501_AMP_MUTE.reg_len); if(ret < 0) { pr_err("init rt5501 to mute error %d\n",ret); return ret; } ret = rt5501_i2c_write(RT5501_AMP_OFF.reg, RT5501_AMP_OFF.reg_len); if(ret < 0) { pr_err("init rt5501 to off error %d\n",ret); return ret; } #endif return ret; } #endif static void hs_imp_gpio_off(struct work_struct *work) { u64 timeout = get_jiffies_64() + 5*HZ; wake_lock(&rt5501_query.gpio_wake_lock); while(1) { if(time_after64(get_jiffies_64(),timeout)) break; else if(rt5501_query.gpio_off_cancel) { wake_unlock(&rt5501_query.gpio_wake_lock); return; } else msleep(10); } mutex_lock(&rt5501_query.gpiolock); pr_info("%s: disable gpio %d\n",__func__,pdata->gpio_rt5501_spk_en); <API key>(pdata->gpio_rt5501_spk_en, 0); rt5501_query.gpiostatus = AMP_GPIO_OFF; if(rt5501_query.s4status == AMP_S4_PWM) { <API key>(); rt5501_query.s4status = AMP_S4_AUTO; } mutex_unlock(&rt5501_query.gpiolock); wake_unlock(&rt5501_query.gpio_wake_lock); } static void hs_imp_detec_func(struct work_struct *work) { struct headset_query *hs; char temp[8]={0x1,}; int ret; int rt5501_status; pr_info("%s: read rt5501 hs imp \n",__func__); hs = container_of(work, struct headset_query, hs_imp_detec_work.work); wake_lock(&hs->hs_wake_lock); rt5501_query.gpio_off_cancel = 1; <API key>(&rt5501_query.gpio_off_work); mutex_lock(&hs->gpiolock); mutex_lock(&hs->mlock); if(hs->hs_qstatus != <API key>) { mutex_unlock(&hs->mlock); mutex_unlock(&hs->gpiolock); wake_unlock(&hs->hs_wake_lock); return; } if((hs->gpiostatus == AMP_GPIO_OFF) && pdata->gpio_rt5501_spk_en) { if(rt5501_query.s4status == AMP_S4_AUTO) { <API key>(); rt5501_query.s4status = AMP_S4_PWM; msleep(1); } pr_info("%s: enable gpio %d\n",__func__,pdata->gpio_rt5501_spk_en); <API key>(pdata->gpio_rt5501_spk_en, 1); rt5501_query.gpiostatus = AMP_GPIO_ON; } msleep(1); rt5501_write_reg(0,0x04); rt5501_write_reg(0xa4,0x52); rt5501_write_reg(1,0x7); msleep(10); rt5501_write_reg(0x3,0x81); msleep(101); #if 0 <API key>(temp,0x0); <API key>(temp,0x1); <API key>(temp,0x2); <API key>(temp,0x3); <API key>(temp,0x5); <API key>(temp,0x6); #endif ret = <API key>(temp,0x4); if(ret < 0) { pr_err("%s: read rt5501 status error %d\n",__func__,ret); if((hs->gpiostatus == AMP_GPIO_ON) && pdata->gpio_rt5501_spk_en) { rt5501_query.gpio_off_cancel = 0; queue_delayed_work(gpio_wq, &rt5501_query.gpio_off_work, msecs_to_jiffies(0)); } mutex_unlock(&hs->mlock); mutex_unlock(&hs->gpiolock); wake_unlock(&hs->hs_wake_lock); return; } rt5501_write_reg(0x0,0x4); mdelay(1); #if 0 init_rt5501(); #endif rt5501_write_reg(0x0,0xc0); rt5501_write_reg(0x81,0x30); rt5501_write_reg(0x87,0xf6); rt5501_write_reg(0x90,0xd0); rt5501_write_reg(0x93,0x9d); rt5501_write_reg(0x95,0x7b); rt5501_write_reg(0xa4,0x01); rt5501_write_reg(0x96,0xae); rt5501_write_reg(0x97,0x11); rt5501_write_reg(0x98,0x22); rt5501_write_reg(0x99,0x44); rt5501_write_reg(0x9a,0x55); rt5501_write_reg(0x9b,0x66); rt5501_write_reg(0x9c,0x99); rt5501_write_reg(0x9d,0x66); rt5501_write_reg(0x9e,0x99); high_imp = 0; if(temp[0] & RT5501_SENSE_READY) { unsigned char om, hsmode; enum HEADSET_OM hsom; hsmode = (temp[0] & 0x30) >> 4; om = (temp[0] & 0xe) >> 1; if(temp[0] == 0xc0 || temp[0] == 0xc1) { hsom = HEADSET_MONO; } else { switch(om) { case 0: hsom = HEADSET_8OM; break; case 1: hsom = HEADSET_16OM; break; case 2: hsom = HEADSET_32OM; break; case 3: hsom = HEADSET_64OM; break; case 4: hsom = HEADSET_128OM; break; case 5: hsom = HEADSET_256OM; break; case 6: hsom = HEADSET_500OM; break; case 7: hsom = HEADSET_1KOM; break; default: hsom = <API key>; break; } } hs->hs_qstatus = RT5501_QUERY_FINISH; hs->headsetom = hsom; if(om >= HEADSET_256OM && om <= HEADSET_1KOM) high_imp = 1; pr_info("rt5501 hs imp value 0x%x hsmode %d om 0x%x hsom %d high_imp %d\n",temp[0] & 0xf,hsmode,om,hsom,high_imp); if((hs->gpiostatus == AMP_GPIO_ON) && pdata->gpio_rt5501_spk_en) { rt5501_query.gpio_off_cancel = 0; queue_delayed_work(gpio_wq, &rt5501_query.gpio_off_work, msecs_to_jiffies(0)); } } else { if(hs->hs_qstatus == <API key>) queue_delayed_work(hs_wq,&rt5501_query.hs_imp_detec_work,QUERY_LATTER); } rt5501_status = hs->rt5501_status; if(high_imp) { rt5501_write_reg(0xb1,0x81); rt5501_write_reg(0x80,0x87); rt5501_write_reg(0x83,0xc3); rt5501_write_reg(0x84,0x63); rt5501_write_reg(0x89,0x7); mdelay(9); rt5501_write_reg(0x83,0xcf); rt5501_write_reg(0x89,0x1d); mdelay(1); rt5501_write_reg(1,0x7); rt5501_write_reg(0xb1,0x81); } else { rt5501_write_reg(1,0xc7); } mutex_unlock(&hs->mlock); mutex_unlock(&hs->gpiolock); if(rt5501_status == RT5501_SUSPEND) set_rt5501_amp(1); wake_unlock(&hs->hs_wake_lock); } static void volume_ramp_func(struct work_struct *work) { mutex_lock(&rt5501_query.actionlock); if(rt5501_query.rt5501_status != RT5501_PLAYBACK) { u8 val; pr_info("%s: ramping mdelay(1); if(high_imp) rt5501_write_reg(0xb1,0x80); rt5501_write_reg(0x2,0x0); mdelay(1); val = 0x7; if (MFG_MODE) { pr_info("Skip volume ramp for MFG build"); val += 15; rt5501_write_reg(1,val); } else { #if 1 int i; for(i=0; i<15; i++) { if(!rt5501_query.action_on) { mutex_unlock(&rt5501_query.actionlock); return; } msleep(1); rt5501_write_reg(1,val); val++; } #else for(i=0; i<8; i++) { msleep(10); rt5501_write_reg(1,val); val += 2; } #endif } } set_amp(1, &RT5501_AMP_ON); mutex_unlock(&rt5501_query.actionlock); } static void set_amp(int on, struct rt5501_config *i2c_command) { pr_info("%s: %d\n", __func__, on); mutex_lock(&rt5501_query.mlock); mutex_lock(&hp_amp_lock); if(rt5501_query.hs_qstatus == <API key>) rt5501_query.hs_qstatus = RT5501_QUERY_FINISH; if (on) { rt5501_query.rt5501_status = RT5501_PLAYBACK; if (rt5501_i2c_write(i2c_command->reg, i2c_command->reg_len) == 0) { last_spkamp_state = 1; pr_info("%s: ON \n", __func__); } } else { if(high_imp) { rt5501_write_reg(1,0x7); rt5501_write_reg(0xb1,0x81); } else { rt5501_write_reg(1,0xc7); } if(rt5501_query.rt5501_status == RT5501_PLAYBACK) { last_spkamp_state = 0; pr_info("%s: OFF\n", __func__); } rt5501_query.rt5501_status = RT5501_OFF; rt5501_query.curmode = RT5501_MODE_OFF; } mutex_unlock(&hp_amp_lock); mutex_unlock(&rt5501_query.mlock); } int query_rt5501(void) { return rt5501Connect; } void set_rt5501_amp(int on) { pr_info("%s: %d\n", __func__, on); rt5501_query.gpio_off_cancel = 1; if(!on) rt5501_query.action_on = 0; <API key>(&rt5501_query.gpio_off_work); <API key>(&rt5501_query.volume_ramp_work); flush_work_sync(&rt5501_query.volume_ramp_work.work); mutex_lock(&rt5501_query.gpiolock); if(on) { if((rt5501_query.gpiostatus == AMP_GPIO_OFF) && pdata->gpio_rt5501_spk_en) { if(rt5501_query.s4status == AMP_S4_AUTO) { <API key>(); rt5501_query.s4status = AMP_S4_PWM; msleep(1); } #ifdef <API key> msleep(50); #endif pr_info("%s: enable gpio %d\n",__func__,pdata->gpio_rt5501_spk_en); <API key>(pdata->gpio_rt5501_spk_en, 1); rt5501_query.gpiostatus = AMP_GPIO_ON; msleep(1); } rt5501_query.action_on = 1; queue_delayed_work(ramp_wq, &rt5501_query.volume_ramp_work, msecs_to_jiffies(0)); } else { set_amp(0, &RT5501_AMP_ON); if((rt5501_query.gpiostatus == AMP_GPIO_ON) && pdata->gpio_rt5501_spk_en) { rt5501_query.gpio_off_cancel = 0; queue_delayed_work(gpio_wq, &rt5501_query.gpio_off_work, msecs_to_jiffies(0)); } } mutex_unlock(&rt5501_query.gpiolock); } static int <API key>(int mode) { if (mode >= rt5501_config_data.mode_num) return -EINVAL; pr_info("%s: set mode %d\n", __func__, mode); if (mode == RT5501_MODE_OFF) memcpy(&RT5501_AMP_OFF, &rt5501_config_data.cmd_data[mode].config, sizeof(struct rt5501_config)); else if (mode == RT5501_INIT) memcpy(&RT5501_AMP_INIT, &rt5501_config_data.cmd_data[mode].config, sizeof(struct rt5501_config)); else if (mode == RT5501_MUTE) memcpy(&RT5501_AMP_MUTE, &rt5501_config_data.cmd_data[mode].config, sizeof(struct rt5501_config)); else { memcpy(&RT5501_AMP_ON, &rt5501_config_data.cmd_data[mode].config, sizeof(struct rt5501_config)); } return 0; } static long rt5501_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { void __user *argp = (void __user *)arg; int rc = 0, modeid = 0; unsigned char tmp[7]; unsigned char reg_idx[1] = {0x01}; struct rt5501_comm_data spk_cfg; unsigned char reg_value[2]; int premode = 0; int rt5501_status = 0; switch (cmd) { case RT5501_WRITE_REG: pr_info("%s: RT5501_WRITE_REG\n", __func__); mutex_lock(&hp_amp_lock); if (!last_spkamp_state) { mdelay(30); } if (copy_from_user(reg_value, argp, sizeof(reg_value))) goto err1; pr_info("%s: reg_value[0]=%2x, reg_value[1]=%2x\n", __func__, \ reg_value[0], reg_value[1]); rc = rt5501_write_reg(reg_value[0], reg_value[1]); err1: mutex_unlock(&hp_amp_lock); break; case RT5501_SET_CONFIG: if (copy_from_user(&spk_cfg, argp, sizeof(struct rt5501_comm_data))) return -EFAULT; memcpy(&RT5501_AMP_ON, &spk_cfg.config, sizeof(struct rt5501_config)); break; case RT5501_READ_CONFIG: mutex_lock(&hp_amp_lock); if (!last_spkamp_state) { mdelay(30); } rc = <API key>(reg_idx, sizeof(reg_idx)); if (rc < 0) goto err2; rc = rt5501_i2c_read(tmp, sizeof(tmp)); if (rc < 0) goto err2; if (copy_to_user(argp, &tmp, sizeof(tmp))) rc = -EFAULT; err2: mutex_unlock(&hp_amp_lock); break; case RT5501_SET_MODE: if (copy_from_user(&modeid, argp, sizeof(modeid))) return -EFAULT; if (modeid >= rt5501_config_data.mode_num || modeid <= 0) { pr_err("unsupported rt5501 mode %d\n", modeid); return -EINVAL; } mutex_lock(&hp_amp_lock); premode = rt5501_query.curmode; rt5501_query.curmode = modeid; rc = <API key>(modeid); rt5501_status = rt5501_query.rt5501_status; mutex_unlock(&hp_amp_lock); pr_info("%s:set rt5501 mode to %d curstatus %d\n", __func__,modeid,rt5501_status); if(rt5501_status == RT5501_SUSPEND || (rt5501_status == RT5501_PLAYBACK && premode != rt5501_query.curmode)) { flush_work_sync(&rt5501_query.volume_ramp_work.work); mutex_lock(&rt5501_query.actionlock); rt5501_query.action_on = 1; mutex_unlock(&rt5501_query.actionlock); queue_delayed_work(ramp_wq, &rt5501_query.volume_ramp_work, msecs_to_jiffies(280)); } break; case RT5501_SET_PARAM: if (copy_from_user(&rt5501_config_data.mode_num, argp, sizeof(unsigned int))) { pr_err("%s: copy from user failed.\n", __func__); return -EFAULT; } if (rt5501_config_data.mode_num <= 0) { pr_err("%s: invalid mode number %d\n", __func__, rt5501_config_data.mode_num); return -EINVAL; } if (rt5501_config_data.cmd_data == NULL) rt5501_config_data.cmd_data = kzalloc(sizeof(struct rt5501_comm_data)*rt5501_config_data.mode_num, GFP_KERNEL); if (!rt5501_config_data.cmd_data) { pr_err("%s: out of memory\n", __func__); return -ENOMEM; } if (copy_from_user(rt5501_config_data.cmd_data, ((struct rt5501_config_data*)argp)->cmd_data \ ,sizeof(struct rt5501_comm_data)*rt5501_config_data.mode_num)) { pr_err("%s: copy data from user failed.\n", __func__); kfree(rt5501_config_data.cmd_data); rt5501_config_data.cmd_data = NULL; return -EFAULT; } pr_info("%s: update rt5501 i2c commands #%d success.\n", __func__, rt5501_config_data.mode_num); mutex_lock(&hp_amp_lock); <API key>(RT5501_MODE_OFF); <API key>(RT5501_MUTE); <API key>(RT5501_INIT); mutex_unlock(&hp_amp_lock); rc = 0; break; case RT5501_QUERY_OM: mutex_lock(&rt5501_query.mlock); rc = rt5501_query.headsetom; mutex_unlock(&rt5501_query.mlock); pr_info("%s: query headset om %d\n", __func__,rc); if (copy_to_user(argp, &rc, sizeof(rc))) rc = -EFAULT; else rc = 0; break; default: pr_err("%s: Invalid command\n", __func__); rc = -EINVAL; break; } return rc; } static struct file_operations rt5501_fops = { .owner = THIS_MODULE, .open = rt5501_open, .release = rt5501_release, .unlocked_ioctl = rt5501_ioctl, }; static struct miscdevice rt5501_device = { .minor = MISC_DYNAMIC_MINOR, .name = "rt5501", .fops = &rt5501_fops, }; int rt5501_probe(struct i2c_client *client, const struct i2c_device_id *id) { int ret = 0; int err = 0; MFG_MODE = board_mfg_mode(); pdata = client->dev.platform_data; if (pdata == NULL) { pr_info("%s: platform data null\n", __func__); pdata = kzalloc(sizeof(*pdata), GFP_KERNEL); if (pdata == NULL) { ret = -ENOMEM; pr_err("%s: platform data is NULL\n", __func__); goto <API key>; } } this_client = client; if (ret < 0) { pr_err("%s: pmic request aud_spk_en pin failed\n", __func__); goto err_free_gpio_all; } if (!<API key>(client->adapter, I2C_FUNC_I2C)) { pr_err("%s: i2c check functionality error\n", __func__); ret = -ENODEV; goto err_free_gpio_all; } if(pdata->gpio_rt5501_spk_en) { char temp[2]; err = gpio_request(pdata->gpio_rt5501_spk_en, "hp_en"); ret = <API key>(pdata->gpio_rt5501_spk_en, 1); if(ret < 0) { pr_err("%s: gpio %d on error %d\n", __func__,pdata->gpio_rt5501_spk_en,ret); } mdelay(1); ret = rt5501_i2c_read(temp, 2); if(ret < 0) { pr_info("rt5501 is not connected\n"); rt5501Connect = 0; } else { pr_info("rt5501 is connected\n"); rt5501Connect = 1; } rt5501_write_reg(0x0,0x4); mdelay(1); rt5501_write_reg(0x0,0xc0); rt5501_write_reg(0x81,0x30); rt5501_write_reg(0x87,0xf6); rt5501_write_reg(0x90,0xd0); rt5501_write_reg(0x93,0x9d); rt5501_write_reg(0x95,0x7b); rt5501_write_reg(0xa4,0x01); rt5501_write_reg(0x96,0xae); rt5501_write_reg(0x97,0x11); rt5501_write_reg(0x98,0x22); rt5501_write_reg(0x99,0x44); rt5501_write_reg(0x9a,0x55); rt5501_write_reg(0x9b,0x66); rt5501_write_reg(0x9c,0x99); rt5501_write_reg(0x9d,0x66); rt5501_write_reg(0x9e,0x99); rt5501_write_reg(0x1,0xc7); <API key>(pdata->gpio_rt5501_spk_en, 0); if(!err) gpio_free(pdata->gpio_rt5501_spk_en); if(ret < 0) { pr_err("%s: gpio %d off error %d\n", __func__,pdata->gpio_rt5501_spk_en,ret); } } if(rt5501Connect) { struct headset_notifier notifier; ret = misc_register(&rt5501_device); if (ret) { pr_err("%s: rt5501_device register failed\n", __func__); goto err_free_gpio_all; } hs_wq = create_workqueue("rt5501_hsdetect"); INIT_DELAYED_WORK(&rt5501_query.hs_imp_detec_work,hs_imp_detec_func); wake_lock_init(&rt5501_query.hs_wake_lock, WAKE_LOCK_SUSPEND, DRIVER_NAME); wake_lock_init(&rt5501_query.gpio_wake_lock, WAKE_LOCK_SUSPEND, DRIVER_NAME); ramp_wq = create_workqueue("rt5501_volume_ramp"); INIT_DELAYED_WORK(&rt5501_query.volume_ramp_work, volume_ramp_func); gpio_wq = create_workqueue("rt5501_gpio_off"); INIT_DELAYED_WORK(&rt5501_query.gpio_off_work, hs_imp_gpio_off); notifier.id = <API key>; notifier.func = <API key>; <API key>(&notifier); } return 0; err_free_gpio_all: rt5501Connect = 0; return ret; <API key>: rt5501Connect = 0; return ret; } static int rt5501_remove(struct i2c_client *client) { struct <API key> *p6185data = i2c_get_clientdata(client); kfree(p6185data); if(rt5501Connect) { misc_deregister(&rt5501_device); <API key>(&rt5501_query.hs_imp_detec_work); destroy_workqueue(hs_wq); } return 0; } static void rt5501_shutdown(struct i2c_client *client) { rt5501_query.gpio_off_cancel = 1; <API key>(&rt5501_query.gpio_off_work); <API key>(&rt5501_query.volume_ramp_work); mutex_lock(&rt5501_query.gpiolock); mutex_lock(&hp_amp_lock); mutex_lock(&rt5501_query.mlock); if((rt5501_query.gpiostatus == AMP_GPIO_OFF) && pdata->gpio_rt5501_spk_en) { if(rt5501_query.s4status == AMP_S4_AUTO) { <API key>(); rt5501_query.s4status = AMP_S4_PWM; msleep(1); } pr_info("%s: enable gpio %d\n",__func__,pdata->gpio_rt5501_spk_en); <API key>(pdata->gpio_rt5501_spk_en, 1); rt5501_query.gpiostatus = AMP_GPIO_ON; msleep(1); } pr_info("%s: reset rt5501\n",__func__); rt5501_write_reg(0x0,0x4); mdelay(1); high_imp = 0; if((rt5501_query.gpiostatus == AMP_GPIO_ON) && pdata->gpio_rt5501_spk_en) { pr_info("%s: disable gpio %d\n",__func__,pdata->gpio_rt5501_spk_en); <API key>(pdata->gpio_rt5501_spk_en, 0); rt5501_query.gpiostatus = AMP_GPIO_OFF; if(rt5501_query.s4status == AMP_S4_PWM) { <API key>(); rt5501_query.s4status = AMP_S4_AUTO; } } mutex_unlock(&rt5501_query.mlock); mutex_unlock(&hp_amp_lock); mutex_unlock(&rt5501_query.gpiolock); } static int rt5501_suspend(struct i2c_client *client, pm_message_t mesg) { return 0; } static int rt5501_resume(struct i2c_client *client) { return 0; } static const struct i2c_device_id rt5501_id[] = { { RT5501_I2C_NAME, 0 }, { } }; static struct i2c_driver rt5501_driver = { .probe = rt5501_probe, .remove = rt5501_remove, .shutdown = rt5501_shutdown, .suspend = rt5501_suspend, .resume = rt5501_resume, .id_table = rt5501_id, .driver = { .name = RT5501_I2C_NAME, }, }; static int __init rt5501_init(void) { pr_info("%s\n", __func__); mutex_init(&hp_amp_lock); mutex_init(&rt5501_query.mlock); mutex_init(&rt5501_query.gpiolock); mutex_init(&rt5501_query.actionlock); rt5501_query.rt5501_status = RT5501_OFF; rt5501_query.hs_qstatus = RT5501_QUERY_OFF; rt5501_query.headsetom = HEADSET_8OM; rt5501_query.curmode = RT5501_MODE_OFF; rt5501_query.gpiostatus = AMP_GPIO_OFF; rt5501_query.s4status = AMP_S4_AUTO; return i2c_add_driver(&rt5501_driver); } static void __exit rt5501_exit(void) { i2c_del_driver(&rt5501_driver); } module_init(rt5501_init); module_exit(rt5501_exit); MODULE_DESCRIPTION("rt5501 Speaker Amp driver"); MODULE_LICENSE("GPL");
<?php // Exit if accessed directly if ( ! defined( 'ABSPATH' ) ) { exit; } // Don't duplicate me! if ( ! class_exists( '<API key>' ) ) { /** * Main <API key> class * * @since 1.0.0 */ class <API key> { /** * Field Constructor. * Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function * * @since 1.0.0 * @access public * @return void */ public function __construct( $field = array(), $value = '', $parent ) { $this->parent = $parent; $this->field = $field; $this->value = $value; if ( empty( $this->_extension_dir ) ) { $this->_extension_dir = trailingslashit( str_replace( '\\', '/', dirname( __FILE__ ) ) ); $this->_extension_url = site_url( str_replace( trailingslashit( str_replace( '\\', '/', ABSPATH ) ), '/', $this->_extension_dir ) ); } } /** * Field Render Function. * Takes the vars and outputs the HTML for the field in the settings * * @since 1.0.0 * @access public * @return void */ public function render() { // Default Redux title field is used to output section title // delete the tr afterwards } public function enqueue() { } } }
#pragma once #if !defined(RM_MISSION_H_INC) #define RM_MISSION_H_INC #ifdef DEBUG_LINKING #pragma message("...including RM_Mission.h") #endif // maximum random choices #define MAX_RANDOM_CHOICES 100 typedef vector<int> rmIntVector_t; class CRMMission { private: rmObjectiveList_t mObjectives; rmInstanceList_t mInstances; CRMInstanceFile mInstanceFile; CRMObjective* mCurrentObjective; bool mValidNodes; bool mValidPaths; bool mValidRivers; bool mValidWeapons; bool mValidAmmo; bool mValidObjectives; bool mValidInstances; int mTimeLimit; int <API key>; // npc multipliers float mAccuracyMultiplier; float mHealthMultiplier; // % chance that RMG pickup is actually spawned float mPickupHealth; float mPickupArmor; float mPickupAmmo; float mPickupWeapon; float mPickupEquipment; string mDescription; string mExitScreen; string mTimeExpiredScreen; // symmetric landscape style symmetry_t mSymmetric; // if set to 1 in the mission file, adds an extra connecting path in symmetric maps // to ensure both sides actually do connect int mBackUpPath; int mDefaultPadding; CRMAreaManager* mAreaManager; CRMPathManager* mPathManager; CRandomTerrain* mLandScape; public: CRMMission ( CRandomTerrain* ); ~CRMMission ( ); bool Load ( const char* name, const char* instances, const char* difficulty ); bool Spawn ( CRandomTerrain* terrain, qboolean IsServer ); void Preview ( const vec3_t from ); CRMObjective* FindObjective ( const char* name ); CRMObjective* GetCurrentObjective ( ) { return mCurrentObjective; } void CompleteMission (void); void FailedMission (bool TimeExpired); void CompleteObjective ( CRMObjective* ojective ); int GetTimeLimit (void) { return mTimeLimit; } int <API key> (void) { return <API key>; } const char* GetDescription (void) { return mDescription.c_str(); } const char* GetExitScreen (void) { return mExitScreen.c_str(); } int GetSymmetric (void) { return mSymmetric; } int GetBackUpPath (void) { return mBackUpPath; } int GetDefaultPadding (void) { return mDefaultPadding; } // void CreateMap ( void ); bool DenyPickupHealth () {return mLandScape->flrand(0.0f,1.0f) > mPickupHealth;} bool DenyPickupArmor () {return mLandScape->flrand(0.0f,1.0f) > mPickupArmor;} bool DenyPickupAmmo () {return mLandScape->flrand(0.0f,1.0f) > mPickupAmmo;} bool DenyPickupWeapon () {return mLandScape->flrand(0.0f,1.0f) > mPickupWeapon;} bool DenyPickupEquipment () {return mLandScape->flrand(0.0f,1.0f) > mPickupEquipment;} private: // void <API key> ( ); // void PurgeTrigger ( CEntity* trigger ); void MirrorPos (vec3_t pos); CGPGroup* ParseRandom ( CGPGroup* random ); bool ParseOrigin ( CGPGroup* originGroup, vec3_t origin, vec3_t lookat, int* flattenHeight ); bool ParseNodes ( CGPGroup* group ); bool ParsePaths ( CGPGroup *paths); bool ParseRivers ( CGPGroup *rivers); void PlaceBridges (); void PlaceWallInstance(CRMInstance* instance, float xpos, float ypos, float zpos, int x, int y, float angle); bool ParseDifficulty ( CGPGroup* difficulty, CGPGroup *parent ); bool ParseWeapons ( CGPGroup* weapons ); bool ParseAmmo ( CGPGroup* ammo ); bool ParseOutfit ( CGPGroup* outfit ); bool ParseObjectives ( CGPGroup* objectives ); bool ParseInstance ( CGPGroup* instance ); bool ParseInstances ( CGPGroup* instances ); bool <API key> ( CGPGroup* group ); bool ParseWallRect ( CGPGroup* group, int side); // void SpawnNPCTriggers ( CCMLandScape* landscape ); // void AttachNPCTriggers ( CCMLandScape* landscape ); }; #endif
#include <linux/gfp.h> #include <asm/unaligned.h> #include "xhci.h" #define PORT_WAKE_BITS (PORT_WKOC_E | PORT_WKDISC_E | PORT_WKCONN_E) #define PORT_RWC_BITS (PORT_CSC | PORT_PEC | PORT_WRC | PORT_OCC | \ PORT_RC | PORT_PLC | PORT_PE) /* usb 1.1 root hub device descriptor */ static u8 usb_bos_descriptor [] = { USB_DT_BOS_SIZE, /* __u8 bLength, 5 bytes */ USB_DT_BOS, /* __u8 bDescriptorType */ 0x0F, 0x00, /* __le16 wTotalLength, 15 bytes */ 0x1, /* __u8 bNumDeviceCaps */ /* First device capability */ <API key>, /* __u8 bLength, 10 bytes */ <API key>, /* Device Capability */ USB_SS_CAP_TYPE, /* bDevCapabilityType, SUPERSPEED_USB */ 0x00, /* bmAttributes, LTM off by default */ USB_5GBPS_OPERATION, 0x00, /* wSpeedsSupported, 5Gbps only */ 0x03, /* <API key>, USB 3.0 speed only */ 0x00, /* bU1DevExitLat, set later. */ 0x00, 0x00 /* __le16 bU2DevExitLat, set later. */ }; static void <API key>(struct xhci_hcd *xhci, struct usb_hub_descriptor *desc, int ports) { u16 temp; desc->bPwrOn2PwrGood = 10; /* xhci section 5.4.9 says 20ms max */ desc->bHubContrCurrent = 0; desc->bNbrPorts = ports; /* Ugh, these should be #defines, FIXME */ /* Using table 11-13 in USB 2.0 spec. */ temp = 0; /* Bits 1:0 - support port power switching, or power always on */ if (HCC_PPC(xhci->hcc_params)) temp |= 0x0001; else temp |= 0x0002; /* Bit 2 - root hubs are not part of a compound device */ /* Bits 4:3 - individual port over current protection */ temp |= 0x0008; /* Bits 6:5 - no TTs in root ports */ /* Bit 7 - no port indicators */ desc->wHubCharacteristics = cpu_to_le16(temp); } /* Fill in the USB 2.0 roothub descriptor */ static void <API key>(struct usb_hcd *hcd, struct xhci_hcd *xhci, struct usb_hub_descriptor *desc) { int ports; u16 temp; __u8 port_removable[(USB_MAXCHILDREN + 1 + 7) / 8]; u32 portsc; unsigned int i; ports = xhci->num_usb2_ports; <API key>(xhci, desc, ports); desc->bDescriptorType = 0x29; temp = 1 + (ports / 8); desc->bDescLength = 7 + 2 * temp; /* The Device Removable bits are reported on a byte granularity. * If the port doesn't exist within that byte, the bit is set to 0. */ memset(port_removable, 0, sizeof(port_removable)); for (i = 0; i < ports; i++) { portsc = xhci_readl(xhci, xhci->usb2_ports[i]); /* If a device is removable, PORTSC reports a 0, same as in the * hub descriptor DeviceRemovable bits. */ if (portsc & PORT_DEV_REMOVE) /* This math is hairy because bit 0 of DeviceRemovable * is reserved, and bit 1 is for port 1, etc. */ port_removable[(i + 1) / 8] |= 1 << ((i + 1) % 8); } /* ch11.h defines a hub descriptor that has room for USB_MAXCHILDREN * ports on it. The USB 2.0 specification says that there are two * variable length fields at the end of the hub descriptor: * DeviceRemovable and PortPwrCtrlMask. But since we can have less than * USB_MAXCHILDREN ports, we may need to use the DeviceRemovable array * to set PortPwrCtrlMask bits. PortPwrCtrlMask must always be set to * 0xFF, so we initialize the both arrays (DeviceRemovable and * PortPwrCtrlMask) to 0xFF. Then we set the DeviceRemovable for each * set of ports that actually exist. */ memset(desc->u.hs.DeviceRemovable, 0xff, sizeof(desc->u.hs.DeviceRemovable)); memset(desc->u.hs.PortPwrCtrlMask, 0xff, sizeof(desc->u.hs.PortPwrCtrlMask)); for (i = 0; i < (ports + 1 + 7) / 8; i++) memset(&desc->u.hs.DeviceRemovable[i], port_removable[i], sizeof(__u8)); } /* Fill in the USB 3.0 roothub descriptor */ static void <API key>(struct usb_hcd *hcd, struct xhci_hcd *xhci, struct usb_hub_descriptor *desc) { int ports; u16 port_removable; u32 portsc; unsigned int i; ports = xhci->num_usb3_ports; <API key>(xhci, desc, ports); desc->bDescriptorType = 0x2a; desc->bDescLength = 12; /* header decode latency should be zero for roothubs, * see section 4.23.5.2. */ desc->u.ss.bHubHdrDecLat = 0; desc->u.ss.wHubDelay = 0; port_removable = 0; /* bit 0 is reserved, bit 1 is for port 1, etc. */ for (i = 0; i < ports; i++) { portsc = xhci_readl(xhci, xhci->usb3_ports[i]); if (portsc & PORT_DEV_REMOVE) port_removable |= 1 << (i + 1); } memset(&desc->u.ss.DeviceRemovable, (__force __u16) cpu_to_le16(port_removable), sizeof(__u16)); } static void xhci_hub_descriptor(struct usb_hcd *hcd, struct xhci_hcd *xhci, struct usb_hub_descriptor *desc) { if (hcd->speed == HCD_USB3) <API key>(hcd, xhci, desc); else <API key>(hcd, xhci, desc); } static unsigned int xhci_port_speed(unsigned int port_status) { if (DEV_LOWSPEED(port_status)) return <API key>; if (DEV_HIGHSPEED(port_status)) return <API key>; /* * FIXME: Yes, we should check for full speed, but the core uses that as * a default in portspeed() in usb/core/hub.c (which is the only place * USB_PORT_STAT_*_SPEED is used). */ return 0; } /* * These bits are Read Only (RO) and should be saved and written to the * registers: 0, 3, 10:13, 30 * connect status, over-current status, port speed, and device removable. * connect status and port speed are also sticky - meaning they're in * the AUX well and they aren't changed by a hot, warm, or cold reset. */ #define XHCI_PORT_RO ((1<<0) | (1<<3) | (0xf<<10) | (1<<30)) /* * These bits are RW; writing a 0 clears the bit, writing a 1 sets the bit: * bits 5:8, 9, 14:15, 25:27 * link state, port power, port indicator state, "wake on" enable state */ #define XHCI_PORT_RWS ((0xf<<5) | (1<<9) | (0x3<<14) | (0x7<<25)) /* * These bits are RW; writing a 1 sets the bit, writing a 0 has no effect: * bit 4 (port reset) */ #define XHCI_PORT_RW1S ((1<<4)) /* * These bits are RW; writing a 1 clears the bit, writing a 0 has no effect: * bits 1, 17, 18, 19, 20, 21, 22, 23 * port enable/disable, and * change bits: connect, PED, warm port reset changed (reserved zero for USB 2.0 ports), * over-current, reset, link state, and L1 change */ #define XHCI_PORT_RW1CS ((1<<1) | (0x7f<<17)) /* * Bit 16 is RW, and writing a '1' to it causes the link state control to be * latched in */ #define XHCI_PORT_RW ((1<<16)) /* * These bits are Reserved Zero (RsvdZ) and zero should be written to them: * bits 2, 24, 28:31 */ #define XHCI_PORT_RZ ((1<<2) | (1<<24) | (0xf<<28)) /* * Given a port state, this function returns a value that would result in the * port being in the same state, if the value was written to the port status * control register. * Save Read Only (RO) bits and save read/write bits where * writing a 0 clears the bit and writing a 1 sets the bit (RWS). * For all other types (RW1S, RW1CS, RW, and RZ), writing a '0' has no effect. */ u32 <API key>(u32 state) { /* Save read-only status and port state */ return (state & XHCI_PORT_RO) | (state & XHCI_PORT_RWS); } /* * find slot id based on port number. * @port: The one-based port number from one of the two split roothubs. */ int <API key>(struct usb_hcd *hcd, struct xhci_hcd *xhci, u16 port) { int slot_id; int i; enum usb_device_speed speed; slot_id = 0; for (i = 0; i < MAX_HC_SLOTS; i++) { if (!xhci->devs[i]) continue; speed = xhci->devs[i]->udev->speed; if (((speed == USB_SPEED_SUPER) == (hcd->speed == HCD_USB3)) && xhci->devs[i]->fake_port == port) { slot_id = i; break; } } return slot_id; } /* * Stop device * It issues stop endpoint command for EP 0 to 30. And wait the last command * to complete. * suspend will set to 1, if suspend bit need to set in command. */ static int xhci_stop_device(struct xhci_hcd *xhci, int slot_id, int suspend) { struct xhci_virt_device *virt_dev; struct xhci_command *cmd; unsigned long flags; int timeleft; int ret; int i; ret = 0; virt_dev = xhci->devs[slot_id]; cmd = xhci_alloc_command(xhci, false, true, GFP_NOIO); if (!cmd) { xhci_dbg(xhci, "Couldn't allocate command structure.\n"); return -ENOMEM; } spin_lock_irqsave(&xhci->lock, flags); for (i = LAST_EP_INDEX; i > 0; i if (virt_dev->eps[i].ring && virt_dev->eps[i].ring->dequeue) <API key>(xhci, slot_id, i, suspend); } cmd->command_trb = xhci->cmd_ring->enqueue; list_add_tail(&cmd->cmd_list, &virt_dev->cmd_list); <API key>(xhci, slot_id, 0, suspend); xhci_ring_cmd_db(xhci); <API key>(&xhci->lock, flags); /* Wait for last stop endpoint command to finish */ timeleft = <API key>( cmd->completion, <API key>); if (timeleft <= 0) { xhci_warn(xhci, "%s while waiting for stop endpoint command\n", timeleft == 0 ? "Timeout" : "Signal"); spin_lock_irqsave(&xhci->lock, flags); /* The timeout might have raced with the event ring handler, so * only delete from the list if the item isn't poisoned. */ if (cmd->cmd_list.next != LIST_POISON1) list_del(&cmd->cmd_list); <API key>(&xhci->lock, flags); ret = -ETIME; goto command_cleanup; } command_cleanup: xhci_free_command(xhci, cmd); return ret; } /* * Ring device, it rings the all doorbells unconditionally. */ void xhci_ring_device(struct xhci_hcd *xhci, int slot_id) { int i; for (i = 0; i < LAST_EP_INDEX + 1; i++) if (xhci->devs[slot_id]->eps[i].ring && xhci->devs[slot_id]->eps[i].ring->dequeue) <API key>(xhci, slot_id, i, 0); return; } static void xhci_disable_port(struct usb_hcd *hcd, struct xhci_hcd *xhci, u16 wIndex, __le32 __iomem *addr, u32 port_status) { /* Don't allow the USB core to disable SuperSpeed ports. */ if (hcd->speed == HCD_USB3) { xhci_dbg(xhci, "Ignoring request to disable " "SuperSpeed port.\n"); return; } /* Write 1 to disable the port */ xhci_writel(xhci, port_status | PORT_PE, addr); port_status = xhci_readl(xhci, addr); xhci_dbg(xhci, "disable port, actual port %d status = 0x%x\n", wIndex, port_status); } static void <API key>(struct xhci_hcd *xhci, u16 wValue, u16 wIndex, __le32 __iomem *addr, u32 port_status) { char *port_change_bit; u32 status; switch (wValue) { case <API key>: status = PORT_RC; port_change_bit = "reset"; break; case <API key>: status = PORT_WRC; port_change_bit = "warm(BH) reset"; break; case <API key>: status = PORT_CSC; port_change_bit = "connect"; break; case <API key>: status = PORT_OCC; port_change_bit = "over-current"; break; case <API key>: status = PORT_PEC; port_change_bit = "enable/disable"; break; case <API key>: status = PORT_PLC; port_change_bit = "suspend/resume"; break; case <API key>: status = PORT_PLC; port_change_bit = "link state"; break; default: /* Should never happen */ return; } /* Change bits are all write 1 to clear */ xhci_writel(xhci, port_status | status, addr); port_status = xhci_readl(xhci, addr); xhci_dbg(xhci, "clear port %s change, actual port %d status = 0x%x\n", port_change_bit, wIndex, port_status); } static int xhci_get_ports(struct usb_hcd *hcd, __le32 __iomem ***port_array) { int max_ports; struct xhci_hcd *xhci = hcd_to_xhci(hcd); if (hcd->speed == HCD_USB3) { max_ports = xhci->num_usb3_ports; *port_array = xhci->usb3_ports; } else { max_ports = xhci->num_usb2_ports; *port_array = xhci->usb2_ports; } return max_ports; } void xhci_set_link_state(struct xhci_hcd *xhci, __le32 __iomem **port_array, int port_id, u32 link_state) { u32 temp; temp = xhci_readl(xhci, port_array[port_id]); temp = <API key>(temp); temp &= ~PORT_PLS_MASK; temp |= PORT_LINK_STROBE | link_state; xhci_writel(xhci, temp, port_array[port_id]); } /* Test and clear port RWC bit */ void <API key>(struct xhci_hcd *xhci, __le32 __iomem **port_array, int port_id, u32 port_bit) { u32 temp; temp = xhci_readl(xhci, port_array[port_id]); if (temp & port_bit) { temp = <API key>(temp); temp |= port_bit; xhci_writel(xhci, temp, port_array[port_id]); } } /* Updates Link Status for super Speed port */ static void <API key>(struct xhci_hcd *xhci, u32 *status, u32 status_reg) { u32 pls = status_reg & PORT_PLS_MASK; /* resume state is a xHCI internal state. * Do not report it to usb core. */ if (pls == XDEV_RESUME) return; /* When the CAS bit is set then warm reset * should be performed on port */ if (status_reg & PORT_CAS) { /* The CAS bit can be set while the port is * in any link state. * Only roothubs have CAS bit, so we * pretend to be in compliance mode * unless we're already in compliance * or the inactive state. */ if (pls != <API key> && pls != <API key>) { pls = <API key>; } /* Return also connection bit - * hub state machine resets port * when this bit is set. */ pls |= <API key>; } else { /* * If CAS bit isn't set but the Port is already at * Compliance Mode, fake a connection so the USB core * notices the Compliance state and resets the port. * This resolves an issue generated by the SN65LVPE502CP * in which sometimes the port enters compliance mode * caused by a delay on the host-device negotiation. */ if ((xhci->quirks & <API key>) && (pls == <API key>)) pls |= <API key>; } /* update status field */ *status |= pls; } /* * Function for Compliance Mode Quirk. * * This Function verifies if all xhc USB3 ports have entered U0, if so, * the compliance mode timer is deleted. A port won't enter * compliance mode if it has previously entered U0. */ void <API key>(struct xhci_hcd *xhci, u32 status, u16 wIndex) { u32 all_ports_seen_u0 = ((1 << xhci->num_usb3_ports)-1); bool port_in_u0 = ((status & PORT_PLS_MASK) == XDEV_U0); if (!(xhci->quirks & <API key>)) return; if ((xhci->port_status_u0 != all_ports_seen_u0) && port_in_u0) { xhci->port_status_u0 |= 1 << wIndex; if (xhci->port_status_u0 == all_ports_seen_u0) { del_timer_sync(&xhci-><API key>); xhci_dbg(xhci, "All USB3 ports have entered U0 already!\n"); xhci_dbg(xhci, "Compliance Mode Recovery Timer Deleted.\n"); } } } int xhci_hub_control(struct usb_hcd *hcd, u16 typeReq, u16 wValue, u16 wIndex, char *buf, u16 wLength) { struct xhci_hcd *xhci = hcd_to_xhci(hcd); int max_ports; unsigned long flags; u32 temp, status; int retval = 0; __le32 __iomem **port_array; int slot_id; struct xhci_bus_state *bus_state; u16 link_state = 0; max_ports = xhci_get_ports(hcd, &port_array); bus_state = &xhci->bus_state[hcd_index(hcd)]; spin_lock_irqsave(&xhci->lock, flags); switch (typeReq) { case GetHubStatus: /* No power source, over-current reported per port */ memset(buf, 0, 4); break; case GetHubDescriptor: /* Check to make sure userspace is asking for the USB 3.0 hub * descriptor for the USB 3.0 roothub. If not, we stall the * endpoint, like external hubs do. */ if (hcd->speed == HCD_USB3 && (wLength < USB_DT_SS_HUB_SIZE || wValue != (USB_DT_SS_HUB << 8))) { xhci_dbg(xhci, "Wrong hub descriptor type for " "USB 3.0 roothub.\n"); goto error; } xhci_hub_descriptor(hcd, xhci, (struct usb_hub_descriptor *) buf); break; case DeviceRequest | <API key>: if ((wValue & 0xff00) != (USB_DT_BOS << 8)) goto error; if (hcd->speed != HCD_USB3) goto error; memcpy(buf, &usb_bos_descriptor, USB_DT_BOS_SIZE + <API key>); temp = xhci_readl(xhci, &xhci->cap_regs->hcs_params3); buf[12] = HCS_U1_LATENCY(temp); put_unaligned_le16(HCS_U2_LATENCY(temp), &buf[13]); <API key>(&xhci->lock, flags); return USB_DT_BOS_SIZE + <API key>; case GetPortStatus: if (!wIndex || wIndex > max_ports) goto error; wIndex status = 0; temp = xhci_readl(xhci, port_array[wIndex]); if (temp == 0xffffffff) { retval = -ENODEV; break; } xhci_dbg(xhci, "get port status, actual port %d status = 0x%x\n", wIndex, temp); /* wPortChange bits */ if (temp & PORT_CSC) status |= <API key> << 16; if (temp & PORT_PEC) status |= <API key> << 16; if ((temp & PORT_OCC)) status |= <API key> << 16; if ((temp & PORT_RC)) status |= <API key> << 16; /* USB3.0 only */ if (hcd->speed == HCD_USB3) { if ((temp & PORT_PLC)) status |= <API key> << 16; if ((temp & PORT_WRC)) status |= <API key> << 16; } if (hcd->speed != HCD_USB3) { if ((temp & PORT_PLS_MASK) == XDEV_U3 && (temp & PORT_POWER)) status |= <API key>; } if ((temp & PORT_PLS_MASK) == XDEV_RESUME && !DEV_SUPERSPEED(temp)) { if ((temp & PORT_RESET) || !(temp & PORT_PE)) goto error; if (time_after_eq(jiffies, bus_state->resume_done[wIndex])) { xhci_dbg(xhci, "Resume USB2 port %d\n", wIndex + 1); bus_state->resume_done[wIndex] = 0; xhci_set_link_state(xhci, port_array, wIndex, XDEV_U0); xhci_dbg(xhci, "set port %d resume\n", wIndex + 1); slot_id = <API key>(hcd, xhci, wIndex + 1); if (!slot_id) { xhci_dbg(xhci, "slot_id is zero\n"); goto error; } xhci_ring_device(xhci, slot_id); bus_state->port_c_suspend |= 1 << wIndex; bus_state->suspended_ports &= ~(1 << wIndex); } else { /* * The resume has been signaling for less than * 20ms. Report the port status as SUSPEND, * let the usbcore check port status again * and clear resume signaling later. */ status |= <API key>; } } if ((temp & PORT_PLS_MASK) == XDEV_U0 && (temp & PORT_POWER) && (bus_state->suspended_ports & (1 << wIndex))) { bus_state->suspended_ports &= ~(1 << wIndex); if (hcd->speed != HCD_USB3) bus_state->port_c_suspend |= 1 << wIndex; } if (temp & PORT_CONNECT) { status |= <API key>; status |= xhci_port_speed(temp); } if (temp & PORT_PE) status |= <API key>; if (temp & PORT_OC) status |= <API key>; if (temp & PORT_RESET) status |= USB_PORT_STAT_RESET; if (temp & PORT_POWER) { if (hcd->speed == HCD_USB3) status |= <API key>; else status |= USB_PORT_STAT_POWER; } /* Update Port Link State for super speed ports*/ if (hcd->speed == HCD_USB3) { <API key>(xhci, &status, temp); /* * Verify if all USB3 Ports Have entered U0 already. * Delete Compliance Mode Timer if so. */ <API key>(xhci, temp, wIndex); } if (bus_state->port_c_suspend & (1 << wIndex)) status |= 1 << <API key>; xhci_dbg(xhci, "Get port status returned 0x%x\n", status); put_unaligned(cpu_to_le32(status), (__le32 *) buf); break; case SetPortFeature: if (wValue == <API key>) link_state = (wIndex & 0xff00) >> 3; wIndex &= 0xff; if (!wIndex || wIndex > max_ports) goto error; wIndex temp = xhci_readl(xhci, port_array[wIndex]); if (temp == 0xffffffff) { retval = -ENODEV; break; } temp = <API key>(temp); /* FIXME: What new port features do we need to support? */ switch (wValue) { case <API key>: temp = xhci_readl(xhci, port_array[wIndex]); if ((temp & PORT_PLS_MASK) != XDEV_U0) { /* Resume the port to U0 first */ xhci_set_link_state(xhci, port_array, wIndex, XDEV_U0); <API key>(&xhci->lock, flags); msleep(10); spin_lock_irqsave(&xhci->lock, flags); } temp = xhci_readl(xhci, port_array[wIndex]); if ((temp & PORT_PE) == 0 || (temp & PORT_RESET) || (temp & PORT_PLS_MASK) >= XDEV_U3) { xhci_warn(xhci, "USB core suspending device " "not in U0/U1/U2.\n"); goto error; } slot_id = <API key>(hcd, xhci, wIndex + 1); if (!slot_id) { xhci_warn(xhci, "slot_id is zero\n"); goto error; } /* unlock to execute stop endpoint commands */ <API key>(&xhci->lock, flags); xhci_stop_device(xhci, slot_id, 1); spin_lock_irqsave(&xhci->lock, flags); xhci_set_link_state(xhci, port_array, wIndex, XDEV_U3); <API key>(&xhci->lock, flags); msleep(10); /* wait device to enter */ spin_lock_irqsave(&xhci->lock, flags); temp = xhci_readl(xhci, port_array[wIndex]); bus_state->suspended_ports |= 1 << wIndex; break; case <API key>: temp = xhci_readl(xhci, port_array[wIndex]); /* Disable port */ if (link_state == <API key>) { xhci_dbg(xhci, "Disable port %d\n", wIndex); temp = <API key>(temp); /* * Clear all change bits, so that we get a new * connection event. */ temp |= PORT_CSC | PORT_PEC | PORT_WRC | PORT_OCC | PORT_RC | PORT_PLC | PORT_CEC; xhci_writel(xhci, temp | PORT_PE, port_array[wIndex]); temp = xhci_readl(xhci, port_array[wIndex]); break; } /* Put link in RxDetect (enable port) */ if (link_state == <API key>) { xhci_dbg(xhci, "Enable port %d\n", wIndex); xhci_set_link_state(xhci, port_array, wIndex, link_state); temp = xhci_readl(xhci, port_array[wIndex]); break; } /* Software should not attempt to set * port link state above '3' (U3) and the port * must be enabled. */ if ((temp & PORT_PE) == 0 || (link_state > USB_SS_PORT_LS_U3)) { xhci_warn(xhci, "Cannot set link state.\n"); goto error; } if (link_state == USB_SS_PORT_LS_U3) { slot_id = <API key>(hcd, xhci, wIndex + 1); if (slot_id) { /* unlock to execute stop endpoint * commands */ <API key>(&xhci->lock, flags); xhci_stop_device(xhci, slot_id, 1); spin_lock_irqsave(&xhci->lock, flags); } } xhci_set_link_state(xhci, port_array, wIndex, link_state); <API key>(&xhci->lock, flags); msleep(20); /* wait device to enter */ spin_lock_irqsave(&xhci->lock, flags); temp = xhci_readl(xhci, port_array[wIndex]); if (link_state == USB_SS_PORT_LS_U3) bus_state->suspended_ports |= 1 << wIndex; break; case USB_PORT_FEAT_POWER: /* * Turn on ports, even if there isn't per-port switching. * HC will report connect events even before this is set. * However, khubd will ignore the roothub events until * the roothub is registered. */ xhci_writel(xhci, temp | PORT_POWER, port_array[wIndex]); temp = xhci_readl(xhci, port_array[wIndex]); xhci_dbg(xhci, "set port power, actual port %d status = 0x%x\n", wIndex, temp); break; case USB_PORT_FEAT_RESET: temp = (temp | PORT_RESET); xhci_writel(xhci, temp, port_array[wIndex]); temp = xhci_readl(xhci, port_array[wIndex]); xhci_dbg(xhci, "set port reset, actual port %d status = 0x%x\n", wIndex, temp); break; case <API key>: temp |= PORT_WR; xhci_writel(xhci, temp, port_array[wIndex]); temp = xhci_readl(xhci, port_array[wIndex]); break; default: goto error; } /* unblock any posted writes */ temp = xhci_readl(xhci, port_array[wIndex]); break; case ClearPortFeature: if (!wIndex || wIndex > max_ports) goto error; wIndex temp = xhci_readl(xhci, port_array[wIndex]); if (temp == 0xffffffff) { retval = -ENODEV; break; } /* FIXME: What new port features do we need to support? */ temp = <API key>(temp); switch (wValue) { case <API key>: temp = xhci_readl(xhci, port_array[wIndex]); xhci_dbg(xhci, "clear <API key>\n"); xhci_dbg(xhci, "PORTSC %04x\n", temp); if (temp & PORT_RESET) goto error; if ((temp & PORT_PLS_MASK) == XDEV_U3) { if ((temp & PORT_PE) == 0) goto error; xhci_set_link_state(xhci, port_array, wIndex, XDEV_RESUME); <API key>(&xhci->lock, flags); msleep(20); spin_lock_irqsave(&xhci->lock, flags); xhci_set_link_state(xhci, port_array, wIndex, XDEV_U0); } bus_state->port_c_suspend |= 1 << wIndex; slot_id = <API key>(hcd, xhci, wIndex + 1); if (!slot_id) { xhci_dbg(xhci, "slot_id is zero\n"); goto error; } xhci_ring_device(xhci, slot_id); break; case <API key>: bus_state->port_c_suspend &= ~(1 << wIndex); case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: <API key>(xhci, wValue, wIndex, port_array[wIndex], temp); break; case <API key>: xhci_disable_port(hcd, xhci, wIndex, port_array[wIndex], temp); break; default: goto error; } break; default: error: /* "stall" on error */ retval = -EPIPE; } <API key>(&xhci->lock, flags); return retval; } /* * Returns 0 if the status hasn't changed, or the number of bytes in buf. * Ports are 0-indexed from the HCD point of view, * and 1-indexed from the USB core pointer of view. * * Note that the status change bits will be cleared as soon as a port status * change event is generated, so we use the saved status from that event. */ int <API key>(struct usb_hcd *hcd, char *buf) { unsigned long flags; u32 temp, status; u32 mask; int i, retval; struct xhci_hcd *xhci = hcd_to_xhci(hcd); int max_ports; __le32 __iomem **port_array; struct xhci_bus_state *bus_state; bool reset_change = false; max_ports = xhci_get_ports(hcd, &port_array); bus_state = &xhci->bus_state[hcd_index(hcd)]; /* Initial status is no changes */ retval = (max_ports + 8) / 8; memset(buf, 0, retval); status = 0; mask = PORT_CSC | PORT_PEC | PORT_OCC | PORT_PLC | PORT_WRC; spin_lock_irqsave(&xhci->lock, flags); /* For each port, did anything change? If so, set that bit in buf. */ for (i = 0; i < max_ports; i++) { temp = xhci_readl(xhci, port_array[i]); if (temp == 0xffffffff) { retval = -ENODEV; break; } if ((temp & mask) != 0 || (bus_state->port_c_suspend & 1 << i) || (bus_state->resume_done[i] && time_after_eq( jiffies, bus_state->resume_done[i]))) { buf[(i + 1) / 8] |= 1 << (i + 1) % 8; status = 1; } if ((temp & PORT_RC)) reset_change = true; } if (!status && !reset_change) { xhci_dbg(xhci, "%s: stopping port polling.\n", __func__); clear_bit(HCD_FLAG_POLL_RH, &hcd->flags); } <API key>(&xhci->lock, flags); return status ? retval : 0; } #ifdef CONFIG_PM int xhci_bus_suspend(struct usb_hcd *hcd) { struct xhci_hcd *xhci = hcd_to_xhci(hcd); int max_ports, port_index; __le32 __iomem **port_array; struct xhci_bus_state *bus_state; unsigned long flags; max_ports = xhci_get_ports(hcd, &port_array); bus_state = &xhci->bus_state[hcd_index(hcd)]; spin_lock_irqsave(&xhci->lock, flags); if (hcd->self.root_hub->do_remote_wakeup) { port_index = max_ports; while (port_index if (bus_state->resume_done[port_index] != 0) { <API key>(&xhci->lock, flags); xhci_dbg(xhci, "suspend failed because " "port %d is resuming\n", port_index + 1); return -EBUSY; } } } port_index = max_ports; bus_state->bus_suspended = 0; while (port_index /* suspend the port if the port is not suspended */ u32 t1, t2; int slot_id; t1 = xhci_readl(xhci, port_array[port_index]); t2 = <API key>(t1); if ((t1 & PORT_PE) && !(t1 & PORT_PLS_MASK)) { xhci_dbg(xhci, "port %d not suspended\n", port_index); slot_id = <API key>(hcd, xhci, port_index + 1); if (slot_id) { <API key>(&xhci->lock, flags); xhci_stop_device(xhci, slot_id, 1); spin_lock_irqsave(&xhci->lock, flags); } t2 &= ~PORT_PLS_MASK; t2 |= PORT_LINK_STROBE | XDEV_U3; set_bit(port_index, &bus_state->bus_suspended); } if (hcd->self.root_hub->do_remote_wakeup) { if (t1 & PORT_CONNECT) { t2 |= PORT_WKOC_E | PORT_WKDISC_E; t2 &= ~PORT_WKCONN_E; } else { t2 |= PORT_WKOC_E | PORT_WKCONN_E; t2 &= ~PORT_WKDISC_E; } } else t2 &= ~PORT_WAKE_BITS; t1 = <API key>(t1); if (t1 != t2) xhci_writel(xhci, t2, port_array[port_index]); } hcd->state = HC_STATE_SUSPENDED; bus_state->next_statechange = jiffies + msecs_to_jiffies(10); <API key>(&xhci->lock, flags); return 0; } int xhci_bus_resume(struct usb_hcd *hcd) { struct xhci_hcd *xhci = hcd_to_xhci(hcd); int max_ports, port_index; __le32 __iomem **port_array; struct xhci_bus_state *bus_state; u32 temp; unsigned long flags; max_ports = xhci_get_ports(hcd, &port_array); bus_state = &xhci->bus_state[hcd_index(hcd)]; if (time_before(jiffies, bus_state->next_statechange)) msleep(5); spin_lock_irqsave(&xhci->lock, flags); if (!HCD_HW_ACCESSIBLE(hcd)) { <API key>(&xhci->lock, flags); return -ESHUTDOWN; } /* delay the irqs */ temp = xhci_readl(xhci, &xhci->op_regs->command); temp &= ~CMD_EIE; xhci_writel(xhci, temp, &xhci->op_regs->command); port_index = max_ports; while (port_index /* Check whether need resume ports. If needed resume port and disable remote wakeup */ u32 temp; int slot_id; temp = xhci_readl(xhci, port_array[port_index]); if (DEV_SUPERSPEED(temp)) temp &= ~(PORT_RWC_BITS | PORT_CEC | PORT_WAKE_BITS); else temp &= ~(PORT_RWC_BITS | PORT_WAKE_BITS); if (test_bit(port_index, &bus_state->bus_suspended) && (temp & PORT_PLS_MASK)) { if (DEV_SUPERSPEED(temp)) { xhci_set_link_state(xhci, port_array, port_index, XDEV_U0); } else { xhci_set_link_state(xhci, port_array, port_index, XDEV_RESUME); <API key>(&xhci->lock, flags); msleep(20); spin_lock_irqsave(&xhci->lock, flags); xhci_set_link_state(xhci, port_array, port_index, XDEV_U0); } /* wait for the port to enter U0 and report port link * state change. */ <API key>(&xhci->lock, flags); msleep(20); spin_lock_irqsave(&xhci->lock, flags); /* Clear PLC */ <API key>(xhci, port_array, port_index, PORT_PLC); slot_id = <API key>(hcd, xhci, port_index + 1); if (slot_id) xhci_ring_device(xhci, slot_id); } else xhci_writel(xhci, temp, port_array[port_index]); } (void) xhci_readl(xhci, &xhci->op_regs->command); bus_state->next_statechange = jiffies + msecs_to_jiffies(5); /* re-enable irqs */ temp = xhci_readl(xhci, &xhci->op_regs->command); temp |= CMD_EIE; xhci_writel(xhci, temp, &xhci->op_regs->command); temp = xhci_readl(xhci, &xhci->op_regs->command); <API key>(&xhci->lock, flags); return 0; } #endif /* CONFIG_PM */
/* * Comment: The event with the Living Mojos is not implemented, just is done that when one of the mojos around the boss take damage will make the boss enter in combat! */ #include "ScriptPCH.h" #include "gundrak.h" enum Spells { SPELL_EMERGE = 54850, SPELL_MIGHTY_BLOW = 54719, SPELL_MERGE = 54878, SPELL_SURGE = 54801, SPELL_FREEZE_ANIM = 16245, SPELL_MOJO_PUDDLE = 55627, H_SPELL_MOJO_PUDDLE = 58994, SPELL_MOJO_WAVE = 55626, H_SPELL_MOJO_WAVE = 58993 }; struct <API key> : public ScriptedAI { <API key>(Creature* pCreature) : ScriptedAI(pCreature) { pInstance = pCreature->GetInstanceData(); } ScriptedInstance* pInstance; bool bHealth; bool bHealth1; uint32 MightyBlowTimer; void Reset() { if (pInstance) pInstance->SetData(<API key>, NOT_STARTED); if (!me->HasFlag(UNIT_FIELD_FLAGS, <API key>)) me->SetFlag(UNIT_FIELD_FLAGS, <API key>); me->RemoveFlag(UNIT_FIELD_FLAGS, <API key>); me->clearUnitState(UNIT_STAT_STUNNED | UNIT_STAT_ROOT); me->SetReactState(REACT_PASSIVE); MightyBlowTimer = 10*IN_MILLISECONDS; bHealth = false; bHealth1 = false; } void EnterCombat(Unit* /*who*/) { if (pInstance) pInstance->SetData(<API key>, IN_PROGRESS); } void CreatureState(Creature* pWho, bool bRestore = false) { if (!pWho) return; if (bRestore) { pWho->clearUnitState(UNIT_STAT_STUNNED | UNIT_STAT_ROOT); pWho->RemoveFlag(UNIT_FIELD_FLAGS, <API key>); if (pWho == me) me->RemoveAura(SPELL_FREEZE_ANIM); }else { pWho->SetFlag(UNIT_FIELD_FLAGS, <API key>); pWho->addUnitState(UNIT_STAT_STUNNED | UNIT_STAT_ROOT); if (pWho == me) DoCast(me,SPELL_FREEZE_ANIM); } } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; if (!bHealth && HealthBelowPct(50) && !HealthBelowPct(5)) { CreatureState(me, false); DoCast(me,SPELL_FREEZE_ANIM); DoCast(me,SPELL_EMERGE); bHealth = true; } if (!bHealth1 && HealthBelowPct(5)) { DoCast(me,SPELL_EMERGE); CreatureState(me, false); bHealth1 = true; me->RemoveAllAuras(); } if (MightyBlowTimer <= diff) { DoCast(me->getVictim(), SPELL_MIGHTY_BLOW, true); MightyBlowTimer = 10*IN_MILLISECONDS; } else MightyBlowTimer -= diff; if (!me->hasUnitState(UNIT_STAT_STUNNED)) <API key>(); } void JustDied(Unit* /*killer*/) { if (pInstance) pInstance->SetData(<API key>, DONE); } void JustSummoned(Creature* pSummon) { if (HealthBelowPct(5)) pSummon->DealDamage(pSummon, pSummon->GetHealth() * 0.5 , NULL, DIRECT_DAMAGE, <API key>, NULL, false); pSummon->AI()->AttackStart(me->getVictim()); } }; struct <API key> : public ScriptedAI { <API key>(Creature* pCreature) : ScriptedAI(pCreature) { pInstance = pCreature->GetInstanceData(); } ScriptedInstance* pInstance; uint32 uiSurgeTimer; bool bGoToColossus; void Reset() { if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(<API key>) : 0)) CAST_AI(<API key>, pColossus->AI())->CreatureState(me, true); uiSurgeTimer = 7*IN_MILLISECONDS; bGoToColossus = false; } void EnterEvadeMode() { me->RemoveFromWorld(); } void MovementInform(uint32 uiType, uint32 /*uiId*/) { if (uiType != POINT_MOTION_TYPE) return; if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(<API key>) : 0)) { CAST_AI(<API key>, pColossus->AI())->CreatureState(pColossus, true); CAST_AI(<API key>, pColossus->AI())->bHealth1 = false; } me->RemoveFromWorld(); } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; if (!bGoToColossus && HealthBelowPct(50)) { if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(<API key>) : 0)) { if (!CAST_AI(<API key>,pColossus->AI())->HealthBelowPct(6)) { me-><API key>(true); DoCast(pColossus, SPELL_MERGE); bGoToColossus = true; } } } if (uiSurgeTimer <= diff) { DoCast(me->getVictim(), SPELL_SURGE); uiSurgeTimer = 7*IN_MILLISECONDS; } else uiSurgeTimer -= diff; <API key>(); } void JustDied(Unit* /*killer*/) { if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(<API key>) : 0)) pColossus->Kill(pColossus); } }; struct npc_living_mojoAI : public ScriptedAI { npc_living_mojoAI(Creature* pCreature) : ScriptedAI(pCreature) { pInstance = pCreature->GetInstanceData(); } ScriptedInstance* pInstance; uint32 uiMojoWaveTimer; uint32 uiMojoPuddleTimer; void Reset() { uiMojoWaveTimer = 2*IN_MILLISECONDS; uiMojoPuddleTimer = 7*IN_MILLISECONDS; } void EnterCombat(Unit* /*who*/) { //Check if the npc is near of Drakkari Colossus. if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(<API key>) : 0)) { if (pColossus->isAlive() && me->IsInRange3d(pColossus->GetHomePosition().GetPositionX(),pColossus->GetHomePosition().GetPositionY(),pColossus->GetHomePosition().GetPositionZ(),0.0f,17.0f)) me->SetReactState(REACT_PASSIVE); else me->SetReactState(REACT_AGGRESSIVE); } } void DamageTaken(Unit* pDone_by, uint32& /*uiDamage*/) { if (me->HasReactState(REACT_PASSIVE)) { if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(<API key>) : 0)) { if (pColossus->isAlive() && !pColossus->isInCombat()) { pColossus->RemoveAura(SPELL_FREEZE_ANIM); pColossus->RemoveFlag(UNIT_FIELD_FLAGS, <API key>); pColossus->SetReactState(REACT_AGGRESSIVE); if (pDone_by && pDone_by->isAlive()) pColossus->AI()->AttackStart(pDone_by); EnterEvadeMode(); } } } } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; if (uiMojoWaveTimer <= diff) { DoCast(me->getVictim(), SPELL_MOJO_WAVE); uiMojoWaveTimer = 15*IN_MILLISECONDS; } else uiMojoWaveTimer -= diff; if (uiMojoPuddleTimer <= diff) { DoCast(me->getVictim(), SPELL_MOJO_PUDDLE); uiMojoPuddleTimer = 18*IN_MILLISECONDS; } else uiMojoPuddleTimer -= diff; <API key>(); } }; CreatureAI* <API key>(Creature* pCreature) { return new <API key> (pCreature); } CreatureAI* <API key>(Creature* pCreature) { return new <API key> (pCreature); } CreatureAI* <API key>(Creature* pCreature) { return new npc_living_mojoAI (pCreature); } void <API key>() { Script* newscript; newscript = new Script; newscript->Name = "<API key>"; newscript->GetAI = &<API key>; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "<API key>"; newscript->GetAI = &<API key>; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "npc_living_mojo"; newscript->GetAI = &<API key>; newscript->RegisterSelf(); }
#include "config.h" #include <glib.h> #include <epan/packet.h> #include "opcua_simpletypes.h" #include "<API key>.h" /** NodeId encoding mask table */ static const value_string g_nodeidmasks[] = { { 0, "Two byte encoded Numeric" }, { 1, "Four byte encoded Numeric" }, { 2, "Numeric of arbitrary length" }, { 3, "String" }, { 4, "URI" }, { 5, "GUID" }, { 6, "ByteString" }, { 0x80, "UriMask" }, { 0, NULL } }; /** Service type table */ extern const value_string g_requesttypes[]; static int <API key> = -1; static int hf_opcua_app_nsid = -1; static int <API key> = -1; /** Register application layer types. */ void <API key>(int proto) { /** header field definitions */ static hf_register_info hf[] = { { &<API key>, { "NodeId EncodingMask", "application.nodeid.encodingmask", FT_UINT8, BASE_HEX, VALS(g_nodeidmasks), 0x0, NULL, HFILL } }, { &hf_opcua_app_nsid, { "NodeId EncodingMask", "application.nodeid.nsid", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &<API key>, { "NodeId Identifier Numeric", "application.nodeid.numeric", FT_UINT32, BASE_DEC, VALS(g_requesttypes), 0x0, NULL, HFILL } } }; <API key>(proto, hf, array_length(hf)); } /** Parses an OpcUa Service NodeId and returns the service type. * In this cases the NodeId is always from type numeric and NSId = 0. */ int parseServiceNodeId(proto_tree *tree, tvbuff_t *tvb, gint *pOffset) { gint iOffset = *pOffset; guint8 EncodingMask; guint32 Numeric = 0; EncodingMask = tvb_get_guint8(tvb, iOffset); proto_tree_add_item(tree, <API key>, tvb, iOffset, 1, ENC_LITTLE_ENDIAN); iOffset++; switch(EncodingMask) { case 0x00: /* two byte node id */ Numeric = tvb_get_guint8(tvb, iOffset); proto_tree_add_item(tree, <API key>, tvb, iOffset, 1, ENC_LITTLE_ENDIAN); iOffset+=1; break; case 0x01: /* four byte node id */ proto_tree_add_item(tree, hf_opcua_app_nsid, tvb, iOffset, 1, ENC_LITTLE_ENDIAN); iOffset+=1; Numeric = tvb_get_letohs(tvb, iOffset); proto_tree_add_item(tree, <API key>, tvb, iOffset, 2, ENC_LITTLE_ENDIAN); iOffset+=2; break; case 0x02: /* numeric, that does not fit into four bytes */ proto_tree_add_item(tree, hf_opcua_app_nsid, tvb, iOffset, 4, ENC_LITTLE_ENDIAN); iOffset+=4; Numeric = tvb_get_letohl(tvb, iOffset); proto_tree_add_item(tree, <API key>, tvb, iOffset, 4, ENC_LITTLE_ENDIAN); iOffset+=4; break; case 0x03: /* string */ case 0x04: /* uri */ case 0x05: /* guid */ case 0x06: /* byte string */ /* NOT USED */ break; }; *pOffset = iOffset; return Numeric; }
#ifndef SPARC_TDEP_H #define SPARC_TDEP_H 1 struct frame_info; struct gdbarch; struct regcache; struct regset; struct <API key>; /* Register offsets for the general-purpose register set. */ struct sparc_gregmap { int r_psr_offset; int r_pc_offset; int r_npc_offset; int r_y_offset; int r_wim_offset; int r_tbr_offset; int r_g1_offset; int r_l0_offset; int r_y_size; }; struct sparc_fpregmap { int r_f0_offset; int r_fsr_offset; }; /* SPARC <API key> information. */ struct gdbarch_tdep { /* Register numbers for the PN and nPC registers. The definitions for (64-bit) UltraSPARC differ from the (32-bit) SPARC definitions. */ int pc_regnum; int npc_regnum; /* Register sets. */ const struct regset *gregset; size_t sizeof_gregset; const struct regset *fpregset; size_t sizeof_fpregset; /* Offset of saved PC in jmp_buf. */ int jb_pc_offset; /* Size of an Procedure Linkage Table (PLT) entry, 0 if we shouldn't treat the PLT special when doing prologue analysis. */ size_t plt_entry_size; /* Alternative location for trap return. Used for single-stepping. */ CORE_ADDR (*step_trap) (struct frame_info *frame, unsigned long insn); /* ISA-specific data types. */ struct type *sparc_psr_type; struct type *sparc_fsr_type; struct type *sparc64_pstate_type; struct type *sparc64_fsr_type; struct type *sparc64_fprs_type; }; /* Register numbers of various important registers. */ enum sparc_regnum { SPARC_G0_REGNUM, SPARC_G1_REGNUM, SPARC_G2_REGNUM, SPARC_G3_REGNUM, SPARC_G4_REGNUM, SPARC_G5_REGNUM, SPARC_G6_REGNUM, SPARC_G7_REGNUM, SPARC_O0_REGNUM, SPARC_O1_REGNUM, SPARC_O2_REGNUM, SPARC_O3_REGNUM, SPARC_O4_REGNUM, SPARC_O5_REGNUM, SPARC_SP_REGNUM, /* %sp (%o6) */ SPARC_O7_REGNUM, SPARC_L0_REGNUM, SPARC_L1_REGNUM, SPARC_L2_REGNUM, SPARC_L3_REGNUM, SPARC_L4_REGNUM, SPARC_L5_REGNUM, SPARC_L6_REGNUM, SPARC_L7_REGNUM, SPARC_I0_REGNUM, SPARC_I1_REGNUM, SPARC_I2_REGNUM, SPARC_I3_REGNUM, SPARC_I4_REGNUM, SPARC_I5_REGNUM, SPARC_FP_REGNUM, /* %fp (%i6) */ SPARC_I7_REGNUM, SPARC_F0_REGNUM, SPARC_F1_REGNUM, SPARC_F2_REGNUM, SPARC_F3_REGNUM, SPARC_F4_REGNUM, SPARC_F5_REGNUM, SPARC_F6_REGNUM, SPARC_F7_REGNUM, SPARC_F31_REGNUM /* %f31 */ = SPARC_F0_REGNUM + 31 }; enum sparc32_regnum { SPARC32_Y_REGNUM = SPARC_F31_REGNUM + 1, SPARC32_PSR_REGNUM, /* %psr */ SPARC32_WIM_REGNUM, /* %wim */ SPARC32_TBR_REGNUM, /* %tbr */ SPARC32_PC_REGNUM, SPARC32_NPC_REGNUM, /* %npc */ SPARC32_FSR_REGNUM, /* %fsr */ SPARC32_CSR_REGNUM, /* %csr */ /* Pseudo registers. */ SPARC32_D0_REGNUM, SPARC32_D30_REGNUM /* %d30 */ = SPARC32_D0_REGNUM + 15 }; struct sparc_frame_cache { /* Base address. */ CORE_ADDR base; CORE_ADDR pc; /* Do we have a frame? */ int frameless_p; /* The offset from the base register to the CFA. */ int frame_offset; /* Mask of `local' and `in' registers saved in the register save area. */ unsigned short int saved_regs_mask; /* Mask of `out' registers copied or renamed to their `in' sibling. */ unsigned char copied_regs_mask; /* Do we have a Structure, Union or Quad-Precision return value? */ int struct_return_p; /* Table of saved registers. */ struct <API key> *saved_regs; }; /* Fetch the instruction at PC. */ extern unsigned long <API key> (CORE_ADDR pc); /* Fetch StackGhost Per-Process XOR cookie. */ extern ULONGEST sparc_fetch_wcookie (struct gdbarch *gdbarch); /* Record the effect of a SAVE instruction on CACHE. */ extern void <API key> (struct sparc_frame_cache *cache); /* Do a full analysis of the prologue at PC and update CACHE accordingly. */ extern CORE_ADDR <API key> (struct gdbarch *gdbarch, CORE_ADDR pc, CORE_ADDR current_pc, struct sparc_frame_cache *cache); extern struct sparc_frame_cache * sparc_frame_cache (struct frame_info *this_frame, void **this_cache); extern struct sparc_frame_cache * sparc32_frame_cache (struct frame_info *this_frame, void **this_cache); extern int <API key> (struct gdbarch *gdbarch, CORE_ADDR pc); extern void <API key> (struct regcache *regcache, CORE_ADDR sp, int regnum); extern void <API key> (const struct regcache *regcache, CORE_ADDR sp, int regnum); /* Register offsets for SunOS 4. */ extern const struct sparc_gregmap <API key>; extern const struct sparc_fpregmap <API key>; extern const struct sparc_fpregmap <API key>; extern void <API key> (const struct sparc_gregmap *gregmap, struct regcache *regcache, int regnum, const void *gregs); extern void <API key> (const struct sparc_gregmap *gregmap, const struct regcache *regcache, int regnum, void *gregs); extern void <API key> (const struct sparc_fpregmap *fpregmap, struct regcache *regcache, int regnum, const void *fpregs); extern void <API key> (const struct sparc_fpregmap *fpregmap, const struct regcache *regcache, int regnum, void *fpregs); extern int <API key> (CORE_ADDR pc); /* Functions and variables exported from sparc-sol2-tdep.c. */ /* Register offsets for Solaris 2. */ extern const struct sparc_gregmap <API key>; extern const struct sparc_fpregmap <API key>; extern int <API key> (CORE_ADDR pc, const char *name); extern const char *<API key> (const char *name); extern void <API key> (struct gdbarch_info info, struct gdbarch *gdbarch); /* Functions and variables exported from sparcnbsd-tdep.c. */ /* Register offsets for NetBSD. */ extern const struct sparc_gregmap sparc32nbsd_gregmap; /* Return the address of a system call's alternative return address. */ extern CORE_ADDR sparcnbsd_step_trap (struct frame_info *frame, unsigned long insn); extern void <API key> (struct gdbarch_info info, struct gdbarch *gdbarch); extern struct <API key> * <API key> (struct frame_info *next_frame); #endif /* sparc-tdep.h */
#define RADEON_VERSION "0.1.6" #include <linux/config.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/tty.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/fb.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/pci.h> #include <linux/vmalloc.h> #include <asm/io.h> #include <asm/uaccess.h> #if defined(__powerpc__) #include <asm/prom.h> #include <asm/pci-bridge.h> #include "macmodes.h" #ifdef CONFIG_NVRAM #include <linux/nvram.h> #endif #ifdef <API key> #include <asm/backlight.h> #endif #ifdef CONFIG_BOOTX_TEXT #include <asm/btext.h> #endif #ifdef CONFIG_ADB_PMU #include <linux/adb.h> #include <linux/pmu.h> #endif #endif /* __powerpc__ */ #ifdef CONFIG_MTRR #include <asm/mtrr.h> #endif #include <video/radeon.h> #include <linux/radeonfb.h> #define DEBUG 1 #if DEBUG #define RTRACE printk #else #define RTRACE if(0) printk #endif // XXX #undef CONFIG_PMAC_PBOOK enum radeon_chips { RADEON_QD, RADEON_QE, RADEON_QF, RADEON_QG, RADEON_QY, RADEON_QZ, RADEON_LW, RADEON_LX, RADEON_LY, RADEON_LZ, RADEON_QL, RADEON_QN, RADEON_QO, RADEON_Ql, RADEON_BB, RADEON_QW, RADEON_QX, RADEON_Id, RADEON_Ie, RADEON_If, RADEON_Ig, RADEON_Ya, RADEON_Yd, RADEON_Ld, RADEON_Le, RADEON_Lf, RADEON_Lg, RADEON_ND, RADEON_NE, RADEON_NF, RADEON_NG, RADEON_QM }; enum radeon_arch { RADEON_R100, RADEON_RV100, RADEON_R200, RADEON_RV200, RADEON_RV250, RADEON_R300, RADEON_M6, RADEON_M7, RADEON_M9 }; static struct radeon_chip_info { const char *name; unsigned char arch; } radeon_chip_info[] __devinitdata = { { "QD", RADEON_R100 }, { "QE", RADEON_R100 }, { "QF", RADEON_R100 }, { "QG", RADEON_R100 }, { "VE QY", RADEON_RV100 }, { "VE QZ", RADEON_RV100 }, { "M7 LW", RADEON_M7 }, { "M7 LX", RADEON_M7 }, { "M6 LY", RADEON_M6 }, { "M6 LZ", RADEON_M6 }, { "8500 QL", RADEON_R200 }, { "8500 QN", RADEON_R200 }, { "8500 QO", RADEON_R200 }, { "8500 Ql", RADEON_R200 }, { "8500 BB", RADEON_R200 }, { "7500 QW", RADEON_RV200 }, { "7500 QX", RADEON_RV200 }, { "9000 Id", RADEON_RV250 }, { "9000 Ie", RADEON_RV250 }, { "9000 If", RADEON_RV250 }, { "9000 Ig", RADEON_RV250 }, { "M9 Ld", RADEON_M9 }, { "M9 Le", RADEON_M9 }, { "M9 Lf", RADEON_M9 }, { "M9 Lg", RADEON_M9 }, { "9700 ND", RADEON_R300 }, { "9700 NE", RADEON_R300 }, { "9700 NF", RADEON_R300 }, { "9700 NG", RADEON_R300 }, { "9100 QM", RADEON_R200 } }; enum radeon_montype { MT_NONE, MT_CRT, /* CRT */ MT_LCD, /* LCD */ MT_DFP, /* DVI */ MT_CTV, /* composite TV */ MT_STV /* S-Video out */ }; static struct pci_device_id radeonfb_pci_table[] = { { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QD}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QE}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QF}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QG}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QY}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QZ}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_LW}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_LX}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_LY}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_LZ}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QL}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QN}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QO}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_Ql}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_BB}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QW}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QX}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_Id}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_Ie}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_If}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_Ig}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_Ya}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_Yd}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_Ld}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_Le}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_Lf}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_Lg}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_ND}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_NE}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_NF}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_NG}, { PCI_VENDOR_ID_ATI, <API key>, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RADEON_QM}, { 0, } }; MODULE_DEVICE_TABLE(pci, radeonfb_pci_table); typedef struct { u16 reg; u32 val; } reg_val; /* these common regs are cleared before mode setting so they do not * interfere with anything */ static reg_val common_regs[] = { { OVR_CLR, 0 }, { OVR_WID_LEFT_RIGHT, 0 }, { OVR_WID_TOP_BOTTOM, 0 }, { OV0_SCALE_CNTL, 0 }, { SUBPIC_CNTL, 0 }, { VIPH_CONTROL, 0 }, { I2C_CNTL_1, 0 }, { GEN_INT_CNTL, 0 }, { CAP0_TRIG_CNTL, 0 }, }; static reg_val common_regs_m6[] = { { OVR_CLR, 0 }, { OVR_WID_LEFT_RIGHT, 0 }, { OVR_WID_TOP_BOTTOM, 0 }, { OV0_SCALE_CNTL, 0 }, { SUBPIC_CNTL, 0 }, { GEN_INT_CNTL, 0 }, { CAP0_TRIG_CNTL, 0 } }; typedef struct { u8 clock_chip_type; u8 struct_size; u8 accelerator_entry; u8 VGA_entry; u16 VGA_table_offset; u16 POST_table_offset; u16 XCLK; u16 MCLK; u8 num_PLL_blocks; u8 size_PLL_blocks; u16 PCLK_ref_freq; u16 PCLK_ref_divider; u32 PCLK_min_freq; u32 PCLK_max_freq; u16 MCLK_ref_freq; u16 MCLK_ref_divider; u32 MCLK_min_freq; u32 MCLK_max_freq; u16 XCLK_ref_freq; u16 XCLK_ref_divider; u32 XCLK_min_freq; u32 XCLK_max_freq; } __attribute__ ((packed)) PLL_BLOCK; struct pll_info { int ppll_max; int ppll_min; int xclk; int ref_div; int ref_clk; }; struct ram_info { int ml; int mb; int trcd; int trp; int twr; int cl; int tr2w; int loop_latency; int rloop; }; struct radeon_regs { /* CRTC regs */ u32 crtc_h_total_disp; u32 <API key>; u32 crtc_v_total_disp; u32 <API key>; u32 crtc_pitch; u32 crtc_gen_cntl; u32 crtc_ext_cntl; u32 dac_cntl; u32 flags; u32 pix_clock; int xres, yres; /* DDA regs */ u32 dda_config; u32 dda_on_off; /* PLL regs */ u32 ppll_div_3; u32 ppll_ref_div; u32 vclk_ecp_cntl; /* Flat panel regs */ u32 <API key>; u32 <API key>; u32 fp_gen_cntl; u32 fp_h_sync_strt_wid; u32 fp_horz_stretch; u32 fp_panel_cntl; u32 fp_v_sync_strt_wid; u32 fp_vert_stretch; u32 lvds_gen_cntl; u32 lvds_pll_cntl; u32 tmds_crc; u32 <API key>; #if defined(__BIG_ENDIAN) u32 surface_cntl; #endif }; struct radeonfb_info { struct fb_info info; struct radeon_regs state; struct radeon_regs init_state; char name[32]; char ram_type[12]; unsigned long mmio_base_phys; unsigned long fb_base_phys; void __iomem *mmio_base; void __iomem *fb_base; struct pci_dev *pdev; unsigned char *EDID; unsigned char __iomem *bios_seg; u32 pseudo_palette[17]; struct { u8 red, green, blue, pad; } palette[256]; int chipset; unsigned char arch; int video_ram; u8 rev; int pitch, bpp, depth; int xres, yres, pixclock; int xres_virtual, yres_virtual; u32 accel_flags; int use_default_var; int got_dfpinfo; int hasCRTC2; int crtDisp_type; int dviDisp_type; int panel_xres, panel_yres; int clock; int hOver_plus, hSync_width, hblank; int vOver_plus, vSync_width, vblank; int hAct_high, vAct_high, interlaced; int synct, misc; u32 dp_gui_master_cntl; struct pll_info pll; int pll_output_freq, post_div, fb_div; struct ram_info ram; int mtrr_hdl; #ifdef CONFIG_PMAC_PBOOK int pm_reg; u32 save_regs[64]; u32 mdll, mdll2; #endif /* CONFIG_PMAC_PBOOK */ int asleep; struct radeonfb_info *next; }; static struct fb_var_screeninfo <API key> = { 640, 480, 640, 480, 0, 0, 8, 0, {0, 6, 0}, {0, 6, 0}, {0, 6, 0}, {0, 0, 0}, 0, 0, -1, -1, 0, 39721, 40, 24, 32, 11, 96, 2, 0, <API key> }; /* * IO macros */ #define INREG8(addr) readb((rinfo->mmio_base)+addr) #define OUTREG8(addr,val) writeb(val, (rinfo->mmio_base)+addr) #define INREG(addr) readl((rinfo->mmio_base)+addr) #define OUTREG(addr,val) writel(val, (rinfo->mmio_base)+addr) #define OUTPLL(addr,val) \ do { \ OUTREG8(CLOCK_CNTL_INDEX, (addr & 0x0000003f) | 0x00000080); \ OUTREG(CLOCK_CNTL_DATA, val); \ } while(0) #define OUTPLLP(addr,val,mask) \ do { \ unsigned int _tmp = INPLL(addr); \ _tmp &= (mask); \ _tmp |= (val); \ OUTPLL(addr, _tmp); \ } while (0) #define OUTREGP(addr,val,mask) \ do { \ unsigned int _tmp = INREG(addr); \ _tmp &= (mask); \ _tmp |= (val); \ OUTREG(addr, _tmp); \ } while (0) static __inline__ u32 _INPLL(struct radeonfb_info *rinfo, u32 addr) { OUTREG8(CLOCK_CNTL_INDEX, addr & 0x0000003f); return (INREG(CLOCK_CNTL_DATA)); } #define INPLL(addr) _INPLL(rinfo, addr) #define PRIMARY_MONITOR(rinfo) ((rinfo->dviDisp_type != MT_NONE) && \ (rinfo->dviDisp_type != MT_STV) && \ (rinfo->dviDisp_type != MT_CTV) ? \ rinfo->dviDisp_type : rinfo->crtDisp_type) static char *GET_MON_NAME(int type) { char *pret = NULL; switch (type) { case MT_NONE: pret = "no"; break; case MT_CRT: pret = "CRT"; break; case MT_DFP: pret = "DFP"; break; case MT_LCD: pret = "LCD"; break; case MT_CTV: pret = "CTV"; break; case MT_STV: pret = "STV"; break; } return pret; } /* * 2D engine routines */ static __inline__ void radeon_engine_flush (struct radeonfb_info *rinfo) { int i; /* initiate flush */ OUTREGP(<API key>, RB2D_DC_FLUSH_ALL, ~RB2D_DC_FLUSH_ALL); for (i=0; i < 2000000; i++) { if (!(INREG(<API key>) & RB2D_DC_BUSY)) break; } } static __inline__ void _radeon_fifo_wait (struct radeonfb_info *rinfo, int entries) { int i; for (i=0; i<2000000; i++) if ((INREG(RBBM_STATUS) & 0x7f) >= entries) return; } static __inline__ void _radeon_engine_idle (struct radeonfb_info *rinfo) { int i; /* ensure FIFO is empty before waiting for idle */ _radeon_fifo_wait (rinfo, 64); for (i=0; i<2000000; i++) { if (((INREG(RBBM_STATUS) & GUI_ACTIVE)) == 0) { radeon_engine_flush (rinfo); return; } } } #define radeon_engine_idle() _radeon_engine_idle(rinfo) #define radeon_fifo_wait(entries) _radeon_fifo_wait(rinfo,entries) /* * helper routines */ static __inline__ u32 radeon_get_dstbpp(u16 depth) { switch (depth) { case 8: return DST_8BPP; case 15: return DST_15BPP; case 16: return DST_16BPP; case 32: return DST_32BPP; default: return 0; } } static inline int var_to_depth(const struct fb_var_screeninfo *var) { if (var->bits_per_pixel != 16) return var->bits_per_pixel; return (var->green.length == 6) ? 16 : 15; } static void <API key>(struct radeonfb_info *rinfo) { u32 clock_cntl_index, mclk_cntl, rbbm_soft_reset; radeon_engine_flush (rinfo); clock_cntl_index = INREG(CLOCK_CNTL_INDEX); mclk_cntl = INPLL(MCLK_CNTL); OUTPLL(MCLK_CNTL, (mclk_cntl | FORCEON_MCLKA | FORCEON_MCLKB | FORCEON_YCLKA | FORCEON_YCLKB | FORCEON_MC | FORCEON_AIC)); rbbm_soft_reset = INREG(RBBM_SOFT_RESET); OUTREG(RBBM_SOFT_RESET, rbbm_soft_reset | SOFT_RESET_CP | SOFT_RESET_HI | SOFT_RESET_SE | SOFT_RESET_RE | SOFT_RESET_PP | SOFT_RESET_E2 | SOFT_RESET_RB); INREG(RBBM_SOFT_RESET); OUTREG(RBBM_SOFT_RESET, rbbm_soft_reset & (u32) ~(SOFT_RESET_CP | SOFT_RESET_HI | SOFT_RESET_SE | SOFT_RESET_RE | SOFT_RESET_PP | SOFT_RESET_E2 | SOFT_RESET_RB)); INREG(RBBM_SOFT_RESET); OUTPLL(MCLK_CNTL, mclk_cntl); OUTREG(CLOCK_CNTL_INDEX, clock_cntl_index); OUTREG(RBBM_SOFT_RESET, rbbm_soft_reset); return; } #define radeon_engine_reset() <API key>(rinfo) static __inline__ u8 <API key>(int post_div) { switch (post_div) { case 1: return 0x00; case 2: return 0x01; case 3: return 0x04; case 4: return 0x02; case 6: return 0x06; case 8: return 0x03; case 12: return 0x07; default: return 0x02; } } static __inline__ int round_div(int num, int den) { return (num + (den / 2)) / den; } static __inline__ int min_bits_req(int val) { int bits_req = 0; if (val == 0) bits_req = 1; while (val) { val >>= 1; bits_req++; } return (bits_req); } static __inline__ int _max(int val1, int val2) { if (val1 >= val2) return val1; else return val2; } /* * globals */ static char *mode_option __initdata; static char noaccel = 0; static char mirror = 0; static int panel_yres __initdata = 0; static char force_dfp __initdata = 0; static struct radeonfb_info *board_list = NULL; static char nomtrr __initdata = 0; /* * prototypes */ static void radeon_save_state (struct radeonfb_info *rinfo, struct radeon_regs *save); static void radeon_engine_init (struct radeonfb_info *rinfo); static void radeon_write_mode (struct radeonfb_info *rinfo, struct radeon_regs *mode); static int __devinit radeon_set_fbinfo (struct radeonfb_info *rinfo); static int __devinit radeon_init_disp (struct radeonfb_info *rinfo); static int <API key> (struct radeonfb_info *rinfo, struct fb_var_screeninfo *var); static void __iomem *radeon_find_rom(struct radeonfb_info *rinfo); static void radeon_get_pllinfo(struct radeonfb_info *rinfo, void __iomem *bios_seg); static void radeon_get_moninfo (struct radeonfb_info *rinfo); static int radeon_get_dfpinfo (struct radeonfb_info *rinfo); static int <API key>(struct radeonfb_info *rinfo); static void radeon_get_EDID(struct radeonfb_info *rinfo); static int <API key>(struct radeonfb_info *rinfo); static void <API key>(struct radeonfb_info *rinfo); #ifdef CONFIG_PPC_OF static int radeon_read_OF (struct radeonfb_info *rinfo); static int radeon_get_EDID_OF(struct radeonfb_info *rinfo); extern struct device_node *<API key>(struct pci_dev *dev); #ifdef CONFIG_PMAC_PBOOK int radeon_sleep_notify(struct pmu_sleep_notifier *self, int when); static struct pmu_sleep_notifier <API key> = { radeon_sleep_notify, SLEEP_LEVEL_VIDEO, }; #endif /* CONFIG_PMAC_PBOOK */ #ifdef <API key> static int <API key>(int on, int level, void *data); static int <API key>(int level, void *data); static struct <API key> <API key> = { <API key>, <API key> }; #endif /* <API key> */ #endif /* CONFIG_PPC_OF */ static void __iomem *radeon_find_rom(struct radeonfb_info *rinfo) { #if defined(__i386__) u32 segstart; char __iomem *rom_base; char __iomem *rom; int stage; int i,j; char aty_rom_sig[] = "761295520"; char *radeon_sig[] = { "RG6", "RADEON" }; for(segstart=0x000c0000; segstart<0x000f0000; segstart+=0x00001000) { stage = 1; rom_base = ioremap(segstart, 0x1000); if ((*rom_base == 0x55) && (((*(rom_base + 1)) & 0xff) == 0xaa)) stage = 2; if (stage != 2) { iounmap(rom_base); continue; } rom = rom_base; for (i = 0; (i < 128 - strlen(aty_rom_sig)) && (stage != 3); i++) { if (aty_rom_sig[0] == *rom) if (strncmp(aty_rom_sig, rom, strlen(aty_rom_sig)) == 0) stage = 3; rom++; } if (stage != 3) { iounmap(rom_base); continue; } rom = rom_base; for (i = 0; (i < 512) && (stage != 4); i++) { for(j = 0;j < sizeof(radeon_sig)/sizeof(char *);j++) { if (radeon_sig[j][0] == *rom) if (strncmp(radeon_sig[j], rom, strlen(radeon_sig[j])) == 0) { stage = 4; break; } } rom++; } if (stage != 4) { iounmap(rom_base); continue; } return rom_base; } #endif return NULL; } static void radeon_get_pllinfo(struct radeonfb_info *rinfo, void __iomem *bios_seg) { void __iomem *bios_header; void __iomem *header_ptr; u16 bios_header_offset, pll_info_offset; PLL_BLOCK pll; if (bios_seg) { bios_header = bios_seg + 0x48L; header_ptr = bios_header; bios_header_offset = readw(header_ptr); bios_header = bios_seg + bios_header_offset; bios_header += 0x30; header_ptr = bios_header; pll_info_offset = readw(header_ptr); header_ptr = bios_seg + pll_info_offset; memcpy_fromio(&pll, header_ptr, 50); rinfo->pll.xclk = (u32)pll.XCLK; rinfo->pll.ref_clk = (u32)pll.PCLK_ref_freq; rinfo->pll.ref_div = (u32)pll.PCLK_ref_divider; rinfo->pll.ppll_min = pll.PCLK_min_freq; rinfo->pll.ppll_max = pll.PCLK_max_freq; printk("radeonfb: ref_clk=%d, ref_div=%d, xclk=%d from BIOS\n", rinfo->pll.ref_clk, rinfo->pll.ref_div, rinfo->pll.xclk); } else { #ifdef CONFIG_PPC_OF if (radeon_read_OF(rinfo)) { unsigned int tmp, Nx, M, ref_div, xclk; tmp = INPLL(X_MPLL_REF_FB_DIV); ref_div = INPLL(PPLL_REF_DIV) & 0x3ff; Nx = (tmp & 0xff00) >> 8; M = (tmp & 0xff); xclk = ((((2 * Nx * rinfo->pll.ref_clk) + (M)) / (2 * M))); rinfo->pll.xclk = xclk; rinfo->pll.ref_div = ref_div; rinfo->pll.ppll_min = 12000; rinfo->pll.ppll_max = 35000; printk("radeonfb: ref_clk=%d, ref_div=%d, xclk=%d from OF\n", rinfo->pll.ref_clk, rinfo->pll.ref_div, rinfo->pll.xclk); return; } #endif /* no BIOS or BIOS not found, use defaults */ switch (rinfo->chipset) { case <API key>: case <API key>: rinfo->pll.ppll_max = 35000; rinfo->pll.ppll_min = 12000; rinfo->pll.xclk = 23000; rinfo->pll.ref_div = 12; rinfo->pll.ref_clk = 2700; break; case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: rinfo->pll.ppll_max = 35000; rinfo->pll.ppll_min = 12000; rinfo->pll.xclk = 27500; rinfo->pll.ref_div = 12; rinfo->pll.ref_clk = 2700; break; case <API key>: case <API key>: case <API key>: case <API key>: rinfo->pll.ppll_max = 35000; rinfo->pll.ppll_min = 12000; rinfo->pll.xclk = 25000; rinfo->pll.ref_div = 12; rinfo->pll.ref_clk = 2700; break; case <API key>: case <API key>: case <API key>: case <API key>: rinfo->pll.ppll_max = 40000; rinfo->pll.ppll_min = 20000; rinfo->pll.xclk = 27000; rinfo->pll.ref_div = 12; rinfo->pll.ref_clk = 2700; break; case <API key>: case <API key>: case <API key>: case <API key>: default: rinfo->pll.ppll_max = 35000; rinfo->pll.ppll_min = 12000; rinfo->pll.xclk = 16600; rinfo->pll.ref_div = 67; rinfo->pll.ref_clk = 2700; break; } printk("radeonfb: ref_clk=%d, ref_div=%d, xclk=%d defaults\n", rinfo->pll.ref_clk, rinfo->pll.ref_div, rinfo->pll.xclk); } } static void radeon_get_moninfo (struct radeonfb_info *rinfo) { unsigned int tmp; if (force_dfp) { rinfo->dviDisp_type = MT_DFP; return; } tmp = INREG(BIOS_4_SCRATCH); printk(KERN_DEBUG "radeon_get_moninfo: bios 4 scratch = %x\n", tmp); if (rinfo->hasCRTC2) { /* primary DVI port */ if (tmp & 0x08) rinfo->dviDisp_type = MT_DFP; else if (tmp & 0x4) rinfo->dviDisp_type = MT_LCD; else if (tmp & 0x200) rinfo->dviDisp_type = MT_CRT; else if (tmp & 0x10) rinfo->dviDisp_type = MT_CTV; else if (tmp & 0x20) rinfo->dviDisp_type = MT_STV; /* secondary CRT port */ if (tmp & 0x2) rinfo->crtDisp_type = MT_CRT; else if (tmp & 0x800) rinfo->crtDisp_type = MT_DFP; else if (tmp & 0x400) rinfo->crtDisp_type = MT_LCD; else if (tmp & 0x1000) rinfo->crtDisp_type = MT_CTV; else if (tmp & 0x2000) rinfo->crtDisp_type = MT_STV; } else { rinfo->dviDisp_type = MT_NONE; tmp = INREG(FP_GEN_CNTL); if (tmp & FP_EN_TMDS) rinfo->crtDisp_type = MT_DFP; else rinfo->crtDisp_type = MT_CRT; } } static void radeon_get_EDID(struct radeonfb_info *rinfo) { #ifdef CONFIG_PPC_OF if (!radeon_get_EDID_OF(rinfo)) RTRACE("radeonfb: could not retrieve EDID from OF\n"); #else /* XXX use other methods later */ #endif } #ifdef CONFIG_PPC_OF static int radeon_get_EDID_OF(struct radeonfb_info *rinfo) { struct device_node *dp; unsigned char *pedid = NULL; static char *propnames[] = { "DFP,EDID", "LCD,EDID", "EDID", "EDID1", NULL }; int i; dp = <API key>(rinfo->pdev); while (dp != NULL) { for (i = 0; propnames[i] != NULL; ++i) { pedid = (unsigned char *) get_property(dp, propnames[i], NULL); if (pedid != NULL) { rinfo->EDID = pedid; return 1; } } dp = dp->child; } return 0; } #endif /* CONFIG_PPC_OF */ static int <API key>(struct radeonfb_info *rinfo) { unsigned char *block = rinfo->EDID; if (!block) return 0; /* jump to the detailed timing block section */ block += 54; rinfo->clock = (block[0] + (block[1] << 8)); rinfo->panel_xres = (block[2] + ((block[4] & 0xf0) << 4)); rinfo->hblank = (block[3] + ((block[4] & 0x0f) << 8)); rinfo->panel_yres = (block[5] + ((block[7] & 0xf0) << 4)); rinfo->vblank = (block[6] + ((block[7] & 0x0f) << 8)); rinfo->hOver_plus = (block[8] + ((block[11] & 0xc0) << 2)); rinfo->hSync_width = (block[9] + ((block[11] & 0x30) << 4)); rinfo->vOver_plus = ((block[10] >> 4) + ((block[11] & 0x0c) << 2)); rinfo->vSync_width = ((block[10] & 0x0f) + ((block[11] & 0x03) << 4)); rinfo->interlaced = ((block[17] & 0x80) >> 7); rinfo->synct = ((block[17] & 0x18) >> 3); rinfo->misc = ((block[17] & 0x06) >> 1); rinfo->hAct_high = rinfo->vAct_high = 0; if (rinfo->synct == 3) { if (rinfo->misc & 2) rinfo->hAct_high = 1; if (rinfo->misc & 1) rinfo->vAct_high = 1; } printk("radeonfb: detected DFP panel size from EDID: %dx%d\n", rinfo->panel_xres, rinfo->panel_yres); rinfo->got_dfpinfo = 1; return 1; } static void <API key>(struct radeonfb_info *rinfo) { struct fb_var_screeninfo *var = &<API key>; var->xres = rinfo->panel_xres; var->yres = rinfo->panel_yres; var->xres_virtual = rinfo->panel_xres; var->yres_virtual = rinfo->panel_yres; var->xoffset = var->yoffset = 0; var->bits_per_pixel = 8; var->pixclock = 100000000 / rinfo->clock; var->left_margin = (rinfo->hblank - rinfo->hOver_plus - rinfo->hSync_width); var->right_margin = rinfo->hOver_plus; var->upper_margin = (rinfo->vblank - rinfo->vOver_plus - rinfo->vSync_width); var->lower_margin = rinfo->vOver_plus; var->hsync_len = rinfo->hSync_width; var->vsync_len = rinfo->vSync_width; var->sync = 0; if (rinfo->synct == 3) { if (rinfo->hAct_high) var->sync |= <API key>; if (rinfo->vAct_high) var->sync |= <API key>; } var->vmode = 0; if (rinfo->interlaced) var->vmode |= FB_VMODE_INTERLACED; rinfo->use_default_var = 1; } static int <API key>(struct radeonfb_info *rinfo) { char __iomem *fpbiosstart, *tmp, *tmp0; char stmp[30]; int i; if (!rinfo->bios_seg) return 0; if (!(fpbiosstart = rinfo->bios_seg + readw(rinfo->bios_seg + 0x48))) { printk("radeonfb: Failed to detect DFP panel info using BIOS\n"); return 0; } if (!(tmp = rinfo->bios_seg + readw(fpbiosstart + 0x40))) { printk("radeonfb: Failed to detect DFP panel info using BIOS\n"); return 0; } for(i=0; i<24; i++) stmp[i] = readb(tmp+i+1); stmp[24] = 0; printk("radeonfb: panel ID string: %s\n", stmp); rinfo->panel_xres = readw(tmp + 25); rinfo->panel_yres = readw(tmp + 27); printk("radeonfb: detected DFP panel size from BIOS: %dx%d\n", rinfo->panel_xres, rinfo->panel_yres); for(i=0; i<32; i++) { tmp0 = rinfo->bios_seg + readw(tmp+64+i*2); if (tmp0 == 0) break; if ((readw(tmp0) == rinfo->panel_xres) && (readw(tmp0+2) == rinfo->panel_yres)) { rinfo->hblank = (readw(tmp0+17) - readw(tmp0+19)) * 8; rinfo->hOver_plus = ((readw(tmp0+21) - readw(tmp0+19) -1) * 8) & 0x7fff; rinfo->hSync_width = readb(tmp0+23) * 8; rinfo->vblank = readw(tmp0+24) - readw(tmp0+26); rinfo->vOver_plus = (readw(tmp0+28) & 0x7ff) - readw(tmp0+26); rinfo->vSync_width = (readw(tmp0+28) & 0xf800) >> 11; rinfo->clock = readw(tmp0+9); rinfo->got_dfpinfo = 1; return 1; } } return 0; } static int radeon_get_dfpinfo (struct radeonfb_info *rinfo) { unsigned int tmp; unsigned short a, b; if (<API key>(rinfo)) <API key>(rinfo); if (<API key>(rinfo)) <API key>(rinfo); if (!rinfo->got_dfpinfo) { /* * it seems all else has failed now and we * resort to probing registers for our DFP info */ if (panel_yres) { rinfo->panel_yres = panel_yres; } else { tmp = INREG(FP_VERT_STRETCH); tmp &= 0x00fff000; rinfo->panel_yres = (unsigned short)(tmp >> 0x0c) + 1; } switch (rinfo->panel_yres) { case 480: rinfo->panel_xres = 640; break; case 600: rinfo->panel_xres = 800; break; case 768: #if defined(__powerpc__) if (rinfo->dviDisp_type == MT_LCD) rinfo->panel_xres = 1152; else #endif rinfo->panel_xres = 1024; break; case 1024: rinfo->panel_xres = 1280; break; case 1050: rinfo->panel_xres = 1400; break; case 1200: rinfo->panel_xres = 1600; break; default: printk("radeonfb: Failed to detect DFP panel size\n"); return 0; } printk("radeonfb: detected DFP panel size from registers: %dx%d\n", rinfo->panel_xres, rinfo->panel_yres); tmp = INREG(<API key>); a = (tmp & <API key>) + 4; b = (tmp & 0x01ff0000) >> <API key>; rinfo->hblank = (a - b + 1) * 8; tmp = INREG(FP_H_SYNC_STRT_WID); rinfo->hOver_plus = (unsigned short) ((tmp & <API key>) >> <API key>) - b - 1; rinfo->hOver_plus *= 8; rinfo->hSync_width = (unsigned short) ((tmp & FP_H_SYNC_WID_MASK) >> FP_H_SYNC_WID_SHIFT); rinfo->hSync_width *= 8; tmp = INREG(<API key>); a = (tmp & <API key>) + 1; b = (tmp & FP_CRTC_V_DISP_MASK) >> <API key>; rinfo->vblank = a - b ; tmp = INREG(FP_V_SYNC_STRT_WID); rinfo->vOver_plus = (unsigned short) (tmp & FP_V_SYNC_STRT_MASK) - b + 1; rinfo->vSync_width = (unsigned short) ((tmp & FP_V_SYNC_WID_MASK) >> FP_V_SYNC_WID_SHIFT); return 1; } return 1; } #ifdef CONFIG_PPC_OF static int radeon_read_OF (struct radeonfb_info *rinfo) { struct device_node *dp; unsigned int *xtal; dp = <API key>(rinfo->pdev); xtal = (unsigned int *) get_property(dp, "ATY,RefCLK", NULL); rinfo->pll.ref_clk = *xtal / 10; if (*xtal) return 1; else return 0; } #endif static void radeon_engine_init (struct radeonfb_info *rinfo) { u32 temp; /* disable 3D engine */ OUTREG(RB3D_CNTL, 0); radeon_engine_reset (); radeon_fifo_wait (1); OUTREG(RB2D_DSTCACHE_MODE, 0); radeon_fifo_wait (1); temp = INREG(<API key>); OUTREG(<API key>, ((temp & 0xc0000000) | (rinfo->pitch << 0x16))); radeon_fifo_wait (1); OUTREGP(DP_DATATYPE, 0, ~HOST_BIG_ENDIAN_EN); radeon_fifo_wait (1); OUTREG(<API key>, (<API key> | <API key>)); temp = radeon_get_dstbpp(rinfo->depth); rinfo->dp_gui_master_cntl = ((temp << 8) | <API key>); radeon_fifo_wait (1); OUTREG(DP_GUI_MASTER_CNTL, (rinfo->dp_gui_master_cntl | <API key> | <API key>)); radeon_fifo_wait (7); /* clear line drawing regs */ OUTREG(DST_LINE_START, 0); OUTREG(DST_LINE_END, 0); /* set brush color regs */ OUTREG(DP_BRUSH_FRGD_CLR, 0xffffffff); OUTREG(DP_BRUSH_BKGD_CLR, 0x00000000); /* set source color regs */ OUTREG(DP_SRC_FRGD_CLR, 0xffffffff); OUTREG(DP_SRC_BKGD_CLR, 0x00000000); /* default write mask */ OUTREG(DP_WRITE_MSK, 0xffffffff); radeon_engine_idle (); } static int __devinit radeon_init_disp (struct radeonfb_info *rinfo) { struct fb_info *info = &rinfo->info; struct fb_var_screeninfo var; var = <API key>; if ((<API key>(rinfo, &var)) < 0) return -1; rinfo->depth = var_to_depth(&var); rinfo->bpp = var.bits_per_pixel; info->var = var; fb_alloc_cmap(&info->cmap, 256, 0); var.activate = FB_ACTIVATE_NOW; return 0; } static int <API key> (struct radeonfb_info *rinfo, struct fb_var_screeninfo *var) { #ifndef MODULE if (mode_option) fb_find_mode (var, &rinfo->info, mode_option, NULL, 0, NULL, 8); else #endif if (rinfo->use_default_var) /* We will use the modified default far */ *var = <API key>; else fb_find_mode (var, &rinfo->info, "640x480-8@60", NULL, 0, NULL, 0); if (noaccel) var->accel_flags &= ~FB_ACCELF_TEXT; else var->accel_flags |= FB_ACCELF_TEXT; return 0; } static int radeon_do_maximize(struct radeonfb_info *rinfo, struct fb_var_screeninfo *var, struct fb_var_screeninfo *v, int nom, int den) { static struct { int xres, yres; } modes[] = { {1600, 1280}, {1280, 1024}, {1024, 768}, {800, 600}, {640, 480}, {-1, -1} }; int i; /* use highest possible virtual resolution */ if (v->xres_virtual == -1 && v->yres_virtual == -1) { printk("radeonfb: using max available virtual resolution\n"); for (i=0; modes[i].xres != -1; i++) { if (modes[i].xres * nom / den * modes[i].yres < rinfo->video_ram / 2) break; } if (modes[i].xres == -1) { printk("radeonfb: could not find virtual resolution that fits into video memory!\n"); return -EINVAL; } v->xres_virtual = modes[i].xres; v->yres_virtual = modes[i].yres; printk("radeonfb: virtual resolution set to max of %dx%d\n", v->xres_virtual, v->yres_virtual); } else if (v->xres_virtual == -1) { v->xres_virtual = (rinfo->video_ram * den / (nom * v->yres_virtual * 2)) & ~15; } else if (v->yres_virtual == -1) { v->xres_virtual = (v->xres_virtual + 15) & ~15; v->yres_virtual = rinfo->video_ram * den / (nom * v->xres_virtual *2); } else { if (v->xres_virtual * nom / den * v->yres_virtual > rinfo->video_ram) { return -EINVAL; } } if (v->xres_virtual * nom / den >= 8192) { v->xres_virtual = 8192 * den / nom - 16; } if (v->xres_virtual < v->xres) return -EINVAL; if (v->yres_virtual < v->yres) return -EINVAL; return 0; } static int radeonfb_check_var (struct fb_var_screeninfo *var, struct fb_info *info) { struct radeonfb_info *rinfo = (struct radeonfb_info *) info->par; struct fb_var_screeninfo v; int nom, den; memcpy (&v, var, sizeof (v)); switch (v.bits_per_pixel) { case 0 ... 8: v.bits_per_pixel = 8; break; case 9 ... 16: v.bits_per_pixel = 16; break; case 17 ... 24: #if 0 /* Doesn't seem to work */ v.bits_per_pixel = 24; break; #endif return -EINVAL; case 25 ... 32: v.bits_per_pixel = 32; break; default: return -EINVAL; } switch (var_to_depth(&v)) { case 8: nom = den = 1; v.red.offset = v.green.offset = v.blue.offset = 0; v.red.length = v.green.length = v.blue.length = 8; v.transp.offset = v.transp.length = 0; break; case 15: nom = 2; den = 1; v.red.offset = 10; v.green.offset = 5; v.blue.offset = 0; v.red.length = v.green.length = v.blue.length = 5; v.transp.offset = v.transp.length = 0; break; case 16: nom = 2; den = 1; v.red.offset = 11; v.green.offset = 5; v.blue.offset = 0; v.red.length = 5; v.green.length = 6; v.blue.length = 5; v.transp.offset = v.transp.length = 0; break; case 24: nom = 4; den = 1; v.red.offset = 16; v.green.offset = 8; v.blue.offset = 0; v.red.length = v.blue.length = v.green.length = 8; v.transp.offset = v.transp.length = 0; break; case 32: nom = 4; den = 1; v.red.offset = 16; v.green.offset = 8; v.blue.offset = 0; v.red.length = v.blue.length = v.green.length = 8; v.transp.offset = 24; v.transp.length = 8; break; default: printk ("radeonfb: mode %dx%dx%d rejected, color depth invalid\n", var->xres, var->yres, var->bits_per_pixel); return -EINVAL; } if (radeon_do_maximize(rinfo, var, &v, nom, den) < 0) return -EINVAL; if (v.xoffset < 0) v.xoffset = 0; if (v.yoffset < 0) v.yoffset = 0; if (v.xoffset > v.xres_virtual - v.xres) v.xoffset = v.xres_virtual - v.xres - 1; if (v.yoffset > v.yres_virtual - v.yres) v.yoffset = v.yres_virtual - v.yres - 1; v.red.msb_right = v.green.msb_right = v.blue.msb_right = v.transp.offset = v.transp.length = v.transp.msb_right = 0; if (noaccel) v.accel_flags = 0; memcpy(var, &v, sizeof(v)); return 0; } static int <API key> (struct fb_var_screeninfo *var, struct fb_info *info) { struct radeonfb_info *rinfo = (struct radeonfb_info *) info; if ((var->xoffset + var->xres > var->xres_virtual) || (var->yoffset + var->yres > var->yres_virtual)) return -EINVAL; if (rinfo->asleep) return 0; OUTREG(CRTC_OFFSET, ((var->yoffset * var->xres_virtual + var->xoffset) * var->bits_per_pixel / 8) & ~7); return 0; } static int radeonfb_ioctl (struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg, struct fb_info *info) { struct radeonfb_info *rinfo = (struct radeonfb_info *) info; unsigned int tmp; u32 value = 0; int rc; switch (cmd) { /* * TODO: set mirror accordingly for non-Mobility chipsets with 2 CRTC's */ case <API key>: switch (rinfo->arch) { case RADEON_R100: case RADEON_RV100: case RADEON_R200: case RADEON_RV200: case RADEON_RV250: case RADEON_R300: return -EINVAL; default: /* RADEON M6, RADEON_M7, RADEON_M9 */ break; } rc = get_user(value, (__u32 __user *)arg); if (rc) return rc; if (value & 0x01) { tmp = INREG(LVDS_GEN_CNTL); tmp |= (LVDS_ON | LVDS_BLON); } else { tmp = INREG(LVDS_GEN_CNTL); tmp &= ~(LVDS_ON | LVDS_BLON); } OUTREG(LVDS_GEN_CNTL, tmp); if (value & 0x02) { tmp = INREG(CRTC_EXT_CNTL); tmp |= CRTC_CRT_ON; mirror = 1; } else { tmp = INREG(CRTC_EXT_CNTL); tmp &= ~CRTC_CRT_ON; mirror = 0; } OUTREG(CRTC_EXT_CNTL, tmp); break; case <API key>: switch (rinfo->arch) { case RADEON_R100: case RADEON_RV100: case RADEON_R200: case RADEON_RV200: case RADEON_RV250: case RADEON_R300: return -EINVAL; default: /* RADEON M6, RADEON_M7, RADEON_M9 */ break; } tmp = INREG(LVDS_GEN_CNTL); if ((LVDS_ON | LVDS_BLON) & tmp) value |= 0x01; tmp = INREG(CRTC_EXT_CNTL); if (CRTC_CRT_ON & tmp) value |= 0x02; return put_user(value, (__u32 __user *)arg); default: return -EINVAL; } return -EINVAL; } static int radeonfb_blank (int blank, struct fb_info *info) { struct radeonfb_info *rinfo = (struct radeonfb_info *) info; u32 val = INREG(CRTC_EXT_CNTL); u32 val2 = INREG(LVDS_GEN_CNTL); if (rinfo->asleep) return 0; #ifdef <API key> if (rinfo->dviDisp_type == MT_LCD && _machine == _MACH_Pmac) { <API key>(!blank); return 0; } #endif /* reset it */ val &= ~(CRTC_DISPLAY_DIS | CRTC_HSYNC_DIS | CRTC_VSYNC_DIS); val2 &= ~(LVDS_DISPLAY_DIS); switch (blank) { case FB_BLANK_UNBLANK: case FB_BLANK_NORMAL: break; case <API key>: val |= (CRTC_DISPLAY_DIS | CRTC_VSYNC_DIS); break; case <API key>: val |= (CRTC_DISPLAY_DIS | CRTC_HSYNC_DIS); break; case FB_BLANK_POWERDOWN: val |= (CRTC_DISPLAY_DIS | CRTC_VSYNC_DIS | CRTC_HSYNC_DIS); val2 |= (LVDS_DISPLAY_DIS); break; } switch (rinfo->dviDisp_type) { case MT_LCD: OUTREG(LVDS_GEN_CNTL, val2); break; case MT_CRT: default: OUTREG(CRTC_EXT_CNTL, val); break; } /* let fbcon do a soft blank for us */ return (blank == FB_BLANK_NORMAL) ? 1 : 0; } static int radeonfb_setcolreg (unsigned regno, unsigned red, unsigned green, unsigned blue, unsigned transp, struct fb_info *info) { struct radeonfb_info *rinfo = (struct radeonfb_info *) info; u32 pindex, vclk_cntl; unsigned int i; if (regno > 255) return 1; red >>= 8; green >>= 8; blue >>= 8; rinfo->palette[regno].red = red; rinfo->palette[regno].green = green; rinfo->palette[regno].blue = blue; /* default */ pindex = regno; if (!rinfo->asleep) { vclk_cntl = INPLL(VCLK_ECP_CNTL); OUTPLL(VCLK_ECP_CNTL, vclk_cntl & ~<API key>); if (rinfo->bpp == 16) { pindex = regno * 8; if (rinfo->depth == 16 && regno > 63) return 1; if (rinfo->depth == 15 && regno > 31) return 1; /* For 565, the green component is mixed one order below */ if (rinfo->depth == 16) { OUTREG(PALETTE_INDEX, pindex>>1); OUTREG(PALETTE_DATA, (rinfo->palette[regno>>1].red << 16) | (green << 8) | (rinfo->palette[regno>>1].blue)); green = rinfo->palette[regno<<1].green; } } if (rinfo->depth != 16 || regno < 32) { OUTREG(PALETTE_INDEX, pindex); OUTREG(PALETTE_DATA, (red << 16) | (green << 8) | blue); } OUTPLL(VCLK_ECP_CNTL, vclk_cntl); } if (regno < 16) { switch (rinfo->depth) { case 15: ((u16 *) (info->pseudo_palette))[regno] = (regno << 10) | (regno << 5) | regno; break; case 16: ((u16 *) (info->pseudo_palette))[regno] = (regno << 11) | (regno << 6) | regno; break; case 24: ((u32 *) (info->pseudo_palette))[regno] = (regno << 16) | (regno << 8) | regno; break; case 32: i = (regno << 8) | regno; ((u32 *) (info->pseudo_palette))[regno] = (i << 16) | i; break; } } return 0; } static void radeon_save_state (struct radeonfb_info *rinfo, struct radeon_regs *save) { /* CRTC regs */ save->crtc_gen_cntl = INREG(CRTC_GEN_CNTL); save->crtc_ext_cntl = INREG(CRTC_EXT_CNTL); save->dac_cntl = INREG(DAC_CNTL); save->crtc_h_total_disp = INREG(CRTC_H_TOTAL_DISP); save-><API key> = INREG(<API key>); save->crtc_v_total_disp = INREG(CRTC_V_TOTAL_DISP); save-><API key> = INREG(<API key>); save->crtc_pitch = INREG(CRTC_PITCH); #if defined(__BIG_ENDIAN) save->surface_cntl = INREG(SURFACE_CNTL); #endif /* FP regs */ save-><API key> = INREG(<API key>); save-><API key> = INREG(<API key>); save->fp_gen_cntl = INREG(FP_GEN_CNTL); save->fp_h_sync_strt_wid = INREG(FP_H_SYNC_STRT_WID); save->fp_horz_stretch = INREG(FP_HORZ_STRETCH); save->fp_v_sync_strt_wid = INREG(FP_V_SYNC_STRT_WID); save->fp_vert_stretch = INREG(FP_VERT_STRETCH); save->lvds_gen_cntl = INREG(LVDS_GEN_CNTL); save->lvds_pll_cntl = INREG(LVDS_PLL_CNTL); save->tmds_crc = INREG(TMDS_CRC); save-><API key> = INREG(<API key>); save->vclk_ecp_cntl = INPLL(VCLK_ECP_CNTL); } static int radeonfb_set_par (struct fb_info *info) { struct radeonfb_info *rinfo = (struct radeonfb_info *)info->par; struct fb_var_screeninfo *mode = &info->var; struct radeon_regs newmode; int hTotal, vTotal, hSyncStart, hSyncEnd, hSyncPol, vSyncStart, vSyncEnd, vSyncPol, cSync; u8 hsync_adj_tab[] = {0, 0x12, 9, 9, 6, 5}; u8 hsync_fudge_fp[] = {2, 2, 0, 0, 5, 5}; u32 dotClock = 1000000000 / mode->pixclock, sync, h_sync_pol, v_sync_pol; int freq = dotClock / 10; /* x 100 */ int xclk_freq, vclk_freq, xclk_per_trans, <API key>; int useable_precision, roff, ron; int min_bits, format = 0; int hsync_start, hsync_fudge, bytpp, hsync_wid, vsync_wid; int primary_mon = PRIMARY_MONITOR(rinfo); int depth = var_to_depth(mode); int accel = (mode->accel_flags & FB_ACCELF_TEXT) != 0; rinfo->xres = mode->xres; rinfo->yres = mode->yres; rinfo->xres_virtual = mode->xres_virtual; rinfo->yres_virtual = mode->yres_virtual; rinfo->pixclock = mode->pixclock; hSyncStart = mode->xres + mode->right_margin; hSyncEnd = hSyncStart + mode->hsync_len; hTotal = hSyncEnd + mode->left_margin; vSyncStart = mode->yres + mode->lower_margin; vSyncEnd = vSyncStart + mode->vsync_len; vTotal = vSyncEnd + mode->upper_margin; if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) { if (rinfo->panel_xres < mode->xres) rinfo->xres = mode->xres = rinfo->panel_xres; if (rinfo->panel_yres < mode->yres) rinfo->yres = mode->yres = rinfo->panel_yres; hTotal = mode->xres + rinfo->hblank; hSyncStart = mode->xres + rinfo->hOver_plus; hSyncEnd = hSyncStart + rinfo->hSync_width; vTotal = mode->yres + rinfo->vblank; vSyncStart = mode->yres + rinfo->vOver_plus; vSyncEnd = vSyncStart + rinfo->vSync_width; } sync = mode->sync; h_sync_pol = sync & <API key> ? 0 : 1; v_sync_pol = sync & <API key> ? 0 : 1; RTRACE("hStart = %d, hEnd = %d, hTotal = %d\n", hSyncStart, hSyncEnd, hTotal); RTRACE("vStart = %d, vEnd = %d, vTotal = %d\n", vSyncStart, vSyncEnd, vTotal); hsync_wid = (hSyncEnd - hSyncStart) / 8; vsync_wid = vSyncEnd - vSyncStart; if (hsync_wid == 0) hsync_wid = 1; else if (hsync_wid > 0x3f) /* max */ hsync_wid = 0x3f; if (vsync_wid == 0) vsync_wid = 1; else if (vsync_wid > 0x1f) /* max */ vsync_wid = 0x1f; hSyncPol = mode->sync & <API key> ? 0 : 1; vSyncPol = mode->sync & <API key> ? 0 : 1; cSync = mode->sync & <API key> ? (1 << 4) : 0; format = radeon_get_dstbpp(depth); bytpp = mode->bits_per_pixel >> 3; if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) hsync_fudge = hsync_fudge_fp[format-1]; else hsync_fudge = hsync_adj_tab[format-1]; hsync_start = hSyncStart - 8 + hsync_fudge; newmode.crtc_gen_cntl = CRTC_EXT_DISP_EN | CRTC_EN | (format << 8); if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) { newmode.crtc_ext_cntl = VGA_ATI_LINEAR | XCRT_CNT_EN; if (mirror) newmode.crtc_ext_cntl |= CRTC_CRT_ON; newmode.crtc_gen_cntl &= ~(CRTC_DBL_SCAN_EN | CRTC_INTERLACE_EN); } else { newmode.crtc_ext_cntl = VGA_ATI_LINEAR | XCRT_CNT_EN | CRTC_CRT_ON; } newmode.dac_cntl = /* INREG(DAC_CNTL) | */ DAC_MASK_ALL | DAC_VGA_ADR_EN | DAC_8BIT_EN; newmode.crtc_h_total_disp = ((((hTotal / 8) - 1) & 0x3ff) | (((mode->xres / 8) - 1) << 16)); newmode.<API key> = ((hsync_start & 0x1fff) | (hsync_wid << 16) | (h_sync_pol << 23)); newmode.crtc_v_total_disp = ((vTotal - 1) & 0xffff) | ((mode->yres - 1) << 16); newmode.<API key> = (((vSyncStart - 1) & 0xfff) | (vsync_wid << 16) | (v_sync_pol << 23)); if (accel) { /* We first calculate the engine pitch */ rinfo->pitch = ((mode->xres_virtual * ((mode->bits_per_pixel + 1) / 8) + 0x3f) & ~(0x3f)) >> 6; /* Then, re-multiply it to get the CRTC pitch */ newmode.crtc_pitch = (rinfo->pitch << 3) / ((mode->bits_per_pixel + 1) / 8); } else newmode.crtc_pitch = (mode->xres_virtual >> 3); newmode.crtc_pitch |= (newmode.crtc_pitch << 16); #if defined(__BIG_ENDIAN) /* * It looks like recent chips have a problem with SURFACE_CNTL, * setting <API key> completely disables the * swapper as well, so we leave it unset now. */ newmode.surface_cntl = 0; /* Setup swapping on both apertures, though we currently * only use aperture 0, enabling swapper on aperture 1 * won't harm */ switch (mode->bits_per_pixel) { case 16: newmode.surface_cntl |= <API key>; newmode.surface_cntl |= <API key>; break; case 24: case 32: newmode.surface_cntl |= <API key>; newmode.surface_cntl |= <API key>; break; } #endif rinfo->pitch = ((mode->xres_virtual * ((mode->bits_per_pixel + 1) / 8) + 0x3f) & ~(0x3f)) / 64; RTRACE("h_total_disp = 0x%x\t hsync_strt_wid = 0x%x\n", newmode.crtc_h_total_disp, newmode.<API key>); RTRACE("v_total_disp = 0x%x\t vsync_strt_wid = 0x%x\n", newmode.crtc_v_total_disp, newmode.<API key>); newmode.xres = mode->xres; newmode.yres = mode->yres; rinfo->bpp = mode->bits_per_pixel; rinfo->depth = depth; if (freq > rinfo->pll.ppll_max) freq = rinfo->pll.ppll_max; if (freq*12 < rinfo->pll.ppll_min) freq = rinfo->pll.ppll_min / 12; { struct { int divider; int bitvalue; } *post_div, post_divs[] = { { 1, 0 }, { 2, 1 }, { 4, 2 }, { 8, 3 }, { 3, 4 }, { 16, 5 }, { 6, 6 }, { 12, 7 }, { 0, 0 }, }; for (post_div = &post_divs[0]; post_div->divider; ++post_div) { rinfo->pll_output_freq = post_div->divider * freq; if (rinfo->pll_output_freq >= rinfo->pll.ppll_min && rinfo->pll_output_freq <= rinfo->pll.ppll_max) break; } rinfo->post_div = post_div->divider; rinfo->fb_div = round_div(rinfo->pll.ref_div*rinfo->pll_output_freq, rinfo->pll.ref_clk); newmode.ppll_ref_div = rinfo->pll.ref_div; newmode.ppll_div_3 = rinfo->fb_div | (post_div->bitvalue << 16); } newmode.vclk_ecp_cntl = rinfo->init_state.vclk_ecp_cntl; #ifdef CONFIG_PPC_OF /* Gross hack for iBook with M7 until I find out a proper fix */ if (<API key>("PowerBook4,3") && rinfo->arch == RADEON_M7) newmode.ppll_div_3 = 0x000600ad; #endif /* CONFIG_PPC_OF */ RTRACE("post div = 0x%x\n", rinfo->post_div); RTRACE("fb_div = 0x%x\n", rinfo->fb_div); RTRACE("ppll_div_3 = 0x%x\n", newmode.ppll_div_3); /* DDA */ vclk_freq = round_div(rinfo->pll.ref_clk * rinfo->fb_div, rinfo->pll.ref_div * rinfo->post_div); xclk_freq = rinfo->pll.xclk; xclk_per_trans = round_div(xclk_freq * 128, vclk_freq * mode->bits_per_pixel); min_bits = min_bits_req(xclk_per_trans); useable_precision = min_bits + 1; <API key> = round_div((xclk_freq * 128) << (11 - useable_precision), vclk_freq * mode->bits_per_pixel); ron = (4 * rinfo->ram.mb + 3 * _max(rinfo->ram.trcd - 2, 0) + 2 * rinfo->ram.trp + rinfo->ram.twr + rinfo->ram.cl + rinfo->ram.tr2w + xclk_per_trans) << (11 - useable_precision); roff = <API key> * (32 - 4); RTRACE("ron = %d, roff = %d\n", ron, roff); RTRACE("vclk_freq = %d, per = %d\n", vclk_freq, <API key>); if ((ron + rinfo->ram.rloop) >= roff) { printk("radeonfb: error ron out of range\n"); return -EINVAL; } newmode.dda_config = (<API key> | (useable_precision << 16) | (rinfo->ram.rloop << 20)); newmode.dda_on_off = (ron << 16) | roff; if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) { unsigned int hRatio, vRatio; /* We force the pixel clock to be always enabled. Allowing it * to be power managed during blanking would save power, but has * nasty interactions with the 2D engine & sleep code that haven't * been solved yet. --BenH */ newmode.vclk_ecp_cntl &= ~<API key>; if (mode->xres > rinfo->panel_xres) mode->xres = rinfo->panel_xres; if (mode->yres > rinfo->panel_yres) mode->yres = rinfo->panel_yres; newmode.fp_horz_stretch = (((rinfo->panel_xres / 8) - 1) << HORZ_PANEL_SHIFT); newmode.fp_vert_stretch = ((rinfo->panel_yres - 1) << VERT_PANEL_SHIFT); if (mode->xres != rinfo->panel_xres) { hRatio = round_div(mode->xres * <API key>, rinfo->panel_xres); newmode.fp_horz_stretch = (((((unsigned long)hRatio) & <API key>)) | (newmode.fp_horz_stretch & (HORZ_PANEL_SIZE | <API key> | HORZ_AUTO_RATIO_INC))); newmode.fp_horz_stretch |= (HORZ_STRETCH_BLEND | HORZ_STRETCH_ENABLE); } newmode.fp_horz_stretch &= ~HORZ_AUTO_RATIO; if (mode->yres != rinfo->panel_yres) { vRatio = round_div(mode->yres * <API key>, rinfo->panel_yres); newmode.fp_vert_stretch = (((((unsigned long)vRatio) & <API key>)) | (newmode.fp_vert_stretch & (VERT_PANEL_SIZE | <API key>))); newmode.fp_vert_stretch |= (VERT_STRETCH_BLEND | VERT_STRETCH_ENABLE); } newmode.fp_vert_stretch &= ~VERT_AUTO_RATIO_EN; newmode.fp_gen_cntl = (rinfo->init_state.fp_gen_cntl & (u32) ~(FP_SEL_CRTC2 | <API key> | FP_DFP_SYNC_SEL | FP_CRT_SYNC_SEL | FP_CRTC_LOCK_8DOT | FP_USE_SHADOW_EN | <API key> | FP_CRT_SYNC_ALT)); newmode.fp_gen_cntl |= (<API key> | <API key>); newmode.lvds_gen_cntl = rinfo->init_state.lvds_gen_cntl; newmode.lvds_pll_cntl = rinfo->init_state.lvds_pll_cntl; newmode.tmds_crc = rinfo->init_state.tmds_crc; newmode.<API key> = rinfo->init_state.<API key>; if (primary_mon == MT_LCD) { newmode.lvds_gen_cntl |= (LVDS_ON | LVDS_BLON); newmode.fp_gen_cntl &= ~(FP_FPON | FP_TMDS_EN); } else { /* DFP */ newmode.fp_gen_cntl |= (FP_FPON | FP_TMDS_EN); newmode.<API key> = (TMDS_RAN_PAT_RST | TMDS_ICHCSEL | TMDS_PLL_EN) & ~(TMDS_PLLRST); newmode.crtc_ext_cntl &= ~CRTC_CRT_ON; } newmode.<API key> = (((rinfo->hblank / 8) & 0x3ff) | (((mode->xres / 8) - 1) << 16)); newmode.<API key> = (rinfo->vblank & 0xffff) | ((mode->yres - 1) << 16); newmode.fp_h_sync_strt_wid = ((rinfo->hOver_plus & 0x1fff) | (hsync_wid << 16) | (h_sync_pol << 23)); newmode.fp_v_sync_strt_wid = ((rinfo->vOver_plus & 0xfff) | (vsync_wid << 16) | (v_sync_pol << 23)); } /* do it! */ if (!rinfo->asleep) { radeon_write_mode (rinfo, &newmode); /* (re)initialize the engine */ if (noaccel) radeon_engine_init (rinfo); } /* Update fix */ if (accel) info->fix.line_length = rinfo->pitch*64; else info->fix.line_length = mode->xres_virtual * ((mode->bits_per_pixel + 1) / 8); info->fix.visual = rinfo->depth == 8 ? <API key> : <API key>; #ifdef CONFIG_BOOTX_TEXT /* Update debug text engine */ <API key>(rinfo->fb_base_phys, mode->xres, mode->yres, rinfo->depth, info->fix.line_length); #endif return 0; } static void radeon_write_mode (struct radeonfb_info *rinfo, struct radeon_regs *mode) { int i; int primary_mon = PRIMARY_MONITOR(rinfo); radeonfb_blank(VESA_POWERDOWN, (struct fb_info *)rinfo); if (rinfo->arch == RADEON_M6) { for (i=0; i<8; i++) OUTREG(common_regs_m6[i].reg, common_regs_m6[i].val); } else { for (i=0; i<9; i++) OUTREG(common_regs[i].reg, common_regs[i].val); } OUTREG(CRTC_GEN_CNTL, mode->crtc_gen_cntl); OUTREGP(CRTC_EXT_CNTL, mode->crtc_ext_cntl, CRTC_HSYNC_DIS | CRTC_VSYNC_DIS | CRTC_DISPLAY_DIS); OUTREGP(DAC_CNTL, mode->dac_cntl, DAC_RANGE_CNTL | DAC_BLANKING); OUTREG(CRTC_H_TOTAL_DISP, mode->crtc_h_total_disp); OUTREG(<API key>, mode-><API key>); OUTREG(CRTC_V_TOTAL_DISP, mode->crtc_v_total_disp); OUTREG(<API key>, mode-><API key>); OUTREG(CRTC_OFFSET, 0); OUTREG(CRTC_OFFSET_CNTL, 0); OUTREG(CRTC_PITCH, mode->crtc_pitch); #if defined(__BIG_ENDIAN) OUTREG(SURFACE_CNTL, mode->surface_cntl); #endif while ((INREG(CLOCK_CNTL_INDEX) & PPLL_DIV_SEL_MASK) != PPLL_DIV_SEL_MASK) { OUTREGP(CLOCK_CNTL_INDEX, PPLL_DIV_SEL_MASK, 0xffff); } OUTPLLP(PPLL_CNTL, PPLL_RESET, 0xffff); while ((INPLL(PPLL_REF_DIV) & PPLL_REF_DIV_MASK) != (mode->ppll_ref_div & PPLL_REF_DIV_MASK)) { OUTPLLP(PPLL_REF_DIV, mode->ppll_ref_div, ~PPLL_REF_DIV_MASK); } while ((INPLL(PPLL_DIV_3) & PPLL_FB3_DIV_MASK) != (mode->ppll_div_3 & PPLL_FB3_DIV_MASK)) { OUTPLLP(PPLL_DIV_3, mode->ppll_div_3, ~PPLL_FB3_DIV_MASK); } while ((INPLL(PPLL_DIV_3) & PPLL_POST3_DIV_MASK) != (mode->ppll_div_3 & PPLL_POST3_DIV_MASK)) { OUTPLLP(PPLL_DIV_3, mode->ppll_div_3, ~PPLL_POST3_DIV_MASK); } OUTPLL(HTOTAL_CNTL, 0); OUTPLLP(PPLL_CNTL, 0, ~PPLL_RESET); // OUTREG(DDA_CONFIG, mode->dda_config); // OUTREG(DDA_ON_OFF, mode->dda_on_off); if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) { OUTREG(<API key>, mode-><API key>); OUTREG(<API key>, mode-><API key>); OUTREG(FP_H_SYNC_STRT_WID, mode->fp_h_sync_strt_wid); OUTREG(FP_V_SYNC_STRT_WID, mode->fp_v_sync_strt_wid); OUTREG(FP_HORZ_STRETCH, mode->fp_horz_stretch); OUTREG(FP_VERT_STRETCH, mode->fp_vert_stretch); OUTREG(FP_GEN_CNTL, mode->fp_gen_cntl); OUTREG(TMDS_CRC, mode->tmds_crc); OUTREG(<API key>, mode-><API key>); if (primary_mon == MT_LCD) { unsigned int tmp = INREG(LVDS_GEN_CNTL); mode->lvds_gen_cntl &= ~LVDS_STATE_MASK; mode->lvds_gen_cntl |= (rinfo->init_state.lvds_gen_cntl & LVDS_STATE_MASK); if ((tmp & (LVDS_ON | LVDS_BLON)) == (mode->lvds_gen_cntl & (LVDS_ON | LVDS_BLON))) { OUTREG(LVDS_GEN_CNTL, mode->lvds_gen_cntl); } else { if (mode->lvds_gen_cntl & (LVDS_ON | LVDS_BLON)) { udelay(1000); OUTREG(LVDS_GEN_CNTL, mode->lvds_gen_cntl); } else { OUTREG(LVDS_GEN_CNTL, mode->lvds_gen_cntl | LVDS_BLON); udelay(1000); OUTREG(LVDS_GEN_CNTL, mode->lvds_gen_cntl); } } } } radeonfb_blank(VESA_NO_BLANKING, (struct fb_info *)rinfo); OUTPLL(VCLK_ECP_CNTL, mode->vclk_ecp_cntl); return; } static struct fb_ops radeonfb_ops = { .owner = THIS_MODULE, .fb_check_var = radeonfb_check_var, .fb_set_par = radeonfb_set_par, .fb_setcolreg = radeonfb_setcolreg, .fb_pan_display = <API key>, .fb_blank = radeonfb_blank, .fb_ioctl = radeonfb_ioctl, #if 0 .fb_fillrect = radeonfb_fillrect, .fb_copyarea = radeonfb_copyarea, .fb_imageblit = radeonfb_imageblit, .fb_rasterimg = radeonfb_rasterimg, #else .fb_fillrect = cfb_fillrect, .fb_copyarea = cfb_copyarea, .fb_imageblit = cfb_imageblit, #endif .fb_cursor = soft_cursor, }; static int __devinit radeon_set_fbinfo (struct radeonfb_info *rinfo) { struct fb_info *info; info = &rinfo->info; info->par = rinfo; info->pseudo_palette = rinfo->pseudo_palette; info->flags = FBINFO_DEFAULT | FBINFO_HWACCEL_YPAN; info->fbops = &radeonfb_ops; info->screen_base = rinfo->fb_base; /* Fill fix common fields */ strlcpy(info->fix.id, rinfo->name, sizeof(info->fix.id)); info->fix.smem_start = rinfo->fb_base_phys; info->fix.smem_len = rinfo->video_ram; info->fix.type = <API key>; info->fix.visual = <API key>; info->fix.xpanstep = 8; info->fix.ypanstep = 1; info->fix.ywrapstep = 0; info->fix.type_aux = 0; info->fix.mmio_start = rinfo->mmio_base_phys; info->fix.mmio_len = RADEON_REGSIZE; if (noaccel) info->fix.accel = FB_ACCEL_NONE; else info->fix.accel = FB_ACCEL_ATI_RADEON; if (radeon_init_disp (rinfo) < 0) return -1; return 0; } #ifdef <API key> /* TODO: Dbl check these tables, we don't go up to full ON backlight * in these, possibly because we noticed MacOS doesn't, but I'd prefer * having some more official numbers from ATI */ static int backlight_conv_m6[] = { 0xff, 0xc0, 0xb5, 0xaa, 0x9f, 0x94, 0x89, 0x7e, 0x73, 0x68, 0x5d, 0x52, 0x47, 0x3c, 0x31, 0x24 }; static int backlight_conv_m7[] = { 0x00, 0x3f, 0x4a, 0x55, 0x60, 0x6b, 0x76, 0x81, 0x8c, 0x97, 0xa2, 0xad, 0xb8, 0xc3, 0xce, 0xd9 }; #define BACKLIGHT_LVDS_OFF #undef BACKLIGHT_DAC_OFF /* We turn off the LCD completely instead of just dimming the backlight. * This provides some greater power saving and the display is useless * without backlight anyway. */ static int <API key>(int on, int level, void *data) { struct radeonfb_info *rinfo = (struct radeonfb_info *)data; unsigned int lvds_gen_cntl = INREG(LVDS_GEN_CNTL); int* conv_table; /* Pardon me for that hack... maybe some day we can figure * out in what direction backlight should work on a given * panel ? */ if ((rinfo->arch == RADEON_M7 || rinfo->arch == RADEON_M9) && !<API key>("PowerBook4,3")) conv_table = backlight_conv_m7; else conv_table = backlight_conv_m6; lvds_gen_cntl |= (LVDS_BL_MOD_EN | LVDS_BLON); if (on && (level > BACKLIGHT_OFF)) { lvds_gen_cntl |= LVDS_DIGON; if (!(lvds_gen_cntl & LVDS_ON)) { lvds_gen_cntl &= ~LVDS_BLON; OUTREG(LVDS_GEN_CNTL, lvds_gen_cntl); (void)INREG(LVDS_GEN_CNTL); mdelay(10); lvds_gen_cntl |= LVDS_BLON; OUTREG(LVDS_GEN_CNTL, lvds_gen_cntl); } lvds_gen_cntl &= ~<API key>; lvds_gen_cntl |= (conv_table[level] << <API key>); lvds_gen_cntl |= (LVDS_ON | LVDS_EN); lvds_gen_cntl &= ~LVDS_DISPLAY_DIS; } else { lvds_gen_cntl &= ~<API key>; lvds_gen_cntl |= (conv_table[0] << <API key>); lvds_gen_cntl |= LVDS_DISPLAY_DIS; OUTREG(LVDS_GEN_CNTL, lvds_gen_cntl); udelay(10); lvds_gen_cntl &= ~(LVDS_ON | LVDS_EN | LVDS_BLON | LVDS_DIGON); } OUTREG(LVDS_GEN_CNTL, lvds_gen_cntl); rinfo->init_state.lvds_gen_cntl &= ~LVDS_STATE_MASK; rinfo->init_state.lvds_gen_cntl |= (lvds_gen_cntl & LVDS_STATE_MASK); return 0; } static int <API key>(int level, void *data) { return <API key>(1, level, data); } #endif /* <API key> */ #ifdef CONFIG_PMAC_PBOOK static u32 dbg_clk; /* * Radeon M6 Power Management code. This code currently only supports * the mobile chips, it's based from some informations provided by ATI * along with hours of tracing of MacOS drivers */ static void radeon_pm_save_regs(struct radeonfb_info *rinfo) { rinfo->save_regs[0] = INPLL(PLL_PWRMGT_CNTL); rinfo->save_regs[1] = INPLL(CLK_PWRMGT_CNTL); rinfo->save_regs[2] = INPLL(MCLK_CNTL); rinfo->save_regs[3] = INPLL(SCLK_CNTL); rinfo->save_regs[4] = INPLL(CLK_PIN_CNTL); rinfo->save_regs[5] = INPLL(VCLK_ECP_CNTL); rinfo->save_regs[6] = INPLL(PIXCLKS_CNTL); rinfo->save_regs[7] = INPLL(MCLK_MISC); rinfo->save_regs[8] = INPLL(P2PLL_CNTL); rinfo->save_regs[9] = INREG(DISP_MISC_CNTL); rinfo->save_regs[10] = INREG(DISP_PWR_MAN); rinfo->save_regs[11] = INREG(LVDS_GEN_CNTL); rinfo->save_regs[12] = INREG(LVDS_PLL_CNTL); rinfo->save_regs[13] = INREG(TV_DAC_CNTL); rinfo->save_regs[14] = INREG(BUS_CNTL1); rinfo->save_regs[15] = INREG(CRTC_OFFSET_CNTL); rinfo->save_regs[16] = INREG(AGP_CNTL); rinfo->save_regs[17] = (INREG(CRTC_GEN_CNTL) & 0xfdffffff) | 0x04000000; rinfo->save_regs[18] = (INREG(CRTC2_GEN_CNTL) & 0xfdffffff) | 0x04000000; rinfo->save_regs[19] = INREG(GPIOPAD_A); rinfo->save_regs[20] = INREG(GPIOPAD_EN); rinfo->save_regs[21] = INREG(GPIOPAD_MASK); rinfo->save_regs[22] = INREG(ZV_LCDPAD_A); rinfo->save_regs[23] = INREG(ZV_LCDPAD_EN); rinfo->save_regs[24] = INREG(ZV_LCDPAD_MASK); rinfo->save_regs[25] = INREG(GPIO_VGA_DDC); rinfo->save_regs[26] = INREG(GPIO_DVI_DDC); rinfo->save_regs[27] = INREG(GPIO_MONID); rinfo->save_regs[28] = INREG(GPIO_CRT2_DDC); rinfo->save_regs[29] = INREG(SURFACE_CNTL); rinfo->save_regs[30] = INREG(MC_FB_LOCATION); rinfo->save_regs[31] = INREG(DISPLAY_BASE_ADDR); rinfo->save_regs[32] = INREG(MC_AGP_LOCATION); rinfo->save_regs[33] = INREG(<API key>); } static void <API key>(struct radeonfb_info *rinfo) { OUTPLL(P2PLL_CNTL, rinfo->save_regs[8] & 0xFFFFFFFE); /* First */ OUTPLL(PLL_PWRMGT_CNTL, rinfo->save_regs[0]); OUTPLL(CLK_PWRMGT_CNTL, rinfo->save_regs[1]); OUTPLL(MCLK_CNTL, rinfo->save_regs[2]); OUTPLL(SCLK_CNTL, rinfo->save_regs[3]); OUTPLL(CLK_PIN_CNTL, rinfo->save_regs[4]); OUTPLL(VCLK_ECP_CNTL, rinfo->save_regs[5]); OUTPLL(PIXCLKS_CNTL, rinfo->save_regs[6]); OUTPLL(MCLK_MISC, rinfo->save_regs[7]); OUTREG(DISP_MISC_CNTL, rinfo->save_regs[9]); OUTREG(DISP_PWR_MAN, rinfo->save_regs[10]); OUTREG(LVDS_GEN_CNTL, rinfo->save_regs[11]); OUTREG(LVDS_PLL_CNTL,rinfo->save_regs[12]); OUTREG(TV_DAC_CNTL, rinfo->save_regs[13]); OUTREG(BUS_CNTL1, rinfo->save_regs[14]); OUTREG(CRTC_OFFSET_CNTL, rinfo->save_regs[15]); OUTREG(AGP_CNTL, rinfo->save_regs[16]); OUTREG(CRTC_GEN_CNTL, rinfo->save_regs[17]); OUTREG(CRTC2_GEN_CNTL, rinfo->save_regs[18]); // wait VBL before that one ? OUTPLL(P2PLL_CNTL, rinfo->save_regs[8]); OUTREG(GPIOPAD_A, rinfo->save_regs[19]); OUTREG(GPIOPAD_EN, rinfo->save_regs[20]); OUTREG(GPIOPAD_MASK, rinfo->save_regs[21]); OUTREG(ZV_LCDPAD_A, rinfo->save_regs[22]); OUTREG(ZV_LCDPAD_EN, rinfo->save_regs[23]); OUTREG(ZV_LCDPAD_MASK, rinfo->save_regs[24]); OUTREG(GPIO_VGA_DDC, rinfo->save_regs[25]); OUTREG(GPIO_DVI_DDC, rinfo->save_regs[26]); OUTREG(GPIO_MONID, rinfo->save_regs[27]); OUTREG(GPIO_CRT2_DDC, rinfo->save_regs[28]); } static void <API key>(struct radeonfb_info *rinfo) { OUTREG(GPIOPAD_MASK, 0x0001ffff); OUTREG(GPIOPAD_EN, 0x00000400); OUTREG(GPIOPAD_A, 0x00000000); OUTREG(ZV_LCDPAD_MASK, 0x00000000); OUTREG(ZV_LCDPAD_EN, 0x00000000); OUTREG(ZV_LCDPAD_A, 0x00000000); OUTREG(GPIO_VGA_DDC, 0x00030000); OUTREG(GPIO_DVI_DDC, 0x00000000); OUTREG(GPIO_MONID, 0x00030000); OUTREG(GPIO_CRT2_DDC, 0x00000000); } static void <API key>(struct radeonfb_info *rinfo) { // u32 reg; // OUTPLL(P2PLL_REF_DIV, 0x0c); // .../... figure out what macos does here } static void <API key>(struct radeonfb_info *rinfo) { u32 reg; reg = INREG(BUS_CNTL1); reg &= ~<API key>; reg |= <API key> | (1<<<API key>); OUTREG(BUS_CNTL1, reg); reg = INPLL(PLL_PWRMGT_CNTL); reg |= <API key> | <API key> | <API key> | <API key>; reg &= ~<API key>; reg &= ~<API key>; OUTPLL(PLL_PWRMGT_CNTL, reg); // reg = INPLL(TV_PLL_CNTL1); // reg |= <API key> | <API key>; // OUTPLL(TV_PLL_CNTL1, reg); reg = INREG(TV_DAC_CNTL); reg &= ~(<API key> |<API key>); reg |=TV_DAC_CNTL_BGSLEEP | TV_DAC_CNTL_RDACPD | TV_DAC_CNTL_GDACPD | TV_DAC_CNTL_BDACPD | (8<<<API key>) | (8<<<API key>); OUTREG(TV_DAC_CNTL, reg); reg = INREG(<API key>); reg &= ~(TMDS_PLL_EN |TMDS_PLLRST); OUTREG(<API key>, reg); // lvds_pll_cntl = regr32(g, LVDS_PLL_CNTL); // lvds_pll_cntl &= ~<API key>; // lvds_pll_cntl |= <API key>; // regw32(g, LVDS_PLL_CNTL, lvds_pll_cntl); reg = INREG(DAC_CNTL); reg &= ~DAC_CMP_EN; OUTREG(DAC_CNTL, reg); reg = INREG(DAC_CNTL2); reg &= ~DAC2_CMP_EN; OUTREG(DAC_CNTL2, reg); reg = INREG(TV_DAC_CNTL); reg &= ~TV_DAC_CNTL_DETECT; OUTREG(TV_DAC_CNTL, reg); } static void <API key>(struct radeonfb_info *rinfo) { /* This code is disabled. It does what is in the pm_init * function of the MacOS driver code ATI sent me. However, * it doesn't fix my sleep problem, and is causing other issues * on wakeup (bascially the machine dying when switching consoles * I haven't had time to investigate this yet */ #if 0 u32 disp_misc_cntl; u32 disp_pwr_man; u32 temp; // set SPLL, MPLL, PPLL, P2PLL, TVPLL, SCLK, MCLK, PCLK, P2CLK, // TCLK and TEST_MODE to 0 temp = INPLL(CLK_PWRMGT_CNTL); OUTPLL(CLK_PWRMGT_CNTL , temp & ~0xc00002ff); // Turn on Power Management temp = INPLL(CLK_PWRMGT_CNTL); OUTPLL(CLK_PWRMGT_CNTL , temp | 0x00000400); // Turn off display clock if using mobile chips temp = INPLL(CLK_PWRMGT_CNTL); OUTREG(CLK_PWRMGT_CNTL , temp | 0x00100000); // Force PIXCLK_ALWAYS_ON and <API key> temp = INPLL(VCLK_ECP_CNTL); OUTPLL(VCLK_ECP_CNTL, temp & ~0x000000c0); // Force ECP_FORCE_ON to 1 temp = INPLL(VCLK_ECP_CNTL); OUTPLL(VCLK_ECP_CNTL, temp | 0x00040000); // Force <API key> and PIXCLK_GV_ALWAYS_ON temp = INPLL(PIXCLKS_CNTL); OUTPLL(PIXCLKS_CNTL, temp & ~0x00001800); // Forcing SCLK_CNTL to ON OUTPLL(SCLK_CNTL, (INPLL(SCLK_CNTL)& 0x00000007) | 0xffff8000 ); // Set PM control over XTALIN pad temp = INPLL(CLK_PIN_CNTL); OUTPLL(CLK_PIN_CNTL, temp | 0x00080000); // Force MCLK and YCLK and MC as dynamic temp = INPLL(MCLK_CNTL); OUTPLL(MCLK_CNTL, temp & 0xffeaffff); // PLL_TURNOFF temp = INPLL(PLL_PWRMGT_CNTL); OUTPLL(PLL_PWRMGT_CNTL, temp | 0x0000001f); // set MOBILE_SU to 1 if M6 or DDR64 is detected temp = INPLL(PLL_PWRMGT_CNTL); OUTPLL(PLL_PWRMGT_CNTL, temp | 0x00010000); // select PM access mode (PM_MODE_SEL) (use ACPI mode) // temp = INPLL(PLL_PWRMGT_CNTL); // OUTPLL(PLL_PWRMGT_CNTL, temp | 0x00002000); temp = INPLL(PLL_PWRMGT_CNTL); OUTPLL(PLL_PWRMGT_CNTL, temp & ~0x00002000); // set DISP_MISC_CNTL register disp_misc_cntl = INREG(DISP_MISC_CNTL); disp_misc_cntl &= ~( <API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key>); OUTREG(DISP_MISC_CNTL, disp_misc_cntl); // set DISP_PWR_MAN register disp_pwr_man = INREG(DISP_PWR_MAN); // clau - 9.29.2000 - changes made to bit23:18 to set to 1 as requested by George disp_pwr_man |= (<API key> | <API key> | // <API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key>); disp_pwr_man &= ~(<API key> | <API key>| <API key> | <API key>); OUTREG(DISP_PWR_MAN, disp_pwr_man); // clau - 10.24.2000 // - add in setting for BUS_CNTL1 b27:26 = 0x01 and b31 = 0x1 // - add in setting for AGP_CNTL b7:0 = 0x20 // - add in setting for DVI_DDC_DATA_OUT_EN b17:16 = 0x0 // the following settings (two lines) are applied at a later part of this function, only on mobile platform // requres -mobile flag OUTREG(BUS_CNTL1, (INREG(BUS_CNTL1) & 0xf3ffffff) | 0x04000000); OUTREG(BUS_CNTL1, INREG(BUS_CNTL1) | 0x80000000); OUTREG(AGP_CNTL, (INREG(AGP_CNTL) & 0xffffff00) | 0x20); OUTREG(GPIO_DVI_DDC, INREG(GPIO_DVI_DDC) & 0xfffcffff); // yulee - 12.12.2000 // A12 only // <API key>@MCLK_MISC = 1 // <API key>@CLK_PIN_CNTL = 0 // only on mobile platform OUTPLL(MCLK_MISC, INPLL(MCLK_MISC) | 0x00040000 ); // yulee -12.12.2000 // AGPCLK_VALID@BUS_CNTL1 = 1 // MOBILE_PLATFORM_SEL@BUS_CNTL1 = 01 // <API key>@CRTC_OFFSET_CNTL = 0 // CG_CLK_TO_OUTPIN@CLK_PIN_CNTL = 0 // only on mobile platform OUTPLL(CLK_PIN_CNTL, INPLL(CLK_PIN_CNTL ) & 0xFFFFF7FF ); OUTREG(BUS_CNTL1, (INREG(BUS_CNTL1 ) & 0xF3FFFFFF) | 0x84000000 ); OUTREG(CRTC_OFFSET_CNTL, INREG(CRTC_OFFSET_CNTL ) & 0xFFEFFFFF ); mdelay(100); #endif /* Disable CRTCs */ OUTREG(CRTC_GEN_CNTL, (INREG(CRTC_GEN_CNTL) & ~CRTC_EN) | CRTC_DISP_REQ_EN_B); OUTREG(CRTC2_GEN_CNTL, (INREG(CRTC2_GEN_CNTL) & ~CRTC2_EN) | CRTC2_DISP_REQ_EN_B); (void)INREG(CRTC2_GEN_CNTL); mdelay(17); } static void radeon_set_suspend(struct radeonfb_info *rinfo, int suspend) { u16 pwr_cmd; if (!rinfo->pm_reg) return; /* Set the chip into appropriate suspend mode (we use D2, * D3 would require a compete re-initialization of the chip, * including PCI config registers, clocks, AGP conf, ...) */ if (suspend) { /* According to ATI, we should program V2CLK here, I have * to verify what's up exactly */ /* Save some registers */ radeon_pm_save_regs(rinfo); /* Check that on M7 too, might work might not. M7 may also * need explicit enabling of PM */ if (rinfo->arch == RADEON_M6) { /* Program V2CLK */ <API key>(rinfo); /* Disable IO PADs */ <API key>(rinfo); /* Set low current */ <API key>(rinfo); /* Prepare chip for power management */ <API key>(rinfo); /* Reset the MDLL */ OUTPLL(MDLL_CKO, INPLL(MDLL_CKO) | MCKOA_RESET); (void)INPLL(MDLL_RDCKA); OUTPLL(MDLL_CKO, INPLL(MDLL_CKO) & ~MCKOA_RESET); (void)INPLL(MDLL_RDCKA); } /* Switch PCI power managment to D2. */ for (;;) { <API key>( rinfo->pdev, rinfo->pm_reg+PCI_PM_CTRL, &pwr_cmd); if (pwr_cmd & 2) break; <API key>( rinfo->pdev, rinfo->pm_reg+PCI_PM_CTRL, (pwr_cmd & ~<API key>) | 2); mdelay(500); } } else { /* Switch back PCI powermanagment to D0 */ mdelay(200); <API key>(rinfo->pdev, rinfo->pm_reg+PCI_PM_CTRL, 0); mdelay(500); dbg_clk = INPLL(1); /* Do we need that on M7 ? */ if (rinfo->arch == RADEON_M6) { /* Restore the MDLL */ OUTPLL(MDLL_CKO, INPLL(MDLL_CKO) & ~MCKOA_RESET); (void)INPLL(MDLL_CKO); } /* Restore some registers */ <API key>(rinfo); } } /* * Save the contents of the framebuffer when we go to sleep, * and restore it when we wake up again. */ int radeon_sleep_notify(struct pmu_sleep_notifier *self, int when) { struct radeonfb_info *rinfo; for (rinfo = board_list; rinfo != NULL; rinfo = rinfo->next) { struct fb_fix_screeninfo fix; int nb; struct display *disp; disp = (rinfo->currcon < 0) ? rinfo->info.disp : &fb_display[rinfo->currcon]; switch (rinfo->arch) { case RADEON_M6: case RADEON_M7: case RADEON_M9: break; default: return PBOOK_SLEEP_REFUSE; } radeonfb_get_fix(&fix, fg_console, (struct fb_info *)rinfo); nb = fb_display[fg_console].var.yres * fix.line_length; switch (when) { case PBOOK_SLEEP_NOW: acquire_console_sem(); disp->dispsw = &fbcon_dummy; if (!noaccel) { /* Make sure engine is reset */ radeon_engine_reset(); radeon_engine_idle(); } /* Blank display and LCD */ radeonfb_blank(VESA_POWERDOWN+1, (struct fb_info *)rinfo); /* Sleep */ rinfo->asleep = 1; radeon_set_suspend(rinfo, 1); release_console_sem(); break; case PBOOK_WAKE: acquire_console_sem(); /* Wakeup */ radeon_set_suspend(rinfo, 0); if (!noaccel) radeon_engine_init(rinfo); rinfo->asleep = 0; radeon_set_dispsw(rinfo, disp); <API key>(rinfo, &disp->var); do_install_cmap(rinfo->currcon < 0 ? 0 : rinfo->currcon, (struct fb_info *)rinfo); radeonfb_blank(0, (struct fb_info *)rinfo); release_console_sem(); printk("CLK_PIN_CNTL on wakeup was: %08x\n", dbg_clk); break; } } return PBOOK_SLEEP_OK; } #endif /* CONFIG_PMAC_PBOOK */ static int <API key> (struct pci_dev *pdev, const struct pci_device_id *ent) { struct radeonfb_info *rinfo; struct radeon_chip_info *rci = &radeon_chip_info[ent->driver_data]; u32 tmp; RTRACE("<API key> BEGIN\n"); /* Enable device in PCI config */ if (pci_enable_device(pdev) != 0) { printk(KERN_ERR "radeonfb: Cannot enable PCI device\n"); return -ENODEV; } rinfo = kmalloc (sizeof (struct radeonfb_info), GFP_KERNEL); if (!rinfo) { printk ("radeonfb: could not allocate memory\n"); return -ENODEV; } memset (rinfo, 0, sizeof (struct radeonfb_info)); //info = &rinfo->info; rinfo->pdev = pdev; strcpy(rinfo->name, rci->name); rinfo->arch = rci->arch; /* Set base addrs */ rinfo->fb_base_phys = pci_resource_start (pdev, 0); rinfo->mmio_base_phys = pci_resource_start (pdev, 2); /* request the mem regions */ if (!request_mem_region (rinfo->fb_base_phys, pci_resource_len(pdev, 0), "radeonfb")) { printk ("radeonfb: cannot reserve FB region\n"); kfree (rinfo); return -ENODEV; } if (!request_mem_region (rinfo->mmio_base_phys, pci_resource_len(pdev, 2), "radeonfb")) { printk ("radeonfb: cannot reserve MMIO region\n"); release_mem_region (rinfo->fb_base_phys, pci_resource_len(pdev, 0)); kfree (rinfo); return -ENODEV; } /* map the regions */ rinfo->mmio_base = ioremap (rinfo->mmio_base_phys, RADEON_REGSIZE); if (!rinfo->mmio_base) { printk ("radeonfb: cannot map MMIO\n"); release_mem_region (rinfo->mmio_base_phys, pci_resource_len(pdev, 2)); release_mem_region (rinfo->fb_base_phys, pci_resource_len(pdev, 0)); kfree (rinfo); return -ENODEV; } rinfo->chipset = pdev->device; switch (rinfo->arch) { case RADEON_R100: rinfo->hasCRTC2 = 0; break; default: /* all the rest have it */ rinfo->hasCRTC2 = 1; break; } #if 0 if (rinfo->arch == RADEON_M7) { /* * Noticed some errors in accel with M7, will have to work these out... */ noaccel = 1; } #endif if (mirror) printk("radeonfb: mirroring display to CRT\n"); /* framebuffer size */ tmp = INREG(CONFIG_MEMSIZE); /* mem size is bits [28:0], mask off the rest */ rinfo->video_ram = tmp & CONFIG_MEMSIZE_MASK; /* ram type */ tmp = INREG(MEM_SDRAM_MODE_REG); switch ((MEM_CFG_TYPE & tmp) >> 30) { case 0: /* SDR SGRAM (2:1) */ strcpy(rinfo->ram_type, "SDR SGRAM"); rinfo->ram.ml = 4; rinfo->ram.mb = 4; rinfo->ram.trcd = 1; rinfo->ram.trp = 2; rinfo->ram.twr = 1; rinfo->ram.cl = 2; rinfo->ram.loop_latency = 16; rinfo->ram.rloop = 16; break; case 1: /* DDR SGRAM */ strcpy(rinfo->ram_type, "DDR SGRAM"); rinfo->ram.ml = 4; rinfo->ram.mb = 4; rinfo->ram.trcd = 3; rinfo->ram.trp = 3; rinfo->ram.twr = 2; rinfo->ram.cl = 3; rinfo->ram.tr2w = 1; rinfo->ram.loop_latency = 16; rinfo->ram.rloop = 16; break; default: /* 64-bit SDR SGRAM */ strcpy(rinfo->ram_type, "SDR SGRAM 64"); rinfo->ram.ml = 4; rinfo->ram.mb = 8; rinfo->ram.trcd = 3; rinfo->ram.trp = 3; rinfo->ram.twr = 1; rinfo->ram.cl = 3; rinfo->ram.tr2w = 1; rinfo->ram.loop_latency = 17; rinfo->ram.rloop = 17; break; } rinfo->bios_seg = radeon_find_rom(rinfo); radeon_get_pllinfo(rinfo, rinfo->bios_seg); /* * Hack to get around some busted production M6's * reporting no ram */ if (rinfo->video_ram == 0) { switch (pdev->device) { case <API key>: case <API key>: rinfo->video_ram = 8192 * 1024; break; default: break; } } RTRACE("radeonfb: probed %s %dk videoram\n", (rinfo->ram_type), (rinfo->video_ram/1024)); #if !defined(__powerpc__) radeon_get_moninfo(rinfo); #else switch (pdev->device) { case <API key>: case <API key>: case <API key>: case <API key>: rinfo->dviDisp_type = MT_LCD; break; default: radeon_get_moninfo(rinfo); break; } #endif radeon_get_EDID(rinfo); if ((rinfo->dviDisp_type == MT_DFP) || (rinfo->dviDisp_type == MT_LCD) || (rinfo->crtDisp_type == MT_DFP)) { if (!radeon_get_dfpinfo(rinfo)) { iounmap(rinfo->mmio_base); release_mem_region (rinfo->mmio_base_phys, pci_resource_len(pdev, 2)); release_mem_region (rinfo->fb_base_phys, pci_resource_len(pdev, 0)); kfree (rinfo); return -ENODEV; } } rinfo->fb_base = ioremap (rinfo->fb_base_phys, rinfo->video_ram); if (!rinfo->fb_base) { printk ("radeonfb: cannot map FB\n"); iounmap(rinfo->mmio_base); release_mem_region (rinfo->mmio_base_phys, pci_resource_len(pdev, 2)); release_mem_region (rinfo->fb_base_phys, pci_resource_len(pdev, 0)); kfree (rinfo); return -ENODEV; } /* I SHOULD FIX THAT CRAP ! I should probably mimmic XFree DRI * driver setup here. * * On PPC, OF based cards setup the internal memory * mapping in strange ways. We change it so that the * framebuffer is mapped at 0 and given half of the card's * address space (2Gb). AGP is mapped high (0xe0000000) and * can use up to 512Mb. Once DRI is fully implemented, we * will have to setup the PCI remapper to remap the agp_special_page * memory page somewhere between those regions so that the card * use a normal PCI bus master cycle to access the ring read ptr. * --BenH. */ #ifdef CONFIG_ALL_PPC if (rinfo->hasCRTC2) OUTREG(CRTC2_GEN_CNTL, (INREG(CRTC2_GEN_CNTL) & ~CRTC2_EN) | CRTC2_DISP_REQ_EN_B); OUTREG(CRTC_EXT_CNTL, INREG(CRTC_EXT_CNTL) | CRTC_DISPLAY_DIS); OUTREG(MC_FB_LOCATION, 0x7fff0000); OUTREG(MC_AGP_LOCATION, 0xffffe000); OUTREG(DISPLAY_BASE_ADDR, 0x00000000); if (rinfo->hasCRTC2) OUTREG(<API key>, 0x00000000); OUTREG(SRC_OFFSET, 0x00000000); OUTREG(DST_OFFSET, 0x00000000); mdelay(10); OUTREG(CRTC_EXT_CNTL, INREG(CRTC_EXT_CNTL) & ~CRTC_DISPLAY_DIS); #endif /* CONFIG_ALL_PPC */ /* save current mode regs before we switch into the new one * so we can restore this upon __exit */ radeon_save_state (rinfo, &rinfo->init_state); /* set all the vital stuff */ radeon_set_fbinfo (rinfo); pci_set_drvdata(pdev, rinfo); rinfo->next = board_list; board_list = rinfo; ((struct fb_info *) rinfo)->device = &pdev->dev; if (<API key> ((struct fb_info *) rinfo) < 0) { printk ("radeonfb: could not register framebuffer\n"); iounmap(rinfo->fb_base); iounmap(rinfo->mmio_base); release_mem_region (rinfo->mmio_base_phys, pci_resource_len(pdev, 2)); release_mem_region (rinfo->fb_base_phys, pci_resource_len(pdev, 0)); kfree (rinfo); return -ENODEV; } #ifdef CONFIG_MTRR rinfo->mtrr_hdl = nomtrr ? -1 : mtrr_add(rinfo->fb_base_phys, rinfo->video_ram, MTRR_TYPE_WRCOMB, 1); #endif #ifdef <API key> if (rinfo->dviDisp_type == MT_LCD) <API key>(&<API key>, rinfo, "ati"); #endif #ifdef CONFIG_PMAC_PBOOK if (rinfo->dviDisp_type == MT_LCD) { rinfo->pm_reg = pci_find_capability(pdev, PCI_CAP_ID_PM); <API key>(&<API key>); } #endif printk ("radeonfb: ATI Radeon %s %s %d MB\n", rinfo->name, rinfo->ram_type, (rinfo->video_ram/(1024*1024))); if (rinfo->hasCRTC2) { printk("radeonfb: DVI port %s monitor connected\n", GET_MON_NAME(rinfo->dviDisp_type)); printk("radeonfb: CRT port %s monitor connected\n", GET_MON_NAME(rinfo->crtDisp_type)); } else { printk("radeonfb: CRT port %s monitor connected\n", GET_MON_NAME(rinfo->crtDisp_type)); } RTRACE("<API key> END\n"); return 0; } static void __devexit <API key> (struct pci_dev *pdev) { struct radeonfb_info *rinfo = pci_get_drvdata(pdev); if (!rinfo) return; /* restore original state * * Doesn't quite work yet, possibly because of the PPC hacking * I do on startup, disable for now. --BenH */ radeon_write_mode (rinfo, &rinfo->init_state); #ifdef CONFIG_MTRR if (rinfo->mtrr_hdl >= 0) mtrr_del(rinfo->mtrr_hdl, 0, 0); #endif <API key> ((struct fb_info *) rinfo); iounmap(rinfo->mmio_base); iounmap(rinfo->fb_base); release_mem_region (rinfo->mmio_base_phys, pci_resource_len(pdev, 2)); release_mem_region (rinfo->fb_base_phys, pci_resource_len(pdev, 0)); kfree (rinfo); } static struct pci_driver radeonfb_driver = { .name = "radeonfb", .id_table = radeonfb_pci_table, .probe = <API key>, .remove = __devexit_p(<API key>), }; int __init radeonfb_old_setup (char *options); int __init radeonfb_old_init (void) { #ifndef MODULE char *option = NULL; if (fb_get_options("radeonfb_old", &option)) return -ENODEV; radeonfb_old_setup(option); #endif return pci_module_init (&radeonfb_driver); } void __exit radeonfb_old_exit (void) { <API key> (&radeonfb_driver); } int __init radeonfb_old_setup (char *options) { char *this_opt; if (!options || !*options) return 0; while ((this_opt = strsep (&options, ",")) != NULL) { if (!*this_opt) continue; if (!strncmp(this_opt, "noaccel", 7)) { noaccel = 1; } else if (!strncmp(this_opt, "mirror", 6)) { mirror = 1; } else if (!strncmp(this_opt, "dfp", 3)) { force_dfp = 1; } else if (!strncmp(this_opt, "panel_yres:", 11)) { panel_yres = simple_strtoul((this_opt+11), NULL, 0); } else if (!strncmp(this_opt, "nomtrr", 6)) { nomtrr = 1; } else mode_option = this_opt; } return 0; } module_init(radeonfb_old_init); #ifdef MODULE module_exit(radeonfb_old_exit); #endif MODULE_AUTHOR("Ani Joshi"); MODULE_DESCRIPTION("framebuffer driver for ATI Radeon chipset"); MODULE_LICENSE("GPL");
#include <cstdlib> #include <zlib.h> #include "utils/zlib.h" #include "utils/logger.h" static void logZlibError(int error) { switch (error) { case Z_MEM_ERROR: LOG_ERROR("Out of memory while decompressing data!"); break; case Z_VERSION_ERROR: LOG_ERROR("Incompatible zlib version!"); break; case Z_DATA_ERROR: LOG_ERROR("Incorrect zlib compressed data!"); break; default: LOG_ERROR("Unknown error while decompressing data!"); } } bool inflateMemory(char *in, unsigned inLength, char *&out, unsigned &outLength) { int bufferSize = 256 * 1024; int ret; z_stream strm; out = (char *)malloc(bufferSize); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = (Bytef *)in; strm.avail_in = inLength; strm.next_out = (Bytef *)out; strm.avail_out = bufferSize; ret = inflateInit2(&strm, 15 + 32); if (ret != Z_OK) { logZlibError(ret); free(out); return false; } do { ret = inflate(&strm, Z_SYNC_FLUSH); switch (ret) { case Z_NEED_DICT: case Z_STREAM_ERROR: ret = Z_DATA_ERROR; case Z_DATA_ERROR: case Z_MEM_ERROR: inflateEnd(&strm); logZlibError(ret); free(out); return false; } if (ret != Z_STREAM_END) { out = (char *)realloc(out, bufferSize * 2); if (!out) { inflateEnd(&strm); logZlibError(Z_MEM_ERROR); free(out); return false; } strm.next_out = (Bytef *)(out + bufferSize); strm.avail_out = bufferSize; bufferSize *= 2; } } while (ret != Z_STREAM_END); if (strm.avail_in != 0) { logZlibError(Z_DATA_ERROR); free(out); return false; } outLength = bufferSize - strm.avail_out; inflateEnd(&strm); return true; }
<?php class <API key> extends \<API key> { /** * @covers InstallDocFormatter * @dataProvider <API key> */ public function testFormat( $expected, $unformattedText, $message = '' ) { $this->assertEquals( $expected, InstallDocFormatter::format( $unformattedText ), $message ); } /** * Provider for testFormat() */ public static function <API key>() { # Format: (expected string, unformattedText string, optional message) return [ # Escape some wikitext [ 'Install &lt;tag>', 'Install <tag>', 'Escaping <' ], [ 'Install &#123;&#123;template}}', 'Install {{template}}', 'Escaping [[' ], [ 'Install &#91;&#91;page]]', 'Install [[page]]', 'Escaping {{' ], [ 'Install &#95;&#95;TOC&#95;&#95;', 'Install __TOC__', 'Escaping __' ], [ 'Install ', "Install \r", 'Removing \r' ], # Transform \t{1,2} into :{1,2} [ ':One indentation', "\tOne indentation", 'Replacing a single \t' ], [ '::Two indentations', "\t\tTwo indentations", 'Replacing 2 x \t' ], # Transform 'T123' links [ '<span class="config-plainlink">[https://phabricator.wikimedia.org/T123 T123]</span>', 'T123', 'Testing T123 links' ], [ 'bug <span class="config-plainlink">[https://phabricator.wikimedia.org/T123 T123]</span>', 'bug T123', 'Testing bug T123 links' ], [ '(<span class="config-plainlink">[https://phabricator.wikimedia.org/T987654 T987654]</span>)', '(T987654)', 'Testing (T987654) links' ], # "Tabc" shouldn't work [ 'Tfoobar', 'Tfoobar', "Don't match T followed by non-digits" ], [ 'T!!fakefake!!', 'T!!fakefake!!', "Don't match T followed by non-digits" ], # Transform 'bug 123' links [ '<span class="config-plainlink">[https://bugzilla.wikimedia.org/123 bug 123]</span>', 'bug 123', 'Testing bug 123 links' ], [ '(<span class="config-plainlink">[https://bugzilla.wikimedia.org/987654 bug 987654]</span>)', '(bug 987654)', 'Testing (bug 987654) links' ], # "bug abc" shouldn't work [ 'bug foobar', 'bug foobar', "Don't match bug followed by non-digits" ], [ 'bug !!fakefake!!', 'bug !!fakefake!!', "Don't match bug followed by non-digits" ], # Transform '$wgFooBar' links [ '<span class="config-plainlink">' . '[https: '$wgFooBar', 'Testing basic $wgFooBar' ], [ '<span class="config-plainlink">' . '[https: '$wgFooBar45', 'Testing $wgFooBar45 (with numbers)' ], [ '<span class="config-plainlink">' . '[https: '$wgFoo_Bar', 'Testing $wgFoo_Bar (with underscore)' ], # Icky variables that shouldn't link [ '$myAwesomeVariable', '$myAwesomeVariable', 'Testing $myAwesomeVariable (not starting with $wg)' ], [ '$()not!a&Var', '$()not!a&Var', 'Testing $()not!a&Var (obviously not a variable)' ], ]; } }
#ifndef __EFS_FS_I_H__ #define __EFS_FS_I_H__ typedef int32_t efs_block_t; typedef uint32_t efs_ino_t; #define EFS_DIRECTEXTENTS 12 /* * layout of an extent, in memory and on disk. 8 bytes exactly. */ typedef union extent_u { unsigned char raw[8]; struct extent_s { unsigned int ex_magic:8; /* magic # (zero) */ unsigned int ex_bn:24; /* basic block */ unsigned int ex_length:8; /* numblocks in this extent */ unsigned int ex_offset:24; /* logical offset into file */ } cooked; } efs_extent; typedef struct edevs { short odev; unsigned int ndev; } efs_devs; /* * extent based filesystem inode as it appears on disk. The efs inode * is exactly 128 bytes long. */ struct efs_dinode { u_short di_mode; /* mode and type of file */ short di_nlink; /* number of links to file */ u_short di_uid; /* owner's user id */ u_short di_gid; /* owner's group id */ int32_t di_size; /* number of bytes in file */ int32_t di_atime; /* time last accessed */ int32_t di_mtime; /* time last modified */ int32_t di_ctime; /* time created */ uint32_t di_gen; /* generation number */ short di_numextents; /* # of extents */ u_char di_version; /* version of inode */ u_char di_spare; /* spare - used by AFS */ union di_addr { efs_extent di_extents[EFS_DIRECTEXTENTS]; efs_devs di_dev; /* device for IFCHR/IFBLK */ } di_u; }; /* efs inode storage in memory */ struct efs_inode_info { int numextents; int lastextent; efs_extent extents[EFS_DIRECTEXTENTS]; struct inode vfs_inode; }; #endif /* __EFS_FS_I_H__ */
import React from "react"; import PropTypes from "prop-types"; import Box from "grommet/components/Box"; import Paragraph from "grommet/components/Paragraph"; import Label from "grommet/components/Label"; import FormLayer from "../components/FormLayer"; class <API key> extends React.Component { constructor(props) { super(props); this.state = { layerActive: false }; } _onClick() { this.setState({ layerActive: true }); } render() { if (this.props.idSchema["$id"] == "root") { return <Box>{this.props.properties.map(prop => prop.content)}</Box>; } else { return ( <Box className="<API key>" direction="row" wrap={false}> { <FormLayer layerActive={this.state.layerActive} onClose={(() => { this.setState({ layerActive: false }); }).bind(this)} properties={this.props.properties.map(prop => prop.content)} /> } <Box flex={true}> <Box align="center"> <Label size="small" strong="none" uppercase={true}> {this.props.title} </Label> </Box> {this.props.description ? ( <Paragraph size="small">{this.props.description}</Paragraph> ) : null} </Box> </Box> ); } } } <API key>.propTypes = { title: PropTypes.string, description: PropTypes.string, required: PropTypes.bool, idSchema: PropTypes.object, uiSchema: PropTypes.object, properties: PropTypes.object }; export default <API key>;
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include "rtos.h" static const struct <API key> <API key>[] = { { 0x24, 32 }, { 0x28, 32 }, { 0x2c, 32 }, { 0x30, 32 }, { 0x00, 32 }, { 0x04, 32 }, { 0x08, 32 }, { 0x0c, 32 }, { 0x10, 32 }, { 0x14, 32 }, { 0x18, 32 }, /* r10 */ { 0x1c, 32 }, /* r11 */ { 0x34, 32 }, /* r12 */ { -2, 32 }, { 0x38, 32 }, { 0x3c, 32 }, { -1, 96 }, /* FPA1 */ { -1, 96 }, /* FPA2 */ { -1, 96 }, /* FPA3 */ { -1, 96 }, /* FPA4 */ { -1, 96 }, /* FPA5 */ { -1, 96 }, /* FPA6 */ { -1, 96 }, /* FPA7 */ { -1, 96 }, /* FPA8 */ { -1, 32 }, /* FPS */ { 0x40, 32 }, /* xPSR */ }; const struct <API key> <API key> = { 0x40, /* <API key> */ -1, /* <API key> */ 26, /* <API key> */ 8, /* stack_alignment */ <API key> /* register_offsets */ };
#include <linux/types.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/spinlock.h> #include <linux/genalloc.h> #include <linux/slab.h> #include <linux/iommu.h> #include <linux/msm_kgsl.h> #include <mach/socinfo.h> #include <mach/msm_iomap.h> #include <mach/board.h> #include <mach/iommu_domains.h> #include <stddef.h> #include "kgsl.h" #include "kgsl_device.h" #include "kgsl_mmu.h" #include "kgsl_sharedmem.h" #include "kgsl_iommu.h" #include "adreno_pm4types.h" #include "adreno.h" #include "kgsl_trace.h" #include "z180.h" #include "kgsl_cffdump.h" static struct <API key> kgsl_iommuv0_reg[KGSL_IOMMU_REG_MAX] = { { 0, 0 }, /* GLOBAL_BASE */ { 0x0, 1 }, /* SCTLR */ { 0x10, 1 }, /* TTBR0 */ { 0x14, 1 }, /* TTBR1 */ { 0x20, 1 }, /* FSR */ { 0x800, 1 }, /* TLBIALL */ { 0x820, 1 }, /* RESUME */ { 0x03C, 1 }, /* TLBLKCR */ { 0x818, 1 }, /* V2PUR */ { 0x2C, 1 }, /* FSYNR0 */ { 0x30, 1 }, /* FSYNR1 */ { 0, 0 }, /* TLBSYNC, not in v0 */ { 0, 0 }, /* TLBSTATUS, not in v0 */ { 0, 0 } /* <API key>, not in v0 */ }; static struct <API key> kgsl_iommuv1_reg[KGSL_IOMMU_REG_MAX] = { { 0, 0 }, /* GLOBAL_BASE */ { 0x0, 1 }, /* SCTLR */ { 0x20, 1 }, /* TTBR0 */ { 0x28, 1 }, /* TTBR1 */ { 0x58, 1 }, /* FSR */ { 0x618, 1 }, /* TLBIALL */ { 0x008, 1 }, /* RESUME */ { 0, 0 }, /* TLBLKCR not in V1 */ { 0, 0 }, /* V2PUR not in V1 */ { 0x68, 1 }, /* FSYNR0 */ { 0x6C, 1 }, /* FSYNR1 */ { 0x7F0, 1 }, /* TLBSYNC */ { 0x7F4, 1 }, /* TLBSTATUS */ { 0x2000, 0 } /* <API key> */ }; static struct iommu_access_ops *iommu_access_ops; static int <API key>(struct kgsl_mmu *mmu, uint32_t flags); static phys_addr_t <API key>(struct kgsl_mmu *mmu); static void _iommu_lock(struct kgsl_iommu const *iommu) { if (iommu_access_ops && iommu_access_ops->iommu_lock_acquire) iommu_access_ops->iommu_lock_acquire( iommu-><API key>); } static void _iommu_unlock(struct kgsl_iommu const *iommu) { if (iommu_access_ops && iommu_access_ops->iommu_lock_release) iommu_access_ops->iommu_lock_release( iommu-><API key>); } struct <API key> <API key>; /* * One page allocation for a guard region to protect against over-zealous * GPU pre-fetch */ static struct page *kgsl_guard_page; static int get_iommu_unit(struct device *dev, struct kgsl_mmu **mmu_out, struct kgsl_iommu_unit **iommu_unit_out) { int i, j, k; for (i = 0; i < KGSL_DEVICE_MAX; i++) { struct kgsl_mmu *mmu; struct kgsl_iommu *iommu; if (kgsl_driver.devp[i] == NULL) continue; mmu = kgsl_get_mmu(kgsl_driver.devp[i]); if (mmu == NULL || mmu->priv == NULL) continue; iommu = mmu->priv; for (j = 0; j < iommu->unit_count; j++) { struct kgsl_iommu_unit *iommu_unit = &iommu->iommu_units[j]; for (k = 0; k < iommu_unit->dev_count; k++) { if (iommu_unit->dev[k].dev == dev) { *mmu_out = mmu; *iommu_unit_out = iommu_unit; return 0; } } } } return -EINVAL; } static struct kgsl_iommu_device *get_iommu_device(struct kgsl_iommu_unit *unit, struct device *dev) { int k; for (k = 0; unit && k < unit->dev_count; k++) { if (unit->dev[k].dev == dev) return &(unit->dev[k]); } return NULL; } /* These functions help find the nearest allocated memory entries on either side * of a faulting address. If we know the nearby allocations memory we can * get a better determination of what we think should have been located in the * faulting region */ /* * A local structure to make it easy to store the interesting bits for the * memory entries on either side of the faulting address */ struct _mem_entry { unsigned int gpuaddr; unsigned int size; unsigned int flags; unsigned int priv; pid_t pid; }; /* * Find the closest alloated memory block with an smaller GPU address then the * given address */ static void _prev_entry(struct <API key> *priv, unsigned int faultaddr, struct _mem_entry *ret) { struct rb_node *node; struct kgsl_mem_entry *entry; for (node = rb_first(&priv->mem_rb); node; ) { entry = rb_entry(node, struct kgsl_mem_entry, node); if (entry->memdesc.gpuaddr > faultaddr) break; /* * If this is closer to the faulting address, then copy * the entry */ if (entry->memdesc.gpuaddr > ret->gpuaddr) { ret->gpuaddr = entry->memdesc.gpuaddr; ret->size = entry->memdesc.size; ret->flags = entry->memdesc.flags; ret->priv = entry->memdesc.priv; ret->pid = priv->pid; } node = rb_next(&entry->node); } } /* * Find the closest alloated memory block with a greater starting GPU address * then the given address */ static void _next_entry(struct <API key> *priv, unsigned int faultaddr, struct _mem_entry *ret) { struct rb_node *node; struct kgsl_mem_entry *entry; for (node = rb_last(&priv->mem_rb); node; ) { entry = rb_entry(node, struct kgsl_mem_entry, node); if (entry->memdesc.gpuaddr < faultaddr) break; /* * If this is closer to the faulting address, then copy * the entry */ if (entry->memdesc.gpuaddr < ret->gpuaddr) { ret->gpuaddr = entry->memdesc.gpuaddr; ret->size = entry->memdesc.size; ret->flags = entry->memdesc.flags; ret->priv = entry->memdesc.priv; ret->pid = priv->pid; } node = rb_prev(&entry->node); } } static void _find_mem_entries(struct kgsl_mmu *mmu, unsigned int faultaddr, unsigned int ptbase, struct _mem_entry *preventry, struct _mem_entry *nextentry) { struct <API key> *private; int id = <API key>(mmu, ptbase); memset(preventry, 0, sizeof(*preventry)); memset(nextentry, 0, sizeof(*nextentry)); /* Set the maximum possible size as an initial value */ nextentry->gpuaddr = 0xFFFFFFFF; mutex_lock(&kgsl_driver.process_mutex); list_for_each_entry(private, &kgsl_driver.process_list, list) { if (private->pagetable && (private->pagetable->name != id)) continue; spin_lock(&private->mem_lock); _prev_entry(private, faultaddr, preventry); _next_entry(private, faultaddr, nextentry); spin_unlock(&private->mem_lock); } mutex_unlock(&kgsl_driver.process_mutex); } static void _print_entry(struct kgsl_device *device, struct _mem_entry *entry) { char name[32]; memset(name, 0, sizeof(name)); <API key>(name, sizeof(name) - 1, entry->flags); KGSL_LOG_DUMP(device, "[%8.8X - %8.8X] %s (pid = %d) (%s)\n", entry->gpuaddr, entry->gpuaddr + entry->size, entry->priv & <API key> ? "(+guard)" : "", entry->pid, name); } static void _check_if_freed(struct kgsl_iommu_device *iommu_dev, unsigned long addr, unsigned int pid) { void *base = kgsl_driver.memfree_hist.base_hist_rb; struct <API key> *wptr; struct <API key> *p; char name[32]; memset(name, 0, sizeof(name)); mutex_lock(&kgsl_driver.memfree_hist_mutex); wptr = kgsl_driver.memfree_hist.wptr; p = wptr; for (;;) { if (p->size && p->pid == pid) if (addr >= p->gpuaddr && addr < (p->gpuaddr + p->size)) { <API key>(name, sizeof(name) - 1, p->flags); KGSL_LOG_DUMP(iommu_dev->kgsldev, " KGSL_LOG_DUMP(iommu_dev->kgsldev, "[%8.8X-%8.8X] (%s) was already freed by pid %d\n", p->gpuaddr, p->gpuaddr + p->size, name, p->pid); } p++; if ((void *)p >= base + kgsl_driver.memfree_hist.size) p = (struct <API key> *) base; if (p == kgsl_driver.memfree_hist.wptr) break; } mutex_unlock(&kgsl_driver.memfree_hist_mutex); } static int <API key>(struct iommu_domain *domain, struct device *dev, unsigned long addr, int flags, void *token) { int ret = 0; struct kgsl_mmu *mmu; struct kgsl_iommu *iommu; struct kgsl_iommu_unit *iommu_unit; struct kgsl_iommu_device *iommu_dev; unsigned int ptbase, fsr; unsigned int pid; struct _mem_entry prev, next; unsigned int fsynr0, fsynr1; int write; struct kgsl_device *device; struct adreno_device *adreno_dev; unsigned int no_page_fault_log = 0; unsigned int curr_context_id = 0; unsigned int curr_global_ts = 0; struct kgsl_context *context; ret = get_iommu_unit(dev, &mmu, &iommu_unit); if (ret) goto done; device = mmu->device; adreno_dev = ADRENO_DEVICE(device); if (atomic_read(&mmu->fault)) { if (adreno_dev->ft_pf_policy & <API key>) ret = -EBUSY; goto done; } iommu_dev = get_iommu_device(iommu_unit, dev); if (!iommu_dev) { KGSL_CORE_ERR("Invalid IOMMU device %p\n", dev); ret = -ENOSYS; goto done; } iommu = mmu->priv; /* * set the fault bits and stuff before any printks so that if fault * handler runs then it will know it's dealing with a pagefault */ <API key>(&device->memstore, &curr_context_id, <API key>(<API key>, current_context)); context = kgsl_context_get(device, curr_context_id); if (context != NULL) { <API key>(&device->memstore, &curr_global_ts, <API key>(<API key>, eoptimestamp)); /* save pagefault timestamp for GFT */ set_bit(<API key>, &context->priv); context->pagefault_ts = curr_global_ts; kgsl_context_put(context); context = NULL; } atomic_set(&mmu->fault, 1); iommu_dev->fault = 1; if (adreno_dev->ft_pf_policy & <API key>) { <API key>(adreno_dev, <API key>); /* turn off GPU IRQ so we don't get faults from it too */ kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_OFF); <API key>(device); } ptbase = <API key>(iommu, iommu_unit, iommu_dev->ctx_id, TTBR0); fsr = <API key>(iommu, iommu_unit, iommu_dev->ctx_id, FSR); fsynr0 = <API key>(iommu, iommu_unit, iommu_dev->ctx_id, FSYNR0); fsynr1 = <API key>(iommu, iommu_unit, iommu_dev->ctx_id, FSYNR1); if (<API key>()) write = ((fsynr1 & (<API key> << <API key>)) ? 1 : 0); else write = ((fsynr0 & (<API key> << <API key>)) ? 1 : 0); pid = <API key>(mmu, ptbase); if (adreno_dev->ft_pf_policy & <API key>) no_page_fault_log = <API key>(mmu, ptbase, addr); if (!no_page_fault_log) { KGSL_MEM_CRIT(iommu_dev->kgsldev, "GPU PAGE FAULT: addr = %lX pid = %d\n", addr, pid); KGSL_MEM_CRIT(iommu_dev->kgsldev, "context = %d FSR = %X FSYNR0 = %X FSYNR1 = %X(%s fault)\n", iommu_dev->ctx_id, fsr, fsynr0, fsynr1, write ? "write" : "read"); _check_if_freed(iommu_dev, addr, pid); KGSL_LOG_DUMP(iommu_dev->kgsldev, " _find_mem_entries(mmu, addr, ptbase, &prev, &next); if (prev.gpuaddr) _print_entry(iommu_dev->kgsldev, &prev); else KGSL_LOG_DUMP(iommu_dev->kgsldev, "*EMPTY*\n"); KGSL_LOG_DUMP(iommu_dev->kgsldev, " <- fault @ %8.8lX\n", addr); if (next.gpuaddr != 0xFFFFFFFF) _print_entry(iommu_dev->kgsldev, &next); else KGSL_LOG_DUMP(iommu_dev->kgsldev, "*EMPTY*\n"); } <API key>(iommu_dev->kgsldev, addr, <API key>(mmu, ptbase), write ? "write" : "read"); /* * We do not want the h/w to resume fetching data from an iommu unit * that has faulted, this is better for debugging as it will stall * the GPU and trigger a snapshot. To stall the transaction return * EBUSY error. */ if (adreno_dev->ft_pf_policy & <API key>) ret = -EBUSY; done: return ret; } /* * <API key> - Disable iommu clocks * @mmu - Pointer to mmu structure * * Disables iommu clocks * Return - void */ static void <API key>(struct kgsl_mmu *mmu, int ctx_id) { struct kgsl_iommu *iommu = mmu->priv; struct msm_iommu_drvdata *iommu_drvdata; int i, j; for (i = 0; i < iommu->unit_count; i++) { struct kgsl_iommu_unit *iommu_unit = &iommu->iommu_units[i]; for (j = 0; j < iommu_unit->dev_count; j++) { if (ctx_id != iommu_unit->dev[j].ctx_id) continue; atomic_dec(&iommu_unit->dev[j].clk_enable_count); BUG_ON( atomic_read(&iommu_unit->dev[j].clk_enable_count) < 0); /* * the clock calls have a refcount so call them on every * enable/disable call */ iommu_drvdata = dev_get_drvdata( iommu_unit->dev[j].dev->parent); if (iommu_drvdata->aclk) <API key>(iommu_drvdata->aclk); if (iommu_drvdata->clk) <API key>(iommu_drvdata->clk); <API key>(iommu_drvdata->pclk); } } } /* * <API key> - An event function that is executed when * the required timestamp is reached. It disables the IOMMU clocks if * the timestamp on which the clocks can be disabled has expired. * @device - The kgsl device pointer * @data - The data passed during event creation, it is the MMU pointer * @id - Context ID, should always be <API key> * @ts - The current timestamp that has expired for the device * * Disables IOMMU clocks if timestamp has expired * Return - void */ static void <API key>(struct kgsl_device *device, void *data, unsigned int id, unsigned int ts, u32 type) { struct <API key> *param = data; if ((0 <= timestamp_cmp(ts, param->ts)) || (<API key> == type)) <API key>(param->mmu, param->ctx_id); else /* something went wrong with the event handling mechanism */ BUG_ON(1); /* Free param we are done using it */ kfree(param); } /* * <API key> - Sets up event to disable IOMMU clocks * @mmu - The kgsl MMU pointer * @ts - Timestamp on which the clocks should be disabled * @ts_valid - Indicates whether ts parameter is valid, if this parameter * is false then it means that the calling function wants to disable the * IOMMU clocks immediately without waiting for any timestamp * @ctx_id: Context id of the IOMMU context for which clocks are to be * turned off * * Creates an event to disable the IOMMU clocks on timestamp and if event * already exists then updates the timestamp of disabling the IOMMU clocks * with the passed in ts if it is greater than the current value at which * the clocks will be disabled * Return - void */ static void <API key>(struct kgsl_mmu *mmu, unsigned int ts, int ctx_id) { struct <API key> *param; param = kzalloc(sizeof(*param), GFP_KERNEL); if (!param) { KGSL_CORE_ERR("kzalloc(%d) failed\n", sizeof(*param)); return; } param->mmu = mmu; param->ctx_id = ctx_id; param->ts = ts; if (kgsl_add_event(mmu->device, <API key>, ts, <API key>, param, mmu)) { KGSL_DRV_ERR(mmu->device, "Failed to add IOMMU disable clk event\n"); kfree(param); } } /* * <API key> - Enable iommu clocks * @mmu - Pointer to mmu structure * @ctx_id - The context bank whose clocks are to be turned on * * Enables iommu clocks of a given context * Return: 0 on success else error code */ static int <API key>(struct kgsl_mmu *mmu, int ctx_id) { int ret = 0; int i, j; struct kgsl_iommu *iommu = mmu->priv; struct msm_iommu_drvdata *iommu_drvdata; for (i = 0; i < iommu->unit_count; i++) { struct kgsl_iommu_unit *iommu_unit = &iommu->iommu_units[i]; for (j = 0; j < iommu_unit->dev_count; j++) { if (ctx_id != iommu_unit->dev[j].ctx_id) continue; iommu_drvdata = dev_get_drvdata(iommu_unit->dev[j].dev->parent); ret = clk_prepare_enable(iommu_drvdata->pclk); if (ret) goto done; if (iommu_drvdata->clk) { ret = clk_prepare_enable(iommu_drvdata->clk); if (ret) { <API key>( iommu_drvdata->pclk); goto done; } } if (iommu_drvdata->aclk) { ret = clk_prepare_enable(iommu_drvdata->aclk); if (ret) { if (iommu_drvdata->clk) <API key>( iommu_drvdata->clk); <API key>( iommu_drvdata->pclk); goto done; } } atomic_inc(&iommu_unit->dev[j].clk_enable_count); } } done: if (ret) { struct kgsl_iommu_unit *iommu_unit; if (iommu->unit_count == i) i iommu_unit = &iommu->iommu_units[i]; do { for (j--; j >= 0; j--) <API key>(mmu, ctx_id); i if (i >= 0) { iommu_unit = &iommu->iommu_units[i]; j = iommu_unit->dev_count; } } while (i >= 0); } return ret; } /* * kgsl_iommu_pt_equal - Check if pagetables are equal * @mmu - Pointer to mmu structure * @pt - Pointer to pagetable * @pt_base - Address of a pagetable that the IOMMU register is * programmed with * * Checks whether the pt_base is equal to the base address of * the pagetable which is contained in the pt structure * Return - Non-zero if the pagetable addresses are equal else 0 */ static int kgsl_iommu_pt_equal(struct kgsl_mmu *mmu, struct kgsl_pagetable *pt, phys_addr_t pt_base) { struct kgsl_iommu_pt *iommu_pt = pt ? pt->priv : NULL; phys_addr_t domain_ptbase = iommu_pt ? <API key>(iommu_pt->domain) : 0; /* Only compare the valid address bits of the pt_base */ domain_ptbase &= <API key>; pt_base &= <API key>; return domain_ptbase && pt_base && (domain_ptbase == pt_base); } /* * <API key> - Free up reaources help by a pagetable * @mmu_specific_pt - Pointer to pagetable which is to be freed * * Return - void */ static void <API key>(struct kgsl_pagetable *pt) { struct kgsl_iommu_pt *iommu_pt = pt->priv; if (iommu_pt->domain) <API key>(iommu_pt->domain); kfree(iommu_pt); iommu_pt = NULL; } /* * <API key> - Create a IOMMU pagetable * * Allocate memory to hold a pagetable and allocate the IOMMU * domain which is the actual IOMMU pagetable * Return - void */ void *<API key>(void) { int domain_num; struct kgsl_iommu_pt *iommu_pt; struct msm_iova_partition kgsl_partition = { .start = 0, .size = 0xFFFFFFFF, }; struct msm_iova_layout kgsl_layout = { .partitions = &kgsl_partition, .npartitions = 1, .client_name = "kgsl", .domain_flags = 0, }; iommu_pt = kzalloc(sizeof(struct kgsl_iommu_pt), GFP_KERNEL); if (!iommu_pt) { KGSL_CORE_ERR("kzalloc(%d) failed\n", sizeof(struct kgsl_iommu_pt)); return NULL; } /* L2 redirect is not stable on IOMMU v1 */ if (<API key>()) kgsl_layout.domain_flags = <API key>; domain_num = msm_register_domain(&kgsl_layout); if (domain_num >= 0) { iommu_pt->domain = <API key>(domain_num); if (iommu_pt->domain) { <API key>(iommu_pt->domain, <API key>, NULL); return iommu_pt; } } KGSL_CORE_ERR("Failed to create iommu domain\n"); kfree(iommu_pt); return NULL; } /* * <API key> - Detach the IOMMU unit from a * pagetable * @mmu - Pointer to the device mmu structure * @priv - Flag indicating whether the private or user context is to be * detached * * Detach the IOMMU unit with the domain that is contained in the * hwpagetable of the given mmu. After detaching the IOMMU unit is not * in use because the PTBR will not be set after a detach * Return - void */ static void <API key>(struct kgsl_mmu *mmu) { struct kgsl_iommu_pt *iommu_pt; struct kgsl_iommu *iommu = mmu->priv; int i, j; for (i = 0; i < iommu->unit_count; i++) { struct kgsl_iommu_unit *iommu_unit = &iommu->iommu_units[i]; iommu_pt = mmu->defaultpagetable->priv; for (j = 0; j < iommu_unit->dev_count; j++) { /* * If there is a 2nd default pagetable then priv domain * is attached with this pagetable */ if (mmu->priv_bank_table && (<API key> == j)) iommu_pt = mmu->priv_bank_table->priv; if (iommu_unit->dev[j].attached) { iommu_detach_device(iommu_pt->domain, iommu_unit->dev[j].dev); iommu_unit->dev[j].attached = false; KGSL_MEM_INFO(mmu->device, "iommu %p detached " "from user dev of MMU: %p\n", iommu_pt->domain, mmu); } } } } /* * <API key> - Attach the IOMMU unit to a * pagetable, i.e set the IOMMU's PTBR to the pagetable address and * setup other IOMMU registers for the device so that it becomes * active * @mmu - Pointer to the device mmu structure * @priv - Flag indicating whether the private or user context is to be * attached * * Attach the IOMMU unit with the domain that is contained in the * hwpagetable of the given mmu. * Return - 0 on success else error code */ static int <API key>(struct kgsl_mmu *mmu) { struct kgsl_iommu_pt *iommu_pt; struct kgsl_iommu *iommu = mmu->priv; int i, j, ret = 0; /* * Loop through all the iommu devcies under all iommu units and * attach the domain */ for (i = 0; i < iommu->unit_count; i++) { struct kgsl_iommu_unit *iommu_unit = &iommu->iommu_units[i]; iommu_pt = mmu->defaultpagetable->priv; for (j = 0; j < iommu_unit->dev_count; j++) { /* * If there is a 2nd default pagetable then priv domain * is attached to this pagetable */ if (mmu->priv_bank_table && (<API key> == j)) iommu_pt = mmu->priv_bank_table->priv; if (!iommu_unit->dev[j].attached) { ret = iommu_attach_device(iommu_pt->domain, iommu_unit->dev[j].dev); if (ret) { KGSL_MEM_ERR(mmu->device, "Failed to attach device, err %d\n", ret); goto done; } iommu_unit->dev[j].attached = true; KGSL_MEM_INFO(mmu->device, "iommu pt %p attached to dev %p, ctx_id %d\n", iommu_pt->domain, iommu_unit->dev[j].dev, iommu_unit->dev[j].ctx_id); } } } done: return ret; } /* * _get_iommu_ctxs - Get device pointer to IOMMU contexts * @mmu - Pointer to mmu device * data - Pointer to the platform data containing information about * iommu devices for one iommu unit * unit_id - The IOMMU unit number. This is not a specific ID but just * a serial number. The serial numbers are treated as ID's of the * IOMMU units * * Return - 0 on success else error code */ static int _get_iommu_ctxs(struct kgsl_mmu *mmu, struct <API key> *data, unsigned int unit_id) { struct kgsl_iommu *iommu = mmu->priv; struct kgsl_iommu_unit *iommu_unit = &iommu->iommu_units[unit_id]; int i, j; int found_ctx; int ret = 0; for (j = 0; j < <API key>; j++) { found_ctx = 0; for (i = 0; i < data->iommu_ctx_count; i++) { if (j == data->iommu_ctxs[i].ctx_id) { found_ctx = 1; break; } } if (!found_ctx) break; if (!data->iommu_ctxs[i].iommu_ctx_name) { KGSL_CORE_ERR("Context name invalid\n"); ret = -EINVAL; goto done; } atomic_set( &(iommu_unit->dev[iommu_unit->dev_count].clk_enable_count), 0); iommu_unit->dev[iommu_unit->dev_count].dev = msm_iommu_get_ctx(data->iommu_ctxs[i].iommu_ctx_name); if (NULL == iommu_unit->dev[iommu_unit->dev_count].dev) ret = -EINVAL; if (IS_ERR(iommu_unit->dev[iommu_unit->dev_count].dev)) { ret = PTR_ERR( iommu_unit->dev[iommu_unit->dev_count].dev); iommu_unit->dev[iommu_unit->dev_count].dev = NULL; } if (ret) goto done; iommu_unit->dev[iommu_unit->dev_count].ctx_id = data->iommu_ctxs[i].ctx_id; iommu_unit->dev[iommu_unit->dev_count].kgsldev = mmu->device; KGSL_DRV_INFO(mmu->device, "Obtained dev handle %p for iommu context %s\n", iommu_unit->dev[iommu_unit->dev_count].dev, data->iommu_ctxs[i].iommu_ctx_name); iommu_unit->dev_count++; } done: if (!iommu_unit->dev_count && !ret) ret = -EINVAL; if (ret) { /* * If at least the first context is initialized on v1 * then we can continue */ if (!<API key>() && iommu_unit->dev_count) ret = 0; else KGSL_CORE_ERR( "Failed to initialize iommu contexts, err: %d\n", ret); } return ret; } /* * <API key> - Initialize some variables during MMU start up * for GPU CPU synchronization * @mmu - Pointer to mmu device * * Return - 0 on success else error code */ static int <API key>(struct kgsl_mmu *mmu) { struct kgsl_iommu *iommu = mmu->priv; uint32_t lock_gpu_addr = 0; if (KGSL_DEVICE_3D0 != mmu->device->id || !<API key>() || !<API key>(mmu) || iommu->sync_lock_vars) return 0; if (!(mmu->flags & <API key>)) { KGSL_DRV_ERR(mmu->device, "The GPU microcode does not support IOMMUv1 sync opcodes\n"); return -ENXIO; } /* Store Lock variables GPU address */ lock_gpu_addr = (iommu->sync_lock_desc.gpuaddr + iommu->sync_lock_offset); <API key>.flag[PROC_APPS] = (lock_gpu_addr + (offsetof(struct <API key>, flag[PROC_APPS]))); <API key>.flag[PROC_GPU] = (lock_gpu_addr + (offsetof(struct <API key>, flag[PROC_GPU]))); <API key>.turn = (lock_gpu_addr + (offsetof(struct <API key>, turn))); iommu->sync_lock_vars = &<API key>; return 0; } #ifdef <API key> /* * kgsl_get_sync_lock - Init Sync Lock between GPU and CPU * @mmu - Pointer to mmu device * * Return - 0 on success else error code */ static int <API key>(struct kgsl_mmu *mmu) { struct kgsl_iommu *iommu = mmu->priv; int status = 0; uint32_t lock_phy_addr = 0; uint32_t page_offset = 0; if (!<API key>() || !<API key>(mmu)) return status; /* * For 2D devices cpu side sync lock is required. For 3D device, * since we only have a single 3D core and we always ensure that * 3D core is idle while writing to IOMMU register using CPU this * lock is not required */ if (KGSL_DEVICE_2D0 == mmu->device->id || KGSL_DEVICE_2D1 == mmu->device->id) { return status; } /* Return if already initialized */ if (iommu-><API key>) return status; iommu_access_ops = <API key>(); if (iommu_access_ops && iommu_access_ops-><API key>) { lock_phy_addr = (uint32_t) iommu_access_ops-><API key>(); if (!lock_phy_addr) { iommu_access_ops = NULL; return status; } lock_phy_addr = lock_phy_addr - (uint32_t)MSM_SHARED_RAM_BASE + (uint32_t)msm_shared_ram_phys; } /* Align the physical address to PAGE boundary and store the offset */ page_offset = (lock_phy_addr & (PAGE_SIZE - 1)); lock_phy_addr = (lock_phy_addr & ~(PAGE_SIZE - 1)); iommu->sync_lock_desc.physaddr = (unsigned int)lock_phy_addr; iommu->sync_lock_offset = page_offset; iommu->sync_lock_desc.size = PAGE_ALIGN(sizeof(<API key>)); status = memdesc_sg_phys(&iommu->sync_lock_desc, iommu->sync_lock_desc.physaddr, iommu->sync_lock_desc.size); if (status) { iommu_access_ops = NULL; return status; } /* Flag Sync Lock is Initialized */ iommu-><API key> = 1; return status; } #else static int <API key>(struct kgsl_mmu *mmu) { return 0; } #endif /* * <API key> - Acquire Sync Lock between GPU and CPU * @mmu - Pointer to mmu device * @cmds - Pointer to array of commands * * Return - int - number of commands. */ inline unsigned int <API key>(struct kgsl_mmu *mmu, unsigned int *cmds) { struct kgsl_device *device = mmu->device; struct adreno_device *adreno_dev = ADRENO_DEVICE(device); struct kgsl_iommu *iommu = mmu->device->mmu.priv; struct <API key> *lock_vars = iommu->sync_lock_vars; unsigned int *start = cmds; if (!iommu-><API key>) return 0; *cmds++ = cp_type3_packet(CP_MEM_WRITE, 2); *cmds++ = lock_vars->flag[PROC_GPU]; *cmds++ = 1; cmds += <API key>(adreno_dev, cmds); *cmds++ = cp_type3_packet(CP_WAIT_REG_MEM, 5); /* MEM SPACE = memory, FUNCTION = equals */ *cmds++ = 0x13; *cmds++ = lock_vars->flag[PROC_GPU]; *cmds++ = 0x1; *cmds++ = 0x1; *cmds++ = 0x1; *cmds++ = cp_type3_packet(CP_MEM_WRITE, 2); *cmds++ = lock_vars->turn; *cmds++ = 0; cmds += <API key>(adreno_dev, cmds); *cmds++ = cp_type3_packet(CP_WAIT_REG_MEM, 5); /* MEM SPACE = memory, FUNCTION = equals */ *cmds++ = 0x13; *cmds++ = lock_vars->flag[PROC_GPU]; *cmds++ = 0x1; *cmds++ = 0x1; *cmds++ = 0x1; *cmds++ = cp_type3_packet(CP_TEST_TWO_MEMS, 3); *cmds++ = lock_vars->flag[PROC_APPS]; *cmds++ = lock_vars->turn; *cmds++ = 0; cmds += <API key>(adreno_dev, cmds); return cmds - start; } /* * <API key> - Release Sync Lock between GPU and CPU * @mmu - Pointer to mmu device * @cmds - Pointer to array of commands * * Return - int - number of commands. */ inline unsigned int <API key>(struct kgsl_mmu *mmu, unsigned int *cmds) { struct kgsl_device *device = mmu->device; struct adreno_device *adreno_dev = ADRENO_DEVICE(device); struct kgsl_iommu *iommu = mmu->device->mmu.priv; struct <API key> *lock_vars = iommu->sync_lock_vars; unsigned int *start = cmds; if (!iommu-><API key>) return 0; *cmds++ = cp_type3_packet(CP_MEM_WRITE, 2); *cmds++ = lock_vars->flag[PROC_GPU]; *cmds++ = 0; *cmds++ = cp_type3_packet(CP_WAIT_REG_MEM, 5); /* MEM SPACE = memory, FUNCTION = equals */ *cmds++ = 0x13; *cmds++ = lock_vars->flag[PROC_GPU]; *cmds++ = 0x0; *cmds++ = 0x1; *cmds++ = 0x1; cmds += <API key>(adreno_dev, cmds); return cmds - start; } /* * kgsl_get_iommu_ctxt - Get device pointer to IOMMU contexts * @mmu - Pointer to mmu device * * Get the device pointers for the IOMMU user and priv contexts of the * kgsl device * Return - 0 on success else error code */ static int kgsl_get_iommu_ctxt(struct kgsl_mmu *mmu) { struct platform_device *pdev = container_of(mmu->device->parentdev, struct platform_device, dev); struct <API key> *pdata_dev = pdev->dev.platform_data; struct kgsl_iommu *iommu = mmu->device->mmu.priv; int i, ret = 0; /* Go through the IOMMU data and get all the context devices */ if (<API key> < pdata_dev->iommu_count) { KGSL_CORE_ERR("Too many IOMMU units defined\n"); ret = -EINVAL; goto done; } for (i = 0; i < pdata_dev->iommu_count; i++) { ret = _get_iommu_ctxs(mmu, &pdata_dev->iommu_data[i], i); if (ret) break; } iommu->unit_count = pdata_dev->iommu_count; done: return ret; } /* * <API key> - Map the IOMMU regsiters in the memory descriptors * of the respective iommu units * @mmu - Pointer to mmu structure * * Return - 0 on success else error code */ static int <API key>(struct kgsl_mmu *mmu) { struct platform_device *pdev = container_of(mmu->device->parentdev, struct platform_device, dev); struct <API key> *pdata_dev = pdev->dev.platform_data; struct kgsl_iommu *iommu = mmu->device->mmu.priv; struct kgsl_iommu_unit *iommu_unit; int i = 0, ret = 0; for (; i < pdata_dev->iommu_count; i++) { struct <API key> data = pdata_dev->iommu_data[i]; iommu_unit = &iommu->iommu_units[i]; /* set up the IOMMU register map for the given IOMMU unit */ if (!data.physstart || !data.physend) { KGSL_CORE_ERR("The register range for IOMMU unit not" " specified\n"); ret = -EINVAL; goto err; } iommu_unit->reg_map.hostptr = ioremap(data.physstart, data.physend - data.physstart + 1); if (!iommu_unit->reg_map.hostptr) { KGSL_CORE_ERR("Failed to map SMMU register address " "space from %x to %x\n", data.physstart, data.physend - data.physstart + 1); ret = -ENOMEM; i goto err; } iommu_unit->reg_map.size = data.physend - data.physstart + 1; iommu_unit->reg_map.physaddr = data.physstart; ret = memdesc_sg_phys(&iommu_unit->reg_map, data.physstart, iommu_unit->reg_map.size); if (ret) goto err; if (!<API key>()) iommu_unit->iommu_halt_enable = 1; iommu_unit->ahb_base = data.physstart - mmu->device->reg_phys; } iommu->unit_count = pdata_dev->iommu_count; return ret; err: /* Unmap any mapped IOMMU regions */ for (; i >= 0; i iommu_unit = &iommu->iommu_units[i]; iounmap(iommu_unit->reg_map.hostptr); iommu_unit->reg_map.size = 0; iommu_unit->reg_map.physaddr = 0; } return ret; } /* * <API key> - Get the address of the pagetable that the * IOMMU ttbr0 register is programmed with * @mmu - Pointer to mmu * @pt - kgsl pagetable pointer that contains the IOMMU domain pointer * * Return - actual pagetable address that the ttbr0 register is programmed * with */ static phys_addr_t <API key>(struct kgsl_mmu *mmu, struct kgsl_pagetable *pt) { struct kgsl_iommu_pt *iommu_pt = pt->priv; return <API key>(iommu_pt->domain) & <API key>; } /* * <API key> - Return the ttbr0 value programmed by * iommu driver * @mmu - Pointer to mmu structure * @hostptr - Pointer to the IOMMU register map. This is used to match * the iommu device whose lsb value is to be returned * @ctx_id - The context bank whose lsb valus is to be returned * Return - returns the ttbr0 value programmed by iommu driver */ static phys_addr_t <API key>(struct kgsl_mmu *mmu, unsigned int unit_id, enum <API key> ctx_id) { struct kgsl_iommu *iommu = mmu->priv; int i, j; for (i = 0; i < iommu->unit_count; i++) { struct kgsl_iommu_unit *iommu_unit = &iommu->iommu_units[i]; for (j = 0; j < iommu_unit->dev_count; j++) if (unit_id == i && ctx_id == iommu_unit->dev[j].ctx_id) return iommu_unit->dev[j].default_ttbr0; } return 0; } static int kgsl_iommu_setstate(struct kgsl_mmu *mmu, struct kgsl_pagetable *pagetable, unsigned int context_id) { int ret = 0; if (mmu->flags & KGSL_FLAGS_STARTED) { /* page table not current, then setup mmu to use new * specified page table */ if (mmu->hwpagetable != pagetable) { unsigned int flags = 0; mmu->hwpagetable = pagetable; flags |= <API key>(mmu->hwpagetable, mmu->device->id) | <API key>; ret = kgsl_setstate(mmu, context_id, <API key> | flags); } } return ret; } /* * <API key> - map iommu registers into a pagetable * @mmu: Pointer to mmu structure * @pt: the pagetable * * To do pagetable switches from the GPU command stream, the IOMMU * registers need to be mapped into the GPU's pagetable. This function * is used differently on different targets. On 8960, the registers * are mapped into every pagetable during kgsl_setup_pt(). On * all other targets, the registers are mapped only into the second * context bank. * * Return - 0 on success else error code */ static int <API key>(struct kgsl_mmu *mmu, struct kgsl_pagetable *pt) { int status; int i = 0; struct kgsl_iommu *iommu = mmu->priv; if (!<API key>()) return 0; for (i = 0; i < iommu->unit_count; i++) { status = kgsl_mmu_map_global(pt, &(iommu->iommu_units[i].reg_map)); if (status) goto err; } /* Map Lock variables to GPU pagetable */ if (iommu-><API key>) { status = kgsl_mmu_map_global(pt, &iommu->sync_lock_desc); if (status) goto err; } return 0; err: for (i--; i >= 0; i--) kgsl_mmu_unmap(pt, &(iommu->iommu_units[i].reg_map)); return status; } static void <API key>(struct kgsl_mmu *mmu, struct kgsl_pagetable *pt) { struct kgsl_iommu *iommu = mmu->priv; int i; for (i = 0; i < iommu->unit_count; i++) kgsl_mmu_unmap(pt, &(iommu->iommu_units[i].reg_map)); if (iommu->sync_lock_desc.gpuaddr) kgsl_mmu_unmap(pt, &iommu->sync_lock_desc); } /* * <API key> - Returns the ahb address of the register * @mmu - Pointer to mmu structure * @iommu_unit - The iommu unit for which base address is requested * @ctx_id - The context ID of the IOMMU ctx * @reg - The register for which address is required * * Return - The address of register which can be used in type0 packet */ static unsigned int <API key>(struct kgsl_mmu *mmu, int iommu_unit, int ctx_id, enum kgsl_iommu_reg_map reg) { struct kgsl_iommu *iommu = mmu->priv; if (iommu->iommu_reg_list[reg].ctx_reg) return iommu->iommu_units[iommu_unit].ahb_base + iommu->iommu_reg_list[reg].reg_offset + (ctx_id << <API key>) + iommu->ctx_offset; else return iommu->iommu_units[iommu_unit].ahb_base + iommu->iommu_reg_list[reg].reg_offset; } static int kgsl_iommu_init(struct kgsl_mmu *mmu) { /* * intialize device mmu * * call this with the global lock held */ int status = 0; struct kgsl_iommu *iommu; atomic_set(&mmu->fault, 0); iommu = kzalloc(sizeof(struct kgsl_iommu), GFP_KERNEL); if (!iommu) { KGSL_CORE_ERR("kzalloc(%d) failed\n", sizeof(struct kgsl_iommu)); return -ENOMEM; } mmu->priv = iommu; status = kgsl_get_iommu_ctxt(mmu); if (status) goto done; status = <API key>(mmu); if (status) goto done; /* * IOMMU-v1 requires hardware halt support to do in stream * pagetable switching. This check assumes that if there are * multiple units, they will be matching hardware. */ mmu->pt_per_process = <API key> && (<API key>() || iommu->iommu_units[0].iommu_halt_enable); /* * For IOMMU per-process pagetables, the allocatable range * and the kernel global range must both be outside * the userspace address range. There is a 1Mb gap * between these address ranges to make overrun * detection easier. * For the shared pagetable case use 2GB and because * mirroring the CPU address space is not possible and * we're better off with extra room. */ if (mmu->pt_per_process) { #ifndef <API key> mmu->pt_base = PAGE_OFFSET; mmu->pt_size = <API key> - <API key>(mmu) - SZ_1M; mmu->use_cpu_map = true; #else mmu->pt_base = KGSL_PAGETABLE_BASE; mmu->pt_size = <API key> + <API key> - KGSL_PAGETABLE_BASE; mmu->use_cpu_map = false; #endif } else { mmu->pt_base = KGSL_PAGETABLE_BASE; #ifndef <API key> mmu->pt_size = SZ_2G; #else mmu->pt_size = <API key> + <API key> - KGSL_PAGETABLE_BASE; #endif mmu->use_cpu_map = false; } status = <API key>(mmu); if (status) goto done; iommu->iommu_reg_list = kgsl_iommuv0_reg; iommu->ctx_offset = <API key>; if (<API key>()) { iommu->iommu_reg_list = kgsl_iommuv0_reg; iommu->ctx_offset = <API key>; } else { iommu->iommu_reg_list = kgsl_iommuv1_reg; iommu->ctx_offset = <API key>; } /* A nop is required in an indirect buffer when switching * pagetables in-stream */ <API key>(mmu->device, &mmu->setstate_memory, <API key>, cp_nop_packet(1)); if (cpu_is_msm8960()) { /* * 8960 doesn't have a second context bank, so the IOMMU * registers must be mapped into every pagetable. */ iommu_ops.mmu_setup_pt = <API key>; iommu_ops.mmu_cleanup_pt = <API key>; } if (kgsl_guard_page == NULL) { kgsl_guard_page = alloc_page(GFP_KERNEL | __GFP_ZERO | __GFP_HIGHMEM); if (kgsl_guard_page == NULL) { status = -ENOMEM; goto done; } } dev_info(mmu->device->dev, "|%s| MMU type set for device is IOMMU\n", __func__); done: if (status) { kfree(iommu); mmu->priv = NULL; } return status; } /* * <API key> - Setup the initial defualtpagetable * for iommu. This function is only called once during first start, successive * start do not call this funciton. * @mmu - Pointer to mmu structure * * Create the initial defaultpagetable and setup the iommu mappings to it * Return - 0 on success else error code */ static int <API key>(struct kgsl_mmu *mmu) { int status = 0; /* If chip is not 8960 then we use the 2nd context bank for pagetable * switching on the 3D side for which a separate table is allocated */ if (<API key>()) { mmu->priv_bank_table = <API key>(mmu, <API key>); if (mmu->priv_bank_table == NULL) { status = -ENOMEM; goto err; } status = <API key>(mmu, mmu->priv_bank_table); if (status) goto err; } mmu->defaultpagetable = <API key>(mmu, KGSL_MMU_GLOBAL_PT); /* Return error if the default pagetable doesn't exist */ if (mmu->defaultpagetable == NULL) { status = -ENOMEM; goto err; } return status; err: if (mmu->priv_bank_table) { <API key>(mmu, mmu->priv_bank_table); <API key>(mmu->priv_bank_table); mmu->priv_bank_table = NULL; } if (mmu->defaultpagetable) { <API key>(mmu->defaultpagetable); mmu->defaultpagetable = NULL; } return status; } /* * <API key> - Allocates tlb entries and locks the * virtual to physical address translation of ringbuffer for 3D * device into tlb. * @mmu - Pointer to mmu structure * * Return - void */ static void <API key>(struct kgsl_mmu *mmu) { struct kgsl_device *device = mmu->device; struct adreno_device *adreno_dev = ADRENO_DEVICE(device); struct adreno_ringbuffer *rb; struct kgsl_iommu *iommu = mmu->priv; unsigned int num_tlb_entries; unsigned int tlblkcr = 0; unsigned int v2pxx = 0; unsigned int vaddr = 0; int i, j, k, l; if (!iommu-><API key>) return; rb = &adreno_dev->ringbuffer; num_tlb_entries = rb->buffer_desc.size / PAGE_SIZE; for (i = 0; i < iommu->unit_count; i++) { struct kgsl_iommu_unit *iommu_unit = &iommu->iommu_units[i]; for (j = 0; j < iommu_unit->dev_count; j++) { tlblkcr = 0; if (cpu_is_msm8960()) tlblkcr |= ((num_tlb_entries & <API key>) << <API key>); else tlblkcr |= (((num_tlb_entries * iommu_unit->dev_count) & <API key>) << <API key>); /* Do not invalidate locked entries on tlbiall flush */ tlblkcr |= ((1 & <API key>) << <API key>); tlblkcr |= ((1 & <API key>) << <API key>); tlblkcr |= ((1 & <API key>) << <API key>); /* Enable tlb locking */ tlblkcr |= ((1 & <API key>) << <API key>); <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, TLBLKCR, tlblkcr); } for (j = 0; j < iommu_unit->dev_count; j++) { /* skip locking entries for private bank on 8960 */ if (cpu_is_msm8960() && <API key> == j) continue; /* Lock the ringbuffer virtual address into tlb */ vaddr = rb->buffer_desc.gpuaddr; for (k = 0; k < num_tlb_entries; k++) { v2pxx = 0; v2pxx |= (((k + j * num_tlb_entries) & <API key>) << <API key>); v2pxx |= vaddr & (<API key> << <API key>); <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, V2PUR, v2pxx); mb(); vaddr += PAGE_SIZE; for (l = 0; l < iommu_unit->dev_count; l++) { tlblkcr = <API key>(iommu, iommu_unit, iommu_unit->dev[l].ctx_id, TLBLKCR); mb(); tlblkcr &= ~(<API key> << <API key>); tlblkcr |= (((k + 1 + (j * num_tlb_entries)) & <API key>) << <API key>); <API key>(iommu, iommu_unit, iommu_unit->dev[l].ctx_id, TLBLKCR, tlblkcr); } } } for (j = 0; j < iommu_unit->dev_count; j++) { tlblkcr = <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, TLBLKCR); mb(); /* Disable tlb locking */ tlblkcr &= ~(<API key> << <API key>); <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, TLBLKCR, tlblkcr); } } } static int kgsl_iommu_start(struct kgsl_mmu *mmu) { int status; struct kgsl_iommu *iommu = mmu->priv; int i, j; int sctlr_val = 0; struct adreno_device *adreno_dev = ADRENO_DEVICE(mmu->device); if (mmu->flags & KGSL_FLAGS_STARTED) return 0; if (mmu->defaultpagetable == NULL) { status = <API key>(mmu); if (status) return -ENOMEM; } status = <API key>(mmu); if (status) return status; /* We use the GPU MMU to control access to IOMMU registers on 8960 with * a225, hence we still keep the MMU active on 8960 */ if (cpu_is_msm8960() && KGSL_DEVICE_3D0 == mmu->device->id) { struct kgsl_mh *mh = &(mmu->device->mh); BUG_ON(iommu->iommu_units[0].reg_map.gpuaddr != 0 && mh->mpu_base > iommu->iommu_units[0].reg_map.gpuaddr); kgsl_regwrite(mmu->device, MH_MMU_CONFIG, 0x00000001); kgsl_regwrite(mmu->device, MH_MMU_MPU_END, mh->mpu_base + mh->mpu_range); } mmu->hwpagetable = mmu->defaultpagetable; status = <API key>(mmu); if (status) { mmu->hwpagetable = NULL; goto done; } status = <API key>(mmu, <API key>); if (status) { KGSL_CORE_ERR("clk enable failed\n"); goto done; } status = <API key>(mmu, <API key>); if (status) { <API key>(mmu, <API key>); KGSL_CORE_ERR("clk enable failed\n"); goto done; } /* Get the lsb value of pagetables set in the IOMMU ttbr0 register as * that value should not change when we change pagetables, so while * changing pagetables we can use this lsb value of the pagetable w/o * having to read it again */ _iommu_lock(iommu); for (i = 0; i < iommu->unit_count; i++) { struct kgsl_iommu_unit *iommu_unit = &iommu->iommu_units[i]; for (j = 0; j < iommu_unit->dev_count; j++) { /* * For IOMMU V1 do not halt IOMMU on pagefault if * FT pagefault policy is set accordingly */ if ((!<API key>()) && (!(adreno_dev->ft_pf_policy & <API key>))) { sctlr_val = <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, SCTLR); sctlr_val |= (0x1 << <API key>); <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, SCTLR, sctlr_val); } if (sizeof(phys_addr_t) > sizeof(unsigned long)) { iommu_unit->dev[j].default_ttbr0 = <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, TTBR0); } else { iommu_unit->dev[j].default_ttbr0 = <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, TTBR0); } } } <API key>(mmu); _iommu_unlock(iommu); /* For complete CFF */ kgsl_cffdump_setmem(mmu->device, mmu->setstate_memory.gpuaddr + <API key>, cp_nop_packet(1), sizeof(unsigned int)); <API key>(mmu, <API key>); <API key>(mmu, <API key>); mmu->flags |= KGSL_FLAGS_STARTED; done: return status; } static int kgsl_iommu_unmap(struct kgsl_pagetable *pt, struct kgsl_memdesc *memdesc, unsigned int *tlb_flags) { int ret = 0, lock_taken = 0; unsigned int range = memdesc->size; struct kgsl_iommu_pt *iommu_pt = pt->priv; struct kgsl_device *device = pt->mmu->device; struct kgsl_iommu *iommu = pt->mmu->priv; /* All GPU addresses as assigned are page aligned, but some functions purturb the gpuaddr with an offset, so apply the mask here to make sure we have the right address */ unsigned int gpuaddr = memdesc->gpuaddr & KGSL_MMU_ALIGN_MASK; if (range == 0 || gpuaddr == 0) return 0; if (<API key>(memdesc)) range += PAGE_SIZE; ret = iommu_unmap_range(iommu_pt->domain, gpuaddr, range); if (ret) { KGSL_CORE_ERR("iommu_unmap_range(%p, %x, %d) failed " "with err: %d\n", iommu_pt->domain, gpuaddr, range, ret); return ret; } if (!mutex_is_locked(&device->mutex) || device->mutex.owner != current) { mutex_lock(&device->mutex); lock_taken = 1; } /* If current pt then flush immediately */ if (<API key>(pt->mmu) && iommu->iommu_units[0].dev[<API key>].attached && kgsl_iommu_pt_equal(pt->mmu, pt, <API key>(pt->mmu))) <API key>(pt->mmu, <API key>); if (lock_taken) mutex_unlock(&device->mutex); return ret; } static int kgsl_iommu_map(struct kgsl_pagetable *pt, struct kgsl_memdesc *memdesc, unsigned int protflags, unsigned int *tlb_flags) { int ret; unsigned int iommu_virt_addr; struct kgsl_iommu_pt *iommu_pt = pt->priv; int size = memdesc->size; BUG_ON(NULL == iommu_pt); iommu_virt_addr = memdesc->gpuaddr; ret = iommu_map_range(iommu_pt->domain, iommu_virt_addr, memdesc->sg, size, protflags); if (ret) { KGSL_CORE_ERR("iommu_map_range(%p, %x, %p, %d, %x) err: %d\n", iommu_pt->domain, iommu_virt_addr, memdesc->sg, size, protflags, ret); return ret; } if (<API key>(memdesc)) { ret = iommu_map(iommu_pt->domain, iommu_virt_addr + size, page_to_phys(kgsl_guard_page), PAGE_SIZE, protflags & ~IOMMU_WRITE); if (ret) { KGSL_CORE_ERR("iommu_map(%p, %x, guard, %x) err: %d\n", iommu_pt->domain, iommu_virt_addr + size, protflags & ~IOMMU_WRITE, ret); /* cleanup the partial mapping */ iommu_unmap_range(iommu_pt->domain, iommu_virt_addr, size); } } return ret; } void <API key>(struct kgsl_mmu *mmu) { struct kgsl_iommu *iommu = mmu->priv; int i, j; if (atomic_read(&mmu->fault)) { for (i = 0; i < iommu->unit_count; i++) { struct kgsl_iommu_unit *iommu_unit = &iommu->iommu_units[i]; for (j = 0; j < iommu_unit->dev_count; j++) { if (iommu_unit->dev[j].fault) { <API key>(mmu, j); _iommu_lock(iommu); <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, RESUME, 1); <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, FSR, 0); <API key>(mmu, j); _iommu_unlock(iommu); iommu_unit->dev[j].fault = 0; } } } atomic_set(&mmu->fault, 0); } } static void kgsl_iommu_stop(struct kgsl_mmu *mmu) { /* * stop device mmu * * call this with the global lock held */ if (mmu->flags & KGSL_FLAGS_STARTED) { /* detach iommu attachment */ <API key>(mmu); mmu->hwpagetable = NULL; mmu->flags &= ~KGSL_FLAGS_STARTED; <API key>(mmu); } /* switch off MMU clocks and cancel any events it has queued */ kgsl_cancel_events(mmu->device, mmu); } static int kgsl_iommu_close(struct kgsl_mmu *mmu) { struct kgsl_iommu *iommu = mmu->priv; int i; if (mmu->priv_bank_table != NULL) { <API key>(mmu, mmu->priv_bank_table); <API key>(mmu->priv_bank_table); } if (mmu->defaultpagetable != NULL) <API key>(mmu->defaultpagetable); for (i = 0; i < iommu->unit_count; i++) { struct kgsl_memdesc *reg_map = &iommu->iommu_units[i].reg_map; if (reg_map->hostptr) iounmap(reg_map->hostptr); kgsl_sg_free(reg_map->sg, reg_map->sglen); reg_map->priv &= ~KGSL_MEMDESC_GLOBAL; } /* clear IOMMU GPU CPU sync structures */ kgsl_sg_free(iommu->sync_lock_desc.sg, iommu->sync_lock_desc.sglen); memset(&iommu->sync_lock_desc, 0, sizeof(iommu->sync_lock_desc)); iommu->sync_lock_vars = NULL; kfree(iommu); if (kgsl_guard_page != NULL) { __free_page(kgsl_guard_page); kgsl_guard_page = NULL; } return 0; } static phys_addr_t <API key>(struct kgsl_mmu *mmu) { phys_addr_t pt_base; struct kgsl_iommu *iommu = mmu->priv; /* We cannot enable or disable the clocks in interrupt context, this function is called from interrupt context if there is an axi error */ if (in_interrupt()) return 0; /* Return the current pt base by reading IOMMU pt_base register */ <API key>(mmu, <API key>); pt_base = <API key>(iommu, (&iommu->iommu_units[0]), <API key>, TTBR0); <API key>(mmu, <API key>); return pt_base & <API key>; } /* * <API key> - Change the IOMMU pagetable or flush IOMMU tlb * of the primary context bank * @mmu - Pointer to mmu structure * @flags - Flags indicating whether pagetable has to chnage or tlb is to be * flushed or both * * Based on flags set the new pagetable fo the IOMMU unit or flush it's tlb or * do both by doing direct register writes to the IOMMu registers through the * cpu * Return - void */ static int <API key>(struct kgsl_mmu *mmu, uint32_t flags) { struct kgsl_iommu *iommu = mmu->priv; int temp; int i; int ret = 0; phys_addr_t pt_base = <API key>(mmu, mmu->hwpagetable); phys_addr_t pt_val; ret = <API key>(mmu, <API key>); if (ret) { KGSL_DRV_ERR(mmu->device, "Failed to enable iommu clocks\n"); return ret; } /* For v0 SMMU GPU needs to be idle for tlb invalidate as well */ if (<API key>()) { ret = kgsl_idle(mmu->device); if (ret) return ret; } /* Acquire GPU-CPU sync Lock here */ _iommu_lock(iommu); if (flags & <API key>) { if (!<API key>()) { ret = kgsl_idle(mmu->device); if (ret) goto unlock; } for (i = 0; i < iommu->unit_count; i++) { /* get the lsb value which should not change when * changing ttbr0 */ pt_val = <API key>(mmu, i, <API key>); pt_base &= <API key>; pt_val &= ~<API key>; pt_val |= pt_base; if (sizeof(phys_addr_t) > sizeof(unsigned long)) { <API key>(iommu, (&iommu->iommu_units[i]), <API key>, TTBR0, pt_val); } else { <API key>(iommu, (&iommu->iommu_units[i]), <API key>, TTBR0, pt_val); } mb(); temp = <API key>(iommu, (&iommu->iommu_units[i]), <API key>, TTBR0); } } /* Flush tlb */ if (flags & <API key>) { unsigned long wait_for_flush; for (i = 0; i < iommu->unit_count; i++) { <API key>(iommu, (&iommu->iommu_units[i]), <API key>, TLBIALL, 1); mb(); /* * Wait for flush to complete by polling the flush * status bit of TLBSTATUS register for not more than * 2 s. After 2s just exit, at that point the SMMU h/w * may be stuck and will eventually cause GPU to hang * or bring the system down. */ if (!<API key>()) { wait_for_flush = jiffies + msecs_to_jiffies(2000); <API key>(iommu, (&iommu->iommu_units[i]), <API key>, TLBSYNC, 0); while (<API key>(iommu, (&iommu->iommu_units[i]), <API key>, TLBSTATUS) & (<API key>)) { if (time_after(jiffies, wait_for_flush)) { KGSL_DRV_ERR(mmu->device, "Wait limit reached for IOMMU tlb flush\n"); break; } cpu_relax(); } } } } unlock: /* Release GPU-CPU sync Lock here */ _iommu_unlock(iommu); /* Disable smmu clock */ <API key>(mmu, <API key>); return ret; } /* * <API key> - Returns the gpu address of IOMMU regsiter * @mmu - Pointer to mmu structure * @iommu_unit - The iommu unit for which base address is requested * @ctx_id - The context ID of the IOMMU ctx * @reg - The register for which address is required * * Return - The gpu address of register which can be used in type3 packet */ static unsigned int <API key>(struct kgsl_mmu *mmu, int iommu_unit, int ctx_id, int reg) { struct kgsl_iommu *iommu = mmu->priv; if (<API key> == reg) return iommu->iommu_units[iommu_unit].reg_map.gpuaddr; if (iommu->iommu_reg_list[reg].ctx_reg) return iommu->iommu_units[iommu_unit].reg_map.gpuaddr + iommu->iommu_reg_list[reg].reg_offset + (ctx_id << <API key>) + iommu->ctx_offset; else return iommu->iommu_units[iommu_unit].reg_map.gpuaddr + iommu->iommu_reg_list[reg].reg_offset; } /* * <API key> - Returns whether IOMMU halt command is * supported * @mmu - Pointer to mmu structure * @iommu_unit - The iommu unit for which the property is requested */ static int <API key>(struct kgsl_mmu *mmu, int iommu_unit) { struct kgsl_iommu *iommu = mmu->priv; return iommu->iommu_units[iommu_unit].iommu_halt_enable; } static int <API key>(struct kgsl_mmu *mmu) { struct kgsl_iommu *iommu = mmu->priv; return iommu->unit_count; } /* * <API key>() - Set the pagefault policy for IOMMU * @mmu: Pointer to mmu structure * @pf_policy: The pagefault polict to set * * Check if the new policy indicated by pf_policy is same as current * policy, if same then return else set the policy */ static int <API key>(struct kgsl_mmu *mmu, unsigned int pf_policy) { int i, j; struct kgsl_iommu *iommu = mmu->priv; struct adreno_device *adreno_dev = ADRENO_DEVICE(mmu->device); int ret = 0; unsigned int sctlr_val; if ((adreno_dev->ft_pf_policy & <API key>) == (pf_policy & <API key>)) return ret; if (<API key>()) return ret; ret = <API key>(mmu, <API key>); if (ret) { KGSL_DRV_ERR(mmu->device, "Failed to enable iommu clocks\n"); return ret; } ret = <API key>(mmu, <API key>); if (ret) { KGSL_DRV_ERR(mmu->device, "Failed to enable iommu clocks\n"); <API key>(mmu, 0, false); return ret; } /* Need to idle device before changing options */ ret = mmu->device->ftbl->idle(mmu->device); if (ret) { <API key>(mmu, 0, false); return ret; } for (i = 0; i < iommu->unit_count; i++) { struct kgsl_iommu_unit *iommu_unit = &iommu->iommu_units[i]; for (j = 0; j < iommu_unit->dev_count; j++) { sctlr_val = <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, SCTLR); if (pf_policy & <API key>) sctlr_val &= ~(0x1 << <API key>); else sctlr_val |= (0x1 << <API key>); <API key>(iommu, iommu_unit, iommu_unit->dev[j].ctx_id, SCTLR, sctlr_val); } } <API key>(mmu, 0, false); return ret; } struct kgsl_mmu_ops iommu_ops = { .mmu_init = kgsl_iommu_init, .mmu_close = kgsl_iommu_close, .mmu_start = kgsl_iommu_start, .mmu_stop = kgsl_iommu_stop, .mmu_setstate = kgsl_iommu_setstate, .mmu_device_setstate = <API key>, .mmu_pagefault = NULL, .<API key> = <API key>, .<API key> = <API key>, .mmu_enable_clk = <API key>, .mmu_disable_clk = <API key>, .<API key> = <API key>, .<API key> = <API key>, .mmu_get_reg_gpuaddr = <API key>, .mmu_get_reg_ahbaddr = <API key>, .<API key> = <API key>, .mmu_pt_equal = kgsl_iommu_pt_equal, .<API key> = <API key>, .<API key> = <API key>, /* These callbacks will be set on some chipsets */ .mmu_setup_pt = NULL, .mmu_cleanup_pt = NULL, .mmu_sync_lock = <API key>, .mmu_sync_unlock = <API key>, .mmu_set_pf_policy = <API key>, }; struct kgsl_mmu_pt_ops iommu_pt_ops = { .mmu_map = kgsl_iommu_map, .mmu_unmap = kgsl_iommu_unmap, .<API key> = <API key>, .<API key> = <API key>, };
// 20020717 gdr // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // with this library; see the file COPYING3. If not see // Test slice class invariants #include <valarray> #include <cstdlib> #include <testsuite_hooks.h> bool construction(std::size_t start, std::size_t size, std::size_t stride) { std::slice s(start, size, stride); return s.start() == start && s.size() == size && s.stride() == stride; } bool copy(std::size_t start, std::size_t size, std::size_t stride) { std::slice s(start, size, stride); std::slice t = s; return t.start() == start && t.size() == size && t.stride() == stride; } bool assignment(std::size_t start, std::size_t size, std::size_t stride) { std::slice s(start, size, stride); std::slice t; t = s; return t.start() == start && t.size() == size && t.stride() == stride; } int main() { std::srand(20020717); using std::rand; VERIFY(construction(rand(), rand(), rand())); VERIFY(copy(rand(), rand(), rand())); VERIFY(assignment(rand(), rand(), rand())); return 0; }
<! * Asterisk-GUI - an Asterisk configuration interface * * Set Date on the Digium Appliance - AA50 * * Copyright (C) 2007-2008, Digium, Inc. * * Pari Nannapaneni <pari@digium.com> * * See http: * the Asterisk project. Please do not directly contact * any of the maintainers of this project for assistance; * the project provides a web site, mailing lists and IRC * channels for your use. * * This program is free software, distributed under the terms of * the GNU General Public License Version 2. See the LICENSE file * at the top of the source tree. * * <html> <head> <title>Update Date & Time</title> <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" /> <link href="stylesheets/schwing.css" media="all" rel="Stylesheet" type="text/css" /> <style type="text/css"></style> </head> <body> <div class="iframeTitleBar"> Update Date & Time <span style="cursor: pointer; cursor: hand;" onclick="window.location.reload();" >&nbsp;<img src="images/refresh.png" title=" Refresh " border=0 >&nbsp;</span> </div> <div class='lite_Heading'> Update Date & Time </div> <table width=700 border=0 align=left> <tr> <td align=right><B>NTP server :</B></td> <td> <span id='NTPSERVER'></span> &nbsp;&nbsp;&nbsp;<A href='#' class='splbutton' title='Edit NTP server' onclick="parent.miscFunctions.click_panel('networking.html');"><B>Edit</B></A> </td> </tr> <tr> <td height=15></td><td></td></tr> <tr> <td valign=top align=right><B>Current System Date :</B></td> <td id='current_date'></td> </tr> <tr class='lite'> <td valign=top align=right><B>Current System Date in Local Time :</B></td> <td id='current_date_local'></td> </tr> <tr> <td height=15></td><td></td></tr> <tr> <td valign=top align=right> <B>Set New Date & Time :</B><BR> <span class='lite'>Enter Date & Time in your Local time&nbsp;&nbsp;</span> </td> <td> <TABLE cellpadding=6 cellspacing=1 border=0> <TR> <TD width=70 align=right>Date </TD> <TD><input size=10 id="date_day"></TD> </TR> <TR> <TD width=70 align=right>Time</TD> <TD> <!-- Time --> <select id="hod"></select>: <select id="minute"></select>&nbsp; <select id="ampm"> <option value="AM">AM</option> <option value="PM">PM</option> </select> <!-- Time --> </TD> </TR> <TR> <TD colspan=2 align=center> <span class='guiButton' onclick='update_systemdate();'>Update</span> </TD> </TR> </TABLE> </td> </tr> </table> <script src="js/jquery.js"></script> <script src="js/astman.js"></script> <script src="js/jquery.tooltip.js"></script> <script src="js/jquery.date_input.js"></script> <script> function localajaxinit(){ top.document.title = 'Set Date & Time' ; parent.ASTGUI.dialog.waitWhile('Loading...'); $("#date_day").date_input(); (function(){ var x; var hod = _$('hod'); var minute = _$('minute'); for(var i=1; i < 13; i++){ x = i.addZero(); ASTGUI.selectbox.append(hod, x , x); } for(var i=0; i < 60; i++){ x = i.addZero(); ASTGUI.selectbox.append(minute, x , x); } hod.selectedIndex = -1; minute.selectedIndex = -1; })(); (function(){ var c = context2json({ filename:'networking.conf' , context : 'general' , usf:1 }); _$('NTPSERVER').innerHTML = (c && c['NTP_ADDRESS']) || '&nbsp;&nbsp; })(); ASTGUI.systemCmdWithOutput( "date ", function(output){ _$('current_date').innerHTML = '&nbsp;&nbsp;' + output.bold_X('UTC') ; _$('current_date_local').innerHTML = '&nbsp;&nbsp;' + ASTGUI.toLocalTime(output); parent.ASTGUI.dialog.hide(); }); }; function update_systemdate(){ parent.ASTGUI.dialog.waitWhile('Updating Date & Time ...'); try{ // convert local time to UTC var lt_minutes = _$('minute').value ; // 0 to 59 var date_day = _$("date_day").value ; if( !date_day || (_$('hod').selectedIndex == -1 ) || ( _$('minute').selectedIndex == -1) ){ parent.ASTGUI.dialog.hide(); return; } var date_day_split = date_day.split(' '); var lt_month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].indexOf(date_day_split[1]); // 0 to 11 var lt_dom = date_day_split[0] ; // 1 to 31 lt_dom = lt_dom.addZero() ; var lt_year = date_day_split[2] ; // 2007 // prepare commands to set the date if( _$('ampm').value == "AM" ){ var lt_hours = (_$('hod').value == "12" )? "00" : _$('hod').value; }else if( _$('ampm').value == "PM"){ var lt_hours = ( _$('hod').value == "12") ? parseInt( _$('hod').value) : parseInt( _$('hod').value) + 12 ; } var lt = new Date(); lt.setFullYear ( lt_year, lt_month, lt_dom ); lt.setHours ( lt_hours, lt_minutes ); var utc_hours = lt.getUTCHours(); // 0 to 23 var utc_minutes = lt.getUTCMinutes(); // 0 to 59 var utc_month = lt.getUTCMonth(); // 0 to 11 var utc_dom = lt.getUTCDate(); // 1 to 31 var utc_year = lt.getUTCFullYear() ; // 2007 if (utc_month < 10) { utc_month = "0"+ String(utc_month+1); }else{utc_month = String(utc_month+1) ;} if (utc_dom < 10) { utc_dom = "0"+ String(utc_dom) ; } if (utc_hours < 10) { utc_hours = "0"+ String(utc_hours) ; } if (utc_minutes < 10) { utc_minutes = "0"+ String(utc_minutes) ; } var newdate = utc_month + utc_dom + utc_hours + utc_minutes + utc_year ; }catch(err){ parent.ASTGUI.dialog.hide(); return false; } parent.ASTGUI.systemCmd( "date -s " + newdate , function(){ parent.ASTGUI.dialog.hide(); var after = function(){ alert("You will be now logged out of the gui.\n Please login again !!"); var f = makeSyncRequest({ action :'logoff'}); top.window.location.reload(); }; ASTGUI.feedback( { msg:'updated date & time', showfor:2 }); setTimeout( after, 1000 ); }); } </script> </body> </html>
/* * UBI input/output unit. * * This unit provides a uniform way to work with all kinds of the underlying * MTD devices. It also implements handy functions for reading and writing UBI * headers. * * We are trying to have a paranoid mindset and not to trust to what we read * from the flash media in order to be more secure and robust. So this unit * validates every single header it reads from the flash media. * * Some words about how the eraseblock headers are stored. * * The erase counter header is always stored at offset zero. By default, the * VID header is stored after the EC header at the closest aligned offset * (i.e. aligned to the minimum I/O unit size). Data starts next to the VID * header at the closest aligned offset. But this default layout may be * changed. For example, for different reasons (e.g., optimization) UBI may be * asked to put the VID header at further offset, and even at an unaligned * offset. Of course, if the offset of the VID header is unaligned, UBI adds * proper padding in front of it. Data offset may also be changed but it has to * be aligned. * * About minimal I/O units. In general, UBI assumes flash device model where * there is only one minimal I/O unit size. E.g., in case of NOR flash it is 1, * in case of NAND flash it is a NAND page, etc. This is reported by MTD in the * @ubi->mtd->writesize field. But as an exception, UBI admits of using another * (smaller) minimal I/O unit size for EC and VID headers to make it possible * to do different optimizations. * * This is extremely useful in case of NAND flashes which admit of several * write operations to one NAND page. In this case UBI can fit EC and VID * headers at one NAND page. Thus, UBI may use "sub-page" size as the minimal * I/O unit for the headers (the @ubi->hdrs_min_io_size field). But it still * reports NAND page size (@ubi->min_io_size) as a minimal I/O unit for the UBI * users. * * Example: some Samsung NANDs with 2KiB pages allow 4x 512-byte writes, so * although the minimal I/O unit is 2K, UBI uses 512 bytes for EC and VID * headers. * * Q: why not just to treat sub-page as a minimal I/O unit of this flash * device, e.g., make @ubi->min_io_size = 512 in the example above? * * A: because when writing a sub-page, MTD still writes a full 2K page but the * bytes which are no relevant to the sub-page are 0xFF. So, basically, writing * 4x512 sub-pages is 4 times slower then writing one 2KiB NAND page. Thus, we * prefer to use sub-pages only for EV and VID headers. * * As it was noted above, the VID header may start at a non-aligned offset. * For example, in case of a 2KiB page NAND flash with a 512 bytes sub-page, * the VID header may reside at offset 1984 which is the last 64 bytes of the * last sub-page (EC header is always at offset zero). This causes some * difficulties when reading and writing VID headers. * * Suppose we have a 64-byte buffer and we read a VID header at it. We change * the data and want to write this VID header out. As we can only write in * 512-byte chunks, we have to allocate one more buffer and copy our VID header * to offset 448 of this buffer. * * The I/O unit does the following trick in order to avoid this extra copy. * It always allocates a @ubi->vid_hdr_alsize bytes buffer for the VID header * and returns a pointer to offset @ubi->vid_hdr_shift of this buffer. When the * VID header is being written out, it shifts the VID header pointer back and * writes the whole sub-page. */ #include <linux/crc32.h> #include <linux/err.h> #include "ubi.h" #ifdef <API key> static int <API key>(const struct ubi_device *ubi, int pnum); static int <API key>(const struct ubi_device *ubi, int pnum); static int <API key>(const struct ubi_device *ubi, int pnum, const struct ubi_ec_hdr *ec_hdr); static int <API key>(const struct ubi_device *ubi, int pnum); static int <API key>(const struct ubi_device *ubi, int pnum, const struct ubi_vid_hdr *vid_hdr); static int <API key>(struct ubi_device *ubi, int pnum, int offset, int len); #else #define <API key>(ubi, pnum) 0 #define <API key>(ubi, pnum) 0 #define <API key>(ubi, pnum, ec_hdr) 0 #define <API key>(ubi, pnum) 0 #define <API key>(ubi, pnum, vid_hdr) 0 #define <API key>(ubi, pnum, offset, len) 0 #endif /** * ubi_io_read - read data from a physical eraseblock. * @ubi: UBI device description object * @buf: buffer where to store the read data * @pnum: physical eraseblock number to read from * @offset: offset within the physical eraseblock from where to read * @len: how many bytes to read * * This function reads data from offset @offset of physical eraseblock @pnum * and stores the read data in the @buf buffer. The following return codes are * possible: * * o %0 if all the requested data were successfully read; * o %UBI_IO_BITFLIPS if all the requested data were successfully read, but * correctable bit-flips were detected; this is harmless but may indicate * that this eraseblock may become bad soon (but do not have to); * o %-EBADMSG if the MTD subsystem reported about data integrity problems, for * example it can be an ECC error in case of NAND; this most probably means * that the data is corrupted; * o %-EIO if some I/O error occurred; * o other negative error codes in case of other errors. */ int ubi_io_read(const struct ubi_device *ubi, void *buf, int pnum, int offset, int len) { int err, retries = 0; size_mtd_t read; loff_mtd_t addr; dbg_io("read %d bytes from PEB %d:%d", len, pnum, offset); ubi_assert(pnum >= 0 && pnum < ubi->peb_count); ubi_assert(offset >= 0 && offset + len <= ubi->peb_size); ubi_assert(len > 0); err = <API key>(ubi, pnum); if (err) return err > 0 ? -EINVAL : err; addr = (loff_mtd_t)pnum * ubi->peb_size + offset; retry: err = ubi->mtd->read(ubi->mtd, addr, len, &read, buf); if (err) { if (err == -EUCLEAN) { /* * -EUCLEAN is reported if there was a bit-flip which * was corrected, so this is harmless. */ ubi_msg("fixable bit-flip detected at PEB %d", pnum); ubi_assert(len == read); return UBI_IO_BITFLIPS; } if (read != len && retries++ < UBI_IO_RETRIES) { dbg_io("error %d while reading %d bytes from PEB %d:%d, " "read only %lld bytes, retry", err, len, pnum, offset, read); yield(); goto retry; } ubi_err("error %d while reading %d bytes from PEB %d:%d, " "read %lld bytes", err, len, pnum, offset, read); ubi_dbg_dump_stack(); /* * The driver should never return -EBADMSG if it failed to read * all the requested data. But some buggy drivers might do * this, so we change it to -EIO. */ if (read != len && err == -EBADMSG) { ubi_assert(0); err = -EIO; } } else { ubi_assert(len == read); if (ubi_dbg_is_bitflip()) { dbg_msg("bit-flip (emulated)"); err = UBI_IO_BITFLIPS; } } return err; } /** * ubi_io_write - write data to a physical eraseblock. * @ubi: UBI device description object * @buf: buffer with the data to write * @pnum: physical eraseblock number to write to * @offset: offset within the physical eraseblock where to write * @len: how many bytes to write * * This function writes @len bytes of data from buffer @buf to offset @offset * of physical eraseblock @pnum. If all the data were successfully written, * zero is returned. If an error occurred, this function returns a negative * error code. If %-EIO is returned, the physical eraseblock most probably went * bad. * * Note, in case of an error, it is possible that something was still written * to the flash media, but may be some garbage. */ int ubi_io_write(struct ubi_device *ubi, const void *buf, int pnum, int offset, int len) { int err; size_mtd_t written; loff_mtd_t addr; dbg_io("write %d bytes to PEB %d:%d", len, pnum, offset); ubi_assert(pnum >= 0 && pnum < ubi->peb_count); ubi_assert(offset >= 0 && offset + len <= ubi->peb_size); ubi_assert(offset % ubi->hdrs_min_io_size == 0); ubi_assert(len > 0 && len % ubi->hdrs_min_io_size == 0); if (ubi->ro_mode) { ubi_err("read-only mode"); return -EROFS; } /* The below has to be compiled out if paranoid checks are disabled */ err = <API key>(ubi, pnum); if (err) return err > 0 ? -EINVAL : err; /* The area we are writing to has to contain all 0xFF bytes */ err = <API key>(ubi, pnum, offset, len); if (err) return err > 0 ? -EINVAL : err; if (offset >= ubi->leb_start) { /* * We write to the data area of the physical eraseblock. Make * sure it has valid EC and VID headers. */ err = <API key>(ubi, pnum); if (err) return err > 0 ? -EINVAL : err; err = <API key>(ubi, pnum); if (err) return err > 0 ? -EINVAL : err; } if (<API key>()) { dbg_err("cannot write %d bytes to PEB %d:%d " "(emulated)", len, pnum, offset); ubi_dbg_dump_stack(); return -EIO; } addr = (loff_mtd_t)pnum * ubi->peb_size + offset; err = ubi->mtd->write(ubi->mtd, addr, len, &written, buf); if (err) { ubi_err("error %d while writing %d bytes to PEB %d:%d, written" " %lld bytes", err, len, pnum, offset, written); ubi_dbg_dump_stack(); } else ubi_assert(written == len); return err; } /** * erase_callback - MTD erasure call-back. * @ei: MTD erase information object. * * Note, even though MTD erase interface is asynchronous, all the current * implementations are synchronous anyway. */ static void erase_callback(struct erase_info *ei) { <API key>((wait_queue_head_t *)ei->priv); } /** * do_sync_erase - synchronously erase a physical eraseblock. * @ubi: UBI device description object * @pnum: the physical eraseblock number to erase * * This function synchronously erases physical eraseblock @pnum and returns * zero in case of success and a negative error code in case of failure. If * %-EIO is returned, the physical eraseblock most probably went bad. */ static int do_sync_erase(struct ubi_device *ubi, int pnum) { int err, retries = 0; struct erase_info ei; wait_queue_head_t wq; dbg_io("erase PEB %d", pnum); retry: init_waitqueue_head(&wq); memset(&ei, 0, sizeof(struct erase_info)); ei.mtd = ubi->mtd; ei.addr = (loff_mtd_t)pnum * ubi->peb_size; ei.len = ubi->peb_size; ei.callback = erase_callback; ei.priv = (unsigned long)&wq; err = ubi->mtd->erase(ubi->mtd, &ei); if (err) { if (retries++ < UBI_IO_RETRIES) { dbg_io("error %d while erasing PEB %d, retry", err, pnum); yield(); goto retry; } ubi_err("cannot erase PEB %d, error %d", pnum, err); ubi_dbg_dump_stack(); return err; } err = <API key>(wq, ei.state == MTD_ERASE_DONE || ei.state == MTD_ERASE_FAILED); if (err) { ubi_err("interrupted PEB %d erasure", pnum); return -EINTR; } if (ei.state == MTD_ERASE_FAILED) { if (retries++ < UBI_IO_RETRIES) { dbg_io("error while erasing PEB %d, retry", pnum); yield(); goto retry; } ubi_err("cannot erase PEB %d", pnum); ubi_dbg_dump_stack(); return -EIO; } err = <API key>(ubi, pnum, 0, ubi->peb_size); if (err) return err > 0 ? -EINVAL : err; if (<API key>() && !err) { dbg_err("cannot erase PEB %d (emulated)", pnum); return -EIO; } return 0; } /** * check_pattern - check if buffer contains only a certain byte pattern. * @buf: buffer to check * @patt: the pattern to check * @size: buffer size in bytes * * This function returns %1 in there are only @patt bytes in @buf, and %0 if * something else was also found. */ static int check_pattern(const void *buf, uint8_t patt, int size) { int i; for (i = 0; i < size; i++) if (((const uint8_t *)buf)[i] != patt) return 0; return 1; } /* Patterns to write to a physical eraseblock when torturing it */ static uint8_t patterns[] = {0xa5, 0x5a, 0x0}; /** * torture_peb - test a supposedly bad physical eraseblock. * @ubi: UBI device description object * @pnum: the physical eraseblock number to test * * This function returns %-EIO if the physical eraseblock did not pass the * test, a positive number of erase operations done if the test was * successfully passed, and other negative error codes in case of other errors. */ static int torture_peb(struct ubi_device *ubi, int pnum) { int err, i, patt_count; patt_count = ARRAY_SIZE(patterns); ubi_assert(patt_count > 0); mutex_lock(&ubi->buf_mutex); for (i = 0; i < patt_count; i++) { err = do_sync_erase(ubi, pnum); if (err) goto out; /* Make sure the PEB contains only 0xFF bytes */ err = ubi_io_read(ubi, ubi->peb_buf1, pnum, 0, ubi->peb_size); if (err) goto out; err = check_pattern(ubi->peb_buf1, 0xFF, ubi->peb_size); if (err == 0) { ubi_err("erased PEB %d, but a non-0xFF byte found", pnum); err = -EIO; goto out; } /* Write a pattern and check it */ memset(ubi->peb_buf1, patterns[i], ubi->peb_size); err = ubi_io_write(ubi, ubi->peb_buf1, pnum, 0, ubi->peb_size); if (err) goto out; memset(ubi->peb_buf1, ~patterns[i], ubi->peb_size); err = ubi_io_read(ubi, ubi->peb_buf1, pnum, 0, ubi->peb_size); if (err) goto out; err = check_pattern(ubi->peb_buf1, patterns[i], ubi->peb_size); if (err == 0) { ubi_err("pattern %x checking failed for PEB %d", patterns[i], pnum); err = -EIO; goto out; } } err = patt_count; out: mutex_unlock(&ubi->buf_mutex); if (err == UBI_IO_BITFLIPS || err == -EBADMSG) { /* * If a bit-flip or data integrity error was detected, the test * has not passed because it happened on a freshly erased * physical eraseblock which means something is wrong with it. */ ubi_err("read problems on freshly erased PEB %d, must be bad", pnum); err = -EIO; } return err; } /** * ubi_io_sync_erase - synchronously erase a physical eraseblock. * @ubi: UBI device description object * @pnum: physical eraseblock number to erase * @torture: if this physical eraseblock has to be tortured * * This function synchronously erases physical eraseblock @pnum. If @torture * flag is not zero, the physical eraseblock is checked by means of writing * different patterns to it and reading them back. If the torturing is enabled, * the physical eraseblock is erased more then once. * * This function returns the number of erasures made in case of success, %-EIO * if the erasure failed or the torturing test failed, and other negative error * codes in case of other errors. Note, %-EIO means that the physical * eraseblock is bad. */ int ubi_io_sync_erase(struct ubi_device *ubi, int pnum, int torture) { int err, ret = 0; ubi_assert(pnum >= 0 && pnum < ubi->peb_count); err = <API key>(ubi, pnum); if (err != 0) return err > 0 ? -EINVAL : err; if (ubi->ro_mode) { ubi_err("read-only mode"); return -EROFS; } if (torture) { ret = torture_peb(ubi, pnum); if (ret < 0) return ret; } err = do_sync_erase(ubi, pnum); if (err) return err; return ret + 1; } /** * ubi_io_is_bad - check if a physical eraseblock is bad. * @ubi: UBI device description object * @pnum: the physical eraseblock number to check * * This function returns a positive number if the physical eraseblock is bad, * zero if not, and a negative error code if an error occurred. */ int ubi_io_is_bad(const struct ubi_device *ubi, int pnum) { struct mtd_info *mtd = ubi->mtd; ubi_assert(pnum >= 0 && pnum < ubi->peb_count); if (ubi->bad_allowed) { int ret; ret = mtd->block_isbad(mtd, (loff_mtd_t)pnum * ubi->peb_size); if (ret < 0) ubi_err("error %d while checking if PEB %d is bad", ret, pnum); else if (ret) dbg_io("PEB %d is bad", pnum); return ret; } return 0; } /** * ubi_io_mark_bad - mark a physical eraseblock as bad. * @ubi: UBI device description object * @pnum: the physical eraseblock number to mark * * This function returns zero in case of success and a negative error code in * case of failure. */ int ubi_io_mark_bad(const struct ubi_device *ubi, int pnum) { int err; struct mtd_info *mtd = ubi->mtd; ubi_assert(pnum >= 0 && pnum < ubi->peb_count); if (ubi->ro_mode) { ubi_err("read-only mode"); return -EROFS; } if (!ubi->bad_allowed) return 0; err = mtd->block_markbad(mtd, (loff_mtd_t)pnum * ubi->peb_size); if (err) ubi_err("cannot mark PEB %d bad, error %d", pnum, err); return err; } /** * validate_ec_hdr - validate an erase counter header. * @ubi: UBI device description object * @ec_hdr: the erase counter header to check * * This function returns zero if the erase counter header is OK, and %1 if * not. */ static int validate_ec_hdr(const struct ubi_device *ubi, const struct ubi_ec_hdr *ec_hdr) { long long ec; int vid_hdr_offset, leb_start; ec = be64_to_cpu(ec_hdr->ec); vid_hdr_offset = be32_to_cpu(ec_hdr->vid_hdr_offset); leb_start = be32_to_cpu(ec_hdr->data_offset); if (ec_hdr->version != UBI_VERSION) { ubi_err("node with incompatible UBI version found: " "this UBI version is %d, image version is %d", UBI_VERSION, (int)ec_hdr->version); goto bad; } if (vid_hdr_offset != ubi->vid_hdr_offset) { ubi_err("bad VID header offset %d, expected %d", vid_hdr_offset, ubi->vid_hdr_offset); goto bad; } if (leb_start != ubi->leb_start) { ubi_err("bad data offset %d, expected %d", leb_start, ubi->leb_start); goto bad; } if (ec < 0 || ec > <API key>) { ubi_err("bad erase counter %lld", ec); goto bad; } return 0; bad: ubi_err("bad EC header"); ubi_dbg_dump_ec_hdr(ec_hdr); ubi_dbg_dump_stack(); return 1; } /** * ubi_io_read_ec_hdr - read and check an erase counter header. * @ubi: UBI device description object * @pnum: physical eraseblock to read from * @ec_hdr: a &struct ubi_ec_hdr object where to store the read erase counter * header * @verbose: be verbose if the header is corrupted or was not found * * This function reads erase counter header from physical eraseblock @pnum and * stores it in @ec_hdr. This function also checks CRC checksum of the read * erase counter header. The following codes may be returned: * * o %0 if the CRC checksum is correct and the header was successfully read; * o %UBI_IO_BITFLIPS if the CRC is correct, but bit-flips were detected * and corrected by the flash driver; this is harmless but may indicate that * this eraseblock may become bad soon (but may be not); * o %UBI_IO_BAD_EC_HDR if the erase counter header is corrupted (a CRC error); * o %UBI_IO_PEB_EMPTY if the physical eraseblock is empty; * o a negative error code in case of failure. */ int ubi_io_read_ec_hdr(struct ubi_device *ubi, int pnum, struct ubi_ec_hdr *ec_hdr, int verbose) { int err, read_err = 0; uint32_t crc, magic, hdr_crc; dbg_io("read EC header from PEB %d", pnum); ubi_assert(pnum >= 0 && pnum < ubi->peb_count); if (UBI_IO_DEBUG) verbose = 1; err = ubi_io_read(ubi, ec_hdr, pnum, 0, UBI_EC_HDR_SIZE); if (err) { if (err != UBI_IO_BITFLIPS && err != -EBADMSG) return err; /* * We read all the data, but either a correctable bit-flip * occurred, or MTD reported about some data integrity error, * like an ECC error in case of NAND. The former is harmless, * the later may mean that the read data is corrupted. But we * have a CRC check-sum and we will detect this. If the EC * header is still OK, we just report this as there was a * bit-flip. */ read_err = err; } magic = be32_to_cpu(ec_hdr->magic); if (magic != UBI_EC_HDR_MAGIC) { /* * The magic field is wrong. Let's check if we have read all * 0xFF. If yes, this physical eraseblock is assumed to be * empty. * * But if there was a read error, we do not test it for all * 0xFFs. Even if it does contain all 0xFFs, this error * indicates that something is still wrong with this physical * eraseblock and we anyway cannot treat it as empty. */ if (read_err != -EBADMSG && check_pattern(ec_hdr, 0xFF, UBI_EC_HDR_SIZE)) { /* The physical eraseblock is supposedly empty */ /* * The below is just a paranoid check, it has to be * compiled out if paranoid checks are disabled. */ err = <API key>(ubi, pnum, 0, ubi->peb_size); if (err) return err > 0 ? UBI_IO_BAD_EC_HDR : err; if (verbose) ubi_warn("no EC header found at PEB %d, " "only 0xFF bytes", pnum); return UBI_IO_PEB_EMPTY; } /* * This is not a valid erase counter header, and these are not * 0xFF bytes. Report that the header is corrupted. */ if (verbose) { ubi_warn("bad magic number at PEB %d: %08x instead of " "%08x", pnum, magic, UBI_EC_HDR_MAGIC); ubi_dbg_dump_ec_hdr(ec_hdr); } return UBI_IO_BAD_EC_HDR; } crc = crc32(UBI_CRC32_INIT, ec_hdr, UBI_EC_HDR_SIZE_CRC); hdr_crc = be32_to_cpu(ec_hdr->hdr_crc); if (hdr_crc != crc) { if (verbose) { ubi_warn("bad EC header CRC at PEB %d, calculated %#08x," " read %#08x", pnum, crc, hdr_crc); ubi_dbg_dump_ec_hdr(ec_hdr); } return UBI_IO_BAD_EC_HDR; } /* And of course validate what has just been read from the media */ err = validate_ec_hdr(ubi, ec_hdr); if (err) { ubi_err("validation failed for PEB %d", pnum); return -EINVAL; } return read_err ? UBI_IO_BITFLIPS : 0; } /** * ubi_io_write_ec_hdr - write an erase counter header. * @ubi: UBI device description object * @pnum: physical eraseblock to write to * @ec_hdr: the erase counter header to write * * This function writes erase counter header described by @ec_hdr to physical * eraseblock @pnum. It also fills most fields of @ec_hdr before writing, so * the caller do not have to fill them. Callers must only fill the @ec_hdr->ec * field. * * This function returns zero in case of success and a negative error code in * case of failure. If %-EIO is returned, the physical eraseblock most probably * went bad. */ int ubi_io_write_ec_hdr(struct ubi_device *ubi, int pnum, struct ubi_ec_hdr *ec_hdr) { int err; uint32_t crc; dbg_io("write EC header to PEB %d", pnum); ubi_assert(pnum >= 0 && pnum < ubi->peb_count); ec_hdr->magic = cpu_to_be32(UBI_EC_HDR_MAGIC); ec_hdr->version = UBI_VERSION; ec_hdr->vid_hdr_offset = cpu_to_be32(ubi->vid_hdr_offset); ec_hdr->data_offset = cpu_to_be32(ubi->leb_start); crc = crc32(UBI_CRC32_INIT, ec_hdr, UBI_EC_HDR_SIZE_CRC); ec_hdr->hdr_crc = cpu_to_be32(crc); err = <API key>(ubi, pnum, ec_hdr); if (err) return -EINVAL; err = ubi_io_write(ubi, ec_hdr, pnum, 0, ubi->ec_hdr_alsize); return err; } /** * validate_vid_hdr - validate a volume identifier header. * @ubi: UBI device description object * @vid_hdr: the volume identifier header to check * * This function checks that data stored in the volume identifier header * @vid_hdr. Returns zero if the VID header is OK and %1 if not. */ static int validate_vid_hdr(const struct ubi_device *ubi, const struct ubi_vid_hdr *vid_hdr) { int vol_type = vid_hdr->vol_type; int copy_flag = vid_hdr->copy_flag; int vol_id = be32_to_cpu(vid_hdr->vol_id); int lnum = be32_to_cpu(vid_hdr->lnum); int compat = vid_hdr->compat; int data_size = be32_to_cpu(vid_hdr->data_size); int used_ebs = be32_to_cpu(vid_hdr->used_ebs); int data_pad = be32_to_cpu(vid_hdr->data_pad); int data_crc = be32_to_cpu(vid_hdr->data_crc); int usable_leb_size = ubi->leb_size - data_pad; if (copy_flag != 0 && copy_flag != 1) { dbg_err("bad copy_flag"); goto bad; } if (vol_id < 0 || lnum < 0 || data_size < 0 || used_ebs < 0 || data_pad < 0) { dbg_err("negative values"); goto bad; } if (vol_id >= UBI_MAX_VOLUMES && vol_id < <API key>) { dbg_err("bad vol_id"); goto bad; } if (vol_id < <API key> && compat != 0) { dbg_err("bad compat"); goto bad; } if (vol_id >= <API key> && compat != UBI_COMPAT_DELETE && compat != UBI_COMPAT_RO && compat != UBI_COMPAT_PRESERVE && compat != UBI_COMPAT_REJECT) { dbg_err("bad compat"); goto bad; } if (vol_type != UBI_VID_DYNAMIC && vol_type != UBI_VID_STATIC) { dbg_err("bad vol_type"); goto bad; } if (data_pad >= ubi->leb_size / 2) { dbg_err("bad data_pad"); goto bad; } if (vol_type == UBI_VID_STATIC) { /* * Although from high-level point of view static volumes may * contain zero bytes of data, but no VID headers can contain * zero at these fields, because they empty volumes do not have * mapped logical eraseblocks. */ if (used_ebs == 0) { dbg_err("zero used_ebs"); goto bad; } if (data_size == 0) { dbg_err("zero data_size"); goto bad; } if (lnum < used_ebs - 1) { if (data_size != usable_leb_size) { dbg_err("bad data_size"); goto bad; } } else if (lnum == used_ebs - 1) { if (data_size == 0) { dbg_err("bad data_size at last LEB"); goto bad; } } else { dbg_err("too high lnum"); goto bad; } } else { if (copy_flag == 0) { if (data_crc != 0) { dbg_err("non-zero data CRC"); goto bad; } if (data_size != 0) { dbg_err("non-zero data_size"); goto bad; } } else { if (data_size == 0) { dbg_err("zero data_size of copy"); goto bad; } } if (used_ebs != 0) { dbg_err("bad used_ebs"); goto bad; } } return 0; bad: ubi_err("bad VID header"); <API key>(vid_hdr); ubi_dbg_dump_stack(); return 1; } /** * ubi_io_read_vid_hdr - read and check a volume identifier header. * @ubi: UBI device description object * @pnum: physical eraseblock number to read from * @vid_hdr: &struct ubi_vid_hdr object where to store the read volume * identifier header * @verbose: be verbose if the header is corrupted or wasn't found * * This function reads the volume identifier header from physical eraseblock * @pnum and stores it in @vid_hdr. It also checks CRC checksum of the read * volume identifier header. The following codes may be returned: * * o %0 if the CRC checksum is correct and the header was successfully read; * o %UBI_IO_BITFLIPS if the CRC is correct, but bit-flips were detected * and corrected by the flash driver; this is harmless but may indicate that * this eraseblock may become bad soon; * o %UBI_IO_BAD_VID_HRD if the volume identifier header is corrupted (a CRC * error detected); * o %UBI_IO_PEB_FREE if the physical eraseblock is free (i.e., there is no VID * header there); * o a negative error code in case of failure. */ int ubi_io_read_vid_hdr(struct ubi_device *ubi, int pnum, struct ubi_vid_hdr *vid_hdr, int verbose) { int err, read_err = 0; uint32_t crc, magic, hdr_crc; void *p; dbg_io("read VID header from PEB %d", pnum); ubi_assert(pnum >= 0 && pnum < ubi->peb_count); if (UBI_IO_DEBUG) verbose = 1; p = (char *)vid_hdr - ubi->vid_hdr_shift; err = ubi_io_read(ubi, p, pnum, ubi->vid_hdr_aloffset, ubi->vid_hdr_alsize); if (err) { if (err != UBI_IO_BITFLIPS && err != -EBADMSG) return err; /* * We read all the data, but either a correctable bit-flip * occurred, or MTD reported about some data integrity error, * like an ECC error in case of NAND. The former is harmless, * the later may mean the read data is corrupted. But we have a * CRC check-sum and we will identify this. If the VID header is * still OK, we just report this as there was a bit-flip. */ read_err = err; } magic = be32_to_cpu(vid_hdr->magic); if (magic != UBI_VID_HDR_MAGIC) { /* * If we have read all 0xFF bytes, the VID header probably does * not exist and the physical eraseblock is assumed to be free. * * But if there was a read error, we do not test the data for * 0xFFs. Even if it does contain all 0xFFs, this error * indicates that something is still wrong with this physical * eraseblock and it cannot be regarded as free. */ if (read_err != -EBADMSG && check_pattern(vid_hdr, 0xFF, UBI_VID_HDR_SIZE)) { /* The physical eraseblock is supposedly free */ /* * The below is just a paranoid check, it has to be * compiled out if paranoid checks are disabled. */ err = <API key>(ubi, pnum, ubi->leb_start, ubi->leb_size); if (err) return err > 0 ? UBI_IO_BAD_VID_HDR : err; if (verbose) ubi_warn("no VID header found at PEB %d, " "only 0xFF bytes", pnum); return UBI_IO_PEB_FREE; } /* * This is not a valid VID header, and these are not 0xFF * bytes. Report that the header is corrupted. */ if (verbose) { ubi_warn("bad magic number at PEB %d: %08x instead of " "%08x", pnum, magic, UBI_VID_HDR_MAGIC); <API key>(vid_hdr); } return UBI_IO_BAD_VID_HDR; } crc = crc32(UBI_CRC32_INIT, vid_hdr, <API key>); hdr_crc = be32_to_cpu(vid_hdr->hdr_crc); if (hdr_crc != crc) { if (verbose) { ubi_warn("bad CRC at PEB %d, calculated %#08x, " "read %#08x", pnum, crc, hdr_crc); <API key>(vid_hdr); } return UBI_IO_BAD_VID_HDR; } /* Validate the VID header that we have just read */ err = validate_vid_hdr(ubi, vid_hdr); if (err) { ubi_err("validation failed for PEB %d", pnum); return -EINVAL; } return read_err ? UBI_IO_BITFLIPS : 0; } /** * <API key> - write a volume identifier header. * @ubi: UBI device description object * @pnum: the physical eraseblock number to write to * @vid_hdr: the volume identifier header to write * * This function writes the volume identifier header described by @vid_hdr to * physical eraseblock @pnum. This function automatically fills the * @vid_hdr->magic and the @vid_hdr->version fields, as well as calculates * header CRC checksum and stores it at vid_hdr->hdr_crc. * * This function returns zero in case of success and a negative error code in * case of failure. If %-EIO is returned, the physical eraseblock probably went * bad. */ int <API key>(struct ubi_device *ubi, int pnum, struct ubi_vid_hdr *vid_hdr) { int err; uint32_t crc; void *p; dbg_io("write VID header to PEB %d", pnum); ubi_assert(pnum >= 0 && pnum < ubi->peb_count); err = <API key>(ubi, pnum); if (err) return err > 0 ? -EINVAL: err; vid_hdr->magic = cpu_to_be32(UBI_VID_HDR_MAGIC); vid_hdr->version = UBI_VERSION; crc = crc32(UBI_CRC32_INIT, vid_hdr, <API key>); vid_hdr->hdr_crc = cpu_to_be32(crc); err = <API key>(ubi, pnum, vid_hdr); if (err) return -EINVAL; p = (char *)vid_hdr - ubi->vid_hdr_shift; err = ubi_io_write(ubi, p, pnum, ubi->vid_hdr_aloffset, ubi->vid_hdr_alsize); return err; } #ifdef <API key> /** * <API key> - ensure that a physical eraseblock is not bad. * @ubi: UBI device description object * @pnum: physical eraseblock number to check * * This function returns zero if the physical eraseblock is good, a positive * number if it is bad and a negative error code if an error occurred. */ static int <API key>(const struct ubi_device *ubi, int pnum) { int err; err = ubi_io_is_bad(ubi, pnum); if (!err) return err; ubi_err("paranoid check failed for PEB %d", pnum); ubi_dbg_dump_stack(); return err; } /** * <API key> - check if an erase counter header is all right. * @ubi: UBI device description object * @pnum: physical eraseblock number the erase counter header belongs to * @ec_hdr: the erase counter header to check * * This function returns zero if the erase counter header contains valid * values, and %1 if not. */ static int <API key>(const struct ubi_device *ubi, int pnum, const struct ubi_ec_hdr *ec_hdr) { int err; uint32_t magic; magic = be32_to_cpu(ec_hdr->magic); if (magic != UBI_EC_HDR_MAGIC) { ubi_err("bad magic %#08x, must be %#08x", magic, UBI_EC_HDR_MAGIC); goto fail; } err = validate_ec_hdr(ubi, ec_hdr); if (err) { ubi_err("paranoid check failed for PEB %d", pnum); goto fail; } return 0; fail: ubi_dbg_dump_ec_hdr(ec_hdr); ubi_dbg_dump_stack(); return 1; } /** * <API key> - check that the erase counter header of a * physical eraseblock is in-place and is all right. * @ubi: UBI device description object * @pnum: the physical eraseblock number to check * * This function returns zero if the erase counter header is all right, %1 if * not, and a negative error code if an error occurred. */ static int <API key>(const struct ubi_device *ubi, int pnum) { int err; uint32_t crc, hdr_crc; struct ubi_ec_hdr *ec_hdr; ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_NOFS); if (!ec_hdr) return -ENOMEM; err = ubi_io_read(ubi, ec_hdr, pnum, 0, UBI_EC_HDR_SIZE); if (err && err != UBI_IO_BITFLIPS && err != -EBADMSG) goto exit; crc = crc32(UBI_CRC32_INIT, ec_hdr, UBI_EC_HDR_SIZE_CRC); hdr_crc = be32_to_cpu(ec_hdr->hdr_crc); if (hdr_crc != crc) { ubi_err("bad CRC, calculated %#08x, read %#08x", crc, hdr_crc); ubi_err("paranoid check failed for PEB %d", pnum); ubi_dbg_dump_ec_hdr(ec_hdr); ubi_dbg_dump_stack(); err = 1; goto exit; } err = <API key>(ubi, pnum, ec_hdr); exit: kfree(ec_hdr); return err; } /** * <API key> - check that a volume identifier header is all right. * @ubi: UBI device description object * @pnum: physical eraseblock number the volume identifier header belongs to * @vid_hdr: the volume identifier header to check * * This function returns zero if the volume identifier header is all right, and * %1 if not. */ static int <API key>(const struct ubi_device *ubi, int pnum, const struct ubi_vid_hdr *vid_hdr) { int err; uint32_t magic; magic = be32_to_cpu(vid_hdr->magic); if (magic != UBI_VID_HDR_MAGIC) { ubi_err("bad VID header magic %#08x at PEB %d, must be %#08x", magic, pnum, UBI_VID_HDR_MAGIC); goto fail; } err = validate_vid_hdr(ubi, vid_hdr); if (err) { ubi_err("paranoid check failed for PEB %d", pnum); goto fail; } return err; fail: ubi_err("paranoid check failed for PEB %d", pnum); <API key>(vid_hdr); ubi_dbg_dump_stack(); return 1; } /** * <API key> - check that the volume identifier header of a * physical eraseblock is in-place and is all right. * @ubi: UBI device description object * @pnum: the physical eraseblock number to check * * This function returns zero if the volume identifier header is all right, * %1 if not, and a negative error code if an error occurred. */ static int <API key>(const struct ubi_device *ubi, int pnum) { int err; uint32_t crc, hdr_crc; struct ubi_vid_hdr *vid_hdr; void *p; vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS); if (!vid_hdr) return -ENOMEM; p = (char *)vid_hdr - ubi->vid_hdr_shift; err = ubi_io_read(ubi, p, pnum, ubi->vid_hdr_aloffset, ubi->vid_hdr_alsize); if (err && err != UBI_IO_BITFLIPS && err != -EBADMSG) goto exit; crc = crc32(UBI_CRC32_INIT, vid_hdr, UBI_EC_HDR_SIZE_CRC); hdr_crc = be32_to_cpu(vid_hdr->hdr_crc); if (hdr_crc != crc) { ubi_err("bad VID header CRC at PEB %d, calculated %#08x, " "read %#08x", pnum, crc, hdr_crc); ubi_err("paranoid check failed for PEB %d", pnum); <API key>(vid_hdr); ubi_dbg_dump_stack(); err = 1; goto exit; } err = <API key>(ubi, pnum, vid_hdr); exit: ubi_free_vid_hdr(ubi, vid_hdr); return err; } /** * <API key> - check that a region of flash is empty. * @ubi: UBI device description object * @pnum: the physical eraseblock number to check * @offset: the starting offset within the physical eraseblock to check * @len: the length of the region to check * * This function returns zero if only 0xFF bytes are present at offset * @offset of the physical eraseblock @pnum, %1 if not, and a negative error * code if an error occurred. */ static int <API key>(struct ubi_device *ubi, int pnum, int offset, int len) { size_mtd_t read; int err; loff_mtd_t addr = (loff_mtd_t)pnum * ubi->peb_size + offset; mutex_lock(&ubi->dbg_buf_mutex); err = ubi->mtd->read(ubi->mtd, addr, len, &read, ubi->dbg_peb_buf); if (err && err != -EUCLEAN) { ubi_err("error %d while reading %d bytes from PEB %d:%d, " "read %lld bytes", err, len, pnum, offset, read); goto error; } err = check_pattern(ubi->dbg_peb_buf, 0xFF, len); if (err == 0) { ubi_err("flash region at PEB %d:%d, length %d does not " "contain all 0xFF bytes", pnum, offset, len); goto fail; } mutex_unlock(&ubi->dbg_buf_mutex); return 0; fail: ubi_err("paranoid check failed for PEB %d", pnum); dbg_msg("hex dump of the %d-%d region", offset, offset + len); print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1, ubi->dbg_peb_buf, len, 1); err = 1; error: ubi_dbg_dump_stack(); mutex_unlock(&ubi->dbg_buf_mutex); return err; } #endif /* <API key> */
#pragma once #include "settings/dialogs/<API key>.h" class CFileItem; namespace PERIPHERALS { class <API key> : public <API key> { public: <API key>(); ~<API key>() override; // specializations of CGUIControl bool OnMessage(CGUIMessage& message) override; virtual void SetFileItem(const CFileItem* item); protected: // implementations of ISettingCallback void OnSettingChanged(std::shared_ptr<const CSetting> setting) override; // specialization of <API key> bool <API key>() const override { return false; } void Save() override; void OnResetSettings() override; void SetupView() override; // specialization of <API key> void InitializeSettings() override; CFileItem* m_item; bool m_initialising = false; std::map<std::string, std::shared_ptr<CSetting>> m_settingsMap; }; } // namespace PERIPHERALS
#include "ScriptMgr.h" #include "scholomance.h" #include "ScriptedCreature.h" enum Spells { <API key> = 24673, SPELL_ILLUSION = 17773, SPELL_DROP_JOURNAL = 26096 }; enum Events { <API key> = 1, EVENT_ILLUSION, EVENT_CLEAVE, <API key> }; class boss_jandice_barov : public CreatureScript { public: boss_jandice_barov() : CreatureScript("boss_jandice_barov") { } struct boss_jandicebarovAI : public ScriptedAI { boss_jandicebarovAI(Creature* creature) : ScriptedAI(creature), Summons(me) { } void Reset() override { events.Reset(); Summons.DespawnAll(); } void JustSummoned(Creature* summoned) override { // Illusions should attack a random target. if (Unit* target = SelectTarget(<API key>, 0)) summoned->AI()->AttackStart(target); summoned->ApplySpellImmune(0, IMMUNITY_DAMAGE, <API key>, true); // Not sure if this is correct. Summons.Summon(summoned); } void JustEngagedWith(Unit* /*who*/) override { events.ScheduleEvent(<API key>, 15s); events.ScheduleEvent(EVENT_ILLUSION, 30s); } void JustDied(Unit* /*killer*/) override { Summons.DespawnAll(); DoCastSelf(SPELL_DROP_JOURNAL, true); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case <API key>: DoCastVictim(<API key>); events.ScheduleEvent(<API key>, 30s); break; case EVENT_ILLUSION: DoCast(SPELL_ILLUSION); me->SetFlag(UNIT_FIELD_FLAGS, <API key>); me->SetDisplayId(11686); // Invisible Model <API key>(me->GetVictim(), -99); events.ScheduleEvent(<API key>, 3s); events.ScheduleEvent(EVENT_ILLUSION, 25s); break; case <API key>: me->RemoveFlag(UNIT_FIELD_FLAGS, <API key>); me->SetDisplayId(11073); //Jandice Model break; default: break; } if (me->HasUnitState(UNIT_STATE_CASTING)) return; } <API key>(); } private: EventMap events; SummonList Summons; }; CreatureAI* GetAI(Creature* creature) const override { return GetScholomanceAI<boss_jandicebarovAI>(creature); } }; void <API key>() { new boss_jandice_barov(); }