code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
public class Test { public int anObject; public void method() { } } public class Test1 extends Test { public void method() { System.out.println(<selection>1 + 2</selection>); System.out.println(anObject); } }
consulo/consulo-groovy
testdata/refactoring/introduceParameter/conflictingField/ConflictingFieldMyClass.java
Java
apache-2.0
245
.navicon-dashboard { background-image:url(images/menu.dashboard.png) !important; } .navicon-dashboard:hover { background-position:0 -30px !important; }
austinsc/Orchard
src/Orchard.Web/Core/Dashboard/styles/menu.dashboard-admin.css
CSS
bsd-3-clause
159
<?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Generates requests to send to PayPal */ class WC_Gateway_Paypal_Request { /** * Stores line items to send to PayPal * @var array */ protected $line_items = array(); /** * Pointer to gateway making the request * @var WC_Gateway_Paypal */ protected $gateway; /** * Endpoint for requests from PayPal * @var string */ protected $notify_url; /** * Constructor * @param WC_Gateway_Paypal $gateway */ public function __construct( $gateway ) { $this->gateway = $gateway; $this->notify_url = WC()->api_request_url( 'WC_Gateway_Paypal' ); } /** * Get the PayPal request URL for an order * @param WC_Order $order * @param boolean $sandbox * @return string */ public function get_request_url( $order, $sandbox = false ) { $paypal_args = http_build_query( $this->get_paypal_args( $order ), '', '&' ); if ( $sandbox ) { return 'https://www.sandbox.paypal.com/cgi-bin/webscr?test_ipn=1&' . $paypal_args; } else { return 'https://www.paypal.com/cgi-bin/webscr?' . $paypal_args; } } /** * Get PayPal Args for passing to PP * * @param WC_Order $order * @return array */ protected function get_paypal_args( $order ) { WC_Gateway_Paypal::log( 'Generating payment form for order ' . $order->get_order_number() . '. Notify URL: ' . $this->notify_url ); return apply_filters( 'woocommerce_paypal_args', array_merge( array( 'cmd' => '_cart', 'business' => $this->gateway->get_option( 'email' ), 'no_note' => 1, 'currency_code' => get_woocommerce_currency(), 'charset' => 'utf-8', 'rm' => is_ssl() ? 2 : 1, 'upload' => 1, 'return' => esc_url( add_query_arg( 'utm_nooverride', '1', $this->gateway->get_return_url( $order ) ) ), 'cancel_return' => esc_url( $order->get_cancel_order_url() ), 'page_style' => $this->gateway->get_option( 'page_style' ), 'paymentaction' => $this->gateway->get_option( 'paymentaction' ), 'bn' => 'WooThemes_Cart', 'invoice' => $this->gateway->get_option( 'invoice_prefix' ) . $order->get_order_number(), 'custom' => json_encode( array( 'order_id' => $order->id, 'order_key' => $order->order_key ) ), 'notify_url' => $this->notify_url, 'first_name' => $order->billing_first_name, 'last_name' => $order->billing_last_name, 'company' => $order->billing_company, 'address1' => $order->billing_address_1, 'address2' => $order->billing_address_2, 'city' => $order->billing_city, 'state' => $this->get_paypal_state( $order->billing_country, $order->billing_state ), 'zip' => $order->billing_postcode, 'country' => $order->billing_country, 'email' => $order->billing_email ), $this->get_phone_number_args( $order ), $this->get_shipping_args( $order ), $this->get_line_item_args( $order ) ), $order ); } /** * Get phone number args for paypal request * @param WC_Order $order * @return array */ protected function get_phone_number_args( $order ) { if ( in_array( $order->billing_country, array( 'US','CA' ) ) ) { $phone_number = str_replace( array( '(', '-', ' ', ')', '.' ), '', $order->billing_phone ); $phone_args = array( 'night_phone_a' => substr( $phone_number, 0, 3 ), 'night_phone_b' => substr( $phone_number, 3, 3 ), 'night_phone_c' => substr( $phone_number, 6, 4 ), 'day_phone_a' => substr( $phone_number, 0, 3 ), 'day_phone_b' => substr( $phone_number, 3, 3 ), 'day_phone_c' => substr( $phone_number, 6, 4 ) ); } else { $phone_args = array( 'night_phone_b' => $order->billing_phone, 'day_phone_b' => $order->billing_phone ); } return $phone_args; } /** * Get shipping args for paypal request * @param WC_Order $order * @return array */ protected function get_shipping_args( $order ) { $shipping_args = array(); if ( 'yes' == $this->gateway->get_option( 'send_shipping' ) ) { $shipping_args['address_override'] = $this->gateway->get_option( 'address_override' ) === 'yes' ? 1 : 0; $shipping_args['no_shipping'] = 0; // If we are sending shipping, send shipping address instead of billing $shipping_args['first_name'] = $order->shipping_first_name; $shipping_args['last_name'] = $order->shipping_last_name; $shipping_args['company'] = $order->shipping_company; $shipping_args['address1'] = $order->shipping_address_1; $shipping_args['address2'] = $order->shipping_address_2; $shipping_args['city'] = $order->shipping_city; $shipping_args['state'] = $this->get_paypal_state( $order->shipping_country, $order->shipping_state ); $shipping_args['country'] = $order->shipping_country; $shipping_args['zip'] = $order->shipping_postcode; } else { $shipping_args['no_shipping'] = 1; } return $shipping_args; } /** * Get line item args for paypal request * @param WC_Order $order * @return array */ protected function get_line_item_args( $order ) { /** * Try passing a line item per product if supported */ if ( ( ! wc_tax_enabled() || ! wc_prices_include_tax() ) && $this->prepare_line_items( $order ) ) { $line_item_args = $this->get_line_items(); $line_item_args['tax_cart'] = $this->number_format( $order->get_total_tax(), $order ); if ( $order->get_total_discount() > 0 ) { $line_item_args['discount_amount_cart'] = $this->round( $order->get_total_discount(), $order ); } /** * Send order as a single item * * For shipping, we longer use shipping_1 because paypal ignores it if *any* shipping rules are within paypal, and paypal ignores anything over 5 digits (999.99 is the max) */ } else { $this->delete_line_items(); $all_items_name = $this->get_order_item_names( $order ); $this->add_line_item( $all_items_name ? $all_items_name : __( 'Order', 'woocommerce' ), 1, $this->number_format( $order->get_total() - $this->round( $order->get_total_shipping() + $order->get_shipping_tax(), $order ), $order ), $order->get_order_number() ); $this->add_line_item( sprintf( __( 'Shipping via %s', 'woocommerce' ), ucwords( $order->get_shipping_method() ) ), 1, $this->number_format( $order->get_total_shipping() + $order->get_shipping_tax(), $order ) ); $line_item_args = $this->get_line_items(); } return $line_item_args; } /** * Get order item names as a string * @param WC_Order $order * @return string */ protected function get_order_item_names( $order ) { $item_names = array(); foreach ( $order->get_items() as $item ) { $item_names[] = $item['name'] . ' x ' . $item['qty']; } return implode( ', ', $item_names ); } /** * Get order item names as a string * @param WC_Order $order * @param array $item * @return string */ protected function get_order_item_name( $order, $item ) { $item_name = $item['name']; $item_meta = new WC_Order_Item_Meta( $item ); if ( $meta = $item_meta->display( true, true ) ) { $item_name .= ' ( ' . $meta . ' )'; } return $item_name; } /** * Return all line items */ protected function get_line_items() { return $this->line_items; } /** * Remove all line items */ protected function delete_line_items() { $this->line_items = array(); } /** * Get line items to send to paypal * * @param WC_Order $order * @return bool */ protected function prepare_line_items( $order ) { $this->delete_line_items(); $calculated_total = 0; // Products foreach ( $order->get_items( array( 'line_item', 'fee' ) ) as $item ) { if ( 'fee' === $item['type'] ) { $item_line_total = $this->number_format( $item['line_total'], $order ); $line_item = $this->add_line_item( $item['name'], 1, $item_line_total ); $calculated_total += $item_line_total; } else { $product = $order->get_product_from_item( $item ); $item_line_total = $this->number_format( $order->get_item_subtotal( $item, false ), $order ); $line_item = $this->add_line_item( $this->get_order_item_name( $order, $item ), $item['qty'], $item_line_total, $product->get_sku() ); $calculated_total += $item_line_total * $item['qty']; } if ( ! $line_item ) { return false; } } // Shipping Cost item - paypal only allows shipping per item, we want to send shipping for the order if ( $order->get_total_shipping() > 0 && ! $this->add_line_item( sprintf( __( 'Shipping via %s', 'woocommerce' ), $order->get_shipping_method() ), 1, $this->round( $order->get_total_shipping(), $order ) ) ) { return false; } // Check for mismatched totals if ( $this->number_format( $calculated_total + $order->get_total_tax() + $this->round( $order->get_total_shipping(), $order ) - $this->round( $order->get_total_discount(), $order ), $order ) != $this->number_format( $order->get_total(), $order ) ) { return false; } return true; } /** * Add PayPal Line Item * @param string $item_name * @param integer $quantity * @param integer $amount * @param string $item_number * @return bool successfully added or not */ protected function add_line_item( $item_name, $quantity = 1, $amount = 0, $item_number = '' ) { $index = ( sizeof( $this->line_items ) / 4 ) + 1; if ( $amount < 0 || $index > 9 ) { return false; } $this->line_items[ 'item_name_' . $index ] = html_entity_decode( wc_trim_string( $item_name ? $item_name : __( 'Item', 'woocommerce' ), 127 ), ENT_NOQUOTES, 'UTF-8' ); $this->line_items[ 'quantity_' . $index ] = $quantity; $this->line_items[ 'amount_' . $index ] = $amount; $this->line_items[ 'item_number_' . $index ] = $item_number; return true; } /** * Get the state to send to paypal * @param string $cc * @param string $state * @return string */ protected function get_paypal_state( $cc, $state ) { if ( 'US' === $cc ) { return $state; } $states = WC()->countries->get_states( $cc ); if ( isset( $states[ $state ] ) ) { return $states[ $state ]; } return $state; } /** * Check if currency has decimals * * @param string $currency * * @return bool */ protected function currency_has_decimals( $currency ) { if ( in_array( $currency, array( 'HUF', 'JPY', 'TWD' ) ) ) { return false; } return true; } /** * Round prices * * @param float|int $price * @param WC_Order $order * * @return float|int */ protected function round( $price, $order ) { $precision = 2; if ( ! $this->currency_has_decimals( $order->get_order_currency() ) ) { $precision = 0; } return round( $price, $precision ); } /** * Format prices * * @param float|int $price * @param WC_Order $order * * @return float|int */ protected function number_format( $price, $order ) { $decimals = 2; if ( ! $this->currency_has_decimals( $order->get_order_currency() ) ) { $decimals = 0; } return number_format( $price, $decimals, '.', '' ); } }
ORNChurch/ornchurch.org
wp-content/plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
PHP
gpl-2.0
11,195
using System; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class DriverDisposalTest : DriverTestFixture { [Test] [IgnoreBrowser(Browser.Safari)] public void ShouldOpenAndCloseBrowserRepeatedly() { for (int i = 0; i < 5; i++) { EnvironmentManager.Instance.CloseCurrentDriver(); CreateFreshDriver(); driver.Url = simpleTestPage; Assert.AreEqual(simpleTestTitle, driver.Title); } } [Test] [NeedsFreshDriver(AfterTest = true)] [IgnoreBrowser(Browser.Safari)] public void ShouldBeAbleToStartNewDriverAfterCallingCloseOnOnlyOpenWindow() { EnvironmentManager.Instance.CloseCurrentDriver(); IWebDriver testDriver = EnvironmentManager.Instance.CreateDriverInstance(); testDriver.Url = simpleTestPage; testDriver.Close(); testDriver.Dispose(); testDriver = EnvironmentManager.Instance.CreateDriverInstance(); testDriver.Url = xhtmlTestPage; Assert.AreEqual("XHTML Test Page", testDriver.Title); testDriver.Close(); testDriver.Dispose(); } [Test] [NeedsFreshDriver(AfterTest = true)] [IgnoreBrowser(Browser.Safari)] public void ShouldBeAbleToCallQuitAfterCallingCloseOnOnlyOpenWindow() { EnvironmentManager.Instance.CloseCurrentDriver(); IWebDriver testDriver = EnvironmentManager.Instance.CreateDriverInstance(); testDriver.Url = simpleTestPage; testDriver.Close(); testDriver.Quit(); testDriver = EnvironmentManager.Instance.CreateDriverInstance(); testDriver.Url = xhtmlTestPage; Assert.AreEqual("XHTML Test Page", testDriver.Title); testDriver.Quit(); } [Test] [NeedsFreshDriver(AfterTest = true)] [IgnoreBrowser(Browser.Safari)] public void ShouldBeAbleToCallDisposeAfterQuit() { EnvironmentManager.Instance.CloseCurrentDriver(); IWebDriver testDriver = EnvironmentManager.Instance.CreateDriverInstance(); testDriver.Url = simpleTestPage; testDriver.Quit(); testDriver.Dispose(); testDriver = EnvironmentManager.Instance.CreateDriverInstance(); testDriver.Url = xhtmlTestPage; Assert.AreEqual("XHTML Test Page", testDriver.Title); testDriver.Quit(); } [Test] [IgnoreBrowser(Browser.Firefox, "Firefox doesn't shut its server down immediately upon calling Close(), so a subsequent call could succeed.")] [IgnoreBrowser(Browser.Safari)] [NeedsFreshDriver(AfterTest = true)] public void ShouldNotBeAbleToCallDriverMethodAfterCallingCloseOnOnlyOpenWindow() { EnvironmentManager.Instance.CloseCurrentDriver(); IWebDriver testDriver = EnvironmentManager.Instance.CreateDriverInstance(); try { testDriver.Url = simpleTestPage; testDriver.Close(); string url = testDriver.Url; // Should never reach this line. Assert.Fail("Should not be able to access Url property after close of only open window"); } catch (WebDriverException) { } catch (InvalidOperationException) { } finally { testDriver.Dispose(); } } [Test] [NeedsFreshDriver(AfterTest = true)] [IgnoreBrowser(Browser.Safari)] public void ShouldNotBeAbleToCallDriverMethodAfterCallingQuit() { EnvironmentManager.Instance.CloseCurrentDriver(); IWebDriver testDriver = EnvironmentManager.Instance.CreateDriverInstance(); try { testDriver.Url = simpleTestPage; testDriver.Quit(); string url = testDriver.Url; // Should never reach this line. Assert.Fail("Should not be able to access Url property after close of only open window"); } catch (WebDriverException) { } finally { testDriver.Dispose(); } } [Test] [NeedsFreshDriver(AfterTest = true)] [IgnoreBrowser(Browser.Safari)] public void ShouldBeAbleToDisposeOfDriver() { EnvironmentManager.Instance.CloseCurrentDriver(); IWebDriver testDriver = EnvironmentManager.Instance.CreateDriverInstance(); testDriver.Url = simpleTestPage; testDriver.Dispose(); } [Test] [NeedsFreshDriver(AfterTest = true)] [IgnoreBrowser(Browser.Safari)] public void ShouldBeAbleToCallDisposeConsecutively() { EnvironmentManager.Instance.CloseCurrentDriver(); IWebDriver testDriver = EnvironmentManager.Instance.CreateDriverInstance(); testDriver.Url = simpleTestPage; testDriver.Dispose(); testDriver.Dispose(); } [Test] [NeedsFreshDriver(AfterTest = true)] [IgnoreBrowser(Browser.Safari)] public void ShouldBeAbleToCallQuitConsecutively() { driver.Url = simpleTestPage; driver.Quit(); driver.Quit(); driver = EnvironmentManager.Instance.CreateDriverInstance(); driver.Url = xhtmlTestPage; driver.Quit(); } } }
jerome-jacob/selenium
dotnet/test/common/DriverDisposalTest.cs
C#
apache-2.0
5,804
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\ChoiceList\View\ChoiceView; class TimezoneTypeTest extends BaseTypeTest { const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\TimezoneType'; public function testTimezonesAreSelectable() { $choices = $this->factory->create(static::TESTED_TYPE) ->createView()->vars['choices']; $this->assertArrayHasKey('Africa', $choices); $this->assertContains(new ChoiceView('Africa/Kinshasa', 'Africa/Kinshasa', 'Kinshasa'), $choices['Africa'], '', false, false); $this->assertArrayHasKey('America', $choices); $this->assertContains(new ChoiceView('America/New_York', 'America/New_York', 'New York'), $choices['America'], '', false, false); } public function testSubmitNull($expected = null, $norm = null, $view = null) { parent::testSubmitNull($expected, $norm, ''); } }
adiIspas/Hootsuite_Backend_API
web_server/code/vendor/symfony/symfony/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimezoneTypeTest.php
PHP
mit
1,188
<li>Uno</li> <li>Dos</li> <li>Tres</li> <li>Cuatro</li> <li>Cinco</li> <li>Seis</li>
february29/Learning
web/vue/AccountBook-Express/node_modules/pug/test/output/block-code.html
HTML
mit
85
# Copyright (C) 2001-2006 Python Software Foundation # Author: Ben Gertzfield, Barry Warsaw # Contact: email-sig@python.org __all__ = [ 'Charset', 'add_alias', 'add_charset', 'add_codec', ] import email.base64mime import email.quoprimime from email import errors from email.encoders import encode_7or8bit # Flags for types of header encodings QP = 1 # Quoted-Printable BASE64 = 2 # Base64 SHORTEST = 3 # the shorter of QP and base64, but only for headers # In "=?charset?q?hello_world?=", the =?, ?q?, and ?= add up to 7 MISC_LEN = 7 DEFAULT_CHARSET = 'us-ascii' # Defaults CHARSETS = { # input header enc body enc output conv 'iso-8859-1': (QP, QP, None), 'iso-8859-2': (QP, QP, None), 'iso-8859-3': (QP, QP, None), 'iso-8859-4': (QP, QP, None), # iso-8859-5 is Cyrillic, and not especially used # iso-8859-6 is Arabic, also not particularly used # iso-8859-7 is Greek, QP will not make it readable # iso-8859-8 is Hebrew, QP will not make it readable 'iso-8859-9': (QP, QP, None), 'iso-8859-10': (QP, QP, None), # iso-8859-11 is Thai, QP will not make it readable 'iso-8859-13': (QP, QP, None), 'iso-8859-14': (QP, QP, None), 'iso-8859-15': (QP, QP, None), 'windows-1252':(QP, QP, None), 'viscii': (QP, QP, None), 'us-ascii': (None, None, None), 'big5': (BASE64, BASE64, None), 'gb2312': (BASE64, BASE64, None), 'euc-jp': (BASE64, None, 'iso-2022-jp'), 'shift_jis': (BASE64, None, 'iso-2022-jp'), 'iso-2022-jp': (BASE64, None, None), 'koi8-r': (BASE64, BASE64, None), 'utf-8': (SHORTEST, BASE64, 'utf-8'), # We're making this one up to represent raw unencoded 8-bit '8bit': (None, BASE64, 'utf-8'), } # Aliases for other commonly-used names for character sets. Map # them to the real ones used in email. ALIASES = { 'latin_1': 'iso-8859-1', 'latin-1': 'iso-8859-1', 'latin_2': 'iso-8859-2', 'latin-2': 'iso-8859-2', 'latin_3': 'iso-8859-3', 'latin-3': 'iso-8859-3', 'latin_4': 'iso-8859-4', 'latin-4': 'iso-8859-4', 'latin_5': 'iso-8859-9', 'latin-5': 'iso-8859-9', 'latin_6': 'iso-8859-10', 'latin-6': 'iso-8859-10', 'latin_7': 'iso-8859-13', 'latin-7': 'iso-8859-13', 'latin_8': 'iso-8859-14', 'latin-8': 'iso-8859-14', 'latin_9': 'iso-8859-15', 'latin-9': 'iso-8859-15', 'cp949': 'ks_c_5601-1987', 'euc_jp': 'euc-jp', 'euc_kr': 'euc-kr', 'ascii': 'us-ascii', } # Map charsets to their Unicode codec strings. CODEC_MAP = { 'gb2312': 'eucgb2312_cn', 'big5': 'big5_tw', # Hack: We don't want *any* conversion for stuff marked us-ascii, as all # sorts of garbage might be sent to us in the guise of 7-bit us-ascii. # Let that stuff pass through without conversion to/from Unicode. 'us-ascii': None, } # Convenience functions for extending the above mappings def add_charset(charset, header_enc=None, body_enc=None, output_charset=None): """Add character set properties to the global registry. charset is the input character set, and must be the canonical name of a character set. Optional header_enc and body_enc is either Charset.QP for quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for the shortest of qp or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. It describes how message headers and message bodies in the input charset are to be encoded. Default is no encoding. Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input. Both input_charset and output_charset must have Unicode codec entries in the module's charset-to-codec mapping; use add_codec(charset, codecname) to add codecs the module does not know about. See the codecs module's documentation for more information. """ if body_enc == SHORTEST: raise ValueError('SHORTEST not allowed for body_enc') CHARSETS[charset] = (header_enc, body_enc, output_charset) def add_alias(alias, canonical): """Add a character set alias. alias is the alias name, e.g. latin-1 canonical is the character set's canonical name, e.g. iso-8859-1 """ ALIASES[alias] = canonical def add_codec(charset, codecname): """Add a codec that map characters in the given charset to/from Unicode. charset is the canonical name of a character set. codecname is the name of a Python codec, as appropriate for the second argument to the unicode() built-in, or to the encode() method of a Unicode string. """ CODEC_MAP[charset] = codecname class Charset: """Map character sets to their email properties. This class provides information about the requirements imposed on email for a specific character set. It also provides convenience routines for converting between character sets, given the availability of the applicable codecs. Given a character set, it will do its best to provide information on how to use that character set in an email in an RFC-compliant way. Certain character sets must be encoded with quoted-printable or base64 when used in email headers or bodies. Certain character sets must be converted outright, and are not allowed in email. Instances of this module expose the following information about a character set: input_charset: The initial character set specified. Common aliases are converted to their `official' email names (e.g. latin_1 is converted to iso-8859-1). Defaults to 7-bit us-ascii. header_encoding: If the character set must be encoded before it can be used in an email header, this attribute will be set to Charset.QP (for quoted-printable), Charset.BASE64 (for base64 encoding), or Charset.SHORTEST for the shortest of QP or BASE64 encoding. Otherwise, it will be None. body_encoding: Same as header_encoding, but describes the encoding for the mail message's body, which indeed may be different than the header encoding. Charset.SHORTEST is not allowed for body_encoding. output_charset: Some character sets must be converted before the can be used in email headers or bodies. If the input_charset is one of them, this attribute will contain the name of the charset output will be converted to. Otherwise, it will be None. input_codec: The name of the Python codec used to convert the input_charset to Unicode. If no conversion codec is necessary, this attribute will be None. output_codec: The name of the Python codec used to convert Unicode to the output_charset. If no conversion codec is necessary, this attribute will have the same value as the input_codec. """ def __init__(self, input_charset=DEFAULT_CHARSET): # RFC 2046, $4.1.2 says charsets are not case sensitive. We coerce to # unicode because its .lower() is locale insensitive. If the argument # is already a unicode, we leave it at that, but ensure that the # charset is ASCII, as the standard (RFC XXX) requires. try: if isinstance(input_charset, unicode): input_charset.encode('ascii') else: input_charset = unicode(input_charset, 'ascii') except UnicodeError: raise errors.CharsetError(input_charset) input_charset = input_charset.lower() # Set the input charset after filtering through the aliases self.input_charset = ALIASES.get(input_charset, input_charset) # We can try to guess which encoding and conversion to use by the # charset_map dictionary. Try that first, but let the user override # it. henc, benc, conv = CHARSETS.get(self.input_charset, (SHORTEST, BASE64, None)) if not conv: conv = self.input_charset # Set the attributes, allowing the arguments to override the default. self.header_encoding = henc self.body_encoding = benc self.output_charset = ALIASES.get(conv, conv) # Now set the codecs. If one isn't defined for input_charset, # guess and try a Unicode codec with the same name as input_codec. self.input_codec = CODEC_MAP.get(self.input_charset, self.input_charset) self.output_codec = CODEC_MAP.get(self.output_charset, self.output_charset) def __str__(self): return self.input_charset.lower() __repr__ = __str__ def __eq__(self, other): return str(self) == str(other).lower() def __ne__(self, other): return not self.__eq__(other) def get_body_encoding(self): """Return the content-transfer-encoding used for body encoding. This is either the string `quoted-printable' or `base64' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate. Returns "quoted-printable" if self.body_encoding is QP. Returns "base64" if self.body_encoding is BASE64. Returns "7bit" otherwise. """ assert self.body_encoding <> SHORTEST if self.body_encoding == QP: return 'quoted-printable' elif self.body_encoding == BASE64: return 'base64' else: return encode_7or8bit def convert(self, s): """Convert a string from the input_codec to the output_codec.""" if self.input_codec <> self.output_codec: return unicode(s, self.input_codec).encode(self.output_codec) else: return s def to_splittable(self, s): """Convert a possibly multibyte string to a safely splittable format. Uses the input_codec to try and convert the string to Unicode, so it can be safely split on character boundaries (even for multibyte characters). Returns the string as-is if it isn't known how to convert it to Unicode with the input_charset. Characters that could not be converted to Unicode will be replaced with the Unicode replacement character U+FFFD. """ if isinstance(s, unicode) or self.input_codec is None: return s try: return unicode(s, self.input_codec, 'replace') except LookupError: # Input codec not installed on system, so return the original # string unchanged. return s def from_splittable(self, ustr, to_output=True): """Convert a splittable string back into an encoded string. Uses the proper codec to try and convert the string from Unicode back into an encoded format. Return the string as-is if it is not Unicode, or if it could not be converted from Unicode. Characters that could not be converted from Unicode will be replaced with an appropriate character (usually '?'). If to_output is True (the default), uses output_codec to convert to an encoded format. If to_output is False, uses input_codec. """ if to_output: codec = self.output_codec else: codec = self.input_codec if not isinstance(ustr, unicode) or codec is None: return ustr try: return ustr.encode(codec, 'replace') except LookupError: # Output codec not installed return ustr def get_output_charset(self): """Return the output character set. This is self.output_charset if that is not None, otherwise it is self.input_charset. """ return self.output_charset or self.input_charset def encoded_header_len(self, s): """Return the length of the encoded header string.""" cset = self.get_output_charset() # The len(s) of a 7bit encoding is len(s) if self.header_encoding == BASE64: return email.base64mime.base64_len(s) + len(cset) + MISC_LEN elif self.header_encoding == QP: return email.quoprimime.header_quopri_len(s) + len(cset) + MISC_LEN elif self.header_encoding == SHORTEST: lenb64 = email.base64mime.base64_len(s) lenqp = email.quoprimime.header_quopri_len(s) return min(lenb64, lenqp) + len(cset) + MISC_LEN else: return len(s) def header_encode(self, s, convert=False): """Header-encode a string, optionally converting it to output_charset. If convert is True, the string will be converted from the input charset to the output charset automatically. This is not useful for multibyte character sets, which have line length issues (multibyte characters must be split on a character, not a byte boundary); use the high-level Header class to deal with these issues. convert defaults to False. The type of encoding (base64 or quoted-printable) will be based on self.header_encoding. """ cset = self.get_output_charset() if convert: s = self.convert(s) # 7bit/8bit encodings return the string unchanged (modulo conversions) if self.header_encoding == BASE64: return email.base64mime.header_encode(s, cset) elif self.header_encoding == QP: return email.quoprimime.header_encode(s, cset, maxlinelen=None) elif self.header_encoding == SHORTEST: lenb64 = email.base64mime.base64_len(s) lenqp = email.quoprimime.header_quopri_len(s) if lenb64 < lenqp: return email.base64mime.header_encode(s, cset) else: return email.quoprimime.header_encode(s, cset, maxlinelen=None) else: return s def body_encode(self, s, convert=True): """Body-encode a string and convert it to output_charset. If convert is True (the default), the string will be converted from the input charset to output charset automatically. Unlike header_encode(), there are no issues with byte boundaries and multibyte charsets in email bodies, so this is usually pretty safe. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding. """ if convert: s = self.convert(s) # 7bit/8bit encodings return the string unchanged (module conversions) if self.body_encoding is BASE64: return email.base64mime.body_encode(s) elif self.body_encoding is QP: return email.quoprimime.body_encode(s) else: return s
zephyrplugins/zephyr
zephyr.plugin.jython/jython2.5.2rc3/Lib/email/charset.py
Python
epl-1.0
15,684
// $Id: imce_wysiwyg.js,v 1.3.4.1 2010/02/21 00:07:04 sun Exp $ /** * Wysiwyg API integration helper function. */ function imceImageBrowser(field_name, url, type, win) { // TinyMCE. if (win !== 'undefined') { win.open(Drupal.settings.imce.url + encodeURIComponent(field_name), '', 'width=760,height=560,resizable=1'); } } /** * CKeditor integration. */ var imceCkeditSendTo = function (file, win) { var parts = /\?(?:.*&)?CKEditorFuncNum=(\d+)(?:&|$)/.exec(win.location.href); if (parts && parts.length > 1) { CKEDITOR.tools.callFunction(parts[1], file.url); win.close(); } else { throw 'CKEditorFuncNum parameter not found or invalid: ' + win.location.href; } };
MarleneWilliams/drupal-6-gatewaychurch
sites/all/new-modules/imce_wysiwyg/js/imce_wysiwyg.js
JavaScript
gpl-2.0
702
require File.expand_path('../../../spec_helper', __FILE__) ruby_version_is "1.9" do describe "Dir#to_path" do it "needs to be reviewed for spec completeness" end end
takano32/rubinius
spec/ruby/core/dir/to_path_spec.rb
Ruby
bsd-3-clause
175
/* * * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package main import ( "flag" "fmt" "io" "net" "strconv" "time" "github.com/coreos/etcd/Godeps/_workspace/src/github.com/golang/protobuf/proto" "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context" "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc" "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc/credentials" "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc/grpclog" testpb "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc/interop/grpc_testing" ) var ( useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP") certFile = flag.String("tls_cert_file", "testdata/server1.pem", "The TLS cert file") keyFile = flag.String("tls_key_file", "testdata/server1.key", "The TLS key file") port = flag.Int("port", 10000, "The server port") ) type testServer struct { } func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { return new(testpb.Empty), nil } func newPayload(t testpb.PayloadType, size int32) (*testpb.Payload, error) { if size < 0 { return nil, fmt.Errorf("requested a response with invalid length %d", size) } body := make([]byte, size) switch t { case testpb.PayloadType_COMPRESSABLE: case testpb.PayloadType_UNCOMPRESSABLE: return nil, fmt.Errorf("payloadType UNCOMPRESSABLE is not supported") default: return nil, fmt.Errorf("unsupported payload type: %d", t) } return &testpb.Payload{ Type: t.Enum(), Body: body, }, nil } func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { pl, err := newPayload(in.GetResponseType(), in.GetResponseSize()) if err != nil { return nil, err } return &testpb.SimpleResponse{ Payload: pl, }, nil } func (s *testServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error { cs := args.GetResponseParameters() for _, c := range cs { if us := c.GetIntervalUs(); us > 0 { time.Sleep(time.Duration(us) * time.Microsecond) } pl, err := newPayload(args.GetResponseType(), c.GetSize()) if err != nil { return err } if err := stream.Send(&testpb.StreamingOutputCallResponse{ Payload: pl, }); err != nil { return err } } return nil } func (s *testServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error { var sum int for { in, err := stream.Recv() if err == io.EOF { return stream.SendAndClose(&testpb.StreamingInputCallResponse{ AggregatedPayloadSize: proto.Int32(int32(sum)), }) } if err != nil { return err } p := in.GetPayload().GetBody() sum += len(p) } } func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { for { in, err := stream.Recv() if err == io.EOF { // read done. return nil } if err != nil { return err } cs := in.GetResponseParameters() for _, c := range cs { if us := c.GetIntervalUs(); us > 0 { time.Sleep(time.Duration(us) * time.Microsecond) } pl, err := newPayload(in.GetResponseType(), c.GetSize()) if err != nil { return err } if err := stream.Send(&testpb.StreamingOutputCallResponse{ Payload: pl, }); err != nil { return err } } } } func (s *testServer) HalfDuplexCall(stream testpb.TestService_HalfDuplexCallServer) error { var msgBuf []*testpb.StreamingOutputCallRequest for { in, err := stream.Recv() if err == io.EOF { // read done. break } if err != nil { return err } msgBuf = append(msgBuf, in) } for _, m := range msgBuf { cs := m.GetResponseParameters() for _, c := range cs { if us := c.GetIntervalUs(); us > 0 { time.Sleep(time.Duration(us) * time.Microsecond) } pl, err := newPayload(m.GetResponseType(), c.GetSize()) if err != nil { return err } if err := stream.Send(&testpb.StreamingOutputCallResponse{ Payload: pl, }); err != nil { return err } } } return nil } func main() { flag.Parse() p := strconv.Itoa(*port) lis, err := net.Listen("tcp", ":"+p) if err != nil { grpclog.Fatalf("failed to listen: %v", err) } var opts []grpc.ServerOption if *useTLS { creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile) if err != nil { grpclog.Fatalf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } server := grpc.NewServer(opts...) testpb.RegisterTestServiceServer(server, &testServer{}) server.Serve(lis) }
KeyTalk/ApplicationInterfaceGateway
vendor/src/github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc/interop/server/server.go
GO
bsd-3-clause
6,144
/* * 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.test; import junit.framework.TestCase; /** * These inner classes all fail the NamingConventionsCheck. They have to live in the tests or else they won't be scanned. */ public class NamingConventionsCheckBadClasses { public static final class NotImplementingTests { } public static final class WrongName extends UnitTestCase { /* * Dummy test so the tests pass. We do this *and* skip the tests so anyone who jumps back to a branch without these tests can still * compile without a failure. That is because clean doesn't actually clean these.... */ public void testDummy() {} } public abstract static class DummyAbstractTests extends UnitTestCase { } public interface DummyInterfaceTests { } public static final class InnerTests extends UnitTestCase { public void testDummy() {} } public static final class WrongNameTheSecond extends UnitTestCase { public void testDummy() {} } public static final class PlainUnit extends TestCase { public void testDummy() {} } public abstract static class UnitTestCase extends TestCase { } public abstract static class IntegTestCase extends UnitTestCase { } }
strahanjen/strahanjen.github.io
elasticsearch-master/buildSrc/src/test/java/org/elasticsearch/test/NamingConventionsCheckBadClasses.java
Java
bsd-3-clause
2,059
/****************************************************************************** * * Copyright(c) 2009-2010 Realtek Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * The full GNU General Public License is included in this distribution in the * file called LICENSE. * * Contact Information: * wlanfae <wlanfae@realtek.com> * Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park, * Hsinchu 300, Taiwan. * * Larry Finger <Larry.Finger@lwfinger.net> * *****************************************************************************/ #include "../wifi.h" #include "../pci.h" #include "../ps.h" #include "reg.h" #include "def.h" #include "phy.h" #include "rf.h" #include "dm.h" #include "table.h" u32 rtl92cu_phy_query_rf_reg(struct ieee80211_hw *hw, enum radio_path rfpath, u32 regaddr, u32 bitmask) { struct rtl_priv *rtlpriv = rtl_priv(hw); u32 original_value, readback_value, bitshift; struct rtl_phy *rtlphy = &(rtlpriv->phy); RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE, ("regaddr(%#x), " "rfpath(%#x), bitmask(%#x)\n", regaddr, rfpath, bitmask)); if (rtlphy->rf_mode != RF_OP_BY_FW) { original_value = _rtl92c_phy_rf_serial_read(hw, rfpath, regaddr); } else { original_value = _rtl92c_phy_fw_rf_serial_read(hw, rfpath, regaddr); } bitshift = _rtl92c_phy_calculate_bit_shift(bitmask); readback_value = (original_value & bitmask) >> bitshift; RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE, ("regaddr(%#x), rfpath(%#x), " "bitmask(%#x), original_value(%#x)\n", regaddr, rfpath, bitmask, original_value)); return readback_value; } void rtl92cu_phy_set_rf_reg(struct ieee80211_hw *hw, enum radio_path rfpath, u32 regaddr, u32 bitmask, u32 data) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_phy *rtlphy = &(rtlpriv->phy); u32 original_value, bitshift; RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE, ("regaddr(%#x), bitmask(%#x), data(%#x), rfpath(%#x)\n", regaddr, bitmask, data, rfpath)); if (rtlphy->rf_mode != RF_OP_BY_FW) { if (bitmask != RFREG_OFFSET_MASK) { original_value = _rtl92c_phy_rf_serial_read(hw, rfpath, regaddr); bitshift = _rtl92c_phy_calculate_bit_shift(bitmask); data = ((original_value & (~bitmask)) | (data << bitshift)); } _rtl92c_phy_rf_serial_write(hw, rfpath, regaddr, data); } else { if (bitmask != RFREG_OFFSET_MASK) { original_value = _rtl92c_phy_fw_rf_serial_read(hw, rfpath, regaddr); bitshift = _rtl92c_phy_calculate_bit_shift(bitmask); data = ((original_value & (~bitmask)) | (data << bitshift)); } _rtl92c_phy_fw_rf_serial_write(hw, rfpath, regaddr, data); } RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE, ("regaddr(%#x), " "bitmask(%#x), data(%#x), rfpath(%#x)\n", regaddr, bitmask, data, rfpath)); } bool rtl92cu_phy_mac_config(struct ieee80211_hw *hw) { bool rtstatus; struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw)); bool is92c = IS_92C_SERIAL(rtlhal->version); rtstatus = _rtl92cu_phy_config_mac_with_headerfile(hw); if (is92c && IS_HARDWARE_TYPE_8192CE(rtlhal)) rtl_write_byte(rtlpriv, 0x14, 0x71); return rtstatus; } bool rtl92cu_phy_bb_config(struct ieee80211_hw *hw) { bool rtstatus = true; struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw)); u16 regval; u8 b_reg_hwparafile = 1; _rtl92c_phy_init_bb_rf_register_definition(hw); regval = rtl_read_word(rtlpriv, REG_SYS_FUNC_EN); rtl_write_word(rtlpriv, REG_SYS_FUNC_EN, regval | BIT(13) | BIT(0) | BIT(1)); rtl_write_byte(rtlpriv, REG_AFE_PLL_CTRL, 0x83); rtl_write_byte(rtlpriv, REG_AFE_PLL_CTRL + 1, 0xdb); rtl_write_byte(rtlpriv, REG_RF_CTRL, RF_EN | RF_RSTB | RF_SDMRSTB); if (IS_HARDWARE_TYPE_8192CE(rtlhal)) { rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN, FEN_PPLL | FEN_PCIEA | FEN_DIO_PCIE | FEN_BB_GLB_RSTn | FEN_BBRSTB); } else if (IS_HARDWARE_TYPE_8192CU(rtlhal)) { rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN, FEN_USBA | FEN_USBD | FEN_BB_GLB_RSTn | FEN_BBRSTB); rtl_write_byte(rtlpriv, REG_LDOHCI12_CTRL, 0x0f); } rtl_write_byte(rtlpriv, REG_AFE_XTAL_CTRL + 1, 0x80); if (b_reg_hwparafile == 1) rtstatus = _rtl92c_phy_bb8192c_config_parafile(hw); return rtstatus; } bool _rtl92cu_phy_config_mac_with_headerfile(struct ieee80211_hw *hw) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_phy *rtlphy = &(rtlpriv->phy); u32 i; u32 arraylength; u32 *ptrarray; RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, ("Read Rtl819XMACPHY_Array\n")); arraylength = rtlphy->hwparam_tables[MAC_REG].length ; ptrarray = rtlphy->hwparam_tables[MAC_REG].pdata; RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, ("Img:RTL8192CEMAC_2T_ARRAY\n")); for (i = 0; i < arraylength; i = i + 2) rtl_write_byte(rtlpriv, ptrarray[i], (u8) ptrarray[i + 1]); return true; } bool _rtl92cu_phy_config_bb_with_headerfile(struct ieee80211_hw *hw, u8 configtype) { int i; u32 *phy_regarray_table; u32 *agctab_array_table; u16 phy_reg_arraylen, agctab_arraylen; struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw)); struct rtl_phy *rtlphy = &(rtlpriv->phy); if (IS_92C_SERIAL(rtlhal->version)) { agctab_arraylen = rtlphy->hwparam_tables[AGCTAB_2T].length; agctab_array_table = rtlphy->hwparam_tables[AGCTAB_2T].pdata; phy_reg_arraylen = rtlphy->hwparam_tables[PHY_REG_2T].length; phy_regarray_table = rtlphy->hwparam_tables[PHY_REG_2T].pdata; } else { agctab_arraylen = rtlphy->hwparam_tables[AGCTAB_1T].length; agctab_array_table = rtlphy->hwparam_tables[AGCTAB_1T].pdata; phy_reg_arraylen = rtlphy->hwparam_tables[PHY_REG_1T].length; phy_regarray_table = rtlphy->hwparam_tables[PHY_REG_1T].pdata; } if (configtype == BASEBAND_CONFIG_PHY_REG) { for (i = 0; i < phy_reg_arraylen; i = i + 2) { if (phy_regarray_table[i] == 0xfe) mdelay(50); else if (phy_regarray_table[i] == 0xfd) mdelay(5); else if (phy_regarray_table[i] == 0xfc) mdelay(1); else if (phy_regarray_table[i] == 0xfb) udelay(50); else if (phy_regarray_table[i] == 0xfa) udelay(5); else if (phy_regarray_table[i] == 0xf9) udelay(1); rtl_set_bbreg(hw, phy_regarray_table[i], MASKDWORD, phy_regarray_table[i + 1]); udelay(1); RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, ("The phy_regarray_table[0] is %x" " Rtl819XPHY_REGArray[1] is %x\n", phy_regarray_table[i], phy_regarray_table[i + 1])); } } else if (configtype == BASEBAND_CONFIG_AGC_TAB) { for (i = 0; i < agctab_arraylen; i = i + 2) { rtl_set_bbreg(hw, agctab_array_table[i], MASKDWORD, agctab_array_table[i + 1]); udelay(1); RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, ("The agctab_array_table[0] is " "%x Rtl819XPHY_REGArray[1] is %x\n", agctab_array_table[i], agctab_array_table[i + 1])); } } return true; } bool _rtl92cu_phy_config_bb_with_pgheaderfile(struct ieee80211_hw *hw, u8 configtype) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_phy *rtlphy = &(rtlpriv->phy); int i; u32 *phy_regarray_table_pg; u16 phy_regarray_pg_len; rtlphy->pwrgroup_cnt = 0; phy_regarray_pg_len = rtlphy->hwparam_tables[PHY_REG_PG].length; phy_regarray_table_pg = rtlphy->hwparam_tables[PHY_REG_PG].pdata; if (configtype == BASEBAND_CONFIG_PHY_REG) { for (i = 0; i < phy_regarray_pg_len; i = i + 3) { if (phy_regarray_table_pg[i] == 0xfe) mdelay(50); else if (phy_regarray_table_pg[i] == 0xfd) mdelay(5); else if (phy_regarray_table_pg[i] == 0xfc) mdelay(1); else if (phy_regarray_table_pg[i] == 0xfb) udelay(50); else if (phy_regarray_table_pg[i] == 0xfa) udelay(5); else if (phy_regarray_table_pg[i] == 0xf9) udelay(1); _rtl92c_store_pwrIndex_diffrate_offset(hw, phy_regarray_table_pg[i], phy_regarray_table_pg[i + 1], phy_regarray_table_pg[i + 2]); } } else { RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE, ("configtype != BaseBand_Config_PHY_REG\n")); } return true; } bool rtl92cu_phy_config_rf_with_headerfile(struct ieee80211_hw *hw, enum radio_path rfpath) { int i; u32 *radioa_array_table; u32 *radiob_array_table; u16 radioa_arraylen, radiob_arraylen; struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw)); struct rtl_phy *rtlphy = &(rtlpriv->phy); if (IS_92C_SERIAL(rtlhal->version)) { radioa_arraylen = rtlphy->hwparam_tables[RADIOA_2T].length; radioa_array_table = rtlphy->hwparam_tables[RADIOA_2T].pdata; radiob_arraylen = rtlphy->hwparam_tables[RADIOB_2T].length; radiob_array_table = rtlphy->hwparam_tables[RADIOB_2T].pdata; RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, ("Radio_A:RTL8192CERADIOA_2TARRAY\n")); RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, ("Radio_B:RTL8192CE_RADIOB_2TARRAY\n")); } else { radioa_arraylen = rtlphy->hwparam_tables[RADIOA_1T].length; radioa_array_table = rtlphy->hwparam_tables[RADIOA_1T].pdata; radiob_arraylen = rtlphy->hwparam_tables[RADIOB_1T].length; radiob_array_table = rtlphy->hwparam_tables[RADIOB_1T].pdata; RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, ("Radio_A:RTL8192CE_RADIOA_1TARRAY\n")); RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, ("Radio_B:RTL8192CE_RADIOB_1TARRAY\n")); } RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, ("Radio No %x\n", rfpath)); switch (rfpath) { case RF90_PATH_A: for (i = 0; i < radioa_arraylen; i = i + 2) { if (radioa_array_table[i] == 0xfe) mdelay(50); else if (radioa_array_table[i] == 0xfd) mdelay(5); else if (radioa_array_table[i] == 0xfc) mdelay(1); else if (radioa_array_table[i] == 0xfb) udelay(50); else if (radioa_array_table[i] == 0xfa) udelay(5); else if (radioa_array_table[i] == 0xf9) udelay(1); else { rtl_set_rfreg(hw, rfpath, radioa_array_table[i], RFREG_OFFSET_MASK, radioa_array_table[i + 1]); udelay(1); } } break; case RF90_PATH_B: for (i = 0; i < radiob_arraylen; i = i + 2) { if (radiob_array_table[i] == 0xfe) { mdelay(50); } else if (radiob_array_table[i] == 0xfd) mdelay(5); else if (radiob_array_table[i] == 0xfc) mdelay(1); else if (radiob_array_table[i] == 0xfb) udelay(50); else if (radiob_array_table[i] == 0xfa) udelay(5); else if (radiob_array_table[i] == 0xf9) udelay(1); else { rtl_set_rfreg(hw, rfpath, radiob_array_table[i], RFREG_OFFSET_MASK, radiob_array_table[i + 1]); udelay(1); } } break; case RF90_PATH_C: RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, ("switch case not process\n")); break; case RF90_PATH_D: RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, ("switch case not process\n")); break; } return true; } void rtl92cu_phy_set_bw_mode_callback(struct ieee80211_hw *hw) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw)); struct rtl_phy *rtlphy = &(rtlpriv->phy); struct rtl_mac *mac = rtl_mac(rtl_priv(hw)); u8 reg_bw_opmode; u8 reg_prsr_rsc; RT_TRACE(rtlpriv, COMP_SCAN, DBG_TRACE, ("Switch to %s bandwidth\n", rtlphy->current_chan_bw == HT_CHANNEL_WIDTH_20 ? "20MHz" : "40MHz")) if (is_hal_stop(rtlhal)) { rtlphy->set_bwmode_inprogress = false; return; } reg_bw_opmode = rtl_read_byte(rtlpriv, REG_BWOPMODE); reg_prsr_rsc = rtl_read_byte(rtlpriv, REG_RRSR + 2); switch (rtlphy->current_chan_bw) { case HT_CHANNEL_WIDTH_20: reg_bw_opmode |= BW_OPMODE_20MHZ; rtl_write_byte(rtlpriv, REG_BWOPMODE, reg_bw_opmode); break; case HT_CHANNEL_WIDTH_20_40: reg_bw_opmode &= ~BW_OPMODE_20MHZ; rtl_write_byte(rtlpriv, REG_BWOPMODE, reg_bw_opmode); reg_prsr_rsc = (reg_prsr_rsc & 0x90) | (mac->cur_40_prime_sc << 5); rtl_write_byte(rtlpriv, REG_RRSR + 2, reg_prsr_rsc); break; default: RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, ("unknown bandwidth: %#X\n", rtlphy->current_chan_bw)); break; } switch (rtlphy->current_chan_bw) { case HT_CHANNEL_WIDTH_20: rtl_set_bbreg(hw, RFPGA0_RFMOD, BRFMOD, 0x0); rtl_set_bbreg(hw, RFPGA1_RFMOD, BRFMOD, 0x0); rtl_set_bbreg(hw, RFPGA0_ANALOGPARAMETER2, BIT(10), 1); break; case HT_CHANNEL_WIDTH_20_40: rtl_set_bbreg(hw, RFPGA0_RFMOD, BRFMOD, 0x1); rtl_set_bbreg(hw, RFPGA1_RFMOD, BRFMOD, 0x1); rtl_set_bbreg(hw, RCCK0_SYSTEM, BCCK_SIDEBAND, (mac->cur_40_prime_sc >> 1)); rtl_set_bbreg(hw, ROFDM1_LSTF, 0xC00, mac->cur_40_prime_sc); rtl_set_bbreg(hw, RFPGA0_ANALOGPARAMETER2, BIT(10), 0); rtl_set_bbreg(hw, 0x818, (BIT(26) | BIT(27)), (mac->cur_40_prime_sc == HAL_PRIME_CHNL_OFFSET_LOWER) ? 2 : 1); break; default: RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, ("unknown bandwidth: %#X\n", rtlphy->current_chan_bw)); break; } rtl92cu_phy_rf6052_set_bandwidth(hw, rtlphy->current_chan_bw); rtlphy->set_bwmode_inprogress = false; RT_TRACE(rtlpriv, COMP_SCAN, DBG_TRACE, ("<==\n")); } void rtl92cu_bb_block_on(struct ieee80211_hw *hw) { struct rtl_priv *rtlpriv = rtl_priv(hw); mutex_lock(&rtlpriv->io.bb_mutex); rtl_set_bbreg(hw, RFPGA0_RFMOD, BCCKEN, 0x1); rtl_set_bbreg(hw, RFPGA0_RFMOD, BOFDMEN, 0x1); mutex_unlock(&rtlpriv->io.bb_mutex); } void _rtl92cu_phy_lc_calibrate(struct ieee80211_hw *hw, bool is2t) { u8 tmpreg; u32 rf_a_mode = 0, rf_b_mode = 0, lc_cal; struct rtl_priv *rtlpriv = rtl_priv(hw); tmpreg = rtl_read_byte(rtlpriv, 0xd03); if ((tmpreg & 0x70) != 0) rtl_write_byte(rtlpriv, 0xd03, tmpreg & 0x8F); else rtl_write_byte(rtlpriv, REG_TXPAUSE, 0xFF); if ((tmpreg & 0x70) != 0) { rf_a_mode = rtl_get_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS); if (is2t) rf_b_mode = rtl_get_rfreg(hw, RF90_PATH_B, 0x00, MASK12BITS); rtl_set_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS, (rf_a_mode & 0x8FFFF) | 0x10000); if (is2t) rtl_set_rfreg(hw, RF90_PATH_B, 0x00, MASK12BITS, (rf_b_mode & 0x8FFFF) | 0x10000); } lc_cal = rtl_get_rfreg(hw, RF90_PATH_A, 0x18, MASK12BITS); rtl_set_rfreg(hw, RF90_PATH_A, 0x18, MASK12BITS, lc_cal | 0x08000); mdelay(100); if ((tmpreg & 0x70) != 0) { rtl_write_byte(rtlpriv, 0xd03, tmpreg); rtl_set_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS, rf_a_mode); if (is2t) rtl_set_rfreg(hw, RF90_PATH_B, 0x00, MASK12BITS, rf_b_mode); } else { rtl_write_byte(rtlpriv, REG_TXPAUSE, 0x00); } } static bool _rtl92cu_phy_set_rf_power_state(struct ieee80211_hw *hw, enum rf_pwrstate rfpwr_state) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw); struct rtl_mac *mac = rtl_mac(rtl_priv(hw)); struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw)); bool bresult = true; u8 i, queue_id; struct rtl8192_tx_ring *ring = NULL; switch (rfpwr_state) { case ERFON: if ((ppsc->rfpwr_state == ERFOFF) && RT_IN_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC)) { bool rtstatus; u32 InitializeCount = 0; do { InitializeCount++; RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG, ("IPS Set eRf nic enable\n")); rtstatus = rtl_ps_enable_nic(hw); } while ((rtstatus != true) && (InitializeCount < 10)); RT_CLEAR_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC); } else { RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG, ("Set ERFON sleeped:%d ms\n", jiffies_to_msecs(jiffies - ppsc-> last_sleep_jiffies))); ppsc->last_awake_jiffies = jiffies; rtl92ce_phy_set_rf_on(hw); } if (mac->link_state == MAC80211_LINKED) { rtlpriv->cfg->ops->led_control(hw, LED_CTL_LINK); } else { rtlpriv->cfg->ops->led_control(hw, LED_CTL_NO_LINK); } break; case ERFOFF: for (queue_id = 0, i = 0; queue_id < RTL_PCI_MAX_TX_QUEUE_COUNT;) { ring = &pcipriv->dev.tx_ring[queue_id]; if (skb_queue_len(&ring->queue) == 0 || queue_id == BEACON_QUEUE) { queue_id++; continue; } else { RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING, ("eRf Off/Sleep: %d times " "TcbBusyQueue[%d] " "=%d before doze!\n", (i + 1), queue_id, skb_queue_len(&ring->queue))); udelay(10); i++; } if (i >= MAX_DOZE_WAITING_TIMES_9x) { RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING, ("\nERFOFF: %d times " "TcbBusyQueue[%d] = %d !\n", MAX_DOZE_WAITING_TIMES_9x, queue_id, skb_queue_len(&ring->queue))); break; } } if (ppsc->reg_rfps_level & RT_RF_OFF_LEVL_HALT_NIC) { RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG, ("IPS Set eRf nic disable\n")); rtl_ps_disable_nic(hw); RT_SET_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC); } else { if (ppsc->rfoff_reason == RF_CHANGE_BY_IPS) { rtlpriv->cfg->ops->led_control(hw, LED_CTL_NO_LINK); } else { rtlpriv->cfg->ops->led_control(hw, LED_CTL_POWER_OFF); } } break; case ERFSLEEP: if (ppsc->rfpwr_state == ERFOFF) return false; for (queue_id = 0, i = 0; queue_id < RTL_PCI_MAX_TX_QUEUE_COUNT;) { ring = &pcipriv->dev.tx_ring[queue_id]; if (skb_queue_len(&ring->queue) == 0) { queue_id++; continue; } else { RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING, ("eRf Off/Sleep: %d times " "TcbBusyQueue[%d] =%d before " "doze!\n", (i + 1), queue_id, skb_queue_len(&ring->queue))); udelay(10); i++; } if (i >= MAX_DOZE_WAITING_TIMES_9x) { RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING, ("\n ERFSLEEP: %d times " "TcbBusyQueue[%d] = %d !\n", MAX_DOZE_WAITING_TIMES_9x, queue_id, skb_queue_len(&ring->queue))); break; } } RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG, ("Set ERFSLEEP awaked:%d ms\n", jiffies_to_msecs(jiffies - ppsc->last_awake_jiffies))); ppsc->last_sleep_jiffies = jiffies; _rtl92c_phy_set_rf_sleep(hw); break; default: RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, ("switch case not process\n")); bresult = false; break; } if (bresult) ppsc->rfpwr_state = rfpwr_state; return bresult; } bool rtl92cu_phy_set_rf_power_state(struct ieee80211_hw *hw, enum rf_pwrstate rfpwr_state) { struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw)); bool bresult = false; if (rfpwr_state == ppsc->rfpwr_state) return bresult; bresult = _rtl92cu_phy_set_rf_power_state(hw, rfpwr_state); return bresult; }
WhiteBearSolutions/WBSAirback
packages/wbsairback-kernel-image/wbsairback-kernel-image-3.2.43/drivers/net/wireless/rtlwifi/rtl8192cu/phy.c
C
apache-2.0
18,974
var WritableStream = require('stream').Writable || require('readable-stream').Writable, inherits = require('util').inherits; var StreamSearch = require('streamsearch'); var PartStream = require('./PartStream'), HeaderParser = require('./HeaderParser'); var B_ONEDASH = new Buffer('-'), B_CRLF = new Buffer('\r\n'); function Dicer(cfg) { if (!(this instanceof Dicer)) return new Dicer(cfg); WritableStream.call(this, cfg); if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) throw new TypeError('Boundary required'); if (typeof cfg.boundary === 'string') this.setBoundary(cfg.boundary); else this._bparser = undefined; this._headerFirst = cfg.headerFirst; var self = this; this._dashes = 0; this._parts = 0; this._finished = false; this._isPreamble = true; this._justMatched = false; this._firstWrite = true; this._inHeader = true; this._part = undefined; this._cb = undefined; this._partOpts = (typeof cfg.partHwm === 'number' ? { highWaterMark: cfg.partHwm } : {}); this._pause = false; this._hparser = new HeaderParser(cfg); this._hparser.on('header', function(header) { self._inHeader = false; self._part.emit('header', header); }); } inherits(Dicer, WritableStream); Dicer.prototype._write = function(data, encoding, cb) { var self = this; if (this._headerFirst && this._isPreamble) { if (!this._part) { this._part = new PartStream(this._partOpts); this.emit('preamble', this._part); } var r = this._hparser.push(data); if (!this._inHeader && r !== undefined && r < data.length) data = data.slice(r); else return cb(); } // allows for "easier" testing if (this._firstWrite) { this._bparser.push(B_CRLF); this._firstWrite = false; } this._bparser.push(data); if (this._pause) this._cb = cb; else cb(); }; Dicer.prototype.reset = function() { this._part = undefined; this._bparser = undefined; this._hparser = undefined; }; Dicer.prototype.setBoundary = function(boundary) { var self = this; this._bparser = new StreamSearch('\r\n--' + boundary); this._bparser.on('info', function(isMatch, data, start, end) { self._oninfo(isMatch, data, start, end); }); }; Dicer.prototype._oninfo = function(isMatch, data, start, end) { var buf, self = this, i = 0, r, shouldWriteMore = true; if (!this._part && this._justMatched && data) { while (this._dashes < 2 && (start + i) < end) { if (data[start + i] === 45) { ++i; ++this._dashes; } else { if (this._dashes) buf = B_ONEDASH; this._dashes = 0; break; } } if (this._dashes === 2) { if ((start + i) < end && this._events.trailer) this.emit('trailer', data.slice(start + i, end)); this.reset(); this._finished = true; //process.nextTick(function() { self.emit('end'); }); } if (this._dashes) return; } if (this._justMatched) this._justMatched = false; if (!this._part) { this._part = new PartStream(this._partOpts); this._part._read = function(n) { if (!self._pause) return; self._pause = false; if (self._cb) { var cb = self._cb; self._cb = undefined; cb(); } }; this.emit(this._isPreamble ? 'preamble' : 'part', this._part); if (!this._isPreamble) this._inHeader = true; } if (data && start < end) { if (this._isPreamble || !this._inHeader) { if (buf) shouldWriteMore = this._part.push(buf); shouldWriteMore = this._part.push(data.slice(start, end)); if (!shouldWriteMore) this._pause = true; } else if (!this._isPreamble && this._inHeader) { if (buf) this._hparser.push(buf); r = this._hparser.push(data.slice(start, end)); if (!this._inHeader && r !== undefined && r < end) this._oninfo(false, data, start + r, end); } } if (isMatch) { this._hparser.reset(); if (this._isPreamble) this._isPreamble = false; else { ++this._parts; this._part.on('end', function() { if (--self._parts === 0 && self._finished) { self._finished = false; self.emit('end'); } }); } this._part.push(null); this._part = undefined; this._justMatched = true; this._dashes = 0; } }; module.exports = Dicer;
kuligowski/ImageGallery
server/node_modules/multer/node_modules/busboy/node_modules/dicer/lib/Dicer.js
JavaScript
mit
4,504
/* * This file is provided under a dual BSD/GPLv2 license. When using or * redistributing this file, you may do so under either license. * * GPL LICENSE SUMMARY * * Copyright(c) 2017 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * BSD LICENSE * * Copyright(c) 2017 Intel Corporation. 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 copy * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation 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. * * Intel PCIe GEN3 NTB Linux driver * */ #include <linux/debugfs.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/random.h> #include <linux/slab.h> #include <linux/ntb.h> #include "ntb_hw_intel.h" #include "ntb_hw_gen1.h" #include "ntb_hw_gen3.h" static int gen3_poll_link(struct intel_ntb_dev *ndev); static const struct intel_ntb_reg gen3_reg = { .poll_link = gen3_poll_link, .link_is_up = xeon_link_is_up, .db_ioread = gen3_db_ioread, .db_iowrite = gen3_db_iowrite, .db_size = sizeof(u32), .ntb_ctl = GEN3_NTBCNTL_OFFSET, .mw_bar = {2, 4}, }; static const struct intel_ntb_alt_reg gen3_pri_reg = { .db_bell = GEN3_EM_DOORBELL_OFFSET, .db_clear = GEN3_IM_INT_STATUS_OFFSET, .db_mask = GEN3_IM_INT_DISABLE_OFFSET, .spad = GEN3_IM_SPAD_OFFSET, }; static const struct intel_ntb_alt_reg gen3_b2b_reg = { .db_bell = GEN3_IM_DOORBELL_OFFSET, .db_clear = GEN3_EM_INT_STATUS_OFFSET, .db_mask = GEN3_EM_INT_DISABLE_OFFSET, .spad = GEN3_B2B_SPAD_OFFSET, }; static const struct intel_ntb_xlat_reg gen3_sec_xlat = { /* .bar0_base = GEN3_EMBAR0_OFFSET, */ .bar2_limit = GEN3_IMBAR1XLMT_OFFSET, .bar2_xlat = GEN3_IMBAR1XBASE_OFFSET, }; static int gen3_poll_link(struct intel_ntb_dev *ndev) { u16 reg_val; int rc; ndev->reg->db_iowrite(ndev->db_link_mask, ndev->self_mmio + ndev->self_reg->db_clear); rc = pci_read_config_word(ndev->ntb.pdev, GEN3_LINK_STATUS_OFFSET, &reg_val); if (rc) return 0; if (reg_val == ndev->lnk_sta) return 0; ndev->lnk_sta = reg_val; return 1; } static int gen3_init_isr(struct intel_ntb_dev *ndev) { int i; /* * The MSIX vectors and the interrupt status bits are not lined up * on Skylake. By default the link status bit is bit 32, however it * is by default MSIX vector0. We need to fixup to line them up. * The vectors at reset is 1-32,0. We need to reprogram to 0-32. */ for (i = 0; i < GEN3_DB_MSIX_VECTOR_COUNT; i++) iowrite8(i, ndev->self_mmio + GEN3_INTVEC_OFFSET + i); /* move link status down one as workaround */ if (ndev->hwerr_flags & NTB_HWERR_MSIX_VECTOR32_BAD) { iowrite8(GEN3_DB_MSIX_VECTOR_COUNT - 2, ndev->self_mmio + GEN3_INTVEC_OFFSET + (GEN3_DB_MSIX_VECTOR_COUNT - 1)); } return ndev_init_isr(ndev, GEN3_DB_MSIX_VECTOR_COUNT, GEN3_DB_MSIX_VECTOR_COUNT, GEN3_DB_MSIX_VECTOR_SHIFT, GEN3_DB_TOTAL_SHIFT); } static int gen3_setup_b2b_mw(struct intel_ntb_dev *ndev, const struct intel_b2b_addr *addr, const struct intel_b2b_addr *peer_addr) { struct pci_dev *pdev; void __iomem *mmio; phys_addr_t bar_addr; pdev = ndev->ntb.pdev; mmio = ndev->self_mmio; /* setup incoming bar limits == base addrs (zero length windows) */ bar_addr = addr->bar2_addr64; iowrite64(bar_addr, mmio + GEN3_IMBAR1XLMT_OFFSET); bar_addr = ioread64(mmio + GEN3_IMBAR1XLMT_OFFSET); dev_dbg(&pdev->dev, "IMBAR1XLMT %#018llx\n", bar_addr); bar_addr = addr->bar4_addr64; iowrite64(bar_addr, mmio + GEN3_IMBAR2XLMT_OFFSET); bar_addr = ioread64(mmio + GEN3_IMBAR2XLMT_OFFSET); dev_dbg(&pdev->dev, "IMBAR2XLMT %#018llx\n", bar_addr); /* zero incoming translation addrs */ iowrite64(0, mmio + GEN3_IMBAR1XBASE_OFFSET); iowrite64(0, mmio + GEN3_IMBAR2XBASE_OFFSET); ndev->peer_mmio = ndev->self_mmio; return 0; } static int gen3_init_ntb(struct intel_ntb_dev *ndev) { int rc; ndev->mw_count = XEON_MW_COUNT; ndev->spad_count = GEN3_SPAD_COUNT; ndev->db_count = GEN3_DB_COUNT; ndev->db_link_mask = GEN3_DB_LINK_BIT; /* DB fixup for using 31 right now */ if (ndev->hwerr_flags & NTB_HWERR_MSIX_VECTOR32_BAD) ndev->db_link_mask |= BIT_ULL(31); switch (ndev->ntb.topo) { case NTB_TOPO_B2B_USD: case NTB_TOPO_B2B_DSD: ndev->self_reg = &gen3_pri_reg; ndev->peer_reg = &gen3_b2b_reg; ndev->xlat_reg = &gen3_sec_xlat; if (ndev->ntb.topo == NTB_TOPO_B2B_USD) { rc = gen3_setup_b2b_mw(ndev, &xeon_b2b_dsd_addr, &xeon_b2b_usd_addr); } else { rc = gen3_setup_b2b_mw(ndev, &xeon_b2b_usd_addr, &xeon_b2b_dsd_addr); } if (rc) return rc; /* Enable Bus Master and Memory Space on the secondary side */ iowrite16(PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER, ndev->self_mmio + GEN3_SPCICMD_OFFSET); break; default: return -EINVAL; } ndev->db_valid_mask = BIT_ULL(ndev->db_count) - 1; ndev->reg->db_iowrite(ndev->db_valid_mask, ndev->self_mmio + ndev->self_reg->db_mask); return 0; } int gen3_init_dev(struct intel_ntb_dev *ndev) { struct pci_dev *pdev; u8 ppd; int rc; pdev = ndev->ntb.pdev; ndev->reg = &gen3_reg; rc = pci_read_config_byte(pdev, XEON_PPD_OFFSET, &ppd); if (rc) return -EIO; ndev->ntb.topo = xeon_ppd_topo(ndev, ppd); dev_dbg(&pdev->dev, "ppd %#x topo %s\n", ppd, ntb_topo_string(ndev->ntb.topo)); if (ndev->ntb.topo == NTB_TOPO_NONE) return -EINVAL; ndev->hwerr_flags |= NTB_HWERR_MSIX_VECTOR32_BAD; rc = gen3_init_ntb(ndev); if (rc) return rc; return gen3_init_isr(ndev); } ssize_t ndev_ntb3_debugfs_read(struct file *filp, char __user *ubuf, size_t count, loff_t *offp) { struct intel_ntb_dev *ndev; void __iomem *mmio; char *buf; size_t buf_size; ssize_t ret, off; union { u64 v64; u32 v32; u16 v16; } u; ndev = filp->private_data; mmio = ndev->self_mmio; buf_size = min(count, 0x800ul); buf = kmalloc(buf_size, GFP_KERNEL); if (!buf) return -ENOMEM; off = 0; off += scnprintf(buf + off, buf_size - off, "NTB Device Information:\n"); off += scnprintf(buf + off, buf_size - off, "Connection Topology -\t%s\n", ntb_topo_string(ndev->ntb.topo)); off += scnprintf(buf + off, buf_size - off, "NTB CTL -\t\t%#06x\n", ndev->ntb_ctl); off += scnprintf(buf + off, buf_size - off, "LNK STA -\t\t%#06x\n", ndev->lnk_sta); if (!ndev->reg->link_is_up(ndev)) off += scnprintf(buf + off, buf_size - off, "Link Status -\t\tDown\n"); else { off += scnprintf(buf + off, buf_size - off, "Link Status -\t\tUp\n"); off += scnprintf(buf + off, buf_size - off, "Link Speed -\t\tPCI-E Gen %u\n", NTB_LNK_STA_SPEED(ndev->lnk_sta)); off += scnprintf(buf + off, buf_size - off, "Link Width -\t\tx%u\n", NTB_LNK_STA_WIDTH(ndev->lnk_sta)); } off += scnprintf(buf + off, buf_size - off, "Memory Window Count -\t%u\n", ndev->mw_count); off += scnprintf(buf + off, buf_size - off, "Scratchpad Count -\t%u\n", ndev->spad_count); off += scnprintf(buf + off, buf_size - off, "Doorbell Count -\t%u\n", ndev->db_count); off += scnprintf(buf + off, buf_size - off, "Doorbell Vector Count -\t%u\n", ndev->db_vec_count); off += scnprintf(buf + off, buf_size - off, "Doorbell Vector Shift -\t%u\n", ndev->db_vec_shift); off += scnprintf(buf + off, buf_size - off, "Doorbell Valid Mask -\t%#llx\n", ndev->db_valid_mask); off += scnprintf(buf + off, buf_size - off, "Doorbell Link Mask -\t%#llx\n", ndev->db_link_mask); off += scnprintf(buf + off, buf_size - off, "Doorbell Mask Cached -\t%#llx\n", ndev->db_mask); u.v64 = ndev_db_read(ndev, mmio + ndev->self_reg->db_mask); off += scnprintf(buf + off, buf_size - off, "Doorbell Mask -\t\t%#llx\n", u.v64); u.v64 = ndev_db_read(ndev, mmio + ndev->self_reg->db_bell); off += scnprintf(buf + off, buf_size - off, "Doorbell Bell -\t\t%#llx\n", u.v64); off += scnprintf(buf + off, buf_size - off, "\nNTB Incoming XLAT:\n"); u.v64 = ioread64(mmio + GEN3_IMBAR1XBASE_OFFSET); off += scnprintf(buf + off, buf_size - off, "IMBAR1XBASE -\t\t%#018llx\n", u.v64); u.v64 = ioread64(mmio + GEN3_IMBAR2XBASE_OFFSET); off += scnprintf(buf + off, buf_size - off, "IMBAR2XBASE -\t\t%#018llx\n", u.v64); u.v64 = ioread64(mmio + GEN3_IMBAR1XLMT_OFFSET); off += scnprintf(buf + off, buf_size - off, "IMBAR1XLMT -\t\t\t%#018llx\n", u.v64); u.v64 = ioread64(mmio + GEN3_IMBAR2XLMT_OFFSET); off += scnprintf(buf + off, buf_size - off, "IMBAR2XLMT -\t\t\t%#018llx\n", u.v64); if (ntb_topo_is_b2b(ndev->ntb.topo)) { off += scnprintf(buf + off, buf_size - off, "\nNTB Outgoing B2B XLAT:\n"); u.v64 = ioread64(mmio + GEN3_EMBAR1XBASE_OFFSET); off += scnprintf(buf + off, buf_size - off, "EMBAR1XBASE -\t\t%#018llx\n", u.v64); u.v64 = ioread64(mmio + GEN3_EMBAR2XBASE_OFFSET); off += scnprintf(buf + off, buf_size - off, "EMBAR2XBASE -\t\t%#018llx\n", u.v64); u.v64 = ioread64(mmio + GEN3_EMBAR1XLMT_OFFSET); off += scnprintf(buf + off, buf_size - off, "EMBAR1XLMT -\t\t%#018llx\n", u.v64); u.v64 = ioread64(mmio + GEN3_EMBAR2XLMT_OFFSET); off += scnprintf(buf + off, buf_size - off, "EMBAR2XLMT -\t\t%#018llx\n", u.v64); off += scnprintf(buf + off, buf_size - off, "\nNTB Secondary BAR:\n"); u.v64 = ioread64(mmio + GEN3_EMBAR0_OFFSET); off += scnprintf(buf + off, buf_size - off, "EMBAR0 -\t\t%#018llx\n", u.v64); u.v64 = ioread64(mmio + GEN3_EMBAR1_OFFSET); off += scnprintf(buf + off, buf_size - off, "EMBAR1 -\t\t%#018llx\n", u.v64); u.v64 = ioread64(mmio + GEN3_EMBAR2_OFFSET); off += scnprintf(buf + off, buf_size - off, "EMBAR2 -\t\t%#018llx\n", u.v64); } off += scnprintf(buf + off, buf_size - off, "\nNTB Statistics:\n"); u.v16 = ioread16(mmio + GEN3_USMEMMISS_OFFSET); off += scnprintf(buf + off, buf_size - off, "Upstream Memory Miss -\t%u\n", u.v16); off += scnprintf(buf + off, buf_size - off, "\nNTB Hardware Errors:\n"); if (!pci_read_config_word(ndev->ntb.pdev, GEN3_DEVSTS_OFFSET, &u.v16)) off += scnprintf(buf + off, buf_size - off, "DEVSTS -\t\t%#06x\n", u.v16); if (!pci_read_config_word(ndev->ntb.pdev, GEN3_LINK_STATUS_OFFSET, &u.v16)) off += scnprintf(buf + off, buf_size - off, "LNKSTS -\t\t%#06x\n", u.v16); if (!pci_read_config_dword(ndev->ntb.pdev, GEN3_UNCERRSTS_OFFSET, &u.v32)) off += scnprintf(buf + off, buf_size - off, "UNCERRSTS -\t\t%#06x\n", u.v32); if (!pci_read_config_dword(ndev->ntb.pdev, GEN3_CORERRSTS_OFFSET, &u.v32)) off += scnprintf(buf + off, buf_size - off, "CORERRSTS -\t\t%#06x\n", u.v32); ret = simple_read_from_buffer(ubuf, count, offp, buf, off); kfree(buf); return ret; } static int intel_ntb3_link_enable(struct ntb_dev *ntb, enum ntb_speed max_speed, enum ntb_width max_width) { struct intel_ntb_dev *ndev; u32 ntb_ctl; ndev = container_of(ntb, struct intel_ntb_dev, ntb); dev_dbg(&ntb->pdev->dev, "Enabling link with max_speed %d max_width %d\n", max_speed, max_width); if (max_speed != NTB_SPEED_AUTO) dev_dbg(&ntb->pdev->dev, "ignoring max_speed %d\n", max_speed); if (max_width != NTB_WIDTH_AUTO) dev_dbg(&ntb->pdev->dev, "ignoring max_width %d\n", max_width); ntb_ctl = ioread32(ndev->self_mmio + ndev->reg->ntb_ctl); ntb_ctl &= ~(NTB_CTL_DISABLE | NTB_CTL_CFG_LOCK); ntb_ctl |= NTB_CTL_P2S_BAR2_SNOOP | NTB_CTL_S2P_BAR2_SNOOP; ntb_ctl |= NTB_CTL_P2S_BAR4_SNOOP | NTB_CTL_S2P_BAR4_SNOOP; iowrite32(ntb_ctl, ndev->self_mmio + ndev->reg->ntb_ctl); return 0; } static int intel_ntb3_mw_set_trans(struct ntb_dev *ntb, int pidx, int idx, dma_addr_t addr, resource_size_t size) { struct intel_ntb_dev *ndev = ntb_ndev(ntb); unsigned long xlat_reg, limit_reg; resource_size_t bar_size, mw_size; void __iomem *mmio; u64 base, limit, reg_val; int bar; if (pidx != NTB_DEF_PEER_IDX) return -EINVAL; if (idx >= ndev->b2b_idx && !ndev->b2b_off) idx += 1; bar = ndev_mw_to_bar(ndev, idx); if (bar < 0) return bar; bar_size = pci_resource_len(ndev->ntb.pdev, bar); if (idx == ndev->b2b_idx) mw_size = bar_size - ndev->b2b_off; else mw_size = bar_size; /* hardware requires that addr is aligned to bar size */ if (addr & (bar_size - 1)) return -EINVAL; /* make sure the range fits in the usable mw size */ if (size > mw_size) return -EINVAL; mmio = ndev->self_mmio; xlat_reg = ndev->xlat_reg->bar2_xlat + (idx * 0x10); limit_reg = ndev->xlat_reg->bar2_limit + (idx * 0x10); base = pci_resource_start(ndev->ntb.pdev, bar); /* Set the limit if supported, if size is not mw_size */ if (limit_reg && size != mw_size) limit = base + size; else limit = base + mw_size; /* set and verify setting the translation address */ iowrite64(addr, mmio + xlat_reg); reg_val = ioread64(mmio + xlat_reg); if (reg_val != addr) { iowrite64(0, mmio + xlat_reg); return -EIO; } dev_dbg(&ntb->pdev->dev, "BAR %d IMBARXBASE: %#Lx\n", bar, reg_val); /* set and verify setting the limit */ iowrite64(limit, mmio + limit_reg); reg_val = ioread64(mmio + limit_reg); if (reg_val != limit) { iowrite64(base, mmio + limit_reg); iowrite64(0, mmio + xlat_reg); return -EIO; } dev_dbg(&ntb->pdev->dev, "BAR %d IMBARXLMT: %#Lx\n", bar, reg_val); /* setup the EP */ limit_reg = ndev->xlat_reg->bar2_limit + (idx * 0x10) + 0x4000; base = ioread64(mmio + GEN3_EMBAR1_OFFSET + (8 * idx)); base &= ~0xf; if (limit_reg && size != mw_size) limit = base + size; else limit = base + mw_size; /* set and verify setting the limit */ iowrite64(limit, mmio + limit_reg); reg_val = ioread64(mmio + limit_reg); if (reg_val != limit) { iowrite64(base, mmio + limit_reg); iowrite64(0, mmio + xlat_reg); return -EIO; } dev_dbg(&ntb->pdev->dev, "BAR %d EMBARXLMT: %#Lx\n", bar, reg_val); return 0; } static int intel_ntb3_peer_db_addr(struct ntb_dev *ntb, phys_addr_t *db_addr, resource_size_t *db_size, u64 *db_data, int db_bit) { phys_addr_t db_addr_base; struct intel_ntb_dev *ndev = ntb_ndev(ntb); if (unlikely(db_bit >= BITS_PER_LONG_LONG)) return -EINVAL; if (unlikely(BIT_ULL(db_bit) & ~ntb_ndev(ntb)->db_valid_mask)) return -EINVAL; ndev_db_addr(ndev, &db_addr_base, db_size, ndev->peer_addr, ndev->peer_reg->db_bell); if (db_addr) { *db_addr = db_addr_base + (db_bit * 4); dev_dbg(&ndev->ntb.pdev->dev, "Peer db addr %llx db bit %d\n", *db_addr, db_bit); } if (db_data) { *db_data = 1; dev_dbg(&ndev->ntb.pdev->dev, "Peer db data %llx db bit %d\n", *db_data, db_bit); } return 0; } static int intel_ntb3_peer_db_set(struct ntb_dev *ntb, u64 db_bits) { struct intel_ntb_dev *ndev = ntb_ndev(ntb); int bit; if (db_bits & ~ndev->db_valid_mask) return -EINVAL; while (db_bits) { bit = __ffs(db_bits); iowrite32(1, ndev->peer_mmio + ndev->peer_reg->db_bell + (bit * 4)); db_bits &= db_bits - 1; } return 0; } static u64 intel_ntb3_db_read(struct ntb_dev *ntb) { struct intel_ntb_dev *ndev = ntb_ndev(ntb); return ndev_db_read(ndev, ndev->self_mmio + ndev->self_reg->db_clear); } static int intel_ntb3_db_clear(struct ntb_dev *ntb, u64 db_bits) { struct intel_ntb_dev *ndev = ntb_ndev(ntb); return ndev_db_write(ndev, db_bits, ndev->self_mmio + ndev->self_reg->db_clear); } const struct ntb_dev_ops intel_ntb3_ops = { .mw_count = intel_ntb_mw_count, .mw_get_align = intel_ntb_mw_get_align, .mw_set_trans = intel_ntb3_mw_set_trans, .peer_mw_count = intel_ntb_peer_mw_count, .peer_mw_get_addr = intel_ntb_peer_mw_get_addr, .link_is_up = intel_ntb_link_is_up, .link_enable = intel_ntb3_link_enable, .link_disable = intel_ntb_link_disable, .db_valid_mask = intel_ntb_db_valid_mask, .db_vector_count = intel_ntb_db_vector_count, .db_vector_mask = intel_ntb_db_vector_mask, .db_read = intel_ntb3_db_read, .db_clear = intel_ntb3_db_clear, .db_set_mask = intel_ntb_db_set_mask, .db_clear_mask = intel_ntb_db_clear_mask, .peer_db_addr = intel_ntb3_peer_db_addr, .peer_db_set = intel_ntb3_peer_db_set, .spad_is_unsafe = intel_ntb_spad_is_unsafe, .spad_count = intel_ntb_spad_count, .spad_read = intel_ntb_spad_read, .spad_write = intel_ntb_spad_write, .peer_spad_addr = intel_ntb_peer_spad_addr, .peer_spad_read = intel_ntb_peer_spad_read, .peer_spad_write = intel_ntb_peer_spad_write, };
BPI-SINOVOIP/BPI-Mainline-kernel
linux-5.4/drivers/ntb/hw/intel/ntb_hw_gen3.c
C
gpl-2.0
18,054
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package workqueue import ( "fmt" "math/rand" "reflect" "testing" "time" "k8s.io/apimachinery/pkg/util/clock" "k8s.io/apimachinery/pkg/util/wait" ) func TestSimpleQueue(t *testing.T) { fakeClock := clock.NewFakeClock(time.Now()) q := NewDelayingQueueWithCustomClock(fakeClock, "") first := "foo" q.AddAfter(first, 50*time.Millisecond) if err := waitForWaitingQueueToFill(q); err != nil { t.Fatalf("unexpected err: %v", err) } if q.Len() != 0 { t.Errorf("should not have added") } fakeClock.Step(60 * time.Millisecond) if err := waitForAdded(q, 1); err != nil { t.Errorf("should have added") } item, _ := q.Get() q.Done(item) // step past the next heartbeat fakeClock.Step(10 * time.Second) err := wait.Poll(1*time.Millisecond, 30*time.Millisecond, func() (done bool, err error) { if q.Len() > 0 { return false, fmt.Errorf("added to queue") } return false, nil }) if err != wait.ErrWaitTimeout { t.Errorf("expected timeout, got: %v", err) } if q.Len() != 0 { t.Errorf("should not have added") } } func TestDeduping(t *testing.T) { fakeClock := clock.NewFakeClock(time.Now()) q := NewDelayingQueueWithCustomClock(fakeClock, "") first := "foo" q.AddAfter(first, 50*time.Millisecond) if err := waitForWaitingQueueToFill(q); err != nil { t.Fatalf("unexpected err: %v", err) } q.AddAfter(first, 70*time.Millisecond) if err := waitForWaitingQueueToFill(q); err != nil { t.Fatalf("unexpected err: %v", err) } if q.Len() != 0 { t.Errorf("should not have added") } // step past the first block, we should receive now fakeClock.Step(60 * time.Millisecond) if err := waitForAdded(q, 1); err != nil { t.Errorf("should have added") } item, _ := q.Get() q.Done(item) // step past the second add fakeClock.Step(20 * time.Millisecond) if q.Len() != 0 { t.Errorf("should not have added") } // test again, but this time the earlier should override q.AddAfter(first, 50*time.Millisecond) q.AddAfter(first, 30*time.Millisecond) if err := waitForWaitingQueueToFill(q); err != nil { t.Fatalf("unexpected err: %v", err) } if q.Len() != 0 { t.Errorf("should not have added") } fakeClock.Step(40 * time.Millisecond) if err := waitForAdded(q, 1); err != nil { t.Errorf("should have added") } item, _ = q.Get() q.Done(item) // step past the second add fakeClock.Step(20 * time.Millisecond) if q.Len() != 0 { t.Errorf("should not have added") } if q.Len() != 0 { t.Errorf("should not have added") } } func TestAddTwoFireEarly(t *testing.T) { fakeClock := clock.NewFakeClock(time.Now()) q := NewDelayingQueueWithCustomClock(fakeClock, "") first := "foo" second := "bar" third := "baz" q.AddAfter(first, 1*time.Second) q.AddAfter(second, 50*time.Millisecond) if err := waitForWaitingQueueToFill(q); err != nil { t.Fatalf("unexpected err: %v", err) } if q.Len() != 0 { t.Errorf("should not have added") } fakeClock.Step(60 * time.Millisecond) if err := waitForAdded(q, 1); err != nil { t.Fatalf("unexpected err: %v", err) } item, _ := q.Get() if !reflect.DeepEqual(item, second) { t.Errorf("expected %v, got %v", second, item) } q.AddAfter(third, 2*time.Second) fakeClock.Step(1 * time.Second) if err := waitForAdded(q, 1); err != nil { t.Fatalf("unexpected err: %v", err) } item, _ = q.Get() if !reflect.DeepEqual(item, first) { t.Errorf("expected %v, got %v", first, item) } fakeClock.Step(2 * time.Second) if err := waitForAdded(q, 1); err != nil { t.Fatalf("unexpected err: %v", err) } item, _ = q.Get() if !reflect.DeepEqual(item, third) { t.Errorf("expected %v, got %v", third, item) } } func TestCopyShifting(t *testing.T) { fakeClock := clock.NewFakeClock(time.Now()) q := NewDelayingQueueWithCustomClock(fakeClock, "") first := "foo" second := "bar" third := "baz" q.AddAfter(first, 1*time.Second) q.AddAfter(second, 500*time.Millisecond) q.AddAfter(third, 250*time.Millisecond) if err := waitForWaitingQueueToFill(q); err != nil { t.Fatalf("unexpected err: %v", err) } if q.Len() != 0 { t.Errorf("should not have added") } fakeClock.Step(2 * time.Second) if err := waitForAdded(q, 3); err != nil { t.Fatalf("unexpected err: %v", err) } actualFirst, _ := q.Get() if !reflect.DeepEqual(actualFirst, third) { t.Errorf("expected %v, got %v", third, actualFirst) } actualSecond, _ := q.Get() if !reflect.DeepEqual(actualSecond, second) { t.Errorf("expected %v, got %v", second, actualSecond) } actualThird, _ := q.Get() if !reflect.DeepEqual(actualThird, first) { t.Errorf("expected %v, got %v", first, actualThird) } } func BenchmarkDelayingQueue_AddAfter(b *testing.B) { fakeClock := clock.NewFakeClock(time.Now()) q := NewDelayingQueueWithCustomClock(fakeClock, "") // Add items for n := 0; n < b.N; n++ { data := fmt.Sprintf("%d", n) q.AddAfter(data, time.Duration(rand.Int63n(int64(10*time.Minute)))) } // Exercise item removal as well fakeClock.Step(11 * time.Minute) for n := 0; n < b.N; n++ { _, _ = q.Get() } } func waitForAdded(q DelayingInterface, depth int) error { return wait.Poll(1*time.Millisecond, 10*time.Second, func() (done bool, err error) { if q.Len() == depth { return true, nil } return false, nil }) } func waitForWaitingQueueToFill(q DelayingInterface) error { return wait.Poll(1*time.Millisecond, 10*time.Second, func() (done bool, err error) { if len(q.(*delayingType).waitingForAddCh) == 0 { return true, nil } return false, nil }) }
ironcladlou/origin
vendor/k8s.io/kubernetes/staging/src/k8s.io/client-go/util/workqueue/delaying_queue_test.go
GO
apache-2.0
6,073
/* * Count register synchronisation. * * All CPUs will have their count registers synchronised to the CPU0 next time * value. This can cause a small timewarp for CPU0. All other CPU's should * not have done anything significant (but they may have had interrupts * enabled briefly - prom_smp_finish() should not be responsible for enabling * interrupts...) */ #include <linux/kernel.h> #include <linux/irqflags.h> #include <linux/cpumask.h> #include <asm/r4k-timer.h> #include <linux/atomic.h> #include <asm/barrier.h> #include <asm/mipsregs.h> static unsigned int initcount = 0; static atomic_t count_count_start = ATOMIC_INIT(0); static atomic_t count_count_stop = ATOMIC_INIT(0); #define COUNTON 100 #define NR_LOOPS 3 void synchronise_count_master(int cpu) { int i; unsigned long flags; pr_info("Synchronize counters for CPU %u: ", cpu); local_irq_save(flags); /* * We loop a few times to get a primed instruction cache, * then the last pass is more or less synchronised and * the master and slaves each set their cycle counters to a known * value all at once. This reduces the chance of having random offsets * between the processors, and guarantees that the maximum * delay between the cycle counters is never bigger than * the latency of information-passing (cachelines) between * two CPUs. */ for (i = 0; i < NR_LOOPS; i++) { /* slaves loop on '!= 2' */ while (atomic_read(&count_count_start) != 1) mb(); atomic_set(&count_count_stop, 0); smp_wmb(); /* Let the slave writes its count register */ atomic_inc(&count_count_start); /* Count will be initialised to current timer */ if (i == 1) initcount = read_c0_count(); /* * Everyone initialises count in the last loop: */ if (i == NR_LOOPS-1) write_c0_count(initcount); /* * Wait for slave to leave the synchronization point: */ while (atomic_read(&count_count_stop) != 1) mb(); atomic_set(&count_count_start, 0); smp_wmb(); atomic_inc(&count_count_stop); } /* Arrange for an interrupt in a short while */ write_c0_compare(read_c0_count() + COUNTON); local_irq_restore(flags); /* * i386 code reported the skew here, but the * count registers were almost certainly out of sync * so no point in alarming people */ pr_cont("done.\n"); } void synchronise_count_slave(int cpu) { int i; /* * Not every cpu is online at the time this gets called, * so we first wait for the master to say everyone is ready */ for (i = 0; i < NR_LOOPS; i++) { atomic_inc(&count_count_start); while (atomic_read(&count_count_start) != 2) mb(); /* * Everyone initialises count in the last loop: */ if (i == NR_LOOPS-1) write_c0_count(initcount); atomic_inc(&count_count_stop); while (atomic_read(&count_count_stop) != 2) mb(); } /* Arrange for an interrupt in a short while */ write_c0_compare(read_c0_count() + COUNTON); } #undef NR_LOOPS
mkvdv/au-linux-kernel-autumn-2017
linux/arch/mips/kernel/sync-r4k.c
C
gpl-3.0
2,928
require 'rexml/document' module ActiveMerchant #:nodoc: module Billing #:nodoc: # Initialization Options # :login Your store number # :pem The text of your linkpoint PEM file. Note # this is not the path to file, but its # contents. If you are only using one PEM # file on your site you can declare it # globally and then you won't need to # include this option # # # A valid store number is required. Unfortunately, with LinkPoint # YOU CAN'T JUST USE ANY OLD STORE NUMBER. Also, you can't just # generate your own PEM file. You'll need to use a special PEM file # provided by LinkPoint. # # Go to http://www.linkpoint.com/support/sup_teststore.asp to set up # a test account and obtain your PEM file. # # Declaring PEM file Globally # ActiveMerchant::Billing::LinkpointGateway.pem_file = File.read( File.dirname(__FILE__) + '/../mycert.pem' ) # # # Valid Order Options # :result => # LIVE Production mode # GOOD Approved response in test mode # DECLINE Declined response in test mode # DUPLICATE Duplicate response in test mode # # :ponumber Order number # # :transactionorigin => Source of the transaction # ECI Email or Internet # MAIL Mail order # MOTO Mail order/Telephone # TELEPHONE Telephone # RETAIL Face-to-face # # :ordertype => # SALE Real live sale # PREAUTH Authorize only # POSTAUTH Forced Ticket or Ticket Only transaction # VOID # CREDIT # CALCSHIPPING For shipping charges calculations # CALCTAX For sales tax calculations # # Recurring Options # :action => # SUBMIT # MODIFY # CANCEL # # :installments Identifies how many recurring payments to charge the customer # :startdate Date to begin charging the recurring payments. Format: YYYYMMDD or "immediate" # :periodicity => # MONTHLY # BIMONTHLY # WEEKLY # BIWEEKLY # YEARLY # DAILY # :threshold Tells how many times to retry the transaction (if it fails) before contacting the merchant. # :comments Uh... comments # # # For reference: # # https://www.linkpointcentral.com/lpc/docs/Help/APIHelp/lpintguide.htm # # Entities = { # :payment => [:subtotal, :tax, :vattax, :shipping, :chargetotal], # :billing => [:name, :address1, :address2, :city, :state, :zip, :country, :email, :phone, :fax, :addrnum], # :shipping => [:name, :address1, :address2, :city, :state, :zip, :country, :weight, :items, :carrier, :total], # :creditcard => [:cardnumber, :cardexpmonth, :cardexpyear, :cvmvalue, :track], # :telecheck => [:routing, :account, :checknumber, :bankname, :bankstate, :dl, :dlstate, :void, :accounttype, :ssn], # :transactiondetails => [:transactionorigin, :oid, :ponumber, :taxexempt, :terminaltype, :ip, :reference_number, :recurring, :tdate], # :periodic => [:action, :installments, :threshold, :startdate, :periodicity, :comments], # :notes => [:comments, :referred] # } # # # IMPORTANT NOTICE: # # LinkPoint's Items entity is not yet supported in this module. # class LinkpointGateway < Gateway # Your global PEM file. This will be assigned to you by linkpoint # # Example: # # ActiveMerchant::Billing::LinkpointGateway.pem_file = File.read( File.dirname(__FILE__) + '/../mycert.pem' ) # cattr_accessor :pem_file TEST_URL = 'https://staging.linkpt.net:1129/' LIVE_URL = 'https://secure.linkpt.net:1129/' # We don't have the certificate to verify LinkPoint self.ssl_strict = false self.supported_countries = ['US'] self.supported_cardtypes = [:visa, :master, :american_express, :discover] self.homepage_url = 'http://www.linkpoint.com/' self.display_name = 'LinkPoint' def initialize(options = {}) requires!(options, :login) @options = { :result => 'LIVE', :pem => LinkpointGateway.pem_file }.update(options) raise ArgumentError, "You need to pass in your pem file using the :pem parameter or set it globally using ActiveMerchant::Billing::LinkpointGateway.pem_file = File.read( File.dirname(__FILE__) + '/../mycert.pem' ) or similar" if @options[:pem].blank? end # Send a purchase request with periodic options # Recurring Options # :action => # SUBMIT # MODIFY # CANCEL # # :installments Identifies how many recurring payments to charge the customer # :startdate Date to begin charging the recurring payments. Format: YYYYMMDD or "immediate" # :periodicity => # :monthly # :bimonthly # :weekly # :biweekly # :yearly # :daily # :threshold Tells how many times to retry the transaction (if it fails) before contacting the merchant. # :comments Uh... comments # def recurring(money, creditcard, options={}) requires!(options, [:periodicity, :bimonthly, :monthly, :biweekly, :weekly, :yearly, :daily], :installments, :order_id ) options.update( :ordertype => "SALE", :action => options[:action] || "SUBMIT", :installments => options[:installments] || 12, :startdate => options[:startdate] || "immediate", :periodicity => options[:periodicity].to_s || "monthly", :comments => options[:comments] || nil, :threshold => options[:threshold] || 3 ) commit(money, creditcard, options) end # Buy the thing def purchase(money, creditcard, options={}) requires!(options, :order_id) options.update( :ordertype => "SALE" ) commit(money, creditcard, options) end # # Authorize the transaction # # Reserves the funds on the customer's credit card, but does not charge the card. # def authorize(money, creditcard, options = {}) requires!(options, :order_id) options.update( :ordertype => "PREAUTH" ) commit(money, creditcard, options) end # # Post an authorization. # # Captures the funds from an authorized transaction. # Order_id must be a valid order id from a prior authorized transaction. # def capture(money, authorization, options = {}) options.update( :order_id => authorization, :ordertype => "POSTAUTH" ) commit(money, nil, options) end # Void a previous transaction def void(identification, options = {}) options.update( :order_id => identification, :ordertype => "VOID" ) commit(nil, nil, options) end # # Refund an order # # identification must be a valid order id previously submitted by SALE # def credit(money, identification, options = {}) options.update( :ordertype => "CREDIT", :order_id => identification ) commit(money, nil, options) end def test? @options[:test] || super end private # Commit the transaction by posting the XML file to the LinkPoint server def commit(money, creditcard, options = {}) response = parse(ssl_post(test? ? TEST_URL : LIVE_URL, post_data(money, creditcard, options))) Response.new(successful?(response), response[:message], response, :test => test?, :authorization => response[:ordernum], :avs_result => { :code => response[:avs].to_s[2,1] }, :cvv_result => response[:avs].to_s[3,1] ) end def successful?(response) response[:approved] == "APPROVED" end # Build the XML file def post_data(money, creditcard, options) params = parameters(money, creditcard, options) xml = REXML::Document.new order = xml.add_element("order") # Merchant Info merchantinfo = order.add_element("merchantinfo") merchantinfo.add_element("configfile").text = @options[:login] # Loop over the params hash to construct the XML string for key, value in params elem = order.add_element(key.to_s) for k, v in params[key] elem.add_element(k.to_s).text = params[key][k].to_s if params[key][k] end # Linkpoint doesn't understand empty elements: order.delete(elem) if elem.size == 0 end return xml.to_s end # Set up the parameters hash just once so we don't have to do it # for every action. def parameters(money, creditcard, options = {}) params = { :payment => { :subtotal => amount(options[:subtotal]), :tax => amount(options[:tax]), :vattax => amount(options[:vattax]), :shipping => amount(options[:shipping]), :chargetotal => amount(money) }, :transactiondetails => { :transactionorigin => options[:transactionorigin] || "ECI", :oid => options[:order_id], :ponumber => options[:ponumber], :taxexempt => options[:taxexempt], :terminaltype => options[:terminaltype], :ip => options[:ip], :reference_number => options[:reference_number], :recurring => options[:recurring] || "NO", #DO NOT USE if you are using the periodic billing option. :tdate => options[:tdate] }, :orderoptions => { :ordertype => options[:ordertype], :result => @options[:result] }, :periodic => { :action => options[:action], :installments => options[:installments], :threshold => options[:threshold], :startdate => options[:startdate], :periodicity => options[:periodicity], :comments => options[:comments] }, :telecheck => { :routing => options[:telecheck_routing], :account => options[:telecheck_account], :checknumber => options[:telecheck_checknumber], :bankname => options[:telecheck_bankname], :dl => options[:telecheck_dl], :dlstate => options[:telecheck_dlstate], :void => options[:telecheck_void], :accounttype => options[:telecheck_accounttype], :ssn => options[:telecheck_ssn], } } if creditcard params[:creditcard] = { :cardnumber => creditcard.number, :cardexpmonth => creditcard.month, :cardexpyear => format_creditcard_expiry_year(creditcard.year), :track => nil } if creditcard.verification_value? params[:creditcard][:cvmvalue] = creditcard.verification_value params[:creditcard][:cvmindicator] = 'provided' else params[:creditcard][:cvmindicator] = 'not_provided' end end if billing_address = options[:billing_address] || options[:address] params[:billing] = {} params[:billing][:name] = billing_address[:name] || creditcard ? creditcard.name : nil params[:billing][:address1] = billing_address[:address1] unless billing_address[:address1].blank? params[:billing][:address2] = billing_address[:address2] unless billing_address[:address2].blank? params[:billing][:city] = billing_address[:city] unless billing_address[:city].blank? params[:billing][:state] = billing_address[:state] unless billing_address[:state].blank? params[:billing][:zip] = billing_address[:zip] unless billing_address[:zip].blank? params[:billing][:country] = billing_address[:country] unless billing_address[:country].blank? params[:billing][:company] = billing_address[:company] unless billing_address[:company].blank? params[:billing][:phone] = billing_address[:phone] unless billing_address[:phone].blank? params[:billing][:email] = options[:email] unless options[:email].blank? end if shipping_address = options[:shipping_address] params[:shipping] = {} params[:shipping][:name] = shipping_address[:name] || creditcard ? creditcard.name : nil params[:shipping][:address1] = shipping_address[:address1] unless shipping_address[:address1].blank? params[:shipping][:address2] = shipping_address[:address2] unless shipping_address[:address2].blank? params[:shipping][:city] = shipping_address[:city] unless shipping_address[:city].blank? params[:shipping][:state] = shipping_address[:state] unless shipping_address[:state].blank? params[:shipping][:zip] = shipping_address[:zip] unless shipping_address[:zip].blank? params[:shipping][:country] = shipping_address[:country] unless shipping_address[:country].blank? end return params end def parse(xml) # For reference, a typical response... # <r_csp></r_csp> # <r_time></r_time> # <r_ref></r_ref> # <r_error></r_error> # <r_ordernum></r_ordernum> # <r_message>This is a test transaction and will not show up in the Reports</r_message> # <r_code></r_code> # <r_tdate>Thu Feb 2 15:40:21 2006</r_tdate> # <r_score></r_score> # <r_authresponse></r_authresponse> # <r_approved>APPROVED</r_approved> # <r_avs></r_avs> response = {:message => "Global Error Receipt", :complete => false} xml = REXML::Document.new("<response>#{xml}</response>") xml.root.elements.each do |node| response[node.name.downcase.sub(/^r_/, '').to_sym] = normalize(node.text) end unless xml.root.nil? response end # Make a ruby type out of the response string def normalize(field) case field when "true" then true when "false" then false when "" then nil when "null" then nil else field end end def format_creditcard_expiry_year(year) sprintf("%.4i", year)[-2..-1] end end end end
camelpunch/simply_agile
vendor/plugins/active_merchant/lib/active_merchant/billing/gateways/linkpoint.rb
Ruby
bsd-3-clause
15,718
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] 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. [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 */ /** * Gets URI that identifies the test. * @return uri identifier of test */ function getTargetURI() { return "http://www.w3.org/2001/DOM-Test-Suite/level2/events/dispatchEvent01"; } var docsLoaded = -1000000; var builder = null; // // This function is called by the testing framework before // running the test suite. // // If there are no configuration exceptions, asynchronous // document loading is started. Otherwise, the status // is set to complete and the exception is immediately // raised when entering the body of the test. // function setUpPage() { setUpPageStatus = 'running'; try { // // creates test document builder, may throw exception // builder = createConfiguredBuilder(); docsLoaded = 0; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } docsLoaded += preload(docRef, "doc", "hc_staff"); if (docsLoaded == 1) { setUpPageStatus = 'complete'; } } catch(ex) { catchInitializationError(builder, ex); setUpPageStatus = 'complete'; } } // // This method is called on the completion of // each asychronous load started in setUpTests. // // When every synchronous loaded document has completed, // the page status is changed which allows the // body of the test to be executed. function loadComplete() { if (++docsLoaded == 1) { setUpPageStatus = 'complete'; } } /** * A null reference is passed to EventTarget.dispatchEvent(), should raise implementation or platform exception. * @author Curt Arnold * @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent * @see http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-17189187 */ function dispatchEvent01() { var success; if(checkInitialization(builder, "dispatchEvent01") != null) return; var doc; var target; var evt = null; var preventDefault; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } doc = load(docRef, "doc", "hc_staff"); { success = false; try { preventDefault = doc.dispatchEvent(evt); } catch (ex) { success = true; } assertTrue("throw_ImplException", success); } } function runTest() { dispatchEvent01(); }
scheib/chromium
third_party/blink/web_tests/dom/legacy_dom_conformance/xhtml/level2/events/dispatchEvent01.js
JavaScript
bsd-3-clause
2,914
#include "clar_libgit2.h" static git_repository *_repo; static git_commit *commit; void test_graph_descendant_of__initialize(void) { git_oid oid; cl_git_pass(git_repository_open(&_repo, cl_fixture("testrepo.git"))); git_oid_fromstr(&oid, "be3563ae3f795b2b4353bcce3a527ad0a4f7f644"); cl_git_pass(git_commit_lookup(&commit, _repo, &oid)); } void test_graph_descendant_of__cleanup(void) { git_commit_free(commit); commit = NULL; git_repository_free(_repo); _repo = NULL; } void test_graph_descendant_of__returns_correct_result(void) { git_commit *other; cl_assert_equal_i(0, git_graph_descendant_of(_repo, git_commit_id(commit), git_commit_id(commit))); cl_git_pass(git_commit_nth_gen_ancestor(&other, commit, 1)); cl_assert_equal_i(1, git_graph_descendant_of(_repo, git_commit_id(commit), git_commit_id(other))); cl_assert_equal_i(0, git_graph_descendant_of(_repo, git_commit_id(other), git_commit_id(commit))); git_commit_free(other); cl_git_pass(git_commit_nth_gen_ancestor(&other, commit, 3)); cl_assert_equal_i(1, git_graph_descendant_of(_repo, git_commit_id(commit), git_commit_id(other))); cl_assert_equal_i(0, git_graph_descendant_of(_repo, git_commit_id(other), git_commit_id(commit))); git_commit_free(other); } void test_graph_descendant_of__nopath(void) { git_oid oid; git_oid_fromstr(&oid, "e90810b8df3e80c413d903f631643c716887138d"); cl_assert_equal_i(0, git_graph_descendant_of(_repo, git_commit_id(commit), &oid)); }
cwahbong/nodegit
vendor/libgit2/tests/graph/descendant_of.c
C
mit
1,470
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../../../shared/complex/numeric/imag', __FILE__) ruby_version_is "1.9" do describe "Numeric#imag" do it_behaves_like(:numeric_imag, :imag) end end
takano32/rubinius
spec/ruby/core/numeric/imag_spec.rb
Ruby
bsd-3-clause
241
<?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/>. /** * Unit tests for the completion condition. * * @package availability_completion * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); use availability_completion\condition; global $CFG; require_once($CFG->libdir . '/completionlib.php'); /** * Unit tests for the completion condition. * * @package availability_completion * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class availability_completion_condition_testcase extends advanced_testcase { /** * Load required classes. */ public function setUp() { // Load the mock info class so that it can be used. global $CFG; require_once($CFG->dirroot . '/availability/tests/fixtures/mock_info.php'); } /** * Tests constructing and using condition as part of tree. */ public function test_in_tree() { global $USER, $CFG; $this->resetAfterTest(); $this->setAdminUser(); // Create course with completion turned on and a Page. $CFG->enablecompletion = true; $CFG->enableavailability = true; $generator = $this->getDataGenerator(); $course = $generator->create_course(array('enablecompletion' => 1)); $page = $generator->get_plugin_generator('mod_page')->create_instance( array('course' => $course->id, 'completion' => COMPLETION_TRACKING_MANUAL)); $modinfo = get_fast_modinfo($course); $cm = $modinfo->get_cm($page->cmid); $info = new \core_availability\mock_info($course, $USER->id); $structure = (object)array('op' => '|', 'show' => true, 'c' => array( (object)array('type' => 'completion', 'cm' => (int)$cm->id, 'e' => COMPLETION_COMPLETE))); $tree = new \core_availability\tree($structure); // Initial check (user has not completed activity). $result = $tree->check_available(false, $info, true, $USER->id); $this->assertFalse($result->is_available()); // Mark activity complete. $completion = new completion_info($course); $completion->update_state($cm, COMPLETION_COMPLETE); // Now it's true! $result = $tree->check_available(false, $info, true, $USER->id); $this->assertTrue($result->is_available()); } /** * Tests the constructor including error conditions. Also tests the * string conversion feature (intended for debugging only). */ public function test_constructor() { // No parameters. $structure = new stdClass(); try { $cond = new condition($structure); $this->fail(); } catch (coding_exception $e) { $this->assertContains('Missing or invalid ->cm', $e->getMessage()); } // Invalid $cm. $structure->cm = 'hello'; try { $cond = new condition($structure); $this->fail(); } catch (coding_exception $e) { $this->assertContains('Missing or invalid ->cm', $e->getMessage()); } // Missing $e. $structure->cm = 42; try { $cond = new condition($structure); $this->fail(); } catch (coding_exception $e) { $this->assertContains('Missing or invalid ->e', $e->getMessage()); } // Invalid $e. $structure->e = 99; try { $cond = new condition($structure); $this->fail(); } catch (coding_exception $e) { $this->assertContains('Missing or invalid ->e', $e->getMessage()); } // Successful construct & display with all different expected values. $structure->e = COMPLETION_COMPLETE; $cond = new condition($structure); $this->assertEquals('{completion:cm42 COMPLETE}', (string)$cond); $structure->e = COMPLETION_COMPLETE_PASS; $cond = new condition($structure); $this->assertEquals('{completion:cm42 COMPLETE_PASS}', (string)$cond); $structure->e = COMPLETION_COMPLETE_FAIL; $cond = new condition($structure); $this->assertEquals('{completion:cm42 COMPLETE_FAIL}', (string)$cond); $structure->e = COMPLETION_INCOMPLETE; $cond = new condition($structure); $this->assertEquals('{completion:cm42 INCOMPLETE}', (string)$cond); } /** * Tests the save() function. */ public function test_save() { $structure = (object)array('cm' => 42, 'e' => COMPLETION_COMPLETE); $cond = new condition($structure); $structure->type = 'completion'; $this->assertEquals($structure, $cond->save()); } /** * Tests the is_available and get_description functions. */ public function test_usage() { global $CFG, $DB; require_once($CFG->dirroot . '/mod/assign/locallib.php'); $this->resetAfterTest(); // Create course with completion turned on. $CFG->enablecompletion = true; $CFG->enableavailability = true; $generator = $this->getDataGenerator(); $course = $generator->create_course(array('enablecompletion' => 1)); $user = $generator->create_user(); $generator->enrol_user($user->id, $course->id); $this->setUser($user); // Create a Page with manual completion for basic checks. $page = $generator->get_plugin_generator('mod_page')->create_instance( array('course' => $course->id, 'name' => 'Page!', 'completion' => COMPLETION_TRACKING_MANUAL)); // Create an assignment - we need to have something that can be graded // so as to test the PASS/FAIL states. Set it up to be completed based // on its grade item. $assignrow = $this->getDataGenerator()->create_module('assign', array( 'course' => $course->id, 'name' => 'Assign!', 'completion' => COMPLETION_TRACKING_AUTOMATIC)); $DB->set_field('course_modules', 'completiongradeitemnumber', 0, array('id' => $assignrow->cmid)); $assign = new assign(context_module::instance($assignrow->cmid), false, false); // Get basic details. $modinfo = get_fast_modinfo($course); $pagecm = $modinfo->get_cm($page->cmid); $assigncm = $assign->get_course_module(); $info = new \core_availability\mock_info($course, $user->id); // COMPLETE state (false), positive and NOT. $cond = new condition((object)array( 'cm' => (int)$pagecm->id, 'e' => COMPLETION_COMPLETE)); $this->assertFalse($cond->is_available(false, $info, true, $user->id)); $information = $cond->get_description(false, false, $info); $information = \core_availability\info::format_info($information, $course); $this->assertRegExp('~Page!.*is marked complete~', $information); $this->assertTrue($cond->is_available(true, $info, true, $user->id)); // INCOMPLETE state (true). $cond = new condition((object)array( 'cm' => (int)$pagecm->id, 'e' => COMPLETION_INCOMPLETE)); $this->assertTrue($cond->is_available(false, $info, true, $user->id)); $this->assertFalse($cond->is_available(true, $info, true, $user->id)); $information = $cond->get_description(false, true, $info); $information = \core_availability\info::format_info($information, $course); $this->assertRegExp('~Page!.*is marked complete~', $information); // Mark page complete. $completion = new completion_info($course); $completion->update_state($pagecm, COMPLETION_COMPLETE); // COMPLETE state (true). $cond = new condition((object)array( 'cm' => (int)$pagecm->id, 'e' => COMPLETION_COMPLETE)); $this->assertTrue($cond->is_available(false, $info, true, $user->id)); $this->assertFalse($cond->is_available(true, $info, true, $user->id)); $information = $cond->get_description(false, true, $info); $information = \core_availability\info::format_info($information, $course); $this->assertRegExp('~Page!.*is incomplete~', $information); // INCOMPLETE state (false). $cond = new condition((object)array( 'cm' => (int)$pagecm->id, 'e' => COMPLETION_INCOMPLETE)); $this->assertFalse($cond->is_available(false, $info, true, $user->id)); $information = $cond->get_description(false, false, $info); $information = \core_availability\info::format_info($information, $course); $this->assertRegExp('~Page!.*is incomplete~', $information); $this->assertTrue($cond->is_available(true, $info, true, $user->id)); // We are going to need the grade item so that we can get pass/fails. $gradeitem = $assign->get_grade_item(); grade_object::set_properties($gradeitem, array('gradepass' => 50.0)); $gradeitem->update(); // With no grade, it should return true for INCOMPLETE and false for // the other three. $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_INCOMPLETE)); $this->assertTrue($cond->is_available(false, $info, true, $user->id)); $this->assertFalse($cond->is_available(true, $info, true, $user->id)); $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_COMPLETE)); $this->assertFalse($cond->is_available(false, $info, true, $user->id)); $this->assertTrue($cond->is_available(true, $info, true, $user->id)); // Check $information for COMPLETE_PASS and _FAIL as we haven't yet. $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_COMPLETE_PASS)); $this->assertFalse($cond->is_available(false, $info, true, $user->id)); $information = $cond->get_description(false, false, $info); $information = \core_availability\info::format_info($information, $course); $this->assertRegExp('~Assign!.*is complete and passed~', $information); $this->assertTrue($cond->is_available(true, $info, true, $user->id)); $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_COMPLETE_FAIL)); $this->assertFalse($cond->is_available(false, $info, true, $user->id)); $information = $cond->get_description(false, false, $info); $information = \core_availability\info::format_info($information, $course); $this->assertRegExp('~Assign!.*is complete and failed~', $information); $this->assertTrue($cond->is_available(true, $info, true, $user->id)); // Change the grade to be complete and failed. self::set_grade($assignrow, $user->id, 40); $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_INCOMPLETE)); $this->assertFalse($cond->is_available(false, $info, true, $user->id)); $this->assertTrue($cond->is_available(true, $info, true, $user->id)); $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_COMPLETE)); $this->assertTrue($cond->is_available(false, $info, true, $user->id)); $this->assertFalse($cond->is_available(true, $info, true, $user->id)); $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_COMPLETE_PASS)); $this->assertFalse($cond->is_available(false, $info, true, $user->id)); $information = $cond->get_description(false, false, $info); $information = \core_availability\info::format_info($information, $course); $this->assertRegExp('~Assign!.*is complete and passed~', $information); $this->assertTrue($cond->is_available(true, $info, true, $user->id)); $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_COMPLETE_FAIL)); $this->assertTrue($cond->is_available(false, $info, true, $user->id)); $this->assertFalse($cond->is_available(true, $info, true, $user->id)); $information = $cond->get_description(false, true, $info); $information = \core_availability\info::format_info($information, $course); $this->assertRegExp('~Assign!.*is not complete and failed~', $information); // Now change it to pass. self::set_grade($assignrow, $user->id, 60); $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_INCOMPLETE)); $this->assertFalse($cond->is_available(false, $info, true, $user->id)); $this->assertTrue($cond->is_available(true, $info, true, $user->id)); $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_COMPLETE)); $this->assertTrue($cond->is_available(false, $info, true, $user->id)); $this->assertFalse($cond->is_available(true, $info, true, $user->id)); $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_COMPLETE_PASS)); $this->assertTrue($cond->is_available(false, $info, true, $user->id)); $this->assertFalse($cond->is_available(true, $info, true, $user->id)); $information = $cond->get_description(false, true, $info); $information = \core_availability\info::format_info($information, $course); $this->assertRegExp('~Assign!.*is not complete and passed~', $information); $cond = new condition((object)array( 'cm' => (int)$assigncm->id, 'e' => COMPLETION_COMPLETE_FAIL)); $this->assertFalse($cond->is_available(false, $info, true, $user->id)); $information = $cond->get_description(false, false, $info); $information = \core_availability\info::format_info($information, $course); $this->assertRegExp('~Assign!.*is complete and failed~', $information); $this->assertTrue($cond->is_available(true, $info, true, $user->id)); // Simulate deletion of an activity by using an invalid cmid. These // conditions always fail, regardless of NOT flag or INCOMPLETE. $cond = new condition((object)array( 'cm' => ($assigncm->id + 100), 'e' => COMPLETION_COMPLETE)); $this->assertFalse($cond->is_available(false, $info, true, $user->id)); $information = $cond->get_description(false, false, $info); $information = \core_availability\info::format_info($information, $course); $this->assertRegExp('~(Missing activity).*is marked complete~', $information); $this->assertFalse($cond->is_available(true, $info, true, $user->id)); $cond = new condition((object)array( 'cm' => ($assigncm->id + 100), 'e' => COMPLETION_INCOMPLETE)); $this->assertFalse($cond->is_available(false, $info, true, $user->id)); } /** * Tests completion_value_used static function. */ public function test_completion_value_used() { global $CFG, $DB; $this->resetAfterTest(); // Create course with completion turned on and some sections. $CFG->enablecompletion = true; $CFG->enableavailability = true; $generator = $this->getDataGenerator(); $course = $generator->create_course( array('numsections' => 1, 'enablecompletion' => 1), array('createsections' => true)); availability_completion\condition::wipe_static_cache(); // Create three pages with manual completion. $page1 = $generator->get_plugin_generator('mod_page')->create_instance( array('course' => $course->id, 'completion' => COMPLETION_TRACKING_MANUAL)); $page2 = $generator->get_plugin_generator('mod_page')->create_instance( array('course' => $course->id, 'completion' => COMPLETION_TRACKING_MANUAL)); $page3 = $generator->get_plugin_generator('mod_page')->create_instance( array('course' => $course->id, 'completion' => COMPLETION_TRACKING_MANUAL)); // Set up page3 to depend on page1, and section1 to depend on page2. $DB->set_field('course_modules', 'availability', '{"op":"|","show":true,"c":[' . '{"type":"completion","e":1,"cm":' . $page1->cmid . '}]}', array('id' => $page3->cmid)); $DB->set_field('course_sections', 'availability', '{"op":"|","show":true,"c":[' . '{"type":"completion","e":1,"cm":' . $page2->cmid . '}]}', array('course' => $course->id, 'section' => 1)); // Now check: nothing depends on page3 but something does on the others. $this->assertTrue(availability_completion\condition::completion_value_used( $course, $page1->cmid)); $this->assertTrue(availability_completion\condition::completion_value_used( $course, $page2->cmid)); $this->assertFalse(availability_completion\condition::completion_value_used( $course, $page3->cmid)); } /** * Updates the grade of a user in the given assign module instance. * * @param stdClass $assignrow Assignment row from database * @param int $userid User id * @param float $grade Grade */ protected static function set_grade($assignrow, $userid, $grade) { $grades = array(); $grades[$userid] = (object)array( 'rawgrade' => $grade, 'userid' => $userid); $assignrow->cmidnumber = null; assign_grade_item_update($assignrow, $grades); } /** * Tests the update_dependency_id() function. */ public function test_update_dependency_id() { $cond = new condition((object)array( 'cm' => 123, 'e' => COMPLETION_COMPLETE)); $this->assertFalse($cond->update_dependency_id('frogs', 123, 456)); $this->assertFalse($cond->update_dependency_id('course_modules', 12, 34)); $this->assertTrue($cond->update_dependency_id('course_modules', 123, 456)); $after = $cond->save(); $this->assertEquals(456, $after->cm); } }
tesler/cspt-moodle
moodle/availability/condition/completion/tests/condition_test.php
PHP
mit
19,088
/* * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc. * 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 as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * File: mib.c * * Purpose: Implement MIB Data Structure * * Author: Tevin Chen * * Date: May 21, 1996 * * Functions: * STAvClearAllCounter - Clear All MIB Counter * STAvUpdateIstStatCounter - Update ISR statistic counter * STAvUpdateRDStatCounter - Update Rx statistic counter * STAvUpdateRDStatCounterEx - Update Rx statistic counter and copy rcv data * STAvUpdateTDStatCounter - Update Tx statistic counter * STAvUpdateTDStatCounterEx - Update Tx statistic counter and copy tx data * STAvUpdate802_11Counter - Update 802.11 mib counter * * Revision History: * */ #include "upc.h" #include "mac.h" #include "tether.h" #include "mib.h" #include "wctl.h" #include "baseband.h" /*--------------------- Static Definitions -------------------------*/ static int msglevel =MSG_LEVEL_INFO; /*--------------------- Static Classes ----------------------------*/ /*--------------------- Static Variables --------------------------*/ /*--------------------- Static Functions --------------------------*/ /*--------------------- Export Variables --------------------------*/ /*--------------------- Export Functions --------------------------*/ /* * Description: Clear All Statistic Counter * * Parameters: * In: * pStatistic - Pointer to Statistic Counter Data Structure * Out: * none * * Return Value: none * */ void STAvClearAllCounter (PSStatCounter pStatistic) { // set memory to zero memset(pStatistic, 0, sizeof(SStatCounter)); } /* * Description: Update Isr Statistic Counter * * Parameters: * In: * pStatistic - Pointer to Statistic Counter Data Structure * wisr - Interrupt status * Out: * none * * Return Value: none * */ void STAvUpdateIsrStatCounter (PSStatCounter pStatistic, DWORD dwIsr) { /**********************/ /* ABNORMAL interrupt */ /**********************/ // not any IMR bit invoke irq if (dwIsr == 0) { pStatistic->ISRStat.dwIsrUnknown++; return; } //Added by Kyle if (dwIsr & ISR_TXDMA0) // ISR, bit0 pStatistic->ISRStat.dwIsrTx0OK++; // TXDMA0 successful if (dwIsr & ISR_AC0DMA) // ISR, bit1 pStatistic->ISRStat.dwIsrAC0TxOK++; // AC0DMA successful if (dwIsr & ISR_BNTX) // ISR, bit2 pStatistic->ISRStat.dwIsrBeaconTxOK++; // BeaconTx successful if (dwIsr & ISR_RXDMA0) // ISR, bit3 pStatistic->ISRStat.dwIsrRx0OK++; // Rx0 successful if (dwIsr & ISR_TBTT) // ISR, bit4 pStatistic->ISRStat.dwIsrTBTTInt++; // TBTT successful if (dwIsr & ISR_SOFTTIMER) // ISR, bit6 pStatistic->ISRStat.dwIsrSTIMERInt++; if (dwIsr & ISR_WATCHDOG) // ISR, bit7 pStatistic->ISRStat.dwIsrWatchDog++; if (dwIsr & ISR_FETALERR) // ISR, bit8 pStatistic->ISRStat.dwIsrUnrecoverableError++; if (dwIsr & ISR_SOFTINT) // ISR, bit9 pStatistic->ISRStat.dwIsrSoftInterrupt++; // software interrupt if (dwIsr & ISR_MIBNEARFULL) // ISR, bit10 pStatistic->ISRStat.dwIsrMIBNearfull++; if (dwIsr & ISR_RXNOBUF) // ISR, bit11 pStatistic->ISRStat.dwIsrRxNoBuf++; // Rx No Buff if (dwIsr & ISR_RXDMA1) // ISR, bit12 pStatistic->ISRStat.dwIsrRx1OK++; // Rx1 successful // if (dwIsr & ISR_ATIMTX) // ISR, bit13 // pStatistic->ISRStat.dwIsrATIMTxOK++; // ATIMTX successful // if (dwIsr & ISR_SYNCTX) // ISR, bit14 // pStatistic->ISRStat.dwIsrSYNCTxOK++; // SYNCTX successful // if (dwIsr & ISR_CFPEND) // ISR, bit18 // pStatistic->ISRStat.dwIsrCFPEnd++; // if (dwIsr & ISR_ATIMEND) // ISR, bit19 // pStatistic->ISRStat.dwIsrATIMEnd++; // if (dwIsr & ISR_SYNCFLUSHOK) // ISR, bit20 // pStatistic->ISRStat.dwIsrSYNCFlushOK++; if (dwIsr & ISR_SOFTTIMER1) // ISR, bit21 pStatistic->ISRStat.dwIsrSTIMER1Int++; } /* * Description: Update Rx Statistic Counter * * Parameters: * In: * pStatistic - Pointer to Statistic Counter Data Structure * byRSR - Rx Status * byNewRSR - Rx Status * pbyBuffer - Rx Buffer * cbFrameLength - Rx Length * Out: * none * * Return Value: none * */ void STAvUpdateRDStatCounter (PSStatCounter pStatistic, BYTE byRSR, BYTE byNewRSR, BYTE byRxRate, PBYTE pbyBuffer, UINT cbFrameLength) { //need change PS802_11Header pHeader = (PS802_11Header)pbyBuffer; if (byRSR & RSR_ADDROK) pStatistic->dwRsrADDROk++; if (byRSR & RSR_CRCOK) { pStatistic->dwRsrCRCOk++; pStatistic->ullRsrOK++; if (cbFrameLength >= U_ETHER_ADDR_LEN) { // update counters in case that successful transmit if (byRSR & RSR_ADDRBROAD) { pStatistic->ullRxBroadcastFrames++; pStatistic->ullRxBroadcastBytes += (ULONGLONG)cbFrameLength; } else if (byRSR & RSR_ADDRMULTI) { pStatistic->ullRxMulticastFrames++; pStatistic->ullRxMulticastBytes += (ULONGLONG)cbFrameLength; } else { pStatistic->ullRxDirectedFrames++; pStatistic->ullRxDirectedBytes += (ULONGLONG)cbFrameLength; } } } if(byRxRate==22) { pStatistic->CustomStat.ullRsr11M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr11MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"11M: ALL[%d], OK[%d]:[%02x]\n", (INT)pStatistic->CustomStat.ullRsr11M, (INT)pStatistic->CustomStat.ullRsr11MCRCOk, byRSR); } else if(byRxRate==11) { pStatistic->CustomStat.ullRsr5M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr5MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" 5M: ALL[%d], OK[%d]:[%02x]\n", (INT)pStatistic->CustomStat.ullRsr5M, (INT)pStatistic->CustomStat.ullRsr5MCRCOk, byRSR); } else if(byRxRate==4) { pStatistic->CustomStat.ullRsr2M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr2MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" 2M: ALL[%d], OK[%d]:[%02x]\n", (INT)pStatistic->CustomStat.ullRsr2M, (INT)pStatistic->CustomStat.ullRsr2MCRCOk, byRSR); } else if(byRxRate==2){ pStatistic->CustomStat.ullRsr1M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr1MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" 1M: ALL[%d], OK[%d]:[%02x]\n", (INT)pStatistic->CustomStat.ullRsr1M, (INT)pStatistic->CustomStat.ullRsr1MCRCOk, byRSR); } else if(byRxRate==12){ pStatistic->CustomStat.ullRsr6M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr6MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" 6M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr6M, (INT)pStatistic->CustomStat.ullRsr6MCRCOk); } else if(byRxRate==18){ pStatistic->CustomStat.ullRsr9M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr9MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" 9M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr9M, (INT)pStatistic->CustomStat.ullRsr9MCRCOk); } else if(byRxRate==24){ pStatistic->CustomStat.ullRsr12M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr12MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"12M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr12M, (INT)pStatistic->CustomStat.ullRsr12MCRCOk); } else if(byRxRate==36){ pStatistic->CustomStat.ullRsr18M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr18MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"18M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr18M, (INT)pStatistic->CustomStat.ullRsr18MCRCOk); } else if(byRxRate==48){ pStatistic->CustomStat.ullRsr24M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr24MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"24M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr24M, (INT)pStatistic->CustomStat.ullRsr24MCRCOk); } else if(byRxRate==72){ pStatistic->CustomStat.ullRsr36M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr36MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"36M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr36M, (INT)pStatistic->CustomStat.ullRsr36MCRCOk); } else if(byRxRate==96){ pStatistic->CustomStat.ullRsr48M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr48MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"48M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr48M, (INT)pStatistic->CustomStat.ullRsr48MCRCOk); } else if(byRxRate==108){ pStatistic->CustomStat.ullRsr54M++; if(byRSR & RSR_CRCOK) { pStatistic->CustomStat.ullRsr54MCRCOk++; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"54M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr54M, (INT)pStatistic->CustomStat.ullRsr54MCRCOk); } else { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Unknown: Total[%d], CRCOK[%d]\n", (INT)pStatistic->dwRsrRxPacket+1, (INT)pStatistic->dwRsrCRCOk); } if (byRSR & RSR_BSSIDOK) pStatistic->dwRsrBSSIDOk++; if (byRSR & RSR_BCNSSIDOK) pStatistic->dwRsrBCNSSIDOk++; if (byRSR & RSR_IVLDLEN) //invalid len (> 2312 byte) pStatistic->dwRsrLENErr++; if (byRSR & RSR_IVLDTYP) //invalid packet type pStatistic->dwRsrTYPErr++; if (byRSR & (RSR_IVLDTYP | RSR_IVLDLEN)) pStatistic->dwRsrErr++; if (byNewRSR & NEWRSR_DECRYPTOK) pStatistic->dwNewRsrDECRYPTOK++; if (byNewRSR & NEWRSR_CFPIND) pStatistic->dwNewRsrCFP++; if (byNewRSR & NEWRSR_HWUTSF) pStatistic->dwNewRsrUTSF++; if (byNewRSR & NEWRSR_BCNHITAID) pStatistic->dwNewRsrHITAID++; if (byNewRSR & NEWRSR_BCNHITAID0) pStatistic->dwNewRsrHITAID0++; // increase rx packet count pStatistic->dwRsrRxPacket++; pStatistic->dwRsrRxOctet += cbFrameLength; if (IS_TYPE_DATA(pbyBuffer)) { pStatistic->dwRsrRxData++; } else if (IS_TYPE_MGMT(pbyBuffer)){ pStatistic->dwRsrRxManage++; } else if (IS_TYPE_CONTROL(pbyBuffer)){ pStatistic->dwRsrRxControl++; } if (byRSR & RSR_ADDRBROAD) pStatistic->dwRsrBroadcast++; else if (byRSR & RSR_ADDRMULTI) pStatistic->dwRsrMulticast++; else pStatistic->dwRsrDirected++; if (WLAN_GET_FC_MOREFRAG(pHeader->wFrameCtl)) pStatistic->dwRsrRxFragment++; if (cbFrameLength < MIN_PACKET_LEN + 4) { pStatistic->dwRsrRunt++; } else if (cbFrameLength == MIN_PACKET_LEN + 4) { pStatistic->dwRsrRxFrmLen64++; } else if ((65 <= cbFrameLength) && (cbFrameLength <= 127)) { pStatistic->dwRsrRxFrmLen65_127++; } else if ((128 <= cbFrameLength) && (cbFrameLength <= 255)) { pStatistic->dwRsrRxFrmLen128_255++; } else if ((256 <= cbFrameLength) && (cbFrameLength <= 511)) { pStatistic->dwRsrRxFrmLen256_511++; } else if ((512 <= cbFrameLength) && (cbFrameLength <= 1023)) { pStatistic->dwRsrRxFrmLen512_1023++; } else if ((1024 <= cbFrameLength) && (cbFrameLength <= MAX_PACKET_LEN + 4)) { pStatistic->dwRsrRxFrmLen1024_1518++; } else if (cbFrameLength > MAX_PACKET_LEN + 4) { pStatistic->dwRsrLong++; } } /* * Description: Update Rx Statistic Counter and copy Rx buffer * * Parameters: * In: * pStatistic - Pointer to Statistic Counter Data Structure * byRSR - Rx Status * byNewRSR - Rx Status * pbyBuffer - Rx Buffer * cbFrameLength - Rx Length * Out: * none * * Return Value: none * */ void STAvUpdateRDStatCounterEx ( PSStatCounter pStatistic, BYTE byRSR, BYTE byNewRSR, BYTE byRxRate, PBYTE pbyBuffer, UINT cbFrameLength ) { STAvUpdateRDStatCounter( pStatistic, byRSR, byNewRSR, byRxRate, pbyBuffer, cbFrameLength ); // rx length pStatistic->dwCntRxFrmLength = cbFrameLength; // rx pattern, we just see 10 bytes for sample memcpy(pStatistic->abyCntRxPattern, (PBYTE)pbyBuffer, 10); } /* * Description: Update Tx Statistic Counter * * Parameters: * In: * pStatistic - Pointer to Statistic Counter Data Structure * byTSR0 - Tx Status * byTSR1 - Tx Status * pbyBuffer - Tx Buffer * cbFrameLength - Tx Length * uIdx - Index of Tx DMA * Out: * none * * Return Value: none * */ void STAvUpdateTDStatCounter ( PSStatCounter pStatistic, BYTE byTSR0, BYTE byTSR1, PBYTE pbyBuffer, UINT cbFrameLength, UINT uIdx ) { PWLAN_80211HDR_A4 pHeader; PBYTE pbyDestAddr; BYTE byTSR0_NCR = byTSR0 & TSR0_NCR; pHeader = (PWLAN_80211HDR_A4) pbyBuffer; if (WLAN_GET_FC_TODS(pHeader->wFrameCtl) == 0) { pbyDestAddr = &(pHeader->abyAddr1[0]); } else { pbyDestAddr = &(pHeader->abyAddr3[0]); } // increase tx packet count pStatistic->dwTsrTxPacket[uIdx]++; pStatistic->dwTsrTxOctet[uIdx] += cbFrameLength; if (byTSR0_NCR != 0) { pStatistic->dwTsrRetry[uIdx]++; pStatistic->dwTsrTotalRetry[uIdx] += byTSR0_NCR; if (byTSR0_NCR == 1) pStatistic->dwTsrOnceRetry[uIdx]++; else pStatistic->dwTsrMoreThanOnceRetry[uIdx]++; } if ((byTSR1&(TSR1_TERR|TSR1_RETRYTMO|TSR1_TMO|ACK_DATA)) == 0) { pStatistic->ullTsrOK[uIdx]++; pStatistic->CustomStat.ullTsrAllOK = (pStatistic->ullTsrOK[TYPE_AC0DMA] + pStatistic->ullTsrOK[TYPE_TXDMA0]); // update counters in case that successful transmit if (IS_BROADCAST_ADDRESS(pbyDestAddr)) { pStatistic->ullTxBroadcastFrames[uIdx]++; pStatistic->ullTxBroadcastBytes[uIdx] += (ULONGLONG)cbFrameLength; } else if (IS_MULTICAST_ADDRESS(pbyDestAddr)) { pStatistic->ullTxMulticastFrames[uIdx]++; pStatistic->ullTxMulticastBytes[uIdx] += (ULONGLONG)cbFrameLength; } else { pStatistic->ullTxDirectedFrames[uIdx]++; pStatistic->ullTxDirectedBytes[uIdx] += (ULONGLONG)cbFrameLength; } } else { if (byTSR1 & TSR1_TERR) pStatistic->dwTsrErr[uIdx]++; if (byTSR1 & TSR1_RETRYTMO) pStatistic->dwTsrRetryTimeout[uIdx]++; if (byTSR1 & TSR1_TMO) pStatistic->dwTsrTransmitTimeout[uIdx]++; if (byTSR1 & ACK_DATA) pStatistic->dwTsrACKData[uIdx]++; } if (IS_BROADCAST_ADDRESS(pbyDestAddr)) pStatistic->dwTsrBroadcast[uIdx]++; else if (IS_MULTICAST_ADDRESS(pbyDestAddr)) pStatistic->dwTsrMulticast[uIdx]++; else pStatistic->dwTsrDirected[uIdx]++; } /* * Description: Update Tx Statistic Counter and copy Tx buffer * * Parameters: * In: * pStatistic - Pointer to Statistic Counter Data Structure * pbyBuffer - Tx Buffer * cbFrameLength - Tx Length * Out: * none * * Return Value: none * */ void STAvUpdateTDStatCounterEx ( PSStatCounter pStatistic, PBYTE pbyBuffer, DWORD cbFrameLength ) { UINT uPktLength; uPktLength = (UINT)cbFrameLength; // tx length pStatistic->dwCntTxBufLength = uPktLength; // tx pattern, we just see 16 bytes for sample memcpy(pStatistic->abyCntTxPattern, pbyBuffer, 16); } /* * Description: Update 802.11 mib counter * * Parameters: * In: * p802_11Counter - Pointer to 802.11 mib counter * pStatistic - Pointer to Statistic Counter Data Structure * dwCounter - hardware counter for 802.11 mib * Out: * none * * Return Value: none * */ void STAvUpdate802_11Counter( PSDot11Counters p802_11Counter, PSStatCounter pStatistic, DWORD dwCounter ) { //p802_11Counter->TransmittedFragmentCount p802_11Counter->MulticastTransmittedFrameCount = (ULONGLONG) (pStatistic->dwTsrBroadcast[TYPE_AC0DMA] + pStatistic->dwTsrBroadcast[TYPE_TXDMA0] + pStatistic->dwTsrMulticast[TYPE_AC0DMA] + pStatistic->dwTsrMulticast[TYPE_TXDMA0]); p802_11Counter->FailedCount = (ULONGLONG) (pStatistic->dwTsrErr[TYPE_AC0DMA] + pStatistic->dwTsrErr[TYPE_TXDMA0]); p802_11Counter->RetryCount = (ULONGLONG) (pStatistic->dwTsrRetry[TYPE_AC0DMA] + pStatistic->dwTsrRetry[TYPE_TXDMA0]); p802_11Counter->MultipleRetryCount = (ULONGLONG) (pStatistic->dwTsrMoreThanOnceRetry[TYPE_AC0DMA] + pStatistic->dwTsrMoreThanOnceRetry[TYPE_TXDMA0]); //p802_11Counter->FrameDuplicateCount p802_11Counter->RTSSuccessCount += (ULONGLONG) (dwCounter & 0x000000ff); p802_11Counter->RTSFailureCount += (ULONGLONG) ((dwCounter & 0x0000ff00) >> 8); p802_11Counter->ACKFailureCount += (ULONGLONG) ((dwCounter & 0x00ff0000) >> 16); p802_11Counter->FCSErrorCount += (ULONGLONG) ((dwCounter & 0xff000000) >> 24); //p802_11Counter->ReceivedFragmentCount p802_11Counter->MulticastReceivedFrameCount = (ULONGLONG) (pStatistic->dwRsrBroadcast + pStatistic->dwRsrMulticast); } /* * Description: Clear 802.11 mib counter * * Parameters: * In: * p802_11Counter - Pointer to 802.11 mib counter * Out: * none * * Return Value: none * */ void STAvClear802_11Counter(PSDot11Counters p802_11Counter) { // set memory to zero memset(p802_11Counter, 0, sizeof(SDot11Counters)); }
go2ev-devteam/Gplus_2159_0801
openplatform/sdk/os/kernel-2.6.32/drivers/staging/vt6655/mib.c
C
gpl-2.0
19,603
require "spec_helper" describe Mongoid::Relations::Builders do class TestClass include Mongoid::Document end let(:klass) do TestClass end let(:relation) do Mongoid::Relations::Embedded::One end describe ".builder" do let(:metadata) do Mongoid::Relations::Metadata.new( :name => :name, :relation => relation, :inverse_class_name => "Person" ) end let(:document) do klass.new end before do document.instance_variable_set(:@attributes, {}) klass.builder("name", metadata) end it "defines a build_* method" do document.should respond_to(:build_name) end it "returns self" do klass.builder("name", metadata).should == klass end context "defined methods" do before do klass.getter("name", metadata).setter("name", metadata) end describe "#build_\{relation\}" do before do @relation = document.build_name(:first_name => "Obie") end it "returns a new document" do @relation.should be_a_kind_of(Name) end it "sets the attributes on the document" do @relation.first_name.should == "Obie" end end end end describe ".creator" do let(:document) do klass.new end before do document.instance_variable_set(:@attributes, {}) klass.creator("name") end it "defines a create_* method" do document.should respond_to(:create_name) end it "returns self" do klass.creator("name").should == klass end context "defined methods" do let(:metadata) do Mongoid::Relations::Metadata.new( :name => :name, :relation => relation, :inverse_class_name => "Person", :as => :namable ) end before do klass.getter("name", metadata).setter("name", metadata) end describe "#create_\{relation\}" do before do Name.any_instance.expects(:save).returns(true) @relation = document.create_name(:first_name => "Obie") end it "returns a newly saved document" do @relation.should be_a_kind_of(Name) end it "sets the attributes on the document" do @relation.first_name.should == "Obie" end end end end end
DanielVartanov/mongoid
spec/unit/mongoid/relations/builders_spec.rb
Ruby
mit
2,396
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # Additional variables for figures, not sphinx default: DIA = dia EPSTOPDF = epstopdf FIGURES = source/figures IMAGES_EPS = \ IMAGES_PNG = ${IMAGES_EPS:.eps=.png} IMAGES_PDF = ${IMAGES_EPS:.eps=.pdf} IMAGES = $(IMAGES_EPS) $(IMAGES_PNG) $(IMAGES_PDF) .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest .NOTPARALLEL: %.eps : %.dia; $(DIA) -t eps $< -e $@ %.png : %.dia; $(DIA) -t png $< -e $@ %.pdf : %.eps; $(EPSTOPDF) $< -o=$@ help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* frag: pickle @if test ! -d $(BUILDDIR)/frag; then mkdir $(BUILDDIR)/frag; fi pushd $(BUILDDIR)/frag && ../../pickle-to-xml.py ../pickle/index.fpickle > navigation.xml && popd cp -r $(BUILDDIR)/pickle/_images $(BUILDDIR)/frag html: $(IMAGES) $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(IMAGES) $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(IMAGES) $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(IMAGES) $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(IMAGES) $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(IMAGES) $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(IMAGES) $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ns-3.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ns-3.qhc" devhelp: $(IMAGES) $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/ns-3" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ns-3" @echo "# devhelp" epub: $(IMAGES) $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(IMAGES) $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(IMAGES) $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(IMAGES) $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(IMAGES) $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(IMAGES) $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(IMAGEs) $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(IMAGES) $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt."
m00re/ns-3-stdma
sources/doc/tutorial/Makefile
Makefile
gpl-2.0
5,358
/* IP tables module for matching the value of the IPv4 and TCP ECN bits * * (C) 2002 by Harald Welte <laforge@gnumonks.org> * * 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/in.h> #include <linux/ip.h> #include <net/ip.h> #include <linux/module.h> #include <linux/skbuff.h> #include <linux/tcp.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_ipv4/ip_tables.h> #include <linux/netfilter_ipv4/ipt_ecn.h> MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>"); MODULE_DESCRIPTION("Xtables: Explicit Congestion Notification (ECN) flag match for IPv4"); MODULE_LICENSE("GPL"); static inline bool match_ip(const struct sk_buff *skb, const struct ipt_ecn_info *einfo) { return (ip_hdr(skb)->tos & IPT_ECN_IP_MASK) == einfo->ip_ect; } static inline bool match_tcp(const struct sk_buff *skb, const struct ipt_ecn_info *einfo, bool *hotdrop) { struct tcphdr _tcph; const struct tcphdr *th; /* In practice, TCP match does this, so can't fail. But let's * be good citizens. */ th = skb_header_pointer(skb, ip_hdrlen(skb), sizeof(_tcph), &_tcph); if (th == NULL) { *hotdrop = false; return false; } if (einfo->operation & IPT_ECN_OP_MATCH_ECE) { if (einfo->invert & IPT_ECN_OP_MATCH_ECE) { if (th->ece == 1) return false; } else { if (th->ece == 0) return false; } } if (einfo->operation & IPT_ECN_OP_MATCH_CWR) { if (einfo->invert & IPT_ECN_OP_MATCH_CWR) { if (th->cwr == 1) return false; } else { if (th->cwr == 0) return false; } } return true; } static bool ecn_mt(const struct sk_buff *skb, const struct xt_match_param *par) { const struct ipt_ecn_info *info = par->matchinfo; if (info->operation & IPT_ECN_OP_MATCH_IP) if (!match_ip(skb, info)) return false; if (info->operation & (IPT_ECN_OP_MATCH_ECE|IPT_ECN_OP_MATCH_CWR)) { if (ip_hdr(skb)->protocol != IPPROTO_TCP) return false; if (!match_tcp(skb, info, par->hotdrop)) return false; } return true; } static bool ecn_mt_check(const struct xt_mtchk_param *par) { const struct ipt_ecn_info *info = par->matchinfo; const struct ipt_ip *ip = par->entryinfo; if (info->operation & IPT_ECN_OP_MATCH_MASK) return false; if (info->invert & IPT_ECN_OP_MATCH_MASK) return false; if (info->operation & (IPT_ECN_OP_MATCH_ECE|IPT_ECN_OP_MATCH_CWR) && ip->proto != IPPROTO_TCP) { printk(KERN_WARNING "ipt_ecn: can't match TCP bits in rule for" " non-tcp packets\n"); return false; } return true; } static struct xt_match ecn_mt_reg __read_mostly = { .name = "ecn", .family = NFPROTO_IPV4, .match = ecn_mt, .matchsize = sizeof(struct ipt_ecn_info), .checkentry = ecn_mt_check, .me = THIS_MODULE, }; static int __init ecn_mt_init(void) { return xt_register_match(&ecn_mt_reg); } static void __exit ecn_mt_exit(void) { xt_unregister_match(&ecn_mt_reg); } module_init(ecn_mt_init); module_exit(ecn_mt_exit);
blueskycoco/d2
net/ipv4/netfilter/ipt_ecn.c
C
gpl-2.0
3,085
/* mt6627_fm_config.c * * (C) Copyright 2011 * MediaTek <www.MediaTek.com> * hongcheng <hongcheng.xia@MediaTek.com> * * FM Radio Driver * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/string.h> #include <linux/slab.h> #include "fm_typedef.h" #include "fm_rds.h" #include "fm_dbg.h" #include "fm_err.h" #include "fm_stdlib.h" #include "fm_patch.h" #include "fm_config.h" /* #include "fm_cust_cfg.h" */ #include "mt6627_fm_cust_cfg.h" fm_cust_cfg mt6627_fm_config; /* static fm_s32 fm_index = 0; */ static fm_s32 MT6627fm_cust_config_print(fm_cust_cfg *cfg) { WCN_DBG(FM_NTC | MAIN, "MT6627 rssi_l:\t%d\n", cfg->rx_cfg.long_ana_rssi_th); WCN_DBG(FM_NTC | MAIN, "MT6627 rssi_s:\t%d\n", cfg->rx_cfg.short_ana_rssi_th); WCN_DBG(FM_NTC | MAIN, "MT6627 pamd_th:\t%d\n", cfg->rx_cfg.pamd_th); WCN_DBG(FM_NTC | MAIN, "MT6627 mr_th:\t%d\n", cfg->rx_cfg.mr_th); WCN_DBG(FM_NTC | MAIN, "MT6627 atdc_th:\t%d\n", cfg->rx_cfg.atdc_th); WCN_DBG(FM_NTC | MAIN, "MT6627 prx_th:\t%d\n", cfg->rx_cfg.prx_th); WCN_DBG(FM_NTC | MAIN, "MT6627 atdev_th:\t%d\n", cfg->rx_cfg.atdev_th); WCN_DBG(FM_NTC | MAIN, "MT6627 smg_th:\t%d\n", cfg->rx_cfg.smg_th); WCN_DBG(FM_NTC | MAIN, "de_emphasis:\t%d\n", cfg->rx_cfg.deemphasis); WCN_DBG(FM_NTC | MAIN, "osc_freq:\t%d\n", cfg->rx_cfg.osc_freq); WCN_DBG(FM_NTC | MAIN, "aud path[%d]I2S state[%d]mode[%d]rate[%d]\n", cfg->aud_cfg.aud_path, cfg->aud_cfg.i2s_info.status, cfg->aud_cfg.i2s_info.mode, cfg->aud_cfg.i2s_info.rate); return 0; } static fm_s32 MT6627cfg_item_handler(fm_s8 *grp, fm_s8 *key, fm_s8 *val, fm_cust_cfg *cfg) { fm_s32 ret = 0; struct fm_rx_cust_cfg *rx_cfg = &cfg->rx_cfg; if (0 <= (ret = cfg_item_match(key, val, "FM_RX_RSSI_TH_LONG_MT6627", &rx_cfg->long_ana_rssi_th))) { /* FMR_RSSI_TH_L = 0x0301 */ return ret; } else if (0 <= (ret = cfg_item_match(key, val, "FM_RX_RSSI_TH_SHORT_MT6627", &rx_cfg->short_ana_rssi_th))) { return ret; } else if (0 <= (ret = cfg_item_match(key, val, "FM_RX_DESENSE_RSSI_MT6627", &rx_cfg->desene_rssi_th))) { return ret; } else if (0 <= (ret = cfg_item_match(key, val, "FM_RX_PAMD_TH_MT6627", &rx_cfg->pamd_th))) { return ret; } else if (0 <= (ret = cfg_item_match(key, val, "FM_RX_MR_TH_MT6627", &rx_cfg->mr_th))) { return ret; } else if (0 <= (ret = cfg_item_match(key, val, "FM_RX_ATDC_TH_MT6627", &rx_cfg->atdc_th))) { return ret; } else if (0 <= (ret = cfg_item_match(key, val, "FM_RX_PRX_TH_MT6627", &rx_cfg->prx_th))) { return ret; } /*else if (0 <= (ret = cfg_item_match(key, val, "FM_RX_ATDEV_TH_MT6627", &rx_cfg->atdev_th))) { return ret; } */ else if (0 <= (ret = cfg_item_match(key, val, "FM_RX_SMG_TH_MT6627", &rx_cfg->smg_th))) { return ret; } else if (0 <= (ret = cfg_item_match(key, val, "FM_RX_DEEMPHASIS_MT6627", &rx_cfg->deemphasis))) { return ret; } else if (0 <= (ret = cfg_item_match(key, val, "FM_RX_OSC_FREQ_MT6627", &rx_cfg->osc_freq))) { return ret; } else { WCN_DBG(FM_WAR | MAIN, "MT6627 invalid key\n"); return -1; } } static fm_s32 MT6627fm_cust_config_default(fm_cust_cfg *cfg) { FMR_ASSERT(cfg); cfg->rx_cfg.long_ana_rssi_th = FM_RX_RSSI_TH_LONG_MT6627; cfg->rx_cfg.short_ana_rssi_th = FM_RX_RSSI_TH_SHORT_MT6627; cfg->rx_cfg.desene_rssi_th = FM_RX_DESENSE_RSSI_MT6627; cfg->rx_cfg.pamd_th = FM_RX_PAMD_TH_MT6627; cfg->rx_cfg.mr_th = FM_RX_MR_TH_MT6627; cfg->rx_cfg.atdc_th = FM_RX_ATDC_TH_MT6627; cfg->rx_cfg.prx_th = FM_RX_PRX_TH_MT6627; cfg->rx_cfg.smg_th = FM_RX_SMG_TH_MT6627; cfg->rx_cfg.deemphasis = FM_RX_DEEMPHASIS_MT6627; cfg->rx_cfg.osc_freq = FM_RX_OSC_FREQ_MT6627; cfg->aud_cfg.aud_path = FM_AUD_I2S; cfg->aud_cfg.i2s_info.status = FM_I2S_OFF; cfg->aud_cfg.i2s_info.mode = FM_I2S_MASTER; cfg->aud_cfg.i2s_info.rate = FM_I2S_32K; cfg->aud_cfg.i2s_pad = FM_I2S_PAD_CONN; return 0; } static fm_s32 MT6627fm_cust_config_file(const fm_s8 *filename, fm_cust_cfg *cfg) { fm_s32 ret = 0; fm_s8 *buf = NULL; fm_s32 file_len = 0; if (!(buf = fm_zalloc(4096))) { WCN_DBG(FM_ALT | MAIN, "-ENOMEM\n"); return -ENOMEM; } /* fm_index = 0; */ file_len = fm_file_read(filename, buf, 4096, 0); if (file_len <= 0) { ret = -1; goto out; } ret = cfg_parser(buf, MT6627cfg_item_handler, cfg); out: if (buf) { fm_free(buf); } return ret; } #define MT6627_FM_CUST_CFG_PATH "etc/fmr/mt6627_fm_cust.cfg" fm_s32 MT6627fm_cust_config_setup(const fm_s8 *filepath) { fm_s32 ret = 0; fm_s8 *filep = NULL; fm_s8 file_path[51] = { 0 }; MT6627fm_cust_config_default(&mt6627_fm_config); WCN_DBG(FM_NTC | MAIN, "MT6627 FM default config\n"); MT6627fm_cust_config_print(&mt6627_fm_config); if (!filepath) { filep = MT6627_FM_CUST_CFG_PATH; } else { memcpy(file_path, filepath, (strlen(filepath) > 50) ? 50 : strlen(filepath)); filep = file_path; trim_path(&filep); } ret = MT6627fm_cust_config_file(filep, &mt6627_fm_config); WCN_DBG(FM_NTC | MAIN, "MT6627 FM cust config\n"); MT6627fm_cust_config_print(&mt6627_fm_config); return ret; }
bq/aquaris-E4
drivers/misc/mediatek/fmradio/mt6627/pub/mt6627_fm_config.c
C
gpl-2.0
5,715
#include <linux/init.h> #include <linux/pci.h> /* PCI interrupt pins */ #define PCIA 1 #define PCIB 2 #define PCIC 3 #define PCID 4 /* This table is filled in by interrogating the PIIX4 chip */ static char pci_irq[5] = { }; static char irq_tab[][5] __initdata = { /* INTA INTB INTC INTD */ {0, 0, 0, 0, 0 }, /* 0: GT64120 PCI bridge */ {0, 0, 0, 0, 0 }, /* 1: Unused */ {0, 0, 0, 0, 0 }, /* 2: Unused */ {0, 0, 0, 0, 0 }, /* 3: Unused */ {0, 0, 0, 0, 0 }, /* 4: Unused */ {0, 0, 0, 0, 0 }, /* 5: Unused */ {0, 0, 0, 0, 0 }, /* 6: Unused */ {0, 0, 0, 0, 0 }, /* 7: Unused */ {0, 0, 0, 0, 0 }, /* 8: Unused */ {0, 0, 0, 0, 0 }, /* 9: Unused */ {0, 0, 0, 0, PCID }, /* 10: PIIX4 USB */ {0, PCIB, 0, 0, 0 }, /* 11: AMD 79C973 Ethernet */ {0, PCIC, 0, 0, 0 }, /* 12: Crystal 4281 Sound */ {0, 0, 0, 0, 0 }, /* 13: Unused */ {0, 0, 0, 0, 0 }, /* 14: Unused */ {0, 0, 0, 0, 0 }, /* 15: Unused */ {0, 0, 0, 0, 0 }, /* 16: Unused */ {0, 0, 0, 0, 0 }, /* 17: Bonito/SOC-it PCI Bridge*/ {0, PCIA, PCIB, PCIC, PCID }, /* 18: PCI Slot 1 */ {0, PCIB, PCIC, PCID, PCIA }, /* 19: PCI Slot 2 */ {0, PCIC, PCID, PCIA, PCIB }, /* 20: PCI Slot 3 */ {0, PCID, PCIA, PCIB, PCIC } /* 21: PCI Slot 4 */ }; int __init pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) { int virq; virq = irq_tab[slot][pin]; return pci_irq[virq]; } /* Do platform specific device initialization at pci_enable_device() time */ int pcibios_plat_dev_init(struct pci_dev *dev) { return 0; } static void malta_piix_func0_fixup(struct pci_dev *pdev) { unsigned char reg_val; static int piixirqmap[16] = { /* PIIX PIRQC[A:D] irq mappings */ 0, 0, 0, 3, 4, 5, 6, 7, 0, 9, 10, 11, 12, 0, 14, 15 }; int i; /* Interrogate PIIX4 to get PCI IRQ mapping */ for (i = 0; i <= 3; i++) { pci_read_config_byte(pdev, 0x60+i, &reg_val); if (reg_val & 0x80) pci_irq[PCIA+i] = 0; /* Disabled */ else pci_irq[PCIA+i] = piixirqmap[reg_val & 15]; } /* Done by YAMON 2.00 onwards */ if (PCI_SLOT(pdev->devfn) == 10) { /* * Set top of main memory accessible by ISA or DMA * devices to 16 Mb. */ pci_read_config_byte(pdev, 0x69, &reg_val); pci_write_config_byte(pdev, 0x69, reg_val | 0xf0); } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB_0, malta_piix_func0_fixup); static void malta_piix_func1_fixup(struct pci_dev *pdev) { unsigned char reg_val; /* Done by YAMON 2.02 onwards */ if (PCI_SLOT(pdev->devfn) == 10) { /* * IDE Decode enable. */ pci_read_config_byte(pdev, 0x41, &reg_val); pci_write_config_byte(pdev, 0x41, reg_val|0x80); pci_read_config_byte(pdev, 0x43, &reg_val); pci_write_config_byte(pdev, 0x43, reg_val|0x80); } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB, malta_piix_func1_fixup); /* Enable PCI 2.1 compatibility in PIIX4 */ static void quirk_dlcsetup(struct pci_dev *dev) { u8 odlc, ndlc; (void) pci_read_config_byte(dev, 0x82, &odlc); /* Enable passive releases and delayed transaction */ ndlc = odlc | 7; (void) pci_write_config_byte(dev, 0x82, ndlc); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB_0, quirk_dlcsetup);
SanDisk-Open-Source/SSD_Dashboard
uefi/linux-source-3.8.0/arch/mips/pci/fixup-malta.c
C
gpl-2.0
3,224
<?php /** * Smarty Internal Plugin * * @package Smarty * @subpackage Cacher */ /** * Cache Handler API * * @package Smarty * @subpackage Cacher * @author Rodney Rehm */ abstract class Smarty_CacheResource { /** * cache for Smarty_CacheResource instances * @var array */ public static $resources = array(); /** * resource types provided by the core * @var array */ protected static $sysplugins = array( 'file' => true, ); /** * populate Cached Object with meta data from Resource * * @param Smarty_Template_Cached $cached cached object * @param Smarty_Internal_Template $_template template object * @return void */ public abstract function populate(Smarty_Template_Cached $cached, Smarty_Internal_Template $_template); /** * populate Cached Object with timestamp and exists from Resource * * @param Smarty_Template_Cached $source cached object * @return void */ public abstract function populateTimestamp(Smarty_Template_Cached $cached); /** * Read the cached template and process header * * @param Smarty_Internal_Template $_template template object * @param Smarty_Template_Cached $cached cached object * @return booelan true or false if the cached content does not exist */ public abstract function process(Smarty_Internal_Template $_template, Smarty_Template_Cached $cached=null); /** * Write the rendered template output to cache * * @param Smarty_Internal_Template $_template template object * @param string $content content to cache * @return boolean success */ public abstract function writeCachedContent(Smarty_Internal_Template $_template, $content); /** * Return cached content * * @param Smarty_Internal_Template $_template template object * @param string $content content of cache */ public function getCachedContent(Smarty_Internal_Template $_template) { if ($_template->cached->handler->process($_template)) { ob_start(); $_template->properties['unifunc']($_template); return ob_get_clean(); } return null; } /** * Empty cache * * @param Smarty $smarty Smarty object * @param integer $exp_time expiration time (number of seconds, not timestamp) * @return integer number of cache files deleted */ public abstract function clearAll(Smarty $smarty, $exp_time=null); /** * Empty cache for a specific template * * @param Smarty $smarty Smarty object * @param string $resource_name template name * @param string $cache_id cache id * @param string $compile_id compile id * @param integer $exp_time expiration time (number of seconds, not timestamp) * @return integer number of cache files deleted */ public abstract function clear(Smarty $smarty, $resource_name, $cache_id, $compile_id, $exp_time); public function locked(Smarty $smarty, Smarty_Template_Cached $cached) { // theoretically locking_timeout should be checked against time_limit (max_execution_time) $start = microtime(true); $hadLock = null; while ($this->hasLock($smarty, $cached)) { $hadLock = true; if (microtime(true) - $start > $smarty->locking_timeout) { // abort waiting for lock release return false; } sleep(1); } return $hadLock; } public function hasLock(Smarty $smarty, Smarty_Template_Cached $cached) { // check if lock exists return false; } public function acquireLock(Smarty $smarty, Smarty_Template_Cached $cached) { // create lock return true; } public function releaseLock(Smarty $smarty, Smarty_Template_Cached $cached) { // release lock return true; } /** * Load Cache Resource Handler * * @param Smarty $smarty Smarty object * @param string $type name of the cache resource * @return Smarty_CacheResource Cache Resource Handler */ public static function load(Smarty $smarty, $type = null) { if (!isset($type)) { $type = $smarty->caching_type; } // try smarty's cache if (isset($smarty->_cacheresource_handlers[$type])) { return $smarty->_cacheresource_handlers[$type]; } // try registered resource if (isset($smarty->registered_cache_resources[$type])) { // do not cache these instances as they may vary from instance to instance return $smarty->_cacheresource_handlers[$type] = $smarty->registered_cache_resources[$type]; } // try sysplugins dir if (isset(self::$sysplugins[$type])) { if (!isset(self::$resources[$type])) { $cache_resource_class = 'Smarty_Internal_CacheResource_' . ucfirst($type); self::$resources[$type] = new $cache_resource_class(); } return $smarty->_cacheresource_handlers[$type] = self::$resources[$type]; } // try plugins dir $cache_resource_class = 'Smarty_CacheResource_' . ucfirst($type); if ($smarty->loadPlugin($cache_resource_class)) { if (!isset(self::$resources[$type])) { self::$resources[$type] = new $cache_resource_class(); } return $smarty->_cacheresource_handlers[$type] = self::$resources[$type]; } // give up throw new SmartyException("Unable to load cache resource '{$type}'"); } /** * Invalid Loaded Cache Files * * @param Smarty $smarty Smarty object */ public static function invalidLoadedCache(Smarty $smarty) { foreach ($smarty->template_objects as $tpl) { if (isset($tpl->cached)) { $tpl->cached->valid = false; $tpl->cached->processed = false; } } } } /** * Smarty Resource Data Object * * Cache Data Container for Template Files * * @package Smarty * @subpackage TemplateResources * @author Rodney Rehm */ class Smarty_Template_Cached { /** * Source Filepath * @var string */ public $filepath = false; /** * Source Content * @var string */ public $content = null; /** * Source Timestamp * @var integer */ public $timestamp = false; /** * Source Existance * @var boolean */ public $exists = false; /** * Cache Is Valid * @var boolean */ public $valid = false; /** * Cache was processed * @var boolean */ public $processed = false; /** * CacheResource Handler * @var Smarty_CacheResource */ public $handler = null; /** * Template Compile Id (Smarty_Internal_Template::$compile_id) * @var string */ public $compile_id = null; /** * Template Cache Id (Smarty_Internal_Template::$cache_id) * @var string */ public $cache_id = null; /** * Id for cache locking * @var string */ public $lock_id = null; /** * flag that cache is locked by this instance * @var bool */ public $is_locked = false; /** * Source Object * @var Smarty_Template_Source */ public $source = null; /** * create Cached Object container * * @param Smarty_Internal_Template $_template template object */ public function __construct(Smarty_Internal_Template $_template) { $this->compile_id = $_template->compile_id; $this->cache_id = $_template->cache_id; $this->source = $_template->source; $_template->cached = $this; $smarty = $_template->smarty; // // load resource handler // $this->handler = $handler = Smarty_CacheResource::load($smarty); // Note: prone to circular references // // check if cache is valid // if (!($_template->caching == Smarty::CACHING_LIFETIME_CURRENT || $_template->caching == Smarty::CACHING_LIFETIME_SAVED) || $_template->source->recompiled) { return; } while (true) { while (true) { $handler->populate($this, $_template); if ($this->timestamp === false || $smarty->force_compile || $smarty->force_cache) { $this->valid = false; } else { $this->valid = true; } if ($this->valid && $_template->caching == Smarty::CACHING_LIFETIME_CURRENT && $_template->cache_lifetime >= 0 && time() > ($this->timestamp + $_template->cache_lifetime)) { // lifetime expired $this->valid = false; } if ($this->valid || !$_template->smarty->cache_locking) { break; } if (!$this->handler->locked($_template->smarty, $this)) { $this->handler->acquireLock($_template->smarty, $this); break 2; } } if ($this->valid) { if (!$_template->smarty->cache_locking || $this->handler->locked($_template->smarty, $this) === null) { // load cache file for the following checks if ($smarty->debugging) { Smarty_Internal_Debug::start_cache($_template); } if($handler->process($_template, $this) === false) { $this->valid = false; } else { $this->processed = true; } if ($smarty->debugging) { Smarty_Internal_Debug::end_cache($_template); } } else { continue; } } else { return; } if ($this->valid && $_template->caching === Smarty::CACHING_LIFETIME_SAVED && $_template->properties['cache_lifetime'] >= 0 && (time() > ($_template->cached->timestamp + $_template->properties['cache_lifetime']))) { $this->valid = false; } if (!$this->valid && $_template->smarty->cache_locking) { $this->handler->acquireLock($_template->smarty, $this); return; } else { return; } } } /** * Write this cache object to handler * * @param Smarty_Internal_Template $_template template object * @param string $content content to cache * @return boolean success */ public function write(Smarty_Internal_Template $_template, $content) { if (!$_template->source->recompiled) { if ($this->handler->writeCachedContent($_template, $content)) { $this->timestamp = time(); $this->exists = true; $this->valid = true; if ($_template->smarty->cache_locking) { $this->handler->releaseLock($_template->smarty, $this); } return true; } } return false; } } ?>
MetSystem/fis
test/libs/smarty-3.1.5/sysplugins/smarty_cacheresource.php
PHP
mit
11,323
#undef MMC_STRPCL #undef MMC_STAT #undef MMC_CLKRT #undef MMC_SPI #undef MMC_CMDAT #undef MMC_RESTO #undef MMC_RDTO #undef MMC_BLKLEN #undef MMC_NOB #undef MMC_PRTBUF #undef MMC_I_MASK #undef END_CMD_RES #undef PRG_DONE #undef DATA_TRAN_DONE #undef MMC_I_REG #undef MMC_CMD #undef MMC_ARGH #undef MMC_ARGL #undef MMC_RES #undef MMC_RXFIFO #undef MMC_TXFIFO #define MMC_STRPCL 0x0000 #define STOP_CLOCK (1 << 0) #define START_CLOCK (2 << 0) #define MMC_STAT 0x0004 #define STAT_END_CMD_RES (1 << 13) #define STAT_PRG_DONE (1 << 12) #define STAT_DATA_TRAN_DONE (1 << 11) #define STAT_CLK_EN (1 << 8) #define STAT_RECV_FIFO_FULL (1 << 7) #define STAT_XMIT_FIFO_EMPTY (1 << 6) #define STAT_RES_CRC_ERR (1 << 5) #define STAT_SPI_READ_ERROR_TOKEN (1 << 4) #define STAT_CRC_READ_ERROR (1 << 3) #define STAT_CRC_WRITE_ERROR (1 << 2) #define STAT_TIME_OUT_RESPONSE (1 << 1) #define STAT_READ_TIME_OUT (1 << 0) #define MMC_CLKRT 0x0008 /* 3 bit */ #define MMC_SPI 0x000c #define SPI_CS_ADDRESS (1 << 3) #define SPI_CS_EN (1 << 2) #define CRC_ON (1 << 1) #define SPI_EN (1 << 0) #define MMC_CMDAT 0x0010 #define CMDAT_DMAEN (1 << 7) #define CMDAT_INIT (1 << 6) #define CMDAT_BUSY (1 << 5) #define CMDAT_STREAM (1 << 4) /* 1 = stream */ #define CMDAT_WRITE (1 << 3) /* 1 = write */ #define CMDAT_DATAEN (1 << 2) #define CMDAT_RESP_NONE (0 << 0) #define CMDAT_RESP_SHORT (1 << 0) #define CMDAT_RESP_R2 (2 << 0) #define CMDAT_RESP_R3 (3 << 0) #define MMC_RESTO 0x0014 /* 7 bit */ #define MMC_RDTO 0x0018 /* 16 bit */ #define MMC_BLKLEN 0x001c /* 10 bit */ #define MMC_NOB 0x0020 /* 16 bit */ #define MMC_PRTBUF 0x0024 #define BUF_PART_FULL (1 << 0) #define MMC_I_MASK 0x0028 /*PXA27x MMC interrupts*/ #define SDIO_SUSPEND_ACK (1 << 12) #define SDIO_INT (1 << 11) #define RD_STALLED (1 << 10) #define RES_ERR (1 << 9) #define DAT_ERR (1 << 8) #define TINT (1 << 7) /*PXA2xx MMC interrupts*/ #define TXFIFO_WR_REQ (1 << 6) #define RXFIFO_RD_REQ (1 << 5) #define CLK_IS_OFF (1 << 4) #define STOP_CMD (1 << 3) #define END_CMD_RES (1 << 2) #define PRG_DONE (1 << 1) #define DATA_TRAN_DONE (1 << 0) #ifdef CONFIG_PXA27x #define MMC_I_MASK_ALL 0x00001fff #else #define MMC_I_MASK_ALL 0x0000007f #endif #define MMC_I_REG 0x002c /* same as MMC_I_MASK */ #define MMC_CMD 0x0030 #define MMC_ARGH 0x0034 /* 16 bit */ #define MMC_ARGL 0x0038 /* 16 bit */ #define MMC_RES 0x003c /* 16 bit */ #define MMC_RXFIFO 0x0040 /* 8 bit */ #define MMC_TXFIFO 0x0044 /* 8 bit */ /* * The base MMC clock rate */ #ifdef CONFIG_PXA27x #define CLOCKRATE_MIN 304688 #define CLOCKRATE_MAX 19500000 #else #define CLOCKRATE_MIN 312500 #define CLOCKRATE_MAX 20000000 #endif #define CLOCKRATE CLOCKRATE_MAX
impedimentToProgress/UCI-BlueChip
snapgear_linux/linux-2.6.21.1/drivers/mmc/pxamci.h
C
mit
2,801
<?php sspmod_cdc_Server::processRequest();
REI-Systems/GovDashboard-Community
webapp/sites/all/libraries/simplesamlphp/modules/cdc/www/server.php
PHP
gpl-3.0
43
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_POLICY_CORE_COMMON_CLOUD_MOCK_CLOUD_EXTERNAL_DATA_MANAGER_H_ #define COMPONENTS_POLICY_CORE_COMMON_CLOUD_MOCK_CLOUD_EXTERNAL_DATA_MANAGER_H_ #include <string> #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "components/policy/core/common/cloud/cloud_external_data_manager.h" #include "components/policy/core/common/external_data_fetcher.h" #include "testing/gmock/include/gmock/gmock.h" namespace net { class URLRequestContextGetter; } namespace policy { class ExternalDataFetcher; class MockCloudExternalDataManager : public CloudExternalDataManager { public: MockCloudExternalDataManager(); virtual ~MockCloudExternalDataManager(); MOCK_METHOD0(OnPolicyStoreLoaded, void(void)); MOCK_METHOD1(Connect, void(scoped_refptr<net::URLRequestContextGetter>)); MOCK_METHOD0(Disconnect, void(void)); MOCK_METHOD2(Fetch, void(const std::string&, const ExternalDataFetcher::FetchCallback&)); scoped_ptr<ExternalDataFetcher> CreateExternalDataFetcher( const std::string& policy); private: DISALLOW_COPY_AND_ASSIGN(MockCloudExternalDataManager); }; } // namespace policy #endif // COMPONENTS_POLICY_CORE_COMMON_CLOUD_MOCK_CLOUD_EXTERNAL_DATA_MANAGER_H_
s20121035/rk3288_android5.1_repo
external/chromium_org/components/policy/core/common/cloud/mock_cloud_external_data_manager.h
C
gpl-3.0
1,454
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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. */ /** * @license AngularJS v1.2.13 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc overview * @name ngRoute * @description * * # ngRoute * * The `ngRoute` module provides routing and deeplinking services and directives for angular apps. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * {@installModule route} * * <div doc-module-components="ngRoute"></div> */ /* global -ngRouteModule */ var ngRouteModule = angular.module('ngRoute', ['ng']). provider('$route', $RouteProvider); /** * @ngdoc object * @name ngRoute.$routeProvider * @function * * @description * * Used for configuring routes. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * ## Dependencies * Requires the {@link ngRoute `ngRoute`} module to be installed. */ function $RouteProvider(){ function inherit(parent, extra) { return angular.extend(new (angular.extend(function() {}, {prototype:parent}))(), extra); } var routes = {}; /** * @ngdoc method * @name ngRoute.$routeProvider#when * @methodOf ngRoute.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exactly match the * route definition. * * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up * to the next slash are matched and stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain named groups starting with a colon and ending with a star: * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain optional named groups with a question mark: e.g.`:name?`. * * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match * `/color/brown/largecode/code/with/slashs/edit` and extract: * * * `color: brown` * * `largecode: code/with/slashs`. * * * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{(string|function()=}` – Controller fn that should be associated with * newly created scope or the name of a {@link angular.Module#controller registered * controller} if passed as a string. * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be * published to scope under the `controllerAs` name. * - `template` – `{string=|function()=}` – html template as a string or a function that * returns an html template as a string which should be used by {@link * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. * This property takes precedence over `templateUrl`. * * If `template` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html * template that should be used by {@link ngRoute.directive:ngView ngView}. * * If `templateUrl` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, the router * will wait for them all to be resolved or one to be rejected before the controller is * instantiated. * If all the promises are resolved successfully, the values of the resolved promises are * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is * fired. If any of the promises are rejected the * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object * is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is * resolved before its value is injected into the controller. Be aware that * `ngRoute.$routeParams` will still refer to the previous route within these resolve * functions. Use `$route.current.params` to access the new route parameters, instead. * * - `redirectTo` – {(string|function())=} – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` * or `$location.hash()` changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive * * If the option is set to `true`, then the particular route can be matched without being * case sensitive * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = angular.extend( {reloadOnSearch: true}, route, path && pathRegExp(path, route) ); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = angular.extend( {redirectTo: path}, pathRegExp(redirectPath, route) ); } return this; }; /** * @param path {string} path * @param opts {Object} options * @return {?Object} * * @description * Normalizes the given path, returning a regular expression * and the original path. * * Inspired by pathRexp in visionmedia/express/lib/utils.js. */ function pathRegExp(path, opts) { var insensitive = opts.caseInsensitiveMatch, ret = { originalPath: path, regexp: path }, keys = ret.keys = []; path = path .replace(/([().])/g, '\\$1') .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option){ var optional = option === '?' ? option : null; var star = option === '*' ? option : null; keys.push({ name: key, optional: !!optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (star && '(.+?)' || '([^/]+)') + (optional || '') + ')' + (optional || ''); }) .replace(/([\/$\*])/g, '\\$1'); ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); return ret; } /** * @ngdoc method * @name ngRoute.$routeProvider#otherwise * @methodOf ngRoute.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', '$sce', function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { /** * @ngdoc object * @name ngRoute.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Array.<Object>} routes Array of all configured routes. * * @description * `$route` is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with the * {@link ngRoute.directive:ngView `ngView`} directive and the * {@link ngRoute.$routeParams `$routeParams`} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link ng.directive:script inlined templates} to get it working on jsfiddle as well. <example module="ngViewExample" deps="angular-route.js"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute']) .config(function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="protractorTest.js"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeStart * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occur. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * @param {Object} angularEvent Synthetic event object. * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeSuccess * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted after a route dependencies are resolved. * {@link ngRoute.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Object} angularEvent Synthetic event object. * @param {Route} current Current route information. * @param {Route|Undefined} previous Previous route information, or undefined if current is * first route entered. */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeError * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Object} angularEvent Synthetic event object * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name ngRoute.$route#$routeUpdate * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name ngRoute.$route#reload * @methodOf ngRoute.$route * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ngRoute.directive:ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(updateRoute); } }; $rootScope.$on('$locationChangeSuccess', updateRoute); return $route; ///////////////////////////////////////////////////// /** * @param on {string} current url * @param route {Object} route regexp to match the url against * @return {?Object} * * @description * Check if the route matches the current url. * * Inspired by match in * visionmedia/express/lib/router/router.js. */ function switchRouteMatcher(on, route) { var keys = route.keys, params = {}; if (!route.regexp) return null; var m = route.regexp.exec(on); if (!m) return null; for (var i = 1, len = m.length; i < len; ++i) { var key = keys[i - 1]; var val = 'string' == typeof m[i] ? decodeURIComponent(m[i]) : m[i]; if (key && val) { params[key.name] = val; } } return params; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$$route === last.$$route && angular.equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; angular.copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$routeChangeStart', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (angular.isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(next). then(function() { if (next) { var locals = angular.extend({}, next.resolve), template, templateUrl; angular.forEach(locals, function(value, key) { locals[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value); }); if (angular.isDefined(template = next.template)) { if (angular.isFunction(template)) { template = template(next.params); } } else if (angular.isDefined(templateUrl = next.templateUrl)) { if (angular.isFunction(templateUrl)) { templateUrl = templateUrl(next.params); } templateUrl = $sce.getTrustedResourceUrl(templateUrl); if (angular.isDefined(templateUrl)) { next.loadedTemplateUrl = templateUrl; template = $http.get(templateUrl, {cache: $templateCache}). then(function(response) { return response.data; }); } } if (angular.isDefined(template)) { locals['$template'] = template; } return $q.all(locals); } }). // after route change then(function(locals) { if (next == $route.current) { if (next) { next.locals = locals; angular.copy(next.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', next, last); } }, function(error) { if (next == $route.current) { $rootScope.$broadcast('$routeChangeError', next, last, error); } }); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; angular.forEach(routes, function(route, path) { if (!match && (params = switchRouteMatcher($location.path(), route))) { match = inherit(route, { params: angular.extend({}, $location.search(), params), pathParams: params}); match.$$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parameters */ function interpolate(string, params) { var result = []; angular.forEach((string||'').split(':'), function(segment, i) { if (i === 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } ngRouteModule.provider('$routeParams', $RouteParamsProvider); /** * @ngdoc object * @name ngRoute.$routeParams * @requires $route * * @description * The `$routeParams` service allows you to retrieve the current set of route parameters. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * The route parameters are a combination of {@link ng.$location `$location`}'s * {@link ng.$location#methods_search `search()`} and {@link ng.$location#methods_path `path()`}. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * Note that the `$routeParams` are only updated *after* a route change completes successfully. * This means that you cannot rely on `$routeParams` being correct in route resolve functions. * Instead you can use `$route.current.params` to access the new route's parameters. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = function() { return {}; }; } ngRouteModule.directive('ngView', ngViewFactory); ngRouteModule.directive('ngView', ngViewFillContentFactory); /** * @ngdoc directive * @name ngRoute.directive:ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * @animations * enter - animation is used to bring new content into the browser. * leave - animation is used to animate existing content away. * * The enter and leave animation occur concurrently. * * @scope * @priority 400 * @param {string=} onload Expression to evaluate whenever the view updates. * * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the view is updated. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated * as an expression yields a truthy value. * @example <example module="ngViewExample" deps="angular-route.js" animations="true"> <file name="index.html"> <div ng-controller="MainCntl as main"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div class="view-animate-container"> <div ng-view class="view-animate"></div> </div> <hr /> <pre>$location.path() = {{main.$location.path()}}</pre> <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre> <pre>$route.current.params = {{main.$route.current.params}}</pre> <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre> <pre>$routeParams = {{main.$routeParams}}</pre> </div> </file> <file name="book.html"> <div> controller: {{book.name}}<br /> Book Id: {{book.params.bookId}}<br /> </div> </file> <file name="chapter.html"> <div> controller: {{chapter.name}}<br /> Book Id: {{chapter.params.bookId}}<br /> Chapter Id: {{chapter.params.chapterId}} </div> </file> <file name="animations.css"> .view-animate-container { position:relative; height:100px!important; position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .view-animate { padding:10px; } .view-animate.ng-enter, .view-animate.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; display:block; width:100%; border-left:1px solid black; position:absolute; top:0; left:0; right:0; bottom:0; padding:10px; } .view-animate.ng-enter { left:100%; } .view-animate.ng-enter.ng-enter-active { left:0; } .view-animate.ng-leave.ng-leave-active { left:-100%; } </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute', 'ngAnimate'], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, controllerAs: 'book' }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl, controllerAs: 'chapter' }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; } function BookCntl($routeParams) { this.name = "BookCntl"; this.params = $routeParams; } function ChapterCntl($routeParams) { this.name = "ChapterCntl"; this.params = $routeParams; } </file> <file name="protractorTest.js"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ngRoute.directive:ngView#$viewContentLoaded * @eventOf ngRoute.directive:ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; function ngViewFactory( $route, $anchorScroll, $animate) { return { restrict: 'ECA', terminal: true, priority: 400, transclude: 'element', link: function(scope, $element, attr, ctrl, $transclude) { var currentScope, currentElement, autoScrollExp = attr.autoscroll, onloadExp = attr.onload || ''; scope.$on('$routeChangeSuccess', update); update(); function cleanupLastView() { if (currentScope) { currentScope.$destroy(); currentScope = null; } if(currentElement) { $animate.leave(currentElement); currentElement = null; } } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (angular.isDefined(template)) { var newScope = scope.$new(); var current = $route.current; // Note: This will also link all children of ng-view that were contained in the original // html. If that content contains controllers, ... they could pollute/change the scope. // However, using ng-view on an element with additional content does not make sense... // Note: We can't remove them in the cloneAttchFn of $transclude as that // function is called before linking the content, which would apply child // directives to non existing elements. var clone = $transclude(newScope, function(clone) { $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () { if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } }); cleanupLastView(); }); currentElement = clone; currentScope = current.scope = newScope; currentScope.$emit('$viewContentLoaded'); currentScope.$eval(onloadExp); } else { cleanupLastView(); } } } }; } // This directive is called during the $transclude call of the first `ngView` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngView // is called. ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; function ngViewFillContentFactory($compile, $controller, $route) { return { restrict: 'ECA', priority: -400, link: function(scope, $element) { var current = $route.current, locals = current.locals; $element.html(locals.$template); var link = $compile($element.contents()); if (current.controller) { locals.$scope = scope; var controller = $controller(current.controller, locals); if (current.controllerAs) { scope[current.controllerAs] = controller; } $element.data('$ngControllerController', controller); $element.children().data('$ngControllerController', controller); } link(scope); } }; } })(window, window.angular);
mbaluch/keycloak
testsuite/integration-arquillian/test-apps/cors/angular-product/src/main/webapp/lib/angular/angular-route.js
JavaScript
apache-2.0
33,181
#!/usr/bin/perl -w # # Copyright 2005-2009 - Steven Rostedt # Licensed under the terms of the GNU GPL License version 2 # # It's simple enough to figure out how this works. # If not, then you can ask me at stripconfig@goodmis.org # # What it does? # # If you have installed a Linux kernel from a distribution # that turns on way too many modules than you need, and # you only want the modules you use, then this program # is perfect for you. # # It gives you the ability to turn off all the modules that are # not loaded on your system. # # Howto: # # 1. Boot up the kernel that you want to stream line the config on. # 2. Change directory to the directory holding the source of the # kernel that you just booted. # 3. Copy the configuraton file to this directory as .config # 4. Have all your devices that you need modules for connected and # operational (make sure that their corresponding modules are loaded) # 5. Run this script redirecting the output to some other file # like config_strip. # 6. Back up your old config (if you want too). # 7. copy the config_strip file to .config # 8. Run "make oldconfig" # # Now your kernel is ready to be built with only the modules that # are loaded. # # Here's what I did with my Debian distribution. # # cd /usr/src/linux-2.6.10 # cp /boot/config-2.6.10-1-686-smp .config # ~/bin/streamline_config > config_strip # mv .config config_sav # mv config_strip .config # make oldconfig # use strict; use Getopt::Long; my $config = ".config"; my $uname = `uname -r`; chomp $uname; my @searchconfigs = ( { "file" => ".config", "exec" => "cat", }, { "file" => "/proc/config.gz", "exec" => "zcat", }, { "file" => "/boot/config-$uname", "exec" => "cat", }, { "file" => "/boot/vmlinuz-$uname", "exec" => "scripts/extract-ikconfig", "test" => "scripts/extract-ikconfig", }, { "file" => "vmlinux", "exec" => "scripts/extract-ikconfig", "test" => "scripts/extract-ikconfig", }, { "file" => "/lib/modules/$uname/kernel/kernel/configs.ko", "exec" => "scripts/extract-ikconfig", "test" => "scripts/extract-ikconfig", }, { "file" => "kernel/configs.ko", "exec" => "scripts/extract-ikconfig", "test" => "scripts/extract-ikconfig", }, { "file" => "kernel/configs.o", "exec" => "scripts/extract-ikconfig", "test" => "scripts/extract-ikconfig", }, ); sub find_config { foreach my $conf (@searchconfigs) { my $file = $conf->{"file"}; next if ( ! -f "$file"); if (defined($conf->{"test"})) { `$conf->{"test"} $conf->{"file"} 2>/dev/null`; next if ($?); } my $exec = $conf->{"exec"}; print STDERR "using config: '$file'\n"; open(CIN, "$exec $file |") || die "Failed to run $exec $file"; return; } die "No config file found"; } find_config; # Parse options my $localmodconfig = 0; my $localyesconfig = 0; GetOptions("localmodconfig" => \$localmodconfig, "localyesconfig" => \$localyesconfig); # Get the build source and top level Kconfig file (passed in) my $ksource = $ARGV[0]; my $kconfig = $ARGV[1]; my $lsmod_file = $ENV{'LSMOD'}; my @makefiles = `find $ksource -name Makefile 2>/dev/null`; chomp @makefiles; my %depends; my %selects; my %prompts; my %objects; my $var; my $iflevel = 0; my @ifdeps; # prevent recursion my %read_kconfigs; sub read_kconfig { my ($kconfig) = @_; my $state = "NONE"; my $config; my @kconfigs; my $cont = 0; my $line; my $source = "$ksource/$kconfig"; my $last_source = ""; # Check for any environment variables used while ($source =~ /\$(\w+)/ && $last_source ne $source) { my $env = $1; $last_source = $source; $source =~ s/\$$env/$ENV{$env}/; } open(KIN, "$source") || die "Can't open $kconfig"; while (<KIN>) { chomp; # Make sure that lines ending with \ continue if ($cont) { $_ = $line . " " . $_; } if (s/\\$//) { $cont = 1; $line = $_; next; } $cont = 0; # collect any Kconfig sources if (/^source\s*"(.*)"/) { $kconfigs[$#kconfigs+1] = $1; } # configs found if (/^\s*(menu)?config\s+(\S+)\s*$/) { $state = "NEW"; $config = $2; for (my $i = 0; $i < $iflevel; $i++) { if ($i) { $depends{$config} .= " " . $ifdeps[$i]; } else { $depends{$config} = $ifdeps[$i]; } $state = "DEP"; } # collect the depends for the config } elsif ($state eq "NEW" && /^\s*depends\s+on\s+(.*)$/) { $state = "DEP"; $depends{$config} = $1; } elsif ($state eq "DEP" && /^\s*depends\s+on\s+(.*)$/) { $depends{$config} .= " " . $1; # Get the configs that select this config } elsif ($state ne "NONE" && /^\s*select\s+(\S+)/) { if (defined($selects{$1})) { $selects{$1} .= " " . $config; } else { $selects{$1} = $config; } # configs without prompts must be selected } elsif ($state ne "NONE" && /^\s*tristate\s\S/) { # note if the config has a prompt $prompts{$config} = 1; # Check for if statements } elsif (/^if\s+(.*\S)\s*$/) { my $deps = $1; # remove beginning and ending non text $deps =~ s/^[^a-zA-Z0-9_]*//; $deps =~ s/[^a-zA-Z0-9_]*$//; my @deps = split /[^a-zA-Z0-9_]+/, $deps; $ifdeps[$iflevel++] = join ':', @deps; } elsif (/^endif/) { $iflevel-- if ($iflevel); # stop on "help" } elsif (/^\s*help\s*$/) { $state = "NONE"; } } close(KIN); # read in any configs that were found. foreach $kconfig (@kconfigs) { if (!defined($read_kconfigs{$kconfig})) { $read_kconfigs{$kconfig} = 1; read_kconfig($kconfig); } } } if ($kconfig) { read_kconfig($kconfig); } sub convert_vars { my ($line, %vars) = @_; my $process = ""; while ($line =~ s/^(.*?)(\$\((.*?)\))//) { my $start = $1; my $variable = $2; my $var = $3; if (defined($vars{$var})) { $process .= $start . $vars{$var}; } else { $process .= $start . $variable; } } $process .= $line; return $process; } # Read all Makefiles to map the configs to the objects foreach my $makefile (@makefiles) { my $line = ""; my %make_vars; open(MIN,$makefile) || die "Can't open $makefile"; while (<MIN>) { # if this line ends with a backslash, continue chomp; if (/^(.*)\\$/) { $line .= $1; next; } $line .= $_; $_ = $line; $line = ""; my $objs; $_ = convert_vars($_, %make_vars); # collect objects after obj-$(CONFIG_FOO_BAR) if (/obj-\$\((CONFIG_[^\)]*)\)\s*[+:]?=\s*(.*)/) { $var = $1; $objs = $2; # check if variables are set } elsif (/^\s*(\S+)\s*[:]?=\s*(.*\S)/) { $make_vars{$1} = $2; } if (defined($objs)) { foreach my $obj (split /\s+/,$objs) { $obj =~ s/-/_/g; if ($obj =~ /(.*)\.o$/) { # Objects may be enabled by more than one config. # Store configs in an array. my @arr; if (defined($objects{$1})) { @arr = @{$objects{$1}}; } $arr[$#arr+1] = $var; # The objects have a hash mapping to a reference # of an array of configs. $objects{$1} = \@arr; } } } } close(MIN); } my %modules; if (defined($lsmod_file)) { if ( ! -f $lsmod_file) { if ( -f $ENV{'objtree'}."/".$lsmod_file) { $lsmod_file = $ENV{'objtree'}."/".$lsmod_file; } else { die "$lsmod_file not found"; } } if ( -x $lsmod_file) { # the file is executable, run it open(LIN, "$lsmod_file|"); } else { # Just read the contents open(LIN, "$lsmod_file"); } } else { # see what modules are loaded on this system my $lsmod; foreach my $dir ( ("/sbin", "/bin", "/usr/sbin", "/usr/bin") ) { if ( -x "$dir/lsmod" ) { $lsmod = "$dir/lsmod"; last; } } if (!defined($lsmod)) { # try just the path $lsmod = "lsmod"; } open(LIN,"$lsmod|") || die "Can not call lsmod with $lsmod"; } while (<LIN>) { next if (/^Module/); # Skip the first line. if (/^(\S+)/) { $modules{$1} = 1; } } close (LIN); # add to the configs hash all configs that are needed to enable # a loaded module. my %configs; foreach my $module (keys(%modules)) { if (defined($objects{$module})) { my @arr = @{$objects{$module}}; foreach my $conf (@arr) { $configs{$conf} = $module; } } else { # Most likely, someone has a custom (binary?) module loaded. print STDERR "$module config not found!!\n"; } } my $valid = "A-Za-z_0-9"; my $repeat = 1; # # Note, we do not care about operands (like: &&, ||, !) we want to add any # config that is in the depend list of another config. This script does # not enable configs that are not already enabled. If we come across a # config A that depends on !B, we can still add B to the list of depends # to keep on. If A was on in the original config, B would not have been # and B would not be turned on by this script. # sub parse_config_dep_select { my ($p) = @_; while ($p =~ /[$valid]/) { if ($p =~ /^[^$valid]*([$valid]+)/) { my $conf = "CONFIG_" . $1; $p =~ s/^[^$valid]*[$valid]+//; if (!defined($configs{$conf})) { # We must make sure that this config has its # dependencies met. $repeat = 1; # do again $configs{$conf} = 1; } } else { die "this should never happen"; } } } while ($repeat) { $repeat = 0; foreach my $config (keys %configs) { $config =~ s/^CONFIG_//; if (defined($depends{$config})) { # This config has dependencies. Make sure they are also included parse_config_dep_select $depends{$config}; } if (defined($prompts{$config}) || !defined($selects{$config})) { next; } # config has no prompt and must be selected. parse_config_dep_select $selects{$config}; } } my %setconfigs; # Finally, read the .config file and turn off any module enabled that # we could not find a reason to keep enabled. while(<CIN>) { if (/CONFIG_IKCONFIG/) { if (/# CONFIG_IKCONFIG is not set/) { # enable IKCONFIG at least as a module print "CONFIG_IKCONFIG=m\n"; # don't ask about PROC print "# CONFIG_IKCONFIG_PROC is not set\n"; } else { print; } next; } if (/^(CONFIG.*)=(m|y)/) { if (defined($configs{$1})) { if ($localyesconfig) { $setconfigs{$1} = 'y'; } else { $setconfigs{$1} = $2; } } elsif ($2 eq "m") { print "# $1 is not set\n"; next; } } print; } close(CIN); # Integrity check, make sure all modules that we want enabled do # indeed have their configs set. loop: foreach my $module (keys(%modules)) { if (defined($objects{$module})) { my @arr = @{$objects{$module}}; foreach my $conf (@arr) { if (defined($setconfigs{$conf})) { next loop; } } print STDERR "module $module did not have configs"; foreach my $conf (@arr) { print STDERR " " , $conf; } print STDERR "\n"; } }
talnoah/android_kernel_htc_dlx
virt/scripts/kconfig/streamline_config.pl
Perl
gpl-2.0
10,861
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'newpage', 'hu', { toolbar: 'Új oldal' });
vousk/jsdelivr
files/ckeditor/4.3.0/plugins/newpage/lang/hu.js
JavaScript
mit
217
/** common.h * * @copyright * Copyright (C) 2010-2013, Intel Corporation * All rights reserved. * * @copyright * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * @copyright * 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. */ /** @file common.h * * @brief Defines common macros and structures used by the Intel Cilk Plus * runtime. * * @ingroup common */ /** @defgroup common Common Definitions * Macro, structure, and class definitions used elsewhere in the runtime. * @{ */ #ifndef INCLUDED_CILK_COMMON #define INCLUDED_CILK_COMMON #ifdef __cplusplus /** Namespace for all Cilk definitions that can be included in user code. */ namespace cilk { /** Namespace for definitions that are primarily intended for use * in other Cilk definitions. */ namespace internal {} } #endif /** Cilk library version = 1.01 */ #define CILK_LIBRARY_VERSION 102 #ifdef __cplusplus # include <cassert> #else # include <assert.h> #endif /** * Prefix standard library function and type names with __STDNS in order to * get correct lookup in both C and C++. */ #ifdef __cplusplus # define __STDNS std:: #else # define __STDNS #endif /** * @def CILK_EXPORT * Define export of runtime functions from shared library. * Should be exported only from cilkrts*.dll/cilkrts*.so * @def CILK_EXPORT_DATA * Define export of runtime data from shared library. */ #ifdef _WIN32 # ifdef IN_CILK_RUNTIME # define CILK_EXPORT __declspec(dllexport) # define CILK_EXPORT_DATA __declspec(dllexport) # else # define CILK_EXPORT __declspec(dllimport) # define CILK_EXPORT_DATA __declspec(dllimport) # endif /* IN_CILK_RUNTIME */ #elif defined(__CYGWIN__) || defined(__APPLE__) || defined(_DARWIN_C_SOURCE) # define CILK_EXPORT /* nothing */ # define CILK_EXPORT_DATA /* nothing */ #else /* Unix/gcc */ # if defined(IN_CILK_RUNTIME) && defined(HAVE_ATTRIBUTE_VISIBILITY) # define CILK_EXPORT __attribute__((visibility("protected"))) # define CILK_EXPORT_DATA __attribute__((visibility("protected"))) # else # define CILK_EXPORT /* nothing */ # define CILK_EXPORT_DATA /* nothing */ # endif /* IN_CILK_RUNTIME */ #endif /* Unix/gcc */ /** * @def __CILKRTS_BEGIN_EXTERN_C * Macro to denote the start of a section in which all names have "C" linkage. * That is, none of the names are to be mangled. * @see __CILKRTS_END_EXTERN_C * @see __CILKRTS_EXTERN_C * * @def __CILKRTS_END_EXTERN_C * Macro to denote the end of a section in which all names have "C" linkage. * That is, none of the names are to be mangled. * @see __CILKRTS_BEGIN_EXTERN_C * @see __CILKRTS_EXTERN_C * * @def __CILKRTS_EXTERN_C * Macro to prefix a single definition which has "C" linkage. * That is, the defined name is not to be mangled. * @see __CILKRTS_BEGIN_EXTERN_C * @see __CILKRTS_END_EXTERN_C */ #ifdef __cplusplus # define __CILKRTS_BEGIN_EXTERN_C extern "C" { # define __CILKRTS_END_EXTERN_C } # define __CILKRTS_EXTERN_C extern "C" #else # define __CILKRTS_BEGIN_EXTERN_C # define __CILKRTS_END_EXTERN_C # define __CILKRTS_EXTERN_C #endif /** * OS-independent macro to specify a function which is known to not throw * an exception. */ #ifdef __cplusplus # ifdef _WIN32 # define __CILKRTS_NOTHROW __declspec(nothrow) # else /* Unix/gcc */ # define __CILKRTS_NOTHROW __attribute__((nothrow)) # endif /* Unix/gcc */ #else # define __CILKRTS_NOTHROW /* nothing */ #endif /* __cplusplus */ /** Cache alignment. (Good enough for most architectures.) */ #define __CILKRTS_CACHE_LINE__ 64 /** * Macro to specify alignment of a data member in a structure. * Because of the way that gcc’s alignment attribute is defined, @a n must * be a numeric literal, not just a compile-time constant expression. */ #ifdef _WIN32 # define CILK_ALIGNAS(n) __declspec(align(n)) #else /* Unix/gcc */ # define CILK_ALIGNAS(n) __attribute__((__aligned__(n))) #endif /** * Macro to specify cache-line alignment of a data member in a structure. */ #define __CILKRTS_CACHE_ALIGN CILK_ALIGNAS(__CILKRTS_CACHE_LINE__) /** * Macro to specify a class as being at least as strictly aligned as some * type on Windows. gcc does not provide a way of doing this, so on Unix, * this just specifies the largest natural type alignment. Put the macro * between the `class` keyword and the class name: * * class CILK_ALIGNAS_TYPE(foo) bar { ... }; */ #ifdef _WIN32 # define CILK_ALIGNAS_TYPE(t) __declspec(align(__alignof(t))) #else /* Unix/gcc */ # define CILK_ALIGNAS_TYPE(t) __attribute__((__aligned__)) #endif /** * @def CILK_API(RET_TYPE) * A function called explicitly by the programmer. * @def CILK_ABI(RET_TYPE) * A function called by compiler-generated code. * @def CILK_ABI_THROWS(RET_TYPE) * An ABI function that may throw an exception * * Even when these are the same definitions, they should be separate macros so * that they can be easily found in the code. */ #ifdef _WIN32 # define CILK_API(RET_TYPE) CILK_EXPORT RET_TYPE __CILKRTS_NOTHROW __cdecl # define CILK_ABI(RET_TYPE) CILK_EXPORT RET_TYPE __CILKRTS_NOTHROW __cdecl # define CILK_ABI_THROWS(RET_TYPE) CILK_EXPORT RET_TYPE __cdecl #else # define CILK_API(RET_TYPE) CILK_EXPORT RET_TYPE __CILKRTS_NOTHROW # define CILK_ABI(RET_TYPE) CILK_EXPORT RET_TYPE __CILKRTS_NOTHROW # define CILK_ABI_THROWS(RET_TYPE) CILK_EXPORT RET_TYPE #endif /** * __CILKRTS_ASSERT should be defined for debugging only, otherwise it * interferes with vectorization. Since NDEBUG is not reliable (it must be * set by the user), we must use a platform-specific detection of debug mode. */ #if defined(_WIN32) && defined(_DEBUG) /* Windows debug */ # define __CILKRTS_ASSERT(e) assert(e) #elif (! defined(_WIN32)) && ! defined(__OPTIMIZE__) /* Unix non-optimized */ # define __CILKRTS_ASSERT(e) assert(e) #elif defined __cplusplus /* C++ non-debug */ # define __CILKRTS_ASSERT(e) static_cast<void>(0) #else /* C non-debug */ # define __CILKRTS_ASSERT(e) ((void) 0) #endif /** * OS-independent macro to specify a function that should be inlined */ #ifdef __cpluspus // C++ # define __CILKRTS_INLINE inline #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L // C99 # define __CILKRTS_INLINE static inline #elif defined(_MSC_VER) // C89 on Windows # define __CILKRTS_INLINE __inline #else // C89 on GCC-compatible systems # define __CILKRTS_INLINE extern __inline__ #endif /** * Functions marked as CILK_EXPORT_AND_INLINE have both * inline versions defined in the Cilk API, as well as * non-inlined versions that are exported (for * compatibility with previous versions that did not * inline the functions). */ #ifdef COMPILING_CILK_API_FUNCTIONS # define CILK_EXPORT_AND_INLINE CILK_EXPORT #else # define CILK_EXPORT_AND_INLINE __CILKRTS_INLINE #endif /** * Try to determine if compiler supports rvalue references. */ #if defined(__cplusplus) && !defined(__CILKRTS_RVALUE_REFERENCES) # if __cplusplus >= 201103L // C++11 # define __CILKRTS_RVALUE_REFERENCES 1 # elif defined(__GXX_EXPERIMENTAL_CXX0X__) # define __CILKRTS_RVALUE_REFERENCES 1 # elif __cplusplus >= 199711L && __cplusplus < 201103L // Compiler recognizes a language version prior to C++11 # elif __INTEL_COMPILER == 1200 && defined(__STDC_HOSTED__) // Intel compiler version 12.0 // __cplusplus has a non-standard definition. In the absence of a // proper definition, look for the C++0x macro, __STDC_HOSTED__. # define __CILKRTS_RVALUE_REFERENCES 1 # elif __INTEL_COMPILER > 1200 && defined(CHAR16T) // Intel compiler version >= 12.1 // __cplusplus has a non-standard definition. In the absence of a // proper definition, look for the Intel macro, CHAR16T # define __CILKRTS_RVALUE_REFERENCES 1 # endif #endif /* * Include stdint.h to define the standard integer types. * * Unfortunately Microsoft doesn't provide stdint.h until Visual Studio 2010, * so use our own definitions until those are available */ #if ! defined(_MSC_VER) || (_MSC_VER >= 1600) # include <stdint.h> #else # ifndef __MS_STDINT_TYPES_DEFINED__ # define __MS_STDINT_TYPES_DEFINED__ typedef signed char int8_t; typedef short int16_t; typedef int int32_t; typedef __int64 int64_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; typedef unsigned __int64 uint64_t; # endif /* __MS_STDINT_TYPES_DEFINED__ */ #endif /* ! defined(_MSC_VER) || (_MSC_VER >= 1600) */ /** * @brief Application Binary Interface version of the Cilk runtime library. * * The ABI version is determined by the compiler used. An object file * compiled with a higher ABI version is not compatible with a library that is * compiled with a lower ABI version. An object file compiled with a lower * ABI version, however, can be used with a library compiled with a higher ABI * version unless otherwise stated. */ #ifndef __CILKRTS_ABI_VERSION # ifdef IN_CILK_RUNTIME # define __CILKRTS_ABI_VERSION 1 # elif defined(__INTEL_COMPILER) && (__INTEL_COMPILER <= 1200) // Intel compilers prior to version 12.1 support only ABI 0 # define __CILKRTS_ABI_VERSION 0 # else // Non-Intel compiler or Intel compiler after version 12.0. # define __CILKRTS_ABI_VERSION 1 # endif #endif // These structs are exported because the inlining of // the internal version of API methods require a worker // structure as parameter. __CILKRTS_BEGIN_EXTERN_C /// Worker struct, exported for inlined API methods /// @ingroup api struct __cilkrts_worker; /// Worker struct, exported for inlined API methods /// @ingroup api typedef struct __cilkrts_worker __cilkrts_worker; /// Worker struct pointer, exported for inlined API methods /// @ingroup api typedef struct __cilkrts_worker *__cilkrts_worker_ptr; /// Fetch the worker out of TLS. CILK_ABI(__cilkrts_worker_ptr) __cilkrts_get_tls_worker(void); /// void *, defined to work around complaints from the compiler /// about using __declspec(nothrow) after the "void *" return type typedef void * __cilkrts_void_ptr; __CILKRTS_END_EXTERN_C #if __CILKRTS_ABI_VERSION >= 1 // Pedigree API is available only for compilers that use ABI version >= 1. /** Pedigree information kept in the worker and stack frame. * @ingroup api */ typedef struct __cilkrts_pedigree { /** Rank at start of spawn helper. Saved rank for spawning functions */ uint64_t rank; /** Link to next in chain */ const struct __cilkrts_pedigree *parent; } __cilkrts_pedigree; #endif // __CILKRTS_ABI_VERSION >= 1 /// @} #endif /* INCLUDED_CILK_COMMON */
Iotlab-404/LFS
usr/lib/gcc/x86_64-unknown-linux-gnu/4.9.2/include/cilk/common.h
C
gpl-3.0
12,478
.mejs-container { position: relative; background: #000; font-family: Helvetica, Arial; } .mejs-container-fullscreen { position: fixed; left: 0; top: 0; right: 0; bottom: 0; overflow: hidden; } .mejs-container-fullscreen .mejs-mediaelement, .mejs-container-fullscreen video { width: 100%; height: 100%; } /* Start: LAYERS */ .mejs-background { position: absolute; top: 0; left: 0; } .mejs-mediaelement { position: absolute; top: 0; left: 0; } .mejs-poster { position: absolute; top: 0; left: 0; } .mejs-overlay { position: absolute; top: 0; left: 0; } .mejs-overlay-play { cursor: pointer; } .mejs-overlay-button { position: absolute; top: 50%; left: 50%; width: 100px; height: 100px; margin: -50px 0 0 -50px; background: url(bigplay.png) top left no-repeat; } .mejs-overlay:hover .mejs-overlay-button{ background-position: 0 -100px ; } .mejs-overlay-loading { position: absolute; top: 50%; left: 50%; width: 80px; height: 80px; margin: -40px 0 0 -40px; background: #333; background: url(background.png); background: rgba(0, 0, 0, 0.9); background: -webkit-gradient(linear, left top, left bottom, from(rgba(50,50,50,0.9)), to(rgba(0,0,0,0.9))); background: -moz-linear-gradient(top, rgba(50,50,50,0.9), rgba(0,0,0,0.9)); background: linear-gradient(rgba(50,50,50,0.9), rgba(0,0,0,0.9)); } .mejs-overlay-loading span { display:block; width: 80px; height: 80px; background: transparent url(loading.gif) center center no-repeat; } /* End: LAYERS */ /* Start: CONTROL BAR */ .mejs-container .mejs-controls { position: absolute; background: none; list-style-type: none; margin: 0; padding: 0; bottom: 0; left: 0; background: url(background.png); background: rgba(0, 0, 0, 0.7); background: -webkit-gradient(linear, left top, left bottom, from(rgba(50,50,50,0.7)), to(rgba(0,0,0,0.7))); background: -moz-linear-gradient(top, rgba(50,50,50,0.7), rgba(0,0,0,0.7)); background: linear-gradient(rgba(50,50,50,0.7), rgba(0,0,0,0.7)); height: 30px; width: 100%; } .mejs-container .mejs-controls div { list-style-type: none; background-image: none; display: block; float: left; margin: 0; padding: 0; width: 26px; height: 26px; font-size: 11px; line-height: 11px; font-family: Helvetica, Arial; } .mejs-controls .mejs-button span { cursor: pointer; display: block; font-size: 0px; line-height: 0; text-decoration: none; margin: 7px 5px; height: 16px; width: 16px; background: transparent url(controls.png) 0 0 no-repeat; } /* End: CONTROL BAR */ /* Start: Time (current / duration) */ .mejs-container .mejs-controls .mejs-time { color: #fff; display: block; height: 17px; width: auto; padding: 8px 3px 0 3px ; overflow: hidden; text-align: center; padding: auto 4px; } .mejs-container .mejs-controls .mejs-time span { font-size: 11px; color: #fff; line-height: 12px; display: block; float: left; margin: 1px 2px 0 0; width: auto; } /* End: Time (current / duration) */ /* Start: Play/pause */ .mejs-controls .mejs-play span { background-position:0 0; } .mejs-controls .mejs-pause span { background-position:0 -16px; } /* End: Play/pause */ /* Stop */ .mejs-controls .mejs-stop span { background-position: -112px 0; } /* End: Play/pause */ /* Start: Progress bar */ .mejs-controls div.mejs-time-rail { width: 200px; padding-top: 5px; } .mejs-controls .mejs-time-rail span { display: block; position: absolute; width: 180px; height: 10px; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; cursor: pointer; } .mejs-controls .mejs-time-rail .mejs-time-total { margin: 5px; background: #333; background: rgba(50,50,50,0.8); background: -webkit-gradient(linear, left top, left bottom, from(rgba(30,30,30,0.8)), to(rgba(60,60,60,0.8))); background: -moz-linear-gradient(top, rgba(30,30,30,0.8), rgba(60,60,60,0.8)); background: linear-gradient(rgba(30,30,30,0.8), rgba(60,60,60,0.8)); filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, startColorstr=#1E1E1E,endColorstr=#3C3C3C); } .mejs-controls .mejs-time-rail .mejs-time-loaded { background: #3caac8; background: rgba(60,170,200,0.8); background: -webkit-gradient(linear, left top, left bottom, from(rgba(44,124,145,0.8)), to(rgba(78,183,212,0.8))); background: -moz-linear-gradient(top, rgba(44,124,145,0.8), rgba(78,183,212,0.8)); background: linear-gradient(rgba(44,124,145,0.8), rgba(78,183,212,0.8)); filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, startColorstr=#2C7C91,endColorstr=#4EB7D4); width: 0; } .mejs-controls .mejs-time-rail .mejs-time-current { width: 0; background: #fff; background: rgba(255,255,255,0.8); background: -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255,0.9)), to(rgba(200,200,200,0.8))); background: -moz-linear-gradient(top, rgba(255,255,255,0.9), rgba(200,200,200,0.8)); filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, startColorstr=#FFFFFF,endColorstr=#C8C8C8); } .mejs-controls .mejs-time-rail .mejs-time-handle { display: none; position: absolute; margin: 0; width: 10px; background: #fff; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; cursor: pointer; border: solid 2px #333; top: -2px; text-align: center; } .mejs-controls .mejs-time-rail .mejs-time-float { visibility: hidden; position: absolute; display: block; background: #eee; width: 36px; height: 17px; border: solid 1px #333; top: -26px; margin-left: -18px; text-align: center; color: #111; } .mejs-controls .mejs-time-rail:hover .mejs-time-float { visibility: visible; } .mejs-controls .mejs-time-rail .mejs-time-float-current { margin: 2px; width: 30px; display: block; text-align: center; left: 0; } .mejs-controls .mejs-time-rail .mejs-time-float-corner { position: absolute; display: block; width: 0; height: 0; line-height: 0; border: solid 5px #eee; border-color: #eee transparent transparent transparent; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; top: 15px; left: 13px; } /* .mejs-controls .mejs-time-rail:hover .mejs-time-handle { visibility:visible; } */ /* End: Progress bar */ /* Start: Fullscreen */ .mejs-controls .mejs-fullscreen-button span { background-position:-32px 0; } .mejs-controls .mejs-unfullscreen span { background-position:-32px -16px; } /* End: Fullscreen */ /* Start: Mute/Volume */ .mejs-controls .mejs-volume-button { } .mejs-controls .mejs-mute span { background-position:-16px -16px; } .mejs-controls .mejs-unmute span { background-position:-16px 0; } .mejs-controls .mejs-volume-button { position: relative; } .mejs-controls .mejs-volume-button .mejs-volume-slider { display: none; height: 115px; width: 25px; background: url(background.png); background: rgba(50, 50, 50, 0.7); -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; top: -115px; left: 0; z-index: 1; position: absolute; margin: 0; } .mejs-controls .mejs-volume-button:hover { -webkit-border-radius: 0 0 4px 4px ; -moz-border-radius: 0 0 4px 4px ; border-radius: 0 0 4px 4px ; } .mejs-controls .mejs-volume-button:hover .mejs-volume-slider { display: block; } .mejs-controls .mejs-volume-button .mejs-volume-slider .mejs-volume-total { position: absolute; left: 11px; top: 8px; width: 2px; height: 100px; background: #ddd; background: rgba(255, 255, 255, 0.5); margin: 0; } .mejs-controls .mejs-volume-button .mejs-volume-slider .mejs-volume-current { position: absolute; left: 11px; top: 8px; width: 2px; height: 100px; background: #ddd; background: rgba(255, 255, 255, 0.9); margin: 0; } .mejs-controls .mejs-volume-button .mejs-volume-slider .mejs-volume-handle { position: absolute; left: 4px; top: -3px; width: 16px; height: 6px; background: #ddd; background: rgba(255, 255, 255, 0.9); cursor: N-resize; -webkit-border-radius: 1px; -moz-border-radius: 1px; border-radius: 1px; margin: 0; } /* End: Mute/Volume */ /* Start: TRACK (Captions and Chapters) */ .mejs-controls .mejs-captions-button { position: relative; } .mejs-controls .mejs-captions-button span { background-position:-48px 0; } .mejs-controls .mejs-captions-button .mejs-captions-selector { visibility: hidden; position: absolute; bottom: 26px; right: -10px; width: 130px; height: 100px; background: url(background.png); background: rgba(50,50,50,0.7); border: solid 1px transparent; padding: 10px; overflow: hidden; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .mejs-controls .mejs-captions-button:hover .mejs-captions-selector { visibility: visible; } .mejs-controls .mejs-captions-button .mejs-captions-selector ul { margin: 0; padding: 0; display: block; list-style-type: none !important; overflow: hidden; } .mejs-controls .mejs-captions-button .mejs-captions-selector ul li{ margin: 0 0 6px 0; padding: 0; list-style-type: none !important; display:block; color: #fff; overflow: hidden; } .mejs-controls .mejs-captions-button .mejs-captions-selector ul li input{ clear: both; float: left; margin: 3px 3px 0px 5px; } .mejs-controls .mejs-captions-button .mejs-captions-selector ul li label{ width: 100px; float: left; padding: 4px 0 0 0; line-height: 15px; font-family: helvetica, arial; font-size: 10px; } .mejs-controls .mejs-captions-button .mejs-captions-translations { font-size: 10px; margin: 0 0 5px 0; } .mejs-chapters { position: absolute; top: 0; left: 0; -xborder-right: solid 1px #fff; width: 10000px; } .mejs-chapters .mejs-chapter { position: absolute; float: left; background: #222; background: rgba(0, 0, 0, 0.7); background: -webkit-gradient(linear, left top, left bottom, from(rgba(50,50,50,0.7)), to(rgba(0,0,0,0.7))); background: -moz-linear-gradient(top, rgba(50,50,50,0.7), rgba(0,0,0,0.7)); background: linear-gradient(rgba(50,50,50,0.7), rgba(0,0,0,0.7)); filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, startColorstr=#323232,endColorstr=#000000); overflow: hidden; border: 0; } .mejs-chapters .mejs-chapter .mejs-chapter-block { font-size: 11px; color: #fff; padding: 5px; display: block; border-right: solid 1px #333; border-bottom: solid 1px #333; cursor: pointer; } .mejs-chapters .mejs-chapter .mejs-chapter-block-last { border-right: none; } .mejs-chapters .mejs-chapter .mejs-chapter-block:hover { /*background: #333;*/ background: #666; background: rgba(102,102,102, 0.7); background: -webkit-gradient(linear, left top, left bottom, from(rgba(102,102,102,0.7)), to(rgba(50,50,50,0.6))); background: -moz-linear-gradient(top, rgba(102,102,102,0.7), rgba(50,50,50,0.6)); filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, startColorstr=#666666,endColorstr=#323232); } .mejs-chapters .mejs-chapter .mejs-chapter-block .ch-title{ font-size: 12px; font-weight: bold; display: block; white-space:nowrap; text-overflow: ellipsis; margin: 0 0 3px 0; line-height: 12px; } .mejs-chapters .mejs-chapter .mejs-chapter-block .ch-timespan{ font-size: 12px; line-height: 12px; margin: 3px 0 4px 0; display: block; white-space:nowrap; text-overflow: ellipsis; } .mejs-captions-layer { position: absolute; bottom: 0; left: 0; text-align:center; /*font-weight: bold;*/ line-height: 22px; font-size: 12px; color: #fff; } .mejs-captions-layer a { color: #fff; text-decoration: underline; } .mejs-captions-layer[lang=ar] { font-size: 20px; font-weight: normal; } .mejs-captions-position { position: absolute; width: 100%; bottom: 15px; } .mejs-captions-position-hover { bottom: 45px; } .mejs-captions-text { padding: 3px 5px; background: url(background.png); background: rgba(20, 20, 20, 0.8); } /* End: TRACK (Captions and Chapters) */ .mejs-clear { clear: both; } /* Start: ERROR */ .me-cannotplay { } .me-cannotplay a { color: #fff; font-weight: bold; } .me-cannotplay span { padding: 15px; display: block; } /* End: ERROR */ /* Start: Loop */ .mejs-controls .mejs-loop-off span{ background-position: -64px -16px; } .mejs-controls .mejs-loop-on span { background-position: -64px 0; } /* End: Loop */ /* Start: backlight */ .mejs-controls .mejs-backlight-off span{ background-position: -80px -16px; } .mejs-controls .mejs-backlight-on span { background-position: -80px 0; } /* End: backlight */ /* Start: picture controls */ .mejs-controls .mejs-picturecontrols-button{ background-position: -96px 0; } /* End: picture controls */
janpaepke/cdnjs
ajax/libs/mediaelement/2.1.1/mediaelementplayer.css
CSS
mit
12,505
/****************************************************************************** * * Copyright(c) 2009-2012 Realtek Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * The full GNU General Public License is included in this distribution in the * file called LICENSE. * * Contact Information: * wlanfae <wlanfae@realtek.com> * Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park, * Hsinchu 300, Taiwan. * * Created on 2010/ 5/18, 1:41 * * Larry Finger <Larry.Finger@lwfinger.net> * *****************************************************************************/ #ifndef __RTL8723E_TABLE__H_ #define __RTL8723E_TABLE__H_ #include <linux/types.h> #define RTL8723E_PHY_REG_1TARRAY_LENGTH 372 extern u32 RTL8723EPHY_REG_1TARRAY[RTL8723E_PHY_REG_1TARRAY_LENGTH]; #define RTL8723E_PHY_REG_ARRAY_PGLENGTH 336 extern u32 RTL8723EPHY_REG_ARRAY_PG[RTL8723E_PHY_REG_ARRAY_PGLENGTH]; #define RTL8723ERADIOA_1TARRAYLENGTH 282 extern u32 RTL8723E_RADIOA_1TARRAY[RTL8723ERADIOA_1TARRAYLENGTH]; #define RTL8723E_RADIOB_1TARRAYLENGTH 1 extern u32 RTL8723E_RADIOB_1TARRAY[RTL8723E_RADIOB_1TARRAYLENGTH]; #define RTL8723E_MACARRAYLENGTH 172 extern u32 RTL8723EMAC_ARRAY[RTL8723E_MACARRAYLENGTH]; #define RTL8723E_AGCTAB_1TARRAYLENGTH 320 extern u32 RTL8723EAGCTAB_1TARRAY[RTL8723E_AGCTAB_1TARRAYLENGTH]; #endif
mericon/Xp_Kernel_LGH850
virt/drivers/net/wireless/rtlwifi/rtl8723ae/table.h
C
gpl-2.0
1,743
// basic uses of function literals with overloads var f: { (x: string): string; (x: number): number; } = (x) => x; var f2: { <T>(x: string): string; <T>(x: number): number; } = (x) => x; var f3: { <T>(x: T): string; <T>(x: T): number; } = (x) => x; var f4: { <T>(x: string): T; <T>(x: number): T; } = (x) => x;
progre/TypeScript
tests/cases/conformance/types/specifyingTypes/typeLiterals/functionLiteralForOverloads.ts
TypeScript
apache-2.0
366
enum E { A, B } enum E2 { A, B } var e: E; var e2: E2; e = E2.A; e2 = E.A; e = <void>null; e = {}; e = ''; function f<T>(a: T) { e = a; }
yortus/TypeScript
tests/cases/conformance/types/primitives/enum/invalidEnumAssignments.ts
TypeScript
apache-2.0
182
# generated from catkin/cmake/template/pkgConfig-version.cmake.in set(PACKAGE_VERSION "0.0.0") set(PACKAGE_VERSION_EXACT False) set(PACKAGE_VERSION_COMPATIBLE False) if("${PACKAGE_FIND_VERSION}" VERSION_EQUAL "${PACKAGE_VERSION}") set(PACKAGE_VERSION_EXACT True) set(PACKAGE_VERSION_COMPATIBLE True) endif() if("${PACKAGE_FIND_VERSION}" VERSION_LESS "${PACKAGE_VERSION}") set(PACKAGE_VERSION_COMPATIBLE True) endif()
FRC900/2016VisionCode
zebROS_ws/devel/share/goal_detection/cmake/goal_detectionConfig-version.cmake
CMake
mit
426
interface I { D?<T>(); }
enginekit/TypeScript
tests/cases/conformance/parser/ecmascript5/MethodSignatures/parserMethodSignature4.ts
TypeScript
apache-2.0
28
class Post include Mongoid::Document include Mongoid::Attributes::Dynamic field :title, type: String field :content, type: String field :rating, type: Integer field :person_title, type: String, default: ->{ person.title if ivar(:person) } attr_accessor :before_add_called, :after_add_called, :before_remove_called, :after_remove_called belongs_to :person, counter_cache: true belongs_to :author, foreign_key: :author_id, class_name: "User" has_and_belongs_to_many :tags, before_add: :before_add_tag, after_add: :after_add_tag, before_remove: :before_remove_tag, after_remove: :after_remove_tag has_many :videos, validate: false has_many :roles, validate: false scope :recent, ->{ where(created_at: { "$lt" => Time.now, "$gt" => 30.days.ago }) } scope :posting, ->{ where(:content.in => [ "Posting" ]) } scope :open, ->{ where(title: "open") } validates_format_of :title, without: /\$\$\$/ def before_add_tag(tag) @before_add_called = true end def after_add_tag(tag) @after_add_called = true end def before_remove_tag(tag) @before_remove_called = true end def after_remove_tag(tag) @after_remove_called = true end class << self def old where(created_at: { "$lt" => 30.days.ago }) end end end
hashrocketeer/mongoid
spec/app/models/post.rb
Ruby
mit
1,283
<!DOCTYPE html> <!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]--> <!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]--> <!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]--> <!--[if (gte IE 9)|!(IE)]><!--> <html lang="en" xmlns="http://www.w3.org/1999/html"> <!--<![endif]--> <head> <!-- Basic Page Needs ================================================== --> <meta charset="utf-8" /> <title>icon-compass: Font Awesome Icons</title> <meta name="description" content="Font Awesome, the iconic font designed for Bootstrap"> <meta name="author" content="Dave Gandy"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--<meta name="viewport" content="initial-scale=1; maximum-scale=1">--> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- CSS ================================================== --> <link rel="stylesheet" href="../../assets/css/site.css"> <link rel="stylesheet" href="../../assets/css/pygments.css"> <link rel="stylesheet" href="../../assets/font-awesome/css/font-awesome.css"> <!--[if IE 7]> <link rel="stylesheet" href="../../assets/font-awesome/css/font-awesome-ie7.css"> <![endif]--> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="../../assets/ico/favicon.ico"> <script type="text/javascript" src="//use.typekit.net/wnc7ioh.js"></script> <script type="text/javascript">try{Typekit.load();}catch(e){}</script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-30136587-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body data-spy="scroll" data-target=".navbar"> <div class="wrapper"> <!-- necessary for sticky footer. wrap all content except footer --> <div class="navbar navbar-inverse navbar-static-top hidden-print"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="../../"><i class="icon-flag"></i> Font Awesome</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class="hidden-tablet "><a href="../../">Home</a></li> <li><a href="../../get-started/">Get Started</a></li> <li class="dropdown-split-left"><a href="../../icons/">Icons</a></li> <li class="dropdown dropdown-split-right hidden-phone"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-caret-down"></i> </a> <ul class="dropdown-menu pull-right"> <li><a href="../../icons/"><i class="icon-flag icon-fixed-width"></i>&nbsp; Icons</a></li> <li class="divider"></li> <li><a href="../../icons/#new"><i class="icon-shield icon-fixed-width"></i>&nbsp; New Icons in 3.2.1</a></li> <li><a href="../../icons/#web-application"><i class="icon-camera-retro icon-fixed-width"></i>&nbsp; Web Application Icons</a></li> <li><a href="../../icons/#currency"><i class="icon-won icon-fixed-width"></i>&nbsp; Currency Icons</a></li> <li><a href="../../icons/#text-editor"><i class="icon-file-text-alt icon-fixed-width"></i>&nbsp; Text Editor Icons</a></li> <li><a href="../../icons/#directional"><i class="icon-hand-right icon-fixed-width"></i>&nbsp; Directional Icons</a></li> <li><a href="../../icons/#video-player"><i class="icon-play-sign icon-fixed-width"></i>&nbsp; Video Player Icons</a></li> <li><a href="../../icons/#brand"><i class="icon-github icon-fixed-width"></i>&nbsp; Brand Icons</a></li> <li><a href="../../icons/#medical"><i class="icon-medkit icon-fixed-width"></i>&nbsp; Medical Icons</a></li> </ul> </li> <li class="dropdown-split-left"><a href="../../examples/">Examples</a></li> <li class="dropdown dropdown-split-right hidden-phone"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-caret-down"></i> </a> <ul class="dropdown-menu pull-right"> <li><a href="../../examples/">Examples</a></li> <li class="divider"></li> <li><a href="../../examples/#new-styles">New Styles</a></li> <li><a href="../../examples/#inline-icons">Inline Icons</a></li> <li><a href="../../examples/#larger-icons">Larger Icons</a></li> <li><a href="../../examples/#bordered-pulled">Bordered & Pulled</a></li> <li><a href="../../examples/#buttons">Buttons</a></li> <li><a href="../../examples/#button-groups">Button Groups</a></li> <li><a href="../../examples/#button-dropdowns">Button Dropdowns</a></li> <li><a href="../../examples/#bulleted-lists">Bulleted Lists</a></li> <li><a href="../../examples/#navigation">Navigation</a></li> <li><a href="../../examples/#form-inputs">Form Inputs</a></li> <li><a href="../../examples/#animated-spinner">Animated Spinner</a></li> <li><a href="../../examples/#rotated-flipped">Rotated &amp; Flipped</a></li> <li><a href="../../examples/#stacked">Stacked</a></li> <li><a href="../../examples/#custom">Custom CSS</a></li> </ul> </li> <li><a href="../../whats-new/"> <span class="hidden-tablet">What's </span>New</a> </li> <li><a href="../../community/">Community</a></li> <li><a href="../../license/">License</a></li> </ul> <ul class="nav pull-right"> <li><a href="http://blog.fontawesome.io">Blog</a></li> </ul> </div> </div> </div> </div> <div class="jumbotron jumbotron-icon"> <div class="container"> <div class="info-icons"> <i class="icon-compass icon-6"></i>&nbsp;&nbsp; <span class="hidden-phone"> <i class="icon-compass icon-5"></i>&nbsp;&nbsp; <span class="hidden-tablet"><i class="icon-compass icon-4"></i>&nbsp;&nbsp;</span> <i class="icon-compass icon-3"></i>&nbsp;&nbsp; <i class="icon-compass icon-2"></i>&nbsp; </span> <i class="icon-compass icon-1"></i> </div> <h1 class="info-class"> icon-compass <small> <i class="icon-compass"></i> &middot; Unicode: <span class="upper">f14e</span> &middot; Created: v3.2 &middot; Categories: Web Application Icons </small> </h1> </div> </div> <div class="container"> <section> <div class="row-fluid"> <div class="span9"> <p>After you get <a href="../../integration/">up and running</a>, you can place Font Awesome icons just about anywhere with the <code>&lt;i&gt;</code> tag:</p> <div class="well well-transparent"> <div style="font-size: 24px; line-height: 1.5em;"> <i class="icon-compass"></i> icon-compass </div> </div> <div class="highlight"><pre><code class="html"><span class="nt">&lt;i</span> <span class="na">class=</span><span class="s">&quot;icon-compass&quot;</span><span class="nt">&gt;&lt;/i&gt;</span> icon-compass </code></pre></div> <br> <div class="lead"><i class="icon-info-sign"></i> Looking for more? Check out the <a href="../../examples/">examples</a>.</div> </div> <div class="span3"> <div class="info-ad"><div id="carbonads-container"><div class="carbonad"><div id="azcarbon"></div><script type="text/javascript">var z = document.createElement("script"); z.type = "text/javascript"; z.async = true; z.src = "http://engine.carbonads.com/z/32291/azcarbon_2_1_0_VERT"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(z, s);</script></div></div> </div> </div> </div> </section> </div> <div class="push"><!-- necessary for sticky footer --></div> </div> <footer class="footer hidden-print"> <div class="container text-center"> <div> <i class="icon-flag"></i> Font Awesome 3.2.1 <span class="hidden-phone">&middot;</span><br class="visible-phone"> Created and Maintained by <a href="http://twitter.com/davegandy">Dave Gandy</a> </div> <div> Font Awesome licensed under <a href="http://scripts.sil.org/OFL">SIL OFL 1.1</a> <span class="hidden-phone">&middot;</span><br class="visible-phone"> Code licensed under <a href="http://opensource.org/licenses/mit-license.html">MIT License</a> <span class="hidden-phone hidden-tablet">&middot;</span><br class="visible-phone visible-tablet"> Documentation licensed under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a> </div> <div> Thanks to <a href="http://tracking.maxcdn.com/c/148092/3982/378"><i class="icon-maxcdn"></i> MaxCDN</a> for providing the excellent <a href="http://www.bootstrapcdn.com/#tab_fontawesome">BootstrapCDN for Font Awesome</a> </div> <div class="project"> <a href="https://github.com/FortAwesome/Font-Awesome">GitHub Project</a> &middot; <a href="https://github.com/FortAwesome/Font-Awesome/issues">Issues</a> </div> </div> </footer> <script src="http://platform.twitter.com/widgets.js"></script> <script src="../../assets/js/jquery-1.7.1.min.js"></script> <script src="../../assets/js/ZeroClipboard-1.1.7.min.js"></script> <script src="../../assets/js/bootstrap-2.3.1.min.js"></script> <script src="../../assets/js/site.js"></script> </body> </html>
zhouhuiqiong/201602node_homework
第2组 刘成军/高姗/第二周作业/public/Font-Awesome-master/Font-Awesome-master/src/3.2.1/icon/compass/index.html
HTML
mit
10,096
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSON 3</title> <link rel="stylesheet" href="page/style.css" media="screen"> </head> <body> <ul id="navigation"> <li><a href="#section_1">JSON 3</a></li> <li><a href="#section_2">Changes from JSON 2</a></li> <li><a href="#section_3">Usage</a></li> <li><a href="#section_4">Compatibility</a></li> <li><a href="#section_5">Contribute</a></li> </ul> <div id="content"> <h1><a name="section_1"></a>JSON 3</h1> <p><img src="http://bestiejs.github.io/json3/page/logo.png" alt="JSON 3 Logo"> </p> <p><strong>JSON 3</strong> is a modern JSON implementation compatible with a variety of JavaScript platforms, including Internet Explorer 6, Opera 7, Safari 2, and Netscape 6. The current version is <strong>3.2.5</strong>. </p> <ul> <li><a href="http://bestiejs.github.io/json3/lib/json3.js">Development Version</a> <em>(38.8 KB; uncompressed with comments)</em></li> <li><a href="http://bestiejs.github.io/json3/lib/json3.min.js">Production Version</a> <em>(3.2 KB; compressed and <code>gzip</code>-ped)</em></li> </ul> <p><a href="http://json.org/">JSON</a> is a language-independent data interchange format based on a loose subset of the JavaScript grammar. Originally popularized by <a href="http://www.crockford.com/">Douglas Crockford</a>, the format was standardized in the <a href="http://es5.github.com/">fifth edition</a> of the ECMAScript specification. The 5.1 edition, ratified in June 2011, incorporates several modifications to the grammar pertaining to the serialization of dates. </p> <p>JSON 3 exposes two functions: <code>stringify()</code> for <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify">serializing</a> a JavaScript value to JSON, and <code>parse()</code> for <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse">producing</a> a JavaScript value from a JSON source string. It is a <strong>drop-in replacement</strong> for <a href="http://json.org/js">JSON 2</a>. The functions behave exactly as described in the ECMAScript spec, <strong>except</strong> for the date serialization discrepancy noted below. </p> <p>The JSON 3 parser does <strong>not</strong> use <code>eval</code> or regular expressions. This provides security and performance benefits in obsolete and mobile environments, where the margin is particularly significant. The complete <a href="http://jsperf.com/json3">benchmark suite</a> is available on <a href="http://jsperf.com/">jsPerf</a>. </p> <p>The project is <a href="http://git.io/json3">hosted on GitHub</a>, along with the <a href="http://bestiejs.github.io/json3/test/test_browser.html">unit tests</a>. It is part of the <a href="https://github.com/bestiejs">BestieJS</a> family, a collection of best-in-class JavaScript libraries that promote cross-platform support, specification precedents, unit testing, and plenty of documentation. </p> <h1><a name="section_2"></a>Changes from JSON 2</h1> <p>JSON 3... </p> <ul> <li>Correctly serializes primitive wrapper objects.</li> <li>Throws a <code>TypeError</code> when serializing cyclic structures (JSON 2 recurses until the call stack overflows).</li> <li>Utilizes <strong>feature tests</strong> to detect broken or incomplete <em>native</em> JSON implementations (JSON 2 only checks for the presence of the native functions). The tests are only executed once at runtime, so there is no additional performance cost when parsing or serializing values.</li> </ul> <p><strong>As of v3.2.3</strong>, JSON 3 is compatible with <a href="http://prototypejs.org">Prototype</a> 1.6.1 and older. </p> <p>In contrast to JSON 2, JSON 3 <strong>does not</strong>... </p> <ul> <li>Add <code>toJSON()</code> methods to the <code>Boolean</code>, <code>Number</code>, and <code>String</code> prototypes. These are not part of any standard, and are made redundant by the design of the <code>stringify()</code> implementation.</li> <li>Add <code>toJSON()</code> or <code>toISOString()</code> methods to <code>Date.prototype</code>. See the note about date serialization below.</li> </ul> <h2>Date Serialization</h2> <p><strong>JSON 3 deviates from the specification in one important way</strong>: it does not define <code>Date#toISOString()</code> or <code>Date#toJSON()</code>. This preserves CommonJS compatibility and avoids polluting native prototypes. Instead, date serialization is performed internally by the <code>stringify()</code> implementation: if a date object does not define a custom <code>toJSON()</code> method, it is serialized as a <a href="http://es5.github.com/#x15.9.1.15">simplified ISO 8601 date-time string</a>. </p> <p><strong>Several native <code>Date#toJSON()</code> implementations produce date time strings that do <em>not</em> conform to the grammar outlined in the spec</strong>. For instance, all versions of Safari 4, as well as JSON 2, fail to serialize extended years correctly. Furthermore, JSON 2 and older implementations omit the milliseconds from the date-time string (optional in ES 5, but required in 5.1). Finally, in all versions of Safari 4 and 5, serializing an invalid date will produce the string <code>&quot;Invalid Date&quot;</code>, rather than <code>null</code>. Because these environments exhibit other serialization bugs, however, JSON 3 will override the native <code>stringify()</code> implementation. </p> <p>Portions of the date serialization code are adapted from the <a href="https://github.com/Yaffle/date-shim"><code>date-shim</code></a> project. </p> <h1><a name="section_3"></a>Usage</h1> <h2>Web Browsers</h2> <pre><code>&lt;script src=&quot;http://bestiejs.github.io/json3/lib/json3.js&quot;&gt;&lt;/script&gt; &lt;script&gt; JSON.stringify({&quot;Hello&quot;: 123}); // =&gt; &#39;{&quot;Hello&quot;:123}&#39; JSON.parse(&quot;[[1, 2, 3], 1, 2, 3, 4]&quot;, function (key, value) { if (typeof value == &quot;number&quot;) { value = value % 2 ? &quot;Odd&quot; : &quot;Even&quot;; } return value; }); // =&gt; [[&quot;Odd&quot;, &quot;Even&quot;, &quot;Odd&quot;], &quot;Odd&quot;, &quot;Even&quot;, &quot;Odd&quot;, &quot;Even&quot;] &lt;/script&gt;</code></pre> <h2>CommonJS Environments</h2> <pre><code>var JSON3 = require(&quot;./path/to/json3&quot;); JSON3.parse(&quot;[1, 2, 3]&quot;); // =&gt; [1, 2, 3]</code></pre> <h2>JavaScript Engines</h2> <pre><code>load(&quot;path/to/json3.js&quot;); JSON.stringify({&quot;Hello&quot;: 123, &quot;Good-bye&quot;: 456}, [&quot;Hello&quot;], &quot;\t&quot;); // =&gt; &#39;{\n\t&quot;Hello&quot;: 123\n}&#39;</code></pre> <h1><a name="section_4"></a>Compatibility</h1> <p>JSON 3 has been <strong>tested</strong> with the following web browsers, CommonJS environments, and JavaScript engines. </p> <h2>Web Browsers</h2> <ul> <li>Windows <a href="http://www.microsoft.com/windows/internet-explorer">Internet Explorer</a>, version 6.0 and higher</li> <li>Mozilla <a href="http://www.mozilla.com/firefox">Firefox</a>, version 1.0 and higher</li> <li>Apple <a href="http://www.apple.com/safari">Safari</a>, version 2.0 and higher</li> <li><a href="http://www.opera.com">Opera</a> 7.02 and higher</li> <li><a href="http://sillydog.org/narchive/gecko.php">Mozilla</a> 1.0, <a href="http://sillydog.org/narchive/">Netscape</a> 6.2.3, and <a href="http://www.seamonkey-project.org/">SeaMonkey</a> 1.0 and higher</li> </ul> <h2>CommonJS Environments</h2> <ul> <li><a href="http://nodejs.org/">Node</a> 0.2.6 and higher</li> <li><a href="http://ringojs.org/">RingoJS</a> 0.4 and higher</li> <li><a href="http://narwhaljs.org/">Narwhal</a> 0.3.2 and higher</li> </ul> <h2>JavaScript Engines</h2> <ul> <li>Mozilla <a href="http://www.mozilla.org/rhino">Rhino</a> 1.5R5 and higher</li> <li>WebKit <a href="https://trac.webkit.org/wiki/JSC">JSC</a></li> <li>Google <a href="http://code.google.com/p/v8">V8</a></li> </ul> <h2>Known Incompatibilities</h2> <ul> <li>Attempting to serialize the <code>arguments</code> object may produce inconsistent results across environments due to specification version differences. As a workaround, please convert the <code>arguments</code> object to an array first: <code>JSON.stringify([].slice.call(arguments, 0))</code>.</li> </ul> <h2>Required Native Methods</h2> <p>JSON 3 assumes that the following methods exist and function as described in the ECMAScript specification: </p> <ul> <li>The <code>Number</code>, <code>String</code>, <code>Array</code>, <code>Object</code>, <code>Date</code>, <code>SyntaxError</code>, and <code>TypeError</code> constructors.</li> <li><code>String.fromCharCode</code></li> <li><code>Object#toString</code></li> <li><code>Function#call</code></li> <li><code>Math.floor</code></li> <li><code>Number#toString</code></li> <li><code>Date#valueOf</code></li> <li><code>String.prototype</code>: <code>indexOf</code>, <code>charCodeAt</code>, <code>charAt</code>, <code>slice</code>.</li> <li><code>Array.prototype</code>: <code>push</code>, <code>pop</code>, <code>join</code>.</li> </ul> <h1><a name="section_5"></a>Contribute</h1> <p>Check out a working copy of the JSON 3 source code with <a href="http://git-scm.com/">Git</a>: </p> <pre><code>$ git clone git://github.com/bestiejs/json3.git $ cd json3 $ git submodule update --init</code></pre> <p>If you&#39;d like to contribute a feature or bug fix, you can <a href="http://help.github.com/fork-a-repo/">fork</a> JSON 3, commit your changes, and <a href="http://help.github.com/send-pull-requests/">send a pull request</a>. Please make sure to update the unit tests in the <code>test</code> directory as well. </p> <p>Alternatively, you can use the <a href="https://github.com/bestiejs/json3/issues">GitHub issue tracker</a> to submit bug reports, feature requests, and questions, or send tweets to <a href="http://twitter.com/kitcambridge">@kitcambridge</a>. </p> <p>JSON 3 is released under the <a href="http://kit.mit-license.org/">MIT License</a>.</p> </div> <div id="footer"> <p>&copy; 2012-2013 <a href="http://kitcambridge.be/">Kit Cambridge</a>.</p> </div> </body> </html>
frangucc/gamify
www/lib/json3/index.html
HTML
mit
10,133
/* MN10300 Watchdog timer * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * - Derived from arch/i386/kernel/nmi.c * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. */ #include <linux/module.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/kernel_stat.h> #include <linux/nmi.h> #include <asm/processor.h> #include <linux/atomic.h> #include <asm/intctl-regs.h> #include <asm/rtc-regs.h> #include <asm/div64.h> #include <asm/smp.h> #include <asm/gdb-stub.h> #include <proc/clock.h> static DEFINE_SPINLOCK(watchdog_print_lock); static unsigned int watchdog; static unsigned int watchdog_hz = 1; unsigned int watchdog_alert_counter[NR_CPUS]; EXPORT_SYMBOL(arch_touch_nmi_watchdog); /* * the best way to detect whether a CPU has a 'hard lockup' problem * is to check its timer makes IRQ counts. If they are not * changing then that CPU has some problem. * * since NMIs dont listen to _any_ locks, we have to be extremely * careful not to rely on unsafe variables. The printk might lock * up though, so we have to break up any console locks first ... * [when there will be more tty-related locks, break them up * here too!] */ static unsigned int last_irq_sums[NR_CPUS]; int __init check_watchdog(void) { irq_cpustat_t tmp[1]; printk(KERN_INFO "Testing Watchdog... "); memcpy(tmp, irq_stat, sizeof(tmp)); local_irq_enable(); mdelay((10 * 1000) / watchdog_hz); /* wait 10 ticks */ local_irq_disable(); if (nmi_count(0) - tmp[0].__nmi_count <= 5) { printk(KERN_WARNING "CPU#%d: Watchdog appears to be stuck!\n", 0); return -1; } printk(KERN_INFO "OK.\n"); /* now that we know it works we can reduce NMI frequency to something * more reasonable; makes a difference in some configs */ watchdog_hz = 1; return 0; } static int __init setup_watchdog(char *str) { unsigned tmp; int opt; u8 ctr; get_option(&str, &opt); if (opt != 1) return 0; watchdog = opt; if (watchdog) { set_intr_stub(EXCEP_WDT, watchdog_handler); ctr = WDCTR_WDCK_65536th; WDCTR = WDCTR_WDRST | ctr; WDCTR = ctr; tmp = WDCTR; tmp = __muldiv64u(1 << (16 + ctr * 2), 1000000, MN10300_WDCLK); tmp = 1000000000 / tmp; watchdog_hz = (tmp + 500) / 1000; } return 1; } __setup("watchdog=", setup_watchdog); void __init watchdog_go(void) { u8 wdt; if (watchdog) { printk(KERN_INFO "Watchdog: running at %uHz\n", watchdog_hz); wdt = WDCTR & ~WDCTR_WDCNE; WDCTR = wdt | WDCTR_WDRST; wdt = WDCTR; WDCTR = wdt | WDCTR_WDCNE; wdt = WDCTR; check_watchdog(); } } #ifdef CONFIG_SMP static void watchdog_dump_register(void *dummy) { printk(KERN_ERR "--- Register Dump (CPU%d) ---\n", CPUID); show_registers(current_frame()); } #endif asmlinkage void watchdog_interrupt(struct pt_regs *regs, enum exception_code excep) { /* * Since current-> is always on the stack, and we always switch * the stack NMI-atomically, it's safe to use smp_processor_id(). */ int sum, cpu; int irq = NMIIRQ; u8 wdt, tmp; wdt = WDCTR & ~WDCTR_WDCNE; WDCTR = wdt; tmp = WDCTR; NMICR = NMICR_WDIF; nmi_count(smp_processor_id())++; kstat_incr_irq_this_cpu(irq); for_each_online_cpu(cpu) { sum = irq_stat[cpu].__irq_count; if ((last_irq_sums[cpu] == sum) #if defined(CONFIG_GDBSTUB) && defined(CONFIG_SMP) && !(CHK_GDBSTUB_BUSY() || atomic_read(&cpu_doing_single_step)) #endif ) { /* * Ayiee, looks like this CPU is stuck ... * wait a few IRQs (5 seconds) before doing the oops ... */ watchdog_alert_counter[cpu]++; if (watchdog_alert_counter[cpu] == 5 * watchdog_hz) { spin_lock(&watchdog_print_lock); /* * We are in trouble anyway, lets at least try * to get a message out. */ bust_spinlocks(1); printk(KERN_ERR "NMI Watchdog detected LOCKUP on CPU%d," " pc %08lx, registers:\n", cpu, regs->pc); #ifdef CONFIG_SMP printk(KERN_ERR "--- Register Dump (CPU%d) ---\n", CPUID); #endif show_registers(regs); #ifdef CONFIG_SMP smp_nmi_call_function(watchdog_dump_register, NULL, 1); #endif printk(KERN_NOTICE "console shuts up ...\n"); console_silent(); spin_unlock(&watchdog_print_lock); bust_spinlocks(0); #ifdef CONFIG_GDBSTUB if (CHK_GDBSTUB_BUSY_AND_ACTIVE()) gdbstub_exception(regs, excep); else gdbstub_intercept(regs, excep); #endif do_exit(SIGSEGV); } } else { last_irq_sums[cpu] = sum; watchdog_alert_counter[cpu] = 0; } } WDCTR = wdt | WDCTR_WDRST; tmp = WDCTR; WDCTR = wdt | WDCTR_WDCNE; tmp = WDCTR; }
BPI-SINOVOIP/BPI-Mainline-kernel
linux-4.14/arch/mn10300/kernel/mn10300-watchdog.c
C
gpl-2.0
4,919
#include <linux/mm.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/module.h> #include <linux/err.h> #include <linux/sched.h> #include <asm/uaccess.h> #define CREATE_TRACE_POINTS #include <trace/events/kmem.h> /** * kstrdup - allocate space for and copy an existing string * @s: the string to duplicate * @gfp: the GFP mask used in the kmalloc() call when allocating memory */ char *kstrdup(const char *s, gfp_t gfp) { size_t len; char *buf; if (!s) return NULL; len = strlen(s) + 1; buf = kmalloc_track_caller(len, gfp); if (buf) memcpy(buf, s, len); return buf; } EXPORT_SYMBOL(kstrdup); /** * kstrndup - allocate space for and copy an existing string * @s: the string to duplicate * @max: read at most @max chars from @s * @gfp: the GFP mask used in the kmalloc() call when allocating memory */ char *kstrndup(const char *s, size_t max, gfp_t gfp) { size_t len; char *buf; if (!s) return NULL; len = strnlen(s, max); buf = kmalloc_track_caller(len+1, gfp); if (buf) { memcpy(buf, s, len); buf[len] = '\0'; } return buf; } EXPORT_SYMBOL(kstrndup); /** * kmemdup - duplicate region of memory * * @src: memory region to duplicate * @len: memory region length * @gfp: GFP mask to use */ void *kmemdup(const void *src, size_t len, gfp_t gfp) { void *p; p = kmalloc_track_caller(len, gfp); if (p) memcpy(p, src, len); return p; } EXPORT_SYMBOL(kmemdup); /** * memdup_user - duplicate memory region from user space * * @src: source address in user space * @len: number of bytes to copy * * Returns an ERR_PTR() on failure. */ void *memdup_user(const void __user *src, size_t len) { void *p; /* * Always use GFP_KERNEL, since copy_from_user() can sleep and * cause pagefault, which makes it pointless to use GFP_NOFS * or GFP_ATOMIC. */ p = kmalloc_track_caller(len, GFP_KERNEL); if (!p) return ERR_PTR(-ENOMEM); if (copy_from_user(p, src, len)) { kfree(p); return ERR_PTR(-EFAULT); } return p; } EXPORT_SYMBOL(memdup_user); /** * __krealloc - like krealloc() but don't free @p. * @p: object to reallocate memory for. * @new_size: how many bytes of memory are required. * @flags: the type of memory to allocate. * * This function is like krealloc() except it never frees the originally * allocated buffer. Use this if you don't want to free the buffer immediately * like, for example, with RCU. */ void *__krealloc(const void *p, size_t new_size, gfp_t flags) { void *ret; size_t ks = 0; if (unlikely(!new_size)) return ZERO_SIZE_PTR; if (p) ks = ksize(p); if (ks >= new_size) return (void *)p; ret = kmalloc_track_caller(new_size, flags); if (ret && p) memcpy(ret, p, ks); return ret; } EXPORT_SYMBOL(__krealloc); /** * krealloc - reallocate memory. The contents will remain unchanged. * @p: object to reallocate memory for. * @new_size: how many bytes of memory are required. * @flags: the type of memory to allocate. * * The contents of the object pointed to are preserved up to the * lesser of the new and old sizes. If @p is %NULL, krealloc() * behaves exactly like kmalloc(). If @size is 0 and @p is not a * %NULL pointer, the object pointed to is freed. */ void *krealloc(const void *p, size_t new_size, gfp_t flags) { void *ret; if (unlikely(!new_size)) { kfree(p); return ZERO_SIZE_PTR; } ret = __krealloc(p, new_size, flags); if (ret && p != ret) kfree(p); return ret; } EXPORT_SYMBOL(krealloc); /** * kzfree - like kfree but zero memory * @p: object to free memory of * * The memory of the object @p points to is zeroed before freed. * If @p is %NULL, kzfree() does nothing. * * Note: this function zeroes the whole allocated buffer which can be a good * deal bigger than the requested buffer size passed to kmalloc(). So be * careful when using this function in performance sensitive code. */ void kzfree(const void *p) { size_t ks; void *mem = (void *)p; if (unlikely(ZERO_OR_NULL_PTR(mem))) return; ks = ksize(mem); memset(mem, 0, ks); kfree(mem); } EXPORT_SYMBOL(kzfree); int kern_ptr_validate(const void *ptr, unsigned long size) { unsigned long addr = (unsigned long)ptr; unsigned long min_addr = PAGE_OFFSET; unsigned long align_mask = sizeof(void *) - 1; if (unlikely(addr < min_addr)) goto out; if (unlikely(addr > (unsigned long)high_memory - size)) goto out; if (unlikely(addr & align_mask)) goto out; if (unlikely(!kern_addr_valid(addr))) goto out; if (unlikely(!kern_addr_valid(addr + size - 1))) goto out; return 1; out: return 0; } /* * strndup_user - duplicate an existing string from user space * @s: The string to duplicate * @n: Maximum number of bytes to copy, including the trailing NUL. */ char *strndup_user(const char __user *s, long n) { char *p; long length; length = strnlen_user(s, n); if (!length) return ERR_PTR(-EFAULT); if (length > n) return ERR_PTR(-EINVAL); p = memdup_user(s, length); if (IS_ERR(p)) return p; p[length - 1] = '\0'; return p; } EXPORT_SYMBOL(strndup_user); #if defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT) void arch_pick_mmap_layout(struct mm_struct *mm) { mm->mmap_base = TASK_UNMAPPED_BASE; mm->get_unmapped_area = arch_get_unmapped_area; mm->unmap_area = arch_unmap_area; } #endif /** * get_user_pages_fast() - pin user pages in memory * @start: starting user address * @nr_pages: number of pages from start to pin * @write: whether pages will be written to * @pages: array that receives pointers to the pages pinned. * Should be at least nr_pages long. * * Returns number of pages pinned. This may be fewer than the number * requested. If nr_pages is 0 or negative, returns 0. If no pages * were pinned, returns -errno. * * get_user_pages_fast provides equivalent functionality to get_user_pages, * operating on current and current->mm, with force=0 and vma=NULL. However * unlike get_user_pages, it must be called without mmap_sem held. * * get_user_pages_fast may take mmap_sem and page table locks, so no * assumptions can be made about lack of locking. get_user_pages_fast is to be * implemented in a way that is advantageous (vs get_user_pages()) when the * user memory area is already faulted in and present in ptes. However if the * pages have to be faulted in, it may turn out to be slightly slower so * callers need to carefully consider what to use. On many architectures, * get_user_pages_fast simply falls back to get_user_pages. */ int __attribute__((weak)) get_user_pages_fast(unsigned long start, int nr_pages, int write, struct page **pages) { struct mm_struct *mm = current->mm; int ret; down_read(&mm->mmap_sem); ret = get_user_pages(current, mm, start, nr_pages, write, 0, pages, NULL); up_read(&mm->mmap_sem); return ret; } EXPORT_SYMBOL_GPL(get_user_pages_fast); /* Tracepoints definitions. */ EXPORT_TRACEPOINT_SYMBOL(kmalloc); EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc); EXPORT_TRACEPOINT_SYMBOL(kmalloc_node); EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc_node); EXPORT_TRACEPOINT_SYMBOL(kfree); EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);
megraf/asuswrt-merlin
release/src-rt-7.x.main/src/linux/linux-2.6.36/mm/util.c
C
gpl-2.0
7,118
namespace Contoso.Core { using System; using System.IO; /// <summary> /// CSV Logger /// </summary> public class CsvLogger : LoggerBase { #region Fields /// <summary> /// The CSV header /// </summary> private const string CsvHeader = "Timestamp,UserAccount,Outcome"; #endregion Fields #region Properties /// <summary> /// Gets or sets the log file location. /// </summary> /// <value> /// The log file location. /// </value> public string LogFileLocation { get; set; } #endregion Properties #region Methods /// <summary> /// Initialise this instance. /// </summary> public override void Initialise() { if (!string.IsNullOrEmpty(this.LogFileLocation)) { if (File.Exists(this.LogFileLocation)) { File.Delete(this.LogFileLocation); } using (StreamWriter file = File.AppendText(this.LogFileLocation)) { file.WriteLine(CsvHeader); } } } /// <summary> /// Logs outcome of user account update in SPO. /// </summary> /// <param name="message">The user</param> /// <param name="ex">The success value</param> public override void LogOutcome(string user, string value) { if (!string.IsNullOrEmpty(this.LogFileLocation)) { using (TextWriter writer = TextWriter.Synchronized(File.AppendText(this.LogFileLocation))) { writer.WriteLine("\"{0}\",\"{1}\",\"{2}\"", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"), user, value); } } } public override void Cleanup() { if (this.EmailSender != null) { string _CurrentTime = DateTime.Now.ToString("dd/MM/yyyy"); string MailHeader = string.Format("{0} - User Profile Utility Outcomes", _CurrentTime); string MailBody = string.Format("The user profile utility was run on {0} and the attached CSV file summarises which accounts were successfully processedgh", _CurrentTime); EmailHelper.SendEmail(this.EmailSender.FromAddress, this.EmailSender.ToAddress, this.EmailSender.Host, this.EmailSender.Port, MailHeader, MailBody, this.LogFileLocation); } } #endregion Methods } }
yagoto/PnP
Samples/Core.BulkUserProfileUpdater/Logger/CsvLogger.cs
C#
mit
2,631
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS Example</title> </head> <body> <script> var myObject = { x: 5, y: 10 }; console.log(myObject); console.log("x = " + myObject.x); console.log("y = " + myObject["y"]); </script> </body> </html>
neelshah23/screencasts
introToD3/examples/code/snapshot41/index.html
HTML
mit
327
<!DOCTYPE html> <!-- DO NOT EDIT! Generated by referrer-policy/generic/tools/generate.py using referrer-policy/generic/template/test.release.html.template. --> <html> <head> <title>Referrer-Policy: Referrer Policy is set to 'origin-only'</title> <meta name="description" content="Check that all subresources in all casses get only the origin portion of the referrer URL."> <meta name="referrer" content="origin"> <link rel="author" title="Kristijan Burnik" href="burnik@chromium.org"> <link rel="help" href="https://w3c.github.io/webappsec/specs/referrer-policy/#referrer-policy-state-origin"> <meta name="assert" content="The referrer URL is origin when a document served over http requires an http sub-resource via img-tag using the meta-referrer delivery method with swap-origin-redirect and when the target request is cross-origin."> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <!-- TODO(kristijanburnik): Minify and merge both: --> <script src="/referrer-policy/generic/common.js"></script> <script src="/referrer-policy/generic/referrer-policy-test-case.js?pipe=sub"></script> </head> <body> <script> ReferrerPolicyTestCase( { "referrer_policy": "origin", "delivery_method": "meta-referrer", "redirection": "swap-origin-redirect", "origin": "cross-origin", "source_protocol": "http", "target_protocol": "http", "subresource": "img-tag", "subresource_path": "/referrer-policy/generic/subresource/image.py", "referrer_url": "origin" }, document.querySelector("meta[name=assert]").content, new SanityChecker() ).start(); </script> <div id="log"></div> </body> </html>
youtube/cobalt
third_party/web_platform_tests/referrer-policy/origin-only/meta-referrer/cross-origin/http-http/img-tag/generic.swap-origin-redirect.http.html
HTML
bsd-3-clause
1,965
/* -*- linux-c -*- * sysctl_net_core.c: sysctl interface to net core subsystem. * * Begun April 1, 1996, Mike Shaver. * Added /proc/sys/net/core directory entry (empty =) ). [MS] */ #include <linux/mm.h> #include <linux/sysctl.h> #include <linux/module.h> #include <linux/socket.h> #include <linux/netdevice.h> #include <linux/ratelimit.h> #include <linux/vmalloc.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/kmemleak.h> #include <net/ip.h> #include <net/sock.h> #include <net/net_ratelimit.h> static int zero = 0; static int ushort_max = USHRT_MAX; static int one = 1; #ifdef CONFIG_RPS static int rps_sock_flow_sysctl(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { unsigned int orig_size, size; int ret, i; ctl_table tmp = { .data = &size, .maxlen = sizeof(size), .mode = table->mode }; struct rps_sock_flow_table *orig_sock_table, *sock_table; static DEFINE_MUTEX(sock_flow_mutex); mutex_lock(&sock_flow_mutex); orig_sock_table = rcu_dereference_protected(rps_sock_flow_table, lockdep_is_held(&sock_flow_mutex)); size = orig_size = orig_sock_table ? orig_sock_table->mask + 1 : 0; ret = proc_dointvec(&tmp, write, buffer, lenp, ppos); if (write) { if (size) { if (size > 1<<30) { /* Enforce limit to prevent overflow */ mutex_unlock(&sock_flow_mutex); return -EINVAL; } size = roundup_pow_of_two(size); if (size != orig_size) { sock_table = vmalloc(RPS_SOCK_FLOW_TABLE_SIZE(size)); if (!sock_table) { mutex_unlock(&sock_flow_mutex); return -ENOMEM; } sock_table->mask = size - 1; } else sock_table = orig_sock_table; for (i = 0; i < size; i++) sock_table->ents[i] = RPS_NO_CPU; } else sock_table = NULL; if (sock_table != orig_sock_table) { rcu_assign_pointer(rps_sock_flow_table, sock_table); if (sock_table) static_key_slow_inc(&rps_needed); if (orig_sock_table) { static_key_slow_dec(&rps_needed); synchronize_rcu(); vfree(orig_sock_table); } } } mutex_unlock(&sock_flow_mutex); return ret; } #endif /* CONFIG_RPS */ static struct ctl_table net_core_table[] = { #ifdef CONFIG_NET { .procname = "wmem_max", .data = &sysctl_wmem_max, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, }, { .procname = "rmem_max", .data = &sysctl_rmem_max, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, }, { .procname = "wmem_default", .data = &sysctl_wmem_default, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, }, { .procname = "rmem_default", .data = &sysctl_rmem_default, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, }, { .procname = "dev_weight", .data = &weight_p, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, { .procname = "netdev_max_backlog", .data = &netdev_max_backlog, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, #ifdef CONFIG_BPF_JIT { .procname = "bpf_jit_enable", .data = &bpf_jit_enable, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, #endif { .procname = "netdev_tstamp_prequeue", .data = &netdev_tstamp_prequeue, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, { .procname = "message_cost", .data = &net_ratelimit_state.interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "message_burst", .data = &net_ratelimit_state.burst, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "optmem_max", .data = &sysctl_optmem_max, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, #ifdef CONFIG_RPS { .procname = "rps_sock_flow_entries", .maxlen = sizeof(int), .mode = 0644, .proc_handler = rps_sock_flow_sysctl }, #endif #endif /* CONFIG_NET */ { .procname = "netdev_budget", .data = &netdev_budget, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, { .procname = "warnings", .data = &net_msg_warn, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, { } }; static struct ctl_table netns_core_table[] = { { .procname = "somaxconn", .data = &init_net.core.sysctl_somaxconn, .maxlen = sizeof(int), .mode = 0644, .extra1 = &zero, .extra2 = &ushort_max, .proc_handler = proc_dointvec_minmax }, { } }; __net_initdata struct ctl_path net_core_path[] = { { .procname = "net", }, { .procname = "core", }, { }, }; static __net_init int sysctl_core_net_init(struct net *net) { struct ctl_table *tbl; net->core.sysctl_somaxconn = SOMAXCONN; tbl = netns_core_table; if (!net_eq(net, &init_net)) { tbl = kmemdup(tbl, sizeof(netns_core_table), GFP_KERNEL); if (tbl == NULL) goto err_dup; tbl[0].data = &net->core.sysctl_somaxconn; } net->core.sysctl_hdr = register_net_sysctl_table(net, net_core_path, tbl); if (net->core.sysctl_hdr == NULL) goto err_reg; return 0; err_reg: if (tbl != netns_core_table) kfree(tbl); err_dup: return -ENOMEM; } static __net_exit void sysctl_core_net_exit(struct net *net) { struct ctl_table *tbl; tbl = net->core.sysctl_hdr->ctl_table_arg; unregister_net_sysctl_table(net->core.sysctl_hdr); BUG_ON(tbl == netns_core_table); kfree(tbl); } static __net_initdata struct pernet_operations sysctl_core_ops = { .init = sysctl_core_net_init, .exit = sysctl_core_net_exit, }; static __init int sysctl_core_init(void) { static struct ctl_table empty[1]; kmemleak_not_leak(register_sysctl_paths(net_core_path, empty)); register_net_sysctl_rotable(net_core_path, net_core_table); return register_pernet_subsys(&sysctl_core_ops); } fs_initcall(sysctl_core_init);
AOSP-bacon/android_kernel_oneplus_msm8974
net/core/sysctl_net_core.c
C
gpl-2.0
5,988
-- Summon minions DELETE FROM `spell_script_names` WHERE `spell_id`=59910; INSERT INTO `spell_script_names`(`spell_id`,`ScriptName`) VALUE (59910,'spell_summon_minions'); -- Heroic spells DELETE FROM `spelldifficulty_dbc` WHERE `id` IN (49198,49034,49037,50089,49668,51363) OR `spellid0` IN (49198,49034,49037,50089,49668,51363); INSERT INTO `spelldifficulty_dbc`(`id`,`spellid0`,`spellid1`) VALUES (49198,49198,59909), -- Arcance Blast (49034,49034,59854), -- Blizzard (49037,49037,59855), -- Frostbolt (50089,50089,59856), -- Wrath of Misery (49668,49668,59004), -- Flash of Darkness (51363,51363,59016); -- Shadow Bolt -- Script assignment for summoners UPDATE `creature_template` SET `ScriptName`='npc_crystal_channel_target',`AIName`='' WHERE `entry`=26712; -- Spawn summoner for Crystal Handlers SET @GUID = 19; DELETE FROM `creature` WHERE `guid`=@GUID; INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `modelid`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `curhealth`) VALUE (@GUID,26712,600,3,17188,-341.31,-724.4,28.57,3.78,3600,8982); -- Check instance script for achievement Oh Novos DELETE FROM `achievement_criteria_data` WHERE `criteria_id`=7361; INSERT INTO `achievement_criteria_data`(`criteria_id`,`type`,`ScriptName`) VALUE (7361,11,'achievement_oh_novos'); -- Waypoints for summoned adds DELETE FROM `waypoint_data` WHERE `id` IN(2759700,2759800,2760000,2662700); INSERT INTO `waypoint_data`(`id`,`point`,`position_x`,`position_y`,`position_z`) VALUES (2759700,1,-379.473,-810.974,59.7612), (2759700,2,-379.449,-791.535,44.1756), (2759700,3,-379.448,-790.328,44.1756), (2759700,4,-379.426,-772.338,28.5884), (2759700,5,-379.415,-763.518,28.5884), (2760000,1,-376.571,-810.681,59.6673), (2760000,2,-375.627,-791.874,44.1756), (2760000,3,-375.629,-790.273,44.1434), (2760000,4,-375.402,-771.145,28.5895), (2760000,5,-375.337,-765.027,28.5895), (2759800,1,-382.303,-810.815,59.7628), (2759800,2,-382.324,-791.595,44.1756), (2759800,3,-382.326,-790.331,44.1746), (2759800,4,-383.037,-770.382,28.5884), (2759800,5,-383.140,-765.399,28.5884), (2662700,1,-346.977,-733.319,28.5838), (2662700,2,-363.009,-765.202,28.5907), (2662700,3,-378.269,-765.701,28.5893); -- SAI for Crystal Handlers and Risen Shadowcasters UPDATE `creature_template` SET `AIName`='SmartAI',`ScriptName`='' WHERE `entry` IN (26627,27600); DELETE FROM `smart_scripts` WHERE `entryorguid` IN (26627,27600) AND `source_type`=0; INSERT INTO `smart_scripts`(`entryorguid`,`event_type`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`action_type`,`action_param1`,`target_type`,`comment`) VALUES (26627,0,1000,1000,5000,5000,11,49668,2,'Crystal Handler - In fight - After 1s then every 5s - Cast Flash of Darkness - On victim'), (27600,0,1000,1000,5000,5000,11,51363,2,'Risen Shadowcaster - In fight - After 1s then every 5s - Cast Shadow Bolt - On victim'); -- Conditions for beam spell DELETE FROM `conditions` WHERE `SourceTypeOrReferenceId`=13 AND `SourceEntry`=52106; INSERT INTO `conditions`(`SourceTypeOrReferenceId`,`SourceGroup`,`SourceEntry`,`ConditionTypeOrReference`,`ConditionTarget`,`ConditionValue1`,`ConditionValue2`,`ConditionValue3`,`Comment`) VALUES (13,1,52106,31,0,3,26712,0,'Beam Channel target has to be Crystal Channel Target'), (13,1,52106,35,1,0, 18,1,'Beam Channel target must not be self');
lovequilt/TrinityCore
sql/old/4.3.4/TDB1_to_TDB2_updates/world/213_2013_01_04_02_world_novos_the_summoner.sql
SQL
gpl-2.0
3,360
/* Area: ffi_call, unwind info Purpose: Check if the unwind information is passed correctly. Limitations: none. PR: none. Originator: Andreas Tobler <andreast@gcc.gnu.org> 20061213 */ /* { dg-do run } */ #include "ffitest.h" static int checking(int a __UNUSED__, short b __UNUSED__, signed char c __UNUSED__) { throw 9; } int main (void) { ffi_cif cif; ffi_type *args[MAX_ARGS]; void *values[MAX_ARGS]; ffi_arg rint; signed int si; signed short ss; signed char sc; args[0] = &ffi_type_sint; values[0] = &si; args[1] = &ffi_type_sshort; values[1] = &ss; args[2] = &ffi_type_schar; values[2] = &sc; /* Initialize the cif */ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &ffi_type_sint, args) == FFI_OK); si = -6; ss = -12; sc = -1; { try { ffi_call(&cif, FFI_FN(checking), &rint, values); } catch (int exception_code) { CHECK(exception_code == 9); } printf("part one OK\n"); /* { dg-output "part one OK" } */ } exit(0); }
fernandoandreotti/cibim
vendor/ruby/2.4.0/gems/ffi-1.9.23/ext/ffi_c/libffi/testsuite/libffi.call/unwindtest_ffi_call.cc
C++
apache-2.0
1,036
@import url(http://fonts.googleapis.com/css?family=News+Cycle:400,700); @import url(http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic); /** * A simple theme for reveal.js presentations, similar * to the default theme. The accent color is darkblue. * * This theme is Copyright (C) 2012 Owen Versteeg, https://github.com/StereotypicalApps. It is MIT licensed. * reveal.js is Copyright (C) 2011-2012 Hakim El Hattab, http://hakim.se */ /********************************************* * GLOBAL STYLES *********************************************/ body { background: white; background-color: white; } .reveal { font-family: "Lato", Times, "Times New Roman", serif; font-size: 36px; font-weight: 200; letter-spacing: -0.02em; color: black; } ::selection { color: white; background: rgba(0, 0, 0, 0.99); text-shadow: none; } /********************************************* * HEADERS *********************************************/ .reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6 { margin: 0 0 20px 0; color: black; font-family: "News Cycle", Impact, sans-serif; line-height: 0.9em; letter-spacing: 0.02em; text-transform: none; text-shadow: none; } .reveal h1 { text-shadow: 0px 0px 6px rgba(0, 0, 0, 0.2); } /********************************************* * LINKS *********************************************/ .reveal a:not(.image) { color: darkblue; text-decoration: none; -webkit-transition: color .15s ease; -moz-transition: color .15s ease; -ms-transition: color .15s ease; -o-transition: color .15s ease; transition: color .15s ease; } .reveal a:not(.image):hover { color: #0000f1; text-shadow: none; border: none; } .reveal .roll span:after { color: #fff; background: #00003f; } /********************************************* * IMAGES *********************************************/ .reveal section img { margin: 15px 0px; background: rgba(255, 255, 255, 0.12); border: 4px solid black; box-shadow: 0 0 10px rgba(0, 0, 0, 0.15); -webkit-transition: all .2s linear; -moz-transition: all .2s linear; -ms-transition: all .2s linear; -o-transition: all .2s linear; transition: all .2s linear; } .reveal a:hover img { background: rgba(255, 255, 255, 0.2); border-color: darkblue; box-shadow: 0 0 20px rgba(0, 0, 0, 0.55); } /********************************************* * NAVIGATION CONTROLS *********************************************/ .reveal .controls div.navigate-left, .reveal .controls div.navigate-left.enabled { border-right-color: darkblue; } .reveal .controls div.navigate-right, .reveal .controls div.navigate-right.enabled { border-left-color: darkblue; } .reveal .controls div.navigate-up, .reveal .controls div.navigate-up.enabled { border-bottom-color: darkblue; } .reveal .controls div.navigate-down, .reveal .controls div.navigate-down.enabled { border-top-color: darkblue; } .reveal .controls div.navigate-left.enabled:hover { border-right-color: #0000f1; } .reveal .controls div.navigate-right.enabled:hover { border-left-color: #0000f1; } .reveal .controls div.navigate-up.enabled:hover { border-bottom-color: #0000f1; } .reveal .controls div.navigate-down.enabled:hover { border-top-color: #0000f1; } /********************************************* * PROGRESS BAR *********************************************/ .reveal .progress { background: rgba(0, 0, 0, 0.2); } .reveal .progress span { background: darkblue; -webkit-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); -moz-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); -ms-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); -o-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); }
dongweiming/blog
zongjie/css/theme/simple.css
CSS
mit
3,862
<?php namespace Anax\MVC; /** * Helpers for redirecting to other pages and controllers. * */ trait TRedirectHelpers { /** * Redirect to current or another route. * * @param string $route the route to redirect to, * null to redirect to current route, "" to redirect to baseurl. * * @return void */ public function redirectTo($route = null) { if (is_null($route)) { $url = $this->di->request->getCurrentUrl(); } else { $url = $this->di->url->create($route); } $this->di->response->redirect($url); } }
donami/ctable
vendor/anax/mvc/src/MVC/TRedirectHelpers.php
PHP
mit
613
/*============================================================================= Copyright (c) 2001-2008 Joel de Guzman Copyright (c) 2001-2008 Hartmut Kaiser http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_DEPRECATED_INCLUDE_SKIPPER_FWD #define BOOST_SPIRIT_DEPRECATED_INCLUDE_SKIPPER_FWD #include <boost/version.hpp> #if BOOST_VERSION >= 103800 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__DMC__) # pragma message ("Warning: This header is deprecated. Please use: boost/spirit/include/classic_skipper_fwd.hpp") #elif defined(__GNUC__) || defined(__HP_aCC) || defined(__SUNPRO_CC) || defined(__IBMCPP__) # warning "This header is deprecated. Please use: boost/spirit/include/classic_skipper_fwd.hpp" #endif #endif #if !defined(BOOST_SPIRIT_USE_OLD_NAMESPACE) #define BOOST_SPIRIT_USE_OLD_NAMESPACE #endif #include <boost/spirit/include/classic_skipper_fwd.hpp> #endif
titanmonsta/fluorescence
winbuild/include/boost/spirit/core/scanner/skipper_fwd.hpp
C++
gpl-3.0
1,131
/** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); };
drleewarden/2014-bootstrap
wp-content/themes/arcade-basic/node_modules/bower/node_modules/insight/node_modules/inquirer/node_modules/rx/src/core/linq/observable/catch.js
JavaScript
gpl-2.0
635
/* * Header file for dma buffer sharing framework. * * Copyright(C) 2011 Linaro Limited. All rights reserved. * Author: Sumit Semwal <sumit.semwal@ti.com> * * Many thanks to linaro-mm-sig list, and specially * Arnd Bergmann <arnd@arndb.de>, Rob Clark <rob@ti.com> and * Daniel Vetter <daniel@ffwll.ch> for their support in creation and * refining of this idea. * * 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, see <http://www.gnu.org/licenses/>. */ #ifndef __DMA_BUF_H__ #define __DMA_BUF_H__ #include <linux/file.h> #include <linux/err.h> #include <linux/scatterlist.h> #include <linux/list.h> #include <linux/dma-mapping.h> #include <linux/fs.h> #include <linux/fence.h> #include <linux/wait.h> struct device; struct dma_buf; struct dma_buf_attachment; /** * struct dma_buf_ops - operations possible on struct dma_buf * @attach: [optional] allows different devices to 'attach' themselves to the * given buffer. It might return -EBUSY to signal that backing storage * is already allocated and incompatible with the requirements * of requesting device. * @detach: [optional] detach a given device from this buffer. * @map_dma_buf: returns list of scatter pages allocated, increases usecount * of the buffer. Requires atleast one attach to be called * before. Returned sg list should already be mapped into * _device_ address space. This call may sleep. May also return * -EINTR. Should return -EINVAL if attach hasn't been called yet. * @unmap_dma_buf: decreases usecount of buffer, might deallocate scatter * pages. * @release: release this buffer; to be called after the last dma_buf_put. * @begin_cpu_access: [optional] called before cpu access to invalidate cpu * caches and allocate backing storage (if not yet done) * respectively pin the objet into memory. * @end_cpu_access: [optional] called after cpu access to flush caches. * @kmap_atomic: maps a page from the buffer into kernel address * space, users may not block until the subsequent unmap call. * This callback must not sleep. * @kunmap_atomic: [optional] unmaps a atomically mapped page from the buffer. * This Callback must not sleep. * @kmap: maps a page from the buffer into kernel address space. * @kunmap: [optional] unmaps a page from the buffer. * @mmap: used to expose the backing storage to userspace. Note that the * mapping needs to be coherent - if the exporter doesn't directly * support this, it needs to fake coherency by shooting down any ptes * when transitioning away from the cpu domain. * @vmap: [optional] creates a virtual mapping for the buffer into kernel * address space. Same restrictions as for vmap and friends apply. * @vunmap: [optional] unmaps a vmap from the buffer */ struct dma_buf_ops { int (*attach)(struct dma_buf *, struct device *, struct dma_buf_attachment *); void (*detach)(struct dma_buf *, struct dma_buf_attachment *); /* For {map,unmap}_dma_buf below, any specific buffer attributes * required should get added to device_dma_parameters accessible * via dev->dma_params. */ struct sg_table * (*map_dma_buf)(struct dma_buf_attachment *, enum dma_data_direction); void (*unmap_dma_buf)(struct dma_buf_attachment *, struct sg_table *, enum dma_data_direction); /* TODO: Add try_map_dma_buf version, to return immed with -EBUSY * if the call would block. */ /* after final dma_buf_put() */ void (*release)(struct dma_buf *); int (*begin_cpu_access)(struct dma_buf *, size_t, size_t, enum dma_data_direction); void (*end_cpu_access)(struct dma_buf *, size_t, size_t, enum dma_data_direction); void *(*kmap_atomic)(struct dma_buf *, unsigned long); void (*kunmap_atomic)(struct dma_buf *, unsigned long, void *); void *(*kmap)(struct dma_buf *, unsigned long); void (*kunmap)(struct dma_buf *, unsigned long, void *); int (*mmap)(struct dma_buf *, struct vm_area_struct *vma); void *(*vmap)(struct dma_buf *); void (*vunmap)(struct dma_buf *, void *vaddr); }; /** * struct dma_buf - shared buffer object * @size: size of the buffer * @file: file pointer used for sharing buffers across, and for refcounting. * @attachments: list of dma_buf_attachment that denotes all devices attached. * @ops: dma_buf_ops associated with this buffer object. * @exp_name: name of the exporter; useful for debugging. * @list_node: node for dma_buf accounting and debugging. * @priv: exporter specific private data for this buffer object. * @resv: reservation object linked to this dma-buf */ struct dma_buf { size_t size; struct file *file; struct list_head attachments; const struct dma_buf_ops *ops; /* mutex to serialize list manipulation, attach/detach and vmap/unmap */ struct mutex lock; unsigned vmapping_counter; void *vmap_ptr; const char *exp_name; struct list_head list_node; void *priv; struct reservation_object *resv; /* poll support */ wait_queue_head_t poll; struct dma_buf_poll_cb_t { struct fence_cb cb; wait_queue_head_t *poll; unsigned long active; } cb_excl, cb_shared; }; /** * struct dma_buf_attachment - holds device-buffer attachment data * @dmabuf: buffer for this attachment. * @dev: device attached to the buffer. * @node: list of dma_buf_attachment. * @priv: exporter specific attachment data. * * This structure holds the attachment information between the dma_buf buffer * and its user device(s). The list contains one attachment struct per device * attached to the buffer. */ struct dma_buf_attachment { struct dma_buf *dmabuf; struct device *dev; struct list_head node; void *priv; }; /** * get_dma_buf - convenience wrapper for get_file. * @dmabuf: [in] pointer to dma_buf * * Increments the reference count on the dma-buf, needed in case of drivers * that either need to create additional references to the dmabuf on the * kernel side. For example, an exporter that needs to keep a dmabuf ptr * so that subsequent exports don't create a new dmabuf. */ static inline void get_dma_buf(struct dma_buf *dmabuf) { get_file(dmabuf->file); } struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf, struct device *dev); void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *dmabuf_attach); struct dma_buf *dma_buf_export_named(void *priv, const struct dma_buf_ops *ops, size_t size, int flags, const char *, struct reservation_object *); #define dma_buf_export(priv, ops, size, flags, resv) \ dma_buf_export_named(priv, ops, size, flags, KBUILD_MODNAME, resv) int dma_buf_fd(struct dma_buf *dmabuf, int flags); struct dma_buf *dma_buf_get(int fd); void dma_buf_put(struct dma_buf *dmabuf); struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *, enum dma_data_direction); void dma_buf_unmap_attachment(struct dma_buf_attachment *, struct sg_table *, enum dma_data_direction); int dma_buf_begin_cpu_access(struct dma_buf *dma_buf, size_t start, size_t len, enum dma_data_direction dir); void dma_buf_end_cpu_access(struct dma_buf *dma_buf, size_t start, size_t len, enum dma_data_direction dir); void *dma_buf_kmap_atomic(struct dma_buf *, unsigned long); void dma_buf_kunmap_atomic(struct dma_buf *, unsigned long, void *); void *dma_buf_kmap(struct dma_buf *, unsigned long); void dma_buf_kunmap(struct dma_buf *, unsigned long, void *); int dma_buf_mmap(struct dma_buf *, struct vm_area_struct *, unsigned long); void *dma_buf_vmap(struct dma_buf *); void dma_buf_vunmap(struct dma_buf *, void *vaddr); int dma_buf_debugfs_create_file(const char *name, int (*write)(struct seq_file *)); #endif /* __DMA_BUF_H__ */
mericon/Xp_Kernel_LGH850
virt/include/linux/dma-buf.h
C
gpl-2.0
8,177
/** * @file fairqueue_test.c * @author Ambroz Bizjak <ambrop7@gmail.com> * * @section LICENSE * * 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 author 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 AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <string.h> #include <stdio.h> #include <stddef.h> #include <misc/debug.h> #include <system/BReactor.h> #include <base/BLog.h> #include <system/BTime.h> #include <flow/PacketPassFairQueue.h> #include <examples/FastPacketSource.h> #include <examples/TimerPacketSink.h> #define OUTPUT_INTERVAL 0 #define REMOVE_INTERVAL 1 #define NUM_INPUTS 3 BReactor reactor; TimerPacketSink sink; PacketPassFairQueue fq; PacketPassFairQueueFlow flows[NUM_INPUTS]; FastPacketSource sources[NUM_INPUTS]; char *data[] = {"0 data", "1 datadatadata", "2 datadatadatadatadata"}; BTimer timer; int current_cancel; static void init_input (int i) { PacketPassFairQueueFlow_Init(&flows[i], &fq); FastPacketSource_Init(&sources[i], PacketPassFairQueueFlow_GetInput(&flows[i]), (uint8_t *)data[i], strlen(data[i]), BReactor_PendingGroup(&reactor)); } static void free_input (int i) { FastPacketSource_Free(&sources[i]); PacketPassFairQueueFlow_Free(&flows[i]); } static void reset_input (void) { PacketPassFairQueueFlow_AssertFree(&flows[current_cancel]); printf("removing %d\n", current_cancel); // remove flow free_input(current_cancel); // init flow init_input(current_cancel); // increment cancel current_cancel = (current_cancel + 1) % NUM_INPUTS; // reset timer BReactor_SetTimer(&reactor, &timer); } static void flow_handler_busy (void *user) { PacketPassFairQueueFlow_AssertFree(&flows[current_cancel]); reset_input(); } static void timer_handler (void *user) { // if flow is busy, request cancel and wait for it if (PacketPassFairQueueFlow_IsBusy(&flows[current_cancel])) { printf("cancelling %d\n", current_cancel); PacketPassFairQueueFlow_RequestCancel(&flows[current_cancel]); PacketPassFairQueueFlow_SetBusyHandler(&flows[current_cancel], flow_handler_busy, NULL); return; } reset_input(); } int main () { // initialize logging BLog_InitStdout(); // init time BTime_Init(); // initialize reactor if (!BReactor_Init(&reactor)) { DEBUG("BReactor_Init failed"); return 1; } // initialize sink TimerPacketSink_Init(&sink, &reactor, 500, OUTPUT_INTERVAL); // initialize queue if (!PacketPassFairQueue_Init(&fq, TimerPacketSink_GetInput(&sink), BReactor_PendingGroup(&reactor), 1, 1)) { DEBUG("PacketPassFairQueue_Init failed"); return 1; } // initialize inputs for (int i = 0; i < NUM_INPUTS; i++) { init_input(i); } // init cancel timer BTimer_Init(&timer, REMOVE_INTERVAL, timer_handler, NULL); BReactor_SetTimer(&reactor, &timer); // init cancel counter current_cancel = 0; // run reactor int ret = BReactor_Exec(&reactor); BReactor_Free(&reactor); return ret; }
Jigsaw-Code/outline-client
third_party/badvpn/examples/fairqueue_test.c
C
apache-2.0
4,461
"use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var Dispatcher = require("flux").Dispatcher; var EventEmitter = _interopRequire(require("eventemitter3")); var Symbol = _interopRequire(require("es-symbol")); var assign = _interopRequire(require("object-assign")); var ACTION_HANDLER = Symbol("action creator handler"); var ACTION_KEY = Symbol("holds the actions uid symbol for listening"); var ACTION_UID = Symbol("the actions uid name"); var EE = Symbol("event emitter instance"); var INIT_SNAPSHOT = Symbol("init snapshot storage"); var LAST_SNAPSHOT = Symbol("last snapshot storage"); var LIFECYCLE = Symbol("store lifecycle listeners"); var LISTENERS = Symbol("stores action listeners storage"); var PUBLIC_METHODS = Symbol("store public method storage"); var STATE_CONTAINER = Symbol("the state container"); function formatAsConstant(name) { return name.replace(/[a-z]([A-Z])/g, function (i) { return "" + i[0] + "_" + i[1].toLowerCase(); }).toUpperCase(); } function uid(container, name) { var count = 0; var key = name; while (Object.hasOwnProperty.call(container, key)) { key = name + String(++count); } return key; } /* istanbul ignore next */ function NoopClass() {} var builtIns = Object.getOwnPropertyNames(NoopClass); var builtInProto = Object.getOwnPropertyNames(NoopClass.prototype); var getInternalMethods = function (obj, excluded) { return Object.getOwnPropertyNames(obj).reduce(function (value, m) { if (excluded.indexOf(m) !== -1) { return value; } value[m] = obj[m]; return value; }, {}); }; var AltStore = (function () { function AltStore(dispatcher, model, state) { var _this8 = this; _classCallCheck(this, AltStore); this[EE] = new EventEmitter(); this[LIFECYCLE] = {}; this[STATE_CONTAINER] = state || model; assign(this[LIFECYCLE], model[LIFECYCLE]); assign(this, model[PUBLIC_METHODS]); // Register dispatcher this.dispatchToken = dispatcher.register(function (payload) { if (model[LISTENERS][payload.action]) { var result = model[LISTENERS][payload.action](payload.data); if (result !== false) { _this8.emitChange(); } } }); if (this[LIFECYCLE].init) { this[LIFECYCLE].init(); } } _createClass(AltStore, { getEventEmitter: { value: function getEventEmitter() { return this[EE]; } }, emitChange: { value: function emitChange() { this[EE].emit("change", this[STATE_CONTAINER]); } }, listen: { value: function listen(cb) { this[EE].on("change", cb); } }, unlisten: { value: function unlisten(cb) { this[EE].removeListener("change", cb); } }, getState: { value: function getState() { // Copy over state so it's RO. return assign({}, this[STATE_CONTAINER]); } } }); return AltStore; })(); var ActionCreator = (function () { function ActionCreator(alt, name, action, actions) { _classCallCheck(this, ActionCreator); this[ACTION_UID] = name; this[ACTION_HANDLER] = action.bind(this); this.actions = actions; this.alt = alt; } _createClass(ActionCreator, { dispatch: { value: function dispatch(data) { this.alt.dispatch(this[ACTION_UID], data); } } }); return ActionCreator; })(); var StoreMixinListeners = { on: function on(lifecycleEvent, handler) { this[LIFECYCLE][lifecycleEvent] = handler.bind(this); }, bindAction: function bindAction(symbol, handler) { if (!symbol) { throw new ReferenceError("Invalid action reference passed in"); } if (typeof handler !== "function") { throw new TypeError("bindAction expects a function"); } if (handler.length > 1) { throw new TypeError("Action handler in store " + this._storeName + " for " + ("" + (symbol[ACTION_KEY] || symbol).toString() + " was defined with 2 ") + "parameters. Only a single parameter is passed through the " + "dispatcher, did you mean to pass in an Object instead?"); } // You can pass in the constant or the function itself if (symbol[ACTION_KEY]) { this[LISTENERS][symbol[ACTION_KEY]] = handler.bind(this); } else { this[LISTENERS][symbol] = handler.bind(this); } }, bindActions: function bindActions(actions) { var _this8 = this; Object.keys(actions).forEach(function (action) { var symbol = actions[action]; var matchFirstCharacter = /./; var assumedEventHandler = action.replace(matchFirstCharacter, function (x) { return "on" + x[0].toUpperCase(); }); var handler = null; if (_this8[action] && _this8[assumedEventHandler]) { // If you have both action and onAction throw new ReferenceError("You have multiple action handlers bound to an action: " + ("" + action + " and " + assumedEventHandler)); } else if (_this8[action]) { // action handler = _this8[action]; } else if (_this8[assumedEventHandler]) { // onAction handler = _this8[assumedEventHandler]; } if (handler) { _this8.bindAction(symbol, handler); } }); }, bindListeners: function bindListeners(obj) { var _this8 = this; Object.keys(obj).forEach(function (methodName) { var symbol = obj[methodName]; var listener = _this8[methodName]; if (!listener) { throw new ReferenceError("" + methodName + " defined but does not exist in " + _this8._storeName); } if (Array.isArray(symbol)) { symbol.forEach(function (action) { _this8.bindAction(action, listener); }); } else { _this8.bindAction(symbol, listener); } }); } }; var StoreMixinEssentials = { waitFor: function waitFor(sources) { if (!sources) { throw new ReferenceError("Dispatch tokens not provided"); } if (arguments.length === 1) { sources = Array.isArray(sources) ? sources : [sources]; } else { sources = Array.prototype.slice.call(arguments); } var tokens = sources.map(function (source) { return source.dispatchToken || source; }); this.dispatcher.waitFor(tokens); }, exportPublicMethods: function exportPublicMethods(methods) { var _this8 = this; Object.keys(methods).forEach(function (methodName) { if (typeof methods[methodName] !== "function") { throw new TypeError("exportPublicMethods expects a function"); } _this8[PUBLIC_METHODS][methodName] = methods[methodName]; }); }, emitChange: function emitChange() { this.getInstance().emitChange(); } }; var setAppState = function (instance, data, onStore) { var obj = JSON.parse(data); Object.keys(obj).forEach(function (key) { var store = instance.stores[key]; if (store[LIFECYCLE].deserialize) { obj[key] = store[LIFECYCLE].deserialize(obj[key]) || obj[key]; } assign(store[STATE_CONTAINER], obj[key]); onStore(store); }); }; var snapshot = function (instance) { return JSON.stringify(Object.keys(instance.stores).reduce(function (obj, key) { var store = instance.stores[key]; var customSnapshot = store[LIFECYCLE].serialize && store[LIFECYCLE].serialize(); obj[key] = customSnapshot ? customSnapshot : store.getState(); return obj; }, {})); }; var saveInitialSnapshot = function (instance, key) { var state = instance.stores[key][STATE_CONTAINER]; var initial = JSON.parse(instance[INIT_SNAPSHOT]); initial[key] = state; instance[INIT_SNAPSHOT] = JSON.stringify(initial); }; var filterSnapshotOfStores = function (serializedSnapshot, storeNames) { var stores = JSON.parse(serializedSnapshot); var storesToReset = storeNames.reduce(function (obj, name) { if (!stores[name]) { throw new ReferenceError("" + name + " is not a valid store"); } obj[name] = stores[name]; return obj; }, {}); return JSON.stringify(storesToReset); }; var createStoreFromObject = function (alt, StoreModel, key, saveStore) { var storeInstance = undefined; var StoreProto = {}; StoreProto[LIFECYCLE] = {}; StoreProto[LISTENERS] = {}; assign(StoreProto, { _storeName: key, alt: alt, dispatcher: alt.dispatcher, getInstance: function getInstance() { return storeInstance; }, setState: function setState() { var values = arguments[0] === undefined ? {} : arguments[0]; assign(this.state, values); this.emitChange(); return false; } }, StoreMixinListeners, StoreMixinEssentials, StoreModel); // bind the store listeners /* istanbul ignore else */ if (StoreProto.bindListeners) { StoreMixinListeners.bindListeners.call(StoreProto, StoreProto.bindListeners); } // bind the lifecycle events /* istanbul ignore else */ if (StoreProto.lifecycle) { Object.keys(StoreProto.lifecycle).forEach(function (event) { StoreMixinListeners.on.call(StoreProto, event, StoreProto.lifecycle[event]); }); } // create the instance and assign the public methods to the instance storeInstance = assign(new AltStore(alt.dispatcher, StoreProto, StoreProto.state), StoreProto.publicMethods); /* istanbul ignore else */ if (saveStore) { alt.stores[key] = storeInstance; saveInitialSnapshot(alt, key); } return storeInstance; }; var Alt = (function () { function Alt() { _classCallCheck(this, Alt); this.dispatcher = new Dispatcher(); this.actions = {}; this.stores = {}; this[LAST_SNAPSHOT] = null; this[INIT_SNAPSHOT] = "{}"; } _createClass(Alt, { dispatch: { value: function dispatch(action, data) { this.dispatcher.dispatch({ action: action, data: data }); } }, createStore: { value: function createStore(StoreModel, iden) { var saveStore = arguments[2] === undefined ? true : arguments[2]; var storeInstance = undefined; var key = iden || StoreModel.name || StoreModel.displayName || ""; if (saveStore && (this.stores[key] || !key)) { /* istanbul ignore else */ if (typeof console !== "undefined") { if (this.stores[key]) { console.warn(new ReferenceError("A store named " + key + " already exists, double check your store " + "names or pass in your own custom identifier for each store")); } else { console.warn(new ReferenceError("Store name was not specified")); } } key = uid(this.stores, key); } if (typeof StoreModel === "object") { return createStoreFromObject(this, StoreModel, key, saveStore); } // Creating a class here so we don't overload the provided store's // prototype with the mixin behaviour and I'm extending from StoreModel // so we can inherit any extensions from the provided store. var Store = (function (_StoreModel) { function Store(alt) { _classCallCheck(this, Store); _get(Object.getPrototypeOf(Store.prototype), "constructor", this).call(this, alt); } _inherits(Store, _StoreModel); return Store; })(StoreModel); assign(Store.prototype, StoreMixinListeners, StoreMixinEssentials, { _storeName: key, alt: this, dispatcher: this.dispatcher, getInstance: function getInstance() { return storeInstance; }, setState: function setState() { var values = arguments[0] === undefined ? {} : arguments[0]; assign(this, values); this.emitChange(); return false; } }); Store.prototype[LIFECYCLE] = {}; Store.prototype[LISTENERS] = {}; Store.prototype[PUBLIC_METHODS] = {}; var store = new Store(this); storeInstance = assign(new AltStore(this.dispatcher, store), getInternalMethods(StoreModel, builtIns)); if (saveStore) { this.stores[key] = storeInstance; saveInitialSnapshot(this, key); } return storeInstance; } }, generateActions: { value: function generateActions() { for (var _len = arguments.length, actionNames = Array(_len), _key = 0; _key < _len; _key++) { actionNames[_key] = arguments[_key]; } return this.createActions(function () { this.generateActions.apply(this, actionNames); }); } }, createActions: { value: function createActions(ActionsClass) { var _this8 = this; var exportObj = arguments[1] === undefined ? {} : arguments[1]; var actions = assign({}, getInternalMethods(ActionsClass.prototype, builtInProto)); var key = ActionsClass.name || ActionsClass.displayName || ""; var ActionsGenerator = (function (_ActionsClass) { function ActionsGenerator(alt) { _classCallCheck(this, ActionsGenerator); _get(Object.getPrototypeOf(ActionsGenerator.prototype), "constructor", this).call(this, alt); } _inherits(ActionsGenerator, _ActionsClass); _createClass(ActionsGenerator, { generateActions: { value: function generateActions() { for (var _len = arguments.length, actionNames = Array(_len), _key = 0; _key < _len; _key++) { actionNames[_key] = arguments[_key]; } actionNames.forEach(function (actionName) { // This is a function so we can later bind this to ActionCreator actions[actionName] = function (x) { for (var _len2 = arguments.length, a = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { a[_key2 - 1] = arguments[_key2]; } this.dispatch(a.length ? [x].concat(a) : x); }; }); } } }); return ActionsGenerator; })(ActionsClass); new ActionsGenerator(this); return Object.keys(actions).reduce(function (obj, action) { var constant = formatAsConstant(action); var actionName = Symbol("" + key + "#" + action); // Wrap the action so we can provide a dispatch method var newAction = new ActionCreator(_this8, actionName, actions[action], obj); // Set all the properties on action obj[action] = newAction[ACTION_HANDLER]; obj[action].defer = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } setTimeout(function () { newAction[ACTION_HANDLER].apply(null, args); }); }; obj[action][ACTION_KEY] = actionName; obj[constant] = actionName; return obj; }, exportObj); } }, takeSnapshot: { value: function takeSnapshot() { var state = snapshot(this); this[LAST_SNAPSHOT] = state; return state; } }, rollback: { value: function rollback() { setAppState(this, this[LAST_SNAPSHOT], function (store) { if (store[LIFECYCLE].rollback) { store[LIFECYCLE].rollback(); } }); } }, recycle: { value: function recycle() { for (var _len = arguments.length, storeNames = Array(_len), _key = 0; _key < _len; _key++) { storeNames[_key] = arguments[_key]; } var initialSnapshot = storeNames.length ? filterSnapshotOfStores(this[INIT_SNAPSHOT], storeNames) : this[INIT_SNAPSHOT]; setAppState(this, initialSnapshot, function (store) { if (store[LIFECYCLE].init) { store[LIFECYCLE].init(); } }); } }, flush: { value: function flush() { var state = snapshot(this); this.recycle(); return state; } }, bootstrap: { value: function bootstrap(data) { setAppState(this, data, function (store) { if (store[LIFECYCLE].bootstrap) { store[LIFECYCLE].bootstrap(); } }); } }, addActions: { // Instance type methods for injecting alt into your application as context value: function addActions(name, ActionsClass) { this.actions[name] = this.createActions(ActionsClass); } }, addStore: { value: function addStore(name, StoreModel, saveStore) { this.createStore(StoreModel, name, saveStore); } }, getActions: { value: function getActions(name) { return this.actions[name]; } }, getStore: { value: function getStore(name) { return this.stores[name]; } } }); return Alt; })(); module.exports = Alt;
AMoo-Miki/cdnjs
ajax/libs/alt/0.14.4/alt.js
JavaScript
mit
18,625
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved #pragma once #include <CritSec.h> #include <linklist.h> #include <StspDefs.h> namespace Microsoft { namespace Samples { namespace SimpleCommunication { class CMediaSource; namespace Network { interface IBufferPacket; } class CMediaStream : public IMFMediaStream, public IMFQualityAdvise2, public IMFGetService { public: static HRESULT CreateInstance(StspStreamDescription *pStreamDescription, Network::IBufferPacket *pAttributesBuffer, CMediaSource *pSource, CMediaStream **ppStream); // IUnknown IFACEMETHOD (QueryInterface) (REFIID iid, void **ppv); IFACEMETHOD_ (ULONG, AddRef) (); IFACEMETHOD_ (ULONG, Release) (); // IMFMediaEventGenerator IFACEMETHOD (BeginGetEvent) (IMFAsyncCallback *pCallback,IUnknown *punkState); IFACEMETHOD (EndGetEvent) (IMFAsyncResult *pResult, IMFMediaEvent **ppEvent); IFACEMETHOD (GetEvent) (DWORD dwFlags, IMFMediaEvent **ppEvent); IFACEMETHOD (QueueEvent) (MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT *pvValue); // IMFMediaStream IFACEMETHOD (GetMediaSource) (IMFMediaSource **ppMediaSource); IFACEMETHOD (GetStreamDescriptor) (IMFStreamDescriptor **ppStreamDescriptor); IFACEMETHOD (RequestSample) (IUnknown *pToken); // IMFQualityAdvise IFACEMETHOD (SetDropMode ) (_In_ MF_QUALITY_DROP_MODE eDropMode); IFACEMETHOD (SetQualityLevel ) ( _In_ MF_QUALITY_LEVEL eQualityLevel); IFACEMETHOD (GetDropMode ) (_Out_ MF_QUALITY_DROP_MODE *peDropMode); IFACEMETHOD (GetQualityLevel )(_Out_ MF_QUALITY_LEVEL *peQualityLevel ); IFACEMETHOD (DropTime) (_In_ LONGLONG hnsAmountToDrop); // IMFQualityAdvise2 IFACEMETHOD (NotifyQualityEvent) (_In_opt_ IMFMediaEvent *pEvent, _Out_ DWORD *pdwFlags); // IMFGetService IFACEMETHOD (GetService) (_In_ REFGUID guidService, _In_ REFIID riid, _Out_ LPVOID *ppvObject); // Other public methods HRESULT Start(); HRESULT Stop(); HRESULT SetRate(float flRate); HRESULT Flush(); HRESULT Shutdown(); void ProcessSample(StspSampleHeader *pSampleHeader, IMFSample *pSample); void ProcessFormatChange(IMFMediaType *pMediaType); HRESULT SetActive(bool fActive); bool IsActive() const {return _fActive;} SourceState GetState() const {return _eSourceState;} DWORD GetId() const {return _dwId;} protected: CMediaStream(CMediaSource *pSource); ~CMediaStream(void); private: class CSourceLock; private: void Initialize(StspStreamDescription *pStreamDescription, Network::IBufferPacket *pAttributesBuffer); void DeliverSamples(); void SetSampleAttributes(StspSampleHeader *pSampleHeader, IMFSample *pSample); void HandleError(HRESULT hErrorCode); HRESULT CheckShutdown() const { if (_eSourceState == SourceState_Shutdown) { return MF_E_SHUTDOWN; } else { return S_OK; } } bool ShouldDropSample(IMFSample *pSample); void CleanSampleQueue(); void ResetDropTime(); private: long _cRef; // reference count SourceState _eSourceState; // Flag to indicate if Shutdown() method was called. ComPtr<CMediaSource> _spSource; // Media source ComPtr<IMFMediaEventQueue> _spEventQueue; // Event queue ComPtr<IMFStreamDescriptor> _spStreamDescriptor; // Stream descriptor ComPtrList<IUnknown> _samples; ComPtrList<IUnknown, true> _tokens; DWORD _dwId; bool _fActive; bool _fVideo; float _flRate; MF_QUALITY_DROP_MODE _eDropMode; bool _fDiscontinuity; bool _fDropTime; bool _fInitDropTime; bool _fWaitingForCleanPoint; LONGLONG _hnsStartDroppingAt; LONGLONG _hnsAmountToDrop; }; }}} // namespace Microsoft::Samples::SimpleCommunication
srinivashappy/Windows-universal-samples
Samples/SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/StspMediaStream.h
C
mit
4,872
/** * 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.contrib.failmon; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Calendar; /********************************************************** * This class represents objects that provide log parsing * functionality. Typically, such objects read log files line * by line and for each log entry they identify, they create a * corresponding EventRecord. In this way, disparate log files * can be merged using the uniform format of EventRecords and can, * thus, be processed in a uniform way. * **********************************************************/ public abstract class LogParser implements Monitored { File file; BufferedReader reader; String hostname; Object [] ips; String dateformat; String timeformat; private String firstLine; private long offset; /** * Create a parser that will read from the specified log file. * * @param fname the filename of the log file to be read */ public LogParser(String fname) { file = new File(fname); ParseState ps = PersistentState.getState(file.getAbsolutePath()); firstLine = ps.firstLine; offset = ps.offset; try { reader = new BufferedReader(new FileReader(file)); checkForRotation(); Environment.logInfo("Checked for rotation..."); reader.skip(offset); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } setNetworkProperties(); } protected void setNetworkProperties() { // determine hostname and ip addresses for the node try { // Get hostname hostname = InetAddress.getLocalHost().getCanonicalHostName(); // Get all associated ip addresses ips = InetAddress.getAllByName(hostname); } catch (UnknownHostException e) { e.printStackTrace(); } } /** * Insert all EventRecords that can be extracted for * the represented hardware component into a LocalStore. * * @param ls the LocalStore into which the EventRecords * are to be stored. */ public void monitor(LocalStore ls) { int in = 0; EventRecord er = null; Environment.logInfo("Started processing log..."); while ((er = getNext()) != null) { // Environment.logInfo("Processing log line:\t" + in++); if (er.isValid()) { ls.insert(er); } } PersistentState.updateState(file.getAbsolutePath(), firstLine, offset); PersistentState.writeState("conf/parsing.state"); } /** * Get an array of all EventRecords that can be extracted for * the represented hardware component. * * @return The array of EventRecords */ public EventRecord[] monitor() { ArrayList<EventRecord> recs = new ArrayList<EventRecord>(); EventRecord er; while ((er = getNext()) != null) recs.add(er); EventRecord[] T = new EventRecord[recs.size()]; return recs.toArray(T); } /** * Continue parsing the log file until a valid log entry is identified. * When one such entry is found, parse it and return a corresponding EventRecord. * * * @return The EventRecord corresponding to the next log entry */ public EventRecord getNext() { try { String line = reader.readLine(); if (line != null) { if (firstLine == null) firstLine = new String(line); offset += line.length() + 1; return parseLine(line); } } catch (IOException e) { e.printStackTrace(); } return null; } /** * Return the BufferedReader, that reads the log file * * @return The BufferedReader that reads the log file */ public BufferedReader getReader() { return reader; } /** * Check whether the log file has been rotated. If so, * start reading the file from the beginning. * */ public void checkForRotation() { try { BufferedReader probe = new BufferedReader(new FileReader(file.getAbsoluteFile())); if (firstLine == null || (!firstLine.equals(probe.readLine()))) { probe.close(); // start reading the file from the beginning reader.close(); reader = new BufferedReader(new FileReader(file.getAbsoluteFile())); firstLine = null; offset = 0; } } catch (IOException e) { e.printStackTrace(); } } /** * Parses one line of the log. If the line contains a valid * log entry, then an appropriate EventRecord is returned, after all * relevant fields have been parsed. * * @param line the log line to be parsed * * @return the EventRecord representing the log entry of the line. If * the line does not contain a valid log entry, then the EventRecord * returned has isValid() = false. When the end-of-file has been reached, * null is returned to the caller. */ abstract public EventRecord parseLine(String line) throws IOException; /** * Parse a date found in Hadoop log file. * * @return a Calendar representing the date */ abstract protected Calendar parseDate(String strDate, String strTime); }
ZhangXFeng/hadoop
src/hadoop-mapreduce1-project/src/contrib/failmon/src/java/org/apache/hadoop/contrib/failmon/LogParser.java
Java
apache-2.0
6,141
class Jq < Formula desc "Lightweight and flexible command-line JSON processor" homepage "https://stedolan.github.io/jq/" url "https://github.com/stedolan/jq/releases/download/jq-1.5/jq-1.5.tar.gz" sha256 "c4d2bfec6436341113419debf479d833692cc5cdab7eb0326b5a4d4fbe9f493c" bottle do cellar :any revision 1 sha256 "8529bc1edac66bdeec82afe80ce671b9d015b02959fe9f37efd2887fd975faf1" => :yosemite sha256 "89a32fb53e7f4330d6db84ba526133228189ea3ba3b15adf7fc743787c8ef645" => :mavericks sha256 "d817dec8745f52802b4ac2fbcd2a7a76a647b2000f43ba9a842f59a4363da55d" => :mountain_lion end head do url "https://github.com/stedolan/jq.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "oniguruma" # jq depends > 1.5 depends_on "bison" => :build # jq depends on bison > 2.5 def install system "autoreconf", "-iv" unless build.stable? system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end test do assert_equal "2\n", pipe_output("#{bin}/jq .bar", '{"foo":1, "bar":2}') end end
baldwicc/homebrew
Library/Formula/jq.rb
Ruby
bsd-2-clause
1,240
// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include -m64 /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,linux package unix const ( SYS_READ = 0 SYS_WRITE = 1 SYS_OPEN = 2 SYS_CLOSE = 3 SYS_STAT = 4 SYS_FSTAT = 5 SYS_LSTAT = 6 SYS_POLL = 7 SYS_LSEEK = 8 SYS_MMAP = 9 SYS_MPROTECT = 10 SYS_MUNMAP = 11 SYS_BRK = 12 SYS_RT_SIGACTION = 13 SYS_RT_SIGPROCMASK = 14 SYS_RT_SIGRETURN = 15 SYS_IOCTL = 16 SYS_PREAD64 = 17 SYS_PWRITE64 = 18 SYS_READV = 19 SYS_WRITEV = 20 SYS_ACCESS = 21 SYS_PIPE = 22 SYS_SELECT = 23 SYS_SCHED_YIELD = 24 SYS_MREMAP = 25 SYS_MSYNC = 26 SYS_MINCORE = 27 SYS_MADVISE = 28 SYS_SHMGET = 29 SYS_SHMAT = 30 SYS_SHMCTL = 31 SYS_DUP = 32 SYS_DUP2 = 33 SYS_PAUSE = 34 SYS_NANOSLEEP = 35 SYS_GETITIMER = 36 SYS_ALARM = 37 SYS_SETITIMER = 38 SYS_GETPID = 39 SYS_SENDFILE = 40 SYS_SOCKET = 41 SYS_CONNECT = 42 SYS_ACCEPT = 43 SYS_SENDTO = 44 SYS_RECVFROM = 45 SYS_SENDMSG = 46 SYS_RECVMSG = 47 SYS_SHUTDOWN = 48 SYS_BIND = 49 SYS_LISTEN = 50 SYS_GETSOCKNAME = 51 SYS_GETPEERNAME = 52 SYS_SOCKETPAIR = 53 SYS_SETSOCKOPT = 54 SYS_GETSOCKOPT = 55 SYS_CLONE = 56 SYS_FORK = 57 SYS_VFORK = 58 SYS_EXECVE = 59 SYS_EXIT = 60 SYS_WAIT4 = 61 SYS_KILL = 62 SYS_UNAME = 63 SYS_SEMGET = 64 SYS_SEMOP = 65 SYS_SEMCTL = 66 SYS_SHMDT = 67 SYS_MSGGET = 68 SYS_MSGSND = 69 SYS_MSGRCV = 70 SYS_MSGCTL = 71 SYS_FCNTL = 72 SYS_FLOCK = 73 SYS_FSYNC = 74 SYS_FDATASYNC = 75 SYS_TRUNCATE = 76 SYS_FTRUNCATE = 77 SYS_GETDENTS = 78 SYS_GETCWD = 79 SYS_CHDIR = 80 SYS_FCHDIR = 81 SYS_RENAME = 82 SYS_MKDIR = 83 SYS_RMDIR = 84 SYS_CREAT = 85 SYS_LINK = 86 SYS_UNLINK = 87 SYS_SYMLINK = 88 SYS_READLINK = 89 SYS_CHMOD = 90 SYS_FCHMOD = 91 SYS_CHOWN = 92 SYS_FCHOWN = 93 SYS_LCHOWN = 94 SYS_UMASK = 95 SYS_GETTIMEOFDAY = 96 SYS_GETRLIMIT = 97 SYS_GETRUSAGE = 98 SYS_SYSINFO = 99 SYS_TIMES = 100 SYS_PTRACE = 101 SYS_GETUID = 102 SYS_SYSLOG = 103 SYS_GETGID = 104 SYS_SETUID = 105 SYS_SETGID = 106 SYS_GETEUID = 107 SYS_GETEGID = 108 SYS_SETPGID = 109 SYS_GETPPID = 110 SYS_GETPGRP = 111 SYS_SETSID = 112 SYS_SETREUID = 113 SYS_SETREGID = 114 SYS_GETGROUPS = 115 SYS_SETGROUPS = 116 SYS_SETRESUID = 117 SYS_GETRESUID = 118 SYS_SETRESGID = 119 SYS_GETRESGID = 120 SYS_GETPGID = 121 SYS_SETFSUID = 122 SYS_SETFSGID = 123 SYS_GETSID = 124 SYS_CAPGET = 125 SYS_CAPSET = 126 SYS_RT_SIGPENDING = 127 SYS_RT_SIGTIMEDWAIT = 128 SYS_RT_SIGQUEUEINFO = 129 SYS_RT_SIGSUSPEND = 130 SYS_SIGALTSTACK = 131 SYS_UTIME = 132 SYS_MKNOD = 133 SYS_USELIB = 134 SYS_PERSONALITY = 135 SYS_USTAT = 136 SYS_STATFS = 137 SYS_FSTATFS = 138 SYS_SYSFS = 139 SYS_GETPRIORITY = 140 SYS_SETPRIORITY = 141 SYS_SCHED_SETPARAM = 142 SYS_SCHED_GETPARAM = 143 SYS_SCHED_SETSCHEDULER = 144 SYS_SCHED_GETSCHEDULER = 145 SYS_SCHED_GET_PRIORITY_MAX = 146 SYS_SCHED_GET_PRIORITY_MIN = 147 SYS_SCHED_RR_GET_INTERVAL = 148 SYS_MLOCK = 149 SYS_MUNLOCK = 150 SYS_MLOCKALL = 151 SYS_MUNLOCKALL = 152 SYS_VHANGUP = 153 SYS_MODIFY_LDT = 154 SYS_PIVOT_ROOT = 155 SYS__SYSCTL = 156 SYS_PRCTL = 157 SYS_ARCH_PRCTL = 158 SYS_ADJTIMEX = 159 SYS_SETRLIMIT = 160 SYS_CHROOT = 161 SYS_SYNC = 162 SYS_ACCT = 163 SYS_SETTIMEOFDAY = 164 SYS_MOUNT = 165 SYS_UMOUNT2 = 166 SYS_SWAPON = 167 SYS_SWAPOFF = 168 SYS_REBOOT = 169 SYS_SETHOSTNAME = 170 SYS_SETDOMAINNAME = 171 SYS_IOPL = 172 SYS_IOPERM = 173 SYS_CREATE_MODULE = 174 SYS_INIT_MODULE = 175 SYS_DELETE_MODULE = 176 SYS_GET_KERNEL_SYMS = 177 SYS_QUERY_MODULE = 178 SYS_QUOTACTL = 179 SYS_NFSSERVCTL = 180 SYS_GETPMSG = 181 SYS_PUTPMSG = 182 SYS_AFS_SYSCALL = 183 SYS_TUXCALL = 184 SYS_SECURITY = 185 SYS_GETTID = 186 SYS_READAHEAD = 187 SYS_SETXATTR = 188 SYS_LSETXATTR = 189 SYS_FSETXATTR = 190 SYS_GETXATTR = 191 SYS_LGETXATTR = 192 SYS_FGETXATTR = 193 SYS_LISTXATTR = 194 SYS_LLISTXATTR = 195 SYS_FLISTXATTR = 196 SYS_REMOVEXATTR = 197 SYS_LREMOVEXATTR = 198 SYS_FREMOVEXATTR = 199 SYS_TKILL = 200 SYS_TIME = 201 SYS_FUTEX = 202 SYS_SCHED_SETAFFINITY = 203 SYS_SCHED_GETAFFINITY = 204 SYS_SET_THREAD_AREA = 205 SYS_IO_SETUP = 206 SYS_IO_DESTROY = 207 SYS_IO_GETEVENTS = 208 SYS_IO_SUBMIT = 209 SYS_IO_CANCEL = 210 SYS_GET_THREAD_AREA = 211 SYS_LOOKUP_DCOOKIE = 212 SYS_EPOLL_CREATE = 213 SYS_EPOLL_CTL_OLD = 214 SYS_EPOLL_WAIT_OLD = 215 SYS_REMAP_FILE_PAGES = 216 SYS_GETDENTS64 = 217 SYS_SET_TID_ADDRESS = 218 SYS_RESTART_SYSCALL = 219 SYS_SEMTIMEDOP = 220 SYS_FADVISE64 = 221 SYS_TIMER_CREATE = 222 SYS_TIMER_SETTIME = 223 SYS_TIMER_GETTIME = 224 SYS_TIMER_GETOVERRUN = 225 SYS_TIMER_DELETE = 226 SYS_CLOCK_SETTIME = 227 SYS_CLOCK_GETTIME = 228 SYS_CLOCK_GETRES = 229 SYS_CLOCK_NANOSLEEP = 230 SYS_EXIT_GROUP = 231 SYS_EPOLL_WAIT = 232 SYS_EPOLL_CTL = 233 SYS_TGKILL = 234 SYS_UTIMES = 235 SYS_VSERVER = 236 SYS_MBIND = 237 SYS_SET_MEMPOLICY = 238 SYS_GET_MEMPOLICY = 239 SYS_MQ_OPEN = 240 SYS_MQ_UNLINK = 241 SYS_MQ_TIMEDSEND = 242 SYS_MQ_TIMEDRECEIVE = 243 SYS_MQ_NOTIFY = 244 SYS_MQ_GETSETATTR = 245 SYS_KEXEC_LOAD = 246 SYS_WAITID = 247 SYS_ADD_KEY = 248 SYS_REQUEST_KEY = 249 SYS_KEYCTL = 250 SYS_IOPRIO_SET = 251 SYS_IOPRIO_GET = 252 SYS_INOTIFY_INIT = 253 SYS_INOTIFY_ADD_WATCH = 254 SYS_INOTIFY_RM_WATCH = 255 SYS_MIGRATE_PAGES = 256 SYS_OPENAT = 257 SYS_MKDIRAT = 258 SYS_MKNODAT = 259 SYS_FCHOWNAT = 260 SYS_FUTIMESAT = 261 SYS_NEWFSTATAT = 262 SYS_UNLINKAT = 263 SYS_RENAMEAT = 264 SYS_LINKAT = 265 SYS_SYMLINKAT = 266 SYS_READLINKAT = 267 SYS_FCHMODAT = 268 SYS_FACCESSAT = 269 SYS_PSELECT6 = 270 SYS_PPOLL = 271 SYS_UNSHARE = 272 SYS_SET_ROBUST_LIST = 273 SYS_GET_ROBUST_LIST = 274 SYS_SPLICE = 275 SYS_TEE = 276 SYS_SYNC_FILE_RANGE = 277 SYS_VMSPLICE = 278 SYS_MOVE_PAGES = 279 SYS_UTIMENSAT = 280 SYS_EPOLL_PWAIT = 281 SYS_SIGNALFD = 282 SYS_TIMERFD_CREATE = 283 SYS_EVENTFD = 284 SYS_FALLOCATE = 285 SYS_TIMERFD_SETTIME = 286 SYS_TIMERFD_GETTIME = 287 SYS_ACCEPT4 = 288 SYS_SIGNALFD4 = 289 SYS_EVENTFD2 = 290 SYS_EPOLL_CREATE1 = 291 SYS_DUP3 = 292 SYS_PIPE2 = 293 SYS_INOTIFY_INIT1 = 294 SYS_PREADV = 295 SYS_PWRITEV = 296 SYS_RT_TGSIGQUEUEINFO = 297 SYS_PERF_EVENT_OPEN = 298 SYS_RECVMMSG = 299 SYS_FANOTIFY_INIT = 300 SYS_FANOTIFY_MARK = 301 SYS_PRLIMIT64 = 302 SYS_NAME_TO_HANDLE_AT = 303 SYS_OPEN_BY_HANDLE_AT = 304 SYS_CLOCK_ADJTIME = 305 SYS_SYNCFS = 306 SYS_SENDMMSG = 307 SYS_SETNS = 308 SYS_GETCPU = 309 SYS_PROCESS_VM_READV = 310 SYS_PROCESS_VM_WRITEV = 311 SYS_KCMP = 312 SYS_FINIT_MODULE = 313 SYS_SCHED_SETATTR = 314 SYS_SCHED_GETATTR = 315 SYS_RENAMEAT2 = 316 SYS_SECCOMP = 317 SYS_GETRANDOM = 318 SYS_MEMFD_CREATE = 319 SYS_KEXEC_FILE_LOAD = 320 SYS_BPF = 321 SYS_EXECVEAT = 322 SYS_USERFAULTFD = 323 SYS_MEMBARRIER = 324 SYS_MLOCK2 = 325 SYS_COPY_FILE_RANGE = 326 SYS_PREADV2 = 327 SYS_PWRITEV2 = 328 SYS_PKEY_MPROTECT = 329 SYS_PKEY_ALLOC = 330 SYS_PKEY_FREE = 331 SYS_STATX = 332 SYS_IO_PGETEVENTS = 333 SYS_RSEQ = 334 )
ooclab/otunnel
vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go
GO
mit
11,485
// +build !linux /* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package selinux // SELinuxEnabled always returns false on non-linux platforms. func SELinuxEnabled() bool { return false } // realSELinuxRunner is the NOP implementation of the SELinuxRunner interface. type realSELinuxRunner struct{} var _ SELinuxRunner = &realSELinuxRunner{} func (_ *realSELinuxRunner) Getfilecon(path string) (string, error) { return "", nil } // FileLabel returns the SELinux label for this path or returns an error. func SetFileLabel(path string, label string) error { return nil }
kubernetes/autoscaler
vertical-pod-autoscaler/e2e/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux_unsupported.go
GO
apache-2.0
1,101
/* * Copyright (C) 2007, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SQLTransaction_h #define SQLTransaction_h #if ENABLE(SQL_DATABASE) #include "AbstractSQLTransaction.h" #include "SQLCallbackWrapper.h" #include "SQLStatement.h" #include "SQLTransactionStateMachine.h" #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> namespace WebCore { class AbstractSQLTransactionBackend; class Database; class SQLError; class SQLStatementCallback; class SQLStatementErrorCallback; class SQLTransactionCallback; class SQLTransactionErrorCallback; class SQLValue; class VoidCallback; class SQLTransaction : public SQLTransactionStateMachine<SQLTransaction>, public AbstractSQLTransaction { public: static PassRefPtr<SQLTransaction> create(Database*, PassRefPtr<SQLTransactionCallback>, PassRefPtr<VoidCallback> successCallback, PassRefPtr<SQLTransactionErrorCallback>, bool readOnly); void performPendingCallback(); void executeSQL(const String& sqlStatement, const Vector<SQLValue>& arguments, PassRefPtr<SQLStatementCallback>, PassRefPtr<SQLStatementErrorCallback>, ExceptionCode&); Database* database() { return m_database.get(); } private: SQLTransaction(Database*, PassRefPtr<SQLTransactionCallback>, PassRefPtr<VoidCallback> successCallback, PassRefPtr<SQLTransactionErrorCallback>, bool readOnly); void clearCallbackWrappers(); // APIs called from the backend published via AbstractSQLTransaction: virtual void requestTransitToState(SQLTransactionState) OVERRIDE; virtual bool hasCallback() const OVERRIDE; virtual bool hasSuccessCallback() const OVERRIDE; virtual bool hasErrorCallback() const OVERRIDE; virtual void setBackend(AbstractSQLTransactionBackend*) OVERRIDE; // State Machine functions: virtual StateFunction stateFunctionFor(SQLTransactionState) OVERRIDE; bool computeNextStateAndCleanupIfNeeded(); // State functions: SQLTransactionState deliverTransactionCallback(); SQLTransactionState deliverTransactionErrorCallback(); SQLTransactionState deliverStatementCallback(); SQLTransactionState deliverQuotaIncreaseCallback(); SQLTransactionState deliverSuccessCallback(); SQLTransactionState unreachableState(); SQLTransactionState sendToBackendState(); SQLTransactionState nextStateForTransactionError(); RefPtr<Database> m_database; RefPtr<AbstractSQLTransactionBackend> m_backend; SQLCallbackWrapper<SQLTransactionCallback> m_callbackWrapper; SQLCallbackWrapper<VoidCallback> m_successCallbackWrapper; SQLCallbackWrapper<SQLTransactionErrorCallback> m_errorCallbackWrapper; bool m_executeSqlAllowed; RefPtr<SQLError> m_transactionError; bool m_readOnly; }; } // namespace WebCore #endif #endif // SQLTransaction_h
klim-iv/phantomjs-qt5
src/webkit/Source/WebCore/Modules/webdatabase/SQLTransaction.h
C
bsd-3-clause
4,326
/* * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 JSBase_h #define JSBase_h #ifndef __cplusplus #include <stdbool.h> #endif #ifdef __OBJC__ #import <Foundation/Foundation.h> #endif /* JavaScript engine interface */ /*! @typedef JSContextGroupRef A group that associates JavaScript contexts with one another. Contexts in the same group may share and exchange JavaScript objects. */ typedef const struct OpaqueJSContextGroup* JSContextGroupRef; /*! @typedef JSContextRef A JavaScript execution context. Holds the global object and other execution state. */ typedef const struct OpaqueJSContext* JSContextRef; /*! @typedef JSGlobalContextRef A global JavaScript execution context. A JSGlobalContext is a JSContext. */ typedef struct OpaqueJSContext* JSGlobalContextRef; /*! @typedef JSStringRef A UTF16 character buffer. The fundamental string representation in JavaScript. */ typedef struct OpaqueJSString* JSStringRef; /*! @typedef JSClassRef A JavaScript class. Used with JSObjectMake to construct objects with custom behavior. */ typedef struct OpaqueJSClass* JSClassRef; /*! @typedef JSPropertyNameArrayRef An array of JavaScript property names. */ typedef struct OpaqueJSPropertyNameArray* JSPropertyNameArrayRef; /*! @typedef JSPropertyNameAccumulatorRef An ordered set used to collect the names of a JavaScript object's properties. */ typedef struct OpaqueJSPropertyNameAccumulator* JSPropertyNameAccumulatorRef; /* JavaScript data types */ /*! @typedef JSValueRef A JavaScript value. The base type for all JavaScript values, and polymorphic functions on them. */ typedef const struct OpaqueJSValue* JSValueRef; /*! @typedef JSObjectRef A JavaScript object. A JSObject is a JSValue. */ typedef struct OpaqueJSValue* JSObjectRef; /* JavaScript symbol exports */ /* These rules should stay the same as in WebKit2/Shared/API/c/WKBase.h */ #undef JS_EXPORT #if defined(JS_NO_EXPORT) #define JS_EXPORT #elif defined(__GNUC__) && !defined(__CC_ARM) && !defined(__ARMCC__) #define JS_EXPORT __attribute__((visibility("default"))) #elif defined(WIN32) || defined(_WIN32) || defined(_WIN32_WCE) || defined(__CC_ARM) || defined(__ARMCC__) #if defined(BUILDING_JavaScriptCore) || defined(STATICALLY_LINKED_WITH_JavaScriptCore) #define JS_EXPORT __declspec(dllexport) #else #define JS_EXPORT __declspec(dllimport) #endif #else /* !defined(JS_NO_EXPORT) */ #define JS_EXPORT #endif /* defined(JS_NO_EXPORT) */ /* JS tests uses WTF but has no config.h, so we need to set the export defines here. */ #ifndef WTF_EXPORT_PRIVATE #define WTF_EXPORT_PRIVATE JS_EXPORT #endif #ifdef __cplusplus extern "C" { #endif /* Script Evaluation */ /*! @function JSEvaluateScript @abstract Evaluates a string of JavaScript. @param ctx The execution context to use. @param script A JSString containing the script to evaluate. @param thisObject The object to use as "this," or NULL to use the global object as "this." @param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions. @param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. @result The JSValue that results from evaluating script, or NULL if an exception is thrown. */ JS_EXPORT JSValueRef JSEvaluateScript(JSContextRef ctx, JSStringRef script, JSObjectRef thisObject, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception); /*! @function JSCheckScriptSyntax @abstract Checks for syntax errors in a string of JavaScript. @param ctx The execution context to use. @param script A JSString containing the script to check for syntax errors. @param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions. @param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. @param exception A pointer to a JSValueRef in which to store a syntax error exception, if any. Pass NULL if you do not care to store a syntax error exception. @result true if the script is syntactically correct, otherwise false. */ JS_EXPORT bool JSCheckScriptSyntax(JSContextRef ctx, JSStringRef script, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception); /*! @function JSGarbageCollect @abstract Performs a JavaScript garbage collection. @param ctx The execution context to use. @discussion JavaScript values that are on the machine stack, in a register, protected by JSValueProtect, set as the global object of an execution context, or reachable from any such value will not be collected. During JavaScript execution, you are not required to call this function; the JavaScript engine will garbage collect as needed. JavaScript values created within a context group are automatically destroyed when the last reference to the context group is released. */ JS_EXPORT void JSGarbageCollect(JSContextRef ctx); #ifdef __cplusplus } #endif /* Enable the Objective-C API for platforms with a modern runtime. */ #if !defined(JSC_OBJC_API_ENABLED) #define JSC_OBJC_API_ENABLED (defined(__clang__) && defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 && !defined(__i386__)) #endif #endif /* JSBase_h */
klim-iv/phantomjs-qt5
src/webkit/Source/JavaScriptCore/API/JSBase.h
C
bsd-3-clause
6,964
/* * rwlock3_t.c * * * -------------------------------------------------------------------------- * * Pthreads-win32 - POSIX Threads Library for Win32 * Copyright(C) 1998 John E. Bossom * Copyright(C) 1999,2005 Pthreads-win32 contributors * * Contact Email: rpj@callisto.canberra.edu.au * * The current list of contributors is contained * in the file CONTRIBUTORS included with the source * code distribution. The list can also be seen at the * following World Wide Web location: * http://sources.redhat.com/pthreads-win32/contributors.html * * 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 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * -------------------------------------------------------------------------- * * Declare a static rwlock object, timed-wrlock it, trywrlock it, * and then unlock it again. * * Depends on API functions: * pthread_rwlock_timedwrlock() * pthread_rwlock_trywrlock() * pthread_rwlock_unlock() */ #include "test.h" #include <sys/timeb.h> pthread_rwlock_t rwlock1 = PTHREAD_RWLOCK_INITIALIZER; static int washere = 0; void * func(void * arg) { assert(pthread_rwlock_trywrlock(&rwlock1) == EBUSY); washere = 1; return 0; } int main() { pthread_t t; struct timespec abstime = { 0, 0 }; PTW32_STRUCT_TIMEB currSysTime; const DWORD NANOSEC_PER_MILLISEC = 1000000; PTW32_FTIME(&currSysTime); abstime.tv_sec = (long)currSysTime.time; abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; abstime.tv_sec += 1; assert(pthread_rwlock_timedwrlock(&rwlock1, &abstime) == 0); assert(pthread_create(&t, NULL, func, NULL) == 0); Sleep(2000); assert(pthread_rwlock_unlock(&rwlock1) == 0); assert(washere == 1); return 0; }
vrtadmin/clamav-devel
win32/3rdparty/pthreads/tests/rwlock3_t.c
C
gpl-2.0
2,508
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.gen.entity; import java.util.List; import org.hibernate.validator.constraints.Length; import com.google.common.collect.Lists; import com.thinkgem.jeesite.common.persistence.DataEntity; import com.thinkgem.jeesite.common.utils.StringUtils; /** * 业务表Entity * @author ThinkGem * @version 2013-10-15 */ public class GenTable extends DataEntity<GenTable> { private static final long serialVersionUID = 1L; private String name; // 名称 private String comments; // 描述 private String className; // 实体类名称 private String parentTable; // 关联父表 private String parentTableFk; // 关联父表外键 private List<GenTableColumn> columnList = Lists.newArrayList(); // 表列 private String nameLike; // 按名称模糊查询 private List<String> pkList; // 当前表主键列表 private GenTable parent; // 父表对象 private List<GenTable> childList = Lists.newArrayList(); // 子表列表 public GenTable() { super(); } public GenTable(String id){ super(id); } @Length(min=1, max=200) public String getName() { return StringUtils.lowerCase(name); } public void setName(String name) { this.name = name; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getParentTable() { return StringUtils.lowerCase(parentTable); } public void setParentTable(String parentTable) { this.parentTable = parentTable; } public String getParentTableFk() { return StringUtils.lowerCase(parentTableFk); } public void setParentTableFk(String parentTableFk) { this.parentTableFk = parentTableFk; } public List<String> getPkList() { return pkList; } public void setPkList(List<String> pkList) { this.pkList = pkList; } public String getNameLike() { return nameLike; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public GenTable getParent() { return parent; } public void setParent(GenTable parent) { this.parent = parent; } public List<GenTableColumn> getColumnList() { return columnList; } public void setColumnList(List<GenTableColumn> columnList) { this.columnList = columnList; } public List<GenTable> getChildList() { return childList; } public void setChildList(List<GenTable> childList) { this.childList = childList; } /** * 获取列名和说明 * @return */ public String getNameAndComments() { return getName() + (comments == null ? "" : " : " + comments); } /** * 获取导入依赖包字符串 * @return */ public List<String> getImportList(){ List<String> importList = Lists.newArrayList(); // 引用列表 for (GenTableColumn column : getColumnList()){ if (column.getIsNotBaseField() || ("1".equals(column.getIsQuery()) && "between".equals(column.getQueryType()) && ("createDate".equals(column.getSimpleJavaField()) || "updateDate".equals(column.getSimpleJavaField())))){ // 导入类型依赖包, 如果类型中包含“.”,则需要导入引用。 if (StringUtils.indexOf(column.getJavaType(), ".") != -1 && !importList.contains(column.getJavaType())){ importList.add(column.getJavaType()); } } if (column.getIsNotBaseField()){ // 导入JSR303、Json等依赖包 for (String ann : column.getAnnotationList()){ if (!importList.contains(StringUtils.substringBeforeLast(ann, "("))){ importList.add(StringUtils.substringBeforeLast(ann, "(")); } } } } // 如果有子表,则需要导入List相关引用 if (getChildList() != null && getChildList().size() > 0){ if (!importList.contains("java.util.List")){ importList.add("java.util.List"); } if (!importList.contains("com.google.common.collect.Lists")){ importList.add("com.google.common.collect.Lists"); } } return importList; } /** * 是否存在父类 * @return */ public Boolean getParentExists(){ return parent != null && StringUtils.isNotBlank(parentTable) && StringUtils.isNotBlank(parentTableFk); } /** * 是否存在create_date列 * @return */ public Boolean getCreateDateExists(){ for (GenTableColumn c : columnList){ if ("create_date".equals(c.getName())){ return true; } } return false; } /** * 是否存在update_date列 * @return */ public Boolean getUpdateDateExists(){ for (GenTableColumn c : columnList){ if ("update_date".equals(c.getName())){ return true; } } return false; } /** * 是否存在del_flag列 * @return */ public Boolean getDelFlagExists(){ for (GenTableColumn c : columnList){ if ("del_flag".equals(c.getName())){ return true; } } return false; } }
southwolf/jeesite
src/main/java/com/thinkgem/jeesite/modules/gen/entity/GenTable.java
Java
apache-2.0
4,996
<!--- # license: 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. --> # cordova-plugin-device-orientation [![Build Status](https://travis-ci.org/apache/cordova-plugin-device-orientation.svg)](https://travis-ci.org/apache/cordova-plugin-device-orientation) 這個外掛程式提供了對設備的指南針的訪問。 羅盤是感應器,可檢測的方向或設備通常指從設備的頂部的標題。 它的措施中從 0 度到 359.99,其中 0 是北部的標題。 訪問是通過一個全球 `navigator.compass` 物件。 雖然該物件附加到全球範圍內 `導航器`,它不可用直到 `deviceready` 事件之後。 document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { console.log(navigator.compass); } ## 安裝 cordova plugin add cordova-plugin-device-orientation ## 支援的平臺 * 亞馬遜火 OS * Android 系統 * 黑莓 10 * 瀏覽器 * 火狐瀏覽器作業系統 * iOS * Tizen * Windows Phone 7 和第 8 (如果在硬體中可用) * Windows 8 ## 方法 * navigator.compass.getCurrentHeading * navigator.compass.watchHeading * navigator.compass.clearWatch ## navigator.compass.getCurrentHeading 獲取當前的羅經航向。羅經航向被經由一個 `CompassHeading` 物件,使用 `compassSuccess` 回呼函數。 navigator.compass.getCurrentHeading(compassSuccess, compassError); ### 示例 function onSuccess(heading) { alert('Heading: ' + heading.magneticHeading); }; function onError(error) { alert('CompassError: ' + error.code); }; navigator.compass.getCurrentHeading(onSuccess, onError); ## navigator.compass.watchHeading 獲取設備的當前標題的間隔時間定期。檢索到的標題,每次執行 `headingSuccess` 回呼函數。 返回的表 ID 引用的指南針手錶的時間間隔。表 ID 可用於與 `navigator.compass.clearWatch` 停止看 navigator.compass。 var watchID = navigator.compass.watchHeading(compassSuccess, compassError, [compassOptions]); `compassOptions` 可能包含以下項: * **frequency**: 經常如何檢索以毫秒為單位的羅經航向。*(Number)*(預設值: 100) * **filter**: 啟動 watchHeading 成功回檔所需的度的變化。當設置此值時,**frequency**將被忽略。*(Number)* ### 示例 function onSuccess(heading) { var element = document.getElementById('heading'); element.innerHTML = 'Heading: ' + heading.magneticHeading; }; function onError(compassError) { alert('Compass error: ' + compassError.code); }; var options = { frequency: 3000 }; // Update every 3 seconds var watchID = navigator.compass.watchHeading(onSuccess, onError, options); ### 瀏覽器的怪癖 隨機生成當前標題的值,以便類比羅盤。 ### iOS 的怪癖 只有一個 `watchHeading` 可以在 iOS 中一次的效果。 如果 `watchHeading` 使用一個篩選器,致電 `getCurrentHeading` 或 `watchHeading` 使用現有的篩選器值來指定標題的變化。 帶有篩選器看標題的變化是與時間間隔比效率更高。 ### 亞馬遜火 OS 怪癖 * `filter`不受支援。 ### Android 的怪癖 * 不支援`filter`. ### 火狐瀏覽器作業系統的怪癖 * 不支援`filter`. ### Tizen 怪癖 * 不支援`filter`. ### Windows Phone 7 和 8 怪癖 * 不支援`filter`. ## navigator.compass.clearWatch 別看手錶 ID 參數所引用的指南針。 navigator.compass.clearWatch(watchID); * **watchID**: 由返回的 ID`navigator.compass.watchHeading`. ### 示例 var watchID = navigator.compass.watchHeading(onSuccess, onError, options); // ... later on ... navigator.compass.clearWatch(watchID); ## CompassHeading `CompassSuccess` 回呼函數返回一個 `CompassHeading` 物件。 ### 屬性 * **magneticHeading**: 在某一時刻在時間中從 0-359.99 度的標題。*(人數)* * **trueHeading**: 在某一時刻的時間與地理北極在 0-359.99 度標題。 負值表示不能確定真正的標題。 *(人數)* * **headingAccuracy**: 中度報告的標題和真正標題之間的偏差。*(人數)* * **timestamp**: 本項決定在其中的時間。*(毫秒)* ### 亞馬遜火 OS 怪癖 * `trueHeading`不受支援,但報告相同的值`magneticHeading` * `headingAccuracy`是始終為 0 因為有沒有區別 `magneticHeading` 和`trueHeading` ### Android 的怪癖 * `trueHeading`屬性不受支援,但報告相同的值`magneticHeading`. * `headingAccuracy`屬性始終是 0 因為有沒有區別 `magneticHeading` 和`trueHeading`. ### 火狐瀏覽器作業系統的怪癖 * `trueHeading`屬性不受支援,但報告相同的值`magneticHeading`. * `headingAccuracy`屬性始終是 0 因為有沒有區別 `magneticHeading` 和`trueHeading`. ### iOS 的怪癖 * `trueHeading`屬性只返回位置服務通過以下方式啟用`navigator.geolocation.watchLocation()`. ## CompassError 當發生錯誤時,`compassError` 回呼函數情況下會返回一個 `CompassError` 物件。 ### 屬性 * **code**: 下面列出的預定義的錯誤代碼之一。 ### 常量 * `CompassError.COMPASS_INTERNAL_ERR` * `CompassError.COMPASS_NOT_SUPPORTED`
circular-code/ImageStream
www/plugins/cordova-plugin-device-orientation/doc/zh/README.md
Markdown
mit
6,255
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example15</title> <script src="../../../angular.min.js"></script> <script src="script.js"></script> </head> <body ng-app="docsScopeProblemExample"> <div ng-controller="NaomiController"> <my-customer></my-customer> </div> <hr> <div ng-controller="IgorController"> <my-customer></my-customer> </div> </body> </html>
orYoffe/wordpress
wp-content/themes/new_theme/js/libs/angular-1.4.1/docs/examples/example-example15/index.html
HTML
gpl-2.0
426
#ifndef EFSW_MUTEXIMPLWIN_HPP #define EFSW_MUTEXIMPLWIN_HPP #include <efsw/base.hpp> #if EFSW_PLATFORM == EFSW_PLATFORM_WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> namespace efsw { namespace Platform { class MutexImpl { public: MutexImpl(); ~MutexImpl(); void lock(); void unlock(); private: CRITICAL_SECTION mMutex; }; }} #endif #endif
diegostamigni/efsw
src/efsw/platform/win/MutexImpl.hpp
C++
mit
409
/** * 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; /** * An <a href="http://camel.apache.org/expression.html">expression</a> * provides a plugin strategy for evaluating expressions on a message exchange to support things like * <a href="http://camel.apache.org/scripting-languages.html">scripting languages</a>, * <a href="http://camel.apache.org/xquery.html">XQuery</a> * or <a href="http://camel.apache.org/sql.html">SQL</a> as well * as any arbitrary Java expression. * * @version */ public interface Expression { /** * Returns the value of the expression on the given exchange * * @param exchange the message exchange on which to evaluate the expression * @param type the expected type of the evaluation result * @return the value of the expression */ <T> T evaluate(Exchange exchange, Class<T> type); }
YMartsynkevych/camel
camel-core/src/main/java/org/apache/camel/Expression.java
Java
apache-2.0
1,637
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package clientauth_test import ( "io/ioutil" "os" "reflect" "testing" "github.com/GoogleCloudPlatform/kubernetes/pkg/clientauth" ) func TestLoadFromFile(t *testing.T) { loadAuthInfoTests := []struct { authData string authInfo *clientauth.Info expectErr bool }{ { `{"user": "user", "password": "pass"}`, &clientauth.Info{User: "user", Password: "pass"}, false, }, { "", nil, true, }, } for _, loadAuthInfoTest := range loadAuthInfoTests { tt := loadAuthInfoTest aifile, err := ioutil.TempFile("", "testAuthInfo") if err != nil { t.Errorf("Unexpected error: %v", err) } if tt.authData != "missing" { defer os.Remove(aifile.Name()) defer aifile.Close() _, err = aifile.WriteString(tt.authData) if err != nil { t.Errorf("Unexpected error: %v", err) } } else { aifile.Close() os.Remove(aifile.Name()) } authInfo, err := clientauth.LoadFromFile(aifile.Name()) gotErr := err != nil if gotErr != tt.expectErr { t.Errorf("expected errorness: %v, actual errorness: %v", tt.expectErr, gotErr) } if !reflect.DeepEqual(authInfo, tt.authInfo) { t.Errorf("Expected %v, got %v", tt.authInfo, authInfo) } } }
pietern/kubernetes
pkg/clientauth/clientauth_test.go
GO
apache-2.0
1,784
/* * Copyright (C) 2002 Roman Zippel <zippel@linux-m68k.org> * Released under the terms of the GNU GPL v2.0. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define LKC_DIRECT_LINK #include "lkc.h" #define DEBUG_EXPR 0 struct expr *expr_alloc_symbol(struct symbol *sym) { struct expr *e = malloc(sizeof(*e)); memset(e, 0, sizeof(*e)); e->type = E_SYMBOL; e->left.sym = sym; return e; } struct expr *expr_alloc_one(enum expr_type type, struct expr *ce) { struct expr *e = malloc(sizeof(*e)); memset(e, 0, sizeof(*e)); e->type = type; e->left.expr = ce; return e; } struct expr *expr_alloc_two(enum expr_type type, struct expr *e1, struct expr *e2) { struct expr *e = malloc(sizeof(*e)); memset(e, 0, sizeof(*e)); e->type = type; e->left.expr = e1; e->right.expr = e2; return e; } struct expr *expr_alloc_comp(enum expr_type type, struct symbol *s1, struct symbol *s2) { struct expr *e = malloc(sizeof(*e)); memset(e, 0, sizeof(*e)); e->type = type; e->left.sym = s1; e->right.sym = s2; return e; } struct expr *expr_alloc_and(struct expr *e1, struct expr *e2) { if (!e1) return e2; return e2 ? expr_alloc_two(E_AND, e1, e2) : e1; } struct expr *expr_alloc_or(struct expr *e1, struct expr *e2) { if (!e1) return e2; return e2 ? expr_alloc_two(E_OR, e1, e2) : e1; } struct expr *expr_copy(struct expr *org) { struct expr *e; if (!org) return NULL; e = malloc(sizeof(*org)); memcpy(e, org, sizeof(*org)); switch (org->type) { case E_SYMBOL: e->left = org->left; break; case E_NOT: e->left.expr = expr_copy(org->left.expr); break; case E_EQUAL: case E_UNEQUAL: e->left.sym = org->left.sym; e->right.sym = org->right.sym; break; case E_AND: case E_OR: case E_CHOICE: e->left.expr = expr_copy(org->left.expr); e->right.expr = expr_copy(org->right.expr); break; default: printf("can't copy type %d\n", e->type); free(e); e = NULL; break; } return e; } void expr_free(struct expr *e) { if (!e) return; switch (e->type) { case E_SYMBOL: break; case E_NOT: expr_free(e->left.expr); return; case E_EQUAL: case E_UNEQUAL: break; case E_OR: case E_AND: expr_free(e->left.expr); expr_free(e->right.expr); break; default: printf("how to free type %d?\n", e->type); break; } free(e); } static int trans_count; #define e1 (*ep1) #define e2 (*ep2) static void __expr_eliminate_eq(enum expr_type type, struct expr **ep1, struct expr **ep2) { if (e1->type == type) { __expr_eliminate_eq(type, &e1->left.expr, &e2); __expr_eliminate_eq(type, &e1->right.expr, &e2); return; } if (e2->type == type) { __expr_eliminate_eq(type, &e1, &e2->left.expr); __expr_eliminate_eq(type, &e1, &e2->right.expr); return; } if (e1->type == E_SYMBOL && e2->type == E_SYMBOL && e1->left.sym == e2->left.sym && (e1->left.sym == &symbol_yes || e1->left.sym == &symbol_no)) return; if (!expr_eq(e1, e2)) return; trans_count++; expr_free(e1); expr_free(e2); switch (type) { case E_OR: e1 = expr_alloc_symbol(&symbol_no); e2 = expr_alloc_symbol(&symbol_no); break; case E_AND: e1 = expr_alloc_symbol(&symbol_yes); e2 = expr_alloc_symbol(&symbol_yes); break; default: ; } } void expr_eliminate_eq(struct expr **ep1, struct expr **ep2) { if (!e1 || !e2) return; switch (e1->type) { case E_OR: case E_AND: __expr_eliminate_eq(e1->type, ep1, ep2); default: ; } if (e1->type != e2->type) switch (e2->type) { case E_OR: case E_AND: __expr_eliminate_eq(e2->type, ep1, ep2); default: ; } e1 = expr_eliminate_yn(e1); e2 = expr_eliminate_yn(e2); } #undef e1 #undef e2 int expr_eq(struct expr *e1, struct expr *e2) { int res, old_count; if (e1->type != e2->type) return 0; switch (e1->type) { case E_EQUAL: case E_UNEQUAL: return e1->left.sym == e2->left.sym && e1->right.sym == e2->right.sym; case E_SYMBOL: return e1->left.sym == e2->left.sym; case E_NOT: return expr_eq(e1->left.expr, e2->left.expr); case E_AND: case E_OR: e1 = expr_copy(e1); e2 = expr_copy(e2); old_count = trans_count; expr_eliminate_eq(&e1, &e2); res = (e1->type == E_SYMBOL && e2->type == E_SYMBOL && e1->left.sym == e2->left.sym); expr_free(e1); expr_free(e2); trans_count = old_count; return res; case E_CHOICE: case E_RANGE: case E_NONE: /* panic */; } if (DEBUG_EXPR) { expr_fprint(e1, stdout); printf(" = "); expr_fprint(e2, stdout); printf(" ?\n"); } return 0; } struct expr *expr_eliminate_yn(struct expr *e) { struct expr *tmp; if (e) switch (e->type) { case E_AND: e->left.expr = expr_eliminate_yn(e->left.expr); e->right.expr = expr_eliminate_yn(e->right.expr); if (e->left.expr->type == E_SYMBOL) { if (e->left.expr->left.sym == &symbol_no) { expr_free(e->left.expr); expr_free(e->right.expr); e->type = E_SYMBOL; e->left.sym = &symbol_no; e->right.expr = NULL; return e; } else if (e->left.expr->left.sym == &symbol_yes) { free(e->left.expr); tmp = e->right.expr; *e = *(e->right.expr); free(tmp); return e; } } if (e->right.expr->type == E_SYMBOL) { if (e->right.expr->left.sym == &symbol_no) { expr_free(e->left.expr); expr_free(e->right.expr); e->type = E_SYMBOL; e->left.sym = &symbol_no; e->right.expr = NULL; return e; } else if (e->right.expr->left.sym == &symbol_yes) { free(e->right.expr); tmp = e->left.expr; *e = *(e->left.expr); free(tmp); return e; } } break; case E_OR: e->left.expr = expr_eliminate_yn(e->left.expr); e->right.expr = expr_eliminate_yn(e->right.expr); if (e->left.expr->type == E_SYMBOL) { if (e->left.expr->left.sym == &symbol_no) { free(e->left.expr); tmp = e->right.expr; *e = *(e->right.expr); free(tmp); return e; } else if (e->left.expr->left.sym == &symbol_yes) { expr_free(e->left.expr); expr_free(e->right.expr); e->type = E_SYMBOL; e->left.sym = &symbol_yes; e->right.expr = NULL; return e; } } if (e->right.expr->type == E_SYMBOL) { if (e->right.expr->left.sym == &symbol_no) { free(e->right.expr); tmp = e->left.expr; *e = *(e->left.expr); free(tmp); return e; } else if (e->right.expr->left.sym == &symbol_yes) { expr_free(e->left.expr); expr_free(e->right.expr); e->type = E_SYMBOL; e->left.sym = &symbol_yes; e->right.expr = NULL; return e; } } break; default: ; } return e; } /* * bool FOO!=n => FOO */ struct expr *expr_trans_bool(struct expr *e) { if (!e) return NULL; switch (e->type) { case E_AND: case E_OR: case E_NOT: e->left.expr = expr_trans_bool(e->left.expr); e->right.expr = expr_trans_bool(e->right.expr); break; case E_UNEQUAL: // FOO!=n -> FOO if (e->left.sym->type == S_TRISTATE) { if (e->right.sym == &symbol_no) { e->type = E_SYMBOL; e->right.sym = NULL; } } break; default: ; } return e; } /* * e1 || e2 -> ? */ static struct expr *expr_join_or(struct expr *e1, struct expr *e2) { struct expr *tmp; struct symbol *sym1, *sym2; if (expr_eq(e1, e2)) return expr_copy(e1); if (e1->type != E_EQUAL && e1->type != E_UNEQUAL && e1->type != E_SYMBOL && e1->type != E_NOT) return NULL; if (e2->type != E_EQUAL && e2->type != E_UNEQUAL && e2->type != E_SYMBOL && e2->type != E_NOT) return NULL; if (e1->type == E_NOT) { tmp = e1->left.expr; if (tmp->type != E_EQUAL && tmp->type != E_UNEQUAL && tmp->type != E_SYMBOL) return NULL; sym1 = tmp->left.sym; } else sym1 = e1->left.sym; if (e2->type == E_NOT) { if (e2->left.expr->type != E_SYMBOL) return NULL; sym2 = e2->left.expr->left.sym; } else sym2 = e2->left.sym; if (sym1 != sym2) return NULL; if (sym1->type != S_BOOLEAN && sym1->type != S_TRISTATE) return NULL; if (sym1->type == S_TRISTATE) { if (e1->type == E_EQUAL && e2->type == E_EQUAL && ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_mod) || (e1->right.sym == &symbol_mod && e2->right.sym == &symbol_yes))) { // (a='y') || (a='m') -> (a!='n') return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_no); } if (e1->type == E_EQUAL && e2->type == E_EQUAL && ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_no) || (e1->right.sym == &symbol_no && e2->right.sym == &symbol_yes))) { // (a='y') || (a='n') -> (a!='m') return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_mod); } if (e1->type == E_EQUAL && e2->type == E_EQUAL && ((e1->right.sym == &symbol_mod && e2->right.sym == &symbol_no) || (e1->right.sym == &symbol_no && e2->right.sym == &symbol_mod))) { // (a='m') || (a='n') -> (a!='y') return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_yes); } } if (sym1->type == S_BOOLEAN && sym1 == sym2) { if ((e1->type == E_NOT && e1->left.expr->type == E_SYMBOL && e2->type == E_SYMBOL) || (e2->type == E_NOT && e2->left.expr->type == E_SYMBOL && e1->type == E_SYMBOL)) return expr_alloc_symbol(&symbol_yes); } if (DEBUG_EXPR) { printf("optimize ("); expr_fprint(e1, stdout); printf(") || ("); expr_fprint(e2, stdout); printf(")?\n"); } return NULL; } static struct expr *expr_join_and(struct expr *e1, struct expr *e2) { struct expr *tmp; struct symbol *sym1, *sym2; if (expr_eq(e1, e2)) return expr_copy(e1); if (e1->type != E_EQUAL && e1->type != E_UNEQUAL && e1->type != E_SYMBOL && e1->type != E_NOT) return NULL; if (e2->type != E_EQUAL && e2->type != E_UNEQUAL && e2->type != E_SYMBOL && e2->type != E_NOT) return NULL; if (e1->type == E_NOT) { tmp = e1->left.expr; if (tmp->type != E_EQUAL && tmp->type != E_UNEQUAL && tmp->type != E_SYMBOL) return NULL; sym1 = tmp->left.sym; } else sym1 = e1->left.sym; if (e2->type == E_NOT) { if (e2->left.expr->type != E_SYMBOL) return NULL; sym2 = e2->left.expr->left.sym; } else sym2 = e2->left.sym; if (sym1 != sym2) return NULL; if (sym1->type != S_BOOLEAN && sym1->type != S_TRISTATE) return NULL; if ((e1->type == E_SYMBOL && e2->type == E_EQUAL && e2->right.sym == &symbol_yes) || (e2->type == E_SYMBOL && e1->type == E_EQUAL && e1->right.sym == &symbol_yes)) // (a) && (a='y') -> (a='y') return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes); if ((e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_no) || (e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_no)) // (a) && (a!='n') -> (a) return expr_alloc_symbol(sym1); if ((e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_mod) || (e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_mod)) // (a) && (a!='m') -> (a='y') return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes); if (sym1->type == S_TRISTATE) { if (e1->type == E_EQUAL && e2->type == E_UNEQUAL) { // (a='b') && (a!='c') -> 'b'='c' ? 'n' : a='b' sym2 = e1->right.sym; if ((e2->right.sym->flags & SYMBOL_CONST) && (sym2->flags & SYMBOL_CONST)) return sym2 != e2->right.sym ? expr_alloc_comp(E_EQUAL, sym1, sym2) : expr_alloc_symbol(&symbol_no); } if (e1->type == E_UNEQUAL && e2->type == E_EQUAL) { // (a='b') && (a!='c') -> 'b'='c' ? 'n' : a='b' sym2 = e2->right.sym; if ((e1->right.sym->flags & SYMBOL_CONST) && (sym2->flags & SYMBOL_CONST)) return sym2 != e1->right.sym ? expr_alloc_comp(E_EQUAL, sym1, sym2) : expr_alloc_symbol(&symbol_no); } if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL && ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_no) || (e1->right.sym == &symbol_no && e2->right.sym == &symbol_yes))) // (a!='y') && (a!='n') -> (a='m') return expr_alloc_comp(E_EQUAL, sym1, &symbol_mod); if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL && ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_mod) || (e1->right.sym == &symbol_mod && e2->right.sym == &symbol_yes))) // (a!='y') && (a!='m') -> (a='n') return expr_alloc_comp(E_EQUAL, sym1, &symbol_no); if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL && ((e1->right.sym == &symbol_mod && e2->right.sym == &symbol_no) || (e1->right.sym == &symbol_no && e2->right.sym == &symbol_mod))) // (a!='m') && (a!='n') -> (a='m') return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes); if ((e1->type == E_SYMBOL && e2->type == E_EQUAL && e2->right.sym == &symbol_mod) || (e2->type == E_SYMBOL && e1->type == E_EQUAL && e1->right.sym == &symbol_mod) || (e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_yes) || (e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_yes)) return NULL; } if (DEBUG_EXPR) { printf("optimize ("); expr_fprint(e1, stdout); printf(") && ("); expr_fprint(e2, stdout); printf(")?\n"); } return NULL; } static void expr_eliminate_dups1(enum expr_type type, struct expr **ep1, struct expr **ep2) { #define e1 (*ep1) #define e2 (*ep2) struct expr *tmp; if (e1->type == type) { expr_eliminate_dups1(type, &e1->left.expr, &e2); expr_eliminate_dups1(type, &e1->right.expr, &e2); return; } if (e2->type == type) { expr_eliminate_dups1(type, &e1, &e2->left.expr); expr_eliminate_dups1(type, &e1, &e2->right.expr); return; } if (e1 == e2) return; switch (e1->type) { case E_OR: case E_AND: expr_eliminate_dups1(e1->type, &e1, &e1); default: ; } switch (type) { case E_OR: tmp = expr_join_or(e1, e2); if (tmp) { expr_free(e1); expr_free(e2); e1 = expr_alloc_symbol(&symbol_no); e2 = tmp; trans_count++; } break; case E_AND: tmp = expr_join_and(e1, e2); if (tmp) { expr_free(e1); expr_free(e2); e1 = expr_alloc_symbol(&symbol_yes); e2 = tmp; trans_count++; } break; default: ; } #undef e1 #undef e2 } static void expr_eliminate_dups2(enum expr_type type, struct expr **ep1, struct expr **ep2) { #define e1 (*ep1) #define e2 (*ep2) struct expr *tmp, *tmp1, *tmp2; if (e1->type == type) { expr_eliminate_dups2(type, &e1->left.expr, &e2); expr_eliminate_dups2(type, &e1->right.expr, &e2); return; } if (e2->type == type) { expr_eliminate_dups2(type, &e1, &e2->left.expr); expr_eliminate_dups2(type, &e1, &e2->right.expr); } if (e1 == e2) return; switch (e1->type) { case E_OR: expr_eliminate_dups2(e1->type, &e1, &e1); // (FOO || BAR) && (!FOO && !BAR) -> n tmp1 = expr_transform(expr_alloc_one(E_NOT, expr_copy(e1))); tmp2 = expr_copy(e2); tmp = expr_extract_eq_and(&tmp1, &tmp2); if (expr_is_yes(tmp1)) { expr_free(e1); e1 = expr_alloc_symbol(&symbol_no); trans_count++; } expr_free(tmp2); expr_free(tmp1); expr_free(tmp); break; case E_AND: expr_eliminate_dups2(e1->type, &e1, &e1); // (FOO && BAR) || (!FOO || !BAR) -> y tmp1 = expr_transform(expr_alloc_one(E_NOT, expr_copy(e1))); tmp2 = expr_copy(e2); tmp = expr_extract_eq_or(&tmp1, &tmp2); if (expr_is_no(tmp1)) { expr_free(e1); e1 = expr_alloc_symbol(&symbol_yes); trans_count++; } expr_free(tmp2); expr_free(tmp1); expr_free(tmp); break; default: ; } #undef e1 #undef e2 } struct expr *expr_eliminate_dups(struct expr *e) { int oldcount; if (!e) return e; oldcount = trans_count; while (1) { trans_count = 0; switch (e->type) { case E_OR: case E_AND: expr_eliminate_dups1(e->type, &e, &e); expr_eliminate_dups2(e->type, &e, &e); default: ; } if (!trans_count) break; e = expr_eliminate_yn(e); } trans_count = oldcount; return e; } struct expr *expr_transform(struct expr *e) { struct expr *tmp; if (!e) return NULL; switch (e->type) { case E_EQUAL: case E_UNEQUAL: case E_SYMBOL: case E_CHOICE: break; default: e->left.expr = expr_transform(e->left.expr); e->right.expr = expr_transform(e->right.expr); } switch (e->type) { case E_EQUAL: if (e->left.sym->type != S_BOOLEAN) break; if (e->right.sym == &symbol_no) { e->type = E_NOT; e->left.expr = expr_alloc_symbol(e->left.sym); e->right.sym = NULL; break; } if (e->right.sym == &symbol_mod) { printf("boolean symbol %s tested for 'm'? test forced to 'n'\n", e->left.sym->name); e->type = E_SYMBOL; e->left.sym = &symbol_no; e->right.sym = NULL; break; } if (e->right.sym == &symbol_yes) { e->type = E_SYMBOL; e->right.sym = NULL; break; } break; case E_UNEQUAL: if (e->left.sym->type != S_BOOLEAN) break; if (e->right.sym == &symbol_no) { e->type = E_SYMBOL; e->right.sym = NULL; break; } if (e->right.sym == &symbol_mod) { printf("boolean symbol %s tested for 'm'? test forced to 'y'\n", e->left.sym->name); e->type = E_SYMBOL; e->left.sym = &symbol_yes; e->right.sym = NULL; break; } if (e->right.sym == &symbol_yes) { e->type = E_NOT; e->left.expr = expr_alloc_symbol(e->left.sym); e->right.sym = NULL; break; } break; case E_NOT: switch (e->left.expr->type) { case E_NOT: // !!a -> a tmp = e->left.expr->left.expr; free(e->left.expr); free(e); e = tmp; e = expr_transform(e); break; case E_EQUAL: case E_UNEQUAL: // !a='x' -> a!='x' tmp = e->left.expr; free(e); e = tmp; e->type = e->type == E_EQUAL ? E_UNEQUAL : E_EQUAL; break; case E_OR: // !(a || b) -> !a && !b tmp = e->left.expr; e->type = E_AND; e->right.expr = expr_alloc_one(E_NOT, tmp->right.expr); tmp->type = E_NOT; tmp->right.expr = NULL; e = expr_transform(e); break; case E_AND: // !(a && b) -> !a || !b tmp = e->left.expr; e->type = E_OR; e->right.expr = expr_alloc_one(E_NOT, tmp->right.expr); tmp->type = E_NOT; tmp->right.expr = NULL; e = expr_transform(e); break; case E_SYMBOL: if (e->left.expr->left.sym == &symbol_yes) { // !'y' -> 'n' tmp = e->left.expr; free(e); e = tmp; e->type = E_SYMBOL; e->left.sym = &symbol_no; break; } if (e->left.expr->left.sym == &symbol_mod) { // !'m' -> 'm' tmp = e->left.expr; free(e); e = tmp; e->type = E_SYMBOL; e->left.sym = &symbol_mod; break; } if (e->left.expr->left.sym == &symbol_no) { // !'n' -> 'y' tmp = e->left.expr; free(e); e = tmp; e->type = E_SYMBOL; e->left.sym = &symbol_yes; break; } break; default: ; } break; default: ; } return e; } int expr_contains_symbol(struct expr *dep, struct symbol *sym) { if (!dep) return 0; switch (dep->type) { case E_AND: case E_OR: return expr_contains_symbol(dep->left.expr, sym) || expr_contains_symbol(dep->right.expr, sym); case E_SYMBOL: return dep->left.sym == sym; case E_EQUAL: case E_UNEQUAL: return dep->left.sym == sym || dep->right.sym == sym; case E_NOT: return expr_contains_symbol(dep->left.expr, sym); default: ; } return 0; } bool expr_depends_symbol(struct expr *dep, struct symbol *sym) { if (!dep) return false; switch (dep->type) { case E_AND: return expr_depends_symbol(dep->left.expr, sym) || expr_depends_symbol(dep->right.expr, sym); case E_SYMBOL: return dep->left.sym == sym; case E_EQUAL: if (dep->left.sym == sym) { if (dep->right.sym == &symbol_yes || dep->right.sym == &symbol_mod) return true; } break; case E_UNEQUAL: if (dep->left.sym == sym) { if (dep->right.sym == &symbol_no) return true; } break; default: ; } return false; } struct expr *expr_extract_eq_and(struct expr **ep1, struct expr **ep2) { struct expr *tmp = NULL; expr_extract_eq(E_AND, &tmp, ep1, ep2); if (tmp) { *ep1 = expr_eliminate_yn(*ep1); *ep2 = expr_eliminate_yn(*ep2); } return tmp; } struct expr *expr_extract_eq_or(struct expr **ep1, struct expr **ep2) { struct expr *tmp = NULL; expr_extract_eq(E_OR, &tmp, ep1, ep2); if (tmp) { *ep1 = expr_eliminate_yn(*ep1); *ep2 = expr_eliminate_yn(*ep2); } return tmp; } void expr_extract_eq(enum expr_type type, struct expr **ep, struct expr **ep1, struct expr **ep2) { #define e1 (*ep1) #define e2 (*ep2) if (e1->type == type) { expr_extract_eq(type, ep, &e1->left.expr, &e2); expr_extract_eq(type, ep, &e1->right.expr, &e2); return; } if (e2->type == type) { expr_extract_eq(type, ep, ep1, &e2->left.expr); expr_extract_eq(type, ep, ep1, &e2->right.expr); return; } if (expr_eq(e1, e2)) { *ep = *ep ? expr_alloc_two(type, *ep, e1) : e1; expr_free(e2); if (type == E_AND) { e1 = expr_alloc_symbol(&symbol_yes); e2 = expr_alloc_symbol(&symbol_yes); } else if (type == E_OR) { e1 = expr_alloc_symbol(&symbol_no); e2 = expr_alloc_symbol(&symbol_no); } } #undef e1 #undef e2 } struct expr *expr_trans_compare(struct expr *e, enum expr_type type, struct symbol *sym) { struct expr *e1, *e2; if (!e) { e = expr_alloc_symbol(sym); if (type == E_UNEQUAL) e = expr_alloc_one(E_NOT, e); return e; } switch (e->type) { case E_AND: e1 = expr_trans_compare(e->left.expr, E_EQUAL, sym); e2 = expr_trans_compare(e->right.expr, E_EQUAL, sym); if (sym == &symbol_yes) e = expr_alloc_two(E_AND, e1, e2); if (sym == &symbol_no) e = expr_alloc_two(E_OR, e1, e2); if (type == E_UNEQUAL) e = expr_alloc_one(E_NOT, e); return e; case E_OR: e1 = expr_trans_compare(e->left.expr, E_EQUAL, sym); e2 = expr_trans_compare(e->right.expr, E_EQUAL, sym); if (sym == &symbol_yes) e = expr_alloc_two(E_OR, e1, e2); if (sym == &symbol_no) e = expr_alloc_two(E_AND, e1, e2); if (type == E_UNEQUAL) e = expr_alloc_one(E_NOT, e); return e; case E_NOT: return expr_trans_compare(e->left.expr, type == E_EQUAL ? E_UNEQUAL : E_EQUAL, sym); case E_UNEQUAL: case E_EQUAL: if (type == E_EQUAL) { if (sym == &symbol_yes) return expr_copy(e); if (sym == &symbol_mod) return expr_alloc_symbol(&symbol_no); if (sym == &symbol_no) return expr_alloc_one(E_NOT, expr_copy(e)); } else { if (sym == &symbol_yes) return expr_alloc_one(E_NOT, expr_copy(e)); if (sym == &symbol_mod) return expr_alloc_symbol(&symbol_yes); if (sym == &symbol_no) return expr_copy(e); } break; case E_SYMBOL: return expr_alloc_comp(type, e->left.sym, sym); case E_CHOICE: case E_RANGE: case E_NONE: /* panic */; } return NULL; } tristate expr_calc_value(struct expr *e) { tristate val1, val2; const char *str1, *str2; if (!e) return yes; switch (e->type) { case E_SYMBOL: sym_calc_value(e->left.sym); return e->left.sym->curr.tri; case E_AND: val1 = expr_calc_value(e->left.expr); val2 = expr_calc_value(e->right.expr); return E_AND(val1, val2); case E_OR: val1 = expr_calc_value(e->left.expr); val2 = expr_calc_value(e->right.expr); return E_OR(val1, val2); case E_NOT: val1 = expr_calc_value(e->left.expr); return E_NOT(val1); case E_EQUAL: sym_calc_value(e->left.sym); sym_calc_value(e->right.sym); str1 = sym_get_string_value(e->left.sym); str2 = sym_get_string_value(e->right.sym); return !strcmp(str1, str2) ? yes : no; case E_UNEQUAL: sym_calc_value(e->left.sym); sym_calc_value(e->right.sym); str1 = sym_get_string_value(e->left.sym); str2 = sym_get_string_value(e->right.sym); return !strcmp(str1, str2) ? no : yes; default: printf("expr_calc_value: %d?\n", e->type); return no; } } int expr_compare_type(enum expr_type t1, enum expr_type t2) { #if 0 return 1; #else if (t1 == t2) return 0; switch (t1) { case E_EQUAL: case E_UNEQUAL: if (t2 == E_NOT) return 1; case E_NOT: if (t2 == E_AND) return 1; case E_AND: if (t2 == E_OR) return 1; case E_OR: if (t2 == E_CHOICE) return 1; case E_CHOICE: if (t2 == 0) return 1; default: return -1; } printf("[%dgt%d?]", t1, t2); return 0; #endif } void expr_print(struct expr *e, void (*fn)(void *, struct symbol *, const char *), void *data, int prevtoken) { if (!e) { fn(data, NULL, "y"); return; } if (expr_compare_type(prevtoken, e->type) > 0) fn(data, NULL, "("); switch (e->type) { case E_SYMBOL: if (e->left.sym->name) fn(data, e->left.sym, e->left.sym->name); else fn(data, NULL, "<choice>"); break; case E_NOT: fn(data, NULL, "!"); expr_print(e->left.expr, fn, data, E_NOT); break; case E_EQUAL: if (e->left.sym->name) fn(data, e->left.sym, e->left.sym->name); else fn(data, NULL, "<choice>"); fn(data, NULL, "="); fn(data, e->right.sym, e->right.sym->name); break; case E_UNEQUAL: if (e->left.sym->name) fn(data, e->left.sym, e->left.sym->name); else fn(data, NULL, "<choice>"); fn(data, NULL, "!="); fn(data, e->right.sym, e->right.sym->name); break; case E_OR: expr_print(e->left.expr, fn, data, E_OR); fn(data, NULL, " || "); expr_print(e->right.expr, fn, data, E_OR); break; case E_AND: expr_print(e->left.expr, fn, data, E_AND); fn(data, NULL, " && "); expr_print(e->right.expr, fn, data, E_AND); break; case E_CHOICE: fn(data, e->right.sym, e->right.sym->name); if (e->left.expr) { fn(data, NULL, " ^ "); expr_print(e->left.expr, fn, data, E_CHOICE); } break; case E_RANGE: fn(data, NULL, "["); fn(data, e->left.sym, e->left.sym->name); fn(data, NULL, " "); fn(data, e->right.sym, e->right.sym->name); fn(data, NULL, "]"); break; default: { char buf[32]; sprintf(buf, "<unknown type %d>", e->type); fn(data, NULL, buf); break; } } if (expr_compare_type(prevtoken, e->type) > 0) fn(data, NULL, ")"); } static void expr_print_file_helper(void *data, struct symbol *sym, const char *str) { fwrite(str, strlen(str), 1, data); } void expr_fprint(struct expr *e, FILE *out) { expr_print(e, expr_print_file_helper, out, E_NONE); } static void expr_print_gstr_helper(void *data, struct symbol *sym, const char *str) { struct gstr *gs = (struct gstr*)data; const char *sym_str = NULL; if (sym) sym_str = sym_get_string_value(sym); if (gs->max_width) { unsigned extra_length = strlen(str); const char *last_cr = strrchr(gs->s, '\n'); unsigned last_line_length; if (sym_str) extra_length += 4 + strlen(sym_str); if (!last_cr) last_cr = gs->s; last_line_length = strlen(gs->s) - (last_cr - gs->s); if ((last_line_length + extra_length) > gs->max_width) str_append(gs, "\\\n"); } str_append(gs, str); if (sym && sym->type != S_UNKNOWN) str_printf(gs, " [=%s]", sym_str); } void expr_gstr_print(struct expr *e, struct gstr *gs) { expr_print(e, expr_print_gstr_helper, gs, E_NONE); }
kyak/openwrt-xburst
scripts/config/expr.c
C
gpl-2.0
26,452
require 'spec_helper' require 'email' describe Email do describe "is_valid?" do it 'treats a nil as invalid' do expect(Email.is_valid?(nil)).to eq(false) end it 'treats a good email as valid' do expect(Email.is_valid?('sam@sam.com')).to eq(true) end it 'treats a bad email as invalid' do expect(Email.is_valid?('sam@sam')).to eq(false) end it 'allows museum tld' do expect(Email.is_valid?('sam@nic.museum')).to eq(true) end it 'does not think a word is an email' do expect(Email.is_valid?('sam')).to eq(false) end end describe "downcase" do it 'downcases local and host part' do expect(Email.downcase('SAM@GMAIL.COM')).to eq('sam@gmail.com') expect(Email.downcase('sam@GMAIL.COM')).to eq('sam@gmail.com') end it 'leaves invalid emails untouched' do expect(Email.downcase('SAM@GMAILCOM')).to eq('SAM@GMAILCOM') expect(Email.downcase('samGMAIL.COM')).to eq('samGMAIL.COM') expect(Email.downcase('sam@GM@AIL.COM')).to eq('sam@GM@AIL.COM') end end end
Procurem/Contraints
spec/components/email/email_spec.rb
Ruby
gpl-2.0
1,085
/////////////////////////////////////////////////////////////////////////////// // Name: wx/choicebk.h // Purpose: wxChoicebook: wxChoice and wxNotebook combination // Author: Vadim Zeitlin // Modified by: Wlodzimierz ABX Skiba from wx/listbook.h // Created: 15.09.04 // Copyright: (c) Vadim Zeitlin, Wlodzimierz Skiba // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifndef _WX_CHOICEBOOK_H_ #define _WX_CHOICEBOOK_H_ #include "wx/defs.h" #if wxUSE_CHOICEBOOK #include "wx/bookctrl.h" #include "wx/choice.h" #include "wx/containr.h" class WXDLLIMPEXP_FWD_CORE wxChoice; wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_CORE, wxEVT_CHOICEBOOK_PAGE_CHANGED, wxBookCtrlEvent ); wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_CORE, wxEVT_CHOICEBOOK_PAGE_CHANGING, wxBookCtrlEvent ); // wxChoicebook flags #define wxCHB_DEFAULT wxBK_DEFAULT #define wxCHB_TOP wxBK_TOP #define wxCHB_BOTTOM wxBK_BOTTOM #define wxCHB_LEFT wxBK_LEFT #define wxCHB_RIGHT wxBK_RIGHT #define wxCHB_ALIGN_MASK wxBK_ALIGN_MASK // ---------------------------------------------------------------------------- // wxChoicebook // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxChoicebook : public wxNavigationEnabled<wxBookCtrlBase> { public: wxChoicebook() { } wxChoicebook(wxWindow *parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = wxEmptyString) { (void)Create(parent, id, pos, size, style, name); } // quasi ctor bool Create(wxWindow *parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = wxEmptyString); virtual bool SetPageText(size_t n, const wxString& strText); virtual wxString GetPageText(size_t n) const; virtual int GetPageImage(size_t n) const; virtual bool SetPageImage(size_t n, int imageId); virtual bool InsertPage(size_t n, wxWindow *page, const wxString& text, bool bSelect = false, int imageId = NO_IMAGE); virtual int SetSelection(size_t n) { return DoSetSelection(n, SetSelection_SendEvent); } virtual int ChangeSelection(size_t n) { return DoSetSelection(n); } virtual void SetImageList(wxImageList *imageList); virtual bool DeleteAllPages(); // returns the choice control wxChoice* GetChoiceCtrl() const { return (wxChoice*)m_bookctrl; } // Override this to return true because the part of parent window // background between our controlling wxChoice and the page area should // show through. virtual bool HasTransparentBackground() { return true; } protected: virtual void DoSetWindowVariant(wxWindowVariant variant); virtual wxWindow *DoRemovePage(size_t page); void UpdateSelectedPage(size_t newsel) { m_selection = static_cast<int>(newsel); GetChoiceCtrl()->Select(m_selection); } wxBookCtrlEvent* CreatePageChangingEvent() const; void MakeChangedEvent(wxBookCtrlEvent &event); // event handlers void OnChoiceSelected(wxCommandEvent& event); private: DECLARE_EVENT_TABLE() DECLARE_DYNAMIC_CLASS_NO_COPY(wxChoicebook) }; // ---------------------------------------------------------------------------- // choicebook event class and related stuff // ---------------------------------------------------------------------------- // wxChoicebookEvent is obsolete and defined for compatibility only #define wxChoicebookEvent wxBookCtrlEvent typedef wxBookCtrlEventFunction wxChoicebookEventFunction; #define wxChoicebookEventHandler(func) wxBookCtrlEventHandler(func) #define EVT_CHOICEBOOK_PAGE_CHANGED(winid, fn) \ wx__DECLARE_EVT1(wxEVT_CHOICEBOOK_PAGE_CHANGED, winid, wxBookCtrlEventHandler(fn)) #define EVT_CHOICEBOOK_PAGE_CHANGING(winid, fn) \ wx__DECLARE_EVT1(wxEVT_CHOICEBOOK_PAGE_CHANGING, winid, wxBookCtrlEventHandler(fn)) // old wxEVT_COMMAND_* constants #define wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED wxEVT_CHOICEBOOK_PAGE_CHANGED #define wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING wxEVT_CHOICEBOOK_PAGE_CHANGING #endif // wxUSE_CHOICEBOOK #endif // _WX_CHOICEBOOK_H_
mishin/dwimperl-windows
strawberry-perl-5.20.0.1-32bit-portable/perl/site/lib/Alien/wxWidgets/msw_3_0_2_uni_gcc_3_4/include/wx/choicebk.h
C
gpl-2.0
4,601
# $Id: __init__.py 7646 2013-04-17 14:17:37Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ This package contains Docutils parser modules. """ __docformat__ = 'reStructuredText' import sys from docutils import Component if sys.version_info < (2,5): from docutils._compat import __import__ class Parser(Component): component_type = 'parser' config_section = 'parsers' def parse(self, inputstring, document): """Override to parse `inputstring` into document tree `document`.""" raise NotImplementedError('subclass must override this method') def setup_parse(self, inputstring, document): """Initial parse setup. Call at start of `self.parse()`.""" self.inputstring = inputstring self.document = document document.reporter.attach_observer(document.note_parse_message) def finish_parse(self): """Finalize parse details. Call at end of `self.parse()`.""" self.document.reporter.detach_observer( self.document.note_parse_message) _parser_aliases = { 'restructuredtext': 'rst', 'rest': 'rst', 'restx': 'rst', 'rtxt': 'rst',} def get_parser_class(parser_name): """Return the Parser class from the `parser_name` module.""" parser_name = parser_name.lower() if parser_name in _parser_aliases: parser_name = _parser_aliases[parser_name] try: module = __import__(parser_name, globals(), locals(), level=1) except ImportError: module = __import__(parser_name, globals(), locals(), level=0) return module.Parser
JulienMcJay/eclock
windows/Python27/Lib/site-packages/docutils/parsers/__init__.py
Python
gpl-2.0
1,657
/*====================================================================== An elsa_cs PCMCIA client driver This driver is for the Elsa PCM ISDN Cards, i.e. the MicroLink The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The initial developer of the original code is David A. Hinds <dahinds@users.sourceforge.net>. Portions created by David A. Hinds are Copyright (C) 1999 David A. Hinds. All Rights Reserved. Modifications from dummy_cs.c are Copyright (C) 1999-2001 Klaus Lichtenwalder <Lichtenwalder@ACM.org>. All Rights Reserved. Alternatively, the contents of this file may be used under the terms of the GNU General Public License version 2 (the "GPL"), in which case the provisions of the GPL are applicable instead of the above. If you wish to allow the use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. ======================================================================*/ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/ptrace.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/timer.h> #include <linux/ioport.h> #include <asm/io.h> #include <asm/system.h> #include <pcmcia/cs.h> #include <pcmcia/cistpl.h> #include <pcmcia/cisreg.h> #include <pcmcia/ds.h> #include "hisax_cfg.h" MODULE_DESCRIPTION("ISDN4Linux: PCMCIA client driver for Elsa PCM cards"); MODULE_AUTHOR("Klaus Lichtenwalder"); MODULE_LICENSE("Dual MPL/GPL"); /*====================================================================*/ /* Parameters that can be set with 'insmod' */ static int protocol = 2; /* EURO-ISDN Default */ module_param(protocol, int, 0); /*====================================================================*/ /* The event() function is this driver's Card Services event handler. It will be called by Card Services when an appropriate card status event is received. The config() and release() entry points are used to configure or release a socket, in response to card insertion and ejection events. They are invoked from the elsa_cs event handler. */ static int elsa_cs_config(struct pcmcia_device *link) __devinit ; static void elsa_cs_release(struct pcmcia_device *link); /* The attach() and detach() entry points are used to create and destroy "instances" of the driver, where each instance represents everything needed to manage one actual PCMCIA card. */ static void elsa_cs_detach(struct pcmcia_device *p_dev) __devexit; typedef struct local_info_t { struct pcmcia_device *p_dev; int busy; int cardnr; } local_info_t; /*====================================================================== elsa_cs_attach() creates an "instance" of the driver, allocatingx local data structures for one device. The device is registered with Card Services. The dev_link structure is initialized, but we don't actually configure the card at this point -- we wait until we receive a card insertion event. ======================================================================*/ static int __devinit elsa_cs_probe(struct pcmcia_device *link) { local_info_t *local; dev_dbg(&link->dev, "elsa_cs_attach()\n"); /* Allocate space for private device-specific data */ local = kzalloc(sizeof(local_info_t), GFP_KERNEL); if (!local) return -ENOMEM; local->p_dev = link; link->priv = local; local->cardnr = -1; /* General socket configuration defaults can go here. In this client, we assume very little, and rely on the CIS for almost everything. In most clients, many details (i.e., number, sizes, and attributes of IO windows) are fixed by the nature of the device, and can be hard-wired here. */ link->resource[0]->end = 8; link->resource[0]->flags |= IO_DATA_PATH_WIDTH_AUTO; link->conf.Attributes = CONF_ENABLE_IRQ; link->conf.IntType = INT_MEMORY_AND_IO; return elsa_cs_config(link); } /* elsa_cs_attach */ /*====================================================================== This deletes a driver "instance". The device is de-registered with Card Services. If it has been released, all local data structures are freed. Otherwise, the structures will be freed when the device is released. ======================================================================*/ static void __devexit elsa_cs_detach(struct pcmcia_device *link) { local_info_t *info = link->priv; dev_dbg(&link->dev, "elsa_cs_detach(0x%p)\n", link); info->busy = 1; elsa_cs_release(link); kfree(info); } /* elsa_cs_detach */ /*====================================================================== elsa_cs_config() is scheduled to run after a CARD_INSERTION event is received, to configure the PCMCIA socket, and to make the device available to the system. ======================================================================*/ static int elsa_cs_configcheck(struct pcmcia_device *p_dev, cistpl_cftable_entry_t *cf, cistpl_cftable_entry_t *dflt, unsigned int vcc, void *priv_data) { int j; p_dev->io_lines = 3; if ((cf->io.nwin > 0) && cf->io.win[0].base) { printk(KERN_INFO "(elsa_cs: looks like the 96 model)\n"); p_dev->resource[0]->start = cf->io.win[0].base; if (!pcmcia_request_io(p_dev)) return 0; } else { printk(KERN_INFO "(elsa_cs: looks like the 97 model)\n"); for (j = 0x2f0; j > 0x100; j -= 0x10) { p_dev->resource[0]->start = j; if (!pcmcia_request_io(p_dev)) return 0; } } return -ENODEV; } static int __devinit elsa_cs_config(struct pcmcia_device *link) { local_info_t *dev; int i; IsdnCard_t icard; dev_dbg(&link->dev, "elsa_config(0x%p)\n", link); dev = link->priv; i = pcmcia_loop_config(link, elsa_cs_configcheck, NULL); if (i != 0) goto failed; if (!link->irq) goto failed; i = pcmcia_request_configuration(link, &link->conf); if (i != 0) goto failed; /* Finally, report what we've done */ dev_info(&link->dev, "index 0x%02x: ", link->conf.ConfigIndex); if (link->conf.Attributes & CONF_ENABLE_IRQ) printk(", irq %d", link->irq); if (link->resource[0]) printk(" & %pR", link->resource[0]); if (link->resource[1]) printk(" & %pR", link->resource[1]); printk("\n"); icard.para[0] = link->irq; icard.para[1] = link->resource[0]->start; icard.protocol = protocol; icard.typ = ISDN_CTYPE_ELSA_PCMCIA; i = hisax_init_pcmcia(link, &(((local_info_t*)link->priv)->busy), &icard); if (i < 0) { printk(KERN_ERR "elsa_cs: failed to initialize Elsa " "PCMCIA %d with %pR\n", i, link->resource[0]); elsa_cs_release(link); } else ((local_info_t*)link->priv)->cardnr = i; return 0; failed: elsa_cs_release(link); return -ENODEV; } /* elsa_cs_config */ /*====================================================================== After a card is removed, elsa_cs_release() will unregister the net device, and release the PCMCIA configuration. If the device is still open, this will be postponed until it is closed. ======================================================================*/ static void elsa_cs_release(struct pcmcia_device *link) { local_info_t *local = link->priv; dev_dbg(&link->dev, "elsa_cs_release(0x%p)\n", link); if (local) { if (local->cardnr >= 0) { /* no unregister function with hisax */ HiSax_closecard(local->cardnr); } } pcmcia_disable_device(link); } /* elsa_cs_release */ static int elsa_suspend(struct pcmcia_device *link) { local_info_t *dev = link->priv; dev->busy = 1; return 0; } static int elsa_resume(struct pcmcia_device *link) { local_info_t *dev = link->priv; dev->busy = 0; return 0; } static struct pcmcia_device_id elsa_ids[] = { PCMCIA_DEVICE_PROD_ID12("ELSA AG (Aachen, Germany)", "MicroLink ISDN/MC ", 0x983de2c4, 0x333ba257), PCMCIA_DEVICE_PROD_ID12("ELSA GmbH, Aachen", "MicroLink ISDN/MC ", 0x639e5718, 0x333ba257), PCMCIA_DEVICE_NULL }; MODULE_DEVICE_TABLE(pcmcia, elsa_ids); static struct pcmcia_driver elsa_cs_driver = { .owner = THIS_MODULE, .drv = { .name = "elsa_cs", }, .probe = elsa_cs_probe, .remove = __devexit_p(elsa_cs_detach), .id_table = elsa_ids, .suspend = elsa_suspend, .resume = elsa_resume, }; static int __init init_elsa_cs(void) { return pcmcia_register_driver(&elsa_cs_driver); } static void __exit exit_elsa_cs(void) { pcmcia_unregister_driver(&elsa_cs_driver); } module_init(init_elsa_cs); module_exit(exit_elsa_cs);
wkritzinger/asuswrt-merlin
release/src-rt-7.x.main/src/linux/linux-2.6.36/drivers/isdn/hisax/elsa_cs.c
C
gpl-2.0
9,442
/* * bootstrap-table - v1.11.0 - 2016-07-02 * https://github.com/wenzhixin/bootstrap-table * Copyright (c) 2016 zhixin wen * Licensed MIT License */ !function(a){"use strict";a.fn.bootstrapTable.locales["ko-KR"]={formatLoadingMessage:function(){return"데이터를 불러오는 중입니다..."},formatRecordsPerPage:function(a){return"페이지 당 "+a+"개 데이터 출력"},formatShowingRows:function(a,b,c){return"전체 "+c+"개 중 "+a+"~"+b+"번째 데이터 출력,"},formatSearch:function(){return"검색"},formatNoMatches:function(){return"조회된 데이터가 없습니다."},formatRefresh:function(){return"새로 고침"},formatToggle:function(){return"전환"},formatColumns:function(){return"컬럼 필터링"}},a.extend(a.fn.bootstrapTable.defaults,a.fn.bootstrapTable.locales["ko-KR"])}(jQuery);
jesusignazio/zocoyula
vendors/bootstrap-table/locale/bootstrap-table-ko-KR.min.js
JavaScript
apache-2.0
815
/* * datastream.h * */ struct buffer_head *befs_read_datastream(struct super_block *sb, const befs_data_stream *ds, befs_off_t pos, uint *off); int befs_fblock2brun(struct super_block *sb, const befs_data_stream *data, befs_blocknr_t fblock, befs_block_run *run); size_t befs_read_lsymlink(struct super_block *sb, const befs_data_stream *data, void *buff, befs_off_t len); befs_blocknr_t befs_count_blocks(struct super_block *sb, const befs_data_stream *ds); extern const befs_inode_addr BAD_IADDR;
mkvdv/au-linux-kernel-autumn-2017
linux/fs/befs/datastream.h
C
gpl-3.0
536
/* * QEMU Bluetooth HCI logic. * * Copyright (C) 2007 OpenMoko, Inc. * Copyright (C) 2008 Andrzej Zaborowski <balrog@zabor.org> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include "qemu-common.h" #include "qemu-timer.h" #include "usb.h" #include "net.h" #include "bt.h" struct bt_hci_s { uint8_t *(*evt_packet)(void *opaque); void (*evt_submit)(void *opaque, int len); void *opaque; uint8_t evt_buf[256]; uint8_t acl_buf[4096]; int acl_len; uint16_t asb_handle; uint16_t psb_handle; int last_cmd; /* Note: Always little-endian */ struct bt_device_s *conn_req_host; struct { int inquire; int periodic; int responses_left; int responses; QEMUTimer *inquiry_done; QEMUTimer *inquiry_next; int inquiry_length; int inquiry_period; int inquiry_mode; #define HCI_HANDLE_OFFSET 0x20 #define HCI_HANDLES_MAX 0x10 struct bt_hci_master_link_s { struct bt_link_s *link; void (*lmp_acl_data)(struct bt_link_s *link, const uint8_t *data, int start, int len); QEMUTimer *acl_mode_timer; } handle[HCI_HANDLES_MAX]; uint32_t role_bmp; int last_handle; int connecting; bdaddr_t awaiting_bdaddr[HCI_HANDLES_MAX]; } lm; uint8_t event_mask[8]; uint16_t voice_setting; /* Notw: Always little-endian */ uint16_t conn_accept_tout; QEMUTimer *conn_accept_timer; struct HCIInfo info; struct bt_device_s device; }; #define DEFAULT_RSSI_DBM 20 #define hci_from_info(ptr) container_of((ptr), struct bt_hci_s, info) #define hci_from_device(ptr) container_of((ptr), struct bt_hci_s, device) struct bt_hci_link_s { struct bt_link_s btlink; uint16_t handle; /* Local */ }; /* LMP layer emulation */ #if 0 static void bt_submit_lmp(struct bt_device_s *bt, int length, uint8_t *data) { int resp, resplen, error, op, tr; uint8_t respdata[17]; if (length < 1) return; tr = *data & 1; op = *(data ++) >> 1; resp = LMP_ACCEPTED; resplen = 2; respdata[1] = op; error = 0; length --; if (op >= 0x7c) { /* Extended opcode */ op |= *(data ++) << 8; resp = LMP_ACCEPTED_EXT; resplen = 4; respdata[0] = op >> 8; respdata[1] = op & 0xff; length --; } switch (op) { case LMP_ACCEPTED: /* data[0] Op code */ if (length < 1) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } resp = 0; break; case LMP_ACCEPTED_EXT: /* data[0] Escape op code * data[1] Extended op code */ if (length < 2) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } resp = 0; break; case LMP_NOT_ACCEPTED: /* data[0] Op code * data[1] Error code */ if (length < 2) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } resp = 0; break; case LMP_NOT_ACCEPTED_EXT: /* data[0] Op code * data[1] Extended op code * data[2] Error code */ if (length < 3) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } resp = 0; break; case LMP_HOST_CONNECTION_REQ: break; case LMP_SETUP_COMPLETE: resp = LMP_SETUP_COMPLETE; resplen = 1; bt->setup = 1; break; case LMP_DETACH: /* data[0] Error code */ if (length < 1) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } bt->setup = 0; resp = 0; break; case LMP_SUPERVISION_TIMEOUT: /* data[0,1] Supervision timeout */ if (length < 2) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } resp = 0; break; case LMP_QUALITY_OF_SERVICE: resp = 0; /* Fall through */ case LMP_QOS_REQ: /* data[0,1] Poll interval * data[2] N(BC) */ if (length < 3) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } break; case LMP_MAX_SLOT: resp = 0; /* Fall through */ case LMP_MAX_SLOT_REQ: /* data[0] Max slots */ if (length < 1) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } break; case LMP_AU_RAND: case LMP_IN_RAND: case LMP_COMB_KEY: /* data[0-15] Random number */ if (length < 16) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } if (op == LMP_AU_RAND) { if (bt->key_present) { resp = LMP_SRES; resplen = 5; /* XXX: [Part H] Section 6.1 on page 801 */ } else { error = HCI_PIN_OR_KEY_MISSING; goto not_accepted; } } else if (op == LMP_IN_RAND) { error = HCI_PAIRING_NOT_ALLOWED; goto not_accepted; } else { /* XXX: [Part H] Section 3.2 on page 779 */ resp = LMP_UNIT_KEY; resplen = 17; memcpy(respdata + 1, bt->key, 16); error = HCI_UNIT_LINK_KEY_USED; goto not_accepted; } break; case LMP_UNIT_KEY: /* data[0-15] Key */ if (length < 16) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } memcpy(bt->key, data, 16); bt->key_present = 1; break; case LMP_SRES: /* data[0-3] Authentication response */ if (length < 4) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } break; case LMP_CLKOFFSET_REQ: resp = LMP_CLKOFFSET_RES; resplen = 3; respdata[1] = 0x33; respdata[2] = 0x33; break; case LMP_CLKOFFSET_RES: /* data[0,1] Clock offset * (Slave to master only) */ if (length < 2) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } break; case LMP_VERSION_REQ: case LMP_VERSION_RES: /* data[0] VersNr * data[1,2] CompId * data[3,4] SubVersNr */ if (length < 5) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } if (op == LMP_VERSION_REQ) { resp = LMP_VERSION_RES; resplen = 6; respdata[1] = 0x20; respdata[2] = 0xff; respdata[3] = 0xff; respdata[4] = 0xff; respdata[5] = 0xff; } else resp = 0; break; case LMP_FEATURES_REQ: case LMP_FEATURES_RES: /* data[0-7] Features */ if (length < 8) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } if (op == LMP_FEATURES_REQ) { resp = LMP_FEATURES_RES; resplen = 9; respdata[1] = (bt->lmp_caps >> 0) & 0xff; respdata[2] = (bt->lmp_caps >> 8) & 0xff; respdata[3] = (bt->lmp_caps >> 16) & 0xff; respdata[4] = (bt->lmp_caps >> 24) & 0xff; respdata[5] = (bt->lmp_caps >> 32) & 0xff; respdata[6] = (bt->lmp_caps >> 40) & 0xff; respdata[7] = (bt->lmp_caps >> 48) & 0xff; respdata[8] = (bt->lmp_caps >> 56) & 0xff; } else resp = 0; break; case LMP_NAME_REQ: /* data[0] Name offset */ if (length < 1) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } resp = LMP_NAME_RES; resplen = 17; respdata[1] = data[0]; respdata[2] = strlen(bt->lmp_name); memset(respdata + 3, 0x00, 14); if (respdata[2] > respdata[1]) memcpy(respdata + 3, bt->lmp_name + respdata[1], respdata[2] - respdata[1]); break; case LMP_NAME_RES: /* data[0] Name offset * data[1] Name length * data[2-15] Name fragment */ if (length < 16) { error = HCI_UNSUPPORTED_LMP_PARAMETER_VALUE; goto not_accepted; } resp = 0; break; default: error = HCI_UNKNOWN_LMP_PDU; /* Fall through */ not_accepted: if (op >> 8) { resp = LMP_NOT_ACCEPTED_EXT; resplen = 5; respdata[0] = op >> 8; respdata[1] = op & 0xff; respdata[2] = error; } else { resp = LMP_NOT_ACCEPTED; resplen = 3; respdata[0] = op & 0xff; respdata[1] = error; } } if (resp == 0) return; if (resp >> 8) { respdata[0] = resp >> 8; respdata[1] = resp & 0xff; } else respdata[0] = resp & 0xff; respdata[0] <<= 1; respdata[0] |= tr; } static void bt_submit_raw_acl(struct bt_piconet_s *net, int length, uint8_t *data) { struct bt_device_s *slave; if (length < 1) return; slave = 0; #if 0 slave = net->slave; #endif switch (data[0] & 3) { case LLID_ACLC: bt_submit_lmp(slave, length - 1, data + 1); break; case LLID_ACLU_START: #if 0 bt_sumbit_l2cap(slave, length - 1, data + 1, (data[0] >> 2) & 1); breka; #endif default: case LLID_ACLU_CONT: break; } } #endif /* HCI layer emulation */ /* Note: we could ignore endiannes because unswapped handles will still * be valid as connection identifiers for the guest - they don't have to * be continuously allocated. We do it though, to preserve similar * behaviour between hosts. Some things, like the BD_ADDR cannot be * preserved though (for example if a real hci is used). */ #ifdef HOST_WORDS_BIGENDIAN # define HNDL(raw) bswap16(raw) #else # define HNDL(raw) (raw) #endif static const uint8_t bt_event_reserved_mask[8] = { 0xff, 0x9f, 0xfb, 0xff, 0x07, 0x18, 0x00, 0x00, }; static inline uint8_t *bt_hci_event_start(struct bt_hci_s *hci, int evt, int len) { uint8_t *packet, mask; int mask_byte; if (len > 255) { fprintf(stderr, "%s: HCI event params too long (%ib)\n", __FUNCTION__, len); exit(-1); } mask_byte = (evt - 1) >> 3; mask = 1 << ((evt - 1) & 3); if (mask & bt_event_reserved_mask[mask_byte] & ~hci->event_mask[mask_byte]) return NULL; packet = hci->evt_packet(hci->opaque); packet[0] = evt; packet[1] = len; return &packet[2]; } static inline void bt_hci_event(struct bt_hci_s *hci, int evt, void *params, int len) { uint8_t *packet = bt_hci_event_start(hci, evt, len); if (!packet) return; if (len) memcpy(packet, params, len); hci->evt_submit(hci->opaque, len + 2); } static inline void bt_hci_event_status(struct bt_hci_s *hci, int status) { evt_cmd_status params = { .status = status, .ncmd = 1, .opcode = hci->last_cmd, }; bt_hci_event(hci, EVT_CMD_STATUS, &params, EVT_CMD_STATUS_SIZE); } static inline void bt_hci_event_complete(struct bt_hci_s *hci, void *ret, int len) { uint8_t *packet = bt_hci_event_start(hci, EVT_CMD_COMPLETE, len + EVT_CMD_COMPLETE_SIZE); evt_cmd_complete *params = (evt_cmd_complete *) packet; if (!packet) return; params->ncmd = 1; params->opcode = hci->last_cmd; if (len) memcpy(&packet[EVT_CMD_COMPLETE_SIZE], ret, len); hci->evt_submit(hci->opaque, len + EVT_CMD_COMPLETE_SIZE + 2); } static void bt_hci_inquiry_done(void *opaque) { struct bt_hci_s *hci = (struct bt_hci_s *) opaque; uint8_t status = HCI_SUCCESS; if (!hci->lm.periodic) hci->lm.inquire = 0; /* The specification is inconsistent about this one. Page 565 reads * "The event parameters of Inquiry Complete event will have a summary * of the result from the Inquiry process, which reports the number of * nearby Bluetooth devices that responded [so hci->responses].", but * Event Parameters (see page 729) has only Status. */ bt_hci_event(hci, EVT_INQUIRY_COMPLETE, &status, 1); } static void bt_hci_inquiry_result_standard(struct bt_hci_s *hci, struct bt_device_s *slave) { inquiry_info params = { .num_responses = 1, .bdaddr = BAINIT(&slave->bd_addr), .pscan_rep_mode = 0x00, /* R0 */ .pscan_period_mode = 0x00, /* P0 - deprecated */ .pscan_mode = 0x00, /* Standard scan - deprecated */ .dev_class[0] = slave->class[0], .dev_class[1] = slave->class[1], .dev_class[2] = slave->class[2], /* TODO: return the clkoff *differenece* */ .clock_offset = slave->clkoff, /* Note: no swapping */ }; bt_hci_event(hci, EVT_INQUIRY_RESULT, &params, INQUIRY_INFO_SIZE); } static void bt_hci_inquiry_result_with_rssi(struct bt_hci_s *hci, struct bt_device_s *slave) { inquiry_info_with_rssi params = { .num_responses = 1, .bdaddr = BAINIT(&slave->bd_addr), .pscan_rep_mode = 0x00, /* R0 */ .pscan_period_mode = 0x00, /* P0 - deprecated */ .dev_class[0] = slave->class[0], .dev_class[1] = slave->class[1], .dev_class[2] = slave->class[2], /* TODO: return the clkoff *differenece* */ .clock_offset = slave->clkoff, /* Note: no swapping */ .rssi = DEFAULT_RSSI_DBM, }; bt_hci_event(hci, EVT_INQUIRY_RESULT_WITH_RSSI, &params, INQUIRY_INFO_WITH_RSSI_SIZE); } static void bt_hci_inquiry_result(struct bt_hci_s *hci, struct bt_device_s *slave) { if (!slave->inquiry_scan || !hci->lm.responses_left) return; hci->lm.responses_left --; hci->lm.responses ++; switch (hci->lm.inquiry_mode) { case 0x00: bt_hci_inquiry_result_standard(hci, slave); return; case 0x01: bt_hci_inquiry_result_with_rssi(hci, slave); return; default: fprintf(stderr, "%s: bad inquiry mode %02x\n", __FUNCTION__, hci->lm.inquiry_mode); exit(-1); } } static void bt_hci_mod_timer_1280ms(QEMUTimer *timer, int period) { qemu_mod_timer(timer, qemu_get_clock_ns(vm_clock) + muldiv64(period << 7, get_ticks_per_sec(), 100)); } static void bt_hci_inquiry_start(struct bt_hci_s *hci, int length) { struct bt_device_s *slave; hci->lm.inquiry_length = length; for (slave = hci->device.net->slave; slave; slave = slave->next) /* Don't uncover ourselves. */ if (slave != &hci->device) bt_hci_inquiry_result(hci, slave); /* TODO: register for a callback on a new device's addition to the * scatternet so that if it's added before inquiry_length expires, * an Inquiry Result is generated immediately. Alternatively re-loop * through the devices on the inquiry_length expiration and report * devices not seen before. */ if (hci->lm.responses_left) bt_hci_mod_timer_1280ms(hci->lm.inquiry_done, hci->lm.inquiry_length); else bt_hci_inquiry_done(hci); if (hci->lm.periodic) bt_hci_mod_timer_1280ms(hci->lm.inquiry_next, hci->lm.inquiry_period); } static void bt_hci_inquiry_next(void *opaque) { struct bt_hci_s *hci = (struct bt_hci_s *) opaque; hci->lm.responses_left += hci->lm.responses; hci->lm.responses = 0; bt_hci_inquiry_start(hci, hci->lm.inquiry_length); } static inline int bt_hci_handle_bad(struct bt_hci_s *hci, uint16_t handle) { return !(handle & HCI_HANDLE_OFFSET) || handle >= (HCI_HANDLE_OFFSET | HCI_HANDLES_MAX) || !hci->lm.handle[handle & ~HCI_HANDLE_OFFSET].link; } static inline int bt_hci_role_master(struct bt_hci_s *hci, uint16_t handle) { return !!(hci->lm.role_bmp & (1 << (handle & ~HCI_HANDLE_OFFSET))); } static inline struct bt_device_s *bt_hci_remote_dev(struct bt_hci_s *hci, uint16_t handle) { struct bt_link_s *link = hci->lm.handle[handle & ~HCI_HANDLE_OFFSET].link; return bt_hci_role_master(hci, handle) ? link->slave : link->host; } static void bt_hci_mode_tick(void *opaque); static void bt_hci_lmp_link_establish(struct bt_hci_s *hci, struct bt_link_s *link, int master) { hci->lm.handle[hci->lm.last_handle].link = link; if (master) { /* We are the master side of an ACL link */ hci->lm.role_bmp |= 1 << hci->lm.last_handle; hci->lm.handle[hci->lm.last_handle].lmp_acl_data = link->slave->lmp_acl_data; } else { /* We are the slave side of an ACL link */ hci->lm.role_bmp &= ~(1 << hci->lm.last_handle); hci->lm.handle[hci->lm.last_handle].lmp_acl_data = link->host->lmp_acl_resp; } /* Mode */ if (master) { link->acl_mode = acl_active; hci->lm.handle[hci->lm.last_handle].acl_mode_timer = qemu_new_timer_ns(vm_clock, bt_hci_mode_tick, link); } } static void bt_hci_lmp_link_teardown(struct bt_hci_s *hci, uint16_t handle) { handle &= ~HCI_HANDLE_OFFSET; hci->lm.handle[handle].link = NULL; if (bt_hci_role_master(hci, handle)) { qemu_del_timer(hci->lm.handle[handle].acl_mode_timer); qemu_free_timer(hci->lm.handle[handle].acl_mode_timer); } } static int bt_hci_connect(struct bt_hci_s *hci, bdaddr_t *bdaddr) { struct bt_device_s *slave; struct bt_link_s link; for (slave = hci->device.net->slave; slave; slave = slave->next) if (slave->page_scan && !bacmp(&slave->bd_addr, bdaddr)) break; if (!slave || slave == &hci->device) return -ENODEV; bacpy(&hci->lm.awaiting_bdaddr[hci->lm.connecting ++], &slave->bd_addr); link.slave = slave; link.host = &hci->device; link.slave->lmp_connection_request(&link); /* Always last */ return 0; } static void bt_hci_connection_reject(struct bt_hci_s *hci, struct bt_device_s *host, uint8_t because) { struct bt_link_s link = { .slave = &hci->device, .host = host, /* Rest uninitialised */ }; host->reject_reason = because; host->lmp_connection_complete(&link); } static void bt_hci_connection_reject_event(struct bt_hci_s *hci, bdaddr_t *bdaddr) { evt_conn_complete params; params.status = HCI_NO_CONNECTION; params.handle = 0; bacpy(&params.bdaddr, bdaddr); params.link_type = ACL_LINK; params.encr_mode = 0x00; /* Encryption not required */ bt_hci_event(hci, EVT_CONN_COMPLETE, &params, EVT_CONN_COMPLETE_SIZE); } static void bt_hci_connection_accept(struct bt_hci_s *hci, struct bt_device_s *host) { struct bt_hci_link_s *link = qemu_mallocz(sizeof(struct bt_hci_link_s)); evt_conn_complete params; uint16_t handle; uint8_t status = HCI_SUCCESS; int tries = HCI_HANDLES_MAX; /* Make a connection handle */ do { while (hci->lm.handle[++ hci->lm.last_handle].link && -- tries) hci->lm.last_handle &= HCI_HANDLES_MAX - 1; handle = hci->lm.last_handle | HCI_HANDLE_OFFSET; } while ((handle == hci->asb_handle || handle == hci->psb_handle) && tries); if (!tries) { qemu_free(link); bt_hci_connection_reject(hci, host, HCI_REJECTED_LIMITED_RESOURCES); status = HCI_NO_CONNECTION; goto complete; } link->btlink.slave = &hci->device; link->btlink.host = host; link->handle = handle; /* Link established */ bt_hci_lmp_link_establish(hci, &link->btlink, 0); complete: params.status = status; params.handle = HNDL(handle); bacpy(&params.bdaddr, &host->bd_addr); params.link_type = ACL_LINK; params.encr_mode = 0x00; /* Encryption not required */ bt_hci_event(hci, EVT_CONN_COMPLETE, &params, EVT_CONN_COMPLETE_SIZE); /* Neets to be done at the very end because it can trigger a (nested) * disconnected, in case the other and had cancelled the request * locally. */ if (status == HCI_SUCCESS) { host->reject_reason = 0; host->lmp_connection_complete(&link->btlink); } } static void bt_hci_lmp_connection_request(struct bt_link_s *link) { struct bt_hci_s *hci = hci_from_device(link->slave); evt_conn_request params; if (hci->conn_req_host) { bt_hci_connection_reject(hci, link->host, HCI_REJECTED_LIMITED_RESOURCES); return; } hci->conn_req_host = link->host; /* TODO: if masked and auto-accept, then auto-accept, * if masked and not auto-accept, then auto-reject */ /* TODO: kick the hci->conn_accept_timer, timeout after * hci->conn_accept_tout * 0.625 msec */ bacpy(&params.bdaddr, &link->host->bd_addr); memcpy(&params.dev_class, &link->host->class, sizeof(params.dev_class)); params.link_type = ACL_LINK; bt_hci_event(hci, EVT_CONN_REQUEST, &params, EVT_CONN_REQUEST_SIZE); return; } static void bt_hci_conn_accept_timeout(void *opaque) { struct bt_hci_s *hci = (struct bt_hci_s *) opaque; if (!hci->conn_req_host) /* Already accepted or rejected. If the other end cancelled the * connection request then we still have to reject or accept it * and then we'll get a disconnect. */ return; /* TODO */ } /* Remove from the list of devices which we wanted to connect to and * are awaiting a response from. If the callback sees a response from * a device which is not on the list it will assume it's a connection * that's been cancelled by the host in the meantime and immediately * try to detach the link and send a Connection Complete. */ static int bt_hci_lmp_connection_ready(struct bt_hci_s *hci, bdaddr_t *bdaddr) { int i; for (i = 0; i < hci->lm.connecting; i ++) if (!bacmp(&hci->lm.awaiting_bdaddr[i], bdaddr)) { if (i < -- hci->lm.connecting) bacpy(&hci->lm.awaiting_bdaddr[i], &hci->lm.awaiting_bdaddr[hci->lm.connecting]); return 0; } return 1; } static void bt_hci_lmp_connection_complete(struct bt_link_s *link) { struct bt_hci_s *hci = hci_from_device(link->host); evt_conn_complete params; uint16_t handle; uint8_t status = HCI_SUCCESS; int tries = HCI_HANDLES_MAX; if (bt_hci_lmp_connection_ready(hci, &link->slave->bd_addr)) { if (!hci->device.reject_reason) link->slave->lmp_disconnect_slave(link); handle = 0; status = HCI_NO_CONNECTION; goto complete; } if (hci->device.reject_reason) { handle = 0; status = hci->device.reject_reason; goto complete; } /* Make a connection handle */ do { while (hci->lm.handle[++ hci->lm.last_handle].link && -- tries) hci->lm.last_handle &= HCI_HANDLES_MAX - 1; handle = hci->lm.last_handle | HCI_HANDLE_OFFSET; } while ((handle == hci->asb_handle || handle == hci->psb_handle) && tries); if (!tries) { link->slave->lmp_disconnect_slave(link); status = HCI_NO_CONNECTION; goto complete; } /* Link established */ link->handle = handle; bt_hci_lmp_link_establish(hci, link, 1); complete: params.status = status; params.handle = HNDL(handle); params.link_type = ACL_LINK; bacpy(&params.bdaddr, &link->slave->bd_addr); params.encr_mode = 0x00; /* Encryption not required */ bt_hci_event(hci, EVT_CONN_COMPLETE, &params, EVT_CONN_COMPLETE_SIZE); } static void bt_hci_disconnect(struct bt_hci_s *hci, uint16_t handle, int reason) { struct bt_link_s *btlink = hci->lm.handle[handle & ~HCI_HANDLE_OFFSET].link; struct bt_hci_link_s *link; evt_disconn_complete params; if (bt_hci_role_master(hci, handle)) { btlink->slave->reject_reason = reason; btlink->slave->lmp_disconnect_slave(btlink); /* The link pointer is invalid from now on */ goto complete; } btlink->host->reject_reason = reason; btlink->host->lmp_disconnect_master(btlink); /* We are the slave, we get to clean this burden */ link = (struct bt_hci_link_s *) btlink; qemu_free(link); complete: bt_hci_lmp_link_teardown(hci, handle); params.status = HCI_SUCCESS; params.handle = HNDL(handle); params.reason = HCI_CONNECTION_TERMINATED; bt_hci_event(hci, EVT_DISCONN_COMPLETE, &params, EVT_DISCONN_COMPLETE_SIZE); } /* TODO: use only one function */ static void bt_hci_lmp_disconnect_host(struct bt_link_s *link) { struct bt_hci_s *hci = hci_from_device(link->host); uint16_t handle = link->handle; evt_disconn_complete params; bt_hci_lmp_link_teardown(hci, handle); params.status = HCI_SUCCESS; params.handle = HNDL(handle); params.reason = hci->device.reject_reason; bt_hci_event(hci, EVT_DISCONN_COMPLETE, &params, EVT_DISCONN_COMPLETE_SIZE); } static void bt_hci_lmp_disconnect_slave(struct bt_link_s *btlink) { struct bt_hci_link_s *link = (struct bt_hci_link_s *) btlink; struct bt_hci_s *hci = hci_from_device(btlink->slave); uint16_t handle = link->handle; evt_disconn_complete params; qemu_free(link); bt_hci_lmp_link_teardown(hci, handle); params.status = HCI_SUCCESS; params.handle = HNDL(handle); params.reason = hci->device.reject_reason; bt_hci_event(hci, EVT_DISCONN_COMPLETE, &params, EVT_DISCONN_COMPLETE_SIZE); } static int bt_hci_name_req(struct bt_hci_s *hci, bdaddr_t *bdaddr) { struct bt_device_s *slave; evt_remote_name_req_complete params; int len; for (slave = hci->device.net->slave; slave; slave = slave->next) if (slave->page_scan && !bacmp(&slave->bd_addr, bdaddr)) break; if (!slave) return -ENODEV; bt_hci_event_status(hci, HCI_SUCCESS); params.status = HCI_SUCCESS; bacpy(&params.bdaddr, &slave->bd_addr); len = snprintf(params.name, sizeof(params.name), "%s", slave->lmp_name ?: ""); memset(params.name + len, 0, sizeof(params.name) - len); bt_hci_event(hci, EVT_REMOTE_NAME_REQ_COMPLETE, &params, EVT_REMOTE_NAME_REQ_COMPLETE_SIZE); return 0; } static int bt_hci_features_req(struct bt_hci_s *hci, uint16_t handle) { struct bt_device_s *slave; evt_read_remote_features_complete params; if (bt_hci_handle_bad(hci, handle)) return -ENODEV; slave = bt_hci_remote_dev(hci, handle); bt_hci_event_status(hci, HCI_SUCCESS); params.status = HCI_SUCCESS; params.handle = HNDL(handle); params.features[0] = (slave->lmp_caps >> 0) & 0xff; params.features[1] = (slave->lmp_caps >> 8) & 0xff; params.features[2] = (slave->lmp_caps >> 16) & 0xff; params.features[3] = (slave->lmp_caps >> 24) & 0xff; params.features[4] = (slave->lmp_caps >> 32) & 0xff; params.features[5] = (slave->lmp_caps >> 40) & 0xff; params.features[6] = (slave->lmp_caps >> 48) & 0xff; params.features[7] = (slave->lmp_caps >> 56) & 0xff; bt_hci_event(hci, EVT_READ_REMOTE_FEATURES_COMPLETE, &params, EVT_READ_REMOTE_FEATURES_COMPLETE_SIZE); return 0; } static int bt_hci_version_req(struct bt_hci_s *hci, uint16_t handle) { evt_read_remote_version_complete params; if (bt_hci_handle_bad(hci, handle)) return -ENODEV; bt_hci_remote_dev(hci, handle); bt_hci_event_status(hci, HCI_SUCCESS); params.status = HCI_SUCCESS; params.handle = HNDL(handle); params.lmp_ver = 0x03; params.manufacturer = cpu_to_le16(0xa000); params.lmp_subver = cpu_to_le16(0xa607); bt_hci_event(hci, EVT_READ_REMOTE_VERSION_COMPLETE, &params, EVT_READ_REMOTE_VERSION_COMPLETE_SIZE); return 0; } static int bt_hci_clkoffset_req(struct bt_hci_s *hci, uint16_t handle) { struct bt_device_s *slave; evt_read_clock_offset_complete params; if (bt_hci_handle_bad(hci, handle)) return -ENODEV; slave = bt_hci_remote_dev(hci, handle); bt_hci_event_status(hci, HCI_SUCCESS); params.status = HCI_SUCCESS; params.handle = HNDL(handle); /* TODO: return the clkoff *differenece* */ params.clock_offset = slave->clkoff; /* Note: no swapping */ bt_hci_event(hci, EVT_READ_CLOCK_OFFSET_COMPLETE, &params, EVT_READ_CLOCK_OFFSET_COMPLETE_SIZE); return 0; } static void bt_hci_event_mode(struct bt_hci_s *hci, struct bt_link_s *link, uint16_t handle) { evt_mode_change params = { .status = HCI_SUCCESS, .handle = HNDL(handle), .mode = link->acl_mode, .interval = cpu_to_le16(link->acl_interval), }; bt_hci_event(hci, EVT_MODE_CHANGE, &params, EVT_MODE_CHANGE_SIZE); } static void bt_hci_lmp_mode_change_master(struct bt_hci_s *hci, struct bt_link_s *link, int mode, uint16_t interval) { link->acl_mode = mode; link->acl_interval = interval; bt_hci_event_mode(hci, link, link->handle); link->slave->lmp_mode_change(link); } static void bt_hci_lmp_mode_change_slave(struct bt_link_s *btlink) { struct bt_hci_link_s *link = (struct bt_hci_link_s *) btlink; struct bt_hci_s *hci = hci_from_device(btlink->slave); bt_hci_event_mode(hci, btlink, link->handle); } static int bt_hci_mode_change(struct bt_hci_s *hci, uint16_t handle, int interval, int mode) { struct bt_hci_master_link_s *link; if (bt_hci_handle_bad(hci, handle) || !bt_hci_role_master(hci, handle)) return -ENODEV; link = &hci->lm.handle[handle & ~HCI_HANDLE_OFFSET]; if (link->link->acl_mode != acl_active) { bt_hci_event_status(hci, HCI_COMMAND_DISALLOWED); return 0; } bt_hci_event_status(hci, HCI_SUCCESS); qemu_mod_timer(link->acl_mode_timer, qemu_get_clock_ns(vm_clock) + muldiv64(interval * 625, get_ticks_per_sec(), 1000000)); bt_hci_lmp_mode_change_master(hci, link->link, mode, interval); return 0; } static int bt_hci_mode_cancel(struct bt_hci_s *hci, uint16_t handle, int mode) { struct bt_hci_master_link_s *link; if (bt_hci_handle_bad(hci, handle) || !bt_hci_role_master(hci, handle)) return -ENODEV; link = &hci->lm.handle[handle & ~HCI_HANDLE_OFFSET]; if (link->link->acl_mode != mode) { bt_hci_event_status(hci, HCI_COMMAND_DISALLOWED); return 0; } bt_hci_event_status(hci, HCI_SUCCESS); qemu_del_timer(link->acl_mode_timer); bt_hci_lmp_mode_change_master(hci, link->link, acl_active, 0); return 0; } static void bt_hci_mode_tick(void *opaque) { struct bt_link_s *link = opaque; struct bt_hci_s *hci = hci_from_device(link->host); bt_hci_lmp_mode_change_master(hci, link, acl_active, 0); } static void bt_hci_reset(struct bt_hci_s *hci) { hci->acl_len = 0; hci->last_cmd = 0; hci->lm.connecting = 0; hci->event_mask[0] = 0xff; hci->event_mask[1] = 0xff; hci->event_mask[2] = 0xff; hci->event_mask[3] = 0xff; hci->event_mask[4] = 0xff; hci->event_mask[5] = 0x1f; hci->event_mask[6] = 0x00; hci->event_mask[7] = 0x00; hci->device.inquiry_scan = 0; hci->device.page_scan = 0; if (hci->device.lmp_name) qemu_free((void *) hci->device.lmp_name); hci->device.lmp_name = NULL; hci->device.class[0] = 0x00; hci->device.class[1] = 0x00; hci->device.class[2] = 0x00; hci->voice_setting = 0x0000; hci->conn_accept_tout = 0x1f40; hci->lm.inquiry_mode = 0x00; hci->psb_handle = 0x000; hci->asb_handle = 0x000; /* XXX: qemu_del_timer(sl->acl_mode_timer); for all links */ qemu_del_timer(hci->lm.inquiry_done); qemu_del_timer(hci->lm.inquiry_next); qemu_del_timer(hci->conn_accept_timer); } static void bt_hci_read_local_version_rp(struct bt_hci_s *hci) { read_local_version_rp lv = { .status = HCI_SUCCESS, .hci_ver = 0x03, .hci_rev = cpu_to_le16(0xa607), .lmp_ver = 0x03, .manufacturer = cpu_to_le16(0xa000), .lmp_subver = cpu_to_le16(0xa607), }; bt_hci_event_complete(hci, &lv, READ_LOCAL_VERSION_RP_SIZE); } static void bt_hci_read_local_commands_rp(struct bt_hci_s *hci) { read_local_commands_rp lc = { .status = HCI_SUCCESS, .commands = { /* Keep updated! */ /* Also, keep in sync with hci->device.lmp_caps in bt_new_hci */ 0xbf, 0x80, 0xf9, 0x03, 0xb2, 0xc0, 0x03, 0xc3, 0x00, 0x0f, 0x80, 0x00, 0xc0, 0x00, 0xe8, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, }; bt_hci_event_complete(hci, &lc, READ_LOCAL_COMMANDS_RP_SIZE); } static void bt_hci_read_local_features_rp(struct bt_hci_s *hci) { read_local_features_rp lf = { .status = HCI_SUCCESS, .features = { (hci->device.lmp_caps >> 0) & 0xff, (hci->device.lmp_caps >> 8) & 0xff, (hci->device.lmp_caps >> 16) & 0xff, (hci->device.lmp_caps >> 24) & 0xff, (hci->device.lmp_caps >> 32) & 0xff, (hci->device.lmp_caps >> 40) & 0xff, (hci->device.lmp_caps >> 48) & 0xff, (hci->device.lmp_caps >> 56) & 0xff, }, }; bt_hci_event_complete(hci, &lf, READ_LOCAL_FEATURES_RP_SIZE); } static void bt_hci_read_local_ext_features_rp(struct bt_hci_s *hci, int page) { read_local_ext_features_rp lef = { .status = HCI_SUCCESS, .page_num = page, .max_page_num = 0x00, .features = { /* Keep updated! */ 0x5f, 0x35, 0x85, 0x7e, 0x9b, 0x19, 0x00, 0x80, }, }; if (page) memset(lef.features, 0, sizeof(lef.features)); bt_hci_event_complete(hci, &lef, READ_LOCAL_EXT_FEATURES_RP_SIZE); } static void bt_hci_read_buffer_size_rp(struct bt_hci_s *hci) { read_buffer_size_rp bs = { /* This can be made configurable, for one standard USB dongle HCI * the four values are cpu_to_le16(0x0180), 0x40, * cpu_to_le16(0x0008), cpu_to_le16(0x0008). */ .status = HCI_SUCCESS, .acl_mtu = cpu_to_le16(0x0200), .sco_mtu = 0, .acl_max_pkt = cpu_to_le16(0x0001), .sco_max_pkt = cpu_to_le16(0x0000), }; bt_hci_event_complete(hci, &bs, READ_BUFFER_SIZE_RP_SIZE); } /* Deprecated in V2.0 (page 661) */ static void bt_hci_read_country_code_rp(struct bt_hci_s *hci) { read_country_code_rp cc ={ .status = HCI_SUCCESS, .country_code = 0x00, /* North America & Europe^1 and Japan */ }; bt_hci_event_complete(hci, &cc, READ_COUNTRY_CODE_RP_SIZE); /* ^1. Except France, sorry */ } static void bt_hci_read_bd_addr_rp(struct bt_hci_s *hci) { read_bd_addr_rp ba = { .status = HCI_SUCCESS, .bdaddr = BAINIT(&hci->device.bd_addr), }; bt_hci_event_complete(hci, &ba, READ_BD_ADDR_RP_SIZE); } static int bt_hci_link_quality_rp(struct bt_hci_s *hci, uint16_t handle) { read_link_quality_rp lq = { .status = HCI_SUCCESS, .handle = HNDL(handle), .link_quality = 0xff, }; if (bt_hci_handle_bad(hci, handle)) lq.status = HCI_NO_CONNECTION; bt_hci_event_complete(hci, &lq, READ_LINK_QUALITY_RP_SIZE); return 0; } /* Generate a Command Complete event with only the Status parameter */ static inline void bt_hci_event_complete_status(struct bt_hci_s *hci, uint8_t status) { bt_hci_event_complete(hci, &status, 1); } static inline void bt_hci_event_complete_conn_cancel(struct bt_hci_s *hci, uint8_t status, bdaddr_t *bd_addr) { create_conn_cancel_rp params = { .status = status, .bdaddr = BAINIT(bd_addr), }; bt_hci_event_complete(hci, &params, CREATE_CONN_CANCEL_RP_SIZE); } static inline void bt_hci_event_auth_complete(struct bt_hci_s *hci, uint16_t handle) { evt_auth_complete params = { .status = HCI_SUCCESS, .handle = HNDL(handle), }; bt_hci_event(hci, EVT_AUTH_COMPLETE, &params, EVT_AUTH_COMPLETE_SIZE); } static inline void bt_hci_event_encrypt_change(struct bt_hci_s *hci, uint16_t handle, uint8_t mode) { evt_encrypt_change params = { .status = HCI_SUCCESS, .handle = HNDL(handle), .encrypt = mode, }; bt_hci_event(hci, EVT_ENCRYPT_CHANGE, &params, EVT_ENCRYPT_CHANGE_SIZE); } static inline void bt_hci_event_complete_name_cancel(struct bt_hci_s *hci, bdaddr_t *bd_addr) { remote_name_req_cancel_rp params = { .status = HCI_INVALID_PARAMETERS, .bdaddr = BAINIT(bd_addr), }; bt_hci_event_complete(hci, &params, REMOTE_NAME_REQ_CANCEL_RP_SIZE); } static inline void bt_hci_event_read_remote_ext_features(struct bt_hci_s *hci, uint16_t handle) { evt_read_remote_ext_features_complete params = { .status = HCI_UNSUPPORTED_FEATURE, .handle = HNDL(handle), /* Rest uninitialised */ }; bt_hci_event(hci, EVT_READ_REMOTE_EXT_FEATURES_COMPLETE, &params, EVT_READ_REMOTE_EXT_FEATURES_COMPLETE_SIZE); } static inline void bt_hci_event_complete_lmp_handle(struct bt_hci_s *hci, uint16_t handle) { read_lmp_handle_rp params = { .status = HCI_NO_CONNECTION, .handle = HNDL(handle), .reserved = 0, /* Rest uninitialised */ }; bt_hci_event_complete(hci, &params, READ_LMP_HANDLE_RP_SIZE); } static inline void bt_hci_event_complete_role_discovery(struct bt_hci_s *hci, int status, uint16_t handle, int master) { role_discovery_rp params = { .status = status, .handle = HNDL(handle), .role = master ? 0x00 : 0x01, }; bt_hci_event_complete(hci, &params, ROLE_DISCOVERY_RP_SIZE); } static inline void bt_hci_event_complete_flush(struct bt_hci_s *hci, int status, uint16_t handle) { flush_rp params = { .status = status, .handle = HNDL(handle), }; bt_hci_event_complete(hci, &params, FLUSH_RP_SIZE); } static inline void bt_hci_event_complete_read_local_name(struct bt_hci_s *hci) { read_local_name_rp params; params.status = HCI_SUCCESS; memset(params.name, 0, sizeof(params.name)); if (hci->device.lmp_name) strncpy(params.name, hci->device.lmp_name, sizeof(params.name)); bt_hci_event_complete(hci, &params, READ_LOCAL_NAME_RP_SIZE); } static inline void bt_hci_event_complete_read_conn_accept_timeout( struct bt_hci_s *hci) { read_conn_accept_timeout_rp params = { .status = HCI_SUCCESS, .timeout = cpu_to_le16(hci->conn_accept_tout), }; bt_hci_event_complete(hci, &params, READ_CONN_ACCEPT_TIMEOUT_RP_SIZE); } static inline void bt_hci_event_complete_read_scan_enable(struct bt_hci_s *hci) { read_scan_enable_rp params = { .status = HCI_SUCCESS, .enable = (hci->device.inquiry_scan ? SCAN_INQUIRY : 0) | (hci->device.page_scan ? SCAN_PAGE : 0), }; bt_hci_event_complete(hci, &params, READ_SCAN_ENABLE_RP_SIZE); } static inline void bt_hci_event_complete_read_local_class(struct bt_hci_s *hci) { read_class_of_dev_rp params; params.status = HCI_SUCCESS; memcpy(params.dev_class, hci->device.class, sizeof(params.dev_class)); bt_hci_event_complete(hci, &params, READ_CLASS_OF_DEV_RP_SIZE); } static inline void bt_hci_event_complete_voice_setting(struct bt_hci_s *hci) { read_voice_setting_rp params = { .status = HCI_SUCCESS, .voice_setting = hci->voice_setting, /* Note: no swapping */ }; bt_hci_event_complete(hci, &params, READ_VOICE_SETTING_RP_SIZE); } static inline void bt_hci_event_complete_read_inquiry_mode( struct bt_hci_s *hci) { read_inquiry_mode_rp params = { .status = HCI_SUCCESS, .mode = hci->lm.inquiry_mode, }; bt_hci_event_complete(hci, &params, READ_INQUIRY_MODE_RP_SIZE); } static inline void bt_hci_event_num_comp_pkts(struct bt_hci_s *hci, uint16_t handle, int packets) { uint16_t buf[EVT_NUM_COMP_PKTS_SIZE(1) / 2 + 1]; evt_num_comp_pkts *params = (void *) ((uint8_t *) buf + 1); params->num_hndl = 1; params->connection->handle = HNDL(handle); params->connection->num_packets = cpu_to_le16(packets); bt_hci_event(hci, EVT_NUM_COMP_PKTS, params, EVT_NUM_COMP_PKTS_SIZE(1)); } static void bt_submit_hci(struct HCIInfo *info, const uint8_t *data, int length) { struct bt_hci_s *hci = hci_from_info(info); uint16_t cmd; int paramlen, i; if (length < HCI_COMMAND_HDR_SIZE) goto short_hci; memcpy(&hci->last_cmd, data, 2); cmd = (data[1] << 8) | data[0]; paramlen = data[2]; if (cmd_opcode_ogf(cmd) == 0 || cmd_opcode_ocf(cmd) == 0) /* NOP */ return; data += HCI_COMMAND_HDR_SIZE; length -= HCI_COMMAND_HDR_SIZE; if (paramlen > length) return; #define PARAM(cmd, param) (((cmd##_cp *) data)->param) #define PARAM16(cmd, param) le16_to_cpup(&PARAM(cmd, param)) #define PARAMHANDLE(cmd) HNDL(PARAM(cmd, handle)) #define LENGTH_CHECK(cmd) if (length < sizeof(cmd##_cp)) goto short_hci /* Note: the supported commands bitmask in bt_hci_read_local_commands_rp * needs to be updated every time a command is implemented here! */ switch (cmd) { case cmd_opcode_pack(OGF_LINK_CTL, OCF_INQUIRY): LENGTH_CHECK(inquiry); if (PARAM(inquiry, length) < 1) { bt_hci_event_complete_status(hci, HCI_INVALID_PARAMETERS); break; } hci->lm.inquire = 1; hci->lm.periodic = 0; hci->lm.responses_left = PARAM(inquiry, num_rsp) ?: INT_MAX; hci->lm.responses = 0; bt_hci_event_status(hci, HCI_SUCCESS); bt_hci_inquiry_start(hci, PARAM(inquiry, length)); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_INQUIRY_CANCEL): if (!hci->lm.inquire || hci->lm.periodic) { fprintf(stderr, "%s: Inquiry Cancel should only be issued after " "the Inquiry command has been issued, a Command " "Status event has been received for the Inquiry " "command, and before the Inquiry Complete event " "occurs", __FUNCTION__); bt_hci_event_complete_status(hci, HCI_COMMAND_DISALLOWED); break; } hci->lm.inquire = 0; qemu_del_timer(hci->lm.inquiry_done); bt_hci_event_complete_status(hci, HCI_SUCCESS); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_PERIODIC_INQUIRY): LENGTH_CHECK(periodic_inquiry); if (!(PARAM(periodic_inquiry, length) < PARAM16(periodic_inquiry, min_period) && PARAM16(periodic_inquiry, min_period) < PARAM16(periodic_inquiry, max_period)) || PARAM(periodic_inquiry, length) < 1 || PARAM16(periodic_inquiry, min_period) < 2 || PARAM16(periodic_inquiry, max_period) < 3) { bt_hci_event_complete_status(hci, HCI_INVALID_PARAMETERS); break; } hci->lm.inquire = 1; hci->lm.periodic = 1; hci->lm.responses_left = PARAM(periodic_inquiry, num_rsp); hci->lm.responses = 0; hci->lm.inquiry_period = PARAM16(periodic_inquiry, max_period); bt_hci_event_complete_status(hci, HCI_SUCCESS); bt_hci_inquiry_start(hci, PARAM(periodic_inquiry, length)); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_EXIT_PERIODIC_INQUIRY): if (!hci->lm.inquire || !hci->lm.periodic) { fprintf(stderr, "%s: Inquiry Cancel should only be issued after " "the Inquiry command has been issued, a Command " "Status event has been received for the Inquiry " "command, and before the Inquiry Complete event " "occurs", __FUNCTION__); bt_hci_event_complete_status(hci, HCI_COMMAND_DISALLOWED); break; } hci->lm.inquire = 0; qemu_del_timer(hci->lm.inquiry_done); qemu_del_timer(hci->lm.inquiry_next); bt_hci_event_complete_status(hci, HCI_SUCCESS); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_CREATE_CONN): LENGTH_CHECK(create_conn); if (hci->lm.connecting >= HCI_HANDLES_MAX) { bt_hci_event_status(hci, HCI_REJECTED_LIMITED_RESOURCES); break; } bt_hci_event_status(hci, HCI_SUCCESS); if (bt_hci_connect(hci, &PARAM(create_conn, bdaddr))) bt_hci_connection_reject_event(hci, &PARAM(create_conn, bdaddr)); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_DISCONNECT): LENGTH_CHECK(disconnect); if (bt_hci_handle_bad(hci, PARAMHANDLE(disconnect))) { bt_hci_event_status(hci, HCI_NO_CONNECTION); break; } bt_hci_event_status(hci, HCI_SUCCESS); bt_hci_disconnect(hci, PARAMHANDLE(disconnect), PARAM(disconnect, reason)); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_CREATE_CONN_CANCEL): LENGTH_CHECK(create_conn_cancel); if (bt_hci_lmp_connection_ready(hci, &PARAM(create_conn_cancel, bdaddr))) { for (i = 0; i < HCI_HANDLES_MAX; i ++) if (bt_hci_role_master(hci, i) && hci->lm.handle[i].link && !bacmp(&hci->lm.handle[i].link->slave->bd_addr, &PARAM(create_conn_cancel, bdaddr))) break; bt_hci_event_complete_conn_cancel(hci, i < HCI_HANDLES_MAX ? HCI_ACL_CONNECTION_EXISTS : HCI_NO_CONNECTION, &PARAM(create_conn_cancel, bdaddr)); } else bt_hci_event_complete_conn_cancel(hci, HCI_SUCCESS, &PARAM(create_conn_cancel, bdaddr)); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_ACCEPT_CONN_REQ): LENGTH_CHECK(accept_conn_req); if (!hci->conn_req_host || bacmp(&PARAM(accept_conn_req, bdaddr), &hci->conn_req_host->bd_addr)) { bt_hci_event_status(hci, HCI_INVALID_PARAMETERS); break; } bt_hci_event_status(hci, HCI_SUCCESS); bt_hci_connection_accept(hci, hci->conn_req_host); hci->conn_req_host = NULL; break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_REJECT_CONN_REQ): LENGTH_CHECK(reject_conn_req); if (!hci->conn_req_host || bacmp(&PARAM(reject_conn_req, bdaddr), &hci->conn_req_host->bd_addr)) { bt_hci_event_status(hci, HCI_INVALID_PARAMETERS); break; } bt_hci_event_status(hci, HCI_SUCCESS); bt_hci_connection_reject(hci, hci->conn_req_host, PARAM(reject_conn_req, reason)); bt_hci_connection_reject_event(hci, &hci->conn_req_host->bd_addr); hci->conn_req_host = NULL; break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_AUTH_REQUESTED): LENGTH_CHECK(auth_requested); if (bt_hci_handle_bad(hci, PARAMHANDLE(auth_requested))) bt_hci_event_status(hci, HCI_NO_CONNECTION); else { bt_hci_event_status(hci, HCI_SUCCESS); bt_hci_event_auth_complete(hci, PARAMHANDLE(auth_requested)); } break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_SET_CONN_ENCRYPT): LENGTH_CHECK(set_conn_encrypt); if (bt_hci_handle_bad(hci, PARAMHANDLE(set_conn_encrypt))) bt_hci_event_status(hci, HCI_NO_CONNECTION); else { bt_hci_event_status(hci, HCI_SUCCESS); bt_hci_event_encrypt_change(hci, PARAMHANDLE(set_conn_encrypt), PARAM(set_conn_encrypt, encrypt)); } break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_REMOTE_NAME_REQ): LENGTH_CHECK(remote_name_req); if (bt_hci_name_req(hci, &PARAM(remote_name_req, bdaddr))) bt_hci_event_status(hci, HCI_NO_CONNECTION); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_REMOTE_NAME_REQ_CANCEL): LENGTH_CHECK(remote_name_req_cancel); bt_hci_event_complete_name_cancel(hci, &PARAM(remote_name_req_cancel, bdaddr)); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_READ_REMOTE_FEATURES): LENGTH_CHECK(read_remote_features); if (bt_hci_features_req(hci, PARAMHANDLE(read_remote_features))) bt_hci_event_status(hci, HCI_NO_CONNECTION); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_READ_REMOTE_EXT_FEATURES): LENGTH_CHECK(read_remote_ext_features); if (bt_hci_handle_bad(hci, PARAMHANDLE(read_remote_ext_features))) bt_hci_event_status(hci, HCI_NO_CONNECTION); else { bt_hci_event_status(hci, HCI_SUCCESS); bt_hci_event_read_remote_ext_features(hci, PARAMHANDLE(read_remote_ext_features)); } break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_READ_REMOTE_VERSION): LENGTH_CHECK(read_remote_version); if (bt_hci_version_req(hci, PARAMHANDLE(read_remote_version))) bt_hci_event_status(hci, HCI_NO_CONNECTION); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_READ_CLOCK_OFFSET): LENGTH_CHECK(read_clock_offset); if (bt_hci_clkoffset_req(hci, PARAMHANDLE(read_clock_offset))) bt_hci_event_status(hci, HCI_NO_CONNECTION); break; case cmd_opcode_pack(OGF_LINK_CTL, OCF_READ_LMP_HANDLE): LENGTH_CHECK(read_lmp_handle); /* TODO: */ bt_hci_event_complete_lmp_handle(hci, PARAMHANDLE(read_lmp_handle)); break; case cmd_opcode_pack(OGF_LINK_POLICY, OCF_HOLD_MODE): LENGTH_CHECK(hold_mode); if (PARAM16(hold_mode, min_interval) > PARAM16(hold_mode, max_interval) || PARAM16(hold_mode, min_interval) < 0x0002 || PARAM16(hold_mode, max_interval) > 0xff00 || (PARAM16(hold_mode, min_interval) & 1) || (PARAM16(hold_mode, max_interval) & 1)) { bt_hci_event_status(hci, HCI_INVALID_PARAMETERS); break; } if (bt_hci_mode_change(hci, PARAMHANDLE(hold_mode), PARAM16(hold_mode, max_interval), acl_hold)) bt_hci_event_status(hci, HCI_NO_CONNECTION); break; case cmd_opcode_pack(OGF_LINK_POLICY, OCF_PARK_MODE): LENGTH_CHECK(park_mode); if (PARAM16(park_mode, min_interval) > PARAM16(park_mode, max_interval) || PARAM16(park_mode, min_interval) < 0x000e || (PARAM16(park_mode, min_interval) & 1) || (PARAM16(park_mode, max_interval) & 1)) { bt_hci_event_status(hci, HCI_INVALID_PARAMETERS); break; } if (bt_hci_mode_change(hci, PARAMHANDLE(park_mode), PARAM16(park_mode, max_interval), acl_parked)) bt_hci_event_status(hci, HCI_NO_CONNECTION); break; case cmd_opcode_pack(OGF_LINK_POLICY, OCF_EXIT_PARK_MODE): LENGTH_CHECK(exit_park_mode); if (bt_hci_mode_cancel(hci, PARAMHANDLE(exit_park_mode), acl_parked)) bt_hci_event_status(hci, HCI_NO_CONNECTION); break; case cmd_opcode_pack(OGF_LINK_POLICY, OCF_ROLE_DISCOVERY): LENGTH_CHECK(role_discovery); if (bt_hci_handle_bad(hci, PARAMHANDLE(role_discovery))) bt_hci_event_complete_role_discovery(hci, HCI_NO_CONNECTION, PARAMHANDLE(role_discovery), 0); else bt_hci_event_complete_role_discovery(hci, HCI_SUCCESS, PARAMHANDLE(role_discovery), bt_hci_role_master(hci, PARAMHANDLE(role_discovery))); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_SET_EVENT_MASK): LENGTH_CHECK(set_event_mask); memcpy(hci->event_mask, PARAM(set_event_mask, mask), 8); bt_hci_event_complete_status(hci, HCI_SUCCESS); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_RESET): bt_hci_reset(hci); bt_hci_event_status(hci, HCI_SUCCESS); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_SET_EVENT_FLT): if (length >= 1 && PARAM(set_event_flt, flt_type) == FLT_CLEAR_ALL) /* No length check */; else LENGTH_CHECK(set_event_flt); /* Filters are not implemented */ bt_hci_event_complete_status(hci, HCI_SUCCESS); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_FLUSH): LENGTH_CHECK(flush); if (bt_hci_handle_bad(hci, PARAMHANDLE(flush))) bt_hci_event_complete_flush(hci, HCI_NO_CONNECTION, PARAMHANDLE(flush)); else { /* TODO: ordering? */ bt_hci_event(hci, EVT_FLUSH_OCCURRED, &PARAM(flush, handle), EVT_FLUSH_OCCURRED_SIZE); bt_hci_event_complete_flush(hci, HCI_SUCCESS, PARAMHANDLE(flush)); } break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_CHANGE_LOCAL_NAME): LENGTH_CHECK(change_local_name); if (hci->device.lmp_name) qemu_free((void *) hci->device.lmp_name); hci->device.lmp_name = qemu_strndup(PARAM(change_local_name, name), sizeof(PARAM(change_local_name, name))); bt_hci_event_complete_status(hci, HCI_SUCCESS); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_LOCAL_NAME): bt_hci_event_complete_read_local_name(hci); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_CONN_ACCEPT_TIMEOUT): bt_hci_event_complete_read_conn_accept_timeout(hci); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_CONN_ACCEPT_TIMEOUT): /* TODO */ LENGTH_CHECK(write_conn_accept_timeout); if (PARAM16(write_conn_accept_timeout, timeout) < 0x0001 || PARAM16(write_conn_accept_timeout, timeout) > 0xb540) { bt_hci_event_complete_status(hci, HCI_INVALID_PARAMETERS); break; } hci->conn_accept_tout = PARAM16(write_conn_accept_timeout, timeout); bt_hci_event_complete_status(hci, HCI_SUCCESS); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_SCAN_ENABLE): bt_hci_event_complete_read_scan_enable(hci); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_SCAN_ENABLE): LENGTH_CHECK(write_scan_enable); /* TODO: check that the remaining bits are all 0 */ hci->device.inquiry_scan = !!(PARAM(write_scan_enable, scan_enable) & SCAN_INQUIRY); hci->device.page_scan = !!(PARAM(write_scan_enable, scan_enable) & SCAN_PAGE); bt_hci_event_complete_status(hci, HCI_SUCCESS); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_CLASS_OF_DEV): bt_hci_event_complete_read_local_class(hci); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_CLASS_OF_DEV): LENGTH_CHECK(write_class_of_dev); memcpy(hci->device.class, PARAM(write_class_of_dev, dev_class), sizeof(PARAM(write_class_of_dev, dev_class))); bt_hci_event_complete_status(hci, HCI_SUCCESS); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_VOICE_SETTING): bt_hci_event_complete_voice_setting(hci); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_VOICE_SETTING): LENGTH_CHECK(write_voice_setting); hci->voice_setting = PARAM(write_voice_setting, voice_setting); bt_hci_event_complete_status(hci, HCI_SUCCESS); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_HOST_NUMBER_OF_COMPLETED_PACKETS): if (length < data[0] * 2 + 1) goto short_hci; for (i = 0; i < data[0]; i ++) if (bt_hci_handle_bad(hci, data[i * 2 + 1] | (data[i * 2 + 2] << 8))) bt_hci_event_complete_status(hci, HCI_INVALID_PARAMETERS); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_INQUIRY_MODE): /* Only if (local_features[3] & 0x40) && (local_commands[12] & 0x40) * else * goto unknown_command */ bt_hci_event_complete_read_inquiry_mode(hci); break; case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_INQUIRY_MODE): /* Only if (local_features[3] & 0x40) && (local_commands[12] & 0x80) * else * goto unknown_command */ LENGTH_CHECK(write_inquiry_mode); if (PARAM(write_inquiry_mode, mode) > 0x01) { bt_hci_event_complete_status(hci, HCI_INVALID_PARAMETERS); break; } hci->lm.inquiry_mode = PARAM(write_inquiry_mode, mode); bt_hci_event_complete_status(hci, HCI_SUCCESS); break; case cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_LOCAL_VERSION): bt_hci_read_local_version_rp(hci); break; case cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_LOCAL_COMMANDS): bt_hci_read_local_commands_rp(hci); break; case cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_LOCAL_FEATURES): bt_hci_read_local_features_rp(hci); break; case cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_LOCAL_EXT_FEATURES): LENGTH_CHECK(read_local_ext_features); bt_hci_read_local_ext_features_rp(hci, PARAM(read_local_ext_features, page_num)); break; case cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_BUFFER_SIZE): bt_hci_read_buffer_size_rp(hci); break; case cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_COUNTRY_CODE): bt_hci_read_country_code_rp(hci); break; case cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_BD_ADDR): bt_hci_read_bd_addr_rp(hci); break; case cmd_opcode_pack(OGF_STATUS_PARAM, OCF_READ_LINK_QUALITY): LENGTH_CHECK(read_link_quality); bt_hci_link_quality_rp(hci, PARAMHANDLE(read_link_quality)); break; default: bt_hci_event_status(hci, HCI_UNKNOWN_COMMAND); break; short_hci: fprintf(stderr, "%s: HCI packet too short (%iB)\n", __FUNCTION__, length); bt_hci_event_status(hci, HCI_INVALID_PARAMETERS); break; } } /* We could perform fragmentation here, we can't do "recombination" because * at this layer the length of the payload is not know ahead, so we only * know that a packet contained the last fragment of the SDU when the next * SDU starts. */ static inline void bt_hci_lmp_acl_data(struct bt_hci_s *hci, uint16_t handle, const uint8_t *data, int start, int len) { struct hci_acl_hdr *pkt = (void *) hci->acl_buf; /* TODO: packet flags */ /* TODO: avoid memcpy'ing */ if (len + HCI_ACL_HDR_SIZE > sizeof(hci->acl_buf)) { fprintf(stderr, "%s: can't take ACL packets %i bytes long\n", __FUNCTION__, len); return; } memcpy(hci->acl_buf + HCI_ACL_HDR_SIZE, data, len); pkt->handle = cpu_to_le16( acl_handle_pack(handle, start ? ACL_START : ACL_CONT)); pkt->dlen = cpu_to_le16(len); hci->info.acl_recv(hci->info.opaque, hci->acl_buf, len + HCI_ACL_HDR_SIZE); } static void bt_hci_lmp_acl_data_slave(struct bt_link_s *btlink, const uint8_t *data, int start, int len) { struct bt_hci_link_s *link = (struct bt_hci_link_s *) btlink; bt_hci_lmp_acl_data(hci_from_device(btlink->slave), link->handle, data, start, len); } static void bt_hci_lmp_acl_data_host(struct bt_link_s *link, const uint8_t *data, int start, int len) { bt_hci_lmp_acl_data(hci_from_device(link->host), link->handle, data, start, len); } static void bt_submit_acl(struct HCIInfo *info, const uint8_t *data, int length) { struct bt_hci_s *hci = hci_from_info(info); uint16_t handle; int datalen, flags; struct bt_link_s *link; if (length < HCI_ACL_HDR_SIZE) { fprintf(stderr, "%s: ACL packet too short (%iB)\n", __FUNCTION__, length); return; } handle = acl_handle((data[1] << 8) | data[0]); flags = acl_flags((data[1] << 8) | data[0]); datalen = (data[3] << 8) | data[2]; data += HCI_ACL_HDR_SIZE; length -= HCI_ACL_HDR_SIZE; if (bt_hci_handle_bad(hci, handle)) { fprintf(stderr, "%s: invalid ACL handle %03x\n", __FUNCTION__, handle); /* TODO: signal an error */ return; } handle &= ~HCI_HANDLE_OFFSET; if (datalen > length) { fprintf(stderr, "%s: ACL packet too short (%iB < %iB)\n", __FUNCTION__, length, datalen); return; } link = hci->lm.handle[handle].link; if ((flags & ~3) == ACL_ACTIVE_BCAST) { if (!hci->asb_handle) hci->asb_handle = handle; else if (handle != hci->asb_handle) { fprintf(stderr, "%s: Bad handle %03x in Active Slave Broadcast\n", __FUNCTION__, handle); /* TODO: signal an error */ return; } /* TODO */ } if ((flags & ~3) == ACL_PICO_BCAST) { if (!hci->psb_handle) hci->psb_handle = handle; else if (handle != hci->psb_handle) { fprintf(stderr, "%s: Bad handle %03x in Parked Slave Broadcast\n", __FUNCTION__, handle); /* TODO: signal an error */ return; } /* TODO */ } /* TODO: increase counter and send EVT_NUM_COMP_PKTS */ bt_hci_event_num_comp_pkts(hci, handle | HCI_HANDLE_OFFSET, 1); /* Do this last as it can trigger further events even in this HCI */ hci->lm.handle[handle].lmp_acl_data(link, data, (flags & 3) == ACL_START, length); } static void bt_submit_sco(struct HCIInfo *info, const uint8_t *data, int length) { struct bt_hci_s *hci = hci_from_info(info); uint16_t handle; int datalen; if (length < 3) return; handle = acl_handle((data[1] << 8) | data[0]); datalen = data[2]; length -= 3; if (bt_hci_handle_bad(hci, handle)) { fprintf(stderr, "%s: invalid SCO handle %03x\n", __FUNCTION__, handle); return; } if (datalen > length) { fprintf(stderr, "%s: SCO packet too short (%iB < %iB)\n", __FUNCTION__, length, datalen); return; } /* TODO */ /* TODO: increase counter and send EVT_NUM_COMP_PKTS if synchronous * Flow Control is enabled. * (See Read/Write_Synchronous_Flow_Control_Enable on page 513 and * page 514.) */ } static uint8_t *bt_hci_evt_packet(void *opaque) { /* TODO: allocate a packet from upper layer */ struct bt_hci_s *s = opaque; return s->evt_buf; } static void bt_hci_evt_submit(void *opaque, int len) { /* TODO: notify upper layer */ struct bt_hci_s *s = opaque; s->info.evt_recv(s->info.opaque, s->evt_buf, len); } static int bt_hci_bdaddr_set(struct HCIInfo *info, const uint8_t *bd_addr) { struct bt_hci_s *hci = hci_from_info(info); bacpy(&hci->device.bd_addr, (const bdaddr_t *) bd_addr); return 0; } static void bt_hci_done(struct HCIInfo *info); static void bt_hci_destroy(struct bt_device_s *dev) { struct bt_hci_s *hci = hci_from_device(dev); bt_hci_done(&hci->info); } struct HCIInfo *bt_new_hci(struct bt_scatternet_s *net) { struct bt_hci_s *s = qemu_mallocz(sizeof(struct bt_hci_s)); s->lm.inquiry_done = qemu_new_timer_ns(vm_clock, bt_hci_inquiry_done, s); s->lm.inquiry_next = qemu_new_timer_ns(vm_clock, bt_hci_inquiry_next, s); s->conn_accept_timer = qemu_new_timer_ns(vm_clock, bt_hci_conn_accept_timeout, s); s->evt_packet = bt_hci_evt_packet; s->evt_submit = bt_hci_evt_submit; s->opaque = s; bt_device_init(&s->device, net); s->device.lmp_connection_request = bt_hci_lmp_connection_request; s->device.lmp_connection_complete = bt_hci_lmp_connection_complete; s->device.lmp_disconnect_master = bt_hci_lmp_disconnect_host; s->device.lmp_disconnect_slave = bt_hci_lmp_disconnect_slave; s->device.lmp_acl_data = bt_hci_lmp_acl_data_slave; s->device.lmp_acl_resp = bt_hci_lmp_acl_data_host; s->device.lmp_mode_change = bt_hci_lmp_mode_change_slave; /* Keep updated! */ /* Also keep in sync with supported commands bitmask in * bt_hci_read_local_commands_rp */ s->device.lmp_caps = 0x8000199b7e85355fll; bt_hci_reset(s); s->info.cmd_send = bt_submit_hci; s->info.sco_send = bt_submit_sco; s->info.acl_send = bt_submit_acl; s->info.bdaddr_set = bt_hci_bdaddr_set; s->device.handle_destroy = bt_hci_destroy; return &s->info; } static void bt_hci_done(struct HCIInfo *info) { struct bt_hci_s *hci = hci_from_info(info); int handle; bt_device_done(&hci->device); if (hci->device.lmp_name) qemu_free((void *) hci->device.lmp_name); /* Be gentle and send DISCONNECT to all connected peers and those * currently waiting for us to accept or reject a connection request. * This frees the links. */ if (hci->conn_req_host) { bt_hci_connection_reject(hci, hci->conn_req_host, HCI_OE_POWER_OFF); return; } for (handle = HCI_HANDLE_OFFSET; handle < (HCI_HANDLE_OFFSET | HCI_HANDLES_MAX); handle ++) if (!bt_hci_handle_bad(hci, handle)) bt_hci_disconnect(hci, handle, HCI_OE_POWER_OFF); /* TODO: this is not enough actually, there may be slaves from whom * we have requested a connection who will soon (or not) respond with * an accept or a reject, so we should also check if hci->lm.connecting * is non-zero and if so, avoid freeing the hci but otherwise disappear * from all qemu social life (e.g. stop scanning and request to be * removed from s->device.net) and arrange for * s->device.lmp_connection_complete to free the remaining bits once * hci->lm.awaiting_bdaddr[] is empty. */ qemu_free_timer(hci->lm.inquiry_done); qemu_free_timer(hci->lm.inquiry_next); qemu_free_timer(hci->conn_accept_timer); qemu_free(hci); }
whitestonelee/tlb_analyzer
qemu/hw/bt-hci.c
C
gpl-3.0
69,187
/* */ require("../../modules/js.array.statics"); module.exports = require("../../modules/$").core.Array.filter;
pauldijou/outdated
test/basic/jspm_packages/npm/core-js@0.9.18/library/fn/array/filter.js
JavaScript
apache-2.0
113
var parent = require('../../es/reflect'); module.exports = parent;
BigBoss424/portfolio
v8/development/node_modules/jimp/node_modules/core-js/stable/reflect/index.js
JavaScript
apache-2.0
68
/* * Virtio SCSI HBA driver * * Copyright IBM Corp. 2010 * Copyright Red Hat, Inc. 2011 * * Authors: * Stefan Hajnoczi <stefanha@linux.vnet.ibm.com> * Paolo Bonzini <pbonzini@redhat.com> * * This work is licensed under the terms of the GNU GPL, version 2 or later. * See the COPYING file in the top-level directory. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/slab.h> #include <linux/mempool.h> #include <linux/virtio.h> #include <linux/virtio_ids.h> #include <linux/virtio_config.h> #include <linux/virtio_scsi.h> #include <linux/cpu.h> #include <scsi/scsi_host.h> #include <scsi/scsi_device.h> #include <scsi/scsi_cmnd.h> #define VIRTIO_SCSI_MEMPOOL_SZ 64 #define VIRTIO_SCSI_EVENT_LEN 8 #define VIRTIO_SCSI_VQ_BASE 2 /* Command queue element */ struct virtio_scsi_cmd { struct scsi_cmnd *sc; struct completion *comp; union { struct virtio_scsi_cmd_req cmd; struct virtio_scsi_ctrl_tmf_req tmf; struct virtio_scsi_ctrl_an_req an; } req; union { struct virtio_scsi_cmd_resp cmd; struct virtio_scsi_ctrl_tmf_resp tmf; struct virtio_scsi_ctrl_an_resp an; struct virtio_scsi_event evt; } resp; } ____cacheline_aligned_in_smp; struct virtio_scsi_event_node { struct virtio_scsi *vscsi; struct virtio_scsi_event event; struct work_struct work; }; struct virtio_scsi_vq { /* Protects vq */ spinlock_t vq_lock; struct virtqueue *vq; }; /* * Per-target queue state. * * This struct holds the data needed by the queue steering policy. When a * target is sent multiple requests, we need to drive them to the same queue so * that FIFO processing order is kept. However, if a target was idle, we can * choose a queue arbitrarily. In this case the queue is chosen according to * the current VCPU, so the driver expects the number of request queues to be * equal to the number of VCPUs. This makes it easy and fast to select the * queue, and also lets the driver optimize the IRQ affinity for the virtqueues * (each virtqueue's affinity is set to the CPU that "owns" the queue). * * An interesting effect of this policy is that only writes to req_vq need to * take the tgt_lock. Read can be done outside the lock because: * * - writes of req_vq only occur when atomic_inc_return(&tgt->reqs) returns 1. * In that case, no other CPU is reading req_vq: even if they were in * virtscsi_queuecommand_multi, they would be spinning on tgt_lock. * * - reads of req_vq only occur when the target is not idle (reqs != 0). * A CPU that enters virtscsi_queuecommand_multi will not modify req_vq. * * Similarly, decrements of reqs are never concurrent with writes of req_vq. * Thus they can happen outside the tgt_lock, provided of course we make reqs * an atomic_t. */ struct virtio_scsi_target_state { /* This spinlock never held at the same time as vq_lock. */ spinlock_t tgt_lock; /* Count of outstanding requests. */ atomic_t reqs; /* Currently active virtqueue for requests sent to this target. */ struct virtio_scsi_vq *req_vq; }; /* Driver instance state */ struct virtio_scsi { struct virtio_device *vdev; /* Get some buffers ready for event vq */ struct virtio_scsi_event_node event_list[VIRTIO_SCSI_EVENT_LEN]; u32 num_queues; /* If the affinity hint is set for virtqueues */ bool affinity_hint_set; /* CPU hotplug notifier */ struct notifier_block nb; struct virtio_scsi_vq ctrl_vq; struct virtio_scsi_vq event_vq; struct virtio_scsi_vq req_vqs[]; }; static struct kmem_cache *virtscsi_cmd_cache; static mempool_t *virtscsi_cmd_pool; static inline struct Scsi_Host *virtio_scsi_host(struct virtio_device *vdev) { return vdev->priv; } static void virtscsi_compute_resid(struct scsi_cmnd *sc, u32 resid) { if (!resid) return; if (!scsi_bidi_cmnd(sc)) { scsi_set_resid(sc, resid); return; } scsi_in(sc)->resid = min(resid, scsi_in(sc)->length); scsi_out(sc)->resid = resid - scsi_in(sc)->resid; } /** * virtscsi_complete_cmd - finish a scsi_cmd and invoke scsi_done * * Called with vq_lock held. */ static void virtscsi_complete_cmd(struct virtio_scsi *vscsi, void *buf) { struct virtio_scsi_cmd *cmd = buf; struct scsi_cmnd *sc = cmd->sc; struct virtio_scsi_cmd_resp *resp = &cmd->resp.cmd; struct virtio_scsi_target_state *tgt = scsi_target(sc->device)->hostdata; dev_dbg(&sc->device->sdev_gendev, "cmd %p response %u status %#02x sense_len %u\n", sc, resp->response, resp->status, resp->sense_len); sc->result = resp->status; virtscsi_compute_resid(sc, resp->resid); switch (resp->response) { case VIRTIO_SCSI_S_OK: set_host_byte(sc, DID_OK); break; case VIRTIO_SCSI_S_OVERRUN: set_host_byte(sc, DID_ERROR); break; case VIRTIO_SCSI_S_ABORTED: set_host_byte(sc, DID_ABORT); break; case VIRTIO_SCSI_S_BAD_TARGET: set_host_byte(sc, DID_BAD_TARGET); break; case VIRTIO_SCSI_S_RESET: set_host_byte(sc, DID_RESET); break; case VIRTIO_SCSI_S_BUSY: set_host_byte(sc, DID_BUS_BUSY); break; case VIRTIO_SCSI_S_TRANSPORT_FAILURE: set_host_byte(sc, DID_TRANSPORT_DISRUPTED); break; case VIRTIO_SCSI_S_TARGET_FAILURE: set_host_byte(sc, DID_TARGET_FAILURE); break; case VIRTIO_SCSI_S_NEXUS_FAILURE: set_host_byte(sc, DID_NEXUS_FAILURE); break; default: scmd_printk(KERN_WARNING, sc, "Unknown response %d", resp->response); /* fall through */ case VIRTIO_SCSI_S_FAILURE: set_host_byte(sc, DID_ERROR); break; } WARN_ON(resp->sense_len > VIRTIO_SCSI_SENSE_SIZE); if (sc->sense_buffer) { memcpy(sc->sense_buffer, resp->sense, min_t(u32, resp->sense_len, VIRTIO_SCSI_SENSE_SIZE)); if (resp->sense_len) set_driver_byte(sc, DRIVER_SENSE); } mempool_free(cmd, virtscsi_cmd_pool); sc->scsi_done(sc); atomic_dec(&tgt->reqs); } static void virtscsi_vq_done(struct virtio_scsi *vscsi, struct virtio_scsi_vq *virtscsi_vq, void (*fn)(struct virtio_scsi *vscsi, void *buf)) { void *buf; unsigned int len; unsigned long flags; struct virtqueue *vq = virtscsi_vq->vq; spin_lock_irqsave(&virtscsi_vq->vq_lock, flags); do { virtqueue_disable_cb(vq); while ((buf = virtqueue_get_buf(vq, &len)) != NULL) fn(vscsi, buf); } while (!virtqueue_enable_cb(vq)); spin_unlock_irqrestore(&virtscsi_vq->vq_lock, flags); } static void virtscsi_req_done(struct virtqueue *vq) { struct Scsi_Host *sh = virtio_scsi_host(vq->vdev); struct virtio_scsi *vscsi = shost_priv(sh); int index = vq->index - VIRTIO_SCSI_VQ_BASE; struct virtio_scsi_vq *req_vq = &vscsi->req_vqs[index]; /* * Read req_vq before decrementing the reqs field in * virtscsi_complete_cmd. * * With barriers: * * CPU #0 virtscsi_queuecommand_multi (CPU #1) * ------------------------------------------------------------ * lock vq_lock * read req_vq * read reqs (reqs = 1) * write reqs (reqs = 0) * increment reqs (reqs = 1) * write req_vq * * Possible reordering without barriers: * * CPU #0 virtscsi_queuecommand_multi (CPU #1) * ------------------------------------------------------------ * lock vq_lock * read reqs (reqs = 1) * write reqs (reqs = 0) * increment reqs (reqs = 1) * write req_vq * read (wrong) req_vq * * We do not need a full smp_rmb, because req_vq is required to get * to tgt->reqs: tgt is &vscsi->tgt[sc->device->id], where sc is stored * in the virtqueue as the user token. */ smp_read_barrier_depends(); virtscsi_vq_done(vscsi, req_vq, virtscsi_complete_cmd); }; static void virtscsi_complete_free(struct virtio_scsi *vscsi, void *buf) { struct virtio_scsi_cmd *cmd = buf; if (cmd->comp) complete_all(cmd->comp); else mempool_free(cmd, virtscsi_cmd_pool); } static void virtscsi_ctrl_done(struct virtqueue *vq) { struct Scsi_Host *sh = virtio_scsi_host(vq->vdev); struct virtio_scsi *vscsi = shost_priv(sh); virtscsi_vq_done(vscsi, &vscsi->ctrl_vq, virtscsi_complete_free); }; static int virtscsi_kick_event(struct virtio_scsi *vscsi, struct virtio_scsi_event_node *event_node) { int err; struct scatterlist sg; unsigned long flags; sg_init_one(&sg, &event_node->event, sizeof(struct virtio_scsi_event)); spin_lock_irqsave(&vscsi->event_vq.vq_lock, flags); err = virtqueue_add_inbuf(vscsi->event_vq.vq, &sg, 1, event_node, GFP_ATOMIC); if (!err) virtqueue_kick(vscsi->event_vq.vq); spin_unlock_irqrestore(&vscsi->event_vq.vq_lock, flags); return err; } static int virtscsi_kick_event_all(struct virtio_scsi *vscsi) { int i; for (i = 0; i < VIRTIO_SCSI_EVENT_LEN; i++) { vscsi->event_list[i].vscsi = vscsi; virtscsi_kick_event(vscsi, &vscsi->event_list[i]); } return 0; } static void virtscsi_cancel_event_work(struct virtio_scsi *vscsi) { int i; for (i = 0; i < VIRTIO_SCSI_EVENT_LEN; i++) cancel_work_sync(&vscsi->event_list[i].work); } static void virtscsi_handle_transport_reset(struct virtio_scsi *vscsi, struct virtio_scsi_event *event) { struct scsi_device *sdev; struct Scsi_Host *shost = virtio_scsi_host(vscsi->vdev); unsigned int target = event->lun[1]; unsigned int lun = (event->lun[2] << 8) | event->lun[3]; switch (event->reason) { case VIRTIO_SCSI_EVT_RESET_RESCAN: scsi_add_device(shost, 0, target, lun); break; case VIRTIO_SCSI_EVT_RESET_REMOVED: sdev = scsi_device_lookup(shost, 0, target, lun); if (sdev) { scsi_remove_device(sdev); scsi_device_put(sdev); } else { pr_err("SCSI device %d 0 %d %d not found\n", shost->host_no, target, lun); } break; default: pr_info("Unsupport virtio scsi event reason %x\n", event->reason); } } static void virtscsi_handle_param_change(struct virtio_scsi *vscsi, struct virtio_scsi_event *event) { struct scsi_device *sdev; struct Scsi_Host *shost = virtio_scsi_host(vscsi->vdev); unsigned int target = event->lun[1]; unsigned int lun = (event->lun[2] << 8) | event->lun[3]; u8 asc = event->reason & 255; u8 ascq = event->reason >> 8; sdev = scsi_device_lookup(shost, 0, target, lun); if (!sdev) { pr_err("SCSI device %d 0 %d %d not found\n", shost->host_no, target, lun); return; } /* Handle "Parameters changed", "Mode parameters changed", and "Capacity data has changed". */ if (asc == 0x2a && (ascq == 0x00 || ascq == 0x01 || ascq == 0x09)) scsi_rescan_device(&sdev->sdev_gendev); scsi_device_put(sdev); } static void virtscsi_handle_event(struct work_struct *work) { struct virtio_scsi_event_node *event_node = container_of(work, struct virtio_scsi_event_node, work); struct virtio_scsi *vscsi = event_node->vscsi; struct virtio_scsi_event *event = &event_node->event; if (event->event & VIRTIO_SCSI_T_EVENTS_MISSED) { event->event &= ~VIRTIO_SCSI_T_EVENTS_MISSED; scsi_scan_host(virtio_scsi_host(vscsi->vdev)); } switch (event->event) { case VIRTIO_SCSI_T_NO_EVENT: break; case VIRTIO_SCSI_T_TRANSPORT_RESET: virtscsi_handle_transport_reset(vscsi, event); break; case VIRTIO_SCSI_T_PARAM_CHANGE: virtscsi_handle_param_change(vscsi, event); break; default: pr_err("Unsupport virtio scsi event %x\n", event->event); } virtscsi_kick_event(vscsi, event_node); } static void virtscsi_complete_event(struct virtio_scsi *vscsi, void *buf) { struct virtio_scsi_event_node *event_node = buf; INIT_WORK(&event_node->work, virtscsi_handle_event); schedule_work(&event_node->work); } static void virtscsi_event_done(struct virtqueue *vq) { struct Scsi_Host *sh = virtio_scsi_host(vq->vdev); struct virtio_scsi *vscsi = shost_priv(sh); virtscsi_vq_done(vscsi, &vscsi->event_vq, virtscsi_complete_event); }; /** * virtscsi_add_cmd - add a virtio_scsi_cmd to a virtqueue * @vq : the struct virtqueue we're talking about * @cmd : command structure * @req_size : size of the request buffer * @resp_size : size of the response buffer * @gfp : flags to use for memory allocations */ static int virtscsi_add_cmd(struct virtqueue *vq, struct virtio_scsi_cmd *cmd, size_t req_size, size_t resp_size, gfp_t gfp) { struct scsi_cmnd *sc = cmd->sc; struct scatterlist *sgs[4], req, resp; struct sg_table *out, *in; unsigned out_num = 0, in_num = 0; out = in = NULL; if (sc && sc->sc_data_direction != DMA_NONE) { if (sc->sc_data_direction != DMA_FROM_DEVICE) out = &scsi_out(sc)->table; if (sc->sc_data_direction != DMA_TO_DEVICE) in = &scsi_in(sc)->table; } /* Request header. */ sg_init_one(&req, &cmd->req, req_size); sgs[out_num++] = &req; /* Data-out buffer. */ if (out) sgs[out_num++] = out->sgl; /* Response header. */ sg_init_one(&resp, &cmd->resp, resp_size); sgs[out_num + in_num++] = &resp; /* Data-in buffer */ if (in) sgs[out_num + in_num++] = in->sgl; return virtqueue_add_sgs(vq, sgs, out_num, in_num, cmd, gfp); } static int virtscsi_kick_cmd(struct virtio_scsi_vq *vq, struct virtio_scsi_cmd *cmd, size_t req_size, size_t resp_size, gfp_t gfp) { unsigned long flags; int err; bool needs_kick = false; spin_lock_irqsave(&vq->vq_lock, flags); err = virtscsi_add_cmd(vq->vq, cmd, req_size, resp_size, gfp); if (!err) needs_kick = virtqueue_kick_prepare(vq->vq); spin_unlock_irqrestore(&vq->vq_lock, flags); if (needs_kick) virtqueue_notify(vq->vq); return err; } static int virtscsi_queuecommand(struct virtio_scsi *vscsi, struct virtio_scsi_vq *req_vq, struct scsi_cmnd *sc) { struct virtio_scsi_cmd *cmd; int ret; struct Scsi_Host *shost = virtio_scsi_host(vscsi->vdev); BUG_ON(scsi_sg_count(sc) > shost->sg_tablesize); /* TODO: check feature bit and fail if unsupported? */ BUG_ON(sc->sc_data_direction == DMA_BIDIRECTIONAL); dev_dbg(&sc->device->sdev_gendev, "cmd %p CDB: %#02x\n", sc, sc->cmnd[0]); ret = SCSI_MLQUEUE_HOST_BUSY; cmd = mempool_alloc(virtscsi_cmd_pool, GFP_ATOMIC); if (!cmd) goto out; memset(cmd, 0, sizeof(*cmd)); cmd->sc = sc; cmd->req.cmd = (struct virtio_scsi_cmd_req){ .lun[0] = 1, .lun[1] = sc->device->id, .lun[2] = (sc->device->lun >> 8) | 0x40, .lun[3] = sc->device->lun & 0xff, .tag = (unsigned long)sc, .task_attr = VIRTIO_SCSI_S_SIMPLE, .prio = 0, .crn = 0, }; BUG_ON(sc->cmd_len > VIRTIO_SCSI_CDB_SIZE); memcpy(cmd->req.cmd.cdb, sc->cmnd, sc->cmd_len); if (virtscsi_kick_cmd(req_vq, cmd, sizeof cmd->req.cmd, sizeof cmd->resp.cmd, GFP_ATOMIC) == 0) ret = 0; else mempool_free(cmd, virtscsi_cmd_pool); out: return ret; } static int virtscsi_queuecommand_single(struct Scsi_Host *sh, struct scsi_cmnd *sc) { struct virtio_scsi *vscsi = shost_priv(sh); struct virtio_scsi_target_state *tgt = scsi_target(sc->device)->hostdata; atomic_inc(&tgt->reqs); return virtscsi_queuecommand(vscsi, &vscsi->req_vqs[0], sc); } static struct virtio_scsi_vq *virtscsi_pick_vq(struct virtio_scsi *vscsi, struct virtio_scsi_target_state *tgt) { struct virtio_scsi_vq *vq; unsigned long flags; u32 queue_num; spin_lock_irqsave(&tgt->tgt_lock, flags); /* * The memory barrier after atomic_inc_return matches * the smp_read_barrier_depends() in virtscsi_req_done. */ if (atomic_inc_return(&tgt->reqs) > 1) vq = ACCESS_ONCE(tgt->req_vq); else { queue_num = smp_processor_id(); while (unlikely(queue_num >= vscsi->num_queues)) queue_num -= vscsi->num_queues; tgt->req_vq = vq = &vscsi->req_vqs[queue_num]; } spin_unlock_irqrestore(&tgt->tgt_lock, flags); return vq; } static int virtscsi_queuecommand_multi(struct Scsi_Host *sh, struct scsi_cmnd *sc) { struct virtio_scsi *vscsi = shost_priv(sh); struct virtio_scsi_target_state *tgt = scsi_target(sc->device)->hostdata; struct virtio_scsi_vq *req_vq = virtscsi_pick_vq(vscsi, tgt); return virtscsi_queuecommand(vscsi, req_vq, sc); } static int virtscsi_tmf(struct virtio_scsi *vscsi, struct virtio_scsi_cmd *cmd) { DECLARE_COMPLETION_ONSTACK(comp); int ret = FAILED; cmd->comp = &comp; if (virtscsi_kick_cmd(&vscsi->ctrl_vq, cmd, sizeof cmd->req.tmf, sizeof cmd->resp.tmf, GFP_NOIO) < 0) goto out; wait_for_completion(&comp); if (cmd->resp.tmf.response == VIRTIO_SCSI_S_OK || cmd->resp.tmf.response == VIRTIO_SCSI_S_FUNCTION_SUCCEEDED) ret = SUCCESS; out: mempool_free(cmd, virtscsi_cmd_pool); return ret; } static int virtscsi_device_reset(struct scsi_cmnd *sc) { struct virtio_scsi *vscsi = shost_priv(sc->device->host); struct virtio_scsi_cmd *cmd; sdev_printk(KERN_INFO, sc->device, "device reset\n"); cmd = mempool_alloc(virtscsi_cmd_pool, GFP_NOIO); if (!cmd) return FAILED; memset(cmd, 0, sizeof(*cmd)); cmd->sc = sc; cmd->req.tmf = (struct virtio_scsi_ctrl_tmf_req){ .type = VIRTIO_SCSI_T_TMF, .subtype = VIRTIO_SCSI_T_TMF_LOGICAL_UNIT_RESET, .lun[0] = 1, .lun[1] = sc->device->id, .lun[2] = (sc->device->lun >> 8) | 0x40, .lun[3] = sc->device->lun & 0xff, }; return virtscsi_tmf(vscsi, cmd); } static int virtscsi_abort(struct scsi_cmnd *sc) { struct virtio_scsi *vscsi = shost_priv(sc->device->host); struct virtio_scsi_cmd *cmd; scmd_printk(KERN_INFO, sc, "abort\n"); cmd = mempool_alloc(virtscsi_cmd_pool, GFP_NOIO); if (!cmd) return FAILED; memset(cmd, 0, sizeof(*cmd)); cmd->sc = sc; cmd->req.tmf = (struct virtio_scsi_ctrl_tmf_req){ .type = VIRTIO_SCSI_T_TMF, .subtype = VIRTIO_SCSI_T_TMF_ABORT_TASK, .lun[0] = 1, .lun[1] = sc->device->id, .lun[2] = (sc->device->lun >> 8) | 0x40, .lun[3] = sc->device->lun & 0xff, .tag = (unsigned long)sc, }; return virtscsi_tmf(vscsi, cmd); } static int virtscsi_target_alloc(struct scsi_target *starget) { struct virtio_scsi_target_state *tgt = kmalloc(sizeof(*tgt), GFP_KERNEL); if (!tgt) return -ENOMEM; spin_lock_init(&tgt->tgt_lock); atomic_set(&tgt->reqs, 0); tgt->req_vq = NULL; starget->hostdata = tgt; return 0; } static void virtscsi_target_destroy(struct scsi_target *starget) { struct virtio_scsi_target_state *tgt = starget->hostdata; kfree(tgt); } static struct scsi_host_template virtscsi_host_template_single = { .module = THIS_MODULE, .name = "Virtio SCSI HBA", .proc_name = "virtio_scsi", .this_id = -1, .queuecommand = virtscsi_queuecommand_single, .eh_abort_handler = virtscsi_abort, .eh_device_reset_handler = virtscsi_device_reset, .can_queue = 1024, .dma_boundary = UINT_MAX, .use_clustering = ENABLE_CLUSTERING, .target_alloc = virtscsi_target_alloc, .target_destroy = virtscsi_target_destroy, }; static struct scsi_host_template virtscsi_host_template_multi = { .module = THIS_MODULE, .name = "Virtio SCSI HBA", .proc_name = "virtio_scsi", .this_id = -1, .queuecommand = virtscsi_queuecommand_multi, .eh_abort_handler = virtscsi_abort, .eh_device_reset_handler = virtscsi_device_reset, .can_queue = 1024, .dma_boundary = UINT_MAX, .use_clustering = ENABLE_CLUSTERING, .target_alloc = virtscsi_target_alloc, .target_destroy = virtscsi_target_destroy, }; #define virtscsi_config_get(vdev, fld) \ ({ \ typeof(((struct virtio_scsi_config *)0)->fld) __val; \ vdev->config->get(vdev, \ offsetof(struct virtio_scsi_config, fld), \ &__val, sizeof(__val)); \ __val; \ }) #define virtscsi_config_set(vdev, fld, val) \ (void)({ \ typeof(((struct virtio_scsi_config *)0)->fld) __val = (val); \ vdev->config->set(vdev, \ offsetof(struct virtio_scsi_config, fld), \ &__val, sizeof(__val)); \ }) static void __virtscsi_set_affinity(struct virtio_scsi *vscsi, bool affinity) { int i; int cpu; /* In multiqueue mode, when the number of cpu is equal * to the number of request queues, we let the qeueues * to be private to one cpu by setting the affinity hint * to eliminate the contention. */ if ((vscsi->num_queues == 1 || vscsi->num_queues != num_online_cpus()) && affinity) { if (vscsi->affinity_hint_set) affinity = false; else return; } if (affinity) { i = 0; for_each_online_cpu(cpu) { virtqueue_set_affinity(vscsi->req_vqs[i].vq, cpu); i++; } vscsi->affinity_hint_set = true; } else { for (i = 0; i < vscsi->num_queues; i++) virtqueue_set_affinity(vscsi->req_vqs[i].vq, -1); vscsi->affinity_hint_set = false; } } static void virtscsi_set_affinity(struct virtio_scsi *vscsi, bool affinity) { get_online_cpus(); __virtscsi_set_affinity(vscsi, affinity); put_online_cpus(); } static int virtscsi_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { struct virtio_scsi *vscsi = container_of(nfb, struct virtio_scsi, nb); switch(action) { case CPU_ONLINE: case CPU_ONLINE_FROZEN: case CPU_DEAD: case CPU_DEAD_FROZEN: __virtscsi_set_affinity(vscsi, true); break; default: break; } return NOTIFY_OK; } static void virtscsi_init_vq(struct virtio_scsi_vq *virtscsi_vq, struct virtqueue *vq) { spin_lock_init(&virtscsi_vq->vq_lock); virtscsi_vq->vq = vq; } static void virtscsi_scan(struct virtio_device *vdev) { struct Scsi_Host *shost = (struct Scsi_Host *)vdev->priv; scsi_scan_host(shost); } static void virtscsi_remove_vqs(struct virtio_device *vdev) { struct Scsi_Host *sh = virtio_scsi_host(vdev); struct virtio_scsi *vscsi = shost_priv(sh); virtscsi_set_affinity(vscsi, false); /* Stop all the virtqueues. */ vdev->config->reset(vdev); vdev->config->del_vqs(vdev); } static int virtscsi_init(struct virtio_device *vdev, struct virtio_scsi *vscsi) { int err; u32 i; u32 num_vqs; vq_callback_t **callbacks; const char **names; struct virtqueue **vqs; num_vqs = vscsi->num_queues + VIRTIO_SCSI_VQ_BASE; vqs = kmalloc(num_vqs * sizeof(struct virtqueue *), GFP_KERNEL); callbacks = kmalloc(num_vqs * sizeof(vq_callback_t *), GFP_KERNEL); names = kmalloc(num_vqs * sizeof(char *), GFP_KERNEL); if (!callbacks || !vqs || !names) { err = -ENOMEM; goto out; } callbacks[0] = virtscsi_ctrl_done; callbacks[1] = virtscsi_event_done; names[0] = "control"; names[1] = "event"; for (i = VIRTIO_SCSI_VQ_BASE; i < num_vqs; i++) { callbacks[i] = virtscsi_req_done; names[i] = "request"; } /* Discover virtqueues and write information to configuration. */ err = vdev->config->find_vqs(vdev, num_vqs, vqs, callbacks, names); if (err) goto out; virtscsi_init_vq(&vscsi->ctrl_vq, vqs[0]); virtscsi_init_vq(&vscsi->event_vq, vqs[1]); for (i = VIRTIO_SCSI_VQ_BASE; i < num_vqs; i++) virtscsi_init_vq(&vscsi->req_vqs[i - VIRTIO_SCSI_VQ_BASE], vqs[i]); virtscsi_set_affinity(vscsi, true); virtscsi_config_set(vdev, cdb_size, VIRTIO_SCSI_CDB_SIZE); virtscsi_config_set(vdev, sense_size, VIRTIO_SCSI_SENSE_SIZE); if (virtio_has_feature(vdev, VIRTIO_SCSI_F_HOTPLUG)) virtscsi_kick_event_all(vscsi); err = 0; out: kfree(names); kfree(callbacks); kfree(vqs); if (err) virtscsi_remove_vqs(vdev); return err; } static int virtscsi_probe(struct virtio_device *vdev) { struct Scsi_Host *shost; struct virtio_scsi *vscsi; int err; u32 sg_elems, num_targets; u32 cmd_per_lun; u32 num_queues; struct scsi_host_template *hostt; /* We need to know how many queues before we allocate. */ num_queues = virtscsi_config_get(vdev, num_queues) ? : 1; num_targets = virtscsi_config_get(vdev, max_target) + 1; if (num_queues == 1) hostt = &virtscsi_host_template_single; else hostt = &virtscsi_host_template_multi; shost = scsi_host_alloc(hostt, sizeof(*vscsi) + sizeof(vscsi->req_vqs[0]) * num_queues); if (!shost) return -ENOMEM; sg_elems = virtscsi_config_get(vdev, seg_max) ?: 1; shost->sg_tablesize = sg_elems; vscsi = shost_priv(shost); vscsi->vdev = vdev; vscsi->num_queues = num_queues; vdev->priv = shost; err = virtscsi_init(vdev, vscsi); if (err) goto virtscsi_init_failed; vscsi->nb.notifier_call = &virtscsi_cpu_callback; err = register_hotcpu_notifier(&vscsi->nb); if (err) { pr_err("registering cpu notifier failed\n"); goto scsi_add_host_failed; } cmd_per_lun = virtscsi_config_get(vdev, cmd_per_lun) ?: 1; shost->cmd_per_lun = min_t(u32, cmd_per_lun, shost->can_queue); shost->max_sectors = virtscsi_config_get(vdev, max_sectors) ?: 0xFFFF; /* LUNs > 256 are reported with format 1, so they go in the range * 16640-32767. */ shost->max_lun = virtscsi_config_get(vdev, max_lun) + 1 + 0x4000; shost->max_id = num_targets; shost->max_channel = 0; shost->max_cmd_len = VIRTIO_SCSI_CDB_SIZE; err = scsi_add_host(shost, &vdev->dev); if (err) goto scsi_add_host_failed; /* * scsi_scan_host() happens in virtscsi_scan() via virtio_driver->scan() * after VIRTIO_CONFIG_S_DRIVER_OK has been set.. */ return 0; scsi_add_host_failed: vdev->config->del_vqs(vdev); virtscsi_init_failed: scsi_host_put(shost); return err; } static void virtscsi_remove(struct virtio_device *vdev) { struct Scsi_Host *shost = virtio_scsi_host(vdev); struct virtio_scsi *vscsi = shost_priv(shost); if (virtio_has_feature(vdev, VIRTIO_SCSI_F_HOTPLUG)) virtscsi_cancel_event_work(vscsi); scsi_remove_host(shost); unregister_hotcpu_notifier(&vscsi->nb); virtscsi_remove_vqs(vdev); scsi_host_put(shost); } #ifdef CONFIG_PM static int virtscsi_freeze(struct virtio_device *vdev) { virtscsi_remove_vqs(vdev); return 0; } static int virtscsi_restore(struct virtio_device *vdev) { struct Scsi_Host *sh = virtio_scsi_host(vdev); struct virtio_scsi *vscsi = shost_priv(sh); return virtscsi_init(vdev, vscsi); } #endif static struct virtio_device_id id_table[] = { { VIRTIO_ID_SCSI, VIRTIO_DEV_ANY_ID }, { 0 }, }; static unsigned int features[] = { VIRTIO_SCSI_F_HOTPLUG, VIRTIO_SCSI_F_CHANGE, }; static struct virtio_driver virtio_scsi_driver = { .feature_table = features, .feature_table_size = ARRAY_SIZE(features), .driver.name = KBUILD_MODNAME, .driver.owner = THIS_MODULE, .id_table = id_table, .probe = virtscsi_probe, .scan = virtscsi_scan, #ifdef CONFIG_PM .freeze = virtscsi_freeze, .restore = virtscsi_restore, #endif .remove = virtscsi_remove, }; static int __init init(void) { int ret = -ENOMEM; virtscsi_cmd_cache = KMEM_CACHE(virtio_scsi_cmd, 0); if (!virtscsi_cmd_cache) { pr_err("kmem_cache_create() for virtscsi_cmd_cache failed\n"); goto error; } virtscsi_cmd_pool = mempool_create_slab_pool(VIRTIO_SCSI_MEMPOOL_SZ, virtscsi_cmd_cache); if (!virtscsi_cmd_pool) { pr_err("mempool_create() for virtscsi_cmd_pool failed\n"); goto error; } ret = register_virtio_driver(&virtio_scsi_driver); if (ret < 0) goto error; return 0; error: if (virtscsi_cmd_pool) { mempool_destroy(virtscsi_cmd_pool); virtscsi_cmd_pool = NULL; } if (virtscsi_cmd_cache) { kmem_cache_destroy(virtscsi_cmd_cache); virtscsi_cmd_cache = NULL; } return ret; } static void __exit fini(void) { unregister_virtio_driver(&virtio_scsi_driver); mempool_destroy(virtscsi_cmd_pool); kmem_cache_destroy(virtscsi_cmd_cache); } module_init(init); module_exit(fini); MODULE_DEVICE_TABLE(virtio, id_table); MODULE_DESCRIPTION("Virtio SCSI HBA driver"); MODULE_LICENSE("GPL");
prasidh09/cse506
unionfs-3.10.y/drivers/scsi/virtio_scsi.c
C
gpl-2.0
26,923
#ifndef __LIS3LV02D_H_ #define __LIS3LV02D_H_ struct lis3lv02d_platform_data { /* please note: the 'click' feature is only supported for * LIS[32]02DL variants of the chip and will be ignored for * others */ #define LIS3_CLICK_SINGLE_X (1 << 0) #define LIS3_CLICK_DOUBLE_X (1 << 1) #define LIS3_CLICK_SINGLE_Y (1 << 2) #define LIS3_CLICK_DOUBLE_Y (1 << 3) #define LIS3_CLICK_SINGLE_Z (1 << 4) #define LIS3_CLICK_DOUBLE_Z (1 << 5) unsigned char click_flags; unsigned char click_thresh_x; unsigned char click_thresh_y; unsigned char click_thresh_z; unsigned char click_time_limit; unsigned char click_latency; unsigned char click_window; #define LIS3_IRQ1_DISABLE (0 << 0) #define LIS3_IRQ1_FF_WU_1 (1 << 0) #define LIS3_IRQ1_FF_WU_2 (2 << 0) #define LIS3_IRQ1_FF_WU_12 (3 << 0) #define LIS3_IRQ1_DATA_READY (4 << 0) #define LIS3_IRQ1_CLICK (7 << 0) #define LIS3_IRQ1_MASK (7 << 0) #define LIS3_IRQ2_DISABLE (0 << 3) #define LIS3_IRQ2_FF_WU_1 (1 << 3) #define LIS3_IRQ2_FF_WU_2 (2 << 3) #define LIS3_IRQ2_FF_WU_12 (3 << 3) #define LIS3_IRQ2_DATA_READY (4 << 3) #define LIS3_IRQ2_CLICK (7 << 3) #define LIS3_IRQ2_MASK (7 << 3) #define LIS3_IRQ_OPEN_DRAIN (1 << 6) #define LIS3_IRQ_ACTIVE_LOW (1 << 7) unsigned char irq_cfg; #define LIS3_WAKEUP_X_LO (1 << 0) #define LIS3_WAKEUP_X_HI (1 << 1) #define LIS3_WAKEUP_Y_LO (1 << 2) #define LIS3_WAKEUP_Y_HI (1 << 3) #define LIS3_WAKEUP_Z_LO (1 << 4) #define LIS3_WAKEUP_Z_HI (1 << 5) unsigned char wakeup_flags; unsigned char wakeup_thresh; unsigned char wakeup_flags2; unsigned char wakeup_thresh2; #define LIS3_HIPASS_CUTFF_8HZ 0 #define LIS3_HIPASS_CUTFF_4HZ 1 #define LIS3_HIPASS_CUTFF_2HZ 2 #define LIS3_HIPASS_CUTFF_1HZ 3 #define LIS3_HIPASS1_DISABLE (1 << 2) #define LIS3_HIPASS2_DISABLE (1 << 3) unsigned char hipass_ctrl; #define LIS3_NO_MAP 0 #define LIS3_DEV_X 1 #define LIS3_DEV_Y 2 #define LIS3_DEV_Z 3 #define LIS3_INV_DEV_X -1 #define LIS3_INV_DEV_Y -2 #define LIS3_INV_DEV_Z -3 s8 axis_x; s8 axis_y; s8 axis_z; int (*setup_resources)(void); int (*release_resources)(void); /* Limits for selftest are specified in chip data sheet */ s16 st_min_limits[3]; /* min pass limit x, y, z */ s16 st_max_limits[3]; /* max pass limit x, y, z */ int irq2; }; #endif /* __LIS3LV02D_H_ */
wkritzinger/asuswrt-merlin
release/src-rt-7.x.main/src/linux/linux-2.6.36/include/linux/lis3lv02d.h
C
gpl-2.0
2,306
var a: [] = []; var a: [Foo<T>] = [foo]; var a: [number] = [123]; var a: [number, string] = [123, "duck"];
jaredly/babel
test/fixtures/generation/flow/tuples/expected.js
JavaScript
mit
107
/* mbed Microcontroller Library * Copyright (c) 2006-2012 ARM Limited * * 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. */ #ifndef FIR_F32_H #define FIR_F32_H #include <stdint.h> #include "arm_math.h" namespace dsp { template<uint16_t num_taps, uint32_t block_size=32> class FIR_f32 { public: FIR_f32(const float32_t *coeff) { arm_fir_init_f32(&fir, num_taps, (float32_t*)coeff, fir_state, block_size); } void process(float32_t *sgn_in, float32_t *sgn_out) { arm_fir_f32(&fir, sgn_in, sgn_out, block_size); } void reset(void) { memset(fir_state, 0, sizeof(fir_state)); } private: arm_fir_instance_f32 fir; float32_t fir_state[block_size + num_taps - 1]; }; } #endif
ruriwo/ErgoThumb072_firmware
tmk_core/tool/mbed/mbed-sdk/libraries/dsp/dsp/FIR_f32.h
C
gpl-2.0
1,765
#ifndef _M68K_BITOPS_H #define _M68K_BITOPS_H /* * Copyright 1992, Linus Torvalds. * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive * for more details. */ #ifndef _LINUX_BITOPS_H #error only <linux/bitops.h> can be included directly #endif #include <linux/compiler.h> #include <asm/barrier.h> /* * Bit access functions vary across the ColdFire and 68k families. * So we will break them out here, and then macro in the ones we want. * * ColdFire - supports standard bset/bclr/bchg with register operand only * 68000 - supports standard bset/bclr/bchg with memory operand * >= 68020 - also supports the bfset/bfclr/bfchg instructions * * Although it is possible to use only the bset/bclr/bchg with register * operands on all platforms you end up with larger generated code. * So we use the best form possible on a given platform. */ static inline void bset_reg_set_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; __asm__ __volatile__ ("bset %1,(%0)" : : "a" (p), "di" (nr & 7) : "memory"); } static inline void bset_mem_set_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; __asm__ __volatile__ ("bset %1,%0" : "+m" (*p) : "di" (nr & 7)); } static inline void bfset_mem_set_bit(int nr, volatile unsigned long *vaddr) { __asm__ __volatile__ ("bfset %1{%0:#1}" : : "d" (nr ^ 31), "o" (*vaddr) : "memory"); } #if defined(CONFIG_COLDFIRE) #define set_bit(nr, vaddr) bset_reg_set_bit(nr, vaddr) #elif defined(CONFIG_CPU_HAS_NO_BITFIELDS) #define set_bit(nr, vaddr) bset_mem_set_bit(nr, vaddr) #else #define set_bit(nr, vaddr) (__builtin_constant_p(nr) ? \ bset_mem_set_bit(nr, vaddr) : \ bfset_mem_set_bit(nr, vaddr)) #endif #define __set_bit(nr, vaddr) set_bit(nr, vaddr) static inline void bclr_reg_clear_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; __asm__ __volatile__ ("bclr %1,(%0)" : : "a" (p), "di" (nr & 7) : "memory"); } static inline void bclr_mem_clear_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; __asm__ __volatile__ ("bclr %1,%0" : "+m" (*p) : "di" (nr & 7)); } static inline void bfclr_mem_clear_bit(int nr, volatile unsigned long *vaddr) { __asm__ __volatile__ ("bfclr %1{%0:#1}" : : "d" (nr ^ 31), "o" (*vaddr) : "memory"); } #if defined(CONFIG_COLDFIRE) #define clear_bit(nr, vaddr) bclr_reg_clear_bit(nr, vaddr) #elif defined(CONFIG_CPU_HAS_NO_BITFIELDS) #define clear_bit(nr, vaddr) bclr_mem_clear_bit(nr, vaddr) #else #define clear_bit(nr, vaddr) (__builtin_constant_p(nr) ? \ bclr_mem_clear_bit(nr, vaddr) : \ bfclr_mem_clear_bit(nr, vaddr)) #endif #define __clear_bit(nr, vaddr) clear_bit(nr, vaddr) static inline void bchg_reg_change_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; __asm__ __volatile__ ("bchg %1,(%0)" : : "a" (p), "di" (nr & 7) : "memory"); } static inline void bchg_mem_change_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; __asm__ __volatile__ ("bchg %1,%0" : "+m" (*p) : "di" (nr & 7)); } static inline void bfchg_mem_change_bit(int nr, volatile unsigned long *vaddr) { __asm__ __volatile__ ("bfchg %1{%0:#1}" : : "d" (nr ^ 31), "o" (*vaddr) : "memory"); } #if defined(CONFIG_COLDFIRE) #define change_bit(nr, vaddr) bchg_reg_change_bit(nr, vaddr) #elif defined(CONFIG_CPU_HAS_NO_BITFIELDS) #define change_bit(nr, vaddr) bchg_mem_change_bit(nr, vaddr) #else #define change_bit(nr, vaddr) (__builtin_constant_p(nr) ? \ bchg_mem_change_bit(nr, vaddr) : \ bfchg_mem_change_bit(nr, vaddr)) #endif #define __change_bit(nr, vaddr) change_bit(nr, vaddr) static inline int test_bit(int nr, const volatile unsigned long *vaddr) { return (vaddr[nr >> 5] & (1UL << (nr & 31))) != 0; } static inline int bset_reg_test_and_set_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; char retval; __asm__ __volatile__ ("bset %2,(%1); sne %0" : "=d" (retval) : "a" (p), "di" (nr & 7) : "memory"); return retval; } static inline int bset_mem_test_and_set_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; char retval; __asm__ __volatile__ ("bset %2,%1; sne %0" : "=d" (retval), "+m" (*p) : "di" (nr & 7)); return retval; } static inline int bfset_mem_test_and_set_bit(int nr, volatile unsigned long *vaddr) { char retval; __asm__ __volatile__ ("bfset %2{%1:#1}; sne %0" : "=d" (retval) : "d" (nr ^ 31), "o" (*vaddr) : "memory"); return retval; } #if defined(CONFIG_COLDFIRE) #define test_and_set_bit(nr, vaddr) bset_reg_test_and_set_bit(nr, vaddr) #elif defined(CONFIG_CPU_HAS_NO_BITFIELDS) #define test_and_set_bit(nr, vaddr) bset_mem_test_and_set_bit(nr, vaddr) #else #define test_and_set_bit(nr, vaddr) (__builtin_constant_p(nr) ? \ bset_mem_test_and_set_bit(nr, vaddr) : \ bfset_mem_test_and_set_bit(nr, vaddr)) #endif #define __test_and_set_bit(nr, vaddr) test_and_set_bit(nr, vaddr) static inline int bclr_reg_test_and_clear_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; char retval; __asm__ __volatile__ ("bclr %2,(%1); sne %0" : "=d" (retval) : "a" (p), "di" (nr & 7) : "memory"); return retval; } static inline int bclr_mem_test_and_clear_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; char retval; __asm__ __volatile__ ("bclr %2,%1; sne %0" : "=d" (retval), "+m" (*p) : "di" (nr & 7)); return retval; } static inline int bfclr_mem_test_and_clear_bit(int nr, volatile unsigned long *vaddr) { char retval; __asm__ __volatile__ ("bfclr %2{%1:#1}; sne %0" : "=d" (retval) : "d" (nr ^ 31), "o" (*vaddr) : "memory"); return retval; } #if defined(CONFIG_COLDFIRE) #define test_and_clear_bit(nr, vaddr) bclr_reg_test_and_clear_bit(nr, vaddr) #elif defined(CONFIG_CPU_HAS_NO_BITFIELDS) #define test_and_clear_bit(nr, vaddr) bclr_mem_test_and_clear_bit(nr, vaddr) #else #define test_and_clear_bit(nr, vaddr) (__builtin_constant_p(nr) ? \ bclr_mem_test_and_clear_bit(nr, vaddr) : \ bfclr_mem_test_and_clear_bit(nr, vaddr)) #endif #define __test_and_clear_bit(nr, vaddr) test_and_clear_bit(nr, vaddr) static inline int bchg_reg_test_and_change_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; char retval; __asm__ __volatile__ ("bchg %2,(%1); sne %0" : "=d" (retval) : "a" (p), "di" (nr & 7) : "memory"); return retval; } static inline int bchg_mem_test_and_change_bit(int nr, volatile unsigned long *vaddr) { char *p = (char *)vaddr + (nr ^ 31) / 8; char retval; __asm__ __volatile__ ("bchg %2,%1; sne %0" : "=d" (retval), "+m" (*p) : "di" (nr & 7)); return retval; } static inline int bfchg_mem_test_and_change_bit(int nr, volatile unsigned long *vaddr) { char retval; __asm__ __volatile__ ("bfchg %2{%1:#1}; sne %0" : "=d" (retval) : "d" (nr ^ 31), "o" (*vaddr) : "memory"); return retval; } #if defined(CONFIG_COLDFIRE) #define test_and_change_bit(nr, vaddr) bchg_reg_test_and_change_bit(nr, vaddr) #elif defined(CONFIG_CPU_HAS_NO_BITFIELDS) #define test_and_change_bit(nr, vaddr) bchg_mem_test_and_change_bit(nr, vaddr) #else #define test_and_change_bit(nr, vaddr) (__builtin_constant_p(nr) ? \ bchg_mem_test_and_change_bit(nr, vaddr) : \ bfchg_mem_test_and_change_bit(nr, vaddr)) #endif #define __test_and_change_bit(nr, vaddr) test_and_change_bit(nr, vaddr) /* * The true 68020 and more advanced processors support the "bfffo" * instruction for finding bits. ColdFire and simple 68000 parts * (including CPU32) do not support this. They simply use the generic * functions. */ #if defined(CONFIG_CPU_HAS_NO_BITFIELDS) #include <asm-generic/bitops/find.h> #include <asm-generic/bitops/ffz.h> #else static inline int find_first_zero_bit(const unsigned long *vaddr, unsigned size) { const unsigned long *p = vaddr; int res = 32; unsigned int words; unsigned long num; if (!size) return 0; words = (size + 31) >> 5; while (!(num = ~*p++)) { if (!--words) goto out; } __asm__ __volatile__ ("bfffo %1{#0,#0},%0" : "=d" (res) : "d" (num & -num)); res ^= 31; out: res += ((long)p - (long)vaddr - 4) * 8; return res < size ? res : size; } #define find_first_zero_bit find_first_zero_bit static inline int find_next_zero_bit(const unsigned long *vaddr, int size, int offset) { const unsigned long *p = vaddr + (offset >> 5); int bit = offset & 31UL, res; if (offset >= size) return size; if (bit) { unsigned long num = ~*p++ & (~0UL << bit); offset -= bit; /* Look for zero in first longword */ __asm__ __volatile__ ("bfffo %1{#0,#0},%0" : "=d" (res) : "d" (num & -num)); if (res < 32) { offset += res ^ 31; return offset < size ? offset : size; } offset += 32; if (offset >= size) return size; } /* No zero yet, search remaining full bytes for a zero */ return offset + find_first_zero_bit(p, size - offset); } #define find_next_zero_bit find_next_zero_bit static inline int find_first_bit(const unsigned long *vaddr, unsigned size) { const unsigned long *p = vaddr; int res = 32; unsigned int words; unsigned long num; if (!size) return 0; words = (size + 31) >> 5; while (!(num = *p++)) { if (!--words) goto out; } __asm__ __volatile__ ("bfffo %1{#0,#0},%0" : "=d" (res) : "d" (num & -num)); res ^= 31; out: res += ((long)p - (long)vaddr - 4) * 8; return res < size ? res : size; } #define find_first_bit find_first_bit static inline int find_next_bit(const unsigned long *vaddr, int size, int offset) { const unsigned long *p = vaddr + (offset >> 5); int bit = offset & 31UL, res; if (offset >= size) return size; if (bit) { unsigned long num = *p++ & (~0UL << bit); offset -= bit; /* Look for one in first longword */ __asm__ __volatile__ ("bfffo %1{#0,#0},%0" : "=d" (res) : "d" (num & -num)); if (res < 32) { offset += res ^ 31; return offset < size ? offset : size; } offset += 32; if (offset >= size) return size; } /* No one yet, search remaining full bytes for a one */ return offset + find_first_bit(p, size - offset); } #define find_next_bit find_next_bit /* * ffz = Find First Zero in word. Undefined if no zero exists, * so code should check against ~0UL first.. */ static inline unsigned long ffz(unsigned long word) { int res; __asm__ __volatile__ ("bfffo %1{#0,#0},%0" : "=d" (res) : "d" (~word & -~word)); return res ^ 31; } #endif #ifdef __KERNEL__ #if defined(CONFIG_CPU_HAS_NO_BITFIELDS) /* * The newer ColdFire family members support a "bitrev" instruction * and we can use that to implement a fast ffs. Older Coldfire parts, * and normal 68000 parts don't have anything special, so we use the * generic functions for those. */ #if (defined(__mcfisaaplus__) || defined(__mcfisac__)) && \ !defined(CONFIG_M68000) && !defined(CONFIG_MCPU32) static inline int __ffs(int x) { __asm__ __volatile__ ("bitrev %0; ff1 %0" : "=d" (x) : "0" (x)); return x; } static inline int ffs(int x) { if (!x) return 0; return __ffs(x) + 1; } #else #include <asm-generic/bitops/ffs.h> #include <asm-generic/bitops/__ffs.h> #endif #include <asm-generic/bitops/fls.h> #include <asm-generic/bitops/__fls.h> #else /* * ffs: find first bit set. This is defined the same way as * the libc and compiler builtin ffs routines, therefore * differs in spirit from the above ffz (man ffs). */ static inline int ffs(int x) { int cnt; __asm__ ("bfffo %1{#0:#0},%0" : "=d" (cnt) : "dm" (x & -x)); return 32 - cnt; } #define __ffs(x) (ffs(x) - 1) /* * fls: find last bit set. */ static inline int fls(int x) { int cnt; __asm__ ("bfffo %1{#0,#0},%0" : "=d" (cnt) : "dm" (x)); return 32 - cnt; } static inline int __fls(int x) { return fls(x) - 1; } #endif #include <asm-generic/bitops/ext2-atomic.h> #include <asm-generic/bitops/le.h> #include <asm-generic/bitops/fls64.h> #include <asm-generic/bitops/sched.h> #include <asm-generic/bitops/hweight.h> #include <asm-generic/bitops/lock.h> #endif /* __KERNEL__ */ #endif /* _M68K_BITOPS_H */
mkvdv/au-linux-kernel-autumn-2017
linux/arch/m68k/include/asm/bitops.h
C
gpl-3.0
12,484
// Copyright ©2014 The gonum 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 path_test import ( "math" "reflect" "testing" "github.com/gonum/graph" "github.com/gonum/graph/concrete" "github.com/gonum/graph/path" "github.com/gonum/graph/path/internal" "github.com/gonum/graph/topo" ) var aStarTests = []struct { name string g graph.Graph s, t int heuristic path.Heuristic wantPath []int }{ { name: "simple path", g: func() graph.Graph { return internal.NewGridFrom( "*..*", "**.*", "**.*", "**.*", ) }(), s: 1, t: 14, wantPath: []int{1, 2, 6, 10, 14}, }, { name: "small open graph", g: internal.NewGrid(3, 3, true), s: 0, t: 8, }, { name: "large open graph", g: internal.NewGrid(1000, 1000, true), s: 0, t: 999*1000 + 999, }, { name: "no path", g: func() graph.Graph { tg := internal.NewGrid(5, 5, true) // Create a complete "wall" across the middle row. tg.Set(2, 0, false) tg.Set(2, 1, false) tg.Set(2, 2, false) tg.Set(2, 3, false) tg.Set(2, 4, false) return tg }(), s: 2, t: 22, }, { name: "partially obstructed", g: func() graph.Graph { tg := internal.NewGrid(10, 10, true) // Create a partial "wall" accross the middle // row with a gap at the left-hand end. tg.Set(4, 1, false) tg.Set(4, 2, false) tg.Set(4, 3, false) tg.Set(4, 4, false) tg.Set(4, 5, false) tg.Set(4, 6, false) tg.Set(4, 7, false) tg.Set(4, 8, false) tg.Set(4, 9, false) return tg }(), s: 5, t: 9*10 + 9, }, { name: "partially obstructed with heuristic", g: func() graph.Graph { tg := internal.NewGrid(10, 10, true) // Create a partial "wall" accross the middle // row with a gap at the left-hand end. tg.Set(4, 1, false) tg.Set(4, 2, false) tg.Set(4, 3, false) tg.Set(4, 4, false) tg.Set(4, 5, false) tg.Set(4, 6, false) tg.Set(4, 7, false) tg.Set(4, 8, false) tg.Set(4, 9, false) return tg }(), s: 5, t: 9*10 + 9, // Manhattan Heuristic heuristic: func(u, v graph.Node) float64 { uid := u.ID() cu := (uid % 10) ru := (uid - cu) / 10 vid := v.ID() cv := (vid % 10) rv := (vid - cv) / 10 return math.Abs(float64(ru-rv)) + math.Abs(float64(cu-cv)) }, }, } func TestAStar(t *testing.T) { for _, test := range aStarTests { pt, _ := path.AStar(concrete.Node(test.s), concrete.Node(test.t), test.g, test.heuristic) p, cost := pt.To(concrete.Node(test.t)) if !topo.IsPathIn(test.g, p) { t.Error("got path that is not path in input graph for %q", test.name) } bfp, ok := path.BellmanFordFrom(concrete.Node(test.s), test.g) if !ok { t.Fatalf("unexpected negative cycle in %q", test.name) } if want := bfp.WeightTo(concrete.Node(test.t)); cost != want { t.Errorf("unexpected cost for %q: got:%v want:%v", test.name, cost, want) } var got = make([]int, 0, len(p)) for _, n := range p { got = append(got, n.ID()) } if test.wantPath != nil && !reflect.DeepEqual(got, test.wantPath) { t.Errorf("unexpected result for %q:\ngot: %v\nwant:%v", test.name, got, test.wantPath) } } } func TestExhaustiveAStar(t *testing.T) { g := concrete.NewGraph() nodes := []locatedNode{ {id: 1, x: 0, y: 6}, {id: 2, x: 1, y: 0}, {id: 3, x: 8, y: 7}, {id: 4, x: 16, y: 0}, {id: 5, x: 17, y: 6}, {id: 6, x: 9, y: 8}, } for _, n := range nodes { g.AddNode(n) } edges := []weightedEdge{ {from: g.Node(1), to: g.Node(2), cost: 7}, {from: g.Node(1), to: g.Node(3), cost: 9}, {from: g.Node(1), to: g.Node(6), cost: 14}, {from: g.Node(2), to: g.Node(3), cost: 10}, {from: g.Node(2), to: g.Node(4), cost: 15}, {from: g.Node(3), to: g.Node(4), cost: 11}, {from: g.Node(3), to: g.Node(6), cost: 2}, {from: g.Node(4), to: g.Node(5), cost: 7}, {from: g.Node(5), to: g.Node(6), cost: 9}, } for _, e := range edges { g.SetEdge(e, e.cost) } heuristic := func(u, v graph.Node) float64 { lu := u.(locatedNode) lv := v.(locatedNode) return math.Hypot(lu.x-lv.x, lu.y-lv.y) } if ok, edge, goal := isMonotonic(g, heuristic); !ok { t.Fatalf("non-monotonic heuristic at edge:%v for goal:%v", edge, goal) } ps := path.DijkstraAllPaths(g) for _, start := range g.Nodes() { for _, goal := range g.Nodes() { pt, _ := path.AStar(start, goal, g, heuristic) gotPath, gotWeight := pt.To(goal) wantPath, wantWeight, _ := ps.Between(start, goal) if gotWeight != wantWeight { t.Errorf("unexpected path weight from %v to %v result: got:%s want:%s", start, goal, gotWeight, wantWeight) } if !reflect.DeepEqual(gotPath, wantPath) { t.Errorf("unexpected path from %v to %v result:\ngot: %v\nwant:%v", start, goal, gotPath, wantPath) } } } } type locatedNode struct { id int x, y float64 } func (n locatedNode) ID() int { return n.id } type weightedEdge struct { from, to graph.Node cost float64 } func (e weightedEdge) From() graph.Node { return e.from } func (e weightedEdge) To() graph.Node { return e.to } type costEdgeListGraph interface { graph.Weighter path.EdgeListerGraph } func isMonotonic(g costEdgeListGraph, h path.Heuristic) (ok bool, at graph.Edge, goal graph.Node) { for _, goal := range g.Nodes() { for _, edge := range g.Edges() { from := edge.From() to := edge.To() if h(from, goal) > g.Weight(edge)+h(to, goal) { return false, edge, goal } } } return true, nil, nil } func TestAStarNullHeuristic(t *testing.T) { for _, test := range shortestPathTests { g := test.g() for _, e := range test.edges { g.SetEdge(e, e.Cost) } var ( pt path.Shortest panicked bool ) func() { defer func() { panicked = recover() != nil }() pt, _ = path.AStar(test.query.From(), test.query.To(), g.(graph.Graph), nil) }() if panicked || test.negative { if !test.negative { t.Errorf("%q: unexpected panic", test.name) } if !panicked { t.Errorf("%q: expected panic for negative edge weight", test.name) } continue } if pt.From().ID() != test.query.From().ID() { t.Fatalf("%q: unexpected from node ID: got:%d want:%d", pt.From().ID(), test.query.From().ID()) } p, weight := pt.To(test.query.To()) if weight != test.weight { t.Errorf("%q: unexpected weight from Between: got:%f want:%f", test.name, weight, test.weight) } if weight := pt.WeightTo(test.query.To()); weight != test.weight { t.Errorf("%q: unexpected weight from Weight: got:%f want:%f", test.name, weight, test.weight) } var got []int for _, n := range p { got = append(got, n.ID()) } ok := len(got) == 0 && len(test.want) == 0 for _, sp := range test.want { if reflect.DeepEqual(got, sp) { ok = true break } } if !ok { t.Errorf("%q: unexpected shortest path:\ngot: %v\nwant from:%v", test.name, p, test.want) } np, weight := pt.To(test.none.To()) if pt.From().ID() == test.none.From().ID() && (np != nil || !math.IsInf(weight, 1)) { t.Errorf("%q: unexpected path:\ngot: path=%v weight=%f\nwant:path=<nil> weight=+Inf", test.name, np, weight) } } }
cdrage/kedge
vendor/github.com/gonum/graph/path/a_star_test.go
GO
apache-2.0
7,212
#ifndef __LINUX_RTNETLINK_H #define __LINUX_RTNETLINK_H #include <linux/mutex.h> #include <linux/netdevice.h> #include <linux/wait.h> #include <uapi/linux/rtnetlink.h> extern int rtnetlink_send(struct sk_buff *skb, struct net *net, u32 pid, u32 group, int echo); extern int rtnl_unicast(struct sk_buff *skb, struct net *net, u32 pid); extern void rtnl_notify(struct sk_buff *skb, struct net *net, u32 pid, u32 group, struct nlmsghdr *nlh, gfp_t flags); extern void rtnl_set_sk_err(struct net *net, u32 group, int error); extern int rtnetlink_put_metrics(struct sk_buff *skb, u32 *metrics); extern int rtnl_put_cacheinfo(struct sk_buff *skb, struct dst_entry *dst, u32 id, long expires, u32 error); void rtmsg_ifinfo(int type, struct net_device *dev, unsigned change, gfp_t flags); struct sk_buff *rtmsg_ifinfo_build_skb(int type, struct net_device *dev, unsigned change, gfp_t flags); void rtmsg_ifinfo_send(struct sk_buff *skb, struct net_device *dev, gfp_t flags); /* RTNL is used as a global lock for all changes to network configuration */ extern void rtnl_lock(void); extern void rtnl_unlock(void); extern int rtnl_trylock(void); extern int rtnl_is_locked(void); extern wait_queue_head_t netdev_unregistering_wq; extern struct mutex net_mutex; #ifdef CONFIG_PROVE_LOCKING extern bool lockdep_rtnl_is_held(void); #else static inline bool lockdep_rtnl_is_held(void) { return true; } #endif /* #ifdef CONFIG_PROVE_LOCKING */ /** * rcu_dereference_rtnl - rcu_dereference with debug checking * @p: The pointer to read, prior to dereferencing * * Do an rcu_dereference(p), but check caller either holds rcu_read_lock() * or RTNL. Note : Please prefer rtnl_dereference() or rcu_dereference() */ #define rcu_dereference_rtnl(p) \ rcu_dereference_check(p, lockdep_rtnl_is_held()) /** * rcu_dereference_bh_rtnl - rcu_dereference_bh with debug checking * @p: The pointer to read, prior to dereference * * Do an rcu_dereference_bh(p), but check caller either holds rcu_read_lock_bh() * or RTNL. Note : Please prefer rtnl_dereference() or rcu_dereference_bh() */ #define rcu_dereference_bh_rtnl(p) \ rcu_dereference_bh_check(p, lockdep_rtnl_is_held()) /** * rtnl_dereference - fetch RCU pointer when updates are prevented by RTNL * @p: The pointer to read, prior to dereferencing * * Return the value of the specified RCU-protected pointer, but omit * both the smp_read_barrier_depends() and the ACCESS_ONCE(), because * caller holds RTNL. */ #define rtnl_dereference(p) \ rcu_dereference_protected(p, lockdep_rtnl_is_held()) static inline struct netdev_queue *dev_ingress_queue(struct net_device *dev) { return rtnl_dereference(dev->ingress_queue); } struct netdev_queue *dev_ingress_queue_create(struct net_device *dev); #ifdef CONFIG_NET_INGRESS void net_inc_ingress_queue(void); void net_dec_ingress_queue(void); #endif #ifdef CONFIG_NET_EGRESS void net_inc_egress_queue(void); void net_dec_egress_queue(void); #endif extern void rtnetlink_init(void); extern void __rtnl_unlock(void); #define ASSERT_RTNL() do { \ if (unlikely(!rtnl_is_locked())) { \ printk(KERN_ERR "RTNL: assertion failed at %s (%d)\n", \ __FILE__, __LINE__); \ dump_stack(); \ } \ } while(0) extern int ndo_dflt_fdb_dump(struct sk_buff *skb, struct netlink_callback *cb, struct net_device *dev, struct net_device *filter_dev, int idx); extern int ndo_dflt_fdb_add(struct ndmsg *ndm, struct nlattr *tb[], struct net_device *dev, const unsigned char *addr, u16 vid, u16 flags); extern int ndo_dflt_fdb_del(struct ndmsg *ndm, struct nlattr *tb[], struct net_device *dev, const unsigned char *addr, u16 vid); extern int ndo_dflt_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq, struct net_device *dev, u16 mode, u32 flags, u32 mask, int nlflags, u32 filter_mask, int (*vlan_fill)(struct sk_buff *skb, struct net_device *dev, u32 filter_mask)); #endif /* __LINUX_RTNETLINK_H */
mikedlowis-prototypes/albase
source/kernel/include/linux/rtnetlink.h
C
bsd-2-clause
4,090
<?php /* * Copyright 2010 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. */ /** * Service definition for Gmail (v1). * * <p> * The Gmail REST API.</p> * * <p> * For more information about this service, see the API * <a href="https://developers.google.com/gmail/api/" target="_blank">Documentation</a> * </p> * * @author Google, Inc. */ class Google_Service_Gmail extends Google_Service { /** View and manage your mail. */ const MAIL_GOOGLE_COM = "https://mail.google.com"; /** Manage drafts and send emails. */ const GMAIL_COMPOSE = "https://www.googleapis.com/auth/gmail.compose"; /** View and modify but not delete your email. */ const GMAIL_MODIFY = "https://www.googleapis.com/auth/gmail.modify"; /** View your emails messages and settings. */ const GMAIL_READONLY = "https://www.googleapis.com/auth/gmail.readonly"; public $users; public $users_drafts; public $users_history; public $users_labels; public $users_messages; public $users_messages_attachments; public $users_threads; /** * Constructs the internal representation of the Gmail service. * * @param Google_Client $client */ public function __construct(Google_Client $client) { parent::__construct($client); $this->servicePath = 'gmail/v1/users/'; $this->version = 'v1'; $this->serviceName = 'gmail'; $this->users = new Google_Service_Gmail_Users_Resource( $this, $this->serviceName, 'users', array( 'methods' => array( 'getProfile' => array( 'path' => '{userId}/profile', 'httpMethod' => 'GET', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ), ) ) ); $this->users_drafts = new Google_Service_Gmail_UsersDrafts_Resource( $this, $this->serviceName, 'drafts', array( 'methods' => array( 'create' => array( 'path' => '{userId}/drafts', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'delete' => array( 'path' => '{userId}/drafts/{id}', 'httpMethod' => 'DELETE', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'get' => array( 'path' => '{userId}/drafts/{id}', 'httpMethod' => 'GET', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'format' => array( 'location' => 'query', 'type' => 'string', ), ), ),'list' => array( 'path' => '{userId}/drafts', 'httpMethod' => 'GET', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'pageToken' => array( 'location' => 'query', 'type' => 'string', ), 'maxResults' => array( 'location' => 'query', 'type' => 'integer', ), ), ),'send' => array( 'path' => '{userId}/drafts/send', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'update' => array( 'path' => '{userId}/drafts/{id}', 'httpMethod' => 'PUT', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ), ) ) ); $this->users_history = new Google_Service_Gmail_UsersHistory_Resource( $this, $this->serviceName, 'history', array( 'methods' => array( 'list' => array( 'path' => '{userId}/history', 'httpMethod' => 'GET', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'pageToken' => array( 'location' => 'query', 'type' => 'string', ), 'maxResults' => array( 'location' => 'query', 'type' => 'integer', ), 'labelId' => array( 'location' => 'query', 'type' => 'string', ), 'startHistoryId' => array( 'location' => 'query', 'type' => 'string', ), ), ), ) ) ); $this->users_labels = new Google_Service_Gmail_UsersLabels_Resource( $this, $this->serviceName, 'labels', array( 'methods' => array( 'create' => array( 'path' => '{userId}/labels', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'delete' => array( 'path' => '{userId}/labels/{id}', 'httpMethod' => 'DELETE', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'get' => array( 'path' => '{userId}/labels/{id}', 'httpMethod' => 'GET', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'list' => array( 'path' => '{userId}/labels', 'httpMethod' => 'GET', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'patch' => array( 'path' => '{userId}/labels/{id}', 'httpMethod' => 'PATCH', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'update' => array( 'path' => '{userId}/labels/{id}', 'httpMethod' => 'PUT', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ), ) ) ); $this->users_messages = new Google_Service_Gmail_UsersMessages_Resource( $this, $this->serviceName, 'messages', array( 'methods' => array( 'delete' => array( 'path' => '{userId}/messages/{id}', 'httpMethod' => 'DELETE', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'get' => array( 'path' => '{userId}/messages/{id}', 'httpMethod' => 'GET', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'metadataHeaders' => array( 'location' => 'query', 'type' => 'string', 'repeated' => true, ), 'format' => array( 'location' => 'query', 'type' => 'string', ), ), ),'import' => array( 'path' => '{userId}/messages/import', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'internalDateSource' => array( 'location' => 'query', 'type' => 'string', ), ), ),'insert' => array( 'path' => '{userId}/messages', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'internalDateSource' => array( 'location' => 'query', 'type' => 'string', ), ), ),'list' => array( 'path' => '{userId}/messages', 'httpMethod' => 'GET', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'maxResults' => array( 'location' => 'query', 'type' => 'integer', ), 'q' => array( 'location' => 'query', 'type' => 'string', ), 'pageToken' => array( 'location' => 'query', 'type' => 'string', ), 'includeSpamTrash' => array( 'location' => 'query', 'type' => 'boolean', ), 'labelIds' => array( 'location' => 'query', 'type' => 'string', 'repeated' => true, ), ), ),'modify' => array( 'path' => '{userId}/messages/{id}/modify', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'send' => array( 'path' => '{userId}/messages/send', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'trash' => array( 'path' => '{userId}/messages/{id}/trash', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'untrash' => array( 'path' => '{userId}/messages/{id}/untrash', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ), ) ) ); $this->users_messages_attachments = new Google_Service_Gmail_UsersMessagesAttachments_Resource( $this, $this->serviceName, 'attachments', array( 'methods' => array( 'get' => array( 'path' => '{userId}/messages/{messageId}/attachments/{id}', 'httpMethod' => 'GET', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'messageId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ), ) ) ); $this->users_threads = new Google_Service_Gmail_UsersThreads_Resource( $this, $this->serviceName, 'threads', array( 'methods' => array( 'delete' => array( 'path' => '{userId}/threads/{id}', 'httpMethod' => 'DELETE', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'get' => array( 'path' => '{userId}/threads/{id}', 'httpMethod' => 'GET', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'metadataHeaders' => array( 'location' => 'query', 'type' => 'string', 'repeated' => true, ), 'format' => array( 'location' => 'query', 'type' => 'string', ), ), ),'list' => array( 'path' => '{userId}/threads', 'httpMethod' => 'GET', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'maxResults' => array( 'location' => 'query', 'type' => 'integer', ), 'q' => array( 'location' => 'query', 'type' => 'string', ), 'pageToken' => array( 'location' => 'query', 'type' => 'string', ), 'includeSpamTrash' => array( 'location' => 'query', 'type' => 'boolean', ), 'labelIds' => array( 'location' => 'query', 'type' => 'string', 'repeated' => true, ), ), ),'modify' => array( 'path' => '{userId}/threads/{id}/modify', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'trash' => array( 'path' => '{userId}/threads/{id}/trash', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'untrash' => array( 'path' => '{userId}/threads/{id}/untrash', 'httpMethod' => 'POST', 'parameters' => array( 'userId' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), 'id' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ), ) ) ); } } /** * The "users" collection of methods. * Typical usage is: * <code> * $gmailService = new Google_Service_Gmail(...); * $users = $gmailService->users; * </code> */ class Google_Service_Gmail_Users_Resource extends Google_Service_Resource { /** * Gets the current user's Gmail profile. (users.getProfile) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Profile */ public function getProfile($userId, $optParams = array()) { $params = array('userId' => $userId); $params = array_merge($params, $optParams); return $this->call('getProfile', array($params), "Google_Service_Gmail_Profile"); } } /** * The "drafts" collection of methods. * Typical usage is: * <code> * $gmailService = new Google_Service_Gmail(...); * $drafts = $gmailService->drafts; * </code> */ class Google_Service_Gmail_UsersDrafts_Resource extends Google_Service_Resource { /** * Creates a new draft with the DRAFT label. (drafts.create) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param Google_Draft $postBody * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Draft */ public function create($userId, Google_Service_Gmail_Draft $postBody, $optParams = array()) { $params = array('userId' => $userId, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('create', array($params), "Google_Service_Gmail_Draft"); } /** * Immediately and permanently deletes the specified draft. Does not simply * trash it. (drafts.delete) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the draft to delete. * @param array $optParams Optional parameters. */ public function delete($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('delete', array($params)); } /** * Gets the specified draft. (drafts.get) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the draft to retrieve. * @param array $optParams Optional parameters. * * @opt_param string format The format to return the draft in. * @return Google_Service_Gmail_Draft */ public function get($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('get', array($params), "Google_Service_Gmail_Draft"); } /** * Lists the drafts in the user's mailbox. (drafts.listUsersDrafts) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param array $optParams Optional parameters. * * @opt_param string pageToken Page token to retrieve a specific page of results * in the list. * @opt_param string maxResults Maximum number of drafts to return. * @return Google_Service_Gmail_ListDraftsResponse */ public function listUsersDrafts($userId, $optParams = array()) { $params = array('userId' => $userId); $params = array_merge($params, $optParams); return $this->call('list', array($params), "Google_Service_Gmail_ListDraftsResponse"); } /** * Sends the specified, existing draft to the recipients in the To, Cc, and Bcc * headers. (drafts.send) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param Google_Draft $postBody * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Message */ public function send($userId, Google_Service_Gmail_Draft $postBody, $optParams = array()) { $params = array('userId' => $userId, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('send', array($params), "Google_Service_Gmail_Message"); } /** * Replaces a draft's content. (drafts.update) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the draft to update. * @param Google_Draft $postBody * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Draft */ public function update($userId, $id, Google_Service_Gmail_Draft $postBody, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('update', array($params), "Google_Service_Gmail_Draft"); } } /** * The "history" collection of methods. * Typical usage is: * <code> * $gmailService = new Google_Service_Gmail(...); * $history = $gmailService->history; * </code> */ class Google_Service_Gmail_UsersHistory_Resource extends Google_Service_Resource { /** * Lists the history of all changes to the given mailbox. History results are * returned in chronological order (increasing historyId). * (history.listUsersHistory) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param array $optParams Optional parameters. * * @opt_param string pageToken Page token to retrieve a specific page of results * in the list. * @opt_param string maxResults The maximum number of history records to return. * @opt_param string labelId Only return messages with a label matching the ID. * @opt_param string startHistoryId Required. Returns history records after the * specified startHistoryId. The supplied startHistoryId should be obtained from * the historyId of a message, thread, or previous list response. History IDs * increase chronologically but are not contiguous with random gaps in between * valid IDs. Supplying an invalid or out of date startHistoryId typically * returns an HTTP 404 error code. A historyId is typically valid for at least a * week, but in some circumstances may be valid for only a few hours. If you * receive an HTTP 404 error response, your application should perform a full * sync. If you receive no nextPageToken in the response, there are no updates * to retrieve and you can store the returned historyId for a future request. * @return Google_Service_Gmail_ListHistoryResponse */ public function listUsersHistory($userId, $optParams = array()) { $params = array('userId' => $userId); $params = array_merge($params, $optParams); return $this->call('list', array($params), "Google_Service_Gmail_ListHistoryResponse"); } } /** * The "labels" collection of methods. * Typical usage is: * <code> * $gmailService = new Google_Service_Gmail(...); * $labels = $gmailService->labels; * </code> */ class Google_Service_Gmail_UsersLabels_Resource extends Google_Service_Resource { /** * Creates a new label. (labels.create) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param Google_Label $postBody * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Label */ public function create($userId, Google_Service_Gmail_Label $postBody, $optParams = array()) { $params = array('userId' => $userId, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('create', array($params), "Google_Service_Gmail_Label"); } /** * Immediately and permanently deletes the specified label and removes it from * any messages and threads that it is applied to. (labels.delete) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the label to delete. * @param array $optParams Optional parameters. */ public function delete($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('delete', array($params)); } /** * Gets the specified label. (labels.get) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the label to retrieve. * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Label */ public function get($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('get', array($params), "Google_Service_Gmail_Label"); } /** * Lists all labels in the user's mailbox. (labels.listUsersLabels) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param array $optParams Optional parameters. * @return Google_Service_Gmail_ListLabelsResponse */ public function listUsersLabels($userId, $optParams = array()) { $params = array('userId' => $userId); $params = array_merge($params, $optParams); return $this->call('list', array($params), "Google_Service_Gmail_ListLabelsResponse"); } /** * Updates the specified label. This method supports patch semantics. * (labels.patch) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the label to update. * @param Google_Label $postBody * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Label */ public function patch($userId, $id, Google_Service_Gmail_Label $postBody, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('patch', array($params), "Google_Service_Gmail_Label"); } /** * Updates the specified label. (labels.update) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the label to update. * @param Google_Label $postBody * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Label */ public function update($userId, $id, Google_Service_Gmail_Label $postBody, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('update', array($params), "Google_Service_Gmail_Label"); } } /** * The "messages" collection of methods. * Typical usage is: * <code> * $gmailService = new Google_Service_Gmail(...); * $messages = $gmailService->messages; * </code> */ class Google_Service_Gmail_UsersMessages_Resource extends Google_Service_Resource { /** * Immediately and permanently deletes the specified message. This operation * cannot be undone. Prefer messages.trash instead. (messages.delete) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the message to delete. * @param array $optParams Optional parameters. */ public function delete($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('delete', array($params)); } /** * Gets the specified message. (messages.get) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the message to retrieve. * @param array $optParams Optional parameters. * * @opt_param string metadataHeaders When given and format is METADATA, only * include headers specified. * @opt_param string format The format to return the message in. * @return Google_Service_Gmail_Message */ public function get($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('get', array($params), "Google_Service_Gmail_Message"); } /** * Imports a message into only this user's mailbox, with standard email delivery * scanning and classification similar to receiving via SMTP. Does not send a * message. (messages.import) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param Google_Message $postBody * @param array $optParams Optional parameters. * * @opt_param string internalDateSource Source for Gmail's internal date of the * message. * @return Google_Service_Gmail_Message */ public function import($userId, Google_Service_Gmail_Message $postBody, $optParams = array()) { $params = array('userId' => $userId, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('import', array($params), "Google_Service_Gmail_Message"); } /** * Directly inserts a message into only this user's mailbox similar to IMAP * APPEND, bypassing most scanning and classification. Does not send a message. * (messages.insert) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param Google_Message $postBody * @param array $optParams Optional parameters. * * @opt_param string internalDateSource Source for Gmail's internal date of the * message. * @return Google_Service_Gmail_Message */ public function insert($userId, Google_Service_Gmail_Message $postBody, $optParams = array()) { $params = array('userId' => $userId, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('insert', array($params), "Google_Service_Gmail_Message"); } /** * Lists the messages in the user's mailbox. (messages.listUsersMessages) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param array $optParams Optional parameters. * * @opt_param string maxResults Maximum number of messages to return. * @opt_param string q Only return messages matching the specified query. * Supports the same query format as the Gmail search box. For example, * "from:someuser@example.com rfc822msgid: is:unread". * @opt_param string pageToken Page token to retrieve a specific page of results * in the list. * @opt_param bool includeSpamTrash Include messages from SPAM and TRASH in the * results. * @opt_param string labelIds Only return messages with labels that match all of * the specified label IDs. * @return Google_Service_Gmail_ListMessagesResponse */ public function listUsersMessages($userId, $optParams = array()) { $params = array('userId' => $userId); $params = array_merge($params, $optParams); return $this->call('list', array($params), "Google_Service_Gmail_ListMessagesResponse"); } /** * Modifies the labels on the specified message. (messages.modify) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the message to modify. * @param Google_ModifyMessageRequest $postBody * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Message */ public function modify($userId, $id, Google_Service_Gmail_ModifyMessageRequest $postBody, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('modify', array($params), "Google_Service_Gmail_Message"); } /** * Sends the specified message to the recipients in the To, Cc, and Bcc headers. * (messages.send) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param Google_Message $postBody * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Message */ public function send($userId, Google_Service_Gmail_Message $postBody, $optParams = array()) { $params = array('userId' => $userId, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('send', array($params), "Google_Service_Gmail_Message"); } /** * Moves the specified message to the trash. (messages.trash) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the message to Trash. * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Message */ public function trash($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('trash', array($params), "Google_Service_Gmail_Message"); } /** * Removes the specified message from the trash. (messages.untrash) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the message to remove from Trash. * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Message */ public function untrash($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('untrash', array($params), "Google_Service_Gmail_Message"); } } /** * The "attachments" collection of methods. * Typical usage is: * <code> * $gmailService = new Google_Service_Gmail(...); * $attachments = $gmailService->attachments; * </code> */ class Google_Service_Gmail_UsersMessagesAttachments_Resource extends Google_Service_Resource { /** * Gets the specified message attachment. (attachments.get) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $messageId The ID of the message containing the attachment. * @param string $id The ID of the attachment. * @param array $optParams Optional parameters. * @return Google_Service_Gmail_MessagePartBody */ public function get($userId, $messageId, $id, $optParams = array()) { $params = array('userId' => $userId, 'messageId' => $messageId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('get', array($params), "Google_Service_Gmail_MessagePartBody"); } } /** * The "threads" collection of methods. * Typical usage is: * <code> * $gmailService = new Google_Service_Gmail(...); * $threads = $gmailService->threads; * </code> */ class Google_Service_Gmail_UsersThreads_Resource extends Google_Service_Resource { /** * Immediately and permanently deletes the specified thread. This operation * cannot be undone. Prefer threads.trash instead. (threads.delete) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id ID of the Thread to delete. * @param array $optParams Optional parameters. */ public function delete($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('delete', array($params)); } /** * Gets the specified thread. (threads.get) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the thread to retrieve. * @param array $optParams Optional parameters. * * @opt_param string metadataHeaders When given and format is METADATA, only * include headers specified. * @opt_param string format The format to return the messages in. * @return Google_Service_Gmail_Thread */ public function get($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('get', array($params), "Google_Service_Gmail_Thread"); } /** * Lists the threads in the user's mailbox. (threads.listUsersThreads) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param array $optParams Optional parameters. * * @opt_param string maxResults Maximum number of threads to return. * @opt_param string q Only return threads matching the specified query. * Supports the same query format as the Gmail search box. For example, * "from:someuser@example.com rfc822msgid: is:unread". * @opt_param string pageToken Page token to retrieve a specific page of results * in the list. * @opt_param bool includeSpamTrash Include threads from SPAM and TRASH in the * results. * @opt_param string labelIds Only return threads with labels that match all of * the specified label IDs. * @return Google_Service_Gmail_ListThreadsResponse */ public function listUsersThreads($userId, $optParams = array()) { $params = array('userId' => $userId); $params = array_merge($params, $optParams); return $this->call('list', array($params), "Google_Service_Gmail_ListThreadsResponse"); } /** * Modifies the labels applied to the thread. This applies to all messages in * the thread. (threads.modify) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the thread to modify. * @param Google_ModifyThreadRequest $postBody * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Thread */ public function modify($userId, $id, Google_Service_Gmail_ModifyThreadRequest $postBody, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('modify', array($params), "Google_Service_Gmail_Thread"); } /** * Moves the specified thread to the trash. (threads.trash) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the thread to Trash. * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Thread */ public function trash($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('trash', array($params), "Google_Service_Gmail_Thread"); } /** * Removes the specified thread from the trash. (threads.untrash) * * @param string $userId The user's email address. The special value me can be * used to indicate the authenticated user. * @param string $id The ID of the thread to remove from Trash. * @param array $optParams Optional parameters. * @return Google_Service_Gmail_Thread */ public function untrash($userId, $id, $optParams = array()) { $params = array('userId' => $userId, 'id' => $id); $params = array_merge($params, $optParams); return $this->call('untrash', array($params), "Google_Service_Gmail_Thread"); } } class Google_Service_Gmail_Draft extends Google_Model { protected $internal_gapi_mappings = array( ); public $id; protected $messageType = 'Google_Service_Gmail_Message'; protected $messageDataType = ''; public function setId($id) { $this->id = $id; } public function getId() { return $this->id; } public function setMessage(Google_Service_Gmail_Message $message) { $this->message = $message; } public function getMessage() { return $this->message; } } class Google_Service_Gmail_History extends Google_Collection { protected $collection_key = 'messages'; protected $internal_gapi_mappings = array( ); public $id; protected $messagesType = 'Google_Service_Gmail_Message'; protected $messagesDataType = 'array'; public function setId($id) { $this->id = $id; } public function getId() { return $this->id; } public function setMessages($messages) { $this->messages = $messages; } public function getMessages() { return $this->messages; } } class Google_Service_Gmail_Label extends Google_Model { protected $internal_gapi_mappings = array( ); public $id; public $labelListVisibility; public $messageListVisibility; public $messagesTotal; public $messagesUnread; public $name; public $threadsTotal; public $threadsUnread; public $type; public function setId($id) { $this->id = $id; } public function getId() { return $this->id; } public function setLabelListVisibility($labelListVisibility) { $this->labelListVisibility = $labelListVisibility; } public function getLabelListVisibility() { return $this->labelListVisibility; } public function setMessageListVisibility($messageListVisibility) { $this->messageListVisibility = $messageListVisibility; } public function getMessageListVisibility() { return $this->messageListVisibility; } public function setMessagesTotal($messagesTotal) { $this->messagesTotal = $messagesTotal; } public function getMessagesTotal() { return $this->messagesTotal; } public function setMessagesUnread($messagesUnread) { $this->messagesUnread = $messagesUnread; } public function getMessagesUnread() { return $this->messagesUnread; } public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } public function setThreadsTotal($threadsTotal) { $this->threadsTotal = $threadsTotal; } public function getThreadsTotal() { return $this->threadsTotal; } public function setThreadsUnread($threadsUnread) { $this->threadsUnread = $threadsUnread; } public function getThreadsUnread() { return $this->threadsUnread; } public function setType($type) { $this->type = $type; } public function getType() { return $this->type; } } class Google_Service_Gmail_ListDraftsResponse extends Google_Collection { protected $collection_key = 'drafts'; protected $internal_gapi_mappings = array( ); protected $draftsType = 'Google_Service_Gmail_Draft'; protected $draftsDataType = 'array'; public $nextPageToken; public $resultSizeEstimate; public function setDrafts($drafts) { $this->drafts = $drafts; } public function getDrafts() { return $this->drafts; } public function setNextPageToken($nextPageToken) { $this->nextPageToken = $nextPageToken; } public function getNextPageToken() { return $this->nextPageToken; } public function setResultSizeEstimate($resultSizeEstimate) { $this->resultSizeEstimate = $resultSizeEstimate; } public function getResultSizeEstimate() { return $this->resultSizeEstimate; } } class Google_Service_Gmail_ListHistoryResponse extends Google_Collection { protected $collection_key = 'history'; protected $internal_gapi_mappings = array( ); protected $historyType = 'Google_Service_Gmail_History'; protected $historyDataType = 'array'; public $historyId; public $nextPageToken; public function setHistory($history) { $this->history = $history; } public function getHistory() { return $this->history; } public function setHistoryId($historyId) { $this->historyId = $historyId; } public function getHistoryId() { return $this->historyId; } public function setNextPageToken($nextPageToken) { $this->nextPageToken = $nextPageToken; } public function getNextPageToken() { return $this->nextPageToken; } } class Google_Service_Gmail_ListLabelsResponse extends Google_Collection { protected $collection_key = 'labels'; protected $internal_gapi_mappings = array( ); protected $labelsType = 'Google_Service_Gmail_Label'; protected $labelsDataType = 'array'; public function setLabels($labels) { $this->labels = $labels; } public function getLabels() { return $this->labels; } } class Google_Service_Gmail_ListMessagesResponse extends Google_Collection { protected $collection_key = 'messages'; protected $internal_gapi_mappings = array( ); protected $messagesType = 'Google_Service_Gmail_Message'; protected $messagesDataType = 'array'; public $nextPageToken; public $resultSizeEstimate; public function setMessages($messages) { $this->messages = $messages; } public function getMessages() { return $this->messages; } public function setNextPageToken($nextPageToken) { $this->nextPageToken = $nextPageToken; } public function getNextPageToken() { return $this->nextPageToken; } public function setResultSizeEstimate($resultSizeEstimate) { $this->resultSizeEstimate = $resultSizeEstimate; } public function getResultSizeEstimate() { return $this->resultSizeEstimate; } } class Google_Service_Gmail_ListThreadsResponse extends Google_Collection { protected $collection_key = 'threads'; protected $internal_gapi_mappings = array( ); public $nextPageToken; public $resultSizeEstimate; protected $threadsType = 'Google_Service_Gmail_Thread'; protected $threadsDataType = 'array'; public function setNextPageToken($nextPageToken) { $this->nextPageToken = $nextPageToken; } public function getNextPageToken() { return $this->nextPageToken; } public function setResultSizeEstimate($resultSizeEstimate) { $this->resultSizeEstimate = $resultSizeEstimate; } public function getResultSizeEstimate() { return $this->resultSizeEstimate; } public function setThreads($threads) { $this->threads = $threads; } public function getThreads() { return $this->threads; } } class Google_Service_Gmail_Message extends Google_Collection { protected $collection_key = 'labelIds'; protected $internal_gapi_mappings = array( ); public $historyId; public $id; public $labelIds; protected $payloadType = 'Google_Service_Gmail_MessagePart'; protected $payloadDataType = ''; public $raw; public $sizeEstimate; public $snippet; public $threadId; public function setHistoryId($historyId) { $this->historyId = $historyId; } public function getHistoryId() { return $this->historyId; } public function setId($id) { $this->id = $id; } public function getId() { return $this->id; } public function setLabelIds($labelIds) { $this->labelIds = $labelIds; } public function getLabelIds() { return $this->labelIds; } public function setPayload(Google_Service_Gmail_MessagePart $payload) { $this->payload = $payload; } public function getPayload() { return $this->payload; } public function setRaw($raw) { $this->raw = $raw; } public function getRaw() { return $this->raw; } public function setSizeEstimate($sizeEstimate) { $this->sizeEstimate = $sizeEstimate; } public function getSizeEstimate() { return $this->sizeEstimate; } public function setSnippet($snippet) { $this->snippet = $snippet; } public function getSnippet() { return $this->snippet; } public function setThreadId($threadId) { $this->threadId = $threadId; } public function getThreadId() { return $this->threadId; } } class Google_Service_Gmail_MessagePart extends Google_Collection { protected $collection_key = 'parts'; protected $internal_gapi_mappings = array( ); protected $bodyType = 'Google_Service_Gmail_MessagePartBody'; protected $bodyDataType = ''; public $filename; protected $headersType = 'Google_Service_Gmail_MessagePartHeader'; protected $headersDataType = 'array'; public $mimeType; public $partId; protected $partsType = 'Google_Service_Gmail_MessagePart'; protected $partsDataType = 'array'; public function setBody(Google_Service_Gmail_MessagePartBody $body) { $this->body = $body; } public function getBody() { return $this->body; } public function setFilename($filename) { $this->filename = $filename; } public function getFilename() { return $this->filename; } public function setHeaders($headers) { $this->headers = $headers; } public function getHeaders() { return $this->headers; } public function setMimeType($mimeType) { $this->mimeType = $mimeType; } public function getMimeType() { return $this->mimeType; } public function setPartId($partId) { $this->partId = $partId; } public function getPartId() { return $this->partId; } public function setParts($parts) { $this->parts = $parts; } public function getParts() { return $this->parts; } } class Google_Service_Gmail_MessagePartBody extends Google_Model { protected $internal_gapi_mappings = array( ); public $attachmentId; public $data; public $size; public function setAttachmentId($attachmentId) { $this->attachmentId = $attachmentId; } public function getAttachmentId() { return $this->attachmentId; } public function setData($data) { $this->data = $data; } public function getData() { return $this->data; } public function setSize($size) { $this->size = $size; } public function getSize() { return $this->size; } } class Google_Service_Gmail_MessagePartHeader extends Google_Model { protected $internal_gapi_mappings = array( ); public $name; public $value; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } public function setValue($value) { $this->value = $value; } public function getValue() { return $this->value; } } class Google_Service_Gmail_ModifyMessageRequest extends Google_Collection { protected $collection_key = 'removeLabelIds'; protected $internal_gapi_mappings = array( ); public $addLabelIds; public $removeLabelIds; public function setAddLabelIds($addLabelIds) { $this->addLabelIds = $addLabelIds; } public function getAddLabelIds() { return $this->addLabelIds; } public function setRemoveLabelIds($removeLabelIds) { $this->removeLabelIds = $removeLabelIds; } public function getRemoveLabelIds() { return $this->removeLabelIds; } } class Google_Service_Gmail_ModifyThreadRequest extends Google_Collection { protected $collection_key = 'removeLabelIds'; protected $internal_gapi_mappings = array( ); public $addLabelIds; public $removeLabelIds; public function setAddLabelIds($addLabelIds) { $this->addLabelIds = $addLabelIds; } public function getAddLabelIds() { return $this->addLabelIds; } public function setRemoveLabelIds($removeLabelIds) { $this->removeLabelIds = $removeLabelIds; } public function getRemoveLabelIds() { return $this->removeLabelIds; } } class Google_Service_Gmail_Profile extends Google_Model { protected $internal_gapi_mappings = array( ); public $emailAddress; public $historyId; public $messagesTotal; public $threadsTotal; public function setEmailAddress($emailAddress) { $this->emailAddress = $emailAddress; } public function getEmailAddress() { return $this->emailAddress; } public function setHistoryId($historyId) { $this->historyId = $historyId; } public function getHistoryId() { return $this->historyId; } public function setMessagesTotal($messagesTotal) { $this->messagesTotal = $messagesTotal; } public function getMessagesTotal() { return $this->messagesTotal; } public function setThreadsTotal($threadsTotal) { $this->threadsTotal = $threadsTotal; } public function getThreadsTotal() { return $this->threadsTotal; } } class Google_Service_Gmail_Thread extends Google_Collection { protected $collection_key = 'messages'; protected $internal_gapi_mappings = array( ); public $historyId; public $id; protected $messagesType = 'Google_Service_Gmail_Message'; protected $messagesDataType = 'array'; public $snippet; public function setHistoryId($historyId) { $this->historyId = $historyId; } public function getHistoryId() { return $this->historyId; } public function setId($id) { $this->id = $id; } public function getId() { return $this->id; } public function setMessages($messages) { $this->messages = $messages; } public function getMessages() { return $this->messages; } public function setSnippet($snippet) { $this->snippet = $snippet; } public function getSnippet() { return $this->snippet; } }
monokal/docker-orangehrm
www/symfony/plugins/orangehrmOpenidAuthenticationPlugin/lib/vendor/GoogleAPIClient/Service/Gmail.php
PHP
gpl-2.0
58,081
/* * Copyright (c) 2012 GCT Semiconductor, Inc. All rights reserved. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/etherdevice.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/udp.h> #include <linux/in.h> #include <linux/if_arp.h> #include <linux/if_ether.h> #include <linux/if_vlan.h> #include <linux/in6.h> #include <linux/tcp.h> #include <linux/icmp.h> #include <linux/icmpv6.h> #include <linux/uaccess.h> #include <net/ndisc.h> #include "gdm_lte.h" #include "netlink_k.h" #include "hci.h" #include "hci_packet.h" #include "gdm_endian.h" /* * Netlink protocol number */ #define NETLINK_LTE 30 /* * Default MTU Size */ #define DEFAULT_MTU_SIZE 1500 #define IP_VERSION_4 4 #define IP_VERSION_6 6 static struct { int ref_cnt; struct sock *sock; } lte_event; static struct device_type wwan_type = { .name = "wwan", }; static int gdm_lte_open(struct net_device *dev) { netif_start_queue(dev); return 0; } static int gdm_lte_close(struct net_device *dev) { netif_stop_queue(dev); return 0; } static int gdm_lte_set_config(struct net_device *dev, struct ifmap *map) { if (dev->flags & IFF_UP) return -EBUSY; return 0; } static void tx_complete(void *arg) { struct nic *nic = arg; if (netif_queue_stopped(nic->netdev)) netif_wake_queue(nic->netdev); } static int gdm_lte_rx(struct sk_buff *skb, struct nic *nic, int nic_type) { int ret; ret = netif_rx_ni(skb); if (ret == NET_RX_DROP) { nic->stats.rx_dropped++; } else { nic->stats.rx_packets++; nic->stats.rx_bytes += skb->len + ETH_HLEN; } return 0; } static int gdm_lte_emulate_arp(struct sk_buff *skb_in, u32 nic_type) { struct nic *nic = netdev_priv(skb_in->dev); struct sk_buff *skb_out; struct ethhdr eth; struct vlan_ethhdr vlan_eth; struct arphdr *arp_in; struct arphdr *arp_out; struct arpdata { u8 ar_sha[ETH_ALEN]; u8 ar_sip[4]; u8 ar_tha[ETH_ALEN]; u8 ar_tip[4]; }; struct arpdata *arp_data_in; struct arpdata *arp_data_out; u8 arp_temp[60]; void *mac_header_data; u32 mac_header_len; /* Format the mac header so that it can be put to skb */ if (ntohs(((struct ethhdr *)skb_in->data)->h_proto) == ETH_P_8021Q) { memcpy(&vlan_eth, skb_in->data, sizeof(struct vlan_ethhdr)); mac_header_data = &vlan_eth; mac_header_len = VLAN_ETH_HLEN; } else { memcpy(&eth, skb_in->data, sizeof(struct ethhdr)); mac_header_data = &eth; mac_header_len = ETH_HLEN; } /* Get the pointer of the original request */ arp_in = (struct arphdr *)(skb_in->data + mac_header_len); arp_data_in = (struct arpdata *)(skb_in->data + mac_header_len + sizeof(struct arphdr)); /* Get the pointer of the outgoing response */ arp_out = (struct arphdr *)arp_temp; arp_data_out = (struct arpdata *)(arp_temp + sizeof(struct arphdr)); /* Copy the arp header */ memcpy(arp_out, arp_in, sizeof(struct arphdr)); arp_out->ar_op = htons(ARPOP_REPLY); /* Copy the arp payload: based on 2 bytes of mac and fill the IP */ arp_data_out->ar_sha[0] = arp_data_in->ar_sha[0]; arp_data_out->ar_sha[1] = arp_data_in->ar_sha[1]; memcpy(&arp_data_out->ar_sha[2], &arp_data_in->ar_tip[0], 4); memcpy(&arp_data_out->ar_sip[0], &arp_data_in->ar_tip[0], 4); memcpy(&arp_data_out->ar_tha[0], &arp_data_in->ar_sha[0], 6); memcpy(&arp_data_out->ar_tip[0], &arp_data_in->ar_sip[0], 4); /* Fill the destination mac with source mac of the received packet */ memcpy(mac_header_data, mac_header_data + ETH_ALEN, ETH_ALEN); /* Fill the source mac with nic's source mac */ memcpy(mac_header_data + ETH_ALEN, nic->src_mac_addr, ETH_ALEN); /* Alloc skb and reserve align */ skb_out = dev_alloc_skb(skb_in->len); if (!skb_out) return -ENOMEM; skb_reserve(skb_out, NET_IP_ALIGN); memcpy(skb_put(skb_out, mac_header_len), mac_header_data, mac_header_len); memcpy(skb_put(skb_out, sizeof(struct arphdr)), arp_out, sizeof(struct arphdr)); memcpy(skb_put(skb_out, sizeof(struct arpdata)), arp_data_out, sizeof(struct arpdata)); skb_out->protocol = ((struct ethhdr *)mac_header_data)->h_proto; skb_out->dev = skb_in->dev; skb_reset_mac_header(skb_out); skb_pull(skb_out, ETH_HLEN); gdm_lte_rx(skb_out, nic, nic_type); return 0; } static int icmp6_checksum(struct ipv6hdr *ipv6, u16 *ptr, int len) { unsigned short *w = ptr; int sum = 0; int i; union { struct { u8 ph_src[16]; u8 ph_dst[16]; u32 ph_len; u8 ph_zero[3]; u8 ph_nxt; } ph __packed; u16 pa[20]; } pseudo_header; memset(&pseudo_header, 0, sizeof(pseudo_header)); memcpy(&pseudo_header.ph.ph_src, &ipv6->saddr.in6_u.u6_addr8, 16); memcpy(&pseudo_header.ph.ph_dst, &ipv6->daddr.in6_u.u6_addr8, 16); pseudo_header.ph.ph_len = ipv6->payload_len; pseudo_header.ph.ph_nxt = ipv6->nexthdr; w = (u16 *)&pseudo_header; for (i = 0; i < ARRAY_SIZE(pseudo_header.pa); i++) sum += pseudo_header.pa[i]; w = ptr; while (len > 1) { sum += *w++; len -= 2; } sum = (sum >> 16) + (sum & 0xFFFF); sum += (sum >> 16); sum = ~sum & 0xffff; return sum; } static int gdm_lte_emulate_ndp(struct sk_buff *skb_in, u32 nic_type) { struct nic *nic = netdev_priv(skb_in->dev); struct sk_buff *skb_out; struct ethhdr eth; struct vlan_ethhdr vlan_eth; struct neighbour_advertisement { u8 target_address[16]; u8 type; u8 length; u8 link_layer_address[6]; }; struct neighbour_advertisement na; struct neighbour_solicitation { u8 target_address[16]; }; struct neighbour_solicitation *ns; struct ipv6hdr *ipv6_in; struct ipv6hdr ipv6_out; struct icmp6hdr *icmp6_in; struct icmp6hdr icmp6_out; void *mac_header_data; u32 mac_header_len; /* Format the mac header so that it can be put to skb */ if (ntohs(((struct ethhdr *)skb_in->data)->h_proto) == ETH_P_8021Q) { memcpy(&vlan_eth, skb_in->data, sizeof(struct vlan_ethhdr)); if (ntohs(vlan_eth.h_vlan_encapsulated_proto) != ETH_P_IPV6) return -1; mac_header_data = &vlan_eth; mac_header_len = VLAN_ETH_HLEN; } else { memcpy(&eth, skb_in->data, sizeof(struct ethhdr)); if (ntohs(eth.h_proto) != ETH_P_IPV6) return -1; mac_header_data = &eth; mac_header_len = ETH_HLEN; } /* Check if this is IPv6 ICMP packet */ ipv6_in = (struct ipv6hdr *)(skb_in->data + mac_header_len); if (ipv6_in->version != 6 || ipv6_in->nexthdr != IPPROTO_ICMPV6) return -1; /* Check if this is NDP packet */ icmp6_in = (struct icmp6hdr *)(skb_in->data + mac_header_len + sizeof(struct ipv6hdr)); if (icmp6_in->icmp6_type == NDISC_ROUTER_SOLICITATION) { /* Check RS */ return -1; } else if (icmp6_in->icmp6_type == NDISC_NEIGHBOUR_SOLICITATION) { /* Check NS */ u8 icmp_na[sizeof(struct icmp6hdr) + sizeof(struct neighbour_advertisement)]; u8 zero_addr8[16] = {0,}; if (memcmp(ipv6_in->saddr.in6_u.u6_addr8, zero_addr8, 16) == 0) /* Duplicate Address Detection: Source IP is all zero */ return 0; icmp6_out.icmp6_type = NDISC_NEIGHBOUR_ADVERTISEMENT; icmp6_out.icmp6_code = 0; icmp6_out.icmp6_cksum = 0; /* R=0, S=1, O=1 */ icmp6_out.icmp6_dataun.un_data32[0] = htonl(0x60000000); ns = (struct neighbour_solicitation *) (skb_in->data + mac_header_len + sizeof(struct ipv6hdr) + sizeof(struct icmp6hdr)); memcpy(&na.target_address, ns->target_address, 16); na.type = 0x02; na.length = 1; na.link_layer_address[0] = 0x00; na.link_layer_address[1] = 0x0a; na.link_layer_address[2] = 0x3b; na.link_layer_address[3] = 0xaf; na.link_layer_address[4] = 0x63; na.link_layer_address[5] = 0xc7; memcpy(&ipv6_out, ipv6_in, sizeof(struct ipv6hdr)); memcpy(ipv6_out.saddr.in6_u.u6_addr8, &na.target_address, 16); memcpy(ipv6_out.daddr.in6_u.u6_addr8, ipv6_in->saddr.in6_u.u6_addr8, 16); ipv6_out.payload_len = htons(sizeof(struct icmp6hdr) + sizeof(struct neighbour_advertisement)); memcpy(icmp_na, &icmp6_out, sizeof(struct icmp6hdr)); memcpy(icmp_na + sizeof(struct icmp6hdr), &na, sizeof(struct neighbour_advertisement)); icmp6_out.icmp6_cksum = icmp6_checksum(&ipv6_out, (u16 *)icmp_na, sizeof(icmp_na)); } else { return -1; } /* Fill the destination mac with source mac of the received packet */ memcpy(mac_header_data, mac_header_data + ETH_ALEN, ETH_ALEN); /* Fill the source mac with nic's source mac */ memcpy(mac_header_data + ETH_ALEN, nic->src_mac_addr, ETH_ALEN); /* Alloc skb and reserve align */ skb_out = dev_alloc_skb(skb_in->len); if (!skb_out) return -ENOMEM; skb_reserve(skb_out, NET_IP_ALIGN); memcpy(skb_put(skb_out, mac_header_len), mac_header_data, mac_header_len); memcpy(skb_put(skb_out, sizeof(struct ipv6hdr)), &ipv6_out, sizeof(struct ipv6hdr)); memcpy(skb_put(skb_out, sizeof(struct icmp6hdr)), &icmp6_out, sizeof(struct icmp6hdr)); memcpy(skb_put(skb_out, sizeof(struct neighbour_advertisement)), &na, sizeof(struct neighbour_advertisement)); skb_out->protocol = ((struct ethhdr *)mac_header_data)->h_proto; skb_out->dev = skb_in->dev; skb_reset_mac_header(skb_out); skb_pull(skb_out, ETH_HLEN); gdm_lte_rx(skb_out, nic, nic_type); return 0; } static s32 gdm_lte_tx_nic_type(struct net_device *dev, struct sk_buff *skb) { struct nic *nic = netdev_priv(dev); struct ethhdr *eth; struct vlan_ethhdr *vlan_eth; struct iphdr *ip; struct ipv6hdr *ipv6; int mac_proto; void *network_data; u32 nic_type = 0; /* NIC TYPE is based on the nic_id of this net_device */ nic_type = 0x00000010 | nic->nic_id; /* Get ethernet protocol */ eth = (struct ethhdr *)skb->data; if (ntohs(eth->h_proto) == ETH_P_8021Q) { vlan_eth = (struct vlan_ethhdr *)skb->data; mac_proto = ntohs(vlan_eth->h_vlan_encapsulated_proto); network_data = skb->data + VLAN_ETH_HLEN; nic_type |= NIC_TYPE_F_VLAN; } else { mac_proto = ntohs(eth->h_proto); network_data = skb->data + ETH_HLEN; } /* Process packet for nic type */ switch (mac_proto) { case ETH_P_ARP: nic_type |= NIC_TYPE_ARP; break; case ETH_P_IP: nic_type |= NIC_TYPE_F_IPV4; ip = network_data; /* Check DHCPv4 */ if (ip->protocol == IPPROTO_UDP) { struct udphdr *udp = network_data + sizeof(struct iphdr); if (ntohs(udp->dest) == 67 || ntohs(udp->dest) == 68) nic_type |= NIC_TYPE_F_DHCP; } break; case ETH_P_IPV6: nic_type |= NIC_TYPE_F_IPV6; ipv6 = network_data; if (ipv6->nexthdr == IPPROTO_ICMPV6) /* Check NDP request */ { struct icmp6hdr *icmp6 = network_data + sizeof(struct ipv6hdr); if (icmp6->icmp6_type == NDISC_NEIGHBOUR_SOLICITATION) nic_type |= NIC_TYPE_ICMPV6; } else if (ipv6->nexthdr == IPPROTO_UDP) /* Check DHCPv6 */ { struct udphdr *udp = network_data + sizeof(struct ipv6hdr); if (ntohs(udp->dest) == 546 || ntohs(udp->dest) == 547) nic_type |= NIC_TYPE_F_DHCP; } break; default: break; } return nic_type; } static int gdm_lte_tx(struct sk_buff *skb, struct net_device *dev) { struct nic *nic = netdev_priv(dev); u32 nic_type; void *data_buf; int data_len; int idx; int ret = 0; nic_type = gdm_lte_tx_nic_type(dev, skb); if (nic_type == 0) { netdev_err(dev, "tx - invalid nic_type\n"); return -1; } if (nic_type & NIC_TYPE_ARP) { if (gdm_lte_emulate_arp(skb, nic_type) == 0) { dev_kfree_skb(skb); return 0; } } if (nic_type & NIC_TYPE_ICMPV6) { if (gdm_lte_emulate_ndp(skb, nic_type) == 0) { dev_kfree_skb(skb); return 0; } } /* * Need byte shift (that is, remove VLAN tag) if there is one * For the case of ARP, this breaks the offset as vlan_ethhdr+4 * is treated as ethhdr However, it shouldn't be a problem as * the response starts from arp_hdr and ethhdr is created by this * driver based on the NIC mac */ if (nic_type & NIC_TYPE_F_VLAN) { struct vlan_ethhdr *vlan_eth = (struct vlan_ethhdr *)skb->data; nic->vlan_id = ntohs(vlan_eth->h_vlan_TCI) & VLAN_VID_MASK; data_buf = skb->data + (VLAN_ETH_HLEN - ETH_HLEN); data_len = skb->len - (VLAN_ETH_HLEN - ETH_HLEN); } else { nic->vlan_id = 0; data_buf = skb->data; data_len = skb->len; } /* If it is a ICMPV6 packet, clear all the other bits : * for backward compatibility with the firmware */ if (nic_type & NIC_TYPE_ICMPV6) nic_type = NIC_TYPE_ICMPV6; /* If it is not a dhcp packet, clear all the flag bits : * original NIC, otherwise the special flag (IPVX | DHCP) */ if (!(nic_type & NIC_TYPE_F_DHCP)) nic_type &= NIC_TYPE_MASK; ret = sscanf(dev->name, "lte%d", &idx); if (ret != 1) { dev_kfree_skb(skb); return -EINVAL; } ret = nic->phy_dev->send_sdu_func(nic->phy_dev->priv_dev, data_buf, data_len, nic->pdn_table.dft_eps_id, 0, tx_complete, nic, idx, nic_type); if (ret == TX_NO_BUFFER || ret == TX_NO_SPC) { netif_stop_queue(dev); if (ret == TX_NO_BUFFER) ret = 0; else ret = -ENOSPC; } else if (ret == TX_NO_DEV) { ret = -ENODEV; } /* Updates tx stats */ if (ret) { nic->stats.tx_dropped++; } else { nic->stats.tx_packets++; nic->stats.tx_bytes += data_len; } dev_kfree_skb(skb); return 0; } static struct net_device_stats *gdm_lte_stats(struct net_device *dev) { struct nic *nic = netdev_priv(dev); return &nic->stats; } static int gdm_lte_event_send(struct net_device *dev, char *buf, int len) { struct nic *nic = netdev_priv(dev); struct hci_packet *hci = (struct hci_packet *)buf; int idx; int ret; ret = sscanf(dev->name, "lte%d", &idx); if (ret != 1) return -EINVAL; return netlink_send(lte_event.sock, idx, 0, buf, gdm_dev16_to_cpu( nic->phy_dev->get_endian( nic->phy_dev->priv_dev), hci->len) + HCI_HEADER_SIZE); } static void gdm_lte_event_rcv(struct net_device *dev, u16 type, void *msg, int len) { struct nic *nic = netdev_priv(dev); nic->phy_dev->send_hci_func(nic->phy_dev->priv_dev, msg, len, NULL, NULL); } int gdm_lte_event_init(void) { if (lte_event.ref_cnt == 0) lte_event.sock = netlink_init(NETLINK_LTE, gdm_lte_event_rcv); if (lte_event.sock) { lte_event.ref_cnt++; return 0; } pr_err("event init failed\n"); return -1; } void gdm_lte_event_exit(void) { if (lte_event.sock && --lte_event.ref_cnt == 0) { sock_release(lte_event.sock->sk_socket); lte_event.sock = NULL; } } static u8 find_dev_index(u32 nic_type) { u8 index; index = (u8)(nic_type & 0x0000000f); if (index > MAX_NIC_TYPE) index = 0; return index; } static void gdm_lte_netif_rx(struct net_device *dev, char *buf, int len, int flagged_nic_type) { u32 nic_type; struct nic *nic; struct sk_buff *skb; struct ethhdr eth; struct vlan_ethhdr vlan_eth; void *mac_header_data; u32 mac_header_len; char ip_version = 0; nic_type = flagged_nic_type & NIC_TYPE_MASK; nic = netdev_priv(dev); if (flagged_nic_type & NIC_TYPE_F_DHCP) { /* Change the destination mac address * with the one requested the IP */ if (flagged_nic_type & NIC_TYPE_F_IPV4) { struct dhcp_packet { u8 op; /* BOOTREQUEST or BOOTREPLY */ u8 htype; /* hardware address type. * 1 = 10mb ethernet */ u8 hlen; /* hardware address length */ u8 hops; /* used by relay agents only */ u32 xid; /* unique id */ u16 secs; /* elapsed since client began * acquisition/renewal */ u16 flags; /* only one flag so far: */ #define BROADCAST_FLAG 0x8000 /* "I need broadcast replies" */ u32 ciaddr; /* client IP (if client is in * BOUND, RENEW or REBINDING state) */ u32 yiaddr; /* 'your' (client) IP address */ /* IP address of next server to use in * bootstrap, returned in DHCPOFFER, * DHCPACK by server */ u32 siaddr_nip; u32 gateway_nip; /* relay agent IP address */ u8 chaddr[16]; /* link-layer client hardware * address (MAC) */ u8 sname[64]; /* server host name (ASCIZ) */ u8 file[128]; /* boot file name (ASCIZ) */ u32 cookie; /* fixed first four option * bytes (99,130,83,99 dec) */ } __packed; void *addr = buf + sizeof(struct iphdr) + sizeof(struct udphdr) + offsetof(struct dhcp_packet, chaddr); ether_addr_copy(nic->dest_mac_addr, addr); } } if (nic->vlan_id > 0) { mac_header_data = (void *)&vlan_eth; mac_header_len = VLAN_ETH_HLEN; } else { mac_header_data = (void *)&eth; mac_header_len = ETH_HLEN; } /* Format the data so that it can be put to skb */ ether_addr_copy(mac_header_data, nic->dest_mac_addr); memcpy(mac_header_data + ETH_ALEN, nic->src_mac_addr, ETH_ALEN); vlan_eth.h_vlan_TCI = htons(nic->vlan_id); vlan_eth.h_vlan_proto = htons(ETH_P_8021Q); if (nic_type == NIC_TYPE_ARP) { /* Should be response: Only happens because * there was a request from the host */ eth.h_proto = htons(ETH_P_ARP); vlan_eth.h_vlan_encapsulated_proto = htons(ETH_P_ARP); } else { ip_version = buf[0] >> 4; if (ip_version == IP_VERSION_4) { eth.h_proto = htons(ETH_P_IP); vlan_eth.h_vlan_encapsulated_proto = htons(ETH_P_IP); } else if (ip_version == IP_VERSION_6) { eth.h_proto = htons(ETH_P_IPV6); vlan_eth.h_vlan_encapsulated_proto = htons(ETH_P_IPV6); } else { netdev_err(dev, "Unknown IP version %d\n", ip_version); return; } } /* Alloc skb and reserve align */ skb = dev_alloc_skb(len + mac_header_len + NET_IP_ALIGN); if (!skb) return; skb_reserve(skb, NET_IP_ALIGN); memcpy(skb_put(skb, mac_header_len), mac_header_data, mac_header_len); memcpy(skb_put(skb, len), buf, len); skb->protocol = ((struct ethhdr *)mac_header_data)->h_proto; skb->dev = dev; skb_reset_mac_header(skb); skb_pull(skb, ETH_HLEN); gdm_lte_rx(skb, nic, nic_type); } static void gdm_lte_multi_sdu_pkt(struct phy_dev *phy_dev, char *buf, int len) { struct net_device *dev; struct multi_sdu *multi_sdu = (struct multi_sdu *)buf; struct sdu *sdu = NULL; u8 *data = (u8 *)multi_sdu->data; u16 i = 0; u16 num_packet; u16 hci_len; u16 cmd_evt; u32 nic_type; u8 index; hci_len = gdm_dev16_to_cpu(phy_dev->get_endian(phy_dev->priv_dev), multi_sdu->len); num_packet = gdm_dev16_to_cpu(phy_dev->get_endian(phy_dev->priv_dev), multi_sdu->num_packet); for (i = 0; i < num_packet; i++) { sdu = (struct sdu *)data; cmd_evt = gdm_dev16_to_cpu(phy_dev-> get_endian(phy_dev->priv_dev), sdu->cmd_evt); hci_len = gdm_dev16_to_cpu(phy_dev-> get_endian(phy_dev->priv_dev), sdu->len); nic_type = gdm_dev32_to_cpu(phy_dev-> get_endian(phy_dev->priv_dev), sdu->nic_type); if (cmd_evt != LTE_RX_SDU) { pr_err("rx sdu wrong hci %04x\n", cmd_evt); return; } if (hci_len < 12) { pr_err("rx sdu invalid len %d\n", hci_len); return; } index = find_dev_index(nic_type); if (index < MAX_NIC_TYPE) { dev = phy_dev->dev[index]; gdm_lte_netif_rx(dev, (char *)sdu->data, (int)(hci_len - 12), nic_type); } else { pr_err("rx sdu invalid nic_type :%x\n", nic_type); } data += ((hci_len + 3) & 0xfffc) + HCI_HEADER_SIZE; } } static void gdm_lte_pdn_table(struct net_device *dev, char *buf, int len) { struct nic *nic = netdev_priv(dev); struct hci_pdn_table_ind *pdn_table = (struct hci_pdn_table_ind *)buf; if (pdn_table->activate) { nic->pdn_table.activate = pdn_table->activate; nic->pdn_table.dft_eps_id = gdm_dev32_to_cpu( nic->phy_dev->get_endian( nic->phy_dev->priv_dev), pdn_table->dft_eps_id); nic->pdn_table.nic_type = gdm_dev32_to_cpu( nic->phy_dev->get_endian( nic->phy_dev->priv_dev), pdn_table->nic_type); netdev_info(dev, "pdn activated, nic_type=0x%x\n", nic->pdn_table.nic_type); } else { memset(&nic->pdn_table, 0x00, sizeof(struct pdn_table)); netdev_info(dev, "pdn deactivated\n"); } } static int gdm_lte_receive_pkt(struct phy_dev *phy_dev, char *buf, int len) { struct hci_packet *hci = (struct hci_packet *)buf; struct hci_pdn_table_ind *pdn_table = (struct hci_pdn_table_ind *)buf; struct sdu *sdu; struct net_device *dev; int ret = 0; u16 cmd_evt; u32 nic_type; u8 index; if (!len) return ret; cmd_evt = gdm_dev16_to_cpu(phy_dev->get_endian(phy_dev->priv_dev), hci->cmd_evt); dev = phy_dev->dev[0]; if (!dev) return 0; switch (cmd_evt) { case LTE_RX_SDU: sdu = (struct sdu *)hci->data; nic_type = gdm_dev32_to_cpu(phy_dev-> get_endian(phy_dev->priv_dev), sdu->nic_type); index = find_dev_index(nic_type); dev = phy_dev->dev[index]; gdm_lte_netif_rx(dev, hci->data, len, nic_type); break; case LTE_RX_MULTI_SDU: gdm_lte_multi_sdu_pkt(phy_dev, buf, len); break; case LTE_LINK_ON_OFF_INDICATION: netdev_info(dev, "link %s\n", ((struct hci_connect_ind *)buf)->connect ? "on" : "off"); break; case LTE_PDN_TABLE_IND: pdn_table = (struct hci_pdn_table_ind *)buf; nic_type = gdm_dev32_to_cpu(phy_dev-> get_endian(phy_dev->priv_dev), pdn_table->nic_type); index = find_dev_index(nic_type); dev = phy_dev->dev[index]; gdm_lte_pdn_table(dev, buf, len); /* Fall through */ default: ret = gdm_lte_event_send(dev, buf, len); break; } return ret; } static int rx_complete(void *arg, void *data, int len, int context) { struct phy_dev *phy_dev = arg; return gdm_lte_receive_pkt(phy_dev, data, len); } void start_rx_proc(struct phy_dev *phy_dev) { int i; for (i = 0; i < MAX_RX_SUBMIT_COUNT; i++) phy_dev->rcv_func(phy_dev->priv_dev, rx_complete, phy_dev, USB_COMPLETE); } static struct net_device_ops gdm_netdev_ops = { .ndo_open = gdm_lte_open, .ndo_stop = gdm_lte_close, .ndo_set_config = gdm_lte_set_config, .ndo_start_xmit = gdm_lte_tx, .ndo_get_stats = gdm_lte_stats, }; static u8 gdm_lte_macaddr[ETH_ALEN] = {0x00, 0x0a, 0x3b, 0x00, 0x00, 0x00}; static void form_mac_address(u8 *dev_addr, u8 *nic_src, u8 *nic_dest, u8 *mac_address, u8 index) { /* Form the dev_addr */ if (!mac_address) ether_addr_copy(dev_addr, gdm_lte_macaddr); else ether_addr_copy(dev_addr, mac_address); /* The last byte of the mac address * should be less than or equal to 0xFC */ dev_addr[ETH_ALEN - 1] += index; /* Create random nic src and copy the first * 3 bytes to be the same as dev_addr */ eth_random_addr(nic_src); memcpy(nic_src, dev_addr, 3); /* Copy the nic_dest from dev_addr*/ ether_addr_copy(nic_dest, dev_addr); } static void validate_mac_address(u8 *mac_address) { /* if zero address or multicast bit set, restore the default value */ if (is_zero_ether_addr(mac_address) || (mac_address[0] & 0x01)) { pr_err("MAC invalid, restoring default\n"); memcpy(mac_address, gdm_lte_macaddr, 6); } } int register_lte_device(struct phy_dev *phy_dev, struct device *dev, u8 *mac_address) { struct nic *nic; struct net_device *net; char pdn_dev_name[16]; int ret = 0; u8 index; validate_mac_address(mac_address); for (index = 0; index < MAX_NIC_TYPE; index++) { /* Create device name lteXpdnX */ sprintf(pdn_dev_name, "lte%%dpdn%d", index); /* Allocate netdev */ net = alloc_netdev(sizeof(struct nic), pdn_dev_name, NET_NAME_UNKNOWN, ether_setup); if (!net) { pr_err("alloc_netdev failed\n"); ret = -ENOMEM; goto err; } net->netdev_ops = &gdm_netdev_ops; net->flags &= ~IFF_MULTICAST; net->mtu = DEFAULT_MTU_SIZE; nic = netdev_priv(net); memset(nic, 0, sizeof(struct nic)); nic->netdev = net; nic->phy_dev = phy_dev; nic->nic_id = index; form_mac_address( net->dev_addr, nic->src_mac_addr, nic->dest_mac_addr, mac_address, index); SET_NETDEV_DEV(net, dev); SET_NETDEV_DEVTYPE(net, &wwan_type); ret = register_netdev(net); if (ret) goto err; netif_carrier_on(net); phy_dev->dev[index] = net; } return 0; err: unregister_lte_device(phy_dev); return ret; } void unregister_lte_device(struct phy_dev *phy_dev) { struct net_device *net; int index; for (index = 0; index < MAX_NIC_TYPE; index++) { net = phy_dev->dev[index]; if (!net) continue; unregister_netdev(net); free_netdev(net); } }
geminy/aidear
oss/linux/linux-4.7/drivers/staging/gdm724x/gdm_lte.c
C
gpl-3.0
24,428
<li> <a href="#glyphicons">Glyphicons</a> <ul class="nav"> <li><a href="#glyphicons-glyphs">Available glyphs</a></li> <li><a href="#glyphicons-how-to-use">How to use</a></li> <li><a href="#glyphicons-examples">Examples</a></li> </ul> </li> <li> <a href="#dropdowns">Dropdowns</a> <ul class="nav"> <li><a href="#dropdowns-example">Example</a></li> <li><a href="#dropdowns-alignment">Alignment options</a></li> <li><a href="#dropdowns-headers">Headers</a></li> <li><a href="#dropdowns-disabled">Disabled menu items</a></li> </ul> </li> <li> <a href="#btn-groups">Button groups</a> <ul class="nav"> <li><a href="#btn-groups-single">Basic example</a></li> <li><a href="#btn-groups-toolbar">Button toolbar</a></li> <li><a href="#btn-groups-sizing">Sizing</a></li> <li><a href="#btn-groups-nested">Nesting</a></li> <li><a href="#btn-groups-vertical">Vertical variation</a></li> <li><a href="#btn-groups-justified">Justified link variation</a></li> </ul> </li> <li> <a href="#btn-dropdowns">Button dropdowns</a> <ul class="nav"> <li><a href="#btn-dropdowns-single">Single button dropdowns</a></li> <li><a href="#btn-dropdowns-split">Split button dropdowns</a></li> <li><a href="#btn-dropdowns-sizing">Sizing</a></li> <li><a href="#btn-dropdowns-dropup">Dropup variation</a></li> </ul> </li> <li> <a href="#input-groups">Input groups</a> <ul class="nav"> <li><a href="#input-groups-basic">Basic example</a></li> <li><a href="#input-groups-sizing">Sizing</a></li> <li><a href="#input-groups-checkboxes-radios">Checkbox and radios addons</a></li> <li><a href="#input-groups-buttons">Button addons</a></li> <li><a href="#input-groups-buttons-dropdowns">Buttons with dropdowns</a></li> <li><a href="#input-groups-buttons-segmented">Segmented buttons</a></li> </ul> </li> <li> <a href="#nav">Navs</a> <ul class="nav"> <li><a href="#nav-tabs">Tabs</a></li> <li><a href="#nav-pills">Pills</a></li> <li><a href="#nav-justified">Justified nav</a></li> <li><a href="#nav-disabled-links">Disabled links</a></li> <li><a href="#nav-dropdowns">Using dropdowns</a></li> </ul> </li> <li> <a href="#navbar">Navbar</a> <ul class="nav"> <li><a href="#navbar-default">Default navbar</a></li> <li><a href="#navbar-forms">Forms</a></li> <li><a href="#navbar-buttons">Buttons</a></li> <li><a href="#navbar-text">Text</a></li> <li><a href="#navbar-links">Non-nav links</a></li> <li><a href="#navbar-component-alignment">Component alignment</a></li> <li><a href="#navbar-fixed-top">Fixed to top</a></li> <li><a href="#navbar-fixed-bottom">Fixed to bottom</a></li> <li><a href="#navbar-static-top">Static top</a></li> <li><a href="#navbar-inverted">Inverted navbar</a></li> </ul> </li> <li><a href="#breadcrumbs">Breadcrumbs</a></li> <li> <a href="#pagination">Pagination</a> <ul class="nav"> <li><a href="#pagination-default">Default pagination</a></li> <li><a href="#pagination-pager">Pager</a></li> </ul> </li> <li><a href="#labels">Labels</a></li> <li><a href="#badges">Badges</a></li> <li><a href="#jumbotron">Jumbotron</a></li> <li><a href="#page-header">Page header</a></li> <li> <a href="#thumbnails">Thumbnails</a> <ul class="nav"> <li><a href="#thumbnails-default">Default example</a></li> <li><a href="#thumbnails-custom-content">Custom content</a></li> </ul> </li> <li> <a href="#alerts">Alerts</a> <ul class="nav"> <li><a href="#alerts-examples">Examples</a></li> <li><a href="#alerts-dismissable">Dismissable alerts</a></li> <li><a href="#alerts-links">Links in alerts</a></li> </ul> </li> <li> <a href="#progress">Progress bars</a> <ul class="nav"> <li><a href="#progress-basic">Basic example</a></li> <li><a href="#progress-label">With label</a></li> <li><a href="#progress-alternatives">Contextual alternatives</a></li> <li><a href="#progress-striped">Striped</a></li> <li><a href="#progress-animated">Animated</a></li> <li><a href="#progress-stacked">Stacked</a></li> </ul> </li> <li> <a href="#media">Media object</a> <ul class="nav"> <li><a href="#media-default">Default media</a></li> <li><a href="#media-list">Media list</a></li> </ul> </li> <li> <a href="#list-group">List group</a> <ul class="nav"> <li><a href="#list-group-basic">Basic example</a></li> <li><a href="#list-group-badges">Badges</a></li> <li><a href="#list-group-linked">Linked items</a></li> <li><a href="#list-group-contextual-classes">Contextual classes</a></li> <li><a href="#list-group-custom-content">Custom content</a></li> </ul> </li> <li> <a href="#panels">Panels</a> <ul class="nav"> <li><a href="#panels-basic">Basic example</a></li> <li><a href="#panels-heading">Panel with heading</a></li> <li><a href="#panels-alternatives">Contextual alternatives</a></li> <li><a href="#panels-tables">With tables</a> <li><a href="#panels-list-group">With list groups</a> </ul> </li> <li><a href="#wells">Wells</a></li>
bocharsky-bw/bionic-symfony
web/libs/bootstrap-3.1.1/docs/_includes/nav-components.html
HTML
mit
5,109
/* * Intel Skylake I2S Machine Driver for NAU88L25+SSM4567 * * Copyright (C) 2015, Intel Corporation. All rights reserved. * * Modified from: * Intel Skylake I2S Machine Driver for NAU88L25 and SSM4567 * * Copyright (C) 2015, Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/module.h> #include <linux/platform_device.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/soc.h> #include <sound/jack.h> #include <sound/pcm_params.h> #include "../../codecs/nau8825.h" #include "../../codecs/hdac_hdmi.h" #include "../skylake/skl.h" #define SKL_NUVOTON_CODEC_DAI "nau8825-hifi" #define SKL_SSM_CODEC_DAI "ssm4567-hifi" #define DMIC_CH(p) p->list[p->count-1] static struct snd_soc_jack skylake_headset; static struct snd_soc_card skylake_audio_card; static const struct snd_pcm_hw_constraint_list *dmic_constraints; struct skl_hdmi_pcm { struct list_head head; struct snd_soc_dai *codec_dai; int device; }; struct skl_nau88125_private { struct list_head hdmi_pcm_list; }; enum { SKL_DPCM_AUDIO_PB = 0, SKL_DPCM_AUDIO_CP, SKL_DPCM_AUDIO_REF_CP, SKL_DPCM_AUDIO_DMIC_CP, SKL_DPCM_AUDIO_HDMI1_PB, SKL_DPCM_AUDIO_HDMI2_PB, SKL_DPCM_AUDIO_HDMI3_PB, }; static inline struct snd_soc_dai *skl_get_codec_dai(struct snd_soc_card *card) { struct snd_soc_pcm_runtime *rtd; list_for_each_entry(rtd, &card->rtd_list, list) { if (!strncmp(rtd->codec_dai->name, SKL_NUVOTON_CODEC_DAI, strlen(SKL_NUVOTON_CODEC_DAI))) return rtd->codec_dai; } return NULL; } static const struct snd_kcontrol_new skylake_controls[] = { SOC_DAPM_PIN_SWITCH("Headphone Jack"), SOC_DAPM_PIN_SWITCH("Headset Mic"), SOC_DAPM_PIN_SWITCH("Left Speaker"), SOC_DAPM_PIN_SWITCH("Right Speaker"), }; static int platform_clock_control(struct snd_soc_dapm_widget *w, struct snd_kcontrol *k, int event) { struct snd_soc_dapm_context *dapm = w->dapm; struct snd_soc_card *card = dapm->card; struct snd_soc_dai *codec_dai; int ret; codec_dai = skl_get_codec_dai(card); if (!codec_dai) { dev_err(card->dev, "Codec dai not found\n"); return -EIO; } if (SND_SOC_DAPM_EVENT_ON(event)) { ret = snd_soc_dai_set_sysclk(codec_dai, NAU8825_CLK_MCLK, 24000000, SND_SOC_CLOCK_IN); if (ret < 0) { dev_err(card->dev, "set sysclk err = %d\n", ret); return -EIO; } } else { ret = snd_soc_dai_set_sysclk(codec_dai, NAU8825_CLK_INTERNAL, 0, SND_SOC_CLOCK_IN); if (ret < 0) { dev_err(card->dev, "set sysclk err = %d\n", ret); return -EIO; } } return ret; } static const struct snd_soc_dapm_widget skylake_widgets[] = { SND_SOC_DAPM_HP("Headphone Jack", NULL), SND_SOC_DAPM_MIC("Headset Mic", NULL), SND_SOC_DAPM_SPK("Left Speaker", NULL), SND_SOC_DAPM_SPK("Right Speaker", NULL), SND_SOC_DAPM_MIC("SoC DMIC", NULL), SND_SOC_DAPM_SPK("DP", NULL), SND_SOC_DAPM_SPK("HDMI", NULL), SND_SOC_DAPM_SUPPLY("Platform Clock", SND_SOC_NOPM, 0, 0, platform_clock_control, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), }; static const struct snd_soc_dapm_route skylake_map[] = { /* HP jack connectors - unknown if we have jack detection */ {"Headphone Jack", NULL, "HPOL"}, {"Headphone Jack", NULL, "HPOR"}, /* speaker */ {"Left Speaker", NULL, "Left OUT"}, {"Right Speaker", NULL, "Right OUT"}, /* other jacks */ {"MIC", NULL, "Headset Mic"}, {"DMic", NULL, "SoC DMIC"}, {"HDMI", NULL, "hif5 Output"}, {"DP", NULL, "hif6 Output"}, /* CODEC BE connections */ { "Left Playback", NULL, "ssp0 Tx"}, { "Right Playback", NULL, "ssp0 Tx"}, { "ssp0 Tx", NULL, "codec0_out"}, /* IV feedback path */ { "codec0_lp_in", NULL, "ssp0 Rx"}, { "ssp0 Rx", NULL, "Left Capture Sense" }, { "ssp0 Rx", NULL, "Right Capture Sense" }, { "Playback", NULL, "ssp1 Tx"}, { "ssp1 Tx", NULL, "codec1_out"}, { "codec0_in", NULL, "ssp1 Rx" }, { "ssp1 Rx", NULL, "Capture" }, /* DMIC */ { "dmic01_hifi", NULL, "DMIC01 Rx" }, { "DMIC01 Rx", NULL, "DMIC AIF" }, { "hifi3", NULL, "iDisp3 Tx"}, { "iDisp3 Tx", NULL, "iDisp3_out"}, { "hifi2", NULL, "iDisp2 Tx"}, { "iDisp2 Tx", NULL, "iDisp2_out"}, { "hifi1", NULL, "iDisp1 Tx"}, { "iDisp1 Tx", NULL, "iDisp1_out"}, { "Headphone Jack", NULL, "Platform Clock" }, { "Headset Mic", NULL, "Platform Clock" }, }; static struct snd_soc_codec_conf ssm4567_codec_conf[] = { { .dev_name = "i2c-INT343B:00", .name_prefix = "Left", }, { .dev_name = "i2c-INT343B:01", .name_prefix = "Right", }, }; static struct snd_soc_dai_link_component ssm4567_codec_components[] = { { /* Left */ .name = "i2c-INT343B:00", .dai_name = SKL_SSM_CODEC_DAI, }, { /* Right */ .name = "i2c-INT343B:01", .dai_name = SKL_SSM_CODEC_DAI, }, }; static int skylake_ssm4567_codec_init(struct snd_soc_pcm_runtime *rtd) { int ret; /* Slot 1 for left */ ret = snd_soc_dai_set_tdm_slot(rtd->codec_dais[0], 0x01, 0x01, 2, 48); if (ret < 0) return ret; /* Slot 2 for right */ ret = snd_soc_dai_set_tdm_slot(rtd->codec_dais[1], 0x02, 0x02, 2, 48); if (ret < 0) return ret; return ret; } static int skylake_nau8825_codec_init(struct snd_soc_pcm_runtime *rtd) { int ret; struct snd_soc_codec *codec = rtd->codec; /* * 4 buttons here map to the google Reference headset * The use of these buttons can be decided by the user space. */ ret = snd_soc_card_jack_new(&skylake_audio_card, "Headset Jack", SND_JACK_HEADSET | SND_JACK_BTN_0 | SND_JACK_BTN_1 | SND_JACK_BTN_2 | SND_JACK_BTN_3, &skylake_headset, NULL, 0); if (ret) { dev_err(rtd->dev, "Headset Jack creation failed %d\n", ret); return ret; } nau8825_enable_jack_detect(codec, &skylake_headset); snd_soc_dapm_ignore_suspend(&rtd->card->dapm, "SoC DMIC"); return ret; } static int skylake_hdmi1_init(struct snd_soc_pcm_runtime *rtd) { struct skl_nau88125_private *ctx = snd_soc_card_get_drvdata(rtd->card); struct snd_soc_dai *dai = rtd->codec_dai; struct skl_hdmi_pcm *pcm; pcm = devm_kzalloc(rtd->card->dev, sizeof(*pcm), GFP_KERNEL); if (!pcm) return -ENOMEM; pcm->device = SKL_DPCM_AUDIO_HDMI1_PB; pcm->codec_dai = dai; list_add_tail(&pcm->head, &ctx->hdmi_pcm_list); return 0; } static int skylake_hdmi2_init(struct snd_soc_pcm_runtime *rtd) { struct skl_nau88125_private *ctx = snd_soc_card_get_drvdata(rtd->card); struct snd_soc_dai *dai = rtd->codec_dai; struct skl_hdmi_pcm *pcm; pcm = devm_kzalloc(rtd->card->dev, sizeof(*pcm), GFP_KERNEL); if (!pcm) return -ENOMEM; pcm->device = SKL_DPCM_AUDIO_HDMI2_PB; pcm->codec_dai = dai; list_add_tail(&pcm->head, &ctx->hdmi_pcm_list); return 0; } static int skylake_hdmi3_init(struct snd_soc_pcm_runtime *rtd) { struct skl_nau88125_private *ctx = snd_soc_card_get_drvdata(rtd->card); struct snd_soc_dai *dai = rtd->codec_dai; struct skl_hdmi_pcm *pcm; pcm = devm_kzalloc(rtd->card->dev, sizeof(*pcm), GFP_KERNEL); if (!pcm) return -ENOMEM; pcm->device = SKL_DPCM_AUDIO_HDMI3_PB; pcm->codec_dai = dai; list_add_tail(&pcm->head, &ctx->hdmi_pcm_list); return 0; } static int skylake_nau8825_fe_init(struct snd_soc_pcm_runtime *rtd) { struct snd_soc_dapm_context *dapm; struct snd_soc_component *component = rtd->cpu_dai->component; dapm = snd_soc_component_get_dapm(component); snd_soc_dapm_ignore_suspend(dapm, "Reference Capture"); return 0; } static unsigned int rates[] = { 48000, }; static struct snd_pcm_hw_constraint_list constraints_rates = { .count = ARRAY_SIZE(rates), .list = rates, .mask = 0, }; static unsigned int channels[] = { 2, }; static struct snd_pcm_hw_constraint_list constraints_channels = { .count = ARRAY_SIZE(channels), .list = channels, .mask = 0, }; static int skl_fe_startup(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; /* * on this platform for PCM device we support, * 48Khz * stereo * 16 bit audio */ runtime->hw.channels_max = 2; snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, &constraints_channels); runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE; snd_pcm_hw_constraint_msbits(runtime, 0, 16, 16); snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE, &constraints_rates); return 0; } static const struct snd_soc_ops skylake_nau8825_fe_ops = { .startup = skl_fe_startup, }; static int skylake_ssp_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT); /* The ADSP will covert the FE rate to 48k, stereo */ rate->min = rate->max = 48000; channels->min = channels->max = 2; /* set SSP0 to 24 bit */ snd_mask_none(fmt); snd_mask_set(fmt, SNDRV_PCM_FORMAT_S24_LE); return 0; } static int skylake_dmic_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); if (params_channels(params) == 2 || DMIC_CH(dmic_constraints) == 2) channels->min = channels->max = 2; else channels->min = channels->max = 4; return 0; } static int skylake_nau8825_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; int ret; ret = snd_soc_dai_set_sysclk(codec_dai, NAU8825_CLK_MCLK, 24000000, SND_SOC_CLOCK_IN); if (ret < 0) dev_err(rtd->dev, "snd_soc_dai_set_sysclk err = %d\n", ret); return ret; } static struct snd_soc_ops skylake_nau8825_ops = { .hw_params = skylake_nau8825_hw_params, }; static unsigned int channels_dmic[] = { 2, 4, }; static struct snd_pcm_hw_constraint_list constraints_dmic_channels = { .count = ARRAY_SIZE(channels_dmic), .list = channels_dmic, .mask = 0, }; static const unsigned int dmic_2ch[] = { 2, }; static const struct snd_pcm_hw_constraint_list constraints_dmic_2ch = { .count = ARRAY_SIZE(dmic_2ch), .list = dmic_2ch, .mask = 0, }; static int skylake_dmic_startup(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; runtime->hw.channels_max = DMIC_CH(dmic_constraints); snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, dmic_constraints); return snd_pcm_hw_constraint_list(substream->runtime, 0, SNDRV_PCM_HW_PARAM_RATE, &constraints_rates); } static struct snd_soc_ops skylake_dmic_ops = { .startup = skylake_dmic_startup, }; static unsigned int rates_16000[] = { 16000, }; static struct snd_pcm_hw_constraint_list constraints_16000 = { .count = ARRAY_SIZE(rates_16000), .list = rates_16000, }; static const unsigned int ch_mono[] = { 1, }; static const struct snd_pcm_hw_constraint_list constraints_refcap = { .count = ARRAY_SIZE(ch_mono), .list = ch_mono, }; static int skylake_refcap_startup(struct snd_pcm_substream *substream) { substream->runtime->hw.channels_max = 1; snd_pcm_hw_constraint_list(substream->runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, &constraints_refcap); return snd_pcm_hw_constraint_list(substream->runtime, 0, SNDRV_PCM_HW_PARAM_RATE, &constraints_16000); } static struct snd_soc_ops skylaye_refcap_ops = { .startup = skylake_refcap_startup, }; /* skylake digital audio interface glue - connects codec <--> CPU */ static struct snd_soc_dai_link skylake_dais[] = { /* Front End DAI links */ [SKL_DPCM_AUDIO_PB] = { .name = "Skl Audio Port", .stream_name = "Audio", .cpu_dai_name = "System Pin", .platform_name = "0000:00:1f.3", .dynamic = 1, .codec_name = "snd-soc-dummy", .codec_dai_name = "snd-soc-dummy-dai", .nonatomic = 1, .init = skylake_nau8825_fe_init, .trigger = { SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .dpcm_playback = 1, .ops = &skylake_nau8825_fe_ops, }, [SKL_DPCM_AUDIO_CP] = { .name = "Skl Audio Capture Port", .stream_name = "Audio Record", .cpu_dai_name = "System Pin", .platform_name = "0000:00:1f.3", .dynamic = 1, .codec_name = "snd-soc-dummy", .codec_dai_name = "snd-soc-dummy-dai", .nonatomic = 1, .trigger = { SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .dpcm_capture = 1, .ops = &skylake_nau8825_fe_ops, }, [SKL_DPCM_AUDIO_REF_CP] = { .name = "Skl Audio Reference cap", .stream_name = "Wake on Voice", .cpu_dai_name = "Reference Pin", .codec_name = "snd-soc-dummy", .codec_dai_name = "snd-soc-dummy-dai", .platform_name = "0000:00:1f.3", .init = NULL, .dpcm_capture = 1, .nonatomic = 1, .dynamic = 1, .ops = &skylaye_refcap_ops, }, [SKL_DPCM_AUDIO_DMIC_CP] = { .name = "Skl Audio DMIC cap", .stream_name = "dmiccap", .cpu_dai_name = "DMIC Pin", .codec_name = "snd-soc-dummy", .codec_dai_name = "snd-soc-dummy-dai", .platform_name = "0000:00:1f.3", .init = NULL, .dpcm_capture = 1, .nonatomic = 1, .dynamic = 1, .ops = &skylake_dmic_ops, }, [SKL_DPCM_AUDIO_HDMI1_PB] = { .name = "Skl HDMI Port1", .stream_name = "Hdmi1", .cpu_dai_name = "HDMI1 Pin", .codec_name = "snd-soc-dummy", .codec_dai_name = "snd-soc-dummy-dai", .platform_name = "0000:00:1f.3", .dpcm_playback = 1, .init = NULL, .trigger = { SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .nonatomic = 1, .dynamic = 1, }, [SKL_DPCM_AUDIO_HDMI2_PB] = { .name = "Skl HDMI Port2", .stream_name = "Hdmi2", .cpu_dai_name = "HDMI2 Pin", .codec_name = "snd-soc-dummy", .codec_dai_name = "snd-soc-dummy-dai", .platform_name = "0000:00:1f.3", .dpcm_playback = 1, .init = NULL, .trigger = { SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .nonatomic = 1, .dynamic = 1, }, [SKL_DPCM_AUDIO_HDMI3_PB] = { .name = "Skl HDMI Port3", .stream_name = "Hdmi3", .cpu_dai_name = "HDMI3 Pin", .codec_name = "snd-soc-dummy", .codec_dai_name = "snd-soc-dummy-dai", .platform_name = "0000:00:1f.3", .trigger = { SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .dpcm_playback = 1, .init = NULL, .nonatomic = 1, .dynamic = 1, }, /* Back End DAI links */ { /* SSP0 - Codec */ .name = "SSP0-Codec", .id = 0, .cpu_dai_name = "SSP0 Pin", .platform_name = "0000:00:1f.3", .no_pcm = 1, .codecs = ssm4567_codec_components, .num_codecs = ARRAY_SIZE(ssm4567_codec_components), .dai_fmt = SND_SOC_DAIFMT_DSP_A | SND_SOC_DAIFMT_IB_NF | SND_SOC_DAIFMT_CBS_CFS, .init = skylake_ssm4567_codec_init, .ignore_pmdown_time = 1, .be_hw_params_fixup = skylake_ssp_fixup, .dpcm_playback = 1, .dpcm_capture = 1, }, { /* SSP1 - Codec */ .name = "SSP1-Codec", .id = 1, .cpu_dai_name = "SSP1 Pin", .platform_name = "0000:00:1f.3", .no_pcm = 1, .codec_name = "i2c-10508825:00", .codec_dai_name = SKL_NUVOTON_CODEC_DAI, .init = skylake_nau8825_codec_init, .dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBS_CFS, .ignore_pmdown_time = 1, .be_hw_params_fixup = skylake_ssp_fixup, .ops = &skylake_nau8825_ops, .dpcm_playback = 1, .dpcm_capture = 1, }, { .name = "dmic01", .id = 2, .cpu_dai_name = "DMIC01 Pin", .codec_name = "dmic-codec", .codec_dai_name = "dmic-hifi", .platform_name = "0000:00:1f.3", .ignore_suspend = 1, .be_hw_params_fixup = skylake_dmic_fixup, .dpcm_capture = 1, .no_pcm = 1, }, { .name = "iDisp1", .id = 3, .cpu_dai_name = "iDisp1 Pin", .codec_name = "ehdaudio0D2", .codec_dai_name = "intel-hdmi-hifi1", .platform_name = "0000:00:1f.3", .dpcm_playback = 1, .init = skylake_hdmi1_init, .no_pcm = 1, }, { .name = "iDisp2", .id = 4, .cpu_dai_name = "iDisp2 Pin", .codec_name = "ehdaudio0D2", .codec_dai_name = "intel-hdmi-hifi2", .platform_name = "0000:00:1f.3", .init = skylake_hdmi2_init, .dpcm_playback = 1, .no_pcm = 1, }, { .name = "iDisp3", .id = 5, .cpu_dai_name = "iDisp3 Pin", .codec_name = "ehdaudio0D2", .codec_dai_name = "intel-hdmi-hifi3", .platform_name = "0000:00:1f.3", .init = skylake_hdmi3_init, .dpcm_playback = 1, .no_pcm = 1, }, }; static int skylake_card_late_probe(struct snd_soc_card *card) { struct skl_nau88125_private *ctx = snd_soc_card_get_drvdata(card); struct skl_hdmi_pcm *pcm; int err; list_for_each_entry(pcm, &ctx->hdmi_pcm_list, head) { err = hdac_hdmi_jack_init(pcm->codec_dai, pcm->device); if (err < 0) return err; } return 0; } /* skylake audio machine driver for SPT + NAU88L25 */ static struct snd_soc_card skylake_audio_card = { .name = "sklnau8825adi", .owner = THIS_MODULE, .dai_link = skylake_dais, .num_links = ARRAY_SIZE(skylake_dais), .controls = skylake_controls, .num_controls = ARRAY_SIZE(skylake_controls), .dapm_widgets = skylake_widgets, .num_dapm_widgets = ARRAY_SIZE(skylake_widgets), .dapm_routes = skylake_map, .num_dapm_routes = ARRAY_SIZE(skylake_map), .codec_conf = ssm4567_codec_conf, .num_configs = ARRAY_SIZE(ssm4567_codec_conf), .fully_routed = true, .late_probe = skylake_card_late_probe, }; static int skylake_audio_probe(struct platform_device *pdev) { struct skl_nau88125_private *ctx; struct skl_machine_pdata *pdata; ctx = devm_kzalloc(&pdev->dev, sizeof(*ctx), GFP_ATOMIC); if (!ctx) return -ENOMEM; INIT_LIST_HEAD(&ctx->hdmi_pcm_list); skylake_audio_card.dev = &pdev->dev; snd_soc_card_set_drvdata(&skylake_audio_card, ctx); pdata = dev_get_drvdata(&pdev->dev); if (pdata) dmic_constraints = pdata->dmic_num == 2 ? &constraints_dmic_2ch : &constraints_dmic_channels; return devm_snd_soc_register_card(&pdev->dev, &skylake_audio_card); } static const struct platform_device_id skl_board_ids[] = { { .name = "skl_n88l25_s4567" }, { .name = "kbl_n88l25_s4567" }, { } }; static struct platform_driver skylake_audio = { .probe = skylake_audio_probe, .driver = { .name = "skl_n88l25_s4567", .pm = &snd_soc_pm_ops, }, .id_table = skl_board_ids, }; module_platform_driver(skylake_audio) /* Module information */ MODULE_AUTHOR("Conrad Cooke <conrad.cooke@intel.com>"); MODULE_AUTHOR("Harsha Priya <harshapriya.n@intel.com>"); MODULE_AUTHOR("Naveen M <naveen.m@intel.com>"); MODULE_AUTHOR("Sathya Prakash M R <sathya.prakash.m.r@intel.com>"); MODULE_AUTHOR("Yong Zhi <yong.zhi@intel.com>"); MODULE_DESCRIPTION("Intel Audio Machine driver for SKL with NAU88L25 and SSM4567 in I2S Mode"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:skl_n88l25_s4567"); MODULE_ALIAS("platform:kbl_n88l25_s4567");
boddob/linux
sound/soc/intel/boards/skl_nau88l25_ssm4567.c
C
gpl-2.0
18,917
/* * linux/arch/arm/mach-nspire/nspire.c * * Copyright (C) 2013 Daniel Tang <tangrs@tangrs.id.au> * * 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/init.h> #include <linux/of_irq.h> #include <linux/of_address.h> #include <linux/of_platform.h> #include <linux/irqchip.h> #include <linux/irqchip/arm-vic.h> #include <linux/clkdev.h> #include <linux/amba/bus.h> #include <linux/amba/clcd.h> #include <asm/mach/arch.h> #include <asm/mach-types.h> #include <asm/mach/map.h> #include "mmio.h" #include "clcd.h" static const char *const nspire_dt_match[] __initconst = { "ti,nspire", "ti,nspire-cx", "ti,nspire-tp", "ti,nspire-clp", NULL, }; static struct clcd_board nspire_clcd_data = { .name = "LCD", .caps = CLCD_CAP_5551 | CLCD_CAP_565, .check = clcdfb_check, .decode = clcdfb_decode, .setup = nspire_clcd_setup, .mmap = nspire_clcd_mmap, .remove = nspire_clcd_remove, }; static struct of_dev_auxdata nspire_auxdata[] __initdata = { OF_DEV_AUXDATA("arm,pl111", NSPIRE_LCD_PHYS_BASE, NULL, &nspire_clcd_data), { } }; static void __init nspire_init(void) { of_platform_default_populate(NULL, nspire_auxdata, NULL); } static void nspire_restart(enum reboot_mode mode, const char *cmd) { void __iomem *base = ioremap(NSPIRE_MISC_PHYS_BASE, SZ_4K); if (!base) return; writel(2, base + NSPIRE_MISC_HWRESET); } DT_MACHINE_START(NSPIRE, "TI-NSPIRE") .dt_compat = nspire_dt_match, .init_machine = nspire_init, .restart = nspire_restart, MACHINE_END
BPI-SINOVOIP/BPI-Mainline-kernel
linux-4.19/arch/arm/mach-nspire/nspire.c
C
gpl-2.0
1,647
// Copyright 2015 Google Inc. 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. package events import ( "testing" "time" info "github.com/google/cadvisor/info/v1" "github.com/stretchr/testify/assert" ) func createOldTime(t *testing.T) time.Time { const longForm = "Jan 2, 2006 at 3:04pm (MST)" linetime, err := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)") if err != nil { t.Fatalf("could not format time.Time object") } else { return linetime } return time.Now() } // used to convert an OomInstance to an Event object func makeEvent(inTime time.Time, containerName string) *info.Event { return &info.Event{ ContainerName: containerName, Timestamp: inTime, EventType: info.EventOom, } } // returns EventManager and Request to use in tests func initializeScenario(t *testing.T) (*events, *Request, *info.Event, *info.Event) { fakeEvent := makeEvent(createOldTime(t), "/") fakeEvent2 := makeEvent(time.Now(), "/") return NewEventManager(DefaultStoragePolicy()), NewRequest(), fakeEvent, fakeEvent2 } func checkNumberOfEvents(t *testing.T, numEventsExpected int, numEventsReceived int) { if numEventsReceived != numEventsExpected { t.Fatalf("Expected to return %v events but received %v", numEventsExpected, numEventsReceived) } } func ensureProperEventReturned(t *testing.T, expectedEvent *info.Event, eventObjectFound *info.Event) { if eventObjectFound != expectedEvent { t.Errorf("Expected to find test object %v but found a different object: %v", expectedEvent, eventObjectFound) } } func TestCheckIfIsSubcontainer(t *testing.T) { myRequest := NewRequest() myRequest.ContainerName = "/root" rootRequest := NewRequest() rootRequest.ContainerName = "/" sameContainerEvent := &info.Event{ ContainerName: "/root", } subContainerEvent := &info.Event{ ContainerName: "/root/subdir", } differentContainerEvent := &info.Event{ ContainerName: "/root-completely-different-container", } if checkIfIsSubcontainer(rootRequest, sameContainerEvent) { t.Errorf("should not have found %v to be a subcontainer of %v", sameContainerEvent, rootRequest) } if !checkIfIsSubcontainer(myRequest, sameContainerEvent) { t.Errorf("should have found %v and %v had the same container name", myRequest, sameContainerEvent) } if checkIfIsSubcontainer(myRequest, subContainerEvent) { t.Errorf("should have found %v and %v had different containers", myRequest, subContainerEvent) } rootRequest.IncludeSubcontainers = true myRequest.IncludeSubcontainers = true if !checkIfIsSubcontainer(rootRequest, sameContainerEvent) { t.Errorf("should have found %v to be a subcontainer of %v", sameContainerEvent.ContainerName, rootRequest.ContainerName) } if !checkIfIsSubcontainer(myRequest, sameContainerEvent) { t.Errorf("should have found %v and %v had the same container", myRequest.ContainerName, sameContainerEvent.ContainerName) } if !checkIfIsSubcontainer(myRequest, subContainerEvent) { t.Errorf("should have found %v was a subcontainer of %v", subContainerEvent.ContainerName, myRequest.ContainerName) } if checkIfIsSubcontainer(myRequest, differentContainerEvent) { t.Errorf("should have found %v and %v had different containers", myRequest.ContainerName, differentContainerEvent.ContainerName) } } func TestWatchEventsDetectsNewEvents(t *testing.T) { myEventHolder, myRequest, fakeEvent, fakeEvent2 := initializeScenario(t) myRequest.EventType[info.EventOom] = true returnEventChannel, err := myEventHolder.WatchEvents(myRequest) assert.Nil(t, err) myEventHolder.AddEvent(fakeEvent) myEventHolder.AddEvent(fakeEvent2) startTime := time.Now() go func() { time.Sleep(5 * time.Second) if time.Since(startTime) > (5 * time.Second) { t.Errorf("Took too long to receive all the events") } }() eventsFound := 0 go func() { for event := range returnEventChannel.GetChannel() { eventsFound += 1 if eventsFound == 1 { ensureProperEventReturned(t, fakeEvent, event) } else if eventsFound == 2 { ensureProperEventReturned(t, fakeEvent2, event) break } } }() } func TestAddEventAddsEventsToEventManager(t *testing.T) { myEventHolder, _, fakeEvent, _ := initializeScenario(t) myEventHolder.AddEvent(fakeEvent) checkNumberOfEvents(t, 1, len(myEventHolder.eventStore)) ensureProperEventReturned(t, fakeEvent, myEventHolder.eventStore[info.EventOom].Get(0).(*info.Event)) } func TestGetEventsForOneEvent(t *testing.T) { myEventHolder, myRequest, fakeEvent, fakeEvent2 := initializeScenario(t) myRequest.MaxEventsReturned = 1 myRequest.EventType[info.EventOom] = true myEventHolder.AddEvent(fakeEvent) myEventHolder.AddEvent(fakeEvent2) receivedEvents, err := myEventHolder.GetEvents(myRequest) assert.Nil(t, err) checkNumberOfEvents(t, 1, len(receivedEvents)) ensureProperEventReturned(t, fakeEvent2, receivedEvents[0]) } func TestGetEventsForTimePeriod(t *testing.T) { myEventHolder, myRequest, fakeEvent, fakeEvent2 := initializeScenario(t) myRequest.StartTime = time.Now().Add(-1 * time.Second * 10) myRequest.EndTime = time.Now().Add(time.Second * 10) myRequest.EventType[info.EventOom] = true myEventHolder.AddEvent(fakeEvent) myEventHolder.AddEvent(fakeEvent2) receivedEvents, err := myEventHolder.GetEvents(myRequest) assert.Nil(t, err) checkNumberOfEvents(t, 1, len(receivedEvents)) ensureProperEventReturned(t, fakeEvent2, receivedEvents[0]) } func TestGetEventsForNoTypeRequested(t *testing.T) { myEventHolder, myRequest, fakeEvent, fakeEvent2 := initializeScenario(t) myEventHolder.AddEvent(fakeEvent) myEventHolder.AddEvent(fakeEvent2) receivedEvents, err := myEventHolder.GetEvents(myRequest) assert.Nil(t, err) checkNumberOfEvents(t, 0, len(receivedEvents)) }
wjiangjay/origin
vendor/github.com/google/cadvisor/events/handler_test.go
GO
apache-2.0
6,285
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using Xunit; namespace System.Runtime.CompilerServices.Tests { public class CallSiteBinderDefaultBehaviourTests { public class NopCallSiteBinder : CallSiteBinder { // Adds no behavior. public override Expression Bind(object[] args, ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel) { throw new NotImplementedException(); } } public class ThrowOnBindDelegate : NopCallSiteBinder { public static readonly Exception ExceptionToThrow = new Exception(); public override T BindDelegate<T>(CallSite<T> site, object[] args) { throw ExceptionToThrow; } } [Fact] public void UpdateLabelImmutableInstance() { Assert.Same(CallSiteBinder.UpdateLabel, CallSiteBinder.UpdateLabel); } [Fact] public void UpdateLabelProperties() { Assert.Equal("CallSiteBinder.UpdateLabel", CallSiteBinder.UpdateLabel.Name); Assert.Equal(typeof(void), CallSiteBinder.UpdateLabel.Type); } [Fact] public void BindDelegateNoValiationNoChangeNullResult() { CallSiteBinder binder = new NopCallSiteBinder(); // Not even a delegate type, and both arguments null. Assert.Null(binder.BindDelegate<object>(null, null)); // Likewise, with empty arguments; Assert.Null(binder.BindDelegate<object>(null, Array.Empty<object>())); // And elements not mutated in any way. var boxedInts = Enumerable.Range(0, 10).Select(i => (object)i).ToArray(); var args = boxedInts.ToArray(); // copy. Assert.Null(binder.BindDelegate<object>(null, args)); for (int i = 0; i != 10; ++i) { Assert.Same(boxedInts[i], args[i]); } } } }
dotnet-bot/corefx
src/System.Linq.Expressions/tests/Dynamic/CallSiteBinderDefaultBehaviourTests.cs
C#
mit
2,276
/* * Kprobes-based tracing events * * Created by Masami Hiramatsu <mhiramat@redhat.com> * * 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 */ #include <linux/module.h> #include <linux/uaccess.h> #include "trace_probe.h" #define KPROBE_EVENT_SYSTEM "kprobes" /** * Kprobe event core functions */ struct trace_kprobe { struct list_head list; struct kretprobe rp; /* Use rp.kp for kprobe use */ unsigned long nhit; const char *symbol; /* symbol name */ struct trace_probe tp; }; #define SIZEOF_TRACE_KPROBE(n) \ (offsetof(struct trace_kprobe, tp.args) + \ (sizeof(struct probe_arg) * (n))) static nokprobe_inline bool trace_kprobe_is_return(struct trace_kprobe *tk) { return tk->rp.handler != NULL; } static nokprobe_inline const char *trace_kprobe_symbol(struct trace_kprobe *tk) { return tk->symbol ? tk->symbol : "unknown"; } static nokprobe_inline unsigned long trace_kprobe_offset(struct trace_kprobe *tk) { return tk->rp.kp.offset; } static nokprobe_inline bool trace_kprobe_has_gone(struct trace_kprobe *tk) { return !!(kprobe_gone(&tk->rp.kp)); } static nokprobe_inline bool trace_kprobe_within_module(struct trace_kprobe *tk, struct module *mod) { int len = strlen(mod->name); const char *name = trace_kprobe_symbol(tk); return strncmp(mod->name, name, len) == 0 && name[len] == ':'; } static nokprobe_inline bool trace_kprobe_is_on_module(struct trace_kprobe *tk) { return !!strchr(trace_kprobe_symbol(tk), ':'); } static int register_kprobe_event(struct trace_kprobe *tk); static int unregister_kprobe_event(struct trace_kprobe *tk); static DEFINE_MUTEX(probe_lock); static LIST_HEAD(probe_list); static int kprobe_dispatcher(struct kprobe *kp, struct pt_regs *regs); static int kretprobe_dispatcher(struct kretprobe_instance *ri, struct pt_regs *regs); /* Memory fetching by symbol */ struct symbol_cache { char *symbol; long offset; unsigned long addr; }; unsigned long update_symbol_cache(struct symbol_cache *sc) { sc->addr = (unsigned long)kallsyms_lookup_name(sc->symbol); if (sc->addr) sc->addr += sc->offset; return sc->addr; } void free_symbol_cache(struct symbol_cache *sc) { kfree(sc->symbol); kfree(sc); } struct symbol_cache *alloc_symbol_cache(const char *sym, long offset) { struct symbol_cache *sc; if (!sym || strlen(sym) == 0) return NULL; sc = kzalloc(sizeof(struct symbol_cache), GFP_KERNEL); if (!sc) return NULL; sc->symbol = kstrdup(sym, GFP_KERNEL); if (!sc->symbol) { kfree(sc); return NULL; } sc->offset = offset; update_symbol_cache(sc); return sc; } /* * Kprobes-specific fetch functions */ #define DEFINE_FETCH_stack(type) \ static void FETCH_FUNC_NAME(stack, type)(struct pt_regs *regs, \ void *offset, void *dest) \ { \ *(type *)dest = (type)regs_get_kernel_stack_nth(regs, \ (unsigned int)((unsigned long)offset)); \ } \ NOKPROBE_SYMBOL(FETCH_FUNC_NAME(stack, type)); DEFINE_BASIC_FETCH_FUNCS(stack) /* No string on the stack entry */ #define fetch_stack_string NULL #define fetch_stack_string_size NULL #define DEFINE_FETCH_memory(type) \ static void FETCH_FUNC_NAME(memory, type)(struct pt_regs *regs, \ void *addr, void *dest) \ { \ type retval; \ if (probe_kernel_address(addr, retval)) \ *(type *)dest = 0; \ else \ *(type *)dest = retval; \ } \ NOKPROBE_SYMBOL(FETCH_FUNC_NAME(memory, type)); DEFINE_BASIC_FETCH_FUNCS(memory) /* * Fetch a null-terminated string. Caller MUST set *(u32 *)dest with max * length and relative data location. */ static void FETCH_FUNC_NAME(memory, string)(struct pt_regs *regs, void *addr, void *dest) { long ret; int maxlen = get_rloc_len(*(u32 *)dest); u8 *dst = get_rloc_data(dest); u8 *src = addr; mm_segment_t old_fs = get_fs(); if (!maxlen) return; /* * Try to get string again, since the string can be changed while * probing. */ set_fs(KERNEL_DS); pagefault_disable(); do ret = __copy_from_user_inatomic(dst++, src++, 1); while (dst[-1] && ret == 0 && src - (u8 *)addr < maxlen); dst[-1] = '\0'; pagefault_enable(); set_fs(old_fs); if (ret < 0) { /* Failed to fetch string */ ((u8 *)get_rloc_data(dest))[0] = '\0'; *(u32 *)dest = make_data_rloc(0, get_rloc_offs(*(u32 *)dest)); } else { *(u32 *)dest = make_data_rloc(src - (u8 *)addr, get_rloc_offs(*(u32 *)dest)); } } NOKPROBE_SYMBOL(FETCH_FUNC_NAME(memory, string)); /* Return the length of string -- including null terminal byte */ static void FETCH_FUNC_NAME(memory, string_size)(struct pt_regs *regs, void *addr, void *dest) { mm_segment_t old_fs; int ret, len = 0; u8 c; old_fs = get_fs(); set_fs(KERNEL_DS); pagefault_disable(); do { ret = __copy_from_user_inatomic(&c, (u8 *)addr + len, 1); len++; } while (c && ret == 0 && len < MAX_STRING_SIZE); pagefault_enable(); set_fs(old_fs); if (ret < 0) /* Failed to check the length */ *(u32 *)dest = 0; else *(u32 *)dest = len; } NOKPROBE_SYMBOL(FETCH_FUNC_NAME(memory, string_size)); #define DEFINE_FETCH_symbol(type) \ void FETCH_FUNC_NAME(symbol, type)(struct pt_regs *regs, void *data, void *dest)\ { \ struct symbol_cache *sc = data; \ if (sc->addr) \ fetch_memory_##type(regs, (void *)sc->addr, dest); \ else \ *(type *)dest = 0; \ } \ NOKPROBE_SYMBOL(FETCH_FUNC_NAME(symbol, type)); DEFINE_BASIC_FETCH_FUNCS(symbol) DEFINE_FETCH_symbol(string) DEFINE_FETCH_symbol(string_size) /* kprobes don't support file_offset fetch methods */ #define fetch_file_offset_u8 NULL #define fetch_file_offset_u16 NULL #define fetch_file_offset_u32 NULL #define fetch_file_offset_u64 NULL #define fetch_file_offset_string NULL #define fetch_file_offset_string_size NULL /* Fetch type information table */ const struct fetch_type kprobes_fetch_type_table[] = { /* Special types */ [FETCH_TYPE_STRING] = __ASSIGN_FETCH_TYPE("string", string, string, sizeof(u32), 1, "__data_loc char[]"), [FETCH_TYPE_STRSIZE] = __ASSIGN_FETCH_TYPE("string_size", u32, string_size, sizeof(u32), 0, "u32"), /* Basic types */ ASSIGN_FETCH_TYPE(u8, u8, 0), ASSIGN_FETCH_TYPE(u16, u16, 0), ASSIGN_FETCH_TYPE(u32, u32, 0), ASSIGN_FETCH_TYPE(u64, u64, 0), ASSIGN_FETCH_TYPE(s8, u8, 1), ASSIGN_FETCH_TYPE(s16, u16, 1), ASSIGN_FETCH_TYPE(s32, u32, 1), ASSIGN_FETCH_TYPE(s64, u64, 1), ASSIGN_FETCH_TYPE_END }; /* * Allocate new trace_probe and initialize it (including kprobes). */ static struct trace_kprobe *alloc_trace_kprobe(const char *group, const char *event, void *addr, const char *symbol, unsigned long offs, int nargs, bool is_return) { struct trace_kprobe *tk; int ret = -ENOMEM; tk = kzalloc(SIZEOF_TRACE_KPROBE(nargs), GFP_KERNEL); if (!tk) return ERR_PTR(ret); if (symbol) { tk->symbol = kstrdup(symbol, GFP_KERNEL); if (!tk->symbol) goto error; tk->rp.kp.symbol_name = tk->symbol; tk->rp.kp.offset = offs; } else tk->rp.kp.addr = addr; if (is_return) tk->rp.handler = kretprobe_dispatcher; else tk->rp.kp.pre_handler = kprobe_dispatcher; if (!event || !is_good_name(event)) { ret = -EINVAL; goto error; } tk->tp.call.class = &tk->tp.class; tk->tp.call.name = kstrdup(event, GFP_KERNEL); if (!tk->tp.call.name) goto error; if (!group || !is_good_name(group)) { ret = -EINVAL; goto error; } tk->tp.class.system = kstrdup(group, GFP_KERNEL); if (!tk->tp.class.system) goto error; INIT_LIST_HEAD(&tk->list); INIT_LIST_HEAD(&tk->tp.files); return tk; error: kfree(tk->tp.call.name); kfree(tk->symbol); kfree(tk); return ERR_PTR(ret); } static void free_trace_kprobe(struct trace_kprobe *tk) { int i; for (i = 0; i < tk->tp.nr_args; i++) traceprobe_free_probe_arg(&tk->tp.args[i]); kfree(tk->tp.call.class->system); kfree(tk->tp.call.name); kfree(tk->symbol); kfree(tk); } static struct trace_kprobe *find_trace_kprobe(const char *event, const char *group) { struct trace_kprobe *tk; list_for_each_entry(tk, &probe_list, list) if (strcmp(ftrace_event_name(&tk->tp.call), event) == 0 && strcmp(tk->tp.call.class->system, group) == 0) return tk; return NULL; } /* * Enable trace_probe * if the file is NULL, enable "perf" handler, or enable "trace" handler. */ static int enable_trace_kprobe(struct trace_kprobe *tk, struct ftrace_event_file *file) { int ret = 0; if (file) { struct event_file_link *link; link = kmalloc(sizeof(*link), GFP_KERNEL); if (!link) { ret = -ENOMEM; goto out; } link->file = file; list_add_tail_rcu(&link->list, &tk->tp.files); tk->tp.flags |= TP_FLAG_TRACE; } else tk->tp.flags |= TP_FLAG_PROFILE; if (trace_probe_is_registered(&tk->tp) && !trace_kprobe_has_gone(tk)) { if (trace_kprobe_is_return(tk)) ret = enable_kretprobe(&tk->rp); else ret = enable_kprobe(&tk->rp.kp); } out: return ret; } /* * Disable trace_probe * if the file is NULL, disable "perf" handler, or disable "trace" handler. */ static int disable_trace_kprobe(struct trace_kprobe *tk, struct ftrace_event_file *file) { struct event_file_link *link = NULL; int wait = 0; int ret = 0; if (file) { link = find_event_file_link(&tk->tp, file); if (!link) { ret = -EINVAL; goto out; } list_del_rcu(&link->list); wait = 1; if (!list_empty(&tk->tp.files)) goto out; tk->tp.flags &= ~TP_FLAG_TRACE; } else tk->tp.flags &= ~TP_FLAG_PROFILE; if (!trace_probe_is_enabled(&tk->tp) && trace_probe_is_registered(&tk->tp)) { if (trace_kprobe_is_return(tk)) disable_kretprobe(&tk->rp); else disable_kprobe(&tk->rp.kp); wait = 1; } out: if (wait) { /* * Synchronize with kprobe_trace_func/kretprobe_trace_func * to ensure disabled (all running handlers are finished). * This is not only for kfree(), but also the caller, * trace_remove_event_call() supposes it for releasing * event_call related objects, which will be accessed in * the kprobe_trace_func/kretprobe_trace_func. */ synchronize_sched(); kfree(link); /* Ignored if link == NULL */ } return ret; } /* Internal register function - just handle k*probes and flags */ static int __register_trace_kprobe(struct trace_kprobe *tk) { int i, ret; if (trace_probe_is_registered(&tk->tp)) return -EINVAL; for (i = 0; i < tk->tp.nr_args; i++) traceprobe_update_arg(&tk->tp.args[i]); /* Set/clear disabled flag according to tp->flag */ if (trace_probe_is_enabled(&tk->tp)) tk->rp.kp.flags &= ~KPROBE_FLAG_DISABLED; else tk->rp.kp.flags |= KPROBE_FLAG_DISABLED; if (trace_kprobe_is_return(tk)) ret = register_kretprobe(&tk->rp); else ret = register_kprobe(&tk->rp.kp); if (ret == 0) tk->tp.flags |= TP_FLAG_REGISTERED; else { pr_warning("Could not insert probe at %s+%lu: %d\n", trace_kprobe_symbol(tk), trace_kprobe_offset(tk), ret); if (ret == -ENOENT && trace_kprobe_is_on_module(tk)) { pr_warning("This probe might be able to register after" "target module is loaded. Continue.\n"); ret = 0; } else if (ret == -EILSEQ) { pr_warning("Probing address(0x%p) is not an " "instruction boundary.\n", tk->rp.kp.addr); ret = -EINVAL; } } return ret; } /* Internal unregister function - just handle k*probes and flags */ static void __unregister_trace_kprobe(struct trace_kprobe *tk) { if (trace_probe_is_registered(&tk->tp)) { if (trace_kprobe_is_return(tk)) unregister_kretprobe(&tk->rp); else unregister_kprobe(&tk->rp.kp); tk->tp.flags &= ~TP_FLAG_REGISTERED; /* Cleanup kprobe for reuse */ if (tk->rp.kp.symbol_name) tk->rp.kp.addr = NULL; } } /* Unregister a trace_probe and probe_event: call with locking probe_lock */ static int unregister_trace_kprobe(struct trace_kprobe *tk) { /* Enabled event can not be unregistered */ if (trace_probe_is_enabled(&tk->tp)) return -EBUSY; /* Will fail if probe is being used by ftrace or perf */ if (unregister_kprobe_event(tk)) return -EBUSY; __unregister_trace_kprobe(tk); list_del(&tk->list); return 0; } /* Register a trace_probe and probe_event */ static int register_trace_kprobe(struct trace_kprobe *tk) { struct trace_kprobe *old_tk; int ret; mutex_lock(&probe_lock); /* Delete old (same name) event if exist */ old_tk = find_trace_kprobe(ftrace_event_name(&tk->tp.call), tk->tp.call.class->system); if (old_tk) { ret = unregister_trace_kprobe(old_tk); if (ret < 0) goto end; free_trace_kprobe(old_tk); } /* Register new event */ ret = register_kprobe_event(tk); if (ret) { pr_warning("Failed to register probe event(%d)\n", ret); goto end; } /* Register k*probe */ ret = __register_trace_kprobe(tk); if (ret < 0) unregister_kprobe_event(tk); else list_add_tail(&tk->list, &probe_list); end: mutex_unlock(&probe_lock); return ret; } /* Module notifier call back, checking event on the module */ static int trace_kprobe_module_callback(struct notifier_block *nb, unsigned long val, void *data) { struct module *mod = data; struct trace_kprobe *tk; int ret; if (val != MODULE_STATE_COMING) return NOTIFY_DONE; /* Update probes on coming module */ mutex_lock(&probe_lock); list_for_each_entry(tk, &probe_list, list) { if (trace_kprobe_within_module(tk, mod)) { /* Don't need to check busy - this should have gone. */ __unregister_trace_kprobe(tk); ret = __register_trace_kprobe(tk); if (ret) pr_warning("Failed to re-register probe %s on" "%s: %d\n", ftrace_event_name(&tk->tp.call), mod->name, ret); } } mutex_unlock(&probe_lock); return NOTIFY_DONE; } static struct notifier_block trace_kprobe_module_nb = { .notifier_call = trace_kprobe_module_callback, .priority = 1 /* Invoked after kprobe module callback */ }; static int create_trace_kprobe(int argc, char **argv) { /* * Argument syntax: * - Add kprobe: p[:[GRP/]EVENT] [MOD:]KSYM[+OFFS]|KADDR [FETCHARGS] * - Add kretprobe: r[:[GRP/]EVENT] [MOD:]KSYM[+0] [FETCHARGS] * Fetch args: * $retval : fetch return value * $stack : fetch stack address * $stackN : fetch Nth of stack (N:0-) * @ADDR : fetch memory at ADDR (ADDR should be in kernel) * @SYM[+|-offs] : fetch memory at SYM +|- offs (SYM is a data symbol) * %REG : fetch register REG * Dereferencing memory fetch: * +|-offs(ARG) : fetch memory at ARG +|- offs address. * Alias name of args: * NAME=FETCHARG : set NAME as alias of FETCHARG. * Type of args: * FETCHARG:TYPE : use TYPE instead of unsigned long. */ struct trace_kprobe *tk; int i, ret = 0; bool is_return = false, is_delete = false; char *symbol = NULL, *event = NULL, *group = NULL; char *arg; unsigned long offset = 0; void *addr = NULL; char buf[MAX_EVENT_NAME_LEN]; /* argc must be >= 1 */ if (argv[0][0] == 'p') is_return = false; else if (argv[0][0] == 'r') is_return = true; else if (argv[0][0] == '-') is_delete = true; else { pr_info("Probe definition must be started with 'p', 'r' or" " '-'.\n"); return -EINVAL; } if (argv[0][1] == ':') { event = &argv[0][2]; if (strchr(event, '/')) { group = event; event = strchr(group, '/') + 1; event[-1] = '\0'; if (strlen(group) == 0) { pr_info("Group name is not specified\n"); return -EINVAL; } } if (strlen(event) == 0) { pr_info("Event name is not specified\n"); return -EINVAL; } } if (!group) group = KPROBE_EVENT_SYSTEM; if (is_delete) { if (!event) { pr_info("Delete command needs an event name.\n"); return -EINVAL; } mutex_lock(&probe_lock); tk = find_trace_kprobe(event, group); if (!tk) { mutex_unlock(&probe_lock); pr_info("Event %s/%s doesn't exist.\n", group, event); return -ENOENT; } /* delete an event */ ret = unregister_trace_kprobe(tk); if (ret == 0) free_trace_kprobe(tk); mutex_unlock(&probe_lock); return ret; } if (argc < 2) { pr_info("Probe point is not specified.\n"); return -EINVAL; } if (isdigit(argv[1][0])) { if (is_return) { pr_info("Return probe point must be a symbol.\n"); return -EINVAL; } /* an address specified */ ret = kstrtoul(&argv[1][0], 0, (unsigned long *)&addr); if (ret) { pr_info("Failed to parse address.\n"); return ret; } } else { /* a symbol specified */ symbol = argv[1]; /* TODO: support .init module functions */ ret = traceprobe_split_symbol_offset(symbol, &offset); if (ret) { pr_info("Failed to parse symbol.\n"); return ret; } if (offset && is_return) { pr_info("Return probe must be used without offset.\n"); return -EINVAL; } } argc -= 2; argv += 2; /* setup a probe */ if (!event) { /* Make a new event name */ if (symbol) snprintf(buf, MAX_EVENT_NAME_LEN, "%c_%s_%ld", is_return ? 'r' : 'p', symbol, offset); else snprintf(buf, MAX_EVENT_NAME_LEN, "%c_0x%p", is_return ? 'r' : 'p', addr); event = buf; } tk = alloc_trace_kprobe(group, event, addr, symbol, offset, argc, is_return); if (IS_ERR(tk)) { pr_info("Failed to allocate trace_probe.(%d)\n", (int)PTR_ERR(tk)); return PTR_ERR(tk); } /* parse arguments */ ret = 0; for (i = 0; i < argc && i < MAX_TRACE_ARGS; i++) { struct probe_arg *parg = &tk->tp.args[i]; /* Increment count for freeing args in error case */ tk->tp.nr_args++; /* Parse argument name */ arg = strchr(argv[i], '='); if (arg) { *arg++ = '\0'; parg->name = kstrdup(argv[i], GFP_KERNEL); } else { arg = argv[i]; /* If argument name is omitted, set "argN" */ snprintf(buf, MAX_EVENT_NAME_LEN, "arg%d", i + 1); parg->name = kstrdup(buf, GFP_KERNEL); } if (!parg->name) { pr_info("Failed to allocate argument[%d] name.\n", i); ret = -ENOMEM; goto error; } if (!is_good_name(parg->name)) { pr_info("Invalid argument[%d] name: %s\n", i, parg->name); ret = -EINVAL; goto error; } if (traceprobe_conflict_field_name(parg->name, tk->tp.args, i)) { pr_info("Argument[%d] name '%s' conflicts with " "another field.\n", i, argv[i]); ret = -EINVAL; goto error; } /* Parse fetch argument */ ret = traceprobe_parse_probe_arg(arg, &tk->tp.size, parg, is_return, true); if (ret) { pr_info("Parse error at argument[%d]. (%d)\n", i, ret); goto error; } } ret = register_trace_kprobe(tk); if (ret) goto error; return 0; error: free_trace_kprobe(tk); return ret; } static int release_all_trace_kprobes(void) { struct trace_kprobe *tk; int ret = 0; mutex_lock(&probe_lock); /* Ensure no probe is in use. */ list_for_each_entry(tk, &probe_list, list) if (trace_probe_is_enabled(&tk->tp)) { ret = -EBUSY; goto end; } /* TODO: Use batch unregistration */ while (!list_empty(&probe_list)) { tk = list_entry(probe_list.next, struct trace_kprobe, list); ret = unregister_trace_kprobe(tk); if (ret) goto end; free_trace_kprobe(tk); } end: mutex_unlock(&probe_lock); return ret; } /* Probes listing interfaces */ static void *probes_seq_start(struct seq_file *m, loff_t *pos) { mutex_lock(&probe_lock); return seq_list_start(&probe_list, *pos); } static void *probes_seq_next(struct seq_file *m, void *v, loff_t *pos) { return seq_list_next(v, &probe_list, pos); } static void probes_seq_stop(struct seq_file *m, void *v) { mutex_unlock(&probe_lock); } static int probes_seq_show(struct seq_file *m, void *v) { struct trace_kprobe *tk = v; int i; seq_putc(m, trace_kprobe_is_return(tk) ? 'r' : 'p'); seq_printf(m, ":%s/%s", tk->tp.call.class->system, ftrace_event_name(&tk->tp.call)); if (!tk->symbol) seq_printf(m, " 0x%p", tk->rp.kp.addr); else if (tk->rp.kp.offset) seq_printf(m, " %s+%u", trace_kprobe_symbol(tk), tk->rp.kp.offset); else seq_printf(m, " %s", trace_kprobe_symbol(tk)); for (i = 0; i < tk->tp.nr_args; i++) seq_printf(m, " %s=%s", tk->tp.args[i].name, tk->tp.args[i].comm); seq_putc(m, '\n'); return 0; } static const struct seq_operations probes_seq_op = { .start = probes_seq_start, .next = probes_seq_next, .stop = probes_seq_stop, .show = probes_seq_show }; static int probes_open(struct inode *inode, struct file *file) { int ret; if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) { ret = release_all_trace_kprobes(); if (ret < 0) return ret; } return seq_open(file, &probes_seq_op); } static ssize_t probes_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { return traceprobe_probes_write(file, buffer, count, ppos, create_trace_kprobe); } static const struct file_operations kprobe_events_ops = { .owner = THIS_MODULE, .open = probes_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, .write = probes_write, }; /* Probes profiling interfaces */ static int probes_profile_seq_show(struct seq_file *m, void *v) { struct trace_kprobe *tk = v; seq_printf(m, " %-44s %15lu %15lu\n", ftrace_event_name(&tk->tp.call), tk->nhit, tk->rp.kp.nmissed); return 0; } static const struct seq_operations profile_seq_op = { .start = probes_seq_start, .next = probes_seq_next, .stop = probes_seq_stop, .show = probes_profile_seq_show }; static int profile_open(struct inode *inode, struct file *file) { return seq_open(file, &profile_seq_op); } static const struct file_operations kprobe_profile_ops = { .owner = THIS_MODULE, .open = profile_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; /* Kprobe handler */ static nokprobe_inline void __kprobe_trace_func(struct trace_kprobe *tk, struct pt_regs *regs, struct ftrace_event_file *ftrace_file) { struct kprobe_trace_entry_head *entry; struct ring_buffer_event *event; struct ring_buffer *buffer; int size, dsize, pc; unsigned long irq_flags; struct ftrace_event_call *call = &tk->tp.call; WARN_ON(call != ftrace_file->event_call); if (ftrace_trigger_soft_disabled(ftrace_file)) return; local_save_flags(irq_flags); pc = preempt_count(); dsize = __get_data_size(&tk->tp, regs); size = sizeof(*entry) + tk->tp.size + dsize; event = trace_event_buffer_lock_reserve(&buffer, ftrace_file, call->event.type, size, irq_flags, pc); if (!event) return; entry = ring_buffer_event_data(event); entry->ip = (unsigned long)tk->rp.kp.addr; store_trace_args(sizeof(*entry), &tk->tp, regs, (u8 *)&entry[1], dsize); event_trigger_unlock_commit_regs(ftrace_file, buffer, event, entry, irq_flags, pc, regs); } static void kprobe_trace_func(struct trace_kprobe *tk, struct pt_regs *regs) { struct event_file_link *link; list_for_each_entry_rcu(link, &tk->tp.files, list) __kprobe_trace_func(tk, regs, link->file); } NOKPROBE_SYMBOL(kprobe_trace_func); /* Kretprobe handler */ static nokprobe_inline void __kretprobe_trace_func(struct trace_kprobe *tk, struct kretprobe_instance *ri, struct pt_regs *regs, struct ftrace_event_file *ftrace_file) { struct kretprobe_trace_entry_head *entry; struct ring_buffer_event *event; struct ring_buffer *buffer; int size, pc, dsize; unsigned long irq_flags; struct ftrace_event_call *call = &tk->tp.call; WARN_ON(call != ftrace_file->event_call); if (ftrace_trigger_soft_disabled(ftrace_file)) return; local_save_flags(irq_flags); pc = preempt_count(); dsize = __get_data_size(&tk->tp, regs); size = sizeof(*entry) + tk->tp.size + dsize; event = trace_event_buffer_lock_reserve(&buffer, ftrace_file, call->event.type, size, irq_flags, pc); if (!event) return; entry = ring_buffer_event_data(event); entry->func = (unsigned long)tk->rp.kp.addr; entry->ret_ip = (unsigned long)ri->ret_addr; store_trace_args(sizeof(*entry), &tk->tp, regs, (u8 *)&entry[1], dsize); event_trigger_unlock_commit_regs(ftrace_file, buffer, event, entry, irq_flags, pc, regs); } static void kretprobe_trace_func(struct trace_kprobe *tk, struct kretprobe_instance *ri, struct pt_regs *regs) { struct event_file_link *link; list_for_each_entry_rcu(link, &tk->tp.files, list) __kretprobe_trace_func(tk, ri, regs, link->file); } NOKPROBE_SYMBOL(kretprobe_trace_func); /* Event entry printers */ static enum print_line_t print_kprobe_event(struct trace_iterator *iter, int flags, struct trace_event *event) { struct kprobe_trace_entry_head *field; struct trace_seq *s = &iter->seq; struct trace_probe *tp; u8 *data; int i; field = (struct kprobe_trace_entry_head *)iter->ent; tp = container_of(event, struct trace_probe, call.event); trace_seq_printf(s, "%s: (", ftrace_event_name(&tp->call)); if (!seq_print_ip_sym(s, field->ip, flags | TRACE_ITER_SYM_OFFSET)) goto out; trace_seq_putc(s, ')'); data = (u8 *)&field[1]; for (i = 0; i < tp->nr_args; i++) if (!tp->args[i].type->print(s, tp->args[i].name, data + tp->args[i].offset, field)) goto out; trace_seq_putc(s, '\n'); out: return trace_handle_return(s); } static enum print_line_t print_kretprobe_event(struct trace_iterator *iter, int flags, struct trace_event *event) { struct kretprobe_trace_entry_head *field; struct trace_seq *s = &iter->seq; struct trace_probe *tp; u8 *data; int i; field = (struct kretprobe_trace_entry_head *)iter->ent; tp = container_of(event, struct trace_probe, call.event); trace_seq_printf(s, "%s: (", ftrace_event_name(&tp->call)); if (!seq_print_ip_sym(s, field->ret_ip, flags | TRACE_ITER_SYM_OFFSET)) goto out; trace_seq_puts(s, " <- "); if (!seq_print_ip_sym(s, field->func, flags & ~TRACE_ITER_SYM_OFFSET)) goto out; trace_seq_putc(s, ')'); data = (u8 *)&field[1]; for (i = 0; i < tp->nr_args; i++) if (!tp->args[i].type->print(s, tp->args[i].name, data + tp->args[i].offset, field)) goto out; trace_seq_putc(s, '\n'); out: return trace_handle_return(s); } static int kprobe_event_define_fields(struct ftrace_event_call *event_call) { int ret, i; struct kprobe_trace_entry_head field; struct trace_kprobe *tk = (struct trace_kprobe *)event_call->data; DEFINE_FIELD(unsigned long, ip, FIELD_STRING_IP, 0); /* Set argument names as fields */ for (i = 0; i < tk->tp.nr_args; i++) { struct probe_arg *parg = &tk->tp.args[i]; ret = trace_define_field(event_call, parg->type->fmttype, parg->name, sizeof(field) + parg->offset, parg->type->size, parg->type->is_signed, FILTER_OTHER); if (ret) return ret; } return 0; } static int kretprobe_event_define_fields(struct ftrace_event_call *event_call) { int ret, i; struct kretprobe_trace_entry_head field; struct trace_kprobe *tk = (struct trace_kprobe *)event_call->data; DEFINE_FIELD(unsigned long, func, FIELD_STRING_FUNC, 0); DEFINE_FIELD(unsigned long, ret_ip, FIELD_STRING_RETIP, 0); /* Set argument names as fields */ for (i = 0; i < tk->tp.nr_args; i++) { struct probe_arg *parg = &tk->tp.args[i]; ret = trace_define_field(event_call, parg->type->fmttype, parg->name, sizeof(field) + parg->offset, parg->type->size, parg->type->is_signed, FILTER_OTHER); if (ret) return ret; } return 0; } #ifdef CONFIG_PERF_EVENTS /* Kprobe profile handler */ static void kprobe_perf_func(struct trace_kprobe *tk, struct pt_regs *regs) { struct ftrace_event_call *call = &tk->tp.call; struct kprobe_trace_entry_head *entry; struct hlist_head *head; int size, __size, dsize; int rctx; head = this_cpu_ptr(call->perf_events); if (hlist_empty(head)) return; dsize = __get_data_size(&tk->tp, regs); __size = sizeof(*entry) + tk->tp.size + dsize; size = ALIGN(__size + sizeof(u32), sizeof(u64)); size -= sizeof(u32); entry = perf_trace_buf_prepare(size, call->event.type, NULL, &rctx); if (!entry) return; entry->ip = (unsigned long)tk->rp.kp.addr; memset(&entry[1], 0, dsize); store_trace_args(sizeof(*entry), &tk->tp, regs, (u8 *)&entry[1], dsize); perf_trace_buf_submit(entry, size, rctx, 0, 1, regs, head, NULL); } NOKPROBE_SYMBOL(kprobe_perf_func); /* Kretprobe profile handler */ static void kretprobe_perf_func(struct trace_kprobe *tk, struct kretprobe_instance *ri, struct pt_regs *regs) { struct ftrace_event_call *call = &tk->tp.call; struct kretprobe_trace_entry_head *entry; struct hlist_head *head; int size, __size, dsize; int rctx; head = this_cpu_ptr(call->perf_events); if (hlist_empty(head)) return; dsize = __get_data_size(&tk->tp, regs); __size = sizeof(*entry) + tk->tp.size + dsize; size = ALIGN(__size + sizeof(u32), sizeof(u64)); size -= sizeof(u32); entry = perf_trace_buf_prepare(size, call->event.type, NULL, &rctx); if (!entry) return; entry->func = (unsigned long)tk->rp.kp.addr; entry->ret_ip = (unsigned long)ri->ret_addr; store_trace_args(sizeof(*entry), &tk->tp, regs, (u8 *)&entry[1], dsize); perf_trace_buf_submit(entry, size, rctx, 0, 1, regs, head, NULL); } NOKPROBE_SYMBOL(kretprobe_perf_func); #endif /* CONFIG_PERF_EVENTS */ /* * called by perf_trace_init() or __ftrace_set_clr_event() under event_mutex. * * kprobe_trace_self_tests_init() does enable_trace_probe/disable_trace_probe * lockless, but we can't race with this __init function. */ static int kprobe_register(struct ftrace_event_call *event, enum trace_reg type, void *data) { struct trace_kprobe *tk = (struct trace_kprobe *)event->data; struct ftrace_event_file *file = data; switch (type) { case TRACE_REG_REGISTER: return enable_trace_kprobe(tk, file); case TRACE_REG_UNREGISTER: return disable_trace_kprobe(tk, file); #ifdef CONFIG_PERF_EVENTS case TRACE_REG_PERF_REGISTER: return enable_trace_kprobe(tk, NULL); case TRACE_REG_PERF_UNREGISTER: return disable_trace_kprobe(tk, NULL); case TRACE_REG_PERF_OPEN: case TRACE_REG_PERF_CLOSE: case TRACE_REG_PERF_ADD: case TRACE_REG_PERF_DEL: return 0; #endif } return 0; } static int kprobe_dispatcher(struct kprobe *kp, struct pt_regs *regs) { struct trace_kprobe *tk = container_of(kp, struct trace_kprobe, rp.kp); tk->nhit++; if (tk->tp.flags & TP_FLAG_TRACE) kprobe_trace_func(tk, regs); #ifdef CONFIG_PERF_EVENTS if (tk->tp.flags & TP_FLAG_PROFILE) kprobe_perf_func(tk, regs); #endif return 0; /* We don't tweek kernel, so just return 0 */ } NOKPROBE_SYMBOL(kprobe_dispatcher); static int kretprobe_dispatcher(struct kretprobe_instance *ri, struct pt_regs *regs) { struct trace_kprobe *tk = container_of(ri->rp, struct trace_kprobe, rp); tk->nhit++; if (tk->tp.flags & TP_FLAG_TRACE) kretprobe_trace_func(tk, ri, regs); #ifdef CONFIG_PERF_EVENTS if (tk->tp.flags & TP_FLAG_PROFILE) kretprobe_perf_func(tk, ri, regs); #endif return 0; /* We don't tweek kernel, so just return 0 */ } NOKPROBE_SYMBOL(kretprobe_dispatcher); static struct trace_event_functions kretprobe_funcs = { .trace = print_kretprobe_event }; static struct trace_event_functions kprobe_funcs = { .trace = print_kprobe_event }; static int register_kprobe_event(struct trace_kprobe *tk) { struct ftrace_event_call *call = &tk->tp.call; int ret; /* Initialize ftrace_event_call */ INIT_LIST_HEAD(&call->class->fields); if (trace_kprobe_is_return(tk)) { call->event.funcs = &kretprobe_funcs; call->class->define_fields = kretprobe_event_define_fields; } else { call->event.funcs = &kprobe_funcs; call->class->define_fields = kprobe_event_define_fields; } if (set_print_fmt(&tk->tp, trace_kprobe_is_return(tk)) < 0) return -ENOMEM; ret = register_ftrace_event(&call->event); if (!ret) { kfree(call->print_fmt); return -ENODEV; } call->flags = 0; call->class->reg = kprobe_register; call->data = tk; ret = trace_add_event_call(call); if (ret) { pr_info("Failed to register kprobe event: %s\n", ftrace_event_name(call)); kfree(call->print_fmt); unregister_ftrace_event(&call->event); } return ret; } static int unregister_kprobe_event(struct trace_kprobe *tk) { int ret; /* tp->event is unregistered in trace_remove_event_call() */ ret = trace_remove_event_call(&tk->tp.call); if (!ret) kfree(tk->tp.call.print_fmt); return ret; } /* Make a debugfs interface for controlling probe points */ static __init int init_kprobe_trace(void) { struct dentry *d_tracer; struct dentry *entry; if (register_module_notifier(&trace_kprobe_module_nb)) return -EINVAL; d_tracer = tracing_init_dentry(); if (IS_ERR(d_tracer)) return 0; entry = debugfs_create_file("kprobe_events", 0644, d_tracer, NULL, &kprobe_events_ops); /* Event list interface */ if (!entry) pr_warning("Could not create debugfs " "'kprobe_events' entry\n"); /* Profile interface */ entry = debugfs_create_file("kprobe_profile", 0444, d_tracer, NULL, &kprobe_profile_ops); if (!entry) pr_warning("Could not create debugfs " "'kprobe_profile' entry\n"); return 0; } fs_initcall(init_kprobe_trace); #ifdef CONFIG_FTRACE_STARTUP_TEST /* * The "__used" keeps gcc from removing the function symbol * from the kallsyms table. */ static __used int kprobe_trace_selftest_target(int a1, int a2, int a3, int a4, int a5, int a6) { return a1 + a2 + a3 + a4 + a5 + a6; } static struct ftrace_event_file * find_trace_probe_file(struct trace_kprobe *tk, struct trace_array *tr) { struct ftrace_event_file *file; list_for_each_entry(file, &tr->events, list) if (file->event_call == &tk->tp.call) return file; return NULL; } /* * Nobody but us can call enable_trace_kprobe/disable_trace_kprobe at this * stage, we can do this lockless. */ static __init int kprobe_trace_self_tests_init(void) { int ret, warn = 0; int (*target)(int, int, int, int, int, int); struct trace_kprobe *tk; struct ftrace_event_file *file; if (tracing_is_disabled()) return -ENODEV; target = kprobe_trace_selftest_target; pr_info("Testing kprobe tracing: "); ret = traceprobe_command("p:testprobe kprobe_trace_selftest_target " "$stack $stack0 +0($stack)", create_trace_kprobe); if (WARN_ON_ONCE(ret)) { pr_warn("error on probing function entry.\n"); warn++; } else { /* Enable trace point */ tk = find_trace_kprobe("testprobe", KPROBE_EVENT_SYSTEM); if (WARN_ON_ONCE(tk == NULL)) { pr_warn("error on getting new probe.\n"); warn++; } else { file = find_trace_probe_file(tk, top_trace_array()); if (WARN_ON_ONCE(file == NULL)) { pr_warn("error on getting probe file.\n"); warn++; } else enable_trace_kprobe(tk, file); } } ret = traceprobe_command("r:testprobe2 kprobe_trace_selftest_target " "$retval", create_trace_kprobe); if (WARN_ON_ONCE(ret)) { pr_warn("error on probing function return.\n"); warn++; } else { /* Enable trace point */ tk = find_trace_kprobe("testprobe2", KPROBE_EVENT_SYSTEM); if (WARN_ON_ONCE(tk == NULL)) { pr_warn("error on getting 2nd new probe.\n"); warn++; } else { file = find_trace_probe_file(tk, top_trace_array()); if (WARN_ON_ONCE(file == NULL)) { pr_warn("error on getting probe file.\n"); warn++; } else enable_trace_kprobe(tk, file); } } if (warn) goto end; ret = target(1, 2, 3, 4, 5, 6); /* Disable trace points before removing it */ tk = find_trace_kprobe("testprobe", KPROBE_EVENT_SYSTEM); if (WARN_ON_ONCE(tk == NULL)) { pr_warn("error on getting test probe.\n"); warn++; } else { file = find_trace_probe_file(tk, top_trace_array()); if (WARN_ON_ONCE(file == NULL)) { pr_warn("error on getting probe file.\n"); warn++; } else disable_trace_kprobe(tk, file); } tk = find_trace_kprobe("testprobe2", KPROBE_EVENT_SYSTEM); if (WARN_ON_ONCE(tk == NULL)) { pr_warn("error on getting 2nd test probe.\n"); warn++; } else { file = find_trace_probe_file(tk, top_trace_array()); if (WARN_ON_ONCE(file == NULL)) { pr_warn("error on getting probe file.\n"); warn++; } else disable_trace_kprobe(tk, file); } ret = traceprobe_command("-:testprobe", create_trace_kprobe); if (WARN_ON_ONCE(ret)) { pr_warn("error on deleting a probe.\n"); warn++; } ret = traceprobe_command("-:testprobe2", create_trace_kprobe); if (WARN_ON_ONCE(ret)) { pr_warn("error on deleting a probe.\n"); warn++; } end: release_all_trace_kprobes(); if (warn) pr_cont("NG: Some tests are failed. Please check them.\n"); else pr_cont("OK\n"); return 0; } late_initcall(kprobe_trace_self_tests_init); #endif
systemdaemon/systemd
src/linux/kernel/trace/trace_kprobe.c
C
gpl-2.0
37,034
/* * Device tables which are exported to userspace via * scripts/mod/file2alias.c. You must keep that file in sync with this * header. */ #ifndef LINUX_MOD_DEVICETABLE_H #define LINUX_MOD_DEVICETABLE_H #ifdef __KERNEL__ #include <linux/types.h> typedef unsigned long kernel_ulong_t; #endif #define PCI_ANY_ID (~0) struct pci_device_id { __u32 vendor, device; /* Vendor and device ID or PCI_ANY_ID*/ __u32 subvendor, subdevice; /* Subsystem ID's or PCI_ANY_ID */ __u32 class, class_mask; /* (class,subclass,prog-if) triplet */ kernel_ulong_t driver_data; /* Data private to the driver */ }; #define IEEE1394_MATCH_VENDOR_ID 0x0001 #define IEEE1394_MATCH_MODEL_ID 0x0002 #define IEEE1394_MATCH_SPECIFIER_ID 0x0004 #define IEEE1394_MATCH_VERSION 0x0008 struct ieee1394_device_id { __u32 match_flags; __u32 vendor_id; __u32 model_id; __u32 specifier_id; __u32 version; kernel_ulong_t driver_data __attribute__((aligned(sizeof(kernel_ulong_t)))); }; /* * Device table entry for "new style" table-driven USB drivers. * User mode code can read these tables to choose which modules to load. * Declare the table as a MODULE_DEVICE_TABLE. * * A probe() parameter will point to a matching entry from this table. * Use the driver_info field for each match to hold information tied * to that match: device quirks, etc. * * Terminate the driver's table with an all-zeroes entry. * Use the flag values to control which fields are compared. */ /** * struct usb_device_id - identifies USB devices for probing and hotplugging * @match_flags: Bit mask controlling of the other fields are used to match * against new devices. Any field except for driver_info may be used, * although some only make sense in conjunction with other fields. * This is usually set by a USB_DEVICE_*() macro, which sets all * other fields in this structure except for driver_info. * @idVendor: USB vendor ID for a device; numbers are assigned * by the USB forum to its members. * @idProduct: Vendor-assigned product ID. * @bcdDevice_lo: Low end of range of vendor-assigned product version numbers. * This is also used to identify individual product versions, for * a range consisting of a single device. * @bcdDevice_hi: High end of version number range. The range of product * versions is inclusive. * @bDeviceClass: Class of device; numbers are assigned * by the USB forum. Products may choose to implement classes, * or be vendor-specific. Device classes specify behavior of all * the interfaces on a devices. * @bDeviceSubClass: Subclass of device; associated with bDeviceClass. * @bDeviceProtocol: Protocol of device; associated with bDeviceClass. * @bInterfaceClass: Class of interface; numbers are assigned * by the USB forum. Products may choose to implement classes, * or be vendor-specific. Interface classes specify behavior only * of a given interface; other interfaces may support other classes. * @bInterfaceSubClass: Subclass of interface; associated with bInterfaceClass. * @bInterfaceProtocol: Protocol of interface; associated with bInterfaceClass. * @bInterfaceNumber: Number of interface; composite devices may use * fixed interface numbers to differentiate between vendor-specific * interfaces. * @driver_info: Holds information used by the driver. Usually it holds * a pointer to a descriptor understood by the driver, or perhaps * device flags. * * In most cases, drivers will create a table of device IDs by using * USB_DEVICE(), or similar macros designed for that purpose. * They will then export it to userspace using MODULE_DEVICE_TABLE(), * and provide it to the USB core through their usb_driver structure. * * See the usb_match_id() function for information about how matches are * performed. Briefly, you will normally use one of several macros to help * construct these entries. Each entry you provide will either identify * one or more specific products, or will identify a class of products * which have agreed to behave the same. You should put the more specific * matches towards the beginning of your table, so that driver_info can * record quirks of specific products. */ struct usb_device_id { /* which fields to match against? */ __u16 match_flags; /* Used for product specific matches; range is inclusive */ __u16 idVendor; __u16 idProduct; __u16 bcdDevice_lo; __u16 bcdDevice_hi; /* Used for device class matches */ __u8 bDeviceClass; __u8 bDeviceSubClass; __u8 bDeviceProtocol; /* Used for interface class matches */ __u8 bInterfaceClass; __u8 bInterfaceSubClass; __u8 bInterfaceProtocol; /* Used for vendor-specific interface matches */ __u8 bInterfaceNumber; /* not matched against */ kernel_ulong_t driver_info __attribute__((aligned(sizeof(kernel_ulong_t)))); }; /* Some useful macros to use to create struct usb_device_id */ #define USB_DEVICE_ID_MATCH_VENDOR 0x0001 #define USB_DEVICE_ID_MATCH_PRODUCT 0x0002 #define USB_DEVICE_ID_MATCH_DEV_LO 0x0004 #define USB_DEVICE_ID_MATCH_DEV_HI 0x0008 #define USB_DEVICE_ID_MATCH_DEV_CLASS 0x0010 #define USB_DEVICE_ID_MATCH_DEV_SUBCLASS 0x0020 #define USB_DEVICE_ID_MATCH_DEV_PROTOCOL 0x0040 #define USB_DEVICE_ID_MATCH_INT_CLASS 0x0080 #define USB_DEVICE_ID_MATCH_INT_SUBCLASS 0x0100 #define USB_DEVICE_ID_MATCH_INT_PROTOCOL 0x0200 #define USB_DEVICE_ID_MATCH_INT_NUMBER 0x0400 #define HID_ANY_ID (~0) #define HID_BUS_ANY 0xffff #define HID_GROUP_ANY 0x0000 struct hid_device_id { __u16 bus; __u16 group; __u32 vendor; __u32 product; kernel_ulong_t driver_data __attribute__((aligned(sizeof(kernel_ulong_t)))); }; /* s390 CCW devices */ struct ccw_device_id { __u16 match_flags; /* which fields to match against */ __u16 cu_type; /* control unit type */ __u16 dev_type; /* device type */ __u8 cu_model; /* control unit model */ __u8 dev_model; /* device model */ kernel_ulong_t driver_info; }; #define CCW_DEVICE_ID_MATCH_CU_TYPE 0x01 #define CCW_DEVICE_ID_MATCH_CU_MODEL 0x02 #define CCW_DEVICE_ID_MATCH_DEVICE_TYPE 0x04 #define CCW_DEVICE_ID_MATCH_DEVICE_MODEL 0x08 /* s390 AP bus devices */ struct ap_device_id { __u16 match_flags; /* which fields to match against */ __u8 dev_type; /* device type */ __u8 pad1; __u32 pad2; kernel_ulong_t driver_info; }; #define AP_DEVICE_ID_MATCH_DEVICE_TYPE 0x01 /* s390 css bus devices (subchannels) */ struct css_device_id { __u8 match_flags; __u8 type; /* subchannel type */ __u16 pad2; __u32 pad3; kernel_ulong_t driver_data; }; #define ACPI_ID_LEN 16 /* only 9 bytes needed here, 16 bytes are used */ /* to workaround crosscompile issues */ struct acpi_device_id { __u8 id[ACPI_ID_LEN]; kernel_ulong_t driver_data; }; #define PNP_ID_LEN 8 #define PNP_MAX_DEVICES 8 struct pnp_device_id { __u8 id[PNP_ID_LEN]; kernel_ulong_t driver_data; }; struct pnp_card_device_id { __u8 id[PNP_ID_LEN]; kernel_ulong_t driver_data; struct { __u8 id[PNP_ID_LEN]; } devs[PNP_MAX_DEVICES]; }; #define SERIO_ANY 0xff struct serio_device_id { __u8 type; __u8 extra; __u8 id; __u8 proto; }; /* * Struct used for matching a device */ struct of_device_id { char name[32]; char type[32]; char compatible[128]; #ifdef __KERNEL__ const void *data; #else kernel_ulong_t data; #endif }; /* VIO */ struct vio_device_id { char type[32]; char compat[32]; }; /* PCMCIA */ struct pcmcia_device_id { __u16 match_flags; __u16 manf_id; __u16 card_id; __u8 func_id; /* for real multi-function devices */ __u8 function; /* for pseudo multi-function devices */ __u8 device_no; __u32 prod_id_hash[4] __attribute__((aligned(sizeof(__u32)))); /* not matched against in kernelspace*/ #ifdef __KERNEL__ const char * prod_id[4]; #else kernel_ulong_t prod_id[4] __attribute__((aligned(sizeof(kernel_ulong_t)))); #endif /* not matched against */ kernel_ulong_t driver_info; #ifdef __KERNEL__ char * cisfile; #else kernel_ulong_t cisfile; #endif }; #define PCMCIA_DEV_ID_MATCH_MANF_ID 0x0001 #define PCMCIA_DEV_ID_MATCH_CARD_ID 0x0002 #define PCMCIA_DEV_ID_MATCH_FUNC_ID 0x0004 #define PCMCIA_DEV_ID_MATCH_FUNCTION 0x0008 #define PCMCIA_DEV_ID_MATCH_PROD_ID1 0x0010 #define PCMCIA_DEV_ID_MATCH_PROD_ID2 0x0020 #define PCMCIA_DEV_ID_MATCH_PROD_ID3 0x0040 #define PCMCIA_DEV_ID_MATCH_PROD_ID4 0x0080 #define PCMCIA_DEV_ID_MATCH_DEVICE_NO 0x0100 #define PCMCIA_DEV_ID_MATCH_FAKE_CIS 0x0200 #define PCMCIA_DEV_ID_MATCH_ANONYMOUS 0x0400 /* Input */ #define INPUT_DEVICE_ID_EV_MAX 0x1f #define INPUT_DEVICE_ID_KEY_MIN_INTERESTING 0x71 #define INPUT_DEVICE_ID_KEY_MAX 0x2ff #define INPUT_DEVICE_ID_REL_MAX 0x0f #define INPUT_DEVICE_ID_ABS_MAX 0x3f #define INPUT_DEVICE_ID_MSC_MAX 0x07 #define INPUT_DEVICE_ID_LED_MAX 0x0f #define INPUT_DEVICE_ID_SND_MAX 0x07 #define INPUT_DEVICE_ID_FF_MAX 0x7f #define INPUT_DEVICE_ID_SW_MAX 0x0f #define INPUT_DEVICE_ID_MATCH_BUS 1 #define INPUT_DEVICE_ID_MATCH_VENDOR 2 #define INPUT_DEVICE_ID_MATCH_PRODUCT 4 #define INPUT_DEVICE_ID_MATCH_VERSION 8 #define INPUT_DEVICE_ID_MATCH_EVBIT 0x0010 #define INPUT_DEVICE_ID_MATCH_KEYBIT 0x0020 #define INPUT_DEVICE_ID_MATCH_RELBIT 0x0040 #define INPUT_DEVICE_ID_MATCH_ABSBIT 0x0080 #define INPUT_DEVICE_ID_MATCH_MSCIT 0x0100 #define INPUT_DEVICE_ID_MATCH_LEDBIT 0x0200 #define INPUT_DEVICE_ID_MATCH_SNDBIT 0x0400 #define INPUT_DEVICE_ID_MATCH_FFBIT 0x0800 #define INPUT_DEVICE_ID_MATCH_SWBIT 0x1000 struct input_device_id { kernel_ulong_t flags; __u16 bustype; __u16 vendor; __u16 product; __u16 version; kernel_ulong_t evbit[INPUT_DEVICE_ID_EV_MAX / BITS_PER_LONG + 1]; kernel_ulong_t keybit[INPUT_DEVICE_ID_KEY_MAX / BITS_PER_LONG + 1]; kernel_ulong_t relbit[INPUT_DEVICE_ID_REL_MAX / BITS_PER_LONG + 1]; kernel_ulong_t absbit[INPUT_DEVICE_ID_ABS_MAX / BITS_PER_LONG + 1]; kernel_ulong_t mscbit[INPUT_DEVICE_ID_MSC_MAX / BITS_PER_LONG + 1]; kernel_ulong_t ledbit[INPUT_DEVICE_ID_LED_MAX / BITS_PER_LONG + 1]; kernel_ulong_t sndbit[INPUT_DEVICE_ID_SND_MAX / BITS_PER_LONG + 1]; kernel_ulong_t ffbit[INPUT_DEVICE_ID_FF_MAX / BITS_PER_LONG + 1]; kernel_ulong_t swbit[INPUT_DEVICE_ID_SW_MAX / BITS_PER_LONG + 1]; kernel_ulong_t driver_info; }; /* EISA */ #define EISA_SIG_LEN 8 /* The EISA signature, in ASCII form, null terminated */ struct eisa_device_id { char sig[EISA_SIG_LEN]; kernel_ulong_t driver_data; }; #define EISA_DEVICE_MODALIAS_FMT "eisa:s%s" struct parisc_device_id { __u8 hw_type; /* 5 bits used */ __u8 hversion_rev; /* 4 bits */ __u16 hversion; /* 12 bits */ __u32 sversion; /* 20 bits */ }; #define PA_HWTYPE_ANY_ID 0xff #define PA_HVERSION_REV_ANY_ID 0xff #define PA_HVERSION_ANY_ID 0xffff #define PA_SVERSION_ANY_ID 0xffffffff /* SDIO */ #define SDIO_ANY_ID (~0) struct sdio_device_id { __u8 class; /* Standard interface or SDIO_ANY_ID */ __u16 vendor; /* Vendor or SDIO_ANY_ID */ __u16 device; /* Device ID or SDIO_ANY_ID */ kernel_ulong_t driver_data /* Data private to the driver */ __attribute__((aligned(sizeof(kernel_ulong_t)))); }; /* SSB core, see drivers/ssb/ */ struct ssb_device_id { __u16 vendor; __u16 coreid; __u8 revision; }; #define SSB_DEVICE(_vendor, _coreid, _revision) \ { .vendor = _vendor, .coreid = _coreid, .revision = _revision, } #define SSB_DEVTABLE_END \ { 0, }, #define SSB_ANY_VENDOR 0xFFFF #define SSB_ANY_ID 0xFFFF #define SSB_ANY_REV 0xFF /* Broadcom's specific AMBA core, see drivers/bcma/ */ struct bcma_device_id { __u16 manuf; __u16 id; __u8 rev; __u8 class; }; #define BCMA_CORE(_manuf, _id, _rev, _class) \ { .manuf = _manuf, .id = _id, .rev = _rev, .class = _class, } #define BCMA_CORETABLE_END \ { 0, }, #define BCMA_ANY_MANUF 0xFFFF #define BCMA_ANY_ID 0xFFFF #define BCMA_ANY_REV 0xFF #define BCMA_ANY_CLASS 0xFF struct virtio_device_id { __u32 device; __u32 vendor; }; #define VIRTIO_DEV_ANY_ID 0xffffffff /* * For Hyper-V devices we use the device guid as the id. */ struct hv_vmbus_device_id { __u8 guid[16]; kernel_ulong_t driver_data /* Data private to the driver */ __attribute__((aligned(sizeof(kernel_ulong_t)))); }; /* rpmsg */ #define RPMSG_NAME_SIZE 32 #define RPMSG_DEVICE_MODALIAS_FMT "rpmsg:%s" struct rpmsg_device_id { char name[RPMSG_NAME_SIZE]; }; /* i2c */ #define I2C_NAME_SIZE 20 #define I2C_MODULE_PREFIX "i2c:" struct i2c_device_id { char name[I2C_NAME_SIZE]; kernel_ulong_t driver_data /* Data private to the driver */ __attribute__((aligned(sizeof(kernel_ulong_t)))); }; /* spi */ #define SPI_NAME_SIZE 32 #define SPI_MODULE_PREFIX "spi:" struct spi_device_id { char name[SPI_NAME_SIZE]; kernel_ulong_t driver_data /* Data private to the driver */ __attribute__((aligned(sizeof(kernel_ulong_t)))); }; /* dmi */ enum dmi_field { DMI_NONE, DMI_BIOS_VENDOR, DMI_BIOS_VERSION, DMI_BIOS_DATE, DMI_SYS_VENDOR, DMI_PRODUCT_NAME, DMI_PRODUCT_VERSION, DMI_PRODUCT_SERIAL, DMI_PRODUCT_UUID, DMI_BOARD_VENDOR, DMI_BOARD_NAME, DMI_BOARD_VERSION, DMI_BOARD_SERIAL, DMI_BOARD_ASSET_TAG, DMI_CHASSIS_VENDOR, DMI_CHASSIS_TYPE, DMI_CHASSIS_VERSION, DMI_CHASSIS_SERIAL, DMI_CHASSIS_ASSET_TAG, DMI_STRING_MAX, }; struct dmi_strmatch { unsigned char slot; char substr[79]; }; #ifndef __KERNEL__ struct dmi_system_id { kernel_ulong_t callback; kernel_ulong_t ident; struct dmi_strmatch matches[4]; kernel_ulong_t driver_data __attribute__((aligned(sizeof(kernel_ulong_t)))); }; #else struct dmi_system_id { int (*callback)(const struct dmi_system_id *); const char *ident; struct dmi_strmatch matches[4]; void *driver_data; }; /* * struct dmi_device_id appears during expansion of * "MODULE_DEVICE_TABLE(dmi, x)". Compiler doesn't look inside it * but this is enough for gcc 3.4.6 to error out: * error: storage size of '__mod_dmi_device_table' isn't known */ #define dmi_device_id dmi_system_id #endif #define DMI_MATCH(a, b) { a, b } #define PLATFORM_NAME_SIZE 20 #define PLATFORM_MODULE_PREFIX "platform:" struct platform_device_id { char name[PLATFORM_NAME_SIZE]; kernel_ulong_t driver_data __attribute__((aligned(sizeof(kernel_ulong_t)))); }; #define MDIO_MODULE_PREFIX "mdio:" #define MDIO_ID_FMT "%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d" #define MDIO_ID_ARGS(_id) \ (_id)>>31, ((_id)>>30) & 1, ((_id)>>29) & 1, ((_id)>>28) & 1, \ ((_id)>>27) & 1, ((_id)>>26) & 1, ((_id)>>25) & 1, ((_id)>>24) & 1, \ ((_id)>>23) & 1, ((_id)>>22) & 1, ((_id)>>21) & 1, ((_id)>>20) & 1, \ ((_id)>>19) & 1, ((_id)>>18) & 1, ((_id)>>17) & 1, ((_id)>>16) & 1, \ ((_id)>>15) & 1, ((_id)>>14) & 1, ((_id)>>13) & 1, ((_id)>>12) & 1, \ ((_id)>>11) & 1, ((_id)>>10) & 1, ((_id)>>9) & 1, ((_id)>>8) & 1, \ ((_id)>>7) & 1, ((_id)>>6) & 1, ((_id)>>5) & 1, ((_id)>>4) & 1, \ ((_id)>>3) & 1, ((_id)>>2) & 1, ((_id)>>1) & 1, (_id) & 1 /** * struct mdio_device_id - identifies PHY devices on an MDIO/MII bus * @phy_id: The result of * (mdio_read(&MII_PHYSID1) << 16 | mdio_read(&PHYSID2)) & @phy_id_mask * for this PHY type * @phy_id_mask: Defines the significant bits of @phy_id. A value of 0 * is used to terminate an array of struct mdio_device_id. */ struct mdio_device_id { __u32 phy_id; __u32 phy_id_mask; }; struct zorro_device_id { __u32 id; /* Device ID or ZORRO_WILDCARD */ kernel_ulong_t driver_data; /* Data private to the driver */ }; #define ZORRO_WILDCARD (0xffffffff) /* not official */ #define ZORRO_DEVICE_MODALIAS_FMT "zorro:i%08X" #define ISAPNP_ANY_ID 0xffff struct isapnp_device_id { unsigned short card_vendor, card_device; unsigned short vendor, function; kernel_ulong_t driver_data; /* data private to the driver */ }; /** * struct amba_id - identifies a device on an AMBA bus * @id: The significant bits if the hardware device ID * @mask: Bitmask specifying which bits of the id field are significant when * matching. A driver binds to a device when ((hardware device ID) & mask) * == id. * @data: Private data used by the driver. */ struct amba_id { unsigned int id; unsigned int mask; #ifndef __KERNEL__ kernel_ulong_t data; #else void *data; #endif }; /* * Match x86 CPUs for CPU specific drivers. * See documentation of "x86_match_cpu" for details. */ struct x86_cpu_id { __u16 vendor; __u16 family; __u16 model; __u16 feature; /* bit index */ kernel_ulong_t driver_data; }; #define X86_FEATURE_MATCH(x) \ { X86_VENDOR_ANY, X86_FAMILY_ANY, X86_MODEL_ANY, x } #define X86_VENDOR_ANY 0xffff #define X86_FAMILY_ANY 0 #define X86_MODEL_ANY 0 #define X86_FEATURE_ANY 0 /* Same as FPU, you can't test for that */ #define IPACK_ANY_FORMAT 0xff #define IPACK_ANY_ID (~0) struct ipack_device_id { __u8 format; /* Format version or IPACK_ANY_ID */ __u32 vendor; /* Vendor ID or IPACK_ANY_ID */ __u32 device; /* Device ID or IPACK_ANY_ID */ }; #endif /* LINUX_MOD_DEVICETABLE_H */
SanDisk-Open-Source/SSD_Dashboard
uefi/linux-source-3.8.0/include/linux/mod_devicetable.h
C
gpl-2.0
16,853
/* * Copyright (C) 2008 The Android Open Source Project * * 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.android.dx.rop.cst; import com.android.dx.rop.type.Type; /** * Utility for turning types into zeroes. */ public final class Zeroes { /** * This class is uninstantiable. */ private Zeroes() { // This space intentionally left blank. } /** * Gets the "zero" (or {@code null}) value for the given type. * * @param type {@code non-null;} the type in question * @return {@code non-null;} its "zero" value */ public static Constant zeroFor(Type type) { switch (type.getBasicType()) { case Type.BT_BOOLEAN: return CstBoolean.VALUE_FALSE; case Type.BT_BYTE: return CstByte.VALUE_0; case Type.BT_CHAR: return CstChar.VALUE_0; case Type.BT_DOUBLE: return CstDouble.VALUE_0; case Type.BT_FLOAT: return CstFloat.VALUE_0; case Type.BT_INT: return CstInteger.VALUE_0; case Type.BT_LONG: return CstLong.VALUE_0; case Type.BT_SHORT: return CstShort.VALUE_0; case Type.BT_OBJECT: return CstKnownNull.THE_ONE; default: { throw new UnsupportedOperationException("no zero for type: " + type.toHuman()); } } } }
raviagarwal7/buck
third-party/java/dx/src/com/android/dx/rop/cst/Zeroes.java
Java
apache-2.0
1,902